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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0afdb443d40a45d1ba2d5caa07fd14cfdd18996a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/algebra/nonarchimedean/basic.lean | 8f6d94f28a25a1690ecaaccdfaf28c54b89de396 | [
"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 | 6,396 | lean | /-
Copyright (c) 2021 Ashwin Iyengar. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Johan Commelin, Ashwin Iyengar, Patrick Massot
-/
import group_theory.subgroup.basic
import topology.algebra.open_subgroup
import topology.algebra.ring.basic
/-!
# Nonarchimedean Topology
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we set up the theory of nonarchimedean topological groups and rings.
A nonarchimedean group is a topological group whose topology admits a basis of
open neighborhoods of the identity element in the group consisting of open subgroups.
A nonarchimedean ring is a topological ring whose underlying topological (additive)
group is nonarchimedean.
## Definitions
- `nonarchimedean_add_group`: nonarchimedean additive group.
- `nonarchimedean_group`: nonarchimedean multiplicative group.
- `nonarchimedean_ring`: nonarchimedean ring.
-/
open_locale pointwise
/-- An topological additive group is nonarchimedean if every neighborhood of 0
contains an open subgroup. -/
class nonarchimedean_add_group (G : Type*)
[add_group G] [topological_space G] extends topological_add_group G : Prop :=
(is_nonarchimedean : ∀ U ∈ nhds (0 : G), ∃ V : open_add_subgroup G, (V : set G) ⊆ U)
/-- A topological group is nonarchimedean if every neighborhood of 1 contains an open subgroup. -/
@[to_additive]
class nonarchimedean_group (G : Type*)
[group G] [topological_space G] extends topological_group G : Prop :=
(is_nonarchimedean : ∀ U ∈ nhds (1 : G), ∃ V : open_subgroup G, (V : set G) ⊆ U)
/-- An topological ring is nonarchimedean if its underlying topological additive
group is nonarchimedean. -/
class nonarchimedean_ring (R : Type*)
[ring R] [topological_space R] extends topological_ring R : Prop :=
(is_nonarchimedean : ∀ U ∈ nhds (0 : R), ∃ V : open_add_subgroup R, (V : set R) ⊆ U)
/-- Every nonarchimedean ring is naturally a nonarchimedean additive group. -/
@[priority 100] -- see Note [lower instance priority]
instance nonarchimedean_ring.to_nonarchimedean_add_group
(R : Type*) [ring R] [topological_space R] [t: nonarchimedean_ring R] :
nonarchimedean_add_group R := {..t}
namespace nonarchimedean_group
variables {G : Type*} [group G] [topological_space G] [nonarchimedean_group G]
variables {H : Type*} [group H] [topological_space H] [topological_group H]
variables {K : Type*} [group K] [topological_space K] [nonarchimedean_group K]
/-- If a topological group embeds into a nonarchimedean group, then it is nonarchimedean. -/
@[to_additive nonarchimedean_add_group.nonarchimedean_of_emb "If a topological group embeds into a
nonarchimedean group, then it is nonarchimedean."]
lemma nonarchimedean_of_emb (f : G →* H) (emb : open_embedding f) : nonarchimedean_group H :=
{ is_nonarchimedean := λ U hU, have h₁ : (f ⁻¹' U) ∈ nhds (1 : G), from
by {apply emb.continuous.tendsto, rwa f.map_one},
let ⟨V, hV⟩ := is_nonarchimedean (f ⁻¹' U) h₁ in
⟨{is_open' := emb.is_open_map _ V.is_open, ..subgroup.map f V},
set.image_subset_iff.2 hV⟩ }
/-- An open neighborhood of the identity in the cartesian product of two nonarchimedean groups
contains the cartesian product of an open neighborhood in each group. -/
@[to_additive nonarchimedean_add_group.prod_subset "An open neighborhood of the identity in the
cartesian product of two nonarchimedean groups contains the cartesian product of an open
neighborhood in each group."]
lemma prod_subset {U} (hU : U ∈ nhds (1 : G × K)) :
∃ (V : open_subgroup G) (W : open_subgroup K), (V : set G) ×ˢ (W : set K) ⊆ U :=
begin
erw [nhds_prod_eq, filter.mem_prod_iff] at hU,
rcases hU with ⟨U₁, hU₁, U₂, hU₂, h⟩,
cases is_nonarchimedean _ hU₁ with V hV,
cases is_nonarchimedean _ hU₂ with W hW,
use V, use W,
rw set.prod_subset_iff,
intros x hX y hY,
exact set.subset.trans (set.prod_mono hV hW) h (set.mem_sep hX hY),
end
/-- An open neighborhood of the identity in the cartesian square of a nonarchimedean group
contains the cartesian square of an open neighborhood in the group. -/
@[to_additive nonarchimedean_add_group.prod_self_subset "An open neighborhood of the identity in the
cartesian square of a nonarchimedean group contains the cartesian square of an open neighborhood in
the group."]
lemma prod_self_subset {U} (hU : U ∈ nhds (1 : G × G)) :
∃ (V : open_subgroup G), (V : set G) ×ˢ (V : set G) ⊆ U :=
let ⟨V, W, h⟩ := prod_subset hU in
⟨V ⊓ W, by {refine set.subset.trans (set.prod_mono _ _) ‹_›; simp}⟩
/-- The cartesian product of two nonarchimedean groups is nonarchimedean. -/
@[to_additive "The cartesian product of two nonarchimedean groups is nonarchimedean."]
instance : nonarchimedean_group (G × K) :=
{ is_nonarchimedean := λ U hU, let ⟨V, W, h⟩ := prod_subset hU in ⟨V.prod W, ‹_›⟩ }
end nonarchimedean_group
namespace nonarchimedean_ring
open nonarchimedean_ring
open nonarchimedean_add_group
variables {R S : Type*}
variables [ring R] [topological_space R] [nonarchimedean_ring R]
variables [ring S] [topological_space S] [nonarchimedean_ring S]
/-- The cartesian product of two nonarchimedean rings is nonarchimedean. -/
instance : nonarchimedean_ring (R × S) :=
{ is_nonarchimedean := nonarchimedean_add_group.is_nonarchimedean }
/-- Given an open subgroup `U` and an element `r` of a nonarchimedean ring, there is an open
subgroup `V` such that `r • V` is contained in `U`. -/
lemma left_mul_subset (U : open_add_subgroup R) (r : R) :
∃ V : open_add_subgroup R, r • (V : set R) ⊆ U :=
⟨U.comap (add_monoid_hom.mul_left r) (continuous_mul_left r),
(U : set R).image_preimage_subset _⟩
/-- An open subgroup of a nonarchimedean ring contains the square of another one. -/
lemma mul_subset (U : open_add_subgroup R) :
∃ V : open_add_subgroup R, (V : set R) * V ⊆ U :=
let ⟨V, H⟩ := prod_self_subset (is_open.mem_nhds (is_open.preimage continuous_mul U.is_open)
begin
simpa only [set.mem_preimage, set_like.mem_coe, prod.snd_zero, mul_zero] using U.zero_mem,
end) in
begin
use V,
rintros v ⟨a, b, ha, hb, hv⟩,
have hy := H (set.mk_mem_prod ha hb),
simp only [set.mem_preimage, set_like.mem_coe] at hy,
rwa hv at hy
end
end nonarchimedean_ring
|
f4f361e52e5999413f9d94e95d673a70a5a31e31 | 99b5e6372af1f404777312358869f95be7de84a3 | /src/hott/types/nat/hott.lean | 5efa9e7919581b44d3f62503b7e9425762f86b2c | [
"Apache-2.0"
] | permissive | forked-from-1kasper/hott3 | 8fa064ab5e8c9d6752a783d74ab226ddc5b5232a | 2db24de7a361a7793b0eae4ca5c3fd4d4a0fc691 | refs/heads/master | 1,584,867,131,028 | 1,530,766,841,000 | 1,530,766,841,000 | 139,797,034 | 0 | 0 | Apache-2.0 | 1,530,766,961,000 | 1,530,766,961,000 | null | UTF-8 | Lean | false | false | 9,451 | lean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Theorems about the natural numbers specific to HoTT
-/
import .order ..pointed .sub
universes u v w
hott_theory
namespace hott
open nat is_trunc hott.algebra hott.is_equiv hott.equiv
namespace nat
@[hott, instance] def is_prop_le (n m : ℕ) : is_prop (n ≤ m) :=
begin
have lem : Π{n m : ℕ} (p : n ≤ m) (q : n = m), p = nat.le_of_eq q,
begin
intros, cases p with m p IH,
{ have H' : q = idp, by apply is_set.elim,
cases H', reflexivity },
{ cases q, apply empty.elim, apply not_succ_le_self p }
end,
apply is_prop.mk, intros H1 H2, induction H2 with m H2 IH,
{ exact lem H1 idp },
{ cases H1,
{ apply empty.elim, apply not_succ_le_self H2},
{ exact ap le.step (IH _)}},
end
@[hott, instance] def is_prop_lt (n m : ℕ) : is_prop (n < m) := is_prop_le _ _
@[hott] def le_equiv_succ_le_succ (n m : ℕ) : (n ≤ m) ≃ (succ n ≤ succ m) :=
equiv_of_is_prop succ_le_succ le_of_succ_le_succ
@[hott] theorem le_succ_equiv_pred_le (n m : ℕ) : (n ≤ succ m) ≃ (pred n ≤ m) :=
equiv_of_is_prop pred_le_pred le_succ_of_pred_le
@[hott] theorem lt_by_cases_lt {a b : ℕ} {P : Type _} (H1 : a < b → P) (H2 : a = b → P)
(H3 : a > b → P) (H : a < b) : lt.by_cases H1 H2 H3 = H1 H :=
begin
dsimp [lt.by_cases], hinduction (lt.trichotomy a b) with p H' H',
{ exact ap H1 (is_prop.elim _ _)},
{ apply empty.elim, cases H' with H' H', apply lt.irrefl b, exact H' ▸ H,
exact lt.asymm H H'}
end
@[hott] theorem lt_by_cases_eq {a b : ℕ} {P : Type _} (H1 : a < b → P) (H2 : a = b → P)
(H3 : a > b → P) (H : a = b) : lt.by_cases H1 H2 H3 = H2 H :=
begin
dsimp [lt.by_cases], induction (lt.trichotomy a b) with H' H',
{ apply empty.elim, apply lt.irrefl b, exact H ▸ H'},
{ cases H' with H' H', exact ap H2 (is_prop.elim _ _), apply empty.elim , apply lt.irrefl b,
exact H ▸ H'}
end
@[hott] theorem lt_by_cases_ge {a b : ℕ} {P : Type _} (H1 : a < b → P) (H2 : a = b → P)
(H3 : a > b → P) (H : a > b) : lt.by_cases H1 H2 H3 = H3 H :=
begin
dsimp [lt.by_cases], induction (lt.trichotomy a b) with H' H',
{ apply empty.elim, exact lt.asymm H H'},
{ cases H' with H' H', apply empty.elim, apply lt.irrefl b, exact H' ▸ H,
exact ap H3 (is_prop.elim _ _)}
end
@[hott] theorem lt_ge_by_cases_lt {n m : ℕ} {P : Type _} (H1 : n < m → P) (H2 : n ≥ m → P)
(H : n < m) : lt_ge_by_cases H1 H2 = H1 H :=
by apply lt_by_cases_lt
@[hott] theorem lt_ge_by_cases_ge {n m : ℕ} {P : Type _} (H1 : n < m → P) (H2 : n ≥ m → P)
(H : n ≥ m) : lt_ge_by_cases H1 H2 = H2 H :=
begin
dsimp [lt_ge_by_cases,lt.by_cases], induction (lt.trichotomy n m) with H' H',
{ apply empty.elim, apply lt.irrefl m, exact lt_of_le_of_lt H H'},
{ cases H' with H' H'; apply ap H2 (is_prop.elim _ _)}
end
@[hott] theorem lt_ge_by_cases_le {n m : ℕ} {P : Type _} {H1 : n ≤ m → P} {H2 : n ≥ m → P}
(H : n ≤ m) (Heq : Π(p : n = m), H1 (le_of_eq p) = H2 (le_of_eq p⁻¹))
: lt_ge_by_cases (λH', H1 (le_of_lt H')) H2 = H1 H :=
begin
dsimp [lt_ge_by_cases,lt.by_cases], induction (lt.trichotomy n m) with H' H',
{ apply ap H1 (is_prop.elim _ _)},
{ cases H' with H' H',
{ induction H', symmetry,
exact ap H1 (is_prop.elim _ _) ⬝ Heq idp ⬝ ap H2 (is_prop.elim _ _)},
{ apply empty.elim, apply lt.irrefl n, apply lt_of_le_of_lt H H'}}
end
@[hott] def nat_eq_equiv (n m : ℕ) : (n = m) ≃ nat.code n m :=
equiv.MK nat.encode
(nat.decode n m)
begin
revert m, induction n; intro m; induction m; intro c,
induction c, reflexivity,
exact empty.elim c,
exact empty.elim c,
dsimp [nat.decode, nat.encode], rwr [←tr_compose], apply n_ih
end
begin
intro p, induction p, induction n,
reflexivity,
exact ap02 succ n_ih
end
@[hott, instance] def pointed_nat : pointed ℕ :=
pointed.mk 0
open sigma sum
@[hott] def eq_even_or_eq_odd (n : ℕ) : (Σk, 2 * k = n) ⊎ (Σk, 2 * k + 1 = n) :=
begin
induction n with n IH,
{ exact inl ⟨0, idp⟩},
{ induction IH with H H; induction H with k p; induction p,
{ exact inr ⟨k, idp⟩},
{ refine inl ⟨k+1, idp⟩}}
end
@[hott] def rec_on_even_odd {P : ℕ → Type _} (n : ℕ) (H : Πk, P (2 * k)) (H2 : Πk, P (2 * k + 1))
: P n :=
begin
cases eq_even_or_eq_odd n with v v; induction v with k p; induction p,
{ exact H k},
{ exact H2 k}
end
/- this inequality comes up a couple of times when using the freudenthal suspension @[hott] theorem -/
@[hott] theorem add_mul_le_mul_add (n m k : ℕ) : n + (succ m) * k ≤ (succ m) * (n + k) :=
calc
n + (succ m) * k ≤ (m * n + n) + (succ m) * k : add_le_add_right (le_add_left _ _) _
... = (succ m) * n + (succ m) * k : by rwr ←succ_mul
... = (succ m) * (n + k) : by rwr ←hott.algebra.left_distrib
/-
Some operations work only for successors. For example fin (succ n) has a 0 and a 1, but fin 0
doesn't. However, we want a bit more, because sometimes we want a zero of (fin a)
where a is either
- equal to a successor, but not definitionally a successor (e.g. (0 : fin (3 + n)))
- definitionally equal to a successor, but not in a way that type class inference can infer.
(e.g. (0 : fin 4). Note that 4 is bit0 (bit0 one), but (bit0 x) (defined as x + x),
is not always a successor)
To solve this we use an auxillary class `is_succ` which can solve whether a number is a
successor.
-/
@[hott, class] inductive is_succ : ℕ → Type
| mk : Π(n : ℕ), is_succ (succ n)
attribute [instance] is_succ.mk
@[hott, instance] def is_succ_1 : is_succ 1 := is_succ.mk 0
@[hott, instance] def is_succ_add_right (n m : ℕ) [H : is_succ m] : is_succ (n+m) :=
by unfreezeI; induction H with m; constructor
@[hott, instance, priority 900] def is_succ_add_left (n m : ℕ) [H : is_succ n] :
is_succ (n+m) :=
by unfreezeI; induction H with n; cases m with m; constructor
@[hott] def is_succ_bit0 (n : ℕ) [H : is_succ n] : is_succ (bit0 n) :=
by dsimp [bit0]; apply_instance
-- level 2 is useful for abelian homotopy groups, which only exist at level 2 and higher
@[hott, class] inductive is_at_least_two : ℕ → Type
| mk : Π(n : ℕ), is_at_least_two (succ (succ n))
attribute [instance] is_at_least_two.mk
@[hott, instance] def is_at_least_two_succ (n : ℕ) [H : is_succ n] :
is_at_least_two (succ n) :=
by unfreezeI; induction H with n; constructor
@[hott, instance] def is_at_least_two_add_right (n m : ℕ) [H : is_at_least_two m] :
is_at_least_two (n+m) :=
by unfreezeI; induction H with m; constructor
@[hott, instance] def is_at_least_two_add_left (n m : ℕ) [H : is_at_least_two n] :
is_at_least_two (n+m) :=
by unfreezeI; induction H with n; cases m with m; try { cases m with m }; constructor
@[hott, instance, priority 900] def is_at_least_two_add_both (n m : ℕ)
[H : is_succ n] [K : is_succ m] : is_at_least_two (n+m) :=
by unfreezeI; induction H with n; induction K with m; cases m with m; constructor
@[hott] def is_at_least_two_bit0 (n : ℕ) [H : is_succ n] : is_at_least_two (bit0 n) :=
by dsimp [bit0]; apply_instance
@[hott] def is_at_least_two_bit1 (n : ℕ) [H : is_succ n] : is_at_least_two (bit1 n) :=
by dsimp [bit1, bit0]; apply_instance
/- some facts about iterate -/
@[hott] def iterate_succ {A : Type _} (f : A → A) (n : ℕ) (x : A) :
f^[succ n] x = f^[n] (f x) :=
begin induction n with n p, refl, exact ap f p end
@[hott] lemma iterate_sub {A : Type _} (f : A ≃ A) {n m : ℕ} (h : n ≥ m) (a : A) :
iterate f (n - m) a = iterate f n (iterate f⁻¹ᶠ m a) :=
begin
induction m with m p generalizing n h,
{ refl },
{ cases n with n, apply empty.elim, apply not_succ_le_zero _ h,
rwr [succ_sub_succ], refine p (le_of_succ_le_succ h) ⬝ _,
refine ap (f^[n]) _ ⬝ (iterate_succ _ _ _)⁻¹, exact (to_right_inv _ _)⁻¹ }
end
@[hott] def iterate_commute {A : Type _} {f g : A → A} (n : ℕ) (h : f ∘ g ~ g ∘ f) :
iterate f n ∘ g ~ g ∘ iterate f n :=
begin induction n with n IH, refl, exact λx, ap f (IH x) ⬝ h _ end
@[hott] def iterate_equiv {A : Type _} (f : A ≃ A) (n : ℕ) : A ≃ A :=
equiv.mk (iterate f n)
begin induction n with n IH, apply is_equiv_id, exactI is_equiv_compose f (iterate f n) end
@[hott] def iterate_inv {A : Type _} (f : A ≃ A) (n : ℕ) :
(iterate_equiv f n)⁻¹ᶠ ~ iterate f⁻¹ᶠ n :=
begin
induction n with n p; intro a,
refl,
exact p (f⁻¹ᶠ a) ⬝ (iterate_succ _ _ _)⁻¹
end
@[hott] def iterate_left_inv {A : Type _} (f : A ≃ A) (n : ℕ) (a : A) : f⁻¹ᵉ^[n] (f^[n] a) = a :=
(iterate_inv f n (f^[n] a))⁻¹ ⬝ to_left_inv (iterate_equiv f n) a
@[hott] def iterate_right_inv {A : Type _} (f : A ≃ A) (n : ℕ) (a : A) : f^[n] (f⁻¹ᵉ^[n] a) = a :=
ap (f^[n]) (iterate_inv f n a)⁻¹ ⬝ to_right_inv (iterate_equiv f n) a
end nat
end hott
|
0fb2e1bf95bbf496b8e835f23e820f1c481c8ae1 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/fintype/basic.lean | f323070c5ba65f41f4d41952c075aa9732ddbb55 | [
"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 | 90,706 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.array.lemmas
import data.finset.fin
import data.finset.option
import data.finset.pi
import data.finset.powerset
import data.finset.prod
import data.finset.sigma
import data.list.nodup_equiv_fin
import data.sym.basic
import data.ulift
import group_theory.perm.basic
import order.well_founded
import tactic.wlog
/-!
# Finite types
This file defines a typeclass to state that a type is finite.
## Main declarations
* `fintype α`: Typeclass saying that a type is finite. It takes as fields a `finset` and a proof
that all terms of type `α` are in it.
* `finset.univ`: The finset of all elements of a fintype.
* `fintype.card α`: Cardinality of a fintype. Equal to `finset.univ.card`.
* `perms_of_finset s`: The finset of permutations of the finset `s`.
* `fintype.trunc_equiv_fin`: A fintype `α` is computably equivalent to `fin (card α)`. The
`trunc`-free, noncomputable version is `fintype.equiv_fin`.
* `fintype.trunc_equiv_of_card_eq` `fintype.equiv_of_card_eq`: Two fintypes of same cardinality are
equivalent. See above.
* `fin.equiv_iff_eq`: `fin m ≃ fin n` iff `m = n`.
* `infinite α`: Typeclass saying that a type is infinite. Defined as `fintype α → false`.
* `not_fintype`: No `fintype` has an `infinite` instance.
* `infinite.nat_embedding`: An embedding of `ℕ` into an infinite type.
We also provide the following versions of the pigeonholes principle.
* `fintype.exists_ne_map_eq_of_card_lt` and `is_empty_of_card_lt`: Finitely many pigeons and
pigeonholes. Weak formulation.
* `fintype.exists_ne_map_eq_of_infinite`: Infinitely many pigeons in finitely many pigeonholes.
Weak formulation.
* `fintype.exists_infinite_fiber`: Infinitely many pigeons in finitely many pigeonholes. Strong
formulation.
Some more pigeonhole-like statements can be found in `data.fintype.card_embedding`.
## Instances
Among others, we provide `fintype` instances for
* A `subtype` of a fintype. See `fintype.subtype`.
* The `option` of a fintype.
* The product of two fintypes.
* The sum of two fintypes.
* `Prop`.
and `infinite` instances for
* specific types: `ℕ`, `ℤ`
* type constructors: `set α`, `finset α`, `multiset α`, `list α`, `α ⊕ β`, `α × β`
along with some machinery
* Types which have a surjection from/an injection to a `fintype` are themselves fintypes. See
`fintype.of_injective` and `fintype.of_surjective`.
* Types which have an injection from/a surjection to an `infinite` type are themselves `infinite`.
See `infinite.of_injective` and `infinite.of_surjective`.
-/
open_locale nat
universes u v
variables {α β γ : Type*}
/-- `fintype α` means that `α` is finite, i.e. there are only
finitely many distinct elements of type `α`. The evidence of this
is a finset `elems` (a list up to permutation without duplicates),
together with a proof that everything of type `α` is in the list. -/
class fintype (α : Type*) :=
(elems [] : finset α)
(complete : ∀ x : α, x ∈ elems)
namespace finset
variable [fintype α]
/-- `univ` is the universal finite set of type `finset α` implied from
the assumption `fintype α`. -/
def univ : finset α := fintype.elems α
@[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) :=
fintype.complete x
@[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ
lemma eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff]
@[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) :=
by ext; simp
lemma univ_nonempty_iff : (univ : finset α).nonempty ↔ nonempty α :=
by rw [← coe_nonempty, coe_univ, set.nonempty_iff_univ_nonempty]
lemma univ_nonempty [nonempty α] : (univ : finset α).nonempty :=
univ_nonempty_iff.2 ‹_›
lemma univ_eq_empty_iff : (univ : finset α) = ∅ ↔ is_empty α :=
by rw [← not_nonempty_iff, ← univ_nonempty_iff, not_nonempty_iff_eq_empty]
@[simp] lemma univ_eq_empty [is_empty α] : (univ : finset α) = ∅ := univ_eq_empty_iff.2 ‹_›
@[simp] lemma univ_unique [unique α] : (univ : finset α) = {default} :=
finset.ext $ λ x, iff_of_true (mem_univ _) $ mem_singleton.2 $ subsingleton.elim x default
@[simp] theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a
instance : order_top (finset α) :=
{ top := univ,
le_top := subset_univ }
section boolean_algebra
variables [decidable_eq α] {s : finset α} {a : α}
instance : boolean_algebra (finset α) :=
{ compl := λ s, univ \ s,
inf_compl_le_bot := λ s x hx, by simpa using hx,
top_le_sup_compl := λ s x hx, by simp,
sdiff_eq := λ s t, by simp [ext_iff, compl],
..finset.order_top,
..finset.order_bot,
..finset.generalized_boolean_algebra }
lemma compl_eq_univ_sdiff (s : finset α) : sᶜ = univ \ s := rfl
@[simp] lemma mem_compl : a ∈ sᶜ ↔ a ∉ s := by simp [compl_eq_univ_sdiff]
lemma not_mem_compl : a ∉ sᶜ ↔ a ∈ s := by rw [mem_compl, not_not]
@[simp, norm_cast] lemma coe_compl (s : finset α) : ↑(sᶜ) = (↑s : set α)ᶜ :=
set.ext $ λ x, mem_compl
@[simp] lemma compl_empty : (∅ : finset α)ᶜ = univ := compl_bot
@[simp] lemma union_compl (s : finset α) : s ∪ sᶜ = univ := sup_compl_eq_top
@[simp] lemma inter_compl (s : finset α) : s ∩ sᶜ = ∅ := inf_compl_eq_bot
@[simp] lemma compl_union (s t : finset α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ := compl_sup
@[simp] lemma compl_inter (s t : finset α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ := compl_inf
@[simp] lemma compl_erase : (s.erase a)ᶜ = insert a sᶜ :=
by { ext, simp only [or_iff_not_imp_left, mem_insert, not_and, mem_compl, mem_erase] }
@[simp] lemma compl_insert : (insert a s)ᶜ = sᶜ.erase a :=
by { ext, simp only [not_or_distrib, mem_insert, iff_self, mem_compl, mem_erase] }
@[simp] lemma insert_compl_self (x : α) : insert x ({x}ᶜ : finset α) = univ :=
by rw [←compl_erase, erase_singleton, compl_empty]
@[simp] lemma compl_filter (p : α → Prop) [decidable_pred p] [Π x, decidable (¬p x)] :
(univ.filter p)ᶜ = univ.filter (λ x, ¬p x) :=
(filter_not _ _).symm
lemma compl_ne_univ_iff_nonempty (s : finset α) : sᶜ ≠ univ ↔ s.nonempty :=
by simp [eq_univ_iff_forall, finset.nonempty]
lemma compl_singleton (a : α) : ({a} : finset α)ᶜ = univ.erase a :=
by rw [compl_eq_univ_sdiff, sdiff_singleton_eq_erase]
lemma insert_inj_on' (s : finset α) : set.inj_on (λ a, insert a s) (sᶜ : finset α) :=
by { rw coe_compl, exact s.insert_inj_on }
end boolean_algebra
@[simp] lemma univ_inter [decidable_eq α] (s : finset α) :
univ ∩ s = s := ext $ λ a, by simp
@[simp] lemma inter_univ [decidable_eq α] (s : finset α) :
s ∩ univ = s :=
by rw [inter_comm, univ_inter]
@[simp] lemma piecewise_univ [Π i : α, decidable (i ∈ (univ : finset α))]
{δ : α → Sort*} (f g : Π i, δ i) : univ.piecewise f g = f :=
by { ext i, simp [piecewise] }
lemma piecewise_compl [decidable_eq α] (s : finset α) [Π i : α, decidable (i ∈ s)]
[Π i : α, decidable (i ∈ sᶜ)] {δ : α → Sort*} (f g : Π i, δ i) :
sᶜ.piecewise f g = s.piecewise g f :=
by { ext i, simp [piecewise] }
@[simp] lemma piecewise_erase_univ {δ : α → Sort*} [decidable_eq α] (a : α) (f g : Π a, δ a) :
(finset.univ.erase a).piecewise f g = function.update f a (g a) :=
by rw [←compl_singleton, piecewise_compl, piecewise_singleton]
lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) :
univ.map e.to_embedding = univ :=
eq_univ_iff_forall.mpr (λ b, mem_map.mpr ⟨e.symm b, mem_univ _, by simp⟩)
@[simp] lemma univ_filter_exists (f : α → β) [fintype β]
[decidable_pred (λ y, ∃ x, f x = y)] [decidable_eq β] :
finset.univ.filter (λ y, ∃ x, f x = y) = finset.univ.image f :=
by { ext, simp }
/-- Note this is a special case of `(finset.image_preimage f univ _).symm`. -/
lemma univ_filter_mem_range (f : α → β) [fintype β]
[decidable_pred (λ y, y ∈ set.range f)] [decidable_eq β] :
finset.univ.filter (λ y, y ∈ set.range f) = finset.univ.image f :=
univ_filter_exists f
lemma coe_filter_univ (p : α → Prop) [decidable_pred p] : (univ.filter p : set α) = {x | p x} :=
by rw [coe_filter, coe_univ, set.sep_univ]
/-- A special case of `finset.sup_eq_supr` that omits the useless `x ∈ univ` binder. -/
lemma sup_univ_eq_supr [complete_lattice β] (f : α → β) : finset.univ.sup f = supr f :=
(sup_eq_supr _ f).trans $ congr_arg _ $ funext $ λ a, supr_pos (mem_univ _)
/-- A special case of `finset.inf_eq_infi` that omits the useless `x ∈ univ` binder. -/
lemma inf_univ_eq_infi [complete_lattice β] (f : α → β) : finset.univ.inf f = infi f :=
sup_univ_eq_supr (by exact f : α → βᵒᵈ)
@[simp] lemma fold_inf_univ [semilattice_inf α] [order_bot α] (a : α) :
finset.univ.fold (⊓) a (λ x, x) = ⊥ :=
eq_bot_iff.2 $ ((finset.fold_op_rel_iff_and $ @_root_.le_inf_iff α _).1 le_rfl).2 ⊥ $
finset.mem_univ _
@[simp] lemma fold_sup_univ [semilattice_sup α] [order_top α] (a : α) :
finset.univ.fold (⊔) a (λ x, x) = ⊤ :=
@fold_inf_univ αᵒᵈ ‹fintype α› _ _ _
end finset
open finset function
namespace fintype
instance decidable_pi_fintype {α} {β : α → Type*} [∀ a, decidable_eq (β a)] [fintype α] :
decidable_eq (Π a, β a) :=
λ f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a)
(by simp [function.funext_iff, fintype.complete])
instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] :
decidable (∀ a, p a) :=
decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp)
instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] :
decidable (∃ a, p a) :=
decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp)
instance decidable_mem_range_fintype [fintype α] [decidable_eq β] (f : α → β) :
decidable_pred (∈ set.range f) :=
λ x, fintype.decidable_exists_fintype
section bundled_homs
instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] :
decidable_eq (α ≃ β) :=
λ a b, decidable_of_iff (a.1 = b.1) equiv.coe_fn_injective.eq_iff
instance decidable_eq_embedding_fintype [decidable_eq β] [fintype α] :
decidable_eq (α ↪ β) :=
λ a b, decidable_of_iff ((a : α → β) = b) function.embedding.coe_injective.eq_iff
@[to_additive]
instance decidable_eq_one_hom_fintype [decidable_eq β] [fintype α] [has_one α] [has_one β]:
decidable_eq (one_hom α β) :=
λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff one_hom.coe_inj)
@[to_additive]
instance decidable_eq_mul_hom_fintype [decidable_eq β] [fintype α] [has_mul α] [has_mul β]:
decidable_eq (α →ₙ* β) :=
λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff mul_hom.coe_inj)
@[to_additive]
instance decidable_eq_monoid_hom_fintype [decidable_eq β] [fintype α]
[mul_one_class α] [mul_one_class β]:
decidable_eq (α →* β) :=
λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff monoid_hom.coe_inj)
instance decidable_eq_monoid_with_zero_hom_fintype [decidable_eq β] [fintype α]
[mul_zero_one_class α] [mul_zero_one_class β] :
decidable_eq (α →*₀ β) :=
λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff monoid_with_zero_hom.coe_inj)
instance decidable_eq_ring_hom_fintype [decidable_eq β] [fintype α]
[semiring α] [semiring β]:
decidable_eq (α →+* β) :=
λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff ring_hom.coe_inj)
end bundled_homs
instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] :
decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance
instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] :
decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance
instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] :
decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance
instance decidable_right_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) :
decidable (function.right_inverse f g) :=
show decidable (∀ x, g (f x) = x), by apply_instance
instance decidable_left_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) :
decidable (function.left_inverse f g) :=
show decidable (∀ x, f (g x) = x), by apply_instance
lemma exists_max [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) :
∃ x₀ : α, ∀ x, f x ≤ f x₀ :=
by simpa using exists_max_image univ f univ_nonempty
lemma exists_min [fintype α] [nonempty α]
{β : Type*} [linear_order β] (f : α → β) :
∃ x₀ : α, ∀ x, f x₀ ≤ f x :=
by simpa using exists_min_image univ f univ_nonempty
/-- Construct a proof of `fintype α` from a universal multiset -/
def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) :
fintype α :=
⟨s.to_finset, by simpa using H⟩
/-- Construct a proof of `fintype α` from a universal list -/
def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) :
fintype α :=
⟨l.to_finset, by simpa using H⟩
theorem exists_univ_list (α) [fintype α] :
∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l :=
let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in
by have := and.intro univ.2 mem_univ_val;
exact ⟨_, by rwa ←e at this⟩
/-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/
def card (α) [fintype α] : ℕ := (@univ α _).card
/-- There is (computably) an equivalence between `α` and `fin (card α)`.
Since it is not unique and depends on which permutation
of the universe list is used, the equivalence is wrapped in `trunc` to
preserve computability.
See `fintype.equiv_fin` for the noncomputable version,
and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq`
for an equiv `α ≃ fin n` given `fintype.card α = n`.
See `fintype.trunc_fin_bijection` for a version without `[decidable_eq α]`.
-/
def trunc_equiv_fin (α) [decidable_eq α] [fintype α] : trunc (α ≃ fin (card α)) :=
by { unfold card finset.card,
exact quot.rec_on_subsingleton (@univ α _).1
(λ l (h : ∀ x : α, x ∈ l) (nd : l.nodup),
trunc.mk (nd.nth_le_equiv_of_forall_mem_list _ h).symm)
mem_univ_val univ.2 }
/-- There is (noncomputably) an equivalence between `α` and `fin (card α)`.
See `fintype.trunc_equiv_fin` for the computable version,
and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq`
for an equiv `α ≃ fin n` given `fintype.card α = n`.
-/
noncomputable def equiv_fin (α) [fintype α] : α ≃ fin (card α) :=
by { letI := classical.dec_eq α, exact (trunc_equiv_fin α).out }
/-- There is (computably) a bijection between `fin (card α)` and `α`.
Since it is not unique and depends on which permutation
of the universe list is used, the bijection is wrapped in `trunc` to
preserve computability.
See `fintype.trunc_equiv_fin` for a version that gives an equivalence
given `[decidable_eq α]`.
-/
def trunc_fin_bijection (α) [fintype α] :
trunc {f : fin (card α) → α // bijective f} :=
by { dunfold card finset.card,
exact quot.rec_on_subsingleton (@univ α _).1
(λ l (h : ∀ x : α, x ∈ l) (nd : l.nodup),
trunc.mk (nd.nth_le_bijection_of_forall_mem_list _ h))
mem_univ_val univ.2 }
instance (α : Type*) : subsingleton (fintype α) :=
⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext_iff, h₁, h₂]⟩
/-- Given a predicate that can be represented by a finset, the subtype
associated to the predicate is a fintype. -/
protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) :
fintype {x // p x} :=
⟨⟨s.1.pmap subtype.mk (λ x, (H x).1),
s.nodup.pmap $ λ a _ b _, congr_arg subtype.val⟩,
λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩
theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) :
@card {x // p x} (fintype.subtype s H) = s.card :=
multiset.card_pmap _ _ _
theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x)
[fintype {x // p x}] :
card {x // p x} = s.card :=
by { rw ← subtype_card s H, congr }
/-- Construct a fintype from a finset with the same elements. -/
def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p :=
fintype.subtype s H
@[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) :
@fintype.card p (of_finset s H) = s.card :=
fintype.subtype_card s H
theorem card_of_finset' {p : set α} (s : finset α)
(H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card :=
by rw ←card_of_finset s H; congr
/-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/
def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β :=
⟨univ.map ⟨f, H.1⟩,
λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩
/-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/
def of_surjective [decidable_eq β] [fintype α] (f : α → β) (H : function.surjective f) :
fintype β :=
⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩
end fintype
section inv
namespace function
variables [fintype α] [decidable_eq β]
namespace injective
variables {f : α → β} (hf : function.injective f)
/--
The inverse of an `hf : injective` function `f : α → β`, of the type `↥(set.range f) → α`.
This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`,
or the function version of applying `(equiv.of_injective f hf).symm`.
This function should not usually be used for actual computation because for most cases,
an explicit inverse can be stated that has better computational properties.
This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where
`N = fintype.card α`.
-/
def inv_of_mem_range : set.range f → α :=
λ b, finset.choose (λ a, f a = b) finset.univ ((exists_unique_congr (by simp)).mp
(hf.exists_unique_of_mem_range b.property))
lemma left_inv_of_inv_of_mem_range (b : set.range f) :
f (hf.inv_of_mem_range b) = b :=
(finset.choose_spec (λ a, f a = b) _ _).right
@[simp] lemma right_inv_of_inv_of_mem_range (a : α) :
hf.inv_of_mem_range (⟨f a, set.mem_range_self a⟩) = a :=
hf (finset.choose_spec (λ a', f a' = f a) _ _).right
lemma inv_fun_restrict [nonempty α] :
(set.range f).restrict (inv_fun f) = hf.inv_of_mem_range :=
begin
ext ⟨b, h⟩,
apply hf,
simp [hf.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)]
end
lemma inv_of_mem_range_surjective : function.surjective hf.inv_of_mem_range :=
λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩
end injective
namespace embedding
variables (f : α ↪ β) (b : set.range f)
/--
The inverse of an embedding `f : α ↪ β`, of the type `↥(set.range f) → α`.
This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`,
or the function version of applying `(equiv.of_injective f f.injective).symm`.
This function should not usually be used for actual computation because for most cases,
an explicit inverse can be stated that has better computational properties.
This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where
`N = fintype.card α`.
-/
def inv_of_mem_range : α :=
f.injective.inv_of_mem_range b
@[simp] lemma left_inv_of_inv_of_mem_range :
f (f.inv_of_mem_range b) = b :=
f.injective.left_inv_of_inv_of_mem_range b
@[simp] lemma right_inv_of_inv_of_mem_range (a : α) :
f.inv_of_mem_range ⟨f a, set.mem_range_self a⟩ = a :=
f.injective.right_inv_of_inv_of_mem_range a
lemma inv_fun_restrict [nonempty α] :
(set.range f).restrict (inv_fun f) = f.inv_of_mem_range :=
begin
ext ⟨b, h⟩,
apply f.injective,
simp [f.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)]
end
lemma inv_of_mem_range_surjective : function.surjective f.inv_of_mem_range :=
λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩
end embedding
end function
end inv
namespace fintype
/-- Given an injective function to a fintype, the domain is also a
fintype. This is noncomputable because injectivity alone cannot be
used to construct preimages. -/
noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α :=
by letI := classical.dec; exact
if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα;
exact of_surjective (inv_fun f) (inv_fun_surjective H)
else ⟨∅, λ x, (hα ⟨x⟩).elim⟩
/-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/
def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective
theorem of_equiv_card [fintype α] (f : α ≃ β) :
@card β (of_equiv α f) = card α :=
multiset.card_map _ _
theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β :=
by rw ← of_equiv_card f; congr
@[congr]
lemma card_congr' {α β} [fintype α] [fintype β] (h : α = β) : card α = card β :=
card_congr (by rw h)
section
variables [fintype α] [fintype β]
/-- If the cardinality of `α` is `n`, there is computably a bijection between `α` and `fin n`.
See `fintype.equiv_fin_of_card_eq` for the noncomputable definition,
and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`.
-/
def trunc_equiv_fin_of_card_eq [decidable_eq α] {n : ℕ} (h : fintype.card α = n) :
trunc (α ≃ fin n) :=
(trunc_equiv_fin α).map (λ e, e.trans (fin.cast h).to_equiv)
/-- If the cardinality of `α` is `n`, there is noncomputably a bijection between `α` and `fin n`.
See `fintype.trunc_equiv_fin_of_card_eq` for the computable definition,
and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`.
-/
noncomputable def equiv_fin_of_card_eq {n : ℕ} (h : fintype.card α = n) :
α ≃ fin n :=
by { letI := classical.dec_eq α, exact (trunc_equiv_fin_of_card_eq h).out }
/-- Two `fintype`s with the same cardinality are (computably) in bijection.
See `fintype.equiv_of_card_eq` for the noncomputable version,
and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for
the specialization to `fin`.
-/
def trunc_equiv_of_card_eq [decidable_eq α] [decidable_eq β] (h : card α = card β) :
trunc (α ≃ β) :=
(trunc_equiv_fin_of_card_eq h).bind (λ e, (trunc_equiv_fin β).map (λ e', e.trans e'.symm))
/-- Two `fintype`s with the same cardinality are (noncomputably) in bijection.
See `fintype.trunc_equiv_of_card_eq` for the computable version,
and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for
the specialization to `fin`.
-/
noncomputable def equiv_of_card_eq (h : card α = card β) : α ≃ β :=
by { letI := classical.dec_eq α, letI := classical.dec_eq β,
exact (trunc_equiv_of_card_eq h).out }
end
theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) :=
⟨λ h, by { haveI := classical.prop_decidable, exact (trunc_equiv_of_card_eq h).nonempty },
λ ⟨f⟩, card_congr f⟩
/-- Any subsingleton type with a witness is a fintype (with one term). -/
def of_subsingleton (a : α) [subsingleton α] : fintype α :=
⟨{a}, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩
@[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] :
@univ _ (of_subsingleton a) = {a} := rfl
/-- Note: this lemma is specifically about `fintype.of_subsingleton`. For a statement about
arbitrary `fintype` instances, use either `fintype.card_le_one_iff_subsingleton` or
`fintype.card_unique`. -/
@[simp] theorem card_of_subsingleton (a : α) [subsingleton α] :
@fintype.card _ (of_subsingleton a) = 1 := rfl
@[simp] theorem card_unique [unique α] [h : fintype α] :
fintype.card α = 1 :=
subsingleton.elim (of_subsingleton default) h ▸ card_of_subsingleton _
@[priority 100] -- see Note [lower instance priority]
instance of_is_empty [is_empty α] : fintype α := ⟨∅, is_empty_elim⟩
/-- Note: this lemma is specifically about `fintype.of_is_empty`. For a statement about
arbitrary `fintype` instances, use `finset.univ_eq_empty`. -/
-- no-lint since while `finset.univ_eq_empty` can prove this, it isn't applicable for `dsimp`.
@[simp, nolint simp_nf] theorem univ_of_is_empty [is_empty α] : @univ α _ = ∅ := rfl
/-- Note: this lemma is specifically about `fintype.of_is_empty`. For a statement about
arbitrary `fintype` instances, use `fintype.card_eq_zero_iff`. -/
@[simp] theorem card_of_is_empty [is_empty α] : fintype.card α = 0 := rfl
open_locale classical
variables (α)
/-- Any subsingleton type is (noncomputably) a fintype (with zero or one term). -/
@[priority 5] -- see Note [lower instance priority]
noncomputable instance of_subsingleton' [subsingleton α] : fintype α :=
if h : nonempty α then
of_subsingleton (nonempty.some h)
else
@fintype.of_is_empty _ $ not_nonempty_iff.mp h
end fintype
namespace set
/-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/
def to_finset (s : set α) [fintype s] : finset α :=
⟨(@finset.univ s _).1.map subtype.val, finset.univ.nodup.map $ λ a b, subtype.eq⟩
@[congr]
lemma to_finset_congr {s t : set α} [fintype s] [fintype t] (h : s = t) :
to_finset s = to_finset t :=
by cc
@[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s :=
by simp [to_finset]
@[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s :=
mem_to_finset
-- We use an arbitrary `[fintype s]` instance here,
-- not necessarily coming from a `[fintype α]`.
@[simp]
lemma to_finset_card {α : Type*} (s : set α) [fintype s] :
s.to_finset.card = fintype.card s :=
multiset.card_map subtype.val finset.univ.val
@[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s :=
set.ext $ λ _, mem_to_finset
@[simp] theorem to_finset_inj {s t : set α} [fintype s] [fintype t] :
s.to_finset = t.to_finset ↔ s = t :=
⟨λ h, by rw [←s.coe_to_finset, h, t.coe_to_finset], λ h, by simp [h]; congr⟩
@[simp, mono] theorem to_finset_mono {s t : set α} [fintype s] [fintype t] :
s.to_finset ⊆ t.to_finset ↔ s ⊆ t :=
by simp [finset.subset_iff, set.subset_def]
@[simp, mono] theorem to_finset_strict_mono {s t : set α} [fintype s] [fintype t] :
s.to_finset ⊂ t.to_finset ↔ s ⊂ t :=
by simp only [finset.ssubset_def, to_finset_mono, ssubset_def]
@[simp] theorem to_finset_disjoint_iff [decidable_eq α] {s t : set α} [fintype s] [fintype t] :
disjoint s.to_finset t.to_finset ↔ disjoint s t :=
by simp only [disjoint_iff_disjoint_coe, coe_to_finset]
theorem to_finset_compl [decidable_eq α] [fintype α] (s : set α) [fintype s] [fintype ↥sᶜ] :
(sᶜ).to_finset = s.to_finsetᶜ :=
by { ext a, simp }
lemma filter_mem_univ_eq_to_finset [fintype α] (s : set α) [fintype s] [decidable_pred (∈ s)] :
finset.univ.filter (∈ s) = s.to_finset :=
by { ext, simp only [mem_filter, finset.mem_univ, true_and, mem_to_finset] }
end set
lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α :=
rfl
lemma finset.eq_univ_of_card [fintype α] (s : finset α) (hs : s.card = fintype.card α) :
s = univ :=
eq_of_subset_of_card_le (subset_univ _) $ by rw [hs, finset.card_univ]
lemma finset.card_eq_iff_eq_univ [fintype α] (s : finset α) :
s.card = fintype.card α ↔ s = finset.univ :=
⟨s.eq_univ_of_card, by { rintro rfl, exact finset.card_univ, }⟩
lemma finset.card_le_univ [fintype α] (s : finset α) :
s.card ≤ fintype.card α :=
card_le_of_subset (subset_univ s)
lemma finset.card_lt_univ_of_not_mem [fintype α] {s : finset α} {x : α} (hx : x ∉ s) :
s.card < fintype.card α :=
card_lt_card ⟨subset_univ s, not_forall.2 ⟨x, λ hx', hx (hx' $ mem_univ x)⟩⟩
lemma finset.card_lt_iff_ne_univ [fintype α] (s : finset α) :
s.card < fintype.card α ↔ s ≠ finset.univ :=
s.card_le_univ.lt_iff_ne.trans (not_iff_not_of_iff s.card_eq_iff_eq_univ)
lemma finset.card_compl_lt_iff_nonempty [fintype α] [decidable_eq α] (s : finset α) :
sᶜ.card < fintype.card α ↔ s.nonempty :=
sᶜ.card_lt_iff_ne_univ.trans s.compl_ne_univ_iff_nonempty
lemma finset.card_univ_diff [decidable_eq α] [fintype α] (s : finset α) :
(finset.univ \ s).card = fintype.card α - s.card :=
finset.card_sdiff (subset_univ s)
lemma finset.card_compl [decidable_eq α] [fintype α] (s : finset α) :
sᶜ.card = fintype.card α - s.card :=
finset.card_univ_diff s
lemma fintype.card_compl_set [fintype α] (s : set α) [fintype s] [fintype ↥sᶜ] :
fintype.card ↥sᶜ = fintype.card α - fintype.card s :=
begin
classical,
rw [← set.to_finset_card, ← set.to_finset_card, ← finset.card_compl, set.to_finset_compl]
end
instance (n : ℕ) : fintype (fin n) :=
⟨finset.fin_range n, finset.mem_fin_range⟩
lemma fin.univ_def (n : ℕ) : (univ : finset (fin n)) = finset.fin_range n := rfl
@[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n :=
list.length_fin_range n
@[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n :=
by rw [finset.card_univ, fintype.card_fin]
/-- `fin` as a map from `ℕ` to `Type` is injective. Note that since this is a statement about
equality of types, using it should be avoided if possible. -/
lemma fin_injective : function.injective fin :=
λ m n h,
(fintype.card_fin m).symm.trans $ (fintype.card_congr $ equiv.cast h).trans (fintype.card_fin n)
/-- A reversed version of `fin.cast_eq_cast` that is easier to rewrite with. -/
theorem fin.cast_eq_cast' {n m : ℕ} (h : fin n = fin m) :
cast h = ⇑(fin.cast $ fin_injective h) :=
(fin.cast_eq_cast _).symm
lemma card_finset_fin_le {n : ℕ} (s : finset (fin n)) : s.card ≤ n :=
by simpa only [fintype.card_fin] using s.card_le_univ
lemma fin.equiv_iff_eq {m n : ℕ} : nonempty (fin m ≃ fin n) ↔ m = n :=
⟨λ ⟨h⟩, by simpa using fintype.card_congr h, λ h, ⟨equiv.cast $ h ▸ rfl ⟩ ⟩
@[simp] lemma fin.image_succ_above_univ {n : ℕ} (i : fin (n + 1)) :
univ.image i.succ_above = {i}ᶜ :=
by { ext m, simp }
@[simp] lemma fin.image_succ_univ (n : ℕ) : (univ : finset (fin n)).image fin.succ = {0}ᶜ :=
by rw [← fin.succ_above_zero, fin.image_succ_above_univ]
@[simp] lemma fin.image_cast_succ (n : ℕ) :
(univ : finset (fin n)).image fin.cast_succ = {fin.last n}ᶜ :=
by rw [← fin.succ_above_last, fin.image_succ_above_univ]
/-- Embed `fin n` into `fin (n + 1)` by prepending zero to the `univ` -/
lemma fin.univ_succ (n : ℕ) :
(univ : finset (fin (n + 1))) = insert 0 (univ.image fin.succ) :=
by simp
/-- Embed `fin n` into `fin (n + 1)` by appending a new `fin.last n` to the `univ` -/
lemma fin.univ_cast_succ (n : ℕ) :
(univ : finset (fin (n + 1))) = insert (fin.last n) (univ.image fin.cast_succ) :=
by simp
/-- Embed `fin n` into `fin (n + 1)` by inserting
around a specified pivot `p : fin (n + 1)` into the `univ` -/
lemma fin.univ_succ_above (n : ℕ) (p : fin (n + 1)) :
(univ : finset (fin (n + 1))) = insert p (univ.image (fin.succ_above p)) :=
by simp
@[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α :=
fintype.of_subsingleton default
/-- Short-circuit instance to decrease search for `unique.fintype`,
since that relies on a subsingleton elimination for `unique`. -/
instance fintype.subtype_eq (y : α) : fintype {x // x = y} :=
fintype.subtype {y} (by simp)
/-- Short-circuit instance to decrease search for `unique.fintype`,
since that relies on a subsingleton elimination for `unique`. -/
instance fintype.subtype_eq' (y : α) : fintype {x // y = x} :=
fintype.subtype {y} (by simp [eq_comm])
@[simp] lemma fintype.card_subtype_eq (y : α) [fintype {x // x = y}] :
fintype.card {x // x = y} = 1 :=
fintype.card_unique
@[simp] lemma fintype.card_subtype_eq' (y : α) [fintype {x // y = x}] :
fintype.card {x // y = x} = 1 :=
fintype.card_unique
@[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl
@[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl
@[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl
@[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl
instance : fintype unit := fintype.of_subsingleton ()
theorem fintype.univ_unit : @univ unit _ = {()} := rfl
theorem fintype.card_unit : fintype.card unit = 1 := rfl
instance : fintype punit := fintype.of_subsingleton punit.star
@[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl
@[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl
instance : fintype bool := ⟨⟨tt ::ₘ ff ::ₘ 0, by simp⟩, λ x, by cases x; simp⟩
@[simp] theorem fintype.univ_bool : @univ bool _ = {tt, ff} := rfl
instance units_int.fintype : fintype ℤˣ :=
⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩
@[simp] lemma units_int.univ : (finset.univ : finset ℤˣ) = {1, -1} := rfl
instance additive.fintype : Π [fintype α], fintype (additive α) := id
instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id
@[simp] theorem fintype.card_units_int : fintype.card ℤˣ = 2 := rfl
@[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl
instance {α : Type*} [fintype α] : fintype (option α) :=
⟨univ.insert_none, λ a, by simp⟩
lemma univ_option (α : Type*) [fintype α] : (univ : finset (option α)) = insert_none univ := rfl
@[simp] theorem fintype.card_option {α : Type*} [fintype α] :
fintype.card (option α) = fintype.card α + 1 :=
(finset.card_cons _).trans $ congr_arg2 _ (card_map _) rfl
/-- If `option α` is a `fintype` then so is `α` -/
def fintype_of_option {α : Type*} [fintype (option α)] : fintype α :=
⟨finset.erase_none (fintype.elems (option α)), λ x, mem_erase_none.mpr (fintype.complete (some x))⟩
/-- A type is a `fintype` if its successor (using `option`) is a `fintype`. -/
def fintype_of_option_equiv [fintype α] (f : α ≃ option β) : fintype β :=
by { haveI := fintype.of_equiv _ f, exact fintype_of_option }
instance {α : Type*} (β : α → Type*)
[fintype α] [∀ a, fintype (β a)] : fintype (sigma β) :=
⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩
@[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] :
(univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl
instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) :=
⟨univ.product univ, λ ⟨a, b⟩, by simp⟩
@[simp] lemma finset.univ_product_univ {α β : Type*} [fintype α] [fintype β] :
(univ : finset α).product (univ : finset β) = univ :=
rfl
@[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] :
fintype.card (α × β) = fintype.card α * fintype.card β :=
card_product _ _
/-- Given that `α × β` is a fintype, `α` is also a fintype. -/
def fintype.prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α :=
⟨(fintype.elems (α × β)).image prod.fst,
λ a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩
/-- Given that `α × β` is a fintype, `β` is also a fintype. -/
def fintype.prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β :=
⟨(fintype.elems (α × β)).image prod.snd,
λ b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩
instance (α : Type*) [fintype α] : fintype (ulift α) :=
fintype.of_equiv _ equiv.ulift.symm
@[simp] theorem fintype.card_ulift (α : Type*) [fintype α] :
fintype.card (ulift α) = fintype.card α :=
fintype.of_equiv_card _
instance (α : Type*) [fintype α] : fintype (plift α) :=
fintype.of_equiv _ equiv.plift.symm
@[simp] theorem fintype.card_plift (α : Type*) [fintype α] :
fintype.card (plift α) = fintype.card α :=
fintype.of_equiv_card _
instance (α : Type*) [fintype α] : fintype αᵒᵈ := ‹fintype α›
@[simp] lemma fintype.card_order_dual (α : Type*) [fintype α] : fintype.card αᵒᵈ = fintype.card α :=
rfl
instance (α : Type*) [fintype α] : fintype (lex α) := ‹fintype α›
@[simp] lemma fintype.card_lex (α : Type*) [fintype α] :
fintype.card (lex α) = fintype.card α := rfl
lemma univ_sum_type {α β : Type*} [fintype α] [fintype β] [fintype (α ⊕ β)] [decidable_eq (α ⊕ β)] :
(univ : finset (α ⊕ β)) = map function.embedding.inl univ ∪ map function.embedding.inr univ :=
begin
rw [eq_comm, eq_univ_iff_forall], simp only [mem_union, mem_map, exists_prop, mem_univ, true_and],
rintro (x|y), exacts [or.inl ⟨x, rfl⟩, or.inr ⟨y, rfl⟩]
end
instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) :=
@fintype.of_equiv _ _ (@sigma.fintype _
(λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _
(λ b, by cases b; apply ulift.fintype))
((equiv.sum_equiv_sigma_bool _ _).symm.trans
(equiv.sum_congr equiv.ulift equiv.ulift))
/-- Given that `α ⊕ β` is a fintype, `α` is also a fintype. This is non-computable as it uses
that `sum.inl` is an injection, but there's no clear inverse if `α` is empty. -/
noncomputable def fintype.sum_left {α β} [fintype (α ⊕ β)] : fintype α :=
fintype.of_injective (sum.inl : α → α ⊕ β) sum.inl_injective
/-- Given that `α ⊕ β` is a fintype, `β` is also a fintype. This is non-computable as it uses
that `sum.inr` is an injection, but there's no clear inverse if `β` is empty. -/
noncomputable def fintype.sum_right {α β} [fintype (α ⊕ β)] : fintype β :=
fintype.of_injective (sum.inr : β → α ⊕ β) sum.inr_injective
@[simp] theorem fintype.card_sum [fintype α] [fintype β] :
fintype.card (α ⊕ β) = fintype.card α + fintype.card β :=
begin
classical,
rw [←finset.card_univ, univ_sum_type, finset.card_union_eq],
{ simp [finset.card_univ] },
{ intros x hx,
suffices : (∃ (a : α), sum.inl a = x) ∧ ∃ (b : β), sum.inr b = x,
{ obtain ⟨⟨a, rfl⟩, ⟨b, hb⟩⟩ := this,
simpa using hb },
simpa using hx }
end
/-- If the subtype of all-but-one elements is a `fintype` then the type itself is a `fintype`. -/
def fintype_of_fintype_ne (a : α) [decidable_pred (= a)] (h : fintype {b // b ≠ a}) : fintype α :=
fintype.of_equiv _ $ equiv.sum_compl (= a)
section finset
/-! ### `fintype (s : finset α)` -/
instance finset.fintype_coe_sort {α : Type u} (s : finset α) : fintype s :=
⟨s.attach, s.mem_attach⟩
@[simp] lemma finset.univ_eq_attach {α : Type u} (s : finset α) :
(univ : finset s) = s.attach :=
rfl
end finset
namespace fintype
variables [fintype α] [fintype β]
lemma card_le_of_injective (f : α → β) (hf : function.injective f) : card α ≤ card β :=
finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h)
lemma card_le_of_embedding (f : α ↪ β) : card α ≤ card β := card_le_of_injective f f.2
lemma card_lt_of_injective_of_not_mem (f : α → β) (h : function.injective f)
{b : β} (w : b ∉ set.range f) : card α < card β :=
calc card α = (univ.map ⟨f, h⟩).card : (card_map _).symm
... < card β : finset.card_lt_univ_of_not_mem $
by rwa [← mem_coe, coe_map, coe_univ, set.image_univ]
lemma card_lt_of_injective_not_surjective (f : α → β) (h : function.injective f)
(h' : ¬function.surjective f) : card α < card β :=
let ⟨y, hy⟩ := not_forall.1 h' in card_lt_of_injective_of_not_mem f h hy
lemma card_le_of_surjective (f : α → β) (h : function.surjective f) : card β ≤ card α :=
card_le_of_injective _ (function.injective_surj_inv h)
lemma card_range_le {α β : Type*} (f : α → β) [fintype α] [fintype (set.range f)] :
fintype.card (set.range f) ≤ fintype.card α :=
fintype.card_le_of_surjective (λ a, ⟨f a, by simp⟩) (λ ⟨_, a, ha⟩, ⟨a, by simpa using ha⟩)
lemma card_range {α β F : Type*} [embedding_like F α β] (f : F) [fintype α]
[fintype (set.range f)] :
fintype.card (set.range f) = fintype.card α :=
eq.symm $ fintype.card_congr $ equiv.of_injective _ $ embedding_like.injective f
/--
The pigeonhole principle for finitely many pigeons and pigeonholes.
This is the `fintype` version of `finset.exists_ne_map_eq_of_card_lt_of_maps_to`.
-/
lemma exists_ne_map_eq_of_card_lt (f : α → β) (h : fintype.card β < fintype.card α) :
∃ x y, x ≠ y ∧ f x = f y :=
let ⟨x, _, y, _, h⟩ := finset.exists_ne_map_eq_of_card_lt_of_maps_to h (λ x _, mem_univ (f x))
in ⟨x, y, h⟩
lemma card_eq_one_iff : card α = 1 ↔ (∃ x : α, ∀ y, y = x) :=
by rw [←card_unit, card_eq]; exact
⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩,
λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm,
λ _, subsingleton.elim _ _⟩⟩⟩
lemma card_eq_zero_iff : card α = 0 ↔ is_empty α :=
by rw [card, finset.card_eq_zero, univ_eq_empty_iff]
lemma card_eq_zero [is_empty α] : card α = 0 := card_eq_zero_iff.2 ‹_›
lemma card_eq_one_iff_nonempty_unique : card α = 1 ↔ nonempty (unique α) :=
⟨λ h, let ⟨d, h⟩ := fintype.card_eq_one_iff.mp h in ⟨{ default := d, uniq := h}⟩,
λ ⟨h⟩, by exactI fintype.card_unique⟩
/-- A `fintype` with cardinality zero is equivalent to `empty`. -/
def card_eq_zero_equiv_equiv_empty : card α = 0 ≃ (α ≃ empty) :=
(equiv.of_iff card_eq_zero_iff).trans (equiv.equiv_empty_equiv α).symm
lemma card_pos_iff : 0 < card α ↔ nonempty α :=
pos_iff_ne_zero.trans $ not_iff_comm.mp $ not_nonempty_iff.trans card_eq_zero_iff.symm
lemma card_pos [h : nonempty α] : 0 < card α :=
card_pos_iff.mpr h
lemma card_ne_zero [nonempty α] : card α ≠ 0 :=
ne_of_gt card_pos
lemma card_le_one_iff : card α ≤ 1 ↔ (∀ a b : α, a = b) :=
let n := card α in
have hn : n = card α := rfl,
match n, hn with
| 0 := λ ha, ⟨λ h, λ a, (card_eq_zero_iff.1 ha.symm).elim a, λ _, ha ▸ nat.le_succ _⟩
| 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm in
by rw [hx a, hx b],
λ _, ha ▸ le_rfl⟩
| (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial,
(λ h, card_unit ▸ card_le_of_injective (λ _, ())
(λ _ _ _, h _ _))⟩
end
lemma card_le_one_iff_subsingleton : card α ≤ 1 ↔ subsingleton α :=
card_le_one_iff.trans subsingleton_iff.symm
lemma one_lt_card_iff_nontrivial : 1 < card α ↔ nontrivial α :=
begin
classical,
rw ←not_iff_not,
push_neg,
rw [not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton]
end
lemma exists_ne_of_one_lt_card (h : 1 < card α) (a : α) : ∃ b : α, b ≠ a :=
by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_ne a }
lemma exists_pair_of_one_lt_card (h : 1 < card α) : ∃ (a b : α), a ≠ b :=
by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_pair_ne α }
lemma card_eq_one_of_forall_eq {i : α} (h : ∀ j, j = i) : card α = 1 :=
fintype.card_eq_one_iff.2 ⟨i,h⟩
lemma one_lt_card [h : nontrivial α] : 1 < fintype.card α :=
fintype.one_lt_card_iff_nontrivial.mpr h
lemma one_lt_card_iff : 1 < card α ↔ ∃ a b : α, a ≠ b :=
one_lt_card_iff_nontrivial.trans nontrivial_iff
lemma two_lt_card_iff : 2 < card α ↔ ∃ a b c : α, a ≠ b ∧ a ≠ c ∧ b ≠ c :=
by simp_rw [←finset.card_univ, two_lt_card_iff, mem_univ, true_and]
lemma injective_iff_surjective {f : α → α} : injective f ↔ surjective f :=
by haveI := classical.prop_decidable; exact
have ∀ {f : α → α}, injective f → surjective f,
from λ f hinj x,
have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _)
((card_image_of_injective univ hinj).symm ▸ le_rfl),
have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _,
exists_of_bex (mem_image.1 h₂),
⟨this,
λ hsurj, has_left_inverse.injective
⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse
(this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩
lemma injective_iff_bijective {f : α → α} : injective f ↔ bijective f :=
by simp [bijective, injective_iff_surjective]
lemma surjective_iff_bijective {f : α → α} : surjective f ↔ bijective f :=
by simp [bijective, injective_iff_surjective]
lemma injective_iff_surjective_of_equiv {β : Type*} {f : α → β} (e : α ≃ β) :
injective f ↔ surjective f :=
have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from injective_iff_surjective,
⟨λ hinj, by simpa [function.comp] using
e.surjective.comp (this.1 (e.symm.injective.comp hinj)),
λ hsurj, by simpa [function.comp] using
e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩
lemma card_of_bijective {f : α → β} (hf : bijective f) : card α = card β :=
card_congr (equiv.of_bijective f hf)
lemma bijective_iff_injective_and_card (f : α → β) :
bijective f ↔ injective f ∧ card α = card β :=
begin
split,
{ intro h, exact ⟨h.1, card_of_bijective h⟩ },
{ rintro ⟨hf, h⟩,
refine ⟨hf, _⟩,
rwa ←injective_iff_surjective_of_equiv (equiv_of_card_eq h) }
end
lemma bijective_iff_surjective_and_card (f : α → β) :
bijective f ↔ surjective f ∧ card α = card β :=
begin
split,
{ intro h, exact ⟨h.2, card_of_bijective h⟩ },
{ rintro ⟨hf, h⟩,
refine ⟨_, hf⟩,
rwa injective_iff_surjective_of_equiv (equiv_of_card_eq h) }
end
lemma right_inverse_of_left_inverse_of_card_le {f : α → β} {g : β → α}
(hfg : left_inverse f g) (hcard : card α ≤ card β) :
right_inverse f g :=
have hsurj : surjective f, from surjective_iff_has_right_inverse.2 ⟨g, hfg⟩,
right_inverse_of_injective_of_left_inverse
((bijective_iff_surjective_and_card _).2
⟨hsurj, le_antisymm hcard (card_le_of_surjective f hsurj)⟩ ).1
hfg
lemma left_inverse_of_right_inverse_of_card_le {f : α → β} {g : β → α}
(hfg : right_inverse f g) (hcard : card β ≤ card α) :
left_inverse f g :=
right_inverse_of_left_inverse_of_card_le hfg hcard
end fintype
lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} :
↑(finset.image f finset.univ) = set.range f :=
by { ext x, simp }
instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} :=
fintype.of_list l.attach l.mem_attach
instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} :=
fintype.of_multiset s.attach s.mem_attach
instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} :=
⟨s.attach, s.mem_attach⟩
instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) :=
finset.subtype.fintype s
@[simp] lemma fintype.card_coe (s : finset α) [fintype s] :
fintype.card s = s.card := fintype.card_of_finset' s (λ _, iff.rfl)
lemma finset.attach_eq_univ {s : finset α} : s.attach = finset.univ := rfl
instance plift.fintype_Prop (p : Prop) [decidable p] : fintype (plift p) :=
⟨if h : p then {⟨h⟩} else ∅, λ ⟨h⟩, by simp [h]⟩
instance Prop.fintype : fintype Prop :=
⟨⟨true ::ₘ false ::ₘ 0, by simp [true_ne_false]⟩,
classical.cases (by simp) (by simp)⟩
@[simp] lemma fintype.card_Prop : fintype.card Prop = 2 := rfl
instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} :=
fintype.subtype (univ.filter p) (by simp)
/- TODO Without the coercion arrow (`↥`) there is an elaboration bug;
it essentially infers `fintype.{v} (set.univ.{u} : set α)` with `v` and `u` distinct.
Reported in leanprover-community/lean#672 -/
@[simp] lemma set.to_finset_univ [fintype ↥(set.univ : set α)] [fintype α] :
(set.univ : set α).to_finset = finset.univ :=
by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] }
@[simp] lemma set.to_finset_eq_empty_iff {s : set α} [fintype s] : s.to_finset = ∅ ↔ s = ∅ :=
by simp [ext_iff, set.ext_iff]
@[simp] lemma set.to_finset_empty : (∅ : set α).to_finset = ∅ :=
set.to_finset_eq_empty_iff.mpr rfl
@[simp] lemma set.to_finset_range [decidable_eq α] [fintype β] (f : β → α) [fintype (set.range f)] :
(set.range f).to_finset = finset.univ.image f :=
by simp [ext_iff]
/-- A set on a fintype, when coerced to a type, is a fintype. -/
def set_fintype [fintype α] (s : set α) [decidable_pred (∈ s)] : fintype s :=
subtype.fintype (λ x, x ∈ s)
lemma set_fintype_card_le_univ [fintype α] (s : set α) [fintype ↥s] :
fintype.card ↥s ≤ fintype.card α :=
fintype.card_le_of_embedding (function.embedding.subtype s)
lemma set_fintype_card_eq_univ_iff [fintype α] (s : set α) [fintype ↥s] :
fintype.card s = fintype.card α ↔ s = set.univ :=
by rw [←set.to_finset_card, finset.card_eq_iff_eq_univ, ←set.to_finset_univ, set.to_finset_inj]
section
variables (α)
/-- The `αˣ` type is equivalent to a subtype of `α × α`. -/
@[simps]
def _root_.units_equiv_prod_subtype [monoid α] :
αˣ ≃ {p : α × α // p.1 * p.2 = 1 ∧ p.2 * p.1 = 1} :=
{ to_fun := λ u, ⟨(u, ↑u⁻¹), u.val_inv, u.inv_val⟩,
inv_fun := λ p, units.mk (p : α × α).1 (p : α × α).2 p.prop.1 p.prop.2,
left_inv := λ u, units.ext rfl,
right_inv := λ p, subtype.ext $ prod.ext rfl rfl}
/-- In a `group_with_zero` `α`, the unit group `αˣ` is equivalent to the subtype of nonzero
elements. -/
@[simps]
def _root_.units_equiv_ne_zero [group_with_zero α] : αˣ ≃ {a : α // a ≠ 0} :=
⟨λ a, ⟨a, a.ne_zero⟩, λ a, units.mk0 _ a.prop, λ _, units.ext rfl, λ _, subtype.ext rfl⟩
end
instance [monoid α] [fintype α] [decidable_eq α] : fintype αˣ :=
fintype.of_equiv _ (units_equiv_prod_subtype α).symm
lemma fintype.card_units [group_with_zero α] [fintype α] [fintype αˣ] :
fintype.card αˣ = fintype.card α - 1 :=
begin
classical,
rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : α)⟩),
fintype.card_congr (units_equiv_ne_zero α)],
have := fintype.card_congr (equiv.sum_compl (= (0 : α))).symm,
rwa [fintype.card_sum, add_comm, fintype.card_subtype_eq] at this,
end
namespace function.embedding
/-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/
noncomputable def equiv_of_fintype_self_embedding [fintype α] (e : α ↪ α) : α ≃ α :=
equiv.of_bijective e (fintype.injective_iff_bijective.1 e.2)
@[simp]
lemma equiv_of_fintype_self_embedding_to_embedding [fintype α] (e : α ↪ α) :
e.equiv_of_fintype_self_embedding.to_embedding = e :=
by { ext, refl, }
/-- If `‖β‖ < ‖α‖` there are no embeddings `α ↪ β`.
This is a formulation of the pigeonhole principle.
Note this cannot be an instance as it needs `h`. -/
@[simp] lemma is_empty_of_card_lt [fintype α] [fintype β]
(h : fintype.card β < fintype.card α) : is_empty (α ↪ β) :=
⟨λ f, let ⟨x, y, ne, feq⟩ := fintype.exists_ne_map_eq_of_card_lt f h in ne $ f.injective feq⟩
/-- A constructive embedding of a fintype `α` in another fintype `β` when `card α ≤ card β`. -/
def trunc_of_card_le [fintype α] [fintype β] [decidable_eq α] [decidable_eq β]
(h : fintype.card α ≤ fintype.card β) : trunc (α ↪ β) :=
(fintype.trunc_equiv_fin α).bind $ λ ea,
(fintype.trunc_equiv_fin β).map $ λ eb,
ea.to_embedding.trans ((fin.cast_le h).to_embedding.trans eb.symm.to_embedding)
lemma nonempty_of_card_le [fintype α] [fintype β]
(h : fintype.card α ≤ fintype.card β) : nonempty (α ↪ β) :=
by { classical, exact (trunc_of_card_le h).nonempty }
lemma exists_of_card_le_finset [fintype α] {s : finset β} (h : fintype.card α ≤ s.card) :
∃ (f : α ↪ β), set.range f ⊆ s :=
begin
rw ← fintype.card_coe at h,
rcases nonempty_of_card_le h with ⟨f⟩,
exact ⟨f.trans (embedding.subtype _), by simp [set.range_subset_iff]⟩
end
end function.embedding
@[simp]
lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) :
univ.map e = univ :=
by rw [←e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding]
namespace fintype
lemma card_lt_of_surjective_not_injective [fintype α] [fintype β] (f : α → β)
(h : function.surjective f) (h' : ¬function.injective f) : card β < card α :=
card_lt_of_injective_not_surjective _ (function.injective_surj_inv h) $ λ hg,
have w : function.bijective (function.surj_inv h) := ⟨function.injective_surj_inv h, hg⟩,
h' $ (injective_iff_surjective_of_equiv (equiv.of_bijective _ w).symm).mpr h
variables [decidable_eq α] [fintype α] {δ : α → Type*}
/-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the
finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the
analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as
there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/
def pi_finset (t : Π a, finset (δ a)) : finset (Π a, δ a) :=
(finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩
@[simp] lemma mem_pi_finset {t : Π a, finset (δ a)} {f : Π a, δ a} :
f ∈ pi_finset t ↔ ∀ a, f a ∈ t a :=
begin
split,
{ simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ,
exists_imp_distrib, mem_pi],
rintro g hg hgf a,
rw ← hgf,
exact hg a },
{ simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi],
exact λ hf, ⟨λ a ha, f a, hf, rfl⟩ }
end
@[simp] lemma coe_pi_finset (t : Π a, finset (δ a)) :
(pi_finset t : set (Π a, δ a)) = set.pi set.univ (λ a, t a) :=
set.ext $ λ x, by { rw set.mem_univ_pi, exact fintype.mem_pi_finset }
lemma pi_finset_subset (t₁ t₂ : Π a, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) :
pi_finset t₁ ⊆ pi_finset t₂ :=
λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a
lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)]
(t₁ t₂ : Π a, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) :
disjoint (pi_finset t₁) (pi_finset t₂) :=
disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂,
disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a)
end fintype
/-! ### pi -/
/-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/
instance pi.fintype {α : Type*} {β : α → Type*}
[decidable_eq α] [fintype α] [∀ a, fintype (β a)] : fintype (Π a, β a) :=
⟨fintype.pi_finset (λ _, univ), by simp⟩
@[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*}
[decidable_eq α] [fintype α] [∀ a, fintype (β a)] :
fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) :=
rfl
instance d_array.fintype {n : ℕ} {α : fin n → Type*}
[∀ n, fintype (α n)] : fintype (d_array n α) :=
fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm
instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) :=
d_array.fintype
instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) :=
fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm
instance quotient.fintype [fintype α] (s : setoid α)
[decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) :=
fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩))
instance finset.fintype [fintype α] : fintype (finset α) :=
⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩
-- irreducible due to this conversation on Zulip:
-- https://leanprover.zulipchat.com/#narrow/stream/113488-general/
-- topic/.60simp.60.20ignoring.20lemmas.3F/near/241824115
@[irreducible] instance function.embedding.fintype {α β} [fintype α] [fintype β]
[decidable_eq α] [decidable_eq β] : fintype (α ↪ β) :=
fintype.of_equiv _ (equiv.subtype_injective_equiv_embedding α β)
instance [decidable_eq α] [fintype α] {n : ℕ} : fintype (sym.sym' α n) :=
quotient.fintype _
instance [decidable_eq α] [fintype α] {n : ℕ} : fintype (sym α n) :=
fintype.of_equiv _ sym.sym_equiv_sym'.symm
@[simp] lemma fintype.card_finset [fintype α] :
fintype.card (finset α) = 2 ^ (fintype.card α) :=
finset.card_powerset finset.univ
lemma finset.mem_powerset_len_univ_iff [fintype α] {s : finset α} {k : ℕ} :
s ∈ powerset_len k (univ : finset α) ↔ card s = k :=
mem_powerset_len.trans $ and_iff_right $ subset_univ _
@[simp] lemma finset.univ_filter_card_eq (α : Type*) [fintype α] (k : ℕ) :
(finset.univ : finset (finset α)).filter (λ s, s.card = k) = finset.univ.powerset_len k :=
by { ext, simp [finset.mem_powerset_len] }
@[simp] lemma fintype.card_finset_len [fintype α] (k : ℕ) :
fintype.card {s : finset α // s.card = k} = nat.choose (fintype.card α) k :=
by simp [fintype.subtype_card, finset.card_univ]
theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] :
fintype.card {x // p x} ≤ fintype.card α :=
fintype.card_le_of_embedding (function.embedding.subtype _)
theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p]
{x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α :=
fintype.card_lt_of_injective_of_not_mem coe subtype.coe_injective $ by rwa subtype.range_coe_subtype
lemma fintype.card_subtype [fintype α] (p : α → Prop) [decidable_pred p] :
fintype.card {x // p x} = ((finset.univ : finset α).filter p).card :=
begin
refine fintype.card_of_subtype _ _,
simp
end
lemma fintype.card_subtype_or (p q : α → Prop)
[fintype {x // p x}] [fintype {x // q x}] [fintype {x // p x ∨ q x}] :
fintype.card {x // p x ∨ q x} ≤ fintype.card {x // p x} + fintype.card {x // q x} :=
begin
classical,
convert fintype.card_le_of_embedding (subtype_or_left_embedding p q),
rw fintype.card_sum
end
lemma fintype.card_subtype_or_disjoint (p q : α → Prop) (h : disjoint p q)
[fintype {x // p x}] [fintype {x // q x}] [fintype {x // p x ∨ q x}] :
fintype.card {x // p x ∨ q x} = fintype.card {x // p x} + fintype.card {x // q x} :=
begin
classical,
convert fintype.card_congr (subtype_or_equiv p q h),
simp
end
theorem fintype.card_quotient_le [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] :
fintype.card (quotient s) ≤ fintype.card α :=
fintype.card_le_of_surjective _ (surjective_quotient_mk _)
theorem fintype.card_quotient_lt [fintype α] {s : setoid α} [decidable_rel ((≈) : α → α → Prop)]
{x y : α} (h1 : x ≠ y) (h2 : x ≈ y) : fintype.card (quotient s) < fintype.card α :=
fintype.card_lt_of_surjective_not_injective _ (surjective_quotient_mk _) $ λ w,
h1 (w $ quotient.eq.mpr h2)
instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] :
fintype (Σ' a, β a) :=
fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm
instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] :
fintype (Σ' a, β a) :=
if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩
else ⟨∅, λ x, h x.1⟩
instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] :
fintype (Σ' a, β a) :=
fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩
instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] :
fintype (Σ' a, β a) :=
if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩
instance set.fintype [fintype α] : fintype (set α) :=
⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin
classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩,
apply (coe_filter _ _).trans, rw [coe_univ, set.sep_univ], refl
end⟩
@[simp] lemma fintype.card_set [fintype α] : fintype.card (set α) = 2 ^ fintype.card α :=
(finset.card_map _).trans (finset.card_powerset _)
instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*)
[Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) :=
if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩
else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩
@[simp] lemma finset.univ_pi_univ {α : Type*} {β : α → Type*}
[decidable_eq α] [fintype α] [∀ a, fintype (β a)] :
finset.univ.pi (λ a : α, (finset.univ : finset (β a))) = finset.univ :=
by { ext, simp }
lemma mem_image_univ_iff_mem_range
{α β : Type*} [fintype α] [decidable_eq β] {f : α → β} {b : β} :
b ∈ univ.image f ↔ b ∈ set.range f :=
by simp
/-- An auxiliary function for `quotient.fin_choice`. Given a
collection of setoids indexed by a type `ι`, a (finite) list `l` of
indices, and a function that for each `i ∈ l` gives a term of the
corresponding quotient type, then there is a corresponding term in the
quotient of the product of the setoids indexed by `l`. -/
def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
Π (l : list ι), (Π i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance)
| [] f := ⟦λ i, false.elim⟧
| (i :: l) f := begin
refine quotient.lift_on₂ (f i (list.mem_cons_self _ _))
(quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h)))
_ _,
exact λ a l, ⟦λ j h,
if e : j = i then by rw e; exact a else
l _ (h.resolve_left e)⟧,
refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
{ subst j, exact h₁ },
{ exact h₂ _ _ }
end
theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
∀ (l : list ι) (f : Π i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧
| [] f := quotient.sound (λ i h, h.elim)
| (i :: l) f := begin
simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l],
refine quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
subst j, refl
end
/-- Given a collection of setoids indexed by a fintype `ι` and a
function that for each `i : ι` gives a term of the corresponding
quotient type, then there is corresponding term in the quotient of the
product of the setoids. -/
def quotient.fin_choice {ι : Type*} [decidable_eq ι] [fintype ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)]
(f : Π i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) :=
quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι,
@quotient (Π i ∈ l, α i) (by apply_instance))
finset.univ.1
(λ l, quotient.fin_choice_aux l (λ i _, f i))
(λ a b h, begin
have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)),
simp [quotient.out_eq] at this,
simp [this],
let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧,
refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)),
congr' 1, exact quotient.sound h,
end))
(λ f, ⟦λ i, f i (finset.mem_univ _)⟧)
(λ a b h, quotient.sound $ λ i, h _ _)
theorem quotient.fin_choice_eq {ι : Type*} [decidable_eq ι] [fintype ι]
{α : ι → Type*} [∀ i, setoid (α i)]
(f : Π i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ :=
begin
let q, swap, change quotient.lift_on q _ _ = _,
have : q = ⟦λ i h, f i⟧,
{ dsimp [q],
exact quotient.induction_on
(@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) },
simp [this], exact setoid.refl _
end
section equiv
open list equiv equiv.perm
variables [decidable_eq α] [decidable_eq β]
/-- Given a list, produce a list of all permutations of its elements. -/
def perms_of_list : list α → list (perm α)
| [] := [1]
| (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f))
lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length!
| [] := rfl
| (a :: l) :=
begin
rw [length_cons, nat.factorial_succ],
simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul],
cc
end
lemma mem_perms_of_list_of_mem {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l) :
f ∈ perms_of_list l :=
begin
induction l with a l IH generalizing f h,
{ exact list.mem_singleton.2 (equiv.ext $ λ x, decidable.by_contradiction $ h _) },
by_cases hfa : f a = a,
{ refine mem_append_left _ (IH (λ x hx, mem_of_ne_of_mem _ (h x hx))),
rintro rfl, exact hx hfa },
have hfa' : f (f a) ≠ f a := mt (λ h, f.injective h) hfa,
have : ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l,
{ intros x hx,
have hxa : x ≠ a,
{ rintro rfl, apply hx, simp only [mul_apply, swap_apply_right] },
refine list.mem_of_ne_of_mem hxa (h x (λ h, _)),
simp only [h, mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq] at hx;
split_ifs at hx, exacts [hxa (h.symm.trans h_1), hx h] },
suffices : f ∈ perms_of_list l ∨ ∃ (b ∈ l) (g ∈ perms_of_list l), swap a b * g = f,
{ simpa only [perms_of_list, exists_prop, list.mem_map, mem_append, list.mem_bind] },
refine or_iff_not_imp_left.2 (λ hfl, ⟨f a, _, swap a (f a) * f, IH this, _⟩),
{ exact mem_of_ne_of_mem hfa (h _ hfa') },
{ rw [←mul_assoc, mul_def (swap a (f a)) (swap a (f a)),
swap_swap, ←perm.one_def, one_mul] }
end
lemma mem_of_mem_perms_of_list :
∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l
| [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp
| (a :: l) f h :=
(mem_append.1 h).elim
(λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx))
(λ h x hx,
let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in
let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in
if hxa : x = a then by simp [hxa]
else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy
else mem_cons_of_mem _ $
mem_of_mem_perms_of_list hg₁ $
by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def];
split_ifs; [exact ne.symm hxy, exact ne.symm hxa, exact hx])
lemma mem_perms_of_list_iff {l : list α} {f : perm α} :
f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l :=
⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩
lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup
| [] hl := by simp [perms_of_list]
| (a :: l) hl :=
have hl' : l.nodup, from hl.of_cons,
have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl',
have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a,
from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1),
by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact
⟨hln', ⟨λ _ _, hln'.map $ λ _ _, mul_left_cancel,
λ i j hj hij x hx₁ hx₂,
let ⟨f, hf⟩ := list.mem_map.1 hx₁ in
let ⟨g, hg⟩ := list.mem_map.1 hx₂ in
have hix : x a = nth_le l i (lt_trans hij hj),
by rw [←hf.2, mul_apply, hmeml hf.1, swap_apply_left],
have hiy : x a = nth_le l j hj,
by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left],
absurd (hf.2.trans (hg.2.symm)) $
λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $
by rw [← hix, hiy]⟩,
λ f hf₁ hf₂,
let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in
let ⟨g, hg⟩ := list.mem_map.1 hx' in
have hgxa : g⁻¹ x = a, from f.injective $
by rw [hmeml hf₁, ← hg.2]; simp,
have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx),
(list.nodup_cons.1 hl).1 $
hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩
/-- Given a finset, produce the finset of all permutations of its elements. -/
def perms_of_finset (s : finset α) : finset (perm α) :=
quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩)
(λ a b hab, hfunext (congr_arg _ (quotient.sound hab))
(λ ha hb _, heq_of_eq $ finset.ext $
by simp [mem_perms_of_list_iff, hab.mem_iff]))
s.2
lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α},
f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s :=
by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff
lemma card_perms_of_finset : ∀ (s : finset α),
(perms_of_finset s).card = s.card! :=
by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l
/-- The collection of permutations of a fintype is a fintype. -/
def fintype_perm [fintype α] : fintype (perm α) :=
⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩
instance [fintype α] [fintype β] : fintype (α ≃ β) :=
if h : fintype.card β = fintype.card α
then trunc.rec_on_subsingleton (fintype.trunc_equiv_fin α)
(λ eα, trunc.rec_on_subsingleton (fintype.trunc_equiv_fin β)
(λ eβ, @fintype.of_equiv _ (perm α) fintype_perm
(equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β))))
else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩
lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α)! :=
subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸
card_perms_of_finset _
lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) :
fintype.card (α ≃ β) = (fintype.card α)! :=
fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm
lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) :
(univ : finset α) = {x} :=
begin
symmetry,
apply eq_of_subset_of_card_le (subset_univ ({x})),
apply le_of_eq,
simp [h, finset.card_univ]
end
end equiv
namespace fintype
section choose
open fintype equiv
variables [fintype α] (p : α → Prop) [decidable_pred p]
/-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of
`α` satisfying `p` this unique element, as an element of the corresponding subtype. -/
def choose_x (hp : ∃! a : α, p a) : {a // p a} :=
⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩
/-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of
`α` satisfying `p` this unique element, as an element of `α`. -/
def choose (hp : ∃! a, p a) : α := choose_x p hp
lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) :=
(choose_x p hp).property
@[simp] lemma choose_subtype_eq {α : Type*} (p : α → Prop) [fintype {a : α // p a}]
[decidable_eq α] (x : {a : α // p a})
(h : ∃! (a : {a // p a}), (a : α) = x := ⟨x, rfl, λ y hy, by simpa [subtype.ext_iff] using hy⟩) :
fintype.choose (λ (y : {a : α // p a}), (y : α) = x) h = x :=
by rw [subtype.ext_iff, fintype.choose_spec (λ (y : {a : α // p a}), (y : α) = x) _]
end choose
section bijection_inverse
open function
variables [fintype α] [decidable_eq β] {f : α → β}
/--
`bij_inv f` is the unique inverse to a bijection `f`. This acts
as a computable alternative to `function.inv_fun`. -/
def bij_inv (f_bij : bijective f) (b : β) : α :=
fintype.choose (λ a, f a = b)
begin
rcases f_bij.right b with ⟨a', fa_eq_b⟩,
rw ← fa_eq_b,
exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩
end
lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f :=
λ a, f_bij.left (choose_spec (λ a', f a' = f a) _)
lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f :=
λ b, choose_spec (λ a', f a' = b) _
lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) :=
⟨(right_inverse_bij_inv _).injective, (left_inverse_bij_inv _).surjective⟩
end bijection_inverse
lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop)
[is_trans α r] [is_irrefl α r] : well_founded r :=
by classical; exact
have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card,
from λ x y hxy, finset.card_lt_card $
by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le,
finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy];
exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩,
subrelation.wf this (measure_wf _)
lemma preorder.well_founded_lt [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) :=
well_founded_of_trans_of_irrefl _
lemma preorder.well_founded_gt [fintype α] [preorder α] : well_founded ((>) : α → α → Prop) :=
well_founded_of_trans_of_irrefl _
@[instance, priority 10] lemma linear_order.is_well_order_lt [fintype α] [linear_order α] :
is_well_order α (<) :=
{ wf := preorder.well_founded_lt }
@[instance, priority 10] lemma linear_order.is_well_order_gt [fintype α] [linear_order α] :
is_well_order α (>) :=
{ wf := preorder.well_founded_gt }
end fintype
/-- A type is said to be infinite if it has no fintype instance.
Note that `infinite α` is equivalent to `is_empty (fintype α)`. -/
class infinite (α : Type*) : Prop :=
(not_fintype : fintype α → false)
lemma not_fintype (α : Type*) [h1 : infinite α] [h2 : fintype α] : false :=
infinite.not_fintype h2
protected lemma fintype.false {α : Type*} [infinite α] (h : fintype α) : false :=
not_fintype α
protected lemma infinite.false {α : Type*} [fintype α] (h : infinite α) : false :=
not_fintype α
@[simp] lemma is_empty_fintype {α : Type*} : is_empty (fintype α) ↔ infinite α :=
⟨λ ⟨x⟩, ⟨x⟩, λ ⟨x⟩, ⟨x⟩⟩
/-- A non-infinite type is a fintype. -/
noncomputable def fintype_of_not_infinite {α : Type*} (h : ¬ infinite α) : fintype α :=
nonempty.some $ by rwa [← not_is_empty_iff, is_empty_fintype]
section
open_locale classical
/--
Any type is (classically) either a `fintype`, or `infinite`.
One can obtain the relevant typeclasses via `cases fintype_or_infinite α; resetI`.
-/
noncomputable def fintype_or_infinite (α : Type*) : psum (fintype α) (infinite α) :=
if h : infinite α then psum.inr h else psum.inl (fintype_of_not_infinite h)
end
lemma finset.exists_minimal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) :
∃ m ∈ s, ∀ x ∈ s, ¬ (x < m) :=
begin
obtain ⟨c, hcs : c ∈ s⟩ := h,
have : well_founded (@has_lt.lt {x // x ∈ s} _) := fintype.well_founded_of_trans_of_irrefl _,
obtain ⟨⟨m, hms : m ∈ s⟩, -, H⟩ := this.has_min set.univ ⟨⟨c, hcs⟩, trivial⟩,
exact ⟨m, hms, λ x hx hxm, H ⟨x, hx⟩ trivial hxm⟩,
end
lemma finset.exists_maximal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) :
∃ m ∈ s, ∀ x ∈ s, ¬ (m < x) :=
@finset.exists_minimal αᵒᵈ _ s h
namespace infinite
lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s :=
not_forall.1 $ λ h, fintype.false ⟨s, h⟩
@[priority 100] -- see Note [lower instance priority]
instance (α : Type*) [H : infinite α] : nontrivial α :=
⟨let ⟨x, hx⟩ := exists_not_mem_finset (∅ : finset α) in
let ⟨y, hy⟩ := exists_not_mem_finset ({x} : finset α) in
⟨y, x, by simpa only [mem_singleton] using hy⟩⟩
protected lemma nonempty (α : Type*) [infinite α] : nonempty α :=
by apply_instance
lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α :=
⟨λ I, by exactI (fintype.of_injective f hf).false⟩
lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α :=
⟨λ I, by { classical, exactI (fintype.of_surjective f hf).false }⟩
end infinite
instance : infinite ℕ :=
⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩
instance : infinite ℤ :=
infinite.of_injective int.of_nat (λ _ _, int.of_nat.inj)
instance infinite.set [infinite α] : infinite (set α) :=
infinite.of_injective singleton (λ a b, set.singleton_eq_singleton_iff.1)
instance [infinite α] : infinite (finset α) :=
infinite.of_injective singleton finset.singleton_injective
instance [nonempty α] : infinite (multiset α) :=
begin
inhabit α,
exact infinite.of_injective (multiset.repeat default) (multiset.repeat_injective _),
end
instance [nonempty α] : infinite (list α) :=
infinite.of_surjective (coe : list α → multiset α) (surjective_quot_mk _)
instance [infinite α] : infinite (option α) :=
infinite.of_injective some (option.some_injective α)
instance sum.infinite_of_left [infinite α] : infinite (α ⊕ β) :=
infinite.of_injective sum.inl sum.inl_injective
instance sum.infinite_of_right [infinite β] : infinite (α ⊕ β) :=
infinite.of_injective sum.inr sum.inr_injective
@[simp] lemma infinite_sum : infinite (α ⊕ β) ↔ infinite α ∨ infinite β :=
begin
refine ⟨λ H, _, λ H, H.elim (@sum.infinite_of_left α β) (@sum.infinite_of_right α β)⟩,
contrapose! H, haveI := fintype_of_not_infinite H.1, haveI := fintype_of_not_infinite H.2,
exact infinite.false
end
instance prod.infinite_of_right [nonempty α] [infinite β] : infinite (α × β) :=
infinite.of_surjective prod.snd prod.snd_surjective
instance prod.infinite_of_left [infinite α] [nonempty β] : infinite (α × β) :=
infinite.of_surjective prod.fst prod.fst_surjective
@[simp] lemma infinite_prod :
infinite (α × β) ↔ infinite α ∧ nonempty β ∨ nonempty α ∧ infinite β :=
begin
refine ⟨λ H, _, λ H, H.elim (and_imp.2 $ @prod.infinite_of_left α β)
(and_imp.2 $ @prod.infinite_of_right α β)⟩,
rw and.comm, contrapose! H, introI H',
rcases infinite.nonempty (α × β) with ⟨a, b⟩,
haveI := fintype_of_not_infinite (H.1 ⟨b⟩), haveI := fintype_of_not_infinite (H.2 ⟨a⟩),
exact H'.false
end
namespace infinite
private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α
| n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset
((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m)
(λ _, multiset.mem_range.1)).to_finset)
private lemma nat_embedding_aux_injective (α : Type*) [infinite α] :
function.injective (nat_embedding_aux α) :=
begin
rintro m n h,
letI := classical.dec_eq α,
wlog hmlen : m ≤ n using m n,
by_contradiction hmn,
have hmn : m < n, from lt_of_le_of_ne hmlen hmn,
refine (classical.some_spec (exists_not_mem_finset
((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m)
(λ _, multiset.mem_range.1)).to_finset)) _,
refine multiset.mem_to_finset.2 (multiset.mem_pmap.2
⟨m, multiset.mem_range.2 hmn, _⟩),
rw [h, nat_embedding_aux]
end
/-- Embedding of `ℕ` into an infinite type. -/
noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α :=
⟨_, nat_embedding_aux_injective α⟩
lemma exists_subset_card_eq (α : Type*) [infinite α] (n : ℕ) :
∃ s : finset α, s.card = n :=
⟨(range n).map (nat_embedding α), by rw [card_map, card_range]⟩
end infinite
/-- If every finset in a type has bounded cardinality, that type is finite. -/
noncomputable def fintype_of_finset_card_le {ι : Type*} (n : ℕ)
(w : ∀ s : finset ι, s.card ≤ n) : fintype ι :=
begin
apply fintype_of_not_infinite,
introI i,
obtain ⟨s, c⟩ := infinite.exists_subset_card_eq ι (n+1),
specialize w s,
rw c at w,
exact nat.not_succ_le_self n w,
end
lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) :
¬ injective f :=
λ hf, (fintype.of_injective f hf).false
/--
The pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are
infinitely many pigeons in finitely many pigeonholes, then there are at least two pigeons in the
same pigeonhole.
See also: `fintype.exists_ne_map_eq_of_card_lt`, `fintype.exists_infinite_fiber`.
-/
lemma fintype.exists_ne_map_eq_of_infinite [infinite α] [fintype β] (f : α → β) :
∃ x y : α, x ≠ y ∧ f x = f y :=
begin
classical, by_contra' hf,
apply not_injective_infinite_fintype f,
intros x y, contrapose, apply hf,
end
-- irreducible due to this conversation on Zulip:
-- https://leanprover.zulipchat.com/#narrow/stream/113488-general/
-- topic/.60simp.60.20ignoring.20lemmas.3F/near/241824115
@[irreducible]
instance function.embedding.is_empty {α β} [infinite α] [fintype β] : is_empty (α ↪ β) :=
⟨λ f, let ⟨x, y, ne, feq⟩ := fintype.exists_ne_map_eq_of_infinite f in ne $ f.injective feq⟩
@[priority 100]
noncomputable instance function.embedding.fintype' {α β : Type*} [fintype β] : fintype (α ↪ β) :=
begin
by_cases h : infinite α,
{ resetI, apply_instance },
{ have := fintype_of_not_infinite h, classical, apply_instance }
-- the `classical` generates `decidable_eq α/β` instances, and resets instance cache
end
/--
The strong pigeonhole principle for infinitely many pigeons in
finitely many pigeonholes. If there are infinitely many pigeons in
finitely many pigeonholes, then there is a pigeonhole with infinitely
many pigeons.
See also: `fintype.exists_ne_map_eq_of_infinite`
-/
lemma fintype.exists_infinite_fiber [infinite α] [fintype β] (f : α → β) :
∃ y : β, infinite (f ⁻¹' {y}) :=
begin
classical,
by_contra' hf,
haveI := λ y, fintype_of_not_infinite $ hf y,
let key : fintype α :=
{ elems := univ.bUnion (λ (y : β), (f ⁻¹' {y}).to_finset),
complete := by simp },
exact key.false,
end
lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) :
¬ surjective f :=
assume (hf : surjective f),
have H : infinite α := infinite.of_surjective f hf,
by exactI not_fintype α
section trunc
/--
For `s : multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `trunc α`.
-/
def trunc_of_multiset_exists_mem {α} (s : multiset α) : (∃ x, x ∈ s) → trunc α :=
quotient.rec_on_subsingleton s $ λ l h,
match l, h with
| [], _ := false.elim (by tauto)
| (a :: _), _ := trunc.mk a
end
/--
A `nonempty` `fintype` constructively contains an element.
-/
def trunc_of_nonempty_fintype (α) [nonempty α] [fintype α] : trunc α :=
trunc_of_multiset_exists_mem finset.univ.val (by simp)
/--
A `fintype` with positive cardinality constructively contains an element.
-/
def trunc_of_card_pos {α} [fintype α] (h : 0 < fintype.card α) : trunc α :=
by { letI := (fintype.card_pos_iff.mp h), exact trunc_of_nonempty_fintype α }
/--
By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a`
to `trunc (Σ' a, P a)`, containing data.
-/
def trunc_sigma_of_exists {α} [fintype α] {P : α → Prop} [decidable_pred P] (h : ∃ a, P a) :
trunc (Σ' a, P a) :=
@trunc_of_nonempty_fintype (Σ' a, P a) (exists.elim h $ λ a ha, ⟨⟨a, ha⟩⟩) _
end trunc
namespace multiset
variables [fintype α] [decidable_eq α]
@[simp] lemma count_univ (a : α) :
count a finset.univ.val = 1 :=
count_eq_one_of_mem finset.univ.nodup (finset.mem_univ _)
end multiset
namespace fintype
/-- A recursor principle for finite types, analogous to `nat.rec`. It effectively says
that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/
def trunc_rec_empty_option {P : Type u → Sort v}
(of_equiv : ∀ {α β}, α ≃ β → P α → P β)
(h_empty : P pempty)
(h_option : ∀ {α} [fintype α] [decidable_eq α], P α → P (option α))
(α : Type u) [fintype α] [decidable_eq α] : trunc (P α) :=
begin
suffices : ∀ n : ℕ, trunc (P (ulift $ fin n)),
{ apply trunc.bind (this (fintype.card α)),
intro h,
apply trunc.map _ (fintype.trunc_equiv_fin α),
intro e,
exact of_equiv (equiv.ulift.trans e.symm) h },
intro n,
induction n with n ih,
{ have : card pempty = card (ulift (fin 0)),
{ simp only [card_fin, card_pempty, card_ulift] },
apply trunc.bind (trunc_equiv_of_card_eq this),
intro e,
apply trunc.mk,
refine of_equiv e h_empty, },
{ have : card (option (ulift (fin n))) = card (ulift (fin n.succ)),
{ simp only [card_fin, card_option, card_ulift] },
apply trunc.bind (trunc_equiv_of_card_eq this),
intro e,
apply trunc.map _ ih,
intro ih,
refine of_equiv e (h_option ih), },
end
/-- An induction principle for finite types, analogous to `nat.rec`. It effectively says
that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/
@[elab_as_eliminator]
lemma induction_empty_option' {P : Π (α : Type u) [fintype α], Prop}
(of_equiv : ∀ α β [fintype β] (e : α ≃ β), @P α (@fintype.of_equiv α β ‹_› e.symm) → @P β ‹_›)
(h_empty : P pempty)
(h_option : ∀ α [fintype α], by exactI P α → P (option α))
(α : Type u) [fintype α] : P α :=
begin
obtain ⟨p⟩ := @trunc_rec_empty_option (λ α, ∀ h, @P α h)
(λ α β e hα hβ, @of_equiv α β hβ e (hα _)) (λ _i, by convert h_empty)
_ α _ (classical.dec_eq α),
{ exact p _ },
{ rintro α hα - Pα hα', resetI, convert h_option α (Pα _) }
end
/-- An induction principle for finite types, analogous to `nat.rec`. It effectively says
that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/
lemma induction_empty_option {P : Type u → Prop}
(of_equiv : ∀ {α β}, α ≃ β → P α → P β)
(h_empty : P pempty)
(h_option : ∀ {α} [fintype α], P α → P (option α))
(α : Type u) [fintype α] : P α :=
begin
refine induction_empty_option' _ _ _ α,
exacts [λ α β _, of_equiv, h_empty, @h_option]
end
end fintype
/-- Auxiliary definition to show `exists_seq_of_forall_finset_exists`. -/
noncomputable def seq_of_forall_finset_exists_aux
{α : Type*} [decidable_eq α] (P : α → Prop) (r : α → α → Prop)
(h : ∀ (s : finset α), ∃ y, (∀ x ∈ s, P x) → (P y ∧ (∀ x ∈ s, r x y))) : ℕ → α
| n := classical.some (h (finset.image (λ (i : fin n), seq_of_forall_finset_exists_aux i)
(finset.univ : finset (fin n))))
using_well_founded {dec_tac := `[exact i.2]}
/-- Induction principle to build a sequence, by adding one point at a time satisfying a given
relation with respect to all the previously chosen points.
More precisely, Assume that, for any finite set `s`, one can find another point satisfying
some relation `r` with respect to all the points in `s`. Then one may construct a
function `f : ℕ → α` such that `r (f m) (f n)` holds whenever `m < n`.
We also ensure that all constructed points satisfy a given predicate `P`. -/
lemma exists_seq_of_forall_finset_exists {α : Type*} (P : α → Prop) (r : α → α → Prop)
(h : ∀ (s : finset α), (∀ x ∈ s, P x) → ∃ y, P y ∧ (∀ x ∈ s, r x y)) :
∃ (f : ℕ → α), (∀ n, P (f n)) ∧ (∀ m n, m < n → r (f m) (f n)) :=
begin
classical,
haveI : nonempty α,
{ rcases h ∅ (by simp) with ⟨y, hy⟩,
exact ⟨y⟩ },
choose! F hF using h,
have h' : ∀ (s : finset α), ∃ y, (∀ x ∈ s, P x) → (P y ∧ (∀ x ∈ s, r x y)) := λ s, ⟨F s, hF s⟩,
set f := seq_of_forall_finset_exists_aux P r h' with hf,
have A : ∀ (n : ℕ), P (f n),
{ assume n,
induction n using nat.strong_induction_on with n IH,
have IH' : ∀ (x : fin n), P (f x) := λ n, IH n.1 n.2,
rw [hf, seq_of_forall_finset_exists_aux],
exact (classical.some_spec (h' (finset.image (λ (i : fin n), f i)
(finset.univ : finset (fin n)))) (by simp [IH'])).1 },
refine ⟨f, A, λ m n hmn, _⟩,
nth_rewrite 1 hf,
rw seq_of_forall_finset_exists_aux,
apply (classical.some_spec (h' (finset.image (λ (i : fin n), f i)
(finset.univ : finset (fin n)))) (by simp [A])).2,
exact finset.mem_image.2 ⟨⟨m, hmn⟩, finset.mem_univ _, rfl⟩,
end
/-- Induction principle to build a sequence, by adding one point at a time satisfying a given
symmetric relation with respect to all the previously chosen points.
More precisely, Assume that, for any finite set `s`, one can find another point satisfying
some relation `r` with respect to all the points in `s`. Then one may construct a
function `f : ℕ → α` such that `r (f m) (f n)` holds whenever `m ≠ n`.
We also ensure that all constructed points satisfy a given predicate `P`. -/
lemma exists_seq_of_forall_finset_exists' {α : Type*} (P : α → Prop) (r : α → α → Prop)
[is_symm α r]
(h : ∀ (s : finset α), (∀ x ∈ s, P x) → ∃ y, P y ∧ (∀ x ∈ s, r x y)) :
∃ (f : ℕ → α), (∀ n, P (f n)) ∧ (∀ m n, m ≠ n → r (f m) (f n)) :=
begin
rcases exists_seq_of_forall_finset_exists P r h with ⟨f, hf, hf'⟩,
refine ⟨f, hf, λ m n hmn, _⟩,
rcases lt_trichotomy m n with h|rfl|h,
{ exact hf' m n h },
{ exact (hmn rfl).elim },
{ apply symm,
exact hf' n m h }
end
/-- A custom induction principle for fintypes. The base case is a subsingleton type,
and the induction step is for non-trivial types, and one can assume the hypothesis for
smaller types (via `fintype.card`).
The major premise is `fintype α`, so to use this with the `induction` tactic you have to give a name
to that instance and use that name.
-/
@[elab_as_eliminator]
lemma fintype.induction_subsingleton_or_nontrivial
{P : Π α [fintype α], Prop} (α : Type*) [fintype α]
(hbase : ∀ α [fintype α] [subsingleton α], by exactI P α)
(hstep : ∀ α [fintype α] [nontrivial α],
by exactI ∀ (ih : ∀ β [fintype β], by exactI ∀ (h : fintype.card β < fintype.card α), P β),
P α) :
P α :=
begin
obtain ⟨ n, hn ⟩ : ∃ n, fintype.card α = n := ⟨fintype.card α, rfl⟩,
unfreezingI { induction n using nat.strong_induction_on with n ih generalizing α },
casesI (subsingleton_or_nontrivial α) with hsing hnontriv,
{ apply hbase, },
{ apply hstep,
introsI β _ hlt,
rw hn at hlt,
exact (ih (fintype.card β) hlt _ rfl), }
end
|
ddf2919895c63f12c2bb345d056c637d86975730 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/algebra/char_p.lean | 342390dd09494831a8e72e567f830f96ce52ed65 | [
"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 | 8,677 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Kenny Lau, Joey van Langen, Casper Putz
Characteristic of semirings.
-/
import data.padics.padic_norm data.nat.choose data.fintype
import data.zmod.basic algebra.module
universes u v
/-- The generator of the kernel of the unique homomorphism ℕ → α for a semiring α -/
class char_p (α : Type u) [semiring α] (p : ℕ) : Prop :=
(cast_eq_zero_iff : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x)
theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 :=
(char_p.cast_eq_zero_iff α p p).2 (dvd_refl p)
theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q :=
nat.dvd_antisymm
((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _))
((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _))
instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 :=
⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩
theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p :=
by letI := classical.dec_eq α; exact
classical.by_cases
(assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0,
⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩)
(λ H, ⟨nat.find (classical.not_forall.1 H), ⟨λ x,
⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2,
nat.find_min (classical.not_forall.1 H)
(nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $
nat.find_spec (classical.not_forall.1 H))
(not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (classical.not_forall.1 H)),
nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)),
zero_mul, add_zero] at H1, H2⟩)),
λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul,
of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul]⟩⟩⟩)
theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p :=
let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩
/-- Noncomuptable function that outputs the unique characteristic of a semiring. -/
noncomputable def ring_char (α : Type u) [semiring α] : ℕ :=
classical.some (char_p.exists_unique α)
theorem ring_char.spec (α : Type u) [semiring α] : ∀ x:ℕ, (x:α) = 0 ↔ ring_char α ∣ x :=
by letI := (classical.some_spec (char_p.exists_unique α)).1;
unfold ring_char; exact char_p.cast_eq_zero_iff α (ring_char α)
theorem ring_char.eq (α : Type u) [semiring α] {p : ℕ} (C : char_p α p) : p = ring_char α :=
(classical.some_spec (char_p.exists_unique α)).2 p C
theorem add_pow_char (α : Type u) [comm_ring α] {p : ℕ} (hp : nat.prime p)
[char_p α p] (x y : α) : (x + y)^p = x^p + y^p :=
begin
rw [add_pow, finset.sum_range_succ, nat.sub_self, pow_zero, nat.choose_self],
rw [nat.cast_one, mul_one, mul_one, add_left_inj],
transitivity,
{ refine finset.sum_eq_single 0 _ _,
{ intros b h1 h2,
have := nat.prime.dvd_choose (nat.pos_of_ne_zero h2) (finset.mem_range.1 h1) hp,
rw [← nat.div_mul_cancel this, nat.cast_mul, char_p.cast_eq_zero α p],
simp only [mul_zero] },
{ intro H, exfalso, apply H, exact finset.mem_range.2 hp.pos } },
rw [pow_zero, nat.sub_zero, one_mul, nat.choose_zero_right, nat.cast_one, mul_one]
end
/-- The frobenius map that sends x to x^p -/
def frobenius (α : Type u) [monoid α] (p : ℕ) (x : α) : α := x^p
theorem frobenius_def (α : Type u) [monoid α] (p : ℕ) (x : α) : frobenius α p x = x ^ p := rfl
theorem frobenius_mul (α : Type u) [comm_monoid α] (p : ℕ) (x y : α) :
frobenius α p (x * y) = frobenius α p x * frobenius α p y := mul_pow x y p
theorem frobenius_one (α : Type u) [monoid α] (p : ℕ) :
frobenius α p 1 = 1 := one_pow _
theorem is_monoid_hom.map_frobenius {α : Type u} {β : Type v} [monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
(p : ℕ) (x : α) : f (frobenius α p x) = frobenius β p (f x) :=
by unfold frobenius; induction p; simp only [pow_zero, pow_succ,
is_monoid_hom.map_one f, is_monoid_hom.map_mul f, *]
instance {α : Type u} [comm_ring α] (p : ℕ) [hp : nat.prime p] [char_p α p] : is_ring_hom (frobenius α p) :=
{ map_one := frobenius_one α p,
map_mul := frobenius_mul α p,
map_add := add_pow_char α hp }
section
variables (α : Type u) [comm_ring α] (p : ℕ) [hp : nat.prime p]
theorem frobenius_zero : frobenius α p 0 = 0 := zero_pow hp.pos
variables [char_p α p] (x y : α)
include hp
theorem frobenius_add : frobenius α p (x + y) = frobenius α p x + frobenius α p y := is_ring_hom.map_add _
theorem frobenius_neg : frobenius α p (-x) = -frobenius α p x := is_ring_hom.map_neg _
theorem frobenius_sub : frobenius α p (x - y) = frobenius α p x - frobenius α p y := is_ring_hom.map_sub _
end
theorem frobenius_inj (α : Type u) [integral_domain α] (p : ℕ) [nat.prime p] [char_p α p] (x y : α)
(H : frobenius α p x = frobenius α p y) : x = y :=
by rw ← sub_eq_zero at H ⊢; rw ← frobenius_sub at H; exact pow_eq_zero H
theorem frobenius_nat_cast (α : Type u) [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x : ℕ) :
frobenius α p x = x :=
by induction x; simp only [nat.cast_zero, nat.cast_succ, frobenius_zero, frobenius_one, frobenius_add, *]
namespace char_p
section
variables (α : Type u) [ring α]
lemma char_p_to_char_zero [char_p α 0] : char_zero α :=
add_group.char_zero_of_inj_zero $
λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff α 0 n).mp h0)
lemma cast_eq_mod (p : ℕ) [char_p α p] (k : ℕ) : (k : α) = (k % p : ℕ) :=
calc (k : α) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div]
... = ↑(k % p) : by simp[cast_eq_zero]
theorem char_ne_zero_of_fintype (p : ℕ) [hc : char_p α p] [fintype α] : p ≠ 0 :=
assume h : p = 0,
have char_zero α := @char_p_to_char_zero α _ (h ▸ hc),
absurd (@nat.cast_injective α _ _ this) (@set.not_injective_nat_fintype α _ _)
end
section integral_domain
open nat
variables (α : Type u) [integral_domain α]
theorem char_ne_one (p : ℕ) [hc : char_p α p] : p ≠ 1 :=
assume hp : p = 1,
have ( 1 : α) = 0, by simpa using (cast_eq_zero_iff α p 1).mpr (hp ▸ dvd_refl p),
absurd this one_ne_zero
theorem char_is_prime_of_ge_two (p : ℕ) [hc : char_p α p] (hp : p ≥ 2) : nat.prime p :=
suffices ∀d ∣ p, d = 1 ∨ d = p, from ⟨hp, this⟩,
assume (d : ℕ) (hdvd : ∃ e, p = d * e),
let ⟨e, hmul⟩ := hdvd in
have (p : α) = 0, from (cast_eq_zero_iff α p p).mpr (dvd_refl p),
have (d : α) * e = 0, from (@cast_mul α _ d e) ▸ (hmul ▸ this),
or.elim (no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero (d : α) e this)
(assume hd : (d : α) = 0,
have p ∣ d, from (cast_eq_zero_iff α p d).mp hd,
show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this))
(assume he : (e : α) = 0,
have p ∣ e, from (cast_eq_zero_iff α p e).mp he,
have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul),
have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›,
have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1),
have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul,
show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this))
theorem char_is_prime_or_zero (p : ℕ) [hc : char_p α p] : nat.prime p ∨ p = 0 :=
match p, hc with
| 0, _ := or.inr rfl
| 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one α _ (1 : ℕ) hc)
| (m+2), hc := or.inl (@char_is_prime_of_ge_two α _ (m+2) hc (nat.le_add_left 2 m))
end
theorem char_is_prime [fintype α] (p : ℕ) [char_p α p] : nat.prime p :=
or.resolve_right (char_is_prime_or_zero α p) (char_ne_zero_of_fintype α p)
end integral_domain
end char_p
namespace zmod
variables {α : Type u} [ring α] {n : ℕ+}
instance cast_is_ring_hom [char_p α n] : is_ring_hom (cast : zmod n → α) :=
{ map_one := by rw ←@nat.cast_one α _ _; exact eq.symm (char_p.cast_eq_mod α n 1),
map_mul := assume x y : zmod n, show ↑((x * y).val) = ↑(x.val) * ↑(y.val),
by rw [zmod.mul_val, ←char_p.cast_eq_mod, nat.cast_mul],
map_add := assume x y : zmod n, show ↑((x + y).val) = ↑(x.val) + ↑(y.val),
by rw [zmod.add_val, ←char_p.cast_eq_mod, nat.cast_add] }
instance to_module [char_p α n] : module (zmod n) α := is_ring_hom.to_module cast
instance to_module' {m : ℕ} {hm : m > 0} [hc : char_p α m] : module (zmod ⟨m, hm⟩) α :=
@zmod.to_module α _ ⟨m, hm⟩ hc
end zmod
|
f39e81d856d881d599faf85f3cc607c396623ede | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/pempty_instances.lean | bacafd4d32d1e0c1d2b1f6c2b47ea1c509ba391f | [
"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 | 495 | lean | /-
Copyright (c) 2021 Julian Kuelshammer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Julian Kuelshammer
-/
import algebra.module.basic
/-!
# Instances on pempty
This file collects facts about algebraic structures on the (universe-polymorphic) empty type, e.g.
that it is a semigroup.
-/
universes u
@[to_additive]
instance semigroup_pempty : semigroup pempty.{u+1} :=
{ mul := λ x y, by cases x,
mul_assoc := λ x y z, by cases x }
|
351a51ed6547709225b1a305d54e96d400f80e1b | 38193807b9085b93599c814229d2b0dacb64ba22 | /benchmarks/diverge/Diverge.lean | 4cc495208bd42157227d3053a5400b974a88f65f | [] | no_license | zgrannan/rest-old | d650363e403a9d5322fb44ee892b743aec558e1b | 6a6974641b25259cb8701af4302169db22b33b6b | refs/heads/master | 1,670,816,037,466 | 1,599,571,928,000 | 1,599,571,928,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 340 | lean | open nat
mutual def f,g
with f : ℕ → ℕ
| (succ x) := have 1 < 1, from sorry, g (succ x)
| zero := zero
with g : ℕ → ℕ
| (succ x) := have x < succ x, from lt_succ_self x, f x
| zero := zero
theorem diverge (x : ℕ): f x = g (succ (succ x)) := sorry
theorem proof (x : ℕ) : g x = f x := begin
simp [diverge]
end
|
c089d7259f0778d22ce17765e67039d1b549b950 | 5412d79aa1dc0b521605c38bef9f0d4557b5a29d | /stage0/src/Lean/Server/Watchdog.lean | 7f6c6dc125a5a7aa77a20ec3a2e9f41d72fbdfd7 | [
"Apache-2.0"
] | permissive | smunix/lean4 | a450ec0927dc1c74816a1bf2818bf8600c9fc9bf | 3407202436c141e3243eafbecb4b8720599b970a | refs/heads/master | 1,676,334,875,188 | 1,610,128,510,000 | 1,610,128,521,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,537 | lean | /-
Copyright (c) 2020 Marc Huisinga. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Marc Huisinga, Wojciech Nawrocki
-/
import Init.System.IO
import Init.Data.ByteArray
import Std.Data.RBMap
import Lean.Elab.Import
import Lean.Data.Lsp
import Lean.Server.FileSource
import Lean.Server.Utils
/-!
For general server architecture, see `README.md`. This module implements the watchdog process.
## Watchdog state
Most LSP clients only send us file diffs, so to facilitate sending entire file contents to freshly restarted
workers, the watchdog needs to maintain the current state of each file. It can also use this state to detect changes
to the header and thus restart the corresponding worker, freeing its imports.
TODO(WN):
We may eventually want to keep track of approximately (since this isn't knowable exactly) where in the file a worker
crashed. Then on restart, we tell said worker to only parse up to that point and query the user about how to proceed
(continue OR allow the user to fix the bug and then continue OR ..). Without this, if the crash is deterministic,
users may be confused about why the server seemingly stopped working for a single file.
## Watchdog <-> worker communication
The watchdog process and its file worker processes communicate via LSP. If the necessity arises,
we might add non-standard commands similarly based on JSON-RPC. Most requests and notifications
are forwarded to the corresponding file worker process, with the exception of these notifications:
- textDocument/didOpen: Launch the file worker, create the associated watchdog state and launch a task to
asynchronously receive LSP packets from the worker (e.g. request responses).
- textDocument/didChange: Update the local file state. If the header was mutated,
signal a shutdown to the file worker by closing the I/O channels.
Then restart the file worker. Otherwise, forward the `didChange` notification.
- textDocument/didClose: Signal a shutdown to the file worker and remove the associated watchdog state.
Moreover, we don't implement the full protocol at this level:
- Upon starting, the `initialize` request is forwarded to the worker, but it must not respond with its server
capabilities. Consequently, the watchdog will not send an `initialized` notification to the worker.
- After `initialize`, the watchdog sends the corresponding `didOpen` notification with the full current state of
the file. No additional `didOpen` notifications will be forwarded to the worker process.
- `$/cancelRequest` notifications are forwarded to all file workers.
- File workers are always terminated with an `exit` notification, without previously receiving a `shutdown` request.
Similarly, they never receive a `didClose` notification.
## Watchdog <-> client communication
The watchdog itself should implement the LSP standard as closely as possible. However we reserve the right to add
non-standard extensions in case they're needed, for example to communicate tactic state.
-/
namespace Lean.Server.Watchdog
open IO
open Std (RBMap RBMap.empty)
open Lsp
open JsonRpc
section Utils
structure OpenDocument where
meta : DocumentMeta
headerAst : Syntax
def workerCfg : Process.StdioConfig := {
stdin := Process.Stdio.piped
stdout := Process.Stdio.piped
-- We pass workers' stderr through to the editor.
stderr := Process.Stdio.inherit
}
/-- Events that a forwarding task of a worker signals to the main task -/
inductive WorkerEvent where
| terminated
| crashed (e : IO.Error)
inductive WorkerState where
/- The watchdog can detect a crashed file worker in two places: When trying to send a message to the file worker
and when reading a request reply.
In the latter case, the forwarding task terminates and delegates a `crashed` event to the main task.
Then, in both cases, the file worker has its state set to `crashed` and requests that are in-flight are errored.
Upon receiving the next packet for that file worker, the file worker is restarted and the packet is forwarded
to it. If the crash was detected while writing a packet, we queue that packet until the next packet for the file
worker arrives. -/
| crashed (queuedMsgs : Array JsonRpc.Message)
| running
abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message (fun a b => Decidable.decide (a < b))
private def parseHeaderAst (input : String) : IO Syntax := do
let inputCtx := Parser.mkInputContext input "<input>"
let (stx, _, _) ← Parser.parseHeader inputCtx
return stx
end Utils
section FileWorker
structure FileWorker where
doc : OpenDocument
proc : Process.Child workerCfg
commTask : Task WorkerEvent
state : WorkerState
-- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state
pendingRequestsRef : IO.Ref PendingRequestMap
namespace FileWorker
variable [ToJson α]
def stdin (fw : FileWorker) : FS.Stream :=
FS.Stream.ofHandle fw.proc.stdin
def stdout (fw : FileWorker) : FS.Stream :=
FS.Stream.ofHandle fw.proc.stdout
def readMessage (fw : FileWorker) : IO JsonRpc.Message := do
let msg ← fw.stdout.readLspMessage
if let Message.response id _ := msg then
fw.pendingRequestsRef.modify (fun pendingRequests => pendingRequests.erase id)
if let Message.responseError id _ _ _ := msg then
fw.pendingRequestsRef.modify (fun pendingRequests => pendingRequests.erase id)
return msg
def writeMessage (fw : FileWorker) (msg : JsonRpc.Message) : IO Unit :=
fw.stdin.writeLspMessage msg
def writeNotification (fw : FileWorker) (n : Notification α) : IO Unit :=
fw.stdin.writeLspNotification n
def writeRequest (fw : FileWorker) (r : Request α) : IO Unit := do
fw.stdin.writeLspRequest r
fw.pendingRequestsRef.modify (fun pendingRequests => pendingRequests.insert r.id r)
def errorPendingRequests (fw : FileWorker) (hError : FS.Stream) (code : ErrorCode) (msg : String) : IO Unit := do
let pendingRequests ← fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests, RBMap.empty))
for ⟨id, _⟩ in pendingRequests do
hError.writeLspResponseError { id := id, code := code, message := msg }
end FileWorker
end FileWorker
section ServerM
abbrev FileWorkerMap := RBMap DocumentUri FileWorker (fun a b => Decidable.decide (a < b))
structure ServerContext where
hIn : FS.Stream
hOut : FS.Stream
hLog : FS.Stream
fileWorkersRef : IO.Ref FileWorkerMap
-- We store these to pass them to workers.
initParams : InitializeParams
workerPath : String
abbrev ServerM := ReaderT ServerContext IO
def updateFileWorkers (val : FileWorker) : ServerM Unit := do
(←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.insert val.doc.meta.uri val)
def findFileWorker (uri : DocumentUri) : ServerM FileWorker := do
match (←(←read).fileWorkersRef.get).find? uri with
| some fw => fw
| none => throwServerError s!"Got unknown document URI ({uri})"
def eraseFileWorker (uri : DocumentUri) : ServerM Unit := do
(←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.erase uri)
def log (msg : String) : ServerM Unit := do
let st ← read
st.hLog.putStrLn msg
st.hLog.flush
/-- Creates a Task which forwards a worker's messages into the output stream until an event
which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/
private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do
let o := (←read).hOut
let rec loop : ServerM WorkerEvent := do
try
let msg ← fw.readMessage
-- Writes to Lean I/O channels are atomic, so these won't trample on each other.
o.writeLspMessage msg
loop
catch err =>
-- If writeLspMessage from above errors we will block here, but the main task will
-- quit eventually anyways if that happens
let exitCode ← fw.proc.wait
if exitCode = 0 then
-- Worker was terminated
fw.errorPendingRequests o ErrorCode.contentModified
("The file worker has been terminated. Either the header has changed,"
++ " or the file was closed, or the server is shutting down.")
return WorkerEvent.terminated
else
-- Worker crashed
fw.errorPendingRequests o ErrorCode.internalError
s!"Server process for {fw.doc.meta.uri} crashed, likely due to a stack overflow in user code."
return WorkerEvent.crashed err
let task ← IO.asTask (loop $ ←read) Task.Priority.dedicated
task.map $ fun
| Except.ok ev => ev
| Except.error e => WorkerEvent.crashed e
def startFileWorker (m : DocumentMeta) : ServerM Unit := do
let st ← read
let headerAst ← parseHeaderAst m.text.source
let workerProc ← Process.spawn {
toStdioConfig := workerCfg
cmd := st.workerPath
-- append file and imports for Nix support; ignored otherwise
args := #["--worker"] ++ (Lean.Elab.headerToImports headerAst).toArray.map (toString ·.module)
}
let pendingRequestsRef ← IO.mkRef (RBMap.empty : PendingRequestMap)
-- The task will never access itself, so this is fine
let commTaskFw : FileWorker := {
doc := ⟨m, headerAst⟩
proc := workerProc
commTask := Task.pure WorkerEvent.terminated
state := WorkerState.running
pendingRequestsRef := pendingRequestsRef
}
let commTask ← forwardMessages commTaskFw
let fw : FileWorker := { commTaskFw with commTask := commTask }
fw.stdin.writeLspRequest ⟨0, "initialize", st.initParams⟩
fw.writeNotification {
method := "textDocument/didOpen"
param := {
textDocument := {
uri := m.uri
languageId := "lean"
version := m.version
text := m.text.source
} : DidOpenTextDocumentParams
}
}
updateFileWorkers fw
def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do
/- The file worker must have crashed just when we were about to terminate it!
That's fine - just forget about it then.
(on didClose we won't need the crashed file worker anymore,
when the header changed we'll start a new one right after
anyways and when we're shutting down the server
it's over either way.) -/
try (←findFileWorker uri).writeMessage (Message.notification "exit" none)
catch err => ()
eraseFileWorker uri
def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do
updateFileWorkers { ←findFileWorker uri with state := WorkerState.crashed queuedMsgs }
/-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed
and restarts the file worker if the `crashed` flag was already set.
Messages that couldn't be sent can be queued up via the queueFailedMessage flag and
will be discharged after the FileWorker is restarted. -/
def tryWriteMessage [Coe α JsonRpc.Message] (uri : DocumentUri) (msg : α) (writeAction : FileWorker → α → IO Unit)
(queueFailedMessage := true) : ServerM Unit := do
let fw ← findFileWorker uri
match fw.state with
| WorkerState.crashed queuedMsgs =>
let mut queuedMsgs := queuedMsgs
if queueFailedMessage then
queuedMsgs := queuedMsgs.push msg
-- restart the crashed FileWorker
eraseFileWorker uri
startFileWorker fw.doc.meta
let newFw ← findFileWorker uri
let mut crashedMsgs := #[]
-- try to discharge all queued msgs, tracking the ones that we can't discharge
for msg in queuedMsgs do
try
newFw.writeMessage msg
catch _ =>
crashedMsgs := crashedMsgs.push msg
if ¬ crashedMsgs.isEmpty then
handleCrash uri crashedMsgs
| WorkerState.running =>
let initialQueuedMsgs :=
if queueFailedMessage then
#[msg]
else
#[]
try
writeAction fw msg
catch _ =>
handleCrash uri (initialQueuedMsgs.map Coe.coe)
end ServerM
section NotificationHandling
def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit :=
let doc := p.textDocument
/- NOTE(WN): `toFileMap` marks line beginnings as immediately following
"\n", which should be enough to handle both LF and CRLF correctly.
This is because LSP always refers to characters by (line, column),
so if we get the line number correct it shouldn't matter that there
is a CR there. -/
startFileWorker ⟨doc.uri, doc.version, doc.text.toFileMap⟩
def handleDidChange (p : DidChangeTextDocumentParams) : ServerM Unit := do
let doc := p.textDocument
let changes := p.contentChanges
let fw ← findFileWorker doc.uri
let oldDoc := fw.doc
let some newVersion ← pure doc.version?
| throwServerError "Expected version number"
if newVersion <= oldDoc.meta.version then
throwServerError "Got outdated version number"
if changes.isEmpty then
return
let (newDocText, _) := foldDocumentChanges changes oldDoc.meta.text
let newMeta : DocumentMeta := ⟨doc.uri, newVersion, newDocText⟩
let newHeaderAst ← parseHeaderAst newDocText.source
if newHeaderAst != oldDoc.headerAst then
/- TODO(WN): we should amortize this somehow
when the user is typing in an import, this
may rapidly destroy/create new processes -/
terminateFileWorker doc.uri
startFileWorker newMeta
else
let newDoc : OpenDocument := ⟨newMeta, oldDoc.headerAst⟩
updateFileWorkers { fw with doc := newDoc }
tryWriteMessage doc.uri ⟨"textDocument/didChange", p⟩ FileWorker.writeNotification
def handleDidClose (p : DidCloseTextDocumentParams) : ServerM Unit :=
terminateFileWorker p.textDocument.uri
def handleCancelRequest (p : CancelParams) : ServerM Unit := do
let fileWorkers ← (←read).fileWorkersRef.get
for ⟨uri, fw⟩ in fileWorkers do
let req? ← fw.pendingRequestsRef.modifyGet (fun pendingRequests =>
(pendingRequests.find? p.id, pendingRequests.erase p.id))
if let some req := req? then
tryWriteMessage uri ⟨"$/cancelRequest", p⟩ FileWorker.writeNotification (queueFailedMessage := false)
end NotificationHandling
section MessageHandling
def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType :=
match fromJson? params with
| some parsed => pure parsed
| none => throwServerError s!"Got param with wrong structure: {params.compress}"
def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do
let handle := fun α [FromJson α] [ToJson α] [FileSource α] => do
let parsedParams ← parseParams α params
let uri := fileSource parsedParams
tryWriteMessage uri ⟨id, method, parsedParams⟩ FileWorker.writeRequest
match method with
| "textDocument/waitForDiagnostics" => handle WaitForDiagnosticsParam
| "textDocument/hover" => handle HoverParams
| "textDocument/documentSymbol" => handle DocumentSymbolParams
| _ =>
(←read).hOut.writeLspResponseError
{ id := id
code := ErrorCode.methodNotFound
message := s!"Unsupported request method: {method}" }
def handleNotification (method : String) (params : Json) : ServerM Unit := do
let handle := (fun α [FromJson α] (handler : α → ServerM Unit) => parseParams α params >>= handler)
match method with
| "textDocument/didOpen" => handle DidOpenTextDocumentParams handleDidOpen
| "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange
| "textDocument/didClose" => handle DidCloseTextDocumentParams handleDidClose
| "$/cancelRequest" => handle CancelParams handleCancelRequest
| _ => (←read).hLog.putStrLn s!"Got unsupported notification: {method}"
end MessageHandling
section MainLoop
def shutdown : ServerM Unit := do
let fileWorkers ← (←read).fileWorkersRef.get
for ⟨uri, _⟩ in fileWorkers do
terminateFileWorker uri
for ⟨_, fw⟩ in fileWorkers do
discard <| IO.wait fw.commTask
inductive ServerEvent where
| WorkerEvent (fw : FileWorker) (ev : WorkerEvent)
| ClientMsg (msg : JsonRpc.Message)
| ClientError (e : IO.Error)
def runClientTask : ServerM (Task ServerEvent) := do
let st ← read
let readMsgAction : IO ServerEvent := do
/- Runs asynchronously. -/
let msg ← st.hIn.readLspMessage
ServerEvent.ClientMsg msg
let clientTask := (←IO.asTask readMsgAction).map $ fun
| Except.ok ev => ev
| Except.error e => ServerEvent.ClientError e
return clientTask
partial def mainLoop (clientTask : Task ServerEvent) : ServerM Unit := do
let st ← read
let workers ← st.fileWorkersRef.get
let workerTasks := workers.fold
(fun acc _ fw =>
match fw.state with
| WorkerState.running => fw.commTask.map (ServerEvent.WorkerEvent fw) :: acc
| _ => acc)
([] : List (Task ServerEvent))
let ev ← IO.waitAny $ clientTask :: workerTasks
match ev with
| ServerEvent.ClientMsg msg =>
match msg with
| Message.request id "shutdown" _ =>
shutdown
st.hOut.writeLspResponse ⟨id, Json.null⟩
| Message.request id method (some params) =>
handleRequest id method (toJson params)
mainLoop (←runClientTask)
| Message.notification method (some params) =>
handleNotification method (toJson params)
mainLoop (←runClientTask)
| _ => throwServerError "Got invalid JSON-RPC message"
| ServerEvent.ClientError e => throw e
| ServerEvent.WorkerEvent fw err =>
match err with
| WorkerEvent.crashed e =>
handleCrash fw.doc.meta.uri #[]
mainLoop clientTask
| WorkerEvent.terminated => throwServerError "Internal server error: got termination event for worker that should have been removed"
end MainLoop
def mkLeanServerCapabilities : ServerCapabilities := {
textDocumentSync? := some {
openClose := true
change := TextDocumentSyncKind.incremental
willSave := false
willSaveWaitUntil := false
save? := none
}
--hoverProvider := true
documentSymbolProvider := true
}
def initAndRunWatchdogAux : ServerM Unit := do
let st ← read
try
discard $ st.hIn.readLspNotificationAs "initialized" InitializedParams
let clientTask ← runClientTask
mainLoop clientTask
let Message.notification "exit" none ← st.hIn.readLspMessage
| throwServerError "Expected an exit notification"
catch err =>
shutdown
throw err
def initAndRunWatchdog (i o e : FS.Stream) : IO Unit := do
let workerPath ← match (←IO.getEnv "LEAN_WORKER_PATH") with
| none => IO.appPath
| some p => p
let fileWorkersRef ← IO.mkRef (RBMap.empty : FileWorkerMap)
let i ← maybeTee "wdIn.txt" false i
let o ← maybeTee "wdOut.txt" true o
let e ← maybeTee "wdErr.txt" true e
let initRequest ← i.readLspRequestAs "initialize" InitializeParams
o.writeLspResponse {
id := initRequest.id
result := {
capabilities := mkLeanServerCapabilities
serverInfo? := some {
name := "Lean 4 server"
version? := "0.0.1"
}
: InitializeResult
}
}
ReaderT.run initAndRunWatchdogAux {
hIn := i
hOut := o
hLog := e
fileWorkersRef := fileWorkersRef
initParams := initRequest.param
workerPath := workerPath
: ServerContext
}
@[export lean_server_watchdog_main]
def watchdogMain : IO UInt32 := do
let i ← IO.getStdin
let o ← IO.getStdout
let e ← IO.getStderr
try
initAndRunWatchdog i o e
return 0
catch err =>
e.putStrLn s!"Watchdog error: {err}"
return 1
end Lean.Server.Watchdog
|
d4aa0491937fd72536fe87d12dbd4a74bf19e3a5 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/category_theory/yoneda.lean | be75fce2bd51d4e36863a1fbea94ca80a0c3cb46 | [
"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 | 6,549 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.hom_functor
/-!
# The Yoneda embedding
The Yoneda embedding as a functor `yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁)`,
along with an instance that it is `fully_faithful`.
Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`.
-/
namespace category_theory
open opposite
universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {C : Type u₁} [category.{v₁} C]
@[simps] def yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁) :=
{ obj := λ X,
{ obj := λ Y, unop Y ⟶ X,
map := λ Y Y' f g, f.unop ≫ g,
map_comp' := λ _ _ _ f g, begin ext, dsimp, erw [category.assoc] end,
map_id' := λ Y, begin ext, dsimp, erw [category.id_comp] end },
map := λ X X' f, { app := λ Y g, g ≫ f } }
@[simps] def coyoneda : Cᵒᵖ ⥤ (C ⥤ Type v₁) :=
{ obj := λ X,
{ obj := λ Y, unop X ⟶ Y,
map := λ Y Y' f g, g ≫ f,
map_comp' := λ _ _ _ f g, begin ext1, dsimp, erw [category.assoc] end,
map_id' := λ Y, begin ext1, dsimp, erw [category.comp_id] end },
map := λ X X' f, { app := λ Y g, f.unop ≫ g },
map_comp' := λ _ _ _ f g, begin ext, dsimp, erw [category.assoc] end,
map_id' := λ X, begin ext, dsimp, erw [category.id_comp] end }
namespace yoneda
lemma obj_map_id {X Y : C} (f : op X ⟶ op Y) :
((@yoneda C _).obj X).map f (𝟙 X) = ((@yoneda C _).map f.unop).app (op Y) (𝟙 Y) :=
by obviously
@[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y)
{Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app (op Z') h = α.app (op Z) (f ≫ h) :=
(functor_to_types.naturality _ _ α f.op h).symm
instance yoneda_full : full (@yoneda C _) :=
{ preimage := λ X Y f, (f.app (op X)) (𝟙 X) }
instance yoneda_faithful : faithful (@yoneda C _) :=
{ map_injective' := λ X Y f g p,
begin
injection p with h,
convert (congr_fun (congr_fun h (op X)) (𝟙 X)); dsimp; simp,
end }
/-- Extensionality via Yoneda. The typical usage would be
```
-- Goal is `X ≅ Y`
apply yoneda.ext,
-- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these
functions are inverses and natural in `Z`.
```
-/
def ext (X Y : C)
(p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X))
(h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f)
(n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y :=
@preimage_iso _ _ _ _ yoneda _ _ _ _
(nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy))
def is_iso {X Y : C} (f : X ⟶ Y) [is_iso (yoneda.map f)] : is_iso f :=
is_iso_of_fully_faithful yoneda f
end yoneda
namespace coyoneda
@[simp] lemma naturality {X Y : Cᵒᵖ} (α : coyoneda.obj X ⟶ coyoneda.obj Y)
{Z Z' : C} (f : Z' ⟶ Z) (h : unop X ⟶ Z') : (α.app Z' h) ≫ f = α.app Z (h ≫ f) :=
begin erw [functor_to_types.naturality], refl end
instance coyoneda_full : full (@coyoneda C _) :=
{ preimage := λ X Y f, ((f.app (unop X)) (𝟙 _)).op }
instance coyoneda_faithful : faithful (@coyoneda C _) :=
{ map_injective' := λ X Y f g p,
begin
injection p with h,
have t := (congr_fun (congr_fun h (unop X)) (𝟙 _)),
simpa using congr_arg has_hom.hom.op t,
end }
def is_iso {X Y : Cᵒᵖ} (f : X ⟶ Y) [is_iso (coyoneda.map f)] : is_iso f :=
is_iso_of_fully_faithful coyoneda f
end coyoneda
class representable (F : Cᵒᵖ ⥤ Type v₁) :=
(X : C)
(w : yoneda.obj X ≅ F)
end category_theory
namespace category_theory
-- For the rest of the file, we are using product categories,
-- so need to restrict to the case morphisms are in 'Type', not 'Sort'.
universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
open opposite
variables (C : Type u₁) [category.{v₁} C]
-- We need to help typeclass inference with some awkward universe levels here.
instance prod_category_instance_1 : category ((Cᵒᵖ ⥤ Type v₁) × Cᵒᵖ) :=
category_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) Cᵒᵖ
instance prod_category_instance_2 : category (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) :=
category_theory.prod.{v₁ (max u₁ v₁)} Cᵒᵖ (Cᵒᵖ ⥤ Type v₁)
open yoneda
def yoneda_evaluation : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) :=
evaluation_uncurried Cᵒᵖ (Type v₁) ⋙ ulift_functor.{u₁}
@[simp] lemma yoneda_evaluation_map_down
(P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) :
((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl
def yoneda_pairing : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) :=
functor.prod yoneda.op (𝟭 (Cᵒᵖ ⥤ Type v₁)) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁)
@[simp] lemma yoneda_pairing_map
(P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) :
(yoneda_pairing C).map α β = yoneda.map α.1.unop ≫ β ≫ α.2 := rfl
def yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C :=
{ hom :=
{ app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))),
naturality' :=
begin
intros X Y f, ext, dsimp,
erw [category.id_comp, ←functor_to_types.naturality],
simp only [category.comp_id, yoneda_obj_map],
end },
inv :=
{ app := λ F x,
{ app := λ X a, (F.2.map a.op) x.down,
naturality' :=
begin
intros X Y f, ext, dsimp,
rw [functor_to_types.map_comp_apply]
end },
naturality' :=
begin
intros X Y f, ext, dsimp,
rw [←functor_to_types.naturality, functor_to_types.map_comp_apply]
end },
hom_inv_id' :=
begin
ext, dsimp,
erw [←functor_to_types.naturality,
obj_map_id],
simp only [yoneda_map_app, has_hom.hom.unop_op],
erw [category.id_comp],
end,
inv_hom_id' :=
begin
ext, dsimp,
rw [functor_to_types.map_id_apply]
end }.
variables {C}
@[simp] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) :
(yoneda.obj X ⟶ F) ≅ ulift.{u₁} (F.obj (op X)) :=
(yoneda_lemma C).app (op X, F)
@[simp] def yoneda_sections_small {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) :
(yoneda.obj X ⟶ F) ≅ F.obj (op X) :=
yoneda_sections X F ≪≫ ulift_trivial _
end category_theory
|
84e07096dcaef74643782ad5dd0aa673b124b476 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/data/setoid_auto.lean | 0a66c08d040b2257c626feb40f5347c93fbf00e6 | [] | 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 | 757 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.logic
universes u l
namespace Mathlib
class setoid (α : Sort u) where
r : α → α → Prop
iseqv : equivalence r
protected instance setoid_has_equiv {α : Sort u} [setoid α] : has_equiv α := has_equiv.mk setoid.r
namespace setoid
theorem refl {α : Sort u} [setoid α] (a : α) : a ≈ a := sorry
theorem symm {α : Sort u} [setoid α] {a : α} {b : α} (hab : a ≈ b) : b ≈ a := sorry
theorem trans {α : Sort u} [setoid α] {a : α} {b : α} {c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c :=
sorry
end Mathlib |
570145eb62d5c3d00907c495cf0d8ecc9497ee7c | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/field_theory/adjoin.lean | c6f2e7dcd0a4aa0db6efc8c9f766c220dd4be540 | [
"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 | 33,349 | 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.intermediate_field
import field_theory.splitting_field
import field_theory.separable
import ring_theory.adjoin_root
import ring_theory.power_basis
/-!
# Adjoining Elements to Fields
In this file we introduce the notion of adjoining elements to fields.
This isn't quite the same as adjoining elements to rings.
For example, `algebra.adjoin K {x}` might not include `x⁻¹`.
## Main results
- `adjoin_adjoin_left`: adjoining S and then T is the same as adjoining `S ∪ T`.
- `bot_eq_top_of_dim_adjoin_eq_one`: if `F⟮x⟯` has dimension `1` over `F` for every `x`
in `E` then `F = E`
## Notation
- `F⟮α⟯`: adjoin a single element `α` to `F`.
-/
open finite_dimensional polynomial
open_locale classical
namespace intermediate_field
section adjoin_def
variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E)
/-- `adjoin F S` extends a field `F` by adjoining a set `S ⊆ E`. -/
def adjoin : intermediate_field F E :=
{ algebra_map_mem' := λ x, subfield.subset_closure (or.inl (set.mem_range_self x)),
..subfield.closure (set.range (algebra_map F E) ∪ S) }
end adjoin_def
section lattice
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E]
@[simp] lemma adjoin_le_iff {S : set E} {T : intermediate_field F E} : adjoin F S ≤ T ↔ S ≤ T :=
⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subfield.subset_closure) H,
λ H, (@subfield.closure_le E _ (set.range (algebra_map F E) ∪ S) T.to_subfield).mpr
(set.union_subset (intermediate_field.set_range_subset T) H)⟩
lemma gc : galois_connection (adjoin F : set E → intermediate_field F E) coe := λ _ _, adjoin_le_iff
/-- Galois insertion between `adjoin` and `coe`. -/
def gi : galois_insertion (adjoin F : set E → intermediate_field F E) coe :=
{ choice := λ S _, adjoin F S,
gc := intermediate_field.gc,
le_l_u := λ S, (intermediate_field.gc (S : set E) (adjoin F S)).1 $ le_refl _,
choice_eq := λ _ _, rfl }
instance : complete_lattice (intermediate_field F E) :=
galois_insertion.lift_complete_lattice intermediate_field.gi
instance : inhabited (intermediate_field F E) := ⟨⊤⟩
lemma mem_bot {x : E} : x ∈ (⊥ : intermediate_field F E) ↔ x ∈ set.range (algebra_map F E) :=
begin
suffices : set.range (algebra_map F E) = (⊥ : intermediate_field F E),
{ rw this, refl },
{ change set.range (algebra_map F E) = subfield.closure (set.range (algebra_map F E) ∪ ∅),
simp [←set.image_univ, ←ring_hom.map_field_closure] }
end
lemma mem_top {x : E} : x ∈ (⊤ : intermediate_field F E) :=
subfield.subset_closure $ or.inr trivial
@[simp] lemma bot_to_subalgebra : (⊥ : intermediate_field F E).to_subalgebra = ⊥ :=
by { ext, rw [mem_to_subalgebra, algebra.mem_bot, mem_bot] }
@[simp] lemma top_to_subalgebra : (⊤ : intermediate_field F E).to_subalgebra = ⊤ :=
by { ext, rw [mem_to_subalgebra, iff_true_right algebra.mem_top], exact mem_top }
/-- Construct an algebra isomorphism from an equality of intermediate fields -/
@[simps apply]
def equiv_of_eq {S T : intermediate_field F E} (h : S = T) : S ≃ₐ[F] T :=
by refine { to_fun := λ x, ⟨x, _⟩, inv_fun := λ x, ⟨x, _⟩, .. }; tidy
@[simp] lemma equiv_of_eq_symm {S T : intermediate_field F E} (h : S = T) :
(equiv_of_eq h).symm = equiv_of_eq h.symm :=
rfl
@[simp] lemma equiv_of_eq_rfl (S : intermediate_field F E) :
equiv_of_eq (rfl : S = S) = alg_equiv.refl :=
by { ext, refl }
@[simp] lemma equiv_of_eq_trans {S T U : intermediate_field F E} (hST : S = T) (hTU : T = U) :
(equiv_of_eq hST).trans (equiv_of_eq hTU) = equiv_of_eq (trans hST hTU) :=
rfl
variables (F E)
/-- The bottom intermediate_field is isomorphic to the field. -/
noncomputable def bot_equiv : (⊥ : intermediate_field F E) ≃ₐ[F] F :=
(subalgebra.equiv_of_eq _ _ bot_to_subalgebra).trans (algebra.bot_equiv F E)
variables {F E}
@[simp] lemma bot_equiv_def (x : F) :
bot_equiv F E (algebra_map F (⊥ : intermediate_field F E) x) = x :=
alg_equiv.commutes (bot_equiv F E) x
noncomputable instance algebra_over_bot : algebra (⊥ : intermediate_field F E) F :=
(intermediate_field.bot_equiv F E).to_alg_hom.to_ring_hom.to_algebra
instance is_scalar_tower_over_bot : is_scalar_tower (⊥ : intermediate_field F E) F E :=
is_scalar_tower.of_algebra_map_eq
begin
intro x,
let ϕ := algebra.of_id F (⊥ : subalgebra F E),
let ψ := alg_equiv.of_bijective ϕ ((algebra.bot_equiv F E).symm.bijective),
change (↑x : E) = ↑(ψ (ψ.symm ⟨x, _⟩)),
rw alg_equiv.apply_symm_apply ψ ⟨x, _⟩,
refl
end
/-- The top intermediate_field is isomorphic to the field. -/
noncomputable def top_equiv : (⊤ : intermediate_field F E) ≃ₐ[F] E :=
(subalgebra.equiv_of_eq _ _ top_to_subalgebra).trans algebra.top_equiv
@[simp] lemma top_equiv_def (x : (⊤ : intermediate_field F E)) : top_equiv x = ↑x :=
begin
suffices : algebra.to_top (top_equiv x) = algebra.to_top (x : E),
{ rwa subtype.ext_iff at this },
exact alg_equiv.apply_symm_apply (alg_equiv.of_bijective algebra.to_top
⟨λ _ _, subtype.mk.inj, λ x, ⟨x.val, by { ext, refl }⟩⟩ : E ≃ₐ[F] (⊤ : subalgebra F E))
(subalgebra.equiv_of_eq _ _ top_to_subalgebra x),
end
@[simp] lemma coe_bot_eq_self (K : intermediate_field F E) : ↑(⊥ : intermediate_field K E) = K :=
by { ext, rw [mem_lift2, mem_bot], exact set.ext_iff.mp subtype.range_coe x }
@[simp] lemma coe_top_eq_top (K : intermediate_field F E) :
↑(⊤ : intermediate_field K E) = (⊤ : intermediate_field F E) :=
set_like.ext_iff.mpr $ λ _, mem_lift2.trans (iff_of_true mem_top mem_top)
end lattice
section adjoin_def
variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E)
lemma adjoin_eq_range_algebra_map_adjoin :
(adjoin F S : set E) = set.range (algebra_map (adjoin F S) E) := (subtype.range_coe).symm
lemma adjoin.algebra_map_mem (x : F) : algebra_map F E x ∈ adjoin F S :=
intermediate_field.algebra_map_mem (adjoin F S) x
lemma adjoin.range_algebra_map_subset : set.range (algebra_map F E) ⊆ adjoin F S :=
begin
intros x hx,
cases hx with f hf,
rw ← hf,
exact adjoin.algebra_map_mem F S f,
end
instance adjoin.field_coe : has_coe_t F (adjoin F S) :=
{coe := λ x, ⟨algebra_map F E x, adjoin.algebra_map_mem F S x⟩}
lemma subset_adjoin : S ⊆ adjoin F S :=
λ x hx, subfield.subset_closure (or.inr hx)
instance adjoin.set_coe : has_coe_t S (adjoin F S) :=
{coe := λ x, ⟨x,subset_adjoin F S (subtype.mem x)⟩}
@[mono] lemma adjoin.mono (T : set E) (h : S ⊆ T) : adjoin F S ≤ adjoin F T :=
galois_connection.monotone_l gc h
lemma adjoin_contains_field_as_subfield (F : subfield E) : (F : set E) ⊆ adjoin F S :=
λ x hx, adjoin.algebra_map_mem F S ⟨x, hx⟩
lemma subset_adjoin_of_subset_left {F : subfield E} {T : set E} (HT : T ⊆ F) : T ⊆ adjoin F S :=
λ x hx, (adjoin F S).algebra_map_mem ⟨x, HT hx⟩
lemma subset_adjoin_of_subset_right {T : set E} (H : T ⊆ S) : T ⊆ adjoin F S :=
λ x hx, subset_adjoin F S (H hx)
@[simp] lemma adjoin_empty (F E : Type*) [field F] [field E] [algebra F E] :
adjoin F (∅ : set E) = ⊥ :=
eq_bot_iff.mpr (adjoin_le_iff.mpr (set.empty_subset _))
/-- If `K` is a field with `F ⊆ K` and `S ⊆ K` then `adjoin F S ≤ K`. -/
lemma adjoin_le_subfield {K : subfield E} (HF : set.range (algebra_map F E) ⊆ K)
(HS : S ⊆ K) : (adjoin F S).to_subfield ≤ K :=
begin
apply subfield.closure_le.mpr,
rw set.union_subset_iff,
exact ⟨HF, HS⟩,
end
lemma adjoin_subset_adjoin_iff {F' : Type*} [field F'] [algebra F' E]
{S S' : set E} : (adjoin F S : set E) ⊆ adjoin F' S' ↔
set.range (algebra_map F E) ⊆ adjoin F' S' ∧ S ⊆ adjoin F' S' :=
⟨λ h, ⟨trans (adjoin.range_algebra_map_subset _ _) h, trans (subset_adjoin _ _) h⟩,
λ ⟨hF, hS⟩, subfield.closure_le.mpr (set.union_subset hF hS)⟩
/-- `F[S][T] = F[S ∪ T]` -/
lemma adjoin_adjoin_left (T : set E) : ↑(adjoin (adjoin F S) T) = adjoin F (S ∪ T) :=
begin
rw set_like.ext'_iff,
change ↑(adjoin (adjoin F S) T) = _,
apply set.eq_of_subset_of_subset; rw adjoin_subset_adjoin_iff; split,
{ rintros _ ⟨⟨x, hx⟩, rfl⟩, exact adjoin.mono _ _ _ (set.subset_union_left _ _) hx },
{ exact subset_adjoin_of_subset_right _ _ (set.subset_union_right _ _) },
{ exact subset_adjoin_of_subset_left _ (adjoin.range_algebra_map_subset _ _) },
{ exact set.union_subset
(subset_adjoin_of_subset_left _ (subset_adjoin _ _))
(subset_adjoin _ _) },
end
@[simp] lemma adjoin_insert_adjoin (x : E) :
adjoin F (insert x (adjoin F S : set E)) = adjoin F (insert x S) :=
le_antisymm
(adjoin_le_iff.mpr (set.insert_subset.mpr ⟨subset_adjoin _ _ (set.mem_insert _ _),
adjoin_le_iff.mpr (subset_adjoin_of_subset_right _ _ (set.subset_insert _ _))⟩))
(adjoin.mono _ _ _ (set.insert_subset_insert (subset_adjoin _ _)))
/-- `F[S][T] = F[T][S]` -/
lemma adjoin_adjoin_comm (T : set E) :
↑(adjoin (adjoin F S) T) = (↑(adjoin (adjoin F T) S) : (intermediate_field F E)) :=
by rw [adjoin_adjoin_left, adjoin_adjoin_left, set.union_comm]
lemma adjoin_map {E' : Type*} [field E'] [algebra F E'] (f : E →ₐ[F] E') :
(adjoin F S).map f = adjoin F (f '' S) :=
begin
ext x,
show x ∈ (subfield.closure (set.range (algebra_map F E) ∪ S)).map (f : E →+* E') ↔
x ∈ subfield.closure (set.range (algebra_map F E') ∪ f '' S),
rw [ring_hom.map_field_closure, set.image_union, ← set.range_comp, ← ring_hom.coe_comp,
f.comp_algebra_map],
refl,
end
lemma algebra_adjoin_le_adjoin : algebra.adjoin F S ≤ (adjoin F S).to_subalgebra :=
algebra.adjoin_le (subset_adjoin _ _)
lemma adjoin_eq_algebra_adjoin (inv_mem : ∀ x ∈ algebra.adjoin F S, x⁻¹ ∈ algebra.adjoin F S) :
(adjoin F S).to_subalgebra = algebra.adjoin F S :=
le_antisymm
(show adjoin F S ≤
{ neg_mem' := λ x, (algebra.adjoin F S).neg_mem, inv_mem' := inv_mem, .. algebra.adjoin F S},
from adjoin_le_iff.mpr (algebra.subset_adjoin))
(algebra_adjoin_le_adjoin _ _)
lemma eq_adjoin_of_eq_algebra_adjoin (K : intermediate_field F E)
(h : K.to_subalgebra = algebra.adjoin F S) : K = adjoin F S :=
begin
apply to_subalgebra_injective,
rw h,
refine (adjoin_eq_algebra_adjoin _ _ _).symm,
intros x,
convert K.inv_mem,
rw ← h,
refl
end
@[elab_as_eliminator]
lemma adjoin_induction {s : set E} {p : E → Prop} {x} (h : x ∈ adjoin F s)
(Hs : ∀ x ∈ s, p x) (Hmap : ∀ x, p (algebra_map F E x))
(Hadd : ∀ x y, p x → p y → p (x + y))
(Hneg : ∀ x, p x → p (-x))
(Hinv : ∀ x, p x → p x⁻¹)
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
subfield.closure_induction h (λ x hx, or.cases_on hx (λ ⟨x, hx⟩, hx ▸ Hmap x) (Hs x))
((algebra_map F E).map_one ▸ Hmap 1)
Hadd Hneg Hinv Hmul
/--
Variation on `set.insert` to enable good notation for adjoining elements to fields.
Used to preferentially use `singleton` rather than `insert` when adjoining one element.
-/
--this definition of notation is courtesy of Kyle Miller on zulip
class insert {α : Type*} (s : set α) :=
(insert : α → set α)
@[priority 1000]
instance insert_empty {α : Type*} : insert (∅ : set α) :=
{ insert := λ x, @singleton _ _ set.has_singleton x }
@[priority 900]
instance insert_nonempty {α : Type*} (s : set α) : insert s :=
{ insert := λ x, set.insert x s }
notation K`⟮`:std.prec.max_plus l:(foldr `, ` (h t, insert.insert t h) ∅) `⟯` := adjoin K l
section adjoin_simple
variables (α : E)
lemma mem_adjoin_simple_self : α ∈ F⟮α⟯ :=
subset_adjoin F {α} (set.mem_singleton α)
/-- generator of `F⟮α⟯` -/
def adjoin_simple.gen : F⟮α⟯ := ⟨α, mem_adjoin_simple_self F α⟩
@[simp] lemma adjoin_simple.algebra_map_gen : algebra_map F⟮α⟯ E (adjoin_simple.gen F α) = α := rfl
@[simp] lemma adjoin_simple.is_integral_gen :
is_integral F (adjoin_simple.gen F α) ↔ is_integral F α :=
by { conv_rhs { rw ← adjoin_simple.algebra_map_gen F α },
rw is_integral_algebra_map_iff (algebra_map F⟮α⟯ E).injective,
apply_instance }
lemma adjoin_simple_adjoin_simple (β : E) : ↑F⟮α⟯⟮β⟯ = F⟮α, β⟯ :=
adjoin_adjoin_left _ _ _
lemma adjoin_simple_comm (β : E) : ↑F⟮α⟯⟮β⟯ = (↑F⟮β⟯⟮α⟯ : intermediate_field F E) :=
adjoin_adjoin_comm _ _ _
-- TODO: develop the API for `subalgebra.is_field_of_algebraic` so it can be used here
lemma adjoin_simple_to_subalgebra_of_integral (hα : is_integral F α) :
(F⟮α⟯).to_subalgebra = algebra.adjoin F {α} :=
begin
apply adjoin_eq_algebra_adjoin,
intros x hx,
by_cases x = 0,
{ rw [h, inv_zero], exact subalgebra.zero_mem (algebra.adjoin F {α}) },
let ϕ := alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly F α,
haveI := minpoly.irreducible hα,
suffices : ϕ ⟨x, hx⟩ * (ϕ ⟨x, hx⟩)⁻¹ = 1,
{ convert subtype.mem (ϕ.symm (ϕ ⟨x, hx⟩)⁻¹),
refine (eq_inv_of_mul_right_eq_one _).symm,
apply_fun ϕ.symm at this,
rw [alg_equiv.map_one, alg_equiv.map_mul, alg_equiv.symm_apply_apply] at this,
rw [←subsemiring.coe_one, ←this, subsemiring.coe_mul, subtype.coe_mk] },
rw mul_inv_cancel (mt (λ key, _) h),
rw ← ϕ.map_zero at key,
change ↑(⟨x, hx⟩ : algebra.adjoin F {α}) = _,
rw [ϕ.injective key, subalgebra.coe_zero]
end
end adjoin_simple
end adjoin_def
section adjoin_intermediate_field_lattice
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} {S : set E}
@[simp] lemma adjoin_eq_bot_iff : adjoin F S = ⊥ ↔ S ⊆ (⊥ : intermediate_field F E) :=
by { rw [eq_bot_iff, adjoin_le_iff], refl, }
@[simp] lemma adjoin_simple_eq_bot_iff : F⟮α⟯ = ⊥ ↔ α ∈ (⊥ : intermediate_field F E) :=
by { rw adjoin_eq_bot_iff, exact set.singleton_subset_iff }
@[simp] lemma adjoin_zero : F⟮(0 : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (zero_mem ⊥)
@[simp] lemma adjoin_one : F⟮(1 : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (one_mem ⊥)
@[simp] lemma adjoin_int (n : ℤ) : F⟮(n : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n)
@[simp] lemma adjoin_nat (n : ℕ) : F⟮(n : E)⟯ = ⊥ :=
adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n)
section adjoin_dim
open finite_dimensional module
variables {K L : intermediate_field F E}
@[simp] lemma dim_eq_one_iff : module.rank F K = 1 ↔ K = ⊥ :=
by rw [← to_subalgebra_eq_iff, ← dim_eq_dim_subalgebra,
subalgebra.dim_eq_one_iff, bot_to_subalgebra]
@[simp] lemma finrank_eq_one_iff : finrank F K = 1 ↔ K = ⊥ :=
by rw [← to_subalgebra_eq_iff, ← finrank_eq_finrank_subalgebra,
subalgebra.finrank_eq_one_iff, bot_to_subalgebra]
lemma dim_adjoin_eq_one_iff : module.rank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) :=
iff.trans dim_eq_one_iff adjoin_eq_bot_iff
lemma dim_adjoin_simple_eq_one_iff : module.rank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) :=
by { rw dim_adjoin_eq_one_iff, exact set.singleton_subset_iff }
lemma finrank_adjoin_eq_one_iff : finrank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) :=
iff.trans finrank_eq_one_iff adjoin_eq_bot_iff
lemma finrank_adjoin_simple_eq_one_iff : finrank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) :=
by { rw [finrank_adjoin_eq_one_iff], exact set.singleton_subset_iff }
/-- If `F⟮x⟯` has dimension `1` over `F` for every `x ∈ E` then `F = E`. -/
lemma bot_eq_top_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) :
(⊥ : intermediate_field F E) = ⊤ :=
begin
ext,
rw iff_true_right intermediate_field.mem_top,
exact dim_adjoin_simple_eq_one_iff.mp (h x),
end
lemma bot_eq_top_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) :
(⊥ : intermediate_field F E) = ⊤ :=
begin
ext,
rw iff_true_right intermediate_field.mem_top,
exact finrank_adjoin_simple_eq_one_iff.mp (h x),
end
lemma subsingleton_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) :
subsingleton (intermediate_field F E) :=
subsingleton_of_bot_eq_top (bot_eq_top_of_dim_adjoin_eq_one h)
lemma subsingleton_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) :
subsingleton (intermediate_field F E) :=
subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_eq_one h)
/-- If `F⟮x⟯` has dimension `≤1` over `F` for every `x ∈ E` then `F = E`. -/
lemma bot_eq_top_of_finrank_adjoin_le_one [finite_dimensional F E]
(h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : (⊥ : intermediate_field F E) = ⊤ :=
begin
apply bot_eq_top_of_finrank_adjoin_eq_one,
exact λ x, by linarith [h x, show 0 < finrank F F⟮x⟯, from finrank_pos],
end
lemma subsingleton_of_finrank_adjoin_le_one [finite_dimensional F E]
(h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : subsingleton (intermediate_field F E) :=
subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_le_one h)
end adjoin_dim
end adjoin_intermediate_field_lattice
section adjoin_integral_element
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E}
variables {K : Type*} [field K] [algebra F K]
lemma minpoly_gen {α : E} (h : is_integral F α) :
minpoly F (adjoin_simple.gen F α) = minpoly F α :=
begin
rw ← adjoin_simple.algebra_map_gen F α at h,
have inj := (algebra_map F⟮α⟯ E).injective,
exact minpoly.eq_of_algebra_map_eq inj ((is_integral_algebra_map_iff inj).mp h)
(adjoin_simple.algebra_map_gen _ _).symm
end
variables (F)
lemma aeval_gen_minpoly (α : E) :
aeval (adjoin_simple.gen F α) (minpoly F α) = 0 :=
begin
ext,
convert minpoly.aeval F α,
conv in (aeval α) { rw [← adjoin_simple.algebra_map_gen F α] },
exact is_scalar_tower.algebra_map_aeval F F⟮α⟯ E _ _
end
/-- algebra isomorphism between `adjoin_root` and `F⟮α⟯` -/
noncomputable def adjoin_root_equiv_adjoin (h : is_integral F α) :
adjoin_root (minpoly F α) ≃ₐ[F] F⟮α⟯ :=
alg_equiv.of_bijective
(adjoin_root.lift_hom (minpoly F α) (adjoin_simple.gen F α) (aeval_gen_minpoly F α))
(begin
set f := adjoin_root.lift _ _ (aeval_gen_minpoly F α : _),
haveI := minpoly.irreducible h,
split,
{ exact ring_hom.injective f },
{ suffices : F⟮α⟯.to_subfield ≤ ring_hom.field_range ((F⟮α⟯.to_subfield.subtype).comp f),
{ exact λ x, Exists.cases_on (this (subtype.mem x)) (λ y hy, ⟨y, subtype.ext hy⟩) },
exact subfield.closure_le.mpr (set.union_subset (λ x hx, Exists.cases_on hx (λ y hy,
⟨y, by { rw [ring_hom.comp_apply, adjoin_root.lift_of], exact hy }⟩))
(set.singleton_subset_iff.mpr ⟨adjoin_root.root (minpoly F α),
by { rw [ring_hom.comp_apply, adjoin_root.lift_root], refl }⟩)) } end)
lemma adjoin_root_equiv_adjoin_apply_root (h : is_integral F α) :
adjoin_root_equiv_adjoin F h (adjoin_root.root (minpoly F α)) =
adjoin_simple.gen F α :=
adjoin_root.lift_root (aeval_gen_minpoly F α)
section power_basis
variables {L : Type*} [field L] [algebra K L]
/-- The elements `1, x, ..., x ^ (d - 1)` form a basis for `K⟮x⟯`,
where `d` is the degree of the minimal polynomial of `x`. -/
noncomputable def power_basis_aux {x : L} (hx : is_integral K x) :
basis (fin (minpoly K x).nat_degree) K K⟮x⟯ :=
(adjoin_root.power_basis (minpoly.ne_zero hx)).basis.map
(adjoin_root_equiv_adjoin K hx).to_linear_equiv
/-- The power basis `1, x, ..., x ^ (d - 1)` for `K⟮x⟯`,
where `d` is the degree of the minimal polynomial of `x`. -/
@[simps]
noncomputable def adjoin.power_basis {x : L} (hx : is_integral K x) :
power_basis K K⟮x⟯ :=
{ gen := adjoin_simple.gen K x,
dim := (minpoly K x).nat_degree,
basis := power_basis_aux hx,
basis_eq_pow := λ i,
by rw [power_basis_aux, basis.map_apply, power_basis.basis_eq_pow,
alg_equiv.to_linear_equiv_apply, alg_equiv.map_pow, adjoin_root.power_basis_gen,
adjoin_root_equiv_adjoin_apply_root] }
lemma adjoin.finite_dimensional {x : L} (hx : is_integral K x) : finite_dimensional K K⟮x⟯ :=
power_basis.finite_dimensional (adjoin.power_basis hx)
lemma adjoin.finrank {x : L} (hx : is_integral K x) :
finite_dimensional.finrank K K⟮x⟯ = (minpoly K x).nat_degree :=
begin
rw power_basis.finrank (adjoin.power_basis hx : _),
refl
end
end power_basis
/-- Algebra homomorphism `F⟮α⟯ →ₐ[F] K` are in bijection with the set of roots
of `minpoly α` in `K`. -/
noncomputable def alg_hom_adjoin_integral_equiv (h : is_integral F α) :
(F⟮α⟯ →ₐ[F] K) ≃ {x // x ∈ ((minpoly F α).map (algebra_map F K)).roots} :=
(adjoin.power_basis h).lift_equiv'.trans ((equiv.refl _).subtype_equiv (λ x,
by rw [adjoin.power_basis_gen, minpoly_gen h, equiv.refl_apply]))
/-- Fintype of algebra homomorphism `F⟮α⟯ →ₐ[F] K` -/
noncomputable def fintype_of_alg_hom_adjoin_integral (h : is_integral F α) :
fintype (F⟮α⟯ →ₐ[F] K) :=
power_basis.alg_hom.fintype (adjoin.power_basis h)
lemma card_alg_hom_adjoin_integral (h : is_integral F α) (h_sep : (minpoly F α).separable)
(h_splits : (minpoly F α).splits (algebra_map F K)) :
@fintype.card (F⟮α⟯ →ₐ[F] K) (fintype_of_alg_hom_adjoin_integral F h) =
(minpoly F α).nat_degree :=
begin
rw alg_hom.card_of_power_basis;
simp only [adjoin.power_basis_dim, adjoin.power_basis_gen, minpoly_gen h, h_sep, h_splits],
end
end adjoin_integral_element
section induction
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E]
/-- An intermediate field `S` is finitely generated if there exists `t : finset E` such that
`intermediate_field.adjoin F t = S`. -/
def fg (S : intermediate_field F E) : Prop := ∃ (t : finset E), adjoin F ↑t = S
lemma fg_adjoin_finset (t : finset E) : (adjoin F (↑t : set E)).fg :=
⟨t, rfl⟩
theorem fg_def {S : intermediate_field F E} : S.fg ↔ ∃ t : set E, set.finite t ∧ adjoin F t = S :=
⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩,
λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩
theorem fg_bot : (⊥ : intermediate_field F E).fg :=
⟨∅, adjoin_empty F E⟩
lemma fg_of_fg_to_subalgebra (S : intermediate_field F E)
(h : S.to_subalgebra.fg) : S.fg :=
begin
cases h with t ht,
exact ⟨t, (eq_adjoin_of_eq_algebra_adjoin _ _ _ ht.symm).symm⟩
end
lemma fg_of_noetherian (S : intermediate_field F E)
[is_noetherian F E] : S.fg :=
S.fg_of_fg_to_subalgebra S.to_subalgebra.fg_of_noetherian
lemma induction_on_adjoin_finset (S : finset E) (P : intermediate_field F E → Prop) (base : P ⊥)
(ih : ∀ (K : intermediate_field F E) (x ∈ S), P K → P ↑K⟮x⟯) : P (adjoin F ↑S) :=
begin
apply finset.induction_on' S,
{ exact base },
{ intros a s h1 _ _ h4,
rw [finset.coe_insert, set.insert_eq, set.union_comm, ←adjoin_adjoin_left],
exact ih (adjoin F s) a h1 h4 }
end
lemma induction_on_adjoin_fg (P : intermediate_field F E → Prop)
(base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯)
(K : intermediate_field F E) (hK : K.fg) : P K :=
begin
obtain ⟨S, rfl⟩ := hK,
exact induction_on_adjoin_finset S P base (λ K x _ hK, ih K x hK),
end
lemma induction_on_adjoin [fd : finite_dimensional F E] (P : intermediate_field F E → Prop)
(base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯)
(K : intermediate_field F E) : P K :=
begin
letI : is_noetherian F E := is_noetherian.iff_fg.2 infer_instance,
exact induction_on_adjoin_fg P base ih K K.fg_of_noetherian
end
end induction
section alg_hom_mk_adjoin_splits
variables (F E K : Type*) [field F] [field E] [field K] [algebra F E] [algebra F K] {S : set E}
/-- Lifts `L → K` of `F → K` -/
def lifts := Σ (L : intermediate_field F E), (L →ₐ[F] K)
variables {F E K}
instance : partial_order (lifts F E K) :=
{ le := λ x y, x.1 ≤ y.1 ∧ (∀ (s : x.1) (t : y.1), (s : E) = t → x.2 s = y.2 t),
le_refl := λ x, ⟨le_refl x.1, λ s t hst, congr_arg x.2 (subtype.ext hst)⟩,
le_trans := λ x y z hxy hyz, ⟨le_trans hxy.1 hyz.1, λ s u hsu, eq.trans
(hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl) (hyz.2 ⟨s, hxy.1 s.mem⟩ u hsu)⟩,
le_antisymm :=
begin
rintros ⟨x1, x2⟩ ⟨y1, y2⟩ ⟨hxy1, hxy2⟩ ⟨hyx1, hyx2⟩,
have : x1 = y1 := le_antisymm hxy1 hyx1,
subst this,
congr,
exact alg_hom.ext (λ s, hxy2 s s rfl),
end }
noncomputable instance : order_bot (lifts F E K) :=
{ bot := ⟨⊥, (algebra.of_id F K).comp (bot_equiv F E).to_alg_hom⟩,
bot_le := λ x, ⟨bot_le, λ s t hst,
begin
cases intermediate_field.mem_bot.mp s.mem with u hu,
rw [show s = (algebra_map F _) u, from subtype.ext hu.symm, alg_hom.commutes],
rw [show t = (algebra_map F _) u, from subtype.ext (eq.trans hu hst).symm, alg_hom.commutes],
end⟩ }
noncomputable instance : inhabited (lifts F E K) := ⟨⊥⟩
lemma lifts.eq_of_le {x y : lifts F E K} (hxy : x ≤ y) (s : x.1) :
x.2 s = y.2 ⟨s, hxy.1 s.mem⟩ := hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl
lemma lifts.exists_max_two {c : set (lifts F E K)} {x y : lifts F E K} (hc : zorn.chain (≤) c)
(hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) :
∃ z : lifts F E K, z ∈ set.insert ⊥ c ∧ x ≤ z ∧ y ≤ z :=
begin
cases (zorn.chain_insert hc (λ _ _ _, or.inl bot_le)).total_of_refl hx hy with hxy hyx,
{ exact ⟨y, hy, hxy, le_refl y⟩ },
{ exact ⟨x, hx, le_refl x, hyx⟩ },
end
lemma lifts.exists_max_three {c : set (lifts F E K)} {x y z : lifts F E K} (hc : zorn.chain (≤) c)
(hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) (hz : z ∈ set.insert ⊥ c) :
∃ w : lifts F E K, w ∈ set.insert ⊥ c ∧ x ≤ w ∧ y ≤ w ∧ z ≤ w :=
begin
obtain ⟨v, hv, hxv, hyv⟩ := lifts.exists_max_two hc hx hy,
obtain ⟨w, hw, hzw, hvw⟩ := lifts.exists_max_two hc hz hv,
exact ⟨w, hw, le_trans hxv hvw, le_trans hyv hvw, hzw⟩,
end
/-- An upper bound on a chain of lifts -/
def lifts.upper_bound_intermediate_field {c : set (lifts F E K)} (hc : zorn.chain (≤) c) :
intermediate_field F E :=
{ carrier := λ s, ∃ x : (lifts F E K), x ∈ set.insert ⊥ c ∧ (s ∈ x.1 : Prop),
zero_mem' := ⟨⊥, set.mem_insert ⊥ c, zero_mem ⊥⟩,
one_mem' := ⟨⊥, set.mem_insert ⊥ c, one_mem ⊥⟩,
neg_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.neg_mem h⟩⟩ },
inv_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.inv_mem h⟩⟩ },
add_mem' := by
{ rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩,
obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy,
exact ⟨z, hz, z.1.add_mem (hxz.1 ha) (hyz.1 hb)⟩ },
mul_mem' := by
{ rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩,
obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy,
exact ⟨z, hz, z.1.mul_mem (hxz.1 ha) (hyz.1 hb)⟩ },
algebra_map_mem' := λ s, ⟨⊥, set.mem_insert ⊥ c, algebra_map_mem ⊥ s⟩ }
/-- The lift on the upper bound on a chain of lifts -/
noncomputable def lifts.upper_bound_alg_hom {c : set (lifts F E K)} (hc : zorn.chain (≤) c) :
lifts.upper_bound_intermediate_field hc →ₐ[F] K :=
{ to_fun := λ s, (classical.some s.mem).2 ⟨s, (classical.some_spec s.mem).2⟩,
map_zero' := alg_hom.map_zero _,
map_one' := alg_hom.map_one _,
map_add' := λ s t, begin
obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc
(classical.some_spec s.mem).1 (classical.some_spec t.mem).1
(classical.some_spec (s + t).mem).1,
rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_add],
refl,
end,
map_mul' := λ s t, begin
obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc
(classical.some_spec s.mem).1 (classical.some_spec t.mem).1
(classical.some_spec (s * t).mem).1,
rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_mul],
refl,
end,
commutes' := λ _, alg_hom.commutes _ _ }
/-- An upper bound on a chain of lifts -/
noncomputable def lifts.upper_bound {c : set (lifts F E K)} (hc : zorn.chain (≤) c) :
lifts F E K :=
⟨lifts.upper_bound_intermediate_field hc, lifts.upper_bound_alg_hom hc⟩
lemma lifts.exists_upper_bound (c : set (lifts F E K)) (hc : zorn.chain (≤) c) :
∃ ub, ∀ a ∈ c, a ≤ ub :=
⟨lifts.upper_bound hc,
begin
intros x hx,
split,
{ exact λ s hs, ⟨x, set.mem_insert_of_mem ⊥ hx, hs⟩ },
{ intros s t hst,
change x.2 s = (classical.some t.mem).2 ⟨t, (classical.some_spec t.mem).2⟩,
obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc (set.mem_insert_of_mem ⊥ hx)
(classical.some_spec t.mem).1,
rw [lifts.eq_of_le hxz, lifts.eq_of_le hyz],
exact congr_arg z.2 (subtype.ext hst) },
end⟩
/-- Extend a lift `x : lifts F E K` to an element `s : E` whose conjugates are all in `K` -/
noncomputable def lifts.lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s)
(h2 : (minpoly F s).splits (algebra_map F K)) : lifts F E K :=
let h3 : is_integral x.1 s := is_integral_of_is_scalar_tower s h1 in
let key : (minpoly x.1 s).splits x.2.to_ring_hom :=
splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero h1))
((splits_map_iff _ _).mpr (by {convert h2, exact ring_hom.ext (λ y, x.2.commutes y)}))
(minpoly.dvd_map_of_is_scalar_tower _ _ _) in
⟨↑x.1⟮s⟯, (@alg_hom_equiv_sigma F x.1 (↑x.1⟮s⟯ : intermediate_field F E) K _ _ _ _ _ _ _
(intermediate_field.algebra x.1⟮s⟯) (is_scalar_tower.of_algebra_map_eq (λ _, rfl))).inv_fun
⟨x.2, (@alg_hom_adjoin_integral_equiv x.1 _ E _ _ s K _ x.2.to_ring_hom.to_algebra
h3).inv_fun ⟨root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)), by {
simp_rw [mem_roots (map_ne_zero (minpoly.ne_zero h3)), is_root, ←eval₂_eq_eval_map],
exact map_root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)) }⟩⟩⟩
lemma lifts.le_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s)
(h2 : (minpoly F s).splits (algebra_map F K)) : x ≤ x.lift_of_splits h1 h2 :=
⟨λ z hz, algebra_map_mem x.1⟮s⟯ ⟨z, hz⟩, λ t u htu, eq.symm begin
rw [←(show algebra_map x.1 x.1⟮s⟯ t = u, from subtype.ext htu)],
letI : algebra x.1 K := x.2.to_ring_hom.to_algebra,
exact (alg_hom.commutes _ t),
end⟩
lemma lifts.mem_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s)
(h2 : (minpoly F s).splits (algebra_map F K)) : s ∈ (x.lift_of_splits h1 h2).1 :=
mem_adjoin_simple_self x.1 s
lemma lifts.exists_lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s)
(h2 : (minpoly F s).splits (algebra_map F K)) : ∃ y, x ≤ y ∧ s ∈ y.1 :=
⟨x.lift_of_splits h1 h2, x.le_lifts_of_splits h1 h2, x.mem_lifts_of_splits h1 h2⟩
lemma alg_hom_mk_adjoin_splits
(hK : ∀ s ∈ S, is_integral F (s : E) ∧ (minpoly F s).splits (algebra_map F K)) :
nonempty (adjoin F S →ₐ[F] K) :=
begin
obtain ⟨x : lifts F E K, hx⟩ := zorn.zorn_partial_order lifts.exists_upper_bound,
refine ⟨alg_hom.mk (λ s, x.2 ⟨s, adjoin_le_iff.mpr (λ s hs, _) s.mem⟩) x.2.map_one (λ s t,
x.2.map_mul ⟨s, _⟩ ⟨t, _⟩) x.2.map_zero (λ s t, x.2.map_add ⟨s, _⟩ ⟨t, _⟩) x.2.commutes⟩,
rcases (x.exists_lift_of_splits (hK s hs).1 (hK s hs).2) with ⟨y, h1, h2⟩,
rwa hx y h1 at h2
end
lemma alg_hom_mk_adjoin_splits' (hS : adjoin F S = ⊤)
(hK : ∀ x ∈ S, is_integral F (x : E) ∧ (minpoly F x).splits (algebra_map F K)) :
nonempty (E →ₐ[F] K) :=
begin
cases alg_hom_mk_adjoin_splits hK with ϕ,
rw hS at ϕ,
exact ⟨ϕ.comp top_equiv.symm.to_alg_hom⟩,
end
end alg_hom_mk_adjoin_splits
end intermediate_field
section power_basis
variables {K L : Type*} [field K] [field L] [algebra K L]
namespace power_basis
open intermediate_field
/-- `pb.equiv_adjoin_simple` is the equivalence between `K⟮pb.gen⟯` and `L` itself. -/
noncomputable def equiv_adjoin_simple (pb : power_basis K L) :
K⟮pb.gen⟯ ≃ₐ[K] L :=
(adjoin.power_basis pb.is_integral_gen).equiv_of_minpoly pb
(minpoly.eq_of_algebra_map_eq (algebra_map K⟮pb.gen⟯ L).injective
(adjoin.power_basis pb.is_integral_gen).is_integral_gen
(by rw [adjoin.power_basis_gen, adjoin_simple.algebra_map_gen]))
@[simp]
lemma equiv_adjoin_simple_aeval (pb : power_basis K L) (f : polynomial K) :
pb.equiv_adjoin_simple (aeval (adjoin_simple.gen K pb.gen) f) = aeval pb.gen f :=
equiv_of_minpoly_aeval _ pb _ f
@[simp]
lemma equiv_adjoin_simple_gen (pb : power_basis K L) :
pb.equiv_adjoin_simple (adjoin_simple.gen K pb.gen) = pb.gen :=
equiv_of_minpoly_gen _ pb _
@[simp]
lemma equiv_adjoin_simple_symm_aeval (pb : power_basis K L) (f : polynomial K) :
pb.equiv_adjoin_simple.symm (aeval pb.gen f) = aeval (adjoin_simple.gen K pb.gen) f :=
by rw [equiv_adjoin_simple, equiv_of_minpoly_symm, equiv_of_minpoly_aeval, adjoin.power_basis_gen]
@[simp]
lemma equiv_adjoin_simple_symm_gen (pb : power_basis K L) :
pb.equiv_adjoin_simple.symm pb.gen = (adjoin_simple.gen K pb.gen) :=
by rw [equiv_adjoin_simple, equiv_of_minpoly_symm, equiv_of_minpoly_gen, adjoin.power_basis_gen]
end power_basis
end power_basis
|
7497f742faee55a5a6ae606b5789ea22df4724ea | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/invertible.lean | e7bf9715b372412fc0520dd48158567c0549e680 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 10,411 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import algebra.group.units
import algebra.ring.basic
/-!
# Invertible elements
This file defines a typeclass `invertible a` for elements `a` with a two-sided
multiplicative inverse.
The intent of the typeclass is to provide a way to write e.g. `⅟2` in a ring
like `ℤ[1/2]` where some inverses exist but there is no general `⁻¹` operator;
or to specify that a field has characteristic `≠ 2`.
It is the `Type`-valued analogue to the `Prop`-valued `is_unit`.
For constructions of the invertible element given a characteristic, see
`algebra/char_p/invertible` and other lemmas in that file.
## Notation
* `⅟a` is `invertible.inv_of a`, the inverse of `a`
## Implementation notes
The `invertible` class lives in `Type`, not `Prop`, to make computation easier.
If multiplication is associative, `invertible` is a subsingleton anyway.
The `simp` normal form tries to normalize `⅟a` to `a ⁻¹`. Otherwise, it pushes
`⅟` inside the expression as much as possible.
Since `invertible a` is not a `Prop` (but it is a `subsingleton`), we have to be careful about
coherence issues: we should avoid having multiple non-defeq instances for `invertible a` in the
same context. This file plays it safe and uses `def` rather than `instance` for most definitions,
users can choose which instances to use at the point of use.
For example, here's how you can use an `invertible 1` instance:
```lean
variables {α : Type*} [monoid α]
def something_that_needs_inverses (x : α) [invertible x] := sorry
section
local attribute [instance] invertible_one
def something_one := something_that_needs_inverses 1
end
```
## Tags
invertible, inverse element, inv_of, a half, one half, a third, one third, ½, ⅓
-/
universes u
variables {α : Type u}
/-- `invertible a` gives a two-sided multiplicative inverse of `a`. -/
class invertible [has_mul α] [has_one α] (a : α) : Type u :=
(inv_of : α) (inv_of_mul_self : inv_of * a = 1) (mul_inv_of_self : a * inv_of = 1)
-- This notation has the same precedence as `has_inv.inv`.
notation `⅟`:1034 := invertible.inv_of
@[simp]
lemma inv_of_mul_self [has_mul α] [has_one α] (a : α) [invertible a] : ⅟a * a = 1 :=
invertible.inv_of_mul_self
@[simp]
lemma mul_inv_of_self [has_mul α] [has_one α] (a : α) [invertible a] : a * ⅟a = 1 :=
invertible.mul_inv_of_self
@[simp]
lemma inv_of_mul_self_assoc [monoid α] (a b : α) [invertible a] : ⅟a * (a * b) = b :=
by rw [←mul_assoc, inv_of_mul_self, one_mul]
@[simp]
lemma mul_inv_of_self_assoc [monoid α] (a b : α) [invertible a] : a * (⅟a * b) = b :=
by rw [←mul_assoc, mul_inv_of_self, one_mul]
@[simp]
lemma mul_inv_of_mul_self_cancel [monoid α] (a b : α) [invertible b] : a * ⅟b * b = a :=
by simp [mul_assoc]
@[simp]
lemma mul_mul_inv_of_self_cancel [monoid α] (a b : α) [invertible b] : a * b * ⅟b = a :=
by simp [mul_assoc]
lemma inv_of_eq_right_inv [monoid α] {a b : α} [invertible a] (hac : a * b = 1) : ⅟a = b :=
left_inv_eq_right_inv (inv_of_mul_self _) hac
lemma inv_of_eq_left_inv [monoid α] {a b : α} [invertible a] (hac : b * a = 1) : ⅟a = b :=
(left_inv_eq_right_inv hac (mul_inv_of_self _)).symm
lemma invertible_unique {α : Type u} [monoid α] (a b : α) [invertible a] [invertible b]
(h : a = b) :
⅟a = ⅟b :=
by { apply inv_of_eq_right_inv, rw [h, mul_inv_of_self], }
instance [monoid α] (a : α) : subsingleton (invertible a) :=
⟨ λ ⟨b, hba, hab⟩ ⟨c, hca, hac⟩, by { congr, exact left_inv_eq_right_inv hba hac } ⟩
/-- If `r` is invertible and `s = r`, then `s` is invertible. -/
def invertible.copy [monoid α] {r : α} (hr : invertible r) (s : α) (hs : s = r) : invertible s :=
{ inv_of := ⅟r,
inv_of_mul_self := by rw [hs, inv_of_mul_self],
mul_inv_of_self := by rw [hs, mul_inv_of_self] }
/-- An `invertible` element is a unit. -/
@[simps]
def unit_of_invertible [monoid α] (a : α) [invertible a] : αˣ :=
{ val := a,
inv := ⅟a,
val_inv := by simp,
inv_val := by simp, }
lemma is_unit_of_invertible [monoid α] (a : α) [invertible a] : is_unit a :=
⟨unit_of_invertible a, rfl⟩
/-- Units are invertible in their associated monoid. -/
def units.invertible [monoid α] (u : αˣ) : invertible (u : α) :=
{ inv_of := ↑(u⁻¹), inv_of_mul_self := u.inv_mul, mul_inv_of_self := u.mul_inv }
@[simp] lemma inv_of_units [monoid α] (u : αˣ) [invertible (u : α)] : ⅟(u : α) = ↑(u⁻¹) :=
inv_of_eq_right_inv u.mul_inv
lemma is_unit.nonempty_invertible [monoid α] {a : α} (h : is_unit a) : nonempty (invertible a) :=
let ⟨x, hx⟩ := h in ⟨x.invertible.copy _ hx.symm⟩
/-- Convert `is_unit` to `invertible` using `classical.choice`.
Prefer `casesI h.nonempty_invertible` over `letI := h.invertible` if you want to avoid choice. -/
noncomputable def is_unit.invertible [monoid α] {a : α} (h : is_unit a) : invertible a :=
classical.choice h.nonempty_invertible
@[simp] lemma nonempty_invertible_iff_is_unit [monoid α] (a : α) :
nonempty (invertible a) ↔ is_unit a :=
⟨nonempty.rec $ @is_unit_of_invertible _ _ _, is_unit.nonempty_invertible⟩
/-- Each element of a group is invertible. -/
def invertible_of_group [group α] (a : α) : invertible a :=
⟨a⁻¹, inv_mul_self a, mul_inv_self a⟩
@[simp] lemma inv_of_eq_group_inv [group α] (a : α) [invertible a] : ⅟a = a⁻¹ :=
inv_of_eq_right_inv (mul_inv_self a)
/-- `1` is the inverse of itself -/
def invertible_one [monoid α] : invertible (1 : α) :=
⟨1, mul_one _, one_mul _⟩
@[simp] lemma inv_of_one [monoid α] [invertible (1 : α)] : ⅟(1 : α) = 1 :=
inv_of_eq_right_inv (mul_one _)
/-- `-⅟a` is the inverse of `-a` -/
def invertible_neg [has_mul α] [has_one α] [has_distrib_neg α] (a : α) [invertible a] :
invertible (-a) := ⟨-⅟a, by simp, by simp ⟩
@[simp] lemma inv_of_neg [monoid α] [has_distrib_neg α] (a : α) [invertible a] [invertible (-a)] :
⅟(-a) = -⅟a :=
inv_of_eq_right_inv (by simp)
@[simp] lemma one_sub_inv_of_two [ring α] [invertible (2:α)] : 1 - (⅟2:α) = ⅟2 :=
(is_unit_of_invertible (2:α)).mul_right_inj.1 $
by rw [mul_sub, mul_inv_of_self, mul_one, bit0, add_sub_cancel]
@[simp] lemma inv_of_two_add_inv_of_two [non_assoc_semiring α] [invertible (2 : α)] :
(⅟2 : α) + (⅟2 : α) = 1 :=
by rw [←two_mul, mul_inv_of_self]
/-- `a` is the inverse of `⅟a`. -/
instance invertible_inv_of [has_one α] [has_mul α] {a : α} [invertible a] : invertible (⅟a) :=
⟨ a, mul_inv_of_self a, inv_of_mul_self a ⟩
@[simp] lemma inv_of_inv_of [monoid α] (a : α) [invertible a] [invertible (⅟a)] : ⅟(⅟a) = a :=
inv_of_eq_right_inv (inv_of_mul_self _)
@[simp] lemma inv_of_inj [monoid α] {a b : α} [invertible a] [invertible b] :
⅟ a = ⅟ b ↔ a = b :=
⟨invertible_unique _ _, invertible_unique _ _⟩
/-- `⅟b * ⅟a` is the inverse of `a * b` -/
def invertible_mul [monoid α] (a b : α) [invertible a] [invertible b] : invertible (a * b) :=
⟨ ⅟b * ⅟a, by simp [←mul_assoc], by simp [←mul_assoc] ⟩
@[simp] lemma inv_of_mul [monoid α] (a b : α) [invertible a] [invertible b] [invertible (a * b)] :
⅟(a * b) = ⅟b * ⅟a :=
inv_of_eq_right_inv (by simp [←mul_assoc])
theorem commute.inv_of_right [monoid α] {a b : α} [invertible b] (h : commute a b) :
commute a (⅟b) :=
calc a * (⅟b) = (⅟b) * (b * a * (⅟b)) : by simp [mul_assoc]
... = (⅟b) * (a * b * ((⅟b))) : by rw h.eq
... = (⅟b) * a : by simp [mul_assoc]
theorem commute.inv_of_left [monoid α] {a b : α} [invertible b] (h : commute b a) :
commute (⅟b) a :=
calc (⅟b) * a = (⅟b) * (a * b * (⅟b)) : by simp [mul_assoc]
... = (⅟b) * (b * a * (⅟b)) : by rw h.eq
... = a * (⅟b) : by simp [mul_assoc]
lemma commute_inv_of {M : Type*} [has_one M] [has_mul M] (m : M) [invertible m] :
commute m (⅟m) :=
calc m * ⅟m = 1 : mul_inv_of_self m
... = ⅟ m * m : (inv_of_mul_self m).symm
lemma nonzero_of_invertible [mul_zero_one_class α] (a : α) [nontrivial α] [invertible a] : a ≠ 0 :=
λ ha, zero_ne_one $ calc 0 = ⅟a * a : by simp [ha]
... = 1 : inv_of_mul_self a
section monoid_with_zero
variable [monoid_with_zero α]
/-- A variant of `ring.inverse_unit`. -/
@[simp] lemma ring.inverse_invertible (x : α) [invertible x] : ring.inverse x = ⅟x :=
ring.inverse_unit (unit_of_invertible _)
end monoid_with_zero
section group_with_zero
variable [group_with_zero α]
/-- `a⁻¹` is an inverse of `a` if `a ≠ 0` -/
def invertible_of_nonzero {a : α} (h : a ≠ 0) : invertible a :=
⟨ a⁻¹, inv_mul_cancel h, mul_inv_cancel h ⟩
@[simp] lemma inv_of_eq_inv (a : α) [invertible a] : ⅟a = a⁻¹ :=
inv_of_eq_right_inv (mul_inv_cancel (nonzero_of_invertible a))
@[simp] lemma inv_mul_cancel_of_invertible (a : α) [invertible a] : a⁻¹ * a = 1 :=
inv_mul_cancel (nonzero_of_invertible a)
@[simp] lemma mul_inv_cancel_of_invertible (a : α) [invertible a] : a * a⁻¹ = 1 :=
mul_inv_cancel (nonzero_of_invertible a)
@[simp] lemma div_mul_cancel_of_invertible (a b : α) [invertible b] : a / b * b = a :=
div_mul_cancel a (nonzero_of_invertible b)
@[simp] lemma mul_div_cancel_of_invertible (a b : α) [invertible b] : a * b / b = a :=
mul_div_cancel a (nonzero_of_invertible b)
@[simp] lemma div_self_of_invertible (a : α) [invertible a] : a / a = 1 :=
div_self (nonzero_of_invertible a)
/-- `b / a` is the inverse of `a / b` -/
def invertible_div (a b : α) [invertible a] [invertible b] : invertible (a / b) :=
⟨b / a, by simp [←mul_div_assoc], by simp [←mul_div_assoc]⟩
@[simp] lemma inv_of_div (a b : α) [invertible a] [invertible b] [invertible (a / b)] :
⅟(a / b) = b / a :=
inv_of_eq_right_inv (by simp [←mul_div_assoc])
/-- `a` is the inverse of `a⁻¹` -/
def invertible_inv {a : α} [invertible a] : invertible (a⁻¹) :=
⟨ a, by simp, by simp ⟩
end group_with_zero
/-- Monoid homs preserve invertibility. -/
def invertible.map {R : Type*} {S : Type*} {F : Type*} [mul_one_class R] [mul_one_class S]
[monoid_hom_class F R S] (f : F) (r : R) [invertible r] :
invertible (f r) :=
{ inv_of := f (⅟r),
inv_of_mul_self := by rw [←map_mul, inv_of_mul_self, map_one],
mul_inv_of_self := by rw [←map_mul, mul_inv_of_self, map_one] }
|
538170a2f7f8849a2cf2aa3ce202d844cd973b92 | 947b78d97130d56365ae2ec264df196ce769371a | /src/Init/Data/String/Extra.lean | 7b3de051a77c7fb3a91101faa5c5cfec8821b0bf | [
"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 | 743 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.Control.Except
import Init.Data.ByteArray
import Init.Util
namespace String
def toNat! (s : String) : Nat :=
if s.isNat then
s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0
else
panic! "Nat expected"
/--
Convert a UTF-8 encoded `ByteArray` string to `String`.
The result is unspecified if `a` is not properly UTF-8 encoded. -/
@[extern "lean_string_from_utf8_unchecked"]
constant fromUTF8Unchecked (a : @& ByteArray) : String := arbitrary _
@[extern "lean_string_to_utf8"]
constant toUTF8 (a : @& String) : ByteArray := arbitrary _
end String
|
1a78dbeefecd03d62b2127406f422ceada370ae5 | 5749d8999a76f3a8fddceca1f6941981e33aaa96 | /src/tactic/core.lean | a871a011708e079c8e3606e1037421bf416aa836 | [
"Apache-2.0"
] | permissive | jdsalchow/mathlib | 13ab43ef0d0515a17e550b16d09bd14b76125276 | 497e692b946d93906900bb33a51fd243e7649406 | refs/heads/master | 1,585,819,143,348 | 1,580,072,892,000 | 1,580,072,892,000 | 154,287,128 | 0 | 0 | Apache-2.0 | 1,540,281,610,000 | 1,540,281,609,000 | null | UTF-8 | Lean | false | false | 56,760 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek
-/
import data.dlist.basic category.basic meta.expr meta.rb_map data.bool tactic.library_note
namespace expr
open tactic
attribute [derive has_reflect] binder_info
/-- Given an expr `α` representing a type with numeral structure,
`of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (α : expr) : ℕ → tactic expr :=
nat.binary_rec
(tactic.mk_mapp ``has_zero.zero [some α, none])
(λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else
do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])
/-- Given an expr `α` representing a type with numeral structure,
`of_int α n` creates the `α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (α : expr) : ℤ → tactic expr
| (n : ℕ) := expr.of_nat α n
| -[1+ n] := do
e ← expr.of_nat α (n+1),
tactic.mk_app ``has_neg.neg [e]
/-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local
constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/
meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=
args.mfoldr (λarg i:expr, do
t ← infer_type arg,
sort l ← infer_type t,
return $ if arg.occurs i ∨ l ≠ level.zero
then (const `Exists [l] : expr) t (i.lambdas [arg])
else (const `and [] : expr) t i)
inner
/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/
meta def {u} traverse {m : Type → Type u} [applicative m]
{elab elab' : bool} (f : expr elab → m (expr elab')) :
expr elab → m (expr elab')
| (var v) := pure $ var v
| (sort l) := pure $ sort l
| (const n ls) := pure $ const n ls
| (mvar n n' e) := mvar n n' <$> f e
| (local_const n n' bi e) := local_const n n' bi <$> f e
| (app e₀ e₁) := app <$> f e₀ <*> f e₁
| (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁
| (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁
| (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂
| (macro mac es) := macro mac <$> list.traverse f es
/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,
with initial value `a`. -/
meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α
| x e := prod.snd <$> (state_t.run (e.traverse $ λ e',
(get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _)
end expr
namespace interaction_monad
open result
/-- `get_result tac` returns the result state of applying `tac` to the current state.
Note that it does not update the current state. -/
meta def get_result {σ α} (tac : interaction_monad σ α) :
interaction_monad σ (interaction_monad.result σ α) | s :=
match tac s with
| r@(success _ s') := success r s'
| r@(exception _ _ s') := success r s'
end
end interaction_monad
namespace lean.parser
open lean interaction_monad.result
/-- `of_tactic' tac` lifts the tactic `tac` into the parser monad.
This replaces `of_tactic` in core, which has a buggy implementation. -/
meta def of_tactic' {α} (tac : tactic α) : parser α :=
do r ← of_tactic (interaction_monad.get_result tac),
match r with
| (success a _) := return a
| (exception f pos _) := exception f pos
end
/-- Override the builtin `lean.parser.of_tactic` coe, which is broken.
(See test/tactics.lean for a failure case.) -/
@[priority 2000]
meta instance has_coe' {α} : has_coe (tactic α) (parser α) :=
⟨of_tactic'⟩
/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the
current line. -/
meta def emit_command_here (str : string) : lean.parser string :=
do (_, left) ← with_input command_like str,
return left
/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in
source code. -/
meta def emit_code_here : string → lean.parser unit
| str := do left ← emit_command_here str,
if left.length = 0 then return ()
else emit_code_here left
end lean.parser
namespace format
/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,
where `.` represents `format.join`. -/
meta def intercalate (x : format) : list format → format :=
format.join ∘ list.intersperse x
end format
namespace tactic
open function
/-- `mk_local_pisn e n` instantiates the first `n` variables of a pi expression `e`,
and returns the new local constants along with the instantiated expression. Fails if `e` does
not begin with at least `n` pi binders. -/
meta def mk_local_pisn : expr → nat → tactic (list expr × expr)
| (expr.pi n bi d b) (c + 1) := do
p ← mk_local' n bi d,
(ps, r) ← mk_local_pisn (b.instantiate_var p) c,
return ((p :: ps), r)
| e 0 := return ([], e)
| _ _ := failed
-- TODO: move to `declaration` namespace in `meta/expr.lean`
/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named
`ls`, type `t`, and body `e`. -/
meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=
declaration.thm n ls t (task.pure e)
/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this
to the environment as a theorem with name `n` and universe parameters `ls`. -/
meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do
((), body) ← solve_aux type tac,
body ← instantiate_mvars body,
add_decl $ mk_theorem n ls type body,
return $ expr.const n $ ls.map level.param
/-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`.
This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare
situations the latter will fail but the former will succeed. -/
meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α :=
mk_app ``id [e] >>= eval_expr α
/-- `mk_fresh_name` returns identifiers starting with underscores,
which are not legal when emitted by tactic programs. `mk_user_fresh_name`
turns the useful source of random names provided by `mk_fresh_name` into
names which are usable by tactic programs.
The returned name has four components which are all strings. -/
meta def mk_user_fresh_name : tactic name :=
do nm ← mk_fresh_name,
return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__
/-- `has_attribute n n'` checks whether n' has attribute n. -/
meta def has_attribute' : name → name → tactic bool | n n' :=
succeeds (has_attribute n n')
/-- Checks whether the name is a simp lemma -/
meta def is_simp_lemma : name → tactic bool :=
has_attribute' `simp
/-- Checks whether the name is an instance. -/
meta def is_instance : name → tactic bool :=
has_attribute' `instance
/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.
Covers all declarations from the current file. -/
meta def local_decls : tactic (name_map declaration) :=
do e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s, if environment.in_current_file' e d.to_name
then s.insert d.to_name d else s),
pure xs
/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/
meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n :=
let nm' := nm.append_suffix ("_" ++ to_string n) in
if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm'
/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it
returns that, otherwise it tries nm_2, nm_3, ... -/
meta def get_unused_decl_name (nm : name) : tactic name :=
get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm
/--
Returns a pair (e, t), where `e ← mk_const d.to_name`, and `t = d.type`
but with universe params updated to match the fresh universe metavariables in `e`.
This should have the same effect as just
```
do e ← mk_const d.to_name,
t ← infer_type e,
return (e, t)
```
but is hopefully faster.
-/
meta def decl_mk_const (d : declaration) : tactic (expr × expr) :=
do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ,
let e : expr := expr.const d.to_name (prod.snd <$> subst),
return (e, d.type.instantiate_univ_params subst)
/-- `mk_local n` creates a dummy local variable with name `n`.
The type of this local constant is a constant with name `n`, so it is very unlikely to be
a meaningful expression. -/
meta def mk_local (n : name) : expr :=
expr.local_const n n binder_info.default (expr.const n [])
/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined
locally using a `let` expression. Otherwise it fails. -/
meta def local_def_value (e : expr) : tactic expr :=
do (v,_) ← solve_aux `(true) (do
(expr.elet n t v _) ← (revert e >> target)
| fail format!"{e} is not a local definition",
return v),
return v
/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with pi binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``pis [a, b] `(f a b)`` will return the expression
`Π (a : Ta) (b : Tb), f a b` -/
meta def pis : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← pis es f,
pure $ expr.pi pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with lambda binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``lambdas [a, b] `(f a b)`` will return the expression
`λ (a : Ta) (b : Tb), f a b` -/
meta def lambdas : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← lambdas es f,
pure $ expr.lam pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,
`y : ty x` and `z : tz x y`, creates an expression of sigma type: `⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`.
-/
meta def mk_psigma : list expr → tactic expr
| [] := mk_const ``punit
| [x@(expr.local_const _ _ _ _)] := pure x
| (x@(expr.local_const _ _ _ _) :: xs) :=
do y ← mk_psigma xs,
α ← infer_type x,
β ← infer_type y,
t ← lambdas [x] β >>= instantiate_mvars,
r ← mk_mapp ``psigma.mk [α,t],
pure $ r x y
| _ := fail "mk_psigma expects a list of local constants"
/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n` times
and uses `ns` to name the resulting variables. Returns a triple: list of new variables, remaining term
and unused variable names.
-/
meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name)
| 0 e hs ns := return (hs.reverse, e, ns)
| (n + 1) e hs ns := do
t ← infer_type e,
if t.is_app_of `eq then return (hs.reverse, e, ns)
else do
[(_, [h, h'], _)] ← cases_core e (ns.take 1),
elim_gen_prod n h' (h :: hs) (ns.drop 1)
private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr)
| 0 e hs := return (hs, e)
| (n + 1) e hs := do
[(_, [h], _), (_, [h'], _)] ← induction e [],
swap,
elim_gen_sum_aux n h' (h::hs)
/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose
type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`. -/
meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do
(hs, h') ← elim_gen_sum_aux n e [],
gs ← get_goals,
set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),
return $ hs.reverse ++ [h']
/-- Given `elab_def`, a tactic to solve the current goal,
`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it
to close the goal. If `trusted` is false, it will be a meta definition. -/
meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=
do cxt ← list.map expr.to_implicit_local_const <$> local_context,
t ← target,
(eqns,d) ← solve_aux t elab_def,
d ← instantiate_mvars d,
t' ← pis cxt t,
d' ← lambdas cxt d,
let univ := t'.collect_univ_params,
add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,
applyc n
/-- Attempts to close the goal with `dec_trivial`. -/
meta def exact_dec_trivial : tactic unit := `[exact dec_trivial]
/-- Runs a tactic for a result, reverting the state after completion -/
meta def retrieve {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
result.exception
/-- Repeat a tactic at least once, calling it recursively on all subgoals,
until it fails. This tactic fails if the first invocation fails. -/
meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t
/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and
at most `n` times or until `t` fails. Fails if `t` does not run at least m times. -/
meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit
| 0 0 t := skip
| 0 (n+1) t := try (t >> iterate_range 0 n t)
| (m+1) n t := t >> iterate_range m (n-1) t
/--
Given a tactic `tac` that takes an expression
and returns a new expression and a proof of equality,
use that tactic to change the type of the hypotheses listed in `hs`,
as well as the goal if `tgt = tt`.
Returns `tt` if any types were successfully changed.
-/
meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool :=
do to_remove ← hs.mfilter $ λ h, do {
h_type ← infer_type h,
succeeds $ do
(new_h_type, pr) ← tac h_type,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact },
goal_simplified ← succeeds $ do {
guard tgt,
(new_t, pr) ← target >>= tac,
replace_target new_t pr },
to_remove.mmap' (λ h, try (clear h)),
return (¬ to_remove.empty ∨ goal_simplified)
/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,
`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting
expression and a proof of equality. -/
meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) :
tactic (expr × expr) :=
prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg
/-- Caches unary type classes on a type `α : Type.{univ}` -/
meta structure instance_cache :=
(α : expr)
(univ : level)
(inst : name_map expr)
/-- Creates an `instance_cache` for the type `α` -/
meta def mk_instance_cache (α : expr) : tactic instance_cache :=
do u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
return ⟨α, u, mk_name_map⟩
namespace instance_cache
/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of
`n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance
via type class resolution, and updates the cache. -/
meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) :=
match c.inst.find n with
| some i := return (c, i)
| none := do e ← mk_app n [c.α] >>= mk_instance,
return (⟨c.α, c.univ, c.inst.insert n e⟩, e)
end
open expr
/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,
`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/
meta def append_typeclasses : expr → instance_cache → list expr →
tactic (instance_cache × list expr)
| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=
do (c, p) ← c.get n, return (c, p :: l)
| _ c l := return (c, l)
/-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`. -/
meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) :=
do d ← get_decl n,
(c, l) ← append_typeclasses d.type.binding_body c l,
return (c, (expr.const n [c.univ]).mk_app (c.α :: l))
end instance_cache
private meta def get_expl_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_expl_pi_arity_aux new_b,
if bi = binder_info.default then
return (r + 1)
else
return r
| e := return 0
/-- Compute the arity of explicit arguments of the given (Pi-)type -/
meta def get_expl_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_expl_pi_arity_aux
/-- Compute the arity of explicit arguments of the given function -/
meta def get_expl_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_expl_pi_arity
/-- Auxilliary defintion for `get_pi_binders`. -/
meta def get_pi_binders_aux : list binder → expr → tactic (list binder × expr)
| es (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
let new_b := expr.instantiate_var b l,
get_pi_binders_aux (⟨n, bi, d⟩::es) new_b
| es e := return (es, e)
/-- Get the binders and target of a pi-type. Instantiates bound variables by
local constants. Cf. `pi_binders` in `meta.expr` (which produces open terms).
See also `mk_local_pis` in `init.core.tactic` which does almost the same. -/
meta def get_pi_binders : expr → tactic (list binder × expr) | e :=
do (es, e) ← get_pi_binders_aux [] e, return (es.reverse, e)
/-- variation on `assert` where a (possibly incomplete)
proof of the assertion is provided as a parameter.
``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and
use `tac` to (partially) construct a proof for it. `gs` is the
list of remaining goals in the proof of `h`.
The benefits over assert are:
- unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`;
- when `tac` does not complete the proof of `h`, returning the list
of goals allows one to write a tactic using `h` and with the confidence
that a proof will not boil over to goals left over from the proof of `h`,
unlike what would be the case when using `tactic.swap`.
-/
meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) :
tactic (expr × list expr) :=
focus1 $
do h' ← assert h p,
[g₀,g₁] ← get_goals,
set_goals [g₀], tac₀,
gs ← get_goals,
set_goals [g₁],
return (h', gs)
/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/
meta def var_names : expr → list name
| (expr.pi n _ _ b) := n :: var_names b
| _ := []
/-- When `struct_n` is the name of a structure type,
`subobject_names struct_n` returns two lists of names `(instances, fields)`.
The names in `instances` are the projections from `struct_n` to the structures that it extends
(assuming it was defined with `old_structure_cmd false`).
The names in `fields` are the standard fields of `struct_n`. -/
meta def subobject_names (struct_n : name) : tactic (list name × list name) :=
do env ← get_env,
[c] ← pure $ env.constructors_of struct_n | fail "too many constructors",
vs ← var_names <$> (mk_const c >>= infer_type),
fields ← env.structure_fields struct_n,
return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs)
private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n :=
do (so,fs) ← subobject_names struct_n,
ts ← so.mmap (λ n, do
(_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= mk_local_pis,
expanded_field_list' $ e.get_app_fn.const_name),
return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)
open functor function
/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure
named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name
of the projection is `prefix.name`. -/
meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) :=
dlist.to_list <$> expanded_field_list' struct_n
/--
Return a list of all type classes which can be instantiated
for the given expression.
-/
meta def get_classes (e : expr) : tactic (list name) :=
attribute.get_instances `class >>= list.mfilter (λ n,
succeeds $ mk_app n [e] >>= mk_instance)
open nat
/-- Create a list of `n` fresh metavariables. -/
meta def mk_mvar_list : ℕ → tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n
/-- Returns the only goal, or fails if there isn't just one goal. -/
meta def get_goal : tactic expr :=
do gs ← get_goals,
match gs with
| [a] := return a
| [] := fail "there are no goals"
| _ := fail "there are too many goals"
end
/--`iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,
or until it fails. Always succeeds. -/
meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := tactic.all_goals $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip
/--`iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first
goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on
current goal. -/
meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)
/--`apply_list l`: try to apply the tactics in the list `l` on the first goal, and
fail if none succeeds -/
meta def apply_list_expr : list expr → tactic unit
| [] := fail "no matching rule"
| (h::t) := do interactive.concat_tags (apply h) <|> apply_list_expr t
/-- constructs a list of expressions given a list of p-expressions, as follows:
- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it
- if the p-expression is a user attribute, add all the theorems with this attribute
to the list.-/
meta def build_list_expr_for_apply : list pexpr → tactic (list expr)
| [] := return []
| (h::t) := do
tail ← build_list_expr_for_apply t,
a ← i_to_expr_for_apply h,
(do l ← attribute.get_instances (expr.const_name a),
m ← list.mmap mk_const l,
return (m.append tail))
<|> return (a::tail)
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times -/
meta def apply_rules (hs : list pexpr) (n : nat) : tactic unit :=
do l ← build_list_expr_for_apply hs,
iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l)
/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local
context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.
Fails if there is nothing named `h` in the local context. -/
meta def replace (h : name) (p : pexpr) : tactic unit :=
do h' ← get_local h,
p ← to_expr p,
note h none p,
clear h'
/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``
or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an
`iff`, returns an expression with the `iff` converted to either the forwards or backwards
implication, as requested. -/
meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr
| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))
| `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0)
| _ f := none
/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B` -/
meta def iff_mp_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mp ty (λ_, e)
/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A` -/
meta def iff_mpr_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mpr ty (λ_, e)
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the forward implication. -/
meta def iff_mp (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the reverse implication. -/
meta def iff_mpr (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/--
Attempts to apply `e`, and if that fails, if `e` is an `iff`,
try applying both directions separately.
-/
meta def apply_iff (e : expr) : tactic (list (name × expr)) :=
let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in
ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)
/-- `symm_apply e cfg` tries `apply e cfg`, and if this fails, calls `symmetry` and tries again. -/
meta def symm_apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) :=
tactic.apply e cfg <|> (symmetry >> tactic.apply e cfg)
/-- `apply_assumption` searches for terms in the local context that can be applied to make progress
on the goal. If the goal is symmetric, it tries each goal in both directions. If this fails, it will
call `exfalso` and repeat. Optional arguments:
* `asms` controls which expressions are applied. Defaults to `local_context`
* `tac` is called after a successful application. Defaults to `skip` -/
meta def apply_assumption
(asms : tactic (list expr) := local_context)
(tac : tactic unit := skip) : tactic unit :=
do { ctx ← asms,
ctx.any_of (λ H, symm_apply H >> tac) } <|>
do { exfalso,
ctx ← asms,
ctx.any_of (λ H, symm_apply H >> tac) }
<|> fail "assumption tactic failed"
/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails
if this is not a definitional equality.
`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`
by reverting `h`, changing the goal, and reintroducing hypotheses. -/
meta def change_core (e : expr) : option expr → tactic unit
| none := tactic.change e
| (some h) :=
do num_reverted : ℕ ← revert h,
expr.pi n bi d b ← target,
tactic.change $ expr.pi n bi e b,
intron num_reverted
/--
`change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,
assuming `olde` and `newe` are defeq when elaborated.
-/
meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit :=
do h ← get_local hyp,
tp ← infer_type h,
olde ← to_expr olde, newe ← to_expr newe,
let repl_tp := tp.replace (λ a n, if a = olde then some newe else none),
change_core repl_tp (some h)
/-- Returns a list of all metavariables in the current partial proof. This can differ from
the list of goals, since the goals can be manually edited. -/
meta def metavariables : tactic (list expr) :=
expr.list_meta_vars <$> result
/-- Fail if the target contains a metavariable. -/
meta def no_mvars_in_target : tactic unit :=
expr.has_meta_var <$> target >>= guardb ∘ bnot
/-- Succeeds only if the current goal is a proposition. -/
meta def propositional_goal : tactic unit :=
do g :: _ ← get_goals,
is_proof g >>= guardb
/-- Succeeds only if we can construct an instance showing the
current goal is a subsingleton type. -/
meta def subsingleton_goal : tactic unit :=
do g :: _ ← get_goals,
ty ← infer_type g >>= instantiate_mvars,
to_expr ``(subsingleton %%ty) >>= mk_instance >> skip
/--
Succeeds only if the current goal is "terminal",
in the sense that no other goals depend on it
(except possibly through shared metavariables; see `independent_goal`).
-/
meta def terminal_goal : tactic unit :=
propositional_goal <|> subsingleton_goal <|>
do g₀ :: _ ← get_goals,
mvars ← (λ L, list.erase L g₀) <$> metavariables,
mvars.mmap' $ λ g, do
t ← infer_type g >>= instantiate_mvars,
d ← kdepends_on t g₀,
monad.whenb d $
pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.")
/--
Succeeds only if the current goal is "independent", in the sense
that no other goals depend on it, even through shared meta-variables.
-/
meta def independent_goal : tactic unit :=
no_mvars_in_target >> terminal_goal
/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,
it only unfolds reducible definitions, so it sometimes fails faster. -/
meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible
variable {α : Type}
private meta def iterate_aux (t : tactic α) : list α → tactic (list α)
| L := (do r ← t, iterate_aux (r :: L)) <|> return L
/-- Apply a tactic as many times as possible, collecting the results in a list. -/
meta def iterate' (t : tactic α) : tactic (list α) :=
list.reverse <$> iterate_aux t []
/-- Apply a tactic as many times as possible, collecting the results in a list.
Fail if the tactic does not succeed at least once. -/
meta def iterate1 (t : tactic α) : tactic (α × list α) :=
do r ← decorate_ex "iterate1 failed: tactic did not succeed" t,
L ← iterate' t,
return (r, L)
/-- Introduces one or more variables and returns the new local constants.
Fails if `intro` cannot be applied. -/
meta def intros1 : tactic (list expr) :=
iterate1 intro1 >>= λ p, return (p.1 :: p.2)
/-- `successes` invokes each tactic in turn, returning the list of successful results. -/
meta def successes (tactics : list (tactic α)) : tactic (list α) :=
list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t))
/-- Return target after instantiating metavars and whnf -/
private meta def target' : tactic expr :=
target >>= instantiate_mvars >>= whnf
/--
Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor.
However it does not reorder goals or invoke `auto_param` tactics.
-/
-- FIXME check if we can remove `auto_param := ff`
meta def fsplit : tactic unit :=
do [c] ← target' >>= get_constructors_for | tactic.fail "fsplit tactic failed, target is not an inductive datatype with only one constructor",
mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip
run_cmd add_interactive [`fsplit]
/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`
succeeds, clears the old hypothesis. -/
meta def injections_and_clear : tactic unit :=
do l ← local_context,
results ← successes $ l.map $ λ e, injection e >> clear e,
when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis")
run_cmd add_interactive [`injections_and_clear]
/-- calls `cases` on every local hypothesis, succeeding if
it succeeds on at least one hypothesis. -/
meta def case_bash : tactic unit :=
do l ← local_context,
r ← successes (l.reverse.map (λ h, cases h >> skip)),
when (r.empty) failed
/-- given a proof `pr : t`, adds `h : t` to the current context, where the name `h` is fresh. -/
meta def note_anon (e : expr) : tactic expr :=
do n ← get_unused_name "lh",
note n none e
/-- `find_local t` returns a local constant with type t, or fails if none exists. -/
meta def find_local (t : pexpr) : tactic expr :=
do t' ← to_expr t,
prod.snd <$> solve_aux t' assumption
/-- `dependent_pose_core l`: introduce dependent hypothesis, where the proofs depend on the values
of the previous local constants. `l` is a list of local constants and their values. -/
meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do
let lc := l.map prod.fst,
let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)),
t ← target,
new_goal ← mk_meta_var (t.pis lc),
old::other_goals ← get_goals,
set_goals (old :: new_goal :: other_goals),
exact ((new_goal.mk_app lc).instantiate_locals lm),
return ()
/-- like `mk_local_pis` but translating into weak head normal form before checking if it is a Π. -/
meta def mk_local_pis_whnf : expr → tactic (list expr × expr) | e := do
(expr.pi n bi d b) ← whnf e | return ([], e),
p ← mk_local' n bi d,
(ps, r) ← mk_local_pis (expr.instantiate_var b p),
return ((p :: ps), r)
/-- Changes `(h : ∀xs, ∃a:α, p a) ⊢ g` to `(d : ∀xs, a) (s : ∀xs, p (d xs) ⊢ g` -/
meta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do
t ← infer_type h,
(ctxt, t) ← mk_local_pis_whnf t,
`(@Exists %%α %%p) ← whnf t transparency.all | fail "expected a term of the shape ∀xs, ∃a, p xs a",
α_t ← infer_type α,
expr.sort u ← whnf α_t transparency.all,
value ← mk_local_def data (α.pis ctxt),
t' ← head_beta (p.app (value.mk_app ctxt)),
spec ← mk_local_def spec (t'.pis ctxt),
dependent_pose_core [
(value, ((((expr.const `classical.some [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt),
(spec, ((((expr.const `classical.some_spec [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt)],
try (tactic.clear h),
intro1,
intro1
/-- Changes `(h : ∀xs, ∃as, p as) ⊢ g` to a list of functions `as`, and a final hypothesis on `p as` -/
meta def choose : expr → list name → tactic unit
| h [] := fail "expect list of variables"
| h [n] := do
cnt ← revert h,
intro n,
intron (cnt - 1),
return ()
| h (n::ns) := do
v ← get_unused_name >>= choose1 h n,
choose v ns
/--
Instantiates metavariables that appear in the current goal.
-/
meta def instantiate_mvars_in_target : tactic unit :=
target >>= instantiate_mvars >>= change
/--
Instantiates metavariables in all goals.
-/
meta def instantiate_mvars_in_goals : tactic unit :=
all_goals $ instantiate_mvars_in_target
/-- This makes sure that the execution of the tactic does not change the tactic state.
This can be helpful while using rewrite, apply, or expr munging.
Remember to instantiate your metavariables before you're done! -/
meta def lock_tactic_state {α} (t : tactic α) : tactic α
| s := match t s with
| result.success a s' := result.success a s
| result.exception msg pos s' := result.exception msg pos s
end
/-- similar to `mk_local_pis` but make meta variables instead of
local constants -/
meta def mk_meta_pis : expr → tactic (list expr × expr)
| (expr.pi n bi d b) := do
p ← mk_meta_var d,
(ps, r) ← mk_meta_pis (expr.instantiate_var b p),
return ((p :: ps), r)
| e := return ([], e)
/--
Hole command used to fill in a structure's field when specifying an instance.
In the following:
```
instance : monad id :=
{! !}
```
invoking hole command `Instance Stub` produces:
```
instance : monad id :=
{ map := _,
map_const := _,
pure := _,
seq := _,
seq_left := _,
seq_right := _,
bind := _ }
```
-/
@[hole_command] meta def instance_stub : hole_command :=
{ name := "Instance Stub",
descr := "Generate a skeleton for the structure under construction.",
action := λ _,
do tgt ← target >>= whnf,
let cl := tgt.get_app_fn.const_name,
env ← get_env,
fs ← expanded_field_list cl,
let fs := fs.map prod.snd,
let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"),
let out := format.to_string format!"{{ {fs} }",
return [(out,"")] }
/-- Like `resolve_name` except when the list of goals is
empty. In that situation `resolve_name` fails whereas
`resolve_name'` simply proceeds on a dummy goal -/
meta def resolve_name' (n : name) : tactic pexpr :=
do [] ← get_goals | resolve_name n,
g ← mk_mvar,
set_goals [g],
resolve_name n <* set_goals []
private meta def strip_prefix' (n : name) : list string → name → tactic name
| s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous
| s (name.mk_string a p) :=
do let n' := s.foldl (flip name.mk_string) name.anonymous,
do { n'' ← tactic.resolve_constant n',
if n'' = n
then pure n'
else strip_prefix' (a :: s) p }
<|> strip_prefix' (a :: s) p
| s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n
/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/
meta def strip_prefix : name → tactic name
| n@(name.mk_string a a_1) :=
if (`_private).is_prefix_of n
then let n' := n.update_prefix name.anonymous in
n' <$ resolve_name' n' <|> pure n
else strip_prefix' n [a] a_1
| n := pure n
/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/
meta def mk_patterns (t : expr) : tactic (list format) :=
do let cl := t.get_app_fn.const_name,
env ← get_env,
let fs := env.constructors_of cl,
fs.mmap $ λ f,
do { (vs,_) ← mk_const f >>= infer_type >>= mk_local_pis,
let vs := vs.filter (λ v, v.is_default_local),
vs ← vs.mmap (λ v,
do v' ← get_unused_name v.local_pp_name,
pose v' none `(()),
pure v' ),
vs.mmap' $ λ v, get_local v >>= clear,
let args := list.intersperse (" " : format) $ vs.map to_fmt,
f ← strip_prefix f,
if args.empty
then pure $ format!"| {f} := _\n"
else pure format!"| ({f} {format.join args}) := _\n" }
/--
Hole command used to generate a `match` expression.
In the following:
```
meta def foo (e : expr) : tactic unit :=
{! e !}
```
invoking hole command `Match Stub` produces:
```
meta def foo (e : expr) : tactic unit :=
match e with
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
end
```
-/
@[hole_command] meta def match_stub : hole_command :=
{ name := "Match Stub",
descr := "Generate a list of equations for a `match` expression.",
action := λ es,
do [e] ← pure es | fail "expecting one expression",
e ← to_expr e,
t ← infer_type e >>= whnf,
fs ← mk_patterns t,
e ← pp e,
let out := format.to_string format!"match {e} with\n{format.join fs}end\n",
return [(out,"")] }
/--
Hole command used to generate a `match` expression.
In the following:
```
meta def foo : {! expr → tactic unit !} -- `:=` is omitted
```
invoking hole command `Equations Stub` produces:
```
meta def foo : expr → tactic unit
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
A similar result can be obtained by invoking `Equations Stub` on the following:
```
meta def foo : expr → tactic unit := -- do not forget to write `:=`!!
{! !}
```
```
meta def foo : expr → tactic unit := -- don't forget to erase `:=`!!
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
-/
@[hole_command] meta def eqn_stub : hole_command :=
{ name := "Equations Stub",
descr := "Generate a list of equations for a recursive definition.",
action := λ es,
do t ← match es with
| [t] := to_expr t
| [] := target
| _ := fail "expecting one type"
end,
e ← whnf t,
(v :: _,_) ← mk_local_pis e | fail "expecting a Pi-type",
t' ← infer_type v,
fs ← mk_patterns t',
t ← pp t,
let out :=
if es.empty then
format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}"
else format.to_string format!"{t}\n{format.join fs}",
return [(out,"")] }
/--
This command lists the constructors that can be used to satisfy the expected type.
When used in the following hole:
```
def foo : ℤ ⊕ ℕ :=
{! !}
```
the command will produce:
```
def foo : ℤ ⊕ ℕ :=
{! sum.inl, sum.inr !}
```
and will display:
```
sum.inl : ℤ → ℤ ⊕ ℕ
sum.inr : ℕ → ℤ ⊕ ℕ
```
-/
@[hole_command] meta def list_constructors_hole : hole_command :=
{ name := "List Constructors",
descr := "Show the list of constructors of the expected type.",
action := λ es,
do t ← target >>= whnf,
(_,t) ← mk_local_pis t,
let cl := t.get_app_fn.const_name,
let args := t.get_app_args,
env ← get_env,
let cs := env.constructors_of cl,
ts ← cs.mmap $ λ c,
do { e ← mk_const c,
t ← infer_type (e.mk_app args) >>= pp,
c ← strip_prefix c,
pure format!"\n{c} : {t}\n" },
fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt),
let out := format.to_string format!"{{! {fs} !}",
trace (format.join ts).to_string,
return [(out,"")] }
/-- Makes the declaration `classical.prop_decidable` available to type class inference.
This asserts that all propositions are decidable, but does not have computational content. -/
meta def classical : tactic unit :=
do h ← get_unused_name `_inst,
mk_const `classical.prop_decidable >>= note h none,
reset_instance_cache
open expr
/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,
returns the expression `f ∘ g ∘ h`. -/
meta def mk_comp (v : expr) : expr → tactic expr
| (app f e) :=
if e = v then pure f
else do
guard (¬ v.occurs f) <|> fail "bad guard",
e' ← mk_comp e >>= instantiate_mvars,
f ← instantiate_mvars f,
mk_mapp ``function.comp [none,none,none,f,e']
| e :=
do guard (e = v),
t ← infer_type e,
mk_mapp ``id [t]
/--
From a lemma of the shape `∀ x, f (g x) = h x`
derive an auxiliary lemma of the form `f ∘ g = h`
for reasoning about higher-order functions.
-/
meta def mk_higher_order_type : expr → tactic expr
| (pi n bi d b@(pi _ _ _ _)) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'
| (pi n bi d b) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(l,r) ← match_eq b' <|> fail format!"not an equality {b'}",
l' ← mk_comp v l,
r' ← mk_comp v r,
mk_app ``eq [l',r']
| e := failed
open lean.parser interactive.types
/-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`.
It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.-/
@[user_attribute]
meta def higher_order_attr : user_attribute unit (option name) :=
{ name := `higher_order,
parser := optional ident,
descr :=
"From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the
form `f ∘ g = h` for reasoning about higher-order functions.",
after_set := some $ λ lmm _ _,
do env ← get_env,
decl ← env.get lmm,
let num := decl.univ_params.length,
let lvls := (list.iota num).map (`l).append_after,
let l : expr := expr.const lmm $ lvls.map level.param,
t ← infer_type l >>= instantiate_mvars,
t' ← mk_higher_order_type t,
(_,pr) ← solve_aux t' $ do {
intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },
pr ← instantiate_mvars pr,
lmm' ← higher_order_attr.get_param lmm,
lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime,
add_decl $ declaration.thm lmm' lvls t' (pure pr),
copy_attribute `simp lmm tt lmm',
copy_attribute `functor_norm lmm tt lmm' }
attribute [higher_order map_comp_pure] map_pure
/--
Use `refine` to partially discharge the goal,
or call `fconstructor` and try again.
-/
private meta def use_aux (h : pexpr) : tactic unit :=
(focus1 (refine h >> done)) <|> (fconstructor >> use_aux)
/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations
at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to
the expected type.
```
example : ∃ x : ℤ, x = x :=
by tactic.use ``(42)
```
See the doc string for `tactic.interactive.use` for more information.
-/
protected meta def use (l : list pexpr) : tactic unit :=
focus1 $ seq (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}")
instantiate_mvars_in_target
/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the
local context. -/
meta def clear_aux_decl_aux : list expr → tactic unit
| [] := skip
| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l
/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/
meta def clear_aux_decl : tactic unit :=
local_context >>= clear_aux_decl_aux
/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)
finds a list of expressions `vs` and returns (e.mk_args (vs ++ [h]), vs) -/
meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr)
| vs e (pi n bi d b) :=
do { v ← mk_meta_var d,
apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|>
(e arg, vs) <$ unify d t
| vs e _ := failed
/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result -/
meta def apply_at (e h : expr) : tactic unit :=
do ht ← infer_type h,
et ← infer_type e,
(h', gs') ← apply_at_aux h ht [] e et,
note h.local_pp_name none h',
clear h,
gs' ← gs'.mfilter is_assigned,
(g :: gs) ← get_goals,
set_goals (g :: gs' ++ gs)
/-- `symmetry_hyp h` applies symmetry on hypothesis `h` -/
meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit :=
do tgt ← infer_type h,
env ← get_env,
let r := get_app_fn tgt,
match env.symm_for (const_name r) with
| (some symm) := do s ← mk_const symm,
apply_at s h
| none := fail "symmetry tactic failed, target is not a relation application with the expected property."
end
precedence `setup_tactic_parser`:0
/-- `setup_tactic_parser_cmd` is a user command that opens the namespaces used in writing
interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.
It does *not* use the `namespace` command, so it will typically be used after
`namespace tactic.interactive`.
-/
@[user_command]
meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") : lean.parser unit :=
emit_code_here "
open lean
open lean.parser
open interactive interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many .
"
/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message
of `t`. -/
meta def trace_error (msg : string) (t : tactic α) : tactic α
| s := match t s with
| (result.success r s') := result.success r s'
| (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s'
| (result.exception none p s') := result.exception none p s'
end
/--
This combinator is for testing purposes. It succeeds if `t` fails with message `msg`,
and fails otherwise.
-/
meta def {u} success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit :=
λ s, match t s with
| (interaction_monad.result.exception msg' _ s') :=
let expected_msg := (msg'.iget ()).to_string in
if msg = expected_msg then result.success () s
else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s
| (interaction_monad.result.success a s) :=
mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s
end
open lean interactive
/-- A type alias for `tactic format`, standing for "pretty print format". -/
meta def pformat := tactic format
/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/
meta def pformat.mk (fmt : format) : pformat := pure fmt
/-- an alias for `pp`. -/
meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat :=
pp x
meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat :=
⟨ id ⟩
meta instance : has_append pformat :=
⟨ λ x y, (++) <$> x <*> y ⟩
meta instance tactic.has_to_tactic_format [has_to_tactic_format α] : has_to_tactic_format (tactic α) :=
⟨ λ x, x >>= to_pfmt ⟩
private meta def parse_pformat : string → list char → parser pexpr
| acc [] := pure ``(to_pfmt %%(reflect acc))
| acc ('\n'::s) :=
do f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f)
| acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s
| acc ('{'::s) :=
do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string,
'}'::s ← return s.to_list | fail "'}' expected",
f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f)
| acc (c::s) := parse_pformat (acc.str c) s
reserve prefix `pformat! `:100
/-- See `format!` in `init/meta/interactive_base.lean`.
The main differences are that `pp` is called instead of `to_fmt` and that we can use
arguments of type `tactic α` in the quotations.
Now, consider the following:
```
e ← to_expr ``(3 + 7),
trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`
trace pformat!"{e}" -- outputs `3 + 7`
```
The difference is significant. And now, the following is expressible:
```
e ← to_expr ``(3 + 7),
trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ`
```
See also: `trace!` and `fail!`
-/
@[user_notation]
meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr :=
do e ← parse_pformat "" s.to_list,
return ``(%%e : pformat)
reserve prefix `fail! `:100
/--
the combination of `pformat` and `fail`
-/
@[user_notation]
meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= fail)
reserve prefix `trace! `:100
/--
the combination of `pformat` and `fail`
-/
@[user_notation]
meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= trace)
/-- A hackish way to get the `src` directory of mathlib. -/
meta def get_mathlib_dir : tactic string :=
do e ← get_env,
s ← e.decl_olean `tactic.reset_instance_cache,
return $ s.popn_back 17
/-- Checks whether a declaration with the given name is declared in mathlib.
If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,
since it is expensive to execute `get_mathlib_dir` many times. -/
meta def is_in_mathlib (n : name) : tactic bool :=
do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n
/-- auxiliary function for apply_under_pis -/
private meta def apply_under_pis_aux (func arg : pexpr) : ℕ → expr → pexpr
| n (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_pis_aux (n+1) bd)
| n _ :=
let vars := ((list.range n).reverse.map (@expr.var ff)),
bd := vars.foldl expr.app arg.mk_explicit in
func bd
/--
Assumes `pi_expr` is of the form `Π x1 ... xn, _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr :=
apply_under_pis_aux func arg 0 pi_expr
/--
Tries to derive instances by unfolding the newly introduced type and applying type class resolution.
For example,
```
@[derive ring] def new_int : Type := ℤ
```
adds an instance `ring new_int`, defined to be the instance of `ring ℤ` found by `apply_instance`.
Multiple instances can be added with `@[derive [ring, module ℝ]]`.
This derive handler applies only to declarations made using `def`, and will fail on such a
declaration if it is unable to derive an instance. It is run with higher priority than the built-in
handlers, which will fail on `def`s.
-/
@[derive_handler, priority 2000] meta def delta_instance : derive_handler :=
λ cls new_decl_name,
do env ← get_env,
if env.is_inductive new_decl_name then return ff else
do new_decl_type ← declaration.type <$> get_decl new_decl_name,
new_decl_pexpr ← resolve_name new_decl_name,
tgt ← to_expr $ apply_under_pis cls new_decl_pexpr new_decl_type,
(_, inst) ← solve_aux tgt
(intros >> reset_instance_cache >> delta_target [new_decl_name] >> apply_instance >> done),
inst ← instantiate_mvars inst,
tgt ← instantiate_mvars tgt,
nm ← get_unused_decl_name $ new_decl_name ++
match cls with
-- the postfix is needed because we can't protect this name. using nm.last directly can
-- conflict with open namespaces
| (expr.const nm _) := (nm.last ++ "_1" : string)
| _ := "inst"
end,
add_decl $ mk_definition nm inst.collect_univ_params tgt inst,
set_basic_attribute `instance nm tt,
return tt
/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.
`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a declaration named `m`
can be found. -/
meta def find_private_decl (n : name) (fr : option name) : tactic name :=
do env ← get_env,
fn ← option_t.run (do
fr ← option_t.mk (return fr),
d ← monad_lift $ get_decl fr,
option_t.mk (return $ env.decl_olean d.to_name) ),
let p : string → bool :=
match fn with
| (some fn) := λ x, fn = x
| none := λ _, tt
end,
let xs := env.decl_filter_map (λ d,
do fn ← env.decl_olean d.to_name,
guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n),
pure d.to_name),
match xs with
| [n] := pure n
| [] := fail "no such private found"
| _ := fail "many matches found"
end
open lean.parser interactive
/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`
and creates a local notation to refer to it.
`import_private foo` looks for `foo` in all imported files. -/
@[user_command]
meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit :=
do n ← ident,
fr ← optional (tk "from" *> ident),
n ← find_private_decl n fr,
c ← resolve_constant n,
d ← get_decl n,
let c := @expr.const tt c d.univ_levels,
new_n ← new_aux_decl_name,
add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted,
let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}",
emit_command_here $ new_not,
skip .
/--
The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`.
Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.
`mk_simp_attribute simp_name none` will use a default description.
Appending the command with `with attr1 attr2 ...` will include all declarations tagged with
`attr1`, `attr2`, ... in the new simp set.
-/
@[user_command]
meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit :=
do n ← ident,
d ← parser.pexpr,
d ← to_expr ``(%%d : option string),
descr ← eval_expr (option string) d,
with_list ← types.with_ident_list <|> return [],
mk_simp_attr n with_list,
add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n
end tactic
|
2bebd7ba1c57234f0a1b34578c898140b93849e9 | 737dc4b96c97368cb66b925eeea3ab633ec3d702 | /stage0/src/Lean/Meta/Tactic/Intro.lean | 097e64b33a5f2cbf2b8019d604f73967550ad9e0 | [
"Apache-2.0"
] | permissive | Bioye97/lean4 | 1ace34638efd9913dc5991443777b01a08983289 | bc3900cbb9adda83eed7e6affeaade7cfd07716d | refs/heads/master | 1,690,589,820,211 | 1,631,051,000,000 | 1,631,067,598,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,425 | 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.Tactic.Util
namespace Lean.Meta
@[inline] private partial def introNImp {σ} (mvarId : MVarId) (n : Nat) (mkName : LocalContext → Name → Bool → σ → MetaM (Name × σ)) (s : σ)
: MetaM (Array FVarId × MVarId) := withMVarContext mvarId do
checkNotAssigned mvarId `introN
let mvarType ← getMVarType mvarId
let lctx ← getLCtx
let rec @[specialize] loop : Nat → LocalContext → Array Expr → Nat → σ → Expr → MetaM (Array Expr × MVarId)
| 0, lctx, fvars, j, _, type =>
let type := type.instantiateRevRange j fvars.size fvars
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstances fvars j do
let tag ← getMVarTag mvarId
let type := type.headBeta
let newMVar ← mkFreshExprSyntheticOpaqueMVar type tag
let lctx ← getLCtx
let newVal ← mkLambdaFVars fvars newMVar
assignExprMVar mvarId newVal
pure $ (fvars, newMVar.mvarId!)
| (i+1), lctx, fvars, j, s, Expr.letE n type val body _ => do
let type := type.instantiateRevRange j fvars.size fvars
let type := type.headBeta
let val := val.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let (n, s) ← mkName lctx n true s
let lctx := lctx.mkLetDecl fvarId n type val
let fvar := mkFVar fvarId
let fvars := fvars.push fvar
loop i lctx fvars j s body
| (i+1), lctx, fvars, j, s, Expr.forallE n type body c => do
let type := type.instantiateRevRange j fvars.size fvars
let type := type.headBeta
let fvarId ← mkFreshId
let (n, s) ← mkName lctx n c.binderInfo.isExplicit s
let lctx := lctx.mkLocalDecl fvarId n type c.binderInfo
let fvar := mkFVar fvarId
let fvars := fvars.push fvar
loop i lctx fvars j s body
| (i+1), lctx, fvars, j, s, type =>
let type := type.instantiateRevRange j fvars.size fvars
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstances fvars j do
let newType ← whnf type
if newType.isForall then
loop (i+1) lctx fvars fvars.size s newType
else
throwTacticEx `introN mvarId "insufficient number of binders"
let (fvars, mvarId) ← loop n lctx #[] 0 s mvarType
pure (fvars.map Expr.fvarId!, mvarId)
register_builtin_option tactic.hygienic : Bool := {
defValue := true
group := "tactic"
descr := "make sure tactics are hygienic"
}
def getHygienicIntro : MetaM Bool := do
return tactic.hygienic.get (← getOptions)
private def mkAuxNameImp (preserveBinderNames : Bool) (hygienic : Bool) (useNamesForExplicitOnly : Bool)
(lctx : LocalContext) (binderName : Name) (isExplicit : Bool) : List Name → MetaM (Name × List Name)
| [] => mkAuxNameWithoutGivenName []
| n :: rest => do
if useNamesForExplicitOnly && !isExplicit then
mkAuxNameWithoutGivenName (n :: rest)
else if n != Name.mkSimple "_" then
pure (n, rest)
else
mkAuxNameWithoutGivenName rest
where
mkAuxNameWithoutGivenName (rest : List Name) : MetaM (Name × List Name) := do
if preserveBinderNames then
pure (binderName, rest)
else if hygienic then
let binderName ← mkFreshUserName binderName
pure (binderName, rest)
else
pure (lctx.getUnusedName binderName, rest)
def introNCore (mvarId : MVarId) (n : Nat) (givenNames : List Name) (useNamesForExplicitOnly : Bool) (preserveBinderNames : Bool)
: MetaM (Array FVarId × MVarId) := do
let hygienic ← getHygienicIntro
if n == 0 then
pure (#[], mvarId)
else
introNImp mvarId n (mkAuxNameImp preserveBinderNames hygienic useNamesForExplicitOnly) givenNames
abbrev introN (mvarId : MVarId) (n : Nat) (givenNames : List Name := []) (useNamesForExplicitOnly := false) : MetaM (Array FVarId × MVarId) :=
introNCore mvarId n givenNames (useNamesForExplicitOnly := useNamesForExplicitOnly) (preserveBinderNames := false)
abbrev introNP (mvarId : MVarId) (n : Nat) : MetaM (Array FVarId × MVarId) :=
introNCore mvarId n [] (useNamesForExplicitOnly := false) (preserveBinderNames := true)
def intro (mvarId : MVarId) (name : Name) : MetaM (FVarId × MVarId) := do
let (fvarIds, mvarId) ← introN mvarId 1 [name]
pure (fvarIds.get! 0, mvarId)
def intro1Core (mvarId : MVarId) (preserveBinderNames : Bool) : MetaM (FVarId × MVarId) := do
let (fvarIds, mvarId) ← introNCore mvarId 1 [] (useNamesForExplicitOnly := false) preserveBinderNames
pure (fvarIds.get! 0, mvarId)
abbrev intro1 (mvarId : MVarId) : MetaM (FVarId × MVarId) :=
intro1Core mvarId false
abbrev intro1P (mvarId : MVarId) : MetaM (FVarId × MVarId) :=
intro1Core mvarId true
private def getIntrosSize : Expr → Nat
| Expr.forallE _ _ b _ => getIntrosSize b + 1
| Expr.letE _ _ _ b _ => getIntrosSize b + 1
| Expr.mdata _ b _ => getIntrosSize b
| _ => 0
def intros (mvarId : MVarId) : MetaM (Array FVarId × MVarId) := do
let type ← Meta.getMVarType mvarId
let type ← instantiateMVars type
let n := getIntrosSize type
if n == 0 then
return (#[], mvarId)
else
Meta.introN mvarId n
end Lean.Meta
|
a19b63354bf88382df306a8ed9065a4073de78f8 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /library/data/num/ops.lean | b9b9bc09305cd21bdb597056f4134215ab735b50 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,032 | lean | ----------------------------------------------------------------------------------------------------
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Author: Leonardo de Moura
----------------------------------------------------------------------------------------------------
import data.num.decl logic.inhabited data.bool
open bool
definition pos_num.is_inhabited [instance] : inhabited pos_num :=
inhabited.mk pos_num.one
namespace pos_num
definition succ (a : pos_num) : pos_num :=
rec_on a (bit0 one) (λn r, bit0 r) (λn r, bit1 n)
definition is_one (a : pos_num) : bool :=
rec_on a tt (λn r, ff) (λn r, ff)
definition pred (a : pos_num) : pos_num :=
rec_on a one (λn r, bit0 n) (λn r, cond (is_one n) one (bit1 r))
definition size (a : pos_num) : pos_num :=
rec_on a one (λn r, succ r) (λn r, succ r)
definition add (a b : pos_num) : pos_num :=
rec_on a
succ
(λn f b, rec_on b
(succ (bit1 n))
(λm r, succ (bit1 (f m)))
(λm r, bit1 (f m)))
(λn f b, rec_on b
(bit1 n)
(λm r, bit1 (f m))
(λm r, bit0 (f m)))
b
notation a + b := add a b
definition mul (a b : pos_num) : pos_num :=
rec_on a
b
(λn r, bit0 r + b)
(λn r, bit0 r)
notation a * b := mul a b
end pos_num
definition num.is_inhabited [instance] : inhabited num :=
inhabited.mk num.zero
namespace num
open pos_num
definition succ (a : num) : num :=
rec_on a (pos one) (λp, pos (succ p))
definition pred (a : num) : num :=
rec_on a zero (λp, cond (is_one p) zero (pos (pred p)))
definition size (a : num) : num :=
rec_on a (pos one) (λp, pos (size p))
definition add (a b : num) : num :=
rec_on a b (λp_a, rec_on b (pos p_a) (λp_b, pos (pos_num.add p_a p_b)))
definition mul (a b : num) : num :=
rec_on a zero (λp_a, rec_on b zero (λp_b, pos (pos_num.mul p_a p_b)))
notation a + b := add a b
notation a * b := mul a b
end num
|
1f8fd4f357bacefd66d51dc24d86e41a4b69b7f8 | 097294e9b80f0d9893ac160b9c7219aa135b51b9 | /instructor/types/option/dm_option_preliminary_test.lean | 99eeb14d65eab89eaeff4a5e812e76cae32871c8 | [] | no_license | AbigailCastro17/CS2102-Discrete-Math | cf296251be9418ce90206f5e66bde9163e21abf9 | d741e4d2d6a9b2e0c8380e51706218b8f608cee4 | refs/heads/main | 1,682,891,087,358 | 1,621,401,341,000 | 1,621,401,341,000 | 368,749,959 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 232 | lean | import .dm_option_preliminary
open hidden
def o1 := dm_option.none -- Hmm. Check it.
#check o1
def o2 := dm_option.none bool -- Probably right
def o3 := dm_option.some tt
#reduce p 0
#reduce p 1
#reduce p 0
-- etc
|
de5d71bcf6ff267dfb9137774f517601fac72de9 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/category_theory/limits/shapes/biproducts.lean | 18cb405f2951e3b266458ec557bf6545c8dd8add | [
"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 | 81,721 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Jakob von Raumer
-/
import algebra.group.ext
import category_theory.limits.shapes.finite_products
import category_theory.limits.shapes.binary_products
import category_theory.preadditive
import category_theory.limits.shapes.kernels
/-!
# Biproducts and binary biproducts
We introduce the notion of (finite) biproducts and binary biproducts.
These are slightly unusual relative to the other shapes in the library,
as they are simultaneously limits and colimits.
(Zero objects are similar; they are "biterminal".)
We treat first the case of a general category with zero morphisms,
and subsequently the case of a preadditive category.
In a category with zero morphisms, we model the (binary) biproduct of `P Q : C`
using a `binary_bicone`, which has a cone point `X`,
and morphisms `fst : X ⟶ P`, `snd : X ⟶ Q`, `inl : P ⟶ X` and `inr : X ⟶ Q`,
such that `inl ≫ fst = 𝟙 P`, `inl ≫ snd = 0`, `inr ≫ fst = 0`, and `inr ≫ snd = 𝟙 Q`.
Such a `binary_bicone` is a biproduct if the cone is a limit cone, and the cocone is a colimit
cocone.
In a preadditive category,
* any `binary_biproduct` satisfies `total : fst ≫ inl + snd ≫ inr = 𝟙 X`
* any `binary_product` is a `binary_biproduct`
* any `binary_coproduct` is a `binary_biproduct`
For biproducts indexed by a `fintype J`, a `bicone` again consists of a cone point `X`
and morphisms `π j : X ⟶ F j` and `ι j : F j ⟶ X` for each `j`,
such that `ι j ≫ π j'` is the identity when `j = j'` and zero otherwise.
In a preadditive category,
* any `biproduct` satisfies `total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)`
* any `product` is a `biproduct`
* any `coproduct` is a `biproduct`
## Notation
As `⊕` is already taken for the sum of types, we introduce the notation `X ⊞ Y` for
a binary biproduct. We introduce `⨁ f` for the indexed biproduct.
## Implementation
Prior to #14046, `has_finite_biproducts` required a `decidable_eq` instance on the indexing type.
As this had no pay-off (everything about limits is non-constructive in mathlib), and occasional cost
(constructing decidability instances appropriate for constructions involving the indexing type),
we made everything classical.
-/
noncomputable theory
universes w w' v u
open category_theory
open category_theory.functor
open_locale classical
namespace category_theory
namespace limits
variables {J : Type w}
variables {C : Type u} [category.{v} C] [has_zero_morphisms C]
/--
A `c : bicone F` is:
* an object `c.X` and
* morphisms `π j : X ⟶ F j` and `ι j : F j ⟶ X` for each `j`,
* such that `ι j ≫ π j'` is the identity when `j = j'` and zero otherwise.
-/
@[nolint has_inhabited_instance]
structure bicone (F : J → C) :=
(X : C)
(π : Π j, X ⟶ F j)
(ι : Π j, F j ⟶ X)
(ι_π : ∀ j j', ι j ≫ π j' = if h : j = j' then eq_to_hom (congr_arg F h) else 0 . obviously)
@[simp, reassoc] lemma bicone_ι_π_self {F : J → C} (B : bicone F) (j : J) :
B.ι j ≫ B.π j = 𝟙 (F j) :=
by simpa using B.ι_π j j
@[simp, reassoc] lemma bicone_ι_π_ne {F : J → C} (B : bicone F) {j j' : J} (h : j ≠ j') :
B.ι j ≫ B.π j' = 0 :=
by simpa [h] using B.ι_π j j'
variables {F : J → C}
namespace bicone
local attribute [tidy] tactic.discrete_cases
/-- Extract the cone from a bicone. -/
def to_cone (B : bicone F) : cone (discrete.functor F) :=
{ X := B.X,
π := { app := λ j, B.π j.as }, }
@[simp] lemma to_cone_X (B : bicone F) : B.to_cone.X = B.X := rfl
@[simp] lemma to_cone_π_app (B : bicone F) (j : J) : B.to_cone.π.app ⟨j⟩ = B.π j := rfl
/-- Extract the cocone from a bicone. -/
def to_cocone (B : bicone F) : cocone (discrete.functor F) :=
{ X := B.X,
ι := { app := λ j, B.ι j.as }, }
@[simp] lemma to_cocone_X (B : bicone F) : B.to_cocone.X = B.X := rfl
@[simp] lemma to_cocone_ι_app (B : bicone F) (j : J) : B.to_cocone.ι.app ⟨j⟩ = B.ι j := rfl
/-- We can turn any limit cone over a discrete collection of objects into a bicone. -/
@[simps]
def of_limit_cone {f : J → C} {t : cone (discrete.functor f)} (ht : is_limit t) :
bicone f :=
{ X := t.X,
π := λ j, t.π.app ⟨j⟩,
ι := λ j, ht.lift (fan.mk _ (λ j', if h : j = j' then eq_to_hom (congr_arg f h) else 0)),
ι_π := λ j j', by simp }
lemma ι_of_is_limit {f : J → C} {t : bicone f} (ht : is_limit t.to_cone) (j : J) :
t.ι j = ht.lift (fan.mk _ (λ j', if h : j = j' then eq_to_hom (congr_arg f h) else 0)) :=
ht.hom_ext (λ j', by { rw ht.fac, discrete_cases, simp [t.ι_π] })
/-- We can turn any colimit cocone over a discrete collection of objects into a bicone. -/
@[simps]
def of_colimit_cocone {f : J → C} {t : cocone (discrete.functor f)} (ht : is_colimit t) :
bicone f :=
{ X := t.X,
π := λ j, ht.desc (cofan.mk _ (λ j', if h : j' = j then eq_to_hom (congr_arg f h) else 0)),
ι := λ j, t.ι.app ⟨j⟩,
ι_π := λ j j', by simp }
lemma π_of_is_colimit {f : J → C} {t : bicone f} (ht : is_colimit t.to_cocone) (j : J) :
t.π j = ht.desc (cofan.mk _ (λ j', if h : j' = j then eq_to_hom (congr_arg f h) else 0)) :=
ht.hom_ext (λ j', by { rw ht.fac, discrete_cases, simp [t.ι_π] })
/-- Structure witnessing that a bicone is both a limit cone and a colimit cocone. -/
@[nolint has_inhabited_instance]
structure is_bilimit {F : J → C} (B : bicone F) :=
(is_limit : is_limit B.to_cone)
(is_colimit : is_colimit B.to_cocone)
local attribute [ext] bicone.is_bilimit
instance subsingleton_is_bilimit {f : J → C} {c : bicone f} : subsingleton c.is_bilimit :=
⟨λ h h', bicone.is_bilimit.ext _ _ (subsingleton.elim _ _) (subsingleton.elim _ _)⟩
section whisker
variables {K : Type w'}
/-- Whisker a bicone with an equivalence between the indexing types. -/
@[simps]
def whisker {f : J → C} (c : bicone f) (g : K ≃ J) : bicone (f ∘ g) :=
{ X := c.X,
π := λ k, c.π (g k),
ι := λ k, c.ι (g k),
ι_π := λ k k',
begin
simp only [c.ι_π],
split_ifs with h h' h'; simp [equiv.apply_eq_iff_eq g] at h h'; tauto
end }
local attribute [tidy] tactic.discrete_cases
/-- Taking the cone of a whiskered bicone results in a cone isomorphic to one gained
by whiskering the cone and postcomposing with a suitable isomorphism. -/
def whisker_to_cone {f : J → C} (c : bicone f) (g : K ≃ J) :
(c.whisker g).to_cone ≅ (cones.postcompose (discrete.functor_comp f g).inv).obj
(c.to_cone.whisker (discrete.functor (discrete.mk ∘ g))) :=
cones.ext (iso.refl _) (by tidy)
/-- Taking the cocone of a whiskered bicone results in a cone isomorphic to one gained
by whiskering the cocone and precomposing with a suitable isomorphism. -/
def whisker_to_cocone {f : J → C} (c : bicone f) (g : K ≃ J) :
(c.whisker g).to_cocone ≅ (cocones.precompose (discrete.functor_comp f g).hom).obj
(c.to_cocone.whisker (discrete.functor (discrete.mk ∘ g))) :=
cocones.ext (iso.refl _) (by tidy)
/-- Whiskering a bicone with an equivalence between types preserves being a bilimit bicone. -/
def whisker_is_bilimit_iff {f : J → C} (c : bicone f) (g : K ≃ J) :
(c.whisker g).is_bilimit ≃ c.is_bilimit :=
begin
refine equiv_of_subsingleton_of_subsingleton (λ hc, ⟨_, _⟩) (λ hc, ⟨_, _⟩),
{ let := is_limit.of_iso_limit hc.is_limit (bicone.whisker_to_cone c g),
let := (is_limit.postcompose_hom_equiv (discrete.functor_comp f g).symm _) this,
exact is_limit.of_whisker_equivalence (discrete.equivalence g) this },
{ let := is_colimit.of_iso_colimit hc.is_colimit (bicone.whisker_to_cocone c g),
let := (is_colimit.precompose_hom_equiv (discrete.functor_comp f g) _) this,
exact is_colimit.of_whisker_equivalence (discrete.equivalence g) this },
{ apply is_limit.of_iso_limit _ (bicone.whisker_to_cone c g).symm,
apply (is_limit.postcompose_hom_equiv (discrete.functor_comp f g).symm _).symm _,
exact is_limit.whisker_equivalence hc.is_limit (discrete.equivalence g) },
{ apply is_colimit.of_iso_colimit _ (bicone.whisker_to_cocone c g).symm,
apply (is_colimit.precompose_hom_equiv (discrete.functor_comp f g) _).symm _,
exact is_colimit.whisker_equivalence hc.is_colimit (discrete.equivalence g) }
end
end whisker
end bicone
/--
A bicone over `F : J → C`, which is both a limit cone and a colimit cocone.
-/
@[nolint has_inhabited_instance]
structure limit_bicone (F : J → C) :=
(bicone : bicone F)
(is_bilimit : bicone.is_bilimit)
/--
`has_biproduct F` expresses the mere existence of a bicone which is
simultaneously a limit and a colimit of the diagram `F`.
-/
class has_biproduct (F : J → C) : Prop :=
mk' :: (exists_biproduct : nonempty (limit_bicone F))
lemma has_biproduct.mk {F : J → C} (d : limit_bicone F) : has_biproduct F :=
⟨nonempty.intro d⟩
/-- Use the axiom of choice to extract explicit `biproduct_data F` from `has_biproduct F`. -/
def get_biproduct_data (F : J → C) [has_biproduct F] : limit_bicone F :=
classical.choice has_biproduct.exists_biproduct
/-- A bicone for `F` which is both a limit cone and a colimit cocone. -/
def biproduct.bicone (F : J → C) [has_biproduct F] : bicone F :=
(get_biproduct_data F).bicone
/-- `biproduct.bicone F` is a bilimit bicone. -/
def biproduct.is_bilimit (F : J → C) [has_biproduct F] : (biproduct.bicone F).is_bilimit :=
(get_biproduct_data F).is_bilimit
/-- `biproduct.bicone F` is a limit cone. -/
def biproduct.is_limit (F : J → C) [has_biproduct F] : is_limit (biproduct.bicone F).to_cone :=
(get_biproduct_data F).is_bilimit.is_limit
/-- `biproduct.bicone F` is a colimit cocone. -/
def biproduct.is_colimit (F : J → C) [has_biproduct F] :
is_colimit (biproduct.bicone F).to_cocone :=
(get_biproduct_data F).is_bilimit.is_colimit
@[priority 100]
instance has_product_of_has_biproduct [has_biproduct F] : has_limit (discrete.functor F) :=
has_limit.mk { cone := (biproduct.bicone F).to_cone,
is_limit := biproduct.is_limit F, }
@[priority 100]
instance has_coproduct_of_has_biproduct [has_biproduct F] : has_colimit (discrete.functor F) :=
has_colimit.mk { cocone := (biproduct.bicone F).to_cocone,
is_colimit := biproduct.is_colimit F, }
variables (J C)
/--
`C` has biproducts of shape `J` if we have
a limit and a colimit, with the same cone points,
of every function `F : J → C`.
-/
class has_biproducts_of_shape : Prop :=
(has_biproduct : Π F : J → C, has_biproduct F)
attribute [instance, priority 100] has_biproducts_of_shape.has_biproduct
/-- `has_finite_biproducts C` represents a choice of biproduct for every family of objects in `C`
indexed by a finite type. -/
class has_finite_biproducts : Prop :=
(has_biproducts_of_shape : Π (J : Type) [fintype J],
has_biproducts_of_shape J C)
attribute [instance, priority 100] has_finite_biproducts.has_biproducts_of_shape
@[priority 100]
instance has_finite_products_of_has_finite_biproducts [has_finite_biproducts C] :
has_finite_products C :=
{ out := λ J _, ⟨λ F, by exactI has_limit_of_iso discrete.nat_iso_functor.symm⟩ }
@[priority 100]
instance has_finite_coproducts_of_has_finite_biproducts [has_finite_biproducts C] :
has_finite_coproducts C :=
{ out := λ J _, ⟨λ F, by exactI has_colimit_of_iso discrete.nat_iso_functor⟩ }
variables {J C}
/--
The isomorphism between the specified limit and the specified colimit for
a functor with a bilimit.
-/
def biproduct_iso (F : J → C) [has_biproduct F] :
limits.pi_obj F ≅ limits.sigma_obj F :=
(is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (biproduct.is_limit F)).trans $
is_colimit.cocone_point_unique_up_to_iso (biproduct.is_colimit F) (colimit.is_colimit _)
end limits
namespace limits
variables {J : Type w}
variables {C : Type u} [category.{v} C] [has_zero_morphisms C]
/-- `biproduct f` computes the biproduct of a family of elements `f`. (It is defined as an
abbreviation for `limit (discrete.functor f)`, so for most facts about `biproduct f`, you will
just use general facts about limits and colimits.) -/
abbreviation biproduct (f : J → C) [has_biproduct f] : C :=
(biproduct.bicone f).X
notation `⨁ ` f:20 := biproduct f
/-- The projection onto a summand of a biproduct. -/
abbreviation biproduct.π (f : J → C) [has_biproduct f] (b : J) : ⨁ f ⟶ f b :=
(biproduct.bicone f).π b
@[simp]
lemma biproduct.bicone_π (f : J → C) [has_biproduct f] (b : J) :
(biproduct.bicone f).π b = biproduct.π f b := rfl
/-- The inclusion into a summand of a biproduct. -/
abbreviation biproduct.ι (f : J → C) [has_biproduct f] (b : J) : f b ⟶ ⨁ f :=
(biproduct.bicone f).ι b
@[simp]
lemma biproduct.bicone_ι (f : J → C) [has_biproduct f] (b : J) :
(biproduct.bicone f).ι b = biproduct.ι f b := rfl
/-- Note that as this lemma has a `if` in the statement, we include a `decidable_eq` argument.
This means you may not be able to `simp` using this lemma unless you `open_locale classical`. -/
@[reassoc]
lemma biproduct.ι_π [decidable_eq J] (f : J → C) [has_biproduct f] (j j' : J) :
biproduct.ι f j ≫ biproduct.π f j' = if h : j = j' then eq_to_hom (congr_arg f h) else 0 :=
by convert (biproduct.bicone f).ι_π j j'
@[simp,reassoc]
lemma biproduct.ι_π_self (f : J → C) [has_biproduct f] (j : J) :
biproduct.ι f j ≫ biproduct.π f j = 𝟙 _ :=
by simp [biproduct.ι_π]
@[simp,reassoc]
lemma biproduct.ι_π_ne (f : J → C) [has_biproduct f] {j j' : J} (h : j ≠ j') :
biproduct.ι f j ≫ biproduct.π f j' = 0 :=
by simp [biproduct.ι_π, h]
/-- Given a collection of maps into the summands, we obtain a map into the biproduct. -/
abbreviation biproduct.lift
{f : J → C} [has_biproduct f] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ⨁ f :=
(biproduct.is_limit f).lift (fan.mk P p)
/-- Given a collection of maps out of the summands, we obtain a map out of the biproduct. -/
abbreviation biproduct.desc
{f : J → C} [has_biproduct f] {P : C} (p : Π b, f b ⟶ P) : ⨁ f ⟶ P :=
(biproduct.is_colimit f).desc (cofan.mk P p)
@[simp, reassoc]
lemma biproduct.lift_π {f : J → C} [has_biproduct f] {P : C} (p : Π b, P ⟶ f b) (j : J) :
biproduct.lift p ≫ biproduct.π f j = p j :=
(biproduct.is_limit f).fac _ ⟨j⟩
@[simp, reassoc]
lemma biproduct.ι_desc {f : J → C} [has_biproduct f] {P : C} (p : Π b, f b ⟶ P) (j : J) :
biproduct.ι f j ≫ biproduct.desc p = p j :=
(biproduct.is_colimit f).fac _ ⟨j⟩
/-- Given a collection of maps between corresponding summands of a pair of biproducts
indexed by the same type, we obtain a map between the biproducts. -/
abbreviation biproduct.map {f g : J → C} [has_biproduct f] [has_biproduct g]
(p : Π b, f b ⟶ g b) : ⨁ f ⟶ ⨁ g :=
is_limit.map (biproduct.bicone f).to_cone (biproduct.is_limit g)
(discrete.nat_trans (λ j, p j.as))
/-- An alternative to `biproduct.map` constructed via colimits.
This construction only exists in order to show it is equal to `biproduct.map`. -/
abbreviation biproduct.map' {f g : J → C} [has_biproduct f] [has_biproduct g]
(p : Π b, f b ⟶ g b) : ⨁ f ⟶ ⨁ g :=
is_colimit.map (biproduct.is_colimit f) (biproduct.bicone g).to_cocone
(discrete.nat_trans (λ j, p j.as))
@[ext] lemma biproduct.hom_ext {f : J → C} [has_biproduct f]
{Z : C} (g h : Z ⟶ ⨁ f)
(w : ∀ j, g ≫ biproduct.π f j = h ≫ biproduct.π f j) : g = h :=
(biproduct.is_limit f).hom_ext (λ j, w j.as)
@[ext] lemma biproduct.hom_ext' {f : J → C} [has_biproduct f]
{Z : C} (g h : ⨁ f ⟶ Z)
(w : ∀ j, biproduct.ι f j ≫ g = biproduct.ι f j ≫ h) : g = h :=
(biproduct.is_colimit f).hom_ext (λ j, w j.as)
lemma biproduct.map_eq_map' {f g : J → C} [has_biproduct f] [has_biproduct g]
(p : Π b, f b ⟶ g b) : biproduct.map p = biproduct.map' p :=
begin
ext j j',
simp only [discrete.nat_trans_app, limits.is_colimit.ι_map, limits.is_limit.map_π, category.assoc,
←bicone.to_cone_π_app, ←biproduct.bicone_π, ←bicone.to_cocone_ι_app, ←biproduct.bicone_ι],
simp only [biproduct.bicone_ι, biproduct.bicone_π, bicone.to_cocone_ι_app, bicone.to_cone_π_app],
dsimp,
rw [biproduct.ι_π_assoc, biproduct.ι_π],
split_ifs,
{ subst h, rw [eq_to_hom_refl, category.id_comp], erw category.comp_id, },
{ simp, },
end
@[simp, reassoc]
lemma biproduct.map_π {f g : J → C} [has_biproduct f] [has_biproduct g]
(p : Π j, f j ⟶ g j) (j : J) :
biproduct.map p ≫ biproduct.π g j = biproduct.π f j ≫ p j :=
limits.is_limit.map_π _ _ _ (discrete.mk j)
@[simp, reassoc]
lemma biproduct.ι_map {f g : J → C} [has_biproduct f] [has_biproduct g]
(p : Π j, f j ⟶ g j) (j : J) :
biproduct.ι f j ≫ biproduct.map p = p j ≫ biproduct.ι g j :=
begin
rw biproduct.map_eq_map',
convert limits.is_colimit.ι_map _ _ _ (discrete.mk j); refl
end
@[simp, reassoc]
lemma biproduct.map_desc {f g : J → C} [has_biproduct f] [has_biproduct g]
(p : Π j, f j ⟶ g j) {P : C} (k : Π j, g j ⟶ P) :
biproduct.map p ≫ biproduct.desc k = biproduct.desc (λ j, p j ≫ k j) :=
by { ext, simp, }
@[simp, reassoc]
lemma biproduct.lift_map {f g : J → C} [has_biproduct f] [has_biproduct g]
{P : C} (k : Π j, P ⟶ f j) (p : Π j, f j ⟶ g j) :
biproduct.lift k ≫ biproduct.map p = biproduct.lift (λ j, k j ≫ p j) :=
by { ext, simp, }
/-- Given a collection of isomorphisms between corresponding summands of a pair of biproducts
indexed by the same type, we obtain an isomorphism between the biproducts. -/
@[simps]
def biproduct.map_iso {f g : J → C} [has_biproduct f] [has_biproduct g]
(p : Π b, f b ≅ g b) : ⨁ f ≅ ⨁ g :=
{ hom := biproduct.map (λ b, (p b).hom),
inv := biproduct.map (λ b, (p b).inv), }
section π_kernel
section
variables (f : J → C) [has_biproduct f]
variables (p : J → Prop) [has_biproduct (subtype.restrict p f)]
/-- The canonical morphism from the biproduct over a restricted index type to the biproduct of
the full index type. -/
def biproduct.from_subtype : ⨁ subtype.restrict p f ⟶ ⨁ f :=
biproduct.desc $ λ j, biproduct.ι _ _
/-- The canonical morphism from a biproduct to the biproduct over a restriction of its index
type. -/
def biproduct.to_subtype : ⨁ f ⟶ ⨁ subtype.restrict p f :=
biproduct.lift $ λ j, biproduct.π _ _
@[simp, reassoc]
lemma biproduct.from_subtype_π [decidable_pred p] (j : J) :
biproduct.from_subtype f p ≫ biproduct.π f j =
if h : p j then biproduct.π (subtype.restrict p f) ⟨j, h⟩ else 0 :=
begin
ext i,
rw [biproduct.from_subtype, biproduct.ι_desc_assoc, biproduct.ι_π],
by_cases h : p j,
{ rw [dif_pos h, biproduct.ι_π],
split_ifs with h₁ h₂ h₂,
exacts [rfl, false.elim (h₂ (subtype.ext h₁)),
false.elim (h₁ (congr_arg subtype.val h₂)), rfl] },
{ rw [dif_neg h, dif_neg (show (i : J) ≠ j, from λ h₂, h (h₂ ▸ i.2)), comp_zero] }
end
lemma biproduct.from_subtype_eq_lift [decidable_pred p] : biproduct.from_subtype f p =
biproduct.lift (λ j, if h : p j then biproduct.π (subtype.restrict p f) ⟨j, h⟩ else 0) :=
biproduct.hom_ext _ _ (by simp)
@[simp, reassoc]
lemma biproduct.from_subtype_π_subtype (j : subtype p) :
biproduct.from_subtype f p ≫ biproduct.π f j = biproduct.π (subtype.restrict p f) j :=
begin
ext i,
rw [biproduct.from_subtype, biproduct.ι_desc_assoc, biproduct.ι_π, biproduct.ι_π],
split_ifs with h₁ h₂ h₂,
exacts [rfl, false.elim (h₂ (subtype.ext h₁)), false.elim (h₁ (congr_arg subtype.val h₂)), rfl]
end
@[simp, reassoc]
lemma biproduct.to_subtype_π (j : subtype p) :
biproduct.to_subtype f p ≫ biproduct.π (subtype.restrict p f) j = biproduct.π f j :=
biproduct.lift_π _ _
@[simp, reassoc]
lemma biproduct.ι_to_subtype [decidable_pred p] (j : J) :
biproduct.ι f j ≫ biproduct.to_subtype f p =
if h : p j then biproduct.ι (subtype.restrict p f) ⟨j, h⟩ else 0 :=
begin
ext i,
rw [biproduct.to_subtype, category.assoc, biproduct.lift_π, biproduct.ι_π],
by_cases h : p j,
{ rw [dif_pos h, biproduct.ι_π],
split_ifs with h₁ h₂ h₂,
exacts [rfl, false.elim (h₂ (subtype.ext h₁)),
false.elim (h₁ (congr_arg subtype.val h₂)), rfl] },
{ rw [dif_neg h, dif_neg (show j ≠ i, from λ h₂, h (h₂.symm ▸ i.2)), zero_comp] }
end
lemma biproduct.to_subtype_eq_desc [decidable_pred p] : biproduct.to_subtype f p =
biproduct.desc (λ j, if h : p j then biproduct.ι (subtype.restrict p f) ⟨j, h⟩ else 0) :=
biproduct.hom_ext' _ _ (by simp)
@[simp, reassoc]
lemma biproduct.ι_to_subtype_subtype (j : subtype p) :
biproduct.ι f j ≫ biproduct.to_subtype f p = biproduct.ι (subtype.restrict p f) j :=
begin
ext i,
rw [biproduct.to_subtype, category.assoc, biproduct.lift_π, biproduct.ι_π, biproduct.ι_π],
split_ifs with h₁ h₂ h₂,
exacts [rfl, false.elim (h₂ (subtype.ext h₁)), false.elim (h₁ (congr_arg subtype.val h₂)), rfl]
end
@[simp, reassoc]
lemma biproduct.ι_from_subtype (j : subtype p) :
biproduct.ι (subtype.restrict p f) j ≫ biproduct.from_subtype f p = biproduct.ι f j :=
biproduct.ι_desc _ _
@[simp, reassoc]
lemma biproduct.from_subtype_to_subtype :
biproduct.from_subtype f p ≫ biproduct.to_subtype f p = 𝟙 (⨁ subtype.restrict p f) :=
begin
refine biproduct.hom_ext _ _ (λ j, _),
rw [category.assoc, biproduct.to_subtype_π, biproduct.from_subtype_π_subtype, category.id_comp]
end
@[simp, reassoc]
lemma biproduct.to_subtype_from_subtype [decidable_pred p] :
biproduct.to_subtype f p ≫ biproduct.from_subtype f p =
biproduct.map (λ j, if p j then 𝟙 (f j) else 0) :=
begin
ext1 i,
by_cases h : p i,
{ simp [h], congr },
{ simp [h] }
end
end
variables (f : J → C) (i : J) [has_biproduct f] [has_biproduct (subtype.restrict (λ j, i ≠ j) f)]
/-- The kernel of `biproduct.π f i` is the inclusion from the biproduct which omits `i`
from the index set `J` into the biproduct over `J`. -/
def biproduct.is_limit_from_subtype : is_limit
(kernel_fork.of_ι (biproduct.from_subtype f (λ j, i ≠ j))
(by simp) : kernel_fork (biproduct.π f i)) :=
fork.is_limit.mk' _ $ λ s,
⟨s.ι ≫ biproduct.to_subtype _ _,
begin
ext j,
rw [kernel_fork.ι_of_ι, category.assoc, category.assoc,
biproduct.to_subtype_from_subtype_assoc, biproduct.map_π],
rcases em (i = j) with (rfl|h),
{ rw [if_neg (not_not.2 rfl), comp_zero, comp_zero, kernel_fork.condition] },
{ rw [if_pos, category.comp_id], exact h, }
end,
begin
intros m hm,
rw [← hm, kernel_fork.ι_of_ι, category.assoc, biproduct.from_subtype_to_subtype],
exact (category.comp_id _).symm
end⟩
/-- The cokernel of `biproduct.ι f i` is the projection from the biproduct over the index set `J`
onto the biproduct omitting `i`. -/
def biproduct.is_colimit_to_subtype : is_colimit
(cokernel_cofork.of_π (biproduct.to_subtype f (λ j, i ≠ j))
(by simp) : cokernel_cofork (biproduct.ι f i)) :=
cofork.is_colimit.mk' _ $ λ s,
⟨biproduct.from_subtype _ _ ≫ s.π,
begin
ext j,
rw [cokernel_cofork.π_of_π, biproduct.to_subtype_from_subtype_assoc,
biproduct.ι_map_assoc],
rcases em (i = j) with (rfl|h),
{ rw [if_neg (not_not.2 rfl), zero_comp, cokernel_cofork.condition] },
{ rw [if_pos, category.id_comp], exact h, }
end,
begin
intros m hm,
rw [← hm, cokernel_cofork.π_of_π, ← category.assoc, biproduct.from_subtype_to_subtype],
exact (category.id_comp _).symm
end⟩
end π_kernel
end limits
namespace limits
section finite_biproducts
variables {J : Type} [fintype J] {K : Type} [fintype K]
{C : Type u} [category.{v} C] [has_zero_morphisms C] [has_finite_biproducts C]
{f : J → C} {g : K → C}
/--
Convert a (dependently typed) matrix to a morphism of biproducts.
-/
def biproduct.matrix (m : Π j k, f j ⟶ g k) : ⨁ f ⟶ ⨁ g :=
biproduct.desc (λ j, biproduct.lift (λ k, m j k))
@[simp, reassoc]
lemma biproduct.matrix_π (m : Π j k, f j ⟶ g k) (k : K) :
biproduct.matrix m ≫ biproduct.π g k = biproduct.desc (λ j, m j k) :=
by { ext, simp [biproduct.matrix], }
@[simp, reassoc]
lemma biproduct.ι_matrix (m : Π j k, f j ⟶ g k) (j : J) :
biproduct.ι f j ≫ biproduct.matrix m = biproduct.lift (λ k, m j k) :=
by { ext, simp [biproduct.matrix], }
/--
Extract the matrix components from a morphism of biproducts.
-/
def biproduct.components (m : ⨁ f ⟶ ⨁ g) (j : J) (k : K) : f j ⟶ g k :=
biproduct.ι f j ≫ m ≫ biproduct.π g k
@[simp] lemma biproduct.matrix_components (m : Π j k, f j ⟶ g k) (j : J) (k : K) :
biproduct.components (biproduct.matrix m) j k = m j k :=
by simp [biproduct.components]
@[simp] lemma biproduct.components_matrix (m : ⨁ f ⟶ ⨁ g) :
biproduct.matrix (λ j k, biproduct.components m j k) = m :=
by { ext, simp [biproduct.components], }
/-- Morphisms between direct sums are matrices. -/
@[simps]
def biproduct.matrix_equiv : (⨁ f ⟶ ⨁ g) ≃ (Π j k, f j ⟶ g k) :=
{ to_fun := biproduct.components,
inv_fun := biproduct.matrix,
left_inv := biproduct.components_matrix,
right_inv := λ m, by { ext, apply biproduct.matrix_components } }
end finite_biproducts
variables {J : Type w} {C : Type u} [category.{v} C] [has_zero_morphisms C]
instance biproduct.ι_mono (f : J → C) [has_biproduct f] (b : J) : split_mono (biproduct.ι f b) :=
{ retraction := biproduct.desc $ pi.single b _ }
instance biproduct.π_epi (f : J → C) [has_biproduct f] (b : J) : split_epi (biproduct.π f b) :=
{ section_ := biproduct.lift $ pi.single b _ }
/-- Auxiliary lemma for `biproduct.unique_up_to_iso`. -/
lemma biproduct.cone_point_unique_up_to_iso_hom (f : J → C) [has_biproduct f] {b : bicone f}
(hb : b.is_bilimit) :
(hb.is_limit.cone_point_unique_up_to_iso (biproduct.is_limit _)).hom = biproduct.lift b.π :=
rfl
/-- Auxiliary lemma for `biproduct.unique_up_to_iso`. -/
lemma biproduct.cone_point_unique_up_to_iso_inv (f : J → C) [has_biproduct f] {b : bicone f}
(hb : b.is_bilimit) :
(hb.is_limit.cone_point_unique_up_to_iso (biproduct.is_limit _)).inv = biproduct.desc b.ι :=
begin
refine biproduct.hom_ext' _ _ (λ j, hb.is_limit.hom_ext (λ j', _)),
discrete_cases,
rw [category.assoc, is_limit.cone_point_unique_up_to_iso_inv_comp, bicone.to_cone_π_app,
biproduct.bicone_π, biproduct.ι_desc, biproduct.ι_π, b.to_cone_π_app, b.ι_π]
end
/-- Biproducts are unique up to isomorphism. This already follows because bilimits are limits,
but in the case of biproducts we can give an isomorphism with particularly nice definitional
properties, namely that `biproduct.lift b.π` and `biproduct.desc b.ι` are inverses of each
other. -/
@[simps]
def biproduct.unique_up_to_iso (f : J → C) [has_biproduct f] {b : bicone f} (hb : b.is_bilimit) :
b.X ≅ ⨁ f :=
{ hom := biproduct.lift b.π,
inv := biproduct.desc b.ι,
hom_inv_id' := by rw [← biproduct.cone_point_unique_up_to_iso_hom f hb,
← biproduct.cone_point_unique_up_to_iso_inv f hb, iso.hom_inv_id],
inv_hom_id' := by rw [← biproduct.cone_point_unique_up_to_iso_hom f hb,
← biproduct.cone_point_unique_up_to_iso_inv f hb, iso.inv_hom_id] }
variables (C)
/-- A category with finite biproducts has a zero object. -/
@[priority 100] -- see Note [lower instance priority]
instance has_zero_object_of_has_finite_biproducts [has_finite_biproducts C] : has_zero_object C :=
by { refine ⟨⟨biproduct empty.elim, λ X, ⟨⟨⟨0⟩, _⟩⟩, λ X, ⟨⟨⟨0⟩, _⟩⟩⟩⟩, tidy, }
section
variables {C} [unique J] (f : J → C)
/-- The limit bicone for the biproduct over an index type with exactly one term. -/
@[simps]
def limit_bicone_of_unique : limit_bicone f :=
{ bicone :=
{ X := f default,
π := λ j, eq_to_hom (by congr),
ι := λ j, eq_to_hom (by congr), },
is_bilimit :=
{ is_limit := (limit_cone_of_unique f).is_limit,
is_colimit := (colimit_cocone_of_unique f).is_colimit, }, }
@[priority 100] instance has_biproduct_unique : has_biproduct f :=
has_biproduct.mk (limit_bicone_of_unique f)
/-- A biproduct over a index type with exactly one term is just the object over that term. -/
@[simps]
def biproduct_unique_iso : ⨁ f ≅ f default :=
(biproduct.unique_up_to_iso _ (limit_bicone_of_unique f).is_bilimit).symm
end
variables {C}
/--
A binary bicone for a pair of objects `P Q : C` consists of the cone point `X`,
maps from `X` to both `P` and `Q`, and maps from both `P` and `Q` to `X`,
so that `inl ≫ fst = 𝟙 P`, `inl ≫ snd = 0`, `inr ≫ fst = 0`, and `inr ≫ snd = 𝟙 Q`
-/
@[nolint has_inhabited_instance]
structure binary_bicone (P Q : C) :=
(X : C)
(fst : X ⟶ P)
(snd : X ⟶ Q)
(inl : P ⟶ X)
(inr : Q ⟶ X)
(inl_fst' : inl ≫ fst = 𝟙 P . obviously)
(inl_snd' : inl ≫ snd = 0 . obviously)
(inr_fst' : inr ≫ fst = 0 . obviously)
(inr_snd' : inr ≫ snd = 𝟙 Q . obviously)
restate_axiom binary_bicone.inl_fst'
restate_axiom binary_bicone.inl_snd'
restate_axiom binary_bicone.inr_fst'
restate_axiom binary_bicone.inr_snd'
attribute [simp, reassoc] binary_bicone.inl_fst binary_bicone.inl_snd
binary_bicone.inr_fst binary_bicone.inr_snd
namespace binary_bicone
variables {P Q : C}
/-- Extract the cone from a binary bicone. -/
def to_cone (c : binary_bicone P Q) : cone (pair P Q) :=
binary_fan.mk c.fst c.snd
@[simp]
lemma to_cone_X (c : binary_bicone P Q) :
c.to_cone.X = c.X := rfl
@[simp]
lemma to_cone_π_app_left (c : binary_bicone P Q) :
c.to_cone.π.app ⟨walking_pair.left⟩ = c.fst := rfl
@[simp]
lemma to_cone_π_app_right (c : binary_bicone P Q) :
c.to_cone.π.app ⟨walking_pair.right⟩ = c.snd := rfl
@[simp]
lemma binary_fan_fst_to_cone (c : binary_bicone P Q) : binary_fan.fst c.to_cone = c.fst := rfl
@[simp]
lemma binary_fan_snd_to_cone (c : binary_bicone P Q) : binary_fan.snd c.to_cone = c.snd := rfl
/-- Extract the cocone from a binary bicone. -/
def to_cocone (c : binary_bicone P Q) : cocone (pair P Q) :=
binary_cofan.mk c.inl c.inr
@[simp]
lemma to_cocone_X (c : binary_bicone P Q) :
c.to_cocone.X = c.X := rfl
@[simp]
lemma to_cocone_ι_app_left (c : binary_bicone P Q) :
c.to_cocone.ι.app ⟨walking_pair.left⟩ = c.inl := rfl
@[simp]
lemma to_cocone_ι_app_right (c : binary_bicone P Q) :
c.to_cocone.ι.app ⟨walking_pair.right⟩ = c.inr := rfl
@[simp]
lemma binary_cofan_inl_to_cocone (c : binary_bicone P Q) : binary_cofan.inl c.to_cocone = c.inl :=
rfl
@[simp]
lemma binary_cofan_inr_to_cocone (c : binary_bicone P Q) : binary_cofan.inr c.to_cocone = c.inr :=
rfl
instance (c : binary_bicone P Q) : split_mono c.inl := { retraction := c.fst, id' := c.inl_fst }
instance (c : binary_bicone P Q) : split_mono c.inr := { retraction := c.snd, id' := c.inr_snd }
instance (c : binary_bicone P Q) : split_epi c.fst := { section_ := c.inl, id' := c.inl_fst }
instance (c : binary_bicone P Q) : split_epi c.snd := { section_ := c.inr, id' := c.inr_snd }
/-- Convert a `binary_bicone` into a `bicone` over a pair. -/
@[simps]
def to_bicone {X Y : C} (b : binary_bicone X Y) : bicone (pair_function X Y) :=
{ X := b.X,
π := λ j, walking_pair.cases_on j b.fst b.snd,
ι := λ j, walking_pair.cases_on j b.inl b.inr,
ι_π := λ j j', by { rcases j with ⟨⟩; rcases j' with ⟨⟩, tidy } }
/-- A binary bicone is a limit cone if and only if the corresponding bicone is a limit cone. -/
def to_bicone_is_limit {X Y : C} (b : binary_bicone X Y) :
is_limit (b.to_bicone.to_cone) ≃ is_limit (b.to_cone) :=
is_limit.equiv_iso_limit $ cones.ext (iso.refl _) (λ j, by { cases j, tidy })
/-- A binary bicone is a colimit cocone if and only if the corresponding bicone is a colimit
cocone. -/
def to_bicone_is_colimit {X Y : C} (b : binary_bicone X Y) :
is_colimit (b.to_bicone.to_cocone) ≃ is_colimit (b.to_cocone) :=
is_colimit.equiv_iso_colimit $ cocones.ext (iso.refl _) (λ j, by { cases j, tidy })
end binary_bicone
namespace bicone
/-- Convert a `bicone` over a function on `walking_pair` to a binary_bicone. -/
@[simps]
def to_binary_bicone {X Y : C} (b : bicone (pair_function X Y)) : binary_bicone X Y :=
{ X := b.X,
fst := b.π walking_pair.left,
snd := b.π walking_pair.right,
inl := b.ι walking_pair.left,
inr := b.ι walking_pair.right,
inl_fst' := by { simp [bicone.ι_π], refl, },
inr_fst' := by simp [bicone.ι_π],
inl_snd' := by simp [bicone.ι_π],
inr_snd' := by { simp [bicone.ι_π], refl, }, }
/-- A bicone over a pair is a limit cone if and only if the corresponding binary bicone is a limit
cone. -/
def to_binary_bicone_is_limit {X Y : C} (b : bicone (pair_function X Y)) :
is_limit (b.to_binary_bicone.to_cone) ≃ is_limit (b.to_cone) :=
is_limit.equiv_iso_limit $ cones.ext (iso.refl _) (λ j, by { rcases j with ⟨⟨⟩⟩; tidy })
/-- A bicone over a pair is a colimit cocone if and only if the corresponding binary bicone is a
colimit cocone. -/
def to_binary_bicone_is_colimit {X Y : C} (b : bicone (pair_function X Y)) :
is_colimit (b.to_binary_bicone.to_cocone) ≃ is_colimit (b.to_cocone) :=
is_colimit.equiv_iso_colimit $ cocones.ext (iso.refl _) (λ j, by { rcases j with ⟨⟨⟩⟩; tidy })
end bicone
/-- Structure witnessing that a binary bicone is a limit cone and a limit cocone. -/
@[nolint has_inhabited_instance]
structure binary_bicone.is_bilimit {P Q : C} (b : binary_bicone P Q) :=
(is_limit : is_limit b.to_cone)
(is_colimit : is_colimit b.to_cocone)
/-- A binary bicone is a bilimit bicone if and only if the corresponding bicone is a bilimit. -/
def binary_bicone.to_bicone_is_bilimit {X Y : C} (b : binary_bicone X Y) :
b.to_bicone.is_bilimit ≃ b.is_bilimit :=
{ to_fun := λ h, ⟨b.to_bicone_is_limit h.is_limit, b.to_bicone_is_colimit h.is_colimit⟩,
inv_fun := λ h, ⟨b.to_bicone_is_limit.symm h.is_limit, b.to_bicone_is_colimit.symm h.is_colimit⟩,
left_inv := λ ⟨h, h'⟩, by { dsimp only, simp },
right_inv := λ ⟨h, h'⟩, by { dsimp only, simp } }
/-- A bicone over a pair is a bilimit bicone if and only if the corresponding binary bicone is a
bilimit. -/
def bicone.to_binary_bicone_is_bilimit {X Y : C} (b : bicone (pair_function X Y)) :
b.to_binary_bicone.is_bilimit ≃ b.is_bilimit :=
{ to_fun := λ h, ⟨b.to_binary_bicone_is_limit h.is_limit,
b.to_binary_bicone_is_colimit h.is_colimit⟩,
inv_fun := λ h, ⟨b.to_binary_bicone_is_limit.symm h.is_limit,
b.to_binary_bicone_is_colimit.symm h.is_colimit⟩,
left_inv := λ ⟨h, h'⟩, by { dsimp only, simp },
right_inv := λ ⟨h, h'⟩, by { dsimp only, simp } }
/--
A bicone over `P Q : C`, which is both a limit cone and a colimit cocone.
-/
@[nolint has_inhabited_instance]
structure binary_biproduct_data (P Q : C) :=
(bicone : binary_bicone P Q)
(is_bilimit : bicone.is_bilimit)
/--
`has_binary_biproduct P Q` expresses the mere existence of a bicone which is
simultaneously a limit and a colimit of the diagram `pair P Q`.
-/
class has_binary_biproduct (P Q : C) : Prop :=
mk' :: (exists_binary_biproduct : nonempty (binary_biproduct_data P Q))
lemma has_binary_biproduct.mk {P Q : C} (d : binary_biproduct_data P Q) :
has_binary_biproduct P Q :=
⟨nonempty.intro d⟩
/--
Use the axiom of choice to extract explicit `binary_biproduct_data F` from `has_binary_biproduct F`.
-/
def get_binary_biproduct_data (P Q : C) [has_binary_biproduct P Q] : binary_biproduct_data P Q :=
classical.choice has_binary_biproduct.exists_binary_biproduct
/-- A bicone for `P Q ` which is both a limit cone and a colimit cocone. -/
def binary_biproduct.bicone (P Q : C) [has_binary_biproduct P Q] : binary_bicone P Q :=
(get_binary_biproduct_data P Q).bicone
/-- `binary_biproduct.bicone P Q` is a limit bicone. -/
def binary_biproduct.is_bilimit (P Q : C) [has_binary_biproduct P Q] :
(binary_biproduct.bicone P Q).is_bilimit :=
(get_binary_biproduct_data P Q).is_bilimit
/-- `binary_biproduct.bicone P Q` is a limit cone. -/
def binary_biproduct.is_limit (P Q : C) [has_binary_biproduct P Q] :
is_limit (binary_biproduct.bicone P Q).to_cone :=
(get_binary_biproduct_data P Q).is_bilimit.is_limit
/-- `binary_biproduct.bicone P Q` is a colimit cocone. -/
def binary_biproduct.is_colimit (P Q : C) [has_binary_biproduct P Q] :
is_colimit (binary_biproduct.bicone P Q).to_cocone :=
(get_binary_biproduct_data P Q).is_bilimit.is_colimit
section
variable (C)
/--
`has_binary_biproducts C` represents the existence of a bicone which is
simultaneously a limit and a colimit of the diagram `pair P Q`, for every `P Q : C`.
-/
class has_binary_biproducts : Prop :=
(has_binary_biproduct : Π (P Q : C), has_binary_biproduct P Q)
attribute [instance, priority 100] has_binary_biproducts.has_binary_biproduct
/--
A category with finite biproducts has binary biproducts.
This is not an instance as typically in concrete categories there will be
an alternative construction with nicer definitional properties.
-/
lemma has_binary_biproducts_of_finite_biproducts [has_finite_biproducts C] :
has_binary_biproducts C :=
{ has_binary_biproduct := λ P Q, has_binary_biproduct.mk
{ bicone := (biproduct.bicone (pair_function P Q)).to_binary_bicone,
is_bilimit := (bicone.to_binary_bicone_is_bilimit _).symm (biproduct.is_bilimit _) } }
end
variables {P Q : C}
instance has_binary_biproduct.has_limit_pair [has_binary_biproduct P Q] :
has_limit (pair P Q) :=
has_limit.mk ⟨_, binary_biproduct.is_limit P Q⟩
instance has_binary_biproduct.has_colimit_pair [has_binary_biproduct P Q] :
has_colimit (pair P Q) :=
has_colimit.mk ⟨_, binary_biproduct.is_colimit P Q⟩
@[priority 100]
instance has_binary_products_of_has_binary_biproducts [has_binary_biproducts C] :
has_binary_products C :=
{ has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm }
@[priority 100]
instance has_binary_coproducts_of_has_binary_biproducts [has_binary_biproducts C] :
has_binary_coproducts C :=
{ has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) }
/--
The isomorphism between the specified binary product and the specified binary coproduct for
a pair for a binary biproduct.
-/
def biprod_iso (X Y : C) [has_binary_biproduct X Y] :
limits.prod X Y ≅ limits.coprod X Y :=
(is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (binary_biproduct.is_limit X Y)).trans $
is_colimit.cocone_point_unique_up_to_iso (binary_biproduct.is_colimit X Y) (colimit.is_colimit _)
/-- An arbitrary choice of biproduct of a pair of objects. -/
abbreviation biprod (X Y : C) [has_binary_biproduct X Y] := (binary_biproduct.bicone X Y).X
notation X ` ⊞ `:20 Y:20 := biprod X Y
/-- The projection onto the first summand of a binary biproduct. -/
abbreviation biprod.fst {X Y : C} [has_binary_biproduct X Y] : X ⊞ Y ⟶ X :=
(binary_biproduct.bicone X Y).fst
/-- The projection onto the second summand of a binary biproduct. -/
abbreviation biprod.snd {X Y : C} [has_binary_biproduct X Y] : X ⊞ Y ⟶ Y :=
(binary_biproduct.bicone X Y).snd
/-- The inclusion into the first summand of a binary biproduct. -/
abbreviation biprod.inl {X Y : C} [has_binary_biproduct X Y] : X ⟶ X ⊞ Y :=
(binary_biproduct.bicone X Y).inl
/-- The inclusion into the second summand of a binary biproduct. -/
abbreviation biprod.inr {X Y : C} [has_binary_biproduct X Y] : Y ⟶ X ⊞ Y :=
(binary_biproduct.bicone X Y).inr
section
variables {X Y : C} [has_binary_biproduct X Y]
@[simp] lemma binary_biproduct.bicone_fst : (binary_biproduct.bicone X Y).fst = biprod.fst := rfl
@[simp] lemma binary_biproduct.bicone_snd : (binary_biproduct.bicone X Y).snd = biprod.snd := rfl
@[simp] lemma binary_biproduct.bicone_inl : (binary_biproduct.bicone X Y).inl = biprod.inl := rfl
@[simp] lemma binary_biproduct.bicone_inr : (binary_biproduct.bicone X Y).inr = biprod.inr := rfl
end
@[simp,reassoc]
lemma biprod.inl_fst {X Y : C} [has_binary_biproduct X Y] :
(biprod.inl : X ⟶ X ⊞ Y) ≫ (biprod.fst : X ⊞ Y ⟶ X) = 𝟙 X :=
(binary_biproduct.bicone X Y).inl_fst
@[simp,reassoc]
lemma biprod.inl_snd {X Y : C} [has_binary_biproduct X Y] :
(biprod.inl : X ⟶ X ⊞ Y) ≫ (biprod.snd : X ⊞ Y ⟶ Y) = 0 :=
(binary_biproduct.bicone X Y).inl_snd
@[simp,reassoc]
lemma biprod.inr_fst {X Y : C} [has_binary_biproduct X Y] :
(biprod.inr : Y ⟶ X ⊞ Y) ≫ (biprod.fst : X ⊞ Y ⟶ X) = 0 :=
(binary_biproduct.bicone X Y).inr_fst
@[simp,reassoc]
lemma biprod.inr_snd {X Y : C} [has_binary_biproduct X Y] :
(biprod.inr : Y ⟶ X ⊞ Y) ≫ (biprod.snd : X ⊞ Y ⟶ Y) = 𝟙 Y :=
(binary_biproduct.bicone X Y).inr_snd
/-- Given a pair of maps into the summands of a binary biproduct,
we obtain a map into the binary biproduct. -/
abbreviation biprod.lift {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) :
W ⟶ X ⊞ Y :=
(binary_biproduct.is_limit X Y).lift (binary_fan.mk f g)
/-- Given a pair of maps out of the summands of a binary biproduct,
we obtain a map out of the binary biproduct. -/
abbreviation biprod.desc {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) :
X ⊞ Y ⟶ W :=
(binary_biproduct.is_colimit X Y).desc (binary_cofan.mk f g)
@[simp, reassoc]
lemma biprod.lift_fst {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) :
biprod.lift f g ≫ biprod.fst = f :=
(binary_biproduct.is_limit X Y).fac _ ⟨walking_pair.left⟩
@[simp, reassoc]
lemma biprod.lift_snd {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) :
biprod.lift f g ≫ biprod.snd = g :=
(binary_biproduct.is_limit X Y).fac _ ⟨walking_pair.right⟩
@[simp, reassoc]
lemma biprod.inl_desc {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) :
biprod.inl ≫ biprod.desc f g = f :=
(binary_biproduct.is_colimit X Y).fac _ ⟨walking_pair.left⟩
@[simp, reassoc]
lemma biprod.inr_desc {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) :
biprod.inr ≫ biprod.desc f g = g :=
(binary_biproduct.is_colimit X Y).fac _ ⟨walking_pair.right⟩
instance biprod.mono_lift_of_mono_left {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X)
(g : W ⟶ Y) [mono f] : mono (biprod.lift f g) :=
mono_of_mono_fac $ biprod.lift_fst _ _
instance biprod.mono_lift_of_mono_right {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X)
(g : W ⟶ Y) [mono g] : mono (biprod.lift f g) :=
mono_of_mono_fac $ biprod.lift_snd _ _
instance biprod.epi_desc_of_epi_left {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W)
[epi f] : epi (biprod.desc f g) :=
epi_of_epi_fac $ biprod.inl_desc _ _
instance biprod.epi_desc_of_epi_right {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W)
[epi g] : epi (biprod.desc f g) :=
epi_of_epi_fac $ biprod.inr_desc _ _
/-- Given a pair of maps between the summands of a pair of binary biproducts,
we obtain a map between the binary biproducts. -/
abbreviation biprod.map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z]
(f : W ⟶ Y) (g : X ⟶ Z) : W ⊞ X ⟶ Y ⊞ Z :=
is_limit.map (binary_biproduct.bicone W X).to_cone (binary_biproduct.is_limit Y Z)
(@map_pair _ _ (pair W X) (pair Y Z) f g)
/-- An alternative to `biprod.map` constructed via colimits.
This construction only exists in order to show it is equal to `biprod.map`. -/
abbreviation biprod.map' {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z]
(f : W ⟶ Y) (g : X ⟶ Z) : W ⊞ X ⟶ Y ⊞ Z :=
is_colimit.map (binary_biproduct.is_colimit W X) (binary_biproduct.bicone Y Z).to_cocone
(@map_pair _ _ (pair W X) (pair Y Z) f g)
@[ext] lemma biprod.hom_ext {X Y Z : C} [has_binary_biproduct X Y] (f g : Z ⟶ X ⊞ Y)
(h₀ : f ≫ biprod.fst = g ≫ biprod.fst) (h₁ : f ≫ biprod.snd = g ≫ biprod.snd) : f = g :=
binary_fan.is_limit.hom_ext (binary_biproduct.is_limit X Y) h₀ h₁
@[ext] lemma biprod.hom_ext' {X Y Z : C} [has_binary_biproduct X Y] (f g : X ⊞ Y ⟶ Z)
(h₀ : biprod.inl ≫ f = biprod.inl ≫ g) (h₁ : biprod.inr ≫ f = biprod.inr ≫ g) : f = g :=
binary_cofan.is_colimit.hom_ext (binary_biproduct.is_colimit X Y) h₀ h₁
lemma biprod.map_eq_map' {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z]
(f : W ⟶ Y) (g : X ⟶ Z) : biprod.map f g = biprod.map' f g :=
begin
ext,
{ simp only [map_pair_left, is_colimit.ι_map, is_limit.map_π, biprod.inl_fst_assoc,
category.assoc, ←binary_bicone.to_cone_π_app_left, ←binary_biproduct.bicone_fst,
←binary_bicone.to_cocone_ι_app_left, ←binary_biproduct.bicone_inl],
simp },
{ simp only [map_pair_left, is_colimit.ι_map, is_limit.map_π, zero_comp,
biprod.inl_snd_assoc, category.assoc,
←binary_bicone.to_cone_π_app_right, ←binary_biproduct.bicone_snd,
←binary_bicone.to_cocone_ι_app_left, ←binary_biproduct.bicone_inl],
simp },
{ simp only [map_pair_right, biprod.inr_fst_assoc, is_colimit.ι_map, is_limit.map_π,
zero_comp, category.assoc,
←binary_bicone.to_cone_π_app_left, ←binary_biproduct.bicone_fst,
←binary_bicone.to_cocone_ι_app_right, ←binary_biproduct.bicone_inr],
simp },
{ simp only [map_pair_right, is_colimit.ι_map, is_limit.map_π, biprod.inr_snd_assoc,
category.assoc, ←binary_bicone.to_cone_π_app_right, ←binary_biproduct.bicone_snd,
←binary_bicone.to_cocone_ι_app_right, ←binary_biproduct.bicone_inr],
simp }
end
instance biprod.inl_mono {X Y : C} [has_binary_biproduct X Y] :
split_mono (biprod.inl : X ⟶ X ⊞ Y) :=
{ retraction := biprod.desc (𝟙 X) (biprod.inr ≫ biprod.fst) }
instance biprod.inr_mono {X Y : C} [has_binary_biproduct X Y] :
split_mono (biprod.inr : Y ⟶ X ⊞ Y) :=
{ retraction := biprod.desc (biprod.inl ≫ biprod.snd) (𝟙 Y)}
instance biprod.fst_epi {X Y : C} [has_binary_biproduct X Y] :
split_epi (biprod.fst : X ⊞ Y ⟶ X) :=
{ section_ := biprod.lift (𝟙 X) (biprod.inl ≫ biprod.snd) }
instance biprod.snd_epi {X Y : C} [has_binary_biproduct X Y] :
split_epi (biprod.snd : X ⊞ Y ⟶ Y) :=
{ section_ := biprod.lift (biprod.inr ≫ biprod.fst) (𝟙 Y) }
@[simp,reassoc]
lemma biprod.map_fst {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z]
(f : W ⟶ Y) (g : X ⟶ Z) :
biprod.map f g ≫ biprod.fst = biprod.fst ≫ f :=
is_limit.map_π _ _ _ (⟨walking_pair.left⟩ : discrete walking_pair)
@[simp,reassoc]
lemma biprod.map_snd {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z]
(f : W ⟶ Y) (g : X ⟶ Z) :
biprod.map f g ≫ biprod.snd = biprod.snd ≫ g :=
is_limit.map_π _ _ _ (⟨walking_pair.right⟩ : discrete walking_pair)
-- Because `biprod.map` is defined in terms of `lim` rather than `colim`,
-- we need to provide additional `simp` lemmas.
@[simp,reassoc]
lemma biprod.inl_map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z]
(f : W ⟶ Y) (g : X ⟶ Z) :
biprod.inl ≫ biprod.map f g = f ≫ biprod.inl :=
begin
rw biprod.map_eq_map',
exact is_colimit.ι_map (binary_biproduct.is_colimit W X) _ _ ⟨walking_pair.left⟩
end
@[simp,reassoc]
lemma biprod.inr_map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z]
(f : W ⟶ Y) (g : X ⟶ Z) :
biprod.inr ≫ biprod.map f g = g ≫ biprod.inr :=
begin
rw biprod.map_eq_map',
exact is_colimit.ι_map (binary_biproduct.is_colimit W X) _ _ ⟨walking_pair.right⟩
end
/-- Given a pair of isomorphisms between the summands of a pair of binary biproducts,
we obtain an isomorphism between the binary biproducts. -/
@[simps]
def biprod.map_iso {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z]
(f : W ≅ Y) (g : X ≅ Z) : W ⊞ X ≅ Y ⊞ Z :=
{ hom := biprod.map f.hom g.hom,
inv := biprod.map f.inv g.inv }
/-- Auxiliary lemma for `biprod.unique_up_to_iso`. -/
lemma biprod.cone_point_unique_up_to_iso_hom (X Y : C) [has_binary_biproduct X Y]
{b : binary_bicone X Y} (hb : b.is_bilimit) :
(hb.is_limit.cone_point_unique_up_to_iso (binary_biproduct.is_limit _ _)).hom
= biprod.lift b.fst b.snd :=
rfl
/-- Auxiliary lemma for `biprod.unique_up_to_iso`. -/
lemma biprod.cone_point_unique_up_to_iso_inv (X Y : C) [has_binary_biproduct X Y]
{b : binary_bicone X Y} (hb : b.is_bilimit) :
(hb.is_limit.cone_point_unique_up_to_iso (binary_biproduct.is_limit _ _)).inv
= biprod.desc b.inl b.inr :=
begin
refine biprod.hom_ext' _ _ (hb.is_limit.hom_ext (λ j, _)) (hb.is_limit.hom_ext (λ j, _)),
all_goals { simp only [category.assoc, is_limit.cone_point_unique_up_to_iso_inv_comp],
rcases j with ⟨⟨⟩⟩ },
all_goals { simp }
end
/-- Binary biproducts are unique up to isomorphism. This already follows because bilimits are
limits, but in the case of biproducts we can give an isomorphism with particularly nice
definitional properties, namely that `biprod.lift b.fst b.snd` and `biprod.desc b.inl b.inr`
are inverses of each other. -/
@[simps]
def biprod.unique_up_to_iso (X Y : C) [has_binary_biproduct X Y] {b : binary_bicone X Y}
(hb : b.is_bilimit) : b.X ≅ X ⊞ Y :=
{ hom := biprod.lift b.fst b.snd,
inv := biprod.desc b.inl b.inr,
hom_inv_id' := by rw [← biprod.cone_point_unique_up_to_iso_hom X Y hb,
← biprod.cone_point_unique_up_to_iso_inv X Y hb, iso.hom_inv_id],
inv_hom_id' := by rw [← biprod.cone_point_unique_up_to_iso_hom X Y hb,
← biprod.cone_point_unique_up_to_iso_inv X Y hb, iso.inv_hom_id] }
section
variables (X Y : C) [has_binary_biproduct X Y]
-- There are three further variations,
-- about `is_iso biprod.inr`, `is_iso biprod.fst` and `is_iso biprod.snd`,
-- but any one suffices to prove `indecomposable_of_simple`
-- and they are likely not separately useful.
lemma biprod.is_iso_inl_iff_id_eq_fst_comp_inl :
is_iso (biprod.inl : X ⟶ X ⊞ Y) ↔ 𝟙 (X ⊞ Y) = biprod.fst ≫ biprod.inl :=
begin
split,
{ introI h,
have := (cancel_epi (inv biprod.inl : X ⊞ Y ⟶ X)).2 biprod.inl_fst,
rw [is_iso.inv_hom_id_assoc, category.comp_id] at this,
rw [this, is_iso.inv_hom_id], },
{ intro h, exact ⟨⟨biprod.fst, biprod.inl_fst, h.symm⟩⟩, },
end
end
section biprod_kernel
section binary_bicone
variables {X Y : C} (c : binary_bicone X Y)
/-- A kernel fork for the kernel of `binary_bicone.fst`. It consists of the morphism
`binary_bicone.inr`. -/
def binary_bicone.fst_kernel_fork : kernel_fork c.fst := kernel_fork.of_ι c.inr c.inr_fst
@[simp] lemma binary_bicone.fst_kernel_fork_ι : (binary_bicone.fst_kernel_fork c).ι = c.inr := rfl
/-- A kernel fork for the kernel of `binary_bicone.snd`. It consists of the morphism
`binary_bicone.inl`. -/
def binary_bicone.snd_kernel_fork : kernel_fork c.snd := kernel_fork.of_ι c.inl c.inl_snd
@[simp] lemma binary_bicone.snd_kernel_fork_ι : (binary_bicone.snd_kernel_fork c).ι = c.inl := rfl
/-- A cokernel cofork for the cokernel of `binary_bicone.inl`. It consists of the morphism
`binary_bicone.snd`. -/
def binary_bicone.inl_cokernel_cofork : cokernel_cofork c.inl :=
cokernel_cofork.of_π c.snd c.inl_snd
@[simp] lemma binary_bicone.inl_cokernel_cofork_π :
(binary_bicone.inl_cokernel_cofork c).π = c.snd := rfl
/-- A cokernel cofork for the cokernel of `binary_bicone.inr`. It consists of the morphism
`binary_bicone.fst`. -/
def binary_bicone.inr_cokernel_cofork : cokernel_cofork c.inr :=
cokernel_cofork.of_π c.fst c.inr_fst
@[simp] lemma binary_bicone.inr_cokernel_cofork_π :
(binary_bicone.inr_cokernel_cofork c).π = c.fst := rfl
variables {c}
/-- The fork defined in `binary_bicone.fst_kernel_fork` is indeed a kernel. -/
def binary_bicone.is_limit_fst_kernel_fork (i : is_limit c.to_cone) :
is_limit c.fst_kernel_fork :=
fork.is_limit.mk' _ $ λ s,
⟨s.ι ≫ c.snd, by apply binary_fan.is_limit.hom_ext i; simp, λ m hm, by simp [← hm]⟩
/-- The fork defined in `binary_bicone.snd_kernel_fork` is indeed a kernel. -/
def binary_bicone.is_limit_snd_kernel_fork (i : is_limit c.to_cone) :
is_limit c.snd_kernel_fork :=
fork.is_limit.mk' _ $ λ s,
⟨s.ι ≫ c.fst, by apply binary_fan.is_limit.hom_ext i; simp, λ m hm, by simp [← hm]⟩
/-- The cofork defined in `binary_bicone.inl_cokernel_cofork` is indeed a cokernel. -/
def binary_bicone.is_colimit_inl_cokernel_cofork (i : is_colimit c.to_cocone) :
is_colimit c.inl_cokernel_cofork :=
cofork.is_colimit.mk' _ $ λ s, ⟨c.inr ≫ s.π, by apply binary_cofan.is_colimit.hom_ext i; simp,
λ m hm, by simp [← hm]⟩
/-- The cofork defined in `binary_bicone.inr_cokernel_cofork` is indeed a cokernel. -/
def binary_bicone.is_colimit_inr_cokernel_cofork (i : is_colimit c.to_cocone) :
is_colimit c.inr_cokernel_cofork :=
cofork.is_colimit.mk' _ $ λ s, ⟨c.inl ≫ s.π, by apply binary_cofan.is_colimit.hom_ext i; simp,
λ m hm, by simp [← hm]⟩
end binary_bicone
section has_binary_biproduct
variables (X Y : C) [has_binary_biproduct X Y]
/-- A kernel fork for the kernel of `biprod.fst`. It consists of the
morphism `biprod.inr`. -/
def biprod.fst_kernel_fork : kernel_fork (biprod.fst : X ⊞ Y ⟶ X) :=
binary_bicone.fst_kernel_fork _
@[simp]
lemma biprod.fst_kernel_fork_ι : fork.ι (biprod.fst_kernel_fork X Y) = biprod.inr :=
rfl
/-- The fork `biprod.fst_kernel_fork` is indeed a limit. -/
def biprod.is_kernel_fst_kernel_fork : is_limit (biprod.fst_kernel_fork X Y) :=
binary_bicone.is_limit_fst_kernel_fork (binary_biproduct.is_limit _ _)
/-- A kernel fork for the kernel of `biprod.snd`. It consists of the
morphism `biprod.inl`. -/
def biprod.snd_kernel_fork : kernel_fork (biprod.snd : X ⊞ Y ⟶ Y) :=
binary_bicone.snd_kernel_fork _
@[simp]
lemma biprod.snd_kernel_fork_ι : fork.ι (biprod.snd_kernel_fork X Y) = biprod.inl :=
rfl
/-- The fork `biprod.snd_kernel_fork` is indeed a limit. -/
def biprod.is_kernel_snd_kernel_fork : is_limit (biprod.snd_kernel_fork X Y) :=
binary_bicone.is_limit_snd_kernel_fork (binary_biproduct.is_limit _ _)
/-- A cokernel cofork for the cokernel of `biprod.inl`. It consists of the
morphism `biprod.snd`. -/
def biprod.inl_cokernel_cofork : cokernel_cofork (biprod.inl : X ⟶ X ⊞ Y) :=
binary_bicone.inl_cokernel_cofork _
@[simp]
lemma biprod.inl_cokernel_cofork_π : cofork.π (biprod.inl_cokernel_cofork X Y) = biprod.snd :=
rfl
/-- The cofork `biprod.inl_cokernel_fork` is indeed a colimit. -/
def biprod.is_cokernel_inl_cokernel_fork : is_colimit (biprod.inl_cokernel_cofork X Y) :=
binary_bicone.is_colimit_inl_cokernel_cofork (binary_biproduct.is_colimit _ _)
/-- A cokernel cofork for the cokernel of `biprod.inr`. It consists of the
morphism `biprod.fst`. -/
def biprod.inr_cokernel_cofork : cokernel_cofork (biprod.inr : Y ⟶ X ⊞ Y) :=
binary_bicone.inr_cokernel_cofork _
@[simp]
lemma biprod.inr_cokernel_cofork_π : cofork.π (biprod.inr_cokernel_cofork X Y) = biprod.fst :=
rfl
/-- The cofork `biprod.inr_cokernel_fork` is indeed a colimit. -/
def biprod.is_cokernel_inr_cokernel_fork : is_colimit (biprod.inr_cokernel_cofork X Y) :=
binary_bicone.is_colimit_inr_cokernel_cofork (binary_biproduct.is_colimit _ _)
end has_binary_biproduct
end biprod_kernel
section is_zero
/-- If `Y` is a zero object, `X ≅ X ⊞ Y` for any `X`. -/
@[simps]
def iso_biprod_zero {X Y : C} [has_binary_biproduct X Y] (hY : is_zero Y) : X ≅ X ⊞ Y :=
{ hom := biprod.inl,
inv := biprod.fst,
inv_hom_id' := begin
apply category_theory.limits.biprod.hom_ext;
simp only [category.assoc, biprod.inl_fst, category.comp_id, category.id_comp,
biprod.inl_snd, comp_zero],
apply hY.eq_of_tgt
end }
/-- If `X` is a zero object, `Y ≅ X ⊞ Y` for any `Y`. -/
@[simps]
def iso_zero_biprod {X Y : C} [has_binary_biproduct X Y] (hY : is_zero X) : Y ≅ X ⊞ Y :=
{ hom := biprod.inr,
inv := biprod.snd,
inv_hom_id' := begin
apply category_theory.limits.biprod.hom_ext;
simp only [category.assoc, biprod.inr_snd, category.comp_id, category.id_comp,
biprod.inr_fst, comp_zero],
apply hY.eq_of_tgt
end }
end is_zero
section
variables [has_binary_biproducts C]
/-- The braiding isomorphism which swaps a binary biproduct. -/
@[simps] def biprod.braiding (P Q : C) : P ⊞ Q ≅ Q ⊞ P :=
{ hom := biprod.lift biprod.snd biprod.fst,
inv := biprod.lift biprod.snd biprod.fst }
/--
An alternative formula for the braiding isomorphism which swaps a binary biproduct,
using the fact that the biproduct is a coproduct.
-/
@[simps]
def biprod.braiding' (P Q : C) : P ⊞ Q ≅ Q ⊞ P :=
{ hom := biprod.desc biprod.inr biprod.inl,
inv := biprod.desc biprod.inr biprod.inl }
lemma biprod.braiding'_eq_braiding {P Q : C} :
biprod.braiding' P Q = biprod.braiding P Q :=
by tidy
/-- The braiding isomorphism can be passed through a map by swapping the order. -/
@[reassoc] lemma biprod.braid_natural {W X Y Z : C} (f : X ⟶ Y) (g : Z ⟶ W) :
biprod.map f g ≫ (biprod.braiding _ _).hom = (biprod.braiding _ _).hom ≫ biprod.map g f :=
by tidy
@[reassoc] lemma biprod.braiding_map_braiding {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) :
(biprod.braiding X W).hom ≫ biprod.map f g ≫ (biprod.braiding Y Z).hom = biprod.map g f :=
by tidy
@[simp, reassoc] lemma biprod.symmetry' (P Q : C) :
biprod.lift biprod.snd biprod.fst ≫ biprod.lift biprod.snd biprod.fst = 𝟙 (P ⊞ Q) :=
by tidy
/-- The braiding isomorphism is symmetric. -/
@[reassoc] lemma biprod.symmetry (P Q : C) :
(biprod.braiding P Q).hom ≫ (biprod.braiding Q P).hom = 𝟙 _ :=
by simp
end
-- TODO:
-- If someone is interested, they could provide the constructions:
-- has_binary_biproducts ↔ has_finite_biproducts
end limits
namespace limits
section preadditive
variables {C : Type u} [category.{v} C] [preadditive C]
variables {J : Type} [fintype J]
open category_theory.preadditive
open_locale big_operators
/--
In a preadditive category, we can construct a biproduct for `f : J → C` from
any bicone `b` for `f` satisfying `total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X`.
(That is, such a bicone is a limit cone and a colimit cocone.)
-/
def is_bilimit_of_total {f : J → C} (b : bicone f) (total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X) :
b.is_bilimit :=
{ is_limit :=
{ lift := λ s, ∑ (j : J), s.π.app ⟨j⟩ ≫ b.ι j,
uniq' := λ s m h,
begin
erw [←category.comp_id m, ←total, comp_sum],
apply finset.sum_congr rfl,
intros j m,
erw [reassoc_of (h ⟨j⟩)],
end,
fac' := λ s j,
begin
cases j,
simp only [sum_comp, category.assoc, bicone.to_cone_π_app, b.ι_π, comp_dite],
-- See note [dsimp, simp].
dsimp, simp,
end },
is_colimit :=
{ desc := λ s, ∑ (j : J), b.π j ≫ s.ι.app ⟨j⟩,
uniq' := λ s m h,
begin
erw [←category.id_comp m, ←total, sum_comp],
apply finset.sum_congr rfl,
intros j m,
erw [category.assoc, h ⟨j⟩],
end,
fac' := λ s j,
begin
cases j,
simp only [comp_sum, ←category.assoc, bicone.to_cocone_ι_app, b.ι_π, dite_comp],
dsimp, simp,
end } }
lemma is_bilimit.total {f : J → C} {b : bicone f} (i : b.is_bilimit) :
∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X :=
i.is_limit.hom_ext (λ j, by { cases j, simp [sum_comp, b.ι_π, comp_dite] })
/--
In a preadditive category, we can construct a biproduct for `f : J → C` from
any bicone `b` for `f` satisfying `total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X`.
(That is, such a bicone is a limit cone and a colimit cocone.)
-/
lemma has_biproduct_of_total {f : J → C} (b : bicone f) (total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X) :
has_biproduct f :=
has_biproduct.mk
{ bicone := b,
is_bilimit := is_bilimit_of_total b total }
/-- In a preadditive category, any finite bicone which is a limit cone is in fact a bilimit
bicone. -/
def is_bilimit_of_is_limit {f : J → C} (t : bicone f) (ht : is_limit t.to_cone) : t.is_bilimit :=
is_bilimit_of_total _ $ ht.hom_ext $
λ j, by { cases j, simp [sum_comp, t.ι_π, dite_comp, comp_dite] }
/-- We can turn any limit cone over a pair into a bilimit bicone. -/
def bicone_is_bilimit_of_limit_cone_of_is_limit {f : J → C} {t : cone (discrete.functor f)}
(ht : is_limit t) : (bicone.of_limit_cone ht).is_bilimit :=
is_bilimit_of_is_limit _ $
is_limit.of_iso_limit ht $ cones.ext (iso.refl _) (by { rintro ⟨j⟩, tidy })
/-- In a preadditive category, if the product over `f : J → C` exists,
then the biproduct over `f` exists. -/
lemma has_biproduct.of_has_product (f : J → C) [has_product f] : has_biproduct f :=
has_biproduct.mk
{ bicone := _,
is_bilimit := bicone_is_bilimit_of_limit_cone_of_is_limit (limit.is_limit _) }
/-- In a preadditive category, any finite bicone which is a colimit cocone is in fact a bilimit
bicone. -/
def is_bilimit_of_is_colimit {f : J → C} (t : bicone f) (ht : is_colimit t.to_cocone) :
t.is_bilimit :=
is_bilimit_of_total _ $ ht.hom_ext $ λ j, begin
cases j,
simp_rw [bicone.to_cocone_ι_app, comp_sum, ← category.assoc, t.ι_π, dite_comp],
tidy
end
/-- We can turn any limit cone over a pair into a bilimit bicone. -/
def bicone_is_bilimit_of_colimit_cocone_of_is_colimit {f : J → C} {t : cocone (discrete.functor f)}
(ht : is_colimit t) : (bicone.of_colimit_cocone ht).is_bilimit :=
is_bilimit_of_is_colimit _ $
is_colimit.of_iso_colimit ht $ cocones.ext (iso.refl _) (by { rintro ⟨j⟩, tidy })
/-- In a preadditive category, if the coproduct over `f : J → C` exists,
then the biproduct over `f` exists. -/
lemma has_biproduct.of_has_coproduct (f : J → C) [has_coproduct f] : has_biproduct f :=
has_biproduct.mk
{ bicone := _,
is_bilimit := bicone_is_bilimit_of_colimit_cocone_of_is_colimit (colimit.is_colimit _) }
/-- A preadditive category with finite products has finite biproducts. -/
lemma has_finite_biproducts.of_has_finite_products [has_finite_products C] :
has_finite_biproducts C :=
⟨λ J _, { has_biproduct := λ F, by exactI has_biproduct.of_has_product _ }⟩
/-- A preadditive category with finite coproducts has finite biproducts. -/
lemma has_finite_biproducts.of_has_finite_coproducts [has_finite_coproducts C] :
has_finite_biproducts C :=
⟨λ J _, { has_biproduct := λ F, by exactI has_biproduct.of_has_coproduct _ }⟩
section
variables {f : J → C} [has_biproduct f]
/--
In any preadditive category, any biproduct satsifies
`∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)`
-/
@[simp] lemma biproduct.total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f) :=
is_bilimit.total (biproduct.is_bilimit _)
lemma biproduct.lift_eq {T : C} {g : Π j, T ⟶ f j} :
biproduct.lift g = ∑ j, g j ≫ biproduct.ι f j :=
begin
ext j,
simp [sum_comp, biproduct.ι_π, comp_dite],
end
lemma biproduct.desc_eq {T : C} {g : Π j, f j ⟶ T} :
biproduct.desc g = ∑ j, biproduct.π f j ≫ g j :=
begin
ext j,
simp [comp_sum, biproduct.ι_π_assoc, dite_comp],
end
@[simp, reassoc] lemma biproduct.lift_desc {T U : C} {g : Π j, T ⟶ f j} {h : Π j, f j ⟶ U} :
biproduct.lift g ≫ biproduct.desc h = ∑ j : J, g j ≫ h j :=
by simp [biproduct.lift_eq, biproduct.desc_eq, comp_sum, sum_comp, biproduct.ι_π_assoc,
comp_dite, dite_comp]
lemma biproduct.map_eq [has_finite_biproducts C] {f g : J → C} {h : Π j, f j ⟶ g j} :
biproduct.map h = ∑ j : J, biproduct.π f j ≫ h j ≫ biproduct.ι g j :=
begin
ext,
simp [biproduct.ι_π, biproduct.ι_π_assoc, comp_sum, sum_comp, comp_dite, dite_comp],
end
@[simp, reassoc]
lemma biproduct.matrix_desc
{K : Type} [fintype K] [has_finite_biproducts C]
{f : J → C} {g : K → C} (m : Π j k, f j ⟶ g k) {P} (x : Π k, g k ⟶ P) :
biproduct.matrix m ≫ biproduct.desc x = biproduct.desc (λ j, ∑ k, m j k ≫ x k) :=
by { ext, simp, }
@[simp, reassoc]
lemma biproduct.lift_matrix
{K : Type} [fintype K] [has_finite_biproducts C]
{f : J → C} {g : K → C} {P} (x : Π j, P ⟶ f j) (m : Π j k, f j ⟶ g k) :
biproduct.lift x ≫ biproduct.matrix m = biproduct.lift (λ k, ∑ j, x j ≫ m j k) :=
by { ext, simp, }
@[reassoc]
lemma biproduct.matrix_map
{K : Type} [fintype K] [has_finite_biproducts C]
{f : J → C} {g : K → C} {h : K → C} (m : Π j k, f j ⟶ g k) (n : Π k, g k ⟶ h k) :
biproduct.matrix m ≫ biproduct.map n = biproduct.matrix (λ j k, m j k ≫ n k) :=
by { ext, simp, }
@[reassoc]
lemma biproduct.map_matrix
{K : Type} [fintype K] [has_finite_biproducts C]
{f : J → C} {g : J → C} {h : K → C} (m : Π k, f k ⟶ g k) (n : Π j k, g j ⟶ h k) :
biproduct.map m ≫ biproduct.matrix n = biproduct.matrix (λ j k, m j ≫ n j k) :=
by { ext, simp, }
end
/-- Reindex a categorical biproduct via an equivalence of the index types. -/
@[simps]
def biproduct.reindex {β γ : Type} [fintype β] [decidable_eq β] [decidable_eq γ]
(ε : β ≃ γ) (f : γ → C) [has_biproduct f] [has_biproduct (f ∘ ε)] : (⨁ (f ∘ ε)) ≅ (⨁ f) :=
{ hom := biproduct.desc (λ b, biproduct.ι f (ε b)),
inv := biproduct.lift (λ b, biproduct.π f (ε b)),
hom_inv_id' := by { ext b b', by_cases h : b = b', { subst h, simp, }, { simp [h], }, },
inv_hom_id' := begin
ext g g',
by_cases h : g = g';
simp [preadditive.sum_comp, preadditive.comp_sum, biproduct.ι_π, biproduct.ι_π_assoc, comp_dite,
equiv.apply_eq_iff_eq_symm_apply, finset.sum_dite_eq' finset.univ (ε.symm g') _, h],
end, }
/--
In a preadditive category, we can construct a binary biproduct for `X Y : C` from
any binary bicone `b` satisfying `total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X`.
(That is, such a bicone is a limit cone and a colimit cocone.)
-/
def is_binary_bilimit_of_total {X Y : C} (b : binary_bicone X Y)
(total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X) : b.is_bilimit :=
{ is_limit :=
{ lift := λ s, binary_fan.fst s ≫ b.inl +
binary_fan.snd s ≫ b.inr,
uniq' := λ s m h, by erw [←category.comp_id m, ←total,
comp_add, reassoc_of (h ⟨walking_pair.left⟩), reassoc_of (h ⟨walking_pair.right⟩)],
fac' := λ s j, by rcases j with ⟨⟨⟩⟩; simp, },
is_colimit :=
{ desc := λ s, b.fst ≫ binary_cofan.inl s +
b.snd ≫ binary_cofan.inr s,
uniq' := λ s m h, by erw [←category.id_comp m, ←total,
add_comp, category.assoc, category.assoc, h ⟨walking_pair.left⟩, h ⟨walking_pair.right⟩],
fac' := λ s j, by rcases j with ⟨⟨⟩⟩; simp, } }
lemma is_bilimit.binary_total {X Y : C} {b : binary_bicone X Y} (i : b.is_bilimit) :
b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X :=
i.is_limit.hom_ext (λ j, by { rcases j with ⟨⟨⟩⟩; simp, })
/--
In a preadditive category, we can construct a binary biproduct for `X Y : C` from
any binary bicone `b` satisfying `total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X`.
(That is, such a bicone is a limit cone and a colimit cocone.)
-/
lemma has_binary_biproduct_of_total {X Y : C} (b : binary_bicone X Y)
(total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X) : has_binary_biproduct X Y :=
has_binary_biproduct.mk
{ bicone := b,
is_bilimit := is_binary_bilimit_of_total b total }
/-- We can turn any limit cone over a pair into a bicone. -/
@[simps]
def binary_bicone.of_limit_cone {X Y : C} {t : cone (pair X Y)} (ht : is_limit t) :
binary_bicone X Y :=
{ X := t.X,
fst := t.π.app ⟨walking_pair.left⟩,
snd := t.π.app ⟨walking_pair.right⟩,
inl := ht.lift (binary_fan.mk (𝟙 X) 0),
inr := ht.lift (binary_fan.mk 0 (𝟙 Y)) }
lemma inl_of_is_limit {X Y : C} {t : binary_bicone X Y} (ht : is_limit t.to_cone) :
t.inl = ht.lift (binary_fan.mk (𝟙 X) 0) :=
by apply ht.uniq (binary_fan.mk (𝟙 X) 0); rintro ⟨⟨⟩⟩; dsimp; simp
lemma inr_of_is_limit {X Y : C} {t : binary_bicone X Y} (ht : is_limit t.to_cone) :
t.inr = ht.lift (binary_fan.mk 0 (𝟙 Y)) :=
by apply ht.uniq (binary_fan.mk 0 (𝟙 Y)); rintro ⟨⟨⟩⟩; dsimp; simp
/-- In a preadditive category, any binary bicone which is a limit cone is in fact a bilimit
bicone. -/
def is_binary_bilimit_of_is_limit {X Y : C} (t : binary_bicone X Y) (ht : is_limit t.to_cone) :
t.is_bilimit :=
is_binary_bilimit_of_total _ (by refine binary_fan.is_limit.hom_ext ht _ _; simp)
/-- We can turn any limit cone over a pair into a bilimit bicone. -/
def binary_bicone_is_bilimit_of_limit_cone_of_is_limit {X Y : C} {t : cone (pair X Y)}
(ht : is_limit t) : (binary_bicone.of_limit_cone ht).is_bilimit :=
is_binary_bilimit_of_total _ $ binary_fan.is_limit.hom_ext ht (by simp) (by simp)
/-- In a preadditive category, if the product of `X` and `Y` exists, then the
binary biproduct of `X` and `Y` exists. -/
lemma has_binary_biproduct.of_has_binary_product (X Y : C) [has_binary_product X Y] :
has_binary_biproduct X Y :=
has_binary_biproduct.mk
{ bicone := _,
is_bilimit := binary_bicone_is_bilimit_of_limit_cone_of_is_limit (limit.is_limit _) }
/-- In a preadditive category, if all binary products exist, then all binary biproducts exist. -/
lemma has_binary_biproducts.of_has_binary_products [has_binary_products C] :
has_binary_biproducts C :=
{ has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_product X Y, }
/-- We can turn any colimit cocone over a pair into a bicone. -/
@[simps]
def binary_bicone.of_colimit_cocone {X Y : C} {t : cocone (pair X Y)} (ht : is_colimit t) :
binary_bicone X Y :=
{ X := t.X,
fst := ht.desc (binary_cofan.mk (𝟙 X) 0),
snd := ht.desc (binary_cofan.mk 0 (𝟙 Y)),
inl := t.ι.app ⟨walking_pair.left⟩,
inr := t.ι.app ⟨walking_pair.right⟩ }
lemma fst_of_is_colimit {X Y : C} {t : binary_bicone X Y} (ht : is_colimit t.to_cocone) :
t.fst = ht.desc (binary_cofan.mk (𝟙 X) 0) :=
begin
apply ht.uniq (binary_cofan.mk (𝟙 X) 0),
rintro ⟨⟨⟩⟩; dsimp; simp
end
lemma snd_of_is_colimit {X Y : C} {t : binary_bicone X Y} (ht : is_colimit t.to_cocone) :
t.snd = ht.desc (binary_cofan.mk 0 (𝟙 Y)) :=
begin
apply ht.uniq (binary_cofan.mk 0 (𝟙 Y)),
rintro ⟨⟨⟩⟩; dsimp; simp
end
/-- In a preadditive category, any binary bicone which is a colimit cocone is in fact a
bilimit bicone. -/
def is_binary_bilimit_of_is_colimit {X Y : C} (t : binary_bicone X Y)
(ht : is_colimit t.to_cocone) : t.is_bilimit :=
is_binary_bilimit_of_total _
begin
refine binary_cofan.is_colimit.hom_ext ht _ _; simp,
{ rw [category.comp_id t.inl] },
{ rw [category.comp_id t.inr] }
end
/-- We can turn any colimit cocone over a pair into a bilimit bicone. -/
def binary_bicone_is_bilimit_of_colimit_cocone_of_is_colimit {X Y : C} {t : cocone (pair X Y)}
(ht : is_colimit t) : (binary_bicone.of_colimit_cocone ht).is_bilimit :=
is_binary_bilimit_of_is_colimit (binary_bicone.of_colimit_cocone ht) $
is_colimit.of_iso_colimit ht $ cocones.ext (iso.refl _) $ λ j, by { rcases j with ⟨⟨⟩⟩, tidy }
/-- In a preadditive category, if the coproduct of `X` and `Y` exists, then the
binary biproduct of `X` and `Y` exists. -/
lemma has_binary_biproduct.of_has_binary_coproduct (X Y : C) [has_binary_coproduct X Y] :
has_binary_biproduct X Y :=
has_binary_biproduct.mk
{ bicone := _,
is_bilimit := binary_bicone_is_bilimit_of_colimit_cocone_of_is_colimit (colimit.is_colimit _) }
/-- In a preadditive category, if all binary coproducts exist, then all binary biproducts exist. -/
lemma has_binary_biproducts.of_has_binary_coproducts [has_binary_coproducts C] :
has_binary_biproducts C :=
{ has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_coproduct X Y, }
section
variables {X Y : C} [has_binary_biproduct X Y]
/--
In any preadditive category, any binary biproduct satsifies
`biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y)`.
-/
@[simp] lemma biprod.total : biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y) :=
begin
ext; simp [add_comp],
end
lemma biprod.lift_eq {T : C} {f : T ⟶ X} {g : T ⟶ Y} :
biprod.lift f g = f ≫ biprod.inl + g ≫ biprod.inr :=
begin
ext; simp [add_comp],
end
lemma biprod.desc_eq {T : C} {f : X ⟶ T} {g : Y ⟶ T} :
biprod.desc f g = biprod.fst ≫ f + biprod.snd ≫ g :=
begin
ext; simp [add_comp],
end
@[simp, reassoc] lemma biprod.lift_desc {T U : C} {f : T ⟶ X} {g : T ⟶ Y} {h : X ⟶ U} {i : Y ⟶ U} :
biprod.lift f g ≫ biprod.desc h i = f ≫ h + g ≫ i :=
by simp [biprod.lift_eq, biprod.desc_eq]
lemma biprod.map_eq [has_binary_biproducts C] {W X Y Z : C} {f : W ⟶ Y} {g : X ⟶ Z} :
biprod.map f g = biprod.fst ≫ f ≫ biprod.inl + biprod.snd ≫ g ≫ biprod.inr :=
by apply biprod.hom_ext; apply biprod.hom_ext'; simp
/--
Every split mono `f` with a cokernel induces a binary bicone with `f` as its `inl` and
the cokernel map as its `snd`.
We will show in `is_bilimit_binary_bicone_of_split_mono_of_cokernel` that this binary bicone is in
fact already a biproduct. -/
@[simps]
def binary_bicone_of_split_mono_of_cokernel {X Y : C} {f : X ⟶ Y} [split_mono f]
{c : cokernel_cofork f} (i : is_colimit c) : binary_bicone X c.X :=
{ X := Y,
fst := retraction f,
snd := c.π,
inl := f,
inr :=
let c' : cokernel_cofork (𝟙 Y - (𝟙 Y - retraction f ≫ f)) :=
cokernel_cofork.of_π (cofork.π c) (by simp) in
let i' : is_colimit c' := is_cokernel_epi_comp i (retraction f) (by simp) in
let i'' := is_colimit_cofork_of_cokernel_cofork i' in
(split_epi_of_idempotent_of_is_colimit_cofork C (by simp) i'').section_,
inl_fst' := by simp,
inl_snd' := by simp,
inr_fst' :=
begin
dsimp only,
rw [split_epi_of_idempotent_of_is_colimit_cofork_section_,
is_colimit_cofork_of_cokernel_cofork_desc, is_cokernel_epi_comp_desc],
dsimp only [cokernel_cofork_of_cofork_of_π],
letI := epi_of_is_colimit_cofork i,
apply zero_of_epi_comp c.π,
simp only [sub_comp, comp_sub, category.comp_id, category.assoc, split_mono.id, sub_self,
cofork.is_colimit.π_desc_assoc, cokernel_cofork.π_of_π, split_mono.id_assoc],
apply sub_eq_zero_of_eq,
apply category.id_comp
end,
inr_snd' := by apply split_epi.id }
/-- The bicone constructed in `binary_bicone_of_split_mono_of_cokernel` is a bilimit.
This is a version of the splitting lemma that holds in all preadditive categories. -/
def is_bilimit_binary_bicone_of_split_mono_of_cokernel {X Y : C} {f : X ⟶ Y} [split_mono f]
{c : cokernel_cofork f} (i : is_colimit c) :
(binary_bicone_of_split_mono_of_cokernel i).is_bilimit :=
is_binary_bilimit_of_total _
begin
simp only [binary_bicone_of_split_mono_of_cokernel_fst,
binary_bicone_of_split_mono_of_cokernel_inr, binary_bicone_of_split_mono_of_cokernel_snd,
split_epi_of_idempotent_of_is_colimit_cofork_section_],
dsimp only [binary_bicone_of_split_mono_of_cokernel_X],
rw [is_colimit_cofork_of_cokernel_cofork_desc, is_cokernel_epi_comp_desc],
simp only [binary_bicone_of_split_mono_of_cokernel_inl, cofork.is_colimit.π_desc,
cokernel_cofork_of_cofork_π, cofork.π_of_π, add_sub_cancel'_right]
end
/-- If `b` is a binary bicone such that `b.inl` is a kernel of `b.snd`, then `b` is a bilimit
bicone. -/
def binary_bicone.is_bilimit_of_kernel_inl {X Y : C} (b : binary_bicone X Y)
(hb : is_limit b.snd_kernel_fork) : b.is_bilimit :=
is_binary_bilimit_of_is_limit _ $ binary_fan.is_limit.mk _
(λ T f g, f ≫ b.inl + g ≫ b.inr) (λ T f g, by simp) (λ T f g, by simp) $ λ T f g m h₁ h₂,
begin
have h₁' : (m - (f ≫ b.inl + g ≫ b.inr)) ≫ b.fst = 0 := by simpa using sub_eq_zero.2 h₁,
have h₂' : (m - (f ≫ b.inl + g ≫ b.inr)) ≫ b.snd = 0 := by simpa using sub_eq_zero.2 h₂,
obtain ⟨q : T ⟶ X, hq : q ≫ b.inl = m - (f ≫ b.inl + g ≫ b.inr)⟩ :=
kernel_fork.is_limit.lift' hb _ h₂',
rw [←sub_eq_zero, ←hq, ←category.comp_id q, ←b.inl_fst, ←category.assoc, hq, h₁', zero_comp]
end
/-- If `b` is a binary bicone such that `b.inr` is a kernel of `b.fst`, then `b` is a bilimit
bicone. -/
def binary_bicone.is_bilimit_of_kernel_inr {X Y : C} (b : binary_bicone X Y)
(hb : is_limit b.fst_kernel_fork) : b.is_bilimit :=
is_binary_bilimit_of_is_limit _ $ binary_fan.is_limit.mk _
(λ T f g, f ≫ b.inl + g ≫ b.inr) (λ t f g, by simp) (λ t f g, by simp) $ λ T f g m h₁ h₂,
begin
have h₁' : (m - (f ≫ b.inl + g ≫ b.inr)) ≫ b.fst = 0 := by simpa using sub_eq_zero.2 h₁,
have h₂' : (m - (f ≫ b.inl + g ≫ b.inr)) ≫ b.snd = 0 := by simpa using sub_eq_zero.2 h₂,
obtain ⟨q : T ⟶ Y, hq : q ≫ b.inr = m - (f ≫ b.inl + g ≫ b.inr)⟩ :=
kernel_fork.is_limit.lift' hb _ h₁',
rw [←sub_eq_zero, ←hq, ←category.comp_id q, ←b.inr_snd, ←category.assoc, hq, h₂', zero_comp]
end
/-- If `b` is a binary bicone such that `b.fst` is a cokernel of `b.inr`, then `b` is a bilimit
bicone. -/
def binary_bicone.is_bilimit_of_cokernel_fst {X Y : C} (b : binary_bicone X Y)
(hb : is_colimit b.inr_cokernel_cofork) : b.is_bilimit :=
is_binary_bilimit_of_is_colimit _ $ binary_cofan.is_colimit.mk _
(λ T f g, b.fst ≫ f + b.snd ≫ g) (λ T f g, by simp) (λ T f g, by simp) $ λ T f g m h₁ h₂,
begin
have h₁' : b.inl ≫ (m - (b.fst ≫ f + b.snd ≫ g)) = 0 := by simpa using sub_eq_zero.2 h₁,
have h₂' : b.inr ≫ (m - (b.fst ≫ f + b.snd ≫ g)) = 0 := by simpa using sub_eq_zero.2 h₂,
obtain ⟨q : X ⟶ T, hq : b.fst ≫ q = m - (b.fst ≫ f + b.snd ≫ g)⟩ :=
cokernel_cofork.is_colimit.desc' hb _ h₂',
rw [←sub_eq_zero, ←hq, ←category.id_comp q, ←b.inl_fst, category.assoc, hq, h₁', comp_zero]
end
/-- If `b` is a binary bicone such that `b.snd` is a cokernel of `b.inl`, then `b` is a bilimit
bicone. -/
def binary_bicone.is_bilimit_of_cokernel_snd {X Y : C} (b : binary_bicone X Y)
(hb : is_colimit b.inl_cokernel_cofork) : b.is_bilimit :=
is_binary_bilimit_of_is_colimit _ $ binary_cofan.is_colimit.mk _
(λ T f g, b.fst ≫ f + b.snd ≫ g) (λ T f g, by simp) (λ T f g, by simp) $ λ T f g m h₁ h₂,
begin
have h₁' : b.inl ≫ (m - (b.fst ≫ f + b.snd ≫ g)) = 0 := by simpa using sub_eq_zero.2 h₁,
have h₂' : b.inr ≫ (m - (b.fst ≫ f + b.snd ≫ g)) = 0 := by simpa using sub_eq_zero.2 h₂,
obtain ⟨q : Y ⟶ T, hq : b.snd ≫ q = m - (b.fst ≫ f + b.snd ≫ g)⟩ :=
cokernel_cofork.is_colimit.desc' hb _ h₁',
rw [←sub_eq_zero, ←hq, ←category.id_comp q, ←b.inr_snd, category.assoc, hq, h₂', comp_zero]
end
/--
Every split epi `f` with a kernel induces a binary bicone with `f` as its `snd` and
the kernel map as its `inl`.
We will show in `binary_bicone_of_split_mono_of_cokernel` that this binary bicone is in fact
already a biproduct. -/
@[simps]
def binary_bicone_of_split_epi_of_kernel {X Y : C} {f : X ⟶ Y} [split_epi f]
{c : kernel_fork f} (i : is_limit c) : binary_bicone c.X Y :=
{ X := X,
fst :=
let c' : kernel_fork (𝟙 X - (𝟙 X - f ≫ section_ f)) :=
kernel_fork.of_ι (fork.ι c) (by simp) in
let i' : is_limit c' := is_kernel_comp_mono i (section_ f) (by simp) in
let i'' := is_limit_fork_of_kernel_fork i' in
(split_mono_of_idempotent_of_is_limit_fork C (by simp) i'').retraction,
snd := f,
inl := c.ι,
inr := section_ f,
inl_fst' := by apply split_mono.id,
inl_snd' := by simp,
inr_fst' :=
begin
dsimp only,
rw [split_mono_of_idempotent_of_is_limit_fork_retraction,
is_limit_fork_of_kernel_fork_lift, is_kernel_comp_mono_lift],
dsimp only [kernel_fork_of_fork_ι],
letI := mono_of_is_limit_fork i,
apply zero_of_comp_mono c.ι,
simp only [comp_sub, category.comp_id, category.assoc, sub_self, fork.is_limit.lift_ι,
fork.ι_of_ι, split_epi.id_assoc]
end,
inr_snd' := by simp }
/-- The bicone constructed in `binary_bicone_of_split_epi_of_kernel` is a bilimit.
This is a version of the splitting lemma that holds in all preadditive categories. -/
def is_bilimit_binary_bicone_of_split_epi_of_kernel {X Y : C} {f : X ⟶ Y} [split_epi f]
{c : kernel_fork f} (i : is_limit c) :
(binary_bicone_of_split_epi_of_kernel i).is_bilimit :=
binary_bicone.is_bilimit_of_kernel_inl _ $ i.of_iso_limit $ fork.ext (iso.refl _) (by simp)
end
section
variables {X Y : C} (f g : X ⟶ Y)
/-- The existence of binary biproducts implies that there is at most one preadditive structure. -/
lemma biprod.add_eq_lift_id_desc [has_binary_biproduct X X] :
f + g = biprod.lift (𝟙 X) (𝟙 X) ≫ biprod.desc f g :=
by simp
/-- The existence of binary biproducts implies that there is at most one preadditive structure. -/
lemma biprod.add_eq_lift_desc_id [has_binary_biproduct Y Y] :
f + g = biprod.lift f g ≫ biprod.desc (𝟙 Y) (𝟙 Y) :=
by simp
end
end preadditive
end limits
open category_theory.limits
section
local attribute [ext] preadditive
/-- The existence of binary biproducts implies that there is at most one preadditive structure. -/
instance subsingleton_preadditive_of_has_binary_biproducts {C : Type u} [category.{v} C]
[has_zero_morphisms C] [has_binary_biproducts C] : subsingleton (preadditive C) :=
subsingleton.intro $ λ a b,
begin
ext X Y f g,
have h₁ := @biprod.add_eq_lift_id_desc _ _ a _ _ f g
(by convert (infer_instance : has_binary_biproduct X X)),
have h₂ := @biprod.add_eq_lift_id_desc _ _ b _ _ f g
(by convert (infer_instance : has_binary_biproduct X X)),
refine h₁.trans (eq.trans _ h₂.symm),
congr' 2;
exact subsingleton.elim _ _
end
end
variables {C : Type u} [category.{v} C] [has_zero_morphisms C] [has_binary_biproducts C]
/-- An object is indecomposable if it cannot be written as the biproduct of two nonzero objects. -/
def indecomposable (X : C) : Prop := ¬ is_zero X ∧ ∀ Y Z, (X ≅ Y ⊞ Z) → is_zero Y ∨ is_zero Z
end category_theory
|
1caab42605c74eb038cc1cd32eef7ca696380656 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/init/subtype.lean | 6bd3b6e6b4b68bb4676a65a3207ab448091d65e9 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 996 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Jeremy Avigad
-/
prelude
import init.datatypes init.logic
open decidable
universe variables u
structure subtype {A : Type u} (P : A → Prop) :=
tag :: (elt_of : A) (has_property : P elt_of)
notation `{` binder ` \ `:0 r:(scoped:1 P, subtype P) `}` := r
namespace subtype
definition exists_of_subtype {A : Type u} {P : A → Prop} : { x \ P x } → ∃ x, P x
| ⟨a, h⟩ := ⟨a, h⟩
variables {A : Type u} {P : A → Prop}
theorem tag_irrelevant {a : A} (h1 h2 : P a) : tag a h1 = tag a h2 :=
rfl
protected theorem eq : ∀ {a1 a2 : {x \ P x}}, elt_of a1 = elt_of a2 → a1 = a2
| ⟨x, h1⟩ ⟨.x, h2⟩ rfl := rfl
end subtype
open subtype
variables {A : Type u} {P : A → Prop}
attribute [instance]
protected definition subtype.is_inhabited {a : A} (h : P a) : inhabited {x \ P x} :=
⟨⟨a, h⟩⟩
|
bd5f03e7f62d0b36d2ac7187df1c74ea456db96c | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/algebra/continued_fractions/computation/basic.lean | 30fe9159a3887c62fc4243778ca32b94741788b6 | [
"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 | 7,885 | lean | /-
Copyright (c) 2020 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import algebra.continued_fractions.basic
import algebra.ordered_field
import algebra.archimedean
/-!
# Computable Continued Fractions
## Summary
We formalise the standard computation of (regular) continued fractions for linear ordered floor
fields. The algorithm is rather simple. Here is an outline of the procedure adapted from Wikipedia:
Take a value `v`. We call `⌊v⌋` the *integer part* of `v` and `v − ⌊v⌋` the *fractional part* of `v`.
A continued fraction representation of `v` can then be given by `[⌊v⌋; b₀, b₁, b₂,...]`,
where `[b₀; b₁, b₂,...]` recursively is the continued fraction representation of `1 / (v − ⌊v⌋)`.
This process stops when the fractional part hits 0.
In other words: to calculate a continued fraction representation of a number `v`, write down the
integer part (i.e. the floor) of `v`. Subtract this integer part from `v`. If the difference is 0,
stop; otherwise find the reciprocal of the difference and repeat. The procedure will terminate if
and only if `v` is rational.
For an example, refer to `int_fract_pair.stream`.
## Main definitions
- `generalized_continued_fraction.int_fract_pair.stream`: computes the stream of integer and
fractional parts of a given value as described in the summary.
- `generalized_continued_fraction.of`: computes the generalised continued fraction of a value `v`.
In fact, it computes a regular continued fraction that terminates if and only if `v` is rational
(those proofs will be added in a future commit).
## Implementation Notes
There is an intermediate definition `generalized_continued_fraction.int_fract_pair.seq1` between
`generalized_continued_fraction.int_fract_pair.stream` and `generalized_continued_fraction.of`
to wire up things. User should not (need to) directly interact with it.
The computation of the integer and fractional pairs of a value can elegantly be
captured by a recursive computation of a stream of option pairs. This is done in
`int_fract_pair.stream`. However, the type then does not guarantee the first pair to always be
`some` value, as expected by a continued fraction.
To separate concerns, we first compute a single head term that always exists in
`generalized_continued_fraction.int_fract_pair.seq1` followed by the remaining stream of option
pairs. This sequence with a head term (`seq1`) is then transformed to a generalized continued
fraction in `generalized_continued_fraction.of` by extracting the wanted integer parts of the
head term and the stream.
## References
- https://en.wikipedia.org/wiki/Continued_fraction
## Tags
numerics, number theory, approximations, fractions
-/
namespace generalized_continued_fraction
open generalized_continued_fraction as gcf
-- Fix a carrier `K`.
variable (K : Type*)
/--
We collect an integer part `b = ⌊v⌋` and fractional part `fr = v - ⌊v⌋` of a value `v` in a pair
`⟨b, fr⟩`.
-/
structure int_fract_pair := (b : ℤ) (fr : K)
/-! Interlude: define some expected coercions and instances. -/
namespace int_fract_pair
/-- Make an `int_fract_pair` printable. -/
instance [has_repr K] : has_repr (int_fract_pair K) :=
⟨λ p, "(b : " ++ (repr p.b) ++ ", fract : " ++ (repr p.fr) ++ ")"⟩
instance inhabited [inhabited K] : inhabited (int_fract_pair K) := ⟨⟨0, (default _)⟩⟩
variable {K}
section coe
/-! Interlude: define some expected coercions. -/
/- Fix another type `β` and assume `K` can be converted to `β`. -/
variables {β : Type*} [has_coe K β]
/-- Coerce a pair by coercing the fractional component. -/
instance has_coe_to_int_fract_pair : has_coe (int_fract_pair K) (int_fract_pair β) :=
⟨λ ⟨b, fr⟩, ⟨b, (fr : β)⟩⟩
@[simp, norm_cast]
lemma coe_to_int_fract_pair {b : ℤ} {fr : K} :
(↑(int_fract_pair.mk b fr) : int_fract_pair β) = int_fract_pair.mk b (↑fr : β) :=
rfl
end coe
-- Note: this could be relaxed to something like `discrete_linear_ordered_division_ring` in the
-- future.
/- Fix a discrete linear ordered field with `floor` function. -/
variables [discrete_linear_ordered_field K] [floor_ring K]
/-- Creates the integer and fractional part of a value `v`, i.e. `⟨⌊v⌋, v - ⌊v⌋⟩`. -/
protected def of (v : K) : int_fract_pair K := ⟨⌊v⌋, fract v⟩
/--
Creates the stream of integer and fractional parts of a value `v` needed to obtain the continued
fraction representation of `v` in `generalized_continued_fraction.of`. More precisely, given a value
`v : K`, it recursively computes a stream of option `ℤ × K` pairs as follows:
- `stream v 0 = some ⟨⌊v⌋, v - ⌊v⌋⟩`
- `stream v (n + 1) = some ⟨⌊frₙ⁻¹⌋, frₙ⁻¹ - ⌊frₙ⁻¹⌋⟩`, if `stream v n = some ⟨_, frₙ⟩` and `frₙ ≠ 0`
- `stream v (n + 1) = none`, otherwise
For example, let `(v : ℚ) := 3.4`. The process goes as follows:
- `stream v 0 = some ⟨⌊v⌋, v - ⌊v⌋⟩ = some ⟨3, 0.4⟩`
- `stream v 1 = some ⟨⌊0.4⁻¹⌋, 0.4⁻¹ - ⌊0.4⁻¹⌋⟩ = some ⟨⌊2.5⌋, 2.5 - ⌊2.5⌋⟩ = some ⟨2, 0.5⟩`
- `stream v 2 = some ⟨⌊0.5⁻¹⌋, 0.5⁻¹ - ⌊0.5⁻¹⌋⟩ = some ⟨⌊2⌋, 2 - ⌊2⌋⟩ = some ⟨2, 0⟩`
- `stream v n = none`, for `n ≥ 3`
-/
protected def stream (v : K) : stream $ option (int_fract_pair K)
| 0 := some (int_fract_pair.of v)
| (n + 1) := do ap_n ← stream n,
if ap_n.fr = 0 then none else int_fract_pair.of ap_n.fr⁻¹
/--
Shows that `int_fract_pair.stream` has the sequence property, that is once we return `none` at
position `n`, we also return `none` at `n + 1`.
-/
lemma stream_is_seq (v : K) : (int_fract_pair.stream v).is_seq :=
by { assume _ hyp, simp [int_fract_pair.stream, hyp] }
/--
Uses `int_fract_pair.stream` to create a sequence with head (i.e. `seq1`) of integer and fractional
parts of a value `v`. The first value of `int_fract_pair.stream` is never `none`, so we can safely
extract it and put the tail of the stream in the sequence part.
This is just an intermediate representation and users should not (need to) directly interact with it.
The setup of rewriting/simplification lemmas that make the definitions easy to use is done in
`algebra.continued_fractions.computation.translations`.
-/
protected def seq1 (v : K) : seq1 $ int_fract_pair K :=
⟨ int_fract_pair.of v,--the head
seq.tail -- take the tail of `int_fract_pair.stream` since the first element is already in the head
-- create a sequence from `int_fract_pair.stream`
⟨ int_fract_pair.stream v, -- the underlying stream
@stream_is_seq _ _ _ v ⟩ ⟩ -- the proof that the stream is a sequence
end int_fract_pair
variable {K}
/--
Returns the `generalized_continued_fraction` of a value. In fact, the returned gcf is also
a `continued_fraction` that terminates if and only if `v` is rational (those proofs will be
added in a future commit).
The continued fraction representation of `v` is given by `[⌊v⌋; b₀, b₁, b₂,...]`, where
`[b₀; b₁, b₂,...]` recursively is the continued fraction representation of `1 / (v − ⌊v⌋)`. This
process stops when the fractional part `v- ⌊v⌋` hits 0 at some step.
The implementation uses `int_fract_pair.stream` to obtain the partial denominators of the continued
fraction. Refer to said function for more details about the computation process.
-/
protected def of [discrete_linear_ordered_field K] [floor_ring K] (v : K) : gcf K :=
let ⟨h, s⟩ := int_fract_pair.seq1 v in -- get the sequence of integer and fractional parts.
⟨ h.b, -- the head is just the first integer part
s.map (λ p, ⟨1, p.b⟩) ⟩ -- the sequence consists of the remaining integer parts as the partial
-- denominators; all partial numerators are simply 1
end generalized_continued_fraction
|
055a9a1f88ae37f4f9d69bdb2577c13a901f6ca0 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/simplifier18.lean | 7ba2caaafd58047037cf88ffa44d14bb4fa17a98 | [
"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,015 | lean | -- Basic fusion
import algebra.ring
open algebra
universe l
constants (T : Type.{l}) (s : comm_ring T)
constants (x1 x2 x3 x4 : T) (f g : T → T)
attribute s [instance]
set_option simplify.max_steps 50000
set_option simplify.fuse true
open simplifier.unit simplifier.ac simplifier.neg
#simplify eq env 0 x1 * x2
#simplify eq env 0 x1 * 2 * x2
#simplify eq env 0 x1 * 2 * x2 * 3
#simplify eq env 0 2 * x2 + x1 * 8 * x2 * 4
#simplify eq env 0 2 * x2 - x1 * 8 * x2 * 4
#simplify eq env 0 2 * x2 - 8 * x2 * 4 * x1
#simplify eq env 0 x2 * x1 + 3 * x1 + (2 * x2 - 8 * x2 * 4 * x1) + x1 * x2
#simplify eq env 0 (x1 * x3 + x1 * 2 + x2 * 3 * x3 + x1 * x2) - 2* x2 * x1 + 1 * x2 * x1 - 3 * x1 * x3
#simplify eq env 0 2 * 2 + x1
#simplify eq env 0 x2 * (2 * 2) + x1
#simplify eq env 0 2 * 2 * x2 + x1
#simplify eq env 0 2 * x2 * 2 + x1
#simplify eq env 0 200 * x2 * 200 + x1
#simplify eq env 0 x1 * 200 * x2 * 200 + x1
#simplify eq env 0 x1 * 200 * x2 * x3 * 200 + x1
#simplify eq env 0 x1 * 200 * x2 * x3 * x4 * 200 + x1
|
8686cf064e61e1304c8115b52fa8a5eea08124ec | b00eb947a9c4141624aa8919e94ce6dcd249ed70 | /tests/lean/run/def7.lean | 719bb856c3bb5f2abd52671614d4f2ecd1c348c8 | [
"Apache-2.0"
] | permissive | gebner/lean4-old | a4129a041af2d4d12afb3a8d4deedabde727719b | ee51cdfaf63ee313c914d83264f91f414a0e3b6e | refs/heads/master | 1,683,628,606,745 | 1,622,651,300,000 | 1,622,654,405,000 | 142,608,821 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,406 | lean | inductive InfTree.{u} (α : Type u)
| leaf : α → InfTree α
| node : (Nat → InfTree α) → InfTree α
open InfTree
def szn.{u} {α : Type u} (n : Nat) : InfTree α → InfTree α → Nat
| leaf a, t2 => 1
| node c, leaf b => 0
| node c, node d => szn n (c n) (d n)
universes u
theorem ex1 {α : Type u} (n : Nat) (c : Nat → InfTree α) (d : Nat → InfTree α) : szn n (node c) (node d) = szn n (c n) (d n) :=
rfl
inductive BTree (α : Type u)
| leaf : α → BTree α
| node : (Bool → Bool → BTree α) → BTree α
def BTree.sz {α : Type u} : BTree α → Nat
| leaf a => 1
| node c => sz (c true true) + sz (c true false) + sz (c false true) + sz (c false false) + 1
theorem ex2 {α : Type u} (c : Bool → Bool → BTree α) : (BTree.node c).sz = (c true true).sz + (c true false).sz + (c false true).sz + (c false false).sz + 1 :=
rfl
inductive L (α : Type u)
| nil : L α
| cons : (Unit → α) → (Unit → L α) → L α
def L.append {α} : L α → L α → L α
| nil, bs => bs
| cons a as, bs => cons a (fun _ => append (as ()) bs)
theorem L.appendNil {α} : (as : L α) → append as nil = as
| nil => rfl
| cons a as =>
show cons a (fun _ => append (as ()) nil) = cons a as from
have ih : append (as ()) nil = as () := appendNil $ as ()
have thunkAux : (fun _ => as ()) = as := funext fun x => by
cases x
exact rfl
by rw [ih, thunkAux]
|
f96deffb3baf5913fbc79225f534b3272c2c9e99 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/fintype/sort.lean | 41ce485adc587ef93fa06ca3f8dd4c02d26dd287 | [
"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 | 858 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.fintype.basic
import data.finset.sort
variables {α : Type*}
open finset
/-- Given a linearly ordered fintype `α` of cardinal `k`, the equiv `mono_equiv_of_fin α h`
is the increasing bijection between `fin k` and `α`. Here, `h` is a proof that
the cardinality of `s` is `k`. We use this instead of a map `fin s.card → α` to avoid
casting issues in further uses of this function. -/
noncomputable def mono_equiv_of_fin (α) [fintype α] [decidable_linear_order α] {k : ℕ}
(h : fintype.card α = k) : fin k ≃ α :=
equiv.of_bijective (mono_of_fin univ h) begin
apply set.bijective_iff_bij_on_univ.2,
rw ← @coe_univ α _,
exact mono_of_fin_bij_on (univ : finset α) h
end
|
2ff365afdcc8ac2b63ba28dcc1a2550612de3fc7 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /tests/compiler/str.lean | 43696454f91fd2d9735730a28d7f34fdc97c3c79 | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 949 | lean | #lang lean4
def showChars : Nat → String → String.Pos → IO Unit
| 0, _, _ => pure ()
| n+1, s, idx => do
unless s.atEnd idx do
IO.println (">> " ++ toString (s.get idx)) *>
showChars n s (s.next idx)
def main : IO UInt32 :=
let s₁ := "hello α_world_β";
let b : String.Pos := 0;
let e := s₁.bsize;
IO.println (s₁.extract b e) *>
IO.println (s₁.extract (b+2) e) *>
IO.println (s₁.extract (b+2) (e-1)) *>
IO.println (s₁.extract (b+2) (e-2)) *>
IO.println (s₁.extract (b+7) e) *>
IO.println (s₁.extract (b+8) e) *>
IO.println (toString e) *>
IO.println (repr " aaa ".trim) *>
showChars s₁.length s₁ 0 *>
IO.println ("abc".isPrefixOf "abcd") *>
IO.println ("abcd".isPrefixOf "abcd") *>
IO.println ("".isPrefixOf "abcd") *>
IO.println ("".isPrefixOf "") *>
IO.println ("ab".isPrefixOf "cb") *>
IO.println ("ab".isPrefixOf "a") *>
IO.println ("αb".isPrefixOf "αbc") *>
pure 0
|
8bed1a312a734ecb776ee95c02484020204fa7f6 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/tactic/omega/nat/sub_elim.lean | 1e5d457f30287800cc3c8cdff829a606cdd5d8e1 | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 5,100 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
Subtraction elimination for linear natural number arithmetic.
Works by repeatedly rewriting goals of the form `P[t-s]` into
`P[x] ∧ (t = s + x ∨ (t ≤ s ∧ x = 0))`, where `x` is fresh.
-/
import tactic.omega.nat.form
namespace omega
namespace nat
open_locale omega.nat
namespace preterm
def sub_terms : preterm → option (preterm × preterm)
| (& i) := none
| (i ** n) := none
| (t +* s) := t.sub_terms <|> s.sub_terms
| (t -* s) := t.sub_terms <|> s.sub_terms <|> some (t,s)
def sub_subst (t s : preterm) (k : nat) : preterm → preterm
| t@(& m) := t
| t@(m ** n) := t
| (x +* y) := x.sub_subst +* y.sub_subst
| (x -* y) :=
if x = t ∧ y = s then (1 ** k)
else x.sub_subst -* y.sub_subst
lemma val_sub_subst {k : nat} {x y : preterm} {v : nat → nat} :
∀ {t : preterm}, t.fresh_index ≤ k →
(sub_subst x y k t).val (update k (x.val v - y.val v) v) = t.val v
| (& m) h1 := rfl
| (m ** n) h1 :=
begin
have h2 : n ≠ k := ne_of_lt h1,
simp only [sub_subst, preterm.val],
rw update_eq_of_ne _ h2,
end
| (t +* s) h1 :=
begin
simp only [sub_subst, val_add], apply fun_mono_2;
apply val_sub_subst (le_trans _ h1),
apply le_max_left, apply le_max_right
end
| (t -* s) h1 :=
begin
simp only [sub_subst, val_sub],
by_cases h2 : t = x ∧ s = y,
{ rw if_pos h2, simp only [val_var, one_mul],
rw [update_eq, h2.left, h2.right] },
{ rw if_neg h2,
simp only [val_sub, sub_subst],
apply fun_mono_2;
apply val_sub_subst (le_trans _ h1),
apply le_max_left, apply le_max_right, }
end
end preterm
namespace form
def sub_terms : form → option (preterm × preterm)
| (t =* s) := t.sub_terms <|> s.sub_terms
| (t ≤* s) := t.sub_terms <|> s.sub_terms
| (¬* p) := p.sub_terms
| (p ∨* q) := p.sub_terms <|> q.sub_terms
| (p ∧* q) := p.sub_terms <|> q.sub_terms
@[simp] def sub_subst (x y : preterm) (k : nat) : form → form
| (t =* s) := preterm.sub_subst x y k t =* preterm.sub_subst x y k s
| (t ≤* s) := preterm.sub_subst x y k t ≤* preterm.sub_subst x y k s
| (¬* p) := ¬* p.sub_subst
| (p ∨* q) := p.sub_subst ∨* q.sub_subst
| (p ∧* q) := p.sub_subst ∧* q.sub_subst
end form
def is_diff (t s : preterm) (k : nat) : form :=
((t =* (s +* (1 ** k))) ∨* (t ≤* s ∧* ((1 ** k) =* &0)))
lemma holds_is_diff {t s : preterm} {k : nat} {v : nat → nat} :
v k = t.val v - s.val v → (is_diff t s k).holds v :=
begin
intro h1,
simp only [form.holds, is_diff, if_pos (eq.refl 1),
preterm.val_add, preterm.val_var, preterm.val_const],
by_cases h2 : t.val v ≤ s.val v,
{ right, refine ⟨h2,_⟩,
rw [h1, one_mul, nat.sub_eq_zero_iff_le], exact h2 },
{ left, rw [h1, one_mul, add_comm, nat.sub_add_cancel _],
rw not_le at h2, apply le_of_lt h2 }
end
def sub_elim_core (t s : preterm) (k : nat) (p : form) : form :=
(form.sub_subst t s k p) ∧* (is_diff t s k)
def sub_fresh_index (t s : preterm) (p : form) : nat :=
max p.fresh_index (max t.fresh_index s.fresh_index)
def sub_elim (t s : preterm) (p : form) : form :=
sub_elim_core t s (sub_fresh_index t s p) p
lemma sub_subst_equiv {k : nat} {x y : preterm} {v : nat → nat} :
∀ p : form, p.fresh_index ≤ k → ((form.sub_subst x y k p).holds
(update k (x.val v - y.val v) v) ↔ (p.holds v))
| (t =* s) h1 :=
begin
simp only [form.holds, form.sub_subst],
apply pred_mono_2;
apply preterm.val_sub_subst (le_trans _ h1),
apply le_max_left, apply le_max_right
end
| (t ≤* s) h1 :=
begin
simp only [form.holds, form.sub_subst],
apply pred_mono_2;
apply preterm.val_sub_subst (le_trans _ h1),
apply le_max_left, apply le_max_right
end
| (¬* p) h1 :=
by { apply not_iff_not_of_iff, apply sub_subst_equiv p h1 }
| (p ∨* q) h1 :=
begin
simp only [form.holds, form.sub_subst],
apply pred_mono_2; apply propext;
apply sub_subst_equiv _ (le_trans _ h1),
apply le_max_left, apply le_max_right
end
| (p ∧* q) h1 :=
begin
simp only [form.holds, form.sub_subst],
apply pred_mono_2; apply propext;
apply sub_subst_equiv _ (le_trans _ h1),
apply le_max_left, apply le_max_right
end
lemma sat_sub_elim {t s : preterm} {p : form} :
p.sat → (sub_elim t s p).sat :=
begin
intro h1, simp only [sub_elim, sub_elim_core],
cases h1 with v h1,
refine ⟨update (sub_fresh_index t s p) (t.val v - s.val v) v, _⟩,
constructor,
{ apply (sub_subst_equiv p _).elim_right h1,
apply le_max_left },
{ apply holds_is_diff, rw update_eq,
apply fun_mono_2;
apply preterm.val_constant; intros x h2;
rw update_eq_of_ne _ (ne.symm (ne_of_gt _));
apply lt_of_lt_of_le h2;
apply le_trans _ (le_max_right _ _),
apply le_max_left, apply le_max_right }
end
lemma unsat_of_unsat_sub_elim (t s : preterm) (p : form) :
(sub_elim t s p).unsat → p.unsat :=
(@not_imp_not _ _ (classical.dec _)).elim_right sat_sub_elim
end nat
end omega
|
906a2898db33805bd2d4090d9e7a8c27ccb63b0f | 36938939954e91f23dec66a02728db08a7acfcf9 | /lean4/deps/x86_semantics/src/X86Semantics/Instructions.lean | 30c09773d53bba86b3dcbaed7c92647318209925 | [] | no_license | pnwamk/reopt-vcg | f8b56dd0279392a5e1c6aee721be8138e6b558d3 | c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d | refs/heads/master | 1,631,145,017,772 | 1,593,549,019,000 | 1,593,549,143,000 | 254,191,418 | 0 | 0 | null | 1,586,377,077,000 | 1,586,377,077,000 | null | UTF-8 | Lean | false | false | 35,812 | lean | import X86Semantics.Common
-- import system.io
namespace x86
------------------------------------------------------------------------
-- Notation
open mc_semantics
open mc_semantics.type
open reg
open semantics
set_option class.instance_max_depth 1000
notation `pattern` body `pat_end` := mk_pattern body
-- Introduces notation x[h..l] to slice the h..l bits out of x.
-- local
notation x `[[`:1025 h `..` l `]]` := slice x h l
-- local
infix ≠ := neq
-- local
infix = := eq
-- local
notation `⇑`:max x:max := coe1 x
-- local
abbreviation ℕ := Nat
infix `.=`:20 := set
--notation d `.=` a `|` s :20 => set_aligned d s a
------------------------------------------------------------------------
-- bitvector functions
def xor {w:ℕ} (x : bv w) (y : bv w) : bv w := prim.bv_xor w x y
def complement {w:ℕ} (b : bv w) : bv w := prim.bv_complement w b
def and {w:ℕ} (x : bv w) (y : bv w) : bv w := prim.bv_and w x y
def or {w:ℕ} (x : bv w) (y : bv w) : bv w := prim.bv_or w x y
def cat {w:ℕ} (x : bv w) (y : bv w) : bv (2*w) := prim.cat w x y
def least_nibble {w:ℕ} (x : bv w) : bv 4 := trunc x 4
def ule {w:ℕ} (x y : bv w) : bit := prim.ule w x y
def ult {w:ℕ} (x y : bv w) : bit := prim.ult w x y
def sub {w:ℕ} (x y : bv w) : bv w := prim.sub w x y
def msb {w:ℕ} (v : bv w) : bit := prim.msb w v
def least_byte {w:ℕ} (v : bv w) : bv 8 := trunc v 8
def even_parity {w:ℕ} (v : bv w) : bit := prim.even_parity w v
infixl `.|.`:65 := or
infixl `.&.`:70 := and
------------------------------------------------------------------------
-- utility functions
def nat_to_bv {w:ℕ} (n:ℕ) : bv w := prim.bv_nat w n
def undef {tp:type} : expression tp := expression.undef tp
def set_result_flags {w:ℕ} (res : bv w) : semantics Unit := do
sf .= msb res;
zf .= res = 0;
pf .= even_parity (least_byte res)
def set_bitwise_flags {w:ℕ} (res : bv w) : semantics Unit := do
of .= bit_zero;
cf .= bit_zero;
af .= undef;
set_result_flags res
def ssbb_overflows {w:ℕ} (dest : bv w) (src : bv w) (borrow : bit) : bit := prim.ssbb_overflows w dest src borrow
def ssub_overflows {w:ℕ} (dest : bv w) (src : bv w) : bit := ssbb_overflows dest src bit_zero
def usbb_overflows {w:ℕ} (dest : bv w) (src : bv w) (borrow : bit) : bit := prim.usbb_overflows w dest src borrow
def usub_overflows {w:ℕ} (dest : bv w) (src : bv w) : bit := usbb_overflows dest src bit_zero
def usub4_overflows {w:ℕ} (dest : bv w) (src : bv w) : bit := usub_overflows (least_nibble dest) (least_nibble src)
def uadc_overflows {w:ℕ} (dest : bv w) (src : bv w) (carry : bit) : bit := prim.uadc_overflows w dest src carry
def uadc4_overflows {w:ℕ} (dest : bv w) (src : bv w) (carry : bit) : bit := uadc_overflows (least_nibble dest) (least_nibble src) carry
def uadd_overflows {w:ℕ} (dest : bv w) (src : bv w) : bit := uadc_overflows dest src bit_zero
def uadd4_overflows {w:ℕ} (dest : bv w) (src : bv w) : bit := uadd_overflows (least_nibble dest) (least_nibble src)
def sadc_overflows {w:ℕ} (dest : bv w) (src : bv w) (carry : bit) : bit := prim.sadc_overflows w dest src carry
def sadd_overflows {w:ℕ} (dest : bv w) (src : bv w) : bit := sadc_overflows dest src bit_zero
def do_xchg {w:ℕ} (addr1 : bv w) (addr2 : bv w) : semantics Unit :=
record_event (event.xchg addr1 addr2)
def mux {tp:type} (c:bit) (t f : tp) : tp := prim.mux tp c t f
------------------------------------------------------------------------
-- imul and mul definitions
def set_overflow (be:bit) : semantics Unit := do
b ← eval be;
cf .= b;
of .= b;
sf .= undef;
zf .= undef;
af .= undef;
pf .= undef
def imul : instruction :=
definst "imul" $ do
pattern fun (src : bv 8) => do
tmp ← eval $ sext (⇑al) 16 * sext src _;
ax .= tmp;
set_overflow $ sext tmp[[7..0]] _ ≠ tmp
pat_end;
pattern fun (src : bv 16) => do
tmp ← eval $ sext (⇑ax) 32 * sext src _;
dx .= tmp[[31..16]];
ax .= tmp[[15.. 0]];
set_overflow $ sext tmp[[15..0]] _ ≠ tmp
pat_end;
pattern fun (src : bv 32) => do
tmp ← eval $ sext ⇑eax 64 * sext src _;
edx .= tmp[[63..32]];
eax .= tmp[[31.. 0]];
set_overflow $ sext tmp[[31..0]] _ ≠ tmp
pat_end;
pattern fun (w : one_of [8,16,32,64]) (dest : lhs (bv w)) (src : bv w) => do
tmp ← eval $ sext ⇑dest (2*w) * sext src (2*w);
tmp_low ← eval $ trunc tmp w;
dest .= tmp_low;
set_overflow $ sext tmp_low (2*w) ≠ tmp
pat_end;
pattern fun (w : one_of [16,32,64]) (dest : lhs (bv w)) (src1 src2 : bv w) => do
tmp ← eval $ sext ⇑src1 (2*w) * sext src2 (2*w);
tmp_low ← eval $ trunc tmp w;
dest .= tmp_low;
set_overflow $ sext tmp_low (2*w) ≠ tmp
pat_end
def mul : instruction := do
definst "mul" $ do
pattern fun (src : bv 8) => do
tmp ← eval $ uext ⇑al 16 * uext src 16;
ax .= tmp;
set_overflow $ tmp[[16..8]] ≠ 0
pat_end;
pattern fun (src : bv 16) => do
tmp ← eval $ uext (⇑ax) 32 * uext src _;
dx .= tmp[[31..16]];
ax .= tmp[[15.. 0]];
set_overflow $ tmp[[31..16]] ≠ 0
pat_end;
pattern fun (src : bv 32) => do
tmp ← eval $ uext ⇑eax 64 * uext src _;
edx .= tmp[[63..32]];
eax .= tmp[[31.. 0]];
set_overflow $ tmp[[63..32]] ≠ 0
pat_end;
pattern fun (src : bv 64) => do
tmp ← eval $ uext ⇑rax 128 * uext src _;
rdx .= tmp[[127..64]];
rax .= tmp[[63 .. 0]];
set_overflow $ tmp[[127..64]] ≠ 0
pat_end
------------------------------------------------------------------------
-- mov definition
def mov : instruction := do
definst "mov" $ do
pattern fun (w : one_of [8,16,32,64]) (dest : lhs (bv w)) (src : bv w) => do
dest .= src
pat_end
------------------------------------------------------------------------
-- mov definition
-- Move Data from String to String
-- def movs : instruction := do
-- definst "movs" $ do sorry
------------------------------------------------------------------------
-- movsx definition
-- Move with Sign-Extension
def movsx : instruction := do
definst "movsx" $ do
pattern fun (w : one_of [16,32,64]) (u : one_of [8, 16, 32]) (dest : lhs (bv w)) (src : bv u) => do
dest .= sext src w
pat_end
------------------------------------------------------------------------
-- movsxd definition
-- Move with Sign-Extension
/-
def movsxd : instruction := do
definst "movsxd" $ do
pattern fun (w : one_of [16 =>32,64]) (u : one_of [16, 32]) (dest : lhs (bv w)) (src : bv u), do
dest .= sext src w
pat_end
-/
------------------------------------------------------------------------
-- movzx definition
-- Move with Zero-Extend
def movzx : instruction := do
definst "movzx" $ do
pattern fun (w : one_of [16,32,64]) (u : one_of [8, 16]) (dest : lhs (bv w)) (src : bv u) => do
dest .= uext src w
pat_end
------------------------------------------------------------------------
-- movdqa definition
-- Move Aligned Packed Integer Values
def movdqa : instruction := do
definst "movdqa" $ do
pattern fun (n : one_of [4, 8, 16]) (dest : lhs (vec n (bv 32))) (src : vec n (bv 32)) => do
set_aligned dest src 16
pat_end
------------------------------------------------------------------------
-- movaps definition
-- Move Aligned Packed Single-Precision Floating-Point Values
def movaps : instruction := do
definst "movaps" $ do
pattern fun (n : one_of [4, 8, 16]) (dest : lhs (vec n (bv 32))) (src : vec n (bv 32)) => do
set_aligned dest src 16
pat_end
------------------------------------------------------------------------
-- movups definition
-- Move Aligned Packed Single-Precision Floating-Point Values
def movups : instruction := do
definst "movups" $ do
pattern fun (n : one_of [4, 8, 16]) (dest : lhs (vec n (bv 32))) (src : vec n (bv 32)) => do
set dest src
pat_end
------------------------------------------------------------------------
-- xchg definition
-- Exchange Register/Memory with Register
def xchg : instruction := do
definst "xchg" $ do
pattern fun (w : one_of [8,16,32,64]) (dest : lhs (bv w)) (src : lhs (bv w)) => do
do_xchg ⇑dest ⇑src
pat_end
------------------------------------------------------------------------
-- cmp definition
-- Compare Two Operands
def do_cmp {u v : Nat} (x : bv u) (src2 : bv v) := do
y ← eval (sext src2 u);
of .= ssub_overflows x y;
af .= usub4_overflows x y;
cf .= usub_overflows x y;
set_result_flags (x - y)
def cmp : instruction := do
definst "cmp" $ do
pattern fun (u v : one_of [8,16,32,64]) (x : bv u) (src2 : bv v) => do_cmp x src2
pat_end;
pattern fun (x : imm (bv 8)) => do_cmp ⇑al (expression.imm x) pat_end;
pattern fun (x : imm (bv 16)) => do_cmp ⇑ax (expression.imm x) pat_end;
pattern fun (x : imm (bv 32)) => do_cmp ⇑eax (expression.imm x) pat_end;
pattern fun (x : imm (bv 64)) => do_cmp ⇑rax (expression.imm x) pat_end
-- pattern (u : one_of [8,16,32,64]) (x : imm (bv u)) := do
------------------------------------------------------------------------
-- cmpxchg definition
-- Compare and Exchange
/-
This instruction should be fairly straigth forward in the register-only
case, but requires more care for the memory case. We will probably also
need a notion of muxing on a bit.
def cmpxchg : instruction := do
definst "cmpxchg" $ do
pattern fun (dest : lhs (bv 8)) (src : bv 8) => do
temp ← eval $ ⇑dest,
do_cmp ⇑al temp,
zf .= temp = dest
pat_end
-/
------------------------------------------------------------------------
-- dec definition
-- Decrement by 1
def dec : instruction := do
definst "dec" $ do
pattern fun (w : one_of [8, 16,32,64]) (value : lhs (bv w)) => do
temp ← eval $ ⇑value - 1;
of .= ssub_overflows temp 1;
af .= usub4_overflows temp 1;
set_result_flags temp;
value .= temp
pat_end
------------------------------------------------------------------------
-- inc definition
-- Increment by 1
def inc : instruction := do
definst "inc" $ do
pattern fun (w : one_of [8, 16,32,64]) (value : lhs (bv w)) => do
temp ← eval $ ⇑value + 1;
of .= sadd_overflows temp 1;
af .= uadd4_overflows temp 1;
set_result_flags temp;
value .= temp
pat_end
------------------------------------------------------------------------
-- neg definition
-- Two's Complement Negation
def neg : instruction := do
definst "neg" $ do
pattern fun (w : one_of [8, 16,32,64]) (dest : lhs (bv w)) => do
cf .= ⇑dest = 0;
of .= ssub_overflows 0 ⇑dest;
af .= usub4_overflows 0 ⇑dest;
r ← eval $ -⇑dest;
set_result_flags r;
dest .= r
pat_end
------------------------------------------------------------------------
-- nop definition
-- No Operation
def nop : instruction := do
definst "nop" $ do
pattern do
(pure () : semantics Unit)
pat_end;
pattern fun (w : one_of [16, 32]) => do
(pure () : semantics Unit)
pat_end
def noopl : instruction := do
definst "noopl" $ do
pattern fun (_ : lhs (bv 32)) => do
(pure () : semantics Unit)
pat_end
------------------------------------------------------------------------
-- pause definition
-- Spin Loop Hint
def pause : instruction := do
definst "pause" $ do
pattern do
(pure () : semantics Unit)
pat_end
------------------------------------------------------------------------
-- div definition
-- Unsigned Divide
def pair_fst {x y : type} (e:pair x y) : x := prim.pair_fst x y e
def pair_snd {x y : type} (e:pair x y) : y := prim.pair_snd x y e
def set_undef (l:List (lhs bit)) : semantics Unit := do
_ <- l.mapM (fun r => r .= undef); pure ()
def div : instruction := do
definst "div" $ do
-- TODO: would it be better to have a single div primitive?
pattern fun (src : bv 8) => do
r ← eval $ prim.quotRem 8 ⇑ax src;
al .= pair_fst r;
ah .= pair_snd r;
set_undef [cf, of, sf, zf, af, pf]
pat_end;
pattern fun (src : bv 16) => do
r ← eval $ prim.quotRem 16 (cat ⇑dx ⇑ax) src;
ax .= pair_fst r;
dx .= pair_snd r;
set_undef [cf, of, sf, zf, af, pf]
pat_end;
pattern fun (src : bv 32) => do
r ← eval $ prim.quotRem 32 (cat ⇑edx ⇑eax) src;
eax .= pair_fst r;
edx .= pair_snd r;
set_undef [cf, of, sf, zf, af, pf]
pat_end;
pattern fun (src : bv 64) => do
r ← eval $ prim.quotRem 64 (cat ⇑rdx ⇑rax) src;
rax .= pair_fst r;
rdx .= pair_snd r;
set_undef [cf, of, sf, zf, af, pf]
pat_end
------------------------------------------------------------------------
-- idiv definition
-- Signed Divide
def idiv : instruction := do
definst "idiv" $ do
-- TODO: would it be better to have a single div primitive?
pattern fun (src : bv 8) => do
r ← eval $ prim.squotRem 8 ⇑ax src;
al .= pair_fst r;
ah .= pair_snd r;
set_undef [cf, of, sf, zf, af, pf]
pat_end;
pattern fun (src : bv 16) => do
r ← eval $ prim.squotRem 16 (cat ⇑dx ⇑ax) src;
ax .= pair_fst r;
dx .= pair_snd r;
set_undef [cf, of, sf, zf, af, pf]
pat_end;
pattern fun (src : bv 32) => do
r ← eval $ prim.squotRem 32 (cat ⇑edx ⇑eax) src;
eax .= pair_fst r;
edx .= pair_snd r;
set_undef [cf, of, sf, zf, af, pf]
pat_end;
pattern fun (src : bv 64) => do
r ← eval $ prim.quotRem 64 (cat ⇑rdx ⇑rax) src;
rax .= pair_fst r;
rdx .= pair_snd r;
set_undef [cf, of, sf, zf, af, pf]
pat_end
------------------------------------------------------------------------
-- and definition
-- Logical AND
def and_def : instruction := do
definst "and" $ do
pattern fun (w : one_of [8, 16, 32, 64]) (dest : lhs (bv w)) (src : bv w) => do
tmp ← eval $ ⇑dest .&. src;
set_bitwise_flags tmp;
dest .= tmp
pat_end
------------------------------------------------------------------------
-- not definition
-- One's Complement Negation
def not : instruction := do
definst "not" $ do
pattern fun (w : one_of [8, 16, 32, 64]) (dest : lhs (bv w)) => do
dest .= complement ⇑dest
pat_end
------------------------------------------------------------------------
-- or definition
-- Logical Inclusive OR
def or_def : instruction := do
definst "or" $ do
pattern fun (u v : one_of [8, 16, 32, 64]) (dest : lhs (bv u)) (src : bv v) => do
dest .= ⇑dest .|. sext src u;
af .= undef;
of .= bit_zero;
cf .= bit_zero;
set_result_flags ⇑dest
pat_end
------------------------------------------------------------------------
-- xor definition
-- Logical Exclusive OR
def xor_def : instruction := do
definst "xor" $ do
pattern fun (u v : one_of [8, 16, 32, 64]) (dest : lhs (bv u)) (src : bv v) => do
dest .= xor ⇑dest (sext src u);
af .= undef;
of .= bit_zero;
cf .= bit_zero;
set_result_flags ⇑dest
pat_end
------------------------------------------------------------------------
-- test definition
-- Logical compare
def test : instruction :=
definst "test" $ do
pattern fun (w : one_of [8, 16, 32, 64]) (x y : bv w) => do
set_bitwise_flags (x .&. y)
pat_end
---------------------------------- --------------------------------------
-- bt definition
-- Bit Test
def bt : instruction := do
definst "bt" $ do
pattern fun (wr : one_of [16, 32, 64]) (wi : one_of [8,16, 32, 64]) (base : reg (bv wr)) (idx : bv wi) => do
cf .= expression.bit_test (expression.of_reg base) idx;
of .= undef;
sf .= undef;
af .= undef;
pf .= undef
pat_end;
pattern fun (w : one_of [16, 32, 64]) (base : addr (bv w)) (idx : reg (bv w)) => do
let i := sext (expression.of_reg idx : bv w) 64;
addr ← eval $ expression.of_addr base + expression.mulc (w/8) (expression.quotc w i);
cf .= expression.bit_test (expression.read (bv w) addr) (expression.of_reg idx);
of .= undef;
sf .= undef;
af .= undef;
pf .= undef
pat_end;
pattern fun (w : one_of [16, 32, 64]) (base : addr (bv w)) (idx : imm (bv 8)) => do
cf .= expression.bit_test (expression.read_addr base) (expression.imm idx);
of .= undef;
sf .= undef;
af .= undef;
pf .= undef
pat_end
------------------------------------------------------------------------
-- btX definition
-- Type for functions for setting bits.
def bitf := ∀(w:one_of [16,32,64]) (j:ℕ), prim (fn (bv w) (fn (bv j) (bv w)))
-- Common function for btc,btr and bts.
def btX (nm:String) (f: bitf) : instruction := do
definst nm $ do
pattern fun (wr : one_of [16, 32, 64]) (wi : one_of [8,16, 32, 64]) (base : reg (bv wr)) (idx : bv wi) => do
cf .= expression.bit_test (expression.of_reg base) idx;
of .= undef;
sf .= undef;
af .= undef;
pf .= undef;
lhs.of_reg base .= f wr wi (expression.of_reg base) idx
pat_end;
pattern fun (w : one_of [16, 32, 64]) (base : addr (bv w)) (idx : reg (bv w)) => do
let i := sext (expression.of_reg idx : bv w) 64;
addr ← eval $ expression.of_addr base + expression.mulc (w/8) (expression.quotc w i);
cf .= expression.bit_test (expression.read (bv w) addr) (expression.of_reg idx);
of .= undef;
sf .= undef;
af .= undef;
pf .= undef;
lhs.write_addr addr (bv w) .= f w w (expression.read (bv w) addr) (expression.of_reg idx)
pat_end;
pattern fun (w : one_of [16, 32, 64]) (base : addr (bv w)) (idx : imm (bv 8)) => do
val ← eval (expression.read_addr base);
cf .= expression.bit_test val (expression.imm idx);
of .= undef;
sf .= undef;
af .= undef;
pf .= undef;
lhs.of_addr base .= f w 8 val (expression.imm idx)
pat_end
--- Bit test and complement
def btc : instruction := btX "btc" prim.btc
--- Bit test and reset
def btr : instruction := btX "btr" prim.btr
--- Bit test and set
def bts : instruction := btX "bts" prim.bts
------------------------------------------------------------------------
-- bsf definition
-- Bit Scan Forward
def bsf_def : instruction := do
definst "bsf" $ do
pattern fun (w : one_of [16, 32, 64]) (r : lhs (bv w)) (y : bv w) => do
cf .= undef;
of .= undef;
sf .= undef;
af .= undef;
pf .= undef;
zf .= y = 0;
r .= bsf y
pat_end
------------------------------------------------------------------------
-- bsr definition
-- Bit Scan Reverse
def bsr_def : instruction := do
definst "bsr" $ do
pattern fun (w : one_of [16, 32, 64]) (r : lhs (bv w)) (y : bv w) => do
cf .= undef;
of .= undef;
sf .= undef;
af .= undef;
pf .= undef;
zf .= y = 0;
r .= bsr y
pat_end
------------------------------------------------------------------------
-- bswap definition
-- Byte Swap
def bswap : instruction := do
definst "bswap" $ do
pattern fun (w : one_of [32, 64]) (dest : lhs (bv w)) => do
dest .= expression.bswap ⇑dest
pat_end
------------------------------------------------------------------------
-- add definition
def add : instruction := do
definst "add" $ do
pattern fun (w : one_of [8, 16, 32, 64]) (dest : lhs (bv w)) (src : bv w) => do
tmp ← eval $ ⇑dest + src;
set_result_flags tmp;
cf .= uadd_overflows tmp src;
of .= sadd_overflows tmp src;
af .= uadd4_overflows tmp src;
dest .= tmp
pat_end;
-- FIXME: this gets around a limitation where the rax is implicit
pattern fun (src : bv 64) => do
tmp <- eval $ ⇑rax + src;
set_result_flags tmp;
cf .= uadd_overflows tmp src;
of .= sadd_overflows tmp src;
af .= uadd4_overflows tmp src;
rax .= tmp
pat_end
------------------------------------------------------------------------
-- adc definition
-- Add with Carry
def adc : instruction := do
definst "adc" $ do
pattern fun (w : one_of [8, 16, 32, 64]) (dest : lhs (bv w)) (src : bv w) => do
tmp ← eval $ expression.adc ⇑dest src cf;
set_result_flags tmp;
cf .= uadc_overflows tmp src cf;
of .= sadc_overflows tmp src cf;
af .= uadc4_overflows tmp src cf;
dest .= tmp
pat_end
------------------------------------------------------------------------
-- xadd definition
-- Exchange and Add
def xadd : instruction := do
definst "xadd" $ do
pattern fun (w : one_of [8, 16, 32, 64]) (dest : lhs (bv w)) (src : lhs (bv w)) => do
tmp ← eval $ ⇑dest + ⇑src;
src .= ⇑dest;
set_result_flags tmp;
cf .= uadd_overflows tmp src;
of .= sadd_overflows tmp src;
af .= uadd4_overflows tmp src;
dest .= tmp
pat_end
------------------------------------------------------------------------
-- fadd definition
def fadd : instruction := do
definst "fadd" $ do
pattern fun (dest : lhs x86_80) (src : lhs x86_80) => do
dest .= x87_fadd dest src
pat_end;
pattern fun (src : lhs float) => do
st0 .= x87_fadd st0 src
pat_end;
pattern fun (src : lhs double) => do
st0 .= x87_fadd st0 src
pat_end
------------------------------------------------------------------------
-- faddp definition
def faddp : instruction := do
definst "faddp" $ do
pattern fun (dest : lhs x86_80) (src : lhs x86_80) => do
dest .= x87_fadd dest src;
record_event event.pop_x87_register_stack
pat_end
------------------------------------------------------------------------
-- fiadd definition
def fiadd : instruction := do
definst "fiadd" $ do
pattern fun (w : one_of [16, 32]) (src : lhs (bv w)) => do
st0 .= x87_fadd st0 src
pat_end
------------------------------------------------------------------------
-- syscall definition
def syscall : instruction :=
definst "syscall" $ mk_pattern (record_event event.syscall)
------------------------------------------------------------------------
-- cpuid definition
def cpuid : instruction :=
definst "cpuid" $ mk_pattern (record_event event.cpuid)
------------------------------------------------------------------------
-- hlt definition
-- Halt
def hlt : instruction :=
definst "hlt" $ mk_pattern (record_event event.hlt)
------------------------------------------------------------------------
-- sub definition
def sub_def : instruction := do
definst "sub" $ do
pattern fun (w : one_of [8, 16, 32, 64]) (dest : lhs (bv w)) (src : bv w) => do
tmp ← eval $ ⇑dest - src;
set_result_flags tmp;
cf .= usub_overflows tmp src;
of .= ssub_overflows tmp src;
af .= usub4_overflows tmp src;
dest .= tmp
pat_end;
pattern fun (src : bv 64) => do
tmp ← eval $ ⇑rax - src;
set_result_flags tmp;
cf .= usub_overflows tmp src;
of .= ssub_overflows tmp src;
af .= usub4_overflows tmp src;
rax .= tmp
pat_end
------------------------------------------------------------------------
-- lea definition
-- Load Effective Address
def lea : instruction :=
definst "lea" $ do
pattern fun (w : one_of [16, 32, 64]) (dest : lhs (bv w)) (src : addr (bv 64)) => do
dest .= trunc (expression.of_addr src) w
pat_end
------------------------------------------------------------------------
-- call definition
-- Call Procedure
def call : instruction :=
definst "call" $ do
pattern fun (v : bv 64) => do
record_event (event.call v)
pat_end
------------------------------------------------------------------------
-- jmp definition
-- Jump
def jmp : instruction :=
definst "jmp" $ do
pattern fun (v : bv 64) => do
record_event (event.jmp v)
pat_end
------------------------------------------------------------------------
-- Condition codes
--
-- Conditional codes for instructions, some of these have multiple names. They only vary
-- in the condition checked so we use helper functions to associate mnemonics with
-- the conditions instead of defining each instruction at the top level.
-- TODO: We might be able to remove the aliases. It looks like the instruction encodings are the same
-- so it might suffice to find out what the decoder will pick as the canonical mnemonic.
def condition_codes : List (List String × expression bit) :=
[ -- Jump if above (cf = 0 and zf = 0)
(["a", "nbe"], expression.bit_and ((cf : bit) = bit_zero) ((zf : bit) = bit_zero))
-- Jump if above or equal (cf = 0)
, (["ae", "nb", "nc"], (cf : bit) = bit_zero)
-- Jump if below (cf = 1)
, (["b", "c", "nae"], (cf : bit))
-- Jump if below or equal (cf = 1 or zf = 1)
, (["be"], expression.bit_or (cf : bit) (zf : bit))
-- Jump if CX is 0
, (["cxz"], (cx : bv 16) = 0)
-- Jump if ECX is 0
, (["ecxz"], (ecx : bv 32) = 0)
-- Jump if RCX is 0
, (["rcxz"], (rcx : bv 64) = 0)
-- Jump if equal (zf = 1)
, (["e", "z"], (zf : bit))
-- Jump if greater (zf = 0 and sf = of)
, (["g", "nle"], expression.bit_and ((zf : bit) = bit_zero) ((sf : bit) = (of : bit)))
-- Jump if greater or equal (sf = of)
, (["ge", "nl"], (sf : bit) = (of : bit))
-- Jump if less (sf ≠ of)
, (["l", "nge"], (sf : bit) ≠ (of : bit))
-- Jump if less or equal (zf = 1 or sf ≠ of)
, (["le", "ng"], expression.bit_or (expression.of_lhs zf = bit_one) (expression.of_lhs sf ≠ expression.of_lhs of))
-- Jump if not above (cf = 1 or zf = 1)
, (["na"], expression.bit_or (expression.of_lhs cf = bit_one) (expression.of_lhs zf = bit_one))
-- Jump if not equal (zf = 0)
, (["ne", "nz"], expression.of_lhs zf = bit_zero)
-- Jump if not overflow (of = 0)
, (["no"], expression.of_lhs of = bit_zero)
-- Jump if not parity (pf = 0)
, (["np", "po"], expression.of_lhs pf = bit_zero)
-- Jump if not sign (sf = 0)
, (["ns"], expression.of_lhs sf = bit_zero)
-- Jump if overflow (of = 1)
, (["o"], expression.of_lhs of = bit_one)
-- Jump if parity (pf = 1)
, (["p", "pe"], expression.of_lhs pf = bit_one)
-- Jump if sign (sf = 1)
, (["s"], expression.of_lhs sf = bit_one)
]
------------------------------------------------------------------------
-- Jcc definition
-- Conditional jumps
def mk_jcc_instruction : String × expression bit → instruction
| (name, cc) => definst ("j" ++ name) $ do
pattern fun (addr : bv 64) => do
record_event (event.branch cc addr)
pat_end
def mk_jcc_instruction_aliases : List String × expression bit → List instruction
| (names, cc) => List.map (fun n => mk_jcc_instruction (n, cc)) names
-- Conditional jump instructions, some of these have multiple names. They only vary
-- in the condition checked so we use helper functions to associate mnemonics with
-- the conditions instead of defining each instruction at the top level.
-- TODO: We might be able to remove the aliases. It looks like the instruction encodings are the same
-- so it might suffice to find out what the decoder will pick as the canonical mnemonic.
def jcc_instructions : List instruction :=
List.join $ List.map mk_jcc_instruction_aliases condition_codes
------------------------------------------------------------------------
-- SETcc definition
-- Conditional sets
def mk_setcc_instruction : String × expression bit → instruction
| (name, cc) => definst ("set" ++ name) $ do
pattern fun (dest : lhs (bv 8)) => do
dest .= mux cc 0 1
pat_end
def mk_setcc_instruction_aliases : List String × expression bit → List instruction
| (names, cc) => List.map (fun n => mk_setcc_instruction (n, cc)) names
-- Conditional jump instructions, some of these have multiple names. They only vary
-- in the condition checked so we use helper functions to associate mnemonics with
-- the conditions instead of defining each instruction at the top level.
-- TODO: We might be able to remove the aliases. It looks like the instruction encodings are the same
-- so it might suffice to find out what the decoder will pick as the canonical mnemonic.
def setcc_instructions : List instruction :=
List.join $ List.map mk_setcc_instruction_aliases condition_codes
------------------------------------------------------------------------
-- CMOVcc definition
-- Conditional moves
def mk_cmovcc_instruction : String × expression bit → instruction
| (name, cc) => definst ("cmov" ++ name) $ do
pattern fun (w : one_of [8,16,32,64]) (dest : lhs (bv w)) (src : bv w) => do
set_cond dest cc src
pat_end
def mk_cmovcc_instruction_aliases : List String × expression bit → List instruction
| (names, cc) => List.map (fun n => mk_cmovcc_instruction (n, cc)) names
def cmovcc_instructions : List instruction :=
List.join $ List.map mk_cmovcc_instruction_aliases condition_codes
------------------------------------------------------------------------
-- leave definition
-- High Level Procedure Exit
def leave : instruction :=
definst "leave" $ do
pattern do
rsp .= rbp;
v ← eval (expression.read (bv 64) rsp);
rsp .= rsp + nat_to_bv 8;
rbp .= v
pat_end
------------------------------------------------------------------------
-- pop definition
-- Pop a Value from the Stack
def pop_def : instruction :=
definst "pop" $ do
pattern fun (w : one_of [16, 32, 64]) (dest: lhs (bv w)) => do
v ← eval (expression.read (bv w) rsp);
rsp .= rsp + nat_to_bv (w/8);
dest .= v
pat_end
------------------------------------------------------------------------
-- push definition
-- Push Word => doubleword or Quadword Onto the Stack
def push_def : instruction :=
definst "push" $ do
pattern fun (w : one_of [8, 16, 32, 64]) (value: bv w) => do
rsp .= rsp - nat_to_bv (w/8);
lhs.write_addr rsp _ .= value
pat_end
------------------------------------------------------------------------
-- ret definition
-- Return from Procedure
def ret : instruction :=
definst "retq" $ do
pattern do
addr ← eval $ expression.read (bv 64) rsp;
rsp .= rsp + nat_to_bv 8;
record_event (event.jmp addr)
pat_end;
pattern fun (off : bv 16) => do
addr ← eval $ expression.read (bv 64) rsp;
rsp .= rsp + (nat_to_bv 8 + uext off 64);
record_event (event.jmp addr)
pat_end
------------------------------------------------------------------------
-- cbw definition
-- Convert Byte to Word
def cbw : instruction :=
definst "cbw" $ do
pattern do
ax .= sext ⇑al 16
pat_end
------------------------------------------------------------------------
-- cdq definition
-- Convert Doubleword to Quadword
def cdq : instruction :=
definst "cdq" $ do
pattern do
let quadword := sext ⇑eax 64; do
edx .= quadword[[63..32]]
pat_end
------------------------------------------------------------------------
-- cdqe definition
-- Convert Doubleword to Quadword
def cdqe : instruction :=
definst "cdqe" $ do
pattern do
rax .= sext ⇑eax 64
pat_end
------------------------------------------------------------------------
-- clc definition
-- Clear Carry Flag
def clc : instruction :=
definst "clc" $ do
pattern do
cf .= bit_zero
pat_end
------------------------------------------------------------------------
-- cld definition
-- Clear Direction Flag
def cld : instruction :=
definst "cld" $ do
pattern do
df .= bit_zero
pat_end
------------------------------------------------------------------------
-- cqo definition
-- Convert Quadword to Octword
def cqo : instruction :=
definst "cqo" $ do
pattern do
let octword := sext ⇑rax 128; do
rdx .= octword[[127..64]]
pat_end
------------------------------------------------------------------------
-- cwd definition
-- Convert Word to Doubleword
def cwd : instruction :=
definst "cwd" $ do
pattern do
let doubleword := sext ⇑ax 32; do
dx .= doubleword[[31..16]]
pat_end
------------------------------------------------------------------------
-- cwde definition
-- Convert Word to Doubleword
def cwde : instruction :=
definst "cwde" $ do
pattern do
eax .= sext ⇑ax 32
pat_end
------------------------------------------------------------------------
-- sar/shr/sal/shl definitions
/-- This is an enum for the shift op, so that our shift code can reflect the Intel description. -/
inductive shift_op
| shl : shift_op -- Also used for shl since it is same operation.
| sar : shift_op
| shr : shift_op
-- Generic shift operation, takes functions for doing the shift and
-- setting the flags.
def do_sh {w:ℕ}
(op : shift_op)
(v: lhs (bv w)) -- value to be shifted
(count: bv 8) -- amount to shift by
(count_mask: bv 8) -- mask for the counter
: semantics Unit := do
-- The intel manual says that the count is masked to give an upper
-- bound on the time the shift takes, with a mask of 63 in the case
-- of a 64 bit operand, and 31 in the other cases.
low_count ← eval $ count .&. count_mask;
-- compute the result
res ← eval $
(match op with
| shift_op.shl => prim.shl w v low_count
| shift_op.shr => prim.shr w v low_count
| shift_op.sar => prim.sar w v low_count)
;
-- When the count is zero, nothing happens, and no flags change
let is_nonzero : expression bit := low_count ≠ 0;
-- Set the af flag
set_cond af is_nonzero undef;
(match op with
| shift_op.shl =>
cf .= prim.shl_carry w cf v low_count
| shift_op.shr => do
cf .= prim.shr_carry w v cf low_count
| shift_op.sar => do
cf .= prim.sar_carry w v cf low_count
);
-- Compute value of of_flag if low_count is 1.
let of_flag :=
(match op with
| shift_op.shl => expression.bit_xor (@msb w res) (@msb w v)
| shift_op.sar => bit_zero
| shift_op.shr => @msb w v
);
set_cond of is_nonzero (mux (low_count = 1) of_flag undef);
set_cond sf is_nonzero (msb res);
set_cond zf is_nonzero (res = 0);
set_cond pf is_nonzero (even_parity (least_byte res));
set_cond v is_nonzero res
def shift_def (nm:String) (o : shift_op) : instruction :=
definst nm $ do
pattern fun (w : one_of [8, 16, 32]) (value: lhs (bv w)) (count: bv 8) => do
do_sh o value count (32-1)
pat_end;
pattern fun (value: lhs (bv 64)) (count: bv 8) => do
do_sh o value count (64-1)
pat_end;
-- CL version
pattern fun (w : one_of [8, 16, 32]) (value: lhs (bv w)) => do
do_sh o value cl (32 - 1)
pat_end;
pattern fun (value: lhs (bv 64)) => do
do_sh o value cl (64 - 1)
pat_end
-- Shift logical right
def shr_def : instruction := shift_def "shr" shift_op.shr
-- Shift arithmetic right
def sar_def : instruction := shift_def "sar" shift_op.sar
-- Shift logical left
def shl_def : instruction := shift_def "shl" shift_op.shl
-- Shift arithmetic left (same as shl semantically)
def sal_def : instruction := shift_def "sal" shift_op.shl
------------------------------------------------------------------------
-- Instruction List
def all_instructions :=
[ and_def
, adc
, add
, bsf_def
, bsr_def
, bswap
, bt
, btc
, btr
, bts
, call
, cbw
, cdq
, cdqe
, clc
, cld
, cmp
, cpuid
, cqo
, cwd
, cwde
, dec
, div
, fadd
, faddp
, fiadd
, hlt
, idiv
, imul
, inc
] ++
jcc_instructions ++ setcc_instructions ++ cmovcc_instructions ++
[ jmp
, lea
, leave
, mov
, movaps
, movups
, movsx
-- , movsxd
, movzx
, mul
, neg
, nop
, noopl
, not
, or_def
, pause
, pop_def
, push_def
, ret
, sal_def
, sar_def
, shl_def
, shr_def
, sub_def
, syscall
, test
, xadd
, xchg
, xor_def
]
end x86
/-
open x86
def main : io Unit := do
monad.mapm' (io.put_str_ln ∘ repr) all_instructions
-/
|
e1a2a11bd64414e22d5d034cf3b2ca5531a98727 | f5f7e6fae601a5fe3cac7cc3ed353ed781d62419 | /src/algebra/ring.lean | cf0391be3cd840db474ab35e8a06003f4e1c8768 | [
"Apache-2.0"
] | permissive | EdAyers/mathlib | 9ecfb2f14bd6caad748b64c9c131befbff0fb4e0 | ca5d4c1f16f9c451cf7170b10105d0051db79e1b | refs/heads/master | 1,626,189,395,845 | 1,555,284,396,000 | 1,555,284,396,000 | 144,004,030 | 0 | 0 | Apache-2.0 | 1,533,727,664,000 | 1,533,727,663,000 | null | UTF-8 | Lean | false | false | 11,525 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn
-/
import algebra.group data.set.basic
universes u v
variable {α : Type u}
section
variable [semiring α]
theorem mul_two (n : α) : n * 2 = n + n :=
(left_distrib n 1 1).trans (by simp)
theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n :=
(two_mul _).symm
variable (α)
lemma zero_ne_one_or_forall_eq_0 : (0 : α) ≠ 1 ∨ (∀a:α, a = 0) :=
by haveI := classical.dec;
refine not_or_of_imp (λ h a, _); simpa using congr_arg ((*) a) h.symm
lemma eq_zero_of_zero_eq_one (h : (0 : α) = 1) : (∀a:α, a = 0) :=
(zero_ne_one_or_forall_eq_0 α).neg_resolve_left h
theorem subsingleton_of_zero_eq_one (h : (0 : α) = 1) : subsingleton α :=
⟨λa b, by rw [eq_zero_of_zero_eq_one α h a, eq_zero_of_zero_eq_one α h b]⟩
end
namespace units
variables [ring α] {a b : α}
instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩
@[simp] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl
@[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl
@[simp] protected theorem neg_neg (u : units α) : - -u = u :=
units.ext $ neg_neg _
@[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) :=
units.ext $ neg_mul_eq_neg_mul_symm _ _
@[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) :=
units.ext $ (neg_mul_eq_mul_neg _ _).symm
@[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp
protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp
end units
instance [semiring α] : semiring (with_zero α) :=
{ left_distrib := λ a b c, begin
cases a with a, {refl},
cases b with b; cases c with c; try {refl},
exact congr_arg some (left_distrib _ _ _)
end,
right_distrib := λ a b c, begin
cases c with c,
{ change (a + b) * 0 = a * 0 + b * 0, simp },
cases a with a; cases b with b; try {refl},
exact congr_arg some (right_distrib _ _ _)
end,
..with_zero.add_comm_monoid,
..with_zero.mul_zero_class,
..with_zero.monoid }
attribute [refl] dvd_refl
attribute [trans] dvd.trans
class is_semiring_hom {α : Type u} {β : Type v} [semiring α] [semiring β] (f : α → β) : Prop :=
(map_zero : f 0 = 0)
(map_one : f 1 = 1)
(map_add : ∀ {x y}, f (x + y) = f x + f y)
(map_mul : ∀ {x y}, f (x * y) = f x * f y)
namespace is_semiring_hom
variables {β : Type v} [semiring α] [semiring β]
variables (f : α → β) [is_semiring_hom f] {x y : α}
instance id : is_semiring_hom (@id α) := by refine {..}; intros; refl
instance comp {γ} [semiring γ] (g : β → γ) [is_semiring_hom g] :
is_semiring_hom (g ∘ f) :=
{ map_zero := by simp [map_zero f]; exact map_zero g,
map_one := by simp [map_one f]; exact map_one g,
map_add := λ x y, by simp [map_add f]; rw map_add g; refl,
map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl }
instance : is_add_monoid_hom f :=
{ ..‹is_semiring_hom f› }
instance : is_monoid_hom f :=
{ ..‹is_semiring_hom f› }
end is_semiring_hom
section
variables [ring α] (a b c d e : α)
lemma mul_neg_one (a : α) : a * -1 = -a := by simp
lemma neg_one_mul (a : α) : -1 * a = -a := by simp
theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d :=
calc
a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp
... ↔ a * e + c - b * e = d : iff.intro (λ h, begin simp [h] end) (λ h,
begin simp [h.symm] end)
... ↔ (a - b) * e + c = d : begin simp [@sub_eq_add_neg α, @right_distrib α] end
theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d :=
assume h,
calc
(a - b) * e + c = (a * e + c) - b * e : begin simp [@sub_eq_add_neg α, @right_distrib α] end
... = d : begin rw h, simp [@add_sub_cancel α] end
theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : α} (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 :=
begin
split,
{ intro ha, apply h, simp [ha] },
{ intro hb, apply h, simp [hb] }
end
end
@[simp] lemma zero_dvd_iff [comm_semiring α] {a : α} : 0 ∣ a ↔ a = 0 :=
⟨eq_zero_of_zero_dvd, λ h, by rw h⟩
section comm_ring
variable [comm_ring α]
@[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) :=
⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩
@[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) :=
⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩
theorem dvd_add_left {a b c : α} (h : a ∣ c) : a ∣ b + c ↔ a ∣ b :=
(dvd_add_iff_left h).symm
theorem dvd_add_right {a b c : α} (h : a ∣ b) : a ∣ b + c ↔ a ∣ c :=
(dvd_add_iff_right h).symm
end comm_ring
class is_ring_hom {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) : Prop :=
(map_one : f 1 = 1)
(map_mul : ∀ {x y}, f (x * y) = f x * f y)
(map_add : ∀ {x y}, f (x + y) = f x + f y)
namespace is_ring_hom
variables {β : Type v} [ring α] [ring β]
def of_semiring (f : α → β) [H : is_semiring_hom f] : is_ring_hom f := {..H}
variables (f : α → β) [is_ring_hom f] {x y : α}
lemma map_zero : f 0 = 0 :=
calc f 0 = f (0 + 0) - f 0 : by rw [map_add f]; simp
... = 0 : by simp
lemma map_neg : f (-x) = -f x :=
calc f (-x) = f (-x + x) - f x : by rw [map_add f]; simp
... = -f x : by simp [map_zero f]
lemma map_sub : f (x - y) = f x - f y :=
by simp [map_add f, map_neg f]
instance id : is_ring_hom (@id α) := by refine {..}; intros; refl
instance comp {γ} [ring γ] (g : β → γ) [is_ring_hom g] :
is_ring_hom (g ∘ f) :=
{ map_add := λ x y, by simp [map_add f]; rw map_add g; refl,
map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl,
map_one := by simp [map_one f]; exact map_one g }
instance : is_semiring_hom f :=
{ map_zero := map_zero f, ..‹is_ring_hom f› }
instance : is_add_group_hom f :=
⟨λ _ _, map_add f⟩
end is_ring_hom
set_option old_structure_cmd true
class nonzero_comm_semiring (α : Type*) extends comm_semiring α, zero_ne_one_class α
class nonzero_comm_ring (α : Type*) extends comm_ring α, zero_ne_one_class α
instance nonzero_comm_ring.to_nonzero_comm_semiring {α : Type*} [I : nonzero_comm_ring α] :
nonzero_comm_semiring α :=
{ zero_ne_one := by convert zero_ne_one,
..show comm_semiring α, by apply_instance }
instance integral_domain.to_nonzero_comm_ring (α : Type*) [id : integral_domain α] :
nonzero_comm_ring α :=
{ ..id }
lemma units.coe_ne_zero [nonzero_comm_semiring α] (u : units α) : (u : α) ≠ 0 :=
λ h : u.1 = 0, by simpa [h, zero_ne_one] using u.3
def nonzero_comm_ring.of_ne [comm_ring α] {x y : α} (h : x ≠ y) : nonzero_comm_ring α :=
{ one := 1,
zero := 0,
zero_ne_one := λ h01, h $ by rw [← one_mul x, ← one_mul y, ← h01, zero_mul, zero_mul],
..show comm_ring α, by apply_instance }
def nonzero_comm_semiring.of_ne [comm_semiring α] {x y : α} (h : x ≠ y) : nonzero_comm_semiring α :=
{ one := 1,
zero := 0,
zero_ne_one := λ h01, h $ by rw [← one_mul x, ← one_mul y, ← h01, zero_mul, zero_mul],
..show comm_semiring α, by apply_instance }
/-- A domain is a ring with no zero divisors, i.e. satisfying
the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain
is an integral domain without assuming commutativity of multiplication. -/
class domain (α : Type u) extends ring α, no_zero_divisors α, zero_ne_one_class α
section domain
variable [domain α]
@[simp] theorem mul_eq_zero {a b : α} : a * b = 0 ↔ a = 0 ∨ b = 0 :=
⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo,
or.elim o (λh, by rw h; apply zero_mul) (λh, by rw h; apply mul_zero)⟩
@[simp] theorem zero_eq_mul {a b : α} : 0 = a * b ↔ a = 0 ∨ b = 0 :=
by rw [eq_comm, mul_eq_zero]
theorem mul_ne_zero' {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 :=
λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) h₁ h₂
theorem domain.mul_right_inj {a b c : α} (ha : a ≠ 0) : b * a = c * a ↔ b = c :=
by rw [← sub_eq_zero, ← mul_sub_right_distrib, mul_eq_zero];
simp [ha]; exact sub_eq_zero
theorem domain.mul_left_inj {a b c : α} (ha : a ≠ 0) : a * b = a * c ↔ b = c :=
by rw [← sub_eq_zero, ← mul_sub_left_distrib, mul_eq_zero];
simp [ha]; exact sub_eq_zero
theorem eq_zero_of_mul_eq_self_right' {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 :=
by apply (mul_eq_zero.1 _).resolve_right (sub_ne_zero.2 h₁);
rw [mul_sub_left_distrib, mul_one, sub_eq_zero, h₂]
theorem eq_zero_of_mul_eq_self_left' {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 :=
by apply (mul_eq_zero.1 _).resolve_left (sub_ne_zero.2 h₁);
rw [mul_sub_right_distrib, one_mul, sub_eq_zero, h₂]
theorem mul_ne_zero_comm' {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 :=
mul_ne_zero' (ne_zero_of_mul_ne_zero_left h) (ne_zero_of_mul_ne_zero_right h)
end domain
/- integral domains -/
section
variables [s : integral_domain α] (a b c d e : α)
include s
instance integral_domain.to_domain : domain α := {..s}
theorem eq_of_mul_eq_mul_right_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : b * a = c * a) : b = c :=
have b * a - c * a = 0, by simp [h],
have (b - c) * a = 0, by rw [mul_sub_right_distrib, this],
have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha,
eq_of_sub_eq_zero this
theorem eq_of_mul_eq_mul_left_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : a * b = a * c) : b = c :=
have a * b - a * c = 0, by simp [h],
have a * (b - c) = 0, by rw [mul_sub_left_distrib, this],
have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha,
eq_of_sub_eq_zero this
theorem mul_dvd_mul_iff_left {a b c : α} (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c :=
exists_congr $ λ d, by rw [mul_assoc, domain.mul_left_inj ha]
theorem mul_dvd_mul_iff_right {a b c : α} (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b :=
exists_congr $ λ d, by rw [mul_right_comm, domain.mul_right_inj hc]
lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 :=
by conv {to_lhs, rw [inv_eq_iff_mul_eq_one, ← mul_one (1 : units α), units.ext_iff, units.coe_mul,
units.coe_mul, mul_self_eq_mul_self_iff, ← units.ext_iff, ← units.coe_neg, ← units.ext_iff] }
end
/- units in various rings -/
namespace units
section comm_semiring
variables [comm_semiring α] (a b : α) (u : units α)
@[simp] lemma coe_dvd : ↑u ∣ a := ⟨↑u⁻¹ * a, by simp⟩
@[simp] lemma dvd_coe_mul : a ∣ b * u ↔ a ∣ b :=
iff.intro
(assume ⟨c, eq⟩, ⟨c * ↑u⁻¹, by rw [← mul_assoc, ← eq, units.mul_inv_cancel_right]⟩)
(assume ⟨c, eq⟩, eq.symm ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _)
@[simp] lemma dvd_coe : a ∣ ↑u ↔ a ∣ 1 :=
suffices a ∣ 1 * ↑u ↔ a ∣ 1, by simpa,
dvd_coe_mul _ _ _
@[simp] lemma coe_mul_dvd : a * u ∣ b ↔ a ∣ b :=
iff.intro
(assume ⟨c, eq⟩, ⟨c * ↑u, eq.symm ▸ by ac_refl⟩)
(assume h, suffices a * ↑u ∣ b * 1, by simpa, mul_dvd_mul h (coe_dvd _ _))
end comm_semiring
section domain
variables [domain α]
@[simp] theorem ne_zero : ∀(u : units α), (↑u : α) ≠ 0
| ⟨u, v, (huv : 0 * v = 1), hvu⟩ rfl := by simpa using huv
end domain
end units
|
fe3d4449a36cbc932461cdd6e8d0286dd200eed0 | 8c9f90127b78cbeb5bb17fd6b5db1db2ffa3cbc4 | /deMorgan.lean | d964453eddd43364449f0b53cbc544e78bba078d | [] | no_license | picrin/lean | 420f4d08bb3796b911d56d0938e4410e1da0e072 | 3d10c509c79704aa3a88ebfb24d08b30ce1137cc | refs/heads/master | 1,611,166,610,726 | 1,536,671,438,000 | 1,536,671,438,000 | 60,029,899 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,342 | lean | -- `variable` is an unfortunate name, conflicting
-- with usual meaning of the word.
-- `p` and `q` are *implicit parameters*
-- passed to our functions. (All lemmas and theorems
-- will be functions)
variables p q : Prop
-- These introduction and elimination rules
-- are analogous to and.intro and and.elim,
-- but they work with falsehoods as opposed to truths.
-- `lemma` is syntactic sugar for `definition`,
lemma andFalseElimRight : ¬(p ∧ q) → (p → ¬q) :=
-- `assume` is syntactic sugar for `λ`
assume (LHS : ¬(p ∧ q)) (Hp: p),
(λ (Hq: q), LHS (and.intro Hp Hq))
lemma andFalseElimLeft : ¬(p ∧ q) → (q → ¬p) :=
assume (LHS : ¬(p ∧ q)) (Hq: q),
(λ (Hp: p), LHS (and.intro Hp Hq))
lemma andFalseIntroLeft : ¬p → ¬(p ∧ q) :=
assume (LHS : ¬p),
(λ Hnpq: (p ∧ q), LHS (and.elim_left Hnpq))
lemma andFalseIntroRight : ¬p → ¬(q ∧ p) :=
assume (LHS : ¬p),
(λ Hnpq: (q ∧ p), LHS (and.elim_right Hnpq))
-- We need classical logic for excluded middle to prove de Morgan's.
open classical
-- Prove de Morgan's.
lemma deMorganAndLeft : ¬(p ∧ q) → (¬p ∨ ¬q) :=
assume LHS : ¬(p ∧ q),
-- The claim easily follows from excluded middle on p
or.elim (em p) -- (p ∨ ¬p)
-- if p, we have to first show that ¬q, and then introduce desired disjunction (¬p ∨ ¬q)
(λ Hp: p, or.intro_right (¬p) (andFalseElimRight p q LHS Hp))
-- if ¬p, we can simply introduce desired disjunction (¬p ∨ ¬q)
(λ Hp: (¬p), or.intro_left (¬q) Hp)
lemma deMorganAndRight : (¬p ∨ ¬q) → ¬(p ∧ q) :=
assume LHS : (¬p ∨ ¬q),
or.elim LHS (andFalseIntroLeft p q) (andFalseIntroRight q p)
-- If this line type-checks correctly, then the theorem is proven.
-- In order to be completely certain about the proof,
-- one has to additionally check that:
-- 1. No additional `axioms` have been defined.
-- Some axioms can lead to inconsistent foundations.
-- 2. The statement of the theorem is correct, i.e.
-- in our case deMorganAnd really *does* correspond
-- to one of the theorems commonly referred to as de Morgan's laws.
theorem deMorganAnd (p : Prop) (q: Prop) : ¬(p ∧ q) ↔ (¬p ∨ ¬q) :=
iff.intro (deMorganAndLeft p q) (deMorganAndRight p q)
-- prints the type of deMorganAnd.
check deMorganAnd
|
6dd498ae4b386920e7be85c4402802b7c2c0525f | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/measure_theory/outer_measure.lean | fae94309036592561dfc9bcbc3ae36d89dcdf3d5 | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 19,601 | 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
Outer measures -- overapproximations of measures
-/
import algebra.big_operators algebra.module
topology.instances.ennreal analysis.specific_limits
measure_theory.measurable_space
noncomputable theory
open set lattice finset function filter encodable
local attribute [instance] classical.prop_decidable
namespace measure_theory
structure outer_measure (α : Type*) :=
(measure_of : set α → ennreal)
(empty : measure_of ∅ = 0)
(mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂)
(Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ (∑i, measure_of (s i)))
namespace outer_measure
instance {α} : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩
section basic
variables {α : Type*} {ms : set (outer_measure α)} {m : outer_measure α}
@[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty
theorem mono' (m : outer_measure α) {s₁ s₂}
(h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h
theorem Union_aux (m : set α → ennreal) (m0 : m ∅ = 0)
{β} [encodable β] (s : β → set α) :
(∑ b, m (s b)) = ∑ i, m (⋃ b ∈ decode2 β i, s b) :=
begin
have H : ∀ n, m (⋃ b ∈ decode2 β n, s b) ≠ 0 → (decode2 β n).is_some,
{ intros n h,
cases decode2 β n with b,
{ exact (h (by simp [m0])).elim },
{ exact rfl } },
refine tsum_eq_tsum_of_ne_zero_bij (λ n h, option.get (H n h)) _ _ _,
{ intros m n hm hn e,
have := mem_decode2.1 (option.get_mem (H n hn)),
rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this },
{ intros b h,
refine ⟨encode b, _, _⟩,
{ convert h, simp [ext_iff, encodek2] },
{ exact option.get_of_mem _ (encodek2 _) } },
{ intros n h,
transitivity, swap,
rw [show decode2 β n = _, from option.get_mem (H n h)],
congr, simp [ext_iff, -option.some_get] }
end
protected theorem Union (m : outer_measure α)
{β} [encodable β] (s : β → set α) :
m (⋃i, s i) ≤ (∑i, m (s i)) :=
by rw [Union_decode2, Union_aux _ m.empty' s]; exact m.Union_nat _
lemma Union_null (m : outer_measure α)
{β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 :=
by simpa [h] using m.Union s
protected lemma union (m : outer_measure α) (s₁ s₂ : set α) :
m (s₁ ∪ s₂) ≤ m s₁ + m s₂ :=
begin
convert m.Union (λ b, cond b s₁ s₂),
{ simp [union_eq_Union] },
{ rw tsum_fintype, change _ = _ + _, simp }
end
lemma union_null (m : outer_measure α) {s₁ s₂ : set α}
(h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 :=
by simpa [h₁, h₂] using m.union s₁ s₂
@[extensionality] lemma ext : ∀{μ₁ μ₂ : outer_measure α},
(∀s, μ₁ s = μ₂ s) → μ₁ = μ₂
| ⟨m₁, e₁, _, u₁⟩ ⟨m₂, e₂, _, u₂⟩ h := by congr; exact funext h
instance : has_zero (outer_measure α) :=
⟨{ measure_of := λ_, 0,
empty := rfl,
mono := assume _ _ _, le_refl 0,
Union_nat := assume s, zero_le _ }⟩
@[simp] theorem zero_apply (s : set α) : (0 : outer_measure α) s = 0 := rfl
instance : inhabited (outer_measure α) := ⟨0⟩
instance : has_add (outer_measure α) :=
⟨λm₁ m₂,
{ measure_of := λs, m₁ s + m₂ s,
empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty],
mono := assume s₁ s₂ h, add_le_add' (m₁.mono h) (m₂.mono h),
Union_nat := assume s,
calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤
(∑i, m₁ (s i)) + (∑i, m₂ (s i)) :
add_le_add' (m₁.Union_nat s) (m₂.Union_nat s)
... = _ : ennreal.tsum_add.symm}⟩
@[simp] theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) :
(m₁ + m₂) s = m₁ s + m₂ s := rfl
instance : add_comm_monoid (outer_measure α) :=
{ zero := 0,
add := (+),
add_comm := assume a b, ext $ assume s, add_comm _ _,
add_assoc := assume a b c, ext $ assume s, add_assoc _ _ _,
add_zero := assume a, ext $ assume s, add_zero _,
zero_add := assume a, ext $ assume s, zero_add _ }
instance : has_bot (outer_measure α) := ⟨0⟩
instance outer_measure.order_bot : order_bot (outer_measure α) :=
{ le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s,
bot := 0,
le_refl := assume a s, le_refl _,
le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s),
le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s),
bot_le := assume a s, zero_le _ }
section supremum
instance : has_Sup (outer_measure α) :=
⟨λms, {
measure_of := λs, ⨆m:ms, m.val s,
empty := le_zero_iff_eq.1 $ supr_le $ λ ⟨m, h⟩, le_of_eq m.empty,
mono := assume s₁ s₂ hs, supr_le_supr $ assume ⟨m, hm⟩, m.mono hs,
Union_nat := assume f, supr_le $ assume m,
calc m.val (⋃i, f i) ≤ (∑ (i : ℕ), m.val (f i)) : m.val.Union_nat _
... ≤ (∑i, ⨆m:ms, m.val (f i)) :
ennreal.tsum_le_tsum $ assume i, le_supr (λm:ms, m.val (f i)) m }⟩
private lemma le_Sup (hm : m ∈ ms) : m ≤ Sup ms :=
λ s, le_supr (λm:ms, m.val s) ⟨m, hm⟩
private lemma Sup_le (hm : ∀m' ∈ ms, m' ≤ m) : Sup ms ≤ m :=
λ s, (supr_le $ assume ⟨m', h'⟩, (hm m' h') s)
instance : has_Inf (outer_measure α) := ⟨λs, Sup {m | ∀m'∈s, m ≤ m'}⟩
private lemma Inf_le (hm : m ∈ ms) : Inf ms ≤ m := Sup_le $ assume m' h', h' _ hm
private lemma le_Inf (hm : ∀m' ∈ ms, m ≤ m') : m ≤ Inf ms := le_Sup hm
instance : complete_lattice (outer_measure α) :=
{ top := Sup univ,
le_top := assume a, le_Sup (mem_univ a),
Sup := Sup,
Sup_le := assume s m, Sup_le,
le_Sup := assume s m, le_Sup,
Inf := Inf,
Inf_le := assume s m, Inf_le,
le_Inf := assume s m, le_Inf,
sup := λa b, Sup {a, b},
le_sup_left := assume a b, le_Sup $ by simp,
le_sup_right := assume a b, le_Sup $ by simp,
sup_le := assume a b c ha hb, Sup_le $ by simp [or_imp_distrib, ha, hb] {contextual:=tt},
inf := λa b, Inf {a, b},
inf_le_left := assume a b, Inf_le $ by simp,
inf_le_right := assume a b, Inf_le $ by simp,
le_inf := assume a b c ha hb, le_Inf $ by simp [or_imp_distrib, ha, hb] {contextual:=tt},
.. outer_measure.order_bot }
@[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) :
(Sup ms) s = ⨆ m : ms, m s := rfl
@[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) :
(⨆ i : ι, f i) s = ⨆ i, f i s :=
le_antisymm
(supr_le $ λ ⟨_, i, rfl⟩, le_supr _ i)
(supr_le $ λ i, le_supr
(λ (m : {a : outer_measure α // ∃ i, f i = a}), m.1 s)
⟨f i, i, rfl⟩)
@[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) :
(m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s :=
by have := supr_apply (λ b, cond b m₁ m₂) s;
rwa [supr_bool_eq, supr_bool_eq] at this
end supremum
def map {β} (f : α → β) (m : outer_measure α) : outer_measure β :=
{ measure_of := λs, m (f ⁻¹' s),
empty := m.empty,
mono := λ s t h, m.mono (preimage_mono h),
Union_nat := λ s, by rw [preimage_Union]; exact
m.Union_nat (λ i, f ⁻¹' s i) }
@[simp] theorem map_apply {β} (f : α → β)
(m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl
@[simp] theorem map_id (m : outer_measure α) : map id m = m :=
ext $ λ s, rfl
@[simp] theorem map_map {β γ} (f : α → β) (g : β → γ)
(m : outer_measure α) : map g (map f m) = map (g ∘ f) m :=
ext $ λ s, rfl
instance : functor outer_measure := {map := λ α β, map}
instance : is_lawful_functor outer_measure :=
{ id_map := λ α, map_id,
comp_map := λ α β γ f g m, (map_map f g m).symm }
/-- The dirac outer measure. -/
def dirac (a : α) : outer_measure α :=
{ measure_of := λs, ⨆ h : a ∈ s, 1,
empty := by simp,
mono := λ s t h, supr_le_supr2 (λ h', ⟨h h', le_refl _⟩),
Union_nat := λ s, supr_le $ λ h,
let ⟨i, h⟩ := mem_Union.1 h in
le_trans (by exact le_supr _ h) (ennreal.le_tsum i) }
@[simp] theorem dirac_apply (a : α) (s : set α) :
dirac a s = ⨆ h : a ∈ s, 1 := rfl
def sum {ι} (f : ι → outer_measure α) : outer_measure α :=
{ measure_of := λs, ∑ i, f i s,
empty := by simp,
mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h),
Union_nat := λ s, by rw ennreal.tsum_comm; exact
ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) }
@[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) :
sum f s = ∑ i, f i s := rfl
instance : has_scalar ennreal (outer_measure α) :=
⟨λ a m, {
measure_of := λs, a * m s,
empty := by simp,
mono := λ s t h, canonically_ordered_semiring.mul_le_mul (le_refl _) (m.mono' h),
Union_nat := λ s, by rw ennreal.mul_tsum; exact
canonically_ordered_semiring.mul_le_mul (le_refl _) (m.Union_nat _) }⟩
@[simp] theorem smul_apply (a : ennreal) (m : outer_measure α) (s : set α) :
(a • m) s = a * m s := rfl
instance : semimodule ennreal (outer_measure α) :=
{ smul_add := λ a m₁ m₂, ext $ λ s, mul_add _ _ _,
add_smul := λ a b m, ext $ λ s, add_mul _ _ _,
mul_smul := λ a b m, ext $ λ s, mul_assoc _ _ _,
one_smul := λ m, ext $ λ s, one_mul _,
zero_smul := λ m, ext $ λ s, zero_mul _,
smul_zero := λ a, ext $ λ s, mul_zero _,
..outer_measure.has_scalar }
theorem smul_dirac_apply (a : ennreal) (b : α) (s : set α) :
(a • dirac b) s = ⨆ h : b ∈ s, a :=
by by_cases b ∈ s; simp [h]
theorem top_apply {s : set α} (h : s ≠ ∅) : (⊤ : outer_measure α) s = ⊤ :=
let ⟨a, as⟩ := set.exists_mem_of_ne_empty h in
top_unique $ le_supr_of_le ⟨(⊤ : ennreal) • dirac a, trivial⟩ $
by simp [smul_dirac_apply, as]
end basic
section of_function
set_option eqn_compiler.zeta true
/-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is
a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/
protected def of_function {α : Type*} (m : set α → ennreal) (m_empty : m ∅ = 0) :
outer_measure α :=
let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑i, m (f i) in
{ measure_of := μ,
empty := le_antisymm
(infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty])
(zero_le _),
mono := assume s₁ s₂ hs, infi_le_infi $ assume f,
infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩,
Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ begin
assume ε hε (hb : (∑i, μ (s i)) < ⊤),
rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩,
refine le_trans _ (add_le_add_left' (le_of_lt hl)),
rw ← ennreal.tsum_add,
choose f hf using show
∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ (∑i, m (f i)) < μ (s i) + ε' i,
{ intro,
have : μ (s i) < μ (s i) + ε' i :=
ennreal.lt_add_right
(lt_of_le_of_lt (by apply ennreal.le_tsum) hb)
(by simpa using hε' i),
simpa [μ, infi_lt_iff] },
refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2),
rw [← ennreal.tsum_prod, ← tsum_equiv equiv.nat_prod_nat_equiv_nat.symm],
swap, {apply_instance},
refine infi_le_of_le _ (infi_le _ _),
exact Union_subset (λ i, subset.trans (hf i).1 $
Union_subset $ λ j, subset.trans (by simp) $
subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)),
end }
theorem of_function_le {α : Type*} (m : set α → ennreal) (m_empty s) :
outer_measure.of_function m m_empty s ≤ m s :=
let f : ℕ → set α := λi, nat.rec_on i s (λn s, ∅) in
infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $
calc (∑i, m (f i)) = ({0} : finset ℕ).sum (λi, m (f i)) :
tsum_eq_sum $ by intro i; cases i; simp [m_empty]
... = m s : by simp; refl
theorem le_of_function {α : Type*} {m m_empty} {μ : outer_measure α} :
μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s :=
⟨λ H s, le_trans (H _) (of_function_le _ _ _),
λ H s, le_infi $ λ f, le_infi $ λ hs,
le_trans (μ.mono hs) $ le_trans (μ.Union f) $
ennreal.tsum_le_tsum $ λ i, H _⟩
end of_function
section caratheodory_measurable
universe u
parameters {α : Type u} (m : outer_measure α)
include m
local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc
variables {s s₁ s₂ : set α}
private def C (s : set α) := ∀t, m t = m (t ∩ s) + m (t \ s)
private lemma C_iff_le {s : set α} : C s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t :=
forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $
by convert m.union _ _; rw inter_union_diff t s
@[simp] private lemma C_empty : C ∅ := by simp [C, m.empty, diff_empty]
private lemma C_compl : C s₁ → C (- s₁) := by simp [C, diff_eq]
@[simp] private lemma C_compl_iff : C (- s) ↔ C s :=
⟨λ h, by simpa using C_compl m h, C_compl⟩
private lemma C_union (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∪ s₂) :=
λ t, begin
rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)),
inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁,
inter_eq_self_of_subset_right (set.subset_union_left _ _),
union_diff_left, h₂ (t ∩ s₁)],
simp [diff_eq]
end
private lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : C s₁) {t : set α} :
m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) :=
by rw [h₁, set.inter_assoc, union_inter_cancel_left,
inter_diff_assoc, union_diff_cancel_left h]
private lemma C_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, C (s i)) → C (⋃i<n, s i)
| 0 h := by simp [nat.not_lt_zero]
| (n + 1) h := by rw Union_lt_succ; exact C_union m
(h n (le_refl (n + 1)))
(C_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _)
private lemma C_inter (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∩ s₂) :=
by rw [← C_compl_iff, compl_inter]; from C_union _ (C_compl _ h₁) (C_compl _ h₂)
private lemma C_sum {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) {t : set α} :
∀ {n}, (finset.range n).sum (λi, m (t ∩ s i)) = m (t ∩ ⋃i<n, s i)
| 0 := by simp [nat.not_lt_zero, m.empty]
| (nat.succ n) := begin
simp [Union_lt_succ, range_succ],
rw [measure_inter_union m _ (h n), C_sum],
intro a, simpa [range_succ] using λ h₁ i hi h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩
end
private lemma C_Union_nat {s : ℕ → set α} (h : ∀i, C (s i))
(hd : pairwise (disjoint on s)) : C (⋃i, s i) :=
C_iff_le.2 $ λ t, begin
have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)),
{ convert m.Union (λ i, t ∩ s i),
{ rw inter_Union },
{ simp [ennreal.tsum_eq_supr_nat, C_sum m h hd] } },
refine le_trans (add_le_add_right' hp) _,
rw ennreal.supr_add,
refine supr_le (λ n, le_trans (add_le_add_left' _)
(ge_of_eq (C_Union_lt m (λ i _, h i) _))),
refine m.mono (diff_subset_diff_right _),
exact bUnion_subset (λ i _, subset_Union _ i),
end
private lemma f_Union {s : ℕ → set α} (h : ∀i, C (s i))
(hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑i, m (s i) :=
begin
refine le_antisymm (m.Union_nat s) _,
rw ennreal.tsum_eq_supr_nat,
refine supr_le (λ n, _),
have := @C_sum _ m _ h hd univ n,
simp at this, simp [this],
exact m.mono (bUnion_subset (λ i _, subset_Union _ i)),
end
private def caratheodory_dynkin : measurable_space.dynkin_system α :=
{ has := C,
has_empty := C_empty,
has_compl := assume s, C_compl,
has_Union_nat := assume f hf hn, C_Union_nat hn hf }
/-- Given an outer measure `μ`, the Caratheodory measurable space is
defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/
protected def caratheodory : measurable_space α :=
caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, C_inter
lemma is_caratheodory {s : set α} :
caratheodory.is_measurable s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) :=
iff.rfl
lemma is_caratheodory_le {s : set α} :
caratheodory.is_measurable s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t :=
C_iff_le
protected lemma Union_eq_of_caratheodory {s : ℕ → set α}
(h : ∀i, caratheodory.is_measurable (s i)) (hd : pairwise (disjoint on s)) :
m (⋃i, s i) = ∑i, m (s i) :=
f_Union h hd
end caratheodory_measurable
variables {α : Type*}
lemma caratheodory_is_measurable {m : set α → ennreal} {s : set α}
{h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) :
(outer_measure.of_function m h₀).caratheodory.is_measurable s :=
let o := (outer_measure.of_function m h₀) in
(is_caratheodory_le o).2 $ λ t,
le_infi $ λ f, le_infi $ λ hf, begin
refine le_trans (add_le_add'
(infi_le_of_le (λi, f i ∩ s) $ infi_le _ _)
(infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _,
{ rw ← Union_inter,
exact inter_subset_inter_left _ hf },
{ rw ← Union_diff,
exact diff_subset_diff_left hf },
{ rw ← ennreal.tsum_add,
exact ennreal.tsum_le_tsum (λ i, hs _) }
end
@[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ :=
top_unique $ λ s _ t, (add_zero _).symm
theorem top_caratheodory : (⊤ : outer_measure α).caratheodory = ⊤ :=
top_unique $ assume s hs, (is_caratheodory_le _).2 $ assume t,
by by_cases ht : t = ∅; simp [ht, top_apply]
theorem le_add_caratheodory (m₁ m₂ : outer_measure α) :
m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory :=
λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t]
theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) :
(⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory :=
λ s h t, by simp [λ i,
measurable_space.is_measurable_infi.1 h i t, ennreal.tsum_add]
theorem le_smul_caratheodory (a : ennreal) (m : outer_measure α) :
m.caratheodory ≤ (a • m).caratheodory :=
λ s h t, by simp [h t, mul_add]
@[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ :=
top_unique $ λ s _ t, begin
by_cases a ∈ t; simp [h],
by_cases a ∈ s; simp [h]
end
section Inf_gen
def Inf_gen (m : set (outer_measure α)) (s : set α) : ennreal :=
⨆(h : s ≠ ∅), ⨅ (μ : outer_measure α) (h : μ ∈ m), μ s
@[simp] lemma Inf_gen_empty (m : set (outer_measure α)) : Inf_gen m ∅ = 0 :=
by simp [Inf_gen]
lemma Inf_gen_nonempty1 (m : set (outer_measure α)) (t : set α) (h : t ≠ ∅) :
Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) :=
by rw [Inf_gen, supr_pos h]
lemma Inf_gen_nonempty2 (m : set (outer_measure α)) (μ) (h : μ ∈ m) (t) :
Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) :=
begin
by_cases ht : t = ∅,
{ simp [ht],
refine (bot_unique $ infi_le_of_le μ $ _).symm,
refine infi_le_of_le h (le_refl ⊥) },
{ exact Inf_gen_nonempty1 m t ht }
end
lemma Inf_eq_of_function_Inf_gen (m : set (outer_measure α)) :
Inf m = outer_measure.of_function (Inf_gen m) (Inf_gen_empty m) :=
begin
refine le_antisymm
(assume t', le_of_function.2 (assume t, _) _)
(lattice.le_Inf $ assume μ hμ t, le_trans (outer_measure.of_function_le _ _ _) _);
by_cases ht : t = ∅; simp [ht, Inf_gen_nonempty1],
{ assume μ hμ, exact (show Inf m ≤ μ, from lattice.Inf_le hμ) t },
{ exact infi_le_of_le μ (infi_le _ hμ) }
end
end Inf_gen
end outer_measure
end measure_theory
|
76a941861a1677641b0de5ae74ae68a413c2af6e | 5756a081670ba9c1d1d3fca7bd47cb4e31beae66 | /Mathport/Syntax/Transform/Basic.lean | c9b9bee7b1004b9f3303630ee958452d2dba0256 | [
"Apache-2.0"
] | permissive | leanprover-community/mathport | 2c9bdc8292168febf59799efdc5451dbf0450d4a | 13051f68064f7638970d39a8fecaede68ffbf9e1 | refs/heads/master | 1,693,841,364,079 | 1,693,813,111,000 | 1,693,813,111,000 | 379,357,010 | 27 | 10 | Apache-2.0 | 1,691,309,132,000 | 1,624,384,521,000 | Lean | UTF-8 | Lean | false | false | 1,899 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import Mathport.Syntax.Translate.Basic
namespace Mathport
namespace Transform
open Lean Elab Elab.Command
abbrev M := CommandElabM
abbrev Transformer := Syntax → M Syntax
def throwUnsupported : M α := Elab.throwUnsupportedSyntax
open Elab in
def catchUnsupportedSyntax (k : M α) : M (Option α) :=
catchInternalId unsupportedSyntaxExceptionId (some <$> k) (fun _ => pure none)
initialize transformerAttr : TagAttribute ←
registerTagAttribute `mathport_transformer "Lean 4 → 4 syntax transformation for prettification"
(validate := fun declName => do
let info ← getConstInfo declName
unless info.type.isConstOf ``Transformer do
throwError "declaration must have type {mkConst ``Transformer}")
def matchAlts := Parser.Term.matchAlts
syntax "mathport_rules " matchAlts : command
open Elab.Command in
macro_rules
| `(mathport_rules $[$alts:matchAlt]*) =>
`(@[mathport_transformer] aux_def mathportRules : Transformer :=
fun $[$alts:matchAlt]* | _ => throwUnsupported)
scoped elab "mathport_transformer_list%" : term => do
let decls := transformerAttr.getDecls (← getEnv) |>.map mkCIdent
Elab.Term.elabTerm (← `((#[$[$decls:term],*] : Array Transformer))) none
partial def applyTransformers (transformers : Array Transformer) (stx : Syntax) : M Syntax :=
stx.rewriteBottomUpM fun stx => do
for tr in transformers do
if let some stx' ← catchUnsupportedSyntax do withRef stx do tr stx then
return ← applyTransformers transformers stx'
return stx
open PrettyPrinter TSyntax.Compat in
macro "#mathport_transform " stx:(term <|> command) : command =>
`(run_cmd logInfo <|<-
applyTransformers mathport_transformer_list% (Unhygienic.run `($stx)))
|
905facd714da7ed9d811d6afd45a52514e4fad82 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/tactic/congr.lean | 37d5efe57eaef08e284fb1620db86168412944b1 | [
"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 | 8,663 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import tactic.lint
import tactic.ext
/-!
# Congruence and related tactics
This file contains the tactic `congr'`, which is an extension of `congr`, and various tactics
using `congr'` internally.
`congr'` has some advantages over `congr`:
* It turns `↔` to equalities, before trying another congr lemma
* You can write `congr' n` to give the maximal depth of recursive applications. This is useful if
`congr` breaks down the goal to aggressively, and the resulting goals are false.
* You can write `congr' with ...` to do `congr', ext ...` in a single tactic.
Other tactics in this file:
* `rcongr`: repeatedly apply `congr'` and `ext.`
* `convert`: like `exact`, but produces an equality goal if the type doesn't match.
* `convert_to`: changes the goal, if you prove an equality between the old goal and the new goal.
* `ac_change`: like `convert_to`, but uses `ac_refl` to discharge the goals.
-/
open tactic
setup_tactic_parser
namespace tactic
/-- Apply the constant `iff_of_eq` to the goal. -/
meta def apply_iff_congr_core : tactic unit :=
applyc ``iff_of_eq
/-- The main part of the body for the loop in `congr'`. This will try to replace a goal `f x = f y`
with `x = y`. Also has support for `==` and `↔`. -/
meta def congr_core' : tactic unit :=
do tgt ← target,
apply_eq_congr_core tgt
<|> apply_heq_congr_core
<|> apply_iff_congr_core
<|> fail "congr tactic failed"
/-- The main function in `convert_to`. Changes the goal to `r` and a proof obligation that the goal
is equal to `r`. -/
meta def convert_to_core (r : pexpr) : tactic unit :=
do tgt ← target,
h ← to_expr ``(_ : %%tgt = %%r),
rewrite_target h,
swap
/-- Attempts to prove the goal by proof irrelevance, but avoids unifying universe metavariables
to do so. -/
meta def by_proof_irrel : tactic unit :=
do tgt ← target,
@expr.const tt n [level.zero] ← pure tgt.get_app_fn,
if n = ``eq then `[apply proof_irrel] else
if n = ``heq then `[apply proof_irrel_heq] else
failed
/--
Same as the `congr` tactic, but takes an optional argument which gives
the depth of recursive applications.
* This is useful when `congr` is too aggressive in breaking down the goal.
* For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y`
and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`.
* If, at any point, a subgoal matches a hypothesis then the subgoal will be closed.
-/
meta def congr' : option ℕ → tactic unit
| o := focus1 $
assumption <|> reflexivity transparency.none <|> by_proof_irrel <|>
(guard (o ≠ some 0) >> congr_core' >>
all_goals' (try (congr' (nat.pred <$> o)))) <|>
reflexivity
namespace interactive
/--
Same as the `congr` tactic, but takes an optional argument which gives
the depth of recursive applications.
* This is useful when `congr` is too aggressive in breaking down the goal.
* For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y`
and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`.
* If, at any point, a subgoal matches a hypothesis then the subgoal will be closed.
* You can use `congr' with p (: n)?` to call `ext p (: n)?` to all subgoals generated by `congr'`.
For example, if the goal is `⊢ f '' s = g '' s` then `congr' with x` generates the goal
`x : α ⊢ f x = g x`.
-/
meta def congr' (n : parse (with_desc "n" small_nat)?) :
parse (tk "with" *> prod.mk <$> rintro_patt_parse_hi* <*> (tk ":" *> small_nat)?)? →
tactic unit
| none := tactic.congr' n
| (some ⟨p, m⟩) := focus1 (tactic.congr' n >> all_goals' (tactic.ext p.join m $> ()))
/--
Repeatedly and apply `congr'` and `ext`, using the given patterns as arguments for `ext`.
There are two ways this tactic stops:
* `congr'` fails (makes no progress), after having already applied `ext`.
* `congr'` canceled out the last usage of `ext`. In this case, the state is reverted to before
the `congr'` was applied.
For example, when the goal is
```lean
⊢ (λ x, f x + 3) '' s = (λ x, g x + 3) '' s
```
then `rcongr x` produces the goal
```lean
x : α ⊢ f x = g x
```
This gives the same result as `congr', ext x, congr'`.
In contrast, `congr'` would produce
```lean
⊢ (λ x, f x + 3) = (λ x, g x + 3)
```
and `congr' with x` (or `congr', ext x`) would produce
```lean
x : α ⊢ f x + 3 = g x + 3
```
-/
meta def rcongr : parse (list.join <$> rintro_patt_parse_hi*) → tactic unit
| ps := do
t ← target,
qs ← try_core (tactic.ext ps none),
some () ← try_core (tactic.congr' none >>
(done <|> do s ← target, guard $ ¬ s =ₐ t)) | skip,
done <|> rcongr (qs.get_or_else ps)
add_tactic_doc
{ name := "congr'",
category := doc_category.tactic,
decl_names := [`tactic.interactive.congr', `tactic.interactive.congr, `tactic.interactive.rcongr],
tags := ["congruence"],
inherit_description_from := `tactic.interactive.congr' }
/--
The `exact e` and `refine e` tactics require a term `e` whose type is
definitionally equal to the goal. `convert e` is similar to `refine e`,
but the type of `e` is not required to exactly match the
goal. Instead, new goals are created for differences between the type
of `e` and the goal. For example, in the proof state
```lean
n : ℕ,
e : prime (2 * n + 1)
⊢ prime (n + n + 1)
```
the tactic `convert e` will change the goal to
```lean
⊢ n + n = 2 * n
```
In this example, the new goal can be solved using `ring`.
The `convert` tactic applies congruence lemmas eagerly before reducing,
therefore it can fail in cases where `exact` succeeds:
```lean
def p (n : ℕ) := true
example (h : p 0) : p 1 := by exact h -- succeeds
example (h : p 0) : p 1 := by convert h -- fails, with leftover goal `1 = 0`
```
If `x y : t`, and an instance `subsingleton t` is in scope, then any goals of the form
`x = y` are solved automatically.
The syntax `convert ← e` will reverse the direction of the new goals
(producing `⊢ 2 * n = n + n` in this example).
Internally, `convert e` works by creating a new goal asserting that
the goal equals the type of `e`, then simplifying it using
`congr'`. The syntax `convert e using n` can be used to control the
depth of matching (like `congr' n`). In the example, `convert e using
1` would produce a new goal `⊢ n + n + 1 = 2 * n + 1`.
-/
meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr)
(n : parse (tk "using" *> small_nat)?) : tactic unit :=
do tgt ← target,
u ← infer_type tgt,
r ← i_to_expr ``(%%r : (_ : %%u)),
src ← infer_type r,
src ← simp_lemmas.mk.dsimplify [] src {fail_if_unchanged := ff},
v ← to_expr (if sym.is_some then ``(%%src = %%tgt) else ``(%%tgt = %%src)) tt ff >>= mk_meta_var,
(if sym.is_some then mk_eq_mp v r else mk_eq_mpr v r) >>= tactic.exact,
gs ← get_goals,
set_goals [v],
try (tactic.congr' n),
gs' ← get_goals,
set_goals $ gs' ++ gs
add_tactic_doc
{ name := "convert",
category := doc_category.tactic,
decl_names := [`tactic.interactive.convert],
tags := ["congruence"] }
/--
`convert_to g using n` attempts to change the current goal to `g`, but unlike `change`,
it will generate equality proof obligations using `congr' n` to resolve discrepancies.
`convert_to g` defaults to using `congr' 1`.
`convert_to` is similar to `convert`, but `convert_to` takes a type (the desired subgoal) while
`convert` takes a proof term.
That is, `convert_to g using n` is equivalent to `convert (_ : g) using n`.
-/
meta def convert_to (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit :=
match n with
| none := convert_to_core r >> `[congr' 1]
| (some 0) := convert_to_core r
| (some o) := convert_to_core r >> tactic.congr' o
end
/--
`ac_change g using n` is `convert_to g using n` followed by `ac_refl`. It is useful for
rearranging/reassociating e.g. sums:
```lean
example (a b c d e f g N : ℕ) : (a + b) + (c + d) + (e + f) + g ≤ N :=
begin
ac_change a + d + e + f + c + g + b ≤ _,
-- ⊢ a + d + e + f + c + g + b ≤ N
end
```
-/
meta def ac_change (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit :=
convert_to r n; try ac_refl
add_tactic_doc
{ name := "convert_to",
category := doc_category.tactic,
decl_names := [`tactic.interactive.convert_to, `tactic.interactive.ac_change],
tags := ["congruence"],
inherit_description_from := `tactic.interactive.convert_to }
end interactive
end tactic
|
b8e9b37398ac519c50fbc331ffc2a768688f2636 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/codeBindUnreachIssue.lean | 97a709d7eb7062730854d70e35d5ba540dd9e996 | [
"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 | 151 | lean | set_option trace.Compiler.result true
def f (x : Empty) (y : Nat) : Nat :=
let g (_ : Unit) : Nat → Nat := x.casesOn
let aux := g ()
y + aux y
|
cbc276278687df9ae492d356bac9a1cb1ba81036 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/logic/relation.lean | cda84742cb0c2686e59db1f3dd692bd806907cd1 | [
"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 | 13,257 | 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
Transitive reflexive as well as reflexive closure of relations.
-/
import tactic.basic logic.relator
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
namespace relation
section comp
variables {r : α → β → Prop} {p : β → γ → Prop} {q : γ → δ → Prop}
def comp (r : α → β → Prop) (p : β → γ → Prop) (a : α) (c : γ) : Prop := ∃b, r a b ∧ p b c
local infixr ` ∘r ` : 80 := relation.comp
lemma comp_eq : r ∘r (=) = r :=
funext $ assume a, funext $ assume b, propext $ iff.intro
(assume ⟨c, h, eq⟩, eq ▸ h)
(assume h, ⟨b, h, rfl⟩)
lemma eq_comp : (=) ∘r r = r :=
funext $ assume a, funext $ assume b, propext $ iff.intro
(assume ⟨c, eq, h⟩, eq.symm ▸ h)
(assume h, ⟨a, rfl, h⟩)
lemma iff_comp {r : Prop → α → Prop} : (↔) ∘r r = r :=
have (↔) = (=), by funext a b; exact iff_eq_eq,
by rw [this, eq_comp]
lemma comp_iff {r : α → Prop → Prop} : r ∘r (↔) = r :=
have (↔) = (=), by funext a b; exact iff_eq_eq,
by rw [this, comp_eq]
lemma comp_assoc : (r ∘r p) ∘r q = r ∘r p ∘r q :=
begin
funext a d, apply propext,
split,
exact assume ⟨c, ⟨b, hab, hbc⟩, hcd⟩, ⟨b, hab, c, hbc, hcd⟩,
exact assume ⟨b, hab, c, hbc, hcd⟩, ⟨c, ⟨b, hab, hbc⟩, hcd⟩
end
lemma flip_comp : flip (r ∘r p) = (flip p) ∘r (flip r) :=
begin
funext c a, apply propext,
split,
exact assume ⟨b, hab, hbc⟩, ⟨b, hbc, hab⟩,
exact assume ⟨b, hbc, hab⟩, ⟨b, hab, hbc⟩
end
end comp
protected def map (r : α → β → Prop) (f : α → γ) (g : β → δ) : γ → δ → Prop :=
λc d, ∃a b, r a b ∧ f a = c ∧ g b = d
variables {r : α → α → Prop} {a b c d : α}
/-- `refl_trans_gen r`: reflexive transitive closure of `r` -/
inductive refl_trans_gen (r : α → α → Prop) (a : α) : α → Prop
| refl : refl_trans_gen a
| tail {b c} : refl_trans_gen b → r b c → refl_trans_gen c
attribute [refl] refl_trans_gen.refl
run_cmd tactic.mk_iff_of_inductive_prop `relation.refl_trans_gen `relation.refl_trans_gen.cases_tail_iff
/-- `refl_gen r`: reflexive closure of `r` -/
inductive refl_gen (r : α → α → Prop) (a : α) : α → Prop
| refl : refl_gen a
| single {b} : r a b → refl_gen b
run_cmd tactic.mk_iff_of_inductive_prop `relation.refl_gen `relation.refl_gen_iff
/-- `trans_gen r`: transitive closure of `r` -/
inductive trans_gen (r : α → α → Prop) (a : α) : α → Prop
| single {b} : r a b → trans_gen b
| tail {b c} : trans_gen b → r b c → trans_gen c
run_cmd tactic.mk_iff_of_inductive_prop `relation.trans_gen `relation.trans_gen_iff
attribute [refl] refl_gen.refl
lemma refl_gen.to_refl_trans_gen : ∀{a b}, refl_gen r a b → refl_trans_gen r a b
| a _ refl_gen.refl := by refl
| a b (refl_gen.single h) := refl_trans_gen.tail refl_trans_gen.refl h
namespace refl_trans_gen
@[trans] lemma trans (hab : refl_trans_gen r a b) (hbc : refl_trans_gen r b c) : refl_trans_gen r a c :=
begin
induction hbc,
case refl_trans_gen.refl { assumption },
case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd }
end
lemma single (hab : r a b) : refl_trans_gen r a b :=
refl.tail hab
lemma head (hab : r a b) (hbc : refl_trans_gen r b c) : refl_trans_gen r a c :=
begin
induction hbc,
case refl_trans_gen.refl { exact refl.tail hab },
case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd }
end
lemma symmetric (h : symmetric r) : symmetric (refl_trans_gen r) :=
begin
intros x y h,
induction h with z w a b c,
{ refl },
{ apply relation.refl_trans_gen.head (h b) c }
end
lemma cases_tail : refl_trans_gen r a b → b = a ∨ (∃c, refl_trans_gen r a c ∧ r c b) :=
(cases_tail_iff r a b).1
lemma head_induction_on
{P : ∀(a:α), refl_trans_gen r a b → Prop}
{a : α} (h : refl_trans_gen r a b)
(refl : P b refl)
(head : ∀{a c} (h' : r a c) (h : refl_trans_gen r c b), P c h → P a (h.head h')) :
P a h :=
begin
induction h generalizing P,
case refl_trans_gen.refl { exact refl },
case refl_trans_gen.tail : b c hab hbc ih {
apply ih,
show P b _, from head hbc _ refl,
show ∀a a', r a a' → refl_trans_gen r a' b → P a' _ → P a _, from assume a a' hab hbc, head hab _
}
end
lemma trans_induction_on
{P : ∀{a b : α}, refl_trans_gen r a b → Prop}
{a b : α} (h : refl_trans_gen r a b)
(ih₁ : ∀a, @P a a refl)
(ih₂ : ∀{a b} (h : r a b), P (single h))
(ih₃ : ∀{a b c} (h₁ : refl_trans_gen r a b) (h₂ : refl_trans_gen r b c), P h₁ → P h₂ → P (h₁.trans h₂)) :
P h :=
begin
induction h,
case refl_trans_gen.refl { exact ih₁ a },
case refl_trans_gen.tail : b c hab hbc ih { exact ih₃ hab (single hbc) ih (ih₂ hbc) }
end
lemma cases_head (h : refl_trans_gen r a b) : a = b ∨ (∃c, r a c ∧ refl_trans_gen r c b) :=
begin
induction h using relation.refl_trans_gen.head_induction_on,
{ left, refl },
{ right, existsi _, split; assumption }
end
lemma cases_head_iff : refl_trans_gen r a b ↔ a = b ∨ (∃c, r a c ∧ refl_trans_gen r c b) :=
begin
split,
{ exact cases_head },
{ assume h,
rcases h with rfl | ⟨c, hac, hcb⟩,
{ refl },
{ exact head hac hcb } }
end
lemma total_of_right_unique (U : relator.right_unique r)
(ab : refl_trans_gen r a b) (ac : refl_trans_gen r a c) :
refl_trans_gen r b c ∨ refl_trans_gen r c b :=
begin
induction ab with b d ab bd IH,
{ exact or.inl ac },
{ rcases IH with IH | IH,
{ rcases cases_head IH with rfl | ⟨e, be, ec⟩,
{ exact or.inr (single bd) },
{ cases U bd be, exact or.inl ec } },
{ exact or.inr (IH.tail bd) } }
end
end refl_trans_gen
namespace trans_gen
lemma to_refl {a b} (h : trans_gen r a b) : refl_trans_gen r a b :=
begin
induction h with b h b c _ bc ab,
exact refl_trans_gen.single h,
exact refl_trans_gen.tail ab bc
end
@[trans] lemma trans_left (hab : trans_gen r a b) (hbc : refl_trans_gen r b c) : trans_gen r a c :=
begin
induction hbc,
case refl_trans_gen.refl : c hab { assumption },
case refl_trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd }
end
@[trans] lemma trans (hab : trans_gen r a b) (hbc : trans_gen r b c) : trans_gen r a c :=
trans_left hab hbc.to_refl
lemma head' (hab : r a b) (hbc : refl_trans_gen r b c) : trans_gen r a c :=
trans_left (single hab) hbc
lemma tail' (hab : refl_trans_gen r a b) (hbc : r b c) : trans_gen r a c :=
begin
induction hab generalizing c,
case refl_trans_gen.refl : c hac { exact single hac },
case refl_trans_gen.tail : d b hab hdb IH { exact tail (IH hdb) hbc }
end
@[trans] lemma trans_right (hab : refl_trans_gen r a b) (hbc : trans_gen r b c) : trans_gen r a c :=
begin
induction hbc,
case trans_gen.single : c hbc { exact tail' hab hbc },
case trans_gen.tail : c d hbc hcd hac { exact hac.tail hcd }
end
lemma head (hab : r a b) (hbc : trans_gen r b c) : trans_gen r a c :=
head' hab hbc.to_refl
lemma tail'_iff : trans_gen r a c ↔ ∃ b, refl_trans_gen r a b ∧ r b c :=
begin
refine ⟨λ h, _, λ ⟨b, hab, hbc⟩, tail' hab hbc⟩,
cases h with _ hac b _ hab hbc,
{ exact ⟨_, by refl, hac⟩ },
{ exact ⟨_, hab.to_refl, hbc⟩ }
end
lemma head'_iff : trans_gen r a c ↔ ∃ b, r a b ∧ refl_trans_gen r b c :=
begin
refine ⟨λ h, _, λ ⟨b, hab, hbc⟩, head' hab hbc⟩,
induction h,
case trans_gen.single : c hac { exact ⟨_, hac, by refl⟩ },
case trans_gen.tail : b c hab hbc IH {
rcases IH with ⟨d, had, hdb⟩, exact ⟨_, had, hdb.tail hbc⟩ }
end
end trans_gen
section refl_trans_gen
open refl_trans_gen
lemma refl_trans_gen_iff_eq (h : ∀b, ¬ r a b) : refl_trans_gen r a b ↔ b = a :=
by rw [cases_head_iff]; simp [h, eq_comm]
lemma refl_trans_gen_iff_eq_or_trans_gen :
refl_trans_gen r a b ↔ b = a ∨ trans_gen r a b :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ cases h with c _ hac hcb,
{ exact or.inl rfl },
{ exact or.inr (trans_gen.tail' hac hcb) } },
{ rcases h with rfl | h, {refl}, {exact h.to_refl} }
end
lemma refl_trans_gen_lift {p : β → β → Prop} {a b : α} (f : α → β)
(h : ∀a b, r a b → p (f a) (f b)) (hab : refl_trans_gen r a b) : refl_trans_gen p (f a) (f b) :=
hab.trans_induction_on (assume a, refl) (assume a b, refl_trans_gen.single ∘ h _ _) (assume a b c _ _, trans)
lemma refl_trans_gen_mono {p : α → α → Prop} :
(∀a b, r a b → p a b) → refl_trans_gen r a b → refl_trans_gen p a b :=
refl_trans_gen_lift id
lemma refl_trans_gen_eq_self (refl : reflexive r) (trans : transitive r) :
refl_trans_gen r = r :=
funext $ λ a, funext $ λ b, propext $
⟨λ h, begin
induction h with b c h₁ h₂ IH, {apply refl},
exact trans IH h₂,
end, single⟩
lemma reflexive_refl_trans_gen : reflexive (refl_trans_gen r) :=
assume a, refl
lemma transitive_refl_trans_gen : transitive (refl_trans_gen r) :=
assume a b c, trans
lemma refl_trans_gen_idem :
refl_trans_gen (refl_trans_gen r) = refl_trans_gen r :=
refl_trans_gen_eq_self reflexive_refl_trans_gen transitive_refl_trans_gen
lemma refl_trans_gen_lift' {p : β → β → Prop} {a b : α} (f : α → β)
(h : ∀a b, r a b → refl_trans_gen p (f a) (f b)) (hab : refl_trans_gen r a b) : refl_trans_gen p (f a) (f b) :=
by simpa [refl_trans_gen_idem] using refl_trans_gen_lift f h hab
lemma refl_trans_gen_closed {p : α → α → Prop} :
(∀ a b, r a b → refl_trans_gen p a b) → refl_trans_gen r a b → refl_trans_gen p a b :=
refl_trans_gen_lift' id
end refl_trans_gen
def join (r : α → α → Prop) : α → α → Prop := λa b, ∃c, r a c ∧ r b c
section join
open refl_trans_gen refl_gen
lemma church_rosser
(h : ∀a b c, r a b → r a c → ∃d, refl_gen r b d ∧ refl_trans_gen r c d)
(hab : refl_trans_gen r a b) (hac : refl_trans_gen r a c) : join (refl_trans_gen r) b c :=
begin
induction hab,
case refl_trans_gen.refl { exact ⟨c, hac, refl⟩ },
case refl_trans_gen.tail : d e had hde ih {
clear hac had a,
rcases ih with ⟨b, hdb, hcb⟩,
have : ∃a, refl_trans_gen r e a ∧ refl_gen r b a,
{ clear hcb, induction hdb,
case refl_trans_gen.refl { exact ⟨e, refl, refl_gen.single hde⟩ },
case refl_trans_gen.tail : f b hdf hfb ih {
rcases ih with ⟨a, hea, hfa⟩,
cases hfa with _ hfa,
{ exact ⟨b, hea.tail hfb, refl_gen.refl⟩ },
{ rcases h _ _ _ hfb hfa with ⟨c, hbc, hac⟩,
exact ⟨c, hea.trans hac, hbc⟩ } } },
rcases this with ⟨a, hea, hba⟩, cases hba with _ hba,
{ exact ⟨b, hea, hcb⟩ },
{ exact ⟨a, hea, hcb.tail hba⟩ } }
end
lemma join_of_single (h : reflexive r) (hab : r a b) : join r a b :=
⟨b, hab, h b⟩
lemma symmetric_join : symmetric (join r) :=
assume a b ⟨c, hac, hcb⟩, ⟨c, hcb, hac⟩
lemma reflexive_join (h : reflexive r) : reflexive (join r) :=
assume a, ⟨a, h a, h a⟩
lemma transitive_join (ht : transitive r) (h : ∀a b c, r a b → r a c → join r b c) :
transitive (join r) :=
assume a b c ⟨x, hax, hbx⟩ ⟨y, hby, hcy⟩,
let ⟨z, hxz, hyz⟩ := h b x y hbx hby in
⟨z, ht hax hxz, ht hcy hyz⟩
lemma equivalence_join (hr : reflexive r) (ht : transitive r) (h : ∀a b c, r a b → r a c → join r b c) :
equivalence (join r) :=
⟨reflexive_join hr, symmetric_join, transitive_join ht h⟩
lemma equivalence_join_refl_trans_gen
(h : ∀a b c, r a b → r a c → ∃d, refl_gen r b d ∧ refl_trans_gen r c d) :
equivalence (join (refl_trans_gen r)) :=
equivalence_join reflexive_refl_trans_gen transitive_refl_trans_gen (assume a b c, church_rosser h)
lemma join_of_equivalence {r' : α → α → Prop} (hr : equivalence r)
(h : ∀a b, r' a b → r a b) : join r' a b → r a b
| ⟨c, hac, hbc⟩ := hr.2.2 (h _ _ hac) (hr.2.1 $ h _ _ hbc)
lemma refl_trans_gen_of_transitive_reflexive {r' : α → α → Prop} (hr : reflexive r) (ht : transitive r)
(h : ∀a b, r' a b → r a b) (h' : refl_trans_gen r' a b) : r a b :=
begin
induction h' with b c hab hbc ih,
{ exact hr _ },
{ exact ht ih (h _ _ hbc) }
end
lemma refl_trans_gen_of_equivalence {r' : α → α → Prop} (hr : equivalence r) :
(∀a b, r' a b → r a b) → refl_trans_gen r' a b → r a b :=
refl_trans_gen_of_transitive_reflexive hr.1 hr.2.2
end join
section eqv_gen
lemma eqv_gen_iff_of_equivalence (h : equivalence r) : eqv_gen r a b ↔ r a b :=
iff.intro
begin
assume h,
induction h,
case eqv_gen.rel { assumption },
case eqv_gen.refl { exact h.1 _ },
case eqv_gen.symm { apply h.2.1, assumption },
case eqv_gen.trans : a b c _ _ hab hbc { exact h.2.2 hab hbc }
end
(eqv_gen.rel a b)
lemma eqv_gen_mono {r p : α → α → Prop}
(hrp : ∀a b, r a b → p a b) (h : eqv_gen r a b) : eqv_gen p a b :=
begin
induction h,
case eqv_gen.rel : a b h { exact eqv_gen.rel _ _ (hrp _ _ h) },
case eqv_gen.refl : { exact eqv_gen.refl _ },
case eqv_gen.symm : a b h ih { exact eqv_gen.symm _ _ ih },
case eqv_gen.trans : a b c ih1 ih2 hab hbc { exact eqv_gen.trans _ _ _ hab hbc }
end
end eqv_gen
end relation
|
8c380f4de0a03a1104c6b728fa67dc043e36218c | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /stage0/src/Lean/Meta/Offset.lean | 76dcf4321945e23bb6e6a965ce3f036e50195cbb | [
"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 | 6,207 | 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.Data.LBool
import Lean.Meta.InferType
namespace Lean.Meta
private abbrev withInstantiatedMVars (e : Expr) (k : Expr → OptionT MetaM α) : OptionT MetaM α := do
let eNew ← instantiateMVars e
if eNew.getAppFn.isMVar then
failure
else
k eNew
/--
Evaluate simple `Nat` expressions.
Remark: this method assumes the given expression has type `Nat`. -/
partial def evalNat : Expr → OptionT MetaM Nat
| Expr.lit (Literal.natVal n) _ => return n
| Expr.mdata _ e _ => evalNat e
| Expr.const `Nat.zero _ _ => return 0
| e@(Expr.app ..) => visit e
| e@(Expr.mvar ..) => visit e
| _ => failure
where
visit e := do
let f := e.getAppFn
match f with
| Expr.mvar .. => withInstantiatedMVars e evalNat
| Expr.const c _ _ =>
let nargs := e.getAppNumArgs
if c == `Nat.succ && nargs == 1 then
let v ← evalNat (e.getArg! 0)
return v+1
else if c == `Nat.add && nargs == 2 then
let v₁ ← evalNat (e.getArg! 0)
let v₂ ← evalNat (e.getArg! 1)
return v₁ + v₂
else if c == `Nat.sub && nargs == 2 then
let v₁ ← evalNat (e.getArg! 0)
let v₂ ← evalNat (e.getArg! 1)
return v₁ - v₂
else if c == `Nat.mul && nargs == 2 then
let v₁ ← evalNat (e.getArg! 0)
let v₂ ← evalNat (e.getArg! 1)
return v₁ * v₂
else if c == `Add.add && nargs == 4 then
let v₁ ← evalNat (e.getArg! 2)
let v₂ ← evalNat (e.getArg! 3)
return v₁ + v₂
else if c == `Sub.sub && nargs == 4 then
let v₁ ← evalNat (e.getArg! 2)
let v₂ ← evalNat (e.getArg! 3)
return v₁ - v₂
else if c == `Mul.mul && nargs == 4 then
let v₁ ← evalNat (e.getArg! 2)
let v₂ ← evalNat (e.getArg! 3)
return v₁ * v₂
else if c == `HAdd.hAdd && nargs == 6 then
let v₁ ← evalNat (e.getArg! 3)
let v₂ ← evalNat (e.getArg! 5)
return v₁ + v₂
else if c == `HSub.hSub && nargs == 6 then
let v₁ ← evalNat (e.getArg! 4)
let v₂ ← evalNat (e.getArg! 5)
return v₁ - v₂
else if c == `HMul.hMul && nargs == 6 then
let v₁ ← evalNat (e.getArg! 4)
let v₂ ← evalNat (e.getArg! 5)
return v₁ * v₂
else if c == `OfNat.ofNat && nargs == 3 then
evalNat (e.getArg! 1)
else
failure
| _ => failure
/- Quick function for converting `e` into `s + k` s.t. `e` is definitionally equal to `Nat.add s k`. -/
private partial def getOffsetAux : Expr → Bool → OptionT MetaM (Expr × Nat)
| e@(Expr.app _ a _), top => do
let f := e.getAppFn
match f with
| Expr.mvar .. => withInstantiatedMVars e (getOffsetAux · top)
| Expr.const c _ _ =>
let nargs := e.getAppNumArgs
if c == `Nat.succ && nargs == 1 then do
let (s, k) ← getOffsetAux a false
pure (s, k+1)
else if c == `Nat.add && nargs == 2 then do
let v ← evalNat (e.getArg! 1)
let (s, k) ← getOffsetAux (e.getArg! 0) false
pure (s, k+v)
else if c == `Add.add && nargs == 4 then do
let v ← evalNat (e.getArg! 3)
let (s, k) ← getOffsetAux (e.getArg! 2) false
pure (s, k+v)
else if c == `HAdd.hAdd && nargs == 6 then do
let v ← evalNat (e.getArg! 5)
let (s, k) ← getOffsetAux (e.getArg! 4) false
pure (s, k+v)
else if top then failure else pure (e, 0)
| _ => if top then failure else pure (e, 0)
| e, top => if top then failure else pure (e, 0)
private def getOffset (e : Expr) : OptionT MetaM (Expr × Nat) :=
getOffsetAux e true
private partial def isOffset : Expr → OptionT MetaM (Expr × Nat)
| e@(Expr.app _ a _) =>
let f := e.getAppFn
match f with
| Expr.mvar .. => withInstantiatedMVars e isOffset
| Expr.const c _ _ =>
let nargs := e.getAppNumArgs
if (c == `Nat.succ && nargs == 1) || (c == `Nat.add && nargs == 2) || (c == `Add.add && nargs == 4) || (c == `HAdd.hAdd && nargs == 6) then
getOffset e
else
failure
| _ => failure
| _ => failure
private def isNatZero (e : Expr) : MetaM Bool := do
match (← evalNat e) with
| some v => v == 0
| _ => false
private def mkOffset (e : Expr) (offset : Nat) : MetaM Expr := do
if offset == 0 then
return e
else if (← isNatZero e) then
return mkNatLit offset
else
return mkAppB (mkConst `Nat.add) e (mkNatLit offset)
def isDefEqOffset (s t : Expr) : MetaM LBool := do
let ifNatExpr (x : MetaM LBool) : MetaM LBool := do
let type ← inferType s
if (← Meta.isExprDefEqAux type (mkConst `Nat)) then
x
else
return LBool.undef
let isDefEq (s t) : MetaM LBool :=
ifNatExpr <| toLBoolM <| Meta.isExprDefEqAux s t
match (← isOffset s) with
| some (s, k₁) =>
match (← isOffset t) with
| some (t, k₂) => -- s+k₁ =?= t+k₂
if k₁ == k₂ then
isDefEq s t
else if k₁ < k₂ then
isDefEq s (← mkOffset t (k₂ - k₁))
else
isDefEq (← mkOffset s (k₁ - k₂)) t
| none =>
match (← evalNat t) with
| some v₂ => -- s+k₁ =?= v₂
if v₂ ≥ k₁ then
isDefEq s (mkNatLit $ v₂ - k₁)
else
ifNatExpr <| return LBool.false
| none =>
return LBool.undef
| none =>
match (← evalNat s) with
| some v₁ =>
match (← isOffset t) with
| some (t, k₂) => -- v₁ =?= t+k₂
if v₁ ≥ k₂ then
isDefEq (mkNatLit $ v₁ - k₂) t
else
ifNatExpr <| return LBool.false
| none =>
match (← evalNat t) with
| some v₂ => ifNatExpr <| return (v₁ == v₂).toLBool -- v₁ =?= v₂
| none => return LBool.undef
| none => return LBool.undef
end Lean.Meta
|
ed0a09ce8a96b16a6269e956c1473c841074a2bc | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/group_theory/perm/subgroup.lean | 95cea04e829a4bb91626548929ae5d6547982347 | [
"Apache-2.0"
] | permissive | hamdysalah1/mathlib | b915f86b2503feeae268de369f1b16932321f097 | 95454452f6b3569bf967d35aab8d852b1ddf8017 | refs/heads/master | 1,677,154,116,545 | 1,611,797,994,000 | 1,611,797,994,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,229 | lean | /-
Copyright (c) 2020 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import group_theory.perm.basic
import data.fintype.basic
import group_theory.subgroup
/-!
# Lemmas about subgroups within the permutations (self-equivalences) of a type `α`
This file provides extra lemmas about some `subgroup`s that exist within `equiv.perm α`.
`group_theory.subgroup` depends on `group_theory.perm.basic`, so these need to be in a separate
file.
-/
namespace equiv
namespace perm
universes u
@[simp]
lemma sum_congr_hom.card_range {α β : Type*}
[fintype (sum_congr_hom α β).range] [fintype (perm α × perm β)] :
fintype.card (sum_congr_hom α β).range = fintype.card (perm α × perm β) :=
fintype.card_eq.mpr ⟨(set.range (sum_congr_hom α β) sum_congr_hom_injective).symm⟩
@[simp]
lemma sigma_congr_right_hom.card_range {α : Type*} {β : α → Type*}
[fintype (sigma_congr_right_hom β).range] [fintype (Π a, perm (β a))] :
fintype.card (sigma_congr_right_hom β).range = fintype.card (Π a, perm (β a)) :=
fintype.card_eq.mpr ⟨(set.range (sigma_congr_right_hom β) sigma_congr_right_hom_injective).symm⟩
end perm
end equiv
|
fea2264fce73f09217bce207d7ea2809b99239b0 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Data/Lsp/InitShutdown.lean | ad1eea912c96f5faefaf380b90dee041c36ebd78 | [
"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,033 | lean | /-
Copyright (c) 2020 Marc Huisinga. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Marc Huisinga, Wojciech Nawrocki
-/
import Lean.Data.Lsp.Capabilities
import Lean.Data.Lsp.Workspace
import Lean.Data.Json
/-! Functionality to do with initializing and shutting down
the server ("General Messages" section of LSP spec). -/
namespace Lean
namespace Lsp
open Json
structure ClientInfo where
name : String
version? : Option String := none
deriving ToJson, FromJson
/--
A TraceValue represents the level of verbosity with which the server systematically reports its execution trace using `$/logTrace` notifications.
[reference](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#traceValue)
-/
inductive Trace where
| off
| messages
| verbose
instance : FromJson Trace := ⟨fun j =>
match j.getStr? with
| Except.ok "off" => return Trace.off
| Except.ok "messages" => return Trace.messages
| Except.ok "verbose" => return Trace.verbose
| _ => throw "uknown trace"⟩
instance Trace.hasToJson : ToJson Trace :=
⟨fun
| Trace.off => "off"
| Trace.messages => "messages"
| Trace.verbose => "verbose"⟩
/-- Lean-specific initialization options. -/
structure InitializationOptions where
/-- Time (in milliseconds) which must pass since latest edit until elaboration begins. Lower
values may make editors feel faster at the cost of higher CPU usage. Defaults to 200ms. -/
editDelay? : Option Nat
/-- Whether the client supports interactive widgets. When true, in order to improve performance
the server may cease including information which can be retrieved interactively in some standard
LSP messages. Defaults to false. -/
hasWidgets? : Option Bool
deriving ToJson, FromJson
structure InitializeParams where
processId? : Option Int := none
clientInfo? : Option ClientInfo := none
/- We don't support the deprecated rootPath
(rootPath? : Option String) -/
rootUri? : Option String := none
initializationOptions? : Option InitializationOptions := none
capabilities : ClientCapabilities
/-- If omitted, we default to off. -/
trace : Trace := Trace.off
workspaceFolders? : Option (Array WorkspaceFolder) := none
deriving ToJson
def InitializeParams.editDelay (params : InitializeParams) : Nat :=
params.initializationOptions? |>.bind (·.editDelay?) |>.getD 200
instance : FromJson InitializeParams where
fromJson? j := do
/- Many of these params can be null instead of not present.
For ease of implementation, we're liberal:
missing params, wrong json types and null all map to none,
even if LSP sometimes only allows some subset of these.
In cases where LSP makes a meaningful distinction
between different kinds of missing values, we'll
follow accordingly. -/
let processId? := j.getObjValAs? Int "processId"
let clientInfo? := j.getObjValAs? ClientInfo "clientInfo"
let rootUri? := j.getObjValAs? String "rootUri"
let initializationOptions? := j.getObjValAs? InitializationOptions "initializationOptions"
let capabilities ← j.getObjValAs? ClientCapabilities "capabilities"
let trace := (j.getObjValAs? Trace "trace").toOption.getD Trace.off
let workspaceFolders? := j.getObjValAs? (Array WorkspaceFolder) "workspaceFolders"
return ⟨
processId?.toOption,
clientInfo?.toOption,
rootUri?.toOption,
initializationOptions?.toOption,
capabilities,
trace,
workspaceFolders?.toOption⟩
inductive InitializedParams where
| mk
instance : FromJson InitializedParams :=
⟨fun _ => pure InitializedParams.mk⟩
instance : ToJson InitializedParams :=
⟨fun _ => Json.null⟩
structure ServerInfo where
name : String
version? : Option String := none
deriving ToJson, FromJson
structure InitializeResult where
capabilities : ServerCapabilities
serverInfo? : Option ServerInfo := none
deriving ToJson, FromJson
end Lsp
end Lean
|
7e9310fe69a7bd4f7df896970ff567905a927236 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/1686.lean | 3f83c58aec579e5d8d07f29450b04d19e1da9a04 | [
"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 | 465 | lean | def f (n : ℕ) := n + n
def g (n : ℕ) := 2*n
example (n : ℕ) : g (n+1) = f n + 2 :=
begin
change 2 * (n + 1) = f n + 2,
unfold f,
guard_target 2 * (n + 1) = n + n + 2,
admit
end
example (n : ℕ) : g (n+1) = f n + 2 :=
begin
change g (n + 1) with 2 * (n+1),
unfold f,
guard_target 2 * (n + 1) = n + n + 2,
admit
end
example (n : ℕ) : g (n+1) = f n + 2 :=
begin
change 2 * (n + 1) = _,
unfold f,
guard_target 2 * (n + 1) = n + n + 2,
admit
end
|
ff15b541b5242ff200048c0831bb15241980adce | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/data/set/intervals/unordered_interval.lean | 026c3420404422509912d76647f45dd1fb4b01fb | [
"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 | 7,905 | lean | /-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import order.bounds
import data.set.intervals.image_preimage
/-!
# Intervals without endpoints ordering
In any decidable linear order `α`, we define the set of elements lying between two elements `a` and
`b` as `Icc (min a b) (max a b)`.
`Icc a b` requires the assumption `a ≤ b` to be meaningful, which is sometimes inconvenient. The
interval as defined in this file is always the set of things lying between `a` and `b`, regardless
of the relative order of `a` and `b`.
For real numbers, `Icc (min a b) (max a b)` is the same as `segment a b`.
## Notation
We use the localized notation `[a, b]` for `interval a b`. One can open the locale `interval` to
make the notation available.
-/
universe u
namespace set
section linear_order
variables {α : Type u} [linear_order α] {a a₁ a₂ b b₁ b₂ x : α}
/-- `interval a b` is the set of elements lying between `a` and `b`, with `a` and `b` included. -/
def interval (a b : α) := Icc (min a b) (max a b)
localized "notation `[`a `, ` b `]` := interval a b" in interval
@[simp] lemma interval_of_le (h : a ≤ b) : [a, b] = Icc a b :=
by rw [interval, min_eq_left h, max_eq_right h]
@[simp] lemma interval_of_ge (h : b ≤ a) : [a, b] = Icc b a :=
by { rw [interval, min_eq_right h, max_eq_left h] }
lemma interval_swap (a b : α) : [a, b] = [b, a] :=
or.elim (le_total a b) (by simp {contextual := tt}) (by simp {contextual := tt})
lemma interval_of_lt (h : a < b) : [a, b] = Icc a b :=
interval_of_le (le_of_lt h)
lemma interval_of_gt (h : b < a) : [a, b] = Icc b a :=
interval_of_ge (le_of_lt h)
lemma interval_of_not_le (h : ¬ a ≤ b) : [a, b] = Icc b a :=
interval_of_gt (lt_of_not_ge h)
lemma interval_of_not_ge (h : ¬ b ≤ a) : [a, b] = Icc a b :=
interval_of_lt (lt_of_not_ge h)
@[simp] lemma interval_self : [a, a] = {a} :=
set.ext $ by simp [le_antisymm_iff, and_comm]
@[simp] lemma nonempty_interval : set.nonempty [a, b] :=
by { simp only [interval, min_le_iff, le_max_iff, nonempty_Icc], left, left, refl }
@[simp] lemma left_mem_interval : a ∈ [a, b] :=
by { rw [interval, mem_Icc], exact ⟨min_le_left _ _, le_max_left _ _⟩ }
@[simp] lemma right_mem_interval : b ∈ [a, b] :=
by { rw interval_swap, exact left_mem_interval }
lemma Icc_subset_interval : Icc a b ⊆ [a, b] :=
by { assume x h, rwa interval_of_le, exact le_trans h.1 h.2 }
lemma Icc_subset_interval' : Icc b a ⊆ [a, b] :=
by { rw interval_swap, apply Icc_subset_interval }
lemma mem_interval_of_le (ha : a ≤ x) (hb : x ≤ b) : x ∈ [a, b] :=
Icc_subset_interval ⟨ha, hb⟩
lemma mem_interval_of_ge (hb : b ≤ x) (ha : x ≤ a) : x ∈ [a, b] :=
Icc_subset_interval' ⟨hb, ha⟩
lemma interval_subset_interval (h₁ : a₁ ∈ [a₂, b₂]) (h₂ : b₁ ∈ [a₂, b₂]) : [a₁, b₁] ⊆ [a₂, b₂] :=
Icc_subset_Icc (le_min h₁.1 h₂.1) (max_le h₁.2 h₂.2)
lemma interval_subset_interval_iff_mem : [a₁, b₁] ⊆ [a₂, b₂] ↔ a₁ ∈ [a₂, b₂] ∧ b₁ ∈ [a₂, b₂] :=
iff.intro (λh, ⟨h left_mem_interval, h right_mem_interval⟩) (λ h, interval_subset_interval h.1 h.2)
lemma interval_subset_interval_iff_le :
[a₁, b₁] ⊆ [a₂, b₂] ↔ min a₂ b₂ ≤ min a₁ b₁ ∧ max a₁ b₁ ≤ max a₂ b₂ :=
by { rw [interval, interval, Icc_subset_Icc_iff], exact min_le_max }
lemma interval_subset_interval_right (h : x ∈ [a, b]) : [x, b] ⊆ [a, b] :=
interval_subset_interval h right_mem_interval
lemma interval_subset_interval_left (h : x ∈ [a, b]) : [a, x] ⊆ [a, b] :=
interval_subset_interval left_mem_interval h
lemma bdd_below_bdd_above_iff_subset_interval (s : set α) :
bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ [a, b] :=
begin
rw [bdd_below_bdd_above_iff_subset_Icc],
split,
{ rintro ⟨a, b, h⟩, exact ⟨a, b, λ x hx, Icc_subset_interval (h hx)⟩ },
{ rintro ⟨a, b, h⟩, exact ⟨min a b, max a b, h⟩ }
end
end linear_order
open_locale interval
section ordered_add_comm_group
variables {α : Type u} [linear_ordered_add_comm_group α] (a b c x y : α)
@[simp] lemma preimage_const_add_interval : (λ x, a + x) ⁻¹' [b, c] = [b - a, c - a] :=
by simp only [interval, preimage_const_add_Icc, min_sub_sub_right, max_sub_sub_right]
@[simp] lemma preimage_add_const_interval : (λ x, x + a) ⁻¹' [b, c] = [b - a, c - a] :=
by simpa only [add_comm] using preimage_const_add_interval a b c
@[simp] lemma preimage_neg_interval : -([a, b]) = [-a, -b] :=
by simp only [interval, preimage_neg_Icc, min_neg_neg, max_neg_neg]
@[simp] lemma preimage_sub_const_interval : (λ x, x - a) ⁻¹' [b, c] = [b + a, c + a] :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_const_sub_interval : (λ x, a - x) ⁻¹' [b, c] = [a - b, a - c] :=
by { rw [interval, interval, preimage_const_sub_Icc],
simp only [sub_eq_add_neg, min_add_add_left, max_add_add_left, min_neg_neg, max_neg_neg], }
@[simp] lemma image_const_add_interval : (λ x, a + x) '' [b, c] = [a + b, a + c] :=
by simp [add_comm]
@[simp] lemma image_add_const_interval : (λ x, x + a) '' [b, c] = [b + a, c + a] :=
by simp
@[simp] lemma image_const_sub_interval : (λ x, a - x) '' [b, c] = [a - b, a - c] :=
by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)]
@[simp] lemma image_sub_const_interval : (λ x, x - a) '' [b, c] = [b - a, c - a] :=
by simp [sub_eq_add_neg, add_comm]
lemma image_neg_interval : has_neg.neg '' [a, b] = [-a, -b] := by simp
variables {a b c x y}
/-- If `[x, y]` is a subinterval of `[a, b]`, then the distance between `x` and `y`
is less than or equal to that of `a` and `b` -/
lemma abs_sub_le_of_subinterval (h : [x, y] ⊆ [a, b]) : abs (y - x) ≤ abs (b - a) :=
begin
rw [← max_sub_min_eq_abs, ← max_sub_min_eq_abs],
rw [interval_subset_interval_iff_le] at h,
exact sub_le_sub h.2 h.1,
end
/-- If `x ∈ [a, b]`, then the distance between `a` and `x` is less than or equal to
that of `a` and `b` -/
lemma abs_sub_left_of_mem_interval (h : x ∈ [a, b]) : abs (x - a) ≤ abs (b - a) :=
abs_sub_le_of_subinterval (interval_subset_interval_left h)
/-- If `x ∈ [a, b]`, then the distance between `x` and `b` is less than or equal to
that of `a` and `b` -/
lemma abs_sub_right_of_mem_interval (h : x ∈ [a, b]) : abs (b - x) ≤ abs (b - a) :=
abs_sub_le_of_subinterval (interval_subset_interval_right h)
end ordered_add_comm_group
section linear_ordered_field
variables {k : Type u} [linear_ordered_field k] {a : k}
@[simp] lemma preimage_mul_const_interval (ha : a ≠ 0) (b c : k) :
(λ x, x * a) ⁻¹' [b, c] = [b / a, c / a] :=
(lt_or_gt_of_ne ha).elim
(λ ha, by simp [interval, ha, ha.le, min_div_div_right_of_nonpos, max_div_div_right_of_nonpos])
(λ (ha : 0 < a), by simp [interval, ha, ha.le, min_div_div_right, max_div_div_right])
@[simp] lemma preimage_const_mul_interval (ha : a ≠ 0) (b c : k) :
(λ x, a * x) ⁻¹' [b, c] = [b / a, c / a] :=
by simp only [← preimage_mul_const_interval ha, mul_comm]
@[simp] lemma preimage_div_const_interval (ha : a ≠ 0) (b c : k) :
(λ x, x / a) ⁻¹' [b, c] = [b * a, c * a] :=
(preimage_mul_const_interval (inv_ne_zero ha) _ _).trans $ by simp [div_eq_mul_inv]
@[simp] lemma image_mul_const_interval (a b c : k) : (λ x, x * a) '' [b, c] = [b * a, c * a] :=
if ha : a = 0 then by simp [ha] else
calc (λ x, x * a) '' [b, c] = (λ x, x / a) ⁻¹' [b, c] :
(units.mk0 a ha).mul_right.image_eq_preimage _
... = [b * a, c * a] : preimage_div_const_interval ha _ _
@[simp] lemma image_const_mul_interval (a b c : k) : (λ x, a * x) '' [b, c] = [a * b, a * c] :=
by simpa only [mul_comm] using image_mul_const_interval a b c
@[simp] lemma image_div_const_interval (a b c : k) : (λ x, x / a) '' [b, c] = [b / a, c / a] :=
image_mul_const_interval _ _ _
end linear_ordered_field
end set
|
cc1236c793de4537a7c080cbae8f8a24fed417c0 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/omega/find_ees.lean | 9529649b468465728b3ca498aa64667caee32cc0 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 5,567 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Seul Baek
-/
/-
A tactic for finding a sequence of equality
elimination rules for a given set of constraints.
-/
import tactic.omega.eq_elim
variables {α β : Type}
open tactic
namespace omega
/-- The state of equality elimination proof search. `eqs` is the list of
equality constraints, and each `t ∈ eqs` represents the constraint `0 = t`.
Similarly, `les` is the list of inequality constraints, and each `t ∈ eqs`
represents the constraint `0 < t`. `ees` is the sequence of equality
elimination steps that have been used so far to obtain the current set of
constraints. The list `ees` grows over time until `eqs` becomes empty. -/
@[derive inhabited]
structure ee_state :=
(eqs : list term)
(les : list term)
(ees : list ee)
@[reducible] meta def eqelim := state_t ee_state tactic
meta def abort {α : Type} : eqelim α := ⟨λ x, failed⟩
private meta def mk_eqelim_state
(eqs les : list term) : tactic ee_state :=
return (ee_state.mk eqs les [])
/-- Get the current list of equality constraints. -/
meta def get_eqs : eqelim (list term) := ee_state.eqs <$> get
/-- Get the current list of inequality constraints. -/
meta def get_les : eqelim (list term) := ee_state.les <$> get
/-- Get the current sequence of equality elimiation steps. -/
meta def get_ees : eqelim (list ee) := ee_state.ees <$> get
/-- Update the list of equality constraints. -/
meta def set_eqs (eqs : list term) : eqelim unit := modify $ λ s, {eqs := eqs, ..s}
/-- Update the list of inequality constraints. -/
meta def set_les (les : list term) : eqelim unit := modify $ λ s, {les := les, ..s}
/-- Update the sequence of equality elimiation steps. -/
meta def set_ees (es : list ee) : eqelim unit := modify $ λ s, {ees := es, ..s}
/-- Add a new step to the sequence of equality elimination steps. -/
meta def add_ee (e : ee) : eqelim unit := do
es ← get_ees, set_ees (es ++ [e])
/-- Return the first equality constraint in the current list of
equality constraints. The returned constraint is 'popped' and
no longer available in the state. -/
meta def head_eq : eqelim term :=
do eqs ← get_eqs,
match eqs with
| [] := abort
| (eq::eqs') := set_eqs eqs' >> pure eq
end
meta def run {α : Type} (eqs les : list term) (r : eqelim α) : tactic α :=
prod.fst <$> (mk_eqelim_state eqs les >>= r.run)
/-- If `t1` succeeds and returns a value, 'commit' to that choice and
run `t3` with the returned value as argument. Do not backtrack
to try `t2` even if `t3` fails. If `t1` fails outright, run `t2`. -/
meta def ee_commit (t1 : eqelim α) (t2 : eqelim β)
(t3 : α → eqelim β) : eqelim β :=
do x ← ((t1 >>= return ∘ some) <|> return none),
match x with
| none := t2
| (some a) := t3 a
end
local notation t1 `!>>=` t2 `;` t3 := ee_commit t1 t2 t3
private meta def of_tactic {α : Type} : tactic α → eqelim α := state_t.lift
/-- GCD of all elements of the list. -/
def gcd : list int → nat
| [] := 0
| (i::is) := nat.gcd i.nat_abs (gcd is)
/-- GCD of all coefficients in a term. -/
meta def get_gcd (t : term) : eqelim int :=
pure ↑(gcd t.snd)
/-- Divide a term by an integer if the integer divides
the constant component of the term. It is assumed that
the integer also divides all coefficients of the term. -/
meta def factor (i : int) (t : term) : eqelim term :=
if i ∣ t.fst
then add_ee (ee.factor i) >> pure (t.div i)
else abort
/-- If list has a nonzero element, return the minimum element
(by absolute value) with its index. Otherwise, return none. -/
meta def find_min_coeff_core : list int → eqelim (int × nat)
| [] := abort
| (i::is) := (do
(j,n) ← find_min_coeff_core is,
if i ≠ 0 ∧ i.nat_abs ≤ j.nat_abs
then pure (i,0)
else pure (j,n+1)) <|>
(if i = (0 : int) then abort else pure (i,0))
/-- Find and return the smallest coefficient (by absolute value) in a term,
along with the coefficient's variable index and the term itself.
If the coefficient is negative, negate both the coefficient and the term
before returning them. -/
meta def find_min_coeff (t : term) : eqelim (int × nat × term) :=
do (i,n) ← find_min_coeff_core t.snd,
if 0 < i
then pure (i,n,t)
else add_ee (ee.neg) >> pure (-i,n,t.neg)
/-- Find an appropriate equality elimination step for the
current state and apply it. -/
meta def elim_eq : eqelim unit := do
t ← head_eq,
i ← get_gcd t,
factor i t !>>= (set_eqs [] >> add_ee (ee.nondiv i)) ;
λ s, find_min_coeff s !>>= add_ee ee.drop ;
λ ⟨i, n, u⟩,
if i = 1
then do eqs ← get_eqs,
les ← get_les,
set_eqs (eqs.map (cancel n u)),
set_les (les.map (cancel n u)),
add_ee (ee.cancel n)
else let v : term := coeffs_reduce n u.fst u.snd in
let r : term := rhs n u.fst u.snd in
do eqs ← get_eqs,
les ← get_les,
set_eqs (v::eqs.map (subst n r)),
set_les (les.map (subst n r)),
add_ee (ee.reduce n),
elim_eq
/-- Find and return the sequence of steps for eliminating
all equality constraints in the current state. -/
meta def elim_eqs : eqelim (list ee) :=
elim_eq !>>= get_ees ; λ _, elim_eqs
/-- Given a linear constrain clause, return a list of steps for eliminating its equality
constraints. -/
meta def find_ees : clause → tactic (list ee)
| (eqs,les) := run eqs les elim_eqs
end omega
|
57fbcc78108a933d0b8a0bb444a97b312cbd996b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/sheaves/operations.lean | c4ce3bb1979d90797bc3979365de5f8fb7f9593a | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 4,089 | lean | /-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import algebra.category.Ring.instances
import algebra.category.Ring.filtered_colimits
import ring_theory.localization.basic
import topology.sheaves.stalks
/-!
# Operations on sheaves
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
## Main definition
- `submonoid_presheaf` : A subpresheaf with a submonoid structure on each of the components.
- `localization_presheaf` : The localization of a presheaf of commrings at a `submonoid_presheaf`.
- `total_quotient_presheaf` : The presheaf of total quotient rings.
-/
open_locale non_zero_divisors
open topological_space opposite category_theory
universes v u w
namespace Top
namespace presheaf
variables {X : Top.{w}} {C : Type u} [category.{v} C] [concrete_category C]
local attribute [instance] concrete_category.has_coe_to_sort
/-- A subpresheaf with a submonoid structure on each of the components. -/
structure submonoid_presheaf [∀ X : C, mul_one_class X]
[∀ (X Y : C), monoid_hom_class (X ⟶ Y) X Y] (F : X.presheaf C) :=
(obj : ∀ U, submonoid (F.obj U))
(map : ∀ {U V : (opens X)ᵒᵖ} (i : U ⟶ V), (obj U) ≤ (obj V).comap (F.map i))
variables {F : X.presheaf CommRing.{w}} (G : F.submonoid_presheaf)
/-- The localization of a presheaf of `CommRing`s with respect to a `submonoid_presheaf`. -/
protected noncomputable
def submonoid_presheaf.localization_presheaf :
X.presheaf CommRing :=
{ obj := λ U, CommRing.of $ localization (G.obj U),
map := λ U V i, CommRing.of_hom $ is_localization.map _ (F.map i) (G.map i),
map_id' := λ U, begin
apply is_localization.ring_hom_ext (G.obj U),
any_goals { dsimp, apply_instance },
refine (is_localization.map_comp _).trans _,
rw F.map_id,
refl,
end,
map_comp' := λ U V W i j, by { refine eq.trans _ (is_localization.map_comp_map _ _).symm,
ext, dsimp, congr, rw F.map_comp, refl } }
/-- The map into the localization presheaf. -/
def submonoid_presheaf.to_localization_presheaf :
F ⟶ G.localization_presheaf :=
{ app := λ U, CommRing.of_hom $ algebra_map (F.obj U) (localization $ G.obj U),
naturality' := λ U V i, (is_localization.map_comp (G.map i)).symm }
instance : epi G.to_localization_presheaf :=
@@nat_trans.epi_of_epi_app _ _ G.to_localization_presheaf (λ U, localization.epi' (G.obj U))
variable (F)
/-- Given a submonoid at each of the stalks, we may define a submonoid presheaf consisting of
sections whose restriction onto each stalk falls in the given submonoid. -/
@[simps] noncomputable
def submonoid_presheaf_of_stalk (S : ∀ x : X, submonoid (F.stalk x)) :
F.submonoid_presheaf :=
{ obj := λ U, ⨅ x : (unop U), submonoid.comap (F.germ x) (S x),
map := λ U V i, begin
intros s hs,
simp only [submonoid.mem_comap, submonoid.mem_infi] at ⊢ hs,
intro x,
change (F.map i.unop.op ≫ F.germ x) s ∈ _,
rw F.germ_res,
exact hs _,
end }
noncomputable
instance : inhabited F.submonoid_presheaf := ⟨F.submonoid_presheaf_of_stalk (λ _, ⊥)⟩
/-- The localization of a presheaf of `CommRing`s at locally non-zero-divisor sections. -/
noncomputable
def total_quotient_presheaf : X.presheaf CommRing.{w} :=
(F.submonoid_presheaf_of_stalk (λ x, (F.stalk x)⁰)).localization_presheaf
/-- The map into the presheaf of total quotient rings -/
@[derive epi] noncomputable
def to_total_quotient_presheaf : F ⟶ F.total_quotient_presheaf :=
submonoid_presheaf.to_localization_presheaf _
instance (F : X.sheaf CommRing.{w}) : mono F.presheaf.to_total_quotient_presheaf :=
begin
apply_with nat_trans.mono_of_mono_app { instances := ff },
intro U,
apply concrete_category.mono_of_injective,
apply is_localization.injective _,
swap 3, { exact localization.is_localization },
intros s hs t e,
apply section_ext F (unop U),
intro x,
rw map_zero,
apply submonoid.mem_infi.mp hs x,
rw [← map_mul, e, map_zero]
end
end presheaf
end Top
|
094af6862ec5b45dbed4d66f2c644379d186e57b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/finset/default.lean | 18a599317abb4e21ec36cde2142af58fde2173c0 | [] | 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 | 419 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.finset.basic
import Mathlib.data.finset.fold
import Mathlib.data.finset.intervals
import Mathlib.data.finset.lattice
import Mathlib.data.finset.nat_antidiagonal
import Mathlib.data.finset.pi
import Mathlib.data.finset.powerset
import Mathlib.data.finset.sort
import Mathlib.data.finset.preimage
import Mathlib.PostPort
namespace Mathlib
|
1d26acd3ea7bb538f7e57e0905edbe8be7b8be65 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/tactic/omega/int/main.lean | 636373b490d047ab7c10070abce29abbf03b0762 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 2,553 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
Main procedure for linear integer arithmetic.
-/
import tactic.omega.prove_unsats
import tactic.omega.int.dnf
open tactic
namespace omega
namespace int
local notation x ` =* ` y := form.eq x y
local notation x ` ≤* ` y := form.le x y
local notation `¬* ` p := form.not p
local notation p ` ∨* ` q := form.or p q
local notation p ` ∧* ` q := form.and p q
run_cmd mk_simp_attr `sugar
attribute [sugar]
not_le not_lt
int.lt_iff_add_one_le
or_false false_or
and_true true_and
ge gt mul_add add_mul
mul_comm sub_eq_add_neg
classical.imp_iff_not_or
classical.iff_iff_not_or_and_or_not
meta def desugar := `[try {simp only with sugar}]
lemma univ_close_of_unsat_clausify (m : nat) (p : form) :
clauses.unsat (dnf (¬* p)) → univ_close p (λ x, 0) m | h1 :=
begin
apply univ_close_of_valid,
apply valid_of_unsat_not,
apply unsat_of_clauses_unsat,
exact h1
end
/- Given a (p : form), return the expr of a (t : univ_close m p) -/
meta def prove_univ_close (m : nat) (p : form) : tactic expr :=
do x ← prove_unsats (dnf (¬*p)),
return `(univ_close_of_unsat_clausify %%`(m) %%`(p) %%x)
meta def to_preterm : expr → tactic preterm
| (expr.var k) := return (preterm.var 1 k)
| `(-%%(expr.var k)) := return (preterm.var (-1 : int) k)
| `(%%(expr.var k) * %%zx) :=
do z ← eval_expr int zx,
return (preterm.var z k)
| `(%%t1x + %%t2x) :=
do t1 ← to_preterm t1x,
t2 ← to_preterm t2x,
return (preterm.add t1 t2)
| zx :=
do z ← eval_expr int zx,
return (preterm.cst z)
meta def to_form_core : expr → tactic form
| `(%%tx1 = %%tx2) :=
do t1 ← to_preterm tx1,
t2 ← to_preterm tx2,
return (t1 =* t2)
| `(%%tx1 ≤ %%tx2) :=
do t1 ← to_preterm tx1,
t2 ← to_preterm tx2,
return (t1 ≤* t2)
| `(¬ %%px) := do p ← to_form_core px, return (¬* p)
| `(%%px ∨ %%qx) :=
do p ← to_form_core px,
q ← to_form_core qx,
return (p ∨* q)
| `(%%px ∧ %%qx) :=
do p ← to_form_core px,
q ← to_form_core qx,
return (p ∧* q)
| _ := failed
meta def to_form : nat → expr → tactic (form × nat)
| m `(_ → %%px) := to_form (m+1) px
| m x := do p ← to_form_core x, return (p,m)
meta def prove_lia : tactic expr :=
do (p,m) ← target >>= to_form 0,
prove_univ_close m p
end int
end omega
open omega.int
meta def omega_int : tactic unit :=
desugar >> prove_lia >>= apply >> skip
|
48c0e0f9a1937cf476b883fe75b15422a4b1c499 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/category/Semigroup/basic.lean | 7e8666e59eda3add7cc71ce9523dabdd04a8661f | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 7,401 | lean | /-
Copyright (c) 2021 Julian Kuelshammer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Julian Kuelshammer
-/
import algebra.pempty_instances
import algebra.hom.equiv.basic
import category_theory.concrete_category.bundled_hom
import category_theory.functor.reflects_isomorphisms
import category_theory.elementwise
/-!
# Category instances for has_mul, has_add, semigroup and add_semigroup
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We introduce the bundled categories:
* `Magma`
* `AddMagma`
* `Semigroup`
* `AddSemigroup`
along with the relevant forgetful functors between them.
This closely follows `algebra.category.Mon.basic`.
## TODO
* Limits in these categories
* free/forgetful adjunctions
-/
universes u v
open category_theory
/-- The category of magmas and magma morphisms. -/
@[to_additive AddMagma]
def Magma : Type (u+1) := bundled has_mul
/-- The category of additive magmas and additive magma morphisms. -/
add_decl_doc AddMagma
namespace Magma
@[to_additive]
instance bundled_hom : bundled_hom @mul_hom :=
⟨@mul_hom.to_fun, @mul_hom.id, @mul_hom.comp, @mul_hom.coe_inj⟩
attribute [derive [large_category, concrete_category]] Magma
attribute [to_additive] Magma.large_category Magma.concrete_category
@[to_additive] instance : has_coe_to_sort Magma Type* := bundled.has_coe_to_sort
/-- Construct a bundled `Magma` from the underlying type and typeclass. -/
@[to_additive]
def of (M : Type u) [has_mul M] : Magma := bundled.of M
/-- Construct a bundled `AddMagma` from the underlying type and typeclass. -/
add_decl_doc AddMagma.of
/-- Typecheck a `mul_hom` as a morphism in `Magma`. -/
@[to_additive] def of_hom {X Y : Type u} [has_mul X] [has_mul Y] (f : X →ₙ* Y) :
of X ⟶ of Y := f
/-- Typecheck a `add_hom` as a morphism in `AddMagma`. -/
add_decl_doc AddMagma.of_hom
@[simp, to_additive] lemma of_hom_apply {X Y : Type u} [has_mul X] [has_mul Y] (f : X →ₙ* Y)
(x : X) : of_hom f x = f x := rfl
@[to_additive]
instance : inhabited Magma := ⟨Magma.of pempty⟩
@[to_additive]
instance (M : Magma) : has_mul M := M.str
@[simp, to_additive] lemma coe_of (R : Type u) [has_mul R] : (Magma.of R : Type u) = R := rfl
end Magma
/-- The category of semigroups and semigroup morphisms. -/
@[to_additive AddSemigroup]
def Semigroup : Type (u+1) := bundled semigroup
/-- The category of additive semigroups and semigroup morphisms. -/
add_decl_doc AddSemigroup
namespace Semigroup
@[to_additive]
instance : bundled_hom.parent_projection semigroup.to_has_mul := ⟨⟩
attribute [derive [large_category, concrete_category]] Semigroup
attribute [to_additive] Semigroup.large_category Semigroup.concrete_category
@[to_additive] instance : has_coe_to_sort Semigroup Type* := bundled.has_coe_to_sort
/-- Construct a bundled `Semigroup` from the underlying type and typeclass. -/
@[to_additive]
def of (M : Type u) [semigroup M] : Semigroup := bundled.of M
/-- Construct a bundled `AddSemigroup` from the underlying type and typeclass. -/
add_decl_doc AddSemigroup.of
/-- Typecheck a `mul_hom` as a morphism in `Semigroup`. -/
@[to_additive] def of_hom {X Y : Type u} [semigroup X] [semigroup Y] (f : X →ₙ* Y) :
of X ⟶ of Y := f
/-- Typecheck a `add_hom` as a morphism in `AddSemigroup`. -/
add_decl_doc AddSemigroup.of_hom
@[simp, to_additive] lemma of_hom_apply {X Y : Type u} [semigroup X] [semigroup Y] (f : X →ₙ* Y)
(x : X) : of_hom f x = f x := rfl
@[to_additive]
instance : inhabited Semigroup := ⟨Semigroup.of pempty⟩
@[to_additive]
instance (M : Semigroup) : semigroup M := M.str
@[simp, to_additive] lemma coe_of (R : Type u) [semigroup R] : (Semigroup.of R : Type u) = R := rfl
@[to_additive has_forget_to_AddMagma]
instance has_forget_to_Magma : has_forget₂ Semigroup Magma := bundled_hom.forget₂ _ _
end Semigroup
variables {X Y : Type u}
section
variables [has_mul X] [has_mul Y]
/-- Build an isomorphism in the category `Magma` from a `mul_equiv` between `has_mul`s. -/
@[to_additive add_equiv.to_AddMagma_iso "Build an isomorphism in the category `AddMagma` from
an `add_equiv` between `has_add`s.", simps]
def mul_equiv.to_Magma_iso (e : X ≃* Y) : Magma.of X ≅ Magma.of Y :=
{ hom := e.to_mul_hom,
inv := e.symm.to_mul_hom }
end
section
variables [semigroup X] [semigroup Y]
/-- Build an isomorphism in the category `Semigroup` from a `mul_equiv` between `semigroup`s. -/
@[to_additive add_equiv.to_AddSemigroup_iso "Build an isomorphism in the category
`AddSemigroup` from an `add_equiv` between `add_semigroup`s.", simps]
def mul_equiv.to_Semigroup_iso (e : X ≃* Y) : Semigroup.of X ≅ Semigroup.of Y :=
{ hom := e.to_mul_hom,
inv := e.symm.to_mul_hom }
end
namespace category_theory.iso
/-- Build a `mul_equiv` from an isomorphism in the category `Magma`. -/
@[to_additive AddMagma_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category
`AddMagma`."]
def Magma_iso_to_mul_equiv {X Y : Magma} (i : X ≅ Y) : X ≃* Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := λ x, by simp,
right_inv := λ y, by simp,
map_mul' := by simp }
/-- Build a `mul_equiv` from an isomorphism in the category `Semigroup`. -/
@[to_additive "Build an `add_equiv` from an isomorphism in the category
`AddSemigroup`."]
def Semigroup_iso_to_mul_equiv {X Y : Semigroup} (i : X ≅ Y) : X ≃* Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := λ x, by simp,
right_inv := λ y, by simp,
map_mul' := by simp }
end category_theory.iso
/-- multiplicative equivalences between `has_mul`s are the same as (isomorphic to) isomorphisms
in `Magma` -/
@[to_additive add_equiv_iso_AddMagma_iso "additive equivalences between `has_add`s are the same
as (isomorphic to) isomorphisms in `AddMagma`"]
def mul_equiv_iso_Magma_iso {X Y : Type u} [has_mul X] [has_mul Y] :
(X ≃* Y) ≅ (Magma.of X ≅ Magma.of Y) :=
{ hom := λ e, e.to_Magma_iso,
inv := λ i, i.Magma_iso_to_mul_equiv }
/-- multiplicative equivalences between `semigroup`s are the same as (isomorphic to) isomorphisms
in `Semigroup` -/
@[to_additive add_equiv_iso_AddSemigroup_iso "additive equivalences between `add_semigroup`s are
the same as (isomorphic to) isomorphisms in `AddSemigroup`"]
def mul_equiv_iso_Semigroup_iso {X Y : Type u} [semigroup X] [semigroup Y] :
(X ≃* Y) ≅ (Semigroup.of X ≅ Semigroup.of Y) :=
{ hom := λ e, e.to_Semigroup_iso,
inv := λ i, i.Semigroup_iso_to_mul_equiv }
@[to_additive]
instance Magma.forget_reflects_isos : reflects_isomorphisms (forget Magma.{u}) :=
{ reflects := λ X Y f _,
begin
resetI,
let i := as_iso ((forget Magma).map f),
let e : X ≃* Y := { ..f, ..i.to_equiv },
exact ⟨(is_iso.of_iso e.to_Magma_iso).1⟩,
end }
@[to_additive]
instance Semigroup.forget_reflects_isos : reflects_isomorphisms (forget Semigroup.{u}) :=
{ reflects := λ X Y f _,
begin
resetI,
let i := as_iso ((forget Semigroup).map f),
let e : X ≃* Y := { ..f, ..i.to_equiv },
exact ⟨(is_iso.of_iso e.to_Semigroup_iso).1⟩,
end }
/-!
Once we've shown that the forgetful functors to type reflect isomorphisms,
we automatically obtain that the `forget₂` functors between our concrete categories
reflect isomorphisms.
-/
example : reflects_isomorphisms (forget₂ Semigroup Magma) := by apply_instance
|
e01d82fa4535c597fdf143c9bae6dda83b625af3 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /hott/algebra/binary.hlean | 18a5525cd48a502ef6c8387382c3f0a0b416da61 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 4,558 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad
General properties of binary operations.
-/
open eq.ops function
namespace binary
section
variable {A : Type}
variables (op₁ : A → A → A) (inv : A → A) (one : A)
local notation a * b := op₁ a b
local notation a ⁻¹ := inv a
definition commutative := Πa b, a * b = b * a
definition associative := Πa b c, (a * b) * c = a * (b * c)
definition left_identity := Πa, one * a = a
definition right_identity := Πa, a * one = a
definition left_inverse := Πa, a⁻¹ * a = one
definition right_inverse := Πa, a * a⁻¹ = one
definition left_cancelative := Πa b c, a * b = a * c → b = c
definition right_cancelative := Πa b c, a * b = c * b → a = c
definition inv_op_cancel_left := Πa b, a⁻¹ * (a * b) = b
definition op_inv_cancel_left := Πa b, a * (a⁻¹ * b) = b
definition inv_op_cancel_right := Πa b, a * b⁻¹ * b = a
definition op_inv_cancel_right := Πa b, a * b * b⁻¹ = a
variable (op₂ : A → A → A)
local notation a + b := op₂ a b
definition left_distributive := Πa b c, a * (b + c) = a * b + a * c
definition right_distributive := Πa b c, (a + b) * c = a * c + b * c
definition right_commutative {B : Type} (f : B → A → B) := Π b a₁ a₂, f (f b a₁) a₂ = f (f b a₂) a₁
definition left_commutative {B : Type} (f : A → B → B) := Π a₁ a₂ b, f a₁ (f a₂ b) = f a₂ (f a₁ b)
end
section
variable {A : Type}
variable {f : A → A → A}
variable H_comm : commutative f
variable H_assoc : associative f
local infixl `*` := f
theorem left_comm : left_commutative f :=
take a b c, calc
a*(b*c) = (a*b)*c : H_assoc
... = (b*a)*c : H_comm
... = b*(a*c) : H_assoc
theorem right_comm : right_commutative f :=
take a b c, calc
(a*b)*c = a*(b*c) : H_assoc
... = a*(c*b) : H_comm
... = (a*c)*b : H_assoc
theorem comm4 (a b c d : A) : a*b*(c*d) = a*c*(b*d) :=
calc
a*b*(c*d) = a*b*c*d : H_assoc
... = a*c*b*d : right_comm H_comm H_assoc
... = a*c*(b*d) : H_assoc
end
section
variable {A : Type}
variable {f : A → A → A}
variable H_assoc : associative f
local infixl `*` := f
theorem assoc4helper (a b c d) : (a*b)*(c*d) = a*((b*c)*d) :=
calc
(a*b)*(c*d) = a*(b*(c*d)) : H_assoc
... = a*((b*c)*d) : H_assoc
end
definition right_commutative_compose_right
{A B : Type} (f : A → A → A) (g : B → A) (rcomm : right_commutative f) : right_commutative (compose_right f g) :=
λ a b₁ b₂, !rcomm
definition left_commutative_compose_left
{A B : Type} (f : A → A → A) (g : B → A) (lcomm : left_commutative f) : left_commutative (compose_left f g) :=
λ a b₁ b₂, !lcomm
end binary
open eq
namespace is_equiv
definition inv_preserve_binary {A B : Type} (f : A → B) [H : is_equiv f]
(mA : A → A → A) (mB : B → B → B) (H : Π(a a' : A), mB (f a) (f a') = f (mA a a'))
(b b' : B) : f⁻¹ (mB b b') = mA (f⁻¹ b) (f⁻¹ b') :=
begin
have H2 : f⁻¹ (mB (f (f⁻¹ b)) (f (f⁻¹ b'))) = f⁻¹ (f (mA (f⁻¹ b) (f⁻¹ b'))), from ap f⁻¹ !H,
rewrite [+right_inv f at H2,left_inv f at H2,▸* at H2,H2]
end
definition preserve_binary_of_inv_preserve {A B : Type} (f : A → B) [H : is_equiv f]
(mA : A → A → A) (mB : B → B → B) (H : Π(b b' : B), mA (f⁻¹ b) (f⁻¹ b') = f⁻¹ (mB b b'))
(a a' : A) : f (mA a a') = mB (f a) (f a') :=
begin
have H2 : f (mA (f⁻¹ (f a)) (f⁻¹ (f a'))) = f (f⁻¹ (mB (f a) (f a'))), from ap f !H,
rewrite [right_inv f at H2,+left_inv f at H2,▸* at H2,H2]
end
end is_equiv
namespace equiv
open is_equiv
definition inv_preserve_binary {A B : Type} (f : A ≃ B)
(mA : A → A → A) (mB : B → B → B) (H : Π(a a' : A), mB (f a) (f a') = f (mA a a'))
(b b' : B) : f⁻¹ (mB b b') = mA (f⁻¹ b) (f⁻¹ b') :=
inv_preserve_binary f mA mB H b b'
definition preserve_binary_of_inv_preserve {A B : Type} (f : A ≃ B)
(mA : A → A → A) (mB : B → B → B) (H : Π(b b' : B), mA (f⁻¹ b) (f⁻¹ b') = f⁻¹ (mB b b'))
(a a' : A) : f (mA a a') = mB (f a) (f a') :=
preserve_binary_of_inv_preserve f mA mB H a a'
end equiv
|
f9b6aeb40cdeafade98f8a971855a4498eb666ee | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/tactic/core.lean | ce316a71ae8275fdff65cb37152cc8191e4d883e | [
"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 | 87,314 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek
-/
import data.dlist.basic
import control.basic
import meta.expr
import meta.rb_map
import data.bool
import tactic.lean_core_docs
import tactic.interactive_expr
import tactic.fix_by_cases
universe variable u
attribute [derive [has_reflect, decidable_eq]] tactic.transparency
instance : has_lt pos :=
{ lt := λ x y, (x.line, x.column) < (y.line, y.column) }
namespace expr
open tactic
/-- Given an expr `α` representing a type with numeral structure,
`of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (α : expr) : ℕ → tactic expr :=
nat.binary_rec
(tactic.mk_mapp ``has_zero.zero [some α, none])
(λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else
do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])
/-- Given an expr `α` representing a type with numeral structure,
`of_int α n` creates the `α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (α : expr) : ℤ → tactic expr
| (n : ℕ) := expr.of_nat α n
| -[1+ n] := do
e ← expr.of_nat α (n+1),
tactic.mk_app ``has_neg.neg [e]
/-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local
constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/
meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=
args.mfoldr (λarg i:expr, do
t ← infer_type arg,
sort l ← infer_type t,
return $ if arg.occurs i ∨ l ≠ level.zero
then (const `Exists [l] : expr) t (i.lambdas [arg])
else (const `and [] : expr) t i)
inner
/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/
meta def traverse {m : Type → Type u} [applicative m]
{elab elab' : bool} (f : expr elab → m (expr elab')) :
expr elab → m (expr elab')
| (var v) := pure $ var v
| (sort l) := pure $ sort l
| (const n ls) := pure $ const n ls
| (mvar n n' e) := mvar n n' <$> f e
| (local_const n n' bi e) := local_const n n' bi <$> f e
| (app e₀ e₁) := app <$> f e₀ <*> f e₁
| (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁
| (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁
| (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂
| (macro mac es) := macro mac <$> list.traverse f es
/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,
with initial value `a`. -/
meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α
| x e := prod.snd <$> (state_t.run (e.traverse $ λ e',
(get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _)
/-- `kreplace e old new` replaces all occurrences of the expression `old` in `e`
with `new`. The occurrences of `old` in `e` are determined using keyed matching
with transparency `md`; see `kabstract` for details. If `unify` is true,
we may assign metavariables in `e` as we match subterms of `e` against `old`. -/
meta def kreplace (e old new : expr) (md := semireducible) (unify := tt)
: tactic expr := do
e ← kabstract e old md unify,
pure $ e.instantiate_var new
end expr
namespace interaction_monad
open result
variables {σ : Type} {α : Type u}
/-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.read` in core.
meta def get_state : interaction_monad σ σ :=
λ state, success state state
/-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.write` in core.
meta def set_state (state : σ) : interaction_monad σ unit :=
λ _, success () state
/--
`run_with_state state tac` applies `tac` to the given state `state` and returns the result,
subsequently restoring the original state.
If `tac` fails, then `run_with_state` does too.
-/
meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α :=
λ s, match tac state with
| success val _ := success val s
| exception fn pos _ := exception fn pos s
end
end interaction_monad
namespace format
/-- `join' [a,b,c]` produces the format object `abc`.
It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/
meta def join' (xs : list format) : format :=
xs.foldl compose nil
/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,
where `.` represents `format.join`. -/
meta def intercalate (x : format) : list format → format :=
join' ∘ list.intersperse x
/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`
the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`
each line break is decided independently -/
meta def soft_break : format :=
group line
end format
section format
open format
/-- format a `list` by separating elements with `soft_break` instead of `line` -/
meta def list.to_line_wrap_format {α : Type u} [has_to_format α] : list α → format
| [] := to_fmt "[]"
| xs := to_fmt "[" ++ group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) ++ to_fmt "]"
end format
namespace tactic
open function
/-- Private work function for `add_local_consts_as_local_hyps`: given
`mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local
hypothesis created as a result and `(var :: rest) : list expr` of more local variables we
examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the
back of the queue and recurse. If it does not, then we perform replacements inside the type of
`var` using the `mappings`, create a new associate local hypothesis, add this to the list of
mappings, and recurse. We are done once all local hypotheses have been processed.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
private meta def add_local_consts_as_local_hyps_aux
: list (expr × expr) → list expr → tactic (list (expr × expr))
| mappings [] := return mappings
| mappings (var :: rest) := do
/- Determine if `var` contains any local variables in the lift `rest`. -/
let is_dependent := var.local_type.fold ff $ λ e n b,
if b then b else e ∈ rest,
/- If so, then skip it---add it to the end of the variable queue. -/
if is_dependent then
add_local_consts_as_local_hyps_aux mappings (rest ++ [var])
else do
/- Otherwise, replace all of the local constants referenced by the type of `var` with the
respective new corresponding local hypotheses as recorded in the list `mappings`. -/
let new_type := var.local_type.replace_subexprs mappings,
/- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/
hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type),
/- Process the next variable in the queue, with the mapping list updated to include the local
hypothesis which we just created. -/
add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest
/-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the
tactic state. This is harder than it sounds, since the list of local constants which we have
been passed can have dependencies between their types.
For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly
add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as
a new local hypothesis, not the old local constant `n` with the same name. Of course, these
dependencies can be nested arbitrarily deep.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) :=
/- The `list.reverse` below is a performance optimisation since the list of available variables
reported by the system is often mostly the reverse of the order in which they are dependent. -/
add_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup
/-- `mk_local_pisn e n` instantiates the first `n` variables of a pi expression `e`,
and returns the new local constants along with the instantiated expression. Fails if `e` does
not begin with at least `n` pi binders. -/
meta def mk_local_pisn : expr → nat → tactic (list expr × expr)
| (expr.pi n bi d b) (c + 1) := do
p ← mk_local' n bi d,
(ps, r) ← mk_local_pisn (b.instantiate_var p) c,
return ((p :: ps), r)
| e 0 := return ([], e)
| _ _ := failed
-- TODO: move to `declaration` namespace in `meta/expr.lean`
/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named
`ls`, type `t`, and body `e`. -/
meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=
declaration.thm n ls t (task.pure e)
/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this
to the environment as a theorem with name `n` and universe parameters `ls`. -/
meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) :
tactic expr :=
do ((), body) ← solve_aux type tac,
body ← instantiate_mvars body,
add_decl $ mk_theorem n ls type body,
return $ expr.const n $ ls.map level.param
/-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`.
This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare
situations the latter will fail but the former will succeed. -/
meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α :=
mk_app ``id [e] >>= eval_expr α
/-- `mk_fresh_name` returns identifiers starting with underscores,
which are not legal when emitted by tactic programs. `mk_user_fresh_name`
turns the useful source of random names provided by `mk_fresh_name` into
names which are usable by tactic programs.
The returned name has four components which are all strings. -/
meta def mk_user_fresh_name : tactic name :=
do nm ← mk_fresh_name,
return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__
/-- `has_attribute' attr_name decl_name` checks
whether `decl_name` exists and has attribute `attr_name`. -/
meta def has_attribute' (attr_name decl_name : name) : tactic bool :=
succeeds (has_attribute attr_name decl_name)
/-- Checks whether the name is a simp lemma -/
meta def is_simp_lemma : name → tactic bool :=
has_attribute' `simp
/-- Checks whether the name is an instance. -/
meta def is_instance : name → tactic bool :=
has_attribute' `instance
/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.
Covers all declarations from the current file. -/
meta def local_decls : tactic (name_map declaration) :=
do e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s, if environment.in_current_file' e d.to_name
then s.insert d.to_name d else s),
pure xs
/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/
meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n :=
let nm' := nm.append_suffix ("_" ++ to_string n) in
if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm'
/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it
returns that, otherwise it tries `nm_2`, `nm_3`, ... -/
meta def get_unused_decl_name (nm : name) : tactic name :=
get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm
/--
Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type`
but with universe params updated to match the fresh universe metavariables in `e`.
This should have the same effect as just
```lean
do e ← mk_const d.to_name,
t ← infer_type e,
return (e, t)
```
but is hopefully faster.
-/
meta def decl_mk_const (d : declaration) : tactic (expr × expr) :=
do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ,
let e : expr := expr.const d.to_name (prod.snd <$> subst),
return (e, d.type.instantiate_univ_params subst)
/--
Replace every universe metavariable in an expression with a universe parameter.
(This is useful when making new declarations.)
-/
meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr :=
do
e.list_univ_meta_vars.enum.mmap (λ n, do
let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)),
unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))),
instantiate_mvars e
/-- `mk_local n` creates a dummy local variable with name `n`.
The type of this local constant is a constant with name `n`, so it is very unlikely to be
a meaningful expression. -/
meta def mk_local (n : name) : expr :=
expr.local_const n n binder_info.default (expr.const n [])
/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with pi binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``pis [a, b] `(f a b)`` will return the expression
`Π (a : Ta) (b : Tb), f a b`. -/
meta def pis : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← pis es f,
pure $ expr.pi pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with lambda binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``lambdas [a, b] `(f a b)`` will return the expression
`λ (a : Ta) (b : Tb), f a b`. -/
meta def lambdas : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← lambdas es f,
pure $ expr.lam pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,
`y : ty x` and `z : tz x y`, creates an expression of sigma type:
`⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`.
-/
meta def mk_psigma : list expr → tactic expr
| [] := mk_const ``punit
| [x@(expr.local_const _ _ _ _)] := pure x
| (x@(expr.local_const _ _ _ _) :: xs) :=
do y ← mk_psigma xs,
α ← infer_type x,
β ← infer_type y,
t ← lambdas [x] β >>= instantiate_mvars,
r ← mk_mapp ``psigma.mk [α,t],
pure $ r x y
| _ := fail "mk_psigma expects a list of local constants"
/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`
times and uses `ns` to name the resulting variables. Returns a triple: list of new variables,
remaining term and unused variable names.
-/
meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name)
| 0 e hs ns := return (hs.reverse, e, ns)
| (n + 1) e hs ns := do
t ← infer_type e,
if t.is_app_of `eq then return (hs.reverse, e, ns)
else do
[(_, [h, h'], _)] ← cases_core e (ns.take 1),
elim_gen_prod n h' (h :: hs) (ns.drop 1)
private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr)
| 0 e hs := return (hs, e)
| (n + 1) e hs := do
[(_, [h], _), (_, [h'], _)] ← induction e [],
swap,
elim_gen_sum_aux n h' (h::hs)
/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose
type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`.
-/
meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do
(hs, h') ← elim_gen_sum_aux n e [],
gs ← get_goals,
set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),
return $ hs.reverse ++ [h']
/-- Given `elab_def`, a tactic to solve the current goal,
`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it
to close the goal. If `trusted` is false, it will be a meta definition. -/
meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=
do cxt ← list.map expr.to_implicit_local_const <$> local_context,
t ← target,
(eqns,d) ← solve_aux t elab_def,
d ← instantiate_mvars d,
t' ← pis cxt t,
d' ← lambdas cxt d,
let univ := t'.collect_univ_params,
add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,
applyc n
/-- Attempts to close the goal with `dec_trivial`. -/
meta def exact_dec_trivial : tactic unit := `[exact dec_trivial]
/-- Runs a tactic for a result, reverting the state after completion. -/
meta def retrieve {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
result.exception
/-- Repeat a tactic at least once, calling it recursively on all subgoals,
until it fails. This tactic fails if the first invocation fails. -/
meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t
/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and
at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/
meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit
| 0 0 t := skip
| 0 (n+1) t := try (t >> iterate_range 0 n t)
| (m+1) n t := t >> iterate_range m (n-1) t
/--
Given a tactic `tac` that takes an expression
and returns a new expression and a proof of equality,
use that tactic to change the type of the hypotheses listed in `hs`,
as well as the goal if `tgt = tt`.
Returns `tt` if any types were successfully changed.
-/
meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) :
tactic bool :=
do to_remove ← hs.mfilter $ λ h, do {
h_type ← infer_type h,
succeeds $ do
(new_h_type, pr) ← tac h_type,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact },
goal_simplified ← succeeds $ do {
guard tgt,
(new_t, pr) ← target >>= tac,
replace_target new_t pr },
to_remove.mmap' (λ h, try (clear h)),
return (¬ to_remove.empty ∨ goal_simplified)
/-- `revert_after e` reverts all local constants after local constant `e`. -/
meta def revert_after (e : expr) : tactic ℕ := do
l ← local_context,
[pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}",
let l := l.drop pos.succ, -- all local hypotheses after `e`
revert_lst l
/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant
with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.
`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the
goal, in which case it just calls `assert`.
In contrast to `generalize` it already introduces the generalized variable. -/
meta def generalize' (e : expr) (n : name) : tactic expr :=
(generalize e n >> intro1) <|> note n none e
/--
`intron_no_renames n` calls `intro` `n` times, using the pretty-printing name
provided by the binder to name the new local constant.
Unlike `intron`, it does not rename introduced constants if the names shadow existing constants.
-/
meta def intron_no_renames : ℕ → tactic unit
| 0 := pure ()
| (n+1) := do
expr.pi pp_n _ _ _ ← target,
intro pp_n,
intron_no_renames n
/-!
### Various tactics related to local definitions (local constants of the form `x : α := t`)
We call `t` the value of `x`.
-/
/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined
locally using a `let` expression. Otherwise it fails. -/
meta def local_def_value (e : expr) : tactic expr :=
pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad.
tactic.unsafe.type_context.run $ do
lctx <- tactic.unsafe.type_context.get_local_context,
some ldecl <- return $ lctx.get_local_decl e.local_uniq_name |
tactic.unsafe.type_context.fail format!"No such hypothesis {s}.",
some let_val <- return ldecl.value |
tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.",
return let_val
/-- `revert_deps e` reverts all the hypotheses that depend on one of the local
constants `e`, including the local definitions that have `e` in their definition.
This fixes a bug in `revert_kdeps` that does not revert local definitions for which `e` only
appears in the definition. -/
/- We cannot implement it as `revert e >> intro1`, because that would change the local constant in
the context. -/
meta def revert_deps (e : expr) : tactic ℕ := do
n ← revert_kdeps e,
l ← local_context,
[pos] ← return $ l.indexes_of e,
let l := l.drop pos.succ, -- local hypotheses after `e`
ls ← l.mfilter $ λ e', try_core (local_def_value e') >>= λ o, return $ o.elim ff $ λ e'',
e''.has_local_constant e,
n' ← revert_lst ls,
return $ n + n'
/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form
`e : α := t`) and otherwise fails. -/
meta def is_local_def (e : expr) : tactic unit :=
retrieve $ do revert e, expr.elet _ _ _ _ ← target, skip
/-- `clear_value e` clears the body of the local definition `e`, changing it into a regular
hypothesis. A hypothesis `e : α := t` is changed to `e : α`.
This tactic is called `clearbody` in Coq. -/
meta def clear_value (e : expr) : tactic unit := do
n ← revert_after e,
is_local_def e <|>
pp e >>= λ s, fail format!"Cannot clear the body of {s}. It is not a local definition.",
let nm := e.local_pp_name,
(generalize' e nm >> clear e) <|>
fail format!"Cannot clear the body of {nm}. The resulting goal is not type correct.",
intron n
/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,
`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting
expression and a proof of equality. -/
meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) :
tactic (expr × expr) :=
prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg
/-- Caches unary type classes on a type `α : Type.{univ}`. -/
meta structure instance_cache :=
(α : expr)
(univ : level)
(inst : name_map expr)
/-- Creates an `instance_cache` for the type `α`. -/
meta def mk_instance_cache (α : expr) : tactic instance_cache :=
do u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
return ⟨α, u, mk_name_map⟩
namespace instance_cache
/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of
`n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance
via type class resolution, and updates the cache. -/
meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) :=
match c.inst.find n with
| some i := return (c, i)
| none := do e ← mk_app n [c.α] >>= mk_instance,
return (⟨c.α, c.univ, c.inst.insert n e⟩, e)
end
open expr
/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,
`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/
meta def append_typeclasses : expr → instance_cache → list expr →
tactic (instance_cache × list expr)
| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=
do (c, p) ← c.get n, return (c, p :: l)
| _ c l := return (c, l)
/-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`.
-/
meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) :=
do d ← get_decl n,
(c, l) ← append_typeclasses d.type.binding_body c l,
return (c, (expr.const n [c.univ]).mk_app (c.α :: l))
/-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) :=
if n = 0 then c.mk_app ``has_zero.zero [] else do
(c, ai) ← c.get ``has_add,
(c, oi) ← c.get ``has_one,
(c, one) ← c.mk_app ``has_one.one [],
return (c, n.binary_rec one $ λ b n e,
if n = 0 then one else
cond b
((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e])
((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e]))
/-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr)
| (n : ℕ) := c.of_nat n
| -[1+ n] := do
(c, e) ← c.of_nat (n+1),
c.mk_app ``has_neg.neg [e]
end instance_cache
private meta def get_expl_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_expl_pi_arity_aux new_b,
if bi = binder_info.default then
return (r + 1)
else
return r
| e := return 0
/-- Compute the arity of explicit arguments of the given (Pi-)type. -/
meta def get_expl_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_expl_pi_arity_aux
/-- Compute the arity of explicit arguments of the given function. -/
meta def get_expl_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_expl_pi_arity
/-- Auxilliary defintion for `get_pi_binders`. -/
meta def get_pi_binders_aux : list binder → expr → tactic (list binder × expr)
| es (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
let new_b := expr.instantiate_var b l,
get_pi_binders_aux (⟨n, bi, d⟩::es) new_b
| es e := return (es, e)
/-- Get the binders and target of a pi-type. Instantiates bound variables by
local constants. Cf. `pi_binders` in `meta.expr` (which produces open terms).
See also `mk_local_pis` in `init.core.tactic` which does almost the same. -/
meta def get_pi_binders : expr → tactic (list binder × expr) | e :=
do (es, e) ← get_pi_binders_aux [] e, return (es.reverse, e)
/-- Auxilliary definition for `get_pi_binders_dep`. -/
meta def get_pi_binders_dep_aux : ℕ → expr → tactic (list (ℕ × binder) × expr)
| n (expr.pi nm bi d b) :=
do l ← mk_local' nm bi d,
(ls, r) ← get_pi_binders_dep_aux (n+1) (expr.instantiate_var b l),
return (if b.has_var then ls else (n, ⟨nm, bi, d⟩)::ls, r)
| n e := return ([], e)
/-- A variant of `get_pi_binders` that only returns the binders that do not occur in later
arguments or in the target. Also returns the argument position of each returned binder. -/
meta def get_pi_binders_dep : expr → tactic (list (ℕ × binder) × expr) :=
get_pi_binders_dep_aux 0
/-- A variation on `assert` where a (possibly incomplete)
proof of the assertion is provided as a parameter.
``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and
use `tac` to (partially) construct a proof for it. `gs` is the
list of remaining goals in the proof of `h`.
The benefits over assert are:
- unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`;
- when `tac` does not complete the proof of `h`, returning the list
of goals allows one to write a tactic using `h` and with the confidence
that a proof will not boil over to goals left over from the proof of `h`,
unlike what would be the case when using `tactic.swap`.
-/
meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) :
tactic (expr × list expr) :=
focus1 $
do h' ← assert h p,
[g₀,g₁] ← get_goals,
set_goals [g₀], tac₀,
gs ← get_goals,
set_goals [g₁],
return (h', gs)
/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/
meta def var_names : expr → list name
| (expr.pi n _ _ b) := n :: var_names b
| _ := []
/-- When `struct_n` is the name of a structure type,
`subobject_names struct_n` returns two lists of names `(instances, fields)`.
The names in `instances` are the projections from `struct_n` to the structures that it extends
(assuming it was defined with `old_structure_cmd false`).
The names in `fields` are the standard fields of `struct_n`. -/
meta def subobject_names (struct_n : name) : tactic (list name × list name) :=
do env ← get_env,
[c] ← pure $ env.constructors_of struct_n | fail "too many constructors",
vs ← var_names <$> (mk_const c >>= infer_type),
fields ← env.structure_fields struct_n,
return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs)
private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n :=
do (so,fs) ← subobject_names struct_n,
ts ← so.mmap (λ n, do
(_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= mk_local_pis,
expanded_field_list' $ e.get_app_fn.const_name),
return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)
open functor function
/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure
named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name
of the projection is `prefix.name`. -/
meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) :=
dlist.to_list <$> expanded_field_list' struct_n
/--
Return a list of all type classes which can be instantiated
for the given expression.
-/
meta def get_classes (e : expr) : tactic (list name) :=
attribute.get_instances `class >>= list.mfilter (λ n,
succeeds $ mk_app n [e] >>= mk_instance)
/--
Finds an instance of an implication `cond → tgt`.
Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention `e`.
The local constant `e` is added as an hypothesis to the tactic state, but should not be used, since
it has been "proven" by a metavariable.
-/
meta def mk_conditional_instance (cond tgt : expr) : tactic (expr × expr) := do
f ← mk_meta_var cond,
e ← assertv `c cond f, swap,
reset_instance_cache,
inst ← mk_instance tgt,
return (e, inst)
open nat
/-- Create a list of `n` fresh metavariables. -/
meta def mk_mvar_list : ℕ → tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n
/-- Returns the only goal, or fails if there isn't just one goal. -/
meta def get_goal : tactic expr :=
do gs ← get_goals,
match gs with
| [a] := return a
| [] := fail "there are no goals"
| _ := fail "there are too many goals"
end
/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,
or until it fails. Always succeeds. -/
meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip
/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first
goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on
current goal. -/
meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)
/-- This makes sure that the execution of the tactic does not change the tactic state.
This can be helpful while using rewrite, apply, or expr munging.
Remember to instantiate your metavariables before you're done! -/
meta def lock_tactic_state {α} (t : tactic α) : tactic α
| s := match t s with
| result.success a s' := result.success a s
| result.exception msg pos s' := result.exception msg pos s
end
/--
`apply_list l`, for `l : list (tactic expr)`,
tries to apply the lemmas generated by the tactics in `l` on the first goal, and
fail if none succeeds.
-/
meta def apply_list_expr (opt : apply_cfg) : list (tactic expr) → tactic unit
| [] := fail "no matching rule"
| (h::t) := (do e ← h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t
/--
Constructs a list of `tactic expr` given a list of p-expressions, as follows:
- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it
- if the p-expression is a user attribute, add all the theorems with this attribute
to the list.
We need to return a list of `tactic expr`, rather than just `expr`, because these expressions
will be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck.
-/
meta def build_list_expr_for_apply : list pexpr → tactic (list (tactic expr))
| [] := return []
| (h::t) := do
tail ← build_list_expr_for_apply t,
a ← i_to_expr_for_apply h,
(do l ← attribute.get_instances (expr.const_name a),
m ← l.mmap (λ n, _root_.to_pexpr <$> mk_const n),
build_list_expr_for_apply (m ++ t))
<|> return ((i_to_expr_for_apply h) :: tail)
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times.
Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies
a lemma from the list until it can't.
-/
meta def apply_rules (hs : list pexpr) (n : nat) (opt : apply_cfg) : tactic unit :=
do l ← lock_tactic_state $ build_list_expr_for_apply hs,
iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt l)
/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local
context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.
Fails if there is nothing named `h` in the local context. -/
meta def replace (h : name) (p : pexpr) : tactic unit :=
do h' ← get_local h,
p ← to_expr p,
note h none p,
clear h'
/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``
or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an
`iff`, returns an expression with the `iff` converted to either the forwards or backwards
implication, as requested. -/
meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr
| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))
| `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0)
| _ f := none
/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/
meta def iff_mp_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mp ty (λ_, e)
/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/
meta def iff_mpr_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mpr ty (λ_, e)
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the forward implication. -/
meta def iff_mp (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the reverse implication. -/
meta def iff_mpr (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/--
Attempts to apply `e`, and if that fails, if `e` is an `iff`,
try applying both directions separately.
-/
meta def apply_iff (e : expr) : tactic (list (name × expr)) :=
let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in
ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)
/--
Configuration options for `apply_any`:
* `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again.
* `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again.
* `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`.
-/
meta structure apply_any_opt extends apply_cfg :=
(use_symmetry : bool := tt)
(use_exfalso : bool := tt)
/--
This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s,
and evaluates these as thunks before trying to apply them.
We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`.
-/
meta def apply_any_thunk
(lemmas : list (tactic expr))
(opt : apply_any_opt := {})
(tac : tactic unit := skip)
(on_success : expr → tactic unit := (λ _, skip))
(on_failure : tactic unit := skip) : tactic unit :=
do
let modes := [skip]
++ (if opt.use_symmetry then [symmetry] else [])
++ (if opt.use_exfalso then [exfalso] else []),
modes.any_of (λ m, do m,
lemmas.any_of (λ H, H >>= (λ e, do apply e opt.to_apply_cfg, on_success e, tac))) <|>
(on_failure >> fail "apply_any tactic failed; no lemma could be applied")
/--
`apply_any lemmas` tries to apply one of the list `lemmas` to the current goal.
`apply_any lemmas opt` allows control over how lemmas are applied.
`opt` has fields:
* `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.)
* `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.)
* `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`).
`apply_any lemmas tac` calls the tactic `tac` after a successful application.
Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange
recursive invocations of `apply_any`.
-/
meta def apply_any
(lemmas : list expr)
(opt : apply_any_opt := {})
(tac : tactic unit := skip) : tactic unit :=
apply_any_thunk (lemmas.map pure) opt tac
/-- Try to apply a hypothesis from the local context to the goal. -/
meta def apply_assumption : tactic unit :=
local_context >>= apply_any
/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails
if this is not a definitional equality.
`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`
by reverting `h`, changing the goal, and reintroducing hypotheses. -/
meta def change_core (e : expr) : option expr → tactic unit
| none := tactic.change e
| (some h) :=
do num_reverted : ℕ ← revert h,
expr.pi n bi d b ← target,
tactic.change $ expr.pi n bi e b,
intron num_reverted
/--
`change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,
assuming `olde` and `newe` are defeq when elaborated.
-/
meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit :=
do h ← get_local hyp,
tp ← infer_type h,
olde ← to_expr olde, newe ← to_expr newe,
let repl_tp := tp.replace (λ a n, if a = olde then some newe else none),
when (repl_tp ≠ tp) $ change_core repl_tp (some h)
/-- Returns a list of all metavariables in the current partial proof. This can differ from
the list of goals, since the goals can be manually edited. -/
meta def metavariables : tactic (list expr) :=
expr.list_meta_vars <$> result
/--
`sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`,
and fail otherwise.
-/
meta def sorry_if_contains_sorry : tactic unit :=
do
g ← target,
guard g.contains_sorry <|> fail "goal does not contain `sorrry`",
tactic.admit
/-- Fail if the target contains a metavariable. -/
meta def no_mvars_in_target : tactic unit :=
expr.has_meta_var <$> target >>= guardb ∘ bnot
/-- Succeeds only if the current goal is a proposition. -/
meta def propositional_goal : tactic unit :=
do g :: _ ← get_goals,
is_proof g >>= guardb
/-- Succeeds only if we can construct an instance showing the
current goal is a subsingleton type. -/
meta def subsingleton_goal : tactic unit :=
do g :: _ ← get_goals,
ty ← infer_type g >>= instantiate_mvars,
to_expr ``(subsingleton %%ty) >>= mk_instance >> skip
/--
Succeeds only if the current goal is "terminal",
in the sense that no other goals depend on it
(except possibly through shared metavariables; see `independent_goal`).
-/
meta def terminal_goal : tactic unit :=
propositional_goal <|> subsingleton_goal <|>
do g₀ :: _ ← get_goals,
mvars ← (λ L, list.erase L g₀) <$> metavariables,
mvars.mmap' $ λ g, do
t ← infer_type g >>= instantiate_mvars,
d ← kdepends_on t g₀,
monad.whenb d $
pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.")
/--
Succeeds only if the current goal is "independent", in the sense
that no other goals depend on it, even through shared meta-variables.
-/
meta def independent_goal : tactic unit :=
no_mvars_in_target >> terminal_goal
/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,
it only unfolds reducible definitions, so it sometimes fails faster. -/
meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible
variable {α : Type}
/-- Apply a tactic as many times as possible, collecting the results in a list.
Fail if the tactic does not succeed at least once. -/
meta def iterate1 (t : tactic α) : tactic (list α) :=
do r ← decorate_ex "iterate1 failed: tactic did not succeed" t,
L ← iterate t,
return (r :: L)
/-- Introduces one or more variables and returns the new local constants.
Fails if `intro` cannot be applied. -/
meta def intros1 : tactic (list expr) :=
iterate1 intro1
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders {α : Type} (t : tactic α) : tactic α :=
do
v ← intros,
r ← t,
revert_lst v,
return r
namespace interactive
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders (i : itactic) : itactic := tactic.under_binders i
end interactive
/-- `successes` invokes each tactic in turn, returning the list of successful results. -/
meta def successes (tactics : list (tactic α)) : tactic (list α) :=
list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t))
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results,
and reverting to the original `tactic_state`.
-/
-- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`.
meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) :=
λ s, result.success
(tactics.map $
λ t : tactic α,
match t s with
| result.success a s' := [a]
| _ := []
end).join s
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results sorted by
the value produced by a subsequent execution of the `sort_by` tactic,
and reverting to the original `tactic_state`.
-/
meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) :
tactic (list (α × ℕ)) :=
λ s, result.success
((tactics.map $
λ t : tactic α,
match (do a ← t, n ← sort_by, return (a, n)) s with
| result.success a s' := [a]
| _ := []
end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s
/-- Return target after instantiating metavars and whnf. -/
private meta def target' : tactic expr :=
target >>= instantiate_mvars >>= whnf
/--
Just like `split`, `fsplit` applies the constructor when the type of the target is
an inductive data type with one constructor.
However it does not reorder goals or invoke `auto_param` tactics.
-/
-- FIXME check if we can remove `auto_param := ff`
meta def fsplit : tactic unit :=
do [c] ← target' >>= get_constructors_for |
fail "fsplit tactic failed, target is not an inductive datatype with only one constructor",
mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip
run_cmd add_interactive [`fsplit]
add_tactic_doc
{ name := "fsplit",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fsplit],
tags := ["logic", "goal management"] }
/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`
succeeds, clears the old hypothesis. -/
meta def injections_and_clear : tactic unit :=
do l ← local_context,
results ← successes $ l.map $ λ e, injection e >> clear e,
when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis")
run_cmd add_interactive [`injections_and_clear]
add_tactic_doc
{ name := "injections_and_clear",
category := doc_category.tactic,
decl_names := [`tactic.interactive.injections_and_clear],
tags := ["context management"] }
/-- Calls `cases` on every local hypothesis, succeeding if
it succeeds on at least one hypothesis. -/
meta def case_bash : tactic unit :=
do l ← local_context,
r ← successes (l.reverse.map (λ h, cases h >> skip)),
when (r.empty) failed
/--
`note_anon t v`, given a proof `v : t`,
adds `h : t` to the current context, where the name `h` is fresh.
`note_anon none v` will infer the type `t` from `v`.
-/
-- While `note` provides a default value for `t`, it doesn't seem this could ever be used.
meta def note_anon (t : option expr) (v : expr) : tactic expr :=
do h ← get_unused_name `h none,
note h t v
/-- `find_local t` returns a local constant with type t, or fails if none exists. -/
meta def find_local (t : pexpr) : tactic expr :=
do t' ← to_expr t,
(prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|>
fail format!"No hypothesis found of the form: {t'}"
/-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values
of the previous local constants. `l` is a list of local constants and their values. -/
meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do
let lc := l.map prod.fst,
let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)),
t ← target,
new_goal ← mk_meta_var (t.pis lc),
old::other_goals ← get_goals,
set_goals (old :: new_goal :: other_goals),
exact ((new_goal.mk_app lc).instantiate_locals lm),
return ()
/-- Like `mk_local_pis` but translating into weak head normal form before checking if it is a `Π`.
-/
meta def mk_local_pis_whnf (e : expr) (md := semireducible) : tactic (list expr × expr) := do
(expr.pi n bi d b) ← whnf e md | return ([], e),
p ← mk_local' n bi d,
(ps, r) ← mk_local_pis (expr.instantiate_var b p),
return ((p :: ps), r)
/-- Changes `(h : ∀xs, ∃a:α, p a) ⊢ g` to `(d : ∀xs, a) (s : ∀xs, p (d xs) ⊢ g`. -/
meta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do
t ← infer_type h,
(ctxt, t) ← mk_local_pis_whnf t,
`(@Exists %%α %%p) ← whnf t transparency.all |
fail "expected a term of the shape ∀xs, ∃a, p xs a",
α_t ← infer_type α,
expr.sort u ← whnf α_t transparency.all,
value ← mk_local_def data (α.pis ctxt),
t' ← head_beta (p.app (value.mk_app ctxt)),
spec ← mk_local_def spec (t'.pis ctxt),
dependent_pose_core [
(value, ((((expr.const `classical.some [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt),
(spec, ((((expr.const `classical.some_spec [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt)],
try (tactic.clear h),
intro1,
intro1
/-- Changes `(h : ∀xs, ∃as, p as) ⊢ g` to a list of functions `as`,
and a final hypothesis on `p as`. -/
meta def choose : expr → list name → tactic unit
| h [] := fail "expect list of variables"
| h [n] := do
cnt ← revert h,
intro n,
intron (cnt - 1),
return ()
| h (n::ns) := do
v ← get_unused_name >>= choose1 h n,
choose v ns
/--
Instantiates metavariables that appear in the current goal.
-/
meta def instantiate_mvars_in_target : tactic unit :=
target >>= instantiate_mvars >>= change
/--
Instantiates metavariables in all goals.
-/
meta def instantiate_mvars_in_goals : tactic unit :=
all_goals' $ instantiate_mvars_in_target
/-- Similar to `mk_local_pis` but make meta variables instead of
local constants. -/
meta def mk_meta_pis : expr → tactic (list expr × expr)
| (expr.pi n bi d b) := do
p ← mk_meta_var d,
(ps, r) ← mk_meta_pis (expr.instantiate_var b p),
return ((p :: ps), r)
| e := return ([], e)
/-- Protect the declaration `n` -/
meta def mk_protected (n : name) : tactic unit :=
do env ← get_env, set_env (env.mk_protected n)
end tactic
namespace lean.parser
open tactic interaction_monad
/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the
current line. -/
meta def emit_command_here (str : string) : lean.parser string :=
do (_, left) ← with_input command_like str,
return left
/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in
source code. -/
meta def emit_code_here : string → lean.parser unit
| str := do left ← emit_command_here str,
if left.length = 0 then return ()
else emit_code_here left
/-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`).
This function deserves a C++ implementation in core lean, and will fail if it is not called from
the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/
meta def get_current_namespace : lean.parser name :=
do n ← tactic.mk_user_fresh_name,
emit_code_here $ sformat!"def {n} := ()",
nfull ← tactic.resolve_constant n,
return $ nfull.get_nth_prefix n.components.length
/-- `get_variables` returns a list of existing variable names, along with their types and binder
info. -/
meta def get_variables : lean.parser (list (name × binder_info × expr)) :=
list.map expr.get_local_const_kind <$> list_available_include_vars
/-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been
"included" by an `include v` statement and are not (yet) `omit`ed. -/
meta def get_included_variables : lean.parser (list (name × binder_info × expr)) :=
do ns ← list_include_var_names,
list.filter (λ v, v.1 ∈ ns) <$> get_variables
/-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local
variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the
local context---precisely those variables which would be ambiently accessible if we were in a
tactic-mode block where the goals had types `es.mmap to_expr`, for example.
Returns a new `ts : tactic_state` with these local variables added, and
`mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable
`var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/
meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr)
: lean.parser (tactic_state × list (expr × expr)) :=
do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the
declared variables to a fake `tactic_state`, and perform the resolution. At the end,
`to_expr e` has done the work of determining which variables were actually referenced, which
we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for
`pexpr`s). -/
vars ← list_available_include_vars,
fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do {
/- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard
them on this first pass. (We return the mappings generated by our second invocation of this
function below.) -/
add_local_consts_as_local_hyps vars,
es.mmap to_expr
},
/- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were
referenced in `e` when it was resolved to `fake_e`.
It is important that we include variables of the kind a) because we want `simp` to have access
to declared local instances, and it is important that we only restrict to variables of kind a)
and b) together since we do not to recognise a hypothesis which is posited as a `variable`
in the environment but not referenced in the `pexpr` we were passed.
One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want
simp to use arbitrary hypotheses which were declared as `variables` in the local environment
but not referenced in the expression to simplify (as one would be expect generally in tactic
mode). -/
included_vars ← list_include_var_names,
let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name,
/- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the
`pexpr` list which we were passed.) -/
let directly_included_vars := vars.filter $ λ var,
(var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars),
/- Inflate the list `directly_included_vars` to include those variables which are "implicitly
included" by virtue of reference to one or multiple others. For example, given
`variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass
instance `prime n` should be included, but `ih : even n` should not. -/
let all_implicitly_included_vars :=
expr.all_implicitly_included_variables vars directly_included_vars,
/- Capture a tactic state where both of these kinds of variables have been added as local
hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/
lean.parser.of_tactic $ do {
mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars,
ts ← get_state,
return (ts, mappings)
}
end lean.parser
namespace tactic
variables {α : Type}
/--
Hole command used to fill in a structure's field when specifying an instance.
In the following:
```lean
instance : monad id :=
{! !}
```
invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under
construction.") produces:
```lean
instance : monad id :=
{ map := _,
map_const := _,
pure := _,
seq := _,
seq_left := _,
seq_right := _,
bind := _ }
```
-/
@[hole_command] meta def instance_stub : hole_command :=
{ name := "Instance Stub",
descr := "Generate a skeleton for the structure under construction.",
action := λ _,
do tgt ← target >>= whnf,
let cl := tgt.get_app_fn.const_name,
env ← get_env,
fs ← expanded_field_list cl,
let fs := fs.map prod.snd,
let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"),
let out := format.to_string format!"{{ {fs} }",
return [(out,"")] }
add_tactic_doc
{ name := "instance_stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.instance_stub],
tags := ["instances"] }
/-- Like `resolve_name` except when the list of goals is
empty. In that situation `resolve_name` fails whereas
`resolve_name'` simply proceeds on a dummy goal -/
meta def resolve_name' (n : name) : tactic pexpr :=
do [] ← get_goals | resolve_name n,
g ← mk_mvar,
set_goals [g],
resolve_name n <* set_goals []
private meta def strip_prefix' (n : name) : list string → name → tactic name
| s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous
| s (name.mk_string a p) :=
do let n' := s.foldl (flip name.mk_string) name.anonymous,
do { n'' ← tactic.resolve_constant n',
if n'' = n
then pure n'
else strip_prefix' (a :: s) p }
<|> strip_prefix' (a :: s) p
| s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n
/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/
meta def strip_prefix : name → tactic name
| n@(name.mk_string a a_1) :=
if (`_private).is_prefix_of n
then let n' := n.update_prefix name.anonymous in
n' <$ resolve_name' n' <|> pure n
else strip_prefix' n [a] a_1
| n := pure n
/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/
meta def mk_patterns (t : expr) : tactic (list format) :=
do let cl := t.get_app_fn.const_name,
env ← get_env,
let fs := env.constructors_of cl,
fs.mmap $ λ f,
do { (vs,_) ← mk_const f >>= infer_type >>= mk_local_pis,
let vs := vs.filter (λ v, v.is_default_local),
vs ← vs.mmap (λ v,
do v' ← get_unused_name v.local_pp_name,
pose v' none `(()),
pure v' ),
vs.mmap' $ λ v, get_local v >>= clear,
let args := list.intersperse (" " : format) $ vs.map to_fmt,
f ← strip_prefix f,
if args.empty
then pure $ format!"| {f} := _\n"
else pure format!"| ({f} {format.join args}) := _\n" }
/--
Hole command used to generate a `match` expression.
In the following:
```lean
meta def foo (e : expr) : tactic unit :=
{! e !}
```
invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression")
produces:
```lean
meta def foo (e : expr) : tactic unit :=
match e with
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
end
```
-/
@[hole_command] meta def match_stub : hole_command :=
{ name := "Match Stub",
descr := "Generate a list of equations for a `match` expression.",
action := λ es,
do [e] ← pure es | fail "expecting one expression",
e ← to_expr e,
t ← infer_type e >>= whnf,
fs ← mk_patterns t,
e ← pp e,
let out := format.to_string format!"match {e} with\n{format.join fs}end\n",
return [(out,"")] }
add_tactic_doc
{ name := "Match Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.match_stub],
tags := ["pattern matching"] }
/--
Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition")
in the following:
```lean
meta def foo : {! expr → tactic unit !} -- `:=` is omitted
```
produces:
```lean
meta def foo : expr → tactic unit
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
A similar result can be obtained by invoking "Equations Stub" on the following:
```lean
meta def foo : expr → tactic unit := -- do not forget to write `:=`!!
{! !}
```
```lean
meta def foo : expr → tactic unit := -- don't forget to erase `:=`!!
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
-/
@[hole_command] meta def eqn_stub : hole_command :=
{ name := "Equations Stub",
descr := "Generate a list of equations for a recursive definition.",
action := λ es,
do t ← match es with
| [t] := to_expr t
| [] := target
| _ := fail "expecting one type"
end,
e ← whnf t,
(v :: _,_) ← mk_local_pis e | fail "expecting a Pi-type",
t' ← infer_type v,
fs ← mk_patterns t',
t ← pp t,
let out :=
if es.empty then
format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}"
else format.to_string format!"{t}\n{format.join fs}",
return [(out,"")] }
add_tactic_doc
{ name := "Equations Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.eqn_stub],
tags := ["pattern matching"] }
/--
This command lists the constructors that can be used to satisfy the expected type.
Invoking "List Constructors" ("Show the list of constructors of the expected type")
in the following hole:
```lean
def foo : ℤ ⊕ ℕ :=
{! !}
```
produces:
```lean
def foo : ℤ ⊕ ℕ :=
{! sum.inl, sum.inr !}
```
and will display:
```lean
sum.inl : ℤ → ℤ ⊕ ℕ
sum.inr : ℕ → ℤ ⊕ ℕ
```
-/
@[hole_command] meta def list_constructors_hole : hole_command :=
{ name := "List Constructors",
descr := "Show the list of constructors of the expected type.",
action := λ es,
do t ← target >>= whnf,
(_,t) ← mk_local_pis t,
let cl := t.get_app_fn.const_name,
let args := t.get_app_args,
env ← get_env,
let cs := env.constructors_of cl,
ts ← cs.mmap $ λ c,
do { e ← mk_const c,
t ← infer_type (e.mk_app args) >>= pp,
c ← strip_prefix c,
pure format!"\n{c} : {t}\n" },
fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt),
let out := format.to_string format!"{{! {fs} !}",
trace (format.join ts).to_string,
return [(out,"")] }
add_tactic_doc
{ name := "List Constructors",
category := doc_category.hole_cmd,
decl_names := [`tactic.list_constructors_hole],
tags := ["goal information"] }
/-- Makes the declaration `classical.prop_decidable` available to type class inference.
This asserts that all propositions are decidable, but does not have computational content. -/
meta def classical : tactic unit :=
do h ← get_unused_name `_inst,
mk_const `classical.prop_decidable >>= note h none,
reset_instance_cache
open expr
/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,
returns the expression `f ∘ g ∘ h`. -/
meta def mk_comp (v : expr) : expr → tactic expr
| (app f e) :=
if e = v then pure f
else do
guard (¬ v.occurs f) <|> fail "bad guard",
e' ← mk_comp e >>= instantiate_mvars,
f ← instantiate_mvars f,
mk_mapp ``function.comp [none,none,none,f,e']
| e :=
do guard (e = v),
t ← infer_type e,
mk_mapp ``id [t]
/--
From a lemma of the shape `∀ x, f (g x) = h x`
derive an auxiliary lemma of the form `f ∘ g = h`
for reasoning about higher-order functions.
-/
meta def mk_higher_order_type : expr → tactic expr
| (pi n bi d b@(pi _ _ _ _)) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'
| (pi n bi d b) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(l,r) ← match_eq b' <|> fail format!"not an equality {b'}",
l' ← mk_comp v l,
r' ← mk_comp v r,
mk_app ``eq [l',r']
| e := failed
open lean.parser interactive.types
/-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`.
It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.
-/
@[user_attribute]
meta def higher_order_attr : user_attribute unit (option name) :=
{ name := `higher_order,
parser := optional ident,
descr :=
"From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the
form `f ∘ g = h` for reasoning about higher-order functions.",
after_set := some $ λ lmm _ _,
do env ← get_env,
decl ← env.get lmm,
let num := decl.univ_params.length,
let lvls := (list.iota num).map (`l).append_after,
let l : expr := expr.const lmm $ lvls.map level.param,
t ← infer_type l >>= instantiate_mvars,
t' ← mk_higher_order_type t,
(_,pr) ← solve_aux t' $ do {
intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },
pr ← instantiate_mvars pr,
lmm' ← higher_order_attr.get_param lmm,
lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime,
add_decl $ declaration.thm lmm' lvls t' (pure pr),
copy_attribute `simp lmm lmm',
copy_attribute `functor_norm lmm lmm' }
add_tactic_doc
{ name := "higher_order",
category := doc_category.attr,
decl_names := [`tactic.higher_order_attr],
tags := ["lemma derivation"] }
attribute [higher_order map_comp_pure] map_pure
/--
Use `refine` to partially discharge the goal,
or call `fconstructor` and try again.
-/
private meta def use_aux (h : pexpr) : tactic unit :=
(focus1 (refine h >> done)) <|> (fconstructor >> use_aux)
/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations
at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to
the expected type.
```lean
example : ∃ x : ℤ, x = x :=
by tactic.use ``(42)
```
See the doc string for `tactic.interactive.use` for more information.
-/
protected meta def use (l : list pexpr) : tactic unit :=
focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}")
instantiate_mvars_in_target
/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the
local context. -/
meta def clear_aux_decl_aux : list expr → tactic unit
| [] := skip
| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l
/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/
meta def clear_aux_decl : tactic unit :=
local_context >>= clear_aux_decl_aux
/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)
finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/
meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr)
| vs e (pi n bi d b) :=
do { v ← mk_meta_var d,
apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|>
(e arg, vs) <$ unify d t
| vs e _ := failed
/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/
meta def apply_at (e h : expr) : tactic unit :=
do ht ← infer_type h,
et ← infer_type e,
(h', gs') ← apply_at_aux h ht [] e et,
note h.local_pp_name none h',
clear h,
gs' ← gs'.mfilter is_assigned,
(g :: gs) ← get_goals,
set_goals (g :: gs' ++ gs)
/-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/
meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit :=
do tgt ← infer_type h,
env ← get_env,
let r := get_app_fn tgt,
match env.symm_for (const_name r) with
| (some symm) := do s ← mk_const symm,
apply_at s h
| none := fail "symmetry tactic failed, target is not a relation application with the expected property."
end
precedence `setup_tactic_parser`:0
/-- `setup_tactic_parser` is a user command that opens the namespaces used in writing
interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.
It does *not* use the `namespace` command, so it will typically be used after
`namespace tactic.interactive`.
-/
@[user_command]
meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") :
lean.parser unit :=
emit_code_here "
open lean
open lean.parser
open interactive interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many .
"
/-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if
`tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/
meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α :=
λ s, match tac s with
| (result.success r s') := (finalizer >> pure r) s'
| (result.exception msg p s') := (finalizer >> result.exception msg p) s'
end
/--
`on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed.
-/
meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s :=
match tac s with
| result.exception msg p s' := (handler *> result.exception msg p) s'
| ok := ok
end
/-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/
meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s :=
match tac s with
| result.exception msg p s :=
let msg (_ : unit) : format := match msg with
| some msg := add_msg ++ format.line ++ msg ()
| none := add_msg
end in
result.exception msg p s
| ok := ok
end
/-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails,
returns the error message. -/
meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) :=
λ s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/
meta def try_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) :=
λ s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s'
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`.
-/
meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit :=
do x ← retrieve_or_report_error t,
match x with
| (sum.inl _) := skip
| (sum.inr msg) := if p msg then skip else fail msg
end
add_tactic_doc
{ name := "setup_tactic_parser",
category := doc_category.cmd,
decl_names := [`tactic.setup_tactic_parser_cmd],
tags := ["parsing", "notation"] }
/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message
of `t`. -/
meta def trace_error (msg : string) (t : tactic α) : tactic α
| s := match t s with
| (result.success r s') := result.success r s'
| (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s'
| (result.exception none p s') := result.exception none p s'
end
/--
``trace_if_enabled `n msg`` traces the message `msg`
only if tracing is enabled for the name `n`.
Create new names registered for tracing with `declare_trace n`.
Then use `set_option trace.n true/false` to enable or disable tracing for `n`.
-/
meta def trace_if_enabled
(n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit :=
when_tracing n (trace msg)
/--
``trace_state_if_enabled `n msg`` prints the tactic state,
preceded by the optional string `msg`,
only if tracing is enabled for the name `n`.
-/
meta def trace_state_if_enabled
(n : name) (msg : string := "") : tactic unit :=
when_tracing n ((if msg = "" then skip else trace msg) >> trace_state)
/--
This combinator is for testing purposes. It succeeds if `t` fails with message `msg`,
and fails otherwise.
-/
meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit :=
λ s, match t s with
| (interaction_monad.result.exception msg' _ s') :=
let expected_msg := (msg'.iget ()).to_string in
if msg = expected_msg then result.success () s
else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s
| (interaction_monad.result.success a s) :=
mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s
end
/--
Construct a `refine ...` or `exact ...` string which would construct `g`.
-/
meta def tactic_statement (g : expr) : tactic string :=
do g ← instantiate_mvars g,
g ← head_beta g,
r ← pp (replace_mvars g),
if g.has_meta_var
then return (sformat!"Try this: refine {r}")
else return (sformat!"Try this: exact {r}")
/-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the
initial goals and returns the goals `tac` ended on. -/
meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) :=
do gs' ← get_goals,
set_goals gs,
finally (prod.mk <$> tac <*> get_goals) (set_goals gs')
/-- like `with_local_goals` but discards the resulting goals -/
meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α :=
prod.fst <$> with_local_goals gs tac
/-- Representation of a proof goal that lends itself to comparison. The
following goal:
```lean
l₀ : T,
l₁ : T
⊢ ∀ v : T, foo
```
is represented as
```
(2, ∀ l₀ l₁ v : T, foo)
```
The number 2 indicates that first the two bound variables of the
`∀` are actually local constant. Comparing two such goals with `=`
rather than `=ₐ` or `is_def_eq` tells us that proof script should
not see the difference between the two.
-/
meta def packaged_goal := ℕ × expr
/-- proof state made of multiple `goal` meant for comparing
the result of running different tactics -/
meta def proof_state := list packaged_goal
meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩
meta instance proof_state.inhabited : inhabited proof_state :=
(infer_instance : inhabited (list packaged_goal))
/-- create a `packaged_goal` corresponding to the current goal -/
meta def get_packaged_goal : tactic packaged_goal := do
ls ← local_context,
tgt ← target >>= instantiate_mvars,
tgt ← pis ls tgt,
pure (ls.length, tgt)
/-- `goal_of_mvar g`, with `g` a meta variable, creates a
`packaged_goal` corresponding to `g` interpretted as a proof goal -/
meta def goal_of_mvar (g : expr) : tactic packaged_goal :=
with_local_goals' [g] get_packaged_goal
/-- `get_proof_state` lists the user visible goal for each goal
of the current state and for each goal, abstracts all of the
meta variables of the other gaols.
This produces a list of goals in the form of `ℕ × expr` where
the `expr` encodes the following proof state:
```lean
2 goals
l₁ : t₁,
l₂ : t₂,
l₃ : t₃
⊢ tgt₁
⊢ tgt₂
```
as
```lean
[ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁),
(0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ]
```
with 2 goals, the first 2 bound variables encode the meta variable
of all the goals, the next 3 (in the first goal) and 0 (in the second goal)
are the local constants.
This representation allows us to compare goals and proof states while
ignoring information like the unique name of local constants and
the equality or difference of meta variables that encode the same goal.
-/
meta def get_proof_state : tactic proof_state :=
do gs ← get_goals,
gs.mmap $ λ g, do
⟨n,g⟩ ← goal_of_mvar g,
g ← gs.mfoldl (λ g v, do
g ← kabstract g v reducible ff,
pure $ pi `goal binder_info.default `(true) g ) g,
pure (n,g)
/--
Run `tac` in a disposable proof state and return the state.
See `proof_state`, `goal` and `get_proof_state`.
-/
meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) :=
try_core $ retrieve $ tac >> get_proof_state
open lean interactive
/-- A type alias for `tactic format`, standing for "pretty print format". -/
meta def pformat := tactic format
/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/
meta def pformat.mk (fmt : format) : pformat := pure fmt
/-- an alias for `pp`. -/
meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat :=
pp x
meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat :=
⟨ id ⟩
meta instance : has_append pformat :=
⟨ λ x y, (++) <$> x <*> y ⟩
meta instance tactic.has_to_tactic_format [has_to_tactic_format α] :
has_to_tactic_format (tactic α) :=
⟨ λ x, x >>= to_pfmt ⟩
private meta def parse_pformat : string → list char → parser pexpr
| acc [] := pure ``(to_pfmt %%(reflect acc))
| acc ('\n'::s) :=
do f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f)
| acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s
| acc ('{'::s) :=
do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string,
'}'::s ← return s.to_list | fail "'}' expected",
f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f)
| acc (c::s) := parse_pformat (acc.str c) s
reserve prefix `pformat! `:100
/-- See `format!` in `init/meta/interactive_base.lean`.
The main differences are that `pp` is called instead of `to_fmt` and that we can use
arguments of type `tactic α` in the quotations.
Now, consider the following:
```lean
e ← to_expr ``(3 + 7),
trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`
trace pformat!"{e}" -- outputs `3 + 7`
```
The difference is significant. And now, the following is expressible:
```lean
e ← to_expr ``(3 + 7),
trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ`
```
See also: `trace!` and `fail!`
-/
@[user_notation]
meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr :=
do e ← parse_pformat "" s.to_list,
return ``(%%e : pformat)
reserve prefix `fail! `:100
/--
The combination of `pformat` and `fail`.
-/
@[user_notation]
meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= fail)
reserve prefix `trace! `:100
/--
The combination of `pformat` and `trace`.
-/
@[user_notation]
meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= trace)
/-- A hackish way to get the `src` directory of mathlib. -/
meta def get_mathlib_dir : tactic string :=
do e ← get_env,
s ← e.decl_olean `tactic.reset_instance_cache,
return $ s.popn_back 17
/-- Checks whether a declaration with the given name is declared in mathlib.
If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,
since it is expensive to execute `get_mathlib_dir` many times. -/
meta def is_in_mathlib (n : name) : tactic bool :=
do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n
/--
Runs a tactic by name.
If it is a `tactic string`, return whatever string it returns.
If it is a `tactic unit`, return the name.
(This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.)
-/
meta def name_to_tactic (n : name) : tactic string :=
do d ← get_decl n,
e ← mk_const n,
let t := d.type,
if (t =ₐ `(tactic unit)) then
(eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n))
else if (t =ₐ `(tactic string)) then
(eval_expr (tactic string) e) >>= (λ t, t)
else fail!"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`"
/-- auxiliary function for `apply_under_n_pis` -/
private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr
| n 0 _ :=
let vars := ((list.range n).reverse.map (@expr.var ff)),
bd := vars.foldl expr.app arg.mk_explicit in
func bd
| n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd)
| n (k+1) t := apply_under_n_pis_aux n 0 t
/--
Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr :=
apply_under_n_pis_aux func arg 0 n pi_expr
/--
Assumes `pi_expr` is of the form `Π x1 ... xn, _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr :=
apply_under_n_pis func arg pi_expr pi_expr.pi_arity
/--
If `func` is a `pexpr` representing a function that takes an argument `a`,
`get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`.
When `tgt` is a `pi` expr, `func` is elaborated in a context
with the domain of `tgt`.
Examples:
* ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument.
* ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`.
* ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0
-/
meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ :=
lock_tactic_state $ do
mv ← mk_mvar,
solve_aux tgt $ intros >> to_expr ``(%%func %%mv),
expr.pi_arity <$> (infer_type mv >>= instantiate_mvars)
/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.
`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a
declaration named `m` can be found. -/
meta def find_private_decl (n : name) (fr : option name) : tactic name :=
do env ← get_env,
fn ← option_t.run (do
fr ← option_t.mk (return fr),
d ← monad_lift $ get_decl fr,
option_t.mk (return $ env.decl_olean d.to_name) ),
let p : string → bool :=
match fn with
| (some fn) := λ x, fn = x
| none := λ _, tt
end,
let xs := env.decl_filter_map (λ d,
do fn ← env.decl_olean d.to_name,
guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n),
pure d.to_name),
match xs with
| [n] := pure n
| [] := fail "no such private found"
| _ := fail "many matches found"
end
open lean.parser interactive
/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`
and creates a local notation to refer to it.
`import_private foo` looks for `foo` in all imported files.
When possible, make `foo` non-private rather than using this feature.
-/
@[user_command]
meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit :=
do n ← ident,
fr ← optional (tk "from" *> ident),
n ← find_private_decl n fr,
c ← resolve_constant n,
d ← get_decl n,
let c := @expr.const tt c d.univ_levels,
new_n ← new_aux_decl_name,
add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted,
let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}",
emit_command_here $ new_not,
skip .
add_tactic_doc
{ name := "import_private",
category := doc_category.cmd,
decl_names := [`tactic.import_private_cmd],
tags := ["renaming"] }
/--
The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`.
Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.
`mk_simp_attribute simp_name none` will use a default description.
Appending the command with `with attr1 attr2 ...` will include all declarations tagged with
`attr1`, `attr2`, ... in the new simp set.
This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string
to the attribute that is defined. If you need to create a simp set in a file where this command is
not available, you should use
```lean
run_cmd mk_simp_attr `simp_name
run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here"
```
-/
@[user_command]
meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit :=
do n ← ident,
d ← parser.pexpr,
d ← to_expr ``(%%d : option string),
descr ← eval_expr (option string) d,
with_list ← types.with_ident_list <|> return [],
mk_simp_attr n with_list,
add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n
add_tactic_doc
{ name := "mk_simp_attribute",
category := doc_category.cmd,
decl_names := [`tactic.mk_simp_attribute_cmd],
tags := ["simplification"] }
/--
Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns
the name of the declaration that defines this attribute.
Fails if there is no user attribute with this name.
Example: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/
meta def get_user_attribute_name (attr_name : name) : tactic name := do
ns ← attribute.get_instances `user_attribute,
ns.mfirst (λ nm, do
d ← get_decl nm,
e ← mk_app `user_attribute.name [d.value],
attr_nm ← eval_expr name e,
guard $ attr_nm = attr_name,
return nm) <|> fail!"'{attr_name}' is not a user attribute."
/-- A tactic to set either a basic attribute or a user attribute, as long as the user attribute has
no parameter.
If a user attribute with a parameter (that is not `unit`) is set, this function will raise an
error. -/
-- possible enhancement if needed: use default value for a user attribute with parameter.
meta def set_attribute (attr_name : name) (c_name : name) (persistent := tt)
(prio : option nat := none) : tactic unit := do
get_decl c_name <|> fail!"unknown declaration {c_name}",
s ← try_or_report_error (set_basic_attribute attr_name c_name persistent prio),
sum.inr msg ← return s | skip,
if msg = (format!"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute").to_string
then do
user_attr_nm ← get_user_attribute_name attr_name,
user_attr_const ← mk_const user_attr_nm,
tac ← eval_pexpr (tactic unit) ``(user_attribute.set %%user_attr_const %%c_name () %%persistent) <|>
fail!"Cannot set attribute @[{attr_name}]. The corresponding user attribute {user_attr_nm} has a parameter.",
tac
else fail msg
end tactic
/--
`find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`),
and returns the value associated with this key if it exists.
Otherwise, it fails.
-/
meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr × v)) (e : expr) :
tactic (expr × v) :=
m.mfind $ λ ⟨e', val⟩, tactic.is_def_eq e e' red
|
6b3aef4be53691dab21539bc51694c5346999e7e | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/topology/dense_embedding.lean | d4dad464ec20922d45a3a56cb5779fce85475849 | [
"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 | 12,823 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import topology.separation
import topology.bases
/-!
# Dense embeddings
This file defines three properties of functions:
* `dense_range f` means `f` has dense image;
* `dense_inducing i` means `i` is also `inducing`;
* `dense_embedding e` means `e` is also an `embedding`.
The main theorem `continuous_extend` gives a criterion for a function
`f : X → Z` to a regular (T₃) space Z to extend along a dense embedding
`i : X → Y` to a continuous function `g : Y → Z`. Actually `i` only
has to be `dense_inducing` (not necessarily injective).
-/
noncomputable theory
open set filter
open_locale classical topological_space filter
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- `i : α → β` is "dense inducing" if it has dense range and the topology on `α`
is the one induced by `i` from the topology on `β`. -/
@[protect_proj] structure dense_inducing [topological_space α] [topological_space β] (i : α → β)
extends inducing i : Prop :=
(dense : dense_range i)
namespace dense_inducing
variables [topological_space α] [topological_space β]
variables {i : α → β} (di : dense_inducing i)
lemma nhds_eq_comap (di : dense_inducing i) :
∀ a : α, 𝓝 a = comap i (𝓝 $ i a) :=
di.to_inducing.nhds_eq_comap
protected lemma continuous (di : dense_inducing i) : continuous i :=
di.to_inducing.continuous
lemma closure_range : closure (range i) = univ :=
di.dense.closure_range
lemma preconnected_space [preconnected_space α] (di : dense_inducing i) : preconnected_space β :=
di.dense.preconnected_space di.continuous
lemma closure_image_mem_nhds {s : set α} {a : α} (di : dense_inducing i) (hs : s ∈ 𝓝 a) :
closure (i '' s) ∈ 𝓝 (i a) :=
begin
rw [di.nhds_eq_comap a, ((nhds_basis_opens _).comap _).mem_iff] at hs,
rcases hs with ⟨U, ⟨haU, hUo⟩, sub : i ⁻¹' U ⊆ s⟩,
refine mem_of_superset (hUo.mem_nhds haU) _,
calc U ⊆ closure (i '' (i ⁻¹' U)) : di.dense.subset_closure_image_preimage_of_is_open hUo
... ⊆ closure (i '' s) : closure_mono (image_subset i sub)
end
lemma dense_image (di : dense_inducing i) {s : set α} : dense (i '' s) ↔ dense s :=
begin
refine ⟨λ H x, _, di.dense.dense_image di.continuous⟩,
rw [di.to_inducing.closure_eq_preimage_closure_image, H.closure_eq, preimage_univ],
trivial
end
/-- The product of two dense inducings is a dense inducing -/
protected lemma prod [topological_space γ] [topological_space δ]
{e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_inducing e₁) (de₂ : dense_inducing e₂) :
dense_inducing (λ(p : α × γ), (e₁ p.1, e₂ p.2)) :=
{ induced := (de₁.to_inducing.prod_mk de₂.to_inducing).induced,
dense := de₁.dense.prod_map de₂.dense }
open topological_space
/-- If the domain of a `dense_inducing` map is a separable space, then so is the codomain. -/
protected lemma separable_space [separable_space α] : separable_space β :=
di.dense.separable_space di.continuous
variables [topological_space δ] {f : γ → α} {g : γ → δ} {h : δ → β}
/--
γ -f→ α
g↓ ↓e
δ -h→ β
-/
lemma tendsto_comap_nhds_nhds {d : δ} {a : α} (di : dense_inducing i)
(H : tendsto h (𝓝 d) (𝓝 (i a))) (comm : h ∘ g = i ∘ f) : tendsto f (comap g (𝓝 d)) (𝓝 a) :=
begin
have lim1 : map g (comap g (𝓝 d)) ≤ 𝓝 d := map_comap_le,
replace lim1 : map h (map g (comap g (𝓝 d))) ≤ map h (𝓝 d) := map_mono lim1,
rw [filter.map_map, comm, ← filter.map_map, map_le_iff_le_comap] at lim1,
have lim2 : comap i (map h (𝓝 d)) ≤ comap i (𝓝 (i a)) := comap_mono H,
rw ← di.nhds_eq_comap at lim2,
exact le_trans lim1 lim2,
end
protected lemma nhds_within_ne_bot (di : dense_inducing i) (b : β) :
ne_bot (𝓝[range i] b) :=
di.dense.nhds_within_ne_bot b
lemma comap_nhds_ne_bot (di : dense_inducing i) (b : β) : ne_bot (comap i (𝓝 b)) :=
comap_ne_bot $ λ s hs,
let ⟨_, ⟨ha, a, rfl⟩⟩ := mem_closure_iff_nhds.1 (di.dense b) s hs in ⟨a, ha⟩
variables [topological_space γ]
/-- If `i : α → β` is a dense inducing, then any function `f : α → γ` "extends"
to a function `g = extend di f : β → γ`. If `γ` is Hausdorff and `f` has a
continuous extension, then `g` is the unique such extension. In general,
`g` might not be continuous or even extend `f`. -/
def extend (di : dense_inducing i) (f : α → γ) (b : β) : γ :=
@@lim _ ⟨f (di.dense.some b)⟩ (comap i (𝓝 b)) f
lemma extend_eq_of_tendsto [t2_space γ] {b : β} {c : γ} {f : α → γ}
(hf : tendsto f (comap i (𝓝 b)) (𝓝 c)) :
di.extend f b = c :=
by haveI := di.comap_nhds_ne_bot; exact hf.lim_eq
lemma extend_eq_at [t2_space γ] {f : α → γ} (a : α) (hf : continuous_at f a) :
di.extend f (i a) = f a :=
extend_eq_of_tendsto _ $ di.nhds_eq_comap a ▸ hf
lemma extend_eq [t2_space γ] {f : α → γ} (hf : continuous f) (a : α) :
di.extend f (i a) = f a :=
di.extend_eq_at a hf.continuous_at
lemma extend_unique_at [t2_space γ] {b : β} {f : α → γ} {g : β → γ} (di : dense_inducing i)
(hf : ∀ᶠ x in comap i (𝓝 b), g (i x) = f x) (hg : continuous_at g b) :
di.extend f b = g b :=
begin
refine di.extend_eq_of_tendsto (λ s hs, mem_map.2 _),
suffices : ∀ᶠ (x : α) in comap i (𝓝 b), g (i x) ∈ s,
from hf.mp (this.mono $ λ x hgx hfx, hfx ▸ hgx),
clear hf f,
refine eventually_comap.2 ((hg.eventually hs).mono _),
rintros _ hxs x rfl,
exact hxs
end
lemma extend_unique [t2_space γ] {f : α → γ} {g : β → γ} (di : dense_inducing i)
(hf : ∀ x, g (i x) = f x) (hg : continuous g) :
di.extend f = g :=
funext $ λ b, extend_unique_at di (eventually_of_forall hf) hg.continuous_at
lemma continuous_at_extend [regular_space γ] {b : β} {f : α → γ} (di : dense_inducing i)
(hf : ∀ᶠ x in 𝓝 b, ∃c, tendsto f (comap i $ 𝓝 x) (𝓝 c)) :
continuous_at (di.extend f) b :=
begin
set φ := di.extend f,
haveI := di.comap_nhds_ne_bot,
suffices : ∀ V' ∈ 𝓝 (φ b), is_closed V' → φ ⁻¹' V' ∈ 𝓝 b,
by simpa [continuous_at, (closed_nhds_basis _).tendsto_right_iff],
intros V' V'_in V'_closed,
set V₁ := {x | tendsto f (comap i $ 𝓝 x) (𝓝 $ φ x)},
have V₁_in : V₁ ∈ 𝓝 b,
{ filter_upwards [hf],
rintros x ⟨c, hc⟩,
dsimp [V₁, φ],
rwa di.extend_eq_of_tendsto hc },
obtain ⟨V₂, V₂_in, V₂_op, hV₂⟩ : ∃ V₂ ∈ 𝓝 b, is_open V₂ ∧ ∀ x ∈ i ⁻¹' V₂, f x ∈ V',
{ simpa [and_assoc] using ((nhds_basis_opens' b).comap i).tendsto_left_iff.mp
(mem_of_mem_nhds V₁_in : b ∈ V₁) V' V'_in },
suffices : ∀ x ∈ V₁ ∩ V₂, φ x ∈ V',
{ filter_upwards [inter_mem V₁_in V₂_in], exact this },
rintros x ⟨x_in₁, x_in₂⟩,
have hV₂x : V₂ ∈ 𝓝 x := is_open.mem_nhds V₂_op x_in₂,
apply V'_closed.mem_of_tendsto x_in₁,
use V₂,
tauto,
end
lemma continuous_extend [regular_space γ] {f : α → γ} (di : dense_inducing i)
(hf : ∀b, ∃c, tendsto f (comap i (𝓝 b)) (𝓝 c)) : continuous (di.extend f) :=
continuous_iff_continuous_at.mpr $ assume b, di.continuous_at_extend $ univ_mem' hf
lemma mk'
(i : α → β)
(c : continuous i)
(dense : ∀x, x ∈ closure (range i))
(H : ∀ (a:α) s ∈ 𝓝 a,
∃t ∈ 𝓝 (i a), ∀ b, i b ∈ t → b ∈ s) :
dense_inducing i :=
{ induced := (induced_iff_nhds_eq i).2 $
λ a, le_antisymm (tendsto_iff_comap.1 $ c.tendsto _) (by simpa [le_def] using H a),
dense := dense }
end dense_inducing
/-- A dense embedding is an embedding with dense image. -/
structure dense_embedding [topological_space α] [topological_space β] (e : α → β)
extends dense_inducing e : Prop :=
(inj : function.injective e)
theorem dense_embedding.mk'
[topological_space α] [topological_space β] (e : α → β)
(c : continuous e)
(dense : dense_range e)
(inj : function.injective e)
(H : ∀ (a:α) s ∈ 𝓝 a,
∃t ∈ 𝓝 (e a), ∀ b, e b ∈ t → b ∈ s) :
dense_embedding e :=
{ inj := inj,
..dense_inducing.mk' e c dense H}
namespace dense_embedding
open topological_space
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
variables {e : α → β} (de : dense_embedding e)
lemma inj_iff {x y} : e x = e y ↔ x = y := de.inj.eq_iff
lemma to_embedding : embedding e :=
{ induced := de.induced,
inj := de.inj }
/-- If the domain of a `dense_embedding` is a separable space, then so is its codomain. -/
protected lemma separable_space [separable_space α] : separable_space β :=
de.to_dense_inducing.separable_space
/-- The product of two dense embeddings is a dense embedding. -/
protected lemma prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁)
(de₂ : dense_embedding e₂) :
dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) :=
{ inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩,
by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩,
..dense_inducing.prod de₁.to_dense_inducing de₂.to_dense_inducing }
/-- The dense embedding of a subtype inside its closure. -/
@[simps] def subtype_emb {α : Type*} (p : α → Prop) (e : α → β) (x : {x // p x}) :
{x // x ∈ closure (e '' {x | p x})} :=
⟨e x, subset_closure $ mem_image_of_mem e x.prop⟩
protected lemma subtype (p : α → Prop) : dense_embedding (subtype_emb p e) :=
{ dense := dense_iff_closure_eq.2 $
begin
ext ⟨x, hx⟩,
rw image_eq_range at hx,
simpa [closure_subtype, ← range_comp, (∘)],
end,
inj := (de.inj.comp subtype.coe_injective).cod_restrict _,
induced := (induced_iff_nhds_eq _).2 (assume ⟨x, hx⟩,
by simp [subtype_emb, nhds_subtype_eq_comap, de.to_inducing.nhds_eq_comap, comap_comap, (∘)]) }
lemma dense_image {s : set α} : dense (e '' s) ↔ dense s :=
de.to_dense_inducing.dense_image
end dense_embedding
lemma dense.dense_embedding_coe [topological_space α] {s : set α} (hs : dense s) :
dense_embedding (coe : s → α) :=
{ dense := hs.dense_range_coe,
.. embedding_subtype_coe }
lemma is_closed_property [topological_space β] {e : α → β} {p : β → Prop}
(he : dense_range e) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) :
∀b, p b :=
have univ ⊆ {b | p b},
from calc univ = closure (range e) : he.closure_range.symm
... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h
... = _ : hp.closure_eq,
assume b, this trivial
lemma is_closed_property2 [topological_space β] {e : α → β} {p : β → β → Prop}
(he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) :
∀b₁ b₂, p b₁ b₂ :=
have ∀q:β×β, p q.1 q.2,
from is_closed_property (he.prod_map he) hp $ λ _, h _ _,
assume b₁ b₂, this ⟨b₁, b₂⟩
lemma is_closed_property3 [topological_space β] {e : α → β} {p : β → β → β → Prop}
(he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2})
(h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) :
∀b₁ b₂ b₃, p b₁ b₂ b₃ :=
have ∀q:β×β×β, p q.1 q.2.1 q.2.2,
from is_closed_property (he.prod_map $ he.prod_map he) hp $ λ _, h _ _ _,
assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩
@[elab_as_eliminator]
lemma dense_range.induction_on [topological_space β] {e : α → β} (he : dense_range e) {p : β → Prop}
(b₀ : β) (hp : is_closed {b | p b}) (ih : ∀a:α, p $ e a) : p b₀ :=
is_closed_property he hp ih b₀
@[elab_as_eliminator]
lemma dense_range.induction_on₂ [topological_space β] {e : α → β} {p : β → β → Prop}
(he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂))
(b₁ b₂ : β) : p b₁ b₂ := is_closed_property2 he hp h _ _
@[elab_as_eliminator]
lemma dense_range.induction_on₃ [topological_space β] {e : α → β} {p : β → β → β → Prop}
(he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2})
(h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃))
(b₁ b₂ b₃ : β) : p b₁ b₂ b₃ := is_closed_property3 he hp h _ _ _
section
variables [topological_space β] [topological_space γ] [t2_space γ]
variables {f : α → β}
/-- Two continuous functions to a t2-space that agree on the dense range of a function are equal. -/
lemma dense_range.equalizer (hfd : dense_range f)
{g h : β → γ} (hg : continuous g) (hh : continuous h) (H : g ∘ f = h ∘ f) :
g = h :=
funext $ λ y, hfd.induction_on y (is_closed_eq hg hh) $ congr_fun H
end
|
a673cebd00518d942278b2d02f81fa9e41021c73 | a523fc1740c8cb84cd0fa0f4b52a760da4e32a5c | /src/missing_mathlib/data/list/basic.lean | eca902092d953fa5bb95f1bfa0972837bd311009 | [] | no_license | abentkamp/spectral | a1aff51e85d30b296a81d256ced1d382345d3396 | 751645679ef1cb6266316349de9e492eff85484c | refs/heads/master | 1,669,994,798,064 | 1,597,591,646,000 | 1,597,591,646,000 | 287,544,072 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 793 | lean | import data.list.basic
universe u
theorem list.foldl_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β)
(a : α) (l : list α) (h : ∀ x y, g (f x y) = f' (g x) (g y)) :
g (list.foldl f a l) = list.foldl f' (g a) (l.map g) :=
begin
induction l generalizing a,
{ simp },
{ simp [list.foldl_cons, l_ih, h] }
end
lemma function.injective_foldl_comp {α : Type*} {l : list (α → α)} {f : α → α}
(hl : ∀ f ∈ l, function.injective f) (hf : function.injective f):
function.injective (@list.foldl (α → α) (α → α) function.comp f l) :=
begin
induction l generalizing f,
{ exact hf },
{ apply l_ih (λ _ h, hl _ (list.mem_cons_of_mem _ h)),
apply function.injective.comp hf,
apply hl _ (list.mem_cons_self _ _) }
end |
921cc31cbd201c95188c49e28db10d23aa057322 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/polynomial/default_auto.lean | 67251d26bbe86a5963e9374a7773688d83ca0f35 | [] | 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 | 342 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.polynomial.algebra_map
import Mathlib.data.polynomial.field_division
import Mathlib.data.polynomial.derivative
import Mathlib.data.polynomial.identities
import Mathlib.data.polynomial.integral_normalization
import Mathlib.PostPort
namespace Mathlib
end Mathlib |
ff8e7a46aec5cfadd250f765da0c101f10b9f806 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/logic/embedding.lean | c10fa4d749acd7bcece01fad278e50fda222e388 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 17,208 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import data.equiv.basic
import data.fun_like.embedding
import data.pprod
import data.set.basic
import data.sigma.basic
/-!
# Injective functions
-/
universes u v w x
namespace function
/-- `α ↪ β` is a bundled injective function. -/
@[nolint has_inhabited_instance] -- depending on cardinalities, an injective function may not exist
structure embedding (α : Sort*) (β : Sort*) :=
(to_fun : α → β)
(inj' : injective to_fun)
infixr ` ↪ `:25 := embedding
instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) (λ _, α → β) := ⟨embedding.to_fun⟩
initialize_simps_projections embedding (to_fun → apply)
instance {α : Sort u} {β : Sort v} : embedding_like (α ↪ β) α β :=
{ coe := embedding.to_fun,
injective' := embedding.inj',
coe_injective' := λ f g h, by { cases f, cases g, congr' } }
end function
section equiv
variables {α : Sort u} {β : Sort v} (f : α ≃ β)
/-- Convert an `α ≃ β` to `α ↪ β`.
This is also available as a coercion `equiv.coe_embedding`.
The explicit `equiv.to_embedding` version is preferred though, since the coercion can have issues
inferring the type of the resulting embedding. For example:
```lean
-- Works:
example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f.to_embedding = s.map f := by simp
-- Error, `f` has type `fin 3 ≃ fin 3` but is expected to have type `fin 3 ↪ ?m_1 : Type ?`
example (s : finset (fin 3)) (f : equiv.perm (fin 3)) : s.map f = s.map f.to_embedding := by simp
```
-/
@[simps] protected def equiv.to_embedding : α ↪ β := ⟨f, f.injective⟩
instance equiv.coe_embedding : has_coe (α ≃ β) (α ↪ β) := ⟨equiv.to_embedding⟩
@[reducible]
instance equiv.perm.coe_embedding : has_coe (equiv.perm α) (α ↪ α) := equiv.coe_embedding
@[simp] lemma equiv.coe_eq_to_embedding : ↑f = f.to_embedding := rfl
/-- Given an equivalence to a subtype, produce an embedding to the elements of the corresponding
set. -/
@[simps]
def equiv.as_embedding {p : β → Prop} (e : α ≃ subtype p) : α ↪ β :=
⟨coe ∘ e, subtype.coe_injective.comp e.injective⟩
@[simp]
lemma equiv.as_embedding_range {α β : Sort*} {p : β → Prop} (e : α ≃ subtype p) :
set.range e.as_embedding = set_of p :=
set.ext $ λ x, ⟨λ ⟨y, h⟩, h ▸ subtype.coe_prop (e y), λ hs, ⟨e.symm ⟨x, hs⟩, by simp⟩⟩
end equiv
namespace function
namespace embedding
lemma coe_injective {α β} : @function.injective (α ↪ β) (α → β) coe_fn := fun_like.coe_injective
@[ext] lemma ext {α β} {f g : embedding α β} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h
lemma ext_iff {α β} {f g : embedding α β} : (∀ x, f x = g x) ↔ f = g := fun_like.ext_iff.symm
@[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl
@[simp] theorem coe_fn_mk {α β} (f : α → β) (i) :
(@mk _ _ f i : α → β) = f := rfl
@[simp] lemma mk_coe {α β : Type*} (f : α ↪ β) (inj) : (⟨f, inj⟩ : α ↪ β) = f :=
by { ext, simp }
protected theorem injective {α β} (f : α ↪ β) : injective f := embedding_like.injective f
lemma apply_eq_iff_eq {α β} (f : α ↪ β) (x y : α) : f x = f y ↔ x = y :=
embedding_like.apply_eq_iff_eq f
/-- The identity map as a `function.embedding`. -/
@[refl, simps {simp_rhs := tt}]
protected def refl (α : Sort*) : α ↪ α :=
⟨id, injective_id⟩
/-- Composition of `f : α ↪ β` and `g : β ↪ γ`. -/
@[trans, simps {simp_rhs := tt}]
protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ :=
⟨g ∘ f, g.injective.comp f.injective⟩
@[simp]
lemma equiv_to_embedding_trans_symm_to_embedding {α β : Sort*} (e : α ≃ β) :
e.to_embedding.trans e.symm.to_embedding = embedding.refl _ :=
by { ext, simp, }
@[simp]
lemma equiv_symm_to_embedding_trans_to_embedding {α β : Sort*} (e : α ≃ β) :
e.symm.to_embedding.trans e.to_embedding = embedding.refl _ :=
by { ext, simp, }
/-- Transfer an embedding along a pair of equivalences. -/
@[simps { fully_applied := ff }]
protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x}
(e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) :=
(equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding)
/-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/
protected noncomputable def of_surjective {α β} (f : β → α) (hf : surjective f) :
α ↪ β :=
⟨surj_inv hf, injective_surj_inv _⟩
/-- Convert a surjective `embedding` to an `equiv` -/
protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) :
α ≃ β :=
equiv.of_bijective f ⟨f.injective, hf⟩
/-- There is always an embedding from an empty type. --/
protected def of_is_empty {α β} [is_empty α] : α ↪ β :=
⟨is_empty_elim, is_empty_elim⟩
/-- Change the value of an embedding `f` at one point. If the prescribed image
is already occupied by some `f a'`, then swap the values at these two points. -/
def set_value {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)]
[∀ a', decidable (f a' = b)] : α ↪ β :=
⟨λ a', if a' = a then b else if f a' = b then f a else f a',
begin
intros x y h,
dsimp at h,
split_ifs at h; try { substI b }; try { simp only [f.injective.eq_iff] at * }; cc
end⟩
theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)]
[∀ a', decidable (f a' = b)] : set_value f a b a = b :=
by simp [set_value]
/-- Embedding into `option α` using `some`. -/
@[simps { fully_applied := ff }] protected def some {α} : α ↪ option α :=
⟨some, option.some_injective α⟩
/-- Embedding into `option α` using `coe`. Usually the correct synctatical form for `simp`. -/
@[simps { fully_applied := ff }]
def coe_option {α} : α ↪ option α := ⟨coe, option.some_injective α⟩
/-- Embedding into `with_top α`. -/
@[simps]
def coe_with_top {α} : α ↪ with_top α := { to_fun := coe, ..embedding.some}
/-- Given an embedding `f : α ↪ β` and a point outside of `set.range f`, construct an embedding
`option α ↪ β`. -/
@[simps] def option_elim {α β} (f : α ↪ β) (x : β) (h : x ∉ set.range f) :
option α ↪ β :=
⟨λ o, o.elim x f, option.injective_iff.2 ⟨f.2, h⟩⟩
/-- Embedding of a `subtype`. -/
def subtype {α} (p : α → Prop) : subtype p ↪ α :=
⟨coe, λ _ _, subtype.ext_val⟩
@[simp] lemma coe_subtype {α} (p : α → Prop) : ⇑(subtype p) = coe := rfl
/-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/
def punit {β : Sort*} (b : β) : punit ↪ β :=
⟨λ _, b, by { rintros ⟨⟩ ⟨⟩ _, refl, }⟩
/-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/
def sectl (α : Sort*) {β : Sort*} (b : β) : α ↪ α × β :=
⟨λ a, (a, b), λ a a' h, congr_arg prod.fst h⟩
/-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/
def sectr {α : Sort*} (a : α) (β : Sort*): β ↪ α × β :=
⟨λ b, (a, b), λ b b' h, congr_arg prod.snd h⟩
/-- Restrict the codomain of an embedding. -/
def cod_restrict {α β} (p : set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p :=
⟨λ a, ⟨f a, H a⟩, λ a b h, f.injective (@congr_arg _ _ _ _ subtype.val h)⟩
@[simp] theorem cod_restrict_apply {α β} (p) (f : α ↪ β) (H a) :
cod_restrict p f H a = ⟨f a, H a⟩ := rfl
/-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/
def prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ :=
⟨prod.map e₁ e₂, e₁.injective.prod_map e₂.injective⟩
@[simp] lemma coe_prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) :
⇑(e₁.prod_map e₂) = prod.map e₁ e₂ :=
rfl
/-- If `e₁` and `e₂` are embeddings, then so is `λ ⟨a, b⟩, ⟨e₁ a, e₂ b⟩ : pprod α γ → pprod β δ`. -/
def pprod_map {α β γ δ : Sort*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : pprod α γ ↪ pprod β δ :=
⟨λ x, ⟨e₁ x.1, e₂ x.2⟩, e₁.injective.pprod_map e₂.injective⟩
section sum
open sum
/-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/
def sum_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ :=
⟨sum.map e₁ e₂,
assume s₁ s₂ h, match s₁, s₂, h with
| inl a₁, inl a₂, h := congr_arg inl $ e₁.injective $ inl.inj h
| inr b₁, inr b₂, h := congr_arg inr $ e₂.injective $ inr.inj h
end⟩
@[simp] theorem coe_sum_map {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) :
⇑(sum_map e₁ e₂) = sum.map e₁ e₂ :=
rfl
/-- The embedding of `α` into the sum `α ⊕ β`. -/
@[simps] def inl {α β : Type*} : α ↪ α ⊕ β :=
⟨sum.inl, λ a b, sum.inl.inj⟩
/-- The embedding of `β` into the sum `α ⊕ β`. -/
@[simps] def inr {α β : Type*} : β ↪ α ⊕ β :=
⟨sum.inr, λ a b, sum.inr.inj⟩
end sum
section sigma
variables {α α' : Type*} {β : α → Type*} {β' : α' → Type*}
/-- `sigma.mk` as an `function.embedding`. -/
@[simps apply] def sigma_mk (a : α) : β a ↪ Σ x, β x :=
⟨sigma.mk a, sigma_mk_injective⟩
/-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family
of embeddings, then `sigma.map f g` is an embedding. -/
@[simps apply] def sigma_map (f : α ↪ α') (g : Π a, β a ↪ β' (f a)) :
(Σ a, β a) ↪ Σ a', β' a' :=
⟨sigma.map f (λ a, g a), f.injective.sigma_map (λ a, (g a).injective)⟩
end sigma
/-- Define an embedding `(Π a : α, β a) ↪ (Π a : α, γ a)` from a family of embeddings
`e : Π a, (β a ↪ γ a)`. This embedding sends `f` to `λ a, e a (f a)`. -/
@[simps] def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) :
(Π a, β a) ↪ (Π a, γ a) :=
⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).injective (congr_fun h a)⟩
/-- An embedding `e : α ↪ β` defines an embedding `(γ → α) ↪ (γ → β)` that sends each `f`
to `e ∘ f`. -/
def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w}
(e : α ↪ β) : (γ → α) ↪ (γ → β) :=
Pi_congr_right (λ _, e)
@[simp] lemma arrow_congr_right_apply {α : Sort u} {β : Sort v} {γ : Sort w}
(e : α ↪ β) (f : γ ↪ α) : arrow_congr_right e f = e ∘ f := rfl
/-- An embedding `e : α ↪ β` defines an embedding `(α → γ) ↪ (β → γ)` for any inhabited type `γ`.
This embedding sends each `f : α → γ` to a function `g : β → γ` such that `g ∘ e = f` and
`g y = default` whenever `y ∉ range e`. -/
noncomputable def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ]
(e : α ↪ β) : (α → γ) ↪ (β → γ) :=
⟨λ f, extend e f (λ _, default), λ f₁ f₂ h, funext $ λ x,
by simpa only [extend_apply e.injective] using congr_fun h (e x)⟩
/-- Restrict both domain and codomain of an embedding. -/
protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β)
(h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} :=
⟨subtype.map f h, subtype.map_injective h f.2⟩
open set
/-- `set.image` as an embedding `set α ↪ set β`. -/
@[simps apply] protected def image {α β} (f : α ↪ β) : set α ↪ set β :=
⟨image f, f.2.image_injective⟩
lemma swap_apply {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y z : α) :
equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) :=
f.injective.swap_apply x y z
lemma swap_comp {α β : Type*} [decidable_eq α] [decidable_eq β] (f : α ↪ β) (x y : α) :
equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y :=
f.injective.swap_comp x y
end embedding
end function
namespace equiv
open function.embedding
/-- The type of embeddings `α ↪ β` is equivalent to
the subtype of all injective functions `α → β`. -/
def subtype_injective_equiv_embedding (α β : Sort*) :
{f : α → β // function.injective f} ≃ (α ↪ β) :=
{ to_fun := λ f, ⟨f.val, f.property⟩,
inv_fun := λ f, ⟨f, f.injective⟩,
left_inv := λ f, by simp,
right_inv := λ f, by {ext, refl} }
/-- If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then the type of embeddings `α₁ ↪ β₁`
is equivalent to the type of embeddings `α₂ ↪ β₂`. -/
@[congr, simps apply] def embedding_congr {α β γ δ : Sort*}
(h : α ≃ β) (h' : γ ≃ δ) : (α ↪ γ) ≃ (β ↪ δ) :=
{ to_fun := λ f, f.congr h h',
inv_fun := λ f, f.congr h.symm h'.symm,
left_inv := λ x, by {ext, simp},
right_inv := λ x, by {ext, simp} }
@[simp] lemma embedding_congr_refl {α β : Sort*} :
embedding_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ↪ β) :=
by {ext, refl}
@[simp] lemma embedding_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*}
(e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) :
embedding_congr (e₁.trans e₂) (e₁'.trans e₂') =
(embedding_congr e₁ e₁').trans (embedding_congr e₂ e₂') :=
rfl
@[simp] lemma embedding_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) :
(embedding_congr e₁ e₂).symm = embedding_congr e₁.symm e₂.symm :=
rfl
lemma embedding_congr_apply_trans {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*}
(ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ ↪ β₁) (g : β₁ ↪ γ₁) :
equiv.embedding_congr ea ec (f.trans g) =
(equiv.embedding_congr ea eb f).trans (equiv.embedding_congr eb ec g) :=
by {ext, simp}
@[simp]
lemma refl_to_embedding {α : Type*} : (equiv.refl α).to_embedding = function.embedding.refl α := rfl
@[simp]
lemma trans_to_embedding {α β γ : Type*} (e : α ≃ β) (f : β ≃ γ) :
(e.trans f).to_embedding = e.to_embedding.trans f.to_embedding := rfl
end equiv
namespace set
/-- The injection map is an embedding between subsets. -/
@[simps apply] def embedding_of_subset {α} (s t : set α) (h : s ⊆ t) : s ↪ t :=
⟨λ x, ⟨x.1, h x.2⟩, λ ⟨x, hx⟩ ⟨y, hy⟩ h, by { congr, injection h }⟩
end set
section subtype
variable {α : Type*}
/-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` can be injectively split
into a sum of subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right. -/
def subtype_or_left_embedding (p q : α → Prop) [decidable_pred p] :
{x // p x ∨ q x} ↪ {x // p x} ⊕ {x // q x} :=
⟨λ x, if h : p x then sum.inl ⟨x, h⟩ else sum.inr ⟨x, x.prop.resolve_left h⟩,
begin
intros x y,
dsimp only,
split_ifs;
simp [subtype.ext_iff]
end⟩
lemma subtype_or_left_embedding_apply_left {p q : α → Prop} [decidable_pred p]
(x : {x // p x ∨ q x}) (hx : p x) : subtype_or_left_embedding p q x = sum.inl ⟨x, hx⟩ :=
dif_pos hx
lemma subtype_or_left_embedding_apply_right {p q : α → Prop} [decidable_pred p]
(x : {x // p x ∨ q x}) (hx : ¬ p x) :
subtype_or_left_embedding p q x = sum.inr ⟨x, x.prop.resolve_left hx⟩ :=
dif_neg hx
/-- A subtype `{x // p x}` can be injectively sent to into a subtype `{x // q x}`,
if `p x → q x` for all `x : α`. -/
@[simps] def subtype.imp_embedding (p q : α → Prop) (h : p ≤ q) :
{x // p x} ↪ {x // q x} :=
⟨λ x, ⟨x, h x x.prop⟩, λ x y, by simp [subtype.ext_iff]⟩
/-- A subtype `{x // p x ∨ q x}` over a disjunction of `p q : α → Prop` is equivalent to a sum of
subtypes `{x // p x} ⊕ {x // q x}` such that `¬ p x` is sent to the right, when
`disjoint p q`.
See also `equiv.sum_compl`, for when `is_compl p q`. -/
@[simps apply] def subtype_or_equiv (p q : α → Prop) [decidable_pred p] (h : disjoint p q) :
{x // p x ∨ q x} ≃ {x // p x} ⊕ {x // q x} :=
{ to_fun := subtype_or_left_embedding p q,
inv_fun := sum.elim
(subtype.imp_embedding _ _ (λ x hx, (or.inl hx : p x ∨ q x)))
(subtype.imp_embedding _ _ (λ x hx, (or.inr hx : p x ∨ q x))),
left_inv := λ x, begin
by_cases hx : p x,
{ rw subtype_or_left_embedding_apply_left _ hx,
simp [subtype.ext_iff] },
{ rw subtype_or_left_embedding_apply_right _ hx,
simp [subtype.ext_iff] },
end,
right_inv := λ x, begin
cases x,
{ simp only [sum.elim_inl],
rw subtype_or_left_embedding_apply_left,
{ simp },
{ simpa using x.prop } },
{ simp only [sum.elim_inr],
rw subtype_or_left_embedding_apply_right,
{ simp },
{ suffices : ¬ p x,
{ simpa },
intro hp,
simpa using h x ⟨hp, x.prop⟩ } }
end }
@[simp] lemma subtype_or_equiv_symm_inl (p q : α → Prop) [decidable_pred p] (h : disjoint p q)
(x : {x // p x}) : (subtype_or_equiv p q h).symm (sum.inl x) = ⟨x, or.inl x.prop⟩ :=
rfl
@[simp] lemma subtype_or_equiv_symm_inr (p q : α → Prop) [decidable_pred p] (h : disjoint p q)
(x : {x // q x}) : (subtype_or_equiv p q h).symm (sum.inr x) = ⟨x, or.inr x.prop⟩ :=
rfl
end subtype
|
db54bc544a2cc66deb8f29f3c31ed44ec8b68394 | 367134ba5a65885e863bdc4507601606690974c1 | /src/analysis/calculus/lagrange_multipliers.lean | 3034271915398e0100946a2ce7381df5028c43dd | [
"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 | 6,765 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury Kudryashov
-/
import analysis.calculus.local_extr
import analysis.calculus.implicit
/-!
# Lagrange multipliers
In this file we formalize the
[Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) method of solving
conditional extremum problems: if a function `φ` has a local extremum at `x₀` on the set
`f ⁻¹' {f x₀}`, `f x = (f₀ x, ..., fₙ₋₁ x)`, then the differentials of `fₖ` and `φ` are linearly
dependent. First we formulate a geometric version of this theorem which does not rely on the
target space being `ℝⁿ`, then restate it in terms of coordinates.
## TODO
Formalize Karush-Kuhn-Tucker theorem
## Tags
lagrange multiplier, local extremum
-/
open filter set
open_locale topological_space filter big_operators
variables {E F : Type*} [normed_group E] [normed_space ℝ E] [complete_space E]
[normed_group F] [normed_space ℝ F] [complete_space F]
{f : E → F} {φ : E → ℝ} {x₀ : E} {f' : E →L[ℝ] F} {φ' : E →L[ℝ] ℝ}
/-- Lagrange multipliers theorem: if `φ : E → ℝ` has a local extremum on the set `{x | f x = f x₀}`
at `x₀`, both `f : E → F` and `φ` are strictly differentiable at `x₀`, and the codomain of `f` is
a complete space, then the linear map `x ↦ (f' x, φ' x)` is not surjective. -/
lemma is_local_extr_on.range_ne_top_of_has_strict_fderiv_at
(hextr : is_local_extr_on φ {x | f x = f x₀} x₀) (hf' : has_strict_fderiv_at f f' x₀)
(hφ' : has_strict_fderiv_at φ φ' x₀) :
(f'.prod φ').range ≠ ⊤ :=
begin
intro htop,
set fφ := λ x, (f x, φ x),
have A : map φ (𝓝[f ⁻¹' {f x₀}] x₀) = 𝓝 (φ x₀),
{ change map (prod.snd ∘ fφ) (𝓝[fφ ⁻¹' {p | p.1 = f x₀}] x₀) = 𝓝 (φ x₀),
rw [← map_map, nhds_within, map_inf_principal_preimage,
(hf'.prod hφ').map_nhds_eq_of_surj htop],
exact map_snd_nhds_within _ },
exact hextr.not_nhds_le_map A.ge
end
/-- Lagrange multipliers theorem: if `φ : E → ℝ` has a local extremum on the set `{x | f x = f x₀}`
at `x₀`, both `f : E → F` and `φ` are strictly differentiable at `x₀`, and the codomain of `f` is
a complete space, then there exist `Λ : dual ℝ F` and `Λ₀ : ℝ` such that `(Λ, Λ₀) ≠ 0` and
`Λ (f' x) + Λ₀ • φ' x = 0` for all `x`. -/
lemma is_local_extr_on.exists_linear_map_of_has_strict_fderiv_at
(hextr : is_local_extr_on φ {x | f x = f x₀} x₀) (hf' : has_strict_fderiv_at f f' x₀)
(hφ' : has_strict_fderiv_at φ φ' x₀) :
∃ (Λ : module.dual ℝ F) (Λ₀ : ℝ), (Λ, Λ₀) ≠ 0 ∧ ∀ x, Λ (f' x) + Λ₀ • φ' x = 0 :=
begin
rcases submodule.exists_le_ker_of_lt_top _
(lt_top_iff_ne_top.2 $ hextr.range_ne_top_of_has_strict_fderiv_at hf' hφ') with ⟨Λ', h0, hΛ'⟩,
set e : ((F →ₗ[ℝ] ℝ) × ℝ) ≃ₗ[ℝ] (F × ℝ →ₗ[ℝ] ℝ) :=
((linear_equiv.refl ℝ (F →ₗ[ℝ] ℝ)).prod (linear_map.ring_lmap_equiv_self ℝ ℝ ℝ).symm).trans
(linear_map.coprod_equiv ℝ),
rcases e.surjective Λ' with ⟨⟨Λ, Λ₀⟩, rfl⟩,
refine ⟨Λ, Λ₀, e.map_ne_zero_iff.1 h0, λ x, _⟩,
convert linear_map.congr_fun (linear_map.range_le_ker_iff.1 hΛ') x using 1,
-- squeezed `simp [mul_comm]` to speed up elaboration
simp only [linear_map.coprod_equiv_apply, linear_equiv.refl_apply,
linear_map.ring_lmap_equiv_self_symm_apply, linear_map.comp_apply,
continuous_linear_map.coe_coe, continuous_linear_map.prod_apply,
linear_equiv.trans_apply, linear_equiv.prod_apply, linear_map.coprod_apply,
linear_map.smul_right_apply, linear_map.one_apply, smul_eq_mul, mul_comm]
end
/-- Lagrange multipliers theorem. Let `f : ι → E → ℝ` be a finite family of functions.
Suppose that `φ : E → ℝ` has a local extremum on the set `{x | ∀ i, f i x = f i x₀}` at `x₀`.
Suppose that all functions `f i` as well as `φ` are strictly differentiable at `x₀`.
Then the derivatives `f' i : E → L[ℝ] ℝ` and `φ' : E →L[ℝ] ℝ` are linearly dependent:
there exist `Λ : ι → ℝ` and `Λ₀ : ℝ`, `(Λ, Λ₀) ≠ 0`, such that `∑ i, Λ i • f' i + Λ₀ • φ' = 0`.
See also `is_local_extr_on.linear_dependent_of_has_strict_fderiv_at` for a version that
states `¬linear_independent ℝ _` instead of existence of `Λ` and `Λ₀`. -/
lemma is_local_extr_on.exists_multipliers_of_has_strict_fderiv_at {ι : Type*} [fintype ι]
{f : ι → E → ℝ} {f' : ι → E →L[ℝ] ℝ}
(hextr : is_local_extr_on φ {x | ∀ i, f i x = f i x₀} x₀)
(hf' : ∀ i, has_strict_fderiv_at (f i) (f' i) x₀)
(hφ' : has_strict_fderiv_at φ φ' x₀) :
∃ (Λ : ι → ℝ) (Λ₀ : ℝ), (Λ, Λ₀) ≠ 0 ∧ ∑ i, Λ i • f' i + Λ₀ • φ' = 0 :=
begin
letI := classical.dec_eq ι,
replace hextr : is_local_extr_on φ {x | (λ i, f i x) = (λ i, f i x₀)} x₀,
by simpa only [function.funext_iff] using hextr,
rcases hextr.exists_linear_map_of_has_strict_fderiv_at
(has_strict_fderiv_at_pi.2 (λ i, hf' i)) hφ'
with ⟨Λ, Λ₀, h0, hsum⟩,
rcases (linear_equiv.pi_ring ℝ ℝ ι ℝ).symm.surjective Λ with ⟨Λ, rfl⟩,
refine ⟨Λ, Λ₀, _, _⟩,
{ simpa only [ne.def, prod.ext_iff, linear_equiv.map_eq_zero_iff, prod.fst_zero] using h0 },
{ ext x, simpa [mul_comm] using hsum x }
end
/-- Lagrange multipliers theorem. Let `f : ι → E → ℝ` be a finite family of functions.
Suppose that `φ : E → ℝ` has a local extremum on the set `{x | ∀ i, f i x = f i x₀}` at `x₀`.
Suppose that all functions `f i` as well as `φ` are strictly differentiable at `x₀`.
Then the derivatives `f' i : E → L[ℝ] ℝ` and `φ' : E →L[ℝ] ℝ` are linearly dependent.
See also `is_local_extr_on.exists_multipliers_of_has_strict_fderiv_at` for a version that
that states existence of Lagrange multipliers `Λ` and `Λ₀` instead of using
`¬linear_independent ℝ _` -/
lemma is_local_extr_on.linear_dependent_of_has_strict_fderiv_at {ι : Type*} [fintype ι]
{f : ι → E → ℝ} {f' : ι → E →L[ℝ] ℝ}
(hextr : is_local_extr_on φ {x | ∀ i, f i x = f i x₀} x₀)
(hf' : ∀ i, has_strict_fderiv_at (f i) (f' i) x₀)
(hφ' : has_strict_fderiv_at φ φ' x₀) :
¬linear_independent ℝ (λ i, option.elim i φ' f' : option ι → E →L[ℝ] ℝ) :=
begin
rw [fintype.linear_independent_iff], push_neg,
rcases hextr.exists_multipliers_of_has_strict_fderiv_at hf' hφ' with ⟨Λ, Λ₀, hΛ, hΛf⟩,
refine ⟨λ i, option.elim i Λ₀ Λ, _, _⟩,
{ simpa [add_comm] using hΛf },
{ simpa [function.funext_iff, not_and_distrib, or_comm, option.exists] using hΛ }
end
|
1eb4e999e5faf8ebbf371ecedf83a046a15df0db | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/matrix/determinant.lean | fa527c57a6b8cb509c8f0d722d10a51af88c9b62 | [
"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 | 31,891 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Chris Hughes, Tim Baanen
-/
import data.matrix.pequiv
import data.matrix.block
import data.matrix.notation
import data.fintype.big_operators
import group_theory.perm.fin
import group_theory.perm.sign
import algebra.algebra.basic
import tactic.ring
import linear_algebra.alternating
import linear_algebra.pi
/-!
# Determinant of a matrix
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the determinant of a matrix, `matrix.det`, and its essential properties.
## Main definitions
- `matrix.det`: the determinant of a square matrix, as a sum over permutations
- `matrix.det_row_alternating`: the determinant, as an `alternating_map` in the rows of the matrix
## Main results
- `det_mul`: the determinant of `A ⬝ B` is the product of determinants
- `det_zero_of_row_eq`: the determinant is zero if there is a repeated row
- `det_block_diagonal`: the determinant of a block diagonal matrix is a product
of the blocks' determinants
## Implementation notes
It is possible to configure `simp` to compute determinants. See the file
`test/matrix.lean` for some examples.
-/
universes u v w z
open equiv equiv.perm finset function
namespace matrix
open_locale matrix big_operators
variables {m n : Type*} [decidable_eq n] [fintype n] [decidable_eq m] [fintype m]
variables {R : Type v} [comm_ring R]
local notation `ε ` σ:max := ((sign σ : ℤ) : R)
/-- `det` is an `alternating_map` in the rows of the matrix. -/
def det_row_alternating : alternating_map R (n → R) R n :=
((multilinear_map.mk_pi_algebra R n R).comp_linear_map (linear_map.proj)).alternatization
/-- The determinant of a matrix given by the Leibniz formula. -/
abbreviation det (M : matrix n n R) : R :=
det_row_alternating M
lemma det_apply (M : matrix n n R) :
M.det = ∑ σ : perm n, σ.sign • ∏ i, M (σ i) i :=
multilinear_map.alternatization_apply _ M
-- This is what the old definition was. We use it to avoid having to change the old proofs below
lemma det_apply' (M : matrix n n R) :
M.det = ∑ σ : perm n, ε σ * ∏ i, M (σ i) i :=
by simp [det_apply, units.smul_def]
@[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = ∏ i, d i :=
begin
rw det_apply',
refine (finset.sum_eq_single 1 _ _).trans _,
{ intros σ h1 h2,
cases not_forall.1 (mt equiv.ext h2) with x h3,
convert mul_zero _,
apply finset.prod_eq_zero,
{ change x ∈ _, simp },
exact if_neg h3 },
{ simp },
{ simp }
end
@[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 :=
(det_row_alternating : alternating_map R (n → R) R n).map_zero
@[simp] lemma det_one : det (1 : matrix n n R) = 1 :=
by rw [← diagonal_one]; simp [-diagonal_one]
lemma det_is_empty [is_empty n] {A : matrix n n R} : det A = 1 :=
by simp [det_apply]
@[simp] lemma coe_det_is_empty [is_empty n] : (det : matrix n n R → R) = function.const _ 1 :=
by { ext, exact det_is_empty, }
lemma det_eq_one_of_card_eq_zero {A : matrix n n R} (h : fintype.card n = 0) : det A = 1 :=
begin
haveI : is_empty n := fintype.card_eq_zero_iff.mp h,
exact det_is_empty,
end
/-- If `n` has only one element, the determinant of an `n` by `n` matrix is just that element.
Although `unique` implies `decidable_eq` and `fintype`, the instances might
not be syntactically equal. Thus, we need to fill in the args explicitly. -/
@[simp]
lemma det_unique {n : Type*} [unique n] [decidable_eq n] [fintype n] (A : matrix n n R) :
det A = A default default :=
by simp [det_apply, univ_unique]
lemma det_eq_elem_of_subsingleton [subsingleton n] (A : matrix n n R) (k : n) :
det A = A k k :=
begin
convert det_unique _,
exact unique_of_subsingleton k
end
lemma det_eq_elem_of_card_eq_one {A : matrix n n R} (h : fintype.card n = 1) (k : n) :
det A = A k k :=
begin
haveI : subsingleton n := fintype.card_le_one_iff_subsingleton.mp h.le,
exact det_eq_elem_of_subsingleton _ _
end
lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) :
∑ σ : perm n, (ε σ) * ∏ x, (M (σ x) (p x) * N (p x) x) = 0 :=
begin
obtain ⟨i, j, hpij, hij⟩ : ∃ i j, p i = p j ∧ i ≠ j,
{ rw [← finite.injective_iff_bijective, injective] at H,
push_neg at H,
exact H },
exact sum_involution
(λ σ _, σ * swap i j)
(λ σ _,
have ∏ x, M (σ x) (p x) = ∏ x, M ((σ * swap i j) x) (p x),
from fintype.prod_equiv (swap i j) _ _ (by simp [apply_swap_eq_self hpij]),
by simp [this, sign_swap hij, prod_mul_distrib])
(λ σ _ _, (not_congr mul_swap_eq_iff).mpr hij)
(λ _ _, mem_univ _)
(λ σ _, mul_swap_involutive i j σ)
end
@[simp] lemma det_mul (M N : matrix n n R) : det (M ⬝ N) = det M * det N :=
calc det (M ⬝ N) = ∑ p : n → n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) :
by simp only [det_apply', mul_apply, prod_univ_sum, mul_sum,
fintype.pi_finset_univ]; rw [finset.sum_comm]
... = ∑ p in (@univ (n → n) _).filter bijective, ∑ σ : perm n,
ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) :
eq.symm $ sum_subset (filter_subset _ _)
(λ f _ hbij, det_mul_aux $ by simpa only [true_and, mem_filter, mem_univ] using hbij)
... = ∑ τ : perm n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (τ i) * N (τ i) i) :
sum_bij (λ p h, equiv.of_bijective p (mem_filter.1 h).2) (λ _ _, mem_univ _)
(λ _ _, rfl) (λ _ _ _ _ h, by injection h)
(λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, coe_fn_injective rfl⟩)
... = ∑ σ : perm n, ∑ τ : perm n, (∏ i, N (σ i) i) * ε τ * (∏ j, M (τ j) (σ j)) :
by simp only [mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc]
... = ∑ σ : perm n, ∑ τ : perm n, (((∏ i, N (σ i) i) * (ε σ * ε τ)) * ∏ i, M (τ i) i) :
sum_congr rfl (λ σ _, fintype.sum_equiv (equiv.mul_right σ⁻¹) _ _
(λ τ,
have ∏ j, M (τ j) (σ j) = ∏ j, M ((τ * σ⁻¹) j) j,
by { rw ← (σ⁻¹ : _ ≃ _).prod_comp, simp only [equiv.perm.coe_mul, apply_inv_self] },
have h : ε σ * ε (τ * σ⁻¹) = ε τ :=
calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) :
by { rw [mul_comm, sign_mul (τ * σ⁻¹)], simp only [int.cast_mul, units.coe_mul] }
... = ε τ : by simp only [inv_mul_cancel_right],
by { simp_rw [equiv.coe_mul_right, h], simp only [this] }))
... = det M * det N : by simp only [det_apply', finset.mul_sum, mul_comm, mul_left_comm]
/-- The determinant of a matrix, as a monoid homomorphism. -/
def det_monoid_hom : matrix n n R →* R :=
{ to_fun := det,
map_one' := det_one,
map_mul' := det_mul }
@[simp] lemma coe_det_monoid_hom : (det_monoid_hom : matrix n n R → R) = det := rfl
/-- On square matrices, `mul_comm` applies under `det`. -/
lemma det_mul_comm (M N : matrix m m R) : det (M ⬝ N) = det (N ⬝ M) :=
by rw [det_mul, det_mul, mul_comm]
/-- On square matrices, `mul_left_comm` applies under `det`. -/
lemma det_mul_left_comm (M N P : matrix m m R) : det (M ⬝ (N ⬝ P)) = det (N ⬝ (M ⬝ P)) :=
by rw [←matrix.mul_assoc, ←matrix.mul_assoc, det_mul, det_mul_comm M N, ←det_mul]
/-- On square matrices, `mul_right_comm` applies under `det`. -/
lemma det_mul_right_comm (M N P : matrix m m R) :
det (M ⬝ N ⬝ P) = det (M ⬝ P ⬝ N) :=
by rw [matrix.mul_assoc, matrix.mul_assoc, det_mul, det_mul_comm N P, ←det_mul]
lemma det_units_conj (M : (matrix m m R)ˣ) (N : matrix m m R) :
det (↑M ⬝ N ⬝ ↑M⁻¹ : matrix m m R) = det N :=
by rw [det_mul_right_comm, ←mul_eq_mul, ←mul_eq_mul, units.mul_inv, one_mul]
lemma det_units_conj' (M : (matrix m m R)ˣ) (N : matrix m m R) :
det (↑M⁻¹ ⬝ N ⬝ ↑M : matrix m m R) = det N := det_units_conj M⁻¹ N
/-- Transposing a matrix preserves the determinant. -/
@[simp] lemma det_transpose (M : matrix n n R) : Mᵀ.det = M.det :=
begin
rw [det_apply', det_apply'],
refine fintype.sum_bijective _ inv_involutive.bijective _ _ _,
intros σ,
rw sign_inv,
congr' 1,
apply fintype.prod_equiv σ,
intros,
simp
end
/-- Permuting the columns changes the sign of the determinant. -/
lemma det_permute (σ : perm n) (M : matrix n n R) : matrix.det (λ i, M (σ i)) = σ.sign * M.det :=
((det_row_alternating : alternating_map R (n → R) R n).map_perm M σ).trans
(by simp [units.smul_def])
/-- Permuting rows and columns with the same equivalence has no effect. -/
@[simp]
lemma det_submatrix_equiv_self (e : n ≃ m) (A : matrix m m R) :
det (A.submatrix e e) = det A :=
begin
rw [det_apply', det_apply'],
apply fintype.sum_equiv (equiv.perm_congr e),
intro σ,
rw equiv.perm.sign_perm_congr e σ,
congr' 1,
apply fintype.prod_equiv e,
intro i,
rw [equiv.perm_congr_apply, equiv.symm_apply_apply, submatrix_apply],
end
/-- Reindexing both indices along the same equivalence preserves the determinant.
For the `simp` version of this lemma, see `det_submatrix_equiv_self`; this one is unsuitable because
`matrix.reindex_apply` unfolds `reindex` first.
-/
lemma det_reindex_self (e : m ≃ n) (A : matrix m m R) : det (reindex e e A) = det A :=
det_submatrix_equiv_self e.symm A
/-- The determinant of a permutation matrix equals its sign. -/
@[simp] lemma det_permutation (σ : perm n) :
matrix.det (σ.to_pequiv.to_matrix : matrix n n R) = σ.sign :=
by rw [←matrix.mul_one (σ.to_pequiv.to_matrix : matrix n n R), pequiv.to_pequiv_mul_matrix,
det_permute, det_one, mul_one]
lemma det_smul (A : matrix n n R) (c : R) : det (c • A) = c ^ fintype.card n * det A :=
calc det (c • A) = det (matrix.mul (diagonal (λ _, c)) A) : by rw [smul_eq_diagonal_mul]
... = det (diagonal (λ _, c)) * det A : det_mul _ _
... = c ^ fintype.card n * det A : by simp [card_univ]
@[simp] lemma det_smul_of_tower {α} [monoid α] [distrib_mul_action α R] [is_scalar_tower α R R]
[smul_comm_class α R R] (c : α) (A : matrix n n R) :
det (c • A) = c ^ fintype.card n • det A :=
by rw [←smul_one_smul R c A, det_smul, smul_pow, one_pow, smul_mul_assoc, one_mul]
lemma det_neg (A : matrix n n R) : det (-A) = (-1) ^ fintype.card n * det A :=
by rw [←det_smul, neg_one_smul]
/-- A variant of `matrix.det_neg` with scalar multiplication by `units ℤ` instead of multiplication
by `R`. -/
lemma det_neg_eq_smul (A : matrix n n R) : det (-A) = (-1 : units ℤ) ^ fintype.card n • det A :=
by rw [←det_smul_of_tower, units.neg_smul, one_smul]
/-- Multiplying each row by a fixed `v i` multiplies the determinant by
the product of the `v`s. -/
lemma det_mul_row (v : n → R) (A : matrix n n R) :
det (of $ λ i j, v j * A i j) = (∏ i, v i) * det A :=
calc det (of $ λ i j, v j * A i j)
= det (A ⬝ diagonal v) : congr_arg det $ by { ext, simp [mul_comm] }
... = (∏ i, v i) * det A : by rw [det_mul, det_diagonal, mul_comm]
/-- Multiplying each column by a fixed `v j` multiplies the determinant by
the product of the `v`s. -/
lemma det_mul_column (v : n → R) (A : matrix n n R) :
det (of $ λ i j, v i * A i j) = (∏ i, v i) * det A :=
multilinear_map.map_smul_univ _ v A
@[simp] lemma det_pow (M : matrix m m R) (n : ℕ) : det (M ^ n) = (det M) ^ n :=
(det_monoid_hom : matrix m m R →* R).map_pow M n
section hom_map
variables {S : Type w} [comm_ring S]
lemma _root_.ring_hom.map_det (f : R →+* S) (M : matrix n n R) :
f M.det = matrix.det (f.map_matrix M) :=
by simp [matrix.det_apply', f.map_sum, f.map_prod]
lemma _root_.ring_equiv.map_det (f : R ≃+* S) (M : matrix n n R) :
f M.det = matrix.det (f.map_matrix M) :=
f.to_ring_hom.map_det _
lemma _root_.alg_hom.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T]
(f : S →ₐ[R] T) (M : matrix n n S) :
f M.det = matrix.det (f.map_matrix M) :=
f.to_ring_hom.map_det _
lemma _root_.alg_equiv.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T]
(f : S ≃ₐ[R] T) (M : matrix n n S) :
f M.det = matrix.det (f.map_matrix M) :=
f.to_alg_hom.map_det _
end hom_map
@[simp] lemma det_conj_transpose [star_ring R] (M : matrix m m R) : det (Mᴴ) = star (det M) :=
((star_ring_end R).map_det _).symm.trans $ congr_arg star M.det_transpose
section det_zero
/-!
### `det_zero` section
Prove that a matrix with a repeated column has determinant equal to zero.
-/
lemma det_eq_zero_of_row_eq_zero {A : matrix n n R} (i : n) (h : ∀ j, A i j = 0) : det A = 0 :=
(det_row_alternating : alternating_map R (n → R) R n).map_coord_zero i (funext h)
lemma det_eq_zero_of_column_eq_zero {A : matrix n n R} (j : n) (h : ∀ i, A i j = 0) : det A = 0 :=
by { rw ← det_transpose, exact det_eq_zero_of_row_eq_zero j h, }
variables {M : matrix n n R} {i j : n}
/-- If a matrix has a repeated row, the determinant will be zero. -/
theorem det_zero_of_row_eq (i_ne_j : i ≠ j) (hij : M i = M j) : M.det = 0 :=
(det_row_alternating : alternating_map R (n → R) R n).map_eq_zero_of_eq M hij i_ne_j
/-- If a matrix has a repeated column, the determinant will be zero. -/
theorem det_zero_of_column_eq (i_ne_j : i ≠ j) (hij : ∀ k, M k i = M k j) : M.det = 0 :=
by { rw [← det_transpose, det_zero_of_row_eq i_ne_j], exact funext hij }
end det_zero
lemma det_update_row_add (M : matrix n n R) (j : n) (u v : n → R) :
det (update_row M j $ u + v) = det (update_row M j u) + det (update_row M j v) :=
(det_row_alternating : alternating_map R (n → R) R n).map_add M j u v
lemma det_update_column_add (M : matrix n n R) (j : n) (u v : n → R) :
det (update_column M j $ u + v) = det (update_column M j u) + det (update_column M j v) :=
begin
rw [← det_transpose, ← update_row_transpose, det_update_row_add],
simp [update_row_transpose, det_transpose]
end
lemma det_update_row_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) :
det (update_row M j $ s • u) = s * det (update_row M j u) :=
(det_row_alternating : alternating_map R (n → R) R n).map_smul M j s u
lemma det_update_column_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) :
det (update_column M j $ s • u) = s * det (update_column M j u) :=
begin
rw [← det_transpose, ← update_row_transpose, det_update_row_smul],
simp [update_row_transpose, det_transpose]
end
lemma det_update_row_smul' (M : matrix n n R) (j : n) (s : R) (u : n → R) :
det (update_row (s • M) j u) = s ^ (fintype.card n - 1) * det (update_row M j u) :=
multilinear_map.map_update_smul _ M j s u
lemma det_update_column_smul' (M : matrix n n R) (j : n) (s : R) (u : n → R) :
det (update_column (s • M) j u) = s ^ (fintype.card n - 1) * det (update_column M j u) :=
begin
rw [← det_transpose, ← update_row_transpose, transpose_smul, det_update_row_smul'],
simp [update_row_transpose, det_transpose]
end
section det_eq
/-! ### `det_eq` section
Lemmas showing the determinant is invariant under a variety of operations.
-/
lemma det_eq_of_eq_mul_det_one {A B : matrix n n R}
(C : matrix n n R) (hC : det C = 1) (hA : A = B ⬝ C) : det A = det B :=
calc det A = det (B ⬝ C) : congr_arg _ hA
... = det B * det C : det_mul _ _
... = det B : by rw [hC, mul_one]
lemma det_eq_of_eq_det_one_mul {A B : matrix n n R}
(C : matrix n n R) (hC : det C = 1) (hA : A = C ⬝ B) : det A = det B :=
calc det A = det (C ⬝ B) : congr_arg _ hA
... = det C * det B : det_mul _ _
... = det B : by rw [hC, one_mul]
lemma det_update_row_add_self (A : matrix n n R) {i j : n} (hij : i ≠ j) :
det (update_row A i (A i + A j)) = det A :=
by simp [det_update_row_add,
det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)]
lemma det_update_column_add_self (A : matrix n n R) {i j : n} (hij : i ≠ j) :
det (update_column A i (λ k, A k i + A k j)) = det A :=
by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A],
exact det_update_row_add_self Aᵀ hij }
lemma det_update_row_add_smul_self (A : matrix n n R) {i j : n} (hij : i ≠ j) (c : R) :
det (update_row A i (A i + c • A j)) = det A :=
by simp [det_update_row_add, det_update_row_smul,
det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)]
lemma det_update_column_add_smul_self (A : matrix n n R) {i j : n} (hij : i ≠ j) (c : R) :
det (update_column A i (λ k, A k i + c • A k j)) = det A :=
by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A],
exact det_update_row_add_smul_self Aᵀ hij c }
lemma det_eq_of_forall_row_eq_smul_add_const_aux
{A B : matrix n n R} {s : finset n} : ∀ (c : n → R) (hs : ∀ i, i ∉ s → c i = 0)
(k : n) (hk : k ∉ s) (A_eq : ∀ i j, A i j = B i j + c i * B k j),
det A = det B :=
begin
revert B,
refine s.induction_on _ _,
{ intros A c hs k hk A_eq,
have : ∀ i, c i = 0,
{ intros i,
specialize hs i,
contrapose! hs,
simp [hs] },
congr,
ext i j,
rw [A_eq, this, zero_mul, add_zero], },
{ intros i s hi ih B c hs k hk A_eq,
have hAi : A i = B i + c i • B k := funext (A_eq i),
rw [@ih (update_row B i (A i)) (function.update c i 0), hAi,
det_update_row_add_smul_self],
{ exact mt (λ h, show k ∈ insert i s, from h ▸ finset.mem_insert_self _ _) hk },
{ intros i' hi',
rw function.update_apply,
split_ifs with hi'i, { refl },
{ exact hs i' (λ h, hi' ((finset.mem_insert.mp h).resolve_left hi'i)) } },
{ exact λ h, hk (finset.mem_insert_of_mem h) },
{ intros i' j',
rw [update_row_apply, function.update_apply],
split_ifs with hi'i,
{ simp [hi'i] },
rw [A_eq, update_row_ne (λ (h : k = i), hk $ h ▸ finset.mem_insert_self k s)] } }
end
/-- If you add multiples of row `B k` to other rows, the determinant doesn't change. -/
lemma det_eq_of_forall_row_eq_smul_add_const
{A B : matrix n n R} (c : n → R) (k : n) (hk : c k = 0)
(A_eq : ∀ i j, A i j = B i j + c i * B k j) :
det A = det B :=
det_eq_of_forall_row_eq_smul_add_const_aux c
(λ i, not_imp_comm.mp $ λ hi, finset.mem_erase.mpr
⟨mt (λ (h : i = k), show c i = 0, from h.symm ▸ hk) hi, finset.mem_univ i⟩)
k (finset.not_mem_erase k finset.univ) A_eq
lemma det_eq_of_forall_row_eq_smul_add_pred_aux {n : ℕ} (k : fin (n + 1)) :
∀ (c : fin n → R) (hc : ∀ (i : fin n), k < i.succ → c i = 0)
{M N : matrix (fin n.succ) (fin n.succ) R}
(h0 : ∀ j, M 0 j = N 0 j)
(hsucc : ∀ (i : fin n) j, M i.succ j = N i.succ j + c i * M i.cast_succ j),
det M = det N :=
begin
refine fin.induction _ (λ k ih, _) k;
intros c hc M N h0 hsucc,
{ congr,
ext i j,
refine fin.cases (h0 j) (λ i, _) i,
rw [hsucc, hc i (fin.succ_pos _), zero_mul, add_zero] },
set M' := update_row M k.succ (N k.succ) with hM',
have hM : M = update_row M' k.succ (M' k.succ + c k • M k.cast_succ),
{ ext i j,
by_cases hi : i = k.succ,
{ simp [hi, hM', hsucc, update_row_self] },
rw [update_row_ne hi, hM', update_row_ne hi] },
have k_ne_succ : k.cast_succ ≠ k.succ := (fin.cast_succ_lt_succ k).ne,
have M_k : M k.cast_succ = M' k.cast_succ := (update_row_ne k_ne_succ).symm,
rw [hM, M_k, det_update_row_add_smul_self M' k_ne_succ.symm, ih (function.update c k 0)],
{ intros i hi,
rw [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff] at hi,
rw function.update_apply,
split_ifs with hik, { refl },
exact hc _ (fin.succ_lt_succ_iff.mpr (lt_of_le_of_ne hi (ne.symm hik))) },
{ rwa [hM', update_row_ne (fin.succ_ne_zero _).symm] },
intros i j,
rw function.update_apply,
split_ifs with hik,
{ rw [zero_mul, add_zero, hM', hik, update_row_self] },
rw [hM', update_row_ne ((fin.succ_injective _).ne hik), hsucc],
by_cases hik2 : k < i,
{ simp [hc i (fin.succ_lt_succ_iff.mpr hik2)] },
rw update_row_ne,
apply ne_of_lt,
rwa [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff, ← not_lt]
end
/-- If you add multiples of previous rows to the next row, the determinant doesn't change. -/
lemma det_eq_of_forall_row_eq_smul_add_pred {n : ℕ}
{A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n → R)
(A_zero : ∀ j, A 0 j = B 0 j)
(A_succ : ∀ (i : fin n) j, A i.succ j = B i.succ j + c i * A i.cast_succ j) :
det A = det B :=
det_eq_of_forall_row_eq_smul_add_pred_aux (fin.last _) c
(λ i hi, absurd hi (not_lt_of_ge (fin.le_last _)))
A_zero A_succ
/-- If you add multiples of previous columns to the next columns, the determinant doesn't change. -/
lemma det_eq_of_forall_col_eq_smul_add_pred {n : ℕ}
{A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n → R)
(A_zero : ∀ i, A i 0 = B i 0)
(A_succ : ∀ i (j : fin n), A i j.succ = B i j.succ + c j * A i j.cast_succ) :
det A = det B :=
by { rw [← det_transpose A, ← det_transpose B],
exact det_eq_of_forall_row_eq_smul_add_pred c A_zero (λ i j, A_succ j i) }
end det_eq
@[simp] lemma det_block_diagonal {o : Type*} [fintype o] [decidable_eq o] (M : o → matrix n n R) :
(block_diagonal M).det = ∏ k, (M k).det :=
begin
-- Rewrite the determinants as a sum over permutations.
simp_rw [det_apply'],
-- The right hand side is a product of sums, rewrite it as a sum of products.
rw finset.prod_sum,
simp_rw [finset.mem_univ, finset.prod_attach_univ, finset.univ_pi_univ],
-- We claim that the only permutations contributing to the sum are those that
-- preserve their second component.
let preserving_snd : finset (equiv.perm (n × o)) :=
finset.univ.filter (λ σ, ∀ x, (σ x).snd = x.snd),
have mem_preserving_snd : ∀ {σ : equiv.perm (n × o)},
σ ∈ preserving_snd ↔ ∀ x, (σ x).snd = x.snd :=
λ σ, finset.mem_filter.trans ⟨λ h, h.2, λ h, ⟨finset.mem_univ _, h⟩⟩,
rw ← finset.sum_subset (finset.subset_univ preserving_snd) _,
-- And that these are in bijection with `o → equiv.perm m`.
rw (finset.sum_bij (λ (σ : ∀ (k : o), k ∈ finset.univ → equiv.perm n) _,
prod_congr_left (λ k, σ k (finset.mem_univ k))) _ _ _ _).symm,
{ intros σ _,
rw mem_preserving_snd,
rintros ⟨k, x⟩,
simp only [prod_congr_left_apply] },
{ intros σ _,
rw [finset.prod_mul_distrib, ←finset.univ_product_univ, finset.prod_product_right],
simp only [sign_prod_congr_left, units.coe_prod, int.cast_prod, block_diagonal_apply_eq,
prod_congr_left_apply] },
{ intros σ σ' _ _ eq,
ext x hx k,
simp only at eq,
have : ∀ k x, prod_congr_left (λ k, σ k (finset.mem_univ _)) (k, x) =
prod_congr_left (λ k, σ' k (finset.mem_univ _)) (k, x) :=
λ k x, by rw eq,
simp only [prod_congr_left_apply, prod.mk.inj_iff] at this,
exact (this k x).1 },
{ intros σ hσ,
rw mem_preserving_snd at hσ,
have hσ' : ∀ x, (σ⁻¹ x).snd = x.snd,
{ intro x, conv_rhs { rw [← perm.apply_inv_self σ x, hσ] } },
have mk_apply_eq : ∀ k x, ((σ (x, k)).fst, k) = σ (x, k),
{ intros k x,
ext,
{ simp only},
{ simp only [hσ] } },
have mk_inv_apply_eq : ∀ k x, ((σ⁻¹ (x, k)).fst, k) = σ⁻¹ (x, k),
{ intros k x,
conv_lhs { rw ← perm.apply_inv_self σ (x, k) },
ext,
{ simp only [apply_inv_self] },
{ simp only [hσ'] } },
refine ⟨λ k _, ⟨λ x, (σ (x, k)).fst, λ x, (σ⁻¹ (x, k)).fst, _, _⟩, _, _⟩,
{ intro x,
simp only [mk_apply_eq, inv_apply_self] },
{ intro x,
simp only [mk_inv_apply_eq, apply_inv_self] },
{ apply finset.mem_univ },
{ ext ⟨k, x⟩,
{ simp only [coe_fn_mk, prod_congr_left_apply] },
{ simp only [prod_congr_left_apply, hσ] } } },
{ intros σ _ hσ,
rw mem_preserving_snd at hσ,
obtain ⟨⟨k, x⟩, hkx⟩ := not_forall.mp hσ,
rw [finset.prod_eq_zero (finset.mem_univ (k, x)), mul_zero],
rw [← @prod.mk.eta _ _ (σ (k, x)), block_diagonal_apply_ne],
exact hkx }
end
/-- The determinant of a 2×2 block matrix with the lower-left block equal to zero is the product of
the determinants of the diagonal blocks. For the generalization to any number of blocks, see
`matrix.det_of_upper_triangular`. -/
@[simp] lemma det_from_blocks_zero₂₁
(A : matrix m m R) (B : matrix m n R) (D : matrix n n R) :
(matrix.from_blocks A B 0 D).det = A.det * D.det :=
begin
classical,
simp_rw det_apply',
convert
(sum_subset (subset_univ ((sum_congr_hom m n).range : set (perm (m ⊕ n))).to_finset) _).symm,
rw sum_mul_sum,
simp_rw univ_product_univ,
rw (sum_bij (λ (σ : perm m × perm n) _, equiv.sum_congr σ.fst σ.snd) _ _ _ _).symm,
{ intros σ₁₂ h,
simp only [],
erw [set.mem_to_finset, monoid_hom.mem_range],
use σ₁₂,
simp only [sum_congr_hom_apply] },
{ simp only [forall_prop_of_true, prod.forall, mem_univ],
intros σ₁ σ₂,
rw fintype.prod_sum_type,
simp_rw [equiv.sum_congr_apply, sum.map_inr, sum.map_inl, from_blocks_apply₁₁,
from_blocks_apply₂₂],
rw mul_mul_mul_comm,
congr,
rw [sign_sum_congr, units.coe_mul, int.cast_mul] },
{ intros σ₁ σ₂ h₁ h₂,
dsimp only [],
intro h,
have h2 : ∀ x, perm.sum_congr σ₁.fst σ₁.snd x = perm.sum_congr σ₂.fst σ₂.snd x,
{ intro x, exact congr_fun (congr_arg to_fun h) x },
simp only [sum.map_inr, sum.map_inl, perm.sum_congr_apply, sum.forall] at h2,
ext,
{ exact h2.left x },
{ exact h2.right x }},
{ intros σ hσ,
erw [set.mem_to_finset, monoid_hom.mem_range] at hσ,
obtain ⟨σ₁₂, hσ₁₂⟩ := hσ,
use σ₁₂,
rw ←hσ₁₂,
simp },
{ intros σ hσ hσn,
have h1 : ¬ (∀ x, ∃ y, sum.inl y = σ (sum.inl x)),
{ by_contradiction,
rw set.mem_to_finset at hσn,
apply absurd (mem_sum_congr_hom_range_of_perm_maps_to_inl _) hσn,
rintros x ⟨a, ha⟩,
rw [←ha], exact h a },
obtain ⟨a, ha⟩ := not_forall.mp h1,
cases hx : σ (sum.inl a) with a2 b,
{ have hn := (not_exists.mp ha) a2,
exact absurd hx.symm hn },
{ rw [finset.prod_eq_zero (finset.mem_univ (sum.inl a)), mul_zero],
rw [hx, from_blocks_apply₂₁], refl }}
end
/-- The determinant of a 2×2 block matrix with the upper-right block equal to zero is the product of
the determinants of the diagonal blocks. For the generalization to any number of blocks, see
`matrix.det_of_lower_triangular`. -/
@[simp] lemma det_from_blocks_zero₁₂
(A : matrix m m R) (C : matrix n m R) (D : matrix n n R) :
(matrix.from_blocks A 0 C D).det = A.det * D.det :=
by rw [←det_transpose, from_blocks_transpose, transpose_zero, det_from_blocks_zero₂₁,
det_transpose, det_transpose]
/-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along column 0. -/
lemma det_succ_column_zero {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) :
det A = ∑ i : fin n.succ, (-1) ^ (i : ℕ) * A i 0 *
det (A.submatrix i.succ_above fin.succ) :=
begin
rw [matrix.det_apply, finset.univ_perm_fin_succ, ← finset.univ_product_univ],
simp only [finset.sum_map, equiv.to_embedding_apply, finset.sum_product, matrix.submatrix],
refine finset.sum_congr rfl (λ i _, fin.cases _ (λ i, _) i),
{ simp only [fin.prod_univ_succ, matrix.det_apply, finset.mul_sum,
equiv.perm.decompose_fin_symm_apply_zero, fin.coe_zero, one_mul,
equiv.perm.decompose_fin.symm_sign, equiv.swap_self, if_true, id.def, eq_self_iff_true,
equiv.perm.decompose_fin_symm_apply_succ, fin.succ_above_zero, equiv.coe_refl, pow_zero,
mul_smul_comm, of_apply] },
-- `univ_perm_fin_succ` gives a different embedding of `perm (fin n)` into
-- `perm (fin n.succ)` than the determinant of the submatrix we want,
-- permute `A` so that we get the correct one.
have : (-1 : R) ^ (i : ℕ) = i.cycle_range.sign,
{ simp [fin.sign_cycle_range] },
rw [fin.coe_succ, pow_succ, this, mul_assoc, mul_assoc, mul_left_comm ↑(equiv.perm.sign _),
← det_permute, matrix.det_apply, finset.mul_sum, finset.mul_sum],
-- now we just need to move the corresponding parts to the same place
refine finset.sum_congr rfl (λ σ _, _),
rw [equiv.perm.decompose_fin.symm_sign, if_neg (fin.succ_ne_zero i)],
calc ((-1) * σ.sign : ℤ) • ∏ i', A (equiv.perm.decompose_fin.symm (fin.succ i, σ) i') i'
= ((-1) * σ.sign : ℤ) • (A (fin.succ i) 0 *
∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (σ i'))) i'.succ) :
by simp only [fin.prod_univ_succ, fin.succ_above_cycle_range,
equiv.perm.decompose_fin_symm_apply_zero, equiv.perm.decompose_fin_symm_apply_succ]
... = (-1) * (A (fin.succ i) 0 * (σ.sign : ℤ) •
∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (σ i'))) i'.succ) :
by simp only [mul_assoc, mul_comm, _root_.neg_mul, one_mul, zsmul_eq_mul, neg_inj,
neg_smul, fin.succ_above_cycle_range],
end
/-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along row 0. -/
lemma det_succ_row_zero {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) :
det A = ∑ j : fin n.succ, (-1) ^ (j : ℕ) * A 0 j *
det (A.submatrix fin.succ j.succ_above) :=
by { rw [← det_transpose A, det_succ_column_zero],
refine finset.sum_congr rfl (λ i _, _),
rw [← det_transpose],
simp only [transpose_apply, transpose_submatrix, transpose_transpose] }
/-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along row `i`. -/
lemma det_succ_row {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) (i : fin n.succ) :
det A = ∑ j : fin n.succ, (-1) ^ (i + j : ℕ) * A i j *
det (A.submatrix i.succ_above j.succ_above) :=
begin
simp_rw [pow_add, mul_assoc, ← mul_sum],
have : det A = (-1 : R) ^ (i : ℕ) * (i.cycle_range⁻¹).sign * det A,
{ calc det A = ↑((-1 : ℤˣ) ^ (i : ℕ) * (-1 : ℤˣ) ^ (i : ℕ) : ℤˣ) * det A :
by simp
... = (-1 : R) ^ (i : ℕ) * (i.cycle_range⁻¹).sign * det A :
by simp [-int.units_mul_self] },
rw [this, mul_assoc],
congr,
rw [← det_permute, det_succ_row_zero],
refine finset.sum_congr rfl (λ j _, _),
rw [mul_assoc, matrix.submatrix, matrix.submatrix],
congr,
{ rw [equiv.perm.inv_def, fin.cycle_range_symm_zero] },
{ ext i' j',
rw [equiv.perm.inv_def, fin.cycle_range_symm_succ] },
end
/-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along column `j`. -/
lemma det_succ_column {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) (j : fin n.succ) :
det A = ∑ i : fin n.succ, (-1) ^ (i + j : ℕ) * A i j *
det (A.submatrix i.succ_above j.succ_above) :=
by { rw [← det_transpose, det_succ_row _ j],
refine finset.sum_congr rfl (λ i _, _),
rw [add_comm, ← det_transpose, transpose_apply, transpose_submatrix, transpose_transpose] }
/-- Determinant of 0x0 matrix -/
@[simp] lemma det_fin_zero {A : matrix (fin 0) (fin 0) R} : det A = 1 :=
det_is_empty
/-- Determinant of 1x1 matrix -/
lemma det_fin_one (A : matrix (fin 1) (fin 1) R) : det A = A 0 0 := det_unique A
lemma det_fin_one_of (a : R) : det !![a] = a := det_fin_one _
/-- Determinant of 2x2 matrix -/
lemma det_fin_two (A : matrix (fin 2) (fin 2) R) :
det A = A 0 0 * A 1 1 - A 0 1 * A 1 0 :=
begin
simp [matrix.det_succ_row_zero, fin.sum_univ_succ],
ring
end
@[simp] lemma det_fin_two_of (a b c d : R) :
matrix.det !![a, b; c, d] = a * d - b * c :=
det_fin_two _
/-- Determinant of 3x3 matrix -/
lemma det_fin_three (A : matrix (fin 3) (fin 3) R) :
det A = A 0 0 * A 1 1 * A 2 2 - A 0 0 * A 1 2 * A 2 1 - A 0 1 * A 1 0 * A 2 2
+ A 0 1 * A 1 2 * A 2 0 + A 0 2 * A 1 0 * A 2 1 - A 0 2 * A 1 1 * A 2 0 :=
begin
simp [matrix.det_succ_row_zero, fin.sum_univ_succ],
ring
end
end matrix
|
7c509ab3ec5acba10f55bdc3c6cf04637f2d8254 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/group_theory/subgroup/pointwise.lean | 0c597042b6136dcf28b86dceb659247bf1d29ca0 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 8,219 | 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 group_theory.subgroup.basic
import group_theory.submonoid.pointwise
/-! # Pointwise instances on `subgroup` and `add_subgroup`s
This file provides the actions
* `subgroup.pointwise_mul_action`
* `add_subgroup.pointwise_mul_action`
which matches the action of `mul_action_set`.
These actions are available in the `pointwise` locale.
## Implementation notes
This file is almost identical to `group_theory/submonoid/pointwise.lean`. Where possible, try to
keep them in sync.
-/
variables {α : Type*} {G : Type*} {A : Type*} [group G] [add_group A]
namespace subgroup
section monoid
variables [monoid α] [mul_distrib_mul_action α G]
/-- The action on a subgroup corresponding to applying the action to every element.
This is available as an instance in the `pointwise` locale. -/
protected def pointwise_mul_action : mul_action α (subgroup G) :=
{ smul := λ a S, S.map (mul_distrib_mul_action.to_monoid_End _ _ a),
one_smul := λ S, (congr_arg (λ f, S.map f) (monoid_hom.map_one _)).trans S.map_id,
mul_smul := λ a₁ a₂ S,
(congr_arg (λ f, S.map f) (monoid_hom.map_mul _ _ _)).trans (S.map_map _ _).symm,}
localized "attribute [instance] subgroup.pointwise_mul_action" in pointwise
open_locale pointwise
lemma pointwise_smul_def {a : α} (S : subgroup G) :
a • S = S.map (mul_distrib_mul_action.to_monoid_End _ _ a) := rfl
@[simp] lemma coe_pointwise_smul (a : α) (S : subgroup G) : ↑(a • S) = a • (S : set G) := rfl
@[simp] lemma pointwise_smul_to_submonoid (a : α) (S : subgroup G) :
(a • S).to_submonoid = a • S.to_submonoid := rfl
lemma smul_mem_pointwise_smul (m : G) (a : α) (S : subgroup G) : m ∈ S → a • m ∈ a • S :=
(set.smul_mem_smul_set : _ → _ ∈ a • (S : set G))
lemma mem_smul_pointwise_iff_exists (m : G) (a : α) (S : subgroup G) :
m ∈ a • S ↔ ∃ (s : G), s ∈ S ∧ a • s = m :=
(set.mem_smul_set : m ∈ a • (S : set G) ↔ _)
instance pointwise_central_scalar [mul_distrib_mul_action αᵐᵒᵖ G] [is_central_scalar α G] :
is_central_scalar α (subgroup G) :=
⟨λ a S, congr_arg (λ f, S.map f) $ monoid_hom.ext $ by exact op_smul_eq_smul _⟩
end monoid
section group
variables [group α] [mul_distrib_mul_action α G]
open_locale pointwise
@[simp] lemma smul_mem_pointwise_smul_iff {a : α} {S : subgroup G} {x : G} :
a • x ∈ a • S ↔ x ∈ S :=
smul_mem_smul_set_iff
lemma mem_pointwise_smul_iff_inv_smul_mem {a : α} {S : subgroup G} {x : G} :
x ∈ a • S ↔ a⁻¹ • x ∈ S :=
mem_smul_set_iff_inv_smul_mem
lemma mem_inv_pointwise_smul_iff {a : α} {S : subgroup G} {x : G} : x ∈ a⁻¹ • S ↔ a • x ∈ S :=
mem_inv_smul_set_iff
@[simp] lemma pointwise_smul_le_pointwise_smul_iff {a : α} {S T : subgroup G} :
a • S ≤ a • T ↔ S ≤ T :=
set_smul_subset_set_smul_iff
lemma pointwise_smul_subset_iff {a : α} {S T : subgroup G} : a • S ≤ T ↔ S ≤ a⁻¹ • T :=
set_smul_subset_iff
lemma subset_pointwise_smul_iff {a : α} {S T : subgroup G} : S ≤ a • T ↔ a⁻¹ • S ≤ T :=
subset_set_smul_iff
/-- Applying a `mul_distrib_mul_action` results in an isomorphic subgroup -/
@[simps] def equiv_smul (a : α) (H : subgroup G) : H ≃* (a • H : subgroup G) :=
(mul_distrib_mul_action.to_mul_equiv G a).subgroup_map H
end group
section group_with_zero
variables [group_with_zero α] [mul_distrib_mul_action α G]
open_locale pointwise
@[simp] lemma smul_mem_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : subgroup G)
(x : G) : a • x ∈ a • S ↔ x ∈ S :=
smul_mem_smul_set_iff₀ ha (S : set G) x
lemma mem_pointwise_smul_iff_inv_smul_mem₀ {a : α} (ha : a ≠ 0) (S : subgroup G) (x : G) :
x ∈ a • S ↔ a⁻¹ • x ∈ S :=
mem_smul_set_iff_inv_smul_mem₀ ha (S : set G) x
lemma mem_inv_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : subgroup G) (x : G) :
x ∈ a⁻¹ • S ↔ a • x ∈ S :=
mem_inv_smul_set_iff₀ ha (S : set G) x
@[simp] lemma pointwise_smul_le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : subgroup G} :
a • S ≤ a • T ↔ S ≤ T :=
set_smul_subset_set_smul_iff₀ ha
lemma pointwise_smul_le_iff₀ {a : α} (ha : a ≠ 0) {S T : subgroup G} : a • S ≤ T ↔ S ≤ a⁻¹ • T :=
set_smul_subset_iff₀ ha
lemma le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : subgroup G} : S ≤ a • T ↔ a⁻¹ • S ≤ T :=
subset_set_smul_iff₀ ha
end group_with_zero
end subgroup
namespace add_subgroup
section monoid
variables [monoid α] [distrib_mul_action α A]
/-- The action on an additive subgroup corresponding to applying the action to every element.
This is available as an instance in the `pointwise` locale. -/
protected def pointwise_mul_action : mul_action α (add_subgroup A) :=
{ smul := λ a S, S.map (distrib_mul_action.to_add_monoid_End _ _ a),
one_smul := λ S, (congr_arg (λ f, S.map f) (monoid_hom.map_one _)).trans S.map_id,
mul_smul := λ a₁ a₂ S,
(congr_arg (λ f, S.map f) (monoid_hom.map_mul _ _ _)).trans (S.map_map _ _).symm,}
localized "attribute [instance] add_subgroup.pointwise_mul_action" in pointwise
open_locale pointwise
@[simp] lemma coe_pointwise_smul (a : α) (S : add_subgroup A) : ↑(a • S) = a • (S : set A) := rfl
@[simp] lemma pointwise_smul_to_add_submonoid (a : α) (S : add_subgroup A) :
(a • S).to_add_submonoid = a • S.to_add_submonoid := rfl
lemma smul_mem_pointwise_smul (m : A) (a : α) (S : add_subgroup A) : m ∈ S → a • m ∈ a • S :=
(set.smul_mem_smul_set : _ → _ ∈ a • (S : set A))
lemma mem_smul_pointwise_iff_exists (m : A) (a : α) (S : add_subgroup A) :
m ∈ a • S ↔ ∃ (s : A), s ∈ S ∧ a • s = m :=
(set.mem_smul_set : m ∈ a • (S : set A) ↔ _)
instance pointwise_central_scalar [distrib_mul_action αᵐᵒᵖ A] [is_central_scalar α A] :
is_central_scalar α (add_subgroup A) :=
⟨λ a S, congr_arg (λ f, S.map f) $ add_monoid_hom.ext $ by exact op_smul_eq_smul _⟩
end monoid
section group
variables [group α] [distrib_mul_action α A]
open_locale pointwise
@[simp] lemma smul_mem_pointwise_smul_iff {a : α} {S : add_subgroup A} {x : A} :
a • x ∈ a • S ↔ x ∈ S :=
smul_mem_smul_set_iff
lemma mem_pointwise_smul_iff_inv_smul_mem {a : α} {S : add_subgroup A} {x : A} :
x ∈ a • S ↔ a⁻¹ • x ∈ S :=
mem_smul_set_iff_inv_smul_mem
lemma mem_inv_pointwise_smul_iff {a : α} {S : add_subgroup A} {x : A} : x ∈ a⁻¹ • S ↔ a • x ∈ S :=
mem_inv_smul_set_iff
@[simp] lemma pointwise_smul_le_pointwise_smul_iff {a : α} {S T : add_subgroup A} :
a • S ≤ a • T ↔ S ≤ T :=
set_smul_subset_set_smul_iff
lemma pointwise_smul_le_iff {a : α} {S T : add_subgroup A} : a • S ≤ T ↔ S ≤ a⁻¹ • T :=
set_smul_subset_iff
lemma le_pointwise_smul_iff {a : α} {S T : add_subgroup A} : S ≤ a • T ↔ a⁻¹ • S ≤ T :=
subset_set_smul_iff
end group
section group_with_zero
variables [group_with_zero α] [distrib_mul_action α A]
open_locale pointwise
@[simp] lemma smul_mem_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : add_subgroup A)
(x : A) : a • x ∈ a • S ↔ x ∈ S :=
smul_mem_smul_set_iff₀ ha (S : set A) x
lemma mem_pointwise_smul_iff_inv_smul_mem₀ {a : α} (ha : a ≠ 0) (S : add_subgroup A) (x : A) :
x ∈ a • S ↔ a⁻¹ • x ∈ S :=
mem_smul_set_iff_inv_smul_mem₀ ha (S : set A) x
lemma mem_inv_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : add_subgroup A) (x : A) :
x ∈ a⁻¹ • S ↔ a • x ∈ S :=
mem_inv_smul_set_iff₀ ha (S : set A) x
@[simp] lemma pointwise_smul_le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : add_subgroup A} :
a • S ≤ a • T ↔ S ≤ T :=
set_smul_subset_set_smul_iff₀ ha
lemma pointwise_smul_le_iff₀ {a : α} (ha : a ≠ 0) {S T : add_subgroup A} :
a • S ≤ T ↔ S ≤ a⁻¹ • T :=
set_smul_subset_iff₀ ha
lemma le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : add_subgroup A} :
S ≤ a • T ↔ a⁻¹ • S ≤ T :=
subset_set_smul_iff₀ ha
end group_with_zero
end add_subgroup
|
43422669f2094f5ec19b0fd441318ea316822ba0 | 1b8f093752ba748c5ca0083afef2959aaa7dace5 | /src/category_theory/adjunctions/initial.lean | 1c340d253bb8b0051c6bef12cf0ce6aa005a72f4 | [] | no_license | khoek/lean-category-theory | 7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386 | 63dcb598e9270a3e8b56d1769eb4f825a177cd95 | refs/heads/master | 1,585,251,725,759 | 1,539,344,445,000 | 1,539,344,445,000 | 145,281,070 | 0 | 0 | null | 1,534,662,376,000 | 1,534,662,376,000 | null | UTF-8 | Lean | false | false | 760 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.adjunctions
import category_theory.universal.comma_categories
open category_theory
open category_theory.comma
namespace categories.adjunctions
-- PROJECT
-- def unit_component_in_slice_category
-- {C D : Category} {L : Functor C D} {R : Functor D C} (A : Adjunction L R) (X : C.Obj)
-- : (SliceCategory X).Obj := sorry
-- def unit_components_initial_in_slice_category
-- {C D : Category} {L : Functor C D} {R : Functor D C} (A : Adjunction L R) (X : C.Obj)
-- : is_initial (unit_component_in_slice_category A X) := sorry
-- and so on
end categories.adjunctions |
d9cc55c72741f1f308a1d0e568096c2893ac242f | 0c1546a496eccfb56620165cad015f88d56190c5 | /library/init/algebra/functions.lean | 36843005ce2c34efb2160353eee77becebfa8723 | [
"Apache-2.0"
] | permissive | Solertis/lean | 491e0939957486f664498fbfb02546e042699958 | 84188c5aa1673fdf37a082b2de8562dddf53df3f | refs/heads/master | 1,610,174,257,606 | 1,486,263,620,000 | 1,486,263,620,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,297 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
-/
prelude
import init.algebra.ordered_field
universe variables u
definition min {α : Type u} [decidable_linear_order α] (a b : α) : α := if a ≤ b then a else b
definition max {α : Type u} [decidable_linear_order α] (a b : α) : α := if a ≤ b then b else a
definition abs {α : Type u} [decidable_linear_ordered_comm_group α] (a : α) : α := max a (-a)
section
open decidable tactic
variables {α : Type u} [decidable_linear_order α]
private meta def min_tac_step : tactic unit :=
solve1 $ intros
>> `[unfold min max]
>> try `[simp_using_hs [if_pos, if_neg]]
>> try `[apply le_refl]
>> try `[apply le_of_not_le, assumption]
meta def tactic.interactive.min_tac (a b : interactive.types.qexpr) : tactic unit :=
`[apply @by_cases (%%a ≤ %%b), repeat {min_tac_step}]
lemma min_le_left (a b : α) : min a b ≤ a :=
by min_tac a b
lemma min_le_right (a b : α) : min a b ≤ b :=
by min_tac a b
lemma le_min {a b c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) : c ≤ min a b :=
by min_tac a b
lemma le_max_left (a b : α) : a ≤ max a b :=
by min_tac a b
lemma le_max_right (a b : α) : b ≤ max a b :=
by min_tac a b
lemma max_le {a b c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) : max a b ≤ c :=
by min_tac a b
lemma eq_min {a b c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) (h₃ : ∀{d}, d ≤ a → d ≤ b → d ≤ c) : c = min a b :=
le_antisymm (le_min h₁ h₂) (h₃ (min_le_left a b) (min_le_right a b))
lemma min_comm (a b : α) : min a b = min b a :=
eq_min (min_le_right a b) (min_le_left a b) (λ c h₁ h₂, le_min h₂ h₁)
lemma min_assoc (a b c : α) : min (min a b) c = min a (min b c) :=
begin
apply eq_min,
{ apply le_trans, apply min_le_left, apply min_le_left },
{ apply le_min, apply le_trans, apply min_le_left, apply min_le_right, apply min_le_right },
{ intros d h₁ h₂, apply le_min, apply le_min h₁, apply le_trans h₂, apply min_le_left,
apply le_trans h₂, apply min_le_right }
end
lemma min_left_comm : ∀ (a b c : α), min a (min b c) = min b (min a c) :=
left_comm (@min α _) (@min_comm α _) (@min_assoc α _)
@[simp]
lemma min_self (a : α) : min a a = a :=
by min_tac a a
@[ematch]
lemma min_eq_left {a b : α} (h : a ≤ b) : min a b = a :=
begin apply eq.symm, apply eq_min (le_refl _) h, intros, assumption end
@[ematch]
lemma min_eq_right {a b : α} (h : b ≤ a) : min a b = b :=
eq.subst (min_comm b a) (min_eq_left h)
lemma eq_max {a b c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) (h₃ : ∀{d}, a ≤ d → b ≤ d → c ≤ d) : c = max a b :=
le_antisymm (h₃ (le_max_left a b) (le_max_right a b)) (max_le h₁ h₂)
lemma max_comm (a b : α) : max a b = max b a :=
eq_max (le_max_right a b) (le_max_left a b) (λ c h₁ h₂, max_le h₂ h₁)
lemma max_assoc (a b c : α) : max (max a b) c = max a (max b c) :=
begin
apply eq_max,
{ apply le_trans, apply le_max_left a b, apply le_max_left },
{ apply max_le, apply le_trans, apply le_max_right a b, apply le_max_left, apply le_max_right },
{ intros d h₁ h₂, apply max_le, apply max_le h₁, apply le_trans (le_max_left _ _) h₂,
apply le_trans (le_max_right _ _) h₂}
end
lemma max_left_comm : ∀ (a b c : α), max a (max b c) = max b (max a c) :=
left_comm (@max α _) (@max_comm α _) (@max_assoc α _)
@[simp]
lemma max_self (a : α) : max a a = a :=
by min_tac a a
lemma max_eq_left {a b : α} (h : b ≤ a) : max a b = a :=
begin apply eq.symm, apply eq_max (le_refl _) h, intros, assumption end
lemma max_eq_right {a b : α} (h : a ≤ b) : max a b = b :=
eq.subst (max_comm b a) (max_eq_left h)
/- these rely on lt_of_lt -/
lemma min_eq_left_of_lt {a b : α} (h : a < b) : min a b = a :=
min_eq_left (le_of_lt h)
lemma min_eq_right_of_lt {a b : α} (h : b < a) : min a b = b :=
min_eq_right (le_of_lt h)
lemma max_eq_left_of_lt {a b : α} (h : b < a) : max a b = a :=
max_eq_left (le_of_lt h)
lemma max_eq_right_of_lt {a b : α} (h : a < b) : max a b = b :=
max_eq_right (le_of_lt h)
/- these use the fact that it is a linear ordering -/
lemma lt_min {a b c : α} (h₁ : a < b) (h₂ : a < c) : a < min b c :=
or.elim (le_or_gt b c)
(assume h : b ≤ c, by min_tac b c)
(assume h : b > c, by min_tac b c)
lemma max_lt {a b c : α} (h₁ : a < c) (h₂ : b < c) : max a b < c :=
or.elim (le_or_gt a b)
(assume h : a ≤ b, by min_tac a b)
(assume h : a > b, by min_tac a b)
end
section
variables {α : Type u} [decidable_linear_ordered_cancel_comm_monoid α]
lemma min_add_add_left (a b c : α) : min (a + b) (a + c) = a + min b c :=
eq.symm (eq_min
(show a + min b c ≤ a + b, from add_le_add_left (min_le_left _ _) _)
(show a + min b c ≤ a + c, from add_le_add_left (min_le_right _ _) _)
(take d,
suppose d ≤ a + b,
suppose d ≤ a + c,
decidable.by_cases
(suppose b ≤ c, by rwa [min_eq_left this])
(suppose ¬ b ≤ c, by rwa [min_eq_right (le_of_lt (lt_of_not_ge this))])))
lemma min_add_add_right (a b c : α) : min (a + c) (b + c) = min a b + c :=
begin rw [add_comm a c, add_comm b c, add_comm _ c], apply min_add_add_left end
lemma max_add_add_left (a b c : α) : max (a + b) (a + c) = a + max b c :=
eq.symm (eq_max
(add_le_add_left (le_max_left _ _) _)
(add_le_add_left (le_max_right _ _) _)
(take d,
suppose a + b ≤ d,
suppose a + c ≤ d,
decidable.by_cases
(suppose b ≤ c, by rwa [max_eq_right this])
(suppose ¬ b ≤ c, by rwa [max_eq_left (le_of_lt (lt_of_not_ge this))])))
lemma max_add_add_right (a b c : α) : max (a + c) (b + c) = max a b + c :=
begin rw [add_comm a c, add_comm b c, add_comm _ c], apply max_add_add_left end
end
section
variables {α : Type u} [decidable_linear_ordered_comm_group α]
lemma max_neg_neg (a b : α) : max (-a) (-b) = - min a b :=
eq.symm (eq_max
(show -a ≤ -(min a b), from neg_le_neg $ min_le_left a b)
(show -b ≤ -(min a b), from neg_le_neg $ min_le_right a b)
(take d,
assume H₁ : -a ≤ d,
assume H₂ : -b ≤ d,
have H : -d ≤ min a b,
from le_min (neg_le_of_neg_le H₁) (neg_le_of_neg_le H₂),
show -(min a b) ≤ d, from neg_le_of_neg_le H))
lemma min_eq_neg_max_neg_neg (a b : α) : min a b = - max (-a) (-b) :=
by rw [max_neg_neg, neg_neg]
lemma min_neg_neg (a b : α) : min (-a) (-b) = - max a b :=
by rw [min_eq_neg_max_neg_neg, neg_neg, neg_neg]
lemma max_eq_neg_min_neg_neg (a b : α) : max a b = - min (-a) (-b) :=
by rw [min_neg_neg, neg_neg]
end
section decidable_linear_ordered_comm_group
variables {α : Type u} [decidable_linear_ordered_comm_group α]
lemma abs_of_nonneg {a : α} (h : a ≥ 0) : abs a = a :=
have h' : -a ≤ a, from le_trans (neg_nonpos_of_nonneg h) h,
max_eq_left h'
lemma abs_of_pos {a : α} (h : a > 0) : abs a = a :=
abs_of_nonneg (le_of_lt h)
lemma abs_of_nonpos {a : α} (h : a ≤ 0) : abs a = -a :=
have h' : a ≤ -a, from le_trans h (neg_nonneg_of_nonpos h),
max_eq_right h'
lemma abs_of_neg {a : α} (h : a < 0) : abs a = -a :=
abs_of_nonpos (le_of_lt h)
lemma abs_zero : abs 0 = (0:α) :=
abs_of_nonneg (le_refl _)
lemma abs_neg (a : α) : abs (-a) = abs a :=
begin unfold abs, rw [max_comm, neg_neg] end
lemma abs_pos_of_pos {a : α} (h : a > 0) : abs a > 0 :=
by rwa (abs_of_pos h)
lemma abs_pos_of_neg {a : α} (h : a < 0) : abs a > 0 :=
abs_neg a ▸ abs_pos_of_pos (neg_pos_of_neg h)
lemma abs_sub (a b : α) : abs (a - b) = abs (b - a) :=
by rw [-neg_sub, abs_neg]
lemma ne_zero_of_abs_ne_zero {a : α} (h : abs a ≠ 0) : a ≠ 0 :=
assume ha, h (eq.symm ha ▸ abs_zero)
/- these assume a linear order -/
lemma eq_zero_of_neg_eq {a : α} (h : -a = a) : a = 0 :=
match lt_trichotomy a 0 with
| or.inl h₁ :=
have a > 0, from h ▸ neg_pos_of_neg h₁,
absurd h₁ (lt_asymm this)
| or.inr (or.inl h₁) := h₁
| or.inr (or.inr h₁) :=
have a < 0, from h ▸ neg_neg_of_pos h₁,
absurd h₁ (lt_asymm this)
end
lemma abs_nonneg (a : α) : abs a ≥ 0 :=
or.elim (le_total 0 a)
(assume h : 0 ≤ a, by rwa (abs_of_nonneg h))
(assume h : a ≤ 0, calc
0 ≤ -a : neg_nonneg_of_nonpos h
... = abs a : eq.symm (abs_of_nonpos h))
lemma abs_abs (a : α) : abs (abs a) = abs a :=
abs_of_nonneg $ abs_nonneg a
lemma le_abs_self (a : α) : a ≤ abs a :=
or.elim (le_total 0 a)
(assume h : 0 ≤ a,
begin rw [abs_of_nonneg h], apply le_refl end)
(assume h : a ≤ 0, le_trans h $ abs_nonneg a)
lemma neg_le_abs_self (a : α) : -a ≤ abs a :=
abs_neg a ▸ le_abs_self (-a)
lemma eq_zero_of_abs_eq_zero {a : α} (h : abs a = 0) : a = 0 :=
have h₁ : a ≤ 0, from h ▸ le_abs_self a,
have h₂ : -a ≤ 0, from h ▸ abs_neg a ▸ le_abs_self (-a),
le_antisymm h₁ (nonneg_of_neg_nonpos h₂)
lemma eq_of_abs_sub_eq_zero {a b : α} (h : abs (a - b) = 0) : a = b :=
have a - b = 0, from eq_zero_of_abs_eq_zero h,
show a = b, from eq_of_sub_eq_zero this
lemma abs_pos_of_ne_zero {a : α} (h : a ≠ 0) : abs a > 0 :=
or.elim (lt_or_gt_of_ne h) abs_pos_of_neg abs_pos_of_pos
lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (abs a) :=
or.elim (le_total 0 a)
(assume h : 0 ≤ a, eq.symm (abs_of_nonneg h) ▸ h1)
(assume h : a ≤ 0, eq.symm (abs_of_nonpos h) ▸ h2)
lemma abs_le_of_le_of_neg_le {a b : α} (h1 : a ≤ b) (h2 : -a ≤ b) : abs a ≤ b :=
abs_by_cases (λ x : α, x ≤ b) h1 h2
lemma abs_lt_of_lt_of_neg_lt {a b : α} (h1 : a < b) (h2 : -a < b) : abs a < b :=
abs_by_cases (λ x : α, x < b) h1 h2
private lemma aux1 {a b : α} (h1 : a + b ≥ 0) (h2 : a ≥ 0) : abs (a + b) ≤ abs a + abs b :=
decidable.by_cases
(assume h3 : b ≥ 0, calc
abs (a + b) ≤ abs (a + b) : by apply le_refl
... = a + b : by rw (abs_of_nonneg h1)
... = abs a + b : by rw (abs_of_nonneg h2)
... = abs a + abs b : by rw (abs_of_nonneg h3))
(assume h3 : ¬ b ≥ 0,
have h4 : b ≤ 0, from le_of_lt (lt_of_not_ge h3),
calc
abs (a + b) = a + b : by rw (abs_of_nonneg h1)
... = abs a + b : by rw (abs_of_nonneg h2)
... ≤ abs a + 0 : add_le_add_left h4 _
... ≤ abs a + -b : add_le_add_left (neg_nonneg_of_nonpos h4) _
... = abs a + abs b : by rw (abs_of_nonpos h4))
private lemma aux2 {a b : α} (h1 : a + b ≥ 0) : abs (a + b) ≤ abs a + abs b :=
or.elim (le_total b 0)
(assume h2 : b ≤ 0,
have h3 : ¬ a < 0, from
assume h4 : a < 0,
have h5 : a + b < 0,
begin
note aux := add_lt_add_of_lt_of_le h4 h2,
rwa [add_zero] at aux
end,
not_lt_of_ge h1 h5,
aux1 h1 (le_of_not_gt h3))
(assume h2 : 0 ≤ b,
begin
assert h3 : abs (b + a) ≤ abs b + abs a,
begin
rw add_comm at h1,
exact aux1 h1 h2
end,
rw [add_comm, add_comm (abs a)],
exact h3
end)
lemma abs_add_le_abs_add_abs (a b : α) : abs (a + b) ≤ abs a + abs b :=
or.elim (le_total 0 (a + b))
(assume h2 : 0 ≤ a + b, aux2 h2)
(assume h2 : a + b ≤ 0,
have h3 : -a + -b = -(a + b), by rw neg_add,
have h4 : -(a + b) ≥ 0, from neg_nonneg_of_nonpos h2,
have h5 : -a + -b ≥ 0, begin rw -h3 at h4, exact h4 end,
calc
abs (a + b) = abs (-a + -b) : by rw [-abs_neg, neg_add]
... ≤ abs (-a) + abs (-b) : aux2 h5
... = abs a + abs b : by rw [abs_neg, abs_neg])
lemma abs_sub_abs_le_abs_sub (a b : α) : abs a - abs b ≤ abs (a - b) :=
have h1 : abs a - abs b + abs b ≤ abs (a - b) + abs b, from
calc
abs a - abs b + abs b = abs a : by rw sub_add_cancel
... = abs (a - b + b) : by rw sub_add_cancel
... ≤ abs (a - b) + abs b : by apply abs_add_le_abs_add_abs,
le_of_add_le_add_right h1
lemma abs_sub_le (a b c : α) : abs (a - c) ≤ abs (a - b) + abs (b - c) :=
calc
abs (a - c) = abs (a - b + (b - c)) : by rw [sub_eq_add_neg, sub_eq_add_neg, sub_eq_add_neg,
add_assoc, neg_add_cancel_left]
... ≤ abs (a - b) + abs (b - c) : by apply abs_add_le_abs_add_abs
lemma abs_add_three (a b c : α) : abs (a + b + c) ≤ abs a + abs b + abs c :=
begin
apply le_trans,
apply abs_add_le_abs_add_abs,
apply le_trans,
apply add_le_add_right,
apply abs_add_le_abs_add_abs,
apply le_refl
end
lemma dist_bdd_within_interval {a b lb ub : α} (h : lb < ub) (hal : lb ≤ a) (hau : a ≤ ub)
(hbl : lb ≤ b) (hbu : b ≤ ub) : abs (a - b) ≤ ub - lb :=
begin
cases (decidable.em (b ≤ a)) with hba hba,
rw (abs_of_nonneg (sub_nonneg_of_le hba)),
apply sub_le_sub,
apply hau,
apply hbl,
rw [abs_of_neg (sub_neg_of_lt (lt_of_not_ge hba)), neg_sub],
apply sub_le_sub,
apply hbu,
apply hal
end
end decidable_linear_ordered_comm_group
section decidable_linear_ordered_comm_ring
variables {α : Type u} [decidable_linear_ordered_comm_ring α]
lemma abs_mul (a b : α) : abs (a * b) = abs a * abs b :=
or.elim (le_total 0 a)
(assume h1 : 0 ≤ a,
or.elim (le_total 0 b)
(assume h2 : 0 ≤ b,
calc
abs (a * b) = a * b : abs_of_nonneg (mul_nonneg h1 h2)
... = abs a * b : by rw (abs_of_nonneg h1)
... = abs a * abs b : by rw (abs_of_nonneg h2))
(assume h2 : b ≤ 0,
calc
abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos h1 h2)
... = a * -b : by rw neg_mul_eq_mul_neg
... = abs a * -b : by rw (abs_of_nonneg h1)
... = abs a * abs b : by rw (abs_of_nonpos h2)))
(assume h1 : a ≤ 0,
or.elim (le_total 0 b)
(assume h2 : 0 ≤ b,
calc
abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg h1 h2)
... = -a * b : by rw neg_mul_eq_neg_mul
... = abs a * b : by rw (abs_of_nonpos h1)
... = abs a * abs b : by rw (abs_of_nonneg h2))
(assume h2 : b ≤ 0,
calc
abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos h1 h2)
... = -a * -b : by rw neg_mul_neg
... = abs a * -b : by rw (abs_of_nonpos h1)
... = abs a * abs b : by rw (abs_of_nonpos h2)))
lemma abs_mul_abs_self (a : α) : abs a * abs a = a * a :=
abs_by_cases (λ x, x * x = a * a) rfl (neg_mul_neg a a)
lemma abs_mul_self (a : α) : abs (a * a) = a * a :=
by rw [abs_mul, abs_mul_abs_self]
lemma sub_le_of_abs_sub_le_left {a b c : α} (h : abs (a - b) ≤ c) : b - c ≤ a :=
if hz : 0 ≤ a - b then
(calc
a ≥ b : le_of_sub_nonneg hz
... ≥ b - c : sub_le_self _ (le_trans (abs_nonneg _) h))
else
have habs : b - a ≤ c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h,
have habs' : b ≤ c + a, from le_add_of_sub_right_le habs,
sub_left_le_of_le_add habs'
lemma sub_le_of_abs_sub_le_right {a b c : α} (h : abs (a - b) ≤ c) : a - c ≤ b :=
sub_le_of_abs_sub_le_left (abs_sub a b ▸ h)
lemma sub_lt_of_abs_sub_lt_left {a b c : α} (h : abs (a - b) < c) : b - c < a :=
if hz : 0 ≤ a - b then
(calc
a ≥ b : le_of_sub_nonneg hz
... > b - c : sub_lt_self _ (lt_of_le_of_lt (abs_nonneg _) h))
else
have habs : b - a < c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h,
have habs' : b < c + a, from lt_add_of_sub_right_lt habs,
sub_left_lt_of_lt_add habs'
lemma sub_lt_of_abs_sub_lt_right {a b c : α} (h : abs (a - b) < c) : a - c < b :=
sub_lt_of_abs_sub_lt_left (abs_sub a b ▸ h)
lemma abs_sub_square (a b : α) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b :=
begin
rw abs_mul_abs_self,
simp [left_distrib, right_distrib]
end
lemma eq_zero_of_mul_self_add_mul_self_eq_zero {x y : α} (h : x * x + y * y = 0) : x = 0 :=
have x * x ≤ (0 : α), from calc
x * x ≤ x * x + y * y : le_add_of_nonneg_right (mul_self_nonneg y)
... = 0 : h,
eq_zero_of_mul_self_eq_zero (le_antisymm this (mul_self_nonneg x))
lemma abs_abs_sub_abs_le_abs_sub (a b : α) : abs (abs a - abs b) ≤ abs (a - b) :=
begin
apply nonneg_le_nonneg_of_squares_le,
repeat {apply abs_nonneg},
repeat {rw abs_sub_square},
repeat {rw abs_abs},
repeat {rw abs_mul_abs_self},
apply sub_le_sub_left,
repeat {rw mul_assoc},
apply mul_le_mul_of_nonneg_left,
rw -abs_mul,
apply le_abs_self,
apply le_of_lt,
apply add_pos,
apply zero_lt_one,
apply zero_lt_one
end
end decidable_linear_ordered_comm_ring
section discrete_linear_ordered_field
variables {α : Type u} [discrete_linear_ordered_field α]
lemma abs_div (a b : α) : abs (a / b) = abs a / abs b :=
decidable.by_cases
(suppose h : b = 0, by rw [h, abs_zero, div_zero, div_zero, abs_zero])
(suppose h : b ≠ 0,
have h₁ : abs b ≠ 0, from
assume h₂, h (eq_zero_of_abs_eq_zero h₂),
eq_div_of_mul_eq _ _ h₁
(show abs (a / b) * abs b = abs a, by rw [-abs_mul, div_mul_cancel _ h]))
lemma abs_one_div (a : α) : abs (1 / a) = 1 / abs a :=
by rw [abs_div, abs_of_nonneg (zero_le_one : 1 ≥ (0 : α))]
end discrete_linear_ordered_field
|
60033c1a1fe9c6ae8fe8ffb4809665b44628ff8d | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/arity1.lean | 84f1e4be85b8913cb658301bb7ee76cef9add5c7 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 410 | lean | open tactic decidable
definition foo (A B : Type) := A → B
definition boo (c : bool) :=
bool.cond c nat bool
definition bla (a : nat) : boo (to_bool (a > 0)) → foo nat nat :=
λ v x, a + x
example : true :=
by do
bla ← mk_const `bla,
infer_type bla >>= trace,
n ← get_arity bla,
trace ("n arity: " ++ to_string n),
when (n ≠ 3) (fail "bla is expected to have arity 3"),
constructor
|
356e22f9b846a9655296a206df909f86050fd0d6 | bdb33f8b7ea65f7705fc342a178508e2722eb851 | /data/encodable.lean | d5069f95784c7aa4c66468ef40bcdb6827ecfdb4 | [
"Apache-2.0"
] | permissive | rwbarton/mathlib | 939ae09bf8d6eb1331fc2f7e067d39567e10e33d | c13c5ea701bb1eec057e0a242d9f480a079105e9 | refs/heads/master | 1,584,015,335,862 | 1,524,142,167,000 | 1,524,142,167,000 | 130,614,171 | 0 | 0 | Apache-2.0 | 1,548,902,667,000 | 1,524,437,371,000 | Lean | UTF-8 | Lean | false | false | 10,050 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Mario Carneiro
Type class for encodable Types.
Note that every encodable Type is countable.
-/
import data.fintype data.list data.list.perm data.list.sort
data.equiv data.nat.basic logic.function
open option list nat function
/-- An encodable type is a "constructively countable" type. This is where
we have an explicit injection `encode : α → nat` and a partial inverse
`decode : nat → option α`. This makes the range of `encode` decidable,
although it is not decidable if `α` is finite or not. -/
class encodable (α : Type*) :=
(encode : α → nat) (decode : nat → option α) (encodek : ∀ a, decode (encode a) = some a)
section encodable
variables {α : Type*} {β : Type*}
universe u
open encodable
section
variables [encodable α]
theorem encode_injective : function.injective (@encode α _)
| x y e := option.some.inj $ by rw [← encodek, e, encodek]
/- lower priority of instance below because we don't want to use encodability
to prove that e.g. equality of nat is decidable. Example of a problem:
lemma H (e : ℕ) : finset.range (nat.succ e) = insert e (finset.range e) :=
begin
exact finset.range_succ
end
fails with this priority not set to zero
-/
@[priority 0] instance decidable_eq_of_encodable : decidable_eq α
| a b := decidable_of_iff _ encode_injective.eq_iff
end
def encodable_of_left_injection [h₁ : encodable α]
(f : β → α) (finv : α → option β) (linv : ∀ b, finv (f b) = some b) : encodable β :=
⟨λ b, encode (f b),
λ n, (decode α n).bind finv,
λ b, by simp [encodable.encodek, option.bind, linv]⟩
def encodable_of_equiv (α) [h : encodable α] : β ≃ α → encodable β
| ⟨f, g, l, r⟩ :=
encodable_of_left_injection f (λ b, some (g b)) (λ b, by rw l; refl)
instance encodable_nat : encodable nat :=
⟨id, some, λ a, rfl⟩
instance encodable_empty : encodable empty :=
⟨λ a, a.rec _, λ n, none, λ a, a.rec _⟩
instance encodable_unit : encodable punit.{u+1} :=
⟨λ_, 0, λn, if n = 0 then some punit.star else none, λ⟨⟩, by simp⟩
instance encodable_option {α : Type*} [h : encodable α] : encodable (option α) :=
⟨λ o, match o with
| some a := succ (encode a)
| none := 0
end,
λ n, if n = 0 then some none else some (decode α (pred n)),
λ o, by cases o; simp [encodable_option._match_1, encodek, nat.succ_ne_zero]⟩
section sum
variables [encodable α] [encodable β]
private def encode_sum : sum α β → nat
| (sum.inl a) := bit ff $ encode a
| (sum.inr b) := bit tt $ encode b
private def decode_sum (n : nat) : option (sum α β) :=
match bodd_div2 n with
| (ff, m) := match decode α m with
| some a := some (sum.inl a)
| none := none
end
| (tt, m) := match decode β m with
| some b := some (sum.inr b)
| none := none
end
end
instance encodable_sum : encodable (sum α β) :=
⟨encode_sum, decode_sum, λ s,
by cases s; simp [encode_sum, decode_sum];
rw [bodd_bit, div2_bit, decode_sum, encodek]; refl⟩
end sum
instance encodable_bool: encodable bool :=
encodable_of_equiv (unit ⊕ unit) equiv.bool_equiv_unit_sum_unit
section sigma
variables {γ : α → Type*} [encodable α] [∀ a, encodable (γ a)]
private def encode_sigma : sigma γ → nat
| ⟨a, b⟩ := mkpair (encode a) (encode b)
private def decode_sigma (n : nat) : option (sigma γ) :=
let (n₁, n₂) := unpair n in
(decode α n₁).bind $ λ a, (decode (γ a) n₂).map $ sigma.mk a
instance encodable_sigma : encodable (sigma γ) :=
⟨encode_sigma, decode_sigma, λ ⟨a, b⟩,
by simp [encode_sigma, decode_sigma, option.bind, option.map, unpair_mkpair, encodek]⟩
end sigma
instance encodable_product [encodable α] [encodable β] : encodable (α × β) :=
encodable_of_equiv _ (equiv.sigma_equiv_prod α β).symm
section list
variable [encodable α]
private def encode_list : list α → nat
| [] := 0
| (a::l) := succ (mkpair (encode_list l) (encode a))
private def decode_list : nat → option (list α)
| 0 := some []
| (succ v) := match unpair v, unpair_le v with
| (v₂, v₁), h :=
have v₂ < succ v, from lt_succ_of_le h,
(::) <$> decode α v₁ <*> decode_list v₂
end
instance encodable_list : encodable (list α) :=
⟨encode_list, decode_list, λ l,
by induction l with a l IH; simp [encode_list, decode_list, unpair_mkpair, encodek, *]⟩
end list
section finset
variables [encodable α]
private def enle (a b : α) : Prop := encode a ≤ encode b
private lemma enle.refl (a : α) : enle a a := le_refl _
private lemma enle.trans (a b c : α) : enle a b → enle b c → enle a c := le_trans
private lemma enle.total (a b : α) : enle a b ∨ enle b a := le_total _ _
private lemma enle.antisymm (a b : α) (h₁ : enle a b) (h₂ : enle b a) : a = b :=
encode_injective (le_antisymm h₁ h₂)
private def decidable_enle (a b : α) : decidable (enle a b) :=
by unfold enle; apply_instance
local attribute [instance] decidable_enle
private def ensort (l : list α) : list α :=
insertion_sort enle l
open subtype list.perm
private lemma sorted_eq_of_perm {l₁ l₂ : list α} (h : l₁ ~ l₂) : ensort l₁ = ensort l₂ :=
eq_of_sorted_of_perm enle.trans enle.antisymm
(perm.trans (perm_insertion_sort _ _) $ perm.trans h (perm_insertion_sort _ _).symm)
(sorted_insertion_sort _ enle.total enle.trans _)
(sorted_insertion_sort _ enle.total enle.trans _)
private def encode_multiset (s : multiset α) : nat :=
encode $ quot.lift_on s
(λ l, ensort l)
(λ l₁ l₂ p, sorted_eq_of_perm p)
private def decode_multiset (n : nat) : option (multiset α) :=
coe <$> decode (list α) n
instance encodable_multiset : encodable (multiset α) :=
⟨encode_multiset, decode_multiset, λ s, quot.induction_on s $ λ l,
show coe <$> decode (list α) (encode (ensort l)) = some ↑l,
by rw [encodek, ← show (ensort l:multiset α) = l,
from quotient.sound (perm_insertion_sort _ _)]; refl⟩
end finset
def encodable_of_list [decidable_eq α] (l : list α) (H : ∀ x, x ∈ l) : encodable α :=
⟨λ a, index_of a l, l.nth, λ a, index_of_nth (H _)⟩
def trunc_encodable_of_fintype (α : Type*) [decidable_eq α] [fintype α] : trunc (encodable α) :=
@@quot.rec_on_subsingleton _
(λ s : multiset α, (∀ x:α, x ∈ s) → trunc (encodable α)) _
finset.univ.1
(λ l H, trunc.mk $ encodable_of_list l H)
finset.mem_univ
section subtype
open subtype decidable
variable {P : α → Prop}
variable [encA : encodable α]
variable [decP : decidable_pred P]
include encA
private def encode_subtype : {a : α // P a} → nat
| ⟨v, h⟩ := encode v
include decP
private def decode_subtype (v : nat) : option {a : α // P a} :=
match decode α v with
| some a := if h : P a then some ⟨a, h⟩ else none
| none := none
end
instance encodable_subtype : encodable {a : α // P a} :=
⟨encode_subtype, decode_subtype,
λ ⟨v, h⟩, by simp [encode_subtype, decode_subtype, encodek, h]⟩
end subtype
instance bool.encodable : encodable bool := encodable_of_equiv _ equiv.bool_equiv_unit_sum_unit
instance int.encodable : encodable ℤ :=
encodable_of_equiv _ equiv.int_equiv_nat
instance encodable_finset [encodable α] : encodable (finset α) :=
encodable_of_equiv {s : multiset α // s.nodup}
⟨λ ⟨a, b⟩, ⟨a, b⟩, λ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩
instance encodable_ulift [encodable α] : encodable (ulift α) :=
encodable_of_equiv _ equiv.ulift
instance encodable_plift [encodable α] : encodable (plift α) :=
encodable_of_equiv _ equiv.plift
noncomputable def encodable_of_inj [encodable β] (f : α → β) (hf : injective f) : encodable α :=
encodable_of_left_injection f (partial_inv f) (λ x, (partial_inv_of_injective hf _ _).2 rfl)
end encodable
/-
Choice function for encodable types and decidable predicates.
We provide the following API
choose {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] : (∃ x, p x) → α :=
choose_spec {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) :=
-/
namespace encodable
section find_a
variables {α : Type*} (p : α → Prop) [encodable α] [decidable_pred p]
private def good : option α → Prop
| (some a) := p a
| none := false
private def decidable_good : decidable_pred (good p)
| n := by cases n; unfold good; apply_instance
local attribute [instance] decidable_good
open encodable
variable {p}
def choose_x (h : ∃ x, p x) : {a:α // p a} :=
have ∃ n, good p (decode α n), from
let ⟨w, pw⟩ := h in ⟨encode w, by simp [good, encodek, pw]⟩,
match _, nat.find_spec this : ∀ o, good p o → {a // p a} with
| some a, h := ⟨a, h⟩
end
def choose (h : ∃ x, p x) : α := (choose_x h).1
lemma choose_spec (h : ∃ x, p x) : p (choose h) := (choose_x h).2
end find_a
theorem axiom_of_choice {α : Type*} {β : α → Type*} {R : Π x, β x → Prop}
[Π a, encodable (β a)] [∀ x y, decidable (R x y)]
(H : ∀x, ∃y, R x y) : ∃f:Πa, β a, ∀x, R x (f x) :=
⟨λ x, choose (H x), λ x, choose_spec (H x)⟩
theorem skolem {α : Type*} {β : α → Type*} {P : Π x, β x → Prop}
[c : Π a, encodable (β a)] [d : ∀ x y, decidable (P x y)] :
(∀x, ∃y, P x y) ↔ ∃f : Π a, β a, (∀x, P x (f x)) :=
⟨axiom_of_choice, λ ⟨f, H⟩ x, ⟨_, H x⟩⟩
end encodable
namespace quot
open encodable
variables {α : Type*} {s : setoid α} [@decidable_rel α (≈)] [encodable α]
-- Choose equivalence class representative
def rep (q : quotient s) : α :=
choose (exists_rep q)
theorem rep_spec (q : quotient s) : ⟦rep q⟧ = q :=
choose_spec (exists_rep q)
def encodable_quotient : encodable (quotient s) :=
⟨λ q, encode (rep q),
λ n, quotient.mk <$> decode α n,
λ q, quot.induction_on q $ λ l,
by rw encodek; exact congr_arg some (rep_spec _)⟩
end quot
|
452c5036889d7368b9dcff7aaeea67e023f7d3d8 | c7e82eae1927be05158e1a5bf2e5a9de9b3c0d4a | /non_mathlib/field_extension.lean | dcd9120cfcc3f815c739149f5c7d705600cb58c7 | [] | no_license | NicholasDyson/lean-polynomials | a869743465b58cd9454443517534afeccd31f275 | 1f8ebc475479b997d14397df3b875a27644ce9b1 | refs/heads/master | 1,693,980,023,161 | 1,635,593,501,000 | 1,635,593,501,000 | 405,369,236 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,926 | lean | import field
inductive item_plus_sqrt (f : Type) [myfld f] (rt : f) : Type
| ips : f -> f -> item_plus_sqrt
open item_plus_sqrt
def ips_zero (f : Type) [myfld f] (rt : f) : (item_plus_sqrt f rt) := ips myfld.zero myfld.zero
def ips_add (f : Type) [myfld f] (rt : f) : (item_plus_sqrt f rt) -> (item_plus_sqrt f rt) -> (item_plus_sqrt f rt)
| (ips a b) (ips c d) := (ips (myfld.add a c) (myfld.add b d))
def ips_negate (f : Type) [myfld f] (rt : f) : (item_plus_sqrt f rt) -> (item_plus_sqrt f rt)
| (ips a b) := (ips (myfld.negate a) (myfld.negate b))
def ips_mul (f : Type) [myfld f] (rt : f) : (item_plus_sqrt f rt) -> (item_plus_sqrt f rt) -> (item_plus_sqrt f rt)
| (ips a b) (ips c d) := (ips ((a .* c) .+ (b .* d .* rt)) ((a .* d) .+ (b .* c)))
def to_ips (f : Type) [myfld f] (rt : f) (x : f) : (item_plus_sqrt f rt) := (ips x myfld.zero)
lemma ips_add_comm (f : Type) [myfld f] (rt : f) (a b c d : f) :
ips_add f rt (ips a b) (ips c d) = ips_add f rt (ips c d) (ips a b) :=
begin
unfold ips_add, rw myfld.add_comm a c, rw myfld.add_comm b d,
end
lemma ips_add_assoc (f : Type) [myfld f] (rt : f) (a1 b1 a2 b2 a3 b3 : f) :
ips_add f rt (ips a1 b1) (ips_add f rt (ips a2 b2) (ips a3 b3)) =
ips_add f rt (ips_add f rt (ips a1 b1) (ips a2 b2)) (ips a3 b3) :=
begin
unfold ips_add, repeat {rw myfld.add_assoc},
end
lemma ips_mul_comm (f : Type) [myfld f] (rt : f) (a b c d : f) :
ips_mul f rt (ips a b) (ips c d) = ips_mul f rt (ips c d) (ips a b) :=
begin
unfold ips_mul, rw myfld.mul_comm a c, rw myfld.mul_comm b d,
rw myfld.mul_comm a d, rw myfld.mul_comm b c,
rw myfld.add_comm (c .* b) (d .* a),
end
def quadratic_formula (f : Type) [myfld f] [fld_not_char_two f] (b c : f) :
(item_plus_sqrt f ((b .* b) .+ ((four f) .* .- c))) :=
ips (.- b) .* (myfld.reciprocal (two f) (fld_not_char_two.not_char_two))
(myfld.reciprocal (two f) (fld_not_char_two.not_char_two))
def quadratic_subst_ips (f : Type) [myfld f] [fld_not_char_two f] (rt : f) (b c : f)
(x : item_plus_sqrt f rt) : (item_plus_sqrt f rt) :=
ips_add f rt (ips_mul f rt x x) (ips_add f rt (ips_mul f rt x (to_ips f rt b)) (to_ips f rt c))
lemma quadratic_formula_works (f : Type) [myfld f] [fld_not_char_two f] (b c : f) :
(quadratic_subst_ips f ((b .* b) .+ ((four f) .* .- c)) b c
(quadratic_formula f b c))
=
(ips myfld.zero myfld.zero) :=
begin
unfold quadratic_formula, unfold quadratic_subst_ips,
unfold to_ips, unfold ips_mul, unfold ips_add,
repeat {rw zero_simp}, repeat {rw zero_mul}, repeat {rw mul_zero}, rw simp_zero, rw zero_simp,
repeat {rw mul_negate, rw mul_negate_alt_simp}, rw mul_negate,
rw double_negative,
have tmp : ∀ (p q rt : f), (p = myfld.zero) -> (q = myfld.zero) ->
((ips p q) : (item_plus_sqrt f rt)) =
((ips myfld.zero myfld.zero) : (item_plus_sqrt f rt)),
intros p q rt h1 h2, rw h1, rw h2,
apply tmp, clear tmp,
rw mul_two_reciprocals,
rw [myfld.mul_comm b (myfld.reciprocal (two f) _)] {occs := occurrences.pos [2]},
rw <- myfld.mul_assoc _ (myfld.reciprocal (two f) _) _,
rw myfld.mul_assoc (myfld.reciprocal (two f) _) (myfld.reciprocal (two f) _) _,
rw mul_two_reciprocals, rw myfld.mul_comm b ((myfld.reciprocal _ _) .* _),
rw <- myfld.mul_assoc (myfld.reciprocal _ _) b b,
rw <- distrib_simp_alt,
have tmp : .- (b .* (myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* b) =
.- ((myfld.reciprocal ((two f) .* (two f)) (mul_nonzero f (two f) (two f) fld_not_char_two.not_char_two fld_not_char_two.not_char_two))
.* ((b .* b) .+ (b .* b))),
rw <- mul_two_reciprocals, have tmp_tmp : ((b .* b) .+ (b .* b)) = (two f) .* (b .* b),
unfold two, rw distrib_simp, rw one_mul_simp,
rw tmp_tmp, rw myfld.mul_assoc _ (two f) _,
rw <- myfld.mul_assoc _ (myfld.reciprocal (two f) _) (two f),
rw myfld.mul_comm (myfld.reciprocal (two f) _) (two f), rw myfld.mul_reciprocal,
rw simp_mul_one, rw myfld.mul_comm b _, rw myfld.mul_assoc,
rw tmp, clear tmp, rw mul_negate_alt f _ ((b .* b) .+ (b .* b)),
rw myfld.add_assoc, rw <- distrib_simp_alt,
rw myfld.add_assoc (b .* b) (b .* b), rw myfld.add_comm _ (.- ((four f) .* c)),
rw <- myfld.add_assoc _ ((b .* b) .+ (b .* b)) _,
rw myfld.add_negate, rw zero_simp,
rw mul_negate_alt_simp, have tmp : (two f) .* (two f) = (four f), unfold four, rw two_plus_two,
rw reciprocal_rewrite f _ (four f) tmp, rw myfld.mul_assoc, rw myfld.mul_comm _ (four f),
rw myfld.mul_reciprocal, rw one_mul_simp, rw myfld.add_comm, rw myfld.add_negate,
clear tmp,
rw myfld.mul_comm _ (b .* (myfld.reciprocal (two f) fld_not_char_two.not_char_two)),
rw <- add_negate, rw <- distrib_simp_alt, rw only_one_reciprocal f (two f) _ (two_ne_zero f),
rw add_two_halves, rw simp_mul_one,
rw myfld.add_comm, rw myfld.mul_comm b _, rw myfld.add_negate,
end
|
f6e4c7d6e5e4ea733499fd6d8404e334a04663ee | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/mv_polynomial/cardinal.lean | 3407ce37f2a6459836355c60f492446873e9011c | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 4,365 | lean | /-
Copyright (c) 2021 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.W.cardinal
import data.mv_polynomial.basic
/-!
# Cardinality of Polynomial Ring
The main result in this file is `mv_polynomial.cardinal_mk_le_max`, which says that
the cardinality of `mv_polynomial σ R` is bounded above by the maximum of `#R`, `#σ`
and `ω`.
-/
universes u
/-
The definitions `mv_polynomial_fun` and `arity` are motivated by defining the following
inductive type as a `W_type` in order to be able to use theorems about the cardinality
of `W_type`.
inductive mv_polynomial_term (σ R : Type u) : Type u
| of_ring : R → mv_polynomial_term
| X : σ → mv_polynomial_term
| add : mv_polynomial_term → mv_polynomial_term → mv_polynomial_term
| mul : mv_polynomial_term → mv_polynomial_term → mv_polynomial_term
`W_type (arity σ R)` is isomorphic to the above type.
-/
open cardinal
open_locale cardinal
/-- A type used to prove theorems about the cardinality of `mv_polynomial σ R`. The
`W_type (arity σ R)` has a constant for every element of `R` and `σ` and two binary functions. -/
private def mv_polynomial_fun (σ R : Type u) : Type u :=
R ⊕ σ ⊕ ulift.{u} bool
variables (σ R : Type u)
/-- A function used to prove theorems about the cardinality of `mv_polynomial σ R`.
The type ``W_type (arity σ R)` has a constant for every element of `R` and `σ` and two binary
functions. -/
private def arity : mv_polynomial_fun σ R → Type u
| (sum.inl _) := pempty
| (sum.inr (sum.inl _)) := pempty
| (sum.inr (sum.inr ⟨ff⟩)) := ulift bool
| (sum.inr (sum.inr ⟨tt⟩)) := ulift bool
private def arity_fintype (x : mv_polynomial_fun σ R) : fintype (arity σ R x) :=
by rcases x with x | x | ⟨_ | _⟩; dsimp [arity]; apply_instance
local attribute [instance] arity_fintype
variables {σ R}
variables [comm_semiring R]
/-- The surjection from `W_type (arity σ R)` into `mv_polynomial σ R`. -/
private noncomputable def to_mv_polynomial :
W_type (arity σ R) → mv_polynomial σ R
| ⟨sum.inl r, _⟩ := mv_polynomial.C r
| ⟨sum.inr (sum.inl i), _⟩ := mv_polynomial.X i
| ⟨sum.inr (sum.inr ⟨ff⟩), f⟩ :=
to_mv_polynomial (f (ulift.up tt)) * to_mv_polynomial (f (ulift.up ff))
| ⟨sum.inr (sum.inr ⟨tt⟩), f⟩ :=
to_mv_polynomial (f (ulift.up tt)) + to_mv_polynomial (f (ulift.up ff))
private lemma to_mv_polynomial_surjective : function.surjective (@to_mv_polynomial σ R _) :=
begin
intro p,
induction p using mv_polynomial.induction_on with x p₁ p₂ ih₁ ih₂ p i ih,
{ exact ⟨W_type.mk (sum.inl x) pempty.elim, rfl⟩ },
{ rcases ih₁ with ⟨w₁, rfl⟩,
rcases ih₂ with ⟨w₂, rfl⟩,
exact ⟨W_type.mk (sum.inr (sum.inr ⟨tt⟩)) (λ x, cond x.down w₁ w₂),
by simp [to_mv_polynomial]⟩ },
{ rcases ih with ⟨w, rfl⟩,
exact ⟨W_type.mk (sum.inr (sum.inr ⟨ff⟩)) (λ x, cond x.down w (W_type.mk
(sum.inr (sum.inl i)) pempty.elim)), by simp [to_mv_polynomial]⟩ }
end
private lemma cardinal_mv_polynomial_fun_le : #(mv_polynomial_fun σ R) ≤ max (max (#R) (#σ)) ω :=
calc #(mv_polynomial_fun σ R) = #R + #σ + #(ulift bool) :
by dsimp [mv_polynomial_fun]; simp only [← add_def, add_assoc, cardinal.mk_ulift]
... ≤ max (max (#R + #σ) (#(ulift bool))) ω : add_le_max _ _
... ≤ max (max (max (max (#R) (#σ)) ω) (#(ulift bool))) ω :
max_le_max (max_le_max (add_le_max _ _) le_rfl) le_rfl
... ≤ _ : begin
have : #(ulift.{u} bool) ≤ ω,
from le_of_lt (lt_omega_iff_fintype.2 ⟨infer_instance⟩),
simp only [max_comm omega.{u}, max_assoc, max_left_comm omega.{u}, max_self, max_eq_left this],
end
namespace mv_polynomial
/-- The cardinality of the multivariate polynomial ring, `mv_polynomial σ R` is at most the maximum
of `#R`, `#σ` and `ω` -/
lemma cardinal_mk_le_max {σ R : Type u} [comm_semiring R] :
#(mv_polynomial σ R) ≤ max (max (#R) (#σ)) ω :=
calc #(mv_polynomial σ R) ≤ #(W_type (arity σ R)) :
cardinal.mk_le_of_surjective to_mv_polynomial_surjective
... ≤ max (#(mv_polynomial_fun σ R)) ω : W_type.cardinal_mk_le_max_omega_of_fintype
... ≤ _ : max_le_max cardinal_mv_polynomial_fun_le le_rfl
... ≤ _ : by simp only [max_assoc, max_self]
end mv_polynomial
|
4e55949481595bbbc0a247169cdf71d0d856a97b | 9c1ad797ec8a5eddb37d34806c543602d9a6bf70 | /monoidal_categories/internal_objects/modules.lean | 9def80cff2c1fb3825587f34400443ec32a80a94 | [] | no_license | timjb/lean-category-theory | 816eefc3a0582c22c05f4ee1c57ed04e57c0982f | 12916cce261d08bb8740bc85e0175b75fb2a60f4 | refs/heads/master | 1,611,078,926,765 | 1,492,080,000,000 | 1,492,080,000,000 | 88,348,246 | 0 | 0 | null | 1,492,262,499,000 | 1,492,262,498,000 | null | UTF-8 | Lean | false | false | 1,681 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan, Scott Morrison
import .semigroup_modules
import .monoids
open tqft.categories
open tqft.categories.monoidal_category
namespace tqft.categories.internal_objects
structure ModuleObject { C : Category } { m : MonoidalStructure C } ( A : MonoidObject m ) extends SemigroupModuleObject A.to_SemigroupObject :=
-- TODO components
( identity : C.compose (m.left_unitor.inverse.components module) (C.compose (m.tensorMorphisms A.unit (C.identity module)) action) = C.identity module )
attribute [simp,ematch] ModuleObject.identity
attribute [ematch] ModuleObject.associativity
structure ModuleMorphism { C : Category } { m : MonoidalStructure C } { A : MonoidObject m } ( X Y : ModuleObject A ) extends SemigroupModuleMorphism X.to_SemigroupModuleObject Y.to_SemigroupModuleObject
attribute [simp,ematch] ModuleMorphism.compatibility
@[pointwise] lemma ModuleMorphism_pointwisewise_equal
{ C : Category }
{ m : MonoidalStructure C }
{ A : MonoidObject m }
{ X Y : ModuleObject A }
( f g : ModuleMorphism X Y )
( w : f.map = g.map ) : f = g :=
begin
induction f,
induction g,
blast
end
definition CategoryOfModules { C : Category } { m : MonoidalStructure C } ( A : MonoidObject m ) : Category :=
{
Obj := ModuleObject A,
Hom := λ X Y, ModuleMorphism X Y,
identity := λ X, ⟨ C.identity X.module, ♮ ⟩,
compose := λ _ _ _ f g, ⟨ C.compose f.map g.map, ♮ ⟩,
left_identity := ♯,
right_identity := ♯,
associativity := ♮
}
end tqft.categories.internal_objects |
a5bc03c2d348c8c86316c57c7efe8844f208cc29 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/complex/re_im_topology.lean | 6eec8014fa1c96cc51ce5af3bcce2ad541c167f5 | [
"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 | 7,726 | lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.complex.basic
import topology.fiber_bundle.is_homeomorphic_trivial_bundle
/-!
# Closure, interior, and frontier of preimages under `re` and `im`
In this fact we use the fact that `ℂ` is naturally homeomorphic to `ℝ × ℝ` to deduce some
topological properties of `complex.re` and `complex.im`.
## Main statements
Each statement about `complex.re` listed below has a counterpart about `complex.im`.
* `complex.is_homeomorphic_trivial_fiber_bundle_re`: `complex.re` turns `ℂ` into a trivial
topological fiber bundle over `ℝ`;
* `complex.is_open_map_re`, `complex.quotient_map_re`: in particular, `complex.re` is an open map
and is a quotient map;
* `complex.interior_preimage_re`, `complex.closure_preimage_re`, `complex.frontier_preimage_re`:
formulas for `interior (complex.re ⁻¹' s)` etc;
* `complex.interior_set_of_re_le` etc: particular cases of the above formulas in the cases when `s`
is one of the infinite intervals `set.Ioi a`, `set.Ici a`, `set.Iio a`, and `set.Iic a`,
formulated as `interior {z : ℂ | z.re ≤ a} = {z | z.re < a}` etc.
## Tags
complex, real part, imaginary part, closure, interior, frontier
-/
open set
noncomputable theory
namespace complex
/-- `complex.re` turns `ℂ` into a trivial topological fiber bundle over `ℝ`. -/
lemma is_homeomorphic_trivial_fiber_bundle_re : is_homeomorphic_trivial_fiber_bundle ℝ re :=
⟨equiv_real_prodₗ.to_homeomorph, λ z, rfl⟩
/-- `complex.im` turns `ℂ` into a trivial topological fiber bundle over `ℝ`. -/
lemma is_homeomorphic_trivial_fiber_bundle_im : is_homeomorphic_trivial_fiber_bundle ℝ im :=
⟨equiv_real_prodₗ.to_homeomorph.trans (homeomorph.prod_comm ℝ ℝ), λ z, rfl⟩
lemma is_open_map_re : is_open_map re := is_homeomorphic_trivial_fiber_bundle_re.is_open_map_proj
lemma is_open_map_im : is_open_map im := is_homeomorphic_trivial_fiber_bundle_im.is_open_map_proj
lemma quotient_map_re : quotient_map re := is_homeomorphic_trivial_fiber_bundle_re.quotient_map_proj
lemma quotient_map_im : quotient_map im := is_homeomorphic_trivial_fiber_bundle_im.quotient_map_proj
lemma interior_preimage_re (s : set ℝ) : interior (re ⁻¹' s) = re ⁻¹' (interior s) :=
(is_open_map_re.preimage_interior_eq_interior_preimage continuous_re _).symm
lemma interior_preimage_im (s : set ℝ) : interior (im ⁻¹' s) = im ⁻¹' (interior s) :=
(is_open_map_im.preimage_interior_eq_interior_preimage continuous_im _).symm
lemma closure_preimage_re (s : set ℝ) : closure (re ⁻¹' s) = re ⁻¹' (closure s) :=
(is_open_map_re.preimage_closure_eq_closure_preimage continuous_re _).symm
lemma closure_preimage_im (s : set ℝ) : closure (im ⁻¹' s) = im ⁻¹' (closure s) :=
(is_open_map_im.preimage_closure_eq_closure_preimage continuous_im _).symm
lemma frontier_preimage_re (s : set ℝ) : frontier (re ⁻¹' s) = re ⁻¹' (frontier s) :=
(is_open_map_re.preimage_frontier_eq_frontier_preimage continuous_re _).symm
lemma frontier_preimage_im (s : set ℝ) : frontier (im ⁻¹' s) = im ⁻¹' (frontier s) :=
(is_open_map_im.preimage_frontier_eq_frontier_preimage continuous_im _).symm
@[simp] lemma interior_set_of_re_le (a : ℝ) : interior {z : ℂ | z.re ≤ a} = {z | z.re < a} :=
by simpa only [interior_Iic] using interior_preimage_re (Iic a)
@[simp] lemma interior_set_of_im_le (a : ℝ) : interior {z : ℂ | z.im ≤ a} = {z | z.im < a} :=
by simpa only [interior_Iic] using interior_preimage_im (Iic a)
@[simp] lemma interior_set_of_le_re (a : ℝ) : interior {z : ℂ | a ≤ z.re} = {z | a < z.re} :=
by simpa only [interior_Ici] using interior_preimage_re (Ici a)
@[simp] lemma interior_set_of_le_im (a : ℝ) : interior {z : ℂ | a ≤ z.im} = {z | a < z.im} :=
by simpa only [interior_Ici] using interior_preimage_im (Ici a)
@[simp] lemma closure_set_of_re_lt (a : ℝ) : closure {z : ℂ | z.re < a} = {z | z.re ≤ a} :=
by simpa only [closure_Iio] using closure_preimage_re (Iio a)
@[simp] lemma closure_set_of_im_lt (a : ℝ) : closure {z : ℂ | z.im < a} = {z | z.im ≤ a} :=
by simpa only [closure_Iio] using closure_preimage_im (Iio a)
@[simp] lemma closure_set_of_lt_re (a : ℝ) : closure {z : ℂ | a < z.re} = {z | a ≤ z.re} :=
by simpa only [closure_Ioi] using closure_preimage_re (Ioi a)
@[simp] lemma closure_set_of_lt_im (a : ℝ) : closure {z : ℂ | a < z.im} = {z | a ≤ z.im} :=
by simpa only [closure_Ioi] using closure_preimage_im (Ioi a)
@[simp] lemma frontier_set_of_re_le (a : ℝ) : frontier {z : ℂ | z.re ≤ a} = {z | z.re = a} :=
by simpa only [frontier_Iic] using frontier_preimage_re (Iic a)
@[simp] lemma frontier_set_of_im_le (a : ℝ) : frontier {z : ℂ | z.im ≤ a} = {z | z.im = a} :=
by simpa only [frontier_Iic] using frontier_preimage_im (Iic a)
@[simp] lemma frontier_set_of_le_re (a : ℝ) : frontier {z : ℂ | a ≤ z.re} = {z | z.re = a} :=
by simpa only [frontier_Ici] using frontier_preimage_re (Ici a)
@[simp] lemma frontier_set_of_le_im (a : ℝ) : frontier {z : ℂ | a ≤ z.im} = {z | z.im = a} :=
by simpa only [frontier_Ici] using frontier_preimage_im (Ici a)
@[simp] lemma frontier_set_of_re_lt (a : ℝ) : frontier {z : ℂ | z.re < a} = {z | z.re = a} :=
by simpa only [frontier_Iio] using frontier_preimage_re (Iio a)
@[simp] lemma frontier_set_of_im_lt (a : ℝ) : frontier {z : ℂ | z.im < a} = {z | z.im = a} :=
by simpa only [frontier_Iio] using frontier_preimage_im (Iio a)
@[simp] lemma frontier_set_of_lt_re (a : ℝ) : frontier {z : ℂ | a < z.re} = {z | z.re = a} :=
by simpa only [frontier_Ioi] using frontier_preimage_re (Ioi a)
@[simp] lemma frontier_set_of_lt_im (a : ℝ) : frontier {z : ℂ | a < z.im} = {z | z.im = a} :=
by simpa only [frontier_Ioi] using frontier_preimage_im (Ioi a)
lemma closure_re_prod_im (s t : set ℝ) : closure (s ×ℂ t) = closure s ×ℂ closure t :=
by simpa only [← preimage_eq_preimage equiv_real_prodₗ.symm.to_homeomorph.surjective,
equiv_real_prodₗ.symm.to_homeomorph.preimage_closure]
using @closure_prod_eq _ _ _ _ s t
lemma interior_re_prod_im (s t : set ℝ) : interior (s ×ℂ t) = interior s ×ℂ interior t :=
by rw [re_prod_im, re_prod_im, interior_inter, interior_preimage_re, interior_preimage_im]
lemma frontier_re_prod_im (s t : set ℝ) :
frontier (s ×ℂ t) = (closure s ×ℂ frontier t) ∪ (frontier s ×ℂ closure t) :=
by simpa only [← preimage_eq_preimage equiv_real_prodₗ.symm.to_homeomorph.surjective,
equiv_real_prodₗ.symm.to_homeomorph.preimage_frontier]
using frontier_prod_eq s t
lemma frontier_set_of_le_re_and_le_im (a b : ℝ) :
frontier {z | a ≤ re z ∧ b ≤ im z} = {z | a ≤ re z ∧ im z = b ∨ re z = a ∧ b ≤ im z} :=
by simpa only [closure_Ici, frontier_Ici] using frontier_re_prod_im (Ici a) (Ici b)
lemma frontier_set_of_le_re_and_im_le (a b : ℝ) :
frontier {z | a ≤ re z ∧ im z ≤ b} = {z | a ≤ re z ∧ im z = b ∨ re z = a ∧ im z ≤ b} :=
by simpa only [closure_Ici, closure_Iic, frontier_Ici, frontier_Iic]
using frontier_re_prod_im (Ici a) (Iic b)
end complex
open complex metric
variables {s t : set ℝ}
lemma is_open.re_prod_im (hs : is_open s) (ht : is_open t) : is_open (s ×ℂ t) :=
(hs.preimage continuous_re).inter (ht.preimage continuous_im)
lemma is_closed.re_prod_im (hs : is_closed s) (ht : is_closed t) : is_closed (s ×ℂ t) :=
(hs.preimage continuous_re).inter (ht.preimage continuous_im)
lemma metric.bounded.re_prod_im (hs : bounded s) (ht : bounded t) : bounded (s ×ℂ t) :=
equiv_real_prodₗ.antilipschitz.bounded_preimage (hs.prod ht)
|
949e797d9ce2f5165a530988683d1edd6ab9fc82 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/algebra/star/chsh.lean | 91552e315065ec8f8ff13b728b98bbe50268916b | [
"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 | 12,232 | 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 algebra.star.algebra
import algebra.algebra.ordered
import analysis.special_functions.pow
/-!
# The Clauser-Horne-Shimony-Holt inequality and Tsirelson's inequality.
We establish a version of the Clauser-Horne-Shimony-Holt (CHSH) inequality
(which is a generalization of Bell's inequality).
This is a foundational result which implies that
quantum mechanics is not a local hidden variable theory.
As usually stated the CHSH inequality requires substantial language from physics and probability,
but it is possible to give a statement that is purely about ordered `*`-algebras.
We do that here, to avoid as many practical and logical dependencies as possible.
Since the algebra of observables of any quantum system is an ordered `*`-algebra
(in particular a von Neumann algebra) this is a strict generalization of the usual statement.
Let `R` be a `*`-ring.
A CHSH tuple in `R` consists of
* four elements `A₀ A₁ B₀ B₁ : R`, such that
* each `Aᵢ` and `Bⱼ` is a self-adjoint involution, and
* the `Aᵢ` commute with the `Bⱼ`.
The physical interpretation is that the four elements are observables (hence self-adjoint)
that take values ±1 (hence involutions), and that the `Aᵢ` are spacelike separated from the `Bⱼ`
(and hence commute).
The CHSH inequality says that when `R` is an ordered `*`-ring
(that is, a `*`-ring which is ordered, and for every `r : R`, `0 ≤ star r * r`),
which is moreover *commutative*, we have
`A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2`
On the other hand, Tsirelson's inequality says that for any ordered `*`-ring we have
`A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2√2`
(A caveat: in the commutative case we need 2⁻¹ in the ring,
and in the noncommutative case we need √2 and √2⁻¹.
To keep things simple we just assume our rings are ℝ-algebras.)
The proofs I've seen in the literature either
assume a significant framework for quantum mechanics,
or assume the ring is a `C^*`-algebra.
In the `C^*`-algebra case,
the order structure is completely determined by the `*`-algebra structure:
`0 ≤ A` iff there exists some `B` so `A = star B * B`.
There's a nice proof of both bounds in this setting at
https://en.wikipedia.org/wiki/Tsirelson%27s_bound
The proof given here is purely algebraic.
## Future work
One can show that Tsirelson's inequality is tight.
In the `*`-ring of n-by-n complex matrices, if `A ≤ λ I` for some `λ : ℝ`,
then every eigenvalue has absolute value at most `λ`.
There is a CHSH tuple in 4-by-4 matrices such that
`A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁` has `2√2` as an eigenvalue.
## References
* [Clauser, Horne, Shimony, Holt,
*Proposed experiment to test local hidden-variable theories*][zbMATH06785026]
* [Bell, *On the Einstein Podolsky Rosen Paradox*][MR3790629]
* [Tsirelson, *Quantum generalizations of Bell's inequality*][MR577178]
-/
universes u
/--
A CHSH tuple in a `star_monoid R` consists of 4 self-adjoint involutions `A₀ A₁ B₀ B₁` such that
the `Aᵢ` commute with the `Bⱼ`.
The physical interpretation is that `A₀` and `A₁` are a pair of boolean observables which
are spacelike separated from another pair `B₀` and `B₁` of boolean observables.
-/
@[nolint has_inhabited_instance]
structure is_CHSH_tuple {R} [monoid R] [star_monoid R] (A₀ A₁ B₀ B₁ : R) :=
(A₀_inv : A₀^2 = 1) (A₁_inv : A₁^2 = 1) (B₀_inv : B₀^2 = 1) (B₁_inv : B₁^2 = 1)
(A₀_sa : star A₀ = A₀) (A₁_sa : star A₁ = A₁) (B₀_sa : star B₀ = B₀) (B₁_sa : star B₁ = B₁)
(A₀B₀_commutes : A₀ * B₀ = B₀ * A₀)
(A₀B₁_commutes : A₀ * B₁ = B₁ * A₀)
(A₁B₀_commutes : A₁ * B₀ = B₀ * A₁)
(A₁B₁_commutes : A₁ * B₁ = B₁ * A₁)
variables {R : Type u}
/--
Given a CHSH tuple (A₀, A₁, B₀, B₁) in a *commutative* ordered `*`-algebra over ℝ,
`A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2`.
(We could work over ℤ[⅟2] if we wanted to!)
-/
lemma CHSH_inequality_of_comm
[ordered_comm_ring R] [star_ordered_ring R] [algebra ℝ R] [ordered_semimodule ℝ R]
(A₀ A₁ B₀ B₁ : R) (T : is_CHSH_tuple A₀ A₁ B₀ B₁) :
A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2 :=
begin
let P := (2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁),
have i₁ : 0 ≤ P,
{ have idem : P * P = 4 * P,
{ -- If we had a Gröbner basis algorithm, this would be trivial.
-- Without one, it is somewhat tedious!
dsimp [P],
simp only [add_mul, mul_add, sub_mul, mul_sub, mul_comm, mul_assoc, add_assoc],
repeat { conv in (B₀ * (A₀ * B₀))
{ rw [T.A₀B₀_commutes, ←mul_assoc B₀ B₀ A₀, ←pow_two, T.B₀_inv, one_mul], } },
repeat { conv in (B₀ * (A₁ * B₀))
{ rw [T.A₁B₀_commutes, ←mul_assoc B₀ B₀ A₁, ←pow_two, T.B₀_inv, one_mul], } },
repeat { conv in (B₁ * (A₀ * B₁))
{ rw [T.A₀B₁_commutes, ←mul_assoc B₁ B₁ A₀, ←pow_two, T.B₁_inv, one_mul], } },
repeat { conv in (B₁ * (A₁ * B₁))
{ rw [T.A₁B₁_commutes, ←mul_assoc B₁ B₁ A₁, ←pow_two, T.B₁_inv, one_mul], } },
conv in (A₀ * (B₀ * (A₀ * B₁)))
{ rw [←mul_assoc, T.A₀B₀_commutes, mul_assoc, ←mul_assoc A₀, ←pow_two, T.A₀_inv, one_mul], },
conv in (A₀ * (B₁ * (A₀ * B₀)))
{ rw [←mul_assoc, T.A₀B₁_commutes, mul_assoc, ←mul_assoc A₀, ←pow_two, T.A₀_inv, one_mul], },
conv in (A₁ * (B₀ * (A₁ * B₁)))
{ rw [←mul_assoc, T.A₁B₀_commutes, mul_assoc, ←mul_assoc A₁, ←pow_two, T.A₁_inv, one_mul], },
conv in (A₁ * (B₁ * (A₁ * B₀)))
{ rw [←mul_assoc, T.A₁B₁_commutes, mul_assoc, ←mul_assoc A₁, ←pow_two, T.A₁_inv, one_mul], },
simp only [←pow_two, T.A₀_inv, T.A₁_inv],
simp only [mul_comm A₁ A₀, mul_comm B₁ B₀, mul_left_comm A₁ A₀, mul_left_comm B₁ B₀,
mul_left_comm B₀ A₀, mul_left_comm B₀ A₁, mul_left_comm B₁ A₀, mul_left_comm B₁ A₁],
norm_num,
simp only [mul_comm _ (2 : R), mul_comm _ (4 : R),
mul_left_comm _ (2 : R), mul_left_comm _ (4 : R)],
abel,
simp only [neg_mul_eq_neg_mul_symm, mul_one, int.cast_bit0, one_mul, int.cast_one,
gsmul_eq_mul, int.cast_neg],
simp only [←mul_assoc, ←add_assoc],
norm_num, },
have idem' : P = (1 / 4 : ℝ) • (P * P),
{ have h : 4 * P = (4 : ℝ) • P := by simp [algebra.smul_def],
rw [idem, h, ←mul_smul],
norm_num, },
have sa : star P = P,
{ dsimp [P],
simp only [star_add, star_sub, star_mul, star_bit0, star_one,
T.A₀_sa, T.A₁_sa, T.B₀_sa, T.B₁_sa, mul_comm B₀, mul_comm B₁], },
rw idem',
conv_rhs { congr, skip, congr, rw ←sa, },
convert smul_le_smul_of_nonneg (star_mul_self_nonneg : 0 ≤ star P * P) _,
{ simp, },
{ apply_instance, },
{ norm_num, }, },
apply le_of_sub_nonneg,
simpa only [sub_add_eq_sub_sub, ←sub_add] using i₁,
end
/-!
We now prove some rather specialized lemmas in preparation for the Tsirelson inequality,
which we hide in a namespace as they are unlikely to be useful elsewhere.
-/
local notation `√2` := (real.sqrt 2 : ℝ)
namespace tsirelson_inequality
/-!
We next need some lemmas about numerals in modules and algebras.
The awkward appearance of both `•ℤ` and `•` seems unavoidable because later calculations by `abel`
will introduce `•ℤ`.
If anyone sees how to obtain these from general statements, please improve this!
-/
lemma two_gsmul_half_smul {α : Type*} [add_comm_group α] [module ℝ α] {X : α} :
2 •ℤ (2⁻¹ : ℝ) • X = X :=
by { rw [gsmul_eq_smul_cast ℝ, ←mul_smul]; norm_num, }
lemma neg_two_gsmul_half_smul {α : Type*} [add_comm_group α] [module ℝ α] {X : α} :
(-2) •ℤ (2⁻¹ : ℝ) • X = - X :=
by { rw [gsmul_eq_smul_cast ℝ, ←mul_smul]; norm_num, }
lemma smul_two {α : Type*} [ring α] [algebra ℝ α] {x : ℝ} :
x • (2 : α) = (2 * x) • 1 :=
by { rw [mul_comm 2 x, mul_smul], simp, }
lemma smul_four {α : Type*} [ring α] [algebra ℝ α] {x : ℝ} :
x • (4 : α) = (4 * x) • 1 :=
by { rw [mul_comm 4 x, mul_smul], simp, }
/-!
Before proving Tsirelson's bound,
we prepare some easy lemmas about √2.
-/
-- This calculation, which we need for Tsirelson's bound,
-- defeated me. Thanks for the rescue from Shing Tak Lam!
lemma tsirelson_inequality_aux : √2 * √2 ^ 3 = √2 * (2 * √2⁻¹ + 4 * (√2⁻¹ * 2⁻¹)) :=
begin
ring_nf,
rw [mul_assoc, inv_mul_cancel, real.sqrt_eq_rpow, ←real.rpow_nat_cast, ←real.rpow_mul],
{ norm_num,
rw show (2 : ℝ) ^ (2 : ℝ) = (2 : ℝ) ^ (2 : ℕ), by { rw ←real.rpow_nat_cast, norm_num },
norm_num },
{ norm_num, },
{ norm_num, },
end
lemma sqrt_two_inv_mul_self : √2⁻¹ * √2⁻¹ = (2⁻¹ : ℝ) :=
by { rw [←mul_inv'], norm_num, }
end tsirelson_inequality
open tsirelson_inequality
/--
In a noncommutative ordered `*`-algebra over ℝ,
Tsirelson's bound for a CHSH tuple (A₀, A₁, B₀, B₁) is
`A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2^(3/2) • 1`.
We prove this by providing an explicit sum-of-squares decomposition
of the difference.
(We could work over `ℤ[2^(1/2), 2^(-1/2)]` if we really wanted to!)
-/
lemma tsirelson_inequality
[ordered_ring R] [star_ordered_ring R]
[algebra ℝ R] [ordered_semimodule ℝ R] [star_algebra ℝ R]
(A₀ A₁ B₀ B₁ : R) (T : is_CHSH_tuple A₀ A₁ B₀ B₁) :
A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ √2^3 • 1 :=
begin
let P := √2⁻¹ • (A₁ + A₀) - B₀,
let Q := √2⁻¹ • (A₁ - A₀) + B₁,
have w : √2^3 • 1 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁ = √2⁻¹ • (P^2 + Q^2),
{ dsimp [P, Q],
-- distribute out all the powers and products appearing on the RHS
simp only [pow_two, sub_mul, mul_sub, add_mul, mul_add, smul_add, smul_sub],
-- pull all coefficients out to the front, and combine `√2`s where possible
simp only [algebra.mul_smul_comm, algebra.smul_mul_assoc, ←mul_smul, sqrt_two_inv_mul_self],
-- replace Aᵢ * Aᵢ = 1 and Bᵢ * Bᵢ = 1
simp only [←pow_two, T.A₀_inv, T.A₁_inv, T.B₀_inv, T.B₁_inv],
-- move Aᵢ to the left of Bᵢ
simp only [←T.A₀B₀_commutes, ←T.A₀B₁_commutes, ←T.A₁B₀_commutes, ←T.A₁B₁_commutes],
-- collect terms, simplify coefficients, and collect terms again:
abel,
simp only [two_gsmul_half_smul, neg_two_gsmul_half_smul],
abel,
-- these are identical, except the `_ • 1` terms don't quite match up
congr,
-- collect terms by hand, as we don't have an analogue of `abel` for modules
simp only [mul_one, int.cast_bit0, algebra.mul_smul_comm, int.cast_one, gsmul_eq_mul],
rw [smul_two, smul_four, ←add_smul],
-- just look at the coefficients now:
congr,
exact mul_left_cancel' (by norm_num) tsirelson_inequality_aux, },
have pos : 0 ≤ √2⁻¹ • (P^2 + Q^2), {
have P_sa : star P = P,
{ dsimp [P],
simp only [star_smul, star_add, star_sub, star_id_of_comm,
T.A₀_sa, T.A₁_sa, T.B₀_sa, T.B₁_sa], },
have Q_sa : star Q = Q,
{ dsimp [Q],
simp only [star_smul, star_add, star_sub, star_id_of_comm,
T.A₀_sa, T.A₁_sa, T.B₀_sa, T.B₁_sa], },
have P2_nonneg : 0 ≤ P^2,
{ rw [pow_two],
conv { congr, skip, congr, rw ←P_sa, },
convert (star_mul_self_nonneg : 0 ≤ star P * P), },
have Q2_nonneg : 0 ≤ Q^2,
{ rw [pow_two],
conv { congr, skip, congr, rw ←Q_sa, },
convert (star_mul_self_nonneg : 0 ≤ star Q * Q), },
convert smul_le_smul_of_nonneg (add_nonneg P2_nonneg Q2_nonneg)
(le_of_lt (show 0 < √2⁻¹, by norm_num)), -- `norm_num` can't directly show `0 ≤ √2⁻¹`
simp, },
apply le_of_sub_nonneg,
simpa only [sub_add_eq_sub_sub, ←sub_add, w] using pos,
end
|
e484bde6fe9ce52ec6b4f4e5c8867a6298c0504b | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Lean/Compiler/IR/EmitUtil.lean | ca6d2caf6a94673ec8b0f6699a81f3617961b7a9 | [
"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 | 3,185 | 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.InitAttr
import Lean.Compiler.IR.CompilerM
/-! # Helper functions for backend code generators -/
namespace Lean.IR
/-- Return true iff `b` is of the form `let x := g ys; ret x` -/
def isTailCallTo (g : Name) (b : FnBody) : Bool :=
match b with
| FnBody.vdecl x _ (Expr.fap f _) (FnBody.ret (Arg.var y)) => x == y && f == g
| _ => false
def usesModuleFrom (env : Environment) (modulePrefix : Name) : Bool :=
env.allImportedModuleNames.toList.any fun modName => modulePrefix.isPrefixOf modName
namespace CollectUsedDecls
abbrev M := ReaderT Environment (StateM NameSet)
@[inline] def collect (f : FunId) : M Unit :=
modify fun s => s.insert f
partial def collectFnBody : FnBody → M Unit
| .vdecl _ _ v b =>
match v with
| .fap f _ => collect f *> collectFnBody b
| .pap f _ => collect f *> collectFnBody b
| _ => collectFnBody b
| .jdecl _ _ v b => collectFnBody v *> collectFnBody b
| .case _ _ _ alts => alts.forM fun alt => collectFnBody alt.body
| e => do unless e.isTerminal do collectFnBody e.body
def collectInitDecl (fn : Name) : M Unit := do
let env ← read
match getInitFnNameFor? env fn with
| some initFn => collect initFn
| _ => pure ()
def collectDecl : Decl → M NameSet
| .fdecl (f := f) (body := b) .. => collectInitDecl f *> CollectUsedDecls.collectFnBody b *> get
| .extern (f := f) .. => collectInitDecl f *> get
end CollectUsedDecls
def collectUsedDecls (env : Environment) (decl : Decl) (used : NameSet := {}) : NameSet :=
(CollectUsedDecls.collectDecl decl env).run' used
abbrev VarTypeMap := Std.HashMap VarId IRType
abbrev JPParamsMap := Std.HashMap JoinPointId (Array Param)
namespace CollectMaps
abbrev Collector := (VarTypeMap × JPParamsMap) → (VarTypeMap × JPParamsMap)
@[inline] def collectVar (x : VarId) (t : IRType) : Collector
| (vs, js) => (vs.insert x t, js)
def collectParams (ps : Array Param) : Collector :=
fun s => ps.foldl (fun s p => collectVar p.x p.ty s) s
@[inline] def collectJP (j : JoinPointId) (xs : Array Param) : Collector
| (vs, js) => (vs, js.insert j xs)
/-- `collectFnBody` assumes the variables in -/
partial def collectFnBody : FnBody → Collector
| .vdecl x t _ b => collectVar x t ∘ collectFnBody b
| .jdecl j xs v b => collectJP j xs ∘ collectParams xs ∘ collectFnBody v ∘ collectFnBody b
| .case _ _ _ alts => fun s => alts.foldl (fun s alt => collectFnBody alt.body s) s
| e => if e.isTerminal then id else collectFnBody e.body
def collectDecl : Decl → Collector
| .fdecl (xs := xs) (body := b) .. => collectParams xs ∘ collectFnBody b
| _ => id
end CollectMaps
/-- Return a pair `(v, j)`, where `v` is a mapping from variable/parameter to type,
and `j` is a mapping from join point to parameters.
This function assumes `d` has normalized indexes (see `normids.lean`). -/
def mkVarJPMaps (d : Decl) : VarTypeMap × JPParamsMap :=
CollectMaps.collectDecl d ({}, {})
end IR
end Lean
|
e9984296b5a5806b3677071bac02661bd20c357f | 95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990 | /src/algebra/pi_instances.lean | 1bc89d868d90f095ef4aed684866a04006f02d03 | [
"Apache-2.0"
] | permissive | uniformity1/mathlib | 829341bad9dfa6d6be9adaacb8086a8a492e85a4 | dd0e9bd8f2e5ec267f68e72336f6973311909105 | refs/heads/master | 1,588,592,015,670 | 1,554,219,842,000 | 1,554,219,842,000 | 179,110,702 | 0 | 0 | Apache-2.0 | 1,554,220,076,000 | 1,554,220,076,000 | null | UTF-8 | Lean | false | false | 17,569 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
Pi instances for algebraic structures.
-/
import order.basic
import algebra.module algebra.group
import data.finset
import tactic.pi_instances
namespace pi
universes u v w
variable {I : Type u} -- The indexing type
variable {f : I → Type v} -- The family of types already equiped with instances
variables (x y : Π i, f i) (i : I)
instance has_zero [∀ i, has_zero $ f i] : has_zero (Π i : I, f i) := ⟨λ i, 0⟩
@[simp] lemma zero_apply [∀ i, has_zero $ f i] : (0 : Π i, f i) i = 0 := rfl
instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ i, 1⟩
@[simp] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl
attribute [to_additive pi.has_zero] pi.has_one
attribute [to_additive pi.zero_apply] pi.one_apply
instance has_add [∀ i, has_add $ f i] : has_add (Π i : I, f i) := ⟨λ x y, λ i, x i + y i⟩
@[simp] lemma add_apply [∀ i, has_add $ f i] : (x + y) i = x i + y i := rfl
instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ x y, λ i, x i * y i⟩
@[simp] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl
attribute [to_additive pi.has_add] pi.has_mul
attribute [to_additive pi.add_apply] pi.mul_apply
instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ x, λ i, (x i)⁻¹⟩
@[simp] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl
instance has_neg [∀ i, has_neg $ f i] : has_neg (Π i : I, f i) := ⟨λ x, λ i, -(x i)⟩
@[simp] lemma neg_apply [∀ i, has_neg $ f i] : (-x) i = -x i := rfl
attribute [to_additive pi.has_neg] pi.has_inv
attribute [to_additive pi.neg_apply] pi.inv_apply
instance has_scalar {α : Type*} [∀ i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩
@[simp] lemma smul_apply {α : Type*} [∀ i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl
instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by pi_instance
instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by pi_instance
instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by pi_instance
instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by pi_instance
instance group [∀ i, group $ f i] : group (Π i : I, f i) := by pi_instance
instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by pi_instance
instance add_semigroup [∀ i, add_semigroup $ f i] : add_semigroup (Π i : I, f i) := by pi_instance
instance add_comm_semigroup [∀ i, add_comm_semigroup $ f i] : add_comm_semigroup (Π i : I, f i) := by pi_instance
instance add_monoid [∀ i, add_monoid $ f i] : add_monoid (Π i : I, f i) := by pi_instance
instance add_comm_monoid [∀ i, add_comm_monoid $ f i] : add_comm_monoid (Π i : I, f i) := by pi_instance
instance add_group [∀ i, add_group $ f i] : add_group (Π i : I, f i) := by pi_instance
instance add_comm_group [∀ i, add_comm_group $ f i] : add_comm_group (Π i : I, f i) := by pi_instance
instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by pi_instance
instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by pi_instance
instance mul_action (α) {m : monoid α} [∀ i, mul_action α $ f i] : mul_action α (Π i : I, f i) :=
{ smul := λ c f i, c • f i,
mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _,
one_smul := λ f, funext $ λ i, one_smul α _ }
instance distrib_mul_action (α) {m : monoid α} [∀ i, add_monoid $ f i] [∀ i, distrib_mul_action α $ f i] : distrib_mul_action α (Π i : I, f i) :=
{ smul_zero := λ c, funext $ λ i, smul_zero _,
smul_add := λ c f g, funext $ λ i, smul_add _ _ _,
..pi.mul_action _ }
variables (I f)
instance semimodule (α) {r : semiring α} [∀ i, add_comm_monoid $ f i] [∀ i, semimodule α $ f i] : semimodule α (Π i : I, f i) :=
{ add_smul := λ c f g, funext $ λ i, add_smul _ _ _,
zero_smul := λ f, funext $ λ i, zero_smul α _,
..pi.distrib_mul_action _ }
variables {I f}
instance module (α) {r : ring α} [∀ i, add_comm_group $ f i] [∀ i, module α $ f i] : module α (Π i : I, f i) := {..pi.semimodule I f α}
instance vector_space (α) {r : discrete_field α} [∀ i, add_comm_group $ f i] [∀ i, vector_space α $ f i] : vector_space α (Π i : I, f i) := {..pi.module α}
instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance add_left_cancel_semigroup [∀ i, add_left_cancel_semigroup $ f i] : add_left_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance add_right_cancel_semigroup [∀ i, add_right_cancel_semigroup $ f i] : add_right_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) :=
by pi_instance
attribute [to_additive pi.add_semigroup] pi.semigroup
attribute [to_additive pi.add_comm_semigroup] pi.comm_semigroup
attribute [to_additive pi.add_monoid] pi.monoid
attribute [to_additive pi.add_comm_monoid] pi.comm_monoid
attribute [to_additive pi.add_group] pi.group
attribute [to_additive pi.add_comm_group] pi.comm_group
attribute [to_additive pi.add_left_cancel_semigroup] pi.left_cancel_semigroup
attribute [to_additive pi.add_right_cancel_semigroup] pi.right_cancel_semigroup
@[to_additive pi.list_sum_apply]
lemma list_prod_apply {α : Type*} {β : α → Type*} [∀a, monoid (β a)] (a : α) :
∀ (l : list (Πa, β a)), l.prod a = (l.map (λf:Πa, β a, f a)).prod
| [] := rfl
| (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l]
@[to_additive pi.multiset_sum_apply]
lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α)
(s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod :=
quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end
@[to_additive pi.finset_sum_apply]
lemma finset_prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α)
(s : finset γ) (g : γ → Πa, β a) : s.prod g a = s.prod (λc, g c a) :=
show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod,
by rw [multiset_prod_apply, multiset.map_map]
def is_ring_hom_pi
{α : Type u} {β : α → Type v} [R : Π a : α, ring (β a)]
{γ : Type w} [ring γ]
(f : Π a : α, γ → β a) [Rh : Π a : α, is_ring_hom (f a)] :
is_ring_hom (λ x b, f b x) :=
begin
dsimp at *,
split,
-- It's a pity that these can't be done using `simp` lemmas.
{ ext, rw [is_ring_hom.map_one (f x)], refl, },
{ intros x y, ext1 z, rw [is_ring_hom.map_mul (f z)], refl, },
{ intros x y, ext1 z, rw [is_ring_hom.map_add (f z)], refl, }
end
end pi
namespace prod
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {p q : α × β}
instance [has_add α] [has_add β] : has_add (α × β) :=
⟨λp q, (p.1 + q.1, p.2 + q.2)⟩
@[to_additive prod.has_add]
instance [has_mul α] [has_mul β] : has_mul (α × β) :=
⟨λp q, (p.1 * q.1, p.2 * q.2)⟩
@[simp, to_additive prod.fst_add]
lemma fst_mul [has_mul α] [has_mul β] : (p * q).1 = p.1 * q.1 := rfl
@[simp, to_additive prod.snd_add]
lemma snd_mul [has_mul α] [has_mul β] : (p * q).2 = p.2 * q.2 := rfl
@[simp, to_additive prod.mk_add_mk]
lemma mk_mul_mk [has_mul α] [has_mul β] (a₁ a₂ : α) (b₁ b₂ : β) :
(a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl
instance [has_zero α] [has_zero β] : has_zero (α × β) := ⟨(0, 0)⟩
@[to_additive prod.has_zero]
instance [has_one α] [has_one β] : has_one (α × β) := ⟨(1, 1)⟩
@[simp, to_additive prod.fst_zero]
lemma fst_one [has_one α] [has_one β] : (1 : α × β).1 = 1 := rfl
@[simp, to_additive prod.snd_zero]
lemma snd_one [has_one α] [has_one β] : (1 : α × β).2 = 1 := rfl
@[to_additive prod.zero_eq_mk]
lemma one_eq_mk [has_one α] [has_one β] : (1 : α × β) = (1, 1) := rfl
instance [has_neg α] [has_neg β] : has_neg (α × β) := ⟨λp, (- p.1, - p.2)⟩
@[to_additive prod.has_neg]
instance [has_inv α] [has_inv β] : has_inv (α × β) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩
@[simp, to_additive prod.fst_neg]
lemma fst_inv [has_inv α] [has_inv β] : (p⁻¹).1 = (p.1)⁻¹ := rfl
@[simp, to_additive prod.snd_neg]
lemma snd_inv [has_inv α] [has_inv β] : (p⁻¹).2 = (p.2)⁻¹ := rfl
@[to_additive prod.neg_mk]
lemma inv_mk [has_inv α] [has_inv β] (a : α) (b : β) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl
instance [add_semigroup α] [add_semigroup β] : add_semigroup (α × β) :=
{ add_assoc := assume a b c, mk.inj_iff.mpr ⟨add_assoc _ _ _, add_assoc _ _ _⟩,
.. prod.has_add }
@[to_additive prod.add_semigroup]
instance [semigroup α] [semigroup β] : semigroup (α × β) :=
{ mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩,
.. prod.has_mul }
instance [add_monoid α] [add_monoid β] : add_monoid (α × β) :=
{ zero_add := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨zero_add _, zero_add _⟩,
add_zero := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨add_zero _, add_zero _⟩,
.. prod.add_semigroup, .. prod.has_zero }
@[to_additive prod.add_monoid]
instance [monoid α] [monoid β] : monoid (α × β) :=
{ one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩,
mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩,
.. prod.semigroup, .. prod.has_one }
instance [add_group α] [add_group β] : add_group (α × β) :=
{ add_left_neg := assume a, mk.inj_iff.mpr ⟨add_left_neg _, add_left_neg _⟩,
.. prod.add_monoid, .. prod.has_neg }
@[to_additive prod.add_group]
instance [group α] [group β] : group (α × β) :=
{ mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩,
.. prod.monoid, .. prod.has_inv }
instance [add_comm_semigroup α] [add_comm_semigroup β] : add_comm_semigroup (α × β) :=
{ add_comm := assume a b, mk.inj_iff.mpr ⟨add_comm _ _, add_comm _ _⟩,
.. prod.add_semigroup }
@[to_additive prod.add_comm_semigroup]
instance [comm_semigroup α] [comm_semigroup β] : comm_semigroup (α × β) :=
{ mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩,
.. prod.semigroup }
instance [add_comm_monoid α] [add_comm_monoid β] : add_comm_monoid (α × β) :=
{ .. prod.add_comm_semigroup, .. prod.add_monoid }
@[to_additive prod.add_comm_monoid]
instance [comm_monoid α] [comm_monoid β] : comm_monoid (α × β) :=
{ .. prod.comm_semigroup, .. prod.monoid }
instance [add_comm_group α] [add_comm_group β] : add_comm_group (α × β) :=
{ .. prod.add_comm_semigroup, .. prod.add_group }
@[to_additive prod.add_comm_group]
instance [comm_group α] [comm_group β] : comm_group (α × β) :=
{ .. prod.comm_semigroup, .. prod.group }
@[to_additive fst.is_add_monoid_hom]
lemma fst.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.fst : α × β → α) :=
by refine_struct {..}; simp
@[to_additive snd.is_add_monoid_hom]
lemma snd.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.snd : α × β → β) :=
by refine_struct {..}; simp
@[to_additive fst.is_add_group_hom]
lemma fst.is_group_hom [group α] [group β] : is_group_hom (prod.fst : α × β → α) :=
by refine_struct {..}; simp
@[to_additive snd.is_add_group_hom]
lemma snd.is_group_hom [group α] [group β] : is_group_hom (prod.snd : α × β → β) :=
by refine_struct {..}; simp
attribute [instance] fst.is_monoid_hom fst.is_add_monoid_hom snd.is_monoid_hom snd.is_add_monoid_hom
fst.is_group_hom fst.is_add_group_hom snd.is_group_hom snd.is_add_group_hom
@[to_additive prod.fst_sum]
lemma fst_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} :
(t.prod f).1 = t.prod (λc, (f c).1) :=
(finset.prod_hom prod.fst).symm
@[to_additive prod.snd_sum]
lemma snd_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} :
(t.prod f).2 = t.prod (λc, (f c).2) :=
(finset.prod_hom prod.snd).symm
instance [semiring α] [semiring β] : semiring (α × β) :=
{ zero_mul := λ a, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩,
mul_zero := λ a, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩,
left_distrib := λ a b c, mk.inj_iff.mpr ⟨left_distrib _ _ _, left_distrib _ _ _⟩,
right_distrib := λ a b c, mk.inj_iff.mpr ⟨right_distrib _ _ _, right_distrib _ _ _⟩,
..prod.add_comm_monoid, ..prod.monoid }
instance [ring α] [ring β] : ring (α × β) :=
{ ..prod.add_comm_group, ..prod.semiring }
instance [comm_ring α] [comm_ring β] : comm_ring (α × β) :=
{ ..prod.ring, ..prod.comm_monoid }
instance [nonzero_comm_ring α] [comm_ring β] : nonzero_comm_ring (α × β) :=
{ zero_ne_one := mt (congr_arg prod.fst) zero_ne_one,
..prod.comm_ring }
instance fst.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.fst : α × β → α) :=
by refine_struct {..}; simp
instance snd.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.snd : α × β → β) :=
by refine_struct {..}; simp
instance fst.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.fst : α × β → α) :=
by refine_struct {..}; simp
instance snd.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.snd : α × β → β) :=
by refine_struct {..}; simp
/-- Left injection function for the inner product
From a vector space (and also group and module) perspective the product is the same as the sum of
two vector spaces. `inl` and `inr` provide the corresponding injection functions.
-/
def inl [has_zero β] (a : α) : α × β := (a, 0)
/-- Right injection function for the inner product -/
def inr [has_zero α] (b : β) : α × β := (0, b)
lemma injective_inl [has_zero β] : function.injective (inl : α → α × β) :=
assume x y h, (prod.mk.inj_iff.mp h).1
lemma injective_inr [has_zero α] : function.injective (inr : β → α × β) :=
assume x y h, (prod.mk.inj_iff.mp h).2
@[simp] lemma inl_eq_inl [has_zero β] {a₁ a₂ : α} : (inl a₁ : α × β) = inl a₂ ↔ a₁ = a₂ :=
iff.intro (assume h, injective_inl h) (assume h, h ▸ rfl)
@[simp] lemma inr_eq_inr [has_zero α] {b₁ b₂ : β} : (inr b₁ : α × β) = inr b₂ ↔ b₁ = b₂ :=
iff.intro (assume h, injective_inr h) (assume h, h ▸ rfl)
@[simp] lemma inl_eq_inr [has_zero α] [has_zero β] {a : α} {b : β} :
inl a = inr b ↔ a = 0 ∧ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma inr_eq_inl [has_zero α] [has_zero β] {a : α} {b : β} :
inr b = inl a ↔ a = 0 ∧ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma fst_inl [has_zero β] (a : α) : (inl a : α × β).1 = a := rfl
@[simp] lemma snd_inl [has_zero β] (a : α) : (inl a : α × β).2 = 0 := rfl
@[simp] lemma fst_inr [has_zero α] (b : β) : (inr b : α × β).1 = 0 := rfl
@[simp] lemma snd_inr [has_zero α] (b : β) : (inr b : α × β).2 = b := rfl
instance [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) := ⟨λa p, (a • p.1, a • p.2)⟩
@[simp] theorem smul_fst [has_scalar α β] [has_scalar α γ]
(a : α) (x : β × γ) : (a • x).1 = a • x.1 := rfl
@[simp] theorem smul_snd [has_scalar α β] [has_scalar α γ]
(a : α) (x : β × γ) : (a • x).2 = a • x.2 := rfl
@[simp] theorem smul_mk [has_scalar α β] [has_scalar α γ]
(a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) := rfl
instance {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ]
[semimodule α β] [semimodule α γ] : semimodule α (β × γ) :=
{ smul_add := assume a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩,
add_smul := assume a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩,
mul_smul := assume a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩,
one_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩,
zero_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩,
smul_zero := assume a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩,
.. prod.has_scalar }
instance {r : ring α} [add_comm_group β] [add_comm_group γ]
[module α β] [module α γ] : module α (β × γ) := {}
instance {r : discrete_field α} [add_comm_group β] [add_comm_group γ]
[vector_space α β] [vector_space α γ] : vector_space α (β × γ) := {}
end prod
namespace finset
@[to_additive finset.prod_mk_sum]
lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ)
(f : γ → α) (g : γ → β) : (s.prod f, s.prod g) = s.prod (λ x, (f x, g x)) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt})
end finset
|
f32393e1b3fc7370ad8864fcc5a6aef96f39e6b5 | caa1512363b76923d0e9cdb716122a5c26c3c6bc | /src/mat.lean | 2e27cad277aab7a2b23457cc7b049fb6e2268351 | [] | no_license | apurvanakade/cvx | deb20e425ce478159a98e1ffc0d37f9c88a89280 | b47784831339df5a3e45f5cddd84edc545f95808 | refs/heads/master | 1,687,403,288,536 | 1,555,930,740,000 | 1,555,930,740,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,832 | lean | import data.matrix data.real.basic
universes u v
namespace matrix
variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o]
variables {α : Type v}
-- TODO: move / generalize in matrix.lean
lemma mul_zero' [ring α] (M : matrix m n α) : M.mul (0 : matrix n l α) = 0 :=
begin
ext i j,
unfold matrix.mul,
simp
end
lemma mul_add' [ring α] (L : matrix m n α) (M N : matrix n l α) : L.mul (M + N) = L.mul M + L.mul N :=
begin
ext i j,
unfold matrix.mul,
simp [left_distrib, finset.sum_add_distrib]
end
lemma add_mul' [ring α] (M N : matrix m n α) (L : matrix n l α) : (M + N).mul L = M.mul L + N.mul L :=
begin
ext i j,
unfold matrix.mul,
simp [right_distrib, finset.sum_add_distrib]
end
@[simp] lemma mul_neg [ring α] (M : matrix m n α) (N : matrix n l α) : M.mul (-N) = - M.mul N :=
begin
ext i j,
unfold matrix.mul,
simp,
end
@[simp] lemma neg_mul [ring α] (M : matrix m n α) (N : matrix n l α) : (-M).mul N = - M.mul N :=
begin
ext i j,
unfold matrix.mul,
simp,
end
lemma mul_sub' [ring α] (L : matrix m n α) (M N : matrix n l α) : L.mul (M - N) = L.mul M - L.mul N :=
by simp [mul_add']
lemma sub_mul' [ring α] (M N : matrix m n α) (L : matrix n l α) : (M - N).mul L = M.mul L - N.mul L :=
by simp [add_mul']
@[simp] lemma mul_smul [comm_ring α] (M : matrix m n α) (a : α) (N : matrix n l α) : M.mul (a • N) = a • M.mul N :=
begin
ext i j,
unfold matrix.mul,
unfold has_scalar.smul,
rw finset.mul_sum,
congr,
ext,
ring
end
@[simp] lemma smul_mul [comm_ring α] (M : matrix m n α) (a : α) (N : matrix n l α) : (a • M).mul N = a • M.mul N :=
begin
ext i j,
unfold matrix.mul,
unfold has_scalar.smul,
rw finset.mul_sum,
congr,
ext,
ring
end
local postfix `ᵀ` : 1500 := transpose
lemma transpose_transpose (M : matrix m n α) :
Mᵀᵀ = M :=
by ext; unfold transpose
lemma transpose_mul [comm_ring α] (M : matrix m n α) (N : matrix n l α) :
(M.mul N)ᵀ = Nᵀ.mul Mᵀ :=
begin
ext i j,
unfold matrix.mul,
unfold transpose,
congr,
ext,
ring
end
lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) :
(M + N)ᵀ = Mᵀ + Nᵀ :=
begin
ext i j,
dsimp [transpose],
refl
end
-- TODO: add to mathlib
lemma transpose_smul [has_mul α] (a : α) (M : matrix m n α) :
(a • M)ᵀ = a • Mᵀ :=
by ext i j; refl
@[simp] lemma transpose_neg [comm_ring α] (M : matrix m n α) :
(- M)ᵀ = - Mᵀ :=
by ext i j; refl
@[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 :=
by ext i j; refl
-- TODO: add to mathlib
lemma eq_iff_transpose_eq (M : matrix m n α) (N : matrix m n α) : M = N ↔ Mᵀ = Nᵀ :=
begin
split,
{ intro h, ext i j, rw h },
{ intro h, ext i j, rw [←transpose_transpose M,h,transpose_transpose] },
end
end matrix
variables {k m n : nat}
variables {α : Type} [ring α]
@[reducible] def mat (α : Type) [ring α] (m n : nat) : Type :=
matrix (fin m) (fin n) α
@[reducible] def vec (α : Type) [ring α] (n : nat) : Type := (fin n) → α
local notation v `⬝` w := matrix.vec_mul_vec v w --TODO: matrix.vec_mul_vec is not the dot product but the outer vector product
namespace mat
def mem (a : α) (A : mat α m n) : Prop :=
∃ i : fin m, ∃ j : fin n, a = A i j
instance has_mem : has_mem α (mat α m n) := ⟨mem⟩
def trace_aux (A : mat α n n) : ∀ m, m ≤ n → α
| 0 h := 0
| (m+1) h :=
have h' : m < n := nat.lt_of_succ_le h,
A ⟨m,h'⟩ ⟨m,h'⟩ + trace_aux m (le_trans (nat.le_succ _) h)
def trace (A : mat α n n) : α := trace_aux A n (le_refl _)
def pos_semidef {α : Type} [ordered_ring α] (A : mat α n n) : Prop :=
∀ x : vec α n, ∀ a ∈ (x ⬝ (matrix.mul_vec A x)), (0 : α) ≤ a
def pos_def {α : Type} [ordered_ring α] (A : mat α n n) : Prop :=
∀ x : vec α n, x ≠ 0 → ∀ a ∈ (x ⬝ (matrix.mul_vec A x)), (0 : α) < a
def loewner {α : Type} [ordered_ring α] (A B : mat α n n) : Prop :=
pos_semidef (A - B)
infix `≼` : 1200 := loewner
infix `≽` : 1200 := λ A B, loewner B A
def strict_loewner [ordered_ring α] (A B : mat α n n) : Prop :=
A ≼ B ∧ A ≠ B
infix `≺` : 1200 := loewner
infix `≻` : 1200 := λ A B, strict_loewner B A
postfix `ᵀ` : 1500 := matrix.transpose
def get_diagonal (A : mat α m m) : mat α m m | i j :=
if i = j
then A i j
else 0
def lower_triangle (A : mat α m m) : mat α m m | i j :=
if i = j
then 1
else if i > j
then A i j
else 0
end mat
def lists_to_mat_core {m n : nat} (ls : list (list α))
(i : fin m) (j : fin n) : option α :=
do l ← ls.nth i.val, l.nth j.val
def lists_to_mat (m n : nat)
(ls : list (list α)) : mat α m n | i j :=
match lists_to_mat_core ls i j with
| none := 0
| (some a) := a
end
|
d54af522cad242e0a1ec9406d6fa68a5d62df0e2 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/limits/constructions/equalizers.lean | e311be168e3fc85fa129a6410feaaddcd3d823bb | [
"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 | 9,315 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Andrew Yang
-/
import category_theory.limits.shapes.equalizers
import category_theory.limits.shapes.binary_products
import category_theory.limits.shapes.pullbacks
import category_theory.limits.preserves.shapes.pullbacks
import category_theory.limits.preserves.shapes.binary_products
/-!
# Constructing equalizers from pullbacks and binary products.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
If a category has pullbacks and binary products, then it has equalizers.
TODO: generalize universe
-/
noncomputable theory
universes v v' u u'
open category_theory category_theory.category
namespace category_theory.limits
variables {C : Type u} [category.{v} C]
variables {D : Type u'} [category.{v'} D] (G : C ⥤ D)
-- We hide the "implementation details" inside a namespace
namespace has_equalizers_of_has_pullbacks_and_binary_products
variables [has_binary_products C] [has_pullbacks C]
/-- Define the equalizing object -/
@[reducible]
def construct_equalizer (F : walking_parallel_pair ⥤ C) : C :=
pullback (prod.lift (𝟙 _) (F.map walking_parallel_pair_hom.left))
(prod.lift (𝟙 _) (F.map walking_parallel_pair_hom.right))
/-- Define the equalizing morphism -/
abbreviation pullback_fst (F : walking_parallel_pair ⥤ C) :
construct_equalizer F ⟶ F.obj walking_parallel_pair.zero :=
pullback.fst
lemma pullback_fst_eq_pullback_snd (F : walking_parallel_pair ⥤ C) :
pullback_fst F = pullback.snd :=
by convert pullback.condition =≫ limits.prod.fst; simp
/-- Define the equalizing cone -/
@[reducible]
def equalizer_cone (F : walking_parallel_pair ⥤ C) : cone F :=
cone.of_fork
(fork.of_ι (pullback_fst F)
(begin
conv_rhs { rw pullback_fst_eq_pullback_snd, },
convert pullback.condition =≫ limits.prod.snd using 1; simp
end))
/-- Show the equalizing cone is a limit -/
def equalizer_cone_is_limit (F : walking_parallel_pair ⥤ C) : is_limit (equalizer_cone F) :=
{ lift :=
begin
intro c, apply pullback.lift (c.π.app _) (c.π.app _),
apply limit.hom_ext,
rintro (_ | _); simp
end,
fac' := by rintros c (_ | _); simp,
uniq' :=
begin
intros c _ J,
have J0 := J walking_parallel_pair.zero, simp at J0,
apply pullback.hom_ext,
{ rwa limit.lift_π },
{ erw [limit.lift_π, ← J0, pullback_fst_eq_pullback_snd] }
end }
end has_equalizers_of_has_pullbacks_and_binary_products
open has_equalizers_of_has_pullbacks_and_binary_products
/-- Any category with pullbacks and binary products, has equalizers. -/
-- This is not an instance, as it is not always how one wants to construct equalizers!
lemma has_equalizers_of_has_pullbacks_and_binary_products
[has_binary_products C] [has_pullbacks C] :
has_equalizers C :=
{ has_limit := λ F, has_limit.mk
{ cone := equalizer_cone F,
is_limit := equalizer_cone_is_limit F } }
local attribute[instance] has_pullback_of_preserves_pullback
/-- A functor that preserves pullbacks and binary products also presrves equalizers. -/
def preserves_equalizers_of_preserves_pullbacks_and_binary_products
[has_binary_products C] [has_pullbacks C]
[preserves_limits_of_shape (discrete walking_pair) G]
[preserves_limits_of_shape walking_cospan G] :
preserves_limits_of_shape walking_parallel_pair G :=
⟨λ K, preserves_limit_of_preserves_limit_cone (equalizer_cone_is_limit K) $
{ lift := λ c, begin
refine pullback.lift _ _ _ ≫ (@@preserves_pullback.iso _ _ _ _ _ _ _ _).inv,
{ exact c.π.app walking_parallel_pair.zero },
{ exact c.π.app walking_parallel_pair.zero },
apply (map_is_limit_of_preserves_of_is_limit G _ _ (prod_is_prod _ _)).hom_ext,
swap, apply_instance,
rintro (_|_),
{ simp only [category.assoc, ← G.map_comp, prod.lift_fst,
binary_fan.π_app_left, binary_fan.mk_fst], },
{ simp only [binary_fan.π_app_right, binary_fan.mk_snd,
category.assoc, ← G.map_comp, prod.lift_snd],
exact (c.π.naturality (walking_parallel_pair_hom.left)).symm.trans
(c.π.naturality (walking_parallel_pair_hom.right)) },
end,
fac' := λ c j, begin
rcases j with (_|_);
simp only [category.comp_id, preserves_pullback.iso_inv_fst, cone.of_fork_π, G.map_comp,
preserves_pullback.iso_inv_fst_assoc, functor.map_cone_π_app, eq_to_hom_refl,
category.assoc, fork.of_ι_π_app, pullback.lift_fst, pullback.lift_fst_assoc],
exact (c.π.naturality (walking_parallel_pair_hom.left)).symm.trans (category.id_comp _)
end,
uniq' := λ s m h, begin
rw iso.eq_comp_inv,
have := h walking_parallel_pair.zero,
dsimp [equalizer_cone] at this,
ext; simp only [preserves_pullback.iso_hom_snd,
category.assoc, preserves_pullback.iso_hom_fst, pullback.lift_fst, pullback.lift_snd,
category.comp_id, ← pullback_fst_eq_pullback_snd, ← this],
end }⟩
-- We hide the "implementation details" inside a namespace
namespace has_coequalizers_of_has_pushouts_and_binary_coproducts
variables [has_binary_coproducts C] [has_pushouts C]
/-- Define the equalizing object -/
@[reducible]
def construct_coequalizer (F : walking_parallel_pair ⥤ C) : C :=
pushout (coprod.desc (𝟙 _) (F.map walking_parallel_pair_hom.left))
(coprod.desc (𝟙 _) (F.map walking_parallel_pair_hom.right))
/-- Define the equalizing morphism -/
abbreviation pushout_inl (F : walking_parallel_pair ⥤ C) :
F.obj walking_parallel_pair.one ⟶ construct_coequalizer F :=
pushout.inl
lemma pushout_inl_eq_pushout_inr (F : walking_parallel_pair ⥤ C) :
pushout_inl F = pushout.inr :=
by convert limits.coprod.inl ≫= pushout.condition; simp
/-- Define the equalizing cocone -/
@[reducible]
def coequalizer_cocone (F : walking_parallel_pair ⥤ C) : cocone F :=
cocone.of_cofork
(cofork.of_π (pushout_inl F)
(begin
conv_rhs { rw pushout_inl_eq_pushout_inr, },
convert limits.coprod.inr ≫= pushout.condition using 1; simp
end))
/-- Show the equalizing cocone is a colimit -/
def coequalizer_cocone_is_colimit (F : walking_parallel_pair ⥤ C) :
is_colimit (coequalizer_cocone F) :=
{ desc :=
begin
intro c, apply pushout.desc (c.ι.app _) (c.ι.app _),
apply colimit.hom_ext,
rintro (_ | _); simp
end,
fac' := by rintros c (_ | _); simp,
uniq' :=
begin
intros c _ J,
have J1 : pushout_inl F ≫ m = c.ι.app walking_parallel_pair.one :=
by simpa using J walking_parallel_pair.one,
apply pushout.hom_ext,
{ rw colimit.ι_desc, exact J1 },
{ rw [colimit.ι_desc, ← pushout_inl_eq_pushout_inr], exact J1 }
end }
end has_coequalizers_of_has_pushouts_and_binary_coproducts
open has_coequalizers_of_has_pushouts_and_binary_coproducts
/-- Any category with pullbacks and binary products, has equalizers. -/
-- This is not an instance, as it is not always how one wants to construct equalizers!
lemma has_coequalizers_of_has_pushouts_and_binary_coproducts
[has_binary_coproducts C] [has_pushouts C] : has_coequalizers C :=
{ has_colimit := λ F, has_colimit.mk
{ cocone := coequalizer_cocone F,
is_colimit := coequalizer_cocone_is_colimit F } }
local attribute[instance] has_pushout_of_preserves_pushout
/-- A functor that preserves pushouts and binary coproducts also presrves coequalizers. -/
def preserves_coequalizers_of_preserves_pushouts_and_binary_coproducts
[has_binary_coproducts C] [has_pushouts C]
[preserves_colimits_of_shape (discrete walking_pair) G]
[preserves_colimits_of_shape walking_span G] :
preserves_colimits_of_shape walking_parallel_pair G :=
⟨λ K, preserves_colimit_of_preserves_colimit_cocone (coequalizer_cocone_is_colimit K) $
{ desc := λ c, begin
refine (@@preserves_pushout.iso _ _ _ _ _ _ _ _).inv ≫ pushout.desc _ _ _,
{ exact c.ι.app walking_parallel_pair.one },
{ exact c.ι.app walking_parallel_pair.one },
apply (map_is_colimit_of_preserves_of_is_colimit G _ _ (coprod_is_coprod _ _)).hom_ext,
swap, apply_instance,
rintro (_|_),
{ simp only [binary_cofan.ι_app_left, binary_cofan.mk_inl, category.assoc, ← G.map_comp_assoc,
coprod.inl_desc] },
{ simp only [binary_cofan.ι_app_right, binary_cofan.mk_inr, category.assoc, ← G.map_comp_assoc,
coprod.inr_desc],
exact (c.ι.naturality walking_parallel_pair_hom.left).trans
(c.ι.naturality walking_parallel_pair_hom.right).symm, },
end,
fac' := λ c j, begin
rcases j with (_|_); simp only [functor.map_cocone_ι_app, cocone.of_cofork_ι, category.id_comp,
eq_to_hom_refl, category.assoc, functor.map_comp, cofork.of_π_ι_app, pushout.inl_desc,
preserves_pushout.inl_iso_inv_assoc],
exact (c.ι.naturality (walking_parallel_pair_hom.left)).trans (category.comp_id _)
end,
uniq' := λ s m h, begin
rw iso.eq_inv_comp,
have := h walking_parallel_pair.one,
dsimp [coequalizer_cocone] at this,
ext; simp only [preserves_pushout.inl_iso_hom_assoc, category.id_comp, pushout.inl_desc,
pushout.inr_desc, preserves_pushout.inr_iso_hom_assoc,
← pushout_inl_eq_pushout_inr, ← this],
end }⟩
end category_theory.limits
|
3ee0e606d144a4d782b5d2e44dd818e49618ff5e | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /src/Init/Data/Float.lean | 9b0d86e53b1ba900491be19d394ad1980989cf6c | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,564 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Core
import Init.Data.Int.Basic
import Init.Data.ToString.Basic
structure FloatSpec where
float : Type
val : float
lt : float → float → Prop
le : float → float → Prop
decLt : DecidableRel lt
decLe : DecidableRel le
-- Just show FloatSpec is inhabited.
constant floatSpec : FloatSpec := {
float := Unit,
val := (),
lt := fun _ _ => True,
le := fun _ _ => True,
decLt := fun _ _ => inferInstanceAs (Decidable True),
decLe := fun _ _ => inferInstanceAs (Decidable True)
}
structure Float where
val : floatSpec.float
instance : Inhabited Float := ⟨{ val := floatSpec.val }⟩
@[extern "lean_float_of_nat"] constant Float.ofNat : (@& Nat) → Float
@[extern c inline "#1 + #2"] constant Float.add : Float → Float → Float
@[extern c inline "#1 - #2"] constant Float.sub : Float → Float → Float
@[extern c inline "#1 * #2"] constant Float.mul : Float → Float → Float
@[extern c inline "#1 / #2"] constant Float.div : Float → Float → Float
@[extern c inline "(- #1)"] constant Float.neg : Float → Float
def Float.ofInt : Int → Float
| Int.ofNat n => Float.ofNat n
| Int.negSucc n => Float.neg (Float.ofNat (Nat.succ n))
set_option bootstrap.genMatcherCode false
def Float.lt : Float → Float → Prop := fun a b =>
match a, b with
| ⟨a⟩, ⟨b⟩ => floatSpec.lt a b
def Float.le : Float → Float → Prop := fun a b =>
floatSpec.le a.val b.val
instance : OfNat Float n := ⟨Float.ofNat n⟩
instance : Add Float := ⟨Float.add⟩
instance : Sub Float := ⟨Float.sub⟩
instance : Mul Float := ⟨Float.mul⟩
instance : Div Float := ⟨Float.div⟩
instance : Neg Float := ⟨Float.neg⟩
instance : LT Float := ⟨Float.lt⟩
instance : LE Float := ⟨Float.le⟩
@[extern c inline "#1 == #2"] constant Float.beq (a b : Float) : Bool
instance : BEq Float := ⟨Float.beq⟩
@[extern c inline "#1 < #2"] constant Float.decLt (a b : Float) : Decidable (a < b) :=
match a, b with
| ⟨a⟩, ⟨b⟩ => floatSpec.decLt a b
@[extern c inline "#1 <= #2"] constant Float.decLe (a b : Float) : Decidable (a ≤ b) :=
match a, b with
| ⟨a⟩, ⟨b⟩ => floatSpec.decLe a b
instance floatDecLt (a b : Float) : Decidable (a < b) := Float.decLt a b
instance floatDecLe (a b : Float) : Decidable (a ≤ b) := Float.decLe a b
@[extern "lean_float_to_string"] constant Float.toString : Float → String
@[extern c inline "(uint8_t)#1"] constant Float.toUInt8 : Float → UInt8
@[extern c inline "(uint16_t)#1"] constant Float.toUInt16 : Float → UInt16
@[extern c inline "(uint32_t)#1"] constant Float.toUInt32 : Float → UInt32
@[extern c inline "(uint64_t)#1"] constant Float.toUInt64 : Float → UInt64
@[extern c inline "(size_t)#1"] constant Float.toUSize : Float → USize
instance : ToString Float where
toString := Float.toString
instance : Repr Float where
reprPrec n _ := Float.toString n
instance : ReprAtom Float := ⟨⟩
abbrev Nat.toFloat (n : Nat) : Float :=
Float.ofNat n
@[extern "sin"] constant Float.sin : Float → Float
@[extern "cos"] constant Float.cos : Float → Float
@[extern "tan"] constant Float.tan : Float → Float
@[extern "asin"] constant Float.asin : Float → Float
@[extern "acos"] constant Float.acos : Float → Float
@[extern "atan"] constant Float.atan : Float → Float
@[extern "atan2"] constant Float.atan2 : Float → Float → Float
@[extern "sinh"] constant Float.sinh : Float → Float
@[extern "cosh"] constant Float.cosh : Float → Float
@[extern "tanh"] constant Float.tanh : Float → Float
@[extern "asinh"] constant Float.asinh : Float → Float
@[extern "acosh"] constant Float.acosh : Float → Float
@[extern "atanh"] constant Float.atanh : Float → Float
@[extern "exp"] constant Float.exp : Float → Float
@[extern "exp2"] constant Float.exp2 : Float → Float
@[extern "log"] constant Float.log : Float → Float
@[extern "log2"] constant Float.log2 : Float → Float
@[extern "log10"] constant Float.log10 : Float → Float
@[extern "pow"] constant Float.pow : Float → Float → Float
@[extern "sqrt"] constant Float.sqrt : Float → Float
@[extern "cbrt"] constant Float.cbrt : Float → Float
instance : Pow Float Float := ⟨Float.pow⟩
@[extern "lean_float_of_scientific"] constant Float.ofScientific (m : Nat) (s : Bool) (e : Nat) : Float
|
5ebba6e1df0285a0c32348e5fa92d409a6cf9edc | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/data/complex/is_R_or_C.lean | 3c3a368b4f371c11523c6e712ee55870f2f0b0e8 | [
"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 | 37,133 | lean | /-
Copyright (c) 2020 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 data.real.sqrt
import field_theory.tower
import analysis.normed_space.finite_dimension
import analysis.normed_space.star.basic
/-!
# `is_R_or_C`: a typeclass for ℝ or ℂ
This file defines the typeclass `is_R_or_C` intended to have only two instances:
ℝ and ℂ. It is meant for definitions and theorems which hold for both the real and the complex case,
and in particular when the real case follows directly from the complex case by setting `re` to `id`,
`im` to zero and so on. Its API follows closely that of ℂ.
Applications include defining inner products and Hilbert spaces for both the real and
complex case. One typically produces the definitions and proof for an arbitrary field of this
typeclass, which basically amounts to doing the complex case, and the two cases then fall out
immediately from the two instances of the class.
The instance for `ℝ` is registered in this file.
The instance for `ℂ` is declared in `analysis.complex.basic`.
## Implementation notes
The coercion from reals into an `is_R_or_C` field is done by registering `algebra_map ℝ K` as
a `has_coe_t`. For this to work, we must proceed carefully to avoid problems involving circular
coercions in the case `K=ℝ`; in particular, we cannot use the plain `has_coe` and must set
priorities carefully. This problem was already solved for `ℕ`, and we copy the solution detailed
in `data/nat/cast`. See also Note [coercion into rings] for more details.
In addition, several lemmas need to be set at priority 900 to make sure that they do not override
their counterparts in `complex.lean` (which causes linter errors).
-/
open_locale big_operators
section
local notation `𝓚` := algebra_map ℝ _
open_locale complex_conjugate
/--
This typeclass captures properties shared by ℝ and ℂ, with an API that closely matches that of ℂ.
-/
class is_R_or_C (K : Type*)
extends densely_normed_field K, star_ring K, normed_algebra ℝ K, complete_space K :=
(re : K →+ ℝ)
(im : K →+ ℝ)
(I : K) -- Meant to be set to 0 for K=ℝ
(I_re_ax : re I = 0)
(I_mul_I_ax : I = 0 ∨ I * I = -1)
(re_add_im_ax : ∀ (z : K), 𝓚 (re z) + 𝓚 (im z) * I = z)
(of_real_re_ax : ∀ r : ℝ, re (𝓚 r) = r)
(of_real_im_ax : ∀ r : ℝ, im (𝓚 r) = 0)
(mul_re_ax : ∀ z w : K, re (z * w) = re z * re w - im z * im w)
(mul_im_ax : ∀ z w : K, im (z * w) = re z * im w + im z * re w)
(conj_re_ax : ∀ z : K, re (conj z) = re z)
(conj_im_ax : ∀ z : K, im (conj z) = -(im z))
(conj_I_ax : conj I = -I)
(norm_sq_eq_def_ax : ∀ (z : K), ∥z∥^2 = (re z) * (re z) + (im z) * (im z))
(mul_im_I_ax : ∀ (z : K), (im z) * im I = im z)
(inv_def_ax : ∀ (z : K), z⁻¹ = conj z * 𝓚 ((∥z∥^2)⁻¹))
(div_I_ax : ∀ (z : K), z / I = -(z * I))
end
mk_simp_attribute is_R_or_C_simps "Simp attribute for lemmas about `is_R_or_C`"
variables {K E : Type*} [is_R_or_C K]
namespace is_R_or_C
open_locale complex_conjugate
/- The priority must be set at 900 to ensure that coercions are tried in the right order.
See Note [coercion into rings], or `data/nat/cast.lean` for more details. -/
@[priority 900] noncomputable instance algebra_map_coe : has_coe_t ℝ K := ⟨algebra_map ℝ K⟩
lemma of_real_alg (x : ℝ) : (x : K) = x • (1 : K) :=
algebra.algebra_map_eq_smul_one x
lemma real_smul_eq_coe_mul (r : ℝ) (z : K) : r • z = (r : K) * z :=
by rw [is_R_or_C.of_real_alg, ←smul_eq_mul, smul_assoc, smul_eq_mul, one_mul]
lemma real_smul_eq_coe_smul [add_comm_group E] [module K E] [module ℝ E] [is_scalar_tower ℝ K E]
(r : ℝ) (x : E) : r • x = (r : K) • x :=
by rw [is_R_or_C.of_real_alg, smul_one_smul]
lemma algebra_map_eq_of_real : ⇑(algebra_map ℝ K) = coe := rfl
@[simp, is_R_or_C_simps] lemma re_add_im (z : K) : ((re z) : K) + (im z) * I = z :=
is_R_or_C.re_add_im_ax z
@[simp, norm_cast, is_R_or_C_simps] lemma of_real_re : ∀ r : ℝ, re (r : K) = r :=
is_R_or_C.of_real_re_ax
@[simp, norm_cast, is_R_or_C_simps] lemma of_real_im : ∀ r : ℝ, im (r : K) = 0 :=
is_R_or_C.of_real_im_ax
@[simp, is_R_or_C_simps] lemma mul_re : ∀ z w : K, re (z * w) = re z * re w - im z * im w :=
is_R_or_C.mul_re_ax
@[simp, is_R_or_C_simps] lemma mul_im : ∀ z w : K, im (z * w) = re z * im w + im z * re w :=
is_R_or_C.mul_im_ax
theorem inv_def (z : K) : z⁻¹ = conj z * ((∥z∥^2)⁻¹:ℝ) :=
is_R_or_C.inv_def_ax z
theorem ext_iff : ∀ {z w : K}, z = w ↔ re z = re w ∧ im z = im w :=
λ z w, { mp := by { rintro rfl, cc },
mpr := by { rintro ⟨h₁,h₂⟩, rw [←re_add_im z, ←re_add_im w, h₁, h₂] } }
theorem ext : ∀ {z w : K}, re z = re w → im z = im w → z = w :=
by { simp_rw ext_iff, cc }
@[simp, norm_cast, is_R_or_C_simps, priority 900] lemma of_real_zero : ((0 : ℝ) : K) = 0 :=
by rw [of_real_alg, zero_smul]
@[simp, is_R_or_C_simps] lemma zero_re' : re (0 : K) = (0 : ℝ) := re.map_zero
@[simp, norm_cast, is_R_or_C_simps, priority 900] lemma of_real_one : ((1 : ℝ) : K) = 1 :=
by rw [of_real_alg, one_smul]
@[simp, is_R_or_C_simps] lemma one_re : re (1 : K) = 1 := by rw [←of_real_one, of_real_re]
@[simp, is_R_or_C_simps] lemma one_im : im (1 : K) = 0 := by rw [←of_real_one, of_real_im]
@[simp, norm_cast, priority 900] theorem of_real_inj {z w : ℝ} : (z : K) = (w : K) ↔ z = w :=
{ mp := λ h, by { convert congr_arg re h; simp only [of_real_re] },
mpr := λ h, by rw h }
@[simp, is_R_or_C_simps] lemma bit0_re (z : K) : re (bit0 z) = bit0 (re z) :=
by simp only [bit0, map_add]
@[simp, is_R_or_C_simps] lemma bit1_re (z : K) : re (bit1 z) = bit1 (re z) :=
by simp only [bit1, add_monoid_hom.map_add, bit0_re, add_right_inj, one_re]
@[simp, is_R_or_C_simps] lemma bit0_im (z : K) : im (bit0 z) = bit0 (im z) :=
by simp only [bit0, map_add]
@[simp, is_R_or_C_simps] lemma bit1_im (z : K) : im (bit1 z) = bit0 (im z) :=
by simp only [bit1, add_right_eq_self, add_monoid_hom.map_add, bit0_im, one_im]
@[simp, is_R_or_C_simps, priority 900]
theorem of_real_eq_zero {z : ℝ} : (z : K) = 0 ↔ z = 0 :=
by rw [←of_real_zero]; exact of_real_inj
theorem of_real_ne_zero {z : ℝ} : (z : K) ≠ 0 ↔ z ≠ 0 := of_real_eq_zero.not
@[simp, is_R_or_C_simps, norm_cast, priority 900]
lemma of_real_add ⦃r s : ℝ⦄ : ((r + s : ℝ) : K) = r + s :=
by { apply (@is_R_or_C.ext_iff K _ ((r + s : ℝ) : K) (r + s)).mpr, simp }
@[simp, is_R_or_C_simps, norm_cast, priority 900]
lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : K) = bit0 (r : K) :=
ext_iff.2 $ by simp [bit0]
@[simp, is_R_or_C_simps, norm_cast, priority 900]
lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : K) = bit1 (r : K) :=
ext_iff.2 $ by simp [bit1]
/- Note: This can be proven by `norm_num` once K is proven to be of characteristic zero below. -/
lemma two_ne_zero : (2 : K) ≠ 0 :=
begin
intro h, rw [(show (2 : K) = ((2 : ℝ) : K), by norm_num), ←of_real_zero, of_real_inj] at h,
linarith,
end
@[simp, norm_cast, is_R_or_C_simps, priority 900]
lemma of_real_neg (r : ℝ) : ((-r : ℝ) : K) = -r := ext_iff.2 $ by simp
@[simp, norm_cast, is_R_or_C_simps, priority 900]
lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : K) = r * s := ext_iff.2 $ by simp with is_R_or_C_simps
@[simp, norm_cast, is_R_or_C_simps]
lemma of_real_smul (r x : ℝ) : r • (x : K) = (r : K) * (x : K) :=
begin
simp_rw [← smul_eq_mul, of_real_alg r],
simp only [algebra.id.smul_eq_mul, one_mul, algebra.smul_mul_assoc],
end
@[is_R_or_C_simps] lemma of_real_mul_re (r : ℝ) (z : K) : re (↑r * z) = r * re z :=
by simp only [mul_re, of_real_im, zero_mul, of_real_re, sub_zero]
@[is_R_or_C_simps] lemma of_real_mul_im (r : ℝ) (z : K) : im (↑r * z) = r * (im z) :=
by simp only [add_zero, of_real_im, zero_mul, of_real_re, mul_im]
@[is_R_or_C_simps] lemma smul_re : ∀ (r : ℝ) (z : K), re (r • z) = r * (re z) :=
λ r z, by { rw algebra.smul_def, apply of_real_mul_re }
@[is_R_or_C_simps] lemma smul_im : ∀ (r : ℝ) (z : K), im (r • z) = r * (im z) :=
λ r z, by { rw algebra.smul_def, apply of_real_mul_im }
/-! ### The imaginary unit, `I` -/
/-- The imaginary unit. -/
@[simp, is_R_or_C_simps] lemma I_re : re (I : K) = 0 := I_re_ax
@[simp, is_R_or_C_simps] lemma I_im (z : K) : im z * im (I : K) = im z := mul_im_I_ax z
@[simp, is_R_or_C_simps] lemma I_im' (z : K) : im (I : K) * im z = im z :=
by rw [mul_comm, I_im _]
@[simp, is_R_or_C_simps] lemma I_mul_re (z : K) : re (I * z) = - im z :=
by simp only [I_re, zero_sub, I_im', zero_mul, mul_re]
lemma I_mul_I : (I : K) = 0 ∨ (I : K) * I = -1 := I_mul_I_ax
@[simp, is_R_or_C_simps] lemma conj_re (z : K) : re (conj z) = re z := is_R_or_C.conj_re_ax z
@[simp, is_R_or_C_simps] lemma conj_im (z : K) : im (conj z) = -(im z) := is_R_or_C.conj_im_ax z
@[simp, is_R_or_C_simps] lemma conj_I : conj (I : K) = -I := is_R_or_C.conj_I_ax
@[simp, is_R_or_C_simps] lemma conj_of_real (r : ℝ) : conj (r : K) = (r : K) :=
by { rw ext_iff, simp only [of_real_im, conj_im, eq_self_iff_true, conj_re, and_self, neg_zero] }
@[simp, is_R_or_C_simps] lemma conj_bit0 (z : K) : conj (bit0 z) = bit0 (conj z) :=
by simp only [bit0, ring_hom.map_add, eq_self_iff_true]
@[simp, is_R_or_C_simps] lemma conj_bit1 (z : K) : conj (bit1 z) = bit1 (conj z) :=
by simp only [bit0, ext_iff, bit1_re, conj_im, eq_self_iff_true, conj_re, neg_add_rev,
and_self, bit1_im]
@[simp, is_R_or_C_simps] lemma conj_neg_I : conj (-I) = (I : K) :=
by simp only [conj_I, ring_hom.map_neg, eq_self_iff_true, neg_neg]
lemma conj_eq_re_sub_im (z : K) : conj z = re z - (im z) * I :=
by { rw ext_iff, simp only [add_zero, I_re, of_real_im, I_im, zero_sub, zero_mul, conj_im,
of_real_re, eq_self_iff_true, sub_zero, conj_re, mul_im, neg_inj,
and_self, mul_re, mul_zero, map_sub], }
@[is_R_or_C_simps] lemma conj_smul (r : ℝ) (z : K) : conj (r • z) = r • conj z :=
begin
simp_rw conj_eq_re_sub_im,
simp only [smul_re, smul_im, of_real_mul],
rw smul_sub,
simp_rw of_real_alg,
simp only [one_mul, algebra.smul_mul_assoc],
end
lemma eq_conj_iff_real {z : K} : conj z = z ↔ ∃ r : ℝ, z = (r : K) :=
begin
split,
{ intro h,
suffices : im z = 0,
{ use (re z),
rw ← add_zero (coe _),
convert (re_add_im z).symm, simp [this] },
contrapose! h,
rw ← re_add_im z,
simp only [conj_of_real, ring_hom.map_add, ring_hom.map_mul, conj_I_ax],
rw [add_left_cancel_iff, ext_iff],
simpa [neg_eq_iff_add_eq_zero, add_self_eq_zero] },
{ rintros ⟨r, rfl⟩, apply conj_of_real }
end
@[simp] lemma star_def : (has_star.star : K → K) = conj := rfl
variables (K)
/-- Conjugation as a ring equivalence. This is used to convert the inner product into a
sesquilinear product. -/
abbreviation conj_to_ring_equiv : K ≃+* Kᵐᵒᵖ := star_ring_equiv
variables {K}
lemma eq_conj_iff_re {z : K} : conj z = z ↔ ((re z) : K) = z :=
eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩
/-- The norm squared function. -/
def norm_sq : K →*₀ ℝ :=
{ to_fun := λ z, re z * re z + im z * im z,
map_zero' := by simp only [add_zero, mul_zero, map_zero],
map_one' := by simp only [one_im, add_zero, mul_one, one_re, mul_zero],
map_mul' := λ z w, by { simp only [mul_im, mul_re], ring } }
lemma norm_sq_eq_def {z : K} : ∥z∥^2 = (re z) * (re z) + (im z) * (im z) := norm_sq_eq_def_ax z
lemma norm_sq_eq_def' (z : K) : norm_sq z = ∥z∥^2 := by { rw norm_sq_eq_def, refl }
@[simp, is_R_or_C_simps] lemma norm_sq_of_real (r : ℝ) : ∥(r : K)∥^2 = r * r :=
by simp only [norm_sq_eq_def, add_zero, mul_zero] with is_R_or_C_simps
@[is_R_or_C_simps] lemma norm_sq_zero : norm_sq (0 : K) = 0 := norm_sq.map_zero
@[is_R_or_C_simps] lemma norm_sq_one : norm_sq (1 : K) = 1 := norm_sq.map_one
lemma norm_sq_nonneg (z : K) : 0 ≤ norm_sq z :=
add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)
@[simp, is_R_or_C_simps] lemma norm_sq_eq_zero {z : K} : norm_sq z = 0 ↔ z = 0 :=
by { rw [norm_sq_eq_def'], simp [sq] }
@[simp, is_R_or_C_simps] lemma norm_sq_pos {z : K} : 0 < norm_sq z ↔ z ≠ 0 :=
by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg]
@[simp, is_R_or_C_simps] lemma norm_sq_neg (z : K) : norm_sq (-z) = norm_sq z :=
by simp only [norm_sq_eq_def', norm_neg]
@[simp, is_R_or_C_simps] lemma norm_sq_conj (z : K) : norm_sq (conj z) = norm_sq z :=
by simp only [norm_sq, neg_mul, monoid_with_zero_hom.coe_mk,
mul_neg, neg_neg] with is_R_or_C_simps
@[simp, is_R_or_C_simps] lemma norm_sq_mul (z w : K) : norm_sq (z * w) = norm_sq z * norm_sq w :=
norm_sq.map_mul z w
lemma norm_sq_add (z w : K) :
norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (re (z * conj w)) :=
by { simp only [norm_sq, map_add, monoid_with_zero_hom.coe_mk, mul_neg,
sub_neg_eq_add] with is_R_or_C_simps, ring }
lemma re_sq_le_norm_sq (z : K) : re z * re z ≤ norm_sq z :=
le_add_of_nonneg_right (mul_self_nonneg _)
lemma im_sq_le_norm_sq (z : K) : im z * im z ≤ norm_sq z :=
le_add_of_nonneg_left (mul_self_nonneg _)
theorem mul_conj (z : K) : z * conj z = ((norm_sq z) : K) :=
by simp only [map_add, add_zero, ext_iff, monoid_with_zero_hom.coe_mk,
add_left_inj, mul_eq_mul_left_iff, zero_mul, add_comm, true_or, eq_self_iff_true,
mul_neg, add_right_neg, zero_add, norm_sq, mul_comm, and_self,
neg_neg, mul_zero, sub_eq_neg_add, neg_zero] with is_R_or_C_simps
theorem add_conj (z : K) : z + conj z = 2 * (re z) :=
by simp only [ext_iff, two_mul, map_add, add_zero, of_real_im, conj_im, of_real_re,
eq_self_iff_true, add_right_neg, conj_re, and_self]
/-- The pseudo-coercion `of_real` as a `ring_hom`. -/
noncomputable def of_real_hom : ℝ →+* K := algebra_map ℝ K
/-- The coercion from reals as a `ring_hom`. -/
noncomputable def coe_hom : ℝ →+* K := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩
@[simp, norm_cast, is_R_or_C_simps, priority 900] lemma of_real_sub (r s : ℝ) :
((r - s : ℝ) : K) = r - s :=
ext_iff.2 $ by simp only [of_real_im, of_real_re, eq_self_iff_true, sub_zero, and_self, map_sub]
@[simp, norm_cast, is_R_or_C_simps, priority 900] lemma of_real_pow (r : ℝ) (n : ℕ) :
((r ^ n : ℝ) : K) = r ^ n :=
begin
induction n,
{ simp only [of_real_one, pow_zero]},
{ simp only [*, of_real_mul, pow_succ]}
end
theorem sub_conj (z : K) : z - conj z = (2 * im z) * I :=
by simp only [ext_iff, two_mul, sub_eq_add_neg, add_mul, map_add, add_zero, add_left_inj, zero_mul,
map_add_neg, eq_self_iff_true, add_right_neg, and_self, neg_neg, mul_zero, neg_zero]
with is_R_or_C_simps
lemma norm_sq_sub (z w : K) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * re (z * conj w) :=
by simp only [norm_sq_add, sub_eq_add_neg, ring_equiv.map_neg, mul_neg,
norm_sq_neg, map_neg]
lemma sqrt_norm_sq_eq_norm {z : K} : real.sqrt (norm_sq z) = ∥z∥ :=
begin
have h₂ : ∥z∥ = real.sqrt (∥z∥^2) := (real.sqrt_sq (norm_nonneg z)).symm,
rw [h₂],
exact congr_arg real.sqrt (norm_sq_eq_def' z)
end
/-! ### Inversion -/
@[simp, is_R_or_C_simps] lemma inv_re (z : K) : re (z⁻¹) = re z / norm_sq z :=
by simp only [inv_def, norm_sq_eq_def, norm_sq, division_def,
monoid_with_zero_hom.coe_mk, sub_zero, mul_zero] with is_R_or_C_simps
@[simp, is_R_or_C_simps] lemma inv_im (z : K) : im (z⁻¹) = im (-z) / norm_sq z :=
by simp only [inv_def, norm_sq_eq_def, norm_sq, division_def, of_real_im,
monoid_with_zero_hom.coe_mk, of_real_re, zero_add, map_neg, mul_zero]
with is_R_or_C_simps
@[simp, norm_cast, is_R_or_C_simps, priority 900]
lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : K) = r⁻¹ :=
begin
rw ext_iff,
by_cases r = 0,
{ simp only [h, of_real_zero, inv_zero, and_self, map_zero]},
{ simp only with is_R_or_C_simps,
field_simp [h, norm_sq] }
end
protected lemma inv_zero : (0⁻¹ : K) = 0 :=
by rw [← of_real_zero, ← of_real_inv, inv_zero]
protected theorem mul_inv_cancel {z : K} (h : z ≠ 0) : z * z⁻¹ = 1 :=
by rw [inv_def, ←mul_assoc, mul_conj, ←of_real_mul, ←norm_sq_eq_def',
mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one]
lemma div_re (z w : K) : re (z / w) = re z * re w / norm_sq w + im z * im w / norm_sq w :=
by simp only [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, neg_mul,
mul_neg, neg_neg, map_neg] with is_R_or_C_simps
lemma div_im (z w : K) : im (z / w) = im z * re w / norm_sq w - re z * im w / norm_sq w :=
by simp only [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm, neg_mul,
mul_neg, map_neg] with is_R_or_C_simps
@[simp, is_R_or_C_simps]
lemma conj_inv (x : K) : conj (x⁻¹) = (conj x)⁻¹ := star_inv' _
@[simp, norm_cast, is_R_or_C_simps, priority 900] lemma of_real_div (r s : ℝ) :
((r / s : ℝ) : K) = r / s :=
map_div₀ (@is_R_or_C.coe_hom K _) r s
lemma div_re_of_real {z : K} {r : ℝ} : re (z / r) = re z / r :=
begin
by_cases h : r = 0,
{ simp only [h, of_real_zero, div_zero, zero_re']},
{ change r ≠ 0 at h,
rw [div_eq_mul_inv, ←of_real_inv, div_eq_mul_inv],
simp only [one_div, of_real_im, of_real_re, sub_zero, mul_re, mul_zero]}
end
@[simp, norm_cast, is_R_or_C_simps, priority 900] lemma of_real_zpow (r : ℝ) (n : ℤ) :
((r ^ n : ℝ) : K) = r ^ n :=
map_zpow₀ (@is_R_or_C.coe_hom K _) r n
lemma I_mul_I_of_nonzero : (I : K) ≠ 0 → (I : K) * I = -1 :=
by { have := I_mul_I_ax, tauto }
@[simp, is_R_or_C_simps] lemma div_I (z : K) : z / I = -(z * I) :=
begin
by_cases h : (I : K) = 0,
{ simp [h] },
{ field_simp [mul_assoc, I_mul_I_of_nonzero h] }
end
@[simp, is_R_or_C_simps] lemma inv_I : (I : K)⁻¹ = -I :=
by field_simp
@[simp, is_R_or_C_simps] lemma norm_sq_inv (z : K) : norm_sq z⁻¹ = (norm_sq z)⁻¹ :=
map_inv₀ (@norm_sq K _) z
@[simp, is_R_or_C_simps] lemma norm_sq_div (z w : K) : norm_sq (z / w) = norm_sq z / norm_sq w :=
map_div₀ (@norm_sq K _) z w
@[is_R_or_C_simps] lemma norm_conj {z : K} : ∥conj z∥ = ∥z∥ :=
by simp only [←sqrt_norm_sq_eq_norm, norm_sq_conj]
@[priority 100] instance : cstar_ring K :=
{ norm_star_mul_self := λ x, (norm_mul _ _).trans $ congr_arg (* ∥x∥) norm_conj }
/-! ### Cast lemmas -/
@[simp, is_R_or_C_simps, norm_cast, priority 900] theorem of_real_nat_cast (n : ℕ) :
((n : ℝ) : K) = n :=
map_nat_cast (@of_real_hom K _) n
@[simp, is_R_or_C_simps, norm_cast] lemma nat_cast_re (n : ℕ) : re (n : K) = n :=
by rw [← of_real_nat_cast, of_real_re]
@[simp, is_R_or_C_simps, norm_cast] lemma nat_cast_im (n : ℕ) : im (n : K) = 0 :=
by rw [← of_real_nat_cast, of_real_im]
@[simp, is_R_or_C_simps, norm_cast, priority 900]
lemma of_real_int_cast (n : ℤ) : ((n : ℝ) : K) = n := map_int_cast (@of_real_hom K _) n
@[simp, is_R_or_C_simps, norm_cast] lemma int_cast_re (n : ℤ) : re (n : K) = n :=
by rw [← of_real_int_cast, of_real_re]
@[simp, is_R_or_C_simps, norm_cast] lemma int_cast_im (n : ℤ) : im (n : K) = 0 :=
by rw [← of_real_int_cast, of_real_im]
@[simp, is_R_or_C_simps, norm_cast, priority 900] theorem of_real_rat_cast (n : ℚ) :
((n : ℝ) : K) = n :=
map_rat_cast (@is_R_or_C.of_real_hom K _) n
@[simp, is_R_or_C_simps, norm_cast] lemma rat_cast_re (q : ℚ) : re (q : K) = q :=
by rw [← of_real_rat_cast, of_real_re]
@[simp, is_R_or_C_simps, norm_cast] lemma rat_cast_im (q : ℚ) : im (q : K) = 0 :=
by rw [← of_real_rat_cast, of_real_im]
/-! ### Characteristic zero -/
/-- ℝ and ℂ are both of characteristic zero. -/
@[priority 100] -- see Note [lower instance priority]
instance char_zero_R_or_C : char_zero K :=
char_zero_of_inj_zero $ λ n h,
by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h
theorem re_eq_add_conj (z : K) : ↑(re z) = (z + conj z) / 2 :=
by rw [add_conj, mul_div_cancel_left ((re z):K) two_ne_zero']
theorem im_eq_conj_sub (z : K) : ↑(im z) = I * (conj z - z) / 2 :=
begin
rw [← neg_inj, ← of_real_neg, ← I_mul_re, re_eq_add_conj],
simp only [mul_add, sub_eq_add_neg, neg_div', neg_mul, conj_I,
mul_neg, neg_add_rev, neg_neg, ring_hom.map_mul]
end
/-! ### Absolute value -/
/-- The complex absolute value function, defined as the square root of the norm squared. -/
@[pp_nodot] noncomputable def abs (z : K) : ℝ := (norm_sq z).sqrt
local notation `abs'` := has_abs.abs
local notation `absK` := @abs K _
@[simp, norm_cast] lemma abs_of_real (r : ℝ) : absK r = abs' r :=
by simp only [abs, norm_sq, real.sqrt_mul_self_eq_abs, add_zero, of_real_im,
monoid_with_zero_hom.coe_mk, of_real_re, mul_zero]
lemma norm_eq_abs (z : K) : ∥z∥ = absK z :=
by simp only [abs, norm_sq_eq_def', norm_nonneg, real.sqrt_sq]
@[is_R_or_C_simps, norm_cast]
lemma norm_of_real (z : ℝ) : ∥(z : K)∥ = ∥z∥ :=
by { rw [is_R_or_C.norm_eq_abs, is_R_or_C.abs_of_real, real.norm_eq_abs] }
lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : absK r = r :=
(abs_of_real _).trans (abs_of_nonneg h)
lemma norm_of_nonneg {r : ℝ} (r_nn : 0 ≤ r) : ∥(r : K)∥ = r :=
by { rw norm_of_real, exact abs_eq_self.mpr r_nn, }
lemma abs_of_nat (n : ℕ) : absK n = n :=
by { rw [← of_real_nat_cast], exact abs_of_nonneg (nat.cast_nonneg n) }
lemma mul_self_abs (z : K) : abs z * abs z = norm_sq z :=
real.mul_self_sqrt (norm_sq_nonneg _)
@[simp, is_R_or_C_simps] lemma abs_zero : absK 0 = 0 := by simp only [abs, real.sqrt_zero, map_zero]
@[simp, is_R_or_C_simps] lemma abs_one : absK 1 = 1 := by simp only [abs, map_one, real.sqrt_one]
@[simp, is_R_or_C_simps] lemma abs_two : absK 2 = 2 :=
calc absK 2 = absK (2 : ℝ) : by rw [of_real_bit0, of_real_one]
... = (2 : ℝ) : abs_of_nonneg (by norm_num)
lemma abs_nonneg (z : K) : 0 ≤ absK z :=
real.sqrt_nonneg _
@[simp, is_R_or_C_simps] lemma abs_eq_zero {z : K} : absK z = 0 ↔ z = 0 :=
(real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero
lemma abs_ne_zero {z : K} : abs z ≠ 0 ↔ z ≠ 0 :=
not_congr abs_eq_zero
@[simp, is_R_or_C_simps] lemma abs_conj (z : K) : abs (conj z) = abs z :=
by simp only [abs, norm_sq_conj]
@[simp, is_R_or_C_simps] lemma abs_mul (z w : K) : abs (z * w) = abs z * abs w :=
by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl
lemma abs_re_le_abs (z : K) : abs' (re z) ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (re z)) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply re_sq_le_norm_sq
lemma abs_im_le_abs (z : K) : abs' (im z) ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (im z)) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply im_sq_le_norm_sq
lemma norm_re_le_norm (z : K) : ∥re z∥ ≤ ∥z∥ :=
by { rw [is_R_or_C.norm_eq_abs, real.norm_eq_abs], exact is_R_or_C.abs_re_le_abs _, }
lemma norm_im_le_norm (z : K) : ∥im z∥ ≤ ∥z∥ :=
by { rw [is_R_or_C.norm_eq_abs, real.norm_eq_abs], exact is_R_or_C.abs_im_le_abs _, }
lemma re_le_abs (z : K) : re z ≤ abs z :=
(abs_le.1 (abs_re_le_abs _)).2
lemma im_le_abs (z : K) : im z ≤ abs z :=
(abs_le.1 (abs_im_le_abs _)).2
lemma im_eq_zero_of_le {a : K} (h : abs a ≤ re a) : im a = 0 :=
begin
rw ← zero_eq_mul_self,
have : re a * re a = re a * re a + im a * im a,
{ convert is_R_or_C.mul_self_abs a;
linarith [re_le_abs a] },
linarith
end
lemma re_eq_self_of_le {a : K} (h : abs a ≤ re a) : (re a : K) = a :=
by { rw ← re_add_im a, simp only [im_eq_zero_of_le h, add_zero, zero_mul] with is_R_or_C_simps }
lemma abs_add (z w : K) : abs (z + w) ≤ abs z + abs w :=
(mul_self_le_mul_self_iff (abs_nonneg _)
(add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $
begin
rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs,
add_right_comm, norm_sq_add, add_le_add_iff_left,
mul_assoc, mul_le_mul_left (@zero_lt_two ℝ _ _)],
simpa [-mul_re] with is_R_or_C_simps using re_le_abs (z * conj w)
end
instance : is_absolute_value absK :=
{ abv_nonneg := abs_nonneg,
abv_eq_zero := λ _, abs_eq_zero,
abv_add := abs_add,
abv_mul := abs_mul }
open is_absolute_value
@[simp, is_R_or_C_simps] lemma abs_abs (z : K) : abs' (abs z) = abs z :=
_root_.abs_of_nonneg (abs_nonneg _)
@[simp, is_R_or_C_simps] lemma abs_pos {z : K} : 0 < abs z ↔ z ≠ 0 := abv_pos abs
@[simp, is_R_or_C_simps] lemma abs_neg : ∀ z : K, abs (-z) = abs z := abv_neg abs
lemma abs_sub : ∀ z w : K, abs (z - w) = abs (w - z) := abv_sub abs
lemma abs_sub_le : ∀ a b c : K, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs
@[simp, is_R_or_C_simps] theorem abs_inv : ∀ z : K, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs
@[simp, is_R_or_C_simps] theorem abs_div : ∀ z w : K, abs (z / w) = abs z / abs w := abv_div abs
lemma abs_abs_sub_le_abs_sub : ∀ z w : K, abs' (abs z - abs w) ≤ abs (z - w) :=
abs_abv_sub_le_abv_sub abs
lemma abs_re_div_abs_le_one (z : K) : abs' (re z / abs z) ≤ 1 :=
begin
by_cases hz : z = 0,
{ simp [hz, zero_le_one] },
{ simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] }
end
lemma abs_im_div_abs_le_one (z : K) : abs' (im z / abs z) ≤ 1 :=
begin
by_cases hz : z = 0,
{ simp [hz, zero_le_one] },
{ simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] }
end
@[simp, is_R_or_C_simps, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : K) = n :=
by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)]
lemma norm_sq_eq_abs (x : K) : norm_sq x = abs x ^ 2 :=
by rw [abs, sq, real.mul_self_sqrt (norm_sq_nonneg _)]
lemma re_eq_abs_of_mul_conj (x : K) : re (x * (conj x)) = abs (x * (conj x)) :=
by rw [mul_conj, of_real_re, abs_of_real, norm_sq_eq_abs, sq, _root_.abs_mul, abs_abs]
lemma abs_sq_re_add_conj (x : K) : (abs (x + conj x))^2 = (re (x + conj x))^2 :=
by simp only [sq, ←norm_sq_eq_abs, norm_sq, map_add, add_zero, monoid_with_zero_hom.coe_mk,
add_right_neg, mul_zero] with is_R_or_C_simps
lemma abs_sq_re_add_conj' (x : K) : (abs (conj x + x))^2 = (re (conj x + x))^2 :=
by simp only [sq, ←norm_sq_eq_abs, norm_sq, map_add, add_zero, monoid_with_zero_hom.coe_mk,
add_left_neg, mul_zero] with is_R_or_C_simps
lemma conj_mul_eq_norm_sq_left (x : K) : conj x * x = ((norm_sq x) : K) :=
begin
rw ext_iff,
refine ⟨by simp only [norm_sq, neg_mul, monoid_with_zero_hom.coe_mk,
sub_neg_eq_add, map_add, sub_zero, mul_zero] with is_R_or_C_simps, _⟩,
simp only [mul_comm, mul_neg, add_left_neg] with is_R_or_C_simps
end
/-! ### Cauchy sequences -/
theorem is_cau_seq_re (f : cau_seq K abs) : is_cau_seq abs' (λ n, re (f n)) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij)
theorem is_cau_seq_im (f : cau_seq K abs) : is_cau_seq abs' (λ n, im (f n)) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij)
/-- The real part of a K Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_re (f : cau_seq K abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_re f⟩
/-- The imaginary part of a K Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_im (f : cau_seq K abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_im f⟩
lemma is_cau_seq_abs {f : ℕ → K} (hf : is_cau_seq abs f) :
is_cau_seq abs' (abs ∘ f) :=
λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in
⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩
@[simp, is_R_or_C_simps, norm_cast, priority 900]
lemma of_real_prod {α : Type*} (s : finset α) (f : α → ℝ) :
((∏ i in s, f i : ℝ) : K) = ∏ i in s, (f i : K) :=
ring_hom.map_prod _ _ _
@[simp, is_R_or_C_simps, norm_cast, priority 900]
lemma of_real_sum {α : Type*} (s : finset α) (f : α → ℝ) :
((∑ i in s, f i : ℝ) : K) = ∑ i in s, (f i : K) :=
ring_hom.map_sum _ _ _
@[simp, is_R_or_C_simps, norm_cast] lemma of_real_finsupp_sum
{α M : Type*} [has_zero M] (f : α →₀ M) (g : α → M → ℝ) :
((f.sum (λ a b, g a b) : ℝ) : K) = f.sum (λ a b, ((g a b) : K)) :=
ring_hom.map_finsupp_sum _ f g
@[simp, is_R_or_C_simps, norm_cast] lemma of_real_finsupp_prod
{α M : Type*} [has_zero M] (f : α →₀ M) (g : α → M → ℝ) :
((f.prod (λ a b, g a b) : ℝ) : K) = f.prod (λ a b, ((g a b) : K)) :=
ring_hom.map_finsupp_prod _ f g
end is_R_or_C
namespace polynomial
open_locale polynomial
lemma of_real_eval (p : ℝ[X]) (x : ℝ) : (p.eval x : K) = aeval ↑x p :=
(@aeval_algebra_map_apply ℝ K _ _ _ x p).symm
end polynomial
namespace finite_dimensional
open_locale classical
open is_R_or_C
/-- This instance generates a type-class problem with a metavariable `?m` that should satisfy
`is_R_or_C ?m`. Since this can only be satisfied by `ℝ` or `ℂ`, this does not cause problems. -/
library_note "is_R_or_C instance"
/-- An `is_R_or_C` field is finite-dimensional over `ℝ`, since it is spanned by `{1, I}`. -/
@[nolint dangerous_instance] instance is_R_or_C_to_real : finite_dimensional ℝ K :=
⟨⟨{1, I},
begin
rw eq_top_iff,
intros a _,
rw [finset.coe_insert, finset.coe_singleton, submodule.mem_span_insert],
refine ⟨re a, (im a) • I, _, _⟩,
{ rw submodule.mem_span_singleton,
use im a },
simp [re_add_im a, algebra.smul_def, algebra_map_eq_of_real]
end⟩⟩
variables (K E) [normed_add_comm_group E] [normed_space K E]
/-- A finite dimensional vector space over an `is_R_or_C` is a proper metric space.
This is not an instance because it would cause a search for `finite_dimensional ?x E` before
`is_R_or_C ?x`. -/
lemma proper_is_R_or_C [finite_dimensional K E] : proper_space E :=
begin
letI : normed_space ℝ E := restrict_scalars.normed_space ℝ K E,
letI : finite_dimensional ℝ E := finite_dimensional.trans ℝ K E,
apply_instance
end
variable {E}
instance is_R_or_C.proper_space_submodule (S : submodule K E) [finite_dimensional K ↥S] :
proper_space S :=
proper_is_R_or_C K S
end finite_dimensional
section instances
noncomputable instance real.is_R_or_C : is_R_or_C ℝ :=
{ re := add_monoid_hom.id ℝ,
im := 0,
I := 0,
I_re_ax := by simp only [add_monoid_hom.map_zero],
I_mul_I_ax := or.intro_left _ rfl,
re_add_im_ax := λ z, by simp only [add_zero, mul_zero, algebra.id.map_eq_id, ring_hom.id_apply,
add_monoid_hom.id_apply],
of_real_re_ax := λ r, by simp only [add_monoid_hom.id_apply, algebra.id.map_eq_self],
of_real_im_ax := λ r, by simp only [add_monoid_hom.zero_apply],
mul_re_ax := λ z w,
by simp only [sub_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply],
mul_im_ax := λ z w, by simp only [add_zero, zero_mul, mul_zero, add_monoid_hom.zero_apply],
conj_re_ax := λ z, by simp only [star_ring_end_apply, star_id_of_comm],
conj_im_ax := λ z, by simp only [neg_zero, add_monoid_hom.zero_apply],
conj_I_ax := by simp only [ring_hom.map_zero, neg_zero],
norm_sq_eq_def_ax := λ z, by simp only [sq, real.norm_eq_abs, ←abs_mul, abs_mul_self z, add_zero,
mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply],
mul_im_I_ax := λ z, by simp only [mul_zero, add_monoid_hom.zero_apply],
inv_def_ax := λ z, by simp only [star_ring_end_apply, star, sq, real.norm_eq_abs,
abs_mul_abs_self, ←div_eq_mul_inv, algebra.id.map_eq_id, id.def, ring_hom.id_apply,
div_self_mul_self'],
div_I_ax := λ z, by simp only [div_zero, mul_zero, neg_zero],
.. real.densely_normed_field, .. real.metric_space }
end instances
namespace is_R_or_C
open_locale complex_conjugate
section cleanup_lemmas
local notation `reR` := @is_R_or_C.re ℝ _
local notation `imR` := @is_R_or_C.im ℝ _
local notation `IR` := @is_R_or_C.I ℝ _
local notation `absR` := @is_R_or_C.abs ℝ _
local notation `norm_sqR` := @is_R_or_C.norm_sq ℝ _
@[simp, is_R_or_C_simps] lemma re_to_real {x : ℝ} : reR x = x := rfl
@[simp, is_R_or_C_simps] lemma im_to_real {x : ℝ} : imR x = 0 := rfl
@[simp, is_R_or_C_simps] lemma conj_to_real {x : ℝ} : conj x = x := rfl
@[simp, is_R_or_C_simps] lemma I_to_real : IR = 0 := rfl
@[simp, is_R_or_C_simps] lemma norm_sq_to_real {x : ℝ} : norm_sq x = x*x :=
by simp [is_R_or_C.norm_sq]
@[simp, is_R_or_C_simps] lemma abs_to_real {x : ℝ} : absR x = has_abs.abs x :=
by simp [is_R_or_C.abs, abs, real.sqrt_mul_self_eq_abs]
@[simp] lemma coe_real_eq_id : @coe ℝ ℝ _ = id := rfl
end cleanup_lemmas
section linear_maps
/-- The real part in a `is_R_or_C` field, as a linear map. -/
def re_lm : K →ₗ[ℝ] ℝ :=
{ map_smul' := smul_re, .. re }
@[simp, is_R_or_C_simps] lemma re_lm_coe : (re_lm : K → ℝ) = re := rfl
/-- The real part in a `is_R_or_C` field, as a continuous linear map. -/
noncomputable def re_clm : K →L[ℝ] ℝ :=
linear_map.mk_continuous re_lm 1 $ by
{ simp only [norm_eq_abs, re_lm_coe, one_mul, abs_to_real], exact abs_re_le_abs, }
@[simp, is_R_or_C_simps] lemma re_clm_norm : ∥(re_clm : K →L[ℝ] ℝ)∥ = 1 :=
begin
apply le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _),
convert continuous_linear_map.ratio_le_op_norm _ (1 : K),
{ simp },
{ apply_instance }
end
@[simp, is_R_or_C_simps, norm_cast] lemma re_clm_coe : ((re_clm : K →L[ℝ] ℝ) :
K →ₗ[ℝ] ℝ) = re_lm := rfl
@[simp, is_R_or_C_simps] lemma re_clm_apply : ((re_clm : K →L[ℝ] ℝ) : K → ℝ) = re := rfl
@[continuity] lemma continuous_re : continuous (re : K → ℝ) := re_clm.continuous
/-- The imaginary part in a `is_R_or_C` field, as a linear map. -/
def im_lm : K →ₗ[ℝ] ℝ :=
{ map_smul' := smul_im, .. im }
@[simp, is_R_or_C_simps] lemma im_lm_coe : (im_lm : K → ℝ) = im := rfl
/-- The imaginary part in a `is_R_or_C` field, as a continuous linear map. -/
noncomputable def im_clm : K →L[ℝ] ℝ :=
linear_map.mk_continuous im_lm 1 $ by
{ simp only [norm_eq_abs, re_lm_coe, one_mul, abs_to_real], exact abs_im_le_abs, }
@[simp, is_R_or_C_simps, norm_cast] lemma im_clm_coe : ((im_clm : K →L[ℝ] ℝ) :
K →ₗ[ℝ] ℝ) = im_lm := rfl
@[simp, is_R_or_C_simps] lemma im_clm_apply : ((im_clm : K →L[ℝ] ℝ) : K → ℝ) = im := rfl
@[continuity] lemma continuous_im : continuous (im : K → ℝ) := im_clm.continuous
/-- Conjugate as an `ℝ`-algebra equivalence -/
def conj_ae : K ≃ₐ[ℝ] K :=
{ inv_fun := conj,
left_inv := conj_conj,
right_inv := conj_conj,
commutes' := conj_of_real,
.. conj }
@[simp, is_R_or_C_simps] lemma conj_ae_coe : (conj_ae : K → K) = conj := rfl
/-- Conjugate as a linear isometry -/
noncomputable def conj_lie : K ≃ₗᵢ[ℝ] K :=
⟨conj_ae.to_linear_equiv, λ z, by simp [norm_eq_abs] with is_R_or_C_simps⟩
@[simp, is_R_or_C_simps] lemma conj_lie_apply : (conj_lie : K → K) = conj := rfl
/-- Conjugate as a continuous linear equivalence -/
noncomputable def conj_cle : K ≃L[ℝ] K := @conj_lie K _
@[simp, is_R_or_C_simps] lemma conj_cle_coe :
(@conj_cle K _).to_linear_equiv = conj_ae.to_linear_equiv := rfl
@[simp, is_R_or_C_simps] lemma conj_cle_apply : (conj_cle : K → K) = conj := rfl
@[simp, is_R_or_C_simps] lemma conj_cle_norm : ∥(@conj_cle K _ : K →L[ℝ] K)∥ = 1 :=
(@conj_lie K _).to_linear_isometry.norm_to_continuous_linear_map
@[priority 100]
instance : has_continuous_star K := ⟨conj_lie.continuous⟩
@[continuity] lemma continuous_conj : continuous (conj : K → K) := continuous_star
/-- The `ℝ → K` coercion, as a linear map -/
noncomputable def of_real_am : ℝ →ₐ[ℝ] K := algebra.of_id ℝ K
@[simp, is_R_or_C_simps] lemma of_real_am_coe : (of_real_am : ℝ → K) = coe := rfl
/-- The ℝ → K coercion, as a linear isometry -/
noncomputable def of_real_li : ℝ →ₗᵢ[ℝ] K :=
{ to_linear_map := of_real_am.to_linear_map, norm_map' := by simp [norm_eq_abs] }
@[simp, is_R_or_C_simps] lemma of_real_li_apply : (of_real_li : ℝ → K) = coe := rfl
/-- The `ℝ → K` coercion, as a continuous linear map -/
noncomputable def of_real_clm : ℝ →L[ℝ] K := of_real_li.to_continuous_linear_map
@[simp, is_R_or_C_simps] lemma of_real_clm_coe :
((@of_real_clm K _) : ℝ →ₗ[ℝ] K) = of_real_am.to_linear_map := rfl
@[simp, is_R_or_C_simps] lemma of_real_clm_apply : (of_real_clm : ℝ → K) = coe := rfl
@[simp, is_R_or_C_simps] lemma of_real_clm_norm : ∥(of_real_clm : ℝ →L[ℝ] K)∥ = 1 :=
linear_isometry.norm_to_continuous_linear_map of_real_li
@[continuity] lemma continuous_of_real : continuous (coe : ℝ → K) := of_real_li.continuous
@[continuity] lemma continuous_abs : continuous (@is_R_or_C.abs K _) :=
by simp only [show @is_R_or_C.abs K _ = has_norm.norm, by { ext, exact (norm_eq_abs _).symm },
continuous_norm]
@[continuity] lemma continuous_norm_sq : continuous (@is_R_or_C.norm_sq K _) :=
begin
have : (@is_R_or_C.norm_sq K _ : K → ℝ) = λ x, (is_R_or_C.abs x) ^ 2,
{ ext,
exact norm_sq_eq_abs _ },
simp only [this, continuous_abs.pow 2],
end
end linear_maps
end is_R_or_C
|
4bb57fa330f2a5963e3fdb3517a2d415943a1fc8 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/order/bounded_lattice.lean | 4a4a2a87e5b0c7ee459a8c47d7bf1d4f9a1db2f7 | [
"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 | 40,188 | 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 order.lattice
import data.option.basic
import tactic.pi_instances
set_option old_structure_cmd true
universes u v
variables {α : Type u} {β : Type v}
/-- Typeclass for the `⊤` (`\top`) notation -/
class has_top (α : Type u) := (top : α)
/-- Typeclass for the `⊥` (`\bot`) notation -/
class has_bot (α : Type u) := (bot : α)
notation `⊤` := has_top.top
notation `⊥` := has_bot.bot
attribute [pattern] has_bot.bot has_top.top
section prio
set_option default_priority 100 -- see Note [default priority]
/-- An `order_top` is a partial order with a maximal element.
(We could state this on preorders, but then it wouldn't be unique
so distinguishing one would seem odd.) -/
class order_top (α : Type u) extends has_top α, partial_order α :=
(le_top : ∀ a : α, a ≤ ⊤)
end prio
section order_top
variables [order_top α] {a b : α}
@[simp] theorem le_top : a ≤ ⊤ :=
order_top.le_top a
theorem top_unique (h : ⊤ ≤ a) : a = ⊤ :=
le_antisymm le_top h
-- TODO: delete in favor of the next?
theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a :=
⟨assume eq, eq.symm ▸ le_refl ⊤, top_unique⟩
@[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ :=
⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩
@[simp] theorem not_top_lt : ¬ ⊤ < a :=
assume h, lt_irrefl a (lt_of_le_of_lt le_top h)
theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ :=
top_le_iff.1 $ h₂ ▸ h
lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ :=
begin
haveI := classical.dec_eq α,
haveI : decidable (⊤ ≤ a) := decidable_of_iff' _ top_le_iff,
by simp [-top_le_iff, lt_iff_le_not_le, not_iff_not.2 (@top_le_iff _ _ a)]
end
lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ :=
lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top
theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ :=
assume ha, hb $ top_unique $ ha ▸ hab
end order_top
lemma strict_mono.top_preimage_top' [linear_order α] [order_top β]
{f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) :
x ≤ a :=
H.top_preimage_top (λ p, by { rw h_top, exact le_top }) x
theorem order_top.ext_top {α} {A B : order_top α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊤ : α) = ⊤ :=
top_unique $ by rw ← H; apply le_top
theorem order_top.ext {α} {A B : order_top α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have tt := order_top.ext_top H,
casesI A, casesI B,
injection this; congr'
end
section prio
set_option default_priority 100 -- see Note [default priority]
/-- An `order_bot` is a partial order with a minimal element.
(We could state this on preorders, but then it wouldn't be unique
so distinguishing one would seem odd.) -/
class order_bot (α : Type u) extends has_bot α, partial_order α :=
(bot_le : ∀ a : α, ⊥ ≤ a)
end prio
section order_bot
variables [order_bot α] {a b : α}
@[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a
theorem bot_unique (h : a ≤ ⊥) : a = ⊥ :=
le_antisymm h bot_le
-- TODO: delete?
theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ :=
⟨assume eq, eq.symm ▸ le_refl ⊥, bot_unique⟩
@[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ :=
⟨bot_unique, assume h, h.symm ▸ le_refl ⊥⟩
@[simp] theorem not_lt_bot : ¬ a < ⊥ :=
assume h, lt_irrefl a (lt_of_lt_of_le h bot_le)
theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ :=
assume ha, hb $ bot_unique $ ha ▸ hab
theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ :=
le_bot_iff.1 $ h₂ ▸ h
lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ :=
begin
haveI := classical.dec_eq α,
haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff,
simp [-le_bot_iff, lt_iff_le_not_le, not_iff_not.2 (@le_bot_iff _ _ a)]
end
lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ :=
bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h
end order_bot
lemma strict_mono.bot_preimage_bot' [linear_order α] [order_bot β]
{f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) :
a ≤ x :=
H.bot_preimage_bot (λ p, by { rw h_bot, exact bot_le }) x
theorem order_bot.ext_bot {α} {A B : order_bot α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊥ : α) = ⊥ :=
bot_unique $ by rw ← H; apply bot_le
theorem order_bot.ext {α} {A B : order_bot α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have tt := order_bot.ext_bot H,
casesI A, casesI B,
injection this; congr'
end
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A `semilattice_sup_top` is a semilattice with top and join. -/
class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α
end prio
section semilattice_sup_top
variables [semilattice_sup_top α] {a : α}
@[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ :=
sup_of_le_left le_top
@[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ :=
sup_of_le_right le_top
end semilattice_sup_top
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/
class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α
end prio
section semilattice_sup_bot
variables [semilattice_sup_bot α] {a b : α}
@[simp] theorem bot_sup_eq : ⊥ ⊔ a = a :=
sup_of_le_right bot_le
@[simp] theorem sup_bot_eq : a ⊔ ⊥ = a :=
sup_of_le_left bot_le
@[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) :=
by rw [eq_bot_iff, sup_le_iff]; simp
end semilattice_sup_bot
instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ :=
{ bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice }
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A `semilattice_inf_top` is a semilattice with top and meet. -/
class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α
end prio
section semilattice_inf_top
variables [semilattice_inf_top α] {a b : α}
@[simp] theorem top_inf_eq : ⊤ ⊓ a = a :=
inf_of_le_right le_top
@[simp] theorem inf_top_eq : a ⊓ ⊤ = a :=
inf_of_le_left le_top
@[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) :=
by rw [eq_top_iff, le_inf_iff]; simp
end semilattice_inf_top
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/
class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α
end prio
section semilattice_inf_bot
variables [semilattice_inf_bot α] {a : α}
@[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ :=
inf_of_le_left bot_le
@[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ :=
inf_of_le_right bot_le
end semilattice_inf_bot
/- Bounded lattices -/
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A bounded lattice is a lattice with a top and bottom element,
denoted `⊤` and `⊥` respectively. This allows for the interpretation
of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/
class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α
end prio
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α :=
{ le_top := assume x, @le_top α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α :=
{ bot_le := assume x, @bot_le α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α :=
{ le_top := assume x, @le_top α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α :=
{ bot_le := assume x, @bot_le α _ x, ..bl }
theorem bounded_lattice.ext {α} {A B : bounded_lattice α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have H1 : @bounded_lattice.to_lattice α A =
@bounded_lattice.to_lattice α B := lattice.ext H,
have H2 := order_bot.ext H,
have H3 : @bounded_lattice.to_order_top α A =
@bounded_lattice.to_order_top α B := order_top.ext H,
have tt := order_bot.ext_bot H,
casesI A, casesI B,
injection H1; injection H2; injection H3; congr'
end
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A bounded distributive lattice is exactly what it sounds like. -/
class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α
end prio
lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α}
(h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c :=
⟨assume : a ⊓ b = ⊥,
calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁]
... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left]
... ≤ c : by simp [this, inf_le_right],
assume : a ≤ c,
bot_unique $
calc a ⊓ b ≤ b ⊓ c : by { rw [inf_comm], exact inf_le_inf_left _ this }
... = ⊥ : h₂⟩
/- Prop instance -/
instance bounded_distrib_lattice_Prop : bounded_distrib_lattice Prop :=
{ le := λa b, a → b,
le_refl := assume _, id,
le_trans := assume a b c f g, g ∘ f,
le_antisymm := assume a b Hab Hba, propext ⟨Hab, Hba⟩,
sup := or,
le_sup_left := @or.inl,
le_sup_right := @or.inr,
sup_le := assume a b c, or.rec,
inf := and,
inf_le_left := @and.left,
inf_le_right := @and.right,
le_inf := assume a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha),
le_sup_inf := assume a b c H, or_iff_not_imp_left.2 $
λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩,
top := true,
le_top := assume a Ha, true.intro,
bot := false,
bot_le := @false.elim }
section logic
variable [preorder α]
theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λx, p x ∧ q x) :=
assume a b h, and.imp (m_p h) (m_q h)
-- Note: by finish [monotone] doesn't work
theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λx, p x ∨ q x) :=
assume a b h, or.imp (m_p h) (m_q h)
end logic
instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, order_bot $ β a] : order_bot (Π a, β a) :=
{ bot := λ _, ⊥,
bot_le := λ x a, bot_le,
.. pi.partial_order }
/- Function lattices -/
instance pi.has_sup {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] : has_sup (Π i, α i) :=
⟨λ f g i, f i ⊔ g i⟩
@[simp] lemma sup_apply {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] (f g : Π i, α i) (i : ι) :
(f ⊔ g) i = f i ⊔ g i :=
rfl
instance pi.has_inf {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] : has_inf (Π i, α i) :=
⟨λ f g i, f i ⊓ g i⟩
@[simp] lemma inf_apply {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] (f g : Π i, α i) (i : ι) :
(f ⊓ g) i = f i ⊓ g i :=
rfl
instance pi.has_bot {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] : has_bot (Π i, α i) :=
⟨λ i, ⊥⟩
@[simp] lemma bot_apply {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] (i : ι) :
(⊥ : Π i, α i) i = ⊥ :=
rfl
instance pi.has_top {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] : has_top (Π i, α i) :=
⟨λ i, ⊤⟩
@[simp] lemma top_apply {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] (i : ι) :
(⊤ : Π i, α i) i = ⊤ :=
rfl
instance pi.semilattice_sup {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup (α i)] :
semilattice_sup (Π i, α i) :=
by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_inf {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf (α i)] :
semilattice_inf (Π i, α i) :=
by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_inf_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_bot (α i)] :
semilattice_inf_bot (Π i, α i) :=
by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_inf_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_top (α i)] :
semilattice_inf_top (Π i, α i) :=
by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_sup_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_bot (α i)] :
semilattice_sup_bot (Π i, α i) :=
by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_sup_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_top (α i)] :
semilattice_sup_top (Π i, α i) :=
by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.lattice {ι : Type*} {α : ι → Type*} [Π i, lattice (α i)] : lattice (Π i, α i) :=
{ .. pi.semilattice_sup, .. pi.semilattice_inf }
instance pi.bounded_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_lattice (α i)] :
bounded_lattice (Π i, α i) :=
{ .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot }
/-- Attach `⊥` to a type. -/
def with_bot (α : Type*) := option α
namespace with_bot
meta instance {α} [has_to_format α] : has_to_format (with_bot α) :=
{ to_format := λ x,
match x with
| none := "⊥"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_bot α) := ⟨some⟩
instance has_bot : has_bot (with_bot α) := ⟨none⟩
instance : inhabited (with_bot α) := ⟨⊥⟩
lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl
lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_bot α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
lemma bot_lt_some [has_lt α] (a : α) : (⊥ : with_bot α) < some a :=
⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩
lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a
instance [preorder α] : preorder (with_bot α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b,
lt := (<),
lt_iff_le_not_le := by intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<)];
split; refl,
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha,
let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in
⟨c, hc, le_trans ab bc⟩ }
instance partial_order [partial_order α] : partial_order (with_bot α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₁ with a,
{ cases o₂ with b, {refl},
rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩,
rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_bot.preorder }
instance order_bot [partial_order α] : order_bot (with_bot α) :=
{ bot_le := λ a a' h, option.no_confusion h,
..with_bot.partial_order, ..with_bot.has_bot }
@[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} :
(a : with_bot α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩
@[simp] theorem some_le_some [partial_order α] {a b : α} :
@has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe
theorem coe_le [partial_order α] {a b : α} :
∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b)
| _ rfl := coe_le_coe
@[norm_cast]
lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some
lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b
| (some a) b := le_refl a
| none b := λ _ h, option.no_confusion h
instance linear_order [linear_order α] : linear_order (with_bot α) :=
{ le_total := λ o₁ o₂, begin
cases o₁ with a, {exact or.inl bot_le},
cases o₂ with b, {exact or.inr bot_le},
simp [le_total]
end,
..with_bot.partial_order }
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<)
| none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩
| (some x) (some y) :=
if h : x < y
then is_true $ by simp *
else is_false $ by simp *
| x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩
instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_bot α) :=
{ decidable_le := λ a b, begin
cases a with a,
{ exact is_true bot_le },
cases b with b,
{ exact is_false (mt (le_antisymm bot_le) (by simp)) },
{ exact decidable_of_iff _ some_le_some }
end,
..with_bot.linear_order }
instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) :=
{ sup := option.lift_or_get (⊔),
le_sup_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
le_sup_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₁ with b; cases o₂ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, sup_le h₁' h₂⟩ }
end,
..with_bot.order_bot }
instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) :=
{ inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)),
inf_le_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_left⟩
end,
inf_le_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_right⟩
end,
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, le_inf ab ac⟩
end,
..with_bot.order_bot }
instance lattice [lattice α] : lattice (with_bot α) :=
{ ..with_bot.semilattice_sup, ..with_bot.semilattice_inf }
theorem lattice_eq_DLO [decidable_linear_order α] :
lattice_of_decidable_linear_order = @with_bot.lattice α _ :=
lattice.ext $ λ x y, iff.rfl
theorem sup_eq_max [decidable_linear_order α] (x y : with_bot α) : x ⊔ y = max x y :=
by rw [← sup_eq_max, lattice_eq_DLO]
theorem inf_eq_min [decidable_linear_order α] (x y : with_bot α) : x ⊓ y = min x y :=
by rw [← inf_eq_min, lattice_eq_DLO]
instance order_top [order_top α] : order_top (with_bot α) :=
{ top := some ⊤,
le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩,
..with_bot.partial_order }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) :=
{ ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot }
lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_bot α → with_bot α → Prop) :=
have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ :=
acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim),
⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot)
(λ b, well_founded.induction h b
(show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) b,
from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot)
(λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] :
densely_ordered (with_bot α) :=
⟨ assume a b,
match a, b with
| a, none := assume h : a < ⊥, (not_lt_bot h).elim
| none, some b := assume h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩
| some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := dense (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
end with_bot
--TODO(Mario): Construct using order dual on with_bot
def with_top (α : Type*) := option α
namespace with_top
meta instance {α} [has_to_format α] : has_to_format (with_top α) :=
{ to_format := λ x,
match x with
| none := "⊤"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_top α) := ⟨some⟩
instance has_top : has_top (with_top α) := ⟨none⟩
instance : inhabited (with_top α) := ⟨⊤⟩
lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl
lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
@[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) .
@[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ .
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_top α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a }
@[priority 10]
instance has_le [has_le α] : has_le (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
@[simp] theorem some_le_some [has_le α] {a b : α} :
@has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b :=
by simp [(≤)]
@[simp] theorem none_le [has_le α] {a : with_top α} :
@has_le.le (with_top α) _ a none :=
by simp [(≤)]
@[simp] theorem none_lt_some [has_lt α] {a : α} :
@has_lt.lt (with_top α) _ (some a) none :=
by simp [(<)]; existsi a; refl
instance [preorder α] : preorder (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a,
lt := (<),
lt_iff_le_not_le := by { intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<),(≤)] },
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc,
let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in
⟨a, ha, le_trans ab bc⟩,
}
instance partial_order [partial_order α] : partial_order (with_top α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₂ with b,
{ cases o₁ with a, {refl},
rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩,
rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_top.preorder }
instance order_top [partial_order α] : order_top (with_top α) :=
{ le_top := λ a a' h, option.no_confusion h,
..with_top.partial_order, .. with_top.has_top }
@[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} :
(a : with_top α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩
theorem le_coe [partial_order α] {a b : α} :
∀ {o : option α}, a ∈ o →
(@has_le.le (with_top α) _ o b ↔ a ≤ b)
| _ rfl := coe_le_coe
theorem le_coe_iff [partial_order α] (b : α) : ∀(x : with_top α), x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b)
| (some a) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem coe_le_iff [partial_order α] (a : α) : ∀(x : with_top α), ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b)
| (some b) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem lt_iff_exists_coe [partial_order α] : ∀(a b : with_top α), a < b ↔ (∃p:α, a = p ∧ ↑p < b)
| (some a) b := by simp [some_eq_coe, coe_eq_coe]
| none b := by simp [none_eq_top]
@[norm_cast]
lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some
lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ :=
lt_of_le_of_ne le_top (λ h, option.no_confusion h)
lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a :=
assume h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim
instance linear_order [linear_order α] : linear_order (with_top α) :=
{ le_total := λ o₁ o₂, begin
cases o₁ with a, {exact or.inr le_top},
cases o₂ with b, {exact or.inl le_top},
simp [le_total]
end,
..with_top.partial_order }
instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_top α) :=
{ decidable_le := λ a b, begin
cases b with b,
{ exact is_true le_top },
cases a with a,
{ exact is_false (mt (le_antisymm le_top) (by simp)) },
{ exact decidable_of_iff _ some_le_some }
end,
..with_top.linear_order }
instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) :=
{ inf := option.lift_or_get (⊓),
inf_le_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
inf_le_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₂ with b; cases o₃ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, le_inf h₁' h₂⟩ }
end,
..with_top.order_top }
lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl
instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) :=
{ sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)),
le_sup_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_left⟩
end,
le_sup_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_right⟩
end,
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, sup_le ab ac⟩
end,
..with_top.order_top }
lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl
instance lattice [lattice α] : lattice (with_top α) :=
{ ..with_top.semilattice_sup, ..with_top.semilattice_inf }
theorem lattice_eq_DLO [decidable_linear_order α] :
lattice_of_decidable_linear_order = @with_top.lattice α _ :=
lattice.ext $ λ x y, iff.rfl
theorem sup_eq_max [decidable_linear_order α] (x y : with_top α) : x ⊔ y = max x y :=
by rw [← sup_eq_max, lattice_eq_DLO]
theorem inf_eq_min [decidable_linear_order α] (x y : with_top α) : x ⊓ y = min x y :=
by rw [← inf_eq_min, lattice_eq_DLO]
instance order_bot [order_bot α] : order_bot (with_top α) :=
{ bot := some ⊥,
bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩,
..with_top.partial_order }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) :=
{ ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot }
lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_top α → with_top α → Prop) :=
have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) :=
λ a, acc.intro _ (well_founded.induction h a
(show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) →
∀ y : with_top α, y < some b → acc (<) y,
from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim)
(λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))),
⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim)
(λ _ _, acc_some _))) acc_some⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] :
densely_ordered (with_top α) :=
⟨ assume a b,
match a, b with
| none, a := assume h : ⊤ < a, (not_top_lt h).elim
| some a, none := assume h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩
| some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := dense (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α]
{a b : with_top α} :
(a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) :=
⟨λ h, let ⟨y, hy⟩ := dense h, ⟨x, hx⟩ := (lt_iff_exists_coe _ _).1 hy.2 in ⟨x, hx.1 ▸ hy⟩,
λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩
end with_top
namespace subtype
/-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. -/
protected def semilattice_sup [semilattice_sup α] {P : α → Prop}
(Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} :=
{ sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩,
le_sup_left := λ x y, @le_sup_left _ _ (x : α) y,
le_sup_right := λ x y, @le_sup_right _ _ (x : α) y,
sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2,
..subtype.partial_order P }
/-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. -/
protected def semilattice_inf [semilattice_inf α] {P : α → Prop}
(Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} :=
{ inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩,
inf_le_left := λ x y, @inf_le_left _ _ (x : α) y,
inf_le_right := λ x y, @inf_le_right _ _ (x : α) y,
le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2,
..subtype.partial_order P }
/-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. -/
protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop}
(Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ x, @bot_le α _ x,
..subtype.semilattice_sup Psup }
/-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. -/
protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop}
(Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ x, @bot_le α _ x,
..subtype.semilattice_inf Pinf }
/-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property. -/
protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop}
(Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} :=
{ top := ⟨⊤, Ptop⟩,
le_top := λ x, @le_top α _ x,
..subtype.semilattice_inf Pinf }
/-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. -/
protected def lattice [lattice α] {P : α → Prop}
(Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) :
lattice {x : α // P x} :=
{ ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup }
end subtype
namespace order_dual
variable (α)
instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩
instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩
instance [order_bot α] : order_top (order_dual α) :=
{ le_top := @bot_le α _,
.. order_dual.partial_order α, .. order_dual.has_top α }
instance [order_top α] : order_bot (order_dual α) :=
{ bot_le := @le_top α _,
.. order_dual.partial_order α, .. order_dual.has_bot α }
instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_top α }
instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_bot α }
instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_top α }
instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_bot α }
instance [bounded_lattice α] : bounded_lattice (order_dual α) :=
{ .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α }
instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) :=
{ .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α }
end order_dual
namespace prod
variables (α β)
instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩
instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩
instance [order_top α] [order_top β] : order_top (α × β) :=
{ le_top := assume a, ⟨le_top, le_top⟩,
.. prod.partial_order α β, .. prod.has_top α β }
instance [order_bot α] [order_bot β] : order_bot (α × β) :=
{ bot_le := assume a, ⟨bot_le, bot_le⟩,
.. prod.partial_order α β, .. prod.has_bot α β }
instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_top α β }
instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_top α β }
instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_bot α β }
instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_bot α β }
instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) :=
{ .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β }
instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] :
bounded_distrib_lattice (α × β) :=
{ .. prod.bounded_lattice α β, .. prod.distrib_lattice α β }
end prod
section disjoint
section semilattice_inf_bot
variable [semilattice_inf_bot α]
/-- Two elements of a lattice are disjoint if their inf is the bottom element.
(This generalizes disjoint sets, viewed as members of the subset lattice.) -/
def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥
theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ :=
eq_bot_iff.2 h
theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ :=
eq_bot_iff.symm
theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a :=
by rw [disjoint, disjoint, inf_comm]
@[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a :=
disjoint.comm.1
@[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := disjoint_iff.2 bot_inf_eq
@[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := disjoint_iff.2 inf_bot_eq
theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) :
disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂)
theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c :=
disjoint.mono h (le_refl _)
theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b :=
disjoint.mono (le_refl _) h
@[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ :=
by simp [disjoint]
lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b :=
by { intro h, rw [←h, disjoint_self] at hab, exact ha hab }
end semilattice_inf_bot
section bounded_distrib_lattice
variables [bounded_distrib_lattice α] {a b c : α}
@[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c :=
by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff]
@[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c :=
by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff]
lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c :=
disjoint_sup_left.2 ⟨ha, hb⟩
lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) :=
disjoint_sup_right.2 ⟨hb, hc⟩
end bounded_distrib_lattice
end disjoint
/-!
### `is_compl` predicate
-/
/-- Two elements `x` and `y` are complements of each other if
`x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/
structure is_compl [bounded_lattice α] (x y : α) : Prop :=
(inf_le_bot : x ⊓ y ≤ ⊥)
(top_le_sup : ⊤ ≤ x ⊔ y)
namespace is_compl
section bounded_lattice
variables [bounded_lattice α] {x y z : α}
protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1
@[symm] protected lemma symm (h : is_compl x y) : is_compl y x :=
⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩
lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y :=
⟨le_of_eq h₁, le_of_eq h₂.symm⟩
lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot
lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup
lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩
end bounded_lattice
variables [bounded_distrib_lattice α] {x y z : α}
lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y :=
⟨λ hz, h.disjoint.mono_left hz,
λ hz, le_of_inf_le_sup_le (le_trans hz bot_le) (le_trans le_top h.top_le_sup)⟩
lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x :=
h.symm.le_left_iff
lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y :=
h.to_order_dual.le_left_iff
lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x :=
h.symm.left_le_iff
lemma antimono {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') :
y' ≤ y :=
h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _)
lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) :
y = z :=
le_antisymm (hxz.antimono hxy $ le_refl x) (hxy.antimono hxz $ le_refl x)
lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) :
x = y :=
hxz.symm.right_unique hyz.symm
lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊔ x') (y ⊓ y') :=
of_eq
(by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm,
h'.inf_eq_bot, inf_bot_eq])
(by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq,
sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq])
lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊓ x') (y ⊔ y') :=
(h.symm.sup_inf h'.symm).symm
lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z :=
inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot
lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y :=
h.symm.inf_left_eq_bot_iff
lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z :=
disjoint_iff.trans h.inf_left_eq_bot_iff
lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y :=
h.symm.disjoint_left_iff
end is_compl
lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ :=
is_compl.of_eq bot_inf_eq sup_top_eq
lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ :=
is_compl.of_eq inf_bot_eq top_sup_eq
|
a99ae7d9cc14e709223f4d6636a814991575dae3 | 367134ba5a65885e863bdc4507601606690974c1 | /src/category_theory/adjunction/opposites.lean | 0955c01ffafe3dddd3651365c321c08d781fef45 | [
"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 | 4,626 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Thomas Read
-/
import category_theory.adjunction.basic
import category_theory.yoneda
import category_theory.opposites
/-!
# Opposite adjunctions
This file contains constructions to relate adjunctions of functors to adjunctions of their
opposites.
These constructions are used to show uniqueness of adjoints (up to natural isomorphism).
## Tags
adjunction, opposite, uniqueness
-/
open category_theory
universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
namespace adjunction
/-- If `G.op` is adjoint to `F.op` then `F` is adjoint to `G`. -/
def adjoint_of_op_adjoint_op (F : C ⥤ D) (G : D ⥤ C) (h : G.op ⊣ F.op) : F ⊣ G :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Y,
((h.hom_equiv (opposite.op Y) (opposite.op X)).trans (op_equiv _ _)).symm.trans (op_equiv _ _) }
/-- If `G` is adjoint to `F.op` then `F` is adjoint to `G.unop`. -/
def adjoint_unop_of_adjoint_op (F : C ⥤ D) (G : Dᵒᵖ ⥤ Cᵒᵖ) (h : G ⊣ F.op) : F ⊣ G.unop :=
adjoint_of_op_adjoint_op F G.unop (h.of_nat_iso_left G.op_unop_iso.symm)
/-- If `G.op` is adjoint to `F` then `F.unop` is adjoint to `G`. -/
def unop_adjoint_of_op_adjoint (F : Cᵒᵖ ⥤ Dᵒᵖ) (G : D ⥤ C) (h : G.op ⊣ F) : F.unop ⊣ G :=
adjoint_of_op_adjoint_op _ _ (h.of_nat_iso_right F.op_unop_iso.symm)
/-- If `G` is adjoint to `F` then `F.unop` is adjoint to `G.unop`. -/
def unop_adjoint_unop_of_adjoint (F : Cᵒᵖ ⥤ Dᵒᵖ) (G : Dᵒᵖ ⥤ Cᵒᵖ) (h : G ⊣ F) : F.unop ⊣ G.unop :=
adjoint_unop_of_adjoint_op F.unop G (h.of_nat_iso_right F.op_unop_iso.symm)
/-- If `G` is adjoint to `F` then `F.op` is adjoint to `G.op`. -/
def op_adjoint_op_of_adjoint (F : C ⥤ D) (G : D ⥤ C) (h : G ⊣ F) : F.op ⊣ G.op :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X Y,
(op_equiv _ Y).trans ((h.hom_equiv _ _).symm.trans (op_equiv X (opposite.op _)).symm) }
/-- If `G` is adjoint to `F.unop` then `F` is adjoint to `G.op`. -/
def adjoint_op_of_adjoint_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) (G : D ⥤ C) (h : G ⊣ F.unop) : F ⊣ G.op :=
(op_adjoint_op_of_adjoint F.unop _ h).of_nat_iso_left F.op_unop_iso
/-- If `G.unop` is adjoint to `F` then `F.op` is adjoint to `G`. -/
def op_adjoint_of_unop_adjoint (F : C ⥤ D) (G : Dᵒᵖ ⥤ Cᵒᵖ) (h : G.unop ⊣ F) : F.op ⊣ G :=
(op_adjoint_op_of_adjoint _ G.unop h).of_nat_iso_right G.op_unop_iso
/-- If `G.unop` is adjoint to `F.unop` then `F` is adjoint to `G`. -/
def adjoint_of_unop_adjoint_unop (F : Cᵒᵖ ⥤ Dᵒᵖ) (G : Dᵒᵖ ⥤ Cᵒᵖ) (h : G.unop ⊣ F.unop) : F ⊣ G :=
(adjoint_op_of_adjoint_unop _ _ h).of_nat_iso_right G.op_unop_iso
/--
If `F` and `F'` are both adjoint to `G`, there is a natural isomorphism
`F.op ⋙ coyoneda ≅ F'.op ⋙ coyoneda`.
We use this in combination with `fully_faithful_cancel_right` to show left adjoints are unique.
-/
def left_adjoints_coyoneda_equiv {F F' : C ⥤ D} {G : D ⥤ C}
(adj1 : F ⊣ G) (adj2 : F' ⊣ G):
F.op ⋙ coyoneda ≅ F'.op ⋙ coyoneda :=
nat_iso.of_components
(λ X, nat_iso.of_components
(λ Y, ((adj1.hom_equiv X.unop Y).trans (adj2.hom_equiv X.unop Y).symm).to_iso)
(by tidy))
(by tidy)
/-- If `F` and `F'` are both left adjoint to `G`, then they are naturally isomorphic. -/
def left_adjoint_uniq {F F' : C ⥤ D} {G : D ⥤ C}
(adj1 : F ⊣ G) (adj2 : F' ⊣ G) : F ≅ F' :=
nat_iso.remove_op (fully_faithful_cancel_right _ (left_adjoints_coyoneda_equiv adj2 adj1))
/-- If `G` and `G'` are both right adjoint to `F`, then they are naturally isomorphic. -/
def right_adjoint_uniq {F : C ⥤ D} {G G' : D ⥤ C}
(adj1 : F ⊣ G) (adj2 : F ⊣ G') : G ≅ G' :=
nat_iso.remove_op
(left_adjoint_uniq (op_adjoint_op_of_adjoint _ F adj2) (op_adjoint_op_of_adjoint _ _ adj1))
/--
Given two adjunctions, if the left adjoints are naturally isomorphic, then so are the right
adjoints.
-/
def nat_iso_of_left_adjoint_nat_iso {F F' : C ⥤ D} {G G' : D ⥤ C}
(adj1 : F ⊣ G) (adj2 : F' ⊣ G') (l : F ≅ F') :
G ≅ G' :=
right_adjoint_uniq adj1 (adj2.of_nat_iso_left l.symm)
/--
Given two adjunctions, if the right adjoints are naturally isomorphic, then so are the left
adjoints.
-/
def nat_iso_of_right_adjoint_nat_iso {F F' : C ⥤ D} {G G' : D ⥤ C}
(adj1 : F ⊣ G) (adj2 : F' ⊣ G') (r : G ≅ G') :
F ≅ F' :=
left_adjoint_uniq adj1 (adj2.of_nat_iso_right r.symm)
end adjunction
|
6b86ac4be4b61ce2b6917ef301a6a17cf89d7b4b | ec62863c729b7eedee77b86d974f2c529fa79d25 | /15/a.lean | 37c21438d1d279a917b0f4534f8e01da105ad93f | [] | no_license | rwbarton/advent-of-lean-4 | 2ac9b17ba708f66051e3d8cd694b0249bc433b65 | 417c7e2718253ba7148c0279fcb251b6fc291477 | refs/heads/main | 1,675,917,092,057 | 1,609,864,581,000 | 1,609,864,581,000 | 317,700,289 | 24 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 529 | lean | def List.head [Inhabited α] : List α → α
| [] => panic! "empty"
| (x :: xs) => x
def List.findAux [BEq α] (n : Int) (y : α) : List α -> Int
| [] => 0
| (x :: xs) => if x == y then n else xs.findAux (n+1) y
def solve (inlst : List Int) : Int := do
let mut lst := inlst.reverse
for _ in [inlst.length:2020] do
lst := ((lst.drop 1).findAux 1 lst.head :: lst)
lst.head
def main : IO Unit := do
let lines ← IO.FS.lines "a.in"
let vals := ((lines.get! 0).splitOn ",").map String.toInt!
IO.print s!"{solve vals}"
|
1e321d9a001cae6b4f1e9ed3fbb2b9e6155fa0f0 | deb45868eed82bf318edfa1465dfc25f93e4fe7d | /M1F/2017-18/Example_Sheet_01/Question_01/solution.lean | 7c6d082660a0faee6878ce82346e8ee9863e7de8 | [] | no_license | elma16/xena | 16421db3416e73d73860a72cf24f32ae56ddb4db | 5a5534aa40e8ec3e05fc85ef374dbf5d27a4a718 | refs/heads/master | 1,625,400,269,823 | 1,506,370,990,000 | 1,506,370,990,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,356 | lean | /-
M1F Sheet 1 Question 1 part (a) , solution.
Author : Kevin Buzzard
Preliminary version
TODO (KMB) : This proof is valid for integers only -- need
: to work with reals.
: figure out how to use x^2 instead of x*x
: figure out how to make 3 mean 3:Z automatically
: remove some of those stupid brackets!
: This is actually the 2016-17 example sheet question; update later.
-/
-- I (KMB) have documented the proof below.
-- The actual M1F question says: "Is it true that if x is any real number,
-- then x^2-3x+2=0 implies x=1?". I am not very good at talking to Xena
-- about real numbers yet, so let's stick to integers.
-- The answer to the question is that it is not true, and x=2 is
-- a counterexample. Let's tell Xena this and see if she believes us.
-- ignore this bit
open int
-- This is not quite the question -- I am letting x be an integer
-- instead of a real number, for technical reasons which I will fix later.
-- This theorem says "it is not true that for all integers x,
-- x^2-3x+2=0 implies x=1"
-- (that weird sign at the beginning is a "not" sign).
-- The proof goes "x=2 is a counterexample."
theorem m1f_sheet01_q01 : ¬ (∀ x : ℤ,((x*x-(3:ℤ)*x+(2:ℤ)=(0:ℤ)) → (x=(1:ℤ)))) :=
begin
-- We prove this by contradiction.
-- let's let H be our false hypothesis.
intro H,
-- H is now the hypothesis ∀ x in ℤ, (x*x-3*x+2=0 → x=1)
-- Now let's set x=2 in H and call the resulting hypothesis H2.
have H2 : (2:ℤ)*2-3*2+2=0 → (2:ℤ)=1,
exact (H 2), -- this is the proof of H2 from H.
-- We now have hypothesis H2, which says 2^2-3*2+2=0 implies 2=1.
-- Now let's check that 2^2-3*2+2=0. Let's call this hypothesis J.
have J : (2:ℤ) * 2 - 3 * 2 + 2 = 0,
trivial,
-- now let's deduce that 2=1 from H2 and J.
have K : (2:ℤ) = 1,
exact (H2 J),
-- This is our contradiction!
-- There is probably one clever thing we can tell Xena right now
-- and she will realise that we have our contradiction straight from 2=1,
-- but I am still really bad at talking to Xena fluently
-- so I have to bumble along for a few more uninteresting lines...
have L : 2 = 1,
exact (iff.mp (int.coe_nat_eq_coe_nat_iff 2 1) K),
have M : 2 ≠ 1,
cc,
-- ...before we get there. TODO: make the ending more fluent.
contradiction
end
-- And there's the proof!
|
ddfad28851b657390512ed310e7d9f9aa5281df3 | ba4b63fe3410ccb8e043a57aa024ac63bf06961c | /src/homeos.lean | 80ab275ab430103ee5b0f0f4ea294c87dfed8f48 | [] | no_license | digama0/lean-scratchpad | f30cd665037c226b63ef9933c8fa83e8770f7909 | fe7d6261d60769328e091a37dff7d456c57366b7 | refs/heads/master | 1,583,695,343,314 | 1,522,993,425,000 | 1,522,993,425,000 | 128,350,243 | 0 | 0 | null | 1,522,993,456,000 | 1,522,993,456,000 | null | UTF-8 | Lean | false | false | 3,083 | lean | import analysis.topology.topological_space
import analysis.topology.continuity
open set function
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
[topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
structure homeo (α β) [topological_space α] [topological_space β] extends equiv α β :=
(fun_con : continuous to_fun)
(inv_con : continuous inv_fun)
instance : has_coe_to_fun (homeo α β) := ⟨_, λ f, f.to_fun⟩
theorem homeo.bijective (f : homeo α β) : bijective f := f.to_equiv.bijective
def homeo.comp : homeo α β → homeo β γ → homeo α γ
| ⟨e1@⟨f₁, g₁, _, _⟩, f₁_con, g₁_con⟩ ⟨e2@⟨f₂, g₂, _, _⟩, f₂_con, g₂_con⟩ :=
⟨e1.trans e2,
continuous.comp f₁_con f₂_con,
continuous.comp g₂_con g₁_con⟩
def homeo.symm (h : homeo α β) : homeo β α :=
{ fun_con := h.inv_con, inv_con := h.fun_con, .. h.to_equiv.symm }
--instance : has_inv (homeo α α) := ⟨λ f, f.symm⟩
local notation f`⁻¹` := f.symm
local notation f ∘ g := homeo.comp g f
theorem homeo.left_inverse (f : homeo α β) : left_inverse f⁻¹ f := f.left_inv
theorem homeo.right_inverse (f : homeo α β) : function.right_inverse f⁻¹ f := f.right_inv
@[simp] lemma homeo.comp_val (f : homeo α β) (g : homeo β γ) (x) : homeo.comp f g x = g (f x) :=
by cases f with e₁; cases g with e₂; cases e₁; cases e₂; refl
def homeo.id (α) [topological_space α] : homeo α α :=
{ fun_con := continuous_id, inv_con := continuous_id, .. equiv.refl α }
@[simp]
lemma home.id_apply : (homeo.id α : α → α) = id := rfl
@[simp] lemma homeo.id_val (x : α) : (homeo.id α) x = x := rfl
theorem homeo.ext {f g : homeo α β} (H : ∀ x, f x = g x) : f = g :=
by cases f; cases g; congr;
exact equiv.eq_of_to_fun_eq (funext H)
lemma id_circ_f (f : homeo α β) : (homeo.id β) ∘ f = f :=
homeo.ext $ by simp
lemma f_circ_id (f : homeo α β) : f ∘ (homeo.id α) = f :=
homeo.ext $ by simp
lemma homeo_comp_assoc (f: homeo α β) (g : homeo β γ) (h : homeo γ δ) : (h ∘ g) ∘ f = h ∘ (g ∘ f) :=
homeo.ext $ by simp
lemma homeo.mul_left_inv (f: homeo α β) : f ∘ f⁻¹ = homeo.id β :=
homeo.ext
begin
suffices : ∀ (x : β), f (f⁻¹ x) = x,
simp [this],
intro,
cases f,
rw homeo.symm,
apply equiv.apply_inverse_apply,
end
lemma homeo.symm_comp (h : homeo α β) : h⁻¹ ∘ h = homeo.id α :=
begin
apply homeo.ext,
simp,
intros,
cases h with f f_con f_inv_con,
rw homeo.symm,
apply equiv.apply_inverse_apply,
end
universe u
instance aut (α : Type u) [topological_space α] : group (homeo α α) :=
{ mul := (∘),
mul_assoc := λ a b c, homeo.ext $ by simp,
one := homeo.id α,
one_mul := id_circ_f,
mul_one := f_circ_id,
inv := homeo.symm,
mul_left_inv := homeo.symm_comp }
@[simp] theorem aut_mul_val (f g : homeo α α) (x) : (f * g) x = f (g x) :=
homeo.comp_val _ _ _
@[simp] theorem aut_one_val (x) : (1 : homeo α α) x = x := rfl
theorem aut_inv (f : homeo α α) : f⁻¹ = f.symm := rfl
|
29678fc89917c1d86f23a173bc5f81acfa8ee58a | d7189ea2ef694124821b033e533f18905b5e87ef | /galois/probabilistic.lean | fa16e28e92e5022bb413bb369a668627f57144e8 | [
"Apache-2.0"
] | permissive | digama0/lean-protocol-support | eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59 | cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda | refs/heads/master | 1,625,421,450,627 | 1,506,035,462,000 | 1,506,035,462,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,993 | lean | /-
This module is the start for defining core concepts needed to talk about
security proofs of cryptographic processes. At the moment, it is a fairly
empty skeleton. I expect more will be needed.
Here are a list of the main concepts that we will need:
"Probability" : A function from some finite domain to rational numbers. The sum should add up to one.
"Negligible function" : We'll need to define this concept, then prove various
operators involving negligible functions (e.g., the sum of two negligible functions
is negligible).
Univariate polynomial:
Polynomial-bounded Probablistic Process: Need an instruction set.
Notion of a "efficient computation":
- Maybe just a family of arithmetic circuits with a polynomial size.
The plan for this work is to create placeholder operations needed to formalize the
security model presented in Alex's paper and/or the Guardtime papers:
Security Proofs for the BLT Signature Scheme
http://eprint.iacr.org/2014/696
Efficient Record-Level Keyless Signatures for Audit Logs
https://eprint.iacr.org/2014/552.pdf
-/
import galois.bitvec
import galois.nat
import galois.rat
instance : has_to_string ℚ :=
⟨ λx, "rat" ⟩
universe variables u v
def algebra.sum {α : Type u} [has_zero α] [has_add α] : list α → α
| [] := 0
| (x::l) := x + algebra.sum l
------------------------------------------------------------------------
-- univariate_poly
inductive univariate_poly.ne_poly (α : Type) [has_zero α]
| last : Π (r : α), r ≠ 0 → univariate_poly.ne_poly
| cons : α → univariate_poly.ne_poly → univariate_poly.ne_poly
-- A univariate polynomial
inductive univariate_poly (α : Type) [has_zero α]
| zero {} : univariate_poly
| nonzero : ne_poly α → univariate_poly
namespace univariate_poly
-- This returns the polynomial denoting a constant
def cns {α : Type} [has_zero α] [decidable_eq α] (x : α) : univariate_poly α :=
if pr : x = 0 then
zero
else
nonzero (ne_poly.last x pr)
def one {α : Type} [has_zero α] [has_one α] [decidable_eq α] : univariate_poly α := cns 1
def cons {α : Type} [has_zero α] [decidable_eq α] : α → univariate_poly α → univariate_poly α
| c zero := cns c
| c (nonzero p) :=
nonzero (ne_poly.cons c p)
-- The free variable in the polynomial
def x {α : Type} [has_zero α] [has_one α] [decidable_eq α] : univariate_poly α := cons 0 one
section eval
variable {α : Type}
variables [has_zero α] [has_add α] [has_mul α]
def ne_eval (x : α) : ne_poly α → α
| (ne_poly.last r pr) := r
| (ne_poly.cons c p) := c + ne_eval p * x
def eval : univariate_poly α → α → α
| zero x := 0
| (nonzero p) x := ne_eval x p
instance : has_coe_to_fun (univariate_poly α) :=
{ F := λe, α → α
, coe := eval
}
end eval
section arith
variable {α : Type}
variable [semiring α]
variable [decidable_eq α]
def ne_add : ne_poly α → ne_poly α → univariate_poly α
| (ne_poly.last x _) (ne_poly.last y _) := cns (x + y)
| (ne_poly.last x _) (ne_poly.cons yc yr) := nonzero (ne_poly.cons (x + yc) yr)
| (ne_poly.cons xc xr) (ne_poly.last y _) := nonzero (ne_poly.cons (xc + y) xr)
| (ne_poly.cons xc xr) (ne_poly.cons yc yr) := cons (xc + yc) (ne_add xr yr)
def add : univariate_poly α → univariate_poly α → univariate_poly α
| zero y := y
| (nonzero x) zero := (nonzero x)
| (nonzero x) (nonzero y) := ne_add x y
instance : has_zero (univariate_poly α) := ⟨ zero ⟩
instance : has_one (univariate_poly α) := ⟨ one ⟩
instance : has_add (univariate_poly α) := ⟨ add ⟩
-- Multipy a non-empty polynomial by a constant
def ne_cmul (c : α) : ne_poly α → univariate_poly α
| (ne_poly.last d pr) := cns (c * d)
| (ne_poly.cons d p) := cons (c * d) (ne_cmul p)
def cmul (c : α) : univariate_poly α → univariate_poly α
| zero := zero
| (nonzero x) := ne_cmul c x
def ne_mul : ne_poly α → univariate_poly α → univariate_poly α
| (ne_poly.last x xnz) y := cmul x y
| (ne_poly.cons c r) y := cmul c y + cons 0 (ne_mul r y)
def mul : univariate_poly α → univariate_poly α → univariate_poly α
| zero y := zero
| (nonzero x) y := ne_mul x y
end arith
section to_string
parameter {α : Type}
parameter [has_zero α]
parameter [has_to_string α]
-- `ne_to_string n p` prints out the polynomial "p × x^n" in normalized form.
def ne_to_string : ℕ → ne_poly α → string
| n (ne_poly.last r pr) := to_string r ++ " x^" ++ to_string n
| n (ne_poly.cons c p) := ne_to_string (n + 1) p ++ " + " ++ to_string c ++ "⬝x^" ++ to_string n
def to_string : univariate_poly α → string
| zero := "0"
| (nonzero p) := ne_to_string 0 p
instance : has_to_string (univariate_poly α) := ⟨ to_string ⟩
end to_string
end univariate_poly
------------------------------------------------------------------------
-- negligible function
-- This is a function with decreases to 0.
--
-- It essentially says that μ approaches 0 super exponentially fast.
def is_negligible (μ : ℕ → ℚ) :=
∀(c : ℕ), ∃(n0 : ℕ), ∀(n : ℕ),
n0 ≤ n → abs (μ n) < 1 / (rat.of_nat (nat.pow n c))
-- This is a function with decreases to 0.
--
-- It essentially says that μ approaches 0 super exponentially fast.
def dep_is_negligible (α : ℕ → Type) (μ : Π(k : ℕ), α k → ℚ) :=
∀(c : ℕ), ∃(n0 : ℕ), ∀(n : ℕ) (x : α n),
n0 ≤ n → abs (μ n x) < 1 / (rat.of_nat (nat.pow n c))
-- This is a function with decreases to 0.
--
-- It essentially says that μ approaches 0 super exponentially fast.
def negligible_function := { μ : ℕ → ℚ // is_negligible μ }
------------------------------------------------------------------------
-- random
-- A monad for getting random values.
--
-- Note. This will almost certainly need to be generalized into a
-- monad for probablistic processes. It will probably need to include
-- some way for defining turing complete operations. Perhaps we will
-- define a notion of an algebra.
inductive random (α : Type) : Type
| uniform_bitvec : Π(k : ℕ), (bitvec k → random) → random
| pure : α → random
instance : has_pure random :=
{ pure := @random.pure }
-- Return the probability that the computation returns true.
def random.pr (r : random bool) : ℚ :=
let on_uniform (k : ℕ) (next : bitvec k → random bool) (rec : bitvec k → rat) : rat :=
algebra.sum (list.map rec (bitvec.all k)) / rat.of_nat (nat.pow 2 k) in
let on_pure (a : bool) : rat := if a then 1 else 0 in
@random.rec bool (λx, rat) on_uniform on_pure r
-- This defines a function family over a class K with domain D and range R.
def family (K D R : Type) := K → D → R
def family.keys {K D R : Type} (f : family K D R) := K
def family.dom {K D R : Type} (f : family K D R) := D
def family.range {K D R : Type} (f : family K D R) := R
-- This creates a random function
def random.fun (k : ℕ) (D R : Type) (f : family (bitvec k) D R) : random (D → R) :=
random.uniform_bitvec k (random.pure ∘ f)
|
0d7b55bede173cf3b366d29699c3e862cbb729d0 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /src/Lean/Server/Requests.lean | 845885afb8b3c5221f6a3b9c3bf5781ede7a1f2b | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 6,482 | lean | /-
Copyright (c) 2021 Wojciech Nawrocki. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki, Marc Huisinga
-/
import Lean.DeclarationRange
import Lean.Data.Json
import Lean.Data.Lsp
import Lean.Server.FileSource
import Lean.Server.FileWorker.Utils
/-! We maintain a global map of LSP request handlers. This allows user code such as plugins
to register its own handlers, for example to support ITP functionality such as goal state
visualization.
For details of how to register one, see `registerLspRequestHandler`. -/
namespace Lean.Server.Requests
structure RequestError where
code : JsonRpc.ErrorCode
message : String
namespace RequestError
open JsonRpc
def fileChanged : RequestError :=
{ code := ErrorCode.contentModified
message := "File changed." }
def methodNotFound (method : String) : RequestError :=
{ code := ErrorCode.methodNotFound
message := s!"No request handler found for '{method}'" }
instance : Coe IO.Error RequestError where
coe e := { code := ErrorCode.internalError
message := toString e }
def toLspResponseError (id : RequestID) (e : RequestError) : ResponseError Unit :=
{ id := id
code := e.code
message := e.message }
end RequestError
structure RequestContext where
srcSearchPath : SearchPath
docRef : IO.Ref FileWorker.EditableDocument
hLog : IO.FS.Stream
abbrev RequestTask α := Task (Except RequestError α)
/-- Workers execute request handlers in this monad. -/
abbrev RequestM := ReaderT RequestContext <| ExceptT RequestError IO
namespace RequestM
open FileWorker
open Snapshots
def readDoc : RequestM EditableDocument := fun rc =>
rc.docRef.get
def asTask (t : RequestM α) : RequestM (RequestTask α) := fun rc => do
let t ← IO.asTask <| t rc
return t.map fun
| Except.error e => throwThe RequestError e
| Except.ok v => v
def mapTask (t : Task α) (f : α → RequestM β) : RequestM (RequestTask β) := fun rc => do
let t ← (IO.mapTask · t) fun a => f a rc
return t.map fun
| Except.error e => throwThe RequestError e
| Except.ok v => v
def bindTask (t : Task α) (f : α → RequestM (RequestTask β)) : RequestM (RequestTask β) := fun rc => do
let t ← IO.bindTask t fun a => do
match (← f a rc) with
| Except.error e => return Task.pure <| Except.ok <| Except.error e
| Except.ok t => return t.map Except.ok
return t.map fun
| Except.error e => throwThe RequestError e
| Except.ok v => v
/-- Create a task which waits for a snapshot matching `p`, handles various errors,
and if a matching snapshot was found executes `x` with it. If not found, the task
executes `notFoundX`. -/
def withWaitFindSnap (doc : EditableDocument) (p : Snapshot → Bool)
(notFoundX : RequestM β)
(x : Snapshot → RequestM β)
: RequestM (RequestTask β) := do
let findTask ← doc.cmdSnaps.waitFind? p
mapTask findTask fun
/- The elaboration task that we're waiting for may be aborted if the file contents change.
In that case, we reply with the `fileChanged` error. Thanks to this, the server doesn't
get bogged down in requests for an old state of the document. -/
| Except.error FileWorker.ElabTaskError.aborted =>
throwThe RequestError RequestError.fileChanged
| Except.error (FileWorker.ElabTaskError.ioError e) =>
throwThe IO.Error e
| Except.error FileWorker.ElabTaskError.eof => notFoundX
| Except.ok none => notFoundX
| Except.ok (some snap) => x snap
end RequestM
/- The global request handlers table. -/
section HandlerTable
open Lsp
private structure RequestHandler where
fileSource : Json → Except RequestError Lsp.DocumentUri
handle : Json → RequestM (RequestTask Json)
builtin_initialize requestHandlers : IO.Ref (Std.PersistentHashMap String RequestHandler) ←
IO.mkRef {}
private def parseParams (paramType : Type) [FromJson paramType] (params : Json) : Except RequestError paramType :=
fromJson? params |>.mapError fun inner =>
{ code := JsonRpc.ErrorCode.parseError
message := s!"Cannot parse request params: {params.compress}\n{inner}" }
/-- NB: This method may only be called in `initialize`/`builtin_initialize` blocks.
A registration consists of:
- a type of JSON-parsable request data `paramType`
- a `FileSource` instance for it so the system knows where to route requests
- a type of JSON-serializable response data `respType`
- an actual `handler` which runs in the `RequestM` monad and is expected
to produce an asynchronous `RequestTask` which does any waiting/computation
A handler task may be cancelled at any time, so it should check the cancellation token when possible
to handle this cooperatively. Any exceptions thrown in a request handler will be reported to the client
as LSP error responses. -/
def registerLspRequestHandler (method : String)
paramType [FromJson paramType] [FileSource paramType]
respType [ToJson respType]
(handler : paramType → RequestM (RequestTask respType)) : IO Unit := do
if !(← IO.initializing) then
throw <| IO.userError s!"Failed to register LSP request handler for '{method}': only possible during initialization"
if (←requestHandlers.get).contains method then
throw <| IO.userError s!"Failed to register LSP request handler for '{method}': already registered"
let fileSource := fun j =>
parseParams paramType j |>.map fun p =>
Lsp.fileSource p
let handle := fun j => do
let params ← parseParams paramType j
let t ← handler params
t.map <| Except.map ToJson.toJson
requestHandlers.modify fun rhs => rhs.insert method { fileSource, handle }
private def lookupLspRequestHandler (method : String) : IO (Option RequestHandler) := do
(← requestHandlers.get).find? method
def routeLspRequest (method : String) (params : Json) : IO (Except RequestError DocumentUri) := do
match (← lookupLspRequestHandler method) with
| none => return Except.error <| RequestError.methodNotFound method
| some rh => return rh.fileSource params
def handleLspRequest (method : String) (params : Json) : RequestM (RequestTask Json) := do
match (← lookupLspRequestHandler method) with
| none => throwThe IO.Error <| IO.userError s!"internal server error: request '{method}' routed through watchdog but unknown in worker; are both using the same plugins?"
| some rh => rh.handle params
end HandlerTable
end Lean.Server.Requests |
82ce7101658cfc54cf8d4062f380b0bc501a499e | 6f5de810441f308574c75db94e700cd376fae571 | /src/dpll.lean | 6770292778347f2a9db74d914346f466e509ee42 | [
"Apache-2.0"
] | permissive | TwoFX/lean-dpll | c64c4beed742133007a08fb054c33e8e7f03f66a | f621689295a9ed883ed9af0b8e817927311ce676 | refs/heads/master | 1,693,255,456,121 | 1,635,758,972,000 | 1,635,758,972,000 | 423,206,970 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,693 | lean | /-
Copyright (c) 2021 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import tactic cnf
universes u v
variables {α : Type u} [decidable_eq α]
namespace list
variables {β : Type v} [add_monoid β] [partial_order β]
variables [contravariant_class β β (+) (<)]
variables [covariant_class β β (+) (<)]
variables [covariant_class β β (function.swap (+)) (≤)]
variables [covariant_class β β (function.swap (+)) (<)]
variables [covariant_class β β (+) (≤)]
variables [@decidable_rel β (≤)]
lemma sum_map_le_sum_map {l : list α} {f g : α → β} (hfg : ∀ x ∈ l, f x ≤ g x) : (l.map f).sum ≤ (l.map g).sum :=
begin
induction l with x l ih,
{ refl },
{ simp only [sum_cons, map],
exact add_le_add (hfg _ (mem_cons_self _ _)) (ih (λ x hx, hfg _ (mem_cons_of_mem _ hx))) }
end
lemma sum_map_lt_sum_map (l : list α) (f g : α → β) (hfg : ∀ x ∈ l, f x ≤ g x) :
(l.map f).sum < (l.map g).sum ↔ ∃ x ∈ l, f x < g x :=
begin
refine ⟨_, _⟩,
{ induction l with a as ih,
{ simp only [lt_self_iff_false, forall_false_left, map_nil] },
{ by_cases h : f a < g a,
{ exact λ _, ⟨a, ⟨mem_cons_self _ _, h⟩⟩ },
{ have hfa : f a = g a := decidable.eq_iff_le_not_lt.2 ⟨hfg _ (mem_cons_self _ _), h⟩,
simp only [list.map_cons, list.sum_cons, hfa, add_lt_add_iff_left],
intro h',
obtain ⟨x, ⟨hx, hx'⟩⟩ := ih (λ x hx, hfg _ (mem_cons_of_mem _ hx)) h',
exact ⟨x, ⟨mem_cons_of_mem _ hx, hx'⟩⟩ } } },
{ rintro ⟨x, ⟨hx, hx'⟩⟩,
obtain ⟨s, t, rfl⟩ := list.mem_split hx,
simp only [sum_cons, map, sum_append, map_append],
refine add_lt_add_of_le_of_lt (sum_map_le_sum_map (λ x hx, hfg _ (mem_append_left _ hx))) _,
exact add_lt_add_of_lt_of_le hx' (sum_map_le_sum_map (λ x hx, hfg _ (mem_append_right _ (mem_cons_of_mem _ hx)))) }
end
end list
namespace literal
end literal
namespace clause
def unit_propagate (l : literal α) (c : clause α) : clause α :=
c.filter $ (≠) l.inverse
def unit_propagate' (l : literal α) (c : clause α) : option (clause α) :=
if l ∈ c then none else some (unit_propagate l c)
lemma unit_propagate'_of_mem {l : literal α} {c : clause α} (h : l ∈ c) : unit_propagate' l c = none :=
by simp only [unit_propagate', h, if_true]
lemma unit_propagate'_of_not_mem {l : literal α} {c : clause α} (h : l ∉ c) :
unit_propagate' l c = some (unit_propagate l c) :=
by simp only [unit_propagate', h, if_false]
lemma unit_propagate'_eq_some (l : literal α) (c d : clause α) :
unit_propagate' l c = some d ↔ l ∉ c ∧ unit_propagate l c = d :=
by by_cases h : l ∈ c; simp [unit_propagate', h]
@[simp]
def satisfied' (ι : interpretation α) : option (clause α) → Prop
| none := tt
| (some c) := satisfied ι c
@[simp]
def length' : option (clause α) → ℕ
| none := 0
| (some c) := c.length
lemma length'_comp_some : (length' : option (clause α) → ℕ) ∘ some = list.length :=
rfl
lemma length_unit_propagate {l : literal α} {c : clause α} (hl : l.inverse ∈ c) :
(unit_propagate l c).length < c.length :=
(list.length_filter_lt_length_iff_exists _ _).2 ⟨_, hl, λ h, h rfl⟩
lemma length'_unit_propagate'_of_mem {l : literal α} {c : clause α} (hl : l ∈ c) : length' (unit_propagate' l c) < c.length :=
by simpa only [unit_propagate'_of_mem hl, length'] using list.length_pos_of_mem hl
lemma length'_unit_propagate' {l : literal α} {c : clause α} (hl : l.inverse ∈ c) : length' (unit_propagate' l c) < c.length :=
begin
by_cases h : l ∈ c,
{ exact length'_unit_propagate'_of_mem h },
{ rw [unit_propagate'_of_not_mem h, length'],
exact length_unit_propagate hl }
end
lemma length_unit_propagate_le (l : literal α) (c : clause α) : (unit_propagate l c).length ≤ c.length :=
list.length_le_of_sublist $ list.filter_sublist c
lemma length'_unit_propagate'_le (l : literal α) (c : clause α) : length' (unit_propagate' l c) ≤ c.length :=
begin
by_cases h : l ∈ c,
{ rw unit_propagate'_of_mem h,
exact zero_le _ },
{ rw unit_propagate'_of_not_mem h,
exact length_unit_propagate_le l c }
end
lemma mem_unit_propagate {l : literal α} {c : clause α} {m : literal α} :
m ∈ unit_propagate l c ↔ m ∈ c ∧ l.inverse ≠ m :=
by rw [unit_propagate, list.mem_filter]
lemma satisfied_unit_propagate (l : literal α) (c : clause α) (ι : interpretation α)
(hl : literal.satisfied ι l) : satisfied ι (unit_propagate l c) ↔ satisfied ι c :=
begin
simp only [satisfied],
refine ⟨_, _⟩,
{ rintro ⟨m, ⟨hmem, hm⟩⟩,
rw [mem_unit_propagate] at hmem,
exact ⟨m, ⟨hmem.1, hm⟩⟩ },
{ rintro ⟨m, ⟨hmem, hm⟩⟩,
refine ⟨m, ⟨_, hm⟩⟩,
{ rw mem_unit_propagate,
refine ⟨hmem, _⟩,
symmetry,
apply literal.not_satisfied_and_satisfied_inverse _ _ _ hm hl } }
end
lemma satisfied'_unit_propagate' (l : literal α) (c : clause α) (ι : interpretation α)
(hl : literal.satisfied ι l) : satisfied' ι (unit_propagate' l c) ↔ satisfied ι c :=
begin
by_cases h : l ∈ c,
{ rw [unit_propagate'_of_mem h, satisfied', satisfied, coe_sort_tt, true_iff],
exact ⟨_, h, hl⟩ },
{ rw [unit_propagate'_of_not_mem h, satisfied', satisfied_unit_propagate],
exact hl }
end
end clause
namespace cnf
def unit_propagate (l : literal α) (c : cnf α) : cnf α :=
c.filter_map $ clause.unit_propagate' l
lemma unit_propagate_cons (l : literal α) (γ : clause α) (c : cnf α) :
unit_propagate l (γ :: c) = if l ∈ γ then unit_propagate l c else (clause.unit_propagate l γ) :: unit_propagate l c :=
begin
by_cases h : l ∈ γ,
{ simp only [h, unit_propagate, clause.unit_propagate'_of_mem h, list.filter_map_cons_none, if_true] },
{ simp only [h, unit_propagate, list.filter_map_cons_some _ _ _ (clause.unit_propagate'_of_not_mem h),
eq_self_iff_true, if_false, and_self] }
end
lemma sizeof_unit_propagate (l : literal α) (c : cnf α) :
sizeof (unit_propagate l c) = (c.map (clause.length' ∘ clause.unit_propagate' l)).sum :=
begin
induction c with γ c ih,
{ refl },
{ simp only [sizeof_eq_size, size, unit_propagate_cons, list.sum_cons, function.comp_app, list.map],
by_cases h : l ∈ γ,
{ simp only [h, clause.unit_propagate'_of_mem h, ←ih, sizeof_eq_size, size, if_true, clause.length', zero_add] },
{ simp only [h, clause.unit_propagate'_of_not_mem h, ←ih, sizeof_eq_size, size, list.sum_cons, clause.length',
if_false, list.map] } }
end
lemma sizeof_cnf (c : cnf α) : sizeof c = (c.map (clause.length' ∘ some)).sum :=
by rw [clause.length'_comp_some, sizeof_eq_size, size]
lemma sizeof_unit_propagate_of_mem {l : literal α} {γ : clause α} {c : cnf α} (hlγ : l ∈ γ ∨ l.inverse ∈ γ) (hγc: γ ∈ c) :
sizeof (unit_propagate l c) < sizeof c :=
begin
rw [sizeof_unit_propagate, sizeof_cnf, list.sum_map_lt_sum_map],
{ cases hlγ,
{ exact ⟨γ, hγc, clause.length'_unit_propagate'_of_mem hlγ⟩ },
{ exact ⟨γ, hγc, clause.length'_unit_propagate' hlγ⟩ } },
{ exact λ _ _, clause.length'_unit_propagate'_le _ _ }
end
lemma mem_unit_propagate (l : literal α) (c : cnf α) (γ : clause α) :
γ ∈ unit_propagate l c ↔ ∃ δ, (δ ∈ c ∧ l ∉ δ) ∧ clause.unit_propagate l δ = γ :=
by simp only [unit_propagate, clause.unit_propagate'_eq_some, and.assoc, list.mem_filter_map]
lemma non_mem_unit_propagate {l : literal α} {c : cnf α} {γ : clause α} (hγ : γ ∈ unit_propagate l c) : l ∉ γ :=
begin
obtain ⟨δ, ⟨⟨hδc, hlδ⟩, rfl⟩⟩ := (mem_unit_propagate l c γ).1 hγ,
exact λ hl, hlδ (clause.mem_unit_propagate.1 hl).1
end
lemma inverse_non_mem_unit_propagate {l : literal α} {c : cnf α} {γ : clause α} (hγ : γ ∈ unit_propagate l c) :
l.inverse ∉ γ :=
begin
obtain ⟨δ, ⟨⟨hδc, hlδ⟩, rfl⟩⟩ := (mem_unit_propagate l c γ).1 hγ,
exact λ hl, (clause.mem_unit_propagate.1 hl).2 rfl
end
lemma satisfied_unit_propagate (l : literal α) {c : cnf α} {ι : interpretation α}
(hl : literal.satisfied ι l) : satisfied ι (unit_propagate l c) ↔ satisfied ι c :=
begin
simp only [satisfied],
refine ⟨λ h γ hγ, _, λ h γ hγ, _⟩,
{ by_cases hlγ : l ∈ γ,
{ rw clause.satisfied,
exact ⟨l, hlγ, hl⟩ },
{ rw ←clause.satisfied_unit_propagate l _ _ hl,
apply h,
rw mem_unit_propagate,
exact ⟨γ, ⟨hγ, hlγ⟩, rfl⟩ } },
{ rw mem_unit_propagate at hγ,
rcases hγ with ⟨δ, ⟨hδ, -⟩, rfl⟩,
rw clause.satisfied_unit_propagate _ _ _ hl,
exact h _ hδ }
end
lemma satisfiable_of_satisfiable_unit_propagate {l : literal α} {c : cnf α} (h : satisfiable (unit_propagate l c)) :
satisfiable c :=
begin
rcases h with ⟨ι, hι⟩,
by_cases h : literal.satisfied ι l,
{ exact ⟨ι, (satisfied_unit_propagate _ h).1 hι⟩ },
{ refine ⟨ι.flip l, (satisfied_unit_propagate l _).1 ((satisfied_iff _ ι (λ γ hγ m hm, _)).2 hι)⟩,
{ simpa only [interpretation.satisfied_flip_eq] using h },
{ apply interpretation.satisfied_flip_neq;
rintro rfl,
exacts [non_mem_unit_propagate hγ hm, inverse_non_mem_unit_propagate hγ hm] } }
end
def any_literal : Π (c : clause α) (hc : c ≠ []), literal α
| [] hc := false.elim (hc rfl)
| (l::lc) hc := l
lemma any_literal_mem : ∀ {c : clause α} (hc : c ≠ []), any_literal c hc ∈ c
| [] hc := false.elim (hc rfl)
| (l::lc) hc := list.mem_cons_self _ _
def dpll : cnf α → bool
| [] := tt
| (x::xs) := if h : [] ∈ x::xs then ff else
have hx : x ≠ [], from λ hx, h $ or.inl hx.symm,
have h1 : sizeof (unit_propagate (any_literal x hx) (x::xs)) < sizeof (x::xs),
from sizeof_unit_propagate_of_mem (or.inl (any_literal_mem hx)) (list.mem_cons_self _ _),
have h2 : sizeof (unit_propagate (any_literal x hx).inverse (x::xs)) < sizeof (x::xs), by
{ refine sizeof_unit_propagate_of_mem (or.inr _) (list.mem_cons_self _ _),
simpa only [literal.inverse_inverse] using any_literal_mem hx },
dpll (unit_propagate (any_literal x hx) (x::xs)) || dpll (unit_propagate (any_literal x hx).inverse (x::xs))
theorem dpll_correct : ∀ (c : cnf α), dpll c ↔ satisfiable c
| [] := by simp only [dpll, satisfiable_empty, coe_sort_tt]
| (x::xs) := if h : [] ∈ x::xs then by simpa [dpll, h] using not_satisfiable_of_empty_mem h else
have hx : x ≠ [], from λ hx, h $ or.inl hx.symm,
have h1 : sizeof (unit_propagate (any_literal x hx) (x::xs)) < sizeof (x::xs),
from sizeof_unit_propagate_of_mem (or.inl (any_literal_mem hx)) (list.mem_cons_self _ _),
have h2 : sizeof (unit_propagate (any_literal x hx).inverse (x::xs)) < sizeof (x::xs), by
{ refine sizeof_unit_propagate_of_mem (or.inr _) (list.mem_cons_self _ _),
simpa only [literal.inverse_inverse] using any_literal_mem hx },
begin
simp only [dpll, h, dpll_correct, bor_coe_iff, bor, dif_neg, not_false_iff, literal.inverse],
clear h1 h2,
refine ⟨_, _⟩,
{ rintro (hr|hr),
{ apply satisfiable_of_satisfiable_unit_propagate hr },
{ apply satisfiable_of_satisfiable_unit_propagate hr } },
{ rintro ⟨ι, hι⟩,
by_cases hlι : literal.satisfied ι (any_literal x hx),
{ exact or.inl ⟨ι, (satisfied_unit_propagate _ hlι).2 hι⟩ },
{ refine or.inr ⟨ι, (satisfied_unit_propagate _ _).2 hι⟩,
simpa only [literal.satisfied_inverse] using hlι } }
end
section
open literal
#eval dpll [[pos 5], [neg 5, pos 6], [neg 6]]
end
end cnf
|
13be38ca1fd2a0e9768471bdefe88a006b88b8f5 | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/doSeqRightIssue.lean | f39a9598dd2de49af0c8c37e25006f114adaa6f5 | [
"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 | 275 | lean | new_frontend
universes u
variables {α : Type u}
variables {β : α → Type v}
theorem ex {p₁ p₂ : Sigma (fun a => β a)} (h₁ : p₁.1 = p₂.1) (h : p₁.2 ≅ p₂.2) : p₁ = p₂ :=
match p₁, p₂, h₁, h with
| ⟨_, _⟩, ⟨_, _⟩, rfl, HEq.refl _ => rfl
|
37147956b264c717910c2523e8ae4e773ef0c6e0 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/number_theory/fermat4_auto.lean | 14b526ffb2b9553edc252cbc4198a49bf9525fab | [] | 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,194 | lean | /-
Copyright (c) 2020 Paul van Wamelen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Paul van Wamelen.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.number_theory.pythagorean_triples
import Mathlib.ring_theory.coprime
import Mathlib.PostPort
namespace Mathlib
/-!
# Fermat's Last Theorem for the case n = 4
There are no non-zero integers `a`, `b` and `c` such that `a ^ 4 + b ^ 4 = c ^ 4`.
-/
/-- Shorthand for three non-zero integers `a`, `b`, and `c` satisfying `a ^ 4 + b ^ 4 = c ^ 2`.
We will show that no integers satisfy this equation. Clearly Fermat's Last theorem for n = 4
follows. -/
def fermat_42 (a : ℤ) (b : ℤ) (c : ℤ) :=
a ≠ 0 ∧ b ≠ 0 ∧ a ^ bit0 (bit0 1) + b ^ bit0 (bit0 1) = c ^ bit0 1
namespace fermat_42
theorem comm {a : ℤ} {b : ℤ} {c : ℤ} : fermat_42 a b c ↔ fermat_42 b a c := sorry
theorem mul {a : ℤ} {b : ℤ} {c : ℤ} {k : ℤ} (hk0 : k ≠ 0) :
fermat_42 a b c ↔ fermat_42 (k * a) (k * b) (k ^ bit0 1 * c) :=
sorry
theorem ne_zero {a : ℤ} {b : ℤ} {c : ℤ} (h : fermat_42 a b c) : c ≠ 0 := sorry
/-- We say a solution to `a ^ 4 + b ^ 4 = c ^ 2` is minimal if there is no other solution with
a smaller `c` (in absolute value). -/
def minimal (a : ℤ) (b : ℤ) (c : ℤ) :=
fermat_42 a b c ∧ ∀ (a1 b1 c1 : ℤ), fermat_42 a1 b1 c1 → int.nat_abs c ≤ int.nat_abs c1
/-- if we have a solution to `a ^ 4 + b ^ 4 = c ^ 2` then there must be a minimal one. -/
theorem exists_minimal {a : ℤ} {b : ℤ} {c : ℤ} (h : fermat_42 a b c) :
∃ (a0 : ℤ), ∃ (b0 : ℤ), ∃ (c0 : ℤ), minimal a0 b0 c0 :=
sorry
/-- a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` must have `a` and `b` coprime. -/
theorem coprime_of_minimal {a : ℤ} {b : ℤ} {c : ℤ} (h : minimal a b c) : is_coprime a b := sorry
/-- We can swap `a` and `b` in a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2`. -/
theorem minimal_comm {a : ℤ} {b : ℤ} {c : ℤ} : minimal a b c → minimal b a c := sorry
/-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has positive `c`. -/
theorem neg_of_minimal {a : ℤ} {b : ℤ} {c : ℤ} : minimal a b c → minimal a b (-c) := sorry
/-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has `a` odd. -/
theorem exists_odd_minimal {a : ℤ} {b : ℤ} {c : ℤ} (h : fermat_42 a b c) :
∃ (a0 : ℤ), ∃ (b0 : ℤ), ∃ (c0 : ℤ), minimal a0 b0 c0 ∧ a0 % bit0 1 = 1 :=
sorry
/-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has
`a` odd and `c` positive. -/
theorem exists_pos_odd_minimal {a : ℤ} {b : ℤ} {c : ℤ} (h : fermat_42 a b c) :
∃ (a0 : ℤ), ∃ (b0 : ℤ), ∃ (c0 : ℤ), minimal a0 b0 c0 ∧ a0 % bit0 1 = 1 ∧ 0 < c0 :=
sorry
end fermat_42
theorem int.coprime_of_sqr_sum {r : ℤ} {s : ℤ} (h2 : is_coprime s r) :
is_coprime (r ^ bit0 1 + s ^ bit0 1) r :=
eq.mpr (id (Eq._oldrec (Eq.refl (is_coprime (r ^ bit0 1 + s ^ bit0 1) r)) (pow_two r)))
(eq.mpr (id (Eq._oldrec (Eq.refl (is_coprime (r * r + s ^ bit0 1) r)) (pow_two s)))
(is_coprime.mul_add_left_left (is_coprime.mul_left h2 h2) r))
theorem int.coprime_of_sqr_sum' {r : ℤ} {s : ℤ} (h : is_coprime r s) :
is_coprime (r ^ bit0 1 + s ^ bit0 1) (r * s) :=
is_coprime.mul_right (int.coprime_of_sqr_sum (iff.mp is_coprime_comm h))
(eq.mpr
(id
(Eq._oldrec (Eq.refl (is_coprime (r ^ bit0 1 + s ^ bit0 1) s))
(add_comm (r ^ bit0 1) (s ^ bit0 1))))
(int.coprime_of_sqr_sum h))
namespace fermat_42
-- If we have a solution to a ^ 4 + b ^ 4 = c ^ 2, we can construct a smaller one. This
-- implies there can't be a smallest solution.
theorem not_minimal {a : ℤ} {b : ℤ} {c : ℤ} (h : minimal a b c) (ha2 : a % bit0 1 = 1)
(hc : 0 < c) : False :=
sorry
end fermat_42
theorem not_fermat_42 {a : ℤ} {b : ℤ} {c : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) :
a ^ bit0 (bit0 1) + b ^ bit0 (bit0 1) ≠ c ^ bit0 1 :=
sorry
theorem not_fermat_4 {a : ℤ} {b : ℤ} {c : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) :
a ^ bit0 (bit0 1) + b ^ bit0 (bit0 1) ≠ c ^ bit0 (bit0 1) :=
sorry
end Mathlib |
b734293347eab73fb5d380fbabd1dee3af352fb8 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /tests/lean/run/quasi_pattern_unification_approx_issue.lean | 33aa4dde64c589807a67d57a1cbd254d534963fc | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 260 | lean |
variables {δ σ : Type}
def foo0 : StateT δ (StateT σ Id) σ :=
getThe σ
def foo1 : StateT δ (StateT σ Id) σ :=
monadLift (get : StateT σ Id σ)
def foo2 : StateT δ (StateT σ Id) σ := do
let s : σ ← monadLift (get : StateT σ Id σ)
pure s
|
dfe4ecf82bb08fcbccf98868b80a4f3774c2cec9 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/probability_theory/independence.lean | d75aba76b3fa6e448b8d62c10a48a5bac23461ba | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 17,218 | lean | /-
Copyright (c) 2021 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne
-/
import measure_theory.measure_space
import measure_theory.pi_system
import algebra.big_operators.intervals
import data.finset.intervals
/-!
# Independence of sets of sets and measure spaces (σ-algebras)
* A family of sets of sets `π : ι → set (set α)` is independent with respect to a measure `μ` if for
any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`,
`μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. It will be used for families of π-systems.
* A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a
measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they
define is independent. I.e., `m : ι → measurable_space α` is independent with respect to a
measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets
`f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i)`.
* Independence of sets (or events in probabilistic parlance) is defined as independence of the
measurable space structures they generate: a set `s` generates the measurable space structure with
measurable sets `∅, s, sᶜ, univ`.
* Independence of functions (or random variables) is also defined as independence of the measurable
space structures they generate: a function `f` for which we have a measurable space `m` on the
codomain generates `measurable_space.comap f m`.
## Main statements
* TODO: `Indep_of_Indep_sets`: if π-systems are independent as sets of sets, then the
measurable space structures they generate are independent.
* `indep_of_indep_sets`: variant with two π-systems.
## Implementation notes
We provide one main definition of independence:
* `Indep_sets`: independence of a family of sets of sets `pi : ι → set (set α)`.
Three other independence notions are defined using `Indep_sets`:
* `Indep`: independence of a family of measurable space structures `m : ι → measurable_space α`,
* `Indep_set`: independence of a family of sets `s : ι → set α`,
* `Indep_fun`: independence of a family of functions. For measurable spaces
`m : Π (i : ι), measurable_space (β i)`, we consider functions `f : Π (i : ι), α → β i`.
Additionally, we provide four corresponding statements for two measurable space structures (resp.
sets of sets, sets, functions) instead of a family. These properties are denoted by the same names
as for a family, but without a capital letter, for example `indep_fun` is the version of `Indep_fun`
for two functions.
The definition of independence for `Indep_sets` uses finite sets (`finset`). An alternative and
equivalent way of defining independence would have been to use countable sets.
TODO: prove that equivalence.
Most of the definitions and lemma in this file list all variables instead of using the `variables`
keyword at the beginning of a section, for example
`lemma indep.symm {α} {m₁ m₂ : measurable_space α} [measurable_space α] {μ : measure α} ...` .
This is intentional, to be able to control the order of the `measurable_space` variables. Indeed
when defining `μ` in the example above, the measurable space used is the last one defined, here
`[measurable_space α]`, and not `m₁` or `m₂`.
## References
* Williams, David. Probability with martingales. Cambridge university press, 1991.
Part A, Chapter 4.
-/
open measure_theory measurable_space
open_locale big_operators classical
namespace probability_theory
section definitions
/-- A family of sets of sets `π : ι → set (set α)` is independent with respect to a measure `μ` if
for any finite set of indices `s = {i_1, ..., i_n}`, for any sets
`f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `.
It will be used for families of pi_systems. -/
def Indep_sets {α ι} [measurable_space α] (π : ι → set (set α)) (μ : measure α . volume_tac) :
Prop :=
∀ (s : finset ι) {f : ι → set α} (H : ∀ i, i ∈ s → f i ∈ π i), μ (⋂ i ∈ s, f i) = ∏ i in s, μ (f i)
/-- Two sets of sets `s₁, s₂` are independent with respect to a measure `μ` if for any sets
`t₁ ∈ p₁, t₂ ∈ s₂`, then `μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/
def indep_sets {α} [measurable_space α] (s1 s2 : set (set α)) (μ : measure α . volume_tac) : Prop :=
∀ t1 t2 : set α, t1 ∈ s1 → t2 ∈ s2 → μ (t1 ∩ t2) = μ t1 * μ t2
/-- A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a
measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they
define is independent. `m : ι → measurable_space α` is independent with respect to measure `μ` if
for any finite set of indices `s = {i_1, ..., i_n}`, for any sets
`f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. -/
def Indep {α ι} (m : ι → measurable_space α) [measurable_space α] (μ : measure α . volume_tac) :
Prop :=
Indep_sets (λ x, (m x).measurable_set') μ
/-- Two measurable space structures (or σ-algebras) `m₁, m₂` are independent with respect to a
measure `μ` (defined on a third σ-algebra) if for any sets `t₁ ∈ m₁, t₂ ∈ m₂`,
`μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/
def indep {α} (m₁ m₂ : measurable_space α) [measurable_space α] (μ : measure α . volume_tac) :
Prop :=
indep_sets (m₁.measurable_set') (m₂.measurable_set') μ
/-- A family of sets is independent if the family of measurable space structures they generate is
independent. For a set `s`, the generated measurable space has measurable sets `∅, s, sᶜ, univ`. -/
def Indep_set {α ι} [measurable_space α] (s : ι → set α) (μ : measure α . volume_tac) : Prop :=
Indep (λ i, generate_from {s i}) μ
/-- Two sets are independent if the two measurable space structures they generate are independent.
For a set `s`, the generated measurable space structure has measurable sets `∅, s, sᶜ, univ`. -/
def indep_set {α} [measurable_space α] (s t : set α) (μ : measure α . volume_tac) : Prop :=
indep (generate_from {s}) (generate_from {t}) μ
/-- A family of functions defined on the same space `α` and taking values in possibly different
spaces, each with a measurable space structure, is independent if the family of measurable space
structures they generate on `α` is independent. For a function `g` with codomain having measurable
space structure `m`, the generated measurable space structure is `measurable_space.comap g m`. -/
def Indep_fun {α ι} [measurable_space α] {β : ι → Type*} (m : Π (x : ι), measurable_space (β x))
(f : Π (x : ι), α → β x) (μ : measure α . volume_tac) : Prop :=
Indep (λ x, measurable_space.comap (f x) (m x)) μ
/-- Two functions are independent if the two measurable space structures they generate are
independent. For a function `f` with codomain having measurable space structure `m`, the generated
measurable space structure is `measurable_space.comap f m`. -/
def indep_fun {α β γ} [measurable_space α] [mβ : measurable_space β] [mγ : measurable_space γ]
(f : α → β) (g : α → γ) (μ : measure α . volume_tac) : Prop :=
indep (measurable_space.comap f mβ) (measurable_space.comap g mγ) μ
end definitions
section indep
lemma indep_sets.symm {α} {s₁ s₂ : set (set α)} [measurable_space α] {μ : measure α}
(h : indep_sets s₁ s₂ μ) :
indep_sets s₂ s₁ μ :=
by { intros t1 t2 ht1 ht2, rw [set.inter_comm, mul_comm], exact h t2 t1 ht2 ht1, }
lemma indep.symm {α} {m₁ m₂ : measurable_space α} [measurable_space α] {μ : measure α}
(h : indep m₁ m₂ μ) :
indep m₂ m₁ μ :=
indep_sets.symm h
lemma indep_sets_of_indep_sets_of_le_left {α} {s₁ s₂ s₃: set (set α)} [measurable_space α]
{μ : measure α} (h_indep : indep_sets s₁ s₂ μ) (h31 : s₃ ⊆ s₁) :
indep_sets s₃ s₂ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 (set.mem_of_subset_of_mem h31 ht1) ht2
lemma indep_sets_of_indep_sets_of_le_right {α} {s₁ s₂ s₃: set (set α)} [measurable_space α]
{μ : measure α} (h_indep : indep_sets s₁ s₂ μ) (h32 : s₃ ⊆ s₂) :
indep_sets s₁ s₃ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (set.mem_of_subset_of_mem h32 ht2)
lemma indep_of_indep_of_le_left {α} {m₁ m₂ m₃: measurable_space α} [measurable_space α]
{μ : measure α} (h_indep : indep m₁ m₂ μ) (h31 : m₃ ≤ m₁) :
indep m₃ m₂ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 (h31 _ ht1) ht2
lemma indep_of_indep_of_le_right {α} {m₁ m₂ m₃: measurable_space α} [measurable_space α]
{μ : measure α} (h_indep : indep m₁ m₂ μ) (h32 : m₃ ≤ m₂) :
indep m₁ m₃ μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (h32 _ ht2)
lemma indep_sets.union {α} [measurable_space α] {s₁ s₂ s' : set (set α)} {μ : measure α}
(h₁ : indep_sets s₁ s' μ) (h₂ : indep_sets s₂ s' μ) :
indep_sets (s₁ ∪ s₂) s' μ :=
begin
intros t1 t2 ht1 ht2,
cases (set.mem_union _ _ _).mp ht1 with ht1₁ ht1₂,
{ exact h₁ t1 t2 ht1₁ ht2, },
{ exact h₂ t1 t2 ht1₂ ht2, },
end
@[simp] lemma indep_sets.union_iff {α} [measurable_space α] {s₁ s₂ s' : set (set α)}
{μ : measure α} :
indep_sets (s₁ ∪ s₂) s' μ ↔ indep_sets s₁ s' μ ∧ indep_sets s₂ s' μ :=
⟨λ h, ⟨indep_sets_of_indep_sets_of_le_left h (set.subset_union_left s₁ s₂),
indep_sets_of_indep_sets_of_le_left h (set.subset_union_right s₁ s₂)⟩,
λ h, indep_sets.union h.left h.right⟩
lemma indep_sets.Union {α ι} [measurable_space α] {s : ι → set (set α)} {s' : set (set α)}
{μ : measure α} (hyp : ∀ n, indep_sets (s n) s' μ) :
indep_sets (⋃ n, s n) s' μ :=
begin
intros t1 t2 ht1 ht2,
rw set.mem_Union at ht1,
cases ht1 with n ht1,
exact hyp n t1 t2 ht1 ht2,
end
lemma indep_sets.inter {α} [measurable_space α] {s₁ s' : set (set α)} (s₂ : set (set α))
{μ : measure α} (h₁ : indep_sets s₁ s' μ) :
indep_sets (s₁ ∩ s₂) s' μ :=
λ t1 t2 ht1 ht2, h₁ t1 t2 ((set.mem_inter_iff _ _ _).mp ht1).left ht2
lemma indep_sets.Inter {α ι} [measurable_space α] {s : ι → set (set α)} {s' : set (set α)}
{μ : measure α} (h : ∃ n, indep_sets (s n) s' μ) :
indep_sets (⋂ n, s n) s' μ :=
by {intros t1 t2 ht1 ht2, cases h with n h, exact h t1 t2 (set.mem_Inter.mp ht1 n) ht2 }
lemma indep_sets_singleton_iff {α} [measurable_space α] {s t : set α} {μ : measure α} :
indep_sets {s} {t} μ ↔ μ (s ∩ t) = μ s * μ t :=
⟨λ h, h s t rfl rfl,
λ h s1 t1 hs1 ht1, by rwa [set.mem_singleton_iff.mp hs1, set.mem_singleton_iff.mp ht1]⟩
end indep
/-! ### Deducing `indep` from `Indep` -/
section from_Indep_to_indep
lemma Indep_sets.indep_sets {α ι} {s : ι → set (set α)} [measurable_space α] {μ : measure α}
(h_indep : Indep_sets s μ) {i j : ι} (hij : i ≠ j) :
indep_sets (s i) (s j) μ :=
begin
intros t₁ t₂ ht₁ ht₂,
have hf_m : ∀ (x : ι), x ∈ {i, j} → (ite (x=i) t₁ t₂) ∈ s x,
{ intros x hx,
cases finset.mem_insert.mp hx with hx hx,
{ simp [hx, ht₁], },
{ simp [finset.mem_singleton.mp hx, hij.symm, ht₂], }, },
have h1 : t₁ = ite (i = i) t₁ t₂, by simp only [if_true, eq_self_iff_true],
have h2 : t₂ = ite (j = i) t₁ t₂, by simp only [hij.symm, if_false],
have h_inter : (⋂ (t : ι) (H : t ∈ ({i, j} : finset ι)), ite (t = i) t₁ t₂)
= (ite (i = i) t₁ t₂) ∩ (ite (j = i) t₁ t₂),
by simp only [finset.set_bInter_singleton, finset.set_bInter_insert],
have h_prod : (∏ (t : ι) in ({i, j} : finset ι), μ (ite (t = i) t₁ t₂))
= μ (ite (i = i) t₁ t₂) * μ (ite (j = i) t₁ t₂),
by simp only [hij, finset.prod_singleton, finset.prod_insert, not_false_iff,
finset.mem_singleton],
rw h1,
nth_rewrite 1 h2,
nth_rewrite 3 h2,
rw [←h_inter, ←h_prod, h_indep {i, j} hf_m],
end
lemma Indep.indep {α ι} {m : ι → measurable_space α} [measurable_space α] {μ : measure α}
(h_indep : Indep m μ) {i j : ι} (hij : i ≠ j) :
indep (m i) (m j) μ :=
begin
change indep_sets ((λ x, (m x).measurable_set') i) ((λ x, (m x).measurable_set') j) μ,
exact Indep_sets.indep_sets h_indep hij,
end
end from_Indep_to_indep
/-!
## π-system lemma
Independence of measurable spaces is equivalent to independence of generating π-systems.
-/
section from_measurable_spaces_to_sets_of_sets
/-! ### Independence of measurable space structures implies independence of generating π-systems -/
lemma Indep.Indep_sets {α ι} [measurable_space α] {μ : measure α} {m : ι → measurable_space α}
{s : ι → set (set α)} (hms : ∀ n, m n = measurable_space.generate_from (s n))
(h_indep : Indep m μ) :
Indep_sets s μ :=
begin
refine (λ S f hfs, h_indep S (λ x hxS, _)),
simp_rw hms x,
exact measurable_set_generate_from (hfs x hxS),
end
lemma indep.indep_sets {α} [measurable_space α] {μ : measure α} {s1 s2 : set (set α)}
(h_indep : indep (generate_from s1) (generate_from s2) μ) :
indep_sets s1 s2 μ :=
λ t1 t2 ht1 ht2, h_indep t1 t2 (measurable_set_generate_from ht1) (measurable_set_generate_from ht2)
end from_measurable_spaces_to_sets_of_sets
section from_pi_systems_to_measurable_spaces
/-! ### Independence of generating π-systems implies independence of measurable space structures -/
private lemma indep_sets.indep_aux {α} {m2 : measurable_space α}
{m : measurable_space α} {μ : measure α} [probability_measure μ] {p1 p2 : set (set α)}
(h2 : m2 ≤ m) (hp2 : is_pi_system p2) (hpm2 : m2 = generate_from p2)
(hyp : indep_sets p1 p2 μ) {t1 t2 : set α} (ht1 : t1 ∈ p1) (ht2m : m2.measurable_set' t2) :
μ (t1 ∩ t2) = μ t1 * μ t2 :=
begin
let μ_inter := μ.restrict t1,
let ν := (μ t1) • μ,
have h_univ : μ_inter set.univ = ν set.univ,
by rw [measure.restrict_apply_univ, measure.smul_apply, measure_univ, mul_one],
haveI : finite_measure μ_inter := @restrict.finite_measure α _ t1 μ ⟨measure_lt_top μ t1⟩,
rw [set.inter_comm, ←@measure.restrict_apply α _ μ t1 t2 (h2 t2 ht2m)],
refine ext_on_measurable_space_of_generate_finite m p2 (λ t ht, _) h2 hpm2 hp2 h_univ ht2m,
have ht2 : m.measurable_set' t,
{ refine h2 _ _,
rw hpm2,
exact measurable_set_generate_from ht, },
rw [measure.restrict_apply ht2, measure.smul_apply, set.inter_comm],
exact hyp t1 t ht1 ht,
end
lemma indep_sets.indep {α} {m1 m2 : measurable_space α} {m : measurable_space α}
{μ : measure α} [probability_measure μ] {p1 p2 : set (set α)} (h1 : m1 ≤ m) (h2 : m2 ≤ m)
(hp1 : is_pi_system p1) (hp2 : is_pi_system p2) (hpm1 : m1 = generate_from p1)
(hpm2 : m2 = generate_from p2) (hyp : indep_sets p1 p2 μ) :
indep m1 m2 μ :=
begin
intros t1 t2 ht1 ht2,
let μ_inter := μ.restrict t2,
let ν := (μ t2) • μ,
have h_univ : μ_inter set.univ = ν set.univ,
by rw [measure.restrict_apply_univ, measure.smul_apply, measure_univ, mul_one],
haveI : finite_measure μ_inter := @restrict.finite_measure α _ t2 μ ⟨measure_lt_top μ t2⟩,
rw [mul_comm, ←@measure.restrict_apply α _ μ t2 t1 (h1 t1 ht1)],
refine ext_on_measurable_space_of_generate_finite m p1 (λ t ht, _) h1 hpm1 hp1 h_univ ht1,
have ht1 : m.measurable_set' t,
{ refine h1 _ _,
rw hpm1,
exact measurable_set_generate_from ht, },
rw [measure.restrict_apply ht1, measure.smul_apply, mul_comm],
exact indep_sets.indep_aux h2 hp2 hpm2 hyp ht ht2,
end
end from_pi_systems_to_measurable_spaces
section indep_set
/-! ### Independence of measurable sets
We prove the following equivalences on `indep_set`, for measurable sets `s, t`.
* `indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t`,
* `indep_set s t μ ↔ indep_sets {s} {t} μ`.
-/
variables {α : Type*} [measurable_space α] {s t : set α} (S T : set (set α))
lemma indep_set_iff_indep_sets_singleton (hs_meas : measurable_set s) (ht_meas : measurable_set t)
(μ : measure α . volume_tac) [probability_measure μ] :
indep_set s t μ ↔ indep_sets {s} {t} μ :=
⟨indep.indep_sets, λ h, indep_sets.indep
(generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu))
(generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu)) (is_pi_system.singleton s)
(is_pi_system.singleton t) rfl rfl h⟩
lemma indep_set_iff_measure_inter_eq_mul (hs_meas : measurable_set s) (ht_meas : measurable_set t)
(μ : measure α . volume_tac) [probability_measure μ] :
indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t :=
(indep_set_iff_indep_sets_singleton hs_meas ht_meas μ).trans indep_sets_singleton_iff
lemma indep_sets.indep_set_of_mem (hs : s ∈ S) (ht : t ∈ T) (hs_meas : measurable_set s)
(ht_meas : measurable_set t) (μ : measure α . volume_tac) [probability_measure μ]
(h_indep : indep_sets S T μ) :
indep_set s t μ :=
(indep_set_iff_measure_inter_eq_mul hs_meas ht_meas μ).mpr (h_indep s t hs ht)
end indep_set
end probability_theory
|
05b8a6e0aa5d35359455ba7825f660472839e7d5 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/algebra/module/multilinear.lean | ef1fead7e6fc31cec231e480aa867d2500e0af43 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 23,805 | 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 topology.algebra.module.basic
import linear_algebra.multilinear.basic
/-!
# Continuous multilinear maps
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define continuous multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are multilinear
and continuous, by extending the space of multilinear maps with a continuity assumption.
Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type, and all these
spaces are also topological spaces.
## Main definitions
* `continuous_multilinear_map R M₁ M₂` is the space of continuous multilinear maps from
`Π(i : ι), M₁ i` to `M₂`. We show that it is an `R`-module.
## Implementation notes
We mostly follow the API of multilinear maps.
## Notation
We introduce the notation `M [×n]→L[R] M'` for the space of continuous `n`-multilinear maps from
`M^n` to `M'`. This is a particular case of the general notion (where we allow varying dependent
types as the arguments of our continuous multilinear maps), but arguably the most important one,
especially when defining iterated derivatives.
-/
open function fin set
open_locale big_operators
universes u v w w₁ w₁' w₂ w₃ w₄
variables {R : Type u} {ι : Type v} {n : ℕ} {M : fin n.succ → Type w} {M₁ : ι → Type w₁}
{M₁' : ι → Type w₁'} {M₂ : Type w₂} {M₃ : Type w₃} {M₄ : Type w₄}
/-- Continuous multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂`
are modules over `R` with a topological structure. In applications, there will be compatibility
conditions between the algebraic and the topological structures, but this is not needed for the
definition. -/
structure continuous_multilinear_map (R : Type u) {ι : Type v} (M₁ : ι → Type w₁) (M₂ : Type w₂)
[semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂]
[∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂]
extends multilinear_map R M₁ M₂ :=
(cont : continuous to_fun)
notation M `[×`:25 n `]→L[`:25 R `] ` M' := continuous_multilinear_map R (λ (i : fin n), M) M'
namespace continuous_multilinear_map
section semiring
variables [semiring R]
[Πi, add_comm_monoid (M i)] [Πi, add_comm_monoid (M₁ i)] [Πi, add_comm_monoid (M₁' i)]
[add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [Π i, module R (M i)]
[Π i, module R (M₁ i)] [Π i, module R (M₁' i)] [module R M₂]
[module R M₃] [module R M₄]
[Π i, topological_space (M i)] [Π i, topological_space (M₁ i)] [Π i, topological_space (M₁' i)]
[topological_space M₂] [topological_space M₃] [topological_space M₄]
(f f' : continuous_multilinear_map R M₁ M₂)
theorem to_multilinear_map_injective :
function.injective (continuous_multilinear_map.to_multilinear_map :
continuous_multilinear_map R M₁ M₂ → multilinear_map R M₁ M₂)
| ⟨f, hf⟩ ⟨g, hg⟩ rfl := rfl
instance continuous_map_class :
continuous_map_class (continuous_multilinear_map R M₁ M₂) (Π i, M₁ i) M₂ :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, to_multilinear_map_injective $ multilinear_map.coe_injective h,
map_continuous := continuous_multilinear_map.cont }
instance : has_coe_to_fun (continuous_multilinear_map R M₁ M₂) (λ _, (Π i, M₁ i) → M₂) :=
⟨λ f, f⟩
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (L₁ : continuous_multilinear_map R M₁ M₂) (v : Π i, M₁ i) : M₂ := L₁ v
initialize_simps_projections continuous_multilinear_map
(-to_multilinear_map, to_multilinear_map_to_fun → apply)
@[continuity] lemma coe_continuous : continuous (f : (Π i, M₁ i) → M₂) := f.cont
@[simp] lemma coe_coe : (f.to_multilinear_map : (Π i, M₁ i) → M₂) = f := rfl
@[ext] theorem ext {f f' : continuous_multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' :=
fun_like.ext _ _ H
theorem ext_iff {f f' : continuous_multilinear_map R M₁ M₂} : f = f' ↔ ∀ x, f x = f' x :=
by rw [← to_multilinear_map_injective.eq_iff, multilinear_map.ext_iff]; refl
@[simp] lemma map_add [decidable_eq ι] (m : Πi, M₁ i) (i : ι) (x y : M₁ i) :
f (update m i (x + y)) = f (update m i x) + f (update m i y) :=
f.map_add' m i x y
@[simp] lemma map_smul [decidable_eq ι] (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) :
f (update m i (c • x)) = c • f (update m i x) :=
f.map_smul' m i c x
lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 :=
f.to_multilinear_map.map_coord_zero i h
@[simp] lemma map_zero [nonempty ι] : f 0 = 0 :=
f.to_multilinear_map.map_zero
instance : has_zero (continuous_multilinear_map R M₁ M₂) :=
⟨{ cont := continuous_const, ..(0 : multilinear_map R M₁ M₂) }⟩
instance : inhabited (continuous_multilinear_map R M₁ M₂) := ⟨0⟩
@[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : continuous_multilinear_map R M₁ M₂) m = 0 := rfl
@[simp] lemma to_multilinear_map_zero :
(0 : continuous_multilinear_map R M₁ M₂).to_multilinear_map = 0 :=
rfl
section has_smul
variables {R' R'' A : Type*} [monoid R'] [monoid R''] [semiring A]
[Π i, module A (M₁ i)] [module A M₂]
[distrib_mul_action R' M₂] [has_continuous_const_smul R' M₂] [smul_comm_class A R' M₂]
[distrib_mul_action R'' M₂] [has_continuous_const_smul R'' M₂] [smul_comm_class A R'' M₂]
instance : has_smul R' (continuous_multilinear_map A M₁ M₂) :=
⟨λ c f, { cont := f.cont.const_smul c, .. c • f.to_multilinear_map }⟩
@[simp] lemma smul_apply (f : continuous_multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) :
(c • f) m = c • f m := rfl
@[simp] lemma to_multilinear_map_smul (c : R') (f : continuous_multilinear_map A M₁ M₂) :
(c • f).to_multilinear_map = c • f.to_multilinear_map :=
rfl
instance [smul_comm_class R' R'' M₂] :
smul_comm_class R' R'' (continuous_multilinear_map A M₁ M₂) :=
⟨λ c₁ c₂ f, ext $ λ x, smul_comm _ _ _⟩
instance [has_smul R' R''] [is_scalar_tower R' R'' M₂] :
is_scalar_tower R' R'' (continuous_multilinear_map A M₁ M₂) :=
⟨λ c₁ c₂ f, ext $ λ x, smul_assoc _ _ _⟩
instance [distrib_mul_action R'ᵐᵒᵖ M₂] [is_central_scalar R' M₂] :
is_central_scalar R' (continuous_multilinear_map A M₁ M₂) :=
⟨λ c₁ f, ext $ λ x, op_smul_eq_smul _ _⟩
instance : mul_action R' (continuous_multilinear_map A M₁ M₂) :=
function.injective.mul_action to_multilinear_map to_multilinear_map_injective (λ _ _, rfl)
end has_smul
section has_continuous_add
variable [has_continuous_add M₂]
instance : has_add (continuous_multilinear_map R M₁ M₂) :=
⟨λ f f', ⟨f.to_multilinear_map + f'.to_multilinear_map, f.cont.add f'.cont⟩⟩
@[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl
@[simp] lemma to_multilinear_map_add (f g : continuous_multilinear_map R M₁ M₂) :
(f + g).to_multilinear_map = f.to_multilinear_map + g.to_multilinear_map :=
rfl
instance add_comm_monoid : add_comm_monoid (continuous_multilinear_map R M₁ M₂) :=
to_multilinear_map_injective.add_comm_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl)
/-- Evaluation of a `continuous_multilinear_map` at a vector as an `add_monoid_hom`. -/
def apply_add_hom (m : Π i, M₁ i) : continuous_multilinear_map R M₁ M₂ →+ M₂ :=
⟨λ f, f m, rfl, λ _ _, rfl⟩
@[simp] lemma sum_apply {α : Type*} (f : α → continuous_multilinear_map R M₁ M₂)
(m : Πi, M₁ i) {s : finset α} : (∑ a in s, f a) m = ∑ a in s, f a m :=
(apply_add_hom m).map_sum f s
end has_continuous_add
/-- If `f` is a continuous multilinear map, then `f.to_continuous_linear_map m i` is the continuous
linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the
`i`-th coordinate. -/
def to_continuous_linear_map [decidable_eq ι] (m : Πi, M₁ i) (i : ι) : M₁ i →L[R] M₂ :=
{ cont := f.cont.comp (continuous_const.update i continuous_id),
.. f.to_multilinear_map.to_linear_map m i }
/-- The cartesian product of two continuous multilinear maps, as a continuous multilinear map. -/
def prod (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) :
continuous_multilinear_map R M₁ (M₂ × M₃) :=
{ cont := f.cont.prod_mk g.cont,
.. f.to_multilinear_map.prod g.to_multilinear_map }
@[simp] lemma prod_apply
(f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) (m : Πi, M₁ i) :
(f.prod g) m = (f m, g m) := rfl
/-- Combine a family of continuous multilinear maps with the same domain and codomains `M' i` into a
continuous multilinear map taking values in the space of functions `Π i, M' i`. -/
def pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)]
[Π i, module R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) :
continuous_multilinear_map R M₁ (Π i, M' i) :=
{ cont := continuous_pi $ λ i, (f i).coe_continuous,
to_multilinear_map := multilinear_map.pi (λ i, (f i).to_multilinear_map) }
@[simp] lemma coe_pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)]
[Π i, topological_space (M' i)] [Π i, module R (M' i)]
(f : Π i, continuous_multilinear_map R M₁ (M' i)) :
⇑(pi f) = λ m j, f j m :=
rfl
lemma pi_apply {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)]
[Π i, topological_space (M' i)] [Π i, module R (M' i)]
(f : Π i, continuous_multilinear_map R M₁ (M' i)) (m : Π i, M₁ i) (j : ι') :
pi f m j = f j m :=
rfl
/-- Restrict the codomain of a continuous multilinear map to a submodule. -/
@[simps to_multilinear_map apply_coe]
def cod_restrict (f : continuous_multilinear_map R M₁ M₂) (p : submodule R M₂) (h : ∀ v, f v ∈ p) :
continuous_multilinear_map R M₁ p :=
⟨f.1.cod_restrict p h, f.cont.subtype_mk _⟩
section
variables (R M₂)
/-- The evaluation map from `ι → M₂` to `M₂` is multilinear at a given `i` when `ι` is subsingleton.
-/
@[simps to_multilinear_map apply]
def of_subsingleton [subsingleton ι] (i' : ι) : continuous_multilinear_map R (λ _ : ι, M₂) M₂ :=
{ to_multilinear_map := multilinear_map.of_subsingleton R _ i',
cont := continuous_apply _ }
variables (M₁) {M₂}
/-- The constant map is multilinear when `ι` is empty. -/
@[simps to_multilinear_map apply]
def const_of_is_empty [is_empty ι] (m : M₂) : continuous_multilinear_map R M₁ M₂ :=
{ to_multilinear_map := multilinear_map.const_of_is_empty R _ m,
cont := continuous_const }
end
/-- If `g` is continuous multilinear and `f` is a collection of continuous linear maps,
then `g (f₁ m₁, ..., fₙ mₙ)` is again a continuous multilinear map, that we call
`g.comp_continuous_linear_map f`. -/
def comp_continuous_linear_map
(g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) :
continuous_multilinear_map R M₁ M₄ :=
{ cont := g.cont.comp $ continuous_pi $ λj, (f j).cont.comp $ continuous_apply _,
.. g.to_multilinear_map.comp_linear_map (λ i, (f i).to_linear_map) }
@[simp] lemma comp_continuous_linear_map_apply (g : continuous_multilinear_map R M₁' M₄)
(f : Π i : ι, M₁ i →L[R] M₁' i) (m : Π i, M₁ i) :
g.comp_continuous_linear_map f m = g (λ i, f i $ m i) :=
rfl
/-- Composing a continuous multilinear map with a continuous linear map gives again a
continuous multilinear map. -/
def _root_.continuous_linear_map.comp_continuous_multilinear_map
(g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) :
continuous_multilinear_map R M₁ M₃ :=
{ cont := g.cont.comp f.cont,
.. g.to_linear_map.comp_multilinear_map f.to_multilinear_map }
@[simp] lemma _root_.continuous_linear_map.comp_continuous_multilinear_map_coe (g : M₂ →L[R] M₃)
(f : continuous_multilinear_map R M₁ M₂) :
((g.comp_continuous_multilinear_map f) : (Πi, M₁ i) → M₃) =
(g : M₂ → M₃) ∘ (f : (Πi, M₁ i) → M₂) :=
by { ext m, refl }
/-- `continuous_multilinear_map.pi` as an `equiv`. -/
@[simps]
def pi_equiv {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)]
[Π i, topological_space (M' i)] [Π i, module R (M' i)] :
(Π i, continuous_multilinear_map R M₁ (M' i)) ≃
continuous_multilinear_map R M₁ (Π i, M' i) :=
{ to_fun := continuous_multilinear_map.pi,
inv_fun := λ f i, (continuous_linear_map.proj i : _ →L[R] M' i).comp_continuous_multilinear_map f,
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, refl } }
/-- An equivalence of the index set defines an equivalence between the spaces of continuous
multilinear maps. This is the forward map of this equivalence. -/
@[simps to_multilinear_map apply]
def dom_dom_congr {ι' : Type*} (e : ι ≃ ι') (f : continuous_multilinear_map R (λ _ : ι, M₂) M₃) :
continuous_multilinear_map R (λ _ : ι', M₂) M₃ :=
{ to_multilinear_map := f.dom_dom_congr e,
cont := f.cont.comp $ continuous_pi $ λ _, continuous_apply _ }
/-- An equivalence of the index set defines an equivalence between the spaces of continuous
multilinear maps. In case of normed spaces, this is a linear isometric equivalence, see
`continuous.multilinear_map.dom_dom_congrₗᵢ`. -/
@[simps]
def dom_dom_congr_equiv {ι' : Type*} (e : ι ≃ ι') :
continuous_multilinear_map R (λ _ : ι, M₂) M₃ ≃ continuous_multilinear_map R (λ _ : ι', M₂) M₃ :=
{ to_fun := dom_dom_congr e,
inv_fun := dom_dom_congr e.symm,
left_inv := λ _, ext $ λ _, by simp,
right_inv := λ _, ext $ λ _, by simp }
/-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one
can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the
additivity of a multilinear map along the first variable. -/
lemma cons_add (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) :
f (cons (x+y) m) = f (cons x m) + f (cons y m) :=
f.to_multilinear_map.cons_add m x y
/-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one
can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the
multiplicativity of a multilinear map along the first variable. -/
lemma cons_smul
(f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) :
f (cons (c • x) m) = c • f (cons x m) :=
f.to_multilinear_map.cons_smul m c x
lemma map_piecewise_add [decidable_eq ι] (m m' : Πi, M₁ i) (t : finset ι) :
f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') :=
f.to_multilinear_map.map_piecewise_add _ _ _
/-- Additivity of a continuous multilinear map along all coordinates at the same time,
writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/
lemma map_add_univ [decidable_eq ι] [fintype ι] (m m' : Πi, M₁ i) :
f (m + m') = ∑ s : finset ι, f (s.piecewise m m') :=
f.to_multilinear_map.map_add_univ _ _
section apply_sum
open fintype finset
variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i))
/-- If `f` is continuous multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the
sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ...,
`r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each
coordinate. -/
lemma map_sum_finset [decidable_eq ι] :
f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) :=
f.to_multilinear_map.map_sum_finset _ _
/-- If `f` is continuous multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of
`f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from
multilinearity by expanding successively with respect to each coordinate. -/
lemma map_sum [decidable_eq ι] [∀ i, fintype (α i)] :
f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) :=
f.to_multilinear_map.map_sum _
end apply_sum
section restrict_scalar
variables (R) {A : Type*} [semiring A] [has_smul R A] [Π (i : ι), module A (M₁ i)]
[module A M₂] [∀ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂]
/-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R`
and their actions on all involved modules agree with the action of `R` on `A`. -/
def restrict_scalars (f : continuous_multilinear_map A M₁ M₂) :
continuous_multilinear_map R M₁ M₂ :=
{ to_multilinear_map := f.to_multilinear_map.restrict_scalars R,
cont := f.cont }
@[simp] lemma coe_restrict_scalars (f : continuous_multilinear_map A M₁ M₂) :
⇑(f.restrict_scalars R) = f := rfl
end restrict_scalar
end semiring
section ring
variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂]
[∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂]
(f f' : continuous_multilinear_map R M₁ M₂)
@[simp] lemma map_sub [decidable_eq ι] (m : Πi, M₁ i) (i : ι) (x y : M₁ i) :
f (update m i (x - y)) = f (update m i x) - f (update m i y) :=
f.to_multilinear_map.map_sub _ _ _ _
section topological_add_group
variable [topological_add_group M₂]
instance : has_neg (continuous_multilinear_map R M₁ M₂) :=
⟨λ f, {cont := f.cont.neg, ..(-f.to_multilinear_map)}⟩
@[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl
instance : has_sub (continuous_multilinear_map R M₁ M₂) :=
⟨λ f g, { cont := f.cont.sub g.cont, .. (f.to_multilinear_map - g.to_multilinear_map) }⟩
@[simp] lemma sub_apply (m : Πi, M₁ i) : (f - f') m = f m - f' m := rfl
instance : add_comm_group (continuous_multilinear_map R M₁ M₂) :=
to_multilinear_map_injective.add_comm_group _
rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
end topological_add_group
end ring
section comm_semiring
variables [comm_semiring R]
[∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂]
[∀i, module R (M₁ i)] [module R M₂]
[∀i, topological_space (M₁ i)] [topological_space M₂]
(f : continuous_multilinear_map R M₁ M₂)
lemma map_piecewise_smul [decidable_eq ι] (c : ι → R) (m : Πi, M₁ i) (s : finset ι) :
f (s.piecewise (λ i, c i • m i) m) = (∏ i in s, c i) • f m :=
f.to_multilinear_map.map_piecewise_smul _ _ _
/-- Multiplicativity of a continuous multilinear map along all coordinates at the same time,
writing `f (λ i, c i • m i)` as `(∏ i, c i) • f m`. -/
lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) :
f (λ i, c i • m i) = (∏ i, c i) • f m :=
f.to_multilinear_map.map_smul_univ _ _
end comm_semiring
section distrib_mul_action
variables {R' R'' A : Type*} [monoid R'] [monoid R''] [semiring A]
[Π i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂]
[Π i, topological_space (M₁ i)] [topological_space M₂]
[Π i, module A (M₁ i)] [module A M₂]
[distrib_mul_action R' M₂] [has_continuous_const_smul R' M₂] [smul_comm_class A R' M₂]
[distrib_mul_action R'' M₂] [has_continuous_const_smul R'' M₂] [smul_comm_class A R'' M₂]
instance [has_continuous_add M₂] : distrib_mul_action R' (continuous_multilinear_map A M₁ M₂) :=
function.injective.distrib_mul_action
⟨to_multilinear_map, to_multilinear_map_zero, to_multilinear_map_add⟩
to_multilinear_map_injective (λ _ _, rfl)
end distrib_mul_action
section module
variables {R' A : Type*} [semiring R'] [semiring A]
[Π i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂]
[Π i, topological_space (M₁ i)] [topological_space M₂] [has_continuous_add M₂]
[Π i, module A (M₁ i)] [module A M₂]
[module R' M₂] [has_continuous_const_smul R' M₂] [smul_comm_class A R' M₂]
/-- The space of continuous multilinear maps over an algebra over `R` is a module over `R`, for the
pointwise addition and scalar multiplication. -/
instance : module R' (continuous_multilinear_map A M₁ M₂) :=
function.injective.module _ ⟨to_multilinear_map, to_multilinear_map_zero, to_multilinear_map_add⟩
to_multilinear_map_injective (λ _ _, rfl)
/-- Linear map version of the map `to_multilinear_map` associating to a continuous multilinear map
the corresponding multilinear map. -/
@[simps] def to_multilinear_map_linear :
continuous_multilinear_map A M₁ M₂ →ₗ[R'] multilinear_map A M₁ M₂ :=
{ to_fun := to_multilinear_map,
map_add' := to_multilinear_map_add,
map_smul' := to_multilinear_map_smul }
/-- `continuous_multilinear_map.pi` as a `linear_equiv`. -/
@[simps {simp_rhs := tt}]
def pi_linear_equiv {ι' : Type*} {M' : ι' → Type*}
[Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [∀ i, has_continuous_add (M' i)]
[Π i, module R' (M' i)] [Π i, module A (M' i)] [∀ i, smul_comm_class A R' (M' i)]
[Π i, has_continuous_const_smul R' (M' i)] :
(Π i, continuous_multilinear_map A M₁ (M' i)) ≃ₗ[R']
continuous_multilinear_map A M₁ (Π i, M' i) :=
{ map_add' := λ x y, rfl,
map_smul' := λ c x, rfl,
.. pi_equiv }
end module
section comm_algebra
variables (R ι) (A : Type*) [fintype ι] [comm_semiring R] [comm_semiring A] [algebra R A]
[topological_space A] [has_continuous_mul A]
/-- The continuous multilinear map on `A^ι`, where `A` is a normed commutative algebra
over `𝕜`, associating to `m` the product of all the `m i`.
See also `continuous_multilinear_map.mk_pi_algebra_fin`. -/
protected def mk_pi_algebra : continuous_multilinear_map R (λ i : ι, A) A :=
{ cont := continuous_finset_prod _ $ λ i hi, continuous_apply _,
to_multilinear_map := multilinear_map.mk_pi_algebra R ι A}
@[simp] lemma mk_pi_algebra_apply (m : ι → A) :
continuous_multilinear_map.mk_pi_algebra R ι A m = ∏ i, m i :=
rfl
end comm_algebra
section algebra
variables (R n) (A : Type*) [comm_semiring R] [semiring A] [algebra R A]
[topological_space A] [has_continuous_mul A]
/-- The continuous multilinear map on `A^n`, where `A` is a normed algebra over `𝕜`, associating to
`m` the product of all the `m i`.
See also: `continuous_multilinear_map.mk_pi_algebra`. -/
protected def mk_pi_algebra_fin : A [×n]→L[R] A :=
{ cont := begin
change continuous (λ m, (list.of_fn m).prod),
simp_rw list.of_fn_eq_map,
exact continuous_list_prod _ (λ i hi, continuous_apply _),
end,
to_multilinear_map := multilinear_map.mk_pi_algebra_fin R n A}
variables {R n A}
@[simp] lemma mk_pi_algebra_fin_apply (m : fin n → A) :
continuous_multilinear_map.mk_pi_algebra_fin R n A m = (list.of_fn m).prod :=
rfl
end algebra
section smul_right
variables [comm_semiring R] [Π i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂]
[Π i, module R (M₁ i)] [module R M₂] [topological_space R] [Π i, topological_space (M₁ i)]
[topological_space M₂] [has_continuous_smul R M₂] (f : continuous_multilinear_map R M₁ R) (z : M₂)
/-- Given a continuous `R`-multilinear map `f` taking values in `R`, `f.smul_right z` is the
continuous multilinear map sending `m` to `f m • z`. -/
@[simps to_multilinear_map apply] def smul_right : continuous_multilinear_map R M₁ M₂ :=
{ to_multilinear_map := f.to_multilinear_map.smul_right z,
cont := f.cont.smul continuous_const }
end smul_right
end continuous_multilinear_map
|
b4b74bf55f6c71756465ae23d0e5aba70f27e098 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/algebra/module/submodule.lean | ca3b6a4ec72ca3d04ad17f91f813f378d12e3353 | [
"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 | 6,942 | lean | /-
Copyright (c) 2015 Nathaniel Thomas. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro
-/
import algebra.module.linear_map
/-!
# Submodules of a module
In this file we define
* `submodule R M` : a subset of a `module` `M` that contains zero and is closed with respect to addition and
scalar multiplication.
* `subspace k M` : an abbreviation for `submodule` assuming that `k` is a `field`.
## Tags
submodule, subspace, linear map
-/
open function
open_locale big_operators
universes u v w
variables {R : Type u} {M : Type v} {ι : Type w}
set_option old_structure_cmd true
/-- A submodule of a module is one which is closed under vector operations.
This is a sufficient condition for the subset of vectors in the submodule
to themselves form a module. -/
structure submodule (R : Type u) (M : Type v) [semiring R]
[add_comm_monoid M] [semimodule R M] extends add_submonoid M : Type v :=
(smul_mem' : ∀ (c:R) {x}, x ∈ carrier → c • x ∈ carrier)
/-- Reinterpret a `submodule` as an `add_submonoid`. -/
add_decl_doc submodule.to_add_submonoid
namespace submodule
variables [semiring R] [add_comm_monoid M] [semimodule R M]
instance : has_coe_t (submodule R M) (set M) := ⟨λ s, s.carrier⟩
instance : has_mem M (submodule R M) := ⟨λ x p, x ∈ (p : set M)⟩
instance : has_coe_to_sort (submodule R M) := ⟨_, λ p, {x : M // x ∈ p}⟩
variables (p q : submodule R M)
@[simp, norm_cast] theorem coe_sort_coe : ↥(p : set M) = p := rfl
variables {p q}
protected theorem «exists» {q : p → Prop} : (∃ x, q x) ↔ (∃ x ∈ p, q ⟨x, ‹_›⟩) := set_coe.exists
protected theorem «forall» {q : p → Prop} : (∀ x, q x) ↔ (∀ x ∈ p, q ⟨x, ‹_›⟩) := set_coe.forall
theorem coe_injective : injective (coe : submodule R M → set M) :=
λ p q h, by cases p; cases q; congr'
@[simp, norm_cast] theorem coe_set_eq : (p : set M) = q ↔ p = q := coe_injective.eq_iff
theorem ext'_iff : p = q ↔ (p : set M) = q := coe_set_eq.symm
@[ext] theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := coe_injective $ set.ext h
theorem to_add_submonoid_injective :
injective (to_add_submonoid : submodule R M → add_submonoid M) :=
λ p q h, ext'_iff.2 $ add_submonoid.ext'_iff.1 h
@[simp] theorem to_add_submonoid_eq : p.to_add_submonoid = q.to_add_submonoid ↔ p = q :=
to_add_submonoid_injective.eq_iff
end submodule
namespace submodule
section add_comm_monoid
variables [semiring R] [add_comm_monoid M]
-- We can infer the module structure implicitly from the bundled submodule,
-- rather than via typeclass resolution.
variables {semimodule_M : semimodule R M}
variables {p q : submodule R M}
variables {r : R} {x y : M}
variables (p)
@[simp] theorem mem_coe : x ∈ (p : set M) ↔ x ∈ p := iff.rfl
@[simp] lemma zero_mem : (0 : M) ∈ p := p.zero_mem'
lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add_mem' h₁ h₂
lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h
lemma sum_mem {t : finset ι} {f : ι → M} : (∀c∈t, f c ∈ p) → (∑ i in t, f i) ∈ p :=
p.to_add_submonoid.sum_mem
lemma sum_smul_mem {t : finset ι} {f : ι → M} (r : ι → R)
(hyp : ∀ c ∈ t, f c ∈ p) : (∑ i in t, r i • f i) ∈ p :=
submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ (hyp i hi))
@[simp] lemma smul_mem_iff' (u : units R) : (u:R) • x ∈ p ↔ x ∈ p :=
⟨λ h, by simpa only [smul_smul, u.inv_mul, one_smul] using p.smul_mem ↑u⁻¹ h, p.smul_mem u⟩
instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩
instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩
instance : inhabited p := ⟨0⟩
instance : has_scalar R p := ⟨λ c x, ⟨c • x.1, smul_mem _ c x.2⟩⟩
protected lemma nonempty : (p : set M).nonempty := ⟨0, p.zero_mem⟩
@[simp] lemma mk_eq_zero {x} (h : x ∈ p) : (⟨x, h⟩ : p) = 0 ↔ x = 0 := subtype.ext_iff_val
variables {p}
@[simp, norm_cast] lemma coe_eq_coe {x y : p} : (x : M) = y ↔ x = y := subtype.ext_iff_val.symm
@[simp, norm_cast] lemma coe_eq_zero {x : p} : (x : M) = 0 ↔ x = 0 := @coe_eq_coe _ _ _ _ _ _ x 0
@[simp, norm_cast] lemma coe_add (x y : p) : (↑(x + y) : M) = ↑x + ↑y := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : p) : M) = 0 := rfl
@[simp, norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl
@[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl
@[simp] lemma coe_mem (x : p) : (x : M) ∈ p := x.2
@[simp] protected lemma eta (x : p) (hx : (x : M) ∈ p) : (⟨x, hx⟩ : p) = x := subtype.eta x hx
variables (p)
instance : add_comm_monoid p :=
{ add := (+), zero := 0, .. p.to_add_submonoid.to_add_comm_monoid }
instance : semimodule R p :=
by refine {smul := (•), ..};
{ intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] }
/-- Embedding of a submodule `p` to the ambient space `M`. -/
protected def subtype : p →ₗ[R] M :=
by refine {to_fun := coe, ..}; simp [coe_smul]
@[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl
lemma subtype_eq_val : ((submodule.subtype p) : p → M) = subtype.val := rfl
end add_comm_monoid
section add_comm_group
variables [ring R] [add_comm_group M]
variables {semimodule_M : semimodule R M}
variables (p p' : submodule R M)
variables {r : R} {x y : M}
lemma neg_mem (hx : x ∈ p) : -x ∈ p := by rw ← neg_one_smul R; exact p.smul_mem _ hx
/-- Reinterpret a submodule as an additive subgroup. -/
def to_add_subgroup : add_subgroup M :=
{ neg_mem' := λ _, p.neg_mem , .. p.to_add_submonoid }
@[simp] lemma coe_to_add_subgroup : (p.to_add_subgroup : set M) = p := rfl
lemma sub_mem : x ∈ p → y ∈ p → x - y ∈ p := p.to_add_subgroup.sub_mem
@[simp] lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := p.to_add_subgroup.neg_mem_iff
lemma add_mem_iff_left : y ∈ p → (x + y ∈ p ↔ x ∈ p) := p.to_add_subgroup.add_mem_cancel_right
lemma add_mem_iff_right : x ∈ p → (x + y ∈ p ↔ y ∈ p) := p.to_add_subgroup.add_mem_cancel_left
instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩
@[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl
instance : add_comm_group p :=
{ add := (+), zero := 0, neg := has_neg.neg, ..p.to_add_subgroup.to_add_comm_group }
@[simp, norm_cast] lemma coe_sub (x y : p) : (↑(x - y) : M) = ↑x - ↑y := rfl
end add_comm_group
end submodule
namespace submodule
variables [division_ring R] [add_comm_group M] [module R M]
variables (p : submodule R M) {r : R} {x y : M}
theorem smul_mem_iff (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p :=
p.smul_mem_iff' (units.mk0 r r0)
end submodule
/-- Subspace of a vector space. Defined to equal `submodule`. -/
abbreviation subspace (R : Type u) (M : Type v)
[field R] [add_comm_group M] [vector_space R M] :=
submodule R M
|
967bf4b036d07eeedb47f9097d7c0e33cc8adce6 | 43390109ab88557e6090f3245c47479c123ee500 | /src/finite_dimensional_vector_spaces/linear_map.lean | 5ebce05d2ef79a4c0b9dcd41e09cd6c1b8067cba | [
"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 | 17,946 | lean | /-
Copyright (c) 2018 Keji Neri, Blair Shi. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Keji Neri, Blair Shi
* `finite_free_module R n`: the set of maps from (fin n) to R (R ^ n)
-- Proved R^n is an abellian group and module R (R ^ n)
* `matrix_to_linear_map` : constructs a matrix based on the given linear map
* `linear_map_to_matrix` : constructs the linear map based on the given matrix
-- Proved the a x b matrices and R-linear maps R^b -> R^a are equivalent
-- Proved the product of two matrix is equivalent to the component of two
-- corresponding linear maps
-- Proved Hom(R^b,R^a)
* `linear_map_to_vec V n` : constructs the basis based on the linear map
* `vec_to_linear_map V n M` : construct the linear map based on the given basis
-- proved a basis v1,v2,...,vn of a fdvs V/k is just an isomorphism k^n -> V
-/
import xenalib.Ellen_Arlt_matrix_rings algebra.big_operators
import data.set.finite algebra.module data.finsupp
import algebra.group linear_algebra.basic data.fintype
import data.equiv.basic linear_algebra.linear_map_module
import algebra.pi_instances algebra.module data.list.basic
open function
universe u
variables {α : Type u}
variables {β : Type*} [add_comm_group α] [add_comm_group β]
/-- Predicate for group homomorphism. -/
class is_add_group_hom (f : α → β) : Prop :=
(add : ∀ a b : α, f (a + b) = (f a) + (f b))
namespace is_add_group_hom
variables (f : α → β) [is_add_group_hom f]
theorem zero : f 0 = 0 :=
add_self_iff_eq_zero.1 $ by simp [(add f 0 _).symm]
theorem inv (a : α) : f(-a) = -(f a) :=
eq.symm $ neg_eq_of_add_eq_zero $ by simp [(add f a (-a)).symm, zero f]
instance id : is_add_group_hom (@id α) :=
⟨λ _ _, rfl⟩
instance comp {γ} [add_comm_group γ] (g : β → γ) [is_add_group_hom g] :
is_add_group_hom (g ∘ f) :=
⟨λ x y, calc
g (f (x + y)) = g (f x + f y) : by rw add f
... = g (f x) + g (f y) : by rw add g⟩
end is_add_group_hom
definition finite_free_module (R : Type) (n : nat) := (fin n) → R
def add (R : Type) (n : nat) [ring R] :=
λ (a b :finite_free_module R n), (λ i, (a i) +(b i))
def smul {R : Type} {n : nat} [ring R] (s : R) (rn : finite_free_module R n) :
finite_free_module R n := λ I, s * (rn I)
theorem add__assoc {R : Type} {n : nat} [ring R] (a b c :(fin n) → R) :
add R n (add R n a b) c = add R n a (add R n b c):=
begin
unfold add,
funext,
simp,
end
theorem add__comm {R : Type} {n : nat} [ring R] (a b :(fin n) → R):
add R n a b =add R n b a :=
begin
unfold add,
funext,
exact add_comm (a i) (b i),
end
def zero (R : Type) (n : nat) [ring R]: finite_free_module R n := λ (i:fin n),(0 :R)
#check zero
theorem zero__add {R : Type} {n : nat} [ring R] (a:finite_free_module R n): add R n (zero R n) a = a:=
begin
unfold add,
funext,
unfold zero,
simp,
end
def neg (R : Type) (n : nat) [ring R]:= λ (a:finite_free_module R n),(λ i, -(a i))
theorem add__left__neg {R : Type} {n : nat} [ring R] (a :finite_free_module R n): add R n (neg R n a) a = zero R n:=
begin
unfold add,
unfold zero,
funext,
unfold neg,
simp,
end
def add__zero {R : Type} {n : nat} [ring R] (a :finite_free_module R n): add R n a (zero R n) =a:=
begin
unfold add,
funext,
unfold zero,
simp,
end
lemma is_add_group_hom_right_inv {α β : Type*} [add_comm_group α] [add_comm_group β]
{f: α → β} [is_add_group_hom f] (hf : injective f) { g :β → α} (h: right_inverse g f):
is_add_group_hom g:= ⟨ λ a b, hf $ by rw[h(a+b),is_add_group_hom.add f,h a,h b]⟩
instance (R : Type) [ring R] (n : nat) : add_comm_group (finite_free_module R n) :=
{add:=add R n,
add_assoc := add__assoc,
zero := zero R n,
zero_add:= zero__add,
neg:=neg R n,
add_left_neg:= add__left__neg,
add_zero:= add__zero ,
add_comm:= add__comm,
}
namespace R_module
variables (R : Type) (n : nat)
variable [ring R]
theorem smul_add (s : R) (rn rm : finite_free_module R n) :
smul s (add R n rn rm) = add R n (smul s rn) (smul s rm) :=
-- s • (rn + rm) = s • rn + s • rm
begin
apply funext,
intro,
unfold smul add,
apply mul_add,
end
theorem add_smul (s t : R) (rn: finite_free_module R n):
smul (s + t) rn = add R n (smul s rn) (smul t rn) :=
begin
apply funext,
intro,
unfold smul add,
apply add_mul,
end
theorem mul_smul (s t : R) (rn : finite_free_module R n):
smul (s * t) rn = smul s (smul t rn) :=
begin
apply funext,
intro,
unfold smul,
apply mul_assoc,
end
theorem one_smul (rn : finite_free_module R n):
smul (1 : R) rn = rn :=
begin
apply funext,
intro,
unfold smul,
apply one_mul,
end
end R_module
instance (R : Type) [ring R] (n : nat) : has_scalar R (finite_free_module R n) :=
{
smul := smul
}
instance {R : Type} {n : nat} [ring R] : module R (finite_free_module R n) :=
{
smul_add := R_module.smul_add R n,
add_smul := R_module.add_smul R n,
mul_smul := R_module.mul_smul R n,
one_smul := R_module.one_smul R n,
}
namespace map_matrix
definition matrix_to_map {R : Type} [ring R] {a b : nat} (M : matrix R a b) :
(finite_free_module R a) → (finite_free_module R b) := λ v ,(λ i,finset.sum finset.univ (λ K, (v K) *M K i ) )
instance hg {R : Type} [ring R] {a b : nat} (M : matrix R a b) : is_add_group_hom (matrix_to_map M) :=
⟨begin
intros,
funext,
unfold matrix_to_map,
show (finset.sum finset.univ (λ (K : fin a), (a_1 K + b_1 K) * M K i) =_),
conv in ( (a_1 _ + b_1 _) * M _ i)
begin
rw [add_mul],
end,
rw finset.sum_add_distrib,
refl,
end⟩
theorem smul_ {R: Type} [ring R] {a b : nat} (M : matrix R a b): ∀ (c : R) (x : finite_free_module R a),
matrix_to_map M (smul c x) = smul c (matrix_to_map M x):=
begin
intros,
unfold matrix_to_map,
funext,
unfold smul,
rw [finset.mul_sum],
simp[mul_assoc],
end
def module_hom {R: Type} [ring R] {a b : nat} (M : matrix R a b) :
@is_linear_map R _ _ _ _ _ (matrix_to_map M) :=
{ add:=
begin
exact is_add_group_hom.add _,
end,
smul:= smul_ _,
}
def matrix_to_linear_map {R : Type} [ring R] {a b : nat} (M : matrix R a b) :
(@linear_map R (finite_free_module R a) (finite_free_module R b) _ _ _) :=
⟨matrix_to_map M, module_hom M⟩
def e (R : Type) [ring R] (a: nat) (i: fin a): finite_free_module R a:= λ j, if i =j then 1 else 0
definition linear_map_to_matrix {R : Type} [ring R] {a b : nat}
(f: @linear_map R (finite_free_module R a) (finite_free_module R b) _ _ _) : matrix R a b :=
λ i j, f.1 (e R a i) j
theorem finset.sum_single {α : Type*} [fintype α]
{β : Type*} [add_comm_monoid β]
(f : α → β) {i : α}
(h : ∀ (j : α), i ≠ j → f j = 0) :
f i = finset.sum finset.univ (λ (K : α), f K) :=
begin
have H : finset.sum (finset.singleton i) (λ (K : α), f K)
= finset.sum finset.univ (λ (K : α), f K),
from finset.sum_subset (λ _ _, finset.mem_univ _)
(λ _ _ H, h _ $ mt (λ h, finset.mem_singleton.2 h.symm) H),
rw [← H, finset.sum_singleton]
end
theorem apply_function_to_sum {R : Type}[ring R] {n p : nat} (f: fin n → finite_free_module R p ) (i : fin p ):
(finset.sum finset.univ (λ (K : fin n),f K)) i = finset.sum finset.univ (λ (K : fin n), f K i):=
begin
rw finset.sum_hom (λ (v: finite_free_module R p), v i ) _,
intros,
simp,
refl,
end
theorem span {R : Type} {n : nat} [ring R] (v : finite_free_module R n):
v = finset.sum finset.univ (λ K, smul (v K) (e R n K)):=
begin
funext,
rw [apply_function_to_sum (λ i, smul (v i) (e R n i))],
simp,
unfold smul,
have H1 : ∀ (j : fin n), x ≠ j → v j * (e R n j) x = 0,
intros,
unfold e,
split_ifs,
exact false.elim (a h.symm),
simp,
have H2: finset.sum finset.univ (λ (K : fin n), v K * e R n K x) = v x * e R n x x,
have Htemp := finset.sum_single (λ (K:fin n), v K * e R n K x ) H1,
rw ←Htemp,
rw H2,
unfold e,
split_ifs,
simp,
simp,
end
theorem equiv_one {R : Type} [ring R] {a b : nat} (f : (@linear_map R (finite_free_module R a) (finite_free_module R b) _ _ _)) :
matrix_to_map (linear_map_to_matrix f ) = f :=
begin
funext,
unfold linear_map_to_matrix,
unfold matrix_to_map,
conv begin
to_rhs,
rw [span v],
end,
rw [← finset.sum_hom f _],
swap 3,
exact is_linear_map.zero f.2,
swap 2,
exact f.2.add,
rw[apply_function_to_sum (λ j,f (smul (v j) (e R a j)))],
simp,
show _ = finset.sum finset.univ (λ (K : fin a), f ((v K) • (e R a K)) i),
congr,
funext,
rw[( linear_map.is_linear_map_coe).smul],
refl,
end
theorem equiv_two {R : Type} [ring R] {p b : nat} (M : matrix R p b):
linear_map_to_matrix ⟨ matrix_to_map M, module_hom M⟩ = M :=
begin
funext,
unfold linear_map_to_matrix,
show (matrix_to_map M) (e R p i) j =_,
unfold matrix_to_map,
have H1: ∀ (K : fin p), i ≠ K → e R p i K * M K j = 0,
intros,
unfold e,
split_ifs,
exact false.elim (a h),
simp,
have H2: finset.sum finset.univ (λ (K : fin p), e R p i K * M K j) = e R p i i * M i j,
have Htemp := finset.sum_single (λ (K : fin p), e R p i K * M K j) H1,
rw ← Htemp,
rw H2,
unfold e,
split_ifs,
simp,
simp,
end
def matrix_transpose {R : Type} [ring R] {a b : nat} (M : matrix R a b) :
matrix R b a := λ I, λ J, M J I
definition matrix_to_map_right {R : Type} [ring R] {a b : nat} (M : matrix R a b) :
(finite_free_module R a) → (finite_free_module R b) :=
λ v, (λ I, finset.sum finset.univ (λ K, (matrix_transpose M) I K * (v K)))
-- end
def matrix_to_linear_map_equiv {R : Type} [ring R] {a b : nat} :
equiv (matrix R a b) (@linear_map R (finite_free_module R a) (finite_free_module R b) _ _ _):=
{to_fun := matrix_to_linear_map,
inv_fun := linear_map_to_matrix,
right_inv:=
begin
unfold function.right_inverse,
unfold function.left_inverse,
intros,
apply subtype.eq,
dsimp,
exact equiv_one x,
end,
left_inv:=
begin
unfold function.left_inverse,
intros,
exact equiv_two x,
end
}
instance {R : Type} [ring R] {a b : nat}: is_add_group_hom (@matrix_to_linear_map R _ a b):=
{
add:=
begin
intros,
unfold matrix_to_linear_map,
apply linear_map.ext,
intro x,
show _ = matrix_to_map a_1 x + matrix_to_map b_1 x,
show matrix_to_map (a_1 + b_1) x = _,
unfold matrix_to_map,
funext,
show _ = (finset.sum finset.univ (λ (K : fin a), x K * a_1 K i)) +
( finset.sum finset.univ (λ (K : fin a), x K * b_1 K i)),
rw[← finset.sum_add_distrib],
congr,
funext,
have H1: x K * (a_1 + b_1) K i = x K * (a_1 K i + b_1 K i),
refl,
rw[H1],
rw[mul_add],
end
}
theorem comp_is_linear_map {R : Type} [ring R] {a b c : nat}
(f : (@linear_map R (finite_free_module R b) (finite_free_module R a) _ _ _))
(g : (@linear_map R (finite_free_module R c) (finite_free_module R b) _ _ _)):
@is_linear_map R _ _ _ _ _ (f.1 ∘ g.1):=
{
add:=
begin
intros,
simp,
have H1: f.val (g.val (x) + g.val(y)) = f.val (g.val (x + y)),
rw[g.2.add],
rw[← H1],
rw[f.2.add],
end,
smul:=
begin
intros,
simp,
have H1: f.val (g.val (c_1 • x)) = f.val(c_1 • g.val(x)),
rw[g.2.smul],
rw[H1],
rw[f.2.smul],
end
}
theorem comp_equal_product_one {R : Type} [ring R] {a b c : nat}
(f : (@linear_map R (finite_free_module R b) (finite_free_module R a) _ _ _))
(g : (@linear_map R (finite_free_module R c) (finite_free_module R b) _ _ _)):
(@linear_map_to_matrix R _ c a (⟨ f.1 ∘ g.1, comp_is_linear_map f g⟩))
= @matrix.mul _ _ b c a (@linear_map_to_matrix R _ c b g ) (@linear_map_to_matrix R _ b a f) :=
begin
unfold linear_map_to_matrix,
unfold matrix.mul,
funext,
simp,
conv
begin
to_lhs,
rw [span (g.1 (e R c i))],
end,
rw [is_linear_map.sum f.2],
rw [apply_function_to_sum ],
congr,
funext,
show f.1 ((g.1 (e R c i) K) • (e R b K)) j = _,
rw [is_linear_map.smul f.2],
refl,
end
theorem comp_equal_product_two {R : Type} [ring R] {a b c : nat}
(M : matrix R b a) (N : matrix R c b):
@matrix_to_linear_map _ _ _ _ (@matrix.mul _ _ b c a N M) =
⟨(@matrix_to_linear_map _ _ _ _ M).1 ∘ (@matrix_to_linear_map _ _ _ _ N).1,
comp_is_linear_map (@matrix_to_linear_map _ _ _ _ M) (@matrix_to_linear_map _ _ _ _ N)⟩ :=
begin
unfold matrix_to_linear_map,
funext,
apply subtype.eq,
simp,
unfold matrix_to_map,
unfold matrix.mul,
funext,
simp,
conv in (v _ * finset.sum _ _)
begin
rw [finset.mul_sum],
end,
simp only [ finset.sum_mul],
conv
begin
to_lhs,
rw [finset.sum_comm],
end,
congr,
funext,
congr,
funext,
rw [mul_assoc],
end
-- R-module structure on Hom(R^b, R^a)
theorem left_inv {R : Type} [ring R] {a b : nat} : left_inverse (@linear_map_to_matrix R _ a b ) (matrix_to_linear_map) :=
begin
unfold function.left_inverse,
intros,
exact equiv_two x,
end
theorem right_inv {R : Type} [ring R] {a b : nat} : right_inverse (@linear_map_to_matrix R _ a b ) (matrix_to_linear_map) :=
begin
unfold function.right_inverse,
unfold function.left_inverse,
intros,
apply subtype.eq,
dsimp,
exact equiv_one x,
end
instance keji {R : Type} [ring R] {a b : nat}: is_add_group_hom (@linear_map_to_matrix R _ a b):=
begin
exact is_add_group_hom_right_inv (injective_of_left_inverse left_inv ) right_inv,
end
def Hom {R : Type} [comm_ring R] {a b : nat} := {f: finite_free_module R a → finite_free_module R b // is_add_group_hom f}
def module_Hom {R: Type} [ring R] {a b : nat} (M : matrix R a b) :
@is_linear_map R _ _ _ _ _ (matrix_to_map M) :=
{ add:=
begin
exact is_add_group_hom.add _,
end,
smul:= smul_ _,
}
-- definition matrix_to_map {R : Type} [ring R] {a b : nat} (M : matrix R a b) :
-- (finite_free_module R a) → (finite_free_module R b) := λ v ,(λ i,finset.sum finset.univ (λ K, (v K) *M K i ) )
def vec_to_mat {R : Type} [ring R] {n : nat} (vc : vector R n) :
matrix R n 1 := λ I, λ J, vector.nth vc I
def mat_mul_vec {R : Type} [ring R] {n m : nat} (M : matrix R n m) (vc : vector R m) :
matrix R n 1 := @matrix.mul _ _ m n 1 M (vec_to_mat vc)
theorem mat_mat_vec_assoc {R : Type} [ring R] {a b c : nat} (M : matrix R a b)
(N : matrix R b c) (vc : vector R c) :
@matrix.mul _ _ b a 1 M (@mat_mul_vec _ _ b c N vc) =
@mat_mul_vec _ _ a c (@matrix.mul _ _ b a c M N) vc :=
begin
apply matrix.mul_assoc,
end
end map_matrix
namespace vector_space
variables {k : Type} {V : Type}
variable [field k]
variable (n : nat)
-- a basis v1,v2,...,vn of a fdvs V/k is just an isomorphism k^n -> V.
open map_matrix
-- helper function to get basis
def simp_fun (V : Type*) [vector_space k V] (n : ℕ) (lm : linear_map (finite_free_module k n) V) :
(fin n → V) :=
λ I, lm (e k n I)
def linear_map_to_vec (V : Type*) [vector_space k V] (n : ℕ) :
(linear_map (finite_free_module k n) V) → vector V n :=
λ lm, vector.of_fn (simp_fun V n lm)
def vec_to_map (V : Type*) [vector_space k V] (n : ℕ) (M : vector V n):
(finite_free_module k n) → V :=
λ sp, finset.sum finset.univ (λ K : fin n, (sp K) • (vector.nth M K))
instance vc_to_map_add_group (V : Type*) [vector_space k V] (n : ℕ) (M : vector V n) :
is_add_group_hom (@vec_to_map k _ _ _ n M) :=
⟨ begin
intros a b,
unfold vec_to_map,
show (finset.sum finset.univ (λ (K : fin n), (a K + b K) • vector.nth M K))=_,
conv in ((a _ + b _) • _)
begin
rw [add_smul],
end,
rw [← finset.sum_add_distrib],
end
⟩
theorem smul' (V : Type*) [vector_space k V] (n : ℕ) (M : vector V n) :
∀ (c : k) (x : finite_free_module k n), @vec_to_map k _ _ _ n M (smul c x) =
c • (@vec_to_map k _ _ _ n M x):=
begin
intros c x,
unfold vec_to_map,
funext,
unfold smul,
conv
begin
to_rhs,
rw [finset.smul_sum],
end,
congr,
funext,
rw [smul_smul],
end
def module_hom' (V : Type*) [vector_space k V] (n : ℕ) (M : vector V n) :
@is_linear_map _ _ _ _ _ _ (@vec_to_map k _ _ _ n M) :=
{
add:=
begin
exact is_add_group_hom.add _,
end,
smul:= @smul' _ _ _ _ _ _,
}
def vec_to_linear_map (V : Type*) [vector_space k V] (n : ℕ) (M : vector V n):
(linear_map (finite_free_module k n) V) :=
⟨ @vec_to_map k _ _ _ n M , @module_hom' _ _ _ _ n M⟩
lemma ext {α : Type*} {n : ℕ} : ∀ (v w : vector α n),
(∀ m : fin n, vector.nth v m = vector.nth w m) → v = w :=
λ ⟨v, hv⟩ ⟨w, hw⟩ h, subtype.eq (list.ext_le (by simp [hv, hw])
(λ m hm hn, h ⟨m, hv ▸ hm⟩))
def left_inv_ (V : Type*) [vector_space k V] (n : ℕ) (M : vector V n):
(@linear_map_to_vec k _ _ _ n) (@vec_to_linear_map k _ _ _ n M) = M :=
begin
unfold vec_to_linear_map,
unfold linear_map_to_vec,
unfold vec_to_map,
dsimp,
unfold simp_fun,
apply ext,
assume m,
rw vector.nth_of_fn,
unfold_coes, dsimp,
rw [← @finset.sum_single _ _ _ _ (λ (K : fin n), e k n m K • vector.nth M K) m ],
simp,
unfold e,
split_ifs,
exact one_smul,
contradiction,
intros,
simp,
unfold e,
split_ifs,
contradiction,
exact zero_smul,
end
def right_inv_ (V : Type*) [vector_space k V] (n : ℕ) (lm : linear_map (finite_free_module k n) V) :
@vec_to_linear_map k _ _ _ n (@linear_map_to_vec k _ _ _ n lm) = lm :=
begin
unfold vec_to_linear_map,
unfold linear_map_to_vec,
unfold vec_to_map,
apply subtype.eq,
dsimp,
funext,
simp,
unfold simp_fun,
unfold_coes,
conv
begin
to_rhs,
rw[span sp],
end,
rw [is_linear_map.sum lm.2],
congr,
funext,
rw[← is_linear_map.smul lm.2],
refl,
end
def n_tuples_eq_linear_maps (V : Type*) [vector_space k V] (n : ℕ) :
equiv (vector V n) (linear_map (finite_free_module k n) V) :=
{ to_fun := vec_to_linear_map V n,
inv_fun := linear_map_to_vec V n,
left_inv := left_inv_ V n,
right_inv := right_inv_ V n,
}
end vector_space |
012bee75135792b78b907253bd49ad095db56a01 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/data/real/basic.lean | ab7d4944d915492a88f09935d4d51b1e742adbf3 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 25,710 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn
The (classical) real numbers ℝ. This is a direct construction
from Cauchy sequences.
-/
import order.conditionally_complete_lattice data.real.cau_seq_completion
algebra.archimedean order.bounds
def real := @cau_seq.completion.Cauchy ℚ _ _ _ abs _
notation `ℝ` := real
namespace real
open cau_seq cau_seq.completion
variables {x y : ℝ}
def of_rat (x : ℚ) : ℝ := of_rat x
def mk (x : cau_seq ℚ abs) : ℝ := cau_seq.completion.mk x
def comm_ring_aux : comm_ring ℝ := cau_seq.completion.comm_ring
instance : comm_ring ℝ := { ..comm_ring_aux }
/- Extra instances to short-circuit type class resolution -/
instance : ring ℝ := by apply_instance
instance : comm_semiring ℝ := by apply_instance
instance : semiring ℝ := by apply_instance
instance : add_comm_group ℝ := by apply_instance
instance : add_group ℝ := by apply_instance
instance : add_comm_monoid ℝ := by apply_instance
instance : add_monoid ℝ := by apply_instance
instance : add_left_cancel_semigroup ℝ := by apply_instance
instance : add_right_cancel_semigroup ℝ := by apply_instance
instance : add_comm_semigroup ℝ := by apply_instance
instance : add_semigroup ℝ := by apply_instance
instance : comm_monoid ℝ := by apply_instance
instance : monoid ℝ := by apply_instance
instance : comm_semigroup ℝ := by apply_instance
instance : semigroup ℝ := by apply_instance
instance : inhabited ℝ := ⟨0⟩
theorem of_rat_sub (x y : ℚ) : of_rat (x - y) = of_rat x - of_rat y :=
congr_arg mk (const_sub _ _)
instance : has_lt ℝ :=
⟨λ x y, quotient.lift_on₂ x y (<) $
λ f₁ g₁ f₂ g₂ hf hg, propext $
⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg),
λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩⟩
@[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := iff.rfl
theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := mk_eq
theorem quotient_mk_eq_mk (f : cau_seq ℚ abs) : ⟦f⟧ = mk f := rfl
theorem mk_eq_mk {f : cau_seq ℚ abs} : cau_seq.completion.mk f = mk f := rfl
@[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f :=
iff_of_eq (congr_arg pos (sub_zero f))
protected def le (x y : ℝ) : Prop := x < y ∨ x = y
instance : has_le ℝ := ⟨real.le⟩
@[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g :=
or_congr iff.rfl quotient.eq
theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b :=
quotient.induction_on₃ a b c (λ f g h,
iff_of_eq (congr_arg pos $ by rw add_sub_add_left_eq_sub))
instance : linear_order ℝ :=
{ le := (≤), lt := (<),
le_refl := λ a, or.inr rfl,
le_trans := λ a b c, quotient.induction_on₃ a b c $
λ f g h, by simpa [quotient_mk_eq_mk] using le_trans,
lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $
λ f g, by simpa [quotient_mk_eq_mk] using lt_iff_le_not_le,
le_antisymm := λ a b, quotient.induction_on₂ a b $
λ f g, by simpa [mk_eq, quotient_mk_eq_mk] using @cau_seq.le_antisymm _ _ f g,
le_total := λ a b, quotient.induction_on₂ a b $
λ f g, by simpa [quotient_mk_eq_mk] using le_total f g }
instance : partial_order ℝ := by apply_instance
instance : preorder ℝ := by apply_instance
theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := const_lt
protected theorem zero_lt_one : (0 : ℝ) < 1 := of_rat_lt.2 zero_lt_one
protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b :=
quotient.induction_on₂ a b $ λ f g,
show pos (f - 0) → pos (g - 0) → pos (f * g - 0),
by simpa using cau_seq.mul_pos
instance : linear_ordered_comm_ring ℝ :=
{ add_le_add_left := λ a b h c,
(le_iff_le_iff_lt_iff_lt.2 $ real.add_lt_add_iff_left c).2 h,
zero_ne_one := ne_of_lt real.zero_lt_one,
mul_nonneg := λ a b a0 b0,
match a0, b0 with
| or.inl a0, or.inl b0 := le_of_lt (real.mul_pos a0 b0)
| or.inr a0, _ := by simp [a0.symm]
| _, or.inr b0 := by simp [b0.symm]
end,
mul_pos := @real.mul_pos,
zero_lt_one := real.zero_lt_one,
add_lt_add_left := λ a b h c, (real.add_lt_add_iff_left c).2 h,
..real.comm_ring, ..real.linear_order }
/- Extra instances to short-circuit type class resolution -/
instance : linear_ordered_ring ℝ := by apply_instance
instance : ordered_ring ℝ := by apply_instance
instance : linear_ordered_semiring ℝ := by apply_instance
instance : ordered_semiring ℝ := by apply_instance
instance : ordered_comm_group ℝ := by apply_instance
instance : ordered_cancel_comm_monoid ℝ := by apply_instance
instance : ordered_comm_monoid ℝ := by apply_instance
instance : domain ℝ := by apply_instance
local attribute [instance] classical.prop_decidable
noncomputable instance : discrete_linear_ordered_field ℝ :=
{ decidable_le := by apply_instance,
..real.linear_ordered_comm_ring,
..real.domain,
..cau_seq.completion.discrete_field }
/- Extra instances to short-circuit type class resolution -/
noncomputable instance : linear_ordered_field ℝ := by apply_instance
noncomputable instance : decidable_linear_ordered_comm_ring ℝ := by apply_instance
noncomputable instance : decidable_linear_ordered_semiring ℝ := by apply_instance
noncomputable instance : decidable_linear_ordered_comm_group ℝ := by apply_instance
noncomputable instance discrete_field : discrete_field ℝ := by apply_instance
noncomputable instance : field ℝ := by apply_instance
noncomputable instance : division_ring ℝ := by apply_instance
noncomputable instance : integral_domain ℝ := by apply_instance
noncomputable instance : nonzero_comm_ring ℝ := by apply_instance
noncomputable instance : decidable_linear_order ℝ := by apply_instance
noncomputable instance : lattice.distrib_lattice ℝ := by apply_instance
noncomputable instance : lattice.lattice ℝ := by apply_instance
noncomputable instance : lattice.semilattice_inf ℝ := by apply_instance
noncomputable instance : lattice.semilattice_sup ℝ := by apply_instance
noncomputable instance : lattice.has_inf ℝ := by apply_instance
noncomputable instance : lattice.has_sup ℝ := by apply_instance
lemma le_of_forall_epsilon_le {a b : real} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b :=
le_of_forall_le_of_dense $ assume x hxb,
calc a ≤ b + (x - b) : h (x-b) $ sub_pos.2 hxb
... = x : by rw [add_comm]; simp
open rat
@[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x :=
eq_cast of_rat rfl of_rat_add of_rat_mul
theorem le_mk_of_forall_le {f : cau_seq ℚ abs} :
(∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f :=
quotient.induction_on x $ λ g h, le_of_not_lt $
λ ⟨K, K0, hK⟩,
let ⟨i, H⟩ := exists_forall_ge_and h $
exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0) in
begin
apply not_lt_of_le (H _ (le_refl _)).1,
rw ← of_rat_eq_cast,
refine ⟨_, half_pos K0, i, λ j ij, _⟩,
have := add_le_add (H _ ij).2.1
(le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1),
rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this
end
theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} :
(∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) → mk f ≤ x
| ⟨i, H⟩ := by rw [← neg_le_neg_iff, ← mk_eq_mk, mk_neg]; exact
le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩
theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ}
(H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $
H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1,
sub_le.1 $ le_mk_of_forall_le $
H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩
instance : archimedean ℝ :=
archimedean_iff_rat_le.2 $ λ x, quotient.induction_on x $ λ f,
let ⟨M, M0, H⟩ := f.bounded' 0 in
⟨M, mk_le_of_forall_le ⟨0, λ i _,
rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩
/- mark `real` irreducible in order to prevent `auto_cases` unfolding reals,
since users rarely want to consider real numbers as Cauchy sequences.
Marking `comm_ring_aux` `irreducible` is done to ensure that there are no problems
with non definitionally equal instances, caused by making `real` irreducible-/
attribute [irreducible] real comm_ring_aux
noncomputable instance : floor_ring ℝ := archimedean.floor_ring _
theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) :=
⟨λ H ε ε0,
let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in
(H _ δ0).imp $ λ i hi j ij, lt_trans
(by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε,
λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $
λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩
theorem of_near (f : ℕ → ℚ) (x : ℝ)
(h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) :
∃ h', real.mk ⟨f, h'⟩ = x :=
⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h),
sub_eq_zero.1 $ abs_eq_zero.1 $
eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0,
mk_near_of_forall_near $
(h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩
theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧
∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub :=
int.exists_greatest_of_bdd
(let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h',
int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩)
(let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩)
theorem exists_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) →
∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y
| ⟨L, hL⟩ ⟨U, hU⟩ := begin
choose f hf using begin
refine λ d : ℕ, @int.exists_greatest_of_bdd
(λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _ _,
{ cases exists_int_gt U with k hk,
refine ⟨k * d, λ z h, _⟩,
rcases h with ⟨y, yS, hy⟩,
refine int.cast_le.1 (le_trans hy _),
simp,
exact mul_le_mul_of_nonneg_right
(le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) },
{ exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ }
end,
have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0,
let ⟨y, yS, hy⟩ := (hf n).1 in
⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩,
have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ),
{ intros n n0 y yS,
have := lt_of_lt_of_le (sub_one_lt_floor _)
(int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩),
simp [-sub_eq_add_neg],
rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel],
exact ne_of_gt (nat.cast_pos.2 n0) },
suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩,
refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ h, _⟩⟩,
{ refine le_of_forall_ge_of_dense (λ z xz, _),
cases exists_nat_gt (x - z)⁻¹ with K hK,
refine le_mk_of_forall_le ⟨K, λ n nK, _⟩,
replace xz := sub_pos.2 xz,
replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK),
have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos xz) hK),
refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS),
rwa [le_sub, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] },
{ exact mk_le_of_forall_le ⟨1, λ n n1,
let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h _ xS)⟩ },
intros ε ε0,
suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε,
{ refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩,
rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij },
intros j k ij ik,
replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij),
replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik),
have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) ij),
have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) ik),
rcases hf₁ _ j0 with ⟨y, yS, hy⟩,
refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _)
((inv_le ε0 (nat.cast_pos.2 k0)).1 ik),
simpa using sub_lt_iff_lt_add'.2
(lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS)
end
noncomputable def Sup (S : set ℝ) : ℝ :=
if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x)
then classical.some (exists_sup S h.1 h.2) else 0
theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x)
{y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y :=
by simp [Sup, h₁, h₂]; exact
classical.some_spec (exists_sup S h₁ h₂) y
theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x)
{y} : y < Sup S ↔ ∃ z ∈ S, y < z :=
by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y)
theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S :=
(Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS
theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub :=
(Sup_le S h₁ ⟨_, h₂⟩).2 h₂
protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) :
is_lub s (Sup s) :=
⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs,
λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩
noncomputable def Inf (S : set ℝ) : ℝ := -Sup {x | -x ∈ S}
theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y)
{y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z :=
begin
refine le_neg.trans ((Sup_le _ _ _).trans _),
{ cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ },
{ cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ },
split; intros H z hz,
{ exact neg_le_neg_iff.1 (H _ $ by simp [hz]) },
{ exact le_neg.2 (H _ hz) }
end
theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y)
{y} : Inf S < y ↔ ∃ z ∈ S, z < y :=
by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y)
theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x :=
(le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS
theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S :=
(le_Inf S h₁ ⟨_, h₂⟩).2 h₂
open lattice
noncomputable instance lattice : lattice ℝ := by apply_instance
noncomputable instance : conditionally_complete_linear_order ℝ :=
{ Sup := real.Sup,
Inf := real.Inf,
le_cSup :=
assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s),
show a ≤ Sup s,
from le_Sup s ‹bdd_above s› ‹a ∈ s›,
cSup_le :=
assume (s : set ℝ) (a : ℝ) (_ : s ≠ ∅) (H : ∀b∈s, b ≤ a),
show Sup s ≤ a,
from Sup_le_ub s (set.exists_mem_of_ne_empty ‹s ≠ ∅›) H,
cInf_le :=
assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s),
show Inf s ≤ a,
from Inf_le s ‹bdd_below s› ‹a ∈ s›,
le_cInf :=
assume (s : set ℝ) (a : ℝ) (_ : s ≠ ∅) (H : ∀b∈s, a ≤ b),
show a ≤ Inf s,
from lb_le_Inf s (set.exists_mem_of_ne_empty ‹s ≠ ∅›) H,
decidable_le := classical.dec_rel _,
..real.linear_order, ..real.lattice}
theorem Sup_empty : lattice.Sup (∅ : set ℝ) = 0 := dif_neg $ by simp
theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : lattice.Sup s = 0 :=
dif_neg $ assume h, hs h.2
theorem Inf_empty : lattice.Inf (∅ : set ℝ) = 0 :=
show Inf ∅ = 0, by simp [Inf]; exact Sup_empty
theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : lattice.Inf s = 0 :=
have bdd_above {x | -x ∈ s} → bdd_below s, from
assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb _ $ by simp [hxs]⟩,
have ¬ bdd_above {x | -x ∈ s}, from mt this hs,
neg_eq_zero.2 $ Sup_of_not_bdd_above $ this
theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x :=
begin
let S := {x : ℝ | const abs x < f},
have lb : ∃ x, x ∈ S := exists_lt f,
have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x :=
λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h,
have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub',
refine ⟨Sup S,
((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩,
{ rcases h with ⟨ε, ε0, i, ih⟩,
refine not_lt_of_le (Sup_le_ub S lb (ub' _ _))
((sub_lt_self_iff _).2 (half_pos ε0)),
refine ⟨_, half_pos ε0, i, λ j ij, _⟩,
rw [sub_apply, const_apply, sub_right_comm,
le_sub_iff_add_le, add_halves],
exact ih _ ij },
{ rcases h with ⟨ε, ε0, i, ih⟩,
refine not_lt_of_le (le_Sup S ub _)
((lt_add_iff_pos_left _).2 (half_pos ε0)),
refine ⟨_, half_pos ε0, i, λ j ij, _⟩,
rw [sub_apply, const_apply, add_comm, ← sub_sub,
le_sub_iff_add_le, add_halves],
exact ih _ ij }
end
noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩
theorem sqrt_exists : ∀ {x : ℝ}, 0 ≤ x → ∃ y, 0 ≤ y ∧ y * y = x :=
suffices H : ∀ {x : ℝ}, 0 < x → x ≤ 1 → ∃ y, 0 < y ∧ y * y = x, begin
intros x x0, cases x0,
cases le_total x 1 with x1 x1,
{ rcases H x0 x1 with ⟨y, y0, hy⟩,
exact ⟨y, le_of_lt y0, hy⟩ },
{ have := (inv_le_inv x0 zero_lt_one).2 x1,
rw inv_one at this,
rcases H (inv_pos x0) this with ⟨y, y0, hy⟩,
refine ⟨y⁻¹, le_of_lt (inv_pos y0), _⟩, rw [← mul_inv', hy, inv_inv'] },
{ exact ⟨0, by simp [x0.symm]⟩ }
end,
λ x x0 x1, begin
let S := {y | 0 < y ∧ y * y ≤ x},
have lb : x ∈ S := ⟨x0, by simpa using (mul_le_mul_right x0).2 x1⟩,
have ub : ∀ y ∈ S, (y:ℝ) ≤ 1,
{ intros y yS, cases yS with y0 yx,
refine (mul_self_le_mul_self_iff (le_of_lt y0) zero_le_one).2 _,
simpa using le_trans yx x1 },
have S0 : 0 < Sup S := lt_of_lt_of_le x0 (le_Sup _ ⟨_, ub⟩ lb),
refine ⟨Sup S, S0, le_antisymm (not_lt.1 $ λ h, _) (not_lt.1 $ λ h, _)⟩,
{ rw [← div_lt_iff S0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at h,
rcases h with ⟨y, ⟨y0, yx⟩, hy⟩,
rw [div_lt_iff S0, ← div_lt_iff' y0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at hy,
rcases hy with ⟨z, ⟨z0, zx⟩, hz⟩,
rw [div_lt_iff y0] at hz,
exact not_lt_of_lt
((mul_lt_mul_right y0).1 (lt_of_le_of_lt yx hz))
((mul_lt_mul_left z0).1 (lt_of_le_of_lt zx hz)) },
{ let s := Sup S, let y := s + (x - s * s) / 3,
replace h : 0 < x - s * s := sub_pos.2 h,
have _30 := bit1_pos zero_le_one,
have : s < y := (lt_add_iff_pos_right _).2 (div_pos h _30),
refine not_le_of_lt this (le_Sup S ⟨_, ub⟩ ⟨lt_trans S0 this, _⟩),
rw [add_mul_self_eq, add_assoc, ← le_sub_iff_add_le', ← add_mul,
← le_div_iff (div_pos h _30), div_div_cancel (ne_of_gt h)],
apply add_le_add,
{ simpa using (mul_le_mul_left (@two_pos ℝ _)).2 (Sup_le_ub _ ⟨_, lb⟩ ub) },
{ rw [div_le_one_iff_le _30],
refine le_trans (sub_le_self _ (mul_self_nonneg _)) (le_trans x1 _),
exact (le_add_iff_nonneg_left _).2 (le_of_lt two_pos) } }
end
def sqrt_aux (f : cau_seq ℚ abs) : ℕ → ℚ
| 0 := rat.mk_nat (f 0).num.to_nat.sqrt (f 0).denom.sqrt
| (n + 1) := let s := sqrt_aux n in max 0 $ (s + f (n+1) / s) / 2
theorem sqrt_aux_nonneg (f : cau_seq ℚ abs) : ∀ i : ℕ, 0 ≤ sqrt_aux f i
| 0 := by rw [sqrt_aux, mk_nat_eq, mk_eq_div];
apply div_nonneg'; exact int.cast_nonneg.2 (int.of_nat_nonneg _)
| (n + 1) := le_max_left _ _
/- TODO(Mario): finish the proof
theorem sqrt_aux_converges (f : cau_seq ℚ abs) : ∃ h x, 0 ≤ x ∧ x * x = max 0 (mk f) ∧
mk ⟨sqrt_aux f, h⟩ = x :=
begin
rcases sqrt_exists (le_max_left 0 (mk f)) with ⟨x, x0, hx⟩,
suffices : ∃ h, mk ⟨sqrt_aux f, h⟩ = x,
{ exact this.imp (λ h e, ⟨x, x0, hx, e⟩) },
apply of_near,
suffices : ∃ δ > 0, ∀ i, abs (↑(sqrt_aux f i) - x) < δ / 2 ^ i,
{ rcases this with ⟨δ, δ0, hδ⟩,
intros,
}
end -/
noncomputable def sqrt (x : ℝ) : ℝ :=
classical.some (sqrt_exists (le_max_left 0 x))
/-quotient.lift_on x
(λ f, mk ⟨sqrt_aux f, (sqrt_aux_converges f).fst⟩)
(λ f g e, begin
rcases sqrt_aux_converges f with ⟨hf, x, x0, xf, xs⟩,
rcases sqrt_aux_converges g with ⟨hg, y, y0, yg, ys⟩,
refine xs.trans (eq.trans _ ys.symm),
rw [← @mul_self_inj_of_nonneg ℝ _ x y x0 y0, xf, yg],
congr' 1, exact quotient.sound e
end)-/
theorem sqrt_prop (x : ℝ) : 0 ≤ sqrt x ∧ sqrt x * sqrt x = max 0 x :=
classical.some_spec (sqrt_exists (le_max_left 0 x))
/-quotient.induction_on x $ λ f,
by rcases sqrt_aux_converges f with ⟨hf, _, x0, xf, rfl⟩; exact ⟨x0, xf⟩-/
theorem sqrt_eq_zero_of_nonpos (h : x ≤ 0) : sqrt x = 0 :=
eq_zero_of_mul_self_eq_zero $ (sqrt_prop x).2.trans $ max_eq_left h
theorem sqrt_nonneg (x : ℝ) : 0 ≤ sqrt x := (sqrt_prop x).1
@[simp] theorem mul_self_sqrt (h : 0 ≤ x) : sqrt x * sqrt x = x :=
(sqrt_prop x).2.trans (max_eq_right h)
@[simp] theorem sqrt_mul_self (h : 0 ≤ x) : sqrt (x * x) = x :=
(mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _))
theorem sqrt_eq_iff_mul_self_eq (hx : 0 ≤ x) (hy : 0 ≤ y) :
sqrt x = y ↔ y * y = x :=
⟨λ h, by rw [← h, mul_self_sqrt hx],
λ h, by rw [← h, sqrt_mul_self hy]⟩
@[simp] theorem sqr_sqrt (h : 0 ≤ x) : sqrt x ^ 2 = x :=
by rw [pow_two, mul_self_sqrt h]
@[simp] theorem sqrt_sqr (h : 0 ≤ x) : sqrt (x ^ 2) = x :=
by rw [pow_two, sqrt_mul_self h]
theorem sqrt_eq_iff_sqr_eq (hx : 0 ≤ x) (hy : 0 ≤ y) :
sqrt x = y ↔ y ^ 2 = x :=
by rw [pow_two, sqrt_eq_iff_mul_self_eq hx hy]
theorem sqrt_mul_self_eq_abs (x : ℝ) : sqrt (x * x) = abs x :=
(le_total 0 x).elim
(λ h, (sqrt_mul_self h).trans (abs_of_nonneg h).symm)
(λ h, by rw [← neg_mul_neg,
sqrt_mul_self (neg_nonneg.2 h), abs_of_nonpos h])
theorem sqrt_sqr_eq_abs (x : ℝ) : sqrt (x ^ 2) = abs x :=
by rw [pow_two, sqrt_mul_self_eq_abs]
@[simp] theorem sqrt_zero : sqrt 0 = 0 :=
by simpa using sqrt_mul_self (le_refl _)
@[simp] theorem sqrt_one : sqrt 1 = 1 :=
by simpa using sqrt_mul_self zero_le_one
@[simp] theorem sqrt_le (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x ≤ sqrt y ↔ x ≤ y :=
by rw [mul_self_le_mul_self_iff (sqrt_nonneg _) (sqrt_nonneg _),
mul_self_sqrt hx, mul_self_sqrt hy]
@[simp] theorem sqrt_lt (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x < sqrt y ↔ x < y :=
lt_iff_lt_of_le_iff_le (sqrt_le hy hx)
lemma sqrt_le_sqrt (h : x ≤ y) : sqrt x ≤ sqrt y :=
begin
rw [mul_self_le_mul_self_iff (sqrt_nonneg _) (sqrt_nonneg _), (sqrt_prop _).2, (sqrt_prop _).2],
exact max_le_max (le_refl _) h
end
lemma sqrt_le_left (hy : 0 ≤ y) : sqrt x ≤ y ↔ x ≤ y ^ 2 :=
begin
rw [mul_self_le_mul_self_iff (sqrt_nonneg _) hy, pow_two],
cases le_total 0 x with hx hx,
{ rw [mul_self_sqrt hx] },
{ have h1 : 0 ≤ y * y := mul_nonneg hy hy,
have h2 : x ≤ y * y := le_trans hx h1,
simp [sqrt_eq_zero_of_nonpos, hx, h1, h2] }
end
/- note: if you want to conclude `x ≤ sqrt y`, then use `le_sqrt_of_sqr_le`.
if you have `x > 0`, consider using `le_sqrt'` -/
lemma le_sqrt (hx : 0 ≤ x) (hy : 0 ≤ y) : x ≤ sqrt y ↔ x ^ 2 ≤ y :=
by rw [mul_self_le_mul_self_iff hx (sqrt_nonneg _), pow_two, mul_self_sqrt hy]
lemma le_sqrt' (hx : 0 < x) : x ≤ sqrt y ↔ x ^ 2 ≤ y :=
begin
rw [mul_self_le_mul_self_iff (le_of_lt hx) (sqrt_nonneg _), pow_two],
cases le_total 0 y with hy hy,
{ rw [mul_self_sqrt hy] },
{ have h1 : 0 < x * x := mul_pos hx hx,
have h2 : ¬x * x ≤ y := not_le_of_lt (lt_of_le_of_lt hy h1),
simp [sqrt_eq_zero_of_nonpos, hy, h1, h2] }
end
lemma le_sqrt_of_sqr_le (h : x ^ 2 ≤ y) : x ≤ sqrt y :=
begin
cases lt_or_ge 0 x with hx hx,
{ rwa [le_sqrt' hx] },
{ exact le_trans hx (sqrt_nonneg y) }
end
@[simp] theorem sqrt_inj (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = sqrt y ↔ x = y :=
by simp [le_antisymm_iff, hx, hy]
@[simp] theorem sqrt_eq_zero (h : 0 ≤ x) : sqrt x = 0 ↔ x = 0 :=
by simpa using sqrt_inj h (le_refl _)
theorem sqrt_eq_zero' : sqrt x = 0 ↔ x ≤ 0 :=
(le_total x 0).elim
(λ h, by simp [h, sqrt_eq_zero_of_nonpos])
(λ h, by simp [h]; simp [le_antisymm_iff, h])
@[simp] theorem sqrt_pos : 0 < sqrt x ↔ 0 < x :=
lt_iff_lt_of_le_iff_le (iff.trans
(by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero')
@[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≤ y) : sqrt (x * y) = sqrt x * sqrt y :=
begin
cases le_total 0 x with hx hx,
{ refine (mul_self_inj_of_nonneg _ (mul_nonneg _ _)).1 _; try {apply sqrt_nonneg},
rw [mul_self_sqrt (mul_nonneg hx hy), mul_assoc,
mul_left_comm (sqrt y), mul_self_sqrt hy, ← mul_assoc, mul_self_sqrt hx] },
{ rw [sqrt_eq_zero'.2 (mul_nonpos_of_nonpos_of_nonneg hx hy),
sqrt_eq_zero'.2 hx, zero_mul] }
end
@[simp] theorem sqrt_mul (hx : 0 ≤ x) (y : ℝ) : sqrt (x * y) = sqrt x * sqrt y :=
by rw [mul_comm, sqrt_mul' _ hx, mul_comm]
@[simp] theorem sqrt_inv (x : ℝ) : sqrt x⁻¹ = (sqrt x)⁻¹ :=
(le_or_lt x 0).elim
(λ h, by simp [sqrt_eq_zero'.2, inv_nonpos, h])
(λ h, by rw [
← mul_self_inj_of_nonneg (sqrt_nonneg _) (le_of_lt $ inv_pos $ sqrt_pos.2 h),
mul_self_sqrt (le_of_lt $ inv_pos h), ← mul_inv', mul_self_sqrt (le_of_lt h)])
@[simp] theorem sqrt_div (hx : 0 ≤ x) (y : ℝ) : sqrt (x / y) = sqrt x / sqrt y :=
by rw [division_def, sqrt_mul hx, sqrt_inv]; refl
attribute [irreducible] real.le
end real
|
01f7a21c8ba377f7e50ceadb5286cd379abce4dd | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /src/Lean/Elab/Command.lean | c5847e00c6470b4c8d18cfe3f38078cf5d559828 | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 18,034 | 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.Parser.Command
import Lean.ResolveName
import Lean.Meta.Reduce
import Lean.Elab.Log
import Lean.Elab.Term
import Lean.Elab.Binders
import Lean.Elab.SyntheticMVars
import Lean.Elab.DeclModifiers
import Lean.Elab.InfoTree
import Lean.Elab.Open
import Lean.Elab.SetOption
namespace Lean.Elab.Command
structure Scope where
header : String
opts : Options := {}
currNamespace : Name := Name.anonymous
openDecls : List OpenDecl := []
levelNames : List Name := []
/-- section variables as `bracketedBinder`s -/
varDecls : Array Syntax := #[]
/-- Globally unique internal identifiers for the `varDecls` -/
varUIds : Array Name := #[]
deriving Inhabited
structure State where
env : Environment
messages : MessageLog := {}
scopes : List Scope := [{ header := "" }]
nextMacroScope : Nat := firstFrontendMacroScope + 1
maxRecDepth : Nat
nextInstIdx : Nat := 1 -- for generating anonymous instance names
ngen : NameGenerator := {}
infoState : InfoState := {}
traceState : TraceState := {}
deriving Inhabited
structure Context where
fileName : String
fileMap : FileMap
currRecDepth : Nat := 0
cmdPos : String.Pos := 0
macroStack : MacroStack := []
currMacroScope : MacroScope := firstFrontendMacroScope
ref : Syntax := Syntax.missing
abbrev CommandElabCoreM (ε) := ReaderT Context $ StateRefT State $ EIO ε
abbrev CommandElabM := CommandElabCoreM Exception
abbrev CommandElab := Syntax → CommandElabM Unit
abbrev Linter := Syntax → CommandElabM Unit
-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the
-- whole monad stack at every use site. May eventually be covered by `deriving`.
instance : Monad CommandElabM := { inferInstanceAs (Monad CommandElabM) with }
def mkState (env : Environment) (messages : MessageLog := {}) (opts : Options := {}) : State := {
env := env
messages := messages
scopes := [{ header := "", opts := opts }]
maxRecDepth := maxRecDepth.get opts
}
/- Linters should be loadable as plugins, so store in a global IO ref instead of an attribute managed by the
environment (which only contains `import`ed objects). -/
builtin_initialize lintersRef : IO.Ref (Array Linter) ← IO.mkRef #[]
def addLinter (l : Linter) : IO Unit := do
let ls ← lintersRef.get
lintersRef.set (ls.push l)
instance : MonadInfoTree CommandElabM where
getInfoState := return (← get).infoState
modifyInfoState f := modify fun s => { s with infoState := f s.infoState }
instance : MonadEnv CommandElabM where
getEnv := do pure (← get).env
modifyEnv f := modify fun s => { s with env := f s.env }
instance : MonadOptions CommandElabM where
getOptions := do pure (← get).scopes.head!.opts
protected def getRef : CommandElabM Syntax :=
return (← read).ref
instance : AddMessageContext CommandElabM where
addMessageContext := addMessageContextPartial
instance : MonadRef CommandElabM where
getRef := Command.getRef
withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x
instance : MonadTrace CommandElabM where
getTraceState := return (← get).traceState
modifyTraceState f := modify fun s => { s with traceState := f s.traceState }
instance : AddErrorMessageContext CommandElabM where
add ref msg := do
let ctx ← read
let ref := getBetterRef ref ctx.macroStack
let msg ← addMessageContext msg
let msg ← addMacroStack msg ctx.macroStack
return (ref, msg)
def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message :=
mkMessageCore ctx.fileName ctx.fileMap msgData severity (ref.getPos?.getD ctx.cmdPos)
private def mkCoreContext (ctx : Context) (s : State) (heartbeats : Nat) : Core.Context :=
let scope := s.scopes.head!
{ options := scope.opts
currRecDepth := ctx.currRecDepth
maxRecDepth := s.maxRecDepth
ref := ctx.ref
currNamespace := scope.currNamespace
openDecls := scope.openDecls
initHeartbeats := heartbeats }
def liftCoreM {α} (x : CoreM α) : CommandElabM α := do
let s ← get
let ctx ← read
let heartbeats ← IO.getNumHeartbeats (ε := Exception)
let Eα := Except Exception α
let x : CoreM Eα := try let a ← x; pure <| Except.ok a catch ex => pure <| Except.error ex
let x : EIO Exception (Eα × Core.State) := (ReaderT.run x (mkCoreContext ctx s heartbeats)).run { env := s.env, ngen := s.ngen }
let (ea, coreS) ← liftM x
modify fun s => { s with env := coreS.env, ngen := coreS.ngen }
match ea with
| Except.ok a => pure a
| Except.error e => throw e
private def ioErrorToMessage (ctx : Context) (ref : Syntax) (err : IO.Error) : Message :=
let ref := getBetterRef ref ctx.macroStack
mkMessageAux ctx ref (toString err) MessageSeverity.error
@[inline] def liftEIO {α} (x : EIO Exception α) : CommandElabM α := liftM x
@[inline] def liftIO {α} (x : IO α) : CommandElabM α := do
let ctx ← read
IO.toEIO (fun (ex : IO.Error) => Exception.error ctx.ref ex.toString) x
instance : MonadLiftT IO CommandElabM where
monadLift := liftIO
def getScope : CommandElabM Scope := do pure (← get).scopes.head!
instance : MonadResolveName CommandElabM where
getCurrNamespace := return (← getScope).currNamespace
getOpenDecls := return (← getScope).openDecls
instance : MonadLog CommandElabM where
getRef := getRef
getFileMap := return (← read).fileMap
getFileName := return (← read).fileName
logMessage msg := do
let currNamespace ← getCurrNamespace
let openDecls ← getOpenDecls
let msg := { msg with data := MessageData.withNamingContext { currNamespace := currNamespace, openDecls := openDecls } msg.data }
modify fun s => { s with messages := s.messages.add msg }
def runLinters (stx : Syntax) : CommandElabM Unit := do
let linters ← lintersRef.get
unless linters.isEmpty do
for linter in linters do
let savedState ← get
try
linter stx
catch ex =>
logException ex
finally
modify fun s => { savedState with messages := s.messages }
protected def getCurrMacroScope : CommandElabM Nat := do pure (← read).currMacroScope
protected def getMainModule : CommandElabM Name := do pure (← getEnv).mainModule
protected def withFreshMacroScope {α} (x : CommandElabM α) : CommandElabM α := do
let fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }))
withReader (fun ctx => { ctx with currMacroScope := fresh }) x
instance : MonadQuotation CommandElabM where
getCurrMacroScope := Command.getCurrMacroScope
getMainModule := Command.getMainModule
withFreshMacroScope := Command.withFreshMacroScope
unsafe def mkCommandElabAttributeUnsafe : IO (KeyedDeclsAttribute CommandElab) :=
mkElabAttribute CommandElab `Lean.Elab.Command.commandElabAttribute `builtinCommandElab `commandElab `Lean.Parser.Command `Lean.Elab.Command.CommandElab "command"
@[implementedBy mkCommandElabAttributeUnsafe]
constant mkCommandElabAttribute : IO (KeyedDeclsAttribute CommandElab)
builtin_initialize commandElabAttribute : KeyedDeclsAttribute CommandElab ← mkCommandElabAttribute
private def addTraceAsMessagesCore (ctx : Context) (log : MessageLog) (traceState : TraceState) : MessageLog :=
traceState.traces.foldl (init := log) fun (log : MessageLog) traceElem =>
let ref := replaceRef traceElem.ref ctx.ref;
let pos := ref.getPos?.getD 0;
log.add (mkMessageCore ctx.fileName ctx.fileMap traceElem.msg MessageSeverity.information pos)
private def addTraceAsMessages : CommandElabM Unit := do
let ctx ← read
modify fun s => { s with
messages := addTraceAsMessagesCore ctx s.messages s.traceState
traceState.traces := {}
}
private def mkInfoTree (elaborator : Name) (stx : Syntax) (trees : Std.PersistentArray InfoTree) : CommandElabM InfoTree := do
let ctx ← read
let s ← get
let scope := s.scopes.head!
let tree := InfoTree.node (Info.ofCommandInfo { elaborator, stx }) trees
return InfoTree.context {
env := s.env, fileMap := ctx.fileMap, mctx := {}, currNamespace := scope.currNamespace, openDecls := scope.openDecls, options := scope.opts
} tree
private def elabCommandUsing (s : State) (stx : Syntax) : List (KeyedDeclsAttribute.AttributeEntry CommandElab) → CommandElabM Unit
| [] => throwError "unexpected syntax{indentD stx}"
| (elabFn::elabFns) =>
catchInternalId unsupportedSyntaxExceptionId
(withInfoTreeContext (mkInfoTree := mkInfoTree elabFn.decl stx) <| elabFn.value stx)
(fun _ => do set s; elabCommandUsing s stx elabFns)
/- Elaborate `x` with `stx` on the macro stack -/
def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : CommandElabM α) : CommandElabM α :=
withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x
instance : MonadMacroAdapter CommandElabM where
getCurrMacroScope := getCurrMacroScope
getNextMacroScope := return (← get).nextMacroScope
setNextMacroScope next := modify fun s => { s with nextMacroScope := next }
instance : MonadRecDepth CommandElabM where
withRecDepth d x := withReader (fun ctx => { ctx with currRecDepth := d }) x
getRecDepth := return (← read).currRecDepth
getMaxRecDepth := return (← get).maxRecDepth
register_builtin_option showPartialSyntaxErrors : Bool := {
defValue := false
descr := "show elaboration errors from partial syntax trees (i.e. after parser recovery)"
}
def withLogging (x : CommandElabM Unit) : CommandElabM Unit := do
try
x
catch ex => match ex with
| Exception.error _ _ => logException ex
| Exception.internal id _ =>
if isAbortExceptionId id then
pure ()
else
let idName ← liftIO <| id.getName;
logError m!"internal exception {idName}"
builtin_initialize registerTraceClass `Elab.command
partial def elabCommand (stx : Syntax) : CommandElabM Unit := do
withLogging <| withRef stx <| withIncRecDepth <| withFreshMacroScope do
match stx with
| Syntax.node k args =>
if k == nullKind then
-- list of commands => elaborate in order
-- The parser will only ever return a single command at a time, but syntax quotations can return multiple ones
args.forM elabCommand
else do
trace `Elab.command fun _ => stx;
let s ← get
match (← liftMacroM <| expandMacroImpl? s.env stx) with
| some (decl, stxNew) =>
withInfoTreeContext (mkInfoTree := mkInfoTree decl stx) do
withMacroExpansion stx stxNew do
elabCommand stxNew
| _ =>
match commandElabAttribute.getEntries s.env k with
| [] => throwError "elaboration function for '{k}' has not been implemented"
| elabFns => elabCommandUsing s stx elabFns
| _ => throwError "unexpected command"
/--
`elabCommand` wrapper that should be used for the initial invocation, not for recursive calls after
macro expansion etc.
-/
def elabCommandTopLevel (stx : Syntax) : CommandElabM Unit := withRef stx do
let initMsgs ← modifyGet fun st => (st.messages, { st with messages := {} })
let initInfoTrees ← getResetInfoTrees
withLogging do
runLinters stx
-- We should *not* factor out `elabCommand`'s `withLogging` to here since it would make its error
-- recovery more coarse. In particular, If `c` in `set_option ... in $c` fails, the remaining
-- `end` command of the `in` macro would be skipped and the option would be leaked to the outside!
elabCommand stx
-- note the order: first process current messages & info trees, then add back old messages & trees,
-- then convert new traces to messages
let mut msgs ← (← get).messages
-- `stx.hasMissing` should imply `initMsgs.hasErrors`, but the latter should be cheaper to check in general
if !showPartialSyntaxErrors.get (← getOptions) && initMsgs.hasErrors && stx.hasMissing then
-- discard elaboration errors, except for a few important and unlikely misleading ones, on parse error
msgs := ⟨msgs.msgs.filter fun msg =>
msg.data.hasTag `Elab.synthPlaceholder || msg.data.hasTag `Tactic.unsolvedGoals⟩
for tree in (← getInfoTrees) do
trace[Elab.info] (← tree.format)
modify fun st => { st with
messages := initMsgs ++ msgs
infoState := { st.infoState with trees := initInfoTrees ++ st.infoState.trees }
}
addTraceAsMessages
/-- Adapt a syntax transformation to a regular, command-producing elaborator. -/
def adaptExpander (exp : Syntax → CommandElabM Syntax) : CommandElab := fun stx => do
let stx' ← exp stx
withMacroExpansion stx stx' <| elabCommand stx'
private def getVarDecls (s : State) : Array Syntax :=
s.scopes.head!.varDecls
instance {α} : Inhabited (CommandElabM α) where
default := throw arbitrary
private def mkMetaContext : Meta.Context := {
config := { foApprox := true, ctxApprox := true, quasiPatternApprox := true }
}
def getBracketedBinderIds : Syntax → Array Name
| `(bracketedBinder|($ids* $[: $ty?]? $(annot?)?)) => ids.map Syntax.getId
| `(bracketedBinder|{$ids* $[: $ty?]?}) => ids.map Syntax.getId
| `(bracketedBinder|[$id : $ty]) => #[id.getId]
| `(bracketedBinder|[$ty]) => #[Name.anonymous]
| _ => #[]
private def mkTermContext (ctx : Context) (s : State) (declName? : Option Name) : Term.Context := do
let scope := s.scopes.head!
let mut sectionVars := {}
for id in scope.varDecls.concatMap getBracketedBinderIds, uid in scope.varUIds do
sectionVars := sectionVars.insert id uid
{ macroStack := ctx.macroStack
fileName := ctx.fileName
fileMap := ctx.fileMap
currMacroScope := ctx.currMacroScope
declName? := declName?
sectionVars := sectionVars }
private def mkTermState (scope : Scope) (s : State) : Term.State := {
messages := {}
levelNames := scope.levelNames
infoState.enabled := s.infoState.enabled
}
def liftTermElabM {α} (declName? : Option Name) (x : TermElabM α) : CommandElabM α := do
let ctx ← read
let s ← get
let heartbeats ← IO.getNumHeartbeats (ε := Exception)
-- dbg_trace "heartbeats: {heartbeats}"
let scope := s.scopes.head!
-- We execute `x` with an empty message log. Thus, `x` cannot modify/view messages produced by previous commands.
-- This is useful for implementing `runTermElabM` where we use `Term.resetMessageLog`
let x : TermElabM _ := withSaveInfoContext x
let x : MetaM _ := (observing x).run (mkTermContext ctx s declName?) (mkTermState scope s)
let x : CoreM _ := x.run mkMetaContext {}
let x : EIO _ _ := x.run (mkCoreContext ctx s heartbeats) { env := s.env, ngen := s.ngen, nextMacroScope := s.nextMacroScope }
let (((ea, termS), metaS), coreS) ← liftEIO x
modify fun s => { s with
env := coreS.env
messages := addTraceAsMessagesCore ctx (s.messages ++ termS.messages) coreS.traceState
nextMacroScope := coreS.nextMacroScope
ngen := coreS.ngen
infoState.trees := s.infoState.trees.append termS.infoState.trees
}
match ea with
| Except.ok a => pure a
| Except.error ex => throw ex
@[inline] def runTermElabM {α} (declName? : Option Name) (elabFn : Array Expr → TermElabM α) : CommandElabM α := do
let scope ← getScope
liftTermElabM declName? <|
Term.withAutoBoundImplicit <|
Term.elabBinders scope.varDecls fun xs => do
-- We need to synthesize postponed terms because this is a checkpoint for the auto-bound implicit feature
-- If we don't use this checkpoint here, then auto-bound implicits in the postponed terms will not be handled correctly.
Term.synthesizeSyntheticMVarsNoPostponing
let mut sectionFVars := {}
for uid in scope.varUIds, x in xs do
sectionFVars := sectionFVars.insert uid x
withReader ({ · with sectionFVars := sectionFVars }) do
-- We don't want to store messages produced when elaborating `(getVarDecls s)` because they have already been saved when we elaborated the `variable`(s) command.
-- So, we use `Term.resetMessageLog`.
Term.resetMessageLog
let xs ← Term.addAutoBoundImplicits xs
Term.withoutAutoBoundImplicit <| elabFn xs
@[inline] def catchExceptions (x : CommandElabM Unit) : CommandElabCoreM Empty Unit := fun ctx ref =>
EIO.catchExceptions (withLogging x ctx ref) (fun _ => pure ())
private def liftAttrM {α} (x : AttrM α) : CommandElabM α := do
liftCoreM x
def getScopes : CommandElabM (List Scope) := do
pure (← get).scopes
def modifyScope (f : Scope → Scope) : CommandElabM Unit :=
modify fun s => { s with
scopes := match s.scopes with
| h::t => f h :: t
| [] => unreachable!
}
def getLevelNames : CommandElabM (List Name) :=
return (← getScope).levelNames
def addUnivLevel (idStx : Syntax) : CommandElabM Unit := withRef idStx do
let id := idStx.getId
let levelNames ← getLevelNames
if levelNames.elem id then
throwAlreadyDeclaredUniverseLevel id
else
modifyScope fun scope => { scope with levelNames := id :: scope.levelNames }
def expandDeclId (declId : Syntax) (modifiers : Modifiers) : CommandElabM ExpandDeclIdResult := do
let currNamespace ← getCurrNamespace
let currLevelNames ← getLevelNames
Lean.Elab.expandDeclId currNamespace currLevelNames declId modifiers
end Elab.Command
export Elab.Command (Linter addLinter)
end Lean
|
93801fa3c999c75cf3a618702be603f13a0f9e5d | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/linear_algebra/direct_sum/tensor_product.lean | feeddfb145064c81d756373ab6011c08ab333c0e | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 2,420 | 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 linear_algebra.tensor_product
import linear_algebra.direct_sum_module
/-!
# Tensor products of direct sums
This file shows that taking `tensor_product`s commutes with taking `direct_sum`s in both arguments.
-/
section ring
namespace tensor_product
open_locale tensor_product
open_locale direct_sum
open linear_map
variables (R : Type*) [comm_ring R]
variables (ι₁ : Type*) (ι₂ : Type*)
variables [decidable_eq ι₁] [decidable_eq ι₂]
variables (M₁ : ι₁ → Type*) (M₂ : ι₂ → Type*)
variables [Π i₁, add_comm_group (M₁ i₁)] [Π i₂, add_comm_group (M₂ i₂)]
variables [Π i₁, module R (M₁ i₁)] [Π i₂, module R (M₂ i₂)]
/-- The linear equivalence `(⨁ i₁, M₁ i₁) ⊗ (⨁ i₂, M₂ i₂) ≃ (⨁ i₁, ⨁ i₂, M₁ i₁ ⊗ M₂ i₂)`, i.e.
"tensor product distributes over direct sum". -/
def direct_sum :
(⨁ i₁, M₁ i₁) ⊗[R] (⨁ i₂, M₂ i₂) ≃ₗ[R] (⨁ (i : ι₁ × ι₂), M₁ i.1 ⊗[R] M₂ i.2) :=
begin
refine linear_equiv.of_linear
(lift $ direct_sum.to_module R _ _ $ λ i₁, flip $ direct_sum.to_module R _ _ $ λ i₂,
flip $ curry $ direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂))
(direct_sum.to_module R _ _ $ λ i, map (direct_sum.lof R _ _ _) (direct_sum.lof R _ _ _))
(linear_map.ext $ direct_sum.to_module.ext _ $ λ i, mk_compr₂_inj $
linear_map.ext $ λ x₁, linear_map.ext $ λ x₂, _)
(mk_compr₂_inj $ linear_map.ext $ direct_sum.to_module.ext _ $ λ i₁, linear_map.ext $ λ x₁,
linear_map.ext $ direct_sum.to_module.ext _ $ λ i₂, linear_map.ext $ λ x₂, _),
repeat { rw compr₂_apply <|> rw comp_apply <|> rw id_apply <|> rw mk_apply <|>
rw direct_sum.to_module_lof <|> rw map_tmul <|> rw lift.tmul <|> rw flip_apply <|>
rw curry_apply },
cases i; refl
end
@[simp] theorem direct_sum_lof_tmul_lof (i₁ : ι₁) (m₁ : M₁ i₁) (i₂ : ι₂) (m₂ : M₂ i₂) :
direct_sum R ι₁ ι₂ M₁ M₂ (direct_sum.lof R ι₁ M₁ i₁ m₁ ⊗ₜ direct_sum.lof R ι₂ M₂ i₂ m₂) =
direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂) (m₁ ⊗ₜ m₂) :=
by simp [direct_sum]
end tensor_product
end ring
|
a9325101265fe893ad0896b25b9652b2d534bad9 | 0707842a58b971bc2c537fdcab2f5cef1c12d77a | /lean4/propositional_logic/avigad.lean | ce9dbc5b6f0536f6da9bb97005f606e1d2d9ab0e | [] | no_license | adolfont/LearningProgramming | 7a41e5dfde8df72fc0b4a23592999ecdb22a26e0 | 866e6654d347287bd0c63aa31d18705174f00324 | refs/heads/master | 1,652,902,832,503 | 1,651,315,660,000 | 1,651,315,660,000 | 1,328,601 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,337 | lean | variable (p q r s : Prop)
#check True
#check False
#check p ∧ q
#check p ∨ q
#check p → q
#check p ↔ q
#check ¬ p
theorem foo : p → q → p ∧ q :=
fun hp hq => And.intro hp hq
theorem bar : p ∧ q → q ∧ p :=
fun ⟨hp, hq⟩ => ⟨hq, hp⟩
example : p → p := by
intro h
apply h
theorem two_plus_two_is_four : 2 + 2 = 4 := rfl
def factorial : Nat → Nat
| 0 => 1
| (n + 1) => (n + 1) * factorial n
#eval factorial 10
#eval factorial 100
def hanoi (numPegs start finish aux : Nat) : IO Unit :=
match numPegs with
| 0 => pure ()
| n + 1 => do
hanoi n start aux finish
IO.println s!"Move disk {n + 1} from peg {start} to peg {finish}"
hanoi n aux finish start
#eval hanoi 7 1 2 3
def addNums : List Nat → Nat
| [] => 0
| a::as => a + addNums as
#eval addNums [0, 1, 2, 3, 4, 5, 6]
theorem and_example : p → q → p ∧ q := by
intro hp
intro hq
apply And.intro
. exact hp
. exact hq
#print and_example
example : p → q → p ∧ q :=
fun hp hq => And.intro hp hq
theorem to_example : (p → q) → ¬ p ∨ q := by
intro hpq
sorry
#print to_example
example (h1 : p → q) : ¬ p ∨ q := by
apply Or.elim (Classical.em p)
. intro hp
apply Or.inr
apply h1
exact hp
. intro hnp
apply Or.inl
exact hnp
|
22fe2b422d0d23363540b160bc143e154cc7082b | 6950a6e5cebf75da9b91f42789baf52514655111 | /import_export.lean | e6746654e9f34e3fbdf7750c0954907d7268d072 | [] | no_license | phlippe/Lean_hammer | a6d0a1af09fbce0c58b801032099b9b91d49ecf0 | 2116279b9c6b334f5b661e4abf4561368cca2391 | refs/heads/master | 1,587,486,769,513 | 1,561,466,931,000 | 1,561,466,931,000 | 169,705,506 | 0 | 1 | null | 1,550,228,564,000 | 1,549,614,939,000 | Lean | UTF-8 | Lean | false | false | 673 | lean | import system.io
import .tptp.translation_tptp
import .problem_translation
--###################
--## IMPORT/EXPORT ##
--###################
-- -> Started but currently stopped. Will be continued after other points are done
open io
open io.fs
meta def export_format (f : format) : io unit := put_str f.to_string
/- run_cmd do ⟨f,_⟩ <- using_hammer $ problem_to_format [`sum_two, `fib] [`(Π(x:ℕ), x + x = 2 * x), `(2*1 = 2), `(1+2=3), `(1:ℕ), `(2:ℕ)] `((1+1 = 2)),
let io_output := export_format f,
let file_handle := mk_file_handle "test.tptp" io.mode.write tt,
-- let p := write file_handle "test" ,
tactic.skip -/ |
ad634e3a482a864406ff7e47a4ea8dd6fcf6fb6d | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/data/sum.lean | b0592a01443befdb1af0d4227e1846bb265ed17b | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 3,355 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
More theorems about the sum type.
-/
universes u v
variables {α : Type u} {β : Type v}
open sum
attribute [derive decidable_eq] sum
@[simp] theorem sum.forall {p : α ⊕ β → Prop} : (∀ x, p x) ↔ (∀ a, p (inl a)) ∧ (∀ b, p (inr b)) :=
⟨λ h, ⟨λ a, h _, λ b, h _⟩, λ ⟨h₁, h₂⟩, sum.rec h₁ h₂⟩
@[simp] theorem sum.exists {p : α ⊕ β → Prop} : (∃ x, p x) ↔ (∃ a, p (inl a)) ∨ ∃ b, p (inr b) :=
⟨λ h, match h with
| ⟨inl a, h⟩ := or.inl ⟨a, h⟩
| ⟨inr b, h⟩ := or.inr ⟨b, h⟩
end, λ h, match h with
| or.inl ⟨a, h⟩ := ⟨inl a, h⟩
| or.inr ⟨b, h⟩ := ⟨inr b, h⟩
end⟩
namespace sum
protected def map {α α' β β'} (f : α → α') (g : β → β') : α ⊕ β → α' ⊕ β'
| (sum.inl x) := sum.inl (f x)
| (sum.inr x) := sum.inr (g x)
@[simp] theorem inl.inj_iff {a b} : (inl a : α ⊕ β) = inl b ↔ a = b :=
⟨inl.inj, congr_arg _⟩
@[simp] theorem inr.inj_iff {a b} : (inr a : α ⊕ β) = inr b ↔ a = b :=
⟨inr.inj, congr_arg _⟩
@[simp] theorem inl_ne_inr {a : α} {b : β} : inl a ≠ inr b.
@[simp] theorem inr_ne_inl {a : α} {b : β} : inr b ≠ inl a.
section
variables (ra : α → α → Prop) (rb : β → β → Prop)
/-- Lexicographic order for sum. Sort all the `inl a` before the `inr b`,
otherwise use the respective order on `α` or `β`. -/
inductive lex : α ⊕ β → α ⊕ β → Prop
| inl {a₁ a₂} (h : ra a₁ a₂) : lex (inl a₁) (inl a₂)
| inr {b₁ b₂} (h : rb b₁ b₂) : lex (inr b₁) (inr b₂)
| sep (a b) : lex (inl a) (inr b)
variables {ra rb}
@[simp] theorem lex_inl_inl {a₁ a₂} : lex ra rb (inl a₁) (inl a₂) ↔ ra a₁ a₂ :=
⟨λ h, by cases h; assumption, lex.inl _⟩
@[simp] theorem lex_inr_inr {b₁ b₂} : lex ra rb (inr b₁) (inr b₂) ↔ rb b₁ b₂ :=
⟨λ h, by cases h; assumption, lex.inr _⟩
@[simp] theorem lex_inr_inl {b a} : ¬ lex ra rb (inr b) (inl a) :=
λ h, by cases h
attribute [simp] lex.sep
theorem lex_acc_inl {a} (aca : acc ra a) : acc (lex ra rb) (inl a) :=
begin
induction aca with a H IH,
constructor, intros y h,
cases h with a' _ h',
exact IH _ h'
end
theorem lex_acc_inr (aca : ∀ a, acc (lex ra rb) (inl a)) {b} (acb : acc rb b) : acc (lex ra rb) (inr b) :=
begin
induction acb with b H IH,
constructor, intros y h,
cases h with _ _ _ b' _ h' a,
{ exact IH _ h' },
{ exact aca _ }
end
theorem lex_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) :=
have aca : ∀ a, acc (lex ra rb) (inl a), from λ a, lex_acc_inl (ha.apply a),
⟨λ x, sum.rec_on x aca (λ b, lex_acc_inr aca (hb.apply b))⟩
end
/-- Swap the factors of a sum type -/
@[simp] def swap : α ⊕ β → β ⊕ α
| (inl a) := inr a
| (inr b) := inl b
@[simp] lemma swap_swap (x : α ⊕ β) : swap (swap x) = x :=
by cases x; refl
@[simp] lemma swap_swap_eq : swap ∘ swap = @id (α ⊕ β) :=
funext $ swap_swap
@[simp] lemma swap_left_inverse : function.left_inverse (@swap α β) swap :=
swap_swap
@[simp] lemma swap_right_inverse : function.right_inverse (@swap α β) swap :=
swap_swap
end sum
|
baea68c5074c113f74b1b28fe5a97e40023e7fce | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /data/pfun.lean | f0ffbde2d67f91828b86fe93c634f94449ea7d6c | [
"Apache-2.0"
] | permissive | kckennylau/mathlib | 21fb810b701b10d6606d9002a4004f7672262e83 | 47b3477e20ffb5a06588dd3abb01fe0fe3205646 | refs/heads/master | 1,634,976,409,281 | 1,542,042,832,000 | 1,542,319,733,000 | 109,560,458 | 0 | 0 | Apache-2.0 | 1,542,369,208,000 | 1,509,867,494,000 | Lean | UTF-8 | Lean | false | false | 15,761 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.set.basic data.option data.equiv.basic
/-- `roption α` is the type of "partial values" of type `α`. It
is similar to `option α` except the domain condition can be an
arbitrary proposition, not necessarily decidable. -/
structure {u} roption (α : Type u) : Type u :=
(dom : Prop)
(get : dom → α)
namespace roption
variables {α : Type*} {β : Type*} {γ : Type*}
/-- Convert an `roption α` with a decidable domain to an option -/
def to_option (o : roption α) [decidable o.dom] : option α :=
if h : dom o then some (o.get h) else none
/-- `roption` extensionality -/
def ext' : Π {o p : roption α}
(H1 : o.dom ↔ p.dom)
(H2 : ∀h₁ h₂, o.get h₁ = p.get h₂), o = p
| ⟨od, o⟩ ⟨pd, p⟩ H1 H2 := have t : od = pd, from propext H1,
by cases t; rw [show o = p, from funext $ λp, H2 p p]
/-- `roption` eta expansion -/
@[simp] theorem eta : Π (o : roption α), (⟨o.dom, λ h, o.get h⟩ : roption α) = o
| ⟨h, f⟩ := rfl
/-- `a ∈ o` means that `o` is defined and equal to `a` -/
protected def mem (a : α) (o : roption α) : Prop := ∃ h, o.get h = a
instance : has_mem α (roption α) := ⟨roption.mem⟩
theorem dom_iff_mem : ∀ {o : roption α}, o.dom ↔ ∃y, y ∈ o
| ⟨p, f⟩ := ⟨λh, ⟨f h, h, rfl⟩, λ⟨_, h, rfl⟩, h⟩
theorem get_mem {o : roption α} (h) : get o h ∈ o := ⟨_, rfl⟩
/-- `roption` extensionality -/
def ext {o p : roption α} (H : ∀ a, a ∈ o ↔ a ∈ p) : o = p :=
ext' ⟨λ h, ((H _).1 ⟨h, rfl⟩).fst,
λ h, ((H _).2 ⟨h, rfl⟩).fst⟩ $
λ a b, ((H _).2 ⟨_, rfl⟩).snd
/-- The `none` value in `roption` has a `false` domain and an empty function. -/
def none : roption α := ⟨false, false.rec _⟩
@[simp] theorem not_mem_none (a : α) : a ∉ @none α := λ h, h.fst
/-- The `some a` value in `roption` has a `true` domain and the
function returns `a`. -/
def some (a : α) : roption α := ⟨true, λ_, a⟩
theorem mem_unique : relator.left_unique ((∈) : α → roption α → Prop)
| _ ⟨p, f⟩ _ ⟨h₁, rfl⟩ ⟨h₂, rfl⟩ := rfl
theorem get_eq_of_mem {o : roption α} {a} (h : a ∈ o) (h') : get o h' = a :=
mem_unique ⟨_, rfl⟩ h
theorem mem_some (a : α) : a ∈ some a := ⟨trivial, rfl⟩
@[simp] theorem mem_some_iff {a b} : b ∈ (some a : roption α) ↔ b = a :=
⟨λ⟨h, e⟩, e.symm, λ e, ⟨trivial, e.symm⟩⟩
theorem eq_some_iff {a : α} {o : roption α} : o = some a ↔ a ∈ o :=
⟨λ e, e.symm ▸ mem_some _,
λ ⟨h, e⟩, e ▸ ext' (iff_true_intro h) (λ _ _, rfl)⟩
theorem eq_none_iff {o : roption α} : o = none ↔ ∀ a, a ∉ o :=
⟨λ e, e.symm ▸ not_mem_none,
λ h, ext (by simpa [not_mem_none])⟩
theorem eq_none_iff' {o : roption α} : o = none ↔ ¬ o.dom :=
⟨λ e, e.symm ▸ id, λ h, eq_none_iff.2 (λ a h', h h'.fst)⟩
instance none_decidable : decidable (@none α).dom := decidable.false
instance some_decidable (a : α) : decidable (some a).dom := decidable.true
@[simp] theorem mem_to_option {o : roption α} [decidable o.dom] {a : α} :
a ∈ to_option o ↔ a ∈ o :=
begin
unfold to_option,
by_cases h : o.dom; simp [h],
{ exact ⟨λ h, ⟨_, h⟩, λ ⟨_, h⟩, h⟩ },
{ exact mt Exists.fst h }
end
/-- Convert an `option α` into an `roption α` -/
def of_option : option α → roption α
| option.none := none
| (option.some a) := some a
@[simp] theorem mem_of_option {a : α} : ∀ {o : option α}, a ∈ of_option o ↔ a ∈ o
| option.none := ⟨λ h, h.fst.elim, λ h, option.no_confusion h⟩
| (option.some b) := ⟨λ h, congr_arg option.some h.snd,
λ h, ⟨trivial, option.some.inj h⟩⟩
@[simp] theorem of_option_dom {α} : ∀ (o : option α), (of_option o).dom ↔ o.is_some
| option.none := by simp [of_option, none]
| (option.some a) := by simp [of_option]
theorem of_option_eq_get {α} (o : option α) : of_option o = ⟨_, @option.get _ o⟩ :=
roption.ext' (of_option_dom o) $ λ h₁ h₂, by cases o; [cases h₁, refl]
instance : has_coe (option α) (roption α) := ⟨of_option⟩
@[simp] theorem mem_coe {a : α} {o : option α} :
a ∈ (o : roption α) ↔ a ∈ o := mem_of_option
@[simp] theorem coe_none : (@option.none α : roption α) = none := rfl
@[simp] theorem coe_some (a : α) : (option.some a : roption α) = some a := rfl
instance of_option_decidable : ∀ o : option α, decidable (of_option o).dom
| option.none := roption.none_decidable
| (option.some a) := roption.some_decidable a
@[simp] theorem to_of_option (o : option α) : to_option (of_option o) = o :=
by cases o; refl
@[simp] theorem of_to_option (o : roption α) [decidable o.dom] : of_option (to_option o) = o :=
ext $ λ a, mem_of_option.trans mem_to_option
noncomputable def equiv_option : roption α ≃ option α :=
by haveI := classical.dec; exact
⟨λ o, to_option o, of_option, λ o, of_to_option o,
λ o, eq.trans (by dsimp; congr) (to_of_option o)⟩
/-- `assert p f` is a bind-like operation which appends an additional condition
`p` to the domain and uses `f` to produce the value. -/
def assert (p : Prop) (f : p → roption α) : roption α :=
⟨∃h : p, (f h).dom, λha, (f ha.fst).get ha.snd⟩
/-- The bind operation has value `g (f.get)`, and is defined when all the
parts are defined. -/
protected def bind (f : roption α) (g : α → roption β) : roption β :=
assert (dom f) (λb, g (f.get b))
/-- The map operation for `roption` just maps the value and maintains the same domain. -/
def map (f : α → β) (o : roption α) : roption β :=
⟨o.dom, f ∘ o.get⟩
theorem mem_map (f : α → β) {o : roption α} :
∀ {a}, a ∈ o → f a ∈ map f o
| _ ⟨h, rfl⟩ := ⟨_, rfl⟩
@[simp] theorem mem_map_iff (f : α → β) {o : roption α} {b} :
b ∈ map f o ↔ ∃ a ∈ o, f a = b :=
⟨match b with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩, rfl⟩ end,
λ ⟨a, h₁, h₂⟩, h₂ ▸ mem_map f h₁⟩
@[simp] theorem map_none (f : α → β) :
map f none = none := eq_none_iff.2 $ λ a, by simp
@[simp] theorem map_some (f : α → β) (a : α) : map f (some a) = some (f a) :=
eq_some_iff.2 $ mem_map f $ mem_some _
theorem mem_assert {p : Prop} {f : p → roption α}
: ∀ {a} (h : p), a ∈ f h → a ∈ assert p f
| _ _ ⟨h, rfl⟩ := ⟨⟨_, _⟩, rfl⟩
@[simp] theorem mem_assert_iff {p : Prop} {f : p → roption α} {a} :
a ∈ assert p f ↔ ∃ h : p, a ∈ f h :=
⟨match a with _, ⟨h, rfl⟩ := ⟨_, ⟨_, rfl⟩⟩ end,
λ ⟨a, h⟩, mem_assert _ h⟩
theorem mem_bind {f : roption α} {g : α → roption β} :
∀ {a b}, a ∈ f → b ∈ g a → b ∈ f.bind g
| _ _ ⟨h, rfl⟩ ⟨h₂, rfl⟩ := ⟨⟨_, _⟩, rfl⟩
@[simp] theorem mem_bind_iff {f : roption α} {g : α → roption β} {b} :
b ∈ f.bind g ↔ ∃ a ∈ f, b ∈ g a :=
⟨match b with _, ⟨⟨h₁, h₂⟩, rfl⟩ := ⟨_, ⟨_, rfl⟩, ⟨_, rfl⟩⟩ end,
λ ⟨a, h₁, h₂⟩, mem_bind h₁ h₂⟩
@[simp] theorem bind_none (f : α → roption β) :
none.bind f = none := eq_none_iff.2 $ λ a, by simp
@[simp] theorem bind_some (a : α) (f : α → roption β) :
(some a).bind f = f a := ext $ by simp
theorem bind_some_eq_map (f : α → β) (x : roption α) :
x.bind (some ∘ f) = map f x :=
ext $ by simp [eq_comm]
theorem bind_assoc {γ} (f : roption α) (g : α → roption β) (k : β → roption γ) :
(f.bind g).bind k = f.bind (λ x, (g x).bind k) :=
ext $ λ a, by simp; exact
⟨λ ⟨_, ⟨_, h₁, h₂⟩, h₃⟩, ⟨_, h₁, _, h₂, h₃⟩,
λ ⟨_, h₁, _, h₂, h₃⟩, ⟨_, ⟨_, h₁, h₂⟩, h₃⟩⟩
@[simp] theorem bind_map {γ} (f : α → β) (x) (g : β → roption γ) :
(map f x).bind g = x.bind (λ y, g (f y)) :=
by rw [← bind_some_eq_map, bind_assoc]; simp
@[simp] theorem map_bind {γ} (f : α → roption β) (x : roption α) (g : β → γ) :
map g (x.bind f) = x.bind (λ y, map g (f y)) :=
by rw [← bind_some_eq_map, bind_assoc]; simp [bind_some_eq_map]
theorem map_map (g : β → γ) (f : α → β) (o : roption α) :
map g (map f o) = map (g ∘ f) o :=
by rw [← bind_some_eq_map, bind_map, bind_some_eq_map]
instance : monad roption :=
{ pure := @some,
map := @map,
bind := @roption.bind }
instance : is_lawful_monad roption :=
{ bind_pure_comp_eq_map := @bind_some_eq_map,
id_map := λ β f, by cases f; refl,
pure_bind := @bind_some,
bind_assoc := @bind_assoc }
theorem map_id' {f : α → α} (H : ∀ (x : α), f x = x) (o) : map f o = o :=
by rw [show f = id, from funext H]; exact id_map o
@[simp] theorem bind_some_right (x : roption α) : x.bind some = x :=
by rw [bind_some_eq_map]; simp [map_id']
@[simp] theorem ret_eq_some (a : α) : return a = some a := rfl
@[simp] theorem map_eq_map {α β} (f : α → β) (o : roption α) :
f <$> o = map f o := rfl
@[simp] theorem bind_eq_bind {α β} (f : roption α) (g : α → roption β) :
f >>= g = f.bind g := rfl
instance : monad_fail roption :=
{ fail := λ_ _, none, ..roption.monad }
/- `restrict p o h` replaces the domain of `o` with `p`, and is well defined when
`p` implies `o` is defined. -/
def restrict (p : Prop) : ∀ (o : roption α), (p → o.dom) → roption α
| ⟨d, f⟩ H := ⟨p, λh, f (H h)⟩
/-- `unwrap o` gets the value at `o`, ignoring the condition.
(This function is unsound.) -/
meta def unwrap (o : roption α) : α := o.get undefined
theorem assert_defined {p : Prop} {f : p → roption α} :
∀ (h : p), (f h).dom → (assert p f).dom := exists.intro
theorem bind_defined {f : roption α} {g : α → roption β} :
∀ (h : f.dom), (g (f.get h)).dom → (f.bind g).dom := assert_defined
@[simp] theorem bind_dom {f : roption α} {g : α → roption β} :
(f.bind g).dom ↔ ∃ h : f.dom, (g (f.get h)).dom := iff.rfl
end roption
/-- `pfun α β`, or `α →. β`, is the type of partial functions from
`α` to `β`. It is defined as `α → roption β`. -/
def pfun (α : Type*) (β : Type*) := α → roption β
infixr ` →. `:25 := pfun
namespace pfun
variables {α : Type*} {β : Type*} {γ : Type*}
/-- The domain of a partial function -/
def dom (f : α →. β) : set α := λ a, (f a).dom
/-- Evaluate a partial function -/
def fn (f : α →. β) (x) (h : dom f x) : β := (f x).get h
/-- Evaluate a partial function to return an `option` -/
def eval_opt (f : α →. β) [D : decidable_pred (dom f)] (x : α) : option β :=
@roption.to_option _ _ (D x)
/-- Partial function extensionality -/
def ext' {f g : α →. β}
(H1 : ∀ a, a ∈ dom f ↔ a ∈ dom g)
(H2 : ∀ a p q, f.fn a p = g.fn a q) : f = g :=
funext $ λ a, roption.ext' (H1 a) (H2 a)
def ext {f g : α →. β} (H : ∀ a b, b ∈ f a ↔ b ∈ g a) : f = g :=
funext $ λ a, roption.ext (H a)
/-- Turn a partial function into a function out of a subtype -/
def as_subtype (f : α →. β) (s : {x // f.dom x}) : β := f.fn s.1 s.2
def equiv_subtype : (α →. β) ≃ (Σ p : α → Prop, subtype p → β) :=
⟨λ f, ⟨f.dom, as_subtype f⟩,
λ ⟨p, f⟩ x, ⟨p x, λ h, f ⟨x, h⟩⟩,
λ f, funext $ λ a, roption.eta _,
λ ⟨p, f⟩, by dsimp; congr; funext a; cases a; refl⟩
/-- Turn a total function into a partial function -/
protected def lift (f : α → β) : α →. β := λ a, roption.some (f a)
instance : has_coe (α → β) (α →. β) := ⟨pfun.lift⟩
@[simp] theorem lift_eq_coe (f : α → β) : pfun.lift f = f := rfl
@[simp] theorem coe_val (f : α → β) (a : α) :
(f : α →. β) a = roption.some (f a) := rfl
/-- The graph of a partial function is the set of pairs
`(x, f x)` where `x` is in the domain of `f`. -/
def graph (f : α →. β) : set (α × β) := {p | p.2 ∈ f p.1}
/-- The range of a partial function is the set of values
`f x` where `x` is in the domain of `f`. -/
def ran (f : α →. β) : set β := {b | ∃a, b ∈ f a}
/-- Restrict a partial function to a smaller domain. -/
def restrict (f : α →. β) {p : set α} (H : p ⊆ f.dom) : α →. β :=
λ x, roption.restrict (p x) (f x) (@H x)
theorem dom_iff_graph (f : α →. β) (x : α) : x ∈ f.dom ↔ ∃y, (x, y) ∈ f.graph :=
roption.dom_iff_mem
theorem lift_graph {f : α → β} {a b} : (a, b) ∈ (f : α →. β).graph ↔ f a = b :=
show (∃ (h : true), f a = b) ↔ f a = b, by simp
/-- The monad `pure` function, the total constant `x` function -/
protected def pure (x : β) : α →. β := λ_, roption.some x
/-- The monad `bind` function, pointwise `roption.bind` -/
def bind (f : α →. β) (g : β → α →. γ) : α →. γ :=
λa, roption.bind (f a) (λb, g b a)
/-- The monad `map` function, pointwise `roption.map` -/
def map (f : β → γ) (g : α →. β) : α →. γ :=
λa, roption.map f (g a)
instance : monad (pfun α) :=
{ pure := @pfun.pure _,
bind := @pfun.bind _,
map := @pfun.map _ }
instance : is_lawful_monad (pfun α) :=
{ bind_pure_comp_eq_map := λ β γ f x, funext $ λ a, roption.bind_some_eq_map _ _,
id_map := λ β f, by funext a; dsimp [functor.map, pfun.map]; cases f a; refl,
pure_bind := λ β γ x f, funext $ λ a, roption.bind_some.{u_1 u_2} _ (f x),
bind_assoc := λ β γ δ f g k,
funext $ λ a, roption.bind_assoc (f a) (λ b, g b a) (λ b, k b a) }
theorem pure_defined (p : set α) (x : β) : p ⊆ (@pfun.pure α _ x).dom := set.subset_univ p
theorem bind_defined {α β γ} (p : set α) {f : α →. β} {g : β → α →. γ}
(H1 : p ⊆ f.dom) (H2 : ∀x, p ⊆ (g x).dom) : p ⊆ (f >>= g).dom :=
λa ha, (⟨H1 ha, H2 _ ha⟩ : (f >>= g).dom a)
def fix (f : α →. β ⊕ α) : α →. β := λ a,
roption.assert (acc (λ x y, sum.inr x ∈ f y) a) $ λ h,
@well_founded.fix_F _ (λ x y, sum.inr x ∈ f y) _
(λ a IH, roption.assert (f a).dom $ λ hf,
by cases e : (f a).get hf with b a';
[exact roption.some b, exact IH _ ⟨hf, e⟩])
a h
theorem dom_of_mem_fix {f : α →. β ⊕ α} {a : α} {b : β}
(h : b ∈ fix f a) : (f a).dom :=
let ⟨h₁, h₂⟩ := roption.mem_assert_iff.1 h in
by rw well_founded.fix_F_eq at h₂; exact h₂.fst.fst
theorem mem_fix_iff {f : α →. β ⊕ α} {a : α} {b : β} :
b ∈ fix f a ↔ sum.inl b ∈ f a ∨ ∃ a', sum.inr a' ∈ f a ∧ b ∈ fix f a' :=
⟨λ h, let ⟨h₁, h₂⟩ := roption.mem_assert_iff.1 h in
begin
rw well_founded.fix_F_eq at h₂,
simp at h₂,
cases h₂ with h₂ h₃,
cases e : (f a).get h₂ with b' a'; simp [e] at h₃,
{ subst b', refine or.inl ⟨h₂, e⟩ },
{ exact or.inr ⟨a', ⟨_, e⟩, roption.mem_assert _ h₃⟩ }
end,
λ h, begin
simp [fix],
rcases h with ⟨h₁, h₂⟩ | ⟨a', h, h₃⟩,
{ refine ⟨⟨_, λ y h', _⟩, _⟩,
{ injection roption.mem_unique ⟨h₁, h₂⟩ h' },
{ rw well_founded.fix_F_eq, simp [h₁, h₂] } },
{ simp [fix] at h₃, cases h₃ with h₃ h₄,
refine ⟨⟨_, λ y h', _⟩, _⟩,
{ injection roption.mem_unique h h' with e,
exact e ▸ h₃ },
{ cases h with h₁ h₂,
rw well_founded.fix_F_eq, simp [h₁, h₂, h₄] } }
end⟩
@[elab_as_eliminator] theorem fix_induction
{f : α →. β ⊕ α} {b : β} {C : α → Sort*} {a : α} (h : b ∈ fix f a)
(H : ∀ a, b ∈ fix f a →
(∀ a', b ∈ fix f a' → sum.inr a' ∈ f a → C a') → C a) : C a :=
begin
replace h := roption.mem_assert_iff.1 h,
have := h.snd, revert this,
induction h.fst with a ha IH, intro h₂,
refine H a (roption.mem_assert_iff.2 ⟨⟨_, ha⟩, h₂⟩)
(λ a' ha' fa', _),
have := (roption.mem_assert_iff.1 ha').snd,
exact IH _ fa' ⟨ha _ fa', this⟩ this
end
end pfun |
b100d4c4a22562a349b564421cabbaa7db400c08 | 5883d9218e6f144e20eee6ca1dab8529fa1a97c0 | /src/exp/subst/apply.lean | 32086cb02d2474c08469597b7de6b3048cc3fcfd | [] | no_license | spl/alpha-conversion-is-easy | 0d035bc570e52a6345d4890e4d0c9e3f9b8126c1 | ed937fe85d8495daffd9412a5524c77b9fcda094 | refs/heads/master | 1,607,649,280,020 | 1,517,380,240,000 | 1,517,380,240,000 | 52,174,747 | 4 | 0 | null | 1,456,052,226,000 | 1,456,001,163,000 | Lean | UTF-8 | Lean | false | false | 1,008 | lean | /-
This files defines `subst.apply`.
-/
import .update
namespace acie -----------------------------------------------------------------
namespace exp ------------------------------------------------------------------
namespace subst ----------------------------------------------------------------
variables {V : Type} [decidable_eq V] -- Type of variable names
variables {vs : Type → Type} [vset vs V] -- Type of variable name sets
-- Apply a substitution to one expression to get another with different free
-- variables.
@[reducible]
protected
def apply : ∀ {X Y : vs V}, subst X Y → exp X → exp Y
| X Y F (var x) := F x
| X Y F (app f e) := app (apply F f) (apply F e)
| X Y F (lam' a e) := lam (apply (subst.update a (fresh Y).1 F) e)
end /- namespace -/ subst ------------------------------------------------------
end /- namespace -/ exp --------------------------------------------------------
end /- namespace -/ acie -------------------------------------------------------
|
2c42e88997f305acf69bf2ea9a974e013f81f81f | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/algebra/smul_with_zero.lean | 12bdc651432af69eca0c8bf8958240e5529491d7 | [
"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 | 5,082 | lean | /-
Copyright (c) 2021 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import group_theory.group_action.defs
/-!
# Introduce `smul_with_zero`
In analogy with the usual monoid action on a Type `M`, we introduce an action of a
`monoid_with_zero` on a Type with `0`.
In particular, for Types `R` and `M`, both containing `0`, we define `smul_with_zero R M` to
be the typeclass where the products `r • 0` and `0 • m` vanish for all `r : R` and all `m : M`.
Moreover, in the case in which `R` is a `monoid_with_zero`, we introduce the typeclass
`mul_action_with_zero R M`, mimicking group actions and having an absorbing `0` in `R`.
Thus, the action is required to be compatible with
* the unit of the monoid, acting as the identity;
* the zero of the monoid_with_zero, acting as zero;
* associativity of the monoid.
We also add an `instance`:
* any `monoid_with_zero` has a `mul_action_with_zero R R` acting on itself.
-/
variables {R R' M M' : Type*}
section has_zero
variables (R M)
/-- `smul_with_zero` is a class consisting of a Type `R` with `0 ∈ R` and a scalar multiplication
of `R` on a Type `M` with `0`, such that the equality `r • m = 0` holds if at least one among `r`
or `m` equals `0`. -/
class smul_with_zero [has_zero R] [has_zero M] extends has_scalar R M :=
(smul_zero : ∀ r : R, r • (0 : M) = 0)
(zero_smul : ∀ m : M, (0 : R) • m = 0)
instance mul_zero_class.to_smul_with_zero [mul_zero_class R] : smul_with_zero R R :=
{ smul := (*),
smul_zero := mul_zero,
zero_smul := zero_mul }
variables (R) {M} [has_zero R] [has_zero M] [smul_with_zero R M]
@[simp] lemma zero_smul (m : M) : (0 : R) • m = 0 := smul_with_zero.zero_smul m
variables {R} (M)
/-- Note that this lemma has different typeclass assumptions to `smul_zero`. -/
@[simp] lemma smul_zero' (r : R) : r • (0 : M) = 0 := smul_with_zero.smul_zero r
variables {R M} [has_zero R'] [has_zero M'] [has_scalar R M']
/-- Pullback a `smul_with_zero` structure along an injective zero-preserving homomorphism. -/
protected def function.injective.smul_with_zero
(f : zero_hom M' M) (hf : function.injective f) (smul : ∀ (a : R) b, f (a • b) = a • f b) :
smul_with_zero R M' :=
{ smul := (•),
zero_smul := λ a, hf $ by simp [smul],
smul_zero := λ a, hf $ by simp [smul]}
/-- Pushforward a `smul_with_zero` structure along a surjective zero-preserving homomorphism. -/
protected def function.surjective.smul_with_zero
(f : zero_hom M M') (hf : function.surjective f) (smul : ∀ (a : R) b, f (a • b) = a • f b) :
smul_with_zero R M' :=
{ smul := (•),
zero_smul := λ m, by { rcases hf m with ⟨x, rfl⟩, simp [←smul] },
smul_zero := λ c, by simp only [← f.map_zero, ← smul, smul_zero'] }
variables (M)
/-- Compose a `smul_with_zero` with a `zero_hom`, with action `f r' • m` -/
def smul_with_zero.comp_hom (f : zero_hom R' R) : smul_with_zero R' M :=
{ smul := (•) ∘ f,
smul_zero := λ m, by simp,
zero_smul := λ m, by simp }
end has_zero
section monoid_with_zero
variables [monoid_with_zero R] [monoid_with_zero R'] [has_zero M]
variables (R M)
/-- An action of a monoid with zero `R` on a Type `M`, also with `0`, extends `mul_action` and
is compatible with `0` (both in `R` and in `M`), with `1 ∈ R`, and with associativity of
multiplication on the monoid `M`. -/
class mul_action_with_zero extends mul_action R M :=
-- these fields are copied from `smul_with_zero`, as `extends` behaves poorly
(smul_zero : ∀ r : R, r • (0 : M) = 0)
(zero_smul : ∀ m : M, (0 : R) • m = 0)
@[priority 100] -- see Note [lower instance priority]
instance mul_action_with_zero.to_smul_with_zero [m : mul_action_with_zero R M] :
smul_with_zero R M :=
{..m}
instance monoid_with_zero.to_mul_action_with_zero : mul_action_with_zero R R :=
{ ..mul_zero_class.to_smul_with_zero R,
..monoid.to_mul_action R }
variables {R M} [mul_action_with_zero R M] [has_zero M'] [has_scalar R M']
/-- Pullback a `mul_action_with_zero` structure along an injective zero-preserving homomorphism. -/
protected def function.injective.mul_action_with_zero
(f : zero_hom M' M) (hf : function.injective f) (smul : ∀ (a : R) b, f (a • b) = a • f b) :
mul_action_with_zero R M' :=
{ ..hf.mul_action f smul, ..hf.smul_with_zero f smul }
/-- Pushforward a `mul_action_with_zero` structure along a surjective zero-preserving homomorphism.
-/
protected def function.surjective.mul_action_with_zero
(f : zero_hom M M') (hf : function.surjective f) (smul : ∀ (a : R) b, f (a • b) = a • f b) :
mul_action_with_zero R M' :=
{ ..hf.mul_action f smul, ..hf.smul_with_zero f smul }
variables (M)
/-- Compose a `mul_action_with_zero` with a `monoid_with_zero_hom`, with action `f r' • m` -/
def mul_action_with_zero.comp_hom (f : monoid_with_zero_hom R' R) :
mul_action_with_zero R' M :=
{ smul := (•) ∘ f,
mul_smul := λ r s m, by simp [mul_smul],
one_smul := λ m, by simp,
.. smul_with_zero.comp_hom M f.to_zero_hom}
end monoid_with_zero
|
ebc4f4d3c6870914999e2a46ec2238c4d3268761 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/real/basic.lean | c93711b5e8169a4959351e7cccabbd1a86c16fdb | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 23,444 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn
-/
import algebra.module.basic
import algebra.bounds
import algebra.order.archimedean
import algebra.star.basic
import data.real.cau_seq_completion
import order.conditionally_complete_lattice
/-!
# Real numbers from Cauchy sequences
This file defines `ℝ` as the type of equivalence classes of Cauchy sequences of rational numbers.
This choice is motivated by how easy it is to prove that `ℝ` is a commutative ring, by simply
lifting everything to `ℚ`.
-/
open_locale pointwise
/-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational
numbers. -/
structure real := of_cauchy ::
(cauchy : @cau_seq.completion.Cauchy ℚ _ _ _ abs _)
notation `ℝ` := real
attribute [pp_using_anonymous_constructor] real
namespace real
open cau_seq cau_seq.completion
variables {x y : ℝ}
lemma ext_cauchy_iff : ∀ {x y : real}, x = y ↔ x.cauchy = y.cauchy
| ⟨a⟩ ⟨b⟩ := by split; cc
lemma ext_cauchy {x y : real} : x.cauchy = y.cauchy → x = y :=
ext_cauchy_iff.2
/-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/
def equiv_Cauchy : ℝ ≃ cau_seq.completion.Cauchy :=
⟨real.cauchy, real.of_cauchy, λ ⟨_⟩, rfl, λ _, rfl⟩
-- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511
@[irreducible] private def zero : ℝ := ⟨0⟩
@[irreducible] private def one : ℝ := ⟨1⟩
@[irreducible] private def add : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a + b⟩
@[irreducible] private def neg : ℝ → ℝ | ⟨a⟩ := ⟨-a⟩
@[irreducible] private def mul : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a * b⟩
instance : has_zero ℝ := ⟨zero⟩
instance : has_one ℝ := ⟨one⟩
instance : has_add ℝ := ⟨add⟩
instance : has_neg ℝ := ⟨neg⟩
instance : has_mul ℝ := ⟨mul⟩
lemma zero_cauchy : (⟨0⟩ : ℝ) = 0 := show _ = zero, by rw zero
lemma one_cauchy : (⟨1⟩ : ℝ) = 1 := show _ = one, by rw one
lemma add_cauchy {a b} : (⟨a⟩ + ⟨b⟩ : ℝ) = ⟨a + b⟩ := show add _ _ = _, by rw add
lemma neg_cauchy {a} : (-⟨a⟩ : ℝ) = ⟨-a⟩ := show neg _ = _, by rw neg
lemma mul_cauchy {a b} : (⟨a⟩ * ⟨b⟩ : ℝ) = ⟨a * b⟩ := show mul _ _ = _, by rw mul
instance : comm_ring ℝ :=
begin
refine_struct { zero := (0 : ℝ),
one := (1 : ℝ),
mul := (*),
add := (+),
neg := @has_neg.neg ℝ _,
sub := λ a b, a + (-b),
npow := @npow_rec ℝ ⟨1⟩ ⟨(*)⟩,
nsmul := @nsmul_rec ℝ ⟨0⟩ ⟨(+)⟩,
zsmul := @zsmul_rec ℝ ⟨0⟩ ⟨(+)⟩ ⟨@has_neg.neg ℝ _⟩ };
repeat { rintro ⟨_⟩, };
try { refl };
simp [← zero_cauchy, ← one_cauchy, add_cauchy, neg_cauchy, mul_cauchy];
apply add_assoc <|> apply add_comm <|> apply mul_assoc <|> apply mul_comm <|>
apply left_distrib <|> apply right_distrib <|> apply sub_eq_add_neg <|> skip
end
/-! Extra instances to short-circuit type class resolution.
These short-circuits have an additional property of ensuring that a computable path is found; if
`field ℝ` is found first, then decaying it to these typeclasses would result in a `noncomputable`
version of them. -/
instance : ring ℝ := by apply_instance
instance : comm_semiring ℝ := by apply_instance
instance : semiring ℝ := by apply_instance
instance : comm_monoid_with_zero ℝ := by apply_instance
instance : monoid_with_zero ℝ := by apply_instance
instance : add_comm_group ℝ := by apply_instance
instance : add_group ℝ := by apply_instance
instance : add_comm_monoid ℝ := by apply_instance
instance : add_monoid ℝ := by apply_instance
instance : add_left_cancel_semigroup ℝ := by apply_instance
instance : add_right_cancel_semigroup ℝ := by apply_instance
instance : add_comm_semigroup ℝ := by apply_instance
instance : add_semigroup ℝ := by apply_instance
instance : comm_monoid ℝ := by apply_instance
instance : monoid ℝ := by apply_instance
instance : comm_semigroup ℝ := by apply_instance
instance : semigroup ℝ := by apply_instance
instance : has_sub ℝ := by apply_instance
instance : module ℝ ℝ := by apply_instance
instance : inhabited ℝ := ⟨0⟩
/-- The real numbers are a `*`-ring, with the trivial `*`-structure. -/
instance : star_ring ℝ := star_ring_of_comm
instance : has_trivial_star ℝ := ⟨λ _, rfl⟩
/-- Coercion `ℚ` → `ℝ` as a `ring_hom`. Note that this
is `cau_seq.completion.of_rat`, not `rat.cast`. -/
def of_rat : ℚ →+* ℝ :=
by refine_struct { to_fun := of_cauchy ∘ of_rat };
simp [of_rat_one, of_rat_zero, of_rat_mul, of_rat_add,
one_cauchy, zero_cauchy, ← mul_cauchy, ← add_cauchy]
lemma of_rat_apply (x : ℚ) : of_rat x = of_cauchy (cau_seq.completion.of_rat x) := rfl
/-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/
def mk (x : cau_seq ℚ abs) : ℝ := ⟨cau_seq.completion.mk x⟩
theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g :=
ext_cauchy_iff.trans mk_eq
@[irreducible]
private def lt : ℝ → ℝ → Prop | ⟨x⟩ ⟨y⟩ :=
quotient.lift_on₂ x y (<) $
λ f₁ g₁ f₂ g₂ hf hg, propext $
⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg),
λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩
instance : has_lt ℝ := ⟨lt⟩
lemma lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g := show lt _ _ ↔ _, by rw lt; refl
@[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g :=
lt_cauchy
lemma mk_zero : mk 0 = 0 := by rw ← zero_cauchy; refl
lemma mk_one : mk 1 = 1 := by rw ← one_cauchy; refl
lemma mk_add {f g : cau_seq ℚ abs} : mk (f + g) = mk f + mk g := by simp [mk, add_cauchy]
lemma mk_mul {f g : cau_seq ℚ abs} : mk (f * g) = mk f * mk g := by simp [mk, mul_cauchy]
lemma mk_neg {f : cau_seq ℚ abs} : mk (-f) = -mk f := by simp [mk, neg_cauchy]
@[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f :=
by rw [← mk_zero, mk_lt]; exact iff_of_eq (congr_arg pos (sub_zero f))
@[irreducible] private def le (x y : ℝ) : Prop := x < y ∨ x = y
instance : has_le ℝ := ⟨le⟩
private lemma le_def {x y : ℝ} : x ≤ y ↔ x < y ∨ x = y := show le _ _ ↔ _, by rw le
@[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g :=
by simp [le_def, mk_eq]; refl
@[elab_as_eliminator]
protected lemma ind_mk {C : real → Prop} (x : real) (h : ∀ y, C (mk y)) : C x :=
begin
cases x with x,
induction x using quot.induction_on with x,
exact h x
end
theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b :=
begin
induction a using real.ind_mk,
induction b using real.ind_mk,
induction c using real.ind_mk,
simp only [mk_lt, ← mk_add],
show pos _ ↔ pos _, rw add_sub_add_left_eq_sub
end
instance : partial_order ℝ :=
{ le := (≤), lt := (<),
lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b,
by simpa using lt_iff_le_not_le,
le_refl := λ a, a.ind_mk (by intro a; rw mk_le),
le_trans := λ a b c, real.ind_mk a $ λ a, real.ind_mk b $ λ b, real.ind_mk c $ λ c,
by simpa using le_trans,
lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b,
by simpa using lt_iff_le_not_le,
le_antisymm := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b,
by simpa [mk_eq] using @cau_seq.le_antisymm _ _ a b }
instance : preorder ℝ := by apply_instance
theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y :=
begin
rw [mk_lt] {md := tactic.transparency.semireducible},
exact const_lt
end
protected theorem zero_lt_one : (0 : ℝ) < 1 :=
by convert of_rat_lt.2 zero_lt_one; simp
protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b :=
begin
induction a using real.ind_mk with a,
induction b using real.ind_mk with b,
simpa only [mk_lt, mk_pos, ← mk_mul] using cau_seq.mul_pos
end
instance : ordered_comm_ring ℝ :=
{ add_le_add_left :=
begin
simp only [le_iff_eq_or_lt],
rintros a b ⟨rfl, h⟩,
{ simp },
{ exact λ c, or.inr ((add_lt_add_iff_left c).2 ‹_›) }
end,
zero_le_one := le_of_lt real.zero_lt_one,
mul_pos := @real.mul_pos,
.. real.comm_ring, .. real.partial_order, .. real.semiring }
instance : ordered_ring ℝ := by apply_instance
instance : ordered_semiring ℝ := by apply_instance
instance : ordered_add_comm_group ℝ := by apply_instance
instance : ordered_cancel_add_comm_monoid ℝ := by apply_instance
instance : ordered_add_comm_monoid ℝ := by apply_instance
instance : nontrivial ℝ := ⟨⟨0, 1, ne_of_lt real.zero_lt_one⟩⟩
open_locale classical
noncomputable instance : linear_order ℝ :=
{ le_total := begin
intros a b,
induction a using real.ind_mk with a,
induction b using real.ind_mk with b,
simpa using le_total a b,
end,
decidable_le := by apply_instance,
.. real.partial_order }
noncomputable instance : linear_ordered_comm_ring ℝ :=
{ .. real.nontrivial, .. real.ordered_ring, .. real.comm_ring, .. real.linear_order }
/- Extra instances to short-circuit type class resolution -/
noncomputable instance : linear_ordered_ring ℝ := by apply_instance
noncomputable instance : linear_ordered_semiring ℝ := by apply_instance
instance : is_domain ℝ :=
{ .. real.nontrivial, .. real.comm_ring, .. linear_ordered_ring.is_domain }
@[irreducible] private noncomputable def inv' : ℝ → ℝ | ⟨a⟩ := ⟨a⁻¹⟩
noncomputable instance : has_inv ℝ := ⟨inv'⟩
lemma inv_cauchy {f} : (⟨f⟩ : ℝ)⁻¹ = ⟨f⁻¹⟩ := show inv' _ = _, by rw inv'
noncomputable instance : linear_ordered_field ℝ :=
{ inv := has_inv.inv,
mul_inv_cancel := begin
rintros ⟨a⟩ h,
rw mul_comm,
simp only [inv_cauchy, mul_cauchy, ← one_cauchy, ← zero_cauchy, ne.def] at *,
exact cau_seq.completion.inv_mul_cancel h,
end,
inv_zero := by simp [← zero_cauchy, inv_cauchy],
..real.linear_ordered_comm_ring, }
/- Extra instances to short-circuit type class resolution -/
noncomputable instance : linear_ordered_add_comm_group ℝ := by apply_instance
noncomputable instance field : field ℝ := by apply_instance
noncomputable instance : division_ring ℝ := by apply_instance
noncomputable instance : distrib_lattice ℝ := by apply_instance
noncomputable instance : lattice ℝ := by apply_instance
noncomputable instance : semilattice_inf ℝ := by apply_instance
noncomputable instance : semilattice_sup ℝ := by apply_instance
noncomputable instance : has_inf ℝ := by apply_instance
noncomputable instance : has_sup ℝ := by apply_instance
noncomputable instance decidable_lt (a b : ℝ) : decidable (a < b) := by apply_instance
noncomputable instance decidable_le (a b : ℝ) : decidable (a ≤ b) := by apply_instance
noncomputable instance decidable_eq (a b : ℝ) : decidable (a = b) := by apply_instance
open rat
@[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x :=
of_rat.eq_rat_cast
theorem le_mk_of_forall_le {f : cau_seq ℚ abs} :
(∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f :=
begin
intro h,
induction x using real.ind_mk with x,
apply le_of_not_lt,
rw mk_lt,
rintro ⟨K, K0, hK⟩,
obtain ⟨i, H⟩ := exists_forall_ge_and h
(exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0)),
apply not_lt_of_le (H _ le_rfl).1,
rw ← of_rat_eq_cast,
rw [mk_lt] {md := tactic.transparency.semireducible},
refine ⟨_, half_pos K0, i, λ j ij, _⟩,
have := add_le_add (H _ ij).2.1
(le_of_lt (abs_lt.1 $ (H _ le_rfl).2.2 _ ij).1),
rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this
end
theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ}
(h : ∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) : mk f ≤ x :=
begin
cases h with i H,
rw [← neg_le_neg_iff, ← mk_neg],
exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩
end
theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ}
(H : ∃ i, ∀ j ≥ i, |(f j : ℝ) - x| ≤ ε) : |mk f - x| ≤ ε :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $
H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1,
sub_le.1 $ le_mk_of_forall_le $
H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩
instance : archimedean ℝ :=
archimedean_iff_rat_le.2 $ λ x, real.ind_mk x $ λ f,
let ⟨M, M0, H⟩ := f.bounded' 0 in
⟨M, mk_le_of_forall_le ⟨0, λ i _,
rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩
noncomputable instance : floor_ring ℝ := archimedean.floor_ring _
theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq
abs (λ i, (f i : ℝ)) :=
⟨λ H ε ε0,
let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in
(H _ δ0).imp $ λ i hi j ij, lt_trans
(by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε,
λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $
λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩
theorem of_near (f : ℕ → ℚ) (x : ℝ)
(h : ∀ ε > 0, ∃ i, ∀ j ≥ i, |(f j : ℝ) - x| < ε) :
∃ h', real.mk ⟨f, h'⟩ = x :=
⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h),
sub_eq_zero.1 $ abs_eq_zero.1 $
eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0,
mk_near_of_forall_near $
(h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩
theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧
∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub :=
int.exists_greatest_of_bdd
(let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h',
int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩)
(let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩)
theorem exists_is_lub (S : set ℝ) (hne : S.nonempty) (hbdd : bdd_above S) :
∃ x, is_lub S x :=
begin
rcases ⟨hne, hbdd⟩ with ⟨⟨L, hL⟩, ⟨U, hU⟩⟩,
have : ∀ d : ℕ, bdd_above {m : ℤ | ∃ y ∈ S, (m : ℝ) ≤ y * d},
{ cases exists_int_gt U with k hk,
refine λ d, ⟨k * d, λ z h, _⟩,
rcases h with ⟨y, yS, hy⟩,
refine int.cast_le.1 (hy.trans _),
push_cast,
exact mul_le_mul_of_nonneg_right ((hU yS).trans hk.le) d.cast_nonneg },
choose f hf using λ d : ℕ, int.exists_greatest_of_bdd (this d) ⟨⌊L * d⌋, L, hL, int.floor_le _⟩,
have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0,
let ⟨y, yS, hy⟩ := (hf n).1 in
⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩,
have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ),
{ intros n n0 y yS,
have := (int.sub_one_lt_floor _).trans_le (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, int.floor_le _⟩),
simp [-sub_eq_add_neg],
rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel],
exact ne_of_gt (nat.cast_pos.2 n0) },
have hg : is_cau_seq abs (λ n, f n / n : ℕ → ℚ),
{ intros ε ε0,
suffices : ∀ j k ≥ ⌈ε⁻¹⌉₊, (f j / j - f k / k : ℚ) < ε,
{ refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ ij _ le_rfl⟩⟩,
rw [neg_lt, neg_sub], exact this _ le_rfl _ ij },
intros j ij k ik,
replace ij := le_trans (nat.le_ceil _) (nat.cast_le.2 ij),
replace ik := le_trans (nat.le_ceil _) (nat.cast_le.2 ik),
have j0 := nat.cast_pos.1 ((inv_pos.2 ε0).trans_le ij),
have k0 := nat.cast_pos.1 ((inv_pos.2 ε0).trans_le ik),
rcases hf₁ _ j0 with ⟨y, yS, hy⟩,
refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _)
((inv_le ε0 (nat.cast_pos.2 k0)).1 ik),
simpa using sub_lt_iff_lt_add'.2
(lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS) },
let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩,
refine ⟨mk g, ⟨λ x xS, _, λ y h, _⟩⟩,
{ refine le_of_forall_ge_of_dense (λ z xz, _),
cases exists_nat_gt (x - z)⁻¹ with K hK,
refine le_mk_of_forall_le ⟨K, λ n nK, _⟩,
replace xz := sub_pos.2 xz,
replace hK := hK.le.trans (nat.cast_le.2 nK),
have n0 : 0 < n := nat.cast_pos.1 ((inv_pos.2 xz).trans_le hK),
refine le_trans _ (hf₂ _ n0 _ xS).le,
rwa [le_sub, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] },
{ exact mk_le_of_forall_le ⟨1, λ n n1,
let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h xS)⟩ }
end
noncomputable instance : has_Sup ℝ :=
⟨λ S, if h : S.nonempty ∧ bdd_above S then classical.some (exists_is_lub S h.1 h.2) else 0⟩
lemma Sup_def (S : set ℝ) :
Sup S = if h : S.nonempty ∧ bdd_above S
then classical.some (exists_is_lub S h.1 h.2) else 0 := rfl
protected theorem is_lub_Sup (S : set ℝ) (h₁ : S.nonempty) (h₂ : bdd_above S) : is_lub S (Sup S) :=
by { simp only [Sup_def, dif_pos (and.intro h₁ h₂)], apply classical.some_spec }
noncomputable instance : has_Inf ℝ := ⟨λ S, -Sup (-S)⟩
lemma Inf_def (S : set ℝ) : Inf S = -Sup (-S) := rfl
protected theorem is_glb_Inf (S : set ℝ) (h₁ : S.nonempty) (h₂ : bdd_below S) :
is_glb S (Inf S) :=
begin
rw [Inf_def, ← is_lub_neg', neg_neg],
exact real.is_lub_Sup _ h₁.neg h₂.neg
end
noncomputable instance : conditionally_complete_linear_order ℝ :=
{ Sup := has_Sup.Sup,
Inf := has_Inf.Inf,
le_cSup := λ s a hs ha, (real.is_lub_Sup s ⟨a, ha⟩ hs).1 ha,
cSup_le := λ s a hs ha, (real.is_lub_Sup s hs ⟨a, ha⟩).2 ha,
cInf_le := λ s a hs ha, (real.is_glb_Inf s ⟨a, ha⟩ hs).1 ha,
le_cInf := λ s a hs ha, (real.is_glb_Inf s hs ⟨a, ha⟩).2 ha,
..real.linear_order, ..real.lattice}
lemma lt_Inf_add_pos {s : set ℝ} (h : s.nonempty) {ε : ℝ} (hε : 0 < ε) :
∃ a ∈ s, a < Inf s + ε :=
exists_lt_of_cInf_lt h $ lt_add_of_pos_right _ hε
lemma add_neg_lt_Sup {s : set ℝ} (h : s.nonempty) {ε : ℝ} (hε : ε < 0) :
∃ a ∈ s, Sup s + ε < a :=
exists_lt_of_lt_cSup h $ add_lt_iff_neg_left.2 hε
lemma Inf_le_iff {s : set ℝ} (h : bdd_below s) (h' : s.nonempty) {a : ℝ} :
Inf s ≤ a ↔ ∀ ε, 0 < ε → ∃ x ∈ s, x < a + ε :=
begin
rw le_iff_forall_pos_lt_add,
split; intros H ε ε_pos,
{ exact exists_lt_of_cInf_lt h' (H ε ε_pos) },
{ rcases H ε ε_pos with ⟨x, x_in, hx⟩,
exact cInf_lt_of_lt h x_in hx }
end
lemma le_Sup_iff {s : set ℝ} (h : bdd_above s) (h' : s.nonempty) {a : ℝ} :
a ≤ Sup s ↔ ∀ ε, ε < 0 → ∃ x ∈ s, a + ε < x :=
begin
rw le_iff_forall_pos_lt_add,
refine ⟨λ H ε ε_neg, _, λ H ε ε_pos, _⟩,
{ exact exists_lt_of_lt_cSup h' (lt_sub_iff_add_lt.mp (H _ (neg_pos.mpr ε_neg))) },
{ rcases H _ (neg_lt_zero.mpr ε_pos) with ⟨x, x_in, hx⟩,
exact sub_lt_iff_lt_add.mp (lt_cSup_of_lt h x_in hx) }
end
@[simp] theorem Sup_empty : Sup (∅ : set ℝ) = 0 := dif_neg $ by simp
lemma csupr_empty {α : Sort*} [is_empty α] (f : α → ℝ) : (⨆ i, f i) = 0 :=
begin
dsimp [supr],
convert real.Sup_empty,
rw set.range_eq_empty_iff,
apply_instance
end
@[simp] lemma csupr_const_zero {α : Sort*} : (⨆ i : α, (0:ℝ)) = 0 :=
begin
casesI is_empty_or_nonempty α,
{ exact real.csupr_empty _ },
{ exact csupr_const },
end
theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : Sup s = 0 :=
dif_neg $ assume h, hs h.2
theorem Sup_univ : Sup (@set.univ ℝ) = 0 :=
real.Sup_of_not_bdd_above $ λ ⟨x, h⟩, not_le_of_lt (lt_add_one _) $ h (set.mem_univ _)
@[simp] theorem Inf_empty : Inf (∅ : set ℝ) = 0 :=
by simp [Inf_def, Sup_empty]
lemma cinfi_empty {α : Sort*} [is_empty α] (f : α → ℝ) : (⨅ i, f i) = 0 :=
begin
dsimp [infi],
convert real.Inf_empty,
rw set.range_eq_empty_iff,
apply_instance
end
@[simp] lemma cinfi_const_zero {α : Sort*} : (⨅ i : α, (0:ℝ)) = 0 :=
begin
casesI is_empty_or_nonempty α,
{ exact real.cinfi_empty _ },
{ exact cinfi_const },
end
theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : Inf s = 0 :=
neg_eq_zero.2 $ Sup_of_not_bdd_above $ mt bdd_above_neg.1 hs
/--
As `0` is the default value for `real.Sup` of the empty set or sets which are not bounded above, it
suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`.
-/
lemma Sup_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Sup S :=
begin
rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩,
{ exact Sup_empty.ge },
{ apply dite _ (λ h, le_cSup_of_le h hy $ hS y hy) (λ h, (Sup_of_not_bdd_above h).ge) }
end
/--
As `0` is the default value for `real.Sup` of the empty set, it suffices to show that `S` is
bounded above by `0` to show that `Sup S ≤ 0`.
-/
lemma Sup_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Sup S ≤ 0 :=
begin
rcases S.eq_empty_or_nonempty with rfl | hS₂,
exacts [Sup_empty.le, cSup_le hS₂ hS],
end
/--
As `0` is the default value for `real.Inf` of the empty set, it suffices to show that `S` is
bounded below by `0` to show that `0 ≤ Inf S`.
-/
lemma Inf_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Inf S :=
begin
rcases S.eq_empty_or_nonempty with rfl | hS₂,
exacts [Inf_empty.ge, le_cInf hS₂ hS]
end
/--
As `0` is the default value for `real.Inf` of the empty set or sets which are not bounded below, it
suffices to show that `S` is bounded above by `0` to show that `Inf S ≤ 0`.
-/
lemma Inf_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Inf S ≤ 0 :=
begin
rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩,
{ exact Inf_empty.le },
{ apply dite _ (λ h, cInf_le_of_le h hy $ hS y hy) (λ h, (Inf_of_not_bdd_below h).le) }
end
lemma Inf_le_Sup (s : set ℝ) (h₁ : bdd_below s) (h₂ : bdd_above s) : Inf s ≤ Sup s :=
begin
rcases s.eq_empty_or_nonempty with rfl | hne,
{ rw [Inf_empty, Sup_empty] },
{ exact cInf_le_cSup h₁ h₂ hne }
end
theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x :=
begin
let S := {x : ℝ | const abs x < f},
have lb : ∃ x, x ∈ S := exists_lt f,
have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x :=
λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h,
have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub',
refine ⟨Sup S,
((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩,
{ rcases h with ⟨ε, ε0, i, ih⟩,
refine (cSup_le lb (ub' _ _)).not_lt (sub_lt_self _ (half_pos ε0)),
refine ⟨_, half_pos ε0, i, λ j ij, _⟩,
rw [sub_apply, const_apply, sub_right_comm,
le_sub_iff_add_le, add_halves],
exact ih _ ij },
{ rcases h with ⟨ε, ε0, i, ih⟩,
refine (le_cSup ub _).not_lt ((lt_add_iff_pos_left _).2 (half_pos ε0)),
refine ⟨_, half_pos ε0, i, λ j ij, _⟩,
rw [sub_apply, const_apply, add_comm, ← sub_sub,
le_sub_iff_add_le, add_halves],
exact ih _ ij }
end
noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩
end real
|
60fd953a358d04afd9b909009775bd4664883e61 | bb31430994044506fa42fd667e2d556327e18dfe | /src/analysis/normed_space/affine_isometry.lean | 34389bb722cb67034cdec9f91f0e936495e80e38 | [
"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 | 24,601 | lean | /-
Copyright (c) 2021 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth
-/
import analysis.normed_space.linear_isometry
import analysis.normed.group.add_torsor
import analysis.normed_space.basic
import linear_algebra.affine_space.restrict
/-!
# Affine isometries
In this file we define `affine_isometry 𝕜 P P₂` to be an affine isometric embedding of normed
add-torsors `P` into `P₂` over normed `𝕜`-spaces and `affine_isometry_equiv` to be an affine
isometric equivalence between `P` and `P₂`.
We also prove basic lemmas and provide convenience constructors. The choice of these lemmas and
constructors is closely modelled on those for the `linear_isometry` and `affine_map` theories.
Since many elementary properties don't require `‖x‖ = 0 → x = 0` we initially set up the theory for
`seminormed_add_comm_group` and specialize to `normed_add_comm_group` only when needed.
## Notation
We introduce the notation `P →ᵃⁱ[𝕜] P₂` for `affine_isometry 𝕜 P P₂`, and `P ≃ᵃⁱ[𝕜] P₂` for
`affine_isometry_equiv 𝕜 P P₂`. In contrast with the notation `→ₗᵢ` for linear isometries, `≃ᵢ`
for isometric equivalences, etc., the "i" here is a superscript. This is for aesthetic reasons to
match the superscript "a" (note that in mathlib `→ᵃ` is an affine map, since `→ₐ` has been taken by
algebra-homomorphisms.)
-/
open function set
variables (𝕜 : Type*) {V V₁ V₂ V₃ V₄ : Type*} {P₁ : Type*} (P P₂ : Type*) {P₃ P₄ : Type*}
[normed_field 𝕜] [seminormed_add_comm_group V] [seminormed_add_comm_group V₁]
[seminormed_add_comm_group V₂] [seminormed_add_comm_group V₃]
[seminormed_add_comm_group V₄]
[normed_space 𝕜 V] [normed_space 𝕜 V₁] [normed_space 𝕜 V₂] [normed_space 𝕜 V₃]
[normed_space 𝕜 V₄]
[pseudo_metric_space P] [metric_space P₁] [pseudo_metric_space P₂] [pseudo_metric_space P₃]
[pseudo_metric_space P₄]
[normed_add_torsor V P] [normed_add_torsor V₁ P₁] [normed_add_torsor V₂ P₂]
[normed_add_torsor V₃ P₃] [normed_add_torsor V₄ P₄]
include V V₂
/-- An `𝕜`-affine isometric embedding of one normed add-torsor over a normed `𝕜`-space into
another. -/
structure affine_isometry extends P →ᵃ[𝕜] P₂ :=
(norm_map : ∀ x : V, ‖linear x‖ = ‖x‖)
omit V V₂
variables {𝕜 P P₂}
-- `→ᵃᵢ` would be more consistent with the linear isometry notation, but it is uglier
notation P ` →ᵃⁱ[`:25 𝕜:25 `] `:0 P₂:0 := affine_isometry 𝕜 P P₂
namespace affine_isometry
variables (f : P →ᵃⁱ[𝕜] P₂)
/-- The underlying linear map of an affine isometry is in fact a linear isometry. -/
protected def linear_isometry : V →ₗᵢ[𝕜] V₂ :=
{ norm_map' := f.norm_map,
.. f.linear }
@[simp] lemma linear_eq_linear_isometry : f.linear = f.linear_isometry.to_linear_map :=
by { ext, refl }
include V V₂
instance : has_coe_to_fun (P →ᵃⁱ[𝕜] P₂) (λ _, P → P₂) := ⟨λ f, f.to_fun⟩
omit V V₂
@[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl
include V V₂
lemma to_affine_map_injective : injective (to_affine_map : (P →ᵃⁱ[𝕜] P₂) → (P →ᵃ[𝕜] P₂))
| ⟨f, _⟩ ⟨g, _⟩ rfl := rfl
lemma coe_fn_injective : @injective (P →ᵃⁱ[𝕜] P₂) (P → P₂) coe_fn :=
affine_map.coe_fn_injective.comp to_affine_map_injective
@[ext] lemma ext {f g : P →ᵃⁱ[𝕜] P₂} (h : ∀ x, f x = g x) : f = g :=
coe_fn_injective $ funext h
omit V V₂
end affine_isometry
namespace linear_isometry
variables (f : V →ₗᵢ[𝕜] V₂)
/-- Reinterpret a linear isometry as an affine isometry. -/
def to_affine_isometry : V →ᵃⁱ[𝕜] V₂ :=
{ norm_map := f.norm_map,
.. f.to_linear_map.to_affine_map }
@[simp] lemma coe_to_affine_isometry : ⇑(f.to_affine_isometry : V →ᵃⁱ[𝕜] V₂) = f := rfl
@[simp] lemma to_affine_isometry_linear_isometry : f.to_affine_isometry.linear_isometry = f :=
by { ext, refl }
-- somewhat arbitrary choice of simp direction
@[simp] lemma to_affine_isometry_to_affine_map :
f.to_affine_isometry.to_affine_map = f.to_linear_map.to_affine_map :=
rfl
end linear_isometry
namespace affine_isometry
/-- We use `f₁` when we need the domain to be a `normed_space`. -/
variables (f : P →ᵃⁱ[𝕜] P₂) (f₁ : P₁ →ᵃⁱ[𝕜] P₂)
@[simp] lemma map_vadd (p : P) (v : V) : f (v +ᵥ p) = f.linear_isometry v +ᵥ f p :=
f.to_affine_map.map_vadd p v
@[simp] lemma map_vsub (p1 p2 : P) : f.linear_isometry (p1 -ᵥ p2) = f p1 -ᵥ f p2 :=
f.to_affine_map.linear_map_vsub p1 p2
@[simp] lemma dist_map (x y : P) : dist (f x) (f y) = dist x y :=
by rw [dist_eq_norm_vsub V₂, dist_eq_norm_vsub V, ← map_vsub, f.linear_isometry.norm_map]
@[simp] lemma nndist_map (x y : P) : nndist (f x) (f y) = nndist x y := by simp [nndist_dist]
@[simp] lemma edist_map (x y : P) : edist (f x) (f y) = edist x y := by simp [edist_dist]
protected lemma isometry : isometry f := f.edist_map
protected lemma injective : injective f₁ := f₁.isometry.injective
@[simp] lemma map_eq_iff {x y : P₁} : f₁ x = f₁ y ↔ x = y := f₁.injective.eq_iff
lemma map_ne {x y : P₁} (h : x ≠ y) : f₁ x ≠ f₁ y := f₁.injective.ne h
protected lemma lipschitz : lipschitz_with 1 f := f.isometry.lipschitz
protected lemma antilipschitz : antilipschitz_with 1 f := f.isometry.antilipschitz
@[continuity] protected lemma continuous : continuous f := f.isometry.continuous
lemma ediam_image (s : set P) : emetric.diam (f '' s) = emetric.diam s :=
f.isometry.ediam_image s
lemma ediam_range : emetric.diam (range f) = emetric.diam (univ : set P) :=
f.isometry.ediam_range
lemma diam_image (s : set P) : metric.diam (f '' s) = metric.diam s :=
f.isometry.diam_image s
lemma diam_range : metric.diam (range f) = metric.diam (univ : set P) :=
f.isometry.diam_range
@[simp] lemma comp_continuous_iff {α : Type*} [topological_space α] {g : α → P} :
continuous (f ∘ g) ↔ continuous g :=
f.isometry.comp_continuous_iff
include V
/-- The identity affine isometry. -/
def id : P →ᵃⁱ[𝕜] P := ⟨affine_map.id 𝕜 P, λ x, rfl⟩
@[simp] lemma coe_id : ⇑(id : P →ᵃⁱ[𝕜] P) = _root_.id := rfl
@[simp] lemma id_apply (x : P) : (affine_isometry.id : P →ᵃⁱ[𝕜] P) x = x := rfl
@[simp] lemma id_to_affine_map : (id.to_affine_map : P →ᵃ[𝕜] P) = affine_map.id 𝕜 P := rfl
instance : inhabited (P →ᵃⁱ[𝕜] P) := ⟨id⟩
include V₂ V₃
/-- Composition of affine isometries. -/
def comp (g : P₂ →ᵃⁱ[𝕜] P₃) (f : P →ᵃⁱ[𝕜] P₂) : P →ᵃⁱ[𝕜] P₃ :=
⟨g.to_affine_map.comp f.to_affine_map, λ x, (g.norm_map _).trans (f.norm_map _)⟩
@[simp] lemma coe_comp (g : P₂ →ᵃⁱ[𝕜] P₃) (f : P →ᵃⁱ[𝕜] P₂) :
⇑(g.comp f) = g ∘ f :=
rfl
omit V V₂ V₃
@[simp] lemma id_comp : (id : P₂ →ᵃⁱ[𝕜] P₂).comp f = f := ext $ λ x, rfl
@[simp] lemma comp_id : f.comp id = f := ext $ λ x, rfl
include V V₂ V₃ V₄
lemma comp_assoc (f : P₃ →ᵃⁱ[𝕜] P₄) (g : P₂ →ᵃⁱ[𝕜] P₃) (h : P →ᵃⁱ[𝕜] P₂) :
(f.comp g).comp h = f.comp (g.comp h) :=
rfl
omit V₂ V₃ V₄
instance : monoid (P →ᵃⁱ[𝕜] P) :=
{ one := id,
mul := comp,
mul_assoc := comp_assoc,
one_mul := id_comp,
mul_one := comp_id }
@[simp] lemma coe_one : ⇑(1 : P →ᵃⁱ[𝕜] P) = _root_.id := rfl
@[simp] lemma coe_mul (f g : P →ᵃⁱ[𝕜] P) : ⇑(f * g) = f ∘ g := rfl
end affine_isometry
namespace affine_subspace
include V
/-- `affine_subspace.subtype` as an `affine_isometry`. -/
def subtypeₐᵢ (s : affine_subspace 𝕜 P) [nonempty s] : s →ᵃⁱ[𝕜] P :=
{ norm_map := s.direction.subtypeₗᵢ.norm_map,
.. s.subtype }
lemma subtypeₐᵢ_linear (s : affine_subspace 𝕜 P) [nonempty s] :
s.subtypeₐᵢ.linear = s.direction.subtype :=
rfl
@[simp] lemma subtypeₐᵢ_linear_isometry (s : affine_subspace 𝕜 P) [nonempty s] :
s.subtypeₐᵢ.linear_isometry = s.direction.subtypeₗᵢ :=
rfl
@[simp] lemma coe_subtypeₐᵢ (s : affine_subspace 𝕜 P) [nonempty s] : ⇑s.subtypeₐᵢ = s.subtype :=
rfl
@[simp] lemma subtypeₐᵢ_to_affine_map (s : affine_subspace 𝕜 P) [nonempty s] :
s.subtypeₐᵢ.to_affine_map = s.subtype :=
rfl
end affine_subspace
variables (𝕜 P P₂)
include V V₂
/-- A affine isometric equivalence between two normed vector spaces. -/
structure affine_isometry_equiv extends P ≃ᵃ[𝕜] P₂ :=
(norm_map : ∀ x, ‖linear x‖ = ‖x‖)
variables {𝕜 P P₂}
omit V V₂
-- `≃ᵃᵢ` would be more consistent with the linear isometry equiv notation, but it is uglier
notation P ` ≃ᵃⁱ[`:25 𝕜:25 `] `:0 P₂:0 := affine_isometry_equiv 𝕜 P P₂
namespace affine_isometry_equiv
variables (e : P ≃ᵃⁱ[𝕜] P₂)
/-- The underlying linear equiv of an affine isometry equiv is in fact a linear isometry equiv. -/
protected def linear_isometry_equiv : V ≃ₗᵢ[𝕜] V₂ :=
{ norm_map' := e.norm_map,
.. e.linear }
@[simp] lemma linear_eq_linear_isometry : e.linear = e.linear_isometry_equiv.to_linear_equiv :=
by { ext, refl }
include V V₂
instance : has_coe_to_fun (P ≃ᵃⁱ[𝕜] P₂) (λ _, P → P₂) := ⟨λ f, f.to_fun⟩
@[simp] lemma coe_mk (e : P ≃ᵃ[𝕜] P₂) (he : ∀ x, ‖e.linear x‖ = ‖x‖) :
⇑(mk e he) = e :=
rfl
@[simp] lemma coe_to_affine_equiv (e : P ≃ᵃⁱ[𝕜] P₂) : ⇑e.to_affine_equiv = e := rfl
lemma to_affine_equiv_injective : injective (to_affine_equiv : (P ≃ᵃⁱ[𝕜] P₂) → (P ≃ᵃ[𝕜] P₂))
| ⟨e, _⟩ ⟨_, _⟩ rfl := rfl
@[ext] lemma ext {e e' : P ≃ᵃⁱ[𝕜] P₂} (h : ∀ x, e x = e' x) : e = e' :=
to_affine_equiv_injective $ affine_equiv.ext h
omit V V₂
/-- Reinterpret a `affine_isometry_equiv` as a `affine_isometry`. -/
def to_affine_isometry : P →ᵃⁱ[𝕜] P₂ := ⟨e.1.to_affine_map, e.2⟩
@[simp] lemma coe_to_affine_isometry : ⇑e.to_affine_isometry = e := rfl
/-- Construct an affine isometry 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 isometry
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₁ ≃ₗᵢ[𝕜] V₂) (p : P₁) (h : ∀ p' : P₁, e p' = e' (p' -ᵥ p) +ᵥ e p) :
P₁ ≃ᵃⁱ[𝕜] P₂ :=
{ norm_map := e'.norm_map,
.. affine_equiv.mk' e e'.to_linear_equiv p h }
@[simp] lemma coe_mk' (e : P₁ → P₂) (e' : V₁ ≃ₗᵢ[𝕜] V₂) (p h) : ⇑(mk' e e' p h) = e := rfl
@[simp] lemma linear_isometry_equiv_mk' (e : P₁ → P₂) (e' : V₁ ≃ₗᵢ[𝕜] V₂) (p h) :
(mk' e e' p h).linear_isometry_equiv = e' := by { ext, refl }
end affine_isometry_equiv
namespace linear_isometry_equiv
variables (e : V ≃ₗᵢ[𝕜] V₂)
/-- Reinterpret a linear isometry equiv as an affine isometry equiv. -/
def to_affine_isometry_equiv : V ≃ᵃⁱ[𝕜] V₂ :=
{ norm_map := e.norm_map,
.. e.to_linear_equiv.to_affine_equiv }
@[simp] lemma coe_to_affine_isometry_equiv : ⇑(e.to_affine_isometry_equiv : V ≃ᵃⁱ[𝕜] V₂) = e := rfl
@[simp] lemma to_affine_isometry_equiv_linear_isometry_equiv :
e.to_affine_isometry_equiv.linear_isometry_equiv = e :=
by { ext, refl }
-- somewhat arbitrary choice of simp direction
@[simp] lemma to_affine_isometry_equiv_to_affine_equiv :
e.to_affine_isometry_equiv.to_affine_equiv = e.to_linear_equiv.to_affine_equiv :=
rfl
-- somewhat arbitrary choice of simp direction
@[simp] lemma to_affine_isometry_equiv_to_affine_isometry :
e.to_affine_isometry_equiv.to_affine_isometry = e.to_linear_isometry.to_affine_isometry :=
rfl
end linear_isometry_equiv
namespace affine_isometry_equiv
variables (e : P ≃ᵃⁱ[𝕜] P₂)
protected lemma isometry : isometry e := e.to_affine_isometry.isometry
/-- Reinterpret a `affine_isometry_equiv` as an `isometric`. -/
def to_isometric : P ≃ᵢ P₂ := ⟨e.to_affine_equiv.to_equiv, e.isometry⟩
@[simp] lemma coe_to_isometric : ⇑e.to_isometric = e := rfl
include V V₂
lemma range_eq_univ (e : P ≃ᵃⁱ[𝕜] P₂) : set.range e = set.univ :=
by { rw ← coe_to_isometric, exact isometric.range_eq_univ _, }
omit V V₂
/-- Reinterpret a `affine_isometry_equiv` as an `homeomorph`. -/
def to_homeomorph : P ≃ₜ P₂ := e.to_isometric.to_homeomorph
@[simp] lemma coe_to_homeomorph : ⇑e.to_homeomorph = e := rfl
protected lemma continuous : continuous e := e.isometry.continuous
protected lemma continuous_at {x} : continuous_at e x := e.continuous.continuous_at
protected lemma continuous_on {s} : continuous_on e s := e.continuous.continuous_on
protected lemma continuous_within_at {s x} : continuous_within_at e s x :=
e.continuous.continuous_within_at
variables (𝕜 P)
include V
/-- Identity map as a `affine_isometry_equiv`. -/
def refl : P ≃ᵃⁱ[𝕜] P := ⟨affine_equiv.refl 𝕜 P, λ x, rfl⟩
variables {𝕜 P}
instance : inhabited (P ≃ᵃⁱ[𝕜] P) := ⟨refl 𝕜 P⟩
@[simp] lemma coe_refl : ⇑(refl 𝕜 P) = id := rfl
@[simp] lemma to_affine_equiv_refl : (refl 𝕜 P).to_affine_equiv = affine_equiv.refl 𝕜 P := rfl
@[simp] lemma to_isometric_refl : (refl 𝕜 P).to_isometric = isometric.refl P := rfl
@[simp] lemma to_homeomorph_refl : (refl 𝕜 P).to_homeomorph = homeomorph.refl P := rfl
omit V
/-- The inverse `affine_isometry_equiv`. -/
def symm : P₂ ≃ᵃⁱ[𝕜] P :=
{ norm_map := e.linear_isometry_equiv.symm.norm_map,
.. e.to_affine_equiv.symm }
@[simp] lemma apply_symm_apply (x : P₂) : e (e.symm x) = x := e.to_affine_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (x : P) : e.symm (e x) = x := e.to_affine_equiv.symm_apply_apply x
@[simp] lemma symm_symm : e.symm.symm = e := ext $ λ x, rfl
@[simp] lemma to_affine_equiv_symm : e.to_affine_equiv.symm = e.symm.to_affine_equiv := rfl
@[simp] lemma to_isometric_symm : e.to_isometric.symm = e.symm.to_isometric := rfl
@[simp] lemma to_homeomorph_symm : e.to_homeomorph.symm = e.symm.to_homeomorph := rfl
include V₃
/-- Composition of `affine_isometry_equiv`s as a `affine_isometry_equiv`. -/
def trans (e' : P₂ ≃ᵃⁱ[𝕜] P₃) : P ≃ᵃⁱ[𝕜] P₃ :=
⟨e.to_affine_equiv.trans e'.to_affine_equiv, λ x, (e'.norm_map _).trans (e.norm_map _)⟩
include V V₂
@[simp] lemma coe_trans (e₁ : P ≃ᵃⁱ[𝕜] P₂) (e₂ : P₂ ≃ᵃⁱ[𝕜] P₃) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl
omit V V₂ V₃
@[simp] lemma trans_refl : e.trans (refl 𝕜 P₂) = e := ext $ λ x, rfl
@[simp] lemma refl_trans : (refl 𝕜 P).trans e = e := ext $ λ x, rfl
@[simp] lemma self_trans_symm : e.trans e.symm = refl 𝕜 P := ext e.symm_apply_apply
@[simp] lemma symm_trans_self : e.symm.trans e = refl 𝕜 P₂ := ext e.apply_symm_apply
include V V₂ V₃
@[simp] lemma coe_symm_trans (e₁ : P ≃ᵃⁱ[𝕜] P₂) (e₂ : P₂ ≃ᵃⁱ[𝕜] P₃) :
⇑(e₁.trans e₂).symm = e₁.symm ∘ e₂.symm :=
rfl
include V₄
lemma trans_assoc (ePP₂ : P ≃ᵃⁱ[𝕜] P₂) (eP₂G : P₂ ≃ᵃⁱ[𝕜] P₃) (eGG' : P₃ ≃ᵃⁱ[𝕜] P₄) :
ePP₂.trans (eP₂G.trans eGG') = (ePP₂.trans eP₂G).trans eGG' :=
rfl
omit V₂ V₃ V₄
/-- The group of affine isometries of a `normed_add_torsor`, `P`. -/
instance : group (P ≃ᵃⁱ[𝕜] P) :=
{ mul := λ e₁ e₂, e₂.trans e₁,
one := refl _ _,
inv := symm,
one_mul := trans_refl,
mul_one := refl_trans,
mul_assoc := λ _ _ _, trans_assoc _ _ _,
mul_left_inv := self_trans_symm }
@[simp] lemma coe_one : ⇑(1 : P ≃ᵃⁱ[𝕜] P) = id := rfl
@[simp] lemma coe_mul (e e' : P ≃ᵃⁱ[𝕜] P) : ⇑(e * e') = e ∘ e' := rfl
@[simp] lemma coe_inv (e : P ≃ᵃⁱ[𝕜] P) : ⇑(e⁻¹) = e.symm := rfl
omit V
@[simp] lemma map_vadd (p : P) (v : V) : e (v +ᵥ p) = e.linear_isometry_equiv v +ᵥ e p :=
e.to_affine_isometry.map_vadd p v
@[simp] lemma map_vsub (p1 p2 : P) : e.linear_isometry_equiv (p1 -ᵥ p2) = e p1 -ᵥ e p2 :=
e.to_affine_isometry.map_vsub p1 p2
@[simp] lemma dist_map (x y : P) : dist (e x) (e y) = dist x y :=
e.to_affine_isometry.dist_map x y
@[simp] lemma edist_map (x y : P) : edist (e x) (e y) = edist x y :=
e.to_affine_isometry.edist_map x y
protected lemma bijective : bijective e := e.1.bijective
protected lemma injective : injective e := e.1.injective
protected lemma surjective : surjective e := e.1.surjective
@[simp] lemma map_eq_iff {x y : P} : e x = e y ↔ x = y := e.injective.eq_iff
lemma map_ne {x y : P} (h : x ≠ y) : e x ≠ e y := e.injective.ne h
protected lemma lipschitz : lipschitz_with 1 e := e.isometry.lipschitz
protected lemma antilipschitz : antilipschitz_with 1 e := e.isometry.antilipschitz
@[simp] lemma ediam_image (s : set P) : emetric.diam (e '' s) = emetric.diam s :=
e.isometry.ediam_image s
@[simp] lemma diam_image (s : set P) : metric.diam (e '' s) = metric.diam s :=
e.isometry.diam_image s
variables {α : Type*} [topological_space α]
@[simp] lemma comp_continuous_on_iff {f : α → P} {s : set α} :
continuous_on (e ∘ f) s ↔ continuous_on f s :=
e.isometry.comp_continuous_on_iff
@[simp] lemma comp_continuous_iff {f : α → P} :
continuous (e ∘ f) ↔ continuous f :=
e.isometry.comp_continuous_iff
section constructions
variables (𝕜)
/-- The map `v ↦ v +ᵥ p` as an affine isometric equivalence between `V` and `P`. -/
def vadd_const (p : P) : V ≃ᵃⁱ[𝕜] P :=
{ norm_map := λ x, rfl,
.. affine_equiv.vadd_const 𝕜 p }
variables {𝕜}
include V
@[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
@[simp] lemma vadd_const_to_affine_equiv (p : P) :
(vadd_const 𝕜 p).to_affine_equiv = affine_equiv.vadd_const 𝕜 p :=
rfl
omit V
variables (𝕜)
/-- `p' ↦ p -ᵥ p'` as an affine isometric equivalence. -/
def const_vsub (p : P) : P ≃ᵃⁱ[𝕜] V :=
{ norm_map := norm_neg,
.. affine_equiv.const_vsub 𝕜 p }
variables {𝕜}
include V
@[simp] lemma coe_const_vsub (p : P) : ⇑(const_vsub 𝕜 p) = (-ᵥ) p := rfl
@[simp] lemma symm_const_vsub (p : P) :
(const_vsub 𝕜 p).symm
= (linear_isometry_equiv.neg 𝕜).to_affine_isometry_equiv.trans (vadd_const 𝕜 p) :=
by { ext, refl }
omit V
variables (𝕜 P)
/-- Translation by `v` (that is, the map `p ↦ v +ᵥ p`) as an affine isometric automorphism of `P`.
-/
def const_vadd (v : V) : P ≃ᵃⁱ[𝕜] P :=
{ norm_map := λ x, rfl,
.. affine_equiv.const_vadd 𝕜 P v }
variables {𝕜 P}
@[simp] lemma coe_const_vadd (v : V) : ⇑(const_vadd 𝕜 P v : P ≃ᵃⁱ[𝕜] P) = (+ᵥ) v := rfl
@[simp] lemma const_vadd_zero : const_vadd 𝕜 P (0:V) = refl 𝕜 P := ext $ zero_vadd V
include 𝕜 V
/-- The map `g` from `V` to `V₂` corresponding to a map `f` from `P` to `P₂`, at a base point `p`,
is an isometry if `f` is one. -/
lemma vadd_vsub {f : P → P₂} (hf : isometry f) {p : P} {g : V → V₂}
(hg : ∀ v, g v = f (v +ᵥ p) -ᵥ f p) : isometry g :=
begin
convert (vadd_const 𝕜 (f p)).symm.isometry.comp (hf.comp (vadd_const 𝕜 p).isometry),
exact funext hg
end
omit 𝕜
variables (𝕜)
/-- Point reflection in `x` as an affine isometric automorphism. -/
def point_reflection (x : P) : P ≃ᵃⁱ[𝕜] P := (const_vsub 𝕜 x).trans (vadd_const 𝕜 x)
variables {𝕜}
lemma point_reflection_apply (x y : P) : (point_reflection 𝕜 x) y = x -ᵥ y +ᵥ x := rfl
@[simp] lemma point_reflection_to_affine_equiv (x : P) :
(point_reflection 𝕜 x).to_affine_equiv = affine_equiv.point_reflection 𝕜 x := rfl
@[simp] lemma point_reflection_self (x : P) : point_reflection 𝕜 x x = x :=
affine_equiv.point_reflection_self 𝕜 x
lemma point_reflection_involutive (x : P) : function.involutive (point_reflection 𝕜 x) :=
equiv.point_reflection_involutive x
@[simp] lemma point_reflection_symm (x : P) : (point_reflection 𝕜 x).symm = point_reflection 𝕜 x :=
to_affine_equiv_injective $ affine_equiv.point_reflection_symm 𝕜 x
@[simp] lemma dist_point_reflection_fixed (x y : P) :
dist (point_reflection 𝕜 x y) x = dist y x :=
by rw [← (point_reflection 𝕜 x).dist_map y x, point_reflection_self]
lemma dist_point_reflection_self' (x y : P) :
dist (point_reflection 𝕜 x y) y = ‖bit0 (x -ᵥ y)‖ :=
by rw [point_reflection_apply, dist_eq_norm_vsub V, vadd_vsub_assoc, bit0]
lemma dist_point_reflection_self (x y : P) :
dist (point_reflection 𝕜 x y) y = ‖(2:𝕜)‖ * dist x y :=
by rw [dist_point_reflection_self', ← two_smul' 𝕜 (x -ᵥ y), norm_smul, ← dist_eq_norm_vsub V]
lemma point_reflection_fixed_iff [invertible (2:𝕜)] {x y : P} :
point_reflection 𝕜 x y = y ↔ y = x :=
affine_equiv.point_reflection_fixed_iff_of_module 𝕜
variables [normed_space ℝ V]
lemma dist_point_reflection_self_real (x y : P) :
dist (point_reflection ℝ x y) y = 2 * dist x y :=
by { rw [dist_point_reflection_self, real.norm_two] }
@[simp] lemma point_reflection_midpoint_left (x y : P) :
point_reflection ℝ (midpoint ℝ x y) x = y :=
affine_equiv.point_reflection_midpoint_left x y
@[simp] lemma point_reflection_midpoint_right (x y : P) :
point_reflection ℝ (midpoint ℝ x y) y = x :=
affine_equiv.point_reflection_midpoint_right x y
end constructions
end affine_isometry_equiv
include V V₂
/-- If `f` is an affine map, then its linear part is continuous iff `f` is continuous. -/
lemma affine_map.continuous_linear_iff {f : P →ᵃ[𝕜] P₂} :
continuous f.linear ↔ continuous f :=
begin
inhabit P,
have : (f.linear : V → V₂) =
(affine_isometry_equiv.vadd_const 𝕜 $ f default).to_homeomorph.symm ∘ f ∘
(affine_isometry_equiv.vadd_const 𝕜 default).to_homeomorph,
{ ext v, simp },
rw this,
simp only [homeomorph.comp_continuous_iff, homeomorph.comp_continuous_iff'],
end
/-- If `f` is an affine map, then its linear part is an open map iff `f` is an open map. -/
lemma affine_map.is_open_map_linear_iff {f : P →ᵃ[𝕜] P₂} :
is_open_map f.linear ↔ is_open_map f :=
begin
inhabit P,
have : (f.linear : V → V₂) =
(affine_isometry_equiv.vadd_const 𝕜 $ f default).to_homeomorph.symm ∘ f ∘
(affine_isometry_equiv.vadd_const 𝕜 default).to_homeomorph,
{ ext v, simp },
rw this,
simp only [homeomorph.comp_is_open_map_iff, homeomorph.comp_is_open_map_iff'],
end
local attribute [instance, nolint fails_quickly] affine_subspace.nonempty_map
include V₁
omit V
namespace affine_subspace
/--
An affine subspace is isomorphic to its image under an injective affine map.
This is the affine version of `submodule.equiv_map_of_injective`.
-/
@[simps]
noncomputable def equiv_map_of_injective (E: affine_subspace 𝕜 P₁) [nonempty E]
(φ : P₁ →ᵃ[𝕜] P₂) (hφ : function.injective φ) : E ≃ᵃ[𝕜] E.map φ :=
{ linear :=
(E.direction.equiv_map_of_injective φ.linear (φ.linear_injective_iff.mpr hφ)).trans
(linear_equiv.of_eq _ _ (affine_subspace.map_direction _ _).symm),
map_vadd' := λ p v, subtype.ext $ φ.map_vadd p v,
.. equiv.set.image _ (E : set P₁) hφ }
/--
Restricts an affine isometry to an affine isometry equivalence between a nonempty affine
subspace `E` and its image.
This is an isometry version of `affine_subspace.equiv_map`, having a stronger premise and a stronger
conclusion.
-/
noncomputable def isometry_equiv_map
(φ : P₁ →ᵃⁱ[𝕜] P₂) (E : affine_subspace 𝕜 P₁) [nonempty E] : E ≃ᵃⁱ[𝕜] E.map φ.to_affine_map :=
⟨E.equiv_map_of_injective φ.to_affine_map φ.injective, (λ _, φ.norm_map _)⟩
@[simp]
lemma isometry_equiv_map.apply_symm_apply
{E : affine_subspace 𝕜 P₁} [nonempty E]
{φ : P₁ →ᵃⁱ[𝕜] P₂} (x : E.map φ.to_affine_map) :
φ ((E.isometry_equiv_map φ).symm x) = x :=
congr_arg coe $ (E.isometry_equiv_map φ).apply_symm_apply _
@[simp]
lemma isometry_equiv_map.coe_apply
(φ : P₁ →ᵃⁱ[𝕜] P₂) (E : affine_subspace 𝕜 P₁) [nonempty E] (g: E) :
↑(E.isometry_equiv_map φ g) = φ g := rfl
@[simp]
lemma isometry_equiv_map.to_affine_map_eq
(φ : P₁ →ᵃⁱ[𝕜] P₂) (E : affine_subspace 𝕜 P₁) [nonempty E] :
(E.isometry_equiv_map φ).to_affine_map = E.equiv_map_of_injective φ.to_affine_map φ.injective :=
rfl
end affine_subspace
|
b81399e9b3c74bfeece78f7f4e05daa954534fa7 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/ring/ulift_auto.lean | b548f18219cb3a6ce585222c68c1473f31ac583c | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,841 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.group.ulift
import Mathlib.data.equiv.ring
import Mathlib.PostPort
universes u u_1
namespace Mathlib
/-!
# `ulift` instances for ring
This file defines instances for ring, semiring and related structures on `ulift` types.
(Recall `ulift α` is just a "copy" of a type `α` in a higher universe.)
We also provide `ulift.ring_equiv : ulift R ≃+* R`.
-/
namespace ulift
protected instance mul_zero_class {α : Type u} [mul_zero_class α] : mul_zero_class (ulift α) :=
mul_zero_class.mk Mul.mul 0 sorry sorry
protected instance distrib {α : Type u} [distrib α] : distrib (ulift α) :=
distrib.mk Mul.mul Add.add sorry sorry
protected instance semiring {α : Type u} [semiring α] : semiring (ulift α) :=
semiring.mk Add.add sorry 0 sorry sorry sorry Mul.mul sorry 1 sorry sorry sorry sorry sorry sorry
/--
The ring equivalence between `ulift α` and `α`.
-/
def ring_equiv {α : Type u} [semiring α] : ulift α ≃+* α :=
ring_equiv.mk down up sorry sorry sorry sorry
protected instance comm_semiring {α : Type u} [comm_semiring α] : comm_semiring (ulift α) :=
comm_semiring.mk Add.add sorry 0 sorry sorry sorry Mul.mul sorry 1 sorry sorry sorry sorry sorry
sorry sorry
protected instance ring {α : Type u} [ring α] : ring (ulift α) :=
ring.mk Add.add sorry 0 sorry sorry Neg.neg Sub.sub sorry sorry Mul.mul sorry 1 sorry sorry sorry
sorry
protected instance comm_ring {α : Type u} [comm_ring α] : comm_ring (ulift α) :=
comm_ring.mk Add.add sorry 0 sorry sorry Neg.neg Sub.sub sorry sorry Mul.mul sorry 1 sorry sorry
sorry sorry sorry
end Mathlib |
99570c91894ad4d7aec010ba3b16f719143d75cf | b7f22e51856f4989b970961f794f1c435f9b8f78 | /hott/algebra/group_theory.hlean | 0d8447579a6dd75242a83110830a402187ef4f63 | [
"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 | 13,416 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Basic group theory
This file will be rewritten in the future, when we develop are more systematic notation for
describing homomorphisms
-/
import algebra.category.category algebra.hott
open eq algebra pointed function is_trunc pi category equiv is_equiv
set_option class.force_new true
namespace group
definition pointed_Group [instance] [constructor] (G : Group) : pointed G :=
pointed.mk 1
definition pType_of_Group [constructor] [reducible] (G : Group) : Type* :=
pointed.MK G 1
definition Set_of_Group [constructor] (G : Group) : Set := trunctype.mk G _
definition Group_of_CommGroup [coercion] [constructor] (G : CommGroup) : Group :=
Group.mk G _
definition comm_group_Group_of_CommGroup [instance] [constructor] [priority 900]
(G : CommGroup) : comm_group (Group_of_CommGroup G) :=
begin esimp, exact _ end
definition group_pType_of_Group [instance] [priority 900] (G : Group) :
group (pType_of_Group G) :=
Group.struct G
/- group homomorphisms -/
definition is_homomorphism [class] [reducible]
{G₁ G₂ : Type} [group G₁] [group G₂] (φ : G₁ → G₂) : Type :=
Π(g h : G₁), φ (g * h) = φ g * φ h
section
variables {G G₁ G₂ G₃ : Type} {g h : G₁} (ψ : G₂ → G₃) {φ₁ φ₂ : G₁ → G₂} (φ : G₁ → G₂)
[group G] [group G₁] [group G₂] [group G₃]
[is_homomorphism ψ] [is_homomorphism φ₁] [is_homomorphism φ₂] [is_homomorphism φ]
definition respect_mul /- φ -/ : Π(g h : G₁), φ (g * h) = φ g * φ h :=
by assumption
theorem respect_one /- φ -/ : φ 1 = 1 :=
mul.right_cancel
(calc
φ 1 * φ 1 = φ (1 * 1) : respect_mul φ
... = φ 1 : ap φ !one_mul
... = 1 * φ 1 : one_mul)
theorem respect_inv /- φ -/ (g : G₁) : φ g⁻¹ = (φ g)⁻¹ :=
eq_inv_of_mul_eq_one (!respect_mul⁻¹ ⬝ ap φ !mul.left_inv ⬝ !respect_one)
definition is_embedding_homomorphism /- φ -/ (H : Π{g}, φ g = 1 → g = 1) : is_embedding φ :=
begin
apply function.is_embedding_of_is_injective,
intro g g' p,
apply eq_of_mul_inv_eq_one,
apply H,
refine !respect_mul ⬝ _,
rewrite [respect_inv φ, p],
apply mul.right_inv
end
definition is_homomorphism_compose {ψ : G₂ → G₃} {φ : G₁ → G₂}
(H1 : is_homomorphism ψ) (H2 : is_homomorphism φ) : is_homomorphism (ψ ∘ φ) :=
λg h, ap ψ !respect_mul ⬝ !respect_mul
definition is_homomorphism_id (G : Type) [group G] : is_homomorphism (@id G) :=
λg h, idp
end
section additive
definition is_add_homomorphism [class] [reducible] {G₁ G₂ : Type} [add_group G₁] [add_group G₂]
(φ : G₁ → G₂) : Type :=
Π(g h : G₁), φ (g + h) = φ g + φ h
variables {G₁ G₂ : Type} (φ : G₁ → G₂) [add_group G₁] [add_group G₂] [is_add_homomorphism φ]
definition respect_add /- φ -/ : Π(g h : G₁), φ (g + h) = φ g + φ h :=
by assumption
theorem respect_zero /- φ -/ : φ 0 = 0 :=
add.right_cancel
(calc
φ 0 + φ 0 = φ (0 + 0) : respect_add φ
... = φ 0 : ap φ !zero_add
... = 0 + φ 0 : zero_add)
theorem respect_neg /- φ -/ (g : G₁) : φ (-g) = -(φ g) :=
eq_neg_of_add_eq_zero (!respect_add⁻¹ ⬝ ap φ !add.left_inv ⬝ !respect_zero)
end additive
structure homomorphism (G₁ G₂ : Group) : Type :=
(φ : G₁ → G₂)
(p : is_homomorphism φ)
infix ` →g `:55 := homomorphism
definition group_fun [unfold 3] [coercion] := @homomorphism.φ
definition homomorphism.struct [instance] [priority 900] {G₁ : Group} {G₂ : Group} (φ : G₁ →g G₂)
: is_homomorphism φ :=
homomorphism.p φ
definition homomorphism.mulstruct [instance] [priority 2000] {G₁ G₂ : Group } (φ : G₁ →g G₂)
: is_homomorphism φ :=
homomorphism.p φ
definition homomorphism.addstruct [instance] [priority 2000] {G₁ G₂ : AddGroup} (φ : G₁ →g G₂)
: is_add_homomorphism φ :=
homomorphism.p φ
variables {G G₁ G₂ G₃ : Group} {g h : G₁} {ψ : G₂ →g G₃} {φ₁ φ₂ : G₁ →g G₂} (φ : G₁ →g G₂)
definition to_respect_mul /- φ -/ (g h : G₁) : φ (g * h) = φ g * φ h :=
respect_mul φ g h
theorem to_respect_one /- φ -/ : φ 1 = 1 :=
respect_one φ
theorem to_respect_inv /- φ -/ (g : G₁) : φ g⁻¹ = (φ g)⁻¹ :=
respect_inv φ g
definition to_is_embedding_homomorphism /- φ -/ (H : Π{g}, φ g = 1 → g = 1) : is_embedding φ :=
is_embedding_homomorphism φ @H
variables (G₁ G₂)
definition is_set_homomorphism [instance] : is_set (G₁ →g G₂) :=
begin
have H : G₁ →g G₂ ≃ Σ(f : G₁ → G₂), Π(g₁ g₂ : G₁), f (g₁ * g₂) = f g₁ * f g₂,
begin
fapply equiv.MK,
{ intro φ, induction φ, constructor, assumption},
{ intro v, induction v, constructor, assumption},
{ intro v, induction v, reflexivity},
{ intro φ, induction φ, reflexivity}
end,
apply is_trunc_equiv_closed_rev, exact H
end
variables {G₁ G₂}
definition pmap_of_homomorphism [constructor] /- φ -/ : pType_of_Group G₁ →* pType_of_Group G₂ :=
pmap.mk φ begin esimp, exact respect_one φ end
definition homomorphism_eq (p : group_fun φ₁ ~ group_fun φ₂) : φ₁ = φ₂ :=
begin
induction φ₁ with φ₁ q₁, induction φ₂ with φ₂ q₂, esimp at p, induction p,
exact ap (homomorphism.mk φ₁) !is_prop.elim
end
section additive
variables {H₁ H₂ : AddGroup} (χ : H₁ →g H₂)
definition to_respect_add /- χ -/ (g h : H₁) : χ (g + h) = χ g + χ h :=
respect_add χ g h
theorem to_respect_zero /- χ -/ : χ 0 = 0 :=
respect_zero χ
theorem to_respect_neg /- χ -/ (g : H₁) : χ (-g) = -(χ g) :=
respect_neg χ g
end additive
section add_mul
variables {H₁ : AddGroup} {H₂ : Group} (χ : H₁ →g H₂)
definition to_respect_add_mul /- χ -/ (g h : H₁) : χ (g + h) = χ g * χ h :=
to_respect_mul χ g h
theorem to_respect_zero_one /- χ -/ : χ 0 = 1 :=
to_respect_one χ
theorem to_respect_neg_inv /- χ -/ (g : H₁) : χ (-g) = (χ g)⁻¹ :=
to_respect_inv χ g
end add_mul
section mul_add
variables {H₁ : Group} {H₂ : AddGroup} (χ : H₁ →g H₂)
definition to_respect_mul_add /- χ -/ (g h : H₁) : χ (g * h) = χ g + χ h :=
to_respect_mul χ g h
theorem to_respect_one_zero /- χ -/ : χ 1 = 0 :=
to_respect_one χ
theorem to_respect_inv_neg /- χ -/ (g : H₁) : χ g⁻¹ = -(χ g) :=
to_respect_inv χ g
end mul_add
/- categorical structure of groups + homomorphisms -/
definition homomorphism_compose [constructor] [trans] (ψ : G₂ →g G₃) (φ : G₁ →g G₂) : G₁ →g G₃ :=
homomorphism.mk (ψ ∘ φ) (is_homomorphism_compose _ _)
variable (G)
definition homomorphism_id [constructor] [refl] : G →g G :=
homomorphism.mk (@id G) (is_homomorphism_id G)
variable {G}
infixr ` ∘g `:75 := homomorphism_compose
notation 1 := homomorphism_id _
structure isomorphism (A B : Group) :=
(to_hom : A →g B)
(is_equiv_to_hom : is_equiv to_hom)
infix ` ≃g `:25 := isomorphism
attribute isomorphism.to_hom [coercion]
attribute isomorphism.is_equiv_to_hom [instance]
definition equiv_of_isomorphism [constructor] (φ : G₁ ≃g G₂) : G₁ ≃ G₂ :=
equiv.mk φ _
definition pequiv_of_isomorphism [constructor] (φ : G₁ ≃g G₂) :
pType_of_Group G₁ ≃* pType_of_Group G₂ :=
pequiv.mk φ begin esimp, exact _ end begin esimp, exact respect_one φ end
definition isomorphism_of_equiv [constructor] (φ : G₁ ≃ G₂)
(p : Πg₁ g₂, φ (g₁ * g₂) = φ g₁ * φ g₂) : G₁ ≃g G₂ :=
isomorphism.mk (homomorphism.mk φ p) !to_is_equiv
definition eq_of_isomorphism {G₁ G₂ : Group} (φ : G₁ ≃g G₂) : G₁ = G₂ :=
Group_eq (equiv_of_isomorphism φ) (respect_mul φ)
definition isomorphism_of_eq {G₁ G₂ : Group} (φ : G₁ = G₂) : G₁ ≃g G₂ :=
isomorphism_of_equiv (equiv_of_eq (ap Group.carrier φ))
begin intros, induction φ, reflexivity end
definition to_ginv [constructor] (φ : G₁ ≃g G₂) : G₂ →g G₁ :=
homomorphism.mk φ⁻¹
abstract begin
intro g₁ g₂, apply eq_of_fn_eq_fn' φ,
rewrite [respect_mul φ, +right_inv φ]
end end
variable (G)
definition isomorphism.refl [refl] [constructor] : G ≃g G :=
isomorphism.mk 1 !is_equiv_id
variable {G}
definition isomorphism.symm [symm] [constructor] (φ : G₁ ≃g G₂) : G₂ ≃g G₁ :=
isomorphism.mk (to_ginv φ) !is_equiv_inv
definition isomorphism.trans [trans] [constructor] (φ : G₁ ≃g G₂) (ψ : G₂ ≃g G₃) : G₁ ≃g G₃ :=
isomorphism.mk (ψ ∘g φ) !is_equiv_compose
definition isomorphism.eq_trans [trans] [constructor]
{G₁ G₂ : Group} {G₃ : Group} (φ : G₁ = G₂) (ψ : G₂ ≃g G₃) : G₁ ≃g G₃ :=
proof isomorphism.trans (isomorphism_of_eq φ) ψ qed
definition isomorphism.trans_eq [trans] [constructor]
{G₁ : Group} {G₂ G₃ : Group} (φ : G₁ ≃g G₂) (ψ : G₂ = G₃) : G₁ ≃g G₃ :=
isomorphism.trans φ (isomorphism_of_eq ψ)
postfix `⁻¹ᵍ`:(max + 1) := isomorphism.symm
infixl ` ⬝g `:75 := isomorphism.trans
infixl ` ⬝gp `:75 := isomorphism.trans_eq
infixl ` ⬝pg `:75 := isomorphism.eq_trans
-- TODO
-- definition Group_univalence (G₁ G₂ : Group) : (G₁ ≃g G₂) ≃ (G₁ = G₂) :=
-- begin
-- fapply equiv.MK,
-- { exact eq_of_isomorphism},
-- { intro p, apply transport _ p, reflexivity},
-- { intro p, induction p, esimp, },
-- { }
-- end
/- category of groups -/
definition precategory_group [constructor] : precategory Group :=
precategory.mk homomorphism
@homomorphism_compose
@homomorphism_id
(λG₁ G₂ G₃ G₄ φ₃ φ₂ φ₁, homomorphism_eq (λg, idp))
(λG₁ G₂ φ, homomorphism_eq (λg, idp))
(λG₁ G₂ φ, homomorphism_eq (λg, idp))
-- TODO
-- definition category_group : category Group :=
-- category.mk precategory_group
-- begin
-- intro G₁ G₂,
-- fapply adjointify,
-- { intro φ, fapply Group_eq, },
-- { },
-- { }
-- end
/- given an equivalence A ≃ B we can transport a group structure on A to a group structure on B -/
section
parameters {A B : Type} (f : A ≃ B) [group A]
definition group_equiv_mul (b b' : B) : B := f (f⁻¹ᶠ b * f⁻¹ᶠ b')
definition group_equiv_one : B := f one
definition group_equiv_inv (b : B) : B := f (f⁻¹ᶠ b)⁻¹
local infix * := group_equiv_mul
local postfix ^ := group_equiv_inv
local notation 1 := group_equiv_one
theorem group_equiv_mul_assoc (b₁ b₂ b₃ : B) : (b₁ * b₂) * b₃ = b₁ * (b₂ * b₃) :=
by rewrite [↑group_equiv_mul, +left_inv f, mul.assoc]
theorem group_equiv_one_mul (b : B) : 1 * b = b :=
by rewrite [↑group_equiv_mul, ↑group_equiv_one, left_inv f, one_mul, right_inv f]
theorem group_equiv_mul_one (b : B) : b * 1 = b :=
by rewrite [↑group_equiv_mul, ↑group_equiv_one, left_inv f, mul_one, right_inv f]
theorem group_equiv_mul_left_inv (b : B) : b^ * b = 1 :=
by rewrite [↑group_equiv_mul, ↑group_equiv_one, ↑group_equiv_inv,
+left_inv f, mul.left_inv]
definition group_equiv_closed : group B :=
⦃group,
mul := group_equiv_mul,
mul_assoc := group_equiv_mul_assoc,
one := group_equiv_one,
one_mul := group_equiv_one_mul,
mul_one := group_equiv_mul_one,
inv := group_equiv_inv,
mul_left_inv := group_equiv_mul_left_inv,
is_set_carrier := is_trunc_equiv_closed 0 f⦄
end
variable (G)
definition trivial_group_of_is_contr [H : is_contr G] : G ≃g G0 :=
begin
fapply isomorphism_of_equiv,
{ apply equiv_unit_of_is_contr},
{ intros, reflexivity}
end
definition trivial_group_of_is_contr' (G : Group) [H : is_contr G] : G = G0 :=
eq_of_isomorphism (trivial_group_of_is_contr G)
variable {G}
/-
A group where the point in the pointed type corresponds with 1 in the group.
We need this structure when we are given a pointed type, and want to say that there is a group
structure on it which is compatible with the point. This is used in chain complexes.
-/
structure pgroup [class] (X : Type*) extends semigroup X, has_inv X :=
(pt_mul : Πa, mul pt a = a)
(mul_pt : Πa, mul a pt = a)
(mul_left_inv_pt : Πa, mul (inv a) a = pt)
definition group_of_pgroup [reducible] [instance] (X : Type*) [H : pgroup X]
: group X :=
⦃group, H,
one := pt,
one_mul := pgroup.pt_mul ,
mul_one := pgroup.mul_pt,
mul_left_inv := pgroup.mul_left_inv_pt⦄
definition pgroup_of_group (X : Type*) [H : group X] (p : one = pt :> X) : pgroup X :=
begin
cases X with X x, esimp at *, induction p,
exact ⦃pgroup, H,
pt_mul := one_mul,
mul_pt := mul_one,
mul_left_inv_pt := mul.left_inv⦄
end
end group
|
59899737963efe4c24cae60c1f48fe37e9875ab3 | b815abf92ce063fe0d1fabf5b42da483552aa3e8 | /library/data/tuple.lean | 4ef6b354a2111e5940cb43382b53e3e7a179bbf9 | [
"Apache-2.0"
] | permissive | yodalee/lean | a368d842df12c63e9f79414ed7bbee805b9001ef | 317989bf9ef6ae1dec7488c2363dbfcdc16e0756 | refs/heads/master | 1,610,551,176,860 | 1,481,430,138,000 | 1,481,646,441,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,278 | 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
Tuples are lists of a fixed size.
It is implemented as a subtype.
-/
import data.list
def tuple (α : Type) (n : ℕ) := {l : list α // list.length l = n}
namespace tuple
variables {α β φ : Type}
variable {n : ℕ}
instance [decidable_eq α] : decidable_eq (tuple α n) :=
begin unfold tuple, apply_instance end
definition nil : tuple α 0 := ⟨[], rfl⟩
definition cons : α → tuple α n → tuple α (nat.succ n)
| a ⟨ v, h ⟩ := ⟨ a::v, congr_arg nat.succ h ⟩
notation a :: b := cons a b
notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l
open nat
definition head : tuple α (nat.succ n) → α
| ⟨list.nil, h ⟩ := let q : 0 = succ n := h in by contradiction
| ⟨list.cons a v, h ⟩ := a
theorem head_cons (a : α) : Π (v : tuple α n), head (a :: v) = a
| ⟨ l, h ⟩ := rfl
definition tail : tuple α (succ n) → tuple α n
| ⟨ list.nil, h ⟩ := let q : 0 = succ n := h in by contradiction
| ⟨ list.cons a v, h ⟩ := ⟨ v, congr_arg pred h ⟩
theorem tail_cons (a : α) : Π (v : tuple α n), tail (a :: v) = v
| ⟨ l, h ⟩ := rfl
definition to_list : tuple α n → list α | ⟨ l, h ⟩ := l
/- append -/
definition append {n m : nat} : tuple α n → tuple α m → tuple α (n + m)
| ⟨ l₁, h₁ ⟩ ⟨ l₂, h₂ ⟩ :=
let p := calc
list.length (l₁ ++ l₂)
= list.length l₁ + list.length l₂ : list.length_append l₁ l₂
... = n + list.length l₂ : congr_arg (λi, i + list.length l₂) h₁
... = n + m : congr_arg (λi, n + i) h₂ in
⟨ list.append l₁ l₂, p ⟩
/- map -/
definition map (f : α → β) : tuple α n → tuple β n
| ⟨ l, h ⟩ :=
let q := calc list.length (list.map f l) = list.length l : list.length_map f l
... = n : h in
⟨ list.map f l, q ⟩
theorem map_nil (f : α → β) : map f nil = nil := rfl
theorem map_cons (f : α → β) (a : α)
: Π (v : tuple α n), map f (a::v) = f a :: map f v
| ⟨ l, h ⟩ := rfl
definition map₂ (f : α → β → φ) : tuple α n → tuple β n → tuple φ n
| ⟨ x, px ⟩ ⟨ y, py ⟩ :=
let z : list φ := list.map₂ f x y in
let pxx : list.length x = n := px in
let pyy : list.length y = n := py in
let p : list.length z = n := calc
list.length z = min (list.length x) (list.length y) : list.length_map₂ f x y
... = min n n : by rewrite [pxx, pyy]
... = n : min_self n in
⟨ z, p ⟩
definition repeat (a : α) : tuple α n
:= ⟨ list.repeat a n, list.length_repeat a n ⟩
definition dropn : Π (i:ℕ), tuple α n → tuple α (n - i)
| i ⟨ l, p ⟩ := ⟨ list.dropn i l, p ▸ list.length_dropn i l ⟩
definition firstn : Π (i:ℕ) {p:i ≤ n}, tuple α n → tuple α i
| i is_le ⟨ l, p ⟩ :=
let q := calc list.length (list.firstn i l)
= min i (list.length l) : list.length_firstn i l
... = min i n : congr_arg (λ v, min i v) p
... = i : min_eq_left is_le in
⟨list.firstn i l, q⟩
section accum
open prod
variable {σ : Type}
definition map_accumr
: (α → σ → σ × β) → tuple α n → σ → σ × tuple β n
| f ⟨ x, px ⟩ c :=
let z := list.map_accumr f x c in
let p := eq.trans (list.length_map_accumr f x c) px in
(prod.fst z, ⟨ prod.snd z, p ⟩)
definition map_accumr₂
: (α → β → σ → σ × φ) → tuple α n → tuple β n → σ → σ × tuple φ n
| f ⟨ x, px ⟩ ⟨ y, py ⟩ c :=
let z := list.map_accumr₂ f x y c in
let pxx : list.length x = n := px in
let pyy : list.length y = n := py in
let p := calc
list.length (prod.snd (list.map_accumr₂ f x y c))
= min (list.length x) (list.length y) : list.length_map_accumr₂ f x y c
... = n : by rewrite [ pxx, pyy, min_self ] in
(prod.fst z, ⟨prod.snd z, p ⟩)
end accum
end tuple
|
fd1dc19590c919fbdbfef74fae5bc3d2616aa530 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/group_theory/sylow.lean | 496bf7ceee6e2858d76c245e39f15309d3d6b0c9 | [
"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 | 19,405 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Thomas Browning
-/
import group_theory.group_action.conj_act
import group_theory.p_group
/-!
# Sylow theorems
The Sylow theorems are the following results for every finite group `G` and every prime number `p`.
* There exists a Sylow `p`-subgroup of `G`.
* All Sylow `p`-subgroups of `G` are conjugate to each other.
* Let `nₚ` be the number of Sylow `p`-subgroups of `G`, then `nₚ` divides the index of the Sylow
`p`-subgroup, `nₚ ≡ 1 [MOD p]`, and `nₚ` is equal to the index of the normalizer of the Sylow
`p`-subgroup in `G`.
## Main definitions
* `sylow p G` : The type of Sylow `p`-subgroups of `G`.
## Main statements
* `exists_subgroup_card_pow_prime`: A generalization of Sylow's first theorem:
For every prime power `pⁿ` dividing the cardinality of `G`,
there exists a subgroup of `G` of order `pⁿ`.
* `is_p_group.exists_le_sylow`: A generalization of Sylow's first theorem:
Every `p`-subgroup is contained in a Sylow `p`-subgroup.
* `sylow_conjugate`: A generalization of Sylow's second theorem:
If the number of Sylow `p`-subgroups is finite, then all Sylow `p`-subgroups are conjugate.
* `card_sylow_modeq_one`: A generalization of Sylow's third theorem:
If the number of Sylow `p`-subgroups is finite, then it is congruent to `1` modulo `p`.
-/
open fintype mul_action subgroup
section infinite_sylow
variables (p : ℕ) (G : Type*) [group G]
/-- A Sylow `p`-subgroup is a maximal `p`-subgroup. -/
structure sylow extends subgroup G :=
(is_p_group' : is_p_group p to_subgroup)
(is_maximal' : ∀ {Q : subgroup G}, is_p_group p Q → to_subgroup ≤ Q → Q = to_subgroup)
variables {p} {G}
namespace sylow
instance : has_coe (sylow p G) (subgroup G) := ⟨sylow.to_subgroup⟩
@[simp] lemma to_subgroup_eq_coe {P : sylow p G} : P.to_subgroup = ↑P := rfl
@[ext] lemma ext {P Q : sylow p G} (h : (P : subgroup G) = Q) : P = Q :=
by cases P; cases Q; congr'
lemma ext_iff {P Q : sylow p G} : P = Q ↔ (P : subgroup G) = Q :=
⟨congr_arg coe, ext⟩
instance : set_like (sylow p G) G :=
{ coe := coe,
coe_injective' := λ P Q h, ext (set_like.coe_injective h) }
end sylow
/-- A generalization of **Sylow's first theorem**.
Every `p`-subgroup is contained in a Sylow `p`-subgroup. -/
lemma is_p_group.exists_le_sylow {P : subgroup G} (hP : is_p_group p P) :
∃ Q : sylow p G, P ≤ Q :=
exists.elim (zorn.zorn_nonempty_partial_order₀ {Q : subgroup G | is_p_group p Q} (λ c hc1 hc2 Q hQ,
⟨ { carrier := ⋃ (R : c), R,
one_mem' := ⟨Q, ⟨⟨Q, hQ⟩, rfl⟩, Q.one_mem⟩,
inv_mem' := λ g ⟨_, ⟨R, rfl⟩, hg⟩, ⟨R, ⟨R, rfl⟩, R.1.inv_mem hg⟩,
mul_mem' := λ g h ⟨_, ⟨R, rfl⟩, hg⟩ ⟨_, ⟨S, rfl⟩, hh⟩, (hc2.total_of_refl R.2 S.2).elim
(λ T, ⟨S, ⟨S, rfl⟩, S.1.mul_mem (T hg) hh⟩) (λ T, ⟨R, ⟨R, rfl⟩, R.1.mul_mem hg (T hh)⟩) },
λ ⟨g, _, ⟨S, rfl⟩, hg⟩, by
{ refine exists_imp_exists (λ k hk, _) (hc1 S.2 ⟨g, hg⟩),
rwa [subtype.ext_iff, coe_pow] at hk ⊢ },
λ M hM g hg, ⟨M, ⟨⟨M, hM⟩, rfl⟩, hg⟩⟩) P hP) (λ Q ⟨hQ1, hQ2, hQ3⟩, ⟨⟨Q, hQ1, hQ3⟩, hQ2⟩)
instance sylow.nonempty : nonempty (sylow p G) :=
nonempty_of_exists is_p_group.of_bot.exists_le_sylow
noncomputable instance sylow.inhabited : inhabited (sylow p G) :=
classical.inhabited_of_nonempty sylow.nonempty
open_locale pointwise
/-- `subgroup.pointwise_mul_action` preserves Sylow subgroups. -/
instance sylow.pointwise_mul_action {α : Type*} [group α] [mul_distrib_mul_action α G] :
mul_action α (sylow p G) :=
{ smul := λ g P, ⟨g • P, P.2.map _, λ Q hQ hS, inv_smul_eq_iff.mp (P.3 (hQ.map _)
(λ s hs, (congr_arg (∈ g⁻¹ • Q) (inv_smul_smul g s)).mp
(smul_mem_pointwise_smul (g • s) g⁻¹ Q (hS (smul_mem_pointwise_smul s g P hs)))))⟩,
one_smul := λ P, sylow.ext (one_smul α P),
mul_smul := λ g h P, sylow.ext (mul_smul g h P) }
lemma sylow.pointwise_smul_def {α : Type*} [group α] [mul_distrib_mul_action α G]
{g : α} {P : sylow p G} : ↑(g • P) = g • (P : subgroup G) := rfl
instance sylow.mul_action : mul_action G (sylow p G) :=
comp_hom _ mul_aut.conj
lemma sylow.smul_def {g : G} {P : sylow p G} : g • P = mul_aut.conj g • P := rfl
lemma sylow.coe_subgroup_smul {g : G} {P : sylow p G} :
↑(g • P) = mul_aut.conj g • (P : subgroup G) := rfl
lemma sylow.coe_smul {g : G} {P : sylow p G} :
↑(g • P) = mul_aut.conj g • (P : set G) := rfl
lemma sylow.smul_eq_iff_mem_normalizer {g : G} {P : sylow p G} :
g • P = P ↔ g ∈ P.1.normalizer :=
begin
rw [eq_comm, set_like.ext_iff, ←inv_mem_iff, mem_normalizer_iff, inv_inv],
exact forall_congr (λ h, iff_congr iff.rfl ⟨λ ⟨a, b, c⟩, (congr_arg _ c).mp
((congr_arg (∈ P.1) (mul_aut.inv_apply_self G (mul_aut.conj g) a)).mpr b),
λ hh, ⟨(mul_aut.conj g)⁻¹ h, hh, mul_aut.apply_inv_self G (mul_aut.conj g) h⟩⟩),
end
lemma subgroup.sylow_mem_fixed_points_iff (H : subgroup G) {P : sylow p G} :
P ∈ fixed_points H (sylow p G) ↔ H ≤ P.1.normalizer :=
by simp_rw [set_like.le_def, ←sylow.smul_eq_iff_mem_normalizer]; exact subtype.forall
lemma is_p_group.inf_normalizer_sylow {P : subgroup G} (hP : is_p_group p P) (Q : sylow p G) :
P ⊓ Q.1.normalizer = P ⊓ Q :=
le_antisymm (le_inf inf_le_left (sup_eq_right.mp (Q.3 (hP.to_inf_left.to_sup_of_normal_right'
Q.2 inf_le_right) le_sup_right))) (inf_le_inf_left P le_normalizer)
lemma is_p_group.sylow_mem_fixed_points_iff
{P : subgroup G} (hP : is_p_group p P) {Q : sylow p G} :
Q ∈ fixed_points P (sylow p G) ↔ P ≤ Q :=
by rw [P.sylow_mem_fixed_points_iff, ←inf_eq_left, hP.inf_normalizer_sylow, inf_eq_left]
/-- A generalization of **Sylow's second theorem**.
If the number of Sylow `p`-subgroups is finite, then all Sylow `p`-subgroups are conjugate. -/
instance [hp : fact p.prime] [fintype (sylow p G)] : is_pretransitive G (sylow p G) :=
⟨λ P Q, by
{ classical,
have H := λ {R : sylow p G} {S : orbit G P},
calc S ∈ fixed_points R (orbit G P)
↔ S.1 ∈ fixed_points R (sylow p G) : forall_congr (λ a, subtype.ext_iff)
... ↔ R.1 ≤ S : R.2.sylow_mem_fixed_points_iff
... ↔ S.1.1 = R : ⟨λ h, R.3 S.1.2 h, ge_of_eq⟩,
suffices : set.nonempty (fixed_points Q (orbit G P)),
{ exact exists.elim this (λ R hR, (congr_arg _ (sylow.ext (H.mp hR))).mp R.2) },
apply Q.2.nonempty_fixed_point_of_prime_not_dvd_card,
refine λ h, hp.out.not_dvd_one (nat.modeq_zero_iff_dvd.mp _),
calc 1 = card (fixed_points P (orbit G P)) : _
... ≡ card (orbit G P) [MOD p] : (P.2.card_modeq_card_fixed_points (orbit G P)).symm
... ≡ 0 [MOD p] : nat.modeq_zero_iff_dvd.mpr h,
convert (set.card_singleton (⟨P, mem_orbit_self P⟩ : orbit G P)).symm,
exact set.eq_singleton_iff_unique_mem.mpr ⟨H.mpr rfl, λ R h, subtype.ext (sylow.ext (H.mp h))⟩ }⟩
variables (p) (G)
/-- A generalization of **Sylow's third theorem**.
If the number of Sylow `p`-subgroups is finite, then it is congruent to `1` modulo `p`. -/
lemma card_sylow_modeq_one [fact p.prime] [fintype (sylow p G)] : card (sylow p G) ≡ 1 [MOD p] :=
begin
refine sylow.nonempty.elim (λ P : sylow p G, _),
have := set.ext (λ Q : sylow p G, calc Q ∈ fixed_points P (sylow p G)
↔ P.1 ≤ Q : P.2.sylow_mem_fixed_points_iff
... ↔ Q.1 = P.1 : ⟨P.3 Q.2, ge_of_eq⟩
... ↔ Q ∈ {P} : sylow.ext_iff.symm.trans set.mem_singleton_iff.symm),
haveI : fintype (fixed_points P.1 (sylow p G)) := by convert set.fintype_singleton P,
have : card (fixed_points P.1 (sylow p G)) = 1 := by convert set.card_singleton P,
exact (P.2.card_modeq_card_fixed_points (sylow p G)).trans (by rw this),
end
variables {p} {G}
@[simp] lemma sylow.orbit_eq_top [fact p.prime] [fintype (sylow p G)] (P : sylow p G) :
orbit G P = ⊤ :=
top_le_iff.mp (λ Q hQ, exists_smul_eq G P Q)
lemma sylow.stabilizer_eq_normalizer (P : sylow p G) : stabilizer G P = P.1.normalizer :=
ext (λ g, sylow.smul_eq_iff_mem_normalizer)
/-- Sylow `p`-subgroups are in bijection with cosets of the normalizer of a Sylow `p`-subgroup -/
noncomputable def sylow.equiv_quotient_normalizer [fact p.prime] [fintype (sylow p G)]
(P : sylow p G) : sylow p G ≃ quotient_group.quotient P.1.normalizer :=
calc sylow p G ≃ (⊤ : set (sylow p G)) : (equiv.set.univ (sylow p G)).symm
... ≃ orbit G P : by rw P.orbit_eq_top
... ≃ quotient_group.quotient (stabilizer G P) : orbit_equiv_quotient_stabilizer G P
... ≃ quotient_group.quotient P.1.normalizer : by rw P.stabilizer_eq_normalizer
noncomputable instance [fact p.prime] [fintype (sylow p G)] (P : sylow p G) :
fintype (quotient_group.quotient P.1.normalizer) :=
of_equiv (sylow p G) P.equiv_quotient_normalizer
lemma card_sylow_eq_card_quotient_normalizer [fact p.prime] [fintype (sylow p G)] (P : sylow p G) :
card (sylow p G) = card (quotient_group.quotient P.1.normalizer) :=
card_congr P.equiv_quotient_normalizer
lemma card_sylow_eq_index_normalizer [fact p.prime] [fintype (sylow p G)] (P : sylow p G) :
card (sylow p G) = P.1.normalizer.index :=
(card_sylow_eq_card_quotient_normalizer P).trans P.1.normalizer.index_eq_card.symm
lemma card_sylow_dvd_index [fact p.prime] [fintype (sylow p G)] (P : sylow p G) :
card (sylow p G) ∣ P.1.index :=
((congr_arg _ (card_sylow_eq_index_normalizer P)).mp dvd_rfl).trans (index_dvd_of_le le_normalizer)
/-- Frattini's Argument -/
lemma sylow.normalizer_sup_eq_top {p : ℕ} [fact p.prime] {N : subgroup G} [N.normal]
[fintype (sylow p N)] (P : sylow p N) : ((↑P : subgroup N).map N.subtype).normalizer ⊔ N = ⊤ :=
begin
refine top_le_iff.mp (λ g hg, _),
obtain ⟨n, hn⟩ := exists_smul_eq N ((mul_aut.conj_normal g : mul_aut N) • P) P,
rw ← inv_mul_cancel_left ↑n g,
refine mul_mem _ (inv_mem _ (mem_sup_right n.2)) (mem_sup_left _),
rw [sylow.smul_def, ←mul_smul, ←mul_aut.conj_normal_coe, ←mul_aut.conj_normal.map_mul,
sylow.ext_iff, sylow.pointwise_smul_def, pointwise_smul_def] at hn,
refine λ x, (mem_map_iff_mem (show function.injective (mul_aut.conj (↑n * g)).to_monoid_hom,
from (mul_aut.conj (↑n * g)).injective)).symm.trans _,
rw [map_map, ←(congr_arg (map N.subtype) hn), map_map],
refl,
end
end infinite_sylow
open equiv equiv.perm finset function list quotient_group
open_locale big_operators
universes u v w
variables {G : Type u} {α : Type v} {β : Type w} [group G]
local attribute [instance, priority 10] subtype.fintype set_fintype classical.prop_decidable
lemma quotient_group.card_preimage_mk [fintype G] (s : subgroup G)
(t : set (quotient s)) : fintype.card (quotient_group.mk ⁻¹' t) =
fintype.card s * fintype.card t :=
by rw [← fintype.card_prod, fintype.card_congr
(preimage_mk_equiv_subgroup_times_set _ _)]
namespace sylow
open subgroup submonoid mul_action
lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : subgroup G}
[fintype ((H : set G) : Type u)] {x : G} :
(x : quotient H) ∈ fixed_points H (quotient H) ↔ x ∈ normalizer H :=
⟨λ hx, have ha : ∀ {y : quotient H}, y ∈ orbit H (x : quotient H) → y = x,
from λ _, ((mem_fixed_points' _).1 hx _),
(inv_mem_iff _).1 (@mem_normalizer_fintype _ _ _ _inst_2 _ (λ n (hn : n ∈ H),
have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, H.inv_mem hn⟩)),
show _ ∈ H, by {rw [mul_inv_rev, inv_inv] at this, convert this, rw inv_inv}
)),
λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H),
(mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2
(let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in
have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂,
(inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_left H (H.inv_mem hb₁)).1
$ by rw hx at hb₂;
simpa [mul_inv_rev, mul_assoc] using hb₂)⟩
def fixed_points_mul_left_cosets_equiv_quotient (H : subgroup G) [fintype (H : set G)] :
mul_action.fixed_points H (quotient H) ≃
quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) :=
@subtype_quotient_equiv_quotient_subtype G (normalizer H : set G) (id _) (id _) (fixed_points _ _)
(λ a, (@mem_fixed_points_mul_left_cosets_iff_mem_normalizer _ _ _ _inst_2 _).symm)
(by intros; refl)
/-- If `H` is a `p`-subgroup of `G`, then the index of `H` inside its normalizer is congruent
mod `p` to the index of `H`. -/
lemma card_quotient_normalizer_modeq_card_quotient [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
{H : subgroup G} (hH : fintype.card H = p ^ n) :
card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H))
≡ card (quotient H) [MOD p] :=
begin
rw [← fintype.card_congr (fixed_points_mul_left_cosets_equiv_quotient H)],
exact ((is_p_group.of_card hH).card_modeq_card_fixed_points _).symm
end
/-- If `H` is a subgroup of `G` of cardinality `p ^ n`, then the cardinality of the
normalizer of `H` is congruent mod `p ^ (n + 1)` to the cardinality of `G`. -/
lemma card_normalizer_modeq_card [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
{H : subgroup G} (hH : fintype.card H = p ^ n) :
card (normalizer H) ≡ card G [MOD p ^ (n + 1)] :=
have subgroup.comap ((normalizer H).subtype : normalizer H →* G) H ≃ H,
from set.bij_on.equiv (normalizer H).subtype
⟨λ _, id, λ _ _ _ _ h, subtype.val_injective h,
λ x hx, ⟨⟨x, le_normalizer hx⟩, hx, rfl⟩⟩,
begin
rw [card_eq_card_quotient_mul_card_subgroup H,
card_eq_card_quotient_mul_card_subgroup
(subgroup.comap ((normalizer H).subtype : normalizer H →* G) H),
fintype.card_congr this, hH, pow_succ],
exact (card_quotient_normalizer_modeq_card_quotient hH).mul_right' _
end
/-- If `H` is a `p`-subgroup but not a Sylow `p`-subgroup, then `p` divides the
index of `H` inside its normalizer. -/
lemma prime_dvd_card_quotient_normalizer [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
(hdvd : p ^ (n + 1) ∣ card G) {H : subgroup G} (hH : fintype.card H = p ^ n) :
p ∣ card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) :=
let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in
have hcard : card (quotient H) = s * p :=
(nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2
⟨⟨1, H.one_mem⟩⟩)).1
(by rwa [← card_eq_card_quotient_mul_card_subgroup H, hH, hs,
pow_succ', mul_assoc, mul_comm p]),
have hm : s * p % p =
card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p :=
hcard ▸ (card_quotient_normalizer_modeq_card_quotient hH).symm,
nat.dvd_of_mod_eq_zero
(by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm)
/-- If `H` is a `p`-subgroup but not a Sylow `p`-subgroup of cardinality `p ^ n`,
then `p ^ (n + 1)` divides the cardinality of the normalizer of `H`. -/
lemma prime_pow_dvd_card_normalizer [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
(hdvd : p ^ (n + 1) ∣ card G) {H : subgroup G} (hH : fintype.card H = p ^ n) :
p ^ (n + 1) ∣ card (normalizer H) :=
nat.modeq_zero_iff_dvd.1 ((card_normalizer_modeq_card hH).trans
hdvd.modeq_zero_nat)
/-- If `H` is a subgroup of `G` of cardinality `p ^ n`,
then `H` is contained in a subgroup of cardinality `p ^ (n + 1)`
if `p ^ (n + 1)` divides the cardinality of `G` -/
theorem exists_subgroup_card_pow_succ [fintype G] {p : ℕ} {n : ℕ} [hp : fact p.prime]
(hdvd : p ^ (n + 1) ∣ card G) {H : subgroup G} (hH : fintype.card H = p ^ n) :
∃ K : subgroup G, fintype.card K = p ^ (n + 1) ∧ H ≤ K :=
let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in
have hcard : card (quotient H) = s * p :=
(nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2
⟨⟨1, H.one_mem⟩⟩)).1
(by rwa [← card_eq_card_quotient_mul_card_subgroup H, hH, hs,
pow_succ', mul_assoc, mul_comm p]),
have hm : s * p % p =
card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) % p :=
card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸
(is_p_group.of_card hH).card_modeq_card_fixed_points _,
have hm' : p ∣ card (quotient (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H)) :=
nat.dvd_of_mod_eq_zero
(by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm),
let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.quotient.group _) _ _ hp hm' in
have hequiv : H ≃ (subgroup.comap ((normalizer H).subtype : normalizer H →* G) H) :=
⟨λ a, ⟨⟨a.1, le_normalizer a.2⟩, a.2⟩, λ a, ⟨a.1.1, a.2⟩,
λ ⟨_, _⟩, rfl, λ ⟨⟨_, _⟩, _⟩, rfl⟩,
⟨subgroup.map ((normalizer H).subtype) (subgroup.comap
(quotient_group.mk' (comap H.normalizer.subtype H)) (gpowers x)),
begin
show card ↥(map H.normalizer.subtype
(comap (mk' (comap H.normalizer.subtype H)) (subgroup.gpowers x))) = p ^ (n + 1),
suffices : card ↥(subtype.val '' ((subgroup.comap (mk' (comap H.normalizer.subtype H))
(gpowers x)) : set (↥(H.normalizer)))) = p^(n+1),
{ convert this using 2 },
rw [set.card_image_of_injective
(subgroup.comap (mk' (comap H.normalizer.subtype H)) (gpowers x) : set (H.normalizer))
subtype.val_injective,
pow_succ', ← hH, fintype.card_congr hequiv, ← hx, order_eq_card_gpowers,
← fintype.card_prod],
exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _)
end,
begin
assume y hy,
simp only [exists_prop, subgroup.coe_subtype, mk'_apply, subgroup.mem_map, subgroup.mem_comap],
refine ⟨⟨y, le_normalizer hy⟩, ⟨0, _⟩, rfl⟩,
rw [gpow_zero, eq_comm, quotient_group.eq_one_iff],
simpa using hy
end⟩
/-- If `H` is a subgroup of `G` of cardinality `p ^ n`,
then `H` is contained in a subgroup of cardinality `p ^ m`
if `n ≤ m` and `p ^ m` divides the cardinality of `G` -/
theorem exists_subgroup_card_pow_prime_le [fintype G] (p : ℕ) : ∀ {n m : ℕ} [hp : fact p.prime]
(hdvd : p ^ m ∣ card G) (H : subgroup G) (hH : card H = p ^ n) (hnm : n ≤ m),
∃ K : subgroup G, card K = p ^ m ∧ H ≤ K
| n m := λ hp hdvd H hH hnm,
(lt_or_eq_of_le hnm).elim
(λ hnm : n < m,
have h0m : 0 < m, from (lt_of_le_of_lt n.zero_le hnm),
have wf : m - 1 < m, from nat.sub_lt h0m zero_lt_one,
have hnm1 : n ≤ m - 1, from le_sub_of_add_le_right' hnm,
let ⟨K, hK⟩ := @exists_subgroup_card_pow_prime_le n (m - 1) hp
(nat.pow_dvd_of_le_of_pow_dvd sub_le_self' hdvd) H hH hnm1 in
have hdvd' : p ^ ((m - 1) + 1) ∣ card G, by rwa [nat.sub_add_cancel h0m],
let ⟨K', hK'⟩ := @exists_subgroup_card_pow_succ _ _ _ _ _ hp hdvd' K hK.1 in
⟨K', by rw [hK'.1, nat.sub_add_cancel h0m], le_trans hK.2 hK'.2⟩)
(λ hnm : n = m, ⟨H, by simp [hH, hnm]⟩)
/-- A generalisation of **Sylow's first theorem**. If `p ^ n` divides
the cardinality of `G`, then there is a subgroup of cardinality `p ^ n` -/
theorem exists_subgroup_card_pow_prime [fintype G] (p : ℕ) {n : ℕ} [fact p.prime]
(hdvd : p ^ n ∣ card G) : ∃ K : subgroup G, fintype.card K = p ^ n :=
let ⟨K, hK⟩ := exists_subgroup_card_pow_prime_le p hdvd ⊥ (by simp) n.zero_le in
⟨K, hK.1⟩
end sylow
|
3892f0f40af43c9e8dd3dad60ec806cba89a2ab0 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/order/omega_complete_partial_order.lean | dd70b69a64d110f25712504bf19345b2eb69c2f1 | [
"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 | 30,370 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import data.pfun
import order.preorder_hom
import tactic.wlog
import tactic.monotonicity
/-!
# Omega Complete Partial Orders
An omega-complete partial order is a partial order with a supremum
operation on increasing sequences indexed by natural numbers (which we
call `ωSup`). In this sense, it is strictly weaker than join complete
semi-lattices as only ω-sized totally ordered sets have a supremum.
The concept of an omega-complete partial order (ωCPO) is useful for the
formalization of the semantics of programming languages. Its notion of
supremum helps define the meaning of recursive procedures.
## Main definitions
* class `omega_complete_partial_order`
* `ite`, `map`, `bind`, `seq` as continuous morphisms
## Instances of `omega_complete_partial_order`
* `roption`
* every `complete_lattice`
* pi-types
* product types
* `monotone_hom`
* `continuous_hom` (with notation →𝒄)
* an instance of `omega_complete_partial_order (α →𝒄 β)`
* `continuous_hom.of_fun`
* `continuous_hom.of_mono`
* continuous functions:
* `id`
* `ite`
* `const`
* `roption.bind`
* `roption.map`
* `roption.seq`
## References
* [Chain-complete posets and directed sets with applications][markowsky1976]
* [Recursive definitions of partial functions and their computations][cadiou1972]
* [Semantics of Programming Languages: Structures and Techniques][gunter1992]
-/
universes u v
local attribute [-simp] roption.bind_eq_bind roption.map_eq_map
open_locale classical
namespace preorder_hom
variables (α : Type*) (β : Type*) {γ : Type*} {φ : Type*}
variables [preorder α] [preorder β] [preorder γ] [preorder φ]
variables {β γ}
/-- The constant function, as a monotone function. -/
@[simps]
def const (f : β) : α →ₘ β :=
{ to_fun := function.const _ f,
monotone' := assume x y h, le_refl _}
variables {α} {α' : Type*} {β' : Type*} [preorder α'] [preorder β']
/-- The diagonal function, as a monotone function. -/
@[simps]
def prod.diag : α →ₘ (α × α) :=
{ to_fun := λ x, (x,x),
monotone' := λ x y h, ⟨h,h⟩ }
/-- The `prod.map` function, as a monotone function. -/
@[simps]
def prod.map (f : α →ₘ β) (f' : α' →ₘ β') : (α × α') →ₘ (β × β') :=
{ to_fun := prod.map f f',
monotone' := λ ⟨x,x'⟩ ⟨y,y'⟩ ⟨h,h'⟩, ⟨f.monotone h,f'.monotone h'⟩ }
/-- The `prod.fst` projection, as a monotone function. -/
@[simps]
def prod.fst : (α × β) →ₘ α :=
{ to_fun := prod.fst,
monotone' := λ ⟨x,x'⟩ ⟨y,y'⟩ ⟨h,h'⟩, h }
/-- The `prod.snd` projection, as a monotone function. -/
@[simps]
def prod.snd : (α × β) →ₘ β :=
{ to_fun := prod.snd,
monotone' := λ ⟨x,x'⟩ ⟨y,y'⟩ ⟨h,h'⟩, h' }
/-- The `prod` constructor, as a monotone function. -/
@[simps]
def prod.zip (f : α →ₘ β) (g : α →ₘ γ) : α →ₘ (β × γ) :=
(prod.map f g).comp prod.diag
/-- `roption.bind` as a monotone function -/
@[simps]
def bind {β γ} (f : α →ₘ roption β) (g : α →ₘ β → roption γ) : α →ₘ roption γ :=
{ to_fun := λ x, f x >>= g x,
monotone' :=
begin
intros x y h a,
simp only [and_imp, exists_prop, roption.bind_eq_bind, roption.mem_bind_iff,
exists_imp_distrib],
intros b hb ha,
refine ⟨b, f.monotone h _ hb, g.monotone h _ _ ha⟩,
end }
end preorder_hom
namespace omega_complete_partial_order
/-- A chain is a monotonically increasing sequence.
See the definition on page 114 of [gunter1992]. -/
def chain (α : Type u) [preorder α] :=
ℕ →ₘ α
namespace chain
variables {α : Type u} {β : Type v} {γ : Type*}
variables [preorder α] [preorder β] [preorder γ]
instance : has_coe_to_fun (chain α) :=
@infer_instance (has_coe_to_fun $ ℕ →ₘ α) _
instance [inhabited α] : inhabited (chain α) :=
⟨ ⟨ λ _, default _, λ _ _ _, le_refl _ ⟩ ⟩
instance : has_mem α (chain α) :=
⟨λa (c : ℕ →ₘ α), ∃ i, a = c i⟩
variables (c c' : chain α)
variables (f : α →ₘ β)
variables (g : β →ₘ γ)
instance : has_le (chain α) :=
{ le := λ x y, ∀ i, ∃ j, x i ≤ y j }
/-- `map` function for `chain` -/
@[simps {fully_applied := ff}] def map : chain β :=
f.comp c
variables {f}
lemma mem_map (x : α) : x ∈ c → f x ∈ chain.map c f :=
λ ⟨i,h⟩, ⟨i, h.symm ▸ rfl⟩
lemma exists_of_mem_map {b : β} : b ∈ c.map f → ∃ a, a ∈ c ∧ f a = b :=
λ ⟨i,h⟩, ⟨c i, ⟨i, rfl⟩, h.symm⟩
lemma mem_map_iff {b : β} : b ∈ c.map f ↔ ∃ a, a ∈ c ∧ f a = b :=
⟨ exists_of_mem_map _, λ h, by { rcases h with ⟨w,h,h'⟩, subst b, apply mem_map c _ h, } ⟩
@[simp]
lemma map_id : c.map preorder_hom.id = c :=
preorder_hom.comp_id _
lemma map_comp : (c.map f).map g = c.map (g.comp f) := rfl
@[mono]
lemma map_le_map {g : α →ₘ β} (h : f ≤ g) : c.map f ≤ c.map g :=
λ i, by simp [mem_map_iff]; intros; existsi i; apply h
/-- `chain.zip` pairs up the elements of two chains that have the same index -/
@[simps]
def zip (c₀ : chain α) (c₁ : chain β) : chain (α × β) :=
preorder_hom.prod.zip c₀ c₁
end chain
end omega_complete_partial_order
open omega_complete_partial_order
section prio
set_option extends_priority 50
/-- An omega-complete partial order is a partial order with a supremum
operation on increasing sequences indexed by natural numbers (which we
call `ωSup`). In this sense, it is strictly weaker than join complete
semi-lattices as only ω-sized totally ordered sets have a supremum.
See the definition on page 114 of [gunter1992]. -/
class omega_complete_partial_order (α : Type*) extends partial_order α :=
(ωSup : chain α → α)
(le_ωSup : ∀(c:chain α), ∀ i, c i ≤ ωSup c)
(ωSup_le : ∀(c:chain α) x, (∀ i, c i ≤ x) → ωSup c ≤ x)
end prio
namespace omega_complete_partial_order
variables {α : Type u} {β : Type v} {γ : Type*}
variables [omega_complete_partial_order α]
/-- Transfer a `omega_complete_partial_order` on `β` to a `omega_complete_partial_order` on `α`
using a strictly monotone function `f : β →ₘ α`, a definition of ωSup and a proof that `f` is
continuous with regard to the provided `ωSup` and the ωCPO on `α`. -/
@[reducible]
protected def lift [partial_order β] (f : β →ₘ α)
(ωSup₀ : chain β → β)
(h : ∀ x y, f x ≤ f y → x ≤ y)
(h' : ∀ c, f (ωSup₀ c) = ωSup (c.map f)) : omega_complete_partial_order β :=
{ ωSup := ωSup₀,
ωSup_le := λ c x hx, h _ _ (by rw h'; apply ωSup_le; intro; apply f.monotone (hx i)),
le_ωSup := λ c i, h _ _ (by rw h'; apply le_ωSup (c.map f)) }
lemma le_ωSup_of_le {c : chain α} {x : α} (i : ℕ) (h : x ≤ c i) : x ≤ ωSup c :=
le_trans h (le_ωSup c _)
lemma ωSup_total {c : chain α} {x : α} (h : ∀ i, c i ≤ x ∨ x ≤ c i) : ωSup c ≤ x ∨ x ≤ ωSup c :=
classical.by_cases
(assume : ∀ i, c i ≤ x, or.inl (ωSup_le _ _ this))
(assume : ¬ ∀ i, c i ≤ x,
have ∃ i, ¬ c i ≤ x,
by simp only [not_forall] at this ⊢; assumption,
let ⟨i, hx⟩ := this in
have x ≤ c i, from (h i).resolve_left hx,
or.inr $ le_ωSup_of_le _ this)
@[mono]
lemma ωSup_le_ωSup_of_le {c₀ c₁ : chain α} (h : c₀ ≤ c₁) : ωSup c₀ ≤ ωSup c₁ :=
ωSup_le _ _ $
λ i, Exists.rec_on (h i) $
λ j h, le_trans h (le_ωSup _ _)
lemma ωSup_le_iff (c : chain α) (x : α) : ωSup c ≤ x ↔ (∀ i, c i ≤ x) :=
begin
split; intros,
{ transitivity ωSup c,
exact le_ωSup _ _, assumption },
exact ωSup_le _ _ ‹_›,
end
/-- A subset `p : α → Prop` of the type closed under `ωSup` induces an
`omega_complete_partial_order` on the subtype `{a : α // p a}`. -/
def subtype {α : Type*} [omega_complete_partial_order α] (p : α → Prop)
(hp : ∀ (c : chain α), (∀ i ∈ c, p i) → p (ωSup c)) :
omega_complete_partial_order (subtype p) :=
omega_complete_partial_order.lift
(preorder_hom.subtype.val p)
(λ c, ⟨ωSup _, hp (c.map (preorder_hom.subtype.val p)) (λ i ⟨n, q⟩, q.symm ▸ (c n).2)⟩)
(λ x y h, h)
(λ c, rfl)
section continuity
open chain
variables [omega_complete_partial_order β]
variables [omega_complete_partial_order γ]
/-- A monotone function `f : α →ₘ β` is continuous if it distributes over ωSup.
In order to distinguish it from the (more commonly used) continuity from topology
(see topology/basic.lean), the present definition is often referred to as
"Scott-continuity" (referring to Dana Scott). It corresponds to continuity
in Scott topological spaces (not defined here). -/
def continuous (f : α →ₘ β) : Prop :=
∀ c : chain α, f (ωSup c) = ωSup (c.map f)
/-- `continuous' f` asserts that `f` is both monotone and continuous. -/
def continuous' (f : α → β) : Prop :=
∃ hf : monotone f, continuous ⟨f, hf⟩
lemma continuous.to_monotone {f : α → β} (hf : continuous' f) : monotone f := hf.fst
lemma continuous.of_bundled (f : α → β) (hf : monotone f)
(hf' : continuous ⟨f, hf⟩) : continuous' f := ⟨hf, hf'⟩
lemma continuous.of_bundled' (f : α →ₘ β) (hf' : continuous f) : continuous' f :=
⟨f.monotone, hf'⟩
lemma continuous.to_bundled (f : α → β) (hf : continuous' f) :
continuous ⟨f, continuous.to_monotone hf⟩ := hf.snd
variables (f : α →ₘ β) (g : β →ₘ γ)
lemma continuous_id : continuous (@preorder_hom.id α _) :=
by intro; rw c.map_id; refl
lemma continuous_comp (hfc : continuous f) (hgc : continuous g) : continuous (g.comp f):=
begin
dsimp [continuous] at *, intro,
rw [hfc,hgc,chain.map_comp]
end
lemma id_continuous' : continuous' (@id α) :=
continuous.of_bundled _ (λ a b h, h)
begin
intro c, apply eq_of_forall_ge_iff, intro z,
simp [ωSup_le_iff,function.const],
end
lemma const_continuous' (x: β) : continuous' (function.const α x) :=
continuous.of_bundled _ (λ a b h, le_refl _)
begin
intro c, apply eq_of_forall_ge_iff, intro z,
simp [ωSup_le_iff,function.const],
end
end continuity
end omega_complete_partial_order
namespace roption
variables {α : Type u} {β : Type v} {γ : Type*}
open omega_complete_partial_order
lemma eq_of_chain {c : chain (roption α)} {a b : α} (ha : some a ∈ c) (hb : some b ∈ c) : a = b :=
begin
cases ha with i ha, replace ha := ha.symm,
cases hb with j hb, replace hb := hb.symm,
wlog h : i ≤ j := le_total i j using [a b i j, b a j i],
rw [eq_some_iff] at ha hb,
have := c.monotone h _ ha, apply mem_unique this hb
end
/-- The (noncomputable) `ωSup` definition for the `ω`-CPO structure on `roption α`. -/
protected noncomputable def ωSup (c : chain (roption α)) : roption α :=
if h : ∃a, some a ∈ c then some (classical.some h) else none
lemma ωSup_eq_some {c : chain (roption α)} {a : α} (h : some a ∈ c) : roption.ωSup c = some a :=
have ∃a, some a ∈ c, from ⟨a, h⟩,
have a' : some (classical.some this) ∈ c, from classical.some_spec this,
calc roption.ωSup c = some (classical.some this) : dif_pos this
... = some a : congr_arg _ (eq_of_chain a' h)
lemma ωSup_eq_none {c : chain (roption α)} (h : ¬∃a, some a ∈ c) : roption.ωSup c = none :=
dif_neg h
lemma mem_chain_of_mem_ωSup {c : chain (roption α)} {a : α} (h : a ∈ roption.ωSup c) : some a ∈ c :=
begin
simp [roption.ωSup] at h, split_ifs at h,
{ have h' := classical.some_spec h_1,
rw ← eq_some_iff at h, rw ← h, exact h' },
{ rcases h with ⟨ ⟨ ⟩ ⟩ }
end
noncomputable instance omega_complete_partial_order : omega_complete_partial_order (roption α) :=
{ ωSup := roption.ωSup,
le_ωSup := λ c i, by { intros x hx, rw ← eq_some_iff at hx ⊢,
rw [ωSup_eq_some, ← hx], rw ← hx, exact ⟨i,rfl⟩ },
ωSup_le := by { rintros c x hx a ha, replace ha := mem_chain_of_mem_ωSup ha,
cases ha with i ha, apply hx i, rw ← ha, apply mem_some } }
section inst
lemma mem_ωSup (x : α) (c : chain (roption α)) : x ∈ ωSup c ↔ some x ∈ c :=
begin
simp [omega_complete_partial_order.ωSup,roption.ωSup],
split,
{ split_ifs, swap, rintro ⟨⟨⟩⟩,
intro h', have hh := classical.some_spec h,
simp at h', subst x, exact hh },
{ intro h,
have h' : ∃ (a : α), some a ∈ c := ⟨_,h⟩,
rw dif_pos h', have hh := classical.some_spec h',
rw eq_of_chain hh h, simp }
end
end inst
end roption
namespace pi
variables {α : Type*} {β : α → Type*} {γ : Type*}
/-- Function application `λ f, f a` is monotone with respect to `f` for fixed `a`. -/
@[simps]
def monotone_apply [∀a, partial_order (β a)] (a : α) : (Πa, β a) →ₘ β a :=
{ to_fun := (λf:Πa, β a, f a),
monotone' := assume f g hfg, hfg a }
open omega_complete_partial_order omega_complete_partial_order.chain
instance [∀a, omega_complete_partial_order (β a)] : omega_complete_partial_order (Πa, β a) :=
{ ωSup := λc a, ωSup (c.map (monotone_apply a)),
ωSup_le := assume c f hf a, ωSup_le _ _ $ by { rintro i, apply hf },
le_ωSup := assume c i x, le_ωSup_of_le _ $ le_refl _ }
namespace omega_complete_partial_order
variables [∀ x, omega_complete_partial_order $ β x]
variables [omega_complete_partial_order γ]
lemma flip₁_continuous'
(f : ∀ x : α, γ → β x) (a : α) (hf : continuous' (λ x y, f y x)) :
continuous' (f a) :=
continuous.of_bundled _
(λ x y h, continuous.to_monotone hf h a)
(λ c, congr_fun (continuous.to_bundled _ hf c) a)
lemma flip₂_continuous'
(f : γ → Π x, β x) (hf : ∀ x, continuous' (λ g, f g x)) : continuous' f :=
continuous.of_bundled _
(λ x y h a, continuous.to_monotone (hf a) h)
(by intro c; ext a; apply continuous.to_bundled _ (hf a) c)
end omega_complete_partial_order
end pi
namespace prod
open omega_complete_partial_order
variables {α : Type*} {β : Type*} {γ : Type*}
variables [omega_complete_partial_order α]
variables [omega_complete_partial_order β]
variables [omega_complete_partial_order γ]
/-- The supremum of a chain in the product `ω`-CPO. -/
@[simps]
protected def ωSup (c : chain (α × β)) : α × β :=
(ωSup (c.map preorder_hom.prod.fst), ωSup (c.map preorder_hom.prod.snd))
@[simps ωSup_fst ωSup_snd]
instance : omega_complete_partial_order (α × β) :=
{ ωSup := prod.ωSup,
ωSup_le := λ c ⟨x,x'⟩ h, ⟨ωSup_le _ _ $ λ i, (h i).1, ωSup_le _ _ $ λ i, (h i).2⟩,
le_ωSup := λ c i,
⟨le_ωSup (c.map preorder_hom.prod.fst) i, le_ωSup (c.map preorder_hom.prod.snd) i⟩ }
end prod
namespace complete_lattice
variables (α : Type u)
/-- Any complete lattice has an `ω`-CPO structure where the countable supremum is a special case
of arbitrary suprema. -/
@[priority 100] -- see Note [lower instance priority]
instance [complete_lattice α] : omega_complete_partial_order α :=
{ ωSup := λc, ⨆ i, c i,
ωSup_le := λ ⟨c, _⟩ s hs, by simp only [supr_le_iff, preorder_hom.coe_fun_mk] at ⊢ hs;
intros i; apply hs i,
le_ωSup := assume ⟨c, _⟩ i, by simp only [preorder_hom.coe_fun_mk]; apply le_supr_of_le i; refl }
variables {α} {β : Type v} [omega_complete_partial_order α] [complete_lattice β]
open omega_complete_partial_order
lemma inf_continuous [is_total β (≤)] (f g : α →ₘ β) (hf : continuous f) (hg : continuous g) :
continuous (f ⊓ g) :=
begin
intro c,
apply eq_of_forall_ge_iff, intro z,
simp only [inf_le_iff, hf c, hg c, ωSup_le_iff, ←forall_or_distrib_left, ←forall_or_distrib_right,
function.comp_app, chain.map_coe, preorder_hom.has_inf_inf_coe],
split,
{ introv h, apply h },
{ intros h i j,
apply or.imp _ _ (h (max i j)); apply le_trans; mono*,
{ apply le_max_left },
{ apply le_max_right }, },
end
lemma Sup_continuous (s : set $ α →ₘ β) (hs : ∀ f ∈ s, continuous f) :
continuous (Sup s) :=
begin
intro c, apply eq_of_forall_ge_iff, intro z,
simp only [ωSup_le_iff, and_imp, preorder_hom.complete_lattice_Sup, set.mem_image,
chain.map_coe, function.comp_app, Sup_le_iff, preorder_hom.has_Sup_Sup_coe,
exists_imp_distrib],
split; introv h hx hb; subst b,
{ apply le_trans _ (h _ _ hx rfl),
mono, apply le_ωSup },
{ rw [hs _ hx c, ωSup_le_iff], intro,
apply h i _ x hx rfl, }
end
theorem Sup_continuous' :
∀s : set (α → β), (∀t∈s, omega_complete_partial_order.continuous' t) →
omega_complete_partial_order.continuous' (Sup s) :=
begin
introv ht, dsimp [continuous'],
have : monotone (Sup s),
{ intros x y h,
apply Sup_le_Sup_of_forall_exists_le, intro,
simp only [and_imp, exists_prop, set.mem_range, set_coe.exists, subtype.coe_mk,
exists_imp_distrib],
intros f hfs hfx,
subst hfx,
refine ⟨f y, ⟨f, hfs, rfl⟩, _⟩,
cases ht _ hfs with hf,
apply hf h },
existsi this,
let s' : set (α →ₘ β) := { f | ⇑f ∈ s },
suffices : omega_complete_partial_order.continuous (Sup s'),
{ convert this, ext,
simp only [supr, has_Sup.Sup, Sup, set.image, set.mem_set_of_eq],
congr, ext,
simp only [exists_prop, set.mem_range, set_coe.exists, set.mem_set_of_eq, subtype.coe_mk],
split,
{ rintro ⟨y,hy,hy'⟩,
cases ht _ hy,
refine ⟨⟨_, w⟩, hy, hy'⟩ },
tauto },
apply complete_lattice.Sup_continuous,
intros f hf,
specialize ht f hf, cases ht, exact ht_h,
end
lemma sup_continuous {f g : α →ₘ β} (hf : continuous f) (hg : continuous g) :
continuous (f ⊔ g) :=
begin
rw ← Sup_pair, apply Sup_continuous,
simp only [or_imp_distrib, forall_and_distrib, set.mem_insert_iff, set.mem_singleton_iff,
forall_eq],
split; assumption,
end
lemma top_continuous :
continuous (⊤ : α →ₘ β) :=
begin
intro c, apply eq_of_forall_ge_iff, intro z,
simp only [ωSup_le_iff, forall_const, chain.map_coe, function.comp_app,
preorder_hom.has_top_top_coe],
end
lemma bot_continuous :
continuous (⊥ : α →ₘ β) :=
begin
intro c, apply eq_of_forall_ge_iff, intro z,
simp only [ωSup_le_iff, forall_const, chain.map_coe, function.comp_app,
preorder_hom.has_bot_bot_coe],
end
end complete_lattice
namespace omega_complete_partial_order
variables {α : Type u} {α' : Type*} {β : Type v} {β' : Type*} {γ : Type*} {φ : Type*}
variables [omega_complete_partial_order α] [omega_complete_partial_order β]
variables [omega_complete_partial_order γ] [omega_complete_partial_order φ]
variables [omega_complete_partial_order α'] [omega_complete_partial_order β']
namespace preorder_hom
/-- Function application `λ f, f a` (for fixed `a`) is a monotone function from the
monotone function space `α →ₘ β` to `β`. -/
@[simps]
def monotone_apply (a : α) : (α →ₘ β) →ₘ β :=
{ to_fun := (λf : α →ₘ β, f a),
monotone' := assume f g hfg, hfg a }
/-- The "forgetful functor" from `α →ₘ β` to `α → β` that takes the underlying function,
is monotone. -/
def to_fun_hom : (α →ₘ β) →ₘ (α → β) :=
{ to_fun := λ f, f.to_fun,
monotone' := λ x y h, h }
/-- The `ωSup` operator for monotone functions. -/
@[simps]
protected def ωSup (c : chain (α →ₘ β)) : α →ₘ β :=
{ to_fun := λ a, ωSup (c.map (monotone_apply a)),
monotone' := λ x y h, ωSup_le_ωSup_of_le (chain.map_le_map _ $ λ a, a.monotone h) }
@[simps ωSup_coe]
instance omega_complete_partial_order : omega_complete_partial_order (α →ₘ β) :=
omega_complete_partial_order.lift preorder_hom.to_fun_hom preorder_hom.ωSup
(λ x y h, h) (λ c, rfl)
end preorder_hom
section old_struct
set_option old_structure_cmd true
variables (α β)
/-- A monotone function on `ω`-continuous partial orders is said to be continuous
if for every chain `c : chain α`, `f (⊔ i, c i) = ⊔ i, f (c i)`.
This is just the bundled version of `preorder_hom.continuous`. -/
structure continuous_hom extends preorder_hom α β :=
(cont : continuous (preorder_hom.mk to_fun monotone'))
attribute [nolint doc_blame] continuous_hom.to_preorder_hom
infixr ` →𝒄 `:25 := continuous_hom -- Input: \r\MIc
instance : has_coe_to_fun (α →𝒄 β) :=
{ F := λ _, α → β,
coe := continuous_hom.to_fun }
instance : has_coe (α →𝒄 β) (α →ₘ β) :=
{ coe := continuous_hom.to_preorder_hom }
instance : partial_order (α →𝒄 β) :=
partial_order.lift continuous_hom.to_fun $ by rintro ⟨⟩ ⟨⟩ h; congr; exact h
end old_struct
namespace continuous_hom
theorem congr_fun {f g : α →𝒄 β} (h : f = g) (x : α) : f x = g x :=
congr_arg (λ h : α →𝒄 β, h x) h
theorem congr_arg (f : α →𝒄 β) {x y : α} (h : x = y) : f x = f y :=
congr_arg (λ x : α, f x) h
@[mono]
lemma monotone (f : α →𝒄 β) : monotone f :=
continuous_hom.monotone' f
lemma ite_continuous' {p : Prop} [hp : decidable p] (f g : α → β)
(hf : continuous' f) (hg : continuous' g) : continuous' (λ x, if p then f x else g x) :=
by split_ifs; simp *
lemma ωSup_bind {β γ : Type v} (c : chain α) (f : α →ₘ roption β) (g : α →ₘ β → roption γ) :
ωSup (c.map (f.bind g)) = ωSup (c.map f) >>= ωSup (c.map g) :=
begin
apply eq_of_forall_ge_iff, intro x,
simp only [ωSup_le_iff, roption.bind_le, chain.mem_map_iff, and_imp, preorder_hom.bind_coe,
exists_imp_distrib],
split; intro h''',
{ intros b hb, apply ωSup_le _ _ _,
rintros i y hy, simp only [roption.mem_ωSup] at hb,
rcases hb with ⟨j,hb⟩, replace hb := hb.symm,
simp only [roption.eq_some_iff, chain.map_coe, function.comp_app, pi.monotone_apply_coe]
at hy hb,
replace hb : b ∈ f (c (max i j)) := f.monotone (c.monotone (le_max_right i j)) _ hb,
replace hy : y ∈ g (c (max i j)) b := g.monotone (c.monotone (le_max_left i j)) _ _ hy,
apply h''' (max i j),
simp only [exists_prop, roption.bind_eq_bind, roption.mem_bind_iff, chain.map_coe,
function.comp_app, preorder_hom.bind_coe],
exact ⟨_,hb,hy⟩, },
{ intros i, intros y hy,
simp only [exists_prop, roption.bind_eq_bind, roption.mem_bind_iff, chain.map_coe,
function.comp_app, preorder_hom.bind_coe] at hy,
rcases hy with ⟨b,hb₀,hb₁⟩,
apply h''' b _,
{ apply le_ωSup (c.map g) _ _ _ hb₁ },
{ apply le_ωSup (c.map f) i _ hb₀ } },
end
lemma bind_continuous' {β γ : Type v} (f : α → roption β) (g : α → β → roption γ) :
continuous' f → continuous' g →
continuous' (λ x, f x >>= g x)
| ⟨hf,hf'⟩ ⟨hg,hg'⟩ :=
continuous.of_bundled' (preorder_hom.bind ⟨f,hf⟩ ⟨g,hg⟩)
(by intro c; rw [ωSup_bind, ← hf', ← hg']; refl)
lemma map_continuous' {β γ : Type v} (f : β → γ) (g : α → roption β)
(hg : continuous' g) :
continuous' (λ x, f <$> g x) :=
by simp only [map_eq_bind_pure_comp];
apply bind_continuous' _ _ hg;
apply const_continuous'
lemma seq_continuous' {β γ : Type v} (f : α → roption (β → γ)) (g : α → roption β)
(hf : continuous' f) (hg : continuous' g) :
continuous' (λ x, f x <*> g x) :=
by simp only [seq_eq_bind_map];
apply bind_continuous' _ _ hf;
apply pi.omega_complete_partial_order.flip₂_continuous'; intro;
apply map_continuous' _ _ hg
lemma continuous (F : α →𝒄 β) (C : chain α) : F (ωSup C) = ωSup (C.map F) :=
continuous_hom.cont _ _
/-- Construct a continuous function from a bare function, a continuous function, and a proof that
they are equal. -/
@[simps, reducible]
def of_fun (f : α → β) (g : α →𝒄 β) (h : f = g) : α →𝒄 β :=
by refine {to_fun := f, ..}; subst h; cases g; assumption
/-- Construct a continuous function from a monotone function with a proof of continuity. -/
@[simps, reducible]
def of_mono (f : α →ₘ β) (h : ∀ c : chain α, f (ωSup c) = ωSup (c.map f)) : α →𝒄 β :=
{ to_fun := f,
monotone' := f.monotone,
cont := h }
/-- The identity as a continuous function. -/
@[simps]
def id : α →𝒄 α :=
of_mono preorder_hom.id
(by intro; rw [chain.map_id]; refl)
/-- The composition of continuous functions. -/
@[simps]
def comp (f : β →𝒄 γ) (g : α →𝒄 β) : α →𝒄 γ :=
of_mono (preorder_hom.comp (↑f) (↑g))
(by intro; rw [preorder_hom.comp, ← preorder_hom.comp, ← chain.map_comp, ← f.continuous,
← g.continuous]; refl)
@[ext]
protected lemma ext (f g : α →𝒄 β) (h : ∀ x, f x = g x) : f = g :=
by cases f; cases g; congr; ext; apply h
protected lemma coe_inj (f g : α →𝒄 β) (h : (f : α → β) = g) : f = g :=
continuous_hom.ext _ _ $ _root_.congr_fun h
@[simp]
lemma comp_id (f : β →𝒄 γ) : f.comp id = f := by ext; refl
@[simp]
lemma id_comp (f : β →𝒄 γ) : id.comp f = f := by ext; refl
@[simp]
lemma comp_assoc (f : γ →𝒄 φ) (g : β →𝒄 γ) (h : α →𝒄 β) : f.comp (g.comp h) = (f.comp g).comp h :=
by ext; refl
@[simp]
lemma coe_apply (a : α) (f : α →𝒄 β) : (f : α →ₘ β) a = f a := rfl
/-- `function.const` is a continuous function. -/
def const (f : β) : α →𝒄 β :=
of_mono (preorder_hom.const _ f)
begin
intro c, apply le_antisymm,
{ simp only [function.const, preorder_hom.const_coe],
apply le_ωSup_of_le 0, refl },
{ apply ωSup_le, simp only [preorder_hom.const_coe, chain.map_coe, function.comp_app],
intros, refl },
end
@[simp] theorem const_apply (f : β) (a : α) : const f a = f := rfl
instance [inhabited β] : inhabited (α →𝒄 β) :=
⟨ const (default β) ⟩
namespace prod
/-- The application of continuous functions as a monotone function.
(It would make sense to make it a continuous function, but we are currently constructing a
`omega_complete_partial_order` instance for `α →𝒄 β`, and we cannot use it as the domain or image
of a continuous function before we do.) -/
@[simps]
def apply : (α →𝒄 β) × α →ₘ β :=
{ to_fun := λ f, f.1 f.2,
monotone' := λ x y h, by dsimp; transitivity y.fst x.snd; [apply h.1, apply y.1.monotone h.2] }
end prod
/-- The map from continuous functions to monotone functions is itself a monotone function. -/
@[simps]
def to_mono : (α →𝒄 β) →ₘ (α →ₘ β) :=
{ to_fun := λ f, f,
monotone' := λ x y h, h }
/-- When proving that a chain of applications is below a bound `z`, it suffices to consider the
functions and values being selected from the same index in the chains.
This lemma is more specific than necessary, i.e. `c₀` only needs to be a
chain of monotone functions, but it is only used with continuous functions. -/
@[simp]
lemma forall_forall_merge (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) :
(∀ (i j : ℕ), (c₀ i) (c₁ j) ≤ z) ↔ ∀ (i : ℕ), (c₀ i) (c₁ i) ≤ z :=
begin
split; introv h,
{ apply h },
{ apply le_trans _ (h (max i j)),
transitivity c₀ i (c₁ (max i j)),
{ apply (c₀ i).monotone, apply c₁.monotone, apply le_max_right },
{ apply c₀.monotone, apply le_max_left } }
end
@[simp]
lemma forall_forall_merge' (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) :
(∀ (j i : ℕ), (c₀ i) (c₁ j) ≤ z) ↔ ∀ (i : ℕ), (c₀ i) (c₁ i) ≤ z :=
by rw [forall_swap,forall_forall_merge]
/-- The `ωSup` operator for continuous functions, which takes the pointwise countable supremum
of the functions in the `ω`-chain. -/
@[simps]
protected def ωSup (c : chain (α →𝒄 β)) : α →𝒄 β :=
continuous_hom.of_mono (ωSup $ c.map to_mono)
begin
intro c',
apply eq_of_forall_ge_iff, intro z,
simp only [ωSup_le_iff, (c _).continuous, chain.map_coe, preorder_hom.monotone_apply_coe,
to_mono_coe, coe_apply, preorder_hom.omega_complete_partial_order_ωSup_coe,
forall_forall_merge, forall_forall_merge', function.comp_app],
end
@[simps ωSup]
instance : omega_complete_partial_order (α →𝒄 β) :=
omega_complete_partial_order.lift continuous_hom.to_mono continuous_hom.ωSup
(λ x y h, h) (λ c, rfl)
lemma ωSup_def (c : chain (α →𝒄 β)) (x : α) : ωSup c x = continuous_hom.ωSup c x := rfl
lemma ωSup_ωSup (c₀ : chain (α →𝒄 β)) (c₁ : chain α) :
ωSup c₀ (ωSup c₁) = ωSup (continuous_hom.prod.apply.comp $ c₀.zip c₁) :=
begin
apply eq_of_forall_ge_iff, intro z,
simp only [ωSup_le_iff, (c₀ _).continuous, chain.map_coe, to_mono_coe, coe_apply,
preorder_hom.omega_complete_partial_order_ωSup_coe, ωSup_def, forall_forall_merge,
chain.zip_coe, preorder_hom.prod.map_coe, preorder_hom.prod.diag_coe, prod.map_mk,
preorder_hom.monotone_apply_coe, function.comp_app, prod.apply_coe,
preorder_hom.comp_coe, ωSup_to_fun],
end
/-- A family of continuous functions yields a continuous family of functions. -/
@[simps]
def flip {α : Type*} (f : α → β →𝒄 γ) : β →𝒄 α → γ :=
{ to_fun := λ x y, f y x,
monotone' := λ x y h a, (f a).monotone h,
cont := by intro; ext; change f x _ = _; rw [(f x).continuous ]; refl, }
/-- `roption.bind` as a continuous function. -/
@[simps { rhs_md := reducible }]
noncomputable def bind {β γ : Type v}
(f : α →𝒄 roption β) (g : α →𝒄 β → roption γ) : α →𝒄 roption γ :=
of_mono (preorder_hom.bind (↑f) (↑g)) $ λ c, begin
rw [preorder_hom.bind, ← preorder_hom.bind, ωSup_bind, ← f.continuous, ← g.continuous],
refl
end
/-- `roption.map` as a continuous function. -/
@[simps {rhs_md := reducible}]
noncomputable def map {β γ : Type v} (f : β → γ) (g : α →𝒄 roption β) : α →𝒄 roption γ :=
of_fun (λ x, f <$> g x) (bind g (const (pure ∘ f))) $
by ext; simp only [map_eq_bind_pure_comp, bind_to_fun, preorder_hom.bind_coe, const_apply,
preorder_hom.const_coe, coe_apply]
/-- `roption.seq` as a continuous function. -/
@[simps {rhs_md := reducible}]
noncomputable def seq {β γ : Type v} (f : α →𝒄 roption (β → γ)) (g : α →𝒄 roption β) :
α →𝒄 roption γ :=
of_fun (λ x, f x <*> g x) (bind f $ (flip $ _root_.flip map g))
(by ext; simp only [seq_eq_bind_map, flip, roption.bind_eq_bind, map_to_fun, roption.mem_bind_iff,
bind_to_fun, preorder_hom.bind_coe, coe_apply, flip_to_fun]; refl)
end continuous_hom
end omega_complete_partial_order
|
7d8581e17809146ad58122e78343c1be5369e832 | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/tactic14.lean | 4a5f67b638f33b8779839b66b2773d319553f113 | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 369 | lean | import standard
using tactic
definition basic_tac : tactic
:= repeat [apply @and_intro | assumption]
set_proof_qed basic_tac -- basic_tac is automatically applied to each element of a proof-qed block
theorem tst (a b : Prop) (H : ¬ a ∨ ¬ b) (Hb : b) : ¬ a ∧ b :=
proof
assume Ha, or_elim H
(assume Hna, absurd Ha Hna)
(assume Hnb, absurd Hb Hnb)
qed |
0e2795c6f74e08c3979d2e890cb4f9272a86e597 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/field_theory/finite/basic.lean | a760a4c7e3c267b9d74ded895db2df64ac4a0e89 | [
"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 | 12,485 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Joey van Langen, Casper Putz
-/
import tactic.apply_fun
import data.equiv.ring
import data.zmod.basic
import linear_algebra.basis
import ring_theory.integral_domain
import field_theory.separable
/-!
# Finite fields
This file contains basic results about finite fields.
Throughout most of this file, `K` denotes a finite field
and `q` is notation for the cardinality of `K`.
See `ring_theory.integral_domain` for the fact that the unit group of a finite field is a
cyclic group, as well as the fact that every finite integral domain is a field
(`field_of_integral_domain`).
## Main results
1. `card_units`: The unit group of a finite field is has cardinality `q - 1`.
2. `sum_pow_units`: The sum of `x^i`, where `x` ranges over the units of `K`, is
- `q-1` if `q-1 ∣ i`
- `0` otherwise
3. `finite_field.card`: The cardinality `q` is a power of the characteristic of `K`.
See `card'` for a variant.
## Notation
Throughout most of this file, `K` denotes a finite field
and `q` is notation for the cardinality of `K`.
-/
variables {K : Type*} [field K] [fintype K]
variables {R : Type*} [integral_domain R]
local notation `q` := fintype.card K
open_locale big_operators
namespace finite_field
open finset function
section polynomial
open polynomial
/-- The cardinality of a field is at most `n` times the cardinality of the image of a degree `n`
polynomial -/
lemma card_image_polynomial_eval [decidable_eq R] [fintype R] {p : polynomial R}
(hp : 0 < p.degree) : fintype.card R ≤ nat_degree p * (univ.image (λ x, eval x p)).card :=
finset.card_le_mul_card_image _ _
(λ a _, calc _ = (p - C a).roots.to_finset.card : congr_arg card
(by simp [finset.ext_iff, mem_roots_sub_C hp])
... ≤ (p - C a).roots.card : multiset.to_finset_card_le _
... ≤ _ : card_roots_sub_C' hp)
/-- If `f` and `g` are quadratic polynomials, then the `f.eval a + g.eval b = 0` has a solution. -/
lemma exists_root_sum_quadratic [fintype R] {f g : polynomial R} (hf2 : degree f = 2)
(hg2 : degree g = 2) (hR : fintype.card R % 2 = 1) : ∃ a b, f.eval a + g.eval b = 0 :=
by letI := classical.dec_eq R; exact
suffices ¬ disjoint (univ.image (λ x : R, eval x f)) (univ.image (λ x : R, eval x (-g))),
begin
simp only [disjoint_left, mem_image] at this,
push_neg at this,
rcases this with ⟨x, ⟨a, _, ha⟩, ⟨b, _, hb⟩⟩,
exact ⟨a, b, by rw [ha, ← hb, eval_neg, neg_add_self]⟩
end,
assume hd : disjoint _ _,
lt_irrefl (2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card) $
calc 2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card
≤ 2 * fintype.card R : nat.mul_le_mul_left _ (finset.card_le_univ _)
... = fintype.card R + fintype.card R : two_mul _
... < nat_degree f * (univ.image (λ x : R, eval x f)).card +
nat_degree (-g) * (univ.image (λ x : R, eval x (-g))).card :
add_lt_add_of_lt_of_le
(lt_of_le_of_ne
(card_image_polynomial_eval (by rw hf2; exact dec_trivial))
(mt (congr_arg (%2)) (by simp [nat_degree_eq_of_degree_eq_some hf2, hR])))
(card_image_polynomial_eval (by rw [degree_neg, hg2]; exact dec_trivial))
... = 2 * (univ.image (λ x : R, eval x f) ∪ univ.image (λ x : R, eval x (-g))).card :
by rw [card_disjoint_union hd]; simp [nat_degree_eq_of_degree_eq_some hf2,
nat_degree_eq_of_degree_eq_some hg2, bit0, mul_add]
end polynomial
lemma card_units : fintype.card (units K) = fintype.card K - 1 :=
begin
classical,
rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : K)⟩)],
haveI := set_fintype {a : K | a ≠ 0},
haveI := set_fintype (@set.univ K),
rw [fintype.card_congr (equiv.units_equiv_ne_zero _),
← @set.card_insert _ _ {a : K | a ≠ 0} _ (not_not.2 (eq.refl (0 : K)))
(set.fintype_insert _ _), fintype.card_congr (equiv.set.univ K).symm],
congr; simp [set.ext_iff, classical.em]
end
lemma prod_univ_units_id_eq_neg_one :
(∏ x : units K, x) = (-1 : units K) :=
begin
classical,
have : (∏ x in (@univ (units K) _).erase (-1), x) = 1,
from prod_involution (λ x _, x⁻¹) (by simp)
(λ a, by simp [units.inv_eq_self_iff] {contextual := tt})
(λ a, by simp [@inv_eq_iff_inv_eq _ _ a, eq_comm] {contextual := tt})
(by simp),
rw [← insert_erase (mem_univ (-1 : units K)), prod_insert (not_mem_erase _ _),
this, mul_one]
end
lemma pow_card_sub_one_eq_one (a : K) (ha : a ≠ 0) : a ^ (q - 1) = 1 :=
calc a ^ (fintype.card K - 1) = (units.mk0 a ha ^ (fintype.card K - 1) : units K) :
by rw [units.coe_pow, units.coe_mk0]
... = 1 : by { classical, rw [← card_units, pow_card_eq_one], refl }
lemma pow_card (a : K) : a ^ q = a :=
begin
have hp : fintype.card K > 0 := fintype.card_pos_iff.2 (by apply_instance),
by_cases h : a = 0, { rw h, apply zero_pow hp },
rw [← nat.succ_pred_eq_of_pos hp, pow_succ, nat.pred_eq_sub_one,
pow_card_sub_one_eq_one a h, mul_one],
end
variable (K)
theorem card (p : ℕ) [char_p K p] : ∃ (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) :=
begin
haveI hp : fact p.prime := ⟨char_p.char_is_prime K p⟩,
letI : vector_space (zmod p) K := { .. (zmod.cast_hom (dvd_refl _) K).to_semimodule },
obtain ⟨n, h⟩ := vector_space.card_fintype (zmod p) K,
rw zmod.card at h,
refine ⟨⟨n, _⟩, hp.1, h⟩,
apply or.resolve_left (nat.eq_zero_or_pos n),
rintro rfl,
rw pow_zero at h,
have : (0 : K) = 1, { apply fintype.card_le_one_iff.mp (le_of_eq h) },
exact absurd this zero_ne_one,
end
theorem card' : ∃ (p : ℕ) (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) :=
let ⟨p, hc⟩ := char_p.exists K in ⟨p, @finite_field.card K _ _ p hc⟩
@[simp] lemma cast_card_eq_zero : (q : K) = 0 :=
begin
rcases char_p.exists K with ⟨p, _char_p⟩, resetI,
rcases card K p with ⟨n, hp, hn⟩,
simp only [char_p.cast_eq_zero_iff K p, hn],
conv { congr, rw [← pow_one p] },
exact pow_dvd_pow _ n.2,
end
lemma forall_pow_eq_one_iff (i : ℕ) :
(∀ x : units K, x ^ i = 1) ↔ q - 1 ∣ i :=
begin
obtain ⟨x, hx⟩ := is_cyclic.exists_generator (units K),
classical,
rw [← card_units, ← order_of_eq_card_of_forall_mem_gpowers hx, order_of_dvd_iff_pow_eq_one],
split,
{ intro h, apply h },
{ intros h y,
simp_rw ← mem_powers_iff_mem_gpowers at hx,
rcases hx y with ⟨j, rfl⟩,
rw [← pow_mul, mul_comm, pow_mul, h, one_pow], }
end
/-- The sum of `x ^ i` as `x` ranges over the units of a finite field of cardinality `q`
is equal to `0` unless `(q - 1) ∣ i`, in which case the sum is `q - 1`. -/
lemma sum_pow_units (i : ℕ) :
∑ x : units K, (x ^ i : K) = if (q - 1) ∣ i then -1 else 0 :=
begin
let φ : units K →* K :=
{ to_fun := λ x, x ^ i,
map_one' := by rw [units.coe_one, one_pow],
map_mul' := by { intros, rw [units.coe_mul, mul_pow] } },
haveI : decidable (φ = 1) := by { classical, apply_instance },
calc ∑ x : units K, φ x = if φ = 1 then fintype.card (units K) else 0 : sum_hom_units φ
... = if (q - 1) ∣ i then -1 else 0 : _,
suffices : (q - 1) ∣ i ↔ φ = 1,
{ simp only [this],
split_ifs with h h, swap, refl,
rw [card_units, nat.cast_sub, cast_card_eq_zero, nat.cast_one, zero_sub],
show 1 ≤ q, from fintype.card_pos_iff.mpr ⟨0⟩ },
rw [← forall_pow_eq_one_iff, monoid_hom.ext_iff],
apply forall_congr, intro x,
rw [units.ext_iff, units.coe_pow, units.coe_one, monoid_hom.one_apply],
refl,
end
/-- The sum of `x ^ i` as `x` ranges over a finite field of cardinality `q`
is equal to `0` if `i < q - 1`. -/
lemma sum_pow_lt_card_sub_one (i : ℕ) (h : i < q - 1) :
∑ x : K, x ^ i = 0 :=
begin
by_cases hi : i = 0,
{ simp only [hi, nsmul_one, sum_const, pow_zero, card_univ, cast_card_eq_zero], },
classical,
have hiq : ¬ (q - 1) ∣ i, { contrapose! h, exact nat.le_of_dvd (nat.pos_of_ne_zero hi) h },
let φ : units K ↪ K := ⟨coe, units.ext⟩,
have : univ.map φ = univ \ {0},
{ ext x,
simp only [true_and, embedding.coe_fn_mk, mem_sdiff, units.exists_iff_ne_zero,
mem_univ, mem_map, exists_prop_of_true, mem_singleton] },
calc ∑ x : K, x ^ i = ∑ x in univ \ {(0 : K)}, x ^ i :
by rw [← sum_sdiff ({0} : finset K).subset_univ, sum_singleton,
zero_pow (nat.pos_of_ne_zero hi), add_zero]
... = ∑ x : units K, x ^ i : by { rw [← this, univ.sum_map φ], refl }
... = 0 : by { rw [sum_pow_units K i, if_neg], exact hiq, }
end
variables {K}
theorem frobenius_pow {p : ℕ} [fact p.prime] [char_p K p] {n : ℕ} (hcard : q = p^n) :
(frobenius K p) ^ n = 1 :=
begin
ext, conv_rhs { rw [ring_hom.one_def, ring_hom.id_apply, ← pow_card x, hcard], }, clear hcard,
induction n, {simp},
rw [pow_succ, pow_succ', pow_mul, ring_hom.mul_def, ring_hom.comp_apply, frobenius_def, n_ih]
end
open polynomial
lemma expand_card (f : polynomial K) :
expand K q f = f ^ q :=
begin
cases char_p.exists K with p hp, letI := hp,
rcases finite_field.card K p with ⟨⟨n, npos⟩, ⟨hp, hn⟩⟩, haveI : fact p.prime := ⟨hp⟩,
dsimp at hn, rw hn at *,
rw ← map_expand_pow_char,
rw [frobenius_pow hn, ring_hom.one_def, map_id],
end
end finite_field
namespace zmod
open finite_field polynomial
lemma sum_two_squares (p : ℕ) [hp : fact p.prime] (x : zmod p) :
∃ a b : zmod p, a^2 + b^2 = x :=
begin
cases hp.1.eq_two_or_odd with hp2 hp_odd,
{ substI p, revert x, exact dec_trivial },
let f : polynomial (zmod p) := X^2,
let g : polynomial (zmod p) := X^2 - C x,
obtain ⟨a, b, hab⟩ : ∃ a b, f.eval a + g.eval b = 0 :=
@exists_root_sum_quadratic _ _ _ f g
(degree_X_pow 2) (degree_X_pow_sub_C dec_trivial _) (by rw [zmod.card, hp_odd]),
refine ⟨a, b, _⟩,
rw ← sub_eq_zero,
simpa only [eval_C, eval_X, eval_pow, eval_sub, ← add_sub_assoc] using hab,
end
end zmod
namespace char_p
lemma sum_two_squares (R : Type*) [integral_domain R] (p : ℕ) [fact (0 < p)] [char_p R p] (x : ℤ) :
∃ a b : ℕ, (a^2 + b^2 : R) = x :=
begin
haveI := char_is_prime_of_pos R p,
obtain ⟨a, b, hab⟩ := zmod.sum_two_squares p x,
refine ⟨a.val, b.val, _⟩,
simpa using congr_arg (zmod.cast_hom (dvd_refl _) R) hab
end
end char_p
open_locale nat
open zmod
/-- The Fermat-Euler totient theorem. `nat.modeq.pow_totient` is an alternative statement
of the same theorem. -/
@[simp] lemma zmod.pow_totient {n : ℕ} [fact (0 < n)] (x : units (zmod n)) : x ^ φ n = 1 :=
by rw [← card_units_eq_totient, pow_card_eq_one]
/-- The Fermat-Euler totient theorem. `zmod.pow_totient` is an alternative statement
of the same theorem. -/
lemma nat.modeq.pow_totient {x n : ℕ} (h : nat.coprime x n) : x ^ φ n ≡ 1 [MOD n] :=
begin
cases n, {simp},
rw ← zmod.eq_iff_modeq_nat,
let x' : units (zmod (n+1)) := zmod.unit_of_coprime _ h,
have := zmod.pow_totient x',
apply_fun (coe : units (zmod (n+1)) → zmod (n+1)) at this,
simpa only [-zmod.pow_totient, nat.succ_eq_add_one, nat.cast_pow, units.coe_one,
nat.cast_one, coe_unit_of_coprime, units.coe_pow],
end
open finite_field
namespace zmod
/-- A variation on Fermat's little theorem. See `zmod.pow_card_sub_one_eq_one` -/
@[simp] lemma pow_card {p : ℕ} [fact p.prime] (x : zmod p) : x ^ p = x :=
by { have h := finite_field.pow_card x, rwa zmod.card p at h }
@[simp] lemma frobenius_zmod (p : ℕ) [fact p.prime] :
frobenius (zmod p) p = ring_hom.id _ :=
by { ext a, rw [frobenius_def, zmod.pow_card, ring_hom.id_apply] }
@[simp] lemma card_units (p : ℕ) [fact p.prime] : fintype.card (units (zmod p)) = p - 1 :=
by rw [card_units, card]
/-- Fermat's Little Theorem: for every unit `a` of `zmod p`, we have `a ^ (p - 1) = 1`. -/
theorem units_pow_card_sub_one_eq_one (p : ℕ) [fact p.prime] (a : units (zmod p)) :
a ^ (p - 1) = 1 :=
by rw [← card_units p, pow_card_eq_one]
/-- Fermat's Little Theorem: for all nonzero `a : zmod p`, we have `a ^ (p - 1) = 1`. -/
theorem pow_card_sub_one_eq_one {p : ℕ} [fact p.prime] {a : zmod p} (ha : a ≠ 0) :
a ^ (p - 1) = 1 :=
by { have h := pow_card_sub_one_eq_one a ha, rwa zmod.card p at h }
open polynomial
lemma expand_card {p : ℕ} [fact p.prime] (f : polynomial (zmod p)) :
expand (zmod p) p f = f ^ p :=
by { have h := finite_field.expand_card f, rwa zmod.card p at h }
end zmod
|
e2c055971c8bb144e2082233b47ab48c470e64a2 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /tests/lean/run/newfrontend1.lean | a07f7bef3c5ad0a83a171649d8d572165db54e13 | [
"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 | 8,776 | lean | def x := 1
#check x
variable {α : Type}
def f (a : α) : α :=
a
def tst (xs : List Nat) : Nat :=
xs.foldl (init := 10) (· + ·)
#check tst [1, 2, 3]
#check fun x y : Nat => x + y
#check tst
#check (fun stx => if True then let e := stx; Pure.pure e else Pure.pure stx : Nat → Id Nat)
#check let x : Nat := 1; x
def foo (a : Nat) (b : Nat := 10) (c : Bool := Bool.true) : Nat :=
a + b
set_option pp.all true
#check foo 1
#check foo 3 (c := false)
def Nat.boo (a : Nat) :=
succ a -- succ here is resolved as `Nat.succ`.
#check Nat.boo
#check true
-- apply is still a valid identifier name
def apply := "hello"
#check apply
theorem simple1 (x y : Nat) (h : x = y) : x = y :=
by {
assumption
}
theorem simple2 (x y : Nat) : x = y → x = y :=
by {
intro h;
assumption
}
syntax "intro2" : tactic
macro_rules
| `(tactic| intro2) => `(tactic| intro; intro )
theorem simple3 (x y : Nat) : x = x → x = y → x = y :=
by {
intro2;
assumption
}
macro "intro3" : tactic => `(intro; intro; intro)
macro "check2" x:term : command => `(#check $x #check $x)
macro "foo" x:term "," y:term : term => `($x + $y + $x)
set_option pp.all false
check2 0+1
check2 foo 0,1
theorem simple4 (x y : Nat) : y = y → x = x → x = y → x = y :=
by {
intro3;
assumption
}
theorem simple5 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro _; intro h3;
exact Eq.trans h3 h1
}
theorem simple6 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro _; intro h3;
refine Eq.trans ?_ h1;
assumption
}
theorem simple7 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro _; intro h3;
refine! Eq.trans ?pre ?post;
exact y;
{ exact h3 }
{ exact h1 }
}
theorem simple8 (x y z : Nat) : y = z → x = x → x = y → x = z := by
intro h1; intro _; intro h3
refine! Eq.trans ?pre ?post
case post => exact h1
case pre => exact h3
theorem simple9 (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros h1 _ h3
traceState
focus
refine! Eq.trans ?pre ?post
first
| exact h1
assumption
| exact y
exact h3
assumption
theorem simple9b (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros h1 _ h3
traceState
focus
refine! Eq.trans ?pre ?post
first
| exact h1
| exact y; exact h3
assumption
theorem simple9c (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros h1 _ h3
solve
| exact h1
| refine! Eq.trans ?pre ?post; exact y; exact h3; assumption
| exact h3
theorem simple9d (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros h1 _ h3
refine! Eq.trans ?pre ?post
solve
| exact h1
| exact y
| exact h3
solve
| exact h1
| exact h3
solve
| exact h1
| assumption
namespace Foo
def Prod.mk := 1
#check (⟨2, 3⟩ : Prod _ _)
end Foo
theorem simple10 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro h2; intro h3;
skip;
apply Eq.trans;
exact h3;
assumption
}
theorem simple11 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro h2; intro h3;
apply @Eq.trans;
traceState;
exact h3;
assumption
}
theorem simple12 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intro h1; intro h2; intro h3;
apply @Eq.trans;
try exact h1; -- `exact h1` fails
traceState;
try exact h3;
traceState;
try exact h1;
}
theorem simple13 (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros h1 h2 h3
traceState
apply @Eq.trans
case b => exact y
traceState
repeat assumption
theorem simple13b (x y z : Nat) : y = z → x = x → x = y → x = z := by {
intros h1 h2 h3;
traceState;
apply @Eq.trans;
case b => exact y;
traceState;
repeat assumption
}
theorem simple14 (x y z : Nat) : y = z → x = x → x = y → x = z := by
intros
apply @Eq.trans
case b => exact y
repeat assumption
theorem simple15 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intros h1 h2 h3;
revert y;
intros y h1 h3;
apply Eq.trans;
exact h3;
exact h1
}
theorem simple16 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by {
intros h1 h2 h3;
try clear x; -- should fail
clear h2;
traceState;
apply Eq.trans;
exact h3;
exact h1
}
macro "blabla" : tactic => `(assumption)
-- Tactic head symbols do not become reserved words
def blabla := 100
#check blabla
theorem simple17 (x : Nat) (h : x = 0) : x = 0 :=
by blabla
theorem simple18 (x : Nat) (h : x = 0) : x = 0 :=
by blabla
theorem simple19 (x y : Nat) (h₁ : x = 0) (h₂ : x = y) : y = 0 :=
by subst x; subst y; exact rfl
theorem tstprec1 (x y z : Nat) : x + y * z = x + (y * z) :=
rfl
theorem tstprec2 (x y z : Nat) : y * z + x = (y * z) + x :=
rfl
set_option pp.all true
#check fun {α} (a : α) => a
#check @(fun α (a : α) => a)
#check
let myid := fun {α} (a : α) => a;
myid [myid 1]
-- In the following example, we need `@` otherwise we will try to insert mvars for α and [Add α],
-- and will fail to generate instance for [Add α]
#check @(fun α (s : Add α) (a : α) => a + a)
def g1 {α} (a₁ a₂ : α) {β} (b : β) : α × α × β :=
(a₁, a₂, b)
def id1 : {α : Type} → α → α :=
fun x => x
def listId : List ({α : Type} → α → α) :=
(fun x => x) :: []
def id2 : {α : Type} → α → α :=
@(fun α (x : α) => id1 x)
def id3 : {α : Type} → α → α :=
@(fun α x => id1 x)
def id4 : {α : Type} → α → α :=
fun x => id1 x
def id5 : {α : Type} → α → α :=
fun {α} x => id1 x
def id6 : {α : Type} → α → α :=
@(fun {α} x => id1 x)
def id7 : {α : Type} → α → α :=
fun {α} x => @id α x
def id8 : {α : Type} → α → α :=
fun {α} x => id (@id α x)
def altTst1 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) :=
⟨StateT.failure, StateT.orElse⟩
def altTst2 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) :=
⟨@(fun α => StateT.failure), @(fun α => StateT.orElse)⟩
def altTst3 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) :=
⟨fun {α} => StateT.failure, fun {α} => StateT.orElse⟩
#check_failure 1 + true
/-
universes u v
/-
MonadFunctorT.{u ?M_1 v} (λ (β : Type u), m α) (λ (β : Type u), m' α) n n'
-/
set_option pp.raw.maxDepth 100
set_option trace.Elab true
def adapt {m m' σ σ'} {n n' : Type → Type} [MonadFunctor m m' n n'] [MonadStateAdapter σ σ' m m'] : MonadStateAdapter σ σ' n n' :=
⟨fun split join => monadMap (adaptState split join : m α → m' α)⟩
-/
syntax "fn" (term:max)+ "=>" term : term
macro_rules
| `(fn $xs* => $b) => `(fun $xs* => $b)
set_option pp.all false
#check fn x => x+1
#check fn α (a : α) => a
def tst1 : {α : Type} → α → α :=
@(fn α a => a)
#check @tst1
syntax ident "==>" term : term
syntax "{" ident "}" "==>" term : term
macro_rules
| `($x:ident ==> $b) => `(fn $x => $b)
| `({$x:ident} ==> $b) => `(fun {$x:ident} => $b)
#check x ==> x+1
def tst2a : {α : Type} → α → α :=
@(α ==> a ==> a)
def tst2b : {α : Type} → α → α :=
{α} ==> a ==> a
#check @tst2a
#check @tst2b
def tst3a : {α : Type} → {β : Type} → α → β → α × β :=
@(α ==> @(β ==> a ==> b ==> (a, b)))
def tst3b : {α : Type} → {β : Type} → α → β → α × β :=
{α} ==> {β} ==> a ==> b ==> (a, b)
syntax "function" (term:max)+ "=>" term : term
macro_rules
| `(function $xs* => $b) => `(@(fun $xs* => $b))
def tst4 : {α : Type} → {β : Type} → α → β → α × β :=
function α β a b => (a, b)
theorem simple20 (x y z : Nat) : y = z → x = x → x = y → x = z :=
by intros h1 h2 h3;
try clear x; -- should fail
clear h2;
traceState;
apply Eq.trans;
exact h3;
exact h1
theorem simple21 (x y z : Nat) : y = z → x = x → y = x → x = z :=
fun h1 _ h3 =>
have x = y from by { apply Eq.symm; assumption };
Eq.trans this (by assumption)
theorem simple22 (x y z : Nat) : y = z → y = x → id (x = z + 0) :=
fun h1 h2 => show x = z + 0 by
apply Eq.trans
exact h2.symm
assumption
skip
theorem simple23 (x y z : Nat) : y = z → x = x → y = x → x = z :=
fun h1 _ h3 =>
have x = y by apply Eq.symm; assumption
Eq.trans this (by assumption)
theorem simple24 (x y z : Nat) : y = z → x = x → y = x → x = z :=
fun h1 _ h3 =>
have h : x = y by apply Eq.symm; assumption
Eq.trans h (by assumption)
def f1 (x : Nat) : Nat :=
let double x := x + x
let rec loop x :=
match x with
| 0 => 0
| x+1 => loop x + double x
loop x
#eval f1 5
def f2 (x : Nat) : String :=
let bad x : String := toString x
bad x
def f3 x y :=
x + y + 1
theorem f3eq x y : f3 x y = x + y + 1 :=
rfl
def f4 (x y : Nat) : String :=
if x > y + 1 then "hello" else "world"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.