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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
068c95093aafba0e12dad38df9e3f44859ecdc0c | c777c32c8e484e195053731103c5e52af26a25d1 | /src/order/category/BoolAlg.lean | 08e38c978beb0a8caa5d2f07b8f265fd5caf7b9b | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 2,650 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import order.category.HeytAlg
/-!
# The category of boolean algebras
This defines `BoolAlg`, the category of boolean algebras.
-/
open order_dual opposite set
universes u
open category_theory
/-- The category of boolean algebras. -/
def BoolAlg := bundled boolean_algebra
namespace BoolAlg
instance : has_coe_to_sort BoolAlg Type* := bundled.has_coe_to_sort
instance (X : BoolAlg) : boolean_algebra X := X.str
/-- Construct a bundled `BoolAlg` from a `boolean_algebra`. -/
def of (α : Type*) [boolean_algebra α] : BoolAlg := bundled.of α
@[simp] lemma coe_of (α : Type*) [boolean_algebra α] : ↥(of α) = α := rfl
instance : inhabited BoolAlg := ⟨of punit⟩
/-- Turn a `BoolAlg` into a `BddDistLat` by forgetting its complement operation. -/
def to_BddDistLat (X : BoolAlg) : BddDistLat := BddDistLat.of X
@[simp] lemma coe_to_BddDistLat (X : BoolAlg) : ↥X.to_BddDistLat = ↥X := rfl
instance : large_category.{u} BoolAlg := induced_category.category to_BddDistLat
instance : concrete_category BoolAlg := induced_category.concrete_category to_BddDistLat
instance has_forget_to_BddDistLat : has_forget₂ BoolAlg BddDistLat :=
induced_category.has_forget₂ to_BddDistLat
section
local attribute [instance] bounded_lattice_hom_class.to_biheyting_hom_class
@[simps] instance has_forget_to_HeytAlg : has_forget₂ BoolAlg HeytAlg :=
{ forget₂ := { obj := λ X, ⟨X⟩, map := λ X Y f, show bounded_lattice_hom X Y, from f } }
end
/-- Constructs an equivalence between Boolean algebras from an order isomorphism between them. -/
@[simps] def iso.mk {α β : BoolAlg.{u}} (e : α ≃o β) : α ≅ β :=
{ hom := (e : bounded_lattice_hom α β),
inv := (e.symm : bounded_lattice_hom β α),
hom_inv_id' := by { ext, exact e.symm_apply_apply _ },
inv_hom_id' := by { ext, exact e.apply_symm_apply _ } }
/-- `order_dual` as a functor. -/
@[simps] def dual : BoolAlg ⥤ BoolAlg :=
{ obj := λ X, of Xᵒᵈ, map := λ X Y, bounded_lattice_hom.dual }
/-- The equivalence between `BoolAlg` and itself induced by `order_dual` both ways. -/
@[simps functor inverse] def dual_equiv : BoolAlg ≌ BoolAlg :=
equivalence.mk dual dual
(nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl)
(nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl)
end BoolAlg
lemma BoolAlg_dual_comp_forget_to_BddDistLat :
BoolAlg.dual ⋙ forget₂ BoolAlg BddDistLat =
forget₂ BoolAlg BddDistLat ⋙ BddDistLat.dual := rfl
|
cfda72ca11a62033f1efa076dcd120781547378b | 957a80ea22c5abb4f4670b250d55534d9db99108 | /library/init/meta/injection_tactic.lean | b8b1ceec10e9efc01c158b30d695e33e26062995 | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 2,723 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.tactic init.function
namespace tactic
open nat tactic environment expr list
private meta def at_end₂ (e₁ e₂ : expr) : ℕ → tactic (list (option expr))
| 2 := return [some e₁, some e₂]
| (n+3) := (λ xs, none :: xs) <$> at_end₂ (n+2)
| _ := fail "at_end expected arity > 1"
-- Auxiliary function for introducing the new equalities produced by the
-- injection tactic
private meta def injection_intro : expr → list name → tactic (list expr × list name)
| (pi n bi b d) ns := do
let hname := @head _ ⟨`h⟩ ns,
h ← intro hname,
(l, ns') ← injection_intro d (tail ns),
return (h :: l, ns')
| e ns := return ([], ns)
-- Tries to decompose the given expression by constructor injectivity.
-- Returns the list of new hypotheses, and the remaining names from the given list.
meta def injection_with (h : expr) (ns : list name) : tactic (list expr × list name) :=
do
ht ← infer_type h,
(lhs0, rhs0) ← match_eq ht,
env ← get_env,
lhs ← whnf lhs0,
rhs ← whnf rhs0,
let n_fl := const_name (get_app_fn lhs),
let n_fr := const_name (get_app_fn rhs),
if n_fl = n_fr then do
let n_inj := n_fl <.> "inj_arrow",
if env.contains n_inj then do
c_inj ← mk_const n_inj,
arity ← get_arity c_inj,
tgt ← target,
args ← at_end₂ h tgt (arity - 1),
pr ← mk_mapp n_inj args,
pr_type ← infer_type pr,
pr_type ← whnf pr_type,
eapply pr,
injection_intro (binding_domain pr_type) ns
else fail "injection tactic failed, argument must be an equality proof where lhs and rhs are of the form (c ...), where c is a constructor"
else do
tgt ← target,
let I_name := name.get_prefix n_fl,
pr ← mk_app (I_name <.> "no_confusion") [tgt, lhs, rhs, h],
exact pr,
return ([], ns)
meta def injection (h : expr) : tactic (list expr) :=
do (t, _) ← injection_with h [], return t
private meta def injections_with_inner : nat → list expr → list name → tactic unit
| 0 lc ns := fail "recursion depth exceeded"
| (n+1) [] ns := skip
| (n+1) (h :: lc) ns :=
do o ← try_core (injection_with h ns), match o with
| none := injections_with_inner (n+1) lc ns
| some ([], _) := skip -- This means that the contradiction part was triggered and the goal is done
| some (t, ns') := injections_with_inner n (t ++ lc) ns'
end
meta def injections_with (ns : list name) : tactic unit :=
do lc ← local_context,
injections_with_inner 5 lc ns
end tactic
|
50e727eaf174a2038710204a55770e38055c7e65 | ff5230333a701471f46c57e8c115a073ebaaa448 | /library/init/category/option.lean | e022dd476df97e09cc4845620fb81a4bf258b0e5 | [
"Apache-2.0"
] | permissive | stanford-cs242/lean | f81721d2b5d00bc175f2e58c57b710d465e6c858 | 7bd861261f4a37326dcf8d7a17f1f1f330e4548c | refs/heads/master | 1,600,957,431,849 | 1,576,465,093,000 | 1,576,465,093,000 | 225,779,423 | 0 | 3 | Apache-2.0 | 1,575,433,936,000 | 1,575,433,935,000 | null | UTF-8 | Lean | false | false | 2,127 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
prelude
import init.category.alternative init.category.lift init.category.except
universes u v
structure option_t (m : Type u → Type v) (α : Type u) : Type v :=
(run : m (option α))
namespace option_t
variables {m : Type u → Type v} [monad m] {α β : Type u}
@[inline] protected def bind_cont {α β : Type u} (f : α → option_t m β) : option α → m (option β)
| (some a) := (f a).run
| none := pure none
@[inline] protected def bind (ma : option_t m α) (f : α → option_t m β) : option_t m β :=
⟨ma.run >>= option_t.bind_cont f⟩
@[inline] protected def pure (a : α) : option_t m α :=
⟨pure (some a)⟩
instance : monad (option_t m) :=
{ pure := @option_t.pure _ _, bind := @option_t.bind _ _ }
protected def orelse (ma : option_t m α) (mb : option_t m α) : option_t m α :=
⟨do some a ← ma.run | mb.run,
pure (some a)⟩
@[inline] protected def fail : option_t m α :=
⟨pure none⟩
instance : alternative (option_t m) :=
{ failure := @option_t.fail m _,
orelse := @option_t.orelse m _,
..option_t.monad }
@[inline] protected def lift (ma : m α) : option_t m α :=
⟨some <$> ma⟩
instance : has_monad_lift m (option_t m) :=
⟨@option_t.lift _ _⟩
@[inline] protected def monad_map {m'} [monad m'] {α} (f : ∀ {α}, m α → m' α) : option_t m α → option_t m' α :=
λ x, ⟨f x.run⟩
instance (m') [monad m'] : monad_functor m m' (option_t m) (option_t m') :=
⟨λ α, option_t.monad_map⟩
protected def catch (ma : option_t m α) (handle : unit → option_t m α) : option_t m α :=
⟨do some a ← ma.run | (handle ()).run,
pure a⟩
instance : monad_except unit (option_t m) :=
{ throw := λ _ _, option_t.fail, catch := @option_t.catch _ _ }
instance (m out) [monad_run out m] : monad_run (λ α, out (option α)) (option_t m) :=
⟨λ α, monad_run.run ∘ option_t.run⟩
end option_t
|
2e9fb3b90b70d68469aa02f658ffc83e7d942606 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/pp_goal_issue.lean | 08f33be1d5f52c0fa419624802904693e809777c | [
"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 | 369 | lean | constant f : (nat → nat → Prop) → Prop
example (h1 : false) : ∀ (a b c : nat), a = 0 → b = 0 → f (λ x y, a + x = b + c + y) :=
begin
intros x x y h h, -- Force name clash
trace_state,
contradiction
end
example (h1 : false) : ∀ (a b c : nat), a = 0 → b = 0 → f (λ x y, a + x = b + c + y) :=
begin
intros,
trace_state,
contradiction
end
|
e2af4947a0e352c2b5f4beaccbe0f2ec1c1d70d8 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/sebastien_coe_simp.lean | 71ebc36052f770436d6a96700b51fd7c85605d4d | [
"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 | 540 | lean | variable (α : Type*)
structure my_equiv :=
(to_fun : α → α)
instance : has_coe_to_fun (my_equiv α) _ := ⟨my_equiv.to_fun⟩
def my_equiv1 : my_equiv α :=
{ to_fun := id }
def my_equiv2 : my_equiv α :=
{ to_fun := id }
@[simp] lemma one_eq_two : my_equiv1 α = my_equiv2 α := rfl
lemma other (x : ℕ) : my_equiv1 ℕ (x + 0) = my_equiv2 ℕ x := by simp [nat.add_zero] -- does not fail
@[simp] lemma two_apply (x : α) : my_equiv2 α x = x := rfl
lemma one_apply (x : α) : my_equiv1 α x = x := by simp -- does not fail
|
7ec94771b0296a5b80b2fb309599b017352cbfc6 | e514e8b939af519a1d5e9b30a850769d058df4e9 | /src/lib_unused/expr.lean | 52916b12b9f80c23c8627cf5c017a29882a354ec | [] | no_license | semorrison/lean-rewrite-search | dca317c5a52e170fb6ffc87c5ab767afb5e3e51a | e804b8f2753366b8957be839908230ee73f9e89f | refs/heads/master | 1,624,051,754,485 | 1,614,160,817,000 | 1,614,160,817,000 | 162,660,605 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 3,269 | lean | import data.list
import tactic.where
import lib.string
namespace binder
meta def set_name : binder → _root_.name → binder
| ⟨_, bi, e⟩ n := ⟨n, bi, e⟩
meta def set_type : binder → expr → binder
| ⟨n, bi, _⟩ e := ⟨n, bi, e⟩
meta def set_binder_info : binder → _root_.binder_info → binder
| ⟨n, _, e⟩ bi := ⟨n, bi, e⟩
meta def pretty_print : binder → tactic string
| ⟨n, bi, e⟩ := let brackets := bi.brackets in do
ppe ← to_string <$> tactic.pp e,
return $ brackets.1 ++ n.to_string ++ " : " ++ ppe ++ brackets.2
private meta def instantiate_list_aux : list binder → list binder → list binder
| seen [] := seen
| seen (⟨n, bi, e⟩ :: rest) :=
let e := e.instantiate_vars $ seen.reverse.map $ λ v, expr.const v.1 [] in
instantiate_list_aux (seen.concat ⟨n, bi, e⟩) rest
meta def instantiate_list : list binder → list binder :=
instantiate_list_aux []
meta def instantiate (e : expr) (l : list binder) : expr :=
e.instantiate_vars $ l.reverse.map $ λ v : binder, expr.const v.1 []
meta def drop_implicit : binder → option binder
| ⟨n, binder_info.default, e⟩ := some ⟨n, binder_info.default, e⟩
| _ := none
meta def list_to_args (l : list binder) (drop_impl : bool := tt) : tactic string := do
l ← (instantiate_list l).mmap binder.pretty_print,
return $ string.intercalate " " l
meta def list_to_invocation (l : list binder) (drop_impl : bool := tt) : string :=
let l := if drop_impl then l.filter_map drop_implicit else l in
string.intercalate " " $ (instantiate_list l).map $ to_string ∘ binder.name
end binder
namespace expr
private meta def unroll_pi_binders_aux : list binder → expr → list binder × expr
| curr (expr.pi var_n bi var_type rest) :=
unroll_pi_binders_aux (curr.concat ⟨var_n, bi, var_type⟩) rest
| curr ex := (curr, ex)
meta def unroll_pi_binders : expr → list binder × expr :=
unroll_pi_binders_aux []
private meta def unroll_lam_binders_aux : list binder → expr → list binder × expr
| curr (expr.lam var_n bi var_type rest) :=
unroll_lam_binders_aux (curr.concat ⟨var_n, bi, var_type⟩) rest
| curr ex := (curr, ex)
meta def unroll_lam_binders : expr → list binder × expr :=
unroll_lam_binders_aux []
end expr
namespace app
meta def count : expr → ℕ
| (expr.app e _) := 1 + count e
| _ := 0
meta def pop_n : expr → ℕ → expr
| e 0 := e
| (expr.app e _) n := pop_n e (n - 1)
| e _ := e
meta def pop (e : expr) : expr := pop_n e 1
meta def get_arg : expr → option expr
| (expr.app _ f) := some f
| _ := none
meta def chop : expr → option (name × list level × list expr)
| (expr.const n us) := some (n, us, [])
| (expr.app e v) :=
match chop e with
| none := none
| some (n, us, vs) := some (n, us, (v :: vs))
end
| _ := none
meta def name (e : expr) : option name :=
match chop e with
| none := none
| some (n, _, _) := n
end
end app
namespace structure_instance
meta def extract_nth_field (st : expr) (n : ℕ) : option expr :=
app.get_arg $ app.pop_n st ((app.count st) - (n + 1))
meta def extract_field (st : expr) (pi : environment.projection_info) : option expr :=
extract_nth_field st (pi.nparams + pi.idx)
end structure_instance
|
4894ce380042827fe598d6a1db978c573a5a970c | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/combinatorics/set_family/lym.lean | 8d47f70ced332e14ef8dcf0aafbe2ada25a96df4 | [
"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,426 | lean | /-
Copyright (c) 2022 Bhavik Mehta, Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Alena Gusakov, Yaël Dillies
-/
import algebra.big_operators.ring
import algebra.order.field.basic
import combinatorics.double_counting
import combinatorics.set_family.shadow
import data.rat.order
/-!
# Lubell-Yamamoto-Meshalkin inequality and Sperner's theorem
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file proves the local LYM and LYM inequalities as well as Sperner's theorem.
## Main declarations
* `finset.card_div_choose_le_card_shadow_div_choose`: Local Lubell-Yamamoto-Meshalkin inequality.
The shadow of a set `𝒜` in a layer takes a greater proportion of its layer than `𝒜` does.
* `finset.sum_card_slice_div_choose_le_one`: Lubell-Yamamoto-Meshalkin inequality. The sum of
densities of `𝒜` in each layer is at most `1` for any antichain `𝒜`.
* `is_antichain.sperner`: Sperner's theorem. The size of any antichain in `finset α` is at most the
size of the maximal layer of `finset α`. It is a corollary of `sum_card_slice_div_choose_le_one`.
## TODO
Prove upward local LYM.
Provide equality cases. Local LYM gives that the equality case of LYM and Sperner is precisely when
`𝒜` is a middle layer.
`falling` could be useful more generally in grade orders.
## References
* http://b-mehta.github.io/maths-notes/iii/mich/combinatorics.pdf
* http://discretemath.imp.fu-berlin.de/DMII-2015-16/kruskal.pdf
## Tags
shadow, lym, slice, sperner, antichain
-/
open finset nat
open_locale big_operators finset_family
variables {𝕜 α : Type*} [linear_ordered_field 𝕜]
namespace finset
/-! ### Local LYM inequality -/
section local_lym
variables [decidable_eq α] [fintype α] {𝒜 : finset (finset α)} {r : ℕ}
/-- The downward **local LYM inequality**, with cancelled denominators. `𝒜` takes up less of `α^(r)`
(the finsets of card `r`) than `∂𝒜` takes up of `α^(r - 1)`. -/
lemma card_mul_le_card_shadow_mul (h𝒜 : (𝒜 : set (finset α)).sized r) :
𝒜.card * r ≤ (∂𝒜).card * (fintype.card α - r + 1) :=
begin
refine card_mul_le_card_mul' (⊆) (λ s hs, _) (λ s hs, _),
{ rw [←h𝒜 hs, ←card_image_of_inj_on s.erase_inj_on],
refine card_le_of_subset _,
simp_rw [image_subset_iff, mem_bipartite_below],
exact λ a ha, ⟨erase_mem_shadow hs ha, erase_subset _ _⟩ },
refine le_trans _ tsub_tsub_le_tsub_add,
rw [←h𝒜.shadow hs, ←card_compl, ←card_image_of_inj_on (insert_inj_on' _)],
refine card_le_of_subset (λ t ht, _),
apply_instance,
rw mem_bipartite_above at ht,
have : ∅ ∉ 𝒜,
{ rw [←mem_coe, h𝒜.empty_mem_iff, coe_eq_singleton],
rintro rfl,
rwa shadow_singleton_empty at hs },
obtain ⟨a, ha, rfl⟩ :=
exists_eq_insert_iff.2 ⟨ht.2, by rw [(sized_shadow_iff this).1 h𝒜.shadow ht.1, h𝒜.shadow hs]⟩,
exact mem_image_of_mem _ (mem_compl.2 ha),
end
/-- The downward **local LYM inequality**. `𝒜` takes up less of `α^(r)` (the finsets of card `r`)
than `∂𝒜` takes up of `α^(r - 1)`. -/
lemma card_div_choose_le_card_shadow_div_choose (hr : r ≠ 0) (h𝒜 : (𝒜 : set (finset α)).sized r) :
(𝒜.card : 𝕜) / (fintype.card α).choose r ≤ (∂𝒜).card / (fintype.card α).choose (r - 1) :=
begin
obtain hr' | hr' := lt_or_le (fintype.card α) r,
{ rw [choose_eq_zero_of_lt hr', cast_zero, div_zero],
exact div_nonneg (cast_nonneg _) (cast_nonneg _) },
replace h𝒜 := card_mul_le_card_shadow_mul h𝒜,
rw div_le_div_iff; norm_cast,
{ cases r,
{ exact (hr rfl).elim },
rw nat.succ_eq_add_one at *,
rw [tsub_add_eq_add_tsub hr', add_tsub_add_eq_tsub_right] at h𝒜,
apply le_of_mul_le_mul_right _ (pos_iff_ne_zero.2 hr),
convert nat.mul_le_mul_right ((fintype.card α).choose r) h𝒜 using 1,
{ simp [mul_assoc, nat.choose_succ_right_eq],
exact or.inl (mul_comm _ _) },
{ simp only [mul_assoc, choose_succ_right_eq, mul_eq_mul_left_iff],
exact or.inl (mul_comm _ _) } },
{ exact nat.choose_pos hr' },
{ exact nat.choose_pos (r.pred_le.trans hr') }
end
end local_lym
/-! ### LYM inequality -/
section lym
section falling
variables [decidable_eq α] (k : ℕ) (𝒜 : finset (finset α))
/-- `falling k 𝒜` is all the finsets of cardinality `k` which are a subset of something in `𝒜`. -/
def falling : finset (finset α) := 𝒜.sup $ powerset_len k
variables {𝒜 k} {s : finset α}
lemma mem_falling : s ∈ falling k 𝒜 ↔ (∃ t ∈ 𝒜, s ⊆ t) ∧ s.card = k :=
by simp_rw [falling, mem_sup, mem_powerset_len, exists_and_distrib_right]
variables (𝒜 k)
lemma sized_falling : (falling k 𝒜 : set (finset α)).sized k := λ s hs, (mem_falling.1 hs).2
lemma slice_subset_falling : 𝒜 # k ⊆ falling k 𝒜 :=
λ s hs, mem_falling.2 $ (mem_slice.1 hs).imp_left $ λ h, ⟨s, h, subset.refl _⟩
lemma falling_zero_subset : falling 0 𝒜 ⊆ {∅} :=
subset_singleton_iff'.2 $ λ t ht, card_eq_zero.1 $ sized_falling _ _ ht
lemma slice_union_shadow_falling_succ : 𝒜 # k ∪ ∂ (falling (k + 1) 𝒜) = falling k 𝒜 :=
begin
ext s,
simp_rw [mem_union, mem_slice, mem_shadow_iff, exists_prop, mem_falling],
split,
{ rintro (h | ⟨s, ⟨⟨t, ht, hst⟩, hs⟩, a, ha, rfl⟩),
{ exact ⟨⟨s, h.1, subset.refl _⟩, h.2⟩ },
refine ⟨⟨t, ht, (erase_subset _ _).trans hst⟩, _⟩,
rw [card_erase_of_mem ha, hs],
refl },
{ rintro ⟨⟨t, ht, hst⟩, hs⟩,
by_cases s ∈ 𝒜,
{ exact or.inl ⟨h, hs⟩ },
obtain ⟨a, ha, hst⟩ := ssubset_iff.1
(ssubset_of_subset_of_ne hst (ht.ne_of_not_mem h).symm),
refine or.inr ⟨insert a s, ⟨⟨t, ht, hst⟩, _⟩, a, mem_insert_self _ _, erase_insert ha⟩,
rw [card_insert_of_not_mem ha, hs] }
end
variables {𝒜 k}
/-- The shadow of `falling m 𝒜` is disjoint from the `n`-sized elements of `𝒜`, thanks to the
antichain property. -/
lemma _root_.is_antichain.disjoint_slice_shadow_falling {m n : ℕ}
(h𝒜 : is_antichain (⊆) (𝒜 : set (finset α))) :
disjoint (𝒜 # m) (∂ (falling n 𝒜)) :=
disjoint_right.2 $ λ s h₁ h₂,
begin
simp_rw [mem_shadow_iff, exists_prop, mem_falling] at h₁,
obtain ⟨s, ⟨⟨t, ht, hst⟩, hs⟩, a, ha, rfl⟩ := h₁,
refine h𝒜 (slice_subset h₂) ht _ ((erase_subset _ _).trans hst),
rintro rfl,
exact not_mem_erase _ _ (hst ha),
end
/-- A bound on any top part of the sum in LYM in terms of the size of `falling k 𝒜`. -/
lemma le_card_falling_div_choose [fintype α] (hk : k ≤ fintype.card α)
(h𝒜 : is_antichain (⊆) (𝒜 : set (finset α))) :
∑ r in range (k + 1),
((𝒜 # (fintype.card α - r)).card : 𝕜) / (fintype.card α).choose (fintype.card α - r)
≤ (falling (fintype.card α - k) 𝒜).card / (fintype.card α).choose (fintype.card α - k) :=
begin
induction k with k ih,
{ simp only [tsub_zero, cast_one, cast_le, sum_singleton, div_one, choose_self, range_one],
exact card_le_of_subset (slice_subset_falling _ _) },
rw succ_eq_add_one at *,
rw [sum_range_succ, ←slice_union_shadow_falling_succ,
card_disjoint_union h𝒜.disjoint_slice_shadow_falling, cast_add, _root_.add_div, add_comm],
rw [←tsub_tsub, tsub_add_cancel_of_le (le_tsub_of_add_le_left hk)],
exact add_le_add_left ((ih $ le_of_succ_le hk).trans $ card_div_choose_le_card_shadow_div_choose
(tsub_pos_iff_lt.2 $ nat.succ_le_iff.1 hk).ne' $ sized_falling _ _) _,
end
end falling
variables {𝒜 : finset (finset α)} {s : finset α} {k : ℕ}
/-- The **Lubell-Yamamoto-Meshalkin inequality**. If `𝒜` is an antichain, then the sum of the
proportion of elements it takes from each layer is less than `1`. -/
lemma sum_card_slice_div_choose_le_one [fintype α] (h𝒜 : is_antichain (⊆) (𝒜 : set (finset α))) :
∑ r in range (fintype.card α + 1), ((𝒜 # r).card : 𝕜) / (fintype.card α).choose r ≤ 1 :=
begin
classical,
rw ←sum_flip,
refine (le_card_falling_div_choose le_rfl h𝒜).trans _,
rw div_le_iff; norm_cast,
{ simpa only [nat.sub_self, one_mul, nat.choose_zero_right, falling]
using (sized_falling 0 𝒜).card_le },
{ rw [tsub_self, choose_zero_right],
exact zero_lt_one }
end
end lym
/-! ### Sperner's theorem -/
/-- **Sperner's theorem**. The size of an antichain in `finset α` is bounded by the size of the
maximal layer in `finset α`. This precisely means that `finset α` is a Sperner order. -/
lemma _root_.is_antichain.sperner [fintype α] {𝒜 : finset (finset α)}
(h𝒜 : is_antichain (⊆) (𝒜 : set (finset α))) :
𝒜.card ≤ (fintype.card α).choose (fintype.card α / 2) :=
begin
classical,
suffices : ∑ r in Iic (fintype.card α),
((𝒜 # r).card : ℚ) / (fintype.card α).choose (fintype.card α / 2) ≤ 1,
{ rwa [←sum_div, ←nat.cast_sum, div_le_one, cast_le, sum_card_slice] at this,
norm_cast,
exact choose_pos (nat.div_le_self _ _) },
rw [Iic_eq_Icc, ←Ico_succ_right, bot_eq_zero, Ico_zero_eq_range],
refine (sum_le_sum $ λ r hr, _).trans (sum_card_slice_div_choose_le_one h𝒜),
rw mem_range at hr,
refine div_le_div_of_le_left _ _ _; norm_cast,
{ exact nat.zero_le _ },
{ exact choose_pos (lt_succ_iff.1 hr) },
{ exact choose_le_middle _ _ }
end
end finset
|
be48987d11f516d45f25fdff6970f3a099a74c31 | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/topology/algebra/continuous_functions.lean | 773f8dbe4b742be5fee2515dae6918c8065af5ef | [
"Apache-2.0"
] | permissive | eric-wieser/mathlib | 42842584f584359bbe1fc8b88b3ff937c8acd72d | d0df6b81cd0920ad569158c06a3fd5abb9e63301 | refs/heads/master | 1,669,546,404,255 | 1,595,254,668,000 | 1,595,254,668,000 | 281,173,504 | 0 | 0 | Apache-2.0 | 1,595,263,582,000 | 1,595,263,581,000 | null | UTF-8 | Lean | false | false | 7,819 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import topology.algebra.module
/- TODO: change subtype of continuous functions into continuous bundled functions. -/
universes u v
local attribute [elab_simple] continuous.comp
namespace continuous_functions
variables {α : Type*} {β : Type*} [topological_space α] [topological_space β]
variables {f g : {f : α → β | continuous f }}
instance : has_coe_to_fun {f : α → β | continuous f } := ⟨_, subtype.val⟩
end continuous_functions
section group_structure
/-!
### Group stucture
In this section we show that continuous functions valued in a topological group inherit
the structure of a group.
-/
@[to_additive continuous_add_submonoid]
instance continuous_submonoid (α : Type u) (β : Type v) [topological_space α] [topological_space β]
[monoid β] [topological_monoid β] : is_submonoid { f : α → β | continuous f } :=
{ one_mem := @continuous_const _ _ _ _ 1,
mul_mem :=
λ f g fc gc, continuous.comp topological_monoid.continuous_mul (continuous.prod_mk fc gc) }.
@[to_additive continuous_add_subgroup]
instance continuous_subgroup (α : Type u) (β : Type v) [topological_space α] [topological_space β]
[group β] [topological_group β] : is_subgroup { f : α → β | continuous f } :=
{ inv_mem := λ f fc, continuous.comp topological_group.continuous_inv fc,
..continuous_submonoid α β, }.
@[to_additive continuous_add_monoid]
instance continuous_monoid {α : Type u} {β : Type v} [topological_space α] [topological_space β]
[monoid β] [topological_monoid β] : monoid { f : α → β | continuous f } :=
subtype.monoid
@[to_additive continuous_add_group]
instance continuous_group {α : Type u} {β : Type v} [topological_space α] [topological_space β]
[group β] [topological_group β] : group { f : α → β | continuous f } :=
subtype.group
@[to_additive continuous_add_comm_group]
instance continuous_comm_group {α : Type*} {β : Type*} [topological_space α] [topological_space β]
[comm_group β] [topological_group β] : comm_group { f : α → β | continuous f } :=
@subtype.comm_group _ _ _ (continuous_subgroup α β) -- infer_instance doesn't work?!
end group_structure
section ring_structure
/-!
### Ring stucture
In this section we show that continuous functions valued in a topological ring `R` inherit
the structure of a ring.
-/
instance continuous_subring (α : Type u) (R : Type v) [topological_space α] [topological_space R]
[ring R] [topological_ring R] : is_subring { f : α → R | continuous f } :=
{ ..continuous_add_subgroup α R,
..continuous_submonoid α R }.
instance continuous_ring {α : Type u} {R : Type v} [topological_space α] [topological_space R]
[ring R] [topological_ring R] : ring { f : α → R | continuous f } :=
@subtype.ring _ _ _ (continuous_subring α R) -- infer_instance doesn't work?!
instance continuous_comm_ring {α : Type u} {R : Type v} [topological_space α] [topological_space R]
[comm_ring R] [topological_ring R] : comm_ring { f : α → R | continuous f } :=
@subtype.comm_ring _ _ _ (continuous_subring α R) -- infer_instance doesn't work?!
end ring_structure
local attribute [ext] subtype.eq
section semimodule_structure
/-!
### Semiodule stucture
In this section we show that continuous functions valued in a topological semimodule `M` over a
topological semiring `R` inherit the structure of a semimodule.
-/
instance continuous_has_scalar {α : Type*} [topological_space α]
(R : Type*) [semiring R] [topological_space R]
(M : Type*) [topological_space M] [add_comm_group M]
[semimodule R M] [topological_semimodule R M] :
has_scalar R { f : α → M | continuous f } :=
⟨λ r f, ⟨r • f, continuous_const.smul f.property⟩⟩
instance continuous_semimodule {α : Type*} [topological_space α]
{R : Type*} [semiring R] [topological_space R]
{M : Type*} [topological_space M] [add_comm_group M] [topological_add_group M]
[semimodule R M] [topological_semimodule R M] :
semimodule R { f : α → M | continuous f } :=
semimodule.of_core $
{ smul := (•),
smul_add := λ c f g, by ext x; exact smul_add c (f x) (g x),
add_smul := λ c₁ c₂ f, by ext x; exact add_smul c₁ c₂ (f x),
mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul c₁ c₂ (f x),
one_smul := λ f, by ext x; exact one_smul R (f x) }
end semimodule_structure
section algebra_structure
/-!
### Algebra structure
In this section we show that continuous functions valued in a topological algebra `A` over a ring
`R` inherit the structure of an algebra. Note that the hypothesis that `A` is a topological algebra is
obtained by requiring that `A` be both a `topological_semimodule` and a `topological_semiring`
(by now we require `topological_ring`: see TODO below).-/
variables {α : Type*} [topological_space α]
{R : Type*} [comm_semiring R]
{A : Type*} [topological_space A] [ring A]
[algebra R A] [topological_ring A]
/-- Continuous constant functions as a `ring_hom`. -/
def C : R →+* { f : α → A | continuous f } :=
{ to_fun := λ c : R, ⟨λ x: α, ((algebra_map R A) c), continuous_const⟩,
map_one' := by ext x; exact (algebra_map R A).map_one,
map_mul' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_mul _ _,
map_zero' := by ext x; exact (algebra_map R A).map_zero,
map_add' := λ c₁ c₂, by ext x; exact (algebra_map R A).map_add _ _ }
variables [topological_space R] [topological_semimodule R A]
instance : algebra R { f : α → A | continuous f } :=
{ to_ring_hom := C,
commutes' := λ c f, by ext x; exact algebra.commutes' _ _,
smul_def' := λ c f, by ext x; exact algebra.smul_def' _ _,
..continuous_semimodule,
..continuous_ring }
/- TODO: We are assuming `A` to be a ring and not a semiring just because there is not yet an
instance of semiring. In turn, we do not want to define yet an instance of semiring because there is
no `is_subsemiring` but only `subsemiring`, and it will make sense to change this when the whole
file will have no more `is_subobject`s but only `subobject`s. It does not make sense to change
it yet in this direction as `subring` does not exist yet, so everything is being blocked by
`subring`: afterwards everything will need to be updated to the new conventions of Mathlib.
Then the instance of `topological_ring` can also be removed. -/
end algebra_structure
section module_over_continuous_functions
/-!
### Structure as module over scalar functions
If `M` is a module over `R`, then we show that the space of continuous functions from `α` to `M`
is naturally a module over the algebra of continuous functions from `α` to `M`. -/
instance continuous_has_scalar' {α : Type*} [topological_space α]
{R : Type*} [semiring R] [topological_space R]
{M : Type*} [topological_space M] [add_comm_group M]
[semimodule R M] [topological_semimodule R M] :
has_scalar { f : α → R | continuous f } { f : α → M | continuous f } :=
⟨λ f g, ⟨λ x, (f x) • (g x), (continuous.smul f.2 g.2)⟩⟩
instance continuous_module' {α : Type*} [topological_space α]
(R : Type*) [ring R] [topological_space R] [topological_ring R]
(M : Type*) [topological_space M] [add_comm_group M] [topological_add_group M]
[module R M] [topological_module R M]
: module { f : α → R | continuous f } { f : α → M | continuous f } :=
semimodule.of_core $
{ smul := (•),
smul_add := λ c f g, by ext x; exact smul_add (c x) (f x) (g x),
add_smul := λ c₁ c₂ f, by ext x; exact add_smul (c₁ x) (c₂ x) (f x),
mul_smul := λ c₁ c₂ f, by ext x; exact mul_smul (c₁ x) (c₂ x) (f x),
one_smul := λ f, by ext x; exact one_smul R (f x) }
end module_over_continuous_functions
|
adf9330782532bb10f049fc6e92958b39cd58ea1 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/number_theory/primorial.lean | 0a8783bf1999021e2c5b94c8a2e4d45ed2722ebc | [
"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 | 7,372 | lean | /-
Copyright (c) 2020 Patrick Stevens. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Stevens
-/
import tactic.ring_exp
import data.nat.parity
import data.nat.choose.sum
/-!
# Primorial
This file defines the primorial function (the product of primes less than or equal to some bound),
and proves that `primorial n ≤ 4 ^ n`.
## Notations
We use the local notation `n#` for the primorial of `n`: that is, the product of the primes less
than or equal to `n`.
-/
open finset
open nat
open_locale big_operators nat
/-- The primorial `n#` of `n` is the product of the primes less than or equal to `n`.
-/
def primorial (n : ℕ) : ℕ := ∏ p in (filter prime (range (n + 1))), p
local notation x`#` := primorial x
lemma primorial_succ {n : ℕ} (n_big : 1 < n) (r : n % 2 = 1) : (n + 1)# = n# :=
begin
have not_prime : ¬prime (n + 1),
{ intros is_prime,
cases (prime.eq_two_or_odd is_prime) with _ n_even,
{ linarith, },
{ exfalso,
rw ←not_even_iff at n_even r,
have e : even (n + 1 - n) := (even_sub (lt_add_one n).le).2 (iff_of_false n_even r),
simp only [nat.add_sub_cancel_left, not_even_one] at e,
exact e, }, },
apply finset.prod_congr,
{ rw [@range_succ (n + 1), filter_insert, if_neg not_prime], },
{ exact λ _ _, rfl, },
end
lemma dvd_choose_of_middling_prime (p : ℕ) (is_prime : prime p) (m : ℕ)
(p_big : m + 1 < p) (p_small : p ≤ 2 * m + 1) : p ∣ choose (2 * m + 1) (m + 1) :=
begin
have m_size : m + 1 ≤ 2 * m + 1 := le_of_lt (lt_of_lt_of_le p_big p_small),
have expanded :
choose (2 * m + 1) (m + 1) * (m + 1)! * (2 * m + 1 - (m + 1))! = (2 * m + 1)! :=
@choose_mul_factorial_mul_factorial (2 * m + 1) (m + 1) m_size,
have p_div_big_fact : p ∣ (2 * m + 1)! := (prime.dvd_factorial is_prime).mpr p_small,
rw [←expanded, mul_assoc] at p_div_big_fact,
have s : ¬(p ∣ (m + 1)!),
{ intros p_div_fact,
have p_le_succ_m : p ≤ m + 1 := (prime.dvd_factorial is_prime).mp p_div_fact,
linarith, },
have t : ¬(p ∣ (2 * m + 1 - (m + 1))!),
{ intros p_div_fact,
have p_small : p ≤ 2 * m + 1 - (m + 1) := (prime.dvd_factorial is_prime).mp p_div_fact,
have t : 2 * m + 1 - (m + 1) = m, by { norm_num, rw two_mul m, exact nat.add_sub_cancel m m, },
rw t at p_small,
obtain p_lt_m | rfl | m_lt_p : _ := lt_trichotomy p m,
{ have r : m < m + 1 := lt_add_one m, linarith, },
{ linarith, },
{ linarith, }, },
obtain p_div_choose | p_div_facts : p ∣ choose (2 * m + 1) (m + 1) ∨ p ∣ _! * _! :=
(prime.dvd_mul is_prime).1 p_div_big_fact,
{ exact p_div_choose, },
cases (prime.dvd_mul is_prime).1 p_div_facts,
cc, cc,
end
lemma prod_primes_dvd {s : finset ℕ} : ∀ (n : ℕ) (h : ∀ a ∈ s, prime a) (div : ∀ a ∈ s, a ∣ n),
(∏ p in s, p) ∣ n :=
begin
apply finset.induction_on s,
{ simp, },
{ intros a s a_not_in_s induct n primes divs,
rw finset.prod_insert a_not_in_s,
obtain ⟨k, rfl⟩ : a ∣ n, by exact divs a (finset.mem_insert_self a s),
have step : ∏ p in s, p ∣ k,
{ apply induct k,
{ intros b b_in_s,
exact primes b (finset.mem_insert_of_mem b_in_s), },
{ intros b b_in_s,
have b_div_n, by exact divs b (finset.mem_insert_of_mem b_in_s),
have a_prime : prime a, { exact primes a (finset.mem_insert_self a s), },
have b_prime : prime b, { exact primes b (finset.mem_insert_of_mem b_in_s), },
obtain b_div_a | b_div_k : b ∣ a ∨ b ∣ k, exact (prime.dvd_mul b_prime).mp b_div_n,
{ exfalso,
have b_eq_a : b = a,
{ cases (nat.dvd_prime a_prime).1 b_div_a with b_eq_1 b_eq_a,
{ subst b_eq_1, exfalso, exact prime.ne_one b_prime rfl, },
{ exact b_eq_a } },
subst b_eq_a,
exact a_not_in_s b_in_s, },
{ exact b_div_k } } },
exact mul_dvd_mul_left a step, }
end
lemma primorial_le_4_pow : ∀ (n : ℕ), n# ≤ 4 ^ n
| 0 := le_refl _
| 1 := le_of_inf_eq rfl
| (n + 2) :=
match nat.mod_two_eq_zero_or_one (n + 1) with
| or.inl n_odd :=
match nat.even_iff.2 n_odd with
| ⟨m, twice_m⟩ :=
let recurse : m + 1 < n + 2 := by linarith in
begin
calc (n + 2)#
= ∏ i in filter prime (range (2 * m + 2)), i : by simpa [←twice_m]
... = ∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2) ∪ range (m + 2)), i :
begin
rw [range_eq_Ico, finset.union_comm, finset.Ico_union_Ico_eq_Ico],
exact bot_le,
simp only [add_le_add_iff_right],
linarith,
end
... = ∏ i in (filter prime (finset.Ico (m + 2) (2 * m + 2))
∪ (filter prime (range (m + 2)))), i :
by rw filter_union
... = (∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2)), i)
* (∏ i in filter prime (range (m + 2)), i) :
begin
apply finset.prod_union,
have disj : disjoint (finset.Ico (m + 2) (2 * m + 2)) (range (m + 2)),
{ simp only [finset.disjoint_left, and_imp, finset.mem_Ico, not_lt,
finset.mem_range],
intros _ pr _, exact pr, },
exact finset.disjoint_filter_filter disj,
end
... ≤ (∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2)), i) * 4 ^ (m + 1) :
by exact nat.mul_le_mul_left _ (primorial_le_4_pow (m + 1))
... ≤ (choose (2 * m + 1) (m + 1)) * 4 ^ (m + 1) :
begin
have s : ∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2)),
i ∣ choose (2 * m + 1) (m + 1),
{ refine prod_primes_dvd (choose (2 * m + 1) (m + 1)) _ _,
{ intros a, rw finset.mem_filter, cc, },
{ intros a, rw finset.mem_filter,
intros pr,
rcases pr with ⟨ size, is_prime ⟩,
simp only [finset.mem_Ico] at size,
rcases size with ⟨ a_big , a_small ⟩,
exact dvd_choose_of_middling_prime a is_prime m a_big
(nat.lt_succ_iff.mp a_small), }, },
have r : ∏ i in filter prime (finset.Ico (m + 2) (2 * m + 2)),
i ≤ choose (2 * m + 1) (m + 1),
{ refine @nat.le_of_dvd _ _ _ s,
exact @choose_pos (2 * m + 1) (m + 1) (by linarith), },
exact nat.mul_le_mul_right _ r,
end
... = (choose (2 * m + 1) m) * 4 ^ (m + 1) : by rw choose_symm_half m
... ≤ 4 ^ m * 4 ^ (m + 1) : nat.mul_le_mul_right _ (choose_middle_le_pow m)
... = 4 ^ (2 * m + 1) : by ring_exp
... = 4 ^ (n + 2) : by rw ←twice_m,
end
end
| or.inr n_even :=
begin
obtain one_lt_n | n_le_one : 1 < n + 1 ∨ n + 1 ≤ 1 := lt_or_le 1 (n + 1),
{ rw primorial_succ (by linarith) n_even,
calc (n + 1)#
≤ 4 ^ n.succ : primorial_le_4_pow (n + 1)
... ≤ 4 ^ (n + 2) : pow_le_pow (by norm_num) (nat.le_succ _), },
{ have n_zero : n = 0 := eq_bot_iff.2 (succ_le_succ_iff.1 n_le_one),
norm_num [n_zero, primorial, range_succ, prod_filter, not_prime_zero, prime_two] },
end
end
|
aacff130321849619e5ff86a3b592868e6e51e13 | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /field_theory/subfield.lean | fef9b531c2f137c6efe64b90053b30c6e9e1cd13 | [
"Apache-2.0"
] | permissive | amswerdlow/mathlib | 9af77a1f08486d8fa059448ae2d97795bd12ec0c | 27f96e30b9c9bf518341705c99d641c38638dfd0 | refs/heads/master | 1,585,200,953,598 | 1,534,275,532,000 | 1,534,275,532,000 | 144,564,700 | 0 | 0 | null | 1,534,156,197,000 | 1,534,156,197,000 | null | UTF-8 | Lean | false | false | 2,009 | lean | /-
Copyright (c) 2018 Andreas Swerdlow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andreas Swerdlow
-/
import ring_theory.subring
variables {F : Type*}
class is_subfield [field F] (s : set F) extends is_subring s :=
(inv_mem : ∀ {x : F}, x ∈ s → x⁻¹ ∈ s)
open is_subfield is_submonoid is_add_submonoid
instance subtype.field [field F] (s : set F) [is_subfield s] : field s :=
{
add := λ (a b : s), ⟨a.val + b.val, add_mem a.property b.property⟩,
add_assoc := assume ⟨a, _⟩ ⟨b, _⟩ ⟨c, _⟩, subtype.eq (add_assoc a b c),
zero := ⟨0, zero_mem s⟩,
zero_add := assume ⟨a, _⟩, subtype.eq (zero_add a),
add_zero := assume ⟨a, _⟩, subtype.eq (add_zero a),
neg := λ (a : s), ⟨ -a.val, is_add_subgroup.neg_mem a.property⟩ ,
add_left_neg := assume ⟨a, _⟩, subtype.eq (add_left_neg a),
add_comm := assume ⟨a, _⟩ ⟨b, _⟩, subtype.eq (add_comm a b),
mul := λ (a b : s), ⟨a.val * b.val, mul_mem a.property b.property⟩,
mul_assoc := assume ⟨a, _⟩ ⟨b, _⟩ ⟨c, _⟩, subtype.eq (mul_assoc a b c),
one := ⟨1, one_mem s⟩,
one_mul := assume ⟨a, _⟩, subtype.eq (one_mul a),
mul_one := assume ⟨a, _⟩, subtype.eq (mul_one a),
left_distrib := assume ⟨a, _⟩ ⟨b, _⟩ ⟨c, _⟩, subtype.eq (left_distrib a b c),
right_distrib := assume ⟨a, _⟩ ⟨b, _⟩ ⟨c, _⟩, subtype.eq (right_distrib a b c),
inv := λ (a : s), ⟨a.val⁻¹, inv_mem a.property⟩,
zero_ne_one := begin apply (iff_false_left zero_ne_one).mp, simp, exact F, apply_instance, end,
mul_inv_cancel := assume ⟨a, _⟩, λ h, subtype.eq (mul_inv_cancel ((iff_false_left (not_not_intro h)).mp (begin dunfold ne, rw auto.not_not_eq, apply subtype.ext, end))),
inv_mul_cancel := assume ⟨a, _⟩, λ h, subtype.eq (inv_mul_cancel ((iff_false_left (not_not_intro h)).mp (begin dunfold ne, rw auto.not_not_eq, apply subtype.ext, end))),
mul_comm := assume ⟨a, _⟩ ⟨b, _⟩, subtype.eq (mul_comm a b),
}
|
c328b62ae18059e57e8c31f0f175d5b40c2cf812 | 7c2dd01406c42053207061adb11703dc7ce0b5e5 | /src/solutions/04_exists.lean | 693bbd345cdcdb3174b815a3ac6cda05d9bf64ff | [
"Apache-2.0"
] | permissive | leanprover-community/tutorials | 50ec79564cbf2ad1afd1ac43d8ee3c592c2883a8 | 79a6872a755c4ae0c2aca57e1adfdac38b1d8bb1 | refs/heads/master | 1,687,466,144,386 | 1,672,061,276,000 | 1,672,061,276,000 | 189,169,918 | 186 | 81 | Apache-2.0 | 1,686,350,300,000 | 1,559,113,678,000 | Lean | UTF-8 | Lean | false | false | 3,021 | lean | import data.real.basic
import data.int.parity
/-
In this file, we learn how to handle the ∃ quantifier.
In order to prove `∃ x, P x`, we give some x₀ using tactic `use x₀` and
then prove `P x₀`. This x₀ can be an object from the local context
or a more complicated expression.
-/
example : ∃ n : ℕ, 8 = 2*n :=
begin
use 4,
refl, -- this is the tactic analogue of the rfl proof term
end
/-
In order to use `h : ∃ x, P x`, we use the `cases` tactic to fix
one x₀ that works.
Again h can come straight from the local context or can be a more
complicated expression.
-/
example (n : ℕ) (h : ∃ k : ℕ, n = k + 1) : n > 0 :=
begin
-- Let's fix k₀ such that n = k₀ + 1.
cases h with k₀ hk₀,
-- It now suffices to prove k₀ + 1 > 0.
rw hk₀,
-- and we have a lemma about this
exact nat.succ_pos k₀,
end
/-
The next exercises use divisibility in ℤ (beware the ∣ symbol which is
not ASCII).
By definition, a ∣ b ↔ ∃ k, b = a*k, so you can prove a ∣ b using the
`use` tactic.
-/
-- Until the end of this file, a, b and c will denote integers, unless
-- explicitly stated otherwise
variables (a b c : ℤ)
-- 0029
example (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c :=
begin
-- sorry
cases h₁ with k hk,
cases h₂ with l hl,
use k*l,
calc c = b*l : hl
... = (a*k)*l : by rw hk
... = a*(k*l) : by ring,
-- sorry
end
/-
A very common pattern is to have an assumption or lemma asserting
h : ∃ x, y = ...
and this is used through the combo:
cases h with x hx,
rw hx at ...
The tactic `rcases` allows us to do recursive `cases`, as indicated by its name,
and also simplifies the above combo when the name hx is replaced by the special
name `rfl`, as in the following example.
It uses the anonymous constructor angle brackets syntax.
-/
example (h1 : a ∣ b) (h2 : a ∣ c) : a ∣ b+c :=
begin
rcases h1 with ⟨k, rfl⟩,
rcases h2 with ⟨l, rfl⟩,
use k+l,
ring,
end
/-
You can use the same `rfl` trick with the `rintros` tactic.
-/
example : a ∣ b → a ∣ c → a ∣ b+c :=
begin
rintros ⟨k, rfl⟩ ⟨l, rfl⟩,
use k+l,
ring,
end
-- 0030
example : 0 ∣ a ↔ a = 0 :=
begin
-- sorry
split,
{ rintro ⟨k, rfl⟩,
ring, },
{ rintro rfl,
use 0,
refl, },
-- sorry
end
/-
We can now start combining quantifiers, using the definition
surjective (f : X → Y) := ∀ y, ∃ x, f x = y
-/
open function
-- In the remaining of this file, f and g will denote functions from
-- ℝ to ℝ.
variables (f g : ℝ → ℝ)
-- 0031
example (h : surjective (g ∘ f)) : surjective g :=
begin
-- sorry
intro y,
rcases h y with ⟨w, rfl⟩,
use f w,
-- sorry
end
/-
The above exercise can be done in three lines. Try to do the
next exercise in four lines.
-/
-- 0032
example (hf : surjective f) (hg : surjective g) : surjective (g ∘ f) :=
begin
-- sorry
intro z,
rcases hg z with ⟨y, rfl⟩,
rcases hf y with ⟨x, rfl⟩,
use x,
-- sorry
end
|
3e1126d05a9d718c225633bce7ed8c45401d15af | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/eqn_compiler_error_msg.lean | fb8c3758eb5327dfc93a728e5a1db1d2a5541c7e | [
"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 | 126 | lean | inductive R : ℕ → Prop
| pos : ∀p n, R (p + n)
lemma R_id : ∀n, R n → R n
| (.(p) + .(n)) (R.pos p n) := R.pos p n
|
7a863642dc12be35fa9fb808fa923acb3eeacdc5 | 9a2260f3b7b64ae9c50bf326fdb0387f5ac64683 | /src/NITRO/Tags.lean | 9986ab8aa0af309ca635617d3882790f5798eaf6 | [
"LicenseRef-scancode-mit-taylor-variant",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | o89/nitro | e8e1c7f3e7baeb7a659f899c605d37b1d3e553a6 | c62a67398a89d6e6a2e9da62350adaf5f17cfda9 | refs/heads/master | 1,670,068,174,264 | 1,669,086,407,000 | 1,669,086,407,000 | 204,147,098 | 3 | 5 | null | null | null | null | UTF-8 | Lean | false | false | 2,690 | lean | import N2O.Data.BERT
abbrev Name := String
inductive Attr : Type
| int : Name → Int → Attr
| str : Name → String → Attr
| list : Name → List String → Attr
| noVal : Name → Attr
structure Event (α : Type) :=
(source : List String) (type : String) (postback : α)
inductive Elem (α : Type) : Type
| tag : Name → List Attr → List (Elem α) → Elem α
| button : Name → List Attr → String → Event α → Elem α
| unpaired : Name → List Attr → Elem α
| liter : String → Elem α
def showAttrValue : Attr → Name × String
| Attr.int name v => (name, toString v)
| Attr.str name v => (name, v)
| Attr.list name v => (name, String.intercalate " " v)
| Attr.noVal name => (name, "")
def rendNameString : Name × String → String
| (name, "") => name
| (name, v) => name ++ "=\"" ++ v ++ "\""
def rendAttr := rendNameString ∘ showAttrValue
def rendAttrs := String.intercalate " " ∘ List.map rendAttr
def rendEvent {α : Type} [BERT α]
(target : String) (ev : Event α) : String :=
let join := String.intercalate ",";
let escape := λ s => "'" ++ s ++ "'";
let renderSource :=
λ s => "tuple(atom('" ++ s ++ "'),string(querySourceRaw('" ++ s ++ "')))";
match writeTerm (BERT.toTerm ev.postback) with
| Sum.ok v =>
"{ var x=qi('" ++ target ++ "'); x && x.addEventListener('" ++ ev.type ++
"',function(event){ if (validateSources([" ++ join (List.map escape ev.source) ++
"])) { ws.send(enc(tuple(atom('pickle'),bin('" ++ target ++
"'),bin(new Uint8Array(" ++ toString v ++ ")),[" ++
join (List.map renderSource ev.source) ++
"]))); } else console.log('Validation error'); })}"
| Sum.fail _ => ""
def htmlEscapeTable : List (Char × String) :=
[ ('&', "&"), ('<', "<"),
('>', ">"), (Char.ofNat 34, """),
('\'', "'"), ('/', "/") ]
-- definition through pattern-matching causes lags of typechecker
def htmlEscapeChar (ch : Char) : String :=
Option.getD (htmlEscapeTable.lookup ch) (String.singleton ch)
def htmlEscape : String → String :=
String.foldl (λ s => String.append s ∘ htmlEscapeChar) ""
abbrev Html := String
abbrev Javascript := String
partial def render {α : Type} [BERT α] : Elem α → Html × Javascript
| Elem.tag tag attrs body =>
let (html, js) := List.unzip (List.map render body);
("<" ++ tag ++ " " ++ rendAttrs attrs ++ ">" ++
String.join html ++
"</" ++ tag ++ ">", String.join js)
| Elem.button name attrs value ev =>
("<button " ++ rendAttrs (Attr.str "id" name :: attrs) ++
">" ++ value ++ "</button>",
rendEvent name ev)
| Elem.unpaired tag attrs =>
("<" ++ tag ++ " " ++ rendAttrs attrs ++ " />", "")
| Elem.liter str => (htmlEscape str, "")
|
4aca61e58b99b9af4c6db21025a80357e175d81e | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/data/nat/choose/dvd.lean | de94388ca425d7ec76028d139728b5ffe6e92be9 | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,784 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Patrick Stevens
-/
import data.nat.choose.basic
import data.nat.prime
/-!
# Divisibility properties of binomial coefficients
-/
namespace nat
open_locale nat
namespace prime
lemma dvd_choose_add {p a b : ℕ} (hap : a < p) (hbp : b < p) (h : p ≤ a + b)
(hp : prime p) : p ∣ choose (a + b) a :=
have h₁ : p ∣ (a + b)!, from hp.dvd_factorial.2 h,
have h₂ : ¬p ∣ a!, from mt hp.dvd_factorial.1 (not_le_of_gt hap),
have h₃ : ¬p ∣ b!, from mt hp.dvd_factorial.1 (not_le_of_gt hbp),
by
rw [← choose_mul_factorial_mul_factorial (le.intro rfl), mul_assoc, hp.dvd_mul, hp.dvd_mul,
nat.add_sub_cancel_left a b] at h₁;
exact h₁.resolve_right (not_or_distrib.2 ⟨h₂, h₃⟩)
lemma dvd_choose_self {p k : ℕ} (hk : 0 < k) (hkp : k < p) (hp : prime p) :
p ∣ choose p k :=
begin
have r : k + (p - k) = p,
by rw [← nat.add_sub_assoc (nat.le_of_lt hkp) k, nat.add_sub_cancel_left],
have e : p ∣ choose (k + (p - k)) k,
by exact dvd_choose_add hkp (nat.sub_lt (hk.trans hkp) hk) (by rw r) hp,
rwa r at e,
end
end prime
lemma cast_choose (K : Type*) [division_ring K] [char_zero K] {a b : ℕ} (h : a ≤ b) :
(b.choose a : K) = b! / (a! * (b - a)!) :=
begin
have : ∀ {n : ℕ}, (n! : K) ≠ 0 := λ n, nat.cast_ne_zero.2 (factorial_ne_zero _),
rw [eq_div_iff_mul_eq (mul_ne_zero this this)],
rw_mod_cast [← mul_assoc, choose_mul_factorial_mul_factorial h],
end
lemma cast_add_choose (K : Type*) [division_ring K] [char_zero K] {a b : ℕ} :
((a + b).choose a : K) = (a + b)! / (a! * b!) :=
by rw [cast_choose K (le_add_right le_rfl), nat.add_sub_cancel_left]
end nat
|
b6aa521b67658928ce3a04c8dbc13ca8bc30a154 | 827a8a5c2041b1d7f55e128581f583dfbd65ecf6 | /cpp.hlean | bee40329e7763ba3e8c3708b073093e6a0ab429b | [
"Apache-2.0"
] | permissive | fpvandoorn/leansnippets | 6af0499f6f3fd2c07e4b580734d77b67574e7c27 | 601bafbe07e9534af76f60994d6bdf741996ef93 | refs/heads/master | 1,590,063,910,882 | 1,545,093,878,000 | 1,545,093,878,000 | 36,044,957 | 2 | 2 | null | 1,442,619,708,000 | 1,432,256,875,000 | Lean | UTF-8 | Lean | false | false | 12,398 | hlean | import core hit.colimit hit.trunc homotopy.connectedness
open eq is_trunc unit quotient seq_colim pi nat equiv sum is_conn
/-
This is the formalization which is part of the paper
Constructing the Propositional Truncation using non-recursive HITs
submitted to CPP 2016.
-/
/-
Call a function f weakly constant if (Πa a', f a = f a')
This theorem states that if f is weakly constant, then (ap f) is weakly constant.
-/
definition weakly_constant_ap {A B : Type} {f : A → B} {a a' : A} (p q : a = a')
(H : Π(a a' : A), f a = f a') : ap f p = ap f q :=
have L : Π{b c : A} {r : b = c}, (H a b)⁻¹ ⬝ H a c = ap f r, from
(λb c r, eq.rec_on r !con.left_inv),
L⁻¹ ⬝ L
/- definition of "one step truncation" in terms of quotients -/
namespace one_step_tr
section
parameters {A : Type}
variables (a a' : A)
protected definition R (a a' : A) : Type₀ := unit
parameter (A)
definition one_step_tr : Type := quotient R
parameter {A}
definition tr : one_step_tr :=
class_of R a
definition tr_eq : tr a = tr a' :=
eq_of_rel _ star
protected definition rec {P : one_step_tr → Type} (Pt : Π(a : A), P (tr a))
(Pe : Π(a a' : A), Pt a =[tr_eq a a'] Pt a') (x : one_step_tr) : P x :=
begin
fapply (quotient.rec_on x),
{ intro a, apply Pt},
{ intro a a' H, cases H, apply Pe}
end
protected definition rec_on [reducible] {P : one_step_tr → Type} (x : one_step_tr)
(Pt : Π(a : A), P (tr a)) (Pe : Π(a a' : A), Pt a =[tr_eq a a'] Pt a') : P x :=
rec Pt Pe x
protected definition elim {P : Type} (Pt : A → P)
(Pe : Π(a a' : A), Pt a = Pt a') (x : one_step_tr) : P :=
rec Pt (λa a', pathover_of_eq _ (Pe a a')) x
protected definition elim_on [reducible] {P : Type} (x : one_step_tr) (Pt : A → P)
(Pe : Π(a a' : A), Pt a = Pt a') : P :=
elim Pt Pe x
theorem rec_tr_eq {P : one_step_tr → Type} (Pt : Π(a : A), P (tr a))
(Pe : Π(a a' : A), Pt a =[tr_eq a a'] Pt a') (a a' : A)
: apd (rec Pt Pe) (tr_eq a a') = Pe a a' :=
!rec_eq_of_rel
theorem elim_tr_eq {P : Type} (Pt : A → P)
(Pe : Π(a a' : A), Pt a = Pt a') (a a' : A)
: ap (elim Pt Pe) (tr_eq a a') = Pe a a' :=
begin
apply inj_inv !(pathover_constant (tr_eq a a')),
rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim,rec_tr_eq],
end
end
definition n_step_tr [reducible] (A : Type) (n : ℕ) : Type :=
nat.rec_on n A (λn' A', one_step_tr A')
end one_step_tr
attribute one_step_tr.rec one_step_tr.elim [recursor 5] [unfold 5]
attribute one_step_tr.rec_on one_step_tr.elim_on [unfold 2]
attribute one_step_tr.tr [constructor]
open one_step_tr
section /- Theorems about the one-step truncation -/
open homotopy trunc prod
theorem tr_eq_ne_idp {A : Type} (a : A) : tr_eq a a ≠ idp :=
begin
intro p,
have H2 : Π{X : Type₁} {x : X} {q : x = x}, q = idp,
from λX x q, calc
q = ap (one_step_tr.elim (λa, x) (λa b, q)) (tr_eq a a) : elim_tr_eq
... = ap (one_step_tr.elim (λa, x) (λa b, q)) (refl (one_step_tr.tr a)) : by rewrite p
... = idp : idp,
exact bool.eq_bnot_ne_idp H2
end
theorem tr_eq_ne_ap_tr {A : Type} {a b : A} (p : a = b) : tr_eq a b ≠ ap tr p :=
by induction p; apply tr_eq_ne_idp
theorem not_inhabited_set_trunc_one_step_tr (A : Type)
: ¬(trunc 1 (one_step_tr A) × is_set (trunc 1 (one_step_tr A))) :=
begin
intro H, induction H with x H,
refine trunc.elim_on x _, clear x, intro x,
induction x,
{ have q : trunc -1 ((tr_eq a a) = idp),
begin
refine to_fun !tr_eq_tr_equiv _,
refine @is_prop.elim _ _ _ _, apply is_trunc_equiv_closed, apply tr_eq_tr_equiv
end,
refine trunc.elim_on q _, clear q, intro p, exact !tr_eq_ne_idp p},
{ apply is_prop.elim}
end
theorem not_is_conn_one_step_tr (A : Type) : ¬is_conn 1 (one_step_tr A) :=
λH, not_inhabited_set_trunc_one_step_tr A (!center, _)
theorem is_prop_trunc_one_step_tr (A : Type) : is_prop (trunc 0 (one_step_tr A)) :=
begin
apply is_prop.mk,
intro x y,
refine trunc.rec_on x _, refine trunc.rec_on y _, clear x y, intro y x,
induction x,
{ induction y,
{ exact ap trunc.tr !tr_eq},
{ apply is_prop.elimo}},
{ apply is_prop.elimo}
end
local attribute is_prop_trunc_one_step_tr [instance]
theorem trunc_0_one_step_tr_equiv (A : Type) : trunc 0 (one_step_tr A) ≃ ∥ A ∥ :=
begin
apply equiv_of_is_prop,
{ intro x, refine trunc.rec _ x, clear x, intro x, induction x,
{ exact tr a},
{ apply is_prop.elim}},
{ intro x, refine trunc.rec _ x, clear x, intro a, exact tr (tr a)},
end
definition one_step_tr_functor [unfold 4] {A B : Type} (f : A → B) (x : one_step_tr A)
: one_step_tr B :=
begin
induction x,
{ exact tr (f a)},
{ apply tr_eq}
end
definition one_step_tr_universal_property [constructor] (A B : Type)
: (one_step_tr A → B) ≃ Σ(f : A → B), Π(x y : A), f x = f y :=
begin
fapply equiv.MK,
{ intro f, fconstructor, intro a, exact f (tr a), intros, exact ap f !tr_eq},
{ intro v a, induction v with f p, induction a, exact f a, apply p},
{ intro v, induction v with f p, esimp, apply ap (sigma.mk _), apply eq_of_homotopy2,
intro a a', apply elim_tr_eq},
{ intro f, esimp, apply eq_of_homotopy, intro a, induction a,
reflexivity,
apply eq_pathover, apply hdeg_square, rewrite [▸*,elim_tr_eq]},
end
end
section
parameter {X : Type}
/- basic constructors -/
private definition A [reducible] (n : ℕ) : Type := nat.rec_on n X (λn' X', one_step_tr X')
private definition f [reducible] ⦃n : ℕ⦄ (a : A n) : A (succ n) := tr a
private definition f_eq [reducible] {n : ℕ} (a a' : A n) : f a = f a' := tr_eq a a'
private definition truncX [reducible] : Type := @seq_colim A f
private definition i [reducible] {n : ℕ} (a : A n) : truncX := inclusion f a
private definition g [reducible] {n : ℕ} (a : A n) : i (f a) = i a := glue f a
/- defining the normal recursor is easy -/
definition rec {P : truncX → Type} [Pt : Πx, is_prop (P x)]
(H : Π(a : X), P (@i 0 a)) (x : truncX) : P x :=
begin
induction x,
{ induction n with n IH,
{ exact H a},
{ induction a,
{ exact !g⁻¹ ▸ IH a},
{ apply is_prop.elimo}}},
{ apply is_prop.elimo}
end
/- point operations -/
definition fr [reducible] [unfold 2] (n : ℕ) (a : X) : A n :=
begin
induction n with n x,
{ exact a},
{ exact f x},
end
/- path operations -/
definition i_fr [unfold 2] (n : ℕ) (a : X) : i (fr n a) = @i 0 a :=
begin
induction n with n p,
{ reflexivity},
{ exact g (fr n a) ⬝ p},
end
definition eq_same {n : ℕ} (a a' : A n) : i a = i a' :=
calc
i a = i (f a) : g
... = i (f a') : ap i (f_eq a a')
... = i a' : g
definition eq_constructors {n : ℕ} (a : X) (b : A n) : @i 0 a = i b :=
calc
i a = i (fr n a) : i_fr
... = i b : eq_same
/- 2-dimensional path operations -/
theorem ap_i_ap_f {n : ℕ} {a a' : A n} (p : a = a') : !g⁻¹ ⬝ ap i (ap !f p) ⬝ !g = ap i p :=
by induction p; apply con.left_inv
theorem ap_i_eq_ap_i_same {n : ℕ} {a a' : A n} (p q : a = a') : ap i p = ap i q :=
!weakly_constant_ap eq_same
theorem ap_f_eq_f {n : ℕ} (a a' : A n)
: !g⁻¹ ⬝ ap i (f_eq (f a) (f a')) ⬝ !g = ap i (f_eq a a') :=
ap _ !ap_i_eq_ap_i_same ⬝ !ap_i_ap_f
theorem eq_same_f {n : ℕ} (a a' : A n)
: (g a)⁻¹ ⬝ eq_same (f a) (f a') ⬝ g a' = eq_same a a' :=
begin
esimp [eq_same],
apply (ap (λx, _ ⬝ x ⬝ _)),
apply (ap_f_eq_f a a'),
end
theorem eq_constructors_comp {n : ℕ} (a : X) (b : A n)
: eq_constructors a (f b) ⬝ g b = eq_constructors a b :=
begin
rewrite [↑eq_constructors,▸*,↓fr n a,↓i_fr n a,con_inv,+con.assoc],
apply ap (λx, _ ⬝ x),
rewrite -con.assoc, exact !eq_same_f
end
theorem is_prop_truncX : is_prop truncX :=
begin
apply is_prop_of_imp_is_contr,
intro a,
refine @rec _ _ _ a,
clear a, intro a,
fapply is_contr.mk,
exact @i 0 a,
intro b,
induction b with n b n b,
{ apply eq_constructors},
{ apply (equiv.to_inv !eq_pathover_equiv_r), apply eq_constructors_comp}
end
end
namespace my_trunc
definition trunc.{u} (A : Type.{u}) : Type.{u} := @truncX A
definition tr {A : Type} : A → trunc A := @i A 0
definition is_prop_trunc (A : Type) : is_prop (trunc A) := is_prop_truncX
definition trunc.rec {A : Type} {P : trunc A → Type}
[Pt : Π(x : trunc A), is_prop (P x)]
(H : Π(a : A), P (tr a)) : Π(x : trunc A), P x := @rec A P Pt H
example {A : Type} {P : trunc A → Type} [Pt : Πaa, is_prop (P aa)]
(H : Πa, P (tr a)) (a : A) : (trunc.rec H) (tr a) = H a := by reflexivity
open sigma prod
-- the constructed truncation is equivalent to the "standard" propositional truncation
-- (called _root_.trunc -1 below)
open trunc
attribute is_prop_trunc [instance]
definition trunc_equiv (A : Type) : trunc A ≃ _root_.trunc -1 A :=
begin
fapply equiv.MK,
{ intro x, induction x using trunc.rec with a, exact trunc.tr a},
{ intro x, refine _root_.trunc.rec _ x, intro a, exact tr a},
{ intro x, induction x with a, reflexivity},
{ intro x, induction x using trunc.rec with a, reflexivity}
end
-- some other recursors we get from this construction:
definition trunc.elim2 {A P : Type} (h : Π{n}, n_step_tr A n → P)
(coh : Π(n : ℕ) (a : n_step_tr A n), h (f a) = h a) (x : trunc A) : P :=
begin
induction x,
{ exact h a},
{ apply coh}
end
definition trunc.rec2 {A : Type} {P : truncX → Type} (h : Π{n} (a : n_step_tr A n), P (i a))
(coh : Π(n : ℕ) (a : n_step_tr A n), h (f a) =[g a] h a)
(x : trunc A) : P x :=
begin
induction x,
{ exact h a},
{ apply coh}
end
definition elim2_equiv [constructor] (A P : Type) : (trunc A → P) ≃
Σ(h : Π{n}, n_step_tr A n → P),
Π(n : ℕ) (a : n_step_tr A n), @h (succ n) (one_step_tr.tr a) = h a :=
begin
fapply equiv.MK,
{ intro h, fconstructor,
{ intro n a, refine h (i a)},
{ intro n a, exact ap h (g a)}},
{ intro x a, induction x with h p, induction a,
exact h a,
apply p},
{ intro x, induction x with h p, fapply sigma_eq,
{ reflexivity},
{ esimp, apply pathover_idp_of_eq, apply eq_of_homotopy2, intro n a, xrewrite elim_glue}},
{ intro h, apply eq_of_homotopy, intro a, esimp, induction a,
esimp,
apply eq_pathover, apply hdeg_square, esimp, rewrite elim_glue}
end
open sigma.ops
definition conditionally_constant_equiv {A P : Type} (k : A → P) :
(Σ(g : trunc A → P), Πa, g (tr a) = k a) ≃
Σ(h : Π{n}, n_step_tr A n → P),
(Π(n : ℕ) (a : n_step_tr A n), h (f a) = h a) × (Πa, @h 0 a = k a) :=
calc
(Σ(g : trunc A → P), Πa, g (tr a) = k a)
≃ Σ(v : Σ(h : Π{n}, n_step_tr A n → P), Π(n : ℕ) (a : n_step_tr A n), h (f a) = h a),
Πa, (v.1) 0 a = k a
: sigma_equiv_sigma !elim2_equiv (λg, equiv.rfl)
... ≃ Σ(h : Π{n}, n_step_tr A n → P) (p : Π(n : ℕ) (a : n_step_tr A n), h (f a) = h a),
Πa, @h 0 a = k a
: sigma_assoc_equiv
... ≃ Σ(h : Π{n}, n_step_tr A n → P),
(Π(n : ℕ) (a : n_step_tr A n), h (f a) = h a) × (Πa, @h 0 a = k a)
: sigma_equiv_sigma_right (λa, !equiv_prod)
definition cocone_of_is_collapsible {A : Type} (f : A → A) (p : Πa a', f a = f a')
(n : ℕ) (x : n_step_tr A n) : A :=
begin
apply f,
induction n with n h,
{ exact x},
{ apply to_inv !one_step_tr_universal_property ⟨f, p⟩, exact one_step_tr_functor h x}
end
definition has_split_support_of_is_collapsible {A : Type} (f : A → A) (p : Πa a', f a = f a')
: trunc A → A :=
begin
fapply to_inv !elim2_equiv,
fconstructor,
{ exact cocone_of_is_collapsible f p},
{ intro n a, apply p}
end
end my_trunc
|
5920e78b54bbcc0a32698fd394ce2cad3f229a99 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/linear_algebra/direct_sum/finsupp.lean | 0b10bdff4d04aa5d666462460f563fc99c26cdcc | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 3,264 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
-/
import linear_algebra.finsupp
import linear_algebra.direct_sum.tensor_product
/-!
# Results on direct sums and finitely supported functions.
1. The linear equivalence between finitely supported functions `ι →₀ M` and
the direct sum of copies of `M` indexed by `ι`.
2. The tensor product of ι →₀ M and κ →₀ N is linearly equivalent to (ι × κ) →₀ (M ⊗ N).
-/
universes u v w
noncomputable theory
open_locale classical direct_sum
open set linear_map submodule
variables {R : Type u} {M : Type v} {N : Type w} [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N]
section finsupp_lequiv_direct_sum
variables (R M) (ι : Type*) [decidable_eq ι]
/-- The finitely supported functions ι →₀ M are in linear equivalence with the direct sum of
copies of M indexed by ι. -/
def finsupp_lequiv_direct_sum : (ι →₀ M) ≃ₗ[R] ⨁ i : ι, M :=
linear_equiv.of_linear
(finsupp.lsum (show ι → (M →ₗ[R] ⨁ i, M), from direct_sum.lof R ι _))
(direct_sum.to_module _ _ _ finsupp.lsingle)
(linear_map.ext $ direct_sum.to_module.ext _ $ λ i,
linear_map.ext $ λ x, by simp [finsupp.sum_single_index])
(linear_map.ext $ λ f, finsupp.ext $ λ i, by simp [finsupp.lsum_apply])
@[simp] theorem finsupp_lequiv_direct_sum_single (i : ι) (m : M) :
finsupp_lequiv_direct_sum R M ι (finsupp.single i m) = direct_sum.lof R ι _ i m :=
finsupp.sum_single_index $ linear_map.map_zero _
@[simp] theorem finsupp_lequiv_direct_sum_symm_lof (i : ι) (m : M) :
(finsupp_lequiv_direct_sum R M ι).symm (direct_sum.lof R ι _ i m) = finsupp.single i m :=
direct_sum.to_module_lof _ _ _
end finsupp_lequiv_direct_sum
section tensor_product
open_locale tensor_product
/-- The tensor product of ι →₀ M and κ →₀ N is linearly equivalent to (ι × κ) →₀ (M ⊗ N). -/
def finsupp_tensor_finsupp (R M N ι κ : Sort*) [comm_ring R]
[add_comm_group M] [module R M] [add_comm_group N] [module R N] :
(ι →₀ M) ⊗[R] (κ →₀ N) ≃ₗ[R] (ι × κ) →₀ (M ⊗[R] N) :=
linear_equiv.trans
(tensor_product.congr (finsupp_lequiv_direct_sum R M ι) (finsupp_lequiv_direct_sum R N κ)) $
linear_equiv.trans
(tensor_product.direct_sum R ι κ (λ _, M) (λ _, N))
(finsupp_lequiv_direct_sum R (M ⊗[R] N) (ι × κ)).symm
@[simp] theorem finsupp_tensor_finsupp_single (R M N ι κ : Sort*) [comm_ring R]
[add_comm_group M] [module R M] [add_comm_group N] [module R N]
(i : ι) (m : M) (k : κ) (n : N) :
finsupp_tensor_finsupp R M N ι κ (finsupp.single i m ⊗ₜ finsupp.single k n) =
finsupp.single (i, k) (m ⊗ₜ n) :=
by simp [finsupp_tensor_finsupp]
@[simp] theorem finsupp_tensor_finsupp_symm_single (R M N ι κ : Sort*) [comm_ring R]
[add_comm_group M] [module R M] [add_comm_group N] [module R N]
(i : ι × κ) (m : M) (n : N) :
(finsupp_tensor_finsupp R M N ι κ).symm (finsupp.single i (m ⊗ₜ n)) =
(finsupp.single i.1 m ⊗ₜ finsupp.single i.2 n) :=
prod.cases_on i $ λ i k, (linear_equiv.symm_apply_eq _).2
(finsupp_tensor_finsupp_single _ _ _ _ _ _ _ _ _).symm
end tensor_product
|
c478fea468450ea4f7108b0013a4755147d04266 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/1333.lean | fe22ce1596ead3cf5ce138860df5e1dde248e203 | [
"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 | 569 | lean | example
(h1 : a = b + 3)
(h2 : b = c + 2)
(h3 : c = d + 1)
(h4 : d = e + 4)
(useless : a = x + 1)
(H : a = 10) :
e = 0 := by
simp [*, -useless] at H
exact H
example
(useless : a = x + 1)
(h1 : a = b + 3)
(h2 : b = c + 2)
(h3 : c = d + 1)
(h4 : d = e + 4)
(H : a = 10) :
e = 0 := by
simp [*, -useless] at H
exact H
example
(useless : a = x + 1)
(h1 : a = b + 3)
(h2 : b = c + 2)
(h3 : c = d + 1)
(h4 : d = e + 4)
(H : a = 10) :
e = 0 := by
simp [*] at H
rw [H] at useless
simp [*, -H] at useless
exact useless
|
17be467dcbfcfa940eb4dd90ef113a1e7b60f0ff | 957a80ea22c5abb4f4670b250d55534d9db99108 | /library/init/native/cf.lean | 7ce9801ab80868c5a23d8d8bee0b4f914a0ac0fe | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 2,477 | lean | /-
Copyright (c) 2016 Jared Roesch. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jared Roesch
-/
prelude
import init.meta.format
import init.meta.expr
import init.data.string
import init.category.state
import init.native.ir
import init.native.format
import init.native.builtin
import init.native.util
import init.native.pass
import init.native.procedure
import init.native.internal
import init.native.config
open native
namespace cf
@[reducible] meta def cf_state :=
config × nat
@[reducible] meta def cf_monad :=
state cf_state
meta def when_debug (action : cf_monad unit) : cf_monad unit := do
(config, _) ← state.read,
if config.debug
then action
else return ()
-- point at the code where you can't synthesize?
-- the error behavior here seems bad if you replace the unit
-- with `u`
meta def trace_cf (s : string) : cf_monad unit :=
when_debug (trace s (return ()))
meta def fresh_name : cf_monad name := do
(config, count) ← state.read,
-- need to replace this with unique prefix as per our earlier conversation
n ← pure $ name.mk_numeral (unsigned.of_nat' count) `_anf_,
state.write (config, count + 1),
return n
private meta def cf_case (action : expr → cf_monad expr) (e : expr) : cf_monad expr := do
under_lambda fresh_name (fun e', action e') e
private meta def cf_cases_on (head : expr) (args : list expr) (cf : expr → cf_monad expr) : cf_monad expr :=
match args with
| [] := return $ mk_call head []
| (scrut :: cases) := do
trace_cf "inside cases on",
cases' ← monad.mapm (cf_case cf) cases,
return $ mk_call head (scrut :: cases')
end
meta def cf' : expr → cf_monad expr
| (expr.elet n ty val body) :=
expr.elet n ty val <$> (cf' body)
| (expr.app f arg) := do
trace_cf "processing app",
let fn := expr.get_app_fn (expr.app f arg),
let args := expr.get_app_args (expr.app f arg),
if is_cases_on fn
then cf_cases_on fn args cf'
else return (mk_call (expr.const `native_compiler.return []) [(expr.app f arg)])
| e := return $ expr.app (expr.const `native_compiler.return []) e
meta def init_state : config → cf_state :=
fun c, (c, 0)
end cf
private meta def cf_transform (conf : config) (e : expr) : expr :=
prod.fst $ (under_lambda cf.fresh_name cf.cf' e) (cf.init_state conf)
meta def cf : pass := {
name := "control_flow",
transform := fun conf proc, procedure.map_body (fun e, cf_transform conf e) proc
}
|
1388f6543ee3e3e9c25f346184266318bdb870c8 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/algebraic_geometry/stalks.lean | 7e86cc44cc5461da3d5c309014818956f6d650b0 | [
"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 | 2,828 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebraic_geometry.presheafed_space
import topology.sheaves.stalks
/-!
# Stalks for presheaved spaces
This file lifts constructions of stalks and pushforwards of stalks to work with
the category of presheafed spaces.
-/
universes v u v' u'
open category_theory
open category_theory.limits category_theory.category category_theory.functor
open algebraic_geometry
open topological_space
variables {C : Type u} [category.{v} C] [has_colimits C]
local attribute [tidy] tactic.op_induction'
open Top.presheaf
namespace algebraic_geometry.PresheafedSpace
/--
The stalk at `x` of a `PresheafedSpace`.
-/
def stalk (X : PresheafedSpace C) (x : X) : C := X.presheaf.stalk x
/--
A morphism of presheafed spaces induces a morphism of stalks.
-/
def stalk_map {X Y : PresheafedSpace C} (α : X ⟶ Y) (x : X) : Y.stalk (α.base x) ⟶ X.stalk x :=
(stalk_functor C (α.base x)).map (α.c) ≫ X.presheaf.stalk_pushforward C α.base x
section restrict
-- PROJECT: restriction preserves stalks.
-- We'll want to define cofinal functors, show precomposing with a cofinal functor preserves colimits,
-- and (easily) verify that "open neighbourhoods of x within U" is cofinal in "open neighbourhoods of x".
/-
def restrict_stalk_iso {U : Top} (X : PresheafedSpace C)
(f : U ⟶ (X : Top.{v})) (h : open_embedding f) (x : U) :
(X.restrict f h).stalk x ≅ X.stalk (f x) :=
begin
dsimp only [stalk, Top.presheaf.stalk, stalk_functor],
dsimp [colim],
sorry
end
-- TODO `restrict_stalk_iso` is compatible with `germ`.
-/
end restrict
namespace stalk_map
@[simp] lemma id (X : PresheafedSpace C) (x : X) : stalk_map (𝟙 X) x = 𝟙 (X.stalk x) :=
begin
dsimp [stalk_map],
simp only [stalk_pushforward.id],
rw [←map_comp],
convert (stalk_functor C x).map_id X.presheaf,
tidy,
end
-- TODO understand why this proof is still gross (i.e. requires using `erw`)
@[simp] lemma comp {X Y Z : PresheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z) (x : X) :
stalk_map (α ≫ β) x =
(stalk_map β (α.base x) : Z.stalk (β.base (α.base x)) ⟶ Y.stalk (α.base x)) ≫
(stalk_map α x : Y.stalk (α.base x) ⟶ X.stalk x) :=
begin
dsimp [stalk_map, stalk_functor, stalk_pushforward],
ext U,
op_induction U,
cases U,
simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc, colimit.ι_pre,
whisker_left_app, whisker_right_app,
assoc, id_comp, map_id, map_comp],
dsimp,
simp only [map_id, assoc, pushforward.comp_inv_app],
-- FIXME Why doesn't simp do this:
erw [category_theory.functor.map_id],
erw [category_theory.functor.map_id],
erw [id_comp, id_comp, id_comp],
end
end stalk_map
end algebraic_geometry.PresheafedSpace
|
483e70f03488875d403c5bf6630fb54db8e2a21a | 07c76fbd96ea1786cc6392fa834be62643cea420 | /hott/algebra/category/iso.hlean | 6d6a16bede2dbaa8c76d2860ecbc3a0345c5a67b | [
"Apache-2.0"
] | permissive | fpvandoorn/lean2 | 5a430a153b570bf70dc8526d06f18fc000a60ad9 | 0889cf65b7b3cebfb8831b8731d89c2453dd1e9f | refs/heads/master | 1,592,036,508,364 | 1,545,093,958,000 | 1,545,093,958,000 | 75,436,854 | 0 | 0 | null | 1,480,718,780,000 | 1,480,718,780,000 | null | UTF-8 | Lean | false | false | 19,642 | hlean | /-
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, Jakob von Raumer
-/
import .precategory types.sigma arity
open eq category prod equiv is_equiv sigma sigma.ops is_trunc
namespace iso
structure split_mono [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) :=
{retraction_of : b ⟶ a}
(retraction_comp : retraction_of ∘ f = id)
structure split_epi [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) :=
{section_of : b ⟶ a}
(comp_section : f ∘ section_of = id)
structure is_iso [class] {ob : Type} [C : precategory ob] {a b : ob} (f : a ⟶ b) :=
(inverse : b ⟶ a)
(left_inverse : inverse ∘ f = id)
(right_inverse : f ∘ inverse = id)
attribute is_iso.inverse [reducible]
open split_mono split_epi is_iso
abbreviation retraction_of [unfold 6] := @split_mono.retraction_of
abbreviation retraction_comp [unfold 6] := @split_mono.retraction_comp
abbreviation section_of [unfold 6] := @split_epi.section_of
abbreviation comp_section [unfold 6] := @split_epi.comp_section
abbreviation inverse [unfold 6] := @is_iso.inverse
abbreviation left_inverse [unfold 6] := @is_iso.left_inverse
abbreviation right_inverse [unfold 6] := @is_iso.right_inverse
postfix ⁻¹ := inverse
--a second notation for the inverse, which is not overloaded
postfix [parsing_only] `⁻¹ʰ`:std.prec.max_plus := inverse -- input using \-1h
variables {ob : Type} [C : precategory ob]
variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a}
include C
definition split_mono_of_is_iso [constructor] [instance] [priority 300]
(f : a ⟶ b) [H : is_iso f] : split_mono f :=
split_mono.mk !left_inverse
definition split_epi_of_is_iso [constructor] [instance] [priority 300]
(f : a ⟶ b) [H : is_iso f] : split_epi f :=
split_epi.mk !right_inverse
definition is_iso_id [constructor] [instance] [priority 500] (a : ob) : is_iso (ID a) :=
is_iso.mk _ !id_id !id_id
definition is_iso_inverse [constructor] [instance] [priority 200] (f : a ⟶ b) {H : is_iso f}
: is_iso f⁻¹ :=
is_iso.mk _ !right_inverse !left_inverse
theorem left_inverse_eq_right_inverse {f : a ⟶ b} {g g' : hom b a}
(Hl : g ∘ f = id) (Hr : f ∘ g' = id) : g = g' :=
by rewrite [-(id_right g), -Hr, assoc, Hl, id_left]
theorem retraction_eq [H : split_mono f] (H2 : f ∘ h = id) : retraction_of f = h :=
left_inverse_eq_right_inverse !retraction_comp H2
theorem section_eq [H : split_epi f] (H2 : h ∘ f = id) : section_of f = h :=
(left_inverse_eq_right_inverse H2 !comp_section)⁻¹
theorem inverse_eq_right [H : is_iso f] (H2 : f ∘ h = id) : f⁻¹ = h :=
left_inverse_eq_right_inverse !left_inverse H2
theorem inverse_eq_left [H : is_iso f] (H2 : h ∘ f = id) : f⁻¹ = h :=
(left_inverse_eq_right_inverse H2 !right_inverse)⁻¹
theorem retraction_eq_section (f : a ⟶ b) [Hl : split_mono f] [Hr : split_epi f] :
retraction_of f = section_of f :=
retraction_eq !comp_section
definition is_iso_of_split_epi_of_split_mono [constructor] (f : a ⟶ b)
[Hl : split_mono f] [Hr : split_epi f] : is_iso f :=
is_iso.mk _ ((retraction_eq_section f) ▸ (retraction_comp f)) (comp_section f)
theorem inverse_unique (H H' : is_iso f) : @inverse _ _ _ _ f H = @inverse _ _ _ _ f H' :=
@inverse_eq_left _ _ _ _ _ _ H !left_inverse
theorem inverse_involutive (f : a ⟶ b) [H : is_iso f] [H : is_iso (f⁻¹)]
: (f⁻¹)⁻¹ = f :=
inverse_eq_right !left_inverse
theorem inverse_eq_inverse {f g : a ⟶ b} [H : is_iso f] [H : is_iso g] (p : f = g)
: f⁻¹ = g⁻¹ :=
by cases p;apply inverse_unique
theorem retraction_id (a : ob) : retraction_of (ID a) = id :=
retraction_eq !id_id
theorem section_id (a : ob) : section_of (ID a) = id :=
section_eq !id_id
theorem id_inverse (a : ob) [H : is_iso (ID a)] : (ID a)⁻¹ = id :=
inverse_eq_left !id_id
definition split_mono_comp [constructor] [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b)
[Hf : split_mono f] [Hg : split_mono g] : split_mono (g ∘ f) :=
split_mono.mk
(show (retraction_of f ∘ retraction_of g) ∘ g ∘ f = id,
by rewrite [-assoc, assoc _ g f, retraction_comp, id_left, retraction_comp])
definition split_epi_comp [constructor] [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b)
[Hf : split_epi f] [Hg : split_epi g] : split_epi (g ∘ f) :=
split_epi.mk
(show (g ∘ f) ∘ section_of f ∘ section_of g = id,
by rewrite [-assoc, {f ∘ _}assoc, comp_section, id_left, comp_section])
definition is_iso_comp [constructor] [instance] [priority 150] (g : b ⟶ c) (f : a ⟶ b)
[Hf : is_iso f] [Hg : is_iso g] : is_iso (g ∘ f) :=
!is_iso_of_split_epi_of_split_mono
theorem is_prop_is_iso [instance] (f : hom a b) : is_prop (is_iso f) :=
begin
apply is_prop.mk, intro H H',
cases H with g li ri, cases H' with g' li' ri',
fapply (apd0111 (@is_iso.mk ob C a b f)),
apply left_inverse_eq_right_inverse,
apply li,
apply ri',
apply is_prop.elimo,
apply is_prop.elimo,
end
end iso open iso
/- isomorphic objects -/
structure iso {ob : Type} [C : precategory ob] (a b : ob) :=
(to_hom : hom a b)
(struct : is_iso to_hom)
infix ` ≅ `:50 := iso
notation c ` ≅[`:50 C:0 `] `:0 c':50 := @iso C _ c c'
attribute iso.struct [instance] [priority 2000]
namespace iso
variables {ob : Type} [C : precategory ob]
variables {a b c : ob} {g : b ⟶ c} {f : a ⟶ b} {h : b ⟶ a}
include C
attribute to_hom [coercion]
protected definition MK [constructor] (f : a ⟶ b) (g : b ⟶ a)
(H1 : g ∘ f = id) (H2 : f ∘ g = id) :=
@(mk f) (is_iso.mk _ H1 H2)
variable {C}
definition to_inv [reducible] [unfold 5] (f : a ≅ b) : b ⟶ a := (to_hom f)⁻¹
definition to_left_inverse [unfold 5] (f : a ≅ b) : (to_hom f)⁻¹ ∘ (to_hom f) = id :=
left_inverse (to_hom f)
definition to_right_inverse [unfold 5] (f : a ≅ b) : (to_hom f) ∘ (to_hom f)⁻¹ = id :=
right_inverse (to_hom f)
variable [C]
protected definition refl [constructor] (a : ob) : a ≅ a :=
mk (ID a) _
protected definition symm [constructor] ⦃a b : ob⦄ (H : a ≅ b) : b ≅ a :=
mk (to_hom H)⁻¹ _
protected definition trans [constructor] ⦃a b c : ob⦄ (H1 : a ≅ b) (H2 : b ≅ c) : a ≅ c :=
mk (to_hom H2 ∘ to_hom H1) _
infixl ` ⬝i `:75 := iso.trans
postfix `⁻¹ⁱ`:(max + 1) := iso.symm
definition change_hom [constructor] (H : a ≅ b) (f : a ⟶ b) (p : to_hom H = f) : a ≅ b :=
iso.MK f (to_inv H) (p ▸ to_left_inverse H) (p ▸ to_right_inverse H)
definition change_inv [constructor] (H : a ≅ b) (g : b ⟶ a) (p : to_inv H = g) : a ≅ b :=
iso.MK (to_hom H) g (p ▸ to_left_inverse H) (p ▸ to_right_inverse H)
definition iso_mk_eq {f f' : a ⟶ b} [H : is_iso f] [H' : is_iso f'] (p : f = f')
: iso.mk f _ = iso.mk f' _ :=
apd011 iso.mk p !is_prop.elimo
variable {C}
definition iso_eq {f f' : a ≅ b} (p : to_hom f = to_hom f') : f = f' :=
by (cases f; cases f'; apply (iso_mk_eq p))
definition iso_pathover {X : Type} {x₁ x₂ : X} {p : x₁ = x₂} {a : X → ob} {b : X → ob}
{f₁ : a x₁ ≅ b x₁} {f₂ : a x₂ ≅ b x₂} (q : to_hom f₁ =[p] to_hom f₂) : f₁ =[p] f₂ :=
begin
cases f₁, cases f₂, esimp at q, induction q, apply pathover_idp_of_eq,
exact ap (iso.mk _) !is_prop.elim
end
variable [C]
-- The structure for isomorphism can be characterized up to equivalence by a sigma type.
protected definition sigma_char ⦃a b : ob⦄ : (Σ (f : hom a b), is_iso f) ≃ (a ≅ b) :=
begin
fapply (equiv.mk),
{intro S, apply iso.mk, apply (S.2)},
{fapply adjointify,
{intro p, cases p with f H, exact sigma.mk f H},
{intro p, cases p, apply idp},
{intro S, cases S, apply idp}},
end
-- The type of isomorphisms between two objects is a set
definition is_set_iso [instance] : is_set (a ≅ b) :=
is_trunc_equiv_closed _ !iso.sigma_char _
definition iso_of_eq [unfold 5] (p : a = b) : a ≅ b :=
eq.rec_on p (iso.refl a)
definition hom_of_eq [reducible] [unfold 5] (p : a = b) : a ⟶ b :=
iso.to_hom (iso_of_eq p)
definition inv_of_eq [reducible] [unfold 5] (p : a = b) : b ⟶ a :=
iso.to_inv (iso_of_eq p)
definition iso_of_eq_inv (p : a = b) : iso_of_eq p⁻¹ = iso.symm (iso_of_eq p) :=
eq.rec_on p idp
theorem hom_of_eq_inv (p : a = b) : hom_of_eq p⁻¹ = inv_of_eq p :=
eq.rec_on p idp
theorem inv_of_eq_inv (p : a = b) : inv_of_eq p⁻¹ = hom_of_eq p :=
eq.rec_on p idp
definition iso_of_eq_con (p : a = b) (q : b = c)
: iso_of_eq (p ⬝ q) = iso.trans (iso_of_eq p) (iso_of_eq q) :=
eq.rec_on q (eq.rec_on p (iso_eq !id_id⁻¹))
definition transport_iso_of_eq (p : a = b) :
p ▸ !iso.refl = iso_of_eq p :=
by cases p; reflexivity
definition hom_pathover {X : Type} {x₁ x₂ : X} {p : x₁ = x₂} {a b : X → ob}
{f₁ : a x₁ ⟶ b x₁} {f₂ : a x₂ ⟶ b x₂} (q : hom_of_eq (ap b p) ∘ f₁ = f₂ ∘ hom_of_eq (ap a p)) :
f₁ =[p] f₂ :=
begin
induction p, apply pathover_idp_of_eq, exact !id_left⁻¹ ⬝ q ⬝ !id_right
end
definition hom_pathover_constant_left {X : Type} {x₁ x₂ : X} {p : x₁ = x₂} {a : ob} {b : X → ob}
{f₁ : a ⟶ b x₁} {f₂ : a ⟶ b x₂} (q : hom_of_eq (ap b p) ∘ f₁ = f₂) : f₁ =[p] f₂ :=
hom_pathover (q ⬝ !id_right⁻¹ ⬝ ap (λx, _ ∘ hom_of_eq x) !ap_constant⁻¹)
definition hom_pathover_constant_right {X : Type} {x₁ x₂ : X} {p : x₁ = x₂} {a : X → ob} {b : ob}
{f₁ : a x₁ ⟶ b} {f₂ : a x₂ ⟶ b} (q : f₁ = f₂ ∘ hom_of_eq (ap a p)) : f₁ =[p] f₂ :=
hom_pathover (ap (λx, hom_of_eq x ∘ _) !ap_constant ⬝ !id_left ⬝ q)
definition hom_pathover_id_left {p : a = b} {c : ob → ob} {f₁ : a ⟶ c a} {f₂ : b ⟶ c b}
(q : hom_of_eq (ap c p) ∘ f₁ = f₂ ∘ hom_of_eq p) : f₁ =[p] f₂ :=
hom_pathover (q ⬝ ap (λx, _ ∘ hom_of_eq x) !ap_id⁻¹)
definition hom_pathover_id_right {p : a = b} {c : ob → ob} {f₁ : c a ⟶ a} {f₂ : c b ⟶ b}
(q : hom_of_eq p ∘ f₁ = f₂ ∘ hom_of_eq (ap c p)) : f₁ =[p] f₂ :=
hom_pathover (ap (λx, hom_of_eq x ∘ _) !ap_id ⬝ q)
definition hom_pathover_id_left_id_right {p : a = b} {f₁ : a ⟶ a} {f₂ : b ⟶ b}
(q : hom_of_eq p ∘ f₁ = f₂ ∘ hom_of_eq p) : f₁ =[p] f₂ :=
hom_pathover_id_left (ap (λx, hom_of_eq x ∘ _) !ap_id ⬝ q)
definition hom_pathover_id_left_constant_right {p : a = b} {f₁ : a ⟶ c} {f₂ : b ⟶ c}
(q : f₁ = f₂ ∘ hom_of_eq p) : f₁ =[p] f₂ :=
hom_pathover_constant_right (q ⬝ ap (λx, _ ∘ hom_of_eq x) !ap_id⁻¹)
definition hom_pathover_constant_left_id_right {p : a = b} {f₁ : c ⟶ a} {f₂ : c ⟶ b}
(q : hom_of_eq p ∘ f₁ = f₂) : f₁ =[p] f₂ :=
hom_pathover_constant_left (ap (λx, hom_of_eq x ∘ _) !ap_id ⬝ q)
section
open funext
variables {X : Type} {x y : X} {F G : X → ob}
definition transport_hom_of_eq (p : F = G) (f : hom (F x) (F y))
: p ▸ f = hom_of_eq (apd10 p y) ∘ f ∘ inv_of_eq (apd10 p x) :=
by induction p; exact !id_leftright⁻¹
definition transport_hom_of_eq_right (p : x = y) (f : hom c (F x))
: p ▸ f = hom_of_eq (ap F p) ∘ f :=
by induction p; exact !id_left⁻¹
definition transport_hom_of_eq_left (p : x = y) (f : hom (F x) c)
: p ▸ f = f ∘ inv_of_eq (ap F p) :=
by induction p; exact !id_right⁻¹
definition transport_hom (p : F ~ G) (f : hom (F x) (F y))
: eq_of_homotopy p ▸ f = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) :=
calc
eq_of_homotopy p ▸ f =
hom_of_eq (apd10 (eq_of_homotopy p) y) ∘ f ∘ inv_of_eq (apd10 (eq_of_homotopy p) x)
: transport_hom_of_eq
... = hom_of_eq (p y) ∘ f ∘ inv_of_eq (p x) : {right_inv apd10 p}
end
structure mono [class] (f : a ⟶ b) :=
(elim : ∀c (g h : hom c a), f ∘ g = f ∘ h → g = h)
structure epi [class] (f : a ⟶ b) :=
(elim : ∀c (g h : hom b c), g ∘ f = h ∘ f → g = h)
definition mono_of_split_mono [instance] (f : a ⟶ b) [H : split_mono f] : mono f :=
mono.mk
(λ c g h H,
calc
g = id ∘ g : by rewrite id_left
... = (retraction_of f ∘ f) ∘ g : by rewrite retraction_comp
... = (retraction_of f ∘ f) ∘ h : by rewrite [-assoc, H, -assoc]
... = id ∘ h : by rewrite retraction_comp
... = h : by rewrite id_left)
definition epi_of_split_epi [instance] (f : a ⟶ b) [H : split_epi f] : epi f :=
epi.mk
(λ c g h H,
calc
g = g ∘ id : by rewrite id_right
... = g ∘ f ∘ section_of f : by rewrite -(comp_section f)
... = h ∘ f ∘ section_of f : by rewrite [assoc, H, -assoc]
... = h ∘ id : by rewrite comp_section
... = h : by rewrite id_right)
definition mono_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : mono f] [Hg : mono g]
: mono (g ∘ f) :=
mono.mk
(λ d h₁ h₂ H,
have H2 : g ∘ (f ∘ h₁) = g ∘ (f ∘ h₂),
begin
rewrite *assoc, exact H
end,
!mono.elim (!mono.elim H2))
definition epi_comp [instance] (g : b ⟶ c) (f : a ⟶ b) [Hf : epi f] [Hg : epi g]
: epi (g ∘ f) :=
epi.mk
(λ d h₁ h₂ H,
have H2 : (h₁ ∘ g) ∘ f = (h₂ ∘ g) ∘ f,
begin
rewrite -*assoc, exact H
end,
!epi.elim (!epi.elim H2))
end iso
attribute iso.refl [refl]
attribute iso.symm [symm]
attribute iso.trans [trans]
namespace iso
/-
rewrite lemmas for inverses, modified from
https://github.com/JasonGross/HoTT-categories/blob/master/theories/Categories/Category/Morphisms.v
-/
section
variables {ob : Type} [C : precategory ob] include C
variables {a b c d : ob} (f : b ⟶ a)
(r : c ⟶ d) (q : b ⟶ c) (p : a ⟶ b)
(g : d ⟶ c)
variable [Hq : is_iso q] include Hq
theorem comp.right_inverse : q ∘ q⁻¹ = id := !right_inverse
theorem comp.left_inverse : q⁻¹ ∘ q = id := !left_inverse
theorem inverse_comp_cancel_left : q⁻¹ ∘ (q ∘ p) = p :=
by rewrite [assoc, left_inverse, id_left]
theorem comp_inverse_cancel_left : q ∘ (q⁻¹ ∘ g) = g :=
by rewrite [assoc, right_inverse, id_left]
theorem comp_inverse_cancel_right : (r ∘ q) ∘ q⁻¹ = r :=
by rewrite [-assoc, right_inverse, id_right]
theorem inverse_comp_cancel_right : (f ∘ q⁻¹) ∘ q = f :=
by rewrite [-assoc, left_inverse, id_right]
theorem comp_inverse [Hp : is_iso p] [Hpq : is_iso (q ∘ p)] : (q ∘ p)⁻¹ʰ = p⁻¹ʰ ∘ q⁻¹ʰ :=
inverse_eq_left
(show (p⁻¹ʰ ∘ q⁻¹ʰ) ∘ q ∘ p = id, from
by rewrite [-assoc, inverse_comp_cancel_left, left_inverse])
theorem inverse_comp_inverse_left [H' : is_iso g] : (q⁻¹ ∘ g)⁻¹ = g⁻¹ ∘ q :=
inverse_involutive q ▸ comp_inverse q⁻¹ g
theorem inverse_comp_inverse_right [H' : is_iso f] : (q ∘ f⁻¹)⁻¹ = f ∘ q⁻¹ :=
inverse_involutive f ▸ comp_inverse q f⁻¹
theorem inverse_comp_inverse_inverse [H' : is_iso r] : (q⁻¹ ∘ r⁻¹)⁻¹ = r ∘ q :=
inverse_involutive r ▸ inverse_comp_inverse_left q r⁻¹
end
section
variables {ob : Type} {C : precategory ob} include C
variables {d c b a : ob}
{r' : c ⟶ d} {i : b ⟶ c} {f : b ⟶ a}
{r : c ⟶ d} {q : b ⟶ c} {p : a ⟶ b}
{g : d ⟶ c} {h : c ⟶ b} {p' : a ⟶ b}
{x : b ⟶ d} {z : a ⟶ c}
{y : d ⟶ b} {w : c ⟶ a}
variable [Hq : is_iso q] include Hq
theorem comp_eq_of_eq_inverse_comp (H : y = q⁻¹ ∘ g) : q ∘ y = g :=
H⁻¹ ▸ comp_inverse_cancel_left q g
theorem comp_eq_of_eq_comp_inverse (H : w = f ∘ q⁻¹) : w ∘ q = f :=
H⁻¹ ▸ inverse_comp_cancel_right f q
theorem eq_comp_of_inverse_comp_eq (H : q⁻¹ ∘ g = y) : g = q ∘ y :=
(comp_eq_of_eq_inverse_comp H⁻¹)⁻¹
theorem eq_comp_of_comp_inverse_eq (H : f ∘ q⁻¹ = w) : f = w ∘ q :=
(comp_eq_of_eq_comp_inverse H⁻¹)⁻¹
variable {Hq}
theorem inverse_comp_eq_of_eq_comp (H : z = q ∘ p) : q⁻¹ ∘ z = p :=
H⁻¹ ▸ inverse_comp_cancel_left q p
theorem comp_inverse_eq_of_eq_comp (H : x = r ∘ q) : x ∘ q⁻¹ = r :=
H⁻¹ ▸ comp_inverse_cancel_right r q
theorem eq_inverse_comp_of_comp_eq (H : q ∘ p = z) : p = q⁻¹ ∘ z :=
(inverse_comp_eq_of_eq_comp H⁻¹)⁻¹
theorem eq_comp_inverse_of_comp_eq (H : r ∘ q = x) : r = x ∘ q⁻¹ :=
(comp_inverse_eq_of_eq_comp H⁻¹)⁻¹
theorem eq_inverse_of_comp_eq_id' (H : h ∘ q = id) : h = q⁻¹ := (inverse_eq_left H)⁻¹
theorem eq_inverse_of_comp_eq_id (H : q ∘ h = id) : h = q⁻¹ := (inverse_eq_right H)⁻¹
theorem inverse_eq_of_id_eq_comp (H : id = h ∘ q) : q⁻¹ = h :=
(eq_inverse_of_comp_eq_id' H⁻¹)⁻¹
theorem inverse_eq_of_id_eq_comp' (H : id = q ∘ h) : q⁻¹ = h :=
(eq_inverse_of_comp_eq_id H⁻¹)⁻¹
variable [Hq]
theorem eq_of_comp_inverse_eq_id (H : i ∘ q⁻¹ = id) : i = q :=
eq_inverse_of_comp_eq_id' H ⬝ inverse_involutive q
theorem eq_of_inverse_comp_eq_id (H : q⁻¹ ∘ i = id) : i = q :=
eq_inverse_of_comp_eq_id H ⬝ inverse_involutive q
theorem eq_of_id_eq_comp_inverse (H : id = i ∘ q⁻¹) : q = i := (eq_of_comp_inverse_eq_id H⁻¹)⁻¹
theorem eq_of_id_eq_inverse_comp (H : id = q⁻¹ ∘ i) : q = i := (eq_of_inverse_comp_eq_id H⁻¹)⁻¹
theorem inverse_comp_id_comp : q⁻¹ ∘ id ∘ q = id :=
ap (λ x, _ ∘ x) !id_left ⬝ !comp.left_inverse
theorem comp_id_comp_inverse : q ∘ id ∘ q⁻¹ = id :=
ap (λ x, _ ∘ x) !id_left ⬝ !comp.right_inverse
variables (q)
theorem comp.cancel_left (H : q ∘ p = q ∘ p') : p = p' :=
by rewrite [-inverse_comp_cancel_left q p, H, inverse_comp_cancel_left q]
theorem comp.cancel_right (H : r ∘ q = r' ∘ q) : r = r' :=
by rewrite [-comp_inverse_cancel_right r q, H, comp_inverse_cancel_right _ q]
end
end iso
namespace iso
/- precomposition and postcomposition by an iso is an equivalence -/
definition is_equiv_postcompose [constructor] {ob : Type} [precategory ob] {a b c : ob}
(g : b ⟶ c) [is_iso g] : is_equiv (λ(f : a ⟶ b), g ∘ f) :=
begin
fapply adjointify,
{ exact λf', g⁻¹ ∘ f'},
{ intro f', apply comp_inverse_cancel_left},
{ intro f, apply inverse_comp_cancel_left}
end
definition equiv_postcompose [constructor] {ob : Type} [precategory ob] {a b c : ob}
(g : b ⟶ c) [is_iso g] : (a ⟶ b) ≃ (a ⟶ c) :=
equiv.mk (λ(f : a ⟶ b), g ∘ f) (is_equiv_postcompose g)
definition is_equiv_precompose [constructor] {ob : Type} [precategory ob] {a b c : ob}
(f : a ⟶ b) [is_iso f] : is_equiv (λ(g : b ⟶ c), g ∘ f) :=
begin
fapply adjointify,
{ exact λg', g' ∘ f⁻¹},
{ intro g', apply comp_inverse_cancel_right},
{ intro g, apply inverse_comp_cancel_right}
end
definition equiv_precompose [constructor] {ob : Type} [precategory ob] {a b c : ob}
(f : a ⟶ b) [is_iso f] : (b ⟶ c) ≃ (a ⟶ c) :=
equiv.mk (λ(g : b ⟶ c), g ∘ f) (is_equiv_precompose f)
end iso
|
d4c4334bded141773611a0510023eae84258d003 | 59b654f4ee2fef898a3487dc03554a569051b63a | /src/old/playground.lean | 0569ffb1ccd7e0fcf520a83ba5037255baeb1069 | [] | no_license | gunpinyo/twisted_cube_formalisation | 180c9157478b66ec2b11ca47c8ff998a3e978a88 | f78206ac495e84bd43a9b820fa10b6c94722e0ec | refs/heads/master | 1,624,501,222,992 | 1,607,081,624,000 | 1,607,081,624,000 | 166,885,106 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,499 | lean | -- import utils
variable b : bool
#check b.rec_on
#check nat.add
inductive fin' : ℕ → Type
| zero : fin' 0
| succ : Π {n : ℕ}, fin' n → fin' (n +1)
-- example : ∀ (n : ℕ) (i : fin n), i.cast_succ = (↑i : fin (n +1)) :=
-- def foo (n : ℕ) : fin n → bool
-- | 0 := false
-- | (i +1) := true
-- def fin_cycle : Π n : ℕ, fin n → fin n
-- | (n +1) ⟨0, _⟩ := fin.last n
-- | (n +1) ⟨i +1, p⟩ := let fin_i : fin n := ⟨i, nat.pred_le_pred p⟩
-- in {! !} --fin.succ (fin.succ (fin_double n fin_i))
def fin_is_even : Π n : ℕ, fin n → bool
| 0 i := i.elim0
| (n +1) ⟨0, _⟩ := true
| (n +1) ⟨i_val +1, succ_i_is_lt⟩ :=
let i : fin n := ⟨i_val, nat.pred_le_pred succ_i_is_lt⟩
in bnot (fin_is_even n i)
@[pattern]
def fin.zero {n : ℕ} : fin (n +1) := ⟨0, nat.zero_lt_succ n⟩
attribute [pattern] fin.succ
def fin_is_even' : Π n : ℕ, fin n → bool
| 0 i := i.elim0
| (n +1) fin.zero := true
| (n +1) (fin.succ i) := bnot (fin_is_even' n i)
I still have another question regarding `fin`. Sometimes, I want to use pattern matching on `i : fin n` in the same way as one will do in `ℕ` but since the inductive part is in `i.val` so I need to do as follows:
```lean
def fin_is_even : Π n : ℕ, fin n → bool
| 0 i := i.elim0
| (n +1) ⟨0, _⟩ := true
| (n +1) ⟨i_val +1, succ_i_is_lt⟩ :=hwere
in bnot (fin_is_even n i)
```
Ok, it works but in practice, I find it quite annoying to write `let i : fin n := ⟨i_val, nat.pred_le_pred succ_i_is_lt⟩` every time whereas `i` should be obtained directly from something like `fin.succ i`. Therefore, I try to use `@[pattern]` to help me with this as follows:
```lean
@[pattern]
def fin.zero {n : ℕ} : fin (n +1) := ⟨0, nat.zero_lt_succ n⟩
attribute [pattern] fin.succ
def fin_is_even' : Π n : ℕ, fin n → bool
| 0 i := i.elim0
| (n +1) fin.zero := true
| (n +1) (fin.succ i) := bnot (fin_is_even n i)
```
However I get an error, what is wrong with my code? Did I misunderstand anything about `@[pattern]`?
section
@[pattern]
def fin_zero {n : ℕ} : fin (n +1) := ⟨0, nat.zero_lt_succ n⟩
@[pattern]
def fin_succ {n : ℕ} : fin n → fin n.succ
| ⟨a, h⟩ := ⟨a.succ, nat.succ_lt_succ h⟩
def fin_is_zero (n : ℕ) : fin n → bool
| fin_zero := false
| (fin_succ i) := true
end
|
ed0f6ccbc167862a544c25d8ed26f451ffa50f38 | e030b0259b777fedcdf73dd966f3f1556d392178 | /library/init/data/list/lemmas.lean | cf008525602f89055755440265cd3f21ce16b903 | [
"Apache-2.0"
] | permissive | fgdorais/lean | 17b46a095b70b21fa0790ce74876658dc5faca06 | c3b7c54d7cca7aaa25328f0a5660b6b75fe26055 | refs/heads/master | 1,611,523,590,686 | 1,484,412,902,000 | 1,484,412,902,000 | 38,489,734 | 0 | 0 | null | 1,435,923,380,000 | 1,435,923,379,000 | null | UTF-8 | Lean | false | false | 7,922 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn
-/
prelude
import init.data.list.basic init.function init.meta
universe variables u v
variables {α : Type u} {β : Type v}
namespace list
lemma nil_append (s : list α) : [] ++ s = s :=
rfl
lemma cons_append (x : α) (s t : list α) : (x::s) ++ t = x::(s ++ t) :=
rfl
lemma map_nil (f : α → β) : map f [] = [] :=
rfl
lemma map_cons (f : α → β) (a : α) (l : list α) : map f (a :: l) = f a :: map f l :=
rfl
lemma length_nil : length (@nil α) = 0 :=
rfl
lemma length_cons (x : α) (t : list α) : length (x::t) = length t + 1 :=
rfl
lemma nth_zero (a : α) (l : list α) : nth (a :: l) 0 = some a :=
rfl
lemma nth_succ (a : α) (l : list α) (n : nat) : nth (a::l) (nat.succ n) = nth l n :=
rfl
/- list membership -/
lemma mem_nil_iff (a : α) : a ∈ [] ↔ false :=
iff.rfl
@[simp] lemma not_mem_nil (a : α) : a ∉ [] :=
iff.mp $ mem_nil_iff a
@[simp] lemma mem_cons_self (a : α) (l : list α) : a ∈ a :: l :=
or.inl rfl
lemma eq_nil_of_forall_not_mem : ∀ {l : list α}, (∀ a, a ∉ l) → l = nil
| [] := assume h, rfl
| (b :: l') := assume h, absurd (mem_cons_self b l') (h b)
lemma mem_cons_of_mem (y : α) {a : α} {l : list α} : a ∈ l → a ∈ y :: l :=
assume H, or.inr H
lemma eq_or_mem_of_mem_cons {a y : α} {l : list α} : a ∈ y::l → a = y ∨ a ∈ l :=
assume h, h
lemma mem_singleton {a b : α} : a ∈ [b] → a = b :=
suppose a ∈ [b], or.elim (eq_or_mem_of_mem_cons this)
(suppose a = b, this)
(suppose a ∈ [], absurd this (not_mem_nil a))
@[simp] lemma mem_singleton_iff (a b : α) : a ∈ [b] ↔ a = b :=
iff.intro mem_singleton (begin intro h, simp [h] end)
lemma mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l :=
assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl)
(suppose a = b, begin subst a, exact binl end)
(suppose a ∈ l, this)
lemma mem_or_mem_of_mem_append {a : α} : ∀ {s t : list α}, a ∈ s ++ t → a ∈ s ∨ a ∈ t
| [] t h := or.inr h
| (b::s) t h :=
have a = b ∨ a ∈ s ++ t, from h,
match this with
| or.inl h₁ := or.inl (h₁ ▸ mem_cons_self _ _)
| or.inr h₁ :=
have a ∈ s ∨ a ∈ t, from mem_or_mem_of_mem_append h₁,
match this with
| or.inl h₂ := or.inl (mem_cons_of_mem _ h₂)
| or.inr h₂ := or.inr h₂
end
end
lemma mem_append_of_mem_or_mem {a : α} {s t : list α} : a ∈ s ∨ a ∈ t → a ∈ s ++ t :=
list.induction_on s
(take h, or.elim h false.elim id)
(take b s,
assume ih : a ∈ s ∨ a ∈ t → a ∈ s ++ t,
suppose a ∈ b::s ∨ a ∈ t,
or.elim this
(suppose a ∈ b::s,
or.elim (eq_or_mem_of_mem_cons this)
(suppose a = b, or.inl this)
(suppose a ∈ s, or.inr (ih (or.inl this))))
(suppose a ∈ t, or.inr (ih (or.inr this))))
@[simp] lemma mem_append_iff (a : α) (s t : list α) : a ∈ s ++ t ↔ a ∈ s ∨ a ∈ t :=
iff.intro mem_or_mem_of_mem_append mem_append_of_mem_or_mem
lemma not_mem_of_not_mem_append_left {a : α} {s t : list α} : a ∉ s++t → a ∉ s :=
λ nainst ains, absurd (mem_append_of_mem_or_mem (or.inl ains)) nainst
lemma not_mem_of_not_mem_append_right {a : α} {s t : list α} : a ∉ s++t → a ∉ t :=
λ nainst aint, absurd (mem_append_of_mem_or_mem (or.inr aint)) nainst
lemma not_mem_append {a : α} {s t : list α} : a ∉ s → a ∉ t → a ∉ s++t :=
λ nains naint ainst, or.elim (mem_or_mem_of_mem_append ainst)
(λ ains, by contradiction)
(λ aint, by contradiction)
lemma length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l
| [] := suppose a ∈ [], begin simp at this, contradiction end
| (b::l) := suppose a ∈ b::l, nat.zero_lt_succ _
lemma mem_split {a : α} {l : list α} : a ∈ l → ∃ s t : list α, l = s ++ (a::t) :=
list.induction_on l
(suppose a ∈ [], begin simp at this, contradiction end)
(take b l,
assume ih : a ∈ l → ∃ s t : list α, l = s ++ (a::t),
suppose a ∈ b::l,
or.elim (eq_or_mem_of_mem_cons this)
(suppose a = b, ⟨[], l, begin rw this, reflexivity end⟩)
(suppose a ∈ l,
match (ih this) with
| ⟨s, t, (h : l = s ++ (a::t))⟩ := ⟨b::s, t, begin rw h, reflexivity end⟩
end))
lemma mem_append_left {a : α} {l₁ : list α} (l₂ : list α) : a ∈ l₁ → a ∈ l₁ ++ l₂ :=
assume ainl₁, mem_append_of_mem_or_mem (or.inl ainl₁)
lemma mem_append_right {a : α} (l₁ : list α) {l₂ : list α} : a ∈ l₂ → a ∈ l₁ ++ l₂ :=
assume ainl₂, mem_append_of_mem_or_mem (or.inr ainl₂)
lemma mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l :=
or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r)
lemma ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b :=
assume nin aeqb, absurd (or.inl aeqb) nin
lemma not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l :=
assume nin nainl, absurd (or.inr nainl) nin
lemma not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l :=
assume P1 P2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or P1 P2))
lemma ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l :=
assume P, and.intro (ne_of_not_mem_cons P) (not_mem_of_not_mem_cons P)
-- TODO(Jeremy): move this to data/list/set.lean
definition sublist (l₁ l₂ : list α) := ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂
instance : has_subset (list α) := ⟨sublist⟩
@[simp] lemma nil_subset (l : list α) : [] ⊆ l :=
λ b i, false.elim (iff.mp (mem_nil_iff b) i)
@[simp] lemma subset.refl (l : list α) : l ⊆ l :=
λ b i, i
lemma subset.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ :=
λ b i, h₂ (h₁ i)
@[simp] lemma subset_cons (a : α) (l : list α) : l ⊆ a::l :=
λ b i, or.inr i
lemma subset_of_cons_subset {a : α} {l₁ l₂ : list α} : a::l₁ ⊆ l₂ → l₁ ⊆ l₂ :=
λ s b i, s (mem_cons_of_mem _ i)
lemma cons_subset_cons {l₁ l₂ : list α} (a : α) (s : l₁ ⊆ l₂) : (a::l₁) ⊆ (a::l₂) :=
λ b hin, or.elim (eq_or_mem_of_mem_cons hin)
(λ e : b = a, or.inl e)
(λ i : b ∈ l₁, or.inr (s i))
@[simp] lemma subset_append_left (l₁ l₂ : list α) : l₁ ⊆ l₁++l₂ :=
λ b i, iff.mpr (mem_append_iff b l₁ l₂) (or.inl i)
@[simp] lemma subset_append_right (l₁ l₂ : list α) : l₂ ⊆ l₁++l₂ :=
λ b i, iff.mpr (mem_append_iff b l₁ l₂) (or.inr i)
lemma subset_cons_of_subset (a : α) {l₁ l₂ : list α} : l₁ ⊆ l₂ → l₁ ⊆ (a::l₂) :=
λ (s : l₁ ⊆ l₂) (a : α) (i : a ∈ l₁), or.inr (s i)
lemma subset_app_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ :=
λ (s : l ⊆ l₁) (a : α) (ainl : a ∈ l),
have a ∈ l₁, from s ainl,
mem_append_of_mem_or_mem (or.inl this)
lemma subset_app_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ :=
λ (s : l ⊆ l₂) (a : α) (ainl : a ∈ l),
have a ∈ l₂, from s ainl,
mem_append_of_mem_or_mem (or.inr this)
lemma cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) :
a::l ⊆ m :=
take b, suppose b ∈ a::l,
or.elim (eq_or_mem_of_mem_cons this)
(suppose b = a, begin subst b, exact ainm end)
(suppose b ∈ l, lsubm this)
lemma app_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) :
l₁ ++ l₂ ⊆ l :=
take a, suppose a ∈ l₁ ++ l₂,
or.elim (mem_or_mem_of_mem_append this)
(suppose a ∈ l₁, l₁subl this)
(suppose a ∈ l₂, l₂subl this)
end list
|
9cd96b8aafb2102157683c7a9a8859027f4bc00b | 827124860511172deb7ee955917c49b2bccd1b3c | /data/containers/utils/list.lean | fa7f0456eeb959503a89bde265431677306214c1 | [] | no_license | joehendrix/lean-containers | afec24c7de19c935774738ff3a0415362894956c | ef6ff0533eada75f18922039f8312badf12e6124 | refs/heads/master | 1,624,853,911,199 | 1,505,890,599,000 | 1,505,890,599,000 | 103,489,962 | 1 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 609 | lean | /- Additional theroems for list. -/
import data.list
import .option
namespace list
theorem find_append {α : Type _} (p : α → Prop) [decidable_pred p] (x y : list α)
: list.find p (x ++ y) = (list.find p x <|> list.find p y) :=
begin
induction x,
case list.nil {
simp [list.find, option.none_or_else],
},
case list.cons h r ind {
simp [list.find, ind],
by_cases (p h); simp [*, option.some_or_else],
}
end
theorem find_cons {α : Type _} (p : α → Prop) [decidable_pred p] (x : α) (y : list α)
: list.find p (x :: y) = if p x then option.some x else y.find p := rfl
end list
|
d11be4fed237655917ebde4261bd8fe5c9fdbad2 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /tests/lean/run/doNotation2.lean | 639c209b3e93a4623d73dc6fe0e5e56c2a71a15e | [
"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 | 4,083 | lean | def f (x : Nat) : IO Nat := do
IO.println "hello world"
let aux (y : Nat) (z : Nat) : IO Nat := do
IO.println "aux started"
IO.println s!"y: {y}, z: {z}"
pure (x+y)
discard <| aux x
(x + 1) -- It is part of the application since it is indented
discard <| aux x (x -- parentheses use `withoutPosition`
-1)
discard <| aux x x;
aux x
x
#eval f 10
def g (xs : List Nat) : StateT Nat Id Nat := do
let mut xs := xs
if xs.isEmpty then
xs := [← get]
dbgTrace! ">>> xs: {xs}"
return xs.length
#eval g [1, 2, 3] |>.run' 10
#eval g [] |>.run' 10
theorem ex1 : (g [1, 2, 4, 5] |>.run' 0) = 4 :=
rfl
theorem ex2 : (g [] |>.run' 0) = 1 :=
rfl
def h (x : Nat) (y : Nat) : Nat := do
let mut x := x
let mut y := y
if x > 0 then
let y := x + 1 -- this is a new `y` that shadows the one above
x := y
else
y := y + 1
return x + y
theorem ex3 (y : Nat) : h 0 y = 0 + (y + 1) :=
rfl
theorem ex4 (y : Nat) : h 1 y = (1 + 1) + y :=
rfl
def sumOdd (xs : List Nat) (threshold : Nat) : Nat := do
let mut sum := 0
for x in xs do
if x % 2 == 1 then
sum := sum + x
if sum > threshold then
break
unless x % 2 == 1 do
continue
dbgTrace! ">> x: {x}"
return sum
#eval sumOdd [1, 2, 3, 4, 5, 6, 7, 9, 11, 101] 10
theorem ex5 : sumOdd [1, 2, 3, 4, 5, 6, 7, 9, 11, 101] 10 = 16 :=
rfl
-- We need `Id.run` because we still have `Monad Option`
def find? (xs : List Nat) (p : Nat → Bool) : Option Nat := Id.run do
let mut result := none
for x in xs do
if p x then
result := x
break
return result
def sumDiff (ps : List (Nat × Nat)) : Nat := do
let mut sum := 0
for (x, y) in ps do
sum := sum + x - y
return sum
theorem ex7 : sumDiff [(2, 1), (10, 5)] = 6 :=
rfl
def f1 (x : Nat) : IO Unit := do
let rec loop : Nat → IO Unit
| 0 => pure ()
| x+1 => do IO.println x; loop x
loop x
#eval f1 10
partial def f2 (x : Nat) : IO Unit := do
let rec
isEven : Nat → Bool
| 0 => true
| x+1 => isOdd x,
isOdd : Nat → Bool
| 0 => false
| x+1 => isEven x
IO.println ("isOdd(" ++ toString x ++ "): " ++ toString (isOdd x))
#eval f2 11
#eval f2 10
def split (xs : List Nat) : List Nat × List Nat := do
let mut evens := []
let mut odds := []
for x in xs.reverse do
if x % 2 == 0 then
evens := x :: evens
else
odds := x :: odds
return (evens, odds)
theorem ex8 : split [1, 2, 3, 4] = ([2, 4], [1, 3]) :=
rfl
def f3 (x : Nat) : IO Bool := do
let y ← cond (x == 0) (do IO.println "hello"; true) false;
!y
def f4 (x y : Nat) : Nat × Nat := do
let mut (x, y) := (x, y)
match x with
| 0 => y := y + 1
| _ => x := x + y
return (x, y)
#eval f4 0 10
#eval f4 5 10
theorem ex9 (y : Nat) : f4 0 y = (0, y+1) :=
rfl
theorem ex10 (x y : Nat) : f4 (x+1) y = ((x+1)+y, y) :=
rfl
def f5 (x y : Nat) : Nat × Nat := do
let mut (x, y) := (x, y)
match x with
| 0 => y := y + 1
| z+1 => dbgTrace! "z: {z}"; x := x + y
return (x, y)
#eval f5 5 6
theorem ex11 (x y : Nat) : f5 (x+1) y = ((x+1)+y, y) :=
rfl
def f6 (x : Nat) : Nat := do
let mut x := x
if x > 10 then
return 0
x := x + 1
return x
theorem ex12 : f6 11 = 0 :=
rfl
theorem ex13 : f6 5 = 6 :=
rfl
def findOdd (xs : List Nat) : Nat := do
for x in xs do
if x % 2 == 1 then
return x
return 0
theorem ex14 : findOdd [2, 4, 5, 8, 7] = 5 :=
rfl
theorem ex15 : findOdd [2, 4, 8, 10] = 0 :=
rfl
def f7 (ref : IO.Ref (Option (Nat × Nat))) : IO Nat := do
let some (x, y) ← ref.get | pure 100
IO.println (toString x ++ ", " ++ toString y)
return x+y
def f7Test : IO Unit := do
unless (← f7 (← IO.mkRef (some (10, 20)))) == 30 do throw $ IO.userError "unexpected"
unless (← f7 (← IO.mkRef none)) == 100 do throw $ IO.userError "unexpected"
#eval f7Test
def f8 (x : Nat) : IO Nat := do
let y ←
if x == 0 then
IO.println "x is zero"
return 100 -- returns from the `do`-block
else
pure (x + 1)
IO.println ("y: " ++ toString y)
return y
def f8Test : IO Unit := do
unless (← f8 0) == 100 do throw $ IO.userError "unexpected"
unless (← f8 1) == 2 do throw $ IO.userError "unexpected"
#eval f8Test
|
ed22d1ddc998260f6544ba4efe681124bd35bd63 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/equivalence.lean | f421667168bf9b584d7fc86ba31fb94229f1a789 | [
"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 | 27,463 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn
-/
import category_theory.functor.fully_faithful
import category_theory.full_subcategory
import category_theory.whiskering
import category_theory.essential_image
import tactic.slice
/-!
# Equivalence of categories
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
An equivalence of categories `C` and `D` is a pair of functors `F : C ⥤ D` and `G : D ⥤ C` such
that `η : 𝟭 C ≅ F ⋙ G` and `ε : G ⋙ F ≅ 𝟭 D`. In many situations, equivalences are a better
notion of "sameness" of categories than the stricter isomorphims of categories.
Recall that one way to express that two functors `F : C ⥤ D` and `G : D ⥤ C` are adjoint is using
two natural transformations `η : 𝟭 C ⟶ F ⋙ G` and `ε : G ⋙ F ⟶ 𝟭 D`, called the unit and the
counit, such that the compositions `F ⟶ FGF ⟶ F` and `G ⟶ GFG ⟶ G` are the identity. Unfortunately,
it is not the case that the natural isomorphisms `η` and `ε` in the definition of an equivalence
automatically give an adjunction. However, it is true that
* if one of the two compositions is the identity, then so is the other, and
* given an equivalence of categories, it is always possible to refine `η` in such a way that the
identities are satisfied.
For this reason, in mathlib we define an equivalence to be a "half-adjoint equivalence", which is
a tuple `(F, G, η, ε)` as in the first paragraph such that the composite `F ⟶ FGF ⟶ F` is the
identity. By the remark above, this already implies that the tuple is an "adjoint equivalence",
i.e., that the composite `G ⟶ GFG ⟶ G` is also the identity.
We also define essentially surjective functors and show that a functor is an equivalence if and only
if it is full, faithful and essentially surjective.
## Main definitions
* `equivalence`: bundled (half-)adjoint equivalences of categories
* `is_equivalence`: type class on a functor `F` containing the data of the inverse `G` as well as
the natural isomorphisms `η` and `ε`.
* `ess_surj`: type class on a functor `F` containing the data of the preimages and the isomorphisms
`F.obj (preimage d) ≅ d`.
## Main results
* `equivalence.mk`: upgrade an equivalence to a (half-)adjoint equivalence
* `is_equivalence.equiv_of_iso`: when `F` and `G` are isomorphic functors, `F` is an equivalence
iff `G` is.
* `equivalence.of_fully_faithfully_ess_surj`: a fully faithful essentially surjective functor is an
equivalence.
## Notations
We write `C ≌ D` (`\backcong`, not to be confused with `≅`/`\cong`) for a bundled equivalence.
-/
namespace category_theory
open category_theory.functor nat_iso category
-- declare the `v`'s first; see `category_theory.category` for an explanation
universes v₁ v₂ v₃ u₁ u₂ u₃
/-- We define an equivalence as a (half)-adjoint equivalence, a pair of functors with
a unit and counit which are natural isomorphisms and the triangle law `Fη ≫ εF = 1`, or in other
words the composite `F ⟶ FGF ⟶ F` is the identity.
In `unit_inverse_comp`, we show that this is actually an adjoint equivalence, i.e., that the
composite `G ⟶ GFG ⟶ G` is also the identity.
The triangle equation is written as a family of equalities between morphisms, it is more
complicated if we write it as an equality of natural transformations, because then we would have
to insert natural transformations like `F ⟶ F1`.
See <https://stacks.math.columbia.edu/tag/001J>
-/
structure equivalence (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] :=
mk' ::
(functor : C ⥤ D)
(inverse : D ⥤ C)
(unit_iso : 𝟭 C ≅ functor ⋙ inverse)
(counit_iso : inverse ⋙ functor ≅ 𝟭 D)
(functor_unit_iso_comp' : ∀(X : C), functor.map ((unit_iso.hom : 𝟭 C ⟶ functor ⋙ inverse).app X) ≫
counit_iso.hom.app (functor.obj X) = 𝟙 (functor.obj X) . obviously)
restate_axiom equivalence.functor_unit_iso_comp'
infixr ` ≌ `:10 := equivalence
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
namespace equivalence
/-- The unit of an equivalence of categories. -/
abbreviation unit (e : C ≌ D) : 𝟭 C ⟶ e.functor ⋙ e.inverse := e.unit_iso.hom
/-- The counit of an equivalence of categories. -/
abbreviation counit (e : C ≌ D) : e.inverse ⋙ e.functor ⟶ 𝟭 D := e.counit_iso.hom
/-- The inverse of the unit of an equivalence of categories. -/
abbreviation unit_inv (e : C ≌ D) : e.functor ⋙ e.inverse ⟶ 𝟭 C := e.unit_iso.inv
/-- The inverse of the counit of an equivalence of categories. -/
abbreviation counit_inv (e : C ≌ D) : 𝟭 D ⟶ e.inverse ⋙ e.functor := e.counit_iso.inv
/- While these abbreviations are convenient, they also cause some trouble,
preventing structure projections from unfolding. -/
@[simp] lemma equivalence_mk'_unit (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit = unit_iso.hom := rfl
@[simp] lemma equivalence_mk'_counit (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit = counit_iso.hom := rfl
@[simp] lemma equivalence_mk'_unit_inv (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit_inv = unit_iso.inv := rfl
@[simp] lemma equivalence_mk'_counit_inv (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit_inv = counit_iso.inv := rfl
@[simp] lemma functor_unit_comp (e : C ≌ D) (X : C) :
e.functor.map (e.unit.app X) ≫ e.counit.app (e.functor.obj X) = 𝟙 (e.functor.obj X) :=
e.functor_unit_iso_comp X
@[simp] lemma counit_inv_functor_comp (e : C ≌ D) (X : C) :
e.counit_inv.app (e.functor.obj X) ≫ e.functor.map (e.unit_inv.app X) = 𝟙 (e.functor.obj X) :=
begin
erw [iso.inv_eq_inv
(e.functor.map_iso (e.unit_iso.app X) ≪≫ e.counit_iso.app (e.functor.obj X)) (iso.refl _)],
exact e.functor_unit_comp X
end
lemma counit_inv_app_functor (e : C ≌ D) (X : C) :
e.counit_inv.app (e.functor.obj X) = e.functor.map (e.unit.app X) :=
by { symmetry, erw [←iso.comp_hom_eq_id (e.counit_iso.app _), functor_unit_comp], refl }
lemma counit_app_functor (e : C ≌ D) (X : C) :
e.counit.app (e.functor.obj X) = e.functor.map (e.unit_inv.app X) :=
by { erw [←iso.hom_comp_eq_id (e.functor.map_iso (e.unit_iso.app X)), functor_unit_comp], refl }
/-- The other triangle equality. The proof follows the following proof in Globular:
http://globular.science/1905.001 -/
@[simp] lemma unit_inverse_comp (e : C ≌ D) (Y : D) :
e.unit.app (e.inverse.obj Y) ≫ e.inverse.map (e.counit.app Y) = 𝟙 (e.inverse.obj Y) :=
begin
rw [←id_comp (e.inverse.map _), ←map_id e.inverse, ←counit_inv_functor_comp, map_comp],
dsimp,
rw [←iso.hom_inv_id_assoc (e.unit_iso.app _) (e.inverse.map (e.functor.map _)),
app_hom, app_inv],
slice_lhs 2 3 { erw [e.unit.naturality] },
slice_lhs 1 2 { erw [e.unit.naturality] },
slice_lhs 4 4
{ rw [←iso.hom_inv_id_assoc (e.inverse.map_iso (e.counit_iso.app _)) (e.unit_inv.app _)] },
slice_lhs 3 4 { erw [←map_comp e.inverse, e.counit.naturality],
erw [(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp],
slice_lhs 2 3 { erw [←map_comp e.inverse, e.counit_iso.inv.naturality, map_comp] },
slice_lhs 3 4 { erw [e.unit_inv.naturality] },
slice_lhs 4 5 { erw [←map_comp (e.functor ⋙ e.inverse), (e.unit_iso.app _).hom_inv_id, map_id] },
erw [id_comp],
slice_lhs 3 4 { erw [←e.unit_inv.naturality] },
slice_lhs 2 3 { erw [←map_comp e.inverse, ←e.counit_iso.inv.naturality,
(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp, (e.unit_iso.app _).hom_inv_id], refl
end
@[simp] lemma inverse_counit_inv_comp (e : C ≌ D) (Y : D) :
e.inverse.map (e.counit_inv.app Y) ≫ e.unit_inv.app (e.inverse.obj Y) = 𝟙 (e.inverse.obj Y) :=
begin
erw [iso.inv_eq_inv
(e.unit_iso.app (e.inverse.obj Y) ≪≫ e.inverse.map_iso (e.counit_iso.app Y)) (iso.refl _)],
exact e.unit_inverse_comp Y
end
lemma unit_app_inverse (e : C ≌ D) (Y : D) :
e.unit.app (e.inverse.obj Y) = e.inverse.map (e.counit_inv.app Y) :=
by { erw [←iso.comp_hom_eq_id (e.inverse.map_iso (e.counit_iso.app Y)), unit_inverse_comp], refl }
lemma unit_inv_app_inverse (e : C ≌ D) (Y : D) :
e.unit_inv.app (e.inverse.obj Y) = e.inverse.map (e.counit.app Y) :=
by { symmetry, erw [←iso.hom_comp_eq_id (e.unit_iso.app _), unit_inverse_comp], refl }
@[simp] lemma fun_inv_map (e : C ≌ D) (X Y : D) (f : X ⟶ Y) :
e.functor.map (e.inverse.map f) = e.counit.app X ≫ f ≫ e.counit_inv.app Y :=
(nat_iso.naturality_2 (e.counit_iso) f).symm
@[simp] lemma inv_fun_map (e : C ≌ D) (X Y : C) (f : X ⟶ Y) :
e.inverse.map (e.functor.map f) = e.unit_inv.app X ≫ f ≫ e.unit.app Y :=
(nat_iso.naturality_1 (e.unit_iso) f).symm
section
-- In this section we convert an arbitrary equivalence to a half-adjoint equivalence.
variables {F : C ⥤ D} {G : D ⥤ C} (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D)
/-- If `η : 𝟭 C ≅ F ⋙ G` is part of a (not necessarily half-adjoint) equivalence, we can upgrade it
to a refined natural isomorphism `adjointify_η η : 𝟭 C ≅ F ⋙ G` which exhibits the properties
required for a half-adjoint equivalence. See `equivalence.mk`. -/
def adjointify_η : 𝟭 C ≅ F ⋙ G :=
calc
𝟭 C ≅ F ⋙ G : η
... ≅ F ⋙ (𝟭 D ⋙ G) : iso_whisker_left F (left_unitor G).symm
... ≅ F ⋙ ((G ⋙ F) ⋙ G) : iso_whisker_left F (iso_whisker_right ε.symm G)
... ≅ F ⋙ (G ⋙ (F ⋙ G)) : iso_whisker_left F (associator G F G)
... ≅ (F ⋙ G) ⋙ (F ⋙ G) : (associator F G (F ⋙ G)).symm
... ≅ 𝟭 C ⋙ (F ⋙ G) : iso_whisker_right η.symm (F ⋙ G)
... ≅ F ⋙ G : left_unitor (F ⋙ G)
lemma adjointify_η_ε (X : C) :
F.map ((adjointify_η η ε).hom.app X) ≫ ε.hom.app (F.obj X) = 𝟙 (F.obj X) :=
begin
dsimp [adjointify_η], simp,
have := ε.hom.naturality (F.map (η.inv.app X)), dsimp at this, rw [this], clear this,
rw [←assoc _ _ (F.map _)],
have := ε.hom.naturality (ε.inv.app $ F.obj X), dsimp at this, rw [this], clear this,
have := (ε.app $ F.obj X).hom_inv_id, dsimp at this, rw [this], clear this,
rw [id_comp], have := (F.map_iso $ η.app X).hom_inv_id, dsimp at this, rw [this]
end
end
/-- Every equivalence of categories consisting of functors `F` and `G` such that `F ⋙ G` and
`G ⋙ F` are naturally isomorphic to identity functors can be transformed into a half-adjoint
equivalence without changing `F` or `G`. -/
protected definition mk (F : C ⥤ D) (G : D ⥤ C)
(η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : C ≌ D :=
⟨F, G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩
/-- Equivalence of categories is reflexive. -/
@[refl, simps] def refl : C ≌ C :=
⟨𝟭 C, 𝟭 C, iso.refl _, iso.refl _, λ X, category.id_comp _⟩
instance : inhabited (C ≌ C) :=
⟨refl⟩
/-- Equivalence of categories is symmetric. -/
@[symm, simps] def symm (e : C ≌ D) : D ≌ C :=
⟨e.inverse, e.functor, e.counit_iso.symm, e.unit_iso.symm, e.inverse_counit_inv_comp⟩
variables {E : Type u₃} [category.{v₃} E]
/-- Equivalence of categories is transitive. -/
@[trans, simps] def trans (e : C ≌ D) (f : D ≌ E) : C ≌ E :=
{ functor := e.functor ⋙ f.functor,
inverse := f.inverse ⋙ e.inverse,
unit_iso :=
begin
refine iso.trans e.unit_iso _,
exact iso_whisker_left e.functor (iso_whisker_right f.unit_iso e.inverse) ,
end,
counit_iso :=
begin
refine iso.trans _ f.counit_iso,
exact iso_whisker_left f.inverse (iso_whisker_right e.counit_iso f.functor)
end,
-- We wouldn't have needed to give this proof if we'd used `equivalence.mk`,
-- but we choose to avoid using that here, for the sake of good structure projection `simp`
-- lemmas.
functor_unit_iso_comp' := λ X,
begin
dsimp,
rw [← f.functor.map_comp_assoc, e.functor.map_comp, ←counit_inv_app_functor, fun_inv_map,
iso.inv_hom_id_app_assoc, assoc, iso.inv_hom_id_app, counit_app_functor,
← functor.map_comp],
erw [comp_id, iso.hom_inv_id_app, functor.map_id],
end }
/-- Composing a functor with both functors of an equivalence yields a naturally isomorphic
functor. -/
def fun_inv_id_assoc (e : C ≌ D) (F : C ⥤ E) : e.functor ⋙ e.inverse ⋙ F ≅ F :=
(functor.associator _ _ _).symm ≪≫ iso_whisker_right e.unit_iso.symm F ≪≫ F.left_unitor
@[simp] lemma fun_inv_id_assoc_hom_app (e : C ≌ D) (F : C ⥤ E) (X : C) :
(fun_inv_id_assoc e F).hom.app X = F.map (e.unit_inv.app X) :=
by { dsimp [fun_inv_id_assoc], tidy }
@[simp] lemma fun_inv_id_assoc_inv_app (e : C ≌ D) (F : C ⥤ E) (X : C) :
(fun_inv_id_assoc e F).inv.app X = F.map (e.unit.app X) :=
by { dsimp [fun_inv_id_assoc], tidy }
/-- Composing a functor with both functors of an equivalence yields a naturally isomorphic
functor. -/
def inv_fun_id_assoc (e : C ≌ D) (F : D ⥤ E) : e.inverse ⋙ e.functor ⋙ F ≅ F :=
(functor.associator _ _ _).symm ≪≫ iso_whisker_right e.counit_iso F ≪≫ F.left_unitor
@[simp] lemma inv_fun_id_assoc_hom_app (e : C ≌ D) (F : D ⥤ E) (X : D) :
(inv_fun_id_assoc e F).hom.app X = F.map (e.counit.app X) :=
by { dsimp [inv_fun_id_assoc], tidy }
@[simp] lemma inv_fun_id_assoc_inv_app (e : C ≌ D) (F : D ⥤ E) (X : D) :
(inv_fun_id_assoc e F).inv.app X = F.map (e.counit_inv.app X) :=
by { dsimp [inv_fun_id_assoc], tidy }
/-- If `C` is equivalent to `D`, then `C ⥤ E` is equivalent to `D ⥤ E`. -/
@[simps functor inverse unit_iso counit_iso]
def congr_left (e : C ≌ D) : (C ⥤ E) ≌ (D ⥤ E) :=
equivalence.mk
((whiskering_left _ _ _).obj e.inverse)
((whiskering_left _ _ _).obj e.functor)
(nat_iso.of_components (λ F, (e.fun_inv_id_assoc F).symm) (by tidy))
(nat_iso.of_components (λ F, e.inv_fun_id_assoc F) (by tidy))
/-- If `C` is equivalent to `D`, then `E ⥤ C` is equivalent to `E ⥤ D`. -/
@[simps functor inverse unit_iso counit_iso]
def congr_right (e : C ≌ D) : (E ⥤ C) ≌ (E ⥤ D) :=
equivalence.mk
((whiskering_right _ _ _).obj e.functor)
((whiskering_right _ _ _).obj e.inverse)
(nat_iso.of_components
(λ F, F.right_unitor.symm ≪≫ iso_whisker_left F e.unit_iso ≪≫ functor.associator _ _ _)
(by tidy))
(nat_iso.of_components
(λ F, functor.associator _ _ _ ≪≫ iso_whisker_left F e.counit_iso ≪≫ F.right_unitor)
(by tidy))
section cancellation_lemmas
variables (e : C ≌ D)
/- We need special forms of `cancel_nat_iso_hom_right(_assoc)` and
`cancel_nat_iso_inv_right(_assoc)` for units and counits, because neither `simp` or `rw` will apply
those lemmas in this setting without providing `e.unit_iso` (or similar) as an explicit argument.
We also provide the lemmas for length four compositions, since they're occasionally useful.
(e.g. in proving that equivalences take monos to monos) -/
@[simp] lemma cancel_unit_right {X Y : C}
(f f' : X ⟶ Y) :
f ≫ e.unit.app Y = f' ≫ e.unit.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_unit_inv_right {X Y : C}
(f f' : X ⟶ e.inverse.obj (e.functor.obj Y)) :
f ≫ e.unit_inv.app Y = f' ≫ e.unit_inv.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_counit_right {X Y : D}
(f f' : X ⟶ e.functor.obj (e.inverse.obj Y)) :
f ≫ e.counit.app Y = f' ≫ e.counit.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_counit_inv_right {X Y : D}
(f f' : X ⟶ Y) :
f ≫ e.counit_inv.app Y = f' ≫ e.counit_inv.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_unit_right_assoc {W X X' Y : C}
(f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) :
f ≫ g ≫ e.unit.app Y = f' ≫ g' ≫ e.unit.app Y ↔ f ≫ g = f' ≫ g' :=
by simp only [←category.assoc, cancel_mono]
@[simp] lemma cancel_counit_inv_right_assoc {W X X' Y : D}
(f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) :
f ≫ g ≫ e.counit_inv.app Y = f' ≫ g' ≫ e.counit_inv.app Y ↔ f ≫ g = f' ≫ g' :=
by simp only [←category.assoc, cancel_mono]
@[simp] lemma cancel_unit_right_assoc' {W X X' Y Y' Z : C}
(f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) :
f ≫ g ≫ h ≫ e.unit.app Z = f' ≫ g' ≫ h' ≫ e.unit.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' :=
by simp only [←category.assoc, cancel_mono]
@[simp] lemma cancel_counit_inv_right_assoc' {W X X' Y Y' Z : D}
(f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) :
f ≫ g ≫ h ≫ e.counit_inv.app Z = f' ≫ g' ≫ h' ≫ e.counit_inv.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' :=
by simp only [←category.assoc, cancel_mono]
end cancellation_lemmas
section
-- There's of course a monoid structure on `C ≌ C`,
-- but let's not encourage using it.
-- The power structure is nevertheless useful.
/-- Natural number powers of an auto-equivalence. Use `(^)` instead. -/
def pow_nat (e : C ≌ C) : ℕ → (C ≌ C)
| 0 := equivalence.refl
| 1 := e
| (n+2) := e.trans (pow_nat (n+1))
/-- Powers of an auto-equivalence. Use `(^)` instead. -/
def pow (e : C ≌ C) : ℤ → (C ≌ C)
| (int.of_nat n) := e.pow_nat n
| (int.neg_succ_of_nat n) := e.symm.pow_nat (n+1)
instance : has_pow (C ≌ C) ℤ := ⟨pow⟩
@[simp] lemma pow_zero (e : C ≌ C) : e^(0 : ℤ) = equivalence.refl := rfl
@[simp] lemma pow_one (e : C ≌ C) : e^(1 : ℤ) = e := rfl
@[simp] lemma pow_neg_one (e : C ≌ C) : e^(-1 : ℤ) = e.symm := rfl
-- TODO as necessary, add the natural isomorphisms `(e^a).trans e^b ≅ e^(a+b)`.
-- At this point, we haven't even defined the category of equivalences.
end
end equivalence
/-- A functor that is part of a (half) adjoint equivalence -/
class is_equivalence (F : C ⥤ D) :=
mk' ::
(inverse : D ⥤ C)
(unit_iso : 𝟭 C ≅ F ⋙ inverse)
(counit_iso : inverse ⋙ F ≅ 𝟭 D)
(functor_unit_iso_comp' : ∀ (X : C), F.map ((unit_iso.hom : 𝟭 C ⟶ F ⋙ inverse).app X) ≫
counit_iso.hom.app (F.obj X) = 𝟙 (F.obj X) . obviously)
restate_axiom is_equivalence.functor_unit_iso_comp'
attribute [simp, reassoc] is_equivalence.functor_unit_iso_comp
namespace is_equivalence
instance of_equivalence (F : C ≌ D) : is_equivalence F.functor :=
{ ..F }
instance of_equivalence_inverse (F : C ≌ D) : is_equivalence F.inverse :=
is_equivalence.of_equivalence F.symm
open equivalence
/-- To see that a functor is an equivalence, it suffices to provide an inverse functor `G` such that
`F ⋙ G` and `G ⋙ F` are naturally isomorphic to identity functors. -/
protected definition mk {F : C ⥤ D} (G : D ⥤ C)
(η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : is_equivalence F :=
⟨G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩
end is_equivalence
namespace functor
/-- Interpret a functor that is an equivalence as an equivalence. -/
def as_equivalence (F : C ⥤ D) [is_equivalence F] : C ≌ D :=
⟨F, is_equivalence.inverse F, is_equivalence.unit_iso, is_equivalence.counit_iso,
is_equivalence.functor_unit_iso_comp⟩
instance is_equivalence_refl : is_equivalence (𝟭 C) :=
is_equivalence.of_equivalence equivalence.refl
/-- The inverse functor of a functor that is an equivalence. -/
def inv (F : C ⥤ D) [is_equivalence F] : D ⥤ C :=
is_equivalence.inverse F
instance is_equivalence_inv (F : C ⥤ D) [is_equivalence F] : is_equivalence F.inv :=
is_equivalence.of_equivalence F.as_equivalence.symm
@[simp] lemma as_equivalence_functor (F : C ⥤ D) [is_equivalence F] :
F.as_equivalence.functor = F := rfl
@[simp] lemma as_equivalence_inverse (F : C ⥤ D) [is_equivalence F] :
F.as_equivalence.inverse = inv F := rfl
@[simp] lemma as_equivalence_unit {F : C ⥤ D} [h : is_equivalence F] :
F.as_equivalence.unit_iso = @@is_equivalence.unit_iso _ _ h := rfl
@[simp] lemma as_equivalence_counit {F : C ⥤ D} [is_equivalence F] :
F.as_equivalence.counit_iso = is_equivalence.counit_iso := rfl
@[simp] lemma inv_inv (F : C ⥤ D) [is_equivalence F] :
inv (inv F) = F := rfl
variables {E : Type u₃} [category.{v₃} E]
instance is_equivalence_trans (F : C ⥤ D) (G : D ⥤ E) [is_equivalence F] [is_equivalence G] :
is_equivalence (F ⋙ G) :=
is_equivalence.of_equivalence (equivalence.trans (as_equivalence F) (as_equivalence G))
end functor
namespace equivalence
@[simp]
lemma functor_inv (E : C ≌ D) : E.functor.inv = E.inverse := rfl
@[simp]
lemma inverse_inv (E : C ≌ D) : E.inverse.inv = E.functor := rfl
@[simp]
lemma functor_as_equivalence (E : C ≌ D) : E.functor.as_equivalence = E :=
by { cases E, congr, }
@[simp]
lemma inverse_as_equivalence (E : C ≌ D) : E.inverse.as_equivalence = E.symm :=
by { cases E, congr, }
end equivalence
namespace is_equivalence
@[simp] lemma fun_inv_map (F : C ⥤ D) [is_equivalence F] (X Y : D) (f : X ⟶ Y) :
F.map (F.inv.map f) = F.as_equivalence.counit.app X ≫ f ≫ F.as_equivalence.counit_inv.app Y :=
begin
erw [nat_iso.naturality_2],
refl
end
@[simp] lemma inv_fun_map (F : C ⥤ D) [is_equivalence F] (X Y : C) (f : X ⟶ Y) :
F.inv.map (F.map f) = F.as_equivalence.unit_inv.app X ≫ f ≫ F.as_equivalence.unit.app Y :=
begin
erw [nat_iso.naturality_1],
refl
end
/-- When a functor `F` is an equivalence of categories, and `G` is isomorphic to `F`, then
`G` is also an equivalence of categories. -/
@[simps]
def of_iso {F G : C ⥤ D} (e : F ≅ G) (hF : is_equivalence F) : is_equivalence G :=
{ inverse := hF.inverse,
unit_iso := hF.unit_iso ≪≫ nat_iso.hcomp e (iso.refl hF.inverse),
counit_iso := nat_iso.hcomp (iso.refl hF.inverse) e.symm ≪≫ hF.counit_iso,
functor_unit_iso_comp' := λ X, begin
dsimp [nat_iso.hcomp],
erw [id_comp, F.map_id, comp_id],
apply (cancel_epi (e.hom.app X)).mp,
slice_lhs 1 2 { rw ← e.hom.naturality, },
slice_lhs 2 3 { rw [← nat_trans.vcomp_app', e.hom_inv_id], },
simp only [nat_trans.id_app, id_comp, comp_id, F.map_comp, assoc],
erw hF.counit_iso.hom.naturality,
slice_lhs 1 2 { rw functor_unit_iso_comp, },
simp only [functor.id_map, id_comp],
end }
/-- Compatibility of `of_iso` with the composition of isomorphisms of functors -/
lemma of_iso_trans {F G H : C ⥤ D} (e : F ≅ G) (e' : G ≅ H) (hF : is_equivalence F) :
(of_iso e' (of_iso e hF)) = of_iso (e ≪≫ e') hF :=
begin
dsimp [of_iso],
congr' 1; ext X; dsimp [nat_iso.hcomp],
{ simp only [id_comp, assoc, functor.map_comp], },
{ simp only [functor.map_id, comp_id, id_comp, assoc], },
end
/-- Compatibility of `of_iso` with identity isomorphisms of functors -/
lemma of_iso_refl (F : C ⥤ D) (hF : is_equivalence F) : of_iso (iso.refl F) hF = hF :=
begin
unfreezingI { rcases hF with ⟨Finv, Funit, Fcounit, Fcomp⟩, },
dsimp [of_iso],
congr' 1; ext X; dsimp [nat_iso.hcomp],
{ simp only [comp_id, map_id], },
{ simp only [id_comp, map_id], },
end
/-- When `F` and `G` are two isomorphic functors, then `F` is an equivalence iff `G` is. -/
@[simps]
def equiv_of_iso {F G : C ⥤ D} (e : F ≅ G) : is_equivalence F ≃ is_equivalence G :=
{ to_fun := of_iso e,
inv_fun := of_iso e.symm,
left_inv := λ hF, by rw [of_iso_trans, iso.self_symm_id, of_iso_refl],
right_inv := λ hF, by rw [of_iso_trans, iso.symm_self_id, of_iso_refl], }
/-- If `G` and `F ⋙ G` are equivalence of categories, then `F` is also an equivalence. -/
@[simp]
def cancel_comp_right {E : Type*} [category E]
(F : C ⥤ D) (G : D ⥤ E) (hG : is_equivalence G) (hGF : is_equivalence (F ⋙ G)) :
is_equivalence F :=
of_iso ((functor.associator F G G.inv) ≪≫ nat_iso.hcomp (iso.refl F) hG.unit_iso.symm ≪≫
right_unitor F) (functor.is_equivalence_trans (F ⋙ G) (G.inv))
/-- If `F` and `F ⋙ G` are equivalence of categories, then `G` is also an equivalence. -/
@[simp]
def cancel_comp_left {E : Type*} [category E]
(F : C ⥤ D) (G : D ⥤ E) (hF : is_equivalence F) (hGF : is_equivalence (F ⋙ G)) :
is_equivalence G :=
of_iso ((functor.associator F.inv F G).symm ≪≫ nat_iso.hcomp hF.counit_iso (iso.refl G) ≪≫
left_unitor G) (functor.is_equivalence_trans F.inv (F ⋙ G))
end is_equivalence
namespace equivalence
/--
An equivalence is essentially surjective.
See <https://stacks.math.columbia.edu/tag/02C3>.
-/
lemma ess_surj_of_equivalence (F : C ⥤ D) [is_equivalence F] : ess_surj F :=
⟨λ Y, ⟨F.inv.obj Y, ⟨F.as_equivalence.counit_iso.app Y⟩⟩⟩
/--
An equivalence is faithful.
See <https://stacks.math.columbia.edu/tag/02C3>.
-/
@[priority 100] -- see Note [lower instance priority]
instance faithful_of_equivalence (F : C ⥤ D) [is_equivalence F] : faithful F :=
{ map_injective' := λ X Y f g w,
begin
have p := congr_arg (@category_theory.functor.map _ _ _ _ F.inv _ _) w,
simpa only [cancel_epi, cancel_mono, is_equivalence.inv_fun_map] using p
end }.
/--
An equivalence is full.
See <https://stacks.math.columbia.edu/tag/02C3>.
-/
@[priority 100] -- see Note [lower instance priority]
instance full_of_equivalence (F : C ⥤ D) [is_equivalence F] : full F :=
{ preimage := λ X Y f, F.as_equivalence.unit.app X ≫ F.inv.map f ≫ F.as_equivalence.unit_inv.app Y,
witness' := λ X Y f, F.inv.map_injective $
by simpa only [is_equivalence.inv_fun_map, assoc, iso.inv_hom_id_app_assoc, iso.inv_hom_id_app]
using comp_id _ }
@[simps] private noncomputable def equivalence_inverse (F : C ⥤ D) [full F] [faithful F]
[ess_surj F] : D ⥤ C :=
{ obj := λ X, F.obj_preimage X,
map := λ X Y f, F.preimage ((F.obj_obj_preimage_iso X).hom ≫ f ≫ (F.obj_obj_preimage_iso Y).inv),
map_id' := λ X, begin apply F.map_injective, tidy end,
map_comp' := λ X Y Z f g, by apply F.map_injective; simp }
/--
A functor which is full, faithful, and essentially surjective is an equivalence.
See <https://stacks.math.columbia.edu/tag/02C3>.
-/
noncomputable def of_fully_faithfully_ess_surj
(F : C ⥤ D) [full F] [faithful F] [ess_surj F] : is_equivalence F :=
is_equivalence.mk (equivalence_inverse F)
(nat_iso.of_components
(λ X, (F.preimage_iso $ F.obj_obj_preimage_iso $ F.obj X).symm)
(λ X Y f, by { apply F.map_injective, obviously }))
(nat_iso.of_components F.obj_obj_preimage_iso (by tidy))
@[simp] lemma functor_map_inj_iff (e : C ≌ D) {X Y : C} (f g : X ⟶ Y) :
e.functor.map f = e.functor.map g ↔ f = g :=
⟨λ h, e.functor.map_injective h, λ h, h ▸ rfl⟩
@[simp] lemma inverse_map_inj_iff (e : C ≌ D) {X Y : D} (f g : X ⟶ Y) :
e.inverse.map f = e.inverse.map g ↔ f = g :=
functor_map_inj_iff e.symm f g
instance ess_surj_induced_functor {C' : Type*} (e : C' ≃ D) : ess_surj (induced_functor e) :=
{ mem_ess_image := λ Y, ⟨e.symm Y, by simp⟩, }
noncomputable
instance induced_functor_of_equiv {C' : Type*} (e : C' ≃ D) : is_equivalence (induced_functor e) :=
equivalence.of_fully_faithfully_ess_surj _
noncomputable
instance fully_faithful_to_ess_image (F : C ⥤ D) [full F] [faithful F] :
is_equivalence F.to_ess_image :=
of_fully_faithfully_ess_surj F.to_ess_image
end equivalence
end category_theory
|
6eb4d0c18ed67052fddcd8d76a54b05472c128e0 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/pp_beta.lean | 5103fdaae91680c670b845db4b247dda532a722d | [
"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 | 86 | lean | open nat
#check (λ x : nat, x) 1
set_option pp.beta true
#check (λ x : nat, x) 1
|
64a09432e38cf9a2c6027eb285d098b76ee8ce56 | d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6 | /Papyrus/Script/SyntaxUtil.lean | d4e9b2e383fc0ff8dc36333dde7182845fe9fc18 | [
"Apache-2.0"
] | permissive | xubaiw/lean4-papyrus | c3fbbf8ba162eb5f210155ae4e20feb2d32c8182 | 02e82973a5badda26fc0f9fd15b3d37e2eb309e0 | refs/heads/master | 1,691,425,756,824 | 1,632,122,825,000 | 1,632,123,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 493 | lean | open Lean Syntax
namespace Papyrus.Script
def mkEvalAt (tk : Syntax) (stx : Syntax) : Syntax :=
mkNode `Lean.Parser.Command.eval #[mkAtomFrom tk "#eval ", stx]
def identAsStrLit (id : Syntax) : Syntax :=
mkStrLit (info := SourceInfo.fromRef id) <| id.getId.toString (escape := false)
def mkCAppFrom (src : Syntax) (fn : Name) (args : Array Syntax) : Syntax :=
mkApp (mkCIdentFrom src fn) args
def mkNumLitFrom (src : Syntax) (val : String) :=
mkNumLit val (SourceInfo.fromRef src)
|
01f9303df5c52d60d7e0fa927c12446a24783d91 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/meta/rb_map.lean | 4fd4ce1b100965be2382e1a74e1b07fb99bb1963 | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 3,627 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Robert Y. Lewis
Additional operations on native rb_maps and rb_sets.
-/
import data.option.defs
namespace native
namespace rb_set
meta def filter {key} (s : rb_set key) (P : key → bool) : rb_set key :=
s.fold s (λ a m, if P a then m else m.erase a)
meta def mfilter {m} [monad m] {key} (s : rb_set key) (P : key → m bool) : m (rb_set key) :=
s.fold (pure s) (λ a m,
do x ← m,
mcond (P a) (pure x) (pure $ x.erase a))
meta def union {key} (s t : rb_set key) : rb_set key :=
s.fold t (λ a t, t.insert a)
end rb_set
namespace rb_map
meta def find_def {α β} [has_lt α] [decidable_rel ((<) : α → α → Prop)]
(x : β) (m : rb_map α β) (k : α) :=
(m.find k).get_or_else x
meta def insert_cons {α β} [has_lt α] [decidable_rel ((<) : α → α → Prop)]
(k : α) (x : β) (m : rb_map α (list β)) : rb_map α (list β) :=
m.insert k (x :: m.find_def [] k)
meta def ifind {α β} [inhabited β] (m : rb_map α β) (a : α) : β :=
(m.find a).iget
meta def zfind {α β} [has_zero β] (m : rb_map α β) (a : α) : β :=
(m.find a).get_or_else 0
meta def add {α β} [has_add β] [has_zero β] [decidable_eq β] (m1 m2 : rb_map α β) : rb_map α β :=
m1.fold m2
(λ n v m,
let nv := v + m2.zfind n in
if nv = 0 then m.erase n else m.insert n nv)
variables {m : Type → Type*} [monad m]
open function
meta def mfilter {key val} [has_lt key] [decidable_rel ((<) : key → key → Prop)]
(P : key → val → m bool) (s : rb_map key val) : m (rb_map.{0 0} key val) :=
rb_map.of_list <$> s.to_list.mfilter (uncurry P)
meta def mmap {key val val'} [has_lt key] [decidable_rel ((<) : key → key → Prop)]
(f : val → m val') (s : rb_map key val) : m (rb_map.{0 0} key val') :=
rb_map.of_list <$> s.to_list.mmap (λ ⟨a,b⟩, prod.mk a <$> f b)
meta def scale {α β} [has_lt α] [decidable_rel ((<) : α → α → Prop)] [has_mul β] (b : β) (m : rb_map α β) : rb_map α β :=
m.map ((*) b)
section
open format prod
variables {key : Type} {data : Type} [has_to_tactic_format key] [has_to_tactic_format data]
private meta def pp_key_data (k : key) (d : data) (first : bool) : tactic format :=
do fk ← tactic.pp k, fd ← tactic.pp d, return $
(if first then to_fmt "" else to_fmt "," ++ line) ++ fk ++ space ++ to_fmt "←" ++ space ++ fd
meta instance : has_to_tactic_format (rb_map key data) :=
⟨λ m, do
(fmt, _) ← fold m (return (to_fmt "", tt))
(λ k d p, do p ← p, pkd ← pp_key_data k d (snd p), return (fst p ++ pkd, ff)),
return $ group $ to_fmt "⟨" ++ nest 1 fmt ++ to_fmt "⟩"⟩
end
end rb_map
namespace rb_lmap
/-- Construct a rb_lmap from a list of key-data pairs -/
protected meta def of_list {key : Type} {data : Type} [has_lt key]
[decidable_rel ((<) : key → key → Prop)] : list (key × data) → rb_lmap key data
| [] := rb_lmap.mk key data
| ((k, v)::ls) := (of_list ls).insert k v
end rb_lmap
end native
namespace name_set
meta def filter (P : name → bool) (s : name_set) : name_set :=
s.fold s (λ a m, if P a then m else m.erase a)
meta def mfilter {m} [monad m] (P : name → m bool) (s : name_set) : m name_set :=
s.fold (pure s) (λ a m,
do x ← m,
mcond (P a) (pure x) (pure $ x.erase a))
meta def mmap {m} [monad m] (f : name → m name) (s : name_set) : m name_set :=
s.fold (pure mk_name_set) (λ a m,
do x ← m,
b ← f a,
(pure $ x.insert b))
meta def union (s t : name_set) : name_set :=
s.fold t (λ a t, t.insert a)
end name_set
|
61e4609478c9e41c7554e35a81ab0401711c3ca3 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/ring_theory/graded_algebra/basic.lean | ae34e467f49e6b9c60ee0631613eaa77c13a3f55 | [
"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 | 9,707 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser, Kevin Buzzard, Jujian Zhang
-/
import algebra.direct_sum.algebra
import algebra.direct_sum.decomposition
import algebra.direct_sum.internal
import algebra.direct_sum.ring
import group_theory.subgroup.basic
/-!
# Internally-graded rings and algebras
This file defines the typeclass `graded_algebra 𝒜`, for working with an algebra `A` that is
internally graded by a collection of submodules `𝒜 : ι → submodule R A`.
See the docstring of that typeclass for more information.
## Main definitions
* `graded_ring 𝒜`: the typeclass, which is a combination of `set_like.graded_monoid`, and
`direct_sum.decomposition 𝒜`.
* `graded_algebra 𝒜`: A convenience alias for `graded_ring` when `𝒜` is a family of submodules.
* `direct_sum.decompose_ring_equiv 𝒜 : A ≃ₐ[R] ⨁ i, 𝒜 i`, a more bundled version of
`direct_sum.decompose 𝒜`.
* `direct_sum.decompose_alg_equiv 𝒜 : A ≃ₐ[R] ⨁ i, 𝒜 i`, a more bundled version of
`direct_sum.decompose 𝒜`.
* `graded_algebra.proj 𝒜 i` is the linear map from `A` to its degree `i : ι` component, such that
`proj 𝒜 i x = decompose 𝒜 x i`.
## Implementation notes
For now, we do not have internally-graded semirings and internally-graded rings; these can be
represented with `𝒜 : ι → submodule ℕ A` and `𝒜 : ι → submodule ℤ A` respectively, since all
`semiring`s are ℕ-algebras via `algebra_nat`, and all `ring`s are `ℤ`-algebras via `algebra_int`.
## Tags
graded algebra, graded ring, graded semiring, decomposition
-/
open_locale direct_sum big_operators
variables {ι R A σ : Type*}
section graded_ring
variables [decidable_eq ι] [add_monoid ι] [comm_semiring R] [semiring A] [algebra R A]
variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ)
include A
open direct_sum
/-- An internally-graded `R`-algebra `A` is one that can be decomposed into a collection
of `submodule R A`s indexed by `ι` such that the canonical map `A → ⨁ i, 𝒜 i` is bijective and
respects multiplication, i.e. the product of an element of degree `i` and an element of degree `j`
is an element of degree `i + j`.
Note that the fact that `A` is internally-graded, `graded_algebra 𝒜`, implies an externally-graded
algebra structure `direct_sum.galgebra R (λ i, ↥(𝒜 i))`, which in turn makes available an
`algebra R (⨁ i, 𝒜 i)` instance.
-/
class graded_ring (𝒜 : ι → σ) extends set_like.graded_monoid 𝒜, direct_sum.decomposition 𝒜.
variables [graded_ring 𝒜]
namespace direct_sum
/-- If `A` is graded by `ι` with degree `i` component `𝒜 i`, then it is isomorphic as
a ring to a direct sum of components. -/
def decompose_ring_equiv : A ≃+* ⨁ i, 𝒜 i := ring_equiv.symm
{ map_mul' := (coe_ring_hom 𝒜).map_mul,
map_add' := (coe_ring_hom 𝒜).map_add,
..(decompose_add_equiv 𝒜).symm }
@[simp] lemma decompose_one : decompose 𝒜 (1 : A) = 1 := map_one (decompose_ring_equiv 𝒜)
@[simp] lemma decompose_symm_one : (decompose 𝒜).symm 1 = (1 : A) :=
map_one (decompose_ring_equiv 𝒜).symm
@[simp] lemma decompose_mul (x y : A) : decompose 𝒜 (x * y) = decompose 𝒜 x * decompose 𝒜 y :=
map_mul (decompose_ring_equiv 𝒜) x y
@[simp] lemma decompose_symm_mul (x y : ⨁ i, 𝒜 i) :
(decompose 𝒜).symm (x * y) = (decompose 𝒜).symm x * (decompose 𝒜).symm y :=
map_mul (decompose_ring_equiv 𝒜).symm x y
end direct_sum
/-- The projection maps of a graded ring -/
def graded_ring.proj (i : ι) : A →+ A :=
(add_submonoid_class.subtype (𝒜 i)).comp $
(dfinsupp.eval_add_monoid_hom i).comp $
ring_hom.to_add_monoid_hom $ ring_equiv.to_ring_hom $ direct_sum.decompose_ring_equiv 𝒜
@[simp] lemma graded_ring.proj_apply (i : ι) (r : A) :
graded_ring.proj 𝒜 i r = (decompose 𝒜 r : ⨁ i, 𝒜 i) i := rfl
lemma graded_ring.proj_recompose (a : ⨁ i, 𝒜 i) (i : ι) :
graded_ring.proj 𝒜 i ((decompose 𝒜).symm a) =
(decompose 𝒜).symm (direct_sum.of _ i (a i)) :=
by rw [graded_ring.proj_apply, decompose_symm_of, equiv.apply_symm_apply]
lemma graded_ring.mem_support_iff [Π i (x : 𝒜 i), decidable (x ≠ 0)] (r : A) (i : ι) :
i ∈ (decompose 𝒜 r).support ↔ graded_ring.proj 𝒜 i r ≠ 0 :=
dfinsupp.mem_support_iff.trans add_submonoid_class.coe_eq_zero.not.symm
end graded_ring
section graded_algebra
variables [decidable_eq ι] [add_monoid ι] [comm_semiring R] [semiring A] [algebra R A]
variables (𝒜 : ι → submodule R A)
/-- A special case of `graded_ring` with `σ = submodule R A`. This is useful both because it
can avoid typeclass search, and because it provides a more concise name. -/
@[reducible]
def graded_algebra := graded_ring 𝒜
/-- A helper to construct a `graded_algebra` when the `set_like.graded_monoid` structure is already
available. This makes the `left_inv` condition easier to prove, and phrases the `right_inv`
condition in a way that allows custom `@[ext]` lemmas to apply.
See note [reducible non-instances]. -/
@[reducible]
def graded_algebra.of_alg_hom [set_like.graded_monoid 𝒜] (decompose : A →ₐ[R] ⨁ i, 𝒜 i)
(right_inv : (direct_sum.coe_alg_hom 𝒜).comp decompose = alg_hom.id R A)
(left_inv : ∀ i (x : 𝒜 i), decompose (x : A) = direct_sum.of (λ i, ↥(𝒜 i)) i x) :
graded_algebra 𝒜 :=
{ decompose' := decompose,
left_inv := alg_hom.congr_fun right_inv,
right_inv := begin
suffices : decompose.comp (direct_sum.coe_alg_hom 𝒜) = alg_hom.id _ _,
from alg_hom.congr_fun this,
ext i x : 2,
exact (decompose.congr_arg $ direct_sum.coe_alg_hom_of _ _ _).trans (left_inv i x),
end}
variable [graded_algebra 𝒜]
namespace direct_sum
/-- If `A` is graded by `ι` with degree `i` component `𝒜 i`, then it is isomorphic as
an algebra to a direct sum of components. -/
@[simps]
def decompose_alg_equiv : A ≃ₐ[R] ⨁ i, 𝒜 i := alg_equiv.symm
{ map_mul' := (coe_alg_hom 𝒜).map_mul,
map_add' := (coe_alg_hom 𝒜).map_add,
commutes' := (coe_alg_hom 𝒜).commutes,
..(decompose_add_equiv 𝒜).symm }
end direct_sum
open direct_sum
/-- The projection maps of graded algebra-/
def graded_algebra.proj (𝒜 : ι → submodule R A) [graded_algebra 𝒜] (i : ι) : A →ₗ[R] A :=
(𝒜 i).subtype.comp $
(dfinsupp.lapply i).comp $
(decompose_alg_equiv 𝒜).to_alg_hom.to_linear_map
@[simp] lemma graded_algebra.proj_apply (i : ι) (r : A) :
graded_algebra.proj 𝒜 i r = (decompose 𝒜 r : ⨁ i, 𝒜 i) i := rfl
lemma graded_algebra.proj_recompose (a : ⨁ i, 𝒜 i) (i : ι) :
graded_algebra.proj 𝒜 i ((decompose 𝒜).symm a) =
(decompose 𝒜).symm (of _ i (a i)) :=
by rw [graded_algebra.proj_apply, decompose_symm_of, equiv.apply_symm_apply]
lemma graded_algebra.mem_support_iff [decidable_eq A] (r : A) (i : ι) :
i ∈ (decompose 𝒜 r).support ↔ graded_algebra.proj 𝒜 i r ≠ 0 :=
dfinsupp.mem_support_iff.trans submodule.coe_eq_zero.not.symm
end graded_algebra
section canonical_order
open graded_ring set_like.graded_monoid direct_sum
variables [semiring A] [decidable_eq ι]
variables [canonically_ordered_add_monoid ι]
variables [set_like σ A] [add_submonoid_class σ A] (𝒜 : ι → σ) [graded_ring 𝒜]
/--
If `A` is graded by a canonically ordered add monoid, then the projection map `x ↦ x₀` is a ring
homomorphism.
-/
@[simps]
def graded_ring.proj_zero_ring_hom : A →+* A :=
{ to_fun := λ a, decompose 𝒜 a 0,
map_one' := decompose_of_mem_same 𝒜 one_mem,
map_zero' := by simp,
map_add' := λ _ _, by simp,
map_mul' := λ x y, begin
-- Convert the abstract add_submonoid into a concrete one. This is necessary as there is no
-- lattice structure on the abstract ones.
let 𝒜' : ι → add_submonoid A :=
λ i, (⟨𝒜 i, λ _ _, add_mem_class.add_mem, zero_mem_class.zero_mem _⟩ : add_submonoid A),
letI : graded_ring 𝒜' :=
{ decompose' := (direct_sum.decompose 𝒜 : A → ⨁ i, 𝒜 i),
left_inv := direct_sum.decomposition.left_inv,
right_inv := direct_sum.decomposition.right_inv,
..(by apply_instance : set_like.graded_monoid 𝒜), },
have m : ∀ x, x ∈ supr 𝒜',
{ intro x,
rw direct_sum.is_internal.add_submonoid_supr_eq_top 𝒜'
(direct_sum.decomposition.is_internal 𝒜'),
exact add_submonoid.mem_top x },
refine add_submonoid.supr_induction 𝒜' (m x) (λ i c hc, _) _ _,
{ refine add_submonoid.supr_induction 𝒜' (m y) (λ j c' hc', _) _ _,
{ by_cases h : i + j = 0,
{ rw [decompose_of_mem_same 𝒜 (show c * c' ∈ 𝒜 0, from h ▸ mul_mem hc hc'),
decompose_of_mem_same 𝒜 (show c ∈ 𝒜 0, from (add_eq_zero_iff.mp h).1 ▸ hc),
decompose_of_mem_same 𝒜 (show c' ∈ 𝒜 0, from (add_eq_zero_iff.mp h).2 ▸ hc')] },
{ rw [decompose_of_mem_ne 𝒜 (mul_mem hc hc') h],
cases (show i ≠ 0 ∨ j ≠ 0, by rwa [add_eq_zero_iff, not_and_distrib] at h) with h' h',
{ simp only [decompose_of_mem_ne 𝒜 hc h', zero_mul] },
{ simp only [decompose_of_mem_ne 𝒜 hc' h', mul_zero] } } },
{ simp only [decompose_zero, zero_apply, add_submonoid_class.coe_zero, mul_zero], },
{ intros _ _ hd he,
simp only [mul_add, decompose_add, add_apply, add_mem_class.coe_add, hd, he] } },
{ simp only [decompose_zero, zero_apply, add_submonoid_class.coe_zero, zero_mul] },
{ rintros _ _ ha hb,
simp only [add_mul, decompose_add, add_apply, add_mem_class.coe_add, ha, hb] },
end }
end canonical_order
|
376f5f02a3817b48f046994c1f5bb7ddc1b6e183 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/ring_theory/subsemiring/basic.lean | b39772122725f6f0908fdf148a9c482ed074b6e3 | [
"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 | 44,276 | lean | /-
Copyright (c) 2020 Yury Kudryashov All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import algebra.module.basic
import algebra.ring.equiv
import algebra.ring.prod
import data.set.finite
import group_theory.submonoid.centralizer
import group_theory.submonoid.membership
/-!
# Bundled subsemirings
We define bundled subsemirings and some standard constructions: `complete_lattice` structure,
`subtype` and `inclusion` ring homomorphisms, subsemiring `map`, `comap` and range (`srange`) of
a `ring_hom` etc.
-/
open_locale big_operators
universes u v w
section add_submonoid_with_one_class
/-- `add_submonoid_with_one_class S R` says `S` is a type of subsets `s ≤ R` that contain `0`, `1`,
and are closed under `(+)` -/
class add_submonoid_with_one_class (S : Type*) (R : out_param $ Type*)
[add_monoid_with_one R] [set_like S R]
extends add_submonoid_class S R, one_mem_class S R
variables {S R : Type*} [add_monoid_with_one R] [set_like S R] (s : S)
lemma nat_cast_mem [add_submonoid_with_one_class S R] (n : ℕ) : (n : R) ∈ s :=
by induction n; simp [zero_mem, add_mem, one_mem, *]
@[priority 74]
instance add_submonoid_with_one_class.to_add_monoid_with_one [add_submonoid_with_one_class S R] :
add_monoid_with_one s :=
{ one := ⟨_, one_mem s⟩,
nat_cast := λ n, ⟨n, nat_cast_mem s n⟩,
nat_cast_zero := subtype.ext nat.cast_zero,
nat_cast_succ := λ n, subtype.ext (nat.cast_succ _),
.. add_submonoid_class.to_add_monoid s }
end add_submonoid_with_one_class
variables {R : Type u} {S : Type v} {T : Type w} [non_assoc_semiring R] (M : submonoid R)
section subsemiring_class
/-- `subsemiring_class S R` states that `S` is a type of subsets `s ⊆ R` that
are both a multiplicative and an additive submonoid. -/
class subsemiring_class (S : Type*) (R : out_param $ Type u) [non_assoc_semiring R] [set_like S R]
extends submonoid_class S R :=
(add_mem : ∀ {s : S} {a b : R}, a ∈ s → b ∈ s → a + b ∈ s)
(zero_mem : ∀ (s : S), (0 : R) ∈ s)
@[priority 100] -- See note [lower instance priority]
instance subsemiring_class.add_submonoid_with_one_class (S : Type*) (R : out_param $ Type u)
[non_assoc_semiring R] [set_like S R] [h : subsemiring_class S R] :
add_submonoid_with_one_class S R :=
{ .. h }
variables [set_like S R] [hSR : subsemiring_class S R] (s : S)
include hSR
lemma coe_nat_mem (n : ℕ) : (n : R) ∈ s :=
by { rw ← nsmul_one, exact nsmul_mem (one_mem _) _ }
namespace subsemiring_class
/-- A subsemiring of a `non_assoc_semiring` inherits a `non_assoc_semiring` structure -/
@[priority 75] -- Prefer subclasses of `non_assoc_semiring` over subclasses of `subsemiring_class`.
instance to_non_assoc_semiring : non_assoc_semiring s :=
subtype.coe_injective.non_assoc_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
(λ _, rfl)
instance nontrivial [nontrivial R] : nontrivial s :=
nontrivial_of_ne 0 1 $ λ H, zero_ne_one (congr_arg subtype.val H)
instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y h,
or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ subtype.ext_iff.mp h)
(λ h, or.inl $ subtype.eq h) (λ h, or.inr $ subtype.eq h) }
/-- The natural ring hom from a subsemiring of semiring `R` to `R`. -/
def subtype : s →+* R :=
{ to_fun := coe, .. submonoid_class.subtype s, .. add_submonoid_class.subtype s }
@[simp] theorem coe_subtype : (subtype s : s → R) = coe := rfl
omit hSR
/-- A subsemiring of a `semiring` is a `semiring`. -/
@[priority 75] -- Prefer subclasses of `semiring` over subclasses of `subsemiring_class`.
instance to_semiring {R} [semiring R] [set_like S R] [subsemiring_class S R] : semiring s :=
subtype.coe_injective.semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
(λ _, rfl)
@[simp, norm_cast] lemma coe_pow {R} [semiring R] [set_like S R] [subsemiring_class S R]
(x : s) (n : ℕ) :
((x^n : s) : R) = (x^n : R) :=
begin
induction n with n ih,
{ simp, },
{ simp [pow_succ, ih], },
end
/-- A subsemiring of a `comm_semiring` is a `comm_semiring`. -/
instance to_comm_semiring {R} [comm_semiring R] [set_like S R] [subsemiring_class S R] :
comm_semiring s :=
subtype.coe_injective.comm_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
/-- A subsemiring of an `ordered_semiring` is an `ordered_semiring`. -/
instance to_ordered_semiring {R} [ordered_semiring R] [set_like S R] [subsemiring_class S R] :
ordered_semiring s :=
subtype.coe_injective.ordered_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
/-- A subsemiring of an `ordered_comm_semiring` is an `ordered_comm_semiring`. -/
instance to_ordered_comm_semiring {R} [ordered_comm_semiring R] [set_like S R]
[subsemiring_class S R] : ordered_comm_semiring s :=
subtype.coe_injective.ordered_comm_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
/-- A subsemiring of a `linear_ordered_semiring` is a `linear_ordered_semiring`. -/
instance to_linear_ordered_semiring {R} [linear_ordered_semiring R] [set_like S R]
[subsemiring_class S R] : linear_ordered_semiring s :=
subtype.coe_injective.linear_ordered_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
/-! Note: currently, there is no `linear_ordered_comm_semiring`. -/
end subsemiring_class
end subsemiring_class
variables [non_assoc_semiring S] [non_assoc_semiring T]
set_option old_structure_cmd true
/-- A subsemiring of a semiring `R` is a subset `s` that is both a multiplicative and an additive
submonoid. -/
structure subsemiring (R : Type u) [non_assoc_semiring R] extends submonoid R, add_submonoid R
/-- Reinterpret a `subsemiring` as a `submonoid`. -/
add_decl_doc subsemiring.to_submonoid
/-- Reinterpret a `subsemiring` as an `add_submonoid`. -/
add_decl_doc subsemiring.to_add_submonoid
namespace subsemiring
instance : set_like (subsemiring R) R :=
{ coe := subsemiring.carrier,
coe_injective' := λ p q h, by cases p; cases q; congr' }
instance : subsemiring_class (subsemiring R) R :=
{ zero_mem := zero_mem',
add_mem := add_mem',
one_mem := one_mem',
mul_mem := mul_mem' }
@[simp]
lemma mem_carrier {s : subsemiring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl
/-- Two subsemirings are equal if they have the same elements. -/
@[ext] theorem ext {S T : subsemiring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h
/-- Copy of a subsemiring with a new `carrier` equal to the old one. Useful to fix definitional
equalities.-/
protected def copy (S : subsemiring R) (s : set R) (hs : s = ↑S) : subsemiring R :=
{ carrier := s,
..S.to_add_submonoid.copy s hs,
..S.to_submonoid.copy s hs }
@[simp] lemma coe_copy (S : subsemiring R) (s : set R) (hs : s = ↑S) :
(S.copy s hs : set R) = s := rfl
lemma copy_eq (S : subsemiring R) (s : set R) (hs : s = ↑S) : S.copy s hs = S :=
set_like.coe_injective hs
lemma to_submonoid_injective : function.injective (to_submonoid : subsemiring R → submonoid R)
| r s h := ext (set_like.ext_iff.mp h : _)
@[mono] lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subsemiring R → submonoid R) :=
λ _ _, id
@[mono] lemma to_submonoid_mono : monotone (to_submonoid : subsemiring R → submonoid R) :=
to_submonoid_strict_mono.monotone
lemma to_add_submonoid_injective :
function.injective (to_add_submonoid : subsemiring R → add_submonoid R)
| r s h := ext (set_like.ext_iff.mp h : _)
@[mono] lemma to_add_submonoid_strict_mono :
strict_mono (to_add_submonoid : subsemiring R → add_submonoid R) := λ _ _, id
@[mono]
lemma to_add_submonoid_mono : monotone (to_add_submonoid : subsemiring R → add_submonoid R) :=
to_add_submonoid_strict_mono.monotone
/-- Construct a `subsemiring R` from a set `s`, a submonoid `sm`, and an additive
submonoid `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/
protected def mk' (s : set R) (sm : submonoid R) (hm : ↑sm = s)
(sa : add_submonoid R) (ha : ↑sa = s) :
subsemiring R :=
{ carrier := s,
zero_mem' := ha ▸ sa.zero_mem,
one_mem' := hm ▸ sm.one_mem,
add_mem' := λ x y, by simpa only [← ha] using sa.add_mem,
mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem }
@[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_submonoid R} (ha : ↑sa = s) :
(subsemiring.mk' s sm hm sa ha : set R) = s := rfl
@[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_submonoid R} (ha : ↑sa = s) {x : R} :
x ∈ subsemiring.mk' s sm hm sa ha ↔ x ∈ s :=
iff.rfl
@[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_submonoid R} (ha : ↑sa = s) :
(subsemiring.mk' s sm hm sa ha).to_submonoid = sm :=
set_like.coe_injective hm.symm
@[simp] lemma mk'_to_add_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s)
{sa : add_submonoid R} (ha : ↑sa =s) :
(subsemiring.mk' s sm hm sa ha).to_add_submonoid = sa :=
set_like.coe_injective ha.symm
end subsemiring
namespace subsemiring
variables (s : subsemiring R)
/-- A subsemiring contains the semiring's 1. -/
protected theorem one_mem : (1 : R) ∈ s := one_mem s
/-- A subsemiring contains the semiring's 0. -/
protected theorem zero_mem : (0 : R) ∈ s := zero_mem s
/-- A subsemiring is closed under multiplication. -/
protected theorem mul_mem {x y : R} : x ∈ s → y ∈ s → x * y ∈ s := mul_mem
/-- A subsemiring is closed under addition. -/
protected theorem add_mem {x y : R} : x ∈ s → y ∈ s → x + y ∈ s := add_mem
/-- Product of a list of elements in a `subsemiring` is in the `subsemiring`. -/
lemma list_prod_mem {R : Type*} [semiring R] (s : subsemiring R) {l : list R} :
(∀x ∈ l, x ∈ s) → l.prod ∈ s :=
list_prod_mem
/-- Sum of a list of elements in a `subsemiring` is in the `subsemiring`. -/
protected lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s := list_sum_mem
/-- Product of a multiset of elements in a `subsemiring` of a `comm_semiring`
is in the `subsemiring`. -/
protected lemma multiset_prod_mem {R} [comm_semiring R] (s : subsemiring R) (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.prod ∈ s :=
multiset_prod_mem m
/-- Sum of a multiset of elements in a `subsemiring` of a `semiring` is
in the `add_subsemiring`. -/
protected lemma multiset_sum_mem (m : multiset R) :
(∀a ∈ m, a ∈ s) → m.sum ∈ s :=
multiset_sum_mem m
/-- Product of elements of a subsemiring of a `comm_semiring` indexed by a `finset` is in the
subsemiring. -/
protected lemma prod_mem {R : Type*} [comm_semiring R] (s : subsemiring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∏ i in t, f i ∈ s :=
prod_mem h
/-- Sum of elements in an `subsemiring` of an `semiring` indexed by a `finset`
is in the `add_subsemiring`. -/
protected lemma sum_mem (s : subsemiring R)
{ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) :
∑ i in t, f i ∈ s :=
sum_mem h
/-- A subsemiring of a `non_assoc_semiring` inherits a `non_assoc_semiring` structure -/
instance to_non_assoc_semiring : non_assoc_semiring s :=
{ mul_zero := λ x, subtype.eq $ mul_zero x,
zero_mul := λ x, subtype.eq $ zero_mul x,
right_distrib := λ x y z, subtype.eq $ right_distrib x y z,
left_distrib := λ x y z, subtype.eq $ left_distrib x y z,
nat_cast := λ n, ⟨n, coe_nat_mem s n⟩,
nat_cast_zero := by simp [nat.cast]; refl,
nat_cast_succ := λ _, by simp [nat.cast]; refl,
.. s.to_submonoid.to_mul_one_class, .. s.to_add_submonoid.to_add_comm_monoid }
@[simp, norm_cast] lemma coe_one : ((1 : s) : R) = (1 : R) := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = (0 : R) := rfl
@[simp, norm_cast] lemma coe_add (x y : s) : ((x + y : s) : R) = (x + y : R) := rfl
@[simp, norm_cast] lemma coe_mul (x y : s) : ((x * y : s) : R) = (x * y : R) := rfl
instance nontrivial [nontrivial R] : nontrivial s :=
nontrivial_of_ne 0 1 $ λ H, zero_ne_one (congr_arg subtype.val H)
protected lemma pow_mem {R : Type*} [semiring R] (s : subsemiring R) {x : R} (hx : x ∈ s) (n : ℕ) :
x^n ∈ s := pow_mem hx n
instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y h,
or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ subtype.ext_iff.mp h)
(λ h, or.inl $ subtype.eq h) (λ h, or.inr $ subtype.eq h) }
/-- A subsemiring of a `semiring` is a `semiring`. -/
instance to_semiring {R} [semiring R] (s : subsemiring R) : semiring s :=
{ ..s.to_non_assoc_semiring, ..s.to_submonoid.to_monoid }
@[simp, norm_cast] lemma coe_pow {R} [semiring R] (s : subsemiring R) (x : s) (n : ℕ) :
((x^n : s) : R) = (x^n : R) :=
begin
induction n with n ih,
{ simp, },
{ simp [pow_succ, ih], },
end
/-- A subsemiring of a `comm_semiring` is a `comm_semiring`. -/
instance to_comm_semiring {R} [comm_semiring R] (s : subsemiring R) : comm_semiring s :=
{ mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..s.to_semiring}
/-- The natural ring hom from a subsemiring of semiring `R` to `R`. -/
def subtype : s →+* R :=
{ to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_submonoid.subtype }
@[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl
/-- A subsemiring of an `ordered_semiring` is an `ordered_semiring`. -/
instance to_ordered_semiring {R} [ordered_semiring R] (s : subsemiring R) : ordered_semiring s :=
subtype.coe_injective.ordered_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
/-- A subsemiring of an `ordered_comm_semiring` is an `ordered_comm_semiring`. -/
instance to_ordered_comm_semiring {R} [ordered_comm_semiring R] (s : subsemiring R) :
ordered_comm_semiring s :=
subtype.coe_injective.ordered_comm_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl)
/-- A subsemiring of a `linear_ordered_semiring` is a `linear_ordered_semiring`. -/
instance to_linear_ordered_semiring {R} [linear_ordered_semiring R] (s : subsemiring R) :
linear_ordered_semiring s :=
subtype.coe_injective.linear_ordered_semiring coe
rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl)
/-! Note: currently, there is no `linear_ordered_comm_semiring`. -/
protected lemma nsmul_mem {x : R} (hx : x ∈ s) (n : ℕ) :
n • x ∈ s := nsmul_mem hx n
@[simp] lemma mem_to_submonoid {s : subsemiring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_submonoid (s : subsemiring R) : (s.to_submonoid : set R) = s := rfl
@[simp] lemma mem_to_add_submonoid {s : subsemiring R} {x : R} :
x ∈ s.to_add_submonoid ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_add_submonoid (s : subsemiring R) : (s.to_add_submonoid : set R) = s := rfl
/-- The subsemiring `R` of the semiring `R`. -/
instance : has_top (subsemiring R) :=
⟨{ .. (⊤ : submonoid R), .. (⊤ : add_submonoid R) }⟩
@[simp] lemma mem_top (x : R) : x ∈ (⊤ : subsemiring R) := set.mem_univ x
@[simp] lemma coe_top : ((⊤ : subsemiring R) : set R) = set.univ := rfl
/-- The preimage of a subsemiring along a ring homomorphism is a subsemiring. -/
def comap (f : R →+* S) (s : subsemiring S) : subsemiring R :=
{ carrier := f ⁻¹' s,
.. s.to_submonoid.comap (f : R →* S), .. s.to_add_submonoid.comap (f : R →+ S) }
@[simp] lemma coe_comap (s : subsemiring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl
@[simp]
lemma mem_comap {s : subsemiring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl
lemma comap_comap (s : subsemiring T) (g : S →+* T) (f : R →+* S) :
(s.comap g).comap f = s.comap (g.comp f) :=
rfl
/-- The image of a subsemiring along a ring homomorphism is a subsemiring. -/
def map (f : R →+* S) (s : subsemiring R) : subsemiring S :=
{ carrier := f '' s,
.. s.to_submonoid.map (f : R →* S), .. s.to_add_submonoid.map (f : R →+ S) }
@[simp] lemma coe_map (f : R →+* S) (s : subsemiring R) : (s.map f : set S) = f '' s := rfl
@[simp] lemma mem_map {f : R →+* S} {s : subsemiring R} {y : S} :
y ∈ s.map f ↔ ∃ x ∈ s, f x = y :=
set.mem_image_iff_bex
@[simp] lemma map_id : s.map (ring_hom.id R) = s :=
set_like.coe_injective $ set.image_id _
lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) :=
set_like.coe_injective $ set.image_image _ _ _
lemma map_le_iff_le_comap {f : R →+* S} {s : subsemiring R} {t : subsemiring S} :
s.map f ≤ t ↔ s ≤ t.comap f :=
set.image_subset_iff
lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) :=
λ S T, map_le_iff_le_comap
/-- A subsemiring is isomorphic to its image under an injective function -/
noncomputable def equiv_map_of_injective
(f : R →+* S) (hf : function.injective f) : s ≃+* s.map f :=
{ map_mul' := λ _ _, subtype.ext (f.map_mul _ _),
map_add' := λ _ _, subtype.ext (f.map_add _ _),
..equiv.set.image f s hf }
@[simp] lemma coe_equiv_map_of_injective_apply
(f : R →+* S) (hf : function.injective f) (x : s) :
(equiv_map_of_injective s f hf x : S) = f x := rfl
end subsemiring
namespace ring_hom
variables (g : S →+* T) (f : R →+* S)
/-- The range of a ring homomorphism is a subsemiring. See Note [range copy pattern]. -/
def srange : subsemiring S :=
((⊤ : subsemiring R).map f).copy (set.range f) set.image_univ.symm
@[simp] lemma coe_srange : (f.srange : set S) = set.range f := rfl
@[simp] lemma mem_srange {f : R →+* S} {y : S} : y ∈ f.srange ↔ ∃ x, f x = y :=
iff.rfl
lemma srange_eq_map (f : R →+* S) : f.srange = (⊤ : subsemiring R).map f :=
by { ext, simp }
lemma mem_srange_self (f : R →+* S) (x : R) : f x ∈ f.srange :=
mem_srange.mpr ⟨x, rfl⟩
lemma map_srange : f.srange.map g = (g.comp f).srange :=
by simpa only [srange_eq_map] using (⊤ : subsemiring R).map_map g f
/-- The range of a morphism of semirings is a fintype, if the domain is a fintype.
Note: this instance can form a diamond with `subtype.fintype` in the
presence of `fintype S`.-/
instance fintype_srange [fintype R] [decidable_eq S] (f : R →+* S) : fintype (srange f) :=
set.fintype_range f
end ring_hom
namespace subsemiring
instance : has_bot (subsemiring R) := ⟨(nat.cast_ring_hom R).srange⟩
instance : inhabited (subsemiring R) := ⟨⊥⟩
lemma coe_bot : ((⊥ : subsemiring R) : set R) = set.range (coe : ℕ → R) :=
(nat.cast_ring_hom R).coe_srange
lemma mem_bot {x : R} : x ∈ (⊥ : subsemiring R) ↔ ∃ n : ℕ, ↑n=x := ring_hom.mem_srange
/-- The inf of two subsemirings is their intersection. -/
instance : has_inf (subsemiring R) :=
⟨λ s t,
{ carrier := s ∩ t,
.. s.to_submonoid ⊓ t.to_submonoid,
.. s.to_add_submonoid ⊓ t.to_add_submonoid }⟩
@[simp] lemma coe_inf (p p' : subsemiring R) : ((p ⊓ p' : subsemiring R) : set R) = p ∩ p' := rfl
@[simp] lemma mem_inf {p p' : subsemiring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
instance : has_Inf (subsemiring R) :=
⟨λ s, subsemiring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subsemiring.to_submonoid t) (by simp)
(⨅ t ∈ s, subsemiring.to_add_submonoid t) (by simp)⟩
@[simp, norm_cast] lemma coe_Inf (S : set (subsemiring R)) :
((Inf S : subsemiring R) : set R) = ⋂ s ∈ S, ↑s := rfl
lemma mem_Inf {S : set (subsemiring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂
@[simp] lemma Inf_to_submonoid (s : set (subsemiring R)) :
(Inf s).to_submonoid = ⨅ t ∈ s, subsemiring.to_submonoid t :=
mk'_to_submonoid _ _
@[simp] lemma Inf_to_add_submonoid (s : set (subsemiring R)) :
(Inf s).to_add_submonoid = ⨅ t ∈ s, subsemiring.to_add_submonoid t :=
mk'_to_add_submonoid _ _
/-- Subsemirings of a semiring form a complete lattice. -/
instance : complete_lattice (subsemiring R) :=
{ bot := (⊥),
bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ coe_nat_mem s n,
top := (⊤),
le_top := λ s x hx, trivial,
inf := (⊓),
inf_le_left := λ s t x, and.left,
inf_le_right := λ s t x, and.right,
le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩,
.. complete_lattice_of_Inf (subsemiring R)
(λ s, is_glb.of_image (λ s t,
show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)}
lemma eq_top_iff' (A : subsemiring R) : A = ⊤ ↔ ∀ x : R, x ∈ A :=
eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩
section center
/-- The center of a semiring `R` is the set of elements that commute with everything in `R` -/
def center (R) [semiring R] : subsemiring R :=
{ carrier := set.center R,
zero_mem' := set.zero_mem_center R,
add_mem' := λ a b, set.add_mem_center,
.. submonoid.center R }
lemma coe_center (R) [semiring R] : ↑(center R) = set.center R := rfl
@[simp]
lemma center_to_submonoid (R) [semiring R] : (center R).to_submonoid = submonoid.center R := rfl
lemma mem_center_iff {R} [semiring R] {z : R} : z ∈ center R ↔ ∀ g, g * z = z * g :=
iff.rfl
instance decidable_mem_center {R} [semiring R] [decidable_eq R] [fintype R] :
decidable_pred (∈ center R) :=
λ _, decidable_of_iff' _ mem_center_iff
@[simp] lemma center_eq_top (R) [comm_semiring R] : center R = ⊤ :=
set_like.coe_injective (set.center_eq_univ R)
/-- The center is commutative. -/
instance {R} [semiring R] : comm_semiring (center R) :=
{ ..submonoid.center.comm_monoid,
..(center R).to_semiring}
end center
section centralizer
/-- The centralizer of a set as subsemiring. -/
def centralizer {R} [semiring R] (s : set R) : subsemiring R :=
{ carrier := s.centralizer,
zero_mem' := set.zero_mem_centralizer _,
add_mem' := λ x y hx hy, set.add_mem_centralizer hx hy,
..submonoid.centralizer s }
@[simp, norm_cast]
lemma coe_centralizer {R} [semiring R] (s : set R) : (centralizer s : set R) = s.centralizer := rfl
lemma centralizer_to_submonoid {R} [semiring R] (s : set R) :
(centralizer s).to_submonoid = submonoid.centralizer s := rfl
lemma mem_centralizer_iff {R} [semiring R] {s : set R} {z : R} :
z ∈ centralizer s ↔ ∀ g ∈ s, g * z = z * g :=
iff.rfl
lemma centralizer_le {R} [semiring R] (s t : set R) (h : s ⊆ t) :
centralizer t ≤ centralizer s :=
set.centralizer_subset h
@[simp]
lemma centralizer_univ {R} [semiring R] : centralizer set.univ = center R :=
set_like.ext' (set.centralizer_univ R)
end centralizer
/-- The `subsemiring` generated by a set. -/
def closure (s : set R) : subsemiring R := Inf {S | s ⊆ S}
lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subsemiring R, s ⊆ S → x ∈ S :=
mem_Inf
/-- The subsemiring generated by a set includes the set. -/
@[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx
lemma not_mem_of_not_mem_closure {s : set R} {P : R} (hP : P ∉ closure s) : P ∉ s :=
λ h, hP (subset_closure h)
/-- A subsemiring `S` includes `closure s` if and only if it includes `s`. -/
@[simp]
lemma closure_le {s : set R} {t : subsemiring R} : closure s ≤ t ↔ s ⊆ t :=
⟨set.subset.trans subset_closure, λ h, Inf_le h⟩
/-- Subsemiring closure of a set is monotone in its argument: if `s ⊆ t`,
then `closure s ≤ closure t`. -/
lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t :=
closure_le.2 $ set.subset.trans h subset_closure
lemma closure_eq_of_le {s : set R} {t : subsemiring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) :
closure s = t :=
le_antisymm (closure_le.2 h₁) h₂
lemma mem_map_equiv {f : R ≃+* S} {K : subsemiring R} {x : S} :
x ∈ K.map (f : R →+* S) ↔ f.symm x ∈ K :=
@set.mem_image_equiv _ _ ↑K f.to_equiv x
lemma map_equiv_eq_comap_symm (f : R ≃+* S) (K : subsemiring R) :
K.map (f : R →+* S) = K.comap f.symm :=
set_like.coe_injective (f.to_equiv.image_eq_preimage K)
lemma comap_equiv_eq_map_symm (f : R ≃+* S) (K : subsemiring S) :
K.comap (f : R →+* S) = K.map f.symm :=
(map_equiv_eq_comap_symm f.symm K).symm
end subsemiring
namespace submonoid
/-- The additive closure of a submonoid is a subsemiring. -/
def subsemiring_closure (M : submonoid R) : subsemiring R :=
{ one_mem' := add_submonoid.mem_closure.mpr (λ y hy, hy M.one_mem),
mul_mem' := λ x y, mul_mem_class.mul_mem_add_closure,
..add_submonoid.closure (M : set R)}
lemma subsemiring_closure_coe :
(M.subsemiring_closure : set R) = add_submonoid.closure (M : set R) := rfl
lemma subsemiring_closure_to_add_submonoid :
M.subsemiring_closure.to_add_submonoid = add_submonoid.closure (M : set R) := rfl
/-- The `subsemiring` generated by a multiplicative submonoid coincides with the
`subsemiring.closure` of the submonoid itself . -/
lemma subsemiring_closure_eq_closure : M.subsemiring_closure = subsemiring.closure (M : set R) :=
begin
ext,
refine ⟨λ hx, _, λ hx, (subsemiring.mem_closure.mp hx) M.subsemiring_closure (λ s sM, _)⟩;
rintros - ⟨H1, rfl⟩;
rintros - ⟨H2, rfl⟩,
{ exact add_submonoid.mem_closure.mp hx H1.to_add_submonoid H2 },
{ exact H2 sM }
end
end submonoid
namespace subsemiring
@[simp]
lemma closure_submonoid_closure (s : set R) : closure ↑(submonoid.closure s) = closure s :=
le_antisymm
(closure_le.mpr (λ y hy, (submonoid.mem_closure.mp hy) (closure s).to_submonoid subset_closure))
(closure_mono (submonoid.subset_closure))
/-- The elements of the subsemiring closure of `M` are exactly the elements of the additive closure
of a multiplicative submonoid `M`. -/
lemma coe_closure_eq (s : set R) :
(closure s : set R) = add_submonoid.closure (submonoid.closure s : set R) :=
by simp [← submonoid.subsemiring_closure_to_add_submonoid, submonoid.subsemiring_closure_eq_closure]
lemma mem_closure_iff {s : set R} {x} :
x ∈ closure s ↔ x ∈ add_submonoid.closure (submonoid.closure s : set R) :=
set.ext_iff.mp (coe_closure_eq s) x
@[simp]
lemma closure_add_submonoid_closure {s : set R} : closure ↑(add_submonoid.closure s) = closure s :=
begin
ext x,
refine ⟨λ hx, _, λ hx, closure_mono add_submonoid.subset_closure hx⟩,
rintros - ⟨H, rfl⟩,
rintros - ⟨J, rfl⟩,
refine (add_submonoid.mem_closure.mp (mem_closure_iff.mp hx)) H.to_add_submonoid (λ y hy, _),
refine (submonoid.mem_closure.mp hy) H.to_submonoid (λ z hz, _),
exact (add_submonoid.mem_closure.mp hz) H.to_add_submonoid (λ w hw, J hw),
end
/-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements
of `s`, and is preserved under addition and multiplication, then `p` holds for all elements
of the closure of `s`. -/
@[elab_as_eliminator]
lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1)
(Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
(@closure_le _ _ _ ⟨p, Hmul, H1, Hadd, H0⟩).2 Hs h
/-- An induction principle for closure membership for predicates with two arguments. -/
@[elab_as_eliminator]
lemma closure_induction₂ {s : set R} {p : R → R → Prop} {x} {y : R} (hx : x ∈ closure s)
(hy : y ∈ closure s)
(Hs : ∀ (x ∈ s) (y ∈ s), p x y)
(H0_left : ∀ x, p 0 x)
(H0_right : ∀ x, p x 0)
(H1_left : ∀ x, p 1 x)
(H1_right : ∀ x, p x 1)
(Hadd_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ + x₂) y)
(Hadd_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ + y₂))
(Hmul_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ * x₂) y)
(Hmul_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ * y₂))
: p x y :=
closure_induction hx
(λ x₁ x₁s, closure_induction hy (Hs x₁ x₁s) (H0_right x₁) (H1_right x₁) (Hadd_right x₁)
(Hmul_right x₁))
(H0_left y) (H1_left y) (λ z z', Hadd_left z z' y) (λ z z', Hmul_left z z' y)
lemma mem_closure_iff_exists_list {R} [semiring R] {s : set R} {x} : x ∈ closure s ↔
∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s) ∧ (L.map list.prod).sum = x :=
⟨λ hx, add_submonoid.closure_induction (mem_closure_iff.1 hx)
(λ x hx, suffices ∃ t : list R, (∀ y ∈ t, y ∈ s) ∧ t.prod = x,
from let ⟨t, ht1, ht2⟩ := this in ⟨[t], list.forall_mem_singleton.2 ht1,
by rw [list.map_singleton, list.sum_singleton, ht2]⟩,
submonoid.closure_induction hx
(λ x hx, ⟨[x], list.forall_mem_singleton.2 hx, one_mul x⟩)
⟨[], list.forall_mem_nil _, rfl⟩
(λ x y ⟨t, ht1, ht2⟩ ⟨u, hu1, hu2⟩, ⟨t ++ u, list.forall_mem_append.2 ⟨ht1, hu1⟩,
by rw [list.prod_append, ht2, hu2]⟩))
⟨[], list.forall_mem_nil _, rfl⟩
(λ x y ⟨L, HL1, HL2⟩ ⟨M, HM1, HM2⟩, ⟨L ++ M, list.forall_mem_append.2 ⟨HL1, HM1⟩,
by rw [list.map_append, list.sum_append, HL2, HM2]⟩),
λ ⟨L, HL1, HL2⟩, HL2 ▸ list_sum_mem (λ r hr, let ⟨t, ht1, ht2⟩ := list.mem_map.1 hr in
ht2 ▸ list_prod_mem _ (λ y hy, subset_closure $ HL1 t ht1 y hy))⟩
variable (R)
/-- `closure` forms a Galois insertion with the coercion to set. -/
protected def gi : galois_insertion (@closure R _) coe :=
{ choice := λ s _, closure s,
gc := λ s t, closure_le,
le_l_u := λ s, subset_closure,
choice_eq := λ s h, rfl }
variable {R}
/-- Closure of a subsemiring `S` equals `S`. -/
lemma closure_eq (s : subsemiring R) : closure (s : set R) = s := (subsemiring.gi R).l_u_eq s
@[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subsemiring.gi R).gc.l_bot
@[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤
lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t :=
(subsemiring.gi R).gc.l_sup
lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) :=
(subsemiring.gi R).gc.l_supr
lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t :=
(subsemiring.gi R).gc.l_Sup
lemma map_sup (s t : subsemiring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f :=
(gc_map_comap f).l_sup
lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subsemiring R) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f).l_supr
lemma comap_inf (s t : subsemiring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f :=
(gc_map_comap f).u_inf
lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subsemiring S) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f).u_infi
@[simp] lemma map_bot (f : R →+* S) : (⊥ : subsemiring R).map f = ⊥ :=
(gc_map_comap f).l_bot
@[simp] lemma comap_top (f : R →+* S) : (⊤ : subsemiring S).comap f = ⊤ :=
(gc_map_comap f).u_top
/-- Given `subsemiring`s `s`, `t` of semirings `R`, `S` respectively, `s.prod t` is `s × t`
as a subsemiring of `R × S`. -/
def prod (s : subsemiring R) (t : subsemiring S) : subsemiring (R × S) :=
{ carrier := (s : set R) ×ˢ (t : set S),
.. s.to_submonoid.prod t.to_submonoid, .. s.to_add_submonoid.prod t.to_add_submonoid}
@[norm_cast]
lemma coe_prod (s : subsemiring R) (t : subsemiring S) :
(s.prod t : set (R × S)) = (s : set R) ×ˢ (t : set S) :=
rfl
lemma mem_prod {s : subsemiring R} {t : subsemiring S} {p : R × S} :
p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl
@[mono] lemma prod_mono ⦃s₁ s₂ : subsemiring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subsemiring S⦄
(ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ :=
set.prod_mono hs ht
lemma prod_mono_right (s : subsemiring R) : monotone (λ t : subsemiring S, s.prod t) :=
prod_mono (le_refl s)
lemma prod_mono_left (t : subsemiring S) : monotone (λ s : subsemiring R, s.prod t) :=
λ s₁ s₂ hs, prod_mono hs (le_refl t)
lemma prod_top (s : subsemiring R) :
s.prod (⊤ : subsemiring S) = s.comap (ring_hom.fst R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst]
lemma top_prod (s : subsemiring S) :
(⊤ : subsemiring R).prod s = s.comap (ring_hom.snd R S) :=
ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd]
@[simp]
lemma top_prod_top : (⊤ : subsemiring R).prod (⊤ : subsemiring S) = ⊤ :=
(top_prod _).trans $ comap_top _
/-- Product of subsemirings is isomorphic to their product as monoids. -/
def prod_equiv (s : subsemiring R) (t : subsemiring S) : s.prod t ≃+* s × t :=
{ map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t }
lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S)
{x : R} :
x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩,
let U : subsemiring R := subsemiring.mk' (⋃ i, (S i : set R))
(⨆ i, (S i).to_submonoid) (submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id))
(⨆ i, (S i).to_add_submonoid) (add_submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)),
suffices : (⨆ i, S i) ≤ U, by simpa using @this x,
exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩),
end
lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S) :
((⨆ i, S i : subsemiring R) : set R) = ⋃ i, ↑(S i) :=
set.ext $ λ x, by simp [mem_supr_of_directed hS]
lemma mem_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty)
(hS : directed_on (≤) S) {x : R} :
x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s :=
begin
haveI : nonempty S := Sne.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk]
end
lemma coe_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) :
(↑(Sup S) : set R) = ⋃ s ∈ S, ↑s :=
set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS]
end subsemiring
namespace ring_hom
variables [non_assoc_semiring T] {s : subsemiring R}
variables {σR σS : Type*}
variables [set_like σR R] [set_like σS S] [subsemiring_class σR R] [subsemiring_class σS S]
open subsemiring
/-- Restriction of a ring homomorphism to a subsemiring of the domain. -/
def restrict (f : R →+* S) (s : σR) : s →+* S := f.comp $ subsemiring_class.subtype s
@[simp] lemma restrict_apply (f : R →+* S) {s : σR} (x : s) : f.restrict s x = f x := rfl
/-- Restriction of a ring homomorphism to a subsemiring of the codomain. -/
def cod_restrict (f : R →+* S) (s : σS) (h : ∀ x, f x ∈ s) : R →+* s :=
{ to_fun := λ n, ⟨f n, h n⟩,
.. (f : R →* S).cod_restrict s h,
.. (f : R →+ S).cod_restrict s h }
/-- Restriction of a ring homomorphism to its range interpreted as a subsemiring.
This is the bundled version of `set.range_factorization`. -/
def srange_restrict (f : R →+* S) : R →+* f.srange :=
f.cod_restrict f.srange f.mem_srange_self
@[simp] lemma coe_srange_restrict (f : R →+* S) (x : R) :
(f.srange_restrict x : S) = f x :=
rfl
lemma srange_restrict_surjective (f : R →+* S) : function.surjective f.srange_restrict :=
λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_srange.mp hy in ⟨x, subtype.ext hx⟩
lemma srange_top_iff_surjective {f : R →+* S} :
f.srange = (⊤ : subsemiring S) ↔ function.surjective f :=
set_like.ext'_iff.trans $ iff.trans (by rw [coe_srange, coe_top]) set.range_iff_surjective
/-- The range of a surjective ring homomorphism is the whole of the codomain. -/
lemma srange_top_of_surjective (f : R →+* S) (hf : function.surjective f) :
f.srange = (⊤ : subsemiring S) :=
srange_top_iff_surjective.2 hf
/-- The subsemiring of elements `x : R` such that `f x = g x` -/
def eq_slocus (f g : R →+* S) : subsemiring R :=
{ carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_mlocus g }
/-- If two ring homomorphisms are equal on a set, then they are equal on its subsemiring closure. -/
lemma eq_on_sclosure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s ≤ f.eq_slocus g, from closure_le.2 h
lemma eq_of_eq_on_stop {f g : R →+* S} (h : set.eq_on f g (⊤ : subsemiring R)) :
f = g :=
ext $ λ x, h trivial
lemma eq_of_eq_on_sdense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) :
f = g :=
eq_of_eq_on_stop $ hs ▸ eq_on_sclosure h
lemma sclosure_preimage_le (f : R →+* S) (s : set S) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx
/-- The image under a ring homomorphism of the subsemiring generated by a set equals
the subsemiring generated by the image of the set. -/
lemma map_sclosure (f : R →+* S) (s : set R) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _)
(sclosure_preimage_le _ _))
(closure_le.2 $ set.image_subset _ subset_closure)
end ring_hom
namespace subsemiring
open ring_hom
/-- The ring homomorphism associated to an inclusion of subsemirings. -/
def inclusion {S T : subsemiring R} (h : S ≤ T) : S →+* T :=
S.subtype.cod_restrict _ (λ x, h x.2)
@[simp] lemma srange_subtype (s : subsemiring R) : s.subtype.srange = s :=
set_like.coe_injective $ (coe_srange _).trans subtype.range_coe
@[simp]
lemma range_fst : (fst R S).srange = ⊤ :=
(fst R S).srange_top_of_surjective $ prod.fst_surjective
@[simp]
lemma range_snd : (snd R S).srange = ⊤ :=
(snd R S).srange_top_of_surjective $ prod.snd_surjective
@[simp]
lemma prod_bot_sup_bot_prod (s : subsemiring R) (t : subsemiring S) :
(s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t :=
le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $
assume p hp, prod.fst_mul_snd p ▸ mul_mem
((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set_like.mem_coe.2 $ one_mem ⊥⟩)
((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set_like.mem_coe.2 $ one_mem ⊥, hp.2⟩)
end subsemiring
namespace ring_equiv
variables {s t : subsemiring R}
/-- Makes the identity isomorphism from a proof two subsemirings of a multiplicative
monoid are equal. -/
def subsemiring_congr (h : s = t) : s ≃+* t :=
{ map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h }
/-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its
`ring_hom.srange`. -/
def sof_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) :
R ≃+* f.srange :=
{ to_fun := λ x, f.srange_restrict x,
inv_fun := λ x, (g ∘ f.srange.subtype) x,
left_inv := h,
right_inv := λ x, subtype.ext $
let ⟨x', hx'⟩ := ring_hom.mem_srange.mp x.prop in
show f (g x) = x, by rw [←hx', h x'],
..f.srange_restrict }
@[simp] lemma sof_left_inverse_apply
{g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) :
↑(sof_left_inverse h x) = f x := rfl
@[simp] lemma sof_left_inverse_symm_apply
{g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.srange) :
(sof_left_inverse h).symm x = g x := rfl
/-- Given an equivalence `e : R ≃+* S` of semirings and a subsemiring `s` of `R`,
`subsemiring_map e s` is the induced equivalence between `s` and `s.map e` -/
@[simps] def subsemiring_map (e : R ≃+* S) (s : subsemiring R) :
s ≃+* s.map e.to_ring_hom :=
{ ..e.to_add_equiv.add_submonoid_map s.to_add_submonoid,
..e.to_mul_equiv.submonoid_map s.to_submonoid }
end ring_equiv
/-! ### Actions by `subsemiring`s
These are just copies of the definitions about `submonoid` starting from `submonoid.mul_action`.
The only new result is `subsemiring.module`.
When `R` is commutative, `algebra.of_subsemiring` provides a stronger result than those found in
this file, which uses the same scalar action.
-/
section actions
namespace subsemiring
variables {R' α β : Type*}
section non_assoc_semiring
variables [non_assoc_semiring R']
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [has_smul R' α] (S : subsemiring R') : has_smul S α := S.to_submonoid.has_smul
lemma smul_def [has_smul R' α] {S : subsemiring R'} (g : S) (m : α) : g • m = (g : R') • m := rfl
instance smul_comm_class_left
[has_smul R' β] [has_smul α β] [smul_comm_class R' α β] (S : subsemiring R') :
smul_comm_class S α β :=
S.to_submonoid.smul_comm_class_left
instance smul_comm_class_right
[has_smul α β] [has_smul R' β] [smul_comm_class α R' β] (S : subsemiring R') :
smul_comm_class α S β :=
S.to_submonoid.smul_comm_class_right
/-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/
instance [has_smul α β] [has_smul R' α] [has_smul R' β] [is_scalar_tower R' α β]
(S : subsemiring R') :
is_scalar_tower S α β :=
S.to_submonoid.is_scalar_tower
instance [has_smul R' α] [has_faithful_smul R' α] (S : subsemiring R') :
has_faithful_smul S α :=
S.to_submonoid.has_faithful_smul
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [has_zero α] [smul_with_zero R' α] (S : subsemiring R') : smul_with_zero S α :=
smul_with_zero.comp_hom _ S.subtype.to_monoid_with_zero_hom.to_zero_hom
end non_assoc_semiring
variables [semiring R']
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [mul_action R' α] (S : subsemiring R') : mul_action S α :=
S.to_submonoid.mul_action
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [add_monoid α] [distrib_mul_action R' α] (S : subsemiring R') : distrib_mul_action S α :=
S.to_submonoid.distrib_mul_action
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [monoid α] [mul_distrib_mul_action R' α] (S : subsemiring R') :
mul_distrib_mul_action S α :=
S.to_submonoid.mul_distrib_mul_action
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [has_zero α] [mul_action_with_zero R' α] (S : subsemiring R') : mul_action_with_zero S α :=
mul_action_with_zero.comp_hom _ S.subtype.to_monoid_with_zero_hom
/-- The action by a subsemiring is the action by the underlying semiring. -/
instance [add_comm_monoid α] [module R' α] (S : subsemiring R') : module S α :=
{ smul := (•), .. module.comp_hom _ S.subtype }
/-- The center of a semiring acts commutatively on that semiring. -/
instance center.smul_comm_class_left : smul_comm_class (center R') R' R' :=
submonoid.center.smul_comm_class_left
/-- The center of a semiring acts commutatively on that semiring. -/
instance center.smul_comm_class_right : smul_comm_class R' (center R') R' :=
submonoid.center.smul_comm_class_right
/-- If all the elements of a set `s` commute, then `closure s` is a commutative monoid. -/
def closure_comm_semiring_of_comm {s : set R'} (hcomm : ∀ (a ∈ s) (b ∈ s), a * b = b * a) :
comm_semiring (closure s) :=
{ mul_comm := λ x y,
begin
ext,
simp only [subsemiring.coe_mul],
refine closure_induction₂ x.prop y.prop hcomm
(λ x, by simp only [zero_mul, mul_zero])
(λ x, by simp only [zero_mul, mul_zero])
(λ x, by simp only [one_mul, mul_one])
(λ x, by simp only [one_mul, mul_one])
(λ x y z h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂])
(λ x y z h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂])
(λ x y z h₁ h₂, by rw [mul_assoc, h₂, ←mul_assoc, h₁, mul_assoc])
(λ x y z h₁ h₂, by rw [←mul_assoc, h₁, mul_assoc, h₂, ←mul_assoc])
end,
..(closure s).to_semiring }
end subsemiring
end actions
-- While this definition is not about `subsemiring`s, this is the earliest we have
-- both `ordered_semiring` and `submonoid` available.
/-- Submonoid of positive elements of an ordered semiring. -/
def pos_submonoid (R : Type*) [ordered_semiring R] [nontrivial R] : submonoid R :=
{ carrier := {x | 0 < x},
one_mem' := show (0 : R) < 1, from zero_lt_one,
mul_mem' := λ x y (hx : 0 < x) (hy : 0 < y), mul_pos hx hy }
@[simp] lemma mem_pos_monoid {R : Type*} [ordered_semiring R] [nontrivial R] (u : Rˣ) :
↑u ∈ pos_submonoid R ↔ (0 : R) < u := iff.rfl
|
3b7267b3a3d006d60e195df4b681f25582fb4390 | 5c4b17dae42fab1d4f493f3b52977bffa54fefea | /4.6.5.lean | 9ed261a7476d268348f22259e32969dfb282ddd8 | [] | no_license | hyponymous/theorem-proving-in-lean-solutions | 9214cb45cc87347862fd17dfdea79fdf24b9df92 | a95320ae81c90c1b15da04574602cd378794400d | refs/heads/master | 1,585,777,733,214 | 1,541,039,359,000 | 1,541,039,359,000 | 153,676,525 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,195 | lean | open classical
variables (α : Type) (p q : α → Prop)
variable a : α
variable r : Prop
--
-- using exists.elim
example : (∃ x : α, r) → r :=
assume h : ∃ x : α, r,
show r, from
exists.elim h
(assume w,
assume hw : r,
hw)
-- using match
example : (∃ x : α, r) → r :=
assume h : ∃ x : α, r,
match h with ⟨w, (hw : r)⟩ :=
hw
end
example : r → (∃ x : α, r) :=
assume hr : r,
⟨a, hr⟩
example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r :=
iff.intro
(assume h : ∃ x, p x ∧ r,
show (∃ x, p x) ∧ r, from
match h with ⟨w, (hw : p w ∧ r)⟩ :=
⟨⟨w, hw.left⟩, hw.right⟩
end)
(assume h : (∃ x, p x) ∧ r,
show ∃ x, p x ∧ r, from
match h.left with ⟨w, (hw : p w)⟩ :=
⟨w, ⟨hw, h.right⟩⟩
end)
example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) :=
iff.intro
(assume h : (∃ x, p x ∨ q x),
show (∃ x, p x) ∨ (∃ x, q x), from
match h with ⟨w, (hw : p w ∨ q w)⟩ :=
or.elim hw
(assume hpw : p w,
or.inl ⟨w, hpw⟩)
(assume hqw : q w,
or.inr ⟨w, hqw⟩)
end)
(assume h : (∃ x, p x) ∨ (∃ x, q x),
show (∃ x, p x ∨ q x), from
or.elim h
(assume hleft : ∃ x, p x,
match hleft with ⟨w, hw⟩ :=
⟨w, or.inl hw⟩
end)
(assume hright : ∃ x, q x,
match hright with ⟨w, hw⟩ :=
⟨w, or.inr hw⟩
end))
--
-- refactor some lemmas for reuse {
lemma not_exists_then_forall_not
{α : Type} {p : α → Prop} : (¬ ∃ x, p x) → (∀ x, ¬ p x) :=
assume h : ¬ ∃ x, p x,
show ∀ x, ¬ p x, from
assume z : α,
show ¬ p z, from
(assume hpz : p z,
show false, from
h ⟨z, hpz⟩)
lemma not_not_exists_then_forall
{α : Type} {p : α → Prop} : ¬ (∃ x, ¬ p x) → (∀ x, p x) :=
assume h : ¬ (∃ x, ¬ p x),
show (∀ x, p x), from
assume z : α,
show p z, from
by_contradiction
(assume hnpz : ¬ p z,
show false, from
h ⟨z, hnpz⟩)
-- }
example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) :=
iff.intro
(assume h : (∀ x, p x),
show ¬ (∃ x, ¬ p x), from
assume hneg : ∃ x, ¬ p x,
show false, from
match hneg with ⟨w, (hw : ¬ p w)⟩ :=
absurd (h w) hw
end)
(assume h : ¬ (∃ x, ¬ p x),
show (∀ x, p x), from
not_not_exists_then_forall h)
example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) :=
iff.intro
(assume h : ∃ x, p x,
show ¬ (∀ x, ¬ p x), from
match h with ⟨w, hw⟩ :=
assume hneg : ∀ x, ¬ p x,
show false, from
absurd hw (hneg w)
end)
(assume h : ¬ (∀ x, ¬ p x), -- ∀ x, ¬ p x → false
show ∃ x, p x, from
by_contradiction
(assume h_tofalsify : ¬ (∃ x, p x),
have h2 : ∀ x, ¬ p x, from not_exists_then_forall_not h_tofalsify,
absurd h2 h))
example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) :=
iff.intro
(assume h : ¬ ∃ x, p x,
show ∀ x, ¬ p x, from
not_exists_then_forall_not h)
(assume h : ∀ x, ¬ p x,
show ¬ ∃ x, p x, from
(assume h2 : ∃ x, p x,
show false, from
match h2 with ⟨w, hw⟩ :=
absurd hw (h w)
end))
theorem not_forall_iff_not_exists
{α : Type} {p : α → Prop} : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) :=
iff.intro
(assume h : ¬ ∀ x, p x,
show ∃ x, ¬ p x, from
by_contradiction
(assume h_tofalsify : ¬ (∃ x, ¬ p x),
have h2 : ∀ x, p x, from not_not_exists_then_forall h_tofalsify,
absurd h2 h))
(assume h : ∃ x, ¬ p x,
show ¬ ∀ x, p x, from
match h with ⟨w, hw⟩ :=
assume hallp : ∀ x, p x,
show false, from
absurd (hallp w) hw
end)
--
example : (∀ x, p x → r) ↔ (∃ x, p x) → r :=
iff.intro
(assume h : (∀ x, p x → r),
show (∃ x, p x) → r, from
(assume h2 : ∃ x, p x,
show r, from
match h2 with ⟨w, (hw : p w)⟩ :=
(h w) hw
end))
(assume h : (∃ x, p x) → r,
show ∀ x, p x → r, from
assume z : α,
show p z → r, from
(assume hpz : p z,
show r, from
h ⟨z, hpz⟩))
example : (∃ x, p x → r) ↔ (∀ x, p x) → r :=
iff.intro
(assume h : ∃ x, p x → r,
show (∀ x, p x) → r, from
match h with ⟨w, (hw : p w → r)⟩ :=
assume h2 : ∀ x, p x,
show r, from
hw (h2 w)
end)
(assume h : (∀ x, p x) → r,
show ∃ x, p x → r, from
by_cases
(assume h_all : ∀ x, p x,
⟨a, (λ hpa, h h_all)⟩)
(assume h_nall : ¬ ∀ x, p x,
have h2 : ∃ x, ¬ p x, from not_forall_iff_not_exists.mp h_nall,
match h2 with ⟨w, hw⟩ :=
⟨w, (
show p w → r, from
(assume hpw : p w, absurd hpw hw)
)⟩
end))
example : (∃ x, r → p x) ↔ (r → ∃ x, p x) :=
iff.intro
(assume h : (∃ x, r → p x),
show (r → ∃ x, p x), from
match h with ⟨w, (hw : r → p w)⟩ :=
assume hr : r,
show ∃ x, p x, from
⟨w, hw hr⟩
end)
(assume h : (r → ∃ x, p x),
show (∃ x, r → p x), from
by_cases
(assume hr : r,
have h2 : ∃ x, p x, from h hr,
match h2 with ⟨w, (hw : p w)⟩ :=
⟨w, (λ _, hw)⟩
end)
(assume hnr : ¬r,
⟨a, (λ hr, absurd hr hnr)⟩))
--
|
31e5b70cf883f0ba67a62ec95cbdc04a43f54af0 | 367134ba5a65885e863bdc4507601606690974c1 | /test/derive_fintype.lean | 272e8e98c9bea7285c65e01ca8128cdb705e2d7c | [
"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 | 1,041 | lean | /-
Copyright (c) 2020 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import tactic.derive_fintype
@[derive fintype]
inductive alphabet
| a | b | c | d | e | f | g | h | i | j | k | l | m
| n | o | p | q | r | s | t | u | v | w | x | y | z
| A | B | C | D | E | F | G | H | I | J | K | L | M
| N | O | P | Q | R | S | T | U | V | W | X | Y | Z
@[derive fintype]
inductive foo
| A (x : bool)
| B (y : unit)
| C (z : fin 37)
@[derive fintype]
inductive foo2 (α : Type)
| A : α → foo2
| B : α → α → foo2
| C : α × α → foo2
| D : foo2
-- @[derive fintype] -- won't work because missing decidable instance
inductive foo3 (α β : Type) (n : ℕ)
| A : (α → β) → foo3
| B : fin n → foo3
instance (α β : Type) [decidable_eq α] [fintype α] [fintype β] (n : ℕ) : fintype (foo3 α β n) :=
by tactic.mk_fintype_instance
@[derive fintype]
structure foo4 {m n : Type} (b : m → ℕ) :=
(x : m × n)
(y : m × n)
(h : b x.1 = b y.1)
|
14fc3e8927a5ba31c83a6fff0eadb3f013bc69a6 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/category/Mon/filtered_colimits.lean | 37fd60e8dcbdaf4ce4edffaba7e8e7f84584af0c | [
"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 | 14,404 | lean | /-
Copyright (c) 2021 Justus Springer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Justus Springer
-/
import algebra.category.Mon.basic
import category_theory.limits.preserves.filtered
import category_theory.concrete_category.elementwise
import category_theory.limits.types
/-!
# The forgetful functor from (commutative) (additive) monoids preserves filtered colimits.
Forgetful functors from algebraic categories usually don't preserve colimits. However, they tend
to preserve _filtered_ colimits.
In this file, we start with a small filtered category `J` and a functor `F : J ⥤ Mon`.
We then construct a monoid structure on the colimit of `F ⋙ forget Mon` (in `Type`), thereby
showing that the forgetful functor `forget Mon` preserves filtered colimits. Similarly for `AddMon`,
`CommMon` and `AddCommMon`.
-/
universes v u
noncomputable theory
open_locale classical
open category_theory
open category_theory.limits
open category_theory.is_filtered (renaming max → max') -- avoid name collision with `_root_.max`.
namespace Mon.filtered_colimits
section
-- We use parameters here, mainly so we can have the abbreviations `M` and `M.mk` below, without
-- passing around `F` all the time.
parameters {J : Type v} [small_category J] (F : J ⥤ Mon.{max v u})
/--
The colimit of `F ⋙ forget Mon` in the category of types.
In the following, we will construct a monoid structure on `M`.
-/
@[to_additive "The colimit of `F ⋙ forget AddMon` in the category of types.
In the following, we will construct an additive monoid structure on `M`."]
abbreviation M : Type (max v u) := types.quot (F ⋙ forget Mon)
/-- The canonical projection into the colimit, as a quotient type. -/
@[to_additive "The canonical projection into the colimit, as a quotient type."]
abbreviation M.mk : (Σ j, F.obj j) → M := quot.mk (types.quot.rel (F ⋙ forget Mon))
@[to_additive]
lemma M.mk_eq (x y : Σ j, F.obj j)
(h : ∃ (k : J) (f : x.1 ⟶ k) (g : y.1 ⟶ k), F.map f x.2 = F.map g y.2) :
M.mk x = M.mk y :=
quot.eqv_gen_sound (types.filtered_colimit.eqv_gen_quot_rel_of_rel (F ⋙ forget Mon) x y h)
variables [is_filtered J]
/--
As `J` is nonempty, we can pick an arbitrary object `j₀ : J`. We use this object to define the
"one" in the colimit as the equivalence class of `⟨j₀, 1 : F.obj j₀⟩`.
-/
@[to_additive "As `J` is nonempty, we can pick an arbitrary object `j₀ : J`. We use this object to
define the \"zero\" in the colimit as the equivalence class of `⟨j₀, 0 : F.obj j₀⟩`."]
instance colimit_has_one : has_one M :=
{ one := M.mk ⟨is_filtered.nonempty.some, 1⟩ }
/--
The definition of the "one" in the colimit is independent of the chosen object of `J`.
In particular, this lemma allows us to "unfold" the definition of `colimit_one` at a custom chosen
object `j`.
-/
@[to_additive "The definition of the \"zero\" in the colimit is independent of the chosen object
of `J`. In particular, this lemma allows us to \"unfold\" the definition of `colimit_zero` at a
custom chosen object `j`."]
lemma colimit_one_eq (j : J) : (1 : M) = M.mk ⟨j, 1⟩ :=
begin
apply M.mk_eq,
refine ⟨max' _ j, left_to_max _ j, right_to_max _ j, _⟩,
simp,
end
/--
The "unlifted" version of multiplication in the colimit. To multiply two dependent pairs
`⟨j₁, x⟩` and `⟨j₂, y⟩`, we pass to a common successor of `j₁` and `j₂` (given by `is_filtered.max`)
and multiply them there.
-/
@[to_additive "The \"unlifted\" version of addition in the colimit. To add two dependent pairs
`⟨j₁, x⟩` and `⟨j₂, y⟩`, we pass to a common successor of `j₁` and `j₂` (given by `is_filtered.max`)
and add them there."]
def colimit_mul_aux (x y : Σ j, F.obj j) : M :=
M.mk ⟨max' x.1 y.1, F.map (left_to_max x.1 y.1) x.2 * F.map (right_to_max x.1 y.1) y.2⟩
/-- Multiplication in the colimit is well-defined in the left argument. -/
@[to_additive "Addition in the colimit is well-defined in the left argument."]
lemma colimit_mul_aux_eq_of_rel_left {x x' y : Σ j, F.obj j}
(hxx' : types.filtered_colimit.rel (F ⋙ forget Mon) x x') :
colimit_mul_aux x y = colimit_mul_aux x' y :=
begin
cases x with j₁ x, cases y with j₂ y, cases x' with j₃ x',
obtain ⟨l, f, g, hfg⟩ := hxx',
simp at hfg,
obtain ⟨s, α, β, γ, h₁, h₂, h₃⟩ := tulip (left_to_max j₁ j₂) (right_to_max j₁ j₂)
(right_to_max j₃ j₂) (left_to_max j₃ j₂) f g,
apply M.mk_eq,
use [s, α, γ],
dsimp,
simp_rw [monoid_hom.map_mul, ← comp_apply, ← F.map_comp, h₁, h₂, h₃, F.map_comp, comp_apply, hfg]
end
/-- Multiplication in the colimit is well-defined in the right argument. -/
@[to_additive "Addition in the colimit is well-defined in the right argument."]
lemma colimit_mul_aux_eq_of_rel_right {x y y' : Σ j, F.obj j}
(hyy' : types.filtered_colimit.rel (F ⋙ forget Mon) y y') :
colimit_mul_aux x y = colimit_mul_aux x y' :=
begin
cases y with j₁ y, cases x with j₂ x, cases y' with j₃ y',
obtain ⟨l, f, g, hfg⟩ := hyy',
simp at hfg,
obtain ⟨s, α, β, γ, h₁, h₂, h₃⟩ := tulip (right_to_max j₂ j₁) (left_to_max j₂ j₁)
(left_to_max j₂ j₃) (right_to_max j₂ j₃) f g,
apply M.mk_eq,
use [s, α, γ],
dsimp,
simp_rw [monoid_hom.map_mul, ← comp_apply, ← F.map_comp, h₁, h₂, h₃, F.map_comp, comp_apply, hfg]
end
/-- Multiplication in the colimit. See also `colimit_mul_aux`. -/
@[to_additive "Addition in the colimit. See also `colimit_add_aux`."]
instance colimit_has_mul : has_mul M :=
{ mul := λ x y, begin
refine quot.lift₂ (colimit_mul_aux F) _ _ x y,
{ intros x y y' h,
apply colimit_mul_aux_eq_of_rel_right,
apply types.filtered_colimit.rel_of_quot_rel,
exact h },
{ intros x x' y h,
apply colimit_mul_aux_eq_of_rel_left,
apply types.filtered_colimit.rel_of_quot_rel,
exact h },
end }
/--
Multiplication in the colimit is independent of the chosen "maximum" in the filtered category.
In particular, this lemma allows us to "unfold" the definition of the multiplication of `x` and `y`,
using a custom object `k` and morphisms `f : x.1 ⟶ k` and `g : y.1 ⟶ k`.
-/
@[to_additive "Addition in the colimit is independent of the chosen \"maximum\" in the filtered
category. In particular, this lemma allows us to \"unfold\" the definition of the addition of `x`
and `y`, using a custom object `k` and morphisms `f : x.1 ⟶ k` and `g : y.1 ⟶ k`."]
lemma colimit_mul_mk_eq (x y : Σ j, F.obj j) (k : J) (f : x.1 ⟶ k) (g : y.1 ⟶ k) :
(M.mk x) * (M.mk y) = M.mk ⟨k, F.map f x.2 * F.map g y.2⟩ :=
begin
cases x with j₁ x, cases y with j₂ y,
obtain ⟨s, α, β, h₁, h₂⟩ := bowtie (left_to_max j₁ j₂) f (right_to_max j₁ j₂) g,
apply M.mk_eq,
use [s, α, β],
dsimp,
simp_rw [monoid_hom.map_mul, ← comp_apply, ← F.map_comp, h₁, h₂],
end
@[to_additive]
instance colimit_monoid : monoid M :=
{ one_mul := λ x, begin
apply quot.induction_on x, clear x, intro x, cases x with j x,
rw [colimit_one_eq F j, colimit_mul_mk_eq F ⟨j, 1⟩ ⟨j, x⟩ j (𝟙 j) (𝟙 j),
monoid_hom.map_one, one_mul, F.map_id, id_apply],
end,
mul_one := λ x, begin
apply quot.induction_on x, clear x, intro x, cases x with j x,
rw [colimit_one_eq F j, colimit_mul_mk_eq F ⟨j, x⟩ ⟨j, 1⟩ j (𝟙 j) (𝟙 j),
monoid_hom.map_one, mul_one, F.map_id, id_apply],
end,
mul_assoc := λ x y z, begin
apply quot.induction_on₃ x y z, clear x y z, intros x y z,
cases x with j₁ x, cases y with j₂ y, cases z with j₃ z,
rw [colimit_mul_mk_eq F ⟨j₁, x⟩ ⟨j₂, y⟩ _ (first_to_max₃ j₁ j₂ j₃) (second_to_max₃ j₁ j₂ j₃),
colimit_mul_mk_eq F ⟨max₃ j₁ j₂ j₃, _⟩ ⟨j₃, z⟩ _ (𝟙 _) (third_to_max₃ j₁ j₂ j₃),
colimit_mul_mk_eq F ⟨j₂, y⟩ ⟨j₃, z⟩ _ (second_to_max₃ j₁ j₂ j₃) (third_to_max₃ j₁ j₂ j₃),
colimit_mul_mk_eq F ⟨j₁, x⟩ ⟨max₃ j₁ j₂ j₃, _⟩ _ (first_to_max₃ j₁ j₂ j₃) (𝟙 _)],
simp only [F.map_id, id_apply, mul_assoc],
end,
..colimit_has_one,
..colimit_has_mul }
/-- The bundled monoid giving the filtered colimit of a diagram. -/
@[to_additive "The bundled additive monoid giving the filtered colimit of a diagram."]
def colimit : Mon := Mon.of M
/-- The monoid homomorphism from a given monoid in the diagram to the colimit monoid. -/
@[to_additive "The additive monoid homomorphism from a given additive monoid in the diagram to the
colimit additive monoid."]
def cocone_morphism (j : J) : F.obj j ⟶ colimit :=
{ to_fun := (types.colimit_cocone (F ⋙ forget Mon)).ι.app j,
map_one' := (colimit_one_eq j).symm,
map_mul' := λ x y, begin
convert (colimit_mul_mk_eq F ⟨j, x⟩ ⟨j, y⟩ j (𝟙 j) (𝟙 j)).symm,
rw [F.map_id, id_apply, id_apply], refl,
end }
@[simp, to_additive]
lemma cocone_naturality {j j' : J} (f : j ⟶ j') :
F.map f ≫ (cocone_morphism j') = cocone_morphism j :=
monoid_hom.coe_inj ((types.colimit_cocone (F ⋙ forget Mon)).ι.naturality f)
/-- The cocone over the proposed colimit monoid. -/
@[to_additive "The cocone over the proposed colimit additive monoid."]
def colimit_cocone : cocone F :=
{ X := colimit,
ι := { app := cocone_morphism } }.
/--
Given a cocone `t` of `F`, the induced monoid homomorphism from the colimit to the cocone point.
As a function, this is simply given by the induced map of the corresponding cocone in `Type`.
The only thing left to see is that it is a monoid homomorphism.
-/
@[to_additive "Given a cocone `t` of `F`, the induced additive monoid homomorphism from the colimit
to the cocone point. As a function, this is simply given by the induced map of the corresponding
cocone in `Type`. The only thing left to see is that it is an additive monoid homomorphism."]
def colimit_desc (t : cocone F) : colimit ⟶ t.X :=
{ to_fun := (types.colimit_cocone_is_colimit (F ⋙ forget Mon)).desc ((forget Mon).map_cocone t),
map_one' := begin
rw colimit_one_eq F is_filtered.nonempty.some,
exact monoid_hom.map_one _,
end,
map_mul' := λ x y, begin
apply quot.induction_on₂ x y, clear x y, intros x y,
cases x with i x, cases y with j y,
rw colimit_mul_mk_eq F ⟨i, x⟩ ⟨j, y⟩ (max' i j) (left_to_max i j) (right_to_max i j),
dsimp [types.colimit_cocone_is_colimit],
rw [monoid_hom.map_mul, t.w_apply, t.w_apply],
end }
/-- The proposed colimit cocone is a colimit in `Mon`. -/
@[to_additive "The proposed colimit cocone is a colimit in `AddMon`."]
def colimit_cocone_is_colimit : is_colimit colimit_cocone :=
{ desc := colimit_desc,
fac' := λ t j, monoid_hom.coe_inj
((types.colimit_cocone_is_colimit (F ⋙ forget Mon)).fac ((forget Mon).map_cocone t) j),
uniq' := λ t m h, monoid_hom.coe_inj $
(types.colimit_cocone_is_colimit (F ⋙ forget Mon)).uniq ((forget Mon).map_cocone t) m
(λ j, funext $ λ x, monoid_hom.congr_fun (h j) x) }
@[to_additive]
instance forget_preserves_filtered_colimits : preserves_filtered_colimits (forget Mon.{u}) :=
{ preserves_filtered_colimits := λ J _ _, by exactI
{ preserves_colimit := λ F, preserves_colimit_of_preserves_colimit_cocone
(colimit_cocone_is_colimit.{u u} F) (types.colimit_cocone_is_colimit (F ⋙ forget Mon.{u})) } }
end
end Mon.filtered_colimits
namespace CommMon.filtered_colimits
open Mon.filtered_colimits (colimit_mul_mk_eq)
section
-- We use parameters here, mainly so we can have the abbreviation `M` below, without
-- passing around `F` all the time.
parameters {J : Type v} [small_category J] [is_filtered J] (F : J ⥤ CommMon.{max v u})
/--
The colimit of `F ⋙ forget₂ CommMon Mon` in the category `Mon`.
In the following, we will show that this has the structure of a _commutative_ monoid.
-/
@[to_additive "The colimit of `F ⋙ forget₂ AddCommMon AddMon` in the category `AddMon`. In the
following, we will show that this has the structure of a _commutative_ additive monoid."]
abbreviation M : Mon := Mon.filtered_colimits.colimit (F ⋙ forget₂ CommMon Mon.{max v u})
@[to_additive]
instance colimit_comm_monoid : comm_monoid M :=
{ mul_comm := λ x y, begin
apply quot.induction_on₂ x y, clear x y, intros x y,
let k := max' x.1 y.1,
let f := left_to_max x.1 y.1,
let g := right_to_max x.1 y.1,
rw [colimit_mul_mk_eq _ x y k f g, colimit_mul_mk_eq _ y x k g f],
dsimp,
rw mul_comm,
end
..M.monoid }
/-- The bundled commutative monoid giving the filtered colimit of a diagram. -/
@[to_additive "The bundled additive commutative monoid giving the filtered colimit of a diagram."]
def colimit : CommMon := CommMon.of M
/-- The cocone over the proposed colimit commutative monoid. -/
@[to_additive "The cocone over the proposed colimit additive commutative monoid."]
def colimit_cocone : cocone F :=
{ X := colimit,
ι := { ..(Mon.filtered_colimits.colimit_cocone (F ⋙ forget₂ CommMon Mon.{max v u})).ι } }
/-- The proposed colimit cocone is a colimit in `CommMon`. -/
@[to_additive "The proposed colimit cocone is a colimit in `AddCommMon`."]
def colimit_cocone_is_colimit : is_colimit colimit_cocone :=
{ desc := λ t, Mon.filtered_colimits.colimit_desc (F ⋙ forget₂ CommMon Mon.{max v u})
((forget₂ CommMon Mon.{max v u}).map_cocone t),
fac' := λ t j, monoid_hom.coe_inj $
(types.colimit_cocone_is_colimit (F ⋙ forget CommMon)).fac ((forget CommMon).map_cocone t) j,
uniq' := λ t m h, monoid_hom.coe_inj $
(types.colimit_cocone_is_colimit (F ⋙ forget CommMon)).uniq ((forget CommMon).map_cocone t) m
((λ j, funext $ λ x, monoid_hom.congr_fun (h j) x)) }
@[to_additive forget₂_AddMon_preserves_filtered_colimits]
instance forget₂_Mon_preserves_filtered_colimits :
preserves_filtered_colimits (forget₂ CommMon Mon.{u}) :=
{ preserves_filtered_colimits := λ J _ _, by exactI
{ preserves_colimit := λ F, preserves_colimit_of_preserves_colimit_cocone
(colimit_cocone_is_colimit.{u u} F)
(Mon.filtered_colimits.colimit_cocone_is_colimit (F ⋙ forget₂ CommMon Mon.{u})) } }
@[to_additive]
instance forget_preserves_filtered_colimits :
preserves_filtered_colimits (forget CommMon.{u}) :=
limits.comp_preserves_filtered_colimits (forget₂ CommMon Mon) (forget Mon)
end
end CommMon.filtered_colimits
|
4317e4971b107c937559eb5de9478554faef7b6c | 842b7df4a999c5c50bbd215b8617dd705e43c2e1 | /test.lean | fbac46fc027e1f79063a6dc0a09027c6ca5b8ba9 | [] | no_license | Samyak-Surti/LeanCode | 1c245631f74b00057d20483c8ac75916e8643b14 | 944eac3e5f43e2614ed246083b97fbdf24181d83 | refs/heads/master | 1,669,023,730,828 | 1,595,534,784,000 | 1,595,534,784,000 | 282,037,186 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 44 | lean | example: 2 + 2 = 4 :=
begin
trivial
end
|
aed79b06e1b664113919f0b440b5a25b90925bc1 | 60bf3fa4185ec5075eaea4384181bfbc7e1dc319 | /src/game/order/level03.lean | 039b74520702129d6b5f432509f759ddd01a42c1 | [
"Apache-2.0"
] | permissive | anrddh/real-number-game | 660f1127d03a78fd35986c771d65c3132c5f4025 | c708c4e02ec306c657e1ea67862177490db041b0 | refs/heads/master | 1,668,214,277,092 | 1,593,105,075,000 | 1,593,105,075,000 | 264,269,218 | 0 | 0 | null | 1,589,567,264,000 | 1,589,567,264,000 | null | UTF-8 | Lean | false | false | 807 | lean | import data.real.basic
namespace xena -- hide
/-
# Chapter 2 : Order
## Level 3
Another property of the absolute value.
-/
notation `|` x `|` := abs x --hide
/- Lemma
For any two real numbers $a$ and $b$, we have that
$$|a| ≤ c ↔ -c ≤ a ≤ c$$.
-/
theorem abs_le (a c : ℝ) (h : 0 ≤ c): |a| ≤ c → (-c) ≤ a ∧ a ≤ c :=
begin
rcases lt_trichotomy a 0 with haNeg | haZero | haPos,
{ -- case a < 0
intro H,
have h1 : | a | = - a, exact abs_of_neg haNeg,
rw h1 at H, split, linarith, linarith,
},
{ -- case a = 0
intro H, rw haZero, split, linarith, exact h,
},
{ -- case 0 < a
intro H,
have h1 : |a| = a, exact abs_of_pos haPos,
rw h1 at H, split, linarith, exact H,
},
done
end
end xena --hide
|
a953a65e613f0b513d1fbe24a48afeb236cf6d3b | 4727251e0cd73359b15b664c3170e5d754078599 | /src/tactic/fix_reflect_string.lean | 2657700a5d25e4cd637176cfa244694e0f50b1f2 | [
"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 | 1,546 | lean | /-
Copyright (c) 2020 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
/-!
# Workaround for stack overflows with `has_reflect string`
The default `has_reflect string` instance in Lean only work for strings up to
few thousand characters. Anything larger than that will trigger a stack overflow because
the string is represented as a very deeply nested expression:
https://github.com/leanprover-community/lean/issues/144
This file adds a higher-priority instance for `has_reflect string`, which
behaves exactly the same for small strings (up to 256 characters). Larger
strings are carefully converted into a call to `string.join`.
-/
/--
Splits a string into chunks of at most `size` characters.
-/
meta def string.to_chunks (size : ℕ) : string → opt_param (list string) [] → list string | s acc :=
if s.length ≤ size then s :: acc else
string.to_chunks (s.popn_back size) (s.backn size :: acc)
section
local attribute [semireducible] reflected
meta instance {α} [has_reflect α] : has_reflect (thunk α) | a :=
expr.lam `x binder_info.default (reflect unit) (reflect $ a ())
end
@[priority 2000]
meta instance : has_reflect string | s :=
let chunk_size := 256 in
if s.length ≤ chunk_size then reflect s else
have ts : list (thunk string), from (s.to_chunks chunk_size).map (λ s _, s),
have h : s = string.join (ts.map (λ t, t ())), from undefined,
suffices reflected (string.join $ ts.map (λ t, t ())), by rwa h,
`(string.join $ list.map _ _)
|
ece820ef1be5626440d4692e95ed06f9155bb542 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/polynomial/monic_auto.lean | ec14381c6f1dd0934b7cb3aee576e336d29cad0a | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,907 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.polynomial.reverse
import Mathlib.algebra.associated
import Mathlib.tactic.omega.default
import Mathlib.PostPort
universes u v y
namespace Mathlib
/-!
# Theory of monic polynomials
We give several tools for proving that polynomials are monic, e.g.
`monic_mul`, `monic_map`.
-/
namespace polynomial
theorem monic.as_sum {R : Type u} [semiring R] {p : polynomial R} (hp : monic p) :
p =
X ^ nat_degree p +
finset.sum (finset.range (nat_degree p)) fun (i : ℕ) => coe_fn C (coeff p i) * X ^ i :=
sorry
theorem ne_zero_of_monic_of_zero_ne_one {R : Type u} [semiring R] {p : polynomial R} (hp : monic p)
(h : 0 ≠ 1) : p ≠ 0 :=
sorry
theorem ne_zero_of_ne_zero_of_monic {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R}
(hp : p ≠ 0) (hq : monic q) : q ≠ 0 :=
sorry
theorem monic_map {R : Type u} {S : Type v} [semiring R] {p : polynomial R} [semiring S]
(f : R →+* S) (hp : monic p) : monic (map f p) :=
sorry
theorem monic_mul_C_of_leading_coeff_mul_eq_one {R : Type u} [semiring R] {p : polynomial R}
[nontrivial R] {b : R} (hp : leading_coeff p * b = 1) : monic (p * coe_fn C b) :=
sorry
theorem monic_of_degree_le {R : Type u} [semiring R] {p : polynomial R} (n : ℕ) (H1 : degree p ≤ ↑n)
(H2 : coeff p n = 1) : monic p :=
sorry
theorem monic_X_pow_add {R : Type u} [semiring R] {p : polynomial R} {n : ℕ} (H : degree p ≤ ↑n) :
monic (X ^ (n + 1) + p) :=
sorry
theorem monic_X_add_C {R : Type u} [semiring R] (x : R) : monic (X + coe_fn C x) :=
pow_one X ▸ monic_X_pow_add degree_C_le
theorem monic_mul {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R} (hp : monic p)
(hq : monic q) : monic (p * q) :=
sorry
theorem monic_pow {R : Type u} [semiring R] {p : polynomial R} (hp : monic p) (n : ℕ) :
monic (p ^ n) :=
sorry
theorem monic_add_of_left {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R}
(hp : monic p) (hpq : degree q < degree p) : monic (p + q) :=
eq.mpr (id (Eq._oldrec (Eq.refl (monic (p + q))) (monic.equations._eqn_1 (p + q))))
(eq.mpr (id (Eq._oldrec (Eq.refl (leading_coeff (p + q) = 1)) (add_comm p q)))
(eq.mpr
(id (Eq._oldrec (Eq.refl (leading_coeff (q + p) = 1)) (leading_coeff_add_of_degree_lt hpq)))
hp))
theorem monic_add_of_right {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R}
(hq : monic q) (hpq : degree p < degree q) : monic (p + q) :=
eq.mpr (id (Eq._oldrec (Eq.refl (monic (p + q))) (monic.equations._eqn_1 (p + q))))
(eq.mpr
(id (Eq._oldrec (Eq.refl (leading_coeff (p + q) = 1)) (leading_coeff_add_of_degree_lt hpq)))
hq)
namespace monic
@[simp] theorem degree_eq_zero_iff_eq_one {R : Type u} [semiring R] {p : polynomial R}
(hp : monic p) : nat_degree p = 0 ↔ p = 1 :=
sorry
theorem nat_degree_mul {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R}
(hp : monic p) (hq : monic q) : nat_degree (p * q) = nat_degree p + nat_degree q :=
sorry
theorem next_coeff_mul {R : Type u} [semiring R] {p : polynomial R} {q : polynomial R}
(hp : monic p) (hq : monic q) : next_coeff (p * q) = next_coeff p + next_coeff q :=
sorry
end monic
theorem monic_prod_of_monic {R : Type u} {ι : Type y} [comm_semiring R] (s : finset ι)
(f : ι → polynomial R) (hs : ∀ (i : ι), i ∈ s → monic (f i)) :
monic (finset.prod s fun (i : ι) => f i) :=
finset.prod_induction (fun (x : ι) => f x) monic monic_mul monic_one hs
theorem is_unit_C {R : Type u} [comm_semiring R] {x : R} : is_unit (coe_fn C x) ↔ is_unit x := sorry
theorem eq_one_of_is_unit_of_monic {R : Type u} [comm_semiring R] {p : polynomial R} (hm : monic p)
(hpu : is_unit p) : p = 1 :=
sorry
theorem monic.next_coeff_prod {R : Type u} {ι : Type y} [comm_semiring R] (s : finset ι)
(f : ι → polynomial R) (h : ∀ (i : ι), i ∈ s → monic (f i)) :
next_coeff (finset.prod s fun (i : ι) => f i) = finset.sum s fun (i : ι) => next_coeff (f i) :=
sorry
theorem monic_X_sub_C {R : Type u} [ring R] (x : R) : monic (X - coe_fn C x) := sorry
theorem monic_X_pow_sub {R : Type u} [ring R] {p : polynomial R} {n : ℕ} (H : degree p ≤ ↑n) :
monic (X ^ (n + 1) - p) :=
sorry
/-- `X ^ n - a` is monic. -/
theorem monic_X_pow_sub_C {R : Type u} [ring R] (a : R) {n : ℕ} (h : n ≠ 0) :
monic (X ^ n - coe_fn C a) :=
sorry
theorem monic_sub_of_left {R : Type u} [ring R] {p : polynomial R} {q : polynomial R} (hp : monic p)
(hpq : degree q < degree p) : monic (p - q) :=
eq.mpr (id (Eq._oldrec (Eq.refl (monic (p - q))) (sub_eq_add_neg p q)))
(monic_add_of_left hp
(eq.mpr (id (Eq._oldrec (Eq.refl (degree (-q) < degree p)) (degree_neg q))) hpq))
theorem monic_sub_of_right {R : Type u} [ring R] {p : polynomial R} {q : polynomial R}
(hq : leading_coeff q = -1) (hpq : degree p < degree q) : monic (p - q) :=
sorry
theorem leading_coeff_of_injective {R : Type u} {S : Type v} [ring R] [semiring S] {f : R →+* S}
(hf : function.injective ⇑f) (p : polynomial R) :
leading_coeff (map f p) = coe_fn f (leading_coeff p) :=
sorry
theorem monic_of_injective {R : Type u} {S : Type v} [ring R] [semiring S] {f : R →+* S}
(hf : function.injective ⇑f) {p : polynomial R} (hp : monic (map f p)) : monic p :=
sorry
@[simp] theorem not_monic_zero {R : Type u} [semiring R] [nontrivial R] : ¬monic 0 := sorry
theorem ne_zero_of_monic {R : Type u} [semiring R] [nontrivial R] {p : polynomial R} (h : monic p) :
p ≠ 0 :=
fun (h₁ : p = 0) => not_monic_zero (h₁ ▸ h)
end Mathlib |
90635274a8cbe07cadf64ea27663664ce4ad4556 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/locally_convex/abs_convex.lean | b302e21cb2d3cd8ce4c3c73bb74ee292725629de | [
"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,282 | lean | /-
Copyright (c) 2022 Moritz Doll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Doll
-/
import analysis.locally_convex.balanced_core_hull
import analysis.locally_convex.with_seminorms
import analysis.convex.gauge
/-!
# Absolutely convex sets
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A set is called absolutely convex or disked if it is convex and balanced.
The importance of absolutely convex sets comes from the fact that every locally convex
topological vector space has a basis consisting of absolutely convex sets.
## Main definitions
* `gauge_seminorm_family`: the seminorm family induced by all open absolutely convex neighborhoods
of zero.
## Main statements
* `with_gauge_seminorm_family`: the topology of a locally convex space is induced by the family
`gauge_seminorm_family`.
## Todo
* Define the disked hull
## Tags
disks, convex, balanced
-/
open normed_field set
open_locale big_operators nnreal pointwise topology
variables {𝕜 E F G ι : Type*}
section nontrivially_normed_field
variables (𝕜 E) {s : set E}
variables [nontrivially_normed_field 𝕜] [add_comm_group E] [module 𝕜 E]
variables [module ℝ E] [smul_comm_class ℝ 𝕜 E]
variables [topological_space E] [locally_convex_space ℝ E] [has_continuous_smul 𝕜 E]
lemma nhds_basis_abs_convex : (𝓝 (0 : E)).has_basis
(λ (s : set E), s ∈ 𝓝 (0 : E) ∧ balanced 𝕜 s ∧ convex ℝ s) id :=
begin
refine (locally_convex_space.convex_basis_zero ℝ E).to_has_basis (λ s hs, _)
(λ s hs, ⟨s, ⟨hs.1, hs.2.2⟩, rfl.subset⟩),
refine ⟨convex_hull ℝ (balanced_core 𝕜 s), _, convex_hull_min (balanced_core_subset s) hs.2⟩,
refine ⟨filter.mem_of_superset (balanced_core_mem_nhds_zero hs.1) (subset_convex_hull ℝ _), _⟩,
refine ⟨balanced_convex_hull_of_balanced (balanced_core_balanced s), _⟩,
exact convex_convex_hull ℝ (balanced_core 𝕜 s),
end
variables [has_continuous_smul ℝ E] [topological_add_group E]
lemma nhds_basis_abs_convex_open : (𝓝 (0 : E)).has_basis
(λ (s : set E), (0 : E) ∈ s ∧ is_open s ∧ balanced 𝕜 s ∧ convex ℝ s) id :=
begin
refine (nhds_basis_abs_convex 𝕜 E).to_has_basis _ _,
{ rintros s ⟨hs_nhds, hs_balanced, hs_convex⟩,
refine ⟨interior s, _, interior_subset⟩,
exact ⟨mem_interior_iff_mem_nhds.mpr hs_nhds, is_open_interior,
hs_balanced.interior (mem_interior_iff_mem_nhds.mpr hs_nhds), hs_convex.interior⟩ },
rintros s ⟨hs_zero, hs_open, hs_balanced, hs_convex⟩,
exact ⟨s, ⟨hs_open.mem_nhds hs_zero, hs_balanced, hs_convex⟩, rfl.subset⟩,
end
end nontrivially_normed_field
section absolutely_convex_sets
variables [topological_space E] [add_comm_monoid E] [has_zero E] [semi_normed_ring 𝕜]
variables [has_smul 𝕜 E] [has_smul ℝ E]
variables (𝕜 E)
/-- The type of absolutely convex open sets. -/
def abs_convex_open_sets :=
{ s : set E // (0 : E) ∈ s ∧ is_open s ∧ balanced 𝕜 s ∧ convex ℝ s }
instance abs_convex_open_sets.has_coe : has_coe (abs_convex_open_sets 𝕜 E) (set E) := ⟨subtype.val⟩
namespace abs_convex_open_sets
variables {𝕜 E}
lemma coe_zero_mem (s : abs_convex_open_sets 𝕜 E) : (0 : E) ∈ (s : set E) := s.2.1
lemma coe_is_open (s : abs_convex_open_sets 𝕜 E) : is_open (s : set E) := s.2.2.1
lemma coe_nhds (s : abs_convex_open_sets 𝕜 E) : (s : set E) ∈ 𝓝 (0 : E) :=
s.coe_is_open.mem_nhds s.coe_zero_mem
lemma coe_balanced (s : abs_convex_open_sets 𝕜 E) : balanced 𝕜 (s : set E) := s.2.2.2.1
lemma coe_convex (s : abs_convex_open_sets 𝕜 E) : convex ℝ (s : set E) := s.2.2.2.2
end abs_convex_open_sets
instance : nonempty (abs_convex_open_sets 𝕜 E) :=
begin
rw ←exists_true_iff_nonempty,
dunfold abs_convex_open_sets,
rw subtype.exists,
exact ⟨set.univ, ⟨mem_univ 0, is_open_univ, balanced_univ, convex_univ⟩, trivial⟩,
end
end absolutely_convex_sets
variables [is_R_or_C 𝕜]
variables [add_comm_group E] [topological_space E]
variables [module 𝕜 E] [module ℝ E] [is_scalar_tower ℝ 𝕜 E]
variables [has_continuous_smul ℝ E]
variables (𝕜 E)
/-- The family of seminorms defined by the gauges of absolute convex open sets. -/
noncomputable
def gauge_seminorm_family : seminorm_family 𝕜 E (abs_convex_open_sets 𝕜 E) :=
λ s, gauge_seminorm s.coe_balanced s.coe_convex (absorbent_nhds_zero s.coe_nhds)
variables {𝕜 E}
lemma gauge_seminorm_family_ball (s : abs_convex_open_sets 𝕜 E) :
(gauge_seminorm_family 𝕜 E s).ball 0 1 = (s : set E) :=
begin
dunfold gauge_seminorm_family,
rw seminorm.ball_zero_eq,
simp_rw gauge_seminorm_to_fun,
exact gauge_lt_one_eq_self_of_open s.coe_convex s.coe_zero_mem s.coe_is_open,
end
variables [topological_add_group E] [has_continuous_smul 𝕜 E]
variables [smul_comm_class ℝ 𝕜 E] [locally_convex_space ℝ E]
/-- The topology of a locally convex space is induced by the gauge seminorm family. -/
lemma with_gauge_seminorm_family : with_seminorms (gauge_seminorm_family 𝕜 E) :=
begin
refine seminorm_family.with_seminorms_of_has_basis _ _,
refine (nhds_basis_abs_convex_open 𝕜 E).to_has_basis (λ s hs, _) (λ s hs, _),
{ refine ⟨s, ⟨_, rfl.subset⟩⟩,
convert (gauge_seminorm_family _ _).basis_sets_singleton_mem ⟨s, hs⟩ one_pos,
rw [gauge_seminorm_family_ball, subtype.coe_mk] },
refine ⟨s, ⟨_, rfl.subset⟩⟩,
rw seminorm_family.basis_sets_iff at hs,
rcases hs with ⟨t, r, hr, rfl⟩,
rw [seminorm.ball_finset_sup_eq_Inter _ _ _ hr],
-- We have to show that the intersection contains zero, is open, balanced, and convex
refine ⟨mem_Inter₂.mpr (λ _ _, by simp [seminorm.mem_ball_zero, hr]),
is_open_bInter (to_finite _) (λ S _, _),
balanced_Inter₂ (λ _ _, seminorm.balanced_ball_zero _ _),
convex_Inter₂ (λ _ _, seminorm.convex_ball _ _ _)⟩,
-- The only nontrivial part is to show that the ball is open
have hr' : r = ‖(r : 𝕜)‖ * 1 := by simp [abs_of_pos hr],
have hr'' : (r : 𝕜) ≠ 0 := by simp [hr.ne'],
rw [hr', ← seminorm.smul_ball_zero hr'', gauge_seminorm_family_ball],
exact S.coe_is_open.smul₀ hr''
end
|
4a0a063f2b204a213403ae09177bd1a7b9781c25 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/data/nat/totient.lean | d78eae8ae6b7ce9ab604edd0e1f4a7c4cbb1958d | [
"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 | 14,621 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import algebra.char_p.two
import data.nat.factorization.basic
import data.nat.periodic
import data.zmod.basic
/-!
# Euler's totient function
This file defines [Euler's totient function](https://en.wikipedia.org/wiki/Euler's_totient_function)
`nat.totient n` which counts the number of naturals less than `n` that are coprime with `n`.
We prove the divisor sum formula, namely that `n` equals `φ` summed over the divisors of `n`. See
`sum_totient`. We also prove two lemmas to help compute totients, namely `totient_mul` and
`totient_prime_pow`.
-/
open finset
open_locale big_operators
namespace nat
/-- Euler's totient function. This counts the number of naturals strictly less than `n` which are
coprime with `n`. -/
def totient (n : ℕ) : ℕ := ((range n).filter n.coprime).card
localized "notation (name := nat.totient) `φ` := nat.totient" in nat
@[simp] theorem totient_zero : φ 0 = 0 := rfl
@[simp] theorem totient_one : φ 1 = 1 :=
by simp [totient]
lemma totient_eq_card_coprime (n : ℕ) : φ n = ((range n).filter n.coprime).card := rfl
lemma totient_le (n : ℕ) : φ n ≤ n :=
((range n).card_filter_le _).trans_eq (card_range n)
lemma totient_lt (n : ℕ) (hn : 1 < n) : φ n < n :=
(card_lt_card (filter_ssubset.2 ⟨0, by simp [hn.ne', pos_of_gt hn]⟩)).trans_eq (card_range n)
lemma totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n
| 0 := dec_trivial
| 1 := by simp [totient]
| (n+2) := λ h, card_pos.2 ⟨1, mem_filter.2 ⟨mem_range.2 dec_trivial, coprime_one_right _⟩⟩
lemma filter_coprime_Ico_eq_totient (a n : ℕ) :
((Ico n (n+a)).filter (coprime a)).card = totient a :=
begin
rw [totient, filter_Ico_card_eq_of_periodic, count_eq_card_filter_range],
exact periodic_coprime a,
end
lemma Ico_filter_coprime_le {a : ℕ} (k n : ℕ) (a_pos : 0 < a) :
((Ico k (k + n)).filter (coprime a)).card ≤ totient a * (n / a + 1) :=
begin
conv_lhs { rw ←nat.mod_add_div n a },
induction n / a with i ih,
{ rw ←filter_coprime_Ico_eq_totient a k,
simp only [add_zero, mul_one, mul_zero, le_of_lt (mod_lt n a_pos)],
mono,
refine monotone_filter_left a.coprime _,
simp only [finset.le_eq_subset],
exact Ico_subset_Ico rfl.le (add_le_add_left (le_of_lt (mod_lt n a_pos)) k), },
simp only [mul_succ],
simp_rw ←add_assoc at ih ⊢,
calc (filter a.coprime (Ico k (k + n % a + a * i + a))).card
= (filter a.coprime (Ico k (k + n % a + a * i)
∪ Ico (k + n % a + a * i) (k + n % a + a * i + a))).card :
begin
congr,
rw Ico_union_Ico_eq_Ico,
rw add_assoc,
exact le_self_add,
exact le_self_add,
end
... ≤ (filter a.coprime (Ico k (k + n % a + a * i))).card + a.totient :
begin
rw [filter_union, ←filter_coprime_Ico_eq_totient a (k + n % a + a * i)],
apply card_union_le,
end
... ≤ a.totient * i + a.totient + a.totient : add_le_add_right ih (totient a),
end
open zmod
/-- Note this takes an explicit `fintype ((zmod n)ˣ)` argument to avoid trouble with instance
diamonds. -/
@[simp] lemma _root_.zmod.card_units_eq_totient (n : ℕ) [ne_zero n] [fintype ((zmod n)ˣ)] :
fintype.card ((zmod n)ˣ) = φ n :=
calc fintype.card ((zmod n)ˣ) = fintype.card {x : zmod n // x.val.coprime n} :
fintype.card_congr zmod.units_equiv_coprime
... = φ n :
begin
unfreezingI { obtain ⟨m, rfl⟩ : ∃ m, n = m + 1 := exists_eq_succ_of_ne_zero ne_zero.out },
simp only [totient, finset.card_eq_sum_ones, fintype.card_subtype, finset.sum_filter,
← fin.sum_univ_eq_sum_range, @nat.coprime_comm (m + 1)],
refl
end
lemma totient_even {n : ℕ} (hn : 2 < n) : even n.totient :=
begin
haveI : fact (1 < n) := ⟨one_lt_two.trans hn⟩,
haveI : ne_zero n := ne_zero.of_gt hn,
suffices : 2 = order_of (-1 : (zmod n)ˣ),
{ rw [← zmod.card_units_eq_totient, even_iff_two_dvd, this], exact order_of_dvd_card_univ },
rw [←order_of_units, units.coe_neg_one, order_of_neg_one, ring_char.eq (zmod n) n, if_neg hn.ne'],
end
lemma totient_mul {m n : ℕ} (h : m.coprime n) : φ (m * n) = φ m * φ n :=
if hmn0 : m * n = 0
then by cases nat.mul_eq_zero.1 hmn0 with h h;
simp only [totient_zero, mul_zero, zero_mul, h]
else
begin
haveI : ne_zero (m * n) := ⟨hmn0⟩,
haveI : ne_zero m := ⟨left_ne_zero_of_mul hmn0⟩,
haveI : ne_zero n := ⟨right_ne_zero_of_mul hmn0⟩,
simp only [← zmod.card_units_eq_totient],
rw [fintype.card_congr (units.map_equiv (zmod.chinese_remainder h).to_mul_equiv).to_equiv,
fintype.card_congr (@mul_equiv.prod_units (zmod m) (zmod n) _ _).to_equiv,
fintype.card_prod]
end
/-- For `d ∣ n`, the totient of `n/d` equals the number of values `k < n` such that `gcd n k = d` -/
lemma totient_div_of_dvd {n d : ℕ} (hnd : d ∣ n) :
φ (n/d) = (filter (λ (k : ℕ), n.gcd k = d) (range n)).card :=
begin
rcases d.eq_zero_or_pos with rfl | hd0, { simp [eq_zero_of_zero_dvd hnd] },
rcases hnd with ⟨x, rfl⟩,
rw nat.mul_div_cancel_left x hd0,
apply finset.card_congr (λ k _, d * k),
{ simp only [mem_filter, mem_range, and_imp, coprime],
refine λ a ha1 ha2, ⟨(mul_lt_mul_left hd0).2 ha1, _⟩,
rw [gcd_mul_left, ha2, mul_one] },
{ simp [hd0.ne'] },
{ simp only [mem_filter, mem_range, exists_prop, and_imp],
refine λ b hb1 hb2, _,
have : d ∣ b, { rw ←hb2, apply gcd_dvd_right },
rcases this with ⟨q, rfl⟩,
refine ⟨q, ⟨⟨(mul_lt_mul_left hd0).1 hb1, _⟩, rfl⟩⟩,
rwa [gcd_mul_left, mul_right_eq_self_iff hd0] at hb2 },
end
lemma sum_totient (n : ℕ) : n.divisors.sum φ = n :=
begin
rcases n.eq_zero_or_pos with rfl | hn, { simp },
rw ←sum_div_divisors n φ,
have : n = ∑ (d : ℕ) in n.divisors, (filter (λ (k : ℕ), n.gcd k = d) (range n)).card,
{ nth_rewrite_lhs 0 ←card_range n,
refine card_eq_sum_card_fiberwise (λ x hx, mem_divisors.2 ⟨_, hn.ne'⟩),
apply gcd_dvd_left },
nth_rewrite_rhs 0 this,
exact sum_congr rfl (λ x hx, totient_div_of_dvd (dvd_of_mem_divisors hx)),
end
lemma sum_totient' (n : ℕ) : ∑ m in (range n.succ).filter (∣ n), φ m = n :=
begin
convert sum_totient _ using 1,
simp only [nat.divisors, sum_filter, range_eq_Ico],
rw sum_eq_sum_Ico_succ_bot; simp
end
/-- When `p` is prime, then the totient of `p ^ (n + 1)` is `p ^ n * (p - 1)` -/
lemma totient_prime_pow_succ {p : ℕ} (hp : p.prime) (n : ℕ) :
φ (p ^ (n + 1)) = p ^ n * (p - 1) :=
calc φ (p ^ (n + 1))
= ((range (p ^ (n + 1))).filter (coprime (p ^ (n + 1)))).card :
totient_eq_card_coprime _
... = (range (p ^ (n + 1)) \ ((range (p ^ n)).image (* p))).card :
congr_arg card begin
rw [sdiff_eq_filter],
apply filter_congr,
simp only [mem_range, mem_filter, coprime_pow_left_iff n.succ_pos,
mem_image, not_exists, hp.coprime_iff_not_dvd],
intros a ha,
split,
{ rintros hap b _ rfl,
exact hap (dvd_mul_left _ _) },
{ rintros h ⟨b, rfl⟩,
rw [pow_succ] at ha,
exact h b (lt_of_mul_lt_mul_left ha (zero_le _)) (mul_comm _ _) }
end
... = _ :
have h1 : function.injective (* p),
from mul_left_injective₀ hp.ne_zero,
have h2 : (range (p ^ n)).image (* p) ⊆ range (p ^ (n + 1)),
from λ a, begin
simp only [mem_image, mem_range, exists_imp_distrib],
rintros b h rfl,
rw [pow_succ'],
exact (mul_lt_mul_right hp.pos).2 h
end,
begin
rw [card_sdiff h2, card_image_of_inj_on (h1.inj_on _), card_range,
card_range, ← one_mul (p ^ n), pow_succ, ← tsub_mul,
one_mul, mul_comm]
end
/-- When `p` is prime, then the totient of `p ^ n` is `p ^ (n - 1) * (p - 1)` -/
lemma totient_prime_pow {p : ℕ} (hp : p.prime) {n : ℕ} (hn : 0 < n) :
φ (p ^ n) = p ^ (n - 1) * (p - 1) :=
by rcases exists_eq_succ_of_ne_zero (pos_iff_ne_zero.1 hn) with ⟨m, rfl⟩;
exact totient_prime_pow_succ hp _
lemma totient_prime {p : ℕ} (hp : p.prime) : φ p = p - 1 :=
by rw [← pow_one p, totient_prime_pow hp]; simp
lemma totient_eq_iff_prime {p : ℕ} (hp : 0 < p) : p.totient = p - 1 ↔ p.prime :=
begin
refine ⟨λ h, _, totient_prime⟩,
replace hp : 1 < p,
{ apply lt_of_le_of_ne,
{ rwa succ_le_iff },
{ rintro rfl,
rw [totient_one, tsub_self] at h,
exact one_ne_zero h } },
rw [totient_eq_card_coprime, range_eq_Ico, ←Ico_insert_succ_left hp.le, finset.filter_insert,
if_neg (not_coprime_of_dvd_of_dvd hp (dvd_refl p) (dvd_zero p)), ←nat.card_Ico 1 p] at h,
refine p.prime_of_coprime hp (λ n hn hnz, finset.filter_card_eq h n $ finset.mem_Ico.mpr ⟨_, hn⟩),
rwa [succ_le_iff, pos_iff_ne_zero],
end
lemma card_units_zmod_lt_sub_one {p : ℕ} (hp : 1 < p) [fintype ((zmod p)ˣ)] :
fintype.card ((zmod p)ˣ) ≤ p - 1 :=
begin
haveI : ne_zero p := ⟨(pos_of_gt hp).ne'⟩,
rw zmod.card_units_eq_totient p,
exact nat.le_pred_of_lt (nat.totient_lt p hp),
end
lemma prime_iff_card_units (p : ℕ) [fintype ((zmod p)ˣ)] :
p.prime ↔ fintype.card ((zmod p)ˣ) = p - 1 :=
begin
casesI eq_zero_or_ne_zero p with hp hp,
{ substI hp,
simp only [zmod, not_prime_zero, false_iff, zero_tsub],
-- the substI created an non-defeq but subsingleton instance diamond; resolve it
suffices : fintype.card ℤˣ ≠ 0, { convert this },
simp },
rw [zmod.card_units_eq_totient, nat.totient_eq_iff_prime $ ne_zero.pos p],
end
@[simp] lemma totient_two : φ 2 = 1 :=
(totient_prime prime_two).trans rfl
lemma totient_eq_one_iff : ∀ {n : ℕ}, n.totient = 1 ↔ n = 1 ∨ n = 2
| 0 := by simp
| 1 := by simp
| 2 := by simp
| (n+3) :=
begin
have : 3 ≤ n + 3 := le_add_self,
simp only [succ_succ_ne_one, false_or],
exact ⟨λ h, not_even_one.elim $ h ▸ totient_even this, by rintro ⟨⟩⟩,
end
/-! ### Euler's product formula for the totient function
We prove several different statements of this formula. -/
/-- Euler's product formula for the totient function. -/
theorem totient_eq_prod_factorization {n : ℕ} (hn : n ≠ 0) :
φ n = n.factorization.prod (λ p k, p ^ (k - 1) * (p - 1)) :=
begin
rw multiplicative_factorization φ @totient_mul totient_one hn,
apply finsupp.prod_congr (λ p hp, _),
have h := zero_lt_iff.mpr (finsupp.mem_support_iff.mp hp),
rw [totient_prime_pow (prime_of_mem_factorization hp) h],
end
/-- Euler's product formula for the totient function. -/
theorem totient_mul_prod_factors (n : ℕ) :
φ n * ∏ p in n.factors.to_finset, p = n * ∏ p in n.factors.to_finset, (p - 1) :=
begin
by_cases hn : n = 0, { simp [hn] },
rw totient_eq_prod_factorization hn,
nth_rewrite 2 ←factorization_prod_pow_eq_self hn,
simp only [←prod_factorization_eq_prod_factors, ←finsupp.prod_mul],
refine finsupp.prod_congr (λ p hp, _),
rw [finsupp.mem_support_iff, ← zero_lt_iff] at hp,
rw [mul_comm, ←mul_assoc, ←pow_succ, nat.sub_add_cancel hp],
end
/-- Euler's product formula for the totient function. -/
theorem totient_eq_div_factors_mul (n : ℕ) :
φ n = n / (∏ p in n.factors.to_finset, p) * (∏ p in n.factors.to_finset, (p - 1)) :=
begin
rw [← mul_div_left n.totient, totient_mul_prod_factors, mul_comm,
nat.mul_div_assoc _ (prod_prime_factors_dvd n), mul_comm],
simpa [prod_factorization_eq_prod_factors] using prod_pos (λ p, pos_of_mem_factorization),
end
/-- Euler's product formula for the totient function. -/
theorem totient_eq_mul_prod_factors (n : ℕ) :
(φ n : ℚ) = n * ∏ p in n.factors.to_finset, (1 - p⁻¹) :=
begin
by_cases hn : n = 0, { simp [hn] },
have hn' : (n : ℚ) ≠ 0, { simp [hn] },
have hpQ : ∏ p in n.factors.to_finset, (p : ℚ) ≠ 0,
{ rw [←cast_prod, cast_ne_zero, ←zero_lt_iff, ←prod_factorization_eq_prod_factors],
exact prod_pos (λ p hp, pos_of_mem_factorization hp) },
simp only [totient_eq_div_factors_mul n, prod_prime_factors_dvd n, cast_mul, cast_prod,
cast_div_char_zero, mul_comm_div, mul_right_inj' hn', div_eq_iff hpQ, ←prod_mul_distrib],
refine prod_congr rfl (λ p hp, _),
have hp := pos_of_mem_factors (list.mem_to_finset.mp hp),
have hp' : (p : ℚ) ≠ 0 := cast_ne_zero.mpr hp.ne.symm,
rw [sub_mul, one_mul, mul_comm, mul_inv_cancel hp', cast_pred hp],
end
lemma totient_gcd_mul_totient_mul (a b : ℕ) : φ (a.gcd b) * φ (a * b) = φ a * φ b * (a.gcd b) :=
begin
have shuffle : ∀ a1 a2 b1 b2 c1 c2 : ℕ, b1 ∣ a1 → b2 ∣ a2 →
(a1/b1 * c1) * (a2/b2 * c2) = (a1*a2)/(b1*b2) * (c1*c2),
{ intros a1 a2 b1 b2 c1 c2 h1 h2,
calc
(a1/b1 * c1) * (a2/b2 * c2) = ((a1/b1) * (a2/b2)) * (c1*c2) : by apply mul_mul_mul_comm
... = (a1*a2)/(b1*b2) * (c1*c2) : by { congr' 1, exact div_mul_div_comm h1 h2 } },
simp only [totient_eq_div_factors_mul],
rw [shuffle, shuffle],
rotate, repeat { apply prod_prime_factors_dvd },
{ simp only [prod_factors_gcd_mul_prod_factors_mul],
rw [eq_comm, mul_comm, ←mul_assoc, ←nat.mul_div_assoc],
exact mul_dvd_mul (prod_prime_factors_dvd a) (prod_prime_factors_dvd b) }
end
lemma totient_super_multiplicative (a b : ℕ) : φ a * φ b ≤ φ (a * b) :=
begin
let d := a.gcd b,
rcases (zero_le a).eq_or_lt with rfl | ha0, { simp },
have hd0 : 0 < d, from nat.gcd_pos_of_pos_left _ ha0,
rw [←mul_le_mul_right hd0, ←totient_gcd_mul_totient_mul a b, mul_comm],
apply mul_le_mul_left' (nat.totient_le d),
end
lemma totient_dvd_of_dvd {a b : ℕ} (h : a ∣ b) : φ a ∣ φ b :=
begin
rcases eq_or_ne a 0 with rfl | ha0, { simp [zero_dvd_iff.1 h] },
rcases eq_or_ne b 0 with rfl | hb0, { simp },
have hab' : a.factorization.support ⊆ b.factorization.support,
{ intro p,
simp only [support_factorization, list.mem_to_finset],
apply factors_subset_of_dvd h hb0 },
rw [totient_eq_prod_factorization ha0, totient_eq_prod_factorization hb0],
refine finsupp.prod_dvd_prod_of_subset_of_dvd hab' (λ p hp, mul_dvd_mul _ dvd_rfl),
exact pow_dvd_pow p (tsub_le_tsub_right ((factorization_le_iff_dvd ha0 hb0).2 h p) 1),
end
lemma totient_mul_of_prime_of_dvd {p n : ℕ} (hp : p.prime) (h : p ∣ n) :
(p * n).totient = p * n.totient :=
begin
have h1 := totient_gcd_mul_totient_mul p n,
rw [(gcd_eq_left h), mul_assoc] at h1,
simpa [(totient_pos hp.pos).ne', mul_comm] using h1,
end
lemma totient_mul_of_prime_of_not_dvd {p n : ℕ} (hp : p.prime) (h : ¬ p ∣ n) :
(p * n).totient = (p - 1) * n.totient :=
begin
rw [totient_mul _, totient_prime hp],
simpa [h] using coprime_or_dvd_of_prime hp n,
end
end nat
|
c0694961da80bccdfa9a74c36259be5bd4d019cd | 682dc1c167e5900ba3168b89700ae1cf501cfa29 | /src/basicmodal/syntax/syntaxlemmas.lean | ec300bc407dc3fd9cd1899b9441ddec92eaf622d | [] | no_license | paulaneeley/modal | 834558c87f55cdd6d8a29bb46c12f4d1de3239bc | ee5d149d4ecb337005b850bddf4453e56a5daf04 | refs/heads/master | 1,675,911,819,093 | 1,609,785,144,000 | 1,609,785,144,000 | 270,388,715 | 13 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 7,316 | lean | /-
Copyright (c) 2021 Paula Neeley. All rights reserved.
Author: Paula Neeley
-/
import basicmodal.language basicmodal.syntax.syntax data.set.basic
local attribute [instance] classical.prop_decidable
open prfK
---------------------- Helper Lemmas ----------------------
lemma iden {Γ : ctx} {φ : form} :
prfK Γ (φ ⊃ φ) :=
begin
exact mp (mp (@pl2 _ φ (φ ⊃ φ) φ) pl1) pl1
end
lemma prtrue {Γ : ctx} : prfK Γ ⊤ := iden
lemma weak {Γ : ctx} {φ ψ : form} :
prfK Γ φ → prfK (Γ ∪ ψ) φ :=
begin
intro h,
induction h,
{apply ax, exact (set.mem_insert_of_mem _ h_h)},
{exact pl1},
{exact pl2},
{exact pl3},
{exact pl4},
{exact pl5},
{exact pl6},
{exact pl7},
{exact kdist},
{apply mp,
{exact h_ih_hpq},
{exact h_ih_hp}},
{exact nec h_ih }
end
lemma pr {Γ : ctx} {φ : form} :
prfK (Γ ∪ φ) φ :=
begin
apply ax;
apply or.intro_left;
simp
end
lemma cut {Γ : ctx} {φ ψ χ : form} :
prfK Γ (φ ⊃ ψ) → prfK Γ (ψ ⊃ χ) → prfK Γ (φ ⊃ χ) :=
begin
intros h1 h2,
exact mp (mp pl2 (mp pl1 h2)) h1
end
lemma conv_deduction {Γ : ctx} {φ ψ : form} :
prfK Γ (φ ⊃ ψ) → prfK (Γ ∪ φ) ψ :=
begin
intro h,
exact mp (weak h) pr
end
lemma hs1 {Γ : ctx} {φ ψ χ : form} :
prfK Γ ((ψ ⊃ χ) ⊃ ((φ ⊃ ψ) ⊃ (φ ⊃ χ))) :=
begin
exact (mp (mp pl2 (mp pl1 pl2)) pl1)
end
lemma likemp {Γ : ctx} {φ ψ : form} :
prfK Γ (φ ⊃ ((φ ⊃ ψ) ⊃ ψ)) :=
begin
exact (mp (mp hs1 (mp pl2 iden)) pl1)
end
lemma dne {Γ : ctx} {φ : form} :
prfK Γ ((¬¬φ) ⊃ φ) :=
begin
have h1 : prfK Γ (φ ⊃ (φ ⊃ φ)), from pl1,
exact (cut (cut pl1 (cut pl7 pl7)) (mp likemp h1))
end
lemma dni {Γ : ctx} {φ : form} : prfK Γ (φ ⊃ ¬¬φ) :=
begin
exact mp pl7 dne
end
lemma imp_if_imp_imp {Γ : ctx} {φ ψ χ : form} : prfK Γ (φ ⊃ χ) → prfK Γ (φ ⊃ (ψ ⊃ χ)) :=
begin
intro h1,
exact mp (mp pl2 (mp pl1 pl1)) h1
end
lemma cut1 {Γ : ctx} {φ ψ χ θ : form} :
prfK Γ (θ ⊃ (φ ⊃ ψ)) → prfK Γ (ψ ⊃ χ) → prfK Γ (θ ⊃ (φ ⊃ χ)) :=
begin
intros h1 h2,
exact cut h1 (mp pl2 (mp pl1 h2))
end
lemma imp_switch {Γ : ctx} {φ ψ χ : form} : prfK Γ (φ ⊃ (ψ ⊃ χ)) → prfK Γ (ψ ⊃ (φ ⊃ χ)) :=
begin
intro h1,
exact mp (mp pl2 (mp pl1 (mp pl2 h1))) pl1
end
lemma l2 {Γ : ctx} {φ ψ χ : form} : prfK Γ ((φ ⊃ (ψ ⊃ χ)) ⊃ (ψ ⊃ (φ ⊃ χ))) :=
begin
exact (mp (mp pl2 (cut pl2 hs1)) (mp pl1 pl1))
end
lemma hs2 {Γ : ctx} {φ ψ χ : form} :
prfK Γ ((φ ⊃ ψ) ⊃ ((ψ ⊃ χ) ⊃ (φ ⊃ χ))) :=
begin
exact (mp l2 hs1)
end
lemma cut2 {Γ : ctx} {φ ψ χ θ : form} :
prfK Γ (φ ⊃ ψ) → prfK Γ (θ ⊃ (ψ ⊃ χ)) → prfK Γ (θ ⊃ (φ ⊃ χ)) :=
begin
intros h1 h2,
exact imp_switch (cut h1 (imp_switch h2))
end
lemma double_imp {Γ : ctx} {φ ψ : form} :
prfK Γ ((φ ⊃ (φ ⊃ ψ)) ⊃ (φ ⊃ ψ)) :=
begin
exact mp pl2 (imp_switch iden)
end
lemma imp_imp_iff_imp {Γ : ctx} {θ φ ψ : form} :
prfK Γ (θ ⊃ (φ ⊃ (φ ⊃ ψ))) ↔ prfK Γ (θ ⊃ (φ ⊃ ψ)) :=
begin
split,
{intro h1,
exact cut h1 double_imp},
{intro h1,
exact cut h1 pl1}
end
lemma imp_shift {Γ : ctx} {θ φ ψ χ : form} :
prfK Γ (θ ⊃ (φ ⊃ (ψ ⊃ χ))) ↔ prfK Γ (θ ⊃ (ψ ⊃ (φ ⊃ χ))) :=
begin
split,
repeat {intro h1, exact cut h1 (cut2 pl1 pl2)}
end
lemma left_and_imp {Γ : ctx} {φ ψ χ : form} :
prfK Γ (ψ ⊃ ((φ & ψ) ⊃ χ)) → prfK Γ ((φ & ψ) ⊃ χ) :=
begin
intro h1,
exact mp double_imp (cut pl6 h1)
end
lemma and_right_imp {Γ : ctx} {φ ψ χ : form} :
prfK Γ ((φ & ψ) ⊃ χ) ↔ prfK Γ (ψ ⊃ (φ ⊃ χ)) :=
begin
split,
{intro h1,
exact mp (cut2 pl1 pl2) (cut1 pl4 h1)},
intro h1,
exact left_and_imp (cut2 pl5 h1)
end
lemma not_and_subst {φ ψ χ : form} {Γ : ctx} :
prfK Γ (φ ↔ ψ) → (prfK Γ ¬(χ & φ) ↔ prfK Γ ¬(χ & ψ)) :=
begin
intro h1, split,
{intro h2,
exact mp (mp pl3 (mp pl1 h2)) (cut dne (mp double_imp (cut2 (cut pl6 (mp pl6 h1))
(cut pl5 pl4))))},
{intro h2,
exact mp (mp pl3 (mp pl1 h2)) (cut dne (mp double_imp (cut2 (cut pl6 (mp pl5 h1))
(cut pl5 pl4))))},
end
lemma not_contra {Γ : ctx} {φ : form} :
prfK Γ ¬(φ & ¬φ) :=
begin
exact mp (mp pl3 (cut dne pl6)) (cut dne pl5)
end
lemma phi_and_true {Γ : ctx} {φ : form} : prfK Γ ((φ&¬⊥) ↔ φ) :=
begin
exact (mp (mp pl4 pl5) (mp (imp_switch pl4) prtrue))
end
lemma imp_and_and_imp {Γ : ctx} {φ ψ χ θ : form} :
prfK Γ (((φ ⊃ ψ) & (χ ⊃ θ))) → prfK Γ (((φ & χ) ⊃ (ψ & θ))) :=
begin
intro h,
exact (mp double_imp (cut (cut pl5 (mp pl5 h)) (cut2 (cut pl6 (mp pl6 h)) pl4)))
end
lemma not_contra_equiv_true {Γ : ctx} {φ : form} :
prfK Γ (¬(φ & ¬φ) ↔ ⊤) :=
begin
exact (mp (mp pl4 (mp pl1 prtrue)) (mp pl1 not_contra))
end
lemma contrapos {Γ : ctx} {φ ψ : form} :
prfK Γ ((¬ψ) ⊃ (¬φ)) ↔ prfK Γ (φ ⊃ ψ) :=
begin
split,
intro h1,
exact mp pl7 h1,
intro h1,
exact mp (cut (cut (mp hs1 dni) (mp hs2 dne)) pl7) h1,
end
lemma iff_not {Γ : ctx} {φ ψ : form} :
prfK Γ (φ ↔ ψ) → prfK Γ (¬ψ ↔ ¬φ) :=
begin
intro h1,
have h2 : prfK Γ (φ ⊃ ψ), from mp pl5 h1,
have h3 : prfK Γ (ψ ⊃ φ), from mp pl6 h1,
rw ←contrapos at h2,
rw ←contrapos at h3,
exact (mp (mp pl4 h2) h3)
end
lemma contra_equiv_false {Γ : ctx} {φ : form} :
prfK Γ ((φ & ¬φ) ↔ ⊥) :=
begin
have h1 := iff_not not_contra_equiv_true,
exact (mp (mp pl4 (cut dni (cut (mp pl6 h1) dne))) (cut dni (cut (mp pl5 h1) dne)))
end
lemma and_switch {Γ : ctx} {φ ψ : form} : prfK Γ ((φ & ψ) ↔ (ψ & φ)) :=
begin
exact (mp (mp pl4 (mp double_imp (cut pl5 (imp_switch (cut pl6 pl4)))))
(mp double_imp (cut pl5 (imp_switch (cut pl6 pl4)))))
end
lemma and_commute {Γ : ctx} {φ ψ χ : form} : prfK Γ (((φ & ψ) & χ) ↔ (φ & (ψ & χ))) :=
begin
exact mp (mp pl4 (mp double_imp (imp_imp_iff_imp.mp
(cut (cut pl5 pl6) (cut2 pl6 (cut1 pl4 (imp_switch (cut (cut pl5 pl5) pl4))))))))
(mp double_imp (imp_imp_iff_imp.mp (cut (cut pl6 pl5)
(imp_switch (cut pl5 (cut1 pl4 (cut2 (cut pl6 pl6) pl4)))))))
end
lemma imp_and_imp {Γ : ctx} {φ ψ χ : form} :
prfK Γ (φ ⊃ ψ) → prfK Γ ((χ & φ) ⊃ (χ & ψ)) :=
begin
intros h1,
exact imp_and_and_imp (mp (mp pl4 iden) h1)
end
lemma demorgans {Γ : ctx} {φ ψ : form} : prfK Γ (¬(φ & ψ)) ↔ prfK Γ (φ ⊃ ¬ψ) :=
begin
split,
intro h1,
exact (and_right_imp.mp (mp (contrapos.mpr (mp pl5 and_switch)) h1)),
intro h1,
exact (mp (contrapos.mpr (mp pl5 and_switch)) (and_right_imp.mpr h1))
end
lemma explosion {Γ : ctx} {ψ : form} : prfK Γ (⊥ ⊃ ψ) :=
begin
apply contrapos.mp, exact (mp pl1 iden)
end
lemma exfalso {Γ : ctx} {φ ψ : form} : prfK Γ ((φ & ¬φ) ⊃ ψ) :=
begin
exact cut not_contra explosion
end
lemma box_dn {Γ : ctx} {φ : form} : prfK Γ ((¬□φ) ↔ ¬(□(¬¬φ))) :=
begin
exact mp (mp pl4 (contrapos.mpr (mp kdist (nec dne)))) (contrapos.mpr (mp kdist (nec dni)))
end
lemma dual_equiv1 {Γ : ctx} {φ : form} : prfK Γ ((□φ) ↔ (¬(◇(¬φ)))) :=
begin
exact mp (mp pl4 (cut (contrapos.mp (mp pl6 box_dn)) dni))
(cut dne (contrapos.mp (mp pl5 box_dn)))
end
lemma dual_equiv2 {Γ : ctx} {φ : form} : prfK Γ ((¬(□¬φ)) ↔ (◇φ)) :=
begin
exact mp (mp pl4 iden) iden,
end
|
ea645635dc00bd2ffe5d50050f55fb46f47d3f52 | dfbb669f3f58ceb57cb207dcfab5726a07425b03 | /vscode-lean4/test/test-fixtures/multi/foo/lakefile.lean | c6899e54cb6c537c9f37d39a10a89ffbda8c95e4 | [
"Apache-2.0"
] | permissive | leanprover/vscode-lean4 | 8bcf7f06867b3c1d42007fe6da863a7a17444dbb | 6ef0bfa668bdeaad0979e6df10551d42fcc01094 | refs/heads/master | 1,692,247,771,767 | 1,691,608,804,000 | 1,691,608,804,000 | 325,845,305 | 64 | 24 | Apache-2.0 | 1,694,176,429,000 | 1,609,435,614,000 | TypeScript | UTF-8 | Lean | false | false | 194 | lean | import Lake
open Lake DSL
package foo {
-- add configuration options here
}
lean_lib Foo {
-- add library configuration options here
}
@[default_target]
lean_exe foo {
root := `Main
}
|
a0b7a7b1c4fae04d99782e04fc84e0224af69fc1 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/measure_theory/integral/integrable_on.lean | c36a42b963b08723825f58ddbcafdb097c8f48ad | [
"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 | 20,812 | lean | /-
Copyright (c) 2021 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Yury Kudryashov
-/
import measure_theory.function.l1_space
import analysis.normed_space.indicator_function
/-! # Functions integrable on a set and at a filter
We define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like
`integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`.
Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)`
saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable
at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite
at `l`.
-/
noncomputable theory
open set filter topological_space measure_theory function
open_locale classical topological_space interval big_operators filter ennreal measure_theory
variables {α β E F : Type*} [measurable_space α]
section
variables [topological_space β] {l l' : filter α} {f g : α → β} {μ ν : measure α}
/-- A function `f` is strongly measurable at a filter `l` w.r.t. a measure `μ` if it is
ae strongly measurable w.r.t. `μ.restrict s` for some `s ∈ l`. -/
def strongly_measurable_at_filter (f : α → β) (l : filter α) (μ : measure α . volume_tac) :=
∃ s ∈ l, ae_strongly_measurable f (μ.restrict s)
@[simp] lemma strongly_measurable_at_bot {f : α → β} : strongly_measurable_at_filter f ⊥ μ :=
⟨∅, mem_bot, by simp⟩
protected lemma strongly_measurable_at_filter.eventually (h : strongly_measurable_at_filter f l μ) :
∀ᶠ s in l.small_sets, ae_strongly_measurable f (μ.restrict s) :=
(eventually_small_sets' $ λ s t, ae_strongly_measurable.mono_set).2 h
protected lemma strongly_measurable_at_filter.filter_mono
(h : strongly_measurable_at_filter f l μ) (h' : l' ≤ l) :
strongly_measurable_at_filter f l' μ :=
let ⟨s, hsl, hs⟩ := h in ⟨s, h' hsl, hs⟩
protected lemma measure_theory.ae_strongly_measurable.strongly_measurable_at_filter
(h : ae_strongly_measurable f μ) :
strongly_measurable_at_filter f l μ :=
⟨univ, univ_mem, by rwa measure.restrict_univ⟩
lemma ae_strongly_measurable.strongly_measurable_at_filter_of_mem
{s} (h : ae_strongly_measurable f (μ.restrict s)) (hl : s ∈ l) :
strongly_measurable_at_filter f l μ :=
⟨s, hl, h⟩
protected lemma measure_theory.strongly_measurable.strongly_measurable_at_filter
(h : strongly_measurable f) :
strongly_measurable_at_filter f l μ :=
h.ae_strongly_measurable.strongly_measurable_at_filter
end
namespace measure_theory
section normed_group
lemma has_finite_integral_restrict_of_bounded [normed_group E] {f : α → E} {s : set α}
{μ : measure α} {C} (hs : μ s < ∞) (hf : ∀ᵐ x ∂(μ.restrict s), ∥f x∥ ≤ C) :
has_finite_integral f (μ.restrict s) :=
by haveI : is_finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩;
exact has_finite_integral_of_bounded hf
variables [normed_group E] {f g : α → E} {s t : set α} {μ ν : measure α}
/-- A function is `integrable_on` a set `s` if it is almost everywhere strongly measurable on `s`
and if the integral of its pointwise norm over `s` is less than infinity. -/
def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop :=
integrable f (μ.restrict s)
lemma integrable_on.integrable (h : integrable_on f s μ) :
integrable f (μ.restrict s) := h
@[simp] lemma integrable_on_empty : integrable_on f ∅ μ :=
by simp [integrable_on, integrable_zero_measure]
@[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ :=
by rw [integrable_on, measure.restrict_univ]
lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _
@[simp] lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ∞ :=
integrable_const_iff.trans $ by rw [measure.restrict_apply_univ]
lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) :
integrable_on f s μ :=
h.mono_measure $ measure.restrict_mono hs hμ
lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) :
integrable_on f s μ :=
h.mono hst le_rfl
lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) :
integrable_on f s μ :=
h.mono (subset.refl _) hμ
lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) :
integrable_on f s μ :=
h.integrable.mono_measure $ measure.restrict_mono_ae hst
lemma integrable_on.congr_set_ae (h : integrable_on f t μ) (hst : s =ᵐ[μ] t) :
integrable_on f s μ :=
h.mono_set_ae hst.le
lemma integrable_on.congr_fun' (h : integrable_on f s μ) (hst : f =ᵐ[μ.restrict s] g) :
integrable_on g s μ :=
integrable.congr h hst
lemma integrable_on.congr_fun (h : integrable_on f s μ) (hst : eq_on f g s)
(hs : measurable_set s) :
integrable_on g s μ :=
h.congr_fun' ((ae_restrict_iff' hs).2 (eventually_of_forall hst))
lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ :=
h.mono_measure $ measure.restrict_le_self
lemma integrable.integrable_on' (h : integrable f (μ.restrict s)) : integrable_on f s μ :=
h
lemma integrable_on.restrict (h : integrable_on f s μ) (hs : measurable_set s) :
integrable_on f s (μ.restrict t) :=
by { rw [integrable_on, measure.restrict_restrict hs], exact h.mono_set (inter_subset_left _ _) }
lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ :=
h.mono_set $ subset_union_left _ _
lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ :=
h.mono_set $ subset_union_right _ _
lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) :
integrable_on f (s ∪ t) μ :=
(hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _
@[simp] lemma integrable_on_union :
integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ :=
⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩
@[simp] lemma integrable_on_singleton_iff {x : α} [measurable_singleton_class α] :
integrable_on f {x} μ ↔ f x = 0 ∨ μ {x} < ∞ :=
begin
have : f =ᵐ[μ.restrict {x}] (λ y, f x),
{ filter_upwards [ae_restrict_mem (measurable_set_singleton x)] with _ ha,
simp only [mem_singleton_iff.1 ha], },
rw [integrable_on, integrable_congr this, integrable_const_iff],
simp,
end
@[simp] lemma integrable_on_finite_Union {s : set β} (hs : s.finite)
{t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ :=
begin
apply hs.induction_on,
{ simp },
{ intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] }
end
@[simp] lemma integrable_on_finset_Union {s : finset β} {t : β → set α} :
integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ :=
integrable_on_finite_Union s.finite_to_set
@[simp] lemma integrable_on_fintype_Union [fintype β] {t : β → set α} :
integrable_on f (⋃ i, t i) μ ↔ ∀ i, integrable_on f (t i) μ :=
by simpa using @integrable_on_finset_Union _ _ _ _ _ f μ finset.univ t
lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) :
integrable_on f s (μ + ν) :=
by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν }
@[simp] lemma integrable_on_add_measure :
integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν :=
⟨λ h, ⟨h.mono_measure (measure.le_add_right le_rfl),
h.mono_measure (measure.le_add_left le_rfl)⟩,
λ h, h.1.add_measure h.2⟩
lemma _root_.measurable_embedding.integrable_on_map_iff [measurable_space β] {e : α → β}
(he : measurable_embedding e) {f : β → E} {μ : measure α} {s : set β} :
integrable_on f s (measure.map e μ) ↔ integrable_on (f ∘ e) (e ⁻¹' s) μ :=
by simp only [integrable_on, he.restrict_map, he.integrable_map_iff]
lemma integrable_on_map_equiv [measurable_space β] (e : α ≃ᵐ β) {f : β → E} {μ : measure α}
{s : set β} :
integrable_on f s (measure.map e μ) ↔ integrable_on (f ∘ e) (e ⁻¹' s) μ :=
by simp only [integrable_on, e.restrict_map, integrable_map_equiv e]
lemma measure_preserving.integrable_on_comp_preimage [measurable_space β] {e : α → β} {ν}
(h₁ : measure_preserving e μ ν) (h₂ : measurable_embedding e) {f : β → E} {s : set β} :
integrable_on (f ∘ e) (e ⁻¹' s) μ ↔ integrable_on f s ν :=
(h₁.restrict_preimage_emb h₂ s).integrable_comp_emb h₂
lemma measure_preserving.integrable_on_image [measurable_space β] {e : α → β} {ν}
(h₁ : measure_preserving e μ ν) (h₂ : measurable_embedding e) {f : β → E} {s : set α} :
integrable_on f (e '' s) ν ↔ integrable_on (f ∘ e) s μ :=
((h₁.restrict_image_emb h₂ s).integrable_comp_emb h₂).symm
lemma integrable_indicator_iff (hs : measurable_set s) :
integrable (indicator s f) μ ↔ integrable_on f s μ :=
by simp [integrable_on, integrable, has_finite_integral, nnnorm_indicator_eq_indicator_nnnorm,
ennreal.coe_indicator, lintegral_indicator _ hs, ae_strongly_measurable_indicator_iff hs]
lemma integrable_on.indicator (h : integrable_on f s μ) (hs : measurable_set s) :
integrable (indicator s f) μ :=
(integrable_indicator_iff hs).2 h
lemma integrable.indicator (h : integrable f μ) (hs : measurable_set s) :
integrable (indicator s f) μ :=
h.integrable_on.indicator hs
lemma integrable_indicator_const_Lp {E} [normed_group E]
{p : ℝ≥0∞} {s : set α} (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : E) :
integrable (indicator_const_Lp p hs hμs c) μ :=
begin
rw [integrable_congr indicator_const_Lp_coe_fn, integrable_indicator_iff hs, integrable_on,
integrable_const_iff, lt_top_iff_ne_top],
right,
simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply] using hμs,
end
lemma integrable_on_iff_integable_of_support_subset {f : α → E} {s : set α}
(h1s : support f ⊆ s) (h2s : measurable_set s) :
integrable_on f s μ ↔ integrable f μ :=
begin
refine ⟨λ h, _, λ h, h.integrable_on⟩,
rwa [← indicator_eq_self.2 h1s, integrable_indicator_iff h2s]
end
lemma integrable_on_Lp_of_measure_ne_top {E} [normed_group E]
{p : ℝ≥0∞} {s : set α} (f : Lp E p μ) (hp : 1 ≤ p) (hμs : μ s ≠ ∞) :
integrable_on f s μ :=
begin
refine mem_ℒp_one_iff_integrable.mp _,
have hμ_restrict_univ : (μ.restrict s) set.univ < ∞,
by simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply, lt_top_iff_ne_top],
haveI hμ_finite : is_finite_measure (μ.restrict s) := ⟨hμ_restrict_univ⟩,
exact ((Lp.mem_ℒp _).restrict s).mem_ℒp_of_exponent_le hp,
end
/-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some
set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.small_sets`. -/
def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) :=
∃ s ∈ l, integrable_on f s μ
variables {l l' : filter α}
protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) :
∀ᶠ s in l.small_sets, integrable_on f s μ :=
iff.mpr (eventually_small_sets' $ λ s t hst ht, ht.mono_set hst) h
lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) :
integrable_at_filter f l μ :=
let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩
lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) :
integrable_at_filter f (l ⊓ l') μ :=
hl.filter_mono inf_le_left
lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) :
integrable_at_filter f (l' ⊓ l) μ :=
hl.filter_mono inf_le_right
@[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} :
integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ :=
begin
refine ⟨_, λ h, h.filter_mono inf_le_left⟩,
rintros ⟨s, ⟨t, ht, u, hu, rfl⟩, hf⟩,
refine ⟨t, ht, _⟩,
refine hf.integrable.mono_measure (λ v hv, _),
simp only [measure.restrict_apply hv],
refine measure_mono_ae (mem_of_superset hu $ λ x hx, _),
exact λ ⟨hv, ht⟩, ⟨hv, ⟨ht, hx⟩⟩
end
alias integrable_at_filter.inf_ae_iff ↔ integrable_at_filter.of_inf_ae _
/-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded
above at `l`, then `f` is integrable at `l`. -/
lemma measure.finite_at_filter.integrable_at_filter {l : filter α} [is_measurably_generated l]
(hfm : strongly_measurable_at_filter f l μ) (hμ : μ.finite_at_filter l)
(hf : l.is_bounded_under (≤) (norm ∘ f)) :
integrable_at_filter f l μ :=
begin
obtain ⟨C, hC⟩ : ∃ C, ∀ᶠ s in l.small_sets, ∀ x ∈ s, ∥f x∥ ≤ C,
from hf.imp (λ C hC, eventually_small_sets.2 ⟨_, hC, λ t, id⟩),
rcases (hfm.eventually.and (hμ.eventually.and hC)).exists_measurable_mem_of_small_sets
with ⟨s, hsl, hsm, hfm, hμ, hC⟩,
refine ⟨s, hsl, ⟨hfm, has_finite_integral_restrict_of_bounded hμ _⟩⟩,
exact C,
rw [ae_restrict_eq hsm, eventually_inf_principal],
exact eventually_of_forall hC
end
lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae
{l : filter α} [is_measurably_generated l] (hfm : strongly_measurable_at_filter f l μ)
(hμ : μ.finite_at_filter l) {b} (hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) :
integrable_at_filter f l μ :=
(hμ.inf_of_left.integrable_at_filter (hfm.filter_mono inf_le_left)
hf.norm.is_bounded_under_le).of_inf_ae
alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ←
_root_.filter.tendsto.integrable_at_filter_ae
lemma measure.finite_at_filter.integrable_at_filter_of_tendsto {l : filter α}
[is_measurably_generated l] (hfm : strongly_measurable_at_filter f l μ)
(hμ : μ.finite_at_filter l) {b} (hf : tendsto f l (𝓝 b)) :
integrable_at_filter f l μ :=
hμ.integrable_at_filter hfm hf.norm.is_bounded_under_le
alias measure.finite_at_filter.integrable_at_filter_of_tendsto ←
_root_.filter.tendsto.integrable_at_filter
lemma integrable_add_of_disjoint {f g : α → E}
(h : disjoint (support f) (support g)) (hf : strongly_measurable f) (hg : strongly_measurable g) :
integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ :=
begin
refine ⟨λ hfg, ⟨_, _⟩, λ h, h.1.add h.2⟩,
{ rw ← indicator_add_eq_left h, exact hfg.indicator hf.measurable_set_support },
{ rw ← indicator_add_eq_right h, exact hfg.indicator hg.measurable_set_support }
end
end normed_group
end measure_theory
open measure_theory
variables [normed_group E]
/-- A function which is continuous on a set `s` is almost everywhere measurable with respect to
`μ.restrict s`. -/
lemma continuous_on.ae_measurable [topological_space α] [opens_measurable_space α]
[measurable_space β] [topological_space β] [borel_space β]
{f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) :
ae_measurable f (μ.restrict s) :=
begin
nontriviality α, inhabit α,
have : piecewise s f (λ _, f default) =ᵐ[μ.restrict s] f := piecewise_ae_eq_restrict hs,
refine ⟨piecewise s f (λ _, f default), _, this.symm⟩,
apply measurable_of_is_open,
assume t ht,
obtain ⟨u, u_open, hu⟩ : ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s :=
_root_.continuous_on_iff'.1 hf t ht,
rw [piecewise_preimage, set.ite, hu],
exact (u_open.measurable_set.inter hs).union ((measurable_const ht.measurable_set).diff hs)
end
/-- A function which is continuous on a separable set `s` is almost everywhere strongly measurable
with respect to `μ.restrict s`. -/
lemma continuous_on.ae_strongly_measurable_of_is_separable
[topological_space α] [pseudo_metrizable_space α] [opens_measurable_space α]
[topological_space β] [pseudo_metrizable_space β]
{f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s)
(h's : topological_space.is_separable s) :
ae_strongly_measurable f (μ.restrict s) :=
begin
letI := pseudo_metrizable_space_pseudo_metric α,
borelize β,
rw ae_strongly_measurable_iff_ae_measurable_separable,
refine ⟨hf.ae_measurable hs, f '' s, hf.is_separable_image h's, _⟩,
exact mem_of_superset (self_mem_ae_restrict hs) (subset_preimage_image _ _),
end
/-- A function which is continuous on a set `s` is almost everywhere strongly measurable with
respect to `μ.restrict s` when either the source space or the target space is second-countable. -/
lemma continuous_on.ae_strongly_measurable
[topological_space α] [topological_space β] [h : second_countable_topology_either α β]
[opens_measurable_space α] [pseudo_metrizable_space β]
{f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) :
ae_strongly_measurable f (μ.restrict s) :=
begin
borelize β,
refine ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨hf.ae_measurable hs, f '' s, _,
mem_of_superset (self_mem_ae_restrict hs) (subset_preimage_image _ _)⟩,
casesI h.out,
{ let f' : s → β := s.restrict f,
have A : continuous f' := continuous_on_iff_continuous_restrict.1 hf,
have B : is_separable (univ : set s) := is_separable_of_separable_space _,
convert is_separable.image B A using 1,
ext x,
simp },
{ exact is_separable_of_separable_space _ }
end
lemma continuous_on.integrable_at_nhds_within_of_is_separable
[topological_space α] [pseudo_metrizable_space α]
[opens_measurable_space α] {μ : measure α} [is_locally_finite_measure μ]
{a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ht : measurable_set t)
(h't : topological_space.is_separable t) (ha : a ∈ t) :
integrable_at_filter f (𝓝[t] a) μ :=
begin
haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _,
exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within,
hft.ae_strongly_measurable_of_is_separable ht h't⟩ (μ.finite_at_nhds_within _ _),
end
lemma continuous_on.integrable_at_nhds_within
[topological_space α] [second_countable_topology_either α E]
[opens_measurable_space α] {μ : measure α} [is_locally_finite_measure μ]
{a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ht : measurable_set t) (ha : a ∈ t) :
integrable_at_filter f (𝓝[t] a) μ :=
begin
haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _,
exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within, hft.ae_strongly_measurable ht⟩
(μ.finite_at_nhds_within _ _),
end
/-- If a function is continuous on an open set `s`, then it is strongly measurable at the filter
`𝓝 x` for all `x ∈ s` if either the source space or the target space is second-countable. -/
lemma continuous_on.strongly_measurable_at_filter [topological_space α]
[opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β]
[second_countable_topology_either α β] {f : α → β} {s : set α} {μ : measure α}
(hs : is_open s) (hf : continuous_on f s) :
∀ x ∈ s, strongly_measurable_at_filter f (𝓝 x) μ :=
λ x hx, ⟨s, is_open.mem_nhds hs hx, hf.ae_strongly_measurable hs.measurable_set⟩
lemma continuous_at.strongly_measurable_at_filter
[topological_space α] [opens_measurable_space α] [second_countable_topology_either α E]
{f : α → E} {s : set α} {μ : measure α} (hs : is_open s) (hf : ∀ x ∈ s, continuous_at f x) :
∀ x ∈ s, strongly_measurable_at_filter f (𝓝 x) μ :=
continuous_on.strongly_measurable_at_filter hs $ continuous_at.continuous_on hf
lemma continuous.strongly_measurable_at_filter [topological_space α] [opens_measurable_space α]
[topological_space β] [pseudo_metrizable_space β] [second_countable_topology_either α β]
{f : α → β} (hf : continuous f) (μ : measure α) (l : filter α) :
strongly_measurable_at_filter f l μ :=
hf.strongly_measurable.strongly_measurable_at_filter
/-- If a function is continuous on a measurable set `s`, then it is measurable at the filter
`𝓝[s] x` for all `x`. -/
lemma continuous_on.strongly_measurable_at_filter_nhds_within {α β : Type*} [measurable_space α]
[topological_space α] [opens_measurable_space α] [topological_space β] [pseudo_metrizable_space β]
[second_countable_topology_either α β] {f : α → β} {s : set α} {μ : measure α}
(hf : continuous_on f s) (hs : measurable_set s) (x : α) :
strongly_measurable_at_filter f (𝓝[s] x) μ :=
⟨s, self_mem_nhds_within, hf.ae_strongly_measurable hs⟩
|
25103d12030ba47ff290b3feffd1f94e7e8e770a | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /hott/init/axioms/funext.hlean | 110b876acccd2494d44923af4b1eeec9c7bf41fc | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 999 | hlean | -- Copyright (c) 2014 Microsoft Corporation. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Author: Jeremy Avigad, Jakob von Raumer
-- Ported from Coq HoTT
prelude
import ..path ..equiv
open eq
-- Funext
-- ------
-- Define function extensionality as a type class
inductive funext [class] : Type :=
mk : (Π (A : Type) (P : A → Type ) (f g : Π x, P x), is_equiv (@apD10 A P f g))
→ funext
namespace funext
universe variables l k
variables [F : funext.{l k}] {A : Type.{l}} {P : A → Type.{k}}
include F
protected definition ap [instance] (f g : Π x, P x) : is_equiv (@apD10 A P f g) :=
rec_on F (λ(H : Π A P f g, _), !H)
definition path_pi {f g : Π x, P x} : f ∼ g → f = g :=
is_equiv.inv (@apD10 A P f g)
omit F
definition path_pi2 [F : funext] {A B : Type} {P : A → B → Type}
(f g : Πx y, P x y) : (Πx y, f x y = g x y) → f = g :=
λ E, path_pi (λx, path_pi (E x))
end funext
|
162dcf908a9ee7e6ee4be1609ad86d8bc1d165fa | 8cd4726d66eec7673bcc0325fed07d5ba5bf17c4 | /hw7.lean | ca0f5f2efcab85a49722e5b295fbe70069940a4f | [] | no_license | justinqcai/CS2102 | 8c5fddedffa6147fedd4b6ee7d5d39fc21f0ddab | d309f0db3f1df52eb77206ee1e8665a3b49d7a0c | refs/heads/master | 1,590,108,991,894 | 1,557,610,044,000 | 1,557,610,044,000 | 186,064,169 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,841 | lean | /- Justin Cai, jc5pz -/
/-
Read, and if you have already read, then re-read, the
chapters in the notes on proofs of disjunctions and negations.
We have added some new material, especially under negation
elimination.
In proofs of bi-implications, use comments to mark the start of
the proofs of the implications in each direction. Label one as
"forward" the other other as "backward."
The collaboration policy for this homework is "no collaboration
allowed." You may study and discuss the underlying concepts with
anyone.
You may provide proofs in the style of your choice: term-style,
tactic style, or mixed. Yes, you can using tactic scripts within
terms and terms within tactic scripts. You may use any tactics
you know of. As a courtesy, we provide begin/end pairs, in case
you should want to use them. Otherwise you may delete them.
-/
/-
1. 15 points
-/
example : ∀ (P Q : Prop), P ∧ Q → P ∨ Q :=
begin
intros P Q,
assume paq,
have p := paq.left,
exact or.inl p,
end
/-
2. 15 points
-/
example :
∀ (P Q R : Prop), (P ∨ Q) → (Q ∨ R) → ¬ Q → (P ∧ R) :=
begin
intros P Q R,
assume poq,
assume qor,
assume nq,
cases poq with p q,
cases qor with q r,
contradiction,
exact and.intro p r,
contradiction,
end
/-
3. 15 points
-/
example :
∀ (P Q R : Prop), P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) :=
begin
intros P Q R,
apply iff.intro,
/- forward -/
assume paqor,
have p := paqor.1,
have qor := paqor.2,
cases qor with q r,
apply or.inl,
exact and.intro p q,
apply or.inr,
exact and.intro p r,
/- backward -/
assume paqopar,
cases paqopar with paq par,
have p := paq.1,
have q := paq.2,
exact and.intro p (or.inl q),
have p := par.1,
have r := par.2,
exact and.intro p (or.inr r),
end
/-
4. 10 points
-/
example : ∀ (P Q R : Prop), P → Q → R → ¬ Q → (Q ∨ ¬ Q) :=
begin
intros P Q R,
assume p,
assume q,
assume r,
assume nq,
contradiction,
end
open classical -- hint: you can now use em easily
/-
4a. 5 points. Write *your own* proof of this conjecture.
-/
example : ∀ (P Q : Prop), ¬ (P ∨ Q) ↔ ¬ P ∧ ¬ Q :=
begin
intros P Q,
apply iff.intro,
/- forward-/
assume npoq,
cases em P with p np,
have f : false := npoq (or.inl p),
exact false.elim f,
cases em Q with q nq,
have f : false := npoq (or.inr q),
exact false.elim f,
exact and.intro np nq,
/-backward-/
assume npanq,
assume npoq,
cases npoq with p q,
have np := npanq.left,
contradiction,
have nq := npanq.right,
contradiction,
end
/-
4b. 5 points. Is this theorem classically true in neither, one, or
both directions. Explain your answer in relation to your proof.
Answer:
This theorem is classically true in both directions. It's definitely
classically true in forward direction because it requires the use of em
(aka classical logic) for the proof to even work, and it's classically true
in backward direction because the backward proof is true in constructive
logic, making it also true in classical logic.
-/
/-
5. 5 points. Write *your own proof* of this conjecture.
-/
example : ∀ (P Q : Prop), ¬ (P ∧ Q) ↔ (¬ P ∨ ¬ Q) :=
begin
intros P Q,
apply iff.intro,
/- forward -/
assume npaq,
cases em P with p np,
cases em Q with q nq,
have f : false := npaq (and.intro p q),
exact false.elim f,
exact or.inr nq,
exact or.inl np,
/-backward-/
assume nponq,
assume paq,
cases nponq with np nq,
have p := paq.left,
have f : false := np p,
exact false.elim f,
have q := paq.right,
have f : false := nq q,
exact false.elim f,
end
/-
6. 10 points
-/
example : ∀ (P : Prop), (¬ ¬ P → P) ↔ (P ∨ ¬ P) :=
begin
intro P,
apply iff.intro,
/-forward-/
assume nnpp,
cases em P with p np,
exact or.inl p,
exact or.inr np,
/-backward-/
assume ponp,
assume nnp,
cases ponp with p np,
exact p,
contradiction,
end
/-
7. 5 points
Tranlate the preceding proposition into English,
referring explicitly to the principles of negation
elimination and excluded middle. Write your sentence
here:
The proposition states that for all P of type Prop, (P implies false
implies false implies P) implies ((P or P implies false) is true), and vice
versa.
1. Assumed P
2. Applied bi-implication introduction
3. Forward proof
a. Assumed not not P implies P
b. Used the law of excluded middle (which states that either P or not P
must be true) to create two cases for P to prove.
I must prove:
1. that if P is true then P or not P is true
2. and that if not P is true then P or not P is true
c. Since I am given a proof of P, I am able to apply the or introduction
rule for the left side (which is asking for a proof of P)
d. Since I am given a proof of not P, I am able to apply the or
introduction rule for the right side (which is asking for a proof of
not P)
4. Backward proof
a. Assumed P or not P is true
b. Assumed not not P is true
c. Created two cases for P or not P to prove.
I must prove:
1. If P is true, then P is true
2. If not P is true, then P is true
d. Since I am given a proof of P, all I had to do was apply that proof of P to
prove that P is true
e. Since I am given a proof of not P and a proof of not not P, there is a
contradiction in the proposition due to negation elimination; all I had to do
was apply the contradiction rule
-/
/-
8. [10 points]
-/
example :
(∀ ( P Q : Prop ), (P → Q) ↔ (¬ Q → ¬ P)) →
∀ (Raining Wet : Prop), (¬ Wet → ¬ Raining) →
(Raining → Wet) :=
begin
intros PQ,
assume Raining Wet,
assume nWetnRaining,
assume Rain,
have RainingWet := PQ Raining Wet,
have RWback := RainingWet.2,
exact RWback nWetnRaining Rain,
end
example :
(∀ ( P Q : Prop ), (P → Q) ↔ (¬ Q → ¬ P)) →
∀ (Raining Wet : Prop), (¬ Wet → ¬ Raining) →
(Raining → Wet) :=
begin
intros PQnQnP Raining Wet,
assume nwnr,
assume r,
have pfRW := PQnQnP Raining Wet,
apply iff.elim_right pfRW nwnr,
exact r,
end
/-
9. [5 points]
What is the name of the principle expressed by the
premise, (P → Q) ↔ (¬ Q → ¬ P)), in the preceding
problem? Answer here:
Proof by Contrapositive
-/ |
90399e2670a685b86fb97238b88fae7540957623 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/compiler/t4.lean | ef27a59492e7cb2a5c2181206996b907ce690dbc | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 3,388 | lean | /- Benchmark for new code generator -/
inductive Expr
| Val : Int → Expr
| Var : String → Expr
| Add : Expr → Expr → Expr
| Mul : Expr → Expr → Expr
| Pow : Expr → Expr → Expr
| Ln : Expr → Expr
open Expr
def Expr.toString : Expr → String
| Val n => toString n
| Var x => x
| Add f g => "(" ++ Expr.toString f ++ " + " ++ Expr.toString g ++ ")"
| Mul f g => "(" ++ Expr.toString f ++ " * " ++ Expr.toString g ++ ")"
| Pow f g => "(" ++ Expr.toString f ++ " ^ " ++ Expr.toString g ++ ")"
| Ln f => "ln(" ++ Expr.toString f ++ ")"
instance : HasToString Expr :=
⟨Expr.toString⟩
partial def pown : Int → Int → Int
| a, 0 => 1
| a, 1 => a
| a, n =>
let b := pown a (n / 2);
b * b * (if n % 2 = 0 then 1 else a)
partial def addAux : Expr → Expr → Expr
| Val n, Val m => Val (n + m)
| Val 0, f => f
| f, Val 0 => f
| f, Val n => addAux (Val n) f
| Val n, Add (Val m) f => addAux (Val (n+m)) f
| f, Add (Val n) g => addAux (Val n) (addAux f g)
| Add f g, h => addAux f (addAux g h)
| f, g => Add f g
def add (a b : Expr) : Expr :=
-- dbgTrace (">> add (" ++ toString a ++ ", " ++ toString b ++ ")") $ fun _ =>
addAux a b
-- set_option trace.compiler.borrowed_inference true
partial def mulAux : Expr → Expr → Expr
| Val n, Val m => Val (n*m)
| Val 0, _ => Val 0
| _, Val 0 => Val 0
| Val 1, f => f
| f, Val 1 => f
| f, Val n => mulAux (Val n) f
| Val n, Mul (Val m) f => mulAux (Val (n*m)) f
| f, Mul (Val n) g => mulAux (Val n) (mulAux f g)
| Mul f g, h => mulAux f (mulAux g h)
| f, g => Mul f g
def mul (a b : Expr) : Expr :=
-- dbgTrace (">> mul (" ++ toString a ++ ", " ++ toString b ++ ")") $ fun _ =>
mulAux a b
def pow : Expr → Expr → Expr
| Val m, Val n => Val (pown m n)
| _, Val 0 => Val 1
| f, Val 1 => f
| Val 0, _ => Val 0
| f, g => Pow f g
def ln : Expr → Expr
| Val 1 => Val 0
| f => Ln f
def d (x : String) : Expr → Expr
| Val _ => Val 0
| Var y => if x = y then Val 1 else Val 0
| Add f g => add (d f) (d g)
| Mul f g =>
-- dbgTrace (">> d (" ++ toString f ++ ", " ++ toString g ++ ")") $ fun _ =>
add (mul f (d g)) (mul g (d f))
| Pow f g => mul (pow f g) (add (mul (mul g (d f)) (pow f (Val (-1)))) (mul (ln f) (d g)))
| Ln f => mul (d f) (pow f (Val (-1)))
def count : Expr → Nat
| Val _ => 1
| Var _ => 1
| Add f g => count f + count g
| Mul f g => count f + count g
| Pow f g => count f + count g
| Ln f => count f
def nestAux (s : Nat) (f : Nat → Expr → IO Expr) : Nat → Expr → IO Expr
| 0, x => pure x
| m@(n+1), x => f (s - m) x >>= nestAux n
def nest (f : Nat → Expr → IO Expr) (n : Nat) (e : Expr) : IO Expr :=
nestAux n f n e
def deriv (i : Nat) (f : Expr) : IO Expr :=
do
let d := d "x" f;
IO.println (toString (i+1) ++ " count: " ++ (toString $ count d));
IO.println (toString d);
pure d
def main (xs : List String) : IO UInt32 :=
do let x := Var "x";
let f := add x (mul x (mul x (add x x)));
IO.println f;
nest deriv 3 f;
pure 0
-- setOption profiler True
-- #eval main []
|
de1830b14197a4fddb294c58e4a0f3e85f1450e0 | e030b0259b777fedcdf73dd966f3f1556d392178 | /tests/lean/run/1226.lean | cee34cdfbb46fe6f2834d1f996984b78cf4be0c1 | [
"Apache-2.0"
] | permissive | fgdorais/lean | 17b46a095b70b21fa0790ce74876658dc5faca06 | c3b7c54d7cca7aaa25328f0a5660b6b75fe26055 | refs/heads/master | 1,611,523,590,686 | 1,484,412,902,000 | 1,484,412,902,000 | 38,489,734 | 0 | 0 | null | 1,435,923,380,000 | 1,435,923,379,000 | null | UTF-8 | Lean | false | false | 1,657 | lean | open nat
inductive vec (α : Type*) : ℕ → Type*
| nil {} : vec 0
| cons : α → Π {n : nat}, vec n → vec (n+1)
namespace vec
def head {α : Type*} : Π {n : ℕ}, vec α (n+1) → α
| n (cons x xs) := x
end vec
constants (dret : Π {n : ℕ}, vec nat n → (vec nat n → nat) → nat)
axiom dret_spec : Π {n : ℕ} (xs : vec nat n) (f : vec nat n → nat), dret xs f = f xs
example (v : vec nat 1) : dret v vec.head = vec.head v :=
by rw dret_spec
example (v : vec nat 2) : dret v vec.head = vec.head v :=
by rw dret_spec
example (v : vec nat 3) : dret v vec.head = vec.head v :=
by rw dret_spec
example (v : vec nat 6) : dret v vec.head = vec.head v :=
by rw dret_spec
example (v : vec nat 32) : dret v vec.head = vec.head v :=
by rw dret_spec
example (v : vec nat 63) : dret v vec.head = vec.head v :=
by rw dret_spec
example (v : vec nat 64) : dret v vec.head = vec.head v :=
by rw dret_spec
example {n : nat} (v : vec nat (n+1)) : dret v vec.head = vec.head v :=
by rw dret_spec
example {n : nat} (v : vec nat (n+2)) : dret v vec.head = vec.head v :=
by rw dret_spec
example {n : nat} (v : vec nat (n+3)) : dret v vec.head = vec.head v :=
by rw dret_spec
attribute [simp] dret_spec
example (v : vec nat 1) : dret v vec.head = vec.head v :=
by simp
example (v : vec nat 2) : dret v vec.head = vec.head v :=
by simp
example (v : vec nat 3) : dret v vec.head = vec.head v :=
by simp
example {n : nat} (v : vec nat (n+1)) : dret v vec.head = vec.head v :=
by simp
example {n : nat} (v : vec nat (n+2)) : dret v vec.head = vec.head v :=
by simp
example {n : nat} (v : vec nat (n+3)) : dret v vec.head = vec.head v :=
by simp
|
98ac6ddde76f592a6eb97c509b26f4e9baf9e3d4 | e9dbaaae490bc072444e3021634bf73664003760 | /src/Problems/2005/IMO_2005_P1.lean | b3155a42c373d4db490a70af068a61e4cbcbc743 | [
"Apache-2.0"
] | permissive | liaofei1128/geometry | 566d8bfe095ce0c0113d36df90635306c60e975b | 3dd128e4eec8008764bb94e18b932f9ffd66e6b3 | refs/heads/master | 1,678,996,510,399 | 1,581,454,543,000 | 1,583,337,839,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 510 | lean | import Geo.Geo.Core
namespace Geo
open Line Polygon Triangle
def IMO_2005_P1 : Prop :=
∀ (A B C : Point),
equilateral ⟨A, B, C⟩ →
∀ (A₁ A₂ B₁ B₂ C₁ C₂ : Point),
allOn [A₁, A₂] (Seg.mk B C) →
allOn [B₁, B₂] (Seg.mk C A) →
allOn [C₁, C₂] (Seg.mk A B) →
convex (Polygon.buildPs [A₁, A₂, B₁, B₂, C₁, C₂]) →
(Polygon.buildPs [A₁, A₂, B₁, B₂, C₁, C₂]).equalSides →
allIntersect [Line.mk A₁ B₂, Line.mk B₁ C₂, Line.mk C₁ A₂]
end Geo
|
ea415914e2eb0569020eaa5c525e4f53937770ac | 11e28114d9553ecd984ac4819661ffce3068bafe | /src/expr_zipper.lean | 9120ada80abbf85a4d3eb1756da3a402672d5521 | [
"MIT"
] | permissive | EdAyers/lean-subtask | 9a26eb81f0c8576effed4ca94342ae1281445c59 | 04ac5a6c3bc3bfd190af4d6dcce444ddc8914e4b | refs/heads/master | 1,586,516,665,621 | 1,558,701,948,000 | 1,558,701,948,000 | 160,983,035 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 26,583 | lean | /- Author: E.W.Ayers © 2019 -/
/- Expression zipper. -/
import .util .table
namespace expr
/-- Labels for each recursive argument of a constructor for `expr`. -/
@[derive decidable_eq]
inductive coord
|app_left |app_right
|lam_var_type |lam_body
|pi_var_type |pi_body
|elet_type |elet_assignment |elet_body
def coord.code: coord → ℕ |coord.app_left := 0 |coord.app_right := 1 |coord.lam_var_type := 2 |coord.lam_body := 3 |coord.pi_var_type := 4 |coord.pi_body := 5 |coord.elet_type := 6 |coord.elet_assignment := 7 |coord.elet_body := 8
instance coord.has_lt : has_lt coord := ⟨λ x y, x.code < y.code⟩
instance coord.dec_lt : decidable_rel ((<) : coord → coord → Prop) := by apply_instance
/-- A list of `coord`s, specifying a position in an expression. The first coordinate says which way to go on the root.-/
def address := list coord
instance address.has_lt : has_lt address := show has_lt (list coord), by apply_instance
instance address.dec_lt : decidable_rel ((<) : address → address → Prop) := by apply_instance
instance address.has_append : has_append address := ⟨list.append⟩
/-- `is_below x y` is true when `∃ z, y ++ z = x` -/
def address.is_below : address → address → bool
|_ [] := tt -- everything is below root.
|[] _ := ff -- root is below nothing but itself.
|(h₁ :: t₁) (h₂ :: t₂) := h₁ = h₂ ∧ address.is_below t₁ t₂
infixr ` ≺ `:50 := address.is_below
namespace zipper
/-- A path is the part of the zipper that remembers the stuff above the zipper's cursor.-/
@[derive decidable_eq]
meta inductive path_entry
|app_left (left : unit) (right : expr) : path_entry
|app_right (left : expr) (right : unit) : path_entry
|lam_var_type (var_name : name) (bi : binder_info) (var_type : unit) (body : expr) : path_entry
|lam_body (var_name : name) (bi : binder_info) (var_type : expr) (body : unit) : path_entry
|pi_var_type (var_name : name) (bi : binder_info) (var_type : unit) (body : expr) : path_entry
|pi_body (var_name : name) (bi : binder_info) (var_type : expr) (body : unit) : path_entry
|elet_type (var_name : name) (type : unit) (assignment : expr) (body : expr) : path_entry
|elet_assignment (var_name : name) (type : expr) (assignment : unit) (body : expr) : path_entry
|elet_body (var_name : name) (type : expr) (assignment : expr) (body : unit) : path_entry
/-- A context entry for the zipper's cursor.
In the current implementation; as zippers traverse below lambdas,
pis and elets, they don't replace de-Bruijn indices with local constants.
-/
@[derive decidable_eq]
meta inductive context_entry
|Hyp (n : name) (bi : binder_info) (type : expr) : context_entry
|Assigned (n : name) (type : expr) (assignment : expr) : context_entry
namespace path_entry
meta def to_coord : path_entry → coord
|(app_left _ _) := coord.app_left
|(app_right _ _) := coord.app_right
|(lam_var_type _ _ _ _) := coord.lam_var_type
|(lam_body _ _ _ _) := coord.lam_body
|(pi_var_type _ _ _ _) := coord.pi_var_type
|(pi_body _ _ _ _) := coord.pi_body
|(elet_type _ _ _ _) := coord.elet_type
|(elet_assignment _ _ _ _) := coord.elet_assignment
|(elet_body _ _ _ _) := coord.elet_body
meta def to_address : list path_entry → address := list.map to_coord ∘ list.reverse
open tactic
meta def to_tactic_format : path_entry → tactic format
|(app_left l r) := (pure $ λ l r, l ++ " $ " ++ r) <*> pp l <*> pp r
|(app_right l r) := (pure $ λ l r, l ++ " $ " ++ r) <*> pp l <*> pp r
|(lam_var_type n _ y b) := (pure $ λ n y b, "λ " ++ n ++ " : " ++ y ++ ", " ++ b) <*> pp n <*> pp y <*> pp b
|(lam_body n _ y b) := (pure $ λ n y b, "λ " ++ n ++ " : " ++ y ++ ", " ++ b) <*> pp n <*> pp y <*> pp b
|(pi_var_type n _ y b) := (pure $ λ n y b, "Π " ++ n ++ " : " ++ y ++ ", " ++ b) <*> pp n <*> pp y <*> pp b
|(pi_body n _ y b) := (pure $ λ n y b, "Π " ++ n ++ " : " ++ y ++ ", " ++ b) <*> pp n <*> pp y <*> pp b
|(elet_type n y a b) := (pure $ λ n y a b, "let " ++ n ++ " : " ++ y ++ " := " ++ a ++ " in " ++ b) <*> pp n <*> pp y <*> pp a <*> pp b
|(elet_assignment n y a b) := (pure $ λ n y a b, "let " ++ n ++ " : " ++ y ++ " := " ++ a ++ " in " ++ b) <*> pp n <*> pp y <*> pp a <*> pp b
|(elet_body n y a b) := (pure $ λ n y a b, "let " ++ n ++ " : " ++ y ++ " := " ++ a ++ " in " ++ b) <*> pp n <*> pp y <*> pp a <*> pp b
meta instance has_to_tactic_format : has_to_tactic_format path_entry := ⟨to_tactic_format⟩
meta def to_context_entry : path_entry → option context_entry
|(lam_body n bi y b) := some $ context_entry.Hyp n bi y
|(pi_body n bi y b) := some $ context_entry.Hyp n bi y
|(elet_body n y a b) := some $ context_entry.Assigned n y a
|_ := none
meta def to_context : list path_entry → list context_entry
:= list.filter_map to_context_entry
end path_entry
namespace context_entry
meta def type : context_entry → expr
|(Hyp _ _ y ) := y
|(Assigned _ y _) := y
meta def name : context_entry → name
|(Hyp n _ _ ) := n
|(Assigned n _ _) := n
meta def to_local : context_entry → tactic expr
|(Hyp n bi t ) := tactic.mk_local' n bi t
|(Assigned n t _) := tactic.mk_local' n binder_info.default t
meta def pexpr_pis_of_ctxt : list context_entry → pexpr → pexpr
|[] e := to_pexpr e
|((context_entry.Hyp n bi y) :: rest) e :=
pexpr_pis_of_ctxt rest $ @expr.pi ff n bi (to_pexpr y) $ e
|((context_entry.Assigned n y a) :: rest) e :=
pexpr_pis_of_ctxt rest $ expr.elet n (to_pexpr y) (to_pexpr a) $ e
-- meta def hyps_of_telescope : telescope → list context_entry
-- := list.map (λ ⟨n,bi,y⟩, context_entry.Hyp n bi y)
end context_entry
end zipper
/--
A zipper over expressions. You can think of this as being like a 'cursor' that can move around an `expr`.
It does not replace bound variables with local constants, but instead maintains its own 'mini-context' of the binders that it is under.
Reference: [Functional Pearl - The Zipper](https://www.st.cs.uni-saarland.de/edu/seminare/2005/advanced-fp/docs/huet-zipper.pdf)
-/
@[derive decidable_eq]
meta structure zipper :=
(path : list zipper.path_entry)
(current : expr)
/-- Result type of calling `zipper.down`. -/
@[derive decidable_eq]
meta inductive down_result
|terminal : down_result
|app (left : zipper) (right : zipper) : down_result
| lam (var_name : name) (bi : binder_info) (var_type : zipper) (body : zipper) : down_result
| pi (var_name : name) (bi : binder_info) (var_type : zipper) (body : zipper) : down_result
|elet (var_name : name) (type : zipper) (assignment : zipper) (body : zipper) : down_result
meta def down_result.children : down_result → list zipper
|(down_result.terminal) := []
|(down_result.app l r) := [l,r]
|(down_result.lam n bi vt b) := [vt,b]
|(down_result.pi n bi vt b) := [vt,b]
|(down_result.elet n t a b) := [t,a,b]
namespace zipper
open path_entry
/--Move the cursor down the expression tree.-/
meta def down : zipper → down_result
|⟨p, expr.app f a⟩ :=
down_result.app
⟨app_left () a :: p, f⟩
⟨app_right f () :: p, a⟩
|⟨p, expr.lam n bi y b⟩ :=
down_result.lam n bi
⟨lam_var_type n bi () b :: p, y⟩
⟨lam_body n bi y () :: p, b⟩
|⟨p, expr.pi n bi y b⟩ :=
down_result.pi n bi
⟨pi_var_type n bi () b :: p, y⟩
⟨pi_body n bi y () :: p, b⟩
|⟨p, expr.elet n t a b⟩ :=
down_result.elet n
⟨elet_type n () a b :: p, t⟩
⟨elet_assignment n t () b :: p, a⟩
⟨elet_body n t a () :: p, b⟩
|⟨p,e⟩ := down_result.terminal
meta def children : zipper → list zipper := down_result.children ∘ down
meta def down_coord : coord → zipper → option zipper
|(coord.app_left) ⟨p,expr.app f a⟩ := some ⟨app_left () a :: p, f⟩
|(coord.app_right) ⟨p,expr.app f a⟩ := some ⟨app_right f () :: p, a⟩
|(coord.lam_var_type) ⟨p,expr.lam n bi y b⟩ := some ⟨lam_var_type n bi () b :: p, y⟩
|(coord.lam_body) ⟨p,expr.lam n bi y b⟩ := some ⟨lam_body n bi y () :: p, b⟩
|(coord.pi_var_type) ⟨p,expr.pi n bi y b⟩ := some ⟨pi_var_type n bi () b :: p, y⟩
|(coord.pi_body) ⟨p,expr.pi n bi y b⟩ := some ⟨pi_body n bi y () :: p, b⟩
|(coord.elet_type) ⟨p,expr.elet n y a b⟩ := some ⟨elet_type n () a b :: p, y⟩
|(coord.elet_assignment) ⟨p,expr.elet n y a b⟩ := some ⟨elet_assignment n y () b :: p, a⟩
|(coord.elet_body) ⟨p,expr.elet n y a b⟩ := some ⟨elet_body n y a () :: p, b⟩
|_ _ := none
/-- Pop the cursor up the expression tree. If we are already at the top, returns `none`. -/
meta def up : zipper → option zipper
|⟨[], e⟩ := none
|⟨app_left () a :: p, f⟩ := some $ zipper.mk p $ expr.app f a
|⟨app_right f () :: p, a⟩ := some $ zipper.mk p $ expr.app f a
|⟨lam_var_type n bi _ b :: p, e⟩ := some $ zipper.mk p $ expr.lam n bi e b
|⟨lam_body n bi y _ :: p, e⟩ := some $ zipper.mk p $ expr.lam n bi y e
|⟨pi_var_type n bi _ b :: p, e⟩ := some $ zipper.mk p $ expr.pi n bi e b
|⟨pi_body n bi y _ :: p, e⟩ := some $ zipper.mk p $ expr.pi n bi y e
|⟨elet_type n _ a b :: p, e⟩ := some $ zipper.mk p $ expr.elet n e a b
|⟨elet_assignment n t _ b :: p, e⟩ := some $ zipper.mk p $ expr.elet n t e b
|⟨elet_body n t a _ :: p, e⟩ := some $ zipper.mk p $ expr.elet n t a e
meta def is_top : zipper → bool := list.empty ∘ path
meta def top := option.repeat up
meta def down_app_left : zipper → option zipper := down_coord coord.app_left
meta def down_app_right : zipper → option zipper := down_coord coord.app_right
meta def down_body : zipper → option zipper := λ z,
match down z with
|down_result.pi _ _ _ b := some b
|down_result.lam _ _ _ b := some b
|down_result.elet _ _ _ b := some b
|_ := none
end
meta def down_var_type : zipper → option zipper := λ z,
match down z with
|down_result.pi _ _ y b := some y
|down_result.lam _ _ y b := some y
|down_result.elet _ y _ b := some y
|_ := none
end
/-- Move the cursor down according to the given address.
If the zipper has the wrong structure then return none.-/
meta def down_address : address → zipper → option zipper
|[] z := some z
|(h::t) z := down_coord h z >>= down_address t
meta def unzip : zipper → expr := λ z, option.rec_on (up z) (current z) (unzip)
meta def zip : expr → zipper := λ e, zipper.mk [] e
meta instance : has_coe expr zipper := ⟨zip⟩
meta def set_current : expr → zipper → zipper
|e ⟨p,_⟩ := ⟨p,e⟩
/-- Map the current subexpression. -/
meta def map : (expr → expr) → zipper → zipper
|f ⟨p,e⟩ := ⟨p,f e⟩
meta def mmap {T} [monad T] : (expr → T expr) → zipper → T zipper
|f ⟨p,e⟩ := zipper.mk p <$> f e
meta def address : zipper → address := to_address ∘ path
meta def ctxt : zipper → list context_entry := to_context ∘ path
/-- The number of binders above the cursor. -/
meta def binder_depth : zipper → ℕ := list.length ∘ ctxt
/-- Replace the current subexpression and unzip. -/
meta def unzip_with : expr → zipper → expr := λ e z, unzip $ z.set_current e
meta def is_var : zipper → bool := expr.is_var ∘ current
meta def is_constant : zipper → bool := expr.is_constant ∘ current
/--True when the current expression does not contain local constants -/
meta def no_local_consts : zipper → bool := list.empty ∘ expr.list_local_consts ∘ current
meta def no_local_const_terms : zipper → tactic bool
:= λ z, list.empty <$> (expr.list_local_const_terms $ current $ z)
meta def is_local_constant : zipper → bool := expr.is_local_constant ∘ current
meta def is_mvar : zipper → bool := expr.is_mvar ∘ current
meta def is_terminal : zipper → bool := λ z, z.down = down_result.terminal
/--Infer the type of the subexpression at the cursor position. -/
meta def infer_type : zipper → tactic expr := λ z, do
⟨ins,lcs⟩ ← list.mfoldl (λ ct s, do
l ← context_entry.to_local s,
pure $ (expr.instantiate_var ct.1 l, l::ct.2)
) (z.current,([] : list expr)) z.ctxt,
y ← tactic.infer_type ins,
let y := lcs.foldl expr.abstract y,
pure y
meta instance : has_to_tactic_format zipper := ⟨λ z, do
whole ← tactic.pp $ z.unzip_with `(()),
current ← tactic.pp z.current,
pure $ format.highlight current format.color.blue ++ " in " ++ whole
⟩
universes u v
/-- Helper lemma for `mk_congr` -/
lemma eq_cc {α : Type u} {β : Type v} (F : α → β) (a₁: α)
: ∀ a₂ : α, a₁ = a₂ → F a₁ = F a₂
:= @eq.rec α a₁ (λ a, F a₁ = F a) rfl
open tactic
/-- Given a zipper, makes a congruence lemma at the zipper's position.
[NOTE] Assumes that the zipper is not inside any binders (for now). -/
meta def mk_congr (z : zipper) : tactic expr := do
when (z.binder_depth ≠ 0) (tactic.fail "Not implemented: congruences inside a binder"),
let lhs := z.current,
let lhs' := z.unzip,
T ← tactic.infer_type lhs,
target ← to_expr $ ```(∀ X : %%(T), (%%lhs = X) → %%lhs' = %%(z.unzip_with $ expr.var 1)),
tactic.fabricate (some target) (do
-- get_goals >>= list.mmap infer_type >>= trace,
refine ```(@eq.rec _ %%lhs (λ X, %%(lhs') = %%(z.unzip_with $ expr.var 0)) rfl),
-- get_goals >>= list.mmap infer_type >>= trace,
pure ()
)
/-- Replace the current expression with an unbound deBruijn variable. -/
meta def unzip_free : zipper → expr := λ z, z.unzip_with $ expr.var z.binder_depth
/-- `apply_congr (rhs,pf) z` takes the given `%%pf : %%z.current = %%rhs` and makes a congruence lemma using the given zipper. -/
meta def apply_congr : (expr × expr) → zipper → tactic (expr × expr) := λ ⟨rhs,pf⟩ z, do
if z.is_top then pure ⟨rhs,pf⟩ else do
let lhs := z.current,
T ← tactic.infer_type lhs,
let lhs' := z.unzip,
let rhs' := unzip_with rhs z,
target ← to_expr $ ```(%%lhs' = %%rhs'),
-- pp target >>= λ m, trace $ ("target: ":format) ++ m,
motive ← to_expr $ @expr.lam ff `X binder_info.default (to_pexpr T) $ ```(%%lhs' = %%(z.unzip_with $ expr.var z.binder_depth)),
-- pp motive >>= λ m, trace $ ("motive: ":format) ++ m,
pf' ← tactic.fabricate (some target) (do
-- trace_state,
refine ```(@eq.rec %%T %%lhs %%motive rfl %%rhs %%pf),
all_goals $ try $ (apply_instance <|> assumption)
),
pure (rhs',pf')
/-- Produce a conversion that uses the given conversion at the zipper's subexpression.-/
meta def apply_conv : conv unit → zipper → conv unit := λ cnv z, do
let lhs := z.current,
T ← tactic.infer_type lhs,
rhs ← mk_meta_var T,
let lhs' := z.unzip,
target ← to_expr $ ```(%%lhs' = %%(z.unzip_with rhs)),
rewrite_target target,
refine ```(@eq.rec %%T %%lhs (λ X, %%lhs' = z.unzip_with $ expr.var 0) rfl %%rhs _),
cnv
/-- A proper argument is one who is not implicit or a proposition.
Ie, anything which the user would see when writing down the term. -/
private meta def is_proper (p : param_info) : bool :=
¬(param_info.is_implicit p || param_info.is_inst_implicit p || param_info.is_prop p)
meta def is_type (z : zipper) : tactic bool := expr.is_sort <$> tactic.infer_type z.current
/-- Take a zipper where the current expression is a function application,
and return zippers over all of the non-implicit, non-prop arguments. -/
meta def down_proper (z : zipper) : tactic (zipper × list zipper) := do
let c := z.current,
let f := expr.get_app_fn c,
let f_name := expr.as_name f,
-- if it is a numeral then don't expand it.
if f_name = `bit0 ∨ f_name = `bit1 then pure (z,[]) else do
let args := expr.get_app_args c,
params ← (fun_info.params <$> tactic.get_fun_info f (args.length)) <|> pure [],
let params := list.reverse params,
⟨zippers, fz⟩ ← params.mfoldl (λ acc p, do
let (⟨zippers,z⟩ : (list zipper) × zipper) := acc,
z' ← down_app_left z,
if is_proper p then do
zr ← down_app_right z,
--t ← is_type zr,
--if t then pure (zippers,z') else
pure (zr::zippers,z')
else pure (zippers, z')
)
(([] : list zipper), z),
pure (fz,zippers)
meta def fold {α} (f : α → zipper → α) : α → zipper → α
| a z := z.children.foldl fold $ f a z
meta def mfold {T} [monad T] {α} (f : α → zipper → T α) : α → zipper → T α
| a z := do a ← f a z, z.children.mfoldl mfold a
/-- Traverse zipper.current, only exploring explicit, non-Prop arguments.
If `f` fails, then that branch is skipped. -/
meta def traverse_proper {α} (f : α → zipper → tactic α) : α → zipper → tactic α
|a z := (do
a ← f a z,
(_,children) ← down_proper z,
children.mfoldl traverse_proper a)
<|> pure a
/-- `minimal_monotone p z` finds the smallest proper subexpressions of the zipper such that
`p` doesn't fail.
[NOTE] It assumes that if `p e` fails, then all of `e`s subexpressions will fail too. -/
meta def minimal_monotone {α} (p : zipper → tactic α) : zipper → tactic (list α)
|z := (do
a ← p z,
(_,children) ← down_proper z,
kids ← list.join <$> list.mmap minimal_monotone children,
pure $ list.cases_on kids [a] (λ _ _,kids)
)
<|> pure []
/-- `maximal_monotone p z`: Find the largest proper subexpressions of the zipper such that
`p` doesn't fail.
[NOTE] It assumes that if `p e` fails, then all of `e`s subexpressions will fail too. -/
meta def maximal_monotone {α} (p : zipper → tactic α) : zipper → tactic (list α)
|z := (do a ← p z, pure [a]) <|> do
(f,children) ← down_proper z,
children ← pure $ if is_local_constant f && ¬children.empty then f :: children else children,
kids ← list.join <$> list.mmap maximal_monotone children,
pure $ kids
/-- `find_occurences z e` finds subexpressions of `z` which non-trivially unify with `e`. -/
meta def find_occurences : zipper → expr → tactic (list zipper) := λ E e, do
rs ← maximal_monotone (λ z,
if z.is_mvar || z.is_constant then failure
else tactic.hypothetically' (unify e z.current transparency.none) *> pure z
) E,
pure rs
meta def has_occurences : zipper → expr → tactic bool
:= λ z e, (bnot ∘ list.empty) <$> find_occurences z e
meta def smallest_absent_subterms_aux (l : expr)
(filter : zipper → tactic bool := combinator.K $ pure tt)
: list expr.address → zipper → tactic (list expr.address × list (ℕ × zipper))
|used z := do
filt ← filter z,
if ¬ filt then pure (used, []) else do
occs ← find_occurences l z.current,
o ← pure $ list.find (λ o, bnot $ list.any used $ λ x, zipper.address o ≺ x) occs,
match o with
|none := do -- z.current is not present, descend.
(_,children) ← down_proper z,
(used,zs) ← list.mfoldl (λ p child, do
(used,zs') ← smallest_absent_subterms_aux (prod.fst p) child,
pure (used,zs' ++ p.2)
) (used,[]) children,
if zs.empty then pure $ (used,[(occs.length + 1,z)]) else pure $ (used,zs)
|some o :=
-- z.current is present on the lhs
-- so now we need to add `o` to the used list so that later matches can't use it.
pure $ (used.insert o.address,[])
end
/-- find subterms of RHS that do not appear on LHS. It will also count when occurrences have been used.
So for example, ``smallest_absent_subterms `(a * b + b * a) `(a * b + a * b)`` will return `[(2,a * b)] because
`a * b` occurs once in the LHS but twice in the RHS.
-/
meta def smallest_absent_subterms (lhs : expr) (rhs : zipper) :=
prod.snd <$> smallest_absent_subterms_aux lhs (λ z, bnot <$> no_local_const_terms z) [] rhs
meta def smallest_absent_composite_subterms (lhs : expr) (rhs : zipper) :=
prod.snd
<$> smallest_absent_subterms_aux lhs
(λ s, do
hlcst ← bnot <$> no_local_const_terms s,
is_term ← expr.is_term s.current,
pure $ hlcst && is_term && expr.is_composite s.current)
[] rhs
/--`lowest_uncommon_subterms l z` finds the smallest subterms of z that are not a subterm of `l`. Subterms must include a local_const -/
meta def lowest_uncommon_subterms (l : expr) (z : zipper) :=
minimal_monotone (λ z,
if z.is_mvar || z.is_constant || z.no_local_consts then failure else do
--let o := expr.occurs z.current l,
matches ← zipper.maximal_monotone (λ rz, (tactic.hypothetically' $ unify z.current rz.current) ) $ zipper.zip l,
-- trace_m "lus: " $ (z,l,o, matches),
if ¬ matches.empty then failure else pure z
) z
meta def largest_common_subterms (z₁ z₂ : zipper): tactic (list zipper) :=
list.join <$> z₁.maximal_monotone (λ z₁,
if z₁.is_mvar then failure else do
ocs ← find_occurences (z₂) z₁.current,
if ocs.empty then failure else pure ocs
)
private meta def count_symbols_aux : table expr → zipper → tactic (table expr)
| acc z := do
(f,zs) ← down_proper z,
if zipper.is_mvar f then pure acc else
zs.mfoldl count_symbols_aux $ table.insert f.current acc
meta def count_symbols : expr → tactic (table expr) := count_symbols_aux ∅ ∘ zip
meta def does_unify (e : expr) : zipper → tactic unit
| z := if z.is_mvar then failure else
(tactic.hypothetically' $ unify e z.current transparency.none ff)
meta def find_subterms (e : expr) : zipper → tactic (list zipper)
:= traverse_proper (λ acc z, (does_unify e z *> pure (z::acc)) <|> pure acc) []
meta def has_single_subterm (e : expr) : zipper → tactic (zipper)
:= λ z, do [x] ← find_subterms e z, pure x
meta def count_subterms (e : expr) : zipper → tactic ℕ
:= λ z, do xs ← find_subterms e z, pure $ list.length xs
meta def find_non_unify_subterm (e : expr) : zipper → tactic zipper
|z :=
if e = z.current then pure z else do
(_,zs) ← down_proper z,
list.mfirst find_non_unify_subterm zs
meta def find_subterm (e : expr) : zipper → tactic zipper
|z :=
(does_unify e z *> pure z)
<|> do
(_,zs) ← down_proper z,
list.mfirst find_subterm zs
meta def distance_to_subterm_down (e : expr) : zipper → nat → tactic nat
|z d :=
if z.is_mvar then failure else
(tactic.hypothetically' $ (do
unify e z.current, pure d
))
<|> (do
-- tactic.trace_m "dtsd: " $ z,
(_,zs) ← down_proper z,
list.mfirst (λ iz : ℕ × zipper, distance_to_subterm_down iz.2 $ iz.1 + d + 1)
$ list.with_indices zs
)
meta def is_app_right : zipper → bool
|⟨(app_right _ _)::t,_⟩ := tt
|_ := ff
meta def right : zipper → option zipper
|z := if is_app_right z then up z >>= right else up z >>= down_app_right
meta def distance_to_subterm_up (e : expr) : ℕ → zipper → tactic ℕ
|d z :=
if is_app_right z then up z >>= distance_to_subterm_up (d+1) else do
-- tactic.trace_m "dtsu1: " $ z,
z ← up z >>= lift down_app_right,
-- tactic.trace_m "dtsu2: " $ z,
distance_to_subterm_down e z (d+1)
<|> distance_to_subterm_up (d+1) z
meta def get_distance (outer : expr) (l : expr) (r : expr) : tactic ℕ := do
outer ← instantiate_mvars outer,
first ← find_subterm l outer,
-- tactic.trace_m "gd: " $ first,
distance_to_subterm_up r 0 first
meta def get_proper_children (e : expr) : tactic (list expr) := do
e ← instantiate_mvars e,
(list.map current <$> prod.snd <$> (down_proper $ zip e)) <|> pure []
meta def get_smallest_complex_subterms (z : zipper) : tactic (list zipper) := do
minimal_monotone (λ z, do ⟨_,[]⟩ ← down_proper z | failure, pure z) z
meta def instantiate_mvars : zipper → tactic zipper
|z := do
let a := address z,
let e := unzip z,
e ← tactic.instantiate_mvars e,
z ← down_address a e,
pure z
/-- Returns true when everything in the zippers except the cursor terms are equal. -/
meta def above_equal : zipper → zipper → tactic bool
|z₁ z₂ := do
list.meq_by (λ x y, pure $ x = y) z₁.path z₂.path
end zipper
end expr |
29ffff146ba0f1dd74b72095bf97d502590e5db4 | f00cc9c04d77f9621aa57d1406d35c522c3ff82c | /library/init/data/ordering/lemmas.lean | 50b7502362e57f76d49c83f9718392c9191974ba | [
"Apache-2.0"
] | permissive | shonfeder/lean | 444c66a74676d74fb3ef682d88cd0f5c1bf928a5 | 24d5a1592d80cefe86552d96410c51bb07e6d411 | refs/heads/master | 1,619,338,440,905 | 1,512,842,340,000 | 1,512,842,340,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,135 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.data.ordering.basic init.meta init.algebra.classes init.ite_simp
set_option default_priority 100
universes u
namespace ordering
/- Delete the following simp lemmas as soon as we improve the simplifier. -/
@[simp] lemma lt_ne_eq : ordering.lt ≠ ordering.eq :=
by contradiction
@[simp] lemma lt_ne_gt : ordering.lt ≠ ordering.gt :=
by contradiction
@[simp] lemma eq_ne_lt : ordering.eq ≠ ordering.lt :=
by contradiction
@[simp] lemma eq_ne_gt : ordering.eq ≠ ordering.gt :=
by contradiction
@[simp] lemma gt_ne_lt : ordering.gt ≠ ordering.lt :=
by contradiction
@[simp] lemma gt_ne_eq : ordering.gt ≠ ordering.eq :=
by contradiction
@[simp] theorem ite_eq_lt_distrib (c : Prop) [decidable c] (a b : ordering) : ((if c then a else b) = ordering.lt) = (if c then a = ordering.lt else b = ordering.lt) :=
by by_cases c with h; simp [h]
@[simp] theorem ite_eq_eq_distrib (c : Prop) [decidable c] (a b : ordering) : ((if c then a else b) = ordering.eq) = (if c then a = ordering.eq else b = ordering.eq) :=
by by_cases c with h; simp [h]
@[simp] theorem ite_eq_gt_distrib (c : Prop) [decidable c] (a b : ordering) : ((if c then a else b) = ordering.gt) = (if c then a = ordering.gt else b = ordering.gt) :=
by by_cases c with h; simp [h]
/- ------------------------------------------------------------------ -/
end ordering
section
variables {α : Type u} {lt : α → α → Prop} [decidable_rel lt]
local attribute [simp] cmp_using
@[simp] lemma cmp_using_eq_lt (a b : α) : (cmp_using lt a b = ordering.lt) = lt a b :=
by simp
@[simp] lemma cmp_using_eq_gt [is_strict_order α lt] (a b : α) : (cmp_using lt a b = ordering.gt) = lt b a :=
begin
simp, apply propext, apply iff.intro,
{ exact λ h, h.2 },
{ intro hba, split, { intro hab, exact absurd (trans hab hba) (irrefl a) }, { assumption } }
end
@[simp] lemma cmp_using_eq_eq (a b : α) : (cmp_using lt a b = ordering.eq) = (¬ lt a b ∧ ¬ lt b a) :=
by simp
end
|
b24266fd3d86d0ed625fa4a10e03607fbc860b8d | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/core.lean | 15657cf447ab10b523a49ac9e8f97b5e74d82bf7 | [] | 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 | 18,040 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
notation, basic datatypes and type classes
-/
import Mathlib.PrePort
universes u l v w u_1 u_2 u₁ u₂ u₃
namespace Mathlib
/- Reserving notation. We do this so that the precedence of all of the operators
can be seen in one place and to prevent core notation being accidentally overloaded later. -/
/- Notation for logical operations and relations -/
/- types and type constructors -/
/- arithmetic operations -/
/- boolean operations -/
/- set operations -/
/- other symbols -/
/--
The kernel definitional equality test (t =?= s) has special support for id_delta applications.
It implements the following rules
1) (id_delta t) =?= t
2) t =?= (id_delta t)
3) (id_delta t) =?= s IF (unfold_of t) =?= s
4) t =?= id_delta s IF t =?= (unfold_of s)
This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel.
We use id_delta applications to address performance problems when type checking
lemmas generated by the equation compiler.
-/
def id_delta {α : Sort u} (a : α) : α :=
a
/-- Gadget for optional parameter support. -/
def opt_param (α : Sort u) (default : α) :=
α
/-- Gadget for marking output parameters in type classes. -/
def out_param (α : Sort u) :=
α
/-
id_rhs is an auxiliary declaration used in the equation compiler to address performance
issues when proving equational lemmas. The equation compiler uses it as a marker.
-/
def id_rhs (α : Sort u) (a : α) : α :=
a
/-- An abbreviation for `punit.{0}`, its most common instantiation.
This type should be preferred over `punit` where possible to avoid
unnecessary universe parameters. -/
def unit :=
PUnit
def unit.star : Unit :=
PUnit.unit
/--
Gadget for defining thunks, thunk parameters have special treatment.
Example: given
def f (s : string) (t : thunk nat) : nat
an application
f "hello" 10
is converted into
f "hello" (λ _, 10)
-/
def thunk (α : Type u) :=
Unit → α
inductive empty
where
/--
Logical not.
`not P`, with notation `¬ P`, is the `Prop` which is true if and only if `P` is false. It is
internally represented as `P → false`, so one way to prove a goal `⊢ ¬ P` is to use `intro h`,
which gives you a new hypothesis `h : P` and the goal `⊢ false`.
A hypothesis `h : ¬ P` can be used in term mode as a function, so if `w : P` then `h w : false`.
Related mathlib tactic: `contrapose`.
-/
def not (a : Prop) :=
a → False
prefix:40 "¬" => Mathlib.not
/-
Initialize the quotient module, which effectively adds the following definitions:
constant quot {α : Sort u} (r : α → α → Prop) : Sort u
constant quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : quot r
constant quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :
(∀ a b : α, r a b → eq (f a) (f b)) → quot r → β
constant quot.ind {α : Sort u} {r : α → α → Prop} {β : quot r → Prop} :
(∀ a : α, β (quot.mk r a)) → ∀ q : quot r, β q
Also the reduction rule:
quot.lift f _ (quot.mk a) ~~> f a
-/
/--
Heterogeneous equality.
Its purpose is to write down equalities between terms whose types are not definitionally equal.
For example, given `x : vector α n` and `y : vector α (0+n)`, `x = y` doesn't typecheck but `x == y` does.
If you have a goal `⊢ x == y`,
your first instinct should be to ask (either yourself, or on [zulip](https://leanprover.zulipchat.com/))
if something has gone wrong already.
If you really do need to follow this route,
you may find the lemmas `eq_rec_heq` and `eq_mpr_heq` useful.
-/
/-- Similar to `prod`, but α and β can be propositions.
We use this type internally to automatically generate the brec_on recursor. -/
/--
Logical and.
`and P Q`, with notation `P ∧ Q`, is the `Prop` which is true precisely when `P` and `Q` are
both true.
To prove a goal `⊢ P ∧ Q`, you can use the tactic `split`,
which gives two separate goals `⊢ P` and `⊢ Q`.
Given a hypothesis `h : P ∧ Q`, you can use the tactic `cases h with hP hQ`
to obtain two new hypotheses `hP : P` and `hQ : Q`. See also the `obtain` or `rcases` tactics in
mathlib.
-/
def and.elim_left {a : Prop} {b : Prop} (h : a ∧ b) : a :=
and.left h
def and.elim_right {a : Prop} {b : Prop} (h : a ∧ b) : b :=
and.right h
infixl:50 " = " => Mathlib.eq
/- eq basic support -/
def rfl {α : Sort u} {a : α} : a = a :=
Eq.refl a
theorem eq.subst {α : Sort u} {P : α → Prop} {a : α} {b : α} (h₁ : a = b) (h₂ : P a) : P b :=
Eq._oldrec h₂ h₁
infixr:75 " ▸ " => Mathlib.eq.subst
theorem eq.trans {α : Sort u} {a : α} {b : α} {c : α} (h₁ : a = b) (h₂ : b = c) : a = c :=
h₂ ▸ h₁
theorem eq.symm {α : Sort u} {a : α} {b : α} (h : a = b) : b = a :=
h ▸ rfl
infixl:50 " == " => Mathlib.heq
def heq.rfl {α : Sort u} {a : α} : a == a :=
HEq.refl a
theorem eq_of_heq {α : Sort u} {a : α} {a' : α} (h : a == a') : a = a' :=
(fun (this : ∀ (α' : Sort u) (a' : α'), a == a' → ∀ (h₂ : α = α'), eq.rec_on h₂ a = a') =>
(fun (this : eq.rec_on (Eq.refl α) a = a') => this) (this α a' h (Eq.refl α)))
fun (α' : Sort u) (a' : α') (h₁ : a == a') => heq.rec_on h₁ fun (h₂ : α = α) => rfl
/- The following four lemmas could not be automatically generated when the
structures were declared, so we prove them manually here. -/
theorem prod.mk.inj {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : (x₁, y₁) = (x₂, y₂) → x₁ = x₂ ∧ y₁ = y₂ :=
fun (h : (x₁, y₁) = (x₂, y₂)) => prod.no_confusion h fun (h₁ : x₁ = x₂) (h₂ : y₁ = y₂) => { left := h₁, right := h₂ }
theorem prod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : (x₁, y₁) = (x₂, y₂) → {P : Sort w} → (x₁ = x₂ → y₁ = y₂ → P) → P :=
fun (h₁ : (x₁, y₁) = (x₂, y₂)) (_x : Sort w) (h₂ : x₁ = x₂ → y₁ = y₂ → _x) => prod.no_confusion h₁ h₂
theorem pprod.mk.inj {α : Sort u} {β : Sort v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : { fst := x₁, snd := y₁ } = { fst := x₂, snd := y₂ } → x₁ = x₂ ∧ y₁ = y₂ :=
fun (h : { fst := x₁, snd := y₁ } = { fst := x₂, snd := y₂ }) =>
pprod.no_confusion h fun (h₁ : x₁ = x₂) (h₂ : y₁ = y₂) => { left := h₁, right := h₂ }
theorem pprod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} : (x₁, y₁) = (x₂, y₂) → {P : Sort w} → (x₁ = x₂ → y₁ = y₂ → P) → P :=
fun (h₁ : (x₁, y₁) = (x₂, y₂)) (_x : Sort w) (h₂ : x₁ = x₂ → y₁ = y₂ → _x) => prod.no_confusion h₁ h₂
inductive sum (α : Type u) (β : Type v)
where
| inl : α → sum α β
| inr : β → sum α β
inductive psum (α : Sort u) (β : Sort v)
where
| inl : α → psum α β
| inr : β → psum α β
/--
Logical or.
`or P Q`, with notation `P ∨ Q`, is the proposition which is true if and only if `P` or `Q` is
true.
To prove a goal `⊢ P ∨ Q`, if you know which alternative you want to prove,
you can use the tactics `left` (which gives the goal `⊢ P`)
or `right` (which gives the goal `⊢ Q`).
Given a hypothesis `h : P ∨ Q` and goal `⊢ R`,
the tactic `cases h` will give you two copies of the goal `⊢ R`,
with the hypothesis `h : P` in the first, and the hypothesis `h : Q` in the second.
-/
def or.intro_left {a : Prop} (b : Prop) (ha : a) : a ∨ b :=
Or.inl ha
def or.intro_right (a : Prop) {b : Prop} (hb : b) : a ∨ b :=
Or.inr hb
structure sigma {α : Type u} (β : α → Type v)
where
fst : α
snd : β fst
structure psigma {α : Sort u} (β : α → Sort v)
where
fst : α
snd : β fst
/- Remark: subtype must take a Sort instead of Type because of the axiom strong_indefinite_description. -/
def decidable_pred {α : Sort u} (r : α → Prop) :=
(a : α) → Decidable (r a)
def decidable_rel {α : Sort u} (r : α → α → Prop) :=
(a b : α) → Decidable (r a b)
def decidable_eq (α : Sort u) :=
DecidableRel Eq
infixr:67 " :: " => Mathlib.list.cons
structure unification_constraint
where
α : Type u
lhs : α
rhs : α
infixl:50 " ≟ " => Mathlib.unification_constraint.mk
infixl:50 " =?= " => Mathlib.unification_constraint.mk
structure unification_hint
where
pattern : unification_constraint
constraints : List unification_constraint
/- Declare builtin and reserved notation -/
class has_inv (α : Type u)
where
inv : α → α
class has_dvd (α : Type u)
where
dvd : α → α → Prop
class has_andthen (α : Type u) (β : Type v) (σ : outParam (Type w))
where
andthen : α → β → σ
class has_union (α : Type u)
where
union : α → α → α
class has_inter (α : Type u)
where
inter : α → α → α
class has_sdiff (α : Type u)
where
sdiff : α → α → α
class has_equiv (α : Sort u)
where
equiv : α → α → Prop
class has_subset (α : Type u)
where
subset : α → α → Prop
/- Type classes has_emptyc and has_insert are
class has_ssubset (α : Type u)
where
ssubset : α → α → Prop
used to implement polymorphic notation for collections.
Example: {a, b, c}. -/
class has_emptyc (α : Type u)
where
emptyc : α
class has_insert (α : outParam (Type u)) (γ : Type v)
where
insert : α → γ → γ
/- Type class used to implement the notation { a ∈ c | p a } -/
class has_singleton (α : outParam (Type u)) (β : Type v)
where
singleton : α → β
class has_sep (α : outParam (Type u)) (γ : Type v)
where
sep : (α → Prop) → γ → γ
/- Type class for set-like membership -/
class has_mem (α : outParam (Type u)) (γ : Type v)
where
mem : α → γ → Prop
class has_pow (α : Type u) (β : Type v)
where
pow : α → β → α
infixl:50 " ∈ " => Mathlib.has_mem.mem
infixl:65 " + " => Mathlib.has_add.add
infixl:70 " * " => Mathlib.has_mul.mul
infixl:65 " - " => Mathlib.has_sub.sub
infixl:70 " / " => Mathlib.has_div.div
infixl:50 " ∣ " => Mathlib.has_dvd.dvd
infixl:70 " % " => Mathlib.has_mod.mod
prefix:75 "-" => Mathlib.has_neg.neg
infixl:50 " <= " => Mathlib.has_le.le
infixl:50 " ≤ " => Mathlib.has_le.le
infixl:50 " < " => Mathlib.has_lt.lt
infixl:65 " ++ " => Mathlib.has_append.append
infixl:1 "; " => Mathlib.has_andthen.andthen
notation:1024 "∅" => Mathlib.has_emptyc.emptyc
infixl:65 " ∪ " => Mathlib.has_union.union
infixl:70 " ∩ " => Mathlib.has_inter.inter
infixl:50 " ⊆ " => Mathlib.has_subset.subset
infixl:50 " ⊂ " => Mathlib.has_ssubset.ssubset
infixl:70 " \ " => Mathlib.has_sdiff.sdiff
infixl:50 " ≈ " => Mathlib.has_equiv.equiv
infixr:80 " ^ " => Mathlib.has_pow.pow
def ge {α : Type u} [HasLessEq α] (a : α) (b : α) :=
b ≤ a
def gt {α : Type u} [HasLess α] (a : α) (b : α) :=
b < a
infixl:50 " >= " => Mathlib.ge
infixl:50 " ≥ " => Mathlib.ge
infixl:50 " > " => Mathlib.gt
def superset {α : Type u} [has_subset α] (a : α) (b : α) :=
b ⊆ a
def ssuperset {α : Type u} [has_ssubset α] (a : α) (b : α) :=
b ⊂ a
infixl:50 " ⊇ " => Mathlib.superset
infixl:50 " ⊃ " => Mathlib.ssuperset
def bit0 {α : Type u} [s : Add α] (a : α) : α :=
a + a
def bit1 {α : Type u} [s₁ : HasOne α] [s₂ : Add α] (a : α) : α :=
bit0 a + 1
class is_lawful_singleton (α : Type u) (β : Type v) [has_emptyc β] [has_insert α β] [has_singleton α β]
where
insert_emptyc_eq : ∀ (x : α), insert x ∅ = has_singleton.singleton x
/- nat basic instances -/
namespace nat
protected def add : Nat → Nat → Nat :=
Nat.add
end nat
protected instance nat.has_zero : HasZero Nat :=
{ zero := 0 }
protected instance nat.has_one : HasOne Nat :=
{ one := 1 }
protected instance nat.has_add : Add Nat :=
{ add := Nat.add }
def std.priority.default : Nat :=
bit0 (bit0 (bit0 (bit1 (bit0 (bit1 (bit1 (bit1 (bit1 1))))))))
def std.priority.max : Nat :=
bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1
(bit1 (bit1 (bit1 (bit1 (bit1 (bit1 1))))))))))))))))))))))))))))))
namespace nat
end nat
protected def nat.prio : Nat :=
std.priority.default + bit0 (bit0 (bit1 (bit0 (bit0 (bit1 1)))))
/-
Global declarations of right binding strength
If a module reassigns these, it will be incompatible with other modules that adhere to these
conventions.
When hovering over a symbol, use "C-c C-k" to see how to input it.
-/
def std.prec.max : Nat :=
bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))))
def std.prec.arrow : Nat :=
bit1 (bit0 (bit0 (bit1 1)))
/-
The next def is "max + 10". It can be used e.g. for postfix operations that should
be stronger than application.
-/
def std.prec.max_plus : Nat :=
std.prec.max + bit0 (bit1 (bit0 1))
postfix:0 "⁻¹" => Mathlib.has_inv.inv
infixr:35 " × " => Mathlib.prod
-- notation for n-ary tuples
/- sizeof -/
def sizeof {α : Sort u} [s : SizeOf α] : α → Nat :=
has_sizeof.sizeof
/-
Declare sizeof instances and lemmas for types declared before has_sizeof.
From now on, the inductive compiler will automatically generate sizeof instances and lemmas.
-/
/- Every type `α` has a default has_sizeof instance that just returns 0 for every element of `α` -/
protected def default.sizeof (α : Sort u) : α → Nat :=
sorry
protected instance default_has_sizeof (α : Sort u) : SizeOf α :=
{ sizeOf := default.sizeof α }
protected def nat.sizeof : Nat → Nat :=
sorry
protected instance nat.has_sizeof : SizeOf Nat :=
{ sizeOf := nat.sizeof }
protected def prod.sizeof {α : Type u} {β : Type v} [SizeOf α] [SizeOf β] : α × β → Nat :=
sorry
protected instance prod.has_sizeof (α : Type u) (β : Type v) [SizeOf α] [SizeOf β] : SizeOf (α × β) :=
{ sizeOf := prod.sizeof }
protected def sum.sizeof {α : Type u} {β : Type v} [SizeOf α] [SizeOf β] : sum α β → Nat :=
sorry
protected instance sum.has_sizeof (α : Type u) (β : Type v) [SizeOf α] [SizeOf β] : SizeOf (sum α β) :=
{ sizeOf := sum.sizeof }
protected def psum.sizeof {α : Type u} {β : Type v} [SizeOf α] [SizeOf β] : psum α β → Nat :=
sorry
protected instance psum.has_sizeof (α : Type u) (β : Type v) [SizeOf α] [SizeOf β] : SizeOf (psum α β) :=
{ sizeOf := psum.sizeof }
protected def sigma.sizeof {α : Type u} {β : α → Type v} [SizeOf α] [(a : α) → SizeOf (β a)] : sigma β → Nat :=
sorry
protected instance sigma.has_sizeof (α : Type u) (β : α → Type v) [SizeOf α] [(a : α) → SizeOf (β a)] : SizeOf (sigma β) :=
{ sizeOf := sigma.sizeof }
protected def psigma.sizeof {α : Type u} {β : α → Type v} [SizeOf α] [(a : α) → SizeOf (β a)] : psigma β → Nat :=
sorry
protected instance psigma.has_sizeof (α : Type u) (β : α → Type v) [SizeOf α] [(a : α) → SizeOf (β a)] : SizeOf (psigma β) :=
{ sizeOf := psigma.sizeof }
protected def punit.sizeof : PUnit → Nat :=
sorry
protected instance punit.has_sizeof : SizeOf PUnit :=
{ sizeOf := punit.sizeof }
protected def bool.sizeof : Bool → Nat :=
sorry
protected instance bool.has_sizeof : SizeOf Bool :=
{ sizeOf := bool.sizeof }
protected def option.sizeof {α : Type u} [SizeOf α] : Option α → Nat :=
sorry
protected instance option.has_sizeof (α : Type u) [SizeOf α] : SizeOf (Option α) :=
{ sizeOf := option.sizeof }
protected def list.sizeof {α : Type u} [SizeOf α] : List α → Nat :=
sorry
protected instance list.has_sizeof (α : Type u) [SizeOf α] : SizeOf (List α) :=
{ sizeOf := list.sizeof }
protected def subtype.sizeof {α : Type u} [SizeOf α] {p : α → Prop} : Subtype p → Nat :=
sorry
protected instance subtype.has_sizeof {α : Type u} [SizeOf α] (p : α → Prop) : SizeOf (Subtype p) :=
{ sizeOf := subtype.sizeof }
theorem nat_add_zero (n : Nat) : n + 0 = n :=
rfl
/- Combinator calculus -/
namespace combinator
def I {α : Type u₁} (a : α) : α :=
a
def K {α : Type u₁} {β : Type u₂} (a : α) (b : β) : α :=
a
end combinator
def combinator.S {α : Type u₁} {β : Type u₂} {γ : Type u₃} (x : α → β → γ) (y : α → β) (z : α) : γ :=
x z (y z)
/-- Auxiliary datatype for #[ ... ] notation.
#[1, 2, 3, 4] is notation for
bin_tree.node
(bin_tree.node (bin_tree.leaf 1) (bin_tree.leaf 2))
(bin_tree.node (bin_tree.leaf 3) (bin_tree.leaf 4))
We use this notation to input long sequences without exhausting the system stack space.
Later, we define a coercion from `bin_tree` into `list`.
-/
inductive bin_tree (α : Type u)
where
| empty : bin_tree α
| leaf : α → bin_tree α
| node : bin_tree α → bin_tree α → bin_tree α
/- Basic unification hints -/
def add_succ_defeq_succ_add_hint (x : Nat) (y : Nat) (z : Nat) : unification_hint :=
unification_hint.mk (x + Nat.succ y =?= Nat.succ z) [z =?= x + y]
/-- Like `by apply_instance`, but not dependent on the tactic framework. -/
def infer_instance {α : Sort u} [i : α] : α :=
i
|
f9cb639aa06792d612be8d8ca8a24f0853be6f1a | ee8cdbabf07f77e7be63a449b8483ce308d37218 | /lean/src/valid/mathd-numbertheory-45.lean | da63ff580939c9d74993b2692f0c9cf6f8819112 | [
"MIT",
"Apache-2.0"
] | permissive | zeta1999/miniF2F | 6d66c75d1c18152e224d07d5eed57624f731d4b7 | c1ba9629559c5273c92ec226894baa0c1ce27861 | refs/heads/main | 1,681,897,460,642 | 1,620,646,361,000 | 1,620,646,361,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 573 | lean | /-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng
-/
import tactic.gptf
import data.nat.basic
import data.real.basic
example : ( nat.gcd 6432 132 ) + 11 = 23 :=
begin
suffices : ( nat.gcd 6432 132 ) = 12, rw this,
rw nat.gcd_rec,
have key₁ : 132 % 6432 = 132, ring,
rw key₁,
rw nat.gcd_rec,
have key₂ : 6432 % 132 = 96, {
suffices : 6432 = 48 * 132 + 96, {
rw this,
norm_num,
},
ring,
},
rw key₂,
rw nat.gcd_rec,
norm_num,
end
|
efe4bf3c9ff98deea508eb429cc5f74ae7be2ae7 | 3b15c7b0b62d8ada1399c112ad88a529e6bfa115 | /stage0/src/Lean/Elab/PreDefinition/WF/Fix.lean | 10c9b07d32b6926c3c0e3abbd43b7abfef20f3c7 | [
"Apache-2.0"
] | permissive | stephenbrady/lean4 | 74bf5cae8a433e9c815708ce96c9e54a5caf2115 | b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9 | refs/heads/master | 1,692,621,473,161 | 1,634,308,743,000 | 1,634,310,749,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,898 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Match.Match
import Lean.Meta.Tactic.Simp.Main
import Lean.Meta.Tactic.Cleanup
import Lean.Elab.PreDefinition.Basic
import Lean.Elab.PreDefinition.Structural.Basic
namespace Lean.Elab.WF
open Meta
private def toUnfold : Std.PHashSet Name :=
[``measure, ``id, ``Prod.lex, ``invImage, ``InvImage, ``Nat.lt_wfRel].foldl (init := {}) fun s a => s.insert a
private def applyDefaultDecrTactic (mvarId : MVarId) : TermElabM Unit := do
let ctx ← Simp.Context.mkDefault
let ctx := { ctx with simpLemmas.toUnfold := toUnfold }
if let some mvarId ← simpTarget mvarId ctx then
-- TODO: invoke tactic to close the goal
trace[Elab.definition.wf] "{MessageData.ofGoal mvarId}"
admit mvarId
private def mkDecreasingProof (decreasingProp : Expr) (decrTactic? : Option Syntax) : TermElabM Expr := do
let mvar ← mkFreshExprSyntheticOpaqueMVar decreasingProp
let mvarId := mvar.mvarId!
let mvarId ← cleanup mvarId
match decrTactic? with
| none => applyDefaultDecrTactic mvarId
| some decrTactic => Term.runTactic mvarId decrTactic
instantiateMVars mvar
private partial def replaceRecApps (recFnName : Name) (decrTactic? : Option Syntax) (F : Expr) (e : Expr) : TermElabM Expr :=
let rec loop (F : Expr) (e : Expr) : TermElabM Expr := do
match e with
| Expr.lam n d b c =>
withLocalDecl n c.binderInfo (← loop F d) fun x => do
mkLambdaFVars #[x] (← loop F (b.instantiate1 x))
| Expr.forallE n d b c =>
withLocalDecl n c.binderInfo (← loop F d) fun x => do
mkForallFVars #[x] (← loop F (b.instantiate1 x))
| Expr.letE n type val body _ =>
withLetDecl n (← loop F type) (← loop F val) fun x => do
mkLetFVars #[x] (← loop F (body.instantiate1 x))
| Expr.mdata d e _ => return mkMData d (← loop F e)
| Expr.proj n i e _ => return mkProj n i (← loop F e)
| Expr.app _ _ _ =>
let processApp (e : Expr) : TermElabM Expr :=
e.withApp fun f args => do
if f.isConstOf recFnName && args.size == 1 then
let r := mkApp F args[0]
let decreasingProp := (← whnf (← inferType r)).bindingDomain!
return mkApp r (← mkDecreasingProof decreasingProp decrTactic?)
else
return mkAppN (← loop F f) (← args.mapM (loop F))
let matcherApp? ← matchMatcherApp? e
match matcherApp? with
| some matcherApp =>
if !Structural.recArgHasLooseBVarsAt recFnName 0 e then
processApp e
else
let matcherApp ← mapError (matcherApp.addArg F) (fun msg => "failed to add functional argument to 'matcher' application" ++ indentD msg)
let altsNew ← (Array.zip matcherApp.alts matcherApp.altNumParams).mapM fun (alt, numParams) =>
lambdaTelescope alt fun xs altBody => do
unless xs.size >= numParams do
throwError "unexpected matcher application alternative{indentExpr alt}\nat application{indentExpr e}"
let FAlt := xs[numParams - 1]
mkLambdaFVars xs (← loop FAlt altBody)
pure { matcherApp with alts := altsNew }.toExpr
| none => processApp e
| e => Structural.ensureNoRecFn recFnName e
loop F e
/-- Refine `F` over `Sum.casesOn` -/
private partial def processSumCasesOn (x F val : Expr) (k : (x : Expr) → (F : Expr) → (val : Expr) → TermElabM Expr) : TermElabM Expr := do
if x.isFVar && val.isAppOfArity ``Sum.casesOn 6 && val.getArg! 3 == x && (val.getArg! 4).isLambda && (val.getArg! 5).isLambda then
let args := val.getAppArgs
let α := args[0]
let β := args[1]
let FDecl ← getLocalDecl F.fvarId!
let (motiveNew, u) ← lambdaTelescope args[2] fun xs type => do
let type ← mkArrow (FDecl.type.replaceFVar x xs[0]) type
return (← mkLambdaFVars xs type, ← getLevel type)
let mkMinorNew (ctorName : Name) (minor : Expr) : TermElabM Expr :=
lambdaTelescope minor fun xs body => do
let xNew ← xs[0]
let valNew ← mkLambdaFVars xs[1:] body
let FTypeNew := FDecl.type.replaceFVar x (← mkAppOptM ctorName #[α, β, xNew])
withLocalDeclD FDecl.userName FTypeNew fun FNew => do
mkLambdaFVars #[xNew, FNew] (← processSumCasesOn xNew FNew valNew k)
let minorLeft ← mkMinorNew ``Sum.inl args[4]
let minorRight ← mkMinorNew ``Sum.inr args[5]
let result := mkAppN (mkConst ``Sum.casesOn [u, (← getDecLevel α), (← getDecLevel β)]) #[α, β, motiveNew, x, minorLeft, minorRight, F]
return result
else
k x F val
/-- Refine `F` over `PSigma.casesOn` -/
private partial def processPSigmaCasesOn (x F val : Expr) (k : (F : Expr) → (val : Expr) → TermElabM Expr) : TermElabM Expr := do
if x.isFVar && val.isAppOfArity ``PSigma.casesOn 5 && val.getArg! 3 == x && (val.getArg! 4).isLambda && (val.getArg! 4).bindingBody!.isLambda then
let args := val.getAppArgs
let [_, u, v] ← val.getAppFn.constLevels! | unreachable!
let α := args[0]
let β := args[1]
let FDecl ← getLocalDecl F.fvarId!
let (motiveNew, w) ← lambdaTelescope args[2] fun xs type => do
let type ← mkArrow (FDecl.type.replaceFVar x xs[0]) type
return (← mkLambdaFVars xs type, ← getLevel type)
let minor ← lambdaTelescope args[4] fun xs body => do
let a ← xs[0]
let xNew ← xs[1]
let valNew ← mkLambdaFVars xs[2:] body
let FTypeNew := FDecl.type.replaceFVar x (← mkAppOptM `PSigma.mk #[α, β, a, xNew])
withLocalDeclD FDecl.userName FTypeNew fun FNew => do
mkLambdaFVars #[a, xNew, FNew] (← processPSigmaCasesOn xNew FNew valNew k)
let result := mkAppN (mkConst ``PSigma.casesOn [w, u, v]) #[α, β, motiveNew, x, minor, F]
return result
else
k F val
def mkFix (preDef : PreDefinition) (wfRel : Expr) (decrTactic? : Option Syntax) : TermElabM PreDefinition := do
let wfFix ← forallBoundedTelescope preDef.type (some 1) fun x type => do
let x := x[0]
let α ← inferType x
let u ← getLevel α
let v ← getLevel type
let motive ← mkLambdaFVars #[x] type
let rel := mkProj ``WellFoundedRelation 0 wfRel
let wf := mkProj ``WellFoundedRelation 1 wfRel
return mkApp4 (mkConst ``WellFounded.fix [u, v]) α motive rel wf
forallBoundedTelescope (← whnf (← inferType wfFix)).bindingDomain! (some 2) fun xs _ => do
let x := xs[0]
let F := xs[1]
let val := preDef.value.betaRev #[x]
let val ← processSumCasesOn x F val fun x F val => processPSigmaCasesOn x F val (replaceRecApps preDef.declName decrTactic?)
return { preDef with value := mkApp wfFix (← mkLambdaFVars #[x, F] val) }
end Lean.Elab.WF
|
eb65be2078da268a952582918eb10fef965f4a14 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/topology/metric_space/cau_seq_filter.lean | f2f98bcd494736598165c3a015dd2e573899d244 | [
"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 | 3,824 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis, Sébastien Gouëzel
-/
import topology.uniform_space.basic analysis.normed_space.basic data.real.cau_seq
import tactic.linarith
/-! # Completeness in terms of `cauchy` filters vs `is_cau_seq` sequences
In this file we apply `metric.complete_of_cauchy_seq_tendsto` to prove that a `normed_ring`
is complete in terms of `cauchy` filter if and only if it is complete in terms
of `cau_seq` Cauchy sequences.
-/
universes u v
open set filter
open_locale topological_space classical
variable {β : Type v}
lemma cau_seq.tendsto_limit [normed_ring β] [hn : is_absolute_value (norm : β → ℝ)]
(f : cau_seq β norm) [cau_seq.is_complete β norm] :
tendsto f at_top (𝓝 f.lim) :=
_root_.tendsto_nhds.mpr
begin
intros s os lfs,
suffices : ∃ (a : ℕ), ∀ (b : ℕ), b ≥ a → f b ∈ s, by simpa using this,
rcases metric.is_open_iff.1 os _ lfs with ⟨ε, ⟨hε, hεs⟩⟩,
cases setoid.symm (cau_seq.equiv_lim f) _ hε with N hN,
existsi N,
intros b hb,
apply hεs,
dsimp [metric.ball], rw [dist_comm, dist_eq_norm],
solve_by_elim
end
variables [normed_field β]
/-
This section shows that if we have a uniform space generated by an absolute value, topological
completeness and Cauchy sequence completeness coincide. The problem is that there isn't
a good notion of "uniform space generated by an absolute value", so right now this is
specific to norm. Furthermore, norm only instantiates is_absolute_value on normed_field.
This needs to be fixed, since it prevents showing that ℤ_[hp] is complete
-/
instance normed_field.is_absolute_value : is_absolute_value (norm : β → ℝ) :=
{ abv_nonneg := norm_nonneg,
abv_eq_zero := λ _, norm_eq_zero,
abv_add := norm_add_le,
abv_mul := normed_field.norm_mul }
open metric
lemma cauchy_seq.is_cau_seq {f : ℕ → β} (hf : cauchy_seq f) :
is_cau_seq norm f :=
begin
cases cauchy_iff.1 hf with hf1 hf2,
intros ε hε,
rcases hf2 {x | dist x.1 x.2 < ε} (dist_mem_uniformity hε) with ⟨t, ⟨ht, htsub⟩⟩,
simp at ht, cases ht with N hN,
existsi N,
intros j hj,
rw ←dist_eq_norm,
apply @htsub (f j, f N),
apply set.mk_mem_prod; solve_by_elim [le_refl]
end
lemma cau_seq.cauchy_seq (f : cau_seq β norm) : cauchy_seq f :=
begin
apply cauchy_iff.2,
split,
{ exact map_ne_bot at_top_ne_bot },
{ intros s hs,
rcases mem_uniformity_dist.1 hs with ⟨ε, ⟨hε, hεs⟩⟩,
cases cau_seq.cauchy₂ f hε with N hN,
existsi {n | n ≥ N}.image f,
simp, split,
{ existsi N, intros b hb, existsi b, simp [hb] },
{ rintros ⟨a, b⟩ ⟨⟨a', ⟨ha'1, ha'2⟩⟩, ⟨b', ⟨hb'1, hb'2⟩⟩⟩,
dsimp at ha'1 ha'2 hb'1 hb'2,
rw [←ha'2, ←hb'2],
apply hεs,
rw dist_eq_norm,
apply hN; assumption }},
end
/-- In a normed field, `cau_seq` coincides with the usual notion of Cauchy sequences. -/
lemma cau_seq_iff_cauchy_seq {α : Type u} [normed_field α] {u : ℕ → α} :
is_cau_seq norm u ↔ cauchy_seq u :=
⟨λh, cau_seq.cauchy_seq ⟨u, h⟩,
λh, h.is_cau_seq⟩
/-- A complete normed field is complete as a metric space, as Cauchy sequences converge by
assumption and this suffices to characterize completeness. -/
@[priority 100] -- see Note [lower instance priority]
instance complete_space_of_cau_seq_complete [cau_seq.is_complete β norm] : complete_space β :=
begin
apply complete_of_cauchy_seq_tendsto,
assume u hu,
have C : is_cau_seq norm u := cau_seq_iff_cauchy_seq.2 hu,
existsi cau_seq.lim ⟨u, C⟩,
rw metric.tendsto_at_top,
assume ε εpos,
cases (cau_seq.equiv_lim ⟨u, C⟩) _ εpos with N hN,
existsi N,
simpa [dist_eq_norm] using hN
end
|
a744ddb628ab1eba473505cfa5c2fefc10370e31 | 271e26e338b0c14544a889c31c30b39c989f2e0f | /src/Init/Lean/Expr.lean | 5a7a791de9fbe3b779329d8b494e07c22509f982 | [
"Apache-2.0"
] | permissive | dgorokho/lean4 | 805f99b0b60c545b64ac34ab8237a8504f89d7d4 | e949a052bad59b1c7b54a82d24d516a656487d8a | refs/heads/master | 1,607,061,363,851 | 1,578,006,086,000 | 1,578,006,086,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32,471 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.HashMap
import Init.Data.HashSet
import Init.Data.PersistentHashMap
import Init.Data.PersistentHashSet
import Init.Lean.Data.KVMap
import Init.Lean.Level
namespace Lean
inductive Literal
| natVal (val : Nat)
| strVal (val : String)
instance Literal.inhabited : Inhabited Literal := ⟨Literal.natVal 0⟩
def Literal.hash : Literal → USize
| Literal.natVal v => hash v
| Literal.strVal v => hash v
instance Literal.hashable : Hashable Literal := ⟨Literal.hash⟩
def Literal.beq : Literal → Literal → Bool
| Literal.natVal v₁, Literal.natVal v₂ => v₁ == v₂
| Literal.strVal v₁, Literal.strVal v₂ => v₁ == v₂
| _, _ => false
instance Literal.hasBeq : HasBeq Literal := ⟨Literal.beq⟩
def Literal.lt : Literal → Literal → Bool
| Literal.natVal _, Literal.strVal _ => true
| Literal.natVal v₁, Literal.natVal v₂ => v₁ < v₂
| Literal.strVal v₁, Literal.strVal v₂ => v₁ < v₂
| _, _ => false
instance Literal.hasLess : HasLess Literal := ⟨fun a b => a.lt b⟩
inductive BinderInfo
| default | implicit | strictImplicit | instImplicit | auxDecl
def BinderInfo.hash : BinderInfo → USize
| BinderInfo.default => 947
| BinderInfo.implicit => 1019
| BinderInfo.strictImplicit => 1087
| BinderInfo.instImplicit => 1153
| BinderInfo.auxDecl => 1229
def BinderInfo.isExplicit : BinderInfo → Bool
| BinderInfo.implicit => false
| BinderInfo.strictImplicit => false
| BinderInfo.instImplicit => false
| _ => true
instance BinderInfo.hashable : Hashable BinderInfo := ⟨BinderInfo.hash⟩
instance BinderInfo.inhabited : Inhabited BinderInfo := ⟨BinderInfo.default⟩
def BinderInfo.isInstImplicit : BinderInfo → Bool
| BinderInfo.instImplicit => true
| _ => false
def BinderInfo.isAuxDecl : BinderInfo → Bool
| BinderInfo.auxDecl => true
| _ => false
protected def BinderInfo.beq : BinderInfo → BinderInfo → Bool
| BinderInfo.default, BinderInfo.default => true
| BinderInfo.implicit, BinderInfo.implicit => true
| BinderInfo.strictImplicit, BinderInfo.strictImplicit => true
| BinderInfo.instImplicit, BinderInfo.instImplicit => true
| BinderInfo.auxDecl, BinderInfo.auxDecl => true
| _, _ => false
instance BinderInfo.hasBeq : HasBeq BinderInfo := ⟨BinderInfo.beq⟩
abbrev MData := KVMap
abbrev MData.empty : MData := {KVMap .}
instance MVData.hasEmptc : HasEmptyc MData := ⟨MData.empty⟩
/--
Cached hash code, cached results, and other data for `Expr`.
hash : 32-bits
hasFVar : 1-bit
hasExprMVar : 1-bit
hasLevelMVar : 1-bit
hasLevelParam : 1-bit
nonDepLet : 1-bit
binderInfo : 3-bits
looseBVarRange : 24-bits -/
def Expr.Data := UInt64
instance Expr.Data.inhabited : Inhabited Expr.Data :=
inferInstanceAs (Inhabited UInt64)
def Expr.Data.hash (c : Expr.Data) : USize :=
c.toUInt32.toUSize
instance Expr.Data.hasBeq : HasBeq Expr.Data :=
⟨fun (a b : UInt64) => a == b⟩
def Expr.Data.looseBVarRange (c : Expr.Data) : UInt32 :=
(c.shiftRight 40).toUInt32
def Expr.Data.hasFVar (c : Expr.Data) : Bool :=
((c.shiftRight 32).land 1) == 1
def Expr.Data.hasExprMVar (c : Expr.Data) : Bool :=
((c.shiftRight 33).land 1) == 1
def Expr.Data.hasLevelMVar (c : Expr.Data) : Bool :=
((c.shiftRight 34).land 1) == 1
def Expr.Data.hasLevelParam (c : Expr.Data) : Bool :=
((c.shiftRight 35).land 1) == 1
def Expr.Data.nonDepLet (c : Expr.Data) : Bool :=
((c.shiftRight 36).land 1) == 1
@[extern c inline "(uint8_t)((#1 << 24) >> 61)"]
def Expr.Data.binderInfo (c : Expr.Data) : BinderInfo :=
let bi := (c.shiftLeft 24).shiftRight 61;
if bi == 0 then BinderInfo.default
else if bi == 1 then BinderInfo.implicit
else if bi == 2 then BinderInfo.strictImplicit
else if bi == 3 then BinderInfo.instImplicit
else BinderInfo.auxDecl
@[extern c inline "(uint64_t)#1"]
def BinderInfo.toUInt64 : BinderInfo → UInt64
| BinderInfo.default => 0
| BinderInfo.implicit => 1
| BinderInfo.strictImplicit => 2
| BinderInfo.instImplicit => 3
| BinderInfo.auxDecl => 4
@[inline] private def Expr.mkDataCore
(h : USize) (looseBVarRange : Nat)
(hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet : Bool) (bi : BinderInfo)
: Expr.Data :=
if looseBVarRange > Nat.pow 2 24 - 1 then panic! "bound variable index is too big"
else
let r : UInt64 :=
h.toUInt32.toUInt64 +
hasFVar.toUInt64.shiftLeft 32 +
hasExprMVar.toUInt64.shiftLeft 33 +
hasLevelMVar.toUInt64.shiftLeft 34 +
hasLevelParam.toUInt64.shiftLeft 35 +
nonDepLet.toUInt64.shiftLeft 36 +
bi.toUInt64.shiftLeft 37 +
looseBVarRange.toUInt64.shiftLeft 40;
r
def Expr.mkData (h : USize) (looseBVarRange : Nat := 0) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool := false) : Expr.Data :=
Expr.mkDataCore h looseBVarRange hasFVar hasExprMVar hasLevelMVar hasLevelParam false BinderInfo.default
def Expr.mkDataForBinder (h : USize) (looseBVarRange : Nat) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool) (bi : BinderInfo) : Expr.Data :=
Expr.mkDataCore h looseBVarRange hasFVar hasExprMVar hasLevelMVar hasLevelParam false bi
def Expr.mkDataForLet (h : USize) (looseBVarRange : Nat) (hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet : Bool) : Expr.Data :=
Expr.mkDataCore h looseBVarRange hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet BinderInfo.default
open Expr
abbrev MVarId := Name
abbrev FVarId := Name
/- We use the `E` suffix (short for `Expr`) to avoid collision with keywords.
We considered using «...», but it is too inconvenient to use. -/
inductive Expr
| bvar : Nat → Data → Expr -- bound variables
| fvar : FVarId → Data → Expr -- free variables
| mvar : MVarId → Data → Expr -- meta variables
| sort : Level → Data → Expr -- Sort
| const : Name → List Level → Data → Expr -- constants
| app : Expr → Expr → Data → Expr -- application
| lam : Name → Expr → Expr → Data → Expr -- lambda abstraction
| forallE : Name → Expr → Expr → Data → Expr -- (dependent) arrow
| letE : Name → Expr → Expr → Expr → Data → Expr -- let expressions
| lit : Literal → Data → Expr -- literals
| mdata : MData → Expr → Data → Expr -- metadata
| proj : Name → Nat → Expr → Data → Expr -- projection
-- IMPORTANT: the following constructor will be deleted
| localE : Name → Name → Expr → Data → Expr -- Lean2 legacy. TODO: delete
namespace Expr
instance : Inhabited Expr :=
⟨sort (arbitrary _) (arbitrary _)⟩
@[inline] def data : Expr → Data
| bvar _ d => d
| fvar _ d => d
| mvar _ d => d
| sort _ d => d
| const _ _ d => d
| app _ _ d => d
| lam _ _ _ d => d
| forallE _ _ _ d => d
| letE _ _ _ _ d => d
| lit _ d => d
| mdata _ _ d => d
| proj _ _ _ d => d
| localE _ _ _ d => d
def hash (e : Expr) : USize :=
e.data.hash
instance : Hashable Expr := ⟨Expr.hash⟩
def hasFVar (e : Expr) : Bool :=
e.data.hasFVar
def hasExprMVar (e : Expr) : Bool :=
e.data.hasExprMVar
def hasLevelMVar (e : Expr) : Bool :=
e.data.hasLevelMVar
def hasMVar (e : Expr) : Bool :=
let d := e.data;
d.hasExprMVar || d.hasLevelMVar
def hasLevelParam (e : Expr) : Bool :=
e.data.hasLevelParam
def looseBVarRange (e : Expr) : Nat :=
e.data.looseBVarRange.toNat
def binderInfo (e : Expr) : BinderInfo :=
e.data.binderInfo
@[export lean_expr_hash] def hashEx : Expr → USize := hash
@[export lean_expr_has_fvar] def hasFVarEx : Expr → Bool := hasFVar
@[export lean_expr_has_expr_mvar] def hasExprMVarEx : Expr → Bool := hasExprMVar
@[export lean_expr_has_level_mvar] def hasLevelMVarEx : Expr → Bool := hasLevelMVar
@[export lean_expr_has_mvar] def hasMVarEx : Expr → Bool := hasMVar
@[export lean_expr_has_level_param] def hasLevelParamEx : Expr → Bool := hasLevelParam
@[export lean_expr_loose_bvar_range] def looseBVarRangeEx (e : Expr) : UInt32 := e.data.looseBVarRange
@[export lean_expr_binder_info] def binderInfoEx : Expr → BinderInfo := binderInfo
end Expr
def mkLit (l : Literal) : Expr :=
Expr.lit l $ mkData (mixHash 3 (hash l))
def mkNatLit (n : Nat) : Expr :=
mkLit (Literal.natVal n)
def mkStrLit (s : String) : Expr :=
mkLit (Literal.strVal s)
def mkConst (n : Name) (lvls : List Level := []) : Expr :=
Expr.const n lvls $ mkData (mixHash 5 $ mixHash (hash n) (hash lvls)) 0 false false (lvls.any Level.hasMVar) (lvls.any Level.hasParam)
def Literal.type : Literal → Expr
| Literal.natVal _ => mkConst `Nat
| Literal.strVal _ => mkConst `String
@[export lean_lit_type]
def Literal.typeEx : Literal → Expr := Literal.type
def mkBVar (idx : Nat) : Expr :=
Expr.bvar idx $ mkData (mixHash 7 $ hash idx) (idx+1)
def mkSort (lvl : Level) : Expr :=
Expr.sort lvl $ mkData (mixHash 11 $ hash lvl) 0 false false lvl.hasMVar lvl.hasParam
def mkFVar (fvarId : FVarId) : Expr :=
Expr.fvar fvarId $ mkData (mixHash 13 $ hash fvarId) 0 true
def mkMVar (fvarId : MVarId) : Expr :=
Expr.mvar fvarId $ mkData (mixHash 17 $ hash fvarId) 0 false true
def mkMData (d : MData) (e : Expr) : Expr :=
Expr.mdata d e $ mkData (mixHash 19 $ hash e) e.looseBVarRange e.hasFVar e.hasExprMVar e.hasLevelMVar e.hasLevelParam
def mkProj (s : Name) (i : Nat) (e : Expr) : Expr :=
Expr.proj s i e $ mkData (mixHash 23 $ mixHash (hash s) $ mixHash (hash i) (hash e))
e.looseBVarRange e.hasFVar e.hasExprMVar e.hasLevelMVar e.hasLevelParam
def mkApp (f a : Expr) : Expr :=
Expr.app f a $ mkData (mixHash 29 $ mixHash (hash f) (hash a))
(Nat.max f.looseBVarRange a.looseBVarRange)
(f.hasFVar || a.hasFVar)
(f.hasExprMVar || a.hasExprMVar)
(f.hasLevelMVar || a.hasLevelMVar)
(f.hasLevelParam || a.hasLevelParam)
def mkLambda (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr :=
Expr.lam x t b $ mkDataForBinder (mixHash 31 $ mixHash (hash t) (hash b))
(Nat.max t.looseBVarRange (b.looseBVarRange - 1))
(t.hasFVar || b.hasFVar)
(t.hasExprMVar || b.hasExprMVar)
(t.hasLevelMVar || b.hasLevelMVar)
(t.hasLevelParam || b.hasLevelParam)
bi
def mkForall (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr :=
Expr.forallE x t b $ mkDataForBinder (mixHash 37 $ mixHash (hash t) (hash b))
(Nat.max t.looseBVarRange (b.looseBVarRange - 1))
(t.hasFVar || b.hasFVar)
(t.hasExprMVar || b.hasExprMVar)
(t.hasLevelMVar || b.hasLevelMVar)
(t.hasLevelParam || b.hasLevelParam)
bi
def mkLet (x : Name) (t : Expr) (v : Expr) (b : Expr) (nonDep : Bool := false) : Expr :=
Expr.letE x t v b $ mkDataForLet (mixHash 41 $ mixHash (hash t) $ mixHash (hash v) (hash b))
(Nat.max (Nat.max t.looseBVarRange v.looseBVarRange) (b.looseBVarRange - 1))
(t.hasFVar || v.hasFVar || b.hasFVar)
(t.hasExprMVar || v.hasExprMVar || b.hasExprMVar)
(t.hasLevelMVar || v.hasLevelMVar || b.hasLevelMVar)
(t.hasLevelParam || v.hasLevelParam || b.hasLevelParam)
nonDep
-- TODO: delete
def mkLocal (x u : Name) (t : Expr) (bi : BinderInfo) : Expr :=
Expr.localE x u t $ mkDataForBinder (mixHash 43 $ hash t) t.looseBVarRange true t.hasExprMVar t.hasLevelMVar t.hasLevelParam bi
@[export lean_expr_mk_bvar] def mkBVarEx : Nat → Expr := mkBVar
@[export lean_expr_mk_fvar] def mkFVarEx : FVarId → Expr := mkFVar
@[export lean_expr_mk_mvar] def mkMVarEx : MVarId → Expr := mkMVar
@[export lean_expr_mk_sort] def mkSortEx : Level → Expr := mkSort
@[export lean_expr_mk_const] def mkConstEx (c : Name) (lvls : List Level) : Expr := mkConst c lvls
@[export lean_expr_mk_app] def mkAppEx : Expr → Expr → Expr := mkApp
@[export lean_expr_mk_lambda] def mkLambdaEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkLambda n bi d b
@[export lean_expr_mk_forall] def mkForallEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkForall n bi d b
@[export lean_expr_mk_let] def mkLetEx (n : Name) (t v b : Expr) : Expr := mkLet n t v b
@[export lean_expr_mk_lit] def mkLitEx : Literal → Expr := mkLit
@[export lean_expr_mk_mdata] def mkMDataEx : MData → Expr → Expr := mkMData
@[export lean_expr_mk_proj] def mkProjEx : Name → Nat → Expr → Expr := mkProj
@[export lean_expr_mk_local] def mkLocalEx : Name → Name → Expr → BinderInfo → Expr := mkLocal
def mkAppN (f : Expr) (args : Array Expr) : Expr :=
args.foldl mkApp f
private partial def mkAppRangeAux (n : Nat) (args : Array Expr) : Nat → Expr → Expr
| i, e => if i < n then mkAppRangeAux (i+1) (mkApp e (args.get! i)) else e
/-- `mkAppRange f i j #[a_1, ..., a_i, ..., a_j, ... ]` ==> the expression `f a_i ... a_{j-1}` -/
def mkAppRange (f : Expr) (i j : Nat) (args : Array Expr) : Expr :=
mkAppRangeAux j args i f
def mkAppRev (fn : Expr) (revArgs : Array Expr) : Expr :=
revArgs.foldr (fun a r => mkApp r a) fn
namespace Expr
-- TODO: implement it in Lean
@[extern "lean_expr_dbg_to_string"]
constant dbgToString (e : @& Expr) : String := arbitrary String
@[extern "lean_expr_quick_lt"]
constant quickLt (a : @& Expr) (b : @& Expr) : Bool := arbitrary _
@[extern "lean_expr_lt"]
constant lt (a : @& Expr) (b : @& Expr) : Bool := arbitrary _
/- Return true iff `a` and `b` are alpha equivalent.
Binder annotations are ignored. -/
@[extern "lean_expr_eqv"]
constant eqv (a : @& Expr) (b : @& Expr) : Bool := arbitrary _
instance : HasBeq Expr := ⟨Expr.eqv⟩
/- Return true iff `a` and `b` are equal.
Binder names and annotations are taking into account. -/
@[extern "lean_expr_equal"]
constant equal (a : @& Expr) (b : @& Expr) : Bool := arbitrary _
def isSort : Expr → Bool
| sort _ _ => true
| _ => false
def isBVar : Expr → Bool
| bvar _ _ => true
| _ => false
def isMVar : Expr → Bool
| mvar _ _ => true
| _ => false
def isFVar : Expr → Bool
| fvar _ _ => true
| _ => false
def isApp : Expr → Bool
| app _ _ _ => true
| _ => false
def isProj : Expr → Bool
| proj _ _ _ _ => true
| _ => false
def isConst : Expr → Bool
| const _ _ _ => true
| _ => false
def isConstOf : Expr → Name → Bool
| const n _ _, m => n == m
| _, _ => false
def isForall : Expr → Bool
| forallE _ _ _ _ => true
| _ => false
def isLambda : Expr → Bool
| lam _ _ _ _ => true
| _ => false
def isBinding : Expr → Bool
| lam _ _ _ _ => true
| forallE _ _ _ _ => true
| _ => false
def isLet : Expr → Bool
| letE _ _ _ _ _ => true
| _ => false
def isMData : Expr → Bool
| mdata _ _ _ => true
| _ => false
def getAppFn : Expr → Expr
| app f a _ => getAppFn f
| e => e
def getAppNumArgsAux : Expr → Nat → Nat
| app f a _, n => getAppNumArgsAux f (n+1)
| e, n => n
def getAppNumArgs (e : Expr) : Nat :=
getAppNumArgsAux e 0
private def getAppArgsAux : Expr → Array Expr → Nat → Array Expr
| app f a _, as, i => getAppArgsAux f (as.set! i a) (i-1)
| _, as, _ => as
@[inline] def getAppArgs (e : Expr) : Array Expr :=
let dummy := mkSort levelZero;
let nargs := e.getAppNumArgs;
getAppArgsAux e (mkArray nargs dummy) (nargs-1)
private def getAppRevArgsAux : Expr → Array Expr → Array Expr
| app f a _, as => getAppRevArgsAux f (as.push a)
| _, as => as
@[inline] def getAppRevArgs (e : Expr) : Array Expr :=
getAppRevArgsAux e (Array.mkEmpty e.getAppNumArgs)
@[specialize] def withAppAux {α} (k : Expr → Array Expr → α) : Expr → Array Expr → Nat → α
| app f a _, as, i => withAppAux f (as.set! i a) (i-1)
| f, as, i => k f as
@[inline] def withApp {α} (e : Expr) (k : Expr → Array Expr → α) : α :=
let dummy := mkSort levelZero;
let nargs := e.getAppNumArgs;
withAppAux k e (mkArray nargs dummy) (nargs-1)
@[specialize] private def withAppRevAux {α} (k : Expr → Array Expr → α) : Expr → Array Expr → α
| app f a _, as => withAppRevAux f (as.push a)
| f, as => k f as
@[inline] def withAppRev {α} (e : Expr) (k : Expr → Array Expr → α) : α :=
withAppRevAux k e (Array.mkEmpty e.getAppNumArgs)
def getRevArgD : Expr → Nat → Expr → Expr
| app f a _, 0, _ => a
| app f _ _, i+1, v => getRevArgD f i v
| _, _, v => v
def getRevArg! : Expr → Nat → Expr
| app f a _, 0 => a
| app f _ _, i+1 => getRevArg! f i
| _, _ => panic! "invalid index"
@[inline] def getArg! (e : Expr) (i : Nat) (n := e.getAppNumArgs) : Expr :=
getRevArg! e (n - i - 1)
@[inline] def getArgD (e : Expr) (i : Nat) (v₀ : Expr) (n := e.getAppNumArgs) : Expr :=
getRevArgD e (n - i - 1) v₀
def isAppOf (e : Expr) (n : Name) : Bool :=
match e.getAppFn with
| const c _ _ => c == n
| _ => false
def isAppOfArity : Expr → Name → Nat → Bool
| const c _ _, n, 0 => c == n
| app f _ _, n, a+1 => isAppOfArity f n a
| _, _, _ => false
def appFn! : Expr → Expr
| app f _ _ => f
| _ => panic! "application expected"
def appArg! : Expr → Expr
| app _ a _ => a
| _ => panic! "application expected"
def constName! : Expr → Name
| const n _ _ => n
| _ => panic! "constant expected"
def constLevels! : Expr → List Level
| const _ ls _ => ls
| _ => panic! "constant expected"
def bvarIdx! : Expr → Nat
| bvar idx _ => idx
| _ => panic! "bvar expected"
def fvarId! : Expr → FVarId
| fvar n _ => n
| _ => panic! "fvar expected"
def mvarId! : Expr → MVarId
| mvar n _ => n
| _ => panic! "mvar expected"
def bindingName! : Expr → Name
| forallE n _ _ _ => n
| lam n _ _ _ => n
| _ => panic! "binding expected"
def bindingDomain! : Expr → Expr
| forallE _ _ d _ => d
| lam _ _ d _ => d
| _ => panic! "binding expected"
def bindingBody! : Expr → Expr
| forallE _ _ b _ => b
| lam _ _ b _ => b
| _ => panic! "binding expected"
def letName! : Expr → Name
| letE n _ _ _ _ => n
| _ => panic! "let expression expected"
def consumeMData : Expr → Expr
| mdata _ e _ => consumeMData e
| e => e
def hasLooseBVars (e : Expr) : Bool :=
e.looseBVarRange > 0
@[extern "lean_expr_has_loose_bvar"]
constant hasLooseBVar (e : @& Expr) (bvarIdx : @& Nat) : Bool := arbitrary _
/--
Lower the loose bound variables `>= s` in `e` by `d`.
That is, a loose bound variable `bvar i`.
`i >= s` is mapped into `bvar (i-d)`. -/
@[extern "lean_expr_lower_loose_bvars"]
constant lowerLooseBVars (e : @& Expr) (s d : @& Nat) : Expr := arbitrary _
/--
Lift loose bound variables `>= s` in `e` by `d`. -/
@[extern "lean_expr_lift_loose_bvars"]
constant liftLooseBVars (e : @& Expr) (s d : @& Nat) : Expr := arbitrary _
/-- Instantiate the loose bound variables in `e` using `subst`.
That is, a loose `Expr.bvar i` is replaced with `subst[i]`. -/
@[extern "lean_expr_instantiate"]
constant instantiate (e : @& Expr) (subst : @& Array Expr) : Expr := arbitrary _
@[extern "lean_expr_instantiate1"]
constant instantiate1 (e : @& Expr) (subst : @& Expr) : Expr := arbitrary _
/-- Similar to instantiate, but `Expr.bvar i` is replaced with `subst[subst.size - i - 1]` -/
@[extern "lean_expr_instantiate_rev"]
constant instantiateRev (e : @& Expr) (subst : @& Array Expr) : Expr := arbitrary _
/-- Similar to `instantiate`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`.
Function panics if `beginIdx <= endIdx <= xs.size` does not hold. -/
@[extern "lean_expr_instantiate_range"]
constant instantiateRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr := arbitrary _
/-- Similar to `instantiateRev`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`.
Function panics if `beginIdx <= endIdx <= xs.size` does not hold. -/
@[extern "lean_expr_instantiate_rev_range"]
constant instantiateRevRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr := arbitrary _
/-- Replace free variables `xs` with loose bound variables. -/
@[extern "lean_expr_abstract"]
constant abstract (e : @& Expr) (xs : @& Array Expr) : Expr := arbitrary _
/-- Similar to `abstract`, but consider only the first `min n xs.size` entries in `xs`. -/
@[extern "lean_expr_abstract_range"]
constant abstractRange (e : @& Expr) (n : @& Nat) (xs : @& Array Expr) : Expr := arbitrary _
instance : HasToString Expr :=
⟨Expr.dbgToString⟩
-- TODO: should not use dbgToString, but constructors.
instance : HasRepr Expr :=
⟨Expr.dbgToString⟩
end Expr
def mkAppB (f a b : Expr) := mkApp (mkApp f a) b
def mkApp2 (f a b : Expr) := mkAppB f a b
def mkApp3 (f a b c : Expr) := mkApp (mkAppB f a b) c
def mkApp4 (f a b c d : Expr) := mkAppB (mkAppB f a b) c d
def mkApp5 (f a b c d e : Expr) := mkApp (mkApp4 f a b c d) e
def mkApp6 (f a b c d e₁ e₂ : Expr) := mkAppB (mkApp4 f a b c d) e₁ e₂
def mkApp7 (f a b c d e₁ e₂ e₃ : Expr) := mkApp3 (mkApp4 f a b c d) e₁ e₂ e₃
def mkApp8 (f a b c d e₁ e₂ e₃ e₄ : Expr) := mkApp4 (mkApp4 f a b c d) e₁ e₂ e₃ e₄
def mkApp9 (f a b c d e₁ e₂ e₃ e₄ e₅ : Expr) := mkApp5 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅
def mkApp10 (f a b c d e₁ e₂ e₃ e₄ e₅ e₆ : Expr) := mkApp6 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅ e₆
def mkDecIsTrue (pred proof : Expr) :=
mkAppB (mkConst `Decidable.isTrue) pred proof
def mkDecIsFalse (pred proof : Expr) :=
mkAppB (mkConst `Decidable.isFalse) pred proof
abbrev ExprMap (α : Type) := HashMap Expr α
abbrev PersistentExprMap (α : Type) := PHashMap Expr α
abbrev ExprSet := HashSet Expr
abbrev PersistentExprSet := PHashSet Expr
abbrev PExprSet := PersistentExprSet
/- Auxiliary type for forcing `==` to be structural equality for `Expr` -/
structure ExprStructEq :=
(val : Expr)
instance exprToExprStructEq : HasCoe Expr ExprStructEq := ⟨ExprStructEq.mk⟩
namespace ExprStructEq
protected def beq : ExprStructEq → ExprStructEq → Bool
| ⟨e₁⟩, ⟨e₂⟩ => Expr.equal e₁ e₂
protected def hash : ExprStructEq → USize
| ⟨e⟩ => e.hash
instance : Inhabited ExprStructEq := ⟨{ val := arbitrary _ }⟩
instance : HasBeq ExprStructEq := ⟨ExprStructEq.beq⟩
instance : Hashable ExprStructEq := ⟨ExprStructEq.hash⟩
instance : HasToString ExprStructEq := ⟨fun e => toString e.val⟩
instance : HasRepr ExprStructEq := ⟨fun e => repr e.val⟩
end ExprStructEq
abbrev ExprStructMap (α : Type) := HashMap ExprStructEq α
abbrev PersistentExprStructMap (α : Type) := PHashMap ExprStructEq α
namespace Expr
private partial def mkAppRevRangeAux (revArgs : Array Expr) (start : Nat) : Expr → Nat → Expr
| b, i =>
if i == start then b
else
let i := i - 1;
mkAppRevRangeAux (mkApp b (revArgs.get! i)) i
/-- `mkAppRevRange f b e args == mkAppRev f (revArgs.extract b e)` -/
def mkAppRevRange (f : Expr) (beginIdx endIdx : Nat) (revArgs : Array Expr) : Expr :=
mkAppRevRangeAux revArgs beginIdx f endIdx
private def betaRevAux (revArgs : Array Expr) (sz : Nat) : Expr → Nat → Expr
| Expr.lam _ _ b _, i =>
if i + 1 < sz then
betaRevAux b (i+1)
else
let n := sz - (i + 1);
mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs
| Expr.mdata _ b _, i => betaRevAux b i
| b, i =>
let n := sz - i;
mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs
/-- If `f` is a lambda expression, than "beta-reduce" it using `revArgs`.
This function is often used with `getAppRev` or `withAppRev`.
Examples:
- `betaRev (fun x y => t x y) #[]` ==> `fun x y => t x y`
- `betaRev (fun x y => t x y) #[a]` ==> `fun y => t a y`
- `betaRev (fun x y => t x y) #[a, b]` ==> t b a`
- `betaRev (fun x y => t x y) #[a, b, c, d]` ==> t d c b a`
Suppose `t` is `(fun x y => t x y) a b c d`, then
`args := t.getAppRev` is `#[d, c, b, a]`,
and `betaRev (fun x y => t x y) #[d, c, b, a]` is `t a b c d`. -/
def betaRev (f : Expr) (revArgs : Array Expr) : Expr :=
if revArgs.size == 0 then f
else betaRevAux revArgs revArgs.size f 0
def isHeadBetaTarget : Expr → Bool
| Expr.lam _ _ _ _ => true
| Expr.mdata _ b _ => isHeadBetaTarget b
| _ => false
def headBeta (e : Expr) : Expr :=
let f := e.getAppFn;
if f.isHeadBetaTarget then betaRev f e.getAppRevArgs else e
private def etaExpandedBody : Expr → Nat → Nat → Option Expr
| app f (bvar j _) _, n+1, i => if j == i then etaExpandedBody f n (i+1) else none
| _, n+1, _ => none
| f, 0, _ => if f.hasLooseBVars then none else some f
private def etaExpandedAux : Expr → Nat → Option Expr
| lam _ _ b _, n => etaExpandedAux b (n+1)
| e, n => etaExpandedBody e n 0
/--
If `e` is of the form `(fun x₁ ... xₙ => f x₁ ... xₙ)` and `f` does not contain `x₁`, ..., `xₙ`,
then return `some f`. Otherwise, return `none`.
It assumes `e` does not have loose bound variables.
Remark: `ₙ` may be 0 -/
def etaExpanded? (e : Expr) : Option Expr :=
etaExpandedAux e 0
/-- Similar to `etaExpanded?`, but only succeeds if `ₙ ≥ 1`. -/
def etaExpandedStrict? : Expr → Option Expr
| lam _ _ b _ => etaExpandedAux b 1
| _ => none
@[specialize] private partial def hasAnyFVarAux (p : FVarId → Bool) : Expr → Bool
| e => if !e.hasFVar then false else
match e with
| Expr.forallE _ d b _ => hasAnyFVarAux d || hasAnyFVarAux b
| Expr.lam _ d b _ => hasAnyFVarAux d || hasAnyFVarAux b
| Expr.mdata _ e _ => hasAnyFVarAux e
| Expr.letE _ t v b _ => hasAnyFVarAux t || hasAnyFVarAux v || hasAnyFVarAux b
| Expr.app f a _ => hasAnyFVarAux f || hasAnyFVarAux a
| Expr.proj _ _ e _ => hasAnyFVarAux e
| Expr.localE _ _ _ _ => unreachable!
| e@(Expr.fvar fvarId _) => p fvarId
| e => false
/-- Return true iff `e` contains a free variable which statisfies `p`. -/
@[inline] def hasAnyFVar (e : Expr) (p : FVarId → Bool) : Bool :=
hasAnyFVarAux p e
/- The update functions here are defined using C code. They will try to avoid
allocating new values using pointer equality.
The hypotheses `(h : e.is... = true)` are used to ensure Lean will not crash
at runtime.
The `update*!` functions are inlined and provide a convenient way of using the
update proofs without providing proofs.
Note that if they are used under a match-expression, the compiler will eliminate
the double-match. -/
@[extern "lean_expr_update_app"]
def updateApp (e : Expr) (newFn : Expr) (newArg : Expr) (h : e.isApp = true) : Expr :=
mkApp newFn newArg
@[inline] def updateApp! (e : Expr) (newFn : Expr) (newArg : Expr) : Expr :=
match e with
| app fn arg c => updateApp (app fn arg c) newFn newArg rfl
| _ => panic! "application expected"
@[extern "lean_expr_update_const"]
def updateConst (e : Expr) (newLevels : List Level) (h : e.isConst = true) : Expr :=
mkConst e.constName! newLevels
@[inline] def updateConst! (e : Expr) (newLevels : List Level) : Expr :=
match e with
| const n ls c => updateConst (const n ls c) newLevels rfl
| _ => panic! "constant expected"
@[extern "lean_expr_update_sort"]
def updateSort (e : Expr) (newLevel : Level) (h : e.isSort = true) : Expr :=
mkSort newLevel
@[inline] def updateSort! (e : Expr) (newLevel : Level) : Expr :=
match e with
| sort l c => updateSort (sort l c) newLevel rfl
| _ => panic! "level expected"
@[extern "lean_expr_update_proj"]
def updateProj (e : Expr) (newExpr : Expr) (h : e.isProj = true) : Expr :=
match e with
| proj s i _ _ => mkProj s i newExpr
| _ => e -- unreachable because of `h`
@[extern "lean_expr_update_mdata"]
def updateMData (e : Expr) (newExpr : Expr) (h : e.isMData = true) : Expr :=
match e with
| mdata d _ _ => mkMData d newExpr
| _ => e -- unreachable because of `h`
@[inline] def updateMData! (e : Expr) (newExpr : Expr) : Expr :=
match e with
| mdata d e c => updateMData (mdata d e c) newExpr rfl
| _ => panic! "mdata expected"
@[inline] def updateProj! (e : Expr) (newExpr : Expr) : Expr :=
match e with
| proj s i e c => updateProj (proj s i e c) newExpr rfl
| _ => panic! "proj expected"
@[extern "lean_expr_update_forall"]
def updateForall (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) (h : e.isForall = true) : Expr :=
mkForall e.bindingName! newBinfo newDomain newBody
@[inline] def updateForall! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| forallE n d b c => updateForall (forallE n d b c) newBinfo newDomain newBody rfl
| _ => panic! "forall expected"
@[inline] def updateForallE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| forallE n d b c => updateForall (forallE n d b c) c.binderInfo newDomain newBody rfl
| _ => panic! "forall expected"
@[extern "lean_expr_update_lambda"]
def updateLambda (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) (h : e.isLambda = true) : Expr :=
mkLambda e.bindingName! newBinfo newDomain newBody
@[inline] def updateLambda! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| lam n d b c => updateLambda (lam n d b c) newBinfo newDomain newBody rfl
| _ => panic! "lambda expected"
@[inline] def updateLambdaE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| lam n d b c => updateLambda (lam n d b c) c.binderInfo newDomain newBody rfl
| _ => panic! "lambda expected"
@[extern "lean_expr_update_let"]
def updateLet (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) (h : e.isLet = true) : Expr :=
mkLet e.letName! newType newVal newBody
@[inline] def updateLet! (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) : Expr :=
match e with
| letE n t v b c => updateLet (letE n t v b c) newType newVal newBody rfl
| _ => panic! "let expression expected"
def updateFn : Expr → Expr → Expr
| e@(app f a _), g => e.updateApp (updateFn f g) a rfl
| _, g => g
/- Instantiate level parameters -/
namespace InstantiateLevelParams
@[inline] def visit (f : Expr → Expr) (e : Expr) : Expr :=
if e.hasLevelParam then f e else e
@[specialize] partial def instantiate (s : Name → Option Level) : Expr → Expr
| e@(lam n d b _) => e.updateLambdaE! (visit instantiate d) (visit instantiate b)
| e@(forallE n d b _) => e.updateForallE! (visit instantiate d) (visit instantiate b)
| e@(letE n t v b _) => e.updateLet! (visit instantiate t) (visit instantiate v) (visit instantiate b)
| e@(app f a _) => e.updateApp (visit instantiate f) (visit instantiate a) rfl
| e@(proj _ _ s _) => e.updateProj (visit instantiate s) rfl
| e@(mdata _ b _) => e.updateMData (visit instantiate b) rfl
| e@(const _ us _) => e.updateConst (us.map (fun u => u.instantiateParams s)) rfl
| e@(sort u _) => e.updateSort (u.instantiateParams s) rfl
| localE _ _ _ _ => unreachable!
| e => e
end InstantiateLevelParams
@[inline] def instantiateLevelParamsCore (s : Name → Option Level) (e : Expr) : Expr :=
if e.hasLevelParam then InstantiateLevelParams.instantiate s e else e
private def getParamSubst : List Name → List Level → Name → Option Level
| p::ps, u::us, p' => if p == p' then some u else getParamSubst ps us p'
| _, _, _ => none
def instantiateLevelParams (e : Expr) (paramNames : List Name) (lvls : List Level) : Expr :=
instantiateLevelParamsCore (getParamSubst paramNames lvls) e
private partial def getParamSubstArray (ps : Array Name) (us : Array Level) (p' : Name) : Nat → Option Level
| i =>
if h : i < ps.size then
let p := ps.get ⟨i, h⟩;
if h : i < us.size then
let u := us.get ⟨i, h⟩;
if p == p' then some u else getParamSubstArray (i+1)
else none
else none
def instantiateLevelParamsArray (e : Expr) (paramNames : Array Name) (lvls : Array Level) : Expr :=
instantiateLevelParamsCore (fun p => getParamSubstArray paramNames lvls p 0) e
end Expr
end Lean
|
3c0e99d6863e4b1d6d8b281231600b2c9702f269 | fe208a542cea7b2d6d7ff79f94d535f6d11d814a | /src/Logic/Chris_Hughes.lean | 9da904d4d1aece05642874a84514efc990f2e559 | [] | no_license | ImperialCollegeLondon/M1F_room_342_questions | c4b98b14113fe900a7f388762269305faff73e63 | 63de9a6ab9c27a433039dd5530bc9b10b1d227f7 | refs/heads/master | 1,585,807,312,561 | 1,545,232,972,000 | 1,545,232,972,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 807 | lean | -- I cheated by making Rohan's proof constructive and evaluating it.
@[derive decidable_eq] inductive fml
| atom (i : ℕ)
| imp (a b : fml)
| not (a : fml)
open fml
infixr ` →' `:50 := imp -- right associative
prefix `¬' `:51 := fml.not
inductive prf : fml → Type
| axk {p q} : prf (p →' q →' p)
| axs {p q r} : prf $ (p →' q →' r) →' (p →' q) →' (p →' r)
| axX {p q} : prf $ ((¬' q) →' (¬' p)) →' p →' q
| mp {p q} : prf p → prf (p →' q) → prf q
| mp' {p q} : prf (p →' q) → prf p → prf q
open prf
theorem not_not_p_of_p (p : fml) : prf (p →' (¬' (¬' p))) :=
mp (mp (mp (@axk (¬' p) (¬' p)) axk)
(mp (mp (mp (mp (mp (@axk (¬' ¬' ¬' p) (¬' ¬' ¬' p)) (mp axk axs))
(mp (mp axk axk) axs)) (mp (mp axX axk) axs)) (mp (mp axX axk) axs)) axs)) axX
|
94df8f82f9bbbfb851de99ca5ff3497263c0cfa0 | e07b1aca72e83a272dd59d24c6e0fa246034d774 | /src/surreal/game/basic.lean | b1dac98b8acd11c6b3eba140148c19ec4551a9a1 | [] | no_license | pedrominicz/learn | 637a343bd4f8669d76819ac660a2d2d3e0958710 | b79b802a9846c86c21d4b6f3e17af36e7382f0ef | refs/heads/master | 1,671,746,990,402 | 1,670,778,113,000 | 1,670,778,113,000 | 265,735,177 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,398 | lean | import set_theory.game.pgame
import tactic.abel
open pgame
open_locale pgame
universes u v
namespace game
instance pgame.setoid : setoid pgame.{u} :=
⟨(≈), equiv_refl, @pgame.equiv.symm, @pgame.equiv.trans⟩
abbreviation game : Type (u+1) := quotient pgame.setoid.{u}
instance : add_comm_group game :=
{ zero := ⟦0⟧,
neg := quotient.lift (λ x, ⟦-x⟧) (λ x₁ x₂ h, quotient.sound ((@neg_equiv_neg_iff x₁ x₂).mpr h)),
add := quotient.lift₂ (λ x y : pgame, ⟦x + y⟧)
(λ x₁ y₁ x₂ y₂ hx hy, quotient.sound (add_congr hx hy)),
add_zero := by { rintro ⟨x⟩, exact quotient.sound (add_zero_equiv x) },
zero_add := by { rintro ⟨x⟩, exact quotient.sound (zero_add_equiv x) },
add_assoc := by { rintros ⟨x⟩ ⟨y⟩ ⟨z⟩, exact quotient.sound add_assoc_equiv },
add_left_neg := by { rintro ⟨x⟩, exact quotient.sound (add_left_neg_equiv x), },
add_comm := by { rintros ⟨x⟩ ⟨y⟩, exact quotient.sound add_comm_equiv } }
instance : has_one game := ⟨⟦1⟧⟩
instance : inhabited game := ⟨0⟩
instance : partial_order game :=
{ le := quotient.lift₂ (λ x y, x ≤ y) (λ x₁ y₁ x₂ y₂ hx hy, propext (le_congr hx hy)),
le_refl := by { rintro ⟨x⟩, exact le_refl x },
le_trans := by { rintros ⟨x⟩ ⟨y⟩ ⟨z⟩, exact @le_trans _ _ x y z },
le_antisymm := by { rintros ⟨x⟩ ⟨y⟩ h₁ h₂, exact quotient.sound ⟨h₁, h₂⟩ } }
def lf : game → game → Prop :=
quotient.lift₂ lf (λ x₁ y₁ x₂ y₂ hx hy, propext (lf_congr hx hy))
local infix ` ⧏ `:50 := lf
@[simp] theorem not_le : ∀ {x y : game}, ¬ x ≤ y ↔ y ⧏ x :=
by { rintro ⟨x⟩ ⟨y⟩, exact pgame.not_le }
@[simp] theorem not_lf : ∀ {x y : game}, ¬ x ⧏ y ↔ y ≤ x :=
by { rintro ⟨x⟩ ⟨y⟩, exact not_lf }
instance : is_trichotomous game (⧏) :=
⟨by { rintro ⟨x⟩ ⟨y⟩, change _ ∨ ⟦x⟧ = ⟦y⟧ ∨ _, rw quotient.eq, exact lf_or_equiv_or_gf x y }⟩
theorem _root_.pgame.le_iff_game_le {x y : pgame} : x ≤ y ↔ ⟦x⟧ ≤ ⟦y⟧ := iff.rfl
theorem _root_.pgame.lf_iff_game_lf {x y : pgame} : pgame.lf x y ↔ ⟦x⟧ ⧏ ⟦y⟧ := iff.rfl
theorem _root_.pgame.lt_iff_game_lt {x y : pgame} : x < y ↔ ⟦x⟧ < ⟦y⟧ := iff.rfl
theorem _root_.pgame.equiv_iff_game_eq {x y : pgame} : x ≈ y ↔ ⟦x⟧ = ⟦y⟧ :=
(@quotient.eq _ _ x y).symm
def fuzzy : game → game → Prop :=
quotient.lift₂ fuzzy (λ x₁ y₁ x₂ y₂ hx hy, propext (fuzzy_congr hx hy))
local infix ` ∥ `:50 := fuzzy
theorem _root_.pgame.fuzzy_iff_game_fuzzy {x y : pgame} : pgame.fuzzy x y ↔ ⟦x⟧ ∥ ⟦y⟧ := iff.rfl
instance covariant_class_add_le : covariant_class game game (+) (≤) :=
⟨by { rintro ⟨x⟩ ⟨y⟩ ⟨z⟩ h, exact @add_le_add_left _ _ _ _ y z h x }⟩
instance covariant_class_swap_add_le : covariant_class game game (function.swap (+)) (≤) :=
⟨by { rintro ⟨x⟩ ⟨y⟩ ⟨z⟩ h, exact @add_le_add_right _ _ _ _ y z h x }⟩
instance covariant_class_add_lt : covariant_class game game (+) (<) :=
⟨by { rintro ⟨x⟩ ⟨y⟩ ⟨z⟩ h, exact @add_lt_add_left _ _ _ _ y z h x }⟩
instance covariant_class_swap_add_lt : covariant_class game game (function.swap (+)) (<) :=
⟨by { rintro ⟨x⟩ ⟨y⟩ ⟨z⟩ h, exact @add_lt_add_right _ _ _ _ y z h x }⟩
theorem add_lf_add_right : ∀ {y z : game} (h : y ⧏ z) (x), y + x ⧏ z + x :=
by { rintro ⟨y⟩ ⟨z⟩ h ⟨x⟩, apply add_lf_add_right h }
theorem add_lf_add_left : ∀ {y z : game} (h : y ⧏ z) (x), x + y ⧏ x + z :=
by { rintro ⟨y⟩ ⟨z⟩ h ⟨x⟩, apply add_lf_add_left h }
instance ordered_add_comm_group : ordered_add_comm_group game :=
{ add_le_add_left := @add_le_add_left _ _ _ game.covariant_class_add_le,
..game.add_comm_group,
..game.partial_order }
end game
namespace pgame
@[simp] lemma quot_neg (x : pgame) : ⟦-x⟧ = -⟦x⟧ := rfl
@[simp] lemma quot_add (x y : pgame) : ⟦x + y⟧ = ⟦x⟧ + ⟦y⟧ := rfl
@[simp] lemma quot_sub (x y : pgame) : ⟦x - y⟧ = ⟦x⟧ - ⟦y⟧ := rfl
theorem quot_eq_of_mk_quot_eq {x y : pgame}
(L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves)
(hl : ∀ (i : x.left_moves), ⟦x.move_left i⟧ = ⟦y.move_left (L i)⟧)
(hr : ∀ (j : y.right_moves), ⟦x.move_right (R.symm j)⟧ = ⟦y.move_right j⟧) :
⟦x⟧ = ⟦y⟧ :=
begin
simp only [quotient.eq] at hl hr,
exact quotient.sound (equiv_of_mk_equiv L R hl hr)
end
def mul : pgame → pgame → pgame
| x@⟨xl, xr, xL, xR⟩ y@⟨yl, yr, yL, yR⟩ :=
⟨xl × yl ⊕ xr × yr, xl × yr ⊕ xr × yl,
@sum.rec _ _ (λ _, pgame)
(@prod.rec _ _ (λ _, pgame) (λ i₁ i₂, mul (xL i₁) y + mul x (yL i₂) - mul (xL i₁) (yL i₂)))
(@prod.rec _ _ (λ _, pgame) (λ j₁ j₂, mul (xR j₁) y + mul x (yR j₂) - mul (xR j₁) (yR j₂))),
@sum.rec _ _ (λ _, pgame)
(@prod.rec _ _ (λ _, pgame) (λ i j, mul (xL i) y + mul x (yR j) - mul (xL i) (yR j)))
(@prod.rec _ _ (λ _, pgame) (λ j i, mul (xR j) y + mul x (yL i) - mul (xR j) (yL i)))⟩
using_well_founded { dec_tac := pgame_wf_tac }
instance : has_mul pgame.{u} :=
⟨λ x y, begin
induction x with xl xr xL xR IHxl IHxr generalizing y,
induction y with yl yr yL yR IHyl IHyr,
have y := mk yl yr yL yR,
refine ⟨xl × yl ⊕ xr × yr, xl × yr ⊕ xr × yl, _, _⟩; rintro (⟨i, j⟩ | ⟨i, j⟩),
{ exact IHxl i y + IHyl j - IHxl i (yL j) },
{ exact IHxr i y + IHyr j - IHxr i (yR j) },
{ exact IHxl i y + IHyr j - IHxl i (yR j) },
{ exact IHxr i y + IHyl j - IHxr i (yL j) }
end⟩
example {x y : pgame} : x * y = mul x y :=
begin
induction x with xl xr xL xR IHxl IHxr generalizing y,
induction y with yl yr yL yR IHyl IHyr,
dsimp only [(*)],
unfold mul,
congr,
all_goals
{ ext,
change _ * _ + mk _ _ _ _ * _ - _ * _ = _,
congr; simp [IHxl, IHxr, IHyl, IHyr] }
end
theorem left_moves_mul : ∀ (x y : pgame.{u}), (x * y).left_moves
= (x.left_moves × y.left_moves ⊕ x.right_moves × y.right_moves)
| ⟨_, _, _, _⟩ ⟨_, _, _, _⟩ := rfl
theorem right_moves_mul : ∀ (x y : pgame.{u}), (x * y).right_moves
= (x.left_moves × y.right_moves ⊕ x.right_moves × y.left_moves)
| ⟨_, _, _, _⟩ ⟨_, _, _, _⟩ := rfl
def to_left_moves_mul {x y : pgame} :
x.left_moves × y.left_moves ⊕ x.right_moves × y.right_moves ≃ (x * y).left_moves :=
equiv.cast (left_moves_mul x y).symm
def to_right_moves_mul {x y : pgame} :
x.left_moves × y.right_moves ⊕ x.right_moves × y.left_moves ≃ (x * y).right_moves :=
equiv.cast (right_moves_mul x y).symm
@[simp] lemma mk_mul_move_left_inl {xl xr yl yr} {xL xR yL yR} {i j} :
(mk xl xr xL xR * mk yl yr yL yR).move_left (sum.inl (i, j))
= xL i * (mk yl yr yL yR) + (mk xl xr xL xR) * yL j - xL i * yL j :=
rfl
@[simp] lemma mul_move_left_inl {x y : pgame} {i j} :
(x * y).move_left (to_left_moves_mul (sum.inl (i, j)))
= x.move_left i * y + x * y.move_left j - x.move_left i * y.move_left j :=
by { cases x, cases y, refl }
@[simp] lemma mk_mul_move_left_inr {xl xr yl yr} {xL xR yL yR} {i j} :
(mk xl xr xL xR * mk yl yr yL yR).move_left (sum.inr (i, j))
= xR i * (mk yl yr yL yR) + (mk xl xr xL xR) * yR j - xR i * yR j :=
rfl
@[simp] lemma mul_move_left_inr {x y : pgame} {i j} :
(x * y).move_left (to_left_moves_mul (sum.inr (i, j)))
= x.move_right i * y + x * y.move_right j - x.move_right i * y.move_right j :=
by { cases x, cases y, refl }
@[simp] lemma mk_mul_move_right_inl {xl xr yl yr} {xL xR yL yR} {i j} :
(mk xl xr xL xR * mk yl yr yL yR).move_right (sum.inl (i, j))
= xL i * (mk yl yr yL yR) + (mk xl xr xL xR) * yR j - xL i * yR j :=
rfl
@[simp] lemma mul_move_right_inl {x y : pgame} {i j} :
(x * y).move_right (to_right_moves_mul (sum.inl (i, j)))
= x.move_left i * y + x * y.move_right j - x.move_left i * y.move_right j :=
by { cases x, cases y, refl }
@[simp] lemma mk_mul_move_right_inr {xl xr yl yr} {xL xR yL yR} {i j} :
(mk xl xr xL xR * mk yl yr yL yR).move_right (sum.inr (i, j))
= xR i * (mk yl yr yL yR) + (mk xl xr xL xR) * yL j - xR i * yL j :=
rfl
@[simp] lemma mul_move_right_inr {x y : pgame} {i j} :
(x * y).move_right (to_right_moves_mul (sum.inr (i, j)))
= x.move_right i * y + x * y.move_left j - x.move_right i * y.move_left j :=
by { cases x, cases y, refl }
lemma left_moves_mul_cases {x y : pgame} (k) {P : (x * y).left_moves → Prop}
(hl : ∀ ix iy, P $ to_left_moves_mul (sum.inl ⟨ix, iy⟩))
(hr : ∀ jx jy, P $ to_left_moves_mul (sum.inr ⟨jx, jy⟩)) : P k :=
begin
rw ←to_left_moves_mul.apply_symm_apply k,
rcases to_left_moves_mul.symm k with ⟨ix, iy⟩ | ⟨jx, jy⟩,
{ apply hl },
{ apply hr }
end
lemma right_moves_mul_cases {x y : pgame} (k) {P : (x * y).right_moves → Prop}
(hl : ∀ i j, P $ to_right_moves_mul (sum.inl ⟨i, j⟩))
(hr : ∀ j i, P $ to_right_moves_mul (sum.inr ⟨j, i⟩)) : P k :=
begin
rw ←to_right_moves_mul.apply_symm_apply k,
rcases to_right_moves_mul.symm k with ⟨i, j⟩ | ⟨j, i⟩,
{ apply hl },
{ apply hr }
end
theorem quot_mul_comm : Π (x y : pgame.{u}), ⟦x * y⟧ = ⟦y * x⟧
| (mk xl xr xL xR) (mk yl yr yL yR) :=
begin
refine quot_eq_of_mk_quot_eq
(equiv.sum_congr (equiv.prod_comm _ _) (equiv.prod_comm _ _))
((equiv.sum_comm _ _).trans (equiv.sum_congr (equiv.prod_comm _ _) (equiv.prod_comm _ _))) _ _;
all_goals { rintro (⟨i, j⟩ | ⟨i, j⟩); dsimp; rw [quot_mul_comm, quot_mul_comm (mk xl xr xL xR)] },
{ rw [quot_mul_comm (xL i), add_comm] },
{ rw [quot_mul_comm (xR i), add_comm] },
{ rw [quot_mul_comm (xR j), add_comm] },
{ rw [quot_mul_comm (xL j), add_comm] }
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem mul_comm_equiv (x y : pgame) : x * y ≈ y * x :=
quotient.exact $ quot_mul_comm _ _
instance is_empty_mul_zero_left_moves (x : pgame.{u}) : is_empty (x * 0).left_moves :=
by { cases x, apply sum.is_empty }
instance is_empty_mul_zero_right_moves (x : pgame.{u}) : is_empty (x * 0).right_moves :=
by { cases x, apply sum.is_empty }
instance is_empty_zero_mul_left_moves (x : pgame.{u}) : is_empty (0 * x).left_moves :=
by { cases x, apply sum.is_empty }
instance is_empty_zero_mul_right_moves (x : pgame.{u}) : is_empty (0 * x).right_moves :=
by { cases x, apply sum.is_empty }
def mul_zero_relabelling (x : pgame) : x * 0 ≡r 0 := relabelling.is_empty _
theorem mul_zero_equiv (x : pgame) : x * 0 ≈ 0 := (mul_zero_relabelling x).equiv
@[simp] theorem quot_mul_zero (x : pgame) : ⟦x * 0⟧ = ⟦0⟧ :=
@quotient.sound _ _ (x * 0) _ x.mul_zero_equiv
def zero_mul_relabelling (x : pgame) : 0 * x ≡r 0 := relabelling.is_empty _
theorem zero_mul_equiv (x : pgame) : 0 * x ≈ 0 := (zero_mul_relabelling x).equiv
@[simp] theorem quot_zero_mul (x : pgame) : ⟦0 * x⟧ = ⟦0⟧ :=
@quotient.sound _ _ (0 * x) _ x.zero_mul_equiv
@[simp] theorem quot_neg_mul : ∀ (x y : pgame), ⟦-x * y⟧ = -⟦x * y⟧
| (mk xl xr xL xR) (mk yl yr yL yR) :=
begin
let x := mk xl xr xL xR,
let y := mk yl yr yL yR,
refine quot_eq_of_mk_quot_eq _ _ _ _,
any_goals
{ fsplit; rintro (⟨_, _⟩ | ⟨_, _⟩);
solve_by_elim [sum.inl, sum.inr, prod.mk] { max_depth := 4 } },
all_goals
{ rintro (⟨_, _⟩ | ⟨_, _⟩),
all_goals
{ change ⟦-_ * y + (-x) * _ - (-_) * _⟧ = ⟦-(_ * y + x * _ - _ * _)⟧,
simp only [quot_add, quot_sub, quot_neg_mul],
simp, abel } }
end
using_well_founded { dec_tac := pgame_wf_tac }
@[simp] theorem quot_mul_neg (x y : pgame) : ⟦x * -y⟧ = -⟦x * y⟧ :=
by rw [quot_mul_comm, quot_neg_mul, quot_mul_comm]
@[simp] theorem quot_left_distrib : ∀ (x y z : pgame), ⟦x * (y + z)⟧ = ⟦x * y⟧ + ⟦x * z⟧
| (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) :=
begin
let x := mk xl xr xL xR,
let y := mk yl yr yL yR,
let z := mk zl zr zL zR,
refine quot_eq_of_mk_quot_eq _ _ _ _,
{ fsplit,
{ rintro (⟨_, _ | _⟩ | ⟨_, _ | _⟩);
solve_by_elim [sum.inl, sum.inr, prod.mk] { max_depth := 5 } },
{ rintro (⟨⟨_, _⟩ | ⟨_, _⟩⟩ | ⟨_, _⟩ | ⟨_, _⟩);
solve_by_elim [sum.inl, sum.inr, prod.mk] { max_depth := 5 } },
{ rintro (⟨_, _ | _⟩ | ⟨_, _ | _⟩); refl },
{ rintro (⟨⟨_, _⟩ | ⟨_, _⟩⟩ | ⟨_, _⟩ | ⟨_, _⟩); refl } },
{ fsplit,
{ rintro (⟨_, _ | _⟩ | ⟨_, _ | _⟩);
solve_by_elim [sum.inl, sum.inr, prod.mk] { max_depth := 5 } },
{ rintro (⟨⟨_, _⟩ | ⟨_, _⟩⟩ | ⟨_, _⟩ | ⟨_, _⟩);
solve_by_elim [sum.inl, sum.inr, prod.mk] { max_depth := 5 } },
{ rintro (⟨_, _ | _⟩ | ⟨_, _ | _⟩); refl },
{ rintro (⟨⟨_, _⟩ | ⟨_, _⟩⟩ | ⟨_, _⟩ | ⟨_, _⟩); refl } },
{ rintro (⟨i, j | k⟩ | ⟨i, j | k⟩),
{ change ⟦xL i * (y + z) + x * (yL j + z) - xL i * (yL j + z)⟧
= ⟦xL i * y + x * yL j - xL i * yL j + x * z⟧,
simp [quot_left_distrib], abel },
{ change ⟦xL i * (y + z) + x * (y + zL k) - xL i * (y + zL k)⟧
= ⟦x * y + (xL i * z + x * zL k - xL i * zL k)⟧,
simp [quot_left_distrib], abel },
{ change ⟦xR i * (y + z) + x * (yR j + z) - xR i * (yR j + z)⟧
= ⟦xR i * y + x * yR j - xR i * yR j + x * z⟧,
simp [quot_left_distrib], abel },
{ change ⟦xR i * (y + z) + x * (y + zR k) - xR i * (y + zR k)⟧
= ⟦x * y + (xR i * z + x * zR k - xR i * zR k)⟧,
simp [quot_left_distrib], abel } },
{ rintro (⟨⟨i, j⟩ | ⟨i, j⟩⟩ | ⟨i, k⟩ | ⟨i, k⟩),
{ change ⟦xL i * (y + z) + x * (yR j + z) - xL i * (yR j + z)⟧
= ⟦xL i * y + x * yR j - xL i * yR j + x * z⟧,
simp [quot_left_distrib], abel },
{ change ⟦xR i * (y + z) + x * (yL j + z) - xR i * (yL j + z)⟧
= ⟦xR i * y + x * yL j - xR i * yL j + x * z⟧,
simp [quot_left_distrib], abel },
{ change ⟦xL i * (y + z) + x * (y + zR k) - xL i * (y + zR k)⟧
= ⟦x * y + (xL i * z + x * zR k - xL i * zR k)⟧,
simp [quot_left_distrib], abel },
{ change ⟦xR i * (y + z) + x * (y + zL k) - xR i * (y + zL k)⟧
= ⟦x * y + (xR i * z + x * zL k - xR i * zL k)⟧,
simp [quot_left_distrib], abel } }
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem left_distrib_equiv (x y z : pgame) : x * (y + z) ≈ x * y + x * z :=
quotient.exact $ quot_left_distrib _ _ _
@[simp] theorem quot_left_distrib_sub (x y z : pgame) : ⟦x * (y - z)⟧ = ⟦x * y⟧ - ⟦x * z⟧ :=
by { change ⟦x * (y + -z)⟧ = ⟦x * y⟧ + -⟦x * z⟧, rw [quot_left_distrib, quot_mul_neg] }
@[simp] theorem quot_right_distrib (x y z : pgame) : ⟦(x + y) * z⟧ = ⟦x * z⟧ + ⟦y * z⟧ :=
by simp only [quot_mul_comm, quot_left_distrib]
theorem right_distrib_equiv (x y z : pgame) : (x + y) * z ≈ x * z + y * z :=
quotient.exact $ quot_right_distrib _ _ _
@[simp] theorem quot_right_distrib_sub (x y z : pgame) : ⟦(y - z) * x⟧ = ⟦y * x⟧ - ⟦z * x⟧ :=
by { change ⟦(y + -z) * x⟧ = ⟦y * x⟧ + -⟦z * x⟧, rw [quot_right_distrib, quot_neg_mul] }
@[simp] theorem quot_mul_one : ∀ (x : pgame), ⟦x * 1⟧ = ⟦x⟧
| (mk xl xr xL xR) :=
begin
let x := mk xl xr xL xR,
refine quot_eq_of_mk_quot_eq _ _ _ _,
{ fsplit,
{ rintro (⟨_, ⟨⟩⟩ | ⟨_, ⟨⟩⟩), assumption },
{ rintro i, exact sum.inl (i, punit.star) },
{ rintro (⟨_, ⟨⟩⟩ | ⟨_, ⟨⟩⟩), refl },
{ rintro i, refl } },
{ fsplit,
{ rintro (⟨_, ⟨⟩⟩ | ⟨_, ⟨⟩⟩), assumption },
{ rintro i, exact sum.inr (i, punit.star) },
{ rintro (⟨_, ⟨⟩⟩ | ⟨_, ⟨⟩⟩), refl },
{ rintro i, refl } },
{ rintro (⟨i, ⟨⟩⟩ | ⟨_, ⟨⟩⟩),
change ⟦xL i * 1 + x * 0 - xL i * 0⟧ = ⟦xL i⟧,
simp [quot_mul_one] },
{ rintro i,
change ⟦xR i * 1 + x * 0 - xR i * 0⟧ = ⟦xR i⟧,
simp [quot_mul_one] }
end
theorem mul_one_equiv (x : pgame) : x * 1 ≈ x := quotient.exact $ quot_mul_one _
@[simp] theorem quot_one_mul (x : pgame) : ⟦1 * x⟧ = ⟦x⟧ :=
by rw [quot_mul_comm, quot_mul_one x]
theorem one_mul_equiv (x : pgame) : 1 * x ≈ x := quotient.exact $ quot_one_mul _
theorem quot_mul_assoc : ∀ (x y z : pgame), ⟦x * y * z⟧ = ⟦x * (y * z)⟧
| (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) :=
begin
let x := mk xl xr xL xR,
let y := mk yl yr yL yR,
let z := mk zl zr zL zR,
refine quot_eq_of_mk_quot_eq _ _ _ _,
{ fsplit,
{ rintro (⟨⟨_, _⟩ | ⟨_, _⟩, _⟩ | ⟨⟨_, _⟩ | ⟨_, _⟩, _⟩);
solve_by_elim [sum.inl, sum.inr, prod.mk] { max_depth := 7 } },
{ rintro (⟨_, ⟨_, _⟩ | ⟨_, _⟩⟩ | ⟨_,⟨_, _⟩ | ⟨_, _⟩⟩);
solve_by_elim [sum.inl, sum.inr, prod.mk] { max_depth := 7 } },
{ rintro (⟨⟨_, _⟩ | ⟨_, _⟩, _⟩ | ⟨⟨_,_⟩ | ⟨_, _⟩,_⟩); refl },
{ rintro (⟨_, ⟨_, _⟩ | ⟨_, _⟩⟩ | ⟨_,⟨_, _⟩ | ⟨_, _⟩⟩); refl } },
{ fsplit,
{ rintro (⟨⟨_, _⟩ | ⟨_, _⟩, _⟩ | ⟨⟨_, _⟩ | ⟨_, _⟩,_⟩);
solve_by_elim [sum.inl, sum.inr, prod.mk] { max_depth := 7 } },
{ rintro (⟨_, ⟨_, _⟩ | ⟨_, _⟩⟩ | ⟨_, ⟨_, _⟩ | ⟨_, _⟩⟩);
solve_by_elim [sum.inl, sum.inr, prod.mk] { max_depth := 7 } },
{ rintro (⟨⟨_, _⟩ | ⟨_, _⟩, _⟩ | ⟨⟨_, _⟩ | ⟨_, _⟩,_⟩); refl },
{ rintro (⟨_, ⟨_, _⟩ | ⟨_, _⟩⟩ | ⟨_, ⟨_, _⟩ | ⟨_, _⟩⟩); refl } },
all_goals
{ try { rintro (⟨⟨_, _⟩ | ⟨_, _⟩, _⟩ | ⟨⟨_, _⟩ | ⟨_, _⟩, _⟩) },
try { rintro (⟨_, ⟨_, _⟩ | ⟨_, _⟩⟩ | ⟨_, ⟨_, _⟩ | ⟨_, _⟩⟩) },
all_goals
{ change ⟦(_ * y + x * _ - _ * _) * z + (x * y) * _
- (_ * y + x * _ - _ * _) * _⟧
= ⟦_ * (y * z) + x * (_ * z + y * _ - _ * _)
- _ * (_ * z + y * _ - _ * _)⟧,
simp [quot_mul_assoc], abel } },
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem mul_assoc_equiv (x y z : pgame) : x * y * z ≈ x * (y * z) :=
quotient.exact $ quot_mul_assoc _ _ _
section
parameters {l r : Type u}
inductive inv_ty (l r : Type u) : bool → Type u
| zero : inv_ty ff
| left₁ : r → inv_ty ff → inv_ty ff
| left₂ : l → inv_ty tt → inv_ty ff
| right₁ : l → inv_ty ff → inv_ty tt
| right₂ : r → inv_ty tt → inv_ty tt
mutual inductive inv_ty_ff, inv_ty_tt (l r : Type u)
with inv_ty_ff : Type u
| zero : inv_ty_ff
| left₁ : r → inv_ty_ff → inv_ty_ff
| left₂ : l → inv_ty_tt → inv_ty_ff
with inv_ty_tt : Type u
| right₁ : l → inv_ty_ff → inv_ty_tt
| right₂ : r → inv_ty_tt → inv_ty_tt
def inv_ty' : bool → Type u
| ff := inv_ty_ff
| tt := inv_ty_tt
def inv_ty'.sizeof : (Σ' b, inv_ty' b) → ℕ
| ⟨ff, x⟩ := @sizeof inv_ty_ff _ x
| ⟨tt, x⟩ := @sizeof inv_ty_tt _ x
meta def inv_ty'.rel_tac : expr → list expr → tactic unit :=
λ _ _, `[exact ⟨_, measure_wf inv_ty'.sizeof⟩]
@[simp] def inv_ty'.rec {C : Π b, inv_ty' b → Sort v}
(hz : C ff inv_ty_ff.zero)
(hl₁ : Π {j x}, C ff x → C ff (inv_ty_ff.left₁ j x))
(hl₂ : Π {i x}, C tt x → C ff (inv_ty_ff.left₂ i x))
(hr₁ : Π {i x}, C ff x → C tt (inv_ty_tt.right₁ i x))
(hr₂ : Π {j x}, C tt x → C tt (inv_ty_tt.right₂ j x))
: Π {b} x, C b x
| ff inv_ty_ff.zero := hz
| ff (inv_ty_ff.left₁ _ x) := hl₁ (@inv_ty'.rec ff x)
| ff (inv_ty_ff.left₂ _ x) := hl₂ (@inv_ty'.rec tt x)
| tt (inv_ty_tt.right₁ _ x) := hr₁ (@inv_ty'.rec ff x)
| tt (inv_ty_tt.right₂ _ x) := hr₂ (@inv_ty'.rec tt x)
using_well_founded { rel_tac := inv_ty'.rel_tac }
@[simp] def f_aux : Π {b}, inv_ty b → inv_ty' b
| _ inv_ty.zero := inv_ty_ff.zero
| _ (inv_ty.left₁ j x) := inv_ty_ff.left₁ j (f_aux x)
| _ (inv_ty.left₂ i x) := inv_ty_ff.left₂ i (f_aux x)
| _ (inv_ty.right₁ i x) := inv_ty_tt.right₁ i (f_aux x)
| _ (inv_ty.right₂ j x) := inv_ty_tt.right₂ j (f_aux x)
@[simp] def f : (Σ b, inv_ty b) → Σ b, inv_ty' b
| ⟨_, x⟩ := ⟨_, f_aux x⟩
@[simp] def f_inv_aux : Π b, inv_ty' b → inv_ty b
| ff inv_ty_ff.zero := inv_ty.zero
| ff (inv_ty_ff.left₁ j x) := inv_ty.left₁ j (f_inv_aux ff x)
| ff (inv_ty_ff.left₂ i x) := inv_ty.left₂ i (f_inv_aux tt x)
| tt (inv_ty_tt.right₁ i x) := inv_ty.right₁ i (f_inv_aux ff x)
| tt (inv_ty_tt.right₂ j x) := inv_ty.right₂ j (f_inv_aux tt x)
using_well_founded { rel_tac := inv_ty'.rel_tac }
@[simp] def f_inv : (Σ b, inv_ty' b) → Σ b, inv_ty b
| ⟨_, x⟩ := ⟨_, f_inv_aux _ x⟩
example : (Σ b, inv_ty b) ≃ Σ b, inv_ty' b :=
by refine ⟨f, f_inv, _, _⟩; rintro ⟨_, x⟩; induction x; simp * at *
end
instance (l r : Type u) [is_empty l] [is_empty r] : is_empty (inv_ty l r tt) :=
⟨by rintro (_|_|_|a|a); exact is_empty_elim a⟩
instance (l r : Type u) : inhabited (inv_ty l r ff) := ⟨inv_ty.zero⟩
instance unique_inv_ty (l r : Type u) [is_empty l] [is_empty r] : unique (inv_ty l r ff) :=
⟨_, by { rintro (_|a|a), refl, all_goals { exact is_empty_elim a } }⟩
def inv_val {l r} (L : l → pgame) (R : r → pgame)
(IHl : l → pgame) (IHr : r → pgame) : ∀ {b}, inv_ty l r b → pgame
| _ inv_ty.zero := 0
| _ (inv_ty.left₁ j x) := (1 + (R j - mk l r L R) * inv_val x) * IHr j
| _ (inv_ty.left₂ i x) := (1 + (L i - mk l r L R) * inv_val x) * IHl i
| _ (inv_ty.right₁ i x) := (1 + (L i - mk l r L R) * inv_val x) * IHl i
| _ (inv_ty.right₂ j x) := (1 + (R j - mk l r L R) * inv_val x) * IHr j
@[simp] theorem inv_val_is_empty {l r b} (L R IHl IHr) (x : inv_ty l r b)
[is_empty l] [is_empty r] : inv_val L R IHl IHr x = 0 :=
by { cases x with a _ a _ a _ a, refl, all_goals { exact is_empty_elim a } }
def inv' : pgame → pgame
| ⟨l, r, L, R⟩ :=
let l' := {i // 0 < L i},
L' : l' → pgame := λ i, L i.1,
IHl' : l' → pgame := λ i, inv' (L i.1),
IHr := λ i, inv' (R i) in
⟨inv_ty l' r ff, inv_ty l' r tt,
inv_val L' R IHl' IHr, inv_val L' R IHl' IHr⟩
def inv'' : pgame → pgame
| ⟨l, r, L, R⟩ := begin
let l' := {i // 0 < L i},
let L' := λ i : l', L i.1,
let IHl' := λ i : l', inv'' (L i.1),
let IHr := λ j, inv'' (R j),
exact ⟨inv_ty l' r ff, inv_ty l' r tt, inv_val L' R IHl' IHr, inv_val L' R IHl' IHr⟩
end
example : inv' = inv'' :=
begin
ext x,
induction x with _ _ _ _ IHl _,
dsimp only [inv'],
congr; ext; solve_by_elim [λ i, IHl (subtype.val i)]
end
def inv''' (x : pgame) : pgame :=
begin
induction x with l r L R IHl IHr,
let l' := {i // 0 < L i},
let L' := λ i : l', L i.1,
let IHl' := λ i : l', IHl i.1,
exact ⟨inv_ty l' r ff, inv_ty l' r tt, inv_val L' R IHl' IHr, inv_val L' R IHl' IHr⟩
end
example : inv' = inv''' :=
begin
ext x,
induction x with _ _ _ _ IHl _,
dsimp only [inv'],
congr; ext; solve_by_elim [λ i, IHl (subtype.val i)]
end
theorem zero_lf_inv' : ∀ (x : pgame), 0 ⧏ inv' x
| ⟨xl, xr, xL, xR⟩ := by { convert lf_mk _ _ inv_ty.zero, refl }
def inv'_zero : inv' 0 ≡r 1 :=
begin
change mk _ _ _ _ ≡r 1,
refine ⟨_, _, λ i, _, is_empty_elim⟩,
{ dsimp, apply equiv.equiv_punit },
{ dsimp, apply equiv.equiv_pempty },
{ simp }
end
theorem inv'_zero_equiv : inv' 0 ≈ 1 := inv'_zero.equiv
def inv'_one : inv' 1 ≡r (1 : pgame.{u}) :=
begin
change mk _ _ _ _ ≡r 1,
haveI : is_empty {i : punit.{u+1} // (0 : pgame.{u}) < 0},
{ rw lt_self_iff_false, apply_instance },
refine ⟨_, _, λ i, _, is_empty_elim⟩,
{ dsimp, apply equiv.equiv_punit },
{ dsimp, apply equiv.equiv_pempty },
{ simp }
end
theorem inv'_one_equiv : inv' 1 ≈ 1 := inv'_one.equiv
noncomputable instance : has_inv pgame :=
⟨by { classical, exact λ x, if x ≈ 0 then 0 else if 0 < x then inv' x else -inv' (-x) }⟩
noncomputable instance : has_div pgame := ⟨λ x y, x * y⁻¹⟩
theorem inv_eq_of_equiv_zero {x : pgame} (h : x ≈ 0) : x⁻¹ = 0 := if_pos h
@[simp] theorem inv_zero : (0 : pgame)⁻¹ = 0 :=
inv_eq_of_equiv_zero (equiv_refl _)
theorem inv_eq_of_pos {x : pgame} (h : 0 < x) : x⁻¹ = inv' x :=
(if_neg h.lf.not_equiv').trans (if_pos h)
theorem inv_eq_of_lf_zero {x : pgame} (h : x ⧏ 0) : x⁻¹ = -inv' (-x) :=
(if_neg h.not_equiv).trans (if_neg h.not_gt)
def inv_one : 1⁻¹ ≡r 1 :=
by { rw inv_eq_of_pos zero_lt_one, exact inv'_one }
theorem inv_one_equiv : 1⁻¹ ≈ 1 := inv_one.equiv
end pgame |
ac78ee2d0542d75202c82be1948c2e4692f01386 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/ring_theory/unique_factorization_domain.lean | 9ccc24e783f57b63cb150b98393e0b6dd8dcfacb | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 50,263 | 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, Jens Wagemaker, Aaron Anderson
-/
import algebra.gcd_monoid
import ring_theory.integral_domain
import ring_theory.noetherian
/-!
# Unique factorization
## Main Definitions
* `wf_dvd_monoid` holds for `monoid`s for which a strict divisibility relation is
well-founded.
* `unique_factorization_monoid` holds for `wf_dvd_monoid`s where
`irreducible` is equivalent to `prime`
## To do
* set up the complete lattice structure on `factor_set`.
-/
variables {α : Type*}
local infix ` ~ᵤ ` : 50 := associated
/-- Well-foundedness of the strict version of |, which is equivalent to the descending chain
condition on divisibility and to the ascending chain condition on
principal ideals in an integral domain.
-/
class wf_dvd_monoid (α : Type*) [comm_monoid_with_zero α] : Prop :=
(well_founded_dvd_not_unit : well_founded (@dvd_not_unit α _))
export wf_dvd_monoid (well_founded_dvd_not_unit)
@[priority 100] -- see Note [lower instance priority]
instance is_noetherian_ring.wf_dvd_monoid [integral_domain α] [is_noetherian_ring α] :
wf_dvd_monoid α :=
⟨by { convert inv_image.wf (λ a, ideal.span ({a} : set α)) (well_founded_submodule_gt _ _),
ext,
exact ideal.span_singleton_lt_span_singleton.symm }⟩
namespace wf_dvd_monoid
variables [comm_monoid_with_zero α]
open associates nat
theorem of_wf_dvd_monoid_associates (h : wf_dvd_monoid (associates α)): wf_dvd_monoid α :=
⟨begin
haveI := h,
refine (surjective.well_founded_iff mk_surjective _).2 wf_dvd_monoid.well_founded_dvd_not_unit,
intros, rw mk_dvd_not_unit_mk_iff
end⟩
variables [wf_dvd_monoid α]
instance wf_dvd_monoid_associates : wf_dvd_monoid (associates α) :=
⟨begin
refine (surjective.well_founded_iff mk_surjective _).1 wf_dvd_monoid.well_founded_dvd_not_unit,
intros, rw mk_dvd_not_unit_mk_iff
end⟩
theorem well_founded_associates : well_founded ((<) : associates α → associates α → Prop) :=
subrelation.wf (λ x y, dvd_not_unit_of_lt) wf_dvd_monoid.well_founded_dvd_not_unit
local attribute [elab_as_eliminator] well_founded.fix
lemma exists_irreducible_factor {a : α} (ha : ¬ is_unit a) (ha0 : a ≠ 0) :
∃ i, irreducible i ∧ i ∣ a :=
(irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_refl _⟩)
(well_founded.fix
wf_dvd_monoid.well_founded_dvd_not_unit
(λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩,
have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]),
(irreducible_or_factor x hx).elim
(λ hxi, ⟨x, hxi, hxy ▸ by simp⟩)
(λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in
⟨i, hi.1, dvd.trans hi.2 (hxy ▸ by simp)⟩)) a ha ha0)
@[elab_as_eliminator] lemma induction_on_irreducible {P : α → Prop} (a : α)
(h0 : P 0) (hu : ∀ u : α, is_unit u → P u)
(hi : ∀ a i : α, a ≠ 0 → irreducible i → P a → P (i * a)) :
P a :=
by haveI := classical.dec; exact
well_founded.fix wf_dvd_monoid.well_founded_dvd_not_unit
(λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0
else if hau : is_unit a then hu a hau
else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in
have hb0 : b ≠ 0, from λ hb0, by simp * at *,
hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i,
hii.1, by rw [hb, mul_comm]⟩))
a
lemma exists_factors (a : α) : a ≠ 0 →
∃f : multiset α, (∀b ∈ f, irreducible b) ∧ associated f.prod a :=
wf_dvd_monoid.induction_on_irreducible a
(λ h, (h rfl).elim)
(λ u hu _, ⟨0, ⟨by simp [hu], associated.symm (by simp [hu, associated_one_iff_is_unit])⟩⟩)
(λ a i ha0 hii ih hia0,
let ⟨s, hs⟩ := ih ha0 in
⟨i ::ₘ s, ⟨by clear _let_match; finish,
by { rw multiset.prod_cons,
exact associated_mul_mul (by refl) hs.2 }⟩⟩)
end wf_dvd_monoid
theorem wf_dvd_monoid.of_well_founded_associates [comm_cancel_monoid_with_zero α]
(h : well_founded ((<) : associates α → associates α → Prop)) : wf_dvd_monoid α :=
wf_dvd_monoid.of_wf_dvd_monoid_associates
⟨by { convert h, ext, exact associates.dvd_not_unit_iff_lt }⟩
theorem wf_dvd_monoid.iff_well_founded_associates [comm_cancel_monoid_with_zero α] :
wf_dvd_monoid α ↔ well_founded ((<) : associates α → associates α → Prop) :=
⟨by apply wf_dvd_monoid.well_founded_associates, wf_dvd_monoid.of_well_founded_associates⟩
section prio
set_option default_priority 100 -- see Note [default priority]
/-- unique factorization monoids.
These are defined as `comm_cancel_monoid_with_zero`s with well-founded strict divisibility
relations, but this is equivalent to more familiar definitions:
Each element (except zero) is uniquely represented as a multiset of irreducible factors.
Uniqueness is only up to associated elements.
Each element (except zero) is non-uniquely represented as a multiset
of prime factors.
To define a UFD using the definition in terms of multisets
of irreducible factors, use the definition `of_exists_unique_irreducible_factors`
To define a UFD using the definition in terms of multisets
of prime factors, use the definition `of_exists_prime_factors`
-/
class unique_factorization_monoid (α : Type*) [comm_cancel_monoid_with_zero α]
extends wf_dvd_monoid α : Prop :=
(irreducible_iff_prime : ∀ {a : α}, irreducible a ↔ prime a)
instance ufm_of_gcd_of_wf_dvd_monoid [nontrivial α] [comm_cancel_monoid_with_zero α]
[wf_dvd_monoid α] [gcd_monoid α] : unique_factorization_monoid α :=
{ irreducible_iff_prime := λ _, gcd_monoid.irreducible_iff_prime
.. ‹wf_dvd_monoid α› }
instance associates.ufm [comm_cancel_monoid_with_zero α]
[unique_factorization_monoid α] : unique_factorization_monoid (associates α) :=
{ irreducible_iff_prime := by { rw ← associates.irreducible_iff_prime_iff,
apply unique_factorization_monoid.irreducible_iff_prime, }
.. (wf_dvd_monoid.wf_dvd_monoid_associates : wf_dvd_monoid (associates α)) }
end prio
namespace unique_factorization_monoid
variables [comm_cancel_monoid_with_zero α] [unique_factorization_monoid α]
theorem exists_prime_factors (a : α) : a ≠ 0 →
∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a :=
by { simp_rw ← unique_factorization_monoid.irreducible_iff_prime,
apply wf_dvd_monoid.exists_factors a }
@[elab_as_eliminator] lemma induction_on_prime {P : α → Prop}
(a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x)
(h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a :=
begin
simp_rw ← unique_factorization_monoid.irreducible_iff_prime at h₃,
exact wf_dvd_monoid.induction_on_irreducible a h₁ h₂ h₃,
end
lemma factors_unique : ∀{f g : multiset α},
(∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod ~ᵤ g.prod →
multiset.rel associated f g :=
by haveI := classical.dec_eq α; exact
λ f, multiset.induction_on f
(λ g _ hg h,
multiset.rel_zero_left.2 $
multiset.eq_zero_of_forall_not_mem (λ x hx,
have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm,
(hg x hx).not_unit (is_unit_iff_dvd_one.2 (dvd.trans (multiset.dvd_prod hx)
(is_unit_iff_dvd_one.1 this)))))
(λ p f ih g hf hg hfg,
let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod
(irreducible_iff_prime.1 (hf p (by simp)))
(λ q hq, irreducible_iff_prime.1 (hg _ hq)) $
(dvd_iff_dvd_of_rel_right hfg).1
(show p ∣ (p ::ₘ f).prod, by simp) in
begin
rw ← multiset.cons_erase hbg,
exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq]))
(λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq))
(associated_mul_left_cancel
(by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb
(hf p (by simp)).ne_zero))
end)
end unique_factorization_monoid
lemma prime_factors_unique [comm_cancel_monoid_with_zero α] : ∀ {f g : multiset α},
(∀ x ∈ f, prime x) → (∀ x ∈ g, prime x) → f.prod ~ᵤ g.prod →
multiset.rel associated f g :=
by haveI := classical.dec_eq α; exact
λ f, multiset.induction_on f
(λ g _ hg h,
multiset.rel_zero_left.2 $
multiset.eq_zero_of_forall_not_mem $ λ x hx,
have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm,
(irreducible_of_prime $ hg x hx).not_unit $ is_unit_iff_dvd_one.2 $
dvd.trans (multiset.dvd_prod hx) (is_unit_iff_dvd_one.1 this))
(λ p f ih g hf hg hfg,
let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod
(hf p (by simp)) (λ q hq, hg _ hq) $
(dvd_iff_dvd_of_rel_right hfg).1
(show p ∣ (p ::ₘ f).prod, by simp) in
begin
rw ← multiset.cons_erase hbg,
exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq]))
(λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq))
(associated_mul_left_cancel
(by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb
(hf p (by simp)).ne_zero))
end)
/-- If an irreducible has a prime factorization,
then it is an associate of one of its prime factors. -/
lemma prime_factors_irreducible [comm_cancel_monoid_with_zero α] {a : α} {f : multiset α}
(ha : irreducible a) (pfa : (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) :
∃ p, a ~ᵤ p ∧ f = p ::ₘ 0 :=
begin
haveI := classical.dec_eq α,
refine multiset.induction_on f (λ h, (ha.not_unit
(associated_one_iff_is_unit.1 (associated.symm h))).elim) _ pfa.2 pfa.1,
rintros p s _ ⟨u, hu⟩ hs,
use p,
have hs0 : s = 0,
{ by_contra hs0,
obtain ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0,
apply (hs q (by simp [hq])).2.1,
refine (ha.is_unit_or_is_unit (_ : _ = ((p * ↑u) * (s.erase q).prod) * _)).resolve_left _,
{ rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq, ← hu,
mul_comm, mul_comm p _, mul_assoc],
simp, },
apply mt is_unit_of_mul_is_unit_left (mt is_unit_of_mul_is_unit_left _),
apply (hs p (multiset.mem_cons_self _ _)).2.1 },
simp only [mul_one, multiset.prod_cons, multiset.prod_zero, hs0] at *,
exact ⟨associated.symm ⟨u, hu⟩, rfl⟩,
end
section exists_prime_factors
variables [comm_cancel_monoid_with_zero α]
variables (pf : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a)
include pf
lemma wf_dvd_monoid.of_exists_prime_factors : wf_dvd_monoid α :=
⟨begin
classical,
apply rel_hom.well_founded (rel_hom.mk _ _) (with_top.well_founded_lt nat.lt_wf),
{ intro a,
by_cases h : a = 0, { exact ⊤ },
exact (classical.some (pf a h)).card },
rintros a b ⟨ane0, ⟨c, hc, b_eq⟩⟩,
rw dif_neg ane0,
by_cases h : b = 0, { simp [h, lt_top_iff_ne_top] },
rw [dif_neg h, with_top.coe_lt_coe],
have cne0 : c ≠ 0, { refine mt (λ con, _) h, rw [b_eq, con, mul_zero] },
calc multiset.card (classical.some (pf a ane0))
< _ + multiset.card (classical.some (pf c cne0)) :
lt_add_of_pos_right _ (multiset.card_pos.mpr (λ con, hc (associated_one_iff_is_unit.mp _)))
... = multiset.card (classical.some (pf a ane0) + classical.some (pf c cne0)) :
(multiset.card_add _ _).symm
... = multiset.card (classical.some (pf b h)) :
multiset.card_eq_card_of_rel (prime_factors_unique _ (classical.some_spec (pf _ h)).1 _),
{ convert (classical.some_spec (pf c cne0)).2.symm,
rw [con, multiset.prod_zero] },
{ intros x hadd,
rw multiset.mem_add at hadd,
cases hadd; apply (classical.some_spec (pf _ _)).1 _ hadd },
{ rw multiset.prod_add,
transitivity a * c,
{ apply associated_mul_mul; apply (classical.some_spec (pf _ _)).2 },
{ rw ← b_eq,
apply (classical.some_spec (pf _ _)).2.symm, } }
end⟩
lemma irreducible_iff_prime_of_exists_prime_factors {p : α} : irreducible p ↔ prime p :=
begin
by_cases hp0 : p = 0,
{ simp [hp0] },
refine ⟨λ h, _, irreducible_of_prime⟩,
obtain ⟨f, hf⟩ := pf p hp0,
obtain ⟨q, hq, rfl⟩ := prime_factors_irreducible h hf,
rw prime_iff_of_associated hq,
exact hf.1 q (multiset.mem_cons_self _ _)
end
theorem unique_factorization_monoid.of_exists_prime_factors :
unique_factorization_monoid α :=
{ irreducible_iff_prime := λ _, irreducible_iff_prime_of_exists_prime_factors pf,
.. wf_dvd_monoid.of_exists_prime_factors pf }
end exists_prime_factors
theorem unique_factorization_monoid.iff_exists_prime_factors [comm_cancel_monoid_with_zero α] :
unique_factorization_monoid α ↔
(∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) :=
⟨λ h, @unique_factorization_monoid.exists_prime_factors _ _ h,
unique_factorization_monoid.of_exists_prime_factors⟩
theorem irreducible_iff_prime_of_exists_unique_irreducible_factors [comm_cancel_monoid_with_zero α]
(eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a)
(uif : ∀ (f g : multiset α),
(∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod →
multiset.rel associated f g)
(p : α) : irreducible p ↔ prime p :=
⟨by letI := classical.dec_eq α; exact λ hpi,
⟨hpi.ne_zero, hpi.1,
λ a b ⟨x, hx⟩,
if hab0 : a * b = 0
then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim
(λ ha0, by simp [ha0])
(λ hb0, by simp [hb0])
else
have hx0 : x ≠ 0, from λ hx0, by simp * at *,
have ha0 : a ≠ 0, from left_ne_zero_of_mul hab0,
have hb0 : b ≠ 0, from right_ne_zero_of_mul hab0,
begin
cases eif x hx0 with fx hfx,
cases eif a ha0 with fa hfa,
cases eif b hb0 with fb hfb,
have h : multiset.rel associated (p ::ₘ fx) (fa + fb),
{ apply uif,
{ exact λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (hfx.1 _), },
{ exact λ i hi, (multiset.mem_add.1 hi).elim (hfa.1 _) (hfb.1 _), },
calc multiset.prod (p ::ₘ fx)
~ᵤ a * b : by rw [hx, multiset.prod_cons];
exact associated_mul_mul (by refl) hfx.2
... ~ᵤ (fa).prod * (fb).prod :
associated_mul_mul hfa.2.symm hfb.2.symm
... = _ : by rw multiset.prod_add, },
exact let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem h
(multiset.mem_cons_self p _) in
(multiset.mem_add.1 hqf).elim
(λ hqa, or.inl $ (dvd_iff_dvd_of_rel_left hq).2 $
(dvd_iff_dvd_of_rel_right hfa.2).1
(multiset.dvd_prod hqa))
(λ hqb, or.inr $ (dvd_iff_dvd_of_rel_left hq).2 $
(dvd_iff_dvd_of_rel_right hfb.2).1
(multiset.dvd_prod hqb))
end⟩, irreducible_of_prime⟩
theorem unique_factorization_monoid.of_exists_unique_irreducible_factors
[comm_cancel_monoid_with_zero α]
(eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a)
(uif : ∀ (f g : multiset α),
(∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod →
multiset.rel associated f g) :
unique_factorization_monoid α :=
unique_factorization_monoid.of_exists_prime_factors (by
{ convert eif,
simp_rw irreducible_iff_prime_of_exists_unique_irreducible_factors eif uif })
namespace unique_factorization_monoid
variables [comm_cancel_monoid_with_zero α] [decidable_eq α] [nontrivial α] [normalization_monoid α]
variables [unique_factorization_monoid α]
/-- Noncomputably determines the multiset of prime factors. -/
noncomputable def factors (a : α) : multiset α := if h : a = 0 then 0 else
multiset.map normalize $ classical.some (unique_factorization_monoid.exists_prime_factors a h)
theorem factors_prod {a : α} (ane0 : a ≠ 0) : associated (factors a).prod a :=
begin
rw [factors, dif_neg ane0],
refine associated.trans _ (classical.some_spec (exists_prime_factors a ane0)).2,
rw [← associates.mk_eq_mk_iff_associated, ← associates.prod_mk, ← associates.prod_mk,
multiset.map_map],
congr' 2,
ext,
rw [function.comp_apply, associates.mk_normalize],
end
theorem prime_of_factor {a : α} : ∀ (x : α), x ∈ factors a → prime x :=
begin
rw [factors],
split_ifs with ane0, { simp },
intros x hx, rcases multiset.mem_map.1 hx with ⟨y, ⟨hy, rfl⟩⟩,
rw prime_iff_of_associated (normalize_associated),
exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 y hy,
end
theorem irreducible_of_factor {a : α} : ∀ (x : α), x ∈ factors a → irreducible x :=
λ x h, irreducible_of_prime (prime_of_factor x h)
theorem normalize_factor {a : α} : ∀ (x : α), x ∈ factors a → normalize x = x :=
begin
rw factors,
split_ifs with h, { simp },
intros x hx,
obtain ⟨y, hy, rfl⟩ := multiset.mem_map.1 hx,
apply normalize_idem
end
lemma factors_irreducible {a : α} (ha : irreducible a) :
factors a = normalize a ::ₘ 0 :=
begin
obtain ⟨p, a_assoc, hp⟩ := prime_factors_irreducible ha
⟨prime_of_factor, factors_prod ha.ne_zero⟩,
have p_mem : p ∈ factors a,
{ rw hp, apply multiset.mem_cons_self },
convert hp,
rwa [← normalize_factor p p_mem, normalize_eq_normalize_iff, dvd_dvd_iff_associated]
end
lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a →
∃ q ∈ factors a, p ~ᵤ q :=
λ ⟨b, hb⟩,
have hb0 : b ≠ 0, from λ hb0, by simp * at *,
have multiset.rel associated (p ::ₘ factors b) (factors a),
from factors_unique
(λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp)
(irreducible_of_factor _))
irreducible_of_factor
(associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0
... = p * b : hb
... ~ᵤ multiset.prod (p ::ₘ factors b) :
by rw multiset.prod_cons; exact associated_mul_mul
(associated.refl _)
(associated.symm (factors_prod hb0))),
multiset.exists_mem_of_rel_of_mem this (by simp)
@[simp] lemma factors_zero : factors (0 : α) = 0 := dif_pos rfl
@[simp] lemma factors_one : factors (1 : α) = 0 :=
begin
rw ← multiset.rel_zero_right,
apply factors_unique irreducible_of_factor,
{ intros x hx,
exfalso,
apply multiset.not_mem_zero x hx },
{ simp [factors_prod one_ne_zero] },
apply_instance
end
@[simp] lemma factors_mul {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) :
factors (x * y) = factors x + factors y :=
begin
have h : (normalize : α → α) = associates.out ∘ associates.mk,
{ ext, rw [function.comp_apply, associates.out_mk], },
rw [← multiset.map_id' (factors (x * y)), ← multiset.map_id' (factors x),
← multiset.map_id' (factors y), ← multiset.map_congr normalize_factor,
← multiset.map_congr normalize_factor, ← multiset.map_congr normalize_factor,
← multiset.map_add, h, ← multiset.map_map associates.out, eq_comm,
← multiset.map_map associates.out],
refine congr rfl _,
apply multiset.map_mk_eq_map_mk_of_rel,
apply factors_unique,
{ intros x hx,
rcases multiset.mem_add.1 hx with hx | hx;
exact irreducible_of_factor x hx },
{ exact irreducible_of_factor },
{ rw multiset.prod_add,
exact associated.trans (associated_mul_mul (factors_prod hx) (factors_prod hy))
(factors_prod (mul_ne_zero hx hy)).symm, }
end
@[simp] lemma factors_pow {x : α} (n : ℕ) :
factors (x ^ n) = n • factors x :=
begin
induction n with n ih,
{ simp },
by_cases h0 : x = 0,
{ simp [h0, zero_pow n.succ_pos, smul_zero] },
rw [pow_succ, succ_nsmul, factors_mul h0 (pow_ne_zero _ h0), ih],
end
lemma dvd_iff_factors_le_factors {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) :
x ∣ y ↔ factors x ≤ factors y :=
begin
split,
{ rintro ⟨c, rfl⟩,
simp [hx, right_ne_zero_of_mul hy] },
{ rw [← dvd_iff_dvd_of_rel_left (factors_prod hx), ← dvd_iff_dvd_of_rel_right (factors_prod hy)],
apply multiset.prod_dvd_prod }
end
end unique_factorization_monoid
namespace unique_factorization_monoid
open_locale classical
open multiset associates
noncomputable theory
variables [comm_cancel_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α]
/-- Noncomputably defines a `normalization_monoid` structure on a `unique_factorization_monoid`. -/
protected def normalization_monoid : normalization_monoid α :=
normalization_monoid_of_monoid_hom_right_inverse {
to_fun := λ a : associates α, if a = 0 then 0 else ((factors a).map
(classical.some mk_surjective.has_right_inverse : associates α → α)).prod,
map_one' := by simp,
map_mul' := λ x y, by {
by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
simp [hx, hy] } } begin
intro x,
dsimp,
by_cases hx : x = 0, { simp [hx] },
have h : associates.mk_monoid_hom ∘ (classical.some mk_surjective.has_right_inverse) =
(id : associates α → associates α),
{ ext x,
rw [function.comp_apply, mk_monoid_hom_apply,
classical.some_spec mk_surjective.has_right_inverse x],
refl },
rw [if_neg hx, ← mk_monoid_hom_apply, monoid_hom.map_multiset_prod, map_map, h, map_id,
← associated_iff_eq],
apply factors_prod hx
end
instance : inhabited (normalization_monoid α) := ⟨unique_factorization_monoid.normalization_monoid⟩
end unique_factorization_monoid
namespace unique_factorization_monoid
variables {R : Type*} [comm_cancel_monoid_with_zero R] [unique_factorization_monoid R]
lemma no_factors_of_no_prime_factors {a b : R} (ha : a ≠ 0)
(h : (∀ {d}, d ∣ a → d ∣ b → ¬ prime d)) : ∀ {d}, d ∣ a → d ∣ b → is_unit d :=
λ d, induction_on_prime d
(by { simp only [zero_dvd_iff], intros, contradiction })
(λ x hx _ _, hx)
(λ d q hp hq ih dvd_a dvd_b,
absurd hq (h (dvd_of_mul_right_dvd dvd_a) (dvd_of_mul_right_dvd dvd_b)))
/-- Euclid's lemma: if `a ∣ b * c` and `a` and `c` have no common prime factors, `a ∣ b`.
Compare `is_coprime.dvd_of_dvd_mul_left`. -/
lemma dvd_of_dvd_mul_left_of_no_prime_factors {a b c : R} (ha : a ≠ 0) :
(∀ {d}, d ∣ a → d ∣ c → ¬ prime d) → a ∣ b * c → a ∣ b :=
begin
refine induction_on_prime c _ _ _,
{ intro no_factors,
simp only [dvd_zero, mul_zero, forall_prop_of_true],
haveI := classical.prop_decidable,
exact is_unit_iff_forall_dvd.mp
(no_factors_of_no_prime_factors ha @no_factors (dvd_refl a) (dvd_zero a)) _ },
{ rintros _ ⟨x, rfl⟩ _ a_dvd_bx,
apply units.dvd_mul_right.mp a_dvd_bx },
{ intros c p hc hp ih no_factors a_dvd_bpc,
apply ih (λ q dvd_a dvd_c hq, no_factors dvd_a (dvd_mul_of_dvd_right dvd_c _) hq),
rw mul_left_comm at a_dvd_bpc,
refine or.resolve_left (left_dvd_or_dvd_right_of_dvd_prime_mul hp a_dvd_bpc) (λ h, _),
exact no_factors h (dvd_mul_right p c) hp }
end
/-- Euclid's lemma: if `a ∣ b * c` and `a` and `b` have no common prime factors, `a ∣ c`.
Compare `is_coprime.dvd_of_dvd_mul_right`. -/
lemma dvd_of_dvd_mul_right_of_no_prime_factors {a b c : R} (ha : a ≠ 0)
(no_factors : ∀ {d}, d ∣ a → d ∣ b → ¬ prime d) : a ∣ b * c → a ∣ c :=
by simpa [mul_comm b c] using dvd_of_dvd_mul_left_of_no_prime_factors ha @no_factors
/-- If `a ≠ 0, b` are elements of a unique factorization domain, then dividing
out their common factor `c'` gives `a'` and `b'` with no factors in common. -/
lemma exists_reduced_factors : ∀ (a ≠ (0 : R)) b,
∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b :=
begin
haveI := classical.prop_decidable,
intros a,
refine induction_on_prime a _ _ _,
{ intros, contradiction },
{ intros a a_unit a_ne_zero b,
use [a, b, 1],
split,
{ intros p p_dvd_a _,
exact is_unit_of_dvd_unit p_dvd_a a_unit },
{ simp } },
{ intros a p a_ne_zero p_prime ih_a pa_ne_zero b,
by_cases p ∣ b,
{ rcases h with ⟨b, rfl⟩,
obtain ⟨a', b', c', no_factor, ha', hb'⟩ := ih_a a_ne_zero b,
refine ⟨a', b', p * c', @no_factor, _, _⟩,
{ rw [mul_assoc, ha'] },
{ rw [mul_assoc, hb'] } },
{ obtain ⟨a', b', c', coprime, rfl, rfl⟩ := ih_a a_ne_zero b,
refine ⟨p * a', b', c', _, mul_left_comm _ _ _, rfl⟩,
intros q q_dvd_pa' q_dvd_b',
cases left_dvd_or_dvd_right_of_dvd_prime_mul p_prime q_dvd_pa' with p_dvd_q q_dvd_a',
{ have : p ∣ c' * b' := dvd_mul_of_dvd_right (dvd_trans p_dvd_q q_dvd_b') _,
contradiction },
exact coprime q_dvd_a' q_dvd_b' } }
end
lemma exists_reduced_factors' (a b : R) (hb : b ≠ 0) :
∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b :=
let ⟨b', a', c', no_factor, hb, ha⟩ := exists_reduced_factors b hb a
in ⟨a', b', c', λ _ hpb hpa, no_factor hpa hpb, ha, hb⟩
section multiplicity
variables [nontrivial R] [normalization_monoid R] [decidable_eq R]
variables [decidable_rel (has_dvd.dvd : R → R → Prop)]
open multiplicity multiset
lemma le_multiplicity_iff_repeat_le_factors {a b : R} {n : ℕ} (ha : irreducible a) (hb : b ≠ 0) :
↑n ≤ multiplicity a b ↔ repeat (normalize a) n ≤ factors b :=
begin
rw ← pow_dvd_iff_le_multiplicity,
revert b,
induction n with n ih, { simp },
intros b hb,
split,
{ rintro ⟨c, rfl⟩,
rw [ne.def, pow_succ, mul_assoc, mul_eq_zero, decidable.not_or_iff_and_not] at hb,
rw [pow_succ, mul_assoc, factors_mul hb.1 hb.2, repeat_succ, factors_irreducible ha,
cons_add, cons_le_cons_iff, zero_add, ← ih hb.2],
apply dvd.intro _ rfl },
{ rw [multiset.le_iff_exists_add],
rintro ⟨u, hu⟩,
rw [← dvd_iff_dvd_of_rel_right (factors_prod hb), hu, prod_add, prod_repeat],
apply dvd.trans (dvd_of_associated (associated_pow_pow _)) (dvd.intro u.prod rfl),
apply associated_normalize }
end
lemma multiplicity_eq_count_factors {a b : R} (ha : irreducible a) (hb : b ≠ 0) :
multiplicity a b = (factors b).count (normalize a) :=
begin
apply le_antisymm,
{ apply enat.le_of_lt_add_one,
rw [← enat.coe_one, ← enat.coe_add, lt_iff_not_ge, ge_iff_le,
le_multiplicity_iff_repeat_le_factors ha hb, ← le_count_iff_repeat_le],
simp },
rw [le_multiplicity_iff_repeat_le_factors ha hb, ← le_count_iff_repeat_le],
end
end multiplicity
end unique_factorization_monoid
namespace associates
open unique_factorization_monoid associated multiset
variables [comm_cancel_monoid_with_zero α]
/-- `factor_set α` representation elements of unique factorization domain as multisets.
`multiset α` produced by `factors` are only unique up to associated elements, while the multisets in
`factor_set α` are unqiue by equality and restricted to irreducible elements. This gives us a
representation of each element as a unique multisets (or the added ⊤ for 0), which has a complete
lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple.
-/
@[reducible] def {u} factor_set (α : Type u) [comm_cancel_monoid_with_zero α] :
Type u :=
with_top (multiset { a : associates α // irreducible a })
local attribute [instance] associated.setoid
theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} :
(↑(a + b) : factor_set α) = a + b :=
by norm_cast
lemma factor_set.sup_add_inf_eq_add [decidable_eq (associates α)] :
∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b
| none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp
| a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp
| (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from
begin
rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add,
with_top.coe_eq_coe],
exact multiset.union_add_inter _ _
end
/-- Evaluates the product of a `factor_set` to be the product of the corresponding multiset,
or `0` if there is none. -/
def factor_set.prod : factor_set α → associates α
| none := 0
| (some s) := (s.map coe).prod
@[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl
@[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} :
(s : factor_set α).prod = (s.map coe).prod :=
rfl
@[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod
| none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp
| a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp
| (some a) (some b) :=
show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod,
by rw [← factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add]
theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod
| none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_refl _
| a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top
| (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h
/-- `bcount p s` is the multiplicity of `p` in the factor_set `s` (with bundled `p`)-/
def bcount [decidable_eq (associates α)] (p : {a : associates α // irreducible a}) :
factor_set α → ℕ
| none := 0
| (some s) := s.count p
variables [dec_irr : Π (p : associates α), decidable (irreducible p)]
include dec_irr
/-- `count p s` is the multiplicity of the irreducible `p` in the factor_set `s`.
If `p` is not irreducible, `count p s` is defined to be `0`. -/
def count [decidable_eq (associates α)] (p : associates α) :
factor_set α → ℕ :=
if hp : irreducible p then bcount ⟨p, hp⟩ else 0
@[simp] lemma count_some [decidable_eq (associates α)] {p : associates α} (hp : irreducible p)
(s : multiset _) : count p (some s) = s.count ⟨p, hp⟩:=
by { dunfold count, split_ifs, refl }
@[simp] lemma count_zero [decidable_eq (associates α)] {p : associates α} (hp : irreducible p) :
count p (0 : factor_set α) = 0 :=
by { dunfold count, split_ifs, refl }
lemma count_reducible [decidable_eq (associates α)] {p : associates α} (hp : ¬ irreducible p) :
count p = 0 := dif_neg hp
omit dec_irr
/-- membership in a factor_set (bundled version) -/
def bfactor_set_mem : {a : associates α // irreducible a} → (factor_set α) → Prop
| _ ⊤ := true
| p (some l) := p ∈ l
include dec_irr
/-- `factor_set_mem p s` is the predicate that the irreducible `p` is a member of
`s : factor_set α`.
If `p` is not irreducible, `p` is not a member of any `factor_set`. -/
def factor_set_mem (p : associates α) (s : factor_set α) : Prop :=
if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false
instance : has_mem (associates α) (factor_set α) := ⟨factor_set_mem⟩
@[simp] lemma factor_set_mem_eq_mem (p : associates α) (s : factor_set α) :
factor_set_mem p s = (p ∈ s) := rfl
lemma mem_factor_set_top {p : associates α} {hp : irreducible p} :
p ∈ (⊤ : factor_set α) :=
begin
dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, exact trivial
end
lemma mem_factor_set_some {p : associates α} {hp : irreducible p}
{l : multiset {a : associates α // irreducible a }} :
p ∈ (l : factor_set α) ↔ subtype.mk p hp ∈ l :=
begin
dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, refl
end
lemma reducible_not_mem_factor_set {p : associates α} (hp : ¬ irreducible p)
(s : factor_set α) : ¬ p ∈ s :=
λ (h : if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false),
by rwa [dif_neg hp] at h
omit dec_irr
variable [unique_factorization_monoid α]
theorem unique' {p q : multiset (associates α)} :
(∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q :=
begin
apply multiset.induction_on_multiset_quot p,
apply multiset.induction_on_multiset_quot q,
assume s t hs ht eq,
refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_monoid.factors_unique _ _ _),
{ exact assume a ha, ((irreducible_mk _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) },
{ exact assume a ha, ((irreducible_mk _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) },
simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq
end
variables [nontrivial α] [normalization_monoid α]
private theorem forall_map_mk_factors_irreducible [decidable_eq α] (x : α) (hx : x ≠ 0) :
∀(a : associates α), a ∈ multiset.map associates.mk (factors x) → irreducible a :=
begin
assume a ha,
rcases multiset.mem_map.1 ha with ⟨c, hc, rfl⟩,
exact (irreducible_mk c).2 (irreducible_of_factor _ hc)
end
theorem prod_le_prod_iff_le {p q : multiset (associates α)}
(hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) :
p.prod ≤ q.prod ↔ p ≤ q :=
iff.intro
begin
classical,
rintros ⟨⟨c⟩, eqc⟩,
have : c ≠ 0, from (mt mk_eq_zero.2 $
assume (hc : quot.mk setoid.r c = 0),
have (0 : associates α) ∈ q, from prod_eq_zero_iff.1 $ eqc.symm ▸ hc.symm ▸ mul_zero _,
not_irreducible_zero ((irreducible_mk 0).1 $ hq _ this)),
have : associates.mk (factors c).prod = quot.mk setoid.r c,
from mk_eq_mk_iff_associated.2 (factors_prod this),
refine multiset.le_iff_exists_add.2 ⟨(factors c).map associates.mk, unique' hq _ _⟩,
{ assume x hx,
rcases multiset.mem_add.1 hx with h | h,
exact hp x h,
exact forall_map_mk_factors_irreducible c ‹c ≠ 0› _ h },
{ simp [multiset.prod_add, prod_mk, *] at * }
end
prod_le_prod
variables [dec : decidable_eq α] [dec' : decidable_eq (associates α)]
include dec
/-- This returns the multiset of irreducible factors as a `factor_set`,
a multiset of irreducible associates `with_top`. -/
noncomputable def factors' (a : α) :
multiset { a : associates α // irreducible a } :=
(factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk _).2 ha⟩)
(irreducible_of_factor)
@[simp] theorem map_subtype_coe_factors' {a : α} :
(factors' a).map coe = (factors a).map associates.mk :=
by simp [factors', multiset.map_pmap, multiset.pmap_eq_map]
theorem factors'_cong {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : a ~ᵤ b) :
factors' a = factors' b :=
have multiset.rel associated (factors a) (factors b), from
factors_unique irreducible_of_factor irreducible_of_factor
((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm),
by simpa [(multiset.map_eq_map subtype.coe_injective).symm, rel_associated_iff_map_eq_map.symm]
include dec'
/-- This returns the multiset of irreducible factors of an associate as a `factor_set`,
a multiset of irreducible associates `with_top`. -/
noncomputable def factors (a : associates α) :
factor_set α :=
begin
refine (if h : a = 0 then ⊤ else
quotient.hrec_on a (λx h, some $ factors' x) _ h),
assume a b hab,
apply function.hfunext,
{ have : a ~ᵤ 0 ↔ b ~ᵤ 0, from
iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0),
simp only [associated_zero_iff_eq_zero] at this,
simp only [quotient_mk_eq_mk, this, mk_eq_zero] },
exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong
(λ c, ha (mk_eq_zero.2 c)) (λ c, hb (mk_eq_zero.2 c)) hab)
end
@[simp] theorem factors_0 : (0 : associates α).factors = ⊤ :=
dif_pos rfl
@[simp] theorem factors_mk (a : α) (h : a ≠ 0) :
(associates.mk a).factors = factors' a :=
by { classical, apply dif_neg, apply (mt mk_eq_zero.1 h) }
theorem prod_factors : ∀(s : factor_set α), s.prod.factors = s
| none := by simp [factor_set.prod]; refl
| (some s) :=
begin
unfold factor_set.prod,
generalize eq_a : (s.map coe).prod = a,
rcases a with ⟨a⟩,
rw quot_mk_eq_mk at *,
have : (s.map (coe : _ → associates α)).prod ≠ 0, from assume ha,
let ⟨⟨a, ha⟩, h, eq⟩ := multiset.mem_map.1 (prod_eq_zero_iff.1 ha) in
have irreducible (0 : associates α), from eq ▸ ha,
not_irreducible_zero ((irreducible_mk _).1 this),
have ha : a ≠ 0, by simp [*] at *,
suffices : (unique_factorization_monoid.factors a).map associates.mk = s.map coe,
{ rw [factors_mk a ha],
apply congr_arg some _,
simpa [(multiset.map_eq_map subtype.coe_injective).symm] },
refine unique'
(forall_map_mk_factors_irreducible _ ha)
(assume a ha, let ⟨⟨x, hx⟩, ha, eq⟩ := multiset.mem_map.1 ha in eq ▸ hx)
_,
rw [prod_mk, eq_a, mk_eq_mk_iff_associated],
exact factors_prod ha
end
@[simp]
theorem factors_prod (a : associates α) : a.factors.prod = a :=
quotient.induction_on a $ assume a, decidable.by_cases
(assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this])
(assume : associates.mk a ≠ 0,
have a ≠ 0, by simp * at *,
by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)])
theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b :=
have a.factors.prod = b.factors.prod, by rw h,
by rwa [factors_prod, factors_prod] at this
omit dec dec'
theorem eq_of_prod_eq_prod {a b : factor_set α} (h : a.prod = b.prod) : a = b :=
begin
classical,
have : a.prod.factors = b.prod.factors, by rw h,
rwa [prod_factors, prod_factors] at this
end
include dec dec'
@[simp] theorem factors_mul (a b : associates α) : (a * b).factors = a.factors + b.factors :=
eq_of_prod_eq_prod $ eq_of_factors_eq_factors $
by rw [prod_add, factors_prod, factors_prod, factors_prod]
theorem factors_mono : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors
| s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right bot_le
theorem factors_le {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b :=
iff.intro
(assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h,
by rwa [factors_prod, factors_prod] at this)
factors_mono
omit dec dec'
theorem prod_le {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b :=
begin
classical,
exact iff.intro
(assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h,
by rwa [prod_factors, prod_factors] at this)
prod_mono
end
include dec dec'
noncomputable instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩
noncomputable instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩
noncomputable instance : bounded_lattice (associates α) :=
{ sup := (⊔),
inf := (⊓),
sup_le :=
assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)),
le_sup_left := assume a b,
le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left,
le_sup_right := assume a b,
le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right,
le_inf :=
assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)),
inf_le_left := assume a b,
le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)),
inf_le_right := assume a b,
le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)),
.. associates.partial_order,
.. associates.order_top,
.. associates.order_bot }
lemma sup_mul_inf (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b :=
show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b,
begin
refine eq_of_factors_eq_factors _,
rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add]
end
include dec_irr
lemma dvd_of_mem_factors {a p : associates α} {hp : irreducible p}
(hm : p ∈ factors a) : p ∣ a :=
begin
by_cases ha0 : a = 0, { rw ha0, exact dvd_zero p },
obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha0,
rw [← associates.factors_prod a],
rw [← ha', factors_mk a0 nza] at hm ⊢,
erw prod_coe,
apply multiset.dvd_prod, apply multiset.mem_map.mpr,
exact ⟨⟨p, hp⟩, mem_factor_set_some.mp hm, rfl⟩
end
omit dec'
lemma dvd_of_mem_factors' {a : α} {p : associates α} {hp : irreducible p} {hz : a ≠ 0}
(h_mem : subtype.mk p hp ∈ factors' a) : p ∣ associates.mk a :=
by { haveI := classical.dec_eq (associates α),
apply @dvd_of_mem_factors _ _ _ _ _ _ _ _ _ _ hp,
rw factors_mk _ hz,
apply mem_factor_set_some.2 h_mem }
omit dec_irr
lemma mem_factors'_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) :
subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a :=
begin
obtain ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd ha0 hp hd,
apply multiset.mem_pmap.mpr, use q, use hq,
exact subtype.eq (eq.symm (mk_eq_mk_iff_associated.mpr hpq))
end
include dec_irr
lemma mem_factors'_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) :
subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a ↔ p ∣ a :=
begin
split,
{ rw ← mk_dvd_mk, apply dvd_of_mem_factors', apply ha0 },
{ apply mem_factors'_of_dvd ha0 }
end
include dec'
lemma mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) :
(associates.mk p) ∈ factors (associates.mk a) :=
begin
rw factors_mk _ ha0, exact mem_factor_set_some.mpr (mem_factors'_of_dvd ha0 hp hd)
end
lemma mem_factors_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) :
(associates.mk p) ∈ factors (associates.mk a) ↔ p ∣ a :=
begin
split,
{ rw ← mk_dvd_mk, apply dvd_of_mem_factors, exact (irreducible_mk p).mpr hp },
{ apply mem_factors_of_dvd ha0 hp }
end
lemma exists_prime_dvd_of_not_inf_one {a b : α}
(ha : a ≠ 0) (hb : b ≠ 0) (h : (associates.mk a) ⊓ (associates.mk b) ≠ 1) :
∃ (p : α), prime p ∧ p ∣ a ∧ p ∣ b :=
begin
have hz : (factors (associates.mk a)) ⊓ (factors (associates.mk b)) ≠ 0,
{ contrapose! h with hf,
change ((factors (associates.mk a)) ⊓ (factors (associates.mk b))).prod = 1,
rw hf,
exact multiset.prod_zero },
rw [factors_mk a ha, factors_mk b hb, ← with_top.coe_inf] at hz,
obtain ⟨⟨p0, p0_irr⟩, p0_mem⟩ := multiset.exists_mem_of_ne_zero ((mt with_top.coe_eq_coe.mpr) hz),
rw multiset.inf_eq_inter at p0_mem,
obtain ⟨p, rfl⟩ : ∃ p, associates.mk p = p0 := quot.exists_rep p0,
refine ⟨p, _, _, _⟩,
{ rw [← irreducible_iff_prime, ← irreducible_mk],
exact p0_irr },
{ apply dvd_of_mk_le_mk,
apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).left,
apply ha, },
{ apply dvd_of_mk_le_mk,
apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).right,
apply hb }
end
theorem coprime_iff_inf_one {a b : α} (ha0 : a ≠ 0) (hb0 : b ≠ 0) :
(associates.mk a) ⊓ (associates.mk b) = 1 ↔ ∀ {d : α}, d ∣ a → d ∣ b → ¬ prime d :=
begin
split,
{ intros hg p ha hb hp,
refine ((associates.prime_mk _).mpr hp).not_unit (is_unit_of_dvd_one _ _),
rw ← hg,
exact le_inf (mk_le_mk_of_dvd ha) (mk_le_mk_of_dvd hb) },
{ contrapose,
intros hg hc,
obtain ⟨p, hp, hpa, hpb⟩ := exists_prime_dvd_of_not_inf_one ha0 hb0 hg,
exact hc hpa hpb hp }
end
omit dec_irr
theorem factors_prime_pow {p : associates α} (hp : irreducible p)
(k : ℕ) : factors (p ^ k) = some (multiset.repeat ⟨p, hp⟩ k) :=
eq_of_prod_eq_prod (by rw [associates.factors_prod, factor_set.prod, multiset.map_repeat,
multiset.prod_repeat, subtype.coe_mk])
include dec_irr
theorem prime_pow_dvd_iff_le {m p : associates α} (h₁ : m ≠ 0)
(h₂ : irreducible p) {k : ℕ} : p ^ k ≤ m ↔ k ≤ count p m.factors :=
begin
obtain ⟨a, nz, rfl⟩ := associates.exists_non_zero_rep h₁,
rw [factors_mk _ nz, ← with_top.some_eq_coe, count_some, multiset.le_count_iff_repeat_le,
← factors_le, factors_prime_pow h₂, factors_mk _ nz],
exact with_top.coe_le_coe
end
theorem le_of_count_ne_zero {m p : associates α} (h0 : m ≠ 0)
(hp : irreducible p) : count p m.factors ≠ 0 → p ≤ m :=
begin
rw [← pos_iff_ne_zero],
intro h,
rw [← pow_one p],
apply (prime_pow_dvd_iff_le h0 hp).2,
simpa only
end
theorem count_mul {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0)
{p : associates α} (hp : irreducible p) :
count p (factors (a * b)) = count p a.factors + count p b.factors :=
begin
obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha,
obtain ⟨b0, nzb, hb'⟩ := exists_non_zero_rep hb,
rw [factors_mul, ← ha', ← hb', factors_mk a0 nza, factors_mk b0 nzb, ← factor_set.coe_add,
← with_top.some_eq_coe, ← with_top.some_eq_coe, ← with_top.some_eq_coe, count_some hp,
multiset.count_add, count_some hp, count_some hp]
end
theorem count_of_coprime {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0)
(hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {p : associates α} (hp : irreducible p) :
count p a.factors = 0 ∨ count p b.factors = 0 :=
begin
rw [or_iff_not_imp_left, ← ne.def],
intro hca,
contrapose! hab with hcb,
exact ⟨p, le_of_count_ne_zero ha hp hca, le_of_count_ne_zero hb hp hcb,
(irreducible_iff_prime.mp hp)⟩,
end
theorem count_mul_of_coprime {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0)
{p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) :
count p a.factors = 0 ∨ count p a.factors = count p (a * b).factors :=
begin
cases count_of_coprime ha hb hab hp with hz hb0, { tauto },
apply or.intro_right,
rw [count_mul ha hb hp, hb0, add_zero]
end
theorem count_mul_of_coprime' {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0)
{p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) :
count p (a * b).factors = count p a.factors
∨ count p (a * b).factors = count p b.factors :=
begin
rw [count_mul ha hb hp],
cases count_of_coprime ha hb hab hp with ha0 hb0,
{ apply or.intro_right, rw [ha0, zero_add] },
{ apply or.intro_left, rw [hb0, add_zero] }
end
theorem dvd_count_of_dvd_count_mul {a b : associates α} (ha : a ≠ 0) (hb : b ≠ 0)
{p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d)
{k : ℕ} (habk : k ∣ count p (a * b).factors) : k ∣ count p a.factors :=
begin
cases count_of_coprime ha hb hab hp with hz h,
{ rw hz, exact dvd_zero k },
{ rw [count_mul ha hb hp, h] at habk, exact habk }
end
omit dec_irr
@[simp] lemma factors_one : factors (1 : associates α) = 0 :=
begin
apply eq_of_prod_eq_prod,
rw associates.factors_prod,
exact multiset.prod_zero,
end
@[simp] theorem pow_factors {a : associates α} {k : ℕ} : (a ^ k).factors = k • a.factors :=
begin
induction k with n h,
{ rw [zero_nsmul, pow_zero], exact factors_one },
{ rw [pow_succ, succ_nsmul, factors_mul, h] }
end
include dec_irr
lemma count_pow {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p)
(k : ℕ) : count p (a ^ k).factors = k * count p a.factors :=
begin
induction k with n h,
{ rw [pow_zero, factors_one, zero_mul, count_zero hp] },
{ rw [pow_succ, count_mul ha (pow_ne_zero _ ha) hp, h, nat.succ_eq_add_one], ring }
end
theorem dvd_count_pow {a : associates α} (ha : a ≠ 0) {p : associates α} (hp : irreducible p)
(k : ℕ) : k ∣ count p (a ^ k).factors := by { rw count_pow ha hp, apply dvd_mul_right }
theorem is_pow_of_dvd_count {a : associates α} (ha : a ≠ 0) {k : ℕ}
(hk : ∀ (p : associates α) (hp : irreducible p), k ∣ count p a.factors) :
∃ (b : associates α), a = b ^ k :=
begin
obtain ⟨a0, hz, rfl⟩ := exists_non_zero_rep ha,
rw [factors_mk a0 hz] at hk,
have hk' : ∀ (p : {a : associates α // irreducible a}), k ∣ (factors' a0).count p,
{ intro p,
have pp : p = ⟨p.val, p.2⟩, { simp only [subtype.coe_eta, subtype.val_eq_coe] },
rw [pp, ← count_some p.2], exact hk p.val p.2 },
obtain ⟨u, hu⟩ := multiset.exists_smul_of_dvd_count _ hk',
use (u : factor_set α).prod,
apply eq_of_factors_eq_factors,
rw [pow_factors, prod_factors, factors_mk a0 hz, ← with_top.some_eq_coe, hu],
exact with_bot.coe_nsmul u k
end
omit dec
omit dec_irr
omit dec'
theorem eq_pow_of_mul_eq_pow {a b c : associates α} (ha : a ≠ 0) (hb : b ≠ 0)
(hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {k : ℕ} (h : a * b = c ^ k) :
∃ (d : associates α), a = d ^ k :=
begin
classical,
by_cases hk0 : k = 0,
{ use 1,
rw [hk0, pow_zero] at h ⊢,
apply (mul_eq_one_iff.1 h).1 },
{ refine is_pow_of_dvd_count ha _,
intros p hp,
apply dvd_count_of_dvd_count_mul ha hb hp hab,
rw h,
apply dvd_count_pow _ hp,
rintros rfl,
rw zero_pow' _ hk0 at h,
cases mul_eq_zero.mp h; contradiction }
end
end associates
section
open associates unique_factorization_monoid
/-- `to_gcd_monoid` constructs a GCD monoid out of a normalization on a
unique factorization domain. -/
noncomputable def unique_factorization_monoid.to_gcd_monoid
(α : Type*) [comm_cancel_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α]
[normalization_monoid α] [decidable_eq (associates α)] [decidable_eq α] : gcd_monoid α :=
{ gcd := λa b, (associates.mk a ⊓ associates.mk b).out,
lcm := λa b, (associates.mk a ⊔ associates.mk b).out,
gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left,
gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right,
dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out,
by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩,
lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp,
lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp,
gcd_mul_lcm := assume a b,
show (associates.mk a ⊓ associates.mk b).out * (associates.mk a ⊔ associates.mk b).out =
normalize (a * b),
by rw [← out_mk, ← out_mul, mul_comm, sup_mul_inf]; refl,
normalize_gcd := assume a b, by convert normalize_out _,
.. ‹normalization_monoid α› }
end
|
5d11d6ca900ebaa4581274c81e830fc3c42902c4 | b24beef0a8b1a8e92be756a25aa78e24908b2b14 | /src/solutions/friday/manifolds.lean | 311261b76227e4f27838457ebafbfd5f91e40fee | [] | permissive | ChristopheMargerin/lftcm2020 | 14967e74cbe92a7b61d32d8130f32cfa09b5172b | 589180047fa4fdfb3179636db58b0b0320549871 | refs/heads/master | 1,668,536,269,632 | 1,594,891,664,000 | 1,594,891,664,000 | 280,112,730 | 0 | 0 | MIT | 1,594,891,963,000 | 1,594,891,962,000 | null | UTF-8 | Lean | false | false | 25,510 | lean | import for_mathlib.manifolds
noncomputable theory
open_locale manifold classical big_operators
open set
/-! ### Local homeomorphisms
Local homeomorphisms are globally defined maps with a globally defined "inverse", but the only
relevant set is the *source*, which should be mapped homeomorphically to the *target*.
-/
/- Define a local homeomorphism from `ℝ` to `ℝ` which is just `x ↦ -x`, but on `(-1, 1)`. In
Lean, the interval `(-1, 1)` is denoted by `Ioo (-1 : ℝ) 1` (where `o` stands for _open_). -/
@[simp] lemma neg_mem_Ioo_minus_one_one (x : ℝ) : -x ∈ Ioo (-1 : ℝ) 1 ↔ x ∈ Ioo (-1 : ℝ) 1 :=
begin
-- sorry
simp [neg_lt, and_comm],
-- sorry
end
def my_first_local_homeo : local_homeomorph ℝ ℝ :=
{ to_fun := λ x, -x,
inv_fun := λ x, -x,
source := Ioo (-1) 1,
target := /- inline sorry -/Ioo (-1) 1/- inline sorry -/,
map_source' :=
begin
-- sorry
assume x hx,
simp [hx],
-- sorry
end,
map_target' :=
begin
-- sorry
assume x hx,
simp [hx],
-- sorry
end,
left_inv' :=
begin
-- sorry
simp,
-- sorry
end,
right_inv' :=
begin
-- sorry
simp,
-- sorry
end,
open_source := /- inline sorry -/is_open_Ioo/- inline sorry -/,
open_target := /- inline sorry -/is_open_Ioo/- inline sorry -/,
continuous_to_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/,
continuous_inv_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/ }
/- Two simple lemmas that will prove useful below. You can leave them sorried if you like. -/
lemma ne_3_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-1 : ℝ) 1) : x ≠ 3 :=
begin
-- sorry
exact ne_of_lt (lt_trans h.2 (by norm_num))
-- sorry
end
lemma neg_ne_3_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-1 : ℝ) 1) : -x ≠ 3 :=
begin
-- sorry
assume h',
simp at h,
linarith,
-- sorry
end
/- Now, define a second local homeomorphism which is almost like the previous one. You may find the
following lemma useful for `continuous_to_fun`: -/
#check continuous_on.congr
def my_second_local_homeo : local_homeomorph ℝ ℝ :=
{ to_fun := λ x, if x = 3 then 0 else - x,
inv_fun := λ x, -x,
source := Ioo (-1) 1,
target := /- inline sorry -/Ioo (-1) 1/- inline sorry -/,
map_source' := /- inline sorry -/λ x hx, by simp [hx, ne_3_of_mem_Ioo hx]/- inline sorry -/,
map_target' := /- inline sorry -/λ x hx, by simp [hx]/- inline sorry -/,
left_inv' := /- inline sorry -/λ x hx, by simp [hx, ne_3_of_mem_Ioo hx]/- inline sorry -/,
right_inv' := /- inline sorry -/λ x hx, by simp [hx, neg_ne_3_of_mem_Ioo hx]/- inline sorry -/,
open_source := /- inline sorry -/is_open_Ioo/- inline sorry -/,
open_target := /- inline sorry -/is_open_Ioo/- inline sorry -/,
continuous_to_fun :=
begin
-- sorry
refine continuous_neg.continuous_on.congr (λ x hx, _),
simp [hx, ne_3_of_mem_Ioo hx],
-- sorry
end,
continuous_inv_fun := /- inline sorry -/continuous_neg.continuous_on/- inline sorry -/ }
/- Although the two above local homeos are the same for all practical purposes as they coincide
where relevant, they are not *equal*: -/
lemma my_first_local_homeo_ne_my_second_local_homeo :
my_first_local_homeo ≠ my_second_local_homeo :=
begin
-- sorry
assume h,
have : my_first_local_homeo 3 = my_second_local_homeo 3, by rw h,
simp [my_first_local_homeo, my_second_local_homeo] at this,
linarith,
-- sorry
end
/- The right equivalence relation for local homeos is not equality, but `eq_on_source`.
Indeed, the two local homeos we have defined above coincide from this point of view. -/
#check @local_homeomorph.eq_on_source
lemma eq_on_source_my_first_local_homeo_my_second_local_homeo :
local_homeomorph.eq_on_source my_first_local_homeo my_second_local_homeo :=
begin
-- sorry
refine ⟨rfl, λ x hx, _⟩,
simp [my_first_local_homeo, my_second_local_homeo, ne_3_of_mem_Ioo hx],
-- sorry
end
/-! ### An example of a charted space structure on `ℝ`
A charted space is a topological space together with a set of local homeomorphisms to a model space,
whose sources cover the whole space. For instance, `ℝ` is already endowed with a charted space
structure with model space `ℝ`, where the unique chart is the identity:
-/
#check charted_space_self ℝ
/- For educational purposes only, we will put another charted space structure on `ℝ` using the
local homeomorphisms we have constructed above. To avoid using too much structure of `ℝ` (and to
avoid confusing Lean), we will work with a copy of `ℝ`, on which we will only register the
topology. -/
@[derive topological_space]
def myℝ : Type := ℝ
instance : charted_space ℝ myℝ :=
{ atlas := { local_homeomorph.refl ℝ, my_first_local_homeo },
chart_at := λ x, if x ∈ Ioo (-1 : ℝ) 1 then my_first_local_homeo else local_homeomorph.refl ℝ,
mem_chart_source :=
begin
-- sorry
assume x,
split_ifs,
{ exact h },
{ exact mem_univ _ }
-- sorry
end,
chart_mem_atlas :=
begin
-- sorry
assume x,
split_ifs;
simp,
-- sorry
end }
/- Now come more interesting bits. We have endowed `myℝ` with a charted space structure, with charts
taking values in `ℝ`. We want to say that this is a smooth structure, i.e., the changes of
coordinates are smooth. In Lean, this is written with `has_structure_groupoid`. A groupoid is a set
of local homeomorphisms of the model space (for example, local homeos that are smooth on their
domain). A charted space admits the groupoid as a structure groupoid if all the changes of
coordinates belong to the groupoid.
There is a difficulty that the definitions are set up to be able to also speak of smooth manifolds
with boundary or with corners, so the name of the smooth groupoid on `ℝ` has the slightly strange
name `times_cont_diff_groupoid ∞ (model_with_corners_self ℝ ℝ)`. To avoid typing again and again
`model_with_corners_self ℝ ℝ`, let us introduce a shortcut
-/
abbreviation I := model_with_corners_self ℝ ℝ
/- In the library, there are such shortcuts for manifolds modelled on `ℝ^n`, denoted with `𝓡 n`,
but for `n = 1` this does not coincide with the above one, as `ℝ^1` (a.k.a. `fin 1 → ℝ`) is not
the same as `ℝ`! -/
instance : has_groupoid myℝ (times_cont_diff_groupoid ∞ I) :=
begin
-- in theory, we should prove that all compositions of charts are diffeos, i.e., they are smooth
-- and their inverse are smooth. For symmetry reasons, it suffices to check one direction
apply has_groupoid_of_pregroupoid,
-- take two charts `e` and `e'`
assume e e' he he',
-- if next line is a little bit slow for your taste, you can replace `simp` with `squeeze_simp`
-- and then follow the advice
simp [atlas] at he he',
dsimp,
-- to continue, some hints:
-- (1) don't hesitate to use the fact that the restriction of a smooth function to a
-- subset is still smooth there (`times_cont_diff.times_cont_diff_on`)
-- (2) hopefully, there is a theorem saying that the negation function is smooth.
-- you can either try to guess its name, or hope that `suggest` will help you there.
-- sorry
rcases he with rfl|rfl; rcases he' with rfl|rfl,
{ exact times_cont_diff_id.times_cont_diff_on },
{ exact times_cont_diff_id.neg.times_cont_diff_on },
{ exact times_cont_diff_id.neg.times_cont_diff_on },
{ convert times_cont_diff_id.times_cont_diff_on,
ext x,
simp [my_first_local_homeo], },
-- sorry
end
/- The statement of the previous instance is not very readable. There is a shortcut notation: -/
instance : smooth_manifold_with_corners I myℝ := {}
/- We will now study a very simple map from `myℝ` to `ℝ`, the identity. -/
def my_map : myℝ → ℝ := λ x, x
/- The map `my_map` is a map going from the type `myℝ` to the type `ℝ`. From the point of view of
the kernel of Lean, it is just the identity, but from the point of view of structures on `myℝ`
and `ℝ` it might not be trivial, as we have registered different instances on these two types. -/
/- The continuity should be trivial, as the topologies on `myℝ` and `ℝ` are definitionally the
same. So `continuous_id` might help. -/
lemma continuous_my_map : continuous my_map :=
-- sorry
continuous_id
-- sorry
/- Smoothness should not be obvious, though, as the manifold structures are not the same: the atlas
on `myℝ` has two elements, while the atlas on `ℝ` has one single element.
Note that `myℝ` is not a vector space, nor a normed space, so one can not ask whether `my_map`
is smooth in the usual sense (as a map between vector spaces): -/
-- lemma times_cont_diff_my_map : times_cont_diff ℝ ∞ my_map := sorry
/- does not make sense (try uncommenting it!) However, we can ask whether `my_map` is a smooth
map between manifolds, i.e., whether it is smooth when read in the charts. When we mention the
smoothness of a map, we should always specify explicitly the model with corners we are using,
because there might be several around (think of a complex manifold that you may want to consider
as a real manifold, to talk about functions which are real-smooth but not holomorphic) -/
lemma times_cont_mdiff_my_map : times_cont_mdiff I I ∞ my_map :=
begin
-- put things in a nicer form. The simpset `mfld_simps` registers many simplification rules for
-- manifolds. `simp` is used heavily in manifold files to bring everything into manageable form.
rw times_cont_mdiff_iff,
simp only [continuous_my_map] with mfld_simps,
-- simp has erased the chart in the target, as it knows that the only chart in the manifold `ℝ`
-- is the identity.
assume x y,
-- sorry
simp [my_map, (∘), chart_at],
split_ifs,
{ exact times_cont_diff_id.neg.times_cont_diff_on },
{ exact times_cont_diff_id.times_cont_diff_on },
-- sorry
end
/- Now, let's go to tangent bundles. We have a smooth manifold, so its tangent bundle should also
be a smooth manifold. -/
-- the type `tangent_bundle I myℝ` makes sense
#check tangent_bundle I myℝ
/- The tangent space above a point of `myℝ` is just a one-dimensional vector space (identified with `ℝ`).
So, one can prescribe an element of the tangent bundle as a pair (more on this below) -/
example : tangent_bundle I myℝ := ((4 : ℝ), 0)
/- Construct the smooth manifold structure on the tangent bundle. Hint: the answer is a one-liner,
and this instance is not really needed. -/
instance tangent_bundle_myℝ : smooth_manifold_with_corners (I.prod I) (tangent_bundle I myℝ) :=
-- sorry
by apply_instance
-- sorry
/-
NB: the model space for the tangent bundle to a product manifold or a tangent space is not
`ℝ × ℝ`, but a copy called `model_prod ℝ ℝ`. Otherwise, `ℝ × ℝ` would have two charted space
structures with model `ℝ × ℝ`, the identity one and the product one, which are not definitionally
equal. And this would be bad.
-/
#check tangent_bundle.charted_space I myℝ
/- A smooth map between manifolds induces a map between their tangent bundles. In `mathlib` this is
called the `tangent_map` (you might instead know it as the "differential" or "pushforward" of the
map). Let us check that the `tangent_map` of `my_map` is smooth. -/
lemma times_cont_mdiff_tangent_map_my_map :
times_cont_mdiff (I.prod I) (I.prod I) ∞ (tangent_map I I my_map) :=
begin
-- hopefully, there is a theorem providing the general result, i.e. the tangent map to a smooth
-- map is smooth.
-- you can either try to guess its name, or hope that `suggest` will help you there.
-- sorry
exact times_cont_mdiff_my_map.times_cont_mdiff_tangent_map le_top,
-- sorry
end
/- (Harder question) Can you show that this tangent bundle is homeomorphic to `ℝ × ℝ`? You could
try to build the homeomorphism by hand, using `tangent_map I I my_map` in one direction and a
similar map in the other direction, but it is probably more efficient to use one of the charts of
the tangent bundle.
Remember, the model space for `tangent_bundle I myℝ` is `model_prod ℝ ℝ`, not `ℝ × ℝ`. But the
topologies on `model_prod ℝ ℝ` and `ℝ × ℝ` are the same, so it is by definition good enough to
construct a homeomorphism with `model_prod ℝ ℝ`.
-/
def my_homeo : tangent_bundle I myℝ ≃ₜ (ℝ × ℝ) :=
begin
-- sorry
let p : tangent_bundle I myℝ := ((4 : ℝ), 0),
let F := chart_at (model_prod ℝ ℝ) p,
have A : ¬ ((4 : ℝ) < 1), by norm_num,
have S : F.source = univ, by simp [F, chart_at, A, @local_homeomorph.refl_source ℝ _],
have T : F.target = univ, by simp [F, chart_at, A, @local_homeomorph.refl_target ℝ _],
exact F.to_homeomorph_of_source_eq_univ_target_eq_univ S T,
-- sorry
end
/- Up to now, we have never used the definition of the tangent bundle, and this corresponds to
the usual mathematical practice: one doesn't care if the tangent space is defined using germs of
curves, or spaces of derivations, or whatever equivalent definition. Instead, one relies all the
time on functoriality (i.e., a smooth map has a well defined derivative, and they compose well,
together with the fact that the tangent bundle to a vector space is the product).
If you want to know more about the internals of the tangent bundle in mathlib, you can browse
through the next section, but it is maybe wiser to skip it on first reading, as it is not needed
to use the library
-/
section you_should_probably_skip_this
/- If `M` is a manifold modelled on a vector space `E`, then the underlying type for the tangent
bundle is just `M × E` -/
lemma tangent_bundle_myℝ_is_prod : tangent_bundle I myℝ = (myℝ × ℝ) :=
/- inline sorry -/rfl/- inline sorry -/
/- This means that you can specify a point in the tangent bundle as a pair `(x, y)`.
However, in general, a tangent bundle is not trivial: the topology on `tangent_bundle I myℝ` is *not*
the product topology. Instead, the tangent space at a point `x` is identified with `ℝ` through some
preferred chart at `x`, called `chart_at ℝ x`, but the way they are glued together depends on the
manifold and the charts.
Even though the tangent bundle to `myℝ` is trivial abstractly, with this construction the
tangent bundle is *not* the product space with the product topology, as we have used various charts
so the gluing is not trivial. The following exercise unfolds the definition to see what is going on.
It is not a reasonable exercise, in the sense that one should never ever do this when working
with a manifold! -/
lemma crazy_formula_after_identifications (x : ℝ) (v : ℝ) :
let p : tangent_bundle I myℝ := ((3 : ℝ), 0) in
chart_at (model_prod ℝ ℝ) p (x, v) = if x ∈ Ioo (-1 : ℝ) 1 then (x, -v) else (x, v) :=
begin
-- this exercise is not easy (and shouldn't be: you are not supposed to use the library like this!)
-- if you really want to do this, you should unfold as much as you can using simp and dsimp, until you
-- are left with a statement speaking of derivatives of real functions, without any manifold code left.
-- sorry
have : ¬ ((3 : ℝ) < 1), by norm_num,
simp only [chart_at, this, mem_Ioo, if_false, and_false],
dsimp [tangent_bundle_core, basic_smooth_bundle_core.chart,
topological_fiber_bundle_core.local_triv, topological_fiber_bundle_core.local_triv',
topological_fiber_bundle_core.index_at,
basic_smooth_bundle_core.to_topological_fiber_bundle_core],
split_ifs,
{ simp only [chart_at, h, my_first_local_homeo, if_true, fderiv_within_univ, prod.mk.inj_iff, mem_Ioo,
fderiv_neg differentiable_at_id', fderiv_id', id.def, continuous_linear_map.coe_id',
continuous_linear_map.neg_apply] with mfld_simps },
{ simp only [chart_at, h, fderiv_within_univ, mem_Ioo, if_false, @local_homeomorph.refl_symm ℝ,
fderiv_id, continuous_linear_map.coe_id'] with mfld_simps }
-- sorry
end
end you_should_probably_skip_this
/-!
### The language of manifolds
In this paragraph, we will try to write down interesting statements of theorems, without proving them. The
goal here is that Lean should not complain on the statement, but the proof should be sorried.
-/
/- Here is a first example, to show you how diffeomorphisms are currently named
(we will probably introduce an abbreviation, but this hasn't been done yet): -/
/-- Two zero-dimensional connected manifolds are diffeomorphic. -/
theorem diffeomorph_of_zero_dim_connected
(M M' : Type*) [topological_space M] [topological_space M']
[charted_space (euclidean_space (fin 0)) M] [charted_space (euclidean_space (fin 0)) M']
[connected_space M] [connected_space M'] :
nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 0)) M M') :=
sorry
/- Do you think that this statement is correct? (note that we have not assumed that our manifolds
are smooth, nor that they are separated, but this is maybe automatic in zero dimension).
Now, write down a version of this theorem in dimension 1, replacing the first sorry with meaningful content
(and adding what is needed before the colon): -/
/-- Two one-dimensional smooth compact connected manifolds are diffeomorphic. -/
theorem diffeomorph_of_one_dim_compact_connected
-- omit
(M M' : Type*) [topological_space M] [topological_space M']
[charted_space (euclidean_space (fin 1)) M] [charted_space (euclidean_space (fin 1)) M']
[connected_space M] [connected_space M'] [compact_space M] [compact_space M']
[t2_space M] [t2_space M']
-- omit
:
-- sorry
nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 1)) M M')
-- sorry
:= sorry
/- You will definitely need to require smoothness and separation in this case, as it is wrong otherwise.
Note that Lean won't complain if you don't put these assumptions, as the theorem would still make
sense, but it would just turn out to be wrong.
The previous statement is not really satisfactory: we would instead like to express that any such
manifold is diffeomorphic to the circle. The trouble is that we don't have the circle as a smooth
manifold yet. Let's cheat and introduce it nevertheless.
-/
@[derive topological_space]
definition sphere (n : ℕ) : Type := metric.sphere (0 : euclidean_space (fin (n+1))) 1
instance (n : ℕ) : has_coe (sphere n) (euclidean_space (fin (n+1))) := ⟨subtype.val⟩
/- Don't try to fill the following instances, the first two should follow from general theory, and
the third one is too much work for an exercise session. -/
instance (n : ℕ) : charted_space (euclidean_space (fin n)) (sphere n) := sorry
instance (n : ℕ) : smooth_manifold_with_corners (𝓡 n) (sphere n) := sorry
instance connected_sphere (n : ℕ) : connected_space (sphere (n+1)) := sorry
/- The next two instances are easier to prove, you can prove them or leave them sorried
as you like. For the second one, you may need to use facts of the library such as -/
#check compact_iff_compact_space
#check metric.compact_iff_closed_bounded
instance (n : ℕ) : t2_space (sphere n) :=
begin
-- sorry
dunfold sphere,
apply_instance
-- sorry
end
instance (n : ℕ) : compact_space (sphere n) :=
begin
-- sorry
dunfold sphere,
apply compact_iff_compact_space.1,
rw metric.compact_iff_closed_bounded,
split,
{ exact metric.is_closed_sphere },
{ rw metric.bounded_iff_subset_ball (0 : euclidean_space (fin (n+1))),
exact ⟨1, metric.sphere_subset_closed_ball⟩ }
-- sorry
end
/- Now, you can prove that any one-dimensional compact connected manifold is diffeomorphic to
the circle -/
theorem diffeomorph_circle_of_one_dim_compact_connected
(M : Type*) [topological_space M] [charted_space (euclidean_space (fin 1)) M]
[connected_space M] [compact_space M] [t2_space M] :
nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 1)) M (sphere 1)) :=
-- sorry
diffeomorph_of_one_dim_compact_connected M (sphere 1)
-- sorry
/- Can you express the sphere eversion theorem, i.e., the fact that there is a smooth isotopy
of immersions between the canonical embedding of the sphere `S^2` and `ℝ^3`, and the antipodal
embedding?
Note that we haven't defined immersions in mathlib, but you can jut require that the fiber
derivative is injective everywhere, which is easy to express if you know that the derivative
of a function `f` from a manifold of dimension `2` to a manifold of dimension `3` at a point `x` is
`mfderiv (𝓡 2) (𝓡 3) f x`.
Don't forget to require the global smoothness of the map! You may need to know that the interval
`[0,1]`, called `Icc (0 : ℝ) 1` in Lean, already has a manifold (with boundary!) structure,
where the corresponding model with corners is called `𝓡∂ 1`.
-/
/-- The sphere eversion theorem. You should fill the first sorry, the second one is out of reach
(now). -/
theorem sphere_eversion :
-- sorry
∃ f : (Icc (0 : ℝ) 1) × (sphere 2) → (euclidean_space (fin 3)),
times_cont_mdiff ((𝓡∂ 1).prod (𝓡 2)) (𝓡 3) ∞ f
∧ ∀ (t : (Icc (0 : ℝ) 1)), ∀ (p : sphere 2),
function.injective (mfderiv (𝓡 2) (𝓡 3) (f ∘ λ y, (t, y)) p)
∧ ∀ (p : sphere 2), f (0, p) = p
∧ ∀ (p : sphere 2), f (1, p) = - p
-- sorry
:=
sorry
/- What about trying to say that there are uncountably many different smooth structures on `ℝ⁴`?
(see https://en.wikipedia.org/wiki/Exotic_R4). The library is not really designed with this in mind,
as in general we only work with one differentiable structure on a space, but it is perfectly
capable of expressing this fact if one uses the `@` version of some definitions. -/
theorem exotic_ℝ4 :
-- sorry
let E := (euclidean_space (fin 4)) in
∃ f : ℝ → charted_space E E,
∀ i, @has_groupoid E _ E _ (f i) (times_cont_diff_groupoid ∞ (𝓡 4))
∧ ∀ i j, nonempty (@structomorph _ _ (times_cont_diff_groupoid ∞ (𝓡 4)) E E _ _ (f i) (f j)) →
i = j
-- sorry
:=
sorry
/-!
### Smooth functions on `[0, 1]`
In this paragraph, you will prove several (math-trivial but Lean-nontrivial) statements on the smooth
structure of `[0,1]`. These facts should be Lean-trivial, but they are not (yet) since there is essentially
nothing in this direction for now in the library.
The goal is as much to be able to write the statements as to prove them. Most of the necessary vocabulary
has been introduced above, so don't hesitate to browse the file if you are stuck. Additionally, you will
need the notion of a smooth function on a subset: it is `times_cont_diff_on` for functions between vector
spaces and `times_cont_mdiff_on` for functions between manifolds.
Lemma 1 : the inclusion of `[0, 1]` in `ℝ` is smooth.
Lemma 2 : Consider a function `f : ℝ → [0, 1]`, which is smooth in the usual sense as a function
from `ℝ` to `ℝ` on a set `s`. Then it is manifold-smooth on `s`.
Definition 3 : construct a function from `ℝ` to `[0,1]` which is the identity on `[0, 1]`.
Theorem 4 : the tangent bundle to `[0, 1]` is homeomorphic to `[0, 1] × ℝ`
(Hint for Theorem 4: don't try to unfold the definition of the tangent bundle, it will only get you
into trouble. Instead, use functoriality of the derivative and Lemma 1 and Definition 3)
-/
-- omit
lemma lemma_one : times_cont_mdiff (𝓡∂ 1) I ∞ (subtype.val : Icc (0 : ℝ) 1 → ℝ) :=
begin
rw times_cont_mdiff_iff,
refine ⟨continuous_subtype_val, _⟩,
simp only with mfld_simps,
assume x y,
by_cases h : (x : ℝ) < 1,
{ simp only [chart_at, h, Icc_left_chart, function.comp, model_with_corners_euclidean_half_space,
add_zero, dif_pos, if_true, max_lt_iff, preimage_set_of_eq, sub_zero, subtype.range_coe_subtype,
subtype.coe_mk, subtype.val_eq_coe] with mfld_simps,
refine (pi_Lp.times_cont_diff_coord 0).times_cont_diff_on.congr (λ x hx, _),
simp only [mem_inter_eq, mem_set_of_eq] at hx,
simp only [hx, le_of_lt hx.right.left, min_eq_left, max_eq_left] },
{ simp only [chart_at, h, Icc_right_chart, function.comp, model_with_corners_euclidean_half_space, dif_pos,
max_lt_iff, preimage_set_of_eq, sub_zero, subtype.range_coe_subtype, if_false, subtype.coe_mk,
subtype.val_eq_coe] with mfld_simps,
have : times_cont_diff ℝ ⊤ (λ (x : euclidean_space (fin 1)), 1 - x 0) :=
times_cont_diff_const.sub (pi_Lp.times_cont_diff_coord 0),
apply this.times_cont_diff_on.congr (λ x hx, _),
simp only [mem_inter_eq, mem_set_of_eq] at hx,
have : 0 ≤ 1 - x 0, by linarith,
simp only [hx, this, max_eq_left] }
end
def direct_function : tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) → (Icc (0 : ℝ) 1) × ℝ :=
λ p, (p.1, mfderiv (𝓡∂ 1) I (subtype.val : Icc (0 : ℝ) 1 → ℝ) p.1 p.2)
-- omit
/-!
### Further things to do
1) can you prove `diffeomorph_of_zero_dim_connected` or `connected_sphere`?
2) Try to express and then prove the local inverse theorem in real manifolds: if a map between
real manifolds (without boundary, modelled on a complete vector space) is smooth, then it is
a local homeomorphism around each point. We already have versions of this statement in mathlib
for functions between vector spaces, but this is very much a work in progress.
3) What about trying to prove `diffeomorph_of_one_dim_compact_connected`? (I am not sure mathlib
is ready for this, as the proofs I am thinking of are currently a little bit too high-powered.
If you manage to do it, you should absolutely PR it!)
4) Why not contribute to the proof of `sphere_eversion`? You can have a look at
https://leanprover-community.github.io/sphere-eversion/ to learn more about this project
by Patrick Massot.
-/
|
66a9f4d30ee2d436a9f7e61350c9114e071a4b8c | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/sheaves/limits.lean | 6ee5b92158cf4b723b2c7f93968c8b430dbfeabd | [] | 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 | 988 | 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.topology.sheaves.presheaf
import Mathlib.category_theory.limits.functor_category
import Mathlib.PostPort
universes v u
namespace Mathlib
/-!
# Presheaves in `C` have limits and colimits when `C` does.
-/
namespace Top
protected instance presheaf.category_theory.limits.has_limits {C : Type u} [category_theory.category C] [category_theory.limits.has_limits C] (X : Top) : category_theory.limits.has_limits (presheaf C X) :=
id category_theory.limits.functor_category_has_limits
protected instance presheaf.category_theory.limits.has_colimits {C : Type u} [category_theory.category C] [category_theory.limits.has_colimits C] (X : Top) : category_theory.limits.has_colimits (presheaf C X) :=
id category_theory.limits.functor_category_has_colimits
|
97241f6fac8120add36e1bad1c77bcce53f52bb4 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/data/polynomial/eval.lean | 526a21bb30f3e39c7f4e926780a691e699bd5cb1 | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 22,783 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import data.polynomial.induction
import data.polynomial.degree.definitions
import deprecated.ring
/-!
# Theory of univariate polynomials
The main defs here are `eval₂`, `eval`, and `map`.
We give several lemmas about their interaction with each other and with module operations.
-/
noncomputable theory
open finsupp finset add_monoid_algebra
open_locale big_operators
namespace polynomial
universes u v w y
variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {a b : R} {m n : ℕ}
section semiring
variables [semiring R] {p q r : polynomial R}
section
variables [semiring S]
variables (f : R →+* S) (x : S)
/-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring
to the target and a value `x` for the variable in the target -/
def eval₂ (p : polynomial R) : S :=
p.sum (λ e a, f a * x ^ e)
lemma eval₂_eq_sum {f : R →+* S} {x : S} : p.eval₂ f x = p.sum (λ e a, f a * x ^ e) := rfl
lemma eval₂_eq_lift_nc {f : R →+* S} {x : S} : eval₂ f x = lift_nc ↑f (powers_hom S x) := rfl
lemma eval₂_congr {R S : Type*} [semiring R] [semiring S]
{f g : R →+* S} {s t : S} {φ ψ : polynomial R} :
f = g → s = t → φ = ψ → eval₂ f s φ = eval₂ g t ψ :=
by rintro rfl rfl rfl; refl
@[simp] lemma eval₂_zero : (0 : polynomial R).eval₂ f x = 0 :=
finsupp.sum_zero_index
@[simp] lemma eval₂_C : (C a).eval₂ f x = f a :=
(sum_single_index $ by rw [f.map_zero, zero_mul]).trans $ by simp [pow_zero, mul_one]
@[simp] lemma eval₂_X : X.eval₂ f x = x :=
(sum_single_index $ by rw [f.map_zero, zero_mul]).trans $ by rw [f.map_one, one_mul, pow_one]
@[simp] lemma eval₂_monomial {n : ℕ} {r : R} : (monomial n r).eval₂ f x = (f r) * x^n :=
begin
apply sum_single_index,
simp,
end
@[simp] lemma eval₂_X_pow {n : ℕ} : (X^n).eval₂ f x = x^n :=
begin
rw X_pow_eq_monomial,
convert eval₂_monomial f x,
simp,
end
@[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x :=
finsupp.sum_add_index
(λ _, by rw [f.map_zero, zero_mul])
(λ _ _ _, by rw [f.map_add, add_mul])
@[simp] lemma eval₂_one : (1 : polynomial R).eval₂ f x = 1 :=
by rw [← C_1, eval₂_C, f.map_one]
@[simp] lemma eval₂_bit0 : (bit0 p).eval₂ f x = bit0 (p.eval₂ f x) :=
by rw [bit0, eval₂_add, bit0]
@[simp] lemma eval₂_bit1 : (bit1 p).eval₂ f x = bit1 (p.eval₂ f x) :=
by rw [bit1, eval₂_add, eval₂_bit0, eval₂_one, bit1]
@[simp] lemma eval₂_smul (g : R →+* S) (p : polynomial R) (x : S) {s : R} :
eval₂ g x (s • p) = g s * eval₂ g x p :=
begin
simp only [eval₂, sum_smul_index, forall_const, zero_mul, g.map_zero, g.map_mul, mul_assoc],
rw [←finsupp.mul_sum],
end
@[simp] lemma eval₂_C_X : eval₂ C X p = p :=
polynomial.induction_on' p (λ p q hp hq, by simp [hp, hq])
(λ n x, by rw [eval₂_monomial, monomial_eq_smul_X, C_mul'])
instance eval₂.is_add_monoid_hom : is_add_monoid_hom (eval₂ f x) :=
{ map_zero := eval₂_zero _ _, map_add := λ _ _, eval₂_add _ _ }
@[simp] lemma eval₂_nat_cast (n : ℕ) : (n : polynomial R).eval₂ f x = n :=
nat.rec_on n rfl $ λ n ih, by rw [n.cast_succ, eval₂_add, ih, eval₂_one, n.cast_succ]
variables [semiring T]
lemma eval₂_sum (p : polynomial T) (g : ℕ → T → polynomial R) (x : S) :
(p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) :=
finsupp.sum_sum_index (by simp [is_add_monoid_hom.map_zero f])
(by intros; simp [right_distrib, is_add_monoid_hom.map_add f])
lemma eval₂_finset_sum (s : finset ι) (g : ι → polynomial R) (x : S) :
(∑ i in s, g i).eval₂ f x = ∑ i in s, (g i).eval₂ f x :=
begin
classical,
induction s using finset.induction with p hp s hs, simp,
rw [sum_insert, eval₂_add, hs, sum_insert]; assumption,
end
lemma eval₂_mul_noncomm (hf : ∀ k, commute (f $ q.coeff k) x) :
eval₂ f x (p * q) = eval₂ f x p * eval₂ f x q :=
begin
simp only [eval₂_eq_lift_nc],
exact lift_nc_mul _ _ p q (λ k n hn, (hf k).pow_right n)
end
@[simp] lemma eval₂_mul_X : eval₂ f x (p * X) = eval₂ f x p * x :=
begin
refine trans (eval₂_mul_noncomm _ _ $ λ k, _) (by rw eval₂_X),
rcases em (k = 1) with (rfl|hk),
{ simp },
{ simp [coeff_X_of_ne_one hk] }
end
@[simp] lemma eval₂_X_mul : eval₂ f x (X * p) = eval₂ f x p * x :=
by rw [X_mul, eval₂_mul_X]
lemma eval₂_mul_C' (h : commute (f a) x) : eval₂ f x (p * C a) = eval₂ f x p * f a :=
begin
rw [eval₂_mul_noncomm, eval₂_C],
intro k,
obtain (hk|(hk : _ = _)) : (C a).coeff k ∈ ({0, a} : set R) := finsupp.single_apply_mem _;
simp [hk, h]
end
lemma eval₂_list_prod_noncomm (ps : list (polynomial R))
(hf : ∀ (p ∈ ps) k, commute (f $ coeff p k) x) :
eval₂ f x ps.prod = (ps.map (polynomial.eval₂ f x)).prod :=
begin
induction ps using list.reverse_rec_on with ps p ihp,
{ simp },
{ simp only [list.forall_mem_append, list.forall_mem_singleton] at hf,
simp [eval₂_mul_noncomm _ _ hf.2, ihp hf.1] }
end
/-- `eval₂` as a `ring_hom` for noncommutative rings -/
def eval₂_ring_hom' (f : R →+* S) (x : S) (hf : ∀ a, commute (f a) x) : polynomial R →+* S :=
{ to_fun := eval₂ f x,
map_add' := λ _ _, eval₂_add _ _,
map_zero' := eval₂_zero _ _,
map_mul' := λ p q, eval₂_mul_noncomm f x (λ k, hf $ coeff q k),
map_one' := eval₂_one _ _ }
end
/-!
We next prove that eval₂ is multiplicative
as long as target ring is commutative
(even if the source ring is not).
-/
section eval₂
variables [comm_semiring S]
variables (f : R →+* S) (x : S)
@[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x :=
eval₂_mul_noncomm _ _ $ λ k, commute.all _ _
lemma eval₂_mul_eq_zero_of_left (q : polynomial R) (hp : p.eval₂ f x = 0) :
(p * q).eval₂ f x = 0 :=
begin
rw eval₂_mul f x,
exact mul_eq_zero_of_left hp (q.eval₂ f x)
end
lemma eval₂_mul_eq_zero_of_right (p : polynomial R) (hq : q.eval₂ f x = 0) :
(p * q).eval₂ f x = 0 :=
begin
rw eval₂_mul f x,
exact mul_eq_zero_of_right (p.eval₂ f x) hq
end
instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) :=
⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩
/-- `eval₂` as a `ring_hom` -/
def eval₂_ring_hom (f : R →+* S) (x) : polynomial R →+* S :=
ring_hom.of (eval₂ f x)
@[simp] lemma coe_eval₂_ring_hom (f : R →+* S) (x) : ⇑(eval₂_ring_hom f x) = eval₂ f x := rfl
lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := (eval₂_ring_hom _ _).map_pow _ _
lemma eval₂_eq_sum_range :
p.eval₂ f x = ∑ i in finset.range (p.nat_degree + 1), f (p.coeff i) * x^i :=
trans (congr_arg _ p.as_sum_range) (trans (eval₂_finset_sum f _ _ x) (congr_arg _ (by simp)))
lemma eval₂_eq_sum_range' (f : R →+* S) {p : polynomial R} {n : ℕ} (hn : p.nat_degree < n) (x : S) :
eval₂ f x p = ∑ i in finset.range n, f (p.coeff i) * x ^ i :=
begin
rw [eval₂_eq_sum, p.sum_over_range' _ _ hn],
intro i,
rw [f.map_zero, zero_mul]
end
end eval₂
section eval
variables {x : R}
/-- `eval x p` is the evaluation of the polynomial `p` at `x` -/
def eval : R → polynomial R → R := eval₂ (ring_hom.id _)
lemma eval_eq_sum : p.eval x = sum p (λ e a, a * x ^ e) :=
rfl
lemma eval_eq_finset_sum (P : polynomial R) (x : R) :
eval x P = ∑ i in range (P.nat_degree + 1), P.coeff i * x ^ i :=
begin
rw eval_eq_sum,
refine P.sum_of_support_subset _ _ _,
{ intros a,
rw [mem_range, nat.lt_add_one_iff],
exact le_nat_degree_of_mem_supp a },
{ intros,
exact zero_mul _ }
end
lemma eval_eq_finset_sum' (P : polynomial R) :
(λ x, eval x P) = (λ x, ∑ i in range (P.nat_degree + 1), P.coeff i * x ^ i) :=
begin
ext,
exact P.eval_eq_finset_sum x
end
@[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _
@[simp] lemma eval_nat_cast {n : ℕ} : (n : polynomial R).eval x = n :=
by simp only [←C_eq_nat_cast, eval_C]
@[simp] lemma eval_X : X.eval x = x := eval₂_X _ _
@[simp] lemma eval_monomial {n a} : (monomial n a).eval x = a * x^n :=
eval₂_monomial _ _
@[simp] lemma eval_zero : (0 : polynomial R).eval x = 0 := eval₂_zero _ _
@[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _
@[simp] lemma eval_one : (1 : polynomial R).eval x = 1 := eval₂_one _ _
@[simp] lemma eval_bit0 : (bit0 p).eval x = bit0 (p.eval x) := eval₂_bit0 _ _
@[simp] lemma eval_bit1 : (bit1 p).eval x = bit1 (p.eval x) := eval₂_bit1 _ _
@[simp] lemma eval_smul (p : polynomial R) (x : R) {s : R} :
(s • p).eval x = s * p.eval x :=
eval₂_smul (ring_hom.id _) _ _
lemma eval_sum (p : polynomial R) (f : ℕ → R → polynomial R) (x : R) :
(p.sum f).eval x = p.sum (λ n a, (f n a).eval x) :=
eval₂_sum _ _ _ _
lemma eval_finset_sum (s : finset ι) (g : ι → polynomial R) (x : R) :
(∑ i in s, g i).eval x = ∑ i in s, (g i).eval x := eval₂_finset_sum _ _ _ _
/-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/
def is_root (p : polynomial R) (a : R) : Prop := p.eval a = 0
instance [decidable_eq R] : decidable (is_root p a) := by unfold is_root; apply_instance
@[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl
lemma coeff_zero_eq_eval_zero (p : polynomial R) :
coeff p 0 = p.eval 0 :=
calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp
... = p.eval 0 : eq.symm $
finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp)
lemma zero_is_root_of_coeff_zero_eq_zero {p : polynomial R} (hp : p.coeff 0 = 0) :
is_root p 0 :=
by rwa coeff_zero_eq_eval_zero at hp
end eval
section comp
/-- The composition of polynomials as a polynomial. -/
def comp (p q : polynomial R) : polynomial R := p.eval₂ C q
lemma comp_eq_sum_left : p.comp q = p.sum (λ e a, C a * q ^ e) :=
rfl
@[simp] lemma comp_X : p.comp X = p :=
begin
simp only [comp, eval₂, ← single_eq_C_mul_X],
exact finsupp.sum_single _,
end
@[simp] lemma X_comp : X.comp p = p := eval₂_X _ _
@[simp] lemma comp_C : p.comp (C a) = C (p.eval a) :=
begin
dsimp [comp, eval₂, eval, finsupp.sum],
rw [← p.support.sum_hom (@C R _)],
apply finset.sum_congr rfl; simp
end
@[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _
@[simp] lemma comp_zero : p.comp (0 : polynomial R) = C (p.eval 0) :=
by rw [← C_0, comp_C]
@[simp] lemma zero_comp : comp (0 : polynomial R) p = 0 :=
by rw [← C_0, C_comp]
@[simp] lemma comp_one : p.comp 1 = C (p.eval 1) :=
by rw [← C_1, comp_C]
@[simp] lemma one_comp : comp (1 : polynomial R) p = 1 :=
by rw [← C_1, C_comp]
@[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _
@[simp] lemma mul_comp {R : Type*} [comm_semiring R] (p q r : polynomial R) :
(p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _
@[simp] lemma bit0_comp : comp (bit0 p : polynomial R) q = bit0 (p.comp q) :=
by simp only [bit0, add_comp]
@[simp] lemma bit1_comp : comp (bit1 p : polynomial R) q = bit1 (p.comp q) :=
by simp only [bit1, add_comp, bit0_comp, one_comp]
lemma comp_assoc {R : Type*} [comm_semiring R] (φ ψ χ : polynomial R) :
(φ.comp ψ).comp χ = φ.comp (ψ.comp χ) :=
begin
apply polynomial.induction_on φ;
{ intros, simp only [add_comp, mul_comp, C_comp, X_comp, pow_succ', ← mul_assoc, *] at * }
end
end comp
section map
variables [semiring S]
variables (f : R →+* S)
/-- `map f p` maps a polynomial `p` across a ring hom `f` -/
def map : polynomial R → polynomial S := eval₂ (C.comp f) X
instance is_semiring_hom_C_f : is_semiring_hom (C ∘ f) :=
is_semiring_hom.comp _ _
@[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _
@[simp] lemma map_X : X.map f = X := eval₂_X _ _
@[simp] lemma map_monomial {n a} : (monomial n a).map f = monomial n (f a) :=
begin
dsimp only [map],
rw [eval₂_monomial, single_eq_C_mul_X], refl,
end
@[simp] lemma map_zero : (0 : polynomial R).map f = 0 := eval₂_zero _ _
@[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _
@[simp] lemma map_one : (1 : polynomial R).map f = 1 := eval₂_one _ _
@[simp] theorem map_nat_cast (n : ℕ) : (n : polynomial R).map f = n :=
nat.rec_on n rfl $ λ n ih, by rw [n.cast_succ, map_add, ih, map_one, n.cast_succ]
@[simp]
lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) :=
begin
rw [map, eval₂, coeff_sum],
conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, finsupp.sum,
← p.support.sum_hom f], },
refine finset.sum_congr rfl (λ x hx, _),
simp [function.comp, coeff_C_mul_X, f.map_mul],
split_ifs; simp [is_semiring_hom.map_zero f],
end
lemma map_map [semiring T] (g : S →+* T)
(p : polynomial R) : (p.map f).map g = p.map (g.comp f) :=
ext (by simp [coeff_map])
@[simp] lemma map_id : p.map (ring_hom.id _) = p := by simp [polynomial.ext_iff, coeff_map]
lemma eval₂_eq_eval_map {x : S} : p.eval₂ f x = (p.map f).eval x :=
begin
apply polynomial.induction_on' p,
{ intros p q hp hq, simp [hp, hq], },
{ intros n r, simp, }
end
lemma map_injective (hf : function.injective f) : function.injective (map f) :=
λ p q h, ext $ λ m, hf $ by rw [← coeff_map f, ← coeff_map f, h]
lemma map_surjective (hf : function.surjective f) : function.surjective (map f) :=
λ p, polynomial.induction_on' p
(λ p q hp hq, let ⟨p', hp'⟩ := hp, ⟨q', hq'⟩ := hq in ⟨p' + q', by rw [map_add f, hp', hq']⟩)
(λ n s, let ⟨r, hr⟩ := hf s in ⟨monomial n r, by rw [map_monomial f, hr]⟩)
variables {f}
lemma map_monic_eq_zero_iff (hp : p.monic) : p.map f = 0 ↔ ∀ x, f x = 0 :=
⟨ λ hfp x, calc f x = f x * f p.leading_coeff : by simp [hp]
... = f x * (p.map f).coeff p.nat_degree : by { congr, apply (coeff_map _ _).symm }
... = 0 : by simp [hfp],
λ h, ext (λ n, trans (coeff_map f n) (h _)) ⟩
lemma map_monic_ne_zero (hp : p.monic) [nontrivial S] : p.map f ≠ 0 :=
λ h, f.map_one_ne_zero ((map_monic_eq_zero_iff hp).mp h _)
variables (f)
open is_semiring_hom
-- If the rings were commutative, we could prove this just using `eval₂_mul`.
-- TODO this proof is just a hack job on the proof of `eval₂_mul`,
-- using that `X` is central. It should probably be golfed!
@[simp] lemma map_mul : (p * q).map f = p.map f * q.map f :=
begin
dunfold map,
dunfold eval₂,
rw [add_monoid_algebra.mul_def, finsupp.sum_mul _ p], simp only [finsupp.mul_sum _ q],
rw [sum_sum_index],
{ apply sum_congr rfl, assume i hi, dsimp only, rw [sum_sum_index],
{ apply sum_congr rfl, assume j hj, dsimp only,
rw [sum_single_index, (C.comp f).map_mul, pow_add],
{ simp [←mul_assoc], conv_lhs { rw ←@X_pow_mul_assoc _ _ _ _ i }, },
{ simp, } },
{ intro, simp, },
{ intros, simp [add_mul], } },
{ intro, simp, },
{ intros, simp [add_mul], }
end
instance map.is_semiring_hom : is_semiring_hom (map f) :=
{ map_zero := eval₂_zero _ _,
map_one := eval₂_one _ _,
map_add := λ _ _, eval₂_add _ _,
map_mul := λ _ _, map_mul f, }
/-- `polynomial.map` as a `ring_hom` -/
def map_ring_hom (f : R →+* S) : polynomial R →+* polynomial S :=
{ to_fun := polynomial.map f,
map_add' := λ _ _, eval₂_add _ _,
map_zero' := eval₂_zero _ _,
map_mul' := λ _ _, map_mul f,
map_one' := eval₂_one _ _ }
@[simp] lemma coe_map_ring_hom (f : R →+* S) : ⇑(map_ring_hom f) = map f := rfl
lemma map_list_prod (L : list (polynomial R)) : L.prod.map f = (L.map $ map f).prod :=
eq.symm $ list.prod_hom _ (monoid_hom.of (map f))
@[simp] lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := is_monoid_hom.map_pow (map f) _ _
lemma mem_map_range {p : polynomial S} :
p ∈ set.range (map f) ↔ ∀ n, p.coeff n ∈ (set.range f) :=
begin
split,
{ rintro ⟨p, rfl⟩ n, rw coeff_map, exact set.mem_range_self _ },
{ intro h, rw p.as_sum_range_C_mul_X_pow,
apply is_add_submonoid.finset_sum_mem,
intros i hi,
rcases h i with ⟨c, hc⟩,
use [C c * X^i],
rw [map_mul, map_C, hc, map_pow, map_X] }
end
lemma eval₂_map [semiring T] (g : S →+* T) (x : T) :
(p.map f).eval₂ g x = p.eval₂ (g.comp f) x :=
begin
convert finsupp.sum_map_range_index _,
{ change map f p = map_range f _ p,
ext,
rw map_range_apply,
exact coeff_map f a, },
{ exact f.map_zero, },
{ intro a, simp only [ring_hom.map_zero, zero_mul], },
end
lemma eval_map (x : S) : (p.map f).eval x = p.eval₂ f x :=
eval₂_map f (ring_hom.id _) x
lemma map_sum {ι : Type*} (g : ι → polynomial R) (s : finset ι) :
(∑ i in s, g i).map f = ∑ i in s, (g i).map f :=
eq.symm $ sum_hom _ _
@[simp]
lemma eval_zero_map (f : R →+* S) (p : polynomial R) :
(p.map f).eval 0 = f (p.eval 0) :=
by simp [←coeff_zero_eq_eval_zero]
@[simp]
lemma eval_one_map (f : R →+* S) (p : polynomial R) :
(p.map f).eval 1 = f (p.eval 1) :=
begin
apply polynomial.induction_on' p,
{ intros p q hp hq, simp [hp, hq], },
{ intros n r, simp, }
end
@[simp]
lemma eval_nat_cast_map (f : R →+* S) (p : polynomial R) (n : ℕ) :
(p.map f).eval n = f (p.eval n) :=
begin
apply polynomial.induction_on' p,
{ intros p q hp hq, simp [hp, hq], },
{ intros n r, simp, }
end
@[simp]
lemma eval_int_cast_map {R S : Type*} [ring R] [ring S]
(f : R →+* S) (p : polynomial R) (i : ℤ) :
(p.map f).eval i = f (p.eval i) :=
begin
apply polynomial.induction_on' p,
{ intros p q hp hq, simp [hp, hq], },
{ intros n r, simp, }
end
end map
/-!
After having set up the basic theory of `eval₂`, `eval`, `comp`, and `map`,
we make `eval₂` irreducible.
Perhaps we can make the others irreducible too?
-/
attribute [irreducible] polynomial.eval₂
section hom_eval₂
-- TODO: Here we need commutativity in both `S` and `T`?
variables [comm_semiring S] [comm_semiring T]
variables (f : R →+* S) (g : S →+* T) (p)
lemma hom_eval₂ (x : S) : g (p.eval₂ f x) = p.eval₂ (g.comp f) (g x) :=
begin
apply polynomial.induction_on p; clear p,
{ intros a, rw [eval₂_C, eval₂_C], refl, },
{ intros p q hp hq, simp only [hp, hq, eval₂_add, g.map_add] },
{ intros n a ih,
simp only [eval₂_mul, eval₂_C, eval₂_X_pow, g.map_mul, g.map_pow],
refl, }
end
end hom_eval₂
end semiring
section comm_semiring
section eval
variables [comm_semiring R] {p q : polynomial R} {x : R}
@[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _
instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _
@[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _
lemma eval₂_hom [comm_semiring S] (f : R →+* S) (x : R) :
p.eval₂ f (f x) = f (p.eval x) :=
(ring_hom.comp_id f) ▸ (hom_eval₂ p (ring_hom.id R) f x).symm
lemma root_mul_left_of_is_root (p : polynomial R) {q : polynomial R} :
is_root q a → is_root (p * q) a :=
λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero]
lemma root_mul_right_of_is_root {p : polynomial R} (q : polynomial R) :
is_root p a → is_root (p * q) a :=
λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul]
/--
Polynomial evaluation commutes with finset.prod
-/
lemma eval_prod {ι : Type*} (s : finset ι) (p : ι → polynomial R) (x : R) :
eval x (∏ j in s, p j) = ∏ j in s, eval x (p j) :=
begin
classical,
apply finset.induction_on s,
{ simp only [finset.prod_empty, eval_one] },
{ intros j s hj hpj,
have h0 : ∏ i in insert j s, eval x (p i) = (eval x (p j)) * ∏ i in s, eval x (p i),
{ apply finset.prod_insert hj },
rw [h0, ← hpj, finset.prod_insert hj, eval_mul] },
end
end eval
section map
variables [comm_semiring R] [comm_semiring S] (f : R →+* S)
lemma map_multiset_prod (m : multiset (polynomial R)) : m.prod.map f = (m.map $ map f).prod :=
eq.symm $ multiset.prod_hom _ (monoid_hom.of (map f))
lemma map_prod {ι : Type*} (g : ι → polynomial R) (s : finset ι) :
(∏ i in s, g i).map f = ∏ i in s, (g i).map f :=
eq.symm $ prod_hom _ _
lemma support_map_subset (p : polynomial R) : (map f p).support ⊆ p.support :=
begin
intros x,
simp only [mem_support_iff],
contrapose!,
change p.coeff x = 0 → (map f p).coeff x = 0,
rw coeff_map,
intro hx,
rw hx,
exact ring_hom.map_zero f,
end
lemma map_comp (p q : polynomial R) : map f (p.comp q) = (map f p).comp (map f q) :=
polynomial.induction_on p
(by simp)
(by simp {contextual := tt})
(by simp [pow_succ', ← mul_assoc, polynomial.comp] {contextual := tt})
end map
end comm_semiring
section ring
variables [ring R] {p q r : polynomial R}
-- @[simp]
-- lemma C_eq_int_cast (n : ℤ) : C ↑n = (n : polynomial R) :=
-- (C : R →+* _).map_int_cast n
lemma C_neg : C (-a) = -C a := ring_hom.map_neg C a
lemma C_sub : C (a - b) = C a - C b := ring_hom.map_sub C a b
instance map.is_ring_hom {S} [ring S] (f : R →+* S) : is_ring_hom (map f) :=
by apply is_ring_hom.of_semiring
@[simp] lemma map_sub {S} [ring S] (f : R →+* S) :
(p - q).map f = p.map f - q.map f :=
is_ring_hom.map_sub _
@[simp] lemma map_neg {S} [ring S] (f : R →+* S) :
(-p).map f = -(p.map f) :=
is_ring_hom.map_neg _
@[simp] lemma map_int_cast {S} [ring S] (f : R →+* S) (n : ℤ) :
map f ↑n = ↑n :=
(ring_hom.of (map f)).map_int_cast n
@[simp] lemma eval_int_cast {n : ℤ} {x : R} : (n : polynomial R).eval x = n :=
by simp only [←C_eq_int_cast, eval_C]
@[simp] lemma eval₂_neg {S} [ring S] (f : R →+* S) {x : S} :
(-p).eval₂ f x = -p.eval₂ f x :=
by rw [eq_neg_iff_add_eq_zero, ←eval₂_add, add_left_neg, eval₂_zero]
@[simp] lemma eval₂_sub {S} [ring S] (f : R →+* S) {x : S} :
(p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x :=
by rw [sub_eq_add_neg, eval₂_add, eval₂_neg, sub_eq_add_neg]
@[simp] lemma eval_neg (p : polynomial R) (x : R) : (-p).eval x = -p.eval x :=
eval₂_neg _
@[simp] lemma eval_sub (p q : polynomial R) (x : R) : (p - q).eval x = p.eval x - q.eval x :=
eval₂_sub _
lemma root_X_sub_C : is_root (X - C a) b ↔ a = b :=
by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm]
@[simp] lemma neg_comp : (-p).comp q = -p.comp q := eval₂_neg _
@[simp] lemma sub_comp : (p - q).comp r = p.comp r - q.comp r := eval₂_sub _
end ring
section comm_ring
variables [comm_ring R] {p q : polynomial R}
instance eval₂.is_ring_hom {S} [comm_ring S]
(f : R →+* S) {x : S} : is_ring_hom (eval₂ f x) :=
by apply is_ring_hom.of_semiring
instance eval.is_ring_hom {x : R} : is_ring_hom (eval x) := eval₂.is_ring_hom _
end comm_ring
end polynomial
|
4a553a9772615e6a1a82d756346379fd0d25c802 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/linear_algebra/special_linear_group.lean | f5d5961a433a2f6ddd5bb0c2a9f4ec6ca57462c1 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,666 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Anne Baanen.
The Special Linear group $SL(n, R)$
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.linear_algebra.matrix
import Mathlib.linear_algebra.nonsingular_inverse
import Mathlib.PostPort
universes u v
namespace Mathlib
/-!
# The Special Linear group $SL(n, R)$
This file defines the elements of the Special Linear group `special_linear_group n R`,
also written `SL(n, R)` or `SLₙ(R)`, consisting of all `n` by `n` `R`-matrices with
determinant `1`. In addition, we define the group structure on `special_linear_group n R`
and the embedding into the general linear group `general_linear_group R (n → R)`
(i.e. `GL(n, R)` or `GLₙ(R)`).
## Main definitions
* `matrix.special_linear_group` is the type of matrices with determinant 1
* `matrix.special_linear_group.group` gives the group structure (under multiplication)
* `matrix.special_linear_group.embedding_GL` is the embedding `SLₙ(R) → GLₙ(R)`
## Implementation notes
The inverse operation in the `special_linear_group` is defined to be the adjugate
matrix, so that `special_linear_group n R` has a group structure for all `comm_ring R`.
We define the elements of `special_linear_group` to be matrices, since we need to
compute their determinant. This is in contrast with `general_linear_group R M`,
which consists of invertible `R`-linear maps on `M`.
## References
* https://en.wikipedia.org/wiki/Special_linear_group
## Tags
matrix group, group, matrix inverse
-/
namespace matrix
/-- `special_linear_group n R` is the group of `n` by `n` `R`-matrices with determinant equal to 1. -/
def special_linear_group (n : Type u) [DecidableEq n] [fintype n] (R : Type v) [comm_ring R] :=
Subtype fun (A : matrix n n R) => det A = 1
namespace special_linear_group
protected instance coe_matrix {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : has_coe (special_linear_group n R) (matrix n n R) :=
has_coe.mk fun (A : special_linear_group n R) => subtype.val A
protected instance coe_fun {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : has_coe_to_fun (special_linear_group n R) :=
has_coe_to_fun.mk (fun (_x : special_linear_group n R) => n → n → R) fun (A : special_linear_group n R) => subtype.val A
/--
`to_lin' A` is matrix multiplication of vectors by `A`, as a linear map.
After the group structure on `special_linear_group n R` is defined,
we show in `to_linear_equiv` that this gives a linear equivalence.
-/
def to_lin' {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) : linear_map R (n → R) (n → R) :=
coe_fn to_lin' ⇑A
theorem ext_iff {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) (B : special_linear_group n R) : A = B ↔ ∀ (i j : n), coe_fn A i j = coe_fn B i j :=
iff.trans subtype.ext_iff_val
{ mp := fun (h : subtype.val A = subtype.val B) (i j : n) => congr_fun (congr_fun h i) j, mpr := ext }
theorem ext {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) (B : special_linear_group n R) : (∀ (i j : n), coe_fn A i j = coe_fn B i j) → A = B :=
iff.mpr (ext_iff A B)
protected instance has_inv {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : has_inv (special_linear_group n R) :=
has_inv.mk fun (A : special_linear_group n R) => { val := adjugate ⇑A, property := sorry }
protected instance has_mul {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : Mul (special_linear_group n R) :=
{ mul :=
fun (A B : special_linear_group n R) => { val := matrix.mul (subtype.val A) (subtype.val B), property := sorry } }
protected instance has_one {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : HasOne (special_linear_group n R) :=
{ one := { val := 1, property := sorry } }
protected instance inhabited {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : Inhabited (special_linear_group n R) :=
{ default := 1 }
@[simp] theorem inv_val {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) : ↑(A⁻¹) = adjugate ⇑A :=
rfl
@[simp] theorem inv_apply {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) : ⇑(A⁻¹) = adjugate ⇑A :=
rfl
@[simp] theorem mul_val {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) (B : special_linear_group n R) : ↑(A * B) = matrix.mul ⇑A ⇑B :=
rfl
@[simp] theorem mul_apply {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) (B : special_linear_group n R) : ⇑(A * B) = matrix.mul ⇑A ⇑B :=
rfl
@[simp] theorem one_val {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : ↑1 = 1 :=
rfl
@[simp] theorem one_apply {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : ⇑1 = 1 :=
rfl
@[simp] theorem det_coe_matrix {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) : det ⇑A = 1 :=
subtype.property A
theorem det_coe_fun {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) : det ⇑A = 1 :=
subtype.property A
@[simp] theorem to_lin'_mul {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) (B : special_linear_group n R) : to_lin' (A * B) = linear_map.comp (to_lin' A) (to_lin' B) :=
to_lin'_mul ⇑A ⇑B
@[simp] theorem to_lin'_one {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : to_lin' 1 = linear_map.id :=
to_lin'_one
protected instance group {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : group (special_linear_group n R) :=
group.mk Mul.mul sorry 1 sorry sorry has_inv.inv (div_inv_monoid.div._default Mul.mul sorry 1 sorry sorry has_inv.inv)
sorry
/-- `to_linear_equiv A` is matrix multiplication of vectors by `A`, as a linear equivalence. -/
def to_linear_equiv {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) : linear_equiv R (n → R) (n → R) :=
linear_equiv.mk (linear_map.to_fun (coe_fn to_lin' ⇑A)) sorry sorry ⇑(to_lin' (A⁻¹)) sorry sorry
/-- `to_GL` is the map from the special linear group to the general linear group -/
def to_GL {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) : linear_map.general_linear_group R (n → R) :=
linear_map.general_linear_group.of_linear_equiv (to_linear_equiv A)
theorem coe_to_GL {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) : ↑(to_GL A) = to_lin' A :=
rfl
@[simp] theorem to_GL_one {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : to_GL 1 = 1 := sorry
@[simp] theorem to_GL_mul {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] (A : special_linear_group n R) (B : special_linear_group n R) : to_GL (A * B) = to_GL A * to_GL B := sorry
/-- `special_linear_group.embedding_GL` is the embedding from `special_linear_group n R`
to `general_linear_group n R`. -/
def embedding_GL {n : Type u} [DecidableEq n] [fintype n] {R : Type v} [comm_ring R] : special_linear_group n R →* linear_map.general_linear_group R (n → R) :=
monoid_hom.mk (fun (A : special_linear_group n R) => to_GL A) sorry sorry
|
5218114ff4239c8b81e0ad1ea9cae9459ef4afeb | 4fa161becb8ce7378a709f5992a594764699e268 | /src/category_theory/limits/cones.lean | ae52a0327788b51f289a7cd5a08b2cd8b1b7accc | [
"Apache-2.0"
] | permissive | laughinggas/mathlib | e4aa4565ae34e46e834434284cb26bd9d67bc373 | 86dcd5cda7a5017c8b3c8876c89a510a19d49aad | refs/heads/master | 1,669,496,232,688 | 1,592,831,995,000 | 1,592,831,995,000 | 274,155,979 | 0 | 0 | Apache-2.0 | 1,592,835,190,000 | 1,592,835,189,000 | null | UTF-8 | Lean | false | false | 13,255 | 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, Floris van Doorn
-/
import category_theory.const
import category_theory.yoneda
universes v u u' -- declare the `v`'s first; see `category_theory.category` for an explanation
open category_theory
-- There is an awkward difficulty with universes here.
-- If we allowed `J` to be a small category in `Prop`, we'd run into trouble
-- because `yoneda.obj (F : (J ⥤ C)ᵒᵖ)` will be a functor into `Sort (max v 1)`,
-- not into `Sort v`.
-- So we don't allow this case; it's not particularly useful anyway.
variables {J : Type v} [small_category J]
variables {C : Type u} [category.{v} C]
open category_theory
open category_theory.category
open category_theory.functor
open opposite
namespace category_theory
namespace functor
variables {J C} (F : J ⥤ C)
/--
`F.cones` is the functor assigning to an object `X` the type of
natural transformations from the constant functor with value `X` to `F`.
An object representing this functor is a limit of `F`.
-/
def cones : Cᵒᵖ ⥤ Type v := (const J).op ⋙ (yoneda.obj F)
lemma cones_obj (X : Cᵒᵖ) : F.cones.obj X = ((const J).obj (unop X) ⟶ F) := rfl
@[simp] lemma cones_map_app {X₁ X₂ : Cᵒᵖ} (f : X₁ ⟶ X₂) (t : F.cones.obj X₁) (j : J) :
(F.cones.map f t).app j = f.unop ≫ t.app j := rfl
/--
`F.cocones` is the functor assigning to an object `X` the type of
natural transformations from `F` to the constant functor with value `X`.
An object corepresenting this functor is a colimit of `F`.
-/
def cocones : C ⥤ Type v := const J ⋙ coyoneda.obj (op F)
lemma cocones_obj (X : C) : F.cocones.obj X = (F ⟶ (const J).obj X) := rfl
@[simp] lemma cocones_map_app {X₁ X₂ : C} (f : X₁ ⟶ X₂) (t : F.cocones.obj X₁) (j : J) :
(F.cocones.map f t).app j = t.app j ≫ f := rfl
end functor
section
variables (J C)
/--
Functorially associated to each functor `J ⥤ C`, we have the `C`-presheaf consisting of
cones with a given cone point.
-/
@[simps] def cones : (J ⥤ C) ⥤ (Cᵒᵖ ⥤ Type v) :=
{ obj := functor.cones,
map := λ F G f, whisker_left (const J).op (yoneda.map f) }
/--
Contravariantly associated to each functor `J ⥤ C`, we have the `C`-copresheaf consisting of
cocones with a given cocone point.
-/
@[simps] def cocones : (J ⥤ C)ᵒᵖ ⥤ (C ⥤ Type v) :=
{ obj := λ F, functor.cocones (unop F),
map := λ F G f, whisker_left (const J) (coyoneda.map f) }
end
namespace limits
/--
A `c : cone F` is:
* an object `c.X` and
* a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`.
`cone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cones.obj X`.
-/
structure cone (F : J ⥤ C) :=
(X : C)
(π : (const J).obj X ⟶ F)
@[simp] lemma cone.w {F : J ⥤ C} (c : cone F) {j j' : J} (f : j ⟶ j') :
c.π.app j ≫ F.map f = c.π.app j' :=
by convert ←(c.π.naturality f).symm; apply id_comp
/--
A `c : cocone F` is
* an object `c.X` and
* a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor.
`cocone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cocones.obj X`.
-/
structure cocone (F : J ⥤ C) :=
(X : C)
(ι : F ⟶ (const J).obj X)
@[simp] lemma cocone.w {F : J ⥤ C} (c : cocone F) {j j' : J} (f : j ⟶ j') :
F.map f ≫ c.ι.app j' = c.ι.app j :=
by convert ←(c.ι.naturality f); apply comp_id
variables {F : J ⥤ C}
namespace cone
def equiv (F : J ⥤ C) : cone F ≅ Σ X, F.cones.obj X :=
{ hom := λ c, ⟨op c.X, c.π⟩,
inv := λ c, { X := unop c.1, π := c.2 },
hom_inv_id' := begin ext, cases x, refl, end,
inv_hom_id' := begin ext, cases x, refl, end }
@[simp] def extensions (c : cone F) : yoneda.obj c.X ⟶ F.cones :=
{ app := λ X f, ((const J).map f) ≫ c.π }
/-- A map to the vertex of a cone induces a cone by composition. -/
@[simp] def extend (c : cone F) {X : C} (f : X ⟶ c.X) : cone F :=
{ X := X,
π := c.extensions.app (op X) f }
@[simp] lemma extend_π (c : cone F) {X : Cᵒᵖ} (f : unop X ⟶ c.X) :
(extend c f).π = c.extensions.app X f :=
rfl
@[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) :=
{ X := c.X,
π := whisker_left E c.π }
end cone
namespace cocone
def equiv (F : J ⥤ C) : cocone F ≅ Σ X, F.cocones.obj X :=
{ hom := λ c, ⟨c.X, c.ι⟩,
inv := λ c, { X := c.1, ι := c.2 },
hom_inv_id' := begin ext, cases x, refl, end,
inv_hom_id' := begin ext, cases x, refl, end }
@[simp] def extensions (c : cocone F) : coyoneda.obj (op c.X) ⟶ F.cocones :=
{ app := λ X f, c.ι ≫ (const J).map f }
/-- A map from the vertex of a cocone induces a cocone by composition. -/
@[simp] def extend (c : cocone F) {X : C} (f : c.X ⟶ X) : cocone F :=
{ X := X,
ι := c.extensions.app X f }
@[simp] lemma extend_ι (c : cocone F) {X : C} (f : c.X ⟶ X) :
(extend c f).ι = c.extensions.app X f :=
rfl
@[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cocone F) : cocone (E ⋙ F) :=
{ X := c.X,
ι := whisker_left E c.ι }
end cocone
@[ext] structure cone_morphism (A B : cone F) :=
(hom : A.X ⟶ B.X)
(w' : ∀ j : J, hom ≫ B.π.app j = A.π.app j . obviously)
restate_axiom cone_morphism.w'
attribute [simp] cone_morphism.w
@[simps] instance cone.category : category.{v} (cone F) :=
{ hom := λ A B, cone_morphism A B,
comp := λ X Y Z f g,
{ hom := f.hom ≫ g.hom,
w' := by intro j; rw [assoc, g.w, f.w] },
id := λ B, { hom := 𝟙 B.X } }
namespace cones
/-- To give an isomorphism between cones, it suffices to give an
isomorphism between their vertices which commutes with the cone
maps. -/
@[ext, simps] def ext {c c' : cone F}
(φ : c.X ≅ c'.X) (w : ∀ j, c.π.app j = φ.hom ≫ c'.π.app j) : c ≅ c' :=
{ hom := { hom := φ.hom },
inv := { hom := φ.inv, w' := λ j, φ.inv_comp_eq.mpr (w j) } }
@[simps] def postcompose {G : J ⥤ C} (α : F ⟶ G) : cone F ⥤ cone G :=
{ obj := λ c, { X := c.X, π := c.π ≫ α },
map := λ c₁ c₂ f, { hom := f.hom, w' :=
by intro; erw ← category.assoc; simp [-category.assoc] } }
def postcompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) :
postcompose (α ≫ β) ≅ postcompose α ⋙ postcompose β :=
nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy)
def postcompose_id : postcompose (𝟙 F) ≅ 𝟭 (cone F) :=
nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy)
@[simps]
def postcompose_equivalence {G : J ⥤ C} (α : F ≅ G) : cone F ≌ cone G :=
{ functor := postcompose α.hom,
inverse := postcompose α.inv,
unit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy),
counit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) }
section
variable (F)
@[simps]
def forget : cone F ⥤ C :=
{ obj := λ t, t.X, map := λ s t f, f.hom }
variables {D : Type u'} [category.{v} D]
@[simps] def functoriality (G : C ⥤ D) : cone F ⥤ cone (F ⋙ G) :=
{ obj := λ A,
{ X := G.obj A.X,
π := { app := λ j, G.map (A.π.app j), naturality' := by intros; erw ←G.map_comp; tidy } },
map := λ X Y f,
{ hom := G.map f.hom,
w' := by intros; rw [←functor.map_comp, f.w] } }
end
end cones
@[ext] structure cocone_morphism (A B : cocone F) :=
(hom : A.X ⟶ B.X)
(w' : ∀ j : J, A.ι.app j ≫ hom = B.ι.app j . obviously)
restate_axiom cocone_morphism.w'
attribute [simp] cocone_morphism.w
@[simps] instance cocone.category : category.{v} (cocone F) :=
{ hom := λ A B, cocone_morphism A B,
comp := λ _ _ _ f g,
{ hom := f.hom ≫ g.hom,
w' := by intro j; rw [←assoc, f.w, g.w] },
id := λ B, { hom := 𝟙 B.X } }
namespace cocones
/-- To give an isomorphism between cocones, it suffices to give an
isomorphism between their vertices which commutes with the cocone
maps. -/
@[ext, simps] def ext {c c' : cocone F}
(φ : c.X ≅ c'.X) (w : ∀ j, c.ι.app j ≫ φ.hom = c'.ι.app j) : c ≅ c' :=
{ hom := { hom := φ.hom },
inv := { hom := φ.inv, w' := λ j, φ.comp_inv_eq.mpr (w j).symm } }
@[simps] def precompose {G : J ⥤ C} (α : G ⟶ F) : cocone F ⥤ cocone G :=
{ obj := λ c, { X := c.X, ι := α ≫ c.ι },
map := λ c₁ c₂ f, { hom := f.hom } }
def precompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) :
precompose (α ≫ β) ≅ precompose β ⋙ precompose α :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
def precompose_id : precompose (𝟙 F) ≅ 𝟭 (cocone F) :=
by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously }
@[simps]
def precompose_equivalence {G : J ⥤ C} (α : G ≅ F) : cocone F ≌ cocone G :=
{ functor := precompose α.hom,
inverse := precompose α.inv,
unit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy),
counit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy) }
section
variable (F)
@[simps]
def forget : cocone F ⥤ C :=
{ obj := λ t, t.X, map := λ s t f, f.hom }
variables {D : Type u'} [category.{v} D]
@[simps] def functoriality (G : C ⥤ D) : cocone F ⥤ cocone (F ⋙ G) :=
{ obj := λ A,
{ X := G.obj A.X,
ι := { app := λ j, G.map (A.ι.app j), naturality' := by intros; erw ←G.map_comp; tidy } },
map := λ _ _ f,
{ hom := G.map f.hom,
w' := by intros; rw [←functor.map_comp, cocone_morphism.w] } }
end
end cocones
end limits
namespace functor
variables {D : Type u'} [category.{v} D]
variables {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D)
open category_theory.limits
/-- The image of a cone in C under a functor G : C ⥤ D is a cone in D. -/
def map_cone (c : cone F) : cone (F ⋙ H) := (cones.functoriality F H).obj c
/-- The image of a cocone in C under a functor G : C ⥤ D is a cocone in D. -/
def map_cocone (c : cocone F) : cocone (F ⋙ H) := (cocones.functoriality F H).obj c
@[simp] lemma map_cone_X (c : cone F) : (H.map_cone c).X = H.obj c.X := rfl
@[simp] lemma map_cocone_X (c : cocone F) : (H.map_cocone c).X = H.obj c.X := rfl
@[simps]
def map_cone_inv [is_equivalence H]
(c : cone (F ⋙ H)) : cone F :=
let t := (inv H).map_cone c in
let α : (F ⋙ H) ⋙ inv H ⟶ F :=
((whisker_left F is_equivalence.unit_iso.inv) : F ⋙ (H ⋙ inv H) ⟶ _) ≫ (functor.right_unitor _).hom in
{ X := t.X,
π := ((category_theory.cones J C).map α).app (op t.X) t.π }
def map_cone_morphism {c c' : cone F} (f : c ⟶ c') :
(H.map_cone c) ⟶ (H.map_cone c') := (cones.functoriality F H).map f
def map_cocone_morphism {c c' : cocone F} (f : c ⟶ c') :
(H.map_cocone c) ⟶ (H.map_cocone c') := (cocones.functoriality F H).map f
@[simp] lemma map_cone_π (c : cone F) (j : J) :
(map_cone H c).π.app j = H.map (c.π.app j) := rfl
@[simp] lemma map_cocone_ι (c : cocone F) (j : J) :
(map_cocone H c).ι.app j = H.map (c.ι.app j) := rfl
/-- `map_cone` is the left inverse to `map_cone_inv`. -/
def map_cone_map_cone_inv {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cone (F ⋙ H)) :
map_cone H (map_cone_inv H c) ≅ c :=
begin
apply cones.ext _ (λ j, _),
{ exact H.inv_fun_id.app c.X },
{ dsimp,
erw [comp_id, ← H.inv_fun_id.hom.naturality (c.π.app j), comp_map, H.map_comp],
congr' 1,
erw [← cancel_epi (H.inv_fun_id.inv.app (H.obj (F.obj j))), nat_iso.inv_hom_id_app,
← (functor.as_equivalence H).functor_unit _, ← H.map_comp, nat_iso.hom_inv_id_app,
H.map_id],
refl }
end
end functor
end category_theory
namespace category_theory.limits
variables {F : J ⥤ Cᵒᵖ}
-- Here and below we only automatically generate the `@[simp]` lemma for the `X` field,
-- as we can be a simpler `rfl` lemma for the components of the natural transformation by hand.
@[simps X] def cone_of_cocone_left_op (c : cocone F.left_op) : cone F :=
{ X := op c.X,
π := nat_trans.right_op (c.ι ≫ (const.op_obj_unop (op c.X)).hom) }
@[simp] lemma cone_of_cocone_left_op_π_app (c : cocone F.left_op) (j) :
(cone_of_cocone_left_op c).π.app j = (c.ι.app (op j)).op :=
by { dsimp [cone_of_cocone_left_op], simp }
@[simps X] def cocone_left_op_of_cone (c : cone F) : cocone (F.left_op) :=
{ X := unop c.X,
ι := nat_trans.left_op c.π }
@[simp] lemma cocone_left_op_of_cone_ι_app (c : cone F) (j) :
(cocone_left_op_of_cone c).ι.app j = (c.π.app (unop j)).unop :=
by { dsimp [cocone_left_op_of_cone], simp }
@[simps X] def cocone_of_cone_left_op (c : cone F.left_op) : cocone F :=
{ X := op c.X,
ι := nat_trans.right_op ((const.op_obj_unop (op c.X)).hom ≫ c.π) }
@[simp] lemma cocone_of_cone_left_op_ι_app (c : cone F.left_op) (j) :
(cocone_of_cone_left_op c).ι.app j = (c.π.app (op j)).op :=
by { dsimp [cocone_of_cone_left_op], simp }
@[simps X] def cone_left_op_of_cocone (c : cocone F) : cone (F.left_op) :=
{ X := unop c.X,
π := nat_trans.left_op c.ι }
@[simp] lemma cone_left_op_of_cocone_π_app (c : cocone F) (j) :
(cone_left_op_of_cocone c).π.app j = (c.ι.app (unop j)).unop :=
by { dsimp [cone_left_op_of_cocone], simp }
end category_theory.limits
|
3b0bbd7ce7981a78a52bf0898b99ec754d781ef2 | 0845ae2ca02071debcfd4ac24be871236c01784f | /library/init/data/nat/default.lean | 3efeb2636d17b03621edee4b87a24c604b5fce3b | [
"Apache-2.0"
] | permissive | GaloisInc/lean4 | 74c267eb0e900bfaa23df8de86039483ecbd60b7 | 228ddd5fdcd98dd4e9c009f425284e86917938aa | refs/heads/master | 1,643,131,356,301 | 1,562,715,572,000 | 1,562,715,572,000 | 192,390,898 | 0 | 0 | null | 1,560,792,750,000 | 1,560,792,749,000 | null | UTF-8 | Lean | false | false | 239 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.data.nat.basic init.data.nat.div init.data.nat.bitwise
|
7d5cd400193a2fd3da9e28b2123f6b57a2f290c2 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/missingExplicitWithForwardNamedDep.lean | 9633bb4acee78c90dc047290d909a54026393829 | [
"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 | 633 | lean | class Foo (α : Type) (β : Type) where
val : Nat
a : α
b : β
#check Foo.val
def valOf [s : Foo α β] : Nat :=
s.val
#eval valOf (s := { val := 10, a := true, b := false : Foo Bool Bool })
def valOf2 (α β : Type) [s : Foo α β] : Nat :=
s.val
#check valOf2 (s := { val := 10, a := true, b := false : Foo Bool Bool })
-- valOf2 Bool Bool
def f (x y z : Nat) := x + y + z
#check f (z := 10)
-- fun (x y : Nat) => f x y 10 : Nat → Nat → Nat
def g {α : Type} (a b : α) := b
#check g (b := 10)
-- fun (a : Nat) => g a 10
def h (α : Type) (a b : α) := b
#check h (b := true)
-- fun a => h Bool a true
|
aae3ca9a156c86d6f29788eb23ae22a088ffced5 | bb31430994044506fa42fd667e2d556327e18dfe | /src/algebra/divisibility/basic.lean | ffa10bb7ff9c1341c66b74c5bb278461339202cf | [
"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 | 4,836 | 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, Amelia Livingston, Yury Kudryashov,
Neil Strickland, Aaron Anderson
-/
import algebra.hom.group
/-!
# Divisibility
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the basics of the divisibility relation in the context of `(comm_)` `monoid`s.
## Main definitions
* `monoid.has_dvd`
## Implementation notes
The divisibility relation is defined for all monoids, and as such, depends on the order of
multiplication if the monoid is not commutative. There are two possible conventions for
divisibility in the noncommutative context, and this relation follows the convention for ordinals,
so `a | b` is defined as `∃ c, b = a * c`.
## Tags
divisibility, divides
-/
variables {α : Type*}
section semigroup
variables [semigroup α] {a b c : α}
/-- There are two possible conventions for divisibility, which coincide in a `comm_monoid`.
This matches the convention for ordinals. -/
@[priority 100]
instance semigroup_has_dvd : has_dvd α :=
has_dvd.mk (λ a b, ∃ c, b = a * c)
-- TODO: this used to not have `c` explicit, but that seems to be important
-- for use with tactics, similar to `exists.intro`
theorem dvd.intro (c : α) (h : a * c = b) : a ∣ b :=
exists.intro c h^.symm
alias dvd.intro ← dvd_of_mul_right_eq
theorem exists_eq_mul_right_of_dvd (h : a ∣ b) : ∃ c, b = a * c := h
theorem dvd.elim {P : Prop} {a b : α} (H₁ : a ∣ b) (H₂ : ∀ c, b = a * c → P) : P :=
exists.elim H₁ H₂
local attribute [simp] mul_assoc mul_comm mul_left_comm
@[trans] theorem dvd_trans : a ∣ b → b ∣ c → a ∣ c
| ⟨d, h₁⟩ ⟨e, h₂⟩ := ⟨d * e, h₁ ▸ h₂.trans $ mul_assoc a d e⟩
alias dvd_trans ← has_dvd.dvd.trans
instance : is_trans α (∣) := ⟨λ a b c, dvd_trans⟩
@[simp] theorem dvd_mul_right (a b : α) : a ∣ a * b := dvd.intro b rfl
theorem dvd_mul_of_dvd_left (h : a ∣ b) (c : α) : a ∣ b * c :=
h.trans (dvd_mul_right b c)
alias dvd_mul_of_dvd_left ← has_dvd.dvd.mul_right
theorem dvd_of_mul_right_dvd (h : a * b ∣ c) : a ∣ c :=
(dvd_mul_right a b).trans h
section map_dvd
variables {M N : Type*} [monoid M] [monoid N]
lemma map_dvd {F : Type*} [mul_hom_class F M N] (f : F) {a b} : a ∣ b → f a ∣ f b
| ⟨c, h⟩ := ⟨f c, h.symm ▸ map_mul f a c⟩
lemma mul_hom.map_dvd (f : M →ₙ* N) {a b} : a ∣ b → f a ∣ f b := map_dvd f
lemma monoid_hom.map_dvd (f : M →* N) {a b} : a ∣ b → f a ∣ f b := map_dvd f
end map_dvd
end semigroup
section monoid
variables [monoid α]
@[refl, simp] theorem dvd_refl (a : α) : a ∣ a := dvd.intro 1 (mul_one a)
theorem dvd_rfl : ∀ {a : α}, a ∣ a := dvd_refl
instance : is_refl α (∣) := ⟨dvd_refl⟩
theorem one_dvd (a : α) : 1 ∣ a := dvd.intro a (one_mul a)
end monoid
section comm_semigroup
variables [comm_semigroup α] {a b c : α}
theorem dvd.intro_left (c : α) (h : c * a = b) : a ∣ b :=
dvd.intro _ (begin rewrite mul_comm at h, apply h end)
alias dvd.intro_left ← dvd_of_mul_left_eq
theorem exists_eq_mul_left_of_dvd (h : a ∣ b) : ∃ c, b = c * a :=
dvd.elim h (assume c, assume H1 : b = a * c, exists.intro c (eq.trans H1 (mul_comm a c)))
lemma dvd_iff_exists_eq_mul_left : a ∣ b ↔ ∃ c, b = c * a :=
⟨exists_eq_mul_left_of_dvd, by { rintro ⟨c, rfl⟩, exact ⟨c, mul_comm _ _⟩, }⟩
theorem dvd.elim_left {P : Prop} (h₁ : a ∣ b) (h₂ : ∀ c, b = c * a → P) : P :=
exists.elim (exists_eq_mul_left_of_dvd h₁) (assume c, assume h₃ : b = c * a, h₂ c h₃)
@[simp] theorem dvd_mul_left (a b : α) : a ∣ b * a := dvd.intro b (mul_comm a b)
theorem dvd_mul_of_dvd_right (h : a ∣ b) (c : α) : a ∣ c * b :=
begin rw mul_comm, exact h.mul_right _ end
alias dvd_mul_of_dvd_right ← has_dvd.dvd.mul_left
local attribute [simp] mul_assoc mul_comm mul_left_comm
theorem mul_dvd_mul : ∀ {a b c d : α}, a ∣ b → c ∣ d → a * c ∣ b * d
| a ._ c ._ ⟨e, rfl⟩ ⟨f, rfl⟩ := ⟨e * f, by simp⟩
theorem dvd_of_mul_left_dvd (h : a * b ∣ c) : b ∣ c :=
dvd.elim h (λ d ceq, dvd.intro (a * d) (by simp [ceq]))
end comm_semigroup
section comm_monoid
variables [comm_monoid α] {a b : α}
theorem mul_dvd_mul_left (a : α) {b c : α} (h : b ∣ c) : a * b ∣ a * c :=
mul_dvd_mul (dvd_refl a) h
theorem mul_dvd_mul_right (h : a ∣ b) (c : α) : a * c ∣ b * c :=
mul_dvd_mul h (dvd_refl c)
theorem pow_dvd_pow_of_dvd {a b : α} (h : a ∣ b) : ∀ n : ℕ, a ^ n ∣ b ^ n
| 0 := by rw [pow_zero, pow_zero]
| (n+1) := by { rw [pow_succ, pow_succ], exact mul_dvd_mul h (pow_dvd_pow_of_dvd n) }
end comm_monoid
|
f4bf0be8d0848bc66690f6bea4e3c06f30a526a1 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/linear_algebra/affine_space/combination.lean | 1999dfe3d6d5e636a27b5587ab578a6d0a80fe1b | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32,024 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import algebra.invertible
import algebra.indicator_function
import linear_algebra.affine_space.affine_map
import linear_algebra.affine_space.affine_subspace
import linear_algebra.finsupp
import tactic.fin_cases
/-!
# Affine combinations of points
This file defines affine combinations of points.
## Main definitions
* `weighted_vsub_of_point` is a general weighted combination of
subtractions with an explicit base point, yielding a vector.
* `weighted_vsub` uses an arbitrary choice of base point and is intended
to be used when the sum of weights is 0, in which case the result is
independent of the choice of base point.
* `affine_combination` adds the weighted combination to the arbitrary
base point, yielding a point rather than a vector, and is intended
to be used when the sum of weights is 1, in which case the result is
independent of the choice of base point.
These definitions are for sums over a `finset`; versions for a
`fintype` may be obtained using `finset.univ`, while versions for a
`finsupp` may be obtained using `finsupp.support`.
## References
* https://en.wikipedia.org/wiki/Affine_space
-/
noncomputable theory
open_locale big_operators classical affine
namespace finset
lemma univ_fin2 : (univ : finset (fin 2)) = {0, 1} :=
by { ext x, fin_cases x; simp }
variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
variables [S : affine_space V P]
include S
variables {ι : Type*} (s : finset ι)
variables {ι₂ : Type*} (s₂ : finset ι₂)
/-- A weighted sum of the results of subtracting a base point from the
given points, as a linear map on the weights. The main cases of
interest are where the sum of the weights is 0, in which case the sum
is independent of the choice of base point, and where the sum of the
weights is 1, in which case the sum added to the base point is
independent of the choice of base point. -/
def weighted_vsub_of_point (p : ι → P) (b : P) : (ι → k) →ₗ[k] V :=
∑ i in s, (linear_map.proj i : (ι → k) →ₗ[k] k).smul_right (p i -ᵥ b)
@[simp] lemma weighted_vsub_of_point_apply (w : ι → k) (p : ι → P) (b : P) :
s.weighted_vsub_of_point p b w = ∑ i in s, w i • (p i -ᵥ b) :=
by simp [weighted_vsub_of_point, linear_map.sum_apply]
/-- The weighted sum is independent of the base point when the sum of
the weights is 0. -/
lemma weighted_vsub_of_point_eq_of_sum_eq_zero (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 0)
(b₁ b₂ : P) : s.weighted_vsub_of_point p b₁ w = s.weighted_vsub_of_point p b₂ w :=
begin
apply eq_of_sub_eq_zero,
rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, ←sum_sub_distrib],
conv_lhs {
congr,
skip,
funext,
rw [←smul_sub, vsub_sub_vsub_cancel_left] },
rw [←sum_smul, h, zero_smul]
end
/-- The weighted sum, added to the base point, is independent of the
base point when the sum of the weights is 1. -/
lemma weighted_vsub_of_point_vadd_eq_of_sum_eq_one (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 1)
(b₁ b₂ : P) :
s.weighted_vsub_of_point p b₁ w +ᵥ b₁ = s.weighted_vsub_of_point p b₂ w +ᵥ b₂ :=
begin
erw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, ←@vsub_eq_zero_iff_eq V,
vadd_vsub_assoc, vsub_vadd_eq_vsub_sub, ←add_sub_assoc, add_comm, add_sub_assoc,
←sum_sub_distrib],
conv_lhs {
congr,
skip,
congr,
skip,
funext,
rw [←smul_sub, vsub_sub_vsub_cancel_left] },
rw [←sum_smul, h, one_smul, vsub_add_vsub_cancel, vsub_self]
end
/-- The weighted sum is unaffected by removing the base point, if
present, from the set of points. -/
@[simp] lemma weighted_vsub_of_point_erase (w : ι → k) (p : ι → P) (i : ι) :
(s.erase i).weighted_vsub_of_point p (p i) w = s.weighted_vsub_of_point p (p i) w :=
begin
rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply],
apply sum_erase,
rw [vsub_self, smul_zero]
end
/-- The weighted sum is unaffected by adding the base point, whether
or not present, to the set of points. -/
@[simp] lemma weighted_vsub_of_point_insert (w : ι → k) (p : ι → P) (i : ι) :
(insert i s).weighted_vsub_of_point p (p i) w = s.weighted_vsub_of_point p (p i) w :=
begin
rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply],
apply sum_insert_zero,
rw [vsub_self, smul_zero]
end
/-- The weighted sum is unaffected by changing the weights to the
corresponding indicator function and adding points to the set. -/
lemma weighted_vsub_of_point_indicator_subset (w : ι → k) (p : ι → P) (b : P) {s₁ s₂ : finset ι}
(h : s₁ ⊆ s₂) :
s₁.weighted_vsub_of_point p b w = s₂.weighted_vsub_of_point p b (set.indicator ↑s₁ w) :=
begin
rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply],
exact set.sum_indicator_subset_of_eq_zero w (λ i wi, wi • (p i -ᵥ b : V)) h (λ i, zero_smul k _)
end
/-- A weighted sum, over the image of an embedding, equals a weighted
sum with the same points and weights over the original
`finset`. -/
lemma weighted_vsub_of_point_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) (b : P) :
(s₂.map e).weighted_vsub_of_point p b w = s₂.weighted_vsub_of_point (p ∘ e) b (w ∘ e) :=
begin
simp_rw [weighted_vsub_of_point_apply],
exact finset.sum_map _ _ _
end
/-- A weighted sum of the results of subtracting a default base point
from the given points, as a linear map on the weights. This is
intended to be used when the sum of the weights is 0; that condition
is specified as a hypothesis on those lemmas that require it. -/
def weighted_vsub (p : ι → P) : (ι → k) →ₗ[k] V :=
s.weighted_vsub_of_point p (classical.choice S.nonempty)
/-- Applying `weighted_vsub` with given weights. This is for the case
where a result involving a default base point is OK (for example, when
that base point will cancel out later); a more typical use case for
`weighted_vsub` would involve selecting a preferred base point with
`weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero` and then
using `weighted_vsub_of_point_apply`. -/
lemma weighted_vsub_apply (w : ι → k) (p : ι → P) :
s.weighted_vsub p w = ∑ i in s, w i • (p i -ᵥ (classical.choice S.nonempty)) :=
by simp [weighted_vsub, linear_map.sum_apply]
/-- `weighted_vsub` gives the sum of the results of subtracting any
base point, when the sum of the weights is 0. -/
lemma weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero (w : ι → k) (p : ι → P)
(h : ∑ i in s, w i = 0) (b : P) : s.weighted_vsub p w = s.weighted_vsub_of_point p b w :=
s.weighted_vsub_of_point_eq_of_sum_eq_zero w p h _ _
/-- The `weighted_vsub` for an empty set is 0. -/
@[simp] lemma weighted_vsub_empty (w : ι → k) (p : ι → P) :
(∅ : finset ι).weighted_vsub p w = (0:V) :=
by simp [weighted_vsub_apply]
/-- The weighted sum is unaffected by changing the weights to the
corresponding indicator function and adding points to the set. -/
lemma weighted_vsub_indicator_subset (w : ι → k) (p : ι → P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) :
s₁.weighted_vsub p w = s₂.weighted_vsub p (set.indicator ↑s₁ w) :=
weighted_vsub_of_point_indicator_subset _ _ _ h
/-- A weighted subtraction, over the image of an embedding, equals a
weighted subtraction with the same points and weights over the
original `finset`. -/
lemma weighted_vsub_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) :
(s₂.map e).weighted_vsub p w = s₂.weighted_vsub (p ∘ e) (w ∘ e) :=
s₂.weighted_vsub_of_point_map _ _ _ _
/-- A weighted sum of the results of subtracting a default base point
from the given points, added to that base point, as an affine map on
the weights. This is intended to be used when the sum of the weights
is 1, in which case it is an affine combination (barycenter) of the
points with the given weights; that condition is specified as a
hypothesis on those lemmas that require it. -/
def affine_combination (p : ι → P) : (ι → k) →ᵃ[k] P :=
{ to_fun := λ w,
s.weighted_vsub_of_point p (classical.choice S.nonempty) w +ᵥ (classical.choice S.nonempty),
linear := s.weighted_vsub p,
map_vadd' := λ w₁ w₂, by simp_rw [vadd_vadd, weighted_vsub, vadd_eq_add, linear_map.map_add] }
/-- The linear map corresponding to `affine_combination` is
`weighted_vsub`. -/
@[simp] lemma affine_combination_linear (p : ι → P) :
(s.affine_combination p : (ι → k) →ᵃ[k] P).linear = s.weighted_vsub p :=
rfl
/-- Applying `affine_combination` with given weights. This is for the
case where a result involving a default base point is OK (for example,
when that base point will cancel out later); a more typical use case
for `affine_combination` would involve selecting a preferred base
point with
`affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one` and
then using `weighted_vsub_of_point_apply`. -/
lemma affine_combination_apply (w : ι → k) (p : ι → P) :
s.affine_combination p w =
s.weighted_vsub_of_point p (classical.choice S.nonempty) w +ᵥ (classical.choice S.nonempty) :=
rfl
/-- `affine_combination` gives the sum with any base point, when the
sum of the weights is 1. -/
lemma affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one (w : ι → k) (p : ι → P)
(h : ∑ i in s, w i = 1) (b : P) :
s.affine_combination p w = s.weighted_vsub_of_point p b w +ᵥ b :=
s.weighted_vsub_of_point_vadd_eq_of_sum_eq_one w p h _ _
/-- Adding a `weighted_vsub` to an `affine_combination`. -/
lemma weighted_vsub_vadd_affine_combination (w₁ w₂ : ι → k) (p : ι → P) :
s.weighted_vsub p w₁ +ᵥ s.affine_combination p w₂ = s.affine_combination p (w₁ + w₂) :=
by rw [←vadd_eq_add, affine_map.map_vadd, affine_combination_linear]
/-- Subtracting two `affine_combination`s. -/
lemma affine_combination_vsub (w₁ w₂ : ι → k) (p : ι → P) :
s.affine_combination p w₁ -ᵥ s.affine_combination p w₂ = s.weighted_vsub p (w₁ - w₂) :=
by rw [←affine_map.linear_map_vsub, affine_combination_linear, vsub_eq_sub]
/-- An `affine_combination` equals a point if that point is in the set
and has weight 1 and the other points in the set have weight 0. -/
@[simp] lemma affine_combination_of_eq_one_of_eq_zero (w : ι → k) (p : ι → P) {i : ι}
(his : i ∈ s) (hwi : w i = 1) (hw0 : ∀ i2 ∈ s, i2 ≠ i → w i2 = 0) :
s.affine_combination p w = p i :=
begin
have h1 : ∑ i in s, w i = 1 := hwi ▸ sum_eq_single i hw0 (λ h, false.elim (h his)),
rw [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p h1 (p i),
weighted_vsub_of_point_apply],
convert zero_vadd V (p i),
convert sum_eq_zero _,
intros i2 hi2,
by_cases h : i2 = i,
{ simp [h] },
{ simp [hw0 i2 hi2 h] }
end
/-- An affine combination is unaffected by changing the weights to the
corresponding indicator function and adding points to the set. -/
lemma affine_combination_indicator_subset (w : ι → k) (p : ι → P) {s₁ s₂ : finset ι}
(h : s₁ ⊆ s₂) :
s₁.affine_combination p w = s₂.affine_combination p (set.indicator ↑s₁ w) :=
by rw [affine_combination_apply, affine_combination_apply,
weighted_vsub_of_point_indicator_subset _ _ _ h]
/-- An affine combination, over the image of an embedding, equals an
affine combination with the same points and weights over the original
`finset`. -/
lemma affine_combination_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) :
(s₂.map e).affine_combination p w = s₂.affine_combination (p ∘ e) (w ∘ e) :=
by simp_rw [affine_combination_apply, weighted_vsub_of_point_map]
variables {V}
/-- Suppose an indexed family of points is given, along with a subset
of the index type. A vector can be expressed as
`weighted_vsub_of_point` using a `finset` lying within that subset and
with a given sum of weights if and only if it can be expressed as
`weighted_vsub_of_point` with that sum of weights for the
corresponding indexed family whose index type is the subtype
corresponding to that subset. -/
lemma eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype {v : V} {x : k}
{s : set ι} {p : ι → P} {b : P} :
(∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = x),
v = fs.weighted_vsub_of_point p b w) ↔
∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = x),
v = fs.weighted_vsub_of_point (λ (i : s), p i) b w :=
begin
simp_rw weighted_vsub_of_point_apply,
split,
{ rintros ⟨fs, hfs, w, rfl, rfl⟩,
use [fs.subtype s, λ i, w i, sum_subtype_of_mem _ hfs, (sum_subtype_of_mem _ hfs).symm] },
{ rintros ⟨fs, w, rfl, rfl⟩,
refine ⟨fs.map (function.embedding.subtype _), map_subtype_subset _,
λ i, if h : i ∈ s then w ⟨i, h⟩ else 0, _, _⟩;
simp }
end
variables (k)
/-- Suppose an indexed family of points is given, along with a subset
of the index type. A vector can be expressed as `weighted_vsub` using
a `finset` lying within that subset and with sum of weights 0 if and
only if it can be expressed as `weighted_vsub` with sum of weights 0
for the corresponding indexed family whose index type is the subtype
corresponding to that subset. -/
lemma eq_weighted_vsub_subset_iff_eq_weighted_vsub_subtype {v : V} {s : set ι} {p : ι → P} :
(∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = 0),
v = fs.weighted_vsub p w) ↔
∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = 0),
v = fs.weighted_vsub (λ (i : s), p i) w :=
eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype
variables (V)
/-- Suppose an indexed family of points is given, along with a subset
of the index type. A point can be expressed as an
`affine_combination` using a `finset` lying within that subset and
with sum of weights 1 if and only if it can be expressed an
`affine_combination` with sum of weights 1 for the corresponding
indexed family whose index type is the subtype corresponding to that
subset. -/
lemma eq_affine_combination_subset_iff_eq_affine_combination_subtype {p0 : P} {s : set ι}
{p : ι → P} :
(∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = 1),
p0 = fs.affine_combination p w) ↔
∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = 1),
p0 = fs.affine_combination (λ (i : s), p i) w :=
begin
simp_rw [affine_combination_apply, eq_vadd_iff_vsub_eq],
exact eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype
end
end finset
namespace finset
variables (k : Type*) {V : Type*} {P : Type*} [division_ring k] [add_comm_group V] [module k V]
variables [affine_space V P] {ι : Type*} (s : finset ι) {ι₂ : Type*} (s₂ : finset ι₂)
/-- The weights for the centroid of some points. -/
def centroid_weights : ι → k := function.const ι (card s : k) ⁻¹
/-- `centroid_weights` at any point. -/
@[simp] lemma centroid_weights_apply (i : ι) : s.centroid_weights k i = (card s : k) ⁻¹ :=
rfl
/-- `centroid_weights` equals a constant function. -/
lemma centroid_weights_eq_const :
s.centroid_weights k = function.const ι ((card s : k) ⁻¹) :=
rfl
variables {k}
/-- The weights in the centroid sum to 1, if the number of points,
converted to `k`, is not zero. -/
lemma sum_centroid_weights_eq_one_of_cast_card_ne_zero (h : (card s : k) ≠ 0) :
∑ i in s, s.centroid_weights k i = 1 :=
by simp [h]
variables (k)
/-- In the characteristic zero case, the weights in the centroid sum
to 1 if the number of points is not zero. -/
lemma sum_centroid_weights_eq_one_of_card_ne_zero [char_zero k] (h : card s ≠ 0) :
∑ i in s, s.centroid_weights k i = 1 :=
by simp [h]
/-- In the characteristic zero case, the weights in the centroid sum
to 1 if the set is nonempty. -/
lemma sum_centroid_weights_eq_one_of_nonempty [char_zero k] (h : s.nonempty) :
∑ i in s, s.centroid_weights k i = 1 :=
s.sum_centroid_weights_eq_one_of_card_ne_zero k (ne_of_gt (card_pos.2 h))
/-- In the characteristic zero case, the weights in the centroid sum
to 1 if the number of points is `n + 1`. -/
lemma sum_centroid_weights_eq_one_of_card_eq_add_one [char_zero k] {n : ℕ}
(h : card s = n + 1) : ∑ i in s, s.centroid_weights k i = 1 :=
s.sum_centroid_weights_eq_one_of_card_ne_zero k (h.symm ▸ nat.succ_ne_zero n)
include V
/-- The centroid of some points. Although defined for any `s`, this
is intended to be used in the case where the number of points,
converted to `k`, is not zero. -/
def centroid (p : ι → P) : P :=
s.affine_combination p (s.centroid_weights k)
/-- The definition of the centroid. -/
lemma centroid_def (p : ι → P) :
s.centroid k p = s.affine_combination p (s.centroid_weights k) :=
rfl
/-- The centroid of a single point. -/
@[simp] lemma centroid_singleton (p : ι → P) (i : ι) :
({i} : finset ι).centroid k p = p i :=
by simp [centroid_def, affine_combination_apply]
/-- The centroid of two points, expressed directly as adding a vector
to a point. -/
lemma centroid_insert_singleton [invertible (2 : k)] (p : ι → P) (i₁ i₂ : ι) :
({i₁, i₂} : finset ι).centroid k p = (2 ⁻¹ : k) • (p i₂ -ᵥ p i₁) +ᵥ p i₁ :=
begin
by_cases h : i₁ = i₂,
{ simp [h] },
{ have hc : (card ({i₁, i₂} : finset ι) : k) ≠ 0,
{ rw [card_insert_of_not_mem (not_mem_singleton.2 h), card_singleton],
norm_num,
exact nonzero_of_invertible _ },
rw [centroid_def,
affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one _ _ _
(sum_centroid_weights_eq_one_of_cast_card_ne_zero _ hc) (p i₁)],
simp [h],
norm_num }
end
/-- The centroid of two points indexed by `fin 2`, expressed directly
as adding a vector to the first point. -/
lemma centroid_insert_singleton_fin [invertible (2 : k)] (p : fin 2 → P) :
univ.centroid k p = (2 ⁻¹ : k) • (p 1 -ᵥ p 0) +ᵥ p 0 :=
begin
rw univ_fin2,
convert centroid_insert_singleton k p 0 1
end
/-- A centroid, over the image of an embedding, equals a centroid with
the same points and weights over the original `finset`. -/
lemma centroid_map (e : ι₂ ↪ ι) (p : ι → P) : (s₂.map e).centroid k p = s₂.centroid k (p ∘ e) :=
by simp [centroid_def, affine_combination_map, centroid_weights]
omit V
/-- `centroid_weights` gives the weights for the centroid as a
constant function, which is suitable when summing over the points
whose centroid is being taken. This function gives the weights in a
form suitable for summing over a larger set of points, as an indicator
function that is zero outside the set whose centroid is being taken.
In the case of a `fintype`, the sum may be over `univ`. -/
def centroid_weights_indicator : ι → k := set.indicator ↑s (s.centroid_weights k)
/-- The definition of `centroid_weights_indicator`. -/
lemma centroid_weights_indicator_def :
s.centroid_weights_indicator k = set.indicator ↑s (s.centroid_weights k) :=
rfl
/-- The sum of the weights for the centroid indexed by a `fintype`. -/
lemma sum_centroid_weights_indicator [fintype ι] :
∑ i, s.centroid_weights_indicator k i = ∑ i in s, s.centroid_weights k i :=
(set.sum_indicator_subset _ (subset_univ _)).symm
/-- In the characteristic zero case, the weights in the centroid
indexed by a `fintype` sum to 1 if the number of points is not
zero. -/
lemma sum_centroid_weights_indicator_eq_one_of_card_ne_zero [char_zero k] [fintype ι]
(h : card s ≠ 0) : ∑ i, s.centroid_weights_indicator k i = 1 :=
begin
rw sum_centroid_weights_indicator,
exact s.sum_centroid_weights_eq_one_of_card_ne_zero k h
end
/-- In the characteristic zero case, the weights in the centroid
indexed by a `fintype` sum to 1 if the set is nonempty. -/
lemma sum_centroid_weights_indicator_eq_one_of_nonempty [char_zero k] [fintype ι]
(h : s.nonempty) : ∑ i, s.centroid_weights_indicator k i = 1 :=
begin
rw sum_centroid_weights_indicator,
exact s.sum_centroid_weights_eq_one_of_nonempty k h
end
/-- In the characteristic zero case, the weights in the centroid
indexed by a `fintype` sum to 1 if the number of points is `n + 1`. -/
lemma sum_centroid_weights_indicator_eq_one_of_card_eq_add_one [char_zero k] [fintype ι] {n : ℕ}
(h : card s = n + 1) : ∑ i, s.centroid_weights_indicator k i = 1 :=
begin
rw sum_centroid_weights_indicator,
exact s.sum_centroid_weights_eq_one_of_card_eq_add_one k h
end
include V
/-- The centroid as an affine combination over a `fintype`. -/
lemma centroid_eq_affine_combination_fintype [fintype ι] (p : ι → P) :
s.centroid k p = univ.affine_combination p (s.centroid_weights_indicator k) :=
affine_combination_indicator_subset _ _ (subset_univ _)
/-- An indexed family of points that is injective on the given
`finset` has the same centroid as the image of that `finset`. This is
stated in terms of a set equal to the image to provide control of
definitional equality for the index type used for the centroid of the
image. -/
lemma centroid_eq_centroid_image_of_inj_on {p : ι → P} (hi : ∀ i j ∈ s, p i = p j → i = j)
{ps : set P} [fintype ps] (hps : ps = p '' ↑s) :
s.centroid k p = (univ : finset ps).centroid k (λ x, x) :=
begin
let f : p '' ↑s → ι := λ x, x.property.some,
have hf : ∀ x, f x ∈ s ∧ p (f x) = x := λ x, x.property.some_spec,
let f' : ps → ι := λ x, f ⟨x, hps ▸ x.property⟩,
have hf' : ∀ x, f' x ∈ s ∧ p (f' x) = x := λ x, hf ⟨x, hps ▸ x.property⟩,
have hf'i : function.injective f',
{ intros x y h,
rw [subtype.ext_iff, ←(hf' x).2, ←(hf' y).2, h] },
let f'e : ps ↪ ι := ⟨f', hf'i⟩,
have hu : finset.univ.map f'e = s,
{ ext x,
rw mem_map,
split,
{ rintros ⟨i, _, rfl⟩,
exact (hf' i).1 },
{ intro hx,
use [⟨p x, hps.symm ▸ set.mem_image_of_mem _ hx⟩, mem_univ _],
refine hi _ _ (hf' _).1 hx _,
rw (hf' _).2,
refl } },
rw [←hu, centroid_map],
congr' with x,
change p (f' x) = ↑x,
rw (hf' x).2
end
/-- Two indexed families of points that are injective on the given
`finset`s and with the same points in the image of those `finset`s
have the same centroid. -/
lemma centroid_eq_of_inj_on_of_image_eq {p : ι → P} (hi : ∀ i j ∈ s, p i = p j → i = j)
{p₂ : ι₂ → P} (hi₂ : ∀ i j ∈ s₂, p₂ i = p₂ j → i = j) (he : p '' ↑s = p₂ '' ↑s₂) :
s.centroid k p = s₂.centroid k p₂ :=
by rw [s.centroid_eq_centroid_image_of_inj_on k hi rfl,
s₂.centroid_eq_centroid_image_of_inj_on k hi₂ he]
end finset
section affine_space'
variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V]
[affine_space V P]
variables {ι : Type*}
include V
/-- A `weighted_vsub` with sum of weights 0 is in the `vector_span` of
an indexed family. -/
lemma weighted_vsub_mem_vector_span {s : finset ι} {w : ι → k}
(h : ∑ i in s, w i = 0) (p : ι → P) :
s.weighted_vsub p w ∈ vector_span k (set.range p) :=
begin
rcases is_empty_or_nonempty ι with hι|⟨⟨i0⟩⟩,
{ resetI, simp [finset.eq_empty_of_is_empty s] },
{ rw [vector_span_range_eq_span_range_vsub_right k p i0, ←set.image_univ,
finsupp.mem_span_image_iff_total,
finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero s w p h (p i0),
finset.weighted_vsub_of_point_apply],
let w' := set.indicator ↑s w,
have hwx : ∀ i, w' i ≠ 0 → i ∈ s := λ i, set.mem_of_indicator_ne_zero,
use [finsupp.on_finset s w' hwx, set.subset_univ _],
rw [finsupp.total_apply, finsupp.on_finset_sum hwx],
{ apply finset.sum_congr rfl,
intros i hi,
simp [w', set.indicator_apply, if_pos hi] },
{ exact λ _, zero_smul k _ } },
end
/-- An `affine_combination` with sum of weights 1 is in the
`affine_span` of an indexed family, if the underlying ring is
nontrivial. -/
lemma affine_combination_mem_affine_span [nontrivial k] {s : finset ι} {w : ι → k}
(h : ∑ i in s, w i = 1) (p : ι → P) :
s.affine_combination p w ∈ affine_span k (set.range p) :=
begin
have hnz : ∑ i in s, w i ≠ 0 := h.symm ▸ one_ne_zero,
have hn : s.nonempty := finset.nonempty_of_sum_ne_zero hnz,
cases hn with i1 hi1,
let w1 : ι → k := function.update (function.const ι 0) i1 1,
have hw1 : ∑ i in s, w1 i = 1,
{ rw [finset.sum_update_of_mem hi1, finset.sum_const_zero, add_zero] },
have hw1s : s.affine_combination p w1 = p i1 :=
s.affine_combination_of_eq_one_of_eq_zero w1 p hi1 (function.update_same _ _ _)
(λ _ _ hne, function.update_noteq hne _ _),
have hv : s.affine_combination p w -ᵥ p i1 ∈ (affine_span k (set.range p)).direction,
{ rw [direction_affine_span, ←hw1s, finset.affine_combination_vsub],
apply weighted_vsub_mem_vector_span,
simp [pi.sub_apply, h, hw1] },
rw ←vsub_vadd (s.affine_combination p w) (p i1),
exact affine_subspace.vadd_mem_of_mem_direction hv (mem_affine_span k (set.mem_range_self _))
end
variables (k) {V}
/-- A vector is in the `vector_span` of an indexed family if and only
if it is a `weighted_vsub` with sum of weights 0. -/
lemma mem_vector_span_iff_eq_weighted_vsub {v : V} {p : ι → P} :
v ∈ vector_span k (set.range p) ↔
∃ (s : finset ι) (w : ι → k) (h : ∑ i in s, w i = 0), v = s.weighted_vsub p w :=
begin
split,
{ rcases is_empty_or_nonempty ι with hι|⟨⟨i0⟩⟩, swap,
{ rw [vector_span_range_eq_span_range_vsub_right k p i0, ←set.image_univ,
finsupp.mem_span_image_iff_total],
rintros ⟨l, hl, hv⟩,
use insert i0 l.support,
set w := (l : ι → k) -
function.update (function.const ι 0 : ι → k) i0 (∑ i in l.support, l i) with hwdef,
use w,
have hw : ∑ i in insert i0 l.support, w i = 0,
{ rw hwdef,
simp_rw [pi.sub_apply, finset.sum_sub_distrib,
finset.sum_update_of_mem (finset.mem_insert_self _ _), finset.sum_const_zero,
finset.sum_insert_of_eq_zero_if_not_mem finsupp.not_mem_support_iff.1,
add_zero, sub_self] },
use hw,
have hz : w i0 • (p i0 -ᵥ p i0 : V) = 0 := (vsub_self (p i0)).symm ▸ smul_zero _,
change (λ i, w i • (p i -ᵥ p i0 : V)) i0 = 0 at hz,
rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero _ w p hw (p i0),
finset.weighted_vsub_of_point_apply, ←hv, finsupp.total_apply,
finset.sum_insert_zero hz],
change ∑ i in l.support, l i • _ = _,
congr' with i,
by_cases h : i = i0,
{ simp [h] },
{ simp [hwdef, h] } },
{ resetI,
rw [set.range_eq_empty, vector_span_empty, submodule.mem_bot],
rintro rfl,
use [∅],
simp } },
{ rintros ⟨s, w, hw, rfl⟩,
exact weighted_vsub_mem_vector_span hw p }
end
variables {k}
/-- A point in the `affine_span` of an indexed family is an
`affine_combination` with sum of weights 1. -/
lemma eq_affine_combination_of_mem_affine_span {p1 : P} {p : ι → P}
(h : p1 ∈ affine_span k (set.range p)) :
∃ (s : finset ι) (w : ι → k) (hw : ∑ i in s, w i = 1), p1 = s.affine_combination p w :=
begin
have hn : ((affine_span k (set.range p)) : set P).nonempty := ⟨p1, h⟩,
rw [affine_span_nonempty, set.range_nonempty_iff_nonempty] at hn,
cases hn with i0,
have h0 : p i0 ∈ affine_span k (set.range p) := mem_affine_span k (set.mem_range_self i0),
have hd : p1 -ᵥ p i0 ∈ (affine_span k (set.range p)).direction :=
affine_subspace.vsub_mem_direction h h0,
rw [direction_affine_span, mem_vector_span_iff_eq_weighted_vsub] at hd,
rcases hd with ⟨s, w, h, hs⟩,
let s' := insert i0 s,
let w' := set.indicator ↑s w,
have h' : ∑ i in s', w' i = 0,
{ rw [←h, set.sum_indicator_subset _ (finset.subset_insert i0 s)] },
have hs' : s'.weighted_vsub p w' = p1 -ᵥ p i0,
{ rw hs,
exact (finset.weighted_vsub_indicator_subset _ _ (finset.subset_insert i0 s)).symm },
let w0 : ι → k := function.update (function.const ι 0) i0 1,
have hw0 : ∑ i in s', w0 i = 1,
{ rw [finset.sum_update_of_mem (finset.mem_insert_self _ _), finset.sum_const_zero, add_zero] },
have hw0s : s'.affine_combination p w0 = p i0 :=
s'.affine_combination_of_eq_one_of_eq_zero w0 p
(finset.mem_insert_self _ _)
(function.update_same _ _ _)
(λ _ _ hne, function.update_noteq hne _ _),
use [s', w0 + w'],
split,
{ simp [pi.add_apply, finset.sum_add_distrib, hw0, h'] },
{ rw [add_comm, ←finset.weighted_vsub_vadd_affine_combination, hw0s, hs', vsub_vadd] }
end
variables (k V)
/-- A point is in the `affine_span` of an indexed family if and only
if it is an `affine_combination` with sum of weights 1, provided the
underlying ring is nontrivial. -/
lemma mem_affine_span_iff_eq_affine_combination [nontrivial k] {p1 : P} {p : ι → P} :
p1 ∈ affine_span k (set.range p) ↔
∃ (s : finset ι) (w : ι → k) (hw : ∑ i in s, w i = 1), p1 = s.affine_combination p w :=
begin
split,
{ exact eq_affine_combination_of_mem_affine_span },
{ rintros ⟨s, w, hw, rfl⟩,
exact affine_combination_mem_affine_span hw p }
end
end affine_space'
section division_ring
variables {k : Type*} {V : Type*} {P : Type*} [division_ring k] [add_comm_group V] [module k V]
variables [affine_space V P] {ι : Type*}
include V
open set finset
/-- The centroid lies in the affine span if the number of points,
converted to `k`, is not zero. -/
lemma centroid_mem_affine_span_of_cast_card_ne_zero {s : finset ι} (p : ι → P)
(h : (card s : k) ≠ 0) : s.centroid k p ∈ affine_span k (range p) :=
affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_cast_card_ne_zero h) p
variables (k)
/-- In the characteristic zero case, the centroid lies in the affine
span if the number of points is not zero. -/
lemma centroid_mem_affine_span_of_card_ne_zero [char_zero k] {s : finset ι} (p : ι → P)
(h : card s ≠ 0) : s.centroid k p ∈ affine_span k (range p) :=
affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_card_ne_zero k h) p
/-- In the characteristic zero case, the centroid lies in the affine
span if the set is nonempty. -/
lemma centroid_mem_affine_span_of_nonempty [char_zero k] {s : finset ι} (p : ι → P)
(h : s.nonempty) : s.centroid k p ∈ affine_span k (range p) :=
affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_nonempty k h) p
/-- In the characteristic zero case, the centroid lies in the affine
span if the number of points is `n + 1`. -/
lemma centroid_mem_affine_span_of_card_eq_add_one [char_zero k] {s : finset ι} (p : ι → P)
{n : ℕ} (h : card s = n + 1) : s.centroid k p ∈ affine_span k (range p) :=
affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_card_eq_add_one k h) p
end division_ring
namespace affine_map
variables {k : Type*} {V : Type*} (P : Type*) [comm_ring k] [add_comm_group V] [module k V]
variables [affine_space V P] {ι : Type*} (s : finset ι)
include V
-- TODO: define `affine_map.proj`, `affine_map.fst`, `affine_map.snd`
/-- A weighted sum, as an affine map on the points involved. -/
def weighted_vsub_of_point (w : ι → k) : ((ι → P) × P) →ᵃ[k] V :=
{ to_fun := λ p, s.weighted_vsub_of_point p.fst p.snd w,
linear := ∑ i in s,
w i • ((linear_map.proj i).comp (linear_map.fst _ _ _) - linear_map.snd _ _ _),
map_vadd' := begin
rintros ⟨p, b⟩ ⟨v, b'⟩,
simp [linear_map.sum_apply, finset.weighted_vsub_of_point, vsub_vadd_eq_vsub_sub,
vadd_vsub_assoc, add_sub, ← sub_add_eq_add_sub, smul_add, finset.sum_add_distrib]
end }
end affine_map
|
9ce377f9e8fc814975fec5ab8f03f8c354f918ae | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/number_theory/arithmetic_function.lean | 2ef99dfa25faa48f5799e165b8152a2e87b8c5b2 | [
"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 | 32,590 | lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import algebra.big_operators.ring
import number_theory.divisors
import algebra.squarefree
import algebra.invertible
/-!
# Arithmetic Functions and Dirichlet Convolution
This file defines arithmetic functions, which are functions from `ℕ` to a specified type that map 0
to 0. In the literature, they are often instead defined as functions from `ℕ+`. These arithmetic
functions are endowed with a multiplication, given by Dirichlet convolution, and pointwise addition,
to form the Dirichlet ring.
## Main Definitions
* `arithmetic_function R` consists of functions `f : ℕ → R` such that `f 0 = 0`.
* An arithmetic function `f` `is_multiplicative` when `x.coprime y → f (x * y) = f x * f y`.
* The pointwise operations `pmul` and `ppow` differ from the multiplication
and power instances on `arithmetic_function R`, which use Dirichlet multiplication.
* `ζ` is the arithmetic function such that `ζ x = 1` for `0 < x`.
* `σ k` is the arithmetic function such that `σ k x = ∑ y in divisors x, y ^ k` for `0 < x`.
* `pow k` is the arithmetic function such that `pow k x = x ^ k` for `0 < x`.
* `id` is the identity arithmetic function on `ℕ`.
* `ω n` is the number of distinct prime factors of `n`.
* `Ω n` is the number of prime factors of `n` counted with multiplicity.
* `μ` is the Möbius function.
## Main Results
* Several forms of Möbius inversion:
* `sum_eq_iff_sum_mul_moebius_eq` for functions to a `comm_ring`
* `sum_eq_iff_sum_smul_moebius_eq` for functions to an `add_comm_group`
* `prod_eq_iff_prod_pow_moebius_eq` for functions to a `comm_group`
* `prod_eq_iff_prod_pow_moebius_eq_of_nonzero` for functions to a `comm_group_with_zero`
## Notation
The arithmetic functions `ζ` and `σ` have Greek letter names, which are localized notation in
the namespace `arithmetic_function`.
## Tags
arithmetic functions, dirichlet convolution, divisors
-/
open finset
open_locale big_operators
namespace nat
variable (R : Type*)
/-- An arithmetic function is a function from `ℕ` that maps 0 to 0. In the literature, they are
often instead defined as functions from `ℕ+`. Multiplication on `arithmetic_functions` is by
Dirichlet convolution. -/
@[derive [has_zero, inhabited]]
def arithmetic_function [has_zero R] := zero_hom ℕ R
variable {R}
namespace arithmetic_function
section has_zero
variable [has_zero R]
instance : has_coe_to_fun (arithmetic_function R) (λ _, ℕ → R) := zero_hom.has_coe_to_fun
@[simp] lemma to_fun_eq (f : arithmetic_function R) : f.to_fun = f := rfl
@[simp]
lemma map_zero {f : arithmetic_function R} : f 0 = 0 :=
zero_hom.map_zero' f
theorem coe_inj {f g : arithmetic_function R} : (f : ℕ → R) = g ↔ f = g :=
⟨λ h, zero_hom.coe_inj h, λ h, h ▸ rfl⟩
@[simp]
lemma zero_apply {x : ℕ} : (0 : arithmetic_function R) x = 0 :=
zero_hom.zero_apply x
@[ext] theorem ext ⦃f g : arithmetic_function R⦄ (h : ∀ x, f x = g x) : f = g :=
zero_hom.ext h
theorem ext_iff {f g : arithmetic_function R} : f = g ↔ ∀ x, f x = g x :=
zero_hom.ext_iff
section has_one
variable [has_one R]
instance : has_one (arithmetic_function R) := ⟨⟨λ x, ite (x = 1) 1 0, rfl⟩⟩
@[simp]
lemma one_one : (1 : arithmetic_function R) 1 = 1 := rfl
@[simp]
lemma one_apply_ne {x : ℕ} (h : x ≠ 1) : (1 : arithmetic_function R) x = 0 := if_neg h
end has_one
end has_zero
instance nat_coe [has_zero R] [has_one R] [has_add R] :
has_coe (arithmetic_function ℕ) (arithmetic_function R) :=
⟨λ f, ⟨↑(f : ℕ → ℕ), by { transitivity ↑(f 0), refl, simp }⟩⟩
@[simp]
lemma nat_coe_nat (f : arithmetic_function ℕ) :
(↑f : arithmetic_function ℕ) = f :=
ext $ λ _, cast_id _
@[simp]
lemma nat_coe_apply [has_zero R] [has_one R] [has_add R] {f : arithmetic_function ℕ} {x : ℕ} :
(f : arithmetic_function R) x = f x := rfl
instance int_coe [has_zero R] [has_one R] [has_add R] [has_neg R] :
has_coe (arithmetic_function ℤ) (arithmetic_function R) :=
⟨λ f, ⟨↑(f : ℕ → ℤ), by { transitivity ↑(f 0), refl, simp }⟩⟩
@[simp]
lemma int_coe_int (f : arithmetic_function ℤ) :
(↑f : arithmetic_function ℤ) = f :=
ext $ λ _, int.cast_id _
@[simp]
lemma int_coe_apply [has_zero R] [has_one R] [has_add R] [has_neg R]
{f : arithmetic_function ℤ} {x : ℕ} :
(f : arithmetic_function R) x = f x := rfl
@[simp]
lemma coe_coe [has_zero R] [has_one R] [has_add R] [has_neg R] {f : arithmetic_function ℕ} :
((f : arithmetic_function ℤ) : arithmetic_function R) = f :=
by { ext, simp, }
section add_monoid
variable [add_monoid R]
instance : has_add (arithmetic_function R) := ⟨λ f g, ⟨λ n, f n + g n, by simp⟩⟩
@[simp]
lemma add_apply {f g : arithmetic_function R} {n : ℕ} : (f + g) n = f n + g n := rfl
instance : add_monoid (arithmetic_function R) :=
{ add_assoc := λ _ _ _, ext (λ _, add_assoc _ _ _),
zero_add := λ _, ext (λ _, zero_add _),
add_zero := λ _, ext (λ _, add_zero _),
.. arithmetic_function.has_zero R,
.. arithmetic_function.has_add }
end add_monoid
instance [add_comm_monoid R] : add_comm_monoid (arithmetic_function R) :=
{ add_comm := λ _ _, ext (λ _, add_comm _ _),
.. arithmetic_function.add_monoid }
instance [add_group R] : add_group (arithmetic_function R) :=
{ neg := λ f, ⟨λ n, - f n, by simp⟩,
add_left_neg := λ _, ext (λ _, add_left_neg _),
.. arithmetic_function.add_monoid }
instance [add_comm_group R] : add_comm_group (arithmetic_function R) :=
{ .. arithmetic_function.add_comm_monoid,
.. arithmetic_function.add_group }
section has_scalar
variables {M : Type*} [has_zero R] [add_comm_monoid M] [has_scalar R M]
/-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function
such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/
instance : has_scalar (arithmetic_function R) (arithmetic_function M) :=
⟨λ f g, ⟨λ n, ∑ x in divisors_antidiagonal n, f x.fst • g x.snd, by simp⟩⟩
@[simp]
lemma smul_apply {f : arithmetic_function R} {g : arithmetic_function M} {n : ℕ} :
(f • g) n = ∑ x in divisors_antidiagonal n, f x.fst • g x.snd := rfl
end has_scalar
/-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function
such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/
instance [semiring R] : has_mul (arithmetic_function R) := ⟨(•)⟩
@[simp]
lemma mul_apply [semiring R] {f g : arithmetic_function R} {n : ℕ} :
(f * g) n = ∑ x in divisors_antidiagonal n, f x.fst * g x.snd := rfl
section module
variables {M : Type*} [semiring R] [add_comm_monoid M] [module R M]
lemma mul_smul' (f g : arithmetic_function R) (h : arithmetic_function M) :
(f * g) • h = f • g • h :=
begin
ext n,
simp only [mul_apply, smul_apply, sum_smul, mul_smul, smul_sum, finset.sum_sigma'],
apply finset.sum_bij,
swap 5,
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l*j), (l, j)⟩ },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H,
simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢,
rcases H with ⟨⟨rfl, n0⟩, rfl, i0⟩,
refine ⟨⟨(mul_assoc _ _ _).symm, n0⟩, rfl, _⟩,
rw mul_ne_zero_iff at *,
exact ⟨i0.2, n0.2⟩, },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [mul_assoc] },
{ rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂,
simp only [finset.mem_sigma, mem_divisors_antidiagonal,
and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢,
rintros rfl h2 rfl rfl,
exact ⟨⟨eq.trans H₁.2.1.symm H₂.2.1, rfl⟩, rfl, rfl⟩ },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i*k, l), (i, k)⟩, _, _⟩,
{ simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢,
rcases H with ⟨⟨rfl, n0⟩, rfl, j0⟩,
refine ⟨⟨mul_assoc _ _ _, n0⟩, rfl, _⟩,
rw mul_ne_zero_iff at *,
exact ⟨n0.1, j0.1⟩ },
{ simp only [true_and, mem_divisors_antidiagonal, and_true, prod.mk.inj_iff, eq_self_iff_true,
ne.def, mem_sigma, heq_iff_eq] at H ⊢,
rw H.2.1 } }
end
lemma one_smul' (b : arithmetic_function M) :
(1 : arithmetic_function R) • b = b :=
begin
ext,
rw smul_apply,
by_cases x0 : x = 0, {simp [x0]},
have h : {(1,x)} ⊆ divisors_antidiagonal x := by simp [x0],
rw ← sum_subset h, {simp},
intros y ymem ynmem,
have y1ne : y.fst ≠ 1,
{ intro con,
simp only [con, mem_divisors_antidiagonal, one_mul, ne.def] at ymem,
simp only [mem_singleton, prod.ext_iff] at ynmem,
tauto },
simp [y1ne],
end
end module
section semiring
variable [semiring R]
instance : monoid (arithmetic_function R) :=
{ one_mul := one_smul',
mul_one := λ f,
begin
ext,
rw mul_apply,
by_cases x0 : x = 0, {simp [x0]},
have h : {(x,1)} ⊆ divisors_antidiagonal x := by simp [x0],
rw ← sum_subset h, {simp},
intros y ymem ynmem,
have y2ne : y.snd ≠ 1,
{ intro con,
simp only [con, mem_divisors_antidiagonal, mul_one, ne.def] at ymem,
simp only [mem_singleton, prod.ext_iff] at ynmem,
tauto },
simp [y2ne],
end,
mul_assoc := mul_smul',
.. arithmetic_function.has_one,
.. arithmetic_function.has_mul }
instance : semiring (arithmetic_function R) :=
{ zero_mul := λ f, by { ext, simp only [mul_apply, zero_mul, sum_const_zero, zero_apply] },
mul_zero := λ f, by { ext, simp only [mul_apply, sum_const_zero, mul_zero, zero_apply] },
left_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, mul_add, mul_apply, add_apply] },
right_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, add_mul, mul_apply, add_apply] },
.. arithmetic_function.has_zero R,
.. arithmetic_function.has_mul,
.. arithmetic_function.has_add,
.. arithmetic_function.add_comm_monoid,
.. arithmetic_function.monoid }
end semiring
instance [comm_semiring R] : comm_semiring (arithmetic_function R) :=
{ mul_comm := λ f g, by { ext,
rw [mul_apply, ← map_swap_divisors_antidiagonal, sum_map],
simp [mul_comm] },
.. arithmetic_function.semiring }
instance [comm_ring R] : comm_ring (arithmetic_function R) :=
{ .. arithmetic_function.add_comm_group,
.. arithmetic_function.comm_semiring }
instance {M : Type*} [semiring R] [add_comm_monoid M] [module R M] :
module (arithmetic_function R) (arithmetic_function M) :=
{ one_smul := one_smul',
mul_smul := mul_smul',
smul_add := λ r x y, by { ext, simp only [sum_add_distrib, smul_add, smul_apply, add_apply] },
smul_zero := λ r, by { ext, simp only [smul_apply, sum_const_zero, smul_zero, zero_apply] },
add_smul := λ r s x, by { ext, simp only [add_smul, sum_add_distrib, smul_apply, add_apply] },
zero_smul := λ r, by { ext, simp only [smul_apply, sum_const_zero, zero_smul, zero_apply] }, }
section zeta
/-- `ζ 0 = 0`, otherwise `ζ x = 1`. The Dirichlet Series is the Riemann ζ. -/
def zeta : arithmetic_function ℕ :=
⟨λ x, ite (x = 0) 0 1, rfl⟩
localized "notation `ζ` := zeta" in arithmetic_function
@[simp]
lemma zeta_apply {x : ℕ} : ζ x = if (x = 0) then 0 else 1 := rfl
lemma zeta_apply_ne {x : ℕ} (h : x ≠ 0) : ζ x = 1 := if_neg h
@[simp]
theorem coe_zeta_mul_apply [semiring R] {f : arithmetic_function R} {x : ℕ} :
(↑ζ * f) x = ∑ i in divisors x, f i :=
begin
rw mul_apply,
transitivity ∑ i in divisors_antidiagonal x, f i.snd,
{ apply sum_congr rfl,
intros i hi,
rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩,
rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_mul] },
{ apply sum_bij (λ i h, prod.snd i),
{ rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] },
{ rintros ⟨a, b⟩ h, refl },
{ rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h,
dsimp at h,
rw h at *,
rw mem_divisors_antidiagonal at *,
ext, swap, {refl},
simp only [prod.fst, prod.snd] at *,
apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm),
rcases h1 with ⟨rfl, h⟩,
apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) },
{ intros a ha,
rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩,
use (b, a),
simp [ne0, mul_comm] } }
end
theorem coe_zeta_smul_apply {M : Type*} [comm_ring R] [add_comm_group M] [module R M]
{f : arithmetic_function M} {x : ℕ} :
((↑ζ : arithmetic_function R) • f) x = ∑ i in divisors x, f i :=
begin
rw smul_apply,
transitivity ∑ i in divisors_antidiagonal x, f i.snd,
{ apply sum_congr rfl,
intros i hi,
rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩,
rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_smul] },
{ apply sum_bij (λ i h, prod.snd i),
{ rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] },
{ rintros ⟨a, b⟩ h, refl },
{ rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h,
dsimp at h,
rw h at *,
rw mem_divisors_antidiagonal at *,
ext, swap, {refl},
simp only [prod.fst, prod.snd] at *,
apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm),
rcases h1 with ⟨rfl, h⟩,
apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) },
{ intros a ha,
rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩,
use (b, a),
simp [ne0, mul_comm] } }
end
@[simp]
theorem coe_mul_zeta_apply [semiring R] {f : arithmetic_function R} {x : ℕ} :
(f * ζ) x = ∑ i in divisors x, f i :=
begin
apply opposite.op_injective,
rw [op_sum],
convert @coe_zeta_mul_apply Rᵒᵖ _ { to_fun := opposite.op ∘ f, map_zero' := by simp} x,
rw [mul_apply, mul_apply, op_sum],
conv_lhs { rw ← map_swap_divisors_antidiagonal, },
rw sum_map,
apply sum_congr rfl,
intros y hy,
by_cases h1 : y.fst = 0,
{ simp [function.comp_apply, h1] },
{ simp only [h1, mul_one, one_mul, prod.fst_swap, function.embedding.coe_fn_mk, prod.snd_swap,
if_false, zeta_apply, zero_hom.coe_mk, nat_coe_apply, cast_one] }
end
theorem zeta_mul_apply {f : arithmetic_function ℕ} {x : ℕ} :
(ζ * f) x = ∑ i in divisors x, f i :=
by rw [← nat_coe_nat ζ, coe_zeta_mul_apply]
theorem mul_zeta_apply {f : arithmetic_function ℕ} {x : ℕ} :
(f * ζ) x = ∑ i in divisors x, f i :=
by rw [← nat_coe_nat ζ, coe_mul_zeta_apply]
end zeta
open_locale arithmetic_function
section pmul
/-- This is the pointwise product of `arithmetic_function`s. -/
def pmul [mul_zero_class R] (f g : arithmetic_function R) :
arithmetic_function R :=
⟨λ x, f x * g x, by simp⟩
@[simp]
lemma pmul_apply [mul_zero_class R] {f g : arithmetic_function R} {x : ℕ} :
f.pmul g x = f x * g x := rfl
lemma pmul_comm [comm_monoid_with_zero R] (f g : arithmetic_function R) :
f.pmul g = g.pmul f :=
by { ext, simp [mul_comm] }
variable [semiring R]
@[simp]
lemma pmul_zeta (f : arithmetic_function R) : f.pmul ↑ζ = f :=
begin
ext x,
cases x;
simp [nat.succ_ne_zero],
end
@[simp]
lemma zeta_pmul (f : arithmetic_function R) : (ζ : arithmetic_function R).pmul f = f :=
begin
ext x,
cases x;
simp [nat.succ_ne_zero],
end
/-- This is the pointwise power of `arithmetic_function`s. -/
def ppow (f : arithmetic_function R) (k : ℕ) :
arithmetic_function R :=
if h0 : k = 0 then ζ else ⟨λ x, (f x) ^ k,
by { rw [map_zero], exact zero_pow (nat.pos_of_ne_zero h0) }⟩
@[simp]
lemma ppow_zero {f : arithmetic_function R} : f.ppow 0 = ζ :=
by rw [ppow, dif_pos rfl]
@[simp]
lemma ppow_apply {f : arithmetic_function R} {k x : ℕ} (kpos : 0 < k) :
f.ppow k x = (f x) ^ k :=
by { rw [ppow, dif_neg (ne_of_gt kpos)], refl }
lemma ppow_succ {f : arithmetic_function R} {k : ℕ} :
f.ppow (k + 1) = f.pmul (f.ppow k) :=
begin
ext x,
rw [ppow_apply (nat.succ_pos k), pow_succ],
induction k; simp,
end
lemma ppow_succ' {f : arithmetic_function R} {k : ℕ} {kpos : 0 < k} :
f.ppow (k + 1) = (f.ppow k).pmul f :=
begin
ext x,
rw [ppow_apply (nat.succ_pos k), pow_succ'],
induction k; simp,
end
end pmul
/-- Multiplicative functions -/
def is_multiplicative [monoid_with_zero R] (f : arithmetic_function R) : Prop :=
f 1 = 1 ∧ (∀ {m n : ℕ}, m.coprime n → f (m * n) = f m * f n)
namespace is_multiplicative
section monoid_with_zero
variable [monoid_with_zero R]
@[simp]
lemma map_one {f : arithmetic_function R} (h : f.is_multiplicative) : f 1 = 1 :=
h.1
@[simp]
lemma map_mul_of_coprime {f : arithmetic_function R} (hf : f.is_multiplicative)
{m n : ℕ} (h : m.coprime n) : f (m * n) = f m * f n :=
hf.2 h
end monoid_with_zero
lemma nat_cast {f : arithmetic_function ℕ} [semiring R] (h : f.is_multiplicative) :
is_multiplicative (f : arithmetic_function R) :=
⟨by simp [h], λ m n cop, by simp [cop, h]⟩
lemma int_cast {f : arithmetic_function ℤ} [ring R] (h : f.is_multiplicative) :
is_multiplicative (f : arithmetic_function R) :=
⟨by simp [h], λ m n cop, by simp [cop, h]⟩
lemma mul [comm_semiring R] {f g : arithmetic_function R}
(hf : f.is_multiplicative) (hg : g.is_multiplicative) :
is_multiplicative (f * g) :=
⟨by { simp [hf, hg], }, begin
simp only [mul_apply],
intros m n cop,
rw sum_mul_sum,
symmetry,
apply sum_bij (λ (x : (ℕ × ℕ) × ℕ × ℕ) h, (x.1.1 * x.2.1, x.1.2 * x.2.2)),
{ rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h,
rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩,
simp only [mem_divisors_antidiagonal, nat.mul_eq_zero, ne.def],
split, {ring},
rw nat.mul_eq_zero at *,
apply not_or ha hb },
{ rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h,
rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩,
dsimp only,
rw [hf.map_mul_of_coprime cop.coprime_mul_right.coprime_mul_right_right,
hg.map_mul_of_coprime cop.coprime_mul_left.coprime_mul_left_right],
ring, },
{ rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ ⟨⟨c1, c2⟩, ⟨d1, d2⟩⟩ hab hcd h,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hab,
rcases hab with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hcd,
simp only [prod.mk.inj_iff] at h,
ext; dsimp only,
{ transitivity nat.gcd (a1 * a2) (a1 * b1),
{ rw [nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] },
{ rw [← hcd.1.1, ← hcd.2.1] at cop,
rw [← hcd.1.1, h.1, nat.gcd_mul_left,
cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] } },
{ transitivity nat.gcd (a1 * a2) (a2 * b2),
{ rw [mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one,
mul_one] },
{ rw [← hcd.1.1, ← hcd.2.1] at cop,
rw [← hcd.1.1, h.2, mul_comm, nat.gcd_mul_left,
cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] } },
{ transitivity nat.gcd (b1 * b2) (a1 * b1),
{ rw [mul_comm, nat.gcd_mul_right,
cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, one_mul] },
{ rw [← hcd.1.1, ← hcd.2.1] at cop,
rw [← hcd.2.1, h.1, mul_comm c1 d1, nat.gcd_mul_left,
cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, mul_one] } },
{ transitivity nat.gcd (b1 * b2) (a2 * b2),
{ rw [nat.gcd_mul_right,
cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] },
{ rw [← hcd.1.1, ← hcd.2.1] at cop,
rw [← hcd.2.1, h.2, nat.gcd_mul_right,
cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] } } },
{ rintros ⟨b1, b2⟩ h,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h,
use ((b1.gcd m, b2.gcd m), (b1.gcd n, b2.gcd n)),
simp only [exists_prop, prod.mk.inj_iff, ne.def, mem_product, mem_divisors_antidiagonal],
rw [← cop.gcd_mul _, ← cop.gcd_mul _, ← h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop h.1,
nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop.symm _],
{ rw [nat.mul_eq_zero, decidable.not_or_iff_and_not] at h, simp [h.2.1, h.2.2] },
rw [mul_comm n m, h.1] }
end⟩
lemma pmul [comm_semiring R] {f g : arithmetic_function R}
(hf : f.is_multiplicative) (hg : g.is_multiplicative) :
is_multiplicative (f.pmul g) :=
⟨by { simp [hf, hg], }, λ m n cop, begin
simp only [pmul_apply, hf.map_mul_of_coprime cop, hg.map_mul_of_coprime cop],
ring,
end⟩
end is_multiplicative
section special_functions
/-- The identity on `ℕ` as an `arithmetic_function`. -/
def id : arithmetic_function ℕ := ⟨id, rfl⟩
@[simp]
lemma id_apply {x : ℕ} : id x = x := rfl
/-- `pow k n = n ^ k`, except `pow 0 0 = 0`. -/
def pow (k : ℕ) : arithmetic_function ℕ := id.ppow k
@[simp]
lemma pow_apply {k n : ℕ} : pow k n = if (k = 0 ∧ n = 0) then 0 else n ^ k :=
begin
cases k,
{ simp [pow] },
simp [pow, (ne_of_lt (nat.succ_pos k)).symm],
end
/-- `σ k n` is the sum of the `k`th powers of the divisors of `n` -/
def sigma (k : ℕ) : arithmetic_function ℕ :=
⟨λ n, ∑ d in divisors n, d ^ k, by simp⟩
localized "notation `σ` := sigma" in arithmetic_function
@[simp]
lemma sigma_apply {k n : ℕ} : σ k n = ∑ d in divisors n, d ^ k := rfl
lemma sigma_one_apply {n : ℕ} : σ 1 n = ∑ d in divisors n, d := by simp
lemma zeta_mul_pow_eq_sigma {k : ℕ} : ζ * pow k = σ k :=
begin
ext,
rw [sigma, zeta_mul_apply],
apply sum_congr rfl,
intros x hx,
rw [pow_apply, if_neg (not_and_of_not_right _ _)],
contrapose! hx,
simp [hx],
end
lemma is_multiplicative_zeta : is_multiplicative ζ :=
⟨by simp, λ m n cop, begin
cases m, {simp},
cases n, {simp},
simp [nat.succ_ne_zero]
end⟩
lemma is_multiplicative_id : is_multiplicative arithmetic_function.id :=
⟨rfl, λ _ _ _, rfl⟩
lemma is_multiplicative.ppow [comm_semiring R] {f : arithmetic_function R}
(hf : f.is_multiplicative) {k : ℕ} :
is_multiplicative (f.ppow k) :=
begin
induction k with k hi,
{ exact is_multiplicative_zeta.nat_cast },
{ rw ppow_succ,
apply hf.pmul hi },
end
lemma is_multiplicative_pow {k : ℕ} : is_multiplicative (pow k) :=
is_multiplicative_id.ppow
lemma is_multiplicative_sigma {k : ℕ} :
is_multiplicative (sigma k) :=
begin
rw [← zeta_mul_pow_eq_sigma],
apply ((is_multiplicative_zeta).mul is_multiplicative_pow)
end
/-- `Ω n` is the number of prime factors of `n`. -/
def card_factors : arithmetic_function ℕ :=
⟨λ n, n.factors.length, by simp⟩
localized "notation `Ω` := card_factors" in arithmetic_function
lemma card_factors_apply {n : ℕ} :
Ω n = n.factors.length := rfl
@[simp]
lemma card_factors_one : Ω 1 = 0 := by simp [card_factors]
lemma card_factors_eq_one_iff_prime {n : ℕ} :
Ω n = 1 ↔ n.prime :=
begin
refine ⟨λ h, _, λ h, list.length_eq_one.2 ⟨n, factors_prime h⟩⟩,
cases n,
{ contrapose! h,
simp },
rcases list.length_eq_one.1 h with ⟨x, hx⟩,
rw [← prod_factors n.succ_pos, hx, list.prod_singleton],
apply prime_of_mem_factors,
rw [hx, list.mem_singleton]
end
lemma card_factors_mul {m n : ℕ} (m0 : m ≠ 0) (n0 : n ≠ 0) :
Ω (m * n) = Ω m + Ω n :=
by rw [card_factors_apply, card_factors_apply, card_factors_apply, ← multiset.coe_card,
← factors_eq, unique_factorization_monoid.normalized_factors_mul m0 n0, factors_eq, factors_eq,
multiset.card_add, multiset.coe_card, multiset.coe_card]
lemma card_factors_multiset_prod {s : multiset ℕ} (h0 : s.prod ≠ 0) :
Ω s.prod = (multiset.map Ω s).sum :=
begin
revert h0,
apply s.induction_on, by simp,
intros a t h h0,
rw [multiset.prod_cons, mul_ne_zero_iff] at h0,
simp [h0, card_factors_mul, h],
end
/-- `ω n` is the number of distinct prime factors of `n`. -/
def card_distinct_factors : arithmetic_function ℕ :=
⟨λ n, n.factors.erase_dup.length, by simp⟩
localized "notation `ω` := card_distinct_factors" in arithmetic_function
lemma card_distinct_factors_zero : ω 0 = 0 := by simp
lemma card_distinct_factors_apply {n : ℕ} :
ω n = n.factors.erase_dup.length := rfl
lemma card_distinct_factors_eq_card_factors_iff_squarefree {n : ℕ} (h0 : n ≠ 0) :
ω n = Ω n ↔ squarefree n :=
begin
rw [squarefree_iff_nodup_factors h0, card_distinct_factors_apply],
split; intro h,
{ rw ← list.eq_of_sublist_of_length_eq n.factors.erase_dup_sublist h,
apply list.nodup_erase_dup },
{ rw h.erase_dup,
refl }
end
/-- `μ` is the Möbius function. If `n` is squarefree with an even number of distinct prime factors,
`μ n = 1`. If `n` is squarefree with an odd number of distinct prime factors, `μ n = -1`.
If `n` is not squarefree, `μ n = 0`. -/
def moebius : arithmetic_function ℤ :=
⟨λ n, if squarefree n then (-1) ^ (card_factors n) else 0, by simp⟩
localized "notation `μ` := moebius" in arithmetic_function
@[simp]
lemma moebius_apply_of_squarefree {n : ℕ} (h : squarefree n): μ n = (-1) ^ (card_factors n) :=
if_pos h
@[simp]
lemma moebius_eq_zero_of_not_squarefree {n : ℕ} (h : ¬ squarefree n): μ n = 0 := if_neg h
lemma moebius_ne_zero_iff_squarefree {n : ℕ} : μ n ≠ 0 ↔ squarefree n :=
begin
split; intro h,
{ contrapose! h,
simp [h] },
{ simp [h, pow_ne_zero] }
end
lemma moebius_ne_zero_iff_eq_or {n : ℕ} : μ n ≠ 0 ↔ μ n = 1 ∨ μ n = -1 :=
begin
split; intro h,
{ rw moebius_ne_zero_iff_squarefree at h,
rw moebius_apply_of_squarefree h,
apply neg_one_pow_eq_or },
{ rcases h with h | h; simp [h] }
end
open unique_factorization_monoid
@[simp] lemma coe_moebius_mul_coe_zeta [comm_ring R] : (μ * ζ : arithmetic_function R) = 1 :=
begin
ext x,
cases x,
{ simp only [divisors_zero, sum_empty, ne.def, not_false_iff, coe_mul_zeta_apply,
zero_ne_one, one_apply_ne] },
cases x,
{ simp only [moebius_apply_of_squarefree, card_factors_one, squarefree_one, divisors_one,
int.cast_one, sum_singleton, coe_mul_zeta_apply, one_one, int_coe_apply, pow_zero] },
rw [coe_mul_zeta_apply, one_apply_ne (ne_of_gt (succ_lt_succ (nat.succ_pos _)))],
simp_rw [int_coe_apply],
rw [←int.cast_sum, ← sum_filter_ne_zero],
convert int.cast_zero,
simp only [moebius_ne_zero_iff_squarefree],
suffices :
∑ (y : finset ℕ) in
(unique_factorization_monoid.normalized_factors x.succ.succ).to_finset.powerset,
ite (squarefree y.val.prod) ((-1:ℤ) ^ Ω y.val.prod) 0 = 0,
{ have h : ∑ i in _, ite (squarefree i) ((-1:ℤ) ^ Ω i) 0 = _ :=
(sum_divisors_filter_squarefree (nat.succ_ne_zero _)),
exact (eq.trans (by congr') h).trans this },
apply eq.trans (sum_congr rfl _) (sum_powerset_neg_one_pow_card_of_nonempty _),
{ intros y hy,
rw [finset.mem_powerset, ← finset.val_le_iff, multiset.to_finset_val] at hy,
have h : unique_factorization_monoid.normalized_factors y.val.prod = y.val,
{ apply factors_multiset_prod_of_irreducible,
intros z hz,
apply irreducible_of_normalized_factor _ (multiset.subset_of_le
(le_trans hy (multiset.erase_dup_le _)) hz) },
rw [if_pos],
{ rw [card_factors_apply, ← multiset.coe_card, ← factors_eq, h, finset.card] },
rw [unique_factorization_monoid.squarefree_iff_nodup_normalized_factors, h],
{ apply y.nodup },
rw [ne.def, multiset.prod_eq_zero_iff],
intro con,
rw ← h at con,
exact not_irreducible_zero (irreducible_of_normalized_factor 0 con) },
{ rw finset.nonempty,
rcases wf_dvd_monoid.exists_irreducible_factor _ (nat.succ_ne_zero _) with ⟨i, hi⟩,
{ rcases exists_mem_normalized_factors_of_dvd (nat.succ_ne_zero _) hi.1 hi.2 with ⟨j, hj, hj2⟩,
use j,
apply multiset.mem_to_finset.2 hj },
rw nat.is_unit_iff,
norm_num },
end
@[simp] lemma coe_zeta_mul_coe_moebius [comm_ring R] : (ζ * μ : arithmetic_function R) = 1 :=
by rw [mul_comm, coe_moebius_mul_coe_zeta]
@[simp] lemma moebius_mul_coe_zeta : (μ * ζ : arithmetic_function ℤ) = 1 :=
by rw [← int_coe_int μ, coe_moebius_mul_coe_zeta]
@[simp] lemma coe_zeta_mul_moebius : (ζ * μ : arithmetic_function ℤ) = 1 :=
by rw [← int_coe_int μ, coe_zeta_mul_coe_moebius]
section comm_ring
variable [comm_ring R]
instance : invertible (ζ : arithmetic_function R) :=
{ inv_of := μ,
inv_of_mul_self := coe_moebius_mul_coe_zeta,
mul_inv_of_self := coe_zeta_mul_coe_moebius}
/-- A unit in `arithmetic_function R` that evaluates to `ζ`, with inverse `μ`. -/
def zeta_unit : units (arithmetic_function R) :=
⟨ζ, μ, coe_zeta_mul_coe_moebius, coe_moebius_mul_coe_zeta⟩
@[simp]
lemma coe_zeta_unit :
((zeta_unit : units (arithmetic_function R)) : arithmetic_function R) = ζ := rfl
@[simp]
lemma inv_zeta_unit :
((zeta_unit⁻¹ : units (arithmetic_function R)) : arithmetic_function R) = μ := rfl
end comm_ring
/-- Möbius inversion for functions to an `add_comm_group`. -/
theorem sum_eq_iff_sum_smul_moebius_eq
[add_comm_group R] {f g : ℕ → R} :
(∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔
∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, μ x.fst • g x.snd = f n :=
begin
let f' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else f x, if_pos rfl⟩,
let g' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else g x, if_pos rfl⟩,
transitivity (ζ : arithmetic_function ℤ) • f' = g',
{ rw ext_iff,
apply forall_congr,
intro n,
cases n, { simp },
rw coe_zeta_smul_apply,
simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', if_false, zero_hom.coe_mk],
rw sum_congr rfl (λ x hx, _),
rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors hx))) },
transitivity μ • g' = f',
{ split; intro h,
{ rw [← h, ← mul_smul, moebius_mul_coe_zeta, one_smul] },
{ rw [← h, ← mul_smul, coe_zeta_mul_moebius, one_smul] } },
{ rw ext_iff,
apply forall_congr,
intro n,
cases n, { simp },
simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', smul_apply,
if_false, zero_hom.coe_mk],
rw sum_congr rfl (λ x hx, _),
rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors (snd_mem_divisors_of_mem_antidiagonal hx)))) },
end
/-- Möbius inversion for functions to a `comm_ring`. -/
theorem sum_eq_iff_sum_mul_moebius_eq [comm_ring R] {f g : ℕ → R} :
(∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔
∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, (μ x.fst : R) * g x.snd = f n :=
begin
rw sum_eq_iff_sum_smul_moebius_eq,
apply forall_congr,
intro a,
apply imp_congr (iff.refl _) (eq.congr_left (sum_congr rfl (λ x hx, _))),
rw [zsmul_eq_mul],
end
/-- Möbius inversion for functions to a `comm_group`. -/
theorem prod_eq_iff_prod_pow_moebius_eq [comm_group R] {f g : ℕ → R} :
(∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔
∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n :=
@sum_eq_iff_sum_smul_moebius_eq (additive R) _ _ _
/-- Möbius inversion for functions to a `comm_group_with_zero`. -/
theorem prod_eq_iff_prod_pow_moebius_eq_of_nonzero [comm_group_with_zero R] {f g : ℕ → R}
(hf : ∀ (n : ℕ), 0 < n → f n ≠ 0) (hg : ∀ (n : ℕ), 0 < n → g n ≠ 0) :
(∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔
∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n :=
begin
refine iff.trans (iff.trans (forall_congr (λ n, _)) (@prod_eq_iff_prod_pow_moebius_eq (units R) _
(λ n, if h : 0 < n then units.mk0 (f n) (hf n h) else 1)
(λ n, if h : 0 < n then units.mk0 (g n) (hg n h) else 1))) (forall_congr (λ n, _));
refine imp_congr_right (λ hn, _),
{ dsimp,
rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0,
prod_congr rfl _],
intros x hx,
rw [dif_pos (nat.pos_of_mem_divisors hx), units.coe_hom_apply, units.coe_mk0] },
{ dsimp,
rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0,
prod_congr rfl _],
intros x hx,
rw [dif_pos (nat.pos_of_mem_divisors (nat.snd_mem_divisors_of_mem_antidiagonal hx)),
units.coe_hom_apply, units.coe_zpow₀, units.coe_mk0] }
end
end special_functions
end arithmetic_function
end nat
|
464e6eff8bb2054d83f2225f08f7dbd7b1de14da | bc1214dae29f5e9d007f2c80f5ddb079115f99c4 | /test.lean | 8aee9530d98ac42b7e0803dc169da8bb11d18c3a | [] | no_license | khkim1/f19-assignments | d2e16416f6f90c36a8c16dc367892505d12ccbba | 9c455e0cb4fcd5f456ea7635a99d787c217fe422 | refs/heads/master | 1,596,569,533,145 | 1,575,519,583,000 | 1,575,519,583,000 | 212,254,214 | 0 | 0 | null | 1,569,990,006,000 | 1,569,990,005,000 | null | UTF-8 | Lean | false | false | 141 | lean |
variables p q : Prop
example (h : p ∧ q) : q ∧ p :=
have hq: q, from h.right,
suffices hp: p, from ⟨hq, hp⟩,
show p, from h.left |
c7ae0821a2534fd4f2c2a70e36c39518be9b0258 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/limits/constructions/limits_of_products_and_equalizers.lean | 0be2e07faa027e09c4c86a9ef34e3d355e315939 | [
"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 | 18,172 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Scott Morrison
-/
import data.fintype.prod
import data.fintype.sigma
import category_theory.limits.shapes.equalizers
import category_theory.limits.shapes.finite_products
import category_theory.limits.preserves.shapes.products
import category_theory.limits.preserves.shapes.equalizers
import category_theory.limits.preserves.finite
import category_theory.limits.constructions.finite_products_of_binary_products
import category_theory.limits.constructions.equalizers
import category_theory.limits.constructions.binary_products
/-!
# Constructing limits from products and equalizers.
If a category has all products, and all equalizers, then it has all limits.
Similarly, if it has all finite products, and all equalizers, then it has all finite limits.
If a functor preserves all products and equalizers, then it preserves all limits.
Similarly, if it preserves all finite products and equalizers, then it preserves all finite limits.
# TODO
Provide the dual results.
Show the analogous results for functors which reflect or create (co)limits.
-/
open category_theory
open opposite
namespace category_theory.limits
universes w v v₂ u u₂
variables {C : Type u} [category.{v} C]
variables {J : Type w} [small_category J]
-- We hide the "implementation details" inside a namespace
namespace has_limit_of_has_products_of_has_equalizers
variables {F : J ⥤ C}
{c₁ : fan F.obj}
{c₂ : fan (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2)}
(s t : c₁.X ⟶ c₂.X)
(hs : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), s ≫ c₂.π.app ⟨f⟩ = c₁.π.app ⟨f.1.1⟩ ≫ F.map f.2)
(ht : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), t ≫ c₂.π.app ⟨f⟩ = c₁.π.app ⟨f.1.2⟩)
(i : fork s t)
include hs ht
/--
(Implementation) Given the appropriate product and equalizer cones, build the cone for `F` which is
limiting if the given cones are also.
-/
@[simps]
def build_limit : cone F :=
{ X := i.X,
π :=
{ app := λ j, i.ι ≫ c₁.π.app ⟨_⟩,
naturality' := λ j₁ j₂ f, begin
dsimp,
rw [category.id_comp, category.assoc, ← hs ⟨⟨_, _⟩, f⟩, i.condition_assoc, ht],
end} }
variable {i}
/--
(Implementation) Show the cone constructed in `build_limit` is limiting, provided the cones used in
its construction are.
-/
def build_is_limit (t₁ : is_limit c₁) (t₂ : is_limit c₂) (hi : is_limit i) :
is_limit (build_limit s t hs ht i) :=
{ lift := λ q,
begin
refine hi.lift (fork.of_ι _ _),
{ refine t₁.lift (fan.mk _ (λ j, _)),
apply q.π.app j },
{ apply t₂.hom_ext,
intro j, discrete_cases,
simp [hs, ht] },
end,
uniq' := λ q m w, hi.hom_ext (i.equalizer_ext (t₁.hom_ext
(λ j, by { cases j, simpa using w j }))) }
end has_limit_of_has_products_of_has_equalizers
open has_limit_of_has_products_of_has_equalizers
/--
Given the existence of the appropriate (possibly finite) products and equalizers,
we can construct a limit cone for `F`.
(This assumes the existence of all equalizers, which is technically stronger than needed.)
-/
noncomputable
def limit_cone_of_equalizer_and_product (F : J ⥤ C)
[has_limit (discrete.functor F.obj)]
[has_limit (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2))]
[has_equalizers C] : limit_cone F :=
{ cone := _,
is_limit :=
build_is_limit
(pi.lift (λ f, limit.π (discrete.functor F.obj) ⟨_⟩ ≫ F.map f.2))
(pi.lift (λ f, limit.π (discrete.functor F.obj) ⟨f.1.2⟩))
(by simp)
(by simp)
(limit.is_limit _)
(limit.is_limit _)
(limit.is_limit _) }
/--
Given the existence of the appropriate (possibly finite) products and equalizers, we know a limit of
`F` exists.
(This assumes the existence of all equalizers, which is technically stronger than needed.)
-/
lemma has_limit_of_equalizer_and_product (F : J ⥤ C)
[has_limit (discrete.functor F.obj)]
[has_limit (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.2))]
[has_equalizers C] : has_limit F :=
has_limit.mk (limit_cone_of_equalizer_and_product F)
/-- A limit can be realised as a subobject of a product. -/
noncomputable
def limit_subobject_product [has_limits_of_size.{w w} C] (F : J ⥤ C) :
limit F ⟶ ∏ (λ j, F.obj j) :=
(limit.iso_limit_cone (limit_cone_of_equalizer_and_product F)).hom ≫ equalizer.ι _ _
instance limit_subobject_product_mono [has_limits_of_size.{w w} C] (F : J ⥤ C) :
mono (limit_subobject_product F) :=
mono_comp _ _
/--
Any category with products and equalizers has all limits.
See <https://stacks.math.columbia.edu/tag/002N>.
-/
lemma has_limits_of_has_equalizers_and_products
[has_products.{w} C] [has_equalizers C] : has_limits_of_size.{w w} C :=
{ has_limits_of_shape := λ J 𝒥,
{ has_limit := λ F, by exactI has_limit_of_equalizer_and_product F } }
/--
Any category with finite products and equalizers has all finite limits.
See <https://stacks.math.columbia.edu/tag/002O>.
-/
lemma has_finite_limits_of_has_equalizers_and_finite_products
[has_finite_products C] [has_equalizers C] : has_finite_limits C :=
⟨λ J _ _, { has_limit := λ F, by exactI has_limit_of_equalizer_and_product F }⟩
variables {D : Type u₂} [category.{v₂} D]
noncomputable theory
section
variables [has_limits_of_shape (discrete J) C]
[has_limits_of_shape (discrete (Σ p : J × J, p.1 ⟶ p.2)) C]
[has_equalizers C]
variables (G : C ⥤ D)
[preserves_limits_of_shape walking_parallel_pair G]
[preserves_limits_of_shape (discrete.{w} J) G]
[preserves_limits_of_shape (discrete.{w} (Σ p : J × J, p.1 ⟶ p.2)) G]
/-- If a functor preserves equalizers and the appropriate products, it preserves limits. -/
def preserves_limit_of_preserves_equalizers_and_product :
preserves_limits_of_shape J G :=
{ preserves_limit := λ K,
begin
let P := ∏ K.obj,
let Q := ∏ (λ (f : (Σ (p : J × J), p.fst ⟶ p.snd)), K.obj f.1.2),
let s : P ⟶ Q := pi.lift (λ f, limit.π (discrete.functor K.obj) ⟨_⟩ ≫ K.map f.2),
let t : P ⟶ Q := pi.lift (λ f, limit.π (discrete.functor K.obj) ⟨f.1.2⟩),
let I := equalizer s t,
let i : I ⟶ P := equalizer.ι s t,
apply preserves_limit_of_preserves_limit_cone
(build_is_limit s t (by simp) (by simp)
(limit.is_limit _)
(limit.is_limit _)
(limit.is_limit _)),
refine is_limit.of_iso_limit (build_is_limit _ _ _ _ _ _ _) _,
{ exact fan.mk _ (λ j, G.map (pi.π _ j)) },
{ exact fan.mk (G.obj Q) (λ f, G.map (pi.π _ f)) },
{ apply G.map s },
{ apply G.map t },
{ intro f,
dsimp,
simp only [←G.map_comp, limit.lift_π, fan.mk_π_app] },
{ intro f,
dsimp,
simp only [←G.map_comp, limit.lift_π, fan.mk_π_app] },
{ apply fork.of_ι (G.map i) _,
simp only [← G.map_comp, equalizer.condition] },
{ apply is_limit_of_has_product_of_preserves_limit },
{ apply is_limit_of_has_product_of_preserves_limit },
{ apply is_limit_fork_map_of_is_limit,
apply equalizer_is_equalizer },
refine cones.ext (iso.refl _) _,
intro j,
dsimp,
simp, -- See note [dsimp, simp].
end }
end
/-- If G preserves equalizers and finite products, it preserves finite limits. -/
def preserves_finite_limits_of_preserves_equalizers_and_finite_products
[has_equalizers C] [has_finite_products C]
(G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G]
[∀ (J : Type) [fintype J], preserves_limits_of_shape (discrete J) G] :
preserves_finite_limits G :=
⟨λ _ _ _, by exactI preserves_limit_of_preserves_equalizers_and_product G⟩
/-- If G preserves equalizers and products, it preserves all limits. -/
def preserves_limits_of_preserves_equalizers_and_products
[has_equalizers C] [has_products.{w} C]
(G : C ⥤ D) [preserves_limits_of_shape walking_parallel_pair G]
[∀ J, preserves_limits_of_shape (discrete.{w} J) G] :
preserves_limits_of_size.{w w} G :=
{ preserves_limits_of_shape := λ J 𝒥,
by exactI preserves_limit_of_preserves_equalizers_and_product G }
lemma has_finite_limits_of_has_terminal_and_pullbacks [has_terminal C] [has_pullbacks C] :
has_finite_limits C :=
@@has_finite_limits_of_has_equalizers_and_finite_products _
(@@has_finite_products_of_has_binary_and_terminal _
(has_binary_products_of_has_terminal_and_pullbacks C) infer_instance)
(@@has_equalizers_of_has_pullbacks_and_binary_products _
(has_binary_products_of_has_terminal_and_pullbacks C) infer_instance)
/-- If G preserves terminal objects and pullbacks, it preserves all finite limits. -/
def preserves_finite_limits_of_preserves_terminal_and_pullbacks
[has_terminal C] [has_pullbacks C] (G : C ⥤ D)
[preserves_limits_of_shape (discrete.{0} pempty) G]
[preserves_limits_of_shape walking_cospan G] :
preserves_finite_limits G :=
begin
haveI : has_finite_limits C := has_finite_limits_of_has_terminal_and_pullbacks,
haveI : preserves_limits_of_shape (discrete walking_pair) G :=
preserves_binary_products_of_preserves_terminal_and_pullbacks G,
exact @@preserves_finite_limits_of_preserves_equalizers_and_finite_products _ _ _ _ G
(preserves_equalizers_of_preserves_pullbacks_and_binary_products G)
(preserves_finite_products_of_preserves_binary_and_terminal G),
end
/-!
We now dualize the above constructions, resorting to copy-paste.
-/
-- We hide the "implementation details" inside a namespace
namespace has_colimit_of_has_coproducts_of_has_coequalizers
variables {F : J ⥤ C}
{c₁ : cofan (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.1)}
{c₂ : cofan F.obj}
(s t : c₁.X ⟶ c₂.X)
(hs : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), c₁.ι.app ⟨f⟩ ≫ s = F.map f.2 ≫ c₂.ι.app ⟨f.1.2⟩)
(ht : ∀ (f : Σ p : J × J, p.1 ⟶ p.2), c₁.ι.app ⟨f⟩ ≫ t = c₂.ι.app ⟨f.1.1⟩)
(i : cofork s t)
include hs ht
/--
(Implementation) Given the appropriate coproduct and coequalizer cocones,
build the cocone for `F` which is colimiting if the given cocones are also.
-/
@[simps]
def build_colimit : cocone F :=
{ X := i.X,
ι :=
{ app := λ j, c₂.ι.app ⟨_⟩ ≫ i.π,
naturality' := λ j₁ j₂ f, begin
dsimp,
rw [category.comp_id, ←reassoc_of (hs ⟨⟨_, _⟩, f⟩), i.condition, ←category.assoc, ht],
end} }
variable {i}
/--
(Implementation) Show the cocone constructed in `build_colimit` is colimiting,
provided the cocones used in its construction are.
-/
def build_is_colimit (t₁ : is_colimit c₁) (t₂ : is_colimit c₂) (hi : is_colimit i) :
is_colimit (build_colimit s t hs ht i) :=
{ desc := λ q,
begin
refine hi.desc (cofork.of_π _ _),
{ refine t₂.desc (cofan.mk _ (λ j, _)),
apply q.ι.app j },
{ apply t₁.hom_ext,
intro j, discrete_cases,
simp [reassoc_of hs, reassoc_of ht] },
end,
uniq' := λ q m w, hi.hom_ext (i.coequalizer_ext (t₂.hom_ext
(λ j, by { cases j, simpa using w j }))) }
end has_colimit_of_has_coproducts_of_has_coequalizers
open has_colimit_of_has_coproducts_of_has_coequalizers
/--
Given the existence of the appropriate (possibly finite) coproducts and coequalizers,
we can construct a colimit cocone for `F`.
(This assumes the existence of all coequalizers, which is technically stronger than needed.)
-/
noncomputable
def colimit_cocone_of_coequalizer_and_coproduct (F : J ⥤ C)
[has_colimit (discrete.functor F.obj)]
[has_colimit (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.1))]
[has_coequalizers C] : colimit_cocone F :=
{ cocone := _,
is_colimit :=
build_is_colimit
(sigma.desc (λ f, F.map f.2 ≫ colimit.ι (discrete.functor F.obj) ⟨f.1.2⟩))
(sigma.desc (λ f, colimit.ι (discrete.functor F.obj) ⟨f.1.1⟩))
(by simp)
(by simp)
(colimit.is_colimit _)
(colimit.is_colimit _)
(colimit.is_colimit _) }
/--
Given the existence of the appropriate (possibly finite) coproducts and coequalizers,
we know a colimit of `F` exists.
(This assumes the existence of all coequalizers, which is technically stronger than needed.)
-/
lemma has_colimit_of_coequalizer_and_coproduct (F : J ⥤ C)
[has_colimit (discrete.functor F.obj)]
[has_colimit (discrete.functor (λ f : (Σ p : J × J, p.1 ⟶ p.2), F.obj f.1.1))]
[has_coequalizers C] : has_colimit F :=
has_colimit.mk (colimit_cocone_of_coequalizer_and_coproduct F)
/-- A colimit can be realised as a quotient of a coproduct. -/
noncomputable
def colimit_quotient_coproduct [has_colimits_of_size.{w w} C] (F : J ⥤ C) :
∐ (λ j, F.obj j) ⟶ colimit F :=
coequalizer.π _ _ ≫ (colimit.iso_colimit_cocone (colimit_cocone_of_coequalizer_and_coproduct F)).inv
instance colimit_quotient_coproduct_epi [has_colimits_of_size.{w w} C] (F : J ⥤ C) :
epi (colimit_quotient_coproduct F) :=
epi_comp _ _
/--
Any category with coproducts and coequalizers has all colimits.
See <https://stacks.math.columbia.edu/tag/002P>.
-/
lemma has_colimits_of_has_coequalizers_and_coproducts
[has_coproducts.{w} C] [has_coequalizers C] : has_colimits_of_size.{w w} C :=
{ has_colimits_of_shape := λ J 𝒥,
{ has_colimit := λ F, by exactI has_colimit_of_coequalizer_and_coproduct F } }
/--
Any category with finite coproducts and coequalizers has all finite colimits.
See <https://stacks.math.columbia.edu/tag/002Q>.
-/
lemma has_finite_colimits_of_has_coequalizers_and_finite_coproducts
[has_finite_coproducts C] [has_coequalizers C] : has_finite_colimits C :=
⟨λ J _ _, { has_colimit := λ F, by exactI has_colimit_of_coequalizer_and_coproduct F }⟩
noncomputable theory
section
variables [has_colimits_of_shape (discrete.{w} J) C]
[has_colimits_of_shape (discrete.{w} (Σ p : J × J, p.1 ⟶ p.2)) C]
[has_coequalizers C]
variables (G : C ⥤ D)
[preserves_colimits_of_shape walking_parallel_pair G]
[preserves_colimits_of_shape (discrete.{w} J) G]
[preserves_colimits_of_shape (discrete.{w} (Σ p : J × J, p.1 ⟶ p.2)) G]
/-- If a functor preserves coequalizers and the appropriate coproducts, it preserves colimits. -/
def preserves_colimit_of_preserves_coequalizers_and_coproduct :
preserves_colimits_of_shape J G :=
{ preserves_colimit := λ K,
begin
let P := ∐ K.obj,
let Q := ∐ (λ (f : (Σ (p : J × J), p.fst ⟶ p.snd)), K.obj f.1.1),
let s : Q ⟶ P := sigma.desc (λ f, K.map f.2 ≫ colimit.ι (discrete.functor K.obj) ⟨_⟩),
let t : Q ⟶ P := sigma.desc (λ f, colimit.ι (discrete.functor K.obj) ⟨f.1.1⟩),
let I := coequalizer s t,
let i : P ⟶ I := coequalizer.π s t,
apply preserves_colimit_of_preserves_colimit_cocone
(build_is_colimit s t (by simp) (by simp)
(colimit.is_colimit _)
(colimit.is_colimit _)
(colimit.is_colimit _)),
refine is_colimit.of_iso_colimit (build_is_colimit _ _ _ _ _ _ _) _,
{ exact cofan.mk (G.obj Q) (λ j, G.map (sigma.ι _ j)) },
{ exact cofan.mk _ (λ f, G.map (sigma.ι _ f)) },
{ apply G.map s },
{ apply G.map t },
{ intro f,
dsimp,
simp only [←G.map_comp, colimit.ι_desc, cofan.mk_ι_app] },
{ intro f,
dsimp,
simp only [←G.map_comp, colimit.ι_desc, cofan.mk_ι_app] },
{ apply cofork.of_π (G.map i) _,
simp only [← G.map_comp, coequalizer.condition] },
{ apply is_colimit_of_has_coproduct_of_preserves_colimit },
{ apply is_colimit_of_has_coproduct_of_preserves_colimit },
{ apply is_colimit_cofork_map_of_is_colimit,
apply coequalizer_is_coequalizer },
refine cocones.ext (iso.refl _) _,
intro j,
dsimp,
simp, -- See note [dsimp, simp].
end }
end
/-- If G preserves coequalizers and finite coproducts, it preserves finite colimits. -/
def preserves_finite_colimits_of_preserves_coequalizers_and_finite_coproducts
[has_coequalizers C] [has_finite_coproducts C]
(G : C ⥤ D) [preserves_colimits_of_shape walking_parallel_pair G]
[∀ J [fintype J], preserves_colimits_of_shape (discrete.{0} J) G] :
preserves_finite_colimits G :=
⟨λ _ _ _, by exactI preserves_colimit_of_preserves_coequalizers_and_coproduct G⟩
/-- If G preserves coequalizers and coproducts, it preserves all colimits. -/
def preserves_colimits_of_preserves_coequalizers_and_coproducts
[has_coequalizers C] [has_coproducts.{w} C]
(G : C ⥤ D) [preserves_colimits_of_shape walking_parallel_pair G]
[∀ J, preserves_colimits_of_shape (discrete.{w} J) G] :
preserves_colimits_of_size.{w} G :=
{ preserves_colimits_of_shape := λ J 𝒥,
by exactI preserves_colimit_of_preserves_coequalizers_and_coproduct G }
lemma has_finite_colimits_of_has_initial_and_pushouts [has_initial C] [has_pushouts C] :
has_finite_colimits C :=
@@has_finite_colimits_of_has_coequalizers_and_finite_coproducts _
(@@has_finite_coproducts_of_has_binary_and_initial _
(has_binary_coproducts_of_has_initial_and_pushouts C) infer_instance)
(@@has_coequalizers_of_has_pushouts_and_binary_coproducts _
(has_binary_coproducts_of_has_initial_and_pushouts C) infer_instance)
/-- If G preserves initial objects and pushouts, it preserves all finite colimits. -/
def preserves_finite_colimits_of_preserves_initial_and_pushouts
[has_initial C] [has_pushouts C] (G : C ⥤ D)
[preserves_colimits_of_shape (discrete.{0} pempty) G]
[preserves_colimits_of_shape walking_span G] :
preserves_finite_colimits G :=
begin
haveI : has_finite_colimits C := has_finite_colimits_of_has_initial_and_pushouts,
haveI : preserves_colimits_of_shape (discrete walking_pair) G :=
preserves_binary_coproducts_of_preserves_initial_and_pushouts G,
exact @@preserves_finite_colimits_of_preserves_coequalizers_and_finite_coproducts _ _ _ _ G
(preserves_coequalizers_of_preserves_pushouts_and_binary_coproducts G)
(preserves_finite_coproducts_of_preserves_binary_and_initial G),
end
end category_theory.limits
|
7a62726a8e3a5ce834a3ab3160d407c60a121692 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /tests/lean/run/alg.lean | 903866a6a44684175912f51ec776caab6e3a8fb9 | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,250 | lean | class Semigroup (α : Type u) extends Mul α where
mul_assoc (a b c : α) : a * b * c = a * (b * c)
export Semigroup (mul_assoc)
class MulComm (α : Type u) extends Mul α where
mul_comm (a b : α) : a * b = b * a
export MulComm (mul_comm)
class CommSemigroup (α : Type u) extends Semigroup α where
mul_comm (a b : α) : a * b = b * a
instance [CommSemigroup α] : MulComm α where
mul_comm := CommSemigroup.mul_comm
class One (α : Type u) where
one : α
instance [One α] : OfNat α (natLit! 1) where
ofNat := One.one
class Monoid (α : Type u) extends Semigroup α, One α where
one_mul (a : α) : 1 * a = a
mul_one (a : α) : a * 1 = a
export Monoid (one_mul mul_one)
class CommMonoid (α : Type u) extends Monoid α where
mul_comm (a b : α) : a * b = b * a
instance [CommMonoid α] : CommSemigroup α where
mul_comm := CommMonoid.mul_comm
instance [CommMonoid α] : MulComm α where
mul_comm := CommSemigroup.mul_comm
class Inv (α : Type u) where
inv : α → α
postfix:max "⁻¹" => Inv.inv
class Group (α : Type u) extends Monoid α, Inv α where
mul_left_inv (a : α) : a⁻¹ * a = 1
export Group (mul_left_inv)
class CommGroup (α : Type u) extends Group α where
mul_comm (a b : α) : a * b = b * a
instance [CommGroup α] : CommMonoid α where
mul_comm := CommGroup.mul_comm
instance [CommGroup α] : MulComm α where
mul_comm := CommGroup.mul_comm
theorem inv_mul_cancel_left [Group α] (a b : α) : a⁻¹ * (a * b) = b := by
rw [← mul_assoc, mul_left_inv, one_mul]
theorem inv_eq_of_mul_eq_one [Group α] {a b : α} (h : a * b = 1) : a⁻¹ = b := by
rw [← mul_one a⁻¹, ←h, ←mul_assoc, mul_left_inv, one_mul]
theorem inv_inv [Group α] (a : α) : (a⁻¹)⁻¹ = a :=
inv_eq_of_mul_eq_one (mul_left_inv a)
theorem mul_right_inv [Group α] (a : α) : a * a⁻¹ = 1 := by
have a⁻¹⁻¹ * a⁻¹ = 1 by rw [mul_left_inv]
rw [inv_inv] at this
assumption
theorem mul_inv_rev [Group α] (a b : α) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := by
apply inv_eq_of_mul_eq_one
rw [mul_assoc, ← mul_assoc b, mul_right_inv, one_mul, mul_right_inv]
theorem mul_inv [CommGroup α] (a b : α) : (a * b)⁻¹ = a⁻¹ * b⁻¹ := by
rw [mul_inv_rev, mul_comm]
|
127d8e6d9fbb001d022d8cf86b888c0a0b134391 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Data/Lsp/Communication.lean | 6b51c2252eec4a30aee5e0f4ead80e39ff1fbf48 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 4,212 | 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 Lean.Data.JsonRpc
/-! Reading/writing LSP messages from/to IO handles. -/
namespace IO.FS.Stream
open Lean
open Lean.JsonRpc
section
private def parseHeaderField (s : String) : Option (String × String) := do
guard $ s ≠ "" ∧ s.takeRight 2 = "\r\n"
let xs := (s.dropRight 2).splitOn ": "
match xs with
| [] => none
| [_] => none
| name :: value :: rest =>
let value := ": ".intercalate (value :: rest)
some ⟨name, value⟩
/-- Returns true when the string is a Lean 3 request.
This means that the user is running a Lean 3 language client that
is not aware of Lean 4. In this case we should give a friendlier message. -/
private def isLean3Request (s : String) : Bool :=
let e : Except String Unit := (do
let j ← Json.parse s
let _ ← j.getObjVal? "command"
let _ ← j.getObjVal? "seq_num"
return ()
)
e.isOk
private partial def readHeaderFields (h : FS.Stream) : IO (List (String × String)) := do
let l ← h.getLine
if (←h.isEof) then
throw $ userError "Stream was closed"
if l = "\r\n" then
pure []
else
match parseHeaderField l with
| some hf =>
let tail ← readHeaderFields h
pure (hf :: tail)
| none =>
if isLean3Request l then
throw $ userError s!"A Lean 3 request was received. Please ensure that your editor has a Lean 4 compatible extension installed. For VSCode, this is\n\n https://github.com/leanprover/vscode-lean4 "
else
throw $ userError s!"Invalid header field: {repr l}"
/-- Returns the Content-Length. -/
private def readLspHeader (h : FS.Stream) : IO Nat := do
let fields ← readHeaderFields h
match fields.lookup "Content-Length" with
| some length => match length.toNat? with
| some n => pure n
| none => throw $ userError s!"Content-Length header field value '{length}' is not a Nat"
| none => throw $ userError s!"No Content-Length field in header: {fields}"
def readLspMessage (h : FS.Stream) : IO Message := do
try
let nBytes ← readLspHeader h
h.readMessage nBytes
catch e =>
throw $ userError s!"Cannot read LSP message: {e}"
def readLspRequestAs (h : FS.Stream) (expectedMethod : String) (α) [FromJson α] : IO (Request α) := do
try
let nBytes ← readLspHeader h
h.readRequestAs nBytes expectedMethod α
catch e =>
throw $ userError s!"Cannot read LSP request: {e}"
def readLspNotificationAs (h : FS.Stream) (expectedMethod : String) (α) [FromJson α] : IO (Notification α) := do
try
let nBytes ← readLspHeader h
h.readNotificationAs nBytes expectedMethod α
catch e =>
throw $ userError s!"Cannot read LSP notification: {e}"
def readLspResponseAs (h : FS.Stream) (expectedID : RequestID) (α) [FromJson α] : IO (Response α) := do
try
let nBytes ← readLspHeader h
h.readResponseAs nBytes expectedID α
catch e =>
throw $ userError s!"Cannot read LSP response: {e}"
end
section
variable [ToJson α]
def writeLspMessage (h : FS.Stream) (msg : Message) : IO Unit := do
-- inlined implementation instead of using jsonrpc's writeMessage
-- to maintain the atomicity of putStr
let j := (toJson msg).compress
let header := s!"Content-Length: {toString j.utf8ByteSize}\r\n\r\n"
h.putStr (header ++ j)
h.flush
def writeLspRequest (h : FS.Stream) (r : Request α) : IO Unit :=
h.writeLspMessage r
def writeLspNotification (h : FS.Stream) (n : Notification α) : IO Unit :=
h.writeLspMessage n
def writeLspResponse (h : FS.Stream) (r : Response α) : IO Unit :=
h.writeLspMessage r
def writeLspResponseError (h : FS.Stream) (e : ResponseError Unit) : IO Unit :=
h.writeLspMessage (Message.responseError e.id e.code e.message none)
def writeLspResponseErrorWithData (h : FS.Stream) (e : ResponseError α) : IO Unit :=
h.writeLspMessage e
end
end IO.FS.Stream
|
405159f39a0e9651a134fd5b275901dd210c7a19 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /tests/lean/run/forInUniv.lean | 9b3c13374de9f786d9af3a565fa18b418400a26a | [
"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 | 421 | lean | #lang lean4
universes u
def f {α : Type u} [BEq α] (xs : List α) (y : α) : α := do
for x in xs do
if x == y then
return x
return y
structure S :=
(key val : Nat)
instance : BEq S :=
⟨fun a b => a.key == b.key⟩
theorem ex1 : f (α := S) [⟨1, 2⟩, ⟨3, 4⟩, ⟨5, 6⟩] ⟨3, 0⟩ = ⟨3, 4⟩ :=
rfl
theorem ex2 : f (α := S) [⟨1, 2⟩, ⟨3, 4⟩, ⟨5, 6⟩] ⟨4, 10⟩ = ⟨4, 10⟩ :=
rfl
|
443e29f961a4f081a9e7879c11f3f3b030c9266b | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /hott/algebra/precategory/strict.hlean | 4e75752c8b653da06afde303630328158252f345 | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,547 | hlean | /-
Copyright (c) 2015 Jakob von Raumer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: algebra.precategory.functor
Authors: Floris van Doorn, Jakob von Raumer
-/
import .basic .functor
open category is_trunc eq function sigma sigma.ops
namespace category
structure strict_precategory[class] (ob : Type) extends precategory ob :=
(is_hset_ob : is_hset ob)
attribute strict_precategory.is_hset_ob [instance]
definition strict_precategory.mk' [reducible] (ob : Type) (C : precategory ob)
(H : is_hset ob) : strict_precategory ob :=
precategory.rec_on C strict_precategory.mk H
structure Strict_precategory : Type :=
(carrier : Type)
(struct : strict_precategory carrier)
attribute Strict_precategory.struct [instance] [coercion]
definition Strict_precategory.to_Precategory [coercion] [reducible]
(C : Strict_precategory) : Precategory :=
Precategory.mk (Strict_precategory.carrier C) C
open functor
definition precat_strict_precat : precategory Strict_precategory :=
precategory.mk (λ a b, functor a b)
(λ a b, @functor.is_hset_functor a b _)
(λ a b c g f, functor.compose g f)
(λ a, functor.id)
(λ a b c d h g f, !functor.assoc)
(λ a b f, !functor.id_left)
(λ a b f, !functor.id_right)
definition Precat_of_strict_precats := precategory.Mk precat_strict_precat
namespace ops
abbreviation SPreCat := Precat_of_strict_precats
--attribute precat_strict_precat [instance]
end ops
end category
|
f8f3081f8e18f6b80ce06f535ba9dffe6beeadd6 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/finsupp/indicator.lean | 918c6da0c0ae8009e550f7e03a8d281ef87f7194 | [
"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 | 1,887 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.finsupp.basic
/-!
# Building finitely supported functions off finsets
This file defines `finsupp.indicator` to help create finsupps from finsets.
## Main declarations
* `finsupp.indicator`: Turns a map from a `finset` into a `finsupp` from the entire type.
-/
noncomputable theory
open finset function
open_locale classical
variables {ι α : Type*}
namespace finsupp
variables [has_zero α] {s : finset ι} (f : Π i ∈ s, α) {i : ι}
/-- Create an element of `ι →₀ α` from a finset `s` and a function `f` defined on this finset. -/
def indicator (s : finset ι) (f : Π i ∈ s, α) : ι →₀ α :=
{ to_fun := λ i, if H : i ∈ s then f i H else 0,
support := (s.attach.filter $ λ i : s, f i.1 i.2 ≠ 0).map $ embedding.subtype _,
mem_support_to_fun := λ i, begin
rw [mem_map, dite_ne_right_iff],
exact ⟨λ ⟨⟨j, hj⟩, hf, rfl⟩, ⟨hj, (mem_filter.1 hf).2⟩,
λ ⟨hi, hf⟩, ⟨⟨i, hi⟩, mem_filter.2 $ ⟨mem_attach _ _, hf⟩, rfl⟩⟩,
end }
lemma indicator_of_mem (hi : i ∈ s) (f : Π i ∈ s, α) : indicator s f i = f i hi := dif_pos hi
lemma indicator_of_not_mem (hi : i ∉ s) (f : Π i ∈ s, α) : indicator s f i = 0 := dif_neg hi
variables (s i)
@[simp] lemma indicator_apply : indicator s f i = if hi : i ∈ s then f i hi else 0 := rfl
lemma indicator_injective : injective (λ f : Π i ∈ s, α, indicator s f) :=
begin
intros a b h,
ext i hi,
rw [←indicator_of_mem hi a, ←indicator_of_mem hi b],
exact congr_fun h i,
end
lemma support_indicator_subset : ((indicator s f).support : set ι) ⊆ s :=
begin
intros i hi,
rw [mem_coe, mem_support_iff] at hi,
by_contra,
exact hi (indicator_of_not_mem h _),
end
end finsupp
|
4de249b35b867c09664a4de26efd3b327d03e6d0 | e4def7044cdf5942eed78db25d2daa58d80eed64 | /src/test_your_setup.lean | 0ee0a276b5b63d88c36c179da899810009365d42 | [] | no_license | kevinsullivan/dm.s20.old | 3f8f736b9a792cca8dd44a73a98ade0b534ed084 | a240be0a53961ac25b5f4426fe7bc8d4dbe7013f | refs/heads/master | 1,607,522,498,471 | 1,579,058,084,000 | 1,579,058,084,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 138 | lean | import topology.basic
-- Is your Lean and VS Code setup working?
#check 0
-- Is Lean's math library working?
#check topological_space |
17fdebdb0b64cdafd4c105c6cbc4c3bf68d2dc06 | 1446f520c1db37e157b631385707cc28a17a595e | /src/Init/Lean/Meta/Exception.lean | 715be79fb788118cf4a4389d9f388b5222e1941f | [
"Apache-2.0"
] | permissive | bdbabiak/lean4 | cab06b8a2606d99a168dd279efdd404edb4e825a | 3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac | refs/heads/master | 1,615,045,275,530 | 1,583,793,696,000 | 1,583,793,696,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,550 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.Environment
import Init.Lean.MetavarContext
import Init.Lean.Message
import Init.Lean.Util.PPGoal
namespace Lean
namespace Meta
abbrev ExceptionContext := MessageDataContext
inductive Bug
| overwritingExprMVar (mvarId : Name)
inductive Exception
| unknownConst (constName : Name) (ctx : ExceptionContext)
| unknownFVar (fvarId : FVarId) (ctx : ExceptionContext)
| unknownExprMVar (mvarId : MVarId) (ctx : ExceptionContext)
| unknownLevelMVar (mvarId : MVarId) (ctx : ExceptionContext)
| unexpectedBVar (bvarIdx : Nat)
| functionExpected (f a : Expr) (ctx : ExceptionContext)
| typeExpected (type : Expr) (ctx : ExceptionContext)
| incorrectNumOfLevels (constName : Name) (constLvls : List Level) (ctx : ExceptionContext)
| invalidProjection (structName : Name) (idx : Nat) (s : Expr) (ctx : ExceptionContext)
| revertFailure (toRevert : Array Expr) (decl : LocalDecl) (ctx : ExceptionContext)
| readOnlyMVar (mvarId : MVarId) (ctx : ExceptionContext)
| isLevelDefEqStuck (u v : Level) (ctx : ExceptionContext)
| isExprDefEqStuck (t s : Expr) (ctx : ExceptionContext)
| letTypeMismatch (fvarId : FVarId) (ctx : ExceptionContext)
| appTypeMismatch (f a : Expr) (ctx : ExceptionContext)
| notInstance (e : Expr) (ctx : ExceptionContext)
| appBuilder (op : Name) (msg : String) (args : Array Expr) (ctx : ExceptionContext)
| synthInstance (inst : Expr) (ctx : ExceptionContext)
| tactic (tacticName : Name) (mvarId : MVarId) (msg : MessageData) (ctx : ExceptionContext)
| bug (b : Bug) (ctx : ExceptionContext)
| other (msg : String)
namespace Exception
instance : Inhabited Exception := ⟨other ""⟩
-- TODO: improve, use (to be implemented) pretty printer
def toStr : Exception → String
| unknownConst c _ => "unknown constant '" ++ toString c ++ "'"
| unknownFVar fvarId _ => "unknown free variable '" ++ toString fvarId ++ "'"
| unknownExprMVar mvarId _ => "unknown metavariable '" ++ toString mvarId ++ "'"
| unknownLevelMVar mvarId _ => "unknown universe level metavariable '" ++ toString mvarId ++ "'"
| unexpectedBVar bvarIdx => "unexpected loose bound variable #" ++ toString bvarIdx
| functionExpected fType args _ => "function expected"
| typeExpected _ _ => "type expected"
| incorrectNumOfLevels c lvls _ => "incorrect number of universe levels for '" ++ toString c ++ "' " ++ toString lvls
| invalidProjection _ _ _ _ => "invalid projection"
| revertFailure _ _ _ => "revert failure"
| readOnlyMVar _ _ => "try to assign read only metavariable"
| isLevelDefEqStuck _ _ _ => "isDefEq is stuck"
| isExprDefEqStuck _ _ _ => "isDefEq is stuck"
| letTypeMismatch _ _ => "type mismatch at let-expression"
| appTypeMismatch _ _ _ => "application type mismatch"
| notInstance _ _ => "type class instance expected"
| appBuilder _ _ _ _ => "application builder failure"
| synthInstance _ _ => "type class instance synthesis failed"
| tactic tacName _ _ _ => "tactic '" ++ toString tacName ++ "' failed"
| bug _ _ => "bug"
| other s => s
instance : HasToString Exception := ⟨toStr⟩
def mkCtx (ctx : ExceptionContext) (m : MessageData) : MessageData :=
MessageData.withContext ctx m
/-- Generate trace message that is suitable for tracing crawlers -/
def toTraceMessageData : Exception → MessageData
| unknownConst c ctx => mkCtx ctx $ `unknownConst ++ " " ++ c
| unknownFVar fvarId ctx => mkCtx ctx $ `unknownFVar ++ " " ++ fvarId
| unknownExprMVar mvarId ctx => mkCtx ctx $ `unknownExprMVar ++ " " ++ mkMVar mvarId
| unknownLevelMVar mvarId ctx => mkCtx ctx $ `unknownLevelMVar ++ " " ++ mkLevelMVar mvarId
| unexpectedBVar bvarIdx => `unexpectedBVar ++ " " ++ mkBVar bvarIdx
| functionExpected f a ctx => mkCtx ctx $ `functionExpected ++ " " ++ mkApp f a
| typeExpected t ctx => mkCtx ctx $ `typeExpected ++ " " ++ t
| incorrectNumOfLevels c lvls ctx => mkCtx ctx $ `incorrectNumOfLevels ++ " " ++ mkConst c lvls
| invalidProjection s i e ctx => mkCtx ctx $ `invalidProjection ++ " " ++ mkProj s i e
| revertFailure xs decl ctx => mkCtx ctx $ `revertFailure -- TODO improve
| readOnlyMVar mvarId ctx => mkCtx ctx $ `readOnlyMVar ++ " " ++ mkMVar mvarId
| isLevelDefEqStuck u v ctx => mkCtx ctx $ `isLevelDefEqStuck ++ " " ++ u ++ " =?= " ++ v
| isExprDefEqStuck t s ctx => mkCtx ctx $ `isExprDefEqStuck ++ " " ++ t ++ " =?= " ++ s
| letTypeMismatch fvarId ctx => mkCtx ctx $ `letTypeMismatch ++ " " ++ mkFVar fvarId
| appTypeMismatch f a ctx => mkCtx ctx $ `appTypeMismatch ++ " " ++ mkApp f a
| notInstance i ctx => mkCtx ctx $ `notInstance ++ " " ++ i
| appBuilder op msg args ctx => mkCtx ctx $ `appBuilder ++ " " ++ op ++ " " ++ args ++ " " ++ msg
| synthInstance inst ctx => mkCtx ctx $ `synthInstance ++ " " ++ inst
| tactic tacName mvarId msg ctx => mkCtx ctx $ `tacticFailure ++ " " ++ tacName ++ " " ++ msg
| bug _ _ => "internal bug" -- TODO improve
| other s => s
end Exception
end Meta
end Lean
|
eb60120a9fe15958e7a152e9519f77d20998b9ea | 4b846d8dabdc64e7ea03552bad8f7fa74763fc67 | /library/tools/super/trim.lean | cad173ad4887f2b3fef0abd17ff52f741ac4800d | [
"Apache-2.0"
] | permissive | pacchiano/lean | 9324b33f3ac3b5c5647285160f9f6ea8d0d767dc | fdadada3a970377a6df8afcd629a6f2eab6e84e8 | refs/heads/master | 1,611,357,380,399 | 1,489,870,101,000 | 1,489,870,101,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,300 | lean | /-
Copyright (c) 2016 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .utils
open monad expr tactic
namespace super
-- TODO(gabriel): rewrite using conversions
meta def trim : expr → tactic expr
| (app (lam n m d b) arg) :=
if ¬b^.has_var then
trim b
else
lift₂ app (trim (lam n m d b)) (trim arg)
| (app a b) := lift₂ app (trim a) (trim b)
| (lam n m d b) := do
x ← mk_local' `x m d,
b' ← trim (instantiate_var b x),
return $ lam n m d (abstract_local b' x^.local_uniq_name)
| (elet n t v b) :=
if has_var b then do
x ← mk_local_def `x t,
b' ← trim (instantiate_var b x),
return $ elet n t v (abstract_local b' x^.local_uniq_name)
else
trim b
| e := return e
-- iterate trim until convergence
meta def trim' : expr → tactic expr
| e := do e' ← trim e,
if e =ₐ e' then
return e
else
trim' e'
open tactic
meta def with_trim {α} (tac : tactic α) : tactic α := do
gs ← get_goals,
match gs with
| (g::gs) := do
g' ← infer_type g >>= mk_meta_var,
set_goals [g'],
r ← tac,
now,
set_goals (g::gs),
instantiate_mvars g' >>= trim' >>= exact,
return r
| [] := fail "no goal"
end
end super
|
14c37a5ce020612ee8428546910764690ed43af4 | 2f8bf12144551bc7d8087a6320990c4621741f3d | /library/init/io.lean | e10da8b3330eb5cedb67b71ed65c316bf7eb873b | [
"Apache-2.0"
] | permissive | jesse-michael-han/lean4 | eb63a12960e69823749edceb4f23fd33fa2253ce | fa16920a6a7700cabc567aa629ce4ae2478a2f40 | refs/heads/master | 1,589,935,810,594 | 1,557,177,860,000 | 1,557,177,860,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,985 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Luke Nelson, Jared Roesch, Leonardo de Moura, Sebastian Ullrich
-/
prelude
import init.control.estate init.data.string.basic
/-- Like https://hackage.haskell.org/package/ghc-Prim-0.5.2.0/docs/GHC-Prim.html#t:RealWorld.
Makes sure we never reorder `IO` operations. -/
constant IO.RealWorld : Type := Unit
/- TODO(Leo): mark it as an opaque definition. Reason: prevent
functions defined in other modules from accessing `IO.RealWorld`.
We don't want action such as
```
def getWorld : IO (IO.RealWorld) := get
```
-/
@[derive Monad MonadExcept]
def EIO (ε : Type) : Type → Type := EState ε IO.RealWorld
instance {ε : Type} {α : Type} [Inhabited ε] : Inhabited (EIO ε α) :=
inferInstanceAs (Inhabited (EState ε IO.RealWorld α))
/-
In the future, we may want to give more concrete data
like in https://doc.rust-lang.org/std/IO/enum.ErrorKind.html
-/
@[derive HasToString Inhabited]
def IO.error := String
def IO.userError (s : String) : IO.error :=
s
abbrev IO : Type → Type := EIO IO.error
@[extern "lean_io_unsafe"]
constant unsafeIO {α : Type} (fn : IO α) : Option α := default _
@[extern 4 "lean_io_timeit"]
constant timeit {α : Type} (msg : @& String) (fn : IO α) : IO α := default _
@[extern 4 "lean_io_allocprof"]
constant allocprof {α : Type} (msg : @& String) (fn : IO α) : IO α := default _
abbrev monadIO (m : Type → Type) := HasMonadLiftT IO m
def ioOfExcept {ε α : Type} [HasToString ε] (e : Except ε α) : IO α :=
match e with
| Except.ok a := pure a
| Except.error e := throw $ toString e
namespace IO
def lazyPure {α : Type} (fn : Unit → α) : IO α :=
pure (fn ())
inductive Fs.Mode
| read | write | readWrite | append
constant Fs.handle : Type := Unit
namespace Prim
open Fs
@[specialize] partial def iterate {α β : Type} : α → (α → IO (Sum α β)) → IO β
| a f :=
do v ← f a,
match v with
| Sum.inl a := iterate a f
| Sum.inr b := pure b
@[extern 2 "lean_io_prim_put_str"]
constant putStr (s: @& String) : IO Unit := default _
@[extern 1 "lean_io_prim_get_line"]
constant getLine : IO String := default _
@[extern 4 "lean_io_prim_handle_mk"]
constant handle.mk (s : @& String) (m : Mode) (bin : Bool := false) : IO handle := default _
@[extern 2 "lean_io_prim_handle_is_eof"]
constant handle.isEof (h : @& handle) : IO Bool := default _
@[extern 2 "lean_io_prim_handle_flush"]
constant handle.flush (h : @& handle) : IO Unit := default _
@[extern 2 "lean_io_prim_handle_close"]
constant handle.close (h : @& handle) : IO Unit := default _
-- TODO: replace `String` with byte buffer
-- constant handle.read : handle → Nat → EIO String
-- constant handle.write : handle → String → EIO Unit
@[extern 2 "lean_io_prim_handle_get_line"]
constant handle.getLine (h : @& handle) : IO String := default _
@[inline] def liftIO {m : Type → Type} {α : Type} [monadIO m] (x : IO α) : m α :=
monadLift x
end Prim
section
variables {m : Type → Type} [Monad m] [monadIO m]
private def putStr : String → m Unit :=
Prim.liftIO ∘ Prim.putStr
def print {α} [HasToString α] (s : α) : m Unit :=
putStr ∘ toString $ s
def println {α} [HasToString α] (s : α) : m Unit :=
print s *> putStr "\n"
end
namespace Fs
variables {m : Type → Type} [Monad m] [monadIO m]
def handle.mk (s : String) (Mode : Mode) (bin : Bool := false) : m handle := Prim.liftIO (Prim.handle.mk s Mode bin)
def handle.isEof : handle → m Bool := Prim.liftIO ∘ Prim.handle.isEof
def handle.flush : handle → m Unit := Prim.liftIO ∘ Prim.handle.flush
def handle.close : handle → m Unit := Prim.liftIO ∘ Prim.handle.flush
-- def handle.read (h : handle) (bytes : Nat) : m String := Prim.liftEIO (Prim.handle.read h bytes)
-- def handle.write (h : handle) (s : String) : m Unit := Prim.liftEIO (Prim.handle.write h s)
def handle.getLine : handle → m String := Prim.liftIO ∘ Prim.handle.getLine
/-
def getChar (h : handle) : m Char :=
do b ← h.read 1,
if b.isEmpty then fail "getChar failed"
else pure b.mkIterator.curr
-/
-- def handle.putChar (h : handle) (c : Char) : m Unit :=
-- h.write (toString c)
-- def handle.putStr (h : handle) (s : String) : m Unit :=
-- h.write s
-- def handle.putStrLn (h : handle) (s : String) : m Unit :=
-- h.putStr s *> h.putStr "\n"
def handle.readToEnd (h : handle) : m String :=
Prim.liftIO $ Prim.iterate "" $ λ r, do
done ← h.isEof,
if done
then pure (Sum.inr r) -- stop
else do
-- HACK: use less efficient `getLine` while `read` is broken
c ← h.getLine,
pure $ Sum.inl (r ++ c) -- continue
def readFile (fname : String) (bin := false) : m String :=
do h ← handle.mk fname Mode.read bin,
r ← h.readToEnd,
h.close,
pure r
-- def writeFile (fname : String) (data : String) (bin := false) : m Unit :=
-- do h ← handle.mk fname Mode.write bin,
-- h.write data,
-- h.close
end Fs
-- constant stdin : IO Fs.handle
-- constant stderr : IO Fs.handle
-- constant stdout : IO Fs.handle
/-
namespace Proc
def child : Type :=
monadIOProcess.child ioCore
def child.stdin : child → handle :=
monadIOProcess.stdin
def child.stdout : child → handle :=
monadIOProcess.stdout
def child.stderr : child → handle :=
monadIOProcess.stderr
def spawn (p : IO.process.spawnArgs) : IO child :=
monadIOProcess.spawn ioCore p
def wait (c : child) : IO Nat :=
monadIOProcess.wait c
end Proc
-/
/- References -/
constant RefPointed : PointedType := default _
def Ref (α : Type) : Type := RefPointed.type
instance (α : Type) : Inhabited (Ref α) :=
⟨RefPointed.val⟩
namespace Prim
@[extern 3 cpp inline "lean::io_mk_ref(#2, #3)"]
constant mkRef {α : Type} (a : α) : IO (Ref α) := default _
@[extern 3 cpp inline "lean::io_ref_get(#2, #3)"]
constant Ref.get {α : Type} (r : @& Ref α) : IO α := default _
@[extern 4 cpp inline "lean::io_ref_set(#2, #3, #4)"]
constant Ref.set {α : Type} (r : @& Ref α) (a : α) : IO Unit := default _
@[extern 4 cpp inline "lean::io_ref_swap(#2, #3, #4)"]
constant Ref.swap {α : Type} (r : @& Ref α) (a : α) : IO α := default _
@[extern 3 cpp inline "lean::io_ref_reset(#2, #3)"]
constant Ref.reset {α : Type} (r : @& Ref α) : IO Unit := default _
end Prim
section
variables {m : Type → Type} [Monad m] [monadIO m]
@[inline] def mkRef {α : Type} (a : α) : m (Ref α) := Prim.liftIO (Prim.mkRef a)
@[inline] def Ref.get {α : Type} (r : Ref α) : m α := Prim.liftIO (Prim.Ref.get r)
@[inline] def Ref.set {α : Type} (r : Ref α) (a : α) : m Unit := Prim.liftIO (Prim.Ref.set r a)
@[inline] def Ref.swap {α : Type} (r : Ref α) (a : α) : m α := Prim.liftIO (Prim.Ref.swap r a)
@[inline] def Ref.reset {α : Type} (r : Ref α) : m Unit := Prim.liftIO (Prim.Ref.reset r)
@[inline] def Ref.modify {α : Type} (r : Ref α) (f : α → α) : m Unit :=
do v ← r.get,
r.reset,
r.set (f v)
end
end IO
/-
/-- Run the external process specified by `args`.
The process will run to completion with its output captured by a pipe, and
read into `String` which is then returned. -/
def IO.cmd (args : IO.process.spawnArgs) : IO String :=
do child ← IO.Proc.spawn { stdout := IO.process.stdio.piped, ..args },
s ← IO.Fs.readToEnd child.stdout,
IO.Fs.close child.stdout,
exitv ← IO.Proc.wait child,
if exitv ≠ 0 then IO.fail $ "process exited with status " ++ repr exitv else pure (),
pure s
-/
universe u
/-- Typeclass used for presenting the output of an `#eval` command. -/
class HasEval (α : Type u) :=
(eval : α → IO Unit)
instance HasRepr.HasEval {α : Type u} [HasRepr α] : HasEval α :=
⟨λ a, IO.println (repr a)⟩
instance IO.HasEval {α : Type} [HasEval α] : HasEval (IO α) :=
⟨λ x, do a ← x, HasEval.eval a⟩
-- special case: do not print `()`
instance IOUnit.HasEval : HasEval (IO Unit) :=
⟨λ x, x⟩
|
62e35a464f83e63451c373252032b737458c621f | 95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990 | /src/data/matrix.lean | 7d9e4a751452066752e7375d39a21a11c497e6d9 | [
"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 | 9,376 | lean | /-
Copyright (c) 2018 Ellen Arlt. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin
Matrices
-/
import algebra.module algebra.pi_instances
import data.fintype
universes u v
def matrix (m n : Type u) [fintype m] [fintype n] (α : Type v) : Type (max u v) :=
m → n → α
namespace matrix
variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o]
variables {α : Type v}
section ext
variables {M N : matrix m n α}
theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N :=
⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩
@[extensionality] theorem ext : (∀ i j, M i j = N i j) → M = N :=
ext_iff.mp
def transpose (M : matrix m n α) : matrix n m α
| x y := M y x
def row (w : m → α) : matrix m punit α
| x y := w x
def col (v : n → α) : matrix punit n α
| x y := v y
end ext
instance [has_add α] : has_add (matrix m n α) := pi.has_add
instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup
instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup
instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero
instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid
instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid
instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg
instance [add_group α] : add_group (matrix m n α) := pi.add_group
instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group
@[simp] theorem zero_val [has_zero α] (i j) : (0 : matrix m n α) i j = 0 := rfl
@[simp] theorem neg_val [has_neg α] (M : matrix m n α) (i j) : (- M) i j = - M i j := rfl
@[simp] theorem add_val [has_add α] (M N : matrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl
section diagonal
variables [decidable_eq n]
def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0
@[simp] theorem diagonal_val_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i :=
by simp [diagonal]
@[simp] theorem diagonal_val_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) :
(diagonal d) i j = 0 := by simp [diagonal, h]
theorem diagonal_val_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) :
(diagonal d) i j = 0 := diagonal_val_ne h.symm
@[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 :=
by simp [diagonal]; refl
section one
variables [has_zero α] [has_one α]
instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩
@[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl
theorem one_val {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl
@[simp] theorem one_val_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_val_eq i
@[simp] theorem one_val_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 :=
diagonal_val_ne
theorem one_val_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 :=
diagonal_val_ne'
end one
end diagonal
@[simp] theorem diagonal_add [decidable_eq n] [add_monoid α] (d₁ d₂ : n → α) :
diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) :=
by ext i j; by_cases i = j; simp [h]
protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) :
matrix l n α :=
λ i k, finset.univ.sum (λ j, M i j * N j k)
theorem mul_val [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} :
(M.mul N) i k = finset.univ.sum (λ j, M i j * N j k) := rfl
local attribute [simp] mul_val
instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩
@[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) :
M * N = M.mul N := rfl
theorem mul_val' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} :
(M * N) i k = finset.univ.sum (λ j, M i j * N j k) := rfl
section semigroup
variables [decidable_eq m] [decidable_eq n] [semiring α]
protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) :
(L.mul M).mul N = L.mul (M.mul N) :=
by funext i k;
simp [finset.mul_sum, finset.sum_mul, mul_assoc];
rw finset.sum_comm
instance : semigroup (matrix n n α) :=
{ mul_assoc := matrix.mul_assoc, ..matrix.has_mul }
end semigroup
@[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) :
-diagonal d = diagonal (λ i, -d i) :=
by ext i j; by_cases i = j; simp [h]
section semiring
variables [semiring α]
theorem mul_zero (M : matrix m n α) : M.mul (0 : matrix n n α) = 0 :=
by ext i j; simp
theorem zero_mul (M : matrix m n α) : (0 : matrix m m α).mul M = 0 :=
by ext i j; simp
theorem mul_add (L : matrix m n α) (M N : matrix n n α) : L.mul (M + N) = L.mul M + L.mul N :=
by ext i j; simp [finset.sum_add_distrib, mul_add]
theorem add_mul (L M : matrix m m α) (N : matrix m n α) : (L + M).mul N = L.mul N + M.mul N :=
by ext i j; simp [finset.sum_add_distrib, add_mul]
@[simp] theorem diagonal_mul [decidable_eq m]
(d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j :=
by simp; rw finset.sum_eq_single i; simp [diagonal_val_ne'] {contextual := tt}
@[simp] theorem mul_diagonal [decidable_eq n]
(d : n → α) (M : matrix m n α) (i j) : M.mul (diagonal d) i j = M i j * d j :=
by simp; rw finset.sum_eq_single j; simp {contextual := tt}
protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α).mul M = M :=
by ext i j; rw [← diagonal_one, diagonal_mul, one_mul]
protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M.mul (1 : matrix n n α) = M :=
by ext i j; rw [← diagonal_one, mul_diagonal, mul_one]
instance [decidable_eq n] : monoid (matrix n n α) :=
{ one_mul := matrix.one_mul,
mul_one := matrix.mul_one,
..matrix.has_one, ..matrix.semigroup }
instance [decidable_eq n] : semiring (matrix n n α) :=
{ mul_zero := mul_zero,
zero_mul := zero_mul,
left_distrib := mul_add,
right_distrib := add_mul,
..matrix.add_comm_monoid,
..matrix.monoid }
@[simp] theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) :
(diagonal d₁).mul (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) :=
by ext i j; by_cases i = j; simp [h]
theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) :
diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) :=
diagonal_mul_diagonal' _ _
end semiring
instance [decidable_eq n] [ring α] : ring (matrix n n α) :=
{ ..matrix.add_comm_group, ..matrix.semiring }
instance [has_mul α] : has_scalar α (matrix m n α) := ⟨λ a M i j, a * M i j⟩
instance [ring α] : module α (matrix m n α) :=
module.of_core
{ smul_add := λ a M N, ext $ λ i j, _root_.mul_add a (M i j) (N i j),
add_smul := λ a b M, ext $ λ i j, _root_.add_mul a b (M i j),
mul_smul := λ a b M, ext $ λ i j, mul_assoc a b (M i j),
one_smul := λ M, ext $ λ i j, one_mul (M i j),
.. (infer_instance : has_scalar α (matrix m n α)) }
section semiring
variables [semiring α]
def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α
| x y := w x * v y
def mul_vec (M : matrix m n α) (v : n → α) : m → α
| x := finset.univ.sum (λy:n, M x y * v y)
def vec_mul (v : m → α) (M : matrix m n α) : n → α
| y := finset.univ.sum (λx:m, v x * M x y)
instance mul_vec.is_add_monoid_hom_left (v : n → α) :
is_add_monoid_hom (λM:matrix m n α, mul_vec M v) :=
⟨by ext; simp [mul_vec]; refl,
begin
intros x y,
ext m,
rw pi.add_apply (mul_vec x v) (mul_vec y v) m,
simp [mul_vec, finset.sum_add_distrib, right_distrib]
end⟩
lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) :
mul_vec (diagonal v) w x = v x * w x :=
begin
transitivity,
refine finset.sum_eq_single x _ _,
{ assume b _ ne, simp [diagonal, ne.symm] },
{ simp },
{ rw [diagonal_val_eq] }
end
lemma vec_mul_vec_eq (w : m → α) (v : n → α) :
vec_mul_vec w v = (row w).mul (col v) :=
by simp [matrix.mul]; refl
end semiring
def minor (A : matrix m n α) (col : l → m) (row : o → n) : matrix l o α :=
λ i j, A (col i) (row j)
@[reducible]
def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α :=
minor A id (fin.cast_add r)
@[reducible]
def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α :=
minor A id (fin.nat_add l)
@[reducible]
def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α :=
minor A (fin.cast_add d) id
@[reducible]
def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α :=
minor A (fin.nat_add u) id
@[reducible]
def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin u) (fin r) α :=
sub_up (sub_right A)
@[reducible]
def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin d) (fin r) α :=
sub_down (sub_right A)
@[reducible]
def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin u) (fin (l)) α :=
sub_up (sub_left A)
@[reducible]
def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin d) (fin (l)) α :=
sub_down (sub_left A)
end matrix
|
2c3041065bc9c42bdaed25e3f6496919c471995f | 57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5 | /data/seq/wseq.lean | 1d58e1991873323fb4785002915abad10732f539 | [
"Apache-2.0"
] | permissive | louisanu/mathlib | 11f56f2d40dc792bc05ee2f78ea37d73e98ecbfe | 2bd5e2159d20a8f20d04fc4d382e65eea775ed39 | refs/heads/master | 1,617,706,993,439 | 1,523,163,654,000 | 1,523,163,654,000 | 124,519,997 | 0 | 0 | Apache-2.0 | 1,520,588,283,000 | 1,520,588,283,000 | null | UTF-8 | Lean | false | false | 55,268 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.seq.seq data.seq.computation data.list.basic data.dlist
universes u v w
/-
coinductive wseq (α : Type u) : Type u
| nil : wseq α
| cons : α → wseq α → wseq α
| think : wseq α → wseq α
-/
/-- Weak sequences.
While the `seq` structure allows for lists which may not be finite,
a weak sequence also allows the computation of each element to
involve an indeterminate amount of computation, including possibly
an infinite loop. This is represented as a regular `seq` interspersed
with `none` elements to indicate that computation is ongoing.
This model is appropriate for Haskell style lazy lists, and is closed
under most interesting computation patterns on infinite lists,
but conversely it is difficult to extract elements from it. -/
def wseq (α) := seq (option α)
namespace wseq
variables {α : Type u} {β : Type v} {γ : Type w}
/-- Turn a sequence into a weak sequence -/
def of_seq : seq α → wseq α := (<$>) some
/-- Turn a list into a weak sequence -/
def of_list (l : list α) : wseq α := of_seq l
/-- Turn a stream into a weak sequence -/
def of_stream (l : stream α) : wseq α := of_seq l
instance coe_seq : has_coe (seq α) (wseq α) := ⟨of_seq⟩
instance coe_list : has_coe (list α) (wseq α) := ⟨of_list⟩
instance coe_stream : has_coe (stream α) (wseq α) := ⟨of_stream⟩
/-- The empty weak sequence -/
def nil : wseq α := seq.nil
/-- Prepend an element to a weak sequence -/
def cons (a : α) : wseq α → wseq α := seq.cons (some a)
/-- Compute for one tick, without producing any elements -/
def think : wseq α → wseq α := seq.cons none
/-- Destruct a weak sequence, to (eventually possibly) produce either
`none` for `nil` or `some (a, s)` if an element is produced. -/
def destruct : wseq α → computation (option (α × wseq α)) :=
computation.corec (λs, match seq.destruct s with
| none := sum.inl none
| some (none, s') := sum.inr s'
| some (some a, s') := sum.inl (some (a, s'))
end)
def cases_on {C : wseq α → Sort v} (s : wseq α) (h1 : C nil)
(h2 : ∀ x s, C (cons x s)) (h3 : ∀ s, C (think s)) : C s :=
seq.cases_on s h1 (λ o, option.cases_on o h3 h2)
protected def mem (a : α) (s : wseq α) := seq.mem (some a) s
instance : has_mem α (wseq α) :=
⟨wseq.mem⟩
theorem not_mem_nil (a : α) : a ∉ @nil α := seq.not_mem_nil a
/-- Get the head of a weak sequence. This involves a possibly
infinite computation. -/
def head (s : wseq α) : computation (option α) :=
computation.map ((<$>) prod.fst) (destruct s)
/-- Encode a computation yielding a weak sequence into additional
`think` constructors in a weak sequence -/
def flatten : computation (wseq α) → wseq α :=
seq.corec (λc, match computation.destruct c with
| sum.inl s := seq.omap return (seq.destruct s)
| sum.inr c' := some (none, c')
end)
/-- Get the tail of a weak sequence. This doesn't need a `computation`
wrapper, unlike `head`, because `flatten` allows us to hide this
in the construction of the weak sequence itself. -/
def tail (s : wseq α) : wseq α :=
flatten $ (λo, option.rec_on o nil prod.snd) <$> destruct s
/-- drop the first `n` elements from `s`. -/
def drop (s : wseq α) : ℕ → wseq α
| 0 := s
| (n+1) := tail (drop n)
attribute [simp] drop
/-- Get the nth element of `s`. -/
def nth (s : wseq α) (n : ℕ) : computation (option α) := head (drop s n)
/-- Convert `s` to a list (if it is finite and completes in finite time). -/
def to_list (s : wseq α) : computation (list α) :=
@computation.corec (list α) (list α × wseq α) (λ⟨l, s⟩,
match seq.destruct s with
| none := sum.inl l.reverse
| some (none, s') := sum.inr (l, s')
| some (some a, s') := sum.inr (a::l, s')
end) ([], s)
/-- Get the length of `s` (if it is finite and completes in finite time). -/
def length (s : wseq α) : computation ℕ :=
@computation.corec ℕ (ℕ × wseq α) (λ⟨n, s⟩,
match seq.destruct s with
| none := sum.inl n
| some (none, s') := sum.inr (n, s')
| some (some a, s') := sum.inr (n+1, s')
end) (0, s)
/-- A weak sequence is finite if `to_list s` terminates. Equivalently,
it is a finite number of `think` and `cons` applied to `nil`. -/
@[class] def is_finite (s : wseq α) : Prop := (to_list s).terminates
instance to_list_terminates (s : wseq α) [h : is_finite s] : (to_list s).terminates := h
/-- Get the list corresponding to a finite weak sequence. -/
def get (s : wseq α) [is_finite s] : list α := (to_list s).get
/-- A weak sequence is *productive* if it never stalls forever - there are
always a finite number of `think`s between `cons` constructors.
The sequence itself is allowed to be infinite though. -/
@[class] def productive (s : wseq α) : Prop := ∀ n, (nth s n).terminates
instance nth_terminates (s : wseq α) [h : productive s] : ∀ n, (nth s n).terminates := h
instance head_terminates (s : wseq α) [h : productive s] : (head s).terminates := h 0
/-- Replace the `n`th element of `s` with `a`. -/
def update_nth (s : wseq α) (n : ℕ) (a : α) : wseq α :=
@seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩,
match seq.destruct s, n with
| none, n := none
| some (none, s'), n := some (none, n, s')
| some (some a', s'), 0 := some (some a', 0, s')
| some (some a', s'), 1 := some (some a, 0, s')
| some (some a', s'), (n+2) := some (some a', n+1, s')
end) (n+1, s)
/-- Remove the `n`th element of `s`. -/
def remove_nth (s : wseq α) (n : ℕ) : wseq α :=
@seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩,
match seq.destruct s, n with
| none, n := none
| some (none, s'), n := some (none, n, s')
| some (some a', s'), 0 := some (some a', 0, s')
| some (some a', s'), 1 := some (none, 0, s')
| some (some a', s'), (n+2) := some (some a', n+1, s')
end) (n+1, s)
/-- Map the elements of `s` over `f`, removing any values that yield `none`. -/
def filter_map (f : α → option β) : wseq α → wseq β :=
seq.corec (λs, match seq.destruct s with
| none := none
| some (none, s') := some (none, s')
| some (some a, s') := some (f a, s')
end)
/-- Select the elements of `s` that satisfy `p`. -/
def filter (p : α → Prop) [decidable_pred p] : wseq α → wseq α :=
filter_map (λa, if p a then some a else none)
-- example of infinite list manipulations
/-- Get the first element of `s` satisfying `p`. -/
def find (p : α → Prop) [decidable_pred p] (s : wseq α) : computation (option α) :=
head $ filter p s
/-- Zip a function over two weak sequences -/
def zip_with (f : α → β → γ) (s1 : wseq α) (s2 : wseq β) : wseq γ :=
@seq.corec (option γ) (wseq α × wseq β) (λ⟨s1, s2⟩,
match seq.destruct s1, seq.destruct s2 with
| some (none, s1'), some (none, s2') := some (none, s1', s2')
| some (some a1, s1'), some (none, s2') := some (none, s1, s2')
| some (none, s1'), some (some a2, s2') := some (none, s1', s2)
| some (some a1, s1'), some (some a2, s2') := some (some (f a1 a2), s1', s2')
| _, _ := none
end) (s1, s2)
/-- Zip two weak sequences into a single sequence of pairs -/
def zip : wseq α → wseq β → wseq (α × β) := zip_with prod.mk
/-- Get the list of indexes of elements of `s` satisfying `p` -/
def find_indexes (p : α → Prop) [decidable_pred p] (s : wseq α) : wseq ℕ :=
(zip s (stream.nats : wseq ℕ)).filter_map
(λ ⟨a, n⟩, if p a then some n else none)
/-- Get the index of the first element of `s` satisfying `p` -/
def find_index (p : α → Prop) [decidable_pred p] (s : wseq α) : computation ℕ :=
(λ o, option.get_or_else o 0) <$> head (find_indexes p s)
/-- Get the index of the first occurrence of `a` in `s` -/
def index_of [decidable_eq α] (a : α) : wseq α → computation ℕ := find_index (eq a)
/-- Get the indexes of occurrences of `a` in `s` -/
def indexes_of [decidable_eq α] (a : α) : wseq α → wseq ℕ := find_indexes (eq a)
/-- `union s1 s2` is a weak sequence which interleaves `s1` and `s2` in
some order (nondeterministically). -/
def union (s1 s2 : wseq α) : wseq α :=
@seq.corec (option α) (wseq α × wseq α) (λ⟨s1, s2⟩,
match seq.destruct s1, seq.destruct s2 with
| none, none := none
| some (a1, s1'), none := some (a1, s1', nil)
| none, some (a2, s2') := some (a2, nil, s2')
| some (none, s1'), some (none, s2') := some (none, s1', s2')
| some (some a1, s1'), some (none, s2') := some (some a1, s1', s2')
| some (none, s1'), some (some a2, s2') := some (some a2, s1', s2')
| some (some a1, s1'), some (some a2, s2') := some (some a1, cons a2 s1', s2')
end) (s1, s2)
/-- Returns `tt` if `s` is `nil` and `ff` if `s` has an element -/
def is_empty (s : wseq α) : computation bool :=
computation.map option.is_none $ head s
/-- Calculate one step of computation -/
def compute (s : wseq α) : wseq α :=
match seq.destruct s with
| some (none, s') := s'
| _ := s
end
/-- Get the first `n` elements of a weak sequence -/
def take (s : wseq α) (n : ℕ) : wseq α :=
@seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩,
match n, seq.destruct s with
| 0, _ := none
| m+1, none := none
| m+1, some (none, s') := some (none, m+1, s')
| m+1, some (some a, s') := some (some a, m, s')
end) (n, s)
/-- Split the sequence at position `n` into a finite initial segment
and the weak sequence tail -/
def split_at (s : wseq α) (n : ℕ) : computation (list α × wseq α) :=
@computation.corec (list α × wseq α) (ℕ × list α × wseq α) (λ⟨n, l, s⟩,
match n, seq.destruct s with
| 0, _ := sum.inl (l.reverse, s)
| m+1, none := sum.inl (l.reverse, s)
| m+1, some (none, s') := sum.inr (n, l, s')
| m+1, some (some a, s') := sum.inr (m, a::l, s')
end) (n, [], s)
/-- Returns `tt` if any element of `s` satisfies `p` -/
def any (s : wseq α) (p : α → bool) : computation bool :=
computation.corec (λs : wseq α,
match seq.destruct s with
| none := sum.inl ff
| some (none, s') := sum.inr s'
| some (some a, s') := if p a then sum.inl tt else sum.inr s'
end) s
/-- Returns `tt` if every element of `s` satisfies `p` -/
def all (s : wseq α) (p : α → bool) : computation bool :=
computation.corec (λs : wseq α,
match seq.destruct s with
| none := sum.inl tt
| some (none, s') := sum.inr s'
| some (some a, s') := if p a then sum.inr s' else sum.inl ff
end) s
/-- Apply a function to the elements of the sequence to produce a sequence
of partial results. (There is no `scanr` because this would require
working from the end of the sequence, which may not exist.) -/
def scanl (f : α → β → α) (a : α) (s : wseq β) : wseq α :=
cons a $ @seq.corec (option α) (α × wseq β) (λ⟨a, s⟩,
match seq.destruct s with
| none := none
| some (none, s') := some (none, a, s')
| some (some b, s') := let a' := f a b in some (some a', a', s')
end) (a, s)
/-- Get the weak sequence of initial segments of the input sequence -/
def inits (s : wseq α) : wseq (list α) :=
cons [] $ @seq.corec (option (list α)) (dlist α × wseq α) (λ ⟨l, s⟩,
match seq.destruct s with
| none := none
| some (none, s') := some (none, l, s')
| some (some a, s') := let l' := l.concat a in
some (some l'.to_list, l', s')
end) (dlist.empty, s)
/-- Like take, but does not wait for a result. Calculates `n` steps of
computation and returns the sequence computed so far -/
def collect (s : wseq α) (n : ℕ) : list α :=
(seq.take n s).filter_map id
/-- Append two weak sequences. As with `seq.append`, this may not use
the second sequence if the first one takes forever to compute -/
def append : wseq α → wseq α → wseq α := seq.append
/-- Map a function over a weak sequence -/
def map (f : α → β) : wseq α → wseq β := seq.map (option.map f)
/-- Flatten a sequence of weak sequences. (Note that this allows
empty sequences, unlike `seq.join`.) -/
def join (S : wseq (wseq α)) : wseq α :=
seq.join ((λo : option (wseq α), match o with
| none := seq1.ret none
| some s := (none, s)
end) <$> S)
/-- Monadic bind operator for weak sequences -/
def bind (s : wseq α) (f : α → wseq β) : wseq β :=
join (map f s)
@[simp] def lift_rel_o (R : α → β → Prop) (C : wseq α → wseq β → Prop) :
option (α × wseq α) → option (β × wseq β) → Prop
| none none := true
| (some (a, s)) (some (b, t)) := R a b ∧ C s t
| _ _ := false
theorem lift_rel_o.imp {R S : α → β → Prop} {C D : wseq α → wseq β → Prop}
(H1 : ∀ a b, R a b → S a b) (H2 : ∀ s t, C s t → D s t) :
∀ {o p}, lift_rel_o R C o p → lift_rel_o S D o p
| none none h := trivial
| (some (a, s)) (some (b, t)) h := and.imp (H1 _ _) (H2 _ _) h
| none (some _) h := false.elim h
| (some (_, _)) none h := false.elim h
theorem lift_rel_o.imp_right (R : α → β → Prop) {C D : wseq α → wseq β → Prop}
(H : ∀ s t, C s t → D s t) {o p} : lift_rel_o R C o p → lift_rel_o R D o p :=
lift_rel_o.imp (λ _ _, id) H
@[simp] def bisim_o (R : wseq α → wseq α → Prop) :
option (α × wseq α) → option (α × wseq α) → Prop := lift_rel_o (=) R
theorem bisim_o.imp {R S : wseq α → wseq α → Prop} (H : ∀ s t, R s t → S s t) {o p} :
bisim_o R o p → bisim_o S o p :=
lift_rel_o.imp_right _ H
/-- Two weak sequences are `lift_rel R` related if they are either both empty,
or they are both nonempty and the heads are `R` related and the tails are
`lift_rel R` related. (This is a coinductive definition.) -/
def lift_rel (R : α → β → Prop) (s : wseq α) (t : wseq β) : Prop :=
∃ C : wseq α → wseq β → Prop, C s t ∧
∀ {s t}, C s t → computation.lift_rel (lift_rel_o R C) (destruct s) (destruct t)
/-- If two sequences are equivalent, then they have the same values and
the same computational behavior (i.e. if one loops forever then so does
the other), although they may differ in the number of `think`s needed to
arrive at the answer. -/
def equiv : wseq α → wseq α → Prop := lift_rel (=)
theorem lift_rel_destruct {R : α → β → Prop} {s : wseq α} {t : wseq β} :
lift_rel R s t →
computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t)
| ⟨R, h1, h2⟩ :=
by refine computation.lift_rel.imp _ _ _ (h2 h1);
apply lift_rel_o.imp_right; exact λ s' t' h', ⟨R, h', @h2⟩
theorem lift_rel_destruct_iff {R : α → β → Prop} {s : wseq α} {t : wseq β} :
lift_rel R s t ↔
computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) :=
⟨lift_rel_destruct, λ h, ⟨λ s t, lift_rel R s t ∨
computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t),
or.inr h, λ s t h, begin
have h : computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t),
{ cases h with h h, exact lift_rel_destruct h, assumption },
apply computation.lift_rel.imp _ _ _ h,
intros a b, apply lift_rel_o.imp_right,
intros s t, apply or.inl
end⟩⟩
infix ~ := equiv
theorem destruct_congr {s t : wseq α} :
s ~ t → computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) :=
lift_rel_destruct
theorem destruct_congr_iff {s t : wseq α} :
s ~ t ↔ computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) :=
lift_rel_destruct_iff
theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) :=
λ s, begin
refine ⟨(=), rfl, λ s t (h : s = t), _⟩,
rw ←h, apply computation.lift_rel.refl,
intro a, cases a with a, simp, cases a; simp, apply H
end
theorem lift_rel_o.swap (R : α → β → Prop) (C) :
function.swap (lift_rel_o R C) = lift_rel_o (function.swap R) (function.swap C) :=
by funext x y; cases x with x; [skip, cases x]; { cases y with y; [skip, cases y]; refl }
theorem lift_rel.swap_lem {R : α → β → Prop} {s1 s2} (h : lift_rel R s1 s2) :
lift_rel (function.swap R) s2 s1 :=
begin
refine ⟨function.swap (lift_rel R), h, λ s t (h : lift_rel R t s), _⟩,
rw [←lift_rel_o.swap, computation.lift_rel.swap],
apply lift_rel_destruct h
end
theorem lift_rel.swap (R : α → β → Prop) :
function.swap (lift_rel R) = lift_rel (function.swap R) :=
funext $ λ x, funext $ λ y, propext ⟨lift_rel.swap_lem, lift_rel.swap_lem⟩
theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) :=
λ s1 s2 (h : function.swap (lift_rel R) s2 s1),
by rwa [lift_rel.swap, show function.swap R = R, from
funext $ λ a, funext $ λ b, propext $ by constructor; apply H] at h
theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) :=
λ s t u h1 h2, begin
refine ⟨λ s u, ∃ t, lift_rel R s t ∧ lift_rel R t u, ⟨t, h1, h2⟩, λ s u h, _⟩,
cases h with t h, cases h with h1 h2,
have h1 := lift_rel_destruct h1,
have h2 := lift_rel_destruct h2,
refine computation.lift_rel_def.2
⟨(computation.terminates_of_lift_rel h1).trans
(computation.terminates_of_lift_rel h2), λ a c ha hc, _⟩,
cases h1.left ha with b hb, cases hb with hb t1,
have t2 := computation.rel_of_lift_rel h2 hb hc,
cases a with a; cases c with c,
{ trivial },
{ cases b, {cases t2}, {cases t1} },
{ cases a, cases b with b, {cases t1}, {cases b, cases t2} },
{ cases a with a s, cases b with b, {cases t1},
cases b with b t, cases c with c u,
cases t1 with ab st, cases t2 with bc tu,
exact ⟨H ab bc, t, st, tu⟩ }
end
theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R)
| ⟨refl, symm, trans⟩ :=
⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩
@[refl] theorem equiv.refl : ∀ (s : wseq α), s ~ s :=
lift_rel.refl (=) eq.refl
@[symm] theorem equiv.symm : ∀ {s t : wseq α}, s ~ t → t ~ s :=
lift_rel.symm (=) (@eq.symm _)
@[trans] theorem equiv.trans : ∀ {s t u : wseq α}, s ~ t → t ~ u → s ~ u :=
lift_rel.trans (=) (@eq.trans _)
theorem equiv.equivalence : equivalence (@equiv α) :=
⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩
open computation
local notation `return` := computation.return
@[simp] theorem destruct_nil : destruct (nil : wseq α) = return none :=
computation.destruct_eq_ret rfl
@[simp] theorem destruct_cons (a : α) (s) : destruct (cons a s) = return (some (a, s)) :=
computation.destruct_eq_ret $ by simp [destruct, cons, computation.rmap]
@[simp] theorem destruct_think (s : wseq α) : destruct (think s) = (destruct s).think :=
computation.destruct_eq_think $ by simp [destruct, think, computation.rmap]
@[simp] theorem seq_destruct_nil : seq.destruct (nil : wseq α) = none :=
seq.destruct_nil
@[simp] theorem seq_destruct_cons (a : α) (s) : seq.destruct (cons a s) = some (some a, s) :=
seq.destruct_cons _ _
@[simp] theorem seq_destruct_think (s : wseq α) : seq.destruct (think s) = some (none, s) :=
seq.destruct_cons _ _
@[simp] theorem head_nil : head (nil : wseq α) = return none := by simp [head]; refl
@[simp] theorem head_cons (a : α) (s) : head (cons a s) = return (some a) := by simp [head]; refl
@[simp] theorem head_think (s : wseq α) : head (think s) = (head s).think := by simp [head]; refl
@[simp] theorem flatten_ret (s : wseq α) : flatten (return s) = s :=
begin
refine seq.eq_of_bisim (λs1 s2, flatten (return s2) = s1) _ rfl,
intros s' s h, rw ←h, simp [flatten],
cases seq.destruct s, { simp },
{ cases val with o s', simp }
end
@[simp] theorem flatten_think (c : computation (wseq α)) : flatten c.think = think (flatten c) :=
seq.destruct_eq_cons $ by simp [flatten, think]
@[simp] theorem destruct_flatten (c : computation (wseq α)) : destruct (flatten c) = c >>= destruct :=
begin
refine computation.eq_of_bisim (λc1 c2, c1 = c2 ∨
∃ c, c1 = destruct (flatten c) ∧ c2 = computation.bind c destruct) _ (or.inr ⟨c, rfl, rfl⟩),
intros c1 c2 h, exact match c1, c2, h with
| _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp
| _, _, (or.inr ⟨c, rfl, rfl⟩) := begin
apply c.cases_on (λa, _) (λc', _); repeat {simp},
{ cases (destruct a).destruct; simp },
{ exact or.inr ⟨c', rfl, rfl⟩ }
end end
end
theorem head_terminates_iff (s : wseq α) : terminates (head s) ↔ terminates (destruct s) :=
terminates_map_iff _ (destruct s)
@[simp] theorem tail_nil : tail (nil : wseq α) = nil := by simp [tail]
@[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by simp [tail]
@[simp] theorem tail_think (s : wseq α) : tail (think s) = (tail s).think := by simp [tail]
@[simp] theorem dropn_nil (n) :
drop (nil : wseq α) n = nil := by induction n; simp [*, drop]
@[simp] theorem dropn_cons (a : α) (s) (n) :
drop (cons a s) (n+1) = drop s n := by induction n; simp [*, drop]
@[simp] theorem dropn_think (s : wseq α) (n) :
drop (think s) n = (drop s n).think := by induction n; simp [*, drop]
theorem dropn_add (s : wseq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n
| 0 := rfl
| (n+1) := congr_arg tail (dropn_add n)
theorem dropn_tail (s : wseq α) (n) : drop (tail s) n = drop s (n + 1) :=
by rw add_comm; symmetry; apply dropn_add
theorem nth_add (s : wseq α) (m n) : nth s (m + n) = nth (drop s m) n :=
congr_arg head (dropn_add _ _ _)
theorem nth_tail (s : wseq α) (n) : nth (tail s) n = nth s (n + 1) :=
congr_arg head (dropn_tail _ _)
@[simp] theorem join_nil : join nil = (nil : wseq α) := seq.join_nil
@[simp] theorem join_think (S : wseq (wseq α)) :
join (think S) = think (join S) :=
by { simp [think, join], unfold functor.map, simp [join, seq1.ret] }
@[simp] theorem join_cons (s : wseq α) (S) :
join (cons s S) = think (append s (join S)) :=
by { simp [think, join], unfold functor.map, simp [join, cons, append] }
@[simp] theorem nil_append (s : wseq α) : append nil s = s := seq.nil_append _
@[simp] theorem cons_append (a : α) (s t) :
append (cons a s) t = cons a (append s t) := seq.cons_append _ _ _
@[simp] theorem think_append (s t : wseq α) :
append (think s) t = think (append s t) := seq.cons_append _ _ _
@[simp] theorem append_nil (s : wseq α) : append s nil = s := seq.append_nil _
@[simp] theorem append_assoc (s t u : wseq α) :
append (append s t) u = append s (append t u) := seq.append_assoc _ _ _
@[simp] def tail.aux : option (α × wseq α) → computation (option (α × wseq α))
| none := return none
| (some (a, s)) := destruct s
theorem destruct_tail (s : wseq α) :
destruct (tail s) = destruct s >>= tail.aux :=
begin
dsimp [tail], simp, rw [← bind_pure_comp_eq_map, is_lawful_monad.bind_assoc],
apply congr_arg, funext o,
rcases o with _|⟨a, s⟩;
apply (@pure_bind computation _ _ _ _ _ _).trans _; simp
end
@[simp] def drop.aux : ℕ → option (α × wseq α) → computation (option (α × wseq α))
| 0 := return
| (n+1) := λ a, tail.aux a >>= drop.aux n
theorem drop.aux_none : ∀ n, @drop.aux α n none = return none
| 0 := rfl
| (n+1) := show computation.bind (return none) (drop.aux n) = return none,
by rw [ret_bind, drop.aux_none]
theorem destruct_dropn :
∀ (s : wseq α) n, destruct (drop s n) = destruct s >>= drop.aux n
| s 0 := (bind_ret' _).symm
| s (n+1) := by rw [← dropn_tail, destruct_dropn _ n,
destruct_tail, is_lawful_monad.bind_assoc]; refl
theorem head_terminates_of_head_tail_terminates (s : wseq α) [T : terminates (head (tail s))] :
terminates (head s) :=
(head_terminates_iff _).2 $ begin
cases (head_terminates_iff _).1 T with a h,
simp [tail] at h,
cases exists_of_mem_bind h with s' h1, cases h1 with h1 h2,
unfold functor.map at h1,
exact let ⟨t, h3, h4⟩ := exists_of_mem_map h1 in terminates_of_mem h3
end
theorem destruct_some_of_destruct_tail_some {s : wseq α} {a}
(h : some a ∈ destruct (tail s)) : ∃ a', some a' ∈ destruct s :=
begin
unfold tail functor.map at h, simp at h,
cases exists_of_mem_bind h with t ht, cases ht with tm td, clear h,
cases exists_of_mem_map tm with t' ht', cases ht' with ht' ht2, clear tm,
cases t' with t'; rw ←ht2 at td; simp at td,
{ have := mem_unique td (ret_mem _), contradiction },
{ exact ⟨_, ht'⟩ }
end
theorem head_some_of_head_tail_some {s : wseq α} {a}
(h : some a ∈ head (tail s)) : ∃ a', some a' ∈ head s :=
begin
unfold head at h,
cases exists_of_mem_map h with o ho, cases ho with md e, clear h,
cases o with o; injection e with h', clear e h',
cases destruct_some_of_destruct_tail_some md with a am,
exact ⟨_, mem_map ((<$>) (@prod.fst α (wseq α))) am⟩
end
theorem head_some_of_nth_some {s : wseq α} {a n}
(h : some a ∈ nth s n) : ∃ a', some a' ∈ head s :=
begin
revert a, induction n with n IH; intros,
exacts [⟨_, h⟩, let ⟨a', h'⟩ := head_some_of_head_tail_some h in IH h']
end
instance productive_tail (s : wseq α) [productive s] : productive (tail s) :=
λ n, by rw [nth_tail]; apply_instance
instance productive_dropn (s : wseq α) [productive s] (n) : productive (drop s n) :=
λ m, by rw [←nth_add]; apply_instance
/-- Given a productive weak sequence, we can collapse all the `think`s to
produce a sequence. -/
def to_seq (s : wseq α) [productive s] : seq α :=
⟨λ n, (nth s n).get, λn h,
begin
induction e : computation.get (nth s (n + 1)), {trivial},
have := mem_of_get_eq _ e,
simp [nth] at this h, cases head_some_of_head_tail_some this with a' h',
have := mem_unique h' (@mem_of_get_eq _ _ _ _ h),
contradiction
end⟩
theorem nth_terminates_le {s : wseq α} {m n} (h : m ≤ n) : terminates (nth s n) → terminates (nth s m) :=
by induction h with m' h IH; [exact id,
exact λ T, IH (@head_terminates_of_head_tail_terminates _ _ T)]
theorem head_terminates_of_nth_terminates {s : wseq α} {n} : terminates (nth s n) → terminates (head s) :=
nth_terminates_le (nat.zero_le n)
theorem destruct_terminates_of_nth_terminates {s : wseq α} {n} (T : terminates (nth s n)) : terminates (destruct s) :=
(head_terminates_iff _).1 $ head_terminates_of_nth_terminates T
theorem mem_rec_on {C : wseq α → Prop} {a s} (M : a ∈ s)
(h1 : ∀ b s', (a = b ∨ C s') → C (cons b s'))
(h2 : ∀ s, C s → C (think s)) : C s :=
begin
apply seq.mem_rec_on M,
intros o s' h, cases o with b,
{ apply h2, cases h, {contradiction}, {assumption} },
{ apply h1, apply or.imp_left _ h, intro h, injection h }
end
@[simp] theorem mem_think (s : wseq α) (a) : a ∈ think s ↔ a ∈ s :=
begin
cases s with f al,
change some (some a) ∈ some none :: f ↔ some (some a) ∈ f,
constructor; intro h,
{ apply (stream.eq_or_mem_of_mem_cons h).resolve_left,
intro, injections },
{ apply stream.mem_cons_of_mem _ h }
end
theorem eq_or_mem_iff_mem {s : wseq α} {a a' s'} :
some (a', s') ∈ destruct s → (a ∈ s ↔ a = a' ∨ a ∈ s') :=
begin
generalize e : destruct s = c, intro h,
revert s, apply computation.mem_rec_on h _ (λ c IH, _); intro s;
apply s.cases_on _ (λ x s, _) (λ s, _); intros m;
have := congr_arg computation.destruct m; simp at this;
cases this with i1 i2,
{ rw [i1, i2],
cases s' with f al,
unfold cons has_mem.mem wseq.mem seq.mem seq.cons, simp,
have h_a_eq_a' : a = a' ↔ some (some a) = some (some a'), {simp},
rw [h_a_eq_a'],
refine ⟨stream.eq_or_mem_of_mem_cons, λo, _⟩,
{ cases o with e m,
{ rw e, apply stream.mem_cons },
{ exact stream.mem_cons_of_mem _ m } } },
{ simp, exact IH this }
end
@[simp] theorem mem_cons_iff (s : wseq α) (b) {a} : a ∈ cons b s ↔ a = b ∨ a ∈ s :=
eq_or_mem_iff_mem $ by simp [ret_mem]
theorem mem_cons_of_mem {s : wseq α} (b) {a} (h : a ∈ s) : a ∈ cons b s :=
(mem_cons_iff _ _).2 (or.inr h)
theorem mem_cons (s : wseq α) (a) : a ∈ cons a s :=
(mem_cons_iff _ _).2 (or.inl rfl)
theorem mem_of_mem_tail {s : wseq α} {a} : a ∈ tail s → a ∈ s :=
begin
intro h, have := h, cases h with n e, revert s, simp [stream.nth],
induction n with n IH; intro s; apply s.cases_on _ (λx s, _) (λ s, _);
repeat{simp}; intros m e; injections,
{ exact or.inr m },
{ exact or.inr m },
{ apply IH m, rw e, cases tail s, refl }
end
theorem mem_of_mem_dropn {s : wseq α} {a} : ∀ {n}, a ∈ drop s n → a ∈ s
| 0 h := h
| (n+1) h := @mem_of_mem_dropn n (mem_of_mem_tail h)
theorem nth_mem {s : wseq α} {a n} : some a ∈ nth s n → a ∈ s :=
begin
revert s, induction n with n IH; intros s h,
{ cases exists_of_mem_map h with o h, cases h with h1 h2,
cases o with o; injection h2 with h',
cases o with a' s',
exact (eq_or_mem_iff_mem h1).2 (or.inl h'.symm) },
{ have := @IH (tail s), rw nth_tail at this,
exact mem_of_mem_tail (this h) }
end
theorem exists_nth_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n, some a ∈ nth s n :=
begin
apply mem_rec_on h,
{ intros a' s' h, cases h with h h,
{ existsi 0, simp [nth], rw h, apply ret_mem },
{ cases h with n h, existsi n+1,
simp [nth], exact h } },
{ intros s' h, cases h with n h,
existsi n, simp [nth], apply think_mem h }
end
theorem exists_dropn_of_mem {s : wseq α} {a} (h : a ∈ s) :
∃ n s', some (a, s') ∈ destruct (drop s n) :=
let ⟨n, h⟩ := exists_nth_of_mem h in ⟨n, begin
cases (head_terminates_iff _).1 ⟨_, h⟩ with o om,
have := mem_unique (mem_map _ om) h,
cases o with o; injection this with i,
cases o with a' s', dsimp at i,
rw i at om, exact ⟨_, om⟩
end⟩
theorem lift_rel_dropn_destruct {R : α → β → Prop} {s t} (H : lift_rel R s t) :
∀ n, computation.lift_rel (lift_rel_o R (lift_rel R))
(destruct (drop s n)) (destruct (drop t n))
| 0 := lift_rel_destruct H
| (n+1) := begin
simp [destruct_tail],
apply lift_rel_bind,
apply lift_rel_dropn_destruct n,
exact λ a b o, match a, b, o with
| none, none, _ := by simp
| some (a, s), some (b, t), ⟨h1, h2⟩ := by simp [tail.aux]; apply lift_rel_destruct h2
end
end
theorem exists_of_lift_rel_left {R : α → β → Prop} {s t}
(H : lift_rel R s t) {a} (h : a ∈ s) : ∃ {b}, b ∈ t ∧ R a b :=
let ⟨n, h⟩ := exists_nth_of_mem h,
⟨some (._, s'), sd, rfl⟩ := exists_of_mem_map h,
⟨some (b, t'), td, ⟨ab, _⟩⟩ := (lift_rel_dropn_destruct H n).left sd in
⟨b, nth_mem (mem_map ((<$>) prod.fst.{v v}) td), ab⟩
theorem exists_of_lift_rel_right {R : α → β → Prop} {s t}
(H : lift_rel R s t) {b} (h : b ∈ t) : ∃ {a}, a ∈ s ∧ R a b :=
by rw ←lift_rel.swap at H; exact exists_of_lift_rel_left H h
theorem head_terminates_of_mem {s : wseq α} {a} (h : a ∈ s) : terminates (head s) :=
let ⟨n, h⟩ := exists_nth_of_mem h in head_terminates_of_nth_terminates ⟨_, h⟩
theorem of_mem_append {s₁ s₂ : wseq α} {a : α} : a ∈ append s₁ s₂ → a ∈ s₁ ∨ a ∈ s₂ :=
seq.of_mem_append
theorem mem_append_left {s₁ s₂ : wseq α} {a : α} : a ∈ s₁ → a ∈ append s₁ s₂ :=
seq.mem_append_left
theorem exists_of_mem_map {f} {b : β} : ∀ {s : wseq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b
| ⟨g, al⟩ h := let ⟨o, om, oe⟩ := seq.exists_of_mem_map h in
by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩
@[simp] theorem lift_rel_nil (R : α → β → Prop) : lift_rel R nil nil :=
by rw [lift_rel_destruct_iff]; simp
@[simp] theorem lift_rel_cons (R : α → β → Prop) (a b s t) :
lift_rel R (cons a s) (cons b t) ↔ R a b ∧ lift_rel R s t :=
by rw [lift_rel_destruct_iff]; simp
@[simp] theorem lift_rel_think_left (R : α → β → Prop) (s t) :
lift_rel R (think s) t ↔ lift_rel R s t :=
by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp
@[simp] theorem lift_rel_think_right (R : α → β → Prop) (s t) :
lift_rel R s (think t) ↔ lift_rel R s t :=
by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp
theorem cons_congr {s t : wseq α} (a : α) (h : s ~ t) : cons a s ~ cons a t :=
by unfold equiv; simp; exact h
theorem think_equiv (s : wseq α) : think s ~ s :=
by unfold equiv; simp; apply equiv.refl
theorem think_congr {s t : wseq α} (a : α) (h : s ~ t) : think s ~ think t :=
by unfold equiv; simp; exact h
theorem head_congr : ∀ {s t : wseq α}, s ~ t → head s ~ head t :=
suffices ∀ {s t : wseq α}, s ~ t → ∀ {o}, o ∈ head s → o ∈ head t, from
λ s t h o, ⟨this h, this h.symm⟩,
begin
intros s t h o ho,
cases @computation.exists_of_mem_map _ _ _ _ (destruct s) ho with ds dsm,
cases dsm with dsm dse, rw ←dse,
cases destruct_congr h with l r,
cases l dsm with dt dtm, cases dtm with dtm dst,
cases ds with a; cases dt with b,
{ apply mem_map _ dtm },
{ cases b, cases dst },
{ cases a, cases dst },
{ cases a with a s', cases b with b t', rw dst.left,
exact @mem_map _ _ (@functor.map _ _ (α × wseq α) _ prod.fst)
_ (destruct t) dtm }
end
theorem flatten_equiv {c : computation (wseq α)} {s} (h : s ∈ c) : flatten c ~ s :=
begin
apply computation.mem_rec_on h, { simp },
{ intro s', apply equiv.trans, simp [think_equiv] }
end
theorem lift_rel_flatten {R : α → β → Prop} {c1 : computation (wseq α)} {c2 : computation (wseq β)}
(h : c1.lift_rel (lift_rel R) c2) : lift_rel R (flatten c1) (flatten c2) :=
let S := λ s t,
∃ c1 c2, s = flatten c1 ∧ t = flatten c2 ∧ computation.lift_rel (lift_rel R) c1 c2 in
⟨S, ⟨c1, c2, rfl, rfl, h⟩, λ s t h,
match s, t, h with ._, ._, ⟨c1, c2, rfl, rfl, h⟩ := begin
simp, apply lift_rel_bind _ _ h,
intros a b ab, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct ab),
intros a b, apply lift_rel_o.imp_right,
intros s t h, refine ⟨return s, return t, _, _, _⟩; simp [h]
end end⟩
theorem flatten_congr {c1 c2 : computation (wseq α)} :
computation.lift_rel equiv c1 c2 → flatten c1 ~ flatten c2 := lift_rel_flatten
theorem tail_congr {s t : wseq α} (h : s ~ t) : tail s ~ tail t :=
begin
apply flatten_congr,
unfold functor.map, rw [←bind_ret, ←bind_ret],
apply lift_rel_bind _ _ (destruct_congr h),
intros a b h, simp,
cases a with a; cases b with b,
{ trivial },
{ cases h },
{ cases a, cases h },
{ cases a with a s', cases b with b t', exact h.right }
end
theorem dropn_congr {s t : wseq α} (h : s ~ t) (n) : drop s n ~ drop t n :=
by induction n; simp [*, tail_congr]
theorem nth_congr {s t : wseq α} (h : s ~ t) (n) : nth s n ~ nth t n :=
head_congr (dropn_congr h _)
theorem mem_congr {s t : wseq α} (h : s ~ t) (a) : a ∈ s ↔ a ∈ t :=
suffices ∀ {s t : wseq α}, s ~ t → a ∈ s → a ∈ t, from ⟨this h, this h.symm⟩,
λ s t h as, let ⟨n, hn⟩ := exists_nth_of_mem as in
nth_mem ((nth_congr h _ _).1 hn)
theorem productive_congr {s t : wseq α} (h : s ~ t) : productive s ↔ productive t :=
forall_congr $ λn, terminates_congr $ nth_congr h _
theorem equiv.ext {s t : wseq α} (h : ∀ n, nth s n ~ nth t n) : s ~ t :=
⟨λ s t, ∀ n, nth s n ~ nth t n, h, λs t h, begin
refine lift_rel_def.2 ⟨_, _⟩,
{ rw [←head_terminates_iff, ←head_terminates_iff],
exact terminates_congr (h 0) },
{ intros a b ma mb,
cases a with a; cases b with b,
{ trivial },
{ injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) },
{ injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) },
{ cases a with a s', cases b with b t',
injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) with ab,
refine ⟨ab, λ n, _⟩,
refine (nth_congr (flatten_equiv (mem_map _ ma)) n).symm.trans
((_ : nth (tail s) n ~ nth (tail t) n).trans
(nth_congr (flatten_equiv (mem_map _ mb)) n)),
rw [nth_tail, nth_tail], apply h } }
end⟩
theorem length_eq_map (s : wseq α) : length s = computation.map list.length (to_list s) :=
begin
refine eq_of_bisim
(λ c1 c2, ∃ (l : list α) (s : wseq α),
c1 = corec length._match_2 (l.length, s) ∧
c2 = computation.map list.length (corec to_list._match_2 (l, s)))
_ ⟨[], s, rfl, rfl⟩,
intros s1 s2 h, cases h with l h, cases h with s h, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _);
repeat {simp [to_list, nil, cons, think, length]},
{ refine ⟨a::l, s, _, _⟩; simp },
{ refine ⟨l, s, _, _⟩; simp }
end
@[simp] theorem of_list_nil : of_list [] = (nil : wseq α) := rfl
@[simp] theorem of_list_cons (a : α) (l) :
of_list (a :: l) = cons a (of_list l) :=
show seq.map some (seq.of_list (a :: l)) =
seq.cons (some a) (seq.map some (seq.of_list l)), by simp
@[simp] theorem to_list'_nil (l : list α) :
corec to_list._match_2 (l, nil) = return l.reverse :=
destruct_eq_ret rfl
@[simp] theorem to_list'_cons (l : list α) (s : wseq α) (a : α) :
corec to_list._match_2 (l, cons a s) =
(corec to_list._match_2 (a::l, s)).think :=
destruct_eq_think $ by simp [to_list, cons]
@[simp] theorem to_list'_think (l : list α) (s : wseq α) :
corec to_list._match_2 (l, think s) =
(corec to_list._match_2 (l, s)).think :=
destruct_eq_think $ by simp [to_list, think]
theorem to_list'_map (l : list α) (s : wseq α) :
corec to_list._match_2 (l, s) =
((++) l.reverse) <$> to_list s :=
begin
refine eq_of_bisim
(λ c1 c2, ∃ (l' : list α) (s : wseq α),
c1 = corec to_list._match_2 (l' ++ l, s) ∧
c2 = computation.map ((++) l.reverse) (corec to_list._match_2 (l', s)))
_ ⟨[], s, rfl, rfl⟩,
intros s1 s2 h, cases h with l' h, cases h with s h, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _);
repeat {simp [to_list, nil, cons, think, length]},
{ refine ⟨a::l', s, _, _⟩; simp },
{ refine ⟨l', s, _, _⟩; simp }
end
@[simp] theorem to_list_cons (a : α) (s) :
to_list (cons a s) = (list.cons a <$> to_list s).think :=
destruct_eq_think $ by unfold to_list; simp; rw to_list'_map; simp; refl
@[simp] theorem to_list_nil : to_list (nil : wseq α) = return [] :=
destruct_eq_ret rfl
theorem to_list_of_list (l : list α) : l ∈ to_list (of_list l) :=
by induction l with a l IH; simp [ret_mem]; exact think_mem (mem_map _ IH)
@[simp] theorem destruct_of_seq (s : seq α) :
destruct (of_seq s) = return (s.head.map $ λ a, (a, of_seq s.tail)) :=
destruct_eq_ret $ begin
simp [of_seq, head, destruct, seq.destruct, seq.head],
rw [show seq.nth (some <$> s) 0 = some <$> seq.nth s 0, by apply seq.map_nth],
cases seq.nth s 0 with a, { refl },
unfold functor.map,
simp [option.map, option.bind, destruct]
end
@[simp] theorem head_of_seq (s : seq α) : head (of_seq s) = return s.head :=
by simp [head]; cases seq.head s; refl
@[simp] theorem tail_of_seq (s : seq α) : tail (of_seq s) = of_seq s.tail :=
begin
simp [tail], apply s.cases_on _ (λ x s, _); simp [of_seq], {refl},
rw [seq.head_cons, seq.tail_cons], refl
end
@[simp] theorem dropn_of_seq (s : seq α) : ∀ n, drop (of_seq s) n = of_seq (s.drop n)
| 0 := rfl
| (n+1) := by dsimp [drop]; rw [dropn_of_seq, tail_of_seq]
theorem nth_of_seq (s : seq α) (n) : nth (of_seq s) n = return (seq.nth s n) :=
by dsimp [nth]; rw [dropn_of_seq, head_of_seq, seq.head_dropn]
instance productive_of_seq (s : seq α) : productive (of_seq s) :=
λ n, by rw nth_of_seq; apply_instance
theorem to_seq_of_seq (s : seq α) : to_seq (of_seq s) = s :=
begin
apply subtype.eq, funext n,
dsimp [to_seq], apply get_eq_of_mem,
rw nth_of_seq, apply ret_mem
end
/-- The monadic `return a` is a singleton list containing `a`. -/
def ret (a : α) : wseq α := of_list [a]
@[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl
@[simp] theorem map_cons (f : α → β) (a s) :
map f (cons a s) = cons (f a) (map f s) := seq.map_cons _ _ _
@[simp] theorem map_think (f : α → β) (s) :
map f (think s) = think (map f s) := seq.map_cons _ _ _
@[simp] theorem map_id (s : wseq α) : map id s = s := by simp [map]
@[simp] theorem map_ret (f : α → β) (a) : map f (ret a) = ret (f a) := by simp [ret]
@[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) :=
seq.map_append _ _ _
theorem map_comp (f : α → β) (g : β → γ) (s : wseq α) :
map (g ∘ f) s = map g (map f s) :=
begin
dsimp [map], rw ←seq.map_comp,
apply congr_fun, apply congr_arg,
funext o, cases o; refl
end
theorem mem_map (f : α → β) {a : α} {s : wseq α} : a ∈ s → f a ∈ map f s :=
seq.mem_map (option.map f)
-- The converse is not true without additional assumptions
theorem exists_of_mem_join {a : α} : ∀ {S : wseq (wseq α)}, a ∈ join S → ∃ s, s ∈ S ∧ a ∈ s :=
suffices ∀ ss : wseq α, a ∈ ss → ∀ s S, append s (join S) = ss →
a ∈ append s (join S) → a ∈ s ∨ ∃ s, s ∈ S ∧ a ∈ s, from λ S h,
(this _ h nil S (by simp) (by simp [h])).resolve_left (not_mem_nil _),
begin
intros ss h, apply mem_rec_on h (λ b ss o, _) (λ ss IH, _); intros s S,
{ refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _);
intros ej m; simp at ej;
have := congr_arg seq.destruct ej; simp at this;
try {cases this}; try {contradiction},
substs b' ss,
simp at m ⊢,
cases o with e IH, { simp [e] },
cases m with e m, { simp [e] },
exact or.imp_left or.inr (IH _ _ rfl m) },
{ refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _);
intros ej m; simp at ej;
have := congr_arg seq.destruct ej; simp at this;
try { try {have := this.1}, contradiction }; subst ss,
{ apply or.inr, simp at m ⊢,
cases IH s S rfl m with as ex,
{ exact ⟨s, or.inl rfl, as⟩ },
{ rcases ex with ⟨s', sS, as⟩,
exact ⟨s', or.inr sS, as⟩ } },
{ apply or.inr, simp at m,
rcases (IH nil S (by simp) (by simp [m])).resolve_left (not_mem_nil _) with ⟨s, sS, as⟩,
exact ⟨s, by simp [sS], as⟩ },
{ simp at m IH ⊢, apply IH _ _ rfl m } }
end
theorem exists_of_mem_bind {s : wseq α} {f : α → wseq β} {b}
(h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a :=
let ⟨t, tm, bt⟩ := exists_of_mem_join h,
⟨a, as, e⟩ := exists_of_mem_map tm in ⟨a, as, by rwa e⟩
theorem destruct_map (f : α → β) (s : wseq α) :
destruct (map f s) = computation.map (option.map (prod.map f (map f))) (destruct s) :=
begin
apply eq_of_bisim (λ c1 c2, ∃ s, c1 = destruct (map f s) ∧
c2 = computation.map (option.map (prod.map f (map f))) (destruct s)),
{ intros c1 c2 h, cases h with s h, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _); simp; simp,
{ refl }, { refl }, { exact ⟨s, rfl, rfl⟩ } },
{ exact ⟨s, rfl, rfl⟩ }
end
theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop)
{s1 : wseq α} {s2 : wseq β}
{f1 : α → γ} {f2 : β → δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b))
: lift_rel S (map f1 s1) (map f2 s2) :=
⟨λ s1 s2, ∃ s t, s1 = map f1 s ∧ s2 = map f2 t ∧ lift_rel R s t,
⟨s1, s2, rfl, rfl, h1⟩,
λ s1 s2 h, match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl, h⟩ := begin
simp [destruct_map], apply computation.lift_rel_map _ _ (lift_rel_destruct h),
intros o p h,
cases o with a; cases p with b; simp [option.map, option.bind],
{ cases b; cases h },
{ cases a; cases h },
{ cases a with a s; cases b with b t, cases h with r h,
exact ⟨h2 r, s, rfl, t, rfl, h⟩ }
end end⟩
theorem map_congr (f : α → β) {s t : wseq α} (h : s ~ t) : map f s ~ map f t :=
lift_rel_map _ _ h (λ _ _, congr_arg _)
@[simp] def destruct_append.aux (t : wseq α) :
option (α × wseq α) → computation (option (α × wseq α))
| none := destruct t
| (some (a, s)) := return (some (a, append s t))
theorem destruct_append (s t : wseq α) :
destruct (append s t) = (destruct s).bind (destruct_append.aux t) :=
begin
apply eq_of_bisim (λ c1 c2, ∃ s t, c1 = destruct (append s t) ∧
c2 = (destruct s).bind (destruct_append.aux t)) _ ⟨s, t, rfl, rfl⟩,
intros c1 c2 h, cases h with s h, cases h with t h, rw [h.left, h.right],
apply s.cases_on _ (λ a s, _) (λ s, _); simp; simp,
{ apply t.cases_on _ (λ b t, _) (λ t, _); simp; simp,
{ refine ⟨nil, t, _, _⟩; simp } },
{ exact ⟨s, t, rfl, rfl⟩ }
end
@[simp] def destruct_join.aux : option (wseq α × wseq (wseq α)) → computation (option (α × wseq α))
| none := return none
| (some (s, S)) := (destruct (append s (join S))).think
theorem destruct_join (S : wseq (wseq α)) :
destruct (join S) = (destruct S).bind destruct_join.aux :=
begin
apply eq_of_bisim (λ c1 c2, c1 = c2 ∨ ∃ S, c1 = destruct (join S) ∧
c2 = (destruct S).bind destruct_join.aux) _ (or.inr ⟨S, rfl, rfl⟩),
intros c1 c2 h, exact match c1, c2, h with
| _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp
| _, _, or.inr ⟨S, rfl, rfl⟩ := begin
apply S.cases_on _ (λ s S, _) (λ S, _); simp; simp,
{ refine or.inr ⟨S, rfl, rfl⟩ }
end end
end
theorem lift_rel_append (R : α → β → Prop) {s1 s2 : wseq α} {t1 t2 : wseq β}
(h1 : lift_rel R s1 t1) (h2 : lift_rel R s2 t2) :
lift_rel R (append s1 s2) (append t1 t2) :=
⟨λ s t, lift_rel R s t ∨ ∃ s1 t1, s = append s1 s2 ∧ t = append t1 t2 ∧ lift_rel R s1 t1,
or.inr ⟨s1, t1, rfl, rfl, h1⟩,
λ s t h, match s, t, h with
| s, t, or.inl h := begin
apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h),
intros a b, apply lift_rel_o.imp_right,
intros s t, apply or.inl
end
| ._, ._, or.inr ⟨s1, t1, rfl, rfl, h⟩ := begin
simp [destruct_append],
apply computation.lift_rel_bind _ _ (lift_rel_destruct h),
intros o p h,
cases o with a; cases p with b,
{ simp, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h2),
intros a b, apply lift_rel_o.imp_right,
intros s t, apply or.inl },
{ cases b; cases h },
{ cases a; cases h },
{ cases a with a s; cases b with b t, cases h with r h,
simp, exact ⟨r, or.inr ⟨s, rfl, t, rfl, h⟩⟩ }
end
end⟩
theorem lift_rel_join.lem (R : α → β → Prop) {S T} {U : wseq α → wseq β → Prop}
(ST : lift_rel (lift_rel R) S T) (HU : ∀ s1 s2, (∃ s t S T,
s1 = append s (join S) ∧ s2 = append t (join T) ∧
lift_rel R s t ∧ lift_rel (lift_rel R) S T) → U s1 s2) {a} (ma : a ∈ destruct (join S)) :
∃ {b}, b ∈ destruct (join T) ∧ lift_rel_o R U a b :=
begin
cases exists_results_of_mem ma with n h, clear ma, revert a S T,
apply nat.strong_induction_on n _,
intros n IH a S T ST ra, simp [destruct_join] at ra, exact
let ⟨o, m, k, rs1, rs2, en⟩ := of_results_bind ra,
⟨p, mT, rop⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct ST) rs1.mem in
by exact match o, p, rop, rs1, rs2, mT with
| none, none, _, rs1, rs2, mT := by simp [destruct_join]; exact
⟨none, mem_bind mT (ret_mem _), by rw eq_of_ret_mem rs2.mem; trivial⟩
| some (s, S'), some (t, T'), ⟨st, ST'⟩, rs1, rs2, mT :=
by simp [destruct_append] at rs2; exact
let ⟨k1, rs3, ek⟩ := of_results_think rs2,
⟨o', m1, n1, rs4, rs5, ek1⟩ := of_results_bind rs3,
⟨p', mt, rop'⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct st) rs4.mem in
by exact match o', p', rop', rs4, rs5, mt with
| none, none, _, rs4, rs5', mt :=
have n1 < n, begin
rw [en, ek, ek1],
apply lt_of_lt_of_le _ (nat.le_add_right _ _),
apply nat.lt_succ_of_le (nat.le_add_right _ _)
end,
let ⟨ob, mb, rob⟩ := IH _ this ST' rs5' in by refine ⟨ob, _, rob⟩;
{ simp [destruct_join], apply mem_bind mT, simp [destruct_append],
apply think_mem, apply mem_bind mt, exact mb }
| some (a, s'), some (b, t'), ⟨ab, st'⟩, rs4, rs5, mt := begin
simp at rs5,
refine ⟨some (b, append t' (join T')), _, _⟩,
{ simp [destruct_join], apply mem_bind mT, simp [destruct_append],
apply think_mem, apply mem_bind mt, apply ret_mem },
rw eq_of_ret_mem rs5.mem,
exact ⟨ab, HU _ _ ⟨s', t', S', T', rfl, rfl, st', ST'⟩⟩
end end
end
end
theorem lift_rel_join (R : α → β → Prop) {S : wseq (wseq α)} {T : wseq (wseq β)}
(h : lift_rel (lift_rel R) S T) : lift_rel R (join S) (join T) :=
⟨λ s1 s2, ∃ s t S T,
s1 = append s (join S) ∧ s2 = append t (join T) ∧
lift_rel R s t ∧ lift_rel (lift_rel R) S T,
⟨nil, nil, S, T, by simp, by simp, by simp, h⟩,
λs1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, begin
clear _fun_match _x,
rw [h1, h2], rw [destruct_append, destruct_append],
apply computation.lift_rel_bind _ _ (lift_rel_destruct st),
exact λ o p h, match o, p, h with
| some (a, s), some (b, t), ⟨h1, h2⟩ :=
by simp; exact ⟨h1, s, t, S, rfl, T, rfl, h2, ST⟩
| none, none, _ := begin
dsimp [destruct_append.aux, computation.lift_rel], constructor,
{ intro, apply lift_rel_join.lem _ ST (λ _ _, id) },
{ intros b mb,
rw [←lift_rel_o.swap], apply lift_rel_join.lem (function.swap R),
{ rw [←lift_rel.swap R, ←lift_rel.swap], apply ST },
{ rw [←lift_rel.swap R, ←lift_rel.swap (lift_rel R)],
exact λ s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩,
⟨t, s, T, S, h2, h1, st, ST⟩ },
{ exact mb } }
end end
end⟩
theorem join_congr {S T : wseq (wseq α)} (h : lift_rel equiv S T) : join S ~ join T :=
lift_rel_join _ h
theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop)
{s1 : wseq α} {s2 : wseq β}
{f1 : α → wseq γ} {f2 : β → wseq δ}
(h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b))
: lift_rel S (bind s1 f1) (bind s2 f2) :=
lift_rel_join _ (lift_rel_map _ _ h1 @h2)
theorem bind_congr {s1 s2 : wseq α} {f1 f2 : α → wseq β}
(h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 :=
lift_rel_bind _ _ h1 (λ a b h, by rw h; apply h2)
@[simp] theorem join_ret (s : wseq α) : join (ret s) ~ s :=
by simp [ret]; apply think_equiv
@[simp] theorem join_map_ret (s : wseq α) : join (map ret s) ~ s :=
begin
refine ⟨λ s1 s2, join (map ret s2) = s1, rfl, _⟩,
intros s' s h, rw ←h,
apply lift_rel_rec
(λ c1 c2, ∃ s,
c1 = destruct (join (map ret s)) ∧ c2 = destruct s),
{ exact λ c1 c2 h, match c1, c2, h with
| ._, ._, ⟨s, rfl, rfl⟩ := begin
clear h _match,
apply s.cases_on _ (λ a s, _) (λ s, _); simp [ret]; simp [ret],
{ refine ⟨_, ret_mem _, _⟩, simp },
{ exact ⟨s, rfl, rfl⟩ }
end end },
{ exact ⟨s, rfl, rfl⟩ }
end
@[simp] theorem join_append (S T : wseq (wseq α)) :
join (append S T) ~ append (join S) (join T) :=
begin
refine ⟨λ s1 s2, ∃ s S T,
s1 = append s (join (append S T)) ∧
s2 = append s (append (join S) (join T)), ⟨nil, S, T, by simp, by simp⟩, _⟩,
intros s1 s2 h,
apply lift_rel_rec (λ c1 c2, ∃ (s : wseq α) S T,
c1 = destruct (append s (join (append S T))) ∧
c2 = destruct (append s (append (join S) (join T)))) _ _ _
(let ⟨s, S, T, h1, h2⟩ := h in
⟨s, S, T, congr_arg destruct h1, congr_arg destruct h2⟩),
intros c1 c2 h,
exact match c1, c2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin
clear _match h h,
apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp; simp,
{ apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp; simp,
{ apply wseq.cases_on T _ (λ s T, _) (λ T, _); simp; simp,
{ refine ⟨s, nil, T, _, _⟩; simp },
{ refine ⟨nil, nil, T, _, _⟩; simp } },
{ exact ⟨s, S, T, rfl, rfl⟩ },
{ refine ⟨nil, S, T, _, _⟩; simp } },
{ exact ⟨s, S, T, rfl, rfl⟩ },
{ exact ⟨s, S, T, rfl, rfl⟩ }
end end
end
@[simp] theorem bind_ret (f : α → β) (s) : bind s (ret ∘ f) ~ map f s :=
begin
dsimp [bind], change (λx, ret (f x)) with (ret ∘ f),
rw [map_comp], apply join_map_ret
end
@[simp] theorem ret_bind (a : α) (f : α → wseq β) :
bind (ret a) f ~ f a := by simp [bind]
@[simp] theorem map_join (f : α → β) (S) :
map f (join S) = join (map (map f) S) :=
begin
apply seq.eq_of_bisim (λs1 s2,
∃ s S, s1 = append s (map f (join S)) ∧
s2 = append s (join (map (map f) S))),
{ intros s1 s2 h,
exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin
apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp; simp,
{ apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp; simp,
{ exact ⟨map f s, S, rfl, rfl⟩ },
{ refine ⟨nil, S, _, _⟩; simp } },
{ exact ⟨_, _, rfl, rfl⟩ },
{ exact ⟨_, _, rfl, rfl⟩ }
end end },
{ refine ⟨nil, S, _, _⟩; simp }
end
@[simp] theorem join_join (SS : wseq (wseq (wseq α))) :
join (join SS) ~ join (map join SS) :=
begin
refine ⟨λ s1 s2, ∃ s S SS,
s1 = append s (join (append S (join SS))) ∧
s2 = append s (append (join S) (join (map join SS))),
⟨nil, nil, SS, by simp, by simp⟩, _⟩,
intros s1 s2 h,
apply lift_rel_rec (λ c1 c2, ∃ s S SS,
c1 = destruct (append s (join (append S (join SS)))) ∧
c2 = destruct (append s (append (join S) (join (map join SS)))))
_ (destruct s1) (destruct s2)
(let ⟨s, S, SS, h1, h2⟩ := h in ⟨s, S, SS, by simp [h1], by simp [h2]⟩),
intros c1 c2 h,
exact match c1, c2, h with ._, ._, ⟨s, S, SS, rfl, rfl⟩ := begin
clear _match h h,
apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp; simp,
{ apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp; simp,
{ apply wseq.cases_on SS _ (λ S SS, _) (λ SS, _); simp; simp,
{ refine ⟨nil, S, SS, _, _⟩; simp },
{ refine ⟨nil, nil, SS, _, _⟩; simp } },
{ exact ⟨s, S, SS, rfl, rfl⟩ },
{ refine ⟨nil, S, SS, _, _⟩; simp } },
{ exact ⟨s, S, SS, rfl, rfl⟩ },
{ exact ⟨s, S, SS, rfl, rfl⟩ }
end end
end
@[simp] theorem bind_assoc (s : wseq α) (f : α → wseq β) (g : β → wseq γ) :
bind (bind s f) g ~ bind s (λ (x : α), bind (f x) g) :=
begin
simp [bind], rw [← map_comp f (map g), map_comp (map g ∘ f) join],
apply join_join
end
instance : monad wseq :=
{ map := @map,
pure := @ret,
bind := @bind }
/-
Unfortunately, wseq is not a lawful monad, because it does not satisfy
the monad laws exactly, only up to sequence equivalence.
Furthermore, even quotienting by the equivalence is not sufficient,
because the join operation involves lists of quotient elements,
with a lifted equivalence relation, and pure quotients cannot handle
this type of construction.
instance : is_lawful_monad wseq :=
{ id_map := @map_id,
bind_pure_comp_eq_map := @bind_ret,
pure_bind := @ret_bind,
bind_assoc := @bind_assoc }
-/
end wseq
|
b0beba750c78d80c5f1b1fe1426479a7bde0b084 | 5719a16e23dfc08cdea7a5bf035b81690f307965 | /src/Init/Lean/Elab/Binders.lean | 8231a0b21de933dc84a86f576dbb5d31a7fbcdac | [
"Apache-2.0"
] | permissive | postmasters/lean4 | 488b03969a371e1507e1e8a4df9ebf63c7cbe7ac | f3976fc53a883ac7606fc59357d43f4b51016ca7 | refs/heads/master | 1,655,582,707,480 | 1,588,682,595,000 | 1,588,682,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,517 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.Elab.Term
import Init.Lean.Elab.Quotation
namespace Lean
namespace Elab
namespace Term
/--
Given syntax of the forms
a) (`:` term)?
b) `:` term
return `term` if it is present, or a hole if not. -/
private def expandBinderType (stx : Syntax) : Syntax :=
if stx.getNumArgs == 0 then
mkHole stx
else
stx.getArg 1
/-- Given syntax of the form `ident <|> hole`, return `ident`. If `hole`, then we create a new anonymous name. -/
private def expandBinderIdent (stx : Syntax) : TermElabM Syntax :=
match_syntax stx with
| `(_) => mkFreshAnonymousIdent stx
| _ => pure stx
/-- Given syntax of the form `(ident >> " : ")?`, return `ident`, or a new instance name. -/
private def expandOptIdent (stx : Syntax) : TermElabM Syntax :=
if stx.getNumArgs == 0 then do
id ← mkFreshInstanceName; pure $ mkIdentFrom stx id
else
pure $ stx.getArg 0
structure BinderView :=
(id : Syntax) (type : Syntax) (bi : BinderInfo)
partial def quoteAutoTactic : Syntax → TermElabM Syntax
| stx@(Syntax.ident _ _ _ _) => throwError stx "invalic auto tactic, identifier is not allowed"
| stx@(Syntax.node k args) =>
if Quotation.isAntiquot stx then
throwError stx "invalic auto tactic, antiquotation is not allowed"
else do
empty ← `(Array.empty);
args ← args.foldlM (fun args arg =>
if k == nullKind && Quotation.isAntiquotSplice arg then
throwError arg "invalic auto tactic, antiquotation is not allowed"
else do
arg ← quoteAutoTactic arg;
`(Array.push $args $arg)) empty;
`(Syntax.node $(quote k) $args)
| Syntax.atom info val => `(Syntax.atom none $(quote val))
| Syntax.missing => unreachable!
def declareTacticSyntax (tactic : Syntax) : TermElabM Name :=
withFreshMacroScope $ do
name ← MonadQuotation.addMacroScope `_auto;
let type := Lean.mkConst `Lean.Syntax;
tactic ← quoteAutoTactic tactic;
val ← elabTerm tactic type;
val ← instantiateMVars tactic val;
trace `Elab.autoParam tactic $ fun _ => val;
let decl := Declaration.defnDecl { name := name, lparams := [], type := type, value := val, hints := ReducibilityHints.opaque, isUnsafe := false };
addDecl tactic decl;
compileDecl tactic decl;
pure name
/-
Expand `optional (binderTactic <|> binderDefault)`
def binderTactic := parser! " := " >> " by " >> tacticParser
def binderDefault := parser! " := " >> termParser
-/
private def expandBinderModifier (type : Syntax) (optBinderModifier : Syntax) : TermElabM Syntax :=
if optBinderModifier.isNone then pure type
else
let modifier := optBinderModifier.getArg 0;
let kind := modifier.getKind;
if kind == `Lean.Parser.Term.binderDefault then do
let defaultVal := modifier.getArg 1;
`(optParam $type $defaultVal)
else if kind == `Lean.Parser.Term.binderTactic then do
let tac := modifier.getArg 2;
name ← declareTacticSyntax tac;
`(autoParam $type $(mkTermIdFrom tac name))
else
throwUnsupportedSyntax
private def getBinderIds (ids : Syntax) : TermElabM (Array Syntax) :=
ids.getArgs.mapM $ fun id =>
let k := id.getKind;
if k == identKind || k == `Lean.Parser.Term.hole then
pure id
else if k == `Lean.Parser.Term.id && id.getArgs.size == 2 && (id.getArg 1).isNone then
-- The parser never generates this case, but it is convenient when writting macros.
pure (id.getArg 0)
else
throwError id "identifier or `_` expected"
private def matchBinder (stx : Syntax) : TermElabM (Array BinderView) :=
match stx with
| Syntax.node k args =>
if k == `Lean.Parser.Term.simpleBinder then do
-- binderIdent+
ids ← getBinderIds (args.get! 0);
let type := mkHole stx;
ids.mapM $ fun id => do id ← expandBinderIdent id; pure { id := id, type := type, bi := BinderInfo.default }
else if k == `Lean.Parser.Term.explicitBinder then do
-- `(` binderIdent+ binderType (binderDefault <|> binderTactic)? `)`
ids ← getBinderIds (args.get! 1);
let type := expandBinderType (args.get! 2);
let optModifier := args.get! 3;
type ← expandBinderModifier type optModifier;
ids.mapM $ fun id => do id ← expandBinderIdent id; pure { id := id, type := type, bi := BinderInfo.default }
else if k == `Lean.Parser.Term.implicitBinder then do
-- `{` binderIdent+ binderType `}`
ids ← getBinderIds (args.get! 1);
let type := expandBinderType (args.get! 2);
ids.mapM $ fun id => do id ← expandBinderIdent id; pure { id := id, type := type, bi := BinderInfo.implicit }
else if k == `Lean.Parser.Term.instBinder then do
-- `[` optIdent type `]`
id ← expandOptIdent (args.get! 1);
let type := args.get! 2;
pure #[ { id := id, type := type, bi := BinderInfo.instImplicit } ]
else
throwUnsupportedSyntax
| _ => throwUnsupportedSyntax
private partial def elabBinderViews (binderViews : Array BinderView)
: Nat → Array Expr → LocalContext → LocalInstances → TermElabM (Array Expr × LocalContext × LocalInstances)
| i, fvars, lctx, localInsts =>
if h : i < binderViews.size then
let binderView := binderViews.get ⟨i, h⟩;
withLCtx lctx localInsts $ do
type ← elabType binderView.type;
fvarId ← mkFreshFVarId;
let fvar := mkFVar fvarId;
let fvars := fvars.push fvar;
-- dbgTrace (toString binderView.id.getId ++ " : " ++ toString type);
let lctx := lctx.mkLocalDecl fvarId binderView.id.getId type binderView.bi;
className? ← isClass binderView.type type;
match className? with
| none => elabBinderViews (i+1) fvars lctx localInsts
| some className => do
resetSynthInstanceCache;
let localInsts := localInsts.push { className := className, fvar := mkFVar fvarId };
elabBinderViews (i+1) fvars lctx localInsts
else
pure (fvars, lctx, localInsts)
private partial def elabBindersAux (binders : Array Syntax)
: Nat → Array Expr → LocalContext → LocalInstances → TermElabM (Array Expr × LocalContext × LocalInstances)
| i, fvars, lctx, localInsts =>
if h : i < binders.size then do
binderViews ← matchBinder (binders.get ⟨i, h⟩);
(fvars, lctx, localInsts) ← elabBinderViews binderViews 0 fvars lctx localInsts;
elabBindersAux (i+1) fvars lctx localInsts
else
pure (fvars, lctx, localInsts)
/--
Elaborate the given binders (i.e., `Syntax` objects for `simpleBinder <|> bracketedBinder`),
update the local context, set of local instances, reset instance chache (if needed), and then
execute `x` with the updated context. -/
def elabBinders {α} (binders : Array Syntax) (x : Array Expr → TermElabM α) : TermElabM α :=
if binders.isEmpty then x #[]
else do
lctx ← getLCtx;
localInsts ← getLocalInsts;
(fvars, lctx, newLocalInsts) ← elabBindersAux binders 0 #[] lctx localInsts;
resettingSynthInstanceCacheWhen (newLocalInsts.size > localInsts.size) $ withLCtx lctx newLocalInsts $
x fvars
@[inline] def elabBinder {α} (binder : Syntax) (x : Expr → TermElabM α) : TermElabM α :=
elabBinders #[binder] (fun fvars => x (fvars.get! 0))
@[builtinTermElab «forall»] def elabForall : TermElab :=
fun stx _ => match_syntax stx with
| `(forall $binders*, $term) =>
elabBinders binders $ fun xs => do
e ← elabType term;
mkForall stx xs e
| _ => throwUnsupportedSyntax
@[builtinTermElab arrow] def elabArrow : TermElab :=
adaptExpander $ fun stx => match_syntax stx with
| `($dom:term -> $rng) => `(forall (a : $dom), $rng)
| _ => throwUnsupportedSyntax
@[builtinTermElab depArrow] def elabDepArrow : TermElab :=
fun stx _ =>
-- bracketedBinder `->` term
let binder := stx.getArg 0;
let term := stx.getArg 2;
elabBinders #[binder] $ fun xs => do
e ← elabType term;
mkForall stx xs e
/-- Main loop `getFunBinderIds?` -/
private partial def getFunBinderIdsAux? : Bool → Syntax → Array Syntax → TermElabM (Option (Array Syntax))
| idOnly, stx, acc =>
match_syntax stx with
| `($f $a) =>
if idOnly then pure none
else do
(some acc) ← getFunBinderIdsAux? false f acc | pure none;
getFunBinderIdsAux? true a acc
| `(_) => do ident ← mkFreshAnonymousIdent stx; pure (some (acc.push ident))
| stx =>
match stx.isSimpleTermId? true with
| some id => pure (some (acc.push id))
| _ => pure none
/--
Auxiliary functions for converting `Term.app ... (Term.app id_1 id_2) ... id_n` into `#[id_1, ..., id_m]`
It is used at `expandFunBinders`. -/
private def getFunBinderIds? (stx : Syntax) : TermElabM (Option (Array Syntax)) :=
getFunBinderIdsAux? false stx #[]
/-- Main loop for `expandFunBinders`. -/
private partial def expandFunBindersAux (binders : Array Syntax) : Syntax → Nat → Array Syntax → TermElabM (Array Syntax × Syntax)
| body, i, newBinders =>
if h : i < binders.size then
let binder := binders.get ⟨i, h⟩;
let processAsPattern : Unit → TermElabM (Array Syntax × Syntax) := fun _ => do {
let pattern := binder;
major ← mkFreshAnonymousIdent binder;
(binders, newBody) ← expandFunBindersAux body (i+1) (newBinders.push $ mkExplicitBinder major (mkHole binder));
newBody ← `(match $major:ident with | $pattern => $newBody);
pure (binders, newBody)
};
match binder with
| Syntax.node `Lean.Parser.Term.implicitBinder _ => expandFunBindersAux body (i+1) (newBinders.push binder)
| Syntax.node `Lean.Parser.Term.instBinder _ => expandFunBindersAux body (i+1) (newBinders.push binder)
| Syntax.node `Lean.Parser.Term.hole _ => do
ident ← mkFreshAnonymousIdent binder;
let type := binder;
expandFunBindersAux body (i+1) (newBinders.push $ mkExplicitBinder ident type)
| Syntax.node `Lean.Parser.Term.paren args =>
-- `(` (termParser >> parenSpecial)? `)`
-- parenSpecial := (tupleTail <|> typeAscription)?
let binderBody := binder.getArg 1;
if binderBody.isNone then processAsPattern ()
else
let idents := binderBody.getArg 0;
let special := binderBody.getArg 1;
if special.isNone then processAsPattern ()
else if (special.getArg 0).getKind != `Lean.Parser.Term.typeAscription then processAsPattern ()
else do
-- typeAscription := `:` term
let type := ((special.getArg 0).getArg 1);
idents? ← getFunBinderIds? idents;
match idents? with
| some idents => expandFunBindersAux body (i+1) (newBinders ++ idents.map (fun ident => mkExplicitBinder ident type))
| none => processAsPattern ()
| binder =>
match binder.isTermId? true with
| some (ident, extra) => do
unless extra.isNone $ throwError binder "invalid binder, simple identifier expected";
let type := mkHole binder;
expandFunBindersAux body (i+1) (newBinders.push $ mkExplicitBinder ident type)
| none => processAsPattern ()
else
pure (newBinders, body)
/--
Auxiliary function for expanding `fun` notation binders. Recall that `fun` parser is defined as
```
def funBinder : Parser := implicitBinder <|> instBinder <|> termParser appPrec
parser! unicodeSymbol "λ" "fun" >> many1 funBinder >> "=>" >> termParser
```
to allow notation such as `fun (a, b) => a + b`, where `(a, b)` should be treated as a pattern.
The result is a pair `(explicitBinders, newBody)`, where `explicitBinders` is syntax of the form
```
`(` ident `:` term `)`
```
which can be elaborated using `elabBinders`, and `newBody` is the updated `body` syntax.
We update the `body` syntax when expanding the pattern notation.
Example: `fun (a, b) => a + b` expands into `fun _a_1 => match _a_1 with | (a, b) => a + b`.
See local function `processAsPattern` at `expandFunBindersAux`. -/
def expandFunBinders (binders : Array Syntax) (body : Syntax) : TermElabM (Array Syntax × Syntax) :=
expandFunBindersAux binders body 0 #[]
namespace FunBinders
structure State :=
(fvars : Array Expr := #[])
(lctx : LocalContext)
(localInsts : LocalInstances)
(expectedType? : Option Expr := none)
private def checkNoOptAutoParam (ref : Syntax) (type : Expr) : TermElabM Unit := do
type ← instantiateMVars ref type;
when type.isOptParam $
throwError ref "optParam is not allowed at 'fun/λ' binders";
when type.isAutoParam $
throwError ref "autoParam is not allowed at 'fun/λ' binders"
private def propagateExpectedType (ref : Syntax) (fvar : Expr) (fvarType : Expr) (s : State) : TermElabM State := do
match s.expectedType? with
| none => pure s
| some expectedType => do
expectedType ← whnfForall ref expectedType;
match expectedType with
| Expr.forallE _ d b _ => do
_ ← isDefEq ref fvarType d;
checkNoOptAutoParam ref fvarType;
let b := b.instantiate1 fvar;
pure { expectedType? := some b, .. s }
| _ => pure { expectedType? := none, .. s }
private partial def elabFunBinderViews (binderViews : Array BinderView) : Nat → State → TermElabM State
| i, s =>
if h : i < binderViews.size then
let binderView := binderViews.get ⟨i, h⟩;
withLCtx s.lctx s.localInsts $ do
type ← elabType binderView.type;
checkNoOptAutoParam binderView.type type;
fvarId ← mkFreshFVarId;
let fvar := mkFVar fvarId;
let s := { fvars := s.fvars.push fvar, .. s };
-- dbgTrace (toString binderView.id.getId ++ " : " ++ toString type);
/-
We do **not** want to support default and auto arguments in lambda abstractions.
Example: `fun (x : Nat := 10) => x+1`.
We do not believe this is an useful feature, and it would complicate the logic here.
-/
let lctx := s.lctx.mkLocalDecl fvarId binderView.id.getId type binderView.bi;
s ← propagateExpectedType binderView.id fvar type s;
let s := { lctx := lctx, .. s };
className? ← isClass binderView.type type;
match className? with
| none => elabFunBinderViews (i+1) s
| some className => do
resetSynthInstanceCache;
let localInsts := s.localInsts.push { className := className, fvar := mkFVar fvarId };
elabFunBinderViews (i+1) { localInsts := localInsts, .. s }
else
pure s
partial def elabFunBindersAux (binders : Array Syntax) : Nat → State → TermElabM State
| i, s =>
if h : i < binders.size then do
binderViews ← matchBinder (binders.get ⟨i, h⟩);
s ← elabFunBinderViews binderViews 0 s;
elabFunBindersAux (i+1) s
else
pure s
end FunBinders
def elabFunBinders {α} (binders : Array Syntax) (expectedType? : Option Expr) (x : Array Expr → Option Expr → TermElabM α) : TermElabM α :=
if binders.isEmpty then x #[] expectedType?
else do
lctx ← getLCtx;
localInsts ← getLocalInsts;
s ← FunBinders.elabFunBindersAux binders 0 { lctx := lctx, localInsts := localInsts, expectedType? := expectedType? };
resettingSynthInstanceCacheWhen (s.localInsts.size > localInsts.size) $ withLCtx s.lctx s.localInsts $
x s.fvars s.expectedType?
@[builtinTermElab «fun»] def elabFun : TermElab :=
fun stx expectedType? => do
-- `fun` term+ `=>` term
let binders := (stx.getArg 1).getArgs;
let body := stx.getArg 3;
(binders, body) ← expandFunBinders binders body;
elabFunBinders binders expectedType? $ fun xs expectedType? => do {
e ← elabTerm body expectedType?;
mkLambda stx xs e
}
/-
Recall that
```
def typeSpec := parser! " : " >> termParser
def optType : Parser := optional typeSpec
``` -/
def expandOptType (ref : Syntax) (optType : Syntax) : Syntax :=
if optType.isNone then
mkHole ref
else
(optType.getArg 0).getArg 1
/- If `useLetExpr` is true, then a kernel let-expression `let x : type := val; body` is created.
Otherwise, we create a term of the form `(fun (x : type) => body) val` -/
def elabLetDeclAux (ref : Syntax) (n : Name) (binders : Array Syntax) (typeStx : Syntax) (valStx : Syntax) (body : Syntax)
(expectedType? : Option Expr) (useLetExpr : Bool) : TermElabM Expr := do
(type, val) ← elabBinders binders $ fun xs => do {
type ← elabType typeStx;
val ← elabTerm valStx type;
val ← ensureHasType valStx type val;
type ← mkForall ref xs type;
val ← mkLambda ref xs val;
pure (type, val)
};
trace `Elab.let.decl ref $ fun _ => n ++ " : " ++ type ++ " := " ++ val;
if useLetExpr then
withLetDecl ref n type val $ fun x => do
body ← elabTerm body expectedType?;
body ← instantiateMVars ref body;
mkLet ref x body
else do
f ← withLocalDecl ref n BinderInfo.default type $ fun x => do {
body ← elabTerm body expectedType?;
body ← instantiateMVars ref body;
mkLambda ref #[x] body
};
pure $ mkApp f val
@[builtinTermElab «let»] def elabLetDecl : TermElab :=
fun stx expectedType? => match_syntax stx with
| `(let $id:ident $args* := $val; $body) =>
elabLetDeclAux stx id.getId args (mkHole stx) val body expectedType? true
| `(let $id:ident $args* : $type := $val; $body) =>
elabLetDeclAux stx id.getId args type val body expectedType? true
| `(let $pat:term := $val; $body) => do
stxNew ← `(let x := $val; match x with $pat => $body);
withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
| `(let $pat:term : $type := $val; $body) => do
stxNew ← `(let x : $type := $val; match x with $pat => $body);
withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
| _ => throwUnsupportedSyntax
@[builtinTermElab «let!»] def elabLetBangDecl : TermElab :=
fun stx expectedType? => match_syntax stx with
| `(let! $id:ident $args* := $val; $body) =>
elabLetDeclAux stx id.getId args (mkHole stx) val body expectedType? false
| `(let! $id:ident $args* : $type := $val; $body) =>
elabLetDeclAux stx id.getId args type val body expectedType? false
| `(let! $pat:term := $val; $body) => do
stxNew ← `(let! x := $val; match x with $pat => $body);
withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
| `(let! $pat:term : $type := $val; $body) => do
stxNew ← `(let! x : $type := $val; match x with $pat => $body);
withMacroExpansion stx stxNew $ elabTerm stxNew expectedType?
| _ => throwUnsupportedSyntax
@[init] private def regTraceClasses : IO Unit := do
registerTraceClass `Elab.let;
pure ()
end Term
end Elab
end Lean
|
93f62a33cc45ffef338b1d95d1c112827361f890 | 3aad12fe82645d2d3173fbedc2e5c2ba945a4d75 | /src/data/serial/basic.lean | 0fe3c2f73b0be0d7779fbf6001f1f440d3b4917e | [] | no_license | seanpm2001/LeanProver-Community_MathLIB-Nursery | 4f88d539cb18d73a94af983092896b851e6640b5 | 0479b31fa5b4d39f41e89b8584c9f5bf5271e8ec | refs/heads/master | 1,688,730,786,645 | 1,572,070,026,000 | 1,572,070,026,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,684 | lean |
import tactic
import tactic.monotonicity
import tactic.norm_num
import category.basic
import category.nursery
import data.equiv.nursery
import data.serial.medium
universes u v w
abbreviation put_m' := medium.put_m'.{u} unsigned
abbreviation put_m := medium.put_m'.{u} unsigned punit
abbreviation get_m := medium.get_m.{u} unsigned
def serial_inverse {α : Type u} (encode : α → put_m) (decode : get_m α) : Prop :=
∀ w, decode -<< encode w = pure w
class serial (α : Type u) :=
(encode : α → put_m)
(decode : get_m α)
(correctness : ∀ w, decode -<< encode w = pure w)
class serial1 (f : Type u → Type v) :=
(encode : Π {α}, (α → put_m) → f α → put_m)
(decode : Π {α}, get_m α → get_m (f α))
(correctness : ∀ {α} put get, serial_inverse.{u} put get →
∀ (w : f α), decode get -<< encode put w = pure w)
instance serial.serial1 {f α} [serial1 f] [serial α] : serial (f α) :=
{ encode := λ x, serial1.encode serial.encode x,
decode := serial1.decode f (serial.decode α),
correctness := serial1.correctness _ _ serial.correctness }
class serial2 (f : Type u → Type v → Type w) :=
(encode : Π {α β}, (α → put_m.{u}) → (β → put_m.{v}) → f α β → put_m.{w})
(decode : Π {α β}, get_m α → get_m β → get_m (f α β))
(correctness : ∀ {α β} putα getα putβ getβ,
serial_inverse putα getα →
serial_inverse putβ getβ →
∀ (w : f α β), decode getα getβ -<< encode putα putβ w = pure w)
instance serial.serial2 {f α β} [serial2 f] [serial α] [serial β] : serial (f α β) :=
{ encode := λ x, serial2.encode serial.encode serial.encode x,
decode := serial2.decode f (serial.decode _) (serial.decode _),
correctness := serial2.correctness _ _ _ _ serial.correctness serial.correctness }
instance serial1.serial2 {f α} [serial2 f] [serial α] : serial1 (f α) :=
{ encode := λ β put x, serial2.encode serial.encode put x,
decode := λ β get, serial2.decode f (serial.decode _) get,
correctness := λ β get put, serial2.correctness _ _ _ _ serial.correctness }
export serial (encode decode)
namespace serial
open function
export medium (hiding put_m get_m put_m')
variables {α β σ γ : Type u} {ω : Type}
def serialize [serial α] (x : α) : list unsigned := (encode x).eval
def deserialize (α : Type u) [serial α] (bytes : list unsigned) : option α := (decode α).eval bytes
lemma deserialize_serialize [serial α] (x : α) :
deserialize _ (serialize x) = some x :=
by simp [deserialize,serialize,eval_eval,serial.correctness]; refl
lemma encode_decode_bind [serial α]
(f : α → get_m β) (f' : punit → put_m) (w : α) :
(decode α >>= f) -<< (encode w >>= f') = f w -<< f' punit.star :=
by { rw [read_write_mono]; rw serial.correctness; refl }
lemma encode_decode_bind' [serial α]
(f : α → get_m β) (w : α) :
(decode α >>= f) -<< (encode w) = f w -<< pure punit.star :=
by { rw [read_write_mono_left]; rw serial.correctness; refl }
lemma encode_decode_pure
(w w' : α) (u : punit) :
(pure w : get_m α) -<< (pure u) = pure w' ↔ w = w' :=
by split; intro h; cases h; refl
open ulift
protected def ulift.encode [serial α] (w : ulift.{v} α) : put_m :=
(liftable1.up _ equiv.punit_equiv_punit (encode (down w) : medium.put_m' unsigned _) : medium.put_m' unsigned _)
protected def ulift.decode [serial α] : get_m (ulift α) :=
get_m.up ulift.up (decode α)
instance [serial α] : serial (ulift.{v u} α) :=
{ encode := ulift.encode
, decode := ulift.decode
, correctness :=
by { introv, simp [ulift.encode,ulift.decode],
rw up_read_write' _ equiv.ulift.symm,
rw [serial.correctness], cases w, refl,
intro, refl } }
instance unsigned.serial : serial unsigned :=
{ encode := λ w, put_m'.write w put_m'.pure
, decode := get_m.read get_m.pure
, correctness := by introv; refl }
-- protected def write_word (w : unsigned) : put_m :=
-- encode (up.{u} w)
@[simp] lemma loop_read_write_word {α β γ : Type u}
(w : unsigned) (x : α) (f : α → unsigned → get_m (β ⊕ α)) (g : β → get_m γ)
(rest : punit → put_m) :
get_m.loop f g x -<< (write_word w >>= rest) =
(f x w >>= get_m.loop.rest f g) -<< rest punit.star := rfl
@[simp] lemma loop_read_write_word' {α β γ : Type u}
(w : unsigned) (x : α) (f : α → unsigned → get_m (β ⊕ α)) (g : β → get_m γ) :
get_m.loop f g x -<< (write_word w) =
(f x w >>= get_m.loop.rest f g) -<< pure punit.star := rfl
-- protected def read_word : get_m.{u} (ulift unsigned) :=
-- decode _
def select_tag' (tag : unsigned) : list (unsigned × get_m α) → get_m α
| [] := get_m.fail
| ((w,x) :: xs) := if w = tag then x else select_tag' xs
def select_tag (xs : list (unsigned × get_m α)) : get_m α :=
do w ← read_word,
select_tag' (down w) xs
@[simp]
lemma read_write_tag_hit {w w' : unsigned} {x : get_m α}
{xs : list (unsigned × get_m α)} {y : put_m}
(h : w = w') :
select_tag ( (w,x) :: xs ) -<< (write_word w' >> y) = x -<< y :=
by subst w'; simp [select_tag,(>>),encode_decode_bind,select_tag']
lemma read_write_tag_hit' {w w' : unsigned} {x : get_m α}
{xs : list (unsigned × get_m α)}
(h : w = w') :
select_tag ( (w,x) :: xs ) -<< (write_word w') = x -<< pure punit.star :=
by subst w'; simp [select_tag,(>>),encode_decode_bind',select_tag']
@[simp]
lemma read_write_tag_miss {w w' : unsigned} {x : get_m α}
{xs : list (unsigned × get_m α)} {y : put_m}
(h : w ≠ w') :
select_tag ( (w,x) :: xs ) -<< (write_word w' >> y) = select_tag xs -<< (write_word w' >> y) :=
by simp [select_tag,(>>),encode_decode_bind,select_tag',*]
def recursive_parser {α} : ℕ → (get_m α → get_m α) → get_m α
| 0 _ := get_m.fail
| (nat.succ n) rec_fn := rec_fn $ recursive_parser n rec_fn
lemma recursive_parser_unfold {α} (n : ℕ) (f : get_m α → get_m α) (h : 1 ≤ n) :
recursive_parser n f = f (recursive_parser (n-1) f) :=
by cases n; [ cases h, refl ]
attribute [simp] serial.correctness
end serial
structure serializer (α : Type u) (β : Type u) :=
(encoder : α → put_m.{u})
(decoder : get_m β)
def serial.mk_serializer' (α) [serial α] : serializer α α :=
{ encoder := encode,
decoder := decode α }
namespace serializer
def valid_serializer {α} (x : serializer α α) :=
serial_inverse
(serializer.encoder x)
(serializer.decoder x)
lemma serializer.eq {α β} (x y : serializer α β)
(h : x.encoder = y.encoder)
(h' : x.decoder = y.decoder) :
x = y :=
by cases x; cases y; congr; assumption
namespace serializer.seq
variables {α : Type u} {i j : Type u}
variables (x : serializer α (i → j))
variables (y : serializer α i)
def encoder := λ (k : α), (x.encoder k >> y.encoder k : put_m' _)
def decoder := x.decoder <*> y.decoder
end serializer.seq
instance {α : Type u} : applicative (serializer.{u} α) :=
{ pure := λ i x, { encoder := λ _, (return punit.star : put_m' _), decoder := pure x }
, seq := λ i j x y,
{ encoder := serializer.seq.encoder x y
, decoder := serializer.seq.decoder x y } }
section lawful_applicative
variables {α β : Type u} {σ : Type u}
@[simp]
lemma decoder_pure (x : β) :
(pure x : serializer σ β).decoder = pure x := rfl
@[simp]
lemma decoder_map (f : α → β) (x : serializer σ α) :
(f <$> x).decoder = f <$> x.decoder := rfl
@[simp]
lemma decoder_seq (f : serializer σ (α → β)) (x : serializer σ α) :
(f <*> x).decoder = f.decoder <*> x.decoder := rfl
@[simp]
lemma encoder_pure (x : β) (w : σ) :
(pure x : serializer σ β).encoder w = (pure punit.star : put_m' _) := rfl
@[simp]
lemma encoder_map (f : α → β) (w : σ) (x : serializer σ α) :
(f <$> x : serializer σ β).encoder w = x.encoder w := rfl
@[simp]
lemma encoder_seq (f : serializer σ (α → β)) (x : serializer σ α) (w : σ) :
(f <*> x : serializer σ β).encoder w = (f.encoder w >> x.encoder w : put_m' _) := rfl
end lawful_applicative
instance {α} : is_lawful_functor (serializer.{u} α) :=
by refine { .. }; intros; apply serializer.eq; try { ext }; simp [map_map]
instance {α} : is_lawful_applicative (serializer.{u} α) :=
by{ constructor; intros; apply serializer.eq; try { ext };
simp [(>>),pure_seq_eq_map,seq_assoc,bind_assoc], }
protected def up {β} (ser : serializer β β) : serializer (ulift.{u v} β) (ulift.{u v} β) :=
{ encoder := pliftable.up' _ ∘ ser.encoder ∘ ulift.down,
decoder := medium.get_m.up ulift.up ser.decoder }
def ser_field_with {α β} (ser : serializer β β) (f : α → β) : serializer α β :=
{ encoder := ser.encoder ∘ f,
decoder := ser.decoder }
@[simp]
def ser_field_with' {α β} (ser : serializer β β) (f : α → β) : serializer.{max u v} α (ulift.{v} β) :=
ser_field_with ser.up (ulift.up ∘ f)
@[simp]
def ser_field {α β} [serial β] (f : α → β) : serializer α β :=
ser_field_with (serial.mk_serializer' β) f
@[simp]
lemma valid_mk_serializer (α) [serial α] :
valid_serializer (serial.mk_serializer' α) :=
serial.correctness
variables {α β σ γ : Type u} {ω : Type}
def there_and_back_again
(y : serializer γ α) (w : γ) : option α :=
y.decoder -<< y.encoder w
open medium (hiding put_m put_m' get_m)
lemma there_and_back_again_seq {ser : serializer α α}
{x : serializer γ (α → β)} {f : α → β} {y : γ → α} {w : γ} {w' : β}
(h' : there_and_back_again x w = pure f)
(h : w' = f (y w))
(h₀ : valid_serializer ser) :
there_and_back_again (x <*> ser_field_with ser y) w = pure w' :=
by { simp [there_and_back_again,(>>),seq_eq_bind_map] at *,
rw [read_write_mono h',map_read_write],
rw [ser_field_with,h₀], subst w', refl }
lemma there_and_back_again_map {ser : serializer α α}
{f : α → β} {y : γ → α} {w : γ}
(h₀ : valid_serializer ser) :
there_and_back_again (f <$> ser_field_with ser y) w = pure (f $ y w) :=
by rw [← pure_seq_eq_map,there_and_back_again_seq]; refl <|> assumption
lemma there_and_back_again_pure (x : β) (w : γ) :
there_and_back_again (pure x) w =
pure x := rfl
lemma valid_serializer_of_there_and_back_again
{α : Type*} (y : serializer α α) :
valid_serializer y ↔
∀ (w : α), there_and_back_again y w = pure w :=
by { simp [valid_serializer,serial_inverse],
repeat { rw forall_congr, intro }, refl }
@[simp]
lemma valid_serializer_up (x: serializer α α) :
valid_serializer (serializer.up.{v} x) ↔ valid_serializer x :=
by { cases x, simp [valid_serializer,serializer.up,serial_inverse,equiv.forall_iff_forall equiv.ulift],
apply forall_congr, intro, dsimp [equiv.ulift,pliftable.up'],
rw up_read_write' _ equiv.ulift.symm, split; intro h,
{ replace h := congr_arg (liftable1.down.{u} option (equiv.symm equiv.ulift)) h,
simp [liftable1.down_up] at h, simp [h], refl },
{ simp [h], refl },
{ intro, refl, } }
open ulift
def ser_field' {α β} [serial β] (f : α → β) : serializer.{max u v} α (ulift.{v} β) :=
ser_field (up ∘ f)
def put₀ {α} (x : α) : put_m.{u} := (pure punit.star : put_m' _)
def get₀ {α} : get_m α := get_m.fail
def of_encoder {α} (x : α → put_m) : serializer α α :=
⟨ x, get₀ ⟩
def of_decoder {α} (x : get_m α) : serializer α α :=
⟨ put₀, x ⟩
section applicative
@[simp]
lemma encoder_ser_field (f : β → α) (x : serializer α α) (w : β) :
(ser_field_with x f).encoder w = x.encoder (f w) := rfl
@[simp]
lemma encoder_up (x : serializer α α) (w : ulift α) :
(serializer.up x).encoder w = pliftable.up' _ (x.encoder $ w.down) := rfl
@[simp]
lemma encoder_of_encoder (x : α → put_m) (w : α) :
(of_encoder x).encoder w = x w := rfl
@[simp]
lemma decoder_ser_field (f : β → α) (x : serializer α α) :
(ser_field_with x f).decoder = x.decoder := rfl
@[simp]
lemma decoder_up (x : serializer α α) :
(serializer.up x).decoder = (x.decoder).up ulift.up := rfl
@[simp]
lemma decoder_of_decoder (x : get_m α) :
(of_decoder x).decoder = x := rfl
end applicative
end serializer
namespace serial
open serializer
def of_serializer {α} (s : serializer α α)
(h : ∀ w, there_and_back_again s w = pure w) : serial α :=
{ encode := s.encoder
, decode := s.decoder
, correctness := @h }
def of_serializer₁ {f : Type u → Type v}
(s : Π α, serializer α α → serializer (f α) (f α))
(h : ∀ α ser, valid_serializer ser →
∀ w, there_and_back_again (s α ser) w = pure w)
(h₀ : ∀ {α} ser w, (s α (of_encoder (encoder ser))).encoder w = (s α ser).encoder w)
(h₁ : ∀ {α} ser, (s α (of_decoder (decoder ser))).decoder = (s α ser).decoder) : serial1 f :=
{ encode := λ α put, (s α (of_encoder put)).encoder
, decode := λ α get, (s α (of_decoder get)).decoder
, correctness := by { introv hh, simp [h₀ ⟨put, get⟩,h₁ ⟨put,get⟩], apply h; assumption } }
def of_serializer₂ {f : Type u → Type v → Type w}
(s : Π α β, serializer α α →
serializer β β →
serializer (f α β) (f α β))
(h : ∀ α β serα serβ, valid_serializer serα → valid_serializer serβ →
∀ w, there_and_back_again (s α β serα serβ) w = pure w)
(h₀ : ∀ {α β} serα serβ w, (s α β (of_encoder (encoder serα)) (of_encoder (encoder serβ))).encoder w = (s α β serα serβ).encoder w)
(h₁ : ∀ {α β} serα serβ, (s α β (of_decoder (decoder serα)) (of_decoder (decoder serβ))).decoder = (s α β serα serβ).decoder) : serial2 f :=
{ encode := λ α β putα putβ, (s α β (of_encoder putα) (of_encoder putβ)).encoder
, decode := λ α β getα getβ, (s α β (of_decoder getα) (of_decoder getβ)).decoder
, correctness := by { introv hα hβ, simp [h₀ ⟨putα,getα⟩ ⟨putβ,getβ⟩,h₁ ⟨putα,getα⟩ ⟨putβ,getβ⟩],
apply h; assumption } }
end serial
namespace tactic
open interactive
open interactive.types
open lean.parser
meta def interactive.mk_serializer (p : parse texpr) : tactic unit :=
do g ← mk_mvar,
refine ``(serial.of_serializer %%p %%g) <|>
refine ``(serial.of_serializer₁ (λ α ser, %%p) %%g _ _) <|>
refine ``(serial.of_serializer₂ (λ α β ser_α ser_β, %%p) %%g _ _),
gs ← get_goals,
set_goals [g],
vs ← intros,
cases vs.ilast,
iterate $
applyc ``serializer.there_and_back_again_map <|>
applyc ``serializer.there_and_back_again_pure <|>
applyc ``serializer.there_and_back_again_seq,
gs' ← get_goals,
set_goals (gs ++ gs'),
repeat $
intros >>
`[simp *] <|>
reflexivity
end tactic
|
0929491b1518d0b1e8f6a2c9d77b49869d159829 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/run/pred_using_structure_cmd.lean | 37fc3aecbf245b492089f25b3c48c081dec73344 | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 345 | lean | variable {A : Type}
structure has_refl (R : A → A → Prop) : Prop :=
(refl : ∀ a, R a a)
structure is_equiv (R : A → A → Prop) extends has_refl R : Prop :=
(symm : ∀ a b, R a b → R b a)
(trans : ∀ a b c, R a b → R b c → R a c)
#check @has_refl.refl
#check @is_equiv.symm
#check @is_equiv.trans
#check @is_equiv.to_has_refl
|
722c9decd8682ffac7c5a173a29588225b68c53b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/analysis/special_functions/arsinh.lean | 71819a35c1fafb1dc6075490575510174aa32028 | [] | 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,909 | lean | /-
Copyright (c) 2020 James Arthur. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: James Arthur, Chris Hughes, Shing Tak Lam
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.analysis.special_functions.trigonometric
import Mathlib.PostPort
namespace Mathlib
/-!
# Inverse of the sinh function
In this file we prove that sinh is bijective and hence has an
inverse, arsinh.
## Main Results
- `sinh_injective`: The proof that `sinh` is injective
- `sinh_surjective`: The proof that `sinh` is surjective
- `sinh_bijective`: The proof `sinh` is bijective
- `arsinh`: The inverse function of `sinh`
## Tags
arsinh, arcsinh, argsinh, asinh, sinh injective, sinh bijective, sinh surjective
-/
namespace real
/-- `arsinh` is defined using a logarithm, `arsinh x = log (x + sqrt(1 + x^2))`. -/
def arsinh (x : ℝ) : ℝ :=
log (x + sqrt (1 + x ^ bit0 1))
/-- `sinh` is injective, `∀ a b, sinh a = sinh b → a = b`. -/
theorem sinh_injective : function.injective sinh :=
strict_mono.injective sinh_strict_mono
/-- `arsinh` is the right inverse of `sinh`. -/
theorem sinh_arsinh (x : ℝ) : sinh (arsinh x) = x := sorry
/-- `sinh` is surjective, `∀ b, ∃ a, sinh a = b`. In this case, we use `a = arsinh b`. -/
theorem sinh_surjective : function.surjective sinh :=
function.left_inverse.surjective sinh_arsinh
/-- `sinh` is bijective, both injective and surjective. -/
theorem sinh_bijective : function.bijective sinh :=
{ left := sinh_injective, right := sinh_surjective }
/-- A rearrangement and `sqrt` of `real.cosh_sq_sub_sinh_sq`. -/
theorem sqrt_one_add_sinh_sq (x : ℝ) : sqrt (1 + sinh x ^ bit0 1) = cosh x := sorry
/-- `arsinh` is the left inverse of `sinh`. -/
theorem arsinh_sinh (x : ℝ) : arsinh (sinh x) = x :=
function.right_inverse_of_injective_of_left_inverse sinh_injective sinh_arsinh x
|
b2a1841f79feb290ebe9048a89d924757bb5eef8 | 07c76fbd96ea1786cc6392fa834be62643cea420 | /hott/homotopy/quaternionic_hopf.hlean | 5fa538bf3e1620143a9e6c2141c0138c41bd35fa | [
"Apache-2.0"
] | permissive | fpvandoorn/lean2 | 5a430a153b570bf70dc8526d06f18fc000a60ad9 | 0889cf65b7b3cebfb8831b8731d89c2453dd1e9f | refs/heads/master | 1,592,036,508,364 | 1,545,093,958,000 | 1,545,093,958,000 | 75,436,854 | 0 | 0 | null | 1,480,718,780,000 | 1,480,718,780,000 | null | UTF-8 | Lean | false | false | 4,290 | hlean | /-
Copyright (c) 2016 Ulrik Buchholtz and Egbert Rijke. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ulrik Buchholtz, Egbert Rijke
The H-space structure on S³ and the quaternionic Hopf fibration
(using the imaginaroid structure on S⁰).
-/
import .complex_hopf .imaginaroid
open eq equiv is_equiv circle is_conn trunc is_trunc sphere susp imaginaroid pointed bool join
namespace hopf
definition involutive_neg_bool [instance] : involutive_neg bool :=
⦃ involutive_neg, neg := bnot, neg_neg := by intro a; induction a: reflexivity ⦄
definition involutive_neg_circle [instance] : involutive_neg circle :=
by change involutive_neg (susp bool); exact _
definition has_star_circle [instance] : has_star circle :=
by change has_star (susp bool); exact _
-- this is the "natural" conjugation defined using the base-loop recursor
definition circle_star [reducible] : S¹ → S¹ :=
circle.elim base loop⁻¹
definition circle_neg_id (x : S¹) : -x = x :=
begin
fapply (rec2_on x),
{ exact seg2⁻¹ },
{ exact seg1 },
{ apply eq_pathover, rewrite ap_id, krewrite elim_merid,
apply square_of_eq, reflexivity },
{ apply eq_pathover, rewrite ap_id, krewrite elim_merid,
apply square_of_eq, apply trans (con.left_inv seg2),
apply inverse, exact con.left_inv seg1 }
end
definition circle_mul_neg (x y : S¹) : x * (-y) = - x * y :=
by rewrite [circle_neg_id,circle_neg_id]
definition circle_star_eq (x : S¹) : x* = circle_star x :=
begin
fapply (rec2_on x),
{ reflexivity },
{ exact seg2⁻¹ ⬝ (tr_constant seg1 base)⁻¹ },
{ apply eq_pathover, krewrite elim_merid, rewrite elim_seg1,
apply square_of_eq, apply trans
(ap (λw, w ⬝ (tr_constant seg1 base)⁻¹) (con.right_inv seg2)⁻¹),
apply con.assoc },
{ apply eq_pathover, krewrite elim_merid, rewrite elim_seg2,
apply square_of_eq, rewrite [↑circle.loop,con_inv,inv_inv,idp_con],
apply con.assoc }
end
open prod prod.ops
definition circle_norm (x : S¹) : x * x* = 1 :=
begin
rewrite circle_star_eq, induction x,
{ reflexivity },
{ apply eq_pathover, rewrite ap_constant,
krewrite [-ap_compose' (λz : S¹ × S¹, circle_mul z.1 z.2)
(λa : S¹, (a, circle_star a))],
rewrite [-ap_compose' (prod_functor (λa : S¹, a) circle_star)
(λa : S¹, (a, a))],
rewrite ap_diagonal,
krewrite [ap_prod_functor (λa : S¹, a) circle_star loop loop],
rewrite [ap_id,↑circle_star], krewrite elim_loop,
krewrite (ap_binary circle_mul loop loop⁻¹),
rewrite [ap_inv,↑circle_mul,elim_loop,ap_id,↑circle_turn,con.left_inv],
constructor }
end
definition circle_star_mul (x y : S¹) : (x * y)* = y* * x* :=
begin
induction x,
{ apply inverse, exact circle_mul_base (y*) },
{ apply eq_pathover, induction y,
{ exact natural_square
(λa : S¹, ap (λb : S¹, b*) (circle_mul_base a)) loop },
{ apply is_prop.elimo } }
end
open sphere.ops
definition imaginaroid_sphere_zero [instance]
: imaginaroid (S 0) :=
⦃ imaginaroid, involutive_neg_bool,
mul := circle_mul,
one_mul := circle_base_mul,
mul_one := circle_mul_base,
mul_neg := circle_mul_neg,
norm := circle_norm,
star_mul := circle_star_mul ⦄
definition sphere_three_h_space [instance] : h_space (S 3) :=
@h_space_equiv_closed (join S¹ S¹)
(cd_h_space (S 0) circle_assoc) (S 3) (join_sphere 1 1)
definition is_conn_sphere_three : is_conn 0 (S 3) :=
begin
have le02 : trunc_index.le 0 2,
from trunc_index.le.step
(trunc_index.le.step (trunc_index.le.tr_refl 0)),
exact @is_conn_of_le (S 3) 0 2 le02 (is_conn_sphere 3)
-- apply is_conn_of_le (S 3) le02
-- doesn't find is_conn_sphere instance
end
local attribute is_conn_sphere_three [instance]
definition quaternionic_hopf' : S 7 → S 4 :=
begin
intro x, apply @sigma.pr1 (susp (S 3)) (hopf (S 3)),
apply inv (hopf.total (S 3)), apply inv (join_sphere 3 3), exact x
end
definition quaternionic_hopf [constructor] : S 7 →* S 4 :=
pmap.mk quaternionic_hopf' idp
end hopf
|
87fbddc35a7b177c5a842e5d6b665c49e69b5f0e | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /stage0/src/Lean/Elab/Match.lean | baf49bc7455a6a3c8286cdc92591ada13dd34fc9 | [
"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 | 40,802 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Match.MatchPatternAttr
import Lean.Meta.Match.Match
import Lean.Elab.SyntheticMVars
import Lean.Elab.App
import Lean.Parser.Term
namespace Lean.Elab.Term
open Meta
open Lean.Parser.Term
/- This modules assumes "match"-expressions use the following syntax.
```lean
def matchDiscr := parser! optional (try (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> termParser
def «match» := parser!:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts
```
-/
structure MatchAltView where
ref : Syntax
patterns : Array Syntax
rhs : Syntax
deriving Inhabited
private def expandSimpleMatch (stx discr lhsVar rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
let newStx ← `(let $lhsVar := $discr; $rhs)
withMacroExpansion stx newStx <| elabTerm newStx expectedType?
private def expandSimpleMatchWithType (stx discr lhsVar type rhs : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
let newStx ← `(let $lhsVar : $type := $discr; $rhs)
withMacroExpansion stx newStx <| elabTerm newStx expectedType?
private def elabDiscrsWitMatchType (discrStxs : Array Syntax) (matchType : Expr) (expectedType : Expr) : TermElabM (Array Expr × Bool) := do
let mut discrs := #[]
let mut i := 0
let mut matchType := matchType
let mut isDep := false
for discrStx in discrStxs do
i := i + 1
matchType ← whnf matchType
match matchType with
| Expr.forallE _ d b _ =>
let discr ← fullApproxDefEq <| elabTermEnsuringType discrStx[1] d
trace[Elab.match]! "discr #{i} {discr} : {d}"
if b.hasLooseBVars then
isDep := true
matchType ← b.instantiate1 discr
discrs := discrs.push discr
| _ =>
throwError! "invalid type provided to match-expression, function type with arity #{discrStxs.size} expected"
pure (discrs, isDep)
private def mkUserNameFor (e : Expr) : TermElabM Name :=
match e with
| Expr.fvar fvarId _ => do pure (← getLocalDecl fvarId).userName
| _ => mkFreshBinderName
/-- Return true iff `n` is an auxiliary variable created by `expandNonAtomicDiscrs?` -/
def isAuxDiscrName (n : Name) : Bool :=
n.hasMacroScopes && n.eraseMacroScopes == `_discr
-- See expandNonAtomicDiscrs?
private def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do
let term := discr[1]
match (← isLocalIdent? term) with
| some e@(Expr.fvar fvarId _) =>
let localDecl ← getLocalDecl fvarId
if !isAuxDiscrName localDecl.userName then
pure e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?`
else
pure localDecl.value
| _ => throwErrorAt discr "unexpected discriminant"
structure ElabMatchTypeAndDiscsResult where
discrs : Array Expr
matchType : Expr
isDep : Bool
alts : Array MatchAltView
private def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr)
: TermElabM ElabMatchTypeAndDiscsResult := do
let numDiscrs := discrStxs.size
if matchOptType.isNone then
let rec loop (i : Nat) (discrs : Array Expr) (matchType : Expr) (isDep : Bool) (matchAltViews : Array MatchAltView) := do
match i with
| 0 => return { discrs := discrs.reverse, matchType := matchType, isDep := isDep, alts := matchAltViews }
| i+1 =>
let discrStx := discrStxs[i]
let discr ← elabAtomicDiscr discrStx
let discr ← instantiateMVars discr
let discrType ← inferType discr
let discrType ← instantiateMVars discrType
let matchTypeBody ← kabstract matchType discr
let isDep := isDep || matchTypeBody.hasLooseBVars
let userName ← mkUserNameFor discr
if discrStx[0].isNone then
loop i (discrs.push discr) (Lean.mkForall userName BinderInfo.default discrType matchTypeBody) isDep matchAltViews
else
let identStx := discrStx[0][0]
withLocalDeclD userName discrType fun x => do
let eqType ← mkEq discr x
withLocalDeclD identStx.getId eqType fun h => do
let matchTypeBody := matchTypeBody.instantiate1 x
let matchType ← mkForallFVars #[x, h] matchTypeBody
let refl ← mkEqRefl discr
let discrs := (discrs.push refl).push discr
let matchAltViews := matchAltViews.map fun altView =>
{ altView with patterns := altView.patterns.insertAt (i+1) identStx }
loop i discrs matchType isDep matchAltViews
loop discrStxs.size (discrs := #[]) (isDep := false) expectedType matchAltViews
else
let matchTypeStx := matchOptType[0][1]
let matchType ← elabType matchTypeStx
let (discrs, isDep) ← elabDiscrsWitMatchType discrStxs matchType expectedType
return { discrs := discrs, matchType := matchType, isDep := isDep, alts := matchAltViews }
def expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do
matchAlts.mapM fun matchAlt => do
let patterns ← matchAlt.patterns.mapM expandMacros
pure { matchAlt with patterns := patterns }
/- Given `stx` a match-expression, return its alternatives. -/
private def getMatchAlts : Syntax → Array MatchAltView
| `(match $discrs,* $[: $ty?]? with $alts:matchAlt*) =>
alts.map fun alt => match alt with
| `(matchAltExpr| | $patterns,* => $rhs) => {
ref := alt,
patterns := patterns,
rhs := rhs
}
| _ => unreachable!
| _ => unreachable!
/--
Auxiliary annotation used to mark terms marked with the "inaccessible" annotation `.(t)` and
`_` in patterns. -/
def mkInaccessible (e : Expr) : Expr :=
mkAnnotation `_inaccessible e
def inaccessible? (e : Expr) : Option Expr :=
annotation? `_inaccessible e
inductive PatternVar where
| localVar (userName : Name)
-- anonymous variables (`_`) are encoded using metavariables
| anonymousVar (mvarId : MVarId)
instance : ToString PatternVar := ⟨fun
| PatternVar.localVar x => toString x
| PatternVar.anonymousVar mvarId => s!"?m{mvarId}"⟩
builtin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind
/--
Create an auxiliary Syntax node wrapping a fresh metavariable id.
We use this kind of Syntax for representing `_` occurring in patterns.
The metavariables are created before we elaborate the patterns into `Expr`s. -/
private def mkMVarSyntax : TermElabM Syntax := do
let mvarId ← mkFreshId
return Syntax.node `MVarWithIdKind #[Syntax.node mvarId #[]]
/-- Given a syntax node constructed using `mkMVarSyntax`, return its MVarId -/
private def getMVarSyntaxMVarId (stx : Syntax) : MVarId :=
stx[0].getKind
/--
The elaboration function for `Syntax` created using `mkMVarSyntax`.
It just converts the metavariable id wrapped by the Syntax into an `Expr`. -/
@[builtinTermElab MVarWithIdKind] def elabMVarWithIdKind : TermElab := fun stx expectedType? =>
return mkInaccessible <| mkMVar (getMVarSyntaxMVarId stx)
@[builtinTermElab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do
let e ← elabTerm stx[1] expectedType?
return mkInaccessible e
/-
Patterns define new local variables.
This module collect them and preprocess `_` occurring in patterns.
Recall that an `_` may represent anonymous variables or inaccessible terms
that are implied by typing constraints. Thus, we represent them with fresh named holes `?x`.
After we elaborate the pattern, if the metavariable remains unassigned, we transform it into
a regular pattern variable. Otherwise, it becomes an inaccessible term.
Macros occurring in patterns are expanded before the `collectPatternVars` method is executed.
The following kinds of Syntax are handled by this module
- Constructor applications
- Applications of functions tagged with the `[matchPattern]` attribute
- Identifiers
- Anonymous constructors
- Structure instances
- Inaccessible terms
- Named patterns
- Tuple literals
- Type ascriptions
- Literals: num, string and char
-/
namespace CollectPatternVars
structure State where
found : NameSet := {}
vars : Array PatternVar := #[]
abbrev M := StateRefT State TermElabM
private def throwCtorExpected {α} : M α :=
throwError "invalid pattern, constructor or constant marked with '[matchPattern]' expected"
private def getNumExplicitCtorParams (ctorVal : ConstructorVal) : TermElabM Nat :=
forallBoundedTelescope ctorVal.type ctorVal.numParams fun ps _ => do
let mut result := 0
for p in ps do
let localDecl ← getLocalDecl p.fvarId!
if localDecl.binderInfo.isExplicit then
result := result+1
pure result
private def throwInvalidPattern {α} : M α :=
throwError "invalid pattern"
namespace CtorApp
/-
An application in a pattern can be
1- A constructor application
The elaborator assumes fields are accessible and inductive parameters are not accessible.
2- A regular application `(f ...)` where `f` is tagged with `[matchPattern]`.
The elaborator assumes implicit arguments are not accessible and explicit ones are accessible.
-/
structure Context where
funId : Syntax
ctorVal? : Option ConstructorVal -- It is `some`, if constructor application
explicit : Bool
ellipsis : Bool
paramDecls : Array LocalDecl
paramDeclIdx : Nat := 0
namedArgs : Array NamedArg
args : List Arg
newArgs : Array Syntax := #[]
deriving Inhabited
private def isDone (ctx : Context) : Bool :=
ctx.paramDeclIdx ≥ ctx.paramDecls.size
private def finalize (ctx : Context) : M Syntax := do
if ctx.namedArgs.isEmpty && ctx.args.isEmpty then
let fStx ← `(@$(ctx.funId):ident)
return Syntax.mkApp fStx ctx.newArgs
else
throwError "too many arguments"
private def isNextArgAccessible (ctx : Context) : Bool :=
let i := ctx.paramDeclIdx
match ctx.ctorVal? with
| some ctorVal => i ≥ ctorVal.numParams -- For constructor applications only fields are accessible
| none =>
if h : i < ctx.paramDecls.size then
-- For `[matchPattern]` applications, only explicit parameters are accessible.
let d := ctx.paramDecls.get ⟨i, h⟩
d.binderInfo.isExplicit
else
false
private def getNextParam (ctx : Context) : LocalDecl × Context :=
let i := ctx.paramDeclIdx
let d := ctx.paramDecls[i]
(d, { ctx with paramDeclIdx := ctx.paramDeclIdx + 1 })
private def pushNewArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) (arg : Arg) : M Context :=
match arg with
| Arg.stx stx => do
let stx ← if accessible then collect stx else pure stx
return { ctx with newArgs := ctx.newArgs.push stx }
| _ => unreachable!
private def processExplicitArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) : M Context :=
match ctx.args with
| [] =>
if ctx.ellipsis then do
let hole ← `(_)
pushNewArg collect accessible ctx (Arg.stx hole)
else
throwError! "explicit parameter is missing, unused named arguments {ctx.namedArgs.map fun narg => narg.name}"
| arg::args => do
let ctx := { ctx with args := args }
pushNewArg collect accessible ctx arg
private def processImplicitArg (collect : Syntax → M Syntax) (accessible : Bool) (ctx : Context) : M Context :=
if ctx.explicit then
processExplicitArg collect accessible ctx
else do
let hole ← `(_)
pushNewArg collect accessible ctx (Arg.stx hole)
private partial def processCtorAppAux (collect : Syntax → M Syntax) (ctx : Context) : M Syntax := do
if isDone ctx then
finalize ctx
else
let accessible := isNextArgAccessible ctx
let (d, ctx) := getNextParam ctx
match ctx.namedArgs.findIdx? fun namedArg => namedArg.name == d.userName with
| some idx =>
let arg := ctx.namedArgs[idx]
let ctx := { ctx with namedArgs := ctx.namedArgs.eraseIdx idx }
let ctx ← pushNewArg collect accessible ctx arg.val
processCtorAppAux collect ctx
| none =>
let ctx ← match d.binderInfo with
| BinderInfo.implicit => processImplicitArg collect accessible ctx
| BinderInfo.instImplicit => processImplicitArg collect accessible ctx
| _ => processExplicitArg collect accessible ctx
processCtorAppAux collect ctx
def processCtorApp (collect : Syntax → M Syntax) (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) : M Syntax := do
let args := args.toList
let (fId, explicit) ← match f with
| `($fId:ident) => pure (fId, false)
| `(@$fId:ident) => pure (fId, true)
| _ => throwError "identifier expected"
let some (Expr.const fName _ _) ← resolveId? fId "pattern" | throwCtorExpected
let fInfo ← getConstInfo fName
forallTelescopeReducing fInfo.type fun xs _ => do
let paramDecls ← xs.mapM (getFVarLocalDecl ·)
match fInfo with
| ConstantInfo.ctorInfo val =>
processCtorAppAux collect
{ funId := fId, explicit := explicit, ctorVal? := val, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis }
| _ =>
let env ← getEnv
if hasMatchPatternAttribute env fName then
processCtorAppAux collect
{ funId := fId, explicit := explicit, ctorVal? := none, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis }
else
throwCtorExpected
end CtorApp
def processCtorApp (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do
let (f, namedArgs, args, ellipsis) ← expandApp stx true
CtorApp.processCtorApp collect f namedArgs args ellipsis
def processCtor (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do
CtorApp.processCtorApp collect stx #[] #[] false
private def processVar (idStx : Syntax) : M Syntax := do
unless idStx.isIdent do
throwErrorAt idStx "identifier expected"
let id := idStx.getId
unless id.eraseMacroScopes.isAtomic do
throwError "invalid pattern variable, must be atomic"
if (← get).found.contains id then
throwError! "invalid pattern, variable '{id}' occurred more than once"
modify fun s => { s with vars := s.vars.push (PatternVar.localVar id), found := s.found.insert id }
return idStx
/- Check whether `stx` is a pattern variable or constructor-like (i.e., constructor or constant tagged with `[matchPattern]` attribute) -/
private def processId (collect : Syntax → M Syntax) (stx : Syntax) : M Syntax := do
let env ← getEnv
match (← resolveId? stx "pattern") with
| none => processVar stx
| some f => match f with
| Expr.const fName _ _ =>
match env.find? fName with
| some (ConstantInfo.ctorInfo _) => processCtor collect stx
| some _ =>
if hasMatchPatternAttribute env fName then
processCtor collect stx
else
processVar stx
| none => throwCtorExpected
| _ => processVar stx
private def nameToPattern : Name → TermElabM Syntax
| Name.anonymous => `(Name.anonymous)
| Name.str p s _ => do let p ← nameToPattern p; `(Name.str $p $(quote s) _)
| Name.num p n _ => do let p ← nameToPattern p; `(Name.num $p $(quote n) _)
private def quotedNameToPattern (stx : Syntax) : TermElabM Syntax :=
match stx[0].isNameLit? with
| some val => nameToPattern val
| none => throwIllFormedSyntax
partial def collect (stx : Syntax) : M Syntax := do
match stx with
| Syntax.node k args => withRef stx <| withFreshMacroScope do
if k == `Lean.Parser.Term.app then
processCtorApp collect stx
else if k == `Lean.Parser.Term.anonymousCtor then
let elems ← args[1].getArgs.mapSepElemsM collect
return Syntax.node k (args.set! 1 <| mkNullNode elems)
else if k == `Lean.Parser.Term.structInst then
/-
```
parser! "{" >> optional (atomic (termParser >> " with "))
>> manyIndent (group (structInstField >> optional ", "))
>> optional ".."
>> optional (" : " >> termParser)
>> " }"
```
-/
let withMod := args[1]
unless withMod.isNone do
throwErrorAt withMod "invalid struct instance pattern, 'with' is not allowed in patterns"
let fields ← args[2].getArgs.mapM fun p => do
-- p is of the form (group (structInstField >> optional ", "))
let field := p[0]
-- parser! structInstLVal >> " := " >> termParser
let newVal ← collect field[2]
let field := field.setArg 2 newVal
pure <| field.setArg 0 field
return Syntax.node k (args.set! 2 <| mkNullNode fields)
else if k == `Lean.Parser.Term.hole then
let r ← mkMVarSyntax
modify fun s => { s with vars := s.vars.push <| PatternVar.anonymousVar <| getMVarSyntaxMVarId r }
return r
else if k == `Lean.Parser.Term.paren then
let arg := args[1]
if arg.isNone then
return stx -- `()`
else
let t := arg[0]
let s := arg[1]
if s.isNone || s[0].getKind == `Lean.Parser.Term.typeAscription then
-- Ignore `s`, since it empty or it is a type ascription
let t ← collect t
let arg := arg.setArg 0 t
return Syntax.node k (args.set! 1 arg)
else
-- Tuple literal is a constructor
let t ← collect t
let arg := arg.setArg 0 t
let tupleTail := s[0]
let tupleTailElems := tupleTail[1].getArgs
let tupleTailElems ← tupleTailElems.mapSepElemsM collect
let tupleTail := tupleTail.setArg 1 <| mkNullNode tupleTailElems
let s := s.setArg 0 tupleTail
let arg := arg.setArg 1 s
return Syntax.node k (args.set! 1 arg)
else if k == `Lean.Parser.Term.explicitUniv then
processCtor collect stx[0]
else if k == `Lean.Parser.Term.namedPattern then
/- Recall that
def namedPattern := check... >> tparser! "@" >> termParser -/
let id := stx[0]
discard <| processVar id
let pat := stx[2]
let pat ← collect pat
`(_root_.namedPattern $id $pat)
else if k == `Lean.Parser.Term.inaccessible then
return stx
else if k == strLitKind then
return stx
else if k == numLitKind then
return stx
else if k == scientificLitKind then
return stx
else if k == charLitKind then
return stx
else if k == `Lean.Parser.Term.quotedName then
/- Quoted names have an elaboration function associated with them, and they will not be macro expanded.
Note that macro expansion is not a good option since it produces a term using the smart constructors `Name.mkStr`, `Name.mkNum`
instead of the constructors `Name.str` and `Name.num` -/
quotedNameToPattern stx
else if k == choiceKind then
throwError "invalid pattern, notation is ambiguous"
else
throwInvalidPattern
| Syntax.ident .. =>
processId collect stx
| stx =>
throwInvalidPattern
def main (alt : MatchAltView) : M MatchAltView := do
let patterns ← alt.patterns.mapM fun p => do
trace[Elab.match]! "collecting variables at pattern: {p}"
collect p
return { alt with patterns := patterns }
end CollectPatternVars
private def collectPatternVars (alt : MatchAltView) : TermElabM (Array PatternVar × MatchAltView) := do
let (alt, s) ← (CollectPatternVars.main alt).run {}
return (s.vars, alt)
/- Return the pattern variables in the given pattern.
Remark: this method is not used here, but in other macros (e.g., at `Do.lean`). -/
def getPatternVars (patternStx : Syntax) : TermElabM (Array PatternVar) := do
let patternStx ← liftMacroM <| expandMacros patternStx
let (_, s) ← (CollectPatternVars.collect patternStx).run {}
return s.vars
def getPatternsVars (patterns : Array Syntax) : TermElabM (Array PatternVar) := do
let collect : CollectPatternVars.M Unit := do
for pattern in patterns do
discard <| CollectPatternVars.collect (← liftMacroM <| expandMacros pattern)
let (_, s) ← collect.run {}
return s.vars
/- We convert the collected `PatternVar`s intro `PatternVarDecl` -/
inductive PatternVarDecl where
/- For `anonymousVar`, we create both a metavariable and a free variable. The free variable is used as an assignment for the metavariable
when it is not assigned during pattern elaboration. -/
| anonymousVar (mvarId : MVarId) (fvarId : FVarId)
| localVar (fvarId : FVarId)
private partial def withPatternVars {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : TermElabM α :=
let rec loop (i : Nat) (decls : Array PatternVarDecl) := do
if h : i < pVars.size then
match pVars.get ⟨i, h⟩ with
| PatternVar.anonymousVar mvarId =>
let type ← mkFreshTypeMVar
let userName ← mkFreshBinderName
withLocalDecl userName BinderInfo.default type fun x =>
loop (i+1) (decls.push (PatternVarDecl.anonymousVar mvarId x.fvarId!))
| PatternVar.localVar userName =>
let type ← mkFreshTypeMVar
withLocalDecl userName BinderInfo.default type fun x =>
loop (i+1) (decls.push (PatternVarDecl.localVar x.fvarId!))
else
/- We must create the metavariables for `PatternVar.anonymousVar` AFTER we create the new local decls using `withLocalDecl`.
Reason: their scope must include the new local decls since some of them are assigned by typing constraints. -/
decls.forM fun decl => match decl with
| PatternVarDecl.anonymousVar mvarId fvarId => do
let type ← inferType (mkFVar fvarId)
discard <| mkFreshExprMVarWithId mvarId type
| _ => pure ()
k decls
loop 0 #[]
private def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : TermElabM (Array Expr × Expr) := do
let mut patterns := #[]
let mut matchType := matchType
for patternStx in patternStxs do
matchType ← whnf matchType
match matchType with
| Expr.forallE _ d b _ =>
let pattern ← elabTermEnsuringType patternStx d
matchType := b.instantiate1 pattern
patterns := patterns.push pattern
| _ => throwError "unexpected match type"
return (patterns, matchType)
def finalizePatternDecls (patternVarDecls : Array PatternVarDecl) : TermElabM (Array LocalDecl) := do
let mut decls := #[]
for pdecl in patternVarDecls do
match pdecl with
| PatternVarDecl.localVar fvarId =>
let decl ← getLocalDecl fvarId
let decl ← instantiateLocalDeclMVars decl
decls := decls.push decl
| PatternVarDecl.anonymousVar mvarId fvarId =>
let e ← instantiateMVars (mkMVar mvarId);
trace[Elab.match]! "finalizePatternDecls: mvarId: {mvarId} := {e}, fvar: {mkFVar fvarId}"
match e with
| Expr.mvar newMVarId _ =>
/- Metavariable was not assigned, or assigned to another metavariable. So,
we assign to the auxiliary free variable we created at `withPatternVars` to `newMVarId`. -/
assignExprMVar newMVarId (mkFVar fvarId)
trace[Elab.match]! "finalizePatternDecls: {mkMVar newMVarId} := {mkFVar fvarId}"
let decl ← getLocalDecl fvarId
let decl ← instantiateLocalDeclMVars decl
decls := decls.push decl
| _ => pure ()
return decls
open Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult)
namespace ToDepElimPattern
structure State where
found : NameSet := {}
localDecls : Array LocalDecl
newLocals : NameSet := {}
abbrev M := StateRefT State TermElabM
private def alreadyVisited (fvarId : FVarId) : M Bool := do
let s ← get
return s.found.contains fvarId
private def markAsVisited (fvarId : FVarId) : M Unit :=
modify fun s => { s with found := s.found.insert fvarId }
private def throwInvalidPattern {α} (e : Expr) : M α :=
throwError! "invalid pattern {indentExpr e}"
/- Create a new LocalDecl `x` for the metavariable `mvar`, and return `Pattern.var x` -/
private def mkLocalDeclFor (mvar : Expr) : M Pattern := do
let mvarId := mvar.mvarId!
let s ← get
match (← getExprMVarAssignment? mvarId) with
| some val => return Pattern.inaccessible val
| none =>
let fvarId ← mkFreshId
let type ← inferType mvar
/- HACK: `fvarId` is not in the scope of `mvarId`
If this generates problems in the future, we should update the metavariable declarations. -/
assignExprMVar mvarId (mkFVar fvarId)
let userName ← mkFreshBinderName
let newDecl := LocalDecl.cdecl arbitrary fvarId userName type BinderInfo.default;
modify fun s =>
{ s with
newLocals := s.newLocals.insert fvarId,
localDecls :=
match s.localDecls.findIdx? fun decl => mvar.occurs decl.type with
| none => s.localDecls.push newDecl -- None of the existing declarations depend on `mvar`
| some i => s.localDecls.insertAt i newDecl }
return Pattern.var fvarId
partial def main (e : Expr) : M Pattern := do
let isLocalDecl (fvarId : FVarId) : M Bool := do
return (← get).localDecls.any fun d => d.fvarId == fvarId
let mkPatternVar (fvarId : FVarId) (e : Expr) : M Pattern := do
if (← alreadyVisited fvarId) then
return Pattern.inaccessible e
else
markAsVisited fvarId
return Pattern.var e.fvarId!
let mkInaccessible (e : Expr) : M Pattern := do
match e with
| Expr.fvar fvarId _ =>
if (← isLocalDecl fvarId) then
mkPatternVar fvarId e
else
return Pattern.inaccessible e
| _ =>
return Pattern.inaccessible e
match inaccessible? e with
| some t => mkInaccessible t
| none =>
match e.arrayLit? with
| some (α, lits) =>
return Pattern.arrayLit α (← lits.mapM main)
| none =>
if e.isAppOfArity `namedPattern 3 then
let p ← main <| e.getArg! 2
match e.getArg! 1 with
| Expr.fvar fvarId _ => return Pattern.as fvarId p
| _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'"
else if e.isNatLit || e.isStringLit || e.isCharLit then
return Pattern.val e
else if e.isFVar then
let fvarId := e.fvarId!
unless (← isLocalDecl fvarId) do
throwInvalidPattern e
mkPatternVar fvarId e
else if e.isMVar then
mkLocalDeclFor e
else
let newE ← whnf e
if newE != e then
main newE
else matchConstCtor e.getAppFn (fun _ => throwInvalidPattern e) fun v us => do
let args := e.getAppArgs
unless args.size == v.numParams + v.numFields do
throwInvalidPattern e
let params := args.extract 0 v.numParams
let fields := args.extract v.numParams args.size
let fields ← fields.mapM main
return Pattern.ctor v.name us params.toList fields.toList
end ToDepElimPattern
def withDepElimPatterns {α} (localDecls : Array LocalDecl) (ps : Array Expr) (k : Array LocalDecl → Array Pattern → TermElabM α) : TermElabM α := do
let (patterns, s) ← (ps.mapM ToDepElimPattern.main).run { localDecls := localDecls }
let localDecls ← s.localDecls.mapM fun d => instantiateLocalDeclMVars d
/- toDepElimPatterns may have added new localDecls. Thus, we must update the local context before we execute `k` -/
let lctx ← getLCtx
let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.erase d.fvarId) lctx
let lctx := localDecls.foldl (fun (lctx : LocalContext) d => lctx.addDecl d) lctx
withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) do
k localDecls patterns
private def withElaboratedLHS {α} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr)
(k : AltLHS → Expr → TermElabM α) : TermElabM α := do
let (patterns, matchType) ← withSynthesize <| elabPatterns patternStxs matchType
let localDecls ← finalizePatternDecls patternVarDecls
let patterns ← patterns.mapM (instantiateMVars ·)
withDepElimPatterns localDecls patterns fun localDecls patterns =>
k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType
def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : TermElabM (AltLHS × Expr) := withRef alt.ref do
let (patternVars, alt) ← collectPatternVars alt
trace[Elab.match]! "patternVars: {patternVars}"
withPatternVars patternVars fun patternVarDecls => do
withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => do
let rhs ← elabTermEnsuringType alt.rhs matchType
let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr
let rhs ← if xs.isEmpty then pure <| mkSimpleThunk rhs else mkLambdaFVars xs rhs
trace[Elab.match]! "rhs: {rhs}"
return (altLHS, rhs)
def mkMatcher (elimName : Name) (matchType : Expr) (numDiscrs : Nat) (lhss : List AltLHS) : TermElabM MatcherResult :=
Meta.Match.mkMatcher elimName matchType numDiscrs lhss
register_builtin_option match.ignoreUnusedAlts : Bool := {
defValue := false
descr := "if true, do not generate error if an alternative is not used"
}
def reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do
unless result.counterExamples.isEmpty do
withHeadRefOnly <| throwError! "missing cases:\n{Meta.Match.counterExamplesToMessageData result.counterExamples}"
unless match.ignoreUnusedAlts.get (← getOptions) || result.unusedAltIdxs.isEmpty do
let mut i := 0
for alt in altLHSS do
if result.unusedAltIdxs.contains i then
withRef alt.ref do
logError "redundant alternative"
i := i + 1
/--
If `altLHSS + rhss` is encoding `| PUnit.unit => rhs[0]`, return `rhs[0]`
Otherwise, return none.
-/
private def isMatchUnit? (altLHSS : List Match.AltLHS) (rhss : Array Expr) : MetaM (Option Expr) := do
assert! altLHSS.length == rhss.size
match altLHSS with
| [ { fvarDecls := [], patterns := [ Pattern.ctor `PUnit.unit .. ], .. } ] =>
/- Recall that for alternatives of the form `| PUnit.unit => rhs`, `rhss[0]` is of the form `fun _ : Unit => b`. -/
match rhss[0] with
| Expr.lam _ _ b _ => return if b.hasLooseBVars then none else b
| _ => return none
| _ => return none
private def elabMatchAux (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr)
: TermElabM Expr := do
let (discrs, matchType, altLHSS, isDep, rhss) ← commitIfDidNotPostpone do
let ⟨discrs, matchType, isDep, altViews⟩ ← elabMatchTypeAndDiscrs discrStxs matchOptType altViews expectedType
let matchAlts ← liftMacroM <| expandMacrosInPatterns altViews
trace[Elab.match]! "matchType: {matchType}"
let alts ← matchAlts.mapM fun alt => elabMatchAltView alt matchType
/-
We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be
able to elaborate examples such as:
```
def f (x : Nat) : Option Nat := none
def g (xs : List (Nat × Nat)) : IO Unit :=
xs.forM fun x =>
match f x.fst with
| _ => pure ()
```
If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because
the type of `x` is only available after we proces the last argument of `List.forM`.
We apply pending default types to make sure we can process examples such as
```
let (a, b) := (0, 0)
```
-/
synthesizeSyntheticMVarsUsingDefault
let rhss := alts.map Prod.snd
let matchType ← instantiateMVars matchType
let altLHSS ← alts.toList.mapM fun alt => do
let altLHS ← Match.instantiateAltLHSMVars alt.1
/- Remark: we try to postpone before throwing an error.
The combinator `commitIfDidNotPostpone` ensures we backtrack any updates that have been performed.
The quick-check `waitExpectedTypeAndDiscrs` minimizes the number of scenarios where we have to postpone here.
Here is an example that passes the `waitExpectedTypeAndDiscrs` test, but postpones here.
```
def bad (ps : Array (Nat × Nat)) : Array (Nat × Nat) :=
(ps.filter fun (p : Prod _ _) =>
match p with
| (x, y) => x == 0)
++
ps
```
When we try to elaborate `fun (p : Prod _ _) => ...` for the first time, we haven't propagated the type of `ps` yet
because `Array.filter` has type `{α : Type u_1} → (α → Bool) → (as : Array α) → optParam Nat 0 → optParam Nat (Array.size as) → Array α`
However, the partial type annotation `(p : Prod _ _)` makes sure we succeed at the quick-check `waitExpectedTypeAndDiscrs`.
-/
withRef altLHS.ref do
for d in altLHS.fvarDecls do
if d.hasExprMVar then
withExistingLocalDecls altLHS.fvarDecls do
tryPostpone
throwMVarError m!"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}"
for p in altLHS.patterns do
if p.hasExprMVar then
withExistingLocalDecls altLHS.fvarDecls do
tryPostpone
throwMVarError m!"invalid match-expression, pattern contains metavariables{indentExpr (← p.toExpr)}"
pure altLHS
return (discrs, matchType, altLHSS, isDep, rhss)
if let some r ← if isDep then pure none else isMatchUnit? altLHSS rhss then
return r
else
let numDiscrs := discrs.size
let matcherName ← mkAuxName `match
let matcherResult ← mkMatcher matcherName matchType numDiscrs altLHSS
let motive ← forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType
reportMatcherResultErrors altLHSS matcherResult
let r := mkApp matcherResult.matcher motive
let r := mkAppN r discrs
let r := mkAppN r rhss
trace[Elab.match]! "result: {r}"
return r
private def getDiscrs (matchStx : Syntax) : Array Syntax :=
matchStx[1].getSepArgs
private def getMatchOptType (matchStx : Syntax) : Syntax :=
matchStx[2]
private def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) :=
let matchOptType := getMatchOptType matchStx;
if matchOptType.isNone then do
let discrs := getDiscrs matchStx;
let allLocal ← discrs.allM fun discr => Option.isSome <$> isLocalIdent? discr[1]
if allLocal then
return none
else
let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) := do
match discrs with
| [] =>
let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx ", ");
pure (matchStx.setArg 1 discrs)
| discr :: discrs =>
-- Recall that
-- matchDiscr := parser! optional (ident >> ":") >> termParser
let term := discr[1]
match (← isLocalIdent? term) with
| some _ => loop discrs (discrsNew.push discr)
| none => withFreshMacroScope do
let d ← `(_discr);
unless isAuxDiscrName d.getId do -- Use assertion?
throwError "unexpected internal auxiliary discriminant name"
let discrNew := discr.setArg 1 d;
let r ← loop discrs (discrsNew.push discrNew)
`(let _discr := $term; $r)
return some (← loop discrs.toList #[])
else
-- We do not pull non atomic discriminants when match type is provided explicitly by the user
return none
private def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do
tryPostponeIfNoneOrMVar expectedType?
match expectedType? with
| some expectedType => pure expectedType
| none => mkFreshTypeMVar
private def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do
-- We don't wait for the discriminants types when match type is provided by user
if getMatchOptType matchStx |>.isNone then
let discrs := getDiscrs matchStx
for discr in discrs do
let term := discr[1]
match (← isLocalIdent? term) with
| none => throwErrorAt discr "unexpected discriminant" -- see `expandNonAtomicDiscrs?
| some d =>
let dType ← inferType d
trace[Elab.match]! "discr {d} : {dType}"
tryPostponeIfMVar dType
/-
We (try to) elaborate a `match` only when the expected type is available.
If the `matchType` has not been provided by the user, we also try to postpone elaboration if the type
of a discriminant is not available. That is, it is of the form `(?m ...)`.
We use `expandNonAtomicDiscrs?` to make sure all discriminants are local variables.
This is a standard trick we use in the elaborator, and it is also used to elaborate structure instances.
Suppose, we are trying to elaborate
```
match g x with
| ... => ...
```
`expandNonAtomicDiscrs?` converts it intro
```
let _discr := g x
match _discr with
| ... => ...
```
Thus, at `tryPostponeIfDiscrTypeIsMVar` we only need to check whether the type of `_discr` is not of the form `(?m ...)`.
Note that, the auxiliary variable `_discr` is expanded at `elabAtomicDiscr`.
This elaboration technique is needed to elaborate terms such as:
```lean
xs.filter fun (a, b) => a > b
```
which are syntax sugar for
```lean
List.filter (fun p => match p with | (a, b) => a > b) xs
```
When we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet.
-/
private def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
tryPostponeIfNoneOrMVar expectedType?
tryPostponeIfDiscrTypeIsMVar matchStx
match expectedType? with
| some expectedType => return expectedType
| none => mkFreshTypeMVar
/-
```
parser!:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts
```
Remark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`.
-/
private def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
let expectedType ← waitExpectedTypeAndDiscrs stx expectedType?
let discrStxs := (getDiscrs stx).map fun d => d
let altViews := getMatchAlts stx
let matchOptType := getMatchOptType stx
elabMatchAux discrStxs altViews matchOptType expectedType
private def isPatternVar (stx : Syntax) : TermElabM Bool := do
match (← resolveId? stx "pattern") with
| none => isAtomicIdent stx
| some f => match f with
| Expr.const fName _ _ =>
match (← getEnv).find? fName with
| some (ConstantInfo.ctorInfo _) => return false
| _ => isAtomicIdent stx
| _ => isAtomicIdent stx
where
isAtomicIdent (stx : Syntax) : Bool :=
stx.isIdent && stx.getId.eraseMacroScopes.isAtomic
-- parser! "match " >> sepBy1 termParser ", " >> optType >> " with " >> matchAlts
@[builtinTermElab «match»] def elabMatch : TermElab := fun stx expectedType? => do
match stx with
| `(match $discr:term with | $y:ident => $rhs:term) =>
if (← isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType?
| `(match $discr:term : $type with | $y:ident => $rhs:term) =>
if (← isPatternVar y) then expandSimpleMatchWithType stx discr y type rhs expectedType? else elabMatchDefault stx expectedType?
| _ => elabMatchDefault stx expectedType?
where
elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
match (← expandNonAtomicDiscrs? stx) with
| some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?
| none =>
let discrs := getDiscrs stx;
let matchOptType := getMatchOptType stx;
if !matchOptType.isNone && discrs.any fun d => !d[0].isNone then
throwErrorAt matchOptType "match expected type should not be provided when discriminants with equality proofs are used"
elabMatchCore stx expectedType?
builtin_initialize
registerTraceClass `Elab.match
-- parser!:leadPrec "nomatch " >> termParser
@[builtinTermElab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? =>
match stx with
| `(nomatch $discrExpr) => do
let expectedType ← waitExpectedType expectedType?
let discr := Syntax.node `Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr]
elabMatchAux #[discr] #[] mkNullNode expectedType
| _ => throwUnsupportedSyntax
end Lean.Elab.Term
|
24a4c12cf041ea301d56fdf43cad924e1545d58c | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/group_theory/submonoid/basic.lean | 442244b2971161cc77378bd748f2b22d480c99c8 | [
"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 | 20,847 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard,
Amelia Livingston, Yury Kudryashov
-/
import group_theory.subsemigroup.basic
/-!
# Submonoids: definition and `complete_lattice` structure
This file defines bundled multiplicative and additive submonoids. We also define
a `complete_lattice` structure on `submonoid`s, define the closure of a set as the minimal submonoid
that includes this set, and prove a few results about extending properties from a dense set (i.e.
a set with `closure s = ⊤`) to the whole monoid, see `submonoid.dense_induction` and
`monoid_hom.of_mdense`.
## Main definitions
* `submonoid M`: the type of bundled submonoids of a monoid `M`; the underlying set is given in
the `carrier` field of the structure, and should be accessed through coercion as in `(S : set M)`.
* `add_submonoid M` : the type of bundled submonoids of an additive monoid `M`.
For each of the following definitions in the `submonoid` namespace, there is a corresponding
definition in the `add_submonoid` namespace.
* `submonoid.copy` : copy of a submonoid with `carrier` replaced by a set that is equal but possibly
not definitionally equal to the carrier of the original `submonoid`.
* `submonoid.closure` : monoid closure of a set, i.e., the least submonoid that includes the set.
* `submonoid.gi` : `closure : set M → submonoid M` and coercion `coe : submonoid M → set M`
form a `galois_insertion`;
* `monoid_hom.eq_mlocus`: the submonoid of elements `x : M` such that `f x = g x`;
* `monoid_hom.of_mdense`: if a map `f : M → N` between two monoids satisfies `f 1 = 1` and
`f (x * y) = f x * f y` for `y` from some dense set `s`, then `f` is a monoid homomorphism.
E.g., if `f : ℕ → M` satisfies `f 0 = 0` and `f (x + 1) = f x + f 1`, then `f` is an additive
monoid homomorphism.
## Implementation notes
Submonoid inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as
membership of a submonoid's underlying set.
Note that `submonoid M` does not actually require `monoid M`, instead requiring only the weaker
`mul_one_class M`.
This file is designed to have very few dependencies. In particular, it should not use natural
numbers. `submonoid` is implemented by extending `subsemigroup` requiring `one_mem'`.
## Tags
submonoid, submonoids
-/
variables {M : Type*} {N : Type*}
variables {A : Type*}
section non_assoc
variables [mul_one_class M] {s : set M}
variables [add_zero_class A] {t : set A}
/-- `one_mem_class S M` says `S` is a type of subsets `s ≤ M`, such that `1 ∈ s` for all `s`. -/
class one_mem_class (S : Type*) (M : out_param $ Type*) [has_one M] [set_like S M] :=
(one_mem : ∀ (s : S), (1 : M) ∈ s)
export one_mem_class (one_mem)
/-- `zero_mem_class S M` says `S` is a type of subsets `s ≤ M`, such that `0 ∈ s` for all `s`. -/
class zero_mem_class (S : Type*) (M : out_param $ Type*) [has_zero M] [set_like S M] :=
(zero_mem : ∀ (s : S), (0 : M) ∈ s)
export zero_mem_class (zero_mem)
attribute [to_additive] one_mem_class
section
set_option old_structure_cmd true
/-- A submonoid of a monoid `M` is a subset containing 1 and closed under multiplication. -/
@[ancestor subsemigroup]
structure submonoid (M : Type*) [mul_one_class M] extends subsemigroup M :=
(one_mem' : (1 : M) ∈ carrier)
end
/-- A submonoid of a monoid `M` can be considered as a subsemigroup of that monoid. -/
add_decl_doc submonoid.to_subsemigroup
/-- `submonoid_class S M` says `S` is a type of subsets `s ≤ M` that contain `1`
and are closed under `(*)` -/
class submonoid_class (S : Type*) (M : out_param $ Type*) [mul_one_class M] [set_like S M]
extends mul_mem_class S M :=
(one_mem : ∀ (s : S), (1 : M) ∈ s)
section
set_option old_structure_cmd true
/-- An additive submonoid of an additive monoid `M` is a subset containing 0 and
closed under addition. -/
@[ancestor add_subsemigroup]
structure add_submonoid (M : Type*) [add_zero_class M] extends add_subsemigroup M :=
(zero_mem' : (0 : M) ∈ carrier)
end
/-- An additive submonoid of an additive monoid `M` can be considered as an
additive subsemigroup of that additive monoid. -/
add_decl_doc add_submonoid.to_add_subsemigroup
/-- `add_submonoid_class S M` says `S` is a type of subsets `s ≤ M` that contain `0`
and are closed under `(+)` -/
class add_submonoid_class (S : Type*) (M : out_param $ Type*) [add_zero_class M] [set_like S M]
extends add_mem_class S M :=
(zero_mem : ∀ (s : S), (0 : M) ∈ s)
attribute [to_additive] submonoid submonoid_class
@[to_additive, priority 100] -- See note [lower instance priority]
instance submonoid_class.to_one_mem_class (S : Type*) (M : out_param $ Type*) [mul_one_class M]
[set_like S M] [h : submonoid_class S M] : one_mem_class S M :=
{ ..h }
@[to_additive]
lemma pow_mem {M} [monoid M] {A : Type*} [set_like A M] [submonoid_class A M] {S : A} {x : M}
(hx : x ∈ S) : ∀ (n : ℕ), x ^ n ∈ S
| 0 := by { rw pow_zero, exact one_mem_class.one_mem S }
| (n + 1) := by { rw pow_succ, exact mul_mem_class.mul_mem hx (pow_mem n) }
namespace submonoid
@[to_additive]
instance : set_like (submonoid M) M :=
{ coe := submonoid.carrier,
coe_injective' := λ p q h, by cases p; cases q; congr' }
@[to_additive]
instance : submonoid_class (submonoid M) M :=
{ one_mem := submonoid.one_mem',
mul_mem := submonoid.mul_mem' }
/-- See Note [custom simps projection] -/
@[to_additive " See Note [custom simps projection]"]
def simps.coe (S : submonoid M) : set M := S
initialize_simps_projections submonoid (carrier → coe)
initialize_simps_projections add_submonoid (carrier → coe)
@[simp, to_additive]
lemma mem_carrier {s : submonoid M} {x : M} : x ∈ s.carrier ↔ x ∈ s := iff.rfl
@[simp, to_additive]
lemma mem_mk {s : set M} {x : M} (h_one) (h_mul) : x ∈ mk s h_one h_mul ↔ x ∈ s := iff.rfl
@[simp, to_additive]
lemma coe_set_mk {s : set M} (h_one) (h_mul) : (mk s h_one h_mul : set M) = s := rfl
@[simp, to_additive]
lemma mk_le_mk {s t : set M} (h_one) (h_mul) (h_one') (h_mul') :
mk s h_one h_mul ≤ mk t h_one' h_mul' ↔ s ⊆ t := iff.rfl
/-- Two submonoids are equal if they have the same elements. -/
@[ext, to_additive "Two `add_submonoid`s are equal if they have the same elements."]
theorem ext {S T : submonoid M}
(h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h
/-- Copy a submonoid replacing `carrier` with a set that is equal to it. -/
@[to_additive "Copy an additive submonoid replacing `carrier` with a set that is equal to it."]
protected def copy (S : submonoid M) (s : set M) (hs : s = S) : submonoid M :=
{ carrier := s,
one_mem' := hs.symm ▸ S.one_mem',
mul_mem' := λ _ _, hs.symm ▸ S.mul_mem' }
variable {S : submonoid M}
@[simp, to_additive] lemma coe_copy {s : set M} (hs : s = S) :
(S.copy s hs : set M) = s := rfl
@[to_additive] lemma copy_eq {s : set M} (hs : s = S) : S.copy s hs = S :=
set_like.coe_injective hs
variable (S)
/-- A submonoid contains the monoid's 1. -/
@[to_additive "An `add_submonoid` contains the monoid's 0."]
protected theorem one_mem : (1 : M) ∈ S := one_mem S
/-- A submonoid is closed under multiplication. -/
@[to_additive "An `add_submonoid` is closed under addition."]
protected theorem mul_mem {x y : M} : x ∈ S → y ∈ S → x * y ∈ S := mul_mem
/-- The submonoid `M` of the monoid `M`. -/
@[to_additive "The additive submonoid `M` of the `add_monoid M`."]
instance : has_top (submonoid M) :=
⟨{ carrier := set.univ,
one_mem' := set.mem_univ 1,
mul_mem' := λ _ _ _ _, set.mem_univ _ }⟩
/-- The trivial submonoid `{1}` of an monoid `M`. -/
@[to_additive "The trivial `add_submonoid` `{0}` of an `add_monoid` `M`."]
instance : has_bot (submonoid M) :=
⟨{ carrier := {1},
one_mem' := set.mem_singleton 1,
mul_mem' := λ a b ha hb, by { simp only [set.mem_singleton_iff] at *, rw [ha, hb, mul_one] }}⟩
@[to_additive]
instance : inhabited (submonoid M) := ⟨⊥⟩
@[simp, to_additive] lemma mem_bot {x : M} : x ∈ (⊥ : submonoid M) ↔ x = 1 := set.mem_singleton_iff
@[simp, to_additive] lemma mem_top (x : M) : x ∈ (⊤ : submonoid M) := set.mem_univ x
@[simp, to_additive] lemma coe_top : ((⊤ : submonoid M) : set M) = set.univ := rfl
@[simp, to_additive] lemma coe_bot : ((⊥ : submonoid M) : set M) = {1} := rfl
/-- The inf of two submonoids is their intersection. -/
@[to_additive "The inf of two `add_submonoid`s is their intersection."]
instance : has_inf (submonoid M) :=
⟨λ S₁ S₂,
{ carrier := S₁ ∩ S₂,
one_mem' := ⟨S₁.one_mem, S₂.one_mem⟩,
mul_mem' := λ _ _ ⟨hx, hx'⟩ ⟨hy, hy'⟩,
⟨S₁.mul_mem hx hy, S₂.mul_mem hx' hy'⟩ }⟩
@[simp, to_additive]
lemma coe_inf (p p' : submonoid M) : ((p ⊓ p' : submonoid M) : set M) = p ∩ p' := rfl
@[simp, to_additive]
lemma mem_inf {p p' : submonoid M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
@[to_additive]
instance : has_Inf (submonoid M) :=
⟨λ s,
{ carrier := ⋂ t ∈ s, ↑t,
one_mem' := set.mem_bInter $ λ i h, i.one_mem,
mul_mem' := λ x y hx hy, set.mem_bInter $ λ i h,
i.mul_mem (by apply set.mem_Inter₂.1 hx i h) (by apply set.mem_Inter₂.1 hy i h) }⟩
@[simp, norm_cast, to_additive]
lemma coe_Inf (S : set (submonoid M)) : ((Inf S : submonoid M) : set M) = ⋂ s ∈ S, ↑s := rfl
@[to_additive]
lemma mem_Inf {S : set (submonoid M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂
@[to_additive]
lemma mem_infi {ι : Sort*} {S : ι → submonoid M} {x : M} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i :=
by simp only [infi, mem_Inf, set.forall_range_iff]
@[simp, norm_cast, to_additive]
lemma coe_infi {ι : Sort*} {S : ι → submonoid M} : (↑(⨅ i, S i) : set M) = ⋂ i, S i :=
by simp only [infi, coe_Inf, set.bInter_range]
/-- Submonoids of a monoid form a complete lattice. -/
@[to_additive "The `add_submonoid`s of an `add_monoid` form a complete lattice."]
instance : complete_lattice (submonoid M) :=
{ le := (≤),
lt := (<),
bot := (⊥),
bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem,
top := (⊤),
le_top := λ S x hx, mem_top x,
inf := (⊓),
Inf := has_Inf.Inf,
le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩,
inf_le_left := λ a b x, and.left,
inf_le_right := λ a b x, and.right,
.. complete_lattice_of_Inf (submonoid M) $ λ s,
is_glb.of_image (λ S T,
show (S : set M) ≤ T ↔ S ≤ T, from set_like.coe_subset_coe) is_glb_binfi }
@[simp, to_additive]
lemma subsingleton_iff : subsingleton (submonoid M) ↔ subsingleton M :=
⟨ λ h, by exactI ⟨λ x y,
have ∀ i : M, i = 1 := λ i, mem_bot.mp $ subsingleton.elim (⊤ : submonoid M) ⊥ ▸ mem_top i,
(this x).trans (this y).symm⟩,
λ h, by exactI ⟨λ x y, submonoid.ext $ λ i, subsingleton.elim 1 i ▸ by simp [submonoid.one_mem]⟩⟩
@[simp, to_additive]
lemma nontrivial_iff : nontrivial (submonoid M) ↔ nontrivial M :=
not_iff_not.mp (
(not_nontrivial_iff_subsingleton.trans subsingleton_iff).trans
not_nontrivial_iff_subsingleton.symm)
@[to_additive]
instance [subsingleton M] : unique (submonoid M) :=
⟨⟨⊥⟩, λ a, @subsingleton.elim _ (subsingleton_iff.mpr ‹_›) a _⟩
@[to_additive]
instance [nontrivial M] : nontrivial (submonoid M) := nontrivial_iff.mpr ‹_›
/-- The `submonoid` generated by a set. -/
@[to_additive "The `add_submonoid` generated by a set"]
def closure (s : set M) : submonoid M := Inf {S | s ⊆ S}
@[to_additive]
lemma mem_closure {x : M} : x ∈ closure s ↔ ∀ S : submonoid M, s ⊆ S → x ∈ S :=
mem_Inf
/-- The submonoid generated by a set includes the set. -/
@[simp, to_additive "The `add_submonoid` generated by a set includes the set."]
lemma subset_closure : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx
@[to_additive]
lemma not_mem_of_not_mem_closure {P : M} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h)
variable {S}
open set
/-- A submonoid `S` includes `closure s` if and only if it includes `s`. -/
@[simp, to_additive "An additive submonoid `S` includes `closure s` if and only if it includes `s`"]
lemma closure_le : closure s ≤ S ↔ s ⊆ S :=
⟨subset.trans subset_closure, λ h, Inf_le h⟩
/-- Submonoid closure of a set is monotone in its argument: if `s ⊆ t`,
then `closure s ≤ closure t`. -/
@[to_additive "Additive submonoid closure of a set is monotone in its argument: if `s ⊆ t`,
then `closure s ≤ closure t`"]
lemma closure_mono ⦃s t : set M⦄ (h : s ⊆ t) : closure s ≤ closure t :=
closure_le.2 $ subset.trans h subset_closure
@[to_additive]
lemma closure_eq_of_le (h₁ : s ⊆ S) (h₂ : S ≤ closure s) : closure s = S :=
le_antisymm (closure_le.2 h₁) h₂
variable (S)
/-- An induction principle for closure membership. If `p` holds for `1` and all elements of `s`, and
is preserved under multiplication, then `p` holds for all elements of the closure of `s`. -/
@[elab_as_eliminator, to_additive "An induction principle for additive closure membership. If `p`
holds for `0` and all elements of `s`, and is preserved under addition, then `p` holds for all
elements of the additive closure of `s`."]
lemma closure_induction {p : M → Prop} {x} (h : x ∈ closure s)
(Hs : ∀ x ∈ s, p x) (H1 : p 1)
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
(@closure_le _ _ _ ⟨p, Hmul, H1⟩).2 Hs h
/-- A dependent version of `submonoid.closure_induction`. -/
@[elab_as_eliminator, to_additive "A dependent version of `add_submonoid.closure_induction`. "]
lemma closure_induction' (s : set M) {p : Π x, x ∈ closure s → Prop}
(Hs : ∀ x (h : x ∈ s), p x (subset_closure h))
(H1 : p 1 (one_mem _))
(Hmul : ∀ x hx y hy, p x hx → p y hy → p (x * y) (mul_mem hx hy))
{x} (hx : x ∈ closure s) :
p x hx :=
begin
refine exists.elim _ (λ (hx : x ∈ closure s) (hc : p x hx), hc),
exact closure_induction hx
(λ x hx, ⟨_, Hs x hx⟩) ⟨_, H1⟩ (λ x y ⟨hx', hx⟩ ⟨hy', hy⟩, ⟨_, Hmul _ _ _ _ hx hy⟩),
end
/-- An induction principle for closure membership for predicates with two arguments. -/
@[elab_as_eliminator, to_additive "An induction principle for additive closure membership for
predicates with two arguments."]
lemma closure_induction₂ {p : M → M → Prop} {x} {y : M} (hx : x ∈ closure s) (hy : y ∈ closure s)
(Hs : ∀ (x ∈ s) (y ∈ s), p x y)
(H1_left : ∀ x, p 1 x)
(H1_right : ∀ x, p x 1)
(Hmul_left : ∀ x y z, p x z → p y z → p (x * y) z)
(Hmul_right : ∀ x y z, p z x → p z y → p z (x * y)) : p x y :=
closure_induction hx
(λ x xs, closure_induction hy (Hs x xs) (H1_right x) (λ z y h₁ h₂, Hmul_right z _ _ h₁ h₂))
(H1_left y) (λ x z h₁ h₂, Hmul_left _ _ _ h₁ h₂)
/-- If `s` is a dense set in a monoid `M`, `submonoid.closure s = ⊤`, then in order to prove that
some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 1`,
and verify that `p x` and `p y` imply `p (x * y)`. -/
@[elab_as_eliminator, to_additive "If `s` is a dense set in an additive monoid `M`,
`add_submonoid.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M`
it suffices to verify `p x` for `x ∈ s`, verify `p 0`, and verify that `p x` and `p y` imply
`p (x + y)`."]
lemma dense_induction {p : M → Prop} (x : M) {s : set M} (hs : closure s = ⊤)
(Hs : ∀ x ∈ s, p x) (H1 : p 1)
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
have ∀ x ∈ closure s, p x, from λ x hx, closure_induction hx Hs H1 Hmul,
by simpa [hs] using this x
variable (M)
/-- `closure` forms a Galois insertion with the coercion to set. -/
@[to_additive "`closure` forms a Galois insertion with the coercion to set."]
protected def gi : galois_insertion (@closure M _) coe :=
{ choice := λ s _, closure s,
gc := λ s t, closure_le,
le_l_u := λ s, subset_closure,
choice_eq := λ s h, rfl }
variable {M}
/-- Closure of a submonoid `S` equals `S`. -/
@[simp, to_additive "Additive closure of an additive submonoid `S` equals `S`"]
lemma closure_eq : closure (S : set M) = S := (submonoid.gi M).l_u_eq S
@[simp, to_additive] lemma closure_empty : closure (∅ : set M) = ⊥ :=
(submonoid.gi M).gc.l_bot
@[simp, to_additive] lemma closure_univ : closure (univ : set M) = ⊤ :=
@coe_top M _ ▸ closure_eq ⊤
@[to_additive]
lemma closure_union (s t : set M) : closure (s ∪ t) = closure s ⊔ closure t :=
(submonoid.gi M).gc.l_sup
@[to_additive]
lemma closure_Union {ι} (s : ι → set M) : closure (⋃ i, s i) = ⨆ i, closure (s i) :=
(submonoid.gi M).gc.l_supr
@[simp, to_additive]
lemma closure_singleton_le_iff_mem (m : M) (p : submonoid M) :
closure {m} ≤ p ↔ m ∈ p :=
by rw [closure_le, singleton_subset_iff, set_like.mem_coe]
@[to_additive]
lemma mem_supr {ι : Sort*} (p : ι → submonoid M) {m : M} :
(m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) :=
begin
rw [← closure_singleton_le_iff_mem, le_supr_iff],
simp only [closure_singleton_le_iff_mem],
end
@[to_additive]
lemma supr_eq_closure {ι : Sort*} (p : ι → submonoid M) :
(⨆ i, p i) = submonoid.closure (⋃ i, (p i : set M)) :=
by simp_rw [submonoid.closure_Union, submonoid.closure_eq]
@[to_additive]
lemma disjoint_def {p₁ p₂ : submonoid M} :
disjoint p₁ p₂ ↔ ∀ {x : M}, x ∈ p₁ → x ∈ p₂ → x = 1 :=
show (∀ x, x ∈ p₁ ∧ x ∈ p₂ → x ∈ ({1} : set M)) ↔ _, by simp
@[to_additive]
lemma disjoint_def' {p₁ p₂ : submonoid M} :
disjoint p₁ p₂ ↔ ∀ {x y : M}, x ∈ p₁ → y ∈ p₂ → x = y → x = 1 :=
disjoint_def.trans ⟨λ h x y hx hy hxy, h hx $ hxy.symm ▸ hy,
λ h x hx hx', h hx hx' rfl⟩
end submonoid
namespace monoid_hom
variables [mul_one_class N]
open submonoid
/-- The submonoid of elements `x : M` such that `f x = g x` -/
@[to_additive "The additive submonoid of elements `x : M` such that `f x = g x`"]
def eq_mlocus (f g : M →* N) : submonoid M :=
{ carrier := {x | f x = g x},
one_mem' := by rw [set.mem_set_of_eq, f.map_one, g.map_one],
mul_mem' := λ x y (hx : _ = _) (hy : _ = _), by simp [*] }
/-- If two monoid homomorphisms are equal on a set, then they are equal on its submonoid closure. -/
@[to_additive "If two monoid homomorphisms are equal on a set, then they are equal on its submonoid
closure."]
lemma eq_on_mclosure {f g : M →* N} {s : set M} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s ≤ f.eq_mlocus g, from closure_le.2 h
@[to_additive]
lemma eq_of_eq_on_mtop {f g : M →* N} (h : set.eq_on f g (⊤ : submonoid M)) :
f = g :=
ext $ λ x, h trivial
@[to_additive]
lemma eq_of_eq_on_mdense {s : set M} (hs : closure s = ⊤) {f g : M →* N} (h : s.eq_on f g) :
f = g :=
eq_of_eq_on_mtop $ hs ▸ eq_on_mclosure h
end monoid_hom
end non_assoc
section assoc
variables [monoid M] [monoid N] {s : set M}
section is_unit
/-- The submonoid consisting of the units of a monoid -/
@[to_additive "The additive submonoid consisting of the additive units of an additive monoid"]
def is_unit.submonoid (M : Type*) [monoid M] : submonoid M :=
{ carrier := set_of is_unit,
one_mem' := by simp only [is_unit_one, set.mem_set_of_eq],
mul_mem' := by { intros a b ha hb, rw set.mem_set_of_eq at *, exact is_unit.mul ha hb } }
@[to_additive]
lemma is_unit.mem_submonoid_iff {M : Type*} [monoid M] (a : M) :
a ∈ is_unit.submonoid M ↔ is_unit a :=
begin
change a ∈ set_of is_unit ↔ is_unit a,
rw set.mem_set_of_eq
end
end is_unit
namespace monoid_hom
open submonoid
/-- Let `s` be a subset of a monoid `M` such that the closure of `s` is the whole monoid.
Then `monoid_hom.of_mdense` defines a monoid homomorphism from `M` asking for a proof
of `f (x * y) = f x * f y` only for `y ∈ s`. -/
@[to_additive]
def of_mdense {M N} [monoid M] [monoid N] {s : set M} (f : M → N) (hs : closure s = ⊤)
(h1 : f 1 = 1) (hmul : ∀ x (y ∈ s), f (x * y) = f x * f y) :
M →* N :=
{ to_fun := f,
map_one' := h1,
map_mul' := λ x y, dense_induction y hs (λ y hy x, hmul x y hy) (by simp [h1])
(λ y₁ y₂ h₁ h₂ x, by simp only [← mul_assoc, h₁, h₂]) x }
/-- Let `s` be a subset of an additive monoid `M` such that the closure of `s` is the whole monoid.
Then `add_monoid_hom.of_mdense` defines an additive monoid homomorphism from `M` asking for a proof
of `f (x + y) = f x + f y` only for `y ∈ s`. -/
add_decl_doc add_monoid_hom.of_mdense
@[simp, norm_cast, to_additive] lemma coe_of_mdense (f : M → N) (hs : closure s = ⊤) (h1 hmul) :
⇑(of_mdense f hs h1 hmul) = f := rfl
end monoid_hom
end assoc
|
4a4fca4953dd605da15e0cc597543527379e0510 | bb31430994044506fa42fd667e2d556327e18dfe | /src/combinatorics/configuration.lean | 36221045516c067e1d2297f18449bc811b6ea990 | [
"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 | 23,666 | lean | /-
Copyright (c) 2021 Thomas Browning. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning
-/
import algebra.big_operators.order
import combinatorics.hall.basic
import data.fintype.big_operators
import set_theory.cardinal.finite
/-!
# Configurations of Points and lines
This file introduces abstract configurations of points and lines, and proves some basic properties.
## Main definitions
* `configuration.nondegenerate`: Excludes certain degenerate configurations,
and imposes uniqueness of intersection points.
* `configuration.has_points`: A nondegenerate configuration in which
every pair of lines has an intersection point.
* `configuration.has_lines`: A nondegenerate configuration in which
every pair of points has a line through them.
* `configuration.line_count`: The number of lines through a given point.
* `configuration.point_count`: The number of lines through a given line.
## Main statements
* `configuration.has_lines.card_le`: `has_lines` implies `|P| ≤ |L|`.
* `configuration.has_points.card_le`: `has_points` implies `|L| ≤ |P|`.
* `configuration.has_lines.has_points`: `has_lines` and `|P| = |L|` implies `has_points`.
* `configuration.has_points.has_lines`: `has_points` and `|P| = |L|` implies `has_lines`.
Together, these four statements say that any two of the following properties imply the third:
(a) `has_lines`, (b) `has_points`, (c) `|P| = |L|`.
-/
open_locale big_operators
namespace configuration
variables (P L : Type*) [has_mem P L]
/-- A type synonym. -/
def dual := P
instance [this : inhabited P] : inhabited (dual P) := this
instance [finite P] : finite (dual P) := ‹finite P›
instance [this : fintype P] : fintype (dual P) := this
instance : has_mem (dual L) (dual P) :=
⟨function.swap (has_mem.mem : P → L → Prop)⟩
/-- A configuration is nondegenerate if:
1) there does not exist a line that passes through all of the points,
2) there does not exist a point that is on all of the lines,
3) there is at most one line through any two points,
4) any two lines have at most one intersection point.
Conditions 3 and 4 are equivalent. -/
class nondegenerate : Prop :=
(exists_point : ∀ l : L, ∃ p, p ∉ l)
(exists_line : ∀ p, ∃ l : L, p ∉ l)
(eq_or_eq : ∀ {p₁ p₂ : P} {l₁ l₂ : L}, p₁ ∈ l₁ → p₂ ∈ l₁ → p₁ ∈ l₂ → p₂ ∈ l₂ → p₁ = p₂ ∨ l₁ = l₂)
/-- A nondegenerate configuration in which every pair of lines has an intersection point. -/
class has_points extends nondegenerate P L :=
(mk_point : Π {l₁ l₂ : L} (h : l₁ ≠ l₂), P)
(mk_point_ax : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), mk_point h ∈ l₁ ∧ mk_point h ∈ l₂)
/-- A nondegenerate configuration in which every pair of points has a line through them. -/
class has_lines extends nondegenerate P L :=
(mk_line : Π {p₁ p₂ : P} (h : p₁ ≠ p₂), L)
(mk_line_ax : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), p₁ ∈ mk_line h ∧ p₂ ∈ mk_line h)
open nondegenerate has_points has_lines
instance [nondegenerate P L] : nondegenerate (dual L) (dual P) :=
{ exists_point := @exists_line P L _ _,
exists_line := @exists_point P L _ _,
eq_or_eq := λ l₁ l₂ p₁ p₂ h₁ h₂ h₃ h₄, (@eq_or_eq P L _ _ p₁ p₂ l₁ l₂ h₁ h₃ h₂ h₄).symm }
instance [has_points P L] : has_lines (dual L) (dual P) :=
{ mk_line := @mk_point P L _ _,
mk_line_ax := λ _ _, mk_point_ax }
instance [has_lines P L] : has_points (dual L) (dual P) :=
{ mk_point := @mk_line P L _ _,
mk_point_ax := λ _ _, mk_line_ax }
lemma has_points.exists_unique_point [has_points P L] (l₁ l₂ : L) (hl : l₁ ≠ l₂) :
∃! p, p ∈ l₁ ∧ p ∈ l₂ :=
⟨mk_point hl, mk_point_ax hl,
λ p hp, (eq_or_eq hp.1 (mk_point_ax hl).1 hp.2 (mk_point_ax hl).2).resolve_right hl⟩
lemma has_lines.exists_unique_line [has_lines P L] (p₁ p₂ : P) (hp : p₁ ≠ p₂) :
∃! l : L, p₁ ∈ l ∧ p₂ ∈ l :=
has_points.exists_unique_point (dual L) (dual P) p₁ p₂ hp
variables {P L}
/-- If a nondegenerate configuration has at least as many points as lines, then there exists
an injective function `f` from lines to points, such that `f l` does not lie on `l`. -/
lemma nondegenerate.exists_injective_of_card_le [nondegenerate P L]
[fintype P] [fintype L] (h : fintype.card L ≤ fintype.card P) :
∃ f : L → P, function.injective f ∧ ∀ l, (f l) ∉ l :=
begin
classical,
let t : L → finset P := λ l, (set.to_finset {p | p ∉ l}),
suffices : ∀ s : finset L, s.card ≤ (s.bUnion t).card, -- Hall's marriage theorem
{ obtain ⟨f, hf1, hf2⟩ := (finset.all_card_le_bUnion_card_iff_exists_injective t).mp this,
exact ⟨f, hf1, λ l, set.mem_to_finset.mp (hf2 l)⟩ },
intro s,
by_cases hs₀ : s.card = 0, -- If `s = ∅`, then `s.card = 0 ≤ (s.bUnion t).card`
{ simp_rw [hs₀, zero_le] },
by_cases hs₁ : s.card = 1, -- If `s = {l}`, then pick a point `p ∉ l`
{ obtain ⟨l, rfl⟩ := finset.card_eq_one.mp hs₁,
obtain ⟨p, hl⟩ := exists_point l,
rw [finset.card_singleton, finset.singleton_bUnion, nat.one_le_iff_ne_zero],
exact finset.card_ne_zero_of_mem (set.mem_to_finset.mpr hl) },
suffices : (s.bUnion t)ᶜ.card ≤ sᶜ.card, -- Rephrase in terms of complements (uses `h`)
{ rw [finset.card_compl, finset.card_compl, tsub_le_iff_left] at this,
replace := h.trans this,
rwa [←add_tsub_assoc_of_le s.card_le_univ, le_tsub_iff_left
(le_add_left s.card_le_univ), add_le_add_iff_right] at this },
have hs₂ : (s.bUnion t)ᶜ.card ≤ 1, -- At most one line through two points of `s`
{ refine finset.card_le_one_iff.mpr (λ p₁ p₂ hp₁ hp₂, _),
simp_rw [finset.mem_compl, finset.mem_bUnion, exists_prop, not_exists, not_and,
set.mem_to_finset, set.mem_set_of_eq, not_not] at hp₁ hp₂,
obtain ⟨l₁, l₂, hl₁, hl₂, hl₃⟩ :=
finset.one_lt_card_iff.mp (nat.one_lt_iff_ne_zero_and_ne_one.mpr ⟨hs₀, hs₁⟩),
exact (eq_or_eq (hp₁ l₁ hl₁) (hp₂ l₁ hl₁) (hp₁ l₂ hl₂) (hp₂ l₂ hl₂)).resolve_right hl₃ },
by_cases hs₃ : sᶜ.card = 0,
{ rw [hs₃, le_zero_iff],
rw [finset.card_compl, tsub_eq_zero_iff_le, has_le.le.le_iff_eq (finset.card_le_univ _),
eq_comm, finset.card_eq_iff_eq_univ] at hs₃ ⊢,
rw hs₃,
rw finset.eq_univ_iff_forall at hs₃ ⊢,
exact λ p, exists.elim (exists_line p) -- If `s = univ`, then show `s.bUnion t = univ`
(λ l hl, finset.mem_bUnion.mpr ⟨l, finset.mem_univ l, set.mem_to_finset.mpr hl⟩) },
{ exact hs₂.trans (nat.one_le_iff_ne_zero.mpr hs₃) }, -- If `s < univ`, then consequence of `hs₂`
end
variables {P} (L)
/-- Number of points on a given line. -/
noncomputable def line_count (p : P) : ℕ := nat.card {l : L // p ∈ l}
variables (P) {L}
/-- Number of lines through a given point. -/
noncomputable def point_count (l : L) : ℕ := nat.card {p : P // p ∈ l}
variables (P L)
lemma sum_line_count_eq_sum_point_count [fintype P] [fintype L] :
∑ p : P, line_count L p = ∑ l : L, point_count P l :=
begin
classical,
simp only [line_count, point_count, nat.card_eq_fintype_card, ←fintype.card_sigma],
apply fintype.card_congr,
calc (Σ p, {l : L // p ∈ l}) ≃ {x : P × L // x.1 ∈ x.2} :
(equiv.subtype_prod_equiv_sigma_subtype (∈)).symm
... ≃ {x : L × P // x.2 ∈ x.1} : (equiv.prod_comm P L).subtype_equiv (λ x, iff.rfl)
... ≃ (Σ l, {p // p ∈ l}) : equiv.subtype_prod_equiv_sigma_subtype (λ (l : L) (p : P), p ∈ l),
end
variables {P L}
lemma has_lines.point_count_le_line_count [has_lines P L] {p : P} {l : L} (h : p ∉ l)
[finite {l : L // p ∈ l}] : point_count P l ≤ line_count L p :=
begin
by_cases hf : infinite {p : P // p ∈ l},
{ exactI (le_of_eq nat.card_eq_zero_of_infinite).trans (zero_le (line_count L p)) },
haveI := fintype_of_not_infinite hf,
casesI nonempty_fintype {l : L // p ∈ l},
rw [line_count, point_count, nat.card_eq_fintype_card, nat.card_eq_fintype_card],
have : ∀ p' : {p // p ∈ l}, p ≠ p' := λ p' hp', h ((congr_arg (∈ l) hp').mpr p'.2),
exact fintype.card_le_of_injective (λ p', ⟨mk_line (this p'), (mk_line_ax (this p')).1⟩)
(λ p₁ p₂ hp, subtype.ext ((eq_or_eq p₁.2 p₂.2 (mk_line_ax (this p₁)).2
((congr_arg _ (subtype.ext_iff.mp hp)).mpr (mk_line_ax (this p₂)).2)).resolve_right
(λ h', (congr_arg _ h').mp h (mk_line_ax (this p₁)).1))),
end
lemma has_points.line_count_le_point_count [has_points P L] {p : P} {l : L} (h : p ∉ l)
[hf : finite {p : P // p ∈ l}] : line_count L p ≤ point_count P l :=
@has_lines.point_count_le_line_count (dual L) (dual P) _ _ l p h hf
variables (P L)
/-- If a nondegenerate configuration has a unique line through any two points, then `|P| ≤ |L|`. -/
lemma has_lines.card_le [has_lines P L] [fintype P] [fintype L] :
fintype.card P ≤ fintype.card L :=
begin
classical,
by_contradiction hc₂,
obtain ⟨f, hf₁, hf₂⟩ := nondegenerate.exists_injective_of_card_le (le_of_not_le hc₂),
have := calc ∑ p, line_count L p = ∑ l, point_count P l : sum_line_count_eq_sum_point_count P L
... ≤ ∑ l, line_count L (f l) :
finset.sum_le_sum (λ l hl, has_lines.point_count_le_line_count (hf₂ l))
... = ∑ p in finset.univ.image f, line_count L p :
finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_image_of_mem f hl) (λ l hl, rfl)
(λ l₁ l₂ hl₁ hl₂ hl₃, hf₁ hl₃) (λ p, by simp_rw [finset.mem_image, eq_comm, imp_self])
... < ∑ p, line_count L p : _,
{ exact lt_irrefl _ this },
{ obtain ⟨p, hp⟩ := not_forall.mp (mt (fintype.card_le_of_surjective f) hc₂),
refine finset.sum_lt_sum_of_subset ((finset.univ.image f).subset_univ) (finset.mem_univ p)
_ _ (λ p hp₁ hp₂, zero_le (line_count L p)),
{ simpa only [finset.mem_image, exists_prop, finset.mem_univ, true_and] },
{ rw [line_count, nat.card_eq_fintype_card, fintype.card_pos_iff],
obtain ⟨l, hl⟩ := @exists_line P L _ _ p,
exact let this := not_exists.mp hp l in ⟨⟨mk_line this, (mk_line_ax this).2⟩⟩ } },
end
/-- If a nondegenerate configuration has a unique point on any two lines, then `|L| ≤ |P|`. -/
lemma has_points.card_le [has_points P L] [fintype P] [fintype L] :
fintype.card L ≤ fintype.card P :=
@has_lines.card_le (dual L) (dual P) _ _ _ _
variables {P L}
lemma has_lines.exists_bijective_of_card_eq [has_lines P L]
[fintype P] [fintype L] (h : fintype.card P = fintype.card L) :
∃ f : L → P, function.bijective f ∧ ∀ l, point_count P l = line_count L (f l) :=
begin
classical,
obtain ⟨f, hf1, hf2⟩ := nondegenerate.exists_injective_of_card_le (ge_of_eq h),
have hf3 := (fintype.bijective_iff_injective_and_card f).mpr ⟨hf1, h.symm⟩,
refine ⟨f, hf3, λ l, (finset.sum_eq_sum_iff_of_le
(by exact λ l hl, has_lines.point_count_le_line_count (hf2 l))).mp
((sum_line_count_eq_sum_point_count P L).symm.trans ((finset.sum_bij (λ l hl, f l)
(λ l hl, finset.mem_univ (f l)) (λ l hl, refl (line_count L (f l)))
(λ l₁ l₂ hl₁ hl₂ hl, hf1 hl) (λ p hp, _)).symm)) l (finset.mem_univ l)⟩,
obtain ⟨l, rfl⟩ := hf3.2 p,
exact ⟨l, finset.mem_univ l, rfl⟩,
end
lemma has_lines.line_count_eq_point_count [has_lines P L] [fintype P] [fintype L]
(hPL : fintype.card P = fintype.card L) {p : P} {l : L} (hpl : p ∉ l) :
line_count L p = point_count P l :=
begin
classical,
obtain ⟨f, hf1, hf2⟩ := has_lines.exists_bijective_of_card_eq hPL,
let s : finset (P × L) := set.to_finset {i | i.1 ∈ i.2},
have step1 : ∑ i : P × L, line_count L i.1 = ∑ i : P × L, point_count P i.2,
{ rw [←finset.univ_product_univ, finset.sum_product_right, finset.sum_product],
simp_rw [finset.sum_const, finset.card_univ, hPL, sum_line_count_eq_sum_point_count] },
have step2 : ∑ i in s, line_count L i.1 = ∑ i in s, point_count P i.2,
{ rw [s.sum_finset_product finset.univ (λ p, set.to_finset {l | p ∈ l})],
rw [s.sum_finset_product_right finset.univ (λ l, set.to_finset {p | p ∈ l})],
refine (finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_univ (f l)) (λ l hl, _)
(λ _ _ _ _ h, hf1.1 h) (λ p hp, _)).symm,
{ simp_rw [finset.sum_const, set.to_finset_card, ←nat.card_eq_fintype_card],
change (point_count P l) • (point_count P l) = (line_count L (f l)) • (line_count L (f l)),
rw hf2 },
{ obtain ⟨l, hl⟩ := hf1.2 p,
exact ⟨l, finset.mem_univ l, hl.symm⟩ },
all_goals { simp_rw [finset.mem_univ, true_and, set.mem_to_finset], exact λ p, iff.rfl } },
have step3 : ∑ i in sᶜ, line_count L i.1 = ∑ i in sᶜ, point_count P i.2,
{ rwa [←s.sum_add_sum_compl, ←s.sum_add_sum_compl, step2, add_left_cancel_iff] at step1 },
rw ← set.to_finset_compl at step3,
exact ((finset.sum_eq_sum_iff_of_le (by exact λ i hi, has_lines.point_count_le_line_count
(set.mem_to_finset.mp hi))).mp step3.symm (p, l) (set.mem_to_finset.mpr hpl)).symm,
end
lemma has_points.line_count_eq_point_count [has_points P L] [fintype P] [fintype L]
(hPL : fintype.card P = fintype.card L) {p : P} {l : L} (hpl : p ∉ l) :
line_count L p = point_count P l :=
(@has_lines.line_count_eq_point_count (dual L) (dual P) _ _ _ _ hPL.symm l p hpl).symm
/-- If a nondegenerate configuration has a unique line through any two points, and if `|P| = |L|`,
then there is a unique point on any two lines. -/
noncomputable def has_lines.has_points [has_lines P L] [fintype P] [fintype L]
(h : fintype.card P = fintype.card L) : has_points P L :=
let this : ∀ l₁ l₂ : L, l₁ ≠ l₂ → ∃ p : P, p ∈ l₁ ∧ p ∈ l₂ := λ l₁ l₂ hl, begin
classical,
obtain ⟨f, hf1, hf2⟩ := has_lines.exists_bijective_of_card_eq h,
haveI : nontrivial L := ⟨⟨l₁, l₂, hl⟩⟩,
haveI := fintype.one_lt_card_iff_nontrivial.mp ((congr_arg _ h).mpr fintype.one_lt_card),
have h₁ : ∀ p : P, 0 < line_count L p := λ p, exists.elim (exists_ne p) (λ q hq, (congr_arg _
nat.card_eq_fintype_card).mpr (fintype.card_pos_iff.mpr ⟨⟨mk_line hq, (mk_line_ax hq).2⟩⟩)),
have h₂ : ∀ l : L, 0 < point_count P l := λ l, (congr_arg _ (hf2 l)).mpr (h₁ (f l)),
obtain ⟨p, hl₁⟩ := fintype.card_pos_iff.mp ((congr_arg _ nat.card_eq_fintype_card).mp (h₂ l₁)),
by_cases hl₂ : p ∈ l₂, exact ⟨p, hl₁, hl₂⟩,
have key' : fintype.card {q : P // q ∈ l₂} = fintype.card {l : L // p ∈ l},
{ exact ((has_lines.line_count_eq_point_count h hl₂).trans nat.card_eq_fintype_card).symm.trans
nat.card_eq_fintype_card, },
have : ∀ q : {q // q ∈ l₂}, p ≠ q := λ q hq, hl₂ ((congr_arg (∈ l₂) hq).mpr q.2),
let f : {q : P // q ∈ l₂} → {l : L // p ∈ l} := λ q, ⟨mk_line (this q), (mk_line_ax (this q)).1⟩,
have hf : function.injective f := λ q₁ q₂ hq, subtype.ext ((eq_or_eq q₁.2 q₂.2
(mk_line_ax (this q₁)).2 ((congr_arg _ (subtype.ext_iff.mp hq)).mpr (mk_line_ax
(this q₂)).2)).resolve_right (λ h, (congr_arg _ h).mp hl₂ (mk_line_ax (this q₁)).1)),
have key' := ((fintype.bijective_iff_injective_and_card f).mpr ⟨hf, key'⟩).2,
obtain ⟨q, hq⟩ := key' ⟨l₁, hl₁⟩,
exact ⟨q, (congr_arg _ (subtype.ext_iff.mp hq)).mp (mk_line_ax (this q)).2, q.2⟩,
end in
{ mk_point := λ l₁ l₂ hl, classical.some (this l₁ l₂ hl),
mk_point_ax := λ l₁ l₂ hl, classical.some_spec (this l₁ l₂ hl) }
/-- If a nondegenerate configuration has a unique point on any two lines, and if `|P| = |L|`,
then there is a unique line through any two points. -/
noncomputable def has_points.has_lines [has_points P L] [fintype P] [fintype L]
(h : fintype.card P = fintype.card L) : has_lines P L :=
let this := @has_lines.has_points (dual L) (dual P) _ _ _ _ h.symm in
{ mk_line := λ _ _, this.mk_point,
mk_line_ax := λ _ _, this.mk_point_ax }
variables (P L)
/-- A projective plane is a nondegenerate configuration in which every pair of lines has
an intersection point, every pair of points has a line through them,
and which has three points in general position. -/
class projective_plane extends nondegenerate P L :=
(mk_point : Π {l₁ l₂ : L} (h : l₁ ≠ l₂), P)
(mk_point_ax : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), mk_point h ∈ l₁ ∧ mk_point h ∈ l₂)
(mk_line : Π {p₁ p₂ : P} (h : p₁ ≠ p₂), L)
(mk_line_ax : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), p₁ ∈ mk_line h ∧ p₂ ∈ mk_line h)
(exists_config : ∃ (p₁ p₂ p₃ : P) (l₁ l₂ l₃ : L), p₁ ∉ l₂ ∧ p₁ ∉ l₃ ∧
p₂ ∉ l₁ ∧ p₂ ∈ l₂ ∧ p₂ ∈ l₃ ∧ p₃ ∉ l₁ ∧ p₃ ∈ l₂ ∧ p₃ ∉ l₃)
namespace projective_plane
@[priority 100] -- see Note [lower instance priority]
instance has_points [h : projective_plane P L] : has_points P L := { .. h }
@[priority 100] -- see Note [lower instance priority]
instance has_lines [h : projective_plane P L] : has_lines P L := { .. h }
variables [projective_plane P L]
instance : projective_plane (dual L) (dual P) :=
{ mk_line := @mk_point P L _ _,
mk_line_ax := λ _ _, mk_point_ax,
mk_point := @mk_line P L _ _,
mk_point_ax := λ _ _, mk_line_ax,
exists_config := by
{ obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, h₁₂, h₁₃, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ :=
@exists_config P L _ _,
exact ⟨l₁, l₂, l₃, p₁, p₂, p₃, h₂₁, h₃₁, h₁₂, h₂₂, h₃₂, h₁₃, h₂₃, h₃₃⟩ },
.. dual.nondegenerate P L }
/-- The order of a projective plane is one less than the number of lines through an arbitrary point.
Equivalently, it is one less than the number of points on an arbitrary line. -/
noncomputable def order : ℕ :=
line_count L (classical.some (@exists_config P L _ _)) - 1
lemma card_points_eq_card_lines [fintype P] [fintype L] : fintype.card P = fintype.card L :=
le_antisymm (has_lines.card_le P L) (has_points.card_le P L)
variables {P} (L)
lemma line_count_eq_line_count [finite P] [finite L] (p q : P) :
line_count L p = line_count L q :=
begin
casesI nonempty_fintype P,
casesI nonempty_fintype L,
obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, h₁₂, h₁₃, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := exists_config,
have h := card_points_eq_card_lines P L,
let n := line_count L p₂,
have hp₂ : line_count L p₂ = n := rfl,
have hl₁ : point_count P l₁ = n := (has_lines.line_count_eq_point_count h h₂₁).symm.trans hp₂,
have hp₃ : line_count L p₃ = n := (has_lines.line_count_eq_point_count h h₃₁).trans hl₁,
have hl₃ : point_count P l₃ = n := (has_lines.line_count_eq_point_count h h₃₃).symm.trans hp₃,
have hp₁ : line_count L p₁ = n := (has_lines.line_count_eq_point_count h h₁₃).trans hl₃,
have hl₂ : point_count P l₂ = n := (has_lines.line_count_eq_point_count h h₁₂).symm.trans hp₁,
suffices : ∀ p : P, line_count L p = n, { exact (this p).trans (this q).symm },
refine λ p, or_not.elim (λ h₂, _) (λ h₂, (has_lines.line_count_eq_point_count h h₂).trans hl₂),
refine or_not.elim (λ h₃, _) (λ h₃, (has_lines.line_count_eq_point_count h h₃).trans hl₃),
rwa (eq_or_eq h₂ h₂₂ h₃ h₂₃).resolve_right (λ h, h₃₃ ((congr_arg (has_mem.mem p₃) h).mp h₃₂)),
end
variables (P) {L}
lemma point_count_eq_point_count [finite P] [finite L] (l m : L) :
point_count P l = point_count P m :=
line_count_eq_line_count (dual P) l m
variables {P L}
lemma line_count_eq_point_count [finite P] [finite L] (p : P) (l : L) :
line_count L p = point_count P l :=
exists.elim (exists_point l) $ λ q hq, (line_count_eq_line_count L p q).trans $
by { casesI nonempty_fintype P, casesI nonempty_fintype L,
exact has_lines.line_count_eq_point_count (card_points_eq_card_lines P L) hq }
variables (P L)
lemma dual.order [finite P] [finite L] : order (dual L) (dual P) = order P L :=
congr_arg (λ n, n - 1) (line_count_eq_point_count _ _)
variables {P} (L)
lemma line_count_eq [finite P] [finite L] (p : P) : line_count L p = order P L + 1 :=
begin
classical,
obtain ⟨q, -, -, l, -, -, -, -, h, -⟩ := classical.some_spec (@exists_config P L _ _),
casesI nonempty_fintype {l : L // q ∈ l},
rw [order, line_count_eq_line_count L p q, line_count_eq_line_count L (classical.some _) q,
line_count, nat.card_eq_fintype_card, nat.sub_add_cancel],
exact fintype.card_pos_iff.mpr ⟨⟨l, h⟩⟩,
end
variables (P) {L}
lemma point_count_eq [finite P] [finite L] (l : L) : point_count P l = order P L + 1 :=
(line_count_eq (dual P) l).trans (congr_arg (λ n, n + 1) (dual.order P L))
variables (P L)
lemma one_lt_order [finite P] [finite L] : 1 < order P L :=
begin
obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, -, -, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := @exists_config P L _ _,
classical,
casesI nonempty_fintype {p : P // p ∈ l₂},
rw [←add_lt_add_iff_right, ←point_count_eq _ l₂, point_count, nat.card_eq_fintype_card],
simp_rw [fintype.two_lt_card_iff, ne, subtype.ext_iff],
have h := mk_point_ax (λ h, h₂₁ ((congr_arg _ h).mpr h₂₂)),
exact ⟨⟨mk_point _, h.2⟩, ⟨p₂, h₂₂⟩, ⟨p₃, h₃₂⟩,
ne_of_mem_of_not_mem h.1 h₂₁, ne_of_mem_of_not_mem h.1 h₃₁, ne_of_mem_of_not_mem h₂₃ h₃₃⟩,
end
variables {P} (L)
lemma two_lt_line_count [finite P] [finite L] (p : P) : 2 < line_count L p :=
by simpa only [line_count_eq L p, nat.succ_lt_succ_iff] using one_lt_order P L
variables (P) {L}
lemma two_lt_point_count [finite P] [finite L] (l : L) : 2 < point_count P l :=
by simpa only [point_count_eq P l, nat.succ_lt_succ_iff] using one_lt_order P L
variables (P) (L)
lemma card_points [fintype P] [finite L] : fintype.card P = order P L ^ 2 + order P L + 1 :=
begin
casesI nonempty_fintype L,
obtain ⟨p, -⟩ := @exists_config P L _ _,
let ϕ : {q // q ≠ p} ≃ Σ (l : {l : L // p ∈ l}), {q // q ∈ l.1 ∧ q ≠ p} :=
{ to_fun := λ q, ⟨⟨mk_line q.2, (mk_line_ax q.2).2⟩, q, (mk_line_ax q.2).1, q.2⟩,
inv_fun := λ lq, ⟨lq.2, lq.2.2.2⟩,
left_inv := λ q, subtype.ext rfl,
right_inv := λ lq, sigma.subtype_ext (subtype.ext ((eq_or_eq (mk_line_ax lq.2.2.2).1
(mk_line_ax lq.2.2.2).2 lq.2.2.1 lq.1.2).resolve_left lq.2.2.2)) rfl },
classical,
have h1 : fintype.card {q // q ≠ p} + 1 = fintype.card P,
{ apply (eq_tsub_iff_add_eq_of_le (nat.succ_le_of_lt (fintype.card_pos_iff.mpr ⟨p⟩))).mp,
convert (fintype.card_subtype_compl _).trans (congr_arg _ (fintype.card_subtype_eq p)) },
have h2 : ∀ l : {l : L // p ∈ l}, fintype.card {q // q ∈ l.1 ∧ q ≠ p} = order P L,
{ intro l,
rw [←fintype.card_congr (equiv.subtype_subtype_equiv_subtype_inter _ _),
fintype.card_subtype_compl (λ (x : subtype (∈ l.val)), x.val = p), ←nat.card_eq_fintype_card],
refine tsub_eq_of_eq_add ((point_count_eq P l.1).trans _),
rw ← fintype.card_subtype_eq (⟨p, l.2⟩ : {q : P // q ∈ l.1}),
simp_rw subtype.ext_iff_val },
simp_rw [←h1, fintype.card_congr ϕ, fintype.card_sigma, h2, finset.sum_const, finset.card_univ],
rw [←nat.card_eq_fintype_card, ←line_count, line_count_eq, smul_eq_mul, nat.succ_mul, sq],
end
lemma card_lines [finite P] [fintype L] :
fintype.card L = order P L ^ 2 + order P L + 1 :=
(card_points (dual L) (dual P)).trans (congr_arg (λ n, n ^ 2 + n + 1) (dual.order P L))
end projective_plane
end configuration
|
290e7a99dcc1e96bba40028bbf162a77d238b5de | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/data/real/ennreal.lean | 8c8ead1997873fe0065c03073e508d9fde34c830 | [
"Apache-2.0"
] | permissive | dexmagic/mathlib | ff48eefc56e2412429b31d4fddd41a976eb287ce | 7a5d15a955a92a90e1d398b2281916b9c41270b2 | refs/heads/master | 1,693,481,322,046 | 1,633,360,193,000 | 1,633,360,193,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 68,565 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Yury Kudryashov
-/
import data.real.nnreal
import data.set.intervals
/-!
# Extended non-negative reals
We define `ennreal = ℝ≥0∞ := with_no ℝ≥0` to be the type of extended nonnegative real numbers,
i.e., the interval `[0, +∞]`. This type is used as the codomain of a `measure_theory.measure`,
and of the extended distance `edist` in a `emetric_space`.
In this file we define some algebraic operations and a linear order on `ℝ≥0∞`
and prove basic properties of these operations, order, and conversions to/from `ℝ`, `ℝ≥0`, and `ℕ`.
## Main definitions
* `ℝ≥0∞`: the extended nonnegative real numbers `[0, ∞]`; defined as `with_top ℝ≥0`; it is
equipped with the following structures:
- coercion from `ℝ≥0` defined in the natural way;
- the natural structure of a complete dense linear order: `↑p ≤ ↑q ↔ p ≤ q` and `∀ a, a ≤ ∞`;
- `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝ≥0)` and `a + ∞ = ∞ + a = ∞`;
- `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝ≥0)`, `0 * ∞ = ∞ * 0 = 0`, and `a *
∞ = ∞ * a = ∞` for `a ≠ 0`;
- `a - b` is defined as the minimal `d` such that `a ≤ d + b`; this way we have
`↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only
subtraction;
- `a⁻¹` is defined as `Inf {b | 1 ≤ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for
`p : ℝ≥0`, `p ≠ 0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`.
- `a / b` is defined as `a * b⁻¹`.
The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn
`ℝ≥0∞` into a canonically ordered commutative semiring of characteristic zero.
* Coercions to/from other types:
- coercion `ℝ≥0 → ℝ≥0∞` is defined as `has_coe`, so one can use `(p : ℝ≥0)` in a context that
expects `a : ℝ≥0∞`, and Lean will apply `coe` automatically;
- `ennreal.to_nnreal` sends `↑p` to `p` and `∞` to `0`;
- `ennreal.to_real := coe ∘ ennreal.to_nnreal` sends `↑p`, `p : ℝ≥0` to `(↑p : ℝ)` and `∞` to `0`;
- `ennreal.of_real := coe ∘ real.to_nnreal` sends `x : ℝ` to `↑⟨max x 0, _⟩`
- `ennreal.ne_top_equiv_nnreal` is an equivalence between `{a : ℝ≥0∞ // a ≠ 0}` and `ℝ≥0`.
## Implementation notes
We define a `can_lift ℝ≥0∞ ℝ≥0` instance, so one of the ways to prove theorems about an `ℝ≥0∞`
number `a` is to consider the cases `a = ∞` and `a ≠ ∞`, and use the tactic `lift a to ℝ≥0 using ha`
in the second case. This instance is even more useful if one already has `ha : a ≠ ∞` in the
context, or if we have `(f : α → ℝ≥0∞) (hf : ∀ x, f x ≠ ∞)`.
## Notations
* `ℝ≥0∞`: the type of the extended nonnegative real numbers;
* `ℝ≥0`: the type of nonnegative real numbers `[0, ∞)`; defined in `data.real.nnreal`;
* `∞`: a localized notation in `ℝ≥0∞` for `⊤ : ℝ≥0∞`.
-/
noncomputable theory
open classical set
open_locale classical big_operators nnreal
variables {α : Type*} {β : Type*}
/-- The extended nonnegative real numbers. This is usually denoted [0, ∞],
and is relevant as the codomain of a measure. -/
@[derive canonically_ordered_comm_semiring, derive complete_linear_order, derive densely_ordered,
derive nontrivial]
def ennreal := with_top ℝ≥0
localized "notation `ℝ≥0∞` := ennreal" in ennreal
localized "notation `∞` := (⊤ : ennreal)" in ennreal
instance : linear_ordered_add_comm_monoid ℝ≥0∞ :=
{ .. ennreal.canonically_ordered_comm_semiring,
.. ennreal.complete_linear_order }
namespace ennreal
variables {a b c d : ℝ≥0∞} {r p q : ℝ≥0}
instance : inhabited ℝ≥0∞ := ⟨0⟩
instance : has_coe ℝ≥0 ℝ≥0∞ := ⟨ option.some ⟩
instance : can_lift ℝ≥0∞ ℝ≥0 :=
{ coe := coe,
cond := λ r, r ≠ ∞,
prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ }
@[simp] lemma none_eq_top : (none : ℝ≥0∞) = ∞ := rfl
@[simp] lemma some_eq_coe (a : ℝ≥0) : (some a : ℝ≥0∞) = (↑a : ℝ≥0∞) := rfl
/-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/
protected def to_nnreal : ℝ≥0∞ → ℝ≥0
| (some r) := r
| none := 0
/-- `to_real x` returns `x` if it is real, `0` otherwise. -/
protected def to_real (a : ℝ≥0∞) : real := coe (a.to_nnreal)
/-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/
protected def of_real (r : real) : ℝ≥0∞ := coe (real.to_nnreal r)
@[simp, norm_cast] lemma to_nnreal_coe : (r : ℝ≥0∞).to_nnreal = r := rfl
@[simp] lemma coe_to_nnreal : ∀{a:ℝ≥0∞}, a ≠ ∞ → ↑(a.to_nnreal) = a
| (some r) h := rfl
| none h := (h rfl).elim
@[simp] lemma of_real_to_real {a : ℝ≥0∞} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a :=
by simp [ennreal.to_real, ennreal.of_real, h]
@[simp] lemma to_real_of_real {r : ℝ} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r :=
by simp [ennreal.to_real, ennreal.of_real, real.coe_to_nnreal _ h]
lemma to_real_of_real' {r : ℝ} : ennreal.to_real (ennreal.of_real r) = max r 0 := rfl
lemma coe_to_nnreal_le_self : ∀{a:ℝ≥0∞}, ↑(a.to_nnreal) ≤ a
| (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _
| none := le_top
lemma coe_nnreal_eq (r : ℝ≥0) : (r : ℝ≥0∞) = ennreal.of_real r :=
by { rw [ennreal.of_real, real.to_nnreal], cases r with r h, congr, dsimp, rw max_eq_left h }
lemma of_real_eq_coe_nnreal {x : ℝ} (h : 0 ≤ x) :
ennreal.of_real x = @coe ℝ≥0 ℝ≥0∞ _ (⟨x, h⟩ : ℝ≥0) :=
by { rw [coe_nnreal_eq], refl }
@[simp] lemma of_real_coe_nnreal : ennreal.of_real p = p := (coe_nnreal_eq p).symm
@[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ≥0) = (0 : ℝ≥0∞) := rfl
@[simp, norm_cast] lemma coe_one : ↑(1 : ℝ≥0) = (1 : ℝ≥0∞) := rfl
@[simp] lemma to_real_nonneg {a : ℝ≥0∞} : 0 ≤ a.to_real := by simp [ennreal.to_real]
@[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl
@[simp] lemma top_to_real : ∞.to_real = 0 := rfl
@[simp] lemma one_to_real : (1 : ℝ≥0∞).to_real = 1 := rfl
@[simp] lemma one_to_nnreal : (1 : ℝ≥0∞).to_nnreal = 1 := rfl
@[simp] lemma coe_to_real (r : ℝ≥0) : (r : ℝ≥0∞).to_real = r := rfl
@[simp] lemma zero_to_nnreal : (0 : ℝ≥0∞).to_nnreal = 0 := rfl
@[simp] lemma zero_to_real : (0 : ℝ≥0∞).to_real = 0 := rfl
@[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 :=
by simp [ennreal.of_real]; refl
@[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ℝ≥0∞) :=
by simp [ennreal.of_real]
lemma of_real_to_real_le {a : ℝ≥0∞} : ennreal.of_real (a.to_real) ≤ a :=
if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha)
lemma forall_ennreal {p : ℝ≥0∞ → Prop} : (∀a, p a) ↔ (∀r:ℝ≥0, p r) ∧ p ∞ :=
⟨assume h, ⟨assume r, h _, h _⟩,
assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩
lemma forall_ne_top {p : ℝ≥0∞ → Prop} : (∀ a ≠ ∞, p a) ↔ ∀ r : ℝ≥0, p r :=
option.ball_ne_none
lemma exists_ne_top {p : ℝ≥0∞ → Prop} : (∃ a ≠ ∞, p a) ↔ ∃ r : ℝ≥0, p r :=
option.bex_ne_none
lemma to_nnreal_eq_zero_iff (x : ℝ≥0∞) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ∞ :=
⟨begin
cases x,
{ simp [none_eq_top] },
{ have A : some (0:ℝ≥0) = (0:ℝ≥0∞) := rfl,
simp [ennreal.to_nnreal, A] {contextual := tt} }
end,
by intro h; cases h; simp [h]⟩
lemma to_real_eq_zero_iff (x : ℝ≥0∞) : x.to_real = 0 ↔ x = 0 ∨ x = ∞ :=
by simp [ennreal.to_real, to_nnreal_eq_zero_iff]
@[simp] lemma coe_ne_top : (r : ℝ≥0∞) ≠ ∞ := with_top.coe_ne_top
@[simp] lemma top_ne_coe : ∞ ≠ (r : ℝ≥0∞) := with_top.top_ne_coe
@[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real]
@[simp] lemma of_real_lt_top {r : ℝ} : ennreal.of_real r < ∞ := lt_top_iff_ne_top.2 of_real_ne_top
@[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real]
@[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top
@[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe
@[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top
@[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe
@[simp, norm_cast] lemma coe_eq_coe : (↑r : ℝ≥0∞) = ↑q ↔ r = q := with_top.coe_eq_coe
@[simp, norm_cast] lemma coe_le_coe : (↑r : ℝ≥0∞) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe
@[simp, norm_cast] lemma coe_lt_coe : (↑r : ℝ≥0∞) < ↑q ↔ r < q := with_top.coe_lt_coe
lemma coe_mono : monotone (coe : ℝ≥0 → ℝ≥0∞) := λ _ _, coe_le_coe.2
@[simp, norm_cast] lemma coe_eq_zero : (↑r : ℝ≥0∞) = 0 ↔ r = 0 := coe_eq_coe
@[simp, norm_cast] lemma zero_eq_coe : 0 = (↑r : ℝ≥0∞) ↔ 0 = r := coe_eq_coe
@[simp, norm_cast] lemma coe_eq_one : (↑r : ℝ≥0∞) = 1 ↔ r = 1 := coe_eq_coe
@[simp, norm_cast] lemma one_eq_coe : 1 = (↑r : ℝ≥0∞) ↔ 1 = r := coe_eq_coe
@[simp, norm_cast] lemma coe_nonneg : 0 ≤ (↑r : ℝ≥0∞) ↔ 0 ≤ r := coe_le_coe
@[simp, norm_cast] lemma coe_pos : 0 < (↑r : ℝ≥0∞) ↔ 0 < r := coe_lt_coe
lemma coe_ne_zero : (r : ℝ≥0∞) ≠ 0 ↔ r ≠ 0 := not_congr coe_eq_coe
@[simp, norm_cast] lemma coe_add : ↑(r + p) = (r + p : ℝ≥0∞) := with_top.coe_add
@[simp, norm_cast] lemma coe_mul : ↑(r * p) = (r * p : ℝ≥0∞) := with_top.coe_mul
@[simp, norm_cast] lemma coe_bit0 : (↑(bit0 r) : ℝ≥0∞) = bit0 r := coe_add
@[simp, norm_cast] lemma coe_bit1 : (↑(bit1 r) : ℝ≥0∞) = bit1 r := by simp [bit1]
lemma coe_two : ((2:ℝ≥0) : ℝ≥0∞) = 2 := by norm_cast
protected lemma zero_lt_one : 0 < (1 : ℝ≥0∞) :=
canonically_ordered_comm_semiring.zero_lt_one
@[simp] lemma one_lt_two : (1 : ℝ≥0∞) < 2 :=
coe_one ▸ coe_two ▸ by exact_mod_cast (@one_lt_two ℕ _ _)
@[simp] lemma zero_lt_two : (0:ℝ≥0∞) < 2 := lt_trans ennreal.zero_lt_one one_lt_two
lemma two_ne_zero : (2:ℝ≥0∞) ≠ 0 := (ne_of_lt zero_lt_two).symm
lemma two_ne_top : (2:ℝ≥0∞) ≠ ∞ := coe_two ▸ coe_ne_top
/-- The set of numbers in `ℝ≥0∞` that are not equal to `∞` is equivalent to `ℝ≥0`. -/
def ne_top_equiv_nnreal : {a | a ≠ ∞} ≃ ℝ≥0 :=
{ to_fun := λ x, ennreal.to_nnreal x,
inv_fun := λ x, ⟨x, coe_ne_top⟩,
left_inv := λ ⟨x, hx⟩, subtype.eq $ coe_to_nnreal hx,
right_inv := λ x, to_nnreal_coe }
lemma cinfi_ne_top [has_Inf α] (f : ℝ≥0∞ → α) : (⨅ x : {x // x ≠ ∞}, f x) = ⨅ x : ℝ≥0, f x :=
eq.symm $ infi_congr _ ne_top_equiv_nnreal.symm.surjective $ λ x, rfl
lemma infi_ne_top [complete_lattice α] (f : ℝ≥0∞ → α) : (⨅ x ≠ ∞, f x) = ⨅ x : ℝ≥0, f x :=
by rw [infi_subtype', cinfi_ne_top]
lemma csupr_ne_top [has_Sup α] (f : ℝ≥0∞ → α) : (⨆ x : {x // x ≠ ∞}, f x) = ⨆ x : ℝ≥0, f x :=
@cinfi_ne_top (order_dual α) _ _
lemma supr_ne_top [complete_lattice α] (f : ℝ≥0∞ → α) : (⨆ x ≠ ∞, f x) = ⨆ x : ℝ≥0, f x :=
@infi_ne_top (order_dual α) _ _
lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ℝ≥0∞ → α} :
(⨅ n, f n) = (⨅ n : ℝ≥0, f n) ⊓ f ∞ :=
le_antisymm
(le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _))
(le_infi $ forall_ennreal.2 ⟨λ r, inf_le_of_left_le $ infi_le _ _, inf_le_right⟩)
lemma supr_ennreal {α : Type*} [complete_lattice α] {f : ℝ≥0∞ → α} :
(⨆ n, f n) = (⨆ n : ℝ≥0, f n) ⊔ f ∞ :=
@infi_ennreal (order_dual α) _ _
@[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top
@[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add
/-- Coercion `ℝ≥0 → ℝ≥0∞` as a `ring_hom`. -/
def of_nnreal_hom : ℝ≥0 →+* ℝ≥0∞ :=
⟨coe, coe_one, λ _ _, coe_mul, coe_zero, λ _ _, coe_add⟩
@[simp] lemma coe_of_nnreal_hom : ⇑of_nnreal_hom = coe := rfl
section actions
/-- A `mul_action` over `ℝ≥0∞` restricts to a `mul_action` over `ℝ≥0`. -/
instance {M : Type*} [mul_action ℝ≥0∞ M] : mul_action ℝ≥0 M :=
mul_action.comp_hom M of_nnreal_hom.to_monoid_hom
lemma smul_def {M : Type*} [mul_action ℝ≥0∞ M] (c : ℝ≥0) (x : M) :
c • x = (c : ℝ≥0∞) • x := rfl
instance {M N : Type*} [mul_action ℝ≥0∞ M] [mul_action ℝ≥0∞ N] [has_scalar M N]
[is_scalar_tower ℝ≥0∞ M N] : is_scalar_tower ℝ≥0 M N :=
{ smul_assoc := λ r, (smul_assoc (r : ℝ≥0∞) : _)}
instance smul_comm_class_left {M N : Type*} [mul_action ℝ≥0∞ N] [has_scalar M N]
[smul_comm_class ℝ≥0∞ M N] : smul_comm_class ℝ≥0 M N :=
{ smul_comm := λ r, (smul_comm (r : ℝ≥0∞) : _)}
instance smul_comm_class_right {M N : Type*} [mul_action ℝ≥0∞ N] [has_scalar M N]
[smul_comm_class M ℝ≥0∞ N] : smul_comm_class M ℝ≥0 N :=
{ smul_comm := λ m r, (smul_comm m (r : ℝ≥0∞) : _)}
/-- A `distrib_mul_action` over `ℝ≥0∞` restricts to a `distrib_mul_action` over `ℝ≥0`. -/
instance {M : Type*} [add_monoid M] [distrib_mul_action ℝ≥0∞ M] : distrib_mul_action ℝ≥0 M :=
distrib_mul_action.comp_hom M of_nnreal_hom.to_monoid_hom
/-- A `module` over `ℝ≥0∞` restricts to a `module` over `ℝ≥0`. -/
instance {M : Type*} [add_comm_monoid M] [module ℝ≥0∞ M] : module ℝ≥0 M :=
module.comp_hom M of_nnreal_hom
/-- An `algebra` over `ℝ≥0∞` restricts to an `algebra` over `ℝ≥0`. -/
instance {A : Type*} [semiring A] [algebra ℝ≥0∞ A] : algebra ℝ≥0 A :=
{ smul := (•),
commutes' := λ r x, by simp [algebra.commutes],
smul_def' := λ r x, by simp [←algebra.smul_def (r : ℝ≥0∞) x, smul_def],
to_ring_hom := ((algebra_map ℝ≥0∞ A).comp (of_nnreal_hom : ℝ≥0 →+* ℝ≥0∞)) }
-- verify that the above produces instances we might care about
example : algebra ℝ≥0 ℝ≥0∞ := by apply_instance
example : distrib_mul_action (units ℝ≥0) ℝ≥0∞ := by apply_instance
lemma coe_smul {R} [monoid R] (r : R) (s : ℝ≥0) [mul_action R ℝ≥0] [has_scalar R ℝ≥0∞]
[is_scalar_tower R ℝ≥0 ℝ≥0] [is_scalar_tower R ℝ≥0 ℝ≥0∞] :
(↑(r • s) : ℝ≥0∞) = r • ↑s :=
begin
rw ←smul_one_smul ℝ≥0 r (s: ℝ≥0∞),
change ↑(r • s) = ↑(r • (1 : ℝ≥0)) * ↑s,
rw [←ennreal.coe_mul, smul_mul_assoc, one_mul],
end
end actions
@[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) :
((s.indicator f a : ℝ≥0) : ℝ≥0∞) = s.indicator (λ x, f x) a :=
(of_nnreal_hom : ℝ≥0 →+ ℝ≥0∞).map_indicator _ _ _
@[simp, norm_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ℝ≥0∞) = r^n :=
of_nnreal_hom.map_pow r n
@[simp] lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top
@[simp] lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top
lemma to_nnreal_add {r₁ r₂ : ℝ≥0∞} (h₁ : r₁ ≠ ∞) (h₂ : r₂ ≠ ∞) :
(r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal :=
by { lift r₁ to ℝ≥0 using h₁, lift r₂ to ℝ≥0 using h₂, refl }
lemma not_lt_top {x : ℝ≥0∞} : ¬ x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, not_not]
lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ :=
by simpa only [lt_top_iff_ne_top] using add_lt_top
lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) :=
begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end
lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) :=
begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end
@[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top
lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ :=
nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top])
_ (nat.succ_le_of_lt h)
lemma mul_eq_top : a * b = ∞ ↔ (a ≠ 0 ∧ b = ∞) ∨ (a = ∞ ∧ b ≠ 0) :=
with_top.mul_eq_top_iff
lemma mul_lt_top : a ≠ ∞ → b ≠ ∞ → a * b < ∞ :=
with_top.mul_lt_top
lemma mul_ne_top : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ :=
by simpa only [lt_top_iff_ne_top] using mul_lt_top
lemma lt_top_of_mul_ne_top_left (h : a * b ≠ ∞) (hb : b ≠ 0) : a < ∞ :=
lt_top_iff_ne_top.2 $ λ ha, h $ mul_eq_top.2 (or.inr ⟨ha, hb⟩)
lemma lt_top_of_mul_ne_top_right (h : a * b ≠ ∞) (ha : a ≠ 0) : b < ∞ :=
lt_top_of_mul_ne_top_left (by rwa [mul_comm]) ha
lemma mul_lt_top_iff {a b : ℝ≥0∞} : a * b < ∞ ↔ (a < ∞ ∧ b < ∞) ∨ a = 0 ∨ b = 0 :=
begin
split,
{ intro h, rw [← or_assoc, or_iff_not_imp_right, or_iff_not_imp_right], intros hb ha,
exact ⟨lt_top_of_mul_ne_top_left h.ne hb, lt_top_of_mul_ne_top_right h.ne ha⟩ },
{ rintro (⟨ha, hb⟩|rfl|rfl); [exact mul_lt_top ha.ne hb.ne, simp, simp] }
end
lemma mul_self_lt_top_iff {a : ℝ≥0∞} : a * a < ⊤ ↔ a < ⊤ :=
by { rw [ennreal.mul_lt_top_iff, and_self, or_self, or_iff_left_iff_imp], rintro rfl, norm_num }
lemma mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b := canonically_ordered_comm_semiring.mul_pos
lemma mul_pos (ha : a ≠ 0) (hb : b ≠ 0) : 0 < a * b :=
mul_pos_iff.2 ⟨pos_iff_ne_zero.2 ha, pos_iff_ne_zero.2 hb⟩
@[simp] lemma pow_eq_top_iff {n : ℕ} : a ^ n = ∞ ↔ a = ∞ ∧ n ≠ 0 :=
begin
induction n with n ihn, { simp },
rw [pow_succ, mul_eq_top, ihn],
fsplit,
{ rintro (⟨-,rfl,h0⟩|⟨rfl,h0⟩); exact ⟨rfl, n.succ_ne_zero⟩ },
{ rintro ⟨rfl, -⟩, exact or.inr ⟨rfl, pow_ne_zero n top_ne_zero⟩ }
end
lemma pow_eq_top (n : ℕ) (h : a ^ n = ∞) : a = ∞ :=
(pow_eq_top_iff.1 h).1
lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ :=
mt (pow_eq_top n) h
lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ :=
by simpa only [lt_top_iff_ne_top] using pow_ne_top
@[simp, norm_cast] lemma coe_finset_sum {s : finset α} {f : α → ℝ≥0} :
↑(∑ a in s, f a) = (∑ a in s, f a : ℝ≥0∞) :=
of_nnreal_hom.map_sum f s
@[simp, norm_cast] lemma coe_finset_prod {s : finset α} {f : α → ℝ≥0} :
↑(∏ a in s, f a) = ((∏ a in s, f a) : ℝ≥0∞) :=
of_nnreal_hom.map_prod f s
section order
@[simp] lemma bot_eq_zero : (⊥ : ℝ≥0∞) = 0 := rfl
@[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r
@[simp] lemma not_top_le_coe : ¬ ∞ ≤ ↑r := with_top.not_top_le_coe r
@[simp, norm_cast] lemma one_le_coe_iff : (1:ℝ≥0∞) ≤ ↑r ↔ 1 ≤ r := coe_le_coe
@[simp, norm_cast] lemma coe_le_one_iff : ↑r ≤ (1:ℝ≥0∞) ↔ r ≤ 1 := coe_le_coe
@[simp, norm_cast] lemma coe_lt_one_iff : (↑p : ℝ≥0∞) < 1 ↔ p < 1 := coe_lt_coe
@[simp, norm_cast] lemma one_lt_coe_iff : 1 < (↑p : ℝ≥0∞) ↔ 1 < p := coe_lt_coe
@[simp, norm_cast] lemma coe_nat (n : ℕ) : ((n : ℝ≥0) : ℝ≥0∞) = n := with_top.coe_nat n
@[simp] lemma of_real_coe_nat (n : ℕ) : ennreal.of_real n = n := by simp [ennreal.of_real]
@[simp] lemma nat_ne_top (n : ℕ) : (n : ℝ≥0∞) ≠ ∞ := with_top.nat_ne_top n
@[simp] lemma top_ne_nat (n : ℕ) : ∞ ≠ n := with_top.top_ne_nat n
@[simp] lemma one_lt_top : 1 < ∞ := coe_lt_top
@[simp, norm_cast] lemma to_nnreal_nat (n : ℕ) : (n : ℝ≥0∞).to_nnreal = n :=
by conv_lhs { rw [← ennreal.coe_nat n, ennreal.to_nnreal_coe] }
@[simp, norm_cast] lemma to_real_nat (n : ℕ) : (n : ℝ≥0∞).to_real = n :=
by conv_lhs { rw [← ennreal.of_real_coe_nat n, ennreal.to_real_of_real (nat.cast_nonneg _)] }
lemma le_coe_iff : a ≤ ↑r ↔ (∃p:ℝ≥0, a = p ∧ p ≤ r) := with_top.le_coe_iff
lemma coe_le_iff : ↑r ≤ a ↔ (∀p:ℝ≥0, a = p → r ≤ p) := with_top.coe_le_iff
lemma lt_iff_exists_coe : a < b ↔ (∃p:ℝ≥0, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe
lemma to_real_le_coe_of_le_coe {a : ℝ≥0∞} {b : ℝ≥0} (h : a ≤ b) : a.to_real ≤ b :=
show ↑a.to_nnreal ≤ ↑b,
begin
have : ↑a.to_nnreal = a := ennreal.coe_to_nnreal (lt_of_le_of_lt h coe_lt_top).ne,
rw ← this at h,
exact_mod_cast h
end
@[simp, norm_cast] lemma coe_finset_sup {s : finset α} {f : α → ℝ≥0} :
↑(s.sup f) = s.sup (λ x, (f x : ℝ≥0∞)) :=
finset.comp_sup_eq_sup_comp_of_is_total _ coe_mono rfl
lemma pow_le_pow {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m :=
begin
cases a,
{ cases m,
{ rw eq_bot_iff.mpr h,
exact le_refl _ },
{ rw [none_eq_top, top_pow (nat.succ_pos m)],
exact le_top } },
{ rw [some_eq_coe, ← coe_pow, ← coe_pow, coe_le_coe],
exact pow_le_pow (by simpa using ha) h }
end
@[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 :=
by simp only [nonpos_iff_eq_zero.symm, max_le_iff]
@[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a)
@[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a)
-- TODO: why this is not a `rfl`? There is some hidden diamond here.
@[simp] lemma sup_eq_max : a ⊔ b = max a b :=
eq_of_forall_ge_iff $ λ c, sup_le_iff.trans max_le_iff.symm
protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n :=
canonically_ordered_comm_semiring.pow_pos
protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 :=
by simpa only [pos_iff_ne_zero] using ennreal.pow_pos
@[simp] lemma not_lt_zero : ¬ a < 0 := by simp
lemma add_lt_add_iff_left (ha : a ≠ ∞) : a + c < a + b ↔ c < b :=
with_top.add_lt_add_iff_left ha
lemma add_lt_add_left (ha : a ≠ ∞) (h : b < c) : a + b < a + c :=
(add_lt_add_iff_left ha).2 h
lemma add_lt_add_iff_right (ha : a ≠ ∞) : c + a < b + a ↔ c < b :=
with_top.add_lt_add_iff_right ha
lemma add_lt_add_right (ha : a ≠ ∞) (h : b < c) : b + a < c + a :=
(add_lt_add_iff_right ha).2 h
instance contravariant_class_add_lt : contravariant_class ℝ≥0∞ ℝ≥0∞ (+) (<) :=
with_top.contravariant_class_add_lt
lemma lt_add_right (ha : a ≠ ∞) (hb : b ≠ 0) : a < a + b :=
by rwa [← pos_iff_ne_zero, ← add_lt_add_iff_left ha, add_zero] at hb
lemma le_of_forall_pos_le_add : ∀{a b : ℝ≥0∞}, (∀ε : ℝ≥0, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b
| a none h := le_top
| none (some a) h :=
have ∞ ≤ ↑a + ↑(1:ℝ≥0), from h 1 zero_lt_one coe_lt_top,
by rw [← coe_add] at this; exact (not_top_le_coe this).elim
| (some a) (some b) h :=
by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff]
at *; exact nnreal.le_of_forall_pos_le_add h
lemma lt_iff_exists_rat_btwn :
a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < real.to_nnreal q ∧ (real.to_nnreal q:ℝ≥0∞) < b) :=
⟨λ h,
begin
rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩,
rcases exists_between h with ⟨c, pc, cb⟩,
rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩,
rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩,
exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩
end,
λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩
lemma lt_iff_exists_real_btwn :
a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ℝ≥0∞) < b) :=
⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in
⟨q, rat.cast_nonneg.2 q0, aq, qb⟩,
λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩
lemma lt_iff_exists_nnreal_btwn :
a < b ↔ (∃r:ℝ≥0, a < r ∧ (r : ℝ≥0∞) < b) :=
with_top.lt_iff_exists_coe_btwn
lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : ℝ≥0, 0 < r ∧ a + r < b) :=
begin
refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_self_add) hr⟩,
cases a, { simpa using hab },
rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩,
let d : ℝ≥0 := ⟨c, c_nonneg⟩,
have ad : a < d,
{ rw of_real_eq_coe_nnreal c_nonneg at ac,
exact coe_lt_coe.1 ac },
refine ⟨d-a, sub_pos_iff_lt.2 ad, _⟩,
rw [some_eq_coe, ← coe_add],
convert cb,
have : real.to_nnreal c = d,
by { rw [← nnreal.coe_eq, real.coe_to_nnreal _ c_nonneg], refl },
rw [add_comm, this],
exact sub_add_cancel_of_le ad.le
end
lemma coe_nat_lt_coe {n : ℕ} : (n : ℝ≥0∞) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe
lemma coe_lt_coe_nat {n : ℕ} : (r : ℝ≥0∞) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe
@[simp, norm_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ℝ≥0∞) < n ↔ m < n :=
ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt
lemma coe_nat_ne_top {n : ℕ} : (n : ℝ≥0∞) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top
lemma coe_nat_mono : strict_mono (coe : ℕ → ℝ≥0∞) := λ _ _, coe_nat_lt_coe_nat.2
@[simp, norm_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ℝ≥0∞) ≤ n ↔ m ≤ n :=
coe_nat_mono.le_iff_le
instance : char_zero ℝ≥0∞ := ⟨coe_nat_mono.injective⟩
protected lemma exists_nat_gt {r : ℝ≥0∞} (h : r ≠ ∞) : ∃n:ℕ, r < n :=
begin
lift r to ℝ≥0 using h,
rcases exists_nat_gt r with ⟨n, hn⟩,
exact ⟨n, coe_lt_coe_nat.2 hn⟩,
end
lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d :=
begin
lift a to ℝ≥0 using ne_top_of_lt ac,
lift b to ℝ≥0 using ne_top_of_lt bd,
cases c, { simp }, cases d, { simp },
simp only [← coe_add, some_eq_coe, coe_lt_coe] at *,
exact add_lt_add ac bd
end
@[norm_cast] lemma coe_min : ((min r p:ℝ≥0):ℝ≥0∞) = min r p :=
coe_mono.map_min
@[norm_cast] lemma coe_max : ((max r p:ℝ≥0):ℝ≥0∞) = max r p :=
coe_mono.map_max
lemma le_of_top_imp_top_of_to_nnreal_le {a b : ℝ≥0∞} (h : a = ⊤ → b = ⊤)
(h_nnreal : a ≠ ⊤ → b ≠ ⊤ → a.to_nnreal ≤ b.to_nnreal) :
a ≤ b :=
begin
by_cases ha : a = ⊤,
{ rw h ha,
exact le_top, },
by_cases hb : b = ⊤,
{ rw hb,
exact le_top, },
rw [←coe_to_nnreal hb, ←coe_to_nnreal ha, coe_le_coe],
exact h_nnreal ha hb,
end
end order
section complete_lattice
lemma coe_Sup {s : set ℝ≥0} : bdd_above s → (↑(Sup s) : ℝ≥0∞) = (⨆a∈s, ↑a) := with_top.coe_Sup
lemma coe_Inf {s : set ℝ≥0} : s.nonempty → (↑(Inf s) : ℝ≥0∞) = (⨅a∈s, ↑a) := with_top.coe_Inf
@[simp] lemma top_mem_upper_bounds {s : set ℝ≥0∞} : ∞ ∈ upper_bounds s :=
assume x hx, le_top
lemma coe_mem_upper_bounds {s : set ℝ≥0} :
↑r ∈ upper_bounds ((coe : ℝ≥0 → ℝ≥0∞) '' s) ↔ r ∈ upper_bounds s :=
by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt}
end complete_lattice
section mul
@[mono] lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d :=
mul_le_mul'
@[mono] lemma mul_lt_mul (ac : a < c) (bd : b < d) : a * b < c * d :=
begin
rcases lt_iff_exists_nnreal_btwn.1 ac with ⟨a', aa', a'c⟩,
lift a to ℝ≥0 using ne_top_of_lt aa',
rcases lt_iff_exists_nnreal_btwn.1 bd with ⟨b', bb', b'd⟩,
lift b to ℝ≥0 using ne_top_of_lt bb',
norm_cast at *,
calc ↑(a * b) < ↑(a' * b') :
coe_lt_coe.2 (mul_lt_mul' aa'.le bb' (zero_le _) ((zero_le a).trans_lt aa'))
... = ↑a' * ↑b' : coe_mul
... ≤ c * d : mul_le_mul a'c.le b'd.le
end
lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul (le_refl a)
lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h (le_refl a)
lemma pow_strict_mono {n : ℕ} (hn : n ≠ 0) : strict_mono (λ (x : ℝ≥0∞), x^n) :=
begin
assume x y hxy,
obtain ⟨n, rfl⟩ := nat.exists_eq_succ_of_ne_zero hn,
induction n with n IH,
{ simp only [hxy, pow_one] },
{ simp only [pow_succ _ n.succ, mul_lt_mul hxy (IH (nat.succ_pos _).ne')] }
end
lemma max_mul : max a b * c = max (a * c) (b * c) :=
mul_right_mono.map_max
lemma mul_max : a * max b c = max (a * b) (a * c) :=
mul_left_mono.map_max
lemma mul_eq_mul_left : a ≠ 0 → a ≠ ∞ → (a * b = a * c ↔ b = c) :=
begin
cases a; cases b; cases c;
simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm,
nnreal.mul_eq_mul_left] {contextual := tt},
end
lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) :=
mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left
lemma mul_le_mul_left : a ≠ 0 → a ≠ ∞ → (a * b ≤ a * c ↔ b ≤ c) :=
begin
cases a; cases b; cases c;
simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt},
assume h, exact mul_le_mul_left (pos_iff_ne_zero.2 h)
end
lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) :=
mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left
lemma mul_lt_mul_left : a ≠ 0 → a ≠ ∞ → (a * b < a * c ↔ b < c) :=
λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le]
lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) :=
mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left
end mul
section sub
instance : has_sub ℝ≥0∞ := ⟨λa b, Inf {d | a ≤ d + b}⟩
@[norm_cast] lemma coe_sub : ↑(p - r) = (↑p:ℝ≥0∞) - r :=
le_antisymm
(le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $
by rintros d rfl; rwa [← coe_add, coe_le_coe, ← sub_le_iff_right] at hb)
(Inf_le $ show (↑p : ℝ≥0∞) ≤ ↑(p - r) + ↑r,
by rw [← coe_add, coe_le_coe, ← sub_le_iff_right])
@[simp] lemma top_sub_coe : ∞ - ↑r = ∞ :=
top_unique $ le_Inf $ by simp [add_eq_top]
@[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 :=
le_antisymm (Inf_le $ le_add_left h) (zero_le _)
@[simp] lemma sub_self : a - a = 0 := sub_eq_zero_of_le $ le_refl _
@[simp] lemma zero_sub : 0 - a = 0 :=
le_antisymm (Inf_le $ zero_le $ 0 + a) (zero_le _)
@[simp] lemma sub_top : a - ∞ = 0 :=
le_antisymm (Inf_le $ by simp) (zero_le _)
lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d :=
Inf_le_Inf $ assume e (h : b ≤ e + d),
calc a ≤ b : h₁
... ≤ e + d : h
... ≤ e + c : add_le_add (le_refl _) h₂
@[simp] lemma add_sub_self : ∀{a b : ℝ≥0∞}, b ≠ ∞ → (a + b) - b = a
| a none := by simp [none_eq_top]
| none (some b) := by simp [none_eq_top, some_eq_coe]
| (some a) (some b) :=
by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, add_sub_cancel_right]
@[simp] lemma add_sub_self' (h : a ≠ ∞) : (a + b) - a = b :=
by rw [add_comm, add_sub_self h]
lemma add_right_inj (h : a ≠ ∞) : a + b = a + c ↔ b = c :=
⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩
lemma add_left_inj (h : a ≠ ∞) : b + a = c + a ↔ b = c :=
by rw [add_comm, add_comm c, add_right_inj h]
@[simp] lemma sub_add_cancel_of_le : ∀{a b : ℝ≥0∞}, b ≤ a → (a - b) + b = a :=
begin
simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt},
rintros r p x rfl h,
rw [← coe_sub, ← coe_add, sub_add_cancel_of_le h]
end
@[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a :=
by rwa [add_comm, sub_add_cancel_of_le]
lemma sub_add_self_eq_max : (a - b) + b = max a b :=
match le_total a b with
| or.inl h := by simp [h, max_eq_right]
| or.inr h := by simp [h, max_eq_left]
end
lemma le_sub_add_self : a ≤ (a - b) + b :=
by { rw sub_add_self_eq_max, exact le_max_left a b }
@[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b :=
iff.intro
(assume h : a - b ≤ c,
calc a ≤ (a - b) + b : le_sub_add_self
... ≤ c + b : add_le_add_right h _)
(assume h : a ≤ c + b, Inf_le h)
protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c :=
add_comm c b ▸ ennreal.sub_le_iff_le_add
lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a :=
λ hb hc, hc ▸ add_sub_self hb
protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b :=
ennreal.sub_le_iff_le_add.2 $ ennreal.sub_le_iff_le_add'.1 h
protected lemma lt_add_of_sub_lt (ht : a ≠ ∞ ∨ b ≠ ∞) (h : a - b < c) : a < c + b :=
begin
rcases eq_or_ne b ∞ with rfl|hb,
{ rw [add_top, lt_top_iff_ne_top], exact ht.resolve_right (not_not.2 rfl) },
{ calc a ≤ (a - b) + b : le_sub_add_self
... < c + b : (add_lt_add_iff_right hb).2 h }
end
protected lemma sub_lt_of_lt_add (hac : c ≤ a) (h : a < b + c) : a - c < b :=
begin
lift c to ℝ≥0 using (ne_top_of_lt $ hac.trans_lt h),
lift a to ℝ≥0 using (ne_top_of_lt h),
rw coe_le_coe at hac,
rw [← coe_sub],
cases b, { exact coe_lt_top },
rwa [some_eq_coe, coe_lt_coe, sub_lt_iff_right hac, ← coe_lt_coe, coe_add]
end
protected lemma sub_lt_iff_lt_add (hb : b ≠ ∞) (hab : b ≤ a) : a - b < c ↔ a < c + b :=
⟨ennreal.lt_add_of_sub_lt (or.inr hb), ennreal.sub_lt_of_lt_add hab⟩
protected lemma sub_lt_self (hat : a ≠ ∞) (h0 : a ≠ 0) (hb : b ≠ 0) : a - b < a :=
(le_total b a).elim (λ hba, ennreal.sub_lt_of_lt_add hba (lt_add_right hat hb))
(λ hab, by rwa [sub_eq_zero_of_le hab, pos_iff_ne_zero])
@[simp] protected lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b :=
by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0
@[simp] protected lemma sub_pos : 0 < a - b ↔ b < a :=
by simp [pos_iff_ne_zero]
lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b :=
begin
cases a, { simp },
cases c, { simp },
cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] },
simp only [some_eq_coe],
rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, lt_sub_iff_right],
end
lemma lt_sub_comm : a < b - c ↔ c < b - a :=
by rw [lt_sub_iff_add_lt, lt_sub_iff_add_lt, add_comm]
lemma sub_le_self (a b : ℝ≥0∞) : a - b ≤ a :=
ennreal.sub_le_iff_le_add.2 $ le_self_add
@[simp] lemma sub_zero : a - 0 = a :=
eq.trans (add_zero (a - 0)).symm $ by simp
lemma sub_lt_of_sub_lt (h₂ : c ≤ a) (h₃ : a ≠ ∞ ∨ b ≠ ∞) (h₁ : a - b < c) : a - c < b :=
ennreal.sub_lt_of_lt_add h₂ (add_comm c b ▸ ennreal.lt_add_of_sub_lt h₃ h₁)
/-- A version of triangle inequality for difference as a "distance". -/
lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) :=
ennreal.sub_le_iff_le_add.2 $
calc a ≤ a - b + b : le_sub_add_self
... ≤ a - b + ((b - c) + c) : add_le_add_left le_sub_add_self _
... = a - b + (b - c) + c : (add_assoc _ _ _).symm
lemma sub_sub_cancel (h : a ≠ ∞) (h2 : b ≤ a) : a - (a - b) = b :=
by rw [← add_left_inj (ne_top_of_le_ne_top h (sub_le_self _ _)),
sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2]
lemma sub_right_inj {a b c : ℝ≥0∞} (ha : a ≠ ∞) (hb : b ≤ a) (hc : c ≤ a) :
a - b = a - c ↔ b = c :=
iff.intro
begin
assume h, have : a - (a - b) = a - (a - c), rw h,
rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this
end
(λ h, by rw h)
lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c :=
begin
cases le_or_lt a b with hab hab,
{ simp [hab, mul_right_mono hab] },
symmetry,
cases eq_or_lt_of_le (zero_le b) with hb hb,
{ subst b, simp },
apply sub_eq_of_add_eq,
{ exact mul_ne_top (ne_top_of_lt hab) (h hb hab) },
rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)]
end
lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) :
a * (b - c) = a * b - a * c :=
by { simp only [mul_comm a], exact sub_mul h }
lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c :=
begin
-- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a`
by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞,
{ rw [sub_mul h],
exact le_refl _ },
{ push_neg at h,
rcases h with ⟨hb, hba, hc⟩,
subst c,
simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self,
zero_le] }
end
end sub
section sum
open finset
/-- A product of finite numbers is still finite -/
lemma prod_lt_top {s : finset α} {f : α → ℝ≥0∞} (h : ∀ a ∈ s, f a ≠ ∞) : (∏ a in s, f a) < ∞ :=
with_top.prod_lt_top h
/-- A sum of finite numbers is still finite -/
lemma sum_lt_top {s : finset α} {f : α → ℝ≥0∞} (h : ∀ a ∈ s, f a ≠ ∞) : ∑ a in s, f a < ∞ :=
with_top.sum_lt_top h
/-- A sum of finite numbers is still finite -/
lemma sum_lt_top_iff {s : finset α} {f : α → ℝ≥0∞} :
∑ a in s, f a < ∞ ↔ (∀ a ∈ s, f a < ∞) :=
with_top.sum_lt_top_iff
/-- A sum of numbers is infinite iff one of them is infinite -/
lemma sum_eq_top_iff {s : finset α} {f : α → ℝ≥0∞} :
(∑ x in s, f x) = ∞ ↔ (∃ a ∈ s, f a = ∞) :=
with_top.sum_eq_top_iff
lemma lt_top_of_sum_ne_top {s : finset α} {f : α → ℝ≥0∞} (h : (∑ x in s, f x) ≠ ∞) {a : α}
(ha : a ∈ s) : f a < ∞ :=
sum_lt_top_iff.1 h.lt_top a ha
/-- seeing `ℝ≥0∞` as `ℝ≥0` does not change their sum, unless one of the `ℝ≥0∞` is
infinity -/
lemma to_nnreal_sum {s : finset α} {f : α → ℝ≥0∞} (hf : ∀a∈s, f a ≠ ∞) :
ennreal.to_nnreal (∑ a in s, f a) = ∑ a in s, ennreal.to_nnreal (f a) :=
begin
rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr rfl],
{ intros x hx, exact (coe_to_nnreal (hf x hx)).symm },
{ exact (sum_lt_top hf).ne }
end
/-- seeing `ℝ≥0∞` as `real` does not change their sum, unless one of the `ℝ≥0∞` is infinity -/
lemma to_real_sum {s : finset α} {f : α → ℝ≥0∞} (hf : ∀ a ∈ s, f a ≠ ∞) :
ennreal.to_real (∑ a in s, f a) = ∑ a in s, ennreal.to_real (f a) :=
by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl }
lemma of_real_sum_of_nonneg {s : finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) :
ennreal.of_real (∑ i in s, f i) = ∑ i in s, ennreal.of_real (f i) :=
begin
simp_rw [ennreal.of_real, ←coe_finset_sum, coe_eq_coe],
exact real.to_nnreal_sum_of_nonneg hf,
end
end sum
section interval
variables {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : set ℝ≥0∞}
protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := Ico_bot
lemma mem_Iio_self_add : x ≠ ∞ → ε ≠ 0 → x ∈ Iio (x + ε) :=
assume xt ε0, lt_add_right xt ε0
lemma mem_Ioo_self_sub_add : x ≠ ∞ → x ≠ 0 → ε₁ ≠ 0 → ε₂ ≠ 0 → x ∈ Ioo (x - ε₁) (x + ε₂) :=
assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_self xt x0 ε0, lt_add_right xt ε0'⟩
end interval
section bit
@[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b :=
⟨λh, begin
rcases (lt_trichotomy a b) with h₁| h₂| h₃,
{ exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) },
{ exact h₂ },
{ exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) }
end,
λh, congr_arg _ h⟩
@[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 :=
by simpa only [bit0_zero] using @bit0_inj a 0
@[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ :=
by rw [bit0, add_eq_top, or_self]
@[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b :=
⟨λh, begin
unfold bit1 at h,
rwa [add_left_inj, bit0_inj] at h,
simp [lt_top_iff_ne_top]
end,
λh, congr_arg _ h⟩
@[simp] lemma bit1_ne_zero : bit1 a ≠ 0 :=
by unfold bit1; simp
@[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 :=
by simpa only [bit1_zero] using @bit1_inj a 0
@[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ :=
by unfold bit1; rw add_eq_top; simp
end bit
section inv
instance : has_inv ℝ≥0∞ := ⟨λa, Inf {b | 1 ≤ a * b}⟩
instance : div_inv_monoid ℝ≥0∞ :=
{ inv := has_inv.inv,
.. (infer_instance : monoid ℝ≥0∞) }
@[simp] lemma inv_zero : (0 : ℝ≥0∞)⁻¹ = ∞ :=
show Inf {b : ℝ≥0∞ | 1 ≤ 0 * b} = ∞, by simp; refl
@[simp] lemma inv_top : ∞⁻¹ = 0 :=
bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul]
@[simp, norm_cast] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ℝ≥0∞) = (↑r)⁻¹ :=
le_antisymm
(le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $
by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb)
(Inf_le $ by simp; rw [← coe_mul, mul_inv_cancel hr]; exact le_refl 1)
lemma coe_inv_le : (↑r⁻¹ : ℝ≥0∞) ≤ (↑r)⁻¹ :=
if hr : r = 0 then by simp only [hr, inv_zero, coe_zero, le_top]
else by simp only [coe_inv hr, le_refl]
@[norm_cast] lemma coe_inv_two : ((2⁻¹:ℝ≥0):ℝ≥0∞) = 2⁻¹ :=
by rw [coe_inv (ne_of_gt _root_.zero_lt_two), coe_two]
@[simp, norm_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ℝ≥0∞) = p / r :=
by rw [div_eq_mul_inv, div_eq_mul_inv, coe_mul, coe_inv hr]
lemma div_zero (h : a ≠ 0) : a / 0 = ∞ := by simp [div_eq_mul_inv, h]
@[simp] lemma inv_one : (1:ℝ≥0∞)⁻¹ = 1 :=
by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 inv_one
@[simp] lemma div_one {a : ℝ≥0∞} : a / 1 = a :=
by rw [div_eq_mul_inv, inv_one, mul_one]
protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n :=
begin
by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe,
zero_pow, top_pow, nat.zero_lt_succ] at *,
rw [← coe_inv h, ← coe_pow, ← coe_inv (pow_ne_zero _ h), ← inv_pow₀, coe_pow]
end
@[simp] lemma inv_inv : (a⁻¹)⁻¹ = a :=
by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe,
-coe_inv, (coe_inv _).symm] at *
lemma inv_involutive : function.involutive (λ a:ℝ≥0∞, a⁻¹) :=
λ a, ennreal.inv_inv
lemma inv_bijective : function.bijective (λ a:ℝ≥0∞, a⁻¹) :=
ennreal.inv_involutive.bijective
@[simp] lemma inv_eq_inv : a⁻¹ = b⁻¹ ↔ a = b := inv_bijective.1.eq_iff
@[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 :=
inv_zero ▸ inv_eq_inv
lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp
@[simp] lemma inv_lt_top {x : ℝ≥0∞} : x⁻¹ < ∞ ↔ 0 < x :=
by { simp only [lt_top_iff_ne_top, inv_ne_top, pos_iff_ne_zero] }
lemma div_lt_top {x y : ℝ≥0∞} (h1 : x ≠ ∞) (h2 : y ≠ 0) : x / y < ∞ :=
mul_lt_top h1 (inv_ne_top.mpr h2)
@[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ :=
inv_top ▸ inv_eq_inv
lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp
@[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ :=
pos_iff_ne_zero.trans inv_ne_zero
@[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a :=
begin
cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top],
{ simp only [lt_irrefl] },
{ exact inv_pos.trans lt_top_iff_ne_top.symm },
{ simp only [not_lt_zero, not_top_lt] },
{ cases eq_or_lt_of_le (zero_le a) with ha ha;
cases eq_or_lt_of_le (zero_le b) with hb hb,
{ subst a, subst b, simp },
{ subst a, simp },
{ subst b, simp [pos_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] },
{ rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe],
simp only [nnreal.coe_lt_coe.symm] at *,
exact inv_lt_inv ha hb } }
end
lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a :=
by simpa only [inv_inv] using @inv_lt_inv a b⁻¹
lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ :=
by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b
@[simp, priority 1100] -- higher than le_inv_iff_mul_le
lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a :=
by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_eq_inv, eq_comm]
lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a :=
by simpa only [inv_inv] using @inv_le_inv a b⁻¹
lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ :=
by simpa only [inv_inv] using @inv_le_inv a⁻¹ b
@[simp] lemma inv_le_one : a⁻¹ ≤ 1 ↔ 1 ≤ a :=
inv_le_iff_inv_le.trans $ by rw inv_one
lemma one_le_inv : 1 ≤ a⁻¹ ↔ a ≤ 1 :=
le_inv_iff_le_inv.trans $ by rw inv_one
@[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a :=
inv_lt_iff_inv_lt.trans $ by rw [inv_one]
lemma pow_le_pow_of_le_one {n m : ℕ} (ha : a ≤ 1) (h : n ≤ m) : a ^ m ≤ a ^ n :=
begin
rw [← @inv_inv a, ← ennreal.inv_pow, ← @ennreal.inv_pow a⁻¹, inv_le_inv],
exact pow_le_pow (one_le_inv.2 ha) h
end
@[simp] lemma div_top : a / ∞ = 0 := by rw [div_eq_mul_inv, inv_top, mul_zero]
@[simp] lemma top_div_coe : ∞ / p = ∞ := by simp [div_eq_mul_inv, top_mul]
lemma top_div_of_ne_top (h : a ≠ ∞) : ∞ / a = ∞ :=
by { lift a to ℝ≥0 using h, exact top_div_coe }
lemma top_div_of_lt_top (h : a < ∞) : ∞ / a = ∞ :=
top_div_of_ne_top h.ne
lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ :=
by by_cases a = ∞; simp [top_div_of_ne_top, *]
@[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹
lemma div_eq_top : a / b = ∞ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ∞ ∧ b ≠ ∞) :=
by simp [div_eq_mul_inv, ennreal.mul_eq_top]
lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) :
a ≤ c / b ↔ a * b ≤ c :=
begin
cases b,
{ simp at ht,
split,
{ assume ha, simp at ha, simp [ha] },
{ contrapose,
assume ha,
simp at ha,
have : a * ∞ = ∞, by simp [ennreal.mul_eq_top, ha],
simp [this, ht] } },
by_cases hb : b ≠ 0,
{ have : (b : ℝ≥0∞) ≠ 0, by simp [hb],
rw [← ennreal.mul_le_mul_left this coe_ne_top],
suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c,
{ simpa [some_eq_coe, div_eq_mul_inv, hb, mul_left_comm, mul_comm, mul_assoc] },
rw [← coe_mul, mul_inv_cancel hb, coe_one, one_mul, mul_comm] },
{ simp at hb,
simp [hb] at h0,
have : c / 0 = ∞, by simp [div_eq_top, h0],
simp [hb, this] }
end
lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b :=
begin
suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_eq_mul_inv],
refine (le_div_iff_mul_le _ _).symm; simpa
end
lemma lt_div_iff_mul_lt (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : c < a / b ↔ c * b < a :=
lt_iff_lt_of_le_iff_le (div_le_iff_le_mul hb0 hbt)
lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b :=
begin
by_cases h0 : c = 0,
{ have : a = 0, by simpa [h0] using h, simp [*] },
by_cases hinf : c = ∞, by simp [hinf],
exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h
end
lemma div_le_of_le_mul' (h : a ≤ b * c) : a / b ≤ c :=
div_le_of_le_mul $ mul_comm b c ▸ h
lemma mul_le_of_le_div (h : a ≤ b / c) : a * c ≤ b :=
begin
rcases _root_.em (c = 0 ∧ b = 0 ∨ c = ∞ ∧ b = ∞) with (⟨rfl, rfl⟩|⟨rfl, rfl⟩)|H,
{ rw [mul_zero], exact le_rfl },
{ exact le_top },
{ simp only [not_or_distrib, not_and_distrib] at H,
rwa ← le_div_iff_mul_le H.1 H.2 }
end
lemma mul_le_of_le_div' (h : a ≤ b / c) : c * a ≤ b :=
mul_comm a c ▸ mul_le_of_le_div h
protected lemma div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) :
c / b < a ↔ c < a * b :=
lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le h0 ht
lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b :=
by { contrapose! h, exact ennreal.div_le_of_le_mul h }
lemma mul_lt_of_lt_div' (h : a < b / c) : c * a < b := mul_comm a c ▸ mul_lt_of_lt_div h
lemma inv_le_iff_le_mul : (b = ∞ → a ≠ 0) → (a = ∞ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) :=
begin
cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt},
by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le]
end
@[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 :=
begin
cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] },
by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le],
suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_eq_mul_inv, h] },
exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top)
end
lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a * a⁻¹ = 1 :=
begin
lift a to ℝ≥0 using ht,
norm_cast at *,
exact mul_inv_cancel h0
end
lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 :=
mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht
lemma eq_inv_of_mul_eq_one (h : a * b = 1) : a = b⁻¹ :=
begin
rcases eq_or_ne b ∞ with rfl|hb,
{ have : false, by simpa [left_ne_zero_of_mul_eq_one h] using h,
exact this.elim },
{ rw [← mul_one a, ← mul_inv_cancel (right_ne_zero_of_mul_eq_one h) hb, ← mul_assoc, h, one_mul] }
end
lemma mul_le_iff_le_inv {a b r : ℝ≥0∞} (hr₀ : r ≠ 0) (hr₁ : r ≠ ∞) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) :=
by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul]
lemma le_of_forall_nnreal_lt {x y : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r < x → ↑r ≤ y) : x ≤ y :=
begin
refine le_of_forall_ge_of_dense (λ r hr, _),
lift r to ℝ≥0 using ne_top_of_lt hr,
exact h r hr
end
lemma le_of_forall_pos_nnreal_lt {x y : ℝ≥0∞} (h : ∀ r : ℝ≥0, 0 < r → ↑r < x → ↑r ≤ y) : x ≤ y :=
le_of_forall_nnreal_lt $ λ r hr, (zero_le r).eq_or_lt.elim (λ h, h ▸ zero_le _) (λ h0, h r h0 hr)
lemma eq_top_of_forall_nnreal_le {x : ℝ≥0∞} (h : ∀ r : ℝ≥0, ↑r ≤ x) : x = ∞ :=
top_unique $ le_of_forall_nnreal_lt $ λ r hr, h r
lemma div_add_div_same {a b c : ℝ≥0∞} : a / c + b / c = (a + b) / c :=
eq.symm $ right_distrib a b (c⁻¹)
lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 :=
mul_inv_cancel h0 hI
lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b :=
by rw [div_eq_mul_inv, mul_assoc, inv_mul_cancel h0 hI, mul_one]
lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b :=
by rw [mul_comm, mul_div_cancel h0 hI]
lemma mul_div_le : a * (b / a) ≤ b :=
begin
by_cases h0 : a = 0, { simp [h0] },
by_cases hI : a = ∞, { simp [hI] },
rw mul_div_cancel' h0 hI, exact le_refl b
end
lemma inv_two_add_inv_two : (2:ℝ≥0∞)⁻¹ + 2⁻¹ = 1 :=
by rw [← two_mul, ← div_eq_mul_inv, div_self two_ne_zero two_ne_top]
lemma add_halves (a : ℝ≥0∞) : a / 2 + a / 2 = a :=
by rw [div_eq_mul_inv, ← mul_add, inv_two_add_inv_two, mul_one]
@[simp] lemma div_zero_iff : a / b = 0 ↔ a = 0 ∨ b = ∞ :=
by simp [div_eq_mul_inv]
@[simp] lemma div_pos_iff : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ∞ :=
by simp [pos_iff_ne_zero, not_or_distrib]
lemma half_pos {a : ℝ≥0∞} (h : a ≠ 0) : 0 < a / 2 :=
by simp [h]
lemma one_half_lt_one : (2⁻¹:ℝ≥0∞) < 1 := inv_lt_one.2 $ one_lt_two
lemma half_lt_self {a : ℝ≥0∞} (hz : a ≠ 0) (ht : a ≠ ∞) : a / 2 < a :=
begin
lift a to ℝ≥0 using ht,
have h : (2 : ℝ≥0∞) = ((2 : ℝ≥0) : ℝ≥0∞), from rfl,
have h' : (2 : ℝ≥0) ≠ 0, from _root_.two_ne_zero',
rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div`
norm_cast at hz,
exact nnreal.half_lt_self hz
end
lemma half_le_self : a / 2 ≤ a := le_add_self.trans_eq (add_halves _)
lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 :=
begin
lift a to ℝ≥0 using h,
exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a)
end
@[simp] lemma one_sub_inv_two : (1:ℝ≥0∞) - 2⁻¹ = 2⁻¹ :=
by simpa only [div_eq_mul_inv, one_mul] using sub_half one_ne_top
lemma exists_inv_nat_lt {a : ℝ≥0∞} (h : a ≠ 0) :
∃n:ℕ, (n:ℝ≥0∞)⁻¹ < a :=
@inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)]
lemma exists_nat_pos_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) :
∃ n > 0, b < (n : ℕ) * a :=
begin
have : b / a ≠ ∞, from mul_ne_top hb (inv_ne_top.2 ha),
refine (ennreal.exists_nat_gt this).imp (λ n hn, _),
have : 0 < (n : ℝ≥0∞), from (zero_le _).trans_lt hn,
refine ⟨coe_nat_lt_coe_nat.1 this, _⟩,
rwa [← ennreal.div_lt_iff (or.inl ha) (or.inr hb)]
end
lemma exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) :
∃ n : ℕ, b < n * a :=
(exists_nat_pos_mul_gt ha hb).imp $ λ n, Exists.snd
lemma exists_nat_pos_inv_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) :
∃ n > 0, ((n : ℕ) : ℝ≥0∞)⁻¹ * a < b :=
begin
rcases exists_nat_pos_mul_gt hb ha with ⟨n, npos, hn⟩,
have : (n : ℝ≥0∞) ≠ 0 := nat.cast_ne_zero.2 npos.lt.ne',
use [n, npos],
rwa [← one_mul b, ← inv_mul_cancel this coe_nat_ne_top,
mul_assoc, mul_lt_mul_left (inv_ne_zero.2 coe_nat_ne_top) (inv_ne_top.2 this)]
end
lemma exists_nnreal_pos_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) :
∃ n > 0, ↑(n : ℝ≥0) * a < b :=
begin
rcases exists_nat_pos_inv_mul_lt ha hb with ⟨n, npos : 0 < n, hn⟩,
use (n : ℝ≥0)⁻¹,
simp [*, npos.ne', zero_lt_one]
end
lemma exists_inv_two_pow_lt (ha : a ≠ 0) :
∃ n : ℕ, 2⁻¹ ^ n < a :=
begin
rcases exists_inv_nat_lt ha with ⟨n, hn⟩,
simp only [← ennreal.inv_pow],
refine ⟨n, lt_trans (inv_lt_inv.2 _) hn⟩,
norm_cast,
exact n.lt_two_pow
end
end inv
section real
lemma to_real_add (ha : a ≠ ∞) (hb : b ≠ ∞) : (a+b).to_real = a.to_real + b.to_real :=
begin
lift a to ℝ≥0 using ha,
lift b to ℝ≥0 using hb,
refl
end
lemma to_real_sub_of_le {a b : ℝ≥0∞} (h : b ≤ a) (ha : a ≠ ∞):
(a - b).to_real = a.to_real - b.to_real :=
begin
lift b to ℝ≥0 using ne_top_of_le_ne_top ha h,
lift a to ℝ≥0 using ha,
simp only [← ennreal.coe_sub, ennreal.coe_to_real, nnreal.coe_sub (ennreal.coe_le_coe.mp h)],
end
lemma le_to_real_sub {a b : ℝ≥0∞} (hb : b ≠ ∞) : a.to_real - b.to_real ≤ (a - b).to_real :=
begin
lift b to ℝ≥0 using hb,
cases a; simp [none_eq_top, some_eq_coe, ← coe_sub, nnreal.sub_def] at *
end
lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real :=
if ha : a = ∞ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg]
else if hb : b = ∞ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg]
else le_of_eq (to_real_add ha hb)
lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) :
ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q :=
by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add,
coe_eq_coe, real.to_nnreal_add hp hq]
lemma of_real_add_le {p q : ℝ} : ennreal.of_real (p + q) ≤ ennreal.of_real p + ennreal.of_real q :=
coe_le_coe.2 real.to_nnreal_add_le
@[simp] lemma to_real_le_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real ≤ b.to_real ↔ a ≤ b :=
begin
lift a to ℝ≥0 using ha,
lift b to ℝ≥0 using hb,
norm_cast
end
lemma to_real_mono (hb : b ≠ ∞) (h : a ≤ b) : a.to_real ≤ b.to_real :=
(to_real_le_to_real (h.trans_lt (lt_top_iff_ne_top.2 hb)).ne hb).2 h
@[simp] lemma to_real_lt_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real < b.to_real ↔ a < b :=
begin
lift a to ℝ≥0 using ha,
lift b to ℝ≥0 using hb,
norm_cast
end
lemma to_real_strict_mono (hb : b ≠ ∞) (h : a < b) : a.to_real < b.to_real :=
(to_real_lt_to_real (h.trans (lt_top_iff_ne_top.2 hb)).ne hb).2 h
lemma to_real_max (hr : a ≠ ∞) (hp : b ≠ ∞) :
ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) :=
(le_total a b).elim
(λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right])
(λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left])
lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a ≠ ∞) :=
begin
cases a,
{ simp [none_eq_top] },
{ simp [some_eq_coe] }
end
lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a ≠ ∞):=
(nnreal.coe_pos).trans to_nnreal_pos_iff
lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q :=
by simp [ennreal.of_real, real.to_nnreal_le_to_nnreal h]
lemma of_real_le_of_le_to_real {a : ℝ} {b : ℝ≥0∞} (h : a ≤ ennreal.to_real b) :
ennreal.of_real a ≤ b :=
(of_real_le_of_real h).trans of_real_to_real_le
@[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) :
ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q :=
by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, real.to_nnreal_le_to_nnreal_iff h]
@[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) :
ennreal.of_real p < ennreal.of_real q ↔ p < q :=
by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, real.to_nnreal_lt_to_nnreal_iff h]
lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) :
ennreal.of_real p < ennreal.of_real q ↔ p < q :=
by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, real.to_nnreal_lt_to_nnreal_iff_of_nonneg hp]
@[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p :=
by simp [ennreal.of_real]
@[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 :=
by simp [ennreal.of_real]
@[simp] lemma zero_eq_of_real {p : ℝ} : 0 = ennreal.of_real p ↔ p ≤ 0 :=
eq_comm.trans of_real_eq_zero
lemma of_real_le_iff_le_to_real {a : ℝ} {b : ℝ≥0∞} (hb : b ≠ ∞) :
ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b :=
begin
lift b to ℝ≥0 using hb,
simpa [ennreal.of_real, ennreal.to_real] using real.to_nnreal_le_iff_le_coe
end
lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ℝ≥0∞} (ha : 0 ≤ a) (hb : b ≠ ∞) :
ennreal.of_real a < b ↔ a < ennreal.to_real b :=
begin
lift b to ℝ≥0 using hb,
simpa [ennreal.of_real, ennreal.to_real] using real.to_nnreal_lt_iff_lt_coe ha
end
lemma le_of_real_iff_to_real_le {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) (hb : 0 ≤ b) :
a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b :=
begin
lift a to ℝ≥0 using ha,
simpa [ennreal.of_real, ennreal.to_real] using real.le_to_nnreal_iff_coe_le hb
end
lemma to_real_le_of_le_of_real {a : ℝ≥0∞} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) :
ennreal.to_real a ≤ b :=
have ha : a ≠ ∞, from ne_top_of_le_ne_top of_real_ne_top h,
(le_of_real_iff_to_real_le ha hb).1 h
lemma lt_of_real_iff_to_real_lt {a : ℝ≥0∞} {b : ℝ} (ha : a ≠ ∞) :
a < ennreal.of_real b ↔ ennreal.to_real a < b :=
begin
lift a to ℝ≥0 using ha,
simpa [ennreal.of_real, ennreal.to_real] using real.lt_to_nnreal_iff_coe_lt
end
lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) :
ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) :=
by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact real.to_nnreal_mul hp }
lemma of_real_pow {p : ℝ} (hp : 0 ≤ p) (n : ℕ) :
ennreal.of_real (p ^ n) = ennreal.of_real p ^ n :=
by rw [of_real_eq_coe_nnreal hp, ← coe_pow, ← of_real_coe_nnreal, nnreal.coe_pow, nnreal.coe_mk]
lemma of_real_inv_of_pos {x : ℝ} (hx : 0 < x) :
(ennreal.of_real x)⁻¹ = ennreal.of_real x⁻¹ :=
by rw [ennreal.of_real, ennreal.of_real, ←@coe_inv (real.to_nnreal x) (by simp [hx]), coe_eq_coe,
real.to_nnreal_inv.symm]
lemma of_real_div_of_pos {x y : ℝ} (hy : 0 < y) :
ennreal.of_real (x / y) = ennreal.of_real x / ennreal.of_real y :=
by rw [div_eq_inv_mul, div_eq_mul_inv, of_real_mul (inv_nonneg.2 hy.le), of_real_inv_of_pos hy,
mul_comm]
lemma to_real_of_real_mul (c : ℝ) (a : ℝ≥0∞) (h : 0 ≤ c) :
ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a :=
begin
cases a,
{ simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top],
by_cases h' : c ≤ 0,
{ rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } },
{ rw [if_neg], refl, rw [of_real_eq_zero], assumption } },
{ simp only [ennreal.to_real, ennreal.to_nnreal],
simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul],
congr, apply real.coe_to_nnreal, exact h }
end
@[simp] lemma to_nnreal_mul_top (a : ℝ≥0∞) : ennreal.to_nnreal (a * ∞) = 0 :=
begin
by_cases h : a = 0,
{ rw [h, zero_mul, zero_to_nnreal] },
{ rw [mul_top, if_neg h, top_to_nnreal] }
end
@[simp] lemma to_nnreal_top_mul (a : ℝ≥0∞) : ennreal.to_nnreal (∞ * a) = 0 :=
by rw [mul_comm, to_nnreal_mul_top]
@[simp] lemma to_real_mul_top (a : ℝ≥0∞) : ennreal.to_real (a * ∞) = 0 :=
by rw [ennreal.to_real, to_nnreal_mul_top, nnreal.coe_zero]
@[simp] lemma to_real_top_mul (a : ℝ≥0∞) : ennreal.to_real (∞ * a) = 0 :=
by { rw mul_comm, exact to_real_mul_top _ }
lemma to_real_eq_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) :
ennreal.to_real a = ennreal.to_real b ↔ a = b :=
begin
lift a to ℝ≥0 using ha,
lift b to ℝ≥0 using hb,
simp only [coe_eq_coe, nnreal.coe_eq, coe_to_real],
end
lemma to_real_smul (r : ℝ≥0) (s : ℝ≥0∞) :
(r • s).to_real = r • s.to_real :=
begin
induction s using with_top.rec_top_coe,
{ rw [show r • ∞ = (r : ℝ≥0∞) * ∞, by refl],
simp only [ennreal.to_real_mul_top, ennreal.top_to_real, smul_zero] },
{ rw [← coe_smul, ennreal.coe_to_real, ennreal.coe_to_real],
refl }
end
/-- `ennreal.to_nnreal` as a `monoid_hom`. -/
def to_nnreal_hom : ℝ≥0∞ →* ℝ≥0 :=
{ to_fun := ennreal.to_nnreal,
map_one' := to_nnreal_coe,
map_mul' := by rintro (_|x) (_|y); simp only [← coe_mul, none_eq_top, some_eq_coe,
to_nnreal_top_mul, to_nnreal_mul_top, top_to_nnreal, mul_zero, zero_mul, to_nnreal_coe] }
lemma to_nnreal_mul {a b : ℝ≥0∞}: (a * b).to_nnreal = a.to_nnreal * b.to_nnreal :=
to_nnreal_hom.map_mul a b
lemma to_nnreal_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).to_nnreal = a.to_nnreal ^ n :=
to_nnreal_hom.map_pow a n
lemma to_nnreal_prod {ι : Type*} {s : finset ι} {f : ι → ℝ≥0∞} :
(∏ i in s, f i).to_nnreal = ∏ i in s, (f i).to_nnreal :=
to_nnreal_hom.map_prod _ _
lemma to_nnreal_inv (a : ℝ≥0∞) : (a⁻¹).to_nnreal = (a.to_nnreal)⁻¹ :=
begin
rcases eq_or_ne a ∞ with rfl|ha, { simp },
lift a to ℝ≥0 using ha,
rcases eq_or_ne a 0 with rfl|ha, { simp },
rw [← coe_inv ha, to_nnreal_coe, to_nnreal_coe]
end
lemma to_nnreal_div (a b : ℝ≥0∞) : (a / b).to_nnreal = a.to_nnreal / b.to_nnreal :=
by rw [div_eq_mul_inv, to_nnreal_mul, to_nnreal_inv, div_eq_mul_inv]
/-- `ennreal.to_real` as a `monoid_hom`. -/
def to_real_hom : ℝ≥0∞ →* ℝ :=
(nnreal.to_real_hom : ℝ≥0 →* ℝ).comp to_nnreal_hom
lemma to_real_mul : (a * b).to_real = a.to_real * b.to_real :=
to_real_hom.map_mul a b
lemma to_real_pow (a : ℝ≥0∞) (n : ℕ) : (a ^ n).to_real = a.to_real ^ n :=
to_real_hom.map_pow a n
lemma to_real_prod {ι : Type*} {s : finset ι} {f : ι → ℝ≥0∞} :
(∏ i in s, f i).to_real = ∏ i in s, (f i).to_real :=
to_real_hom.map_prod _ _
lemma to_real_inv (a : ℝ≥0∞) : (a⁻¹).to_real = (a.to_real)⁻¹ :=
by { simp_rw ennreal.to_real, norm_cast, exact to_nnreal_inv a, }
lemma to_real_div (a b : ℝ≥0∞) : (a / b).to_real = a.to_real / b.to_real :=
by rw [div_eq_mul_inv, to_real_mul, to_real_inv, div_eq_mul_inv]
lemma of_real_prod_of_nonneg {s : finset α} {f : α → ℝ} (hf : ∀ i, i ∈ s → 0 ≤ f i) :
ennreal.of_real (∏ i in s, f i) = ∏ i in s, ennreal.of_real (f i) :=
begin
simp_rw [ennreal.of_real, ←coe_finset_prod, coe_eq_coe],
exact real.to_nnreal_prod_of_nonneg hf,
end
@[simp] lemma to_nnreal_bit0 {x : ℝ≥0∞} : (bit0 x).to_nnreal = bit0 (x.to_nnreal) :=
begin
by_cases hx_top : x = ∞,
{ simp [hx_top, bit0_eq_top_iff.mpr rfl], },
exact to_nnreal_add hx_top hx_top,
end
@[simp] lemma to_nnreal_bit1 {x : ℝ≥0∞} (hx_top : x ≠ ∞) :
(bit1 x).to_nnreal = bit1 (x.to_nnreal) :=
by simp [bit1, bit1, to_nnreal_add (by rwa [ne.def, bit0_eq_top_iff]) ennreal.one_ne_top]
@[simp] lemma to_real_bit0 {x : ℝ≥0∞} : (bit0 x).to_real = bit0 (x.to_real) :=
by simp [ennreal.to_real]
@[simp] lemma to_real_bit1 {x : ℝ≥0∞} (hx_top : x ≠ ∞) :
(bit1 x).to_real = bit1 (x.to_real) :=
by simp [ennreal.to_real, hx_top]
@[simp] lemma of_real_bit0 {r : ℝ} (hr : 0 ≤ r) :
ennreal.of_real (bit0 r) = bit0 (ennreal.of_real r) :=
of_real_add hr hr
@[simp] lemma of_real_bit1 {r : ℝ} (hr : 0 ≤ r) :
ennreal.of_real (bit1 r) = bit1 (ennreal.of_real r) :=
(of_real_add (by simp [hr]) zero_le_one).trans (by simp [real.to_nnreal_one, bit1, hr])
end real
section infi
variables {ι : Sort*} {f g : ι → ℝ≥0∞}
lemma infi_add : infi f + a = ⨅i, f i + a :=
le_antisymm
(le_infi $ assume i, add_le_add (infi_le _ _) $ le_refl _)
(ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _)
lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) :=
le_antisymm
(ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i)
(supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a))
lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) :=
begin
refine (eq_of_forall_ge_iff $ λ c, _),
rw [ennreal.sub_le_iff_le_add, add_comm, infi_add],
simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm],
end
lemma Inf_add {s : set ℝ≥0∞} : Inf s + a = ⨅b∈s, b + a :=
by simp [Inf_eq_infi, infi_add]
lemma add_infi {a : ℝ≥0∞} : a + infi f = ⨅b, a + f b :=
by rw [add_comm, infi_add]; simp [add_comm]
lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) :=
suffices (⨅a, f a + g a) ≤ infi f + infi g,
from le_antisymm (le_infi $ assume a, add_le_add (infi_le _ _) (infi_le _ _)) this,
calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') :
le_infi $ assume a, le_infi $ assume a',
let ⟨k, h⟩ := h a a' in infi_le_of_le k h
... = infi f + infi g :
by simp [add_infi, infi_add]
lemma infi_sum {f : ι → α → ℝ≥0∞} {s : finset α} [nonempty ι]
(h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) :
(⨅i, ∑ a in s, f i a) = ∑ a in s, ⨅i, f i a :=
finset.induction_on s (by simp) $ assume a s ha ih,
have ∀ (i j : ι), ∃ (k : ι), f k a + ∑ b in s, f k b ≤ f i a + ∑ b in s, f j b,
from assume i j,
let ⟨k, hk⟩ := h (insert a s) i j in
⟨k, add_le_add (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $
assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩,
by simp [ha, ih.symm, infi_add_infi this]
/-- If `x ≠ 0` and `x ≠ ∞`, then right multiplication by `x` maps infimum to infimum.
See also `ennreal.infi_mul` that assumes `[nonempty ι]` but does not require `x ≠ 0`. -/
lemma infi_mul_of_ne {ι} {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h0 : x ≠ 0) (h : x ≠ ∞) :
infi f * x = ⨅ i, f i * x :=
le_antisymm
mul_right_mono.map_infi_le
((div_le_iff_le_mul (or.inl h0) $ or.inl h).mp $ le_infi $
λ i, (div_le_iff_le_mul (or.inl h0) $ or.inl h).mpr $ infi_le _ _)
/-- If `x ≠ ∞`, then right multiplication by `x` maps infimum over a nonempty type to infimum. See
also `ennreal.infi_mul_of_ne` that assumes `x ≠ 0` but does not require `[nonempty ι]`. -/
lemma infi_mul {ι} [nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) :
infi f * x = ⨅ i, f i * x :=
begin
by_cases h0 : x = 0,
{ simp only [h0, mul_zero, infi_const] },
{ exact infi_mul_of_ne h0 h }
end
/-- If `x ≠ ∞`, then left multiplication by `x` maps infimum over a nonempty type to infimum. See
also `ennreal.mul_infi_of_ne` that assumes `x ≠ 0` but does not require `[nonempty ι]`. -/
lemma mul_infi {ι} [nonempty ι] {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h : x ≠ ∞) :
x * infi f = ⨅ i, x * f i :=
by simpa only [mul_comm] using infi_mul h
/-- If `x ≠ 0` and `x ≠ ∞`, then left multiplication by `x` maps infimum to infimum.
See also `ennreal.mul_infi` that assumes `[nonempty ι]` but does not require `x ≠ 0`. -/
lemma mul_infi_of_ne {ι} {f : ι → ℝ≥0∞} {x : ℝ≥0∞} (h0 : x ≠ 0) (h : x ≠ ∞) :
x * infi f = ⨅ i, x * f i :=
by simpa only [mul_comm] using infi_mul_of_ne h0 h
/-! `supr_mul`, `mul_supr` and variants are in `topology.instances.ennreal`. -/
end infi
section supr
@[simp] lemma supr_eq_zero {ι : Sort*} {f : ι → ℝ≥0∞} : (⨆ i, f i) = 0 ↔ ∀ i, f i = 0 :=
supr_eq_bot
@[simp] lemma supr_zero_eq_zero {ι : Sort*} : (⨆ i : ι, (0 : ℝ≥0∞)) = 0 :=
by simp
lemma sup_eq_zero {a b : ℝ≥0∞} : a ⊔ b = 0 ↔ a = 0 ∧ b = 0 := sup_eq_bot_iff
lemma supr_coe_nat : (⨆n:ℕ, (n : ℝ≥0∞)) = ∞ :=
(supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb)
end supr
/-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`,
but it holds in `ℝ≥0∞` with the additional assumption that `a ≠ ∞`. -/
lemma le_of_add_le_add_left {a b c : ℝ≥0∞} (ha : a ≠ ∞) :
a + b ≤ a + c → b ≤ c :=
begin
lift a to ℝ≥0 using ha,
cases b; cases c; simp [← ennreal.coe_add, ennreal.coe_le_coe]
end
/-- `le_of_add_le_add_right` is normally applicable to `ordered_cancel_add_comm_monoid`,
but it holds in `ℝ≥0∞` with the additional assumption that `a ≠ ∞`. -/
lemma le_of_add_le_add_right {a b c : ℝ≥0∞} : a ≠ ∞ →
b + a ≤ c + a → b ≤ c :=
by simpa only [add_comm _ a] using le_of_add_le_add_left
end ennreal
|
75683544a9b9ab92621c3ad8870f5dfd09da0e90 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/parser_error_recovery.lean | 1ad789807b01999a1be8d3e03320757670e325b9 | [
"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 | 643 | lean | /- unknown identifiers -/
def f1 : ℕ → ℕ
| 42 := 1234
| arg := ag
#eval f1 42 -- OK (prints 1234)
/- incomplete structure instances -/
def f2 : ℕ × ℕ := { fst := 1234, sn}
#reduce f2.fst -- OK (prints 1234)
/- incomplete if-then-else -/
def f3 (x : ℕ) : ℕ :=
(if x ≥ 42 then 1234)
-- ^ missing else reported here
#eval f3 42 -- OK (prints 1234)
/- η-expanded syntax errors -/
def f4 : list ℕ :=
list.map nat.suc []
#eval f4 -- OK (prints [])
/- tactic scripts with syntax errors -/
lemma f5 (x : ℕ) : x+1 = 1+x :=
by {
simp,
trace_state, -- OK (no goals)
simmp,***,
simp a,,, |
8a66a7b3eff5f0d292c68eaa74c679287fa6d452 | 6065973b1fa7bbacba932011c9e2f32bf7bdd6c1 | /src/algebra/group/prod.lean | ec248edc5f6ecefe939be8724b7a6267f7475453 | [
"Apache-2.0"
] | permissive | khmacdonald/mathlib | 90a0fa2222369fa69ed2fbfb841b74d2bdfd66cb | 3669cb35c578441812ad30fd967d21a94b6f387e | refs/heads/master | 1,675,863,801,090 | 1,609,761,876,000 | 1,609,761,876,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,572 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot, Yury Kudryashov
-/
import algebra.group.hom
import data.equiv.mul_add
import data.prod
/-!
# Monoid, group etc structures on `M × N`
In this file we define one-binop (`monoid`, `group` etc) structures on `M × N`. We also prove
trivial `simp` lemmas, and define the following operations on `monoid_hom`s:
* `fst M N : M × N →* M`, `snd M N : M × N →* N`: projections `prod.fst` and `prod.snd`
as `monoid_hom`s;
* `inl M N : M →* M × N`, `inr M N : N →* M × N`: inclusions of first/second monoid
into the product;
* `f.prod g : `M →* N × P`: sends `x` to `(f x, g x)`;
* `f.coprod g : M × N →* P`: sends `(x, y)` to `f x * g y`;
* `f.prod_map g : M × N → M' × N'`: `prod.map f g` as a `monoid_hom`,
sends `(x, y)` to `(f x, g y)`.
-/
variables {A : Type*} {B : Type*} {G : Type*} {H : Type*} {M : Type*} {N : Type*} {P : Type*}
namespace prod
@[to_additive]
instance [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩
@[simp, to_additive]
lemma fst_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).1 = p.1 * q.1 := rfl
@[simp, to_additive]
lemma snd_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).2 = p.2 * q.2 := rfl
@[simp, to_additive]
lemma mk_mul_mk [has_mul M] [has_mul N] (a₁ a₂ : M) (b₁ b₂ : N) :
(a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl
@[to_additive]
instance [has_one M] [has_one N] : has_one (M × N) := ⟨(1, 1)⟩
@[simp, to_additive]
lemma fst_one [has_one M] [has_one N] : (1 : M × N).1 = 1 := rfl
@[simp, to_additive]
lemma snd_one [has_one M] [has_one N] : (1 : M × N).2 = 1 := rfl
@[to_additive]
lemma one_eq_mk [has_one M] [has_one N] : (1 : M × N) = (1, 1) := rfl
@[simp, to_additive]
lemma mk_eq_one [has_one M] [has_one N] {x : M} {y : N} : (x, y) = 1 ↔ x = 1 ∧ y = 1 :=
mk.inj_iff
@[to_additive]
lemma fst_mul_snd [monoid M] [monoid N] (p : M × N) :
(p.fst, 1) * (1, p.snd) = p :=
ext (mul_one p.1) (one_mul p.2)
@[to_additive]
instance [has_inv M] [has_inv N] : has_inv (M × N) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩
@[simp, to_additive]
lemma fst_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).1 = (p.1)⁻¹ := rfl
@[simp, to_additive]
lemma snd_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).2 = (p.2)⁻¹ := rfl
@[simp, to_additive]
lemma inv_mk [has_inv G] [has_inv H] (a : G) (b : H) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl
@[to_additive]
instance [has_div M] [has_div N] : has_div (M × N) := ⟨λ p q, ⟨p.1 / q.1, p.2 / q.2⟩⟩
@[simp] lemma fst_sub [add_group A] [add_group B] (a b : A × B) : (a - b).1 = a.1 - b.1 := rfl
@[simp] lemma snd_sub [add_group A] [add_group B] (a b : A × B) : (a - b).2 = a.2 - b.2 := rfl
@[simp] lemma mk_sub_mk [add_group A] [add_group B] (x₁ x₂ : A) (y₁ y₂ : B) :
(x₁, y₁) - (x₂, y₂) = (x₁ - x₂, y₁ - y₂) := rfl
@[to_additive]
instance [semigroup M] [semigroup N] : semigroup (M × N) :=
{ mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩,
.. prod.has_mul }
@[to_additive]
instance [monoid M] [monoid N] : monoid (M × N) :=
{ 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 }
@[to_additive]
instance [group G] [group H] : group (G × H) :=
{ mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩,
div_eq_mul_inv := λ a b, mk.inj_iff.mpr ⟨div_eq_mul_inv _ _, div_eq_mul_inv _ _⟩,
.. prod.monoid, .. prod.has_inv, .. prod.has_div }
@[to_additive]
instance [comm_semigroup G] [comm_semigroup H] : comm_semigroup (G × H) :=
{ mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩,
.. prod.semigroup }
@[to_additive]
instance [left_cancel_semigroup G] [left_cancel_semigroup H] :
left_cancel_semigroup (G × H) :=
{ mul_left_cancel := λ a b c h, prod.ext (mul_left_cancel (prod.ext_iff.1 h).1)
(mul_left_cancel (prod.ext_iff.1 h).2),
.. prod.semigroup }
@[to_additive]
instance [right_cancel_semigroup G] [right_cancel_semigroup H] :
right_cancel_semigroup (G × H) :=
{ mul_right_cancel := λ a b c h, prod.ext (mul_right_cancel (prod.ext_iff.1 h).1)
(mul_right_cancel (prod.ext_iff.1 h).2),
.. prod.semigroup }
@[to_additive]
instance [comm_monoid M] [comm_monoid N] : comm_monoid (M × N) :=
{ .. prod.comm_semigroup, .. prod.monoid }
@[to_additive]
instance [comm_group G] [comm_group H] : comm_group (G × H) :=
{ .. prod.comm_semigroup, .. prod.group }
/-- The monoid equivalence between units of a product of two monoids, and the product of the
units of each monoid. -/
def units [monoid M] [monoid N] : units (M × N) ≃* units M × units N :=
mul_equiv.mk'
{ to_fun := λ ⟨⟨u₁, u₂⟩, ⟨v₁, v₂⟩, huv, hvu⟩,
⟨⟨u₁, v₁, by {rw [prod.mk_mul_mk, prod.mk_eq_one] at huv, exact huv.1},
by {rw [prod.mk_mul_mk, prod.mk_eq_one] at hvu, exact hvu.1}⟩,
⟨u₂, v₂, by {rw [prod.mk_mul_mk, prod.mk_eq_one] at huv, exact huv.2},
by {rw [prod.mk_mul_mk, prod.mk_eq_one] at hvu, exact hvu.2}⟩⟩,
inv_fun := λ ⟨⟨u₁, v₁, huv₁, hvu₁⟩, ⟨u₂, v₂, huv₂, hvu₂⟩⟩,
⟨(u₁, u₂), (v₁, v₂), by {rw [prod.mk_mul_mk, prod.mk_eq_one], exact ⟨huv₁, huv₂⟩},
by {rw [prod.mk_mul_mk, prod.mk_eq_one], exact ⟨hvu₁, hvu₂⟩}⟩,
left_inv := by {rintro ⟨⟨u₁, u₂⟩, ⟨v₁, v₂⟩, huv, hvu⟩, simpa, },
right_inv := by {rintro ⟨⟨u₁, v₁, huv₁, hvu₁⟩, ⟨u₂, v₂, huv₂, hvu₂⟩⟩, simpa, } }
(λ ⟨⟨ux, ux₂⟩, ⟨vx₁, vx₂⟩, hxuv, hxvu⟩ ⟨⟨uy₁, uy₂⟩, ⟨vy₁, vy₂⟩, hyuv, hyvu⟩, rfl)
-- TODO attribute [to_additive add_units] units fails
end prod
namespace monoid_hom
variables (M N) [monoid M] [monoid N]
/-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `M`.-/
@[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism
from `A × B` to `A`"]
def fst : M × N →* M := ⟨prod.fst, rfl, λ _ _, rfl⟩
/-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `N`.-/
@[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism
from `A × B` to `B`"]
def snd : M × N →* N := ⟨prod.snd, rfl, λ _ _, rfl⟩
/-- Given monoids `M`, `N`, the natural inclusion homomorphism from `M` to `M × N`. -/
@[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism
from `A` to `A × B`."]
def inl : M →* M × N :=
⟨λ x, (x, 1), rfl, λ _ _, prod.ext rfl (one_mul 1).symm⟩
/-- Given monoids `M`, `N`, the natural inclusion homomorphism from `N` to `M × N`. -/
@[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism
from `B` to `A × B`."]
def inr : N →* M × N :=
⟨λ y, (1, y), rfl, λ _ _, prod.ext (one_mul 1).symm rfl⟩
variables {M N}
@[simp, to_additive] lemma coe_fst : ⇑(fst M N) = prod.fst := rfl
@[simp, to_additive] lemma coe_snd : ⇑(snd M N) = prod.snd := rfl
@[simp, to_additive] lemma inl_apply (x) : inl M N x = (x, 1) := rfl
@[simp, to_additive] lemma inr_apply (y) : inr M N y = (1, y) := rfl
@[simp, to_additive] lemma fst_comp_inl : (fst M N).comp (inl M N) = id M := rfl
@[simp, to_additive] lemma snd_comp_inl : (snd M N).comp (inl M N) = 1 := rfl
@[simp, to_additive] lemma fst_comp_inr : (fst M N).comp (inr M N) = 1 := rfl
@[simp, to_additive] lemma snd_comp_inr : (snd M N).comp (inr M N) = id N := rfl
section prod
variable [monoid P]
/-- Combine two `monoid_hom`s `f : M →* N`, `g : M →* P` into `f.prod g : M →* N × P`
given by `(f.prod g) x = (f x, g x)` -/
@[to_additive prod "Combine two `add_monoid_hom`s `f : M →+ N`, `g : M →+ P` into
`f.prod g : M →+ N × P` given by `(f.prod g) x = (f x, g x)`"]
protected def prod (f : M →* N) (g : M →* P) : M →* N × P :=
{ to_fun := λ x, (f x, g x),
map_one' := prod.ext f.map_one g.map_one,
map_mul' := λ x y, prod.ext (f.map_mul x y) (g.map_mul x y) }
@[simp, to_additive prod_apply]
lemma prod_apply (f : M →* N) (g : M →* P) (x) : f.prod g x = (f x, g x) := rfl
@[simp, to_additive fst_comp_prod]
lemma fst_comp_prod (f : M →* N) (g : M →* P) : (fst N P).comp (f.prod g) = f :=
ext $ λ x, rfl
@[simp, to_additive snd_comp_prod]
lemma snd_comp_prod (f : M →* N) (g : M →* P) : (snd N P).comp (f.prod g) = g :=
ext $ λ x, rfl
@[simp, to_additive prod_unique]
lemma prod_unique (f : M →* N × P) :
((fst N P).comp f).prod ((snd N P).comp f) = f :=
ext $ λ x, by simp only [prod_apply, coe_fst, coe_snd, comp_apply, prod.mk.eta]
end prod
section prod_map
variables {M' : Type*} {N' : Type*} [monoid M'] [monoid N'] [monoid P]
(f : M →* M') (g : N →* N')
/-- `prod.map` as a `monoid_hom`. -/
@[to_additive prod_map "`prod.map` as an `add_monoid_hom`"]
def prod_map : M × N →* M' × N' := (f.comp (fst M N)).prod (g.comp (snd M N))
@[to_additive prod_map_def]
lemma prod_map_def : prod_map f g = (f.comp (fst M N)).prod (g.comp (snd M N)) := rfl
@[simp, to_additive coe_prod_map]
lemma coe_prod_map : ⇑(prod_map f g) = prod.map f g := rfl
@[to_additive prod_comp_prod_map]
lemma prod_comp_prod_map (f : P →* M) (g : P →* N) (f' : M →* M') (g' : N →* N') :
(f'.prod_map g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) :=
rfl
end prod_map
section coprod
variables [comm_monoid P] (f : M →* P) (g : N →* P)
/-- Coproduct of two `monoid_hom`s with the same codomain:
`f.coprod g (p : M × N) = f p.1 * g p.2`. -/
@[to_additive "Coproduct of two `add_monoid_hom`s with the same codomain:
`f.coprod g (p : M × N) = f p.1 + g p.2`."]
def coprod : M × N →* P := f.comp (fst M N) * g.comp (snd M N)
@[simp, to_additive]
lemma coprod_apply (p : M × N) : f.coprod g p = f p.1 * g p.2 := rfl
@[simp, to_additive]
lemma coprod_comp_inl : (f.coprod g).comp (inl M N) = f :=
ext $ λ x, by simp [coprod_apply]
@[simp, to_additive]
lemma coprod_comp_inr : (f.coprod g).comp (inr M N) = g :=
ext $ λ x, by simp [coprod_apply]
@[simp, to_additive] lemma coprod_unique (f : M × N →* P) :
(f.comp (inl M N)).coprod (f.comp (inr M N)) = f :=
ext $ λ x, by simp [coprod_apply, inl_apply, inr_apply, ← map_mul]
@[simp, to_additive] lemma coprod_inl_inr {M N : Type*} [comm_monoid M] [comm_monoid N] :
(inl M N).coprod (inr M N) = id (M × N) :=
coprod_unique (id $ M × N)
lemma comp_coprod {Q : Type*} [comm_monoid Q] (h : P →* Q) (f : M →* P) (g : N →* P) :
h.comp (f.coprod g) = (h.comp f).coprod (h.comp g) :=
ext $ λ x, by simp
end coprod
end monoid_hom
namespace mul_equiv
variables (M N) [monoid M] [monoid N]
/-- The equivalence between `M × N` and `N × M` given by swapping the components is multiplicative. -/
@[to_additive prod_comm "The equivalence between `M × N` and `N × M` given by swapping the components is
additive."]
def prod_comm : M × N ≃* N × M :=
{ map_mul' := λ ⟨x₁, y₁⟩ ⟨x₂, y₂⟩, rfl, ..equiv.prod_comm M N }
@[simp, to_additive coe_prod_comm] lemma coe_prod_comm : ⇑(prod_comm M N) = prod.swap := rfl
@[simp, to_additive coe_prod_comm_symm] lemma coe_prod_comm_symm :
⇑((prod_comm M N).symm) = prod.swap := rfl
end mul_equiv
|
84c7fdff046bc292544d03ea6ecb082a93d4b841 | 5b0c53e5aaa0e60538d10f6b619a464aaf463815 | /misc.hlean | 93a9a3b7f2b2602a7cea720973fdbfcf226392a5 | [
"Apache-2.0"
] | permissive | bbentzen/hott-book-in-lean | f845a19ef09d48d2fb813624b4650d5832a47e10 | 9e262e633e653280b9cde5d287631fcec8501f64 | refs/heads/master | 1,586,430,679,994 | 1,519,975,089,000 | 1,519,975,089,000 | 50,330,220 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 992 | hlean | /-
Copyright (c) 2017 Bruno Bentzen. All rights reserved.
Released under the Apache License 2.0 (see "License");
-/
import .ch2 .ch3 .ch4
open eq prod unit bool sum sigma ua funext nat lift
/- ************************************** -/
/- Miscellaneous results -/
/- ************************************** -/
-- Contractability:
-- Every contractable type A induce a contractible path A=A:
definition contr_implies_loop_contr :
isContr(A) → isContr(A = A) :=
λ H, ⟨ refl A,
λ p, ua_refl ⬝ ap ua
(show typeq_refl A = idtoeqv p, from
sigma_eq ⟨funext (λ x, ((pr2 H) x)⁻¹ ⬝ (pr2 H) (pr1 (idtoeqv p) x) ) ,
(biinv_is_prop (pr1 (idtoeqv p))) _ (pr2 (idtoeqv p)) ⟩)
⬝ (ua_uniq p) ⟩
-- Every path type of a contractible type is contractible:
definition contr_implies_paths_contr :
isContr(A) → Π (x y : A), isContr(x = y) :=
λ H, λ x y, ⟨ ((pr2 H) x)⁻¹ ⬝ (pr2 H) y , λ p, eq.rec_on p (left_inv _) ⟩
--
|
61975906d6faf16e720b094b429be27a4cbbbfde | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /tests/lean/mvar2.lean | 43e7ac144f162b97a625f6dcf14a6e60a79700e3 | [
"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 | 1,435 | lean | import Lean.MetavarContext
open Lean
def check (b : Bool) : IO Unit :=
«unless» b (throw $ IO.userError "error")
def f := mkConst `f []
def g := mkConst `g []
def a := mkConst `a []
def b := mkConst `b []
def c := mkConst `c []
def b0 := mkBVar 0
def b1 := mkBVar 1
def b2 := mkBVar 2
def u := mkLevelParam `u
def typeE := mkSort levelOne
def natE := mkConst `Nat []
def boolE := mkConst `Bool []
def vecE := mkConst `Vec [levelZero]
def α := mkFVar `α
def x := mkFVar `x
def y := mkFVar `y
def z := mkFVar `z
def w := mkFVar `w
def m1 := mkMVar `m1
def m2 := mkMVar `m2
def m3 := mkMVar `m3
def bi := BinderInfo.default
def arrow (d b : Expr) := mkForall `_ bi d b
def lctx1 : LocalContext := {}
def lctx2 := lctx1.mkLocalDecl `α `α typeE
def lctx3 := lctx2.mkLocalDecl `x `x m1
def lctx4 := lctx3.mkLocalDecl `y `y (arrow natE (mkAppN m3 #[α, x]))
def mctx1 : MetavarContext := {}
def mctx2 := mctx1.addExprMVarDecl `m1 `m1 lctx1 #[] typeE
def mctx3 := mctx2.addExprMVarDecl `m2 `m2 lctx3 #[] natE
def mctx4 := mctx3.addExprMVarDecl `m3 `m3 lctx1 #[] (arrow typeE (arrow natE natE))
def mctx5 := mctx4.assignDelayed `m3 lctx3 #[α, x] m2
def mctx6 := mctx5.assignExpr `m2 (arrow α α)
def mctx7 := mctx6.assignExpr `m1 natE
def t2 := lctx4.mkLambda #[α, x, y] $ mkAppN f #[mkAppN m3 #[α, x], x]
#eval check (!t2.hasFVar)
#eval t2
#eval (mctx6.instantiateMVars t2).1
#eval (mctx7.instantiateMVars t2).1
|
2b0acd66329e33e1787f7265e2b8fa6e77728572 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/measure_theory/function/ess_sup.lean | 1f8e498fb7586b8e0b41768648f3b835d2022e92 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 9,959 | 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.constructions.borel_space
import order.filter.ennreal
/-!
# Essential supremum and infimum
We define the essential supremum and infimum of a function `f : α → β` with respect to a measure
`μ` on `α`. The essential supremum is the infimum of the constants `c : β` such that `f x ≤ c`
almost everywhere.
TODO: The essential supremum of functions `α → ℝ≥0∞` is used in particular to define the norm in
the `L∞` space (see measure_theory/lp_space.lean).
There is a different quantity which is sometimes also called essential supremum: the least
upper-bound among measurable functions of a family of measurable functions (in an almost-everywhere
sense). We do not define that quantity here, which is simply the supremum of a map with values in
`α →ₘ[μ] β` (see measure_theory/ae_eq_fun.lean).
## Main definitions
* `ess_sup f μ := μ.ae.limsup f`
* `ess_inf f μ := μ.ae.liminf f`
-/
open measure_theory filter topological_space
open_locale ennreal measure_theory
variables {α β : Type*} {m : measurable_space α} {μ ν : measure α}
section conditionally_complete_lattice
variable [conditionally_complete_lattice β]
/-- Essential supremum of `f` with respect to measure `μ`: the smallest `c : β` such that
`f x ≤ c` a.e. -/
def ess_sup {m : measurable_space α} (f : α → β) (μ : measure α) := μ.ae.limsup f
/-- Essential infimum of `f` with respect to measure `μ`: the greatest `c : β` such that
`c ≤ f x` a.e. -/
def ess_inf {m : measurable_space α} (f : α → β) (μ : measure α) := μ.ae.liminf f
lemma ess_sup_congr_ae {f g : α → β} (hfg : f =ᵐ[μ] g) : ess_sup f μ = ess_sup g μ :=
limsup_congr hfg
lemma ess_inf_congr_ae {f g : α → β} (hfg : f =ᵐ[μ] g) : ess_inf f μ = ess_inf g μ :=
@ess_sup_congr_ae α βᵒᵈ _ _ _ _ _ hfg
end conditionally_complete_lattice
section conditionally_complete_linear_order
variable [conditionally_complete_linear_order β]
lemma ess_sup_eq_Inf {m : measurable_space α} (μ : measure α) (f : α → β) :
ess_sup f μ = Inf {a | μ {x | a < f x} = 0} :=
begin
dsimp [ess_sup, limsup, Limsup],
congr,
ext a,
simp [eventually_map, ae_iff],
end
end conditionally_complete_linear_order
section complete_lattice
variable [complete_lattice β]
@[simp] lemma ess_sup_measure_zero {m : measurable_space α} {f : α → β} :
ess_sup f (0 : measure α) = ⊥ :=
le_bot_iff.mp (Inf_le (by simp [set.mem_set_of_eq, eventually_le, ae_iff]))
@[simp] lemma ess_inf_measure_zero {m : measurable_space α} {f : α → β} :
ess_inf f (0 : measure α) = ⊤ :=
@ess_sup_measure_zero α βᵒᵈ _ _ _
lemma ess_sup_mono_ae {f g : α → β} (hfg : f ≤ᵐ[μ] g) : ess_sup f μ ≤ ess_sup g μ :=
limsup_le_limsup hfg
lemma ess_inf_mono_ae {f g : α → β} (hfg : f ≤ᵐ[μ] g) : ess_inf f μ ≤ ess_inf g μ :=
liminf_le_liminf hfg
lemma ess_sup_const (c : β) (hμ : μ ≠ 0) : ess_sup (λ x : α, c) μ = c :=
begin
haveI hμ_ne_bot : μ.ae.ne_bot, { rwa [ne_bot_iff, ne.def, ae_eq_bot] },
exact limsup_const c,
end
lemma ess_sup_le_of_ae_le {f : α → β} (c : β) (hf : f ≤ᵐ[μ] (λ _, c)) : ess_sup f μ ≤ c :=
begin
refine (ess_sup_mono_ae hf).trans _,
by_cases hμ : μ = 0,
{ simp [hμ], },
{ rwa ess_sup_const, },
end
lemma ess_inf_const (c : β) (hμ : μ ≠ 0) : ess_inf (λ x : α, c) μ = c :=
@ess_sup_const α βᵒᵈ _ _ _ _ hμ
lemma le_ess_inf_of_ae_le {f : α → β} (c : β) (hf : (λ _, c) ≤ᵐ[μ] f) : c ≤ ess_inf f μ :=
@ess_sup_le_of_ae_le α βᵒᵈ _ _ _ _ c hf
lemma ess_sup_const_bot : ess_sup (λ x : α, (⊥ : β)) μ = (⊥ : β) :=
limsup_const_bot
lemma ess_inf_const_top : ess_inf (λ x : α, (⊤ : β)) μ = (⊤ : β) :=
liminf_const_top
lemma order_iso.ess_sup_apply {m : measurable_space α} {γ} [complete_lattice γ]
(f : α → β) (μ : measure α) (g : β ≃o γ) :
g (ess_sup f μ) = ess_sup (λ x, g (f x)) μ :=
begin
refine order_iso.limsup_apply g _ _ _ _,
all_goals { is_bounded_default, },
end
lemma order_iso.ess_inf_apply {m : measurable_space α} {γ} [complete_lattice γ]
(f : α → β) (μ : measure α) (g : β ≃o γ) :
g (ess_inf f μ) = ess_inf (λ x, g (f x)) μ :=
@order_iso.ess_sup_apply α βᵒᵈ _ _ γᵒᵈ _ _ _ g.dual
lemma ess_sup_mono_measure {f : α → β} (hμν : ν ≪ μ) : ess_sup f ν ≤ ess_sup f μ :=
begin
refine limsup_le_limsup_of_le (measure.ae_le_iff_absolutely_continuous.mpr hμν) _ _,
all_goals { is_bounded_default, },
end
lemma ess_sup_mono_measure' {α : Type*} {β : Type*} {m : measurable_space α}
{μ ν : measure_theory.measure α} [complete_lattice β] {f : α → β} (hμν : ν ≤ μ) :
ess_sup f ν ≤ ess_sup f μ := ess_sup_mono_measure (measure.absolutely_continuous_of_le hμν)
lemma ess_inf_antitone_measure {f : α → β} (hμν : μ ≪ ν) : ess_inf f ν ≤ ess_inf f μ :=
begin
refine liminf_le_liminf_of_le (measure.ae_le_iff_absolutely_continuous.mpr hμν) _ _,
all_goals { is_bounded_default, },
end
lemma ess_sup_smul_measure {f : α → β} {c : ℝ≥0∞} (hc : c ≠ 0) :
ess_sup f (c • μ) = ess_sup f μ :=
begin
simp_rw ess_sup,
suffices h_smul : (c • μ).ae = μ.ae, by rw h_smul,
ext1,
simp_rw mem_ae_iff,
simp [hc],
end
section topological_space
variables {γ : Type*} {mγ : measurable_space γ} {f : α → γ} {g : γ → β}
include mγ
lemma ess_sup_comp_le_ess_sup_map_measure (hf : ae_measurable f μ) :
ess_sup (g ∘ f) μ ≤ ess_sup g (measure.map f μ) :=
begin
refine Limsup_le_Limsup_of_le (λ t, _) (by is_bounded_default) (by is_bounded_default),
simp_rw filter.mem_map,
have : (g ∘ f) ⁻¹' t = f ⁻¹' (g ⁻¹' t), by { ext1 x, simp_rw set.mem_preimage, },
rw this,
exact λ h, mem_ae_of_mem_ae_map hf h,
end
lemma _root_.measurable_embedding.ess_sup_map_measure (hf : measurable_embedding f) :
ess_sup g (measure.map f μ) = ess_sup (g ∘ f) μ :=
begin
refine le_antisymm _ (ess_sup_comp_le_ess_sup_map_measure hf.measurable.ae_measurable),
refine Limsup_le_Limsup (by is_bounded_default) (by is_bounded_default) (λ c h_le, _),
rw eventually_map at h_le ⊢,
exact hf.ae_map_iff.mpr h_le,
end
variables [measurable_space β] [topological_space β] [second_countable_topology β]
[order_closed_topology β] [opens_measurable_space β]
lemma ess_sup_map_measure_of_measurable (hg : measurable g) (hf : ae_measurable f μ) :
ess_sup g (measure.map f μ) = ess_sup (g ∘ f) μ :=
begin
refine le_antisymm _ (ess_sup_comp_le_ess_sup_map_measure hf),
refine Limsup_le_Limsup (by is_bounded_default) (by is_bounded_default) (λ c h_le, _),
rw eventually_map at h_le ⊢,
rw ae_map_iff hf (measurable_set_le hg measurable_const),
exact h_le,
end
lemma ess_sup_map_measure (hg : ae_measurable g (measure.map f μ)) (hf : ae_measurable f μ) :
ess_sup g (measure.map f μ) = ess_sup (g ∘ f) μ :=
begin
rw [ess_sup_congr_ae hg.ae_eq_mk, ess_sup_map_measure_of_measurable hg.measurable_mk hf],
refine ess_sup_congr_ae _,
have h_eq := ae_of_ae_map hf hg.ae_eq_mk,
rw ← eventually_eq at h_eq,
exact h_eq.symm,
end
omit mγ
end topological_space
end complete_lattice
section complete_linear_order
variable [complete_linear_order β]
lemma ae_lt_of_ess_sup_lt {f : α → β} {x : β} (hf : ess_sup f μ < x) : ∀ᵐ y ∂μ, f y < x :=
filter.eventually_lt_of_limsup_lt hf
lemma ae_lt_of_lt_ess_inf {f : α → β} {x : β} (hf : x < ess_inf f μ) : ∀ᵐ y ∂μ, x < f y :=
@ae_lt_of_ess_sup_lt α βᵒᵈ _ _ _ _ _ hf
lemma ess_sup_indicator_eq_ess_sup_restrict [has_zero β] {s : set α}
{f : α → β} (hf : 0 ≤ᵐ[μ.restrict s] f) (hs : measurable_set s) (hs_not_null : μ s ≠ 0) :
ess_sup (s.indicator f) μ = ess_sup f (μ.restrict s) :=
begin
refine le_antisymm _ (Limsup_le_Limsup_of_le (map_restrict_ae_le_map_indicator_ae hs)
(by is_bounded_default) (by is_bounded_default)),
refine Limsup_le_Limsup (by is_bounded_default) (by is_bounded_default) (λ c h_restrict_le, _),
rw eventually_map at h_restrict_le ⊢,
rw ae_restrict_iff' hs at h_restrict_le,
have hc : 0 ≤ c,
{ rsuffices ⟨x, hx⟩ : ∃ x, 0 ≤ f x ∧ f x ≤ c, from hx.1.trans hx.2,
refine frequently.exists _,
{ exact μ.ae, },
rw [eventually_le, ae_restrict_iff' hs] at hf,
have hs' : ∃ᵐ x ∂μ, x ∈ s,
{ contrapose! hs_not_null,
rw [not_frequently, ae_iff] at hs_not_null,
suffices : {a : α | ¬a ∉ s} = s, by rwa ← this,
simp, },
refine hs'.mp (hf.mp (h_restrict_le.mono (λ x hxs_imp_c hxf_nonneg hxs, _))),
rw pi.zero_apply at hxf_nonneg,
exact ⟨hxf_nonneg hxs, hxs_imp_c hxs⟩, },
refine h_restrict_le.mono (λ x hxc, _),
by_cases hxs : x ∈ s,
{ simpa [hxs] using hxc hxs, },
{ simpa [hxs] using hc, },
end
end complete_linear_order
namespace ennreal
variables {f : α → ℝ≥0∞}
lemma ae_le_ess_sup (f : α → ℝ≥0∞) : ∀ᵐ y ∂μ, f y ≤ ess_sup f μ :=
eventually_le_limsup f
@[simp] lemma ess_sup_eq_zero_iff : ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 :=
limsup_eq_zero_iff
lemma ess_sup_const_mul {a : ℝ≥0∞} : ess_sup (λ (x : α), a * (f x)) μ = a * ess_sup f μ :=
limsup_const_mul
lemma ess_sup_mul_le (f g : α → ℝ≥0∞) : ess_sup (f * g) μ ≤ ess_sup f μ * ess_sup g μ :=
limsup_mul_le f g
lemma ess_sup_add_le (f g : α → ℝ≥0∞) : ess_sup (f + g) μ ≤ ess_sup f μ + ess_sup g μ :=
limsup_add_le f g
lemma ess_sup_liminf_le {ι} [countable ι] [linear_order ι] (f : ι → α → ℝ≥0∞) :
ess_sup (λ x, at_top.liminf (λ n, f n x)) μ ≤ at_top.liminf (λ n, ess_sup (λ x, f n x) μ) :=
by { simp_rw ess_sup, exact ennreal.limsup_liminf_le_liminf_limsup (λ a b, f b a), }
end ennreal
|
099f18ba4aa58d656724183eb66a9f4784d4f1c4 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/continued_fractions/computation/approximation_corollaries.lean | 1c0e022f378cc8be506b775c636eb49ec043888d | [
"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 | 6,595 | lean | /-
Copyright (c) 2021 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import algebra.continued_fractions.computation.approximations
import algebra.continued_fractions.convergents_equiv
import topology.algebra.ordered.basic
/-!
# Corollaries From Approximation Lemmas (`algebra.continued_fractions.computation.approximations`)
## Summary
We show that the generalized_continued_fraction given by `generalized_continued_fraction.of` in fact
is a (regular) continued fraction. Using the equivalence of the convergents computations
(`generalized_continued_fraction.convergents` and `generalized_continued_fraction.convergents'`) for
continued fractions (see `algebra.continued_fractions.convergents_equiv`), it follows that the
convergents computations for `generalized_continued_fraction.of` are equivalent.
Moreover, we show the convergence of the continued fractions computations, that is
`(generalized_continued_fraction.of v).convergents` indeed computes `v` in the limit.
## Main Definitions
- `continued_fraction.of` returns the (regular) continued fraction of a value.
## Main Theorems
- `generalized_continued_fraction.of_convergents_eq_convergents'` shows that the convergents
computations for `generalized_continued_fraction.of` are equivalent.
- `generalized_continued_fraction.of_convergence` shows that
`(generalized_continued_fraction.of v).convergents` converges to `v`.
## Tags
convergence, fractions
-/
variables {K : Type*} (v : K) [linear_ordered_field K] [floor_ring K]
open generalized_continued_fraction as gcf
lemma generalized_continued_fraction.of_is_simple_continued_fraction :
(gcf.of v).is_simple_continued_fraction :=
(λ _ _ nth_part_num_eq, gcf.of_part_num_eq_one nth_part_num_eq)
/-- Creates the simple continued fraction of a value. -/
def simple_continued_fraction.of : simple_continued_fraction K :=
⟨gcf.of v, generalized_continued_fraction.of_is_simple_continued_fraction v⟩
lemma simple_continued_fraction.of_is_continued_fraction :
(simple_continued_fraction.of v).is_continued_fraction :=
(λ _ denom nth_part_denom_eq,
lt_of_lt_of_le zero_lt_one(gcf.of_one_le_nth_part_denom nth_part_denom_eq))
/-- Creates the continued fraction of a value. -/
def continued_fraction.of : continued_fraction K :=
⟨simple_continued_fraction.of v, simple_continued_fraction.of_is_continued_fraction v⟩
namespace generalized_continued_fraction
open continued_fraction as cf
lemma of_convergents_eq_convergents' : (gcf.of v).convergents = (gcf.of v).convergents' :=
@cf.convergents_eq_convergents' _ _ (continued_fraction.of v)
section convergence
/-!
### Convergence
We next show that `(generalized_continued_fraction.of v).convergents v` converges to `v`.
-/
variable [archimedean K]
local notation `|` x `|` := abs x
open nat
theorem of_convergence_epsilon :
∀ (ε > (0 : K)), ∃ (N : ℕ), ∀ (n ≥ N), |v - (gcf.of v).convergents n| < ε :=
begin
assume ε ε_pos,
-- use the archimedean property to obtian a suitable N
rcases (exists_nat_gt (1 / ε) : ∃ (N' : ℕ), 1 / ε < N') with ⟨N', one_div_ε_lt_N'⟩,
let N := max N' 5, -- set minimum to 5 to have N ≤ fib N work
existsi N,
assume n n_ge_N,
let g := gcf.of v,
cases decidable.em (g.terminated_at n) with terminated_at_n not_terminated_at_n,
{ have : v = g.convergents n, from of_correctness_of_terminated_at terminated_at_n,
have : v - g.convergents n = 0, from sub_eq_zero.elim_right this,
rw [this],
exact_mod_cast ε_pos },
{ let B := g.denominators n,
let nB := g.denominators (n + 1),
have abs_v_sub_conv_le : |v - g.convergents n| ≤ 1 / (B * nB), from
abs_sub_convergents_le not_terminated_at_n,
suffices : 1 / (B * nB) < ε, from lt_of_le_of_lt abs_v_sub_conv_le this,
-- show that `0 < (B * nB)` and then multiply by `B * nB` to get rid of the division
have nB_ineq : (fib (n + 2) : K) ≤ nB, by
{ have : ¬g.terminated_at (n + 1 - 1), from not_terminated_at_n,
exact (succ_nth_fib_le_of_nth_denom (or.inr this)) },
have B_ineq : (fib (n + 1) : K) ≤ B, by
{ have : ¬g.terminated_at (n - 1), from mt (terminated_stable n.pred_le) not_terminated_at_n,
exact (succ_nth_fib_le_of_nth_denom (or.inr this)) },
have zero_lt_B : 0 < B, by
{ have : (0 : K) < fib (n + 1), by exact_mod_cast fib_pos n.zero_lt_succ,
exact (lt_of_lt_of_le this B_ineq) },
have zero_lt_mul_conts : 0 < B * nB, by
{ have : 0 < nB, by
{ have : (0 : K) < fib (n + 2), by exact_mod_cast fib_pos (n + 1).zero_lt_succ,
exact (lt_of_lt_of_le this nB_ineq) },
solve_by_elim [mul_pos] },
suffices : 1 < ε * (B * nB), from (div_lt_iff zero_lt_mul_conts).elim_right this,
-- use that `N ≥ n` was obtained from the archimedean property to show the following
have one_lt_ε_mul_N : 1 < ε * n, by
{ have one_lt_ε_mul_N' : 1 < ε * (N' : K), from (div_lt_iff' ε_pos).elim_left one_div_ε_lt_N',
have : (N' : K) ≤ N, by exact_mod_cast (le_max_left _ _),
have : ε * N' ≤ ε * n, from
(mul_le_mul_left ε_pos).elim_right (le_trans this (by exact_mod_cast n_ge_N)),
exact (lt_of_lt_of_le one_lt_ε_mul_N' this) },
suffices : ε * n ≤ ε * (B * nB), from lt_of_lt_of_le one_lt_ε_mul_N this,
-- cancel `ε`
suffices : (n : K) ≤ B * nB, from (mul_le_mul_left ε_pos).elim_right this,
show (n : K) ≤ B * nB,
calc (n : K)
≤ fib n : by exact_mod_cast (le_fib_self $ le_trans
(le_max_right N' 5) n_ge_N)
... ≤ fib (n + 1) : by exact_mod_cast fib_le_fib_succ
... ≤ fib (n + 1) * fib (n + 1) : by exact_mod_cast ((fib (n + 1)).le_mul_self)
... ≤ fib (n + 1) * fib (n + 2) : mul_le_mul_of_nonneg_left
(by exact_mod_cast fib_le_fib_succ)
(by exact_mod_cast (fib (n + 1)).zero_le)
... ≤ B * nB : mul_le_mul B_ineq nB_ineq
(by exact_mod_cast (fib (n + 2)).zero_le)
(le_of_lt zero_lt_B) }
end
local attribute [instance] preorder.topology
theorem of_convergence [order_topology K] :
filter.tendsto ((gcf.of v).convergents) filter.at_top $ nhds v :=
by simpa [linear_ordered_add_comm_group.tendsto_nhds, abs_sub_comm] using (of_convergence_epsilon v)
end convergence
end generalized_continued_fraction
|
2f48cb3b2c8e57ba9f4856250e7d1814bf26c008 | 737dc4b96c97368cb66b925eeea3ab633ec3d702 | /stage0/src/Lean/Elab/Tactic/BuiltinTactic.lean | 9d2f7ad2524083eadc223addcedcd6199282847e | [
"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 | 10,497 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Tactic.Basic
namespace Lean.Elab.Tactic
open Meta
@[builtinTactic Lean.Parser.Tactic.«done»] def evalDone : Tactic := fun _ =>
done
@[builtinTactic seq1] def evalSeq1 : Tactic := fun stx => do
let args := stx[0].getArgs
for i in [:args.size] do
if i % 2 == 0 then
evalTactic args[i]
else
saveTacticInfoForToken args[i] -- add `TacticInfo` node for `;`
@[builtinTactic paren] def evalParen : Tactic := fun stx =>
evalTactic stx[1]
/- Evaluate `many (group (tactic >> optional ";")) -/
def evalManyTacticOptSemi (stx : Syntax) : TacticM Unit := do
stx.forArgsM fun seqElem => do
evalTactic seqElem[0]
saveTacticInfoForToken seqElem[1] -- add TacticInfo node for `;`
@[builtinTactic tacticSeq1Indented] def evalTacticSeq1Indented : Tactic := fun stx =>
evalManyTacticOptSemi stx[0]
@[builtinTactic tacticSeqBracketed] def evalTacticSeqBracketed : Tactic := fun stx => do
let initInfo ← mkInitialTacticInfo stx[0]
withRef stx[2] <| closeUsingOrAdmit do
-- save state before/after entering focus on `{`
withInfoContext (pure ()) initInfo
evalManyTacticOptSemi stx[1]
@[builtinTactic Parser.Tactic.focus] def evalFocus : Tactic := fun stx => do
let mkInfo ← mkInitialTacticInfo stx[0]
focus do
-- show focused state on `focus`
withInfoContext (pure ()) mkInfo
evalTactic stx[1]
private def getOptRotation (stx : Syntax) : Nat :=
if stx.isNone then 1 else stx[0].toNat
@[builtinTactic Parser.Tactic.rotateLeft] def evalRotateLeft : Tactic := fun stx => do
let n := getOptRotation stx[1]
setGoals <| (← getGoals).rotateLeft n
@[builtinTactic Parser.Tactic.rotateRight] def evalRotateRight : Tactic := fun stx => do
let n := getOptRotation stx[1]
setGoals <| (← getGoals).rotateRight n
@[builtinTactic Parser.Tactic.open] def evalOpen : Tactic := fun stx => do
try
pushScope
let openDecls ← elabOpenDecl stx[1]
withTheReader Core.Context (fun ctx => { ctx with openDecls := openDecls }) do
evalTactic stx[3]
finally
popScope
@[builtinTactic Parser.Tactic.set_option] def elabSetOption : Tactic := fun stx => do
let options ← Elab.elabSetOption stx[1] stx[2]
withTheReader Core.Context (fun ctx => { ctx with maxRecDepth := maxRecDepth.get options, options := options }) do
evalTactic stx[4]
@[builtinTactic Parser.Tactic.allGoals] def evalAllGoals : Tactic := fun stx => do
let mvarIds ← getGoals
let mut mvarIdsNew := #[]
for mvarId in mvarIds do
unless (← isExprMVarAssigned mvarId) do
setGoals [mvarId]
try
evalTactic stx[1]
mvarIdsNew := mvarIdsNew ++ (← getUnsolvedGoals)
catch ex =>
logException ex
mvarIdsNew := mvarIdsNew.push mvarId
setGoals mvarIdsNew.toList
@[builtinTactic Parser.Tactic.anyGoals] def evalAnyGoals : Tactic := fun stx => do
let mvarIds ← getGoals
let mut mvarIdsNew := #[]
let mut succeeded := false
for mvarId in mvarIds do
unless (← isExprMVarAssigned mvarId) do
setGoals [mvarId]
try
evalTactic stx[1]
mvarIdsNew := mvarIdsNew ++ (← getUnsolvedGoals)
succeeded := true
catch _ =>
mvarIdsNew := mvarIdsNew.push mvarId
unless succeeded do
throwError "failed on all goals"
setGoals mvarIdsNew.toList
@[builtinTactic tacticSeq] def evalTacticSeq : Tactic := fun stx =>
evalTactic stx[0]
partial def evalChoiceAux (tactics : Array Syntax) (i : Nat) : TacticM Unit :=
if h : i < tactics.size then
let tactic := tactics.get ⟨i, h⟩
catchInternalId unsupportedSyntaxExceptionId
(evalTactic tactic)
(fun _ => evalChoiceAux tactics (i+1))
else
throwUnsupportedSyntax
@[builtinTactic choice] def evalChoice : Tactic := fun stx =>
evalChoiceAux stx.getArgs 0
@[builtinTactic skip] def evalSkip : Tactic := fun stx => pure ()
@[builtinTactic unknown] def evalUnknown : Tactic := fun stx => do
addCompletionInfo <| CompletionInfo.tactic stx (← getGoals)
@[builtinTactic failIfSuccess] def evalFailIfSuccess : Tactic := fun stx => do
let tactic := stx[1]
if (← try evalTactic tactic; pure true catch _ => pure false) then
throwError "tactic succeeded"
@[builtinTactic traceState] def evalTraceState : Tactic := fun stx => do
let gs ← getUnsolvedGoals
logInfo (goalsToMessageData gs)
@[builtinTactic Lean.Parser.Tactic.assumption] def evalAssumption : Tactic := fun stx =>
liftMetaTactic fun mvarId => do Meta.assumption mvarId; pure []
@[builtinTactic Lean.Parser.Tactic.contradiction] def evalContradiction : Tactic := fun stx =>
liftMetaTactic fun mvarId => do Meta.contradiction mvarId; pure []
@[builtinTactic Lean.Parser.Tactic.intro] def evalIntro : Tactic := fun stx => do
match stx with
| `(tactic| intro) => introStep `_
| `(tactic| intro $h:ident) => introStep h.getId
| `(tactic| intro _) => introStep `_
| `(tactic| intro $pat:term) => evalTactic (← `(tactic| intro h; match h with | $pat:term => ?_; try clear h))
| `(tactic| intro $h:term $hs:term*) => evalTactic (← `(tactic| intro $h:term; intro $hs:term*))
| _ => throwUnsupportedSyntax
where
introStep (n : Name) : TacticM Unit :=
liftMetaTactic fun mvarId => do
let (_, mvarId) ← Meta.intro mvarId n
pure [mvarId]
@[builtinTactic Lean.Parser.Tactic.introMatch] def evalIntroMatch : Tactic := fun stx => do
let matchAlts := stx[1]
let stxNew ← liftMacroM <| Term.expandMatchAltsIntoMatchTactic stx matchAlts
withMacroExpansion stx stxNew <| evalTactic stxNew
@[builtinTactic «intros»] def evalIntros : Tactic := fun stx =>
match stx with
| `(tactic| intros) => liftMetaTactic fun mvarId => do
let (_, mvarId) ← Meta.intros mvarId
return [mvarId]
| `(tactic| intros $ids*) => liftMetaTactic fun mvarId => do
let (_, mvarId) ← Meta.introN mvarId ids.size (ids.map getNameOfIdent').toList
return [mvarId]
| _ => throwUnsupportedSyntax
@[builtinTactic Lean.Parser.Tactic.revert] def evalRevert : Tactic := fun stx =>
match stx with
| `(tactic| revert $hs*) => do
let (_, mvarId) ← Meta.revert (← getMainGoal) (← getFVarIds hs)
replaceMainGoal [mvarId]
| _ => throwUnsupportedSyntax
/- Sort free variables using an order `x < y` iff `x` was defined after `y` -/
private def sortFVarIds (fvarIds : Array FVarId) : TacticM (Array FVarId) :=
withMainContext do
let lctx ← getLCtx
return fvarIds.qsort fun fvarId₁ fvarId₂ =>
match lctx.find? fvarId₁, lctx.find? fvarId₂ with
| some d₁, some d₂ => d₁.index > d₂.index
| some _, none => false
| none, some _ => true
| none, none => Name.quickLt fvarId₁ fvarId₂
@[builtinTactic Lean.Parser.Tactic.clear] def evalClear : Tactic := fun stx =>
match stx with
| `(tactic| clear $hs*) => do
let fvarIds ← getFVarIds hs
let fvarIds ← sortFVarIds fvarIds
for fvarId in fvarIds do
withMainContext do
let mvarId ← clear (← getMainGoal) fvarId
replaceMainGoal [mvarId]
| _ => throwUnsupportedSyntax
def forEachVar (hs : Array Syntax) (tac : MVarId → FVarId → MetaM MVarId) : TacticM Unit := do
for h in hs do
withMainContext do
let fvarId ← getFVarId h
let mvarId ← tac (← getMainGoal) (← getFVarId h)
replaceMainGoal [mvarId]
@[builtinTactic Lean.Parser.Tactic.subst] def evalSubst : Tactic := fun stx =>
match stx with
| `(tactic| subst $hs*) => forEachVar hs Meta.subst
| _ => throwUnsupportedSyntax
/--
First method searches for a metavariable `g` s.t. `tag` is a suffix of its name.
If none is found, then it searches for a metavariable `g` s.t. `tag` is a prefix of its name. -/
private def findTag? (mvarIds : List MVarId) (tag : Name) : TacticM (Option MVarId) := do
let mvarId? ← mvarIds.findM? fun mvarId => return tag.isSuffixOf (← getMVarDecl mvarId).userName
match mvarId? with
| some mvarId => return mvarId
| none => mvarIds.findM? fun mvarId => return tag.isPrefixOf (← getMVarDecl mvarId).userName
def renameInaccessibles (mvarId : MVarId) (hs : Array Syntax) : TacticM MVarId := do
if hs.isEmpty then
return mvarId
else
let mvarDecl ← getMVarDecl mvarId
let mut lctx := mvarDecl.lctx
let mut hs := hs
let n := lctx.numIndices
for i in [:n] do
let j := n - i - 1
match lctx.getAt? j with
| none => pure ()
| some localDecl =>
if localDecl.userName.hasMacroScopes then
let h := hs.back
if h.isIdent then
let newName := h.getId
lctx := lctx.setUserName localDecl.fvarId newName
hs := hs.pop
if hs.isEmpty then
break
unless hs.isEmpty do
logError m!"too many variable names provided"
let mvarNew ← mkFreshExprMVarAt lctx mvarDecl.localInstances mvarDecl.type MetavarKind.syntheticOpaque mvarDecl.userName
assignExprMVar mvarId mvarNew
return mvarNew.mvarId!
@[builtinTactic «case»] def evalCase : Tactic
| stx@`(tactic| case $tag $hs* =>%$arr $tac:tacticSeq) => do
let gs ← getUnsolvedGoals
let g ←
if tag.isIdent then
let tag := tag.getId
let some g ← findTag? gs tag | throwError "tag not found"
pure g
else
getMainGoal
let gs := gs.erase g
let g ← renameInaccessibles g hs
setGoals [g]
let savedTag ← getMVarTag g
setMVarTag g Name.anonymous
try
withCaseRef arr tac do
closeUsingOrAdmit (withTacticInfoContext stx (evalTactic tac))
finally
setMVarTag g savedTag
done
setGoals gs
| _ => throwUnsupportedSyntax
@[builtinTactic «renameI»] def evalRenameInaccessibles : Tactic
| stx@`(tactic| renameI $hs*) => do replaceMainGoal [← renameInaccessibles (← getMainGoal) hs]
| _ => throwUnsupportedSyntax
@[builtinTactic «first»] partial def evalFirst : Tactic := fun stx => do
let tacs := stx[1].getArgs
if tacs.isEmpty then throwUnsupportedSyntax
loop tacs 0
where
loop (tacs : Array Syntax) (i : Nat) :=
if i == tacs.size - 1 then
evalTactic tacs[i][1]
else
evalTactic tacs[i][1] <|> loop tacs (i+1)
end Lean.Elab.Tactic
|
0b6ebb0a51e913267538f7832d1aa61e05bb4c3a | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/iffRefl.lean | 6a204696dba58f56f7dcdeb503b5e2f1e46c458c | [
"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 | 162 | lean | macro_rules | `(tactic| rfl) => `(tactic| exact Iff.rfl)
theorem r (A : Prop) : A ↔ A := by rfl
theorem s (A B : Prop) (h : A ↔ B) : B ↔ A := by
rw [h]
|
f06308f16aff101cdc27ebcf8d11bea8ac72b2d4 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /tests/lean/interactive/hover.lean | 6d2011b89b8ad335fa09337830201706fbaf40cd | [
"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 | 1,931 | lean | import Lean
example : True := by
apply True.intro
--^ textDocument/hover
example : True := by
simp [True.intro]
--^ textDocument/hover
example (n : Nat) : True := by
match n with
| Nat.zero => _
--^ textDocument/hover
| n + 1 => _
/-- My tactic -/
macro "mytac" o:("only"?) e:term : tactic => `(exact $e)
example : True := by
mytac only True.intro
--^ textDocument/hover
--^ textDocument/hover
--^ textDocument/hover
/-- My way better tactic -/
macro_rules
| `(tactic| mytac $[only]? $e) => `(apply $e)
example : True := by
mytac only True.intro
--^ textDocument/hover
/-- My ultimate tactic -/
elab_rules : tactic
| `(tactic| mytac $[only]? $e) => `(tactic| refine $e) >>= Lean.Elab.Tactic.evalTactic
example : True := by
mytac only True.intro
--^ textDocument/hover
/-- My notation -/
macro "mynota" e:term : term => e
#check mynota 1
--^ textDocument/hover
/-- My way better notation -/
macro_rules
| `(mynota $e) => `(2 * $e)
#check mynota 1
--^ textDocument/hover
-- macro_rules take precedence over elab_rules for term/command, so use new syntax
syntax "mynota'" term : term
/-- My ultimate notation -/
elab_rules : term
| `(mynota' $e) => `($e * $e) >>= (Lean.Elab.Term.elabTerm · none)
#check mynota' 1
--^ textDocument/hover
/-- My command -/
macro "mycmd" e:term : command => `(def hi := $e)
mycmd 1
--^ textDocument/hover
/-- My way better command -/
macro_rules
| `(mycmd $e) => `(@[inline] def hi := $e)
mycmd 1
--^ textDocument/hover
syntax "mycmd'" term : command
/-- My ultimate command -/
elab_rules : command
| `(mycmd' $e) => `(/-- hi -/ @[inline] def hi := $e) >>= Lean.Elab.Command.elabCommand
mycmd' 1
--^ textDocument/hover
#check ({ a := }) -- should not show `sorry`
--^ textDocument/hover
example : True := by
simp [id True.intro]
--^ textDocument/hover
--^ textDocument/hover
|
8b9c08d88990a2b09417f0d4e3679ee4eae29a1c | 66a6486e19b71391cc438afee5f081a4257564ec | /homotopy/join_theorem.hlean | 6185190799693f34f6ebf5e3c0ac1eafb7e3dd27 | [
"Apache-2.0"
] | permissive | spiceghello/Spectral | c8ccd1e32d4b6a9132ccee20fcba44b477cd0331 | 20023aa3de27c22ab9f9b4a177f5a1efdec2b19f | refs/heads/master | 1,611,263,374,078 | 1,523,349,717,000 | 1,523,349,717,000 | 92,312,239 | 0 | 0 | null | 1,495,642,470,000 | 1,495,642,470,000 | null | UTF-8 | Lean | false | false | 1,960 | hlean | /-- Authors: Clive, Egbert --/
import homotopy.connectedness homotopy.join
open eq sigma pi function join is_conn is_trunc equiv is_equiv
namespace retraction
variables {A B C : Type} (r2 : B → C) (r1 : A → B)
definition is_retraction_compose
[Hr2 : is_retraction r2] [Hr1 : is_retraction r1] :
is_retraction (r2 ∘ r1) :=
begin
cases Hr2 with s2 s2_is_right_inverse,
cases Hr1 with s1 s1_is_right_inverse,
fapply is_retraction.mk,
{ exact s1 ∘ s2},
{ intro b, esimp,
calc
r2 (r1 (s1 (s2 (b)))) = r2 (s2 (b)) : ap r2 (s1_is_right_inverse (s2 b))
... = b : s2_is_right_inverse b
}, /-- QED --/
end
definition is_retraction_compose_equiv_left [Hr2 : is_equiv r2] [Hr1 : is_retraction r1] : is_retraction (r2 ∘ r1) :=
begin
apply is_retraction_compose,
end
definition is_retraction_compose_equiv_right [Hr2 : is_retraction r2] [Hr1 : is_equiv r1] : is_retraction (r2 ∘ r1) :=
begin
apply is_retraction_compose,
end
end retraction
namespace is_conn
section
open retraction
universe variable u
parameters (n : ℕ₋₂) {A : Type.{u}}
parameter sec : ΠV : trunctype.{u} n,
is_retraction (const A : V → (A → V))
include sec
protected definition intro : is_conn n A :=
begin
apply is_conn_of_map_to_unit,
apply is_conn_fun.intro,
intro P,
refine is_retraction_compose_equiv_right (const A) (pi_unit_left P),
end
end
end is_conn
section Join_Theorem
variables (X Y : Type)
(m n : ℕ₋₂)
[HXm : is_conn m X]
[HYn : is_conn n Y]
include HXm HYn
theorem is_conn_join : is_conn (m +2+ n) (join X Y) :=
begin
apply is_conn.intro,
intro V,
apply is_retraction_of_is_equiv,
apply is_equiv_of_is_contr_fun,
intro f,
refine is_contr_equiv_closed _,
{exact unit},
symmetry,
exact sorry
end
end Join_Theorem
|
d6c17daa57f99d72eda2a22f17644fde129d2d7f | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/diag.lean | 730a5610077479376d4ebf731d2d40c82f01d04c | [
"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 | 557 | lean | import data.examples.vector
open nat
namespace vector
definition diag {A} {n} : vector (vector A n) n → vector A n :=
nat.rec_on n
(λv, nil)
(λn₁ (r : vector (vector A n₁) n₁ → vector A n₁) (v : vector (vector A (succ n₁)) (succ n₁)),
let h₁ : A := head (head v) in
let t₁ : vector (vector A n₁) n₁ := map tail (tail v) in
h₁ :: r t₁)
example : diag ((1 :: 2 :: 3 :: nil) :: (4 :: 5 :: 6 :: nil) :: (7 :: 8 :: 9 :: nil) :: nil) = (1 :: 5 :: 9 :: nil : vector num 3) :=
rfl
end vector
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.