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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c51fcb87a97ca4927c48c77912333ae4cc8f091d | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/group_theory/quotient_group.lean | 6a7a0ef712eadae4bf5a14e6868cc4c2f8b92093 | [
"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 | 7,383 | lean | /-
Copyright (c) 2018 Kevin Buzzard and Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Patrick Massot.
This file is to a certain extent based on `quotient_module.lean` by Johannes Hölzl.
-/
import group_theory.coset
universes u v
namespace quotient_group
variables {G : Type u} [group G] (N : subgroup G) [nN : N.normal] {H : Type v} [group H]
include nN
@[to_additive quotient_add_group.add_group]
instance : group (quotient N) :=
{ one := (1 : G),
mul := quotient.map₂' (*)
(λ a₁ b₁ hab₁ a₂ b₂ hab₂,
((N.mul_mem_cancel_right (N.inv_mem hab₂)).1
(by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹),
mul_assoc _ b₂, ← mul_assoc b₂, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)];
exact nN.conj_mem _ hab₁ _))),
mul_assoc := λ a b c, quotient.induction_on₃' a b c
(λ a b c, congr_arg mk (mul_assoc a b c)),
one_mul := λ a, quotient.induction_on' a
(λ a, congr_arg mk (one_mul a)),
mul_one := λ a, quotient.induction_on' a
(λ a, congr_arg mk (mul_one a)),
inv := λ a, quotient.lift_on' a (λ a, ((a⁻¹ : G) : quotient N))
(λ a b hab, quotient.sound' begin
show a⁻¹⁻¹ * b⁻¹ ∈ N,
rw ← mul_inv_rev,
exact N.inv_mem (nN.mem_comm hab)
end),
mul_left_inv := λ a, quotient.induction_on' a
(λ a, congr_arg mk (mul_left_inv a)) }
/-- The group homomorphism from `G` to `G/N`. -/
@[to_additive quotient_add_group.mk' "The additive group homomorphism from `G` to `G/N`."]
def mk' : G →* quotient N := monoid_hom.mk' (quotient_group.mk) (λ _ _, rfl)
@[simp, to_additive quotient_add_group.ker_mk]
lemma ker_mk :
monoid_hom.ker (quotient_group.mk' N : G →* quotient_group.quotient N) = N :=
begin
ext g,
rw [monoid_hom.mem_ker, eq_comm],
show (((1 : G) : quotient_group.quotient N)) = g ↔ _,
rw [quotient_group.eq, one_inv, one_mul],
end
-- for commutative groups we don't need normality assumption
omit nN
@[to_additive quotient_add_group.add_comm_group]
instance {G : Type*} [comm_group G] (N : subgroup G) : comm_group (quotient N) :=
{ mul_comm := λ a b, quotient.induction_on₂' a b
(λ a b, congr_arg mk (mul_comm a b)),
..@quotient_group.group _ _ N N.normal_of_comm }
include nN
@[simp, to_additive quotient_add_group.coe_zero]
lemma coe_one : ((1 : G) : quotient N) = 1 := rfl
@[simp, to_additive quotient_add_group.coe_add]
lemma coe_mul (a b : G) : ((a * b : G) : quotient N) = a * b := rfl
@[simp, to_additive quotient_add_group.coe_neg]
lemma coe_inv (a : G) : ((a⁻¹ : G) : quotient N) = a⁻¹ := rfl
@[simp] lemma coe_pow (a : G) (n : ℕ) : ((a ^ n : G) : quotient N) = a ^ n :=
(mk' N).map_pow a n
@[simp] lemma coe_gpow (a : G) (n : ℤ) : ((a ^ n : G) : quotient N) = a ^ n :=
(mk' N).map_gpow a n
local notation ` Q ` := quotient N
/-- A group homomorphism `φ : G →* H` with `N ⊆ ker(φ)` descends (i.e. `lift`s) to a
group homomorphism `G/N →* H`. -/
@[to_additive quotient_add_group.lift "An `add_group` homomorphism `φ : G →+ H` with `N ⊆ ker(φ)`
descends (i.e. `lift`s) to a group homomorphism `G/N →* H`."]
def lift (φ : G →* H) (HN : ∀x∈N, φ x = 1) : Q →* H :=
monoid_hom.mk'
(λ q : Q, q.lift_on' φ $ assume a b (hab : a⁻¹ * b ∈ N),
(calc φ a = φ a * 1 : (mul_one _).symm
... = φ a * φ (a⁻¹ * b) : HN (a⁻¹ * b) hab ▸ rfl
... = φ (a * (a⁻¹ * b)) : (is_mul_hom.map_mul φ a (a⁻¹ * b)).symm
... = φ b : by rw mul_inv_cancel_left))
(λ q r, quotient.induction_on₂' q r $ is_mul_hom.map_mul φ)
@[simp, to_additive quotient_add_group.lift_mk]
lemma lift_mk {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) :
lift N φ HN (g : Q) = φ g := rfl
@[simp, to_additive quotient_add_group.lift_mk']
lemma lift_mk' {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) :
lift N φ HN (mk g : Q) = φ g := rfl
/-- A group homomorphism `f : G →* H` induces a map `G/N →* H/M` if `N ⊆ f⁻¹(M)`. -/
@[to_additive quotient_add_group.map "An `add_group` homomorphism `f : G →+ H` induces a map
`G/N →+ H/M` if `N ⊆ f⁻¹(M)`."]
def map (M : subgroup H) [M.normal] (f : G →* H) (h : N ≤ M.comap f) :
quotient N →* quotient M :=
begin
refine quotient_group.lift N ((mk' M).comp f) _,
assume x hx,
refine quotient_group.eq.2 _,
rw [mul_one, subgroup.inv_mem_iff],
exact h hx,
end
omit nN
variables (φ : G →* H)
open function monoid_hom
/-- The induced map from the quotient by the kernel to the codomain. -/
@[to_additive quotient_add_group.ker_lift "The induced map from the quotient by the kernel to the
codomain."]
def ker_lift : quotient (ker φ) →* H :=
lift _ φ $ λ g, φ.mem_ker.mp
@[simp, to_additive quotient_add_group.ker_lift_mk]
lemma ker_lift_mk (g : G) : (ker_lift φ) g = φ g :=
lift_mk _ _ _
@[simp, to_additive quotient_add_group.ker_lift_mk']
lemma ker_lift_mk' (g : G) : (ker_lift φ) (mk g) = φ g :=
lift_mk' _ _ _
@[to_additive quotient_add_group.injective_ker_lift]
lemma ker_lift_injective : injective (ker_lift φ) :=
assume a b, quotient.induction_on₂' a b $
assume a b (h : φ a = φ b), quotient.sound' $
show a⁻¹ * b ∈ ker φ, by rw [mem_ker,
is_mul_hom.map_mul φ, ← h, is_group_hom.map_inv φ, inv_mul_self]
-- Note that ker φ isn't definitionally ker (to_range φ)
-- so there is a bit of annoying code duplication here
/-- The induced map from the quotient by the kernel to the range. -/
@[to_additive quotient_add_group.range_ker_lift "The induced map from the quotient by the kernel to
the range."]
def range_ker_lift : quotient (ker φ) →* φ.range :=
lift _ (to_range φ) $ λ g hg, (mem_ker _).mp $ by rwa to_range_ker
@[to_additive quotient_add_group.range_ker_lift_injective]
lemma range_ker_lift_injective : injective (range_ker_lift φ) :=
assume a b, quotient.induction_on₂' a b $
assume a b (h : to_range φ a = to_range φ b), quotient.sound' $
show a⁻¹ * b ∈ ker φ, by rw [←to_range_ker, mem_ker,
is_mul_hom.map_mul (to_range φ), ← h, is_group_hom.map_inv (to_range φ), inv_mul_self]
@[to_additive quotient_add_group.range_ker_lift_surjective]
lemma range_ker_lift_surjective : surjective (range_ker_lift φ) :=
begin
rintro ⟨_, g, rfl⟩,
use mk g,
refl,
end
/-- The first isomorphism theorem (a definition): the canonical isomorphism between
`G/(ker φ)` to `range φ`. -/
@[to_additive quotient_add_group.quotient_ker_equiv_range "The first isomorphism theorem
(a definition): the canonical isomorphism between `G/(ker φ)` to `range φ`."]
noncomputable def quotient_ker_equiv_range : (quotient (ker φ)) ≃* range φ :=
mul_equiv.of_bijective (range_ker_lift φ) ⟨range_ker_lift_injective φ, range_ker_lift_surjective φ⟩
/-- The canonical isomorphism `G/(ker φ) ≃* H` induced by a surjection `φ : G →* H`. -/
@[to_additive quotient_add_group.quotient_ker_equiv_of_surjective "The canonical isomorphism
`G/(ker φ) ≃+ H` induced by a surjection `φ : G →+ H`."]
noncomputable def quotient_ker_equiv_of_surjective (hφ : function.surjective φ) :
(quotient (ker φ)) ≃* H :=
mul_equiv.of_bijective (ker_lift φ) ⟨ker_lift_injective φ, λ h, begin
rcases hφ h with ⟨g, rfl⟩,
use mk g,
refl
end⟩
end quotient_group
|
6920243b1b40dc39f2633eb9d1642629d97b8f12 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/algebra/group/to_additive.lean | c6ac817ffa3915166615a4a32dbb097f355cc9ff | [
"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 | 9,882 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Yury Kudryashov.
-/
import tactic.basic tactic.transform_decl tactic.algebra
/-!
# Transport multiplicative to additive
This file defines an attribute `to_additive` that can be used to
automatically transport theorems and definitions (but not inductive
types and structures) from multiplicative theory to additive theory.
To use this attribute, just write
```
@[to_additive]
theorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm
```
This code will generate a theorem named `add_comm'`. It is also
possible to manually specify the name of the new declaration, and
provide a documentation string.
The transport tries to do the right thing in most cases using several
heuristics described below. However, in some cases it fails, and
requires manual intervention.
## Implementation notes
### Handling of hidden definitions
Before transporting the “main” declaration `src`, `to_additive` first
scans its type and value for names starting with `src`, and transports
them. This includes auxiliary definitions like `src._match_1`,
`src._proof_1`.
After transporting the “main” declaration, `to_additive` transports
its equational lemmas.
### Structure fields and constructors
If `src` is a structure, then `to_additive` automatically adds
structure fields to its mapping, and similarly for constructors of
inductive types.
For new structures this means that `to_additive` automatically handles
coercions, and for old structures it does the same, if ancestry
information is present in `@[ancestor]` attributes.
### Name generation
* If `@[to_additive]` is called without a `name` argument, then the
new name is autogenerated. First, it takes the longest prefix of
the source name that is already known to `to_additive`, and replaces
this prefix with its additive counterpart. Second, it takes the last
part of the name (i.e., after the last dot), and replaces common
name parts (“mul”, “one”, “inv”, “prod”) with their additive versions.
* If `@[to_additive]` is called with a `name` argument `new_name`
/without a dot/, then `to_additive` updates the prefix as described
above, then replaces the last part of the name with `new_name`.
* If `@[to_additive]` is called with a `name` argument
`new_namespace.new_name` /with a dot/, then `to_additive` uses this
new name as is.
As a safety check, in the first two cases `to_additive` double checks
that the new name differs from the original one.
### Missing features
* Automatically transport structures and other inductive types.
* Handle `protected` attribute. Currently all new definitions are public.
* For structures, automatically generate theorems like `group α ↔
add_group (additive α)`.
* Mapping of prefixes that do not correspond to any definition, see
`quotient_group`.
* Rewrite rules for the last part of the name that work in more
cases. E.g., we can replace `monoid` with `add_monoid` etc.
-/
namespace to_additive
open tactic exceptional
@[user_attribute]
meta def aux_attr : user_attribute (name_map name) name :=
{ name := `to_additive_aux,
descr := "Auxiliary attribute for `to_additive`. DON'T USE IT",
cache_cfg := ⟨λ ns,
ns.mfoldl
(λ dict n',
let n := match n' with
| name.mk_string s pre := if s = "_to_additive" then pre else n'
| _ := n'
end
in dict.insert n <$> aux_attr.get_param n')
mk_name_map, []⟩,
parser := lean.parser.ident }
meta def map_namespace (src tgt : name) : command :=
do let n := src.mk_string "_to_additive",
let decl := declaration.thm n [] `(unit) (pure (reflect ())),
add_decl decl,
aux_attr.set n tgt tt
@[derive has_reflect, derive inhabited]
structure value_type := (tgt : name) (doc : option string)
/-- Dictionary of words used by `to_additive.guess_name` to autogenerate
names. -/
meta def tokens_dict : native.rb_map string string :=
native.rb_map.of_list $
[("mul", "add"), ("one", "zero"), ("inv", "neg"), ("prod", "sum")]
/-- Autogenerate target name for `to_additive`. -/
meta def guess_name : string → string :=
string.map_tokens '_' $ list.map $
string.map_tokens ''' $ list.map $
λ s, (tokens_dict.find s).get_or_else s
meta def target_name (src tgt : name) (dict : name_map name) : tactic name :=
(if tgt.get_prefix ≠ name.anonymous -- `tgt` is a full name
then pure tgt
else match src with
| (name.mk_string s pre) :=
do let tgt_auto := guess_name s,
guard (tgt.to_string ≠ tgt_auto)
<|> trace ("`to_additive " ++ src.to_string ++ "`: remove `name` argument"),
pure $ name.mk_string
(if tgt = name.anonymous then tgt_auto else tgt.to_string)
(pre.map_prefix dict.find)
| _ := fail ("to_additive: can't transport " ++ src.to_string)
end) >>=
(λ res,
if res = src
then fail ("to_additive: can't transport " ++ src.to_string ++ " to itself")
else pure res)
meta def parser : lean.parser value_type :=
do
tgt ← optional lean.parser.ident,
e ← optional interactive.types.texpr,
doc ← match e with
| some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string)
| none := pure none
end,
return ⟨tgt.get_or_else name.anonymous, doc⟩
private meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) :
command :=
do
src_fields ← f src,
tgt_fields ← f tgt,
guard (src_fields.length = tgt_fields.length) <|>
fail ("Failed to map fields of " ++ src.to_string),
(src_fields.zip tgt_fields).mmap' $
λ names, guard (names.fst = names.snd) <|>
aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio
meta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command :=
let aux := proceed_fields_aux src tgt prio in
do
aux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >>
aux (λ n, (list.map (λ (x : name), "to_" ++ x.to_string) <$>
(ancestor_attr.get_param n <|> pure []))) >>
aux (λ n, (env.constructors_of n).mmap $
λ cs, match cs with
| (name.mk_string s pre) :=
(guard (pre = n) <|> fail "Bad constructor name") >>
pure s
| _ := fail "Bad constructor name"
end)
@[user_attribute]
protected meta def attr : user_attribute unit value_type :=
{ name := `to_additive,
descr := "Transport multiplicative to additive",
parser := parser,
after_set := some $ λ src prio persistent, do
guard persistent <|> fail "`to_additive` can't be used as a local attribute",
env ← get_env,
val ← attr.get_param src,
dict ← aux_attr.get_cache,
tgt ← target_name src val.tgt dict,
aux_attr.set src tgt tt,
let dict := dict.insert src tgt,
if env.contains tgt
then proceed_fields env src tgt prio
else do
transform_decl_with_prefix_dict dict src tgt
[`reducible, `simp, `instance, `refl, `symm, `trans, `elab_as_eliminator],
match val.doc with
| some doc := add_doc_string tgt doc
| none := skip
end }
end to_additive
/- map operations -/
attribute [to_additive] has_mul has_one has_inv
/- map structures -/
attribute [to_additive add_semigroup] semigroup
attribute [to_additive add_comm_semigroup] comm_semigroup
attribute [to_additive add_left_cancel_semigroup] left_cancel_semigroup
attribute [to_additive add_right_cancel_semigroup] right_cancel_semigroup
attribute [to_additive add_monoid] monoid
attribute [to_additive add_comm_monoid] comm_monoid
attribute [to_additive add_group] group
attribute [to_additive add_comm_group] comm_group
/- map theorems -/
attribute [to_additive] mul_assoc
attribute [to_additive add_semigroup_to_is_eq_associative] semigroup_to_is_associative
attribute [to_additive] mul_comm
attribute [to_additive add_comm_semigroup_to_is_eq_commutative] comm_semigroup_to_is_commutative
attribute [to_additive] mul_left_comm
attribute [to_additive] mul_right_comm
attribute [to_additive] mul_left_cancel
attribute [to_additive] mul_right_cancel
attribute [to_additive] mul_left_cancel_iff
attribute [to_additive] mul_right_cancel_iff
attribute [to_additive] one_mul
attribute [to_additive] mul_one
attribute [to_additive] mul_left_inv
attribute [to_additive] inv_mul_self
attribute [to_additive] inv_mul_cancel_left
attribute [to_additive] inv_mul_cancel_right
attribute [to_additive] inv_eq_of_mul_eq_one
attribute [to_additive neg_zero] one_inv
attribute [to_additive] inv_inv
attribute [to_additive] mul_right_inv
attribute [to_additive] mul_inv_self
attribute [to_additive] inv_inj
attribute [to_additive] group.mul_left_cancel
attribute [to_additive] group.mul_right_cancel
attribute [to_additive to_left_cancel_add_semigroup] group.to_left_cancel_semigroup
attribute [to_additive to_right_cancel_add_semigroup] group.to_right_cancel_semigroup
attribute [to_additive] mul_inv_cancel_left
attribute [to_additive] mul_inv_cancel_right
attribute [to_additive neg_add_rev] mul_inv_rev
attribute [to_additive] eq_inv_of_eq_inv
attribute [to_additive] eq_inv_of_mul_eq_one
attribute [to_additive] eq_mul_inv_of_mul_eq
attribute [to_additive] eq_inv_mul_of_mul_eq
attribute [to_additive] inv_mul_eq_of_eq_mul
attribute [to_additive] mul_inv_eq_of_eq_mul
attribute [to_additive] eq_mul_of_mul_inv_eq
attribute [to_additive] eq_mul_of_inv_mul_eq
attribute [to_additive] mul_eq_of_eq_inv_mul
attribute [to_additive] mul_eq_of_eq_mul_inv
attribute [to_additive neg_add] mul_inv
|
73acf902e3eb60eec436d4e770f9146d9843ac5a | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/pfunctor/multivariate/basic.lean | 823037162e2cb34638adaa5e2e7683f6cb18c267 | [
"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 | 6,521 | lean | /-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Simon Hudon
-/
import control.functor.multivariate
import data.pfunctor.univariate.basic
/-!
# Multivariate polynomial functors.
Multivariate polynomial functors are used for defining M-types and W-types.
They map a type vector `α` to the type `Σ a : A, B a ⟹ α`, with `A : Type` and
`B : A → typevec n`. They interact well with Lean's inductive definitions because
they guarantee that occurrences of `α` are positive.
-/
universes u v
open_locale mvfunctor
/--
multivariate polynomial functors
-/
structure mvpfunctor (n : ℕ) :=
(A : Type.{u}) (B : A → typevec.{u} n)
namespace mvpfunctor
open mvfunctor (liftp liftr)
variables {n m : ℕ} (P : mvpfunctor.{u} n)
/-- Applying `P` to an object of `Type` -/
def obj (α : typevec.{u} n) : Type u := Σ a : P.A, P.B a ⟹ α
/-- Applying `P` to a morphism of `Type` -/
def map {α β : typevec n} (f : α ⟹ β) : P.obj α → P.obj β :=
λ ⟨a, g⟩, ⟨a, typevec.comp f g⟩
instance : inhabited (mvpfunctor n) :=
⟨ ⟨default, λ _, default⟩ ⟩
instance obj.inhabited {α : typevec n} [inhabited P.A] [Π i, inhabited (α i)] :
inhabited (P.obj α) :=
⟨ ⟨default, λ _ _, default⟩ ⟩
instance : mvfunctor P.obj :=
⟨@mvpfunctor.map n P⟩
theorem map_eq {α β : typevec n} (g : α ⟹ β) (a : P.A) (f : P.B a ⟹ α) :
@mvfunctor.map _ P.obj _ _ _ g ⟨a, f⟩ = ⟨a, g ⊚ f⟩ :=
rfl
theorem id_map {α : typevec n} : ∀ x : P.obj α, typevec.id <$$> x = x
| ⟨a, g⟩ := rfl
theorem comp_map {α β γ : typevec n} (f : α ⟹ β) (g : β ⟹ γ) :
∀ x : P.obj α, (g ⊚ f) <$$> x = g <$$> (f <$$> x)
| ⟨a, h⟩ := rfl
instance : is_lawful_mvfunctor P.obj :=
{ id_map := @id_map _ P,
comp_map := @comp_map _ P }
/-- Constant functor where the input object does not affect the output -/
def const (n : ℕ) (A : Type u) : mvpfunctor n :=
{ A := A, B := λ a i, pempty }
section const
variables (n) {A : Type u} {α β : typevec.{u} n}
/-- Constructor for the constant functor -/
def const.mk (x : A) {α} : (const n A).obj α :=
⟨ x, λ i a, pempty.elim a ⟩
variables {n A}
/-- Destructor for the constant functor -/
def const.get (x : (const n A).obj α) : A :=
x.1
@[simp]
lemma const.get_map (f : α ⟹ β) (x : (const n A).obj α) :
const.get (f <$$> x) = const.get x :=
by { cases x, refl }
@[simp]
lemma const.get_mk (x : A) : const.get (const.mk n x : (const n A).obj α) = x :=
by refl
@[simp]
lemma const.mk_get (x : (const n A).obj α) : const.mk n (const.get x) = x :=
by { cases x, dsimp [const.get,const.mk], congr' with _ ⟨ ⟩ }
end const
/-- Functor composition on polynomial functors -/
def comp (P : mvpfunctor.{u} n) (Q : fin2 n → mvpfunctor.{u} m) : mvpfunctor m :=
{ A := Σ a₂ : P.1, Π i, P.2 a₂ i → (Q i).1,
B := λ a, λ i, Σ j (b : P.2 a.1 j), (Q j).2 (a.snd j b) i }
variables {P} {Q : fin2 n → mvpfunctor.{u} m} {α β : typevec.{u} m}
/-- Constructor for functor composition -/
def comp.mk (x : P.obj (λ i, (Q i).obj α)) : (comp P Q).obj α :=
⟨ ⟨ x.1, λ i a, (x.2 _ a).1 ⟩, λ i a, (x.snd a.fst (a.snd).fst).snd i (a.snd).snd ⟩
/-- Destructor for functor composition -/
def comp.get (x : (comp P Q).obj α) : P.obj (λ i, (Q i).obj α) :=
⟨ x.1.1, λ i a, ⟨x.fst.snd i a, λ (j : fin2 m) (b : (Q i).B _ j), x.snd j ⟨i, ⟨a, b⟩⟩⟩ ⟩
lemma comp.get_map (f : α ⟹ β) (x : (comp P Q).obj α) :
comp.get (f <$$> x) = (λ i (x : (Q i).obj α), f <$$> x) <$$> comp.get x :=
by { cases x, refl }
@[simp]
lemma comp.get_mk (x : P.obj (λ i, (Q i).obj α)) : comp.get (comp.mk x) = x :=
begin
cases x,
simp! [comp.get,comp.mk],
end
@[simp]
lemma comp.mk_get (x : (comp P Q).obj α) : comp.mk (comp.get x) = x :=
begin
cases x,
dsimp [comp.get,comp.mk],
ext : 2; intros, refl, refl,
congr, ext1; intros; refl,
ext : 2, congr, rcases x_1 with ⟨a,b,c⟩; refl
end
/-
lifting predicates and relations
-/
theorem liftp_iff {α : typevec n} (p : Π ⦃i⦄ , α i → Prop) (x : P.obj α) :
liftp p x ↔ ∃ a f, x = ⟨a, f⟩ ∧ ∀ i j, p (f i j) :=
begin
split,
{ rintros ⟨y, hy⟩, cases h : y with a f,
refine ⟨a, λ i j, (f i j).val, _, λ i j, (f i j).property⟩,
rw [←hy, h, map_eq], refl },
rintros ⟨a, f, xeq, pf⟩,
use ⟨a, λ i j, ⟨f i j, pf i j⟩⟩,
rw [xeq], reflexivity
end
theorem liftp_iff' {α : typevec n} (p : Π ⦃i⦄ , α i → Prop) (a : P.A) (f : P.B a ⟹ α) :
@liftp.{u} _ P.obj _ α p ⟨a,f⟩ ↔ ∀ i x, p (f i x) :=
begin
simp only [liftp_iff, sigma.mk.inj_iff]; split; intro,
{ casesm* [Exists _, _ ∧ _], subst_vars, assumption },
repeat { constructor <|> assumption }
end
theorem liftr_iff {α : typevec n} (r : Π ⦃i⦄, α i → α i → Prop) (x y : P.obj α) :
liftr r x y ↔ ∃ a f₀ f₁, x = ⟨a, f₀⟩ ∧ y = ⟨a, f₁⟩ ∧ ∀ i j, r (f₀ i j) (f₁ i j) :=
begin
split,
{ rintros ⟨u, xeq, yeq⟩, cases h : u with a f,
use [a, λ i j, (f i j).val.fst, λ i j, (f i j).val.snd],
split, { rw [←xeq, h], refl },
split, { rw [←yeq, h], refl },
intros i j, exact (f i j).property },
rintros ⟨a, f₀, f₁, xeq, yeq, h⟩,
use ⟨a, λ i j, ⟨(f₀ i j, f₁ i j), h i j⟩⟩,
dsimp, split,
{ rw [xeq], refl },
rw [yeq], refl
end
open set mvfunctor
theorem supp_eq {α : typevec n} (a : P.A) (f : P.B a ⟹ α) (i) :
@supp.{u} _ P.obj _ α (⟨a,f⟩ : P.obj α) i = f i '' univ :=
begin
ext, simp only [supp, image_univ, mem_range, mem_set_of_eq],
split; intro h,
{ apply @h (λ i x, ∃ (y : P.B a i), f i y = x),
rw liftp_iff', intros, refine ⟨_,rfl⟩ },
{ simp only [liftp_iff'], cases h, subst x,
tauto }
end
end mvpfunctor
/-
Decomposing an n+1-ary pfunctor.
-/
namespace mvpfunctor
open typevec
variables {n : ℕ} (P : mvpfunctor.{u} (n+1))
/-- Split polynomial functor, get a n-ary functor
from a `n+1`-ary functor -/
def drop : mvpfunctor n :=
{ A := P.A, B := λ a, (P.B a).drop }
/-- Split polynomial functor, get a univariate functor
from a `n+1`-ary functor -/
def last : pfunctor :=
{ A := P.A, B := λ a, (P.B a).last }
/-- append arrows of a polynomial functor application -/
@[reducible] def append_contents {α : typevec n} {β : Type*}
{a : P.A} (f' : P.drop.B a ⟹ α) (f : P.last.B a → β) :
P.B a ⟹ α ::: β :=
split_fun f' f
end mvpfunctor
|
b174b03a6b98a68ac6da1b907f6b5df0f46944d1 | e0e64c424bf126977aef10e58324934782979062 | /src/wk4/subgroups.lean | 8f7e4a92c3d3336efde8069dd8dbe1562b4ddb8a | [] | no_license | jamesa9283/LiaLeanTutor | 34e9e133a4f7dd415f02c14c4a62351bb9fd8c21 | c7ac1400f26eb2992f5f1ee0aaafb54b74665072 | refs/heads/master | 1,686,146,337,422 | 1,625,227,392,000 | 1,625,227,392,000 | 373,130,175 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 19,672 | lean | /-
Change the below line to
import week_2.kb_solutions.Part_A_groups_solutions
(once the solutions are posted) if you want to get rid of the warning
-/
import wk4.groups
/-!
## Subgroups
We define the structure `subgroup G`, whose terms are subgroups of `G`.
A subgroup of `G` is implemented as a subset of `G` closed under
`1`, `*` and `⁻¹`.
-/
namespace xena
/-- A subgroup of a group G is a subset containing 1
and closed under multiplication and inverse. -/
structure subgroup (G : Type) [group G] :=
(carrier : set G)
(one_mem' : (1 : G) ∈ carrier)
(mul_mem' {x y} : x ∈ carrier → y ∈ carrier → x * y ∈ carrier)
(inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier)
/-
At this point, here's what we have.
A term `H` of type `subgroup G`, written `H : subgroup G`, is a
*quadruple*. To give a term `H : subgroup G` is to give the following four things:
1) `H.carrier` (a subset of `G`),
2) `H.one_mem'` (a proof that `1 ∈ H.carrier`),
3) `H.mul_mem'` (a proof that `H` is closed under multiplication)
4) `H.inv_mem'` (a proof that `H` is closed under inverses).
Note in particular that Lean, being super-pedantic, *distinguishes* between
the subgroup `H` and the subset `H.carrier`. One is a subgroup, one is
a subset. When we get going we will start by setting up some infrastructure
so that this difference will be hard to notice.
Note also that if `x` is in the subgroup `H` of `H` then the _type_ of `x` is still `G`,
and `x ∈ carrier` is a Proposition. Note also that `x : carrier` doesn't
make sense (`carrier` is a term, not a type, rather counterintuitively).
-/
namespace subgroup
open xena.group
-- let G be a group and let H and K be subgroups
variables {G : Type} [group G] (H J K : subgroup G)
/-
This `h ∈ H.carrier` notation kind of stinks. I don't want to write `H.carrier`
everywhere, because I want to be able to identify the subgroup `H` with
its underlying subset `H.carrier`. Note that these things are not _equal_,
firstly because `H` contains the proof that `H.carrier` is a subgroup, and
secondly because these terms have different types! `H` has type `subgroup G`
and `H.carrier` has type `set G`. Let's start by sorting this out.
-/
-- If `x : G` and `H : subgroup G` then let's define the notation
-- `x ∈ H` to mean `x ∈ H.carrier`
instance : has_mem G (subgroup G) := ⟨λ m H, m ∈ H.carrier⟩
-- Let's also define a "coercion", a.k.a. an "invisible map"
-- from subgroups of `G` to subsets of `G`, sending `H` to `H.carrier`.
-- The map is not completely invisible -- it's a little ↑. So
-- if you see `↑H` in the future, it means the subset `H.carrier` by definition.
instance : has_coe (subgroup G) (set G) := ⟨λ H, H.carrier⟩
-- `λ` is just computer science notation for ↦ (mapsto); so
-- `λ H, H.carrier` is the function `H ↦ H.carrier`.
-- Let's check we have this working, and also tell the simplifier that we
-- would rather talk about `g ∈ H` than any other way of saying it.
/-- `g` is in the underlying subset of `H` iff `g ∈ H`. -/
@[simp] lemma mem_carrier {g : G} : g ∈ H.carrier ↔ g ∈ H :=
begin
-- true by definition
refl
end
/-- `g` is in `H` considered as a subset of `G`, iff `g` is in `H` considered
as subgroup of `G`. -/
@[simp] lemma mem_coe {g : G} : g ∈ (↑H : set G) ↔ g ∈ H :=
begin
-- true by definition
refl
end
-- Now let's define theorems without the `'`s in, which use this
-- more natural notation
/-- A subgroup contains the group's 1. -/
theorem one_mem : (1 : G) ∈ H := H.one_mem'
/-- A subgroup is closed under multiplication. -/
theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H :=
begin
apply H.mul_mem'
end
/-
begin
intros x y,
apply mul_mem';
rw mem_carrier,
{ exact x},
{ exact y},
-- what do you think?
end
-/
/-- A subgroup is closed under inverse -/
theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H :=
begin
apply H.inv_mem',
-- what do you think?
end
/-
So here are the three theorems which you need to remember about subgroups.
Say `H : subgroup G`. Then:
`H.one_mem : (1 : G) ∈ H`
`H.mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H`
`H.inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H`
These now look like the way a mathematician would write things.
Now let's start to prove basic theorems about subgroups (or, as a the computer
scientists would say, make a basic _interface_ or _API_ for subgroups),
using this sensible notation.
Here's an example; let's prove `x ∈ H ↔ x⁻¹ ∈ H`. Let's put the more
complicated expression on the left hand side of the `↔` though, because then
we can make it a `simp` lemma.
-/
-- Remember that `xena.group.inv_inv x` is the statement that `x⁻¹⁻¹ = x`
@[simp] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H :=
begin
split,
{ intros H,
-- fiddled around with using inv_mem, doesn't work, so I need another inv
rw ← inv_inv x, -- this adds another inv
apply inv_mem, -- this gets rid of one of the inv
exact H,
},
{ apply inv_mem,}
end
-- We could prove a bunch more theorems here. Let's just do one more.
-- Let's show that if x and xy are in H then so is y.
theorem mem_of_mem_mul_mem {x y : G} (hx : x ∈ H) (hxy : x * y ∈ H) : y ∈ H :=
begin
rw ← inv_mem_iff at hx,
convert H.mul_mem hx hxy,
simp only [eq_self_iff_true, xena.group.inv_mul_cancel_left],
end
/-
Subgroups are extensional objects (like most things in mathematics):
two subgroups are equal if they have the same underlying subset,
and also if they have the same underlying elements.
Let's prove variants of this triviality now. The first one is rather
un-mathematical: it takes a subgroup apart into its pieces. I'll see if
you can do the other two!
-/
/-- Two subgroups are equal if the underlying subsets are equal. -/
theorem ext' {H K : subgroup G} (h : H.carrier = K.carrier) : H = K :=
begin
-- first take H and K apart
cases H, -- H now broken up into its underlying 3-tuple.
cases K,
-- and now it must be obvious, so let's see if the simplifier can do it.
simp * at *, -- it can!
end
-- here's a variant. You can prove it using `ext'`.
/-- Two subgroups are equal if and only if the underlying subsets are equal. -/
theorem ext'_iff {H K : subgroup G} :
H.carrier = K.carrier ↔ H = K :=
begin
split,
{ exact ext',},
{ intro h,
rw h,
}
end
-- to do this next one, first apply the `ext'` theorem we just proved,
-- and then use the `ext` tactic (which works on sets)
/-- Two subgroups are equal if they have the same elements. -/
@[ext] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K :=
begin
apply ext',
ext,
apply h,
end
/-
We tagged that theorem with `ext`, so now the `ext` tactic works on subgroups
too: if you ever have a goal of proving that two subgroups are equal, you can
use the `ext` tactic to reduce to showing that they have the same elements.
-/
/-
## The lattice structure on subgroups
Subgroups of a group form what is known as a *lattice*.
This is a partially ordered set with a sensible notion of
max and min. We partially order subgroups by saying `H ≤ K` if
`H.carrier ⊆ K.carrier`. Subgroups even have a good notion of an infinite
Sup and Inf (the Inf of a bunch of subgroups is just their intersection;
their Sup is the subgroup generated by their union).
This combinatorial structure (a partially ordered set with good
finite and infinite notions of Sup and Inf) is called a "complete lattice",
and Lean has this structure inbuilt into it. We will construct
a complete lattice structure on `subgroup G`.
We start by defining a relation ≤ on the type of subgroups of a group.
We say H ≤ K iff H.carrier ⊆ K.carrier .
-/
/-- If `H` and `K` are subgroups of `G`, we write `H ≤ K` to
mean `H.carrier ⊆ K.carrier` -/
instance : has_le (subgroup G) := ⟨λ H K, H.carrier ⊆ K.carrier⟩
-- useful to restate the definition so we can `rw` it
lemma le_def : H ≤ K ↔ H.carrier ⊆ K.carrier :=
begin
-- true by definition
refl
end
-- another useful variant
lemma le_iff : H ≤ K ↔ ∀ g, g ∈ H → g ∈ K :=
begin
-- true by definition
refl,
end
-- Now let's check the axioms for a partial order.
-- These are not hard, they just reduce immediately to the
-- fact that ⊆ is a partial order
@[refl] lemma le_refl : H ≤ H :=
begin
rw le_def,
-- Lean knows ⊆ is reflexive so the sneaky `refl` which Lean tries after `rw`
-- has closed the goal!
end
lemma le_antisymm : H ≤ K → K ≤ H → H = K :=
begin
rw [le_def, le_def, ← ext'_iff],
intros HK KH,
-- now this is antisymmetry of ⊆, which Lean knows
exact set.subset.antisymm HK KH,
end
@[trans] lemma le_trans : H ≤ J → J ≤ K → H ≤ K :=
begin
rw [le_def, le_def, le_def],
-- now this is transitivity of ⊆, which Lean knows
exact set.subset.trans,
end
-- We've made `subgroup G` into a partial order!
instance : partial_order (subgroup G) :=
{ le := (≤),
le_refl := le_refl,
le_antisymm := le_antisymm,
le_trans := le_trans }
/-
### intersections
Let's prove that the intersection of two subgroups is a subgroup. In Lean
this is a definition: given two subgroups, we define a new subgroup whose
underlying subset is the intersection of the subsets, and then prove
the axioms.
-/
/-- The intersection of two subgroups is also a subgroup -/
def inf (H K : subgroup G) : subgroup G :=
{ carrier := H.carrier ∩ K.carrier, -- the carrier is the intersection
one_mem' :=
begin
-- recall that x ∈ Y ∩ Z is _by definition_ x ∈ Y ∧ x ∈ Z, so you can `split` this.
split,
{ exact H.one_mem,},
{ exact K.one_mem,},
end,
mul_mem' :=
begin
intros x y hx hy,
cases hx with hx1 hx2,
cases hy with hy1 hy2,
exact ⟨H.mul_mem hx1 hy1, K.mul_mem hx2 hy2⟩
end,
inv_mem' :=
begin
rintros x ⟨h1, h2⟩,
exact ⟨ H.inv_mem h1, K.inv_mem h2 ⟩,
end }
-- Notation for `inf` in computer science circles is ⊓.
instance : has_inf (subgroup G) := ⟨inf⟩
/-- The underlying set of the inf of two subgroups is just their intersection -/
lemma inf_def (H K : subgroup G) : (H ⊓ K : set G) = (H : set G) ∩ K :=
begin
-- true by definition
refl
end
/-
## Subgroup generated by a subset.
To do the sup of two subgroups is harder, because we don't just take
the union, we need to then look at the subgroup generated by this union
(e.g. the union of the x and y axes in ℝ² is not a subgroup). So we need
to have a machine to spit out the subgroup of `G` generated by a subset `S : set G`.
There are two completely different ways to do this. The first is a "top-down"
approach. We could define the subgroup generated by `S` to be the intersection of
all the subgroups of `G` that contain `S`. The second is a "bottom-up" approach.
We could define the subgroup generated by `S` "by induction" (or more precisely
by recursion), saying that `S` is in the subgroup, 1 is in the subgroup,
the product of two things in the subgroup is in the subgroup, the
inverse of something in the subgroup is in the subgroup, and that's it.
Both methods come out rather nicely in Lean. Let's do the first one.
We are going to be using a bunch of theorems about "bounded intersections",
a.k.a. `set.bInter`. We will soon get tired of writing `set.blah` so let's
`open set` so that we can skip it.
-/
open set
/-
Here is the API for `set.bInter` (or `bInter`, as we can now call it):
Notation: `⋂` (type with `\I`)
If `X : set (subgroup G)`, i.e. if `X` is a set of subgroups of `G`, then
`⋂ K ∈ X, (K : set G)` means "take the intersection of the underlying subsets".
-- mem_bInter_iff says you're in the intersection iff you're in
-- all the things you're intersecting. Very useful for rewriting.
`mem_bInter_iff : (g ∈ ⋂ (K ∈ S), f K) ↔ (∀ K, K ∈ s → g ∈ f K)`
-- mem_bInter is just the one way implication. Very useful for `apply`ing.
`mem_bInter : (∀ K, K ∈ s → g ∈ f K) → (g ∈ ⋂ (K ∈ S), f K)`
-/
/-
We will consider the closure of a set as the intersect of all subgroups
containing the set
-/
/-- The Inf of a set of subgroups of G is their intersection. -/
def Inf (X : set (subgroup G)) : subgroup G :=
{ carrier := ⋂ K ∈ X, (K : set G), -- carrier is the intersection of the underlying sets
one_mem' :=
begin
rw mem_bInter_iff,
intros x hxX,
apply x.one_mem,
end,
mul_mem' := begin
intros x y hx hy,
rw mem_bInter_iff at hx hy ⊢,
intros a haX,
-- specialize hx a haX,
-- specialize hy a haX,
apply a.mul_mem (hx a haX) (hy a haX), -- a.mul_mem hx hy
end,
inv_mem' := begin
intros x hx,
rw mem_bInter_iff at hx ⊢,
intros a haX,
apply a.inv_mem (hx a haX),
end,
}
/-- The *closure* of a subset `S` of `G` is the `Inf` of the subgroups of `G`
which contain `S`. -/
def closure (S : set G) : subgroup G := Inf {H : subgroup G | S ⊆ H}
-- we can restate mem_bInter_iff using our new "closure" language:
lemma mem_closure_iff {S : set G} {x : G} :
x ∈ closure S ↔ ∀ H : subgroup G, S ⊆ H → x ∈ H := mem_bInter_iff
/-
There is an underlying abstraction here, which you may not know about.
A "closure operator" in mathematics
https://en.wikipedia.org/wiki/Closure_operator
is something mapping subsets of a set X to subsets of X, and satisfying three
axioms:
1) `subset_closure : S ⊆ closure S`
2) `closure_mono : (S ⊆ T) → (closure S ⊆ closure T)`
3) `closure_closure : closure (closure S) = closure S`
It works for closure in topological spaces, and it works here too.
It also works for algebraic closures of fields, and there are several
other places in mathematics where it shows up. This idea, of "abstracting"
and axiomatising a phenomenon which shows up in more than one place,
is really key in Lean.
Let's prove these three lemmas in the case where `X = G` and `closure S`
is the subgroup generated by `S`.
Here are some things you might find helpful.
Remember
`mem_coe : g ∈ ↑H ↔ g ∈ H`
`mem_carrier : g ∈ H.carrier ↔ g ∈ H`
There's
`mem_closure_iff : x ∈ closure S ↔ ∀ (H : subgroup G), S ⊆ ↑H → x ∈ H`
(`closure S` is a subgroup so you might need to use `mem_coe` or `mem_carrier` first)
For subsets there's
`subset.trans : X ⊆ Y → Y ⊆ Z → X ⊆ Z`
You might find `le_antisymm : H ≤ K → K ≤ H → H = K` from above useful
-/
/-
Reminder: X ⊆ Y means `∀ g, g ∈ X → g ∈ Y` and it's definitional,
so you can just start this with `intro g`.
-/
lemma subset_closure (S : set G) : S ⊆ ↑(closure S) :=
begin
intros g hgS,
rw [mem_coe, mem_closure_iff],
intros H hSH,
exact hSH hgS, -- as X ⊆ Y means `∀ g, g ∈ X → g ∈ Y`, then giving hSH hgS
-- will just return a term of type that is the same as the goal
end
-- It's useful to know `subset.trans : X ⊆ Y → Y ⊆ Z → X ⊆ Z`
lemma closure_mono {S T : set G} (hST : S ⊆ T) : closure S ≤ closure T :=
begin
intros x hxS,
rw [mem_carrier, mem_closure_iff] at ⊢ hxS,
-- apply hST hxS, -- has type x ∈ closure S but is expected to have type ?m_1 ∈ S
-- so this is useful, but after we have something like a ∈ S.
--rw mem_closure_iff at hxS ⊢,
intros H hH,
-- have hH2 := subset.trans hST hH,
-- rw mem_closure_iff at hxS,
-- specialize hxS H (subset.trans hST hH),
exact (hxS H (subset.trans hST hH)),
end
-- not one of the axioms, but sometimes handy
lemma closure_le (S : set G) (H : subgroup G) : closure S ≤ H ↔ S ⊆ ↑H :=
begin
split,
{ intros hSH,
apply subset.trans (subset_closure S) hSH,
},
{ intros hSH g hg,
rw mem_carrier,
rw [mem_carrier, mem_closure_iff] at hg,
apply hg H hSH,
},
end
-- You can start this one by applying `le_antisymm`,
lemma closure_closure (S : set G) : closure S = closure (closure S) :=
begin
apply le_antisymm,
{ apply subset_closure,},
{ rw closure_le,
intros x hx,
exact hx,
},
end
-- This shows that every subgroup is the closure of something, namely its
-- underlying subset.
lemma closure_self {H : subgroup G} : closure ↑H = H :=
begin
apply le_antisymm,
{ rw le_iff,
intros g hg,
rw mem_closure_iff at hg,
apply hg H, refl,
},
{ apply subset_closure,},
end
/-
Recall the second proposed construction of the subgroup closure of a subset `S`;
it is the smallest subgroup `H` of `G` such that `S ⊆ H` and which contains
`1` and is closed under `*` and `⁻¹`. This inductive constuction (which we
did not make) comes with a so-called "recursor": if we have a true/false
statement `p g` attached to each element `g` of G with the following properties:
1) `p s` is true for all `s ∈ S`,
2) `p 1` is true,
3) If `p x` and `p y` then `p (x * y)`,
4) If `p x` then `p x⁻¹`
Then `p` is true on all of `closure S`.
If we had made an inductive definition of `closure S` then this would have been true
by definition! We used another definition, so we will have to prove it
ourselves.
-/
/-- An induction principle for closures. -/
lemma closure_induction {p : G → Prop} {S : set G}
(HS : ∀ x ∈ S, p x)
(H1 : p 1)
(Hmul : ∀ x y, p x → p y → p (x * y))
(Hinv : ∀ x, p x → p x⁻¹) :
-- conclusion after colon
∀ x, x ∈ closure S → p x :=
begin
-- the subset of G where `p` is true is a subgroup. Let's call it H
let H : subgroup G :=
{ carrier := p,
one_mem' := H1,
mul_mem' := Hmul,
inv_mem' := Hinv },
-- The goal is just that closure S ≤ H, by definition.
change closure S ≤ H,
-- Our hypothesis HS is just that S ⊆ ↑H, by definition
change S ⊆ ↑H at HS,
-- I think you can take it from here!
rw closure_le,
exact HS, -- assumption
end
/-
Finally we prove that the `closure` and `coe` maps form a `galois_insertion`.
This is another abstraction, it generalises `galois_connection`, which is
something that shows up all over the place (algebraic geometry, Galois theory etc).
See
https://en.wikipedia.org/wiki/Galois_connection
A partial order can be considered as a category, with Hom(A,B) having
one element if A ≤ B and no elements otherwise. A Galois connection between
two partial orders is just a pair of adjoint functors between the categories.
Adjointness in our case is `S ⊆ ↑H ↔ closure S ≤ H`.
The reason it's an insertion and not just a connection is that if you start
with a subgroup, take the underlying subset, and then look at the subgroup
generated by that set, you get back to where you started. So it's like one
of the adjoint functors being a forgetful functor.
-/
/-- THIS IS A DOCSTRING -/
def gi : galois_insertion (closure : set G → subgroup G) (coe : subgroup G → set G) :=
{ choice := λ S _, closure S,
gc := closure_le,
le_l_u := λ H, subset_closure (H : set G),
choice_eq := λ _ _, rfl }
/-
One use of this abstraction is that now we can pull back the complete
lattice structure on `set G` to get a complete lattice structure on `subgroup G`.
-/
instance : complete_lattice (subgroup G) :=
{.. galois_insertion.lift_complete_lattice gi}
/-
We just proved loads of lemmas about Infs and Sups of subgroups automatically,
and have access to a ton more because the `complete_lattice` structure in
Lean has a big API. See for example
https://leanprover-community.github.io/mathlib_docs/order/complete_lattice.html#complete_lattice
All those theorems are now true for subgroups. None are particularly hard to prove,
but the point is that we don't now have to prove any of them ourselves.
-/
end subgroup
end xena
/-
Further work: `bot` and `top` (would have to explain the
API for `singleton` and `univ`)
-/ |
87b0e1a9879095eba0ab824512378dbdc1922dcd | 94e33a31faa76775069b071adea97e86e218a8ee | /src/algebra/group/basic.lean | 188264c85cf6e57411dfba2fbfefb3b1cb731ece | [
"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 | 21,620 | 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, Simon Hudon, Mario Carneiro
-/
import algebra.group.defs
import data.bracket
import logic.function.basic
/-!
# Basic lemmas about semigroups, monoids, and groups
This file lists various basic lemmas about semigroups, monoids, and groups. Most proofs are
one-liners from the corresponding axioms. For the definitions of semigroups, monoids and groups, see
`algebra/group/defs.lean`.
-/
open function
universe u
variables {α G : Type*}
section associative
variables (f : α → α → α) [is_associative α f] (x y : α)
/--
Composing two associative operations of `f : α → α → α` on the left
is equal to an associative operation on the left.
-/
lemma comp_assoc_left : (f x) ∘ (f y) = (f (f x y)) :=
by { ext z, rw [function.comp_apply, @is_associative.assoc _ f] }
/--
Composing two associative operations of `f : α → α → α` on the right
is equal to an associative operation on the right.
-/
lemma comp_assoc_right : (λ z, f z x) ∘ (λ z, f z y) = (λ z, f z (f y x)) :=
by { ext z, rw [function.comp_apply, @is_associative.assoc _ f] }
end associative
section semigroup
/--
Composing two multiplications on the left by `y` then `x`
is equal to a multiplication on the left by `x * y`.
-/
@[simp, to_additive
"Composing two additions on the left by `y` then `x`
is equal to a addition on the left by `x + y`."]
lemma comp_mul_left [semigroup α] (x y : α) :
((*) x) ∘ ((*) y) = ((*) (x * y)) :=
comp_assoc_left _ _ _
/--
Composing two multiplications on the right by `y` and `x`
is equal to a multiplication on the right by `y * x`.
-/
@[simp, to_additive
"Composing two additions on the right by `y` and `x`
is equal to a addition on the right by `y + x`."]
lemma comp_mul_right [semigroup α] (x y : α) :
(* x) ∘ (* y) = (* (y * x)) :=
comp_assoc_right _ _ _
end semigroup
section mul_one_class
variables {M : Type u} [mul_one_class M]
@[to_additive]
lemma ite_mul_one {P : Prop} [decidable P] {a b : M} :
ite P (a * b) 1 = ite P a 1 * ite P b 1 :=
by { by_cases h : P; simp [h], }
@[to_additive]
lemma ite_one_mul {P : Prop} [decidable P] {a b : M} :
ite P 1 (a * b) = ite P 1 a * ite P 1 b :=
by { by_cases h : P; simp [h], }
@[to_additive]
lemma eq_one_iff_eq_one_of_mul_eq_one {a b : M} (h : a * b = 1) : a = 1 ↔ b = 1 :=
by split; { rintro rfl, simpa using h }
@[to_additive]
lemma one_mul_eq_id : ((*) (1 : M)) = id := funext one_mul
@[to_additive]
lemma mul_one_eq_id : (* (1 : M)) = id := funext mul_one
end mul_one_class
section comm_semigroup
variables [comm_semigroup G]
@[no_rsimp, to_additive]
lemma mul_left_comm : ∀ a b c : G, a * (b * c) = b * (a * c) :=
left_comm has_mul.mul mul_comm mul_assoc
@[to_additive]
lemma mul_right_comm : ∀ a b c : G, a * b * c = a * c * b :=
right_comm has_mul.mul mul_comm mul_assoc
@[to_additive]
theorem mul_mul_mul_comm (a b c d : G) : (a * b) * (c * d) = (a * c) * (b * d) :=
by simp only [mul_left_comm, mul_assoc]
@[to_additive]
lemma mul_rotate (a b c : G) : a * b * c = b * c * a :=
by simp only [mul_left_comm, mul_comm]
@[to_additive]
lemma mul_rotate' (a b c : G) : a * (b * c) = b * (c * a) :=
by simp only [mul_left_comm, mul_comm]
end comm_semigroup
section add_comm_semigroup
variables {M : Type u} [add_comm_semigroup M]
lemma bit0_add (a b : M) : bit0 (a + b) = bit0 a + bit0 b :=
add_add_add_comm _ _ _ _
lemma bit1_add [has_one M] (a b : M) : bit1 (a + b) = bit0 a + bit1 b :=
(congr_arg (+ (1 : M)) $ bit0_add a b : _).trans (add_assoc _ _ _)
lemma bit1_add' [has_one M] (a b : M) : bit1 (a + b) = bit1 a + bit0 b :=
by rw [add_comm, bit1_add, add_comm]
end add_comm_semigroup
local attribute [simp] mul_assoc sub_eq_add_neg
section add_monoid
variables {M : Type u} [add_monoid M] {a b c : M}
@[simp] lemma bit0_zero : bit0 (0 : M) = 0 := add_zero _
@[simp] lemma bit1_zero [has_one M] : bit1 (0 : M) = 1 :=
by rw [bit1, bit0_zero, zero_add]
end add_monoid
section comm_monoid
variables {M : Type u} [comm_monoid M] {x y z : M}
@[to_additive] lemma inv_unique (hy : x * y = 1) (hz : x * z = 1) : y = z :=
left_inv_eq_right_inv (trans (mul_comm _ _) hy) hz
end comm_monoid
section left_cancel_monoid
variables {M : Type u} [left_cancel_monoid M] {a b : M}
@[simp, to_additive] lemma mul_right_eq_self : a * b = a ↔ b = 1 :=
calc a * b = a ↔ a * b = a * 1 : by rw mul_one
... ↔ b = 1 : mul_left_cancel_iff
@[simp, to_additive] lemma self_eq_mul_right : a = a * b ↔ b = 1 :=
eq_comm.trans mul_right_eq_self
end left_cancel_monoid
section right_cancel_monoid
variables {M : Type u} [right_cancel_monoid M] {a b : M}
@[simp, to_additive] lemma mul_left_eq_self : a * b = b ↔ a = 1 :=
calc a * b = b ↔ a * b = 1 * b : by rw one_mul
... ↔ a = 1 : mul_right_cancel_iff
@[simp, to_additive] lemma self_eq_mul_left : b = a * b ↔ a = 1 :=
eq_comm.trans mul_left_eq_self
end right_cancel_monoid
section has_involutive_inv
variables [has_involutive_inv G] {a b : G}
@[simp, to_additive]
lemma inv_involutive : function.involutive (has_inv.inv : G → G) := inv_inv
@[simp, to_additive]
lemma inv_surjective : function.surjective (has_inv.inv : G → G) :=
inv_involutive.surjective
@[to_additive]
lemma inv_injective : function.injective (has_inv.inv : G → G) :=
inv_involutive.injective
@[simp, to_additive] theorem inv_inj {a b : G} : a⁻¹ = b⁻¹ ↔ a = b := inv_injective.eq_iff
@[to_additive]
lemma eq_inv_of_eq_inv (h : a = b⁻¹) : b = a⁻¹ :=
by simp [h]
@[to_additive]
theorem eq_inv_iff_eq_inv : a = b⁻¹ ↔ b = a⁻¹ :=
⟨eq_inv_of_eq_inv, eq_inv_of_eq_inv⟩
@[to_additive]
theorem inv_eq_iff_inv_eq : a⁻¹ = b ↔ b⁻¹ = a :=
eq_comm.trans $ eq_inv_iff_eq_inv.trans eq_comm
variables (G)
@[simp, to_additive] lemma inv_comp_inv : has_inv.inv ∘ has_inv.inv = @id G :=
inv_involutive.comp_self
@[to_additive] lemma left_inverse_inv : left_inverse (λ a : G, a⁻¹) (λ a, a⁻¹) := inv_inv
@[to_additive] lemma right_inverse_inv : left_inverse (λ a : G, a⁻¹) (λ a, a⁻¹) := inv_inv
end has_involutive_inv
section div_inv_monoid
variables [div_inv_monoid G] {a b c : G}
@[to_additive, field_simps] -- The attributes are out of order on purpose
lemma inv_eq_one_div (x : G) :
x⁻¹ = 1 / x :=
by rw [div_eq_mul_inv, one_mul]
@[to_additive]
lemma mul_one_div (x y : G) :
x * (1 / y) = x / y :=
by rw [div_eq_mul_inv, one_mul, div_eq_mul_inv]
@[to_additive]
lemma mul_div_assoc (a b c : G) : a * b / c = a * (b / c) :=
by rw [div_eq_mul_inv, div_eq_mul_inv, mul_assoc _ _ _]
@[to_additive, field_simps] -- The attributes are out of order on purpose
lemma mul_div_assoc' (a b c : G) : a * (b / c) = (a * b) / c :=
(mul_div_assoc _ _ _).symm
@[simp, to_additive] lemma one_div (a : G) : 1 / a = a⁻¹ :=
(inv_eq_one_div a).symm
@[to_additive] lemma mul_div (a b c : G) : a * (b / c) = a * b / c :=
by simp only [mul_assoc, div_eq_mul_inv]
@[to_additive] lemma div_eq_mul_one_div (a b : G) : a / b = a * (1 / b) :=
by rw [div_eq_mul_inv, one_div]
end div_inv_monoid
section division_monoid
variables [division_monoid α] {a b c : α}
local attribute [simp] mul_assoc div_eq_mul_inv
@[to_additive] lemma inv_eq_of_mul_eq_one_left (h : a * b = 1) : b⁻¹ = a :=
by rw [←inv_eq_of_mul_eq_one_right h, inv_inv]
@[to_additive] lemma eq_inv_of_mul_eq_one_left (h : a * b = 1) : a = b⁻¹ :=
(inv_eq_of_mul_eq_one_left h).symm
@[to_additive] lemma eq_inv_of_mul_eq_one_right (h : a * b = 1) : b = a⁻¹ :=
(inv_eq_of_mul_eq_one_right h).symm
@[to_additive] lemma eq_one_div_of_mul_eq_one_left (h : b * a = 1) : b = 1 / a :=
by rw [eq_inv_of_mul_eq_one_left h, one_div]
@[to_additive] lemma eq_one_div_of_mul_eq_one_right (h : a * b = 1) : b = 1 / a :=
by rw [eq_inv_of_mul_eq_one_right h, one_div]
@[to_additive] lemma eq_of_div_eq_one (h : a / b = 1) : a = b :=
inv_injective $ inv_eq_of_mul_eq_one_right $ by rwa ←div_eq_mul_inv
@[to_additive] lemma div_ne_one_of_ne : a ≠ b → a / b ≠ 1 := mt eq_of_div_eq_one
variables (a b c)
@[to_additive] lemma one_div_mul_one_div_rev : (1 / a) * (1 / b) = 1 / (b * a) := by simp
@[to_additive] lemma inv_div_left : a⁻¹ / b = (b * a)⁻¹ := by simp
@[simp, to_additive] lemma inv_div : (a / b)⁻¹ = b / a := by simp
@[simp, to_additive] lemma one_div_div : 1 / (a / b) = b / a := by simp
@[simp, to_additive] lemma inv_one : (1 : α)⁻¹ = 1 :=
by simpa only [one_div, inv_inv] using (inv_div (1 : α) 1).symm
@[simp, to_additive] lemma div_one : a / 1 = a := by simp
@[to_additive] lemma one_div_one : (1 : α) / 1 = 1 := div_one _
@[to_additive] lemma one_div_one_div : 1 / (1 / a) = a := by simp
variables {a b c}
@[simp, to_additive] lemma inv_eq_one : a⁻¹ = 1 ↔ a = 1 := inv_injective.eq_iff' inv_one
@[simp, to_additive] lemma one_eq_inv : 1 = a⁻¹ ↔ a = 1 := eq_comm.trans inv_eq_one
@[to_additive] lemma inv_ne_one : a⁻¹ ≠ 1 ↔ a ≠ 1 := inv_eq_one.not
@[to_additive] lemma eq_of_one_div_eq_one_div (h : 1 / a = 1 / b) : a = b :=
by rw [←one_div_one_div a, h, one_div_one_div]
variables (a b c)
-- The attributes are out of order on purpose
@[to_additive, field_simps] lemma div_div_eq_mul_div : a / (b / c) = a * c / b := by simp
@[simp, to_additive] lemma div_inv_eq_mul : a / b⁻¹ = a * b := by simp
@[to_additive] lemma div_mul_eq_div_div_swap : a / (b * c) = a / c / b :=
by simp only [mul_assoc, mul_inv_rev, div_eq_mul_inv]
end division_monoid
lemma bit0_neg [subtraction_monoid α] (a : α) : bit0 (-a) = -bit0 a := (neg_add_rev _ _).symm
section division_comm_monoid
variables [division_comm_monoid α] (a b c d : α)
local attribute [simp] mul_assoc mul_comm mul_left_comm div_eq_mul_inv
@[to_additive neg_add] lemma mul_inv : (a * b)⁻¹ = a⁻¹ * b⁻¹ := by simp
@[to_additive] lemma inv_div' : (a / b)⁻¹ = a⁻¹ / b⁻¹ := by simp
@[to_additive] lemma div_eq_inv_mul : a / b = b⁻¹ * a := by simp
@[to_additive] lemma inv_mul_eq_div : a⁻¹ * b = b / a := by simp
@[to_additive] lemma inv_mul' : (a * b)⁻¹ = a⁻¹ / b := by simp
@[simp, to_additive] lemma inv_div_inv : (a⁻¹ / b⁻¹) = b / a := by simp
@[to_additive] lemma inv_inv_div_inv : (a⁻¹ / b⁻¹)⁻¹ = a / b := by simp
@[to_additive] lemma one_div_mul_one_div : (1 / a) * (1 / b) = 1 / (a * b) := by simp
@[to_additive] lemma div_right_comm : a / b / c = a / c / b := by simp
@[to_additive, field_simps] lemma div_div : a / b / c = a / (b * c) := by simp
@[to_additive] lemma div_mul : a / b * c = a / (b / c) := by simp
@[to_additive] lemma mul_div_left_comm : a * (b / c) = b * (a / c) := by simp
@[to_additive] lemma mul_div_right_comm : a * b / c = a / c * b := by simp
@[to_additive] lemma div_mul_eq_div_div : a / (b * c) = a / b / c := by simp
@[to_additive, field_simps] lemma div_mul_eq_mul_div : a / b * c = a * c / b := by simp
@[to_additive] lemma mul_comm_div : a / b * c = a * (c / b) := by simp
@[to_additive] lemma div_mul_comm : a / b * c = c / b * a := by simp
@[to_additive] lemma div_mul_eq_div_mul_one_div : a / (b * c) = (a / b) * (1 / c) := by simp
@[to_additive] lemma div_div_div_eq : a / b / (c / d) = a * d / (b * c) := by simp
@[to_additive] lemma div_div_div_comm : a / b / (c / d) = a / c / (b / d) := by simp
@[to_additive] lemma div_mul_div_comm : a / b * (c / d) = a * c / (b * d) := by simp
@[to_additive] lemma mul_div_mul_comm : a * b / (c * d) = a / c * (b / d) := by simp
end division_comm_monoid
section group
variables [group G] {a b c d : G}
@[simp, to_additive] theorem div_eq_inv_self : a / b = b⁻¹ ↔ a = 1 :=
by rw [div_eq_mul_inv, mul_left_eq_self]
@[to_additive]
theorem mul_left_surjective (a : G) : function.surjective ((*) a) :=
λ x, ⟨a⁻¹ * x, mul_inv_cancel_left a x⟩
@[to_additive]
theorem mul_right_surjective (a : G) : function.surjective (λ x, x * a) :=
λ x, ⟨x * a⁻¹, inv_mul_cancel_right x a⟩
@[to_additive]
lemma eq_mul_inv_of_mul_eq (h : a * c = b) : a = b * c⁻¹ :=
by simp [h.symm]
@[to_additive]
lemma eq_inv_mul_of_mul_eq (h : b * a = c) : a = b⁻¹ * c :=
by simp [h.symm]
@[to_additive]
lemma inv_mul_eq_of_eq_mul (h : b = a * c) : a⁻¹ * b = c :=
by simp [h]
@[to_additive]
lemma mul_inv_eq_of_eq_mul (h : a = c * b) : a * b⁻¹ = c :=
by simp [h]
@[to_additive]
lemma eq_mul_of_mul_inv_eq (h : a * c⁻¹ = b) : a = b * c :=
by simp [h.symm]
@[to_additive]
lemma eq_mul_of_inv_mul_eq (h : b⁻¹ * a = c) : a = b * c :=
by simp [h.symm, mul_inv_cancel_left]
@[to_additive]
lemma mul_eq_of_eq_inv_mul (h : b = a⁻¹ * c) : a * b = c :=
by rw [h, mul_inv_cancel_left]
@[to_additive]
lemma mul_eq_of_eq_mul_inv (h : a = c * b⁻¹) : a * b = c :=
by simp [h]
@[to_additive]
theorem mul_eq_one_iff_eq_inv : a * b = 1 ↔ a = b⁻¹ :=
⟨eq_inv_of_mul_eq_one_left, λ h, by rw [h, mul_left_inv]⟩
@[to_additive]
theorem mul_eq_one_iff_inv_eq : a * b = 1 ↔ a⁻¹ = b :=
by rw [mul_eq_one_iff_eq_inv, eq_inv_iff_eq_inv, eq_comm]
@[to_additive]
theorem eq_inv_iff_mul_eq_one : a = b⁻¹ ↔ a * b = 1 :=
mul_eq_one_iff_eq_inv.symm
@[to_additive]
theorem inv_eq_iff_mul_eq_one : a⁻¹ = b ↔ a * b = 1 :=
mul_eq_one_iff_inv_eq.symm
@[to_additive]
theorem eq_mul_inv_iff_mul_eq : a = b * c⁻¹ ↔ a * c = b :=
⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩
@[to_additive]
theorem eq_inv_mul_iff_mul_eq : a = b⁻¹ * c ↔ b * a = c :=
⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩
@[to_additive]
theorem inv_mul_eq_iff_eq_mul : a⁻¹ * b = c ↔ b = a * c :=
⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩
@[to_additive]
theorem mul_inv_eq_iff_eq_mul : a * b⁻¹ = c ↔ a = c * b :=
⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩
@[to_additive]
theorem mul_inv_eq_one : a * b⁻¹ = 1 ↔ a = b :=
by rw [mul_eq_one_iff_eq_inv, inv_inv]
@[to_additive]
theorem inv_mul_eq_one : a⁻¹ * b = 1 ↔ a = b :=
by rw [mul_eq_one_iff_eq_inv, inv_inj]
@[to_additive]
lemma div_left_injective : function.injective (λ a, a / b) :=
by simpa only [div_eq_mul_inv] using λ a a' h, mul_left_injective (b⁻¹) h
@[to_additive]
lemma div_right_injective : function.injective (λ a, b / a) :=
by simpa only [div_eq_mul_inv] using λ a a' h, inv_injective (mul_right_injective b h)
@[simp, to_additive sub_add_cancel]
lemma div_mul_cancel' (a b : G) : a / b * b = a :=
by rw [div_eq_mul_inv, inv_mul_cancel_right a b]
@[simp, to_additive sub_self]
lemma div_self' (a : G) : a / a = 1 :=
by rw [div_eq_mul_inv, mul_right_inv a]
@[simp, to_additive add_sub_cancel]
lemma mul_div_cancel'' (a b : G) : a * b / b = a :=
by rw [div_eq_mul_inv, mul_inv_cancel_right a b]
@[simp, to_additive]
lemma mul_div_mul_right_eq_div (a b c : G) : (a * c) / (b * c) = a / b :=
by rw [div_mul_eq_div_div_swap]; simp only [mul_left_inj, eq_self_iff_true, mul_div_cancel'']
@[to_additive eq_sub_of_add_eq]
lemma eq_div_of_mul_eq' (h : a * c = b) : a = b / c :=
by simp [← h]
@[to_additive sub_eq_of_eq_add]
lemma div_eq_of_eq_mul'' (h : a = c * b) : a / b = c :=
by simp [h]
@[to_additive]
lemma eq_mul_of_div_eq (h : a / c = b) : a = b * c :=
by simp [← h]
@[to_additive]
lemma mul_eq_of_eq_div (h : a = c / b) : a * b = c :=
by simp [h]
@[simp, to_additive]
lemma div_right_inj : a / b = a / c ↔ b = c :=
div_right_injective.eq_iff
@[simp, to_additive]
lemma div_left_inj : b / a = c / a ↔ b = c :=
by { rw [div_eq_mul_inv, div_eq_mul_inv], exact mul_left_inj _ }
@[simp, to_additive sub_add_sub_cancel]
lemma div_mul_div_cancel' (a b c : G) : (a / b) * (b / c) = a / c :=
by rw [← mul_div_assoc, div_mul_cancel']
@[simp, to_additive sub_sub_sub_cancel_right]
lemma div_div_div_cancel_right' (a b c : G) : (a / c) / (b / c) = a / b :=
by rw [← inv_div c b, div_inv_eq_mul, div_mul_div_cancel']
@[to_additive]
theorem div_eq_one : a / b = 1 ↔ a = b :=
⟨eq_of_div_eq_one, λ h, by rw [h, div_self']⟩
alias div_eq_one ↔ _ div_eq_one_of_eq
alias sub_eq_zero ↔ _ sub_eq_zero_of_eq
@[to_additive]
theorem div_ne_one : a / b ≠ 1 ↔ a ≠ b :=
not_congr div_eq_one
@[simp, to_additive]
theorem div_eq_self : a / b = a ↔ b = 1 :=
by rw [div_eq_mul_inv, mul_right_eq_self, inv_eq_one]
@[to_additive eq_sub_iff_add_eq]
theorem eq_div_iff_mul_eq' : a = b / c ↔ a * c = b :=
by rw [div_eq_mul_inv, eq_mul_inv_iff_mul_eq]
@[to_additive]
theorem div_eq_iff_eq_mul : a / b = c ↔ a = c * b :=
by rw [div_eq_mul_inv, mul_inv_eq_iff_eq_mul]
@[to_additive]
theorem eq_iff_eq_of_div_eq_div (H : a / b = c / d) : a = b ↔ c = d :=
by rw [← div_eq_one, H, div_eq_one]
@[to_additive]
theorem left_inverse_div_mul_left (c : G) : function.left_inverse (λ x, x / c) (λ x, x * c) :=
assume x, mul_div_cancel'' x c
@[to_additive]
theorem left_inverse_mul_left_div (c : G) : function.left_inverse (λ x, x * c) (λ x, x / c) :=
assume x, div_mul_cancel' x c
@[to_additive]
theorem left_inverse_mul_right_inv_mul (c : G) :
function.left_inverse (λ x, c * x) (λ x, c⁻¹ * x) :=
assume x, mul_inv_cancel_left c x
@[to_additive]
theorem left_inverse_inv_mul_mul_right (c : G) :
function.left_inverse (λ x, c⁻¹ * x) (λ x, c * x) :=
assume x, inv_mul_cancel_left c x
@[to_additive]
lemma exists_npow_eq_one_of_zpow_eq_one {n : ℤ} (hn : n ≠ 0) {x : G} (h : x ^ n = 1) :
∃ n : ℕ, 0 < n ∧ x ^ n = 1 :=
begin
cases n with n n,
{ rw zpow_of_nat at h,
refine ⟨n, nat.pos_of_ne_zero (λ n0, hn _), h⟩, rw n0, refl },
{ rw [zpow_neg_succ_of_nat, inv_eq_one] at h,
refine ⟨n + 1, n.succ_pos, h⟩ }
end
end group
section comm_group
variables [comm_group G] {a b c d : G}
local attribute [simp] mul_assoc mul_comm mul_left_comm div_eq_mul_inv
@[to_additive]
lemma div_eq_of_eq_mul' {a b c : G} (h : a = b * c) : a / b = c :=
by rw [h, div_eq_mul_inv, mul_comm, inv_mul_cancel_left]
@[simp, to_additive]
lemma mul_div_mul_left_eq_div (a b c : G) : (c * a) / (c * b) = a / b :=
by simp
@[to_additive eq_sub_of_add_eq']
lemma eq_div_of_mul_eq'' (h : c * a = b) : a = b / c :=
by simp [h.symm]
@[to_additive]
lemma eq_mul_of_div_eq' (h : a / b = c) : a = b * c :=
by simp [h.symm]
@[to_additive]
lemma mul_eq_of_eq_div' (h : b = c / a) : a * b = c :=
begin simp [h], rw [mul_comm c, mul_inv_cancel_left] end
@[to_additive sub_sub_self]
lemma div_div_self' (a b : G) : a / (a / b) = b :=
by simpa using mul_inv_cancel_left a b
@[to_additive]
lemma div_eq_div_mul_div (a b c : G) : a / b = c / b * (a / c) := by simp [mul_left_comm c]
@[simp, to_additive]
lemma div_div_cancel (a b : G) : a / (a / b) = b := div_div_self' a b
@[simp, to_additive]
lemma div_div_cancel_left (a b : G) : a / b / a = b⁻¹ := by simp
@[to_additive eq_sub_iff_add_eq']
lemma eq_div_iff_mul_eq'' : a = b / c ↔ c * a = b :=
by rw [eq_div_iff_mul_eq', mul_comm]
@[to_additive]
lemma div_eq_iff_eq_mul' : a / b = c ↔ a = b * c :=
by rw [div_eq_iff_eq_mul, mul_comm]
@[simp, to_additive add_sub_cancel']
lemma mul_div_cancel''' (a b : G) : a * b / a = b := by rw [div_eq_inv_mul, inv_mul_cancel_left]
@[simp, to_additive]
lemma mul_div_cancel'_right (a b : G) : a * (b / a) = b :=
by rw [← mul_div_assoc, mul_div_cancel''']
@[simp, to_additive sub_add_cancel']
lemma div_mul_cancel'' (a b : G) : a / (a * b) = b⁻¹ :=
by rw [← inv_div, mul_div_cancel''']
-- This lemma is in the `simp` set under the name `mul_inv_cancel_comm_assoc`,
-- along with the additive version `add_neg_cancel_comm_assoc`,
-- defined in `algebra/group/commute`
@[to_additive]
lemma mul_mul_inv_cancel'_right (a b : G) : a * (b * a⁻¹) = b :=
by rw [← div_eq_mul_inv, mul_div_cancel'_right a b]
@[simp, to_additive]
lemma mul_mul_div_cancel (a b c : G) : (a * c) * (b / c) = a * b :=
by rw [mul_assoc, mul_div_cancel'_right]
@[simp, to_additive]
lemma div_mul_mul_cancel (a b c : G) : (a / c) * (b * c) = a * b :=
by rw [mul_left_comm, div_mul_cancel', mul_comm]
@[simp, to_additive sub_add_sub_cancel']
lemma div_mul_div_cancel'' (a b c : G) : (a / b) * (c / a) = c / b :=
by rw mul_comm; apply div_mul_div_cancel'
@[simp, to_additive]
lemma mul_div_div_cancel (a b c : G) : (a * b) / (a / c) = b * c :=
by rw [← div_mul, mul_div_cancel''']
@[simp, to_additive]
lemma div_div_div_cancel_left (a b c : G) : (c / a) / (c / b) = b / a :=
by rw [← inv_div b c, div_inv_eq_mul, mul_comm, div_mul_div_cancel']
@[to_additive] lemma div_eq_div_iff_mul_eq_mul : a / b = c / d ↔ a * d = c * b :=
begin
rw [div_eq_iff_eq_mul, div_mul_eq_mul_div, eq_comm, div_eq_iff_eq_mul'],
simp only [mul_comm, eq_comm]
end
@[to_additive] lemma div_eq_div_iff_div_eq_div : a / b = c / d ↔ a / c = b / d :=
by rw [div_eq_iff_eq_mul, div_mul_eq_mul_div, div_eq_iff_eq_mul', mul_div_assoc]
end comm_group
section subtraction_comm_monoid
variables {M : Type u} [subtraction_comm_monoid M]
lemma bit0_sub (a b : M) : bit0 (a - b) = bit0 a - bit0 b :=
sub_add_sub_comm _ _ _ _
lemma bit1_sub [has_one M] (a b : M) : bit1 (a - b) = bit1 a - bit0 b :=
(congr_arg (+ (1 : M)) $ bit0_sub a b : _).trans $ sub_add_eq_add_sub _ _ _
end subtraction_comm_monoid
section commutator
/-- The commutator of two elements `g₁` and `g₂`. -/
instance commutator_element {G : Type*} [group G] : has_bracket G G :=
⟨λ g₁ g₂, g₁ * g₂ * g₁⁻¹ * g₂⁻¹⟩
lemma commutator_element_def {G : Type*} [group G] (g₁ g₂ : G) :
⁅g₁, g₂⁆ = g₁ * g₂ * g₁⁻¹ * g₂⁻¹ := rfl
end commutator
|
40c679e47efa163999df1d2d25c49f20df2d1727 | d0f9af2b0ace5ce352570d61b09019c8ef4a3b96 | /hw8/hw8_turn_in/hw8_valid_reasoning_formulae.lean | 27f7fcfeba30da7f1201893c61142fec82b08694 | [] | no_license | jngo13/Discrete-Mathematics | 8671540ef2da7c75915d32332dd20c02f001474e | bf674a866e61f60e6e6d128df85fa73819091787 | refs/heads/master | 1,675,615,657,924 | 1,609,142,011,000 | 1,609,142,011,000 | 267,190,341 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,412 | lean | /-
Justin Ngo
jmn4fms
4/5/20
Sullivan 2102-001
-/
import .propositional_logic_syntax_and_semantics
open pExp
/-
Your task: We give you propositions in zero to
three variables (P, Q, and, R). You must decide
whether each is valid or not. To do this, you
must use pEval to evaluate any given propositions
under each of the possible interpretations of its
variables.
To test a 1-variable proposition will require
two interpretations; for 2 variables, four; for
three, eight, etc. In general, there are 2^n,
where n is the number of variables. Adding one
variable geometrically increases the number of
possible interpretations.
-/
/-
Here are the three propositional variables, P
Q, and R that we'll use to write propositions
and test them here.
-/
def P := pVar (var.mk 0)
def Q := pVar (var.mk 1)
def R := pVar (var.mk 2)
/-
Below is a list of formulae, many of which
express fundamental rules of valid reasoning.
We also state several fallacies: desceptively
faulty, which is to say invalid, non-rules of
logically sound reasoning.
Your job is to classify each as valid or not
valid. To do this you will produce a truth
table for each one. It is good that we have
an automatic evaluator as that makes the job
easy. For each of the formulae that's not valid,
give an English language counterexample: some
scenario that shows that the formula is
not always true.
To do this assignment, evaluate each proposition
under each of its possible interpretations. Each
interpretation defines the inputs in one row of
the truth table, and the result of applying pEval
to the expression under that interpetation, gives
you the truth value of the proposition under that
interpretation.
A given proposition will be valid if it evalutes
to true under *all* of its interpretations. You
have to define some interpretations, then apply
the pEval function to the given proposition for
each of its possible interpretation.axioms
Some of the formulae contain only one variable.
We use P. You will need two interpretations in
this cases. Call them Pt and Pf. A one-variable
propositions has two interpretations, and thus
two rows in its truth table.
Some formula have two variables. We call them
P and Q. Now there are four interpretations. Call
them PtQt, PtQf, PfQt, PfQf.
Finally, some of the propositions we give you have
three variables. Here we have eight interpretations
under which to evaluate each such proposition. You
can give them names such as PtQtRt, PtQtRf, etc.
If we look at the sequence of t's and f's in each
of these names and rewrite t's as ones f's as zeros,
then we see that our names basically count down from
2^n-1 to zero in binary notation.
PQR
ttt 111 7 2^3-1
ttf 110 6
tft 101 5
tff 100 4
ftt 011 3
ftf 010 2
fft 001 1
fff 000 0
So, for each proposition, evaluate it under each
of its possible interpretations; then look at the
list of resulting truth values. If all are true,
then you have proved that the proposition is valid.
If there is at least one interpretation under which
the proposition evaluates to true, it's decidable.
If there is no interpretation that makes it true,
then it is unsatisfiable.
-/
/- # 1.
Define three sets of interpretations, one for each
"arity" of proposition (1-, 2-, or 3 variables), as
explained above.
-/
-- Answer
-- Set 1
def Pt: var→ bool
| (var.mk 0) := tt
| _ := ff
def Pf: var→ bool
| (var.mk 0) := ff
| _ := tt
--Set 2
def PtQt: var→ bool
| (var.mk 0) := tt
| (var.mk 1) := tt
| _ := ff
def PtQf: var→ bool
| (var.mk 0) := tt
| (var.mk 1) := ff
| _ := ff
def PfQt: var→ bool
| (var.mk 0) := ff
| (var.mk 1) := tt
| _ := ff
def PfQf: var→ bool
| (var.mk 0) := ff
| (var.mk 1) := ff
| _ := ff
-- Set 3
def PtQtRt: var→ bool
| (var.mk 0) := tt
| (var.mk 1) := tt
| (var.mk 2) := tt
| _ := ff
def PtQtRf: var→ bool
| (var.mk 0) := tt
| (var.mk 1) := tt
| (var.mk 2) := ff
| _ := ff
def PtQfRt: var→ bool
| (var.mk 0) := tt
| (var.mk 1) := ff
| (var.mk 2) := tt
| _ := ff
def PtQfRf: var→ bool
| (var.mk 0) := tt
| (var.mk 1) := ff
| (var.mk 2) := ff
| _ := ff
def PfQtRt: var→ bool
| (var.mk 0) := ff
| (var.mk 1) := tt
| (var.mk 2) := tt
| _ := ff
def PfQtRf: var→ bool
| (var.mk 0) := ff
| (var.mk 1) := tt
| (var.mk 2) := ff
| _ := ff
def PfQfRt: var→ bool
| (var.mk 0) := ff
| (var.mk 1) := ff
| (var.mk 2) := tt
| _ := ff
def PfQfRf: var→ bool
| (var.mk 0) := ff
| (var.mk 1) := ff
| (var.mk 2) := ff
| _ := ff
/-
2. Use pEval to evaluate each of the following formulae
under each of its possible interpretations. The use the
resulting list of Boolean truth values to decide which
properties the proposition has. Here are the propositions
for which you are to decide the properties it has.
-/
def true_intro : pExp := pTrue
#eval pEval true_intro Pt
#eval pEval true_intro Pf
-- valid
def false_elim := pFalse >> P
#eval pEval false_elim Pt
#eval pEval false_elim Pf
-- valid
def true_imp := pTrue >> P
#eval pEval true_imp Pt
#eval pEval true_imp Pf
-- satisfiable
-- TRUE if it is raining outside, then the streets are wet
-- FALSE if the streets are wet, then it is raining outside
-- the streets could be wet for another reason
def and_intro := P >> Q >> (P ∧ Q)
#eval pEval and_intro PtQt
#eval pEval and_intro PtQf
#eval pEval and_intro PfQt
#eval pEval and_intro PfQf
-- valid
def and_elim_left := (P ∧ Q) >> P
#eval pEval and_elim_left PtQt
#eval pEval and_elim_left PtQf
#eval pEval and_elim_left PfQt
#eval pEval and_elim_left PfQf
-- valid
def and_elim_right := (P ∧ Q) >> Q
#eval pEval and_elim_right PtQt
#eval pEval and_elim_right PtQf
#eval pEval and_elim_right PfQt
#eval pEval and_elim_right PfQf
-- valid
def or_intro_left := P >> (P ∨ Q)
#eval pEval or_intro_left PtQt
#eval pEval or_intro_left PtQf
#eval pEval or_intro_left PfQt
#eval pEval or_intro_left PfQf
-- valid
def or_intro_right := Q >> (P ∨ Q)
#eval pEval or_intro_right PtQt
#eval pEval or_intro_right PtQf
#eval pEval or_intro_right PfQt
#eval pEval or_intro_right PfQf
-- valid
def or_elim := (P ∨ Q) >> (P >> R) >> (Q >> R) >> R
#eval pEval or_elim PtQtRt
#eval pEval or_elim PtQtRf
#eval pEval or_elim PtQfRt
#eval pEval or_elim PtQfRf
#eval pEval or_elim PfQtRt
#eval pEval or_elim PfQtRf
#eval pEval or_elim PfQfRt
#eval pEval or_elim PfQfRf
-- valid
def iff_intro := (P >> Q) >> (Q >> P) >> (P ↔ Q)
#eval pEval iff_intro PtQt
#eval pEval iff_intro PtQf
#eval pEval iff_intro PfQt
#eval pEval iff_intro PfQf
-- valid
def iff_intro' := ((P >> Q) ∧ (Q >> P)) >> (P ↔ Q)
#eval pEval iff_intro' PtQt
#eval pEval iff_intro' PtQf
#eval pEval iff_intro' PfQt
#eval pEval iff_intro' PfQf
-- valid
def iff_elim_left := (P ↔ Q) >> (P >> Q)
#eval pEval iff_elim_left PtQt
#eval pEval iff_elim_left PtQf
#eval pEval iff_elim_left PfQt
#eval pEval iff_elim_left PfQf
-- valid
def iff_elim_right := (P ↔ Q) >> (Q >> P)
#eval pEval iff_elim_right PtQt
#eval pEval iff_elim_right PtQf
#eval pEval iff_elim_right PfQt
#eval pEval iff_elim_right PfQf
-- valid
def arrow_elim := (P >> Q) >> (P >> Q)
#eval pEval arrow_elim PtQt
#eval pEval arrow_elim PtQf
#eval pEval arrow_elim PfQt
#eval pEval arrow_elim PfQf
def resolution := (P ∨ Q) >> (¬ Q ∨ R) >> (P ∨ R)
#eval pEval resolution PtQtRt
#eval pEval resolution PtQtRf
#eval pEval resolution PtQfRt
#eval pEval resolution PtQfRf
#eval pEval resolution PfQtRt
#eval pEval resolution PfQtRf
#eval pEval resolution PfQfRt
#eval pEval resolution PfQfRf
-- valid
def unit_resolution := (P ∨ Q) >> ((¬ Q) >> P)
#eval pEval unit_resolution PtQt
#eval pEval unit_resolution PtQf
#eval pEval unit_resolution PfQt
#eval pEval unit_resolution PfQf
-- valid
def syllogism := (P >> Q) >> (Q >> R) >> (P >> R)
#eval pEval syllogism PtQtRt
#eval pEval syllogism PtQtRf
#eval pEval syllogism PtQfRt
#eval pEval syllogism PtQfRf
#eval pEval syllogism PfQtRt
#eval pEval syllogism PfQtRf
#eval pEval syllogism PfQfRt
#eval pEval syllogism PfQfRf
-- valid
def modus_tollens := (P >> Q) >> (¬ Q >> ¬ P)
#eval pEval modus_tollens PtQt
#eval pEval modus_tollens PtQf
#eval pEval modus_tollens PfQt
#eval pEval modus_tollens PfQf
-- valid
def neg_elim := (¬ ¬ P) >> P
#eval pEval neg_elim Pt
#eval pEval neg_elim Pf
-- valid
def excluded_middle := P ∨ (¬ P)
#eval pEval excluded_middle Pt
#eval pEval excluded_middle Pf
-- valid
def neg_intro := (P >> pFalse) >> (¬ P)
#eval pEval neg_intro Pt
#eval pEval neg_intro Pf
-- valid
def affirm_consequence := (P >> Q) >> (Q >> P)
#eval pEval affirm_consequence PtQt
#eval pEval affirm_consequence PtQf
#eval pEval affirm_consequence PfQt
#eval pEval affirm_consequence PfQf
-- satisfiable
-- if it is NOT raining outside, then the streets can be wet = TRUE
-- if the streets are wet, then it is NOT raining outside = FALSE
-- true >> false = false
def affirm_disjunct := (P ∨ Q) >> (P >> ¬ Q)
#eval pEval affirm_disjunct PtQt
#eval pEval affirm_disjunct PtQf
#eval pEval affirm_disjunct PfQt
#eval pEval affirm_disjunct PfQf
-- satisfiable
-- if it is raining outside OR the streets are wet = TRUE
-- if if its raining outside, then the streets are NOT wet = FALSE
-- true >> false = false
def deny_antecedent := (P >> Q) >> (¬ P >> ¬ Q)
#eval pEval deny_antecedent PtQt
#eval pEval deny_antecedent PtQf
#eval pEval deny_antecedent PfQt
#eval pEval deny_antecedent PfQf
-- satisfiable
-- if it is raining outside the streets are wet = TRUE
-- if it is NOT raining outside, then the streets can NOT be wet = FALSE
-- true >> false = false
axioms A B : Prop
#check A ∨ B ∧ B ∨ A
#check (A ∨ B) ∧ (B ∨ A)
#check A ∨ (B ∧ B) ∨ A
#check A ∨ B → B ∨ A
#check (A ∨ B) → (B ∨ A)
#check A ∨ (B → B) ∨ A
#check A → B ↔ B → A
#check (A → B) ↔ (B → A)
#check A → (B ↔ B) → A
#check A ↔ B ∨ B ↔ A
#check (A ↔ B) ∨ (B ↔ A)
#check A ↔ (B ∨ B) ↔ A
#check A → B ∨ B → A
#check (A → B) ∨ (B → A)
#check A → (B ∨ B) → A
/-
Study the valid rules and learn their names.
These rules, which, here, we are validating
"semantically" (by the method of truth tables)
will become fundamental "rules of inference",
for reasoning "syntactically" when we get to
predicate logic. There is not much memorizing
in this class, but this is one case where you
will find it important to learn the names and
definitions of these rules.
-/ |
b5649c9920004e2e909f57b85d159a1c97599707 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/1760.lean | 806a155dccab653819772de7a1f45f898d96bff6 | [
"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 | 117 | lean | -- should run in linear time
#check [[[[[[[[[[[[[[[[[[[[[[[[
#check (((((((((((((((((((((((())))))))))))))))))))))))
|
06f126814feed9b677b5336752d1917385ca41e9 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Meta/Closure.lean | 7ac2972f4a1b77793c349b9e3914da0d2af3b51f | [
"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 | 15,448 | 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.MetavarContext
import Lean.Environment
import Lean.Util.FoldConsts
import Lean.Meta.Basic
import Lean.Meta.Check
/-!
This module provides functions for "closing" open terms and
creating auxiliary definitions. Here, we say a term is "open" if
it contains free/meta-variables.
The "closure" is performed by lambda abstracting the
free/meta-variables. Recall that in dependent type theory
lambda abstracting a let-variable may produce type incorrect terms.
For example, given the context
```lean
(n : Nat := 20)
(x : Vector α n)
(y : Vector α 20)
```
the term `x = y` is correct. However, its closure using lambda abstractions
is not.
```lean
fun (n : Nat) (x : Vector α n) (y : Vector α 20) => x = y
```
A previous version of this module would address this issue by
always use let-expressions to abstract let-vars. In the example above,
it would produce
```lean
let n : Nat := 20; fun (x : Vector α n) (y : Vector α 20) => x = y
```
This approach produces correct result, but produces unsatisfactory
results when we want to create auxiliary definitions.
For example, consider the context
```lean
(x : Nat)
(y : Nat := fact x)
```
and the term `h (g y)`, now suppose we want to create an auxiliary definition for `y`.
The previous version of this module would compute the auxiliary definition
```lean
def aux := fun (x : Nat) => let y : Nat := fact x; h (g y)
```
and would return the term `aux x` as a substitute for `h (g y)`.
This is correct, but we will re-evaluate `fact x` whenever we use `aux`.
In this module, we produce
```lean
def aux := fun (y : Nat) => h (g y)
```
Note that in this particular case, it is safe to lambda abstract the let-varible `y`.
This module uses the following approach to decide whether it is safe or not to lambda
abstract a let-variable.
1) We enable zeta-expansion tracking in `MetaM`. That is, whenever we perform type checking
if a let-variable needs to zeta expanded, we store it in the set `zetaFVarIds`.
We say a let-variable is zeta expanded when we replace it with its value.
2) We use the `MetaM` type checker `check` to type check the expression we want to close,
and the type of the binders.
3) If a let-variable is not in `zetaFVarIds`, we lambda abstract it.
Remark: We still use let-expressions for let-variables in `zetaFVarIds`, but we move the
`let` inside the lambdas. The idea is to make sure the auxiliary definition does not have
an interleaving of `lambda` and `let` expressions. Thus, if the let-variable occurs in
the type of one of the lambdas, we simply zeta-expand it there.
As a final example consider the context
```lean
(x_1 : Nat)
(x_2 : Nat)
(x_3 : Nat)
(x : Nat := fact (10 + x_1 + x_2 + x_3))
(ty : Type := Nat → Nat)
(f : ty := fun x => x)
(n : Nat := 20)
(z : f 10)
```
and we use this module to compute an auxiliary definition for the term
```lean
(let y : { v : Nat // v = n } := ⟨20, rfl⟩; y.1 + n + f x, z + 10)
```
we obtain
```lean
def aux (x : Nat) (f : Nat → Nat) (z : Nat) : Nat×Nat :=
let n : Nat := 20;
(let y : {v // v=n} := {val := 20, property := ex._proof_1}; y.val+n+f x, z+10)
```
BTW, this module also provides the `zeta : Bool` flag. When set to true, it
expands all let-variables occurring in the target expression.
-/
namespace Lean.Meta
namespace Closure
structure ToProcessElement where
fvarId : FVarId
newFVarId : FVarId
deriving Inhabited
structure Context where
zeta : Bool
structure State where
visitedLevel : LevelMap Level := {}
visitedExpr : ExprStructMap Expr := {}
levelParams : Array Name := #[]
nextLevelIdx : Nat := 1
levelArgs : Array Level := #[]
newLocalDecls : Array LocalDecl := #[]
newLocalDeclsForMVars : Array LocalDecl := #[]
newLetDecls : Array LocalDecl := #[]
nextExprIdx : Nat := 1
exprMVarArgs : Array Expr := #[]
exprFVarArgs : Array Expr := #[]
toProcess : Array ToProcessElement := #[]
abbrev ClosureM := ReaderT Context $ StateRefT State MetaM
@[inline] def visitLevel (f : Level → ClosureM Level) (u : Level) : ClosureM Level := do
if !u.hasMVar && !u.hasParam then
pure u
else
let s ← get
match s.visitedLevel.find? u with
| some v => pure v
| none => do
let v ← f u
modify fun s => { s with visitedLevel := s.visitedLevel.insert u v }
pure v
@[inline] def visitExpr (f : Expr → ClosureM Expr) (e : Expr) : ClosureM Expr := do
if !e.hasLevelParam && !e.hasFVar && !e.hasMVar then
pure e
else
let s ← get
match s.visitedExpr.find? e with
| some r => pure r
| none =>
let r ← f e
modify fun s => { s with visitedExpr := s.visitedExpr.insert e r }
pure r
def mkNewLevelParam (u : Level) : ClosureM Level := do
let s ← get
let p := (`u).appendIndexAfter s.nextLevelIdx
modify fun s => { s with levelParams := s.levelParams.push p, nextLevelIdx := s.nextLevelIdx + 1, levelArgs := s.levelArgs.push u }
pure $ mkLevelParam p
partial def collectLevelAux : Level → ClosureM Level
| u@(Level.succ v) => return u.updateSucc! (← visitLevel collectLevelAux v)
| u@(Level.max v w) => return u.updateMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w)
| u@(Level.imax v w) => return u.updateIMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w)
| u@(Level.mvar ..) => mkNewLevelParam u
| u@(Level.param ..) => mkNewLevelParam u
| u@(Level.zero) => pure u
def collectLevel (u : Level) : ClosureM Level := do
-- u ← instantiateLevelMVars u
visitLevel collectLevelAux u
def preprocess (e : Expr) : ClosureM Expr := do
let e ← instantiateMVars e
let ctx ← read
-- If we are not zeta-expanding let-decls, then we use `check` to find
-- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect.
if !ctx.zeta then
check e
pure e
/--
Remark: This method does not guarantee unique user names.
The correctness of the procedure does not rely on unique user names.
Recall that the pretty printer takes care of unintended collisions. -/
def mkNextUserName : ClosureM Name := do
let s ← get
let n := (`_x).appendIndexAfter s.nextExprIdx
modify fun s => { s with nextExprIdx := s.nextExprIdx + 1 }
pure n
def pushToProcess (elem : ToProcessElement) : ClosureM Unit :=
modify fun s => { s with toProcess := s.toProcess.push elem }
partial def collectExprAux (e : Expr) : ClosureM Expr := do
let collect (e : Expr) := visitExpr collectExprAux e
match e with
| Expr.proj _ _ s => return e.updateProj! (← collect s)
| Expr.forallE _ d b _ => return e.updateForallE! (← collect d) (← collect b)
| Expr.lam _ d b _ => return e.updateLambdaE! (← collect d) (← collect b)
| Expr.letE _ t v b _ => return e.updateLet! (← collect t) (← collect v) (← collect b)
| Expr.app f a => return e.updateApp! (← collect f) (← collect a)
| Expr.mdata _ b => return e.updateMData! (← collect b)
| Expr.sort u => return e.updateSort! (← collectLevel u)
| Expr.const _ us => return e.updateConst! (← us.mapM collectLevel)
| Expr.mvar mvarId =>
let mvarDecl ← mvarId.getDecl
let type ← preprocess mvarDecl.type
let type ← collect type
let newFVarId ← mkFreshFVarId
let userName ← mkNextUserName
modify fun s => { s with
newLocalDeclsForMVars := s.newLocalDeclsForMVars.push $ .cdecl default newFVarId userName type .default .default,
exprMVarArgs := s.exprMVarArgs.push e
}
return mkFVar newFVarId
| Expr.fvar fvarId =>
match (← read).zeta, (← fvarId.getValue?) with
| true, some value => collect (← preprocess value)
| _, _ =>
let newFVarId ← mkFreshFVarId
pushToProcess ⟨fvarId, newFVarId⟩
return mkFVar newFVarId
| e => pure e
def collectExpr (e : Expr) : ClosureM Expr := do
let e ← preprocess e
visitExpr collectExprAux e
partial def pickNextToProcessAux (lctx : LocalContext) (i : Nat) (toProcess : Array ToProcessElement) (elem : ToProcessElement)
: ToProcessElement × Array ToProcessElement :=
if h : i < toProcess.size then
let elem' := toProcess.get ⟨i, h⟩
if (lctx.get! elem.fvarId).index < (lctx.get! elem'.fvarId).index then
pickNextToProcessAux lctx (i+1) (toProcess.set ⟨i, h⟩ elem) elem'
else
pickNextToProcessAux lctx (i+1) toProcess elem
else
(elem, toProcess)
def pickNextToProcess? : ClosureM (Option ToProcessElement) := do
let lctx ← getLCtx
let s ← get
if s.toProcess.isEmpty then
pure none
else
modifyGet fun s =>
let elem := s.toProcess.back
let toProcess := s.toProcess.pop
let (elem, toProcess) := pickNextToProcessAux lctx 0 toProcess elem
(some elem, { s with toProcess := toProcess })
def pushFVarArg (e : Expr) : ClosureM Unit :=
modify fun s => { s with exprFVarArgs := s.exprFVarArgs.push e }
def pushLocalDecl (newFVarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default) : ClosureM Unit := do
let type ← collectExpr type
modify fun s => { s with newLocalDecls := s.newLocalDecls.push <| .cdecl default newFVarId userName type bi .default }
partial def process : ClosureM Unit := do
match (← pickNextToProcess?) with
| none => pure ()
| some ⟨fvarId, newFVarId⟩ =>
match (← fvarId.getDecl) with
| .cdecl _ _ userName type bi _ =>
pushLocalDecl newFVarId userName type bi
pushFVarArg (mkFVar fvarId)
process
| .ldecl _ _ userName type val _ _ =>
let zetaFVarIds ← getZetaFVarIds
if !zetaFVarIds.contains fvarId then
/- Non-dependent let-decl
Recall that if `fvarId` is in `zetaFVarIds`, then we zeta-expanded it
during type checking (see `check` at `collectExpr`).
Our type checker may zeta-expand declarations that are not needed, but this
check is conservative, and seems to work well in practice. -/
pushLocalDecl newFVarId userName type
pushFVarArg (mkFVar fvarId)
process
else
/- Dependent let-decl -/
let type ← collectExpr type
let val ← collectExpr val
modify fun s => { s with newLetDecls := s.newLetDecls.push <| .ldecl default newFVarId userName type val false .default }
/- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of newFVarId
at `newLocalDecls` -/
modify fun s => { s with newLocalDecls := s.newLocalDecls.map (·.replaceFVarId newFVarId val) }
process
@[inline] def mkBinding (isLambda : Bool) (decls : Array LocalDecl) (b : Expr) : Expr :=
let xs := decls.map LocalDecl.toExpr
let b := b.abstract xs
decls.size.foldRev (init := b) fun i b =>
let decl := decls[i]!
match decl with
| .cdecl _ _ n ty bi _ =>
let ty := ty.abstractRange i xs
if isLambda then
Lean.mkLambda n bi ty b
else
Lean.mkForall n bi ty b
| .ldecl _ _ n ty val nonDep _ =>
if b.hasLooseBVar 0 then
let ty := ty.abstractRange i xs
let val := val.abstractRange i xs
mkLet n ty val b nonDep
else
b.lowerLooseBVars 1 1
def mkLambda (decls : Array LocalDecl) (b : Expr) : Expr :=
mkBinding true decls b
def mkForall (decls : Array LocalDecl) (b : Expr) : Expr :=
mkBinding false decls b
structure MkValueTypeClosureResult where
levelParams : Array Name
type : Expr
value : Expr
levelArgs : Array Level
exprArgs : Array Expr
def mkValueTypeClosureAux (type : Expr) (value : Expr) : ClosureM (Expr × Expr) := do
resetZetaFVarIds
withTrackingZeta do
let type ← collectExpr type
let value ← collectExpr value
process
pure (type, value)
def mkValueTypeClosure (type : Expr) (value : Expr) (zeta : Bool) : MetaM MkValueTypeClosureResult := do
let ((type, value), s) ← ((mkValueTypeClosureAux type value).run { zeta := zeta }).run {}
let newLocalDecls := s.newLocalDecls.reverse ++ s.newLocalDeclsForMVars
let newLetDecls := s.newLetDecls.reverse
let type := mkForall newLocalDecls (mkForall newLetDecls type)
let value := mkLambda newLocalDecls (mkLambda newLetDecls value)
pure {
type := type,
value := value,
levelParams := s.levelParams,
levelArgs := s.levelArgs,
exprArgs := s.exprFVarArgs.reverse ++ s.exprMVarArgs
}
end Closure
/--
Create an auxiliary definition with the given name, type and value.
The parameters `type` and `value` may contain free and meta variables.
A "closure" is computed, and a term of the form `name.{u_1 ... u_n} t_1 ... t_m` is
returned where `u_i`s are universe parameters and metavariables `type` and `value` depend on,
and `t_j`s are free and meta variables `type` and `value` depend on. -/
def mkAuxDefinition (name : Name) (type : Expr) (value : Expr) (zeta : Bool := false) (compile : Bool := true) : MetaM Expr := do
let result ← Closure.mkValueTypeClosure type value zeta
let env ← getEnv
let decl := Declaration.defnDecl {
name := name
levelParams := result.levelParams.toList
type := result.type
value := result.value
hints := ReducibilityHints.regular (getMaxHeight env result.value + 1)
safety := if env.hasUnsafe result.type || env.hasUnsafe result.value then DefinitionSafety.unsafe else DefinitionSafety.safe
}
addDecl decl
if compile then
compileDecl decl
return mkAppN (mkConst name result.levelArgs.toList) result.exprArgs
/-- Similar to `mkAuxDefinition`, but infers the type of `value`. -/
def mkAuxDefinitionFor (name : Name) (value : Expr) (zeta : Bool := false) : MetaM Expr := do
let type ← inferType value
let type := type.headBeta
mkAuxDefinition name type value (zeta := zeta)
/--
Create an auxiliary theorem with the given name, type and value. It is similar to `mkAuxDefinition`.
-/
def mkAuxTheorem (name : Name) (type : Expr) (value : Expr) (zeta : Bool := false) : MetaM Expr := do
let result ← Closure.mkValueTypeClosure type value zeta
let env ← getEnv
let decl :=
if env.hasUnsafe result.type || env.hasUnsafe result.value then
-- `result` contains unsafe code, thus we cannot use a theorem.
Declaration.defnDecl {
name
levelParams := result.levelParams.toList
type := result.type
value := result.value
hints := ReducibilityHints.opaque
safety := DefinitionSafety.unsafe
}
else
Declaration.thmDecl {
name
levelParams := result.levelParams.toList
type := result.type
value := result.value
}
addDecl decl
return mkAppN (mkConst name result.levelArgs.toList) result.exprArgs
/--
Similar to `mkAuxTheorem`, but infers the type of `value`.
-/
def mkAuxTheoremFor (name : Name) (value : Expr) (zeta : Bool := false) : MetaM Expr := do
let type ← inferType value
let type := type.headBeta
mkAuxTheorem name type value zeta
end Lean.Meta
|
66bd27895574419ab7c7aa450d0bf30c4c38fc16 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/stream/defs.lean | 01fc44fde9e398fdb740d3b9be3c6477ddfc087f | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 5,235 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
/-!
# Definition of `stream` and functions on streams
A stream `stream α` is an infinite sequence of elements of `α`. One can also think about it as an
infinite list. In this file we define `stream` and some functions that take and/or return streams.
-/
universes u v w
/-- A stream `stream α` is an infinite sequence of elements of `α`. -/
def stream (α : Type u) := nat → α
open nat
namespace stream
variables {α : Type u} {β : Type v} {δ : Type w}
/-- Prepend an element to a stream. -/
def cons (a : α) (s : stream α) : stream α :=
λ i,
match i with
| 0 := a
| succ n := s n
end
notation h :: t := cons h t
/-- Head of a stream: `stream.head s = stream.nth 0 s`. -/
def head (s : stream α) : α :=
s 0
/-- Tail of a stream: `stream.tail (h :: t) = t`. -/
def tail (s : stream α) : stream α :=
λ i, s (i+1)
/-- Drop first `n` elements of a stream. -/
def drop (n : nat) (s : stream α) : stream α :=
λ i, s (i+n)
/-- `n`-th element of a stream. -/
def nth (s : stream α) (n : ℕ) : α :=
s n
/-- Proposition saying that all elements of a stream satisfy a predicate. -/
def all (p : α → Prop) (s : stream α) := ∀ n, p (nth s n)
/-- Proposition saying that at least one element of a stream satisfies a predicate. -/
def any (p : α → Prop) (s : stream α) := ∃ n, p (nth s n)
/-- `a ∈ s` means that `a = stream.nth n s` for some `n`. -/
instance : has_mem α (stream α) :=
⟨λ a s, any (λ b, a = b) s⟩
/-- Apply a function `f` to all elements of a stream `s`. -/
def map (f : α → β) (s : stream α) : stream β :=
λ n, f (nth s n)
/-- Zip two streams using a binary operation:
`stream.nth n (stream.zip f s₁ s₂) = f (stream.nth s₁) (stream.nth s₂)`. -/
def zip (f : α → β → δ) (s₁ : stream α) (s₂ : stream β) : stream δ :=
λ n, f (nth s₁ n) (nth s₂ n)
/-- The constant stream: `stream.nth n (stream.const a) = a`. -/
def const (a : α) : stream α :=
λ n, a
/-- Iterates of a function as a stream. -/
def iterate (f : α → α) (a : α) : stream α :=
λ n, nat.rec_on n a (λ n r, f r)
def corec (f : α → β) (g : α → α) : α → stream β :=
λ a, map f (iterate g a)
def corec_on (a : α) (f : α → β) (g : α → α) : stream β :=
corec f g a
def corec' (f : α → β × α) : α → stream β := corec (prod.fst ∘ f) (prod.snd ∘ f)
/-- Use a state monad to generate a stream through corecursion -/
def corec_state {σ α} (cmd : state σ α) (s : σ) : stream α :=
corec prod.fst (cmd.run ∘ prod.snd) (cmd.run s)
-- corec is also known as unfold
def unfolds (g : α → β) (f : α → α) (a : α) : stream β :=
corec g f a
/-- Interleave two streams. -/
def interleave (s₁ s₂ : stream α) : stream α :=
corec_on (s₁, s₂)
(λ ⟨s₁, s₂⟩, head s₁)
(λ ⟨s₁, s₂⟩, (s₂, tail s₁))
infix `⋈`:65 := interleave
/-- Elements of a stream with even indices. -/
def even (s : stream α) : stream α :=
corec
(λ s, head s)
(λ s, tail (tail s))
s
/-- Elements of a stream with odd indices. -/
def odd (s : stream α) : stream α :=
even (tail s)
/-- Append a stream to a list. -/
def append_stream : list α → stream α → stream α
| [] s := s
| (list.cons a l) s := a :: append_stream l s
infix `++ₛ`:65 := append_stream
/-- `take n s` returns a list of the `n` first elements of stream `s` -/
def take : ℕ → stream α → list α
| 0 s := []
| (n+1) s := list.cons (head s) (take n (tail s))
/-- An auxiliary definition for `stream.cycle` corecursive def -/
protected def cycle_f : α × list α × α × list α → α
| (v, _, _, _) := v
/-- An auxiliary definition for `stream.cycle` corecursive def -/
protected def cycle_g : α × list α × α × list α → α × list α × α × list α
| (v₁, [], v₀, l₀) := (v₀, l₀, v₀, l₀)
| (v₁, list.cons v₂ l₂, v₀, l₀) := (v₂, l₂, v₀, l₀)
/-- Interpret a nonempty list as a cyclic stream. -/
def cycle : Π (l : list α), l ≠ [] → stream α
| [] h := absurd rfl h
| (list.cons a l) h := corec stream.cycle_f stream.cycle_g (a, l, a, l)
/-- Tails of a stream, starting with `stream.tail s`. -/
def tails (s : stream α) : stream (stream α) :=
corec id tail (tail s)
/-- An auxiliary definition for `stream.inits`. -/
def inits_core (l : list α) (s : stream α) : stream (list α) :=
corec_on (l, s)
(λ ⟨a, b⟩, a)
(λ p, match p with (l', s') := (l' ++ [head s'], tail s') end)
/-- Nonempty initial segments of a stream. -/
def inits (s : stream α) : stream (list α) :=
inits_core [head s] (tail s)
/-- A constant stream, same as `stream.const`. -/
def pure (a : α) : stream α :=
const a
/-- Given a stream of functions and a stream of values, apply `n`-th function to `n`-th value. -/
def apply (f : stream (α → β)) (s : stream α) : stream β :=
λ n, (nth f n) (nth s n)
infix `⊛`:75 := apply -- input as \o*
/-- The stream of natural numbers: `stream.nth n stream.nats = n`. -/
def nats : stream nat :=
λ n, n
end stream
|
fd6fc8dc59bd84eaaf8931548e8ba729b689f7ad | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/group_theory/abelianization.lean | 5181444e05164df03b50c68c6ba5714f07e07411 | [
"Apache-2.0"
] | permissive | mcncm/mathlib | 8d25099344d9d2bee62822cb9ed43aa3e09fa05e | fde3d78cadeec5ef827b16ae55664ef115e66f57 | refs/heads/master | 1,672,743,316,277 | 1,602,618,514,000 | 1,602,618,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,624 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Michael Howes
The functor Grp → Ab which is the left adjoint
of the forgetful functor Ab → Grp.
-/
import group_theory.quotient_group
import tactic.group
universes u v
-- let G be a group
variables (G : Type u) [group G]
/-- The commutator subgroup of a group G is the normal subgroup
generated by the commutators [p,q]=`p*q*p⁻¹*q⁻¹` -/
@[derive subgroup.normal]
def commutator : subgroup G :=
subgroup.normal_closure {x | ∃ p q, p * q * p⁻¹ * q⁻¹ = x}
/-- The abelianization of G is the quotient of G by its commutator subgroup -/
def abelianization : Type u :=
quotient_group.quotient (commutator G)
namespace abelianization
local attribute [instance] quotient_group.left_rel
instance : comm_group (abelianization G) :=
{ mul_comm := λ x y, quotient.induction_on₂' x y $ λ a b,
begin
apply quotient.sound,
apply subgroup.subset_normal_closure,
use b⁻¹, use a⁻¹,
group,
end,
.. quotient_group.group _ }
instance : inhabited (abelianization G) := ⟨1⟩
variable {G}
/-- `of` is the canonical projection from G to its abelianization. -/
def of : G →* abelianization G :=
{ to_fun := quotient_group.mk,
map_one' := rfl,
map_mul' := λ x y, rfl }
section lift
-- so far -- built Gᵃᵇ and proved it's an abelian group.
-- defined `of : G → Gᵃᵇ`
-- let A be an abelian group and let f be a group hom from G to A
variables {A : Type v} [comm_group A] (f : G →* A)
lemma commutator_subset_ker : commutator G ≤ f.ker :=
begin
apply subgroup.normal_closure_le_normal,
rintros x ⟨p, q, rfl⟩,
simp [monoid_hom.mem_ker, mul_right_comm (f p) (f q)],
end
/-- If `f : G → A` is a group homomorphism to an abelian group, then `lift f` is the unique map from
the abelianization of a `G` to `A` that factors through `f`. -/
def lift : abelianization G →* A :=
quotient_group.lift _ f (λ x h, f.mem_ker.2 $ commutator_subset_ker _ h)
@[simp] lemma lift.of (x : G) : lift f (of x) = f x :=
rfl
theorem lift.unique
(φ : abelianization G →* A)
-- hφ : φ agrees with f on the image of G in Gᵃᵇ
(hφ : ∀ (x : G), φ (of x) = f x)
{x : abelianization G} :
φ x = lift f x :=
quotient_group.induction_on x hφ
end lift
variables {A : Type v} [monoid A]
theorem hom_ext (φ ψ : abelianization G →* A)
(h : φ.comp of = ψ.comp of) : φ = ψ :=
begin
ext x,
apply quotient_group.induction_on x,
intro z,
show φ.comp of z = _,
rw h,
refl,
end
end abelianization
|
cb55b944f6f36a65e30ca733b0c248ce98bbcdcc | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/order/rel_iso/basic.lean | 2c78215fa64077604251e87d1bb77a95d7bcc4e2 | [
"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,779 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.fun_like.basic
import logic.embedding.basic
import order.rel_classes
/-!
# Relation homomorphisms, embeddings, isomorphisms
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines relation homomorphisms, embeddings, isomorphisms and order embeddings and
isomorphisms.
## Main declarations
* `rel_hom`: Relation homomorphism. A `rel_hom r s` is a function `f : α → β` such that
`r a b → s (f a) (f b)`.
* `rel_embedding`: Relation embedding. A `rel_embedding r s` is an embedding `f : α ↪ β` such that
`r a b ↔ s (f a) (f b)`.
* `rel_iso`: Relation isomorphism. A `rel_iso r s` is an equivalence `f : α ≃ β` such that
`r a b ↔ s (f a) (f b)`.
* `sum_lex_congr`, `prod_lex_congr`: Creates a relation homomorphism between two `sum_lex` or two
`prod_lex` from relation homomorphisms between their arguments.
## Notation
* `→r`: `rel_hom`
* `↪r`: `rel_embedding`
* `≃r`: `rel_iso`
-/
open function
universes u v w
variables {α β γ δ : Type*}
{r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} {u : δ → δ → Prop}
/-- A relation homomorphism with respect to a given pair of relations `r` and `s`
is a function `f : α → β` such that `r a b → s (f a) (f b)`. -/
@[nolint has_nonempty_instance]
structure rel_hom {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) :=
(to_fun : α → β)
(map_rel' : ∀ {a b}, r a b → s (to_fun a) (to_fun b))
infix ` →r `:25 := rel_hom
section
set_option old_structure_cmd true
/-- `rel_hom_class F r s` asserts that `F` is a type of functions such that all `f : F`
satisfy `r a b → s (f a) (f b)`.
The relations `r` and `s` are `out_param`s since figuring them out from a goal is a higher-order
matching problem that Lean usually can't do unaided.
-/
class rel_hom_class (F : Type*) {α β : out_param $ Type*}
(r : out_param $ α → α → Prop) (s : out_param $ β → β → Prop)
extends fun_like F α (λ _, β) :=
(map_rel : ∀ (f : F) {a b}, r a b → s (f a) (f b))
export rel_hom_class (map_rel)
-- The free parameters `r` and `s` are `out_param`s so this is not dangerous.
attribute [nolint dangerous_instance] rel_hom_class.to_fun_like
end
namespace rel_hom_class
variables {F : Type*}
protected theorem is_irrefl [rel_hom_class F r s] (f : F) : ∀ [is_irrefl β s], is_irrefl α r
| ⟨H⟩ := ⟨λ a h, H _ (map_rel f h)⟩
protected theorem is_asymm [rel_hom_class F r s] (f : F) : ∀ [is_asymm β s], is_asymm α r
| ⟨H⟩ := ⟨λ a b h₁ h₂, H _ _ (map_rel f h₁) (map_rel f h₂)⟩
protected theorem acc [rel_hom_class F r s] (f : F) (a : α) : acc s (f a) → acc r a :=
begin
generalize h : f a = b, intro ac,
induction ac with _ H IH generalizing a, subst h,
exact ⟨_, λ a' h, IH (f a') (map_rel f h) _ rfl⟩
end
protected theorem well_founded [rel_hom_class F r s] (f : F) :
∀ (h : well_founded s), well_founded r
| ⟨H⟩ := ⟨λ a, rel_hom_class.acc f _ (H _)⟩
end rel_hom_class
namespace rel_hom
instance : rel_hom_class (r →r s) r s :=
{ coe := λ o, o.to_fun,
coe_injective' := λ f g h, by { cases f, cases g, congr' },
map_rel := map_rel' }
/-- Auxiliary instance if `rel_hom_class.to_fun_like.to_has_coe_to_fun` isn't found -/
instance : has_coe_to_fun (r →r s) (λ _, α → β) := ⟨λ o, o.to_fun⟩
initialize_simps_projections rel_hom (to_fun → apply)
protected theorem map_rel (f : r →r s) {a b} : r a b → s (f a) (f b) := f.map_rel'
@[simp] theorem coe_fn_mk (f : α → β) (o) :
(@rel_hom.mk _ _ r s f o : α → β) = f := rfl
@[simp] theorem coe_fn_to_fun (f : r →r s) : (f.to_fun : α → β) = f := rfl
/-- The map `coe_fn : (r →r s) → (α → β)` is injective. -/
theorem coe_fn_injective : @function.injective (r →r s) (α → β) coe_fn :=
fun_like.coe_injective
@[ext] theorem ext ⦃f g : r →r s⦄ (h : ∀ x, f x = g x) : f = g :=
fun_like.ext f g h
theorem ext_iff {f g : r →r s} : f = g ↔ ∀ x, f x = g x :=
fun_like.ext_iff
/-- Identity map is a relation homomorphism. -/
@[refl, simps] protected def id (r : α → α → Prop) : r →r r :=
⟨λ x, x, λ a b x, x⟩
/-- Composition of two relation homomorphisms is a relation homomorphism. -/
@[trans, simps] protected def comp (g : s →r t) (f : r →r s) : r →r t :=
⟨λ x, g (f x), λ a b h, g.2 (f.2 h)⟩
/-- A relation homomorphism is also a relation homomorphism between dual relations. -/
protected def swap (f : r →r s) : swap r →r swap s :=
⟨f, λ a b, f.map_rel⟩
/-- A function is a relation homomorphism from the preimage relation of `s` to `s`. -/
def preimage (f : α → β) (s : β → β → Prop) : f ⁻¹'o s →r s := ⟨f, λ a b, id⟩
end rel_hom
/-- An increasing function is injective -/
lemma injective_of_increasing (r : α → α → Prop) (s : β → β → Prop) [is_trichotomous α r]
[is_irrefl β s] (f : α → β) (hf : ∀ {x y}, r x y → s (f x) (f y)) : injective f :=
begin
intros x y hxy,
rcases trichotomous_of r x y with h | h | h,
have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this,
exact h,
have := hf h, rw hxy at this, exfalso, exact irrefl_of s (f y) this
end
/-- An increasing function is injective -/
lemma rel_hom.injective_of_increasing [is_trichotomous α r]
[is_irrefl β s] (f : r →r s) : injective f :=
injective_of_increasing r s f (λ x y, f.map_rel)
-- TODO: define a `rel_iff_class` so we don't have to do all the `convert` trickery?
theorem surjective.well_founded_iff {f : α → β} (hf : surjective f)
(o : ∀ {a b}, r a b ↔ s (f a) (f b)) : well_founded r ↔ well_founded s :=
iff.intro (begin
refine rel_hom_class.well_founded (rel_hom.mk _ _ : s →r r),
{ exact classical.some hf.has_right_inverse },
intros a b h, apply o.2, convert h,
iterate 2 { apply classical.some_spec hf.has_right_inverse },
end) (rel_hom_class.well_founded (⟨f, λ _ _, o.1⟩ : r →r s))
/-- A relation embedding with respect to a given pair of relations `r` and `s`
is an embedding `f : α ↪ β` such that `r a b ↔ s (f a) (f b)`. -/
structure rel_embedding {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ↪ β :=
(map_rel_iff' : ∀ {a b}, s (to_embedding a) (to_embedding b) ↔ r a b)
infix ` ↪r `:25 := rel_embedding
/-- The induced relation on a subtype is an embedding under the natural inclusion. -/
definition subtype.rel_embedding {X : Type*} (r : X → X → Prop) (p : X → Prop) :
((subtype.val : subtype p → X) ⁻¹'o r) ↪r r :=
⟨embedding.subtype p, λ x y, iff.rfl⟩
theorem preimage_equivalence {α β} (f : α → β) {s : β → β → Prop}
(hs : equivalence s) : equivalence (f ⁻¹'o s) :=
⟨λ a, hs.1 _, λ a b h, hs.2.1 h, λ a b c h₁ h₂, hs.2.2 h₁ h₂⟩
namespace rel_embedding
/-- A relation embedding is also a relation homomorphism -/
def to_rel_hom (f : r ↪r s) : (r →r s) :=
{ to_fun := f.to_embedding.to_fun,
map_rel' := λ x y, (map_rel_iff' f).mpr }
instance : has_coe (r ↪r s) (r →r s) := ⟨to_rel_hom⟩
-- see Note [function coercion]
instance : has_coe_to_fun (r ↪r s) (λ _, α → β) := ⟨λ o, o.to_embedding⟩
-- TODO: define and instantiate a `rel_embedding_class` when `embedding_like` is defined
instance : rel_hom_class (r ↪r s) r s :=
{ coe := coe_fn,
coe_injective' := λ f g h, by { rcases f with ⟨⟨⟩⟩, rcases g with ⟨⟨⟩⟩, congr' },
map_rel := λ f a b, iff.mpr (map_rel_iff' f) }
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (h : r ↪r s) : α → β := h
initialize_simps_projections rel_embedding (to_embedding_to_fun → apply, -to_embedding)
@[simp] lemma to_rel_hom_eq_coe (f : r ↪r s) : f.to_rel_hom = f := rfl
@[simp] lemma coe_coe_fn (f : r ↪r s) : ((f : r →r s) : α → β) = f := rfl
theorem injective (f : r ↪r s) : injective f := f.inj'
@[simp] theorem inj (f : r ↪r s) {a b} : f a = f b ↔ a = b := f.injective.eq_iff
theorem map_rel_iff (f : r ↪r s) {a b} : s (f a) (f b) ↔ r a b := f.map_rel_iff'
@[simp] theorem coe_fn_mk (f : α ↪ β) (o) :
(@rel_embedding.mk _ _ r s f o : α → β) = f := rfl
@[simp] theorem coe_fn_to_embedding (f : r ↪r s) : (f.to_embedding : α → β) = f := rfl
/-- The map `coe_fn : (r ↪r s) → (α → β)` is injective. -/
theorem coe_fn_injective : @function.injective (r ↪r s) (α → β) coe_fn := fun_like.coe_injective
@[ext] theorem ext ⦃f g : r ↪r s⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h
theorem ext_iff {f g : r ↪r s} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff
/-- Identity map is a relation embedding. -/
@[refl, simps] protected def refl (r : α → α → Prop) : r ↪r r :=
⟨embedding.refl _, λ a b, iff.rfl⟩
/-- Composition of two relation embeddings is a relation embedding. -/
@[trans] protected def trans (f : r ↪r s) (g : s ↪r t) : r ↪r t :=
⟨f.1.trans g.1, λ a b, by simp [f.map_rel_iff, g.map_rel_iff]⟩
instance (r : α → α → Prop) : inhabited (r ↪r r) := ⟨rel_embedding.refl _⟩
theorem trans_apply (f : r ↪r s) (g : s ↪r t) (a : α) : (f.trans g) a = g (f a) := rfl
@[simp] theorem coe_trans (f : r ↪r s) (g : s ↪r t) : ⇑(f.trans g) = g ∘ f := rfl
/-- A relation embedding is also a relation embedding between dual relations. -/
protected def swap (f : r ↪r s) : swap r ↪r swap s :=
⟨f.to_embedding, λ a b, f.map_rel_iff⟩
/-- If `f` is injective, then it is a relation embedding from the
preimage relation of `s` to `s`. -/
def preimage (f : α ↪ β) (s : β → β → Prop) : f ⁻¹'o s ↪r s := ⟨f, λ a b, iff.rfl⟩
theorem eq_preimage (f : r ↪r s) : r = f ⁻¹'o s :=
by { ext a b, exact f.map_rel_iff.symm }
protected theorem is_irrefl (f : r ↪r s) [is_irrefl β s] : is_irrefl α r :=
⟨λ a, mt f.map_rel_iff.2 (irrefl (f a))⟩
protected theorem is_refl (f : r ↪r s) [is_refl β s] : is_refl α r :=
⟨λ a, f.map_rel_iff.1 $ refl _⟩
protected theorem is_symm (f : r ↪r s) [is_symm β s] : is_symm α r :=
⟨λ a b, imp_imp_imp f.map_rel_iff.2 f.map_rel_iff.1 symm⟩
protected theorem is_asymm (f : r ↪r s) [is_asymm β s] : is_asymm α r :=
⟨λ a b h₁ h₂, asymm (f.map_rel_iff.2 h₁) (f.map_rel_iff.2 h₂)⟩
protected theorem is_antisymm : ∀ (f : r ↪r s) [is_antisymm β s], is_antisymm α r
| ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, f.inj' (H _ _ (o.2 h₁) (o.2 h₂))⟩
protected theorem is_trans : ∀ (f : r ↪r s) [is_trans β s], is_trans α r
| ⟨f, o⟩ ⟨H⟩ := ⟨λ a b c h₁ h₂, o.1 (H _ _ _ (o.2 h₁) (o.2 h₂))⟩
protected theorem is_total : ∀ (f : r ↪r s) [is_total β s], is_total α r
| ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o o).1 (H _ _)⟩
protected theorem is_preorder : ∀ (f : r ↪r s) [is_preorder β s], is_preorder α r
| f H := by exactI {..f.is_refl, ..f.is_trans}
protected theorem is_partial_order : ∀ (f : r ↪r s) [is_partial_order β s], is_partial_order α r
| f H := by exactI {..f.is_preorder, ..f.is_antisymm}
protected theorem is_linear_order : ∀ (f : r ↪r s) [is_linear_order β s], is_linear_order α r
| f H := by exactI {..f.is_partial_order, ..f.is_total}
protected theorem is_strict_order : ∀ (f : r ↪r s) [is_strict_order β s], is_strict_order α r
| f H := by exactI {..f.is_irrefl, ..f.is_trans}
protected theorem is_trichotomous : ∀ (f : r ↪r s) [is_trichotomous β s], is_trichotomous α r
| ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o (or_congr f.inj'.eq_iff o)).1 (H _ _)⟩
protected theorem is_strict_total_order :
∀ (f : r ↪r s) [is_strict_total_order β s], is_strict_total_order α r
| f H := by exactI {..f.is_trichotomous, ..f.is_strict_order}
protected theorem acc (f : r ↪r s) (a : α) : acc s (f a) → acc r a :=
begin
generalize h : f a = b, intro ac,
induction ac with _ H IH generalizing a, subst h,
exact ⟨_, λ a' h, IH (f a') (f.map_rel_iff.2 h) _ rfl⟩
end
protected theorem well_founded : ∀ (f : r ↪r s) (h : well_founded s), well_founded r
| f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩
protected theorem is_well_founded (f : r ↪r s) [is_well_founded β s] : is_well_founded α r :=
⟨f.well_founded is_well_founded.wf⟩
protected theorem is_well_order : ∀ (f : r ↪r s) [is_well_order β s], is_well_order α r
| f H := by exactI {wf := f.well_founded H.wf, ..f.is_strict_total_order}
end rel_embedding
instance subtype.well_founded_lt [has_lt α] [well_founded_lt α] (p : α → Prop) :
well_founded_lt (subtype p) := (subtype.rel_embedding (<) p).is_well_founded
instance subtype.well_founded_gt [has_lt α] [well_founded_gt α] (p : α → Prop) :
well_founded_gt (subtype p) := (subtype.rel_embedding (>) p).is_well_founded
/-- `quotient.mk` as a relation homomorphism between the relation and the lift of a relation. -/
@[simps] def quotient.mk_rel_hom [setoid α] {r : α → α → Prop} (H) :
r →r quotient.lift₂ r H :=
⟨@quotient.mk α _, λ _ _, id⟩
/-- `quotient.out` as a relation embedding between the lift of a relation and the relation. -/
@[simps]
noncomputable def quotient.out_rel_embedding [setoid α] {r : α → α → Prop} (H) :
quotient.lift₂ r H ↪r r :=
⟨embedding.quotient_out α, begin
refine λ x y, quotient.induction_on₂ x y (λ a b, _),
apply iff_iff_eq.2 (H _ _ _ _ _ _);
apply quotient.mk_out
end⟩
/-- `quotient.out'` as a relation embedding between the lift of a relation and the relation. -/
@[simps]
noncomputable def quotient.out'_rel_embedding {s : setoid α} {r : α → α → Prop} (H) :
(λ a b, quotient.lift_on₂' a b r H) ↪r r :=
{ to_fun := quotient.out',
..quotient.out_rel_embedding _ }
@[simp] theorem acc_lift₂_iff [setoid α] {r : α → α → Prop} {H} {a} :
acc (quotient.lift₂ r H) ⟦a⟧ ↔ acc r a :=
begin
split,
{ exact rel_hom_class.acc (quotient.mk_rel_hom H) a, },
{ intro ac,
induction ac with _ H IH, dsimp at IH,
refine ⟨_, λ q h, _⟩,
obtain ⟨a', rfl⟩ := q.exists_rep,
exact IH a' h, },
end
@[simp] theorem acc_lift_on₂'_iff {s : setoid α} {r : α → α → Prop} {H} {a} :
acc (λ x y, quotient.lift_on₂' x y r H) (quotient.mk' a : quotient s) ↔ acc r a :=
acc_lift₂_iff
/-- A relation is well founded iff its lift to a quotient is. -/
theorem well_founded_lift₂_iff [setoid α] {r : α → α → Prop} {H} :
well_founded (quotient.lift₂ r H) ↔ well_founded r :=
begin
split,
{ exact rel_hom_class.well_founded (quotient.mk_rel_hom H), },
{ refine λ wf, ⟨λ q, _⟩,
obtain ⟨a, rfl⟩ := q.exists_rep,
exact acc_lift₂_iff.2 (wf.apply a), },
end
alias well_founded_lift₂_iff ↔ well_founded.of_quotient_lift₂ well_founded.quotient_lift₂
@[simp] theorem well_founded_lift_on₂'_iff {s : setoid α} {r : α → α → Prop} {H} :
well_founded (λ x y : quotient s, quotient.lift_on₂' x y r H) ↔ well_founded r :=
well_founded_lift₂_iff
alias well_founded_lift_on₂'_iff ↔
well_founded.of_quotient_lift_on₂' well_founded.quotient_lift_on₂'
namespace rel_embedding
/--
To define an relation embedding from an antisymmetric relation `r` to a reflexive relation `s` it
suffices to give a function together with a proof that it satisfies `s (f a) (f b) ↔ r a b`.
-/
def of_map_rel_iff (f : α → β) [is_antisymm α r] [is_refl β s]
(hf : ∀ a b, s (f a) (f b) ↔ r a b) : r ↪r s :=
{ to_fun := f,
inj' := λ x y h, antisymm ((hf _ _).1 (h ▸ refl _)) ((hf _ _).1 (h ▸ refl _)),
map_rel_iff' := hf }
@[simp]
lemma of_map_rel_iff_coe (f : α → β) [is_antisymm α r] [is_refl β s]
(hf : ∀ a b, s (f a) (f b) ↔ r a b) :
⇑(of_map_rel_iff f hf : r ↪r s) = f :=
rfl
/-- It suffices to prove `f` is monotone between strict relations
to show it is a relation embedding. -/
def of_monotone [is_trichotomous α r] [is_asymm β s] (f : α → β)
(H : ∀ a b, r a b → s (f a) (f b)) : r ↪r s :=
begin
haveI := @is_asymm.is_irrefl β s _,
refine ⟨⟨f, λ a b e, _⟩, λ a b, ⟨λ h, _, H _ _⟩⟩,
{ refine ((@trichotomous _ r _ a b).resolve_left _).resolve_right _;
exact λ h, @irrefl _ s _ _ (by simpa [e] using H _ _ h) },
{ refine (@trichotomous _ r _ a b).resolve_right (or.rec (λ e, _) (λ h', _)),
{ subst e, exact irrefl _ h },
{ exact asymm (H _ _ h') h } }
end
@[simp] theorem of_monotone_coe [is_trichotomous α r] [is_asymm β s] (f : α → β) (H) :
(@of_monotone _ _ r s _ _ f H : α → β) = f := rfl
/-- A relation embedding from an empty type. -/
def of_is_empty (r : α → α → Prop) (s : β → β → Prop) [is_empty α] : r ↪r s :=
⟨embedding.of_is_empty, is_empty_elim⟩
/-- `sum.inl` as a relation embedding into `sum.lift_rel r s`. -/
@[simps] def sum_lift_rel_inl (r : α → α → Prop) (s : β → β → Prop) : r ↪r sum.lift_rel r s :=
{ to_fun := sum.inl,
inj' := sum.inl_injective,
map_rel_iff' := λ a b, sum.lift_rel_inl_inl }
/-- `sum.inr` as a relation embedding into `sum.lift_rel r s`. -/
@[simps] def sum_lift_rel_inr (r : α → α → Prop) (s : β → β → Prop) : s ↪r sum.lift_rel r s :=
{ to_fun := sum.inr,
inj' := sum.inr_injective,
map_rel_iff' := λ a b, sum.lift_rel_inr_inr }
/-- `sum.map` as a relation embedding between `sum.lift_rel` relations. -/
@[simps] def sum_lift_rel_map (f : r ↪r s) (g : t ↪r u) : sum.lift_rel r t ↪r sum.lift_rel s u :=
{ to_fun := sum.map f g,
inj' := f.injective.sum_map g.injective,
map_rel_iff' := by { rintro (a | b) (c | d); simp [f.map_rel_iff, g.map_rel_iff] } }
/-- `sum.inl` as a relation embedding into `sum.lex r s`. -/
@[simps] def sum_lex_inl (r : α → α → Prop) (s : β → β → Prop) : r ↪r sum.lex r s :=
{ to_fun := sum.inl,
inj' := sum.inl_injective,
map_rel_iff' := λ a b, sum.lex_inl_inl }
/-- `sum.inr` as a relation embedding into `sum.lex r s`. -/
@[simps] def sum_lex_inr (r : α → α → Prop) (s : β → β → Prop) : s ↪r sum.lex r s :=
{ to_fun := sum.inr,
inj' := sum.inr_injective,
map_rel_iff' := λ a b, sum.lex_inr_inr }
/-- `sum.map` as a relation embedding between `sum.lex` relations. -/
@[simps] def sum_lex_map (f : r ↪r s) (g : t ↪r u) : sum.lex r t ↪r sum.lex s u :=
{ to_fun := sum.map f g,
inj' := f.injective.sum_map g.injective,
map_rel_iff' := by { rintro (a | b) (c | d); simp [f.map_rel_iff, g.map_rel_iff] } }
/-- `λ b, prod.mk a b` as a relation embedding. -/
@[simps] def prod_lex_mk_left (s : β → β → Prop) {a : α} (h : ¬ r a a) : s ↪r prod.lex r s :=
{ to_fun := prod.mk a,
inj' := prod.mk.inj_left a,
map_rel_iff' := λ b₁ b₂, by simp [prod.lex_def, h] }
/-- `λ a, prod.mk a b` as a relation embedding. -/
@[simps] def prod_lex_mk_right (r : α → α → Prop) {b : β} (h : ¬ s b b) : r ↪r prod.lex r s :=
{ to_fun := λ a, (a, b),
inj' := prod.mk.inj_right b,
map_rel_iff' := λ a₁ a₂, by simp [prod.lex_def, h] }
/-- `prod.map` as a relation embedding. -/
@[simps] def prod_lex_map (f : r ↪r s) (g : t ↪r u) : prod.lex r t ↪r prod.lex s u :=
{ to_fun := prod.map f g,
inj' := f.injective.prod_map g.injective,
map_rel_iff' := λ a b, by simp [prod.lex_def, f.map_rel_iff, g.map_rel_iff] }
end rel_embedding
/-- A relation isomorphism is an equivalence that is also a relation embedding. -/
structure rel_iso {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ≃ β :=
(map_rel_iff' : ∀ {a b}, s (to_equiv a) (to_equiv b) ↔ r a b)
infix ` ≃r `:25 := rel_iso
namespace rel_iso
/-- Convert an `rel_iso` to an `rel_embedding`. This function is also available as a coercion
but often it is easier to write `f.to_rel_embedding` than to write explicitly `r` and `s`
in the target type. -/
def to_rel_embedding (f : r ≃r s) : r ↪r s :=
⟨f.to_equiv.to_embedding, λ _ _, f.map_rel_iff'⟩
theorem to_equiv_injective : injective (to_equiv : (r ≃r s) → α ≃ β)
| ⟨e₁, o₁⟩ ⟨e₂, o₂⟩ h := by { congr, exact h }
instance : has_coe (r ≃r s) (r ↪r s) := ⟨to_rel_embedding⟩
-- see Note [function coercion]
instance : has_coe_to_fun (r ≃r s) (λ _, α → β) := ⟨λ f, f⟩
-- TODO: define and instantiate a `rel_iso_class` when `equiv_like` is defined
instance : rel_hom_class (r ≃r s) r s :=
{ coe := coe_fn,
coe_injective' := equiv.coe_fn_injective.comp to_equiv_injective,
map_rel := λ f a b, iff.mpr (map_rel_iff' f) }
@[simp] lemma to_rel_embedding_eq_coe (f : r ≃r s) : f.to_rel_embedding = f := rfl
@[simp] lemma coe_coe_fn (f : r ≃r s) : ((f : r ↪r s) : α → β) = f := rfl
theorem map_rel_iff (f : r ≃r s) {a b} : s (f a) (f b) ↔ r a b := f.map_rel_iff'
@[simp] theorem coe_fn_mk (f : α ≃ β) (o : ∀ ⦃a b⦄, s (f a) (f b) ↔ r a b) :
(rel_iso.mk f o : α → β) = f := rfl
@[simp] theorem coe_fn_to_equiv (f : r ≃r s) : (f.to_equiv : α → β) = f := rfl
/-- The map `coe_fn : (r ≃r s) → (α → β)` is injective. Lean fails to parse
`function.injective (λ e : r ≃r s, (e : α → β))`, so we use a trick to say the same. -/
theorem coe_fn_injective : @function.injective (r ≃r s) (α → β) coe_fn := fun_like.coe_injective
@[ext] theorem ext ⦃f g : r ≃r s⦄ (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h
theorem ext_iff {f g : r ≃r s} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff
/-- Inverse map of a relation isomorphism is a relation isomorphism. -/
@[symm] protected def symm (f : r ≃r s) : s ≃r r :=
⟨f.to_equiv.symm, λ a b, by erw [← f.map_rel_iff, f.1.apply_symm_apply, f.1.apply_symm_apply]⟩
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (h : r ≃r s) : α → β := h
/-- See Note [custom simps projection]. -/
def simps.symm_apply (h : r ≃r s) : β → α := h.symm
initialize_simps_projections rel_iso
(to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv)
/-- Identity map is a relation isomorphism. -/
@[refl, simps apply] protected def refl (r : α → α → Prop) : r ≃r r :=
⟨equiv.refl _, λ a b, iff.rfl⟩
/-- Composition of two relation isomorphisms is a relation isomorphism. -/
@[trans, simps apply] protected def trans (f₁ : r ≃r s) (f₂ : s ≃r t) : r ≃r t :=
⟨f₁.to_equiv.trans f₂.to_equiv, λ a b, f₂.map_rel_iff.trans f₁.map_rel_iff⟩
instance (r : α → α → Prop) : inhabited (r ≃r r) := ⟨rel_iso.refl _⟩
@[simp] lemma default_def (r : α → α → Prop) : default = rel_iso.refl r := rfl
/-- A relation isomorphism between equal relations on equal types. -/
@[simps to_equiv apply] protected def cast {α β : Type u} {r : α → α → Prop} {s : β → β → Prop}
(h₁ : α = β) (h₂ : r == s) : r ≃r s :=
⟨equiv.cast h₁, λ a b, by { subst h₁, rw eq_of_heq h₂, refl }⟩
@[simp] protected theorem cast_symm {α β : Type u} {r : α → α → Prop} {s : β → β → Prop}
(h₁ : α = β) (h₂ : r == s) : (rel_iso.cast h₁ h₂).symm = rel_iso.cast h₁.symm h₂.symm := rfl
@[simp] protected theorem cast_refl {α : Type u} {r : α → α → Prop}
(h₁ : α = α := rfl) (h₂ : r == r := heq.rfl) : rel_iso.cast h₁ h₂ = rel_iso.refl r := rfl
@[simp] protected theorem cast_trans {α β γ : Type u}
{r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} (h₁ : α = β) (h₁' : β = γ)
(h₂ : r == s) (h₂' : s == t): (rel_iso.cast h₁ h₂).trans (rel_iso.cast h₁' h₂') =
rel_iso.cast (h₁.trans h₁') (h₂.trans h₂') :=
ext $ λ x, by { subst h₁, refl }
/-- a relation isomorphism is also a relation isomorphism between dual relations. -/
protected def swap (f : r ≃r s) : (swap r) ≃r (swap s) :=
⟨f.to_equiv, λ _ _, f.map_rel_iff⟩
@[simp] theorem coe_fn_symm_mk (f o) : ((@rel_iso.mk _ _ r s f o).symm : β → α) = f.symm :=
rfl
@[simp] theorem apply_symm_apply (e : r ≃r s) (x : β) : e (e.symm x) = x :=
e.to_equiv.apply_symm_apply x
@[simp] theorem symm_apply_apply (e : r ≃r s) (x : α) : e.symm (e x) = x :=
e.to_equiv.symm_apply_apply x
theorem rel_symm_apply (e : r ≃r s) {x y} : r x (e.symm y) ↔ s (e x) y :=
by rw [← e.map_rel_iff, e.apply_symm_apply]
theorem symm_apply_rel (e : r ≃r s) {x y} : r (e.symm x) y ↔ s x (e y) :=
by rw [← e.map_rel_iff, e.apply_symm_apply]
protected lemma bijective (e : r ≃r s) : bijective e := e.to_equiv.bijective
protected lemma injective (e : r ≃r s) : injective e := e.to_equiv.injective
protected lemma surjective (e : r ≃r s) : surjective e := e.to_equiv.surjective
@[simp] lemma eq_iff_eq (f : r ≃r s) {a b} : f a = f b ↔ a = b :=
f.injective.eq_iff
/-- Any equivalence lifts to a relation isomorphism between `s` and its preimage. -/
protected def preimage (f : α ≃ β) (s : β → β → Prop) : f ⁻¹'o s ≃r s := ⟨f, λ a b, iff.rfl⟩
instance is_well_order.preimage {α : Type u} (r : α → α → Prop) [is_well_order α r] (f : β ≃ α) :
is_well_order β (f ⁻¹'o r) :=
@rel_embedding.is_well_order _ _ (f ⁻¹'o r) r (rel_iso.preimage f r) _
instance is_well_order.ulift {α : Type u} (r : α → α → Prop) [is_well_order α r] :
is_well_order (ulift α) (ulift.down ⁻¹'o r) :=
is_well_order.preimage r equiv.ulift
/-- A surjective relation embedding is a relation isomorphism. -/
@[simps apply]
noncomputable def of_surjective (f : r ↪r s) (H : surjective f) : r ≃r s :=
⟨equiv.of_bijective f ⟨f.injective, H⟩, λ a b, f.map_rel_iff⟩
/--
Given relation isomorphisms `r₁ ≃r s₁` and `r₂ ≃r s₂`, construct a relation isomorphism for the
lexicographic orders on the sum.
-/
def sum_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂}
(e₁ : @rel_iso α₁ β₁ r₁ s₁) (e₂ : @rel_iso α₂ β₂ r₂ s₂) :
sum.lex r₁ r₂ ≃r sum.lex s₁ s₂ :=
⟨equiv.sum_congr e₁.to_equiv e₂.to_equiv, λ a b,
by cases e₁ with f hf; cases e₂ with g hg;
cases a; cases b; simp [hf, hg]⟩
/--
Given relation isomorphisms `r₁ ≃r s₁` and `r₂ ≃r s₂`, construct a relation isomorphism for the
lexicographic orders on the product.
-/
def prod_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂}
(e₁ : @rel_iso α₁ β₁ r₁ s₁) (e₂ : @rel_iso α₂ β₂ r₂ s₂) :
prod.lex r₁ r₂ ≃r prod.lex s₁ s₂ :=
⟨equiv.prod_congr e₁.to_equiv e₂.to_equiv,
λ a b, by simp [prod.lex_def, e₁.map_rel_iff, e₂.map_rel_iff]⟩
/-- Two relations on empty types are isomorphic. -/
def rel_iso_of_is_empty (r : α → α → Prop) (s : β → β → Prop) [is_empty α] [is_empty β] : r ≃r s :=
⟨equiv.equiv_of_is_empty α β, is_empty_elim⟩
/-- Two irreflexive relations on a unique type are isomorphic. -/
def rel_iso_of_unique_of_irrefl (r : α → α → Prop) (s : β → β → Prop)
[is_irrefl α r] [is_irrefl β s] [unique α] [unique β] : r ≃r s :=
⟨equiv.equiv_of_unique α β,
λ x y, by simp [not_rel_of_subsingleton r, not_rel_of_subsingleton s]⟩
/-- Two reflexive relations on a unique type are isomorphic. -/
def rel_iso_of_unique_of_refl (r : α → α → Prop) (s : β → β → Prop)
[is_refl α r] [is_refl β s] [unique α] [unique β] : r ≃r s :=
⟨equiv.equiv_of_unique α β,
λ x y, by simp [rel_of_subsingleton r, rel_of_subsingleton s]⟩
end rel_iso
|
d52f76a27d3534b80f8f3772bb5924c0e11a6bb1 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/1226.lean | cfa6b2d8cec7973ab1cabfd14c51b9e64e9c69ad | [
"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 | 1,663 | lean | open nat
inductive {u} vec (α : Type u) : ℕ → Type u
| 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
|
d294096acb8c4233b3ccf9d85300864d4a708c6d | 36938939954e91f23dec66a02728db08a7acfcf9 | /lean/translate.lean | 2acefb5f1cb95c4db8e10a3e24ed48de8c22ec0d | [
"Apache-2.0"
] | permissive | pnwamk/reopt-vcg | f8b56dd0279392a5e1c6aee721be8138e6b558d3 | c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d | refs/heads/master | 1,631,145,017,772 | 1,593,549,019,000 | 1,593,549,143,000 | 254,191,418 | 0 | 0 | null | 1,586,377,077,000 | 1,586,377,077,000 | null | UTF-8 | Lean | false | false | 12,432 | lean |
import x86_semantics.instructions
import x86_semantics.evaluator
import decodex86
import tactic.find
open mc_semantics
open mc_semantics.type
lemma {u} find_index_lt {α : Type u} (p : α -> Prop) [decidable_pred p] : Π(ls : list α), list.find_index p ls ≤ ls.length :=
begin
intros,
induction ls,
{ simp [list.find_index] },
{ simp [list.find_index],
by_cases (p ls_hd),
{ simp [h] },
{ simp [h, nat.one_add], apply nat.succ_le_succ, exact ls_ih }
}
end
lemma {u} index_of_lt {α : Type u} [decidable_eq α] (ls : list α) (x : α)
: list.index_of x ls ≤ ls.length := by apply find_index_lt
namespace x86
@[reducible]
def some_gpr := sigma (λ(tp : gpreg_type), concrete_reg (bv tp.width))
def register_to_reg (r : decodex86.register) : option some_gpr :=
let idx := reg.r64_names.index_of r.top in
if H : idx = reg.r64_names.length
then none
else let idx' := @fin.mk 16 idx (begin
destruct (lt_or_eq_of_le (index_of_lt reg.r64_names r.top)); intros Hle,
exact Hle,
contradiction
end)
in let mk : Π(tp : gpreg_type), option some_gpr
:= λ(tp : gpreg_type), some ⟨tp, concrete_reg.gpreg idx' tp⟩
in
match (r.width, r.offset) with
| (8, 0) := mk gpreg_type.reg8l
| (8, 8) := mk gpreg_type.reg8h
| (16, 0) := mk gpreg_type.reg16
| (32, 0) := mk gpreg_type.reg32
| (0, 0) := mk gpreg_type.reg64 -- 0 0 means full reg.
| _ := none
end
open decodex86
def throw_if {m} {ε} [monad m] [monad_except ε m] (P : Prop) [decidable P] (what : ε) : m unit :=
if P then throw what else return ()
-- instance {α : Type} : decidable_pred (@option.is_none α) :=
-- begin
-- unfold decidable_pred,
-- intros,
-- cases a,
-- { simp [is_none], apply is_true, constructor},
-- { simp [is_none], apply is_false, simp}
-- end
-- instance is_some_decidable {α : Type} : decidable_pred (@option.is_some α) :=
-- begin
-- unfold decidable_pred,
-- intros,
-- cases a,
-- { simp [is_some], apply is_false, simp},
-- { simp [is_some], apply is_true, constructor}
-- end
def guard_some {m} [monad m] [monad_except string m] {α β : Type} (reason : string) (x : option α) (f : α -> m β) : m β :=
match x with
| none := throw (string.append "guard_some: none: " reason)
| (some y) := f y
end
def option_register_to_bv64 {m} [monad m] [monad_except string m]
(nenv : nat_env) (s : machine_state)
(opt_r : option decodex86.register) : m (bitvec 64) :=
match opt_r with
| none := return (bitvec.of_nat 64 0)
| (some r) :=
if r.top = "rip"
then return s.ip
else guard_some "option_register_to_bv64" (register_to_reg r)
(λ(r' : some_gpr),
match r' with
| (sigma.mk gpreg_type.reg64 rr) := return (concrete_reg.from_state nenv rr s)
| _ := throw "not a 64bit reg"
end)
end
def operand_to_arg_lval {m} [monad m] [monad_except string m]
(nenv : nat_env) (s : machine_state)
(tp : type) (otp : decodex86.operand_type) : decodex86.operand_value -> m arg_lval
-- FIXME: check width?
| (operand_value.register r) := do sgpr <- guard_some "operand_to_arg_lhs register" (register_to_reg r) return,
assert_types nenv (bv sgpr.fst.width) tp,
return (arg_lval.reg sgpr.snd)
-- FIXME: check width?
| (operand_value.segment opt_r r) := do
throw_if (option.is_some opt_r) "got a segment reg",
-- FIXME: clag
sgpr <- guard_some "operand_to_arg_value_lhs register" (register_to_reg r) return,
assert_types nenv (bv sgpr.fst.width) tp,
return (arg_lval.reg sgpr.snd)
| (operand_value.immediate nbytes val) := throw "operand_to_arg_lval: got an immdiate"
-- FIXME: we use ip out of the state, we could use the value encoded in the decoded instruction
| (operand_value.rel_immediate next_addr nbytes val) := throw "operand_to_arg_lval: got an immdeiate"
-- base + scale * idx + disp
| (operand_value.memloc opt_seg opt_base scale opt_idx disp) := do
n <- match otp with | (operand_type.mem n) := return n | other := throw "memloc not of mem type" end,
assert_types nenv (bv n) tp,
throw_if (option.is_some opt_seg) "got a segment reg",
b_v <- option_register_to_bv64 nenv s opt_base,
idx_v <- option_register_to_bv64 nenv s opt_idx,
return (arg_lval.memloc n (b_v + scale * idx_v + disp))
def operand_to_arg_value_lhs {m} [monad m] [monad_except string m]
(nenv : nat_env) (s : machine_state)
(tp : type) (op : decodex86.operand) : m (arg_value nenv) :=
arg_value.lval nenv <$> operand_to_arg_lval nenv s tp op.type op.value
def operand_to_value {m} [monad m] [monad_except string m]
(nenv : nat_env) (s : machine_state)
(tp : type) (op : decodex86.operand) : m (value nenv tp) :=
match op.value with
| (operand_value.immediate nbytes val) :=
-- FIXME: rather than failing here, we will sign extend/truncate. This may be the wrong approach.
-- We could also extend operand_type
match tp with
| (bv e) := return (bitvec.of_int (nat_expr.eval_default nenv e) ((bitvec.of_nat (8 * nbytes) val).to_int))
| _ := throw "Immediate should be a bv"
end
-- FIXME: we use ip out of the state, we could use the value encoded in the decoded instruction
| (operand_value.rel_immediate next_addr nbytes val) := do
-- checks for width = 64 bit, basically
@value.type_check nenv m _ _ (bv 64) (s.ip + bitvec.of_nat _ val) tp
| _ := do lval <- operand_to_arg_lval nenv s tp op.type op.value,
arg_lval.to_value' nenv s lval tp
end
def operand_to_arg_value_expr {m} [monad m] [monad_except string m]
(nenv : nat_env) (s : machine_state)
(tp : type) (op : decodex86.operand) : m (arg_value nenv) :=
arg_value.rval <$> operand_to_value nenv s tp op
def {u v w} first_comb {ε : Type u} {m : Type v → Type w}
[monad_except ε m] {α : Type v} (e : ε) (f : ε -> ε -> ε) : list (m α) -> m α
| [] := throw e
| [x] := x
| (x :: xs) := catch x $ λe1, catch (first_comb xs) $ λe2, throw (f e1 e2)
-- Inside the list monad here
def possible_nat_envs : list binding -> list nat_env
| [] := [[]]
| (binding.one_of ns :: xs) := do n <- ns, e <- possible_nat_envs xs, return (some n :: e)
| (_ :: xs) := do e <- possible_nat_envs xs, return (none :: e)
/-
def test_pattern := match mov.patterns with | [x] := x | _ := sorry end
#eval possible_nat_envs test_pattern.context.bindings.reverse
-/
def make_environment_helper (nenv : nat_env) (s : machine_state)
: list binding -> list decodex86.operand -> nat_env -> except string (environment nenv)
| [] [] _ := return []
| (binding.one_of _ :: rest) ops (some n :: ns) := do e <- make_environment_helper rest ops ns,
return (arg_value.natv nenv n :: e)
| (binding.reg tp :: rest) (op :: ops) (_ :: ns) :=
annotate' "reg" $ do
av <- operand_to_arg_value_lhs nenv s tp op,
-- Mainly to check things are of the right form
match av with | (arg_value.lval _ (arg_lval.reg r)) := return () | _ := throw "Not a register" end,
e <- make_environment_helper rest ops ns,
return (av :: e)
| (binding.addr tp :: rest) (op :: ops) (_ :: ns) :=
annotate' "addr" $ do
av <- operand_to_arg_value_lhs nenv s tp op,
-- Mainly to check things are of the right form
match av with | (arg_value.lval _ (arg_lval.memloc _ _)) := return () | _ := throw "Not a memloc" end,
e <- make_environment_helper rest ops ns,
return (av :: e)
| (binding.imm tp :: rest) (op :: ops) (_ :: ns) :=
annotate' "imm" $ do
-- FIXME: check that it is, in fact, an immediate
av <- operand_to_arg_value_expr nenv s tp op,
e <- make_environment_helper rest ops ns,
return (av :: e)
| (binding.lhs tp :: rest) (op :: ops) (_ :: ns) :=
annotate' "lhs" $ do
av <- operand_to_arg_value_lhs nenv s tp op,
e <- make_environment_helper rest ops ns,
return (av :: e)
| (binding.expression tp :: rest) (op :: ops) (_ :: ns) :=
annotate' "expression" $ do
av <- operand_to_arg_value_expr nenv s tp op,
e <- make_environment_helper rest ops ns,
return (av :: e)
| _ _ _ := throw "binding/operand mismatch"
/-
inductive binding
| one_of : list nat → binding
| reg : type → binding
| addr : type → binding
| imm : type → binding
| lhs : type → binding
| expression : type → binding
-/
def make_environment (s : machine_state) (bindings : list binding) (ops : list decodex86.operand)
: except string (sigma environment) :=
first_comb "make_environment: no patterns" (λl r, r) -- l ++ ", " ++ r)
(list.map (λnenv, do e <- make_environment_helper nenv s bindings ops nenv, return (sigma.mk nenv e)) (possible_nat_envs bindings))
def instantiate_pattern (s : machine_state) (inst : instruction) (i : decodex86.instruction)
: except string ((sigma environment) × x86.pattern) :=
first_comb "instantiate_pattern: no patterns" (λl r, r) -- l ++ ", " ++ r)
(list.map (λ(p : x86.pattern), do e <- make_environment s p.context.bindings.reverse i.operands, return (e, p)) inst.patterns)
-- def eval_simple_instruction (s : instruction) (i : decodex86.instruction) : evaluator environment :=
-- match s.patterns with
-- | [p] := do match_context p.context.bindings.reverse i.operands,
-- s <- get,
-- return s.environment
-- | _ := throw "not a simple instruction"
-- end
def instruction_family (inst : decodex86.instruction) : string :=
let (pfx, rest) := list.span char.is_upper inst.mnemonic.to_list in
(list.map char.to_lower pfx).as_string
def instruction_map : rbmap string instruction :=
rbmap.from_list (list.map (λ(i : instruction), (i.mnemonic, i)) all_instructions)
def eval_instruction { ost : Type } (s : system_state ost) (sys : system_m ost unit) (i : decodex86.instruction) : except string (system_state ost) :=
match instruction_map.find (instruction_family i) with
| none := throw ("Unknown instruction: " ++ i.mnemonic)
| (some inst) := do (sigma.mk nenv env, p) <- annotate' "pattern" (instantiate_pattern s.machine_state inst i),
annotate' "pattern.eval" (pattern.eval ost sys nenv p env s)
end
/- testing -/
def get_sexp : string -> sexp := λst,
match sexp.from_string st with
| (sum.inr s) := s
| _ := sexp.list []
end
def string_to_instruction (s : string) : option decodex86.instruction :=
decodex86.exec_parser decodex86.parser.instructionp (get_sexp s)
-- def go (s : string) : string :=
-- match string_to_instruction s with
-- | none := "No parse"
-- | (some i) := repr i.operands
-- end
-- namespace except
-- def to_sum {a} {b} : except a b -> sum a b
-- | (except.error e) := sum.inl e
-- | (except.ok v) := sum.inr v
-- end except
-- def go2 (s : string) (si : instruction) : string :=
-- match string_to_instruction s with
-- | none := "No parse"
-- | (some i) := match ((eval_simple_instruction si i).run evaluator_state.empty) with
-- | (except.error e) := "error: " ++ e
-- | (except.ok (e, _)) := has_repr.repr e
-- end
-- end
-- def run_get_rax (s : string) : string :=
-- match string_to_instruction s with
-- | none := "No parse"
-- | (some i) := match (eval_instruction machine_state.empty i) with
-- | (except.error e) := "error: " ++ e
-- | (except.ok s) := s.print_regs -- has_repr.repr (s.get_gpreg 0)
-- end
-- end
-- #eval instruction_family <$> string_to_instruction "(instruction MOV32ri (register rax eax 32 0) (immediate 4 1))"
-- #eval run_get_rax "(instruction MOV64ri32 (other (register rax rax 0 0)) (other (immediate 4 4294967295)))"
-- #eval run_get_rax "(instruction MOV32mi (i32mem (memloc no-register (register rax rax 0 0) 1 no-register 0)) (i32imm (immediate 4 65535)))"
end x86
|
e122eae8cb1af7b51506864e43286188d2cb7be5 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/data/countable/basic.lean | 9db635167cc6837cfc0499a5fda2bea779bc8aab | [
"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 | 3,178 | lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import logic.equiv.nat
import logic.equiv.fin
import data.countable.defs
/-!
# Countable types
In this file we provide basic instances of the `countable` typeclass defined elsewhere.
-/
universes u v w
open function
instance : countable ℤ := countable.of_equiv ℕ equiv.int_equiv_nat.symm
/-!
### Definition in terms of `function.embedding`
-/
section embedding
variables {α : Sort u} {β : Sort v}
lemma countable_iff_nonempty_embedding : countable α ↔ nonempty (α ↪ ℕ) :=
⟨λ ⟨⟨f, hf⟩⟩, ⟨⟨f, hf⟩⟩, λ ⟨f⟩, ⟨⟨f, f.2⟩⟩⟩
lemma nonempty_embedding_nat (α) [countable α] : nonempty (α ↪ ℕ) :=
countable_iff_nonempty_embedding.1 ‹_›
protected lemma function.embedding.countable [countable β] (f : α ↪ β) : countable α :=
f.injective.countable
end embedding
/-!
### Operations on `Type*`s
-/
section type
variables {α : Type u} {β : Type v} {π : α → Type w}
instance [countable α] [countable β] : countable (α ⊕ β) :=
begin
rcases exists_injective_nat α with ⟨f, hf⟩,
rcases exists_injective_nat β with ⟨g, hg⟩,
exact (equiv.nat_sum_nat_equiv_nat.injective.comp $ hf.sum_map hg).countable
end
instance [countable α] : countable (option α) :=
countable.of_equiv _ (equiv.option_equiv_sum_punit α).symm
instance [countable α] [countable β] : countable (α × β) :=
begin
rcases exists_injective_nat α with ⟨f, hf⟩,
rcases exists_injective_nat β with ⟨g, hg⟩,
exact (equiv.nat_prod_nat_equiv_nat.injective.comp $ hf.prod_map hg).countable
end
instance [countable α] [Π a, countable (π a)] : countable (sigma π) :=
begin
rcases exists_injective_nat α with ⟨f, hf⟩,
choose g hg using λ a, exists_injective_nat (π a),
exact ((equiv.sigma_equiv_prod ℕ ℕ).injective.comp $ hf.sigma_map hg).countable
end
end type
section sort
variables {α : Sort u} {β : Sort v} {π : α → Sort w}
/-!
### Operations on and `Sort*`s
-/
@[priority 500]
instance set_coe.countable {α} [countable α] (s : set α) : countable s := subtype.countable
instance [countable α] [countable β] : countable (psum α β) :=
countable.of_equiv (plift α ⊕ plift β) (equiv.plift.sum_psum equiv.plift)
instance [countable α] [countable β] : countable (pprod α β) :=
countable.of_equiv (plift α × plift β) (equiv.plift.prod_pprod equiv.plift)
instance [countable α] [Π a, countable (π a)] : countable (psigma π) :=
countable.of_equiv (Σ a : plift α, plift (π a.down)) (equiv.psigma_equiv_sigma_plift π).symm
instance [finite α] [Π a, countable (π a)] : countable (Π a, π a) :=
begin
haveI : ∀ n, countable (fin n → ℕ),
{ intro n, induction n with n ihn,
{ apply_instance },
{ exactI countable.of_equiv _ (equiv.pi_fin_succ _ _).symm } },
rcases finite.exists_equiv_fin α with ⟨n, ⟨e⟩⟩,
have f := λ a, (nonempty_embedding_nat (π a)).some,
exact ((embedding.Pi_congr_right f).trans (equiv.Pi_congr_left' _ e).to_embedding).countable
end
end sort
|
3422185cbd3fe66bd6db6335c64121302e7c01c5 | 2fbe653e4bc441efde5e5d250566e65538709888 | /src/topology/uniform_space/cauchy.lean | 9bc2d41ed6e83d7132ff4a1998cd19564c8412cf | [
"Apache-2.0"
] | permissive | aceg00/mathlib | 5e15e79a8af87ff7eb8c17e2629c442ef24e746b | 8786ea6d6d46d6969ac9a869eb818bf100802882 | refs/heads/master | 1,649,202,698,930 | 1,580,924,783,000 | 1,580,924,783,000 | 149,197,272 | 0 | 0 | Apache-2.0 | 1,537,224,208,000 | 1,537,224,207,000 | null | UTF-8 | Lean | false | false | 22,612 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
Theory of Cauchy filters in uniform spaces. Complete uniform spaces. Totally bounded subsets.
-/
import topology.uniform_space.basic topology.bases data.set.intervals
universes u v
open filter topological_space lattice set classical
open_locale classical
variables {α : Type u} {β : Type v} [uniform_space α]
open_locale uniformity topological_space
/-- A filter `f` is Cauchy if for every entourage `r`, there exists an
`s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy
sequences, because if `a : ℕ → α` then the filter of sets containing
cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/
def cauchy (f : filter α) := f ≠ ⊥ ∧ filter.prod f f ≤ (𝓤 α)
/-- A set `s` is called *complete*, if any Cauchy filter `f` such that `s ∈ f`
has a limit in `s` (formally, it satisfies `f ≤ 𝓝 x` for some `x ∈ s`). -/
def is_complete (s : set α) := ∀f, cauchy f → f ≤ principal s → ∃x∈s, f ≤ 𝓝 x
lemma cauchy_iff {f : filter α} :
cauchy f ↔ (f ≠ ⊥ ∧ (∀ s ∈ 𝓤 α, ∃t∈f.sets, set.prod t t ⊆ s)) :=
and_congr iff.rfl $ forall_congr $ assume s, forall_congr $ assume hs, mem_prod_same_iff
lemma cauchy_map_iff {l : filter β} {f : β → α} :
cauchy (l.map f) ↔ (l ≠ ⊥ ∧ tendsto (λp:β×β, (f p.1, f p.2)) (l.prod l) (𝓤 α)) :=
by rw [cauchy, (≠), map_eq_bot_iff, prod_map_map_eq]; refl
lemma cauchy_downwards {f g : filter α} (h_c : cauchy f) (hg : g ≠ ⊥) (h_le : g ≤ f) : cauchy g :=
⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩
lemma cauchy_nhds {a : α} : cauchy (𝓝 a) :=
⟨nhds_ne_bot,
calc filter.prod (𝓝 a) (𝓝 a) =
(𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set(α×α),
set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod
... ≤ (𝓤 α).lift' (λs:set (α×α), comp_rel s s) :
le_infi $ assume s, le_infi $ assume hs,
infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $
principal_mono.mpr $
assume ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩
... ≤ 𝓤 α : comp_le_uniformity⟩
lemma cauchy_pure {a : α} : cauchy (pure a) :=
cauchy_downwards cauchy_nhds pure_ne_bot (pure_le_nhds a)
/-- The common part of the proofs of `le_nhds_of_cauchy_adhp` and
`sequentially_complete.le_nhds_of_seq_tendsto_nhds`: if for any entourage `s`
one can choose a set `t ∈ f` of diameter `s` such that it contains a point `y`
with `(x, y) ∈ s`, then `f` converges to `x`. -/
lemma le_nhds_of_cauchy_adhp_aux {f : filter α} {x : α}
(adhs : ∀ s ∈ 𝓤 α, ∃ t ∈ f, (set.prod t t ⊆ s) ∧ ∃ y, (y ∈ t) ∧ (x, y) ∈ s) :
f ≤ 𝓝 x :=
begin
-- Consider a neighborhood `s` of `x`
assume s hs,
-- Take an entourage twice smaller than `s`
rcases comp_mem_uniformity_sets (mem_nhds_uniformity_iff.1 hs) with ⟨U, U_mem, hU⟩,
-- Take a set `t ∈ f`, `t × t ⊆ U`, and a point `y ∈ t` such that `(x, y) ∈ U`
rcases adhs U U_mem with ⟨t, t_mem, ht, y, hy, hxy⟩,
apply mem_sets_of_superset t_mem,
-- Given a point `z ∈ t`, we have `(x, y) ∈ U` and `(y, z) ∈ t × t ⊆ U`, hence `z ∈ s`
exact (λ z hz, hU (prod_mk_mem_comp_rel hxy (ht $ mk_mem_prod hy hz)) rfl)
end
/-- If `x` is an adherent (cluster) point for a Cauchy filter `f`, then it is a limit point
for `f`. -/
lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f)
(adhs : f ⊓ 𝓝 x ≠ ⊥) : f ≤ 𝓝 x :=
le_nhds_of_cauchy_adhp_aux
begin
assume s hs,
-- Take `t ∈ f` such that `t × t ⊆ s`.
rcases (cauchy_iff.1 hf).2 s hs with ⟨t, t_mem, ht⟩,
use [t, t_mem, ht],
exact (forall_sets_nonempty_iff_ne_bot.2 adhs _
(inter_mem_inf_sets t_mem (mem_nhds_left x hs)))
end
lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) :
f ≤ 𝓝 x ↔ f ⊓ 𝓝 x ≠ ⊥ :=
⟨assume h, (inf_of_le_left h).symm ▸ hf.left,
le_nhds_of_cauchy_adhp hf⟩
lemma cauchy_map [uniform_space β] {f : filter α} {m : α → β}
(hm : uniform_continuous m) (hf : cauchy f) : cauchy (map m f) :=
⟨have f ≠ ⊥, from hf.left, by simp; assumption,
calc filter.prod (map m f) (map m f) =
map (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_map_map_eq
... ≤ map (λp:α×α, (m p.1, m p.2)) (𝓤 α) : map_mono hf.right
... ≤ 𝓤 β : hm⟩
lemma cauchy_comap [uniform_space β] {f : filter β} {m : α → β}
(hm : comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α)
(hf : cauchy f) (hb : comap m f ≠ ⊥) : cauchy (comap m f) :=
⟨hb,
calc filter.prod (comap m f) (comap m f) =
comap (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_comap_comap_eq
... ≤ comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) : comap_mono hf.right
... ≤ 𝓤 α : hm⟩
/-- Cauchy sequences. Usually defined on ℕ, but often it is also useful to say that a function
defined on ℝ is Cauchy at +∞ to deduce convergence. Therefore, we define it in a type class that
is general enough to cover both ℕ and ℝ, which are the main motivating examples. -/
def cauchy_seq [semilattice_sup β] (u : β → α) := cauchy (at_top.map u)
lemma cauchy_seq_of_tendsto_nhds [semilattice_sup β] [nonempty β] (f : β → α) {x}
(hx : tendsto f at_top (𝓝 x)) :
cauchy_seq f :=
cauchy_downwards cauchy_nhds (map_ne_bot at_top_ne_bot) hx
lemma cauchy_seq_iff_prod_map [inhabited β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ map (prod.map u u) at_top ≤ 𝓤 α :=
iff.trans (and_iff_right (map_ne_bot at_top_ne_bot)) (prod_map_at_top_eq u u ▸ iff.rfl)
lemma cauchy_seq_of_controlled [semilattice_sup β] [inhabited β]
(U : β → set (α × α)) (hU : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s)
{f : β → α} (hf : ∀ {N m n : β}, N ≤ m → N ≤ n → (f m, f n) ∈ U N) :
cauchy_seq f :=
cauchy_seq_iff_prod_map.2
begin
assume s hs,
rw [mem_map, mem_at_top_sets],
cases hU s hs with N hN,
refine ⟨(N, N), λ mn hmn, _⟩,
cases mn with m n,
exact hN (hf hmn.1 hmn.2)
end
/-- A complete space is defined here using uniformities. A uniform space
is complete if every Cauchy filter converges. -/
class complete_space (α : Type u) [uniform_space α] : Prop :=
(complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ 𝓝 x)
lemma complete_univ {α : Type u} [uniform_space α] [complete_space α] :
is_complete (univ : set α) :=
begin
assume f hf _,
rcases complete_space.complete hf with ⟨x, hx⟩,
exact ⟨x, by simp, hx⟩
end
lemma cauchy_prod [uniform_space β] {f : filter α} {g : filter β} :
cauchy f → cauchy g → cauchy (filter.prod f g)
| ⟨f_proper, hf⟩ ⟨g_proper, hg⟩ := ⟨filter.prod_ne_bot.2 ⟨f_proper, g_proper⟩,
let p_α := λp:(α×β)×(α×β), (p.1.1, p.2.1), p_β := λp:(α×β)×(α×β), (p.1.2, p.2.2) in
suffices (f.prod f).comap p_α ⊓ (g.prod g).comap p_β ≤ (𝓤 α).comap p_α ⊓ (𝓤 β).comap p_β,
by simpa [uniformity_prod, filter.prod, filter.comap_inf, filter.comap_comap_comp, (∘),
lattice.inf_assoc, lattice.inf_comm, lattice.inf_left_comm],
lattice.inf_le_inf (filter.comap_mono hf) (filter.comap_mono hg)⟩
instance complete_space.prod [uniform_space β] [complete_space α] [complete_space β] :
complete_space (α × β) :=
{ complete := λ f hf,
let ⟨x1, hx1⟩ := complete_space.complete $ cauchy_map uniform_continuous_fst hf in
let ⟨x2, hx2⟩ := complete_space.complete $ cauchy_map uniform_continuous_snd hf in
⟨(x1, x2), by rw [nhds_prod_eq, filter.prod_def];
from filter.le_lift (λ s hs, filter.le_lift' $ λ t ht,
have H1 : prod.fst ⁻¹' s ∈ f.sets := hx1 hs,
have H2 : prod.snd ⁻¹' t ∈ f.sets := hx2 ht,
filter.inter_mem_sets H1 H2)⟩ }
/--If `univ` is complete, the space is a complete space -/
lemma complete_space_of_is_complete_univ (h : is_complete (univ : set α)) : complete_space α :=
⟨λ f hf, let ⟨x, _, hx⟩ := h f hf ((@principal_univ α).symm ▸ le_top) in ⟨x, hx⟩⟩
lemma cauchy_iff_exists_le_nhds [complete_space α] {l : filter α} (hl : l ≠ ⊥) :
cauchy l ↔ (∃x, l ≤ 𝓝 x) :=
⟨complete_space.complete, assume ⟨x, hx⟩, cauchy_downwards cauchy_nhds hl hx⟩
lemma cauchy_map_iff_exists_tendsto [complete_space α] {l : filter β} {f : β → α}
(hl : l ≠ ⊥) : cauchy (l.map f) ↔ (∃x, tendsto f l (𝓝 x)) :=
cauchy_iff_exists_le_nhds (map_ne_bot hl)
/-- A Cauchy sequence in a complete space converges -/
theorem cauchy_seq_tendsto_of_complete [semilattice_sup β] [complete_space α]
{u : β → α} (H : cauchy_seq u) : ∃x, tendsto u at_top (𝓝 x) :=
complete_space.complete H
/-- If `K` is a complete subset, then any cauchy sequence in `K` converges to a point in `K` -/
lemma cauchy_seq_tendsto_of_is_complete [semilattice_sup β] {K : set α} (h₁ : is_complete K)
{u : β → α} (h₂ : ∀ n, u n ∈ K) (h₃ : cauchy_seq u) : ∃ v ∈ K, tendsto u at_top (𝓝 v) :=
h₁ _ h₃ $ le_principal_iff.2 $ mem_map_sets_iff.2 ⟨univ, univ_mem_sets,
by { simp only [image_univ], rintros _ ⟨n, rfl⟩, exact h₂ n }⟩
theorem le_nhds_lim_of_cauchy {α} [uniform_space α] [complete_space α]
[inhabited α] {f : filter α} (hf : cauchy f) : f ≤ 𝓝 (lim f) :=
lim_spec (complete_space.complete hf)
lemma is_complete_of_is_closed [complete_space α] {s : set α}
(h : is_closed s) : is_complete s :=
λ f cf fs, let ⟨x, hx⟩ := complete_space.complete cf in
⟨x, is_closed_iff_nhds.mp h x (ne_bot_of_le_ne_bot cf.left (le_inf hx fs)), hx⟩
/-- A set `s` is totally bounded if for every entourage `d` there is a finite
set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/
def totally_bounded (s : set α) : Prop :=
∀d ∈ 𝓤 α, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d})
theorem totally_bounded_iff_subset {s : set α} : totally_bounded s ↔
∀d ∈ 𝓤 α, ∃t ⊆ s, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) :=
⟨λ H d hd, begin
rcases comp_symm_of_uniformity hd with ⟨r, hr, rs, rd⟩,
rcases H r hr with ⟨k, fk, ks⟩,
let u := {y ∈ k | ∃ x, x ∈ s ∧ (x, y) ∈ r},
let f : u → α := λ x, classical.some x.2.2,
have : ∀ x : u, f x ∈ s ∧ (f x, x.1) ∈ r := λ x, classical.some_spec x.2.2,
refine ⟨range f, _, _, _⟩,
{ exact range_subset_iff.2 (λ x, (this x).1) },
{ have : finite u := finite_subset fk (λ x h, h.1),
exact ⟨@set.fintype_range _ _ _ _ this.fintype⟩ },
{ intros x xs,
have := ks xs, simp at this,
rcases this with ⟨y, hy, xy⟩,
let z : coe_sort u := ⟨y, hy, x, xs, xy⟩,
exact mem_bUnion_iff.2 ⟨_, ⟨z, rfl⟩, rd $ mem_comp_rel.2 ⟨_, xy, rs (this z).2⟩⟩ }
end,
λ H d hd, let ⟨t, _, ht⟩ := H d hd in ⟨t, ht⟩⟩
lemma totally_bounded_subset {s₁ s₂ : set α} (hs : s₁ ⊆ s₂)
(h : totally_bounded s₂) : totally_bounded s₁ :=
assume d hd, let ⟨t, ht₁, ht₂⟩ := h d hd in ⟨t, ht₁, subset.trans hs ht₂⟩
lemma totally_bounded_empty : totally_bounded (∅ : set α) :=
λ d hd, ⟨∅, finite_empty, empty_subset _⟩
lemma totally_bounded_closure {s : set α} (h : totally_bounded s) :
totally_bounded (closure s) :=
assume t ht,
let ⟨t', ht', hct', htt'⟩ := mem_uniformity_is_closed ht, ⟨c, hcf, hc⟩ := h t' ht' in
⟨c, hcf,
calc closure s ⊆ closure (⋃ (y : α) (H : y ∈ c), {x : α | (x, y) ∈ t'}) : closure_mono hc
... = _ : closure_eq_of_is_closed $ is_closed_bUnion hcf $ assume i hi,
continuous_iff_is_closed.mp (continuous_id.prod_mk continuous_const) _ hct'
... ⊆ _ : bUnion_subset $ assume i hi, subset.trans (assume x, @htt' (x, i))
(subset_bUnion_of_mem hi)⟩
lemma totally_bounded_image [uniform_space β] {f : α → β} {s : set α}
(hf : uniform_continuous f) (hs : totally_bounded s) : totally_bounded (f '' s) :=
assume t ht,
have {p:α×α | (f p.1, f p.2) ∈ t} ∈ 𝓤 α,
from hf ht,
let ⟨c, hfc, hct⟩ := hs _ this in
⟨f '' c, finite_image f hfc,
begin
simp [image_subset_iff],
simp [subset_def] at hct,
intros x hx, simp [-mem_image],
exact let ⟨i, hi, ht⟩ := hct x hx in ⟨f i, mem_image_of_mem f hi, ht⟩
end⟩
lemma cauchy_of_totally_bounded_of_ultrafilter {s : set α} {f : filter α}
(hs : totally_bounded s) (hf : is_ultrafilter f) (h : f ≤ principal s) : cauchy f :=
⟨hf.left, assume t ht,
let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in
let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in
have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f.sets,
from mem_sets_of_superset (le_principal_iff.mp h) hs_union,
have ∃y∈i, {x | (x,y) ∈ t'} ∈ f.sets,
from mem_of_finite_Union_ultrafilter hf hi this,
let ⟨y, hy, hif⟩ := this in
have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t',
from assume ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩,
⟨y, h₁, ht'_symm h₂⟩,
(filter.prod f f).sets_of_superset (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩
lemma totally_bounded_iff_filter {s : set α} :
totally_bounded s ↔ (∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c) :=
⟨assume : totally_bounded s, assume f hf hs,
⟨ultrafilter_of f, ultrafilter_of_le,
cauchy_of_totally_bounded_of_ultrafilter this
(ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hs)⟩,
assume h : ∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c, assume d hd,
classical.by_contradiction $ assume hs,
have hd_cover : ∀{t:set α}, finite t → ¬ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}),
by simpa using hs,
let
f := ⨅t:{t : set α // finite t}, principal (s \ (⋃y∈t.val, {x | (x,y) ∈ d})),
⟨a, ha⟩ := (@ne_empty_iff_nonempty α s).1
(assume h, hd_cover finite_empty $ h.symm ▸ empty_subset _)
in
have f ≠ ⊥,
from infi_ne_bot_of_directed ⟨a⟩
(assume ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨⟨t₁ ∪ t₂, finite_union ht₁ ht₂⟩,
principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $
assume t, Union_subset_Union_const or.inl,
principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $
assume t, Union_subset_Union_const or.inr⟩)
(assume ⟨t, ht⟩, by simp [diff_eq_empty]; exact hd_cover ht),
have f ≤ principal s, from infi_le_of_le ⟨∅, finite_empty⟩ $ by simp; exact subset.refl s,
let
⟨c, (hc₁ : c ≤ f), (hc₂ : cauchy c)⟩ := h f ‹f ≠ ⊥› this,
⟨m, hm, (hmd : set.prod m m ⊆ d)⟩ := (@mem_prod_same_iff α c d).mp $ hc₂.right hd
in
have c ≤ principal s, from le_trans ‹c ≤ f› this,
have m ∩ s ∈ c.sets, from inter_mem_sets hm $ le_principal_iff.mp this,
let ⟨y, hym, hys⟩ := nonempty_of_mem_sets hc₂.left this in
let ys := (⋃y'∈({y}:set α), {x | (x, y') ∈ d}) in
have m ⊆ ys,
from assume y' hy',
show y' ∈ (⋃y'∈({y}:set α), {x | (x, y') ∈ d}),
by simp; exact @hmd (y', y) ⟨hy', hym⟩,
have c ≤ principal (s - ys),
from le_trans hc₁ $ infi_le_of_le ⟨{y}, finite_singleton _⟩ $ le_refl _,
have (s - ys) ∩ (m ∩ s) ∈ c.sets,
from inter_mem_sets (le_principal_iff.mp this) ‹m ∩ s ∈ c.sets›,
have ∅ ∈ c.sets,
from c.sets_of_superset this $ assume x ⟨⟨hxs, hxys⟩, hxm, _⟩, hxys $ ‹m ⊆ ys› hxm,
hc₂.left $ empty_in_sets_eq_bot.mp this⟩
lemma totally_bounded_iff_ultrafilter {s : set α} :
totally_bounded s ↔ (∀f, is_ultrafilter f → f ≤ principal s → cauchy f) :=
⟨assume hs f, cauchy_of_totally_bounded_of_ultrafilter hs,
assume h, totally_bounded_iff_filter.mpr $ assume f hf hfs,
have cauchy (ultrafilter_of f),
from h (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs),
⟨ultrafilter_of f, ultrafilter_of_le, this⟩⟩
lemma compact_iff_totally_bounded_complete {s : set α} :
compact s ↔ totally_bounded s ∧ is_complete s :=
⟨λ hs, ⟨totally_bounded_iff_ultrafilter.2 (λ f hf1 hf2,
let ⟨x, xs, fx⟩ := compact_iff_ultrafilter_le_nhds.1 hs f hf1 hf2 in
cauchy_downwards (cauchy_nhds) (hf1.1) fx),
λ f fc fs,
let ⟨a, as, fa⟩ := hs f fc.1 fs in
⟨a, as, le_nhds_of_cauchy_adhp fc fa⟩⟩,
λ ⟨ht, hc⟩, compact_iff_ultrafilter_le_nhds.2
(λf hf hfs, hc _ (totally_bounded_iff_ultrafilter.1 ht _ hf hfs) hfs)⟩
@[priority 100] -- see Note [lower instance priority]
instance complete_of_compact {α : Type u} [uniform_space α] [compact_space α] : complete_space α :=
⟨λf hf, by simpa [principal_univ] using (compact_iff_totally_bounded_complete.1 compact_univ).2 f hf⟩
lemma compact_of_totally_bounded_is_closed [complete_space α] {s : set α}
(ht : totally_bounded s) (hc : is_closed s) : compact s :=
(@compact_iff_totally_bounded_complete α _ s).2 ⟨ht, is_complete_of_is_closed hc⟩
/-! ### Sequentially complete space
In this section we prove that a uniform space is complete provided that it is sequentially complete
(i.e., any Cauchy sequence converges) and its uniformity filter admits a countable generating set.
In particular, this applies to (e)metric spaces, see the files `topology/metric_space/emetric_space` and
`topology/metric_space/basic`.
More precisely, we assume that there is a sequence of entourages `U_n` such that any other
entourage includes one of `U_n`. Then any Cauchy filter `f` generates a decreasing sequence of
sets `s_n ∈ f` such that `s_n × s_n ⊆ U_n`. Choose a sequence `x_n∈s_n`. It is easy to show
that this is a Cauchy sequence. If this sequence converges to some `a`, then `f ≤ 𝓝 a`. -/
namespace sequentially_complete
variables {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)}
(U_mem : ∀ n, U n ∈ 𝓤 α) (U_le : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s)
open set finset
noncomputable theory
/-- An auxiliary sequence of sets approximating a Cauchy filter. -/
def set_seq_aux (n : ℕ) : {s : set α // ∃ (_ : s ∈ f), s.prod s ⊆ U n } :=
indefinite_description _ $ (cauchy_iff.1 hf).2 (U n) (U_mem n)
/-- Given a Cauchy filter `f` and a sequence `U` of entourages, `set_seq` provides
a sequence of monotonically decreasing sets `s n ∈ f` such that `(s n).prod (s n) ⊆ U`. -/
def set_seq (n : ℕ) : set α := ⋂ m ∈ Iic n, (set_seq_aux hf U_mem m).val
lemma set_seq_mem (n : ℕ) : set_seq hf U_mem n ∈ f :=
Inter_mem_sets (finite_le_nat n) (λ m _, (set_seq_aux hf U_mem m).2.fst)
lemma set_seq_mono ⦃m n : ℕ⦄ (h : m ≤ n) : set_seq hf U_mem n ⊆ set_seq hf U_mem m :=
bInter_subset_bInter_left (λ k hk, le_trans hk h)
lemma set_seq_sub_aux (n : ℕ) : set_seq hf U_mem n ⊆ set_seq_aux hf U_mem n :=
bInter_subset_of_mem right_mem_Iic
lemma set_seq_prod_subset {N m n} (hm : N ≤ m) (hn : N ≤ n) :
(set_seq hf U_mem m).prod (set_seq hf U_mem n) ⊆ U N :=
begin
assume p hp,
refine (set_seq_aux hf U_mem N).2.snd ⟨_, _⟩;
apply set_seq_sub_aux,
exact set_seq_mono hf U_mem hm hp.1,
exact set_seq_mono hf U_mem hn hp.2
end
/-- A sequence of points such that `seq n ∈ set_seq n`. Here `set_seq` is a monotonically
decreasing sequence of sets `set_seq n ∈ f` with diameters controlled by a given sequence
of entourages. -/
def seq (n : ℕ) : α := some $ nonempty_of_mem_sets hf.1 (set_seq_mem hf U_mem n)
lemma seq_mem (n : ℕ) : seq hf U_mem n ∈ set_seq hf U_mem n :=
some_spec $ nonempty_of_mem_sets hf.1 (set_seq_mem hf U_mem n)
lemma seq_pair_mem ⦃N m n : ℕ⦄ (hm : N ≤ m) (hn : N ≤ n) :
(seq hf U_mem m, seq hf U_mem n) ∈ U N :=
set_seq_prod_subset hf U_mem hm hn ⟨seq_mem hf U_mem m, seq_mem hf U_mem n⟩
include U_le
theorem seq_is_cauchy_seq : cauchy_seq $ seq hf U_mem :=
cauchy_seq_of_controlled U U_le $ seq_pair_mem hf U_mem
/-- If the sequence `sequentially_complete.seq` converges to `a`, then `f ≤ 𝓝 a`. -/
theorem le_nhds_of_seq_tendsto_nhds ⦃a : α⦄ (ha : tendsto (seq hf U_mem) at_top (𝓝 a)) :
f ≤ 𝓝 a :=
le_nhds_of_cauchy_adhp_aux
begin
assume s hs,
rcases U_le s hs with ⟨m, hm⟩,
rcases (tendsto_at_top' _ _).1 ha _ (mem_nhds_left a (U_mem m)) with ⟨n, hn⟩,
refine ⟨set_seq hf U_mem (max m n), set_seq_mem hf U_mem _, _,
seq hf U_mem (max m n), seq_mem hf U_mem _, _⟩,
{ have := le_max_left m n,
exact set.subset.trans (set_seq_prod_subset hf U_mem this this) hm },
{ exact hm (hn _ $ le_max_right m n) }
end
end sequentially_complete
namespace uniform_space
open sequentially_complete
variables (H : has_countable_basis (𝓤 α))
include H
/-- A uniform space is complete provided that (a) its uniformity filter has a countable basis;
(b) any sequence satisfying a "controlled" version of the Cauchy condition converges. -/
theorem complete_of_convergent_controlled_sequences (U : ℕ → set (α × α)) (U_mem : ∀ n, U n ∈ 𝓤 α)
(HU : ∀ u : ℕ → α, (∀ N m n, N ≤ m → N ≤ n → (u m, u n) ∈ U N) → ∃ a, tendsto u at_top (𝓝 a)) :
complete_space α :=
begin
rcases (𝓤 α).has_countable_basis_iff_mono_seq'.1 H with ⟨U', U'_mono, hU'⟩,
have Hmem : ∀ n, U n ∩ U' n ∈ 𝓤 α,
from λ n, inter_mem_sets (U_mem n) (hU'.2 ⟨n, subset.refl _⟩),
refine ⟨λ f hf, (HU (seq hf Hmem) (λ N m n hm hn, _)).imp $
le_nhds_of_seq_tendsto_nhds _ _ (λ s hs, _)⟩,
{ rcases (hU'.1 hs) with ⟨N, hN⟩,
exact ⟨N, subset.trans (inter_subset_right _ _) hN⟩ },
{ exact inter_subset_left _ _ (seq_pair_mem hf Hmem hm hn) }
end
/-- A sequentially complete uniform space with a countable basis of the uniformity filter is
complete. -/
theorem complete_of_cauchy_seq_tendsto
(H' : ∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) :
complete_space α :=
let ⟨U', U'_mono, hU'⟩ := (𝓤 α).has_countable_basis_iff_mono_seq'.1 H in
complete_of_convergent_controlled_sequences H U' (λ n, hU'.2 ⟨n, subset.refl _⟩)
(λ u hu, H' u $ cauchy_seq_of_controlled U' (λ s hs, hU'.1 hs) hu)
protected lemma first_countable_topology : first_countable_topology α :=
⟨λ a, by { rw nhds_eq_comap_uniformity, exact H.comap (prod.mk a) }⟩
end uniform_space
|
3d0dfd2b9ff273b147b8b010b9cb28092874f2d5 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/pkg/user_attr/lakefile.lean | 3b0c46f9730c7b364b18ab97750133d8590abaae | [
"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 | 87 | lean | import Lake
open System Lake DSL
package user_attr
@[defaultTarget] lean_lib UserAttr
|
596a2a9f3e942cf4c9781f5eebc7e3589bac08ae | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/ite_simp_auto.lean | 2e7a7b969463c4f0981721bb7dc821954c38eb9a | [] | 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 | 885 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.data.bool.default
namespace Mathlib
/-
Simplification lemmas for ite.
We don't prove them at logic.lean because it is easier to prove them using
the tactic framework.
-/
@[simp] theorem if_true_right_eq_or (p : Prop) [h : Decidable p] (q : Prop) :
ite p q True = (¬p ∨ q) :=
sorry
@[simp] theorem if_true_left_eq_or (p : Prop) [h : Decidable p] (q : Prop) :
ite p True q = (p ∨ q) :=
sorry
@[simp] theorem if_false_right_eq_and (p : Prop) [h : Decidable p] (q : Prop) :
ite p q False = (p ∧ q) :=
sorry
@[simp] theorem if_false_left_eq_and (p : Prop) [h : Decidable p] (q : Prop) :
ite p False q = (¬p ∧ q) :=
sorry
end Mathlib |
afc6f8ec88a9a407db674b115f4f4b7c5f77de13 | 3446e92e64a5de7ed1f2109cfb024f83cd904c34 | /src/game/world2/level13.lean | 9658bfdf7a336fd7144d6f76f5106b05ed9a507c | [] | no_license | kckennylau/natural_number_game | 019f4a5f419c9681e65234ecd124c564f9a0a246 | ad8c0adaa725975be8a9f978c8494a39311029be | refs/heads/master | 1,598,784,137,722 | 1,571,905,156,000 | 1,571,905,156,000 | 218,354,686 | 0 | 0 | null | 1,572,373,319,000 | 1,572,373,318,000 | null | UTF-8 | Lean | false | false | 739 | lean | import mynat.definition -- hide
import mynat.add -- hide
import game.world2.level12 -- hide
namespace mynat -- hide
/-
# World 2 -- Addition World
## Level 13 -- `add_left_eq_zero`
You have the usual stuff.
* `zero_ne_succ : ∀ (a : mynat), zero ≠ succ(a)`
might be useful for this one.
The following lemma will be useful when we want to prove that $\leq$ is antisymmetric
somewhere in world 4.
-/
/- Lemma
If $a$ and $b$ are natural numbers such that
$$ a + b = 0, $$
then $b = 0$.
-/
lemma add_left_eq_zero {{a b : mynat}} : a + b = 0 → b = 0 :=
begin [less_leaky]
intro H,
cases b with c,
{ refl},
{ rw add_succ at H,
exfalso,
apply zero_ne_succ (a + c),
rw H,
refl,
},
end
end mynat -- hide
|
8ab25aa6eb1269a8b4ad1d26ee0f67702a56df75 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /src/Init/Lean/Data/LBool.lean | 99d85f17c4dea7f95cf8bb6f9586bd1dae5893f8 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 1,014 | 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.Data.ToString
namespace Lean
inductive LBool
| false
| true
| undef
namespace LBool
instance : Inhabited LBool := ⟨false⟩
def neg : LBool → LBool
| true => false
| false => true
| undef => undef
def and : LBool → LBool → LBool
| true, b => b
| a, _ => a
def beq : LBool → LBool → Bool
| true, true => Bool.true
| false, false => Bool.true
| undef, undef => Bool.true
| _, _ => Bool.false
instance : HasBeq LBool := ⟨beq⟩
def toString : LBool → String
| true => "true"
| false => "false"
| undef => "undef"
instance : HasToString LBool := ⟨toString⟩
end LBool
end Lean
def Bool.toLBool : Bool → Lean.LBool
| true => Lean.LBool.true
| false => Lean.LBool.false
@[inline] def toLBoolM {m : Type → Type} [Monad m] (x : m Bool) : m Lean.LBool := do
b ← x; pure b.toLBool
|
ee49b114386fd45a5abbf58937985c1d5f904c4f | 8cb37a089cdb4af3af9d8bf1002b417e407a8e9e | /library/init/meta/float.lean | 772249a9ab5e80b8e62f763fef897b96021405ad | [
"Apache-2.0"
] | permissive | kbuzzard/lean | ae3c3db4bb462d750dbf7419b28bafb3ec983ef7 | ed1788fd674bb8991acffc8fca585ec746711928 | refs/heads/master | 1,620,983,366,617 | 1,618,937,600,000 | 1,618,937,600,000 | 359,886,396 | 1 | 0 | Apache-2.0 | 1,618,936,987,000 | 1,618,936,987,000 | null | UTF-8 | Lean | false | false | 6,017 | lean | /- Authors: E.W.Ayers -/
prelude
import init.data
namespace native
meta constant float : Type
namespace float
-- fixed values based on the underlying C++ float implementation.
namespace specification
/-- The base. Either 2 or 10. -/
meta constant radix : nat
/-- The length of the mantissa. -/
meta constant precision : nat
/-- The maximum exponent. -/
meta constant emax : nat
/-- The minimum exponent. `= 1 - emax` -/
meta constant emin : int
end specification
open specification
/-- Returns the difference between 1.0 and the next representable value of the given floating-point type.
Reference: https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon
-/
meta constant epsilon : float
/-- returns the maximum rounding error -/
meta constant round_error : float
/-- Positive infinity. -/
meta constant infinity : float
/-- Quiet NaN. -/
meta constant qNaN : float
/-- Signalling NaN. -/
meta constant sNaN : float
/-- Returns true when the value is positive or negative infinity.-/
meta constant is_infinite : float → bool
meta constant is_finite : float → bool
/-- Returns true when the value is qNaN or sNaN-/
meta constant is_nan : float → bool
/-- Reference: https://en.cppreference.com/w/cpp/numeric/math/isnormal
https://stackoverflow.com/questions/8341395/what-is-a-subnormal-floating-point-number
-/
meta constant is_normal : float → bool
/-- The sign `s` of the float. `tt` if negative. -/
meta constant sign : float → bool
/-- The exponent `e` of the float in the base given by `radix`. `emin ≤ e ≤ emax`. Returns none if the number is not finite. -/
meta constant exponent : float → option int
/-- Decompose the number `f` in to `(s,e)` where `0.5 ≤ s < 1.0` and `emin ≤ e ≤ emax` such that `f = s * 2 ^ e`. -/
meta constant frexp : float → float × int
/-- Decompose in to integer `fst` and fractional `snd` parts. -/
meta constant modf : float → float × float
/-- `mantissa f` returns a number `s` where `0.5 ≤ s < 1.0` such that there exists an integer `e` such that `f = s * 2 ^ e` -/
meta def mantissa : float → float := prod.fst ∘ frexp
-- [TODO]
-- /-- List of digits in the mantissa of the float. `d₀.d₁d₂d₃ ⋯`
-- The length is `precision` and `0 ≤ dᵢ < radix` for each digit `dᵢ`.
-- The head of the list is the most significant digit.
-- -/
-- meta constant mantissa_digits : float → array precision nat
meta constant add : float → float → float
meta instance : has_add float := ⟨add⟩
meta constant sub : float → float → float
meta instance : has_sub float := ⟨sub⟩
meta constant neg : float → float
meta instance : has_neg float := ⟨neg⟩
meta constant mul : float → float → float
meta instance : has_mul float := ⟨mul⟩
meta constant div : float → float → float
meta instance : has_div float := ⟨div⟩
/-- remainder of the floating point division operation. -/
meta constant fmod : float → float → float
/-- signed remainder of the division operation. -/
meta constant remainder : float → float → float
meta constant max : float → float → float
meta constant min : float → float → float
meta constant pow : float → float → float
meta instance has_float_pow : has_pow float float := ⟨pow⟩
/-- Square root. -/
meta constant sqrt : float → float
/-- Cube root. -/
meta constant cbrt : float → float
/-- Computes `sqrt(x^2 + y^2)`. -/
meta constant hypot : float → float → float
/-- Exponential function. -/
meta constant exp : float → float
/-- 2 raised to the given power. -/
meta constant exp2 : float → float
/-- Natural logarithm. -/
meta constant log : float → float
meta constant log2 : float → float
meta constant log10 : float → float
meta constant pi : float
meta constant sin : float → float
meta constant cos : float → float
meta constant tan : float → float
meta constant asin : float → float
meta constant acos : float → float
meta constant atan : float → float
/-- `atan2 y x` finds the angle anticlockwise from the x-axis to the point `[x,y]`.-/
meta constant atan2 : float → float → float
meta constant sinh : float → float
meta constant cosh : float → float
meta constant tanh : float → float
meta constant asinh : float → float
meta constant acosh : float → float
meta constant atanh : float → float
meta constant abs : float → float
/-- Nearest integer not less than the given value. -/
meta constant ceil : float → int
/-- Nearest integer not greater than the given value. -/
meta constant floor : float → int
/-- Nearest integer not greater in magnitude than the given value. -/
meta constant trunc : float → int
/-- Round to the nearest integer, rounding away from zero in halfway cases. -/
meta constant round : float → int
meta constant lt : float → float → bool
meta instance : has_lt float := ⟨λ x y, lt x y⟩
meta instance decidable_lt : decidable_rel (float.has_lt.lt) := by apply_instance
meta constant le : float → float → bool
meta instance : has_le float := ⟨λ x y, le x y⟩
meta instance decidable_le : decidable_rel (float.has_le.le) := by apply_instance
meta constant dec_eq : decidable_eq float
attribute [instance] dec_eq
meta constant of_nat : nat → float
meta constant of_int : int → float
meta instance of_nat_coe : has_coe nat float := ⟨of_nat⟩
meta instance of_int_coe : has_coe int float := ⟨of_int⟩
protected meta def zero : float := of_nat 0
protected meta def one : float := of_nat 1
meta instance : has_zero float := ⟨float.zero⟩
meta instance : has_one float := ⟨float.one⟩
meta constant to_repr : float → string
meta instance : has_repr float := ⟨to_repr⟩
meta instance : has_to_string float := ⟨to_repr⟩
meta instance : has_to_format float := ⟨format.of_string ∘ to_string⟩
meta constant of_string : string → option float
meta instance has_nat_pow : has_pow float nat :=
⟨λ a b, native.float.pow a (float.of_nat b)⟩
end float
end native
|
1b6d3f66f3c4aa679cad52e67d5daab757541b25 | f00cc9c04d77f9621aa57d1406d35c522c3ff82c | /library/init/data/bool/lemmas.lean | c378a8ef0fd0e03e152ad7bd4dfe52d8ef5f98bd | [
"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 | 4,676 | 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.bool.basic init.meta
attribute [simp] cond bor band bnot bxor
@[simp] lemma {u} cond_a_a {α : Type u} (b : bool) (a : α) : cond b a a = a :=
by cases b; simp
@[simp] lemma band_self (b : bool) : b && b = b :=
by cases b; simp
@[simp] lemma band_tt (b : bool) : b && tt = b :=
by cases b; simp
@[simp] lemma band_ff (b : bool) : b && ff = ff :=
by cases b; simp
@[simp] lemma tt_band (b : bool) : tt && b = b :=
by cases b; simp
@[simp] lemma ff_band (b : bool) : ff && b = ff :=
by cases b; simp
@[simp] lemma bor_self (b : bool) : b || b = b :=
by cases b; simp
@[simp] lemma bor_tt (b : bool) : b || tt = tt :=
by cases b; simp
@[simp] lemma bor_ff (b : bool) : b || ff = b :=
by cases b; simp
@[simp] lemma tt_bor (b : bool) : tt || b = tt :=
by cases b; simp
@[simp] lemma ff_bor (b : bool) : ff || b = b :=
by cases b; simp
@[simp] lemma bxor_self (b : bool) : bxor b b = ff :=
by cases b; simp
@[simp] lemma bxor_tt (b : bool) : bxor b tt = bnot b :=
by cases b; simp
@[simp] lemma bxor_ff (b : bool) : bxor b ff = b :=
by cases b; simp
@[simp] lemma tt_bxor (b : bool) : bxor tt b = bnot b :=
by cases b; simp
@[simp] lemma ff_bxor (b : bool) : bxor ff b = b :=
by cases b; simp
@[simp] lemma bnot_bnot (b : bool) : bnot (bnot b) = b :=
by cases b; simp
@[simp] lemma tt_eq_ff_eq_false : ¬(tt = ff) :=
by contradiction
@[simp] lemma ff_eq_tt_eq_false : ¬(ff = tt) :=
by contradiction
@[simp] lemma eq_ff_eq_not_eq_tt (b : bool) : (¬(b = tt)) = (b = ff) :=
by cases b; simp
@[simp] lemma eq_tt_eq_not_eq_ff (b : bool) : (¬(b = ff)) = (b = tt) :=
by cases b; simp
lemma eq_ff_of_not_eq_tt {b : bool} : (¬(b = tt)) → (b = ff) :=
eq.mp (eq_ff_eq_not_eq_tt b)
lemma eq_tt_of_not_eq_ff {b : bool} : (¬(b = ff)) → (b = tt) :=
eq.mp (eq_tt_eq_not_eq_ff b)
@[simp] lemma band_eq_true_eq_eq_tt_and_eq_tt (a b : bool) : (a && b = tt) = (a = tt ∧ b = tt) :=
by cases a; cases b; simp
@[simp] lemma bor_eq_true_eq_eq_tt_or_eq_tt (a b : bool) : (a || b = tt) = (a = tt ∨ b = tt) :=
by cases a; cases b; simp
@[simp] lemma bnot_eq_true_eq_eq_ff (a : bool) : (bnot a = tt) = (a = ff) :=
by cases a; simp
@[simp] lemma band_eq_false_eq_eq_ff_or_eq_ff (a b : bool) : (a && b = ff) = (a = ff ∨ b = ff) :=
by cases a; cases b; simp
@[simp] lemma bor_eq_false_eq_eq_ff_and_eq_ff (a b : bool) : (a || b = ff) = (a = ff ∧ b = ff) :=
by cases a; cases b; simp
@[simp] lemma bnot_eq_ff_eq_eq_tt (a : bool) : (bnot a = ff) = (a = tt) :=
by cases a; simp
@[simp] lemma coe_ff : ↑ff = false :=
show (ff = tt) = false, by simp
@[simp] lemma coe_tt : ↑tt = true :=
show (tt = tt) = true, by simp
@[simp] theorem to_bool_iff (p : Prop) [d : decidable p] : (to_bool p = tt) ↔ p :=
match d with
| is_true hp := ⟨λh, hp, λ_, rfl⟩
| is_false hnp := ⟨λh, bool.no_confusion h, λhp, absurd hp hnp⟩
end
theorem to_bool_true {p : Prop} [decidable p] : p → to_bool p := (to_bool_iff p).2
theorem to_bool_tt {p : Prop} [decidable p] : p → to_bool p = tt := to_bool_true
theorem of_to_bool_true {p : Prop} [decidable p] : to_bool p → p := (to_bool_iff p).1
theorem bool_iff_false {b : bool} : ¬ b ↔ b = ff := by cases b; exact dec_trivial
theorem bool_eq_false {b : bool} : ¬ b → b = ff := bool_iff_false.1
@[simp] theorem to_bool_ff_iff (p : Prop) [decidable p] : to_bool p = ff ↔ ¬p :=
bool_iff_false.symm.trans (not_congr (to_bool_iff _))
theorem to_bool_ff {p : Prop} [decidable p] : ¬p → to_bool p = ff := (to_bool_ff_iff p).2
theorem of_to_bool_ff {p : Prop} [decidable p] : to_bool p = ff → ¬p := (to_bool_ff_iff p).1
theorem to_bool_congr {p q : Prop} [decidable p] [decidable q] (h : p ↔ q) : to_bool p = to_bool q :=
begin
induction h' : to_bool q,
exact to_bool_ff (mt h.1 $ of_to_bool_ff h'),
exact to_bool_true (h.2 $ of_to_bool_true h')
end
@[simp] theorem bor_coe_iff (a b : bool) : a || b ↔ a ∨ b :=
by cases a; cases b; exact dec_trivial
@[simp] theorem band_coe_iff (a b : bool) : a && b ↔ a ∧ b :=
by cases a; cases b; exact dec_trivial
@[simp] theorem bxor_coe_iff (a b : bool) : bxor a b ↔ xor a b :=
by cases a; cases b; exact dec_trivial
@[simp] theorem ite_eq_tt_distrib (c : Prop) [decidable c] (a b : bool) : ((if c then a else b) = tt) = (if c then a = tt else b = tt) :=
by by_cases c with h; simp [h]
@[simp] theorem ite_eq_ff_distrib (c : Prop) [decidable c] (a b : bool) : ((if c then a else b) = ff) = (if c then a = ff else b = ff) :=
by by_cases c with h; simp [h]
|
f9ade180dd5b854b255c402f24fba6fccd247202 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/bug6.lean | 656398533ec98a15ba11b4c930f978c2e06be064 | [
"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 | 331 | lean | import logic
open eq
section
variable {A : Type}
theorem T {a b : A} (H : a = b) : b = a
:= symm H
variables x y : A
variable H : x = y
check T H
check T
end
section
variable {A : Type}
theorem T2 ⦃a b : A⦄ (H : a = b) : b = a
:= symm H
variables x y : A
variable H : x = y
check T2 H
check T2
end
|
50aba6b8e38eef4a429ba475bf72186a822d86dc | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/Lake/CLI/Init.lean | 037f04d249ab38ef3d982f919d66008db33c13e2 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 5,656 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Sebastian Ullrich, Mac Malone
-/
import Lake.Util.Git
import Lake.Util.Sugar
import Lake.Config.Package
import Lake.Config.Workspace
import Lake.Load.Config
import Lake.Build.Actions
namespace Lake
open Git System
/-- The default module of an executable in `std` package. -/
def defaultExeRoot : Name := `Main
/-- `elan` toolchain file name -/
def toolchainFileName : FilePath :=
"lean-toolchain"
def gitignoreContents :=
s!"/{defaultBuildDir}
/{defaultPackagesDir}/*
"
def libFileContents :=
s!"def hello := \"world\""
def mainFileName : FilePath :=
s!"{defaultExeRoot}.lean"
def mainFileContents (libRoot : String) :=
s!"import {libRoot}
def main : IO Unit :=
IO.println s!\"Hello, \{hello}!\"
"
def exeFileContents :=
s!"def main : IO Unit :=
IO.println s!\"Hello, world!\"
"
def stdConfigFileContents (pkgName libRoot : String) :=
s!"import Lake
open Lake DSL
package {pkgName} \{
-- add package configuration options here
}
lean_lib {libRoot} \{
-- add library configuration options here
}
@[default_target]
lean_exe {pkgName} \{
root := `Main
}
"
def exeConfigFileContents (pkgName exeRoot : String) :=
s!"import Lake
open Lake DSL
package {pkgName} \{
-- add package configuration options here
}
@[default_target]
lean_exe {exeRoot} \{
-- add executable configuration options here
}
"
def libConfigFileContents (pkgName libRoot : String) :=
s!"import Lake
open Lake DSL
package {pkgName} \{
-- add package configuration options here
}
@[default_target]
lean_lib {libRoot} \{
-- add library configuration options here
}
"
def mathConfigFileContents (pkgName libRoot : String) :=
s!"import Lake
open Lake DSL
package {pkgName} \{
-- add any package configuration options here
}
require mathlib from git
\"https://github.com/leanprover-community/mathlib4.git\"
@[default_target]
lean_lib {libRoot} \{
-- add any library configuration options here
}
"
def mathToolchainUrl : String :=
"https://raw.githubusercontent.com/leanprover-community/mathlib4/master/lean-toolchain"
/-- The options for the template argument to `initPkg`. -/
inductive InitTemplate
| std | exe | lib | math
deriving Repr, DecidableEq
instance : Inhabited InitTemplate := ⟨.std⟩
def InitTemplate.parse? : String → Option InitTemplate
| "std" => some .std
| "exe" => some .exe
| "lib" => some .lib
| "math" => some .math
| _ => none
def InitTemplate.configFileContents (pkgName root : String) : InitTemplate → String
| .std => stdConfigFileContents pkgName root
| .lib => libConfigFileContents pkgName root
| .exe => exeConfigFileContents pkgName root
| .math => mathConfigFileContents pkgName root
def escapeName! : Name → String
| .anonymous => "[anonymous]"
| .str .anonymous s => escape s
| .str n s => escapeName! n ++ "." ++ escape s
| _ => unreachable!
where
escape s := Lean.idBeginEscape.toString ++ s ++ Lean.idEndEscape.toString
/-- Initialize a new Lake package in the given directory with the given name. -/
def initPkg (dir : FilePath) (name : String) (tmp : InitTemplate) : LogIO PUnit := do
let pkgName := stringToLegalOrSimpleName name
-- determine the name to use for the root
-- use upper camel case unless the specific module name already exists
let (root, rootFile, rootExists) ← do
let root := pkgName
let rootFile := Lean.modToFilePath dir root "lean"
let rootExists ← rootFile.pathExists
if tmp = .exe || rootExists then
pure (root, rootFile, rootExists)
else
let root := toUpperCamelCase (toUpperCamelCaseString name |>.toName)
let rootFile := Lean.modToFilePath dir root "lean"
pure (root, rootFile, ← rootFile.pathExists)
-- write default configuration file
let configFile := dir / defaultConfigFile
if (← configFile.pathExists) then
error "package already initialized"
let rootNameStr := escapeName! root
let contents := tmp.configFileContents (escapeName! pkgName) rootNameStr
IO.FS.writeFile configFile contents
-- write example code if the files do not already exist
if tmp = .exe then
unless (← rootFile.pathExists) do
IO.FS.writeFile rootFile exeFileContents
else
if !rootExists then
IO.FS.createDirAll rootFile.parent.get!
IO.FS.writeFile rootFile libFileContents
if tmp = .std then
let mainFile := dir / mainFileName
unless (← mainFile.pathExists) do
IO.FS.writeFile mainFile <| mainFileContents rootNameStr
-- write Lean's toolchain to file (if it has one) for `elan`
if Lean.toolchain ≠ "" then
if tmp = .math then
download "lean-toolchain" mathToolchainUrl (dir / toolchainFileName)
else
IO.FS.writeFile (dir / toolchainFileName) <| Lean.toolchain ++ "\n"
-- update `.gitignore` with additional entries for Lake
let h ← IO.FS.Handle.mk (dir / ".gitignore") IO.FS.Mode.append
h.putStr gitignoreContents
-- initialize a `.git` repository if none already
unless (← FilePath.isDir <| dir / ".git") do
let repo := GitRepo.mk dir
try
repo.quietInit
unless upstreamBranch = "master" do
repo.checkoutBranch upstreamBranch
else
logWarning "failed to initialize git repository"
def init (pkgName : String) (tmp : InitTemplate) : LogIO PUnit :=
initPkg "." pkgName tmp
def new (pkgName : String) (tmp : InitTemplate) : LogIO PUnit := do
let dirName := pkgName.map fun chr => if chr == '.' then '-' else chr
IO.FS.createDir dirName
initPkg dirName pkgName tmp
|
31ea1f276afcd6bbfe7599f4fc77f08ed016985f | abd85493667895c57a7507870867b28124b3998f | /src/linear_algebra/quadratic_form.lean | 81f90ee82e09d65ec0ea120a69e82ad5062b19c1 | [
"Apache-2.0"
] | permissive | pechersky/mathlib | d56eef16bddb0bfc8bc552b05b7270aff5944393 | f1df14c2214ee114c9738e733efd5de174deb95d | refs/heads/master | 1,666,714,392,571 | 1,591,747,567,000 | 1,591,747,567,000 | 270,557,274 | 0 | 0 | Apache-2.0 | 1,591,597,975,000 | 1,591,597,974,000 | null | UTF-8 | Lean | false | false | 20,457 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Anne Baanen
-/
import algebra.invertible
import linear_algebra.bilinear_form
import linear_algebra.determinant
import linear_algebra.special_linear_group
/-!
# Quadratic forms
This file defines quadratic forms over a `R`-module `M`.
A quadratic form is a map `Q : M → R` such that
(`to_fun_smul`) `Q (a • x) = a * a * Q x`
(`polar_...`) The map `polar Q := λ x y, Q (x + y) - Q x - Q y` is bilinear.
They come with a scalar multiplication, `(a • Q) x = Q (a • x) = a * a * Q x`,
and composition with linear maps `f`, `Q.comp f x = Q (f x)`.
## Main definitions
* `quadratic_form.associated`: associated bilinear form
* `quadratic_form.pos_def`: positive definite quadratic forms
* `quadratic_form.discr`: discriminant of a quadratic form
## Main statements
* `quadratic_form.associated_left_inverse`,
* `quadratic_form.associated_right_inverse`: in a commutative ring where 2 has
an inverse, there is a correspondence between quadratic forms and symmetric
bilinear forms
## Notation
In this file, the variable `R` is used when a `ring` structure is sufficient and
`R₁` is used when specifically a `comm_ring` is required. This allows us to keep
`[module R M]` and `[module R₁ M]` assumptions in the variables without
confusion between `*` from `ring` and `*` from `comm_ring`.
## References
* https://en.wikipedia.org/wiki/Quadratic_form
* https://en.wikipedia.org/wiki/Discriminant#Quadratic_forms
## Tags
quadratic form, homogeneous polynomial, quadratic polynomial
-/
universes u v w
variables {R : Type u} {M : Type v} [add_comm_group M] [ring R]
variables {R₁ : Type u} [comm_ring R₁]
namespace quadratic_form
/-- Up to a factor 2, `Q.polar` is the associated bilinear form for a quadratic form `Q`.d
Source of this name: https://en.wikipedia.org/wiki/Quadratic_form#Generalization
-/
def polar (f : M → R) (x y : M) :=
f (x + y) - f x - f y
lemma polar_add (f g : M → R) (x y : M) :
polar (f + g) x y = polar f x y + polar g x y :=
by { simp only [polar, pi.add_apply], abel }
lemma polar_neg (f : M → R) (x y : M) :
polar (-f) x y = - polar f x y :=
by { simp only [polar, pi.neg_apply, sub_eq_add_neg, neg_add] }
lemma polar_smul (f : M → R) (s : R) (x y : M) :
polar (s • f) x y = s * polar f x y :=
by { simp only [polar, pi.smul_apply, smul_eq_mul, mul_sub] }
lemma polar_comm (f : M → R₁) (x y : M) : polar f x y = polar f y x :=
by rw [polar, polar, add_comm, sub_sub, sub_sub, add_comm (f x) (f y)]
end quadratic_form
variables [module R M] [module R₁ M]
open quadratic_form
/-- A quadratic form over a module. -/
structure quadratic_form (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] :=
(to_fun : M → R)
(to_fun_smul : ∀ (a : R) (x : M), to_fun (a • x) = a * a * to_fun x)
(polar_add_left' : ∀ (x x' y : M), polar to_fun (x + x') y = polar to_fun x y + polar to_fun x' y)
(polar_smul_left' : ∀ (a : R) (x y : M), polar to_fun (a • x) y = a • polar to_fun x y)
(polar_add_right' : ∀ (x y y' : M), polar to_fun x (y + y') = polar to_fun x y + polar to_fun x y')
(polar_smul_right' : ∀ (a : R) (x y : M), polar to_fun x (a • y) = a • polar to_fun x y)
namespace quadratic_form
variables {Q : quadratic_form R M}
instance : has_coe_to_fun (quadratic_form R M) :=
⟨_, λ B, B.to_fun⟩
/-- The `simp` normal form for a quadratic form is `coe_fn`, not `to_fun`. -/
@[simp] lemma to_fun_eq_apply : Q.to_fun = ⇑ Q := rfl
@[simp]
lemma polar_add_left (x x' y : M) :
polar Q (x + x') y = polar Q x y + polar Q x' y :=
Q.polar_add_left' x x' y
@[simp]
lemma polar_smul_left (a : R) (x y : M) :
polar Q (a • x) y = a * polar Q x y :=
Q.polar_smul_left' a x y
@[simp]
lemma polar_add_right (x y y' : M) :
polar Q x (y + y') = polar Q x y + polar Q x y' :=
Q.polar_add_right' x y y'
@[simp]
lemma polar_smul_right (a : R) (x y : M) :
polar Q x (a • y) = a * polar Q x y :=
Q.polar_smul_right' a x y
lemma map_smul (a : R) (x : M) : Q (a • x) = a * a * Q x := Q.to_fun_smul a x
lemma map_add_self (x : M) : Q (x + x) = 4 * Q x :=
by { rw [←one_smul R x, ←add_smul, map_smul], norm_num }
lemma map_zero : Q 0 = 0 :=
by rw [←@zero_smul R _ _ _ _ (0 : M), map_smul, zero_mul, zero_mul]
lemma map_neg (x : M) : Q (-x) = Q x :=
by rw [←@neg_one_smul R _ _ _ _ x, map_smul, neg_one_mul, neg_neg, one_mul]
lemma map_sub (x y : M) : Q (x - y) = Q (y - x) :=
by rw [←neg_sub, map_neg]
variable {Q' : quadratic_form R M}
@[ext] lemma ext (H : ∀ (x : M), Q x = Q' x) : Q = Q' :=
by { cases Q, cases Q', congr, funext, apply H }
instance : has_zero (quadratic_form R M) :=
⟨ { to_fun := λ x, 0,
to_fun_smul := λ a x, by simp,
polar_add_left' := λ x x' y, by simp [polar],
polar_smul_left' := λ a x y, by simp [polar],
polar_add_right' := λ x y y', by simp [polar],
polar_smul_right' := λ a x y, by simp [polar] } ⟩
@[simp] lemma zero_apply (x : M) : (0 : quadratic_form R M) x = 0 := rfl
instance : inhabited (quadratic_form R M) := ⟨0⟩
instance : has_add (quadratic_form R M) :=
⟨ λ Q Q',
{ to_fun := Q + Q',
to_fun_smul := λ a x,
by simp only [pi.add_apply, map_smul, mul_add],
polar_add_left' := λ x x' y,
by simp only [polar_add, polar_add_left, add_assoc, add_left_comm],
polar_smul_left' := λ a x y,
by simp only [polar_add, smul_eq_mul, mul_add, polar_smul_left],
polar_add_right' := λ x y y',
by simp only [polar_add, polar_add_right, add_assoc, add_left_comm],
polar_smul_right' := λ a x y,
by simp only [polar_add, smul_eq_mul, mul_add, polar_smul_right] } ⟩
@[simp] lemma coe_fn_add (Q Q' : quadratic_form R M) : ⇑(Q + Q') = Q + Q' := rfl
@[simp] lemma add_apply (Q Q' : quadratic_form R M) (x : M) : (Q + Q') x = Q x + Q' x := rfl
instance : has_neg (quadratic_form R M) :=
⟨ λ Q,
{ to_fun := -Q,
to_fun_smul := λ a x,
by simp only [pi.neg_apply, map_smul, mul_neg_eq_neg_mul_symm],
polar_add_left' := λ x x' y,
by simp only [polar_neg, polar_add_left, neg_add],
polar_smul_left' := λ a x y,
by simp only [polar_neg, polar_smul_left, mul_neg_eq_neg_mul_symm, smul_eq_mul],
polar_add_right' := λ x y y',
by simp only [polar_neg, polar_add_right, neg_add],
polar_smul_right' := λ a x y,
by simp only [polar_neg, polar_smul_right, mul_neg_eq_neg_mul_symm, smul_eq_mul] } ⟩
@[simp] lemma coe_fn_neg (Q : quadratic_form R M) : ⇑(-Q) = -Q := rfl
@[simp] lemma neg_apply (Q : quadratic_form R M) (x : M) : (-Q) x = -Q x := rfl
instance : has_scalar R₁ (quadratic_form R₁ M) :=
⟨ λ a Q,
{ to_fun := a • Q,
to_fun_smul := λ b x, by simp only [pi.smul_apply, map_smul, smul_eq_mul, mul_left_comm],
polar_add_left' := λ x x' y, by simp only [polar_smul, polar_add_left, mul_add],
polar_smul_left' := λ b x y,
by simp only [polar_smul, polar_smul_left, smul_eq_mul, mul_left_comm],
polar_add_right' := λ x y y', by simp only [polar_smul, polar_add_right, mul_add],
polar_smul_right' := λ b x y,
by simp only [polar_smul, polar_smul_right, smul_eq_mul, mul_left_comm] } ⟩
@[simp] lemma coe_fn_smul (a : R₁) (Q : quadratic_form R₁ M) : ⇑(a • Q) = a • Q := rfl
@[simp] lemma smul_apply (a : R₁) (Q : quadratic_form R₁ M) (x : M) : (a • Q) x = a * Q x := rfl
instance : add_comm_group (quadratic_form R M) :=
{ add_comm := λ Q Q', by { ext, simp only [add_apply, add_comm] },
add_assoc := λ Q Q' Q'', by { ext, simp only [add_apply, add_assoc] },
add_left_neg := λ Q, by { ext, simp only [add_apply, neg_apply, zero_apply, add_left_neg] },
add_zero := λ Q, by { ext, simp only [zero_apply, add_apply, add_zero] },
zero_add := λ Q, by { ext, simp only [zero_apply, add_apply, zero_add] },
..quadratic_form.has_add,
..quadratic_form.has_neg,
..quadratic_form.has_zero }
instance : module R₁ (quadratic_form R₁ M) :=
{ mul_smul := λ a b Q, ext (λ x, by simp only [smul_apply, mul_left_comm, mul_assoc]),
one_smul := λ Q, ext (λ x, by simp),
smul_add := λ a Q Q', by { ext, simp only [add_apply, smul_apply, mul_add] },
smul_zero := λ a, by { ext, simp only [zero_apply, smul_apply, mul_zero] },
zero_smul := λ Q, by { ext, simp only [zero_apply, smul_apply, zero_mul] },
add_smul := λ a b Q, by { ext, simp only [add_apply, smul_apply, add_mul] } }
section comp
variables {N : Type v} [add_comm_group N] [module R N]
/-- Compose the quadratic form with a linear function. -/
def comp (Q : quadratic_form R N) (f : M →ₗ[R] N) :
quadratic_form R M :=
{ to_fun := λ x, Q (f x),
to_fun_smul := λ a x, by simp only [map_smul, f.map_smul],
polar_add_left' := λ x x' y,
by convert polar_add_left (f x) (f x') (f y) using 1;
simp only [polar, f.map_add],
polar_smul_left' := λ a x y,
by convert polar_smul_left a (f x) (f y) using 1;
simp only [polar, f.map_smul, f.map_add, smul_eq_mul],
polar_add_right' := λ x y y',
by convert polar_add_right (f x) (f y) (f y') using 1;
simp only [polar, f.map_add],
polar_smul_right' := λ a x y,
by convert polar_smul_right a (f x) (f y) using 1;
simp only [polar, f.map_smul, f.map_add, smul_eq_mul] }
@[simp] lemma comp_apply (Q : quadratic_form R N) (f : M →ₗ[R] N) (x : M) :
(Q.comp f) x = Q (f x) := rfl
end comp
section comm_ring
/-- Create a quadratic form in a commutative ring by proving only one side of the bilinearity. -/
def mk_left (f : M → R₁)
(to_fun_smul : ∀ a x, f (a • x) = a * a * f x)
(polar_add_left : ∀ x x' y, polar f (x + x') y = polar f x y + polar f x' y)
(polar_smul_left : ∀ a x y, polar f (a • x) y = a * polar f x y) :
quadratic_form R₁ M :=
{ to_fun := f,
to_fun_smul := to_fun_smul,
polar_add_left' := polar_add_left,
polar_smul_left' := polar_smul_left,
polar_add_right' :=
λ x y y', by rw [polar_comm, polar_add_left, polar_comm f y x, polar_comm f y' x],
polar_smul_right' :=
λ a x y, by rw [polar_comm, polar_smul_left, polar_comm f y x, smul_eq_mul] }
/-- The product of linear forms is a quadratic form. -/
def lin_mul_lin (f g : M →ₗ[R₁] R₁) : quadratic_form R₁ M :=
mk_left (f * g)
(λ a x, by { simp, ring })
(λ x x' y, by { simp [polar], ring })
(λ a x y, by { simp [polar], ring })
@[simp]
lemma lin_mul_lin_apply (f g : M →ₗ[R₁] R₁) (x) : lin_mul_lin f g x = f x * g x := rfl
@[simp]
lemma add_lin_mul_lin (f g h : M →ₗ[R₁] R₁) :
lin_mul_lin (f + g) h = lin_mul_lin f h + lin_mul_lin g h :=
ext (λ x, add_mul _ _ _)
@[simp]
lemma lin_mul_lin_add (f g h : M →ₗ[R₁] R₁) :
lin_mul_lin f (g + h) = lin_mul_lin f g + lin_mul_lin f h :=
ext (λ x, mul_add _ _ _)
variables {N : Type v} [add_comm_group N] [module R₁ N]
@[simp]
lemma lin_mul_lin_comp (f g : M →ₗ[R₁] R₁) (h : N →ₗ[R₁] M) :
(lin_mul_lin f g).comp h = lin_mul_lin (f.comp h) (g.comp h) :=
rfl
variables {n : Type*}
/-- `proj i j` is the quadratic form mapping the vector `x : n → R₁` to `x i * x j` -/
def proj (i j : n) : quadratic_form R₁ (n → R₁) :=
lin_mul_lin (@linear_map.proj _ _ _ (λ _, R₁) _ _ i) (@linear_map.proj _ _ _ (λ _, R₁) _ _ j)
@[simp]
lemma proj_apply (i j : n) (x : n → R₁) : proj i j x = x i * x j := rfl
end comm_ring
end quadratic_form
/-!
### Associated bilinear forms
Over a commutative ring with an inverse of 2, the theory of quadratic forms is
basically identical to that of symmetric bilinear forms. The map from quadratic
forms to bilinear forms giving this identification is called the `associated`
quadratic form.
-/
variables {B : bilin_form R M}
namespace bilin_form
open quadratic_form
lemma polar_to_quadratic_form (x y : M) : polar (λ x, B x x) x y = B x y + B y x :=
by simp [polar, add_left, add_right, sub_eq_add_neg _ (B y y), add_comm (B y x) _, add_assoc]
/-- A bilinear form gives a quadratic form by applying the argument twice. -/
def to_quadratic_form (B : bilin_form R M) : quadratic_form R M :=
⟨ λ x, B x x,
λ a x, by simp [smul_left, smul_right, mul_assoc],
λ x x' y, by simp [polar_to_quadratic_form, add_left, add_right, add_left_comm, add_assoc],
λ a x y, by simp [polar_to_quadratic_form, smul_left, smul_right, mul_add],
λ x y y', by simp [polar_to_quadratic_form, add_left, add_right, add_left_comm, add_assoc],
λ a x y, by simp [polar_to_quadratic_form, smul_left, smul_right, mul_add] ⟩
@[simp] lemma to_quadratic_form_apply (B : bilin_form R M) (x : M) :
B.to_quadratic_form x = B x x :=
rfl
end bilin_form
namespace quadratic_form
open bilin_form sym_bilin_form
section associated
variables [invertible (2 : R₁)] {B₁ : bilin_form R₁ M}
/-- `associated` is the linear map that sends a quadratic form to its associated
symmetric bilinear form -/
def associated : quadratic_form R₁ M →ₗ[R₁] bilin_form R₁ M :=
{ to_fun := λ Q,
{ bilin := λ x y, ⅟2 * polar Q x y,
bilin_add_left := λ x y z, by rw [← mul_add, polar_add_left],
bilin_smul_left := λ x y z, by rw [← mul_left_comm, polar_smul_left],
bilin_add_right := λ x y z, by rw [← mul_add, polar_add_right],
bilin_smul_right := λ x y z, by rw [← mul_left_comm, polar_smul_right] },
add := λ Q Q', by { ext, simp [bilin_form.add_apply, polar_add, mul_add] },
smul := λ a Q, by { ext, simp [bilin_form.smul_apply, polar_smul, mul_left_comm] },
}
variables {Q : quadratic_form R₁ M}
@[simp] lemma associated_apply (x y : M) :
associated Q x y = ⅟2 * (Q (x + y) - Q x - Q y) := rfl
lemma associated_is_sym : is_sym Q.associated :=
λ x y, by simp [add_comm, add_left_comm, sub_eq_add_neg]
@[simp] lemma associated_comp {N : Type v} [add_comm_group N] [module R₁ N] (f : N →ₗ[R₁] M) :
(Q.comp f).associated = Q.associated.comp f f :=
by { ext, simp }
@[simp] lemma associated_lin_mul_lin (f g : M →ₗ[R₁] R₁) :
(lin_mul_lin f g).associated =
⅟(2 : R₁) • (bilin_form.lin_mul_lin f g + bilin_form.lin_mul_lin g f) :=
by { ext, simp [bilin_form.add_apply, bilin_form.smul_apply], ring }
lemma associated_to_quadratic_form (B : bilin_form R₁ M) (x y : M) :
associated B.to_quadratic_form x y = ⅟2 * (B x y + B y x) :=
by simp [associated_apply, ←polar_to_quadratic_form, polar]
lemma associated_left_inverse (h : is_sym B₁) :
B₁.to_quadratic_form.associated = B₁ :=
bilin_form.ext $ λ x y,
by rw [associated_to_quadratic_form, sym h x y, ←two_mul, ←mul_assoc, inv_of_mul_self, one_mul]
lemma associated_right_inverse : Q.associated.to_quadratic_form = Q :=
quadratic_form.ext $ λ x,
calc Q.associated.to_quadratic_form x
= ⅟2 * (Q x + Q x) : by simp [map_add_self, bit0, add_mul, add_assoc]
... = Q x : by rw [← two_mul (Q x), ←mul_assoc, inv_of_mul_self, one_mul]
end associated
section pos_def
variables {R₂ : Type u} [ordered_ring R₂] [module R₂ M] {Q₂ : quadratic_form R₂ M}
/-- A positive definite quadratic form is positive on nonzero vectors. -/
def pos_def (Q₂ : quadratic_form R₂ M) : Prop := ∀ x ≠ 0, 0 < Q₂ x
lemma pos_def.smul {R} [linear_ordered_comm_ring R] [module R M]
{Q : quadratic_form R M} (h : pos_def Q) {a : R} (a_pos : 0 < a) : pos_def (a • Q) :=
λ x hx, mul_pos a_pos (h x hx)
variables {n : Type*}
lemma pos_def.add (Q Q' : quadratic_form R₂ M) (hQ : pos_def Q) (hQ' : pos_def Q') :
pos_def (Q + Q') :=
λ x hx, add_pos (hQ x hx) (hQ' x hx)
lemma lin_mul_lin_self_pos_def {R} [linear_ordered_comm_ring R] [module R M]
(f : M →ₗ[R] R) (hf : linear_map.ker f = ⊥) :
pos_def (lin_mul_lin f f) :=
λ x hx, mul_self_pos (λ h, hx (linear_map.ker_eq_bot.mp hf (by rw [h, linear_map.map_zero])))
end pos_def
end quadratic_form
section
/-!
### Quadratic forms and matrices
Connect quadratic forms and matrices, in order to explicitly compute with them.
The convention is twos out, so there might be a factor 2⁻¹ in the entries of the
matrix.
The determinant of the matrix is the discriminant of the quadratic form.
-/
variables {n : Type w} [fintype n]
/-- `M.to_quadratic_form` is the map `λ x, col x ⬝ M ⬝ row x` as a quadratic form. -/
def matrix.to_quadratic_form (M : matrix n n R₁) : quadratic_form R₁ (n → R₁) :=
M.to_bilin_form.to_quadratic_form
variables [decidable_eq n] [invertible (2 : R₁)]
/-- A matrix representation of the quadratic form. -/
def quadratic_form.to_matrix (Q : quadratic_form R₁ (n → R₁)) :
matrix n n R₁ :=
Q.associated.to_matrix
open quadratic_form
lemma quadratic_form.to_matrix_smul (a : R₁) (Q : quadratic_form R₁ (n → R₁)) :
(a • Q).to_matrix = a • Q.to_matrix :=
by simp only [to_matrix, bilin_form.to_matrix_smul, linear_map.map_smul]
end
namespace quadratic_form
variables {n : Type w} [fintype n]
variables [decidable_eq n] [invertible (2 : R₁)]
variables {m : Type w} [fintype m] [decidable_eq m]
open_locale matrix
@[simp]
lemma to_matrix_comp (Q : quadratic_form R₁ (m → R₁)) (f : (n → R₁) →ₗ[R₁] (m → R₁)) :
(Q.comp f).to_matrix = f.to_matrixᵀ ⬝ Q.to_matrix ⬝ f.to_matrix :=
by { ext, simp [to_matrix, bilin_form.to_matrix_comp] }
section discriminant
variables {Q : quadratic_form R₁ (n → R₁)}
/-- The discriminant of a quadratic form generalizes the discriminant of a quadratic polynomial. -/
def discr (Q : quadratic_form R₁ (n → R₁)) : R₁ := Q.to_matrix.det
lemma discr_smul (a : R₁) : (a • Q).discr = a ^ fintype.card n * Q.discr :=
by simp only [discr, to_matrix_smul, matrix.det_smul]
lemma discr_comp (f : (n → R₁) →ₗ[R₁] (n → R₁)) :
(Q.comp f).discr = f.to_matrix.det * f.to_matrix.det * Q.discr :=
by simp [discr, mul_left_comm, mul_comm]
end discriminant
end quadratic_form
namespace quadratic_form
variables {M₁ : Type*} {M₂ : Type*} {M₃ : Type*}
variables [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M₁] [module R M₂] [module R M₃]
/-- An isometry between two quadratic spaces `M₁, Q₁` and `M₂, Q₂` over a ring `R`,
is a linear equivalence between `M₁` and `M₂` that commutes with the quadratic forms. -/
@[nolint has_inhabited_instance] structure isometry
(Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) extends M₁ ≃ₗ[R] M₂ :=
(map_app' : ∀ m, Q₂ (to_fun m) = Q₁ m)
/-- Two quadratic forms over a ring `R` are equivalent
if there exists an isometry between them:
a linear equivalence that transforms one quadratic form into the other. -/
def equivalent (Q₁ : quadratic_form R M₁) (Q₂ : quadratic_form R M₂) := nonempty (Q₁.isometry Q₂)
namespace isometry
variables {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃}
instance : has_coe (Q₁.isometry Q₂) (M₁ ≃ₗ[R] M₂) := ⟨isometry.to_linear_equiv⟩
instance : has_coe_to_fun (Q₁.isometry Q₂) :=
{ F := λ _, M₁ → M₂, coe := λ f, ⇑(f : M₁ ≃ₗ[R] M₂) }
@[simp] lemma map_app (f : Q₁.isometry Q₂) (m : M₁) : Q₂ (f m) = Q₁ m := f.map_app' m
/-- The identity isometry from a quadratic form to itself. -/
@[refl]
def refl (Q : quadratic_form R M) : Q.isometry Q :=
{ map_app' := λ m, rfl,
.. linear_equiv.refl R M }
/-- The inverse isometry of an isometry between two quadratic forms. -/
@[symm]
def symm (f : Q₁.isometry Q₂) : Q₂.isometry Q₁ :=
{ map_app' := by { intro m, rw ← f.map_app, congr, exact f.to_linear_equiv.apply_symm_apply m },
.. (f : M₁ ≃ₗ[R] M₂).symm }
/-- The composition of two isometries between quadratic forms. -/
@[trans]
def trans (f : Q₁.isometry Q₂) (g : Q₂.isometry Q₃) : Q₁.isometry Q₃ :=
{ map_app' := by { intro m, rw [← f.map_app, ← g.map_app], refl },
.. (f : M₁ ≃ₗ[R] M₂).trans (g : M₂ ≃ₗ[R] M₃) }
end isometry
namespace equivalent
variables {Q₁ : quadratic_form R M₁} {Q₂ : quadratic_form R M₂} {Q₃ : quadratic_form R M₃}
@[refl]
lemma refl (Q : quadratic_form R M) : Q.equivalent Q := ⟨isometry.refl Q⟩
@[symm]
lemma symm (h : Q₁.equivalent Q₂) : Q₂.equivalent Q₁ := h.elim $ λ f, ⟨f.symm⟩
@[trans]
lemma trans (h : Q₁.equivalent Q₂) (h' : Q₂.equivalent Q₃) : Q₁.equivalent Q₃ :=
h'.elim $ h.elim $ λ f g, ⟨f.trans g⟩
end equivalent
end quadratic_form
|
f20614df8f1ee56fd39b32eb6befbfa59051f094 | 097294e9b80f0d9893ac160b9c7219aa135b51b9 | /instructor/types/option/dm_option_test.lean | 255e8d4cc200875585055e40a2b357365a07dcd3 | [] | no_license | AbigailCastro17/CS2102-Discrete-Math | cf296251be9418ce90206f5e66bde9163e21abf9 | d741e4d2d6a9b2e0c8380e51706218b8f608cee4 | refs/heads/main | 1,682,891,087,358 | 1,621,401,341,000 | 1,621,401,341,000 | 368,749,959 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 576 | lean | import .dm_option
open hidden
/-
Because the type argument is now
implicit, if we want to give it
explicitly, we need to turn off
implicit args with @.
-/
def o1 := @dm_option.none -- Hmm. Check it.
#check @dm_option.none
-- Ah, partial evaluation
-- Now we give type arg explicitly
def o2 := @dm_option.none bool
def o3 := dm_option.some tt
-- Now we represent a partial func p
-- defined for n=0, otherwise undefined
def p : ℕ → dm_option ℕ
| nat.zero := dm_option.some nat.zero
| _ := dm_option.none
#reduce p 0
#reduce p 1
#reduce p 2
-- etc |
18885c4c80840f2c34ac8f99275961061bfa7465 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/analysis/normed_space/linear_isometry.lean | cf114fb7bb08ee3dad35b5a020d77a807c0ec351 | [] | 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 | 25,305 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.metric_space.isometry
import Mathlib.PostPort
universes u_6 u_7 u_8 l u_1 u_2 u_3 u_4 u_5
namespace Mathlib
/-!
# Linear isometries
In this file we define `linear_isometry R E F` (notation: `E →ₗᵢ[R] F`) to be a linear isometric
embedding of `E` into `F` and `linear_isometry_equiv` (notation: `E ≃ₗᵢ[R] F`) to be a linear
isometric equivalence between `E` and `F`.
We also prove some trivial lemmas and provide convenience constructors.
-/
/-- An `R`-linear isometric embedding of one normed `R`-module into another. -/
structure linear_isometry (R : Type u_6) (E : Type u_7) (F : Type u_8) [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F]
extends linear_map R E F
where
norm_map' : ∀ (x : E), norm (coe_fn _to_linear_map x) = norm x
namespace linear_isometry
protected instance has_coe_to_fun {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] : has_coe_to_fun (linear_isometry R E F) :=
has_coe_to_fun.mk (fun (f : linear_isometry R E F) => E → F)
fun (f : linear_isometry R E F) => linear_map.to_fun (to_linear_map f)
@[simp] theorem coe_to_linear_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : ⇑(to_linear_map f) = ⇑f :=
rfl
theorem to_linear_map_injective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] : function.injective to_linear_map := sorry
theorem coe_fn_injective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] : function.injective fun (f : linear_isometry R E F) (x : E) => coe_fn f x :=
function.injective.comp linear_map.coe_injective to_linear_map_injective
theorem ext {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] {f : linear_isometry R E F} {g : linear_isometry R E F} (h : ∀ (x : E), coe_fn f x = coe_fn g x) : f = g :=
coe_fn_injective (funext h)
@[simp] theorem map_zero {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : coe_fn f 0 = 0 :=
linear_map.map_zero (to_linear_map f)
@[simp] theorem map_add {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (x : E) (y : E) : coe_fn f (x + y) = coe_fn f x + coe_fn f y :=
linear_map.map_add (to_linear_map f) x y
@[simp] theorem map_sub {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (x : E) (y : E) : coe_fn f (x - y) = coe_fn f x - coe_fn f y :=
linear_map.map_sub (to_linear_map f) x y
@[simp] theorem map_smul {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (c : R) (x : E) : coe_fn f (c • x) = c • coe_fn f x :=
linear_map.map_smul (to_linear_map f) c x
@[simp] theorem norm_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (x : E) : norm (coe_fn f x) = norm x :=
norm_map' f x
@[simp] theorem nnnorm_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (x : E) : nnnorm (coe_fn f x) = nnnorm x :=
nnreal.eq (norm_map f x)
protected theorem isometry {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : isometry ⇑f :=
add_monoid_hom.isometry_of_norm (linear_map.to_add_monoid_hom (to_linear_map f)) (norm_map f)
@[simp] theorem dist_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (x : E) (y : E) : dist (coe_fn f x) (coe_fn f y) = dist x y :=
isometry.dist_eq (linear_isometry.isometry f) x y
@[simp] theorem edist_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (x : E) (y : E) : edist (coe_fn f x) (coe_fn f y) = edist x y :=
isometry.edist_eq (linear_isometry.isometry f) x y
protected theorem injective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : function.injective ⇑f :=
isometry.injective (linear_isometry.isometry f)
theorem map_eq_iff {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) {x : E} {y : E} : coe_fn f x = coe_fn f y ↔ x = y :=
function.injective.eq_iff (linear_isometry.injective f)
theorem map_ne {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) {x : E} {y : E} (h : x ≠ y) : coe_fn f x ≠ coe_fn f y :=
function.injective.ne (linear_isometry.injective f) h
protected theorem lipschitz {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : lipschitz_with 1 ⇑f :=
isometry.lipschitz (linear_isometry.isometry f)
protected theorem antilipschitz {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : antilipschitz_with 1 ⇑f :=
isometry.antilipschitz (linear_isometry.isometry f)
protected theorem continuous {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : continuous ⇑f :=
isometry.continuous (linear_isometry.isometry f)
theorem ediam_image {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (s : set E) : emetric.diam (⇑f '' s) = emetric.diam s :=
isometry.ediam_image (linear_isometry.isometry f) s
theorem ediam_range {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : emetric.diam (set.range ⇑f) = emetric.diam set.univ :=
isometry.ediam_range (linear_isometry.isometry f)
theorem diam_image {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) (s : set E) : metric.diam (⇑f '' s) = metric.diam s :=
isometry.diam_image (linear_isometry.isometry f) s
theorem diam_range {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : metric.diam (set.range ⇑f) = metric.diam set.univ :=
isometry.diam_range (linear_isometry.isometry f)
/-- Interpret a linear isometry as a continuous linear map. -/
def to_continuous_linear_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : continuous_linear_map R E F :=
continuous_linear_map.mk (to_linear_map f)
@[simp] theorem coe_to_continuous_linear_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : ⇑(to_continuous_linear_map f) = ⇑f :=
rfl
@[simp] theorem comp_continuous_iff {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) {α : Type u_4} [topological_space α] {g : α → E} : continuous (⇑f ∘ g) ↔ continuous g := sorry
/-- The identity linear isometry. -/
def id {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : linear_isometry R E E :=
mk linear_map.id sorry
@[simp] theorem coe_id {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : ⇑id = ⇑id :=
rfl
protected instance inhabited {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : Inhabited (linear_isometry R E E) :=
{ default := id }
/-- Composition of linear isometries. -/
def comp {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} [semiring R] [normed_group E] [normed_group F] [normed_group G] [semimodule R E] [semimodule R F] [semimodule R G] (g : linear_isometry R F G) (f : linear_isometry R E F) : linear_isometry R E G :=
mk (linear_map.comp (to_linear_map g) (to_linear_map f)) sorry
@[simp] theorem coe_comp {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} [semiring R] [normed_group E] [normed_group F] [normed_group G] [semimodule R E] [semimodule R F] [semimodule R G] (g : linear_isometry R F G) (f : linear_isometry R E F) : ⇑(comp g f) = ⇑g ∘ ⇑f :=
rfl
@[simp] theorem id_comp {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : comp id f = f :=
ext fun (x : E) => rfl
@[simp] theorem comp_id {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (f : linear_isometry R E F) : comp f id = f :=
ext fun (x : E) => rfl
theorem comp_assoc {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} {G' : Type u_5} [semiring R] [normed_group E] [normed_group F] [normed_group G] [normed_group G'] [semimodule R E] [semimodule R F] [semimodule R G] [semimodule R G'] (f : linear_isometry R G G') (g : linear_isometry R F G) (h : linear_isometry R E F) : comp (comp f g) h = comp f (comp g h) :=
rfl
protected instance monoid {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : monoid (linear_isometry R E E) :=
monoid.mk comp comp_assoc id id_comp comp_id
@[simp] theorem coe_one {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : ⇑1 = ⇑id :=
rfl
@[simp] theorem coe_mul {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] (f : linear_isometry R E E) (g : linear_isometry R E E) : ⇑(f * g) = ⇑f ∘ ⇑g :=
rfl
end linear_isometry
/-- A linear isometric equivalence between two normed vector spaces. -/
structure linear_isometry_equiv (R : Type u_6) (E : Type u_7) (F : Type u_8) [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F]
extends linear_equiv R E F
where
norm_map' : ∀ (x : E), norm (coe_fn _to_linear_equiv x) = norm x
namespace linear_isometry_equiv
protected instance has_coe_to_fun {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] : has_coe_to_fun (linear_isometry_equiv R E F) :=
has_coe_to_fun.mk (fun (f : linear_isometry_equiv R E F) => E → F)
fun (f : linear_isometry_equiv R E F) => linear_equiv.to_fun (to_linear_equiv f)
@[simp] theorem coe_mk {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_equiv R E F) (he : ∀ (x : E), norm (coe_fn e x) = norm x) : ⇑(mk e he) = ⇑e :=
rfl
@[simp] theorem coe_to_linear_equiv {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : ⇑(to_linear_equiv e) = ⇑e :=
rfl
theorem to_linear_equiv_injective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] : function.injective to_linear_equiv := sorry
theorem ext {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] {e : linear_isometry_equiv R E F} {e' : linear_isometry_equiv R E F} (h : ∀ (x : E), coe_fn e x = coe_fn e' x) : e = e' :=
to_linear_equiv_injective (linear_equiv.ext h)
/-- Construct a `linear_isometry_equiv` from a `linear_equiv` and two inequalities:
`∀ x, ∥e x∥ ≤ ∥x∥` and `∀ y, ∥e.symm y∥ ≤ ∥y∥`. -/
def of_bounds {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_equiv R E F) (h₁ : ∀ (x : E), norm (coe_fn e x) ≤ norm x) (h₂ : ∀ (y : F), norm (coe_fn (linear_equiv.symm e) y) ≤ norm y) : linear_isometry_equiv R E F :=
mk e sorry
@[simp] theorem norm_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) : norm (coe_fn e x) = norm x :=
norm_map' e x
/-- Reinterpret a `linear_isometry_equiv` as a `linear_isometry`. -/
def to_linear_isometry {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : linear_isometry R E F :=
linear_isometry.mk (↑(to_linear_equiv e)) (norm_map' e)
protected theorem isometry {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : isometry ⇑e :=
linear_isometry.isometry (to_linear_isometry e)
/-- Reinterpret a `linear_isometry_equiv` as an `isometric`. -/
def to_isometric {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : E ≃ᵢ F :=
isometric.mk (linear_equiv.to_equiv (to_linear_equiv e)) (linear_isometry_equiv.isometry e)
protected theorem continuous {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : continuous ⇑e :=
isometry.continuous (linear_isometry_equiv.isometry e)
/-- Identity map as a `linear_isometry_equiv`. -/
def refl (R : Type u_1) (E : Type u_2) [semiring R] [normed_group E] [semimodule R E] : linear_isometry_equiv R E E :=
mk (linear_equiv.refl R E) sorry
protected instance inhabited {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : Inhabited (linear_isometry_equiv R E E) :=
{ default := refl R E }
@[simp] theorem coe_refl {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : ⇑(refl R E) = id :=
rfl
/-- The inverse `linear_isometry_equiv`. -/
def symm {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : linear_isometry_equiv R F E :=
mk (linear_equiv.symm (to_linear_equiv e)) sorry
@[simp] theorem apply_symm_apply {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : F) : coe_fn e (coe_fn (symm e) x) = x :=
linear_equiv.apply_symm_apply (to_linear_equiv e) x
@[simp] theorem symm_apply_apply {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) : coe_fn (symm e) (coe_fn e x) = x :=
linear_equiv.symm_apply_apply (to_linear_equiv e) x
@[simp] theorem map_eq_zero_iff {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) {x : E} : coe_fn e x = 0 ↔ x = 0 :=
linear_equiv.map_eq_zero_iff (to_linear_equiv e)
@[simp] theorem symm_symm {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : symm (symm e) = e :=
ext fun (x : E) => rfl
@[simp] theorem coe_symm_to_linear_equiv {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : ⇑(linear_equiv.symm (to_linear_equiv e)) = ⇑(symm e) :=
rfl
/-- Composition of `linear_isometry_equiv`s as a `linear_isometry_equiv`. -/
def trans {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} [semiring R] [normed_group E] [normed_group F] [normed_group G] [semimodule R E] [semimodule R F] [semimodule R G] (e : linear_isometry_equiv R E F) (e' : linear_isometry_equiv R F G) : linear_isometry_equiv R E G :=
mk (linear_equiv.trans (to_linear_equiv e) (to_linear_equiv e')) sorry
@[simp] theorem coe_trans {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} [semiring R] [normed_group E] [normed_group F] [normed_group G] [semimodule R E] [semimodule R F] [semimodule R G] (e₁ : linear_isometry_equiv R E F) (e₂ : linear_isometry_equiv R F G) : ⇑(trans e₁ e₂) = ⇑e₂ ∘ ⇑e₁ :=
rfl
@[simp] theorem trans_refl {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : trans e (refl R F) = e :=
ext fun (x : E) => rfl
@[simp] theorem refl_trans {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : trans (refl R E) e = e :=
ext fun (x : E) => rfl
@[simp] theorem trans_symm {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : trans e (symm e) = refl R E :=
ext (symm_apply_apply e)
@[simp] theorem symm_trans {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : trans (symm e) e = refl R F :=
ext (apply_symm_apply e)
@[simp] theorem coe_symm_trans {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} [semiring R] [normed_group E] [normed_group F] [normed_group G] [semimodule R E] [semimodule R F] [semimodule R G] (e₁ : linear_isometry_equiv R E F) (e₂ : linear_isometry_equiv R F G) : ⇑(symm (trans e₁ e₂)) = ⇑(symm e₁) ∘ ⇑(symm e₂) :=
rfl
theorem trans_assoc {R : Type u_1} {E : Type u_2} {F : Type u_3} {G : Type u_4} {G' : Type u_5} [semiring R] [normed_group E] [normed_group F] [normed_group G] [normed_group G'] [semimodule R E] [semimodule R F] [semimodule R G] [semimodule R G'] (eEF : linear_isometry_equiv R E F) (eFG : linear_isometry_equiv R F G) (eGG' : linear_isometry_equiv R G G') : trans eEF (trans eFG eGG') = trans (trans eEF eFG) eGG' :=
rfl
protected instance group {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : group (linear_isometry_equiv R E E) :=
group.mk (fun (e₁ e₂ : linear_isometry_equiv R E E) => trans e₂ e₁) sorry (refl R E) trans_refl refl_trans symm
(div_inv_monoid.div._default (fun (e₁ e₂ : linear_isometry_equiv R E E) => trans e₂ e₁) sorry (refl R E) trans_refl
refl_trans symm)
trans_symm
@[simp] theorem coe_one {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] : ⇑1 = id :=
rfl
@[simp] theorem coe_mul {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] (e : linear_isometry_equiv R E E) (e' : linear_isometry_equiv R E E) : ⇑(e * e') = ⇑e ∘ ⇑e' :=
rfl
@[simp] theorem coe_inv {R : Type u_1} {E : Type u_2} [semiring R] [normed_group E] [semimodule R E] (e : linear_isometry_equiv R E E) : ⇑(e⁻¹) = ⇑(symm e) :=
rfl
/-- Reinterpret a `linear_isometry_equiv` as a `continuous_linear_equiv`. -/
def to_continuous_linear_equiv {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : continuous_linear_equiv R E F :=
continuous_linear_equiv.mk (to_linear_equiv e)
@[simp] theorem map_zero {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : coe_fn e 0 = 0 :=
linear_equiv.map_zero (to_linear_equiv e)
@[simp] theorem map_add {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) (y : E) : coe_fn e (x + y) = coe_fn e x + coe_fn e y :=
linear_equiv.map_add (to_linear_equiv e) x y
@[simp] theorem map_sub {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) (y : E) : coe_fn e (x - y) = coe_fn e x - coe_fn e y :=
linear_equiv.map_sub (to_linear_equiv e) x y
@[simp] theorem map_smul {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (c : R) (x : E) : coe_fn e (c • x) = c • coe_fn e x :=
linear_equiv.map_smul (to_linear_equiv e) c x
@[simp] theorem nnnorm_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) : nnnorm (coe_fn e x) = nnnorm x :=
linear_isometry.nnnorm_map (to_linear_isometry e) x
@[simp] theorem dist_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) (y : E) : dist (coe_fn e x) (coe_fn e y) = dist x y :=
linear_isometry.dist_map (to_linear_isometry e) x y
@[simp] theorem edist_map {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (x : E) (y : E) : edist (coe_fn e x) (coe_fn e y) = edist x y :=
linear_isometry.edist_map (to_linear_isometry e) x y
protected theorem bijective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : function.bijective ⇑e :=
linear_equiv.bijective (to_linear_equiv e)
protected theorem injective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : function.injective ⇑e :=
linear_equiv.injective (to_linear_equiv e)
protected theorem surjective {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : function.surjective ⇑e :=
linear_equiv.surjective (to_linear_equiv e)
theorem map_eq_iff {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) {x : E} {y : E} : coe_fn e x = coe_fn e y ↔ x = y :=
function.injective.eq_iff (linear_isometry_equiv.injective e)
theorem map_ne {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) {x : E} {y : E} (h : x ≠ y) : coe_fn e x ≠ coe_fn e y :=
function.injective.ne (linear_isometry_equiv.injective e) h
protected theorem lipschitz {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : lipschitz_with 1 ⇑e :=
isometry.lipschitz (linear_isometry_equiv.isometry e)
protected theorem antilipschitz {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) : antilipschitz_with 1 ⇑e :=
isometry.antilipschitz (linear_isometry_equiv.isometry e)
theorem ediam_image {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (s : set E) : emetric.diam (⇑e '' s) = emetric.diam s :=
isometry.ediam_image (linear_isometry_equiv.isometry e) s
theorem diam_image {R : Type u_1} {E : Type u_2} {F : Type u_3} [semiring R] [normed_group E] [normed_group F] [semimodule R E] [semimodule R F] (e : linear_isometry_equiv R E F) (s : set E) : metric.diam (⇑e '' s) = metric.diam s :=
isometry.diam_image (linear_isometry_equiv.isometry e) s
|
dcbfd2d2e475889c5e6e492c1b78587be95d59dd | 670b1582ba4780d3b4a49063d5afea44a337bc24 | /src/tptp/tptp.lean | 598d32ed914349a2ce9e178aed4ecd69bb6308f5 | [] | no_license | robertylewis/Lean_hammer | 9bd8a75cb6fc76b3387c84f0678ccfd69fa10c88 | 7c8b6235c064fac164cbd389c8d459bd106e09b1 | refs/heads/master | 1,587,608,490,192 | 1,550,228,670,000 | 1,550,228,670,000 | 170,843,813 | 0 | 0 | null | 1,550,225,214,000 | 1,550,225,213,000 | null | UTF-8 | Lean | false | false | 21,343 | lean |
@[reducible] meta def debruijn := nat
meta def neg : bool → bool
| tt := ff
| ff := tt
meta inductive folpred
| P : folpred
| T : folpred
| eq : folpred
meta inductive folterm
| const : name → folterm -- Constant with given label
| lconst : name → name → folterm --
| prf : folterm
| var : debruijn → folterm -- Variable, but what is debruijn for? Are variables just specified by counter? X1,X2,X3,...
| app : folterm → folterm → folterm -- @(t,s) is the same as t s => apply t on input s
meta inductive folform
| P : folterm → folform -- P(t) represents the provability of t
| T : folterm → folterm → folform -- T(t,τ) represents that t has type τ
| eq : folterm → folterm → folform -- Equality. t == s
| bottom : folform -- Constant False
| top : folform -- Constant True
| neg : folform → folform -- Negation function. ¬A
| imp : folform → folform → folform -- Imply: A → B
| iff : folform → folform → folform -- Two-sided imply/iff: A ↔ B
| conj : folform → folform → folform -- Conjunction: A ∧ B
| disj : folform → folform → folform -- Disjunction: A ∨ B
| all : name → name → folform → folform -- For all: ∀ (a : α) t -- a and α are the names, t the formula
| exist : name → name → folform → folform -- Exists: ∃ (a : α) t -- Similar as above
meta structure introduced_constant := -- Structure representing a new constant introduced for translation
(n : name) (e : expr) -- name and type
meta structure axioma := -- Note: axiom is reserved word in Lean, thus the additional a
(n : name) (f : folform) -- Every axiom is specified by a name and its formula
meta structure hammer_state := -- Structure representing the state of the hammer (list of axioms with corresponding list of newly introduced constants for translation)
(axiomas : list axioma)
(introduced_constants : list introduced_constant)
meta def hammer_tactic :=
state_t hammer_state tactic
section tptp
open format
-- Used functions from this set
-- 1) to_fmt: {α : Type} (a : α) := a → format => returns a format object for an instance of any type
-- 2)
-- axiom is a reserved word in Lean
meta inductive role -- Role of a formula. Can be either axiom or conjecture (for tptp format)
| axioma : role
| conjecture : role
meta def role.to_format : role → format -- Probably decide how to print a formula?
| role.axioma := to_fmt "axiom"
| role.conjecture := to_fmt "conjecture"
/-
has_to_format instances tell Lean how to print objects of this type.
e.g. if you `#eval t` where `t : role`, this tells Lean to use `roll.to_format` to print the
result of the eval.
-/
meta instance : has_to_format role := -- What is this for?
⟨role.to_format⟩
meta def folterm.to_name : folterm → name
| (folterm.const n) := "c_" ++ n
| (folterm.lconst n1 n2) := "lc_" ++ n1 ++ "_" ++ n2
| (folterm.prf) := "prf"
| (folterm.var n) := "var"
| (folterm.app t u) := "a_" ++ t.to_name ++ "-" ++ u.to_name
-- Check whether a folterm is a constant expression or not (does it contain a variable or not?)
meta def folterm.is_const : folterm → bool
| (folterm.const _) := tt
| (folterm.lconst _ _) := tt
| (folterm.prf) := tt
| (folterm.var _) := ff
| (folterm.app t u) := t.is_const && u.is_const
meta def folterm.is_eq : folterm → folterm → bool
| (folterm.const n1) (folterm.const n2) := (n1 = n2)
| (folterm.const _) _ := ff
| (folterm.lconst n1 l1) (folterm.lconst n2 l2) := (n1 = n2) && (l1 = l2)
| (folterm.lconst _ _) _ := ff
| (folterm.prf) (folterm.prf) := tt
| (folterm.prf) _ := ff
| (folterm.var n1) (folterm.var n2) := (n1 = n2)
| (folterm.var _) _ := ff
| (folterm.app t1 u1) (folterm.app t2 u2) := (t1.is_eq t2) && (u1.is_eq u2)
| (folterm.app _ _) _ := ff
meta def folterm.is_eq_besides_vars : folterm → folterm → bool
| (folterm.var _) _ := tt
| _ (folterm.var _) := tt
| (folterm.const n1) (folterm.const n2) := (n1 = n2)
| (folterm.const _) _ := ff
| (folterm.lconst n1 l1) (folterm.lconst n2 l2) := (n1 = n2) && (l1 = l2)
| (folterm.lconst _ _) _ := ff
| (folterm.prf) (folterm.prf) := tt
| (folterm.prf) _ := ff
| (folterm.app t1 u1) (folterm.app t2 u2) := (t1.is_eq_besides_vars t2) && (u1.is_eq_besides_vars u2)
| (folterm.app _ _) _ := ff
meta def folterm.is_eq_besides_deeper_vars : folterm → folterm → bool
| (folterm.var _) _ := ff
| _ (folterm.var _) := ff
| (folterm.const n1) (folterm.const n2) := (n1 = n2)
| (folterm.const _) _ := ff
| (folterm.lconst n1 l1) (folterm.lconst n2 l2) := (n1 = n2) && (l1 = l2)
| (folterm.lconst _ _) _ := ff
| (folterm.prf) (folterm.prf) := tt
| (folterm.prf) _ := ff
| (folterm.app t1 u1) (folterm.app t2 u2) := (t1.is_eq_besides_vars t2) && (u1.is_eq_besides_vars u2)
| (folterm.app _ _) _ := ff
meta def folterm.replace : folterm → folterm → folterm → folterm
| orig@(folterm.app t u) old_term new_term := if orig.is_eq old_term then new_term else folterm.app (folterm.replace t old_term new_term) (folterm.replace u old_term new_term)
| orig old_term new_term := if orig.is_eq old_term then new_term else orig
meta def folform.replace_term : folform → folterm → folterm → folform
| orig@(folform.P t) old_term new_term := folform.P $ t.replace old_term new_term
| orig@(folform.T t1 t2) old_term new_term := folform.T (t1.replace old_term new_term) (t2.replace old_term new_term)
| orig@(folform.eq t1 t2) old_term new_term := folform.eq (t1.replace old_term new_term) (t2.replace old_term new_term)
| orig@(folform.neg f) old_term new_term := folform.neg (f.replace_term old_term new_term)
| orig@(folform.imp f1 f2) old_term new_term := folform.imp (f1.replace_term old_term new_term) (f2.replace_term old_term new_term)
| orig@(folform.iff f1 f2) old_term new_term := folform.iff (f1.replace_term old_term new_term) (f2.replace_term old_term new_term)
| orig@(folform.conj f1 f2) old_term new_term := folform.conj (f1.replace_term old_term new_term) (f2.replace_term old_term new_term)
| orig@(folform.disj f1 f2) old_term new_term := folform.disj (f1.replace_term old_term new_term) (f2.replace_term old_term new_term)
| orig@(folform.all n1 n2 f) old_term new_term := folform.all n1 n2 (f.replace_term old_term new_term)
| orig@(folform.exist n1 n2 f) old_term new_term := folform.exist n1 n2 (f.replace_term old_term new_term)
| orig _ _ := orig
meta def folterm.get_all_const_terms : folterm → list folterm
| c@(folterm.app t u) := if folterm.is_const c then [c] ++ t.get_all_const_terms ++ u.get_all_const_terms else t.get_all_const_terms ++ u.get_all_const_terms
-- All other parts are not considered as constant as we are not interested in replacing a constant by another constant
| (folterm.const _) := []
| (folterm.lconst _ _) := []
| (folterm.prf) := []
| (folterm.var _) := []
meta def folform.get_all_const_terms : folform → list folterm
| orig@(folform.P t) := t.get_all_const_terms
| orig@(folform.T t1 t2) := t1.get_all_const_terms ++ t2.get_all_const_terms
| orig@(folform.eq t1 t2) := t1.get_all_const_terms ++ t2.get_all_const_terms
| orig@(folform.neg f) := f.get_all_const_terms
| orig@(folform.imp f1 f2) := f1.get_all_const_terms ++ f2.get_all_const_terms
| orig@(folform.iff f1 f2) := f1.get_all_const_terms ++ f2.get_all_const_terms
| orig@(folform.conj f1 f2) := f1.get_all_const_terms ++ f2.get_all_const_terms
| orig@(folform.disj f1 f2) := f1.get_all_const_terms ++ f2.get_all_const_terms
| orig@(folform.all n1 n2 f) := f.get_all_const_terms
| orig@(folform.exist n1 n2 f) := f.get_all_const_terms
| orig := []
meta def folterm.contains_only_const : folterm → folterm → bool
| c@(folterm.app t u) ct := if (c.is_eq_besides_deeper_vars ct) && (neg c.is_const) then ff else t.contains_only_const ct && u.contains_only_const ct
| c ct := (neg (c.is_eq_besides_deeper_vars ct)) || (c.is_const)
meta def folform.contains_only_const : folform → folterm → bool
| orig@(folform.P t) ct := t.contains_only_const ct
| orig@(folform.T t1 t2) ct := t1.contains_only_const ct && t2.contains_only_const ct
| orig@(folform.eq t1 t2) ct := t1.contains_only_const ct && t2.contains_only_const ct
| orig@(folform.neg f) ct := f.contains_only_const ct
| orig@(folform.imp f1 f2) ct := f1.contains_only_const ct && f2.contains_only_const ct
| orig@(folform.iff f1 f2) ct := f1.contains_only_const ct && f2.contains_only_const ct
| orig@(folform.conj f1 f2) ct := f1.contains_only_const ct && f2.contains_only_const ct
| orig@(folform.disj f1 f2) ct := f1.contains_only_const ct && f2.contains_only_const ct
| orig@(folform.all n1 n2 f) ct := f.contains_only_const ct
| orig@(folform.exist n1 n2 f) ct := f.contains_only_const ct
| orig ct := tt
-- Retrieve a list of all free variables for a given formula, and return it as cartesian product (why as cartesian product?)
-- Only looks at the name but not the type of the variable...
meta def folform.to_format_collect_vars : folform → list name → (list name × folform)
| (folform.all n n1 e@(folform.all _ _ _)) xs := folform.to_format_collect_vars e (n :: xs)
| (folform.exist n n1 e@(folform.exist _ _ _)) xs := folform.to_format_collect_vars e (n :: xs)
| (folform.all n n1 e) xs := ((n :: xs).reverse, e)
| (folform.exist n n1 e) xs := ((n :: xs).reverse, e)
| e@_ xs := (xs.reverse, e)
-- Print name
meta def name_to_id_format : name → format
| n := "'" ++ to_fmt n ++ "'"
-- For a list of (probably free) variables, print out the name by calling V1, V2, ... with element x
meta def names_to_id_format : list name → nat → list format
| (x::xs) d := ("V" ++ to_fmt (d+1) ++ " /* " ++ to_fmt x ++ " */") :: names_to_id_format xs (d+1)
| [] d := []
-- For what do I have to define this type? It is an identity mapping of input to output
/-
I don't know. format objects are a little richer than strings -- they include grouping information
for pretty-printing with line breaks, etc. Maybe this is there as a future hook for better grouping.
Right now I don't think it does anything.
-/
meta def mygroup : format → format := id -- @[inline] def id {α : Sort u} (a : α) : α := a
-- Convert term into format. Second argument defines the depth (number of free variables that already have been defined in this formula)
/-
lconst is a local constant, not a long constant.
-/
meta def folterm.to_format : folterm → nat → format
| (folterm.const n) _ := "'" ++ to_fmt n ++ "'" -- A constant is converted into its name itself
| (folterm.lconst n _) _ := "'" ++ to_fmt n ++ "'" -- A long(?) constant is processed the same way
| (folterm.prf) _ := "prf" -- A proof is printed out as proof (is this a tptp convention?)
| (folterm.var i) depth := "V" ++ to_fmt (depth - i) -- Variable indicated by "V" and number. Last defined variable has number i=0, then it goes up to depth-1
| (folterm.app t u) depth := -- Apply t on u -> a('t', 'u')
"a(" ++ t.to_format depth ++ "," ++
(mygroup $ nest 2 $ line ++ u.to_format depth) ++ ")" -- Lean notation: "a $ b c" is the same as "a (b c)", just simplifies notation of brackets
-- Convert formula into format with extra input
-- depth: defines number of free variables that already have been defined
meta def folform.to_format_aux : folform → nat → format
-- For-all operator ∀ n:n1, f
| e@(folform.all n n1 f) depth :=
let (ys, g) := folform.to_format_collect_vars e [] in -- Define (ys,g) as the expression for all following statements
let ys' := names_to_id_format ys depth in
"! [" ++ -- ! is TPTP expression for ∀
(mygroup $ nest 3 $ (join $ list.intersperse ("," ++ line) ys') ++ "] :") ++ -- Print list of free variables
-- list.intersperse: put new element ","+newline between all elements. Similar to " ".join(list) in python
-- join: Composes multiple formats into one by (similar to) concatenating the single formats/strings
(mygroup $ nest 2 $ line ++ "(" ++ (mygroup $ nest 1 $ g.to_format_aux $ depth + ys.length)) ++ ")" -- Print subformula with different depth!
-- There-exists operator ∃ n:n1, f
| e@(folform.exist n n1 f) depth :=
-- Same process as ∀ but only change "!" by "?" for TPTP output
let (ys, g) := folform.to_format_collect_vars e [] in
let ys' := names_to_id_format ys depth in
"? [" ++
(mygroup $ nest 3 $ (join $ list.intersperse ("," ++ line) ys') ++ "] :") ++
(mygroup $ nest 2 $ line ++ "(" ++ (mygroup $ nest 1 $ g.to_format_aux $ depth + ys.length)) ++ ")"
-- Constant false
| folform.bottom _ := to_fmt "$false"
-- Constant true
| folform.top _ := to_fmt "$true"
-- Stating p function (p(t) returns whether t is proofable or not)
| (folform.P t) depth :=
"p(" ++ (nest 2 $ t.to_format depth) ++ ")"
-- Stating t function (T(t,u) returns whether t is of type u)
| (folform.T t u) depth :=
"t(" ++ (mygroup $ nest 2 $ t.to_format depth ++ "," ++ line ++ u.to_format depth ++ ")")
-- Equality relation t=u
| (folform.eq t u) depth :=
"(" ++ (nest 1 $ t.to_format depth ++
(mygroup $ line ++ "= " ++ (nest 2 $ u.to_format depth ++ ")")))
-- Negate f. If f is equality relation, just negate this one
| (folform.neg f) depth :=
match f with
| (folform.eq t u) := -- Equality relations are negated by '!=' instead of '~(...=...)'
"(" ++ (nest 1 $ t.to_format depth ++
(mygroup $ line ++ "!= " ++ (nest 3 $ u.to_format depth ++ ")")))
| _ := "~(" ++ (nest 2 $ f.to_format_aux depth ++ ")")
end
-- Imply f → g with token '=>' in TPTP notation
| (folform.imp f g) depth :=
"(" ++ (nest 1 $ f.to_format_aux depth ++ ")") ++
(mygroup $ line ++ (nest 4 $ "=> (" ++ g.to_format_aux depth ++ ")"))
-- Iff similar to imply
| (folform.iff f g) depth :=
"(" ++ (nest 1 $ f.to_format_aux depth ++ ")") ++
(mygroup $ line ++ (nest 5 $ "<=> (" ++ g.to_format_aux depth ++ ")"))
-- Conjecture f ∧ g
| (folform.conj f g) depth :=
"(" ++ (nest 1 $ f.to_format_aux depth ++ ")") ++
(mygroup $ line ++ (nest 3 $ "& (" ++ g.to_format_aux depth ++ ")"))
-- Disjunction f ∨ g
| (folform.disj f g) depth :=
"(" ++ (nest 1 $ f.to_format_aux depth ++ ")") ++
(mygroup $ line ++ (nest 3 $ "| (" ++ g.to_format_aux depth ++ ")"))
-- For outer formulas, start with depth 0 (all others use recursive function above)
meta def folform.to_format (f : folform) : format := folform.to_format_aux f 0
-- What for is this instance?
meta instance : has_to_format folform :=
⟨folform.to_format⟩
-- Convert formula with name and role to output string
meta def to_fof : string → role → folform → format
| id r f :=
to_fmt "fof("
++ (mygroup $ nest 4 $ join $ list.intersperse ("," ++ line) $ -- Combine all parts by "," and new line
[to_fmt id, to_fmt r, "(" ++ (mygroup $ nest 1 $ to_fmt f) ++ ")"]) ++ to_fmt ")." -- Output: fof(name, role, (formula)).
-- Combine list of axioma into single string
meta def to_tptp : list axioma → folform → format
| (⟨n, f⟩::as) conjecture :=
to_fof ("'" ++ to_string n ++ "'") role.axioma f
++ line
++ line
++ to_tptp as conjecture
| [] conjecture := to_fof "'problem_conjecture'" role.conjecture conjecture
-- What do we need this constant for?
-- For a list of elements, call "to_fmt" function and return as single string '[...]'
meta def myformat {α : Type} [has_to_format α] : list α → format
| [] := to_fmt "[]"
| xs := to_fmt "[" ++ mygroup (format.nest 1 $ format.join $ list.intersperse ("," ++ format.line) $ xs.map to_fmt) ++ to_fmt "]"
end tptp
-----------------------------------
---- Debug functions ----
-----------------------------------
-- 1) Print out a formula as it is
-- 2) Print a formula in TPTP form
meta def name.repr : name → string
| name.anonymous := "name.anonymous"
| (name.mk_numeral n p) := "(name.mk_numeral " ++ repr n ++ " " ++ name.repr p ++ ")"
| (name.mk_string s p) := "(name.mk_string " ++ repr s ++ " " ++ name.repr p ++ ")"
meta instance : has_repr name :=
⟨name.repr⟩
meta def folterm.repr : folterm → string
| (folterm.const n) := "(folterm.const " ++ repr n ++ ")"
| (folterm.lconst n n1) := "(folterm.lconst " ++ repr n ++ " " ++ repr n1 ++ ")"
| folterm.prf := "folterm.prf"
| (folterm.var n) := "(folterm.var " ++ repr n ++ ")"
| (folterm.app t1 t2) := "(folterm.app " ++ folterm.repr t1 ++ " " ++ folterm.repr t2 ++ ")"
meta instance : has_repr folterm :=
⟨folterm.repr⟩
meta def folpred.repr : folpred → string
| folpred.P := "folpred.P"
| folpred.T := "folpred.T"
| folpred.eq := "folpred.eq"
meta instance : has_repr folpred :=
⟨folpred.repr⟩
meta def folform.repr : folform → string
| (folform.P t) := "(folform.P " ++ repr t ++ ")"
| (folform.T t u) := "(folform.T " ++ repr t ++ " " ++ repr u ++ ")"
| (folform.eq t u) := "(folform.eq " ++ repr t ++ " " ++ repr u ++ ")"
| folform.bottom := "folform.bottom"
| folform.top := "folform.top"
| (folform.neg f) := "(folform.neg " ++ folform.repr f ++ ")"
| (folform.imp f g) := "(folform.imp " ++ folform.repr f ++ " " ++ folform.repr g ++ ")"
| (folform.iff f g) := "(folform.iff " ++ folform.repr f ++ " " ++ folform.repr g ++ ")"
| (folform.conj f g) := "(folform.conj " ++ folform.repr f ++ " " ++ folform.repr g ++ ")"
| (folform.disj f g) := "(folform.disj " ++ folform.repr f ++ " " ++ folform.repr g ++ ")"
| (folform.all n n1 f) := "(folform.all " ++ repr n ++ " " ++ repr n1 ++ " " ++ folform.repr f ++ ")"
| (folform.exist n n1 f) := "(folform.exist " ++ repr n ++ " " ++ repr n1 ++ " " ++ folform.repr f ++ ")"
meta instance : has_repr folform :=
⟨folform.repr⟩
meta def folterm.abstract_locals_core : folterm → ℕ → list name → folterm
| e@(folterm.lconst n n1) d ln :=
list.foldl
(λ e' n', if n = n' then folterm.var $ d + ln.reverse.find_index (= n) else e')
e
ln
| (folterm.app t1 t2) d ln := folterm.app (t1.abstract_locals_core d ln) (t2.abstract_locals_core d ln)
| e d ln := e
meta def folterm.abstract_locals : folterm → list name → folterm := λ f l, f.abstract_locals_core 0 l
meta def folform.abstract_locals_core : folform → nat → list name → folform
| e@(folform.P t) d ln := folform.P $ t.abstract_locals_core d ln
| e@(folform.T t u) d ln := folform.T (t.abstract_locals_core d ln) (u.abstract_locals_core d ln)
| e@(folform.eq t u) d ln := folform.eq (t.abstract_locals_core d ln) (u.abstract_locals_core d ln)
| e@(folform.neg f) d ln := folform.neg (f.abstract_locals_core d ln)
| e@(folform.imp f1 f2) d ln := folform.imp (f1.abstract_locals_core d ln) (f2.abstract_locals_core d ln)
| e@(folform.iff f1 f2) d ln := folform.iff (f1.abstract_locals_core d ln) (f2.abstract_locals_core d ln)
| e@(folform.conj f1 f2) d ln := folform.conj (f1.abstract_locals_core d ln) (f2.abstract_locals_core d ln)
| e@(folform.disj f1 f2) d ln := folform.disj (f1.abstract_locals_core d ln) (f2.abstract_locals_core d ln)
| e@(folform.all n n1 f) d ln := folform.all n n1 (f.abstract_locals_core (d+1) ln)
| e@(folform.exist n n1 f) d ln := folform.exist n n1 (f.abstract_locals_core (d+1) ln)
| e d ln := e
meta def folform.abstract_locals : folform → list name → folform := λ f l, f.abstract_locals_core 0 l
------------------------------------
------------------------------------
meta def example_formula : folform :=
folform.all `h1 `h1 $ folform.all `h2 `h2 $ -- folform.all `h3 `h3 $
folform.neg $
folform.iff
(folform.conj
(folform.neg $ folform.eq (folterm.var 0) (folterm.var 1))
(folform.eq (folterm.var 0) (folterm.var 1)) )
(folform.imp
(folform.conj (folform.P $ folterm.const "a") (folform.disj (folform.P $ folterm.var 0) (folform.P $ folterm.var 1)))
(folform.T (folterm.var 0) (folterm.app (folterm.var 1) (folterm.var 0))))
meta def example_formula2 : folform :=
folform.imp (folform.conj (folform.P $ folterm.const "n") (folform.P $ folterm.const "a"))
(folform.T (folterm.const "n") (folterm.app (folterm.const "n") (folterm.app (folterm.const "n") (folterm.const("a")))))
meta def print_list (l : list folterm) : tactic unit :=
l.reverse.mmap' $ λ x, tactic.trace (x.to_format 1)
-- run_cmd do let t1 := folterm.app (folterm.const "a") (folterm.var 1), let t2 := folterm.app (folterm.const "a") (folterm.var 1), tactic.trace $ t1.is_eq t2
-- run_cmd do let t1 := folterm.app (folterm.var 2) (folterm.const "a"), let t2 := folterm.app (folterm.const "a") (folterm.const "d"),
-- tactic.trace $ t1.is_eq_besides_vars t2,
-- tactic.trace $ t1.contains_only_const t2,
-- tactic.trace $ (folterm.var 2).contains_only_const t2
-- run_cmd do let form := example_formula2,
-- let t1 := folterm.app (folterm.const "n") (folterm.const "a"),
-- let t2 := folterm.const "n2",
-- tactic.trace $ t1.to_format 1,
-- tactic.trace $ t2.to_format 1,
-- tactic.trace form,
-- tactic.trace $ folform.replace_term form t1 t2,
-- print_list $ folform.get_all_const_terms form,
-- print_list $ folform.get_all_const_terms $ folform.replace_term form t1 t2
-- #eval tactic.trace $ to_fof "example_formula" role.axioma example_formula
-- #eval tactic.trace $ to_fof "example_formula2" role.conjecture example_formula2
-- #eval tactic.trace example_formula.repr
-----------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------
|
5b8ae9caadb1df3a336ccb19ae6425706bd8693e | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/ring_theory/power_series/basic.lean | 838c32c44e36e51767d32e22ed4ac18cf3a27fde | [
"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 | 64,515 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Kenny Lau
-/
import data.mv_polynomial
import linear_algebra.std_basis
import ring_theory.ideal.local_ring
import ring_theory.ideal.operations
import ring_theory.multiplicity
import ring_theory.algebra_tower
import tactic.linarith
import algebra.big_operators.nat_antidiagonal
/-!
# Formal power series
This file defines (multivariate) formal power series
and develops the basic properties of these objects.
A formal power series is to a polynomial like an infinite sum is to a finite sum.
We provide the natural inclusion from polynomials to formal power series.
## Generalities
The file starts with setting up the (semi)ring structure on multivariate power series.
`trunc n φ` truncates a formal power series to the polynomial
that has the same coefficients as `φ`, for all `m ≤ n`, and `0` otherwise.
If the constant coefficient of a formal power series is invertible,
then this formal power series is invertible.
Formal power series over a local ring form a local ring.
## Formal power series in one variable
We prove that if the ring of coefficients is an integral domain,
then formal power series in one variable form an integral domain.
The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`.
If the coefficients form an integral domain, then `order` is a valuation
(`order_mul`, `le_order_add`).
## Implementation notes
In this file we define multivariate formal power series with
variables indexed by `σ` and coefficients in `R` as
`mv_power_series σ R := (σ →₀ ℕ) → R`.
Unfortunately there is not yet enough API to show that they are the completion
of the ring of multivariate polynomials. However, we provide most of the infrastructure
that is needed to do this. Once I-adic completion (topological or algebraic) is available
it should not be hard to fill in the details.
Formal power series in one variable are defined as
`power_series R := mv_power_series unit R`.
This allows us to port a lot of proofs and properties
from the multivariate case to the single variable case.
However, it means that formal power series are indexed by `unit →₀ ℕ`,
which is of course canonically isomorphic to `ℕ`.
We then build some glue to treat formal power series as if they are indexed by `ℕ`.
Occasionally this leads to proofs that are uglier than expected.
-/
noncomputable theory
open_locale classical big_operators
/-- Multivariate formal power series, where `σ` is the index set of the variables
and `R` is the coefficient ring.-/
def mv_power_series (σ : Type*) (R : Type*) := (σ →₀ ℕ) → R
namespace mv_power_series
open finsupp
variables {σ R : Type*}
instance [inhabited R] : inhabited (mv_power_series σ R) := ⟨λ _, default _⟩
instance [has_zero R] : has_zero (mv_power_series σ R) := pi.has_zero
instance [add_monoid R] : add_monoid (mv_power_series σ R) := pi.add_monoid
instance [add_group R] : add_group (mv_power_series σ R) := pi.add_group
instance [add_comm_monoid R] : add_comm_monoid (mv_power_series σ R) := pi.add_comm_monoid
instance [add_comm_group R] : add_comm_group (mv_power_series σ R) := pi.add_comm_group
instance [nontrivial R] : nontrivial (mv_power_series σ R) := function.nontrivial
instance {A} [semiring R] [add_comm_monoid A] [module R A] :
module R (mv_power_series σ A) := pi.module _ _ _
instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A]
[has_scalar R S] [is_scalar_tower R S A] :
is_scalar_tower R S (mv_power_series σ A) :=
pi.is_scalar_tower
section semiring
variables (R) [semiring R]
/-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/
def monomial (n : σ →₀ ℕ) : R →ₗ[R] mv_power_series σ R :=
linear_map.std_basis R _ n
/-- The `n`th coefficient of a multivariate formal power series.-/
def coeff (n : σ →₀ ℕ) : (mv_power_series σ R) →ₗ[R] R := linear_map.proj n
variables {R}
/-- Two multivariate formal power series are equal if all their coefficients are equal.-/
@[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) :
φ = ψ :=
funext h
/-- Two multivariate formal power series are equal
if and only if all their coefficients are equal.-/
lemma ext_iff {φ ψ : mv_power_series σ R} :
φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) :=
function.funext_iff
lemma monomial_def [decidable_eq σ] (n : σ →₀ ℕ) :
monomial R n = linear_map.std_basis R _ n :=
by convert rfl -- unify the `decidable` arguments
lemma coeff_monomial [decidable_eq σ] (m n : σ →₀ ℕ) (a : R) :
coeff R m (monomial R n a) = if m = n then a else 0 :=
by rw [coeff, monomial_def, linear_map.proj_apply, linear_map.std_basis_apply,
function.update_apply, pi.zero_apply]
@[simp] lemma coeff_monomial_same (n : σ →₀ ℕ) (a : R) :
coeff R n (monomial R n a) = a :=
linear_map.std_basis_same R _ n a
lemma coeff_monomial_ne {m n : σ →₀ ℕ} (h : m ≠ n) (a : R) :
coeff R m (monomial R n a) = 0 :=
linear_map.std_basis_ne R _ _ _ h a
lemma eq_of_coeff_monomial_ne_zero {m n : σ →₀ ℕ} {a : R} (h : coeff R m (monomial R n a) ≠ 0) :
m = n :=
by_contra $ λ h', h $ coeff_monomial_ne h' a
@[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) :
(coeff R n).comp (monomial R n) = linear_map.id :=
linear_map.ext $ coeff_monomial_same n
@[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff R n (0 : mv_power_series σ R) = 0 := rfl
variables (m n : σ →₀ ℕ) (φ ψ : mv_power_series σ R)
instance : has_one (mv_power_series σ R) := ⟨monomial R (0 : σ →₀ ℕ) 1⟩
lemma coeff_one [decidable_eq σ] :
coeff R n (1 : mv_power_series σ R) = if n = 0 then 1 else 0 :=
coeff_monomial _ _ _
lemma coeff_zero_one : coeff R (0 : σ →₀ ℕ) 1 = 1 :=
coeff_monomial_same 0 1
lemma monomial_zero_one : monomial R (0 : σ →₀ ℕ) 1 = 1 := rfl
instance : has_mul (mv_power_series σ R) :=
⟨λ φ ψ n, ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ⟩
lemma coeff_mul : coeff R n (φ * ψ) =
∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := rfl
protected lemma zero_mul : (0 : mv_power_series σ R) * φ = 0 :=
ext $ λ n, by simp [coeff_mul]
protected lemma mul_zero : φ * 0 = 0 :=
ext $ λ n, by simp [coeff_mul]
lemma coeff_monomial_mul (a : R) :
coeff R m (monomial R n a * φ) = if n ≤ m then a * coeff R (m - n) φ else 0 :=
begin
have : ∀ p ∈ antidiagonal m,
coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 (monomial R n a) * coeff R p.2 φ ≠ 0 → p.1 = n :=
λ p _ hp, eq_of_coeff_monomial_ne_zero (left_ne_zero_of_mul hp),
rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_fst_eq,
finset.sum_ite_index],
simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty]
end
lemma coeff_mul_monomial (a : R) :
coeff R m (φ * monomial R n a) = if n ≤ m then coeff R (m - n) φ * a else 0 :=
begin
have : ∀ p ∈ antidiagonal m,
coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 φ * coeff R p.2 (monomial R n a) ≠ 0 → p.2 = n :=
λ p _ hp, eq_of_coeff_monomial_ne_zero (right_ne_zero_of_mul hp),
rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_snd_eq,
finset.sum_ite_index],
simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty]
end
lemma coeff_add_monomial_mul (a : R) :
coeff R (m + n) (monomial R m a * φ) = a * coeff R n φ :=
begin
rw [coeff_monomial_mul, if_pos, nat_add_sub_cancel_left],
exact le_add_right le_rfl
end
lemma coeff_add_mul_monomial (a : R) :
coeff R (m + n) (φ * monomial R n a) = coeff R m φ * a :=
begin
rw [coeff_mul_monomial, if_pos, nat_add_sub_cancel],
exact le_add_left le_rfl
end
protected lemma one_mul : (1 : mv_power_series σ R) * φ = φ :=
ext $ λ n, by simpa using coeff_add_monomial_mul 0 n φ 1
protected lemma mul_one : φ * 1 = φ :=
ext $ λ n, by simpa using coeff_add_mul_monomial n 0 φ 1
protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ R) :
φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ :=
ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, linear_map.map_add]
protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ R) :
(φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ :=
ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, linear_map.map_add]
protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ R) :
(φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) :=
begin
ext1 n,
simp only [coeff_mul, finset.sum_mul, finset.mul_sum, finset.sum_sigma'],
refine finset.sum_bij (λ p _, ⟨(p.2.1, p.2.2 + p.1.2), (p.2.2, p.1.2)⟩) _ _ _ _;
simp only [mem_antidiagonal, finset.mem_sigma, heq_iff_eq, prod.mk.inj_iff, and_imp,
exists_prop],
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩, dsimp only, rintro rfl rfl,
simp [add_assoc] },
{ rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩, dsimp only, rintro rfl rfl,
apply mul_assoc },
{ rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩ ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl - rfl rfl - rfl rfl,
refl },
{ rintro ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl,
refine ⟨⟨(i + k, l), (i, k)⟩, _, _⟩; simp [add_assoc] }
end
instance : semiring (mv_power_series σ R) :=
{ mul_one := mv_power_series.mul_one,
one_mul := mv_power_series.one_mul,
mul_assoc := mv_power_series.mul_assoc,
mul_zero := mv_power_series.mul_zero,
zero_mul := mv_power_series.zero_mul,
left_distrib := mv_power_series.mul_add,
right_distrib := mv_power_series.add_mul,
.. mv_power_series.has_one,
.. mv_power_series.has_mul,
.. mv_power_series.add_comm_monoid }
end semiring
instance [comm_semiring R] : comm_semiring (mv_power_series σ R) :=
{ mul_comm := λ φ ψ, ext $ λ n, by simpa only [coeff_mul, mul_comm]
using sum_antidiagonal_swap n (λ a b, coeff R a φ * coeff R b ψ),
.. mv_power_series.semiring }
instance [ring R] : ring (mv_power_series σ R) :=
{ .. mv_power_series.semiring,
.. mv_power_series.add_comm_group }
instance [comm_ring R] : comm_ring (mv_power_series σ R) :=
{ .. mv_power_series.comm_semiring,
.. mv_power_series.add_comm_group }
section semiring
variables [semiring R]
lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : R) :
monomial R m a * monomial R n b = monomial R (m + n) (a * b) :=
begin
ext k,
simp only [coeff_mul_monomial, coeff_monomial],
split_ifs with h₁ h₂ h₃ h₃ h₂; try { refl },
{ rw [← h₂, nat_sub_add_cancel h₁] at h₃, exact (h₃ rfl).elim },
{ rw [h₃, nat_add_sub_cancel] at h₂, exact (h₂ rfl).elim },
{ exact zero_mul b },
{ rw h₂ at h₁, exact (h₁ $ le_add_left le_rfl).elim }
end
variables (σ) (R)
/-- The constant multivariate formal power series.-/
def C : R →+* mv_power_series σ R :=
{ map_one' := rfl,
map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm,
map_zero' := (monomial R (0 : _)).map_zero,
.. monomial R (0 : σ →₀ ℕ) }
variables {σ} {R}
@[simp] lemma monomial_zero_eq_C : ⇑(monomial R (0 : σ →₀ ℕ)) = C σ R := rfl
lemma monomial_zero_eq_C_apply (a : R) : monomial R (0 : σ →₀ ℕ) a = C σ R a := rfl
lemma coeff_C [decidable_eq σ] (n : σ →₀ ℕ) (a : R) :
coeff R n (C σ R a) = if n = 0 then a else 0 :=
coeff_monomial _ _ _
lemma coeff_zero_C (a : R) : coeff R (0 : σ →₀ℕ) (C σ R a) = a :=
coeff_monomial_same 0 a
/-- The variables of the multivariate formal power series ring.-/
def X (s : σ) : mv_power_series σ R := monomial R (single s 1) 1
lemma coeff_X [decidable_eq σ] (n : σ →₀ ℕ) (s : σ) :
coeff R n (X s : mv_power_series σ R) = if n = (single s 1) then 1 else 0 :=
coeff_monomial _ _ _
lemma coeff_index_single_X [decidable_eq σ] (s t : σ) :
coeff R (single t 1) (X s : mv_power_series σ R) = if t = s then 1 else 0 :=
by { simp only [coeff_X, single_left_inj one_ne_zero], split_ifs; refl }
@[simp] lemma coeff_index_single_self_X (s : σ) :
coeff R (single s 1) (X s : mv_power_series σ R) = 1 :=
coeff_monomial_same _ _
lemma coeff_zero_X (s : σ) : coeff R (0 : σ →₀ ℕ) (X s : mv_power_series σ R) = 0 :=
by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) }
lemma X_def (s : σ) : X s = monomial R (single s 1) 1 := rfl
lemma X_pow_eq (s : σ) (n : ℕ) :
(X s : mv_power_series σ R)^n = monomial R (single s n) 1 :=
begin
induction n with n ih,
{ rw [pow_zero, finsupp.single_zero, monomial_zero_one] },
{ rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] }
end
lemma coeff_X_pow [decidable_eq σ] (m : σ →₀ ℕ) (s : σ) (n : ℕ) :
coeff R m ((X s : mv_power_series σ R)^n) = if m = single s n then 1 else 0 :=
by rw [X_pow_eq s n, coeff_monomial]
@[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) :
coeff R n (φ * C σ R a) = coeff R n φ * a :=
by simpa using coeff_add_mul_monomial n 0 φ a
@[simp] lemma coeff_C_mul (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) :
coeff R n (C σ R a * φ) = a * coeff R n φ :=
by simpa using coeff_add_monomial_mul 0 n φ a
lemma coeff_zero_mul_X (φ : mv_power_series σ R) (s : σ) :
coeff R (0 : σ →₀ ℕ) (φ * X s) = 0 :=
begin
have : ¬single s 1 ≤ 0, from λ h, by simpa using h s,
simp only [X, coeff_mul_monomial, if_neg this]
end
lemma coeff_zero_X_mul (φ : mv_power_series σ R) (s : σ) :
coeff R (0 : σ →₀ ℕ) (X s * φ) = 0 :=
begin
have : ¬single s 1 ≤ 0, from λ h, by simpa using h s,
simp only [X, coeff_monomial_mul, if_neg this]
end
variables (σ) (R)
/-- The constant coefficient of a formal power series.-/
def constant_coeff : (mv_power_series σ R) →+* R :=
{ to_fun := coeff R (0 : σ →₀ ℕ),
map_one' := coeff_zero_one,
map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero],
map_zero' := linear_map.map_zero _,
.. coeff R (0 : σ →₀ ℕ) }
variables {σ} {R}
@[simp] lemma coeff_zero_eq_constant_coeff :
⇑(coeff R (0 : σ →₀ ℕ)) = constant_coeff σ R := rfl
lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ R) :
coeff R (0 : σ →₀ ℕ) φ = constant_coeff σ R φ := rfl
@[simp] lemma constant_coeff_C (a : R) : constant_coeff σ R (C σ R a) = a := rfl
@[simp] lemma constant_coeff_comp_C :
(constant_coeff σ R).comp (C σ R) = ring_hom.id R := rfl
@[simp] lemma constant_coeff_zero : constant_coeff σ R 0 = 0 := rfl
@[simp] lemma constant_coeff_one : constant_coeff σ R 1 = 1 := rfl
@[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ R (X s) = 0 := coeff_zero_X s
/-- If a multivariate formal power series is invertible,
then so is its constant coefficient.-/
lemma is_unit_constant_coeff (φ : mv_power_series σ R) (h : is_unit φ) :
is_unit (constant_coeff σ R φ) :=
h.map (constant_coeff σ R).to_monoid_hom
@[simp]
lemma coeff_smul (f : mv_power_series σ R) (n) (a : R) :
coeff _ n (a • f) = a * coeff _ n f :=
rfl
lemma X_inj [nontrivial R] {s t : σ} : (X s : mv_power_series σ R) = X t ↔ s = t :=
⟨begin
intro h, replace h := congr_arg (coeff R (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h,
split_ifs at h with H,
{ rw finsupp.single_eq_single_iff at H,
cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } },
{ exfalso, exact one_ne_zero h }
end, congr_arg X⟩
end semiring
section map
variables {S T : Type*} [semiring R] [semiring S] [semiring T]
variables (f : R →+* S) (g : S →+* T)
variable (σ)
/-- The map between multivariate formal power series induced by a map on the coefficients.-/
def map : mv_power_series σ R →+* mv_power_series σ S :=
{ to_fun := λ φ n, f $ coeff R n φ,
map_zero' := ext $ λ n, f.map_zero,
map_one' := ext $ λ n, show f ((coeff R n) 1) = (coeff S n) 1,
by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] },
map_add' := λ φ ψ, ext $ λ n,
show f ((coeff R n) (φ + ψ)) = f ((coeff R n) φ) + f ((coeff R n) ψ), by simp,
map_mul' := λ φ ψ, ext $ λ n, show f _ = _,
begin
rw [coeff_mul, f.map_sum, coeff_mul, finset.sum_congr rfl],
rintros ⟨i,j⟩ hij, rw [f.map_mul], refl,
end }
variable {σ}
@[simp] lemma map_id : map σ (ring_hom.id R) = ring_hom.id _ := rfl
lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl
@[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ R) :
coeff S n (map σ f φ) = f (coeff R n φ) := rfl
@[simp] lemma constant_coeff_map (φ : mv_power_series σ R) :
constant_coeff σ S (map σ f φ) = f (constant_coeff σ R φ) := rfl
@[simp] lemma map_monomial (n : σ →₀ ℕ) (a : R) :
map σ f (monomial R n a) = monomial S n (f a) :=
by { ext m, simp [coeff_monomial, apply_ite f] }
@[simp] lemma map_C (a : R) : map σ f (C σ R a) = C σ S (f a) :=
map_monomial _ _ _
@[simp] lemma map_X (s : σ) : map σ f (X s) = X s := by simp [X]
end map
section algebra
variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A]
instance : algebra R (mv_power_series σ A) :=
{ commutes' := λ a φ, by { ext n, simp [algebra.commutes] },
smul_def' := λ a σ, by { ext n, simp [(coeff A n).map_smul_of_tower a, algebra.smul_def] },
to_ring_hom := (mv_power_series.map σ (algebra_map R A)).comp (C σ R),
.. mv_power_series.module }
theorem C_eq_algebra_map : C σ R = (algebra_map R (mv_power_series σ R)) := rfl
theorem algebra_map_apply {r : R} :
algebra_map R (mv_power_series σ A) r = C σ A (algebra_map R A r) :=
begin
change (mv_power_series.map σ (algebra_map R A)).comp (C σ R) r = _,
simp,
end
instance [nonempty σ] [nontrivial R] : nontrivial (subalgebra R (mv_power_series σ R)) :=
⟨⟨⊥, ⊤, begin
rw [ne.def, set_like.ext_iff, not_forall],
inhabit σ,
refine ⟨X (default σ), _⟩,
simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top],
intros x,
rw [ext_iff, not_forall],
refine ⟨finsupp.single (default σ) 1, _⟩,
simp [algebra_map_apply, coeff_C],
end⟩⟩
end algebra
section trunc
variables [comm_semiring R] (n : σ →₀ ℕ)
/-- Auxiliary definition for the truncation function. -/
def trunc_fun (φ : mv_power_series σ R) : mv_polynomial σ R :=
∑ m in Iic_finset n, mv_polynomial.monomial m (coeff R m φ)
lemma coeff_trunc_fun (m : σ →₀ ℕ) (φ : mv_power_series σ R) :
(trunc_fun n φ).coeff m = if m ≤ n then coeff R m φ else 0 :=
by simp [trunc_fun, mv_polynomial.coeff_sum]
variable (R)
/-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/
def trunc : mv_power_series σ R →+ mv_polynomial σ R :=
{ to_fun := trunc_fun n,
map_zero' := by { ext, simp [coeff_trunc_fun] },
map_add' := by { intros, ext, simp [coeff_trunc_fun, ite_add], split_ifs; refl } }
variable {R}
lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ R) :
(trunc R n φ).coeff m = if m ≤ n then coeff R m φ else 0 :=
by simp [trunc, coeff_trunc_fun]
@[simp] lemma trunc_one : trunc R n 1 = 1 :=
mv_polynomial.ext _ _ $ λ m,
begin
rw [coeff_trunc, coeff_one],
split_ifs with H H' H',
{ subst m, simp },
{ symmetry, rw mv_polynomial.coeff_one, exact if_neg (ne.symm H'), },
{ symmetry, rw mv_polynomial.coeff_one, refine if_neg _,
intro H', apply H, subst m, intro s, exact nat.zero_le _ }
end
@[simp] lemma trunc_C (a : R) : trunc R n (C σ R a) = mv_polynomial.C a :=
mv_polynomial.ext _ _ $ λ m,
begin
rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C],
split_ifs with H; refl <|> try {simp * at *},
exfalso, apply H, subst m, intro s, exact nat.zero_le _
end
end trunc
section comm_semiring
variable [comm_semiring R]
lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ R} :
(X s : mv_power_series σ R)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff R m φ = 0 :=
begin
split,
{ rintros ⟨φ, rfl⟩ m h,
rw [coeff_mul, finset.sum_eq_zero],
rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul],
contrapose! h, subst i, rw finsupp.mem_antidiagonal at hij,
rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ },
{ intro h, refine ⟨λ m, coeff R (m + (single s n)) φ, _⟩,
ext m, by_cases H : m - single s n + single s n = m,
{ rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)],
{ rw [coeff_X_pow, if_pos rfl, one_mul],
simpa using congr_arg (λ (m : σ →₀ ℕ), coeff R m φ) H.symm },
{ rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal at hij,
rw coeff_X_pow, split_ifs with hi,
{ exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩,
ext t, simp only [nat.add_sub_cancel_left, finsupp.add_apply, finsupp.nat_sub_apply] },
{ exact zero_mul _ } },
{ intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal, add_comm] } },
{ rw [h, coeff_mul, finset.sum_eq_zero],
{ rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal at hij,
rw coeff_X_pow, split_ifs with hi,
{ exfalso, apply H, rw [← hij, hi], ext,
rw [coe_add, coe_add, pi.add_apply, pi.add_apply, nat_add_sub_cancel_left, add_comm], },
{ exact zero_mul _ } },
{ classical, contrapose! H, ext t,
by_cases hst : s = t,
{ subst t, simpa using nat.sub_add_cancel H },
{ simp [finsupp.single_apply, hst] } } } }
end
lemma X_dvd_iff {s : σ} {φ : mv_power_series σ R} :
(X s : mv_power_series σ R) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff R m φ = 0 :=
begin
rw [← pow_one (X s : mv_power_series σ R), X_pow_dvd_iff],
split; intros h m hm,
{ exact h m (hm.symm ▸ zero_lt_one) },
{ exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) }
end
end comm_semiring
section ring
variables [ring R]
/-
The inverse of a multivariate formal power series is defined by
well-founded recursion on the coeffients of the inverse.
-/
/-- Auxiliary definition that unifies
the totalised inverse formal power series `(_)⁻¹` and
the inverse formal power series that depends on
an inverse of the constant coefficient `inv_of_unit`.-/
protected noncomputable def inv.aux (a : R) (φ : mv_power_series σ R) : mv_power_series σ R
| n := if n = 0 then a else
- a * ∑ x in n.antidiagonal,
if h : x.2 < n then coeff R x.1 φ * inv.aux x.2 else 0
using_well_founded
{ rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩],
dec_tac := tactic.assumption }
lemma coeff_inv_aux [decidable_eq σ] (n : σ →₀ ℕ) (a : R) (φ : mv_power_series σ R) :
coeff R n (inv.aux a φ) = if n = 0 then a else
- a * ∑ x in n.antidiagonal,
if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 :=
show inv.aux a φ n = _,
begin
rw inv.aux,
convert rfl -- unify `decidable` instances
end
/-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/
def inv_of_unit (φ : mv_power_series σ R) (u : units R) : mv_power_series σ R :=
inv.aux (↑u⁻¹) φ
lemma coeff_inv_of_unit [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ R) (u : units R) :
coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else
- ↑u⁻¹ * ∑ x in n.antidiagonal,
if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 :=
coeff_inv_aux n (↑u⁻¹) φ
@[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ R) (u : units R) :
constant_coeff σ R (inv_of_unit φ u) = ↑u⁻¹ :=
by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl]
lemma mul_inv_of_unit (φ : mv_power_series σ R) (u : units R) (h : constant_coeff σ R φ = u) :
φ * inv_of_unit φ u = 1 :=
ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], }
else
begin
have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal,
{ rw [finsupp.mem_antidiagonal, zero_add] },
rw [coeff_one, if_neg H, coeff_mul,
← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _),
coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H,
neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, units.mul_inv_cancel_left,
← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _),
finset.insert_erase this, if_neg (not_lt_of_ge $ le_refl _), zero_add, add_comm,
← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl],
rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal] at hij,
cases hij with h₁ h₂,
subst n, rw if_pos,
suffices : (0 : _) + j < i + j, {simpa},
apply add_lt_add_right,
split,
{ intro s, exact nat.zero_le _ },
{ intro H, apply h₁,
suffices : i = 0, {simp [this]},
ext1 s, exact nat.eq_zero_of_le_zero (H s) }
end
end ring
section comm_ring
variable [comm_ring R]
/-- Multivariate formal power series over a local ring form a local ring. -/
instance is_local_ring [local_ring R] : local_ring (mv_power_series σ R) :=
{ is_local := by { intro φ, rcases local_ring.is_local (constant_coeff σ R φ) with ⟨u,h⟩|⟨u,h⟩;
[left, right];
{ refine is_unit_of_mul_eq_one _ _ (mul_inv_of_unit _ u _),
simpa using h.symm } } }
-- TODO(jmc): once adic topology lands, show that this is complete
end comm_ring
section local_ring
variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S)
[is_local_ring_hom f]
-- Thanks to the linter for informing us that this instance does
-- not actually need R and S to be local rings!
/-- The map `A[[X]] → B[[X]]` induced by a local ring hom `A → B` is local -/
instance map.is_local_ring_hom : is_local_ring_hom (map σ f) :=
⟨begin
rintros φ ⟨ψ, h⟩,
replace h := congr_arg (constant_coeff σ S) h,
rw constant_coeff_map at h,
have : is_unit (constant_coeff σ S ↑ψ) := @is_unit_constant_coeff σ S _ (↑ψ) ψ.is_unit,
rw h at this,
rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩,
exact is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc.symm)
end⟩
variables [local_ring R] [local_ring S]
instance : local_ring (mv_power_series σ R) :=
{ is_local := local_ring.is_local }
end local_ring
section field
variables {k : Type*} [field k]
/-- The inverse `1/f` of a multivariable power series `f` over a field -/
protected def inv (φ : mv_power_series σ k) : mv_power_series σ k :=
inv.aux (constant_coeff σ k φ)⁻¹ φ
instance : has_inv (mv_power_series σ k) := ⟨mv_power_series.inv⟩
lemma coeff_inv [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ k) :
coeff k n (φ⁻¹) = if n = 0 then (constant_coeff σ k φ)⁻¹ else
- (constant_coeff σ k φ)⁻¹ * ∑ x in n.antidiagonal,
if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 :=
coeff_inv_aux n _ φ
@[simp] lemma constant_coeff_inv (φ : mv_power_series σ k) :
constant_coeff σ k (φ⁻¹) = (constant_coeff σ k φ)⁻¹ :=
by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl]
lemma inv_eq_zero {φ : mv_power_series σ k} :
φ⁻¹ = 0 ↔ constant_coeff σ k φ = 0 :=
⟨λ h, by simpa using congr_arg (constant_coeff σ k) h,
λ h, ext $ λ n, by { rw coeff_inv, split_ifs;
simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩
@[simp, priority 1100]
lemma inv_of_unit_eq (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) :
inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl
@[simp]
lemma inv_of_unit_eq' (φ : mv_power_series σ k) (u : units k) (h : constant_coeff σ k φ = u) :
inv_of_unit φ u = φ⁻¹ :=
begin
rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero),
congr' 1, rw [units.ext_iff], exact h.symm,
end
@[simp] protected lemma mul_inv (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) :
φ * φ⁻¹ = 1 :=
by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl]
@[simp] protected lemma inv_mul (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) :
φ⁻¹ * φ = 1 :=
by rw [mul_comm, φ.mul_inv h]
protected lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : mv_power_series σ k}
(h : constant_coeff σ k φ₃ ≠ 0) :
φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ :=
⟨λ k, by simp [k, mul_assoc, mv_power_series.inv_mul _ h],
λ k, by simp [← k, mul_assoc, mv_power_series.mul_inv _ h]⟩
protected lemma eq_inv_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) :
φ = ψ⁻¹ ↔ φ * ψ = 1 :=
by rw [← mv_power_series.eq_mul_inv_iff_mul_eq h, one_mul]
protected lemma inv_eq_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) :
ψ⁻¹ = φ ↔ φ * ψ = 1 :=
by rw [eq_comm, mv_power_series.eq_inv_iff_mul_eq_one h]
end field
end mv_power_series
namespace mv_polynomial
open finsupp
variables {σ : Type*} {R : Type*} [comm_semiring R]
/-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/
instance coe_to_mv_power_series : has_coe (mv_polynomial σ R) (mv_power_series σ R) :=
⟨λ φ n, coeff n φ⟩
@[simp, norm_cast] lemma coeff_coe (φ : mv_polynomial σ R) (n : σ →₀ ℕ) :
mv_power_series.coeff R n ↑φ = coeff n φ := rfl
@[simp, norm_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : R) :
(monomial n a : mv_power_series σ R) = mv_power_series.monomial R n a :=
mv_power_series.ext $ λ m,
begin
rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial],
split_ifs with h₁ h₂; refl <|> subst m; contradiction
end
@[simp, norm_cast] lemma coe_zero : ((0 : mv_polynomial σ R) : mv_power_series σ R) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : mv_polynomial σ R) : mv_power_series σ R) = 1 :=
coe_monomial _ _
@[simp, norm_cast] lemma coe_add (φ ψ : mv_polynomial σ R) :
((φ + ψ : mv_polynomial σ R) : mv_power_series σ R) = φ + ψ := rfl
@[simp, norm_cast] lemma coe_mul (φ ψ : mv_polynomial σ R) :
((φ * ψ : mv_polynomial σ R) : mv_power_series σ R) = φ * ψ :=
mv_power_series.ext $ λ n,
by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul]
@[simp, norm_cast] lemma coe_C (a : R) :
((C a : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.C σ R a :=
coe_monomial _ _
@[simp, norm_cast] lemma coe_X (s : σ) :
((X s : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.X s :=
coe_monomial _ _
/--
The coercion from multivariable polynomials to multivariable power series
as a ring homomorphism.
-/
-- TODO as an algebra homomorphism?
def coe_to_mv_power_series.ring_hom : mv_polynomial σ R →+* mv_power_series σ R :=
{ to_fun := (coe : mv_polynomial σ R → mv_power_series σ R),
map_zero' := coe_zero,
map_one' := coe_one,
map_add' := coe_add,
map_mul' := coe_mul }
end mv_polynomial
/-- Formal power series over the coefficient ring `R`.-/
def power_series (R : Type*) := mv_power_series unit R
namespace power_series
open finsupp (single)
variable {R : Type*}
section
local attribute [reducible] power_series
instance [inhabited R] : inhabited (power_series R) := by apply_instance
instance [add_monoid R] : add_monoid (power_series R) := by apply_instance
instance [add_group R] : add_group (power_series R) := by apply_instance
instance [add_comm_monoid R] : add_comm_monoid (power_series R) := by apply_instance
instance [add_comm_group R] : add_comm_group (power_series R) := by apply_instance
instance [semiring R] : semiring (power_series R) := by apply_instance
instance [comm_semiring R] : comm_semiring (power_series R) := by apply_instance
instance [ring R] : ring (power_series R) := by apply_instance
instance [comm_ring R] : comm_ring (power_series R) := by apply_instance
instance [nontrivial R] : nontrivial (power_series R) := by apply_instance
instance {A} [semiring R] [add_comm_monoid A] [module R A] :
module R (power_series A) := by apply_instance
instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A]
[has_scalar R S] [is_scalar_tower R S A] :
is_scalar_tower R S (power_series A) :=
pi.is_scalar_tower
instance {A} [semiring A] [comm_semiring R] [algebra R A] :
algebra R (power_series A) := by apply_instance
end
section semiring
variables (R) [semiring R]
/-- The `n`th coefficient of a formal power series.-/
def coeff (n : ℕ) : power_series R →ₗ[R] R := mv_power_series.coeff R (single () n)
/-- The `n`th monomial with coefficient `a` as formal power series.-/
def monomial (n : ℕ) : R →ₗ[R] power_series R := mv_power_series.monomial R (single () n)
variables {R}
lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) :
coeff R n = mv_power_series.coeff R s :=
by erw [coeff, ← h, ← finsupp.unique_single s]
/-- Two formal power series are equal if all their coefficients are equal.-/
@[ext] lemma ext {φ ψ : power_series R} (h : ∀ n, coeff R n φ = coeff R n ψ) :
φ = ψ :=
mv_power_series.ext $ λ n,
by { rw ← coeff_def, { apply h }, refl }
/-- Two formal power series are equal if all their coefficients are equal.-/
lemma ext_iff {φ ψ : power_series R} : φ = ψ ↔ (∀ n, coeff R n φ = coeff R n ψ) :=
⟨λ h n, congr_arg (coeff R n) h, ext⟩
/-- Constructor for formal power series.-/
def mk {R} (f : ℕ → R) : power_series R := λ s, f (s ())
@[simp] lemma coeff_mk (n : ℕ) (f : ℕ → R) : coeff R n (mk f) = f n :=
congr_arg f finsupp.single_eq_same
lemma coeff_monomial (m n : ℕ) (a : R) :
coeff R m (monomial R n a) = if m = n then a else 0 :=
calc coeff R m (monomial R n a) = _ : mv_power_series.coeff_monomial _ _ _
... = if m = n then a else 0 :
by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl }
lemma monomial_eq_mk (n : ℕ) (a : R) :
monomial R n a = mk (λ m, if m = n then a else 0) :=
ext $ λ m, by { rw [coeff_monomial, coeff_mk] }
@[simp] lemma coeff_monomial_same (n : ℕ) (a : R) :
coeff R n (monomial R n a) = a :=
mv_power_series.coeff_monomial_same _ _
@[simp] lemma coeff_comp_monomial (n : ℕ) :
(coeff R n).comp (monomial R n) = linear_map.id :=
linear_map.ext $ coeff_monomial_same n
variable (R)
/--The constant coefficient of a formal power series. -/
def constant_coeff : power_series R →+* R := mv_power_series.constant_coeff unit R
/-- The constant formal power series.-/
def C : R →+* power_series R := mv_power_series.C unit R
variable {R}
/-- The variable of the formal power series ring.-/
def X : power_series R := mv_power_series.X ()
@[simp] lemma coeff_zero_eq_constant_coeff :
⇑(coeff R 0) = constant_coeff R :=
by { rw [coeff, finsupp.single_zero], refl }
lemma coeff_zero_eq_constant_coeff_apply (φ : power_series R) :
coeff R 0 φ = constant_coeff R φ :=
by rw [coeff_zero_eq_constant_coeff]; refl
@[simp] lemma monomial_zero_eq_C : ⇑(monomial R 0) = C R :=
by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C]
lemma monomial_zero_eq_C_apply (a : R) : monomial R 0 a = C R a :=
by simp
lemma coeff_C (n : ℕ) (a : R) :
coeff R n (C R a : power_series R) = if n = 0 then a else 0 :=
by rw [← monomial_zero_eq_C_apply, coeff_monomial]
@[simp] lemma coeff_zero_C (a : R) : coeff R 0 (C R a) = a :=
by rw [← monomial_zero_eq_C_apply, coeff_monomial_same 0 a]
lemma X_eq : (X : power_series R) = monomial R 1 1 := rfl
lemma coeff_X (n : ℕ) :
coeff R n (X : power_series R) = if n = 1 then 1 else 0 :=
by rw [X_eq, coeff_monomial]
@[simp] lemma coeff_zero_X : coeff R 0 (X : power_series R) = 0 :=
by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X]
@[simp] lemma coeff_one_X : coeff R 1 (X : power_series R) = 1 :=
by rw [coeff_X, if_pos rfl]
lemma X_pow_eq (n : ℕ) : (X : power_series R)^n = monomial R n 1 :=
mv_power_series.X_pow_eq _ n
lemma coeff_X_pow (m n : ℕ) :
coeff R m ((X : power_series R)^n) = if m = n then 1 else 0 :=
by rw [X_pow_eq, coeff_monomial]
@[simp] lemma coeff_X_pow_self (n : ℕ) :
coeff R n ((X : power_series R)^n) = 1 :=
by rw [coeff_X_pow, if_pos rfl]
@[simp] lemma coeff_one (n : ℕ) :
coeff R n (1 : power_series R) = if n = 0 then 1 else 0 :=
coeff_C n 1
lemma coeff_zero_one : coeff R 0 (1 : power_series R) = 1 :=
coeff_zero_C 1
lemma coeff_mul (n : ℕ) (φ ψ : power_series R) :
coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ :=
begin
symmetry,
apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)),
{ rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij,
rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], },
{ rintros ⟨i,j⟩ hij, refl },
{ rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl,
simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id },
{ rintros ⟨f,g⟩ hfg,
refine ⟨(f (), g ()), _, _⟩,
{ rw finsupp.mem_antidiagonal at hfg,
rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] },
{ rw prod.mk.inj_iff, dsimp,
exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } }
end
@[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series R) (a : R) :
coeff R n (φ * C R a) = coeff R n φ * a :=
mv_power_series.coeff_mul_C _ φ a
@[simp] lemma coeff_C_mul (n : ℕ) (φ : power_series R) (a : R) :
coeff R n (C R a * φ) = a * coeff R n φ :=
mv_power_series.coeff_C_mul _ φ a
@[simp] lemma coeff_smul (n : ℕ) (φ : power_series R) (a : R) :
coeff R n (a • φ) = a * coeff R n φ :=
rfl
@[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series R) :
coeff R (n+1) (φ * X) = coeff R n φ :=
begin
simp only [coeff, finsupp.single_add],
convert φ.coeff_add_mul_monomial (single () n) (single () 1) _,
rw mul_one
end
@[simp] lemma coeff_succ_X_mul (n : ℕ) (φ : power_series R) :
coeff R (n + 1) (X * φ) = coeff R n φ :=
begin
simp only [coeff, finsupp.single_add, add_comm n 1],
convert φ.coeff_add_monomial_mul (single () 1) (single () n) _,
rw one_mul,
end
@[simp] lemma constant_coeff_C (a : R) : constant_coeff R (C R a) = a := rfl
@[simp] lemma constant_coeff_comp_C :
(constant_coeff R).comp (C R) = ring_hom.id R := rfl
@[simp] lemma constant_coeff_zero : constant_coeff R 0 = 0 := rfl
@[simp] lemma constant_coeff_one : constant_coeff R 1 = 1 := rfl
@[simp] lemma constant_coeff_X : constant_coeff R X = 0 := mv_power_series.coeff_zero_X _
lemma coeff_zero_mul_X (φ : power_series R) : coeff R 0 (φ * X) = 0 := by simp
lemma coeff_zero_X_mul (φ : power_series R) : coeff R 0 (X * φ) = 0 := by simp
/-- If a formal power series is invertible, then so is its constant coefficient.-/
lemma is_unit_constant_coeff (φ : power_series R) (h : is_unit φ) :
is_unit (constant_coeff R φ) :=
mv_power_series.is_unit_constant_coeff φ h
/-- Split off the constant coefficient. -/
lemma eq_shift_mul_X_add_const (φ : power_series R) :
φ = mk (λ p, coeff R (p + 1) φ) * X + C R (constant_coeff R φ) :=
begin
ext (_ | n),
{ simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff,
zero_add, mul_zero, ring_hom.map_mul], },
{ simp only [coeff_succ_mul_X, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero,
if_false, add_zero], }
end
/-- Split off the constant coefficient. -/
lemma eq_X_mul_shift_add_const (φ : power_series R) :
φ = X * mk (λ p, coeff R (p + 1) φ) + C R (constant_coeff R φ) :=
begin
ext (_ | n),
{ simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff,
zero_add, zero_mul, ring_hom.map_mul], },
{ simp only [coeff_succ_X_mul, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero,
if_false, add_zero], }
end
section map
variables {S : Type*} {T : Type*} [semiring S] [semiring T]
variables (f : R →+* S) (g : S →+* T)
/-- The map between formal power series induced by a map on the coefficients.-/
def map : power_series R →+* power_series S :=
mv_power_series.map _ f
@[simp] lemma map_id : (map (ring_hom.id R) :
power_series R → power_series R) = id := rfl
lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl
@[simp] lemma coeff_map (n : ℕ) (φ : power_series R) :
coeff S n (map f φ) = f (coeff R n φ) := rfl
end map
end semiring
section comm_semiring
variables [comm_semiring R]
lemma X_pow_dvd_iff {n : ℕ} {φ : power_series R} :
(X : power_series R)^n ∣ φ ↔ ∀ m, m < n → coeff R m φ = 0 :=
begin
convert @mv_power_series.X_pow_dvd_iff unit R _ () n φ, apply propext,
classical, split; intros h m hm,
{ rw finsupp.unique_single m, convert h _ hm },
{ apply h, simpa only [finsupp.single_eq_same] using hm }
end
lemma X_dvd_iff {φ : power_series R} :
(X : power_series R) ∣ φ ↔ constant_coeff R φ = 0 :=
begin
rw [← pow_one (X : power_series R), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply],
split; intro h,
{ exact h 0 zero_lt_one },
{ intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) }
end
open finset nat
/-- The ring homomorphism taking a power series `f(X)` to `f(aX)`. -/
noncomputable def rescale (a : R) : power_series R →+* power_series R :=
{ to_fun := λ f, power_series.mk $ λ n, a^n * (power_series.coeff R n f),
map_zero' := by { ext, simp only [linear_map.map_zero, power_series.coeff_mk, mul_zero], },
map_one' := by { ext1, simp only [mul_boole, power_series.coeff_mk, power_series.coeff_one],
split_ifs, { rw [h, pow_zero], }, refl, },
map_add' := by { intros, ext, exact mul_add _ _ _, },
map_mul' := λ f g, by {
ext,
rw [power_series.coeff_mul, power_series.coeff_mk, power_series.coeff_mul, finset.mul_sum],
apply sum_congr rfl,
simp only [coeff_mk, prod.forall, nat.mem_antidiagonal],
intros b c H,
rw [←H, pow_add, mul_mul_mul_comm] }, }
@[simp] lemma coeff_rescale (f : power_series R) (a : R) (n : ℕ) :
coeff R n (rescale a f) = a^n * coeff R n f := coeff_mk n _
@[simp] lemma rescale_zero : rescale 0 = (C R).comp (constant_coeff R) :=
begin
ext,
simp only [function.comp_app, ring_hom.coe_comp, rescale, ring_hom.coe_mk,
power_series.coeff_mk _ _, coeff_C],
split_ifs,
{ simp only [h, one_mul, coeff_zero_eq_constant_coeff, pow_zero], },
{ rw [zero_pow' n h, zero_mul], },
end
lemma rescale_zero_apply : rescale 0 X = C R (constant_coeff R X) :=
by simp
@[simp] lemma rescale_one : rescale 1 = ring_hom.id (power_series R) :=
by { ext, simp only [ring_hom.id_apply, rescale, one_pow, coeff_mk, one_mul,
ring_hom.coe_mk], }
section trunc
/-- The `n`th truncation of a formal power series to a polynomial -/
def trunc (n : ℕ) (φ : power_series R) : polynomial R :=
∑ m in Ico 0 (n + 1), polynomial.monomial m (coeff R m φ)
lemma coeff_trunc (m) (n) (φ : power_series R) :
(trunc n φ).coeff m = if m ≤ n then coeff R m φ else 0 :=
by simp [trunc, polynomial.coeff_sum, polynomial.coeff_monomial, nat.lt_succ_iff]
@[simp] lemma trunc_zero (n) : trunc n (0 : power_series R) = 0 :=
polynomial.ext $ λ m,
begin
rw [coeff_trunc, linear_map.map_zero, polynomial.coeff_zero],
split_ifs; refl
end
@[simp] lemma trunc_one (n) : trunc n (1 : power_series R) = 1 :=
polynomial.ext $ λ m,
begin
rw [coeff_trunc, coeff_one],
split_ifs with H H' H'; rw [polynomial.coeff_one],
{ subst m, rw [if_pos rfl] },
{ symmetry, exact if_neg (ne.elim (ne.symm H')) },
{ symmetry, refine if_neg _,
intro H', apply H, subst m, exact nat.zero_le _ }
end
@[simp] lemma trunc_C (n) (a : R) : trunc n (C R a) = polynomial.C a :=
polynomial.ext $ λ m,
begin
rw [coeff_trunc, coeff_C, polynomial.coeff_C],
split_ifs with H; refl <|> try {simp * at *}
end
@[simp] lemma trunc_add (n) (φ ψ : power_series R) :
trunc n (φ + ψ) = trunc n φ + trunc n ψ :=
polynomial.ext $ λ m,
begin
simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add],
split_ifs with H, {refl}, {rw [zero_add]}
end
end trunc
end comm_semiring
section ring
variables [ring R]
/-- Auxiliary function used for computing inverse of a power series -/
protected def inv.aux : R → power_series R → power_series R :=
mv_power_series.inv.aux
lemma coeff_inv_aux (n : ℕ) (a : R) (φ : power_series R) :
coeff R n (inv.aux a φ) = if n = 0 then a else
- a * ∑ x in finset.nat.antidiagonal n,
if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 :=
begin
rw [coeff, inv.aux, mv_power_series.coeff_inv_aux],
simp only [finsupp.single_eq_zero],
split_ifs, {refl},
congr' 1,
symmetry,
apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)),
{ rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij,
rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], },
{ rintros ⟨i,j⟩ hij,
by_cases H : j < n,
{ rw [if_pos H, if_pos], {refl},
split,
{ rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H },
{ intro hh, rw lt_iff_not_ge at H, apply H,
simpa [finsupp.single_eq_same] using hh () } },
{ rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩,
simpa [finsupp.single_eq_same] using not_lt.1 H } },
{ rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl,
simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id },
{ rintros ⟨f,g⟩ hfg,
refine ⟨(f (), g ()), _, _⟩,
{ rw finsupp.mem_antidiagonal at hfg,
rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] },
{ rw prod.mk.inj_iff, dsimp,
exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } }
end
/-- A formal power series is invertible if the constant coefficient is invertible.-/
def inv_of_unit (φ : power_series R) (u : units R) : power_series R :=
mv_power_series.inv_of_unit φ u
lemma coeff_inv_of_unit (n : ℕ) (φ : power_series R) (u : units R) :
coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else
- ↑u⁻¹ * ∑ x in finset.nat.antidiagonal n,
if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 :=
coeff_inv_aux n ↑u⁻¹ φ
@[simp] lemma constant_coeff_inv_of_unit (φ : power_series R) (u : units R) :
constant_coeff R (inv_of_unit φ u) = ↑u⁻¹ :=
by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl]
lemma mul_inv_of_unit (φ : power_series R) (u : units R) (h : constant_coeff R φ = u) :
φ * inv_of_unit φ u = 1 :=
mv_power_series.mul_inv_of_unit φ u $ h
/-- Two ways of removing the constant coefficient of a power series are the same. -/
lemma sub_const_eq_shift_mul_X (φ : power_series R) :
φ - C R (constant_coeff R φ) = power_series.mk (λ p, coeff R (p + 1) φ) * X :=
sub_eq_iff_eq_add.mpr (eq_shift_mul_X_add_const φ)
lemma sub_const_eq_X_mul_shift (φ : power_series R) :
φ - C R (constant_coeff R φ) = X * power_series.mk (λ p, coeff R (p + 1) φ) :=
sub_eq_iff_eq_add.mpr (eq_X_mul_shift_add_const φ)
end ring
section comm_ring
variables {A : Type*} [comm_ring A]
@[simp] lemma rescale_neg_one_X : rescale (-1 : A) X = -X :=
begin
ext, simp only [linear_map.map_neg, coeff_rescale, coeff_X],
split_ifs with h; simp [h]
end
/-- The ring homomorphism taking a power series `f(X)` to `f(-X)`. -/
noncomputable def eval_neg_hom : power_series A →+* power_series A :=
rescale (-1 : A)
@[simp] lemma eval_neg_hom_X : eval_neg_hom (X : power_series A) = -X :=
rescale_neg_one_X
end comm_ring
section integral_domain
variable [integral_domain R]
lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : power_series R) (h : φ * ψ = 0) :
φ = 0 ∨ ψ = 0 :=
begin
rw or_iff_not_imp_left, intro H,
have ex : ∃ m, coeff R m φ ≠ 0, { contrapose! H, exact ext H },
let m := nat.find ex,
have hm₁ : coeff R m φ ≠ 0 := nat.find_spec ex,
have hm₂ : ∀ k < m, ¬coeff R k φ ≠ 0 := λ k, nat.find_min ex,
ext n, rw (coeff R n).map_zero, apply nat.strong_induction_on n,
clear n, intros n ih,
replace h := congr_arg (coeff R (m + n)) h,
rw [linear_map.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h,
{ replace h := eq_zero_or_eq_zero_of_mul_eq_zero h,
rw or_iff_not_imp_left at h, exact h hm₁ },
{ rintro ⟨i,j⟩ hij hne,
by_cases hj : j < n, { rw [ih j hj, mul_zero] },
by_cases hi : i < m,
{ specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] },
rw finset.nat.mem_antidiagonal at hij,
push_neg at hi hj,
suffices : m < i,
{ have : m + n < i + j := add_lt_add_of_lt_of_le this hj,
exfalso, exact ne_of_lt this hij.symm },
contrapose! hne, have : i = m := le_antisymm hne hi, subst i, clear hi hne,
simpa [ne.def, prod.mk.inj_iff] using (add_right_inj m).mp hij },
{ contrapose!, intro h, rw finset.nat.mem_antidiagonal }
end
instance : integral_domain (power_series R) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero,
.. power_series.nontrivial,
.. power_series.comm_ring }
/-- The ideal spanned by the variable in the power series ring
over an integral domain is a prime ideal.-/
lemma span_X_is_prime : (ideal.span ({X} : set (power_series R))).is_prime :=
begin
suffices : ideal.span ({X} : set (power_series R)) = (constant_coeff R).ker,
{ rw this, exact ring_hom.ker_is_prime _ },
apply ideal.ext, intro φ,
rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff]
end
/-- The variable of the power series ring over an integral domain is prime.-/
lemma X_prime : prime (X : power_series R) :=
begin
rw ← ideal.span_singleton_prime,
{ exact span_X_is_prime },
{ intro h, simpa using congr_arg (coeff R 1) h }
end
lemma rescale_injective {a : R} (ha : a ≠ 0) : function.injective (rescale a) :=
begin
intros p q h,
rw power_series.ext_iff at *,
intros n,
specialize h n,
rw [coeff_rescale, coeff_rescale, mul_eq_mul_left_iff] at h,
apply h.resolve_right,
intro h',
exact ha (pow_eq_zero h'),
end
end integral_domain
section local_ring
variables {S : Type*} [comm_ring R] [comm_ring S]
(f : R →+* S) [is_local_ring_hom f]
instance map.is_local_ring_hom : is_local_ring_hom (map f) :=
mv_power_series.map.is_local_ring_hom f
variables [local_ring R] [local_ring S]
instance : local_ring (power_series R) :=
mv_power_series.local_ring
end local_ring
section algebra
variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A]
theorem C_eq_algebra_map {r : R} : C R r = (algebra_map R (power_series R)) r := rfl
theorem algebra_map_apply {r : R} :
algebra_map R (power_series A) r = C A (algebra_map R A r) :=
mv_power_series.algebra_map_apply
instance [nontrivial R] : nontrivial (subalgebra R (power_series R)) :=
mv_power_series.subalgebra.nontrivial
end algebra
section field
variables {k : Type*} [field k]
/-- The inverse 1/f of a power series f defined over a field -/
protected def inv : power_series k → power_series k :=
mv_power_series.inv
instance : has_inv (power_series k) := ⟨power_series.inv⟩
lemma inv_eq_inv_aux (φ : power_series k) :
φ⁻¹ = inv.aux (constant_coeff k φ)⁻¹ φ := rfl
lemma coeff_inv (n) (φ : power_series k) :
coeff k n (φ⁻¹) = if n = 0 then (constant_coeff k φ)⁻¹ else
- (constant_coeff k φ)⁻¹ * ∑ x in finset.nat.antidiagonal n,
if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 :=
by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff k φ)⁻¹ φ]
@[simp] lemma constant_coeff_inv (φ : power_series k) :
constant_coeff k (φ⁻¹) = (constant_coeff k φ)⁻¹ :=
mv_power_series.constant_coeff_inv φ
lemma inv_eq_zero {φ : power_series k} :
φ⁻¹ = 0 ↔ constant_coeff k φ = 0 :=
mv_power_series.inv_eq_zero
@[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series k) (h : constant_coeff k φ ≠ 0) :
inv_of_unit φ (units.mk0 _ h) = φ⁻¹ :=
mv_power_series.inv_of_unit_eq _ _
@[simp] lemma inv_of_unit_eq' (φ : power_series k) (u : units k) (h : constant_coeff k φ = u) :
inv_of_unit φ u = φ⁻¹ :=
mv_power_series.inv_of_unit_eq' φ _ h
@[simp] protected lemma mul_inv (φ : power_series k) (h : constant_coeff k φ ≠ 0) :
φ * φ⁻¹ = 1 :=
mv_power_series.mul_inv φ h
@[simp] protected lemma inv_mul (φ : power_series k) (h : constant_coeff k φ ≠ 0) :
φ⁻¹ * φ = 1 :=
mv_power_series.inv_mul φ h
lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : power_series k} (h : constant_coeff k φ₃ ≠ 0) :
φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ :=
mv_power_series.eq_mul_inv_iff_mul_eq h
lemma eq_inv_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) :
φ = ψ⁻¹ ↔ φ * ψ = 1 :=
mv_power_series.eq_inv_iff_mul_eq_one h
lemma inv_eq_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) :
ψ⁻¹ = φ ↔ φ * ψ = 1 :=
mv_power_series.inv_eq_iff_mul_eq_one h
end field
end power_series
namespace power_series
variable {R : Type*}
local attribute [instance, priority 1] classical.prop_decidable
noncomputable theory
section order_basic
open multiplicity
variables [comm_semiring R]
/-- The order of a formal power series `φ` is the greatest `n : enat`
such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/
@[reducible] def order (φ : power_series R) : enat :=
multiplicity X φ
lemma order_finite_of_coeff_ne_zero (φ : power_series R) (h : ∃ n, coeff R n φ ≠ 0) :
(order φ).dom :=
begin
cases h with n h, refine ⟨n, _⟩, dsimp only,
rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩
end
/-- If the order of a formal power series is finite,
then the coefficient indexed by the order is nonzero.-/
lemma coeff_order (φ : power_series R) (h : (order φ).dom) :
coeff R (φ.order.get h) φ ≠ 0 :=
begin
have H := nat.find_spec h, contrapose! H, rw X_pow_dvd_iff,
intros m hm, by_cases Hm : m < nat.find h,
{ have := nat.find_min h Hm, push_neg at this,
rw X_pow_dvd_iff at this, exact this m (lt_add_one m) },
have : m = nat.find h, {linarith}, {rwa this}
end
/-- If the `n`th coefficient of a formal power series is nonzero,
then the order of the power series is less than or equal to `n`.-/
lemma order_le (φ : power_series R) (n : ℕ) (h : coeff R n φ ≠ 0) :
order φ ≤ n :=
begin
have h : ¬ X^(n+1) ∣ φ,
{ rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ },
have : (order φ).dom := ⟨n, h⟩,
rw [← enat.coe_get this, enat.coe_le_coe],
refine nat.find_min' this h
end
/-- The `n`th coefficient of a formal power series is `0` if `n` is strictly
smaller than the order of the power series.-/
lemma coeff_of_lt_order (φ : power_series R) (n : ℕ) (h: ↑n < order φ) :
coeff R n φ = 0 :=
by { contrapose! h, exact order_le _ _ h }
/-- The order of the `0` power series is infinite.-/
@[simp] lemma order_zero : order (0 : power_series R) = ⊤ :=
multiplicity.zero _
/-- The `0` power series is the unique power series with infinite order.-/
@[simp] lemma order_eq_top {φ : power_series R} :
φ.order = ⊤ ↔ φ = 0 :=
begin
split,
{ intro h, ext n, rw [(coeff R n).map_zero, coeff_of_lt_order], simp [h] },
{ rintros rfl, exact order_zero }
end
/-- The order of a formal power series is at least `n` if
the `i`th coefficient is `0` for all `i < n`.-/
lemma nat_le_order (φ : power_series R) (n : ℕ) (h : ∀ i < n, coeff R i φ = 0) :
↑n ≤ order φ :=
begin
by_contra H, rw not_le at H,
have : (order φ).dom := enat.dom_of_le_coe H.le,
rw [← enat.coe_get this, enat.coe_lt_coe] at H,
exact coeff_order _ this (h _ H)
end
/-- The order of a formal power series is at least `n` if
the `i`th coefficient is `0` for all `i < n`.-/
lemma le_order (φ : power_series R) (n : enat) (h : ∀ i : ℕ, ↑i < n → coeff R i φ = 0) :
n ≤ order φ :=
begin
induction n using enat.cases_on,
{ show _ ≤ _, rw [top_le_iff, order_eq_top],
ext i, exact h _ (enat.coe_lt_top i) },
{ apply nat_le_order, simpa only [enat.coe_lt_coe] using h }
end
/-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero,
and the `i`th coefficient is `0` for all `i < n`.-/
lemma order_eq_nat {φ : power_series R} {n : ℕ} :
order φ = n ↔ (coeff R n φ ≠ 0) ∧ (∀ i, i < n → coeff R i φ = 0) :=
begin
simp only [eq_coe_iff, X_pow_dvd_iff], push_neg,
split,
{ rintros ⟨h₁, m, hm₁, hm₂⟩, refine ⟨_, h₁⟩,
suffices : n = m, { rwa this },
suffices : m ≥ n, { linarith },
contrapose! hm₂, exact h₁ _ hm₂ },
{ rintros ⟨h₁, h₂⟩, exact ⟨h₂, n, lt_add_one n, h₁⟩ }
end
/-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero,
and the `i`th coefficient is `0` for all `i < n`.-/
lemma order_eq {φ : power_series R} {n : enat} :
order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff R i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff R i φ = 0) :=
begin
induction n using enat.cases_on,
{ rw order_eq_top, split,
{ rintro rfl, split; intros,
{ exfalso, exact enat.coe_ne_top ‹_› ‹_› },
{ exact (coeff _ _).map_zero } },
{ rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (enat.coe_lt_top i) } },
{ simpa [enat.coe_inj] using order_eq_nat }
end
/-- The order of the sum of two formal power series
is at least the minimum of their orders.-/
lemma le_order_add (φ ψ : power_series R) :
min (order φ) (order ψ) ≤ order (φ + ψ) :=
multiplicity.min_le_multiplicity_add
private lemma order_add_of_order_eq.aux (φ ψ : power_series R)
(h : order φ ≠ order ψ) (H : order φ < order ψ) :
order (φ + ψ) ≤ order φ ⊓ order ψ :=
begin
suffices : order (φ + ψ) = order φ,
{ rw [le_inf_iff, this], exact ⟨le_refl _, le_of_lt H⟩ },
{ rw order_eq, split,
{ intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order ψ i (hi.symm ▸ H), add_zero],
exact (order_eq_nat.1 hi.symm).1 },
{ intros i hi,
rw [(coeff _ _).map_add, coeff_of_lt_order φ i hi,
coeff_of_lt_order ψ i (lt_trans hi H), zero_add] } }
end
/-- The order of the sum of two formal power series
is the minimum of their orders if their orders differ.-/
lemma order_add_of_order_eq (φ ψ : power_series R) (h : order φ ≠ order ψ) :
order (φ + ψ) = order φ ⊓ order ψ :=
begin
refine le_antisymm _ (le_order_add _ _),
by_cases H₁ : order φ < order ψ,
{ apply order_add_of_order_eq.aux _ _ h H₁ },
by_cases H₂ : order ψ < order φ,
{ simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ },
exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁))
end
/-- The order of the product of two formal power series
is at least the sum of their orders.-/
lemma order_mul_ge (φ ψ : power_series R) :
order φ + order ψ ≤ order (φ * ψ) :=
begin
apply le_order,
intros n hn, rw [coeff_mul, finset.sum_eq_zero],
rintros ⟨i,j⟩ hij,
by_cases hi : ↑i < order φ,
{ rw [coeff_of_lt_order φ i hi, zero_mul] },
by_cases hj : ↑j < order ψ,
{ rw [coeff_of_lt_order ψ j hj, mul_zero] },
rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij,
exfalso,
apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add hi hj),
rw [← nat.cast_add, hij]
end
/-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/
lemma order_monomial (n : ℕ) (a : R) [decidable (a = 0)] :
order (monomial R n a) = if a = 0 then ⊤ else n :=
begin
split_ifs with h,
{ rw [h, order_eq_top, linear_map.map_zero] },
{ rw [order_eq], split; intros i hi,
{ rw [enat.coe_inj] at hi, rwa [hi, coeff_monomial_same] },
{ rw [enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } }
end
/-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/
lemma order_monomial_of_ne_zero (n : ℕ) (a : R) (h : a ≠ 0) :
order (monomial R n a) = n :=
by rw [order_monomial, if_neg h]
/-- If `n` is strictly smaller than the order of `ψ`, then the `n`th coefficient of its product
with any other power series is `0`. -/
lemma coeff_mul_of_lt_order {φ ψ : power_series R} {n : ℕ} (h : ↑n < ψ.order) :
coeff R n (φ * ψ) = 0 :=
begin
suffices : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, 0,
rw [this, finset.sum_const_zero],
rw [coeff_mul],
apply finset.sum_congr rfl (λ x hx, _),
refine mul_eq_zero_of_right (coeff R x.fst φ) (ψ.coeff_of_lt_order x.snd (lt_of_le_of_lt _ h)),
rw finset.nat.mem_antidiagonal at hx,
norm_cast,
linarith,
end
lemma coeff_mul_one_sub_of_lt_order {R : Type*} [comm_ring R] {φ ψ : power_series R}
(n : ℕ) (h : ↑n < ψ.order) :
coeff R n (φ * (1 - ψ)) = coeff R n φ :=
by simp [coeff_mul_of_lt_order h, mul_sub]
lemma coeff_mul_prod_one_sub_of_lt_order {R ι : Type*} [comm_ring R] (k : ℕ) (s : finset ι)
(φ : power_series R) (f : ι → power_series R) :
(∀ i ∈ s, ↑k < (f i).order) → coeff R k (φ * ∏ i in s, (1 - f i)) = coeff R k φ :=
begin
apply finset.induction_on s,
{ simp },
{ intros a s ha ih t,
simp only [finset.mem_insert, forall_eq_or_imp] at t,
rw [finset.prod_insert ha, ← mul_assoc, mul_right_comm, coeff_mul_one_sub_of_lt_order _ t.1],
exact ih t.2 },
end
end order_basic
section order_zero_ne_one
variables [comm_semiring R] [nontrivial R]
/-- The order of the formal power series `1` is `0`.-/
@[simp] lemma order_one : order (1 : power_series R) = 0 :=
by simpa using order_monomial_of_ne_zero 0 (1:R) one_ne_zero
/-- The order of the formal power series `X` is `1`.-/
@[simp] lemma order_X : order (X : power_series R) = 1 :=
by simpa only [nat.cast_one] using order_monomial_of_ne_zero 1 (1:R) one_ne_zero
/-- The order of the formal power series `X^n` is `n`.-/
@[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series R)^n) = n :=
by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero }
end order_zero_ne_one
section order_integral_domain
variables [integral_domain R]
/-- The order of the product of two formal power series over an integral domain
is the sum of their orders.-/
lemma order_mul (φ ψ : power_series R) :
order (φ * ψ) = order φ + order ψ :=
multiplicity.mul (X_prime)
end order_integral_domain
end power_series
namespace polynomial
open finsupp
variables {σ : Type*} {R : Type*} [comm_semiring R]
/-- The natural inclusion from polynomials into formal power series.-/
instance coe_to_power_series : has_coe (polynomial R) (power_series R) :=
⟨λ φ, power_series.mk $ λ n, coeff φ n⟩
@[simp, norm_cast] lemma coeff_coe (φ : polynomial R) (n) :
power_series.coeff R n φ = coeff φ n :=
congr_arg (coeff φ) (finsupp.single_eq_same)
@[simp, norm_cast] lemma coe_monomial (n : ℕ) (a : R) :
(monomial n a : power_series R) = power_series.monomial R n a :=
by { ext, simp [coeff_coe, power_series.coeff_monomial, polynomial.coeff_monomial, eq_comm] }
@[simp, norm_cast] lemma coe_zero : ((0 : polynomial R) : power_series R) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : polynomial R) : power_series R) = 1 :=
begin
have := coe_monomial 0 (1:R),
rwa power_series.monomial_zero_eq_C_apply at this,
end
@[simp, norm_cast] lemma coe_add (φ ψ : polynomial R) :
((φ + ψ : polynomial R) : power_series R) = φ + ψ :=
by { ext, simp }
@[simp, norm_cast] lemma coe_mul (φ ψ : polynomial R) :
((φ * ψ : polynomial R) : power_series R) = φ * ψ :=
power_series.ext $ λ n,
by simp only [coeff_coe, power_series.coeff_mul, coeff_mul]
@[simp, norm_cast] lemma coe_C (a : R) :
((C a : polynomial R) : power_series R) = power_series.C R a :=
begin
have := coe_monomial 0 a,
rwa power_series.monomial_zero_eq_C_apply at this,
end
@[simp, norm_cast] lemma coe_X :
((X : polynomial R) : power_series R) = power_series.X :=
coe_monomial _ _
/--
The coercion from polynomials to power series
as a ring homomorphism.
-/
-- TODO as an algebra homomorphism?
def coe_to_power_series.ring_hom : polynomial R →+* power_series R :=
{ to_fun := (coe : polynomial R → power_series R),
map_zero' := coe_zero,
map_one' := coe_one,
map_add' := coe_add,
map_mul' := coe_mul }
end polynomial
|
181bfc3398fad433cce3dbe6ce38de8fa0f1b161 | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/data/hash_map.lean | b99e16bfc35a1890a908fa3fa307d894e6f8ee10 | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 27,874 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
-/
import data.pnat.basic
import data.array.lemmas
import algebra.group
import data.sigma.basic
universes u v w
/-- `bucket_array α β` is the underlying data type for `hash_map α β`,
an array of linked lists of key-value pairs. -/
def bucket_array (α : Type u) (β : α → Type v) (n : ℕ+) :=
array n.1 (list Σ a, β a)
/-- Make a hash_map index from a `nat` hash value and a (positive) buffer size -/
def hash_map.mk_idx (n : ℕ+) (i : nat) : fin n.1 :=
⟨i % n.1, nat.mod_lt _ n.2⟩
namespace bucket_array
section
parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat)
variables {n : ℕ+} (data : bucket_array α β n)
instance : inhabited (bucket_array α β n) :=
⟨mk_array _ []⟩
/-- Read the bucket corresponding to an element -/
def read (a : α) : list Σ a, β a :=
let bidx := hash_map.mk_idx n (hash_fn a) in
data.read bidx
/-- Write the bucket corresponding to an element -/
def write (a : α) (l : list Σ a, β a) : bucket_array α β n :=
let bidx := hash_map.mk_idx n (hash_fn a) in
data.write bidx l
/-- Modify (read, apply `f`, and write) the bucket corresponding to an element -/
def modify (a : α) (f : list (Σ a, β a) → list (Σ a, β a)) : bucket_array α β n :=
let bidx := hash_map.mk_idx n (hash_fn a) in
array.write data bidx (f (array.read data bidx))
/-- The list of all key-value pairs in the bucket list -/
def as_list : list Σ a, β a := data.to_list.join
theorem mem_as_list {a : Σ a, β a} : a ∈ data.as_list ↔ ∃i, a ∈ array.read data i :=
have (∃ (l : list (Σ (a : α), β a)) (i : fin (n.val)), a ∈ l ∧ array.read data i = l) ↔
∃ (i : fin (n.val)), a ∈ array.read data i,
by rw exists_swap; exact exists_congr (λ i, by simp),
by simp [as_list]; simpa [array.mem.def, and_comm]
/-- Fold a function `f` over the key-value pairs in the bucket list -/
def foldl {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : δ :=
data.foldl d (λ b d, b.foldl (λ r a, f r a.1 a.2) d)
theorem foldl_eq {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) :
data.foldl d f = data.as_list.foldl (λ r a, f r a.1 a.2) d :=
by rw [foldl, as_list, list.foldl_join, ← array.to_list_foldl]
end
end bucket_array
namespace hash_map
section
parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat)
/-- Insert the pair `⟨a, b⟩` into the correct location in the bucket array
(without checking for duplication) -/
def reinsert_aux {n} (data : bucket_array α β n) (a : α) (b : β a) : bucket_array α β n :=
data.modify hash_fn a (λl, ⟨a, b⟩ :: l)
theorem mk_as_list (n : ℕ+) : bucket_array.as_list (mk_array n.1 [] : bucket_array α β n) = [] :=
list.eq_nil_iff_forall_not_mem.mpr $ λ x m,
let ⟨i, h⟩ := (bucket_array.mem_as_list _).1 m in h
parameter [decidable_eq α]
/-- Search a bucket for a key `a` and return the value -/
def find_aux (a : α) : list (Σ a, β a) → option (β a)
| [] := none
| (⟨a',b⟩::t) := if h : a' = a then some (eq.rec_on h b) else find_aux t
theorem find_aux_iff {a : α} {b : β a} : Π {l : list Σ a, β a}, (l.map sigma.fst).nodup → (find_aux a l = some b ↔ sigma.mk a b ∈ l)
| [] nd := ⟨λn, by injection n, false.elim⟩
| (⟨a',b'⟩::t) nd := begin
by_cases a' = a,
{ clear find_aux_iff, subst h,
suffices : b' = b ↔ b' = b ∨ sigma.mk a' b ∈ t, {simpa [find_aux, eq_comm]},
refine (or_iff_left_of_imp (λ m, _)).symm,
have : a' ∉ t.map sigma.fst, from list.not_mem_of_nodup_cons nd,
exact this.elim (list.mem_map_of_mem sigma.fst m) },
{ have : sigma.mk a b ≠ ⟨a', b'⟩,
{ intro e, injection e with e, exact h e.symm },
simp at nd, simp [find_aux, h, ne.symm h, find_aux_iff, nd] }
end
/-- Returns `tt` if the bucket `l` contains the key `a` -/
def contains_aux (a : α) (l : list Σ a, β a) : bool :=
(find_aux a l).is_some
theorem contains_aux_iff {a : α} {l : list Σ a, β a} (nd : (l.map sigma.fst).nodup) : contains_aux a l ↔ a ∈ l.map sigma.fst :=
begin
unfold contains_aux,
cases h : find_aux a l with b; simp,
{ assume (b : β a) (m : sigma.mk a b ∈ l),
rw (find_aux_iff nd).2 m at h,
contradiction },
{ show ∃ (b : β a), sigma.mk a b ∈ l,
exact ⟨_, (find_aux_iff nd).1 h⟩ },
end
/-- Modify a bucket to replace a value in the list. Leaves the list
unchanged if the key is not found. -/
def replace_aux (a : α) (b : β a) : list (Σ a, β a) → list (Σ a, β a)
| [] := []
| (⟨a', b'⟩::t) := if a' = a then ⟨a, b⟩::t else ⟨a', b'⟩ :: replace_aux t
/-- Modify a bucket to remove a key, if it exists. -/
def erase_aux (a : α) : list (Σ a, β a) → list (Σ a, β a)
| [] := []
| (⟨a', b'⟩::t) := if a' = a then t else ⟨a', b'⟩ :: erase_aux t
/-- The predicate `valid bkts sz` means that `bkts` satisfies the `hash_map`
invariants: There are exactly `sz` elements in it, every pair is in the
bucket determined by its key and the hash function, and no key appears
multiple times in the list. -/
structure valid {n} (bkts : bucket_array α β n) (sz : nat) : Prop :=
(len : bkts.as_list.length = sz)
(idx : ∀ {i} {a : Σ a, β a}, a ∈ array.read bkts i →
mk_idx n (hash_fn a.1) = i)
(nodup : ∀i, ((array.read bkts i).map sigma.fst).nodup)
theorem valid.idx_enum {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz)
{i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) :
∃ h, mk_idx n (hash_fn a) = ⟨i, h⟩ :=
(array.mem_to_list_enum.mp he).imp (λ h e, by subst e; exact v.idx hl)
theorem valid.idx_enum_1 {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz)
{i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) :
(mk_idx n (hash_fn a)).1 = i :=
let ⟨h, e⟩ := v.idx_enum _ he hl in by rw e; refl
theorem valid.as_list_nodup {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) : (bkts.as_list.map sigma.fst).nodup :=
begin
suffices : (bkts.to_list.map (list.map sigma.fst)).pairwise list.disjoint,
{ simp [bucket_array.as_list, list.nodup_join, this],
change ∀ l s, array.mem s bkts → list.map sigma.fst s = l → l.nodup,
introv m e, subst e, cases m with i e, subst e,
apply v.nodup },
rw [← list.enum_map_snd bkts.to_list, list.pairwise_map, list.pairwise_map],
have : (bkts.to_list.enum.map prod.fst).nodup := by simp [list.nodup_range],
refine list.pairwise.imp_of_mem _ ((list.pairwise_map _).1 this),
rw prod.forall, intros i l₁,
rw prod.forall, intros j l₂ me₁ me₂ ij,
simp [list.disjoint], intros a b ml₁ b' ml₂,
apply ij, rwa [← v.idx_enum_1 _ me₁ ml₁, ← v.idx_enum_1 _ me₂ ml₂]
end
theorem mk_valid (n : ℕ+) : @valid n (mk_array n.1 []) 0 :=
⟨by simp [mk_as_list], λ i a h, by cases h, λ i, list.nodup_nil⟩
theorem valid.find_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {a : α} {b : β a} :
find_aux a (bkts.read hash_fn a) = some b ↔ sigma.mk a b ∈ bkts.as_list :=
(find_aux_iff (v.nodup _)).trans $
by rw bkts.mem_as_list; exact ⟨λ h, ⟨_, h⟩, λ ⟨i, h⟩, (v.idx h).symm ▸ h⟩
theorem valid.contains_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) (a : α) :
contains_aux a (bkts.read hash_fn a) ↔ a ∈ bkts.as_list.map sigma.fst :=
by simp [contains_aux, option.is_some_iff_exists, v.find_aux_iff hash_fn]
section
parameters {n : ℕ+} {bkts : bucket_array α β n}
{bidx : fin n.1} {f : list (Σ a, β a) → list (Σ a, β a)}
(u v1 v2 w : list Σ a, β a)
local notation `L` := array.read bkts bidx
private def bkts' : bucket_array α β n := array.write bkts bidx (f L)
variables (hl : L = u ++ v1 ++ w)
(hfl : f L = u ++ v2 ++ w)
include hl hfl
theorem append_of_modify : ∃ u' w', bkts.as_list = u' ++ v1 ++ w' ∧ bkts'.as_list = u' ++ v2 ++ w' :=
begin
unfold bucket_array.as_list,
have h : bidx.1 < bkts.to_list.length, {simp [bidx.2]},
refine ⟨(bkts.to_list.take bidx.1).join ++ u, w ++ (bkts.to_list.drop (bidx.1+1)).join, _, _⟩,
{ conv { to_lhs,
rw [← list.take_append_drop bidx.1 bkts.to_list, list.drop_eq_nth_le_cons h],
simp [hl] }, simp },
{ conv { to_lhs,
rw [bkts', array.write_to_list, list.update_nth_eq_take_cons_drop _ h],
simp [hfl] }, simp }
end
variables (hvnd : (v2.map sigma.fst).nodup)
(hal : ∀ (a : Σ a, β a), a ∈ v2 → mk_idx n (hash_fn a.1) = bidx)
(djuv : (u.map sigma.fst).disjoint (v2.map sigma.fst))
(djwv : (w.map sigma.fst).disjoint (v2.map sigma.fst))
include hvnd hal djuv djwv
theorem valid.modify {sz : ℕ} (v : valid bkts sz) :
v1.length ≤ sz + v2.length ∧ valid bkts' (sz + v2.length - v1.length) :=
begin
rcases append_of_modify u v1 v2 w hl hfl with ⟨u', w', e₁, e₂⟩,
rw [← v.len, e₁],
suffices : valid bkts' (u' ++ v2 ++ w').length,
{ simpa [ge, add_comm, add_left_comm, nat.le_add_right, nat.add_sub_cancel_left] },
refine ⟨congr_arg _ e₂, λ i a, _, λ i, _⟩,
{ by_cases bidx = i,
{ subst i, rw [bkts', array.read_write, hfl],
have := @valid.idx _ _ _ v bidx a,
simp only [hl, list.mem_append, or_imp_distrib, forall_and_distrib] at this ⊢,
exact ⟨⟨this.1.1, hal _⟩, this.2⟩ },
{ rw [bkts', array.read_write_of_ne _ _ h], apply v.idx } },
{ by_cases bidx = i,
{ subst i, rw [bkts', array.read_write, hfl],
have := @valid.nodup _ _ _ v bidx,
simp [hl, list.nodup_append] at this,
simp [list.nodup_append, this, hvnd, djuv, djwv.symm] },
{ rw [bkts', array.read_write_of_ne _ _ h], apply v.nodup } }
end
end
theorem valid.replace_aux (a : α) (b : β a) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst →
∃ (u w : list Σ a, β a) b', l = u ++ [⟨a, b'⟩] ++ w ∧ replace_aux a b l = u ++ [⟨a, b⟩] ++ w
| [] := false.elim
| (⟨a', b'⟩::t) := begin
by_cases e : a' = a,
{ subst a',
suffices : ∃ (u w : list Σ a, β a) (b'' : β a),
(sigma.mk a b') :: t = u ++ ⟨a, b''⟩ :: w ∧
replace_aux a b (⟨a, b'⟩ :: t) = u ++ ⟨a, b⟩ :: w, {simpa},
refine ⟨[], t, b', _⟩, simp [replace_aux] },
{ suffices : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a),
(sigma.mk a' b') :: t = u ++ ⟨a, b''⟩ :: w ∧
(sigma.mk a' b') :: (replace_aux a b t) = u ++ ⟨a, b⟩ :: w,
{ simpa [replace_aux, ne.symm e, e] },
intros x m,
have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a),
t = u ++ ⟨a, b''⟩ :: w ∧ replace_aux a b t = u ++ ⟨a, b⟩ :: w,
{ simpa using valid.replace_aux t },
rcases IH x m with ⟨u, w, b'', hl, hfl⟩,
exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm, ne.symm e]⟩ }
end
theorem valid.replace {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a)
(Hc : contains_aux a (bkts.read hash_fn a))
(v : valid bkts sz) : valid (bkts.modify hash_fn a (replace_aux a b)) sz :=
begin
have nd := v.nodup (mk_idx n (hash_fn a)),
rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a)))
((contains_aux_iff nd).1 Hc) with ⟨u, w, b', hl, hfl⟩,
simp [hl, list.nodup_append] at nd,
refine (v.modify hash_fn
u [⟨a, b'⟩] [⟨a, b⟩] w hl hfl (list.nodup_singleton _)
(λa' e, by simp at e; rw e)
(λa' e1 e2, _)
(λa' e1 e2, _)).2;
{ revert e1, simp [-sigma.exists] at e2, subst a', simp [nd] }
end
theorem valid.insert {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a)
(Hnc : ¬ contains_aux a (bkts.read hash_fn a))
(v : valid bkts sz) : valid (reinsert_aux bkts a b) (sz+1) :=
begin
have nd := v.nodup (mk_idx n (hash_fn a)),
refine (v.modify hash_fn
[] [] [⟨a, b⟩] (bkts.read hash_fn a) rfl rfl (list.nodup_singleton _)
(λa' e, by simp at e; rw e)
(λa', false.elim)
(λa' e1 e2, _)).2,
simp [-sigma.exists] at e2, subst a',
exact Hnc ((contains_aux_iff nd).2 e1)
end
theorem valid.erase_aux (a : α) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst →
∃ (u w : list Σ a, β a) b, l = u ++ [⟨a, b⟩] ++ w ∧ erase_aux a l = u ++ [] ++ w
| [] := false.elim
| (⟨a', b'⟩::t) := begin
by_cases e : a' = a,
{ subst a',
simpa [erase_aux, and_comm] using show ∃ u w (x : β a),
t = u ++ w ∧ (sigma.mk a b') :: t = u ++ ⟨a, x⟩ :: w,
from ⟨[], t, b', by simp⟩ },
{ simp [erase_aux, e, ne.symm e],
suffices : ∀ (b : β a) (_ : sigma.mk a b ∈ t), ∃ u w (x : β a),
(sigma.mk a' b') :: t = u ++ ⟨a, x⟩ :: w ∧
(sigma.mk a' b') :: (erase_aux a t) = u ++ w,
{ simpa [replace_aux, ne.symm e, e] },
intros b m,
have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (x : β a),
t = u ++ ⟨a, x⟩ :: w ∧ erase_aux a t = u ++ w,
{ simpa using valid.erase_aux t },
rcases IH b m with ⟨u, w, b'', hl, hfl⟩,
exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm]⟩ }
end
theorem valid.erase {n} {bkts : bucket_array α β n} {sz}
(a : α) (Hc : contains_aux a (bkts.read hash_fn a))
(v : valid bkts sz) : valid (bkts.modify hash_fn a (erase_aux a)) (sz-1) :=
begin
have nd := v.nodup (mk_idx n (hash_fn a)),
rcases hash_map.valid.erase_aux a (array.read bkts (mk_idx n (hash_fn a)))
((contains_aux_iff nd).1 Hc) with ⟨u, w, b, hl, hfl⟩,
refine (v.modify hash_fn u [⟨a, b⟩] [] w hl hfl list.nodup_nil _ _ _).2;
simp
end
end
end hash_map
/-- A hash map data structure, representing a finite key-value map
with key type `α` and value type `β` (which may depend on `α`). -/
structure hash_map (α : Type u) [decidable_eq α] (β : α → Type v) :=
(hash_fn : α → nat)
(size : ℕ)
(nbuckets : ℕ+)
(buckets : bucket_array α β nbuckets)
(is_valid : hash_map.valid hash_fn buckets size)
/-- Construct an empty hash map with buffer size `nbuckets` (default 8). -/
def mk_hash_map {α : Type u} [decidable_eq α] {β : α → Type v} (hash_fn : α → nat) (nbuckets := 8) : hash_map α β :=
let n := if nbuckets = 0 then 8 else nbuckets in
let nz : n > 0 := by abstract { cases nbuckets; simp [if_pos, nat.succ_ne_zero] } in
{ hash_fn := hash_fn,
size := 0,
nbuckets := ⟨n, nz⟩,
buckets := mk_array n [],
is_valid := hash_map.mk_valid _ _ }
namespace hash_map
variables {α : Type u} {β : α → Type v} [decidable_eq α]
/-- Return the value corresponding to a key, or `none` if not found -/
def find (m : hash_map α β) (a : α) : option (β a) :=
find_aux a (m.buckets.read m.hash_fn a)
/-- Return `tt` if the key exists in the map -/
def contains (m : hash_map α β) (a : α) : bool :=
(m.find a).is_some
instance : has_mem α (hash_map α β) := ⟨λa m, m.contains a⟩
/-- Fold a function over the key-value pairs in the map -/
def fold {δ : Type w} (m : hash_map α β) (d : δ) (f : δ → Π a, β a → δ) : δ :=
m.buckets.foldl d f
/-- The list of key-value pairs in the map -/
def entries (m : hash_map α β) : list Σ a, β a :=
m.buckets.as_list
/-- The list of keys in the map -/
def keys (m : hash_map α β) : list α :=
m.entries.map sigma.fst
theorem find_iff (m : hash_map α β) (a : α) (b : β a) :
m.find a = some b ↔ sigma.mk a b ∈ m.entries :=
m.is_valid.find_aux_iff _
theorem contains_iff (m : hash_map α β) (a : α) :
m.contains a ↔ a ∈ m.keys :=
m.is_valid.contains_aux_iff _ _
theorem entries_empty (hash_fn : α → nat) (n) :
(@mk_hash_map α _ β hash_fn n).entries = [] :=
by dsimp [entries, mk_hash_map]; rw mk_as_list
theorem keys_empty (hash_fn : α → nat) (n) :
(@mk_hash_map α _ β hash_fn n).keys = [] :=
by dsimp [keys]; rw entries_empty; refl
theorem find_empty (hash_fn : α → nat) (n a) :
(@mk_hash_map α _ β hash_fn n).find a = none :=
by induction h : (@mk_hash_map α _ β hash_fn n).find a; [refl,
{ have := (find_iff _ _ _).1 h, rw entries_empty at this, contradiction }]
theorem not_contains_empty (hash_fn : α → nat) (n a) :
¬ (@mk_hash_map α _ β hash_fn n).contains a :=
by apply bool_iff_false.2; dsimp [contains]; rw [find_empty]; refl
theorem insert_lemma (hash_fn : α → nat) {n n'}
{bkts : bucket_array α β n} {sz} (v : valid hash_fn bkts sz) :
valid hash_fn (bkts.foldl (mk_array _ [] : bucket_array α β n') (reinsert_aux hash_fn)) sz :=
begin
suffices : ∀ (l : list Σ a, β a) (t : bucket_array α β n') sz,
valid hash_fn t sz → ((l ++ t.as_list).map sigma.fst).nodup →
valid hash_fn (l.foldl (λr (a : Σ a, β a), reinsert_aux hash_fn r a.1 a.2) t) (sz + l.length),
{ have p := this bkts.as_list _ _ (mk_valid _ _),
rw [mk_as_list, list.append_nil, zero_add, v.len] at p,
rw bucket_array.foldl_eq,
exact p (v.as_list_nodup _) },
intro l, induction l with c l IH; intros t sz v nd, {exact v},
rw show sz + (c :: l).length = sz + 1 + l.length, by simp [add_comm],
rcases (show (l.map sigma.fst).nodup ∧
((bucket_array.as_list t).map sigma.fst).nodup ∧
c.fst ∉ l.map sigma.fst ∧
c.fst ∉ (bucket_array.as_list t).map sigma.fst ∧
(l.map sigma.fst).disjoint ((bucket_array.as_list t).map sigma.fst),
by simpa [list.nodup_append, not_or_distrib, and_comm, and.left_comm] using nd)
with ⟨nd1, nd2, nm1, nm2, dj⟩,
have v' := v.insert _ _ c.2 (λHc, nm2 $ (v.contains_aux_iff _ c.1).1 Hc),
apply IH _ _ v',
suffices : ∀ ⦃a : α⦄ (b : β a), sigma.mk a b ∈ l →
∀ (b' : β a), sigma.mk a b' ∈ (reinsert_aux hash_fn t c.1 c.2).as_list → false,
{ simpa [list.nodup_append, nd1, v'.as_list_nodup _, list.disjoint] },
intros a b m1 b' m2,
rcases (reinsert_aux hash_fn t c.1 c.2).mem_as_list.1 m2 with ⟨i, im⟩,
have : sigma.mk a b' ∉ array.read t i,
{ intro m3,
have : a ∈ list.map sigma.fst t.as_list :=
list.mem_map_of_mem sigma.fst (t.mem_as_list.2 ⟨_, m3⟩),
exact dj (list.mem_map_of_mem sigma.fst m1) this },
by_cases h : mk_idx n' (hash_fn c.1) = i,
{ subst h,
have e : sigma.mk a b' = ⟨c.1, c.2⟩,
{ simpa [reinsert_aux, bucket_array.modify, array.read_write, this] using im },
injection e with e, subst a,
exact nm1.elim (@list.mem_map_of_mem _ _ sigma.fst _ _ m1) },
{ apply this,
simpa [reinsert_aux, bucket_array.modify, array.read_write_of_ne _ _ h] using im }
end
/-- Insert a key-value pair into the map. (Modifies `m` in-place when applicable) -/
def insert : Π (m : hash_map α β) (a : α) (b : β a), hash_map α β
| ⟨hash_fn, size, n, buckets, v⟩ a b :=
let bkt := buckets.read hash_fn a in
if hc : contains_aux a bkt then
{ hash_fn := hash_fn,
size := size,
nbuckets := n,
buckets := buckets.modify hash_fn a (replace_aux a b),
is_valid := v.replace _ a b hc }
else
let size' := size + 1,
buckets' := buckets.modify hash_fn a (λl, ⟨a, b⟩::l),
valid' := v.insert _ a b hc in
if size' ≤ n.1 then
{ hash_fn := hash_fn,
size := size',
nbuckets := n,
buckets := buckets',
is_valid := valid' }
else
let n' : ℕ+ := ⟨n.1 * 2, mul_pos n.2 dec_trivial⟩,
buckets'' : bucket_array α β n' :=
buckets'.foldl (mk_array _ []) (reinsert_aux hash_fn) in
{ hash_fn := hash_fn,
size := size',
nbuckets := n',
buckets := buckets'',
is_valid := insert_lemma _ valid' }
theorem mem_insert : Π (m : hash_map α β) (a b a' b'),
(sigma.mk a' b' : sigma β) ∈ (m.insert a b).entries ↔
if a = a' then b == b' else sigma.mk a' b' ∈ m.entries
| ⟨hash_fn, size, n, bkts, v⟩ a b a' b' := begin
let bkt := bkts.read hash_fn a,
have nd : (bkt.map sigma.fst).nodup := v.nodup (mk_idx n (hash_fn a)),
have lem : Π (bkts' : bucket_array α β n) (v1 u w)
(hl : bucket_array.as_list bkts = u ++ v1 ++ w)
(hfl : bucket_array.as_list bkts' = u ++ [⟨a, b⟩] ++ w)
(veq : (v1 = [] ∧ ¬ contains_aux a bkt) ∨ ∃b'', v1 = [⟨a, b''⟩]),
sigma.mk a' b' ∈ bkts'.as_list ↔
if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list,
{ intros bkts' v1 u w hl hfl veq,
rw [hl, hfl],
by_cases h : a = a',
{ subst a',
suffices : b = b' ∨ sigma.mk a b' ∈ u ∨ sigma.mk a b' ∈ w ↔ b = b',
{ simpa [eq_comm, or.left_comm] },
refine or_iff_left_of_imp (not.elim $ not_or_distrib.2 _),
rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩,
{ have na := (not_iff_not_of_iff $ v.contains_aux_iff _ _).1 Hnc,
simp [hl, not_or_distrib] at na, simp [na] },
{ have nd' := v.as_list_nodup _,
simp [hl, list.nodup_append] at nd', simp [nd'] } },
{ suffices : sigma.mk a' b' ∉ v1, {simp [h, ne.symm h, this]},
rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩; simp [ne.symm h] } },
by_cases Hc : (contains_aux a bkt : Prop),
{ rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a)))
((contains_aux_iff nd).1 Hc) with ⟨u', w', b'', hl', hfl'⟩,
rcases (append_of_modify u' [⟨a, b''⟩] [⟨a, b⟩] w' hl' hfl') with ⟨u, w, hl, hfl⟩,
simpa [insert, @dif_pos (contains_aux a bkt) _ Hc]
using lem _ _ u w hl hfl (or.inr ⟨b'', rfl⟩) },
{ let size' := size + 1,
let bkts' := bkts.modify hash_fn a (λl, ⟨a, b⟩::l),
have mi : sigma.mk a' b' ∈ bkts'.as_list ↔
if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list :=
let ⟨u, w, hl, hfl⟩ := append_of_modify [] [] [⟨a, b⟩] _ rfl rfl in
lem bkts' _ u w hl hfl $ or.inl ⟨rfl, Hc⟩,
simp [insert, @dif_neg (contains_aux a bkt) _ Hc],
by_cases h : size' ≤ n.1,
-- TODO(Mario): Why does the by_cases assumption look different than the stated one?
{ simpa [show size' ≤ n.1, from h] using mi },
{ let n' : ℕ+ := ⟨n.1 * 2, mul_pos n.2 dec_trivial⟩,
let bkts'' : bucket_array α β n' := bkts'.foldl (mk_array _ []) (reinsert_aux hash_fn),
suffices : sigma.mk a' b' ∈ bkts''.as_list ↔ sigma.mk a' b' ∈ bkts'.as_list.reverse,
{ simpa [show ¬ size' ≤ n.1, from h, mi] },
rw [show bkts'' = bkts'.as_list.foldl _ _, from bkts'.foldl_eq _ _,
← list.foldr_reverse],
induction bkts'.as_list.reverse with a l IH,
{ simp [mk_as_list] },
{ cases a with a'' b'',
let B := l.foldr (λ (y : sigma β) (x : bucket_array α β n'),
reinsert_aux hash_fn x y.1 y.2) (mk_array n'.1 []),
rcases append_of_modify [] [] [⟨a'', b''⟩] _ rfl rfl with ⟨u, w, hl, hfl⟩,
simp [IH.symm, or.left_comm, show B.as_list = _, from hl,
show (reinsert_aux hash_fn B a'' b'').as_list = _, from hfl] } } }
end
theorem find_insert_eq (m : hash_map α β) (a : α) (b : β a) : (m.insert a b).find a = some b :=
(find_iff (m.insert a b) a b).2 $ (mem_insert m a b a b).2 $ by rw if_pos rfl
theorem find_insert_ne (m : hash_map α β) (a a' : α) (b : β a) (h : a ≠ a') :
(m.insert a b).find a' = m.find a' :=
option.eq_of_eq_some $ λb',
let t := mem_insert m a b a' b' in
(find_iff _ _ _).trans $ iff.trans (by rwa if_neg h at t) (find_iff _ _ _).symm
theorem find_insert (m : hash_map α β) (a' a : α) (b : β a) :
(m.insert a b).find a' = if h : a = a' then some (eq.rec_on h b) else m.find a' :=
if h : a = a' then by rw dif_pos h; exact
match a', h with ._, rfl := find_insert_eq m a b end
else by rw dif_neg h; exact find_insert_ne m a a' b h
/-- Insert a list of key-value pairs into the map. (Modifies `m` in-place when applicable) -/
def insert_all (l : list (Σ a, β a)) (m : hash_map α β) : hash_map α β :=
l.foldl (λ m ⟨a, b⟩, insert m a b) m
/-- Construct a hash map from a list of key-value pairs. -/
def of_list (l : list (Σ a, β a)) (hash_fn) : hash_map α β :=
insert_all l (mk_hash_map hash_fn (2 * l.length))
/-- Remove a key from the map. (Modifies `m` in-place when applicable) -/
def erase (m : hash_map α β) (a : α) : hash_map α β :=
match m with ⟨hash_fn, size, n, buckets, v⟩ :=
if hc : contains_aux a (buckets.read hash_fn a) then
{ hash_fn := hash_fn,
size := size - 1,
nbuckets := n,
buckets := buckets.modify hash_fn a (erase_aux a),
is_valid := v.erase _ a hc }
else m
end
theorem mem_erase : Π (m : hash_map α β) (a a' b'),
(sigma.mk a' b' : sigma β) ∈ (m.erase a).entries ↔
a ≠ a' ∧ sigma.mk a' b' ∈ m.entries
| ⟨hash_fn, size, n, bkts, v⟩ a a' b' := begin
let bkt := bkts.read hash_fn a,
by_cases Hc : (contains_aux a bkt : Prop),
{ let bkts' := bkts.modify hash_fn a (erase_aux a),
suffices : sigma.mk a' b' ∈ bkts'.as_list ↔ a ≠ a' ∧ sigma.mk a' b' ∈ bkts.as_list,
{ simpa [erase, @dif_pos (contains_aux a bkt) _ Hc] },
have nd := v.nodup (mk_idx n (hash_fn a)),
rcases valid.erase_aux a bkt ((contains_aux_iff nd).1 Hc) with ⟨u', w', b, hl', hfl'⟩,
rcases append_of_modify u' [⟨a, b⟩] [] _ hl' hfl' with ⟨u, w, hl, hfl⟩,
suffices : ∀_:sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w, a ≠ a',
{ have : sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w ↔ (¬a = a' ∧ a' = a) ∧ b' == b ∨
¬a = a' ∧ (sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w),
{ simp [eq_comm, not_and_self_iff, and_iff_right_of_imp this] },
simpa [hl, show bkts'.as_list = _, from hfl, and_or_distrib_left,
and_comm, and.left_comm, or.left_comm] },
intros m e, subst a', revert m, apply not_or_distrib.2,
have nd' := v.as_list_nodup _,
simp [hl, list.nodup_append] at nd', simp [nd'] },
{ suffices : ∀_:sigma.mk a' b' ∈ bucket_array.as_list bkts, a ≠ a',
{ simp [erase, @dif_neg (contains_aux a bkt) _ Hc, entries, and_iff_right_of_imp this] },
intros m e, subst a',
exact Hc ((v.contains_aux_iff _ _).2 (list.mem_map_of_mem sigma.fst m)) }
end
theorem find_erase_eq (m : hash_map α β) (a : α) : (m.erase a).find a = none :=
begin
cases h : (m.erase a).find a with b, {refl},
exact absurd rfl ((mem_erase m a a b).1 ((find_iff (m.erase a) a b).1 h)).left
end
theorem find_erase_ne (m : hash_map α β) (a a' : α) (h : a ≠ a') :
(m.erase a).find a' = m.find a' :=
option.eq_of_eq_some $ λb',
(find_iff _ _ _).trans $ (mem_erase m a a' b').trans $
(and_iff_right h).trans (find_iff _ _ _).symm
theorem find_erase (m : hash_map α β) (a' a : α) :
(m.erase a).find a' = if a = a' then none else m.find a' :=
if h : a = a' then by subst a'; simp [find_erase_eq m a]
else by rw if_neg h; exact find_erase_ne m a a' h
section string
variables [has_to_string α] [∀ a, has_to_string (β a)]
open prod
private def key_data_to_string (a : α) (b : β a) (first : bool) : string :=
(if first then "" else ", ") ++ sformat!"{a} ← {b}"
private def to_string (m : hash_map α β) : string :=
"⟨" ++ (fst (fold m ("", tt) (λ p a b, (fst p ++ key_data_to_string a b (snd p), ff)))) ++ "⟩"
instance : has_to_string (hash_map α β) :=
⟨to_string⟩
end string
section format
open format prod
variables [has_to_format α] [∀ a, has_to_format (β a)]
private meta def format_key_data (a : α) (b : β a) (first : bool) : format :=
(if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt a ++ space ++ to_fmt "←" ++ space ++ to_fmt b
private meta def to_format (m : hash_map α β) : format :=
group $ to_fmt "⟨" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ p a b, (fst p ++ format_key_data a b (snd p), ff)))) ++
to_fmt "⟩"
meta instance : has_to_format (hash_map α β) :=
⟨to_format⟩
end format
end hash_map
|
29e61a8303c47441f20db56cdc0777a037d804b7 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/tactic/tauto.lean | 89ffec7d814524d0e24c47e515c109a1c5d9b8f5 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 11,537 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import tactic.hint
namespace tactic
open expr
open tactic.interactive ( casesm constructor_matching )
/--
find all assumptions of the shape `¬ (p ∧ q)` or `¬ (p ∨ q)` and
replace them using de Morgan's law.
-/
meta def distrib_not : tactic unit :=
do hs ← local_context,
hs.for_each $ λ h,
all_goals' $
iterate_at_most' 3 $
do h ← get_local h.local_pp_name,
e ← infer_type h,
match e with
| `(¬ _ = _) := replace h.local_pp_name ``(mt iff.to_eq %%h)
| `(_ ≠ _) := replace h.local_pp_name ``(mt iff.to_eq %%h)
| `(_ = _) := replace h.local_pp_name ``(eq.to_iff %%h)
| `(¬ (_ ∧ _)) := replace h.local_pp_name ``(decidable.not_and_distrib'.mp %%h) <|>
replace h.local_pp_name ``(decidable.not_and_distrib.mp %%h)
| `(¬ (_ ∨ _)) := replace h.local_pp_name ``(not_or_distrib.mp %%h)
| `(¬ ¬ _) := replace h.local_pp_name ``(decidable.of_not_not %%h)
| `(¬ (_ → (_ : Prop))) := replace h.local_pp_name ``(decidable.not_imp.mp %%h)
| `(¬ (_ ↔ _)) := replace h.local_pp_name ``(decidable.not_iff.mp %%h)
| `(_ ↔ _) := replace h.local_pp_name ``(decidable.iff_iff_and_or_not_and_not.mp %%h) <|>
replace h.local_pp_name
``(decidable.iff_iff_and_or_not_and_not.mp (%%h).symm) <|>
() <$ tactic.cases h
| `(_ → _) := replace h.local_pp_name ``(decidable.not_or_of_imp %%h)
| _ := failed
end
/-!
The following definitions maintain a path compression datastructure, i.e. a forest such that:
- every node is the type of a hypothesis
- there is a edge between two nodes only if they are provably equivalent
- every edge is labelled with a proof of equivalence for its vertices
- edges are added when normalizing propositions.
-/
meta def tauto_state := ref $ expr_map (option (expr × expr))
meta def modify_ref {α : Type} (r : ref α) (f : α → α) :=
read_ref r >>= write_ref r ∘ f
meta def add_refl (r : tauto_state) (e : expr) : tactic (expr × expr) :=
do m ← read_ref r,
p ← mk_mapp `rfl [none,e],
write_ref r $ m.insert e none,
return (e,p)
/--
If there exists a symmetry lemma that can be applied to the hypothesis `e`,
store it.
-/
meta def add_symm_proof (r : tauto_state) (e : expr) : tactic (expr × expr) :=
do env ← get_env,
let rel := e.get_app_fn.const_name,
some symm ← pure $ environment.symm_for env rel
| add_refl r e,
(do e' ← mk_meta_var `(Prop),
iff_t ← to_expr ``(%%e = %%e'),
(_,p) ← solve_aux iff_t
(applyc `iff.to_eq ; () <$ split ; applyc symm),
e' ← instantiate_mvars e',
m ← read_ref r,
write_ref r $ (m.insert e (e',p)).insert e' none,
return (e',p) )
<|> add_refl r e
meta def add_edge (r : tauto_state) (x y p : expr) : tactic unit :=
modify_ref r $ λ m, m.insert x (y,p)
/--
Retrieve the root of the hypothesis `e` from the proof forest.
If `e` has not been internalized, add it to the proof forest.
-/
meta def root (r : tauto_state) : expr → tactic (expr × expr) | e :=
do m ← read_ref r,
let record_e : tactic (expr × expr) :=
match e with
| v@(expr.mvar _ _ _) :=
(do (e,p) ← get_assignment v >>= root,
add_edge r v e p,
return (e,p)) <|>
add_refl r e
| _ := add_refl r e
end,
some e' ← pure $ m.find e | record_e,
match e' with
| (some (e',p')) :=
do (e'',p'') ← root e',
p'' ← mk_app `eq.trans [p',p''],
add_edge r e e'' p'',
pure (e'',p'')
| none := prod.mk e <$> mk_mapp `rfl [none,some e]
end
/--
Given hypotheses `a` and `b`, build a proof that `a` is equivalent to `b`,
applying congruence and recursing into arguments if `a` and `b`
are applications of function symbols.
-/
meta def symm_eq (r : tauto_state) : expr → expr → tactic expr | a b :=
do m ← read_ref r,
(a',pa) ← root r a,
(b',pb) ← root r b,
(unify a' b' >> add_refl r a' *> mk_mapp `rfl [none,a]) <|>
do p ← match (a', b') with
| (`(¬ %%a₀), `(¬ %%b₀)) :=
do p ← symm_eq a₀ b₀,
p' ← mk_app `congr_arg [`(not),p],
add_edge r a' b' p',
return p'
| (`(%%a₀ ∧ %%a₁), `(%%b₀ ∧ %%b₁)) :=
do p₀ ← symm_eq a₀ b₀,
p₁ ← symm_eq a₁ b₁,
p' ← to_expr ``(congr (congr_arg and %%p₀) %%p₁),
add_edge r a' b' p',
return p'
| (`(%%a₀ ∨ %%a₁), `(%%b₀ ∨ %%b₁)) :=
do p₀ ← symm_eq a₀ b₀,
p₁ ← symm_eq a₁ b₁,
p' ← to_expr ``(congr (congr_arg or %%p₀) %%p₁),
add_edge r a' b' p',
return p'
| (`(%%a₀ ↔ %%a₁), `(%%b₀ ↔ %%b₁)) :=
(do p₀ ← symm_eq a₀ b₀,
p₁ ← symm_eq a₁ b₁,
p' ← to_expr ``(congr (congr_arg iff %%p₀) %%p₁),
add_edge r a' b' p',
return p') <|>
do p₀ ← symm_eq a₀ b₁,
p₁ ← symm_eq a₁ b₀,
p' ← to_expr ``(eq.trans (congr (congr_arg iff %%p₀) %%p₁)
(iff.to_eq iff.comm ) ),
add_edge r a' b' p',
return p'
| (`(%%a₀ → %%a₁), `(%%b₀ → %%b₁)) :=
if ¬ a₁.has_var ∧ ¬ b₁.has_var then
do p₀ ← symm_eq a₀ b₀,
p₁ ← symm_eq a₁ b₁,
p' ← mk_app `congr_arg [`(implies),p₀,p₁],
add_edge r a' b' p',
return p'
else unify a' b' >> add_refl r a' *> mk_mapp `rfl [none,a]
| (_, _) :=
(do guard $ a'.get_app_fn.is_constant ∧
a'.get_app_fn.const_name = b'.get_app_fn.const_name,
(a'',pa') ← add_symm_proof r a',
guard $ a'' =ₐ b',
pure pa' )
end,
p' ← mk_eq_trans pa p,
add_edge r a' b' p',
mk_eq_symm pb >>= mk_eq_trans p'
meta def find_eq_type (r : tauto_state) : expr → list expr → tactic (expr × expr)
| e [] := failed
| e (H :: Hs) :=
do t ← infer_type H,
(prod.mk H <$> symm_eq r e t) <|> find_eq_type e Hs
private meta def contra_p_not_p (r : tauto_state) : list expr → list expr → tactic unit
| [] Hs := failed
| (H1 :: Rs) Hs :=
do t ← (extract_opt_auto_param <$> infer_type H1) >>= whnf,
(do a ← match_not t,
(H2,p) ← find_eq_type r a Hs,
H2 ← to_expr ``( (%%p).mpr %%H2 ),
tgt ← target,
pr ← mk_app `absurd [tgt, H2, H1],
tactic.exact pr)
<|> contra_p_not_p Rs Hs
meta def contradiction_with (r : tauto_state) : tactic unit :=
contradiction <|>
do tactic.try intro1,
ctx ← local_context,
contra_p_not_p r ctx ctx
meta def contradiction_symm :=
using_new_ref (native.rb_map.mk _ _) contradiction_with
meta def assumption_with (r : tauto_state) : tactic unit :=
do { ctx ← local_context,
t ← target,
(H,p) ← find_eq_type r t ctx,
mk_eq_mpr p H >>= tactic.exact }
<|> fail "assumption tactic failed"
meta def assumption_symm :=
using_new_ref (native.rb_map.mk _ _) assumption_with
/--
Configuration options for `tauto`.
If `classical` is `tt`, runs `classical` before the rest of `tauto`.
`closer` is run on any remaining subgoals left by `tauto_core; basic_tauto_tacs`.
-/
meta structure tauto_cfg :=
(classical : bool := ff)
(closer : tactic unit := pure ())
meta def tautology (cfg : tauto_cfg := {}) : tactic unit := focus1 $
let basic_tauto_tacs : list (tactic unit) :=
[reflexivity, solve_by_elim,
constructor_matching none [``(_ ∧ _),``(_ ↔ _),``(Exists _),``(true)]],
tauto_core (r : tauto_state) : tactic unit :=
do try (contradiction_with r);
try (assumption_with r);
repeat (do
gs ← get_goals,
repeat (() <$ tactic.intro1);
distrib_not;
casesm (some ()) [``(_ ∧ _),``(_ ∨ _),``(Exists _),``(false)];
try (contradiction_with r);
try (target >>= match_or >> refine ``( or_iff_not_imp_left.mpr _));
try (target >>= match_or >> refine ``( or_iff_not_imp_right.mpr _));
repeat (() <$ tactic.intro1);
constructor_matching (some ()) [``(_ ∧ _),``(_ ↔ _),``(true)];
try (assumption_with r),
gs' ← get_goals,
guard (gs ≠ gs') ) in
do when cfg.classical (classical tt),
using_new_ref (expr_map.mk _) tauto_core;
repeat (first basic_tauto_tacs); cfg.closer, done
namespace interactive
local postfix `?`:9001 := optional
setup_tactic_parser
/--
`tautology` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _`
and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged
using `reflexivity` or `solve_by_elim`.
This is a finishing tactic: it either closes the goal or raises an error.
The variant `tautology!` uses the law of excluded middle.
`tautology {closer := tac}` will use `tac` on any subgoals created by `tautology`
that it is unable to solve before failing.
-/
meta def tautology (c : parse $ (tk "!")?) (cfg : tactic.tauto_cfg := {}) :=
tactic.tautology $ { classical := c.is_some, ..cfg }
-- Now define a shorter name for the tactic `tautology`.
/--
`tauto` breaks down assumptions of the form `_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _`
and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged
using `reflexivity` or `solve_by_elim`.
This is a finishing tactic: it either closes the goal or raises an error.
The variant `tauto!` uses the law of excluded middle.
`tauto {closer := tac}` will use `tac` on any subgoals created by `tauto`
that it is unable to solve before failing.
-/
meta def tauto (c : parse $ (tk "!")?) (cfg : tactic.tauto_cfg := {}) : tactic unit :=
tautology c cfg
add_hint_tactic "tauto"
/--
This tactic (with shorthand `tauto`) breaks down assumptions of the form
`_ ∧ _`, `_ ∨ _`, `_ ↔ _` and `∃ _, _`
and splits a goal of the form `_ ∧ _`, `_ ↔ _` or `∃ _, _` until it can be discharged
using `reflexivity` or `solve_by_elim`. This is a finishing tactic: it
either closes the goal or raises an error.
The variants `tautology!` and `tauto!` use the law of excluded middle.
For instance, one can write:
```lean
example (p q r : Prop) [decidable p] [decidable r] : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (r ∨ p ∨ r) := by tauto
```
and the decidability assumptions can be dropped if `tauto!` is used
instead of `tauto`.
`tauto {closer := tac}` will use `tac` on any subgoals created by `tauto`
that it is unable to solve before failing.
-/
add_tactic_doc
{ name := "tautology",
category := doc_category.tactic,
decl_names := [`tactic.interactive.tautology, `tactic.interactive.tauto],
tags := ["logic", "decision procedure"] }
end interactive
end tactic
|
41ec79331992ac663204d1554784e440fe79de5c | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/conj_auto.lean | a22adaf548bc407ed63347853313e73d057181cb | [] | 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,338 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.endomorphism
import Mathlib.algebra.group_power.default
import Mathlib.PostPort
universes u v v₁ u₁
namespace Mathlib
/-!
# Conjugate morphisms by isomorphisms
An isomorphism `α : X ≅ Y` defines
- a monoid isomorphism `conj : End X ≃* End Y` by `α.conj f = α.inv ≫ f ≫ α.hom`;
- a group isomorphism `conj_Aut : Aut X ≃* Aut Y` by `α.conj_Aut f = α.symm ≪≫ f ≪≫ α`.
For completeness, we also define `hom_congr : (X ≅ X₁) → (Y ≅ Y₁) → (X ⟶ Y) ≃ (X₁ ⟶ Y₁)`, cf. `equiv.arrow_congr`.
-/
namespace category_theory
namespace iso
/-- If `X` is isomorphic to `X₁` and `Y` is isomorphic to `Y₁`, then
there is a natural bijection between `X ⟶ Y` and `X₁ ⟶ Y₁`. See also `equiv.arrow_congr`. -/
def hom_congr {C : Type u} [category C] {X : C} {Y : C} {X₁ : C} {Y₁ : C} (α : X ≅ X₁)
(β : Y ≅ Y₁) : (X ⟶ Y) ≃ (X₁ ⟶ Y₁) :=
equiv.mk (fun (f : X ⟶ Y) => inv α ≫ f ≫ hom β) (fun (f : X₁ ⟶ Y₁) => hom α ≫ f ≫ inv β) sorry
sorry
@[simp] theorem hom_congr_apply {C : Type u} [category C] {X : C} {Y : C} {X₁ : C} {Y₁ : C}
(α : X ≅ X₁) (β : Y ≅ Y₁) (f : X ⟶ Y) : coe_fn (hom_congr α β) f = inv α ≫ f ≫ hom β :=
rfl
theorem hom_congr_comp {C : Type u} [category C] {X : C} {Y : C} {Z : C} {X₁ : C} {Y₁ : C} {Z₁ : C}
(α : X ≅ X₁) (β : Y ≅ Y₁) (γ : Z ≅ Z₁) (f : X ⟶ Y) (g : Y ⟶ Z) :
coe_fn (hom_congr α γ) (f ≫ g) = coe_fn (hom_congr α β) f ≫ coe_fn (hom_congr β γ) g :=
sorry
@[simp] theorem hom_congr_refl {C : Type u} [category C] {X : C} {Y : C} (f : X ⟶ Y) :
coe_fn (hom_congr (refl X) (refl Y)) f = f :=
sorry
@[simp] theorem hom_congr_trans {C : Type u} [category C] {X₁ : C} {Y₁ : C} {X₂ : C} {Y₂ : C}
{X₃ : C} {Y₃ : C} (α₁ : X₁ ≅ X₂) (β₁ : Y₁ ≅ Y₂) (α₂ : X₂ ≅ X₃) (β₂ : Y₂ ≅ Y₃) (f : X₁ ⟶ Y₁) :
coe_fn (hom_congr (α₁ ≪≫ α₂) (β₁ ≪≫ β₂)) f =
coe_fn (equiv.trans (hom_congr α₁ β₁) (hom_congr α₂ β₂)) f :=
sorry
@[simp] theorem hom_congr_symm {C : Type u} [category C] {X₁ : C} {Y₁ : C} {X₂ : C} {Y₂ : C}
(α : X₁ ≅ X₂) (β : Y₁ ≅ Y₂) : equiv.symm (hom_congr α β) = hom_congr (symm α) (symm β) :=
rfl
/-- An isomorphism between two objects defines a monoid isomorphism between their
monoid of endomorphisms. -/
def conj {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) : End X ≃* End Y :=
mul_equiv.mk (equiv.to_fun (hom_congr α α)) (equiv.inv_fun (hom_congr α α)) sorry sorry sorry
theorem conj_apply {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : End X) :
coe_fn (conj α) f = inv α ≫ f ≫ hom α :=
rfl
@[simp] theorem conj_comp {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : End X)
(g : End X) : coe_fn (conj α) (f ≫ g) = coe_fn (conj α) f ≫ coe_fn (conj α) g :=
mul_equiv.map_mul (conj α) g f
@[simp] theorem conj_id {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) :
coe_fn (conj α) 𝟙 = 𝟙 :=
mul_equiv.map_one (conj α)
@[simp] theorem refl_conj {C : Type u} [category C] {X : C} (f : End X) :
coe_fn (conj (refl X)) f = f :=
sorry
@[simp] theorem trans_conj {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) {Z : C} (β : Y ≅ Z)
(f : End X) : coe_fn (conj (α ≪≫ β)) f = coe_fn (conj β) (coe_fn (conj α) f) :=
hom_congr_trans α α β β f
@[simp] theorem symm_self_conj {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : End X) :
coe_fn (conj (symm α)) (coe_fn (conj α) f) = f :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (coe_fn (conj (symm α)) (coe_fn (conj α) f) = f))
(Eq.symm (trans_conj α (symm α) f))))
(eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (conj (α ≪≫ symm α)) f = f)) (self_symm_id α)))
(eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (conj (refl X)) f = f)) (refl_conj f))) (Eq.refl f)))
@[simp] theorem self_symm_conj {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : End Y) :
coe_fn (conj α) (coe_fn (conj (symm α)) f) = f :=
symm_self_conj (symm α) f
@[simp] theorem conj_pow {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : End X) (n : ℕ) :
coe_fn (conj α) (f ^ n) = coe_fn (conj α) f ^ n :=
monoid_hom.map_pow (mul_equiv.to_monoid_hom (conj α)) f n
/-- `conj` defines a group isomorphisms between groups of automorphisms -/
def conj_Aut {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) : Aut X ≃* Aut Y :=
mul_equiv.trans (mul_equiv.symm (Aut.units_End_equiv_Aut X))
(mul_equiv.trans (units.map_equiv (conj α)) (Aut.units_End_equiv_Aut Y))
theorem conj_Aut_apply {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : Aut X) :
coe_fn (conj_Aut α) f = symm α ≪≫ f ≪≫ α :=
sorry
@[simp] theorem conj_Aut_hom {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : Aut X) :
hom (coe_fn (conj_Aut α) f) = coe_fn (conj α) (hom f) :=
rfl
@[simp] theorem trans_conj_Aut {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) {Z : C}
(β : Y ≅ Z) (f : Aut X) :
coe_fn (conj_Aut (α ≪≫ β)) f = coe_fn (conj_Aut β) (coe_fn (conj_Aut α) f) :=
sorry
@[simp] theorem conj_Aut_mul {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : Aut X)
(g : Aut X) : coe_fn (conj_Aut α) (f * g) = coe_fn (conj_Aut α) f * coe_fn (conj_Aut α) g :=
mul_equiv.map_mul (conj_Aut α) f g
@[simp] theorem conj_Aut_trans {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : Aut X)
(g : Aut X) : coe_fn (conj_Aut α) (f ≪≫ g) = coe_fn (conj_Aut α) f ≪≫ coe_fn (conj_Aut α) g :=
conj_Aut_mul α g f
@[simp] theorem conj_Aut_pow {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : Aut X)
(n : ℕ) : coe_fn (conj_Aut α) (f ^ n) = coe_fn (conj_Aut α) f ^ n :=
monoid_hom.map_pow (mul_equiv.to_monoid_hom (conj_Aut α)) f n
@[simp] theorem conj_Aut_gpow {C : Type u} [category C] {X : C} {Y : C} (α : X ≅ Y) (f : Aut X)
(n : ℤ) : coe_fn (conj_Aut α) (f ^ n) = coe_fn (conj_Aut α) f ^ n :=
monoid_hom.map_gpow (mul_equiv.to_monoid_hom (conj_Aut α)) f n
end iso
namespace functor
theorem map_hom_congr {C : Type u} [category C] {D : Type u₁} [category D] (F : C ⥤ D) {X : C}
{Y : C} {X₁ : C} {Y₁ : C} (α : X ≅ X₁) (β : Y ≅ Y₁) (f : X ⟶ Y) :
map F (coe_fn (iso.hom_congr α β) f) =
coe_fn (iso.hom_congr (map_iso F α) (map_iso F β)) (map F f) :=
sorry
theorem map_conj {C : Type u} [category C] {D : Type u₁} [category D] (F : C ⥤ D) {X : C} {Y : C}
(α : X ≅ Y) (f : End X) :
map F (coe_fn (iso.conj α) f) = coe_fn (iso.conj (map_iso F α)) (map F f) :=
map_hom_congr F α α f
theorem map_conj_Aut {C : Type u} [category C] {D : Type u₁} [category D] (F : C ⥤ D) {X : C}
{Y : C} (α : X ≅ Y) (f : Aut X) :
map_iso F (coe_fn (iso.conj_Aut α) f) = coe_fn (iso.conj_Aut (map_iso F α)) (map_iso F f) :=
sorry
end Mathlib |
344be80fe76642640f0e3930d2d8c11ea19255c9 | 37b510e903b0c4b79327d2a739d5a5973997750b | /spatial-reasoning-problem-06.lean | 810ac5baa03a17d186ff71d55e845c4a4e62b025 | [] | no_license | yfaria/common-sense-lean | 5124f71460c0d09efeda9dab5db68417cb4053f6 | 459ea9b9515c077461aa4b5b5191e3c76748aaa9 | refs/heads/master | 1,652,126,029,266 | 1,587,485,762,000 | 1,587,485,762,000 | 257,465,961 | 0 | 0 | null | 1,587,438,417,000 | 1,587,438,416,000 | null | UTF-8 | Lean | false | false | 1,835 | lean | /- Spatial Reasoning Problem 01 -/
/- It can be found at: github.com/ontologyportal/sumo/blob/master/tests/SpatialQs.txt -/
-- (6) A bookcase is on the floor. A book is on the bookcase. Is the book higher than the floor?
universe V
constant U : Type
constants Right Left Book Furniture Floor On TransitivePositionalAttribute PositionalAttribute Above : U
constant ins : U → U → Prop
constant located : U → U → Prop
constant subclass : U → U → Prop
constant orientation: U → U → U → Prop
/-
(exists (?B ?F ?BOOK)
(and
(instance ?BOOK Book)
(instance ?B Furniture)
(instance ?F Floor)
(orientation ?B ?F On)
(orientation ?BOOK ?B On)))
-/
axiom a1 : ∃ b f book : U ,
ins book Book ∧
ins b Furniture ∧
ins f Floor ∧
orientation b f On ∧
orientation book b On
/-
(subclass TransitivePositionalAttribute PositionalAttribute)
-/
axiom a2 : subclass TransitivePositionalAttribute PositionalAttribute
/-
(=>
(and
(orientation ?A ?B ?P)
(orientation ?B ?C ?P)
(instance ?P TransitivePositionalAttribute))
(orientation ?A ?C ?P))
-/
axiom a3 : ∀ a b c p : U,
(orientation a b p ∧
orientation b c p ∧
ins p TransitivePositionalAttribute) →
orientation a c p
/-
(=>
(and
(orientation ?A ?B On)
(orientation ?B ?C On))
(orientation ?A ?C Above))
-/
axiom a4 : ∀ a b c : U,
orientation a b On ∧ orientation b c On →
orientation a c Above
theorem book_above_floor : ∃ (book : U) (f : U), orientation book f Above :=
begin
apply exists.elim a1, assume b h1,
apply exists.elim h1, assume f h2,
apply exists.elim h2, assume book h3,
apply exists.intro book, apply exists.intro f,
apply a4 book b f,
split,
exact h3.right.right.right.right,
exact h3.right.right.right.left
end
|
82498a734c83db60f57e23f985ae195127d33836 | c61b91f85121053c627318ad8fcde30dfb8637d2 | /Chapter4/4-2.lean | cb5dbdb5c27c8005ba00438294f0914f9faa68e2 | [] | no_license | robkorn/theorem-proving-in-lean-exercises | 9e2256360eaf6f8df6cdd8fd656e63dfb04c8cdb | 9c51da587105ee047a9db55d52709d881a39be7a | refs/heads/master | 1,585,403,341,988 | 1,540,142,619,000 | 1,540,142,619,000 | 148,431,678 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,971 | lean |
universe u
#check @eq.refl.{u}
#check @eq.symm.{u}
#check @eq.trans
-- If '@' is used but no universe is specified it uses a default one it seems
namespace prev
variables (α : Type u) (a b c d : α)
variables (hab : a = b) (hcb : c = b) (hcd : c = d)
example : a = d := (hab.trans hcb.symm).trans hcd
end prev
namespace refl
variables (α β : Type u)
example (f : α → β) (a : α) : (λx, f x) a = f a := eq.refl (f a)
example (f : α → β) (a : α) : (λx, f x) a = f a := eq.refl _
example (f : α → β) (a : α) : (λx, f x) a = f a := rfl
example (a : α) (b : α) : (a, b).1 = a := eq.refl a
example (a : α) (b : α) : (a, b).1 = a := eq.refl _
example (a : α) (b : α) : (a, b).1 = a := rfl
example : 2 + 3 = 5 := eq.refl 5
example : 2 + 3 = 5 := eq.refl _
example : 2 + 3 = 5 := rfl
end refl
namespace reflequiv
example (α : Type u) (a b : α) (p : α → Prop) (h1 :a = b) (h2 : p a) : p b :=
eq.subst h1 h2
example (α : Type u) (a b : α) (p : α → Prop)
(h1 : a = b) (h2 : p a) : p b :=
h1 ▸ h2
end reflequiv
namespace cong
variable α : Type
variables a b : α
variables f g : α → ℕ
variable h₁ : a = b
variable h₂ : f = g
example : f a = f b := congr_arg _ h₁
example : f a = g a := congr_fun h₂ _
example : f a = g b := congr h₂ h₁
end cong
namespace ints
variables x y z : ℤ
example (x y z : ℕ) : x * (y + z) = x * y + x * z := mul_add x y z
example (x y z : ℕ) : (x + y) * z = x * z + y * z := add_mul x y z
example (x y z : ℕ) : x + y + z = x + (y + z) := add_assoc x y z
example (x y : ℕ) : (x + y) * (x + y) = x * x + y * x + x * y + y * y :=
have h1 : (x + y) * (x + y) = (x + y) * x + (x + y) * y,
from left_distrib (x + y) x y,
have h2 : (x + y) * (x + y) = x * x + y * x + (x * y + y * y),
from (right_distrib x y y) ▸ (right_distrib x y x) ▸ h1,
(add_assoc (x * x + y * x) (x * y) (y * y)).symm ▸ h2
-- or:
-- h2.trans (add_assoc (x * x + y * x) (x * y) (y * y)).symm
end ints
|
e1ebfb5c09d8b37cfc9dd16459a21a357cbd40e1 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/finset/nat_antidiagonal.lean | 89b428effedb0f9bbca4fe4f98e06791c2fbfe4a | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 4,910 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import data.finset.card
import data.multiset.nat_antidiagonal
/-!
# Antidiagonals in ℕ × ℕ as finsets
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the antidiagonals of ℕ × ℕ as finsets: the `n`-th antidiagonal is the finset of
pairs `(i, j)` such that `i + j = n`. This is useful for polynomial multiplication and more
generally for sums going from `0` to `n`.
## Notes
This refines files `data.list.nat_antidiagonal` and `data.multiset.nat_antidiagonal`.
-/
namespace finset
namespace nat
/-- The antidiagonal of a natural number `n` is
the finset of pairs `(i, j)` such that `i + j = n`. -/
def antidiagonal (n : ℕ) : finset (ℕ × ℕ) :=
⟨multiset.nat.antidiagonal n, multiset.nat.nodup_antidiagonal n⟩
/-- A pair (i, j) is contained in the antidiagonal of `n` if and only if `i + j = n`. -/
@[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} :
x ∈ antidiagonal n ↔ x.1 + x.2 = n :=
by rw [antidiagonal, mem_def, multiset.nat.mem_antidiagonal]
/-- The cardinality of the antidiagonal of `n` is `n + 1`. -/
@[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 :=
by simp [antidiagonal]
/-- The antidiagonal of `0` is the list `[(0, 0)]` -/
@[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} :=
rfl
lemma antidiagonal_succ (n : ℕ) :
antidiagonal (n + 1) = cons (0, n + 1) ((antidiagonal n).map
(function.embedding.prod_map ⟨nat.succ, nat.succ_injective⟩ (function.embedding.refl _)))
(by simp) :=
begin
apply eq_of_veq,
rw [cons_val, map_val],
{ apply multiset.nat.antidiagonal_succ },
end
lemma antidiagonal_succ' (n : ℕ) :
antidiagonal (n + 1) = cons (n + 1, 0) ((antidiagonal n).map
(function.embedding.prod_map (function.embedding.refl _) ⟨nat.succ, nat.succ_injective⟩))
(by simp) :=
begin
apply eq_of_veq,
rw [cons_val, map_val],
exact multiset.nat.antidiagonal_succ',
end
lemma antidiagonal_succ_succ' {n : ℕ} :
antidiagonal (n + 2) =
cons (0, n + 2)
(cons (n + 2, 0) ((antidiagonal n).map
(function.embedding.prod_map ⟨nat.succ, nat.succ_injective⟩ ⟨nat.succ, nat.succ_injective⟩))
$ by simp) (by simp) :=
by { simp_rw [antidiagonal_succ (n + 1), antidiagonal_succ', finset.map_cons, map_map], refl }
lemma map_swap_antidiagonal {n : ℕ} :
(antidiagonal n).map ⟨prod.swap, prod.swap_right_inverse.injective⟩ = antidiagonal n :=
eq_of_veq $ by simp [antidiagonal, multiset.nat.map_swap_antidiagonal]
/-- A point in the antidiagonal is determined by its first co-ordinate. -/
lemma antidiagonal_congr {n : ℕ} {p q : ℕ × ℕ} (hp : p ∈ antidiagonal n)
(hq : q ∈ antidiagonal n) : p = q ↔ p.fst = q.fst :=
begin
refine ⟨congr_arg prod.fst, (λ h, prod.ext h ((add_right_inj q.fst).mp _))⟩,
rw mem_antidiagonal at hp hq,
rw [hq, ← h, hp],
end
lemma antidiagonal.fst_le {n : ℕ} {kl : ℕ × ℕ} (hlk : kl ∈ antidiagonal n) :
kl.1 ≤ n :=
begin
rw le_iff_exists_add,
use kl.2,
rwa [mem_antidiagonal, eq_comm] at hlk
end
lemma antidiagonal.snd_le {n : ℕ} {kl : ℕ × ℕ} (hlk : kl ∈ antidiagonal n) :
kl.2 ≤ n :=
begin
rw le_iff_exists_add,
use kl.1,
rwa [mem_antidiagonal, eq_comm, add_comm] at hlk
end
lemma filter_fst_eq_antidiagonal (n m : ℕ) :
filter (λ x : ℕ × ℕ, x.fst = m) (antidiagonal n) = if m ≤ n then {(m, n - m)} else ∅ :=
begin
ext ⟨x, y⟩,
simp only [mem_filter, nat.mem_antidiagonal],
split_ifs with h h,
{ simp [and_comm, eq_tsub_iff_add_eq_of_le h, add_comm] {contextual := tt} },
{ rw not_le at h,
simp only [not_mem_empty, iff_false, not_and],
exact λ hn, ne_of_lt (lt_of_le_of_lt (le_self_add.trans hn.le) h) }
end
lemma filter_snd_eq_antidiagonal (n m : ℕ) :
filter (λ x : ℕ × ℕ, x.snd = m) (antidiagonal n) = if m ≤ n then {(n - m, m)} else ∅ :=
begin
have : (λ (x : ℕ × ℕ), x.snd = m) ∘ prod.swap = (λ (x : ℕ × ℕ), x.fst = m),
{ ext, simp },
rw ←map_swap_antidiagonal,
simp [filter_map, this, filter_fst_eq_antidiagonal, apply_ite (finset.map _)]
end
section equiv_prod
/-- The disjoint union of antidiagonals `Σ (n : ℕ), antidiagonal n` is equivalent to the product
`ℕ × ℕ`. This is such an equivalence, obtained by mapping `(n, (k, l))` to `(k, l)`. -/
@[simps] def sigma_antidiagonal_equiv_prod : (Σ (n : ℕ), antidiagonal n) ≃ ℕ × ℕ :=
{ to_fun := λ x, x.2,
inv_fun := λ x, ⟨x.1 + x.2, x, mem_antidiagonal.mpr rfl⟩,
left_inv :=
begin
rintros ⟨n, ⟨k, l⟩, h⟩,
rw mem_antidiagonal at h,
exact sigma.subtype_ext h rfl,
end,
right_inv := λ x, rfl }
end equiv_prod
end nat
end finset
|
41ad9eab3eada75196dfa74bfcff1bdf510b7ab6 | 5749d8999a76f3a8fddceca1f6941981e33aaa96 | /src/analysis/calculus/tangent_cone.lean | 612005dc4ee69c7174dbd8015262c8905de40c13 | [
"Apache-2.0"
] | permissive | jdsalchow/mathlib | 13ab43ef0d0515a17e550b16d09bd14b76125276 | 497e692b946d93906900bb33a51fd243e7649406 | refs/heads/master | 1,585,819,143,348 | 1,580,072,892,000 | 1,580,072,892,000 | 154,287,128 | 0 | 0 | Apache-2.0 | 1,540,281,610,000 | 1,540,281,609,000 | null | UTF-8 | Lean | false | false | 18,843 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import analysis.convex analysis.normed_space.bounded_linear_maps analysis.specific_limits
/-!
# Tangent cone
In this file, we define two predicates `unique_diff_within_at 𝕜 s x` and `unique_diff_on 𝕜 s`
ensuring that, if a function has two derivatives, then they have to coincide. As a direct
definition of this fact (quantifying on all target types and all functions) would depend on
universes, we use a more intrinsic definition: if all the possible tangent directions to the set
`s` at the point `x` span a dense subset of the whole subset, it is easy to check that the
derivative has to be unique.
Therefore, we introduce the set of all tangent directions, named `tangent_cone_at`,
and express `unique_diff_within_at` and `unique_diff_on` in terms of it.
One should however think of this definition as an implementation detail: the only reason to
introduce the predicates `unique_diff_within_at` and `unique_diff_on` is to ensure the uniqueness
of the derivative. This is why their names reflect their uses, and not how they are defined.
## Implementation details
Note that this file is imported by `fderiv.lean`. Hence, derivatives are not defined yet. The
property of uniqueness of the derivative is therefore proved in `fderiv.lean`, but based on the
properties of the tangent cone we prove here.
-/
variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F]
variables {G : Type*} [normed_group G] [normed_space ℝ G]
set_option class.instance_max_depth 50
open filter set
open_locale topological_space
/-- The set of all tangent directions to the set `s` at the point `x`. -/
def tangent_cone_at (s : set E) (x : E) : set E :=
{y : E | ∃(c : ℕ → 𝕜) (d : ℕ → E), {n:ℕ | x + d n ∈ s} ∈ (at_top : filter ℕ) ∧
(tendsto (λn, ∥c n∥) at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))}
/-- A property ensuring that the tangent cone to `s` at `x` spans a dense subset of the whole space.
The main role of this property is to ensure that the differential within `s` at `x` is unique,
hence this name. The uniqueness it asserts is proved in `unique_diff_within_at.eq` in `fderiv.lean`.
To avoid pathologies in dimension 0, we also require that `x` belongs to the closure of `s` (which
is automatic when `E` is not `0`-dimensional).
-/
def unique_diff_within_at (s : set E) (x : E) : Prop :=
closure ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E) = univ ∧ x ∈ closure s
/-- A property ensuring that the tangent cone to `s` at any of its points spans a dense subset of
the whole space. The main role of this property is to ensure that the differential along `s` is
unique, hence this name. The uniqueness it asserts is proved in `unique_diff_on.eq` in
`fderiv.lean`. -/
def unique_diff_on (s : set E) : Prop :=
∀x ∈ s, unique_diff_within_at 𝕜 s x
variables {𝕜} {x y : E} {s t : set E}
section tangent_cone
/- This section is devoted to the properties of the tangent cone. -/
open normed_field
lemma tangent_cone_univ : tangent_cone_at 𝕜 univ x = univ :=
begin
refine univ_subset_iff.1 (λy hy, _),
rcases exists_one_lt_norm 𝕜 with ⟨w, hw⟩,
refine ⟨λn, w^n, λn, (w^n)⁻¹ • y, univ_mem_sets' (λn, mem_univ _), _, _⟩,
{ simp only [norm_pow],
exact tendsto_pow_at_top_at_top_of_gt_1 hw },
{ convert tendsto_const_nhds,
ext n,
have : w ^ n * (w ^ n)⁻¹ = 1,
{ apply mul_inv_cancel,
apply pow_ne_zero,
simpa [norm_eq_zero] using (ne_of_lt (lt_trans zero_lt_one hw)).symm },
rw [smul_smul, this, one_smul] }
end
lemma tangent_cone_mono (h : s ⊆ t) :
tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x :=
begin
rintros y ⟨c, d, ds, ctop, clim⟩,
exact ⟨c, d, mem_sets_of_superset ds (λn hn, h hn), ctop, clim⟩
end
/-- Auxiliary lemma ensuring that, under the assumptions defining the tangent cone,
the sequence `d` tends to 0 at infinity. -/
lemma tangent_cone_at.lim_zero {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E}
(hc : tendsto (λn, ∥c n∥) l at_top) (hd : tendsto (λn, c n • d n) l (𝓝 y)) :
tendsto d l (𝓝 0) :=
begin
have A : tendsto (λn, ∥c n∥⁻¹) l (𝓝 0) := tendsto_inv_at_top_zero.comp hc,
have B : tendsto (λn, ∥c n • d n∥) l (𝓝 ∥y∥) :=
(continuous_norm.tendsto _).comp hd,
have C : tendsto (λn, ∥c n∥⁻¹ * ∥c n • d n∥) l (𝓝 (0 * ∥y∥)) := A.mul B,
rw zero_mul at C,
have : {n | ∥c n∥⁻¹ * ∥c n • d n∥ = ∥d n∥} ∈ l,
{ apply mem_sets_of_superset (ne_mem_of_tendsto_norm_at_top hc 0) (λn hn, _),
rw [mem_set_of_eq, norm_smul, ← mul_assoc, inv_mul_cancel, one_mul],
rwa [ne.def, norm_eq_zero] },
have D : tendsto (λ n, ∥d n∥) l (𝓝 0) :=
tendsto.congr' this C,
rw tendsto_zero_iff_norm_tendsto_zero,
exact D
end
lemma tangent_cone_mono_nhds (h : nhds_within x s ≤ nhds_within x t) :
tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x :=
begin
rintros y ⟨c, d, ds, ctop, clim⟩,
refine ⟨c, d, _, ctop, clim⟩,
suffices : tendsto (λ n, x + d n) at_top (nhds_within x t),
from tendsto_principal.1 (tendsto_inf.1 this).2,
apply tendsto_le_right h,
refine tendsto_inf.2 ⟨_, tendsto_principal.2 ds⟩,
simpa only [add_zero] using tendsto_const_nhds.add (tangent_cone_at.lim_zero at_top ctop clim)
end
/-- Tangent cone of `s` at `x` depends only on `nhds_within x s`. -/
lemma tangent_cone_congr (h : nhds_within x s = nhds_within x t) :
tangent_cone_at 𝕜 s x = tangent_cone_at 𝕜 t x :=
subset.antisymm
(tangent_cone_mono_nhds $ le_of_eq h)
(tangent_cone_mono_nhds $ le_of_eq h.symm)
/-- Intersecting with a neighborhood of the point does not change the tangent cone. -/
lemma tangent_cone_inter_nhds (ht : t ∈ 𝓝 x) :
tangent_cone_at 𝕜 (s ∩ t) x = tangent_cone_at 𝕜 s x :=
tangent_cone_congr (nhds_within_restrict' _ ht).symm
/-- The tangent cone of a product contains the tangent cone of its left factor. -/
lemma subset_tangent_cone_prod_left {t : set F} {y : F} (ht : y ∈ closure t) :
set.prod (tangent_cone_at 𝕜 s x) {(0 : F)} ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) :=
begin
rintros ⟨v, w⟩ ⟨⟨c, d, hd, hc, hy⟩, hw⟩,
have : w = 0, by simpa using hw,
rw this,
have : ∀n, ∃d', y + d' ∈ t ∧ ∥c n • d'∥ ≤ ((1:ℝ)/2)^n,
{ assume n,
have c_pos : 0 < 1 + ∥c n∥ :=
add_pos_of_pos_of_nonneg zero_lt_one (norm_nonneg _),
rcases metric.mem_closure_iff'.1 ht ((1 + ∥c n∥)⁻¹ * (1/2)^n) _ with ⟨z, z_pos, hz⟩,
refine ⟨z - y, _, _⟩,
{ convert z_pos, abel },
{ rw [norm_smul, ← dist_eq_norm, dist_comm],
calc ∥c n∥ * dist y z ≤ (1 + ∥c n∥) * ((1 + ∥c n∥)⁻¹ * (1/2)^n) :
begin
apply mul_le_mul _ (le_of_lt hz) dist_nonneg (le_of_lt c_pos),
simp only [zero_le_one, le_add_iff_nonneg_left]
end
... = (1/2)^n :
begin
rw [← mul_assoc, mul_inv_cancel, one_mul],
exact ne_of_gt c_pos
end },
{ apply mul_pos (inv_pos c_pos) (pow_pos _ _),
norm_num } },
choose d' hd' using this,
refine ⟨c, λn, (d n, d' n), _, hc, _⟩,
show {n : ℕ | (x, y) + (d n, d' n) ∈ set.prod s t} ∈ at_top,
{ apply filter.mem_sets_of_superset hd,
assume n hn,
simp at hn,
simp [hn, (hd' n).1] },
{ apply tendsto_prod_mk_nhds hy,
change tendsto (λ (n : ℕ), c n • d' n) at_top (𝓝 0),
rw tendsto_zero_iff_norm_tendsto_zero,
refine squeeze_zero (λn, norm_nonneg _) (λn, (hd' n).2) _,
apply tendsto_pow_at_top_nhds_0_of_lt_1; norm_num }
end
/-- The tangent cone of a product contains the tangent cone of its right factor. -/
lemma subset_tangent_cone_prod_right {t : set F} {y : F}
(hs : x ∈ closure s) :
set.prod {(0 : E)} (tangent_cone_at 𝕜 t y) ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) :=
begin
rintros ⟨v, w⟩ ⟨hv, ⟨c, d, hd, hc, hy⟩⟩,
have : v = 0, by simpa using hv,
rw this,
have : ∀n, ∃d', x + d' ∈ s ∧ ∥c n • d'∥ ≤ ((1:ℝ)/2)^n,
{ assume n,
have c_pos : 0 < 1 + ∥c n∥ :=
add_pos_of_pos_of_nonneg zero_lt_one (norm_nonneg _),
rcases metric.mem_closure_iff'.1 hs ((1 + ∥c n∥)⁻¹ * (1/2)^n) _ with ⟨z, z_pos, hz⟩,
refine ⟨z - x, _, _⟩,
{ convert z_pos, abel },
{ rw [norm_smul, ← dist_eq_norm, dist_comm],
calc ∥c n∥ * dist x z ≤ (1 + ∥c n∥) * ((1 + ∥c n∥)⁻¹ * (1/2)^n) :
begin
apply mul_le_mul _ (le_of_lt hz) dist_nonneg (le_of_lt c_pos),
simp only [zero_le_one, le_add_iff_nonneg_left]
end
... = (1/2)^n :
begin
rw [← mul_assoc, mul_inv_cancel, one_mul],
exact ne_of_gt c_pos
end },
{ apply mul_pos (inv_pos c_pos) (pow_pos _ _),
norm_num } },
choose d' hd' using this,
refine ⟨c, λn, (d' n, d n), _, hc, _⟩,
show {n : ℕ | (x, y) + (d' n, d n) ∈ set.prod s t} ∈ at_top,
{ apply filter.mem_sets_of_superset hd,
assume n hn,
simp at hn,
simp [hn, (hd' n).1] },
{ apply tendsto_prod_mk_nhds _ hy,
change tendsto (λ (n : ℕ), c n • d' n) at_top (𝓝 0),
rw tendsto_zero_iff_norm_tendsto_zero,
refine squeeze_zero (λn, norm_nonneg _) (λn, (hd' n).2) _,
apply tendsto_pow_at_top_nhds_0_of_lt_1; norm_num }
end
/-- If a subset of a real vector space contains a segment, then the direction of this
segment belongs to the tangent cone at its endpoints. -/
lemma mem_tangent_cone_of_segment_subset {s : set G} {x y : G} (h : segment x y ⊆ s) :
y - x ∈ tangent_cone_at ℝ s x :=
begin
let w : ℝ := 2,
let c := λn:ℕ, (2:ℝ)^n,
let d := λn:ℕ, (c n)⁻¹ • (y-x),
refine ⟨c, d, filter.univ_mem_sets' (λn, h _), _, _⟩,
show x + d n ∈ segment x y,
{ refine ⟨(c n)⁻¹, ⟨_, _⟩, _⟩,
{ rw inv_nonneg, apply pow_nonneg, norm_num },
{ apply inv_le_one, apply one_le_pow_of_one_le, norm_num },
{ simp only [d], abel } },
show filter.tendsto (λ (n : ℕ), ∥c n∥) filter.at_top filter.at_top,
{ have : (λ (n : ℕ), ∥c n∥) = c,
by { ext n, exact abs_of_nonneg (pow_nonneg (by norm_num) _) },
rw this,
exact tendsto_pow_at_top_at_top_of_gt_1 (by norm_num) },
show filter.tendsto (λ (n : ℕ), c n • d n) filter.at_top (𝓝 (y - x)),
{ have : (λ (n : ℕ), c n • d n) = (λn, y - x),
{ ext n,
simp only [d, smul_smul],
rw [mul_inv_cancel, one_smul],
exact pow_ne_zero _ (by norm_num) },
rw this,
apply tendsto_const_nhds }
end
end tangent_cone
section unique_diff
/- This section is devoted to properties of the predicates `unique_diff_within_at` and
`unique_diff_on`. -/
lemma unique_diff_within_at_univ : unique_diff_within_at 𝕜 univ x :=
by { rw [unique_diff_within_at, tangent_cone_univ], simp }
lemma unique_diff_on_univ : unique_diff_on 𝕜 (univ : set E) :=
λx hx, unique_diff_within_at_univ
lemma unique_diff_within_at.mono_nhds (h : unique_diff_within_at 𝕜 s x)
(st : nhds_within x s ≤ nhds_within x t) :
unique_diff_within_at 𝕜 t x :=
begin
unfold unique_diff_within_at at *,
rw [← univ_subset_iff, ← h.1],
rw [mem_closure_iff_nhds_within_ne_bot] at h ⊢,
exact ⟨closure_mono (submodule.span_mono (tangent_cone_mono_nhds st)),
lattice.ne_bot_of_le_ne_bot h.2 st⟩
end
lemma unique_diff_within_at.mono (h : unique_diff_within_at 𝕜 s x) (st : s ⊆ t) :
unique_diff_within_at 𝕜 t x :=
h.mono_nhds $ nhds_within_mono _ st
lemma unique_diff_within_at_congr (st : nhds_within x s = nhds_within x t) :
unique_diff_within_at 𝕜 s x ↔ unique_diff_within_at 𝕜 t x :=
⟨λ h, h.mono_nhds $ le_of_eq st, λ h, h.mono_nhds $ le_of_eq st.symm⟩
lemma unique_diff_within_at_inter (ht : t ∈ 𝓝 x) :
unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x :=
unique_diff_within_at_congr $ (nhds_within_restrict' _ ht).symm
lemma unique_diff_within_at.inter (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ 𝓝 x) :
unique_diff_within_at 𝕜 (s ∩ t) x :=
(unique_diff_within_at_inter ht).2 hs
lemma unique_diff_within_at_inter' (ht : t ∈ nhds_within x s) :
unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x :=
unique_diff_within_at_congr $ (nhds_within_restrict'' _ ht).symm
lemma unique_diff_within_at.inter' (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ nhds_within x s) :
unique_diff_within_at 𝕜 (s ∩ t) x :=
(unique_diff_within_at_inter' ht).2 hs
lemma is_open.unique_diff_within_at (hs : is_open s) (xs : x ∈ s) : unique_diff_within_at 𝕜 s x :=
begin
have := unique_diff_within_at_univ.inter (mem_nhds_sets hs xs),
rwa univ_inter at this
end
lemma unique_diff_on.inter (hs : unique_diff_on 𝕜 s) (ht : is_open t) : unique_diff_on 𝕜 (s ∩ t) :=
λx hx, (hs x hx.1).inter (mem_nhds_sets ht hx.2)
lemma is_open.unique_diff_on (hs : is_open s) : unique_diff_on 𝕜 s :=
λx hx, is_open.unique_diff_within_at hs hx
/-- The product of two sets of unique differentiability at points `x` and `y` has unique
differentiability at `(x, y)`. -/
lemma unique_diff_within_at.prod {t : set F} {y : F}
(hs : unique_diff_within_at 𝕜 s x) (ht : unique_diff_within_at 𝕜 t y) :
unique_diff_within_at 𝕜 (set.prod s t) (x, y) :=
begin
rw [unique_diff_within_at, ← univ_subset_iff] at ⊢ hs ht,
split,
{ assume v _,
rw metric.mem_closure_iff',
assume ε ε_pos,
rcases v with ⟨v₁, v₂⟩,
rcases metric.mem_closure_iff'.1 (hs.1 (mem_univ v₁)) ε ε_pos with ⟨w₁, w₁_mem, h₁⟩,
rcases metric.mem_closure_iff'.1 (ht.1 (mem_univ v₂)) ε ε_pos with ⟨w₂, w₂_mem, h₂⟩,
have I₁ : (w₁, (0 : F)) ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 (set.prod s t) (x, y)),
{ apply submodule.span_induction w₁_mem,
{ assume w hw,
have : (w, (0 : F)) ∈ (set.prod (tangent_cone_at 𝕜 s x) {(0 : F)}),
{ rw mem_prod,
simp [hw],
apply mem_insert },
have : (w, (0 : F)) ∈ tangent_cone_at 𝕜 (set.prod s t) (x, y) :=
subset_tangent_cone_prod_left ht.2 this,
exact submodule.subset_span this },
{ exact submodule.zero_mem _ },
{ assume a b ha hb,
have : (a, (0 : F)) + (b, (0 : F)) = (a + b, (0 : F)), by simp,
rw ← this,
exact submodule.add_mem _ ha hb },
{ assume c a ha,
have : c • (0 : F) = (0 : F), by simp,
rw ← this,
exact submodule.smul_mem _ _ ha } },
have I₂ : ((0 : E), w₂) ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 (set.prod s t) (x, y)),
{ apply submodule.span_induction w₂_mem,
{ assume w hw,
have : ((0 : E), w) ∈ (set.prod {(0 : E)} (tangent_cone_at 𝕜 t y)),
{ rw mem_prod,
simp [hw],
apply mem_insert },
have : ((0 : E), w) ∈ tangent_cone_at 𝕜 (set.prod s t) (x, y) :=
subset_tangent_cone_prod_right hs.2 this,
exact submodule.subset_span this },
{ exact submodule.zero_mem _ },
{ assume a b ha hb,
have : ((0 : E), a) + ((0 : E), b) = ((0 : E), a + b), by simp,
rw ← this,
exact submodule.add_mem _ ha hb },
{ assume c a ha,
have : c • (0 : E) = (0 : E), by simp,
rw ← this,
exact submodule.smul_mem _ _ ha } },
have I : (w₁, w₂) ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 (set.prod s t) (x, y)),
{ have : (w₁, (0 : F)) + ((0 : E), w₂) = (w₁, w₂), by simp,
rw ← this,
exact submodule.add_mem _ I₁ I₂ },
refine ⟨(w₁, w₂), I, _⟩,
simp [dist, h₁, h₂] },
{ simp [closure_prod_eq, mem_prod_iff, hs.2, ht.2] }
end
/-- The product of two sets of unique differentiability is a set of unique differentiability. -/
lemma unique_diff_on.prod {t : set F} (hs : unique_diff_on 𝕜 s) (ht : unique_diff_on 𝕜 t) :
unique_diff_on 𝕜 (set.prod s t) :=
λ ⟨x, y⟩ h, unique_diff_within_at.prod (hs x h.1) (ht y h.2)
/-- In a real vector space, a convex set with nonempty interior is a set of unique
differentiability. -/
theorem unique_diff_on_convex {s : set G} (conv : convex s) (hs : interior s ≠ ∅) :
unique_diff_on ℝ s :=
begin
assume x xs,
have A : ∀v, ∃a∈ tangent_cone_at ℝ s x, ∃b∈ tangent_cone_at ℝ s x, ∃δ>(0:ℝ), δ • v = b-a,
{ assume v,
rcases ne_empty_iff_exists_mem.1 hs with ⟨y, hy⟩,
have ys : y ∈ s := interior_subset hy,
have : ∃(δ : ℝ), 0<δ ∧ y + δ • v ∈ s,
{ by_cases h : ∥v∥ = 0,
{ exact ⟨1, zero_lt_one, by simp [(norm_eq_zero _).1 h, ys]⟩ },
{ rcases mem_interior.1 hy with ⟨u, us, u_open, yu⟩,
rcases metric.is_open_iff.1 u_open y yu with ⟨ε, εpos, hε⟩,
let δ := (ε/2) / ∥v∥,
have δpos : 0 < δ := div_pos (half_pos εpos) (lt_of_le_of_ne (norm_nonneg _) (ne.symm h)),
have : y + δ • v ∈ s,
{ apply us (hε _),
rw [metric.mem_ball, dist_eq_norm],
calc ∥(y + δ • v) - y ∥ = ∥δ • v∥ : by {congr' 1, abel }
... = ∥δ∥ * ∥v∥ : norm_smul _ _
... = δ * ∥v∥ : by simp only [norm, abs_of_nonneg (le_of_lt δpos)]
... = ε /2 : div_mul_cancel _ h
... < ε : half_lt_self εpos },
exact ⟨δ, δpos, this⟩ } },
rcases this with ⟨δ, δpos, hδ⟩,
refine ⟨y-x, _, (y + δ • v) - x, _, δ, δpos, by abel⟩,
exact mem_tangent_cone_of_segment_subset (convex_segment_iff.1 conv x y xs ys),
exact mem_tangent_cone_of_segment_subset (convex_segment_iff.1 conv x _ xs hδ) },
have B : ∀v:G, v ∈ submodule.span ℝ (tangent_cone_at ℝ s x),
{ assume v,
rcases A v with ⟨a, ha, b, hb, δ, hδ, h⟩,
have : v = δ⁻¹ • (b - a),
by { rw [← h, smul_smul, inv_mul_cancel, one_smul], exact (ne_of_gt hδ) },
rw this,
exact submodule.smul_mem _ _
(submodule.sub_mem _ (submodule.subset_span hb) (submodule.subset_span ha)) },
refine ⟨univ_subset_iff.1 (λv hv, subset_closure (B v)), subset_closure xs⟩
end
/-- The real interval `[0, 1]` is a set of unique differentiability. -/
lemma unique_diff_on_Icc_zero_one : unique_diff_on ℝ (Icc (0:ℝ) 1) :=
begin
apply unique_diff_on_convex (convex_Icc 0 1),
have : (1/(2:ℝ)) ∈ interior (Icc (0:ℝ) 1) :=
mem_interior.2 ⟨Ioo (0:ℝ) 1, Ioo_subset_Icc_self, is_open_Ioo, by norm_num, by norm_num⟩,
exact ne_empty_of_mem this,
end
end unique_diff
|
d1b04c6d67447d0703ec7fb276acff4390e84bd8 | bf532e3e865883a676110e756f800e0ddeb465be | /tests/wlog.lean | 3b9253108a6f9c608871051e2a852502b26f89a7 | [
"Apache-2.0"
] | permissive | aqjune/mathlib | da42a97d9e6670d2efaa7d2aa53ed3585dafc289 | f7977ff5a6bcf7e5c54eec908364ceb40dafc795 | refs/heads/master | 1,631,213,225,595 | 1,521,089,840,000 | 1,521,089,840,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,745 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import tactic
example {a b : Prop} (h₀ : a → b) (h₁ : a) : b :=
begin
apply_assumption,
apply_assumption,
end
example {a b : Prop} (h₀ : a → b) (h₁ : a) : b :=
by solve_by_elim
example {α : Type} {p : α → Prop} (h₀ : ∀ x, p x) (y : α) : p y :=
begin
apply_assumption,
end
section tauto₀
variables p q r : Prop
variables h : p ∧ q ∨ p ∧ r
include h
example : p ∧ p :=
by tauto
end tauto₀
section tauto₁
variables α : Type
variables p q r : α → Prop
variables h : (∃ x, p x ∧ q x) ∨ (∃ x, p x ∧ r x)
include h
example : ∃ x, p x :=
by tauto
end tauto₁
section tauto₂
variables α : Type
variables x : α
variables p q r : α → Prop
variables h₀ : (∀ x, p x → q x → r x) ∨ r x
variables h₁ : p x
variables h₂ : q x
include h₀ h₁ h₂
example : ∃ x, r x :=
by tauto
end tauto₂
example {x y : ℕ} :
x = 1 → false :=
begin
intros a,
wlog h : x = y,
{ guard_target x = y ∨ y = x,
admit },
{ guard_hyp h := x = y,
guard_hyp a := x = 1,
admit },
end
example {x y : ℕ} :
false :=
begin
wlog h : x ≤ y,
{ guard_hyp h := x ≤ y,
guard_target false,
admit },
end
example {x y z : ℕ} :
false :=
begin
wlog h : x ≤ y + z,
{ guard_target x ≤ y + z ∨ x ≤ z + y,
admit },
{ guard_hyp h := x ≤ y + z,
guard_target false,
admit },
end
example {x y z : ℕ} :
false :=
begin
wlog : x ≤ y + z using x y,
{ guard_target x ≤ y + z ∨ y ≤ x + z,
admit },
{ guard_hyp a := x ≤ y + z,
guard_target false,
admit },
end
|
9138f195c21a9e6fb4fa8d97a3954a380412288c | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/monoid_algebra/basic.lean | 2b974ff06455cd365d6b66424e5b7a890dfdfa4b | [
"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 | 64,625 | 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 G. Kudryashov, Scott Morrison
-/
import algebra.big_operators.finsupp
import algebra.hom.non_unital_alg
import algebra.module.big_operators
import linear_algebra.finsupp
/-!
# Monoid algebras
When the domain of a `finsupp` has a multiplicative or additive structure, we can define
a convolution product. To mathematicians this structure is known as the "monoid algebra",
i.e. the finite formal linear combinations over a given semiring of elements of the monoid.
The "group ring" ℤ[G] or the "group algebra" k[G] are typical uses.
In fact the construction of the "monoid algebra" makes sense when `G` is not even a monoid, but
merely a magma, i.e., when `G` carries a multiplication which is not required to satisfy any
conditions at all. In this case the construction yields a not-necessarily-unital,
not-necessarily-associative algebra but it is still adjoint to the forgetful functor from such
algebras to magmas, and we prove this as `monoid_algebra.lift_magma`.
In this file we define `monoid_algebra k G := G →₀ k`, and `add_monoid_algebra k G`
in the same way, and then define the convolution product on these.
When the domain is additive, this is used to define polynomials:
```
polynomial α := add_monoid_algebra ℕ α
mv_polynomial σ α := add_monoid_algebra (σ →₀ ℕ) α
```
When the domain is multiplicative, e.g. a group, this will be used to define the group ring.
## Implementation note
Unfortunately because additive and multiplicative structures both appear in both cases,
it doesn't appear to be possible to make much use of `to_additive`, and we just settle for
saying everything twice.
Similarly, I attempted to just define
`add_monoid_algebra k G := monoid_algebra k (multiplicative G)`, but the definitional equality
`multiplicative G = G` leaks through everywhere, and seems impossible to use.
-/
noncomputable theory
open_locale big_operators
open finset finsupp
universes u₁ u₂ u₃
variables (k : Type u₁) (G : Type u₂) {R : Type*}
/-! ### Multiplicative monoids -/
section
variables [semiring k]
/--
The monoid algebra over a semiring `k` generated by the monoid `G`.
It is the type of finite formal `k`-linear combinations of terms of `G`,
endowed with the convolution product.
-/
@[derive [inhabited, add_comm_monoid]]
def monoid_algebra : Type (max u₁ u₂) := G →₀ k
instance : has_coe_to_fun (monoid_algebra k G) (λ _, G → k) :=
finsupp.has_coe_to_fun
end
namespace monoid_algebra
variables {k G}
section
variables [semiring k] [non_unital_non_assoc_semiring R]
/-- A non-commutative version of `monoid_algebra.lift`: given a additive homomorphism `f : k →+ R`
and a homomorphism `g : G → R`, returns the additive homomorphism from
`monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f` is a ring homomorphism
and the range of either `f` or `g` is in center of `R`, then the result is a ring homomorphism. If
`R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra homomorphism called
`monoid_algebra.lift`. -/
def lift_nc (f : k →+ R) (g : G → R) : monoid_algebra k G →+ R :=
lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g x)).comp f)
@[simp] lemma lift_nc_single (f : k →+ R) (g : G → R) (a : G) (b : k) :
lift_nc f g (single a b) = f b * g a :=
lift_add_hom_apply_single _ _ _
end
section has_mul
variables [semiring k] [has_mul G]
/-- The product of `f g : monoid_algebra k G` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x * y = a`. (Think of the group ring of a group.) -/
instance : has_mul (monoid_algebra k G) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)⟩
lemma mul_def {f g : monoid_algebra k G} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) :=
rfl
instance : non_unital_non_assoc_semiring (monoid_algebra k G) :=
{ zero := 0,
mul := (*),
add := (+),
left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero,
single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add],
right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, zero_mul,
single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero,
sum_add],
zero_mul := assume f, by simp only [mul_def, sum_zero_index],
mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_zero],
.. finsupp.add_comm_monoid }
variables [semiring R]
lemma lift_nc_mul {g_hom : Type*} [mul_hom_class g_hom G R] (f : k →+* R) (g : g_hom)
(a b : monoid_algebra k G) (h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g y)) :
lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b :=
begin
conv_rhs { rw [← sum_single a, ← sum_single b] },
simp_rw [mul_def, (lift_nc _ g).map_finsupp_sum, lift_nc_single, finsupp.sum_mul,
finsupp.mul_sum],
refine finset.sum_congr rfl (λ y hy, finset.sum_congr rfl (λ x hx, _)),
simp [mul_assoc, (h_comm hy).left_comm]
end
end has_mul
section semigroup
variables [semiring k] [semigroup G] [semiring R]
instance : non_unital_semiring (monoid_algebra k G) :=
{ zero := 0,
mul := (*),
add := (+),
mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff,
add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add],
.. monoid_algebra.non_unital_non_assoc_semiring}
end semigroup
section has_one
variables [non_assoc_semiring R] [semiring k] [has_one G]
/-- The unit of the multiplication is `single 1 1`, i.e. the function
that is `1` at `1` and zero elsewhere. -/
instance : has_one (monoid_algebra k G) :=
⟨single 1 1⟩
lemma one_def : (1 : monoid_algebra k G) = single 1 1 :=
rfl
@[simp] lemma lift_nc_one {g_hom : Type*} [one_hom_class g_hom G R] (f : k →+* R) (g : g_hom) :
lift_nc (f : k →+ R) g 1 = 1 :=
by simp [one_def]
end has_one
section mul_one_class
variables [semiring k] [mul_one_class G]
instance : non_assoc_semiring (monoid_algebra k G) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
nat_cast := λ n, single 1 n,
nat_cast_zero := by simp [nat.cast],
nat_cast_succ := λ _, by simp [nat.cast]; refl,
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul,
single_zero, sum_zero, zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero,
single_zero, sum_zero, add_zero, mul_one, sum_single],
..monoid_algebra.non_unital_non_assoc_semiring }
lemma nat_cast_def (n : ℕ) : (n : monoid_algebra k G) = single 1 n := rfl
end mul_one_class
/-! #### Semiring structure -/
section semiring
variables [semiring k] [monoid G]
instance : semiring (monoid_algebra k G) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
.. monoid_algebra.non_unital_semiring,
.. monoid_algebra.non_assoc_semiring }
variables [semiring R]
/-- `lift_nc` as a `ring_hom`, for when `f x` and `g y` commute -/
def lift_nc_ring_hom (f : k →+* R) (g : G →* R) (h_comm : ∀ x y, commute (f x) (g y)) :
monoid_algebra k G →+* R :=
{ to_fun := lift_nc (f : k →+ R) g,
map_one' := lift_nc_one _ _,
map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _,
..(lift_nc (f : k →+ R) g)}
end semiring
instance [comm_semiring k] [comm_semigroup G] : non_unital_comm_semiring (monoid_algebra k G) :=
{ mul_comm := assume f g,
begin
simp only [mul_def, finsupp.sum, mul_comm],
rw [finset.sum_comm],
simp only [mul_comm]
end,
.. monoid_algebra.non_unital_semiring }
instance [semiring k] [nontrivial k] [nonempty G]: nontrivial (monoid_algebra k G) :=
finsupp.nontrivial
/-! #### Derived instances -/
section derived_instances
instance [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_algebra k G) :=
{ .. monoid_algebra.non_unital_comm_semiring,
.. monoid_algebra.semiring }
instance [semiring k] [subsingleton k] : unique (monoid_algebra k G) :=
finsupp.unique_of_right
instance [ring k] : add_comm_group (monoid_algebra k G) :=
finsupp.add_comm_group
instance [ring k] [has_mul G] : non_unital_non_assoc_ring (monoid_algebra k G) :=
{ .. monoid_algebra.add_comm_group,
.. monoid_algebra.non_unital_non_assoc_semiring }
instance [ring k] [semigroup G] : non_unital_ring (monoid_algebra k G) :=
{ .. monoid_algebra.add_comm_group,
.. monoid_algebra.non_unital_semiring }
instance [ring k] [mul_one_class G] : non_assoc_ring (monoid_algebra k G) :=
{ int_cast := λ z, single 1 (z : k),
int_cast_of_nat := λ n, by simpa,
int_cast_neg_succ_of_nat := λ n, by simpa,
.. monoid_algebra.add_comm_group,
.. monoid_algebra.non_assoc_semiring }
lemma int_cast_def [ring k] [mul_one_class G] (z : ℤ) : (z : monoid_algebra k G) = single 1 z := rfl
instance [ring k] [monoid G] : ring (monoid_algebra k G) :=
{ .. monoid_algebra.non_assoc_ring,
.. monoid_algebra.semiring }
instance [comm_ring k] [comm_semigroup G] : non_unital_comm_ring (monoid_algebra k G) :=
{ .. monoid_algebra.non_unital_comm_semiring,
.. monoid_algebra.non_unital_ring }
instance [comm_ring k] [comm_monoid G] : comm_ring (monoid_algebra k G) :=
{ .. monoid_algebra.non_unital_comm_ring,
.. monoid_algebra.ring }
variables {S : Type*}
instance [semiring k] [smul_zero_class R k] :
smul_zero_class R (monoid_algebra k G) :=
finsupp.smul_zero_class
instance [semiring k] [distrib_smul R k] :
distrib_smul R (monoid_algebra k G) :=
finsupp.distrib_smul _ _
instance [monoid R] [semiring k] [distrib_mul_action R k] :
distrib_mul_action R (monoid_algebra k G) :=
finsupp.distrib_mul_action G k
instance [semiring R] [semiring k] [module R k] :
module R (monoid_algebra k G) :=
finsupp.module G k
instance [monoid R] [semiring k] [distrib_mul_action R k] [has_faithful_smul R k] [nonempty G] :
has_faithful_smul R (monoid_algebra k G) :=
finsupp.has_faithful_smul
instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k]
[has_smul R S] [is_scalar_tower R S k] :
is_scalar_tower R S (monoid_algebra k G) :=
finsupp.is_scalar_tower G k
instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k]
[smul_comm_class R S k] :
smul_comm_class R S (monoid_algebra k G) :=
finsupp.smul_comm_class G k
instance [monoid R] [semiring k] [distrib_mul_action R k] [distrib_mul_action Rᵐᵒᵖ k]
[is_central_scalar R k] :
is_central_scalar R (monoid_algebra k G) :=
finsupp.is_central_scalar G k
/-- This is not an instance as it conflicts with `monoid_algebra.distrib_mul_action` when `G = kˣ`.
-/
def comap_distrib_mul_action_self [group G] [semiring k] :
distrib_mul_action G (monoid_algebra k G) :=
finsupp.comap_distrib_mul_action
end derived_instances
section misc_theorems
variables [semiring k]
local attribute [reducible] monoid_algebra
lemma mul_apply [decidable_eq G] [has_mul G] (f g : monoid_algebra k G) (x : G) :
(f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ * a₂ = x then b₁ * b₂ else 0) :=
begin
rw [mul_def],
simp only [finsupp.sum_apply, single_apply],
end
lemma mul_apply_antidiagonal [has_mul G] (f g : monoid_algebra k G) (x : G) (s : finset (G × G))
(hs : ∀ {p : G × G}, p ∈ s ↔ p.1 * p.2 = x) :
(f * g) x = ∑ p in s, (f p.1 * g p.2) :=
let F : G × G → k := λ p, by classical; exact if p.1 * p.2 = x then f p.1 * g p.2 else 0 in
calc (f * g) x = (∑ a₁ in f.support, ∑ a₂ in g.support, F (a₁, a₂)) :
mul_apply f g x
... = ∑ p in f.support ×ˢ g.support, F p : finset.sum_product.symm
... = ∑ p in (f.support ×ˢ g.support).filter (λ p : G × G, p.1 * p.2 = x), f p.1 * g p.2 :
(finset.sum_filter _ _).symm
... = ∑ p in s.filter (λ p : G × G, p.1 ∈ f.support ∧ p.2 ∈ g.support), f p.1 * g p.2 :
sum_congr (by { ext, simp only [mem_filter, mem_product, hs, and_comm] }) (λ _ _, rfl)
... = ∑ p in s, f p.1 * g p.2 : sum_subset (filter_subset _ _) $ λ p hps hp,
begin
simp only [mem_filter, mem_support_iff, not_and, not_not] at hp ⊢,
by_cases h1 : f p.1 = 0,
{ rw [h1, zero_mul] },
{ rw [hp hps h1, mul_zero] }
end
@[simp] lemma single_mul_single [has_mul G] {a₁ a₂ : G} {b₁ b₂ : k} :
(single a₁ b₁ : monoid_algebra k G) * single a₂ b₂ = single (a₁ * a₂) (b₁ * b₂) :=
(sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans
(sum_single_index (by rw [mul_zero, single_zero]))
@[simp] lemma single_pow [monoid G] {a : G} {b : k} :
∀ n : ℕ, (single a b : monoid_algebra k G)^n = single (a^n) (b ^ n)
| 0 := by { simp only [pow_zero], refl }
| (n+1) := by simp only [pow_succ, single_pow n, single_mul_single]
section
/-- Like `finsupp.map_domain_zero`, but for the `1` we define in this file -/
@[simp] lemma map_domain_one {α : Type*} {β : Type*} {α₂ : Type*}
[semiring β] [has_one α] [has_one α₂] {F : Type*} [one_hom_class F α α₂] (f : F) :
(map_domain f (1 : monoid_algebra β α) : monoid_algebra β α₂) = (1 : monoid_algebra β α₂) :=
by simp_rw [one_def, map_domain_single, map_one]
/-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/
lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_mul α] [has_mul α₂]
{F : Type*} [mul_hom_class F α α₂] (f : F) (x y : monoid_algebra β α) :
(map_domain f (x * y : monoid_algebra β α) : monoid_algebra β α₂) =
(map_domain f x * map_domain f y : monoid_algebra β α₂) :=
begin
simp_rw [mul_def, map_domain_sum, map_domain_single, map_mul],
rw finsupp.sum_map_domain_index,
{ congr,
ext a b,
rw finsupp.sum_map_domain_index,
{ simp },
{ simp [mul_add] } },
{ simp },
{ simp [add_mul] }
end
variables (k G)
/-- The embedding of a magma into its magma algebra. -/
@[simps] def of_magma [has_mul G] : G →ₙ* (monoid_algebra k G) :=
{ to_fun := λ a, single a 1,
map_mul' := λ a b, by simp only [mul_def, mul_one, sum_single_index, single_eq_zero, mul_zero], }
/-- The embedding of a unital magma into its magma algebra. -/
@[simps] def of [mul_one_class G] : G →* monoid_algebra k G :=
{ to_fun := λ a, single a 1,
map_one' := rfl,
.. of_magma k G }
end
lemma smul_of [mul_one_class G] (g : G) (r : k) :
r • (of k G g) = single g r := by simp
lemma of_injective [mul_one_class G] [nontrivial k] : function.injective (of k G) :=
λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h
/--
`finsupp.single` as a `monoid_hom` from the product type into the monoid algebra.
Note the order of the elements of the product are reversed compared to the arguments of
`finsupp.single`.
-/
@[simps] def single_hom [mul_one_class G] : k × G →* monoid_algebra k G :=
{ to_fun := λ a, single a.2 a.1,
map_one' := rfl,
map_mul' := λ a b, single_mul_single.symm }
lemma mul_single_apply_aux [has_mul G] (f : monoid_algebra k G) {r : k}
{x y z : G} (H : ∀ a, a * x = z ↔ a = y) :
(f * single x r) z = f y * r :=
by classical; exact
have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ * a₂ = z) (b₁ * b₂) 0) =
ite (a₁ * x = z) (b₁ * r) 0,
from λ a₁ b₁, sum_single_index $ by simp,
calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) :
by simp only [mul_apply, A, H]
... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _
... = f y * r : by split_ifs with h; simp at h; simp [h]
lemma mul_single_one_apply [mul_one_class G] (f : monoid_algebra k G) (r : k) (x : G) :
(f * single 1 r) x = f x * r :=
f.mul_single_apply_aux $ λ a, by rw [mul_one]
lemma single_mul_apply_aux [has_mul G] (f : monoid_algebra k G) {r : k} {x y z : G}
(H : ∀ a, x * a = y ↔ a = z) :
(single x r * f) y = r * f z :=
by classical; exact (
have f.sum (λ a b, ite (x * a = y) (0 * b) 0) = 0, by simp,
calc (single x r * f) y = sum f (λ a b, ite (x * a = y) (r * b) 0) :
(mul_apply _ _ _).trans $ sum_single_index (by exact this)
... = f.sum (λ a b, ite (a = z) (r * b) 0) : by simp only [H]
... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _
... = _ : by split_ifs with h; simp at h; simp [h])
lemma single_one_mul_apply [mul_one_class G] (f : monoid_algebra k G) (r : k) (x : G) :
(single 1 r * f) x = r * f x :=
f.single_mul_apply_aux $ λ a, by rw [one_mul]
lemma lift_nc_smul [mul_one_class G] {R : Type*} [semiring R] (f : k →+* R) (g : G →* R) (c : k)
(φ : monoid_algebra k G) :
lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ :=
begin
suffices : (lift_nc ↑f g).comp (smul_add_hom k (monoid_algebra k G) c) =
(add_monoid_hom.mul_left (f c)).comp (lift_nc ↑f g),
from add_monoid_hom.congr_fun this φ,
ext a b, simp [mul_assoc]
end
end misc_theorems
/-! #### Non-unital, non-associative algebra structure -/
section non_unital_non_assoc_algebra
variables (k) [semiring k] [distrib_smul R k] [has_mul G]
instance is_scalar_tower_self [is_scalar_tower R k k] :
is_scalar_tower R (monoid_algebra k G) (monoid_algebra k G) :=
⟨λ t a b,
begin
ext m,
classical,
simp only [mul_apply, finsupp.smul_sum, smul_ite, smul_mul_assoc, sum_smul_index', zero_mul,
if_t_t, implies_true_iff, eq_self_iff_true, sum_zero, coe_smul, smul_eq_mul, pi.smul_apply,
smul_zero],
end⟩
/-- Note that if `k` is a `comm_semiring` then we have `smul_comm_class k k k` and so we can take
`R = k` in the below. In other words, if the coefficients are commutative amongst themselves, they
also commute with the algebra multiplication. -/
instance smul_comm_class_self [smul_comm_class R k k] :
smul_comm_class R (monoid_algebra k G) (monoid_algebra k G) :=
⟨λ t a b,
begin
ext m,
simp only [mul_apply, finsupp.sum, finset.smul_sum, smul_ite, mul_smul_comm, sum_smul_index',
implies_true_iff, eq_self_iff_true, coe_smul, ite_eq_right_iff, smul_eq_mul, pi.smul_apply,
mul_zero, smul_zero],
end⟩
instance smul_comm_class_symm_self [smul_comm_class k R k] :
smul_comm_class (monoid_algebra k G) R (monoid_algebra k G) :=
⟨λ t a b, by { haveI := smul_comm_class.symm k R k, rw ← smul_comm, } ⟩
variables {A : Type u₃} [non_unital_non_assoc_semiring A]
/-- A non_unital `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its
values on the functions `single a 1`. -/
lemma non_unital_alg_hom_ext [distrib_mul_action k A]
{φ₁ φ₂ : monoid_algebra k G →ₙₐ[k] A}
(h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ :=
non_unital_alg_hom.to_distrib_mul_action_hom_injective $
finsupp.distrib_mul_action_hom_ext' $
λ a, distrib_mul_action_hom.ext_ring (h a)
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma non_unital_alg_hom_ext' [distrib_mul_action k A]
{φ₁ φ₂ : monoid_algebra k G →ₙₐ[k] A}
(h : φ₁.to_mul_hom.comp (of_magma k G) = φ₂.to_mul_hom.comp (of_magma k G)) : φ₁ = φ₂ :=
non_unital_alg_hom_ext k $ mul_hom.congr_fun h
/-- The functor `G ↦ monoid_algebra k G`, from the category of magmas to the category of non-unital,
non-associative algebras over `k` is adjoint to the forgetful functor in the other direction. -/
@[simps] def lift_magma [module k A] [is_scalar_tower k A A] [smul_comm_class k A A] :
(G →ₙ* A) ≃ (monoid_algebra k G →ₙₐ[k] A) :=
{ to_fun := λ f,
{ to_fun := λ a, a.sum (λ m t, t • f m),
map_smul' := λ t' a,
begin
rw [finsupp.smul_sum, sum_smul_index'],
{ simp_rw smul_assoc, },
{ intros m, exact zero_smul k (f m), },
end,
map_mul' := λ a₁ a₂,
begin
let g : G → k → A := λ m t, t • f m,
have h₁ : ∀ m, g m 0 = 0, { intros, exact zero_smul k (f m), },
have h₂ : ∀ m (t₁ t₂ : k), g m (t₁ + t₂) = g m t₁ + g m t₂, { intros, rw ← add_smul, },
simp_rw [finsupp.mul_sum, finsupp.sum_mul, smul_mul_smul, ← f.map_mul, mul_def,
sum_comm a₂ a₁, sum_sum_index h₁ h₂, sum_single_index (h₁ _)],
end,
.. lift_add_hom (λ x, (smul_add_hom k A).flip (f x)) },
inv_fun := λ F, F.to_mul_hom.comp (of_magma k G),
left_inv := λ f, by { ext m, simp only [non_unital_alg_hom.coe_mk, of_magma_apply,
non_unital_alg_hom.to_mul_hom_eq_coe, sum_single_index, function.comp_app, one_smul, zero_smul,
mul_hom.coe_comp, non_unital_alg_hom.coe_to_mul_hom], },
right_inv := λ F, by { ext m, simp only [non_unital_alg_hom.coe_mk, of_magma_apply,
non_unital_alg_hom.to_mul_hom_eq_coe, sum_single_index, function.comp_app, one_smul, zero_smul,
mul_hom.coe_comp, non_unital_alg_hom.coe_to_mul_hom], }, }
end non_unital_non_assoc_algebra
/-! #### Algebra structure -/
section algebra
local attribute [reducible] monoid_algebra
lemma single_one_comm [comm_semiring k] [mul_one_class G] (r : k) (f : monoid_algebra k G) :
single 1 r * f = f * single 1 r :=
by { ext, rw [single_one_mul_apply, mul_single_one_apply, mul_comm] }
/-- `finsupp.single 1` as a `ring_hom` -/
@[simps] def single_one_ring_hom [semiring k] [mul_one_class G] : k →+* monoid_algebra k G :=
{ map_one' := rfl,
map_mul' := λ x y, by rw [single_add_hom, single_mul_single, one_mul],
..finsupp.single_add_hom 1}
/-- If `f : G → H` is a multiplicative homomorphism between two monoids, then
`finsupp.map_domain f` is a ring homomorphism between their monoid algebras. -/
@[simps]
def map_domain_ring_hom (k : Type*) {H F : Type*} [semiring k] [monoid G] [monoid H]
[monoid_hom_class F G H] (f : F) :
monoid_algebra k G →+* monoid_algebra k H :=
{ map_one' := map_domain_one f,
map_mul' := λ x y, map_domain_mul f x y,
..(finsupp.map_domain.add_monoid_hom f : monoid_algebra k G →+ monoid_algebra k H) }
/-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1`
and `single 1 b`, then they are equal. -/
lemma ring_hom_ext {R} [semiring k] [mul_one_class G] [semiring R]
{f g : monoid_algebra k G →+* R} (h₁ : ∀ b, f (single 1 b) = g (single 1 b))
(h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g :=
ring_hom.coe_add_monoid_hom_injective $ add_hom_ext $ λ a b,
by rw [← one_mul a, ← mul_one b, ← single_mul_single, f.coe_add_monoid_hom,
g.coe_add_monoid_hom, f.map_mul, g.map_mul, h₁, h_of]
/-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1`
and `single 1 b`, then they are equal.
See note [partially-applied ext lemmas]. -/
@[ext] lemma ring_hom_ext' {R} [semiring k] [mul_one_class G] [semiring R]
{f g : monoid_algebra k G →+* R} (h₁ : f.comp single_one_ring_hom = g.comp single_one_ring_hom)
(h_of : (f : monoid_algebra k G →* R).comp (of k G) =
(g : monoid_algebra k G →* R).comp (of k G)) :
f = g :=
ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of)
/--
The instance `algebra k (monoid_algebra A G)` whenever we have `algebra k A`.
In particular this provides the instance `algebra k (monoid_algebra k G)`.
-/
instance {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] :
algebra k (monoid_algebra A G) :=
{ smul_def' := λ r a, by { ext, simp [single_one_mul_apply, algebra.smul_def, pi.smul_apply], },
commutes' := λ r f, by { ext, simp [single_one_mul_apply, mul_single_one_apply,
algebra.commutes], },
..single_one_ring_hom.comp (algebra_map k A) }
/-- `finsupp.single 1` as a `alg_hom` -/
@[simps]
def single_one_alg_hom {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] :
A →ₐ[k] monoid_algebra A G :=
{ commutes' := λ r, by { ext, simp, refl, }, ..single_one_ring_hom}
@[simp] lemma coe_algebra_map {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] :
⇑(algebra_map k (monoid_algebra A G)) = single 1 ∘ (algebra_map k A) :=
rfl
lemma single_eq_algebra_map_mul_of [comm_semiring k] [monoid G] (a : G) (b : k) :
single a b = algebra_map k (monoid_algebra k G) b * of k G a :=
by simp
lemma single_algebra_map_eq_algebra_map_mul_of {A : Type*} [comm_semiring k] [semiring A]
[algebra k A] [monoid G] (a : G) (b : k) :
single a (algebra_map k A b) = algebra_map k (monoid_algebra A G) b * of A G a :=
by simp
lemma induction_on [semiring k] [monoid G] {p : monoid_algebra k G → Prop} (f : monoid_algebra k G)
(hM : ∀ g, p (of k G g)) (hadd : ∀ f g : monoid_algebra k G, p f → p g → p (f + g))
(hsmul : ∀ (r : k) f, p f → p (r • f)) : p f :=
begin
refine finsupp.induction_linear f _ (λ f g hf hg, hadd f g hf hg) (λ g r, _),
{ simpa using hsmul 0 (of k G 1) (hM 1) },
{ convert hsmul r (of k G g) (hM g),
simp only [mul_one, smul_single', of_apply] },
end
end algebra
section lift
variables {k G} [comm_semiring k] [monoid G]
variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B]
/-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/
def lift_nc_alg_hom (f : A →ₐ[k] B) (g : G →* B) (h_comm : ∀ x y, commute (f x) (g y)) :
monoid_algebra A G →ₐ[k] B :=
{ to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm,
commutes' := by simp [lift_nc_ring_hom],
..(lift_nc_ring_hom (f : A →+* B) g h_comm)}
/-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its
values on the functions `single a 1`. -/
lemma alg_hom_ext ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄
(h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ :=
alg_hom.to_linear_map_injective $ finsupp.lhom_ext' $ λ a, linear_map.ext_ring (h a)
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄
(h : (φ₁ : monoid_algebra k G →* A).comp (of k G) =
(φ₂ : monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ :=
alg_hom_ext $ monoid_hom.congr_fun h
variables (k G A)
/-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism
`monoid_algebra k G →ₐ[k] A`. -/
def lift : (G →* A) ≃ (monoid_algebra k G →ₐ[k] A) :=
{ inv_fun := λ f, (f : monoid_algebra k G →* A).comp (of k G),
to_fun := λ F, lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _,
left_inv := λ f, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] },
right_inv := λ F, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] } }
variables {k G A}
lemma lift_apply' (F : G →* A) (f : monoid_algebra k G) :
lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F a) := rfl
lemma lift_apply (F : G →* A) (f : monoid_algebra k G) :
lift k G A F f = f.sum (λ a b, b • F a) :=
by simp only [lift_apply', algebra.smul_def]
lemma lift_def (F : G →* A) :
⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F :=
rfl
@[simp] lemma lift_symm_apply (F : monoid_algebra k G →ₐ[k] A) (x : G) :
(lift k G A).symm F x = F (single x 1) := rfl
lemma lift_of (F : G →* A) (x) :
lift k G A F (of k G x) = F x :=
by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply]
@[simp] lemma lift_single (F : G →* A) (a b) :
lift k G A F (single a b) = b • F a :=
by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom]
lemma lift_unique' (F : monoid_algebra k G →ₐ[k] A) :
F = lift k G A ((F : monoid_algebra k G →* A).comp (of k G)) :=
((lift k G A).apply_symm_apply F).symm
/-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by
its values on `F (single a 1)`. -/
lemma lift_unique (F : monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) :
F f = f.sum (λ a b, b • F (single a 1)) :=
by conv_lhs { rw lift_unique' F, simp [lift_apply] }
/-- If `f : G → H` is a homomorphism between two magmas, then
`finsupp.map_domain f` is a non-unital algebra homomorphism between their magma algebras. -/
@[simps]
def map_domain_non_unital_alg_hom (k A : Type*) [comm_semiring k] [semiring A] [algebra k A]
{G H F : Type*} [has_mul G] [has_mul H] [mul_hom_class F G H] (f : F) :
monoid_algebra A G →ₙₐ[k] monoid_algebra A H :=
{ map_mul' := λ x y, map_domain_mul f x y,
map_smul' := λ r x, map_domain_smul r x,
..(finsupp.map_domain.add_monoid_hom f : monoid_algebra A G →+ monoid_algebra A H) }
lemma map_domain_algebra_map (k A : Type*) {H F : Type*} [comm_semiring k] [semiring A]
[algebra k A] [monoid H] [monoid_hom_class F G H] (f : F) (r : k) :
map_domain f (algebra_map k (monoid_algebra A G) r) =
algebra_map k (monoid_algebra A H) r :=
by simp only [coe_algebra_map, map_domain_single, map_one]
/-- If `f : G → H` is a multiplicative homomorphism between two monoids, then
`finsupp.map_domain f` is an algebra homomorphism between their monoid algebras. -/
@[simps]
def map_domain_alg_hom (k A : Type*) [comm_semiring k] [semiring A] [algebra k A] {H F : Type*}
[monoid H] [monoid_hom_class F G H] (f : F) :
monoid_algebra A G →ₐ[k] monoid_algebra A H :=
{ commutes' := map_domain_algebra_map k A f,
..map_domain_ring_hom A f}
end lift
section
local attribute [reducible] monoid_algebra
variables (k)
/-- When `V` is a `k[G]`-module, multiplication by a group element `g` is a `k`-linear map. -/
def group_smul.linear_map [monoid G] [comm_semiring k]
(V : Type u₃) [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V]
[is_scalar_tower k (monoid_algebra k G) V] (g : G) :
V →ₗ[k] V :=
{ to_fun := λ v, (single g (1 : k) • v : V),
map_add' := λ x y, smul_add (single g (1 : k)) x y,
map_smul' := λ c x, smul_algebra_smul_comm _ _ _ }
@[simp]
lemma group_smul.linear_map_apply [monoid G] [comm_semiring k]
(V : Type u₃) [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V]
[is_scalar_tower k (monoid_algebra k G) V] (g : G) (v : V) :
(group_smul.linear_map k V g) v = (single g (1 : k) • v : V) :=
rfl
section
variables {k}
variables [monoid G] [comm_semiring k] {V W : Type u₃}
[add_comm_monoid V] [module k V] [module (monoid_algebra k G) V]
[is_scalar_tower k (monoid_algebra k G) V]
[add_comm_monoid W] [module k W] [module (monoid_algebra k G) W]
[is_scalar_tower k (monoid_algebra k G) W]
(f : V →ₗ[k] W)
(h : ∀ (g : G) (v : V), f (single g (1 : k) • v : V) = (single g (1 : k) • (f v) : W))
include h
/-- Build a `k[G]`-linear map from a `k`-linear map and evidence that it is `G`-equivariant. -/
def equivariant_of_linear_of_comm : V →ₗ[monoid_algebra k G] W :=
{ to_fun := f,
map_add' := λ v v', by simp,
map_smul' := λ c v,
begin
apply finsupp.induction c,
{ simp, },
{ intros g r c' nm nz w,
dsimp at *,
simp only [add_smul, f.map_add, w, add_left_inj, single_eq_algebra_map_mul_of, ← smul_smul],
erw [algebra_map_smul (monoid_algebra k G) r, algebra_map_smul (monoid_algebra k G) r,
f.map_smul, h g v, of_apply],
all_goals { apply_instance } }
end, }
@[simp]
lemma equivariant_of_linear_of_comm_apply (v : V) : (equivariant_of_linear_of_comm f h) v = f v :=
rfl
end
end
section
universe ui
variable {ι : Type ui}
local attribute [reducible] monoid_algebra
lemma prod_single [comm_semiring k] [comm_monoid G]
{s : finset ι} {a : ι → G} {b : ι → k} :
(∏ i in s, single (a i) (b i)) = single (∏ i in s, a i) (∏ i in s, b i) :=
finset.cons_induction_on s rfl $ λ a s has ih, by rw [prod_cons has, ih,
single_mul_single, prod_cons has, prod_cons has]
end
section -- We now prove some additional statements that hold for group algebras.
variables [semiring k] [group G]
local attribute [reducible] monoid_algebra
@[simp]
lemma mul_single_apply (f : monoid_algebra k G) (r : k) (x y : G) :
(f * single x r) y = f (y * x⁻¹) * r :=
f.mul_single_apply_aux $ λ a, eq_mul_inv_iff_mul_eq.symm
@[simp]
lemma single_mul_apply (r : k) (x : G) (f : monoid_algebra k G) (y : G) :
(single x r * f) y = r * f (x⁻¹ * y) :=
f.single_mul_apply_aux $ λ z, eq_inv_mul_iff_mul_eq.symm
lemma mul_apply_left (f g : monoid_algebra k G) (x : G) :
(f * g) x = (f.sum $ λ a b, b * (g (a⁻¹ * x))) :=
calc (f * g) x = sum f (λ a b, (single a b * g) x) :
by rw [← finsupp.sum_apply, ← finsupp.sum_mul, f.sum_single]
... = _ : by simp only [single_mul_apply, finsupp.sum]
-- If we'd assumed `comm_semiring`, we could deduce this from `mul_apply_left`.
lemma mul_apply_right (f g : monoid_algebra k G) (x : G) :
(f * g) x = (g.sum $ λa b, (f (x * a⁻¹)) * b) :=
calc (f * g) x = sum g (λ a b, (f * single a b) x) :
by rw [← finsupp.sum_apply, ← finsupp.mul_sum, g.sum_single]
... = _ : by simp only [mul_single_apply, finsupp.sum]
end
section opposite
open finsupp mul_opposite
variables [semiring k]
/-- The opposite of an `monoid_algebra R I` equivalent as a ring to
the `monoid_algebra Rᵐᵒᵖ Iᵐᵒᵖ` over the opposite ring, taking elements to their opposite. -/
@[simps {simp_rhs := tt}] protected noncomputable def op_ring_equiv [monoid G] :
(monoid_algebra k G)ᵐᵒᵖ ≃+* monoid_algebra kᵐᵒᵖ Gᵐᵒᵖ :=
{ map_mul' := begin
dsimp only [add_equiv.to_fun_eq_coe, ←add_equiv.coe_to_add_monoid_hom],
rw add_monoid_hom.map_mul_iff,
ext i₁ r₁ i₂ r₂ : 6,
simp
end,
..op_add_equiv.symm.trans $ (finsupp.map_range.add_equiv (op_add_equiv : k ≃+ kᵐᵒᵖ)).trans $
finsupp.dom_congr op_equiv }
@[simp] lemma op_ring_equiv_single [monoid G] (r : k) (x : G) :
monoid_algebra.op_ring_equiv (op (single x r)) = single (op x) (op r) :=
by simp
@[simp] lemma op_ring_equiv_symm_single [monoid G] (r : kᵐᵒᵖ) (x : Gᵐᵒᵖ) :
monoid_algebra.op_ring_equiv.symm (single x r) = op (single x.unop r.unop) :=
by simp
end opposite
section submodule
variables {k G} [comm_semiring k] [monoid G]
variables {V : Type*} [add_comm_monoid V]
variables [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V]
/-- A submodule over `k` which is stable under scalar multiplication by elements of `G` is a
submodule over `monoid_algebra k G` -/
def submodule_of_smul_mem (W : submodule k V) (h : ∀ (g : G) (v : V), v ∈ W → (of k G g) • v ∈ W) :
submodule (monoid_algebra k G) V :=
{ carrier := W,
zero_mem' := W.zero_mem',
add_mem' := λ _ _, W.add_mem',
smul_mem' := begin
intros f v hv,
rw [←finsupp.sum_single f, finsupp.sum, finset.sum_smul],
simp_rw [←smul_of, smul_assoc],
exact submodule.sum_smul_mem W _ (λ g _, h g v hv)
end }
end submodule
end monoid_algebra
/-! ### Additive monoids -/
section
variables [semiring k]
/--
The monoid algebra over a semiring `k` generated by the additive monoid `G`.
It is the type of finite formal `k`-linear combinations of terms of `G`,
endowed with the convolution product.
-/
@[derive [inhabited, add_comm_monoid]]
def add_monoid_algebra := G →₀ k
instance : has_coe_to_fun (add_monoid_algebra k G) (λ _, G → k) :=
finsupp.has_coe_to_fun
end
namespace add_monoid_algebra
variables {k G}
section
variables [semiring k] [non_unital_non_assoc_semiring R]
/-- A non-commutative version of `add_monoid_algebra.lift`: given a additive homomorphism `f : k →+
R` and a map `g : multiplicative G → R`, returns the additive
homomorphism from `add_monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f`
is a ring homomorphism and the range of either `f` or `g` is in center of `R`, then the result is a
ring homomorphism. If `R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra
homomorphism called `add_monoid_algebra.lift`. -/
def lift_nc (f : k →+ R) (g : multiplicative G → R) : add_monoid_algebra k G →+ R :=
lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g $ multiplicative.of_add x)).comp f)
@[simp] lemma lift_nc_single (f : k →+ R) (g : multiplicative G → R) (a : G) (b : k) :
lift_nc f g (single a b) = f b * g (multiplicative.of_add a) :=
lift_add_hom_apply_single _ _ _
end
section has_mul
variables [semiring k] [has_add G]
/-- The product of `f g : add_monoid_algebra k G` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x + y = a`. (Think of the product of multivariate
polynomials where `α` is the additive monoid of monomial exponents.) -/
instance : has_mul (add_monoid_algebra k G) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩
lemma mul_def {f g : add_monoid_algebra k G} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) :=
rfl
instance : non_unital_non_assoc_semiring (add_monoid_algebra k G) :=
{ zero := 0,
mul := (*),
add := (+),
left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero,
single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add],
right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul,
single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero,
sum_add],
zero_mul := assume f, by simp only [mul_def, sum_zero_index],
mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_zero],
nsmul := λ n f, n • f,
nsmul_zero' := by { intros, ext, simp [-nsmul_eq_mul, add_smul] },
nsmul_succ' := by { intros, ext, simp [-nsmul_eq_mul, nat.succ_eq_one_add, add_smul] },
.. finsupp.add_comm_monoid }
variables [semiring R]
lemma lift_nc_mul {g_hom : Type*} [mul_hom_class g_hom (multiplicative G) R] (f : k →+* R)
(g : g_hom) (a b : add_monoid_algebra k G)
(h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g $ multiplicative.of_add y)) :
lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b :=
(monoid_algebra.lift_nc_mul f g _ _ @h_comm : _)
end has_mul
section has_one
variables [semiring k] [has_zero G] [non_assoc_semiring R]
/-- The unit of the multiplication is `single 1 1`, i.e. the function
that is `1` at `0` and zero elsewhere. -/
instance : has_one (add_monoid_algebra k G) :=
⟨single 0 1⟩
lemma one_def : (1 : add_monoid_algebra k G) = single 0 1 :=
rfl
@[simp] lemma lift_nc_one {g_hom : Type*} [one_hom_class g_hom (multiplicative G) R]
(f : k →+* R) (g : g_hom) :
lift_nc (f : k →+ R) g 1 = 1 :=
(monoid_algebra.lift_nc_one f g : _)
end has_one
section semigroup
variables [semiring k] [add_semigroup G]
instance : non_unital_semiring (add_monoid_algebra k G) :=
{ zero := 0,
mul := (*),
add := (+),
mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff,
add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add],
.. add_monoid_algebra.non_unital_non_assoc_semiring }
end semigroup
section mul_one_class
variables [semiring k] [add_zero_class G]
instance : non_assoc_semiring (add_monoid_algebra k G) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
nat_cast := λ n, single 0 n,
nat_cast_zero := by simp [nat.cast],
nat_cast_succ := λ _, by simp [nat.cast]; refl,
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul,
single_zero, sum_zero, zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero,
single_zero, sum_zero, add_zero, mul_one, sum_single],
.. add_monoid_algebra.non_unital_non_assoc_semiring }
lemma nat_cast_def (n : ℕ) : (n : add_monoid_algebra k G) = single 0 n := rfl
end mul_one_class
/-! #### Semiring structure -/
section semiring
instance {R : Type*} [semiring k] [smul_zero_class R k] :
smul_zero_class R (add_monoid_algebra k G) :=
finsupp.smul_zero_class
variables [semiring k] [add_monoid G]
instance : semiring (add_monoid_algebra k G) :=
{ one := 1,
mul := (*),
zero := 0,
add := (+),
.. add_monoid_algebra.non_unital_semiring,
.. add_monoid_algebra.non_assoc_semiring, }
variables [semiring R]
/-- `lift_nc` as a `ring_hom`, for when `f` and `g` commute -/
def lift_nc_ring_hom (f : k →+* R) (g : multiplicative G →* R)
(h_comm : ∀ x y, commute (f x) (g y)) :
add_monoid_algebra k G →+* R :=
{ to_fun := lift_nc (f : k →+ R) g,
map_one' := lift_nc_one _ _,
map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _,
..(lift_nc (f : k →+ R) g)}
end semiring
instance [comm_semiring k] [add_comm_semigroup G] :
non_unital_comm_semiring (add_monoid_algebra k G) :=
{ mul_comm := @mul_comm (monoid_algebra k $ multiplicative G) _,
.. add_monoid_algebra.non_unital_semiring }
instance [semiring k] [nontrivial k] [nonempty G] : nontrivial (add_monoid_algebra k G) :=
finsupp.nontrivial
/-! #### Derived instances -/
section derived_instances
instance [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_algebra k G) :=
{ .. add_monoid_algebra.non_unital_comm_semiring,
.. add_monoid_algebra.semiring }
instance [semiring k] [subsingleton k] : unique (add_monoid_algebra k G) :=
finsupp.unique_of_right
instance [ring k] : add_comm_group (add_monoid_algebra k G) :=
finsupp.add_comm_group
instance [ring k] [has_add G] : non_unital_non_assoc_ring (add_monoid_algebra k G) :=
{ .. add_monoid_algebra.add_comm_group,
.. add_monoid_algebra.non_unital_non_assoc_semiring }
instance [ring k] [add_semigroup G] : non_unital_ring (add_monoid_algebra k G) :=
{ .. add_monoid_algebra.add_comm_group,
.. add_monoid_algebra.non_unital_semiring }
instance [ring k] [add_zero_class G] : non_assoc_ring (add_monoid_algebra k G) :=
{ int_cast := λ z, single 0 (z : k),
int_cast_of_nat := λ n, by simpa,
int_cast_neg_succ_of_nat := λ n, by simpa,
.. add_monoid_algebra.add_comm_group,
.. add_monoid_algebra.non_assoc_semiring }
lemma int_cast_def [ring k] [add_zero_class G] (z : ℤ) :
(z : add_monoid_algebra k G) = single 0 z := rfl
instance [ring k] [add_monoid G] : ring (add_monoid_algebra k G) :=
{ .. add_monoid_algebra.non_assoc_ring,
.. add_monoid_algebra.semiring }
instance [comm_ring k] [add_comm_semigroup G] : non_unital_comm_ring (add_monoid_algebra k G) :=
{ .. add_monoid_algebra.non_unital_comm_semiring,
.. add_monoid_algebra.non_unital_ring }
instance [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_algebra k G) :=
{ .. add_monoid_algebra.non_unital_comm_ring,
.. add_monoid_algebra.ring }
variables {S : Type*}
instance [monoid R] [semiring k] [distrib_mul_action R k] :
distrib_mul_action R (add_monoid_algebra k G) :=
finsupp.distrib_mul_action G k
instance [monoid R] [semiring k] [distrib_mul_action R k] [has_faithful_smul R k] [nonempty G] :
has_faithful_smul R (add_monoid_algebra k G) :=
finsupp.has_faithful_smul
instance [semiring R] [semiring k] [module R k] : module R (add_monoid_algebra k G) :=
finsupp.module G k
instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k]
[has_smul R S] [is_scalar_tower R S k] :
is_scalar_tower R S (add_monoid_algebra k G) :=
finsupp.is_scalar_tower G k
instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k]
[smul_comm_class R S k] :
smul_comm_class R S (add_monoid_algebra k G) :=
finsupp.smul_comm_class G k
instance [monoid R] [semiring k] [distrib_mul_action R k] [distrib_mul_action Rᵐᵒᵖ k]
[is_central_scalar R k] :
is_central_scalar R (add_monoid_algebra k G) :=
finsupp.is_central_scalar G k
/-! It is hard to state the equivalent of `distrib_mul_action G (add_monoid_algebra k G)`
because we've never discussed actions of additive groups. -/
end derived_instances
.
section misc_theorems
variables [semiring k]
lemma mul_apply [decidable_eq G] [has_add G] (f g : add_monoid_algebra k G) (x : G) :
(f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ + a₂ = x then b₁ * b₂ else 0) :=
@monoid_algebra.mul_apply k (multiplicative G) _ _ _ _ _ _
lemma mul_apply_antidiagonal [has_add G] (f g : add_monoid_algebra k G) (x : G) (s : finset (G × G))
(hs : ∀ {p : G × G}, p ∈ s ↔ p.1 + p.2 = x) :
(f * g) x = ∑ p in s, (f p.1 * g p.2) :=
@monoid_algebra.mul_apply_antidiagonal k (multiplicative G) _ _ _ _ _ s @hs
lemma single_mul_single [has_add G] {a₁ a₂ : G} {b₁ b₂ : k} :
(single a₁ b₁ * single a₂ b₂ : add_monoid_algebra k G) = single (a₁ + a₂) (b₁ * b₂) :=
@monoid_algebra.single_mul_single k (multiplicative G) _ _ _ _ _ _
-- This should be a `@[simp]` lemma, but the simp_nf linter times out if we add this.
-- Probably the correct fix is to make a `[add_]monoid_algebra.single` with the correct type,
-- instead of relying on `finsupp.single`.
lemma single_pow [add_monoid G] {a : G} {b : k} :
∀ n : ℕ, ((single a b)^n : add_monoid_algebra k G) = single (n • a) (b ^ n)
| 0 := by { simp only [pow_zero, zero_nsmul], refl }
| (n+1) :=
by rw [pow_succ, pow_succ, single_pow n, single_mul_single, add_comm, add_nsmul, one_nsmul]
/-- Like `finsupp.map_domain_zero`, but for the `1` we define in this file -/
@[simp] lemma map_domain_one {α : Type*} {β : Type*} {α₂ : Type*}
[semiring β] [has_zero α] [has_zero α₂] {F : Type*} [zero_hom_class F α α₂] (f : F) :
(map_domain f (1 : add_monoid_algebra β α) : add_monoid_algebra β α₂) =
(1 : add_monoid_algebra β α₂) :=
by simp_rw [one_def, map_domain_single, map_zero]
/-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/
lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_add α] [has_add α₂]
{F : Type*} [add_hom_class F α α₂] (f : F) (x y : add_monoid_algebra β α) :
(map_domain f (x * y : add_monoid_algebra β α) : add_monoid_algebra β α₂) =
(map_domain f x * map_domain f y : add_monoid_algebra β α₂) :=
begin
simp_rw [mul_def, map_domain_sum, map_domain_single, map_add],
rw finsupp.sum_map_domain_index,
{ congr,
ext a b,
rw finsupp.sum_map_domain_index,
{ simp },
{ simp [mul_add] } },
{ simp },
{ simp [add_mul] }
end
section
variables (k G)
/-- The embedding of an additive magma into its additive magma algebra. -/
@[simps] def of_magma [has_add G] : multiplicative G →ₙ* add_monoid_algebra k G :=
{ to_fun := λ a, single a 1,
map_mul' := λ a b, by simpa only [mul_def, mul_one, sum_single_index, single_eq_zero, mul_zero], }
/-- Embedding of a magma with zero into its magma algebra. -/
def of [add_zero_class G] : multiplicative G →* add_monoid_algebra k G :=
{ to_fun := λ a, single a 1,
map_one' := rfl,
.. of_magma k G }
/-- Embedding of a magma with zero `G`, into its magma algebra, having `G` as source. -/
def of' : G → add_monoid_algebra k G := λ a, single a 1
end
@[simp] lemma of_apply [add_zero_class G] (a : multiplicative G) : of k G a = single a.to_add 1 :=
rfl
@[simp] lemma of'_apply (a : G) : of' k G a = single a 1 := rfl
lemma of'_eq_of [add_zero_class G] (a : G) : of' k G a = of k G a := rfl
lemma of_injective [nontrivial k] [add_zero_class G] : function.injective (of k G) :=
λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h
/--
`finsupp.single` as a `monoid_hom` from the product type into the additive monoid algebra.
Note the order of the elements of the product are reversed compared to the arguments of
`finsupp.single`.
-/
@[simps] def single_hom [add_zero_class G] : k × multiplicative G →* add_monoid_algebra k G :=
{ to_fun := λ a, single a.2.to_add a.1,
map_one' := rfl,
map_mul' := λ a b, single_mul_single.symm }
lemma mul_single_apply_aux [has_add G] (f : add_monoid_algebra k G) (r : k)
(x y z : G) (H : ∀ a, a + x = z ↔ a = y) :
(f * single x r) z = f y * r :=
@monoid_algebra.mul_single_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H
lemma mul_single_zero_apply [add_zero_class G] (f : add_monoid_algebra k G) (r : k) (x : G) :
(f * single 0 r) x = f x * r :=
f.mul_single_apply_aux r _ _ _ $ λ a, by rw [add_zero]
lemma single_mul_apply_aux [has_add G] (f : add_monoid_algebra k G) (r : k) (x y z : G)
(H : ∀ a, x + a = y ↔ a = z) :
(single x r * f : add_monoid_algebra k G) y = r * f z :=
@monoid_algebra.single_mul_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H
lemma single_zero_mul_apply [add_zero_class G] (f : add_monoid_algebra k G) (r : k) (x : G) :
(single 0 r * f : add_monoid_algebra k G) x = r * f x :=
f.single_mul_apply_aux r _ _ _ $ λ a, by rw [zero_add]
lemma mul_single_apply [add_group G] (f : add_monoid_algebra k G) (r : k) (x y : G) :
(f * single x r) y = f (y - x) * r :=
(sub_eq_add_neg y x).symm ▸
@monoid_algebra.mul_single_apply k (multiplicative G) _ _ _ _ _ _
lemma single_mul_apply [add_group G] (r : k) (x : G) (f : add_monoid_algebra k G) (y : G) :
(single x r * f : add_monoid_algebra k G) y = r * f (- x + y) :=
@monoid_algebra.single_mul_apply k (multiplicative G) _ _ _ _ _ _
lemma lift_nc_smul {R : Type*} [add_zero_class G] [semiring R] (f : k →+* R)
(g : multiplicative G →* R) (c : k) (φ : monoid_algebra k G) :
lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ :=
@monoid_algebra.lift_nc_smul k (multiplicative G) _ _ _ _ f g c φ
lemma induction_on [add_monoid G] {p : add_monoid_algebra k G → Prop} (f : add_monoid_algebra k G)
(hM : ∀ g, p (of k G (multiplicative.of_add g)))
(hadd : ∀ f g : add_monoid_algebra k G, p f → p g → p (f + g))
(hsmul : ∀ (r : k) f, p f → p (r • f)) : p f :=
begin
refine finsupp.induction_linear f _ (λ f g hf hg, hadd f g hf hg) (λ g r, _),
{ simpa using hsmul 0 (of k G (multiplicative.of_add 0)) (hM 0) },
{ convert hsmul r (of k G (multiplicative.of_add g)) (hM g),
simp only [mul_one, to_add_of_add, smul_single', of_apply] },
end
/-- If `f : G → H` is an additive homomorphism between two additive monoids, then
`finsupp.map_domain f` is a ring homomorphism between their add monoid algebras. -/
@[simps]
def map_domain_ring_hom (k : Type*) [semiring k] {H F : Type*} [add_monoid G] [add_monoid H]
[add_monoid_hom_class F G H] (f : F) :
add_monoid_algebra k G →+* add_monoid_algebra k H :=
{ map_one' := map_domain_one f,
map_mul' := λ x y, map_domain_mul f x y,
..(finsupp.map_domain.add_monoid_hom f : monoid_algebra k G →+ monoid_algebra k H) }
end misc_theorems
end add_monoid_algebra
/-!
#### Conversions between `add_monoid_algebra` and `monoid_algebra`
We have not defined `add_monoid_algebra k G = monoid_algebra k (multiplicative G)`
because historically this caused problems;
since the changes that have made `nsmul` definitional, this would be possible,
but for now we just contruct the ring isomorphisms using `ring_equiv.refl _`.
-/
/-- The equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of
`multiplicative` -/
protected def add_monoid_algebra.to_multiplicative [semiring k] [has_add G] :
add_monoid_algebra k G ≃+* monoid_algebra k (multiplicative G) :=
{ to_fun := equiv_map_domain multiplicative.of_add,
map_mul' := λ x y, begin
repeat {rw equiv_map_domain_eq_map_domain},
dsimp [multiplicative.of_add],
convert monoid_algebra.map_domain_mul (mul_hom.id (multiplicative G)) _ _,
end,
..finsupp.dom_congr multiplicative.of_add }
/-- The equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of `additive` -/
protected def monoid_algebra.to_additive [semiring k] [has_mul G] :
monoid_algebra k G ≃+* add_monoid_algebra k (additive G) :=
{ to_fun := equiv_map_domain additive.of_mul,
map_mul' := λ x y, begin
repeat {rw equiv_map_domain_eq_map_domain},
dsimp [additive.of_mul],
convert monoid_algebra.map_domain_mul (mul_hom.id G) _ _,
end,
..finsupp.dom_congr additive.of_mul }
namespace add_monoid_algebra
variables {k G}
/-! #### Non-unital, non-associative algebra structure -/
section non_unital_non_assoc_algebra
variables (k) [semiring k] [distrib_smul R k] [has_add G]
instance is_scalar_tower_self [is_scalar_tower R k k] :
is_scalar_tower R (add_monoid_algebra k G) (add_monoid_algebra k G) :=
@monoid_algebra.is_scalar_tower_self k (multiplicative G) R _ _ _ _
/-- Note that if `k` is a `comm_semiring` then we have `smul_comm_class k k k` and so we can take
`R = k` in the below. In other words, if the coefficients are commutative amongst themselves, they
also commute with the algebra multiplication. -/
instance smul_comm_class_self [smul_comm_class R k k] :
smul_comm_class R (add_monoid_algebra k G) (add_monoid_algebra k G) :=
@monoid_algebra.smul_comm_class_self k (multiplicative G) R _ _ _ _
instance smul_comm_class_symm_self [smul_comm_class k R k] :
smul_comm_class (add_monoid_algebra k G) R (add_monoid_algebra k G) :=
@monoid_algebra.smul_comm_class_symm_self k (multiplicative G) R _ _ _ _
variables {A : Type u₃} [non_unital_non_assoc_semiring A]
/-- A non_unital `k`-algebra homomorphism from `add_monoid_algebra k G` is uniquely defined by its
values on the functions `single a 1`. -/
lemma non_unital_alg_hom_ext [distrib_mul_action k A]
{φ₁ φ₂ : add_monoid_algebra k G →ₙₐ[k] A}
(h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ :=
@monoid_algebra.non_unital_alg_hom_ext k (multiplicative G) _ _ _ _ _ φ₁ φ₂ h
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma non_unital_alg_hom_ext' [distrib_mul_action k A]
{φ₁ φ₂ : add_monoid_algebra k G →ₙₐ[k] A}
(h : φ₁.to_mul_hom.comp (of_magma k G) = φ₂.to_mul_hom.comp (of_magma k G)) : φ₁ = φ₂ :=
@monoid_algebra.non_unital_alg_hom_ext' k (multiplicative G) _ _ _ _ _ φ₁ φ₂ h
/-- The functor `G ↦ add_monoid_algebra k G`, from the category of magmas to the category of
non-unital, non-associative algebras over `k` is adjoint to the forgetful functor in the other
direction. -/
@[simps] def lift_magma [module k A] [is_scalar_tower k A A] [smul_comm_class k A A] :
(multiplicative G →ₙ* A) ≃ (add_monoid_algebra k G →ₙₐ[k] A) :=
{ to_fun := λ f, { to_fun := λ a, sum a (λ m t, t • f (multiplicative.of_add m)),
.. (monoid_algebra.lift_magma k f : _)},
inv_fun := λ F, F.to_mul_hom.comp (of_magma k G),
.. (monoid_algebra.lift_magma k : (multiplicative G →ₙ* A) ≃ (_ →ₙₐ[k] A)) }
end non_unital_non_assoc_algebra
/-! #### Algebra structure -/
section algebra
local attribute [reducible] add_monoid_algebra
/-- `finsupp.single 0` as a `ring_hom` -/
@[simps] def single_zero_ring_hom [semiring k] [add_monoid G] : k →+* add_monoid_algebra k G :=
{ map_one' := rfl,
map_mul' := λ x y, by rw [single_add_hom, single_mul_single, zero_add],
..finsupp.single_add_hom 0}
/-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1`
and `single 0 b`, then they are equal. -/
lemma ring_hom_ext {R} [semiring k] [add_monoid G] [semiring R]
{f g : add_monoid_algebra k G →+* R} (h₀ : ∀ b, f (single 0 b) = g (single 0 b))
(h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g :=
@monoid_algebra.ring_hom_ext k (multiplicative G) R _ _ _ _ _ h₀ h_of
/-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1`
and `single 0 b`, then they are equal.
See note [partially-applied ext lemmas]. -/
@[ext] lemma ring_hom_ext' {R} [semiring k] [add_monoid G] [semiring R]
{f g : add_monoid_algebra k G →+* R}
(h₁ : f.comp single_zero_ring_hom = g.comp single_zero_ring_hom)
(h_of : (f : add_monoid_algebra k G →* R).comp (of k G) =
(g : add_monoid_algebra k G →* R).comp (of k G)) :
f = g :=
ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of)
section opposite
open finsupp mul_opposite
variables [semiring k]
/-- The opposite of an `add_monoid_algebra R I` is ring equivalent to
the `add_monoid_algebra Rᵐᵒᵖ I` over the opposite ring, taking elements to their opposite. -/
@[simps {simp_rhs := tt}] protected noncomputable def op_ring_equiv [add_comm_monoid G] :
(add_monoid_algebra k G)ᵐᵒᵖ ≃+* add_monoid_algebra kᵐᵒᵖ G :=
{ map_mul' := begin
dsimp only [add_equiv.to_fun_eq_coe, ←add_equiv.coe_to_add_monoid_hom],
rw add_monoid_hom.map_mul_iff,
ext i r i' r' : 6,
dsimp,
simp only [map_range_single, single_mul_single, ←op_mul, add_comm]
end,
..mul_opposite.op_add_equiv.symm.trans
(finsupp.map_range.add_equiv (mul_opposite.op_add_equiv : k ≃+ kᵐᵒᵖ))}
@[simp] lemma op_ring_equiv_single [add_comm_monoid G] (r : k) (x : G) :
add_monoid_algebra.op_ring_equiv (op (single x r)) = single x (op r) :=
by simp
@[simp] lemma op_ring_equiv_symm_single [add_comm_monoid G] (r : kᵐᵒᵖ) (x : Gᵐᵒᵖ) :
add_monoid_algebra.op_ring_equiv.symm (single x r) = op (single x r.unop) :=
by simp
end opposite
/--
The instance `algebra R (add_monoid_algebra k G)` whenever we have `algebra R k`.
In particular this provides the instance `algebra k (add_monoid_algebra k G)`.
-/
instance [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] :
algebra R (add_monoid_algebra k G) :=
{ smul_def' := λ r a, by { ext, simp [single_zero_mul_apply, algebra.smul_def, pi.smul_apply], },
commutes' := λ r f, by { ext, simp [single_zero_mul_apply, mul_single_zero_apply,
algebra.commutes], },
..single_zero_ring_hom.comp (algebra_map R k) }
/-- `finsupp.single 0` as a `alg_hom` -/
@[simps] def single_zero_alg_hom [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] :
k →ₐ[R] add_monoid_algebra k G :=
{ commutes' := λ r, by { ext, simp, refl, }, ..single_zero_ring_hom}
@[simp] lemma coe_algebra_map [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] :
(algebra_map R (add_monoid_algebra k G) : R → add_monoid_algebra k G) =
single 0 ∘ (algebra_map R k) :=
rfl
end algebra
section lift
variables {k G} [comm_semiring k] [add_monoid G]
variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B]
/-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/
def lift_nc_alg_hom (f : A →ₐ[k] B) (g : multiplicative G →* B)
(h_comm : ∀ x y, commute (f x) (g y)) :
add_monoid_algebra A G →ₐ[k] B :=
{ to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm,
commutes' := by simp [lift_nc_ring_hom],
..(lift_nc_ring_hom (f : A →+* B) g h_comm)}
/-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its
values on the functions `single a 1`. -/
lemma alg_hom_ext ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄
(h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ :=
@monoid_algebra.alg_hom_ext k (multiplicative G) _ _ _ _ _ _ _ h
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄
(h : (φ₁ : add_monoid_algebra k G →* A).comp (of k G) =
(φ₂ : add_monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ :=
alg_hom_ext $ monoid_hom.congr_fun h
variables (k G A)
/-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism
`monoid_algebra k G →ₐ[k] A`. -/
def lift : (multiplicative G →* A) ≃ (add_monoid_algebra k G →ₐ[k] A) :=
{ inv_fun := λ f, (f : add_monoid_algebra k G →* A).comp (of k G),
to_fun := λ F,
{ to_fun := lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _,
.. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ F},
.. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ }
variables {k G A}
lemma lift_apply' (F : multiplicative G →* A) (f : monoid_algebra k G) :
lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F (multiplicative.of_add a)) := rfl
lemma lift_apply (F : multiplicative G →* A) (f : monoid_algebra k G) :
lift k G A F f = f.sum (λ a b, b • F (multiplicative.of_add a)) :=
by simp only [lift_apply', algebra.smul_def]
lemma lift_def (F : multiplicative G →* A) :
⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F :=
rfl
@[simp] lemma lift_symm_apply (F : add_monoid_algebra k G →ₐ[k] A) (x : multiplicative G) :
(lift k G A).symm F x = F (single x.to_add 1) := rfl
lemma lift_of (F : multiplicative G →* A) (x : multiplicative G) :
lift k G A F (of k G x) = F x :=
by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply]
@[simp] lemma lift_single (F : multiplicative G →* A) (a b) :
lift k G A F (single a b) = b • F (multiplicative.of_add a) :=
by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom]
lemma lift_unique' (F : add_monoid_algebra k G →ₐ[k] A) :
F = lift k G A ((F : add_monoid_algebra k G →* A).comp (of k G)) :=
((lift k G A).apply_symm_apply F).symm
/-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by
its values on `F (single a 1)`. -/
lemma lift_unique (F : add_monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) :
F f = f.sum (λ a b, b • F (single a 1)) :=
by conv_lhs { rw lift_unique' F, simp [lift_apply] }
lemma alg_hom_ext_iff {φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A} :
(∀ x, φ₁ (finsupp.single x 1) = φ₂ (finsupp.single x 1)) ↔ φ₁ = φ₂ :=
⟨λ h, alg_hom_ext h, by rintro rfl _; refl⟩
end lift
section
local attribute [reducible] add_monoid_algebra
universe ui
variable {ι : Type ui}
lemma prod_single [comm_semiring k] [add_comm_monoid G]
{s : finset ι} {a : ι → G} {b : ι → k} :
(∏ i in s, single (a i) (b i)) = single (∑ i in s, a i) (∏ i in s, b i) :=
finset.cons_induction_on s rfl $ λ a s has ih, by rw [prod_cons has, ih,
single_mul_single, sum_cons has, prod_cons has]
end
lemma map_domain_algebra_map {A H F : Type*} [comm_semiring k] [semiring A]
[algebra k A] [add_monoid G] [add_monoid H] [add_monoid_hom_class F G H] (f : F) (r : k) :
map_domain f (algebra_map k (add_monoid_algebra A G) r) =
algebra_map k (add_monoid_algebra A H) r :=
by simp only [function.comp_app, map_domain_single, add_monoid_algebra.coe_algebra_map, map_zero]
/-- If `f : G → H` is a homomorphism between two additive magmas, then `finsupp.map_domain f` is a
non-unital algebra homomorphism between their additive magma algebras. -/
@[simps]
def map_domain_non_unital_alg_hom (k A : Type*) [comm_semiring k] [semiring A] [algebra k A]
{G H F : Type*} [has_add G] [has_add H] [add_hom_class F G H] (f : F) :
add_monoid_algebra A G →ₙₐ[k] add_monoid_algebra A H :=
{ map_mul' := λ x y, map_domain_mul f x y,
map_smul' := λ r x, map_domain_smul r x,
..(finsupp.map_domain.add_monoid_hom f : monoid_algebra A G →+ monoid_algebra A H) }
/-- If `f : G → H` is an additive homomorphism between two additive monoids, then
`finsupp.map_domain f` is an algebra homomorphism between their add monoid algebras. -/
@[simps] def map_domain_alg_hom (k A : Type*) [comm_semiring k] [semiring A] [algebra k A]
[add_monoid G] {H F : Type*} [add_monoid H] [add_monoid_hom_class F G H] (f : F) :
add_monoid_algebra A G →ₐ[k] add_monoid_algebra A H :=
{ commutes' := map_domain_algebra_map f,
..map_domain_ring_hom A f}
end add_monoid_algebra
variables [comm_semiring R] (k G)
/-- The algebra equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of
`multiplicative`. -/
def add_monoid_algebra.to_multiplicative_alg_equiv [semiring k] [algebra R k] [add_monoid G] :
add_monoid_algebra k G ≃ₐ[R] monoid_algebra k (multiplicative G) :=
{ commutes' := λ r, by simp [add_monoid_algebra.to_multiplicative],
..add_monoid_algebra.to_multiplicative k G }
/-- The algebra equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of
`additive`. -/
def monoid_algebra.to_additive_alg_equiv [semiring k] [algebra R k] [monoid G] :
monoid_algebra k G ≃ₐ[R] add_monoid_algebra k (additive G) :=
{ commutes' := λ r, by simp [monoid_algebra.to_additive],
..monoid_algebra.to_additive k G }
|
a23c6bc1939889cba9954a194490d326cc95089c | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/data/set/basic.lean | 68a16d6150f63282949abf488e4c1a09299df92d | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 121,162 | 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
-/
import order.boolean_algebra
/-!
# Basic properties of sets
Sets in Lean are homogeneous; all their elements have the same type. Sets whose elements
have type `X` are thus defined as `set X := X → Prop`. Note that this function need not
be decidable. The definition is in the core library.
This file provides some basic definitions related to sets and functions not present in the core
library, as well as extra lemmas for functions in the core library (empty set, univ, union,
intersection, insert, singleton, set-theoretic difference, complement, and powerset).
Note that a set is a term, not a type. There is a coercion from `set α` to `Type*` sending
`s` to the corresponding subtype `↥s`.
See also the file `set_theory/zfc.lean`, which contains an encoding of ZFC set theory in Lean.
## Main definitions
Notation used here:
- `f : α → β` is a function,
- `s : set α` and `s₁ s₂ : set α` are subsets of `α`
- `t : set β` is a subset of `β`.
Definitions in the file:
* `nonempty s : Prop` : the predicate `s ≠ ∅`. Note that this is the preferred way to express the
fact that `s` has an element (see the Implementation Notes).
* `preimage f t : set α` : the preimage f⁻¹(t) (written `f ⁻¹' t` in Lean) of a subset of β.
* `subsingleton s : Prop` : the predicate saying that `s` has at most one element.
* `nontrivial s : Prop` : the predicate saying that `s` has at least two distinct elements.
* `range f : set β` : the image of `univ` under `f`.
Also works for `{p : Prop} (f : p → α)` (unlike `image`)
* `inclusion s₁ s₂ : ↥s₁ → ↥s₂` : the map `↥s₁ → ↥s₂` induced by an inclusion `s₁ ⊆ s₂`.
## Notation
* `f ⁻¹' t` for `preimage f t`
* `f '' s` for `image f s`
* `sᶜ` for the complement of `s`
## Implementation notes
* `s.nonempty` is to be preferred to `s ≠ ∅` or `∃ x, x ∈ s`. It has the advantage that
the `s.nonempty` dot notation can be used.
* For `s : set α`, do not use `subtype s`. Instead use `↥s` or `(s : Type*)` or `s`.
## Tags
set, sets, subset, subsets, image, preimage, pre-image, range, union, intersection, insert,
singleton, complement, powerset
-/
/-! ### Set coercion to a type -/
open function
universes u v w x
namespace set
variable {α : Type*}
instance : has_le (set α) := ⟨λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t⟩
instance : has_subset (set α) := ⟨(≤)⟩
instance {α : Type*} : boolean_algebra (set α) :=
{ sup := λ s t, {x | x ∈ s ∨ x ∈ t},
le := (≤),
lt := λ s t, s ⊆ t ∧ ¬t ⊆ s,
inf := λ s t, {x | x ∈ s ∧ x ∈ t},
bot := ∅,
compl := λ s, {x | x ∉ s},
top := univ,
sdiff := λ s t, {x | x ∈ s ∧ x ∉ t},
.. (infer_instance : boolean_algebra (α → Prop)) }
instance : has_ssubset (set α) := ⟨(<)⟩
instance : has_union (set α) := ⟨(⊔)⟩
instance : has_inter (set α) := ⟨(⊓)⟩
@[simp] lemma top_eq_univ : (⊤ : set α) = univ := rfl
@[simp] lemma bot_eq_empty : (⊥ : set α) = ∅ := rfl
@[simp] lemma sup_eq_union : ((⊔) : set α → set α → set α) = (∪) := rfl
@[simp] lemma inf_eq_inter : ((⊓) : set α → set α → set α) = (∩) := rfl
@[simp] lemma le_eq_subset : ((≤) : set α → set α → Prop) = (⊆) := rfl
@[simp] lemma lt_eq_ssubset : ((<) : set α → set α → Prop) = (⊂) := rfl
/-- Coercion from a set to the corresponding subtype. -/
instance {α : Type u} : has_coe_to_sort (set α) (Type u) := ⟨λ s, {x // x ∈ s}⟩
instance pi_set_coe.can_lift (ι : Type u) (α : Π i : ι, Type v) [ne : Π i, nonempty (α i)]
(s : set ι) :
can_lift (Π i : s, α i) (Π i, α i) :=
{ coe := λ f i, f i,
.. pi_subtype.can_lift ι α s }
instance pi_set_coe.can_lift' (ι : Type u) (α : Type v) [ne : nonempty α] (s : set ι) :
can_lift (s → α) (ι → α) :=
pi_set_coe.can_lift ι (λ _, α) s
end set
section set_coe
variables {α : Type u}
theorem set.coe_eq_subtype (s : set α) : ↥s = {x // x ∈ s} := rfl
@[simp] theorem set.coe_set_of (p : α → Prop) : ↥{x | p x} = {x // p x} := rfl
@[simp] theorem set_coe.forall {s : set α} {p : s → Prop} :
(∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) :=
subtype.forall
@[simp] theorem set_coe.exists {s : set α} {p : s → Prop} :
(∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) :=
subtype.exists
theorem set_coe.exists' {s : set α} {p : Π x, x ∈ s → Prop} :
(∃ x (h : x ∈ s), p x h) ↔ (∃ x : s, p x x.2) :=
(@set_coe.exists _ _ $ λ x, p x.1 x.2).symm
theorem set_coe.forall' {s : set α} {p : Π x, x ∈ s → Prop} :
(∀ x (h : x ∈ s), p x h) ↔ (∀ x : s, p x x.2) :=
(@set_coe.forall _ _ $ λ x, p x.1 x.2).symm
@[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : ↥s = ↥t) (x : s),
cast H x = ⟨x.1, H' ▸ x.2⟩
| s _ rfl _ ⟨x, h⟩ := rfl
theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b :=
subtype.eq
theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b :=
iff.intro set_coe.ext (assume h, h ▸ rfl)
end set_coe
/-- See also `subtype.prop` -/
lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.prop
/-- Duplicate of `eq.subset'`, which currently has elaboration problems. -/
lemma eq.subset {α} {s t : set α} : s = t → s ⊆ t :=
by { rintro rfl x hx, exact hx }
namespace set
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a b : α} {s t u : set α}
instance : inhabited (set α) := ⟨∅⟩
@[ext]
theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b :=
funext (assume x, propext (h x))
theorem ext_iff {s t : set α} : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t :=
⟨λ h x, by rw h, ext⟩
@[trans] theorem mem_of_mem_of_subset {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx
lemma forall_in_swap {p : α → β → Prop} :
(∀ (a ∈ s) b, p a b) ↔ ∀ b (a ∈ s), p a b :=
by tauto
/-! ### Lemmas about `mem` and `set_of` -/
lemma mem_set_of {a : α} {p : α → Prop} : a ∈ {x | p x} ↔ p a := iff.rfl
/-- If `h : a ∈ {x | p x}` then `h.out : p x`. These are definitionally equal, but this can
nevertheless be useful for various reasons, e.g. to apply further projection notation or in an
argument to `simp`. -/
lemma _root_.has_mem.mem.out {p : α → Prop} {a : α} (h : a ∈ {x | p x}) : p a := h
theorem nmem_set_of_eq {a : α} {p : α → Prop} : a ∉ {x | p x} = ¬ p a := rfl
@[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl
theorem set_of_set {s : set α} : set_of s = s := rfl
lemma set_of_app_iff {p : α → Prop} {x : α} : {x | p x} x ↔ p x := iff.rfl
theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl
lemma set_of_bijective : bijective (set_of : (α → Prop) → set α) := bijective_id
@[simp] theorem set_of_subset_set_of {p q : α → Prop} :
{a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl
@[simp] lemma sep_set_of {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl
lemma set_of_and {p q : α → Prop} : {a | p a ∧ q a} = {a | p a} ∩ {a | q a} := rfl
lemma set_of_or {p q : α → Prop} : {a | p a ∨ q a} = {a | p a} ∪ {a | q a} := rfl
/-! ### Subset and strict subset relations -/
instance : is_refl (set α) (⊆) := has_le.le.is_refl
instance : is_trans (set α) (⊆) := has_le.le.is_trans
instance : is_antisymm (set α) (⊆) := has_le.le.is_antisymm
instance : is_irrefl (set α) (⊂) := has_lt.lt.is_irrefl
instance : is_trans (set α) (⊂) := has_lt.lt.is_trans
instance : is_asymm (set α) (⊂) := has_lt.lt.is_asymm
instance : is_nonstrict_strict_order (set α) (⊆) (⊂) := ⟨λ _ _, iff.rfl⟩
-- TODO(Jeremy): write a tactic to unfold specific instances of generic notation?
lemma subset_def : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl
lemma ssubset_def : s ⊂ t = (s ⊆ t ∧ ¬ t ⊆ s) := rfl
@[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id
theorem subset.rfl {s : set α} : s ⊆ s := subset.refl s
@[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := λ x h, bc $ ab h
@[trans] theorem mem_of_eq_of_mem {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s :=
hx.symm ▸ h
theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b :=
set.ext $ λ x, ⟨@h₁ _, @h₂ _⟩
theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a :=
⟨λ e, ⟨e.subset, e.symm.subset⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩
-- an alternative name
theorem eq_of_subset_of_subset {a b : set α} : a ⊆ b → b ⊆ a → a = b := subset.antisymm
theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} (h : s₁ ⊆ s₂) : a ∈ s₁ → a ∈ s₂ := @h _
theorem not_mem_subset (h : s ⊆ t) : a ∉ t → a ∉ s :=
mt $ mem_of_subset_of_mem h
theorem not_subset : (¬ s ⊆ t) ↔ ∃a ∈ s, a ∉ t := by simp only [subset_def, not_forall]
/-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/
protected theorem eq_or_ssubset_of_subset (h : s ⊆ t) : s = t ∨ s ⊂ t :=
eq_or_lt_of_le h
lemma exists_of_ssubset {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) :=
not_subset.1 h.2
protected lemma ssubset_iff_subset_ne {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t :=
@lt_iff_le_and_ne (set α) _ s t
lemma ssubset_iff_of_subset {s t : set α} (h : s ⊆ t) : s ⊂ t ↔ ∃ x ∈ t, x ∉ s :=
⟨exists_of_ssubset, λ ⟨x, hxt, hxs⟩, ⟨h, λ h, hxs $ h hxt⟩⟩
protected lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊂ s₂)
(hs₂s₃ : s₂ ⊆ s₃) :
s₁ ⊂ s₃ :=
⟨subset.trans hs₁s₂.1 hs₂s₃, λ hs₃s₁, hs₁s₂.2 (subset.trans hs₂s₃ hs₃s₁)⟩
protected lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊆ s₂)
(hs₂s₃ : s₂ ⊂ s₃) :
s₁ ⊂ s₃ :=
⟨subset.trans hs₁s₂ hs₂s₃.1, λ hs₃s₁, hs₂s₃.2 (subset.trans hs₃s₁ hs₁s₂)⟩
theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := id
@[simp] theorem not_not_mem : ¬ (a ∉ s) ↔ a ∈ s := not_not
/-! ### Non-empty sets -/
/-- The property `s.nonempty` expresses the fact that the set `s` is not empty. It should be used
in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks
to the dot notation. -/
protected def nonempty (s : set α) : Prop := ∃ x, x ∈ s
@[simp] lemma nonempty_coe_sort {s : set α} : nonempty ↥s ↔ s.nonempty := nonempty_subtype
lemma nonempty_def : s.nonempty ↔ ∃ x, x ∈ s := iff.rfl
lemma nonempty_of_mem {x} (h : x ∈ s) : s.nonempty := ⟨x, h⟩
theorem nonempty.not_subset_empty : s.nonempty → ¬(s ⊆ ∅)
| ⟨x, hx⟩ hs := hs hx
theorem nonempty.ne_empty : ∀ {s : set α}, s.nonempty → s ≠ ∅
| _ ⟨x, hx⟩ rfl := hx
@[simp] theorem not_nonempty_empty : ¬(∅ : set α).nonempty :=
λ h, h.ne_empty rfl
/-- Extract a witness from `s.nonempty`. This function might be used instead of case analysis
on the argument. Note that it makes a proof depend on the `classical.choice` axiom. -/
protected noncomputable def nonempty.some (h : s.nonempty) : α := classical.some h
protected lemma nonempty.some_mem (h : s.nonempty) : h.some ∈ s := classical.some_spec h
lemma nonempty.mono (ht : s ⊆ t) (hs : s.nonempty) : t.nonempty := hs.imp ht
lemma nonempty_of_not_subset (h : ¬s ⊆ t) : (s \ t).nonempty :=
let ⟨x, xs, xt⟩ := not_subset.1 h in ⟨x, xs, xt⟩
lemma nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).nonempty :=
nonempty_of_not_subset ht.2
lemma nonempty.of_diff (h : (s \ t).nonempty) : s.nonempty := h.imp $ λ _, and.left
lemma nonempty_of_ssubset' (ht : s ⊂ t) : t.nonempty := (nonempty_of_ssubset ht).of_diff
lemma nonempty.inl (hs : s.nonempty) : (s ∪ t).nonempty := hs.imp $ λ _, or.inl
lemma nonempty.inr (ht : t.nonempty) : (s ∪ t).nonempty := ht.imp $ λ _, or.inr
@[simp] lemma union_nonempty : (s ∪ t).nonempty ↔ s.nonempty ∨ t.nonempty := exists_or_distrib
lemma nonempty.left (h : (s ∩ t).nonempty) : s.nonempty := h.imp $ λ _, and.left
lemma nonempty.right (h : (s ∩ t).nonempty) : t.nonempty := h.imp $ λ _, and.right
lemma inter_nonempty : (s ∩ t).nonempty ↔ ∃ x, x ∈ s ∧ x ∈ t := iff.rfl
lemma inter_nonempty_iff_exists_left : (s ∩ t).nonempty ↔ ∃ x ∈ s, x ∈ t :=
by simp_rw [inter_nonempty, exists_prop]
lemma inter_nonempty_iff_exists_right : (s ∩ t).nonempty ↔ ∃ x ∈ t, x ∈ s :=
by simp_rw [inter_nonempty, exists_prop, and_comm]
lemma nonempty_iff_univ_nonempty : nonempty α ↔ (univ : set α).nonempty :=
⟨λ ⟨x⟩, ⟨x, trivial⟩, λ ⟨x, _⟩, ⟨x⟩⟩
@[simp] lemma univ_nonempty : ∀ [h : nonempty α], (univ : set α).nonempty
| ⟨x⟩ := ⟨x, trivial⟩
lemma nonempty.to_subtype (h : s.nonempty) : nonempty s :=
nonempty_subtype.2 h
instance [nonempty α] : nonempty (set.univ : set α) := set.univ_nonempty.to_subtype
lemma nonempty_of_nonempty_subtype [nonempty s] : s.nonempty :=
nonempty_subtype.mp ‹_›
/-! ### Lemmas about the empty set -/
theorem empty_def : (∅ : set α) = {x | false} := rfl
@[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl
@[simp] theorem set_of_false : {a : α | false} = ∅ := rfl
@[simp] theorem empty_subset (s : set α) : ∅ ⊆ s.
theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ :=
(subset.antisymm_iff.trans $ and_iff_left (empty_subset _)).symm
theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := subset_empty_iff.symm
lemma eq_empty_of_forall_not_mem (h : ∀ x, x ∉ s) : s = ∅ := subset_empty_iff.1 h
theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1
theorem eq_empty_of_is_empty [is_empty α] (s : set α) : s = ∅ :=
eq_empty_of_subset_empty $ λ x hx, is_empty_elim x
/-- There is exactly one set of a type that is empty. -/
instance unique_empty [is_empty α] : unique (set α) :=
{ default := ∅, uniq := eq_empty_of_is_empty }
lemma not_nonempty_iff_eq_empty {s : set α} : ¬s.nonempty ↔ s = ∅ :=
by simp only [set.nonempty, eq_empty_iff_forall_not_mem, not_exists]
lemma empty_not_nonempty : ¬(∅ : set α).nonempty := λ h, h.ne_empty rfl
theorem ne_empty_iff_nonempty : s ≠ ∅ ↔ s.nonempty := not_iff_comm.1 not_nonempty_iff_eq_empty
@[simp] lemma is_empty_coe_sort {s : set α} : is_empty ↥s ↔ s = ∅ :=
not_iff_not.1 $ by simpa using ne_empty_iff_nonempty.symm
lemma eq_empty_or_nonempty (s : set α) : s = ∅ ∨ s.nonempty :=
or_iff_not_imp_left.2 ne_empty_iff_nonempty.1
theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ :=
subset_empty_iff.1 $ e ▸ h
theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true :=
iff_true_intro $ λ x, false.elim
instance (α : Type u) : is_empty.{u+1} (∅ : set α) :=
⟨λ x, x.2⟩
@[simp] lemma empty_ssubset : ∅ ⊂ s ↔ s.nonempty :=
(@bot_lt_iff_ne_bot (set α) _ _ _).trans ne_empty_iff_nonempty
/-!
### Universal set.
In Lean `@univ α` (or `univ : set α`) is the set that contains all elements of type `α`.
Mathematically it is the same as `α` but it has a different type.
-/
@[simp] theorem set_of_true : {x : α | true} = univ := rfl
@[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial
@[simp] lemma univ_eq_empty_iff : (univ : set α) = ∅ ↔ is_empty α :=
eq_empty_iff_forall_not_mem.trans ⟨λ H, ⟨λ x, H x trivial⟩, λ H x _, @is_empty.false α H x⟩
theorem empty_ne_univ [nonempty α] : (∅ : set α) ≠ univ :=
λ e, not_is_empty_of_nonempty α $ univ_eq_empty_iff.1 e.symm
@[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial
theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ :=
(subset.antisymm_iff.trans $ and_iff_right (subset_univ _)).symm
theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1
theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s :=
univ_subset_iff.symm.trans $ forall_congr $ λ x, imp_iff_right ⟨⟩
theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2
lemma eq_univ_of_subset {s t : set α} (h : s ⊆ t) (hs : s = univ) : t = univ :=
eq_univ_of_univ_subset $ hs ▸ h
lemma exists_mem_of_nonempty (α) : ∀ [nonempty α], ∃x:α, x ∈ (univ : set α)
| ⟨x⟩ := ⟨x, trivial⟩
lemma ne_univ_iff_exists_not_mem {α : Type*} (s : set α) : s ≠ univ ↔ ∃ a, a ∉ s :=
by rw [←not_forall, ←eq_univ_iff_forall]
lemma not_subset_iff_exists_mem_not_mem {α : Type*} {s t : set α} :
¬ s ⊆ t ↔ ∃ x, x ∈ s ∧ x ∉ t :=
by simp [subset_def]
lemma univ_unique [unique α] : @set.univ α = {default} :=
set.ext $ λ x, iff_of_true trivial $ subsingleton.elim x default
instance nontrivial_of_nonempty [nonempty α] : nontrivial (set α) := ⟨⟨∅, univ, empty_ne_univ⟩⟩
/-! ### Lemmas about union -/
theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl
theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl
theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr
theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H
theorem mem_union.elim {x : α} {a b : set α} {P : Prop}
(H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P :=
or.elim H₁ H₂ H₃
theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl
@[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl
@[simp] theorem union_self (a : set α) : a ∪ a = a := ext $ λ x, or_self _
@[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext $ λ x, or_false _
@[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext $ λ x, false_or _
theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext $ λ x, or.comm
theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext $ λ x, or.assoc
instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩
instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩
theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) :=
ext $ λ x, or.left_comm
theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ :=
ext $ λ x, or.right_comm
@[simp] theorem union_eq_left_iff_subset {s t : set α} : s ∪ t = s ↔ t ⊆ s :=
sup_eq_left
@[simp] theorem union_eq_right_iff_subset {s t : set α} : s ∪ t = t ↔ s ⊆ t :=
sup_eq_right
theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t :=
union_eq_right_iff_subset.mpr h
theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s :=
union_eq_left_iff_subset.mpr h
@[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl
@[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr
theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r :=
λ x, or.rec (@sr _) (@tr _)
@[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u :=
(forall_congr (by exact λ x, or_imp_distrib)).trans forall_and_distrib
theorem union_subset_union {s₁ s₂ t₁ t₂ : set α}
(h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := λ x, or.imp (@h₁ _) (@h₂ _)
theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t :=
union_subset_union h subset.rfl
theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ :=
union_subset_union subset.rfl h
lemma subset_union_of_subset_left {s t : set α} (h : s ⊆ t) (u : set α) : s ⊆ t ∪ u :=
subset.trans h (subset_union_left t u)
lemma subset_union_of_subset_right {s u : set α} (h : s ⊆ u) (t : set α) : s ⊆ t ∪ u :=
subset.trans h (subset_union_right t u)
lemma union_congr_left (ht : t ⊆ s ∪ u) (hu : u ⊆ s ∪ t) : s ∪ t = s ⊔ u := sup_congr_left ht hu
lemma union_congr_right (hs : s ⊆ t ∪ u) (ht : t ⊆ s ∪ u) : s ∪ u = t ∪ u := sup_congr_right hs ht
lemma union_eq_union_iff_left : s ∪ t = s ∪ u ↔ t ⊆ s ∪ u ∧ u ⊆ s ∪ t := sup_eq_sup_iff_left
lemma union_eq_union_iff_right : s ∪ u = t ∪ u ↔ s ⊆ t ∪ u ∧ t ⊆ s ∪ u := sup_eq_sup_iff_right
@[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ :=
by simp only [← subset_empty_iff]; exact union_subset_iff
@[simp] lemma union_univ {s : set α} : s ∪ univ = univ := sup_top_eq
@[simp] lemma univ_union {s : set α} : univ ∪ s = univ := top_sup_eq
/-! ### Lemmas about intersection -/
theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl
theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl
@[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl
theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩
theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left
theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right
@[simp] theorem inter_self (a : set α) : a ∩ a = a := ext $ λ x, and_self _
@[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext $ λ x, and_false _
@[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext $ λ x, false_and _
theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext $ λ x, and.comm
theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext $ λ x, and.assoc
instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩
instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩
theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
ext $ λ x, and.left_comm
theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ :=
ext $ λ x, and.right_comm
@[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x, and.left
@[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x, and.right
theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := λ x h, ⟨rs h, rt h⟩
@[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t :=
(forall_congr (by exact λ x, imp_and_distrib)).trans forall_and_distrib
@[simp] theorem inter_eq_left_iff_subset {s t : set α} : s ∩ t = s ↔ s ⊆ t :=
inf_eq_left
@[simp] theorem inter_eq_right_iff_subset {s t : set α} : s ∩ t = t ↔ t ⊆ s :=
inf_eq_right
theorem inter_eq_self_of_subset_left {s t : set α} : s ⊆ t → s ∩ t = s :=
inter_eq_left_iff_subset.mpr
theorem inter_eq_self_of_subset_right {s t : set α} : t ⊆ s → s ∩ t = t :=
inter_eq_right_iff_subset.mpr
lemma inter_congr_left (ht : s ∩ u ⊆ t) (hu : s ∩ t ⊆ u) : s ∩ t = s ∩ u := inf_congr_left ht hu
lemma inter_congr_right (hs : t ∩ u ⊆ s) (ht : s ∩ u ⊆ t) : s ∩ u = t ∩ u := inf_congr_right hs ht
lemma inter_eq_inter_iff_left : s ∩ t = s ∩ u ↔ s ∩ u ⊆ t ∧ s ∩ t ⊆ u := inf_eq_inf_iff_left
lemma inter_eq_inter_iff_right : s ∩ u = t ∩ u ↔ t ∩ u ⊆ s ∧ s ∩ u ⊆ t := inf_eq_inf_iff_right
@[simp] theorem inter_univ (a : set α) : a ∩ univ = a := inf_top_eq
@[simp] theorem univ_inter (a : set α) : univ ∩ a = a := top_inf_eq
theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α}
(h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := λ x, and.imp (@h₁ _) (@h₂ _)
theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u :=
inter_subset_inter H subset.rfl
theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t :=
inter_subset_inter subset.rfl H
theorem union_inter_cancel_left {s t : set α} : (s ∪ t) ∩ s = s :=
inter_eq_self_of_subset_right $ subset_union_left _ _
theorem union_inter_cancel_right {s t : set α} : (s ∪ t) ∩ t = t :=
inter_eq_self_of_subset_right $ subset_union_right _ _
/-! ### Distributivity laws -/
theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) :=
inf_sup_left
theorem inter_union_distrib_left {s t u : set α} : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) :=
inf_sup_left
theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) :=
inf_sup_right
theorem union_inter_distrib_right {s t u : set α} : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) :=
inf_sup_right
theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) :=
sup_inf_left
theorem union_inter_distrib_left {s t u : set α} : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) :=
sup_inf_left
theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) :=
sup_inf_right
theorem inter_union_distrib_right {s t u : set α} : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) :=
sup_inf_right
lemma union_union_distrib_left (s t u : set α) : s ∪ (t ∪ u) = (s ∪ t) ∪ (s ∪ u) :=
sup_sup_distrib_left _ _ _
lemma union_union_distrib_right (s t u : set α) : (s ∪ t) ∪ u = (s ∪ u) ∪ (t ∪ u) :=
sup_sup_distrib_right _ _ _
lemma inter_inter_distrib_left (s t u : set α) : s ∩ (t ∩ u) = (s ∩ t) ∩ (s ∩ u) :=
inf_inf_distrib_left _ _ _
lemma inter_inter_distrib_right (s t u : set α) : (s ∩ t) ∩ u = (s ∩ u) ∩ (t ∩ u) :=
inf_inf_distrib_right _ _ _
lemma union_union_union_comm (s t u v : set α) : (s ∪ t) ∪ (u ∪ v) = (s ∪ u) ∪ (t ∪ v) :=
sup_sup_sup_comm _ _ _ _
lemma inter_inter_inter_comm (s t u v : set α) : (s ∩ t) ∩ (u ∩ v) = (s ∩ u) ∩ (t ∩ v) :=
inf_inf_inf_comm _ _ _ _
/-!
### Lemmas about `insert`
`insert α s` is the set `{α} ∪ s`.
-/
theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl
@[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := λ y, or.inr
theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl
theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr
theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id
lemma mem_of_mem_insert_of_ne : b ∈ insert a s → b ≠ a → b ∈ s := or.resolve_left
lemma eq_of_not_mem_of_mem_insert : b ∈ insert a s → b ∉ s → b = a := or.resolve_right
@[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ x = a ∨ x ∈ s := iff.rfl
@[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s :=
ext $ λ x, or_iff_right_of_imp $ λ e, e.symm ▸ h
lemma ne_insert_of_not_mem {s : set α} (t : set α) {a : α} : a ∉ s → s ≠ insert a t :=
mt $ λ e, e.symm ▸ mem_insert _ _
@[simp] lemma insert_eq_self : insert a s = s ↔ a ∈ s := ⟨λ h, h ▸ mem_insert _ _, insert_eq_of_mem⟩
lemma insert_ne_self : insert a s ≠ s ↔ a ∉ s := insert_eq_self.not
theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) :=
by simp only [subset_def, or_imp_distrib, forall_and_distrib, forall_eq, mem_insert_iff]
theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := λ x, or.imp_right (@h _)
theorem insert_subset_insert_iff (ha : a ∉ s) : insert a s ⊆ insert a t ↔ s ⊆ t :=
begin
refine ⟨λ h x hx, _, insert_subset_insert⟩,
rcases h (subset_insert _ _ hx) with (rfl|hxt),
exacts [(ha hx).elim, hxt]
end
theorem ssubset_iff_insert {s t : set α} : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t :=
begin
simp only [insert_subset, exists_and_distrib_right, ssubset_def, not_subset],
simp only [exists_prop, and_comm]
end
theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s :=
ssubset_iff_insert.2 ⟨a, h, subset.rfl⟩
theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) :=
ext $ λ x, or.left_comm
@[simp] lemma insert_idem (a : α) (s : set α) : insert a (insert a s) = insert a s :=
insert_eq_of_mem $ mem_insert _ _
theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ λ x, or.assoc
@[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ λ x, or.left_comm
@[simp] theorem insert_nonempty (a : α) (s : set α) : (insert a s).nonempty := ⟨a, mem_insert a s⟩
instance (a : α) (s : set α) : nonempty (insert a s : set α) := (insert_nonempty a s).to_subtype
lemma insert_inter_distrib (a : α) (s t : set α) : insert a (s ∩ t) = insert a s ∩ insert a t :=
ext $ λ y, or_and_distrib_left
lemma insert_union_distrib (a : α) (s t : set α) : insert a (s ∪ t) = insert a s ∪ insert a t :=
ext $ λ _, or_or_distrib_left _ _ _
lemma insert_inj (ha : a ∉ s) : insert a s = insert b s ↔ a = b :=
⟨λ h, eq_of_not_mem_of_mem_insert (h.subst $ mem_insert a s) ha, congr_arg _⟩
-- useful in proofs by induction
theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α}
(H : ∀ x, x ∈ insert a s → P x) (x) (h : x ∈ s) : P x := H _ (or.inr h)
theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α}
(H : ∀ x, x ∈ s → P x) (ha : P a) (x) (h : x ∈ insert a s) : P x :=
h.elim (λ e, e.symm ▸ ha) (H _)
theorem bex_insert_iff {P : α → Prop} {a : α} {s : set α} :
(∃ x ∈ insert a s, P x) ↔ P a ∨ (∃ x ∈ s, P x) :=
bex_or_left_distrib.trans $ or_congr_left' bex_eq_left
theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} :
(∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) :=
ball_or_left_distrib.trans $ and_congr_left' forall_eq
/-! ### Lemmas about singletons -/
theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := (insert_emptyc_eq _).symm
@[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := iff.rfl
@[simp] lemma set_of_eq_eq_singleton {a : α} : {n | n = a} = {a} := rfl
@[simp] lemma set_of_eq_eq_singleton' {a : α} : {x | a = x} = {a} := ext $ λ x, eq_comm
-- TODO: again, annotation needed
@[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := @rfl _ _
theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := h
@[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y :=
ext_iff.trans eq_iff_eq_cancel_left
lemma singleton_injective : injective (singleton : α → set α) :=
λ _ _, singleton_eq_singleton_iff.mp
theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := H
theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := rfl
@[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := union_self _
theorem pair_comm (a b : α) : ({a, b} : set α) = {b, a} := union_comm _ _
@[simp] theorem singleton_nonempty (a : α) : ({a} : set α).nonempty :=
⟨a, rfl⟩
@[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := forall_eq
theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := rfl
@[simp] theorem singleton_union : {a} ∪ s = insert a s := rfl
@[simp] theorem union_singleton : s ∪ {a} = insert a s := union_comm _ _
@[simp] theorem singleton_inter_nonempty : ({a} ∩ s).nonempty ↔ a ∈ s :=
by simp only [set.nonempty, mem_inter_eq, mem_singleton_iff, exists_eq_left]
@[simp] theorem inter_singleton_nonempty : (s ∩ {a}).nonempty ↔ a ∈ s :=
by rw [inter_comm, singleton_inter_nonempty]
@[simp] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s :=
not_nonempty_iff_eq_empty.symm.trans singleton_inter_nonempty.not
@[simp] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s :=
by rw [inter_comm, singleton_inter_eq_empty]
lemma nmem_singleton_empty {s : set α} : s ∉ ({∅} : set (set α)) ↔ s.nonempty :=
ne_empty_iff_nonempty
instance unique_singleton (a : α) : unique ↥({a} : set α) :=
⟨⟨⟨a, mem_singleton a⟩⟩, λ ⟨x, h⟩, subtype.eq h⟩
lemma eq_singleton_iff_unique_mem : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a :=
subset.antisymm_iff.trans $ and.comm.trans $ and_congr_left' singleton_subset_iff
lemma eq_singleton_iff_nonempty_unique_mem : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a :=
eq_singleton_iff_unique_mem.trans $ and_congr_left $ λ H, ⟨λ h', ⟨_, h'⟩, λ ⟨x, h⟩, H x h ▸ h⟩
-- while `simp` is capable of proving this, it is not capable of turning the LHS into the RHS.
@[simp] lemma default_coe_singleton (x : α) : (default : ({x} : set α)) = ⟨x, rfl⟩ := rfl
/-! ### Lemmas about sets defined as `{x ∈ s | p x}`. -/
theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} :=
⟨xs, px⟩
@[simp] theorem sep_mem_eq {s t : set α} : {x ∈ s | x ∈ t} = s ∩ t := rfl
@[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} :
x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl
theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x :=
iff.rfl
theorem eq_sep_of_subset {s t : set α} (h : s ⊆ t) : s = {x ∈ t | x ∈ s} :=
(inter_eq_self_of_subset_right h).symm
@[simp] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := λ x, and.left
@[simp] lemma sep_empty (p : α → Prop) : {x ∈ (∅ : set α) | p x} = ∅ :=
by { ext, exact false_and _ }
theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (H : {x ∈ s | p x} = ∅)
(x) : x ∈ s → ¬ p x := not_and.1 (eq_empty_iff_forall_not_mem.1 H x : _)
@[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := univ_inter _
@[simp] lemma sep_true : {a ∈ s | true} = s :=
by { ext, simp }
@[simp] lemma sep_false : {a ∈ s | false} = ∅ :=
by { ext, simp }
lemma sep_inter_sep {p q : α → Prop} :
{x ∈ s | p x} ∩ {x ∈ s | q x} = {x ∈ s | p x ∧ q x} :=
begin
ext,
simp_rw [mem_inter_iff, mem_sep_iff],
rw [and_and_and_comm, and_self],
end
@[simp] lemma subset_singleton_iff {α : Type*} {s : set α} {x : α} : s ⊆ {x} ↔ ∀ y ∈ s, y = x :=
iff.rfl
lemma subset_singleton_iff_eq {s : set α} {x : α} : s ⊆ {x} ↔ s = ∅ ∨ s = {x} :=
begin
obtain (rfl | hs) := s.eq_empty_or_nonempty,
use ⟨λ _, or.inl rfl, λ _, empty_subset _⟩,
simp [eq_singleton_iff_nonempty_unique_mem, hs, ne_empty_iff_nonempty.2 hs],
end
lemma nonempty.subset_singleton_iff (h : s.nonempty) : s ⊆ {a} ↔ s = {a} :=
subset_singleton_iff_eq.trans $ or_iff_right h.ne_empty
lemma ssubset_singleton_iff {s : set α} {x : α} : s ⊂ {x} ↔ s = ∅ :=
begin
rw [ssubset_iff_subset_ne, subset_singleton_iff_eq, or_and_distrib_right, and_not_self, or_false,
and_iff_left_iff_imp],
rintro rfl,
refine ne_comm.1 (ne_empty_iff_nonempty.2 (singleton_nonempty _)),
end
lemma eq_empty_of_ssubset_singleton {s : set α} {x : α} (hs : s ⊂ {x}) : s = ∅ :=
ssubset_singleton_iff.1 hs
/-! ### Disjointness -/
lemma _root_.disjoint.inter_eq : disjoint s t → s ∩ t = ∅ := disjoint.eq_bot
lemma disjoint_left : disjoint s t ↔ ∀ ⦃a⦄, a ∈ s → a ∉ t := forall_congr $ λ _, not_and
lemma disjoint_right : disjoint s t ↔ ∀ ⦃a⦄, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left]
/-! ### Lemmas about complement -/
lemma compl_def (s : set α) : sᶜ = {x | x ∉ s} := rfl
theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ sᶜ := h
lemma compl_set_of {α} (p : α → Prop) : {a | p a}ᶜ = { a | ¬ p a } := rfl
theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ sᶜ) : x ∉ s := h
@[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ sᶜ = (x ∉ s) := rfl
theorem mem_compl_iff (s : set α) (x : α) : x ∈ sᶜ ↔ x ∉ s := iff.rfl
lemma not_mem_compl_iff {x : α} : x ∉ sᶜ ↔ x ∈ s := not_not
@[simp] theorem inter_compl_self (s : set α) : s ∩ sᶜ = ∅ := inf_compl_eq_bot
@[simp] theorem compl_inter_self (s : set α) : sᶜ ∩ s = ∅ := compl_inf_eq_bot
@[simp] theorem compl_empty : (∅ : set α)ᶜ = univ := compl_bot
@[simp] theorem compl_union (s t : set α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ := compl_sup
theorem compl_inter (s t : set α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ := compl_inf
@[simp] theorem compl_univ : (univ : set α)ᶜ = ∅ := compl_top
@[simp] lemma compl_empty_iff {s : set α} : sᶜ = ∅ ↔ s = univ := compl_eq_bot
@[simp] lemma compl_univ_iff {s : set α} : sᶜ = univ ↔ s = ∅ := compl_eq_top
lemma compl_ne_univ : sᶜ ≠ univ ↔ s.nonempty :=
compl_univ_iff.not.trans ne_empty_iff_nonempty
lemma nonempty_compl {s : set α} : sᶜ.nonempty ↔ s ≠ univ :=
ne_empty_iff_nonempty.symm.trans compl_empty_iff.not
lemma mem_compl_singleton_iff {a x : α} : x ∈ ({a} : set α)ᶜ ↔ x ≠ a :=
mem_singleton_iff.not
lemma compl_singleton_eq (a : α) : ({a} : set α)ᶜ = {x | x ≠ a} :=
ext $ λ x, mem_compl_singleton_iff
@[simp]
lemma compl_ne_eq_singleton (a : α) : ({x | x ≠ a} : set α)ᶜ = {a} :=
by { ext, simp, }
theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = (sᶜ ∩ tᶜ)ᶜ :=
ext $ λ x, or_iff_not_and_not
theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = (sᶜ ∪ tᶜ)ᶜ :=
ext $ λ x, and_iff_not_or_not
@[simp] theorem union_compl_self (s : set α) : s ∪ sᶜ = univ := eq_univ_iff_forall.2 $ λ x, em _
@[simp] theorem compl_union_self (s : set α) : sᶜ ∪ s = univ := by rw [union_comm, union_compl_self]
lemma compl_subset_comm : sᶜ ⊆ t ↔ tᶜ ⊆ s := @compl_le_iff_compl_le _ s _ _
lemma subset_compl_comm : s ⊆ tᶜ ↔ t ⊆ sᶜ := @le_compl_iff_le_compl _ t _ _
@[simp] lemma compl_subset_compl : sᶜ ⊆ tᶜ ↔ t ⊆ s := @compl_le_compl_iff_le (set α) _ _ _
lemma subset_compl_iff_disjoint_left : s ⊆ tᶜ ↔ disjoint t s :=
@le_compl_iff_disjoint_left (set α) _ _ _
lemma subset_compl_iff_disjoint_right : s ⊆ tᶜ ↔ disjoint s t :=
@le_compl_iff_disjoint_right (set α) _ _ _
lemma disjoint_compl_left_iff_subset : disjoint sᶜ t ↔ t ⊆ s := disjoint_compl_left_iff
lemma disjoint_compl_right_iff_subset : disjoint s tᶜ ↔ s ⊆ t := disjoint_compl_right_iff
alias subset_compl_iff_disjoint_right ↔ _ _root_.disjoint.subset_compl_right
alias subset_compl_iff_disjoint_left ↔ _ _root_.disjoint.subset_compl_left
alias disjoint_compl_left_iff_subset ↔ _ _root_.has_subset.subset.disjoint_compl_left
alias disjoint_compl_right_iff_subset ↔ _ _root_.has_subset.subset.disjoint_compl_right
theorem subset_union_compl_iff_inter_subset {s t u : set α} : s ⊆ t ∪ uᶜ ↔ s ∩ u ⊆ t :=
(@is_compl_compl _ u _).le_sup_right_iff_inf_left_le
theorem compl_subset_iff_union {s t : set α} : sᶜ ⊆ t ↔ s ∪ t = univ :=
iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, or_iff_not_imp_left
@[simp] lemma subset_compl_singleton_iff {a : α} {s : set α} : s ⊆ {a}ᶜ ↔ a ∉ s :=
subset_compl_comm.trans singleton_subset_iff
theorem inter_subset (a b c : set α) : a ∩ b ⊆ c ↔ a ⊆ bᶜ ∪ c :=
forall_congr $ λ x, and_imp.trans $ imp_congr_right $ λ _, imp_iff_not_or
lemma inter_compl_nonempty_iff {s t : set α} : (s ∩ tᶜ).nonempty ↔ ¬ s ⊆ t :=
(not_subset.trans $ exists_congr $ by exact λ x, by simp [mem_compl]).symm
/-! ### Lemmas about set difference -/
theorem diff_eq (s t : set α) : s \ t = s ∩ tᶜ := rfl
@[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl
theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t :=
⟨h1, h2⟩
theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s :=
h.left
theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t :=
h.right
theorem diff_eq_compl_inter {s t : set α} : s \ t = tᶜ ∩ s :=
by rw [diff_eq, inter_comm]
theorem nonempty_diff {s t : set α} : (s \ t).nonempty ↔ ¬ (s ⊆ t) := inter_compl_nonempty_iff
theorem diff_subset (s t : set α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le
theorem union_diff_cancel' {s t u : set α} (h₁ : s ⊆ t) (h₂ : t ⊆ u) : t ∪ (u \ s) = u :=
sup_sdiff_cancel' h₁ h₂
theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t :=
sup_sdiff_cancel_right h
theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t :=
disjoint.sup_sdiff_cancel_left h
theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s :=
disjoint.sup_sdiff_cancel_right h
@[simp] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s :=
sup_sdiff_left_self
@[simp] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t :=
sup_sdiff_right_self
theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u :=
sup_sdiff
theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) :=
inf_sdiff_assoc
@[simp] theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ :=
inf_sdiff_self_right
@[simp] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s :=
sup_inf_sdiff s t
@[simp] lemma diff_union_inter (s t : set α) : (s \ t) ∪ (s ∩ t) = s :=
by { rw union_comm, exact sup_inf_sdiff _ _ }
@[simp] theorem inter_union_compl (s t : set α) : (s ∩ t) ∪ (s ∩ tᶜ) = s := inter_union_diff _ _
theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ :=
show s₁ ≤ s₂ → t₂ ≤ t₁ → s₁ \ t₁ ≤ s₂ \ t₂, from sdiff_le_sdiff
theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t :=
sdiff_le_sdiff_right ‹s₁ ≤ s₂›
theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t :=
sdiff_le_sdiff_left ‹t ≤ u›
theorem compl_eq_univ_diff (s : set α) : sᶜ = univ \ s :=
top_sdiff.symm
@[simp] lemma empty_diff (s : set α) : (∅ \ s : set α) = ∅ :=
bot_sdiff
theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t :=
sdiff_eq_bot_iff
@[simp] theorem diff_empty {s : set α} : s \ ∅ = s :=
sdiff_bot
@[simp] lemma diff_univ (s : set α) : s \ univ = ∅ := diff_eq_empty.2 (subset_univ s)
theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) :=
sdiff_sdiff_left
-- the following statement contains parentheses to help the reader
lemma diff_diff_comm {s t u : set α} : (s \ t) \ u = (s \ u) \ t :=
sdiff_sdiff_comm
lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u :=
show s \ t ≤ u ↔ s ≤ t ∪ u, from sdiff_le_iff
lemma subset_diff_union (s t : set α) : s ⊆ (s \ t) ∪ t :=
show s ≤ (s \ t) ∪ t, from le_sdiff_sup
lemma diff_union_of_subset {s t : set α} (h : t ⊆ s) :
(s \ t) ∪ t = s :=
subset.antisymm (union_subset (diff_subset _ _) h) (subset_diff_union _ _)
@[simp] lemma diff_singleton_subset_iff {x : α} {s t : set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t :=
by { rw [←union_singleton, union_comm], apply diff_subset_iff }
lemma subset_diff_singleton {x : α} {s t : set α} (h : s ⊆ t) (hx : x ∉ s) : s ⊆ t \ {x} :=
subset_inter h $ subset_compl_comm.1 $ singleton_subset_iff.2 hx
lemma subset_insert_diff_singleton (x : α) (s : set α) : s ⊆ insert x (s \ {x}) :=
by rw [←diff_singleton_subset_iff]
lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t :=
show s \ t ≤ u ↔ s \ u ≤ t, from sdiff_le_comm
lemma diff_inter {s t u : set α} : s \ (t ∩ u) = (s \ t) ∪ (s \ u) :=
sdiff_inf
lemma diff_inter_diff {s t u : set α} : s \ t ∩ (s \ u) = s \ (t ∪ u) :=
sdiff_sup.symm
lemma diff_compl : s \ tᶜ = s ∩ t := sdiff_compl
lemma diff_diff_right {s t u : set α} : s \ (t \ u) = (s \ t) ∪ (s ∩ u) :=
sdiff_sdiff_right'
@[simp] theorem insert_diff_of_mem (s) (h : a ∈ t) : insert a s \ t = s \ t :=
by { ext, split; simp [or_imp_distrib, h] {contextual := tt} }
theorem insert_diff_of_not_mem (s) (h : a ∉ t) : insert a s \ t = insert a (s \ t) :=
begin
classical,
ext x,
by_cases h' : x ∈ t,
{ have : x ≠ a,
{ assume H,
rw H at h',
exact h h' },
simp [h, h', this] },
{ simp [h, h'] }
end
lemma insert_diff_self_of_not_mem {a : α} {s : set α} (h : a ∉ s) :
insert a s \ {a} = s :=
by { ext, simp [and_iff_left_of_imp (λ hx : x ∈ s, show x ≠ a, from λ hxa, h $ hxa ▸ hx)] }
@[simp] lemma insert_diff_eq_singleton {a : α} {s : set α} (h : a ∉ s) :
insert a s \ s = {a} :=
begin
ext,
rw [set.mem_diff, set.mem_insert_iff, set.mem_singleton_iff, or_and_distrib_right,
and_not_self, or_false, and_iff_left_iff_imp],
rintro rfl,
exact h,
end
lemma inter_insert_of_mem (h : a ∈ s) : s ∩ insert a t = insert a (s ∩ t) :=
by rw [insert_inter_distrib, insert_eq_of_mem h]
lemma insert_inter_of_mem (h : a ∈ t) : insert a s ∩ t = insert a (s ∩ t) :=
by rw [insert_inter_distrib, insert_eq_of_mem h]
lemma inter_insert_of_not_mem (h : a ∉ s) : s ∩ insert a t = s ∩ t :=
ext $ λ x, and_congr_right $ λ hx, or_iff_right $ ne_of_mem_of_not_mem hx h
lemma insert_inter_of_not_mem (h : a ∉ t) : insert a s ∩ t = s ∩ t :=
ext $ λ x, and_congr_left $ λ hx, or_iff_right $ ne_of_mem_of_not_mem hx h
@[simp] theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t :=
sup_sdiff_self_right
@[simp] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t :=
sup_sdiff_self_left
@[simp] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ :=
inf_sdiff_self_left
@[simp] theorem diff_inter_self_eq_diff {s t : set α} : s \ (t ∩ s) = s \ t :=
sdiff_inf_self_right
@[simp] theorem diff_self_inter {s t : set α} : s \ (s ∩ t) = s \ t :=
sdiff_inf_self_left
@[simp] theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ :=
show s \ t = s ↔ t ⊓ s ≤ ⊥, from sdiff_eq_self_iff_disjoint
@[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s :=
diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h]
@[simp] theorem insert_diff_singleton {a : α} {s : set α} :
insert a (s \ {a}) = insert a s :=
by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union]
@[simp] lemma diff_self {s : set α} : s \ s = ∅ := sdiff_self
lemma diff_diff_right_self (s t : set α) : s \ (s \ t) = s ∩ t := sdiff_sdiff_right_self
lemma diff_diff_cancel_left {s t : set α} (h : s ⊆ t) : t \ (t \ s) = s :=
sdiff_sdiff_eq_self h
lemma mem_diff_singleton {x y : α} {s : set α} : x ∈ s \ {y} ↔ (x ∈ s ∧ x ≠ y) :=
iff.rfl
lemma mem_diff_singleton_empty {s : set α} {t : set (set α)} :
s ∈ t \ {∅} ↔ (s ∈ t ∧ s.nonempty) :=
mem_diff_singleton.trans $ iff.rfl.and ne_empty_iff_nonempty
lemma union_eq_diff_union_diff_union_inter (s t : set α) :
s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) :=
sup_eq_sdiff_sup_sdiff_sup_inf
/-! ### Powerset -/
/-- `𝒫 s = set.powerset s` is the set of all subsets of `s`. -/
def powerset (s : set α) : set (set α) := {t | t ⊆ s}
prefix `𝒫`:100 := powerset
theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ 𝒫 s := h
theorem subset_of_mem_powerset {x s : set α} (h : x ∈ 𝒫 s) : x ⊆ s := h
@[simp] theorem mem_powerset_iff (x s : set α) : x ∈ 𝒫 s ↔ x ⊆ s := iff.rfl
theorem powerset_inter (s t : set α) : 𝒫 (s ∩ t) = 𝒫 s ∩ 𝒫 t :=
ext $ λ u, subset_inter_iff
@[simp] theorem powerset_mono : 𝒫 s ⊆ 𝒫 t ↔ s ⊆ t :=
⟨λ h, h (subset.refl s), λ h u hu, subset.trans hu h⟩
theorem monotone_powerset : monotone (powerset : set α → set (set α)) :=
λ s t, powerset_mono.2
@[simp] theorem powerset_nonempty : (𝒫 s).nonempty :=
⟨∅, empty_subset s⟩
@[simp] theorem powerset_empty : 𝒫 (∅ : set α) = {∅} :=
ext $ λ s, subset_empty_iff
@[simp] theorem powerset_univ : 𝒫 (univ : set α) = univ :=
eq_univ_of_forall subset_univ
/-! ### If-then-else for sets -/
/-- `ite` for sets: `set.ite t s s' ∩ t = s ∩ t`, `set.ite t s s' ∩ tᶜ = s' ∩ tᶜ`.
Defined as `s ∩ t ∪ s' \ t`. -/
protected def ite (t s s' : set α) : set α := s ∩ t ∪ s' \ t
@[simp] lemma ite_inter_self (t s s' : set α) : t.ite s s' ∩ t = s ∩ t :=
by rw [set.ite, union_inter_distrib_right, diff_inter_self, inter_assoc, inter_self, union_empty]
@[simp] lemma ite_compl (t s s' : set α) : tᶜ.ite s s' = t.ite s' s :=
by rw [set.ite, set.ite, diff_compl, union_comm, diff_eq]
@[simp] lemma ite_inter_compl_self (t s s' : set α) : t.ite s s' ∩ tᶜ = s' ∩ tᶜ :=
by rw [← ite_compl, ite_inter_self]
@[simp] lemma ite_diff_self (t s s' : set α) : t.ite s s' \ t = s' \ t :=
ite_inter_compl_self t s s'
@[simp] lemma ite_same (t s : set α) : t.ite s s = s := inter_union_diff _ _
@[simp] lemma ite_left (s t : set α) : s.ite s t = s ∪ t := by simp [set.ite]
@[simp] lemma ite_right (s t : set α) : s.ite t s = t ∩ s := by simp [set.ite]
@[simp] lemma ite_empty (s s' : set α) : set.ite ∅ s s' = s' :=
by simp [set.ite]
@[simp] lemma ite_univ (s s' : set α) : set.ite univ s s' = s :=
by simp [set.ite]
@[simp] lemma ite_empty_left (t s : set α) : t.ite ∅ s = s \ t :=
by simp [set.ite]
@[simp] lemma ite_empty_right (t s : set α) : t.ite s ∅ = s ∩ t :=
by simp [set.ite]
lemma ite_mono (t : set α) {s₁ s₁' s₂ s₂' : set α} (h : s₁ ⊆ s₂) (h' : s₁' ⊆ s₂') :
t.ite s₁ s₁' ⊆ t.ite s₂ s₂' :=
union_subset_union (inter_subset_inter_left _ h) (inter_subset_inter_left _ h')
lemma ite_subset_union (t s s' : set α) : t.ite s s' ⊆ s ∪ s' :=
union_subset_union (inter_subset_left _ _) (diff_subset _ _)
lemma inter_subset_ite (t s s' : set α) : s ∩ s' ⊆ t.ite s s' :=
ite_same t (s ∩ s') ▸ ite_mono _ (inter_subset_left _ _) (inter_subset_right _ _)
lemma ite_inter_inter (t s₁ s₂ s₁' s₂' : set α) :
t.ite (s₁ ∩ s₂) (s₁' ∩ s₂') = t.ite s₁ s₁' ∩ t.ite s₂ s₂' :=
by { ext x, simp only [set.ite, set.mem_inter_eq, set.mem_diff, set.mem_union_eq], itauto }
lemma ite_inter (t s₁ s₂ s : set α) :
t.ite (s₁ ∩ s) (s₂ ∩ s) = t.ite s₁ s₂ ∩ s :=
by rw [ite_inter_inter, ite_same]
lemma ite_inter_of_inter_eq (t : set α) {s₁ s₂ s : set α} (h : s₁ ∩ s = s₂ ∩ s) :
t.ite s₁ s₂ ∩ s = s₁ ∩ s :=
by rw [← ite_inter, ← h, ite_same]
lemma subset_ite {t s s' u : set α} : u ⊆ t.ite s s' ↔ u ∩ t ⊆ s ∧ u \ t ⊆ s' :=
begin
simp only [subset_def, ← forall_and_distrib],
refine forall_congr (λ x, _),
by_cases hx : x ∈ t; simp [*, set.ite]
end
/-! ### Inverse image -/
/-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`,
is the set of `x : α` such that `f x ∈ s`. -/
def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s}
infix ` ⁻¹' `:80 := preimage
section preimage
variables {f : α → β} {g : β → γ}
@[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl
@[simp] theorem mem_preimage {s : set β} {a : α} : (a ∈ f ⁻¹' s) ↔ (f a ∈ s) := iff.rfl
lemma preimage_congr {f g : α → β} {s : set β} (h : ∀ (x : α), f x = g x) : f ⁻¹' s = g ⁻¹' s :=
by { congr' with x, apply_assumption }
theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t :=
assume x hx, h hx
@[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl
theorem subset_preimage_univ {s : set α} : s ⊆ f ⁻¹' univ := subset_univ _
@[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl
@[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl
@[simp] theorem preimage_compl {s : set β} : f ⁻¹' sᶜ = (f ⁻¹' s)ᶜ := rfl
@[simp] theorem preimage_diff (f : α → β) (s t : set β) :
f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl
@[simp] theorem preimage_ite (f : α → β) (s t₁ t₂ : set β) :
f ⁻¹' (s.ite t₁ t₂) = (f ⁻¹' s).ite (f ⁻¹' t₁) (f ⁻¹' t₂) :=
rfl
@[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} :=
rfl
@[simp] theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl
@[simp] theorem preimage_id' {s : set α} : (λ x, x) ⁻¹' s = s := rfl
@[simp] theorem preimage_const_of_mem {b : β} {s : set β} (h : b ∈ s) :
(λ (x : α), b) ⁻¹' s = univ :=
eq_univ_of_forall $ λ x, h
@[simp] theorem preimage_const_of_not_mem {b : β} {s : set β} (h : b ∉ s) :
(λ (x : α), b) ⁻¹' s = ∅ :=
eq_empty_of_subset_empty $ λ x hx, h hx
theorem preimage_const (b : β) (s : set β) [decidable (b ∈ s)] :
(λ (x : α), b) ⁻¹' s = if b ∈ s then univ else ∅ :=
by { split_ifs with hb hb, exacts [preimage_const_of_mem hb, preimage_const_of_not_mem hb] }
theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl
lemma preimage_preimage {g : β → γ} {f : α → β} {s : set γ} :
f ⁻¹' (g ⁻¹' s) = (λ x, g (f x)) ⁻¹' s :=
preimage_comp.symm
theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} :
s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) :=
⟨assume s_eq x h, by { rw [s_eq], simp },
assume h, ext $ λ ⟨x, hx⟩, by simp [h]⟩
lemma nonempty_of_nonempty_preimage {s : set β} {f : α → β} (hf : (f ⁻¹' s).nonempty) :
s.nonempty :=
let ⟨x, hx⟩ := hf in ⟨f x, hx⟩
end preimage
/-! ### Image of a set under a function -/
section image
/-- The image of `s : set α` by `f : α → β`, written `f '' s`,
is the set of `y : β` such that `f x = y` for some `x ∈ s`. -/
def image (f : α → β) (s : set α) : set β := {y | ∃ x, x ∈ s ∧ f x = y}
infix ` '' `:80 := image
theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} :
y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm
theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl
@[simp] theorem mem_image (f : α → β) (s : set α) (y : β) :
y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl
lemma image_eta (f : α → β) : f '' s = (λ x, f x) '' s := rfl
theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a :=
⟨_, h, rfl⟩
theorem _root_.function.injective.mem_set_image {f : α → β} (hf : injective f) {s : set α} {a : α} :
f a ∈ f '' s ↔ a ∈ s :=
⟨λ ⟨b, hb, eq⟩, (hf eq) ▸ hb, mem_image_of_mem f⟩
theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} :
(∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) :=
by simp
theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop}
(h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y :=
ball_image_iff.2 h
theorem bex_image_iff {f : α → β} {s : set α} {p : β → Prop} :
(∃ y ∈ f '' s, p y) ↔ (∃ x ∈ s, p (f x)) :=
by simp
theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) :
∀{y : β}, y ∈ f '' s → C y
| ._ ⟨a, a_in, rfl⟩ := h a a_in
theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s)
(h : ∀ (x : α), x ∈ s → C (f x)) : C y :=
mem_image_elim h h_y
@[congr] lemma image_congr {f g : α → β} {s : set α}
(h : ∀a∈s, f a = g a) : f '' s = g '' s :=
by safe [ext_iff, iff_def]
/-- A common special case of `image_congr` -/
lemma image_congr' {f g : α → β} {s : set α} (h : ∀ (x : α), f x = g x) : f '' s = g '' s :=
image_congr (λx _, h x)
theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) :=
subset.antisymm
(ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha)
(ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha)
/-- A variant of `image_comp`, useful for rewriting -/
lemma image_image (g : β → γ) (f : α → β) (s : set α) : g '' (f '' s) = (λ x, g (f x)) '' s :=
(image_comp g f s).symm
lemma image_comm {β'} {f : β → γ} {g : α → β} {f' : α → β'} {g' : β' → γ}
(h_comm : ∀ a, f (g a) = g' (f' a)) :
(s.image g).image f = (s.image f').image g' :=
by simp_rw [image_image, h_comm]
lemma _root_.function.semiconj.set_image {f : α → β} {ga : α → α} {gb : β → β}
(h : function.semiconj f ga gb) :
function.semiconj (image f) (image ga) (image gb) :=
λ s, image_comm h
lemma _root_.function.commute.set_image {f g : α → α} (h : function.commute f g) :
function.commute (image f) (image g) :=
h.set_image
/-- Image is monotone with respect to `⊆`. See `set.monotone_image` for the statement in
terms of `≤`. -/
theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b :=
by { simp only [subset_def, mem_image_eq], exact λ x, λ ⟨w, h1, h2⟩, ⟨w, h h1, h2⟩ }
theorem image_union (f : α → β) (s t : set α) :
f '' (s ∪ t) = f '' s ∪ f '' t :=
ext $ λ x, ⟨by rintro ⟨a, h|h, rfl⟩; [left, right]; exact ⟨_, h, rfl⟩,
by rintro (⟨a, h, rfl⟩ | ⟨a, h, rfl⟩); refine ⟨_, _, rfl⟩; [left, right]; exact h⟩
@[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := by { ext, simp }
lemma image_inter_subset (f : α → β) (s t : set α) :
f '' (s ∩ t) ⊆ f '' s ∩ f '' t :=
subset_inter (image_subset _ $ inter_subset_left _ _) (image_subset _ $ inter_subset_right _ _)
theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) :
f '' s ∩ f '' t = f '' (s ∩ t) :=
subset.antisymm
(assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩,
have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *),
⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩)
(image_inter_subset _ _ _)
theorem image_inter {f : α → β} {s t : set α} (H : injective f) :
f '' s ∩ f '' t = f '' (s ∩ t) :=
image_inter_on (assume x _ y _ h, H h)
theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ :=
eq_univ_of_forall $ by { simpa [image] }
@[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} :=
by { ext, simp [image, eq_comm] }
@[simp] theorem nonempty.image_const {s : set α} (hs : s.nonempty) (a : β) : (λ _, a) '' s = {a} :=
ext $ λ x, ⟨λ ⟨y, _, h⟩, h ▸ mem_singleton _,
λ h, (eq_of_mem_singleton h).symm ▸ hs.imp (λ y hy, ⟨hy, rfl⟩)⟩
@[simp] lemma image_eq_empty {α β} {f : α → β} {s : set α} : f '' s = ∅ ↔ s = ∅ :=
by { simp only [eq_empty_iff_forall_not_mem],
exact ⟨λ H a ha, H _ ⟨_, ha, rfl⟩, λ H b ⟨_, ha, _⟩, H _ ha⟩ }
lemma preimage_compl_eq_image_compl [boolean_algebra α] (S : set α) :
compl ⁻¹' S = compl '' S :=
set.ext (λ x, ⟨λ h, ⟨xᶜ,h, compl_compl x⟩,
λ h, exists.elim h (λ y hy, (compl_eq_comm.mp hy.2).symm.subst hy.1)⟩)
theorem mem_compl_image [boolean_algebra α] (t : α) (S : set α) :
t ∈ compl '' S ↔ tᶜ ∈ S :=
by simp [←preimage_compl_eq_image_compl]
/-- A variant of `image_id` -/
@[simp] lemma image_id' (s : set α) : (λx, x) '' s = s := by { ext, simp }
theorem image_id (s : set α) : id '' s = s := by simp
theorem compl_compl_image [boolean_algebra α] (S : set α) :
compl '' (compl '' S) = S :=
by rw [←image_comp, compl_comp_compl, image_id]
theorem image_insert_eq {f : α → β} {a : α} {s : set α} :
f '' (insert a s) = insert (f a) (f '' s) :=
by { ext, simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] }
theorem image_pair (f : α → β) (a b : α) : f '' {a, b} = {f a, f b} :=
by simp only [image_insert_eq, image_singleton]
theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α}
(I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s :=
λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s)
theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α}
(I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s :=
λ b h, ⟨f b, h, I b⟩
theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α}
(h₁ : left_inverse g f) (h₂ : right_inverse g f) :
image f = preimage g :=
funext $ λ s, subset.antisymm
(image_subset_preimage_of_inverse h₁ s)
(preimage_subset_image_of_inverse h₂ s)
theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α}
(h₁ : left_inverse g f) (h₂ : right_inverse g f) :
b ∈ f '' s ↔ g b ∈ s :=
by rw image_eq_preimage_of_inverse h₁ h₂; refl
theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' sᶜ ⊆ (f '' s)ᶜ :=
disjoint.subset_compl_left $ by simp [disjoint, image_inter H]
theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : (f '' s)ᶜ ⊆ f '' sᶜ :=
compl_subset_iff_union.2 $
by { rw ← image_union, simp [image_univ_of_surjective H] }
theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' sᶜ = (f '' s)ᶜ :=
subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2)
theorem subset_image_diff (f : α → β) (s t : set α) :
f '' s \ f '' t ⊆ f '' (s \ t) :=
begin
rw [diff_subset_iff, ← image_union, union_diff_self],
exact image_subset f (subset_union_right t s)
end
theorem image_diff {f : α → β} (hf : injective f) (s t : set α) :
f '' (s \ t) = f '' s \ f '' t :=
subset.antisymm
(subset.trans (image_inter_subset _ _ _) $ inter_subset_inter_right _ $ image_compl_subset hf)
(subset_image_diff f s t)
lemma nonempty.image (f : α → β) {s : set α} : s.nonempty → (f '' s).nonempty
| ⟨x, hx⟩ := ⟨f x, mem_image_of_mem f hx⟩
lemma nonempty.of_image {f : α → β} {s : set α} : (f '' s).nonempty → s.nonempty
| ⟨y, x, hx, _⟩ := ⟨x, hx⟩
@[simp] lemma nonempty_image_iff {f : α → β} {s : set α} :
(f '' s).nonempty ↔ s.nonempty :=
⟨nonempty.of_image, λ h, h.image f⟩
lemma nonempty.preimage {s : set β} (hs : s.nonempty) {f : α → β} (hf : surjective f) :
(f ⁻¹' s).nonempty :=
let ⟨y, hy⟩ := hs, ⟨x, hx⟩ := hf y in ⟨x, mem_preimage.2 $ hx.symm ▸ hy⟩
instance (f : α → β) (s : set α) [nonempty s] : nonempty (f '' s) :=
(set.nonempty.image f nonempty_of_nonempty_subtype).to_subtype
/-- image and preimage are a Galois connection -/
@[simp] theorem image_subset_iff {s : set α} {t : set β} {f : α → β} :
f '' s ⊆ t ↔ s ⊆ f ⁻¹' t :=
ball_image_iff
theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s :=
image_subset_iff.2 subset.rfl
theorem subset_preimage_image (f : α → β) (s : set α) :
s ⊆ f ⁻¹' (f '' s) :=
λ x, mem_image_of_mem f
theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s :=
subset.antisymm
(λ x ⟨y, hy, e⟩, h e ▸ hy)
(subset_preimage_image f s)
theorem image_preimage_eq {f : α → β} (s : set β) (h : surjective f) : f '' (f ⁻¹' s) = s :=
subset.antisymm
(image_preimage_subset f s)
(λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩)
lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = f ⁻¹' t ↔ s = t :=
iff.intro
(assume eq, by rw [← image_preimage_eq s hf, ← image_preimage_eq t hf, eq])
(assume eq, eq ▸ rfl)
lemma image_inter_preimage (f : α → β) (s : set α) (t : set β) :
f '' (s ∩ f ⁻¹' t) = f '' s ∩ t :=
begin
apply subset.antisymm,
{ calc f '' (s ∩ f ⁻¹' t) ⊆ f '' s ∩ (f '' (f⁻¹' t)) : image_inter_subset _ _ _
... ⊆ f '' s ∩ t : inter_subset_inter_right _ (image_preimage_subset f t) },
{ rintros _ ⟨⟨x, h', rfl⟩, h⟩,
exact ⟨x, ⟨h', h⟩, rfl⟩ }
end
lemma image_preimage_inter (f : α → β) (s : set α) (t : set β) :
f '' (f ⁻¹' t ∩ s) = t ∩ f '' s :=
by simp only [inter_comm, image_inter_preimage]
@[simp] lemma image_inter_nonempty_iff {f : α → β} {s : set α} {t : set β} :
(f '' s ∩ t).nonempty ↔ (s ∩ f ⁻¹' t).nonempty :=
by rw [←image_inter_preimage, nonempty_image_iff]
lemma image_diff_preimage {f : α → β} {s : set α} {t : set β} : f '' (s \ f ⁻¹' t) = f '' s \ t :=
by simp_rw [diff_eq, ← preimage_compl, image_inter_preimage]
theorem compl_image : image (compl : set α → set α) = preimage compl :=
image_eq_preimage_of_inverse compl_compl compl_compl
theorem compl_image_set_of {p : set α → Prop} :
compl '' {s | p s} = {s | p sᶜ} :=
congr_fun compl_image p
theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) :
s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) :=
λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩
theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) :
s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) :=
λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r)
theorem subset_image_union (f : α → β) (s : set α) (t : set β) :
f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t :=
image_subset_iff.2 (union_preimage_subset _ _ _)
lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} :
f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl
lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t :=
iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq,
by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq]
lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t :=
begin
refine (iff.symm $ iff.intro (image_subset f) $ assume h, _),
rw [← preimage_image_eq s hf, ← preimage_image_eq t hf],
exact preimage_mono h
end
lemma prod_quotient_preimage_eq_image [s : setoid α] (g : quotient s → β) {h : α → β}
(Hh : h = g ∘ quotient.mk) (r : set (β × β)) :
{x : quotient s × quotient s | (g x.1, g x.2) ∈ r} =
(λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) :=
Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂
(λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩),
λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from
have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂,
h₃.1 ▸ h₃.2 ▸ h₁⟩)
lemma exists_image_iff (f : α → β) (x : set α) (P : β → Prop) :
(∃ (a : f '' x), P a) ↔ ∃ (a : x), P (f a) :=
⟨λ ⟨a, h⟩, ⟨⟨_, a.prop.some_spec.1⟩, a.prop.some_spec.2.symm ▸ h⟩,
λ ⟨a, h⟩, ⟨⟨_, _, a.prop, rfl⟩, h⟩⟩
/-- Restriction of `f` to `s` factors through `s.image_factorization f : s → f '' s`. -/
def image_factorization (f : α → β) (s : set α) : s → f '' s :=
λ p, ⟨f p.1, mem_image_of_mem f p.2⟩
lemma image_factorization_eq {f : α → β} {s : set α} :
subtype.val ∘ image_factorization f s = f ∘ subtype.val :=
funext $ λ p, rfl
lemma surjective_onto_image {f : α → β} {s : set α} :
surjective (image_factorization f s) :=
λ ⟨_, ⟨a, ha, rfl⟩⟩, ⟨⟨a, ha⟩, rfl⟩
/-- If the only elements outside `s` are those left fixed by `σ`, then mapping by `σ` has no effect.
-/
lemma image_perm {s : set α} {σ : equiv.perm α} (hs : {a : α | σ a ≠ a} ⊆ s) : σ '' s = s :=
begin
ext i,
obtain hi | hi := eq_or_ne (σ i) i,
{ refine ⟨_, λ h, ⟨i, h, hi⟩⟩,
rintro ⟨j, hj, h⟩,
rwa σ.injective (hi.trans h.symm) },
{ refine iff_of_true ⟨σ.symm i, hs $ λ h, hi _, σ.apply_symm_apply _⟩ (hs hi),
convert congr_arg σ h; exact (σ.apply_symm_apply _).symm }
end
end image
/-! ### Subsingleton -/
/-- A set `s` is a `subsingleton` if it has at most one element. -/
protected def subsingleton (s : set α) : Prop :=
∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y
lemma subsingleton.anti (ht : t.subsingleton) (hst : s ⊆ t) : s.subsingleton :=
λ x hx y hy, ht (hst hx) (hst hy)
lemma subsingleton.eq_singleton_of_mem (hs : s.subsingleton) {x:α} (hx : x ∈ s) : s = {x} :=
ext $ λ y, ⟨λ hy, (hs hx hy) ▸ mem_singleton _, λ hy, (eq_of_mem_singleton hy).symm ▸ hx⟩
@[simp] lemma subsingleton_empty : (∅ : set α).subsingleton := λ x, false.elim
@[simp] lemma subsingleton_singleton {a} : ({a} : set α).subsingleton :=
λ x hx y hy, (eq_of_mem_singleton hx).symm ▸ (eq_of_mem_singleton hy).symm ▸ rfl
lemma subsingleton_of_subset_singleton (h : s ⊆ {a}) : s.subsingleton :=
subsingleton_singleton.anti h
lemma subsingleton_of_forall_eq (a : α) (h : ∀ b ∈ s, b = a) : s.subsingleton :=
λ b hb c hc, (h _ hb).trans (h _ hc).symm
lemma subsingleton_iff_singleton {x} (hx : x ∈ s) : s.subsingleton ↔ s = {x} :=
⟨λ h, h.eq_singleton_of_mem hx, λ h,h.symm ▸ subsingleton_singleton⟩
lemma subsingleton.eq_empty_or_singleton (hs : s.subsingleton) :
s = ∅ ∨ ∃ x, s = {x} :=
s.eq_empty_or_nonempty.elim or.inl (λ ⟨x, hx⟩, or.inr ⟨x, hs.eq_singleton_of_mem hx⟩)
lemma subsingleton.induction_on {p : set α → Prop} (hs : s.subsingleton) (he : p ∅)
(h₁ : ∀ x, p {x}) : p s :=
by { rcases hs.eq_empty_or_singleton with rfl|⟨x, rfl⟩, exacts [he, h₁ _] }
lemma subsingleton_univ [subsingleton α] : (univ : set α).subsingleton :=
λ x hx y hy, subsingleton.elim x y
lemma subsingleton_of_univ_subsingleton (h : (univ : set α).subsingleton) : subsingleton α :=
⟨λ a b, h (mem_univ a) (mem_univ b)⟩
@[simp] lemma subsingleton_univ_iff : (univ : set α).subsingleton ↔ subsingleton α :=
⟨subsingleton_of_univ_subsingleton, λ h, @subsingleton_univ _ h⟩
lemma subsingleton_of_subsingleton [subsingleton α] {s : set α} : set.subsingleton s :=
subsingleton_univ.anti (subset_univ s)
lemma subsingleton_is_top (α : Type*) [partial_order α] : set.subsingleton {x : α | is_top x} :=
λ x hx y hy, hx.is_max.eq_of_le (hy x)
lemma subsingleton_is_bot (α : Type*) [partial_order α] : set.subsingleton {x : α | is_bot x} :=
λ x hx y hy, hx.is_min.eq_of_ge (hy x)
lemma exists_eq_singleton_iff_nonempty_subsingleton :
(∃ a : α, s = {a}) ↔ s.nonempty ∧ s.subsingleton :=
begin
refine ⟨_, λ h, _⟩,
{ rintros ⟨a, rfl⟩,
exact ⟨singleton_nonempty a, subsingleton_singleton⟩ },
{ exact h.2.eq_empty_or_singleton.resolve_left h.1.ne_empty },
end
/-- `s`, coerced to a type, is a subsingleton type if and only if `s` is a subsingleton set. -/
@[simp, norm_cast] lemma subsingleton_coe (s : set α) : subsingleton s ↔ s.subsingleton :=
begin
split,
{ refine λ h, (λ a ha b hb, _),
exact set_coe.ext_iff.2 (@subsingleton.elim s h ⟨a, ha⟩ ⟨b, hb⟩) },
{ exact λ h, subsingleton.intro (λ a b, set_coe.ext (h a.property b.property)) }
end
/-- The `coe_sort` of a set `s` in a subsingleton type is a subsingleton.
For the corresponding result for `subtype`, see `subtype.subsingleton`. -/
instance subsingleton_coe_of_subsingleton [subsingleton α] {s : set α} : subsingleton s :=
by { rw [s.subsingleton_coe], exact subsingleton_of_subsingleton }
/-- The image of a subsingleton is a subsingleton. -/
lemma subsingleton.image (hs : s.subsingleton) (f : α → β) : (f '' s).subsingleton :=
λ _ ⟨x, hx, Hx⟩ _ ⟨y, hy, Hy⟩, Hx ▸ Hy ▸ congr_arg f (hs hx hy)
/-- The preimage of a subsingleton under an injective map is a subsingleton. -/
theorem subsingleton.preimage {s : set β} (hs : s.subsingleton) {f : α → β}
(hf : function.injective f) : (f ⁻¹' s).subsingleton := λ a ha b hb, hf $ hs ha hb
/-- If the image of a set under an injective map is a subsingleton, the set is a subsingleton. -/
theorem subsingleton_of_image {α β : Type*} {f : α → β} (hf : function.injective f)
(s : set α) (hs : (f '' s).subsingleton) : s.subsingleton :=
(hs.preimage hf).anti $ subset_preimage_image _ _
/-- If the preimage of a set under an surjective map is a subsingleton,
the set is a subsingleton. -/
theorem subsingleton_of_preimage {α β : Type*} {f : α → β} (hf : function.surjective f)
(s : set β) (hs : (f ⁻¹' s).subsingleton) : s.subsingleton :=
λ fx hx fy hy, by { rcases ⟨hf fx, hf fy⟩ with ⟨⟨x, rfl⟩, ⟨y, rfl⟩⟩, exact congr_arg f (hs hx hy) }
/-! ### Nontrivial -/
/-- A set `s` is `nontrivial` if it has at least two distinct elements. -/
protected def nontrivial (s : set α) : Prop := ∃ x y ∈ s, x ≠ y
lemma nontrivial_of_mem_mem_ne {x y} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) : s.nontrivial :=
⟨x, hx, y, hy, hxy⟩
/-- Extract witnesses from s.nontrivial. This function might be used instead of case analysis on the
argument. Note that it makes a proof depend on the classical.choice axiom. -/
protected noncomputable def nontrivial.some (hs : s.nontrivial) : α × α :=
(hs.some, hs.some_spec.some_spec.some)
protected lemma nontrivial.some_fst_mem (hs : s.nontrivial) : hs.some.fst ∈ s := hs.some_spec.some
protected lemma nontrivial.some_snd_mem (hs : s.nontrivial) : hs.some.snd ∈ s :=
hs.some_spec.some_spec.some_spec.some
protected lemma nontrivial.some_fst_ne_some_snd (hs : s.nontrivial) : hs.some.fst ≠ hs.some.snd :=
hs.some_spec.some_spec.some_spec.some_spec
lemma nontrivial.mono (hs : s.nontrivial) (hst : s ⊆ t) : t.nontrivial :=
let ⟨x, hx, y, hy, hxy⟩ := hs in ⟨x, hst hx, y, hst hy, hxy⟩
lemma nontrivial_pair {x y} (hxy : x ≠ y) : ({x, y} : set α).nontrivial :=
⟨x, mem_insert _ _, y, mem_insert_of_mem _ (mem_singleton _), hxy⟩
lemma nontrivial_of_pair_subset {x y} (hxy : x ≠ y) (h : {x, y} ⊆ s) : s.nontrivial :=
(nontrivial_pair hxy).mono h
lemma nontrivial.pair_subset (hs : s.nontrivial) : ∃ x y (hab : x ≠ y), {x, y} ⊆ s :=
let ⟨x, hx, y, hy, hxy⟩ := hs in ⟨x, y, hxy, insert_subset.2 ⟨hx, (singleton_subset_iff.2 hy)⟩⟩
lemma nontrivial_iff_pair_subset : s.nontrivial ↔ ∃ x y (hxy : x ≠ y), {x, y} ⊆ s :=
⟨nontrivial.pair_subset, λ H, let ⟨x, y, hxy, h⟩ := H in nontrivial_of_pair_subset hxy h⟩
lemma nontrivial_of_exists_ne {x} (hx : x ∈ s) (h : ∃ y ∈ s, y ≠ x) : s.nontrivial :=
let ⟨y, hy, hyx⟩ := h in ⟨y, hy, x, hx, hyx⟩
lemma nontrivial.exists_ne {z} (hs : s.nontrivial) : ∃ x ∈ s, x ≠ z :=
begin
by_contra H, push_neg at H,
rcases hs with ⟨x, hx, y, hy, hxy⟩,
rw [H x hx, H y hy] at hxy,
exact hxy rfl
end
lemma nontrivial_iff_exists_ne {x} (hx : x ∈ s) : s.nontrivial ↔ ∃ y ∈ s, y ≠ x :=
⟨λ H, H.exists_ne, nontrivial_of_exists_ne hx⟩
lemma nontrivial_of_lt [preorder α] {x y} (hx : x ∈ s) (hy : y ∈ s) (hxy : x < y) : s.nontrivial :=
⟨x, hx, y, hy, ne_of_lt hxy⟩
lemma nontrivial_of_exists_lt [preorder α] (H : ∃ x y ∈ s, x < y) : s.nontrivial :=
let ⟨x, hx, y, hy, hxy⟩ := H in nontrivial_of_lt hx hy hxy
lemma nontrivial.exists_lt [linear_order α] (hs : s.nontrivial) : ∃ x y ∈ s, x < y :=
let ⟨x, hx, y, hy, hxy⟩ := hs in
or.elim (lt_or_gt_of_ne hxy) (λ H, ⟨x, hx, y, hy, H⟩) (λ H, ⟨y, hy, x, hx, H⟩)
lemma nontrivial.iff_exists_lt [linear_order α] : s.nontrivial ↔ ∃ x y ∈ s, x < y :=
⟨nontrivial.exists_lt, nontrivial_of_exists_lt⟩
lemma nontrivial.nonempty (hs : s.nontrivial) : s.nonempty := let ⟨x, hx, _⟩ := hs in ⟨x, hx⟩
lemma nontrivial.ne_empty (hs : s.nontrivial) : s ≠ ∅ := hs.nonempty.ne_empty
lemma nontrivial.not_subset_empty (hs : s.nontrivial) : ¬ s ⊆ ∅ := hs.nonempty.not_subset_empty
@[simp] lemma not_nontrivial_empty : ¬ (∅ : set α).nontrivial := λ h, h.ne_empty rfl
@[simp] lemma not_nontrivial_singleton {x} : ¬ ({x} : set α).nontrivial :=
λ H, begin
rw nontrivial_iff_exists_ne (mem_singleton x) at H,
exact let ⟨y, hy, hya⟩ := H in hya (mem_singleton_iff.1 hy)
end
lemma nontrivial.ne_singleton {x} (hs : s.nontrivial) : s ≠ {x} :=
λ H, by { rw H at hs, exact not_nontrivial_singleton hs }
lemma nontrivial.not_subset_singleton {x} (hs : s.nontrivial) : ¬ s ⊆ {x} :=
(not_congr subset_singleton_iff_eq).2 (not_or hs.ne_empty hs.ne_singleton)
lemma nontrivial_univ [nontrivial α] : (univ : set α).nontrivial :=
let ⟨x, y, hxy⟩ := exists_pair_ne α in ⟨x, mem_univ _, y, mem_univ _, hxy⟩
lemma nontrivial_of_univ_nontrivial (h : (univ : set α).nontrivial) : nontrivial α :=
let ⟨x, _, y, _, hxy⟩ := h in ⟨⟨x, y, hxy⟩⟩
@[simp] lemma nontrivial_univ_iff : (univ : set α).nontrivial ↔ nontrivial α :=
⟨nontrivial_of_univ_nontrivial, λ h, @nontrivial_univ _ h⟩
lemma nontrivial_of_nontrivial (hs : s.nontrivial) : nontrivial α :=
let ⟨x, _, y, _, hxy⟩ := hs in ⟨⟨x, y, hxy⟩⟩
/-- `s`, coerced to a type, is a nontrivial type if and only if `s` is a nontrivial set. -/
@[simp, norm_cast] lemma nontrivial_coe (s : set α) : nontrivial s ↔ s.nontrivial :=
by simp_rw [← nontrivial_univ_iff, set.nontrivial, mem_univ,
exists_true_left, set_coe.exists, subtype.mk_eq_mk]
/-- A type with a set `s` whose `coe_sort` is a nontrivial type is nontrivial.
For the corresponding result for `subtype`, see `subtype.nontrivial_iff_exists_ne`. -/
lemma nontrivial_of_nontrivial_coe (hs : nontrivial s) : nontrivial α :=
by { rw [s.nontrivial_coe] at hs, exact nontrivial_of_nontrivial hs }
theorem nontrivial_mono {α : Type*} {s t : set α} (hst : s ⊆ t) (hs : nontrivial s) :
nontrivial t := (nontrivial_coe _).2 $ (s.nontrivial_coe.1 hs).mono hst
/-- The preimage of a nontrivial set under a surjective map is nontrivial. -/
theorem nontrivial.preimage {s : set β} (hs : s.nontrivial) {f : α → β}
(hf : function.surjective f) : (f ⁻¹' s).nontrivial :=
begin
rcases hs with ⟨fx, hx, fy, hy, hxy⟩,
rcases ⟨hf fx, hf fy⟩ with ⟨⟨x, rfl⟩, ⟨y, rfl⟩⟩,
exact ⟨x, hx, y, hy, mt (congr_arg f) hxy⟩
end
/-- The image of a nontrivial set under an injective map is nontrivial. -/
theorem nontrivial.image (hs : s.nontrivial)
{f : α → β} (hf : function.injective f) : (f '' s).nontrivial :=
let ⟨x, hx, y, hy, hxy⟩ := hs in ⟨f x, mem_image_of_mem f hx, f y, mem_image_of_mem f hy, hf.ne hxy⟩
/-- If the image of a set is nontrivial, the set is nontrivial. -/
lemma nontrivial_of_image (f : α → β) (s : set α) (hs : (f '' s).nontrivial) : s.nontrivial :=
let ⟨_, ⟨x, hx, rfl⟩, _, ⟨y, hy, rfl⟩, hxy⟩ := hs in ⟨x, hx, y, hy, mt (congr_arg f) hxy⟩
/-- If the preimage of a set under an injective map is nontrivial, the set is nontrivial. -/
lemma nontrivial_of_preimage {f : α → β} (hf : function.injective f) (s : set β)
(hs : (f ⁻¹' s).nontrivial) : s.nontrivial :=
(hs.image hf).mono $ image_preimage_subset _ _
@[simp] lemma not_subsingleton_iff : ¬ s.subsingleton ↔ s.nontrivial :=
by simp_rw [set.subsingleton, set.nontrivial, not_forall]
@[simp] lemma not_nontrivial_iff : ¬ s.nontrivial ↔ s.subsingleton :=
iff.not_left not_subsingleton_iff.symm
theorem univ_eq_true_false : univ = ({true, false} : set Prop) :=
eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp)
section preorder
variables [preorder α] [preorder β] (f : α → β)
/-! ### Monotonicity on singletons -/
protected lemma subsingleton.monotone_on (h : s.subsingleton) :
monotone_on f s :=
λ a ha b hb _, (congr_arg _ (h ha hb)).le
protected lemma subsingleton.antitone_on (h : s.subsingleton) :
antitone_on f s :=
λ a ha b hb _, (congr_arg _ (h hb ha)).le
protected lemma subsingleton.strict_mono_on (h : s.subsingleton) :
strict_mono_on f s :=
λ a ha b hb hlt, (hlt.ne (h ha hb)).elim
protected lemma subsingleton.strict_anti_on (h : s.subsingleton) :
strict_anti_on f s :=
λ a ha b hb hlt, (hlt.ne (h ha hb)).elim
@[simp] lemma monotone_on_singleton : monotone_on f {a} :=
subsingleton_singleton.monotone_on f
@[simp] lemma antitone_on_singleton : antitone_on f {a} :=
subsingleton_singleton.antitone_on f
@[simp] lemma strict_mono_on_singleton : strict_mono_on f {a} :=
subsingleton_singleton.strict_mono_on f
@[simp] lemma strict_anti_on_singleton : strict_anti_on f {a} :=
subsingleton_singleton.strict_anti_on f
end preorder
/-! ### Lemmas about range of a function. -/
section range
variables {f : ι → α}
open function
/-- Range of a function.
This function is more flexible than `f '' univ`, as the image requires that the domain is in Type
and not an arbitrary Sort. -/
def range (f : ι → α) : set α := {x | ∃y, f y = x}
@[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl
@[simp] theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩
theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) :=
by simp
theorem forall_subtype_range_iff {p : range f → Prop} :
(∀ a : range f, p a) ↔ ∀ i, p ⟨f i, mem_range_self _⟩ :=
⟨λ H i, H _, λ H ⟨y, i, hi⟩, by { subst hi, apply H }⟩
theorem exists_range_iff {p : α → Prop} : (∃ a ∈ range f, p a) ↔ (∃ i, p (f i)) :=
by simp
lemma exists_range_iff' {p : α → Prop} :
(∃ a, a ∈ range f ∧ p a) ↔ ∃ i, p (f i) :=
by simpa only [exists_prop] using exists_range_iff
lemma exists_subtype_range_iff {p : range f → Prop} :
(∃ a : range f, p a) ↔ ∃ i, p ⟨f i, mem_range_self _⟩ :=
⟨λ ⟨⟨a, i, hi⟩, ha⟩, by { subst a, exact ⟨i, ha⟩}, λ ⟨i, hi⟩, ⟨_, hi⟩⟩
theorem range_iff_surjective : range f = univ ↔ surjective f :=
eq_univ_iff_forall
alias range_iff_surjective ↔ _ _root_.function.surjective.range_eq
@[simp] theorem image_univ {f : α → β} : f '' univ = range f :=
by { ext, simp [image, range] }
theorem image_subset_range (f : α → β) (s) : f '' s ⊆ range f :=
by rw ← image_univ; exact image_subset _ (subset_univ _)
theorem mem_range_of_mem_image (f : α → β) (s) {x : β} (h : x ∈ f '' s) : x ∈ range f :=
image_subset_range f s h
lemma nonempty.preimage' {s : set β} (hs : s.nonempty) {f : α → β} (hf : s ⊆ set.range f) :
(f ⁻¹' s).nonempty :=
let ⟨y, hy⟩ := hs, ⟨x, hx⟩ := hf hy in ⟨x, set.mem_preimage.2 $ hx.symm ▸ hy⟩
theorem range_comp (g : α → β) (f : ι → α) : range (g ∘ f) = g '' range f :=
subset.antisymm
(forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _))
(ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self)
theorem range_subset_iff : range f ⊆ s ↔ ∀ y, f y ∈ s :=
forall_range_iff
theorem range_eq_iff (f : α → β) (s : set β) :
range f = s ↔ (∀ a, f a ∈ s) ∧ ∀ b ∈ s, ∃ a, f a = b :=
by { rw ←range_subset_iff, exact le_antisymm_iff }
lemma range_comp_subset_range (f : α → β) (g : β → γ) : range (g ∘ f) ⊆ range g :=
by rw range_comp; apply image_subset_range
lemma range_nonempty_iff_nonempty : (range f).nonempty ↔ nonempty ι :=
⟨λ ⟨y, x, hxy⟩, ⟨x⟩, λ ⟨x⟩, ⟨f x, mem_range_self x⟩⟩
lemma range_nonempty [h : nonempty ι] (f : ι → α) : (range f).nonempty :=
range_nonempty_iff_nonempty.2 h
@[simp] lemma range_eq_empty_iff {f : ι → α} : range f = ∅ ↔ is_empty ι :=
by rw [← not_nonempty_iff, ← range_nonempty_iff_nonempty, not_nonempty_iff_eq_empty]
lemma range_eq_empty [is_empty ι] (f : ι → α) : range f = ∅ := range_eq_empty_iff.2 ‹_›
instance [nonempty ι] (f : ι → α) : nonempty (range f) := (range_nonempty f).to_subtype
@[simp] lemma image_union_image_compl_eq_range (f : α → β) :
(f '' s) ∪ (f '' sᶜ) = range f :=
by rw [← image_union, ← image_univ, ← union_compl_self]
lemma insert_image_compl_eq_range (f : α → β) (x : α) :
insert (f x) (f '' {x}ᶜ) = range f :=
begin
ext y, rw [mem_range, mem_insert_iff, mem_image],
split,
{ rintro (h | ⟨x', hx', h⟩),
{ exact ⟨x, h.symm⟩ },
{ exact ⟨x', h⟩ } },
{ rintro ⟨x', h⟩,
by_cases hx : x' = x,
{ left, rw [← h, hx] },
{ right, refine ⟨_, _, h⟩, rw mem_compl_singleton_iff, exact hx } }
end
theorem image_preimage_eq_inter_range {f : α → β} {t : set β} :
f '' (f ⁻¹' t) = t ∩ range f :=
ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩,
assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $
show y ∈ f ⁻¹' t, by simp [preimage, h_eq, hx]⟩
lemma image_preimage_eq_of_subset {f : α → β} {s : set β} (hs : s ⊆ range f) :
f '' (f ⁻¹' s) = s :=
by rw [image_preimage_eq_inter_range, inter_eq_self_of_subset_left hs]
lemma image_preimage_eq_iff {f : α → β} {s : set β} : f '' (f ⁻¹' s) = s ↔ s ⊆ range f :=
⟨by { intro h, rw [← h], apply image_subset_range }, image_preimage_eq_of_subset⟩
lemma subset_range_iff_exists_image_eq {f : α → β} {s : set β} :
s ⊆ range f ↔ ∃ t, f '' t = s :=
⟨λ h, ⟨_, image_preimage_eq_iff.2 h⟩, λ ⟨t, ht⟩, ht ▸ image_subset_range _ _⟩
lemma range_image (f : α → β) : range (image f) = 𝒫 (range f) :=
ext $ λ s, subset_range_iff_exists_image_eq.symm
lemma preimage_subset_preimage_iff {s t : set α} {f : β → α} (hs : s ⊆ range f) :
f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t :=
begin
split,
{ intros h x hx, rcases hs hx with ⟨y, rfl⟩, exact h hx },
intros h x, apply h
end
lemma preimage_eq_preimage' {s t : set α} {f : β → α} (hs : s ⊆ range f) (ht : t ⊆ range f) :
f ⁻¹' s = f ⁻¹' t ↔ s = t :=
begin
split,
{ intro h, apply subset.antisymm, rw [←preimage_subset_preimage_iff hs, h],
rw [←preimage_subset_preimage_iff ht, h] },
rintro rfl, refl
end
@[simp] theorem preimage_inter_range {f : α → β} {s : set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s :=
set.ext $ λ x, and_iff_left ⟨x, rfl⟩
@[simp] theorem preimage_range_inter {f : α → β} {s : set β} : f ⁻¹' (range f ∩ s) = f ⁻¹' s :=
by rw [inter_comm, preimage_inter_range]
theorem preimage_image_preimage {f : α → β} {s : set β} :
f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s :=
by rw [image_preimage_eq_inter_range, preimage_inter_range]
@[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id
@[simp] theorem range_id' : range (λ (x : α), x) = univ := range_id
@[simp] theorem _root_.prod.range_fst [nonempty β] : range (prod.fst : α × β → α) = univ :=
prod.fst_surjective.range_eq
@[simp] theorem _root_.prod.range_snd [nonempty α] : range (prod.snd : α × β → β) = univ :=
prod.snd_surjective.range_eq
@[simp] theorem range_eval {ι : Type*} {α : ι → Sort*} [Π i, nonempty (α i)] (i : ι) :
range (eval i : (Π i, α i) → α i) = univ :=
(surjective_eval i).range_eq
theorem is_compl_range_inl_range_inr : is_compl (range $ @sum.inl α β) (range sum.inr) :=
⟨by { rintro y ⟨⟨x₁, rfl⟩, ⟨x₂, _⟩⟩, cc },
by { rintro (x|y) -; [left, right]; exact mem_range_self _ }⟩
@[simp] theorem range_inl_union_range_inr : range (sum.inl : α → α ⊕ β) ∪ range sum.inr = univ :=
is_compl_range_inl_range_inr.sup_eq_top
@[simp] theorem range_inl_inter_range_inr : range (sum.inl : α → α ⊕ β) ∩ range sum.inr = ∅ :=
is_compl_range_inl_range_inr.inf_eq_bot
@[simp] theorem range_inr_union_range_inl : range (sum.inr : β → α ⊕ β) ∪ range sum.inl = univ :=
is_compl_range_inl_range_inr.symm.sup_eq_top
@[simp] theorem range_inr_inter_range_inl : range (sum.inr : β → α ⊕ β) ∩ range sum.inl = ∅ :=
is_compl_range_inl_range_inr.symm.inf_eq_bot
@[simp] theorem preimage_inl_image_inr (s : set β) : sum.inl ⁻¹' (@sum.inr α β '' s) = ∅ :=
by { ext, simp }
@[simp] theorem preimage_inr_image_inl (s : set α) : sum.inr ⁻¹' (@sum.inl α β '' s) = ∅ :=
by { ext, simp }
@[simp] theorem preimage_inl_range_inr : sum.inl ⁻¹' range (sum.inr : β → α ⊕ β) = ∅ :=
by rw [← image_univ, preimage_inl_image_inr]
@[simp] theorem preimage_inr_range_inl : sum.inr ⁻¹' range (sum.inl : α → α ⊕ β) = ∅ :=
by rw [← image_univ, preimage_inr_image_inl]
@[simp] lemma compl_range_inl : (range (sum.inl : α → α ⊕ β))ᶜ = range (sum.inr : β → α ⊕ β) :=
is_compl_range_inl_range_inr.compl_eq
@[simp] lemma compl_range_inr : (range (sum.inr : β → α ⊕ β))ᶜ = range (sum.inl : α → α ⊕ β) :=
is_compl_range_inl_range_inr.symm.compl_eq
@[simp] theorem range_quot_mk (r : α → α → Prop) : range (quot.mk r) = univ :=
(surjective_quot_mk r).range_eq
instance can_lift [can_lift α β] : can_lift (set α) (set β) :=
{ coe := λ s, can_lift.coe '' s,
cond := λ s, ∀ x ∈ s, can_lift.cond β x,
prf := λ s hs, subset_range_iff_exists_image_eq.mp (λ x hx, can_lift.prf _ (hs x hx)) }
@[simp] theorem range_quotient_mk [setoid α] : range (λx : α, ⟦x⟧) = univ :=
range_quot_mk _
lemma range_const_subset {c : α} : range (λ x : ι, c) ⊆ {c} :=
range_subset_iff.2 $ λ x, rfl
@[simp] lemma range_const : ∀ [nonempty ι] {c : α}, range (λx:ι, c) = {c}
| ⟨x⟩ c := subset.antisymm range_const_subset $
assume y hy, (mem_singleton_iff.1 hy).symm ▸ mem_range_self x
lemma range_subtype_map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀ x, p x → q (f x)) :
range (subtype.map f h) = coe ⁻¹' (f '' {x | p x}) :=
begin
ext ⟨x, hx⟩,
simp_rw [mem_preimage, mem_range, mem_image, subtype.exists, subtype.map, subtype.coe_mk,
mem_set_of, exists_prop]
end
lemma image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap :=
image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse
theorem preimage_singleton_nonempty {f : α → β} {y : β} :
(f ⁻¹' {y}).nonempty ↔ y ∈ range f :=
iff.rfl
theorem preimage_singleton_eq_empty {f : α → β} {y : β} :
f ⁻¹' {y} = ∅ ↔ y ∉ range f :=
not_nonempty_iff_eq_empty.symm.trans preimage_singleton_nonempty.not
lemma range_subset_singleton {f : ι → α} {x : α} : range f ⊆ {x} ↔ f = const ι x :=
by simp [range_subset_iff, funext_iff, mem_singleton]
lemma image_compl_preimage {f : α → β} {s : set β} : f '' ((f ⁻¹' s)ᶜ) = range f \ s :=
by rw [compl_eq_univ_diff, image_diff_preimage, image_univ]
/-- Any map `f : ι → β` factors through a map `range_factorization f : ι → range f`. -/
def range_factorization (f : ι → β) : ι → range f :=
λ i, ⟨f i, mem_range_self i⟩
lemma range_factorization_eq {f : ι → β} :
subtype.val ∘ range_factorization f = f :=
funext $ λ i, rfl
@[simp] lemma range_factorization_coe (f : ι → β) (a : ι) :
(range_factorization f a : β) = f a := rfl
@[simp] lemma coe_comp_range_factorization (f : ι → β) : coe ∘ range_factorization f = f := rfl
lemma surjective_onto_range : surjective (range_factorization f) :=
λ ⟨_, ⟨i, rfl⟩⟩, ⟨i, rfl⟩
lemma image_eq_range (f : α → β) (s : set α) : f '' s = range (λ(x : s), f x) :=
by { ext, split, rintro ⟨x, h1, h2⟩, exact ⟨⟨x, h1⟩, h2⟩, rintro ⟨⟨x, h1⟩, h2⟩, exact ⟨x, h1, h2⟩ }
@[simp] lemma sum.elim_range {α β γ : Type*} (f : α → γ) (g : β → γ) :
range (sum.elim f g) = range f ∪ range g :=
by simp [set.ext_iff, mem_range]
lemma range_ite_subset' {p : Prop} [decidable p] {f g : α → β} :
range (if p then f else g) ⊆ range f ∪ range g :=
begin
by_cases h : p, {rw if_pos h, exact subset_union_left _ _},
{rw if_neg h, exact subset_union_right _ _}
end
lemma range_ite_subset {p : α → Prop} [decidable_pred p] {f g : α → β} :
range (λ x, if p x then f x else g x) ⊆ range f ∪ range g :=
begin
rw range_subset_iff, intro x, by_cases h : p x,
simp [if_pos h, mem_union, mem_range_self],
simp [if_neg h, mem_union, mem_range_self]
end
@[simp] lemma preimage_range (f : α → β) : f ⁻¹' (range f) = univ :=
eq_univ_of_forall mem_range_self
/-- The range of a function from a `unique` type contains just the
function applied to its single value. -/
lemma range_unique [h : unique ι] : range f = {f default} :=
begin
ext x,
rw mem_range,
split,
{ rintros ⟨i, hi⟩,
rw h.uniq i at hi,
exact hi ▸ mem_singleton _ },
{ exact λ h, ⟨default, h.symm⟩ }
end
lemma range_diff_image_subset (f : α → β) (s : set α) :
range f \ f '' s ⊆ f '' sᶜ :=
λ y ⟨⟨x, h₁⟩, h₂⟩, ⟨x, λ h, h₂ ⟨x, h, h₁⟩, h₁⟩
lemma range_diff_image {f : α → β} (H : injective f) (s : set α) :
range f \ f '' s = f '' sᶜ :=
subset.antisymm (range_diff_image_subset f s) $ λ y ⟨x, hx, hy⟩, hy ▸
⟨mem_range_self _, λ ⟨x', hx', eq⟩, hx $ H eq ▸ hx'⟩
/-- We can use the axiom of choice to pick a preimage for every element of `range f`. -/
noncomputable def range_splitting (f : α → β) : range f → α := λ x, x.2.some
-- This can not be a `@[simp]` lemma because the head of the left hand side is a variable.
lemma apply_range_splitting (f : α → β) (x : range f) : f (range_splitting f x) = x :=
x.2.some_spec
attribute [irreducible] range_splitting
@[simp] lemma comp_range_splitting (f : α → β) : f ∘ range_splitting f = coe :=
by { ext, simp only [function.comp_app], apply apply_range_splitting, }
-- When `f` is injective, see also `equiv.of_injective`.
lemma left_inverse_range_splitting (f : α → β) :
left_inverse (range_factorization f) (range_splitting f) :=
λ x, by { ext, simp only [range_factorization_coe], apply apply_range_splitting, }
lemma range_splitting_injective (f : α → β) : injective (range_splitting f) :=
(left_inverse_range_splitting f).injective
lemma right_inverse_range_splitting {f : α → β} (h : injective f) :
right_inverse (range_factorization f) (range_splitting f) :=
(left_inverse_range_splitting f).right_inverse_of_injective $
λ x y hxy, h $ subtype.ext_iff.1 hxy
lemma preimage_range_splitting {f : α → β} (hf : injective f) :
preimage (range_splitting f) = image (range_factorization f) :=
(image_eq_preimage_of_inverse (right_inverse_range_splitting hf)
(left_inverse_range_splitting f)).symm
lemma is_compl_range_some_none (α : Type*) :
is_compl (range (some : α → option α)) {none} :=
⟨λ x ⟨⟨a, ha⟩, (hn : x = none)⟩, option.some_ne_none _ (ha.trans hn),
λ x hx, option.cases_on x (or.inr rfl) (λ x, or.inl $ mem_range_self _)⟩
@[simp] lemma compl_range_some (α : Type*) :
(range (some : α → option α))ᶜ = {none} :=
(is_compl_range_some_none α).compl_eq
@[simp] lemma range_some_inter_none (α : Type*) : range (some : α → option α) ∩ {none} = ∅ :=
(is_compl_range_some_none α).inf_eq_bot
@[simp] lemma range_some_union_none (α : Type*) : range (some : α → option α) ∪ {none} = univ :=
(is_compl_range_some_none α).sup_eq_top
@[simp] lemma insert_none_range_some (α : Type*) :
insert none (range (some : α → option α)) = univ :=
(is_compl_range_some_none α).symm.sup_eq_top
end range
end set
open set
namespace function
variables {ι : Sort*} {α : Type*} {β : Type*} {f : α → β}
lemma surjective.preimage_injective (hf : surjective f) : injective (preimage f) :=
assume s t, (preimage_eq_preimage hf).1
lemma injective.preimage_image (hf : injective f) (s : set α) : f ⁻¹' (f '' s) = s :=
preimage_image_eq s hf
lemma injective.preimage_surjective (hf : injective f) : surjective (preimage f) :=
by { intro s, use f '' s, rw hf.preimage_image }
lemma injective.subsingleton_image_iff (hf : injective f) {s : set α} :
(f '' s).subsingleton ↔ s.subsingleton :=
⟨subsingleton_of_image hf s, λ h, h.image f⟩
lemma surjective.image_preimage (hf : surjective f) (s : set β) : f '' (f ⁻¹' s) = s :=
image_preimage_eq s hf
lemma surjective.image_surjective (hf : surjective f) : surjective (image f) :=
by { intro s, use f ⁻¹' s, rw hf.image_preimage }
lemma surjective.nonempty_preimage (hf : surjective f) {s : set β} :
(f ⁻¹' s).nonempty ↔ s.nonempty :=
by rw [← nonempty_image_iff, hf.image_preimage]
lemma injective.image_injective (hf : injective f) : injective (image f) :=
by { intros s t h, rw [←preimage_image_eq s hf, ←preimage_image_eq t hf, h] }
lemma surjective.preimage_subset_preimage_iff {s t : set β} (hf : surjective f) :
f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t :=
by { apply preimage_subset_preimage_iff, rw [hf.range_eq], apply subset_univ }
lemma surjective.range_comp {ι' : Sort*} {f : ι → ι'} (hf : surjective f) (g : ι' → α) :
range (g ∘ f) = range g :=
ext $ λ y, (@surjective.exists _ _ _ hf (λ x, g x = y)).symm
lemma injective.nonempty_apply_iff {f : set α → set β} (hf : injective f)
(h2 : f ∅ = ∅) {s : set α} : (f s).nonempty ↔ s.nonempty :=
by rw [← ne_empty_iff_nonempty, ← h2, ← ne_empty_iff_nonempty, hf.ne_iff]
lemma injective.mem_range_iff_exists_unique (hf : injective f) {b : β} :
b ∈ range f ↔ ∃! a, f a = b :=
⟨λ ⟨a, h⟩, ⟨a, h, λ a' ha, hf (ha.trans h.symm)⟩, exists_unique.exists⟩
lemma injective.exists_unique_of_mem_range (hf : injective f) {b : β} (hb : b ∈ range f) :
∃! a, f a = b :=
hf.mem_range_iff_exists_unique.mp hb
theorem injective.compl_image_eq (hf : injective f) (s : set α) :
(f '' s)ᶜ = f '' sᶜ ∪ (range f)ᶜ :=
begin
ext y,
rcases em (y ∈ range f) with ⟨x, rfl⟩|hx,
{ simp [hf.eq_iff] },
{ rw [mem_range, not_exists] at hx,
simp [hx] }
end
lemma left_inverse.image_image {g : β → α} (h : left_inverse g f) (s : set α) :
g '' (f '' s) = s :=
by rw [← image_comp, h.comp_eq_id, image_id]
lemma left_inverse.preimage_preimage {g : β → α} (h : left_inverse g f) (s : set α) :
f ⁻¹' (g ⁻¹' s) = s :=
by rw [← preimage_comp, h.comp_eq_id, preimage_id]
end function
open function
lemma option.injective_iff {α β} {f : option α → β} :
injective f ↔ injective (f ∘ some) ∧ f none ∉ range (f ∘ some) :=
begin
simp only [mem_range, not_exists, (∘)],
refine ⟨λ hf, ⟨hf.comp (option.some_injective _), λ x, hf.ne $ option.some_ne_none _⟩, _⟩,
rintro ⟨h_some, h_none⟩ (_|a) (_|b) hab,
exacts [rfl, (h_none _ hab.symm).elim, (h_none _ hab).elim, congr_arg some (h_some hab)]
end
/-! ### Image and preimage on subtypes -/
namespace subtype
variable {α : Type*}
lemma coe_image {p : α → Prop} {s : set (subtype p)} :
coe '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} :=
set.ext $ assume a,
⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩,
assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩
@[simp] lemma coe_image_of_subset {s t : set α} (h : t ⊆ s) : coe '' {x : ↥s | ↑x ∈ t} = t :=
begin
ext x,
rw set.mem_image,
exact ⟨λ ⟨x', hx', hx⟩, hx ▸ hx', λ hx, ⟨⟨x, h hx⟩, hx, rfl⟩⟩,
end
lemma range_coe {s : set α} :
range (coe : s → α) = s :=
by { rw ← set.image_univ, simp [-set.image_univ, coe_image] }
/-- A variant of `range_coe`. Try to use `range_coe` if possible.
This version is useful when defining a new type that is defined as the subtype of something.
In that case, the coercion doesn't fire anymore. -/
lemma range_val {s : set α} :
range (subtype.val : s → α) = s :=
range_coe
/-- We make this the simp lemma instead of `range_coe`. The reason is that if we write
for `s : set α` the function `coe : s → α`, then the inferred implicit arguments of `coe` are
`coe α (λ x, x ∈ s)`. -/
@[simp] lemma range_coe_subtype {p : α → Prop} :
range (coe : subtype p → α) = {x | p x} :=
range_coe
@[simp] lemma coe_preimage_self (s : set α) : (coe : s → α) ⁻¹' s = univ :=
by rw [← preimage_range (coe : s → α), range_coe]
lemma range_val_subtype {p : α → Prop} :
range (subtype.val : subtype p → α) = {x | p x} :=
range_coe
theorem coe_image_subset (s : set α) (t : set s) : coe '' t ⊆ s :=
λ x ⟨y, yt, yvaleq⟩, by rw ←yvaleq; exact y.property
theorem coe_image_univ (s : set α) : (coe : s → α) '' set.univ = s :=
image_univ.trans range_coe
@[simp] theorem image_preimage_coe (s t : set α) :
(coe : s → α) '' (coe ⁻¹' t) = t ∩ s :=
image_preimage_eq_inter_range.trans $ congr_arg _ range_coe
theorem image_preimage_val (s t : set α) :
(subtype.val : s → α) '' (subtype.val ⁻¹' t) = t ∩ s :=
image_preimage_coe s t
theorem preimage_coe_eq_preimage_coe_iff {s t u : set α} :
((coe : s → α) ⁻¹' t = coe ⁻¹' u) ↔ t ∩ s = u ∩ s :=
by rw [← image_preimage_coe, ← image_preimage_coe, coe_injective.image_injective.eq_iff]
@[simp] theorem preimage_coe_inter_self (s t : set α) :
(coe : s → α) ⁻¹' (t ∩ s) = coe ⁻¹' t :=
by rw [preimage_coe_eq_preimage_coe_iff, inter_assoc, inter_self]
theorem preimage_val_eq_preimage_val_iff (s t u : set α) :
((subtype.val : s → α) ⁻¹' t = subtype.val ⁻¹' u) ↔ (t ∩ s = u ∩ s) :=
preimage_coe_eq_preimage_coe_iff
lemma exists_set_subtype {t : set α} (p : set α → Prop) :
(∃(s : set t), p (coe '' s)) ↔ ∃(s : set α), s ⊆ t ∧ p s :=
begin
split,
{ rintro ⟨s, hs⟩, refine ⟨coe '' s, _, hs⟩,
convert image_subset_range _ _, rw [range_coe] },
rintro ⟨s, hs₁, hs₂⟩, refine ⟨coe ⁻¹' s, _⟩,
rw [image_preimage_eq_of_subset], exact hs₂, rw [range_coe], exact hs₁
end
lemma preimage_coe_nonempty {s t : set α} : ((coe : s → α) ⁻¹' t).nonempty ↔ (s ∩ t).nonempty :=
by rw [inter_comm, ← image_preimage_coe, nonempty_image_iff]
lemma preimage_coe_eq_empty {s t : set α} : (coe : s → α) ⁻¹' t = ∅ ↔ s ∩ t = ∅ :=
by simp only [← not_nonempty_iff_eq_empty, preimage_coe_nonempty]
@[simp] lemma preimage_coe_compl (s : set α) : (coe : s → α) ⁻¹' sᶜ = ∅ :=
preimage_coe_eq_empty.2 (inter_compl_self s)
@[simp] lemma preimage_coe_compl' (s : set α) : (coe : sᶜ → α) ⁻¹' s = ∅ :=
preimage_coe_eq_empty.2 (compl_inter_self s)
end subtype
namespace set
/-! ### Lemmas about `inclusion`, the injection of subtypes induced by `⊆` -/
section inclusion
variables {α : Type*} {s t u : set α}
/-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/
def inclusion (h : s ⊆ t) : s → t :=
λ x : s, (⟨x, h x.2⟩ : t)
@[simp] lemma inclusion_self (x : s) : inclusion subset.rfl x = x := by { cases x, refl }
lemma inclusion_eq_id (h : s ⊆ s) : inclusion h = id := funext inclusion_self
@[simp] lemma inclusion_mk {h : s ⊆ t} (a : α) (ha : a ∈ s) : inclusion h ⟨a, ha⟩ = ⟨a, h ha⟩ := rfl
lemma inclusion_right (h : s ⊆ t) (x : t) (m : (x : α) ∈ s) : inclusion h ⟨x, m⟩ = x :=
by { cases x, refl }
@[simp] lemma inclusion_inclusion (hst : s ⊆ t) (htu : t ⊆ u) (x : s) :
inclusion htu (inclusion hst x) = inclusion (hst.trans htu) x :=
by { cases x, refl }
@[simp] lemma inclusion_comp_inclusion {α} {s t u : set α} (hst : s ⊆ t) (htu : t ⊆ u) :
inclusion htu ∘ inclusion hst = inclusion (hst.trans htu) :=
funext (inclusion_inclusion hst htu)
@[simp] lemma coe_inclusion (h : s ⊆ t) (x : s) : (inclusion h x : α) = (x : α) := rfl
lemma inclusion_injective (h : s ⊆ t) : injective (inclusion h)
| ⟨_, _⟩ ⟨_, _⟩ := subtype.ext_iff_val.2 ∘ subtype.ext_iff_val.1
@[simp] lemma range_inclusion (h : s ⊆ t) : range (inclusion h) = {x : t | (x:α) ∈ s} :=
by { ext ⟨x, hx⟩, simp [inclusion] }
lemma eq_of_inclusion_surjective {s t : set α} {h : s ⊆ t}
(h_surj : function.surjective (inclusion h)) : s = t :=
begin
rw [← range_iff_surjective, range_inclusion, eq_univ_iff_forall] at h_surj,
exact set.subset.antisymm h (λ x hx, h_surj ⟨x, hx⟩)
end
end inclusion
/-! ### Injectivity and surjectivity lemmas for image and preimage -/
section image_preimage
variables {α : Type u} {β : Type v} {f : α → β}
@[simp]
lemma preimage_injective : injective (preimage f) ↔ surjective f :=
begin
refine ⟨λ h y, _, surjective.preimage_injective⟩,
obtain ⟨x, hx⟩ : (f ⁻¹' {y}).nonempty,
{ rw [h.nonempty_apply_iff preimage_empty], apply singleton_nonempty },
exact ⟨x, hx⟩
end
@[simp]
lemma preimage_surjective : surjective (preimage f) ↔ injective f :=
begin
refine ⟨λ h x x' hx, _, injective.preimage_surjective⟩,
cases h {x} with s hs, have := mem_singleton x,
rwa [← hs, mem_preimage, hx, ← mem_preimage, hs, mem_singleton_iff, eq_comm] at this
end
@[simp] lemma image_surjective : surjective (image f) ↔ surjective f :=
begin
refine ⟨λ h y, _, surjective.image_surjective⟩,
cases h {y} with s hs,
have := mem_singleton y, rw [← hs] at this, rcases this with ⟨x, h1x, h2x⟩,
exact ⟨x, h2x⟩
end
@[simp] lemma image_injective : injective (image f) ↔ injective f :=
begin
refine ⟨λ h x x' hx, _, injective.image_injective⟩,
rw [← singleton_eq_singleton_iff], apply h,
rw [image_singleton, image_singleton, hx]
end
lemma preimage_eq_iff_eq_image {f : α → β} (hf : bijective f) {s t} :
f ⁻¹' s = t ↔ s = f '' t :=
by rw [← image_eq_image hf.1, hf.2.image_preimage]
lemma eq_preimage_iff_image_eq {f : α → β} (hf : bijective f) {s t} :
s = f ⁻¹' t ↔ f '' s = t :=
by rw [← image_eq_image hf.1, hf.2.image_preimage]
end image_preimage
/-!
### Images of binary and ternary functions
This section is very similar to `order.filter.n_ary`. Please keep them in sync.
-/
section n_ary_image
variables {α α' β β' γ γ' δ δ' ε ε' : Type*} {f f' : α → β → γ} {g g' : α → β → γ → δ}
variables {s s' : set α} {t t' : set β} {u u' : set γ} {a a' : α} {b b' : β} {c c' : γ} {d d' : δ}
/-- The image of a binary function `f : α → β → γ` as a function `set α → set β → set γ`.
Mathematically this should be thought of as the image of the corresponding function `α × β → γ`.
-/
def image2 (f : α → β → γ) (s : set α) (t : set β) : set γ :=
{c | ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c }
lemma mem_image2_eq : c ∈ image2 f s t = ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := rfl
@[simp] lemma mem_image2 : c ∈ image2 f s t ↔ ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := iff.rfl
lemma mem_image2_of_mem (h1 : a ∈ s) (h2 : b ∈ t) : f a b ∈ image2 f s t :=
⟨a, b, h1, h2, rfl⟩
lemma mem_image2_iff (hf : injective2 f) : f a b ∈ image2 f s t ↔ a ∈ s ∧ b ∈ t :=
⟨ by { rintro ⟨a', b', ha', hb', h⟩, rcases hf h with ⟨rfl, rfl⟩, exact ⟨ha', hb'⟩ },
λ ⟨ha, hb⟩, mem_image2_of_mem ha hb⟩
/-- image2 is monotone with respect to `⊆`. -/
lemma image2_subset (hs : s ⊆ s') (ht : t ⊆ t') : image2 f s t ⊆ image2 f s' t' :=
by { rintro _ ⟨a, b, ha, hb, rfl⟩, exact mem_image2_of_mem (hs ha) (ht hb) }
lemma image2_subset_left (ht : t ⊆ t') : image2 f s t ⊆ image2 f s t' := image2_subset subset.rfl ht
lemma image2_subset_right (hs : s ⊆ s') : image2 f s t ⊆ image2 f s' t :=
image2_subset hs subset.rfl
lemma image_subset_image2_left (hb : b ∈ t) : (λ a, f a b) '' s ⊆ image2 f s t :=
ball_image_of_ball $ λ a ha, mem_image2_of_mem ha hb
lemma image_subset_image2_right (ha : a ∈ s) : f a '' t ⊆ image2 f s t :=
ball_image_of_ball $ λ b, mem_image2_of_mem ha
lemma forall_image2_iff {p : γ → Prop} :
(∀ z ∈ image2 f s t, p z) ↔ ∀ (x ∈ s) (y ∈ t), p (f x y) :=
⟨λ h x hx y hy, h _ ⟨x, y, hx, hy, rfl⟩, λ h z ⟨x, y, hx, hy, hz⟩, hz ▸ h x hx y hy⟩
@[simp] lemma image2_subset_iff {u : set γ} :
image2 f s t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), f x y ∈ u :=
forall_image2_iff
lemma image2_union_left : image2 f (s ∪ s') t = image2 f s t ∪ image2 f s' t :=
begin
ext c, split,
{ rintros ⟨a, b, h1a|h2a, hb, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ },
{ rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, _, ‹_›, rfl⟩; simp [mem_union, *] }
end
lemma image2_union_right : image2 f s (t ∪ t') = image2 f s t ∪ image2 f s t' :=
begin
ext c, split,
{ rintros ⟨a, b, ha, h1b|h2b, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ },
{ rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, ‹_›, _, rfl⟩; simp [mem_union, *] }
end
@[simp] lemma image2_empty_left : image2 f ∅ t = ∅ := ext $ by simp
@[simp] lemma image2_empty_right : image2 f s ∅ = ∅ := ext $ by simp
lemma nonempty.image2 : s.nonempty → t.nonempty → (image2 f s t).nonempty :=
λ ⟨a, ha⟩ ⟨b, hb⟩, ⟨_, mem_image2_of_mem ha hb⟩
@[simp] lemma image2_nonempty_iff : (image2 f s t).nonempty ↔ s.nonempty ∧ t.nonempty :=
⟨λ ⟨_, a, b, ha, hb, _⟩, ⟨⟨a, ha⟩, b, hb⟩, λ h, h.1.image2 h.2⟩
lemma nonempty.of_image2_left (h : (image2 f s t).nonempty) : s.nonempty :=
(image2_nonempty_iff.1 h).1
lemma nonempty.of_image2_right (h : (image2 f s t).nonempty) : t.nonempty :=
(image2_nonempty_iff.1 h).2
@[simp] lemma image2_eq_empty_iff : image2 f s t = ∅ ↔ s = ∅ ∨ t = ∅ :=
by simp_rw [←not_nonempty_iff_eq_empty, image2_nonempty_iff, not_and_distrib]
lemma image2_inter_subset_left : image2 f (s ∩ s') t ⊆ image2 f s t ∩ image2 f s' t :=
by { rintro _ ⟨a, b, ⟨h1a, h2a⟩, hb, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }
lemma image2_inter_subset_right : image2 f s (t ∩ t') ⊆ image2 f s t ∩ image2 f s t' :=
by { rintro _ ⟨a, b, ha, ⟨h1b, h2b⟩, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }
@[simp] lemma image2_singleton_left : image2 f {a} t = f a '' t :=
ext $ λ x, by simp
@[simp] lemma image2_singleton_right : image2 f s {b} = (λ a, f a b) '' s :=
ext $ λ x, by simp
lemma image2_singleton : image2 f {a} {b} = {f a b} := by simp
@[congr] lemma image2_congr (h : ∀ (a ∈ s) (b ∈ t), f a b = f' a b) :
image2 f s t = image2 f' s t :=
by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨a, b, ha, hb, by rw h a ha b hb⟩ }
/-- A common special case of `image2_congr` -/
lemma image2_congr' (h : ∀ a b, f a b = f' a b) : image2 f s t = image2 f' s t :=
image2_congr (λ a _ b _, h a b)
/-- The image of a ternary function `f : α → β → γ → δ` as a function
`set α → set β → set γ → set δ`. Mathematically this should be thought of as the image of the
corresponding function `α × β × γ → δ`.
-/
def image3 (g : α → β → γ → δ) (s : set α) (t : set β) (u : set γ) : set δ :=
{d | ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d }
@[simp] lemma mem_image3 : d ∈ image3 g s t u ↔ ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d :=
iff.rfl
lemma image3_mono (hs : s ⊆ s') (ht : t ⊆ t') (hu : u ⊆ u') : image3 g s t u ⊆ image3 g s' t' u' :=
λ x, Exists₃.imp $ λ a b c ⟨ha, hb, hc, hx⟩, ⟨hs ha, ht hb, hu hc, hx⟩
@[congr] lemma image3_congr (h : ∀ (a ∈ s) (b ∈ t) (c ∈ u), g a b c = g' a b c) :
image3 g s t u = image3 g' s t u :=
by { ext x,
split; rintro ⟨a, b, c, ha, hb, hc, rfl⟩; exact ⟨a, b, c, ha, hb, hc, by rw h a ha b hb c hc⟩ }
/-- A common special case of `image3_congr` -/
lemma image3_congr' (h : ∀ a b c, g a b c = g' a b c) : image3 g s t u = image3 g' s t u :=
image3_congr (λ a _ b _ c _, h a b c)
lemma image2_image2_left (f : δ → γ → ε) (g : α → β → δ) :
image2 f (image2 g s t) u = image3 (λ a b c, f (g a b) c) s t u :=
begin
ext, split,
{ rintro ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ },
{ rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩ }
end
lemma image2_image2_right (f : α → δ → ε) (g : β → γ → δ) :
image2 f s (image2 g t u) = image3 (λ a b c, f a (g b c)) s t u :=
begin
ext, split,
{ rintro ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ },
{ rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩ }
end
lemma image_image2 (f : α → β → γ) (g : γ → δ) :
g '' image2 f s t = image2 (λ a b, g (f a b)) s t :=
begin
ext, split,
{ rintro ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ },
{ rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩ }
end
lemma image2_image_left (f : γ → β → δ) (g : α → γ) :
image2 f (g '' s) t = image2 (λ a b, f (g a) b) s t :=
begin
ext, split,
{ rintro ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ },
{ rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩ }
end
lemma image2_image_right (f : α → γ → δ) (g : β → γ) :
image2 f s (g '' t) = image2 (λ a b, f a (g b)) s t :=
begin
ext, split,
{ rintro ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ },
{ rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩ }
end
lemma image2_swap (f : α → β → γ) (s : set α) (t : set β) :
image2 f s t = image2 (λ a b, f b a) t s :=
by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨b, a, hb, ha, rfl⟩ }
@[simp] lemma image2_left (h : t.nonempty) : image2 (λ x y, x) s t = s :=
by simp [nonempty_def.mp h, ext_iff]
@[simp] lemma image2_right (h : s.nonempty) : image2 (λ x y, y) s t = t :=
by simp [nonempty_def.mp h, ext_iff]
lemma image2_assoc {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'}
(h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) :
image2 f (image2 g s t) u = image2 f' s (image2 g' t u) :=
by simp only [image2_image2_left, image2_image2_right, h_assoc]
lemma image2_comm {g : β → α → γ} (h_comm : ∀ a b, f a b = g b a) : image2 f s t = image2 g t s :=
(image2_swap _ _ _).trans $ by simp_rw h_comm
lemma image2_left_comm {f : α → δ → ε} {g : β → γ → δ} {f' : α → γ → δ'} {g' : β → δ' → ε}
(h_left_comm : ∀ a b c, f a (g b c) = g' b (f' a c)) :
image2 f s (image2 g t u) = image2 g' t (image2 f' s u) :=
by { rw [image2_swap f', image2_swap f], exact image2_assoc (λ _ _ _, h_left_comm _ _ _) }
lemma image2_right_comm {f : δ → γ → ε} {g : α → β → δ} {f' : α → γ → δ'} {g' : δ' → β → ε}
(h_right_comm : ∀ a b c, f (g a b) c = g' (f' a c) b) :
image2 f (image2 g s t) u = image2 g' (image2 f' s u) t :=
by { rw [image2_swap g, image2_swap g'], exact image2_assoc (λ _ _ _, h_right_comm _ _ _) }
lemma image_image2_distrib {g : γ → δ} {f' : α' → β' → δ} {g₁ : α → α'} {g₂ : β → β'}
(h_distrib : ∀ a b, g (f a b) = f' (g₁ a) (g₂ b)) :
(image2 f s t).image g = image2 f' (s.image g₁) (t.image g₂) :=
by simp_rw [image_image2, image2_image_left, image2_image_right, h_distrib]
/-- Symmetric of `set.image2_image_left_comm`. -/
lemma image_image2_distrib_left {g : γ → δ} {f' : α' → β → δ} {g' : α → α'}
(h_distrib : ∀ a b, g (f a b) = f' (g' a) b) :
(image2 f s t).image g = image2 f' (s.image g') t :=
(image_image2_distrib h_distrib).trans $ by rw image_id'
/-- Symmetric of `set.image_image2_right_comm`. -/
lemma image_image2_distrib_right {g : γ → δ} {f' : α → β' → δ} {g' : β → β'}
(h_distrib : ∀ a b, g (f a b) = f' a (g' b)) :
(image2 f s t).image g = image2 f' s (t.image g') :=
(image_image2_distrib h_distrib).trans $ by rw image_id'
/-- Symmetric of `set.image_image2_distrib_left`. -/
lemma image2_image_left_comm {f : α' → β → γ} {g : α → α'} {f' : α → β → δ} {g' : δ → γ}
(h_left_comm : ∀ a b, f (g a) b = g' (f' a b)) :
image2 f (s.image g) t = (image2 f' s t).image g' :=
(image_image2_distrib_left $ λ a b, (h_left_comm a b).symm).symm
/-- Symmetric of `set.image_image2_distrib_right`. -/
lemma image_image2_right_comm {f : α → β' → γ} {g : β → β'} {f' : α → β → δ} {g' : δ → γ}
(h_right_comm : ∀ a b, f a (g b) = g' (f' a b)) :
image2 f s (t.image g) = (image2 f' s t).image g' :=
(image_image2_distrib_right $ λ a b, (h_right_comm a b).symm).symm
/-- The other direction does not hold because of the `s`-`s` cross terms on the RHS. -/
lemma image2_distrib_subset_left {f : α → δ → ε} {g : β → γ → δ} {f₁ : α → β → β'} {f₂ : α → γ → γ'}
{g' : β' → γ' → ε} (h_distrib : ∀ a b c, f a (g b c) = g' (f₁ a b) (f₂ a c)) :
image2 f s (image2 g t u) ⊆ image2 g' (image2 f₁ s t) (image2 f₂ s u) :=
begin
rintro _ ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩,
rw h_distrib,
exact mem_image2_of_mem (mem_image2_of_mem ha hb) (mem_image2_of_mem ha hc),
end
/-- The other direction does not hold because of the `u`-`u` cross terms on the RHS. -/
lemma image2_distrib_subset_right {f : δ → γ → ε} {g : α → β → δ} {f₁ : α → γ → α'}
{f₂ : β → γ → β'} {g' : α' → β' → ε} (h_distrib : ∀ a b c, f (g a b) c = g' (f₁ a c) (f₂ b c)) :
image2 f (image2 g s t) u ⊆ image2 g' (image2 f₁ s u) (image2 f₂ t u) :=
begin
rintro _ ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩,
rw h_distrib,
exact mem_image2_of_mem (mem_image2_of_mem ha hc) (mem_image2_of_mem hb hc),
end
lemma image_image2_antidistrib {g : γ → δ} {f' : β' → α' → δ} {g₁ : β → β'} {g₂ : α → α'}
(h_antidistrib : ∀ a b, g (f a b) = f' (g₁ b) (g₂ a)) :
(image2 f s t).image g = image2 f' (t.image g₁) (s.image g₂) :=
by { rw image2_swap f, exact image_image2_distrib (λ _ _, h_antidistrib _ _) }
/-- Symmetric of `set.image2_image_left_anticomm`. -/
lemma image_image2_antidistrib_left {g : γ → δ} {f' : β' → α → δ} {g' : β → β'}
(h_antidistrib : ∀ a b, g (f a b) = f' (g' b) a) :
(image2 f s t).image g = image2 f' (t.image g') s :=
(image_image2_antidistrib h_antidistrib).trans $ by rw image_id'
/-- Symmetric of `set.image_image2_right_anticomm`. -/
lemma image_image2_antidistrib_right {g : γ → δ} {f' : β → α' → δ} {g' : α → α'}
(h_antidistrib : ∀ a b, g (f a b) = f' b (g' a)) :
(image2 f s t).image g = image2 f' t (s.image g') :=
(image_image2_antidistrib h_antidistrib).trans $ by rw image_id'
/-- Symmetric of `set.image_image2_antidistrib_left`. -/
lemma image2_image_left_anticomm {f : α' → β → γ} {g : α → α'} {f' : β → α → δ} {g' : δ → γ}
(h_left_anticomm : ∀ a b, f (g a) b = g' (f' b a)) :
image2 f (s.image g) t = (image2 f' t s).image g' :=
(image_image2_antidistrib_left $ λ a b, (h_left_anticomm b a).symm).symm
/-- Symmetric of `set.image_image2_antidistrib_right`. -/
lemma image_image2_right_anticomm {f : α → β' → γ} {g : β → β'} {f' : β → α → δ} {g' : δ → γ}
(h_right_anticomm : ∀ a b, f a (g b) = g' (f' b a)) :
image2 f s (t.image g) = (image2 f' t s).image g' :=
(image_image2_antidistrib_right $ λ a b, (h_right_anticomm b a).symm).symm
end n_ary_image
end set
namespace subsingleton
variables {α : Type*} [subsingleton α]
lemma eq_univ_of_nonempty {s : set α} : s.nonempty → s = univ :=
λ ⟨x, hx⟩, eq_univ_of_forall $ λ y, subsingleton.elim x y ▸ hx
@[elab_as_eliminator]
lemma set_cases {p : set α → Prop} (h0 : p ∅) (h1 : p univ) (s) : p s :=
s.eq_empty_or_nonempty.elim (λ h, h.symm ▸ h0) $ λ h, (eq_univ_of_nonempty h).symm ▸ h1
lemma mem_iff_nonempty {α : Type*} [subsingleton α] {s : set α} {x : α} :
x ∈ s ↔ s.nonempty :=
⟨λ hx, ⟨x, hx⟩, λ ⟨y, hy⟩, subsingleton.elim y x ▸ hy⟩
end subsingleton
/-! ### Decidability instances for sets -/
namespace set
variables {α : Type u} (s t : set α) (a : α)
instance decidable_sdiff [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s \ t) :=
(by apply_instance : decidable (a ∈ s ∧ a ∉ t))
instance decidable_inter [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s ∩ t) :=
(by apply_instance : decidable (a ∈ s ∧ a ∈ t))
instance decidable_union [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s ∪ t) :=
(by apply_instance : decidable (a ∈ s ∨ a ∈ t))
instance decidable_compl [decidable (a ∈ s)] : decidable (a ∈ sᶜ) :=
(by apply_instance : decidable (a ∉ s))
instance decidable_emptyset : decidable_pred (∈ (∅ : set α)) :=
λ _, decidable.is_false (by simp)
instance decidable_univ : decidable_pred (∈ (set.univ : set α)) :=
λ _, decidable.is_true (by simp)
instance decidable_set_of (p : α → Prop) [decidable (p a)] : decidable (a ∈ {a | p a}) :=
by assumption
end set
|
7f0ab5e7b25219c9e6cf2ffb7ca5a18dfc8129d0 | 492a7e27d49633a89f7ce6e1e28f676b062fcbc9 | /src/monoidal_categories_reboot/hypergraph_category.lean | 1e52366d630c176efda6b30d2a2d4f9b67db3c87 | [
"Apache-2.0"
] | permissive | semorrison/monoidal-categories-reboot | 9edba30277de48a234b63813cf85b171772ce36f | 48b5f1d535daba4e591672042a298ac36be2e6dd | refs/heads/master | 1,642,472,396,149 | 1,560,587,477,000 | 1,560,587,477,000 | 156,465,626 | 0 | 1 | null | 1,541,549,278,000 | 1,541,549,278,000 | null | UTF-8 | Lean | false | false | 2,957 | lean | -- Copyright (c) 2018 Michael Jendrusch. All rights reserved.
import .monoidal_category
import .braided_monoidal_category
import .monoid_object
universes v u
namespace category_theory.hypergraph
open category_theory.monoidal
open category_theory.monoidal.monoidal_category
open category_theory.monoidal.braided_monoidal_category
@[reducible]
def reassociate_and_braid_product {C : Type u} (X Y : C) [symmetric_monoidal_category.{v} C] :=
(associator X Y (X ⊗ Y)).hom ≫ ((𝟙 X) ⊗ (associator Y X Y).inv) ≫
((𝟙 X) ⊗ (braiding Y X).hom ⊗ (𝟙 Y)) ≫ (associator X (X ⊗ Y) Y).inv ≫
((associator X X Y).inv ⊗ (𝟙 Y)) ≫ (associator (X ⊗ X) Y Y).hom
@[reducible]
def reassociate_and_braid_coproduct {C : Type u} (X Y : C) [symmetric_monoidal_category.{v} C] :=
(associator X X (Y ⊗ Y)).hom ≫ ((𝟙 X) ⊗ (associator X Y Y).inv) ≫
((𝟙 X) ⊗ (braiding X Y).hom ⊗ (𝟙 Y)) ≫
((𝟙 X) ⊗ (associator Y X Y).hom) ≫ (associator X Y (X ⊗ Y)).inv
class hypergraph_category (C : Type u) extends symmetric_monoidal_category.{v} C :=
-- each object is equipped with the structure of a special commutative Frobenius monoid:
(frobenius_structure : Π X : C, special_commutative_frobenius_object X)
-- the Frobenius structure and the tensor product interact in the obvious way:
(product_tensor' : Π X Y : C,
reassociate_and_braid_product X Y ≫
((frobenius_structure X).product ⊗ (frobenius_structure Y).product)
= (frobenius_structure (X ⊗ Y)).product
. obviously)
(coproduct_tensor' : Π X Y : C,
((frobenius_structure X).coproduct ⊗ (frobenius_structure Y).coproduct) ≫
reassociate_and_braid_coproduct X Y
= (frobenius_structure (X ⊗ Y)).coproduct
. obviously)
(unit_tensor' : Π X Y : C,
(left_unitor tensor_unit).inv ≫
((frobenius_structure X).unit ⊗ (frobenius_structure Y).unit)
= (frobenius_structure (X ⊗ Y)).unit
. obviously)
(counit_tensor' : Π X Y : C,
((frobenius_structure X).counit ⊗ (frobenius_structure Y).counit) ≫
(left_unitor tensor_unit).hom
= (frobenius_structure (X ⊗ Y)).counit
. obviously)
restate_axiom hypergraph_category.product_tensor'
attribute [search] hypergraph_category.product_tensor
restate_axiom hypergraph_category.coproduct_tensor'
attribute [search] hypergraph_category.coproduct_tensor
restate_axiom hypergraph_category.unit_tensor'
attribute [search] hypergraph_category.unit_tensor
restate_axiom hypergraph_category.counit_tensor'
attribute [search] hypergraph_category.counit_tensor
end category_theory.hypergraph
|
3631478bc1b35f579dbdec8f1057ca9801a21b44 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/valuation/valuation_subring.lean | f814c27e93924b2f3655c7d4ab5ab3ed02606157 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 13,793 | lean | /-
Copyright (c) 2022 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz, Junyan Xu
-/
import ring_theory.valuation.valuation_ring
import ring_theory.localization.as_subring
import algebraic_geometry.prime_spectrum.basic
/-!
# Valuation subrings of a field
# Projects
The order structure on `valuation_subring K`.
-/
open_locale classical
noncomputable theory
variables (K : Type*) [field K]
/-- A valuation subring of a field `K` is a subring `A` such that for every `x : K`,
either `x ∈ A` or `x⁻¹ ∈ K`. -/
structure valuation_subring extends subring K :=
(mem_or_inv_mem' : ∀ x : K, x ∈ carrier ∨ x⁻¹ ∈ carrier)
namespace valuation_subring
variables {K} (A : valuation_subring K)
instance : set_like (valuation_subring K) K :=
{ coe := λ A, A.to_subring,
coe_injective' := by { rintro ⟨⟨⟩⟩ ⟨⟨⟩⟩ _, congr' } }
@[simp] lemma mem_carrier (x : K) : x ∈ A.carrier ↔ x ∈ A := iff.refl _
@[simp] lemma mem_to_subring (x : K) : x ∈ A.to_subring ↔ x ∈ A := iff.refl _
@[ext] lemma ext (A B : valuation_subring K)
(h : ∀ x, x ∈ A ↔ x ∈ B) : A = B := set_like.ext h
lemma zero_mem : (0 : K) ∈ A := A.to_subring.zero_mem
lemma one_mem : (1 : K) ∈ A := A.to_subring.one_mem
lemma add_mem (x y : K) : x ∈ A → y ∈ A → x + y ∈ A := A.to_subring.add_mem
lemma mul_mem (x y : K) : x ∈ A → y ∈ A → x * y ∈ A := A.to_subring.mul_mem
lemma neg_mem (x : K) : x ∈ A → (-x) ∈ A := A.to_subring.neg_mem
lemma mem_or_inv_mem (x : K) : x ∈ A ∨ x⁻¹ ∈ A := A.mem_or_inv_mem' _
instance : comm_ring A := show comm_ring A.to_subring, by apply_instance
instance : is_domain A := show is_domain A.to_subring, by apply_instance
instance : has_top (valuation_subring K) := has_top.mk $
{ mem_or_inv_mem' := λ x, or.inl trivial,
..(⊤ : subring K) }
lemma mem_top (x : K) : x ∈ (⊤ : valuation_subring K) := trivial
lemma le_top : A ≤ ⊤ := λ a ha, mem_top _
instance : order_top (valuation_subring K) :=
{ top := ⊤,
le_top := le_top }
instance : inhabited (valuation_subring K) := ⟨⊤⟩
instance : valuation_ring A :=
{ cond := λ a b,
begin
by_cases (b : K) = 0, { use 0, left, ext, simp [h] },
by_cases (a : K) = 0, { use 0, right, ext, simp [h] },
cases A.mem_or_inv_mem (a/b) with hh hh,
{ use ⟨a/b,hh⟩, right, ext, field_simp, ring },
{ rw (show (a/b : K)⁻¹ = b/a, by field_simp) at hh,
use ⟨b/a,hh⟩, left, ext, field_simp, ring },
end }
instance : algebra A K :=
show algebra A.to_subring K, by apply_instance
@[simp]
lemma algebra_map_apply (a : A) : algebra_map A K a = a := rfl
instance : is_fraction_ring A K :=
{ map_units := λ ⟨y,hy⟩,
(units.mk0 (y : K) (λ c, non_zero_divisors.ne_zero hy $ subtype.ext c)).is_unit,
surj := λ z, begin
by_cases z = 0, { use (0,1), simp [h] },
cases A.mem_or_inv_mem z with hh hh,
{ use (⟨z,hh⟩,1), simp },
{ refine ⟨⟨1,⟨⟨_,hh⟩,_⟩⟩, mul_inv_cancel h⟩,
exact mem_non_zero_divisors_iff_ne_zero.2 (λ c, h (inv_eq_zero.mp (congr_arg coe c))) },
end,
eq_iff_exists := λ a b, ⟨ λ h, ⟨1, by { ext, simpa using h }⟩, λ ⟨c,h⟩,
congr_arg coe ((mul_eq_mul_right_iff.1 h).resolve_right (non_zero_divisors.ne_zero c.2)) ⟩ }
/-- The value group of the valuation associated to `A`. -/
@[derive linear_ordered_comm_group_with_zero]
def value_group := valuation_ring.value_group A K
/-- Any valuation subring of `K` induces a natural valuation on `K`. -/
def valuation : valuation K A.value_group := valuation_ring.valuation A K
instance inhabited_value_group : inhabited A.value_group := ⟨A.valuation 0⟩
lemma valuation_le_one (a : A) : A.valuation a ≤ 1 :=
(valuation_ring.mem_integer_iff A K _).2 ⟨a,rfl⟩
lemma mem_of_valuation_le_one (x : K) (h : A.valuation x ≤ 1) : x ∈ A :=
let ⟨a,ha⟩ := (valuation_ring.mem_integer_iff A K x).1 h in ha ▸ a.2
lemma valuation_le_one_iff (x : K) : A.valuation x ≤ 1 ↔ x ∈ A :=
⟨mem_of_valuation_le_one _ _, λ ha, A.valuation_le_one ⟨x,ha⟩⟩
lemma valuation_eq_iff (x y : K) : A.valuation x = A.valuation y ↔
∃ a : Aˣ, (a : K) * y = x := quotient.eq'
lemma valuation_le_iff (x y : K) : A.valuation x ≤ A.valuation y ↔
∃ a : A, (a : K) * y = x := iff.rfl
lemma valuation_surjective : function.surjective A.valuation := surjective_quot_mk _
lemma valuation_unit (a : Aˣ) : A.valuation a = 1 :=
by { rw [← A.valuation.map_one, valuation_eq_iff], use a, simp }
lemma valuation_eq_one_iff (a : A) : is_unit a ↔ A.valuation a = 1 :=
⟨ λ h, A.valuation_unit h.unit,
λ h, begin
have ha : (a : K) ≠ 0,
{ intro c, rw [c, A.valuation.map_zero] at h, exact zero_ne_one h },
have ha' : (a : K)⁻¹ ∈ A,
{ rw [← valuation_le_one_iff, A.valuation.map_inv, h, inv_one] },
apply is_unit_of_mul_eq_one a ⟨a⁻¹, ha'⟩, ext, field_simp,
end ⟩
lemma valuation_lt_one_or_eq_one (a : A) : A.valuation a < 1 ∨ A.valuation a = 1 :=
lt_or_eq_of_le (A.valuation_le_one a)
lemma valuation_lt_one_iff (a : A) : a ∈ local_ring.maximal_ideal A ↔ A.valuation a < 1 :=
begin
rw local_ring.mem_maximal_ideal,
dsimp [nonunits], rw valuation_eq_one_iff,
exact (A.valuation_le_one a).lt_iff_ne.symm,
end
/-- A subring `R` of `K` such that for all `x : K` either `x ∈ R` or `x⁻¹ ∈ R` is
a valuation subring of `K`. -/
def of_subring (R : subring K) (hR : ∀ x : K, x ∈ R ∨ x⁻¹ ∈ R) : valuation_subring K :=
{ mem_or_inv_mem' := hR, ..R }
@[simp]
lemma mem_of_subring (R : subring K) (hR : ∀ x : K, x ∈ R ∨ x⁻¹ ∈ R) (x : K) :
x ∈ of_subring R hR ↔ x ∈ R := iff.refl _
/-- An overring of a valuation ring is a valuation ring. -/
def of_le (R : valuation_subring K) (S : subring K) (h : R.to_subring ≤ S) :
valuation_subring K :=
{ mem_or_inv_mem' := λ x, (R.mem_or_inv_mem x).imp (@h x) (@h _), ..S}
section order
instance : semilattice_sup (valuation_subring K) :=
{ sup := λ R S, of_le R (R.to_subring ⊔ S.to_subring) $ le_sup_left,
le_sup_left := λ R S x hx, (le_sup_left : R.to_subring ≤ R.to_subring ⊔ S.to_subring) hx,
le_sup_right := λ R S x hx, (le_sup_right : S.to_subring ≤ R.to_subring ⊔ S.to_subring) hx,
sup_le := λ R S T hR hT x hx, (sup_le hR hT : R.to_subring ⊔ S.to_subring ≤ T.to_subring) hx,
..(infer_instance : partial_order (valuation_subring K)) }
/-- The ring homomorphism induced by the partial order. -/
def inclusion (R S : valuation_subring K) (h : R ≤ S) : R →+* S :=
subring.inclusion h
/-- The canonical ring homomorphism from a valuation ring to its field of fractions. -/
def subtype (R : valuation_subring K) : R →+* K :=
subring.subtype R.to_subring
/-- The canonical map on value groups induced by a coarsening of valuation rings. -/
def map_of_le (R S : valuation_subring K) (h : R ≤ S) :
R.value_group →*₀ S.value_group :=
{ to_fun := quotient.map' id $ λ x y ⟨u,hu⟩, ⟨units.map (R.inclusion S h).to_monoid_hom u, hu⟩,
map_zero' := rfl,
map_one' := rfl,
map_mul' := by { rintro ⟨⟩ ⟨⟩, refl } }
@[mono]
lemma monotone_map_of_le (R S : valuation_subring K) (h : R ≤ S) :
monotone (R.map_of_le S h) :=
by { rintros ⟨⟩ ⟨⟩ ⟨a,ha⟩, exact ⟨R.inclusion S h a, ha⟩ }
@[simp]
lemma map_of_le_comp_valuation (R S : valuation_subring K) (h : R ≤ S) :
R.map_of_le S h ∘ R.valuation = S.valuation := by { ext, refl }
@[simp]
lemma map_of_le_valuation_apply (R S : valuation_subring K) (h : R ≤ S) (x : K) :
R.map_of_le S h (R.valuation x) = S.valuation x := rfl
/-- The ideal corresponding to a coarsening of a valuation ring. -/
def ideal_of_le (R S : valuation_subring K) (h : R ≤ S) : ideal R :=
(local_ring.maximal_ideal S).comap (R.inclusion S h)
instance prime_ideal_of_le (R S : valuation_subring K) (h : R ≤ S) :
(ideal_of_le R S h).is_prime := (local_ring.maximal_ideal S).comap_is_prime _
/-- The coarsening of a valuation ring associated to a prime ideal. -/
def of_prime (A : valuation_subring K) (P : ideal A) [P.is_prime] :
valuation_subring K :=
of_le A (localization.subalgebra.of_field K P.prime_compl $
le_non_zero_divisors_of_no_zero_divisors $ not_not_intro P.zero_mem).to_subring $
λ a ha, subalgebra.algebra_map_mem _ (⟨a,ha⟩ : A)
instance of_prime_algebra (A : valuation_subring K) (P : ideal A) [P.is_prime] :
algebra A (A.of_prime P) := subalgebra.algebra _
instance of_prime_scalar_tower (A : valuation_subring K) (P : ideal A) [P.is_prime] :
is_scalar_tower A (A.of_prime P) K := is_scalar_tower.subalgebra' A K K _
instance of_prime_localization (A : valuation_subring K) (P : ideal A) [P.is_prime] :
is_localization.at_prime (A.of_prime P) P :=
by apply localization.subalgebra.is_localization_of_field K
lemma le_of_prime (A : valuation_subring K) (P : ideal A) [P.is_prime] :
A ≤ of_prime A P :=
λ a ha, subalgebra.algebra_map_mem _ (⟨a,ha⟩ : A)
lemma of_prime_valuation_eq_one_iff_mem_prime_compl
(A : valuation_subring K)
(P : ideal A) [P.is_prime] (x : A) :
(of_prime A P).valuation x = 1 ↔ x ∈ P.prime_compl :=
begin
rw [← is_localization.at_prime.is_unit_to_map_iff (A.of_prime P) P x, valuation_eq_one_iff], refl,
end
@[simp]
lemma ideal_of_le_of_prime (A : valuation_subring K) (P : ideal A) [P.is_prime] :
ideal_of_le A (of_prime A P) (le_of_prime A P) = P :=
by { ext, apply is_localization.at_prime.to_map_mem_maximal_iff }
@[simp]
lemma of_prime_ideal_of_le (R S : valuation_subring K) (h : R ≤ S) :
of_prime R (ideal_of_le R S h) = S :=
begin
ext x, split,
{ rintro ⟨a,r,hr,rfl⟩, apply mul_mem, { exact h a.2 },
{ rw [← valuation_le_one_iff, valuation.map_inv, ← inv_one, inv_le_inv₀],
{ exact not_lt.1 ((not_iff_not.2 $ valuation_lt_one_iff S _).1 hr) },
{ intro hh, erw [valuation.zero_iff, subring.coe_eq_zero_iff] at hh,
apply hr, rw hh, apply ideal.zero_mem (R.ideal_of_le S h) },
{ exact one_ne_zero } } },
{ intro hx, by_cases hr : x ∈ R, { exact R.le_of_prime _ hr },
have : x ≠ 0 := λ h, hr (by { rw h, exact R.zero_mem }),
replace hr := (R.mem_or_inv_mem x).resolve_left hr,
{ use [1, x⁻¹, hr], split,
{ change (⟨x⁻¹, h hr⟩ : S) ∉ nonunits S,
erw [mem_nonunits_iff, not_not],
apply is_unit_of_mul_eq_one _ (⟨x,hx⟩ : S),
ext, field_simp },
{ field_simp } } },
end
lemma of_prime_le_of_le (P Q : ideal A) [P.is_prime] [Q.is_prime]
(h : P ≤ Q) : of_prime A Q ≤ of_prime A P :=
λ x ⟨a, s, hs, he⟩, ⟨a, s, λ c, hs (h c), he⟩
lemma ideal_of_le_le_of_le (R S : valuation_subring K)
(hR : A ≤ R) (hS : A ≤ S) (h : R ≤ S) :
ideal_of_le A S hS ≤ ideal_of_le A R hR :=
λ x hx, (valuation_lt_one_iff R _).2 begin
by_contra c, push_neg at c, replace c := monotone_map_of_le R S h c,
rw [(map_of_le _ _ _).map_one, map_of_le_valuation_apply] at c,
apply not_le_of_lt ((valuation_lt_one_iff S _).1 hx) c,
end
/-- The equivalence between coarsenings of a valuation ring and its prime ideals.-/
@[simps]
def prime_spectrum_equiv :
prime_spectrum A ≃ { S | A ≤ S } :=
{ to_fun := λ P, ⟨of_prime A P.as_ideal, le_of_prime _ _⟩,
inv_fun := λ S, ⟨ideal_of_le _ S S.2, infer_instance⟩,
left_inv := λ P, by { ext1, simpa },
right_inv := λ S, by { ext1, simp } }
/-- An ordered variant of `prime_spectrum_equiv`. -/
@[simps]
def prime_spectrum_order_equiv : (prime_spectrum A)ᵒᵈ ≃o {S | A ≤ S} :=
{ map_rel_iff' := λ P Q,
⟨ λ h, begin
have := ideal_of_le_le_of_le A _ _ _ _ h,
iterate 2 { erw ideal_of_le_of_prime at this },
exact this,
end,
λ h, by { apply of_prime_le_of_le, exact h } ⟩,
..(prime_spectrum_equiv A) }
instance linear_order_overring : linear_order { S | A ≤ S } :=
{ le_total := let i : is_total (prime_spectrum A) (≤) := (subtype.rel_embedding _ _).is_total in
by exactI (prime_spectrum_order_equiv A).symm.to_rel_embedding.is_total.total,
decidable_le := infer_instance,
..(infer_instance : partial_order _) }
end order
end valuation_subring
namespace valuation
variables {K} {Γ Γ₁ Γ₂ : Type*}
[linear_ordered_comm_group_with_zero Γ]
[linear_ordered_comm_group_with_zero Γ₁]
[linear_ordered_comm_group_with_zero Γ₂]
(v : valuation K Γ)
(v₁ : valuation K Γ₁)
(v₂ : valuation K Γ₂)
/-- The valuation subring associated to a valuation. -/
def valuation_subring : valuation_subring K :=
{ mem_or_inv_mem' := begin
intros x,
cases le_or_lt (v x) 1,
{ left, exact h },
{ right, change v x⁻¹ ≤ 1,
rw [v.map_inv, ← inv_one, inv_le_inv₀],
{ exact le_of_lt h },
{ intro c, simpa [c] using h },
{ exact one_ne_zero } }
end,
.. v.integer }
@[simp]
lemma mem_valuation_subring_iff (x : K) : x ∈ v.valuation_subring ↔ v x ≤ 1 := iff.refl _
lemma is_equiv_iff_valuation_subring : v₁.is_equiv v₂ ↔
v₁.valuation_subring = v₂.valuation_subring :=
begin
split,
{ intros h, ext x, specialize h x 1, simpa using h },
{ intros h, apply is_equiv_of_val_le_one,
intros x,
have : x ∈ v₁.valuation_subring ↔ x ∈ v₂.valuation_subring, by rw h,
simpa using this }
end
lemma is_equiv_valuation_valuation_subring :
v.is_equiv v.valuation_subring.valuation :=
begin
rw [is_equiv_iff_val_le_one],
intro x,
rw valuation_subring.valuation_le_one_iff,
refl,
end
end valuation
namespace valuation_subring
variables {K} (A : valuation_subring K)
@[simp]
lemma valuation_subring_valuation : A.valuation.valuation_subring = A :=
by { ext, rw ← A.valuation_le_one_iff, refl }
end valuation_subring
|
0c1cc1e2cee20546dd4bca67597a1c286a907068 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/algebra/continued_fractions/convergents_equiv.lean | d250ab67e873e41b404276ede201d1167dd52333 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 20,595 | lean | /-
Copyright (c) 2020 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import algebra.continued_fractions.continuants_recurrence
import algebra.continued_fractions.terminated_stable
import tactic.linarith
/-!
# Equivalence of Recursive and Direct Computations of `gcf` Convergents
## Summary
We show the equivalence of two computations of convergents (recurrence relation (`convergents`) vs.
direct evaluation (`convergents'`)) for `gcf`s on linear ordered fields. We follow the proof from
[hardy2008introduction], Chapter 10. Here's a sketch:
Let `c` be a continued fraction `[h; (a₀, b₀), (a₁, b₁), (a₂, b₂),...]`, visually:
a₀
h + ---------------------------
a₁
b₀ + --------------------
a₂
b₁ + --------------
a₃
b₂ + --------
b₃ + ...
One can compute the convergents of `c` in two ways:
1. Directly evaluating the fraction described by `c` up to a given `n` (`convergents'`)
2. Using the recurrence (`convergents`):
- `A₋₁ = 1, A₀ = h, Aₙ = bₙ₋₁ * Aₙ₋₁ + aₙ₋₁ * Aₙ₋₂`, and
- `B₋₁ = 0, B₀ = 1, Bₙ = bₙ₋₁ * Bₙ₋₁ + aₙ₋₁ * Bₙ₋₂`.
To show the equivalence of the computations in the main theorem of this file
`convergents_eq_convergents'`, we proceed by induction. The case `n = 0` is trivial.
For `n + 1`, we first "squash" the `n + 1`th position of `c` into the `n`th position to obtain
another continued fraction
`c' := [h; (a₀, b₀),..., (aₙ-₁, bₙ-₁), (aₙ, bₙ + aₙ₊₁ / bₙ₊₁), (aₙ₊₁, bₙ₊₁),...]`.
This squashing process is formalised in section `squash`. Note that directly evaluating `c` up to
position `n + 1` is equal to evaluating `c'` up to `n`. This is shown in lemma
`succ_nth_convergent'_eq_squash_gcf_nth_convergent'`.
By the inductive hypothesis, the two computations for the `n`th convergent of `c` coincide.
So all that is left to show is that the recurrence relation for `c` at `n + 1` and and `c'` at
`n` coincide. This can be shown by another induction.
The corresponding lemma in this file is `succ_nth_convergent_eq_squash_gcf_nth_convergent`.
## Main Theorems
- `generalized_continued_fraction.convergents_eq_convergents'` shows the equivalence under a strict
positivity restriction on the sequence.
- `continued_fractions.convergents_eq_convergents'` shows the equivalence for (regular) continued
fractions.
## References
- https://en.wikipedia.org/wiki/Generalized_continued_fraction
- [*Hardy, GH and Wright, EM and Heath-Brown, Roger and Silverman, Joseph*][hardy2008introduction]
## Tags
fractions, recurrence, equivalence
-/
variables {K : Type*} {n : ℕ}
namespace generalized_continued_fraction
open generalized_continued_fraction as gcf
variables {g : gcf K} {s : seq $ gcf.pair K}
section squash
/-!
We will show the equivalence of the computations by induction. To make the induction work, we need
to be able to *squash* the nth and (n + 1)th value of a sequence. This squashing itself and the
lemmas about it are not very interesting. As a reader, you hence might want to skip this section.
-/
section with_division_ring
variable [division_ring K]
/--
Given a sequence of gcf.pairs `s = [(a₀, bₒ), (a₁, b₁), ...]`, `squash_seq s n`
combines `⟨aₙ, bₙ⟩` and `⟨aₙ₊₁, bₙ₊₁⟩` at position `n` to `⟨aₙ, bₙ + aₙ₊₁ / bₙ₊₁⟩`. For example,
`squash_seq s 0 = [(a₀, bₒ + a₁ / b₁), (a₁, b₁),...]`.
If `s.terminated_at (n + 1)`, then `squash_seq s n = s`.
-/
def squash_seq (s : seq $ gcf.pair K) (n : ℕ) : seq (gcf.pair K) :=
match prod.mk (s.nth n) (s.nth (n + 1)) with
| ⟨some gp_n, some gp_succ_n⟩ := seq.nats.zip_with
-- return the squashed value at position `n`; otherwise, do nothing.
(λ n' gp, if n' = n then ⟨gp_n.a, gp_n.b + gp_succ_n.a / gp_succ_n.b⟩ else gp) s
| _ := s
end
/-! We now prove some simple lemmas about the squashed sequence -/
/-- If the sequence already terminated at position `n + 1`, nothing gets squashed. -/
lemma squash_seq_eq_self_of_terminated (terminated_at_succ_n : s.terminated_at (n + 1)) :
squash_seq s n = s :=
begin
change s.nth (n + 1) = none at terminated_at_succ_n,
cases s_nth_eq : (s.nth n);
simp only [*, squash_seq]
end
/-- If the sequence has not terminated before position `n + 1`, the value at `n + 1` gets
squashed into position `n`. -/
lemma squash_seq_nth_of_not_terminated {gp_n gp_succ_n : gcf.pair K}
(s_nth_eq : s.nth n = some gp_n) (s_succ_nth_eq : s.nth (n + 1) = some gp_succ_n) :
(squash_seq s n).nth n = some ⟨gp_n.a, gp_n.b + gp_succ_n.a / gp_succ_n.b⟩ :=
by simp [*, squash_seq, (seq.zip_with_nth_some (seq.nats_nth n) s_nth_eq _)]
/-- The values before the squashed position stay the same. -/
lemma squash_seq_nth_of_lt {m : ℕ} (m_lt_n : m < n) : (squash_seq s n).nth m = s.nth m :=
begin
cases s_succ_nth_eq : s.nth (n + 1),
case option.none { rw (squash_seq_eq_self_of_terminated s_succ_nth_eq) },
case option.some
{ obtain ⟨gp_n, s_nth_eq⟩ : ∃ gp_n, s.nth n = some gp_n, from
s.ge_stable n.le_succ s_succ_nth_eq,
obtain ⟨gp_m, s_mth_eq⟩ : ∃ gp_m, s.nth m = some gp_m, from
s.ge_stable (le_of_lt m_lt_n) s_nth_eq,
simp [*, squash_seq, (seq.zip_with_nth_some (seq.nats_nth m) s_mth_eq _),
(ne_of_lt m_lt_n)] }
end
/-- Squashing at position `n + 1` and taking the tail is the same as squashing the tail of the
sequence at position `n`. -/
lemma squash_seq_succ_n_tail_eq_squash_seq_tail_n :
(squash_seq s (n + 1)).tail = squash_seq s.tail n :=
begin
cases s_succ_succ_nth_eq : s.nth (n + 2) with gp_succ_succ_n,
case option.none
{ have : squash_seq s (n + 1) = s, from squash_seq_eq_self_of_terminated s_succ_succ_nth_eq,
cases s_succ_nth_eq : (s.nth (n + 1));
simp only [squash_seq, seq.nth_tail, s_succ_nth_eq, s_succ_succ_nth_eq] },
case option.some
{ obtain ⟨gp_succ_n, s_succ_nth_eq⟩ : ∃ gp_succ_n, s.nth (n + 1) = some gp_succ_n, from
s.ge_stable (n + 1).le_succ s_succ_succ_nth_eq,
-- apply extensionality with `m` and continue by cases `m = n`.
ext m,
cases decidable.em (m = n) with m_eq_n m_ne_n,
{ have : s.tail.nth n = some gp_succ_n, from (s.nth_tail n).trans s_succ_nth_eq,
simp [*, squash_seq, seq.nth_tail, (seq.zip_with_nth_some (seq.nats_nth n) this),
(seq.zip_with_nth_some (seq.nats_nth (n + 1)) s_succ_nth_eq)] },
{ have : s.tail.nth m = s.nth (m + 1), from s.nth_tail m,
cases s_succ_mth_eq : s.nth (m + 1),
all_goals { have s_tail_mth_eq, from this.trans s_succ_mth_eq },
{ simp only [*, squash_seq, seq.nth_tail, (seq.zip_with_nth_none' s_succ_mth_eq),
(seq.zip_with_nth_none' s_tail_mth_eq)] },
{ simp [*, squash_seq, seq.nth_tail,
(seq.zip_with_nth_some (seq.nats_nth (m + 1)) s_succ_mth_eq),
(seq.zip_with_nth_some (seq.nats_nth m) s_tail_mth_eq)] } } }
end
/-- The auxiliary function `convergents'_aux` returns the same value for a sequence and the
corresponding squashed sequence at the squashed position. -/
lemma succ_succ_nth_convergent'_aux_eq_succ_nth_convergent'_aux_squash_seq :
convergents'_aux s (n + 2) = convergents'_aux (squash_seq s n) (n + 1) :=
begin
cases s_succ_nth_eq : (s.nth $ n + 1) with gp_succ_n,
case option.none
{ rw [(squash_seq_eq_self_of_terminated s_succ_nth_eq),
(convergents'_aux_stable_step_of_terminated s_succ_nth_eq)] },
case option.some
{ induction n with m IH generalizing s gp_succ_n,
case nat.zero
{ obtain ⟨gp_head, s_head_eq⟩ : ∃ gp_head, s.head = some gp_head, from
s.ge_stable zero_le_one s_succ_nth_eq,
have : (squash_seq s 0).head = some ⟨gp_head.a, gp_head.b + gp_succ_n.a / gp_succ_n.b⟩,
from squash_seq_nth_of_not_terminated s_head_eq s_succ_nth_eq,
simp [*, convergents'_aux, seq.head, seq.nth_tail] },
case nat.succ
{ obtain ⟨gp_head, s_head_eq⟩ : ∃ gp_head, s.head = some gp_head, from
s.ge_stable (m + 2).zero_le s_succ_nth_eq,
suffices : gp_head.a / (gp_head.b + convergents'_aux s.tail (m + 2))
= convergents'_aux (squash_seq s (m + 1)) (m + 2), by
simpa only [convergents'_aux, s_head_eq],
have : convergents'_aux s.tail (m + 2) = convergents'_aux (squash_seq s.tail m) (m + 1), by
{ have : s.tail.nth (m + 1) = some gp_succ_n, by simpa [seq.nth_tail] using s_succ_nth_eq,
exact (IH _ this) },
have : (squash_seq s (m + 1)).head = some gp_head, from
(squash_seq_nth_of_lt m.succ_pos).trans s_head_eq,
simp only [*, convergents'_aux, squash_seq_succ_n_tail_eq_squash_seq_tail_n] } }
end
/-! Let us now lift the squashing operation to gcfs. -/
/--
Given a gcf `g = [h; (a₀, bₒ), (a₁, b₁), ...]`, we have
- `squash_nth.gcf g 0 = [h + a₀ / b₀); (a₀, bₒ), ...]`,
- `squash_nth.gcf g (n + 1) = ⟨g.h, squash_seq g.s n⟩`
-/
def squash_gcf (g : gcf K) : ℕ → gcf K
| 0 := match g.s.nth 0 with
| none := g
| some gp := ⟨g.h + gp.a / gp.b, g.s⟩
end
| (n + 1) := ⟨g.h, squash_seq g.s n⟩
/-! Again, we derive some simple lemmas that are not really of interest. This time for the
squashed gcf. -/
/-- If the gcf already terminated at position `n`, nothing gets squashed. -/
lemma squash_gcf_eq_self_of_terminated (terminated_at_n : terminated_at g n) :
squash_gcf g n = g :=
begin
cases n,
case nat.zero
{ change g.s.nth 0 = none at terminated_at_n,
simp only [convergents', squash_gcf, convergents'_aux, terminated_at_n] },
case nat.succ
{ cases g, simp [(squash_seq_eq_self_of_terminated terminated_at_n), squash_gcf] }
end
/-- The values before the squashed position stay the same. -/
lemma squash_gcf_nth_of_lt {m : ℕ} (m_lt_n : m < n) :
(squash_gcf g (n + 1)).s.nth m = g.s.nth m :=
by simp only [squash_gcf, (squash_seq_nth_of_lt m_lt_n)]
/-- `convergents'` returns the same value for a gcf and the corresponding squashed gcf at the
squashed position. -/
lemma succ_nth_convergent'_eq_squash_gcf_nth_convergent' :
g.convergents' (n + 1) = (squash_gcf g n).convergents' n :=
begin
cases n,
case nat.zero
{ cases g_s_head_eq : (g.s.nth 0);
simp [g_s_head_eq, squash_gcf, convergents', convergents'_aux, seq.head] },
case nat.succ
{ simp only [succ_succ_nth_convergent'_aux_eq_succ_nth_convergent'_aux_squash_seq,
convergents', squash_gcf] }
end
/-- The auxiliary continuants before the squashed position stay the same. -/
lemma continuants_aux_eq_continuants_aux_squash_gcf_of_le {m : ℕ} :
m ≤ n → continuants_aux g m = (squash_gcf g n).continuants_aux m :=
nat.strong_induction_on m
(begin
clear m,
assume m IH m_le_n,
cases m with m',
{ refl },
{ cases n with n',
{ have : false, from m'.not_succ_le_zero m_le_n, contradiction }, -- 1 ≰ 0
{ cases m' with m'',
{ refl },
{ -- get some inequalities to instantiate the IH for m'' and m'' + 1
have m'_lt_n : m'' + 1 < n' + 1, from m_le_n,
have : m'' + 1 < m'' + 2, by linarith,
have succ_m''th_conts_aux_eq := IH (m'' + 1) this (le_of_lt m'_lt_n),
have : m'' < m'' + 2, by linarith,
have m''th_conts_aux_eq := IH m'' this (le_of_lt $ lt_of_lt_of_le (by linarith) n'.le_succ),
have : (squash_gcf g (n' + 1)).s.nth m'' = g.s.nth m'', from
squash_gcf_nth_of_lt (by linarith),
simp [continuants_aux, succ_m''th_conts_aux_eq, m''th_conts_aux_eq, this] } } }
end)
end with_division_ring
/-- The convergents coincide in the expected way at the squashed position if the partial denominator
at the squashed position is not zero. -/
lemma succ_nth_convergent_eq_squash_gcf_nth_convergent [field K]
(nth_part_denom_ne_zero : ∀ {b : K}, g.partial_denominators.nth n = some b → b ≠ 0) :
g.convergents (n + 1) = (squash_gcf g n).convergents n :=
begin
cases decidable.em (g.terminated_at n) with terminated_at_n not_terminated_at_n,
{ have : squash_gcf g n = g, from squash_gcf_eq_self_of_terminated terminated_at_n,
simp only [this, (convergents_stable_of_terminated n.le_succ terminated_at_n)] },
{ obtain ⟨⟨a, b⟩, s_nth_eq⟩ : ∃ gp_n, g.s.nth n = some gp_n, from
option.ne_none_iff_exists.elim_left not_terminated_at_n,
have b_ne_zero : b ≠ 0, from nth_part_denom_ne_zero (part_denom_eq_s_b s_nth_eq),
cases n with n',
case nat.zero
{ suffices : (b * g.h + a) / b = g.h + a / b, by
simpa [squash_gcf, s_nth_eq, convergent_eq_conts_a_div_conts_b,
(continuants_recurrence_aux s_nth_eq zeroth_continuant_aux_eq_one_zero
first_continuant_aux_eq_h_one)],
calc
(b * g.h + a) / b = b * g.h / b + a / b : by ring -- requires `field` rather than `division_ring`
... = g.h + a / b : by rw (mul_div_cancel_left _ b_ne_zero) },
case nat.succ
{ obtain ⟨⟨pa, pb⟩, s_n'th_eq⟩ : ∃ gp_n', g.s.nth n' = some gp_n' :=
g.s.ge_stable n'.le_succ s_nth_eq,
-- Notations
let g' := squash_gcf g (n' + 1),
set pred_conts := g.continuants_aux (n' + 1) with succ_n'th_conts_aux_eq,
set ppred_conts := g.continuants_aux n' with n'th_conts_aux_eq,
let pA := pred_conts.a, let pB := pred_conts.b,
let ppA := ppred_conts.a, let ppB := ppred_conts.b,
set pred_conts' := g'.continuants_aux (n' + 1) with succ_n'th_conts_aux_eq',
set ppred_conts' := g'.continuants_aux n' with n'th_conts_aux_eq',
let pA' := pred_conts'.a, let pB' := pred_conts'.b, let ppA' := ppred_conts'.a,
let ppB' := ppred_conts'.b,
-- first compute the convergent of the squashed gcf
have : g'.convergents (n' + 1)
= ((pb + a / b) * pA' + pa * ppA') / ((pb + a / b) * pB' + pa * ppB'),
{ have : g'.s.nth n' = some ⟨pa, pb + a / b⟩,
{ simpa only [squash_nth_gcf] using
(squash_seq_nth_of_not_terminated s_n'th_eq s_nth_eq) },
rw [convergent_eq_conts_a_div_conts_b,
(continuants_recurrence_aux this n'th_conts_aux_eq'.symm succ_n'th_conts_aux_eq'.symm)], },
rw this,
-- then compute the convergent of the original gcf by recursively unfolding the continuants
-- computation twice
have : g.convergents (n' + 2)
= (b * (pb * pA + pa * ppA) + a * pA) / (b * (pb * pB + pa * ppB) + a * pB),
{ -- use the recurrence once
have : g.continuants_aux (n' + 2) = ⟨pb * pA + pa * ppA, pb * pB + pa * ppB⟩ :=
continuants_aux_recurrence s_n'th_eq n'th_conts_aux_eq.symm succ_n'th_conts_aux_eq.symm,
-- and a second time
rw [convergent_eq_conts_a_div_conts_b,
(continuants_recurrence_aux s_nth_eq succ_n'th_conts_aux_eq.symm this)] },
rw this,
suffices : ((pb + a / b) * pA + pa * ppA) / ((pb + a / b) * pB + pa * ppB)
= (b * (pb * pA + pa * ppA) + a * pA) / (b * (pb * pB + pa * ppB) + a * pB),
{ obtain ⟨eq1, eq2, eq3, eq4⟩ : pA' = pA ∧ pB' = pB ∧ ppA' = ppA ∧ ppB' = ppB,
{ simp [*, (continuants_aux_eq_continuants_aux_squash_gcf_of_le $ le_refl $ n' + 1).symm,
(continuants_aux_eq_continuants_aux_squash_gcf_of_le n'.le_succ).symm] },
symmetry,
simpa only [eq1, eq2, eq3, eq4, mul_div_cancel _ b_ne_zero] },
field_simp [b_ne_zero],
congr' 1; ring } }
end
end squash
/-- Shows that the recurrence relation (`convergents`) and direct evaluation (`convergents'`) of the
gcf coincide at position `n` if the sequence of fractions contains strictly positive values only.
Requiring positivity of all values is just one possible condition to obtain this result.
For example, the dual - sequences with strictly negative values only - would also work.
In practice, one most commonly deals with (regular) continued fractions, which satisfy the
positivity criterion required here. The analogous result for them
(see `continued_fractions.convergents_eq_convergents`) hence follows directly from this theorem.
-/
theorem convergents_eq_convergents' [linear_ordered_field K]
(s_pos : ∀ {gp : gcf.pair K} {m : ℕ}, m < n → g.s.nth m = some gp → 0 < gp.a ∧ 0 < gp.b) :
g.convergents n = g.convergents' n :=
begin
induction n with n IH generalizing g,
case nat.zero { simp },
case nat.succ
{ let g' := squash_gcf g n, -- first replace the rhs with the squashed computation
suffices : g.convergents (n + 1) = g'.convergents' n, by
rwa [succ_nth_convergent'_eq_squash_gcf_nth_convergent'],
cases decidable.em (terminated_at g n) with terminated_at_n not_terminated_at_n,
{ have g'_eq_g : g' = g, from squash_gcf_eq_self_of_terminated terminated_at_n,
have : ∀ ⦃gp m⦄, m < n → g.s.nth m = some gp → 0 < gp.a ∧ 0 < gp.b, by
{ assume _ _ m_lt_n s_mth_eq, exact (s_pos (nat.lt.step m_lt_n) s_mth_eq) },
rw [(convergents_stable_of_terminated n.le_succ terminated_at_n), g'_eq_g, (IH this)] },
{ suffices : g.convergents (n + 1) = g'.convergents n, by -- invoke the IH for the squashed gcf
{ have : ∀ ⦃gp' m⦄, m < n → g'.s.nth m = some gp' → 0 < gp'.a ∧ 0 < gp'.b, by
{ assume gp' m m_lt_n s_mth_eq',
-- case distinction on m + 1 = n or m + 1 < n
cases m_lt_n with n succ_m_lt_n,
{ -- the difficult case at the squashed position: we first obtain the values from
-- the sequence
obtain ⟨gp_succ_m, s_succ_mth_eq⟩ : ∃ gp_succ_m, g.s.nth (m + 1) = some gp_succ_m, from
option.ne_none_iff_exists.elim_left not_terminated_at_n,
obtain ⟨gp_m, mth_s_eq⟩ : ∃ gp_m, g.s.nth m = some gp_m, from
g.s.ge_stable m.le_succ s_succ_mth_eq,
-- we then plug them into the recurrence
suffices : 0 < gp_m.a ∧ 0 < gp_m.b + gp_succ_m.a / gp_succ_m.b, by {
have : g'.s.nth m = some ⟨gp_m.a, gp_m.b + gp_succ_m.a / gp_succ_m.b⟩, from
squash_seq_nth_of_not_terminated mth_s_eq s_succ_mth_eq,
have : gp' = ⟨gp_m.a, gp_m.b + gp_succ_m.a / gp_succ_m.b⟩, by cc,
rwa this },
split,
{ exact (s_pos (nat.lt.step m_lt_n) mth_s_eq).left },
{ have : 0 < gp_m.b, from (s_pos (nat.lt.step m_lt_n) mth_s_eq).right,
have : 0 < gp_succ_m.a / gp_succ_m.b, by
{ have : 0 < gp_succ_m.a ∧ 0 < gp_succ_m.b, from
s_pos (lt_add_one $ m + 1) s_succ_mth_eq,
exact (div_pos this.left this.right) },
linarith } },
{ -- the easy case: before the squashed position, nothing changes
have : g.s.nth m = some gp', by {
have : g'.s.nth m = g.s.nth m, from squash_gcf_nth_of_lt succ_m_lt_n,
rwa this at s_mth_eq' },
exact s_pos (nat.lt.step $ nat.lt.step succ_m_lt_n) this } },
rwa [(IH this).symm] },
-- now the result follows from the fact that the convergents coincide at the squashed position
-- as established in `succ_nth_convergent_eq_squash_gcf_nth_convergent`.
have : ∀ ⦃b⦄, g.partial_denominators.nth n = some b → b ≠ 0, by
{ assume b nth_part_denom_eq,
obtain ⟨gp, s_nth_eq, ⟨refl⟩⟩ : ∃ gp, g.s.nth n = some gp ∧ gp.b = b, from
exists_s_b_of_part_denom nth_part_denom_eq,
exact (ne_of_lt (s_pos (lt_add_one n) s_nth_eq).right).symm },
exact succ_nth_convergent_eq_squash_gcf_nth_convergent this } }
end
end generalized_continued_fraction
namespace continued_fraction
open generalized_continued_fraction as gcf
open simple_continued_fraction as scf
open continued_fraction as cf
/-- Shows that the recurrence relation (`convergents`) and direct evaluation (`convergents'`) of a
(regular) continued fraction coincide. -/
theorem convergents_eq_convergents' [linear_ordered_field K] {c : cf K} :
(↑c : gcf K).convergents = (↑c : gcf K).convergents' :=
begin
ext n,
apply gcf.convergents_eq_convergents',
assume gp m m_lt_n s_nth_eq,
split,
{ have : gp.a = 1, from (c : scf K).property m gp.a (gcf.part_num_eq_s_a s_nth_eq),
simp only [zero_lt_one, this] },
{ exact (c.property m gp.b $ gcf.part_denom_eq_s_b s_nth_eq) }
end
end continued_fraction
|
86c657c3adba5c4aa6447d218f7a8d65cdc723c7 | 4e3bf8e2b29061457a887ac8889e88fa5aa0e34c | /lean/love02_tactical_proofs_homework_solution.lean | e0e5b4ca97333d61550822695f0d05eecb03a827 | [] | no_license | mukeshtiwari/logical_verification_2019 | 9f964c067a71f65eb8884743273fbeef99e6503d | 16f62717f55ed5b7b87e03ae0134791a9bef9b9a | refs/heads/master | 1,619,158,844,208 | 1,585,139,500,000 | 1,585,139,500,000 | 249,906,380 | 0 | 0 | null | 1,585,118,728,000 | 1,585,118,727,000 | null | UTF-8 | Lean | false | false | 1,790 | lean | /- LoVe Homework 2: Tactical Proofs -/
import .love02_tactical_proofs_exercise
namespace LoVe
/- Question 2 (**optional**): Logical Connectives -/
/- 2.1 (**optional**). Prove the following property about double negation.
Hint: You will need to apply the elimination rule for `false` at a key point in
the proof. -/
lemma herman (p : Prop) : ¬¬ (¬¬ p → p) :=
begin
intro hnnnpp,
apply hnnnpp,
intro hnnp,
apply false.elim,
apply hnnp,
intro hp,
apply hnnnpp,
intro hnnp,
exact hp
end
/- 2.2 (**optional**). Prove the missing link in our chain of classical axiom
implications.
Hint: You will need to apply the double negation hypothesis for `p ∨ ¬ p`. You
will also need the left and right introduction rules for `or` at some point. -/
#check excluded_middle
#check peirce
#check double_negation
lemma em_of_dn : double_negation → excluded_middle :=
begin
simp [double_negation, excluded_middle],
intros hdoubleneg p,
apply hdoubleneg,
intro hnponp,
apply hnponp,
apply or.intro_right,
intro hnp,
apply hnponp,
apply or.intro_left,
assumption
end
/- 2.3 (**optional**). We have proved three of the six possible implications
between `excluded_middle`, `peirce`, and `double_negation`. State and prove the
three missing implications, exploiting the three theorems we already have. -/
#check peirce_of_em
#check dn_of_peirce
#check em_of_dn
lemma dn_imp_peirce : double_negation → peirce :=
begin
intro h,
apply peirce_of_em,
apply em_of_dn,
exact h
end
lemma peirce_imp_em : peirce → excluded_middle :=
begin
intro h,
apply em_of_dn,
apply dn_of_peirce,
exact h
end
lemma em_imp_dn : excluded_middle → double_negation :=
begin
intro h,
apply dn_of_peirce,
apply peirce_of_em,
exact h
end
end LoVe
|
6187685f8ac33c2742e3a789ac9ad3e848bf1171 | ba4794a0deca1d2aaa68914cd285d77880907b5c | /src/game/intro.lean | 1d7ed06201ace95476331b39a907b40c699f0d1d | [
"Apache-2.0"
] | permissive | ChrisHughes24/natural_number_game | c7c00aa1f6a95004286fd456ed13cf6e113159ce | 9d09925424da9f6275e6cfe427c8bcf12bb0944f | refs/heads/master | 1,600,715,773,528 | 1,573,910,462,000 | 1,573,910,462,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,755 | lean | /-
# The Natural Number Game, version 1.09b
## By Kevin Buzzard and Mohammad Pedramfar.
# What is this game?
Welcome to the natural number game -- a part-book part-game which shows the power of induction.
Blue nodes on the graph are ones that you are ready to enter. Grey nodes you should stay away
from -- try blue ones higher up the chain first. Green nodes are completed.
In this game, you get own version of the natural numbers, called `mynat`, in a programming
language called Lean. Your version of the natural numbers satisfies something called
the principle of mathematical induction, and a couple
of other things too (Peano's axioms). Unfortunately, nobody has proved any theorems about these
natural numbers yet. For example, addition will be defined for you,
but nobody has proved that `x + y = y + x` yet. This is your job. You're going to
prove mathematical theorems using the Lean theorem prover. In other words, you're going to solve
levels in a computer game.
You're going to prove these theorems using *tactics*. The introductory world, Tutorial World,
will take you through some of these tactics. During your proofs, your "goal" (i.e. what you're
supposed to be proving) will be displayed with a `⊢` symbol in front of it. If the top
right hand box reports "Theorem Proved!", you have closed all the goals in the level
and can move on to the next level in the world you're in. When you've finished a world,
hit "main menu" in the top left to get back here.
# What's new?
Lots of things. A function world, two proposition worlds, and the advanced addition
and multiplication worlds are back! To come: inequality world.
# Thanks
Special thanks to Rob Lewis for tactic hackery, Bryan Gin-Ge Chen for
javascript hackery, Patrick Massot for his
<a href="https://github.com/leanprover-community/format_lean" target="blank">Lean to html formatter</a>,
Sian Carey for Power World,
and, last but not least, all the people who fed back comments, including
the 2019-20 Imperial College 1st year maths beta tester students, Marie-Amélie Lawn,
Toby Gee, Joseph Myers, and all the people who have been in touch
via the <a href="https://leanprover.zulipchat.com/" target="blank">Lean Zulip chat</a>
or the <a href="https://xenaproject.wordpress.com/" target="blank">Xena Project blog</a>
or via <a href="https://twitter.com/XenaProject" target="blank">Twitter</a>.
The natural number game is brought to you by the Xena project, a project based at Imperial College London
whose aim is to get mathematics undergraduates using computer theorem provers.
Lean is a computer theorem prover being developed at Microsoft Research.
Prove a theorem. Write a function. <a href="https://twitter.com/XenaProject" target="blank">@XenaProject</a>.
-/
|
e169a6bfc1bd3cd2a5ed5363078e0c2566217e25 | 592ee40978ac7604005a4e0d35bbc4b467389241 | /Library/generated/mathscheme-lean/BoundedDistributiveLattice.lean | af9919fa3e145da0d56f196fa76a2d1e2425bd44 | [] | no_license | ysharoda/Deriving-Definitions | 3e149e6641fae440badd35ac110a0bd705a49ad2 | dfecb27572022de3d4aa702cae8db19957523a59 | refs/heads/master | 1,679,127,857,700 | 1,615,939,007,000 | 1,615,939,007,000 | 229,785,731 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,680 | lean | import init.data.nat.basic
import init.data.fin.basic
import data.vector
import .Prelude
open Staged
open nat
open fin
open vector
section BoundedDistributiveLattice
structure BoundedDistributiveLattice (A : Type) : Type :=
(times : (A → (A → A)))
(plus : (A → (A → A)))
(commutative_times : (∀ {x y : A} , (times x y) = (times y x)))
(associative_times : (∀ {x y z : A} , (times (times x y) z) = (times x (times y z))))
(idempotent_times : (∀ {x : A} , (times x x) = x))
(commutative_plus : (∀ {x y : A} , (plus x y) = (plus y x)))
(associative_plus : (∀ {x y z : A} , (plus (plus x y) z) = (plus x (plus y z))))
(idempotent_plus : (∀ {x : A} , (plus x x) = x))
(leftAbsorp_times_plus : (∀ {x y : A} , (times x (plus x y)) = x))
(leftAbsorp_plus_times : (∀ {x y : A} , (plus x (times x y)) = x))
(leftModular_times_plus : (∀ {x y z : A} , (plus (times x y) (times x z)) = (times x (plus y (times x z)))))
(zero : A)
(lunit_zero : (∀ {x : A} , (plus zero x) = x))
(runit_zero : (∀ {x : A} , (plus x zero) = x))
(one : A)
(lunit_one : (∀ {x : A} , (times one x) = x))
(runit_one : (∀ {x : A} , (times x one) = x))
(leftDistributive_times_plus : (∀ {x y z : A} , (times x (plus y z)) = (plus (times x y) (times x z))))
open BoundedDistributiveLattice
structure Sig (AS : Type) : Type :=
(timesS : (AS → (AS → AS)))
(plusS : (AS → (AS → AS)))
(zeroS : AS)
(oneS : AS)
structure Product (A : Type) : Type :=
(timesP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(plusP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(zeroP : (Prod A A))
(oneP : (Prod A A))
(commutative_timesP : (∀ {xP yP : (Prod A A)} , (timesP xP yP) = (timesP yP xP)))
(associative_timesP : (∀ {xP yP zP : (Prod A A)} , (timesP (timesP xP yP) zP) = (timesP xP (timesP yP zP))))
(idempotent_timesP : (∀ {xP : (Prod A A)} , (timesP xP xP) = xP))
(commutative_plusP : (∀ {xP yP : (Prod A A)} , (plusP xP yP) = (plusP yP xP)))
(associative_plusP : (∀ {xP yP zP : (Prod A A)} , (plusP (plusP xP yP) zP) = (plusP xP (plusP yP zP))))
(idempotent_plusP : (∀ {xP : (Prod A A)} , (plusP xP xP) = xP))
(leftAbsorp_times_plusP : (∀ {xP yP : (Prod A A)} , (timesP xP (plusP xP yP)) = xP))
(leftAbsorp_plus_timesP : (∀ {xP yP : (Prod A A)} , (plusP xP (timesP xP yP)) = xP))
(leftModular_times_plusP : (∀ {xP yP zP : (Prod A A)} , (plusP (timesP xP yP) (timesP xP zP)) = (timesP xP (plusP yP (timesP xP zP)))))
(lunit_0P : (∀ {xP : (Prod A A)} , (plusP zeroP xP) = xP))
(runit_0P : (∀ {xP : (Prod A A)} , (plusP xP zeroP) = xP))
(lunit_1P : (∀ {xP : (Prod A A)} , (timesP oneP xP) = xP))
(runit_1P : (∀ {xP : (Prod A A)} , (timesP xP oneP) = xP))
(leftDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP xP (plusP yP zP)) = (plusP (timesP xP yP) (timesP xP zP))))
structure Hom {A1 : Type} {A2 : Type} (Bo1 : (BoundedDistributiveLattice A1)) (Bo2 : (BoundedDistributiveLattice A2)) : Type :=
(hom : (A1 → A2))
(pres_times : (∀ {x1 x2 : A1} , (hom ((times Bo1) x1 x2)) = ((times Bo2) (hom x1) (hom x2))))
(pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Bo1) x1 x2)) = ((plus Bo2) (hom x1) (hom x2))))
(pres_zero : (hom (zero Bo1)) = (zero Bo2))
(pres_one : (hom (one Bo1)) = (one Bo2))
structure RelInterp {A1 : Type} {A2 : Type} (Bo1 : (BoundedDistributiveLattice A1)) (Bo2 : (BoundedDistributiveLattice A2)) : Type 1 :=
(interp : (A1 → (A2 → Type)))
(interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Bo1) x1 x2) ((times Bo2) y1 y2))))))
(interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Bo1) x1 x2) ((plus Bo2) y1 y2))))))
(interp_zero : (interp (zero Bo1) (zero Bo2)))
(interp_one : (interp (one Bo1) (one Bo2)))
inductive BoundedDistributiveLatticeTerm : Type
| timesL : (BoundedDistributiveLatticeTerm → (BoundedDistributiveLatticeTerm → BoundedDistributiveLatticeTerm))
| plusL : (BoundedDistributiveLatticeTerm → (BoundedDistributiveLatticeTerm → BoundedDistributiveLatticeTerm))
| zeroL : BoundedDistributiveLatticeTerm
| oneL : BoundedDistributiveLatticeTerm
open BoundedDistributiveLatticeTerm
inductive ClBoundedDistributiveLatticeTerm (A : Type) : Type
| sing : (A → ClBoundedDistributiveLatticeTerm)
| timesCl : (ClBoundedDistributiveLatticeTerm → (ClBoundedDistributiveLatticeTerm → ClBoundedDistributiveLatticeTerm))
| plusCl : (ClBoundedDistributiveLatticeTerm → (ClBoundedDistributiveLatticeTerm → ClBoundedDistributiveLatticeTerm))
| zeroCl : ClBoundedDistributiveLatticeTerm
| oneCl : ClBoundedDistributiveLatticeTerm
open ClBoundedDistributiveLatticeTerm
inductive OpBoundedDistributiveLatticeTerm (n : ℕ) : Type
| v : ((fin n) → OpBoundedDistributiveLatticeTerm)
| timesOL : (OpBoundedDistributiveLatticeTerm → (OpBoundedDistributiveLatticeTerm → OpBoundedDistributiveLatticeTerm))
| plusOL : (OpBoundedDistributiveLatticeTerm → (OpBoundedDistributiveLatticeTerm → OpBoundedDistributiveLatticeTerm))
| zeroOL : OpBoundedDistributiveLatticeTerm
| oneOL : OpBoundedDistributiveLatticeTerm
open OpBoundedDistributiveLatticeTerm
inductive OpBoundedDistributiveLatticeTerm2 (n : ℕ) (A : Type) : Type
| v2 : ((fin n) → OpBoundedDistributiveLatticeTerm2)
| sing2 : (A → OpBoundedDistributiveLatticeTerm2)
| timesOL2 : (OpBoundedDistributiveLatticeTerm2 → (OpBoundedDistributiveLatticeTerm2 → OpBoundedDistributiveLatticeTerm2))
| plusOL2 : (OpBoundedDistributiveLatticeTerm2 → (OpBoundedDistributiveLatticeTerm2 → OpBoundedDistributiveLatticeTerm2))
| zeroOL2 : OpBoundedDistributiveLatticeTerm2
| oneOL2 : OpBoundedDistributiveLatticeTerm2
open OpBoundedDistributiveLatticeTerm2
def simplifyCl {A : Type} : ((ClBoundedDistributiveLatticeTerm A) → (ClBoundedDistributiveLatticeTerm A))
| (plusCl zeroCl x) := x
| (plusCl x zeroCl) := x
| (timesCl oneCl x) := x
| (timesCl x oneCl) := x
| (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2))
| (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2))
| zeroCl := zeroCl
| oneCl := oneCl
| (sing x1) := (sing x1)
def simplifyOpB {n : ℕ} : ((OpBoundedDistributiveLatticeTerm n) → (OpBoundedDistributiveLatticeTerm n))
| (plusOL zeroOL x) := x
| (plusOL x zeroOL) := x
| (timesOL oneOL x) := x
| (timesOL x oneOL) := x
| (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2))
| (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2))
| zeroOL := zeroOL
| oneOL := oneOL
| (v x1) := (v x1)
def simplifyOp {n : ℕ} {A : Type} : ((OpBoundedDistributiveLatticeTerm2 n A) → (OpBoundedDistributiveLatticeTerm2 n A))
| (plusOL2 zeroOL2 x) := x
| (plusOL2 x zeroOL2) := x
| (timesOL2 oneOL2 x) := x
| (timesOL2 x oneOL2) := x
| (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2))
| (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2))
| zeroOL2 := zeroOL2
| oneOL2 := oneOL2
| (v2 x1) := (v2 x1)
| (sing2 x1) := (sing2 x1)
def evalB {A : Type} : ((BoundedDistributiveLattice A) → (BoundedDistributiveLatticeTerm → A))
| Bo (timesL x1 x2) := ((times Bo) (evalB Bo x1) (evalB Bo x2))
| Bo (plusL x1 x2) := ((plus Bo) (evalB Bo x1) (evalB Bo x2))
| Bo zeroL := (zero Bo)
| Bo oneL := (one Bo)
def evalCl {A : Type} : ((BoundedDistributiveLattice A) → ((ClBoundedDistributiveLatticeTerm A) → A))
| Bo (sing x1) := x1
| Bo (timesCl x1 x2) := ((times Bo) (evalCl Bo x1) (evalCl Bo x2))
| Bo (plusCl x1 x2) := ((plus Bo) (evalCl Bo x1) (evalCl Bo x2))
| Bo zeroCl := (zero Bo)
| Bo oneCl := (one Bo)
def evalOpB {A : Type} {n : ℕ} : ((BoundedDistributiveLattice A) → ((vector A n) → ((OpBoundedDistributiveLatticeTerm n) → A)))
| Bo vars (v x1) := (nth vars x1)
| Bo vars (timesOL x1 x2) := ((times Bo) (evalOpB Bo vars x1) (evalOpB Bo vars x2))
| Bo vars (plusOL x1 x2) := ((plus Bo) (evalOpB Bo vars x1) (evalOpB Bo vars x2))
| Bo vars zeroOL := (zero Bo)
| Bo vars oneOL := (one Bo)
def evalOp {A : Type} {n : ℕ} : ((BoundedDistributiveLattice A) → ((vector A n) → ((OpBoundedDistributiveLatticeTerm2 n A) → A)))
| Bo vars (v2 x1) := (nth vars x1)
| Bo vars (sing2 x1) := x1
| Bo vars (timesOL2 x1 x2) := ((times Bo) (evalOp Bo vars x1) (evalOp Bo vars x2))
| Bo vars (plusOL2 x1 x2) := ((plus Bo) (evalOp Bo vars x1) (evalOp Bo vars x2))
| Bo vars zeroOL2 := (zero Bo)
| Bo vars oneOL2 := (one Bo)
def inductionB {P : (BoundedDistributiveLatticeTerm → Type)} : ((∀ (x1 x2 : BoundedDistributiveLatticeTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((∀ (x1 x2 : BoundedDistributiveLatticeTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → ((P zeroL) → ((P oneL) → (∀ (x : BoundedDistributiveLatticeTerm) , (P x))))))
| ptimesl pplusl p0l p1l (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl pplusl p0l p1l x1) (inductionB ptimesl pplusl p0l p1l x2))
| ptimesl pplusl p0l p1l (plusL x1 x2) := (pplusl _ _ (inductionB ptimesl pplusl p0l p1l x1) (inductionB ptimesl pplusl p0l p1l x2))
| ptimesl pplusl p0l p1l zeroL := p0l
| ptimesl pplusl p0l p1l oneL := p1l
def inductionCl {A : Type} {P : ((ClBoundedDistributiveLatticeTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClBoundedDistributiveLatticeTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((∀ (x1 x2 : (ClBoundedDistributiveLatticeTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → ((P zeroCl) → ((P oneCl) → (∀ (x : (ClBoundedDistributiveLatticeTerm A)) , (P x)))))))
| psing ptimescl ppluscl p0cl p1cl (sing x1) := (psing x1)
| psing ptimescl ppluscl p0cl p1cl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl ppluscl p0cl p1cl x1) (inductionCl psing ptimescl ppluscl p0cl p1cl x2))
| psing ptimescl ppluscl p0cl p1cl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ptimescl ppluscl p0cl p1cl x1) (inductionCl psing ptimescl ppluscl p0cl p1cl x2))
| psing ptimescl ppluscl p0cl p1cl zeroCl := p0cl
| psing ptimescl ppluscl p0cl p1cl oneCl := p1cl
def inductionOpB {n : ℕ} {P : ((OpBoundedDistributiveLatticeTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpBoundedDistributiveLatticeTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((∀ (x1 x2 : (OpBoundedDistributiveLatticeTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → ((P zeroOL) → ((P oneOL) → (∀ (x : (OpBoundedDistributiveLatticeTerm n)) , (P x)))))))
| pv ptimesol pplusol p0ol p1ol (v x1) := (pv x1)
| pv ptimesol pplusol p0ol p1ol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol pplusol p0ol p1ol x1) (inductionOpB pv ptimesol pplusol p0ol p1ol x2))
| pv ptimesol pplusol p0ol p1ol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv ptimesol pplusol p0ol p1ol x1) (inductionOpB pv ptimesol pplusol p0ol p1ol x2))
| pv ptimesol pplusol p0ol p1ol zeroOL := p0ol
| pv ptimesol pplusol p0ol p1ol oneOL := p1ol
def inductionOp {n : ℕ} {A : Type} {P : ((OpBoundedDistributiveLatticeTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpBoundedDistributiveLatticeTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((∀ (x1 x2 : (OpBoundedDistributiveLatticeTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → ((P zeroOL2) → ((P oneOL2) → (∀ (x : (OpBoundedDistributiveLatticeTerm2 n A)) , (P x))))))))
| pv2 psing2 ptimesol2 pplusol2 p0ol2 p1ol2 (v2 x1) := (pv2 x1)
| pv2 psing2 ptimesol2 pplusol2 p0ol2 p1ol2 (sing2 x1) := (psing2 x1)
| pv2 psing2 ptimesol2 pplusol2 p0ol2 p1ol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 p1ol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 p1ol2 x2))
| pv2 psing2 ptimesol2 pplusol2 p0ol2 p1ol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 p1ol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 p0ol2 p1ol2 x2))
| pv2 psing2 ptimesol2 pplusol2 p0ol2 p1ol2 zeroOL2 := p0ol2
| pv2 psing2 ptimesol2 pplusol2 p0ol2 p1ol2 oneOL2 := p1ol2
def stageB : (BoundedDistributiveLatticeTerm → (Staged BoundedDistributiveLatticeTerm))
| (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2))
| (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2))
| zeroL := (Now zeroL)
| oneL := (Now oneL)
def stageCl {A : Type} : ((ClBoundedDistributiveLatticeTerm A) → (Staged (ClBoundedDistributiveLatticeTerm A)))
| (sing x1) := (Now (sing x1))
| (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2))
| (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2))
| zeroCl := (Now zeroCl)
| oneCl := (Now oneCl)
def stageOpB {n : ℕ} : ((OpBoundedDistributiveLatticeTerm n) → (Staged (OpBoundedDistributiveLatticeTerm n)))
| (v x1) := (const (code (v x1)))
| (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2))
| (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2))
| zeroOL := (Now zeroOL)
| oneOL := (Now oneOL)
def stageOp {n : ℕ} {A : Type} : ((OpBoundedDistributiveLatticeTerm2 n A) → (Staged (OpBoundedDistributiveLatticeTerm2 n A)))
| (sing2 x1) := (Now (sing2 x1))
| (v2 x1) := (const (code (v2 x1)))
| (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2))
| (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2))
| zeroOL2 := (Now zeroOL2)
| oneOL2 := (Now oneOL2)
structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type :=
(timesT : ((Repr A) → ((Repr A) → (Repr A))))
(plusT : ((Repr A) → ((Repr A) → (Repr A))))
(zeroT : (Repr A))
(oneT : (Repr A))
end BoundedDistributiveLattice |
098f1134dda9c908f8933fc359bd69321eaedcc8 | 22e97a5d648fc451e25a06c668dc03ac7ed7bc25 | /src/data/semiquot.lean | 9334ab21aba753c7e4dd262dc430203b81eb2f3c | [
"Apache-2.0"
] | permissive | keeferrowan/mathlib | f2818da875dbc7780830d09bd4c526b0764a4e50 | aad2dfc40e8e6a7e258287a7c1580318e865817e | refs/heads/master | 1,661,736,426,952 | 1,590,438,032,000 | 1,590,438,032,000 | 266,892,663 | 0 | 0 | Apache-2.0 | 1,590,445,835,000 | 1,590,445,835,000 | null | UTF-8 | Lean | false | false | 7,454 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
A data type for semiquotients, which are classically equivalent to
nonempty sets, but are useful for programming; the idea is that
a semiquotient set `S` represents some (particular but unknown)
element of `S`. This can be used to model nondeterministic functions,
which return something in a range of values (represented by the
predicate `S`) but are not completely determined.
-/
import data.set.lattice
/-- A member of `semiquot α` is classically a nonempty `set α`,
and in the VM is represented by an element of `α`; the relation
between these is that the VM element is required to be a member
of the set `s`. The specific element of `s` that the VM computes
is hidden by a quotient construction, allowing for the representation
of nondeterministic functions. -/
structure {u} semiquot (α : Type*) := mk' ::
(s : set α)
(val : trunc ↥s)
namespace semiquot
variables {α : Type*} {β : Type*}
instance : has_mem α (semiquot α) := ⟨λ a q, a ∈ q.s⟩
/-- Construct a `semiquot α` from `h : a ∈ s` where `s : set α`. -/
def mk {a : α} {s : set α} (h : a ∈ s) : semiquot α :=
⟨s, trunc.mk ⟨a, h⟩⟩
theorem ext_s {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ q₁.s = q₂.s :=
⟨congr_arg _,
λ h, by cases q₁; cases q₂; congr; exact h⟩
theorem ext {q₁ q₂ : semiquot α} : q₁ = q₂ ↔ ∀ a, a ∈ q₁ ↔ a ∈ q₂ :=
ext_s.trans set.ext_iff
theorem exists_mem (q : semiquot α) : ∃ a, a ∈ q :=
let ⟨⟨a, h⟩, h₂⟩ := q.2.exists_rep in ⟨a, h⟩
theorem eq_mk_of_mem {q : semiquot α} {a : α} (h : a ∈ q) :
q = @mk _ a q.1 h := ext_s.2 rfl
theorem nonempty (q : semiquot α) : q.s.nonempty := q.exists_mem
/-- `pure a` is `a` reinterpreted as an unspecified element of `{a}`. -/
protected def pure (a : α) : semiquot α := mk (set.mem_singleton a)
@[simp] theorem mem_pure' {a b : α} : a ∈ semiquot.pure b ↔ a = b :=
set.mem_singleton_iff
/-- Replace `s` in a `semiquot` with a superset. -/
def blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s) : semiquot α :=
⟨s, trunc.lift (λ a : q.s, trunc.mk ⟨a.1, h a.2⟩)
(λ _ _, trunc.eq _ _) q.2⟩
/-- Replace `s` in a `q : semiquot α` with a union `s ∪ q.s` -/
def blur (s : set α) (q : semiquot α) : semiquot α :=
blur' q (set.subset_union_right s q.s)
theorem blur_eq_blur' (q : semiquot α) (s : set α) (h : q.s ⊆ s) :
blur s q = blur' q h :=
by unfold blur; congr; exact set.union_eq_self_of_subset_right h
@[simp] theorem mem_blur' (q : semiquot α) {s : set α} (h : q.s ⊆ s)
{a : α} : a ∈ blur' q h ↔ a ∈ s := iff.rfl
/-- Convert a `trunc α` to a `semiquot α`. -/
def of_trunc (q : trunc α) : semiquot α :=
⟨set.univ, q.map (λ a, ⟨a, trivial⟩)⟩
/-- Convert a `semiquot α` to a `trunc α`. -/
def to_trunc (q : semiquot α) : trunc α :=
q.2.map subtype.val
/-- If `f` is a constant on `q.s`, then `q.lift_on f` is the value of `f`
at any point of `q`. -/
def lift_on (q : semiquot α) (f : α → β) (h : ∀ a b ∈ q, f a = f b) : β :=
trunc.lift_on q.2 (λ x, f x.1) (λ x y, h _ _ x.2 y.2)
theorem lift_on_of_mem (q : semiquot α)
(f : α → β) (h : ∀ a b ∈ q, f a = f b)
(a : α) (aq : a ∈ q) : lift_on q f h = f a :=
by revert h; rw eq_mk_of_mem aq; intro; refl
def map (f : α → β) (q : semiquot α) : semiquot β :=
⟨f '' q.1, q.2.map (λ x, ⟨f x.1, set.mem_image_of_mem _ x.2⟩)⟩
@[simp] theorem mem_map (f : α → β) (q : semiquot α) (b : β) :
b ∈ map f q ↔ ∃ a, a ∈ q ∧ f a = b := set.mem_image _ _ _
def bind (q : semiquot α) (f : α → semiquot β) : semiquot β :=
⟨⋃ a ∈ q.1, (f a).1,
q.2.bind (λ a, (f a.1).2.map (λ b, ⟨b.1, set.mem_bUnion a.2 b.2⟩))⟩
@[simp] theorem mem_bind (q : semiquot α) (f : α → semiquot β) (b : β) :
b ∈ bind q f ↔ ∃ a ∈ q, b ∈ f a := set.mem_bUnion_iff
instance : monad semiquot :=
{ pure := @semiquot.pure,
map := @semiquot.map,
bind := @semiquot.bind }
@[simp] theorem mem_pure {a b : α} : a ∈ (pure b : semiquot α) ↔ a = b :=
set.mem_singleton_iff
theorem mem_pure_self (a : α) : a ∈ (pure a : semiquot α) :=
set.mem_singleton a
@[simp] theorem pure_inj {a b : α} : (pure a : semiquot α) = pure b ↔ a = b :=
ext_s.trans set.singleton_eq_singleton_iff
instance : is_lawful_monad semiquot :=
{ pure_bind := λ α β x f, ext.2 $ by simp,
bind_assoc := λ α β γ s f g, ext.2 $ by simp; exact
λ c, ⟨λ ⟨b, ⟨a, as, bf⟩, cg⟩, ⟨a, as, b, bf, cg⟩,
λ ⟨a, as, b, bf, cg⟩, ⟨b, ⟨a, as, bf⟩, cg⟩⟩,
id_map := λ α q, ext.2 $ by simp,
bind_pure_comp_eq_map := λ α β f s, ext.2 $ by simp [eq_comm] }
instance : has_le (semiquot α) := ⟨λ s t, s.s ⊆ t.s⟩
instance : partial_order (semiquot α) :=
{ le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t,
le_refl := λ s, set.subset.refl _,
le_trans := λ s t u, set.subset.trans,
le_antisymm := λ s t h₁ h₂, ext_s.2 (set.subset.antisymm h₁ h₂) }
instance : semilattice_sup (semiquot α) :=
{ sup := λ s, blur s.s,
le_sup_left := λ s t, set.subset_union_left _ _,
le_sup_right := λ s t, set.subset_union_right _ _,
sup_le := λ s t u, set.union_subset,
..semiquot.partial_order }
@[simp] theorem pure_le {a : α} {s : semiquot α} : pure a ≤ s ↔ a ∈ s :=
set.singleton_subset_iff
def is_pure (q : semiquot α) := ∀ a b ∈ q, a = b
def get (q : semiquot α) (h : q.is_pure) : α := lift_on q id h
theorem get_mem {q : semiquot α} (p) : get q p ∈ q :=
let ⟨a, h⟩ := exists_mem q in
by unfold get; rw lift_on_of_mem q _ _ a h; exact h
theorem eq_pure {q : semiquot α} (p) : q = pure (get q p) :=
ext.2 $ λ a, by simp; exact
⟨λ h, p _ _ h (get_mem _), λ e, e.symm ▸ get_mem _⟩
@[simp] theorem pure_is_pure (a : α) : is_pure (pure a)
| b c ab ac := by { simp at ab ac, cc }
theorem is_pure_iff {s : semiquot α} : is_pure s ↔ ∃ a, s = pure a :=
⟨λ h, ⟨_, eq_pure h⟩, λ ⟨a, e⟩, e.symm ▸ pure_is_pure _⟩
theorem is_pure.mono {s t : semiquot α}
(st : s ≤ t) (h : is_pure t) : is_pure s
| a b as bs := h _ _ (st as) (st bs)
theorem is_pure.min {s t : semiquot α} (h : is_pure t) : s ≤ t ↔ s = t :=
⟨λ st, le_antisymm st $ by rw [eq_pure h, eq_pure (h.mono st)]; simp;
exact h _ _ (get_mem _) (st $ get_mem _),
le_of_eq⟩
theorem is_pure_of_subsingleton [subsingleton α] (q : semiquot α) : is_pure q
| a b aq bq := subsingleton.elim _ _
/-- `univ : semiquot α` represents an unspecified element of `univ : set α`. -/
def univ [inhabited α] : semiquot α :=
mk $ set.mem_univ (default _)
instance [inhabited α] : inhabited (semiquot α) := ⟨univ⟩
@[simp] theorem mem_univ [inhabited α] : ∀ a, a ∈ @univ α _ :=
@set.mem_univ α
@[congr] theorem univ_unique (I J : inhabited α) : @univ _ I = @univ _ J :=
ext.2 $ by simp
@[simp] theorem is_pure_univ [inhabited α] : @is_pure α univ ↔ subsingleton α :=
⟨λ h, ⟨λ a b, h a b trivial trivial⟩, λ ⟨h⟩ a b _ _, h a b⟩
instance [inhabited α] : order_top (semiquot α) :=
{ top := univ,
le_top := λ s, set.subset_univ _,
..semiquot.partial_order }
instance [inhabited α] : semilattice_sup_top (semiquot α) :=
{ ..semiquot.order_top,
..semiquot.semilattice_sup }
end semiquot
|
1d5bcd9e1056bd1c4e1877ce6c51b17521420351 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/def13.lean | 2358a6088940fa5ebd8c96d738c935911752b74e | [
"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 | 492 | lean | inductive vec (A : Type) : nat → Type
| nil {} : vec 0
| cons : Π {n}, A → vec n → vec (n+1)
open vec
variables {A : Type}
variables f : A → A → A
definition map_head_1 : ∀ {n}, vec A n → vec A n → vec A n
| .(0) nil nil := nil
| .(n+1) (@cons .(A) n a va) (cons b vb) := cons (f a b) va
example : map_head_1 f nil nil = nil :=
rfl
example (a b : A) (n : nat) (va vb : vec A n) : map_head_1 f (cons a va) (cons b vb) = cons (f a b) va :=
rfl
|
be97530412a1eabac20912d4356aebad3ef1b36f | 70f8755415fa7a17f87402cde4651e9f4db1b5bb | /src/for_mathlib.lean | f8d3f9a6e05facd8091197ae5f4a93672c2a6dbe | [
"Apache-2.0"
] | permissive | shingarov/qpf | ab935dc2298db12c87ac011a2e4d2c27e0bdef4b | debe2eacb8cf46b21aba2eaf3f2e20940da0263b | refs/heads/master | 1,653,705,576,607 | 1,570,136,035,000 | 1,570,136,035,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 22,733 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Simon Hudon
-/
import data.pfun category.functor category.applicative data.list.sort data.list.basic
universes u v
lemma eq_mp_heq :
∀ {α β : Sort*} {a : α} {a' : β} (h₂ : a == a'), (eq.mp (type_eq_of_heq h₂) a) = a'
| α ._ a a' heq.rfl := rfl
namespace sigma
variables {α₁ α₂ α₃ : Type u}
variables {β₁ : α₁ → Type v} {β₂ : α₂ → Type v} {β₃ : α₃ → Type v}
variables {g : sigma β₂ → sigma β₃} {f : sigma β₁ → sigma β₂}
theorem eq_fst {s₁ s₂ : sigma β₁} : s₁ = s₂ → s₁.1 = s₂.1 :=
by cases s₁; cases s₂; cc
theorem eq_snd {s₁ s₂ : sigma β₁} : s₁ = s₂ → s₁.2 == s₂.2 :=
by cases s₁; cases s₂; cc
@[extensionality]
lemma ext {x₀ x₁ : sigma β₁}
(h₀ : x₀.1 = x₁.1)
(h₁ : x₀.1 = x₁.1 → x₀.2 == x₁.2) :
x₀ = x₁ :=
by casesm* sigma _; cases h₀; cases h₁ h₀; refl
lemma eta (x : sigma β₁) : sigma.mk x.1 x.2 = x :=
by cases x; refl
end sigma
namespace list
def zip_with₃ {α β γ φ} (f : α → β → γ → φ) : list α → list β → list γ → list φ
| (x::xs) (y::ys) (z::zs) := f x y z :: zip_with₃ xs ys zs
| _ _ _ := []
variables {m : Type u → Type v} [applicative m]
def mzip_with₃ {α β γ φ} (f : α → β → γ → m φ) : list α → list β → list γ → m (list φ)
| (x::xs) (y::ys) (z::zs) := (::) <$> f x y z <*> mzip_with₃ xs ys zs
| _ _ _ := pure []
def mzip_with₄ {α β γ φ ψ} (f : α → β → γ → φ → m ψ) :
list α → list β → list γ → list φ → m (list ψ)
| (w :: ws) (x::xs) (y::ys) (z::zs) := (::) <$> f w x y z <*> mzip_with₄ ws xs ys zs
| _ _ _ _ := pure []
-- def mmap_enum_if' {α} (p : α → Prop) [decidable_pred p] (f : ℕ → α → m α) : ℕ → list α → m (list α)
-- | n [] := pure []
-- | n (x :: xs) :=
-- if p x then (::) <$> f n x <*> mmap_enum_if' (n+1) xs
-- else cons x <$> mmap_enum_if' n xs
-- def mmap_enum_if {α} (p : α → Prop) [decidable_pred p] (f : ℕ → α → m α) : list α → m (list α) :=
-- mmap_enum_if' p f 0
end list
namespace roption
variables {α : Type*} {β : Type*} {γ : Type*}
open function
lemma assert_if_neg {p : Prop}
(x : p → roption α)
(h : ¬ p)
: assert p x = roption.none :=
by { dsimp [assert,roption.none],
have : (∃ (h : p), (x h).dom) ↔ false,
{ split ; intros h' ; repeat { cases h' with h' },
exact h h' },
congr,
repeat { rw this <|> apply hfunext },
intros h h', cases h', }
lemma assert_if_pos {p : Prop}
(x : p → roption α)
(h : p)
: assert p x = x h :=
by { dsimp [assert],
have : (∃ (h : p), (x h).dom) ↔ (x h).dom,
{ split ; intros h'
; cases h' <|> split
; assumption, },
cases hx : x h, congr, rw [this,hx],
apply hfunext, rw [this,hx],
intros, simp [hx] }
@[simp]
lemma roption.none_bind {α β : Type*} (f : α → roption β)
: roption.none >>= f = roption.none :=
by simp [roption.none,has_bind.bind,roption.bind,assert_if_neg]
end roption
namespace monad
@[simp]
lemma bind_pure_star {m} [monad m] [is_lawful_monad m] (x : m punit) :
x >>= (λ (_x : punit), pure punit.star : punit → m punit) = x :=
by { transitivity,
{ apply congr_arg, ext z, cases z, refl },
{ simp } }
variables {α β γ : Type u}
variables {m : Type u → Type v} [monad m]
@[reducible]
def pipe (a : α → m β) (b : β → m γ) : α → m γ :=
λ x, a x >>= b
infixr ` >=> `:55 := pipe
@[functor_norm]
lemma map_bind_eq_bind_comp {α β γ} {m} [monad m] [is_lawful_monad m]
(f : α → β) (cmd : m α) (g : β → m γ) :
(f <$> cmd) >>= g = cmd >>= g ∘ f :=
by rw [← bind_pure_comp_eq_map,bind_assoc,(∘)]; simp
@[functor_norm]
lemma bind_map {α β γ} {m} [monad m] [is_lawful_monad m]
(f : α → γ → β) (cmd : m α) (g : α → m γ) :
cmd >>= (λ x, f x <$> g x) = do { x ← cmd, y ← g x, pure $ f x y } :=
by congr; ext; rw [← bind_pure (g x),map_bind]; simp
@[functor_norm]
lemma bind_seq {α β γ : Type u} {m} [monad m] [is_lawful_monad m]
(f : α → m (γ → β)) (cmd : m α) (g : α → m γ) :
cmd >>= (λ x, f x <*> g x) = do { x ← cmd, h ← f x, y ← g x, pure $ h y } :=
by congr; ext; simp [seq_eq_bind_map] with functor_norm
end monad
attribute [functor_norm] bind_assoc has_bind.and_then map_bind seq_left_eq seq_right_eq
namespace sum
variables {e : Type v} {α β : Type u}
protected def seq : Π (x : sum e (α → β)) (f : sum e α), sum e β
| (sum.inl e) _ := sum.inl e
| (sum.inr f) x := f <$> x
instance : applicative (sum e) :=
{ seq := @sum.seq e,
pure := @sum.inr e }
instance : is_lawful_applicative (sum e) :=
by constructor; intros;
casesm* _ ⊕ _; simp [(<*>),sum.seq,pure,(<$>)];
refl
end sum
namespace functor
def foldl (α : Type u) (β : Type v) := α → α
def foldr (α : Type u) (β : Type v) := α → α
instance foldr.applicative {α} : applicative (foldr α) :=
{ pure := λ _ _, id,
seq := λ _ _ f x, f ∘ x }
instance foldl.applicative {α} : applicative (foldl α) :=
{ pure := λ _ _, id,
seq := λ _ _ f x, x ∘ f }
instance foldr.is_lawful_applicative {α} : is_lawful_applicative (foldr α) :=
by refine { .. }; intros; refl
instance foldl.is_lawful_applicative {α} : is_lawful_applicative (foldl α) :=
by refine { .. }; intros; refl
def foldr.eval {α β} (x : foldr α β) : α → α := x
def foldl.eval {α β} (x : foldl α β) : α → α := x
def foldl.cons {α β} (x : α) : foldl (list α) β :=
list.cons x
def foldr.cons {α β} (x : α) : foldr (list α) β :=
list.cons x
def foldl.cons' {α} (x : α) : foldl (list α) punit :=
list.cons x
def foldl.lift {α} (x : α → α) : foldl α punit := x
def foldr.lift {α} (x : α → α) : foldr α punit := x
end functor
instance {α : Type u} : traversable (prod.{u u} α) :=
{ map := λ β γ f (x : α × β), prod.mk x.1 $ f x.2,
traverse := λ m _ β γ f (x : α × β), by exactI prod.mk x.1 <$> f x.2 }
namespace traversable
variables {t : Type u → Type u} [traversable t]
def to_list {α} (x : t α) : list α :=
@functor.foldr.eval _ (t punit) (traverse functor.foldr.cons x) []
end traversable
/-
namespace name
-- def append_suffix : name → string → name
-- | (mk_string s n) s' := mk_string (s ++ s') n
-- | n _ := n
end name
-/
namespace level
meta def fold_mvar {α} : level → (name → α → α) → α → α
| zero f := id
| (succ a) f := fold_mvar a f
| (param a) f := id
| (mvar a) f := f a
| (max a b) f := fold_mvar a f ∘ fold_mvar b f
| (imax a b) f := fold_mvar a f ∘ fold_mvar b f
meta def pred : level → level
| level.zero := level.zero
| (level.succ a) := a
| (level.max a b) := max (pred a) (pred b)
| (level.imax a b) := max (pred a) (pred b)
| l@(level.param a) := l
| l@(level.mvar a) := l
end level
namespace native
namespace rb_map
-- #check rb_map
variables {key : Type} {val val' : Type}
-- section
variables [has_lt key] [decidable_rel ((<) : key → key → Prop)]
variables (f : val → val → val)
-- def intersect' : list (key × val) → list (key × val) → list (key × val)
-- | [] m := []
-- | ((k,x)::xs) [] := []
-- | ((k,x)::xs) ((k',x')::xs') :=
-- if h : k < k' then intersect' xs ((k',x')::xs')
-- else if k' < k then intersect' ((k,x)::xs) xs'
-- else (k,f x x') :: intersect' xs xs'
open function (on_fun)
def sort {α : Type} (f : α → key) : list α → list α := list.merge_sort (on_fun (<) f)
-- end
meta def filter_map (f : key → val → option val') (x : rb_map key val) : rb_map key val' :=
fold x (mk _ _) $ λa b m', (insert m' a <$> f a b).get_or_else m'
meta def intersect_with (m m' : rb_map key val) : rb_map key val :=
m.filter_map $ λ k x, f x <$> m'.find k
meta def intersect (x y : rb_map key val) : rb_map key val :=
intersect_with (function.const val) x y
meta def difference (m m' : rb_map key val) : rb_map key val :=
m.filter_map (λ k x, guard (¬ m'.contains k) >> pure x)
end rb_map
end native
namespace expr
meta def replace_all (e : expr) (p : expr → Prop) [decidable_pred p] (r : expr) : expr :=
e.replace $ λ e i, guard (p e) >> pure (r.lift_vars 0 i)
meta def const_params : expr → list level
| (const _ ls) := ls
| _ := []
meta def sort_univ : expr → level
| (sort ls) := ls
| _ := level.zero
meta def collect_meta_univ (e : expr) : list name :=
native.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s,
match e' with
| (sort u) := u.fold_mvar (flip native.rb_set.insert) s
| (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s
| _ := s
end
meta def instantiate_pi : expr → list expr → expr
| (expr.pi n bi d b) (e::es) := instantiate_pi (b.instantiate_var e) es
| e _ := e
end expr
namespace tactic
meta def unify_univ (u u' : level) : tactic unit :=
unify (expr.sort u) (expr.sort u')
meta def add_decl' (d : declaration) : tactic expr :=
do add_decl d,
pure $ expr.const d.to_name $ d.univ_params.map level.param
meta def renew : expr → tactic expr
| (expr.local_const uniq pp bi t) := mk_local' pp bi t
| e := fail format!"{e} is not a local constant"
meta def trace_expr (e : expr) : tactic expr :=
do t ← infer_type e >>= pp,
e' ← pp e,
trace format!"{e'} : {t}",
pure e
open declaration (defn)
meta def trace_def (n : name) : tactic unit :=
do (defn n _ t df _ _) ← get_decl n,
t ← pp t, df ← pp df,
trace format!"\ndef {n} : {t} :=\n{df}\n"
meta def is_type (e : expr) : tactic bool :=
do (expr.sort _) ← infer_type e | pure ff,
pure tt
meta def list_macros : expr → list (name × list expr) | e :=
e.fold [] (λ m i s,
match m with
| (expr.macro m args) := (expr.macro_def_name m, args) :: s
| _ := s end)
meta def expand_untrusted (tac : tactic unit) : tactic unit :=
do tgt ← target,
mv ← mk_meta_var tgt,
gs ← get_goals,
set_goals [mv],
tac,
env ← get_env,
pr ← env.unfold_untrusted_macros <$> instantiate_mvars mv,
set_goals gs,
exact pr
meta def binders : expr → tactic (list expr)
| (expr.pi n bi d b) :=
do v ← mk_local' n bi d,
(::) v <$> binders (b.instantiate_var v)
| _ := pure []
meta def rec_args_count (t c : name) : tactic ℕ :=
do ct ← mk_const c >>= infer_type,
(list.length ∘ list.filter (λ v : expr, v.local_type.is_app_of t)) <$> binders ct
meta def match_induct_hyp (n : name) : list expr → list expr → tactic (list $ expr × option expr)
| [] [] := pure []
| [] _ := fail "wrong number of inductive hypotheses"
| (x :: xs) [] := (::) (x,none) <$> match_induct_hyp xs []
| (x :: xs) (h :: hs) :=
do t ← infer_type x,
if t.is_app_of n
then (::) (x,h) <$> match_induct_hyp xs hs
else (::) (x,none) <$> match_induct_hyp xs (h :: hs)
meta def is_recursive_type (n : name) : tactic bool :=
do e ← get_env,
let cs := e.constructors_of n,
rs ← cs.mmap (rec_args_count n),
pure $ rs.any (λ r, r > 0)
meta def better_induction (e : expr) : tactic $ list (name × list (expr × option expr) × list (name × expr)) :=
do t ← infer_type e,
let tn := t.get_app_fn.const_name,
env ← get_env,
focus1 $
do vs ← induction e,
gs ← get_goals,
vs' ← list.mzip_with₃ (λ n g (pat : name × list expr × list (name × expr)),
do let ⟨_,args,σ⟩ := pat,
set_goals [g],
nrec ← rec_args_count tn n,
let ⟨args,rec⟩ := args.split_at (args.length - nrec),
args ← match_induct_hyp tn args rec,
pure ((n,args,σ))) (env.constructors_of tn) gs vs,
set_goals gs,
pure vs'
meta def extract_def' {α} (n : name) (trusted : bool) (elab_def : tactic α) : tactic α :=
do cxt ← list.map to_implicit <$> local_context,
t ← target,
(r,d) ← solve_aux t elab_def,
d ← instantiate_mvars d,
t' ← pis cxt t,
d' ← lambdas cxt d,
let univ := t'.collect_univ_params,
add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,
r <$ (applyc n; assumption)
open expr list nat
meta def remove_intl_const : expr → tactic expr
| v@(local_const uniq pp bi _) :=
do t ← infer_type v,
pure $ local_const uniq pp bi t
| e := pure e
meta def intron' : ℕ → tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> intro1 <*> intron' n
meta def unpi : expr → tactic (list expr × expr)
| (pi n bi d b) :=
do v ← mk_local' n bi d,
prod.map (cons v) id <$> unpi (b.instantiate_var v)
| e := pure ([],e)
meta def unify_app_aux : expr → expr → list expr → tactic expr
| e (pi _ _ d b) (a :: as) :=
do t ← infer_type a,
unify t d,
e' ← head_beta (e a),
b' ← whnf (b.instantiate_var a),
unify_app_aux e' b' as
| e t (_ :: _) := fail "too many arguments"
| e _ [] := pure e
meta def unify_app (e : expr) (args : list expr) : tactic expr :=
do t ← infer_type e >>= whnf,
unify_app_aux e t args
meta def unify_mapp_aux : expr → expr → list (option expr) → tactic expr
| e (pi _ _ d b) (none :: as) :=
do a ← mk_mvar,
t ← infer_type a,
unify t d,
e' ← head_beta (e a),
b' ← whnf (b.instantiate_var a),
unify_mapp_aux e' b' as
| e (pi _ _ d b) (some a :: as) :=
do t ← infer_type a,
unify t d,
e' ← head_beta (e a),
b' ← whnf (b.instantiate_var a),
unify_mapp_aux e' b' as
| e t (_ :: _) := fail "too many arguments"
| e _ [] := pure e
meta def unify_mapp (e : expr) (args : list (option expr)) : tactic expr :=
do t ← infer_type e >>= whnf,
unify_mapp_aux e t args
meta def mk_to_string (t : expr) (fn of_string : name) (ls : list expr) (out : expr) : tactic expr :=
do let n := t.get_app_fn.const_name,
d ← get_decl n,
let r : reducibility_hints := reducibility_hints.regular 1 tt,
env ← get_env,
ls ← local_context,
sig ← to_expr ``(%%t → %%out),
of_string ← mk_const of_string,
(_,df) ← solve_aux sig $ do
{ match env.structure_fields n with
| (some fs) :=
do a ← intro1,
[(_,xs,_)] ← cases_core a,
let l := xs.length,
fn' ← mk_const fn,
out ← list.mzip_with₄ (λ x (fn : name) (y : expr) z,
do let fn := (fn.update_prefix name.anonymous).to_string,
to_expr ``(%%of_string (%%(reflect x) ++ %%(reflect fn) ++ " := ") ++ %%fn' %%y ++ %%of_string %%(reflect z)))
("{ " :: list.repeat " " (l-1)) fs xs (list.repeat ",\n" (l-1) ++ [" }"]),
to_expr (out.foldr (λ e acc, ``(%%e ++ %%acc)) ``(%%of_string %%(reflect "" : expr))) >>= exact,
pure ()
| none :=
do g ← main_goal,
a ← intro1,
xs ← cases_core a,
fn ← mk_const fn,
out ← xs.mmap $ λ ⟨c,xs,_⟩,
do { out ← xs.mmap $ λ x, to_expr ``(%%of_string " (" ++ %%fn %%x ++ %%of_string ")"),
let c := (c.update_prefix name.anonymous).to_string,
to_expr (out.foldr (λ e acc, ``(%%e ++ %%acc)) ``(%%of_string %%(reflect c : expr))) >>= exact },
pure () end },
df ← instantiate_mvars df >>= lambdas ls,
t ← infer_type df,
add_decl' $ declaration.defn (n ++ fn) d.univ_params t df r d.is_trusted
meta def mk_has_to_format : tactic unit :=
do `(has_to_format %%t) ← target,
ls ← local_context,
e ← mk_to_string t `to_fmt `format.of_string ls `(format),
refine ``( { to_format := %%(e.mk_app ls) } ),
pure ()
meta def mk_has_repr : tactic unit :=
do `(has_repr %%t) ← target,
ls ← local_context,
e ← mk_to_string t `repr `id ls `(string),
refine ``( { repr := %%(e.mk_app ls) } ),
pure ()
@[derive_handler]
meta def has_repr_derive_handler : derive_handler :=
instance_derive_handler ``has_repr mk_has_repr
@[derive_handler]
meta def has_to_format_derive_handler : derive_handler :=
instance_derive_handler ``has_to_format mk_has_to_format
instance name.has_repr : has_repr name :=
{ repr := λ x, "`" ++ x.to_string }
private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α :=
fail format!"invalid simplification lemma '{n}' (use command 'set_option trace.simp_lemmas true' for more details)"
private meta def check_no_overload (p : pexpr) : tactic unit :=
when p.is_choice_macro $
match p with
| macro _ ps :=
fail $ to_fmt "ambiguous overload, possible interpretations" ++
format.join (ps.map (λ p, (to_fmt p).indent 4))
| _ := failed
end
private meta def add_simps : simp_lemmas → list name → tactic simp_lemmas
| s [] := return s
| s (n::ns) := do s' ← s.add_simp n, add_simps s' ns
private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : list name) (n : name) (ref : pexpr) : tactic (simp_lemmas × list name) :=
do
p ← resolve_name n,
check_no_overload p,
-- unpack local refs
let e := p.erase_annotations.get_app_fn.erase_annotations,
match e with
| const n _ :=
(do b ← is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s ← s.add_simp n, return (s, u))
<|>
(do eqns ← get_eqn_lemmas_for tt n, guard (eqns.length > 0), save_const_type_info n ref, s ← add_simps s eqns, return (s, u))
<|>
(do env ← get_env, guard (env.is_projection n).is_some, return (s, n::u))
<|>
report_invalid_simp_lemma n
| _ :=
(do e ← i_to_expr_no_subgoals p, b ← is_valid_simp_lemma e, guard b, try (save_type_info e ref), s ← s.add e, return (s, u))
<|>
report_invalid_simp_lemma n
end
meta def simp_lemmas.add_pexpr (s : simp_lemmas) (u : list name) (p : pexpr) : tactic (simp_lemmas × list name) :=
match p with
| (const c []) := simp_lemmas.resolve_and_add s u c p
| (local_const c _ _ _) := simp_lemmas.resolve_and_add s u c p
| _ := do new_e ← i_to_expr_no_subgoals p, s ← s.add new_e, return (s, u)
end
meta def simp_lemmas.append_pexprs : simp_lemmas → list name → list pexpr → tactic (simp_lemmas × list name)
| s u [] := return (s, u)
| s u (l::ls) := do (s, u) ← simp_lemmas.add_pexpr s u l, simp_lemmas.append_pexprs s u ls
meta def simp_only (ls : list pexpr) (attrs : list name := []) : tactic unit :=
do let ls := ls.map (simp_arg_type.expr), -- >>= simp_lemmas.append_pexprs simp_lemmas.mk [],
-- interactive.dsimp tt ls [] (interactive.loc.ns [none])
interactive.simp none tt ls attrs (interactive.loc.ns [none])
meta def mk_substitution (vs : list expr) : tactic (list expr × list (name × expr)) :=
do vs' ← intron' vs.length,
let σ := (vs.map expr.local_uniq_name).zip vs',
pure (vs', σ)
open interactive.types interactive lean.parser
@[user_command]
meta def test_signature_cmd (_ : parse $ tk "#test") : lean.parser unit :=
do e ← ident,
show tactic unit, from
do d ← get_decl e,
let e := @const tt d.to_name d.univ_levels,
t ← infer_type e >>= pp,
e.collect_meta_univ.enum.mmap' $ λ ⟨i,v⟩, unify_univ (level.mvar v) (level.param ("u_" ++ to_string i : string)),
e ← instantiate_mvars e,
e ← pp e,
trace format!"\nexample : {t} :=\n{e}\n",
pure ()
end tactic
namespace tactic.interactive
open lean lean.parser interactive interactive.types tactic
local postfix `*`:9000 := many
meta def splita := split; [skip, assumption]
@[hole_command]
meta def whnf_type_hole : hole_command :=
{ name := "Reduce expected type",
descr := "Reduce expected type",
action := λ es,
do t ← match es with
| [h] := to_expr h >>= infer_type >>= whnf
| [] := target >>= whnf
| _ := fail "too many expressions"
end,
trace t,
pure [] }
meta def trace_error {α} (tac : tactic α) : tactic α
| s :=
match tac s with
| r@(interaction_monad.result.success a a_1) := r
| r@(interaction_monad.result.exception none a_1 a_2) := (trace "(no error message)" >> interaction_monad.result.exception none a_1) s
| r@(interaction_monad.result.exception (some msg) a_1 a_2) := (trace (msg ()) >> interaction_monad.result.exception none a_1) s
end
end tactic.interactive
instance subsingleton.fin0 {α} : subsingleton (fin 0 → α) :=
subsingleton.intro $ λ a b, funext $ λ i, fin.elim0 i
attribute [extensionality] function.hfunext
meta def options.list_names (o : options) : list name := o.fold [] (::)
namespace expr
meta def bracket (p : ℕ) (fmt : format) (p' : ℕ) : format :=
if p' < p then format.paren fmt else fmt
meta def fmt_binder (n : name) : binder_info → format → format
| binder_info.default t := format!"({n} : {t})"
| binder_info.implicit t := format!"{{{n} : {t}}"
| binder_info.strict_implicit t := format!"⦃{n} : {t}⦄"
| binder_info.inst_implicit t := format!"[{n} : {t}]"
| binder_info.aux_decl t := "_"
meta def parsable_printer' : expr → list name → ℕ → format
| (expr.var a) l := λ _, format!"@{(l.nth a).get_or_else name.anonymous}"
| (expr.sort level.zero) l := λ _, to_fmt "Prop"
| (expr.sort (level.succ u)) l := λ _, format!"Type.{{{u}}"
| (expr.sort u) l := λ _, format!"Sort.{{{u}}"
| (expr.const a []) l := λ _, format!"@{a}"
| (expr.const a ls) l := λ _, format!"@{a}.{{{format.intercalate \" \" $ list.map to_fmt ls}}"
| (expr.mvar a a_1 a_2) l := λ _, to_fmt a
| (expr.local_const a a_1 a_2 a_3) l := λ _, to_fmt a_1
| (expr.app a a_1) l := bracket 10 $ format!"{parsable_printer' a l 10} {parsable_printer' a_1 l 9}"
| (expr.lam a a_1 a_2 a_3) l := bracket 8 $ format!"λ {fmt_binder a a_1 $ parsable_printer' a_2 l 10}, {parsable_printer' a_3 (a :: l) 10}"
| (expr.pi a a_1 a_2 a_3) l :=
if a_3.has_var_idx 0
then bracket 8 $ format!"Π {fmt_binder a a_1 $ parsable_printer' a_2 l 10}, {parsable_printer' a_3 (a :: l) 10}"
else bracket 8 $ format!"{parsable_printer' a_2 l 7} → {parsable_printer' a_3 (a :: l) 7}"
| (expr.elet a a_1 a_2 a_3) l := bracket 8 $ format!"let {a} : {parsable_printer' a_1 l 10} := {parsable_printer' a_2 l 10} in {parsable_printer' a_3 (a :: l) 10}"
| (expr.macro a a_1) l := λ _, to_fmt "unsupported"
meta def parsable_printer (e : expr) : format := parsable_printer' e [] 10
meta def as_binder (e : expr) := fmt_binder e.local_pp_name e.binding_info (parsable_printer e.local_type)
end expr
meta def stack_trace : vm_monitor ℕ :=
{ init := 0,
step := λ i,
do j ← vm.stack_size,
if i = j then pure i else do
fn ← vm.curr_fn,
vm.put_str $ (list.repeat ' ' j).as_string ++ fn.to_string,
pure j }
lemma mpr_mpr : Π {α β} (h : α = β) (h' : β = α) (x : α), h.mpr (h'.mpr x) = x
| _ _ rfl rfl x := rfl
|
37320bed021d5bc3263188a43a1fe1ec9887e832 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/algebra/indicator_function.lean | 7b0b2702fa0e74d115467909afefc105885a1d3e | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 20,205 | lean | /-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import algebra.support
/-!
# Indicator function
- `indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `0` otherwise.
- `mul_indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `1` otherwise.
## Implementation note
In mathematics, an indicator function or a characteristic function is a function
used to indicate membership of an element in a set `s`,
having the value `1` for all elements of `s` and the value `0` otherwise.
But since it is usually used to restrict a function to a certain set `s`,
we let the indicator function take the value `f x` for some function `f`, instead of `1`.
If the usual indicator function is needed, just set `f` to be the constant function `λx, 1`.
## Tags
indicator, characteristic
-/
noncomputable theory
open_locale classical big_operators
open function
variables {α β ι M N : Type*}
namespace set
section has_one
variables [has_one M] [has_one N] {s t : set α} {f g : α → M} {a : α}
/-- `indicator s f a` is `f a` if `a ∈ s`, `0` otherwise. -/
def indicator {M} [has_zero M] (s : set α) (f : α → M) : α → M := λ x, if x ∈ s then f x else 0
/-- `mul_indicator s f a` is `f a` if `a ∈ s`, `1` otherwise. -/
@[to_additive]
def mul_indicator (s : set α) (f : α → M) : α → M := λ x, if x ∈ s then f x else 1
@[simp, to_additive] lemma piecewise_eq_mul_indicator : s.piecewise f 1 = s.mul_indicator f := rfl
@[to_additive] lemma mul_indicator_apply (s : set α) (f : α → M) (a : α) :
mul_indicator s f a = if a ∈ s then f a else 1 := rfl
@[simp, to_additive] lemma mul_indicator_of_mem (h : a ∈ s) (f : α → M) :
mul_indicator s f a = f a := if_pos h
@[simp, to_additive] lemma mul_indicator_of_not_mem (h : a ∉ s) (f : α → M) :
mul_indicator s f a = 1 := if_neg h
@[to_additive] lemma mul_indicator_eq_one_or_self (s : set α) (f : α → M) (a : α) :
mul_indicator s f a = 1 ∨ mul_indicator s f a = f a :=
if h : a ∈ s then or.inr (mul_indicator_of_mem h f) else or.inl (mul_indicator_of_not_mem h f)
@[simp, to_additive] lemma mul_indicator_apply_eq_self :
s.mul_indicator f a = f a ↔ (a ∉ s → f a = 1) :=
ite_eq_left_iff.trans $ by rw [@eq_comm _ (f a)]
@[simp, to_additive] lemma mul_indicator_eq_self : s.mul_indicator f = f ↔ mul_support f ⊆ s :=
by simp only [funext_iff, subset_def, mem_mul_support, mul_indicator_apply_eq_self, not_imp_comm]
@[to_additive] lemma mul_indicator_eq_self_of_superset (h1 : s.mul_indicator f = f) (h2 : s ⊆ t) :
t.mul_indicator f = f :=
by { rw mul_indicator_eq_self at h1 ⊢, exact subset.trans h1 h2 }
@[simp, to_additive] lemma mul_indicator_apply_eq_one :
mul_indicator s f a = 1 ↔ (a ∈ s → f a = 1) :=
ite_eq_right_iff
@[simp, to_additive] lemma mul_indicator_eq_one :
mul_indicator s f = (λ x, 1) ↔ disjoint (mul_support f) s :=
by simp only [funext_iff, mul_indicator_apply_eq_one, set.disjoint_left, mem_mul_support,
not_imp_not]
@[simp, to_additive] lemma mul_indicator_eq_one' :
mul_indicator s f = 1 ↔ disjoint (mul_support f) s :=
mul_indicator_eq_one
@[simp, to_additive] lemma mul_support_mul_indicator :
function.mul_support (s.mul_indicator f) = s ∩ function.mul_support f :=
ext $ λ x, by simp [function.mem_mul_support, mul_indicator_apply_eq_one]
/-- If a multiplicative indicator function is not equal to one at a point, then that
point is in the set. -/
@[to_additive] lemma mem_of_mul_indicator_ne_one (h : mul_indicator s f a ≠ 1) : a ∈ s :=
not_imp_comm.1 (λ hn, mul_indicator_of_not_mem hn f) h
@[to_additive] lemma eq_on_mul_indicator : eq_on (mul_indicator s f) f s :=
λ x hx, mul_indicator_of_mem hx f
@[to_additive] lemma mul_support_mul_indicator_subset : mul_support (s.mul_indicator f) ⊆ s :=
λ x hx, hx.imp_symm (λ h, mul_indicator_of_not_mem h f)
@[simp, to_additive] lemma mul_indicator_mul_support : mul_indicator (mul_support f) f = f :=
mul_indicator_eq_self.2 subset.rfl
@[simp, to_additive] lemma mul_indicator_range_comp {ι : Sort*} (f : ι → α) (g : α → M) :
mul_indicator (range f) g ∘ f = g ∘ f :=
piecewise_range_comp _ _ _
@[to_additive] lemma mul_indicator_congr (h : eq_on f g s) :
mul_indicator s f = mul_indicator s g :=
funext $ λx, by { simp only [mul_indicator], split_ifs, { exact h h_1 }, refl }
@[simp, to_additive] lemma mul_indicator_univ (f : α → M) : mul_indicator (univ : set α) f = f :=
mul_indicator_eq_self.2 $ subset_univ _
@[simp, to_additive] lemma mul_indicator_empty (f : α → M) : mul_indicator (∅ : set α) f = λa, 1 :=
mul_indicator_eq_one.2 $ disjoint_empty _
@[to_additive] lemma mul_indicator_empty' (f : α → M) : mul_indicator (∅ : set α) f = 1 :=
mul_indicator_empty f
variable (M)
@[simp, to_additive] lemma mul_indicator_one (s : set α) :
mul_indicator s (λx, (1:M)) = λx, (1:M) :=
mul_indicator_eq_one.2 $ by simp only [mul_support_one, empty_disjoint]
@[simp, to_additive] lemma mul_indicator_one' {s : set α} : s.mul_indicator (1 : α → M) = 1 :=
mul_indicator_one M s
variable {M}
@[to_additive] lemma mul_indicator_mul_indicator (s t : set α) (f : α → M) :
mul_indicator s (mul_indicator t f) = mul_indicator (s ∩ t) f :=
funext $ λx, by { simp only [mul_indicator], split_ifs, repeat {simp * at * {contextual := tt}} }
@[simp, to_additive] lemma mul_indicator_inter_mul_support (s : set α) (f : α → M) :
mul_indicator (s ∩ mul_support f) f = mul_indicator s f :=
by rw [← mul_indicator_mul_indicator, mul_indicator_mul_support]
@[to_additive] lemma comp_mul_indicator (h : M → β) (f : α → M) {s : set α} {x : α} :
h (s.mul_indicator f x) = s.piecewise (h ∘ f) (const α (h 1)) x :=
s.apply_piecewise _ _ (λ _, h)
@[to_additive] lemma mul_indicator_comp_right {s : set α} (f : β → α) {g : α → M} {x : β} :
mul_indicator (f ⁻¹' s) (g ∘ f) x = mul_indicator s g (f x) :=
by { simp only [mul_indicator], split_ifs; refl }
@[to_additive] lemma mul_indicator_comp_of_one {g : M → N} (hg : g 1 = 1) :
mul_indicator s (g ∘ f) = g ∘ (mul_indicator s f) :=
begin
funext,
simp only [mul_indicator],
split_ifs; simp [*]
end
@[to_additive] lemma comp_mul_indicator_const (c : M) (f : M → N) (hf : f 1 = 1) :
(λ x, f (s.mul_indicator (λ x, c) x)) = s.mul_indicator (λ x, f c) :=
(mul_indicator_comp_of_one hf).symm
@[to_additive] lemma mul_indicator_preimage (s : set α) (f : α → M) (B : set M) :
(mul_indicator s f)⁻¹' B = s.ite (f ⁻¹' B) (1 ⁻¹' B) :=
piecewise_preimage s f 1 B
@[to_additive] lemma mul_indicator_preimage_of_not_mem (s : set α) (f : α → M)
{t : set M} (ht : (1:M) ∉ t) :
(mul_indicator s f)⁻¹' t = f ⁻¹' t ∩ s :=
by simp [mul_indicator_preimage, pi.one_def, set.preimage_const_of_not_mem ht]
@[to_additive] lemma mem_range_mul_indicator {r : M} {s : set α} {f : α → M} :
r ∈ range (mul_indicator s f) ↔ (r = 1 ∧ s ≠ univ) ∨ (r ∈ f '' s) :=
by simp [mul_indicator, ite_eq_iff, exists_or_distrib, eq_univ_iff_forall, and_comm, or_comm,
@eq_comm _ r 1]
@[to_additive] lemma mul_indicator_rel_mul_indicator {r : M → M → Prop} (h1 : r 1 1)
(ha : a ∈ s → r (f a) (g a)) :
r (mul_indicator s f a) (mul_indicator s g a) :=
by { simp only [mul_indicator], split_ifs with has has, exacts [ha has, h1] }
end has_one
section monoid
variables [mul_one_class M] {s t : set α} {f g : α → M} {a : α}
@[to_additive] lemma mul_indicator_union_mul_inter_apply (f : α → M) (s t : set α) (a : α) :
mul_indicator (s ∪ t) f a * mul_indicator (s ∩ t) f a =
mul_indicator s f a * mul_indicator t f a :=
by by_cases hs : a ∈ s; by_cases ht : a ∈ t; simp *
@[to_additive] lemma mul_indicator_union_mul_inter (f : α → M) (s t : set α) :
mul_indicator (s ∪ t) f * mul_indicator (s ∩ t) f = mul_indicator s f * mul_indicator t f :=
funext $ mul_indicator_union_mul_inter_apply f s t
@[to_additive] lemma mul_indicator_union_of_not_mem_inter (h : a ∉ s ∩ t) (f : α → M) :
mul_indicator (s ∪ t) f a = mul_indicator s f a * mul_indicator t f a :=
by rw [← mul_indicator_union_mul_inter_apply f s t, mul_indicator_of_not_mem h, mul_one]
@[to_additive] lemma mul_indicator_union_of_disjoint (h : disjoint s t) (f : α → M) :
mul_indicator (s ∪ t) f = λa, mul_indicator s f a * mul_indicator t f a :=
funext $ λa, mul_indicator_union_of_not_mem_inter (λ ha, h ha) _
@[to_additive] lemma mul_indicator_mul (s : set α) (f g : α → M) :
mul_indicator s (λa, f a * g a) = λa, mul_indicator s f a * mul_indicator s g a :=
by { funext, simp only [mul_indicator], split_ifs, { refl }, rw mul_one }
@[simp, to_additive] lemma mul_indicator_compl_mul_self_apply (s : set α) (f : α → M) (a : α) :
mul_indicator sᶜ f a * mul_indicator s f a = f a :=
classical.by_cases (λ ha : a ∈ s, by simp [ha]) (λ ha, by simp [ha])
@[simp, to_additive] lemma mul_indicator_compl_mul_self (s : set α) (f : α → M) :
mul_indicator sᶜ f * mul_indicator s f = f :=
funext $ mul_indicator_compl_mul_self_apply s f
@[simp, to_additive] lemma mul_indicator_self_mul_compl_apply (s : set α) (f : α → M) (a : α) :
mul_indicator s f a * mul_indicator sᶜ f a = f a :=
classical.by_cases (λ ha : a ∈ s, by simp [ha]) (λ ha, by simp [ha])
@[simp, to_additive] lemma mul_indicator_self_mul_compl (s : set α) (f : α → M) :
mul_indicator s f * mul_indicator sᶜ f = f :=
funext $ mul_indicator_self_mul_compl_apply s f
@[to_additive] lemma mul_indicator_mul_eq_left {f g : α → M}
(h : disjoint (mul_support f) (mul_support g)) :
(mul_support f).mul_indicator (f * g) = f :=
begin
refine (mul_indicator_congr $ λ x hx, _).trans mul_indicator_mul_support,
have : g x = 1, from nmem_mul_support.1 (disjoint_left.1 h hx),
rw [pi.mul_apply, this, mul_one]
end
@[to_additive] lemma mul_indicator_mul_eq_right {f g : α → M}
(h : disjoint (mul_support f) (mul_support g)) :
(mul_support g).mul_indicator (f * g) = g :=
begin
refine (mul_indicator_congr $ λ x hx, _).trans mul_indicator_mul_support,
have : f x = 1, from nmem_mul_support.1 (disjoint_right.1 h hx),
rw [pi.mul_apply, this, one_mul]
end
/-- `set.mul_indicator` as a `monoid_hom`. -/
@[to_additive "`set.indicator` as an `add_monoid_hom`."]
def mul_indicator_hom {α} (M) [mul_one_class M] (s : set α) : (α → M) →* (α → M) :=
{ to_fun := mul_indicator s,
map_one' := mul_indicator_one M s,
map_mul' := mul_indicator_mul s }
end monoid
section distrib_mul_action
variables {A : Type*} [add_monoid A] [monoid M] [distrib_mul_action M A]
lemma indicator_smul (s : set α) (r : M) (f : α → A) :
indicator s (λ (x : α), r • f x) = λ (x : α), r • indicator s f x :=
by { simp only [indicator], funext, split_ifs, refl, exact (smul_zero r).symm }
end distrib_mul_action
section group
variables {G : Type*} [group G] {s t : set α} {f g : α → G} {a : α}
@[to_additive] lemma mul_indicator_inv' (s : set α) (f : α → G) :
mul_indicator s (f⁻¹) = (mul_indicator s f)⁻¹ :=
(mul_indicator_hom G s).map_inv f
@[to_additive] lemma mul_indicator_inv (s : set α) (f : α → G) :
mul_indicator s (λa, (f a)⁻¹) = λa, (mul_indicator s f a)⁻¹ :=
mul_indicator_inv' s f
lemma indicator_sub {G} [add_group G] (s : set α) (f g : α → G) :
indicator s (λa, f a - g a) = λa, indicator s f a - indicator s g a :=
(indicator_hom G s).map_sub f g
@[to_additive indicator_compl'] lemma mul_indicator_compl (s : set α) (f : α → G) :
mul_indicator sᶜ f = f * (mul_indicator s f)⁻¹ :=
eq_mul_inv_of_mul_eq $ s.mul_indicator_compl_mul_self f
lemma indicator_compl {G} [add_group G] (s : set α) (f : α → G) :
indicator sᶜ f = f - indicator s f :=
by rw [sub_eq_add_neg, indicator_compl']
@[to_additive indicator_diff'] lemma mul_indicator_diff (h : s ⊆ t) (f : α → G) :
mul_indicator (t \ s) f = mul_indicator t f * (mul_indicator s f)⁻¹ :=
eq_mul_inv_of_mul_eq $ by rw [pi.mul_def, ← mul_indicator_union_of_disjoint disjoint_diff.symm f,
diff_union_self, union_eq_self_of_subset_right h]
lemma indicator_diff {G : Type*} [add_group G] {s t : set α} (h : s ⊆ t) (f : α → G) :
indicator (t \ s) f = indicator t f - indicator s f :=
by rw [indicator_diff' h, sub_eq_add_neg]
end group
section comm_monoid
variables [comm_monoid M]
/-- Consider a product of `g i (f i)` over a `finset`. Suppose `g` is a
function such as `pow`, which maps a second argument of `1` to
`1`. Then if `f` is replaced by the corresponding multiplicative indicator
function, the `finset` may be replaced by a possibly larger `finset`
without changing the value of the sum. -/
@[to_additive] lemma prod_mul_indicator_subset_of_eq_one [has_one N] (f : α → N)
(g : α → N → M) {s t : finset α} (h : s ⊆ t) (hg : ∀ a, g a 1 = 1) :
∏ i in s, g i (f i) = ∏ i in t, g i (mul_indicator ↑s f i) :=
begin
rw ← finset.prod_subset h _,
{ apply finset.prod_congr rfl,
intros i hi,
congr,
symmetry,
exact mul_indicator_of_mem hi _ },
{ refine λ i hi hn, _,
convert hg i,
exact mul_indicator_of_not_mem hn _ }
end
/-- Consider a sum of `g i (f i)` over a `finset`. Suppose `g` is a
function such as multiplication, which maps a second argument of 0 to
0. (A typical use case would be a weighted sum of `f i * h i` or `f i
• h i`, where `f` gives the weights that are multiplied by some other
function `h`.) Then if `f` is replaced by the corresponding indicator
function, the `finset` may be replaced by a possibly larger `finset`
without changing the value of the sum. -/
add_decl_doc set.sum_indicator_subset_of_eq_zero
@[to_additive] lemma prod_mul_indicator_subset (f : α → M) {s t : finset α} (h : s ⊆ t) :
∏ i in s, f i = ∏ i in t, mul_indicator ↑s f i :=
prod_mul_indicator_subset_of_eq_one _ (λ a b, b) h (λ _, rfl)
/-- Summing an indicator function over a possibly larger `finset` is
the same as summing the original function over the original
`finset`. -/
add_decl_doc sum_indicator_subset
@[to_additive] lemma mul_indicator_finset_prod (I : finset ι) (s : set α) (f : ι → α → M) :
mul_indicator s (∏ i in I, f i) = ∏ i in I, mul_indicator s (f i) :=
(mul_indicator_hom M s).map_prod _ _
@[to_additive] lemma mul_indicator_finset_bUnion {ι} (I : finset ι)
(s : ι → set α) {f : α → M} : (∀ (i ∈ I) (j ∈ I), i ≠ j → disjoint (s i) (s j)) →
mul_indicator (⋃ i ∈ I, s i) f = λ a, ∏ i in I, mul_indicator (s i) f a :=
begin
refine finset.induction_on I _ _,
{ intro h, funext, simp },
assume a I haI ih hI,
funext,
rw [finset.prod_insert haI, finset.set_bUnion_insert, mul_indicator_union_of_not_mem_inter, ih _],
{ assume i hi j hj hij,
exact hI i (finset.mem_insert_of_mem hi) j (finset.mem_insert_of_mem hj) hij },
simp only [not_exists, exists_prop, mem_Union, mem_inter_eq, not_and],
assume hx a' ha',
refine disjoint_left.1 (hI a (finset.mem_insert_self _ _) a' (finset.mem_insert_of_mem ha') _) hx,
exact (ne_of_mem_of_not_mem ha' haI).symm
end
end comm_monoid
section mul_zero_class
variables [mul_zero_class M] {s t : set α} {f g : α → M} {a : α}
lemma indicator_mul (s : set α) (f g : α → M) :
indicator s (λa, f a * g a) = λa, indicator s f a * indicator s g a :=
by { funext, simp only [indicator], split_ifs, { refl }, rw mul_zero }
lemma indicator_mul_left (s : set α) (f g : α → M) :
indicator s (λa, f a * g a) a = indicator s f a * g a :=
by { simp only [indicator], split_ifs, { refl }, rw [zero_mul] }
lemma indicator_mul_right (s : set α) (f g : α → M) :
indicator s (λa, f a * g a) a = f a * indicator s g a :=
by { simp only [indicator], split_ifs, { refl }, rw [mul_zero] }
lemma inter_indicator_mul {t1 t2 : set α} (f g : α → M) (x : α) :
(t1 ∩ t2).indicator (λ x, f x * g x) x = t1.indicator f x * t2.indicator g x :=
by { rw [← set.indicator_indicator], simp [indicator] }
end mul_zero_class
section monoid_with_zero
variables [monoid_with_zero M]
lemma indicator_prod_one {s : set α} {t : set β} {x : α} {y : β} :
(s.prod t).indicator (1 : _ → M) (x, y) = s.indicator 1 x * t.indicator 1 y :=
by simp [indicator, ← ite_and]
end monoid_with_zero
section order
variables [has_one M] [preorder M] {s t : set α} {f g : α → M} {a : α} {y : M}
@[to_additive] lemma mul_indicator_apply_le' (hfg : a ∈ s → f a ≤ y) (hg : a ∉ s → 1 ≤ y) :
mul_indicator s f a ≤ y :=
if ha : a ∈ s then by simpa [ha] using hfg ha else by simpa [ha] using hg ha
@[to_additive] lemma mul_indicator_le' (hfg : ∀ a ∈ s, f a ≤ g a) (hg : ∀ a ∉ s, 1 ≤ g a) :
mul_indicator s f ≤ g :=
λ a, mul_indicator_apply_le' (hfg _) (hg _)
@[to_additive] lemma le_mul_indicator_apply {y} (hfg : a ∈ s → y ≤ g a) (hf : a ∉ s → y ≤ 1) :
y ≤ mul_indicator s g a :=
@mul_indicator_apply_le' α (order_dual M) ‹_› _ _ _ _ _ hfg hf
@[to_additive] lemma le_mul_indicator (hfg : ∀ a ∈ s, f a ≤ g a) (hf : ∀ a ∉ s, f a ≤ 1) :
f ≤ mul_indicator s g :=
λ a, le_mul_indicator_apply (hfg _) (hf _)
@[to_additive indicator_apply_nonneg]
lemma one_le_mul_indicator_apply (h : a ∈ s → 1 ≤ f a) : 1 ≤ mul_indicator s f a :=
le_mul_indicator_apply h (λ _, le_rfl)
@[to_additive indicator_nonneg]
lemma one_le_mul_indicator (h : ∀ a ∈ s, 1 ≤ f a) (a : α) : 1 ≤ mul_indicator s f a :=
one_le_mul_indicator_apply (h a)
@[to_additive] lemma mul_indicator_apply_le_one (h : a ∈ s → f a ≤ 1) : mul_indicator s f a ≤ 1 :=
mul_indicator_apply_le' h (λ _, le_rfl)
@[to_additive] lemma mul_indicator_le_one (h : ∀ a ∈ s, f a ≤ 1) (a : α) :
mul_indicator s f a ≤ 1 :=
mul_indicator_apply_le_one (h a)
@[to_additive] lemma mul_indicator_le_mul_indicator (h : f a ≤ g a) :
mul_indicator s f a ≤ mul_indicator s g a :=
mul_indicator_rel_mul_indicator (le_refl _) (λ _, h)
attribute [mono] mul_indicator_le_mul_indicator indicator_le_indicator
@[to_additive] lemma mul_indicator_le_mul_indicator_of_subset (h : s ⊆ t) (hf : ∀ a, 1 ≤ f a)
(a : α) :
mul_indicator s f a ≤ mul_indicator t f a :=
mul_indicator_apply_le' (λ ha, le_mul_indicator_apply (λ _, le_rfl) (λ hat, (hat $ h ha).elim))
(λ ha, one_le_mul_indicator_apply (λ _, hf _))
@[to_additive] lemma mul_indicator_le_self' (hf : ∀ x ∉ s, 1 ≤ f x) : mul_indicator s f ≤ f :=
mul_indicator_le' (λ _ _, le_refl _) hf
@[to_additive] lemma mul_indicator_Union_apply {ι M} [complete_lattice M] [has_one M]
(h1 : (⊥:M) = 1) (s : ι → set α) (f : α → M) (x : α) :
mul_indicator (⋃ i, s i) f x = ⨆ i, mul_indicator (s i) f x :=
begin
by_cases hx : x ∈ ⋃ i, s i,
{ rw [mul_indicator_of_mem hx],
rw [mem_Union] at hx,
refine le_antisymm _ (supr_le $ λ i, mul_indicator_le_self' (λ x hx, h1 ▸ bot_le) x),
rcases hx with ⟨i, hi⟩,
exact le_supr_of_le i (ge_of_eq $ mul_indicator_of_mem hi _) },
{ rw [mul_indicator_of_not_mem hx],
simp only [mem_Union, not_exists] at hx,
simp [hx, ← h1] }
end
end order
section canonically_ordered_monoid
variables [canonically_ordered_monoid M]
@[to_additive] lemma mul_indicator_le_self (s : set α) (f : α → M) :
mul_indicator s f ≤ f :=
mul_indicator_le_self' $ λ _ _, one_le _
@[to_additive] lemma mul_indicator_apply_le {a : α} {s : set α} {f g : α → M}
(hfg : a ∈ s → f a ≤ g a) :
mul_indicator s f a ≤ g a :=
mul_indicator_apply_le' hfg $ λ _, one_le _
@[to_additive] lemma mul_indicator_le {s : set α} {f g : α → M} (hfg : ∀ a ∈ s, f a ≤ g a) :
mul_indicator s f ≤ g :=
mul_indicator_le' hfg $ λ _ _, one_le _
end canonically_ordered_monoid
end set
@[to_additive] lemma monoid_hom.map_mul_indicator {M N : Type*} [monoid M] [monoid N] (f : M →* N)
(s : set α) (g : α → M) (x : α) :
f (s.mul_indicator g x) = s.mul_indicator (f ∘ g) x :=
congr_fun (set.mul_indicator_comp_of_one f.map_one).symm x
|
4bb2dccbdeb935f8a5be92d520b8130a8ed30738 | 90bd8c2a52dbaaba588bdab57b155a7ec1532de0 | /src/locally_path_connected.lean | 5ec8c7d3be4a83eb3de877b80164023d145aba49 | [
"Apache-2.0"
] | permissive | shingtaklam1324/alg-top | fd434f1478925a232af45f18f370ee3a22811c54 | 4c88e28df6f0a329f26eab32bae023789193990e | refs/heads/master | 1,689,447,024,947 | 1,630,073,400,000 | 1,630,073,400,000 | 381,528,689 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 234 | lean | import topology.path_connected
class locally_path_connected_space (X : Type _) [topological_space X] :=
(path_connected : ∀ (x : X) (U : set X), x ∈ U → is_open U → ∃ V : set X, x ∈ V ∧ V ⊆ U ∧ is_path_connected V)
|
24d2b227d6a9cf3f506517b43c090db220425437 | 19cc34575500ee2e3d4586c15544632aa07a8e66 | /src/measure_theory/simple_func_dense.lean | 831aa9ed147e6755a0a246cbbef3e3f8f08a7b8b | [
"Apache-2.0"
] | permissive | LibertasSpZ/mathlib | b9fcd46625eb940611adb5e719a4b554138dade6 | 33f7870a49d7cc06d2f3036e22543e6ec5046e68 | refs/heads/master | 1,672,066,539,347 | 1,602,429,158,000 | 1,602,429,158,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,481 | lean | /-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Yury Kudryashov
-/
import measure_theory.l1_space
/-!
# Density of simple functions
Show that each Borel measurable function can be approximated,
both pointwise and in `L¹` norm, by a sequence of simple functions.
## Main definitions
* `measure_theory.simple_func.nearest_pt (e : ℕ → α) (N : ℕ) : α →ₛ ℕ`: the `simple_func` sending
each `x : α` to the point `e k` which is the nearest to `x` among `e 0`, ..., `e N`.
* `measure_theory.simple_func.approx_on (f : β → α) (hf : measurable f) (s : set α) (y₀ : α)
(h₀ : y₀ ∈ s) [separable_space s] (n : ℕ) : β →ₛ α` : a simple function that takes values in `s`
and approximates `f`. If `f x ∈ s`, then `measure_theory.simple_func.approx_on f hf s y₀ h₀ n x`
tends to `f x` as `n` tends to `∞`. If `α` is a `normed_group`, `f x - y₀`
is `measure_theory.integrable`, and `f x ∈ s` for a.e. `x`, then
`simple_func.approx_on f hf s y₀ h₀ n` tends to `f` in `L₁`. The main use case is `s = univ`,
`y₀ = 0`.
## Notations
* `α →ₛ β` (local notation): the type of simple functions `α → β`.
-/
open set filter topological_space
open_locale classical topological_space
variables {α β ι E : Type*}
namespace measure_theory
open ennreal emetric
local infixr ` →ₛ `:25 := simple_func
namespace simple_func
variables [measurable_space α] [emetric_space α] [opens_measurable_space α]
/-- `nearest_pt_ind e N x` is the index `k` such that `e k` is the nearest point to `x` among the
points `e 0`, ..., `e N`. If more than one point are at the same distance from `x`, then
`nearest_pt_ind e N x` returns the least of their indexes. -/
noncomputable def nearest_pt_ind (e : ℕ → α) : ℕ → α →ₛ ℕ
| 0 := const α 0
| (N + 1) := piecewise (⋂ k ≤ N, {x | edist (e (N + 1)) x < edist (e k) x})
(is_measurable.Inter $ λ k, is_measurable.Inter_Prop $ λ hk,
is_measurable_lt measurable_edist_right measurable_edist_right)
(const α $ N + 1) (nearest_pt_ind N)
/-- `nearest_pt e N x` is the nearest point to `x` among the points `e 0`, ..., `e N`. If more than
one point are at the same distance from `x`, then `nearest_pt e N x` returns the point with the
least possible index. -/
noncomputable def nearest_pt (e : ℕ → α) (N : ℕ) : α →ₛ α :=
(nearest_pt_ind e N).map e
@[simp] lemma nearest_pt_ind_zero (e : ℕ → α) : nearest_pt_ind e 0 = const α 0 := rfl
@[simp] lemma nearest_pt_zero (e : ℕ → α) : nearest_pt e 0 = const α (e 0) := rfl
lemma nearest_pt_ind_succ (e : ℕ → α) (N : ℕ) (x : α) :
nearest_pt_ind e (N + 1) x =
if ∀ k ≤ N, edist (e (N + 1)) x < edist (e k) x
then N + 1 else nearest_pt_ind e N x :=
by { simp only [nearest_pt_ind, coe_piecewise, set.piecewise], congr, simp }
lemma nearest_pt_ind_le (e : ℕ → α) (N : ℕ) (x : α) : nearest_pt_ind e N x ≤ N :=
begin
induction N with N ihN, { simp },
simp only [nearest_pt_ind_succ],
split_ifs,
exacts [le_rfl, ihN.trans N.le_succ]
end
lemma edist_nearest_pt_le (e : ℕ → α) (x : α) {k N : ℕ} (hk : k ≤ N) :
edist (nearest_pt e N x) x ≤ edist (e k) x :=
begin
induction N with N ihN generalizing k,
{ simp [le_zero_iff_eq.1 hk, le_refl] },
{ simp only [nearest_pt, nearest_pt_ind_succ, map_apply],
split_ifs,
{ rcases hk.eq_or_lt with rfl|hk,
exacts [le_rfl, (h k (nat.lt_succ_iff.1 hk)).le] },
{ push_neg at h,
rcases h with ⟨l, hlN, hxl⟩,
rcases hk.eq_or_lt with rfl|hk,
exacts [(ihN hlN).trans hxl, ihN (nat.lt_succ_iff.1 hk)] } }
end
lemma tendsto_nearest_pt {e : ℕ → α} {x : α} (hx : x ∈ closure (range e)) :
tendsto (λ N, nearest_pt e N x) at_top (𝓝 x) :=
begin
refine (at_top_basis.tendsto_iff nhds_basis_eball).2 (λ ε hε, _),
rcases emetric.mem_closure_iff.1 hx ε hε with ⟨_, ⟨N, rfl⟩, hN⟩,
rw [edist_comm] at hN,
exact ⟨N, trivial, λ n hn, (edist_nearest_pt_le e x hn).trans_lt hN⟩
end
variables [measurable_space β] {f : β → α}
/-- Approximate a measurable function by a sequence of simple functions `F n` such that
`F n x ∈ s`. -/
noncomputable def approx_on (f : β → α) (hf : measurable f) (s : set α) (y₀ : α) (h₀ : y₀ ∈ s)
[separable_space s] (n : ℕ) :
β →ₛ α :=
by haveI : nonempty s := ⟨⟨y₀, h₀⟩⟩;
exact comp (nearest_pt (λ k, nat.cases_on k y₀ (coe ∘ dense_seq s) : ℕ → α) n) f hf
@[simp] lemma approx_on_zero {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s)
[separable_space s] (x : β) :
approx_on f hf s y₀ h₀ 0 x = y₀ :=
rfl
lemma approx_on_mem {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s)
[separable_space s] (n : ℕ) (x : β) :
approx_on f hf s y₀ h₀ n x ∈ s :=
begin
haveI : nonempty s := ⟨⟨y₀, h₀⟩⟩,
suffices : ∀ n, (nat.cases_on n y₀ (coe ∘ dense_seq s) : α) ∈ s, { apply this },
rintro (_|n),
exacts [h₀, subtype.mem _]
end
@[simp] lemma approx_on_comp {γ : Type*} [measurable_space γ] {f : β → α} (hf : measurable f)
{g : γ → β} (hg : measurable g) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s) [separable_space s] (n : ℕ) :
approx_on (f ∘ g) (hf.comp hg) s y₀ h₀ n = (approx_on f hf s y₀ h₀ n).comp g hg :=
rfl
lemma tendsto_approx_on {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s)
[separable_space s] {x : β} (hx : f x ∈ closure s) :
tendsto (λ n, approx_on f hf s y₀ h₀ n x) at_top (𝓝 $ f x) :=
begin
haveI : nonempty s := ⟨⟨y₀, h₀⟩⟩,
rw [← @subtype.range_coe _ s, ← image_univ, ← dense_seq_dense s] at hx,
simp only [approx_on, coe_comp],
refine tendsto_nearest_pt (closure_minimal _ is_closed_closure hx),
simp only [nat.range_cases_on, closure_union, @range_comp _ _ _ _ coe],
exact subset.trans (image_closure_subset_closure_image continuous_subtype_coe)
(subset_union_right _ _)
end
lemma edist_approx_on_le {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s)
[separable_space s] (x : β) (n : ℕ) :
edist (approx_on f hf s y₀ h₀ n x) (f x) ≤ edist y₀ (f x) :=
begin
dsimp only [approx_on, coe_comp, (∘)],
exact edist_nearest_pt_le _ _ (zero_le _)
end
lemma edist_approx_on_y0_le {f : β → α} (hf : measurable f) {s : set α} {y₀ : α} (h₀ : y₀ ∈ s)
[separable_space s] (x : β) (n : ℕ) :
edist y₀ (approx_on f hf s y₀ h₀ n x) ≤ edist y₀ (f x) + edist y₀ (f x) :=
calc edist y₀ (approx_on f hf s y₀ h₀ n x) ≤
edist y₀ (f x) + edist (approx_on f hf s y₀ h₀ n x) (f x) : edist_triangle_right _ _ _
... ≤ edist y₀ (f x) + edist y₀ (f x) : add_le_add_left (edist_approx_on_le hf h₀ x n) _
variables [measurable_space E] [normed_group E]
lemma norm_approx_on_zero_le [opens_measurable_space E] {f : β → E} (hf : measurable f)
{s : set E} (h₀ : (0 : E) ∈ s) [separable_space s] (x : β) (n : ℕ) :
∥approx_on f hf s 0 h₀ n x∥ ≤ ∥f x∥ + ∥f x∥ :=
begin
have := edist_approx_on_y0_le hf h₀ x n,
simp [edist_comm (0 : E), edist_eq_coe_nnnorm] at this,
exact_mod_cast this,
end
lemma tendsto_approx_on_l1_edist [opens_measurable_space E]
{f : β → E} (hf : measurable f) {s : set E} {y₀ : E} (h₀ : y₀ ∈ s) [separable_space s]
{μ : measure β} (hμ : ∀ᵐ x ∂μ, f x ∈ closure s) (hi : has_finite_integral (λ x, f x - y₀) μ) :
tendsto (λ n, ∫⁻ x, edist (approx_on f hf s y₀ h₀ n x) (f x) ∂μ) at_top (𝓝 0) :=
begin
simp only [has_finite_integral, ← nndist_eq_nnnorm, ← edist_nndist, ← edist_comm y₀] at hi,
have : ∀ n, measurable (λ x, edist (approx_on f hf s y₀ h₀ n x) (f x)) :=
λ n, (approx_on f hf s y₀ h₀ n).measurable_bind (λ y x, edist y (f x))
(λ y, measurable_edist_right.comp hf),
convert tendsto_lintegral_of_dominated_convergence _ this
(λ n, eventually_of_forall $ λ x, edist_approx_on_le hf h₀ x n) hi (hμ.mono $ λ x hx, _),
show tendsto (λ n, edist _ (f x)) at_top (𝓝 $ edist (f x) (f x)),
from (tendsto_approx_on hf h₀ hx).edist tendsto_const_nhds,
simp
end
lemma integrable_approx_on [borel_space E]
{f : β → E} {μ : measure β} (hf : integrable f μ) {s : set E} {y₀ : E} (h₀ : y₀ ∈ s)
[separable_space s] (hi₀ : integrable (λ x, y₀) μ) (n : ℕ) :
integrable (approx_on f hf.1 s y₀ h₀ n) μ :=
begin
refine ⟨(approx_on f hf.1 s y₀ h₀ n).measurable, _⟩,
suffices : integrable (λ x, approx_on f hf.1 s y₀ h₀ n x - y₀) μ,
{ convert this.add' hi₀, ext1 x, simp },
refine ⟨(approx_on f hf.1 s y₀ h₀ n - const β y₀).measurable, _⟩,
have hi := hf.sub' hi₀,
simp only [has_finite_integral, ← nndist_eq_nnnorm, ← edist_nndist, edist_comm _ y₀,
pi.sub_apply] at hi ⊢,
have : measurable (λ x, edist y₀ (f x)) := measurable_edist_right.comp hf.1,
calc ∫⁻ x, edist y₀ (approx_on f hf.1 s y₀ h₀ n x) ∂μ ≤ ∫⁻ x, edist y₀ (f x) + edist y₀ (f x) ∂μ :
measure_theory.lintegral_mono (λ x, edist_approx_on_y0_le hf.1 h₀ x n)
... = ∫⁻ x, edist y₀ (f x) ∂μ + ∫⁻ x, edist y₀ (f x) ∂μ :
measure_theory.lintegral_add this this
... < ⊤ :
add_lt_top.2 ⟨hi, hi⟩
end
lemma tendsto_approx_on_univ_l1_edist [opens_measurable_space E] [second_countable_topology E]
{f : β → E} {μ : measure β} (hf : integrable f μ) :
tendsto (λ n, ∫⁻ x, edist (approx_on f hf.1 univ 0 trivial n x) (f x) ∂μ) at_top (𝓝 0) :=
tendsto_approx_on_l1_edist hf.1 trivial (by simp) (by simpa using hf.2)
lemma integrable_approx_on_univ [borel_space E] [second_countable_topology E]
{f : β → E} {μ : measure β} (hf : integrable f μ) (n : ℕ) :
integrable (approx_on f hf.1 univ 0 trivial n) μ :=
integrable_approx_on hf _ (integrable_zero _ _ _) n
lemma tendsto_approx_on_univ_l1 [borel_space E] [second_countable_topology E]
{f : β → E} {μ : measure β} (hf : integrable f μ) :
tendsto (λ n, l1.of_fun (approx_on f hf.1 univ 0 trivial n) (integrable_approx_on_univ hf n))
at_top (𝓝 $ l1.of_fun f hf) :=
tendsto_iff_edist_tendsto_0.2 $ tendsto_approx_on_univ_l1_edist hf
end simple_func
end measure_theory
|
64263a2d0f5194cfaf032cf24f7a6bd75a6624e6 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/ring_theory/polynomial/default_auto.lean | 1be4f387c5338b896952474e5b02bf2705f8d204 | [] | 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 | 159 | lean | import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.ring_theory.polynomial.basic
import Mathlib.PostPort
namespace Mathlib
end Mathlib |
a26f4310301222fbb32f0b2ce0c2d175df6245e2 | c31182a012eec69da0a1f6c05f42b0f0717d212d | /src/rescale/LC.lean | c7875db838b6ec97e6eb099f10b447759c7460c9 | [] | no_license | Ja1941/lean-liquid | fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc | 8e80ed0cbdf5145d6814e833a674eaf05a1495c1 | refs/heads/master | 1,689,437,983,362 | 1,628,362,719,000 | 1,628,362,719,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,150 | lean | import rescale.pseudo_normed_group
import pseudo_normed_group.LC
open_locale classical nnreal
open opposite ProFiltPseuNormGrpWithTinv
open SemiNormedGroup opposite Profinite pseudo_normed_group category_theory breen_deligne
open profinitely_filtered_pseudo_normed_group
universe variable u
variables (r : ℝ≥0) (V : SemiNormedGroup) (r' : ℝ≥0) [fact (0 < r')]
variables (c c₁ c₂ c₃ c₄ : ℝ≥0) (l m n : ℕ)
@[simp] theorem LCFP_rescale (N : ℝ≥0)
(M) [profinitely_filtered_pseudo_normed_group_with_Tinv r' M] :
(LCFP V r' c n).obj (op (of r' (rescale N M))) =
(LCFP V r' (c * N⁻¹) n).obj (op (of r' M)) := rfl
namespace breen_deligne
namespace basic_universal_map
variables (ϕ : basic_universal_map m n)
theorem eval_FP_rescale [ϕ.suitable c₁ c₂]
(N : ℝ≥0) (M) [profinitely_filtered_pseudo_normed_group_with_Tinv r' M] :
(eval_FP r' c₁ c₂ ϕ).app (of r' (rescale N M)) =
((eval_FP r' (c₁ * N⁻¹) (c₂ * N⁻¹) ϕ).app (of r' M)) :=
begin
ext x i, dsimp only [eval_FP, continuous_map.coe_mk, eval_png₀, subtype.coe_mk],
simp only [eval_png_apply]
end
theorem eval_LCFP_rescale [ϕ.suitable c₂ c₁]
(N : ℝ≥0) (M) [profinitely_filtered_pseudo_normed_group_with_Tinv r' M] :
(eval_LCFP V r' ϕ c₁ c₂).app (op (of r' (rescale N M))) =
by clean @_root_.id _ ((eval_LCFP V r' ϕ (c₁ * N⁻¹) (c₂ * N⁻¹)).app (op (of r' M))) :=
begin
dsimp only [eval_LCFP, whisker_right_app, nat_trans.op_app, unop_op],
rw eval_FP_rescale
end
end basic_universal_map
namespace universal_map
variables (ϕ : universal_map m n)
theorem eval_LCFP_rescale [ϕ.suitable c₂ c₁]
(N : ℝ≥0)
(M) [profinitely_filtered_pseudo_normed_group_with_Tinv r' M] :
(eval_LCFP V r' c₁ c₂ ϕ).app (op (of r' (rescale N M))) =
(by clean @_root_.id _ ((eval_LCFP V r' (c₁ * N⁻¹) (c₂ * N⁻¹) ϕ).app (op (of r' M)))) :=
begin
simp only [eval_LCFP, ← nat_trans.app_hom_apply,
add_monoid_hom.map_sum, add_monoid_hom.map_int_module_smul],
simp only [nat_trans.app_hom_apply, basic_universal_map.eval_LCFP_rescale],
end
end universal_map
end breen_deligne
|
15922715d56647239720a60a2e622481e85f02e4 | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch3/ex0317.lean | a2627cc1ff1fcc39488f76684821322b5d22252c | [] | no_license | Ailrun/Theorem_Proving_in_Lean | ae6a23f3c54d62d401314d6a771e8ff8b4132db2 | 2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68 | refs/heads/master | 1,609,838,270,467 | 1,586,846,743,000 | 1,586,846,743,000 | 240,967,761 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 96 | lean | variables p q r : Prop
example (hnp : ¬p) (hq : q) (hqp : q → p) : r := absurd (hqp hq) hnp
|
1dca28eb1a1f62720c375b319eedcb800fc8990a | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/analysis/normed_space/linear_isometry.lean | e5be4c01074aad7bebd438c86c8187c0b20ce0ba | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,652 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.normed_space.basic
import linear_algebra.finite_dimensional
/-!
# Linear isometries
In this file we define `linear_isometry R E F` (notation: `E →ₗᵢ[R] F`) to be a linear isometric
embedding of `E` into `F` and `linear_isometry_equiv` (notation: `E ≃ₗᵢ[R] F`) to be a linear
isometric equivalence between `E` and `F`.
We also prove some trivial lemmas and provide convenience constructors.
Since a lot of elementary properties don't require `∥x∥ = 0 → x = 0` we start setting up the
theory for `semi_normed_space` and we specialize to `normed_space` when needed.
-/
open function set
variables {R E F G G' E₁ : Type*} [semiring R]
[semi_normed_group E] [semi_normed_group F] [semi_normed_group G] [semi_normed_group G']
[module R E] [module R F] [module R G] [module R G']
[normed_group E₁] [module R E₁]
/-- An `R`-linear isometric embedding of one normed `R`-module into another. -/
structure linear_isometry (R E F : Type*) [semiring R] [semi_normed_group E]
[semi_normed_group F] [module R E] [module R F] extends E →ₗ[R] F :=
(norm_map' : ∀ x, ∥to_linear_map x∥ = ∥x∥)
notation E ` →ₗᵢ[`:25 R:25 `] `:0 F:0 := linear_isometry R E F
namespace linear_isometry
/-- We use `f₁` when we need the domain to be a `normed_space`. -/
variables (f : E →ₗᵢ[R] F) (f₁ : E₁ →ₗᵢ[R] F)
instance : has_coe_to_fun (E →ₗᵢ[R] F) := ⟨_, λ f, f.to_fun⟩
@[simp] lemma coe_to_linear_map : ⇑f.to_linear_map = f := rfl
lemma to_linear_map_injective : injective (to_linear_map : (E →ₗᵢ[R] F) → (E →ₗ[R] F))
| ⟨f, _⟩ ⟨g, _⟩ rfl := rfl
lemma coe_fn_injective : injective (λ (f : E →ₗᵢ[R] F) (x : E), f x) :=
linear_map.coe_injective.comp to_linear_map_injective
@[ext] lemma ext {f g : E →ₗᵢ[R] F} (h : ∀ x, f x = g x) : f = g :=
coe_fn_injective $ funext h
@[simp] lemma map_zero : f 0 = 0 := f.to_linear_map.map_zero
@[simp] lemma map_add (x y : E) : f (x + y) = f x + f y := f.to_linear_map.map_add x y
@[simp] lemma map_sub (x y : E) : f (x - y) = f x - f y := f.to_linear_map.map_sub x y
@[simp] lemma map_smul (c : R) (x : E) : f (c • x) = c • f x := f.to_linear_map.map_smul c x
@[simp] lemma norm_map (x : E) : ∥f x∥ = ∥x∥ := f.norm_map' x
@[simp] lemma nnnorm_map (x : E) : nnnorm (f x) = nnnorm x := nnreal.eq $ f.norm_map x
protected lemma isometry : isometry f :=
f.to_linear_map.to_add_monoid_hom.isometry_of_norm f.norm_map
@[simp] lemma dist_map (x y : E) : dist (f x) (f y) = dist x y := f.isometry.dist_eq x y
@[simp] lemma edist_map (x y : E) : edist (f x) (f y) = edist x y := f.isometry.edist_eq x y
protected lemma injective : injective f₁ := f₁.isometry.injective
@[simp] lemma map_eq_iff {x y : E₁} : f₁ x = f₁ y ↔ x = y := f₁.injective.eq_iff
lemma map_ne {x y : E₁} (h : x ≠ y) : f₁ x ≠ f₁ y := f₁.injective.ne h
protected lemma lipschitz : lipschitz_with 1 f := f.isometry.lipschitz
protected lemma antilipschitz : antilipschitz_with 1 f := f.isometry.antilipschitz
@[continuity] protected lemma continuous : continuous f := f.isometry.continuous
lemma ediam_image (s : set E) : emetric.diam (f '' s) = emetric.diam s :=
f.isometry.ediam_image s
lemma ediam_range : emetric.diam (range f) = emetric.diam (univ : set E) :=
f.isometry.ediam_range
lemma diam_image (s : set E) : metric.diam (f '' s) = metric.diam s :=
f.isometry.diam_image s
lemma diam_range : metric.diam (range f) = metric.diam (univ : set E) :=
f.isometry.diam_range
/-- Interpret a linear isometry as a continuous linear map. -/
def to_continuous_linear_map : E →L[R] F := ⟨f.to_linear_map, f.continuous⟩
@[simp] lemma coe_to_continuous_linear_map : ⇑f.to_continuous_linear_map = f := rfl
@[simp] lemma comp_continuous_iff {α : Type*} [topological_space α] {g : α → E} :
continuous (f ∘ g) ↔ continuous g :=
f.isometry.comp_continuous_iff
/-- The identity linear isometry. -/
def id : E →ₗᵢ[R] E := ⟨linear_map.id, λ x, rfl⟩
@[simp] lemma coe_id : ⇑(id : E →ₗᵢ[R] E) = id := rfl
@[simp] lemma id_apply (x : E) : (id : E →ₗᵢ[R] E) x = x := rfl
@[simp] lemma id_to_linear_map : (id.to_linear_map : E →ₗ[R] E) = linear_map.id := rfl
instance : inhabited (E →ₗᵢ[R] E) := ⟨id⟩
/-- Composition of linear isometries. -/
def comp (g : F →ₗᵢ[R] G) (f : E →ₗᵢ[R] F) : E →ₗᵢ[R] G :=
⟨g.to_linear_map.comp f.to_linear_map, λ x, (g.norm_map _).trans (f.norm_map _)⟩
@[simp] lemma coe_comp (g : F →ₗᵢ[R] G) (f : E →ₗᵢ[R] F) :
⇑(g.comp f) = g ∘ f :=
rfl
@[simp] lemma id_comp : (id : F →ₗᵢ[R] F).comp f = f := ext $ λ x, rfl
@[simp] lemma comp_id : f.comp id = f := ext $ λ x, rfl
lemma comp_assoc (f : G →ₗᵢ[R] G') (g : F →ₗᵢ[R] G) (h : E →ₗᵢ[R] F) :
(f.comp g).comp h = f.comp (g.comp h) :=
rfl
instance : monoid (E →ₗᵢ[R] E) :=
{ one := id,
mul := comp,
mul_assoc := comp_assoc,
one_mul := id_comp,
mul_one := comp_id }
@[simp] lemma coe_one : ⇑(1 : E →ₗᵢ[R] E) = id := rfl
@[simp] lemma coe_mul (f g : E →ₗᵢ[R] E) : ⇑(f * g) = f ∘ g := rfl
end linear_isometry
namespace submodule
variables {R' : Type*} [ring R'] [module R' E] (p : submodule R' E)
/-- `submodule.subtype` as a `linear_isometry`. -/
def subtypeₗᵢ : p →ₗᵢ[R'] E := ⟨p.subtype, λ x, rfl⟩
@[simp] lemma coe_subtypeₗᵢ : ⇑p.subtypeₗᵢ = p.subtype := rfl
@[simp] lemma subtypeₗᵢ_to_linear_map : p.subtypeₗᵢ.to_linear_map = p.subtype := rfl
/-- `submodule.subtype` as a `continuous_linear_map`. -/
def subtypeL : p →L[R'] E := p.subtypeₗᵢ.to_continuous_linear_map
@[simp] lemma coe_subtypeL : (p.subtypeL : p →ₗ[R'] E) = p.subtype := rfl
@[simp] lemma coe_subtypeL' : ⇑p.subtypeL = p.subtype := rfl
@[simp] lemma range_subtypeL : p.subtypeL.range = p :=
range_subtype _
@[simp] lemma ker_subtypeL : p.subtypeL.ker = ⊥ :=
ker_subtype _
end submodule
/-- A linear isometric equivalence between two normed vector spaces. -/
structure linear_isometry_equiv (R E F : Type*) [semiring R] [semi_normed_group E]
[semi_normed_group F] [module R E] [module R F] extends E ≃ₗ[R] F :=
(norm_map' : ∀ x, ∥to_linear_equiv x∥ = ∥x∥)
notation E ` ≃ₗᵢ[`:25 R:25 `] `:0 F:0 := linear_isometry_equiv R E F
namespace linear_isometry_equiv
variables (e : E ≃ₗᵢ[R] F)
instance : has_coe_to_fun (E ≃ₗᵢ[R] F) := ⟨_, λ f, f.to_fun⟩
@[simp] lemma coe_mk (e : E ≃ₗ[R] F) (he : ∀ x, ∥e x∥ = ∥x∥) :
⇑(mk e he) = e :=
rfl
@[simp] lemma coe_to_linear_equiv (e : E ≃ₗᵢ[R] F) : ⇑e.to_linear_equiv = e := rfl
lemma to_linear_equiv_injective : injective (to_linear_equiv : (E ≃ₗᵢ[R] F) → (E ≃ₗ[R] F))
| ⟨e, _⟩ ⟨_, _⟩ rfl := rfl
@[ext] lemma ext {e e' : E ≃ₗᵢ[R] F} (h : ∀ x, e x = e' x) : e = e' :=
to_linear_equiv_injective $ linear_equiv.ext h
/-- Construct a `linear_isometry_equiv` from a `linear_equiv` and two inequalities:
`∀ x, ∥e x∥ ≤ ∥x∥` and `∀ y, ∥e.symm y∥ ≤ ∥y∥`. -/
def of_bounds (e : E ≃ₗ[R] F) (h₁ : ∀ x, ∥e x∥ ≤ ∥x∥) (h₂ : ∀ y, ∥e.symm y∥ ≤ ∥y∥) : E ≃ₗᵢ[R] F :=
⟨e, λ x, le_antisymm (h₁ x) $ by simpa only [e.symm_apply_apply] using h₂ (e x)⟩
@[simp] lemma norm_map (x : E) : ∥e x∥ = ∥x∥ := e.norm_map' x
/-- Reinterpret a `linear_isometry_equiv` as a `linear_isometry`. -/
def to_linear_isometry : E →ₗᵢ[R] F := ⟨e.1, e.2⟩
@[simp] lemma coe_to_linear_isometry : ⇑e.to_linear_isometry = e := rfl
protected lemma isometry : isometry e := e.to_linear_isometry.isometry
/-- Reinterpret a `linear_isometry_equiv` as an `isometric`. -/
def to_isometric : E ≃ᵢ F := ⟨e.to_linear_equiv.to_equiv, e.isometry⟩
@[simp] lemma coe_to_isometric : ⇑e.to_isometric = e := rfl
lemma range_eq_univ (e : E ≃ₗᵢ[R] F) : set.range e = set.univ :=
by { rw ← coe_to_isometric, exact isometric.range_eq_univ _, }
/-- Reinterpret a `linear_isometry_equiv` as an `homeomorph`. -/
def to_homeomorph : E ≃ₜ F := e.to_isometric.to_homeomorph
@[simp] lemma coe_to_homeomorph : ⇑e.to_homeomorph = e := rfl
protected lemma continuous : continuous e := e.isometry.continuous
protected lemma continuous_at {x} : continuous_at e x := e.continuous.continuous_at
protected lemma continuous_on {s} : continuous_on e s := e.continuous.continuous_on
protected lemma continuous_within_at {s x} : continuous_within_at e s x :=
e.continuous.continuous_within_at
/-- Interpret a `linear_isometry_equiv` as a continuous linear equiv. -/
def to_continuous_linear_equiv : E ≃L[R] F :=
{ .. e.to_linear_isometry.to_continuous_linear_map,
.. e.to_homeomorph }
@[simp] lemma coe_to_continuous_linear_equiv : ⇑e.to_continuous_linear_equiv = e := rfl
variables (R E)
/-- Identity map as a `linear_isometry_equiv`. -/
def refl : E ≃ₗᵢ[R] E := ⟨linear_equiv.refl R E, λ x, rfl⟩
variables {R E}
instance : inhabited (E ≃ₗᵢ[R] E) := ⟨refl R E⟩
@[simp] lemma coe_refl : ⇑(refl R E) = id := rfl
/-- The inverse `linear_isometry_equiv`. -/
def symm : F ≃ₗᵢ[R] E :=
⟨e.to_linear_equiv.symm,
λ x, (e.norm_map _).symm.trans $ congr_arg norm $ e.to_linear_equiv.apply_symm_apply x⟩
@[simp] lemma apply_symm_apply (x : F) : e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (x : E) : e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply x
@[simp] lemma map_eq_zero_iff {x : E} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff
@[simp] lemma symm_symm : e.symm.symm = e := ext $ λ x, rfl
@[simp] lemma to_linear_equiv_symm : e.to_linear_equiv.symm = e.symm.to_linear_equiv := rfl
@[simp] lemma to_isometric_symm : e.to_isometric.symm = e.symm.to_isometric := rfl
@[simp] lemma to_homeomorph_symm : e.to_homeomorph.symm = e.symm.to_homeomorph := rfl
/-- Composition of `linear_isometry_equiv`s as a `linear_isometry_equiv`. -/
def trans (e' : F ≃ₗᵢ[R] G) : E ≃ₗᵢ[R] G :=
⟨e.to_linear_equiv.trans e'.to_linear_equiv, λ x, (e'.norm_map _).trans (e.norm_map _)⟩
@[simp] lemma coe_trans (e₁ : E ≃ₗᵢ[R] F) (e₂ : F ≃ₗᵢ[R] G) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl
@[simp] lemma trans_refl : e.trans (refl R F) = e := ext $ λ x, rfl
@[simp] lemma refl_trans : (refl R E).trans e = e := ext $ λ x, rfl
@[simp] lemma trans_symm : e.trans e.symm = refl R E := ext e.symm_apply_apply
@[simp] lemma symm_trans : e.symm.trans e = refl R F := ext e.apply_symm_apply
@[simp] lemma coe_symm_trans (e₁ : E ≃ₗᵢ[R] F) (e₂ : F ≃ₗᵢ[R] G) :
⇑(e₁.trans e₂).symm = e₁.symm ∘ e₂.symm :=
rfl
lemma trans_assoc (eEF : E ≃ₗᵢ[R] F) (eFG : F ≃ₗᵢ[R] G) (eGG' : G ≃ₗᵢ[R] G') :
eEF.trans (eFG.trans eGG') = (eEF.trans eFG).trans eGG' :=
rfl
instance : group (E ≃ₗᵢ[R] E) :=
{ mul := λ e₁ e₂, e₂.trans e₁,
one := refl _ _,
inv := symm,
one_mul := trans_refl,
mul_one := refl_trans,
mul_assoc := λ _ _ _, trans_assoc _ _ _,
mul_left_inv := trans_symm }
@[simp] lemma coe_one : ⇑(1 : E ≃ₗᵢ[R] E) = id := rfl
@[simp] lemma coe_mul (e e' : E ≃ₗᵢ[R] E) : ⇑(e * e') = e ∘ e' := rfl
@[simp] lemma coe_inv (e : E ≃ₗᵢ[R] E) : ⇑(e⁻¹) = e.symm := rfl
/-- Reinterpret a `linear_isometry_equiv` as a `continuous_linear_equiv`. -/
instance : has_coe_t (E ≃ₗᵢ[R] F) (E ≃L[R] F) :=
⟨λ e, ⟨e.to_linear_equiv, e.continuous, e.to_isometric.symm.continuous⟩⟩
instance : has_coe_t (E ≃ₗᵢ[R] F) (E →L[R] F) := ⟨λ e, ↑(e : E ≃L[R] F)⟩
@[simp] lemma coe_coe : ⇑(e : E ≃L[R] F) = e := rfl
@[simp] lemma coe_coe' : ((e : E ≃L[R] F) : E →L[R] F) = e := rfl
@[simp] lemma coe_coe'' : ⇑(e : E →L[R] F) = e := rfl
@[simp] lemma map_zero : e 0 = 0 := e.1.map_zero
@[simp] lemma map_add (x y : E) : e (x + y) = e x + e y := e.1.map_add x y
@[simp] lemma map_sub (x y : E) : e (x - y) = e x - e y := e.1.map_sub x y
@[simp] lemma map_smul (c : R) (x : E) : e (c • x) = c • e x := e.1.map_smul c x
@[simp] lemma nnnorm_map (x : E) : nnnorm (e x) = nnnorm x := e.to_linear_isometry.nnnorm_map x
@[simp] lemma dist_map (x y : E) : dist (e x) (e y) = dist x y :=
e.to_linear_isometry.dist_map x y
@[simp] lemma edist_map (x y : E) : edist (e x) (e y) = edist x y :=
e.to_linear_isometry.edist_map x y
protected lemma bijective : bijective e := e.1.bijective
protected lemma injective : injective e := e.1.injective
protected lemma surjective : surjective e := e.1.surjective
@[simp] lemma map_eq_iff {x y : E} : e x = e y ↔ x = y := e.injective.eq_iff
lemma map_ne {x y : E} (h : x ≠ y) : e x ≠ e y := e.injective.ne h
protected lemma lipschitz : lipschitz_with 1 e := e.isometry.lipschitz
protected lemma antilipschitz : antilipschitz_with 1 e := e.isometry.antilipschitz
@[simp] lemma ediam_image (s : set E) : emetric.diam (e '' s) = emetric.diam s :=
e.isometry.ediam_image s
@[simp] lemma diam_image (s : set E) : metric.diam (e '' s) = metric.diam s :=
e.isometry.diam_image s
variables {α : Type*} [topological_space α]
@[simp] lemma comp_continuous_on_iff {f : α → E} {s : set α} :
continuous_on (e ∘ f) s ↔ continuous_on f s :=
e.isometry.comp_continuous_on_iff
@[simp] lemma comp_continuous_iff {f : α → E} :
continuous (e ∘ f) ↔ continuous f :=
e.isometry.comp_continuous_iff
end linear_isometry_equiv
namespace linear_isometry
open finite_dimensional linear_map
variables {R₁ : Type*} [field R₁] [module R₁ E₁] [module R₁ F]
[finite_dimensional R₁ E₁] [finite_dimensional R₁ F]
/-- A linear isometry between finite dimensional spaces of equal dimension can be upgraded
to a linear isometry equivalence. -/
noncomputable def to_linear_isometry_equiv
(li : E₁ →ₗᵢ[R₁] F) (h : finrank R₁ E₁ = finrank R₁ F) : E₁ ≃ₗᵢ[R₁] F :=
{ to_linear_equiv := li.to_linear_map.linear_equiv_of_ker_eq_bot
(ker_eq_bot_of_injective li.injective) h,
norm_map' := li.norm_map' }
@[simp] lemma coe_to_linear_isometry_equiv
(li : E₁ →ₗᵢ[R₁] F) (h : finrank R₁ E₁ = finrank R₁ F) :
(li.to_linear_isometry_equiv h : E₁ → F) = li := rfl
@[simp] lemma to_linear_isometry_equiv_apply
(li : E₁ →ₗᵢ[R₁] F) (h : finrank R₁ E₁ = finrank R₁ F) (x : E₁) :
(li.to_linear_isometry_equiv h) x = li x := rfl
end linear_isometry
|
5f812765aa0d20cedb162261798b9910ed760a42 | 649957717d58c43b5d8d200da34bf374293fe739 | /src/algebra/pi_instances.lean | 2714029eb7129ca4d6e63ddd98c2d99cb9f090ee | [
"Apache-2.0"
] | permissive | Vtec234/mathlib | b50c7b21edea438df7497e5ed6a45f61527f0370 | fb1848bbbfce46152f58e219dc0712f3289d2b20 | refs/heads/master | 1,592,463,095,113 | 1,562,737,749,000 | 1,562,737,749,000 | 196,202,858 | 0 | 0 | Apache-2.0 | 1,562,762,338,000 | 1,562,762,337,000 | null | UTF-8 | Lean | false | false | 18,758 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
Pi instances for algebraic structures.
-/
import order.basic
import algebra.module algebra.group
import data.finset
import ring_theory.subring
import tactic.pi_instances
namespace pi
universes u v w
variable {I : Type u} -- The indexing type
variable {f : I → Type v} -- The family of types already equiped with instances
variables (x y : Π i, f i) (i : I)
instance has_zero [∀ i, has_zero $ f i] : has_zero (Π i : I, f i) := ⟨λ i, 0⟩
@[simp] lemma zero_apply [∀ i, has_zero $ f i] : (0 : Π i, f i) i = 0 := rfl
instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ i, 1⟩
@[simp] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl
attribute [to_additive pi.has_zero] pi.has_one
attribute [to_additive pi.zero_apply] pi.one_apply
instance has_add [∀ i, has_add $ f i] : has_add (Π i : I, f i) := ⟨λ x y, λ i, x i + y i⟩
@[simp] lemma add_apply [∀ i, has_add $ f i] : (x + y) i = x i + y i := rfl
instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ x y, λ i, x i * y i⟩
@[simp] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl
attribute [to_additive pi.has_add] pi.has_mul
attribute [to_additive pi.add_apply] pi.mul_apply
instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ x, λ i, (x i)⁻¹⟩
@[simp] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl
instance has_neg [∀ i, has_neg $ f i] : has_neg (Π i : I, f i) := ⟨λ x, λ i, -(x i)⟩
@[simp] lemma neg_apply [∀ i, has_neg $ f i] : (-x) i = -x i := rfl
attribute [to_additive pi.has_neg] pi.has_inv
attribute [to_additive pi.neg_apply] pi.inv_apply
instance has_scalar {α : Type*} [∀ i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩
@[simp] lemma smul_apply {α : Type*} [∀ i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl
instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by pi_instance
instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by pi_instance
instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by pi_instance
instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by pi_instance
instance group [∀ i, group $ f i] : group (Π i : I, f i) := by pi_instance
instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by pi_instance
instance add_semigroup [∀ i, add_semigroup $ f i] : add_semigroup (Π i : I, f i) := by pi_instance
instance add_comm_semigroup [∀ i, add_comm_semigroup $ f i] : add_comm_semigroup (Π i : I, f i) := by pi_instance
instance add_monoid [∀ i, add_monoid $ f i] : add_monoid (Π i : I, f i) := by pi_instance
instance add_comm_monoid [∀ i, add_comm_monoid $ f i] : add_comm_monoid (Π i : I, f i) := by pi_instance
instance add_group [∀ i, add_group $ f i] : add_group (Π i : I, f i) := by pi_instance
instance add_comm_group [∀ i, add_comm_group $ f i] : add_comm_group (Π i : I, f i) := by pi_instance
instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by pi_instance
instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by pi_instance
instance mul_action (α) {m : monoid α} [∀ i, mul_action α $ f i] : mul_action α (Π i : I, f i) :=
{ smul := λ c f i, c • f i,
mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _,
one_smul := λ f, funext $ λ i, one_smul α _ }
instance distrib_mul_action (α) {m : monoid α} [∀ i, add_monoid $ f i] [∀ i, distrib_mul_action α $ f i] : distrib_mul_action α (Π i : I, f i) :=
{ smul_zero := λ c, funext $ λ i, smul_zero _,
smul_add := λ c f g, funext $ λ i, smul_add _ _ _,
..pi.mul_action _ }
variables (I f)
instance semimodule (α) {r : semiring α} [∀ i, add_comm_monoid $ f i] [∀ i, semimodule α $ f i] : semimodule α (Π i : I, f i) :=
{ add_smul := λ c f g, funext $ λ i, add_smul _ _ _,
zero_smul := λ f, funext $ λ i, zero_smul α _,
..pi.distrib_mul_action _ }
variables {I f}
instance module (α) {r : ring α} [∀ i, add_comm_group $ f i] [∀ i, module α $ f i] : module α (Π i : I, f i) := {..pi.semimodule I f α}
instance vector_space (α) {r : discrete_field α} [∀ i, add_comm_group $ f i] [∀ i, vector_space α $ f i] : vector_space α (Π i : I, f i) := {..pi.module α}
instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance add_left_cancel_semigroup [∀ i, add_left_cancel_semigroup $ f i] : add_left_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance add_right_cancel_semigroup [∀ i, add_right_cancel_semigroup $ f i] : add_right_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) :=
by pi_instance
instance ordered_comm_group [∀ i, ordered_comm_group $ f i] : ordered_comm_group (Π i : I, f i) :=
{ add_lt_add_left := λ a b hab c, ⟨λ i, add_le_add_left (hab.1 i) (c i),
λ h, hab.2 $ λ i, le_of_add_le_add_left (h i)⟩,
add_le_add_left := λ x y hxy c i, add_le_add_left (hxy i) _,
..pi.add_comm_group,
..pi.partial_order }
attribute [to_additive pi.add_semigroup] pi.semigroup
attribute [to_additive pi.add_comm_semigroup] pi.comm_semigroup
attribute [to_additive pi.add_monoid] pi.monoid
attribute [to_additive pi.add_comm_monoid] pi.comm_monoid
attribute [to_additive pi.add_group] pi.group
attribute [to_additive pi.add_comm_group] pi.comm_group
attribute [to_additive pi.add_left_cancel_semigroup] pi.left_cancel_semigroup
attribute [to_additive pi.add_right_cancel_semigroup] pi.right_cancel_semigroup
@[to_additive pi.list_sum_apply]
lemma list_prod_apply {α : Type*} {β : α → Type*} [∀a, monoid (β a)] (a : α) :
∀ (l : list (Πa, β a)), l.prod a = (l.map (λf:Πa, β a, f a)).prod
| [] := rfl
| (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l]
@[to_additive pi.multiset_sum_apply]
lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α)
(s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod :=
quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end
@[to_additive pi.finset_sum_apply]
lemma finset_prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α)
(s : finset γ) (g : γ → Πa, β a) : s.prod g a = s.prod (λc, g c a) :=
show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod,
by rw [multiset_prod_apply, multiset.map_map]
instance is_ring_hom_pi
{α : Type u} {β : α → Type v} [R : Π a : α, ring (β a)]
{γ : Type w} [ring γ]
(f : Π a : α, γ → β a) [Rh : Π a : α, is_ring_hom (f a)] :
is_ring_hom (λ x b, f b x) :=
begin
split,
-- It's a pity that these can't be done using `simp` lemmas.
{ ext, rw [is_ring_hom.map_one (f x)], refl, },
{ intros x y, ext1 z, rw [is_ring_hom.map_mul (f z)], refl, },
{ intros x y, ext1 z, rw [is_ring_hom.map_add (f z)], refl, }
end
end pi
namespace prod
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {p q : α × β}
instance [has_add α] [has_add β] : has_add (α × β) :=
⟨λp q, (p.1 + q.1, p.2 + q.2)⟩
@[to_additive prod.has_add]
instance [has_mul α] [has_mul β] : has_mul (α × β) :=
⟨λp q, (p.1 * q.1, p.2 * q.2)⟩
@[simp, to_additive prod.fst_add]
lemma fst_mul [has_mul α] [has_mul β] : (p * q).1 = p.1 * q.1 := rfl
@[simp, to_additive prod.snd_add]
lemma snd_mul [has_mul α] [has_mul β] : (p * q).2 = p.2 * q.2 := rfl
@[simp, to_additive prod.mk_add_mk]
lemma mk_mul_mk [has_mul α] [has_mul β] (a₁ a₂ : α) (b₁ b₂ : β) :
(a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl
instance [has_zero α] [has_zero β] : has_zero (α × β) := ⟨(0, 0)⟩
@[to_additive prod.has_zero]
instance [has_one α] [has_one β] : has_one (α × β) := ⟨(1, 1)⟩
@[simp, to_additive prod.fst_zero]
lemma fst_one [has_one α] [has_one β] : (1 : α × β).1 = 1 := rfl
@[simp, to_additive prod.snd_zero]
lemma snd_one [has_one α] [has_one β] : (1 : α × β).2 = 1 := rfl
@[to_additive prod.zero_eq_mk]
lemma one_eq_mk [has_one α] [has_one β] : (1 : α × β) = (1, 1) := rfl
instance [has_neg α] [has_neg β] : has_neg (α × β) := ⟨λp, (- p.1, - p.2)⟩
@[to_additive prod.has_neg]
instance [has_inv α] [has_inv β] : has_inv (α × β) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩
@[simp, to_additive prod.fst_neg]
lemma fst_inv [has_inv α] [has_inv β] : (p⁻¹).1 = (p.1)⁻¹ := rfl
@[simp, to_additive prod.snd_neg]
lemma snd_inv [has_inv α] [has_inv β] : (p⁻¹).2 = (p.2)⁻¹ := rfl
@[to_additive prod.neg_mk]
lemma inv_mk [has_inv α] [has_inv β] (a : α) (b : β) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl
instance [add_semigroup α] [add_semigroup β] : add_semigroup (α × β) :=
{ add_assoc := assume a b c, mk.inj_iff.mpr ⟨add_assoc _ _ _, add_assoc _ _ _⟩,
.. prod.has_add }
@[to_additive prod.add_semigroup]
instance [semigroup α] [semigroup β] : semigroup (α × β) :=
{ mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩,
.. prod.has_mul }
instance [add_monoid α] [add_monoid β] : add_monoid (α × β) :=
{ zero_add := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨zero_add _, zero_add _⟩,
add_zero := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨add_zero _, add_zero _⟩,
.. prod.add_semigroup, .. prod.has_zero }
@[to_additive prod.add_monoid]
instance [monoid α] [monoid β] : monoid (α × β) :=
{ one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩,
mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩,
.. prod.semigroup, .. prod.has_one }
instance [add_group α] [add_group β] : add_group (α × β) :=
{ add_left_neg := assume a, mk.inj_iff.mpr ⟨add_left_neg _, add_left_neg _⟩,
.. prod.add_monoid, .. prod.has_neg }
@[to_additive prod.add_group]
instance [group α] [group β] : group (α × β) :=
{ mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩,
.. prod.monoid, .. prod.has_inv }
instance [add_comm_semigroup α] [add_comm_semigroup β] : add_comm_semigroup (α × β) :=
{ add_comm := assume a b, mk.inj_iff.mpr ⟨add_comm _ _, add_comm _ _⟩,
.. prod.add_semigroup }
@[to_additive prod.add_comm_semigroup]
instance [comm_semigroup α] [comm_semigroup β] : comm_semigroup (α × β) :=
{ mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩,
.. prod.semigroup }
instance [add_comm_monoid α] [add_comm_monoid β] : add_comm_monoid (α × β) :=
{ .. prod.add_comm_semigroup, .. prod.add_monoid }
@[to_additive prod.add_comm_monoid]
instance [comm_monoid α] [comm_monoid β] : comm_monoid (α × β) :=
{ .. prod.comm_semigroup, .. prod.monoid }
instance [add_comm_group α] [add_comm_group β] : add_comm_group (α × β) :=
{ .. prod.add_comm_semigroup, .. prod.add_group }
@[to_additive prod.add_comm_group]
instance [comm_group α] [comm_group β] : comm_group (α × β) :=
{ .. prod.comm_semigroup, .. prod.group }
@[to_additive fst.is_add_monoid_hom]
lemma fst.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.fst : α × β → α) :=
{ map_mul := λ _ _, rfl, map_one := rfl }
@[to_additive snd.is_add_monoid_hom]
lemma snd.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.snd : α × β → β) :=
{ map_mul := λ _ _, rfl, map_one := rfl }
@[to_additive fst.is_add_group_hom]
lemma fst.is_group_hom [group α] [group β] : is_group_hom (prod.fst : α × β → α) :=
{ map_mul := λ _ _, rfl }
@[to_additive snd.is_add_group_hom]
lemma snd.is_group_hom [group α] [group β] : is_group_hom (prod.snd : α × β → β) :=
{ map_mul := λ _ _, rfl }
attribute [instance] fst.is_monoid_hom fst.is_add_monoid_hom snd.is_monoid_hom snd.is_add_monoid_hom
fst.is_group_hom fst.is_add_group_hom snd.is_group_hom snd.is_add_group_hom
@[to_additive prod.fst_sum]
lemma fst_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} :
(t.prod f).1 = t.prod (λc, (f c).1) :=
(finset.prod_hom prod.fst).symm
@[to_additive prod.snd_sum]
lemma snd_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} :
(t.prod f).2 = t.prod (λc, (f c).2) :=
(finset.prod_hom prod.snd).symm
instance [semiring α] [semiring β] : semiring (α × β) :=
{ zero_mul := λ a, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩,
mul_zero := λ a, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩,
left_distrib := λ a b c, mk.inj_iff.mpr ⟨left_distrib _ _ _, left_distrib _ _ _⟩,
right_distrib := λ a b c, mk.inj_iff.mpr ⟨right_distrib _ _ _, right_distrib _ _ _⟩,
..prod.add_comm_monoid, ..prod.monoid }
instance [ring α] [ring β] : ring (α × β) :=
{ ..prod.add_comm_group, ..prod.semiring }
instance [comm_ring α] [comm_ring β] : comm_ring (α × β) :=
{ ..prod.ring, ..prod.comm_monoid }
instance [nonzero_comm_ring α] [comm_ring β] : nonzero_comm_ring (α × β) :=
{ zero_ne_one := mt (congr_arg prod.fst) zero_ne_one,
..prod.comm_ring }
instance fst.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.fst : α × β → α) :=
by refine_struct {..}; simp
instance snd.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.snd : α × β → β) :=
by refine_struct {..}; simp
instance fst.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.fst : α × β → α) :=
by refine_struct {..}; simp
instance snd.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.snd : α × β → β) :=
by refine_struct {..}; simp
/-- Left injection function for the inner product
From a vector space (and also group and module) perspective the product is the same as the sum of
two vector spaces. `inl` and `inr` provide the corresponding injection functions.
-/
def inl [has_zero β] (a : α) : α × β := (a, 0)
/-- Right injection function for the inner product -/
def inr [has_zero α] (b : β) : α × β := (0, b)
lemma injective_inl [has_zero β] : function.injective (inl : α → α × β) :=
assume x y h, (prod.mk.inj_iff.mp h).1
lemma injective_inr [has_zero α] : function.injective (inr : β → α × β) :=
assume x y h, (prod.mk.inj_iff.mp h).2
@[simp] lemma inl_eq_inl [has_zero β] {a₁ a₂ : α} : (inl a₁ : α × β) = inl a₂ ↔ a₁ = a₂ :=
iff.intro (assume h, injective_inl h) (assume h, h ▸ rfl)
@[simp] lemma inr_eq_inr [has_zero α] {b₁ b₂ : β} : (inr b₁ : α × β) = inr b₂ ↔ b₁ = b₂ :=
iff.intro (assume h, injective_inr h) (assume h, h ▸ rfl)
@[simp] lemma inl_eq_inr [has_zero α] [has_zero β] {a : α} {b : β} :
inl a = inr b ↔ a = 0 ∧ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma inr_eq_inl [has_zero α] [has_zero β] {a : α} {b : β} :
inr b = inl a ↔ a = 0 ∧ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma fst_inl [has_zero β] (a : α) : (inl a : α × β).1 = a := rfl
@[simp] lemma snd_inl [has_zero β] (a : α) : (inl a : α × β).2 = 0 := rfl
@[simp] lemma fst_inr [has_zero α] (b : β) : (inr b : α × β).1 = 0 := rfl
@[simp] lemma snd_inr [has_zero α] (b : β) : (inr b : α × β).2 = b := rfl
instance [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) := ⟨λa p, (a • p.1, a • p.2)⟩
@[simp] theorem smul_fst [has_scalar α β] [has_scalar α γ]
(a : α) (x : β × γ) : (a • x).1 = a • x.1 := rfl
@[simp] theorem smul_snd [has_scalar α β] [has_scalar α γ]
(a : α) (x : β × γ) : (a • x).2 = a • x.2 := rfl
@[simp] theorem smul_mk [has_scalar α β] [has_scalar α γ]
(a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) := rfl
instance {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ]
[semimodule α β] [semimodule α γ] : semimodule α (β × γ) :=
{ smul_add := assume a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩,
add_smul := assume a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩,
mul_smul := assume a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩,
one_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩,
zero_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩,
smul_zero := assume a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩,
.. prod.has_scalar }
instance {r : ring α} [add_comm_group β] [add_comm_group γ]
[module α β] [module α γ] : module α (β × γ) := {}
instance {r : discrete_field α} [add_comm_group β] [add_comm_group γ]
[vector_space α β] [vector_space α γ] : vector_space α (β × γ) := {}
section substructures
variables (s : set α) (t : set β)
@[to_additive prod.is_add_submonoid]
instance [monoid α] [monoid β] [is_submonoid s] [is_submonoid t] :
is_submonoid (s.prod t) :=
{ one_mem := by rw set.mem_prod; split; apply is_submonoid.one_mem,
mul_mem := by intros; rw set.mem_prod at *; split; apply is_submonoid.mul_mem; tauto }
@[to_additive prod.is_add_subgroup]
instance is_subgroup.prod [group α] [group β] [is_subgroup s] [is_subgroup t] :
is_subgroup (s.prod t) :=
{ inv_mem := by intros; rw set.mem_prod at *; split; apply is_subgroup.inv_mem; tauto,
.. prod.is_submonoid s t }
instance is_subring.prod [ring α] [ring β] [is_subring s] [is_subring t] :
is_subring (s.prod t) :=
{ .. prod.is_submonoid s t, .. prod.is_add_subgroup s t }
end substructures
end prod
namespace finset
@[to_additive finset.prod_mk_sum]
lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ)
(f : γ → α) (g : γ → β) : (s.prod f, s.prod g) = s.prod (λ x, (f x, g x)) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt})
end finset
|
f8776a4c6a7f0d5595e6407dfef1d8c00f349b6e | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Util.lean | aa614b11118177baf9f3ecedf7f8acc1170af330 | [
"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 | 673 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.Util.CollectFVars
import Init.Lean.Util.CollectLevelParams
import Init.Lean.Util.CollectMVars
import Init.Lean.Util.FindMVar
import Init.Lean.Util.MonadCache
import Init.Lean.Util.PPExt
import Init.Lean.Util.PPGoal
import Init.Lean.Util.Path
import Init.Lean.Util.Profile
import Init.Lean.Util.RecDepth
import Init.Lean.Util.Sorry
import Init.Lean.Util.Trace
import Init.Lean.Util.WHNF
import Init.Lean.Util.FindExpr
import Init.Lean.Util.ReplaceExpr
import Init.Lean.Util.FoldConsts
|
168e37b36c04bb20c4ec6c3bc6e2dbb27133d08a | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /linear_algebra/basic.lean | edb18fc276ccfca99ec982a526a47336110ec5a7 | [
"Apache-2.0"
] | permissive | kckennylau/mathlib | 21fb810b701b10d6606d9002a4004f7672262e83 | 47b3477e20ffb5a06588dd3abb01fe0fe3205646 | refs/heads/master | 1,634,976,409,281 | 1,542,042,832,000 | 1,542,319,733,000 | 109,560,458 | 0 | 0 | Apache-2.0 | 1,542,369,208,000 | 1,509,867,494,000 | Lean | UTF-8 | Lean | false | false | 42,012 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard
Basics of linear algebra. This sets up the "categorical/lattice structure" of
modules, submodules, and linear maps.
-/
import algebra.pi_instances data.finsupp order.order_iso
open function lattice
reserve infix `≃ₗ` : 50
universes u v w x y
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type y} {ι : Type x}
@[elab_as_eliminator]
lemma classical.some_spec3 {α : Type*} {p : α → Prop} {h : ∃a, p a}
(q : α → Prop) (hpq : ∀a, p a → q a) : q (classical.some h) :=
hpq _ $ classical.some_spec _
namespace finset
lemma smul_sum [ring γ] [add_comm_group β] [module γ β]
{s : finset α} {a : γ} {f : α → β} :
a • (s.sum f) = s.sum (λc, a • f c) :=
(finset.sum_hom ((•) a) (@smul_zero γ β _ _ _ a) (assume _ _, smul_add _ _ _)).symm
end finset
namespace finsupp
lemma smul_sum [has_zero β] [ring γ] [add_comm_group δ] [module γ δ]
{v : α →₀ β} {c : γ} {h : α → β → δ} :
c • (v.sum h) = v.sum (λa b, c • h a b) :=
finset.smul_sum
end finsupp
namespace linear_map
section
variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
variables (f g : β →ₗ γ)
include α
theorem comp_id (f : β →ₗ γ) : f.comp id = f :=
linear_map.ext $ λ x, rfl
theorem id_comp (f : β →ₗ γ) : id.comp f = f :=
linear_map.ext $ λ x, rfl
def cod_restrict (p : submodule α β) (f : γ →ₗ β) (h : ∀c, f c ∈ p) : γ →ₗ p :=
by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp
@[simp] theorem cod_restrict_apply (p : submodule α β) (f : γ →ₗ β) {h} (x : γ) :
(cod_restrict p f h x : β) = f x := rfl
def inverse (g : γ → β) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : γ →ₗ β :=
by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact
⟨g, λ x y, by rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂],
λ a b, by rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂]⟩
instance : has_zero (β →ₗ γ) := ⟨⟨λ _, 0, by simp, by simp⟩⟩
@[simp] lemma zero_apply (x : β) : (0 : β →ₗ γ) x = 0 := rfl
instance : has_neg (β →ₗ γ) := ⟨λ f, ⟨λ b, - f b, by simp, by simp⟩⟩
@[simp] lemma neg_apply (x : β) : (- f) x = - f x := rfl
instance : has_add (β →ₗ γ) := ⟨λ f g, ⟨λ b, f b + g b, by simp, by simp [smul_add]⟩⟩
@[simp] lemma add_apply (x : β) : (f + g) x = f x + g x := rfl
instance : add_comm_group (β →ₗ γ) :=
by refine {zero := 0, add := (+), neg := has_neg.neg, ..};
intros; ext; simp
lemma sum_apply [decidable_eq δ] (t : finset δ) (f : δ → β →ₗ γ) (b : β) :
t.sum f b = t.sum (λd, f d b) :=
(@finset.sum_hom _ _ _ t f _ _ (λ g : β →ₗ γ, g b) (by simp) (by simp)).symm
@[simp] lemma sub_apply (x : β) : (f - g) x = f x - g x := rfl
def smul_right (f : γ →ₗ α) (x : β) : γ →ₗ β :=
⟨λb, f b • x, by simp [add_smul], by simp [smul_smul]⟩.
@[simp] theorem smul_right_apply (f : γ →ₗ α) (x : β) (c : γ) :
(smul_right f x : γ → β) c = f c • x := rfl
instance : has_one (β →ₗ β) := ⟨linear_map.id⟩
instance : has_mul (β →ₗ β) := ⟨linear_map.comp⟩
@[simp] lemma one_app (x : β) : (1 : β →ₗ β) x = x := rfl
@[simp] lemma mul_app (A B : β →ₗ β) (x : β) : (A * B) x = A (B x) := rfl
section
variables (α β)
include β
-- declaring this an instance breaks `real.lean` with reaching max. instance resolution depth
def endomorphism_ring : ring (β →ₗ β) :=
by refine {mul := (*), one := 1, ..linear_map.add_comm_group, ..};
{ intros, apply linear_map.ext, simp }
/-- The group of invertible linear maps from `β` to itself -/
def general_linear_group :=
by haveI := endomorphism_ring α β; exact units (β →ₗ β)
end
section
variables (β γ)
def fst : β × γ →ₗ β := ⟨prod.fst, λ x y, rfl, λ x y, rfl⟩
def snd : β × γ →ₗ γ := ⟨prod.snd, λ x y, rfl, λ x y, rfl⟩
end
@[simp] theorem fst_apply (x : β × γ) : fst β γ x = x.1 := rfl
@[simp] theorem snd_apply (x : β × γ) : snd β γ x = x.2 := rfl
def pair (f : β →ₗ γ) (g : β →ₗ δ) : β →ₗ γ × δ :=
⟨λ x, (f x, g x), λ x y, by simp, λ x y, by simp⟩
@[simp] theorem pair_apply (f : β →ₗ γ) (g : β →ₗ δ) (x : β) :
pair f g x = (f x, g x) := rfl
@[simp] theorem fst_pair (f : β →ₗ γ) (g : β →ₗ δ) :
(fst γ δ).comp (pair f g) = f := by ext; refl
@[simp] theorem snd_pair (f : β →ₗ γ) (g : β →ₗ δ) :
(snd γ δ).comp (pair f g) = g := by ext; refl
@[simp] theorem pair_fst_snd : pair (fst β γ) (snd β γ) = linear_map.id :=
by ext; refl
section
variables (β γ)
def inl : β →ₗ β × γ := by refine ⟨prod.inl, _, _⟩; intros; simp [prod.inl]
def inr : γ →ₗ β × γ := by refine ⟨prod.inr, _, _⟩; intros; simp [prod.inr]
end
@[simp] theorem inl_apply (x : β) : inl β γ x = (x, 0) := rfl
@[simp] theorem inr_apply (x : γ) : inr β γ x = (0, x) := rfl
def copair (f : β →ₗ δ) (g : γ →ₗ δ) : β × γ →ₗ δ :=
⟨λ x, f x.1 + g x.2, λ x y, by simp, λ x y, by simp [smul_add]⟩
@[simp] theorem copair_apply (f : β →ₗ δ) (g : γ →ₗ δ) (x : β) (y : γ) :
copair f g (x, y) = f x + g y := rfl
@[simp] theorem copair_inl (f : β →ₗ δ) (g : γ →ₗ δ) :
(copair f g).comp (inl β γ) = f := by ext; simp
@[simp] theorem copair_inr (f : β →ₗ δ) (g : γ →ₗ δ) :
(copair f g).comp (inr β γ) = g := by ext; simp
@[simp] theorem copair_inl_inr : copair (inl β γ) (inr β γ) = linear_map.id :=
by ext ⟨x, y⟩; simp
theorem fst_eq_copair : fst β γ = copair linear_map.id 0 := by ext ⟨x, y⟩; simp
theorem snd_eq_copair : snd β γ = copair 0 linear_map.id := by ext ⟨x, y⟩; simp
theorem inl_eq_pair : inl β γ = pair linear_map.id 0 := rfl
theorem inr_eq_pair : inr β γ = pair 0 linear_map.id := rfl
end
section comm_ring
variables [comm_ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
variables (f g : β →ₗ γ)
include α
instance : has_scalar α (β →ₗ γ) := ⟨λ a f,
⟨λ b, a • f b, by simp [smul_add], by simp [smul_smul, mul_comm]⟩⟩
@[simp] lemma smul_apply (a : α) (x : β) : (a • f) x = a • f x := rfl
instance : module α (β →ₗ γ) :=
module.of_core $ by refine { smul := (•), ..};
intros; ext; simp [smul_add, add_smul, smul_smul]
def congr_right (f : γ →ₗ δ) : (β →ₗ γ) →ₗ (β →ₗ δ) :=
⟨linear_map.comp f,
λ _ _, linear_map.ext $ λ _, f.2 _ _,
λ _ _, linear_map.ext $ λ _, f.3 _ _⟩
end comm_ring
end linear_map
namespace submodule
variables {R:ring α} [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
variables (p p' : submodule α β) (q q' : submodule α γ)
variables {r : α} {x y : β}
include R
open set lattice
instance : partial_order (submodule α β) :=
partial_order.lift (coe : submodule α β → set β) $ λ a b, ext'
lemma le_def {p p' : submodule α β} : p ≤ p' ↔ (p : set β) ⊆ p' := iff.rfl
lemma le_def' {p p' : submodule α β} : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl
def of_le {p p' : submodule α β} (h : p ≤ p') : p →ₗ p' :=
linear_map.cod_restrict _ p.subtype $ λ ⟨x, hx⟩, h hx
@[simp] theorem of_le_apply {p p' : submodule α β} (h : p ≤ p')
(x : p) : (of_le h x : β) = x := rfl
instance : has_bot (submodule α β) :=
⟨by split; try {exact {0}}; simp {contextual := tt}⟩
@[simp] lemma bot_coe : ((⊥ : submodule α β) : set β) = {0} := rfl
@[simp] lemma mem_bot : x ∈ (⊥ : submodule α β) ↔ x = 0 := mem_singleton_iff
instance : order_bot (submodule α β) :=
{ bot := ⊥,
bot_le := λ p x, by simp {contextual := tt},
..submodule.partial_order }
instance : has_top (submodule α β) :=
⟨by split; try {exact set.univ}; simp⟩
@[simp] lemma top_coe : ((⊤ : submodule α β) : set β) = univ := rfl
@[simp] lemma mem_top : x ∈ (⊤ : submodule α β) := trivial
instance : order_top (submodule α β) :=
{ top := ⊤,
le_top := λ p x _, trivial,
..submodule.partial_order }
instance : has_Inf (submodule α β) :=
⟨λ S, {
carrier := ⋂ s ∈ S, ↑s,
zero := by simp,
add := by simp [add_mem] {contextual := tt},
smul := by simp [smul_mem] {contextual := tt} }⟩
private lemma Inf_le' {S : set (submodule α β)} {p} : p ∈ S → Inf S ≤ p :=
bInter_subset_of_mem
private lemma le_Inf' {S : set (submodule α β)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S :=
subset_bInter
instance : has_inf (submodule α β) :=
⟨λ p p', {
carrier := p ∩ p',
zero := by simp,
add := by simp [add_mem] {contextual := tt},
smul := by simp [smul_mem] {contextual := tt} }⟩
instance : complete_lattice (submodule α β) :=
{ sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x},
le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha,
le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb,
sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩,
inf := (⊓),
le_inf := λ a b c, subset_inter,
inf_le_left := λ a b, inter_subset_left _ _,
inf_le_right := λ a b, inter_subset_right _ _,
Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t},
le_Sup := λ s p hs, le_Inf' $ λ p' hp', hp' _ hs,
Sup_le := λ s p hs, Inf_le' hs,
Inf := Inf,
le_Inf := λ s a, le_Inf',
Inf_le := λ s a, Inf_le',
..submodule.lattice.order_top,
..submodule.lattice.order_bot }
lemma eq_top_iff' {p : submodule α β} : p = ⊤ ↔ ∀ x, x ∈ p :=
eq_top_iff.trans ⟨λ h x, @h x trivial, λ h x _, h x⟩
@[simp] theorem inf_coe : (p ⊓ p' : set β) = p ∩ p' := rfl
@[simp] theorem mem_inf {p p' : submodule α β} :
x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
@[simp] theorem Inf_coe (P : set (submodule α β)) : (↑(Inf P) : set β) = ⋂ p ∈ P, ↑p := rfl
@[simp] theorem infi_coe {ι} (p : ι → submodule α β) :
(↑⨅ i, p i : set β) = ⋂ i, ↑(p i) :=
by rw [infi, Inf_coe]; ext a; simp; exact
⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩
@[simp] theorem mem_infi {ι} (p : ι → submodule α β) :
x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i :=
by rw [← mem_coe, infi_coe, mem_Inter]; refl
theorem disjoint_def {p p' : submodule α β} :
disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:β) :=
show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set β)) ↔ _, by simp
/-- The pushforward -/
def map (f : β →ₗ γ) (p : submodule α β) : submodule α γ :=
{ carrier := f '' p,
zero := ⟨0, p.zero_mem, f.map_zero⟩,
add := by rintro _ _ ⟨b₁, hb₁, rfl⟩ ⟨b₂, hb₂, rfl⟩;
exact ⟨_, p.add_mem hb₁ hb₂, f.map_add _ _⟩,
smul := by rintro a _ ⟨b, hb, rfl⟩;
exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩ }
lemma map_coe (f : β →ₗ γ) (p : submodule α β) :
(map f p : set γ) = f '' p := rfl
@[simp] lemma mem_map {f : β →ₗ γ} {p : submodule α β} {x : γ} :
x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl
theorem mem_map_of_mem {f : β →ₗ γ} {p : submodule α β} {r} (h : r ∈ p) : f r ∈ map f p :=
set.mem_image_of_mem _ h
lemma map_id : map linear_map.id p = p :=
submodule.ext $ λ a, by simp
lemma map_comp (f : β →ₗ γ) (g : γ →ₗ δ) (p : submodule α β) :
map (g.comp f) p = map g (map f p) :=
submodule.ext' $ by simp [map_coe]; rw ← image_comp
lemma map_mono {f : β →ₗ γ} {p p' : submodule α β} : p ≤ p' → map f p ≤ map f p' :=
image_subset _
/-- The pullback -/
def comap (f : β →ₗ γ) (p : submodule α γ) : submodule α β :=
{ carrier := f ⁻¹' p,
zero := by simp,
add := λ x y h₁ h₂, by simp [p.add_mem h₁ h₂],
smul := λ a x h, by simp [p.smul_mem _ h] }
@[simp] lemma comap_coe (f : β →ₗ γ) (p : submodule α γ) :
(comap f p : set β) = f ⁻¹' p := rfl
@[simp] lemma mem_comap {f : β →ₗ γ} {p : submodule α γ} :
x ∈ comap f p ↔ f x ∈ p := iff.rfl
lemma comap_id : comap linear_map.id p = p :=
submodule.ext' rfl
lemma comap_comp (f : β →ₗ γ) (g : γ →ₗ δ) (p : submodule α δ) :
comap (g.comp f) p = comap f (comap g p) := rfl
lemma comap_mono {f : β →ₗ γ} {q q' : submodule α γ} : q ≤ q' → comap f q ≤ comap f q' :=
preimage_mono
@[simp] lemma comap_top (f : β →ₗ γ) : comap f ⊤ = ⊤ := rfl
lemma map_le_iff_le_comap {f : β →ₗ γ} {p : submodule α β} {q : submodule α γ} :
map f p ≤ q ↔ p ≤ comap f q := image_subset_iff
lemma map_comap_le (f : β →ₗ γ) (q : submodule α γ) : map f (comap f q) ≤ q :=
map_le_iff_le_comap.2 $ le_refl _
lemma le_comap_map (f : β →ₗ γ) (p : submodule α β) : p ≤ comap f (map f p) :=
map_le_iff_le_comap.1 $ le_refl _
@[simp] lemma map_bot (f : β →ₗ γ) : map f ⊥ = ⊥ :=
eq_bot_iff.2 $ map_le_iff_le_comap.2 bot_le
--TODO(Mario): is there a way to prove this from order properties?
lemma map_inf_eq_map_inf_comap {f : β →ₗ γ}
{p : submodule α β} {p' : submodule α γ} :
map f p ⊓ p' = map f (p ⊓ comap f p') :=
le_antisymm
(by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩)
(le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right))
lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' :=
ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩
def span (s : set β) : submodule α β := Inf {p | s ⊆ p}
variables {s t : set β}
lemma mem_span : x ∈ span s ↔ ∀ p : submodule α β, s ⊆ p → x ∈ p :=
mem_bInter_iff
lemma subset_span : s ⊆ span s :=
λ x h, mem_span.2 $ λ p hp, hp h
lemma span_le {p} : span s ≤ p ↔ s ⊆ p :=
⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩
lemma span_mono (h : s ⊆ t) : span s ≤ span t :=
span_le.2 $ subset.trans h subset_span
lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span s) : span s = p :=
le_antisymm (span_le.2 h₁) h₂
@[simp] lemma span_eq : span (p : set β) = p :=
span_eq_of_le _ (subset.refl _) subset_span
@[elab_as_eliminator] lemma span_induction {p : β → Prop} (h : x ∈ span s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0)
(H1 : ∀ x y, p x → p y → p (x + y))
(H2 : ∀ a x, p x → p (a • x)) : p x :=
(@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h
variables (β)
protected def gi : galois_insertion (@span α β _ _ _) coe :=
{ choice := λ s _, span s,
gc := λ s t, span_le,
le_l_u := λ s, subset_span,
choice_eq := λ s h, rfl }
variables {β}
@[simp] lemma span_empty : span (∅ : set β) = ⊥ :=
(submodule.gi β).gc.l_bot
lemma span_union (s t : set β) : span (s ∪ t) = span s ⊔ span t :=
(submodule.gi β).gc.l_sup
lemma span_Union {ι} (s : ι → set β) : span (⋃ i, s i) = ⨆ i, span (s i) :=
(submodule.gi β).gc.l_supr
@[simp] theorem Union_coe_of_directed {ι} (hι : nonempty ι)
(S : ι → submodule α β)
(H : ∀ i j, ∃ k, S i ≤ S k ∧ S j ≤ S k) :
((supr S : submodule α β) : set β) = ⋃ i, S i :=
begin
refine subset.antisymm _ (Union_subset $ le_supr S),
rw [show supr S = ⨆ i, span (S i), by simp, ← span_Union],
unfreezeI,
refine λ x hx, span_induction hx (λ _, id) _ _ _,
{ cases hι with i, exact mem_Union.2 ⟨i, by simp⟩ },
{ simp, intros x y i hi j hj,
rcases H i j with ⟨k, ik, jk⟩,
exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ },
{ simp [-mem_coe]; exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ },
end
@[simp] theorem mem_supr_of_directed {ι} (hι : nonempty ι)
(S : ι → submodule α β)
(H : ∀ i j, ∃ k, S i ≤ S k ∧ S j ≤ S k) {x} :
x ∈ supr S ↔ ∃ i, x ∈ S i :=
by rw [← mem_coe, Union_coe_of_directed hι S H, mem_Union]; refl
theorem mem_Sup_of_directed {s : set (submodule α β)}
{z} (hzs : z ∈ Sup s) (x ∈ s)
(hdir : ∀ i ∈ s, ∀ j ∈ s, ∃ k ∈ s, i ≤ k ∧ j ≤ k) :
∃ y ∈ s, z ∈ y :=
begin
haveI := classical.dec, rw Sup_eq_supr at hzs,
have, { refine (mem_supr_of_directed ⟨⊥⟩ _ (λ i j, _)).1 hzs,
by_cases his : i ∈ s; by_cases hjs : j ∈ s,
{ rcases hdir i his j hjs with ⟨k, hks, hik, hjk⟩,
exact ⟨k, le_supr_of_le hks (supr_le $ λ _, hik),
le_supr_of_le hks (supr_le $ λ _, hjk)⟩ },
{ exact ⟨i, le_refl _, supr_le $ hjs.elim⟩ },
{ exact ⟨j, supr_le $ his.elim, le_refl _⟩ },
{ exact ⟨⊥, supr_le $ his.elim, supr_le $ hjs.elim⟩ } },
cases this with N hzn, by_cases hns : N ∈ s,
{ have : (⨆ (H : N ∈ s), N) ≤ N := supr_le (λ _, le_refl _),
exact ⟨N, hns, this hzn⟩ },
{ have : (⨆ (H : N ∈ s), N) ≤ ⊥ := supr_le hns.elim,
cases mem_bot.1 (this hzn), exact ⟨x, H, x.zero_mem⟩ }
end
variables {p p'}
lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x :=
⟨λ h, begin
rw [← span_eq p, ← span_eq p', ← span_union] at h,
apply span_induction h,
{ rintro y (h | h),
{ exact ⟨y, h, 0, by simp, by simp⟩ },
{ exact ⟨0, by simp, y, h, by simp⟩ } },
{ exact ⟨0, by simp, 0, by simp⟩ },
{ rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩,
exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp⟩ },
{ rintro a _ ⟨y, hy, z, hz, rfl⟩,
exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ }
end,
by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _
((le_sup_left : p ≤ p ⊔ p') hy)
((le_sup_right : p' ≤ p ⊔ p') hz)⟩
variables (p p')
lemma mem_span_singleton {y : β} : x ∈ span ({y} : set β) ↔ ∃ a, a • y = x :=
⟨λ h, begin
apply span_induction h,
{ rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ },
{ exact ⟨0, by simp⟩ },
{ rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩,
exact ⟨a + b, by simp [add_smul]⟩ },
{ rintro a _ ⟨b, rfl⟩,
exact ⟨a * b, by simp [smul_smul]⟩ }
end,
by rintro ⟨a, y, rfl⟩; exact
smul_mem _ _ (subset_span $ by simp)⟩
lemma span_singleton_eq_range (y : β) : (span ({y} : set β) : set β) = range (• y) :=
set.ext $ λ x, mem_span_singleton
lemma mem_span_insert {y} : x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a • y + z :=
begin
rw [← union_singleton, span_union, mem_sup],
simp [mem_span_singleton], split,
{ rintro ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩, exact ⟨a, z, hz, rfl⟩ },
{ rintro ⟨a, z, hz, rfl⟩, exact ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩ }
end
lemma mem_span_insert' {y} : x ∈ span (insert y s) ↔ ∃a, x + a • y ∈ span s :=
begin
rw mem_span_insert, split,
{ rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz]⟩ },
{ rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp⟩ }
end
lemma span_insert_eq_span (h : x ∈ span s) : span (insert x s) = span s :=
span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _)
lemma span_span : span (span s : set β) = span s := span_eq _
lemma span_eq_bot : span (s : set β) = ⊥ ↔ ∀ x ∈ s, (x:β) = 0 :=
eq_bot_iff.trans ⟨
λ H x h, mem_bot.1 $ H $ subset_span h,
λ H, span_le.2 (λ x h, mem_bot.2 (H x h))⟩
lemma span_singleton_eq_bot : span ({x} : set β) = ⊥ ↔ x = 0 :=
span_eq_bot.trans $ by simp
@[simp] lemma span_image (f : β →ₗ γ) : span (f '' s) = map f (span s) :=
span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $
span_le.2 $ image_subset_iff.1 subset_span
def prod : submodule α (β × γ) :=
{ carrier := set.prod p q,
zero := ⟨zero_mem _, zero_mem _⟩,
add := by rintro ⟨x₁, y₁⟩ ⟨x₂, y₂⟩ ⟨hx₁, hy₁⟩ ⟨hx₂, hy₂⟩;
exact ⟨add_mem _ hx₁ hx₂, add_mem _ hy₁ hy₂⟩,
smul := by rintro a ⟨x, y⟩ ⟨hx, hy⟩;
exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩ }
@[simp] lemma prod_coe :
(prod p q : set (β × γ)) = set.prod p q := rfl
@[simp] lemma mem_prod {p : submodule α β} {q : submodule α γ} {x : β × γ} :
x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod
lemma span_prod_le (s : set β) (t : set γ) :
span (set.prod s t) ≤ prod (span s) (span t) :=
span_le.2 $ set.prod_mono subset_span subset_span
@[simp] lemma prod_top : (prod ⊤ ⊤ : submodule α (β × γ)) = ⊤ :=
by ext; simp
@[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule α (β × γ)) = ⊥ :=
by ext ⟨x, y⟩; simp [prod.zero_eq_mk]
lemma prod_mono {p p' : submodule α β} {q q' : submodule α γ} :
p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono
@[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') :=
ext' set.prod_inter_prod
@[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') :=
begin
refine le_antisymm (sup_le
(prod_mono le_sup_left le_sup_left)
(prod_mono le_sup_right le_sup_right)) _,
simp [le_def'], intros xx yy hxx hyy,
rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩,
rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩,
refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩
end
-- TODO(Mario): Factor through add_subgroup
def quotient_rel : setoid β :=
⟨λ x y, x - y ∈ p, λ x, by simp,
λ x y h, by simpa using neg_mem _ h,
λ x y z h₁ h₂, by simpa using add_mem _ h₁ h₂⟩
def quotient : Type* := quotient (quotient_rel p)
namespace quotient
def mk {p : submodule α β} : β → quotient p := quotient.mk'
@[simp] theorem mk_eq_mk {p : submodule α β} (x : β) : (quotient.mk x : quotient p) = mk x := rfl
@[simp] theorem mk'_eq_mk {p : submodule α β} (x : β) : (quotient.mk' x : quotient p) = mk x := rfl
@[simp] theorem quot_mk_eq_mk {p : submodule α β} (x : β) : (quot.mk _ x : quotient p) = mk x := rfl
protected theorem eq {x y : β} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq'
instance : has_zero (quotient p) := ⟨mk 0⟩
@[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl
@[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p :=
by simpa using (quotient.eq p : mk x = 0 ↔ _)
instance : has_add (quotient p) :=
⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $
λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa using add_mem p h₁ h₂⟩
@[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl
instance : has_neg (quotient p) :=
⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $
λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩
@[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl
instance : add_comm_group (quotient p) :=
by refine {zero := 0, add := (+), neg := has_neg.neg, ..};
repeat {rintro ⟨⟩};
simp [-mk_zero, (mk_zero p).symm, -mk_add, (mk_add p).symm, -mk_neg, (mk_neg p).symm]
instance : has_scalar α (quotient p) :=
⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $
λ x y h, (quotient.eq p).2 $ by simpa [smul_add] using smul_mem p a h⟩
@[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl
instance : module α (quotient p) :=
module.of_core $ by refine {smul := (•), ..};
repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul,
-mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm]
instance {α β} {R:discrete_field α} [add_comm_group β] [vector_space α β]
(p : submodule α β) : vector_space α (quotient p) := {}
end quotient
end submodule
namespace linear_map
variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
include α
open submodule
@[simp] lemma finsupp_sum {α β γ δ} [ring α] [add_comm_group β] [module α β]
[add_comm_group γ] [module α γ] [has_zero δ]
(f : β →ₗ γ) {t : ι →₀ δ} {g : ι → δ → β} :
f (t.sum g) = t.sum (λi d, f (g i d)) := f.map_sum
theorem map_cod_restrict (p : submodule α β) (f : γ →ₗ β) (h p') :
submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) :=
submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.coe_ext]
theorem comap_cod_restrict (p : submodule α β) (f : γ →ₗ β) (hf p') :
submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') :=
submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩
def range (f : β →ₗ γ) : submodule α γ := map f ⊤
theorem range_coe (f : β →ₗ γ) : (range f : set γ) = set.range f := set.image_univ
@[simp] theorem mem_range {f : β →ₗ γ} : ∀ {x}, x ∈ range f ↔ ∃ y, f y = x :=
(set.ext_iff _ _).1 (range_coe f).
@[simp] theorem range_id : range (linear_map.id : β →ₗ β) = ⊤ := map_id _
theorem range_comp (f : β →ₗ γ) (g : γ →ₗ δ) : range (g.comp f) = map g (range f) :=
map_comp _ _ _
theorem range_comp_le_range (f : β →ₗ γ) (g : γ →ₗ δ) : range (g.comp f) ≤ range g :=
by rw range_comp; exact map_mono le_top
theorem range_eq_top {f : β →ₗ γ} : range f = ⊤ ↔ surjective f :=
by rw [← submodule.ext'_iff, range_coe, top_coe, set.range_iff_surjective]
lemma range_le_iff_comap {f : β →ₗ γ} {p : submodule α γ} : range f ≤ p ↔ comap f p = ⊤ :=
by rw [range, map_le_iff_le_comap, eq_top_iff]
def ker (f : β →ₗ γ) : submodule α β := comap f ⊥
@[simp] theorem mem_ker {f : β →ₗ γ} {y} : y ∈ ker f ↔ f y = 0 := mem_bot
@[simp] theorem ker_id : ker (linear_map.id : β →ₗ β) = ⊥ := rfl
theorem ker_comp (f : β →ₗ γ) (g : γ →ₗ δ) : ker (g.comp f) = comap f (ker g) := rfl
theorem ker_le_ker_comp (f : β →ₗ γ) (g : γ →ₗ δ) : ker f ≤ ker (g.comp f) :=
by rw ker_comp; exact comap_mono bot_le
theorem sub_mem_ker_iff {f : β →ₗ γ} {x y} : x - y ∈ f.ker ↔ f x = f y :=
by rw [mem_ker, map_sub, sub_eq_zero]
theorem disjoint_ker {f : β →ₗ γ} {p : submodule α β} :
disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 :=
by simp [disjoint_def]
theorem disjoint_ker' {f : β →ₗ γ} {p : submodule α β} :
disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y :=
disjoint_ker.trans
⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]),
λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩
theorem inj_of_disjoint_ker {f : β →ₗ γ} {p : submodule α β}
{s : set β} (h : s ⊆ p) (hd : disjoint p (ker f)) :
∀ x y ∈ s, f x = f y → x = y :=
λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy)
theorem ker_eq_bot {f : β →ₗ γ} : ker f = ⊥ ↔ injective f :=
by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤
lemma le_ker_iff_map {f : β →ₗ γ} {p : submodule α β} : p ≤ ker f ↔ map f p = ⊥ :=
by rw [ker, eq_bot_iff, map_le_iff_le_comap]
lemma map_comap_eq (f : β →ₗ γ) (q : submodule α γ) :
map f (comap f q) = range f ⊓ q :=
le_antisymm (le_inf (map_mono le_top) (map_comap_le _ _)) $
by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩
lemma map_comap_eq_self {f : β →ₗ γ} {q : submodule α γ} (h : q ≤ range f) :
map f (comap f q) = q :=
by rw [map_comap_eq, inf_of_le_right h]
lemma comap_map_eq (f : β →ₗ γ) (p : submodule α β) :
comap f (map f p) = p ⊔ ker f :=
begin
refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)),
rintro x ⟨y, hy, e⟩,
exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩
end
lemma comap_map_eq_self {f : β →ₗ γ} {p : submodule α β} (h : ker f ≤ p) :
comap f (map f p) = p :=
by rw [comap_map_eq, sup_of_le_left h]
@[simp] theorem ker_zero : ker (0 : β →ₗ γ) = ⊤ :=
eq_top_iff'.2 $ λ x, by simp
theorem ker_eq_top {f : β →ₗ γ} : ker f = ⊤ ↔ f = 0 :=
⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩
theorem map_le_map_iff {f : β →ₗ γ} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' :=
⟨λ H x hx, let ⟨y, hy, e⟩ := H ⟨x, hx, rfl⟩ in ker_eq_bot.1 hf e ▸ hy, map_mono⟩
theorem map_injective {f : β →ₗ γ} (hf : ker f = ⊥) : injective (map f) :=
λ p p' h, le_antisymm ((map_le_map_iff hf).1 (le_of_eq h)) ((map_le_map_iff hf).1 (ge_of_eq h))
theorem comap_le_comap_iff {f : β →ₗ γ} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' :=
⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩
theorem comap_injective {f : β →ₗ γ} (hf : range f = ⊤) : injective (comap f) :=
λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h))
theorem map_copair_prod (f : β →ₗ δ) (g : γ →ₗ δ) (p : submodule α β) (q : submodule α γ) :
map (copair f g) (p.prod q) = map f p ⊔ map g q :=
begin
refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)),
{ rw le_def', rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩,
exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ },
{ exact λ x hx, ⟨(x, 0), by simp [hx]⟩ },
{ exact λ x hx, ⟨(0, x), by simp [hx]⟩ }
end
theorem comap_pair_prod (f : β →ₗ γ) (g : β →ₗ δ) (p : submodule α γ) (q : submodule α δ) :
comap (pair f g) (p.prod q) = comap f p ⊓ comap g q :=
submodule.ext $ λ x, iff.rfl
theorem prod_eq_inf_comap (p : submodule α β) (q : submodule α γ) :
p.prod q = p.comap (linear_map.fst β γ) ⊓ q.comap (linear_map.snd β γ) :=
submodule.ext $ λ x, iff.rfl
theorem prod_eq_sup_map (p : submodule α β) (q : submodule α γ) :
p.prod q = p.map (linear_map.inl β γ) ⊔ q.map (linear_map.inr β γ) :=
by rw [← map_copair_prod, copair_inl_inr, map_id]
lemma span_inl_union_inr {s : set β} {t : set γ} :
span (prod.inl '' s ∪ prod.inr '' t) = (span s).prod (span t) :=
by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image]; refl
end linear_map
namespace submodule
variables {R:ring α} [add_comm_group β] [add_comm_group γ] [module α β] [module α γ]
variables (p p' : submodule α β) (q : submodule α γ)
include R
open linear_map
@[simp] theorem map_top (f : β →ₗ γ) : map f ⊤ = range f := rfl
@[simp] theorem comap_bot (f : β →ₗ γ) : comap f ⊥ = ker f := rfl
@[simp] theorem ker_subtype : p.subtype.ker = ⊥ :=
ker_eq_bot.2 $ λ x y, subtype.eq'
@[simp] theorem range_subtype : p.subtype.range = p :=
by simpa using map_comap_subtype p ⊤
lemma map_subtype_le (p' : submodule α p) : map p.subtype p' ≤ p :=
by simpa using (map_mono le_top : map p.subtype p' ≤ p.subtype.range)
/-- If N ⊆ M then submodules of N are the same as submodules of M contained in N -/
def map_subtype.order_iso :
((≤) : submodule α p → submodule α p → Prop) ≃o
((≤) : {p' : submodule α β // p' ≤ p} → {p' : submodule α β // p' ≤ p} → Prop) :=
{ to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩,
inv_fun := λ q, comap p.subtype q,
left_inv := λ p', comap_map_eq_self $ by simp,
right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [map_comap_subtype p, inf_of_le_right hq],
ord := λ p₁ p₂, (map_le_map_iff $ ker_subtype _).symm }
def map_subtype.le_order_embedding :
((≤) : submodule α p → submodule α p → Prop) ≼o ((≤) : submodule α β → submodule α β → Prop) :=
(order_iso.to_order_embedding $ map_subtype.order_iso p).trans (subtype.order_embedding _ _)
@[simp] lemma map_subtype_embedding_eq (p' : submodule α p) :
map_subtype.le_order_embedding p p' = map p.subtype p' := rfl
def map_subtype.lt_order_embedding :
((<) : submodule α p → submodule α p → Prop) ≼o ((<) : submodule α β → submodule α β → Prop) :=
(map_subtype.le_order_embedding p).lt_embedding_of_le_embedding
@[simp] theorem map_inl : p.map (inl β γ) = prod p ⊥ :=
by ext ⟨x, y⟩; simp [and.left_comm, eq_comm]
@[simp] theorem map_inr : q.map (inr β γ) = prod ⊥ q :=
by ext ⟨x, y⟩; simp [and.left_comm, eq_comm]
@[simp] theorem comap_fst : p.comap (fst β γ) = prod p ⊤ :=
by ext ⟨x, y⟩; simp
@[simp] theorem comap_snd : q.comap (snd β γ) = prod ⊤ q :=
by ext ⟨x, y⟩; simp
@[simp] theorem prod_comap_inl : (prod p q).comap (inl β γ) = p := by ext; simp
@[simp] theorem prod_comap_inr : (prod p q).comap (inr β γ) = q := by ext; simp
@[simp] theorem prod_map_fst : (prod p q).map (fst β γ) = p :=
by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)]
@[simp] theorem prod_map_snd : (prod p q).map (snd β γ) = q :=
by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)]
@[simp] theorem ker_inl : (inl β γ).ker = ⊥ :=
by rw [ker, ← prod_bot, prod_comap_inl]
@[simp] theorem ker_inr : (inr β γ).ker = ⊥ :=
by rw [ker, ← prod_bot, prod_comap_inr]
@[simp] theorem range_fst : (fst β γ).range = ⊤ :=
by rw [range, ← prod_top, prod_map_fst]
@[simp] theorem range_snd : (snd β γ).range = ⊤ :=
by rw [range, ← prod_top, prod_map_snd]
def mkq : β →ₗ p.quotient := ⟨quotient.mk, by simp, by simp⟩
@[simp] theorem mkq_apply (x : β) : p.mkq x = quotient.mk x := rfl
def liftq (f : β →ₗ γ) (h : p ≤ f.ker) : p.quotient →ₗ γ :=
⟨λ x, _root_.quotient.lift_on' x f $
λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab,
by rintro ⟨x⟩ ⟨y⟩; exact map_add f x y,
by rintro a ⟨x⟩; exact map_smul f a x⟩
@[simp] theorem liftq_apply (f : β →ₗ γ) {h} (x : β) :
p.liftq f h (quotient.mk x) = f x := rfl
@[simp] theorem liftq_mkq (f : β →ₗ γ) (h) : (p.liftq f h).comp p.mkq = f :=
by ext; refl
@[simp] theorem range_mkq : p.mkq.range = ⊤ :=
eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, trivial, rfl⟩
@[simp] theorem ker_mkq : p.mkq.ker = p :=
by ext; simp
lemma le_comap_mkq (p' : submodule α p.quotient) : p ≤ comap p.mkq p' :=
by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p')
@[simp] theorem mkq_map_self : map p.mkq p = ⊥ :=
by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _
@[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' :=
by simp [comap_map_eq, sup_comm]
def mapq (f : β →ₗ γ) (h : p ≤ comap f q) : p.quotient →ₗ q.quotient :=
p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h
@[simp] theorem mapq_apply (f : β →ₗ γ) {h} (x : β) :
mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl
theorem mapq_mkq (f : β →ₗ γ) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f :=
by ext x; refl
theorem comap_liftq (f : β →ₗ γ) (h) :
q.comap (p.liftq f h) = (q.comap f).map (mkq p) :=
le_antisymm
(by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩)
(by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _)
theorem ker_liftq (f : β →ₗ γ) (h) :
ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _
theorem ker_liftq_eq_bot (f : β →ₗ γ) (h) (h' : ker f = p) : ker (p.liftq f h) = ⊥ :=
by rw [ker_liftq, h', mkq_map_self]
/-- Correspondence Theorem -/
def comap_mkq.order_iso :
((≤) : submodule α p.quotient → submodule α p.quotient → Prop) ≃o
((≤) : {p' : submodule α β // p ≤ p'} → {p' : submodule α β // p ≤ p'} → Prop) :=
{ to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩,
inv_fun := λ q, map p.mkq q,
left_inv := λ p', map_comap_eq_self $ by simp,
right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [comap_map_mkq p, sup_of_le_right hq],
ord := λ p₁ p₂, (comap_le_comap_iff $ range_mkq _).symm }
def comap_mkq.le_order_embedding :
((≤) : submodule α p.quotient → submodule α p.quotient → Prop) ≼o ((≤) : submodule α β → submodule α β → Prop) :=
(order_iso.to_order_embedding $ comap_mkq.order_iso p).trans (subtype.order_embedding _ _)
@[simp] lemma comap_mkq_embedding_eq (p' : submodule α p.quotient) :
comap_mkq.le_order_embedding p p' = comap p.mkq p' := rfl
def comap_mkq.lt_order_embedding :
((<) : submodule α p.quotient → submodule α p.quotient → Prop) ≼o ((<) : submodule α β → submodule α β → Prop) :=
(comap_mkq.le_order_embedding p).lt_embedding_of_le_embedding
end submodule
section
set_option old_structure_cmd true
structure linear_equiv {α : Type u} (β : Type v) (γ : Type w)
[ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ]
extends β →ₗ γ, β ≃ γ
end
infix ` ≃ₗ ` := linear_equiv
namespace linear_equiv
section ring
variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
include α
section
variable (β)
def refl : β ≃ₗ β := { .. linear_map.id, .. equiv.refl β }
end
def symm (e : β ≃ₗ γ) : γ ≃ₗ β :=
{ .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv,
.. e.to_equiv.symm }
def trans (e₁ : β ≃ₗ γ) (e₂ : γ ≃ₗ δ) : β ≃ₗ δ :=
{ .. e₂.to_linear_map.comp e₁.to_linear_map,
.. e₁.to_equiv.trans e₂.to_equiv }
instance : has_coe (β ≃ₗ γ) (β →ₗ γ) := ⟨to_linear_map⟩
@[simp] theorem apply_symm_apply (e : β ≃ₗ γ) (c : γ) : e (e.symm c) = c := e.6 c
@[simp] theorem symm_apply_apply (e : β ≃ₗ γ) (b : β) : e.symm (e b) = b := e.5 b
@[simp] theorem coe_apply (e : β ≃ₗ γ) (b : β) : (e : β →ₗ γ) b = e b := rfl
noncomputable def of_bijective
(f : β →ₗ γ) (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : β ≃ₗ γ :=
{ ..f, ..@equiv.of_bijective _ _ f
⟨linear_map.ker_eq_bot.1 hf₁, linear_map.range_eq_top.1 hf₂⟩ }
@[simp] theorem of_bijective_apply (f : β →ₗ γ) {hf₁ hf₂} (x : β) :
of_bijective f hf₁ hf₂ x = f x := rfl
def of_linear (f : β →ₗ γ) (g : γ →ₗ β)
(h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : β ≃ₗ γ :=
{ inv_fun := g,
left_inv := linear_map.ext_iff.1 h₂,
right_inv := linear_map.ext_iff.1 h₁,
..f }
@[simp] theorem of_linear_apply (f : β →ₗ γ) (g : γ →ₗ β) {h₁ h₂}
(x : β) : of_linear f g h₁ h₂ x = f x := rfl
@[simp] theorem of_linear_symm_apply (f : β →ₗ γ) (g : γ →ₗ β) {h₁ h₂}
(x : γ) : (of_linear f g h₁ h₂).symm x = g x := rfl
@[simp] protected theorem ker (f : β ≃ₗ γ) : (f : β →ₗ γ).ker = ⊥ :=
linear_map.ker_eq_bot.2 f.to_equiv.bijective.1
@[simp] protected theorem range (f : β ≃ₗ γ) : (f : β →ₗ γ).range = ⊤ :=
linear_map.range_eq_top.2 f.to_equiv.bijective.2
def of_top (p : submodule α β) (h : p = ⊤) : p ≃ₗ β :=
{ inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩,
left_inv := λ ⟨x, h⟩, rfl,
right_inv := λ x, rfl,
.. p.subtype }
@[simp] theorem of_top_apply (p : submodule α β) {h} (x : p) :
of_top p h x = x := rfl
@[simp] theorem of_top_symm_apply (p : submodule α β) {h} (x : β) :
↑((of_top p h).symm x) = x := rfl
end ring
section comm_ring
variables [comm_ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
include α
def congr_right (f : γ ≃ₗ δ) : (β →ₗ γ) ≃ₗ (β →ₗ δ) :=
of_linear
f.to_linear_map.congr_right
f.symm.to_linear_map.congr_right
(linear_map.ext $ λ _, linear_map.ext $ λ _, f.6 _)
(linear_map.ext $ λ _, linear_map.ext $ λ _, f.5 _)
end comm_ring
end linear_equiv
namespace linear_map
variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
variables (f : β →ₗ γ)
/-- First Isomorphism Law -/
noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ f.range :=
have hr : ∀ x : f.range, ∃ y, f y = ↑x := λ x, x.2.imp $ λ _, and.right,
let F : f.ker.quotient →ₗ f.range :=
f.ker.liftq (cod_restrict f.range f $ λ x, ⟨x, trivial, rfl⟩)
(λ x hx, by simp; apply subtype.coe_ext.2; simpa using hx) in
{ inv_fun := λx, submodule.quotient.mk (classical.some (hr x)),
left_inv := by rintro ⟨x⟩; exact
(submodule.quotient.eq _).2 (sub_mem_ker_iff.2 $
classical.some_spec $ hr $ F $ submodule.quotient.mk x),
right_inv := λ x : range f, subtype.eq $ classical.some_spec (hr x),
.. F }
open submodule
/-- Second Isomorphism Law -/
noncomputable def sup_quotient_equiv_quotient_inf (p p' : submodule α β) :
(comap p.subtype (p ⊓ p')).quotient ≃ₗ
(comap (p ⊔ p').subtype p').quotient :=
begin
let F : (comap p.subtype (p ⊓ p')).quotient →ₗ
(comap (p ⊔ p').subtype p').quotient :=
(comap p.subtype (p ⊓ p')).liftq
((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin
rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype],
exact comap_mono (inf_le_inf le_sup_left (le_refl _)),
end,
have hsup : ∀ x : p ⊔ p', ∃ y : p, ↑x - ↑y ∈ p',
{ rintro ⟨x, hx⟩,
rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩,
exact ⟨⟨y, hy⟩, by simp [hz]⟩ },
let G := λ x, classical.some (hsup x),
have hG : ∀ x : p ⊔ p', ↑x - ↑(G x) ∈ p' :=
λ x, classical.some_spec (hsup x),
refine {
to_fun := F,
inv_fun := λ q, quotient.lift_on' q (λ x, submodule.quotient.mk (G x)) _,
..F, .. },
{ refine λ x y h, (submodule.quotient.eq _).2 ⟨(G x - G y : p).2, _⟩,
simpa using add_mem _ (sub_mem p' h (hG x)) (hG y) },
{ rintro ⟨x⟩,
refine ((submodule.quotient.eq _).2 _).symm,
exact ⟨(x - G _ : p).2, hG ⟨↑x, _⟩⟩ },
{ rintro ⟨x⟩, refine (quot.sound _).symm, exact hG x }
end
end linear_map
|
30206b9f008ea5c8c8b9c473bbeb504515430de9 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/multiset/sort.lean | 14f16370604d9c80481f03298feba1e620b81fc2 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 1,483 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.list.sort
import data.multiset.basic
import data.string.basic
/-!
# Construct a sorted list from a multiset.
-/
namespace multiset
open list
variables {α : Type*}
section sort
variables (r : α → α → Prop) [decidable_rel r]
[is_trans α r] [is_antisymm α r] [is_total α r]
/-- `sort s` constructs a sorted list from the multiset `s`.
(Uses merge sort algorithm.) -/
def sort (s : multiset α) : list α :=
quot.lift_on s (merge_sort r) $ λ a b h,
eq_of_perm_of_sorted
((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm)
(sorted_merge_sort r _)
(sorted_merge_sort r _)
@[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl
@[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) :=
quot.induction_on s $ λ l, sorted_merge_sort r _
@[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s :=
quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _
@[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
by rw [← mem_coe, sort_eq]
@[simp] theorem length_sort {s : multiset α} : (sort r s).length = s.card :=
quot.induction_on s $ length_merge_sort _
end sort
instance [has_repr α] : has_repr (multiset α) :=
⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩
end multiset
|
a74901c484b0ac6007a53f9ed94d8ed30d004dbd | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/ring_theory/perfection.lean | 898854c0ec94bd9fcdda7b817080f1a2316cfb30 | [] | 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 | 24,048 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.char_p.default
import Mathlib.algebra.ring.pi
import Mathlib.analysis.special_functions.pow
import Mathlib.field_theory.perfect_closure
import Mathlib.ring_theory.localization
import Mathlib.ring_theory.subring
import Mathlib.ring_theory.valuation.integers
import Mathlib.PostPort
universes u₁ u₂ l u₃ u₄
namespace Mathlib
/-!
# Ring Perfection and Tilt
In this file we define the perfection of a ring of characteristic p, and the tilt of a field
given a valuation to `ℝ≥0`.
## TODO
Define the valuation on the tilt, and define a characteristic predicate for the tilt.
-/
/-- The perfection of a monoid `M`, defined to be the projective limit of `M`
using the `p`-th power maps `M → M` indexed by the natural numbers, implemented as
`{ f : ℕ → M | ∀ n, f (n + 1) ^ p = f n }`. -/
def monoid.perfection (M : Type u₁) [comm_monoid M] (p : ℕ) : submonoid (ℕ → M) :=
submonoid.mk (set_of fun (f : ℕ → M) => ∀ (n : ℕ), f (n + 1) ^ p = f n) sorry sorry
/-- The perfection of a ring `R` with characteristic `p`,
defined to be the projective limit of `R` using the Frobenius maps `R → R`
indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/
def ring.perfection (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact (nat.prime p)] [char_p R p] : subsemiring (ℕ → R) :=
subsemiring.mk (submonoid.carrier (monoid.perfection R p)) sorry sorry sorry sorry
namespace perfection
/-- The `n`-th coefficient of an element of the perfection. -/
def coeff (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact (nat.prime p)] [char_p R p] (n : ℕ) : ↥(ring.perfection R p) →+* R :=
ring_hom.mk (fun (f : ↥(ring.perfection R p)) => subtype.val f n) sorry sorry sorry sorry
theorem ext {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] {f : ↥(ring.perfection R p)} {g : ↥(ring.perfection R p)} (h : ∀ (n : ℕ), coe_fn (coeff R p n) f = coe_fn (coeff R p n) g) : f = g :=
subtype.eq (funext h)
/-- The `p`-th root of an element of the perfection. -/
def pth_root (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact (nat.prime p)] [char_p R p] : ↥(ring.perfection R p) →+* ↥(ring.perfection R p) :=
ring_hom.mk
(fun (f : ↥(ring.perfection R p)) => { val := fun (n : ℕ) => coe_fn (coeff R p (n + 1)) f, property := sorry }) sorry
sorry sorry sorry
@[simp] theorem coeff_mk {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ℕ → R) (hf : f ∈ ring.perfection R p) (n : ℕ) : coe_fn (coeff R p n) { val := f, property := hf } = f n :=
rfl
theorem coeff_pth_root {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ↥(ring.perfection R p)) (n : ℕ) : coe_fn (coeff R p n) (coe_fn (pth_root R p) f) = coe_fn (coeff R p (n + 1)) f :=
rfl
theorem coeff_pow_p {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ↥(ring.perfection R p)) (n : ℕ) : coe_fn (coeff R p (n + 1)) (f ^ p) = coe_fn (coeff R p n) f := sorry
theorem coeff_pow_p' {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ↥(ring.perfection R p)) (n : ℕ) : coe_fn (coeff R p (n + 1)) f ^ p = coe_fn (coeff R p n) f :=
subtype.property f n
theorem coeff_frobenius {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ↥(ring.perfection R p)) (n : ℕ) : coe_fn (coeff R p (n + 1)) (coe_fn (frobenius (↥(ring.perfection R p)) p) f) = coe_fn (coeff R p n) f := sorry
theorem coeff_iterate_frobenius {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ↥(ring.perfection R p)) (n : ℕ) (m : ℕ) : coe_fn (coeff R p (n + m)) (nat.iterate (⇑(frobenius (↥(ring.perfection R p)) p)) m f) = coe_fn (coeff R p n) f := sorry
theorem coeff_iterate_frobenius' {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ↥(ring.perfection R p)) (n : ℕ) (m : ℕ) (hmn : m ≤ n) : coe_fn (coeff R p n) (nat.iterate (⇑(frobenius (↥(ring.perfection R p)) p)) m f) = coe_fn (coeff R p (n - m)) f :=
Eq.symm (Eq.trans (Eq.symm (coeff_iterate_frobenius f (n - m) m)) (Eq.symm (nat.sub_add_cancel hmn) ▸ rfl))
theorem pth_root_frobenius {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] : ring_hom.comp (pth_root R p) (frobenius (↥(ring.perfection R p)) p) = ring_hom.id ↥(ring.perfection R p) := sorry
theorem frobenius_pth_root {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] : ring_hom.comp (frobenius (↥(ring.perfection R p)) p) (pth_root R p) = ring_hom.id ↥(ring.perfection R p) := sorry
theorem coeff_add_ne_zero {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] {f : ↥(ring.perfection R p)} {n : ℕ} (hfn : coe_fn (coeff R p n) f ≠ 0) (k : ℕ) : coe_fn (coeff R p (n + k)) f ≠ 0 := sorry
theorem coeff_ne_zero_of_le {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] {f : ↥(ring.perfection R p)} {m : ℕ} {n : ℕ} (hfm : coe_fn (coeff R p m) f ≠ 0) (hmn : m ≤ n) : coe_fn (coeff R p n) f ≠ 0 := sorry
protected instance perfect_ring (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact (nat.prime p)] [char_p R p] : perfect_ring (↥(ring.perfection R p)) p :=
perfect_ring.mk ⇑(pth_root R p) sorry sorry
protected instance ring (p : ℕ) [hp : fact (nat.prime p)] (R : Type u₁) [comm_ring R] [char_p R p] : ring ↥(ring.perfection R p) :=
subring.to_ring (subsemiring.to_subring (ring.perfection R p) sorry)
protected instance comm_ring (p : ℕ) [hp : fact (nat.prime p)] (R : Type u₁) [comm_ring R] [char_p R p] : comm_ring ↥(ring.perfection R p) :=
subring.to_comm_ring (subsemiring.to_subring (ring.perfection R p) sorry)
/-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect,
any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* perfection S p`. -/
@[simp] theorem lift_symm_apply (p : ℕ) [hp : fact (nat.prime p)] (R : Type u₁) [comm_semiring R] [char_p R p] [perfect_ring R p] (S : Type u₂) [comm_semiring S] [char_p S p] (hmn : R →+* ↥(ring.perfection S p)) : coe_fn (equiv.symm (lift p R S)) hmn = ring_hom.comp (coeff S p 0) hmn :=
Eq.refl (coe_fn (equiv.symm (lift p R S)) hmn)
theorem hom_ext (p : ℕ) [hp : fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] [perfect_ring R p] {S : Type u₂} [comm_semiring S] [char_p S p] {f : R →+* ↥(ring.perfection S p)} {g : R →+* ↥(ring.perfection S p)} (hfg : ∀ (x : R), coe_fn (coeff S p 0) (coe_fn f x) = coe_fn (coeff S p 0) (coe_fn g x)) : f = g :=
equiv.injective (equiv.symm (lift p R S)) (ring_hom.ext hfg)
/-- A ring homomorphism `R →+* S` induces `perfection R p →+* perfection S p` -/
@[simp] theorem map_apply_coe {R : Type u₁} [comm_semiring R] (p : ℕ) [hp : fact (nat.prime p)] [char_p R p] {S : Type u₂} [comm_semiring S] [char_p S p] (φ : R →+* S) (f : ↥(ring.perfection R p)) (n : ℕ) : coe (coe_fn (map p φ) f) n = coe_fn φ (coe_fn (coeff R p n) f) :=
Eq.refl (coe (coe_fn (map p φ) f) n)
theorem coeff_map {R : Type u₁} [comm_semiring R] (p : ℕ) [hp : fact (nat.prime p)] [char_p R p] {S : Type u₂} [comm_semiring S] [char_p S p] (φ : R →+* S) (f : ↥(ring.perfection R p)) (n : ℕ) : coe_fn (coeff S p n) (coe_fn (map p φ) f) = coe_fn φ (coe_fn (coeff R p n) f) :=
rfl
end perfection
/-- A perfection map to a ring of characteristic `p` is a map that is isomorphic
to its perfection. -/
structure perfection_map (p : ℕ) [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₂} [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* R)
where
injective : ∀ {x y : P},
(∀ (n : ℕ), coe_fn π (nat.iterate (⇑(pth_root P p)) n x) = coe_fn π (nat.iterate (⇑(pth_root P p)) n y)) → x = y
surjective : ∀ (f : ℕ → R),
(∀ (n : ℕ), f (n + 1) ^ p = f n) → ∃ (x : P), ∀ (n : ℕ), coe_fn π (nat.iterate (⇑(pth_root P p)) n x) = f n
namespace perfection_map
/-- Create a `perfection_map` from an isomorphism to the perfection. -/
theorem mk' {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {f : P →+* R} (g : P ≃+* ↥(ring.perfection R p)) (hfg : coe_fn (perfection.lift p P R) f = ↑g) : perfection_map p f := sorry
/-- The canonical perfection map from the perfection of a ring. -/
theorem of (p : ℕ) [fact (nat.prime p)] (R : Type u₁) [comm_semiring R] [char_p R p] : perfection_map p (perfection.coeff R p 0) :=
mk' (ring_equiv.refl ↥(ring.perfection R p))
(iff.mpr (equiv.apply_eq_iff_eq_symm_apply (perfection.lift p (↥(ring.perfection R p)) R)) rfl)
/-- For a perfect ring, it itself is the perfection. -/
theorem id (p : ℕ) [fact (nat.prime p)] (R : Type u₁) [comm_semiring R] [char_p R p] [perfect_ring R p] : perfection_map p (ring_hom.id R) := sorry
/-- A perfection map induces an isomorphism to the prefection. -/
def equiv {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {π : P →+* R} (m : perfection_map p π) : P ≃+* ↥(ring.perfection R p) :=
ring_equiv.of_bijective (coe_fn (perfection.lift p P R) π) sorry
theorem equiv_apply {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {π : P →+* R} (m : perfection_map p π) (x : P) : coe_fn (equiv m) x = coe_fn (coe_fn (perfection.lift p P R) π) x :=
rfl
theorem comp_equiv {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {π : P →+* R} (m : perfection_map p π) (x : P) : coe_fn (perfection.coeff R p 0) (coe_fn (equiv m) x) = coe_fn π x :=
rfl
theorem comp_equiv' {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {π : P →+* R} (m : perfection_map p π) : ring_hom.comp (perfection.coeff R p 0) ↑(equiv m) = π :=
ring_hom.ext fun (x : P) => rfl
theorem comp_symm_equiv {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {π : P →+* R} (m : perfection_map p π) (f : ↥(ring.perfection R p)) : coe_fn π (coe_fn (ring_equiv.symm (equiv m)) f) = coe_fn (perfection.coeff R p 0) f :=
Eq.trans (Eq.symm (comp_equiv m (coe_fn (ring_equiv.symm (equiv m)) f)))
(congr_arg (⇑(perfection.coeff R p 0)) (ring_equiv.apply_symm_apply (equiv m) f))
theorem comp_symm_equiv' {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {π : P →+* R} (m : perfection_map p π) : ring_hom.comp π ↑(ring_equiv.symm (equiv m)) = perfection.coeff R p 0 :=
ring_hom.ext (comp_symm_equiv m)
/-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect,
any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* P`,
where `P` is any perfection of `S`. -/
@[simp] theorem lift_apply (p : ℕ) [fact (nat.prime p)] (R : Type u₁) [comm_semiring R] [char_p R p] [perfect_ring R p] (S : Type u₂) [comm_semiring S] [char_p S p] (P : Type u₃) [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* S) (m : perfection_map p π) (f : R →+* S) : coe_fn (lift p R S P π m) f = ring_hom.comp (↑(ring_equiv.symm (equiv m))) (coe_fn (perfection.lift p R S) f) :=
Eq.refl (coe_fn (lift p R S P π m) f)
theorem hom_ext {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] [perfect_ring R p] {S : Type u₂} [comm_semiring S] [char_p S p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* S) (m : perfection_map p π) {f : R →+* P} {g : R →+* P} (hfg : ∀ (x : R), coe_fn π (coe_fn f x) = coe_fn π (coe_fn g x)) : f = g :=
equiv.injective (equiv.symm (lift p R S P π m)) (ring_hom.ext hfg)
/-- A ring homomorphism `R →+* S` induces `P →+* Q`, a map of the respective perfections -/
def map (p : ℕ) [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {S : Type u₂} [comm_semiring S] [char_p S p] {Q : Type u₄} [comm_semiring Q] [char_p Q p] [perfect_ring Q p] {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) : P →+* Q :=
coe_fn (lift p P S Q σ n) (ring_hom.comp φ π)
theorem comp_map (p : ℕ) [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {S : Type u₂} [comm_semiring S] [char_p S p] {Q : Type u₄} [comm_semiring Q] [char_p Q p] [perfect_ring Q p] {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) : ring_hom.comp σ (map p m n φ) = ring_hom.comp φ π :=
equiv.symm_apply_apply (lift p P S Q σ n) (ring_hom.comp φ π)
theorem map_map (p : ℕ) [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {S : Type u₂} [comm_semiring S] [char_p S p] {Q : Type u₄} [comm_semiring Q] [char_p Q p] [perfect_ring Q p] {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) (x : P) : coe_fn σ (coe_fn (map p m n φ) x) = coe_fn φ (coe_fn π x) :=
iff.mp ring_hom.ext_iff (comp_map p m n φ) x
-- Why is this slow?
theorem map_eq_map (p : ℕ) [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {S : Type u₂} [comm_semiring S] [char_p S p] (φ : R →+* S) : map p (of p R) (of p S) φ = perfection.map p φ := sorry
end perfection_map
/-- `O/(p)` for `O`, ring of integers of `K`. -/
def mod_p (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) :=
ideal.quotient (ideal.span (singleton ↑p))
namespace mod_p
protected instance comm_ring (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) : comm_ring (mod_p K v O hv p) :=
ideal.quotient.comm_ring (ideal.span (singleton ↑p))
protected instance char_p (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : char_p (mod_p K v O hv p) p :=
char_p.quotient O p
(mt (valuation.integers.one_of_is_unit hv) (Eq.symm (ring_hom.map_nat_cast (algebra_map O K) p) ▸ hvp))
protected instance nontrivial (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : nontrivial (mod_p K v O hv p) :=
char_p.nontrivial_of_char_ne_one (nat.prime.ne_one hp)
/-- For a field `K` with valuation `v : K → ℝ≥0` and ring of integers `O`,
a function `O/(p) → ℝ≥0` that sends `0` to `0` and `x + (p)` to `v(x)` as long as `x ∉ (p)`. -/
def pre_val (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) (x : mod_p K v O hv p) : nnreal :=
ite (x = 0) 0 (coe_fn v (coe_fn (algebra_map O K) (quotient.out' x)))
theorem pre_val_mk {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} {x : O} (hx : coe_fn (ideal.quotient.mk (ideal.span (singleton ↑p))) x ≠ 0) : pre_val K v O hv p (coe_fn (ideal.quotient.mk (ideal.span (singleton ↑p))) x) = coe_fn v (coe_fn (algebra_map O K) x) := sorry
theorem pre_val_zero {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} : pre_val K v O hv p 0 = 0 :=
if_pos rfl
theorem pre_val_mul {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} {x : mod_p K v O hv p} {y : mod_p K v O hv p} (hxy0 : x * y ≠ 0) : pre_val K v O hv p (x * y) = pre_val K v O hv p x * pre_val K v O hv p y := sorry
theorem pre_val_add {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} (x : mod_p K v O hv p) (y : mod_p K v O hv p) : pre_val K v O hv p (x + y) ≤ max (pre_val K v O hv p x) (pre_val K v O hv p y) := sorry
theorem v_p_lt_pre_val {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} {x : mod_p K v O hv p} : coe_fn v ↑p < pre_val K v O hv p x ↔ x ≠ 0 := sorry
theorem pre_val_eq_zero {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} {x : mod_p K v O hv p} : pre_val K v O hv p x = 0 ↔ x = 0 := sorry
theorem v_p_lt_val {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] (hv : valuation.integers v O) {p : ℕ} {x : O} : coe_fn v ↑p < coe_fn v (coe_fn (algebra_map O K) x) ↔ coe_fn (ideal.quotient.mk (ideal.span (singleton ↑p))) x ≠ 0 := sorry
theorem mul_ne_zero_of_pow_p_ne_zero {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] {x : mod_p K v O hv p} {y : mod_p K v O hv p} (hx : x ^ p ≠ 0) (hy : y ^ p ≠ 0) : x * y ≠ 0 := sorry
end mod_p
/-- Perfection of `O/(p)` where `O` is the ring of integers of `K`. -/
def pre_tilt (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : subsemiring (ℕ → mod_p K v O hv p) :=
ring.perfection (mod_p K v O hv p) p
namespace pre_tilt
protected instance comm_ring (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : comm_ring ↥(pre_tilt K v O hv p) :=
perfection.comm_ring p (mod_p K v O hv p)
/-- The valuation `Perfection(O/(p)) → ℝ≥0` as a function.
Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`;
otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/
def val_aux (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] (f : ↥(pre_tilt K v O hv p)) : nnreal :=
dite (∃ (n : ℕ), coe_fn (perfection.coeff (mod_p K v O hv p) p n) f ≠ 0)
(fun (h : ∃ (n : ℕ), coe_fn (perfection.coeff (mod_p K v O hv p) p n) f ≠ 0) =>
mod_p.pre_val K v O hv p (coe_fn (perfection.coeff (mod_p K v O hv p) p (nat.find h)) f) ^ p ^ nat.find h)
fun (h : ¬∃ (n : ℕ), coe_fn (perfection.coeff (mod_p K v O hv p) p n) f ≠ 0) => 0
theorem coeff_nat_find_add_ne_zero {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] {f : ↥(pre_tilt K v O hv p)} {h : ∃ (n : ℕ), coe_fn (perfection.coeff (mod_p K v O hv p) p n) f ≠ 0} (k : ℕ) : coe_fn (perfection.coeff (mod_p K v O hv p) p (nat.find h + k)) f ≠ 0 :=
perfection.coeff_add_ne_zero (nat.find_spec h) k
theorem val_aux_eq {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] {f : ↥(pre_tilt K v O hv p)} {n : ℕ} (hfn : coe_fn (perfection.coeff (mod_p K v O hv p) p n) f ≠ 0) : val_aux K v O hv p f = mod_p.pre_val K v O hv p (coe_fn (perfection.coeff (mod_p K v O hv p) p n) f) ^ p ^ n := sorry
theorem val_aux_zero {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : val_aux K v O hv p 0 = 0 := sorry
theorem val_aux_one {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : val_aux K v O hv p 1 = 1 := sorry
theorem val_aux_mul {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] (f : ↥(pre_tilt K v O hv p)) (g : ↥(pre_tilt K v O hv p)) : val_aux K v O hv p (f * g) = val_aux K v O hv p f * val_aux K v O hv p g := sorry
theorem val_aux_add {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] (f : ↥(pre_tilt K v O hv p)) (g : ↥(pre_tilt K v O hv p)) : val_aux K v O hv p (f + g) ≤ max (val_aux K v O hv p f) (val_aux K v O hv p g) := sorry
/-- The valuation `Perfection(O/(p)) → ℝ≥0`.
Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`;
otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/
def val (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : valuation (↥(pre_tilt K v O hv p)) nnreal :=
valuation.mk (val_aux K v O hv p) val_aux_zero val_aux_one val_aux_mul val_aux_add
theorem map_eq_zero {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] {f : ↥(pre_tilt K v O hv p)} : coe_fn (val K v O hv p) f = 0 ↔ f = 0 := sorry
protected instance integral_domain (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : integral_domain ↥(pre_tilt K v O hv p) :=
integral_domain.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul
sorry comm_ring.one sorry sorry sorry sorry sorry sorry sorry
end pre_tilt
/-- The tilt of a field, as defined in Perfectoid Spaces by Peter Scholze, as in
[scholze2011perfectoid]. Given a field `K` with valuation `K → ℝ≥0` and ring of integers `O`,
this is implemented as the fraction field of the perfection of `O/(p)`. -/
def tilt (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] :=
fraction_ring ↥(pre_tilt K v O hv p)
namespace tilt
protected instance field (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : field (tilt K v O hv p) :=
fraction_ring.field
|
cd85d332b4fffb24cea0132ba04a1bdd2b66c2ea | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/run/e1.lean | 5e0d251f9d9c63aca3c884f576052bfc1474c2b4 | [
"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 | 327 | lean | prelude
definition Prop : Sort.{1} := Sort.{0}
constant eq : forall {A : Type}, A → A → Prop
constant N : Type
constants a b c : N
infix `=`:50 := eq
#check a = b
constant f : Prop → N → N
constant g : N → N → N
precedence `+`:50
infixl + := f
infixl + := g
#check a + b + c
constant p : Prop
#check p + a + b + c
|
5bb13d565919af1311717aa7e2d739a99ce07c29 | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/algebra/group/basic.lean | 075e2064a8133fe941a48526761a75cf2ef0861c | [
"Apache-2.0"
] | permissive | ntzwq/mathlib | ca50b21079b0a7c6781c34b62199a396dd00cee2 | 36eec1a98f22df82eaccd354a758ef8576af2a7f | refs/heads/master | 1,675,193,391,478 | 1,607,822,996,000 | 1,607,822,996,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,186 | 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, Simon Hudon, Mario Carneiro
-/
import algebra.group.defs
import logic.function.basic
universe u
section associative
variables {α : Type u} (f : α → α → α) [is_associative α f] (x y : α)
/--
Composing two associative operations of `f : α → α → α` on the left
is equal to an associative operation on the left.
-/
lemma comp_assoc_left : (f x) ∘ (f y) = (f (f x y)) :=
by { ext z, rw [function.comp_apply, @is_associative.assoc _ f] }
/--
Composing two associative operations of `f : α → α → α` on the right
is equal to an associative operation on the right.
-/
lemma comp_assoc_right : (λ z, f z x) ∘ (λ z, f z y) = (λ z, f z (f y x)) :=
by { ext z, rw [function.comp_apply, @is_associative.assoc _ f] }
end associative
section semigroup
variables {α : Type*}
/--
Composing two multiplications on the left by `y` then `x`
is equal to a multiplication on the left by `x * y`.
-/
@[simp, to_additive
"Composing two additions on the left by `y` then `x`
is equal to a addition on the left by `x + y`."]
lemma comp_mul_left [semigroup α] (x y : α) :
((*) x) ∘ ((*) y) = ((*) (x * y)) :=
comp_assoc_left _ _ _
/--
Composing two multiplications on the right by `y` and `x`
is equal to a multiplication on the right by `y * x`.
-/
@[simp, to_additive
"Composing two additions on the right by `y` and `x`
is equal to a addition on the right by `y + x`."]
lemma comp_mul_right [semigroup α] (x y : α) :
(* x) ∘ (* y) = (* (y * x)) :=
comp_assoc_right _ _ _
end semigroup
section monoid
variables {M : Type u} [monoid M]
@[to_additive]
lemma ite_mul_one {P : Prop} [decidable P] {a b : M} :
ite P (a * b) 1 = ite P a 1 * ite P b 1 :=
by { by_cases h : P; simp [h], }
@[to_additive]
lemma eq_one_iff_eq_one_of_mul_eq_one {a b : M} (h : a * b = 1) : a = 1 ↔ b = 1 :=
by split; { rintro rfl, simpa using h }
end monoid
section comm_semigroup
variables {G : Type u} [comm_semigroup G]
@[no_rsimp, to_additive]
lemma mul_left_comm : ∀ a b c : G, a * (b * c) = b * (a * c) :=
left_comm has_mul.mul mul_comm mul_assoc
attribute [no_rsimp] add_left_comm
@[to_additive]
lemma mul_right_comm : ∀ a b c : G, a * b * c = a * c * b :=
right_comm has_mul.mul mul_comm mul_assoc
@[to_additive]
theorem mul_mul_mul_comm (a b c d : G) : (a * b) * (c * d) = (a * c) * (b * d) :=
by simp only [mul_left_comm, mul_assoc]
end comm_semigroup
local attribute [simp] mul_assoc sub_eq_add_neg
section add_monoid
variables {M : Type u} [add_monoid M] {a b c : M}
@[simp] lemma bit0_zero : bit0 (0 : M) = 0 := add_zero _
@[simp] lemma bit1_zero [has_one M] : bit1 (0 : M) = 1 :=
by rw [bit1, bit0_zero, zero_add]
end add_monoid
section comm_monoid
variables {M : Type u} [comm_monoid M] {x y z : M}
@[to_additive] lemma inv_unique (hy : x * y = 1) (hz : x * z = 1) : y = z :=
left_inv_eq_right_inv (trans (mul_comm _ _) hy) hz
end comm_monoid
section left_cancel_monoid
variables {M : Type u} [left_cancel_monoid M] {a b : M}
@[simp, to_additive] lemma mul_eq_left_iff : a * b = a ↔ b = 1 :=
calc a * b = a ↔ a * b = a * 1 : by rw mul_one
... ↔ b = 1 : mul_left_cancel_iff
@[simp, to_additive] lemma left_eq_mul_iff : a = a * b ↔ b = 1 :=
eq_comm.trans mul_eq_left_iff
end left_cancel_monoid
section right_cancel_monoid
variables {M : Type u} [right_cancel_monoid M] {a b : M}
@[simp, to_additive] lemma mul_eq_right_iff : a * b = b ↔ a = 1 :=
calc a * b = b ↔ a * b = 1 * b : by rw one_mul
... ↔ a = 1 : mul_right_cancel_iff
@[simp, to_additive] lemma right_eq_mul_iff : b = a * b ↔ a = 1 :=
eq_comm.trans mul_eq_right_iff
end right_cancel_monoid
section div_inv_monoid
-- TODO: in a later PR, this `group G` instance will become `div_inv_monoid`
variables {G : Type u} [group G]
@[to_additive]
lemma group.inv_eq_one_div (x : G) :
x⁻¹ = 1 / x :=
by rw [group.div_eq_mul_inv, one_mul]
@[to_additive]
lemma group.mul_one_div (x y : G) :
x * (1 / y) = x / y :=
by rw [group.div_eq_mul_inv, one_mul, group.div_eq_mul_inv]
end div_inv_monoid
section group
variables {G : Type u} [group G] {a b c : G}
@[simp, to_additive]
lemma inv_mul_cancel_right (a b : G) : a * b⁻¹ * b = a :=
by simp [mul_assoc]
@[simp, to_additive neg_zero]
lemma one_inv : 1⁻¹ = (1 : G) :=
inv_eq_of_mul_eq_one (one_mul 1)
@[to_additive]
theorem left_inverse_inv (G) [group G] :
function.left_inverse (λ a : G, a⁻¹) (λ a, a⁻¹) :=
inv_inv
@[simp, to_additive]
lemma inv_involutive : function.involutive (has_inv.inv : G → G) := inv_inv
@[to_additive]
lemma inv_injective : function.injective (has_inv.inv : G → G) :=
inv_involutive.injective
@[simp, to_additive] theorem inv_inj : a⁻¹ = b⁻¹ ↔ a = b := inv_injective.eq_iff
@[simp, to_additive]
lemma mul_inv_cancel_left (a b : G) : a * (a⁻¹ * b) = b :=
by rw [← mul_assoc, mul_right_inv, one_mul]
@[to_additive]
theorem mul_left_surjective (a : G) : function.surjective ((*) a) :=
λ x, ⟨a⁻¹ * x, mul_inv_cancel_left a x⟩
@[to_additive]
theorem mul_right_surjective (a : G) : function.surjective (λ x, x * a) :=
λ x, ⟨x * a⁻¹, inv_mul_cancel_right x a⟩
@[simp, to_additive neg_add_rev]
lemma mul_inv_rev (a b : G) : (a * b)⁻¹ = b⁻¹ * a⁻¹ :=
inv_eq_of_mul_eq_one $ by simp
@[to_additive]
lemma eq_inv_of_eq_inv (h : a = b⁻¹) : b = a⁻¹ :=
by simp [h]
@[to_additive]
lemma eq_inv_of_mul_eq_one (h : a * b = 1) : a = b⁻¹ :=
have a⁻¹ = b, from inv_eq_of_mul_eq_one h,
by simp [this.symm]
@[to_additive]
lemma eq_mul_inv_of_mul_eq (h : a * c = b) : a = b * c⁻¹ :=
by simp [h.symm]
@[to_additive]
lemma eq_inv_mul_of_mul_eq (h : b * a = c) : a = b⁻¹ * c :=
by simp [h.symm]
@[to_additive]
lemma inv_mul_eq_of_eq_mul (h : b = a * c) : a⁻¹ * b = c :=
by simp [h]
@[to_additive]
lemma mul_inv_eq_of_eq_mul (h : a = c * b) : a * b⁻¹ = c :=
by simp [h]
@[to_additive]
lemma eq_mul_of_mul_inv_eq (h : a * c⁻¹ = b) : a = b * c :=
by simp [h.symm]
@[to_additive]
lemma eq_mul_of_inv_mul_eq (h : b⁻¹ * a = c) : a = b * c :=
by simp [h.symm, mul_inv_cancel_left]
@[to_additive]
lemma mul_eq_of_eq_inv_mul (h : b = a⁻¹ * c) : a * b = c :=
by rw [h, mul_inv_cancel_left]
@[to_additive]
lemma mul_eq_of_eq_mul_inv (h : a = c * b⁻¹) : a * b = c :=
by simp [h]
@[to_additive]
theorem mul_self_iff_eq_one : a * a = a ↔ a = 1 :=
by have := @mul_right_inj _ _ a a 1; rwa mul_one at this
@[simp, to_additive]
theorem inv_eq_one : a⁻¹ = 1 ↔ a = 1 :=
by rw [← @inv_inj _ _ a 1, one_inv]
@[simp, to_additive]
theorem one_eq_inv : 1 = a⁻¹ ↔ a = 1 :=
by rw [eq_comm, inv_eq_one]
@[to_additive]
theorem inv_ne_one : a⁻¹ ≠ 1 ↔ a ≠ 1 :=
not_congr inv_eq_one
@[to_additive]
theorem eq_inv_iff_eq_inv : a = b⁻¹ ↔ b = a⁻¹ :=
⟨eq_inv_of_eq_inv, eq_inv_of_eq_inv⟩
@[to_additive]
theorem inv_eq_iff_inv_eq : a⁻¹ = b ↔ b⁻¹ = a :=
eq_comm.trans $ eq_inv_iff_eq_inv.trans eq_comm
@[to_additive]
theorem mul_eq_one_iff_eq_inv : a * b = 1 ↔ a = b⁻¹ :=
by simpa [mul_left_inv, -mul_left_inj] using @mul_left_inj _ _ b a (b⁻¹)
@[to_additive]
theorem mul_eq_one_iff_inv_eq : a * b = 1 ↔ a⁻¹ = b :=
by rw [mul_eq_one_iff_eq_inv, eq_inv_iff_eq_inv, eq_comm]
@[to_additive]
theorem eq_inv_iff_mul_eq_one : a = b⁻¹ ↔ a * b = 1 :=
mul_eq_one_iff_eq_inv.symm
@[to_additive]
theorem inv_eq_iff_mul_eq_one : a⁻¹ = b ↔ a * b = 1 :=
mul_eq_one_iff_inv_eq.symm
@[to_additive]
theorem eq_mul_inv_iff_mul_eq : a = b * c⁻¹ ↔ a * c = b :=
⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩
@[to_additive]
theorem eq_inv_mul_iff_mul_eq : a = b⁻¹ * c ↔ b * a = c :=
⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩
@[to_additive]
theorem inv_mul_eq_iff_eq_mul : a⁻¹ * b = c ↔ b = a * c :=
⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩
@[to_additive]
theorem mul_inv_eq_iff_eq_mul : a * b⁻¹ = c ↔ a = c * b :=
⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩
@[to_additive]
theorem mul_inv_eq_one : a * b⁻¹ = 1 ↔ a = b :=
by rw [mul_eq_one_iff_eq_inv, inv_inv]
@[to_additive]
theorem inv_mul_eq_one : a⁻¹ * b = 1 ↔ a = b :=
by rw [mul_eq_one_iff_eq_inv, inv_inj]
@[simp, to_additive]
lemma mul_left_eq_self : a * b = b ↔ a = 1 :=
⟨λ h, @mul_right_cancel _ _ a b 1 (by simp [h]), λ h, by simp [h]⟩
@[simp, to_additive]
lemma mul_right_eq_self : a * b = a ↔ b = 1 :=
⟨λ h, @mul_left_cancel _ _ a b 1 (by simp [h]), λ h, by simp [h]⟩
@[to_additive]
lemma div_left_injective : function.injective (λ a, a / b) :=
by simpa only [group.div_eq_mul_inv] using λ a a' h, mul_left_injective (b⁻¹) h
@[to_additive]
lemma div_right_injective : function.injective (λ a, b / a) :=
by simpa only [group.div_eq_mul_inv] using λ a a' h, inv_injective (mul_right_injective b h)
end group
section add_group
variables {G : Type u} [add_group G] {a b c d : G}
@[simp] lemma sub_self (a : G) : a - a = 0 :=
by rw [sub_eq_add_neg, add_right_neg a]
@[simp] lemma sub_add_cancel (a b : G) : a - b + b = a :=
by rw [sub_eq_add_neg, neg_add_cancel_right a b]
@[simp] lemma add_sub_cancel (a b : G) : a + b - b = a :=
by rw [sub_eq_add_neg, add_neg_cancel_right a b]
lemma add_sub_assoc (a b c : G) : a + b - c = a + (b - c) :=
by rw [sub_eq_add_neg, add_assoc, ←sub_eq_add_neg]
lemma eq_of_sub_eq_zero (h : a - b = 0) : a = b :=
have 0 + b = b, by rw zero_add,
have (a - b) + b = b, by rwa h,
by rwa [sub_eq_add_neg, neg_add_cancel_right] at this
lemma sub_eq_zero_of_eq (h : a = b) : a - b = 0 :=
by rw [h, sub_self]
lemma sub_eq_zero_iff_eq : a - b = 0 ↔ a = b :=
⟨eq_of_sub_eq_zero, sub_eq_zero_of_eq⟩
@[simp] lemma zero_sub (a : G) : 0 - a = -a :=
by rw [sub_eq_add_neg, zero_add (-a)]
@[simp] lemma sub_zero (a : G) : a - 0 = a :=
by rw [sub_eq_add_neg, neg_zero, add_zero]
lemma sub_ne_zero_of_ne (h : a ≠ b) : a - b ≠ 0 :=
begin
intro hab,
apply h,
apply eq_of_sub_eq_zero hab
end
@[simp] lemma sub_neg_eq_add (a b : G) : a - (-b) = a + b :=
by rw [sub_eq_add_neg, neg_neg]
@[simp] lemma neg_sub (a b : G) : -(a - b) = b - a :=
neg_eq_of_add_eq_zero (by rw [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left,
add_right_neg])
local attribute [simp] add_assoc
lemma add_sub (a b c : G) : a + (b - c) = a + b - c :=
by simp
lemma sub_add_eq_sub_sub_swap (a b c : G) : a - (b + c) = a - c - b :=
by simp
@[simp] lemma add_sub_add_right_eq_sub (a b c : G) : (a + c) - (b + c) = a - b :=
by rw [sub_add_eq_sub_sub_swap]; simp
lemma eq_sub_of_add_eq (h : a + c = b) : a = b - c :=
by simp [h.symm]
lemma sub_eq_of_eq_add (h : a = c + b) : a - b = c :=
by simp [h]
lemma eq_add_of_sub_eq (h : a - c = b) : a = b + c :=
by simp [h.symm]
lemma add_eq_of_eq_sub (h : a = c - b) : a + b = c :=
by simp [h]
@[simp] lemma sub_right_inj : a - b = a - c ↔ b = c :=
sub_right_injective.eq_iff
@[simp] lemma sub_left_inj : b - a = c - a ↔ b = c :=
by { rw [sub_eq_add_neg, sub_eq_add_neg], exact add_left_inj _ }
lemma sub_add_sub_cancel (a b c : G) : (a - b) + (b - c) = a - c :=
by rw [← add_sub_assoc, sub_add_cancel]
lemma sub_sub_sub_cancel_right (a b c : G) : (a - c) - (b - c) = a - b :=
by rw [← neg_sub c b, sub_neg_eq_add, sub_add_sub_cancel]
theorem sub_sub_assoc_swap : a - (b - c) = a + c - b :=
by simp
theorem sub_eq_zero : a - b = 0 ↔ a = b :=
⟨eq_of_sub_eq_zero, λ h, by rw [h, sub_self]⟩
theorem sub_ne_zero : a - b ≠ 0 ↔ a ≠ b :=
not_congr sub_eq_zero
theorem eq_sub_iff_add_eq : a = b - c ↔ a + c = b :=
by rw [sub_eq_add_neg, eq_add_neg_iff_add_eq]
theorem sub_eq_iff_eq_add : a - b = c ↔ a = c + b :=
by rw [sub_eq_add_neg, add_neg_eq_iff_eq_add]
theorem eq_iff_eq_of_sub_eq_sub (H : a - b = c - d) : a = b ↔ c = d :=
by rw [← sub_eq_zero, H, sub_eq_zero]
theorem left_inverse_sub_add_left (c : G) : function.left_inverse (λ x, x - c) (λ x, x + c) :=
assume x, add_sub_cancel x c
theorem left_inverse_add_left_sub (c : G) : function.left_inverse (λ x, x + c) (λ x, x - c) :=
assume x, sub_add_cancel x c
theorem left_inverse_add_right_neg_add (c : G) :
function.left_inverse (λ x, c + x) (λ x, - c + x) :=
assume x, add_neg_cancel_left c x
theorem left_inverse_neg_add_add_right (c : G) :
function.left_inverse (λ x, - c + x) (λ x, c + x) :=
assume x, neg_add_cancel_left c x
end add_group
section comm_group
variables {G : Type u} [comm_group G]
@[to_additive neg_add]
lemma mul_inv (a b : G) : (a * b)⁻¹ = a⁻¹ * b⁻¹ :=
by rw [mul_inv_rev, mul_comm]
end comm_group
section add_comm_group
variables {G : Type u} [add_comm_group G] {a b c d : G}
local attribute [simp] add_assoc add_comm add_left_comm sub_eq_add_neg
lemma sub_add_eq_sub_sub (a b c : G) : a - (b + c) = a - b - c :=
by simp
lemma neg_add_eq_sub (a b : G) : -a + b = b - a :=
by simp
lemma sub_add_eq_add_sub (a b c : G) : a - b + c = a + c - b :=
by simp
lemma sub_sub (a b c : G) : a - b - c = a - (b + c) :=
by simp
lemma sub_add (a b c : G) : a - b + c = a - (b - c) :=
by simp
@[simp] lemma add_sub_add_left_eq_sub (a b c : G) : (c + a) - (c + b) = a - b :=
by simp
lemma eq_sub_of_add_eq' (h : c + a = b) : a = b - c :=
by simp [h.symm]
lemma sub_eq_of_eq_add' (h : a = b + c) : a - b = c :=
begin simp [h], rw [add_left_comm], simp end
lemma eq_add_of_sub_eq' (h : a - b = c) : a = b + c :=
by simp [h.symm]
lemma add_eq_of_eq_sub' (h : b = c - a) : a + b = c :=
begin simp [h], rw [add_comm c, add_neg_cancel_left] end
lemma sub_sub_self (a b : G) : a - (a - b) = b :=
begin simp, rw [add_comm b, add_neg_cancel_left] end
lemma add_sub_comm (a b c d : G) : a + b - (c + d) = (a - c) + (b - d) :=
by simp
lemma sub_eq_sub_add_sub (a b c : G) : a - b = c - b + (a - c) :=
begin simp, rw [add_left_comm c], simp end
lemma neg_neg_sub_neg (a b : G) : - (-a - -b) = a - b :=
by simp
@[simp] lemma sub_sub_cancel (a b : G) : a - (a - b) = b := sub_sub_self a b
lemma sub_eq_neg_add (a b : G) : a - b = -b + a :=
by rw [sub_eq_add_neg, add_comm _ _]
theorem neg_add' (a b : G) : -(a + b) = -a - b :=
by rw [sub_eq_add_neg, neg_add a b]
@[simp]
lemma neg_sub_neg (a b : G) : -a - -b = b - a :=
by simp [sub_eq_neg_add, add_comm]
lemma eq_sub_iff_add_eq' : a = b - c ↔ c + a = b :=
by rw [eq_sub_iff_add_eq, add_comm]
lemma sub_eq_iff_eq_add' : a - b = c ↔ a = b + c :=
by rw [sub_eq_iff_eq_add, add_comm]
@[simp]
lemma add_sub_cancel' (a b : G) : a + b - a = b :=
by rw [sub_eq_neg_add, neg_add_cancel_left]
@[simp]
lemma add_sub_cancel'_right (a b : G) : a + (b - a) = b :=
by rw [← add_sub_assoc, add_sub_cancel']
-- This lemma is in the `simp` set under the name `add_neg_cancel_comm_assoc`,
-- defined in `algebra/group/commute`
lemma add_add_neg_cancel'_right (a b : G) : a + (b + -a) = b :=
by rw [← sub_eq_add_neg, add_sub_cancel'_right a b]
lemma sub_right_comm (a b c : G) : a - b - c = a - c - b :=
by { repeat { rw sub_eq_add_neg }, exact add_right_comm _ _ _ }
@[simp] lemma add_add_sub_cancel (a b c : G) : (a + c) + (b - c) = a + b :=
by rw [add_assoc, add_sub_cancel'_right]
@[simp] lemma sub_add_add_cancel (a b c : G) : (a - c) + (b + c) = a + b :=
by rw [add_left_comm, sub_add_cancel, add_comm]
@[simp] lemma sub_add_sub_cancel' (a b c : G) : (a - b) + (c - a) = c - b :=
by rw add_comm; apply sub_add_sub_cancel
@[simp] lemma add_sub_sub_cancel (a b c : G) : (a + b) - (a - c) = b + c :=
by rw [← sub_add, add_sub_cancel']
@[simp] lemma sub_sub_sub_cancel_left (a b c : G) : (c - a) - (c - b) = b - a :=
by rw [← neg_sub b c, sub_neg_eq_add, add_comm, sub_add_sub_cancel]
lemma sub_eq_sub_iff_add_eq_add : a - b = c - d ↔ a + d = c + b :=
begin
rw [sub_eq_iff_eq_add, sub_add_eq_add_sub, eq_comm, sub_eq_iff_eq_add'],
simp only [add_comm, eq_comm]
end
lemma sub_eq_sub_iff_sub_eq_sub : a - b = c - d ↔ a - c = b - d :=
by simp [-sub_eq_add_neg, sub_eq_sub_iff_add_eq_add, add_comm]
end add_comm_group
|
2ebff48b0828c65fa38e8f171cf01d30a9f7ae26 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Init/Control/Except.lean | 6ade8de1d8b6bc7e0dd87399bad6e958e969ffa6 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 6,891 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jared Roesch, Sebastian Ullrich
The Except monad transformer.
-/
prelude
import Init.Control.Basic
import Init.Control.Id
import Init.Coe
namespace Except
variable {ε : Type u}
@[inline] protected def pure (a : α) : Except ε α :=
Except.ok a
@[inline] protected def map (f : α → β) : Except ε α → Except ε β
| Except.error err => Except.error err
| Except.ok v => Except.ok <| f v
@[simp] theorem map_id : Except.map (ε := ε) (α := α) (β := α) id = id := by
apply funext
intro e
simp [Except.map]; cases e <;> rfl
@[inline] protected def mapError (f : ε → ε') : Except ε α → Except ε' α
| Except.error err => Except.error <| f err
| Except.ok v => Except.ok v
@[inline] protected def bind (ma : Except ε α) (f : α → Except ε β) : Except ε β :=
match ma with
| Except.error err => Except.error err
| Except.ok v => f v
/-- Returns true if the value is `Except.ok`, false otherwise. -/
@[inline] protected def toBool : Except ε α → Bool
| Except.ok _ => true
| Except.error _ => false
abbrev isOk : Except ε α → Bool := Except.toBool
@[inline] protected def toOption : Except ε α → Option α
| Except.ok a => some a
| Except.error _ => none
@[inline] protected def tryCatch (ma : Except ε α) (handle : ε → Except ε α) : Except ε α :=
match ma with
| Except.ok a => Except.ok a
| Except.error e => handle e
def orElseLazy (x : Except ε α) (y : Unit → Except ε α) : Except ε α :=
match x with
| Except.ok a => Except.ok a
| Except.error _ => y ()
instance : Monad (Except ε) where
pure := Except.pure
bind := Except.bind
map := Except.map
end Except
def ExceptT (ε : Type u) (m : Type u → Type v) (α : Type u) : Type v :=
m (Except ε α)
@[inline] def ExceptT.mk {ε : Type u} {m : Type u → Type v} {α : Type u} (x : m (Except ε α)) : ExceptT ε m α := x
@[inline] def ExceptT.run {ε : Type u} {m : Type u → Type v} {α : Type u} (x : ExceptT ε m α) : m (Except ε α) := x
namespace ExceptT
variable {ε : Type u} {m : Type u → Type v} [Monad m]
@[inline] protected def pure {α : Type u} (a : α) : ExceptT ε m α :=
ExceptT.mk <| pure (Except.ok a)
@[inline] protected def bindCont {α β : Type u} (f : α → ExceptT ε m β) : Except ε α → m (Except ε β)
| Except.ok a => f a
| Except.error e => pure (Except.error e)
@[inline] protected def bind {α β : Type u} (ma : ExceptT ε m α) (f : α → ExceptT ε m β) : ExceptT ε m β :=
ExceptT.mk <| ma >>= ExceptT.bindCont f
@[inline] protected def map {α β : Type u} (f : α → β) (x : ExceptT ε m α) : ExceptT ε m β :=
ExceptT.mk <| x >>= fun a => match a with
| (Except.ok a) => pure <| Except.ok (f a)
| (Except.error e) => pure <| Except.error e
@[inline] protected def lift {α : Type u} (t : m α) : ExceptT ε m α :=
ExceptT.mk <| Except.ok <$> t
instance : MonadLift (Except ε) (ExceptT ε m) := ⟨fun e => ExceptT.mk <| pure e⟩
instance : MonadLift m (ExceptT ε m) := ⟨ExceptT.lift⟩
@[inline] protected def tryCatch {α : Type u} (ma : ExceptT ε m α) (handle : ε → ExceptT ε m α) : ExceptT ε m α :=
ExceptT.mk <| ma >>= fun res => match res with
| Except.ok a => pure (Except.ok a)
| Except.error e => (handle e)
instance : MonadFunctor m (ExceptT ε m) := ⟨fun f x => f x⟩
instance : Monad (ExceptT ε m) where
pure := ExceptT.pure
bind := ExceptT.bind
map := ExceptT.map
@[inline] protected def adapt {ε' α : Type u} (f : ε → ε') : ExceptT ε m α → ExceptT ε' m α := fun x =>
ExceptT.mk <| Except.mapError f <$> x
end ExceptT
instance (m : Type u → Type v) (ε₁ : Type u) (ε₂ : Type u) [Monad m] [MonadExceptOf ε₁ m] : MonadExceptOf ε₁ (ExceptT ε₂ m) where
throw e := ExceptT.mk <| throwThe ε₁ e
tryCatch x handle := ExceptT.mk <| tryCatchThe ε₁ x handle
instance (m : Type u → Type v) (ε : Type u) [Monad m] : MonadExceptOf ε (ExceptT ε m) where
throw e := ExceptT.mk <| pure (Except.error e)
tryCatch := ExceptT.tryCatch
instance [Monad m] [Inhabited ε] : Inhabited (ExceptT ε m α) where
default := throw default
instance (ε) : MonadExceptOf ε (Except ε) where
throw := Except.error
tryCatch := Except.tryCatch
namespace MonadExcept
variable {ε : Type u} {m : Type v → Type w}
/-- Alternative orelse operator that allows to select which exception should be used.
The default is to use the first exception since the standard `orelse` uses the second. -/
@[inline] def orelse' [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) (useFirstEx := true) : m α :=
tryCatch t₁ fun e₁ => tryCatch t₂ fun e₂ => throw (if useFirstEx then e₁ else e₂)
end MonadExcept
@[inline] def observing {ε α : Type u} {m : Type u → Type v} [Monad m] [MonadExcept ε m] (x : m α) : m (Except ε α) :=
tryCatch (do let a ← x; pure (Except.ok a)) (fun ex => pure (Except.error ex))
def liftExcept [MonadExceptOf ε m] [Pure m] : Except ε α → m α
| Except.ok a => pure a
| Except.error e => throw e
instance (ε : Type u) (m : Type u → Type v) [Monad m] : MonadControl m (ExceptT ε m) where
stM := Except ε
liftWith f := liftM <| f fun x => x.run
restoreM x := x
class MonadFinally (m : Type u → Type v) where
/-- `tryFinally' x f` runs `x` and then the "finally" computation `f`.
When `x` succeeds with `a : α`, `f (some a)` is returned. If `x` fails
for `m`'s definition of failure, `f none` is returned. Hence `tryFinally'`
can be thought of as performing the same role as a `finally` block in
an imperative programming language. -/
tryFinally' {α β} : m α → (Option α → m β) → m (α × β)
export MonadFinally (tryFinally')
/-- Execute `x` and then execute `finalizer` even if `x` threw an exception -/
@[inline] def tryFinally {m : Type u → Type v} {α β : Type u} [MonadFinally m] [Functor m] (x : m α) (finalizer : m β) : m α :=
let y := tryFinally' x (fun _ => finalizer)
(·.1) <$> y
instance Id.finally : MonadFinally Id where
tryFinally' := fun x h =>
let a := x
let b := h (some x)
pure (a, b)
instance ExceptT.finally {m : Type u → Type v} {ε : Type u} [MonadFinally m] [Monad m] : MonadFinally (ExceptT ε m) where
tryFinally' := fun x h => ExceptT.mk do
let r ← tryFinally' x fun e? => match e? with
| some (Except.ok a) => h (some a)
| _ => h none
match r with
| (Except.ok a, Except.ok b) => pure (Except.ok (a, b))
| (_, Except.error e) => pure (Except.error e) -- second error has precedence
| (Except.error e, _) => pure (Except.error e)
|
eb21af976cdc36c677eb246dad0e5472cd50d6bb | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/computedFields.lean | c67f895da1dcb3001cf3323b22ca5f80a2732276 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,163 | lean | inductive Exp
| hole
| var (i : UInt32)
| app (a b : Exp)
with
/-- Computes the hash -/ @[simp, computed_field] protected hash : Exp → UInt64
| .var i => Hashable.hash i
| .app a b => mixHash a.hash b.hash
| .hole => 32
def dagLikeTerm : Nat → Exp
| 0 => .app (.var 42) .hole
| n+1 => .app (dagLikeTerm n) (dagLikeTerm n)
#eval (dagLikeTerm 1000).hash -- memoized
def varNum? : Exp → Option UInt32
| .var i => i
| _ => none
example : varNum? (.var 32) = some 32 := by native_decide
namespace WithIndices
inductive B.C (α : Type u) : Nat → Type u
| a : C α 0
| b (c : C α n) {d : C α (n-1)} : C α (n+1)
with
@[computed_field] hash : ∀ α i, C α i → UInt64
| _, _, .a => 1
| _, _, .b c => 42 + c.hash
#eval (B.C.b (α := Nat) (.a) (d := .a)).hash
end WithIndices
namespace Mutual
mutual
inductive A
| a (b : B)
| b (b : B)
with
@[computed_field] f : A → Nat
| .a c => 32 + c.f
| .b c => 42 + 2*c.f
inductive B
| c (a : A)
| d
with
@[computed_field] f : B → Nat
| .c a => a.f
| .d => 0
end
#eval (B.c (.a .d)).f
end Mutual
|
d1ec501cf8fc6af455012e1b9d7de7ad6fbaed48 | 6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf | /src/game/world2/level6.lean | 2942ad1c59bdb2dcc205e0fa11b71037a52f50b6 | [
"Apache-2.0"
] | permissive | arolihas/natural_number_game | 4f0c93feefec93b8824b2b96adff8b702b8b43ce | 8e4f7b4b42888a3b77429f90cce16292bd288138 | refs/heads/master | 1,621,872,426,808 | 1,586,270,467,000 | 1,586,270,467,000 | 253,648,466 | 0 | 0 | null | 1,586,219,694,000 | 1,586,219,694,000 | null | UTF-8 | Lean | false | false | 4,878 | lean | import mynat.definition -- hide
import mynat.add -- hide
import game.world2.level5 -- hide
import tactic.ring -- hide
namespace mynat -- hide
/-
# Addition World
## Level 6: `add_right_comm`
Lean sometimes writes `a + b + c`. What does it mean? The convention is
that if there are no brackets displayed in an addition formula, the brackets
are around the left most `+` (Lean's addition is "left associative").
So the goal in this level is `(a + b) + c = (a + c) + b`. This isn't
quite `add_assoc` or `add_comm`, it's something you'll have to prove
by putting these two theorems together.
If you hadn't picked up on this already, `rw add_assoc` will
change `(x + y) + z` to `x + (y + z)`, but to change it back
you will need `rw ← add_assoc`. Get the left arrow by typing `\l`
then the space bar.
Similarly, if `h : a = b` then `rw h` will change `a`'s to `b`'s
and `rw ← h` will change `b`'s to `a`'s.
Also, you can be (and will need to be, in this level) more precise
about where to rewrite theorems. `rw add_comm,` will just find the
first `? + ?` it sees and swap it around. You can target more specific
additions like this: `rw add_comm a` will swap around
additions of the form `a + ?`, and `rw add_comm a b,` will only
swap additions of the form `a + b`.
## Where next?
There are thirteen more levels about addition after this one, but before
you can attempt them you need to learn some more tactics. So after this
level you have a choice -- either move on to Multiplication World (which you can
solve with the tactics you know) or try Function World (and learn some new ones).
After solving this level, click "Main Menu" in the top left to take you back
to the overworld, and make your choice. Other things, perhaps of interest
to some players, are mentioned below the lemma.
-/
/- Lemma
For all natural numbers $a, b$ and $c$, we have
$$ a + b + c = a + c + b. $$
-/
lemma add_right_comm (a b c : mynat) : a + b + c = a + c + b :=
begin [nat_num_game]
end
/-
If you have got this far, then you have become very good at
manipulating equalities in Lean. You can also now collect
four collectibles (or `instance`s, as Lean calls them)
```
mynat.add_semigroup -- (after level 2)
mynat.add_monoid -- (after level 2)
mynat.add_comm_semigroup mynat (after level 4)
mynat.add_comm_monoid -- (after level 4)
```
In Multiplication World you will be able to collect such
advanced collectibles as `mynat.comm_semiring` and
`mynat.distrib`, and then move on to power world and
the famous collectible at the end of it.
One last thing -- didn't you think that solving this level
`add_right_comm` was boring? Check out this AI that can do it for us.
First we have to get the `add_comm_monoid` collectible,
which we do by saying the magic words which make Lean's type class inference
system give it to us.
-/
instance : add_comm_monoid mynat := by structure_helper
/-
Now the `simp` AI becomes accessible (it's just an advanced
tactic really), and can nail some really tedious-for-a-human-to-solve
goals. For example check out this one-line proof:
-/
example (a b c d e : mynat) :
(((a+b)+c)+d)+e=(c+((b+e)+a))+d := begin
simp
end
/-
Imagine having to do that one by hand! The AI closes the goal
because it knows how to use associativity and commutativity
sensibly in a commutative monoid.
You are now done with addition world. Go back to the main menu (top left)
and decide whether to press on with multiplication world and power world
(which can be solved with `rw`, `refl` and `induction`), or to go on
to Function World where you can learn the tactics needed to prove
goals of the form $P\implies Q$, thus enabling you to solve more
advanced addition world levels such as $a+t=b+t\implies a=b$. Note that
Function World is more challenging mathematically; but if you can do Addition
World you can surely do Multiplication World and Power World.
-/
end mynat -- hide
/- Tactic : simp
## Summary
The `simp` tactic is a high-level tactic which tries
to prove equalities using facts in its database (such
as `add_assoc` and `add_comm`).
## Details
The `simp` tactic does basic automation. By level 6 of
Addition World you
have proved enough about addition for `simp` to be able
to solve all equalities whose proofs involve a tedious number
of rewrites of `add_assoc` and `add_comm`, and by
level 9 of Multiplication World the same is true of `mul_assoc` and `mul_comm`.
### Example:
If our goal is this:
```
⊢ a + b + c + d + e = c + (b + e + a) + d
```
and you have completed addition world, then you've proved
enough about addition to solve this level with `simp`.
Note however that you can't prove `add_assoc` with `simp`,
because `add_assoc` is an ingredient to get `simp` working.
### Example:
If our goal is this:
```
⊢ a * b * c = c * b * a
```
then as long as you've completed Multiplication World, `simp` will close this
goal.
-/
|
7b277f8be6ceccf14c7084a2a0d0104c02a0c816 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/order/filter/ennreal.lean | c96d3769bdab9099f01818264bc7c258d6f6b7f5 | [
"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 | 4,482 | 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 data.real.ennreal
import order.filter.countable_Inter
import order.liminf_limsup
/-!
# Order properties of extended non-negative reals
This file compiles filter-related results about `ℝ≥0∞` (see data/real/ennreal.lean).
-/
open filter
open_locale filter ennreal
namespace ennreal
variables {α : Type*} {f : filter α}
lemma eventually_le_limsup [countable_Inter_filter f] (u : α → ℝ≥0∞) :
∀ᶠ y in f, u y ≤ f.limsup u :=
begin
by_cases hx_top : f.limsup u = ⊤,
{ simp_rw hx_top,
exact eventually_of_forall (λ a, le_top), },
have h_forall_le : ∀ᶠ y in f, ∀ n : ℕ, u y < f.limsup u + (1:ℝ≥0∞)/n,
{ rw eventually_countable_forall,
refine λ n, eventually_lt_of_limsup_lt _,
nth_rewrite 0 ←add_zero (f.limsup u),
exact (add_lt_add_iff_left hx_top).mpr (by simp), },
refine h_forall_le.mono (λ y hy, le_of_forall_pos_le_add (λ r hr_pos hx_top, _)),
have hr_ne_zero : (r : ℝ≥0∞) ≠ 0,
{ rw [ne.def, coe_eq_zero],
exact (ne_of_lt hr_pos).symm, },
cases (exists_inv_nat_lt hr_ne_zero) with i hi,
rw inv_eq_one_div at hi,
exact le_trans (le_of_lt (hy i)) (add_le_add_left hi.le (f.limsup u)),
end
lemma limsup_eq_zero_iff [countable_Inter_filter f] {u : α → ℝ≥0∞} :
f.limsup u = 0 ↔ u =ᶠ[f] 0 :=
begin
split; intro h,
{ have hu_zero := eventually_le.trans (eventually_le_limsup u)
(eventually_of_forall (λ _, le_of_eq h)),
exact hu_zero.mono (λ x hx, le_antisymm hx (zero_le _)), },
{ rw limsup_congr h,
simp_rw [pi.zero_apply, ←ennreal.bot_eq_zero, limsup_const_bot] },
end
lemma limsup_const_mul_of_ne_top {u : α → ℝ≥0∞} {a : ℝ≥0∞} (ha_top : a ≠ ⊤) :
f.limsup (λ (x : α), a * (u x)) = a * f.limsup u :=
begin
by_cases ha_zero : a = 0,
{ simp_rw [ha_zero, zero_mul, ←ennreal.bot_eq_zero],
exact limsup_const_bot, },
let g := λ x : ℝ≥0∞, a * x,
have hg_bij : function.bijective g,
from function.bijective_iff_has_inverse.mpr ⟨(λ x, a⁻¹ * x),
⟨λ x, by simp [←mul_assoc, inv_mul_cancel ha_zero ha_top],
λ x, by simp [g, ←mul_assoc, mul_inv_cancel ha_zero ha_top]⟩⟩,
have hg_mono : strict_mono g,
from strict_mono_of_monotone_of_injective
(λ _ _ _, by rwa mul_le_mul_left ha_zero ha_top) hg_bij.1,
let g_iso := strict_mono.order_iso_of_surjective g hg_mono hg_bij.2,
refine (order_iso.limsup_apply g_iso _ _ _ _).symm,
all_goals { by is_bounded_default },
end
lemma limsup_const_mul [countable_Inter_filter f] {u : α → ℝ≥0∞} {a : ℝ≥0∞} :
f.limsup (λ (x : α), a * (u x)) = a * f.limsup u :=
begin
by_cases ha_top : a ≠ ⊤,
{ exact limsup_const_mul_of_ne_top ha_top, },
push_neg at ha_top,
by_cases hu : u =ᶠ[f] 0,
{ have hau : (λ x, a * (u x)) =ᶠ[f] 0,
{ refine hu.mono (λ x hx, _),
rw pi.zero_apply at hx,
simp [hx], },
simp only [limsup_congr hu, limsup_congr hau, pi.zero_apply, ← bot_eq_zero, limsup_const_bot],
simp, },
{ simp_rw [ha_top, top_mul],
have hu_mul : ∃ᶠ (x : α) in f, ⊤ ≤ ite (u x = 0) (0 : ℝ≥0∞) ⊤,
{ rw [eventually_eq, not_eventually] at hu,
refine hu.mono (λ x hx, _),
rw pi.zero_apply at hx,
simp [hx], },
have h_top_le : f.limsup (λ (x : α), ite (u x = 0) (0 : ℝ≥0∞) ⊤) = ⊤,
from eq_top_iff.mpr (le_limsup_of_frequently_le hu_mul),
have hfu : f.limsup u ≠ 0, from mt limsup_eq_zero_iff.1 hu,
simp only [h_top_le, hfu, if_false], },
end
lemma limsup_add_le [countable_Inter_filter f] (u v : α → ℝ≥0∞) :
f.limsup (u + v) ≤ f.limsup u + f.limsup v :=
Inf_le ((eventually_le_limsup u).mp ((eventually_le_limsup v).mono
(λ _ hxg hxf, add_le_add hxf hxg)))
lemma limsup_liminf_le_liminf_limsup {β} [encodable β] {f : filter α} [countable_Inter_filter f]
{g : filter β} (u : α → β → ℝ≥0∞) :
f.limsup (λ (a : α), g.liminf (λ (b : β), u a b)) ≤ g.liminf (λ b, f.limsup (λ a, u a b)) :=
begin
have h1 : ∀ᶠ a in f, ∀ b, u a b ≤ f.limsup (λ a', u a' b),
by { rw eventually_countable_forall, exact λ b, ennreal.eventually_le_limsup (λ a, u a b), },
refine Inf_le (h1.mono (λ x hx, filter.liminf_le_liminf (filter.eventually_of_forall hx) _)),
filter.is_bounded_default,
end
end ennreal
|
10318995af73f91bafa8c873865f974e9e17a862 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/list/cycle.lean | 4829da9fa281e5037215b16a958d12afc9380488 | [
"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 | 20,458 | lean | /-
Copyright (c) 2021 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import data.list.rotate
import data.finset.basic
/-!
# Cycles of a list
Lists have an equivalence relation of whether they are rotational permutations of one another.
This relation is defined as `is_rotated`.
Based on this, we define the quotient of lists by the rotation relation, called `cycle`.
-/
namespace list
variables {α : Type*} [decidable_eq α]
/-- Return the `z` such that `x :: z :: _` appears in `xs`, or `default` if there is no such `z`. -/
def next_or : Π (xs : list α) (x default : α), α
| [] x default := default
| [y] x default := default -- Handles the not-found and the wraparound case
| (y :: z :: xs) x default := if x = y then z else next_or (z :: xs) x default
@[simp] lemma next_or_nil (x d : α) : next_or [] x d = d := rfl
@[simp] lemma next_or_singleton (x y d : α) : next_or [y] x d = d := rfl
@[simp] lemma next_or_self_cons_cons (xs : list α) (x y d : α) :
next_or (x :: y :: xs) x d = y :=
if_pos rfl
lemma next_or_cons_of_ne (xs : list α) (y x d : α) (h : x ≠ y) :
next_or (y :: xs) x d = next_or xs x d :=
begin
cases xs with z zs,
{ refl },
{ exact if_neg h }
end
/-- `next_or` does not depend on the default value, if the next value appears. -/
lemma next_or_eq_next_or_of_mem_of_ne (xs : list α) (x d d' : α)
(x_mem : x ∈ xs) (x_ne : x ≠ xs.last (ne_nil_of_mem x_mem)) :
next_or xs x d = next_or xs x d' :=
begin
induction xs with y ys IH,
{ cases x_mem },
cases ys with z zs,
{ simp at x_mem x_ne, contradiction },
by_cases h : x = y,
{ rw [h, next_or_self_cons_cons, next_or_self_cons_cons] },
{ rw [next_or, next_or, IH];
simpa [h] using x_mem }
end
lemma mem_of_next_or_ne {xs : list α} {x d : α} (h : next_or xs x d ≠ d) :
x ∈ xs :=
begin
induction xs with y ys IH,
{ simpa using h },
cases ys with z zs,
{ simpa using h },
{ by_cases hx : x = y,
{ simp [hx] },
{ rw [next_or_cons_of_ne _ _ _ _ hx] at h,
simpa [hx] using IH h } }
end
lemma next_or_concat {xs : list α} {x : α} (d : α) (h : x ∉ xs) :
next_or (xs ++ [x]) x d = d :=
begin
induction xs with z zs IH,
{ simp },
{ obtain ⟨hz, hzs⟩ := not_or_distrib.mp (mt (mem_cons_iff _ _ _).mp h),
rw [cons_append, next_or_cons_of_ne _ _ _ _ hz, IH hzs] }
end
lemma next_or_mem {xs : list α} {x d : α} (hd : d ∈ xs) :
next_or xs x d ∈ xs :=
begin
revert hd,
suffices : ∀ (xs' : list α) (h : ∀ x ∈ xs, x ∈ xs') (hd : d ∈ xs'), next_or xs x d ∈ xs',
{ exact this xs (λ _, id) },
intros xs' hxs' hd,
induction xs with y ys ih,
{ exact hd },
cases ys with z zs,
{ exact hd },
rw next_or,
split_ifs with h,
{ exact hxs' _ (mem_cons_of_mem _ (mem_cons_self _ _)) },
{ exact ih (λ _ h, hxs' _ (mem_cons_of_mem _ h)) },
end
/--
Given an element `x : α` of `l : list α` such that `x ∈ l`, get the next
element of `l`. This works from head to tail, (including a check for last element)
so it will match on first hit, ignoring later duplicates.
For example:
* `next [1, 2, 3] 2 _ = 3`
* `next [1, 2, 3] 3 _ = 1`
* `next [1, 2, 3, 2, 4] 2 _ = 3`
* `next [1, 2, 3, 2] 2 _ = 3`
* `next [1, 1, 2, 3, 2] 1 _ = 1`
-/
def next (l : list α) (x : α) (h : x ∈ l) : α :=
next_or l x (l.nth_le 0 (length_pos_of_mem h))
/--
Given an element `x : α` of `l : list α` such that `x ∈ l`, get the previous
element of `l`. This works from head to tail, (including a check for last element)
so it will match on first hit, ignoring later duplicates.
* `prev [1, 2, 3] 2 _ = 1`
* `prev [1, 2, 3] 1 _ = 3`
* `prev [1, 2, 3, 2, 4] 2 _ = 1`
* `prev [1, 2, 3, 4, 2] 2 _ = 1`
* `prev [1, 1, 2] 1 _ = 2`
-/
def prev : Π (l : list α) (x : α) (h : x ∈ l), α
| [] _ h := by simpa using h
| [y] _ _ := y
| (y :: z :: xs) x h := if hx : x = y then (last (z :: xs) (cons_ne_nil _ _)) else
if x = z then y else prev (z :: xs) x (by simpa [hx] using h)
variables (l : list α) (x : α) (h : x ∈ l)
@[simp] lemma next_singleton (x y : α) (h : x ∈ [y]) :
next [y] x h = y := rfl
@[simp] lemma prev_singleton (x y : α) (h : x ∈ [y]) :
prev [y] x h = y := rfl
lemma next_cons_cons_eq' (y z : α) (h : x ∈ (y :: z :: l)) (hx : x = y) :
next (y :: z :: l) x h = z :=
by rw [next, next_or, if_pos hx]
@[simp] lemma next_cons_cons_eq (z : α) (h : x ∈ (x :: z :: l)) :
next (x :: z :: l) x h = z :=
next_cons_cons_eq' l x x z h rfl
lemma next_ne_head_ne_last (y : α) (h : x ∈ (y :: l)) (hy : x ≠ y)
(hx : x ≠ last (y :: l) (cons_ne_nil _ _)) :
next (y :: l) x h = next l x (by simpa [hy] using h) :=
begin
rw [next, next, next_or_cons_of_ne _ _ _ _ hy, next_or_eq_next_or_of_mem_of_ne],
{ rwa last_cons at hx },
{ simpa [hy] using h }
end
lemma next_cons_concat (y : α) (hy : x ≠ y) (hx : x ∉ l)
(h : x ∈ y :: l ++ [x] := mem_append_right _ (mem_singleton_self x)) :
next (y :: l ++ [x]) x h = y :=
begin
rw [next, next_or_concat],
{ refl },
{ simp [hy, hx] }
end
lemma next_last_cons (y : α) (h : x ∈ (y :: l)) (hy : x ≠ y)
(hx : x = last (y :: l) (cons_ne_nil _ _)) (hl : nodup l) :
next (y :: l) x h = y :=
begin
rw [next, nth_le, ←init_append_last (cons_ne_nil y l), hx, next_or_concat],
subst hx,
intro H,
obtain ⟨_ | k, hk, hk'⟩ := nth_le_of_mem H,
{ simpa [init_eq_take, nth_le_take', hy.symm] using hk' },
suffices : k.succ = l.length,
{ simpa [this] using hk },
cases l with hd tl,
{ simpa using hk },
{ rw nodup_iff_nth_le_inj at hl,
rw [length, nat.succ_inj'],
apply hl,
simpa [init_eq_take, nth_le_take', last_eq_nth_le] using hk' }
end
lemma prev_last_cons' (y : α) (h : x ∈ (y :: l)) (hx : x = y) :
prev (y :: l) x h = last (y :: l) (cons_ne_nil _ _) :=
begin
cases l;
simp [prev, hx]
end
@[simp] lemma prev_last_cons (h : x ∈ (x :: l)) :
prev (x :: l) x h = last (x :: l) (cons_ne_nil _ _) :=
prev_last_cons' l x x h rfl
lemma prev_cons_cons_eq' (y z : α) (h : x ∈ (y :: z :: l)) (hx : x = y) :
prev (y :: z :: l) x h = last (z :: l) (cons_ne_nil _ _) :=
by rw [prev, dif_pos hx]
@[simp] lemma prev_cons_cons_eq (z : α) (h : x ∈ (x :: z :: l)) :
prev (x :: z :: l) x h = last (z :: l) (cons_ne_nil _ _) :=
prev_cons_cons_eq' l x x z h rfl
lemma prev_cons_cons_of_ne' (y z : α) (h : x ∈ (y :: z :: l)) (hy : x ≠ y) (hz : x = z) :
prev (y :: z :: l) x h = y :=
begin
cases l,
{ simp [prev, hy, hz] },
{ rw [prev, dif_neg hy, if_pos hz] }
end
lemma prev_cons_cons_of_ne (y : α) (h : x ∈ (y :: x :: l)) (hy : x ≠ y) :
prev (y :: x :: l) x h = y :=
prev_cons_cons_of_ne' _ _ _ _ _ hy rfl
lemma prev_ne_cons_cons (y z : α) (h : x ∈ (y :: z :: l)) (hy : x ≠ y) (hz : x ≠ z) :
prev (y :: z :: l) x h = prev (z :: l) x (by simpa [hy] using h) :=
begin
cases l,
{ simpa [hy, hz] using h },
{ rw [prev, dif_neg hy, if_neg hz] }
end
include h
lemma next_mem : l.next x h ∈ l :=
next_or_mem (nth_le_mem _ _ _)
lemma prev_mem : l.prev x h ∈ l :=
begin
cases l with hd tl,
{ simpa using h },
induction tl with hd' tl hl generalizing hd,
{ simp },
{ by_cases hx : x = hd,
{ simp only [hx, prev_cons_cons_eq],
exact mem_cons_of_mem _ (last_mem _) },
{ rw [prev, dif_neg hx],
split_ifs with hm,
{ exact mem_cons_self _ _ },
{ exact mem_cons_of_mem _ (hl _ _) } } }
end
lemma next_nth_le (l : list α) (h : nodup l) (n : ℕ) (hn : n < l.length) :
next l (l.nth_le n hn) (nth_le_mem _ _ _) = l.nth_le ((n + 1) % l.length)
(nat.mod_lt _ (n.zero_le.trans_lt hn)) :=
begin
cases l with x l,
{ simpa using hn },
induction l with y l hl generalizing x n,
{ simp },
{ cases n,
{ simp },
{ have hn' : n.succ ≤ l.length.succ,
{ refine nat.succ_le_of_lt _,
simpa [nat.succ_lt_succ_iff] using hn },
have hx': (x :: y :: l).nth_le n.succ hn ≠ x,
{ intro H,
suffices : n.succ = 0,
{ simpa },
rw nodup_iff_nth_le_inj at h,
refine h _ _ hn nat.succ_pos' _,
simpa using H },
rcases hn'.eq_or_lt with hn''|hn'',
{ rw [next_last_cons],
{ simp [hn''] },
{ exact hx' },
{ simp [last_eq_nth_le, hn''] },
{ exact nodup_of_nodup_cons h } },
{ have : n < l.length := by simpa [nat.succ_lt_succ_iff] using hn'' ,
rw [next_ne_head_ne_last _ _ _ _ hx'],
{ simp [nat.mod_eq_of_lt (nat.succ_lt_succ (nat.succ_lt_succ this)),
hl _ _ (nodup_of_nodup_cons h), nat.mod_eq_of_lt (nat.succ_lt_succ this)] },
{ rw last_eq_nth_le,
intro H,
suffices : n.succ = l.length.succ,
{ exact absurd hn'' this.ge.not_lt },
rw nodup_iff_nth_le_inj at h,
refine h _ _ hn _ _,
{ simp },
{ simpa using H } } } } }
end
lemma prev_nth_le (l : list α) (h : nodup l) (n : ℕ) (hn : n < l.length) :
prev l (l.nth_le n hn) (nth_le_mem _ _ _) = l.nth_le ((n + (l.length - 1)) % l.length)
(nat.mod_lt _ (n.zero_le.trans_lt hn)) :=
begin
cases l with x l,
{ simpa using hn },
induction l with y l hl generalizing n x,
{ simp },
{ rcases n with _|_|n,
{ simpa [last_eq_nth_le, nat.mod_eq_of_lt (nat.succ_lt_succ l.length.lt_succ_self)] },
{ simp only [mem_cons_iff, nodup_cons] at h,
push_neg at h,
simp [add_comm, prev_cons_cons_of_ne, h.left.left.symm] },
{ rw [prev_ne_cons_cons],
{ convert hl _ _ (nodup_of_nodup_cons h) _ using 1,
have : ∀ k hk, (y :: l).nth_le k hk = (x :: y :: l).nth_le (k + 1) (nat.succ_lt_succ hk),
{ intros,
simpa },
rw [this],
congr,
simp only [nat.add_succ_sub_one, add_zero, length],
simp only [length, nat.succ_lt_succ_iff] at hn,
set k := l.length,
rw [nat.succ_add, ←nat.add_succ, nat.add_mod_right, nat.succ_add, ←nat.add_succ _ k,
nat.add_mod_right, nat.mod_eq_of_lt, nat.mod_eq_of_lt],
{ exact nat.lt_succ_of_lt hn },
{ exact nat.succ_lt_succ (nat.lt_succ_of_lt hn) } },
{ intro H,
suffices : n.succ.succ = 0,
{ simpa },
rw nodup_iff_nth_le_inj at h,
refine h _ _ hn nat.succ_pos' _,
simpa using H },
{ intro H,
suffices : n.succ.succ = 1,
{ simpa },
rw nodup_iff_nth_le_inj at h,
refine h _ _ hn (nat.succ_lt_succ nat.succ_pos') _,
simpa using H } } }
end
lemma pmap_next_eq_rotate_one (h : nodup l) :
l.pmap l.next (λ _ h, h) = l.rotate 1 :=
begin
apply list.ext_le,
{ simp },
{ intros,
rw [nth_le_pmap, nth_le_rotate, next_nth_le _ h] }
end
lemma pmap_prev_eq_rotate_length_sub_one (h : nodup l) :
l.pmap l.prev (λ _ h, h) = l.rotate (l.length - 1) :=
begin
apply list.ext_le,
{ simp },
{ intros n hn hn',
rw [nth_le_rotate, nth_le_pmap, prev_nth_le _ h] }
end
lemma prev_next (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) :
prev l (next l x hx) (next_mem _ _ _) = x :=
begin
obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx,
simp only [next_nth_le, prev_nth_le, h, nat.mod_add_mod],
cases l with hd tl,
{ simp },
{ have : n < 1 + tl.length := by simpa [add_comm] using hn,
simp [add_left_comm, add_comm, add_assoc, nat.mod_eq_of_lt this] }
end
lemma next_prev (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) :
next l (prev l x hx) (prev_mem _ _ _) = x :=
begin
obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx,
simp only [next_nth_le, prev_nth_le, h, nat.mod_add_mod],
cases l with hd tl,
{ simp },
{ have : n < 1 + tl.length := by simpa [add_comm] using hn,
simp [add_left_comm, add_comm, add_assoc, nat.mod_eq_of_lt this] }
end
lemma prev_reverse_eq_next (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) :
prev l.reverse x (mem_reverse.mpr hx) = next l x hx :=
begin
obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx,
have lpos : 0 < l.length := k.zero_le.trans_lt hk,
have key : l.length - 1 - k < l.length :=
(nat.sub_le _ _).trans_lt (nat.sub_lt_self lpos nat.succ_pos'),
rw ←nth_le_pmap l.next (λ _ h, h) (by simpa using hk),
simp_rw [←nth_le_reverse l k (key.trans_le (by simp)), pmap_next_eq_rotate_one _ h],
rw ←nth_le_pmap l.reverse.prev (λ _ h, h),
{ simp_rw [pmap_prev_eq_rotate_length_sub_one _ (nodup_reverse.mpr h), rotate_reverse,
length_reverse, nat.mod_eq_of_lt (nat.sub_lt_self lpos nat.succ_pos'),
nat.sub_sub_self (nat.succ_le_of_lt lpos)],
rw ←nth_le_reverse,
{ simp [nat.sub_sub_self (nat.le_pred_of_lt hk)] },
{ simpa using (nat.sub_le _ _).trans_lt (nat.sub_lt_self lpos nat.succ_pos') } },
{ simpa using (nat.sub_le _ _).trans_lt (nat.sub_lt_self lpos nat.succ_pos') }
end
lemma next_reverse_eq_prev (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) :
next l.reverse x (mem_reverse.mpr hx) = prev l x hx :=
begin
convert (prev_reverse_eq_next l.reverse (nodup_reverse.mpr h) x (mem_reverse.mpr hx)).symm,
exact (reverse_reverse l).symm
end
lemma is_rotated_next_eq {l l' : list α} (h : l ~r l') (hn : nodup l) {x : α} (hx : x ∈ l) :
l.next x hx = l'.next x (h.mem_iff.mp hx) :=
begin
obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx,
obtain ⟨n, rfl⟩ := id h,
rw [next_nth_le _ hn],
simp_rw ←nth_le_rotate' _ n k,
rw [next_nth_le _ (h.nodup_iff.mp hn), ←nth_le_rotate' _ n],
simp [add_assoc]
end
lemma is_rotated_prev_eq {l l' : list α} (h : l ~r l') (hn : nodup l) {x : α} (hx : x ∈ l) :
l.prev x hx = l'.prev x (h.mem_iff.mp hx) :=
begin
rw [←next_reverse_eq_prev _ hn, ←next_reverse_eq_prev _ (h.nodup_iff.mp hn)],
exact is_rotated_next_eq h.reverse (nodup_reverse.mpr hn) _
end
end list
open list
/--
`cycle α` is the quotient of `list α` by cyclic permutation.
Duplicates are allowed.
-/
def cycle (α : Type*) : Type* := quotient (is_rotated.setoid α)
namespace cycle
variables {α : Type*}
instance : has_coe (list α) (cycle α) := ⟨quot.mk _⟩
@[simp] lemma coe_eq_coe {l₁ l₂ : list α} : (l₁ : cycle α) = l₂ ↔ (l₁ ~r l₂) :=
@quotient.eq _ (is_rotated.setoid _) _ _
@[simp] lemma mk_eq_coe (l : list α) :
quot.mk _ l = (l : cycle α) := rfl
@[simp] lemma mk'_eq_coe (l : list α) :
quotient.mk' l = (l : cycle α) := rfl
instance : inhabited (cycle α) := ⟨(([] : list α) : cycle α)⟩
/--
For `x : α`, `s : cycle α`, `x ∈ s` indicates that `x` occurs at least once in `s`.
-/
def mem (a : α) (s : cycle α) : Prop :=
quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~r l₂), propext $ e.mem_iff)
instance : has_mem α (cycle α) := ⟨mem⟩
@[simp] lemma mem_coe_iff {a : α} {l : list α} :
a ∈ (l : cycle α) ↔ a ∈ l := iff.rfl
instance [decidable_eq α] : decidable_eq (cycle α) :=
λ s₁ s₂, quotient.rec_on_subsingleton₂' s₁ s₂ (λ l₁ l₂,
decidable_of_iff' _ quotient.eq')
instance [decidable_eq α] (x : α) (s : cycle α) : decidable (x ∈ s) :=
quotient.rec_on_subsingleton' s (λ l, list.decidable_mem x l)
/--
Reverse a `s : cycle α` by reversing the underlying `list`.
-/
def reverse (s : cycle α) : cycle α :=
quot.map reverse (λ l₁ l₂ (e : l₁ ~r l₂), e.reverse) s
@[simp] lemma reverse_coe (l : list α) :
(l : cycle α).reverse = l.reverse := rfl
@[simp] lemma mem_reverse_iff {a : α} {s : cycle α} :
a ∈ s.reverse ↔ a ∈ s :=
quot.induction_on s (λ _, mem_reverse)
@[simp] lemma reverse_reverse (s : cycle α) :
s.reverse.reverse = s :=
quot.induction_on s (λ _, by simp)
/--
The length of the `s : cycle α`, which is the number of elements, counting duplicates.
-/
def length (s : cycle α) : ℕ :=
quot.lift_on s length (λ l₁ l₂ (e : l₁ ~r l₂), e.perm.length_eq)
@[simp] lemma length_coe (l : list α) :
length (l : cycle α) = l.length := rfl
@[simp] lemma length_reverse (s : cycle α) :
s.reverse.length = s.length :=
quot.induction_on s length_reverse
/--
A `s : cycle α` that is at most one element.
-/
def subsingleton (s : cycle α) : Prop :=
s.length ≤ 1
lemma length_subsingleton_iff {s : cycle α} :
subsingleton s ↔ length s ≤ 1 := iff.rfl
@[simp] lemma subsingleton_reverse_iff {s : cycle α} :
s.reverse.subsingleton ↔ s.subsingleton :=
by simp [length_subsingleton_iff]
lemma subsingleton.congr {s : cycle α} (h : subsingleton s) :
∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y :=
begin
induction s using quot.induction_on with l,
simp only [length_subsingleton_iff, length_coe, mk_eq_coe, le_iff_lt_or_eq, nat.lt_add_one_iff,
length_eq_zero, length_eq_one, nat.not_lt_zero, false_or] at h,
rcases h with rfl|⟨z, rfl⟩;
simp
end
/--
A `s : cycle α` that is made up of at least two unique elements.
-/
def nontrivial (s : cycle α) : Prop := ∃ (x y : α) (h : x ≠ y), x ∈ s ∧ y ∈ s
@[simp] lemma nontrivial_reverse_iff {s : cycle α} :
s.reverse.nontrivial ↔ s.nontrivial :=
by simp [nontrivial]
lemma length_nontrivial {s : cycle α} (h : nontrivial s) :
2 ≤ length s :=
begin
obtain ⟨x, y, hxy, hx, hy⟩ := h,
induction s using quot.induction_on with l,
rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩),
{ simpa using hx },
{ simp only [mem_coe_iff, mk_eq_coe, mem_singleton] at hx hy,
simpa [hx, hy] using hxy },
{ simp [bit0] }
end
/--
The `s : cycle α` contains no duplicates.
-/
def nodup (s : cycle α) : Prop :=
quot.lift_on s nodup (λ l₁ l₂ (e : l₁ ~r l₂), propext $ e.nodup_iff)
@[simp] lemma nodup_coe_iff {l : list α} :
nodup (l : cycle α) ↔ l.nodup := iff.rfl
@[simp] lemma nodup_reverse_iff {s : cycle α} :
s.reverse.nodup ↔ s.nodup :=
quot.induction_on s (λ _, nodup_reverse)
lemma subsingleton.nodup {s : cycle α} (h : subsingleton s) :
nodup s :=
begin
induction s using quot.induction_on with l,
cases l with hd tl,
{ simp },
{ have : tl = [] := by simpa [subsingleton, length_eq_zero] using h,
simp [this] }
end
/--
The `s : cycle α` as a `multiset α`.
-/
def to_multiset (s : cycle α) : multiset α :=
quotient.lift_on' s (λ l, (l : multiset α)) (λ l₁ l₂ (h : l₁ ~r l₂), multiset.coe_eq_coe.mpr h.perm)
section decidable
variable [decidable_eq α]
instance {s : cycle α} : decidable (nodup s) :=
quot.rec_on_subsingleton s (λ (l : list α), list.nodup_decidable l)
/--
The `s : cycle α` as a `finset α`.
-/
def to_finset (s : cycle α) : finset α :=
s.to_multiset.to_finset
/-- Given a `s : cycle α` such that `nodup s`, retrieve the next element after `x ∈ s`. -/
def next : Π (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s), α :=
λ s, quot.hrec_on s (λ l hn x hx, next l x hx)
(λ l₁ l₂ (h : l₁ ~r l₂),
function.hfunext (propext h.nodup_iff) (λ h₁ h₂ he, function.hfunext rfl
(λ x y hxy, function.hfunext (propext (by simpa [eq_of_heq hxy] using h.mem_iff))
(λ hm hm' he', heq_of_eq (by simpa [eq_of_heq hxy] using is_rotated_next_eq h h₁ _)))))
/-- Given a `s : cycle α` such that `nodup s`, retrieve the previous element before `x ∈ s`. -/
def prev : Π (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s), α :=
λ s, quot.hrec_on s (λ l hn x hx, prev l x hx)
(λ l₁ l₂ (h : l₁ ~r l₂),
function.hfunext (propext h.nodup_iff) (λ h₁ h₂ he, function.hfunext rfl
(λ x y hxy, function.hfunext (propext (by simpa [eq_of_heq hxy] using h.mem_iff))
(λ hm hm' he', heq_of_eq (by simpa [eq_of_heq hxy] using is_rotated_prev_eq h h₁ _)))))
@[simp] lemma prev_reverse_eq_next (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) :
s.reverse.prev (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.next hs x hx :=
begin
induction s using quot.induction_on,
exact prev_reverse_eq_next _ hs _ _
end
@[simp] lemma next_reverse_eq_prev (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) :
s.reverse.next (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.prev hs x hx :=
by simp [←prev_reverse_eq_next]
@[simp] lemma next_mem (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) :
s.next hs x hx ∈ s :=
begin
induction s using quot.induction_on,
exact next_mem _ _ _
end
lemma prev_mem (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) :
s.prev hs x hx ∈ s :=
by { rw [←next_reverse_eq_prev, ←mem_reverse_iff], exact next_mem _ _ _ _ }
end decidable
end cycle
|
8cd1f9896ba9c987152436b41a79c21a8de0fecf | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/nary_overload.lean | 01e0f0766fd615bcc30eaff98e6a57badae4b43c | [
"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 | 580 | lean | prelude
constant {l} vec : Type l → Type l
constant {l} lst : Type l → Type l
constant vec.nil {A : Type} : vec A
constant lst.nil {A : Type} : lst A
constant vec.cons {A : Type} : A → vec A → vec A
constant lst.cons {A : Type} : A → lst A → lst A
notation `[` l:(foldr `, ` (h t, vec.cons h t) vec.nil `]`) := l
notation `[` l:(foldr `, ` (h t, lst.cons h t) lst.nil `]`) := l
constant A : Type
variables a b c : A
#check [a, b, c]
#check ([a, b, c] : vec A)
#check ([a, b, c] : lst A)
set_option pp.all true
#check ([a, b, c] : vec A)
#check ([a, b, c] : lst A)
|
0b7e63b7e6757c17f9c96cd9944df2a2a28d8996 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/treeMap.lean | 5dce56f8ef7f0d11de8800ce8c0c65ce0322b7bd | [
"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 | 322 | lean | inductive TreeNode :=
| mkLeaf (name : String) : TreeNode
| mkNode (name : String) (children : List TreeNode) : TreeNode
open TreeNode in def treeToList (t : TreeNode) : List String :=
match t with
| mkLeaf name => [name]
| mkNode name children => name :: List.join (children.map treeToList)
termination_by _ t => t
|
1291af50088f3424c32ceda1ff353e7fd925c98b | bb31430994044506fa42fd667e2d556327e18dfe | /src/algebra/algebra/pi.lean | 005b3f1bee61cc0d75e01a5fd7e1b8e0a1184817 | [
"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 | 5,091 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import algebra.algebra.equiv
/-!
# The R-algebra structure on families of R-algebras
The R-algebra structure on `Π i : I, A i` when each `A i` is an R-algebra.
## Main defintions
* `pi.algebra`
* `pi.eval_alg_hom`
* `pi.const_alg_hom`
-/
universes u v w
namespace pi
variable {I : Type u} -- The indexing type
variable {R : Type*} -- The scalar type
variable {f : I → Type v} -- The family of types already equipped with instances
variables (x y : Π i, f i) (i : I)
variables (I f)
instance algebra {r : comm_semiring R}
[s : ∀ i, semiring (f i)] [∀ i, algebra R (f i)] :
algebra R (Π i : I, f i) :=
{ commutes' := λ a f, begin ext, simp [algebra.commutes], end,
smul_def' := λ a f, begin ext, simp [algebra.smul_def], end,
..(pi.ring_hom (λ i, algebra_map R (f i)) : R →+* Π i : I, f i) }
lemma algebra_map_def {r : comm_semiring R}
[s : ∀ i, semiring (f i)] [∀ i, algebra R (f i)] (a : R) :
algebra_map R (Π i, f i) a = (λ i, algebra_map R (f i) a) := rfl
@[simp] lemma algebra_map_apply {r : comm_semiring R}
[s : ∀ i, semiring (f i)] [∀ i, algebra R (f i)] (a : R) (i : I) :
algebra_map R (Π i, f i) a i = algebra_map R (f i) a := rfl
-- One could also build a `Π i, R i`-algebra structure on `Π i, A i`,
-- when each `A i` is an `R i`-algebra, although I'm not sure that it's useful.
variables {I} (R) (f)
/-- `function.eval` as an `alg_hom`. The name matches `pi.eval_ring_hom`, `pi.eval_monoid_hom`,
etc. -/
@[simps]
def eval_alg_hom {r : comm_semiring R} [Π i, semiring (f i)] [Π i, algebra R (f i)] (i : I) :
(Π i, f i) →ₐ[R] f i :=
{ to_fun := λ f, f i, commutes' := λ r, rfl, .. pi.eval_ring_hom f i}
variables (A B : Type*) [comm_semiring R] [semiring B] [algebra R B]
/-- `function.const` as an `alg_hom`. The name matches `pi.const_ring_hom`, `pi.const_monoid_hom`,
etc. -/
@[simps]
def const_alg_hom : B →ₐ[R] (A → B) :=
{ to_fun := function.const _,
commutes' := λ r, rfl,
.. pi.const_ring_hom A B}
/-- When `R` is commutative and permits an `algebra_map`, `pi.const_ring_hom` is equal to that
map. -/
@[simp] lemma const_ring_hom_eq_algebra_map : const_ring_hom A R = algebra_map R (A → R) :=
rfl
@[simp] lemma const_alg_hom_eq_algebra_of_id : const_alg_hom R A R = algebra.of_id R (A → R) :=
rfl
end pi
/-- A special case of `pi.algebra` for non-dependent types. Lean struggles to elaborate
definitions elsewhere in the library without this, -/
instance function.algebra {R : Type*} (I : Type*) (A : Type*) [comm_semiring R]
[semiring A] [algebra R A] : algebra R (I → A) :=
pi.algebra _ _
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w} {I : Type*}
variables [comm_semiring R] [semiring A] [semiring B]
variables [algebra R A] [algebra R B]
/-- `R`-algebra homomorphism between the function spaces `I → A` and `I → B`, induced by an
`R`-algebra homomorphism `f` between `A` and `B`. -/
@[simps] protected def comp_left (f : A →ₐ[R] B) (I : Type*) : (I → A) →ₐ[R] (I → B) :=
{ to_fun := λ h, f ∘ h,
commutes' := λ c, by { ext, exact f.commutes' c },
.. f.to_ring_hom.comp_left I }
end alg_hom
namespace alg_equiv
/-- A family of algebra equivalences `Π j, (A₁ j ≃ₐ A₂ j)` generates a
multiplicative equivalence between `Π j, A₁ j` and `Π j, A₂ j`.
This is the `alg_equiv` version of `equiv.Pi_congr_right`, and the dependent version of
`alg_equiv.arrow_congr`.
-/
@[simps apply]
def Pi_congr_right {R ι : Type*} {A₁ A₂ : ι → Type*} [comm_semiring R]
[Π i, semiring (A₁ i)] [Π i, semiring (A₂ i)] [Π i, algebra R (A₁ i)] [Π i, algebra R (A₂ i)]
(e : Π i, A₁ i ≃ₐ[R] A₂ i) : (Π i, A₁ i) ≃ₐ[R] Π i, A₂ i :=
{ to_fun := λ x j, e j (x j),
inv_fun := λ x j, (e j).symm (x j),
commutes' := λ r, by { ext i, simp },
.. @ring_equiv.Pi_congr_right ι A₁ A₂ _ _ (λ i, (e i).to_ring_equiv) }
@[simp]
lemma Pi_congr_right_refl {R ι : Type*} {A : ι → Type*} [comm_semiring R]
[Π i, semiring (A i)] [Π i, algebra R (A i)] :
Pi_congr_right (λ i, (alg_equiv.refl : A i ≃ₐ[R] A i)) = alg_equiv.refl := rfl
@[simp]
lemma Pi_congr_right_symm {R ι : Type*} {A₁ A₂ : ι → Type*} [comm_semiring R]
[Π i, semiring (A₁ i)] [Π i, semiring (A₂ i)] [Π i, algebra R (A₁ i)] [Π i, algebra R (A₂ i)]
(e : Π i, A₁ i ≃ₐ[R] A₂ i) : (Pi_congr_right e).symm = (Pi_congr_right $ λ i, (e i).symm) := rfl
@[simp]
lemma Pi_congr_right_trans {R ι : Type*} {A₁ A₂ A₃ : ι → Type*} [comm_semiring R]
[Π i, semiring (A₁ i)] [Π i, semiring (A₂ i)] [Π i, semiring (A₃ i)]
[Π i, algebra R (A₁ i)] [Π i, algebra R (A₂ i)] [Π i, algebra R (A₃ i)]
(e₁ : Π i, A₁ i ≃ₐ[R] A₂ i) (e₂ : Π i, A₂ i ≃ₐ[R] A₃ i) :
(Pi_congr_right e₁).trans (Pi_congr_right e₂) = (Pi_congr_right $ λ i, (e₁ i).trans (e₂ i)) :=
rfl
end alg_equiv
|
124687303ec587fde2812c70932a48c3b3be2b0d | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/testing/slim_check/testable.lean | b355cc40c8c9842c8fe605a4e88f97c2771bf57f | [
"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 | 28,409 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import testing.slim_check.sampleable
/-!
# `testable` Class
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Testable propositions have a procedure that can generate counter-examples
together with a proof that they invalidate the proposition.
This is a port of the Haskell QuickCheck library.
## Creating Customized Instances
The type classes `testable` and `sampleable` are the means by which
`slim_check` creates samples and tests them. For instance, the proposition
`∀ i j : ℕ, i ≤ j` has a `testable` instance because `ℕ` is sampleable
and `i ≤ j` is decidable. Once `slim_check` finds the `testable`
instance, it can start using the instance to repeatedly creating samples
and checking whether they satisfy the property. This allows the
user to create new instances and apply `slim_check` to new situations.
### Polymorphism
The property `testable.check (∀ (α : Type) (xs ys : list α), xs ++ ys
= ys ++ xs)` shows us that type-polymorphic properties can be
tested. `α` is instantiated with `ℤ` first and then tested as normal
monomorphic properties.
The monomorphisation limits the applicability of `slim_check` to
polymorphic properties that can be stated about integers. The
limitation may be lifted in the future but, for now, if
one wishes to use a different type than `ℤ`, one has to refer to
the desired type.
### What do I do if I'm testing a property about my newly defined type?
Let us consider a type made for a new formalization:
```lean
structure my_type :=
(x y : ℕ)
(h : x ≤ y)
```
How do we test a property about `my_type`? For instance, let us consider
`testable.check $ ∀ a b : my_type, a.y ≤ b.x → a.x ≤ b.y`. Writing this
property as is will give us an error because we do not have an instance
of `sampleable my_type`. We can define one as follows:
```lean
instance : sampleable my_type :=
{ sample := do
x ← sample ℕ,
xy_diff ← sample ℕ,
return { x := x, y := x + xy_diff, h := /- some proof -/ } }
```
We can see that the instance is very simple because our type is built
up from other type that have `sampleable` instances. `sampleable` also
has a `shrink` method but it is optional. We may want to implement one
for ease of testing as:
```lean
/- ... -/
shrink := λ ⟨x,y,h⟩, (λ ⟨x,y⟩, { x := x, y := x + y, h := /- proof -/}) <$> shrink (x, y - x) }
```
Again, we take advantage of the fact that other types have useful
`shrink` implementations, in this case `prod`.
### Optimizing the sampling
Some properties are guarded by a proposition. For instance, recall this
example:
```lean
#eval testable.check (∀ x : ℕ, 2 ∣ x → x < 100)
```
When testing the above example, we generate a natural number, we check
that it is even and test it if it is even or throw it away and start
over otherwise. Statistically, we can expect half of our samples to be
thrown away by such a filter. Sometimes, the filter is more
restrictive. For instance we might need `x` to be a `prime`
number. This would cause most of our samples to be discarded.
We can help `slim_check` find good samples by providing specialized
sampleable instances. Below, we show an instance for the subtype
of even natural numbers. This means that, when producing
a sample, it is forced to produce a proof that it is even.
```lean
instance {k : ℕ} [fact (0 < k)] : sampleable { x : ℕ // k ∣ x } :=
{ sample := do { n ← sample ℕ, pure ⟨k*n, dvd_mul_right _ _⟩ },
shrink := λ ⟨x,h⟩, (λ y, ⟨k*y, dvd_mul_right _ _⟩) <$> shrink x }
```
Such instance will be preferred when testing a proposition of the shape
`∀ x : T, p x → q`
We can observe the effect by enabling tracing:
```lean
/- no specialized sampling -/
#eval testable.check (∀ x : ℕ, 2 ∣ x → x < 100) { trace_discarded := tt }
-- discard
-- x := 1
-- discard
-- x := 41
-- discard
-- x := 3
-- discard
-- x := 5
-- discard
-- x := 5
-- discard
-- x := 197
-- discard
-- x := 469
-- discard
-- x := 9
-- discard
-- ===================
-- Found problems!
-- x := 552
-- -------------------
/- let us define a specialized sampling instance -/
instance {k : ℕ} : sampleable { x : ℕ // k ∣ x } :=
{ sample := do { n ← sample ℕ, pure ⟨k*n, dvd_mul_right _ _⟩ },
shrink := λ ⟨x,h⟩, (λ y, ⟨k*y, dvd_mul_right _ _⟩) <$> shrink x }
#eval testable.check (∀ x : ℕ, 2 ∣ x → x < 100) { enable_tracing := tt }
-- ===================
-- Found problems!
-- x := 358
-- -------------------
```
Similarly, it is common to write properties of the form: `∀ i j, i ≤ j → ...`
as the following example show:
```lean
#eval check (∀ i j k : ℕ, j < k → i - k < i - j)
```
Without subtype instances, the above property discards many samples
because `j < k` does not hold. Fortunately, we have appropriate
instance to choose `k` intelligently.
## Main definitions
* `testable` class
* `testable.check`: a way to test a proposition using random examples
## Tags
random testing
## References
* https://hackage.haskell.org/package/QuickCheck
-/
universes u v
variables var var' : string
variable α : Type u
variable β : α → Prop
variable f : Type → Prop
namespace slim_check
/-- Result of trying to disprove `p`
The constructors are:
* `success : (psum unit p) → test_result`
succeed when we find another example satisfying `p`
In `success h`, `h` is an optional proof of the proposition.
Without the proof, all we know is that we found one example
where `p` holds. With a proof, the one test was sufficient to
prove that `p` holds and we do not need to keep finding examples.
* `gave_up {} : ℕ → test_result`
give up when a well-formed example cannot be generated.
`gave_up n` tells us that `n` invalid examples were tried.
Above 100, we give up on the proposition and report that we
did not find a way to properly test it.
* `failure : ¬ p → (list string) → ℕ → test_result`
a counter-example to `p`; the strings specify values for the relevant variables.
`failure h vs n` also carries a proof that `p` does not hold. This way, we can
guarantee that there will be no false positive. The last component, `n`,
is the number of times that the counter-example was shrunk.
-/
@[derive inhabited]
inductive test_result (p : Prop)
| success : (psum unit p) → test_result
| gave_up {} : ℕ → test_result
| failure : ¬ p → (list string) → ℕ → test_result
/-- format a `test_result` as a string. -/
protected def test_result.to_string {p} : test_result p → string
| (test_result.success (psum.inl ())) := "success (without proof)"
| (test_result.success (psum.inr h)) := "success (with proof)"
| (test_result.gave_up n) := sformat!"gave up {n} times"
| (test_result.failure a vs _) := sformat!"failed {vs}"
/-- configuration for testing a property -/
@[derive [has_reflect, inhabited]]
structure slim_check_cfg :=
(num_inst : ℕ := 100) -- number of examples
(max_size : ℕ := 100) -- final size argument
(trace_discarded : bool := ff) -- enable the printing out of discarded samples
(trace_success : bool := ff) -- enable the printing out of successful tests
(trace_shrink : bool := ff) -- enable the printing out of shrinking steps
(trace_shrink_candidates : bool := ff) -- enable the printing out of shrinking candidates
(random_seed : option ℕ := none) -- specify a seed to the random number generator to
-- obtain a deterministic behavior
(quiet : bool := ff) -- suppress success message when running `slim_check`
instance {p} : has_to_string (test_result p) := ⟨ test_result.to_string ⟩
/--
`printable_prop p` allows one to print a proposition so that
`slim_check` can indicate how values relate to each other.
-/
class printable_prop (p : Prop) :=
(print_prop : option string)
@[priority 100] -- see [note priority]
instance default_printable_prop {p} : printable_prop p :=
⟨ none ⟩
/-- `testable p` uses random examples to try to disprove `p`. -/
class testable (p : Prop) :=
(run [] (cfg : slim_check_cfg) (minimize : bool) : gen (test_result p))
open _root_.list
open test_result
/-- applicative combinator proof carrying test results -/
def combine {p q : Prop} : psum unit (p → q) → psum unit p → psum unit q
| (psum.inr f) (psum.inr x) := psum.inr (f x)
| _ _ := psum.inl ()
/-- Combine the test result for properties `p` and `q` to create a test for their conjunction. -/
def and_counter_example {p q : Prop} :
test_result p →
test_result q →
test_result (p ∧ q)
| (failure Hce xs n) _ := failure (λ h, Hce h.1) xs n
| _ (failure Hce xs n) := failure (λ h, Hce h.2) xs n
| (success xs) (success ys) := success $ combine (combine (psum.inr and.intro) xs) ys
| (gave_up n) (gave_up m) := gave_up $ n + m
| (gave_up n) _ := gave_up n
| _ (gave_up n) := gave_up n
/-- Combine the test result for properties `p` and `q` to create a test for their disjunction -/
def or_counter_example {p q : Prop} :
test_result p →
test_result q →
test_result (p ∨ q)
| (failure Hce xs n) (failure Hce' ys n') := failure (λ h, or_iff_not_and_not.1 h ⟨Hce, Hce'⟩)
(xs ++ ys) (n + n')
| (success xs) _ := success $ combine (psum.inr or.inl) xs
| _ (success ys) := success $ combine (psum.inr or.inr) ys
| (gave_up n) (gave_up m) := gave_up $ n + m
| (gave_up n) _ := gave_up n
| _ (gave_up n) := gave_up n
/-- If `q → p`, then `¬ p → ¬ q` which means that testing `p` can allow us
to find counter-examples to `q`. -/
def convert_counter_example {p q : Prop}
(h : q → p) :
test_result p →
opt_param (psum unit (p → q)) (psum.inl ()) →
test_result q
| (failure Hce xs n) _ := failure (mt h Hce) xs n
| (success Hp) Hpq := success (combine Hpq Hp)
| (gave_up n) _ := gave_up n
/-- Test `q` by testing `p` and proving the equivalence between the two. -/
def convert_counter_example' {p q : Prop}
(h : p ↔ q) (r : test_result p) :
test_result q :=
convert_counter_example h.2 r (psum.inr h.1)
/-- When we assign a value to a universally quantified variable,
we record that value using this function so that our counter-examples
can be informative. -/
def add_to_counter_example (x : string) {p q : Prop}
(h : q → p) :
test_result p →
opt_param (psum unit (p → q)) (psum.inl ()) →
test_result q
| (failure Hce xs n) _ := failure (mt h Hce) (x :: xs) n
| r hpq := convert_counter_example h r hpq
/-- Add some formatting to the information recorded by `add_to_counter_example`. -/
def add_var_to_counter_example {γ : Type v} [has_repr γ]
(var : string) (x : γ) {p q : Prop}
(h : q → p) : test_result p →
opt_param (psum unit (p → q)) (psum.inl ()) →
test_result q :=
@add_to_counter_example (var ++ " := " ++ repr x) _ _ h
/-- Gadget used to introspect the name of bound variables.
It is used with the `testable` typeclass so that
`testable (named_binder "x" (∀ x, p x))` can use the variable name
of `x` in error messages displayed to the user. If we find that instantiating
the above quantifier with 3 falsifies it, we can print:
```
==============
Problem found!
==============
x := 3
```
-/
@[simp, nolint unused_arguments]
def named_binder (n : string) (p : Prop) : Prop := p
/-- Is the given test result a failure? -/
def is_failure {p} : test_result p → bool
| (test_result.failure _ _ _) := tt
| _ := ff
instance and_testable (p q : Prop) [testable p] [testable q] :
testable (p ∧ q) :=
⟨ λ cfg min, do
xp ← testable.run p cfg min,
xq ← testable.run q cfg min,
pure $ and_counter_example xp xq ⟩
instance or_testable (p q : Prop) [testable p] [testable q] :
testable (p ∨ q) :=
⟨ λ cfg min, do
xp ← testable.run p cfg min,
match xp with
| success (psum.inl h) := pure $ success (psum.inl h)
| success (psum.inr h) := pure $ success (psum.inr $ or.inl h)
| _ := do
xq ← testable.run q cfg min,
pure $ or_counter_example xp xq
end ⟩
instance iff_testable (p q : Prop) [testable ((p ∧ q) ∨ (¬ p ∧ ¬ q))] :
testable (p ↔ q) :=
⟨ λ cfg min, do
xp ← testable.run ((p ∧ q) ∨ (¬ p ∧ ¬ q)) cfg min,
return $ convert_counter_example' (by tauto!) xp ⟩
open printable_prop
@[priority 1000]
instance dec_guard_testable (p : Prop) [printable_prop p] [decidable p] (β : p → Prop)
[∀ h, testable (β h)] : testable (named_binder var $ Π h, β h) :=
⟨ λ cfg min, do
if h : p
then
match print_prop p with
| none := (λ r, convert_counter_example ($ h) r (psum.inr $ λ q _, q)) <$>
testable.run (β h) cfg min
| some str := (λ r, add_to_counter_example (sformat!"guard: {str}") ($ h) r
(psum.inr $ λ q _, q)) <$> testable.run (β h) cfg min
end
else if cfg.trace_discarded ∨ cfg.trace_success then
match print_prop p with
| none := trace "discard" $ return $ gave_up 1
| some str := trace sformat!"discard: {str} does not hold" $ return $ gave_up 1
end
else return $ gave_up 1 ⟩
/-- Type tag that replaces a type's `has_repr` instance with its `has_to_string` instance. -/
def use_has_to_string (α : Type*) := α
instance use_has_to_string.inhabited [I : inhabited α] : inhabited (use_has_to_string α) := I
/-- Add the type tag `use_has_to_string` to an expression's type. -/
def use_has_to_string.mk {α} (x : α) : use_has_to_string α := x
instance [has_to_string α] : has_repr (use_has_to_string α) :=
⟨ @to_string α _ ⟩
@[priority 2000]
instance all_types_testable [testable (f ℤ)] : testable (named_binder var $ Π x, f x) :=
⟨ λ cfg min, do
r ← testable.run (f ℤ) cfg min,
return $ add_var_to_counter_example var (use_has_to_string.mk "ℤ") ($ ℤ) r ⟩
/-- Trace the value of sampled variables if the sample is discarded. -/
def trace_if_giveup {p α β} [has_repr α] (tracing_enabled : bool) (var : string) (val : α) :
test_result p → thunk β → β
| (test_result.gave_up _) :=
if tracing_enabled then trace (sformat!" {var} := {repr val}")
else ($ ())
| _ := ($ ())
/-- testable instance for a property iterating over the element of a list -/
@[priority 5000]
instance test_forall_in_list
[∀ x, testable (β x)] [has_repr α] :
Π xs : list α, testable (named_binder var $ ∀ x, named_binder var' $ x ∈ xs → β x)
| [] := ⟨ λ tracing min, return $ success $ psum.inr (by { introv x h, cases h} ) ⟩
| (x :: xs) :=
⟨ λ cfg min, do
r ← testable.run (β x) cfg min,
trace_if_giveup cfg.trace_discarded var x r $
match r with
| failure _ _ _ := return $ add_var_to_counter_example var x
(by { intro h, apply h, left, refl }) r
| success hp := do
rs ← @testable.run _ (test_forall_in_list xs) cfg min,
return $ convert_counter_example
(by { intros h i h',
apply h,
right, apply h' })
rs
(combine (psum.inr
$ by { intros j h, simp only [ball_cons, named_binder],
split ; assumption, } ) hp)
| gave_up n := do
rs ← @testable.run _ (test_forall_in_list xs) cfg min,
match rs with
| (success _) := return $ gave_up n
| (failure Hce xs n) := return $ failure
(by { simp only [ball_cons, named_binder],
apply not_and_of_not_right _ Hce, }) xs n
| (gave_up n') := return $ gave_up (n + n')
end
end ⟩
/-- Test proposition `p` by randomly selecting one of the provided
testable instances. -/
def combine_testable (p : Prop)
(t : list $ testable p) (h : 0 < t.length) : testable p :=
⟨ λ cfg min, have 0 < length (map (λ t, @testable.run _ t cfg min) t),
by { rw [length_map], apply h },
gen.one_of (list.map (λ t, @testable.run _ t cfg min) t) this ⟩
open sampleable_ext
/--
Format the counter-examples found in a test failure.
-/
def format_failure (s : string) (xs : list string) (n : ℕ) : string :=
let counter_ex := string.intercalate "\n" xs in
sformat!"
===================
{s}
{counter_ex}
({n} shrinks)
-------------------
"
/--
Format the counter-examples found in a test failure.
-/
def format_failure' (s : string) {p} : test_result p → string
| (success a) := ""
| (gave_up a) := ""
| (test_result.failure _ xs n) := format_failure s xs n
/--
Increase the number of shrinking steps in a test result.
-/
def add_shrinks {p} (n : ℕ) : test_result p → test_result p
| r@(success a) := r
| r@(gave_up a) := r
| (test_result.failure h vs n') := test_result.failure h vs $ n + n'
/-- Shrink a counter-example `x` by using `shrink x`, picking the first
candidate that falsifies a property and recursively shrinking that one.
The process is guaranteed to terminate because `shrink x` produces
a proof that all the values it produces are smaller (according to `sizeof`)
than `x`. -/
def minimize_aux [sampleable_ext α] [∀ x, testable (β x)] (cfg : slim_check_cfg) (var : string) :
proxy_repr α → ℕ → option_t gen (Σ x, test_result (β (interp α x))) :=
well_founded.fix has_well_founded.wf $ λ x f_rec n, do
if cfg.trace_shrink_candidates
then return $ trace sformat!
"candidates for {var} :=\n{repr (sampleable_ext.shrink x).to_list}\n" ()
else pure (),
⟨y,r,⟨h₁⟩⟩ ← (sampleable_ext.shrink x).mfirst (λ ⟨a,h⟩, do
⟨r⟩ ← monad_lift (uliftable.up $ testable.run (β (interp α a)) cfg tt
: gen (ulift $ test_result $ β $ interp α a)),
if is_failure r
then pure (⟨a, r, ⟨h⟩⟩ : (Σ a, test_result (β (interp α a)) × plift (sizeof_lt a x)))
else failure),
if cfg.trace_shrink then return $
trace (sformat!"{var} := {repr y}" ++ format_failure' "Shrink counter-example:" r) ()
else pure (),
f_rec y h₁ (n+1) <|> pure ⟨y,add_shrinks (n+1) r⟩
/-- Once a property fails to hold on an example, look for smaller counter-examples
to show the user. -/
def minimize [sampleable_ext α] [∀ x, testable (β x)] (cfg : slim_check_cfg) (var : string)
(x : proxy_repr α) (r : test_result (β (interp α x))) :
gen (Σ x, test_result (β (interp α x))) := do
if cfg.trace_shrink then return $
trace (sformat!"{var} := {repr x}" ++ format_failure' "Shrink counter-example:" r) ()
else pure (),
x' ← option_t.run $ minimize_aux α _ cfg var x 0,
pure $ x'.get_or_else ⟨x, r⟩
@[priority 2000]
instance exists_testable (p : Prop)
[testable (named_binder var (∀ x, named_binder var' $ β x → p))] :
testable (named_binder var' (named_binder var (∃ x, β x) → p)) :=
⟨ λ cfg min, do
x ← testable.run (named_binder var (∀ x, named_binder var' $ β x → p)) cfg min,
pure $ convert_counter_example' exists_imp_distrib.symm x ⟩
/-- Test a universal property by creating a sample of the right type and instantiating the
bound variable with it -/
instance var_testable [sampleable_ext α] [∀ x, testable (β x)] :
testable (named_binder var $ Π x : α, β x) :=
⟨ λ cfg min, do
uliftable.adapt_down (sampleable_ext.sample α) $
λ x, do
r ← testable.run (β (sampleable_ext.interp α x)) cfg ff,
uliftable.adapt_down (if is_failure r ∧ min
then minimize _ _ cfg var x r
else if cfg.trace_success
then trace (sformat!" {var} := {repr x}") $ pure ⟨x,r⟩
else pure ⟨x,r⟩) $
λ ⟨x,r⟩, return $ trace_if_giveup cfg.trace_discarded var x r (add_var_to_counter_example var x
($ sampleable_ext.interp α x) r) ⟩
/-- Test a universal property about propositions -/
instance prop_var_testable (β : Prop → Prop) [I : ∀ b : bool, testable (β b)] :
testable (named_binder var $ Π p : Prop, β p) :=
⟨λ cfg min, do
convert_counter_example (λ h (b : bool), h b) <$> @testable.run
(named_binder var $ Π b : bool, β b) _ cfg min⟩
@[priority 3000]
instance unused_var_testable (β) [inhabited α] [testable β] :
testable (named_binder var $ Π x : α, β) :=
⟨ λ cfg min, do
r ← testable.run β cfg min,
pure $ convert_counter_example ($ default) r (psum.inr $ λ x _, x) ⟩
@[priority 2000]
instance subtype_var_testable {p : α → Prop}
[∀ x, printable_prop (p x)]
[∀ x, testable (β x)]
[I : sampleable_ext (subtype p)] :
testable (named_binder var $ Π x : α, named_binder var' $ p x → β x) :=
⟨ λ cfg min,
do let test (x : subtype p) : testable (β x) :=
⟨ λ cfg min, do
r ← testable.run (β x.val) cfg min,
match print_prop (p x) with
| none := pure r
| some str := pure $ add_to_counter_example sformat!"guard: {str} (by construction)"
id r (psum.inr id)
end ⟩,
r ← @testable.run (∀ x : subtype p, β x.val) (@slim_check.var_testable var _ _ I test) cfg
min,
pure $ convert_counter_example'
⟨λ (h : ∀ x : subtype p, β x) x h', h ⟨x,h'⟩,
λ h ⟨x,h'⟩, h x h'⟩
r ⟩
@[priority 100]
instance decidable_testable (p : Prop) [printable_prop p] [decidable p] : testable p :=
⟨ λ cfg min, return $
if h : p then success (psum.inr h)
else
match print_prop p with
| none := failure h [] 0
| some str := failure h [sformat!"issue: {str} does not hold"] 0
end ⟩
instance eq.printable_prop {α} [has_repr α] (x y : α) : printable_prop (x = y) :=
⟨ some sformat!"{repr x} = {repr y}" ⟩
instance ne.printable_prop {α} [has_repr α] (x y : α) : printable_prop (x ≠ y) :=
⟨ some sformat!"{repr x} ≠ {repr y}" ⟩
instance le.printable_prop {α} [has_le α] [has_repr α] (x y : α) : printable_prop (x ≤ y) :=
⟨ some sformat!"{repr x} ≤ {repr y}" ⟩
instance lt.printable_prop {α} [has_lt α] [has_repr α] (x y : α) : printable_prop (x < y) :=
⟨ some sformat!"{repr x} < {repr y}" ⟩
instance perm.printable_prop {α} [has_repr α] (xs ys : list α) : printable_prop (xs ~ ys) :=
⟨ some sformat!"{repr xs} ~ {repr ys}" ⟩
instance and.printable_prop (x y : Prop) [printable_prop x] [printable_prop y] :
printable_prop (x ∧ y) :=
⟨ do x' ← print_prop x,
y' ← print_prop y,
some sformat!"({x'} ∧ {y'})" ⟩
instance or.printable_prop (x y : Prop) [printable_prop x] [printable_prop y] :
printable_prop (x ∨ y) :=
⟨ do x' ← print_prop x,
y' ← print_prop y,
some sformat!"({x'} ∨ {y'})" ⟩
instance iff.printable_prop (x y : Prop) [printable_prop x] [printable_prop y] :
printable_prop (x ↔ y) :=
⟨ do x' ← print_prop x,
y' ← print_prop y,
some sformat!"({x'} ↔ {y'})" ⟩
instance imp.printable_prop (x y : Prop) [printable_prop x] [printable_prop y] :
printable_prop (x → y) :=
⟨ do x' ← print_prop x,
y' ← print_prop y,
some sformat!"({x'} → {y'})" ⟩
instance not.printable_prop (x : Prop) [printable_prop x] : printable_prop (¬ x) :=
⟨ do x' ← print_prop x,
some sformat!"¬ {x'}" ⟩
instance true.printable_prop : printable_prop true :=
⟨ some "true" ⟩
instance false.printable_prop : printable_prop false :=
⟨ some "false" ⟩
instance bool.printable_prop (b : bool) : printable_prop b :=
⟨ some $ if b then "true" else "false" ⟩
section io
open _root_.nat
variable {p : Prop}
/-- Execute `cmd` and repeat every time the result is `gave_up` (at most
`n` times). -/
def retry (cmd : rand (test_result p)) : ℕ → rand (test_result p)
| 0 := return $ gave_up 1
| (succ n) := do
r ← cmd,
match r with
| success hp := return $ success hp
| (failure Hce xs n) := return (failure Hce xs n)
| (gave_up _) := retry n
end
/-- Count the number of times the test procedure gave up. -/
def give_up (x : ℕ) : test_result p → test_result p
| (success (psum.inl ())) := gave_up x
| (success (psum.inr p)) := success (psum.inr p)
| (gave_up n) := gave_up (n+x)
| (failure Hce xs n) := failure Hce xs n
variable (p)
variable [testable p]
/-- Try `n` times to find a counter-example for `p`. -/
def testable.run_suite_aux (cfg : slim_check_cfg) : test_result p → ℕ → rand (test_result p)
| r 0 := return r
| r (succ n) :=
do let size := (cfg.num_inst - n - 1) * cfg.max_size / cfg.num_inst,
when cfg.trace_success $ return $ trace sformat!"[slim_check: sample]" (),
x ← retry ( (testable.run p cfg tt).run ⟨ size ⟩) 10,
match x with
| (success (psum.inl ())) := testable.run_suite_aux r n
| (success (psum.inr Hp)) := return $ success (psum.inr Hp)
| (failure Hce xs n) := return (failure Hce xs n)
| (gave_up g) := testable.run_suite_aux (give_up g r) n
end
/-- Try to find a counter-example of `p`. -/
def testable.run_suite (cfg : slim_check_cfg := {}) : rand (test_result p) :=
testable.run_suite_aux p cfg (success $ psum.inl ()) cfg.num_inst
/-- Run a test suite for `p` in `io`. -/
def testable.check' (cfg : slim_check_cfg := {}) : io (test_result p) :=
match cfg.random_seed with
| some seed := io.run_rand_with seed (testable.run_suite p cfg)
| none := io.run_rand (testable.run_suite p cfg)
end
namespace tactic
open _root_.tactic expr
/-!
## Decorations
Instances of `testable` use `named_binder` as a decoration on
propositions in order to access the name of bound variables, as in
`named_binder "x" (forall x, x < y)`. This helps the
`testable` instances create useful error messages where variables
are matched with values that falsify a given proposition.
The following functions help support the gadget so that the user does
not have to put them in themselves.
-/
/-- `add_existential_decorations p` adds `a `named_binder` annotation at the
root of `p` if `p` is an existential quantification. -/
meta def add_existential_decorations : expr → expr
| e@`(@Exists %%α %%(lam n bi d b)) :=
let n := to_string n in
const ``named_binder [] (`(n) : expr) e
| e := e
/-- Traverse the syntax of a proposition to find universal quantifiers
and existential quantifiers and add `named_binder` annotations next to
them. -/
meta def add_decorations : expr → expr | e :=
e.replace $ λ e _,
match e with
| (pi n bi d b) :=
let n := to_string n in
some $ const ``named_binder [] (`(n) : expr)
(pi n bi (add_existential_decorations d) (add_decorations b))
| e := none
end
/-- `decorations_of p` is used as a hint to `mk_decorations` to specify
that the goal should be satisfied with a proposition equivalent to `p`
with added annotations. -/
@[reducible, nolint unused_arguments]
def decorations_of (p : Prop) := Prop
/-- In a goal of the shape `⊢ tactic.decorations_of p`, `mk_decoration` examines
the syntax of `p` and add `named_binder` around universal quantifications and
existential quantifications to improve error messages.
This tool can be used in the declaration of a function as follows:
```lean
def foo (p : Prop) (p' : tactic.decorations_of p . mk_decorations) [testable p'] : ...
```
`p` is the parameter given by the user, `p'` is an equivalent proposition where
the quantifiers are annotated with `named_binder`.
-/
meta def mk_decorations : tactic unit := do
`(tactic.decorations_of %%p) ← target,
exact $ add_decorations p
end tactic
/-- Run a test suite for `p` and return true or false: should we believe that `p` holds? -/
def testable.check (p : Prop) (cfg : slim_check_cfg := {})
(p' : tactic.decorations_of p . tactic.mk_decorations) [testable p'] : io punit := do
x ← match cfg.random_seed with
| some seed := io.run_rand_with seed (testable.run_suite p' cfg)
| none := io.run_rand (testable.run_suite p' cfg)
end,
match x with
| (success _) := when (¬ cfg.quiet) $ io.put_str_ln "Success"
| (gave_up n) := io.fail sformat!"Gave up {repr n} times"
| (failure _ xs n) := do
io.fail $ format_failure "Found problems!" xs n
end
end io
end slim_check
|
135fde33ff76a5a11d6c58fc6fb205556d55e1e1 | 94637389e03c919023691dcd05bd4411b1034aa5 | /src/zzz_junk/04_type_library/00_empty.lean | 7341d09131154c74aa3abd961d13f5bf099aa184 | [] | no_license | kevinsullivan/complogic-s21 | 7c4eef2105abad899e46502270d9829d913e8afc | 99039501b770248c8ceb39890be5dfe129dc1082 | refs/heads/master | 1,682,985,669,944 | 1,621,126,241,000 | 1,621,126,241,000 | 335,706,272 | 0 | 38 | null | 1,618,325,669,000 | 1,612,374,118,000 | Lean | UTF-8 | Lean | false | false | 489 | lean | namespace hidden
/-
The empty data type has no
values/constructors at all.
This fact becomes interesting
and useful when one performs
a case analysis on values of
this type, as there are no
cases to consider.
-/
inductive empty : Type
/-
Exercise: Show that you can
implement a function, e2n, that
takes (assumes it's given) an
argument, e, of type empty and
that then uses match/with/end
to "eliminate" e and to return
without returning any particular
value of type nat.
-/
end hidden |
53f1a574c4319744fb1f7192aa27d73a9d9ee56a | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/theories/group_theory/cyclic.lean | 8b6d2539fe0f6187321599e84f3716c6231dcd66 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 15,864 | lean | /-
Copyright (c) 2015 Haitao Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Haitao Zhang
-/
import data algebra.group algebra.group_power .finsubg .hom .perm
open function finset
open eq.ops
namespace group_theory
section cyclic
open nat fin list
local attribute madd [reducible]
variable {A : Type}
variable [ambG : group A]
include ambG
lemma pow_mod {a : A} {n m : nat} : a ^ m = 1 → a ^ n = a ^ (n % m) :=
assume Pid,
have a ^ (n / m * m) = 1, from calc
a ^ (n / m * m) = a ^ (m * (n / m)) : by rewrite (mul.comm (n / m) m)
... = (a ^ m) ^ (n / m) : by rewrite pow_mul
... = 1 ^ (n / m) : by rewrite Pid
... = 1 : one_pow (n / m),
calc a ^ n = a ^ (n / m * m + n % m) : by rewrite -(eq_div_mul_add_mod n m)
... = a ^ (n / m * m) * a ^ (n % m) : by rewrite pow_add
... = 1 * a ^ (n % m) : by rewrite this
... = a ^ (n % m) : by rewrite one_mul
lemma pow_sub_eq_one_of_pow_eq {a : A} {i j : nat} :
a^i = a^j → a^(i - j) = 1 :=
assume Pe, or.elim (lt_or_ge i j)
(assume Piltj, begin rewrite [sub_eq_zero_of_le (nat.le_of_lt Piltj)] end)
(assume Pigej, begin rewrite [pow_sub a Pigej, Pe, mul.right_inv] end)
lemma pow_dist_eq_one_of_pow_eq {a : A} {i j : nat} :
a^i = a^j → a^(dist i j) = 1 :=
assume Pe, or.elim (lt_or_ge i j)
(suppose i < j, by rewrite [dist_eq_sub_of_lt this]; exact pow_sub_eq_one_of_pow_eq (eq.symm Pe))
(suppose i ≥ j, by rewrite [dist_eq_sub_of_ge this]; exact pow_sub_eq_one_of_pow_eq Pe)
lemma pow_madd {a : A} {n : nat} {i j : fin (succ n)} :
a^(succ n) = 1 → a^(val (i + j)) = a^i * a^j :=
assume Pe, calc
a^(val (i + j)) = a^((i + j) % (succ n)) : rfl
... = a^(val i + val j) : by rewrite [-pow_mod Pe]
... = a^i * a^j : by rewrite pow_add
lemma mk_pow_mod {a : A} {n m : nat} : a ^ (succ m) = 1 → a ^ n = a ^ (mk_mod m n) :=
assume Pe, pow_mod Pe
variable [finA : fintype A]
include finA
open fintype
variable [deceqA : decidable_eq A]
include deceqA
lemma exists_pow_eq_one (a : A) : ∃ n, n < card A ∧ a ^ (succ n) = 1 :=
let f := (λ i : fin (succ (card A)), a ^ i) in
have Pninj : ¬(injective f), from assume Pinj,
absurd (card_le_of_inj _ _ (exists.intro f Pinj))
(begin rewrite [card_fin], apply not_succ_le_self end),
obtain i₁ P₁, from exists_not_of_not_forall Pninj,
obtain i₂ P₂, from exists_not_of_not_forall P₁,
obtain Pfe Pne, from and_not_of_not_implies P₂,
have Pvne : val i₁ ≠ val i₂, from assume Pveq, absurd (eq_of_veq Pveq) Pne,
exists.intro (pred (dist i₁ i₂)) (begin
rewrite [succ_pred_of_pos (dist_pos_of_ne Pvne)], apply and.intro,
apply lt_of_succ_lt_succ,
rewrite [succ_pred_of_pos (dist_pos_of_ne Pvne)],
apply nat.lt_of_le_of_lt dist_le_max (max_lt i₁ i₂),
apply pow_dist_eq_one_of_pow_eq Pfe
end)
-- Another possibility is to generate a list of powers and use find to get the first
-- unity.
-- The bound on bex is arbitrary as long as it is large enough (at least card A). Making
-- it larger simplifies some proofs, such as a ∈ cyc a.
definition cyc (a : A) : finset A := {x ∈ univ | bex (succ (card A)) (λ n, a ^ n = x)}
definition order (a : A) := card (cyc a)
definition pow_fin (a : A) (n : nat) (i : fin (order a)) := a ^ (i + n)
definition cyc_pow_fin (a : A) (n : nat) : finset A := image (pow_fin a n) univ
lemma order_le_group_order {a : A} : order a ≤ card A :=
card_le_card_of_subset !subset_univ
lemma cyc_has_one (a : A) : 1 ∈ cyc a :=
begin
apply mem_sep_of_mem !mem_univ,
existsi 0, apply and.intro,
apply zero_lt_succ,
apply pow_zero
end
lemma order_pos (a : A) : 0 < order a :=
length_pos_of_mem (cyc_has_one a)
lemma cyc_mul_closed (a : A) : finset_mul_closed_on (cyc a) :=
take g h, assume Pgin Phin,
obtain n Plt Pe, from exists_pow_eq_one a,
obtain i Pilt Pig, from of_mem_sep Pgin,
obtain j Pjlt Pjh, from of_mem_sep Phin,
begin
rewrite [-Pig, -Pjh, -pow_add, pow_mod Pe],
apply mem_sep_of_mem !mem_univ,
existsi ((i + j) % (succ n)), apply and.intro,
apply nat.lt_trans (mod_lt (i+j) !zero_lt_succ) (succ_lt_succ Plt),
apply rfl
end
lemma cyc_has_inv (a : A) : finset_has_inv (cyc a) :=
take g, assume Pgin,
obtain n Plt Pe, from exists_pow_eq_one a,
obtain i Pilt Pig, from of_mem_sep Pgin,
let ni := -(mk_mod n i) in
have Pinv : g*a^ni = 1, by
rewrite [-Pig, mk_pow_mod Pe, -(pow_madd Pe), add.right_inv],
begin
rewrite [inv_eq_of_mul_eq_one Pinv],
apply mem_sep_of_mem !mem_univ,
existsi ni, apply and.intro,
apply nat.lt_trans (is_lt ni) (succ_lt_succ Plt),
apply rfl
end
lemma self_mem_cyc (a : A) : a ∈ cyc a :=
mem_sep_of_mem !mem_univ
(exists.intro (1 : nat) (and.intro (succ_lt_succ card_pos) !pow_one))
lemma mem_cyc (a : A) : ∀ {n : nat}, a^n ∈ cyc a
| 0 := cyc_has_one a
| (succ n) :=
begin rewrite pow_succ', apply cyc_mul_closed a, exact mem_cyc, apply self_mem_cyc end
lemma order_le {a : A} {n : nat} : a^(succ n) = 1 → order a ≤ succ n :=
assume Pe, let s := image (pow_nat a) (upto (succ n)) in
have Psub: cyc a ⊆ s, from subset_of_forall
(take g, assume Pgin, obtain i Pilt Pig, from of_mem_sep Pgin, begin
rewrite [-Pig, pow_mod Pe],
apply mem_image,
apply mem_upto_of_lt (mod_lt i !zero_lt_succ),
exact rfl end),
#nat calc order a ≤ card s : card_le_card_of_subset Psub
... ≤ card (upto (succ n)) : !card_image_le
... = succ n : card_upto (succ n)
lemma pow_ne_of_lt_order {a : A} {n : nat} : succ n < order a → a^(succ n) ≠ 1 :=
assume Plt, not_imp_not_of_imp order_le (not_le_of_gt Plt)
lemma eq_zero_of_pow_eq_one {a : A} : ∀ {n : nat}, a^n = 1 → n < order a → n = 0
| 0 := assume Pe Plt, rfl
| (succ n) := assume Pe Plt, absurd Pe (pow_ne_of_lt_order Plt)
lemma pow_fin_inj (a : A) (n : nat) : injective (pow_fin a n) :=
take i j : fin (order a),
suppose a^(i + n) = a^(j + n),
have a^(dist i j) = 1, begin apply !dist_add_add_right ▸ (pow_dist_eq_one_of_pow_eq this) end,
have dist i j = 0, from
eq_zero_of_pow_eq_one this (nat.lt_of_le_of_lt dist_le_max (max_lt i j)),
eq_of_veq (eq_of_dist_eq_zero this)
lemma cyc_eq_cyc (a : A) (n : nat) : cyc_pow_fin a n = cyc a :=
have Psub : cyc_pow_fin a n ⊆ cyc a, from subset_of_forall
(take g, assume Pgin,
obtain i Pin Pig, from exists_of_mem_image Pgin, by rewrite [-Pig]; apply mem_cyc),
eq_of_card_eq_of_subset (begin apply eq.trans,
apply card_image_eq_of_inj_on,
rewrite [to_set_univ, -set.injective_iff_inj_on_univ], exact pow_fin_inj a n,
rewrite [card_fin] end) Psub
lemma pow_order (a : A) : a^(order a) = 1 :=
obtain i Pin Pone, from exists_of_mem_image (eq.symm (cyc_eq_cyc a 1) ▸ cyc_has_one a),
or.elim (eq_or_lt_of_le (succ_le_of_lt (is_lt i)))
(assume P, P ▸ Pone) (assume P, absurd Pone (pow_ne_of_lt_order P))
lemma eq_one_of_order_eq_one {a : A} : order a = 1 → a = 1 :=
assume Porder,
calc a = a^1 : by rewrite (pow_one a)
... = a^(order a) : by rewrite Porder
... = 1 : by rewrite pow_order
lemma order_of_min_pow {a : A} {n : nat}
(Pone : a^(succ n) = 1) (Pmin : ∀ i, i < n → a^(succ i) ≠ 1) : order a = succ n :=
or.elim (eq_or_lt_of_le (order_le Pone)) (λ P, P)
(λ P : order a < succ n, begin
have Pn : a^(order a) ≠ 1,
begin
rewrite [-(succ_pred_of_pos (order_pos a))],
apply Pmin, apply nat.lt_of_succ_lt_succ,
rewrite [succ_pred_of_pos !order_pos], assumption
end,
exact absurd (pow_order a) Pn end)
lemma order_dvd_of_pow_eq_one {a : A} {n : nat} (Pone : a^n = 1) : order a ∣ n :=
have Pe : a^(n % order a) = 1, from
begin
revert Pone,
rewrite [eq_div_mul_add_mod n (order a) at {1}, pow_add, mul.comm _ (order a), pow_mul, pow_order, one_pow, one_mul],
intros, assumption
end,
dvd_of_mod_eq_zero (eq_zero_of_pow_eq_one Pe (mod_lt n !order_pos))
attribute [instance]
definition cyc_is_finsubg (a : A) : is_finsubg (cyc a) :=
is_finsubg.mk (cyc_has_one a) (cyc_mul_closed a) (cyc_has_inv a)
lemma order_dvd_group_order (a : A) : order a ∣ card A :=
dvd.intro (eq.symm (!mul.comm ▸ lagrange_theorem (subset_univ (cyc a))))
definition pow_fin' (a : A) (i : fin (succ (pred (order a)))) := pow_nat a i
local attribute group_of_add_group [instance]
lemma pow_fin_hom (a : A) : homomorphic (pow_fin' a) :=
take i j : fin (succ (pred (order a))),
begin
rewrite [↑pow_fin'],
apply pow_madd,
rewrite [succ_pred_of_pos !order_pos],
exact pow_order a
end
definition pow_fin_is_iso (a : A) : is_iso_class (pow_fin' a) :=
is_iso_class.mk (pow_fin_hom a)
(have H : injective (λ (i : fin (order a)), a ^ (val i + 0)), from pow_fin_inj a 0,
begin rewrite [↑pow_fin', succ_pred_of_pos !order_pos]; exact H end)
end cyclic
section rot
open nat list
open fin fintype list
section
local attribute group_of_add_group [instance]
lemma pow_eq_mul {n : nat} {i : fin (succ n)} : ∀ {k : nat}, i^k = mk_mod n (i*k)
| 0 := by rewrite [pow_zero]
| (succ k) := begin
have Psucc : i^(succ k) = madd (i^k) i, by apply pow_succ',
rewrite [Psucc, pow_eq_mul],
apply eq_of_veq,
rewrite [mul_succ, val_madd, ↑mk_mod, mod_add_mod]
end
end
definition rotl : ∀ {n : nat} m : nat, fin n → fin n
| 0 := take m i, elim0 i
| (succ n) := take m, madd (mk_mod n (n*m))
definition rotr : ∀ {n : nat} m : nat, fin n → fin n
| (0:nat) := take m i, elim0 i
| (nat.succ n) := take m, madd (-(mk_mod n (n*m)))
lemma rotl_succ' {n m : nat} : rotl m = madd (mk_mod n (n*m)) := rfl
lemma rotl_zero : ∀ {n : nat}, @rotl n 0 = id
| 0 := funext take i, elim0 i
| (nat.succ n) := funext take i, begin rewrite [↑rotl, mul_zero, mk_mod_zero_eq, zero_madd] end
lemma rotl_id : ∀ {n : nat}, @rotl n n = id
| 0 := funext take i, elim0 i
| (nat.succ n) :=
have P : mk_mod n (n * succ n) = mk_mod n 0,
from eq_of_veq (by rewrite [↑mk_mod, mul_mod_left]),
begin rewrite [rotl_succ', P], apply rotl_zero end
lemma rotl_to_zero {n i : nat} : rotl i (mk_mod n i) = 0 :=
eq_of_veq begin rewrite [↑rotl, val_madd], esimp [mk_mod], rewrite [ mod_add_mod, add_mod_mod, -succ_mul, mul_mod_right] end
lemma rotl_compose : ∀ {n : nat} {j k : nat}, (@rotl n j) ∘ (rotl k) = rotl (j + k)
| 0 := take j k, funext take i, elim0 i
| (succ n) := take j k, funext take i, eq.symm begin
rewrite [*rotl_succ', left_distrib, -(@madd_mk_mod n (n*j)), madd_assoc],
end
lemma rotr_rotl : ∀ {n : nat} (m : nat) {i : fin n}, rotr m (rotl m i) = i
| 0 := take m i, elim0 i
| (nat.succ n) := take m i, calc (-(mk_mod n (n*m))) + ((mk_mod n (n*m)) + i) = i : by rewrite neg_add_cancel_left
lemma rotl_rotr : ∀ {n : nat} (m : nat), (@rotl n m) ∘ (rotr m) = id
| 0 := take m, funext take i, elim0 i
| (nat.succ n) := take m, funext take i, calc (mk_mod n (n*m)) + (-(mk_mod n (n*m)) + i) = i : add_neg_cancel_left
lemma rotl_succ {n : nat} : (rotl 1) ∘ (@succ n) = lift_succ :=
funext (take i, eq_of_veq (begin rewrite [↑comp, ↑rotl, ↑madd, mul_one n, ↑mk_mod, mod_add_mod, ↑lift_succ, val_succ, -succ_add_eq_succ_add, add_mod_self_left, mod_eq_of_lt (lt.trans (is_lt i) !lt_succ_self), -val_lift] end))
definition list.rotl {A : Type} : ∀ l : list A, list A
| [] := []
| (a::l) := l++[a]
lemma rotl_cons {A : Type} {a : A} {l} : list.rotl (a::l) = l++[a] := rfl
lemma rotl_map {A B : Type} {f : A → B} : ∀ {l : list A}, list.rotl (map f l) = map f (list.rotl l)
| [] := rfl
| (a::l) := begin rewrite [map_cons, *rotl_cons, map_append] end
lemma rotl_eq_rotl : ∀ {n : nat}, map (rotl 1) (upto n) = list.rotl (upto n)
| 0 := rfl
| (succ n) := begin
rewrite [upto_step at {1}, fin.upto_succ, rotl_cons, map_append],
congruence,
rewrite [map_map], congruence, exact rotl_succ,
rewrite [map_singleton], congruence, rewrite [↑rotl, mul_one n, ↑mk_mod, ↑maxi, ↑madd],
congruence, rewrite [ mod_add_mod, val_zero, add_zero, mod_eq_of_lt !lt_succ_self ]
end
attribute [reducible]
definition seq (A : Type) (n : nat) := fin n → A
variable {A : Type}
definition rotl_fun {n : nat} (m : nat) (f : seq A n) : seq A n := f ∘ (rotl m)
definition rotr_fun {n : nat} (m : nat) (f : seq A n) : seq A n := f ∘ (rotr m)
lemma rotl_seq_zero {n : nat} : rotl_fun 0 = @id (seq A n) :=
funext take f, begin rewrite [↑rotl_fun, rotl_zero] end
lemma rotl_seq_ne_id : ∀ {n : nat}, (∃ a b : A, a ≠ b) → ∀ i, i < n → rotl_fun (succ i) ≠ (@id (seq A (succ n)))
| 0 := assume Pex, take i, assume Piltn, absurd Piltn !not_lt_zero
| (nat.succ n) := assume Pex, obtain a b Pne, from Pex, take i, assume Pilt,
let f := (λ j : fin (succ (succ n)), if j = 0 then a else b),
fi := mk_mod (succ n) (succ i) in
have Pfne : rotl_fun (succ i) f fi ≠ f fi,
from begin rewrite [↑rotl_fun, rotl_to_zero, mk_mod_of_lt (succ_lt_succ Pilt), if_pos rfl, if_neg mk_succ_ne_zero], assumption end,
have P : rotl_fun (succ i) f ≠ f, from
assume Peq, absurd (congr_fun Peq fi) Pfne,
assume Peq, absurd (congr_fun Peq f) P
lemma rotr_rotl_fun {n : nat} (m : nat) (f : seq A n) : rotr_fun m (rotl_fun m f) = f :=
calc f ∘ (rotl m) ∘ (rotr m) = f ∘ ((rotl m) ∘ (rotr m)) : by rewrite -comp.assoc
... = f ∘ id : by rewrite (rotl_rotr m)
lemma rotl_fun_inj {n : nat} {m : nat} : @injective (seq A n) (seq A n) (rotl_fun m) :=
injective_of_has_left_inverse (exists.intro (rotr_fun m) (rotr_rotl_fun m))
lemma seq_rotl_eq_list_rotl {n : nat} (f : seq A n) :
fun_to_list (rotl_fun 1 f) = list.rotl (fun_to_list f) :=
begin
rewrite [↑fun_to_list, ↑rotl_fun, -map_map, rotl_map],
congruence, exact rotl_eq_rotl
end
end rot
section rotg
open nat fin fintype
attribute [reducible]
definition rotl_perm (A : Type) [finA : fintype A] [deceqA : decidable_eq A] (n : nat) (m : nat) : perm (seq A n) :=
perm.mk (rotl_fun m) rotl_fun_inj
variable {A : Type}
variable [finA : fintype A]
variable [deceqA : decidable_eq A]
variable {n : nat}
include finA deceqA
lemma rotl_perm_mul {i j : nat} : (rotl_perm A n i) * (rotl_perm A n j) = rotl_perm A n (j+i) :=
eq_of_feq (funext take f, calc
f ∘ (rotl j) ∘ (rotl i) = f ∘ ((rotl j) ∘ (rotl i)) : by rewrite -comp.assoc
... = f ∘ (rotl (j+i)) : by rewrite rotl_compose)
lemma rotl_perm_pow_eq : ∀ {i : nat}, (rotl_perm A n 1) ^ i = rotl_perm A n i
| 0 := begin rewrite [pow_zero, ↑rotl_perm, perm_one, -eq_iff_feq], esimp, rewrite rotl_seq_zero end
| (succ i) := begin rewrite [pow_succ', rotl_perm_pow_eq, rotl_perm_mul, one_add] end
lemma rotl_perm_pow_eq_one : (rotl_perm A n 1) ^ n = 1 :=
eq.trans rotl_perm_pow_eq (eq_of_feq begin esimp [rotl_perm], rewrite [↑rotl_fun, rotl_id] end)
lemma rotl_perm_mod {i : nat} : rotl_perm A n i = rotl_perm A n (i % n) :=
calc rotl_perm A n i = (rotl_perm A n 1) ^ i : by rewrite rotl_perm_pow_eq
... = (rotl_perm A n 1) ^ (i % n) : by rewrite (pow_mod rotl_perm_pow_eq_one)
... = rotl_perm A n (i % n) : by rewrite rotl_perm_pow_eq
-- needs A to have at least two elements!
lemma rotl_perm_pow_ne_one (Pex : ∃ a b : A, a ≠ b) : ∀ i, i < n → (rotl_perm A (succ n) 1)^(succ i) ≠ 1 :=
take i, assume Piltn, begin
intro P, revert P, rewrite [rotl_perm_pow_eq, -eq_iff_feq, perm_one, *perm.f_mk],
intro P, exact absurd P (rotl_seq_ne_id Pex i Piltn)
end
lemma rotl_perm_order (Pex : ∃ a b : A, a ≠ b) : order (rotl_perm A (succ n) 1) = (succ n) :=
order_of_min_pow rotl_perm_pow_eq_one (rotl_perm_pow_ne_one Pex)
end rotg
end group_theory
|
0a1470477a53eebe9fb978eea8ab17ff3e0a0dd4 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/limits/preserves/shapes/equalizers.lean | 8aaee3c376d9db568baf94887cc0d26c9f947c09 | [
"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,231 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.limits.shapes.split_coequalizer
import category_theory.limits.preserves.basic
/-!
# Preserving (co)equalizers
Constructions to relate the notions of preserving (co)equalizers and reflecting (co)equalizers
to concrete (co)forks.
In particular, we show that `equalizer_comparison f g G` is an isomorphism iff `G` preserves
the limit of the parallel pair `f,g`, as well as the dual result.
-/
noncomputable theory
universes w v₁ v₂ u₁ u₂
open category_theory category_theory.category category_theory.limits
variables {C : Type u₁} [category.{v₁} C]
variables {D : Type u₂} [category.{v₂} D]
variables (G : C ⥤ D)
namespace category_theory.limits
section equalizers
variables {X Y Z : C} {f g : X ⟶ Y} {h : Z ⟶ X} (w : h ≫ f = h ≫ g)
/--
The map of a fork is a limit iff the fork consisting of the mapped morphisms is a limit. This
essentially lets us commute `fork.of_ι` with `functor.map_cone`.
-/
def is_limit_map_cone_fork_equiv :
is_limit (G.map_cone (fork.of_ι h w)) ≃
is_limit (fork.of_ι (G.map h) (by simp only [←G.map_comp, w]) : fork (G.map f) (G.map g)) :=
(is_limit.postcompose_hom_equiv (diagram_iso_parallel_pair _) _).symm.trans
(is_limit.equiv_iso_limit (fork.ext (iso.refl _) (by { simp [fork.ι] })))
/-- The property of preserving equalizers expressed in terms of forks. -/
def is_limit_fork_map_of_is_limit [preserves_limit (parallel_pair f g) G]
(l : is_limit (fork.of_ι h w)) :
is_limit (fork.of_ι (G.map h) (by simp only [←G.map_comp, w]) : fork (G.map f) (G.map g)) :=
is_limit_map_cone_fork_equiv G w (preserves_limit.preserves l)
/-- The property of reflecting equalizers expressed in terms of forks. -/
def is_limit_of_is_limit_fork_map [reflects_limit (parallel_pair f g) G]
(l : is_limit (fork.of_ι (G.map h) (by simp only [←G.map_comp, w]) : fork (G.map f) (G.map g))) :
is_limit (fork.of_ι h w) :=
reflects_limit.reflects ((is_limit_map_cone_fork_equiv G w).symm l)
variables (f g) [has_equalizer f g]
/--
If `G` preserves equalizers and `C` has them, then the fork constructed of the mapped morphisms of
a fork is a limit.
-/
def is_limit_of_has_equalizer_of_preserves_limit
[preserves_limit (parallel_pair f g) G] :
is_limit (fork.of_ι (G.map (equalizer.ι f g))
(by simp only [←G.map_comp, equalizer.condition])) :=
is_limit_fork_map_of_is_limit G _ (equalizer_is_equalizer f g)
variables [has_equalizer (G.map f) (G.map g)]
/--
If the equalizer comparison map for `G` at `(f,g)` is an isomorphism, then `G` preserves the
equalizer of `(f,g)`.
-/
def preserves_equalizer.of_iso_comparison [i : is_iso (equalizer_comparison f g G)] :
preserves_limit (parallel_pair f g) G :=
begin
apply preserves_limit_of_preserves_limit_cone (equalizer_is_equalizer f g),
apply (is_limit_map_cone_fork_equiv _ _).symm _,
apply is_limit.of_point_iso (limit.is_limit (parallel_pair (G.map f) (G.map g))),
apply i,
end
variables [preserves_limit (parallel_pair f g) G]
/--
If `G` preserves the equalizer of `(f,g)`, then the equalizer comparison map for `G` at `(f,g)` is
an isomorphism.
-/
def preserves_equalizer.iso :
G.obj (equalizer f g) ≅ equalizer (G.map f) (G.map g) :=
is_limit.cone_point_unique_up_to_iso
(is_limit_of_has_equalizer_of_preserves_limit G f g)
(limit.is_limit _)
@[simp]
lemma preserves_equalizer.iso_hom :
(preserves_equalizer.iso G f g).hom = equalizer_comparison f g G :=
rfl
instance : is_iso (equalizer_comparison f g G) :=
begin
rw ← preserves_equalizer.iso_hom,
apply_instance
end
end equalizers
section coequalizers
variables {X Y Z : C} {f g : X ⟶ Y} {h : Y ⟶ Z} (w : f ≫ h = g ≫ h)
/--
The map of a cofork is a colimit iff the cofork consisting of the mapped morphisms is a colimit.
This essentially lets us commute `cofork.of_π` with `functor.map_cocone`.
-/
def is_colimit_map_cocone_cofork_equiv :
is_colimit (G.map_cocone (cofork.of_π h w)) ≃
is_colimit (cofork.of_π (G.map h) (by simp only [←G.map_comp, w]) : cofork (G.map f) (G.map g)) :=
(is_colimit.precompose_inv_equiv (diagram_iso_parallel_pair _) _).symm.trans $
is_colimit.equiv_iso_colimit $ cofork.ext (iso.refl _) $
begin
dsimp only [cofork.π, cofork.of_π_ι_app],
dsimp, rw [category.comp_id, category.id_comp]
end
/-- The property of preserving coequalizers expressed in terms of coforks. -/
def is_colimit_cofork_map_of_is_colimit [preserves_colimit (parallel_pair f g) G]
(l : is_colimit (cofork.of_π h w)) :
is_colimit (cofork.of_π (G.map h) (by simp only [←G.map_comp, w]) : cofork (G.map f) (G.map g)) :=
is_colimit_map_cocone_cofork_equiv G w (preserves_colimit.preserves l)
/-- The property of reflecting coequalizers expressed in terms of coforks. -/
def is_colimit_of_is_colimit_cofork_map [reflects_colimit (parallel_pair f g) G]
(l : is_colimit (cofork.of_π (G.map h) (by simp only [←G.map_comp, w])
: cofork (G.map f) (G.map g))) :
is_colimit (cofork.of_π h w) :=
reflects_colimit.reflects ((is_colimit_map_cocone_cofork_equiv G w).symm l)
variables (f g) [has_coequalizer f g]
/--
If `G` preserves coequalizers and `C` has them, then the cofork constructed of the mapped morphisms
of a cofork is a colimit.
-/
def is_colimit_of_has_coequalizer_of_preserves_colimit
[preserves_colimit (parallel_pair f g) G] :
is_colimit (cofork.of_π (G.map (coequalizer.π f g)) _) :=
is_colimit_cofork_map_of_is_colimit G _ (coequalizer_is_coequalizer f g)
variables [has_coequalizer (G.map f) (G.map g)]
/--
If the coequalizer comparison map for `G` at `(f,g)` is an isomorphism, then `G` preserves the
coequalizer of `(f,g)`.
-/
def of_iso_comparison [i : is_iso (coequalizer_comparison f g G)] :
preserves_colimit (parallel_pair f g) G :=
begin
apply preserves_colimit_of_preserves_colimit_cocone (coequalizer_is_coequalizer f g),
apply (is_colimit_map_cocone_cofork_equiv _ _).symm _,
apply is_colimit.of_point_iso (colimit.is_colimit (parallel_pair (G.map f) (G.map g))),
apply i,
end
variables [preserves_colimit (parallel_pair f g) G]
/--
If `G` preserves the coequalizer of `(f,g)`, then the coequalizer comparison map for `G` at `(f,g)`
is an isomorphism.
-/
def preserves_coequalizer.iso :
coequalizer (G.map f) (G.map g) ≅ G.obj (coequalizer f g) :=
is_colimit.cocone_point_unique_up_to_iso
(colimit.is_colimit _)
(is_colimit_of_has_coequalizer_of_preserves_colimit G f g)
@[simp]
lemma preserves_coequalizer.iso_hom :
(preserves_coequalizer.iso G f g).hom = coequalizer_comparison f g G :=
rfl
instance : is_iso (coequalizer_comparison f g G) :=
begin
rw ← preserves_coequalizer.iso_hom,
apply_instance
end
instance map_π_epi : epi (G.map (coequalizer.π f g)) :=
⟨λ W h k, by { rw ←ι_comp_coequalizer_comparison, apply (cancel_epi _).1, apply epi_comp }⟩
@[reassoc]
lemma map_π_preserves_coequalizer_inv :
G.map (coequalizer.π f g) ≫ (preserves_coequalizer.iso G f g).inv =
coequalizer.π (G.map f) (G.map g) :=
begin
rw [←ι_comp_coequalizer_comparison_assoc, ←preserves_coequalizer.iso_hom,
iso.hom_inv_id, comp_id],
end
@[reassoc]
lemma map_π_preserves_coequalizer_inv_desc
{W : D} (k : G.obj Y ⟶ W) (wk : G.map f ≫ k = G.map g ≫ k) :
G.map (coequalizer.π f g) ≫ (preserves_coequalizer.iso G f g).inv ≫ coequalizer.desc k wk = k :=
by rw [←category.assoc, map_π_preserves_coequalizer_inv, coequalizer.π_desc]
@[reassoc]
lemma map_π_preserves_coequalizer_inv_colim_map
{X' Y' : D} (f' g' : X' ⟶ Y') [has_coequalizer f' g'] (p : G.obj X ⟶ X') (q : G.obj Y ⟶ Y')
(wf : (G.map f) ≫ q = p ≫ f') (wg : (G.map g) ≫ q = p ≫ g') :
G.map (coequalizer.π f g) ≫ (preserves_coequalizer.iso G f g).inv ≫
colim_map (parallel_pair_hom (G.map f) (G.map g) f' g' p q wf wg) =
q ≫ coequalizer.π f' g' :=
by rw [←category.assoc, map_π_preserves_coequalizer_inv, ι_colim_map, parallel_pair_hom_app_one]
@[reassoc]
lemma map_π_preserves_coequalizer_inv_colim_map_desc
{X' Y' : D} (f' g' : X' ⟶ Y') [has_coequalizer f' g'] (p : G.obj X ⟶ X') (q : G.obj Y ⟶ Y')
(wf : (G.map f) ≫ q = p ≫ f') (wg : (G.map g) ≫ q = p ≫ g')
{Z' : D} (h : Y' ⟶ Z') (wh : f' ≫ h = g' ≫ h) :
G.map (coequalizer.π f g) ≫ (preserves_coequalizer.iso G f g).inv ≫
colim_map (parallel_pair_hom (G.map f) (G.map g) f' g' p q wf wg) ≫
coequalizer.desc h wh =
q ≫ h :=
begin
slice_lhs 1 3 { rw map_π_preserves_coequalizer_inv_colim_map },
slice_lhs 2 3 { rw coequalizer.π_desc },
end
/-- Any functor preserves coequalizers of split pairs. -/
@[priority 1]
instance preserves_split_coequalizers (f g : X ⟶ Y) [has_split_coequalizer f g] :
preserves_colimit (parallel_pair f g) G :=
begin
apply preserves_colimit_of_preserves_colimit_cocone
((has_split_coequalizer.is_split_coequalizer f g).is_coequalizer),
apply (is_colimit_map_cocone_cofork_equiv G _).symm
((has_split_coequalizer.is_split_coequalizer f g).map G).is_coequalizer,
end
end coequalizers
end category_theory.limits
|
ab06224d7bc2abdc31821f20a5eedbda5a7b3c68 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/offsetIssue.lean | 8f92ca0d85d18aba8c328a39f67bdb01ad5b83a6 | [
"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 | 441 | lean | def BV (n : Nat) := { a : Array Bool // a.size = n }
axiom foo {n m : Nat} (a : BV n) (b : BV m) : BV (n - m)
def test (x1 : BV 30002) (x2 : BV 30001) (y1 : BV 60004) (y2 : BV 60003) : Prop :=
foo x1 x2 = without_expected_type foo y1 y2
@[elab_without_expected_type]
axiom foo2 {n m : Nat} (a : BV n) (b : BV m) : BV (n - m)
def test2 (x1 : BV 30002) (x2 : BV 30001) (y1 : BV 60004) (y2 : BV 60003) : Prop :=
foo2 x1 x2 = foo2 y1 y2
|
be75cca65f3aff4d583ab2ad4dadfc72a71c7b05 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/rat/denumerable.lean | 6c0d6a97d7e8c812ca7b5a32756b9dff21f9df10 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 1,296 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import set_theory.cardinal.basic
/-!
# Denumerability of ℚ
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file proves that ℚ is infinite, denumerable, and deduces that it has cardinality `omega`.
-/
namespace rat
open denumerable
instance : infinite ℚ :=
infinite.of_injective (coe : ℕ → ℚ) nat.cast_injective
private def denumerable_aux : ℚ ≃ { x : ℤ × ℕ // 0 < x.2 ∧ x.1.nat_abs.coprime x.2 } :=
{ to_fun := λ x, ⟨⟨x.1, x.2⟩, x.3, x.4⟩,
inv_fun := λ x, ⟨x.1.1, x.1.2, x.2.1, x.2.2⟩,
left_inv := λ ⟨_, _, _, _⟩, rfl,
right_inv := λ ⟨⟨_, _⟩, _, _⟩, rfl }
/-- **Denumerability of the Rational Numbers** -/
instance : denumerable ℚ :=
begin
let T := { x : ℤ × ℕ // 0 < x.2 ∧ x.1.nat_abs.coprime x.2 },
letI : infinite T := infinite.of_injective _ denumerable_aux.injective,
letI : encodable T := subtype.encodable,
letI : denumerable T := of_encodable_of_infinite T,
exact denumerable.of_equiv T denumerable_aux
end
end rat
open_locale cardinal
lemma cardinal.mk_rat : #ℚ = ℵ₀ := by simp
|
36a70fd760ceccfb43a39821f7c06d5b17bc83f2 | 59e5eb5b0b465111c363c967363a954891f7de2e | /Leancode/fptp/src/algebra.lean | 0b54c7af06b470cfab4b7ef61118791e323199ae | [
"Apache-2.0"
] | permissive | mukeshtiwari/formal-fptp | 1987fb35e5594ea047b1b2f7e36a804dece6272f | 883a6a245cfdce7af0fc3cc2c3769281fe60afa0 | refs/heads/master | 1,650,002,177,929 | 1,585,742,596,000 | 1,585,742,596,000 | 249,091,342 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,110 | lean | import
tactic.find tactic.omega
data.vector list_lemma
namespace AlgStructures
class monoid {A : Type*} (e : A) (f : A → A → A) [decidable_eq A] :=
(Hassoc : ∀ a b c : A, f a (f b c) = f (f a b) c)
(Hidl : ∀ a : A, f e a = a)
(Hidr : ∀ a : A, f a e = a)
class group {A : Type*} (e : A) (f : A → A → A)
(inv : A → A) [Hdec : decidable_eq A] :=
(Hmon : @monoid A e f Hdec)
(Hinvl : ∀ x, f (inv x) x = e)
(Hinvr : ∀ x, f x (inv x) = e)
class abelian_group {A : Type*} (e : A) (f : A → A → A)
(inv : A → A) [Hdec : decidable_eq A] :=
(Hg : @group A e f inv Hdec)
(Hcomm : ∀ x y : A, f x y = f y x)
/- assuming a ring with identity -/
class ring {A : Type*} (zero one : A)
(Radd Rsub Rmult : A → A → A) (Ropp : A → A)
[Hdec : decidable_eq A] :=
(Habel : @abelian_group A zero Radd Ropp Hdec)
(Hmon : @monoid A one Rmult Hdec)
(Ring_distr_l : forall x y z, Rmult (Radd x y) z =
Radd (Rmult x z) (Rmult y z))
(Ring_distr_r : forall x y z, Rmult z (Radd x y) =
Radd (Rmult z x) (Rmult z y))
(Ring_sub_def : forall x y, Rsub x y = Radd x (Ropp y))
class commutative_ring {A : Type*} (zero one : A)
(Radd Rsub Rmult : A → A → A) (Ropp : A → A)
[Hdec : decidable_eq A] :=
(Hring : @ring A zero one Radd Rsub Rmult Ropp Hdec)
(Hinv : forall x y : A, Rmult x y = Rmult y x)
class field {A : Type*} (zero one : A)
(Fadd Fsub Fmult Fdiv : A → A → A) (Fopp Finv : A → A)
[Hdec : decidable_eq A] :=
(Hcring : @commutative_ring A zero one Fadd Fsub Fmult
Fopp Hdec)
(Hfinvl : forall x : A, x ≠ zero -> Fmult (Finv x) x = one)
(Hfinvr : forall x : A, x ≠ zero -> Fmult x (Finv x) = one)
(Hzinv : Finv zero = zero)
class vector_space {F : Type*} {V : Type*} (Fzero Fone : F)
(Fadd Fsub Fmult Fdiv : F → F → F) (Fopp Finv : F → F)
(Vone : V) (Vdot : V → V → V) (Vinv : V → V) (Vop : F → V → V)
[Hfdec : decidable_eq F] [Hgdec : decidable_eq V] :=
(Hfield : @field F Fzero Fone Fadd Fsub Fmult Fdiv Fopp Finv Hfdec)
(Hgroup : @abelian_group V Vone Vdot Vinv Hgdec)
(Hcomp : forall (x y : F) (v : V), Vop x (Vop y v) = Vop (Fmult x y) v)
(Hdistr_fv : forall x v₁ v₂, Vop x (Vdot v₁ v₂) = Vdot (Vop x v₁) (Vop x v₂))
(Hdistr_vf : forall x y v, Vop (Fadd x y) v = Vdot (Vop x v) (Vop y v))
(Hfoneid : forall v, Vop Fone v = v)
(Hfzerid : forall v, Vop Fzero v = Vone)
end AlgStructures
namespace Elgamal
open AlgStructures
section
variables
{F : Type*}
{G : Type*}
(Fzero Fone : F)
(Fadd Fsub Fmult Fdiv : F → F → F)
(Fopp Finv : F → F)
(Gone : G)
(Gdot : G → G → G)
(Ginv : G → G)
(Gop : F → G → G)
[Hfdec : decidable_eq F]
[Hgdec : decidable_eq G]
[Hvec : @vector_space F G
Fzero Fone Fadd
Fsub Fmult Fdiv
Fopp Finv Gone
Gdot Ginv Gop
Hfdec Hgdec]
variables
(g : G) /- generator -/
(x : F) /- private key -/
(h : G) /- publick key -/
(Hp : h = Gop x g) /- g = h^x -/
/- When suppling Gdot, map m => g^m -/
def elgamal_enc (r : F) (m : G) :=
(Gop r g, Gdot m (Gop r h))
def elgamal_dec (c : G × G) : G :=
Gdot c.2 (Ginv (Gop x c.1))
def elgamal_reenc (r : F) (c : G × G) :=
(Gdot c.1 (Gop r g), Gdot c.2 (Gop r h))
def ciphertext_mult (c d : G × G) :=
(Gdot c.1 d.1, Gdot c.2 d.2)
def vector_elegamal_enc {n : ℕ} :
vector F n -> vector G n ->
vector (G × G) n
| ⟨rs, Hr⟩ ⟨ms, Hm⟩ :=
⟨list.zip_with (elgamal_enc Gdot Gop g h) rs ms,
begin
have Ht : list.length rs = list.length ms :=
begin rw [Hm, Hr] end, rw <- Hr,
apply zip_with_len_l, exact Ht
end⟩
def vector_elegamal_dec {n : ℕ} :
vector (G × G) n -> vector G n
| ⟨cs, Hc⟩ :=
⟨list.map (elgamal_dec Gdot Ginv Gop x) cs,
by rw <- Hc; apply map_with_len_l⟩
def vector_elegamal_reenc {n : ℕ} :
vector F n -> vector (G × G) n ->
vector (G × G) n
| ⟨rs, Hr⟩ ⟨cs, Hc⟩ :=
⟨list.zip_with (elgamal_reenc Gdot Gop g h) rs cs,
begin
have Ht : list.length rs = list.length cs :=
begin rw [Hc, Hr] end,
rw <- Hr, apply zip_with_len_l, exact Ht
end⟩
def vector_ciphertext_mult {n : ℕ} :
vector (G × G) n -> vector (G × G) n ->
vector (G × G) n
| ⟨cs₁ , Hc₁⟩ ⟨cs₂, Hc₂⟩ :=
⟨list.zip_with (ciphertext_mult Gdot) cs₁ cs₂,
begin
have Ht : list.length cs₁ = list.length cs₂ :=
begin rw [Hc₁, Hc₂] end,
rw <- Hc₁, apply zip_with_len_l, exact Ht,
end⟩
include Hvec Hp
theorem decryption_correct (r : F) (m : G) (c : G × G):
c = elgamal_enc Gdot Gop g h r m ->
elgamal_dec Gdot Ginv Gop x c = m :=
begin
intro Hc, rw [Hc, Hp],
unfold elgamal_enc elgamal_dec,
simp,
destruct Hvec, intros, clear a,
repeat {rw Hcomp},
destruct Hgroup, intros, clear a,
destruct Hfield, intros, clear a,
destruct Hcring, intros, clear a,
rw Hinv,
destruct Hring, intros, clear a,
destruct Hg, intros, clear a,
destruct Hmon_1, intros, clear a,
rw [<- Hassoc, Hinvr, Hidr]
end
theorem reencryption_decrypt_correct
(r₁ r₂ : F) (m : G) (c₁ c₂ : G × G) :
c₁ = elgamal_enc Gdot Gop g h r₁ m ->
c₂ = elgamal_reenc Gdot Gop g h r₂ c₁ ->
elgamal_dec Gdot Ginv Gop x c₂ = m :=
begin
intros Hc₁ Hc₂,
rw [Hc₂, Hc₁, Hp],
unfold elgamal_dec
elgamal_reenc elgamal_enc,
simp, sorry
end
theorem ciphertext_mult_homomorphic
(r₁ r₂ : F) (m₁ m₂ : G) (c₁ c₂ c₃ : G × G) :
c₁ = elgamal_enc Gdot Gop g h r₁ m₁ ->
c₂ = elgamal_enc Gdot Gop g h r₂ m₂ ->
c₃ = ciphertext_mult Gdot c₁ c₂ ->
elgamal_dec Gdot Ginv Gop x c₃ = Gdot m₁ m₂ :=
begin
intros Hc₁ Hc₂ Hc₃,
rw [Hc₃, Hc₂, Hc₁, Hp],
unfold elgamal_enc
ciphertext_mult elgamal_dec,
simp, /- feed to sat solver-/
sorry
end
end
end Elgamal |
d82f6d06a4e82b580ee90702b661b17e81d3a97d | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /test/norm_num_ext.lean | 5f75b9d9e575161ef47e15d14186ce74ddf5efe7 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 13,495 | lean | /-
Copyright (c) 2021 Mario Carneiro All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.big_operators.norm_num
import data.nat.squarefree
import data.int.gcd
import data.nat.fib
import data.nat.prime
import data.nat.sqrt_norm_num
import analysis.special_functions.pow.real
import number_theory.legendre_symbol.norm_num
/-!
# Tests for `norm_num` extensions
-/
-- coverage tests
example : nat.sqrt 0 = 0 := by norm_num
example : nat.sqrt 1 = 1 := by norm_num
example : nat.sqrt 2 = 1 := by norm_num
example : nat.sqrt 3 = 1 := by norm_num
example : nat.sqrt 4 = 2 := by norm_num
example : nat.sqrt 9 = 3 := by norm_num
example : nat.sqrt 10 = 3 := by norm_num
example : nat.sqrt 100 = 10 := by norm_num
example : nat.sqrt 120 = 10 := by norm_num
example : nat.sqrt 121 = 11 := by norm_num
example : nat.coprime 1 2 := by norm_num
example : nat.coprime 2 1 := by norm_num
example : ¬ nat.coprime 0 0 := by norm_num
example : ¬ nat.coprime 0 3 := by norm_num
example : ¬ nat.coprime 2 0 := by norm_num
example : nat.coprime 2 3 := by norm_num
example : ¬ nat.coprime 2 4 := by norm_num
example : nat.gcd 1 2 = 1 := by norm_num
example : nat.gcd 2 1 = 1 := by norm_num
example : nat.gcd 0 0 = 0 := by norm_num
example : nat.gcd 0 3 = 3 := by norm_num
example : nat.gcd 2 0 = 2 := by norm_num
example : nat.gcd 2 3 = 1 := by norm_num
example : nat.gcd 2 4 = 2 := by norm_num
example : nat.lcm 1 2 = 2 := by norm_num
example : nat.lcm 2 1 = 2 := by norm_num
example : nat.lcm 0 0 = 0 := by norm_num
example : nat.lcm 0 3 = 0 := by norm_num
example : nat.lcm 2 0 = 0 := by norm_num
example : nat.lcm 2 3 = 6 := by norm_num
example : nat.lcm 2 4 = 4 := by norm_num
example : int.gcd 2 3 = 1 := by norm_num
example : int.gcd (-2) 3 = 1 := by norm_num
example : int.gcd 2 (-3) = 1 := by norm_num
example : int.gcd (-2) (-3) = 1 := by norm_num
example : int.lcm 2 3 = 6 := by norm_num
example : int.lcm (-2) 3 = 6 := by norm_num
example : int.lcm 2 (-3) = 6 := by norm_num
example : int.lcm (-2) (-3) = 6 := by norm_num
example : ¬ nat.prime 0 := by norm_num
example : ¬ nat.prime 1 := by norm_num
example : nat.prime 2 := by norm_num
example : nat.prime 3 := by norm_num
example : ¬ nat.prime 4 := by norm_num
example : nat.prime 5 := by norm_num
example : nat.prime 109 := by norm_num
example : nat.prime 1277 := by norm_num
example : ¬ nat.prime 1000000000000000000000000000000000000000000000000 := by norm_num
example : nat.min_fac 0 = 2 := by norm_num
example : nat.min_fac 1 = 1 := by norm_num
example : nat.min_fac 2 = 2 := by norm_num
example : nat.min_fac 3 = 3 := by norm_num
example : nat.min_fac 4 = 2 := by norm_num
example : nat.min_fac 121 = 11 := by norm_num
example : nat.min_fac 221 = 13 := by norm_num
example : nat.factors 0 = [] := by norm_num
example : nat.factors 1 = [] := by norm_num
example : nat.factors 2 = [2] := by norm_num
example : nat.factors 3 = [3] := by norm_num
example : nat.factors 4 = [2, 2] := by norm_num
example : nat.factors 12 = [2, 2, 3] := by norm_num
example : nat.factors 221 = [13, 17] := by norm_num
-- randomized tests
example : nat.gcd 35 29 = 1 := by norm_num
example : int.gcd 35 29 = 1 := by norm_num
example : nat.lcm 35 29 = 1015 := by norm_num
example : int.gcd 35 29 = 1 := by norm_num
example : nat.coprime 35 29 := by norm_num
example : nat.gcd 80 2 = 2 := by norm_num
example : int.gcd 80 2 = 2 := by norm_num
example : nat.lcm 80 2 = 80 := by norm_num
example : int.gcd 80 2 = 2 := by norm_num
example : ¬ nat.coprime 80 2 := by norm_num
example : nat.gcd 19 17 = 1 := by norm_num
example : int.gcd 19 17 = 1 := by norm_num
example : nat.lcm 19 17 = 323 := by norm_num
example : int.gcd 19 17 = 1 := by norm_num
example : nat.coprime 19 17 := by norm_num
example : nat.gcd 11 18 = 1 := by norm_num
example : int.gcd 11 18 = 1 := by norm_num
example : nat.lcm 11 18 = 198 := by norm_num
example : int.gcd 11 18 = 1 := by norm_num
example : nat.coprime 11 18 := by norm_num
example : nat.gcd 23 73 = 1 := by norm_num
example : int.gcd 23 73 = 1 := by norm_num
example : nat.lcm 23 73 = 1679 := by norm_num
example : int.gcd 23 73 = 1 := by norm_num
example : nat.coprime 23 73 := by norm_num
example : nat.gcd 73 68 = 1 := by norm_num
example : int.gcd 73 68 = 1 := by norm_num
example : nat.lcm 73 68 = 4964 := by norm_num
example : int.gcd 73 68 = 1 := by norm_num
example : nat.coprime 73 68 := by norm_num
example : nat.gcd 28 16 = 4 := by norm_num
example : int.gcd 28 16 = 4 := by norm_num
example : nat.lcm 28 16 = 112 := by norm_num
example : int.gcd 28 16 = 4 := by norm_num
example : ¬ nat.coprime 28 16 := by norm_num
example : nat.gcd 44 98 = 2 := by norm_num
example : int.gcd 44 98 = 2 := by norm_num
example : nat.lcm 44 98 = 2156 := by norm_num
example : int.gcd 44 98 = 2 := by norm_num
example : ¬ nat.coprime 44 98 := by norm_num
example : nat.gcd 21 79 = 1 := by norm_num
example : int.gcd 21 79 = 1 := by norm_num
example : nat.lcm 21 79 = 1659 := by norm_num
example : int.gcd 21 79 = 1 := by norm_num
example : nat.coprime 21 79 := by norm_num
example : nat.gcd 93 34 = 1 := by norm_num
example : int.gcd 93 34 = 1 := by norm_num
example : nat.lcm 93 34 = 3162 := by norm_num
example : int.gcd 93 34 = 1 := by norm_num
example : nat.coprime 93 34 := by norm_num
example : ¬ nat.prime 912 := by norm_num
example : nat.min_fac 912 = 2 := by norm_num
example : nat.factors 912 = [2, 2, 2, 2, 3, 19] := by norm_num
example : ¬ nat.prime 681 := by norm_num
example : nat.min_fac 681 = 3 := by norm_num
example : nat.factors 681 = [3, 227] := by norm_num
example : ¬ nat.prime 728 := by norm_num
example : nat.min_fac 728 = 2 := by norm_num
example : nat.factors 728 = [2, 2, 2, 7, 13] := by norm_num
example : ¬ nat.prime 248 := by norm_num
example : nat.min_fac 248 = 2 := by norm_num
example : nat.factors 248 = [2, 2, 2, 31] := by norm_num
example : ¬ nat.prime 682 := by norm_num
example : nat.min_fac 682 = 2 := by norm_num
example : nat.factors 682 = [2, 11, 31] := by norm_num
example : ¬ nat.prime 115 := by norm_num
example : nat.min_fac 115 = 5 := by norm_num
example : nat.factors 115 = [5, 23] := by norm_num
example : ¬ nat.prime 824 := by norm_num
example : nat.min_fac 824 = 2 := by norm_num
example : nat.factors 824 = [2, 2, 2, 103] := by norm_num
example : ¬ nat.prime 942 := by norm_num
example : nat.min_fac 942 = 2 := by norm_num
example : nat.factors 942 = [2, 3, 157] := by norm_num
example : ¬ nat.prime 34 := by norm_num
example : nat.min_fac 34 = 2 := by norm_num
example : nat.factors 34 = [2, 17] := by norm_num
example : ¬ nat.prime 754 := by norm_num
example : nat.min_fac 754 = 2 := by norm_num
example : nat.factors 754 = [2, 13, 29] := by norm_num
example : ¬ nat.prime 663 := by norm_num
example : nat.min_fac 663 = 3 := by norm_num
example : nat.factors 663 = [3, 13, 17] := by norm_num
example : ¬ nat.prime 923 := by norm_num
example : nat.min_fac 923 = 13 := by norm_num
example : nat.factors 923 = [13, 71] := by norm_num
example : ¬ nat.prime 77 := by norm_num
example : nat.min_fac 77 = 7 := by norm_num
example : nat.factors 77 = [7, 11] := by norm_num
example : ¬ nat.prime 162 := by norm_num
example : nat.min_fac 162 = 2 := by norm_num
example : nat.factors 162 = [2, 3, 3, 3, 3] := by norm_num
example : ¬ nat.prime 669 := by norm_num
example : nat.min_fac 669 = 3 := by norm_num
example : nat.factors 669 = [3, 223] := by norm_num
example : ¬ nat.prime 476 := by norm_num
example : nat.min_fac 476 = 2 := by norm_num
example : nat.factors 476 = [2, 2, 7, 17] := by norm_num
example : nat.prime 251 := by norm_num
example : nat.min_fac 251 = 251 := by norm_num
example : nat.factors 251 = [251] := by norm_num
example : ¬ nat.prime 129 := by norm_num
example : nat.min_fac 129 = 3 := by norm_num
example : nat.factors 129 = [3, 43] := by norm_num
example : ¬ nat.prime 471 := by norm_num
example : nat.min_fac 471 = 3 := by norm_num
example : nat.factors 471 = [3, 157] := by norm_num
example : ¬ nat.prime 851 := by norm_num
example : nat.min_fac 851 = 23 := by norm_num
example : nat.factors 851 = [23, 37] := by norm_num
example : ¬ squarefree 0 := by norm_num
example : squarefree 1 := by norm_num
example : squarefree 2 := by norm_num
example : squarefree 3 := by norm_num
example : ¬ squarefree 4 := by norm_num
example : squarefree 5 := by norm_num
example : squarefree 6 := by norm_num
example : squarefree 7 := by norm_num
example : ¬ squarefree 8 := by norm_num
example : ¬ squarefree 9 := by norm_num
example : squarefree 10 := by norm_num
example : squarefree (2*3*5*17) := by norm_num
example : ¬ squarefree (2*3*5*5*17) := by norm_num
example : squarefree 251 := by norm_num
example : squarefree (3 : ℤ) :=
begin
-- `norm_num` should fail on this example, instead of producing an incorrect proof.
success_if_fail { norm_num },
exact irreducible.squarefree (prime.irreducible
(int.prime_iff_nat_abs_prime.mpr (by norm_num)))
end
example : @squarefree ℕ multiplicative.monoid 1 :=
begin
-- `norm_num` should fail on this example, instead of producing an incorrect proof.
success_if_fail { norm_num },
-- the statement was deliberately wacky, let's fix it
change squarefree (multiplicative.of_add 1 : multiplicative ℕ),
rintros x ⟨dx, hd⟩,
revert x dx,
rw multiplicative.of_add.surjective.forall₂,
intros x dx h,
simp_rw [←of_add_add, multiplicative.of_add.injective.eq_iff] at h,
cases x,
{ simp [is_unit_one], exact is_unit_one },
{ simp only [nat.succ_add, nat.add_succ] at h,
cases h },
end
example : nat.fib 0 = 0 := by norm_num
example : nat.fib 1 = 1 := by norm_num
example : nat.fib 2 = 1 := by norm_num
example : nat.fib 3 = 2 := by norm_num
example : nat.fib 4 = 3 := by norm_num
example : nat.fib 5 = 5 := by norm_num
example : nat.fib 6 = 8 := by norm_num
example : nat.fib 7 = 13 := by norm_num
example : nat.fib 8 = 21 := by norm_num
example : nat.fib 9 = 34 := by norm_num
example : nat.fib 10 = 55 := by norm_num
example : nat.fib 37 = 24157817 := by norm_num
example : nat.fib 64 = 10610209857723 := by norm_num
example : nat.fib 100 + nat.fib 101 = nat.fib 102 := by norm_num
example : (2 : ℝ) ^ (3 : ℝ) = 8 := by norm_num
example : (1 : ℝ) ^ (20 : ℝ) = 1 := by norm_num
example : (2 : ℝ) ^ (-3 : ℝ) = 1/8 := by norm_num
section big_operators
variables {α : Type*} [comm_ring α]
open_locale big_operators
-- Lists:
example : ([1, 2, 1, 3]).sum = 7 := by norm_num [-list.sum_cons]
example : (([1, 2, 1, 3] : list ℚ).map (λ i, i^2)).sum = 15 := by norm_num [-list.map]
example : (list.range 10).sum = 45 := by norm_num [-list.range_succ]
example : (list.fin_range 10).sum = 45 := by norm_num [-list.fin_range_succ_eq_map]
-- Multisets:
example : (1 ::ₘ 2 ::ₘ 1 ::ₘ 3 ::ₘ {}).sum = 7 := by norm_num [-multiset.sum_cons]
example : ((1 ::ₘ 2 ::ₘ 1 ::ₘ 3 ::ₘ {}).map (λ i, i^2)).sum = 15 := by norm_num [-multiset.map_cons]
example : (({1, 2, 1, 3} : multiset ℚ).map (λ i, i^2)).sum = 15 := by norm_num [-multiset.map_cons]
example : (multiset.range 10).sum = 45 := by norm_num [-multiset.map_cons, -multiset.range_succ]
example : (↑[1, 2, 1, 3] : multiset ℕ).sum = 7 := by norm_num
-- Finsets:
example (f : fin 0 → α) : ∑ i : fin 0, f i = 0 := by norm_num
example (f : ℕ → α) : ∑ i in (∅ : finset ℕ), f i = 0 := by norm_num
example (f : fin 3 → α) : ∑ i : fin 3, f i = f 0 + f 1 + f 2 := by norm_num; ring
example (f : fin 4 → α) : ∑ i : fin 4, f i = f 0 + f 1 + f 2 + f 3 := by norm_num; ring
example (f : ℕ → α) : ∑ i in {0, 1, 2}, f i = f 0 + f 1 + f 2 := by norm_num; ring
example (f : ℕ → α) : ∑ i in {0, 2, 2, 3, 1, 0}, f i = f 0 + f 1 + f 2 + f 3 := by norm_num; ring
example (f : ℕ → α) : ∑ i in {0, 2, 2 - 3, 3 - 1, 1, 0}, f i = f 0 + f 1 + f 2 := by norm_num; ring
example : (∑ i in finset.range 10, (i^2 : ℕ)) = 285 := by norm_num
example : (∑ i in finset.Icc 5 10, (i^2 : ℕ)) = 355 := by norm_num
example : (∑ i in finset.Ico 5 10, (i^2 : ℕ)) = 255 := by norm_num
example : (∑ i in finset.Ioc 5 10, (i^2 : ℕ)) = 330 := by norm_num
example : (∑ i in finset.Ioo 5 10, (i^2 : ℕ)) = 230 := by norm_num
example : (∑ i : ℤ in finset.Ioo (-5) 5, i^2) = 60 := by norm_num
example (f : ℕ → α) : ∑ i in finset.mk {0, 1, 2} dec_trivial, f i = f 0 + f 1 + f 2 :=
by norm_num; ring
-- Combined with other `norm_num` extensions:
example : ∏ i in finset.range 9, nat.sqrt (i + 1) = 96 := by norm_num
example : ∏ i in {1, 4, 9, 16}, nat.sqrt i = 24 := by norm_num
example : ∏ i in finset.Icc 0 8, nat.sqrt (i + 1) = 96 := by norm_num
-- Nested operations:
example : ∑ i : fin 2, ∑ j : fin 2, ![![0, 1], ![2, 3]] i j = 6 := by norm_num
end big_operators
section jacobi
-- Jacobi and Legendre symbols
open_locale number_theory_symbols
example : J(123 | 335) = -1 := by norm_num
example : J(-2345 | 6789) = -1 := by norm_num
example : J(-1 | 1655801) = 1 := by norm_num
example : J(-102334155 | 165580141) = -1 := by norm_num
example : J(58378362899022564339483801989973056405585914719065 |
53974350278769849773003214636618718468638750007307) = -1 := by norm_num
example : J(3 + 4 | 3 * 5) = -1 := by norm_num
example : J(J(-1 | 7) | 11) = -1 := by norm_num
instance prime_1000003 : fact (nat.prime 1000003) := ⟨by norm_num⟩
example : legendre_sym 1000003 7 = -1 := by norm_num
end jacobi
|
c6ddf8ad9b91a4ff4860122769be7bd84f032010 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/group_theory/congruence.lean | 6bd131d651b82293c061b220f951fcb3f790e2c7 | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 48,196 | lean | /-
Copyright (c) 2019 Amelia Livingston. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Amelia Livingston
-/
import data.setoid.basic
import algebra.group.pi
import algebra.group.prod
import data.equiv.mul_add
import group_theory.submonoid.operations
/-!
# Congruence relations
This file defines congruence relations: equivalence relations that preserve a binary operation,
which in this case is multiplication or addition. The principal definition is a `structure`
extending a `setoid` (an equivalence relation), and the inductive definition of the smallest
congruence relation containing a binary relation is also given (see `con_gen`).
The file also proves basic properties of the quotient of a type by a congruence relation, and the
complete lattice of congruence relations on a type. We then establish an order-preserving bijection
between the set of congruence relations containing a congruence relation `c` and the set of
congruence relations on the quotient by `c`.
The second half of the file concerns congruence relations on monoids, in which case the
quotient by the congruence relation is also a monoid. There are results about the universal
property of quotients of monoids, and the isomorphism theorems for monoids.
## Implementation notes
The inductive definition of a congruence relation could be a nested inductive type, defined using
the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work.
A nested inductive definition could conceivably shorten proofs, because they would allow invocation
of the corresponding lemmas about `eqv_gen`.
The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]`
respectively as these tags do not work on a structure coerced to a binary relation.
There is a coercion from elements of a type to the element's equivalence class under a
congruence relation.
A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which
membership is an equivalence relation, but whilst this fact is established in the file, it is not
used, since this perspective adds more layers of definitional unfolding.
## Tags
congruence, congruence relation, quotient, quotient by congruence relation, monoid,
quotient monoid, isomorphism theorems
-/
variables (M : Type*) {N : Type*} {P : Type*}
set_option old_structure_cmd true
open function setoid
/-- A congruence relation on a type with an addition is an equivalence relation which
preserves addition. -/
structure add_con [has_add M] extends setoid M :=
(add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z))
/-- A congruence relation on a type with a multiplication is an equivalence relation which
preserves multiplication. -/
@[to_additive add_con] structure con [has_mul M] extends setoid M :=
(mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z))
/-- The equivalence relation underlying an additive congruence relation. -/
add_decl_doc add_con.to_setoid
/-- The equivalence relation underlying a multiplicative congruence relation. -/
add_decl_doc con.to_setoid
variables {M}
/-- The inductively defined smallest additive congruence relation containing a given binary
relation. -/
inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop
| of : Π x y, r x y → add_con_gen.rel x y
| refl : Π x, add_con_gen.rel x x
| symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x
| trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z
| add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z)
/-- The inductively defined smallest multiplicative congruence relation containing a given binary
relation. -/
@[to_additive add_con_gen.rel]
inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop
| of : Π x y, r x y → con_gen.rel x y
| refl : Π x, con_gen.rel x x
| symm : Π x y, con_gen.rel x y → con_gen.rel y x
| trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z
| mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z)
/-- The inductively defined smallest multiplicative congruence relation containing a given binary
relation. -/
@[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing
a given binary relation."]
def con_gen [has_mul M] (r : M → M → Prop) : con M :=
⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩, con_gen.rel.mul⟩
namespace con
section
variables [has_mul M] [has_mul N] [has_mul P] (c : con M)
@[to_additive]
instance : inhabited (con M) :=
⟨con_gen empty_relation⟩
/-- A coercion from a congruence relation to its underlying binary relation. -/
@[to_additive "A coercion from an additive congruence relation to its underlying binary relation."]
instance : has_coe_to_fun (con M) := ⟨_, λ c, λ x y, c.r x y⟩
@[simp, to_additive] lemma rel_eq_coe (c : con M) : c.r = c := rfl
/-- Congruence relations are reflexive. -/
@[to_additive "Additive congruence relations are reflexive."]
protected lemma refl (x) : c x x := c.2.1 x
/-- Congruence relations are symmetric. -/
@[to_additive "Additive congruence relations are symmetric."]
protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.2.2.1 h
/-- Congruence relations are transitive. -/
@[to_additive "Additive congruence relations are transitive."]
protected lemma trans : ∀ {x y z}, c x y → c y z → c x z :=
λ _ _ _ h, c.2.2.2 h
/-- Multiplicative congruence relations preserve multiplication. -/
@[to_additive "Additive congruence relations preserve addition."]
protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) :=
λ _ _ _ _ h1 h2, c.3 h1 h2
@[simp, to_additive] lemma rel_mk {r : M → M → Prop} {h₁ h₂ a b} :
con.mk r h₁ h₂ a b ↔ r a b :=
iff.rfl
/-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M`
`x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/
@[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation
`c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."]
instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩
variables {c}
/-- The map sending a congruence relation to its underlying binary relation is injective. -/
@[to_additive "The map sending an additive congruence relation to its underlying binary relation
is injective."]
lemma ext' {c d : con M} (H : c.r = d.r) : c = d :=
by cases c; cases d; simpa using H
/-- Extensionality rule for congruence relations. -/
@[ext, to_additive "Extensionality rule for additive congruence relations."]
lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d :=
ext' $ by ext; apply H
attribute [ext] add_con.ext
/-- The map sending a congruence relation to its underlying equivalence relation is injective. -/
@[to_additive "The map sending an additive congruence relation to its underlying equivalence
relation is injective."]
lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d :=
ext $ ext_iff.1 H
/-- Iff version of extensionality rule for congruence relations. -/
@[to_additive "Iff version of extensionality rule for additive congruence relations."]
lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d :=
⟨ext, λ h _ _, h ▸ iff.rfl⟩
/-- Two congruence relations are equal iff their underlying binary relations are equal. -/
@[to_additive "Two additive congruence relations are equal iff their underlying binary relations
are equal."]
lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d :=
⟨ext', λ h, h ▸ rfl⟩
/-- The kernel of a multiplication-preserving function as a congruence relation. -/
@[to_additive "The kernel of an addition-preserving function as an additive congruence relation."]
def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M :=
{ r := λ x y, f x = f y,
iseqv := ⟨λ _, rfl, λ _ _, eq.symm, λ _ _ _, eq.trans⟩,
mul' := λ _ _ _ _ h1 h2, by rw [h, h1, h2, h] }
/-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and
`d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁`
by `c` and `x₂` is related to `y₂` by `d`. -/
@[to_additive prod "Given types with additions `M, N`, the product of two congruence relations
`c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁`
is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."]
protected def prod (c : con M) (d : con N) : con (M × N) :=
{ mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid }
/-- The product of an indexed collection of congruence relations. -/
@[to_additive "The product of an indexed collection of additive congruence relations."]
def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)]
(C : Π i, con (f i)) : con (Π i, f i) :=
{ mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid }
variables (c)
@[simp, to_additive] lemma coe_eq : c.to_setoid.r = c := rfl
-- Quotients
/-- Defining the quotient by a congruence relation of a type with a multiplication. -/
@[to_additive "Defining the quotient by an additive congruence relation of a type with
an addition."]
protected def quotient := quotient $ c.to_setoid
/-- Coercion from a type with a multiplication to its quotient by a congruence relation.
See Note [use has_coe_t]. -/
@[to_additive "Coercion from a type with an addition to its quotient by an additive congruence
relation", priority 0]
instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩
/-- The quotient by a decidable congruence relation has decidable equality. -/
@[to_additive "The quotient by a decidable additive congruence relation has decidable equality."]
instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient :=
@quotient.decidable_eq M c.to_setoid d
@[simp, to_additive] lemma quot_mk_eq_coe {M : Type*} [has_mul M] (c : con M) (x : M) :
quot.mk c x = (x : c.quotient) :=
rfl
/-- The function on the quotient by a congruence relation `c` induced by a function that is
constant on `c`'s equivalence classes. -/
@[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c`
induced by a function that is constant on `c`'s equivalence classes."]
protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β)
(h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h
/-- The binary function on the quotient by a congruence relation `c` induced by a binary function
that is constant on `c`'s equivalence classes. -/
@[elab_as_eliminator, to_additive "The binary function on the quotient by a congruence relation `c`
induced by a binary function that is constant on `c`'s equivalence classes."]
protected def lift_on₂ {β} {c : con M} (q r : c.quotient) (f : M → M → β)
(h : ∀ a₁ a₂ b₁ b₂, c a₁ b₁ → c a₂ b₂ → f a₁ a₂ = f b₁ b₂) : β := quotient.lift_on₂' q r f h
/-- A version of `quotient.hrec_on₂'` for quotients by `con`. -/
@[to_additive "A version of `quotient.hrec_on₂'` for quotients by `add_con`."]
protected def hrec_on₂ {cM : con M} {cN : con N} {φ : cM.quotient → cN.quotient → Sort*}
(a : cM.quotient) (b : cN.quotient)
(f : Π (x : M) (y : N), φ x y) (h : ∀ x y x' y', cM x x' → cN y y' → f x y == f x' y') :
φ a b :=
quotient.hrec_on₂' a b f h
@[simp, to_additive] lemma hrec_on₂_coe {cM : con M} {cN : con N}
{φ : cM.quotient → cN.quotient → Sort*} (a : M) (b : N)
(f : Π (x : M) (y : N), φ x y) (h : ∀ x y x' y', cM x x' → cN y y' → f x y == f x' y') :
con.hrec_on₂ ↑a ↑b f h = f a b :=
rfl
variables {c}
/-- The inductive principle used to prove propositions about the elements of a quotient by a
congruence relation. -/
@[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about
the elements of a quotient by an additive congruence relation."]
protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q :=
quotient.induction_on' q H
/-- A version of `con.induction_on` for predicates which take two arguments. -/
@[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take
two arguments."]
protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop}
(p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q :=
quotient.induction_on₂' p q H
variables (c)
/-- Two elements are related by a congruence relation `c` iff they are represented by the same
element of the quotient by `c`. -/
@[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they
are represented by the same element of the quotient by `c`."]
protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b :=
quotient.eq'
/-- The multiplication induced on the quotient by a congruence relation on a type with a
multiplication. -/
@[to_additive "The addition induced on the quotient by an additive congruence relation on a type
with an addition."]
instance has_mul : has_mul c.quotient :=
⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient))
$ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩
/-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/
@[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation
`c` equals `c`."]
lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c :=
ext $ λ x y, quotient.eq'
variables {c}
/-- The coercion to the quotient of a congruence relation commutes with multiplication (by
definition). -/
@[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with
addition (by definition)."]
lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl
/-- Definition of the function on the quotient by a congruence relation `c` induced by a function
that is constant on `c`'s equivalence classes. -/
@[simp, to_additive "Definition of the function on the quotient by an additive congruence
relation `c` induced by a function that is constant on `c`'s equivalence classes."]
protected lemma lift_on_coe {β} (c : con M) (f : M → β)
(h : ∀ a b, c a b → f a = f b) (x : M) :
con.lift_on (x : c.quotient) f h = f x := rfl
/-- Makes an isomorphism of quotients by two congruence relations, given that the relations are
equal. -/
@[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations,
given that the relations are equal."]
protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient :=
{ map_mul' := λ x y, by rcases x; rcases y; refl,
..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h }
-- The complete lattice of congruence relations on a type
/-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`,
`x` is related to `y` by `d` if `x` is related to `y` by `c`. -/
@[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff
`∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."]
instance : has_le (con M) := ⟨λ c d, ∀ ⦃x y⦄, c x y → d x y⟩
/-- Definition of `≤` for congruence relations. -/
@[to_additive "Definition of `≤` for additive congruence relations."]
theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl
/-- The infimum of a set of congruence relations on a given type with a multiplication. -/
@[to_additive "The infimum of a set of additive congruence relations on a given type with
an addition."]
instance : has_Inf (con M) :=
⟨λ S, ⟨λ x y, ∀ c : con M, c ∈ S → c x y,
⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc,
λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩,
λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩
/-- The infimum of a set of congruence relations is the same as the infimum of the set's image
under the map to the underlying equivalence relation. -/
@[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of
the set's image under the map to the underlying equivalence relation."]
lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) :=
setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS,
λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩
/-- The infimum of a set of congruence relations is the same as the infimum of the set's image
under the map to the underlying binary relation. -/
@[to_additive "The infimum of a set of additive congruence relations is the same as the infimum
of the set's image under the map to the underlying binary relation."]
lemma Inf_def (S : set (con M)) : (Inf S).r = Inf (r '' S) :=
by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl }
@[to_additive]
instance : partial_order (con M) :=
{ le := (≤),
lt := λ c d, c ≤ d ∧ ¬d ≤ c,
le_refl := λ c _ _, id,
le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h,
lt_iff_le_not_le := λ _ _, iff.rfl,
le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ }
/-- The complete lattice of congruence relations on a given type with a multiplication. -/
@[to_additive "The complete lattice of additive congruence relations on a given type with
an addition."]
instance : complete_lattice (con M) :=
{ inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid).1, (c.to_setoid ⊓ d.to_setoid).2,
λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩,
inf_le_left := λ _ _ _ _ h, h.1,
inf_le_right := λ _ _ _ _ h, h.2,
le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩,
top := { mul' := by tauto, ..setoid.complete_lattice.top},
le_top := λ _ _ _ h, trivial,
bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot},
bot_le := λ c x y h, h ▸ c.refl x,
.. complete_lattice_of_Inf (con M) $ assume s,
⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ }
/-- The infimum of two congruence relations equals the infimum of the underlying binary
operations. -/
@[to_additive "The infimum of two additive congruence relations equals the infimum of the
underlying binary operations."]
lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl
/-- Definition of the infimum of two congruence relations. -/
@[to_additive "Definition of the infimum of two additive congruence relations."]
theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl
/-- The inductively defined smallest congruence relation containing a binary relation `r` equals
the infimum of the set of congruence relations containing `r`. -/
@[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation
containing a binary relation `r` equals the infimum of the set of additive congruence relations
containing `r`."]
theorem con_gen_eq (r : M → M → Prop) :
con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} :=
le_antisymm
(λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _)
(λ _ _ _ _ _, con.trans _)
$ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc)
(Inf_le (λ _ _, con_gen.rel.of _ _))
/-- The smallest congruence relation containing a binary relation `r` is contained in any
congruence relation containing `r`. -/
@[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary
relation `r` is contained in any additive congruence relation containing `r`."]
theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → c.r x y) :
con_gen r ≤ c :=
by rw con_gen_eq; exact Inf_le h
/-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation
containing `s` contains the smallest congruence relation containing `r`. -/
@[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the
smallest additive congruence relation containing `s` contains the smallest additive congruence
relation containing `r`."]
theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) :
con_gen r ≤ con_gen s :=
con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr
/-- Congruence relations equal the smallest congruence relation in which they are contained. -/
@[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest
additive congruence relation in which they are contained."]
lemma con_gen_of_con (c : con M) : con_gen c = c :=
le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of
/-- The map sending a binary relation to the smallest congruence relation in which it is
contained is idempotent. -/
@[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive
congruence relation in which it is contained is idempotent."]
lemma con_gen_idem (r : M → M → Prop) :
con_gen (con_gen r) = con_gen r :=
con_gen_of_con _
/-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing
the binary relation '`x` is related to `y` by `c` or `d`'. -/
@[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the
smallest additive congruence relation containing the binary relation '`x` is related to `y`
by `c` or `d`'."]
lemma sup_eq_con_gen (c d : con M) :
c ⊔ d = con_gen (λ x y, c x y ∨ d x y) :=
begin
rw con_gen_eq,
apply congr_arg Inf,
simp only [le_def, or_imp_distrib, ← forall_and_distrib]
end
/-- The supremum of two congruence relations equals the smallest congruence relation containing
the supremum of the underlying binary operations. -/
@[to_additive "The supremum of two additive congruence relations equals the smallest additive
congruence relation containing the supremum of the underlying binary operations."]
lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) :=
by rw sup_eq_con_gen; refl
/-- The supremum of a set of congruence relations `S` equals the smallest congruence relation
containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by
`c`'. -/
@[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations `S` equals
the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S`
such that `x` is related to `y` by `c`'."]
lemma Sup_eq_con_gen (S : set (con M)) :
Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) :=
begin
rw con_gen_eq,
apply congr_arg Inf,
ext,
exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2,
λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩,
end
/-- The supremum of a set of congruence relations is the same as the smallest congruence relation
containing the supremum of the set's image under the map to the underlying binary relation. -/
@[to_additive "The supremum of a set of additive congruence relations is the same as the smallest
additive congruence relation containing the supremum of the set's image under the map to the
underlying binary relation."]
lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (r '' S)) :=
begin
rw [Sup_eq_con_gen, Sup_image],
congr' with x y,
simp only [Sup_image, supr_apply, supr_Prop_eq, exists_prop, rel_eq_coe]
end
variables (M)
/-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into
binary relations on `M`. -/
@[to_additive "There is a Galois insertion of additive congruence relations on a type with
an addition `M` into binary relations on `M`."]
protected noncomputable def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen r :=
{ choice := λ r h, con_gen r,
gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩,
le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x,
choice_eq := λ _ _, rfl }
variables {M} (c)
/-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s
image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)`
by a congruence relation `c`.' -/
@[to_additive "Given a function `f`, the smallest additive congruence relation containing the
binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the
elements of `f⁻¹(y)` by an additive congruence relation `c`.'"]
def map_gen (f : M → N) : con N :=
con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b
/-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a
congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the
elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/
@[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in
an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined
by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"]
def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c)
(hf : surjective f) : con N :=
{ mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩,
⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩,
..c.to_setoid.map_of_surjective f h hf }
/-- A specialization of 'the smallest congruence relation containing a congruence relation `c`
equals `c`'. -/
@[to_additive "A specialization of 'the smallest additive congruence relation containing
an additive congruence relation `c` equals `c`'."]
lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y)
(h : mul_ker f H ≤ c) (hf : surjective f) :
c.map_gen f = c.map_of_surjective f H h hf :=
by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl
/-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a
multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain
defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/
@[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`,
an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain
defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "]
def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M :=
{ mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2,
..c.to_setoid.comap f }
@[simp, to_additive] lemma comap_rel {f : M → N} (H : ∀ x y, f (x * y) = f x * f y)
{c : con N} {x y : M} :
comap f H c x y ↔ c (f x) (f y) :=
iff.rfl
section
open quotient
/-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving
bijection between the set of congruence relations containing `c` and the congruence relations
on the quotient of `M` by `c`. -/
@[to_additive "Given an additive congruence relation `c` on a type `M` with an addition,
the order-preserving bijection between the set of additive congruence relations containing `c` and
the additive congruence relations on the quotient of `M` by `c`."]
def correspondence : {d // c ≤ d} ≃o (con c.quotient) :=
{ to_fun := λ d, d.1.map_of_surjective coe _
(by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid,
inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h,
show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩,
left_inv := λ d, subtype.ext_iff_val.2 $ ext $ λ _ _,
⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in
d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy,
λ h, ⟨_, _, rfl, rfl, h⟩⟩,
right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤
comap (coe : M → c.quotient) (λ x y, rfl) d :=
λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in
ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H,
con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩,
map_rel_iff' := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, rfl, rfl, hs⟩ in
t.1.trans (t.1.symm $ t.2 $ eq_rel.1 hx) $ t.1.trans ht $ t.2 $ eq_rel.1 hy,
λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩⟩ }
end
end
section mul_one_class
variables {M} [mul_one_class M] [mul_one_class N] [mul_one_class P] (c : con M)
/-- The quotient of a monoid by a congruence relation is a monoid. -/
@[to_additive "The quotient of an `add_monoid` by an additive congruence relation is
an `add_monoid`."]
instance mul_one_class : mul_one_class c.quotient :=
{ one := ((1 : M) : c.quotient),
mul := (*),
mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _,
one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ }
variables {c}
/-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the
monoid's 1. -/
@[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation
is the equivalence class of the `add_monoid`'s 0."]
lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl
variables (M c)
/-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/
@[to_additive "The `add_submonoid` of `M × M` defined by an additive congruence
relation on an `add_monoid` `M`."]
protected def submonoid : submonoid (M × M) :=
{ carrier := { x | c x.1 x.2 },
one_mem' := c.iseqv.1 1,
mul_mem' := λ _ _, c.mul }
variables {M c}
/-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership
is an equivalence relation. -/
@[to_additive "The additive congruence relation on an `add_monoid` `M` from
an `add_submonoid` of `M × M` for which membership is an equivalence relation."]
def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M :=
{ r := λ x y, (x, y) ∈ N,
iseqv := H,
mul' := λ _ _ _ _, N.mul_mem }
/-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose
elements are `(x, y)` such that `x` is related to `y` by `c`. -/
@[to_additive "Coercion from a congruence relation `c` on an `add_monoid` `M`
to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x`
is related to `y` by `c`."]
instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩
@[to_additive] lemma mem_coe {c : con M} {x y} :
(x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl
@[to_additive]
theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d :=
ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H
@[to_additive]
lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d :=
⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩
/-- The kernel of a monoid homomorphism as a congruence relation. -/
@[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."]
def ker (f : M →* P) : con M := mul_ker f f.3
/-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/
@[simp, to_additive "The definition of the additive congruence relation defined by an `add_monoid`
homomorphism's kernel."]
lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl
/-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/
@[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation
(namely 0)."]
instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩
variables (c)
/-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/
@[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive
congruence relation."]
def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩
variables (x y : M)
/-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence
relation `c` equals `c`. -/
@[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by
an additive congruence relation `c` equals `c`."]
lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq
variables {c}
/-- The natural homomorphism from a monoid to its quotient by a congruence relation is
surjective. -/
@[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence
relation is surjective."]
lemma mk'_surjective : surjective c.mk' :=
quotient.surjective_quotient_mk'
@[simp, to_additive] lemma coe_mk' : (c.mk' : M → c.quotient) = coe := rfl
/-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are
those in the preimage of `f(x)` under `f`. -/
@[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of
an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "]
lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} :=
set.ext $ λ x,
⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm,
λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩
/-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence
relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with
`f`. -/
@[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation
`c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s
quotient homomorphism composed with `f`."]
lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) :=
ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl
variables (c) (f : M →* P)
/-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a
homomorphism constant on `c`'s equivalence classes. -/
@[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence
relation `c` induced by a homomorphism constant on `c`'s equivalence classes."]
def lift (H : c ≤ ker f) : c.quotient →* P :=
{ to_fun := λ x, con.lift_on x f $ λ _ _ h, H h,
map_one' := by rw ←f.map_one; refl,
map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl }
variables {c f}
/-- The diagram describing the universal property for quotients of monoids commutes. -/
@[to_additive "The diagram describing the universal property for quotients of `add_monoid`s
commutes."]
lemma lift_mk' (H : c ≤ ker f) (x) :
c.lift f H (c.mk' x) = f x := rfl
/-- The diagram describing the universal property for quotients of monoids commutes. -/
@[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s
commutes."]
lemma lift_coe (H : c ≤ ker f) (x : M) :
c.lift f H x = f x := rfl
/-- The diagram describing the universal property for quotients of monoids commutes. -/
@[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s
commutes."]
theorem lift_comp_mk' (H : c ≤ ker f) :
(c.lift f H).comp c.mk' = f := by ext; refl
/-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the
homomorphism on the quotient induced by `f` composed with the natural map from the monoid to
the quotient. -/
@[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive
congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the
natural map from the `add_monoid` to the quotient."]
lemma lift_apply_mk' (f : c.quotient →* P) :
c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f :=
by ext; rcases x; refl
/-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they
are equal on elements that are coercions from the monoid. -/
@[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation
are equal if they are equal on elements that are coercions from the `add_monoid`."]
lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g :=
begin
rw [←lift_apply_mk' f, ←lift_apply_mk' g],
congr' 1,
exact monoid_hom.ext_iff.2 h,
end
/-- The uniqueness part of the universal property for quotients of monoids. -/
@[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."]
theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P)
(Hg : g.comp c.mk' = f) : g = c.lift f H :=
lift_funext g (c.lift f H) $ λ x, by { subst f, refl }
/-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s
equivalence classes, `f` has the same image as the homomorphism that `f` induces on the
quotient. -/
@[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f`
constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces
on the quotient."]
theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange :=
submonoid.ext $ λ x, ⟨by rintros ⟨⟨y⟩, hy⟩; exact ⟨y, hy⟩, λ ⟨y, hy⟩, ⟨↑y, hy⟩⟩
/-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes
induce a surjective homomorphism on `c`'s quotient. -/
@[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence
relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."]
lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) :
surjective (c.lift f h) :=
λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩
variables (c f)
/-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence
relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/
@[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f`
is the unique additive congruence relation on `M` whose induced map from the quotient of `M`
to `P` is injective."]
lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) :
ker f = c :=
to_setoid_inj $ ker_eq_lift_of_injective f H h
variables {c}
/-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/
@[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel
of an `add_monoid` homomorphism."]
def ker_lift : (ker f).quotient →* P :=
(ker f).lift f $ λ _ _, id
variables {f}
/-- The diagram described by the universal property for quotients of monoids, when the congruence
relation is the kernel of the homomorphism, commutes. -/
@[simp, to_additive "The diagram described by the universal property for quotients
of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism,
commutes."]
lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl
/-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has
the same image as `f`. -/
@[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism
on the quotient by `f`'s kernel has the same image as `f`."]
lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange :=
lift_range $ λ _ _, id
/-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/
@[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient
by `f`'s kernel."]
lemma ker_lift_injective (f : M →* P) : injective (ker_lift f) :=
λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2
/-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient
map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/
@[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d`
contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient
by `d`."]
def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient :=
c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from
(mk'_ker d).symm ▸ h hc
/-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of
the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient
map. -/
@[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d`
contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d`
induced by `d`'s quotient map."]
lemma map_apply {c d : con M} (h : c ≤ d) (x) :
c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl
variables (c)
/-- The first isomorphism theorem for monoids. -/
@[to_additive "The first isomorphism theorem for `add_monoid`s."]
noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange :=
{ map_mul' := monoid_hom.map_mul _,
..equiv.of_bijective
((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _
$ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).mrange_restrict) $
(equiv.bijective _).comp
⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections,
λ ⟨w, z, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ }
/-- The first isomorphism theorem for monoids in the case of a homomorphism with right inverse. -/
@[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a homomorphism
with right inverse.", simps]
def quotient_ker_equiv_of_right_inverse (f : M →* P) (g : P → M)
(hf : function.right_inverse g f) :
(ker f).quotient ≃* P :=
{ to_fun := ker_lift f,
inv_fun := coe ∘ g,
left_inv := λ x, ker_lift_injective _ (by rw [function.comp_app, ker_lift_mk, hf]),
right_inv := hf,
.. ker_lift f }
/-- The first isomorphism theorem for monoids in the case of a surjective homomorphism.
For a `computable` version, see `con.quotient_ker_equiv_of_right_inverse`.
-/
@[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective
homomorphism.
For a `computable` version, see `add_con.quotient_ker_equiv_of_right_inverse`.
"]
noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) :
(ker f).quotient ≃* P :=
quotient_ker_equiv_of_right_inverse _ _ hf.has_right_inverse.some_spec
/-- The second isomorphism theorem for monoids. -/
@[to_additive "The second isomorphism theorem for `add_monoid`s."]
noncomputable def comap_quotient_equiv (f : N →* M) :
(comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange :=
(con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f
/-- The third isomorphism theorem for monoids. -/
@[to_additive "The third isomorphism theorem for `add_monoid`s."]
def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) :
(ker (c.map d h)).quotient ≃* d.quotient :=
{ map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b,
show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl,
..quotient_quotient_equiv_quotient c.to_setoid d.to_setoid h }
end mul_one_class
section monoids
/-- The quotient of a monoid by a congruence relation is a monoid. -/
@[to_additive "The quotient of an `add_monoid` by an additive congruence relation is
an `add_monoid`."]
instance monoid {M : Type*} [monoid M] (c : con M): monoid c.quotient :=
{ one := ((1 : M) : c.quotient),
mul := (*),
mul_assoc := λ x y z, quotient.induction_on₃' x y z
$ λ _ _ _, congr_arg coe $ mul_assoc _ _ _,
.. c.mul_one_class }
/-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/
@[to_additive "The quotient of an `add_comm_monoid` by an additive congruence
relation is an `add_comm_monoid`."]
instance comm_monoid {M : Type*} [comm_monoid M] (c : con M) :
comm_monoid c.quotient :=
{ mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm],
..c.monoid}
end monoids
section groups
variables {M} [group M] [group N] [group P] (c : con M)
/-- Multiplicative congruence relations preserve inversion. -/
@[to_additive "Additive congruence relations preserve negation."]
protected lemma inv : ∀ {w x}, c w x → c w⁻¹ x⁻¹ :=
λ x y h, by simpa using c.symm (c.mul (c.mul (c.refl x⁻¹) h) (c.refl y⁻¹))
/-- The inversion induced on the quotient by a congruence relation on a type with a
inversion. -/
@[to_additive "The negation induced on the quotient by an additive congruence relation on a type
with an negation."]
instance has_inv : has_inv c.quotient :=
⟨λ x, quotient.lift_on' x (λ w, ((w⁻¹ : M) : c.quotient))
$ λ x y h, c.eq.2 $ c.inv h⟩
/-- The quotient of a group by a congruence relation is a group. -/
@[to_additive "The quotient of an `add_group` by an additive congruence relation is
an `add_group`."]
instance group : group c.quotient :=
{ inv := λ x, x⁻¹,
mul_left_inv := λ x, show x⁻¹ * x = 1,
from quotient.induction_on' x $ λ _, congr_arg coe $ mul_left_inv _,
.. con.monoid c}
end groups
section units
variables {α : Type*} [monoid M] {c : con M}
/-- In order to define a function `units (con.quotient c) → α` on the units of `con.quotient c`,
where `c : con M` is a multiplicative congruence on a monoid, it suffices to define a function `f`
that takes elements `x y : M` with proofs of `c (x * y) 1` and `c (y * x) 1`, and returns an element
of `α` provided that `f x y _ _ = f x' y' _ _` whenever `c x x'` and `c y y'`. -/
@[to_additive lift_on_add_units] def lift_on_units (u : units c.quotient)
(f : Π (x y : M), c (x * y) 1 → c (y * x) 1 → α)
(Hf : ∀ x y hxy hyx x' y' hxy' hyx', c x x' → c y y' → f x y hxy hyx = f x' y' hxy' hyx') :
α :=
begin
refine @con.hrec_on₂ M M _ _ c c (λ x y, x * y = 1 → y * x = 1 → α)
(u : c.quotient) (↑u⁻¹ : c.quotient)
(λ (x y : M) (hxy : (x * y : c.quotient) = 1) (hyx : (y * x : c.quotient) = 1),
f x y (c.eq.1 hxy) (c.eq.1 hyx)) (λ x y x' y' hx hy, _) u.3 u.4,
ext1, { rw [c.eq.2 hx, c.eq.2 hy] },
rintro Hxy Hxy' -,
ext1, { rw [c.eq.2 hx, c.eq.2 hy] },
rintro Hyx Hyx' -,
exact heq_of_eq (Hf _ _ _ _ _ _ _ _ hx hy)
end
/-- In order to define a function `units (con.quotient c) → α` on the units of `con.quotient c`,
where `c : con M` is a multiplicative congruence on a monoid, it suffices to define a function `f`
that takes elements `x y : M` with proofs of `c (x * y) 1` and `c (y * x) 1`, and returns an element
of `α` provided that `f x y _ _ = f x' y' _ _` whenever `c x x'` and `c y y'`. -/
add_decl_doc add_con.lift_on_add_units
@[simp, to_additive]
lemma lift_on_units_mk (f : Π (x y : M), c (x * y) 1 → c (y * x) 1 → α)
(Hf : ∀ x y hxy hyx x' y' hxy' hyx', c x x' → c y y' → f x y hxy hyx = f x' y' hxy' hyx')
(x y : M) (hxy hyx) :
lift_on_units ⟨(x : c.quotient), y, hxy, hyx⟩ f Hf = f x y (c.eq.1 hxy) (c.eq.1 hyx) :=
rfl
@[elab_as_eliminator, to_additive induction_on_add_units]
lemma induction_on_units {p : units c.quotient → Prop} (u : units c.quotient)
(H : ∀ (x y : M) (hxy : c (x * y) 1) (hyx : c (y * x) 1), p ⟨x, y, c.eq.2 hxy, c.eq.2 hyx⟩) :
p u :=
begin
rcases u with ⟨⟨x⟩, ⟨y⟩, h₁, h₂⟩,
exact H x y (c.eq.1 h₁) (c.eq.1 h₂)
end
end units
end con
|
3c8ad3cce64af37363c91e53a447e8c956fab34d | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /src/Lean/Server/AsyncList.lean | 6b62d00c4e356293a8376bc63c5f0c2fcccc5327 | [
"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 | 4,945 | lean | /-
Copyright (c) 2020 Wojciech Nawrocki. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki
-/
import Init.System.IO
namespace IO
universe u v
/-- An async IO list is like a lazy list but instead of being *unevaluated* `Thunk`s,
lazy tails are `Task`s *being evaluated asynchronously*. A tail can signal the end
of computation (successful or due to a failure) with a terminating value of type `ε`. -/
inductive AsyncList (ε : Type u) (α : Type v) where
| cons (hd : α) (tl : AsyncList ε α)
| asyncTail (tl : Task $ Except ε $ AsyncList ε α)
| nil
namespace AsyncList
instance : Inhabited (AsyncList ε α) := ⟨nil⟩
-- TODO(WN): tail-recursion without forcing sync?
partial def append : AsyncList ε α → AsyncList ε α → AsyncList ε α
| cons hd tl, s => cons hd (append tl s)
| asyncTail ttl, s => asyncTail (ttl.map $ Except.map (append · s))
| nil, s => s
instance : Append (AsyncList ε α) := ⟨append⟩
def ofList : List α → AsyncList ε α :=
List.foldr AsyncList.cons AsyncList.nil
instance : Coe (List α) (AsyncList ε α) := ⟨ofList⟩
private def coeErr {β} [Coe Error ε] (t : Task $ Except Error $ Except ε β) : Task (Except ε β) :=
t.map $ fun
| Except.ok v => v
| Except.error (e : Error) => Except.error (e : ε)
/-- Given a step computation `f` which takes the accumulator and either produces
another value or stops with a terminating value, produces an async stream of its
iterated applications. The initial value is *not* included. The computation can
throw IO exceptions, so to handle this the terminating value type must include
`IO.Error`.
For cooperatively cancelling an ongoing computation, we recommend referencing
a cancellation token in `f` and checking it when appropriate. -/
partial def unfoldAsync [Coe Error ε] (f : α → ExceptT ε IO α) (init : α)
: IO (AsyncList ε α) := do
let rec step (a : α) : ExceptT ε IO (AsyncList ε α) := do
let aNext ← f a
let tNext ← coeErr <$> asTask (step aNext)
return cons aNext $ asyncTail tNext
let tInit ← coeErr <$> asTask (step init)
asyncTail tInit
/-- The computed, synchronous list. If an async tail was present, returns also
its terminating value. -/
partial def getAll : AsyncList ε α → List α × Option ε
| cons hd tl =>
let ⟨l, e?⟩ := tl.getAll
⟨hd :: l, e?⟩
| nil => ⟨[], none⟩
| asyncTail tl =>
match tl.get with
| Except.ok tl => tl.getAll
| Except.error e => ⟨[], some e⟩
/-- Spawns a `Task` waiting on the prefix of elements for which `p` is true. -/
partial def waitAll [Coe Error ε] (p : α → Bool := fun _ => true) : AsyncList ε α → IO (Task (List α × Option ε))
| cons hd tl => do
if p hd then
let t ← tl.waitAll p
t.map fun ⟨l, e?⟩ => ⟨hd :: l, e?⟩
else
return Task.pure ⟨[hd], none⟩
| nil => return Task.pure ⟨[], none⟩
| asyncTail tl => do
let t : Task (Except IO.Error (List α × Option ε)) ← IO.bindTask tl fun
| Except.ok tl => Task.map Except.ok <$> tl.waitAll p
| Except.error e => return Task.pure <| Except.ok ⟨[], some e⟩
t.map fun
| Except.error e => ⟨[], some e⟩
| Except.ok v => v
/-- Spawns a `Task` acting like `List.find?` but which will wait for tail evalution
when necessary to traverse the list. If the tail terminates before a matching element
is found, the task throws the terminating value. -/
partial def waitFind? (p : α → Bool) [Coe Error ε] : AsyncList ε α → IO (Task $ Except ε $ Option α)
| nil => return Task.pure <| Except.ok none
| cons hd tl => do
if p hd then return Task.pure <| Except.ok <| some hd
else tl.waitFind? p
| asyncTail tl => do
let t ← IO.bindTask tl fun
| Except.ok tl => Task.map Except.ok <$> tl.waitFind? p
| Except.error e => return Task.pure <| Except.ok <| Except.error e
coeErr t
/-- Extends the `finishedPrefix` as far as possible. If computation was ongoing
and has finished, also returns the terminating value. -/
partial def updateFinishedPrefix : AsyncList ε α → IO (AsyncList ε α × Option ε)
| cons hd tl => do
let ⟨tl, e?⟩ ← tl.updateFinishedPrefix
pure ⟨cons hd tl, e?⟩
| nil => pure ⟨nil, none⟩
| l@(asyncTail tl) => do
if (← hasFinished tl) then
match tl.get with
| Except.ok tl => tl.updateFinishedPrefix
| Except.error e => pure ⟨nil, some e⟩
else pure ⟨l, none⟩
private partial def finishedPrefixAux : List α → AsyncList ε α → List α
| acc, cons hd tl => finishedPrefixAux (hd :: acc) tl
| acc, nil => acc
| acc, asyncTail tl => acc
/-- The longest already-computed prefix of the list. -/
def finishedPrefix : AsyncList ε α → List α :=
List.reverse ∘ (finishedPrefixAux [])
end AsyncList
end IO
|
c988f3ce4e6cbc6e289fff4aeb7aa108dd96e8ae | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/limits/shapes/functor_category.lean | e2d84559f7d9ef5624f8336ca8065510b85e0584 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 1,052 | lean | /-
Copyright (c) 2022 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.limits.shapes.finite_limits
import category_theory.limits.functor_category
/-!
# If `D` has finite (co)limits, so do the functor categories `C ⥤ D`.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
These are boiler-plate instances, in their own file as neither import otherwise needs the other.
-/
open category_theory
namespace category_theory.limits
universes v₁ v₂ u₁ u₂ w
variables {C : Type u₁} [category.{v₁} C]
variables {D : Type u₂} [category.{v₂} D]
instance functor_category_has_finite_limits [has_finite_limits D] : has_finite_limits (C ⥤ D) :=
{ out := λ J _ _, by exactI infer_instance, }
instance functor_category_has_finite_colimits [has_finite_colimits D] :
has_finite_colimits (C ⥤ D) :=
{ out := λ J _ _, by exactI infer_instance, }
end category_theory.limits
|
35de898950f97453184d0bb26018b305045e6086 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/rat/cast.lean | 07c06c6d78039afab86a619a0b229012b53b67a1 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 13,965 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import data.rat.order
import data.int.char_zero
import algebra.field.opposite
/-!
# Casts for Rational Numbers
## Summary
We define the canonical injection from ℚ into an arbitrary division ring and prove various
casting lemmas showing the well-behavedness of this injection.
## Notations
- `/.` is infix notation for `rat.mk`.
## Tags
rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting
-/
variables {F α β : Type*}
namespace rat
open_locale rat
section with_div_ring
variable [division_ring α]
/-- Construct the canonical injection from `ℚ` into an arbitrary
division ring. If the field has positive characteristic `p`,
we define `1 / p = 1 / 0 = 0` for consistency with our
division by zero convention. -/
-- see Note [coercion into rings]
@[priority 900] instance cast_coe : has_coe_t ℚ α := ⟨λ r, r.1 / r.2⟩
theorem cast_def (r : ℚ) : (r : α) = r.num / r.denom := rfl
@[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n :=
show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one]
@[simp, norm_cast] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n :=
by rw [coe_int_eq_of_int, cast_of_int]
@[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n
@[simp, norm_cast] theorem cast_zero : ((0 : ℚ) : α) = 0 :=
(cast_of_int _).trans int.cast_zero
@[simp, norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1 :=
(cast_of_int _).trans int.cast_one
theorem cast_commute (r : ℚ) (a : α) : commute ↑r a :=
(r.1.cast_commute a).div_left (r.2.cast_commute a)
theorem cast_comm (r : ℚ) (a : α) : (r : α) * a = a * r :=
(cast_commute r a).eq
theorem commute_cast (a : α) (r : ℚ) : commute a r :=
(r.cast_commute a).symm
@[norm_cast] theorem cast_mk_of_ne_zero (a b : ℤ)
(b0 : (b:α) ≠ 0) : (a /. b : α) = a / b :=
begin
have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} },
cases e : a /. b with n d h c,
have d0 : (d:α) ≠ 0,
{ intro d0,
have dd := denom_dvd a b,
cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke,
have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl},
rw [d0, zero_mul] at this, contradiction },
rw [num_denom'] at e,
have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e),
rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this,
symmetry, change (a / b : α) = n / d,
rw [div_eq_mul_inv, eq_div_iff_mul_eq d0, mul_assoc, (d.commute_cast _).eq,
← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one]
end
@[norm_cast] theorem cast_add_of_ne_zero : ∀ {m n : ℚ},
(m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin
have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl),
have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl),
rw [num_denom', num_denom', add_def d₁0' d₂0'],
suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) +
n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹,
{ rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero],
{ simpa [division_def, left_distrib, right_distrib, mul_inv_rev, d₁0, d₂0, mul_assoc] },
all_goals {simp [d₁0, d₂0]} },
rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul,
(nat.cast_commute _ _).eq], simp [d₁0, mul_assoc]
end
@[simp, norm_cast] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n
| ⟨n, d, h, c⟩ := show (↑-n / d : α) = -(n / d),
by rw [div_eq_mul_inv, div_eq_mul_inv, int.cast_neg, neg_mul_eq_neg_mul]
@[norm_cast] theorem cast_sub_of_ne_zero {m n : ℚ}
(m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n :=
have ((-n).denom : α) ≠ 0, by cases n; exact n0,
by simp [sub_eq_add_neg, (cast_add_of_ne_zero m0 this)]
@[norm_cast] theorem cast_mul_of_ne_zero : ∀ {m n : ℚ},
(m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin
have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl),
have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl),
rw [num_denom', num_denom', mul_def d₁0' d₂0'],
suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)),
{ rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero],
{ simpa [division_def, mul_inv_rev, d₁0, d₂0, mul_assoc] },
all_goals {simp [d₁0, d₂0]} },
rw [(d₁.commute_cast (_:α)).inv_right₀.eq]
end
@[simp] theorem cast_inv_nat (n : ℕ) : ((n⁻¹ : ℚ) : α) = n⁻¹ :=
begin
cases n, { simp },
simp_rw [coe_nat_eq_mk, inv_def, mk, mk_nat, dif_neg n.succ_ne_zero, mk_pnat],
simp [cast_def]
end
@[simp] theorem cast_inv_int (n : ℤ) : ((n⁻¹ : ℚ) : α) = n⁻¹ :=
begin
cases n,
{ exact cast_inv_nat _ },
{ simp only [int.cast_neg_succ_of_nat, ← nat.cast_succ, cast_neg, inv_neg, cast_inv_nat] }
end
@[norm_cast] theorem cast_inv_of_ne_zero : ∀ {n : ℚ},
(n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹
| ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin
have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl,
have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl),
rw [num_denom', inv_def],
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div];
simp [n0, d0]
end
@[norm_cast] theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0)
(nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n :=
have (n⁻¹.denom : ℤ) ∣ n.num,
by conv in n⁻¹.denom { rw [←(@num_denom n), inv_def] };
apply denom_dvd,
have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from
λ h, let ⟨k, e⟩ := this in
by have := congr_arg (coe : ℤ → α) e;
rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this,
by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def]
@[simp, norm_cast] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin
refine ⟨λ h, _, congr_arg _⟩,
have d₁0 : d₁ ≠ 0 := ne_of_gt h₁,
have d₂0 : d₂ ≠ 0 := ne_of_gt h₂,
have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0,
have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0,
rw [num_denom', num_denom'] at h ⊢,
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢,
rwa [eq_div_iff_mul_eq d₂a, division_def, mul_assoc, (d₁.cast_commute (d₂:α)).inv_left₀.eq,
← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq d₁a, eq_comm,
← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul,
int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h
end
theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α)
| m n := cast_inj.1
@[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 :=
by rw [← cast_zero, cast_inj]
theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 :=
not_congr cast_eq_zero
@[simp, norm_cast] theorem cast_add [char_zero α] (m n) :
((m + n : ℚ) : α) = m + n :=
cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp, norm_cast] theorem cast_sub [char_zero α] (m n) :
((m - n : ℚ) : α) = m - n :=
cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp, norm_cast] theorem cast_mul [char_zero α] (m n) :
((m * n : ℚ) : α) = m * n :=
cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp, norm_cast] theorem cast_bit0 [char_zero α] (n : ℚ) :
((bit0 n : ℚ) : α) = bit0 n :=
cast_add _ _
@[simp, norm_cast] theorem cast_bit1 [char_zero α] (n : ℚ) :
((bit1 n : ℚ) : α) = bit1 n :=
by rw [bit1, cast_add, cast_one, cast_bit0]; refl
variable (α)
/-- Coercion `ℚ → α` as a `ring_hom`. -/
def cast_hom [char_zero α] : ℚ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩
variable {α}
@[simp] lemma coe_cast_hom [char_zero α] : ⇑(cast_hom α) = coe := rfl
@[simp, norm_cast] theorem cast_inv [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ :=
(cast_hom α).map_inv _
@[simp, norm_cast] theorem cast_div [char_zero α] (m n) :
((m / n : ℚ) : α) = m / n :=
(cast_hom α).map_div _ _
@[norm_cast] theorem cast_mk [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b :=
by simp only [mk_eq_div, cast_div, cast_coe_int]
@[simp, norm_cast] theorem cast_pow [char_zero α] (q) (k : ℕ) :
((q ^ k : ℚ) : α) = q ^ k :=
(cast_hom α).map_pow q k
end with_div_ring
@[simp, norm_cast] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n
| ⟨n, d, h, c⟩ :=
by { rw [num_denom', cast_mk, mk_eq_div, div_nonneg_iff, div_nonneg_iff], norm_cast }
@[simp, norm_cast] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n :=
by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg]
@[simp, norm_cast] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n :=
by simpa [-cast_le] using not_congr (@cast_le α _ n m)
@[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 :=
by rw [← cast_zero, cast_le]
@[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 :=
by rw [← cast_zero, cast_lt]
@[simp, norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n
| ⟨n, d, h, c⟩ := by rw [num_denom', cast_mk, mk_eq_div]
@[simp] lemma cast_hom_rat : cast_hom ℚ = ring_hom.id ℚ :=
ring_hom.ext cast_id
@[simp, norm_cast] theorem cast_min [linear_ordered_field α] {a b : ℚ} :
(↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [h, min_def]
@[simp, norm_cast] theorem cast_max [linear_ordered_field α] {a b : ℚ} :
(↑(max a b) : α) = max a b :=
by by_cases b ≤ a; simp [h, max_def]
@[simp, norm_cast] theorem cast_abs [linear_ordered_field α] {q : ℚ} :
((|q| : ℚ) : α) = |q| :=
by simp [abs_eq_max_neg]
end rat
open rat ring_hom
lemma ring_hom.eq_rat_cast {k} [division_ring k] (f : ℚ →+* k) (r : ℚ) : f r = r :=
calc f r = f (r.1 / r.2) : by rw [← int.cast_coe_nat, ← mk_eq_div, num_denom]
... = f r.1 / f r.2 : f.map_div _ _
... = r.1 / r.2 : by rw [map_nat_cast, map_int_cast]
-- This seems to be true for a `[char_p k]` too because `k'` must have the same characteristic
-- but the proof would be much longer
@[simp] lemma map_rat_cast [division_ring α] [division_ring β] [char_zero α] [ring_hom_class F α β]
(f : F) (q : ℚ) : f q = q :=
((f : α →+* β).comp $ cast_hom α).eq_rat_cast q
lemma ring_hom.ext_rat {R : Type*} [semiring R] (f g : ℚ →+* R) : f = g :=
begin
ext r,
refine rat.num_denom_cases_on' r _,
intros a b b0,
let φ : ℤ →+* R := f.comp (int.cast_ring_hom ℚ),
let ψ : ℤ →+* R := g.comp (int.cast_ring_hom ℚ),
rw [rat.mk_eq_div, int.cast_coe_nat],
have b0' : (b:ℚ) ≠ 0 := nat.cast_ne_zero.2 b0,
have : ∀ n : ℤ, f n = g n := λ n, show φ n = ψ n, by rw [φ.ext_int ψ],
calc f (a * b⁻¹)
= f a * f b⁻¹ * (g (b:ℤ) * g b⁻¹) :
by rw [int.cast_coe_nat, ← g.map_mul, mul_inv_cancel b0', g.map_one, mul_one, f.map_mul]
... = g a * f b⁻¹ * (f (b:ℤ) * g b⁻¹) : by rw [this a, ← this b]
... = g (a * b⁻¹) :
by rw [int.cast_coe_nat, mul_assoc, ← mul_assoc (f b⁻¹),
← f.map_mul, inv_mul_cancel b0', f.map_one, one_mul, g.map_mul]
end
instance rat.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℚ →+* R) :=
⟨ring_hom.ext_rat⟩
namespace monoid_with_zero_hom
variables {M : Type*} [group_with_zero M]
/-- If `f` and `g` agree on the integers then they are equal `φ`.
See note [partially-applied ext lemmas] for why `comp` is used here. -/
@[ext]
theorem ext_rat {f g : ℚ →*₀ M}
(same_on_int : f.comp (int.cast_ring_hom ℚ).to_monoid_with_zero_hom =
g.comp (int.cast_ring_hom ℚ).to_monoid_with_zero_hom) : f = g :=
begin
have same_on_int' : ∀ k : ℤ, f k = g k := congr_fun same_on_int,
ext x,
rw [← @rat.num_denom x, rat.mk_eq_div, f.map_div, g.map_div,
same_on_int' x.num, same_on_int' x.denom],
end
/-- Positive integer values of a morphism `φ` and its value on `-1` completely determine `φ`. -/
theorem ext_rat_on_pnat {f g : ℚ →*₀ M}
(same_on_neg_one : f (-1) = g (-1)) (same_on_pnat : ∀ n : ℕ, 0 < n → f n = g n) : f = g :=
ext_rat $ ext_int' (by simpa) ‹_›
end monoid_with_zero_hom
namespace mul_opposite
variables [division_ring α]
@[simp, norm_cast] lemma op_rat_cast (r : ℚ) : op (r : α) = (↑r : αᵐᵒᵖ) :=
by rw [cast_def, div_eq_mul_inv, op_mul, op_inv, op_nat_cast, op_int_cast,
(commute.cast_int_right _ r.num).eq, cast_def, div_eq_mul_inv]
@[simp, norm_cast] lemma unop_rat_cast (r : ℚ) : unop (r : αᵐᵒᵖ) = r :=
by rw [cast_def, div_eq_mul_inv, unop_mul, unop_inv, unop_nat_cast, unop_int_cast,
(commute.cast_int_right _ r.num).eq, cast_def, div_eq_mul_inv]
end mul_opposite
|
2c354a3c88ff07a61e773010635d35e2c0e7f0b6 | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /library/algebra/group.lean | e338da33474f8f57e0f4dcee00a86be226db85d7 | [
"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 | 17,974 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: algebra.group
Authors: Jeremy Avigad, Leonardo de Moura
Various multiplicative and additive structures. Partially modeled on Isabelle's library.
-/
import logic.eq data.unit data.sigma data.prod
import algebra.function algebra.binary
open eq eq.ops -- note: ⁻¹ will be overloaded
open binary
namespace algebra
variable {A : Type}
/- overloaded symbols -/
structure has_mul [class] (A : Type) :=
(mul : A → A → A)
structure has_add [class] (A : Type) :=
(add : A → A → A)
structure has_one [class] (A : Type) :=
(one : A)
structure has_zero [class] (A : Type) :=
(zero : A)
structure has_inv [class] (A : Type) :=
(inv : A → A)
structure has_neg [class] (A : Type) :=
(neg : A → A)
infixl `*` := has_mul.mul
infixl `+` := has_add.add
postfix `⁻¹` := has_inv.inv
prefix `-` := has_neg.neg
notation 1 := !has_one.one
notation 0 := !has_zero.zero
/- semigroup -/
structure semigroup [class] (A : Type) extends has_mul A :=
(mul_assoc : ∀a b c, mul (mul a b) c = mul a (mul b c))
theorem mul.assoc [s : semigroup A] (a b c : A) : a * b * c = a * (b * c) :=
!semigroup.mul_assoc
structure comm_semigroup [class] (A : Type) extends semigroup A :=
(mul_comm : ∀a b, mul a b = mul b a)
theorem mul.comm [s : comm_semigroup A] (a b : A) : a * b = b * a :=
!comm_semigroup.mul_comm
theorem mul.left_comm [s : comm_semigroup A] (a b c : A) : a * (b * c) = b * (a * c) :=
binary.left_comm (@mul.comm A s) (@mul.assoc A s) a b c
theorem mul.right_comm [s : comm_semigroup A] (a b c : A) : (a * b) * c = (a * c) * b :=
binary.right_comm (@mul.comm A s) (@mul.assoc A s) a b c
structure left_cancel_semigroup [class] (A : Type) extends semigroup A :=
(mul_left_cancel : ∀a b c, mul a b = mul a c → b = c)
theorem mul.left_cancel [s : left_cancel_semigroup A] {a b c : A} :
a * b = a * c → b = c :=
!left_cancel_semigroup.mul_left_cancel
structure right_cancel_semigroup [class] (A : Type) extends semigroup A :=
(mul_right_cancel : ∀a b c, mul a b = mul c b → a = c)
theorem mul.right_cancel [s : right_cancel_semigroup A] {a b c : A} :
a * b = c * b → a = c :=
!right_cancel_semigroup.mul_right_cancel
/- additive semigroup -/
structure add_semigroup [class] (A : Type) extends has_add A :=
(add_assoc : ∀a b c, add (add a b) c = add a (add b c))
theorem add.assoc [s : add_semigroup A] (a b c : A) : a + b + c = a + (b + c) :=
!add_semigroup.add_assoc
structure add_comm_semigroup [class] (A : Type) extends add_semigroup A :=
(add_comm : ∀a b, add a b = add b a)
theorem add.comm [s : add_comm_semigroup A] (a b : A) : a + b = b + a :=
!add_comm_semigroup.add_comm
theorem add.left_comm [s : add_comm_semigroup A] (a b c : A) :
a + (b + c) = b + (a + c) :=
binary.left_comm (@add.comm A s) (@add.assoc A s) a b c
theorem add.right_comm [s : add_comm_semigroup A] (a b c : A) : (a + b) + c = (a + c) + b :=
binary.right_comm (@add.comm A s) (@add.assoc A s) a b c
structure add_left_cancel_semigroup [class] (A : Type) extends add_semigroup A :=
(add_left_cancel : ∀a b c, add a b = add a c → b = c)
theorem add.left_cancel [s : add_left_cancel_semigroup A] {a b c : A} :
a + b = a + c → b = c :=
!add_left_cancel_semigroup.add_left_cancel
structure add_right_cancel_semigroup [class] (A : Type) extends add_semigroup A :=
(add_right_cancel : ∀a b c, add a b = add c b → a = c)
theorem add.right_cancel [s : add_right_cancel_semigroup A] {a b c : A} :
a + b = c + b → a = c :=
!add_right_cancel_semigroup.add_right_cancel
/- monoid -/
structure monoid [class] (A : Type) extends semigroup A, has_one A :=
(one_mul : ∀a, mul one a = a) (mul_one : ∀a, mul a one = a)
theorem one_mul [s : monoid A] (a : A) : 1 * a = a := !monoid.one_mul
theorem mul_one [s : monoid A] (a : A) : a * 1 = a := !monoid.mul_one
structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A
/- additive monoid -/
structure add_monoid [class] (A : Type) extends add_semigroup A, has_zero A :=
(zero_add : ∀a, add zero a = a) (add_zero : ∀a, add a zero = a)
theorem zero_add [s : add_monoid A] (a : A) : 0 + a = a := !add_monoid.zero_add
theorem add_zero [s : add_monoid A] (a : A) : a + 0 = a := !add_monoid.add_zero
structure add_comm_monoid [class] (A : Type) extends add_monoid A, add_comm_semigroup A
/- group -/
structure group [class] (A : Type) extends monoid A, has_inv A :=
(mul_left_inv : ∀a, mul (inv a) a = one)
-- Note: with more work, we could derive the axiom one_mul
section group
variable [s : group A]
include s
theorem mul.left_inv (a : A) : a⁻¹ * a = 1 := !group.mul_left_inv
theorem inv_mul_cancel_left (a b : A) : a⁻¹ * (a * b) = b :=
calc
a⁻¹ * (a * b) = a⁻¹ * a * b : !mul.assoc⁻¹
... = 1 * b : mul.left_inv
... = b : one_mul
theorem inv_mul_cancel_right (a b : A) : a * b⁻¹ * b = a :=
calc
a * b⁻¹ * b = a * (b⁻¹ * b) : mul.assoc
... = a * 1 : mul.left_inv
... = a : mul_one
theorem inv_eq_of_mul_eq_one {a b : A} (H : a * b = 1) : a⁻¹ = b :=
calc
a⁻¹ = a⁻¹ * 1 : !mul_one⁻¹
... = a⁻¹ * (a * b) : H
... = b : inv_mul_cancel_left
theorem inv_one : 1⁻¹ = 1 := inv_eq_of_mul_eq_one (one_mul 1)
theorem inv_inv (a : A) : (a⁻¹)⁻¹ = a := inv_eq_of_mul_eq_one (mul.left_inv a)
theorem inv.inj {a b : A} (H : a⁻¹ = b⁻¹) : a = b :=
calc
a = (a⁻¹)⁻¹ : !inv_inv⁻¹
... = (b⁻¹)⁻¹ : H
... = b : inv_inv
theorem inv_eq_inv_iff_eq (a b : A) : a⁻¹ = b⁻¹ ↔ a = b :=
iff.intro (assume H, inv.inj H) (assume H, congr_arg _ H)
theorem inv_eq_one_iff_eq_one (a b : A) : a⁻¹ = 1 ↔ a = 1 :=
inv_one ▸ inv_eq_inv_iff_eq a 1
theorem eq_inv_of_eq_inv {a b : A} (H : a = b⁻¹) : b = a⁻¹ :=
H⁻¹ ▸ (inv_inv b)⁻¹
theorem eq_inv_iff_eq_inv (a b : A) : a = b⁻¹ ↔ b = a⁻¹ :=
iff.intro !eq_inv_of_eq_inv !eq_inv_of_eq_inv
theorem mul.right_inv (a : A) : a * a⁻¹ = 1 :=
calc
a * a⁻¹ = (a⁻¹)⁻¹ * a⁻¹ : inv_inv
... = 1 : mul.left_inv
theorem mul_inv_cancel_left (a b : A) : a * (a⁻¹ * b) = b :=
calc
a * (a⁻¹ * b) = a * a⁻¹ * b : !mul.assoc⁻¹
... = 1 * b : mul.right_inv
... = b : one_mul
theorem mul_inv_cancel_right (a b : A) : a * b * b⁻¹ = a :=
calc
a * b * b⁻¹ = a * (b * b⁻¹) : mul.assoc
... = a * 1 : mul.right_inv
... = a : mul_one
theorem inv_mul (a b : A) : (a * b)⁻¹ = b⁻¹ * a⁻¹ :=
inv_eq_of_mul_eq_one
(calc
a * b * (b⁻¹ * a⁻¹) = a * (b * (b⁻¹ * a⁻¹)) : mul.assoc
... = a * a⁻¹ : mul_inv_cancel_left
... = 1 : mul.right_inv)
theorem eq_of_mul_inv_eq_one {a b : A} (H : a * b⁻¹ = 1) : a = b :=
calc
a = a * b⁻¹ * b : !inv_mul_cancel_right⁻¹
... = 1 * b : H
... = b : one_mul
-- TODO: better names for the next eight theorems? (Also for additive ones.)
theorem eq_mul_inv_of_mul_eq {a b c : A} (H : a * b = c) : a = c * b⁻¹ :=
H ▸ !mul_inv_cancel_right⁻¹
theorem eq_inv_mul_of_mul_eq {a b c : A} (H : a * b = c) : b = a⁻¹ * c :=
H ▸ !inv_mul_cancel_left⁻¹
theorem inv_mul_eq_of_eq_mul {a b c : A} (H : a = b * c) : b⁻¹ * a = c :=
H⁻¹ ▸ !inv_mul_cancel_left
theorem mul_inv_eq_of_eq_mul {a b c : A} (H : a = b * c) : a * c⁻¹ = b :=
H⁻¹ ▸ !mul_inv_cancel_right
theorem eq_mul_of_mul_inv_eq {a b c : A} (H : a * b⁻¹ = c) : a = c * b :=
!inv_inv ▸ (eq_mul_inv_of_mul_eq H)
theorem eq_mul_of_inv_mul_eq {a b c : A} (H : a⁻¹ * b = c) : b = a * c :=
!inv_inv ▸ (eq_inv_mul_of_mul_eq H)
theorem mul_eq_of_eq_inv_mul {a b c : A} (H : a = b⁻¹ * c) : b * a = c :=
!inv_inv ▸ (inv_mul_eq_of_eq_mul H)
theorem mul_eq_of_eq_mul_inv {a b c : A} (H : a = b * c⁻¹) : a * c = b :=
!inv_inv ▸ (mul_inv_eq_of_eq_mul H)
theorem mul_eq_iff_eq_inv_mul (a b c : A) : a * b = c ↔ b = a⁻¹ * c :=
iff.intro eq_inv_mul_of_mul_eq mul_eq_of_eq_inv_mul
theorem mul_eq_iff_eq_mul_inv (a b c : A) : a * b = c ↔ a = c * b⁻¹ :=
iff.intro eq_mul_inv_of_mul_eq mul_eq_of_eq_mul_inv
theorem mul_left_cancel {a b c : A} (H : a * b = a * c) : b = c :=
calc b = a⁻¹ * (a * b) : inv_mul_cancel_left
... = a⁻¹ * (a * c) : H
... = c : inv_mul_cancel_left
theorem mul_right_cancel {a b c : A} (H : a * b = c * b) : a = c :=
calc a = (a * b) * b⁻¹ : mul_inv_cancel_right
... = (c * b) * b⁻¹ : H
... = c : mul_inv_cancel_right
definition group.to_left_cancel_semigroup [instance] [coercion] [reducible] : left_cancel_semigroup A :=
⦃ left_cancel_semigroup, s,
mul_left_cancel := @mul_left_cancel A s ⦄
definition group.to_right_cancel_semigroup [instance] [coercion] [reducible] : right_cancel_semigroup A :=
⦃ right_cancel_semigroup, s,
mul_right_cancel := @mul_right_cancel A s ⦄
end group
structure comm_group [class] (A : Type) extends group A, comm_monoid A
/- additive group -/
structure add_group [class] (A : Type) extends add_monoid A, has_neg A :=
(add_left_inv : ∀a, add (neg a) a = zero)
section add_group
variables [s : add_group A]
include s
theorem add.left_inv (a : A) : -a + a = 0 := !add_group.add_left_inv
theorem neg_add_cancel_left (a b : A) : -a + (a + b) = b :=
calc
-a + (a + b) = -a + a + b : add.assoc
... = 0 + b : add.left_inv
... = b : zero_add
theorem neg_add_cancel_right (a b : A) : a + -b + b = a :=
calc
a + -b + b = a + (-b + b) : add.assoc
... = a + 0 : add.left_inv
... = a : add_zero
theorem neg_eq_of_add_eq_zero {a b : A} (H : a + b = 0) : -a = b :=
calc
-a = -a + 0 : add_zero
... = -a + (a + b) : H
... = b : neg_add_cancel_left
theorem neg_zero : -0 = 0 := neg_eq_of_add_eq_zero (zero_add 0)
theorem neg_neg (a : A) : -(-a) = a := neg_eq_of_add_eq_zero (add.left_inv a)
theorem neg.inj {a b : A} (H : -a = -b) : a = b :=
calc
a = -(-a) : neg_neg
... = b : neg_eq_of_add_eq_zero (H⁻¹ ▸ (add.left_inv _))
theorem neg_eq_neg_iff_eq (a b : A) : -a = -b ↔ a = b :=
iff.intro (assume H, neg.inj H) (assume H, congr_arg _ H)
theorem neg_eq_zero_iff_eq_zero (a : A) : -a = 0 ↔ a = 0 :=
neg_zero ▸ !neg_eq_neg_iff_eq
theorem eq_neg_of_eq_neg {a b : A} (H : a = -b) : b = -a :=
H⁻¹ ▸ (neg_neg b)⁻¹
theorem eq_neg_iff_eq_neg (a b : A) : a = -b ↔ b = -a :=
iff.intro !eq_neg_of_eq_neg !eq_neg_of_eq_neg
theorem add.right_inv (a : A) : a + -a = 0 :=
calc
a + -a = -(-a) + -a : neg_neg
... = 0 : add.left_inv
theorem add_neg_cancel_left (a b : A) : a + (-a + b) = b :=
calc
a + (-a + b) = a + -a + b : add.assoc
... = 0 + b : add.right_inv
... = b : zero_add
theorem add_neg_cancel_right (a b : A) : a + b + -b = a :=
calc
a + b + -b = a + (b + -b) : add.assoc
... = a + 0 : add.right_inv
... = a : add_zero
theorem neg_add_rev (a b : A) : -(a + b) = -b + -a :=
neg_eq_of_add_eq_zero
(calc
a + b + (-b + -a) = a + (b + (-b + -a)) : add.assoc
... = a + -a : add_neg_cancel_left
... = 0 : add.right_inv)
theorem eq_add_neg_of_add_eq {a b c : A} (H : a + b = c) : a = c + -b :=
H ▸ !add_neg_cancel_right⁻¹
theorem eq_neg_add_of_add_eq {a b c : A} (H : a + b = c) : b = -a + c :=
H ▸ !neg_add_cancel_left⁻¹
theorem neg_add_eq_of_eq_add {a b c : A} (H : a = b + c) : -b + a = c :=
H⁻¹ ▸ !neg_add_cancel_left
theorem add_neg_eq_of_eq_add {a b c : A} (H : a = b + c) : a + -c = b :=
H⁻¹ ▸ !add_neg_cancel_right
theorem eq_add_of_add_neg_eq {a b c : A} (H : a + -b = c) : a = c + b :=
!neg_neg ▸ (eq_add_neg_of_add_eq H)
theorem eq_add_of_neg_add_eq {a b c : A} (H : -a + b = c) : b = a + c :=
!neg_neg ▸ (eq_neg_add_of_add_eq H)
theorem add_eq_of_eq_neg_add {a b c : A} (H : a = -b + c) : b + a = c :=
!neg_neg ▸ (neg_add_eq_of_eq_add H)
theorem add_eq_of_eq_add_neg {a b c : A} (H : a = b + -c) : a + c = b :=
!neg_neg ▸ (add_neg_eq_of_eq_add H)
theorem add_eq_iff_eq_neg_add (a b c : A) : a + b = c ↔ b = -a + c :=
iff.intro eq_neg_add_of_add_eq add_eq_of_eq_neg_add
theorem add_eq_iff_eq_add_neg (a b c : A) : a + b = c ↔ a = c + -b :=
iff.intro eq_add_neg_of_add_eq add_eq_of_eq_add_neg
theorem add_left_cancel {a b c : A} (H : a + b = a + c) : b = c :=
calc b = -a + (a + b) : !neg_add_cancel_left⁻¹
... = -a + (a + c) : H
... = c : neg_add_cancel_left
theorem add_right_cancel {a b c : A} (H : a + b = c + b) : a = c :=
calc a = (a + b) + -b : !add_neg_cancel_right⁻¹
... = (c + b) + -b : H
... = c : add_neg_cancel_right
definition add_group.to_left_cancel_semigroup [instance] [coercion] [reducible] :
add_left_cancel_semigroup A :=
⦃ add_left_cancel_semigroup, s,
add_left_cancel := @add_left_cancel A s ⦄
definition add_group.to_add_right_cancel_semigroup [instance] [coercion] [reducible] :
add_right_cancel_semigroup A :=
⦃ add_right_cancel_semigroup, s,
add_right_cancel := @add_right_cancel A s ⦄
/- sub -/
-- TODO: derive corresponding facts for div in a field
definition sub [reducible] (a b : A) : A := a + -b
infix `-` := sub
theorem sub_self (a : A) : a - a = 0 := !add.right_inv
theorem sub_add_cancel (a b : A) : a - b + b = a := !neg_add_cancel_right
theorem add_sub_cancel (a b : A) : a + b - b = a := !add_neg_cancel_right
theorem eq_of_sub_eq_zero {a b : A} (H : a - b = 0) : a = b :=
calc
a = (a - b) + b : !sub_add_cancel⁻¹
... = 0 + b : H
... = b : zero_add
theorem eq_iff_sub_eq_zero (a b : A) : a = b ↔ a - b = 0 :=
iff.intro (assume H, H ▸ !sub_self) (assume H, eq_of_sub_eq_zero H)
theorem zero_sub (a : A) : 0 - a = -a := !zero_add
theorem sub_zero (a : A) : a - 0 = a := subst (eq.symm neg_zero) !add_zero
theorem sub_neg_eq_add (a b : A) : a - (-b) = a + b := !neg_neg ▸ rfl
theorem neg_sub (a b : A) : -(a - b) = b - a :=
neg_eq_of_add_eq_zero
(calc
a - b + (b - a) = a - b + b - a : !add.assoc⁻¹
... = a - a : sub_add_cancel
... = 0 : sub_self)
theorem add_sub (a b c : A) : a + (b - c) = a + b - c := !add.assoc⁻¹
theorem sub_add_eq_sub_sub_swap (a b c : A) : a - (b + c) = a - c - b :=
calc
a - (b + c) = a + (-c - b) : neg_add_rev
... = a - c - b : !add.assoc⁻¹
theorem sub_eq_iff_eq_add (a b c : A) : a - b = c ↔ a = c + b :=
iff.intro (assume H, eq_add_of_add_neg_eq H) (assume H, add_neg_eq_of_eq_add H)
theorem eq_sub_iff_add_eq (a b c : A) : a = b - c ↔ a + c = b :=
iff.intro (assume H, add_eq_of_eq_add_neg H) (assume H, eq_add_neg_of_add_eq H)
theorem eq_iff_eq_of_sub_eq_sub {a b c d : A} (H : a - b = c - d) : a = b ↔ c = d :=
calc
a = b ↔ a - b = 0 : eq_iff_sub_eq_zero
... ↔ c - d = 0 : H ▸ !iff.refl
... ↔ c = d : iff.symm (eq_iff_sub_eq_zero c d)
end add_group
structure add_comm_group [class] (A : Type) extends add_group A, add_comm_monoid A
section add_comm_group
variable [s : add_comm_group A]
include s
theorem sub_add_eq_sub_sub (a b c : A) : a - (b + c) = a - b - c :=
!add.comm ▸ !sub_add_eq_sub_sub_swap
theorem neg_add_eq_sub (a b : A) : -a + b = b - a := !add.comm
theorem neg_add (a b : A) : -(a + b) = -a + -b := add.comm (-b) (-a) ▸ neg_add_rev a b
theorem sub_add_eq_add_sub (a b c : A) : a - b + c = a + c - b := !add.right_comm
theorem sub_sub (a b c : A) : a - b - c = a - (b + c) :=
calc
a - b - c = a + (-b + -c) : add.assoc
... = a + -(b + c) : {(neg_add b c)⁻¹}
... = a - (b + c) : rfl
theorem add_sub_add_left_eq_sub (a b c : A) : (c + a) - (c + b) = a - b :=
calc
(c + a) - (c + b) = c + a - c - b : sub_add_eq_sub_sub
... = a + c - c - b : add.comm c a
... = a - b : add_sub_cancel
end add_comm_group
/- bundled structures -/
structure Semigroup :=
(carrier : Type) (struct : semigroup carrier)
attribute Semigroup.carrier [coercion]
attribute Semigroup.struct [instance]
structure CommSemigroup :=
(carrier : Type) (struct : comm_semigroup carrier)
attribute CommSemigroup.carrier [coercion]
attribute CommSemigroup.struct [instance]
structure Monoid :=
(carrier : Type) (struct : monoid carrier)
attribute Monoid.carrier [coercion]
attribute Monoid.struct [instance]
structure CommMonoid :=
(carrier : Type) (struct : comm_monoid carrier)
attribute CommMonoid.carrier [coercion]
attribute CommMonoid.struct [instance]
structure Group :=
(carrier : Type) (struct : group carrier)
attribute Group.carrier [coercion]
attribute Group.struct [instance]
structure CommGroup :=
(carrier : Type) (struct : comm_group carrier)
attribute CommGroup.carrier [coercion]
attribute CommGroup.struct [instance]
structure AddSemigroup :=
(carrier : Type) (struct : add_semigroup carrier)
attribute AddSemigroup.carrier [coercion]
attribute AddSemigroup.struct [instance]
structure AddCommSemigroup :=
(carrier : Type) (struct : add_comm_semigroup carrier)
attribute AddCommSemigroup.carrier [coercion]
attribute AddCommSemigroup.struct [instance]
structure AddMonoid :=
(carrier : Type) (struct : add_monoid carrier)
attribute AddMonoid.carrier [coercion]
attribute AddMonoid.struct [instance]
structure AddCommMonoid :=
(carrier : Type) (struct : add_comm_monoid carrier)
attribute AddCommMonoid.carrier [coercion]
attribute AddCommMonoid.struct [instance]
structure AddGroup :=
(carrier : Type) (struct : add_group carrier)
attribute AddGroup.carrier [coercion]
attribute AddGroup.struct [instance]
structure AddCommGroup :=
(carrier : Type) (struct : add_comm_group carrier)
attribute AddCommGroup.carrier [coercion]
attribute AddCommGroup.struct [instance]
end algebra
|
50abfdcac3293d696075119e3af0c221a4192fde | ac89c256db07448984849346288e0eeffe8b20d0 | /stage0/src/Lean/Elab/Extra.lean | e18968d9f9a9692cff7701128d6286edcef805a5 | [
"Apache-2.0"
] | permissive | chepinzhang/lean4 | 002cc667f35417a418f0ebc9cb4a44559bb0ccac | 24fe2875c68549b5481f07c57eab4ad4a0ae5305 | refs/heads/master | 1,688,942,838,326 | 1,628,801,942,000 | 1,628,801,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,523 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.App
/-
Auxiliary elaboration functions: AKA custom elaborators
-/
namespace Lean.Elab.Term
open Meta
@[builtinTermElab binrel] def elabBinRel : TermElab := fun stx expectedType? => do
match (← resolveId? stx[1]) with
| some f =>
let s ← saveState
let (lhs, rhs) ← withSynthesize (mayPostpone := true) do
let mut lhs ← elabTerm stx[2] none
let mut rhs ← elabTerm stx[3] none
if lhs.isAppOfArity ``OfNat.ofNat 3 then
lhs ← ensureHasType (← inferType rhs) lhs
else if rhs.isAppOfArity ``OfNat.ofNat 3 then
rhs ← ensureHasType (← inferType lhs) rhs
return (lhs, rhs)
let lhsType ← inferType lhs
let rhsType ← inferType rhs
let (lhs, rhs) ←
try
pure (lhs, ← withRef stx[3] do ensureHasType lhsType rhs)
catch _ =>
try
pure (← withRef stx[2] do ensureHasType rhsType lhs, rhs)
catch _ =>
s.restore
-- Use default approach
let lhs ← elabTerm stx[2] none
let rhs ← elabTerm stx[3] none
let lhsType ← inferType lhs
let rhsType ← inferType rhs
pure (lhs, ← withRef stx[3] do ensureHasType lhsType rhs)
elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] expectedType? (explicit := false) (ellipsis := false)
| none => throwUnknownConstant stx[1].getId
-- TODO: move to another file?
private def hasUnknownType (e : Expr) : MetaM Bool :=
return (← inferType e).getAppFn.isMVar
@[builtinTermElab binop] def elabBinOp : TermElab := fun stx expectedType? => do
match stx with
| `(binop% $f $lhs $rhs) =>
match expectedType? with
| none =>
-- We elaborate as a normal application when expected type is not available
let stxNew ← `($f:ident $lhs $rhs)
withMacroExpansion stx stxNew <| elabTerm stxNew none
| some expectedType =>
match (← resolveId? f) with
| some f =>
let syntheticMVarsSaved := (← get).syntheticMVars
modify fun s => { s with syntheticMVars := [] }
try
let lhs ← elabTerm lhs none
let rhs ← elabTerm rhs none
if (← hasUnknownType lhs) && (← hasUnknownType rhs) then
-- We want the numerals in terms such as `(1 + 1)` `(2 * 3 + 4)` to be elaborated using the expected type
-- This is particularly important when there is no coercion from `Nat` to the expected type.
elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] expectedType (explicit := false) (ellipsis := false)
else
-- We force TC resolution and default instances to be used.
-- Note that we do not provide the expected type to make sure it can be inferred by the TC procedure. See issue #382
let r ← elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] (expectedType? := none) (explicit := false) (ellipsis := false)
synthesizeSyntheticMVarsUsingDefault
return r
finally
modify fun s => { s with syntheticMVars := s.syntheticMVars ++ syntheticMVarsSaved }
| none => throwUnknownConstant stx[1].getId
| _ => throwUnsupportedSyntax
@[builtinTermElab forInMacro] def elabForIn : TermElab := fun stx expectedType? => do
match stx with
| `(forIn% $col $init $body) =>
match (← isLocalIdent? col) with
| none => elabTerm (← `(let col := $col; forIn% col $init $body)) expectedType?
| some colFVar =>
tryPostponeIfNoneOrMVar expectedType?
let m ← getMonad expectedType?
let colType ← inferType colFVar
let elemType ← mkFreshExprMVar (mkSort (mkLevelSucc (← mkFreshLevelMVar)))
let forInInstance ←
try
mkAppM ``ForIn #[m, colType, elemType]
catch
ex => tryPostpone; throwError "failed to construct 'ForIn' instance for collection{indentExpr colType}\nand monad{indentExpr m}"
match (← trySynthInstance forInInstance) with
| LOption.some val =>
let ref ← getRef
let forInFn ← mkConst ``forIn
let namedArgs : Array NamedArg := #[
{ ref := ref, name := `m, val := Arg.expr m},
{ ref := ref, name := `ρ, val := Arg.expr colType},
{ ref := ref, name := `α, val := Arg.expr elemType},
{ ref := ref, name := `self, val := Arg.expr forInInstance},
{ ref := ref, name := `inst, val := Arg.expr val} ]
elabAppArgs forInFn #[] #[Arg.stx col, Arg.stx init, Arg.stx body] expectedType? (explicit := false) (ellipsis := false)
| LOption.undef => tryPostpone; throwFailure forInInstance
| LOption.none => throwFailure forInInstance
| _ => throwUnsupportedSyntax
where
getMonad (expectedType? : Option Expr) : TermElabM Expr := do
match expectedType? with
| none => throwError "invalid 'forIn%' notation, expected type is not available"
| some expectedType =>
match (← isTypeApp? expectedType) with
| some (m, _) => return m
| none => throwError "invalid 'forIn%' notation, expected type is not of of the form `M α`{indentExpr expectedType}"
throwFailure (forInInstance : Expr) : TermElabM Expr :=
throwError "failed to synthesize instance for 'forIn%' notation{indentExpr forInInstance}"
end Lean.Elab.Term
|
e6b4029f58db01dce60f49bf3c5ddf484647c7a1 | 9b9a16fa2cb737daee6b2785474678b6fa91d6d4 | /src/measure_theory/measure_space.lean | 8e070ba966b8062cc1890bbd664927eb1766010e | [
"Apache-2.0"
] | permissive | johoelzl/mathlib | 253f46daa30b644d011e8e119025b01ad69735c4 | 592e3c7a2dfbd5826919b4605559d35d4d75938f | refs/heads/master | 1,625,657,216,488 | 1,551,374,946,000 | 1,551,374,946,000 | 98,915,829 | 0 | 0 | Apache-2.0 | 1,522,917,267,000 | 1,501,524,499,000 | Lean | UTF-8 | Lean | false | false | 34,938 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
Measure spaces -- measures
Measures are restricted to a measurable space (associated by the type class `measurable_space`).
This allows us to prove equalities between measures by restricting to a generating set of the
measurable space.
On the other hand, the `μ.measure s` projection (i.e. the measure of `s` on the measure space `μ`)
is the _outer_ measure generated by `μ`. This gives us a unrestricted monotonicity rule and it is
somehow well-behaved on non-measurable sets.
This allows us for the `lebesgue` measure space to have the `borel` measurable space, but still be
a complete measure.
-/
import data.set order.galois_connection topology.instances.ennreal
measure_theory.outer_measure
noncomputable theory
open classical set lattice filter finset function
local attribute [instance] prop_decidable
universes u v w x
namespace measure_theory
section of_measurable
parameters {α : Type*} [measurable_space α]
parameters (m : Π (s : set α), is_measurable s → ennreal)
parameters (m0 : m ∅ is_measurable.empty = 0)
include m0
/-- Measure projection which is ∞ for non-measurable sets.
`measure'` is mainly used to derive the outer measure, for the main `measure` projection. -/
def measure' (s : set α) : ennreal := ⨅ h : is_measurable s, m s h
lemma measure'_eq {s} (h : is_measurable s) : measure' s = m s h :=
by simp [measure', h]
lemma measure'_empty : measure' ∅ = 0 :=
(measure'_eq is_measurable.empty).trans m0
lemma measure'_Union_nat
{f : ℕ → set α}
(hm : ∀i, is_measurable (f i))
(mU : m (⋃i, f i) (is_measurable.Union hm) = (∑i, m (f i) (hm i))) :
measure' (⋃i, f i) = (∑i, measure' (f i)) :=
(measure'_eq _).trans $ mU.trans $
by congr; funext i; rw measure'_eq
/-- outer measure of a measure -/
def outer_measure' : outer_measure α :=
outer_measure.of_function measure' measure'_empty
lemma measure'_Union_le_tsum_nat'
(mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)),
m (⋃i, f i) (is_measurable.Union hm) ≤ (∑i, m (f i) (hm i)))
(s : ℕ → set α) :
measure' (⋃i, s i) ≤ (∑i, measure' (s i)) :=
begin
by_cases h : ∀i, is_measurable (s i),
{ rw [measure'_eq _ _ (is_measurable.Union h),
congr_arg tsum _], {apply mU h},
funext i, apply measure'_eq _ _ (h i) },
{ cases not_forall.1 h with i hi,
exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) }
end
parameter (mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union hm) = (∑i, m (f i) (hm i)))
include mU
lemma measure'_Union
{β} [encodable β] {f : β → set α}
(hd : pairwise (disjoint on f)) (hm : ∀i, is_measurable (f i)) :
measure' (⋃i, f i) = (∑i, measure' (f i)) :=
begin
rw [encodable.Union_decode2, outer_measure.Union_aux],
{ exact measure'_Union_nat _ _
(λ n, encodable.Union_decode2_cases is_measurable.empty hm)
(mU _ (measurable_space.Union_decode2_disjoint_on hd)) },
{ apply measure'_empty },
end
lemma measure'_union {s₁ s₂ : set α}
(hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
measure' (s₁ ∪ s₂) = measure' s₁ + measure' s₂ :=
begin
rw [union_eq_Union, measure'_Union _ _ @mU
(pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩),
tsum_fintype],
change _+_ = _, simp
end
lemma measure'_mono {s₁ s₂ : set α} (h₁ : is_measurable s₁) (hs : s₁ ⊆ s₂) :
measure' s₁ ≤ measure' s₂ :=
le_infi $ λ h₂, begin
have := measure'_union _ _ @mU disjoint_diff h₁ (h₂.diff h₁),
rw union_diff_cancel hs at this,
rw ← measure'_eq m m0 _,
exact le_iff_exists_add.2 ⟨_, this⟩
end
lemma measure'_Union_le_tsum_nat : ∀ (s : ℕ → set α),
measure' (⋃i, s i) ≤ (∑i, measure' (s i)) :=
measure'_Union_le_tsum_nat' $ λ f h, begin
simp [Union_disjointed.symm] {single_pass := tt},
rw [mU (is_measurable.disjointed h) disjoint_disjointed],
refine ennreal.tsum_le_tsum (λ i, _),
rw [← measure'_eq m m0, ← measure'_eq m m0],
exact measure'_mono _ _ @mU (is_measurable.disjointed h _) (inter_subset_left _ _)
end
lemma outer_measure'_eq {s : set α} (hs : is_measurable s) :
outer_measure' s = m s hs :=
by rw ← measure'_eq m m0 hs; exact
(le_antisymm (outer_measure.of_function_le _ _ _) $
le_infi $ λ f, le_infi $ λ hf,
le_trans (measure'_mono _ _ @mU hs hf) $
measure'_Union_le_tsum_nat _ _ @mU _)
lemma outer_measure'_eq_measure' {s : set α} (hs : is_measurable s) :
outer_measure' s = measure' s :=
by rw [measure'_eq m m0 hs, outer_measure'_eq m m0 @mU hs]
end of_measurable
namespace outer_measure
variables {α : Type*} [measurable_space α] (m : outer_measure α)
def trim : outer_measure α :=
outer_measure' (λ s _, m s) m.empty
theorem trim_ge : m ≤ m.trim :=
λ s, le_infi $ λ f, le_infi $ λ hs,
le_trans (m.mono hs) $ le_trans (m.Union_nat f) $
ennreal.tsum_le_tsum $ λ i, le_infi $ λ hf, le_refl _
theorem trim_eq {s : set α} (hs : is_measurable s) : m.trim s = m s :=
le_antisymm (le_trans (of_function_le _ _ _) (infi_le _ hs)) (trim_ge _ _)
theorem trim_congr {m₁ m₂ : outer_measure α}
(H : ∀ {s : set α}, is_measurable s → m₁ s = m₂ s) :
m₁.trim = m₂.trim :=
by unfold trim; congr; funext s hs; exact H hs
theorem trim_le_trim {m₁ m₂ : outer_measure α} (H : m₁ ≤ m₂) : m₁.trim ≤ m₂.trim :=
λ s, infi_le_infi $ λ f, infi_le_infi $ λ hs,
ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _
theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔
∀ s, is_measurable s → m₁ s ≤ m₂ s :=
le_of_function.trans $ forall_congr $ λ s, le_infi_iff
theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), m t :=
begin
refine le_antisymm
(le_infi $ λ t, le_infi $ λ st, le_infi $ λ ht, _)
(le_infi $ λ f, le_infi $ λ hf, _),
{ rw ← trim_eq m ht, exact (trim m).mono st },
{ by_cases h : ∀i, is_measurable (f i),
{ refine infi_le_of_le _ (infi_le_of_le hf $
infi_le_of_le (is_measurable.Union h) _),
rw congr_arg tsum _, {exact m.Union_nat _},
funext i, exact measure'_eq _ _ (h i) },
{ cases not_forall.1 h with i hi,
exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } }
end
theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ is_measurable t}, m t.1 :=
by simp [infi_subtype, infi_and, trim_eq_infi]
theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim :=
le_antisymm (le_trim_iff.2 $ λ s hs, by simp [trim_eq _ hs, le_refl]) (trim_ge _)
theorem trim_zero : (0 : outer_measure α).trim = 0 :=
ext $ λ s, le_antisymm
(le_trans ((trim 0).mono (subset_univ s)) $
le_of_eq $ trim_eq _ is_measurable.univ)
(zero_le _)
theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim :=
ext $ λ s, begin
simp [trim_eq_infi'],
rw ennreal.infi_add_infi,
rintro ⟨t₁, st₁, ht₁⟩ ⟨t₂, st₂, ht₂⟩,
exact ⟨⟨_, subset_inter_iff.2 ⟨st₁, st₂⟩, ht₁.inter ht₂⟩,
add_le_add'
(m₁.mono' (inter_subset_left _ _))
(m₂.mono' (inter_subset_right _ _))⟩,
end
theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim :=
λ s, by simp [trim_eq_infi]; exact
λ t st ht, ennreal.tsum_le_tsum (λ i,
infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht)
end outer_measure
structure measure (α : Type*) [measurable_space α] extends outer_measure α :=
(m_Union {f : ℕ → set α} :
(∀i, is_measurable (f i)) → pairwise (disjoint on f) →
measure_of (⋃i, f i) = (∑i, measure_of (f i)))
(trimmed : to_outer_measure.trim = to_outer_measure)
/-- Measure projections for a measure space.
For measurable sets this returns the measure assigned by the `measure_of` field in `measure`.
But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and
subadditivity for all sets.
-/
instance measure.has_coe_to_fun {α} [measurable_space α] : has_coe_to_fun (measure α) :=
⟨λ _, set α → ennreal, λ m, m.to_outer_measure⟩
namespace measure
def of_measurable {α} [measurable_space α]
(m : Π (s : set α), is_measurable s → ennreal)
(m0 : m ∅ is_measurable.empty = 0)
(mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑i, m (f i) (h i))) :
measure α :=
{ m_Union := λ f hf hd,
show outer_measure' m m0 (Union f) =
∑ i, outer_measure' m m0 (f i), begin
rw [outer_measure'_eq m m0 @mU, mU hf hd],
congr, funext n, rw outer_measure'_eq m m0 @mU
end,
trimmed :=
show (outer_measure' m m0).trim = outer_measure' m m0, begin
unfold outer_measure.trim,
congr, funext s hs,
exact outer_measure'_eq m m0 @mU hs
end,
..outer_measure' m m0 }
lemma of_measurable_apply {α} [measurable_space α]
{m : Π (s : set α), is_measurable s → ennreal}
{m0 : m ∅ is_measurable.empty = 0}
{mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑i, m (f i) (h i))}
(s : set α) (hs : is_measurable s) :
of_measurable m m0 @mU s = m s hs :=
outer_measure'_eq m m0 @mU hs
@[extensionality] lemma ext {α} [measurable_space α] :
∀ {μ₁ μ₂ : measure α}, (∀s, is_measurable s → μ₁ s = μ₂ s) → μ₁ = μ₂
| ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h := by congr; rw [← h₁, ← h₂];
exact outer_measure.trim_congr h
end measure
section
variables {α : Type*} {β : Type*} [measurable_space α] {μ μ₁ μ₂ : measure α} {s s₁ s₂ : set α}
@[simp] lemma to_outer_measure_apply (s) : μ.to_outer_measure s = μ s := rfl
lemma measure_eq_trim (s) : μ s = μ.to_outer_measure.trim s :=
by rw μ.trimmed; refl
lemma measure_eq_infi (s) : μ s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), μ t :=
by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl
lemma measure_eq_outer_measure' :
μ s = outer_measure' (λ s _, μ s) μ.empty s :=
measure_eq_trim _
lemma to_outer_measure_eq_outer_measure' :
μ.to_outer_measure = outer_measure' (λ s _, μ s) μ.empty :=
μ.trimmed.symm
lemma measure_eq_measure' (hs : is_measurable s) :
μ s = measure' (λ s _, μ s) μ.empty s :=
by rw [measure_eq_outer_measure',
outer_measure'_eq_measure' (λ s _, μ s) _ μ.m_Union hs]
@[simp] lemma measure_empty : μ ∅ = 0 := μ.empty
lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h
lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 :=
by rw [← le_zero_iff_eq, ← h₂]; exact measure_mono h
lemma exists_is_measurable_superset_of_measure_eq_zero {s : set α} (h : μ s = 0) :
∃t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 :=
begin
rw [measure_eq_infi] at h,
have h := (infi_eq_bot _).1 h,
choose t ht using show ∀n:ℕ, ∃t, s ⊆ t ∧ is_measurable t ∧ μ t < n⁻¹,
{ assume n,
have : (0 : ennreal) < n⁻¹ :=
(zero_lt_iff_ne_zero.2 $ ennreal.inv_ne_zero.2 $ ennreal.nat_ne_top _),
rcases h _ this with ⟨t, ht⟩,
use [t],
simpa [(>), infi_lt_iff, -add_comm] using ht },
refine ⟨⋂n, t n, subset_Inter (λn, (ht n).1), is_measurable.Inter (λn, (ht n).2.1), _⟩,
refine eq_of_le_of_forall_le_of_dense bot_le (assume r hr, _),
rcases ennreal.exists_inv_nat_lt (ne_of_gt hr) with ⟨n, hn⟩,
calc μ (⋂n, t n) ≤ μ (t n) : measure_mono (Inter_subset _ _)
... ≤ n⁻¹ : le_of_lt (ht n).2.2
... ≤ r : le_of_lt hn
end
theorem measure_Union_le {β} [encodable β] (s : β → set α) : μ (⋃i, s i) ≤ (∑i, μ (s i)) :=
μ.to_outer_measure.Union _
lemma measure_Union_null {β} [encodable β] {s : β → set α} :
(∀ i, μ (s i) = 0) → μ (⋃i, s i) = 0 :=
μ.to_outer_measure.Union_null
theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ :=
μ.to_outer_measure.union _ _
lemma measure_union_null {s₁ s₂ : set α} : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 :=
μ.to_outer_measure.union_null
lemma measure_Union {β} [encodable β] {f : β → set α}
(hn : pairwise (disjoint on f)) (h : ∀i, is_measurable (f i)) :
μ (⋃i, f i) = (∑i, μ (f i)) :=
by rw [measure_eq_measure' (is_measurable.Union h),
measure'_Union (λ s _, μ s) _ μ.m_Union hn h];
simp [measure_eq_measure', h]
lemma measure_union (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
μ (s₁ ∪ s₂) = μ s₁ + μ s₂ :=
by rw [measure_eq_measure' (h₁.union h₂),
measure'_union (λ s _, μ s) _ μ.m_Union hd h₁ h₂];
simp [measure_eq_measure', h₁, h₂]
lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s)
(hd : pairwise_on s (disjoint on f)) (h : ∀b∈s, is_measurable (f b)) :
μ (⋃b∈s, f b) = ∑p:s, μ (f p.1) :=
begin
haveI := hs.to_encodable,
rw [← measure_Union, bUnion_eq_Union],
{ rintro ⟨i, hi⟩ ⟨j, hj⟩ ij x ⟨h₁, h₂⟩,
exact hd i hi j hj (mt subtype.eq' ij:_) ⟨h₁, h₂⟩ },
{ simpa }
end
lemma measure_sUnion {S : set (set α)} (hs : countable S)
(hd : pairwise_on S disjoint) (h : ∀s∈S, is_measurable s) :
μ (⋃₀ S) = ∑s:S, μ s.1 :=
by rw [sUnion_eq_bUnion, measure_bUnion hs hd h]
lemma measure_diff {s₁ s₂ : set α} (h : s₂ ⊆ s₁)
(h₁ : is_measurable s₁) (h₂ : is_measurable s₂)
(h_fin : μ s₂ < ⊤) : μ (s₁ \ s₂) = μ s₁ - μ s₂ :=
begin
refine (ennreal.add_sub_self' h_fin).symm.trans _,
rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h]
end
lemma measure_Union_eq_supr_nat {s : ℕ → set α} (h : ∀i, is_measurable (s i)) (hs : monotone s) :
μ (⋃i, s i) = (⨆i, μ (s i)) :=
begin
refine le_antisymm _ (supr_le $ λ i, measure_mono $ subset_Union _ _),
rw [← Union_disjointed,
measure_Union disjoint_disjointed (is_measurable.disjointed h),
ennreal.tsum_eq_supr_nat],
refine supr_le (λ n, _),
cases n, {apply zero_le _},
suffices : sum (finset.range n.succ) (λ i, μ (disjointed s i)) = μ (s n),
{ rw this, exact le_supr _ n },
rw [← Union_disjointed_of_mono hs, measure_Union, tsum_eq_sum],
{ apply sum_congr rfl, intros i hi,
simp [finset.mem_range.1 hi] },
{ intros i hi, simp [mt finset.mem_range.2 hi] },
{ rintro i j ij x ⟨⟨_, ⟨_, rfl⟩, h₁⟩, ⟨_, ⟨_, rfl⟩, h₂⟩⟩,
exact disjoint_disjointed i j ij ⟨h₁, h₂⟩ },
{ intro i,
by_cases h' : i < n.succ; simp [h', is_measurable.empty],
apply is_measurable.disjointed h }
end
lemma measure_Inter_eq_infi_nat {s : ℕ → set α}
(h : ∀i, is_measurable (s i)) (hs : ∀i j, i ≤ j → s j ⊆ s i)
(hfin : ∃i, μ (s i) < ⊤) :
μ (⋂i, s i) = (⨅i, μ (s i)) :=
begin
rcases hfin with ⟨k, hk⟩,
rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k),
ennreal.sub_infi,
← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)),
← measure_diff (Inter_subset _ k) (h k) (is_measurable.Inter h)
(lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk),
diff_Inter_left, measure_Union_eq_supr_nat],
{ congr, funext i,
cases le_total k i with ik ik,
{ exact measure_diff (hs _ _ ik) (h k) (h i)
(lt_of_le_of_lt (measure_mono (hs _ _ ik)) hk) },
{ rw [diff_eq_empty.2 (hs _ _ ik), measure_empty,
ennreal.sub_eq_zero_of_le (measure_mono (hs _ _ ik))] } },
{ exact λ i, (h k).diff (h i) },
{ exact λ i j ij, diff_subset_diff_right (hs _ _ ij) }
end
lemma measure_eq_inter_diff {μ : measure α} {s t : set α}
(hs : is_measurable s) (ht : is_measurable t) :
μ s = μ (s ∩ t) + μ (s \ t) :=
have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs ,
by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t]
lemma tendsto_measure_Union {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : monotone s) :
tendsto (μ ∘ s) at_top (nhds (μ (⋃n, s n))) :=
begin
rw measure_Union_eq_supr_nat hs hm,
exact tendsto_at_top_supr_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm $ hnm)
end
lemma tendsto_measure_Inter {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : ∀n m, n ≤ m → s m ⊆ s n) (hf : ∃i, μ (s i) < ⊤):
tendsto (μ ∘ s) at_top (nhds (μ (⋂n, s n))) :=
begin
rw measure_Inter_eq_infi_nat hs hm hf,
exact tendsto_at_top_infi_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm _ _ $ hnm),
end
end
def outer_measure.to_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
measure α :=
measure.of_measurable (λ s _, m s) m.empty
(λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd)
lemma le_to_outer_measure_caratheodory {α} [ms : measurable_space α]
(μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory :=
begin
assume s hs,
rw to_outer_measure_eq_outer_measure',
refine outer_measure.caratheodory_is_measurable (λ t, le_infi $ λ ht, _),
rw [← measure_eq_measure' (ht.inter hs),
← measure_eq_measure' (ht.diff hs),
← measure_union _ (ht.inter hs) (ht.diff hs),
inter_union_diff],
exact le_refl _,
exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁
end
lemma to_measure_to_outer_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
(m.to_measure h).to_outer_measure = m.trim := rfl
@[simp] lemma to_measure_apply {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory)
{s : set α} (hs : is_measurable s) :
m.to_measure h s = m s := m.trim_eq hs
lemma to_outer_measure_to_measure {α : Type*} [ms : measurable_space α] {μ : measure α} :
μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ :=
measure.ext $ λ s, μ.to_outer_measure.trim_eq
namespace measure
variables {α : Type*} {β : Type*} {γ : Type*}
[measurable_space α] [measurable_space β] [measurable_space γ]
instance : has_zero (measure α) :=
⟨{ to_outer_measure := 0,
m_Union := λ f hf hd, tsum_zero.symm,
trimmed := outer_measure.trim_zero }⟩
@[simp] theorem zero_to_outer_measure :
(0 : measure α).to_outer_measure = 0 := rfl
@[simp] theorem zero_apply (s : set α) : (0 : measure α) s = 0 := rfl
instance : inhabited (measure α) := ⟨0⟩
instance : has_add (measure α) :=
⟨λμ₁ μ₂, {
to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure,
m_Union := λs hs hd,
show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑ i, μ₁ (s i) + μ₂ (s i),
by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs],
trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩
@[simp] theorem add_to_outer_measure (μ₁ μ₂ : measure α) :
(μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl
@[simp] theorem add_apply (μ₁ μ₂ : measure α) (s : set α) :
(μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl
instance : add_comm_monoid (measure α) :=
{ zero := 0,
add := (+),
add_assoc := assume a b c, ext $ assume s hs, add_assoc _ _ _,
add_comm := assume a b, ext $ assume s hs, add_comm _ _,
zero_add := assume a, ext $ assume s hs, zero_add _,
add_zero := assume a, ext $ assume s hs, add_zero _ }
instance : partial_order (measure α) :=
{ le := λm₁ m₂, ∀ s, is_measurable s → m₁ s ≤ m₂ s,
le_refl := assume m s hs, le_refl _,
le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs),
le_antisymm := assume m₁ m₂ h₁ h₂, ext $
assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) }
theorem le_iff {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, is_measurable s → μ₁ s ≤ μ₂ s := iff.rfl
theorem to_outer_measure_le {μ₁ μ₂ : measure α} :
μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ :=
by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl
theorem le_iff' {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s :=
to_outer_measure_le.symm
section
variables {m : set (measure α)} {μ : measure α}
lemma Inf_caratheodory (s : set α) (hs : is_measurable s) :
(Inf (measure.to_outer_measure '' m)).caratheodory.is_measurable s :=
begin
rw [outer_measure.Inf_eq_of_function_Inf_gen],
refine outer_measure.caratheodory_is_measurable (assume t, _),
by_cases ht : t = ∅, { simp [ht] },
simp only [outer_measure.Inf_gen_nonempty1 _ _ ht, le_infi_iff, ball_image_iff,
to_outer_measure_apply, measure_eq_infi t],
assume μ hμ u htu hu,
have hm : ∀{s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t,
{ assume s t hst,
rw [outer_measure.Inf_gen_nonempty2 _ _ (mem_image_of_mem _ hμ)],
refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _),
rw [to_outer_measure_apply],
refine measure_mono hst },
rw [measure_eq_inter_diff hu hs],
refine add_le_add' (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu)
end
instance : has_Inf (measure α) :=
⟨λm, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩
lemma Inf_apply {m : set (measure α)} {s : set α} (hs : is_measurable s) :
Inf m s = Inf (to_outer_measure '' m) s :=
to_measure_apply _ _ hs
private lemma Inf_le (h : μ ∈ m) : Inf m ≤ μ :=
have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h),
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
private lemma le_Inf (h : ∀μ' ∈ m, μ ≤ μ') : μ ≤ Inf m :=
have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) :=
le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ,
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
instance : has_Sup (measure α) := ⟨λs, Inf {μ' | ∀μ∈s, μ ≤ μ' }⟩
private lemma le_Sup (h : μ ∈ m) : μ ≤ Sup m := le_Inf $ assume μ' h', h' _ h
private lemma Sup_le (h : ∀μ' ∈ m, μ' ≤ μ) : Sup m ≤ μ := Inf_le h
instance : order_bot (measure α) :=
{ bot := 0, bot_le := assume a s hs, bot_le, .. measure.partial_order }
instance : order_top (measure α) :=
{ top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top),
le_top := assume a s hs,
by by_cases s = ∅; simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply],
.. measure.partial_order }
instance : complete_lattice (measure α) :=
{ Inf := Inf,
Sup := Sup,
inf := λa b, Inf {a, b},
sup := λa b, Sup {a, b},
le_Sup := assume s μ h, le_Sup h,
Sup_le := assume s μ h, Sup_le h,
Inf_le := assume s μ h, Inf_le h,
le_Inf := assume s μ h, le_Inf h,
le_sup_left := assume a b, le_Sup $ by simp,
le_sup_right := assume a b, le_Sup $ by simp,
sup_le := assume a b c hac hbc, Sup_le $ by simp [*, or_imp_distrib] {contextual := tt},
inf_le_left := assume a b, Inf_le $ by simp,
inf_le_right := assume a b, Inf_le $ by simp,
le_inf := assume a b c hac hbc, le_Inf $ by simp [*, or_imp_distrib] {contextual := tt},
.. measure.partial_order, .. measure.lattice.order_top, .. measure.lattice.order_bot }
end
def map (f : α → β) (μ : measure α) : measure β :=
if hf : measurable f then
(μ.to_outer_measure.map f).to_measure $ λ s hs t,
le_to_outer_measure_caratheodory μ _ (hf _ hs) (f ⁻¹' t)
else 0
variables {μ ν : measure α}
@[simp] theorem map_apply {f : α → β} (hf : measurable f)
{s : set β} (hs : is_measurable s) :
(map f μ : measure β) s = μ (f ⁻¹' s) :=
by rw [map, dif_pos hf, to_measure_apply _ _ hs]; refl
@[simp] lemma map_id : map id μ = μ :=
ext $ λ s, map_apply measurable_id
lemma map_map {f : α → β} {g : β → γ} (hf : measurable f) (hg : measurable g) :
map g (map f μ) = map (g ∘ f) μ :=
ext $ λ s hs,
by simp [hf, hg, hs, hg.preimage hs, hf.comp hg];
rw ← preimage_comp
/-- The dirac measure. -/
def dirac (a : α) : measure α :=
(outer_measure.dirac a).to_measure (by simp)
@[simp] lemma dirac_apply (a : α) {s : set α} (hs : is_measurable s) :
(dirac a : measure α) s = ⨆ h : a ∈ s, 1 :=
to_measure_apply _ _ hs
/-- Sum of an indexed family of measures. -/
def sum {ι : Type*} (f : ι → measure α) : measure α :=
(outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $
le_trans
(by exact le_infi (λ i, le_to_outer_measure_caratheodory _))
(outer_measure.le_sum_caratheodory _)
/-- Counting measure on any measurable space. -/
def count : measure α := sum dirac
@[class] def is_complete {α} {_:measurable_space α} (μ : measure α) : Prop :=
∀ s, μ s = 0 → is_measurable s
/-- The "almost everywhere" filter of co-null sets. -/
def a_e (μ : measure α) : filter α :=
{ sets := {s | μ (-s) = 0},
univ_sets := by simp [measure_empty],
inter_sets := λ s t hs ht, by simp [compl_inter]; exact measure_union_null hs ht,
sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs }
lemma mem_a_e_iff (s : set α) : s ∈ μ.a_e.sets ↔ μ (- s) = 0 := iff.refl _
end measure
end measure_theory
section is_complete
open measure_theory
variables {α : Type*} [measurable_space α] (μ : measure α)
def is_null_measurable (s : set α) : Prop :=
∃ t z, s = t ∪ z ∧ is_measurable t ∧ μ z = 0
theorem is_null_measurable_iff {μ : measure α} {s : set α} :
is_null_measurable μ s ↔
∃ t, t ⊆ s ∧ is_measurable t ∧ μ (s \ t) = 0 :=
begin
split,
{ rintro ⟨t, z, rfl, ht, hz⟩,
refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩,
simp [union_diff_left, diff_subset] },
{ rintro ⟨t, st, ht, hz⟩,
exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ }
end
theorem is_null_measurable_measure_eq {μ : measure α} {s t : set α}
(st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t :=
begin
refine le_antisymm _ (measure_mono st),
have := measure_union_le t (s \ t),
rw [union_diff_cancel st, hz] at this, simpa
end
theorem is_measurable.is_null_measurable
{s : set α} (hs : is_measurable s) : is_null_measurable μ s :=
⟨s, ∅, by simp, hs, μ.empty⟩
theorem is_null_measurable_of_complete [c : μ.is_complete]
{s : set α} : is_null_measurable μ s ↔ is_measurable s :=
⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact
is_measurable.union ht (c _ hz),
λ h, h.is_null_measurable _⟩
variables {μ}
theorem is_null_measurable.union_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s ∪ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, le_zero_iff_eq.1
(le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩
end
theorem null_is_null_measurable {z : set α}
(hz : μ z = 0) : is_null_measurable μ z :=
by simpa using (is_measurable.empty.is_null_measurable _).union_null hz
theorem is_null_measurable.Union_nat {s : ℕ → set α}
(hs : ∀ i, is_null_measurable μ (s i)) :
is_null_measurable μ (Union s) :=
begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht,
rcases ht with ⟨st, ht, hz⟩,
refine is_null_measurable_iff.2
⟨Union t, Union_subset_Union st, is_measurable.Union ht,
measure_mono_null _ (measure_Union_null hz)⟩,
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff)
end
theorem is_measurable.diff_null {s z : set α}
(hs : is_measurable s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rw measure_eq_infi at hz,
choose f hf using show ∀ q : {q:ℚ//q>0}, ∃ t:set α,
z ⊆ t ∧ is_measurable t ∧ μ t < (nnreal.of_real q.1 : ennreal),
{ rintro ⟨ε, ε0⟩,
have : 0 < (nnreal.of_real ε : ennreal), { simpa using ε0 },
rw ← hz at this, simpa [infi_lt_iff] },
refine is_null_measurable_iff.2 ⟨s \ Inter f,
diff_subset_diff_right (subset_Inter (λ i, (hf i).1)),
hs.diff (is_measurable.Inter (λ i, (hf i).2.1)),
measure_mono_null _ (le_zero_iff_eq.1 $ le_of_not_lt $ λ h, _)⟩,
{ exact Inter f },
{ rw [diff_subset_iff, diff_union_self],
exact subset.trans (diff_subset _ _) (subset_union_left _ _) },
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩,
simp at ε0,
apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h),
exact measure_mono (Inter_subset _ _)
end
theorem is_null_measurable.diff_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
rw [set.union_diff_distrib],
exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz')
end
theorem is_null_measurable.compl {s : set α}
(hs : is_null_measurable μ s) :
is_null_measurable μ (-s) :=
begin
rcases hs with ⟨t, z, rfl, ht, hz⟩,
rw compl_union,
exact ht.compl.diff_null hz
end
def null_measurable {α : Type u} [measurable_space α]
(μ : measure α) : measurable_space α :=
{ is_measurable := is_null_measurable μ,
is_measurable_empty := is_measurable.empty.is_null_measurable _,
is_measurable_compl := λ s hs, hs.compl,
is_measurable_Union := λ f, is_null_measurable.Union_nat }
def completion {α : Type u} [measurable_space α] (μ : measure α) :
@measure_theory.measure α (null_measurable μ) :=
{ to_outer_measure := μ.to_outer_measure,
m_Union := λ s hs hd, show μ (Union s) = ∑ i, μ (s i), begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩,
rw is_null_measurable_measure_eq (Union_subset_Union st),
{ rw measure_Union _ ht,
{ congr, funext i,
exact (is_null_measurable_measure_eq (st i) (hz i)).symm },
{ rintro i j ij x ⟨h₁, h₂⟩,
exact hd i j ij ⟨st i h₁, st j h₂⟩ } },
{ refine measure_mono_null _ (measure_Union_null hz),
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff) }
end,
trimmed := begin
letI := null_measurable μ,
refine le_antisymm (λ s, _) (outer_measure.trim_ge _),
rw outer_measure.trim_eq_infi,
dsimp, clear _inst,
rw measure_eq_infi s,
exact infi_le_infi (λ t, infi_le_infi $ λ st,
infi_le_infi2 $ λ ht, ⟨ht.is_null_measurable _, le_refl _⟩)
end }
instance completion.is_complete {α : Type u} [measurable_space α] (μ : measure α) :
(completion μ).is_complete :=
λ z hz, null_is_null_measurable hz
end is_complete
namespace measure_theory
/-- A measure space is a measurable space equipped with a
measure, referred to as `volume`. -/
class measure_space (α : Type*) extends measurable_space α :=
(μ {} : measure α)
section measure_space
variables {α : Type*} [measure_space α] {s₁ s₂ : set α}
open measure_space
def volume : set α → ennreal := @μ α _
@[simp] lemma volume_empty : volume (∅ : set α) = 0 := μ.empty
lemma volume_mono : s₁ ⊆ s₂ → volume s₁ ≤ volume s₂ := measure_mono
lemma volume_mono_null : s₁ ⊆ s₂ → volume s₂ = 0 → volume s₁ = 0 :=
measure_mono_null
theorem volume_Union_le {β} [encodable β] :
∀ (s : β → set α), volume (⋃i, s i) ≤ (∑i, volume (s i)) :=
measure_Union_le
lemma volume_Union_null {β} [encodable β] {s : β → set α} :
(∀ i, volume (s i) = 0) → volume (⋃i, s i) = 0 :=
measure_Union_null
theorem volume_union_le : ∀ (s₁ s₂ : set α), volume (s₁ ∪ s₂) ≤ volume s₁ + volume s₂ :=
measure_union_le
lemma volume_union_null : volume s₁ = 0 → volume s₂ = 0 → volume (s₁ ∪ s₂) = 0 :=
measure_union_null
lemma volume_Union {β} [encodable β] {f : β → set α} :
pairwise (disjoint on f) → (∀i, is_measurable (f i)) →
volume (⋃i, f i) = (∑i, volume (f i)) :=
measure_Union
lemma volume_union : disjoint s₁ s₂ → is_measurable s₁ → is_measurable s₂ →
volume (s₁ ∪ s₂) = volume s₁ + volume s₂ :=
measure_union
lemma volume_bUnion {β} {s : set β} {f : β → set α} : countable s →
pairwise_on s (disjoint on f) → (∀b∈s, is_measurable (f b)) →
volume (⋃b∈s, f b) = ∑p:s, volume (f p.1) :=
measure_bUnion
lemma volume_sUnion {S : set (set α)} : countable S →
pairwise_on S disjoint → (∀s∈S, is_measurable s) →
volume (⋃₀ S) = ∑s:S, volume s.1 :=
measure_sUnion
lemma volume_bUnion_finset {β} {s : finset β} {f : β → set α}
(hd : pairwise_on ↑s (disjoint on f)) (hm : ∀b∈s, is_measurable (f b)) :
volume (⋃b∈s, f b) = s.sum (λp, volume (f p)) :=
show volume (⋃b∈(↑s : set β), f b) = s.sum (λp, volume (f p)),
begin
rw [volume_bUnion (countable_finite (finset.finite_to_set s)) hd hm, tsum_eq_sum],
{ show s.attach.sum (λb:(↑s : set β), volume (f b)) = s.sum (λb, volume (f b)),
exact @finset.sum_attach _ _ s _ (λb, volume (f b)) },
simp
end
lemma volume_diff : s₂ ⊆ s₁ → is_measurable s₁ → is_measurable s₂ →
volume s₂ < ⊤ → volume (s₁ \ s₂) = volume s₁ - volume s₂ :=
measure_diff
/-- `∀ₘ a:α, p a` states that the property `p` is almost everywhere true in the measure space
associated with `α`. This means that the measure of the complementary of `p` is `0`.
In a probability measure, the measure of `p` is `1`, when `p` is measurable.
-/
def all_ae (p : α → Prop) : Prop := { a | p a } ∈ (@measure_space.μ α _).a_e.sets
notation `∀ₘ` binders `, ` r:(scoped P, all_ae P) := r
lemma all_ae_congr {p q : α → Prop} (h : ∀ₘ a, p a ↔ q a) : (∀ₘ a, p a) ↔ (∀ₘ a, q a) :=
iff.intro
(assume h', by filter_upwards [h, h'] assume a hpq hp, hpq.1 hp)
(assume h', by filter_upwards [h, h'] assume a hpq hq, hpq.2 hq)
lemma all_ae_iff {p : α → Prop} : (∀ₘ a, p a) ↔ volume { a | ¬ p a } = 0 := iff.refl _
lemma all_ae_all_iff {ι : Type*} [encodable ι] {p : α → ι → Prop} :
(∀ₘ a, ∀i, p a i) ↔ (∀i, ∀ₘ a, p a i):=
begin
refine iff.intro (assume h i, _) (assume h, _),
{ filter_upwards [h] assume a ha, ha i },
{ have h := measure_Union_null h,
rw [← compl_Inter] at h,
filter_upwards [h] assume a, mem_Inter.1 }
end
end measure_space
end measure_theory
|
bb33bb4ab7ad7692053da22f3efadd90bdd85bb5 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/multiset/lattice.lean | a37ffb92ab5c0c729f6cee122db51dd3c73e7d69 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 3,837 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.multiset.finset_ops
import data.multiset.fold
/-!
# Lattice operations on multisets
-/
namespace multiset
variables {α : Type*}
/-! ### sup -/
section sup
variables [semilattice_sup_bot α]
/-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/
def sup (s : multiset α) : α := s.fold (⊔) ⊥
@[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ :=
fold_zero _ _
@[simp] lemma sup_cons (a : α) (s : multiset α) :
(a ::ₘ s).sup = a ⊔ s.sup :=
fold_cons_left _ _ _ _
@[simp] lemma sup_singleton {a : α} : (a ::ₘ 0).sup = a := by simp
@[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup :=
eq.trans (by simp [sup]) (fold_add _ _ _ _ _)
lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup :=
sup_le.1 (le_refl _) _ h
lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup :=
sup_le.2 $ assume b hb, le_sup (h hb)
variables [decidable_eq α]
@[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup :=
fold_erase_dup_idem _ _ _
@[simp] lemma sup_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp
@[simp] lemma sup_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp
@[simp] lemma sup_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).sup = a ⊔ s.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp
lemma nodup_sup_iff {α : Type*} [decidable_eq α] {m : multiset (multiset α) } :
m.sup.nodup ↔ ∀ (a : multiset α), a ∈ m → a.nodup :=
begin
apply m.induction_on,
{ simp },
{ intros a s h,
simp [h] }
end
end sup
/-! ### inf -/
section inf
variables [semilattice_inf_top α]
/-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/
def inf (s : multiset α) : α := s.fold (⊓) ⊤
@[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ :=
fold_zero _ _
@[simp] lemma inf_cons (a : α) (s : multiset α) :
(a ::ₘ s).inf = a ⊓ s.inf :=
fold_cons_left _ _ _ _
@[simp] lemma inf_singleton {a : α} : (a ::ₘ 0).inf = a := by simp
@[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf :=
eq.trans (by simp [inf]) (fold_add _ _ _ _ _)
lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a :=
le_inf.1 (le_refl _) _ h
lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf :=
le_inf.2 $ assume b hb, inf_le (h hb)
variables [decidable_eq α]
@[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf :=
fold_erase_dup_idem _ _ _
@[simp] lemma inf_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp
@[simp] lemma inf_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp
@[simp] lemma inf_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).inf = a ⊓ s.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp
end inf
end multiset
|
bc8bcb94fde418b4c7b6bc85c870103413799d75 | 737dc4b96c97368cb66b925eeea3ab633ec3d702 | /src/Lean/Elab/Match.lean | 75423a6085fbe7c5420dae6ae7409f086e09a7b5 | [
"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 | 45,370 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.CollectFVars
import Lean.Meta.Match.MatchPatternAttr
import Lean.Meta.Match.Match
import Lean.Meta.SortLocalDecls
import Lean.Meta.GeneralizeVars
import Lean.Elab.SyntheticMVars
import Lean.Elab.Arg
import Lean.Parser.Term
import Lean.Elab.PatternVar
namespace Lean.Elab.Term
open Meta
open Lean.Parser.Term
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 mkUserNameFor (e : Expr) : TermElabM Name := do
match e with
/- Remark: we use `mkFreshUserName` to make sure we don't add a variable to the local context that can be resolved to `e`. -/
| Expr.fvar fvarId _ => mkFreshUserName ((← 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
/--
We treat `@x` as atomic to avoid unnecessary extra local declarations from being
inserted into the local context. Recall that `expandMatchAltsIntoMatch` uses `@` modifier.
Thus this is kind of discriminant is quite common.
Remark: if the discriminat is `Systax.missing`, we abort the elaboration of the `match`-expression.
This can happen due to error recovery. Example
```
example : (p ∨ p) → p := fun h => match
```
If we don't abort, the elaborator loops because we will keep trying to expand
```
match
```
into
```
let d := <Syntax.missing>; match
```
Recall that `Syntax.setArg stx i arg` is a no-op when `i` is out-of-bounds. -/
def isAtomicDiscr? (discr : Syntax) : TermElabM (Option Expr) := do
match discr with
| `($x:ident) => isLocalIdent? x
| `(@$x:ident) => isLocalIdent? x
| _ => if discr.isMissing then throwAbortTerm else return none
-- See expandNonAtomicDiscrs?
private def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do
let term := discr[1]
match (← isAtomicDiscr? term) with
| some e@(Expr.fvar fvarId _) =>
let localDecl ← getLocalDecl fvarId
if !isAuxDiscrName localDecl.userName then
return e -- it is not an auxiliary local created by `expandNonAtomicDiscrs?`
else
instantiateMVars localDecl.value
| _ => throwErrorAt discr "unexpected discriminant"
structure ElabMatchTypeAndDiscrsResult where
discrs : Array Expr
matchType : Expr
/- `true` when performing dependent elimination. We use this to decide whether we optimize the "match unit" case.
See `isMatchUnit?`. -/
isDep : Bool
alts : Array MatchAltView
private partial def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptType : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr)
: TermElabM ElabMatchTypeAndDiscrsResult := do
let numDiscrs := discrStxs.size
if matchOptType.isNone then
elabDiscrs 0 #[]
else
let matchTypeStx := matchOptType[0][1]
let matchType ← elabType matchTypeStx
let (discrs, isDep) ← elabDiscrsWitMatchType matchType expectedType
return { discrs := discrs, matchType := matchType, isDep := isDep, alts := matchAltViews }
where
/- Easy case: elaborate discriminant when the match-type has been explicitly provided by the user. -/
elabDiscrsWitMatchType (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"
return (discrs, isDep)
markIsDep (r : ElabMatchTypeAndDiscrsResult) :=
{ r with isDep := true }
/- Elaborate discriminants inferring the match-type -/
elabDiscrs (i : Nat) (discrs : Array Expr) : TermElabM ElabMatchTypeAndDiscrsResult := do
if h : i < discrStxs.size then
let discrStx := discrStxs.get ⟨i, h⟩
let discr ← elabAtomicDiscr discrStx
let discr ← instantiateMVars discr
let discrType ← inferType discr
let discrType ← instantiateMVars discrType
let discrs := discrs.push discr
let userName ← mkUserNameFor discr
if discrStx[0].isNone then
let mut result ← elabDiscrs (i + 1) discrs
let matchTypeBody ← kabstract result.matchType discr
if matchTypeBody.hasLooseBVars then
result := markIsDep result
return { result with matchType := Lean.mkForall userName BinderInfo.default discrType matchTypeBody }
else
let discrs := discrs.push (← mkEqRefl discr)
let result ← elabDiscrs (i + 1) discrs
let result := markIsDep result
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 ← kabstract result.matchType discr
let matchTypeBody := matchTypeBody.instantiate1 x
let matchType ← mkForallFVars #[x, h] matchTypeBody
return { result with
matchType := matchType
alts := result.alts.map fun altView => { altView with patterns := altView.patterns.insertAt (i+1) identStx }
}
else
return { discrs, alts := matchAltViews, isDep := false, matchType := expectedType }
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 }
private def getMatchGeneralizing? : Syntax → Option Bool
| `(match (generalizing := true) $discrs,* $[: $ty?]? with $alts:matchAlt*) => some true
| `(match (generalizing := false) $discrs,* $[: $ty?]? with $alts:matchAlt*) => some false
| _ => none
/- Given `stx` a match-expression, return its alternatives. -/
private def getMatchAlts : Syntax → Array MatchAltView
| `(match $[$gen]? $discrs,* $[: $ty?]? with $alts:matchAlt*) =>
alts.filterMap fun alt => match alt with
| `(matchAltExpr| | $patterns,* => $rhs) => some {
ref := alt,
patterns := patterns,
rhs := rhs
}
| _ => none
| _ => #[]
builtin_initialize Parser.registerBuiltinNodeKind `MVarWithIdKind
open Meta.Match (mkInaccessible inaccessible?)
/--
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
open Lean.Elab.Term.Quotation in
@[builtinQuotPrecheck Lean.Parser.Term.match] def precheckMatch : Precheck
| `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do
discrs.forM precheck
for (pats, rhs) in patss.zip rhss do
let vars ←
try
getPatternsVars pats
catch
| _ => return -- can happen in case of pattern antiquotations
Quotation.withNewLocals (getPatternVarNames vars) <| precheck rhs
| _ => throwUnsupportedSyntax
/- 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 #[]
/-
Remark: when performing dependent pattern matching, we often had to write code such as
```lean
def Vec.map' (f : α → β) (xs : Vec α n) : Vec β n :=
match n, xs with
| _, nil => nil
| _, cons a as => cons (f a) (map' f as)
```
We had to include `n` and the `_`s because the type of `xs` depends on `n`.
Moreover, `nil` and `cons a as` have different types.
This was quite tedious. So, we have implemented an automatic "discriminant refinement procedure".
The procedure is based on the observation that we get a type error whenenver we forget to include `_`s
and the indices a discriminant depends on. So, we catch the exception, check whether the type of the discriminant
is an indexed family, and add their indices as new discriminants.
The current implementation, adds indices as they are found, and does not
try to "sort" the new discriminants.
If the refinement process fails, we report the original error message.
-/
/- Auxiliary structure for storing an type mismatch exception when processing the
pattern #`idx` of some alternative. -/
structure PatternElabException where
ex : Exception
patternIdx : Nat -- Discriminant that sh
pathToIndex : List Nat -- Path to the problematic inductive type index that produced the type mismatch
/--
This method is part of the "discriminant refinement" procedure. It in invoked when the
type of the `pattern` does not match the expected type. The expected type is based on the
motive computed using the `match` discriminants.
It tries to compute a path to an index of the discriminant type.
For example, suppose the user has written
```
inductive Mem (a : α) : List α → Prop where
| head {as} : Mem a (a::as)
| tail {as} : Mem a as → Mem a (a'::as)
infix:50 " ∈ " => Mem
example (a b : Nat) (h : a ∈ [b]) : b = a :=
match h with
| Mem.head => rfl
```
The motive for the match is `a ∈ [b] → b = a`, and get a type mismatch between the type
of `Mem.head` and `a ∈ [b]`. This procedure return the path `[2, 1]` to the index `b`.
We use it to produce the following refinement
```
example (a b : Nat) (h : a ∈ [b]) : b = a :=
match b, h with
| _, Mem.head => rfl
```
which produces the new motive `(x : Nat) → a ∈ [x] → x = a`
After this refinement step, the `match` is elaborated successfully.
This method relies on the fact that the dependent pattern matcher compiler solves equations
between indices of indexed inductive families.
The following kinds of equations are supported by this compiler:
- `x = t`
- `t = x`
- `ctor ... = ctor ...`
where `x` is a free variable, `t` is an arbitrary term, and `ctor` is constructor.
Our procedure ensures that "information" is not lost, and will *not* succeed in an
example such as
```
example (a b : Nat) (f : Nat → Nat) (h : f a ∈ [f b]) : f b = f a :=
match h with
| Mem.head => rfl
```
and will not add `f b` as a new discriminant. We may add an option in the future to
enable this more liberal form of refinement.
-/
private partial def findDiscrRefinementPath (pattern : Expr) (expected : Expr) : OptionT MetaM (List Nat) := do
goType (← instantiateMVars (← inferType pattern)) expected
where
checkCompatibleApps (t d : Expr) : OptionT MetaM Unit := do
guard d.isApp
guard <| t.getAppNumArgs == d.getAppNumArgs
let tFn := t.getAppFn
let dFn := d.getAppFn
guard <| tFn.isConst && dFn.isConst
guard (← isDefEq tFn dFn)
-- Visitor for inductive types
goType (t d : Expr) : OptionT MetaM (List Nat) := do
trace[Meta.debug] "type {t} =?= {d}"
let t ← whnf t
let d ← whnf d
checkCompatibleApps t d
matchConstInduct t.getAppFn (fun _ => failure) fun info _ => do
let tArgs := t.getAppArgs
let dArgs := d.getAppArgs
for i in [:info.numParams] do
let tArg := tArgs[i]
let dArg := dArgs[i]
unless (← isDefEq tArg dArg) do
return i :: (← goType tArg dArg)
for i in [info.numParams : tArgs.size] do
let tArg := tArgs[i]
let dArg := dArgs[i]
unless (← isDefEq tArg dArg) do
return i :: (← goIndex tArg dArg)
failure
-- Visitor for indexed families
goIndex (t d : Expr) : OptionT MetaM (List Nat) := do
let t ← whnfD t
let d ← whnfD d
if t.isFVar || d.isFVar then
return [] -- Found refinement path
else
trace[Meta.debug] "index {t} =?= {d}"
checkCompatibleApps t d
matchConstCtor t.getAppFn (fun _ => failure) fun info _ => do
let tArgs := t.getAppArgs
let dArgs := d.getAppArgs
for i in [:info.numParams] do
let tArg := tArgs[i]
let dArg := dArgs[i]
unless (← isDefEq tArg dArg) do
failure
for i in [info.numParams : tArgs.size] do
let tArg := tArgs[i]
let dArg := dArgs[i]
unless (← isDefEq tArg dArg) do
return i :: (← goIndex tArg dArg)
failure
private partial def eraseIndices (type : Expr) : MetaM Expr := do
let type' ← whnfD type
matchConstInduct type'.getAppFn (fun _ => return type) fun info _ => do
let args := type'.getAppArgs
let params ← args[:info.numParams].toArray.mapM eraseIndices
let result := mkAppN type'.getAppFn params
let resultType ← inferType result
let (newIndices, _, _) ← forallMetaTelescopeReducing resultType (some (args.size - info.numParams))
return mkAppN result newIndices
private def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : ExceptT PatternElabException TermElabM (Array Expr × Expr) :=
withReader (fun ctx => { ctx with implicitLambda := false }) do
let mut patterns := #[]
let mut matchType := matchType
for idx in [:patternStxs.size] do
let patternStx := patternStxs[idx]
matchType ← whnf matchType
match matchType with
| Expr.forallE _ d b _ =>
let pattern ← do
let s ← saveState
try
liftM <| withSynthesize <| withoutErrToSorry <| elabTermEnsuringType patternStx d
catch ex : Exception =>
restoreState s
match (← liftM <| commitIfNoErrors? <| withoutErrToSorry do elabTermAndSynthesize patternStx (← eraseIndices d)) with
| some pattern =>
match (← findDiscrRefinementPath pattern d |>.run) with
| some path =>
trace[Meta.debug] "refinement path: {path}"
restoreState s
-- Wrap the type mismatch exception for the "discriminant refinement" feature.
throwThe PatternElabException { ex := ex, patternIdx := idx, pathToIndex := path }
| none => restoreState s; throw ex
| none => throw ex
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.name} := {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 ()
/- We perform a topological sort (dependecies) on `decls` because the pattern elaboration process may produce a sequence where a declaration d₁ may occur after d₂ when d₂ depends on d₁. -/
sortLocalDecls 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 : FVarIdSet := {}
localDecls : Array LocalDecl
newLocals : FVarIdSet := {}
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 ← mkFreshFVarId
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 isMatchValue e 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 _ => do
if (← isProof e) then
/- We mark nested proofs as inaccessible. This is fine due to proof irrelevance.
We need this feature to be able to elaborate definitions such as:
```
def f : Fin 2 → Nat
| 0 => 5
| 1 => 45
```
-/
return Pattern.inaccessible e
else
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 α) : ExceptT PatternElabException TermElabM α := do
let (patterns, matchType) ← withSynthesize <| elabPatterns patternStxs matchType
id (α := TermElabM α) do
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
private def elabMatchAltView (alt : MatchAltView) (matchType : Expr) : ExceptT PatternElabException 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)
/--
Collect problematic index for the "discriminant refinement feature". This method is invoked
when we detect a type mismatch at a pattern #`idx` of some alternative. -/
private partial def getIndexToInclude? (discr : Expr) (pathToIndex : List Nat) : TermElabM (Option Expr) := do
go (← inferType discr) pathToIndex |>.run
where
go (e : Expr) (path : List Nat) : OptionT MetaM Expr := do
match path with
| [] => return e
| i::path =>
let e ← whnfD e
guard <| e.isApp && i < e.getAppNumArgs
go (e.getArg! i) path
/--
"Generalize" variables that depend on the discriminants.
Remarks and limitations:
- If `matchType` is a proposition, then we generalize even when the user did not provide `(generalizing := true)`.
Motivation: users should have control about the actual `match`-expressions in their programs.
- We currently do not generalize let-decls.
- We abort generalization if the new `matchType` is type incorrect.
- Only discriminants that are free variables are considered during specialization.
- We "generalize" by adding new discriminants and pattern variables. We do not "clear" the generalized variables,
but they become inaccessible since they are shadowed by the patterns variables. We assume this is ok since
this is the exact behavior users would get if they had written it by hand. Recall there is no `clear` in term mode.
-/
private def generalize (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (generalizing? : Option Bool) : TermElabM (Array Expr × Expr × Array MatchAltView × Bool) := do
let gen ←
match generalizing? with
| some g => pure g
| _ => isProp matchType
if !gen then
return (discrs, matchType, altViews, false)
else
let ysFVarIds ← getFVarsToGeneralize discrs
/- let-decls are currently being ignored by the generalizer. -/
let ysFVarIds ← ysFVarIds.filterM fun fvarId => return !(← getLocalDecl fvarId).isLet
if ysFVarIds.isEmpty then
return (discrs, matchType, altViews, false)
else
let ys := ysFVarIds.map mkFVar
-- trace[Meta.debug] "ys: {ys}, discrs: {discrs}"
let matchType' ← forallBoundedTelescope matchType discrs.size fun ds type => do
let type ← mkForallFVars ys type
let (discrs', ds') := Array.unzip <| Array.zip discrs ds |>.filter fun (di, d) => di.isFVar
let type := type.replaceFVars discrs' ds'
mkForallFVars ds type
-- trace[Meta.debug] "matchType': {matchType'}"
if (← isTypeCorrect matchType') then
let discrs := discrs ++ ys
let altViews ← altViews.mapM fun altView => do
let patternVars ← getPatternsVars altView.patterns
-- We traverse backwards because we want to keep the most recent names.
-- For example, if `ys` contains `#[h, h]`, we want to make sure `mkFreshUsername is applied to the first `h`,
-- since it is already shadowed by the second.
let ysUserNames ← ys.foldrM (init := #[]) fun ys ysUserNames => do
let yDecl ← getLocalDecl ys.fvarId!
let mut yUserName := yDecl.userName
if ysUserNames.contains yUserName then
yUserName ← mkFreshUserName yUserName
-- Explicitly provided pattern variables shadow `y`
else if patternVars.any fun | PatternVar.localVar x => x == yUserName | _ => false then
yUserName ← mkFreshUserName yUserName
return ysUserNames.push yUserName
let ysIds ← ysUserNames.reverse.mapM fun n => return mkIdentFrom (← getRef) n
return { altView with patterns := altView.patterns ++ ysIds }
return (discrs, matchType', altViews, true)
else
return (discrs, matchType, altViews, true)
private partial def elabMatchAltViews (generalizing? : Option Bool) (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) : TermElabM (Array Expr × Expr × Array (AltLHS × Expr) × Bool) := do
loop discrs matchType altViews none
where
/-
"Discriminant refinement" main loop.
`first?` contains the first error message we found before updated the `discrs`. -/
loop (discrs : Array Expr) (matchType : Expr) (altViews : Array MatchAltView) (first? : Option (SavedState × Exception))
: TermElabM (Array Expr × Expr × Array (AltLHS × Expr) × Bool) := do
let s ← saveState
let (discrs', matchType', altViews', refined) ← generalize discrs matchType altViews generalizing?
match (← altViews'.mapM (fun altView => elabMatchAltView altView matchType') |>.run) with
| Except.ok alts => return (discrs', matchType', alts, first?.isSome || refined)
| Except.error { patternIdx := patternIdx, pathToIndex := pathToIndex, ex := ex } =>
trace[Meta.debug] "pathToIndex: {toString pathToIndex}"
let some index ← getIndexToInclude? discrs[patternIdx] pathToIndex
| throwEx (← updateFirst first? ex)
trace[Meta.debug] "index: {index}"
if (← discrs.anyM fun discr => isDefEq discr index) then
throwEx (← updateFirst first? ex)
let first ← updateFirst first? ex
s.restore
let indices ← collectDeps #[index] discrs
let matchType ←
try
updateMatchType indices matchType
catch ex =>
throwEx first
let altViews ← addWildcardPatterns indices.size altViews
let discrs := indices ++ discrs
loop discrs matchType altViews first
throwEx {α} (p : SavedState × Exception) : TermElabM α := do
p.1.restore; throw p.2
updateFirst (first? : Option (SavedState × Exception)) (ex : Exception) : TermElabM (SavedState × Exception) := do
match first? with
| none => return (← saveState, ex)
| some first => return first
containsFVar (es : Array Expr) (fvarId : FVarId) : Bool :=
es.any fun e => e.isFVar && e.fvarId! == fvarId
/- Update `indices` by including any free variable `x` s.t.
- Type of some `discr` depends on `x`.
- Type of `x` depends on some free variable in `indices`.
If we don't include these extra variables in indices, then
`updateMatchType` will generate a type incorrect term.
For example, suppose `discr` contains `h : @HEq α a α b`, and
`indices` is `#[α, b]`, and `matchType` is `@HEq α a α b → B`.
`updateMatchType indices matchType` produces the type
`(α' : Type) → (b : α') → @HEq α' a α' b → B` which is type incorrect
because we have `a : α`.
The method `collectDeps` will include `a` into `indices`.
This method does not handle dependencies among non-free variables.
We rely on the type checking method `check` at `updateMatchType`.
Remark: `indices : Array Expr` does not need to be an array anymore.
We should cleanup this code, and use `index : Expr` instead.
-/
collectDeps (indices : Array Expr) (discrs : Array Expr) : TermElabM (Array Expr) := do
let mut s : CollectFVars.State := {}
for discr in discrs do
s := collectFVars s (← instantiateMVars (← inferType discr))
let (indicesFVar, indicesNonFVar) := indices.split Expr.isFVar
let indicesFVar := indicesFVar.map Expr.fvarId!
let mut toAdd := #[]
for fvarId in s.fvarSet.toList do
unless containsFVar discrs fvarId || containsFVar indices fvarId do
let localDecl ← getLocalDecl fvarId
let mctx ← getMCtx
for indexFVarId in indicesFVar do
if mctx.localDeclDependsOn localDecl indexFVarId then
toAdd := toAdd.push fvarId
let lctx ← getLCtx
let indicesFVar := (indicesFVar ++ toAdd).qsort fun fvarId₁ fvarId₂ =>
(lctx.get! fvarId₁).index < (lctx.get! fvarId₂).index
return indicesFVar.map mkFVar ++ indicesNonFVar
updateMatchType (indices : Array Expr) (matchType : Expr) : TermElabM Expr := do
let matchType ← indices.foldrM (init := matchType) fun index matchType => do
let indexType ← inferType index
let matchTypeBody ← kabstract matchType index
let userName ← mkUserNameFor index
return Lean.mkForall userName BinderInfo.default indexType matchTypeBody
check matchType
return matchType
addWildcardPatterns (num : Nat) (altViews : Array MatchAltView) : TermElabM (Array MatchAltView) := do
let hole := mkHole (← getRef)
let wildcards := mkArray num hole
return altViews.map fun altView => { altView with patterns := wildcards ++ altView.patterns }
def mkMatcher (input : Meta.Match.MkMatcherInput) : TermElabM MatcherResult :=
Meta.Match.mkMatcher input
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 <| logError m!"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 (generalizing? : Option Bool) (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptType : Syntax) (expectedType : Expr)
: TermElabM Expr := do
let mut generalizing? := generalizing?
if !matchOptType.isNone then
if generalizing? == some true then
throwError "the '(generalizing := true)' parameter is not supported when the 'match' type is explicitly provided"
generalizing? := some false
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 (discrs, matchType, alts, refined) ← elabMatchAltViews generalizing? discrs matchType matchAlts
let isDep := isDep || refined
/-
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, lhss := altLHSS }
matcherResult.addMatcher
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[2].getSepArgs
private def getMatchOptType (matchStx : Syntax) : Syntax :=
matchStx[3]
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 <$> isAtomicDiscr? discr[1]
if allLocal then
return none
else
-- We use `foundFVars` to make sure the discriminants are distinct variables.
-- See: code for computing "matchType" at `elabMatchTypeAndDiscrs`
let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) (foundFVars : FVarIdSet) := do
match discrs with
| [] =>
let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx ", ");
pure (matchStx.setArg 2 discrs)
| discr :: discrs =>
-- Recall that
-- matchDiscr := leading_parser optional (ident >> ":") >> termParser
let term := discr[1]
let addAux : TermElabM Syntax := 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) foundFVars
`(let _discr := $term; $r)
match (← isAtomicDiscr? term) with
| some x => if x.isFVar then loop discrs (discrsNew.push discr) (foundFVars.insert x.fvarId!) else addAux
| none => addAux
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 (← isAtomicDiscr? 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
/-
```
leading_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 gen? := getMatchGeneralizing? stx
let altViews := getMatchAlts stx
let matchOptType := getMatchOptType stx
elabMatchAux gen? 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
| some _ => return !hasMatchPatternAttribute (← getEnv) fName
| _ => isAtomicIdent stx
| _ => isAtomicIdent stx
where
isAtomicIdent (stx : Syntax) : Bool :=
stx.isIdent && stx.getId.eraseMacroScopes.isAtomic
-- leading_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?
| _ => 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
-- leading_parser:leadPrec "nomatch " >> termParser
@[builtinTermElab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? => do
match stx with
| `(nomatch $discrExpr) =>
match (← isLocalIdent? discrExpr) with
| some _ =>
let expectedType ← waitExpectedType expectedType?
let discr := Syntax.node ``Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr]
elabMatchAux none #[discr] #[] mkNullNode expectedType
| _ =>
let stxNew ← `(let _discr := $discrExpr; nomatch _discr)
withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?
| _ => throwUnsupportedSyntax
end Lean.Elab.Term
|
d61c0a08a7d80c45225cd5f1ae8027aaf3bc9173 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/measure_theory/covering/one_dim.lean | 9476116be57c0122609b5d3cb088ad8ffce6262b | [
"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 | 2,333 | lean | /-
Copyright (c) 2022 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import measure_theory.covering.density_theorem
import measure_theory.measure.haar_lebesgue
/-!
# Covering theorems for Lebesgue measure in one dimension
We have a general theory of covering theorems for doubling measures, developed notably
in `density_theorems.lean`. In this file, we expand the API for this theory in one dimension,
by showing that intervals belong to the relevant Vitali family.
-/
open set measure_theory is_doubling_measure filter
open_locale topological_space
namespace real
lemma Icc_mem_vitali_family_at_right {x y : ℝ} (hxy : x < y) :
Icc x y ∈ (vitali_family (volume : measure ℝ) 1).sets_at x :=
begin
rw Icc_eq_closed_ball,
refine closed_ball_mem_vitali_family_of_dist_le_mul _ _ (by linarith),
rw [dist_comm, real.dist_eq, abs_of_nonneg];
linarith,
end
lemma tendsto_Icc_vitali_family_right (x : ℝ) :
tendsto (λ y, Icc x y) (𝓝[>] x) ((vitali_family (volume : measure ℝ) 1).filter_at x) :=
begin
refine (vitali_family.tendsto_filter_at_iff _).2 ⟨_, _⟩,
{ filter_upwards [self_mem_nhds_within] with y hy using Icc_mem_vitali_family_at_right hy },
{ assume ε εpos,
have : x ∈ Ico x (x + ε) := ⟨le_refl _, by linarith⟩,
filter_upwards [Icc_mem_nhds_within_Ioi this] with y hy,
rw closed_ball_eq_Icc,
exact Icc_subset_Icc (by linarith) hy.2 }
end
lemma Icc_mem_vitali_family_at_left {x y : ℝ} (hxy : x < y) :
Icc x y ∈ (vitali_family (volume : measure ℝ) 1).sets_at y :=
begin
rw Icc_eq_closed_ball,
refine closed_ball_mem_vitali_family_of_dist_le_mul _ _ (by linarith),
rw [real.dist_eq, abs_of_nonneg];
linarith,
end
lemma tendsto_Icc_vitali_family_left (x : ℝ) :
tendsto (λ y, Icc y x) (𝓝[<] x) ((vitali_family (volume : measure ℝ) 1).filter_at x) :=
begin
refine (vitali_family.tendsto_filter_at_iff _).2 ⟨_, _⟩,
{ filter_upwards [self_mem_nhds_within] with y hy using Icc_mem_vitali_family_at_left hy },
{ assume ε εpos,
have : x ∈ Ioc (x - ε) x := ⟨by linarith, le_refl _⟩,
filter_upwards [Icc_mem_nhds_within_Iio this] with y hy,
rw closed_ball_eq_Icc,
exact Icc_subset_Icc hy.1 (by linarith) }
end
end real
|
ae637b3e8393e9c9322c3937be7513c1c10e0309 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /11_Tactic-Style_Proofs.org.26.lean | 46494d8da9f7f7c6f536510d9719ccddd3bb0cbe | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 611 | lean | import standard
example (p q r : Prop) : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) :=
begin
apply iff.intro,
{ intro H,
apply (or.elim (and.elim_right H)),
{ intro Hq,
apply or.intro_left,
apply and.intro,
{ exact (and.elim_left H) },
{ exact Hq }},
{ intro Hr,
apply or.intro_right,
apply and.intro,
{ exact (and.elim_left H)},
{ exact Hr }}},
{ intro H,
apply (or.elim H),
{ intro Hpq,
apply and.intro,
{ exact (and.elim_left Hpq) },
{ apply or.intro_left,
exact (and.elim_right Hpq) }},
{ intro Hpr,
apply and.intro,
{ exact (and.elim_left Hpr)},
{ apply or.intro_right,
exact (and.elim_right Hpr) }}}
end
|
be88c19163d2f755868d46f5586211960529089e | bb31430994044506fa42fd667e2d556327e18dfe | /src/topology/algebra/module/linear_pmap.lean | 2740693517f52a9989263067d902e65cfaa2525c | [
"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 | 6,487 | 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 linear_algebra.linear_pmap
import topology.algebra.module.basic
/-!
# Partially defined linear operators over topological vector spaces
We define basic notions of partially defined linear operators, which we call unbounded operators
for short.
In this file we prove all elementary properties of unbounded operators that do not assume that the
underlying spaces are normed.
## Main definitions
* `linear_pmap.is_closed`: An unbounded operator is closed iff its graph is closed.
* `linear_pmap.is_closable`: An unbounded operator is closable iff the closure of its graph is a
graph.
* `linear_pmap.closure`: For a closable unbounded operator `f : linear_pmap R E F` the closure is
the smallest closed extension of `f`. If `f` is not closable, then `f.closure` is defined as `f`.
* `linear_pmap.has_core`: a submodule contained in the domain is a core if restricting to the core
does not lose information about the unbounded operator.
## Main statements
* `linear_pmap.closable_iff_exists_closed_extension`: an unbounded operator is closable iff it has a
closed extension.
* `linear_pmap.closable.exists_unique`: there exists a unique closure
* `linear_pmap.closure_has_core`: the domain of `f` is a core of its closure
## References
* [J. Weidmann, *Linear Operators in Hilbert Spaces*][weidmann_linear]
## Tags
Unbounded operators, closed operators
-/
open_locale topological_space
variables {R E F : Type*}
variables [comm_ring R] [add_comm_group E] [add_comm_group F]
variables [module R E] [module R F]
variables [topological_space E] [topological_space F]
namespace linear_pmap
/-! ### Closed and closable operators -/
/-- An unbounded operator is closed iff its graph is closed. -/
def is_closed (f : E →ₗ.[R] F) : Prop :=
is_closed (f.graph : set (E × F))
variables [has_continuous_add E] [has_continuous_add F]
variables [topological_space R] [has_continuous_smul R E] [has_continuous_smul R F]
/-- An unbounded operator is closable iff the closure of its graph is a graph. -/
def is_closable (f : E →ₗ.[R] F) : Prop :=
∃ (f' : linear_pmap R E F), f.graph.topological_closure = f'.graph
/-- A closed operator is trivially closable. -/
lemma is_closed.is_closable {f : E →ₗ.[R] F} (hf : f.is_closed) : f.is_closable :=
⟨f, hf.submodule_topological_closure_eq⟩
/-- If `g` has a closable extension `f`, then `g` itself is closable. -/
lemma is_closable.le_is_closable {f g : E →ₗ.[R] F} (hf : f.is_closable) (hfg : g ≤ f) :
g.is_closable :=
begin
cases hf with f' hf,
have : g.graph.topological_closure ≤ f'.graph :=
by { rw ←hf, exact submodule.topological_closure_mono (le_graph_of_le hfg) },
refine ⟨g.graph.topological_closure.to_linear_pmap _, _⟩,
{ intros x hx hx',
cases x,
exact f'.graph_fst_eq_zero_snd (this hx) hx' },
rw [submodule.to_linear_pmap_graph_eq],
end
/-- The closure is unique. -/
lemma is_closable.exists_unique {f : E →ₗ.[R] F} (hf : f.is_closable) :
∃! (f' : E →ₗ.[R] F), f.graph.topological_closure = f'.graph :=
begin
refine exists_unique_of_exists_of_unique hf (λ _ _ hy₁ hy₂, eq_of_eq_graph _),
rw [←hy₁, ←hy₂],
end
open_locale classical
/-- If `f` is closable, then `f.closure` is the closure. Otherwise it is defined
as `f.closure = f`. -/
noncomputable
def closure (f : E →ₗ.[R] F) : E →ₗ.[R] F :=
if hf : f.is_closable then hf.some else f
lemma closure_def {f : E →ₗ.[R] F} (hf : f.is_closable) :
f.closure = hf.some :=
by simp [closure, hf]
lemma closure_def' {f : E →ₗ.[R] F} (hf : ¬f.is_closable) :
f.closure = f :=
by simp [closure, hf]
/-- The closure (as a submodule) of the graph is equal to the graph of the closure
(as a `linear_pmap`). -/
lemma is_closable.graph_closure_eq_closure_graph {f : E →ₗ.[R] F} (hf : f.is_closable) :
f.graph.topological_closure = f.closure.graph :=
begin
rw closure_def hf,
exact hf.some_spec,
end
/-- A `linear_pmap` is contained in its closure. -/
lemma le_closure (f : E →ₗ.[R] F) : f ≤ f.closure :=
begin
by_cases hf : f.is_closable,
{ refine le_of_le_graph _,
rw ←hf.graph_closure_eq_closure_graph,
exact (graph f).le_topological_closure },
rw closure_def' hf,
end
lemma is_closable.closure_mono {f g : E →ₗ.[R] F} (hg : g.is_closable) (h : f ≤ g) :
f.closure ≤ g.closure :=
begin
refine le_of_le_graph _,
rw ←(hg.le_is_closable h).graph_closure_eq_closure_graph,
rw ←hg.graph_closure_eq_closure_graph,
exact submodule.topological_closure_mono (le_graph_of_le h),
end
/-- If `f` is closable, then the closure is closed. -/
lemma is_closable.closure_is_closed {f : E →ₗ.[R] F} (hf : f.is_closable) :
f.closure.is_closed :=
begin
rw [is_closed, ←hf.graph_closure_eq_closure_graph],
exact f.graph.is_closed_topological_closure,
end
/-- If `f` is closable, then the closure is closable. -/
lemma is_closable.closure_is_closable {f : E →ₗ.[R] F} (hf : f.is_closable) :
f.closure.is_closable :=
hf.closure_is_closed.is_closable
lemma is_closable_iff_exists_closed_extension {f : E →ₗ.[R] F} : f.is_closable ↔
∃ (g : E →ₗ.[R] F) (hg : g.is_closed), f ≤ g :=
⟨λ h, ⟨f.closure, h.closure_is_closed, f.le_closure⟩, λ ⟨_, hg, h⟩, hg.is_closable.le_is_closable h⟩
/-! ### The core of a linear operator -/
/-- A submodule `S` is a core of `f` if the closure of the restriction of `f` to `S` is again `f`.-/
structure has_core (f : E →ₗ.[R] F) (S : submodule R E) : Prop :=
(le_domain : S ≤ f.domain)
(closure_eq : (f.dom_restrict S).closure = f)
lemma has_core_def {f : E →ₗ.[R] F} {S : submodule R E} (h : f.has_core S) :
(f.dom_restrict S).closure = f := h.2
/-- For every unbounded operator `f` the submodule `f.domain` is a core of its closure.
Note that we don't require that `f` is closable, due to the definition of the closure. -/
lemma closure_has_core (f : E →ₗ.[R] F) : f.closure.has_core f.domain :=
begin
refine ⟨f.le_closure.1, _⟩,
congr,
ext,
{ simp only [dom_restrict_domain, submodule.mem_inf, and_iff_left_iff_imp],
intro hx,
exact f.le_closure.1 hx },
intros x y hxy,
let z : f.closure.domain := ⟨y.1, f.le_closure.1 y.2⟩,
have hyz : (y : E) = z := by simp,
rw f.le_closure.2 hyz,
exact dom_restrict_apply (hxy.trans hyz),
end
end linear_pmap
|
d6b07c5911542e5bbaa52095368741cd90574f81 | 367134ba5a65885e863bdc4507601606690974c1 | /src/tactic/ring_exp.lean | d720ac50ca7e504c33a80e143dc65f71ab961765 | [
"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 | 57,155 | lean | /-
Copyright (c) 2019 Tim Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Tim Baanen.
Solve equations in commutative (semi)rings with exponents.
-/
import tactic.norm_num
import control.traversable.basic
/-!
# `ring_exp` tactic
A tactic for solving equations in commutative (semi)rings,
where the exponents can also contain variables.
More precisely, expressions of the following form are supported:
- constants (non-negative integers)
- variables
- coefficients (any rational number, embedded into the (semi)ring)
- addition of expressions
- multiplication of expressions
- exponentiation of expressions (the exponent must have type `ℕ`)
- subtraction and negation of expressions (if the base is a full ring)
The motivating example is proving `2 * 2^n * b = b * 2^(n+1)`,
something that the `ring` tactic cannot do, but `ring_exp` can.
## Implementation notes
The basic approach to prove equalities is to normalise both sides and check for equality.
The normalisation is guided by building a value in the type `ex` at the meta level,
together with a proof (at the base level) that the original value is equal to
the normalised version.
The normalised version and normalisation proofs are also stored in the `ex` type.
The outline of the file:
- Define an inductive family of types `ex`, parametrised over `ex_type`,
which can represent expressions with `+`, `*`, `^` and rational numerals.
The parametrisation over `ex_type` ensures that associativity and distributivity are applied,
by restricting which kinds of subexpressions appear as arguments to the various operators.
- Represent addition, multiplication and exponentiation in the `ex` type,
thus allowing us to map expressions to `ex` (the `eval` function drives this).
We apply associativity and distributivity of the operators here (helped by `ex_type`)
and commutativity as well (by sorting the subterms; unfortunately not helped by anything).
Any expression not of the above formats is treated as an atom (the same as a variable).
There are some details we glossed over which make the plan more complicated:
- The order on atoms is not initially obvious.
We construct a list containing them in order of initial appearance in the expression,
then use the index into the list as a key to order on.
- In the tactic, a normalized expression `ps : ex` lives in the meta-world,
but the normalization proofs live in the real world.
Thus, we cannot directly say `ps.orig = ps.pretty` anywhere,
but we have to carefully construct the proof when we compute `ps`.
This was a major source of bugs in development!
- For `pow`, the exponent must be a natural number, while the base can be any semiring `α`.
We swap out operations for the base ring `α` with those for the exponent ring `ℕ`
as soon as we deal with exponents.
This is accomplished by the `in_exponent` function and is relatively painless since
we work in a `reader` monad.
- The normalized form of an expression is the one that is useful for the tactic,
but not as nice to read. To remedy this, the user-facing normalization calls `ex.simp`.
## Caveats and future work
Subtraction cancels out identical terms, but division does not.
That is: `a - a = 0 := by ring_exp` solves the goal,
but `a / a := 1 by ring_exp` doesn't.
Note that `0 / 0` is generally defined to be `0`,
so division cancelling out is not true in general.
Multiplication of powers can be simplified a little bit further:
`2 ^ n * 2 ^ n = 4 ^ n := by ring_exp` could be implemented
in a similar way that `2 * a + 2 * a = 4 * a := by ring_exp` already works.
This feature wasn't needed yet, so it's not implemented yet.
## Tags
ring, semiring, exponent, power
-/
-- The base ring `α` will have a universe level `u`.
-- We do not introduce `α` as a variable yet,
-- in order to make it explicit or implicit as required.
universes u
namespace tactic.ring_exp
open nat
/--
The `atom` structure is used to represent atomic expressions:
those which `ring_exp` cannot parse any further.
For instance, `a + (a % b)` has `a` and `(a % b)` as atoms.
The `ring_exp_eq` tactic does not normalize the subexpressions in atoms,
but `ring_exp` does if `ring_exp_eq` was not sufficient.
Atoms in fact represent equivalence classes of expressions,
modulo definitional equality.
The field `index : ℕ` should be a unique number for each class,
while `value : expr` contains a representative of this class.
The function `resolve_atom` determines the appropriate atom
for a given expression.
-/
meta structure atom : Type := (value : expr) (index : ℕ)
namespace atom
/--
The `eq` operation on `atom`s works modulo definitional equality,
ignoring their `value`s.
The invariants on `atom` ensure indices are unique per value.
Thus, `eq` indicates equality as long as the `atom`s come from the same context.
-/
meta def eq (a b : atom) : bool := a.index = b.index
/--
We order `atom`s on the order of appearance in the main expression.
-/
meta def lt (a b : atom) : bool := a.index < b.index
meta instance : has_repr atom := ⟨λ x, "(atom " ++ repr x.2 ++ ")"⟩
end atom
section expression
/-!
### `expression` section
In this section, we define the `ex` type and its basic operations.
First, we introduce the supporting types `coeff`, `ex_type` and `ex_info`.
For understanding the code, it's easier to check out `ex` itself first,
then refer back to the supporting types.
The arithmetic operations on `ex` need additional definitions,
so they are defined in a later section.
-/
/--
Coefficients in the expression are stored in a wrapper structure,
allowing for easier modification of the data structures.
The modifications might be caching of the result of `expr.of_rat`,
or using a different meta representation of numerals.
-/
@[derive decidable_eq, derive inhabited]
structure coeff : Type := (value : ℚ)
/-- The values in `ex_type` are used as parameters to `ex` to control the expression's structure. -/
@[derive decidable_eq, derive inhabited]
inductive ex_type : Type
| base : ex_type
| sum : ex_type
| prod : ex_type
| exp : ex_type
open ex_type
/--
Each `ex` stores information for its normalization proof.
The `orig` expression is the expression that was passed to `eval`.
The `pretty` expression is the normalised form that the `ex` represents.
(I didn't call this something like `norm`, because there are already
too many things called `norm` in mathematics!)
The field `proof` contains an optional proof term of type `%%orig = %%pretty`.
The value `none` for the proof indicates that everything reduces to reflexivity.
(Which saves space in quite a lot of cases.)
-/
meta structure ex_info : Type :=
(orig : expr) (pretty : expr) (proof : option expr)
/--
The `ex` type is an abstract representation of an expression with `+`, `*` and `^`.
Those operators are mapped to the `sum`, `prod` and `exp` constructors respectively.
The `zero` constructor is the base case for `ex sum`, e.g. `1 + 2` is represented
by (something along the lines of) `sum 1 (sum 2 zero)`.
The `coeff` constructor is the base case for `ex prod`, and is used for numerals.
The code maintains the invariant that the coefficient is never `0`.
The `var` constructor is the base case for `ex exp`, and is used for atoms.
The `sum_b` constructor allows for addition in the base of an exponentiation;
it serves a similar purpose as the parentheses in `(a + b)^c`.
The code maintains the invariant that the argument to `sum_b` is not `zero`
or `sum _ zero`.
All of the constructors contain an `ex_info` field,
used to carry around (arguments to) proof terms.
While the `ex_type` parameter enforces some simplification invariants,
the following ones must be manually maintained at the risk of insufficient power:
- the argument to `coeff` must be nonzero (to ensure `0 = 0 * 1`)
- the argument to `sum_b` must be of the form `sum a (sum b bs)` (to ensure `(a + 0)^n = a^n`)
- normalisation proofs of subexpressions must be `refl ps.pretty`
- if we replace `sum` with `cons` and `zero` with `nil`, the resulting list is sorted
according to the `lt` relation defined further down; similarly for `prod` and `coeff`
(to ensure `a + b = b + a`).
The first two invariants could be encoded in a subtype of `ex`,
but aren't (yet) to spare some implementation burden.
The other invariants cannot be encoded because we need the `tactic` monad to check them.
(For example, the correct equality check of `expr` is `is_def_eq : expr → expr → tactic unit`.)
-/
meta inductive ex : ex_type → Type
| zero (info : ex_info) : ex sum
| sum (info : ex_info) : ex prod → ex sum → ex sum
| coeff (info : ex_info) : coeff → ex prod
| prod (info : ex_info) : ex exp → ex prod → ex prod
| var (info : ex_info) : atom → ex base
| sum_b (info : ex_info) : ex sum → ex base
| exp (info : ex_info) : ex base → ex prod → ex exp
/--
Return the proof information associated to the `ex`.
-/
meta def ex.info : Π {et : ex_type} (ps : ex et), ex_info
| sum (ex.zero i) := i
| sum (ex.sum i _ _) := i
| prod (ex.coeff i _) := i
| prod (ex.prod i _ _) := i
| base (ex.var i _) := i
| base (ex.sum_b i _) := i
| exp (ex.exp i _ _) := i
/--
Return the original, non-normalized version of this `ex`.
Note that arguments to another `ex` are always "pre-normalized":
their `orig` and `pretty` are equal, and their `proof` is reflexivity.
-/
meta def ex.orig {et : ex_type} (ps : ex et) : expr := ps.info.orig
/--
Return the normalized version of this `ex`.
-/
meta def ex.pretty {et : ex_type} (ps : ex et) : expr := ps.info.pretty
/--
Return the normalisation proof of the given expression.
If the proof is `refl`, we give `none` instead,
which helps to control the size of proof terms.
To get an actual term, use `ex.proof_term`,
or use `mk_proof` with the correct set of arguments.
-/
meta def ex.proof {et : ex_type} (ps : ex et) : option expr := ps.info.proof
/--
Update the `orig` and `proof` fields of the `ex_info`.
Intended for use in `ex.set_info`.
-/
meta def ex_info.set (i : ex_info) (o : option expr) (pf : option expr) : ex_info :=
{orig := o.get_or_else i.pretty, proof := pf, .. i}
/--
Update the `ex_info` of the given expression.
We use this to combine intermediate normalisation proofs.
Since `pretty` only depends on the subexpressions,
which do not change, we do not set `pretty`.
-/
meta def ex.set_info : Π {et : ex_type} (ps : ex et), option expr → option expr → ex et
| sum (ex.zero i) o pf := ex.zero (i.set o pf)
| sum (ex.sum i p ps) o pf := ex.sum (i.set o pf) p ps
| prod (ex.coeff i x) o pf := ex.coeff (i.set o pf) x
| prod (ex.prod i p ps) o pf := ex.prod (i.set o pf) p ps
| base (ex.var i x) o pf := ex.var (i.set o pf) x
| base (ex.sum_b i ps) o pf := ex.sum_b (i.set o pf) ps
| exp (ex.exp i p ps) o pf := ex.exp (i.set o pf) p ps
instance coeff_has_repr : has_repr coeff := ⟨λ x, repr x.1⟩
/-- Convert an `ex` to a `string`. -/
meta def ex.repr : Π {et : ex_type}, ex et → string
| sum (ex.zero _) := "0"
| sum (ex.sum _ p ps) := ex.repr p ++ " + " ++ ex.repr ps
| prod (ex.coeff _ x) := repr x
| prod (ex.prod _ p ps) := ex.repr p ++ " * " ++ ex.repr ps
| base (ex.var _ x) := repr x
| base (ex.sum_b _ ps) := "(" ++ ex.repr ps ++ ")"
| exp (ex.exp _ p ps) := ex.repr p ++ " ^ " ++ ex.repr ps
meta instance {et : ex_type} : has_repr (ex et) := ⟨ex.repr⟩
/--
Equality test for expressions.
Since equivalence of `atom`s is not the same as equality,
we cannot make a true `(=)` operator for `ex` either.
-/
meta def ex.eq : Π {et : ex_type}, ex et → ex et → bool
| sum (ex.zero _) (ex.zero _) := tt
| sum (ex.zero _) (ex.sum _ _ _) := ff
| sum (ex.sum _ _ _) (ex.zero _) := ff
| sum (ex.sum _ p ps) (ex.sum _ q qs) := p.eq q && ps.eq qs
| prod (ex.coeff _ x) (ex.coeff _ y) := x = y
| prod (ex.coeff _ _) (ex.prod _ _ _) := ff
| prod (ex.prod _ _ _) (ex.coeff _ _) := ff
| prod (ex.prod _ p ps) (ex.prod _ q qs) := p.eq q && ps.eq qs
| base (ex.var _ x) (ex.var _ y) := x.eq y
| base (ex.var _ _) (ex.sum_b _ _) := ff
| base (ex.sum_b _ _) (ex.var _ _) := ff
| base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.eq qs
| exp (ex.exp _ p ps) (ex.exp _ q qs) := p.eq q && ps.eq qs
/--
The ordering on expressions.
As for `ex.eq`, this is a linear order only in one context.
-/
meta def ex.lt : Π {et : ex_type}, ex et → ex et → bool
| sum _ (ex.zero _) := ff
| sum (ex.zero _) _ := tt
| sum (ex.sum _ p ps) (ex.sum _ q qs) := p.lt q || (p.eq q && ps.lt qs)
| prod (ex.coeff _ x) (ex.coeff _ y) := x.1 < y.1
| prod (ex.coeff _ _) _ := tt
| prod _ (ex.coeff _ _) := ff
| prod (ex.prod _ p ps) (ex.prod _ q qs) := p.lt q || (p.eq q && ps.lt qs)
| base (ex.var _ x) (ex.var _ y) := x.lt y
| base (ex.var _ _) (ex.sum_b _ _) := tt
| base (ex.sum_b _ _) (ex.var _ _) := ff
| base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.lt qs
| exp (ex.exp _ p ps) (ex.exp _ q qs) := p.lt q || (p.eq q && ps.lt qs)
end expression
section operations
/-!
### `operations` section
This section defines the operations (on `ex`) that use tactics.
They live in the `ring_exp_m` monad,
which adds a cache and a list of encountered atoms to the `tactic` monad.
Throughout this section, we will be constructing proof terms.
The lemmas used in the construction are all defined over a commutative semiring α.
-/
variables {α : Type u} [comm_semiring α]
open tactic
open ex_type
/--
Stores the information needed in the `eval` function and its dependencies,
so they can (re)construct expressions.
The `eval_info` structure stores this information for one type,
and the `context` combines the two types, one for bases and one for exponents.
-/
meta structure eval_info :=
(α : expr) (univ : level)
-- Cache the instances for optimization and consistency
(csr_instance : expr) (ha_instance : expr) (hm_instance : expr) (hp_instance : expr)
-- Optional instances (only required for (-) and (/) respectively)
(ring_instance : option expr) (dr_instance : option expr)
-- Cache common constants.
(zero : expr) (one : expr)
/--
The `context` contains the full set of information needed for the `eval` function.
This structure has two copies of `eval_info`:
one is for the base (typically some semiring `α`) and another for the exponent (always `ℕ`).
When evaluating an exponent, we put `info_e` in `info_b`.
-/
meta structure context :=
(info_b : eval_info) (info_e : eval_info) (transp : transparency)
/--
The `ring_exp_m` monad is used instead of `tactic` to store the context.
-/
@[derive [monad, alternative]]
meta def ring_exp_m (α : Type) : Type := reader_t context (state_t (list atom) tactic) α
/--
Access the instance cache.
-/
meta def get_context : ring_exp_m context := reader_t.read
/--
Lift an operation in the `tactic` monad to the `ring_exp_m` monad.
This operation will not access the cache.
-/
meta def lift {α} (m : tactic α) : ring_exp_m α := reader_t.lift (state_t.lift m)
/--
Change the context of the given computation,
so that expressions are evaluated in the exponent ring,
instead of the base ring.
-/
meta def in_exponent {α} (mx : ring_exp_m α) : ring_exp_m α := do
ctx ← get_context,
reader_t.lift $ mx.run ⟨ctx.info_e, ctx.info_e, ctx.transp⟩
/--
Specialized version of `mk_app` where the first two arguments are `{α}` `[some_class α]`.
Should be faster because it can use the cached instances.
-/
meta def mk_app_class (f : name) (inst : expr) (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
pure $ (@expr.const tt f [ctx.info_b.univ] ctx.info_b.α inst).mk_app args
/--
Specialized version of `mk_app` where the first two arguments are `{α}` `[comm_semiring α]`.
Should be faster because it can use the cached instances.
-/
meta def mk_app_csr (f : name) (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class f (ctx.info_b.csr_instance) args
/--
Specialized version of `mk_app ``has_add.add`.
Should be faster because it can use the cached instances.
-/
meta def mk_add (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class ``has_add.add ctx.info_b.ha_instance args
/--
Specialized version of `mk_app ``has_mul.mul`.
Should be faster because it can use the cached instances.
-/
meta def mk_mul (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class ``has_mul.mul ctx.info_b.hm_instance args
/--
Specialized version of `mk_app ``has_pow.pow`.
Should be faster because it can use the cached instances.
-/
meta def mk_pow (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
pure $ (@expr.const tt ``has_pow.pow
[ctx.info_b.univ, ctx.info_e.univ]
ctx.info_b.α ctx.info_e.α
ctx.info_b.hp_instance).mk_app args
/-- Construct a normalization proof term or return the cached one. -/
meta def ex_info.proof_term (ps : ex_info) : ring_exp_m expr :=
match ps.proof with
| none := lift $ tactic.mk_eq_refl ps.pretty
| (some p) := pure p
end
/-- Construct a normalization proof term or return the cached one. -/
meta def ex.proof_term {et : ex_type} (ps : ex et) : ring_exp_m expr := ps.info.proof_term
/--
If all `ex_info` have trivial proofs, return a trivial proof.
Otherwise, construct all proof terms.
Useful in applications where trivial proofs combine to another trivial proof,
most importantly to pass to `mk_proof_or_refl`.
-/
meta def none_or_proof_term : list ex_info → ring_exp_m (option (list expr))
| [] := pure none
| (x :: xs) := do
xs_pfs ← none_or_proof_term xs,
match (x.proof, xs_pfs) with
| (none, none) := pure none
| (some x_pf, none) := do
xs_pfs ← traverse ex_info.proof_term xs,
pure (some (x_pf :: xs_pfs))
| (_, some xs_pfs) := do
x_pf ← x.proof_term,
pure (some (x_pf :: xs_pfs))
end
/--
Use the proof terms as arguments to the given lemma.
If the lemma could reduce to reflexivity, consider using `mk_proof_or_refl.`
-/
meta def mk_proof (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do
hs' ← traverse ex_info.proof_term hs,
mk_app_csr lem (args ++ hs')
/--
Use the proof terms as arguments to the given lemma.
Often, we construct a proof term using congruence where reflexivity suffices.
To solve this, the following function tries to get away with reflexivity.
-/
meta def mk_proof_or_refl (term : expr) (lem : name) (args : list expr) (hs : list ex_info) :
ring_exp_m expr := do
hs_full ← none_or_proof_term hs,
match hs_full with
| none := lift $ mk_eq_refl term
| (some hs') := mk_app_csr lem (args ++ hs')
end
/-- A shortcut for adding the original terms of two expressions. -/
meta def add_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_add [ps.orig, qs.orig]
/-- A shortcut for multiplying the original terms of two expressions. -/
meta def mul_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_mul [ps.orig, qs.orig]
/-- A shortcut for exponentiating the original terms of two expressions. -/
meta def pow_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_pow [ps.orig, qs.orig]
/-- Congruence lemma for constructing `ex.sum`. -/
lemma sum_congr {p p' ps ps' : α} : p = p' → ps = ps' → p + ps = p' + ps' := by cc
/-- Congruence lemma for constructing `ex.prod`. -/
lemma prod_congr {p p' ps ps' : α} : p = p' → ps = ps' → p * ps = p' * ps' := by cc
/-- Congruence lemma for constructing `ex.exp`. -/
lemma exp_congr {p p' : α} {ps ps' : ℕ} : p = p' → ps = ps' → p ^ ps = p' ^ ps' := by cc
/-- Constructs `ex.zero` with the correct arguments. -/
meta def ex_zero : ring_exp_m (ex sum) := do
ctx ← get_context,
pure $ ex.zero ⟨ctx.info_b.zero, ctx.info_b.zero, none⟩
/-- Constructs `ex.sum` with the correct arguments. -/
meta def ex_sum (p : ex prod) (ps : ex sum) : ring_exp_m (ex sum) := do
pps_o ← add_orig p ps,
pps_p ← mk_add [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``sum_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.sum ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
/--
Constructs `ex.coeff` with the correct arguments.
There are more efficient constructors for specific numerals:
if `x = 0`, you should use `ex_zero`; if `x = 1`, use `ex_one`.
-/
meta def ex_coeff (x : rat) : ring_exp_m (ex prod) := do
ctx ← get_context,
x_p ← lift $ expr.of_rat ctx.info_b.α x,
pure (ex.coeff ⟨x_p, x_p, none⟩ ⟨x⟩)
/--
Constructs `ex.coeff 1` with the correct arguments.
This is a special case for optimization purposes.
-/
meta def ex_one : ring_exp_m (ex prod) := do
ctx ← get_context,
pure $ ex.coeff ⟨ctx.info_b.one, ctx.info_b.one, none⟩ ⟨1⟩
/-- Constructs `ex.prod` with the correct arguments. -/
meta def ex_prod (p : ex exp) (ps : ex prod) : ring_exp_m (ex prod) := do
pps_o ← mul_orig p ps,
pps_p ← mk_mul [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``prod_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.prod ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
/-- Constructs `ex.var` with the correct arguments. -/
meta def ex_var (p : atom) : ring_exp_m (ex base) := pure (ex.var ⟨p.1, p.1, none⟩ p)
/-- Constructs `ex.sum_b` with the correct arguments. -/
meta def ex_sum_b (ps : ex sum) : ring_exp_m (ex base) :=
pure (ex.sum_b ps.info (ps.set_info none none))
/-- Constructs `ex.exp` with the correct arguments. -/
meta def ex_exp (p : ex base) (ps : ex prod) : ring_exp_m (ex exp) := do
ctx ← get_context,
pps_o ← pow_orig p ps,
pps_p ← mk_pow [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``exp_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.exp ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
lemma base_to_exp_pf {p p' : α} : p = p' → p = p' ^ 1 := by simp
/-- Conversion from `ex base` to `ex exp`. -/
meta def base_to_exp (p : ex base) : ring_exp_m (ex exp) := do
o ← in_exponent $ ex_one,
ps ← ex_exp p o,
pf ← mk_proof ``base_to_exp_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma exp_to_prod_pf {p p' : α} : p = p' → p = p' * 1 := by simp
/-- Conversion from `ex exp` to `ex prod`. -/
meta def exp_to_prod (p : ex exp) : ring_exp_m (ex prod) := do
o ← ex_one,
ps ← ex_prod p o,
pf ← mk_proof ``exp_to_prod_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma prod_to_sum_pf {p p' : α} : p = p' → p = p' + 0 := by simp
/-- Conversion from `ex prod` to `ex sum`. -/
meta def prod_to_sum (p : ex prod) : ring_exp_m (ex sum) := do
z ← ex_zero,
ps ← ex_sum p z,
pf ← mk_proof ``prod_to_sum_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma atom_to_sum_pf (p : α) : p = p ^ 1 * 1 + 0 := by simp
/--
A more efficient conversion from `atom` to `ex sum`.
The result should be the same as `ex_var p >>= base_to_exp >>= exp_to_prod >>= prod_to_sum`,
except we need to calculate less intermediate steps.
-/
meta def atom_to_sum (p : atom) : ring_exp_m (ex sum) := do
p' ← ex_var p,
o ← in_exponent $ ex_one,
p' ← ex_exp p' o,
o ← ex_one,
p' ← ex_prod p' o,
z ← ex_zero,
p' ← ex_sum p' z,
pf ← mk_proof ``atom_to_sum_pf [p.1] [],
pure $ p'.set_info p.1 pf
/--
Compute the sum of two coefficients.
Note that the result might not be a valid expression:
if `p = -q`, then the result should be `ex.zero : ex sum` instead.
The caller must detect when this happens!
The returned value is of the form `ex.coeff _ (p + q)`,
with the proof of `expr.of_rat p + expr.of_rat q = expr.of_rat (p + q)`.
-/
meta def add_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do
ctx ← get_context,
pq_o ← mk_add [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_field pq_o,
pure $ ex.coeff ⟨pq_o, pq_p, pq_pf⟩ ⟨p.1 + q.1⟩
lemma mul_coeff_pf_one_mul (q : α) : 1 * q = q := one_mul q
lemma mul_coeff_pf_mul_one (p : α) : p * 1 = p := mul_one p
/--
Compute the product of two coefficients.
The returned value is of the form `ex.coeff _ (p * q)`,
with the proof of `expr.of_rat p * expr.of_rat q = expr.of_rat (p * q)`.
-/
meta def mul_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) :=
match p.1, q.1 with -- Special case to speed up multiplication with 1.
| ⟨1, 1, _, _⟩, _ := do
ctx ← get_context,
pq_o ← mk_mul [p_p, q_p],
pf ← mk_app_csr ``mul_coeff_pf_one_mul [q_p],
pure $ ex.coeff ⟨pq_o, q_p, pf⟩ ⟨q.1⟩
| _, ⟨1, 1, _, _⟩ := do
ctx ← get_context,
pq_o ← mk_mul [p_p, q_p],
pf ← mk_app_csr ``mul_coeff_pf_mul_one [p_p],
pure $ ex.coeff ⟨pq_o, p_p, pf⟩ ⟨p.1⟩
| _, _ := do
ctx ← get_context,
pq' ← mk_mul [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_field pq',
pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩
end
section rewrite
/-! ### `rewrite` section
In this section we deal with rewriting terms to fit in the basic grammar of `eval`.
For example, `nat.succ n` is rewritten to `n + 1` before it is evaluated further.
-/
/-- Given a proof that the expressions `ps_o` and `ps'.orig` are equal,
show that `ps_o` and `ps'.pretty` are equal.
Useful to deal with aliases in `eval`. For instance, `nat.succ p` can be handled
as an alias of `p + 1` as follows:
```
| ps_o@`(nat.succ %%p_o) := do
ps' ← eval `(%%p_o + 1),
pf ← lift $ mk_app ``nat.succ_eq_add_one [p_o],
rewrite ps_o ps' pf
```
-/
meta def rewrite (ps_o : expr) (ps' : ex sum) (pf : expr) : ring_exp_m (ex sum) :=
do
ps'_pf ← ps'.info.proof_term,
pf ← lift $ mk_eq_trans pf ps'_pf,
pure $ ps'.set_info ps_o pf
end rewrite
/--
Represents the way in which two products are equal except coefficient.
This type is used in the function `add_overlap`.
In order to deal with equations of the form `a * 2 + a = 3 * a`,
the `add` function will add up overlapping products,
turning `a * 2 + a` into `a * 3`.
We need to distinguish `a * 2 + a` from `a * 2 + b` in order to do this,
and the `overlap` type carries the information on how it overlaps.
The case `none` corresponds to non-overlapping products, e.g. `a * 2 + b`;
the case `nonzero` to overlapping products adding to non-zero, e.g. `a * 2 + a`
(the `ex prod` field will then look like `a * 3` with a proof that `a * 2 + a = a * 3`);
the case `zero` to overlapping products adding to zero, e.g. `a * 2 + a * -2`.
We distinguish those two cases because in the second, the whole product reduces to `0`.
A potential extension to the tactic would also do this for the base of exponents,
e.g. to show `2^n * 2^n = 4^n`.
-/
meta inductive overlap : Type
| none : overlap
| nonzero : ex prod → overlap
| zero : ex sum → overlap
lemma add_overlap_pf {ps qs pq} (p : α) : ps + qs = pq → p * ps + p * qs = p * pq := λ pq_pf, calc
p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _)
... = p * pq : by rw pq_pf
lemma add_overlap_pf_zero {ps qs} (p : α) : ps + qs = 0 → p * ps + p * qs = 0 := λ pq_pf, calc
p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _)
... = p * 0 : by rw pq_pf
... = 0 : mul_zero _
/--
Given arguments `ps`, `qs` of the form `ps' * x` and `ps' * y` respectively
return `ps + qs = ps' * (x + y)` (with `x` and `y` arbitrary coefficients).
For other arguments, return `overlap.none`.
-/
meta def add_overlap : ex prod → ex prod → ring_exp_m overlap
| (ex.coeff x_i x) (ex.coeff y_i y) := do
xy@(ex.coeff _ xy_c) ← add_coeff x_i.pretty y_i.pretty x y
| lift $ fail "internal error: add_coeff should return ex.coeff",
if xy_c.1 = 0
then do
z ← ex_zero,
pure $ overlap.zero (z.set_info xy.orig xy.proof)
else pure $ overlap.nonzero xy
| (ex.prod _ _ _) (ex.coeff _ _) := pure overlap.none
| (ex.coeff _ _) (ex.prod _ _ _) := pure overlap.none
| pps@(ex.prod _ p ps) qqs@(ex.prod _ q qs) := if p.eq q
then do
pq_ol ← add_overlap ps qs,
pqs_o ← add_orig pps qqs,
match pq_ol with
| overlap.none := pure overlap.none
| (overlap.nonzero pq) := do
pqs ← ex_prod p pq,
pf ← mk_proof ``add_overlap_pf
[ps.pretty, qs.pretty, pq.pretty, p.pretty]
[pq.info],
pure $ overlap.nonzero (pqs.set_info pqs_o pf)
| (overlap.zero pq) := do
z ← ex_zero,
pf ← mk_proof ``add_overlap_pf_zero
[ps.pretty, qs.pretty, p.pretty]
[pq.info],
pure $ overlap.zero (z.set_info pqs_o pf)
end
else pure overlap.none
section addition
lemma add_pf_z_sum {ps qs qs' : α} : ps = 0 → qs = qs' → ps + qs = qs' := λ ps_pf qs_pf, calc
ps + qs = 0 + qs' : by rw [ps_pf, qs_pf]
... = qs' : zero_add _
lemma add_pf_sum_z {ps ps' qs : α} : ps = ps' → qs = 0 → ps + qs = ps' := λ ps_pf qs_pf, calc
ps + qs = ps' + 0 : by rw [ps_pf, qs_pf]
... = ps' : add_zero _
lemma add_pf_sum_overlap {pps p ps qqs q qs pq pqs : α} :
pps = p + ps → qqs = q + qs → p + q = pq → ps + qs = pqs → pps + qqs = pq + pqs := by cc
lemma add_pf_sum_overlap_zero {pps p ps qqs q qs pqs : α} :
pps = p + ps → qqs = q + qs → p + q = 0 → ps + qs = pqs → pps + qqs = pqs :=
λ pps_pf qqs_pf pq_pf pqs_pf, calc
pps + qqs = (p + ps) + (q + qs) : by rw [pps_pf, qqs_pf]
... = (p + q) + (ps + qs) : by cc
... = 0 + pqs : by rw [pq_pf, pqs_pf]
... = pqs : zero_add _
lemma add_pf_sum_lt {pps p ps qqs pqs : α} :
pps = p + ps → ps + qqs = pqs → pps + qqs = p + pqs := by cc
lemma add_pf_sum_gt {pps qqs q qs pqs : α} :
qqs = q + qs → pps + qs = pqs → pps + qqs = q + pqs := by cc
/--
Add two expressions.
* `0 + qs = 0`
* `ps + 0 = 0`
* `ps * x + ps * y = ps * (x + y)` (for `x`, `y` coefficients; uses `add_overlap`)
* `(p + ps) + (q + qs) = p + (ps + (q + qs))` (if `p.lt q`)
* `(p + ps) + (q + qs) = q + ((p + ps) + qs)` (if not `p.lt q`)
-/
meta def add : ex sum → ex sum → ring_exp_m (ex sum)
| ps@(ex.zero ps_i) qs := do
pf ← mk_proof ``add_pf_z_sum [ps.orig, qs.orig, qs.pretty] [ps.info, qs.info],
pqs_o ← add_orig ps qs,
pure $ qs.set_info pqs_o pf
| ps qs@(ex.zero qs_i) := do
pf ← mk_proof ``add_pf_sum_z [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info],
pqs_o ← add_orig ps qs,
pure $ ps.set_info pqs_o pf
| pps@(ex.sum pps_i p ps) qqs@(ex.sum qqs_i q qs) := do
ol ← add_overlap p q,
ppqqs_o ← add_orig pps qqs,
match ol with
| (overlap.nonzero pq) := do
pqs ← add ps qs,
pqqs ← ex_sum pq pqs,
qqs_pf ← qqs.proof_term,
pf ← mk_proof ``add_pf_sum_overlap
[pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pq.pretty, pqs.pretty]
[pps.info, qqs.info, pq.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
| (overlap.zero pq) := do
pqs ← add ps qs,
pf ← mk_proof ``add_pf_sum_overlap_zero
[pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[pps.info, qqs.info, pq.info, pqs.info],
pure $ pqs.set_info ppqqs_o pf
| overlap.none := if p.lt q
then do
pqs ← add ps qqs,
ppqs ← ex_sum p pqs,
pf ← mk_proof ``add_pf_sum_lt
[pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqqs_o pf
else do
pqs ← add pps qs,
pqqs ← ex_sum q pqs,
pf ← mk_proof ``add_pf_sum_gt
[pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
end
end addition
section multiplication
lemma mul_pf_c_c {ps ps' qs qs' pq : α} :
ps = ps' → qs = qs' → ps' * qs' = pq → ps * qs = pq := by cc
lemma mul_pf_c_prod {ps qqs q qs pqs : α} :
qqs = q * qs → ps * qs = pqs → ps * qqs = q * pqs := by cc
lemma mul_pf_prod_c {pps p ps qs pqs : α} :
pps = p * ps → ps * qs = pqs → pps * qs = p * pqs := by cc
lemma mul_pp_pf_overlap {pps p_b ps qqs qs psqs : α} {p_e q_e : ℕ} :
pps = p_b ^ p_e * ps → qqs = p_b ^ q_e * qs →
p_b ^ (p_e + q_e) * (ps * qs) = psqs → pps * qqs = psqs
:= λ ps_pf qs_pf psqs_pf, by simp [symm psqs_pf, pow_add, ps_pf, qs_pf]; ac_refl
lemma mul_pp_pf_prod_lt {pps p ps qqs pqs : α} :
pps = p * ps → ps * qqs = pqs → pps * qqs = p * pqs := by cc
lemma mul_pp_pf_prod_gt {pps qqs q qs pqs : α} :
qqs = q * qs → pps * qs = pqs → pps * qqs = q * pqs := by cc
/--
Multiply two expressions.
* `x * y = (x * y)` (for `x`, `y` coefficients)
* `x * (q * qs) = q * (qs * x)` (for `x` coefficient)
* `(p * ps) * y = p * (ps * y)` (for `y` coefficient)
* `(p_b^p_e * ps) * (p_b^q_e * qs) = p_b^(p_e + q_e) * (ps * qs)`
(if `p_e` and `q_e` are identical except coefficient)
* `(p * ps) * (q * qs) = p * (ps * (q * qs))` (if `p.lt q`)
* `(p * ps) * (q * qs) = q * ((p * ps) * qs)` (if not `p.lt q`)
-/
meta def mul_pp : ex prod → ex prod → ring_exp_m (ex prod)
| ps@(ex.coeff _ x) qs@(ex.coeff _ y) := do
pq ← mul_coeff ps.pretty qs.pretty x y,
pq_o ← mul_orig ps qs,
pf ← mk_proof_or_refl pq.pretty ``mul_pf_c_c
[ps.orig, ps.pretty, qs.orig, qs.pretty, pq.pretty]
[ps.info, qs.info, pq.info],
pure $ pq.set_info pq_o pf
| ps@(ex.coeff _ x) qqs@(ex.prod _ q qs) := do
pqs ← mul_pp ps qs,
pqqs ← ex_prod q pqs,
pqqs_o ← mul_orig ps qqs,
pf ← mk_proof ``mul_pf_c_prod
[ps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info pqqs_o pf
| pps@(ex.prod _ p ps) qs@(ex.coeff _ y) := do
pqs ← mul_pp ps qs,
ppqs ← ex_prod p pqs,
ppqs_o ← mul_orig pps qs,
pf ← mk_proof ``mul_pf_prod_c
[pps.orig, p.pretty, ps.pretty, qs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqs_o pf
| pps@(ex.prod _ p@(ex.exp _ p_b p_e) ps) qqs@(ex.prod _ q@(ex.exp _ q_b q_e) qs) := do
ppqqs_o ← mul_orig pps qqs,
pq_ol ← in_exponent $ add_overlap p_e q_e,
match pq_ol, p_b.eq q_b with
| (overlap.nonzero pq_e), tt := do
psqs ← mul_pp ps qs,
pq ← ex_exp p_b pq_e,
ppsqqs ← ex_prod pq psqs,
pf ← mk_proof ``mul_pp_pf_overlap
[pps.orig, p_b.pretty, ps.pretty, qqs.orig, qs.pretty, ppsqqs.pretty, p_e.pretty, q_e.pretty]
[pps.info, qqs.info, ppsqqs.info],
pure $ ppsqqs.set_info ppqqs_o pf
| _, _ := if p.lt q then do
pqs ← mul_pp ps qqs,
ppqs ← ex_prod p pqs,
pf ← mk_proof ``mul_pp_pf_prod_lt
[pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqqs_o pf
else do
pqs ← mul_pp pps qs,
pqqs ← ex_prod q pqs,
pf ← mk_proof ``mul_pp_pf_prod_gt
[pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
end
lemma mul_p_pf_zero {ps qs : α} : ps = 0 → ps * qs = 0 :=
λ ps_pf, by rw [ps_pf, zero_mul]
lemma mul_p_pf_sum {pps p ps qs ppsqs : α} : pps = p + ps →
p * qs + ps * qs = ppsqs → pps * qs = ppsqs := λ pps_pf ppsqs_pf, calc
pps * qs = (p + ps) * qs : by rw [pps_pf]
... = p * qs + ps * qs : add_mul _ _ _
... = ppsqs : ppsqs_pf
/--
Multiply two expressions.
* `0 * qs = 0`
* `(p + ps) * qs = (p * qs) + (ps * qs)`
-/
meta def mul_p : ex sum → ex prod → ring_exp_m (ex sum)
| ps@(ex.zero ps_i) qs := do
z ← ex_zero,
z_o ← mul_orig ps qs,
pf ← mk_proof ``mul_p_pf_zero [ps.orig, qs.orig] [ps.info],
pure $ z.set_info z_o pf
| pps@(ex.sum pps_i p ps) qs := do
pqs ← mul_pp p qs >>= prod_to_sum,
psqs ← mul_p ps qs,
ppsqs ← add pqs psqs,
pps_pf ← pps.proof_term,
ppsqs_o ← mul_orig pps qs,
ppsqs_pf ← ppsqs.proof_term,
pf ← mk_proof ``mul_p_pf_sum
[pps.orig, p.pretty, ps.pretty, qs.orig, ppsqs.pretty]
[pps.info, ppsqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma mul_pf_zero {ps qs : α} : qs = 0 → ps * qs = 0 :=
λ qs_pf, by rw [qs_pf, mul_zero]
lemma mul_pf_sum {ps qqs q qs psqqs : α} : qqs = q + qs → ps * q + ps * qs = psqqs →
ps * qqs = psqqs := λ qs_pf psqqs_pf, calc
ps * qqs = ps * (q + qs) : by rw [qs_pf]
... = ps * q + ps * qs : mul_add _ _ _
... = psqqs : psqqs_pf
/--
Multiply two expressions.
* `ps * 0 = 0`
* `ps * (q + qs) = (ps * q) + (ps * qs)`
-/
meta def mul : ex sum → ex sum → ring_exp_m (ex sum)
| ps qs@(ex.zero qs_i) := do
z ← ex_zero,
z_o ← mul_orig ps qs,
pf ← mk_proof ``mul_pf_zero [ps.orig, qs.orig] [qs.info],
pure $ z.set_info z_o pf
| ps qqs@(ex.sum qqs_i q qs) := do
psq ← mul_p ps q,
psqs ← mul ps qs,
psqqs ← add psq psqs,
psqqs_o ← mul_orig ps qqs,
pf ← mk_proof ``mul_pf_sum
[ps.orig, qqs.orig, q.orig, qs.orig, psqqs.pretty]
[qqs.info, psqqs.info],
pure $ psqqs.set_info psqqs_o pf
end multiplication
section exponentiation
lemma pow_e_pf_exp {pps p : α} {ps qs psqs : ℕ} :
pps = p ^ ps → ps * qs = psqs → pps ^ qs = p ^ psqs :=
λ pps_pf psqs_pf, calc
pps ^ qs = (p ^ ps) ^ qs : by rw [pps_pf]
... = p ^ (ps * qs) : symm (pow_mul _ _ _)
... = p ^ psqs : by rw [psqs_pf]
/--
Compute the exponentiation of two coefficients.
The returned value is of the form `ex.coeff _ (p ^ q)`,
with the proof of `expr.of_rat p ^ expr.of_rat q = expr.of_rat (p ^ q)`.
-/
meta def pow_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do
ctx ← get_context,
pq' ← mk_pow [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_pow pq',
pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩
/--
Exponentiate two expressions.
* `(p ^ ps) ^ qs = p ^ (ps * qs)`
-/
meta def pow_e : ex exp → ex prod → ring_exp_m (ex exp)
| pps@(ex.exp pps_i p ps) qs := do
psqs ← in_exponent $ mul_pp ps qs,
ppsqs ← ex_exp p psqs,
ppsqs_o ← pow_orig pps qs,
pf ← mk_proof ``pow_e_pf_exp
[pps.orig, p.pretty, ps.pretty, qs.orig, psqs.pretty]
[pps.info, psqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma pow_pp_pf_one {ps : α} {qs : ℕ} : ps = 1 → ps ^ qs = 1 :=
λ ps_pf, by rw [ps_pf, one_pow]
lemma pow_pf_c_c {ps ps' pq : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps' ^ qs' = pq → ps ^ qs = pq := by cc
lemma pow_pp_pf_c {ps ps' pqs : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps' ^ qs' = pqs → ps ^ qs = pqs * 1 :=
by simp; cc
lemma pow_pp_pf_prod {pps p ps pqs psqs : α} {qs : ℕ} : pps = p * ps →
p ^ qs = pqs → ps ^ qs = psqs → pps ^ qs = pqs * psqs :=
λ pps_pf pqs_pf psqs_pf, calc
pps ^ qs = (p * ps) ^ qs : by rw [pps_pf]
... = p ^ qs * ps ^ qs : mul_pow _ _ _
... = pqs * psqs : by rw [pqs_pf, psqs_pf]
/--
Exponentiate two expressions.
* `1 ^ qs = 1`
* `x ^ qs = x ^ qs` (for `x` coefficient)
* `(p * ps) ^ qs = p ^ qs + ps ^ qs`
-/
meta def pow_pp : ex prod → ex prod → ring_exp_m (ex prod)
| ps@(ex.coeff ps_i ⟨⟨1, 1, _, _⟩⟩) qs := do
o ← ex_one,
o_o ← pow_orig ps qs,
pf ← mk_proof ``pow_pp_pf_one [ps.orig, qs.orig] [ps.info],
pure $ o.set_info o_o pf
| ps@(ex.coeff ps_i x) qs@(ex.coeff qs_i y) := do
pq ← pow_coeff ps.pretty qs.pretty x y,
pq_o ← pow_orig ps qs,
pf ← mk_proof_or_refl pq.pretty ``pow_pf_c_c
[ps.orig, ps.pretty, pq.pretty, qs.orig, qs.pretty]
[ps.info, qs.info, pq.info],
pure $ pq.set_info pq_o pf
| ps@(ex.coeff ps_i x) qs := do
ps'' ← pure ps >>= prod_to_sum >>= ex_sum_b,
pqs ← ex_exp ps'' qs,
pqs_o ← pow_orig ps qs,
pf ← mk_proof_or_refl pqs.pretty ``pow_pp_pf_c
[ps.orig, ps.pretty, pqs.pretty, qs.orig, qs.pretty]
[ps.info, qs.info, pqs.info],
pqs' ← exp_to_prod pqs,
pure $ pqs'.set_info pqs_o pf
| pps@(ex.prod pps_i p ps) qs := do
pqs ← pow_e p qs,
psqs ← pow_pp ps qs,
ppsqs ← ex_prod pqs psqs,
ppsqs_o ← pow_orig pps qs,
pf ← mk_proof ``pow_pp_pf_prod
[pps.orig, p.pretty, ps.pretty, pqs.pretty, psqs.pretty, qs.orig]
[pps.info, pqs.info, psqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma pow_p_pf_one {ps ps' : α} {qs : ℕ} : ps = ps' → qs = succ zero → ps ^ qs = ps' :=
λ ps_pf qs_pf, calc
ps ^ qs = ps' ^ 1 : by rw [ps_pf, qs_pf]
... = ps' : pow_one _
lemma pow_p_pf_zero {ps : α} {qs qs' : ℕ} : ps = 0 → qs = succ qs' → ps ^ qs = 0 :=
λ ps_pf qs_pf, calc
ps ^ qs = 0 ^ (succ qs') : by rw [ps_pf, qs_pf]
... = 0 : zero_pow (succ_pos qs')
lemma pow_p_pf_succ {ps pqqs : α} {qs qs' : ℕ} :
qs = succ qs' → ps * ps ^ qs' = pqqs → ps ^ qs = pqqs :=
λ qs_pf pqqs_pf, calc
ps ^ qs = ps ^ succ qs' : by rw [qs_pf]
... = ps * ps ^ qs' : pow_succ _ _
... = pqqs : by rw [pqqs_pf]
lemma pow_p_pf_singleton {pps p pqs : α} {qs : ℕ} :
pps = p + 0 → p ^ qs = pqs → pps ^ qs = pqs :=
λ pps_pf pqs_pf, by rw [pps_pf, add_zero, pqs_pf]
lemma pow_p_pf_cons {ps ps' : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps ^ qs = ps' ^ qs' := by cc
/--
Exponentiate two expressions.
* `ps ^ 1 = ps`
* `0 ^ qs = 0` (note that this is handled *after* `ps ^ 0 = 1`)
* `(p + 0) ^ qs = p ^ qs`
* `ps ^ (qs + 1) = ps * ps ^ qs` (note that this is handled *after* `p + 0 ^ qs = p ^ qs`)
* `ps ^ qs = ps ^ qs` (otherwise)
-/
meta def pow_p : ex sum → ex prod → ring_exp_m (ex sum)
| ps qs@(ex.coeff qs_i ⟨⟨1, 1, _, _⟩⟩) := do
ps_o ← pow_orig ps qs,
pf ← mk_proof ``pow_p_pf_one [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info],
pure $ ps.set_info ps_o pf
| ps@(ex.zero ps_i) qs@(ex.coeff qs_i ⟨⟨succ y, 1, _, _⟩⟩) := do
ctx ← get_context,
z ← ex_zero,
qs_pred ← lift $ expr.of_nat ctx.info_e.α y,
pf ← mk_proof ``pow_p_pf_zero [ps.orig, qs.orig, qs_pred] [ps.info, qs.info],
z_o ← pow_orig ps qs,
pure $ z.set_info z_o pf
| pps@(ex.sum pps_i p (ex.zero _)) qqs := do
pqs ← pow_pp p qqs,
pqs_o ← pow_orig pps qqs,
pf ← mk_proof ``pow_p_pf_singleton
[pps.orig, p.pretty, pqs.pretty, qqs.orig]
[pps.info, pqs.info],
prod_to_sum $ pqs.set_info pqs_o pf
| ps qs@(ex.coeff qs_i ⟨⟨int.of_nat (succ n), 1, den_pos, _⟩⟩) := do
qs' ← in_exponent $ ex_coeff ⟨int.of_nat n, 1, den_pos, coprime_one_right _⟩,
pqs ← pow_p ps qs',
pqqs ← mul ps pqs,
pqqs_o ← pow_orig ps qs,
pf ← mk_proof ``pow_p_pf_succ
[ps.orig, pqqs.pretty, qs.orig, qs'.pretty]
[qs.info, pqqs.info],
pure $ pqqs.set_info pqqs_o pf
| pps qqs := do -- fallback: treat them as atoms
pps' ← ex_sum_b pps,
psqs ← ex_exp pps' qqs,
psqs_o ← pow_orig pps qqs,
pf ← mk_proof_or_refl psqs.pretty ``pow_p_pf_cons
[pps.orig, pps.pretty, qqs.orig, qqs.pretty]
[pps.info, qqs.info],
exp_to_prod (psqs.set_info psqs_o pf) >>= prod_to_sum
lemma pow_pf_zero {ps : α} {qs : ℕ} : qs = 0 → ps ^ qs = 1 := λ qs_pf, calc
ps ^ qs = ps ^ 0 : by rw [qs_pf]
... = 1 : pow_zero _
lemma pow_pf_sum {ps psqqs : α} {qqs q qs : ℕ} : qqs = q + qs →
ps ^ q * ps ^ qs = psqqs → ps ^ qqs = psqqs := λ qqs_pf psqqs_pf, calc
ps ^ qqs = ps ^ (q + qs) : by rw [qqs_pf]
... = ps ^ q * ps ^ qs : pow_add _ _ _
... = psqqs : psqqs_pf
/--
Exponentiate two expressions.
* `ps ^ 0 = 1`
* `ps ^ (q + qs) = ps ^ q * ps ^ qs`
-/
meta def pow : ex sum → ex sum → ring_exp_m (ex sum)
| ps qs@(ex.zero qs_i) := do
o ← ex_one,
o_o ← pow_orig ps qs,
pf ← mk_proof ``pow_pf_zero [ps.orig, qs.orig] [qs.info],
prod_to_sum $ o.set_info o_o pf
| ps qqs@(ex.sum qqs_i q qs) := do
psq ← pow_p ps q,
psqs ← pow ps qs,
psqqs ← mul psq psqs,
psqqs_o ← pow_orig ps qqs,
pf ← mk_proof ``pow_pf_sum
[ps.orig, psqqs.pretty, qqs.orig, q.pretty, qs.pretty]
[qqs.info, psqqs.info],
pure $ psqqs.set_info psqqs_o pf
end exponentiation
lemma simple_pf_sum_zero {p p' : α} : p = p' → p + 0 = p' := by simp
lemma simple_pf_prod_one {p p' : α} : p = p' → p * 1 = p' := by simp
lemma simple_pf_prod_neg_one {α} [ring α] {p p' : α} : p = p' → p * -1 = - p' := by simp
lemma simple_pf_var_one (p : α) : p ^ 1 = p := by simp
lemma simple_pf_exp_one {p p' : α} : p = p' → p ^ 1 = p' := by simp
/--
Give a simpler, more human-readable representation of the normalized expression.
Normalized expressions might have the form `a^1 * 1 + 0`,
since the dummy operations reduce special cases in pattern-matching.
Humans prefer to read `a` instead.
This tactic gets rid of the dummy additions, multiplications and exponentiations.
-/
meta def ex.simple : Π {et : ex_type}, ex et → ring_exp_m (expr × expr)
| sum pps@(ex.sum pps_i p (ex.zero _)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_sum_zero [p.pretty, p_p, p_pf]
| sum (ex.sum pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← ps.simple,
prod.mk
<$> mk_add [p_p, ps_p]
<*> mk_app_csr ``sum_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| prod (ex.prod pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_prod_one [p.pretty, p_p, p_pf]
| prod pps@(ex.prod pps_i p (ex.coeff _ ⟨⟨-1, 1, _, _⟩⟩)) := do
ctx ← get_context,
match ctx.info_b.ring_instance with
| none := prod.mk pps.pretty <$> pps.proof_term
| (some ringi) := do
(p_p, p_pf) ← p.simple,
prod.mk
<$> lift (mk_app ``has_neg.neg [p_p])
<*> mk_app_class ``simple_pf_prod_neg_one ringi [p.pretty, p_p, p_pf]
end
| prod (ex.prod pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← ps.simple,
prod.mk
<$> mk_mul [p_p, ps_p]
<*> mk_app_csr ``prod_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| base (ex.sum_b pps_i ps) := ps.simple
| exp (ex.exp pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_exp_one [p.pretty, p_p, p_pf]
| exp (ex.exp pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← in_exponent $ ps.simple,
prod.mk
<$> mk_pow [p_p, ps_p]
<*> mk_app_csr ``exp_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| et ps := prod.mk ps.pretty <$> ps.proof_term
/--
Performs a lookup of the atom `a` in the list of known atoms,
or allocates a new one.
If `a` is not definitionally equal to any of the list's entries,
a new atom is appended to the list and returned.
The index of this atom is kept track of in the second inductive argument.
This function is mostly useful in `resolve_atom`,
which updates the state with the new list of atoms.
-/
meta def resolve_atom_aux (a : expr) : list atom → ℕ → ring_exp_m (atom × list atom)
| [] n := let atm : atom := ⟨a, n⟩ in pure (atm, [atm])
| bas@(b :: as) n := do
ctx ← get_context,
(lift $ is_def_eq a b.value ctx.transp >> pure (b , bas)) <|> do
(atm, as') ← resolve_atom_aux as (succ n),
pure (atm, b :: as')
/--
Convert the expression to an atom:
either look up a definitionally equal atom,
or allocate it as a new atom.
You probably want to use `eval_base` if `eval` doesn't work
instead of directly calling `resolve_atom`,
since `eval_base` can also handle numerals.
-/
meta def resolve_atom (a : expr) : ring_exp_m atom := do
atoms ← reader_t.lift $ state_t.get,
(atm, atoms') ← resolve_atom_aux a atoms 0,
reader_t.lift $ state_t.put atoms',
pure atm
/--
Treat the expression atomically: as a coefficient or atom.
Handles cases where `eval` cannot treat the expression as a known operation
because it is just a number or single variable.
-/
meta def eval_base (ps : expr) : ring_exp_m (ex sum) :=
match ps.to_rat with
| some ⟨0, 1, _, _⟩ := ex_zero
| some x := ex_coeff x >>= prod_to_sum
| none := do
a ← resolve_atom ps,
atom_to_sum a
end
lemma negate_pf {α} [ring α] {ps ps' : α} : (-1) * ps = ps' → -ps = ps' := by simp
/--
Negate an expression by multiplying with `-1`.
Only works if there is a `ring` instance; otherwise it will `fail`.
-/
meta def negate (ps : ex sum) : ring_exp_m (ex sum) := do
ctx ← get_context,
match ctx.info_b.ring_instance with
| none := lift $ fail "internal error: negate called in semiring"
| (some ring_instance) := do
minus_one ← ex_coeff (-1) >>= prod_to_sum,
ps' ← mul minus_one ps,
ps_pf ← ps'.proof_term,
pf ← mk_app_class ``negate_pf ring_instance [ps.orig, ps'.pretty, ps_pf],
ps'_o ← lift $ mk_app ``has_neg.neg [ps.orig],
pure $ ps'.set_info ps'_o pf
end
lemma inverse_pf {α} [division_ring α] {ps ps_u ps_p e' e'' : α} :
ps = ps_u → ps_u = ps_p → ps_p ⁻¹ = e' → e' = e'' → ps ⁻¹ = e'' :=
by cc
/--
Invert an expression by simplifying, applying `has_inv.inv` and treating the result as an atom.
Only works if there is a `division_ring` instance; otherwise it will `fail`.
-/
meta def inverse (ps : ex sum) : ring_exp_m (ex sum) := do
ctx ← get_context,
dri ← match ctx.info_b.dr_instance with
| none := lift $ fail "division is only supported in a division ring"
| (some dri) := pure dri
end,
(ps_simple, ps_simple_pf) ← ps.simple,
e ← lift $ mk_app ``has_inv.inv [ps_simple],
(e', e_pf) ← lift (norm_num.derive e) <|> ((λ e_pf, (e, e_pf)) <$> lift (mk_eq_refl e)),
e'' ← eval_base e',
ps_pf ← ps.proof_term,
e''_pf ← e''.proof_term,
pf ← mk_app_class ``inverse_pf dri
[ ps.orig, ps.pretty, ps_simple, e', e''.pretty,
ps_pf, ps_simple_pf, e_pf, e''_pf],
e''_o ← lift $ mk_app ``has_inv.inv [ps.orig],
pure $ e''.set_info e''_o pf
lemma sub_pf {α} [ring α] {ps qs psqs : α} (h : ps + -qs = psqs) : ps - qs = psqs :=
by rwa sub_eq_add_neg
lemma div_pf {α} [division_ring α] {ps qs psqs : α} (h : ps * qs⁻¹ = psqs) : ps / qs = psqs :=
by rwa div_eq_mul_inv
end operations
section wiring
/-!
### `wiring` section
This section deals with going from `expr` to `ex` and back.
The main attraction is `eval`, which uses `add`, `mul`, etc.
to calculate an `ex` from a given `expr`.
Other functions use `ex`es to produce `expr`s together with a proof,
or produce the context to run `ring_exp_m` from an `expr`.
-/
open tactic
open ex_type
/--
Compute a normalized form (of type `ex`) from an expression (of type `expr`).
This is the main driver of the `ring_exp` tactic,
calling out to `add`, `mul`, `pow`, etc. to parse the `expr`.
-/
meta def eval : expr → ring_exp_m (ex sum)
| e@`(%%ps + %%qs) := do
ps' ← eval ps,
qs' ← eval qs,
add ps' qs'
| ps_o@`(nat.succ %%p_o) := do
ps' ← eval `(%%p_o + 1),
pf ← lift $ mk_app ``nat.succ_eq_add_one [p_o],
rewrite ps_o ps' pf
| e@`(%%ps - %%qs) := (do
ctx ← get_context,
ri ← match ctx.info_b.ring_instance with
| none := lift $ fail "subtraction is not directly supported in a semiring"
| (some ri) := pure ri
end,
ps' ← eval ps,
qs' ← eval qs >>= negate,
psqs ← add ps' qs',
psqs_pf ← psqs.proof_term,
pf ← mk_app_class ``sub_pf ri [ps, qs, psqs.pretty, psqs_pf],
pure (psqs.set_info e pf)) <|> eval_base e
| e@`(- %%ps) := do
ps' ← eval ps,
negate ps' <|> eval_base e
| e@`(%%ps * %%qs) := do
ps' ← eval ps,
qs' ← eval qs,
mul ps' qs'
| e@`(has_inv.inv %%ps) := do
ps' ← eval ps,
inverse ps' <|> eval_base e
| e@`(%%ps / %%qs) := do
ctx ← get_context,
dri ← match ctx.info_b.dr_instance with
| none := lift $ fail "division is only directly supported in a division ring"
| (some dri) := pure dri
end,
ps' ← eval ps,
qs' ← eval qs,
(do qs'' ← inverse qs',
psqs ← mul ps' qs'',
psqs_pf ← psqs.proof_term,
pf ← mk_app_class ``div_pf dri [ps, qs, psqs.pretty, psqs_pf],
pure (psqs.set_info e pf)) <|> eval_base e
| e@`(@has_pow.pow _ _ %%hp_instance %%ps %%qs) := do
ps' ← eval ps,
qs' ← in_exponent $ eval qs,
psqs ← pow ps' qs',
psqs_pf ← psqs.proof_term,
(do has_pow_pf ← match hp_instance with
| `(monoid.has_pow) := lift $ mk_eq_refl e
| _ := lift $ fail "has_pow instance must be nat.has_pow or monoid.has_pow"
end,
pf ← lift $ mk_eq_trans has_pow_pf psqs_pf,
pure $ psqs.set_info e pf) <|> eval_base e
| ps := eval_base ps
/--
Run `eval` on the expression and return the result together with normalization proof.
See also `eval_simple` if you want something that behaves like `norm_num`.
-/
meta def eval_with_proof (e : expr) : ring_exp_m (ex sum × expr) := do
e' ← eval e,
prod.mk e' <$> e'.proof_term
/--
Run `eval` on the expression and simplify the result.
Returns a simplified normalized expression, together with an equality proof.
See also `eval_with_proof` if you just want to check the equality of two expressions.
-/
meta def eval_simple (e : expr) : ring_exp_m (expr × expr) := do
(complicated, complicated_pf) ← eval_with_proof e,
(simple, simple_pf) ← complicated.simple,
prod.mk simple <$> lift (mk_eq_trans complicated_pf simple_pf)
/-- Compute the `eval_info` for a given type `α`. -/
meta def make_eval_info (α : expr) : tactic eval_info := do
u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
csr_instance ← mk_app ``comm_semiring [α] >>= mk_instance,
ring_instance ← (some <$> (mk_app ``ring [α] >>= mk_instance) <|> pure none),
dr_instance ← (some <$> (mk_app ``division_ring [α] >>= mk_instance) <|> pure none),
ha_instance ← mk_app ``has_add [α] >>= mk_instance,
hm_instance ← mk_app ``has_mul [α] >>= mk_instance,
hp_instance ← mk_mapp ``monoid.has_pow [some α, none],
z ← mk_mapp ``has_zero.zero [α, none],
o ← mk_mapp ``has_one.one [α, none],
pure ⟨α, u, csr_instance, ha_instance, hm_instance, hp_instance, ring_instance, dr_instance, z, o⟩
/-- Use `e` to build the context for running `mx`. -/
meta def run_ring_exp {α} (transp : transparency) (e : expr) (mx : ring_exp_m α) : tactic α := do
info_b ← infer_type e >>= make_eval_info,
info_e ← mk_const ``nat >>= make_eval_info,
(λ x : (_ × _), x.1) <$> (state_t.run (reader_t.run mx ⟨info_b, info_e, transp⟩) [])
/-- Repeatedly apply `eval_simple` on (sub)expressions. -/
meta def normalize (transp : transparency) (e : expr) : tactic (expr × expr) := do
(_, e', pf') ← ext_simplify_core () {}
simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do
(e'', pf) ← run_ring_exp transp e $ eval_simple e,
guard (¬ e'' =ₐ e),
return ((), e'', some pf, ff))
(λ _ _ _ _ _, failed) `eq e,
pure (e', pf')
end wiring
end tactic.ring_exp
namespace tactic.interactive
open interactive interactive.types lean.parser tactic tactic.ring_exp
local postfix `?`:9001 := optional
/--
Tactic for solving equations of *commutative* (semi)rings,
allowing variables in the exponent.
This version of `ring_exp` fails if the target is not an equality.
The variant `ring_exp_eq!` will use a more aggressive reducibility setting
to determine equality of atoms.
-/
meta def ring_exp_eq (red : parse (tk "!")?) : tactic unit := do
`(eq %%ps %%qs) ← target >>= whnf,
let transp := if red.is_some then semireducible else reducible,
((ps', ps_pf), (qs', qs_pf)) ← run_ring_exp transp ps $
prod.mk <$> eval_with_proof ps <*> eval_with_proof qs,
if ps'.eq qs'
then do
qs_pf_inv ← mk_eq_symm qs_pf,
pf ← mk_eq_trans ps_pf qs_pf_inv,
tactic.interactive.exact ``(%%pf)
else fail "ring_exp failed to prove equality"
/--
Tactic for evaluating expressions in *commutative* (semi)rings, allowing for variables in the
exponent.
This tactic extends `ring`: it should solve every goal that `ring` can solve.
Additionally, it knows how to evaluate expressions with complicated exponents
(where `ring` only understands constant exponents).
The variants `ring_exp!` and `ring_exp_eq!` use a more aggessive reducibility setting to determine
equality of atoms.
For example:
```lean
example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp
example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp
example (x y : ℕ) : x + id y = y + id x := by ring_exp!
```
-/
meta def ring_exp (red : parse (tk "!")?) (loc : parse location) : tactic unit :=
match loc with
| interactive.loc.ns [none] := ring_exp_eq red
| _ := failed
end <|>
do ns ← loc.get_locals,
let transp := if red.is_some then semireducible else reducible,
tt ← tactic.replace_at (normalize transp) ns loc.include_goal
| fail "ring_exp failed to simplify",
when loc.include_goal $ try tactic.reflexivity
add_tactic_doc
{ name := "ring_exp",
category := doc_category.tactic,
decl_names := [`tactic.interactive.ring_exp],
tags := ["arithmetic", "simplification", "decision procedure"] }
end tactic.interactive
namespace conv.interactive
open conv interactive
open tactic tactic.interactive (ring_exp_eq)
open tactic.ring_exp (normalize)
local postfix `?`:9001 := optional
/--
Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring_exp`.
-/
meta def ring_exp (red : parse (lean.parser.tk "!")?) : conv unit :=
let transp := if red.is_some then semireducible else reducible in
discharge_eq_lhs (ring_exp_eq red)
<|> replace_lhs (normalize transp)
<|> fail "ring_exp failed to simplify"
end conv.interactive
|
f1400337f1447e3f9f62a41c52ea9050c18c6362 | 5883d9218e6f144e20eee6ca1dab8529fa1a97c0 | /src/vname/type.lean | 1f626a3ab7aca3a078bcf6378e6e52daadc8360b | [] | no_license | spl/alpha-conversion-is-easy | 0d035bc570e52a6345d4890e4d0c9e3f9b8126c1 | ed937fe85d8495daffd9412a5524c77b9fcda094 | refs/heads/master | 1,607,649,280,020 | 1,517,380,240,000 | 1,517,380,240,000 | 52,174,747 | 4 | 0 | null | 1,456,052,226,000 | 1,456,001,163,000 | Lean | UTF-8 | Lean | false | false | 1,982 | lean | /-
This file contains the `vname` type, the type of variable names in a variable
set, and other related type definitions.
-/
import vset
import data.has_mem
import data.sigma.basic
namespace acie -----------------------------------------------------------------
variables {V : Type} [decidable_eq V] -- Type of variable names
variables {vs : Type → Type} [vset vs V] -- Type of variable name sets
/-
A `vname X` is a variable name (e.g. `a : V`) paired with the status of its
membership in the variable name set `X` (e.g. `a ∈ X`).
The underlying type is `psigma`, so we can use the anonymous constructor
notation `x = ⟨a, pa⟩` to refer to a `x : vname X` with the variable, `a : V`
(or `x.1`), and its proof of membership, `pa : P a X` (or `x.2`).
-/
@[reducible]
def vname (P : Prop → Prop) (X : vs V) : Type :=
Σ' a : V, P (a ∈ X)
namespace vname ----------------------------------------------------------------
/-
A `vname.id X` is a variable name set member. Its variable name is an element of
the variable name set `X`.
-/
@[reducible]
protected
def id : vs V → Type :=
vname id
/-
A `vname.not X` is a variable set non-member. Its variable name is *not* an
element of the variable name set `X`.
-/
@[reducible]
protected
def not : vs V → Type :=
vname not
-- Notation for `vname.id` and `vname.not`.
prefix `ν∈ `:40 := vname.id -- \nu\in
prefix `ν∉ `:40 := vname.not -- \nu\notin
-- A function from an `vname.id` to an `vname.id`.
@[reducible]
protected
def id.fun (X Y : vs V) : Type :=
ν∈ X → ν∈ Y
-- Notation for `vname.id.fun`.
infixr ` →ν `:25 := vname.id.fun
instance decidable_eq (X : vs V) : decidable_eq (ν∈ X) :=
psigma.decidable_eq
instance has_repr [has_repr V] (X : vs V) : has_repr (ν∈ X) :=
⟨has_repr.repr ∘ psigma.fst⟩
end /- namespace -/ vname ------------------------------------------------------
end /- namespace -/ acie -------------------------------------------------------
|
45811304e186f04655e3c27576acee065a6f5668 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /hott/algebra/category/nat_trans.hlean | b7421ff7e02c31f0e2bc54218013642587f140e7 | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 7,488 | 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 .functor.basic
open eq category functor is_trunc equiv sigma.ops sigma is_equiv function pi funext iso
structure nat_trans {C : Precategory} {D : Precategory} (F G : C ⇒ D)
: Type :=
(natural_map : Π (a : C), hom (F a) (G a))
(naturality : Π {a b : C} (f : hom a b), G f ∘ natural_map a = natural_map b ∘ F f)
namespace nat_trans
infixl ` ⟹ `:25 := nat_trans -- \==>
variables {B C D E : Precategory} {F G H I : C ⇒ D} {F' G' : D ⇒ E} {F'' G'' : E ⇒ B} {J : C ⇒ C}
attribute natural_map [coercion]
protected definition compose [constructor] (η : G ⟹ H) (θ : F ⟹ G) : F ⟹ H :=
nat_trans.mk
(λ a, η a ∘ θ a)
(λ a b f,
abstract calc
H f ∘ (η a ∘ θ a) = (H f ∘ η a) ∘ θ a : by rewrite assoc
... = (η b ∘ G f) ∘ θ a : by rewrite naturality
... = η b ∘ (G f ∘ θ a) : by rewrite assoc
... = η b ∘ (θ b ∘ F f) : by rewrite naturality
... = (η b ∘ θ b) ∘ F f : by rewrite assoc
end)
infixr ` ∘n `:60 := nat_trans.compose
definition compose_def (η : G ⟹ H) (θ : F ⟹ G) (c : C) : (η ∘n θ) c = η c ∘ θ c := idp
protected definition id [reducible] [constructor] {F : C ⇒ D} : nat_trans F F :=
mk (λa, id) (λa b f, !id_right ⬝ !id_left⁻¹)
protected definition ID [reducible] [constructor] (F : C ⇒ D) : nat_trans F F :=
(@nat_trans.id C D F)
notation 1 := nat_trans.id
definition constant_nat_trans [constructor] (C : Precategory) {D : Precategory} {d d' : D}
(g : d ⟶ d') : constant_functor C d ⟹ constant_functor C d' :=
mk (λc, g) (λc c' f, !id_comp_eq_comp_id)
definition nat_trans_mk_eq {η₁ η₂ : Π (a : C), hom (F a) (G a)}
(nat₁ : Π (a b : C) (f : hom a b), G f ∘ η₁ a = η₁ b ∘ F f)
(nat₂ : Π (a b : C) (f : hom a b), G f ∘ η₂ a = η₂ b ∘ F f)
(p : η₁ ~ η₂)
: nat_trans.mk η₁ nat₁ = nat_trans.mk η₂ nat₂ :=
apd011 nat_trans.mk (eq_of_homotopy p) !is_prop.elim
definition nat_trans_eq {η₁ η₂ : F ⟹ G} : natural_map η₁ ~ natural_map η₂ → η₁ = η₂ :=
by induction η₁; induction η₂; apply nat_trans_mk_eq
protected definition assoc (η₃ : H ⟹ I) (η₂ : G ⟹ H) (η₁ : F ⟹ G) :
η₃ ∘n (η₂ ∘n η₁) = (η₃ ∘n η₂) ∘n η₁ :=
nat_trans_eq (λa, !assoc)
protected definition id_left (η : F ⟹ G) : 1 ∘n η = η :=
nat_trans_eq (λa, !id_left)
protected definition id_right (η : F ⟹ G) : η ∘n 1 = η :=
nat_trans_eq (λa, !id_right)
protected definition sigma_char (F G : C ⇒ D) :
(Σ (η : Π (a : C), hom (F a) (G a)), Π (a b : C) (f : hom a b), G f ∘ η a = η b ∘ F f) ≃ (F ⟹ G) :=
begin
fapply equiv.mk,
-- TODO(Leo): investigate why we need to use rexact in the following line
{intro S, apply nat_trans.mk, rexact (S.2)},
fapply adjointify,
intro H,
fapply sigma.mk,
intro a, exact (H a),
intro a b f, exact (naturality H f),
intro η, apply nat_trans_eq, intro a, apply idp,
intro S,
fapply sigma_eq,
{ apply eq_of_homotopy, intro a, apply idp},
{ apply is_prop.elimo}
end
definition is_set_nat_trans [instance] : is_set (F ⟹ G) :=
by apply is_trunc_is_equiv_closed; apply (equiv.to_is_equiv !nat_trans.sigma_char)
definition change_natural_map [constructor] (η : F ⟹ G) (f : Π (a : C), F a ⟶ G a)
(p : Πa, η a = f a) : F ⟹ G :=
nat_trans.mk f (λa b g, p a ▸ p b ▸ naturality η g)
definition nat_trans_functor_compose [constructor] (η : G ⟹ H) (F : E ⇒ C)
: G ∘f F ⟹ H ∘f F :=
nat_trans.mk
(λ a, η (F a))
(λ a b f, naturality η (F f))
definition functor_nat_trans_compose [constructor] (F : D ⇒ E) (η : G ⟹ H)
: F ∘f G ⟹ F ∘f H :=
nat_trans.mk
(λ a, F (η a))
(λ a b f, calc
F (H f) ∘ F (η a) = F (H f ∘ η a) : by rewrite respect_comp
... = F (η b ∘ G f) : by rewrite (naturality η f)
... = F (η b) ∘ F (G f) : by rewrite respect_comp)
definition nat_trans_id_functor_compose [constructor] (η : J ⟹ 1) (F : E ⇒ C)
: J ∘f F ⟹ F :=
nat_trans.mk
(λ a, η (F a))
(λ a b f, naturality η (F f))
definition id_nat_trans_functor_compose [constructor] (η : 1 ⟹ J) (F : E ⇒ C)
: F ⟹ J ∘f F :=
nat_trans.mk
(λ a, η (F a))
(λ a b f, naturality η (F f))
definition functor_nat_trans_id_compose [constructor] (F : C ⇒ D) (η : J ⟹ 1)
: F ∘f J ⟹ F :=
nat_trans.mk
(λ a, F (η a))
(λ a b f, calc
F f ∘ F (η a) = F (f ∘ η a) : by rewrite respect_comp
... = F (η b ∘ J f) : by rewrite (naturality η f)
... = F (η b) ∘ F (J f) : by rewrite respect_comp)
definition functor_id_nat_trans_compose [constructor] (F : C ⇒ D) (η : 1 ⟹ J)
: F ⟹ F ∘f J :=
nat_trans.mk
(λ a, F (η a))
(λ a b f, calc
F (J f) ∘ F (η a) = F (J f ∘ η a) : by rewrite respect_comp
... = F (η b ∘ f) : by rewrite (naturality η f)
... = F (η b) ∘ F f : by rewrite respect_comp)
infixr ` ∘nf ` :62 := nat_trans_functor_compose
infixr ` ∘fn ` :62 := functor_nat_trans_compose
infixr ` ∘n1f `:62 := nat_trans_id_functor_compose
infixr ` ∘1nf `:62 := id_nat_trans_functor_compose
infixr ` ∘f1n `:62 := functor_id_nat_trans_compose
infixr ` ∘fn1 `:62 := functor_nat_trans_id_compose
definition nf_fn_eq_fn_nf_pt (η : F ⟹ G) (θ : F' ⟹ G') (c : C)
: (θ (G c)) ∘ (F' (η c)) = (G' (η c)) ∘ (θ (F c)) :=
(naturality θ (η c))⁻¹
variable (F')
definition nf_fn_eq_fn_nf_pt' (η : F ⟹ G) (θ : F'' ⟹ G'') (c : C)
: (θ (F' (G c))) ∘ (F'' (F' (η c))) = (G'' (F' (η c))) ∘ (θ (F' (F c))) :=
(naturality θ (F' (η c)))⁻¹
variable {F'}
definition nf_fn_eq_fn_nf (η : F ⟹ G) (θ : F' ⟹ G')
: (θ ∘nf G) ∘n (F' ∘fn η) = (G' ∘fn η) ∘n (θ ∘nf F) :=
nat_trans_eq (λ c, nf_fn_eq_fn_nf_pt η θ c)
definition fn_n_distrib (F' : D ⇒ E) (η : G ⟹ H) (θ : F ⟹ G)
: F' ∘fn (η ∘n θ) = (F' ∘fn η) ∘n (F' ∘fn θ) :=
nat_trans_eq (λc, by apply respect_comp)
definition n_nf_distrib (η : G ⟹ H) (θ : F ⟹ G) (F' : B ⇒ C)
: (η ∘n θ) ∘nf F' = (η ∘nf F') ∘n (θ ∘nf F') :=
nat_trans_eq (λc, idp)
definition fn_id (F' : D ⇒ E) : F' ∘fn nat_trans.ID F = 1 :=
nat_trans_eq (λc, by apply respect_id)
definition id_nf (F' : B ⇒ C) : nat_trans.ID F ∘nf F' = 1 :=
nat_trans_eq (λc, idp)
definition id_fn (η : G ⟹ H) (c : C) : (1 ∘fn η) c = η c :=
idp
definition nf_id (η : G ⟹ H) (c : C) : (η ∘nf 1) c = η c :=
idp
definition nat_trans_of_eq [reducible] [constructor] (p : F = G) : F ⟹ G :=
nat_trans.mk (λc, hom_of_eq (ap010 to_fun_ob p c))
(λa b f, eq.rec_on p (!id_right ⬝ !id_left⁻¹))
definition compose_rev [unfold_full] (θ : F ⟹ G) (η : G ⟹ H) : F ⟹ H := η ∘n θ
end nat_trans
attribute nat_trans.compose_rev [trans]
attribute nat_trans.id [refl]
|
377aff9906f45f60edccc094e8000bd4688e0979 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/measure_theory/integral/lebesgue.lean | c6221acf215c966fcd3eb41d1844dde0aab2c1eb | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 142,012 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl
-/
import measure_theory.measure.mutually_singular
import measure_theory.constructions.borel_space
import algebra.indicator_function
import algebra.support
import dynamics.ergodic.measure_preserving
/-!
# Lebesgue integral for `ℝ≥0∞`-valued functions
We define simple functions and show that each Borel measurable function on `ℝ≥0∞` can be
approximated by a sequence of simple functions.
To prove something for an arbitrary measurable function into `ℝ≥0∞`, the theorem
`measurable.ennreal_induction` shows that is it sufficient to show that the property holds for
(multiples of) characteristic functions and is closed under addition and supremum of increasing
sequences of functions.
## Notation
We introduce the following notation for the lower Lebesgue integral of a function `f : α → ℝ≥0∞`.
* `∫⁻ x, f x ∂μ`: integral of a function `f : α → ℝ≥0∞` with respect to a measure `μ`;
* `∫⁻ x, f x`: integral of a function `f : α → ℝ≥0∞` with respect to the canonical measure
`volume` on `α`;
* `∫⁻ x in s, f x ∂μ`: integral of a function `f : α → ℝ≥0∞` over a set `s` with respect
to a measure `μ`, defined as `∫⁻ x, f x ∂(μ.restrict s)`;
* `∫⁻ x in s, f x`: integral of a function `f : α → ℝ≥0∞` over a set `s` with respect
to the canonical measure `volume`, defined as `∫⁻ x, f x ∂(volume.restrict s)`.
-/
noncomputable theory
open set (hiding restrict restrict_apply) filter ennreal function (support)
open_locale classical topological_space big_operators nnreal ennreal measure_theory
namespace measure_theory
variables {α β γ δ : Type*}
/-- A function `f` from a measurable space to any type is called *simple*,
if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles
a function with these properties. -/
structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) :=
(to_fun : α → β)
(measurable_set_fiber' : ∀ x, measurable_set (to_fun ⁻¹' {x}))
(finite_range' : (set.range to_fun).finite)
local infixr ` →ₛ `:25 := simple_func
namespace simple_func
section measurable
variables [measurable_space α]
instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) (λ _, α → β) := ⟨to_fun⟩
lemma coe_injective ⦃f g : α →ₛ β⦄ (H : (f : α → β) = g) : f = g :=
by cases f; cases g; congr; exact H
@[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g :=
coe_injective $ funext H
lemma finite_range (f : α →ₛ β) : (set.range f).finite := f.finite_range'
lemma measurable_set_fiber (f : α →ₛ β) (x : β) : measurable_set (f ⁻¹' {x}) :=
f.measurable_set_fiber' x
@[simp] lemma apply_mk (f : α → β) (h h') (x : α) : simple_func.mk f h h' x = f x := rfl
/-- Simple function defined on the empty type. -/
def of_is_empty [is_empty α] : α →ₛ β :=
{ to_fun := is_empty_elim,
measurable_set_fiber' := λ x, subsingleton.measurable_set,
finite_range' := by simp [range_eq_empty] }
/-- Range of a simple function `α →ₛ β` as a `finset β`. -/
protected def range (f : α →ₛ β) : finset β := f.finite_range.to_finset
@[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ b ∈ range f :=
finite.mem_to_finset _
theorem mem_range_self (f : α →ₛ β) (x : α) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩
@[simp] lemma coe_range (f : α →ₛ β) : (↑f.range : set β) = set.range f :=
f.finite_range.coe_to_finset
theorem mem_range_of_measure_ne_zero {f : α →ₛ β} {x : β} {μ : measure α} (H : μ (f ⁻¹' {x}) ≠ 0) :
x ∈ f.range :=
let ⟨a, ha⟩ := nonempty_of_measure_ne_zero H in
mem_range.2 ⟨a, ha⟩
lemma forall_range_iff {f : α →ₛ β} {p : β → Prop} :
(∀ y ∈ f.range, p y) ↔ ∀ x, p (f x) :=
by simp only [mem_range, set.forall_range_iff]
lemma exists_range_iff {f : α →ₛ β} {p : β → Prop} :
(∃ y ∈ f.range, p y) ↔ ∃ x, p (f x) :=
by simpa only [mem_range, exists_prop] using set.exists_range_iff
lemma preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range :=
preimage_singleton_eq_empty.trans $ not_congr mem_range.symm
lemma exists_forall_le [nonempty β] [preorder β] [is_directed β (≤)] (f : α →ₛ β) :
∃ C, ∀ x, f x ≤ C :=
f.range.exists_le.imp $ λ C, forall_range_iff.1
/-- Constant function as a `simple_func`. -/
def const (α) {β} [measurable_space α] (b : β) : α →ₛ β :=
⟨λ a, b, λ x, measurable_set.const _, finite_range_const⟩
instance [inhabited β] : inhabited (α →ₛ β) := ⟨const _ default⟩
theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl
@[simp] theorem coe_const (b : β) : ⇑(const α b) = function.const α b := rfl
@[simp] lemma range_const (α) [measurable_space α] [nonempty α] (b : β) :
(const α b).range = {b} :=
finset.coe_injective $ by simp
lemma range_const_subset (α) [measurable_space α] (b : β) :
(const α b).range ⊆ {b} :=
finset.coe_subset.1 $ by simp
lemma measurable_set_cut (r : α → β → Prop) (f : α →ₛ β)
(h : ∀b, measurable_set {a | r a b}) : measurable_set {a | r a (f a)} :=
begin
have : {a | r a (f a)} = ⋃ b ∈ range f, {a | r a b} ∩ f ⁻¹' {b},
{ ext a,
suffices : r a (f a) ↔ ∃ i, r a (f i) ∧ f a = f i, by simpa,
exact ⟨λ h, ⟨a, ⟨h, rfl⟩⟩, λ ⟨a', ⟨h', e⟩⟩, e.symm ▸ h'⟩ },
rw this,
exact measurable_set.bUnion f.finite_range.countable
(λ b _, measurable_set.inter (h b) (f.measurable_set_fiber _))
end
@[measurability]
theorem measurable_set_preimage (f : α →ₛ β) (s) : measurable_set (f ⁻¹' s) :=
measurable_set_cut (λ _ b, b ∈ s) f (λ b, measurable_set.const (b ∈ s))
/-- A simple function is measurable -/
@[measurability]
protected theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f :=
λ s _, measurable_set_preimage f s
@[measurability]
protected theorem ae_measurable [measurable_space β] {μ : measure α} (f : α →ₛ β) :
ae_measurable f μ :=
f.measurable.ae_measurable
protected lemma sum_measure_preimage_singleton (f : α →ₛ β) {μ : measure α} (s : finset β) :
∑ y in s, μ (f ⁻¹' {y}) = μ (f ⁻¹' ↑s) :=
sum_measure_preimage_singleton _ (λ _ _, f.measurable_set_fiber _)
lemma sum_range_measure_preimage_singleton (f : α →ₛ β) (μ : measure α) :
∑ y in f.range, μ (f ⁻¹' {y}) = μ univ :=
by rw [f.sum_measure_preimage_singleton, coe_range, preimage_range]
/-- If-then-else as a `simple_func`. -/
def piecewise (s : set α) (hs : measurable_set s) (f g : α →ₛ β) : α →ₛ β :=
⟨s.piecewise f g,
λ x, by letI : measurable_space β := ⊤; exact
f.measurable.piecewise hs g.measurable trivial,
(f.finite_range.union g.finite_range).subset range_ite_subset⟩
@[simp] theorem coe_piecewise {s : set α} (hs : measurable_set s) (f g : α →ₛ β) :
⇑(piecewise s hs f g) = s.piecewise f g :=
rfl
theorem piecewise_apply {s : set α} (hs : measurable_set s) (f g : α →ₛ β) (a) :
piecewise s hs f g a = if a ∈ s then f a else g a :=
rfl
@[simp] lemma piecewise_compl {s : set α} (hs : measurable_set sᶜ) (f g : α →ₛ β) :
piecewise sᶜ hs f g = piecewise s hs.of_compl g f :=
coe_injective $ by simp [hs]
@[simp] lemma piecewise_univ (f g : α →ₛ β) : piecewise univ measurable_set.univ f g = f :=
coe_injective $ by simp
@[simp] lemma piecewise_empty (f g : α →ₛ β) : piecewise ∅ measurable_set.empty f g = g :=
coe_injective $ by simp
lemma support_indicator [has_zero β] {s : set α} (hs : measurable_set s) (f : α →ₛ β) :
function.support (f.piecewise s hs (simple_func.const α 0)) = s ∩ function.support f :=
set.support_indicator
lemma range_indicator {s : set α} (hs : measurable_set s)
(hs_nonempty : s.nonempty) (hs_ne_univ : s ≠ univ) (x y : β) :
(piecewise s hs (const α x) (const α y)).range = {x, y} :=
by simp only [← finset.coe_inj, coe_range, coe_piecewise, range_piecewise, coe_const,
finset.coe_insert, finset.coe_singleton, hs_nonempty.image_const,
(nonempty_compl.2 hs_ne_univ).image_const, singleton_union]
lemma measurable_bind [measurable_space γ] (f : α →ₛ β) (g : β → α → γ)
(hg : ∀ b, measurable (g b)) : measurable (λ a, g (f a) a) :=
λ s hs, f.measurable_set_cut (λ a b, g b a ∈ s) $ λ b, hg b hs
/-- If `f : α →ₛ β` is a simple function and `g : β → α →ₛ γ` is a family of simple functions,
then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/
def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ :=
⟨λa, g (f a) a,
λ c, f.measurable_set_cut (λ a b, g b a = c) $ λ b, (g b).measurable_set_preimage {c},
(f.finite_range.bUnion (λ b _, (g b).finite_range)).subset $
by rintro _ ⟨a, rfl⟩; simp; exact ⟨a, a, rfl⟩⟩
@[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) :
f.bind g a = g (f a) a := rfl
/-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple
function `g ∘ f : α →ₛ γ` -/
def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g)
theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl
theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl
@[simp] theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl
@[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) :
(f.map g).range = f.range.image g :=
finset.coe_injective $ by simp only [coe_range, coe_map, finset.coe_image, range_comp]
@[simp] theorem map_const (g : β → γ) (b : β) : (const α b).map g = const α (g b) := rfl
lemma map_preimage (f : α →ₛ β) (g : β → γ) (s : set γ) :
(f.map g) ⁻¹' s = f ⁻¹' ↑(f.range.filter (λb, g b ∈ s)) :=
by { simp only [coe_range, sep_mem_eq, set.mem_range, function.comp_app, coe_map, finset.coe_filter,
← mem_preimage, inter_comm, preimage_inter_range], apply preimage_comp }
lemma map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) :
(f.map g) ⁻¹' {c} = f ⁻¹' ↑(f.range.filter (λ b, g b = c)) :=
map_preimage _ _ _
/-- Composition of a `simple_fun` and a measurable function is a `simple_func`. -/
def comp [measurable_space β] (f : β →ₛ γ) (g : α → β) (hgm : measurable g) : α →ₛ γ :=
{ to_fun := f ∘ g,
finite_range' := f.finite_range.subset $ set.range_comp_subset_range _ _,
measurable_set_fiber' := λ z, hgm (f.measurable_set_fiber z) }
@[simp] lemma coe_comp [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) :
⇑(f.comp g hgm) = f ∘ g :=
rfl
lemma range_comp_subset_range [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) :
(f.comp g hgm).range ⊆ f.range :=
finset.coe_subset.1 $ by simp only [coe_range, coe_comp, set.range_comp_subset_range]
/-- Extend a `simple_func` along a measurable embedding: `f₁.extend g hg f₂` is the function
`F : β →ₛ γ` such that `F ∘ g = f₁` and `F y = f₂ y` whenever `y ∉ range g`. -/
def extend [measurable_space β] (f₁ : α →ₛ γ) (g : α → β)
(hg : measurable_embedding g) (f₂ : β →ₛ γ) : β →ₛ γ :=
{ to_fun := function.extend g f₁ f₂,
finite_range' := (f₁.finite_range.union $ f₂.finite_range.subset
(image_subset_range _ _)).subset (range_extend_subset _ _ _),
measurable_set_fiber' :=
begin
letI : measurable_space γ := ⊤, haveI : measurable_singleton_class γ := ⟨λ _, trivial⟩,
exact λ x, hg.measurable_extend f₁.measurable f₂.measurable (measurable_set_singleton _)
end }
@[simp] lemma extend_apply [measurable_space β] (f₁ : α →ₛ γ) {g : α → β}
(hg : measurable_embedding g) (f₂ : β →ₛ γ) (x : α) : (f₁.extend g hg f₂) (g x) = f₁ x :=
function.extend_apply hg.injective _ _ _
@[simp] lemma extend_apply' [measurable_space β] (f₁ : α →ₛ γ) {g : α → β}
(hg : measurable_embedding g) (f₂ : β →ₛ γ) {y : β} (h : ¬∃ x, g x = y) :
(f₁.extend g hg f₂) y = f₂ y :=
function.extend_apply' _ _ _ h
@[simp] lemma extend_comp_eq' [measurable_space β] (f₁ : α →ₛ γ) {g : α → β}
(hg : measurable_embedding g) (f₂ : β →ₛ γ) : (f₁.extend g hg f₂) ∘ g = f₁ :=
funext $ λ x, extend_apply _ _ _ _
@[simp] lemma extend_comp_eq [measurable_space β] (f₁ : α →ₛ γ) {g : α → β}
(hg : measurable_embedding g) (f₂ : β →ₛ γ) : (f₁.extend g hg f₂).comp g hg.measurable = f₁ :=
coe_injective $ extend_comp_eq' _ _ _
/-- If `f` is a simple function taking values in `β → γ` and `g` is another simple function
with the same domain and codomain `β`, then `f.seq g = f a (g a)`. -/
def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f)
@[simp] lemma seq_apply (f : α →ₛ (β → γ)) (g : α →ₛ β) (a : α) : f.seq g a = f a (g a) := rfl
/-- Combine two simple functions `f : α →ₛ β` and `g : α →ₛ β`
into `λ a, (f a, g a)`. -/
def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g
@[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl
lemma pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : set β) (t : set γ) :
pair f g ⁻¹' s ×ˢ t = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl
/- A special form of `pair_preimage` -/
lemma pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) :
(pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) :=
by { rw ← singleton_prod_singleton, exact pair_preimage _ _ _ _ }
theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp
@[to_additive] instance [has_one β] : has_one (α →ₛ β) := ⟨const α 1⟩
@[to_additive] instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩
@[to_additive] instance [has_div β] : has_div (α →ₛ β) := ⟨λf g, (f.map (/)).seq g⟩
@[to_additive] instance [has_inv β] : has_inv (α →ₛ β) := ⟨λf, f.map (has_inv.inv)⟩
instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩
instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩
instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩
@[simp, to_additive] lemma const_one [has_one β] : const α (1 : β) = 1 := rfl
@[simp, norm_cast, to_additive] lemma coe_one [has_one β] : ⇑(1 : α →ₛ β) = 1 := rfl
@[simp, norm_cast, to_additive] lemma coe_mul [has_mul β] (f g : α →ₛ β) : ⇑(f * g) = f * g := rfl
@[simp, norm_cast, to_additive] lemma coe_inv [has_inv β] (f : α →ₛ β) : ⇑(f⁻¹) = f⁻¹ := rfl
@[simp, norm_cast, to_additive] lemma coe_div [has_div β] (f g : α →ₛ β) : ⇑(f / g) = f / g := rfl
@[simp, norm_cast] lemma coe_le [preorder β] {f g : α →ₛ β} : (f : α → β) ≤ g ↔ f ≤ g := iff.rfl
@[simp, norm_cast] lemma coe_sup [has_sup β] (f g : α →ₛ β) : ⇑(f ⊔ g) = f ⊔ g := rfl
@[simp, norm_cast] lemma coe_inf [has_inf β] (f g : α →ₛ β) : ⇑(f ⊓ g) = f ⊓ g := rfl
@[to_additive] lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl
@[to_additive] lemma div_apply [has_div β] (f g : α →ₛ β) (x : α) : (f / g) x = f x / g x := rfl
@[to_additive] lemma inv_apply [has_inv β] (f : α →ₛ β) (x : α) : f⁻¹ x = (f x)⁻¹ := rfl
lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl
lemma inf_apply [has_inf β] (f g : α →ₛ β) (a : α) : (f ⊓ g) a = f a ⊓ g a := rfl
@[simp, to_additive] lemma range_one [nonempty α] [has_one β] : (1 : α →ₛ β).range = {1} :=
finset.ext $ λ x, by simp [eq_comm]
@[simp] lemma range_eq_empty_of_is_empty {β} [hα : is_empty α] (f : α →ₛ β) :
f.range = ∅ :=
begin
rw ← finset.not_nonempty_iff_eq_empty,
by_contra,
obtain ⟨y, hy_mem⟩ := h,
rw [simple_func.mem_range, set.mem_range] at hy_mem,
obtain ⟨x, hxy⟩ := hy_mem,
rw is_empty_iff at hα,
exact hα x,
end
lemma eq_zero_of_mem_range_zero [has_zero β] : ∀ {y : β}, y ∈ (0 : α →ₛ β).range → y = 0 :=
forall_range_iff.2 $ λ x, rfl
@[to_additive]
lemma mul_eq_map₂ [has_mul β] (f g : α →ₛ β) : f * g = (pair f g).map (λp:β×β, p.1 * p.2) := rfl
lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) := rfl
@[to_additive]
lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl
@[to_additive]
theorem map_mul [has_mul β] [has_mul γ] {g : β → γ}
(hg : ∀ x y, g (x * y) = g x * g y) (f₁ f₂ : α →ₛ β) : (f₁ * f₂).map g = f₁.map g * f₂.map g :=
ext $ λ x, hg _ _
variables {K : Type*}
instance [has_smul K β] : has_smul K (α →ₛ β) := ⟨λ k f, f.map ((•) k)⟩
@[simp] lemma coe_smul [has_smul K β] (c : K) (f : α →ₛ β) : ⇑(c • f) = c • f := rfl
lemma smul_apply [has_smul K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl
instance has_nat_pow [monoid β] : has_pow (α →ₛ β) ℕ := ⟨λ f n, f.map (^ n)⟩
@[simp] lemma coe_pow [monoid β] (f : α →ₛ β) (n : ℕ) : ⇑(f ^ n) = f ^ n := rfl
lemma pow_apply [monoid β] (n : ℕ) (f : α →ₛ β) (a : α) : (f ^ n) a = f a ^ n := rfl
instance has_int_pow [div_inv_monoid β] : has_pow (α →ₛ β) ℤ := ⟨λ f n, f.map (^ n)⟩
@[simp] lemma coe_zpow [div_inv_monoid β] (f : α →ₛ β) (z : ℤ) : ⇑(f ^ z) = f ^ z := rfl
lemma zpow_apply [div_inv_monoid β] (z : ℤ) (f : α →ₛ β) (a : α) : (f ^ z) a = f a ^ z := rfl
-- TODO: work out how to generate these instances with `to_additive`, which gets confused by the
-- argument order swap between `coe_smul` and `coe_pow`.
section additive
instance [add_monoid β] : add_monoid (α →ₛ β) :=
function.injective.add_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add
(λ _ _, coe_smul _ _)
instance [add_comm_monoid β] : add_comm_monoid (α →ₛ β) :=
function.injective.add_comm_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add
(λ _ _, coe_smul _ _)
instance [add_group β] : add_group (α →ₛ β) :=
function.injective.add_group (λ f, show α → β, from f) coe_injective
coe_zero coe_add coe_neg coe_sub (λ _ _, coe_smul _ _) (λ _ _, coe_smul _ _)
instance [add_comm_group β] : add_comm_group (α →ₛ β) :=
function.injective.add_comm_group (λ f, show α → β, from f) coe_injective
coe_zero coe_add coe_neg coe_sub (λ _ _, coe_smul _ _) (λ _ _, coe_smul _ _)
end additive
@[to_additive] instance [monoid β] : monoid (α →ₛ β) :=
function.injective.monoid (λ f, show α → β, from f) coe_injective coe_one coe_mul coe_pow
@[to_additive] instance [comm_monoid β] : comm_monoid (α →ₛ β) :=
function.injective.comm_monoid (λ f, show α → β, from f) coe_injective coe_one coe_mul coe_pow
@[to_additive] instance [group β] : group (α →ₛ β) :=
function.injective.group (λ f, show α → β, from f) coe_injective
coe_one coe_mul coe_inv coe_div coe_pow coe_zpow
@[to_additive] instance [comm_group β] : comm_group (α →ₛ β) :=
function.injective.comm_group (λ f, show α → β, from f) coe_injective
coe_one coe_mul coe_inv coe_div coe_pow coe_zpow
instance [semiring K] [add_comm_monoid β] [module K β] : module K (α →ₛ β) :=
function.injective.module K ⟨λ f, show α → β, from f, coe_zero, coe_add⟩
coe_injective coe_smul
lemma smul_eq_map [has_smul K β] (k : K) (f : α →ₛ β) : k • f = f.map ((•) k) := rfl
instance [preorder β] : preorder (α →ₛ β) :=
{ le_refl := λf a, le_rfl,
le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a),
.. simple_func.has_le }
instance [partial_order β] : partial_order (α →ₛ β) :=
{ le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a),
.. simple_func.preorder }
instance [has_le β] [order_bot β] : order_bot (α →ₛ β) :=
{ bot := const α ⊥, bot_le := λf a, bot_le }
instance [has_le β] [order_top β] : order_top (α →ₛ β) :=
{ top := const α ⊤, le_top := λf a, le_top }
instance [semilattice_inf β] : semilattice_inf (α →ₛ β) :=
{ inf := (⊓),
inf_le_left := assume f g a, inf_le_left,
inf_le_right := assume f g a, inf_le_right,
le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a),
.. simple_func.partial_order }
instance [semilattice_sup β] : semilattice_sup (α →ₛ β) :=
{ sup := (⊔),
le_sup_left := assume f g a, le_sup_left,
le_sup_right := assume f g a, le_sup_right,
sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a),
.. simple_func.partial_order }
instance [lattice β] : lattice (α →ₛ β) :=
{ .. simple_func.semilattice_sup,.. simple_func.semilattice_inf }
instance [has_le β] [bounded_order β] : bounded_order (α →ₛ β) :=
{ .. simple_func.order_bot, .. simple_func.order_top }
lemma finset_sup_apply [semilattice_sup β] [order_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) :
s.sup f a = s.sup (λc, f c a) :=
begin
refine finset.induction_on s rfl _,
assume a s hs ih,
rw [finset.sup_insert, finset.sup_insert, sup_apply, ih]
end
section restrict
variables [has_zero β]
/-- Restrict a simple function `f : α →ₛ β` to a set `s`. If `s` is measurable,
then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const α 0`. -/
def restrict (f : α →ₛ β) (s : set α) : α →ₛ β :=
if hs : measurable_set s then piecewise s hs f 0 else 0
theorem restrict_of_not_measurable {f : α →ₛ β} {s : set α}
(hs : ¬measurable_set s) :
restrict f s = 0 :=
dif_neg hs
@[simp] theorem coe_restrict (f : α →ₛ β) {s : set α} (hs : measurable_set s) :
⇑(restrict f s) = indicator s f :=
by { rw [restrict, dif_pos hs], refl }
@[simp] theorem restrict_univ (f : α →ₛ β) : restrict f univ = f :=
by simp [restrict]
@[simp] theorem restrict_empty (f : α →ₛ β) : restrict f ∅ = 0 :=
by simp [restrict]
theorem map_restrict_of_zero [has_zero γ] {g : β → γ} (hg : g 0 = 0) (f : α →ₛ β) (s : set α) :
(f.restrict s).map g = (f.map g).restrict s :=
ext $ λ x,
if hs : measurable_set s then by simp [hs, set.indicator_comp_of_zero hg]
else by simp [restrict_of_not_measurable hs, hg]
theorem map_coe_ennreal_restrict (f : α →ₛ ℝ≥0) (s : set α) :
(f.restrict s).map (coe : ℝ≥0 → ℝ≥0∞) = (f.map coe).restrict s :=
map_restrict_of_zero ennreal.coe_zero _ _
theorem map_coe_nnreal_restrict (f : α →ₛ ℝ≥0) (s : set α) :
(f.restrict s).map (coe : ℝ≥0 → ℝ) = (f.map coe).restrict s :=
map_restrict_of_zero nnreal.coe_zero _ _
theorem restrict_apply (f : α →ₛ β) {s : set α} (hs : measurable_set s) (a) :
restrict f s a = indicator s f a :=
by simp only [f.coe_restrict hs]
theorem restrict_preimage (f : α →ₛ β) {s : set α} (hs : measurable_set s)
{t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t :=
by simp [hs, indicator_preimage_of_not_mem _ _ ht, inter_comm]
theorem restrict_preimage_singleton (f : α →ₛ β) {s : set α} (hs : measurable_set s)
{r : β} (hr : r ≠ 0) : restrict f s ⁻¹' {r} = s ∩ f ⁻¹' {r} :=
f.restrict_preimage hs hr.symm
lemma mem_restrict_range {r : β} {s : set α} {f : α →ₛ β} (hs : measurable_set s) :
r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (r ∈ f '' s) :=
by rw [← finset.mem_coe, coe_range, coe_restrict _ hs, mem_range_indicator]
lemma mem_image_of_mem_range_restrict {r : β} {s : set α} {f : α →ₛ β}
(hr : r ∈ (restrict f s).range) (h0 : r ≠ 0) :
r ∈ f '' s :=
if hs : measurable_set s then by simpa [mem_restrict_range hs, h0] using hr
else by { rw [restrict_of_not_measurable hs] at hr,
exact (h0 $ eq_zero_of_mem_range_zero hr).elim }
@[mono] lemma restrict_mono [preorder β] (s : set α) {f g : α →ₛ β} (H : f ≤ g) :
f.restrict s ≤ g.restrict s :=
if hs : measurable_set s then λ x, by simp only [coe_restrict _ hs, indicator_le_indicator (H x)]
else by simp only [restrict_of_not_measurable hs, le_refl]
end restrict
section approx
section
variables [semilattice_sup β] [order_bot β] [has_zero β]
/-- Fix a sequence `i : ℕ → β`. Given a function `α → β`, its `n`-th approximation
by simple functions is defined so that in case `β = ℝ≥0∞` it sends each `a` to the supremum
of the set `{i k | k ≤ n ∧ i k ≤ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/
def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β :=
(finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a})
lemma approx_apply [topological_space β] [order_closed_topology β] [measurable_space β]
[opens_measurable_space β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : measurable f) :
(approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) :=
begin
dsimp only [approx],
rw [finset_sup_apply],
congr,
funext k,
rw [restrict_apply],
refl,
exact (hf measurable_set_Ici)
end
lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) :=
assume n m h, finset.sup_mono $ finset.range_subset.2 h
lemma approx_comp [topological_space β] [order_closed_topology β] [measurable_space β]
[opens_measurable_space β] [measurable_space γ]
{i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α)
(hf : measurable f) (hg : measurable g) :
(approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) :=
by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)]
end
lemma supr_approx_apply [topological_space β] [complete_lattice β] [order_closed_topology β]
[has_zero β] [measurable_space β] [opens_measurable_space β]
(i : ℕ → β) (f : α → β) (a : α) (hf : measurable f) (h_zero : (0 : β) = ⊥) :
(⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) :=
begin
refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _),
{ rw [approx_apply a hf, h_zero],
refine finset.sup_le (assume k hk, _),
split_ifs,
exact le_supr_of_le k (le_supr _ h),
exact bot_le },
{ refine le_supr_of_le (k+1) _,
rw [approx_apply a hf],
have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _),
refine le_trans (le_of_eq _) (finset.le_sup this),
rw [if_pos hk] }
end
end approx
section eapprox
/-- A sequence of `ℝ≥0∞`s such that its range is the set of non-negative rational numbers. -/
def ennreal_rat_embed (n : ℕ) : ℝ≥0∞ :=
ennreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ))
lemma ennreal_rat_embed_encode (q : ℚ) :
ennreal_rat_embed (encodable.encode q) = real.to_nnreal q :=
by rw [ennreal_rat_embed, encodable.encodek]; refl
/-- Approximate a function `α → ℝ≥0∞` by a sequence of simple functions. -/
def eapprox : (α → ℝ≥0∞) → ℕ → α →ₛ ℝ≥0∞ :=
approx ennreal_rat_embed
lemma eapprox_lt_top (f : α → ℝ≥0∞) (n : ℕ) (a : α) : eapprox f n a < ∞ :=
begin
simp only [eapprox, approx, finset_sup_apply, finset.sup_lt_iff, with_top.zero_lt_top,
finset.mem_range, ennreal.bot_eq_zero, restrict],
assume b hb,
split_ifs,
{ simp only [coe_zero, coe_piecewise, piecewise_eq_indicator, coe_const],
calc {a : α | ennreal_rat_embed b ≤ f a}.indicator (λ x, ennreal_rat_embed b) a
≤ ennreal_rat_embed b : indicator_le_self _ _ a
... < ⊤ : ennreal.coe_lt_top },
{ exact with_top.zero_lt_top },
end
@[mono] lemma monotone_eapprox (f : α → ℝ≥0∞) : monotone (eapprox f) :=
monotone_approx _ f
lemma supr_eapprox_apply (f : α → ℝ≥0∞) (hf : measurable f) (a : α) :
(⨆n, (eapprox f n : α →ₛ ℝ≥0∞) a) = f a :=
begin
rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl],
refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _),
assume h,
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩,
have : (real.to_nnreal q : ℝ≥0∞) ≤
(⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k),
{ refine le_supr_of_le (encodable.encode q) _,
rw [ennreal_rat_embed_encode q],
refine le_supr_of_le (le_of_lt q_lt) _,
exact le_rfl },
exact lt_irrefl _ (lt_of_le_of_lt this lt_q)
end
lemma eapprox_comp [measurable_space γ] {f : γ → ℝ≥0∞} {g : α → γ} {n : ℕ}
(hf : measurable f) (hg : measurable g) :
(eapprox (f ∘ g) n : α → ℝ≥0∞) = (eapprox f n : γ →ₛ ℝ≥0∞) ∘ g :=
funext $ assume a, approx_comp a hf hg
/-- Approximate a function `α → ℝ≥0∞` by a series of simple functions taking their values
in `ℝ≥0`. -/
def eapprox_diff (f : α → ℝ≥0∞) : ∀ (n : ℕ), α →ₛ ℝ≥0
| 0 := (eapprox f 0).map ennreal.to_nnreal
| (n+1) := (eapprox f (n+1) - eapprox f n).map ennreal.to_nnreal
lemma sum_eapprox_diff (f : α → ℝ≥0∞) (n : ℕ) (a : α) :
(∑ k in finset.range (n+1), (eapprox_diff f k a : ℝ≥0∞)) = eapprox f n a :=
begin
induction n with n IH,
{ simp only [nat.nat_zero_eq_zero, finset.sum_singleton, finset.range_one], refl },
{ rw [finset.sum_range_succ, nat.succ_eq_add_one, IH, eapprox_diff, coe_map, function.comp_app,
coe_sub, pi.sub_apply, ennreal.coe_to_nnreal,
add_tsub_cancel_of_le (monotone_eapprox f (nat.le_succ _) _)],
apply (lt_of_le_of_lt _ (eapprox_lt_top f (n+1) a)).ne,
rw tsub_le_iff_right,
exact le_self_add },
end
lemma tsum_eapprox_diff (f : α → ℝ≥0∞) (hf : measurable f) (a : α) :
(∑' n, (eapprox_diff f n a : ℝ≥0∞)) = f a :=
by simp_rw [ennreal.tsum_eq_supr_nat' (tendsto_add_at_top_nat 1), sum_eapprox_diff,
supr_eapprox_apply f hf a]
end eapprox
end measurable
section measure
variables {m : measurable_space α} {μ ν : measure α}
/-- Integral of a simple function whose codomain is `ℝ≥0∞`. -/
def lintegral {m : measurable_space α} (f : α →ₛ ℝ≥0∞) (μ : measure α) : ℝ≥0∞ :=
∑ x in f.range, x * μ (f ⁻¹' {x})
lemma lintegral_eq_of_subset (f : α →ₛ ℝ≥0∞) {s : finset ℝ≥0∞}
(hs : ∀ x, f x ≠ 0 → μ (f ⁻¹' {f x}) ≠ 0 → f x ∈ s) :
f.lintegral μ = ∑ x in s, x * μ (f ⁻¹' {x}) :=
begin
refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _,
{ simpa only [forall_range_iff, mul_ne_zero_iff, and_imp] },
{ intros, assumption },
{ intros b _ hb,
refine ⟨b, _, hb, rfl⟩,
rw [mem_range, ← preimage_singleton_nonempty],
exact nonempty_of_measure_ne_zero (mul_ne_zero_iff.1 hb).2 },
{ intros, refl }
end
lemma lintegral_eq_of_subset' (f : α →ₛ ℝ≥0∞) {s : finset ℝ≥0∞}
(hs : f.range \ {0} ⊆ s) :
f.lintegral μ = ∑ x in s, x * μ (f ⁻¹' {x}) :=
f.lintegral_eq_of_subset $ λ x hfx _, hs $
finset.mem_sdiff.2 ⟨f.mem_range_self x, mt finset.mem_singleton.1 hfx⟩
/-- Calculate the integral of `(g ∘ f)`, where `g : β → ℝ≥0∞` and `f : α →ₛ β`. -/
lemma map_lintegral (g : β → ℝ≥0∞) (f : α →ₛ β) :
(f.map g).lintegral μ = ∑ x in f.range, g x * μ (f ⁻¹' {x}) :=
begin
simp only [lintegral, range_map],
refine finset.sum_image' _ (assume b hb, _),
rcases mem_range.1 hb with ⟨a, rfl⟩,
rw [map_preimage_singleton, ← f.sum_measure_preimage_singleton, finset.mul_sum],
refine finset.sum_congr _ _,
{ congr },
{ assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h },
end
lemma add_lintegral (f g : α →ₛ ℝ≥0∞) : (f + g).lintegral μ = f.lintegral μ + g.lintegral μ :=
calc (f + g).lintegral μ =
∑ x in (pair f g).range, (x.1 * μ (pair f g ⁻¹' {x}) + x.2 * μ (pair f g ⁻¹' {x})) :
by rw [add_eq_map₂, map_lintegral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _)
... = ∑ x in (pair f g).range, x.1 * μ (pair f g ⁻¹' {x}) +
∑ x in (pair f g).range, x.2 * μ (pair f g ⁻¹' {x}) : by rw [finset.sum_add_distrib]
... = ((pair f g).map prod.fst).lintegral μ + ((pair f g).map prod.snd).lintegral μ :
by rw [map_lintegral, map_lintegral]
... = lintegral f μ + lintegral g μ : rfl
lemma const_mul_lintegral (f : α →ₛ ℝ≥0∞) (x : ℝ≥0∞) :
(const α x * f).lintegral μ = x * f.lintegral μ :=
calc (f.map (λa, x * a)).lintegral μ = ∑ r in f.range, x * r * μ (f ⁻¹' {r}) :
map_lintegral _ _
... = ∑ r in f.range, x * (r * μ (f ⁻¹' {r})) :
finset.sum_congr rfl (assume a ha, mul_assoc _ _ _)
... = x * f.lintegral μ :
finset.mul_sum.symm
/-- Integral of a simple function `α →ₛ ℝ≥0∞` as a bilinear map. -/
def lintegralₗ {m : measurable_space α} : (α →ₛ ℝ≥0∞) →ₗ[ℝ≥0∞] measure α →ₗ[ℝ≥0∞] ℝ≥0∞ :=
{ to_fun := λ f,
{ to_fun := lintegral f,
map_add' := by simp [lintegral, mul_add, finset.sum_add_distrib],
map_smul' := λ c μ, by simp [lintegral, mul_left_comm _ c, finset.mul_sum] },
map_add' := λ f g, linear_map.ext (λ μ, add_lintegral f g),
map_smul' := λ c f, linear_map.ext (λ μ, const_mul_lintegral f c) }
@[simp] lemma zero_lintegral : (0 : α →ₛ ℝ≥0∞).lintegral μ = 0 :=
linear_map.ext_iff.1 lintegralₗ.map_zero μ
lemma lintegral_add {ν} (f : α →ₛ ℝ≥0∞) : f.lintegral (μ + ν) = f.lintegral μ + f.lintegral ν :=
(lintegralₗ f).map_add μ ν
lemma lintegral_smul (f : α →ₛ ℝ≥0∞) (c : ℝ≥0∞) :
f.lintegral (c • μ) = c • f.lintegral μ :=
(lintegralₗ f).map_smul c μ
@[simp] lemma lintegral_zero [measurable_space α] (f : α →ₛ ℝ≥0∞) :
f.lintegral 0 = 0 :=
(lintegralₗ f).map_zero
lemma lintegral_sum {m : measurable_space α} {ι} (f : α →ₛ ℝ≥0∞) (μ : ι → measure α) :
f.lintegral (measure.sum μ) = ∑' i, f.lintegral (μ i) :=
begin
simp only [lintegral, measure.sum_apply, f.measurable_set_preimage, ← finset.tsum_subtype,
← ennreal.tsum_mul_left],
apply ennreal.tsum_comm
end
lemma restrict_lintegral (f : α →ₛ ℝ≥0∞) {s : set α} (hs : measurable_set s) :
(restrict f s).lintegral μ = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) :=
calc (restrict f s).lintegral μ = ∑ r in f.range, r * μ (restrict f s ⁻¹' {r}) :
lintegral_eq_of_subset _ $ λ x hx, if hxs : x ∈ s
then λ _, by simp only [f.restrict_apply hs, indicator_of_mem hxs, mem_range_self]
else false.elim $ hx $ by simp [*]
... = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) :
finset.sum_congr rfl $ forall_range_iff.2 $ λ b, if hb : f b = 0 then by simp only [hb, zero_mul]
else by rw [restrict_preimage_singleton _ hs hb, inter_comm]
lemma lintegral_restrict {m : measurable_space α} (f : α →ₛ ℝ≥0∞) (s : set α) (μ : measure α) :
f.lintegral (μ.restrict s) = ∑ y in f.range, y * μ (f ⁻¹' {y} ∩ s) :=
by simp only [lintegral, measure.restrict_apply, f.measurable_set_preimage]
lemma restrict_lintegral_eq_lintegral_restrict (f : α →ₛ ℝ≥0∞) {s : set α}
(hs : measurable_set s) :
(restrict f s).lintegral μ = f.lintegral (μ.restrict s) :=
by rw [f.restrict_lintegral hs, lintegral_restrict]
lemma const_lintegral (c : ℝ≥0∞) : (const α c).lintegral μ = c * μ univ :=
begin
rw [lintegral],
casesI is_empty_or_nonempty α,
{ simp [μ.eq_zero_of_is_empty] },
{ simp [preimage_const_of_mem] },
end
lemma const_lintegral_restrict (c : ℝ≥0∞) (s : set α) :
(const α c).lintegral (μ.restrict s) = c * μ s :=
by rw [const_lintegral, measure.restrict_apply measurable_set.univ, univ_inter]
lemma restrict_const_lintegral (c : ℝ≥0∞) {s : set α} (hs : measurable_set s) :
((const α c).restrict s).lintegral μ = c * μ s :=
by rw [restrict_lintegral_eq_lintegral_restrict _ hs, const_lintegral_restrict]
lemma le_sup_lintegral (f g : α →ₛ ℝ≥0∞) : f.lintegral μ ⊔ g.lintegral μ ≤ (f ⊔ g).lintegral μ :=
calc f.lintegral μ ⊔ g.lintegral μ =
((pair f g).map prod.fst).lintegral μ ⊔ ((pair f g).map prod.snd).lintegral μ : rfl
... ≤ ∑ x in (pair f g).range, (x.1 ⊔ x.2) * μ (pair f g ⁻¹' {x}) :
begin
rw [map_lintegral, map_lintegral],
refine sup_le _ _;
refine finset.sum_le_sum (λ a _, mul_le_mul_right' _ _),
exact le_sup_left,
exact le_sup_right
end
... = (f ⊔ g).lintegral μ : by rw [sup_eq_map₂, map_lintegral]
/-- `simple_func.lintegral` is monotone both in function and in measure. -/
@[mono] lemma lintegral_mono {f g : α →ₛ ℝ≥0∞} (hfg : f ≤ g) (hμν : μ ≤ ν) :
f.lintegral μ ≤ g.lintegral ν :=
calc f.lintegral μ ≤ f.lintegral μ ⊔ g.lintegral μ : le_sup_left
... ≤ (f ⊔ g).lintegral μ : le_sup_lintegral _ _
... = g.lintegral μ : by rw [sup_of_le_right hfg]
... ≤ g.lintegral ν : finset.sum_le_sum $ λ y hy, ennreal.mul_left_mono $
hμν _ (g.measurable_set_preimage _)
/-- `simple_func.lintegral` depends only on the measures of `f ⁻¹' {y}`. -/
lemma lintegral_eq_of_measure_preimage [measurable_space β] {f : α →ₛ ℝ≥0∞} {g : β →ₛ ℝ≥0∞}
{ν : measure β} (H : ∀ y, μ (f ⁻¹' {y}) = ν (g ⁻¹' {y})) :
f.lintegral μ = g.lintegral ν :=
begin
simp only [lintegral, ← H],
apply lintegral_eq_of_subset,
simp only [H],
intros,
exact mem_range_of_measure_ne_zero ‹_›
end
/-- If two simple functions are equal a.e., then their `lintegral`s are equal. -/
lemma lintegral_congr {f g : α →ₛ ℝ≥0∞} (h : f =ᵐ[μ] g) :
f.lintegral μ = g.lintegral μ :=
lintegral_eq_of_measure_preimage $ λ y, measure_congr $
eventually.set_eq $ h.mono $ λ x hx, by simp [hx]
lemma lintegral_map' {β} [measurable_space β] {μ' : measure β} (f : α →ₛ ℝ≥0∞) (g : β →ₛ ℝ≥0∞)
(m' : α → β) (eq : ∀ a, f a = g (m' a)) (h : ∀s, measurable_set s → μ' s = μ (m' ⁻¹' s)) :
f.lintegral μ = g.lintegral μ' :=
lintegral_eq_of_measure_preimage $ λ y,
by { simp only [preimage, eq], exact (h (g ⁻¹' {y}) (g.measurable_set_preimage _)).symm }
lemma lintegral_map {β} [measurable_space β] (g : β →ₛ ℝ≥0∞) {f : α → β} (hf : measurable f) :
g.lintegral (measure.map f μ) = (g.comp f hf).lintegral μ :=
eq.symm $ lintegral_map' _ _ f (λ a, rfl) (λ s hs, measure.map_apply hf hs)
end measure
section fin_meas_supp
open finset function
lemma support_eq [measurable_space α] [has_zero β] (f : α →ₛ β) :
support f = ⋃ y ∈ f.range.filter (λ y, y ≠ 0), f ⁻¹' {y} :=
set.ext $ λ x, by simp only [mem_support, set.mem_preimage, mem_filter, mem_range_self, true_and,
exists_prop, mem_Union, set.mem_range, mem_singleton_iff, exists_eq_right']
variables {m : measurable_space α} [has_zero β] [has_zero γ] {μ : measure α} {f : α →ₛ β}
lemma measurable_set_support [measurable_space α] (f : α →ₛ β) : measurable_set (support f) :=
by { rw f.support_eq, exact finset.measurable_set_bUnion _ (λ y hy, measurable_set_fiber _ _), }
/-- A `simple_func` has finite measure support if it is equal to `0` outside of a set of finite
measure. -/
protected def fin_meas_supp {m : measurable_space α} (f : α →ₛ β) (μ : measure α) : Prop :=
f =ᶠ[μ.cofinite] 0
lemma fin_meas_supp_iff_support : f.fin_meas_supp μ ↔ μ (support f) < ∞ := iff.rfl
lemma fin_meas_supp_iff : f.fin_meas_supp μ ↔ ∀ y ≠ 0, μ (f ⁻¹' {y}) < ∞ :=
begin
split,
{ refine λ h y hy, lt_of_le_of_lt (measure_mono _) h,
exact λ x hx (H : f x = 0), hy $ H ▸ eq.symm hx },
{ intro H,
rw [fin_meas_supp_iff_support, support_eq],
refine lt_of_le_of_lt (measure_bUnion_finset_le _ _) (sum_lt_top _),
exact λ y hy, (H y (finset.mem_filter.1 hy).2).ne }
end
namespace fin_meas_supp
lemma meas_preimage_singleton_ne_zero (h : f.fin_meas_supp μ) {y : β} (hy : y ≠ 0) :
μ (f ⁻¹' {y}) < ∞ :=
fin_meas_supp_iff.1 h y hy
protected lemma map {g : β → γ} (hf : f.fin_meas_supp μ) (hg : g 0 = 0) :
(f.map g).fin_meas_supp μ :=
flip lt_of_le_of_lt hf (measure_mono $ support_comp_subset hg f)
lemma of_map {g : β → γ} (h : (f.map g).fin_meas_supp μ) (hg : ∀b, g b = 0 → b = 0) :
f.fin_meas_supp μ :=
flip lt_of_le_of_lt h $ measure_mono $ support_subset_comp hg _
lemma map_iff {g : β → γ} (hg : ∀ {b}, g b = 0 ↔ b = 0) :
(f.map g).fin_meas_supp μ ↔ f.fin_meas_supp μ :=
⟨λ h, h.of_map $ λ b, hg.1, λ h, h.map $ hg.2 rfl⟩
protected lemma pair {g : α →ₛ γ} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) :
(pair f g).fin_meas_supp μ :=
calc μ (support $ pair f g) = μ (support f ∪ support g) : congr_arg μ $ support_prod_mk f g
... ≤ μ (support f) + μ (support g) : measure_union_le _ _
... < _ : add_lt_top.2 ⟨hf, hg⟩
protected lemma map₂ [has_zero δ] (hf : f.fin_meas_supp μ)
{g : α →ₛ γ} (hg : g.fin_meas_supp μ) {op : β → γ → δ} (H : op 0 0 = 0) :
((pair f g).map (function.uncurry op)).fin_meas_supp μ :=
(hf.pair hg).map H
protected lemma add {β} [add_monoid β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ)
(hg : g.fin_meas_supp μ) :
(f + g).fin_meas_supp μ :=
by { rw [add_eq_map₂], exact hf.map₂ hg (zero_add 0) }
protected lemma mul {β} [monoid_with_zero β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ)
(hg : g.fin_meas_supp μ) :
(f * g).fin_meas_supp μ :=
by { rw [mul_eq_map₂], exact hf.map₂ hg (zero_mul 0) }
lemma lintegral_lt_top {f : α →ₛ ℝ≥0∞} (hm : f.fin_meas_supp μ) (hf : ∀ᵐ a ∂μ, f a ≠ ∞) :
f.lintegral μ < ∞ :=
begin
refine sum_lt_top (λ a ha, _),
rcases eq_or_ne a ∞ with rfl|ha,
{ simp only [ae_iff, ne.def, not_not] at hf,
simp [set.preimage, hf] },
{ by_cases ha0 : a = 0,
{ subst a, rwa [zero_mul] },
{ exact mul_ne_top ha (fin_meas_supp_iff.1 hm _ ha0).ne } }
end
lemma of_lintegral_ne_top {f : α →ₛ ℝ≥0∞} (h : f.lintegral μ ≠ ∞) : f.fin_meas_supp μ :=
begin
refine fin_meas_supp_iff.2 (λ b hb, _),
rw [f.lintegral_eq_of_subset' (finset.subset_insert b _)] at h,
refine ennreal.lt_top_of_mul_ne_top_right _ hb,
exact (lt_top_of_sum_ne_top h (finset.mem_insert_self _ _)).ne
end
lemma iff_lintegral_lt_top {f : α →ₛ ℝ≥0∞} (hf : ∀ᵐ a ∂μ, f a ≠ ∞) :
f.fin_meas_supp μ ↔ f.lintegral μ < ∞ :=
⟨λ h, h.lintegral_lt_top hf, λ h, of_lintegral_ne_top h.ne⟩
end fin_meas_supp
end fin_meas_supp
/-- To prove something for an arbitrary simple function, it suffices to show
that the property holds for (multiples of) characteristic functions and is closed under
addition (of functions with disjoint support).
It is possible to make the hypotheses in `h_add` a bit stronger, and such conditions can be added
once we need them (for example it is only necessary to consider the case where `g` is a multiple
of a characteristic function, and that this multiple doesn't appear in the image of `f`) -/
@[elab_as_eliminator]
protected lemma induction {α γ} [measurable_space α] [add_monoid γ] {P : simple_func α γ → Prop}
(h_ind : ∀ c {s} (hs : measurable_set s),
P (simple_func.piecewise s hs (simple_func.const _ c) (simple_func.const _ 0)))
(h_add : ∀ ⦃f g : simple_func α γ⦄, disjoint (support f) (support g) → P f → P g → P (f + g))
(f : simple_func α γ) : P f :=
begin
generalize' h : f.range \ {0} = s,
rw [← finset.coe_inj, finset.coe_sdiff, finset.coe_singleton, simple_func.coe_range] at h,
revert s f h, refine finset.induction _ _,
{ intros f hf, rw [finset.coe_empty, diff_eq_empty, range_subset_singleton] at hf,
convert h_ind 0 measurable_set.univ, ext x, simp [hf] },
{ intros x s hxs ih f hf,
have mx := f.measurable_set_preimage {x},
let g := simple_func.piecewise (f ⁻¹' {x}) mx 0 f,
have Pg : P g,
{ apply ih, simp only [g, simple_func.coe_piecewise, range_piecewise],
rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, hf, finset.coe_insert,
insert_diff_self_of_not_mem, diff_eq_empty.mpr, set.empty_union],
{ rw [set.image_subset_iff], convert set.subset_univ _,
exact preimage_const_of_mem (mem_singleton _) },
{ rwa [finset.mem_coe] }},
convert h_add _ Pg (h_ind x mx),
{ ext1 y, by_cases hy : y ∈ f ⁻¹' {x}; [simpa [hy], simp [hy]] },
rintro y, by_cases hy : y ∈ f ⁻¹' {x}; simp [hy] }
end
end simple_func
section lintegral
open simple_func
variables {m : measurable_space α} {μ ν : measure α}
/-- The **lower Lebesgue integral** of a function `f` with respect to a measure `μ`. -/
@[irreducible] def lintegral {m : measurable_space α} (μ : measure α) (f : α → ℝ≥0∞) : ℝ≥0∞ :=
⨆ (g : α →ₛ ℝ≥0∞) (hf : ⇑g ≤ f), g.lintegral μ
/-! In the notation for integrals, an expression like `∫⁻ x, g ∥x∥ ∂μ` will not be parsed correctly,
and needs parentheses. We do not set the binding power of `r` to `0`, because then
`∫⁻ x, f x = 0` will be parsed incorrectly. -/
notation `∫⁻` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral μ r
notation `∫⁻` binders `, ` r:(scoped:60 f, lintegral volume f) := r
notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 :=
lintegral (measure.restrict μ s) r
notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, lintegral (measure.restrict volume s) f) := r
theorem simple_func.lintegral_eq_lintegral {m : measurable_space α} (f : α →ₛ ℝ≥0∞)
(μ : measure α) :
∫⁻ a, f a ∂ μ = f.lintegral μ :=
begin
rw lintegral,
exact le_antisymm
(supr₂_le $ λ g hg, lintegral_mono hg $ le_rfl)
(le_supr₂_of_le f le_rfl le_rfl)
end
@[mono] lemma lintegral_mono' {m : measurable_space α} ⦃μ ν : measure α⦄ (hμν : μ ≤ ν)
⦃f g : α → ℝ≥0∞⦄ (hfg : f ≤ g) :
∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂ν :=
begin
rw [lintegral, lintegral],
exact supr_mono (λ φ, supr_mono' $ λ hφ, ⟨le_trans hφ hfg, lintegral_mono (le_refl φ) hμν⟩)
end
lemma lintegral_mono ⦃f g : α → ℝ≥0∞⦄ (hfg : f ≤ g) :
∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ :=
lintegral_mono' (le_refl μ) hfg
lemma lintegral_mono_nnreal {f g : α → ℝ≥0} (h : f ≤ g) :
∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ :=
lintegral_mono $ λ a, ennreal.coe_le_coe.2 (h a)
lemma supr_lintegral_measurable_le_eq_lintegral (f : α → ℝ≥0∞) :
(⨆ (g : α → ℝ≥0∞) (g_meas : measurable g) (hg : g ≤ f), ∫⁻ a, g a ∂μ) = ∫⁻ a, f a ∂μ :=
begin
apply le_antisymm,
{ exact supr_le (λ i, supr_le (λ hi, supr_le (λ h'i, lintegral_mono h'i))) },
{ rw lintegral,
refine supr₂_le (λ i hi, le_supr₂_of_le i i.measurable $ le_supr_of_le hi _),
exact le_of_eq (i.lintegral_eq_lintegral _).symm },
end
lemma lintegral_mono_set {m : measurable_space α} ⦃μ : measure α⦄
{s t : set α} {f : α → ℝ≥0∞} (hst : s ⊆ t) :
∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in t, f x ∂μ :=
lintegral_mono' (measure.restrict_mono hst (le_refl μ)) (le_refl f)
lemma lintegral_mono_set' {m : measurable_space α} ⦃μ : measure α⦄
{s t : set α} {f : α → ℝ≥0∞} (hst : s ≤ᵐ[μ] t) :
∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in t, f x ∂μ :=
lintegral_mono' (measure.restrict_mono' hst (le_refl μ)) (le_refl f)
lemma monotone_lintegral {m : measurable_space α} (μ : measure α) : monotone (lintegral μ) :=
lintegral_mono
@[simp] lemma lintegral_const (c : ℝ≥0∞) : ∫⁻ a, c ∂μ = c * μ univ :=
by rw [← simple_func.const_lintegral, ← simple_func.lintegral_eq_lintegral, simple_func.coe_const]
lemma lintegral_zero : ∫⁻ a:α, 0 ∂μ = 0 := by simp
lemma lintegral_zero_fun : lintegral μ (0 : α → ℝ≥0∞) = 0 := lintegral_zero
@[simp] lemma lintegral_one : ∫⁻ a, (1 : ℝ≥0∞) ∂μ = μ univ :=
by rw [lintegral_const, one_mul]
lemma set_lintegral_const (s : set α) (c : ℝ≥0∞) : ∫⁻ a in s, c ∂μ = c * μ s :=
by rw [lintegral_const, measure.restrict_apply_univ]
lemma set_lintegral_one (s) : ∫⁻ a in s, 1 ∂μ = μ s :=
by rw [set_lintegral_const, one_mul]
lemma set_lintegral_const_lt_top [is_finite_measure μ] (s : set α) {c : ℝ≥0∞} (hc : c ≠ ∞) :
∫⁻ a in s, c ∂μ < ∞ :=
begin
rw lintegral_const,
exact ennreal.mul_lt_top hc (measure_ne_top (μ.restrict s) univ),
end
lemma lintegral_const_lt_top [is_finite_measure μ] {c : ℝ≥0∞} (hc : c ≠ ∞) :
∫⁻ a, c ∂μ < ∞ :=
by simpa only [measure.restrict_univ] using set_lintegral_const_lt_top univ hc
section
variable (μ)
/-- For any function `f : α → ℝ≥0∞`, there exists a measurable function `g ≤ f` with the same
integral. -/
lemma exists_measurable_le_lintegral_eq (f : α → ℝ≥0∞) :
∃ g : α → ℝ≥0∞, measurable g ∧ g ≤ f ∧ ∫⁻ a, f a ∂μ = ∫⁻ a, g a ∂μ :=
begin
cases eq_or_ne (∫⁻ a, f a ∂μ) 0 with h₀ h₀,
{ exact ⟨0, measurable_zero, zero_le f, h₀.trans lintegral_zero.symm⟩ },
rcases exists_seq_strict_mono_tendsto' h₀.bot_lt with ⟨L, hL_mono, hLf, hL_tendsto⟩,
have : ∀ n, ∃ g : α → ℝ≥0∞, measurable g ∧ g ≤ f ∧ L n < ∫⁻ a, g a ∂μ,
{ intro n,
simpa only [← supr_lintegral_measurable_le_eq_lintegral f, lt_supr_iff, exists_prop]
using (hLf n).2 },
choose g hgm hgf hLg,
refine ⟨λ x, ⨆ n, g n x, measurable_supr hgm, λ x, supr_le (λ n, hgf n x), le_antisymm _ _⟩,
{ refine le_of_tendsto' hL_tendsto (λ n, (hLg n).le.trans $ lintegral_mono $ λ x, _),
exact le_supr (λ n, g n x) n },
{ exact lintegral_mono (λ x, supr_le $ λ n, hgf n x) }
end
end
/-- `∫⁻ a in s, f a ∂μ` is defined as the supremum of integrals of simple functions
`φ : α →ₛ ℝ≥0∞` such that `φ ≤ f`. This lemma says that it suffices to take
functions `φ : α →ₛ ℝ≥0`. -/
lemma lintegral_eq_nnreal {m : measurable_space α} (f : α → ℝ≥0∞) (μ : measure α) :
(∫⁻ a, f a ∂μ) = (⨆ (φ : α →ₛ ℝ≥0) (hf : ∀ x, ↑(φ x) ≤ f x),
(φ.map (coe : ℝ≥0 → ℝ≥0∞)).lintegral μ) :=
begin
rw lintegral,
refine le_antisymm
(supr₂_le $ assume φ hφ, _)
(supr_mono' $ λ φ, ⟨φ.map (coe : ℝ≥0 → ℝ≥0∞), le_rfl⟩),
by_cases h : ∀ᵐ a ∂μ, φ a ≠ ∞,
{ let ψ := φ.map ennreal.to_nnreal,
replace h : ψ.map (coe : ℝ≥0 → ℝ≥0∞) =ᵐ[μ] φ :=
h.mono (λ a, ennreal.coe_to_nnreal),
have : ∀ x, ↑(ψ x) ≤ f x := λ x, le_trans ennreal.coe_to_nnreal_le_self (hφ x),
exact le_supr_of_le (φ.map ennreal.to_nnreal)
(le_supr_of_le this (ge_of_eq $ lintegral_congr h)) },
{ have h_meas : μ (φ ⁻¹' {∞}) ≠ 0, from mt measure_zero_iff_ae_nmem.1 h,
refine le_trans le_top (ge_of_eq $ (supr_eq_top _).2 $ λ b hb, _),
obtain ⟨n, hn⟩ : ∃ n : ℕ, b < n * μ (φ ⁻¹' {∞}), from exists_nat_mul_gt h_meas (ne_of_lt hb),
use (const α (n : ℝ≥0)).restrict (φ ⁻¹' {∞}),
simp only [lt_supr_iff, exists_prop, coe_restrict, φ.measurable_set_preimage, coe_const,
ennreal.coe_indicator, map_coe_ennreal_restrict, simple_func.map_const, ennreal.coe_nat,
restrict_const_lintegral],
refine ⟨indicator_le (λ x hx, le_trans _ (hφ _)), hn⟩,
simp only [mem_preimage, mem_singleton_iff] at hx,
simp only [hx, le_top] }
end
lemma exists_simple_func_forall_lintegral_sub_lt_of_pos {f : α → ℝ≥0∞} (h : ∫⁻ x, f x ∂μ ≠ ∞)
{ε : ℝ≥0∞} (hε : ε ≠ 0) :
∃ φ : α →ₛ ℝ≥0, (∀ x, ↑(φ x) ≤ f x) ∧ ∀ ψ : α →ₛ ℝ≥0, (∀ x, ↑(ψ x) ≤ f x) →
(map coe (ψ - φ)).lintegral μ < ε :=
begin
rw lintegral_eq_nnreal at h,
have := ennreal.lt_add_right h hε,
erw ennreal.bsupr_add at this; [skip, exact ⟨0, λ x, zero_le _⟩],
simp_rw [lt_supr_iff, supr_lt_iff, supr_le_iff] at this,
rcases this with ⟨φ, hle : ∀ x, ↑(φ x) ≤ f x, b, hbφ, hb⟩,
refine ⟨φ, hle, λ ψ hψ, _⟩,
have : (map coe φ).lintegral μ ≠ ∞, from ne_top_of_le_ne_top h (le_supr₂ φ hle),
rw [← ennreal.add_lt_add_iff_left this, ← add_lintegral, ← map_add @ennreal.coe_add],
refine (hb _ (λ x, le_trans _ (max_le (hle x) (hψ x)))).trans_lt hbφ,
norm_cast,
simp only [add_apply, sub_apply, add_tsub_eq_max]
end
theorem supr_lintegral_le {ι : Sort*} (f : ι → α → ℝ≥0∞) :
(⨆i, ∫⁻ a, f i a ∂μ) ≤ (∫⁻ a, ⨆i, f i a ∂μ) :=
begin
simp only [← supr_apply],
exact (monotone_lintegral μ).le_map_supr
end
lemma supr₂_lintegral_le {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ℝ≥0∞) :
(⨆ i j, ∫⁻ a, f i j a ∂μ) ≤ (∫⁻ a, ⨆ i j, f i j a ∂μ) :=
by { convert (monotone_lintegral μ).le_map_supr₂ f, ext1 a, simp only [supr_apply] }
theorem le_infi_lintegral {ι : Sort*} (f : ι → α → ℝ≥0∞) :
(∫⁻ a, ⨅i, f i a ∂μ) ≤ (⨅i, ∫⁻ a, f i a ∂μ) :=
by { simp only [← infi_apply], exact (monotone_lintegral μ).map_infi_le }
lemma le_infi₂_lintegral {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ℝ≥0∞) :
(∫⁻ a, ⨅ i (h : ι' i), f i h a ∂μ) ≤ (⨅ i (h : ι' i), ∫⁻ a, f i h a ∂μ) :=
by { convert (monotone_lintegral μ).map_infi₂_le f, ext1 a, simp only [infi_apply] }
lemma lintegral_mono_ae {f g : α → ℝ≥0∞} (h : ∀ᵐ a ∂μ, f a ≤ g a) :
(∫⁻ a, f a ∂μ) ≤ (∫⁻ a, g a ∂μ) :=
begin
rcases exists_measurable_superset_of_null h with ⟨t, hts, ht, ht0⟩,
have : ∀ᵐ x ∂μ, x ∉ t := measure_zero_iff_ae_nmem.1 ht0,
rw [lintegral, lintegral],
refine (supr_le $ assume s, supr_le $ assume hfs,
le_supr_of_le (s.restrict tᶜ) $ le_supr_of_le _ _),
{ assume a,
by_cases a ∈ t;
simp [h, restrict_apply, ht.compl],
exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) },
{ refine le_of_eq (simple_func.lintegral_congr $ this.mono $ λ a hnt, _),
by_cases hat : a ∈ t; simp [hat, ht.compl],
exact (hnt hat).elim }
end
lemma set_lintegral_mono_ae {s : set α} {f g : α → ℝ≥0∞}
(hf : measurable f) (hg : measurable g) (hfg : ∀ᵐ x ∂μ, x ∈ s → f x ≤ g x) :
∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in s, g x ∂μ :=
lintegral_mono_ae $ (ae_restrict_iff $ measurable_set_le hf hg).2 hfg
lemma set_lintegral_mono {s : set α} {f g : α → ℝ≥0∞}
(hf : measurable f) (hg : measurable g) (hfg : ∀ x ∈ s, f x ≤ g x) :
∫⁻ x in s, f x ∂μ ≤ ∫⁻ x in s, g x ∂μ :=
set_lintegral_mono_ae hf hg (ae_of_all _ hfg)
lemma lintegral_congr_ae {f g : α → ℝ≥0∞} (h : f =ᵐ[μ] g) :
(∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) :=
le_antisymm (lintegral_mono_ae $ h.le) (lintegral_mono_ae $ h.symm.le)
lemma lintegral_congr {f g : α → ℝ≥0∞} (h : ∀ a, f a = g a) :
(∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) :=
by simp only [h]
lemma set_lintegral_congr {f : α → ℝ≥0∞} {s t : set α} (h : s =ᵐ[μ] t) :
∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ :=
by rw [measure.restrict_congr_set h]
lemma set_lintegral_congr_fun {f g : α → ℝ≥0∞} {s : set α} (hs : measurable_set s)
(hfg : ∀ᵐ x ∂μ, x ∈ s → f x = g x) :
∫⁻ x in s, f x ∂μ = ∫⁻ x in s, g x ∂μ :=
by { rw lintegral_congr_ae, rw eventually_eq, rwa ae_restrict_iff' hs, }
/-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence.
See `lintegral_supr_directed` for a more general form. -/
theorem lintegral_supr
{f : ℕ → α → ℝ≥0∞} (hf : ∀n, measurable (f n)) (h_mono : monotone f) :
(∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) :=
begin
set c : ℝ≥0 → ℝ≥0∞ := coe,
set F := λ a:α, ⨆n, f n a,
have hF : measurable F := measurable_supr hf,
refine le_antisymm _ (supr_lintegral_le _),
rw [lintegral_eq_nnreal],
refine supr_le (assume s, supr_le (assume hsf, _)),
refine ennreal.le_of_forall_lt_one_mul_le (assume a ha, _),
rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩,
have ha : r < 1 := ennreal.coe_lt_coe.1 ha,
let rs := s.map (λa, r * a),
have eq_rs : (const α r : α →ₛ ℝ≥0∞) * map c s = rs.map c,
{ ext1 a, exact ennreal.coe_mul.symm },
have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}),
{ assume p,
rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]},
refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _),
by_cases p_eq : p = 0, { simp [p_eq] },
simp at hx, subst hx,
have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] },
have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] },
have : (rs.map c) x < ⨆ (n : ℕ), f n x,
{ refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x),
suffices : r * s x < 1 * s x, simpa [rs],
exact mul_lt_mul_of_pos_right ha (pos_iff_ne_zero.2 this) },
rcases lt_supr_iff.1 this with ⟨i, hi⟩,
exact mem_Union.2 ⟨i, le_of_lt hi⟩ },
have mono : ∀r:ℝ≥0∞, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}),
{ assume r i j h,
refine inter_subset_inter (subset.refl _) _,
assume x hx, exact le_trans hx (h_mono h x) },
have h_meas : ∀n, measurable_set {a : α | ⇑(map c rs) a ≤ f n a} :=
assume n, measurable_set_le (simple_func.measurable _) (hf n),
calc (r:ℝ≥0∞) * (s.map c).lintegral μ = ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r}) :
by rw [← const_mul_lintegral, eq_rs, simple_func.lintegral]
... = ∑ r in (rs.map c).range, r * μ (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) :
by simp only [(eq _).symm]
... = ∑ r in (rs.map c).range, (⨆n, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) :
finset.sum_congr rfl $ assume x hx,
begin
rw [measure_Union_eq_supr (directed_of_sup $ mono x), ennreal.mul_supr],
end
... = ⨆n, ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) :
begin
rw [ennreal.finset_sum_supr_nat],
assume p i j h,
exact mul_le_mul_left' (measure_mono $ mono p h) _
end
... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).lintegral μ) :
begin
refine supr_mono (λ n, _),
rw [restrict_lintegral _ (h_meas n)],
{ refine le_of_eq (finset.sum_congr rfl $ assume r hr, _),
congr' 2 with a,
refine and_congr_right _,
simp {contextual := tt} }
end
... ≤ (⨆n, ∫⁻ a, f n a ∂μ) :
begin
refine supr_mono (λ n, _),
rw [← simple_func.lintegral_eq_lintegral],
refine lintegral_mono (assume a, _),
simp only [map_apply] at h_meas,
simp only [coe_map, restrict_apply _ (h_meas _), (∘)],
exact indicator_apply_le id,
end
end
/-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence. Version with
ae_measurable functions. -/
theorem lintegral_supr' {f : ℕ → α → ℝ≥0∞} (hf : ∀n, ae_measurable (f n) μ)
(h_mono : ∀ᵐ x ∂μ, monotone (λ n, f n x)) :
(∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) :=
begin
simp_rw ←supr_apply,
let p : α → (ℕ → ℝ≥0∞) → Prop := λ x f', monotone f',
have hp : ∀ᵐ x ∂μ, p x (λ i, f i x), from h_mono,
have h_ae_seq_mono : monotone (ae_seq hf p),
{ intros n m hnm x,
by_cases hx : x ∈ ae_seq_set hf p,
{ exact ae_seq.prop_of_mem_ae_seq_set hf hx hnm, },
{ simp only [ae_seq, hx, if_false],
exact le_rfl, }, },
rw lintegral_congr_ae (ae_seq.supr hf hp).symm,
simp_rw supr_apply,
rw @lintegral_supr _ _ μ _ (ae_seq.measurable hf p) h_ae_seq_mono,
congr,
exact funext (λ n, lintegral_congr_ae (ae_seq.ae_seq_n_eq_fun_n_ae hf hp n)),
end
/-- Monotone convergence theorem expressed with limits -/
theorem lintegral_tendsto_of_tendsto_of_monotone {f : ℕ → α → ℝ≥0∞} {F : α → ℝ≥0∞}
(hf : ∀n, ae_measurable (f n) μ) (h_mono : ∀ᵐ x ∂μ, monotone (λ n, f n x))
(h_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 $ F x)) :
tendsto (λ n, ∫⁻ x, f n x ∂μ) at_top (𝓝 $ ∫⁻ x, F x ∂μ) :=
begin
have : monotone (λ n, ∫⁻ x, f n x ∂μ) :=
λ i j hij, lintegral_mono_ae (h_mono.mono $ λ x hx, hx hij),
suffices key : ∫⁻ x, F x ∂μ = ⨆n, ∫⁻ x, f n x ∂μ,
{ rw key,
exact tendsto_at_top_supr this },
rw ← lintegral_supr' hf h_mono,
refine lintegral_congr_ae _,
filter_upwards [h_mono, h_tendsto]
with _ hx_mono hx_tendsto using tendsto_nhds_unique hx_tendsto (tendsto_at_top_supr hx_mono),
end
lemma lintegral_eq_supr_eapprox_lintegral {f : α → ℝ≥0∞} (hf : measurable f) :
(∫⁻ a, f a ∂μ) = (⨆n, (eapprox f n).lintegral μ) :=
calc (∫⁻ a, f a ∂μ) = (∫⁻ a, ⨆n, (eapprox f n : α → ℝ≥0∞) a ∂μ) :
by congr; ext a; rw [supr_eapprox_apply f hf]
... = (⨆n, ∫⁻ a, (eapprox f n : α → ℝ≥0∞) a ∂μ) :
begin
rw [lintegral_supr],
{ measurability, },
{ assume i j h, exact (monotone_eapprox f h) }
end
... = (⨆n, (eapprox f n).lintegral μ) : by congr; ext n; rw [(eapprox f n).lintegral_eq_lintegral]
/-- If `f` has finite integral, then `∫⁻ x in s, f x ∂μ` is absolutely continuous in `s`: it tends
to zero as `μ s` tends to zero. This lemma states states this fact in terms of `ε` and `δ`. -/
lemma exists_pos_set_lintegral_lt_of_measure_lt {f : α → ℝ≥0∞} (h : ∫⁻ x, f x ∂μ ≠ ∞)
{ε : ℝ≥0∞} (hε : ε ≠ 0) :
∃ δ > 0, ∀ s, μ s < δ → ∫⁻ x in s, f x ∂μ < ε :=
begin
rcases exists_between hε.bot_lt with ⟨ε₂, hε₂0 : 0 < ε₂, hε₂ε⟩,
rcases exists_between hε₂0 with ⟨ε₁, hε₁0, hε₁₂⟩,
rcases exists_simple_func_forall_lintegral_sub_lt_of_pos h hε₁0.ne' with ⟨φ, hle, hφ⟩,
rcases φ.exists_forall_le with ⟨C, hC⟩,
use [(ε₂ - ε₁) / C, ennreal.div_pos_iff.2 ⟨(tsub_pos_iff_lt.2 hε₁₂).ne', ennreal.coe_ne_top⟩],
refine λ s hs, lt_of_le_of_lt _ hε₂ε,
simp only [lintegral_eq_nnreal, supr_le_iff],
intros ψ hψ,
calc (map coe ψ).lintegral (μ.restrict s)
≤ (map coe φ).lintegral (μ.restrict s) + (map coe (ψ - φ)).lintegral (μ.restrict s) :
begin
rw [← simple_func.add_lintegral, ← simple_func.map_add @ennreal.coe_add],
refine simple_func.lintegral_mono (λ x, _) le_rfl,
simp only [add_tsub_eq_max, le_max_right, coe_map, function.comp_app, simple_func.coe_add,
simple_func.coe_sub, pi.add_apply, pi.sub_apply, with_top.coe_max]
end
... ≤ (map coe φ).lintegral (μ.restrict s) + ε₁ :
begin
refine add_le_add le_rfl (le_trans _ (hφ _ hψ).le),
exact simple_func.lintegral_mono le_rfl measure.restrict_le_self
end
... ≤ (simple_func.const α (C : ℝ≥0∞)).lintegral (μ.restrict s) + ε₁ :
add_le_add (simple_func.lintegral_mono (λ x, coe_le_coe.2 (hC x)) le_rfl) le_rfl
... = C * μ s + ε₁ : by simp only [←simple_func.lintegral_eq_lintegral, coe_const,
lintegral_const, measure.restrict_apply, measurable_set.univ, univ_inter]
... ≤ C * ((ε₂ - ε₁) / C) + ε₁ :
add_le_add_right (ennreal.mul_le_mul le_rfl hs.le) _
... ≤ (ε₂ - ε₁) + ε₁ : add_le_add mul_div_le le_rfl
... = ε₂ : tsub_add_cancel_of_le hε₁₂.le,
end
/-- If `f` has finite integral, then `∫⁻ x in s, f x ∂μ` is absolutely continuous in `s`: it tends
to zero as `μ s` tends to zero. -/
lemma tendsto_set_lintegral_zero {ι} {f : α → ℝ≥0∞} (h : ∫⁻ x, f x ∂μ ≠ ∞)
{l : filter ι} {s : ι → set α} (hl : tendsto (μ ∘ s) l (𝓝 0)) :
tendsto (λ i, ∫⁻ x in s i, f x ∂μ) l (𝓝 0) :=
begin
simp only [ennreal.nhds_zero, tendsto_infi, tendsto_principal, mem_Iio, ← pos_iff_ne_zero]
at hl ⊢,
intros ε ε0,
rcases exists_pos_set_lintegral_lt_of_measure_lt h ε0.ne' with ⟨δ, δ0, hδ⟩,
exact (hl δ δ0).mono (λ i, hδ _)
end
/-- The sum of the lower Lebesgue integrals of two functions is less than or equal to the integral
of their sum. The other inequality needs one of these functions to be (a.e.-)measurable. -/
lemma le_lintegral_add (f g : α → ℝ≥0∞) : ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ ≤ ∫⁻ a, f a + g a ∂μ :=
begin
dunfold lintegral,
refine ennreal.bsupr_add_bsupr_le' ⟨0, zero_le f⟩ ⟨0, zero_le g⟩ (λ f' hf' g' hg', _),
exact le_supr₂_of_le (f' + g') (add_le_add hf' hg') (add_lintegral _ _).ge
end
-- Use stronger lemmas `lintegral_add_left`/`lintegral_add_right` instead
lemma lintegral_add_aux {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) :
∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ :=
calc (∫⁻ a, f a + g a ∂μ) =
(∫⁻ a, (⨆n, (eapprox f n : α → ℝ≥0∞) a) + (⨆n, (eapprox g n : α → ℝ≥0∞) a) ∂μ) :
by simp only [supr_eapprox_apply, hf, hg]
... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ℝ≥0∞) a) ∂μ) :
begin
congr, funext a,
rw [ennreal.supr_add_supr_of_monotone], { refl },
{ assume i j h, exact monotone_eapprox _ h a },
{ assume i j h, exact monotone_eapprox _ h a },
end
... = (⨆n, (eapprox f n).lintegral μ + (eapprox g n).lintegral μ) :
begin
rw [lintegral_supr],
{ congr,
funext n, rw [← simple_func.add_lintegral, ← simple_func.lintegral_eq_lintegral],
refl },
{ measurability, },
{ assume i j h a, exact add_le_add (monotone_eapprox _ h _) (monotone_eapprox _ h _) }
end
... = (⨆n, (eapprox f n).lintegral μ) + (⨆n, (eapprox g n).lintegral μ) :
by refine (ennreal.supr_add_supr_of_monotone _ _).symm;
{ assume i j h, exact simple_func.lintegral_mono (monotone_eapprox _ h) (le_refl μ) }
... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) :
by rw [lintegral_eq_supr_eapprox_lintegral hf, lintegral_eq_supr_eapprox_lintegral hg]
/-- If `f g : α → ℝ≥0∞` are two functions and one of them is (a.e.) measurable, then the Lebesgue
integral of `f + g` equals the sum of integrals. This lemma assumes that `f` is integrable, see also
`measure_theory.lintegral_add_right` and primed versions of these lemmas. -/
@[simp] lemma lintegral_add_left {f : α → ℝ≥0∞} (hf : measurable f) (g : α → ℝ≥0∞) :
∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ :=
begin
refine le_antisymm _ (le_lintegral_add _ _),
rcases exists_measurable_le_lintegral_eq μ (λ a, f a + g a) with ⟨φ, hφm, hφ_le, hφ_eq⟩,
calc ∫⁻ a, f a + g a ∂μ = ∫⁻ a, φ a ∂μ : hφ_eq
... ≤ ∫⁻ a, f a + (φ a - f a) ∂μ : lintegral_mono (λ a, le_add_tsub)
... = ∫⁻ a, f a ∂μ + ∫⁻ a, φ a - f a ∂μ : lintegral_add_aux hf (hφm.sub hf)
... ≤ ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ :
add_le_add_left (lintegral_mono $ λ a, tsub_le_iff_left.2 $ hφ_le a) _
end
lemma lintegral_add_left' {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (g : α → ℝ≥0∞) :
∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ :=
by rw [lintegral_congr_ae hf.ae_eq_mk, ← lintegral_add_left hf.measurable_mk,
lintegral_congr_ae (hf.ae_eq_mk.add (ae_eq_refl g))]
lemma lintegral_add_right' (f : α → ℝ≥0∞) {g : α → ℝ≥0∞} (hg : ae_measurable g μ) :
∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ :=
by simpa only [add_comm] using lintegral_add_left' hg f
/-- If `f g : α → ℝ≥0∞` are two functions and one of them is (a.e.) measurable, then the Lebesgue
integral of `f + g` equals the sum of integrals. This lemma assumes that `g` is integrable, see also
`measure_theory.lintegral_add_left` and primed versions of these lemmas. -/
@[simp] lemma lintegral_add_right (f : α → ℝ≥0∞) {g : α → ℝ≥0∞} (hg : measurable g) :
∫⁻ a, f a + g a ∂μ = ∫⁻ a, f a ∂μ + ∫⁻ a, g a ∂μ :=
lintegral_add_right' f hg.ae_measurable
@[simp] lemma lintegral_smul_measure (c : ℝ≥0∞) (f : α → ℝ≥0∞) :
∫⁻ a, f a ∂ (c • μ) = c * ∫⁻ a, f a ∂μ :=
by simp only [lintegral, supr_subtype', simple_func.lintegral_smul, ennreal.mul_supr, smul_eq_mul]
@[simp] lemma lintegral_sum_measure {m : measurable_space α} {ι} (f : α → ℝ≥0∞)
(μ : ι → measure α) :
∫⁻ a, f a ∂(measure.sum μ) = ∑' i, ∫⁻ a, f a ∂(μ i) :=
begin
simp only [lintegral, supr_subtype', simple_func.lintegral_sum, ennreal.tsum_eq_supr_sum],
rw [supr_comm],
congr, funext s,
induction s using finset.induction_on with i s hi hs, { apply bot_unique, simp },
simp only [finset.sum_insert hi, ← hs],
refine (ennreal.supr_add_supr _).symm,
intros φ ψ,
exact ⟨⟨φ ⊔ ψ, λ x, sup_le (φ.2 x) (ψ.2 x)⟩,
add_le_add (simple_func.lintegral_mono le_sup_left le_rfl)
(finset.sum_le_sum $ λ j hj, simple_func.lintegral_mono le_sup_right le_rfl)⟩
end
theorem has_sum_lintegral_measure {ι} {m : measurable_space α} (f : α → ℝ≥0∞) (μ : ι → measure α) :
has_sum (λ i, ∫⁻ a, f a ∂(μ i)) (∫⁻ a, f a ∂(measure.sum μ)) :=
(lintegral_sum_measure f μ).symm ▸ ennreal.summable.has_sum
@[simp] lemma lintegral_add_measure {m : measurable_space α} (f : α → ℝ≥0∞) (μ ν : measure α) :
∫⁻ a, f a ∂ (μ + ν) = ∫⁻ a, f a ∂μ + ∫⁻ a, f a ∂ν :=
by simpa [tsum_fintype] using lintegral_sum_measure f (λ b, cond b μ ν)
@[simp] lemma lintegral_finset_sum_measure {ι} {m : measurable_space α} (s : finset ι)
(f : α → ℝ≥0∞) (μ : ι → measure α) :
∫⁻ a, f a ∂(∑ i in s, μ i) = ∑ i in s, ∫⁻ a, f a ∂μ i :=
by { rw [← measure.sum_coe_finset, lintegral_sum_measure, ← finset.tsum_subtype'], refl }
@[simp] lemma lintegral_zero_measure {m : measurable_space α} (f : α → ℝ≥0∞) :
∫⁻ a, f a ∂(0 : measure α) = 0 :=
bot_unique $ by simp [lintegral]
lemma set_lintegral_empty (f : α → ℝ≥0∞) : ∫⁻ x in ∅, f x ∂μ = 0 :=
by rw [measure.restrict_empty, lintegral_zero_measure]
lemma set_lintegral_univ (f : α → ℝ≥0∞) : ∫⁻ x in univ, f x ∂μ = ∫⁻ x, f x ∂μ :=
by rw measure.restrict_univ
lemma set_lintegral_measure_zero (s : set α) (f : α → ℝ≥0∞) (hs' : μ s = 0) :
∫⁻ x in s, f x ∂μ = 0 :=
begin
convert lintegral_zero_measure _,
exact measure.restrict_eq_zero.2 hs',
end
lemma lintegral_finset_sum' (s : finset β) {f : β → α → ℝ≥0∞}
(hf : ∀ b ∈ s, ae_measurable (f b) μ) :
(∫⁻ a, ∑ b in s, f b a ∂μ) = ∑ b in s, ∫⁻ a, f b a ∂μ :=
begin
induction s using finset.induction_on with a s has ih,
{ simp },
{ simp only [finset.sum_insert has],
rw [finset.forall_mem_insert] at hf,
rw [lintegral_add_left' hf.1, ih hf.2] }
end
lemma lintegral_finset_sum (s : finset β) {f : β → α → ℝ≥0∞} (hf : ∀ b ∈ s, measurable (f b)) :
(∫⁻ a, ∑ b in s, f b a ∂μ) = ∑ b in s, ∫⁻ a, f b a ∂μ :=
lintegral_finset_sum' s (λ b hb, (hf b hb).ae_measurable)
@[simp] lemma lintegral_const_mul (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : measurable f) :
(∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) :=
calc (∫⁻ a, r * f a ∂μ) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a) ∂μ) :
by { congr, funext a, rw [← supr_eapprox_apply f hf, ennreal.mul_supr], refl }
... = (⨆n, r * (eapprox f n).lintegral μ) :
begin
rw [lintegral_supr],
{ congr, funext n,
rw [← simple_func.const_mul_lintegral, ← simple_func.lintegral_eq_lintegral] },
{ assume n, exact simple_func.measurable _ },
{ assume i j h a, exact mul_le_mul_left' (monotone_eapprox _ h _) _ }
end
... = r * (∫⁻ a, f a ∂μ) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_lintegral hf]
lemma lintegral_const_mul'' (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) :
(∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) :=
begin
have A : ∫⁻ a, f a ∂μ = ∫⁻ a, hf.mk f a ∂μ := lintegral_congr_ae hf.ae_eq_mk,
have B : ∫⁻ a, r * f a ∂μ = ∫⁻ a, r * hf.mk f a ∂μ :=
lintegral_congr_ae (eventually_eq.fun_comp hf.ae_eq_mk _),
rw [A, B, lintegral_const_mul _ hf.measurable_mk],
end
lemma lintegral_const_mul_le (r : ℝ≥0∞) (f : α → ℝ≥0∞) :
r * (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, r * f a ∂μ) :=
begin
rw [lintegral, ennreal.mul_supr],
refine supr_le (λs, _),
rw [ennreal.mul_supr],
simp only [supr_le_iff],
assume hs,
rw [← simple_func.const_mul_lintegral, lintegral],
refine le_supr_of_le (const α r * s) (le_supr_of_le (λx, _) le_rfl),
exact mul_le_mul_left' (hs x) _
end
lemma lintegral_const_mul' (r : ℝ≥0∞) (f : α → ℝ≥0∞) (hr : r ≠ ∞) :
(∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) :=
begin
by_cases h : r = 0,
{ simp [h] },
apply le_antisymm _ (lintegral_const_mul_le r f),
have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr,
have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv },
have := lintegral_const_mul_le (r⁻¹) (λx, r * f x),
simp [(mul_assoc _ _ _).symm, rinv'] at this,
simpa [(mul_assoc _ _ _).symm, rinv]
using mul_le_mul_left' this r
end
lemma lintegral_mul_const (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : measurable f) :
∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r :=
by simp_rw [mul_comm, lintegral_const_mul r hf]
lemma lintegral_mul_const'' (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) :
∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r :=
by simp_rw [mul_comm, lintegral_const_mul'' r hf]
lemma lintegral_mul_const_le (r : ℝ≥0∞) (f : α → ℝ≥0∞) :
∫⁻ a, f a ∂μ * r ≤ ∫⁻ a, f a * r ∂μ :=
by simp_rw [mul_comm, lintegral_const_mul_le r f]
lemma lintegral_mul_const' (r : ℝ≥0∞) (f : α → ℝ≥0∞) (hr : r ≠ ∞):
∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r :=
by simp_rw [mul_comm, lintegral_const_mul' r f hr]
/- A double integral of a product where each factor contains only one variable
is a product of integrals -/
lemma lintegral_lintegral_mul {β} [measurable_space β] {ν : measure β}
{f : α → ℝ≥0∞} {g : β → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g ν) :
∫⁻ x, ∫⁻ y, f x * g y ∂ν ∂μ = ∫⁻ x, f x ∂μ * ∫⁻ y, g y ∂ν :=
by simp [lintegral_const_mul'' _ hg, lintegral_mul_const'' _ hf]
-- TODO: Need a better way of rewriting inside of a integral
lemma lintegral_rw₁ {f f' : α → β} (h : f =ᵐ[μ] f') (g : β → ℝ≥0∞) :
(∫⁻ a, g (f a) ∂μ) = (∫⁻ a, g (f' a) ∂μ) :=
lintegral_congr_ae $ h.mono $ λ a h, by rw h
-- TODO: Need a better way of rewriting inside of a integral
lemma lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : f₁ =ᵐ[μ] f₁')
(h₂ : f₂ =ᵐ[μ] f₂') (g : β → γ → ℝ≥0∞) :
(∫⁻ a, g (f₁ a) (f₂ a) ∂μ) = (∫⁻ a, g (f₁' a) (f₂' a) ∂μ) :=
lintegral_congr_ae $ h₁.mp $ h₂.mono $ λ _ h₂ h₁, by rw [h₁, h₂]
@[simp] lemma lintegral_indicator (f : α → ℝ≥0∞) {s : set α} (hs : measurable_set s) :
∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ :=
begin
simp only [lintegral, ← restrict_lintegral_eq_lintegral_restrict _ hs, supr_subtype'],
apply le_antisymm; refine supr_mono' (subtype.forall.2 $ λ φ hφ, _),
{ refine ⟨⟨φ, le_trans hφ (indicator_le_self _ _)⟩, _⟩,
refine simple_func.lintegral_mono (λ x, _) le_rfl,
by_cases hx : x ∈ s,
{ simp [hx, hs, le_refl] },
{ apply le_trans (hφ x),
simp [hx, hs, le_refl] } },
{ refine ⟨⟨φ.restrict s, λ x, _⟩, le_rfl⟩,
simp [hφ x, hs, indicator_le_indicator] }
end
lemma lintegral_indicator₀ (f : α → ℝ≥0∞) {s : set α} (hs : null_measurable_set s μ) :
∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ :=
by rw [← lintegral_congr_ae (indicator_ae_eq_of_ae_eq_set hs.to_measurable_ae_eq),
lintegral_indicator _ (measurable_set_to_measurable _ _),
measure.restrict_congr_set hs.to_measurable_ae_eq]
lemma set_lintegral_eq_const {f : α → ℝ≥0∞} (hf : measurable f) (r : ℝ≥0∞) :
∫⁻ x in {x | f x = r}, f x ∂μ = r * μ {x | f x = r} :=
begin
have : ∀ᵐ x ∂μ, x ∈ {x | f x = r} → f x = r := ae_of_all μ (λ _ hx, hx),
rw [set_lintegral_congr_fun _ this],
dsimp,
rw [lintegral_const, measure.restrict_apply measurable_set.univ, set.univ_inter],
exact hf (measurable_set_singleton r)
end
/-- A version of **Markov's inequality** for two functions. It doesn't follow from the standard
Markov's inequality because we only assume measurability of `g`, not `f`. -/
lemma lintegral_add_mul_meas_add_le_le_lintegral {f g : α → ℝ≥0∞} (hle : f ≤ᵐ[μ] g)
(hg : ae_measurable g μ) (ε : ℝ≥0∞) :
∫⁻ a, f a ∂μ + ε * μ {x | f x + ε ≤ g x} ≤ ∫⁻ a, g a ∂μ :=
begin
rcases exists_measurable_le_lintegral_eq μ f with ⟨φ, hφm, hφ_le, hφ_eq⟩,
calc ∫⁻ x, f x ∂μ + ε * μ {x | f x + ε ≤ g x} = ∫⁻ x, φ x ∂μ + ε * μ {x | f x + ε ≤ g x} :
by rw [hφ_eq]
... ≤ ∫⁻ x, φ x ∂μ + ε * μ {x | φ x + ε ≤ g x} :
add_le_add_left (mul_le_mul_left'
(measure_mono $ λ x, (add_le_add_right (hφ_le _) _).trans) _) _
... = ∫⁻ x, φ x + indicator {x | φ x + ε ≤ g x} (λ _, ε) x ∂μ :
begin
rw [lintegral_add_left hφm, lintegral_indicator₀, set_lintegral_const],
exact measurable_set_le (hφm.null_measurable.measurable'.add_const _) hg.null_measurable
end
... ≤ ∫⁻ x, g x ∂μ : lintegral_mono_ae (hle.mono $ λ x hx₁, _),
simp only [indicator_apply], split_ifs with hx₂,
exacts [hx₂, (add_zero _).trans_le $ (hφ_le x).trans hx₁]
end
/-- **Markov's inequality** also known as **Chebyshev's first inequality**. -/
lemma mul_meas_ge_le_lintegral₀ {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (ε : ℝ≥0∞) :
ε * μ {x | ε ≤ f x} ≤ ∫⁻ a, f a ∂μ :=
by simpa only [lintegral_zero, zero_add]
using lintegral_add_mul_meas_add_le_le_lintegral (ae_of_all _ $ λ x, zero_le (f x)) hf ε
/-- **Markov's inequality** also known as **Chebyshev's first inequality**. For a version assuming
`ae_measurable`, see `mul_meas_ge_le_lintegral₀`. -/
lemma mul_meas_ge_le_lintegral {f : α → ℝ≥0∞} (hf : measurable f) (ε : ℝ≥0∞) :
ε * μ {x | ε ≤ f x} ≤ ∫⁻ a, f a ∂μ :=
mul_meas_ge_le_lintegral₀ hf.ae_measurable ε
lemma lintegral_eq_top_of_measure_eq_top_pos {f : α → ℝ≥0∞} (hf : ae_measurable f μ)
(hμf : 0 < μ {x | f x = ∞}) : ∫⁻ x, f x ∂μ = ∞ :=
eq_top_iff.mpr $
calc ∞ = ∞ * μ {x | ∞ ≤ f x} : by simp [mul_eq_top, hμf.ne.symm]
... ≤ ∫⁻ x, f x ∂μ : mul_meas_ge_le_lintegral₀ hf ∞
/-- **Markov's inequality** also known as **Chebyshev's first inequality**. -/
lemma meas_ge_le_lintegral_div {f : α → ℝ≥0∞} (hf : ae_measurable f μ) {ε : ℝ≥0∞}
(hε : ε ≠ 0) (hε' : ε ≠ ∞) :
μ {x | ε ≤ f x} ≤ (∫⁻ a, f a ∂μ) / ε :=
(ennreal.le_div_iff_mul_le (or.inl hε) (or.inl hε')).2 $
by { rw [mul_comm], exact mul_meas_ge_le_lintegral₀ hf ε }
lemma ae_eq_of_ae_le_of_lintegral_le {f g : α → ℝ≥0∞} (hfg : f ≤ᵐ[μ] g)
(hf : ∫⁻ x, f x ∂μ ≠ ∞) (hg : ae_measurable g μ) (hgf : ∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ) :
f =ᵐ[μ] g :=
begin
have : ∀ n : ℕ, ∀ᵐ x ∂μ, g x < f x + n⁻¹,
{ intro n,
simp only [ae_iff, not_lt],
have : ∫⁻ x, f x ∂μ + (↑n)⁻¹ * μ {x : α | f x + n⁻¹ ≤ g x} ≤ ∫⁻ x, f x ∂μ,
from (lintegral_add_mul_meas_add_le_le_lintegral hfg hg n⁻¹).trans hgf,
rw [(ennreal.cancel_of_ne hf).add_le_iff_nonpos_right, nonpos_iff_eq_zero, mul_eq_zero] at this,
exact this.resolve_left (ennreal.inv_ne_zero.2 (ennreal.nat_ne_top _)) },
refine hfg.mp ((ae_all_iff.2 this).mono (λ x hlt hle, hle.antisymm _)),
suffices : tendsto (λ n : ℕ, f x + n⁻¹) at_top (𝓝 (f x)),
from ge_of_tendsto' this (λ i, (hlt i).le),
simpa only [inv_top, add_zero]
using tendsto_const_nhds.add (ennreal.tendsto_inv_iff.2 ennreal.tendsto_nat_nhds_top)
end
@[simp] lemma lintegral_eq_zero_iff' {f : α → ℝ≥0∞} (hf : ae_measurable f μ) :
∫⁻ a, f a ∂μ = 0 ↔ f =ᵐ[μ] 0 :=
have ∫⁻ a : α, 0 ∂μ ≠ ∞, by simpa only [lintegral_zero] using zero_ne_top,
⟨λ h, (ae_eq_of_ae_le_of_lintegral_le (ae_of_all _ $ zero_le f) this hf
(h.trans lintegral_zero.symm).le).symm, λ h, (lintegral_congr_ae h).trans lintegral_zero⟩
@[simp] lemma lintegral_eq_zero_iff {f : α → ℝ≥0∞} (hf : measurable f) :
∫⁻ a, f a ∂μ = 0 ↔ f =ᵐ[μ] 0 :=
lintegral_eq_zero_iff' hf.ae_measurable
lemma lintegral_pos_iff_support {f : α → ℝ≥0∞} (hf : measurable f) :
0 < ∫⁻ a, f a ∂μ ↔ 0 < μ (function.support f) :=
by simp [pos_iff_ne_zero, hf, filter.eventually_eq, ae_iff, function.support]
/-- Weaker version of the monotone convergence theorem-/
lemma lintegral_supr_ae {f : ℕ → α → ℝ≥0∞} (hf : ∀n, measurable (f n))
(h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f n.succ a) :
(∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) :=
let ⟨s, hs⟩ := exists_measurable_superset_of_null
(ae_iff.1 (ae_all_iff.2 h_mono)) in
let g := λ n a, if a ∈ s then 0 else f n a in
have g_eq_f : ∀ᵐ a ∂μ, ∀n, g n a = f n a,
from (measure_zero_iff_ae_nmem.1 hs.2.2).mono (assume a ha n, if_neg ha),
calc
∫⁻ a, ⨆n, f n a ∂μ = ∫⁻ a, ⨆n, g n a ∂μ :
lintegral_congr_ae $ g_eq_f.mono $ λ a ha, by simp only [ha]
... = ⨆n, (∫⁻ a, g n a ∂μ) :
lintegral_supr
(assume n, measurable_const.piecewise hs.2.1 (hf n))
(monotone_nat_of_le_succ $ assume n a, classical.by_cases
(assume h : a ∈ s, by simp [g, if_pos h])
(assume h : a ∉ s,
begin
simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h,
simp only [not_not, mem_set_of_eq] at this, exact this n
end))
... = ⨆n, (∫⁻ a, f n a ∂μ) :
by simp only [lintegral_congr_ae (g_eq_f.mono $ λ a ha, ha _)]
lemma lintegral_sub {f g : α → ℝ≥0∞} (hg : measurable g)
(hg_fin : ∫⁻ a, g a ∂μ ≠ ∞) (h_le : g ≤ᵐ[μ] f) :
∫⁻ a, f a - g a ∂μ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ :=
begin
refine ennreal.eq_sub_of_add_eq hg_fin _,
rw [← lintegral_add_right _ hg],
exact lintegral_congr_ae (h_le.mono $ λ x hx, tsub_add_cancel_of_le hx)
end
lemma lintegral_sub_le (f g : α → ℝ≥0∞) (hf : measurable f) :
∫⁻ x, g x ∂μ - ∫⁻ x, f x ∂μ ≤ ∫⁻ x, g x - f x ∂μ :=
begin
rw tsub_le_iff_right,
by_cases hfi : ∫⁻ x, f x ∂μ = ∞,
{ rw [hfi, ennreal.add_top],
exact le_top },
{ rw [← lintegral_add_right _ hf],
exact lintegral_mono (λ x, le_tsub_add) }
end
lemma lintegral_strict_mono_of_ae_le_of_frequently_ae_lt {f g : α → ℝ≥0∞} (hg : ae_measurable g μ)
(hfi : ∫⁻ x, f x ∂μ ≠ ∞) (h_le : f ≤ᵐ[μ] g) (h : ∃ᵐ x ∂μ, f x ≠ g x) :
∫⁻ x, f x ∂μ < ∫⁻ x, g x ∂μ :=
begin
contrapose! h,
simp only [not_frequently, ne.def, not_not],
exact ae_eq_of_ae_le_of_lintegral_le h_le hfi hg h
end
lemma lintegral_strict_mono_of_ae_le_of_ae_lt_on {f g : α → ℝ≥0∞}
(hg : ae_measurable g μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) (h_le : f ≤ᵐ[μ] g)
{s : set α} (hμs : μ s ≠ 0) (h : ∀ᵐ x ∂μ, x ∈ s → f x < g x) :
∫⁻ x, f x ∂μ < ∫⁻ x, g x ∂μ :=
lintegral_strict_mono_of_ae_le_of_frequently_ae_lt hg hfi h_le $
((frequently_ae_mem_iff.2 hμs).and_eventually h).mono $ λ x hx, (hx.2 hx.1).ne
lemma lintegral_strict_mono {f g : α → ℝ≥0∞} (hμ : μ ≠ 0)
(hg : ae_measurable g μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) (h : ∀ᵐ x ∂μ, f x < g x) :
∫⁻ x, f x ∂μ < ∫⁻ x, g x ∂μ :=
begin
rw [ne.def, ← measure.measure_univ_eq_zero] at hμ,
refine lintegral_strict_mono_of_ae_le_of_ae_lt_on hg hfi (ae_le_of_ae_lt h) hμ _,
simpa using h,
end
lemma set_lintegral_strict_mono {f g : α → ℝ≥0∞} {s : set α}
(hsm : measurable_set s) (hs : μ s ≠ 0) (hg : measurable g)
(hfi : ∫⁻ x in s, f x ∂μ ≠ ∞) (h : ∀ᵐ x ∂μ, x ∈ s → f x < g x) :
∫⁻ x in s, f x ∂μ < ∫⁻ x in s, g x ∂μ :=
lintegral_strict_mono (by simp [hs]) hg.ae_measurable hfi ((ae_restrict_iff' hsm).mpr h)
/-- Monotone convergence theorem for nonincreasing sequences of functions -/
lemma lintegral_infi_ae
{f : ℕ → α → ℝ≥0∞} (h_meas : ∀n, measurable (f n))
(h_mono : ∀n:ℕ, f n.succ ≤ᵐ[μ] f n) (h_fin : ∫⁻ a, f 0 a ∂μ ≠ ∞) :
∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ :=
have fn_le_f0 : ∫⁻ a, ⨅n, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ, from
lintegral_mono (assume a, infi_le_of_le 0 le_rfl),
have fn_le_f0' : (⨅n, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ, from infi_le_of_le 0 le_rfl,
(ennreal.sub_right_inj h_fin fn_le_f0 fn_le_f0').1 $
show ∫⁻ a, f 0 a ∂μ - ∫⁻ a, ⨅n, f n a ∂μ = ∫⁻ a, f 0 a ∂μ - (⨅n, ∫⁻ a, f n a ∂μ), from
calc
∫⁻ a, f 0 a ∂μ - (∫⁻ a, ⨅n, f n a ∂μ) = ∫⁻ a, f 0 a - ⨅n, f n a ∂μ:
(lintegral_sub (measurable_infi h_meas)
(ne_top_of_le_ne_top h_fin $ lintegral_mono (assume a, infi_le _ _))
(ae_of_all _ $ assume a, infi_le _ _)).symm
... = ∫⁻ a, ⨆n, f 0 a - f n a ∂μ : congr rfl (funext (assume a, ennreal.sub_infi))
... = ⨆n, ∫⁻ a, f 0 a - f n a ∂μ :
lintegral_supr_ae
(assume n, (h_meas 0).sub (h_meas n))
(assume n, (h_mono n).mono $ assume a ha, tsub_le_tsub le_rfl ha)
... = ⨆n, ∫⁻ a, f 0 a ∂μ - ∫⁻ a, f n a ∂μ :
have h_mono : ∀ᵐ a ∂μ, ∀n:ℕ, f n.succ a ≤ f n a := ae_all_iff.2 h_mono,
have h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f 0 a := assume n, h_mono.mono $ assume a h,
begin
induction n with n ih,
{exact le_rfl}, {exact le_trans (h n) ih}
end,
congr_arg supr $ funext $ assume n, lintegral_sub (h_meas _)
(ne_top_of_le_ne_top h_fin $ lintegral_mono_ae $ h_mono n) (h_mono n)
... = ∫⁻ a, f 0 a ∂μ - ⨅n, ∫⁻ a, f n a ∂μ : ennreal.sub_infi.symm
/-- Monotone convergence theorem for nonincreasing sequences of functions -/
lemma lintegral_infi
{f : ℕ → α → ℝ≥0∞} (h_meas : ∀n, measurable (f n))
(h_anti : antitone f) (h_fin : ∫⁻ a, f 0 a ∂μ ≠ ∞) :
∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ :=
lintegral_infi_ae h_meas (λ n, ae_of_all _ $ h_anti n.le_succ) h_fin
/-- Known as Fatou's lemma, version with `ae_measurable` functions -/
lemma lintegral_liminf_le' {f : ℕ → α → ℝ≥0∞} (h_meas : ∀n, ae_measurable (f n) μ) :
∫⁻ a, liminf at_top (λ n, f n a) ∂μ ≤ liminf at_top (λ n, ∫⁻ a, f n a ∂μ) :=
calc
∫⁻ a, liminf at_top (λ n, f n a) ∂μ = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a ∂μ :
by simp only [liminf_eq_supr_infi_of_nat]
... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a ∂μ :
lintegral_supr'
(assume n, ae_measurable_binfi _ (to_countable _) h_meas)
(ae_of_all μ (assume a n m hnm, infi_le_infi_of_subset $ λ i hi, le_trans hnm hi))
... ≤ ⨆n:ℕ, ⨅i≥n, ∫⁻ a, f i a ∂μ :
supr_mono $ λ n, le_infi₂_lintegral _
... = at_top.liminf (λ n, ∫⁻ a, f n a ∂μ) : filter.liminf_eq_supr_infi_of_nat.symm
/-- Known as Fatou's lemma -/
lemma lintegral_liminf_le {f : ℕ → α → ℝ≥0∞} (h_meas : ∀n, measurable (f n)) :
∫⁻ a, liminf at_top (λ n, f n a) ∂μ ≤ liminf at_top (λ n, ∫⁻ a, f n a ∂μ) :=
lintegral_liminf_le' (λ n, (h_meas n).ae_measurable)
lemma limsup_lintegral_le {f : ℕ → α → ℝ≥0∞} {g : α → ℝ≥0∞}
(hf_meas : ∀ n, measurable (f n)) (h_bound : ∀n, f n ≤ᵐ[μ] g) (h_fin : ∫⁻ a, g a ∂μ ≠ ∞) :
limsup at_top (λn, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, f n a) ∂μ :=
calc
limsup at_top (λn, ∫⁻ a, f n a ∂μ) = ⨅n:ℕ, ⨆i≥n, ∫⁻ a, f i a ∂μ :
limsup_eq_infi_supr_of_nat
... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a ∂μ :
infi_mono $ assume n, supr₂_lintegral_le _
... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a ∂μ :
begin
refine (lintegral_infi _ _ _).symm,
{ assume n, exact measurable_bsupr _ (to_countable _) hf_meas },
{ assume n m hnm a, exact (supr_le_supr_of_subset $ λ i hi, le_trans hnm hi) },
{ refine ne_top_of_le_ne_top h_fin (lintegral_mono_ae _),
refine (ae_all_iff.2 h_bound).mono (λ n hn, _),
exact supr_le (λ i, supr_le $ λ hi, hn i) }
end
... = ∫⁻ a, limsup at_top (λn, f n a) ∂μ :
by simp only [limsup_eq_infi_supr_of_nat]
/-- Dominated convergence theorem for nonnegative functions -/
lemma tendsto_lintegral_of_dominated_convergence
{F : ℕ → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞)
(hF_meas : ∀n, measurable (F n)) (h_bound : ∀n, F n ≤ᵐ[μ] bound)
(h_fin : ∫⁻ a, bound a ∂μ ≠ ∞)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) :=
tendsto_of_le_liminf_of_limsup_le
(calc ∫⁻ a, f a ∂μ = ∫⁻ a, liminf at_top (λ (n : ℕ), F n a) ∂μ :
lintegral_congr_ae $ h_lim.mono $ assume a h, h.liminf_eq.symm
... ≤ liminf at_top (λ n, ∫⁻ a, F n a ∂μ) : lintegral_liminf_le hF_meas)
(calc limsup at_top (λ (n : ℕ), ∫⁻ a, F n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, F n a) ∂μ :
limsup_lintegral_le hF_meas h_bound h_fin
... = ∫⁻ a, f a ∂μ : lintegral_congr_ae $ h_lim.mono $ λ a h, h.limsup_eq)
/-- Dominated convergence theorem for nonnegative functions which are just almost everywhere
measurable. -/
lemma tendsto_lintegral_of_dominated_convergence'
{F : ℕ → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞)
(hF_meas : ∀n, ae_measurable (F n) μ) (h_bound : ∀n, F n ≤ᵐ[μ] bound)
(h_fin : ∫⁻ a, bound a ∂μ ≠ ∞)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) :=
begin
have : ∀ n, ∫⁻ a, F n a ∂μ = ∫⁻ a, (hF_meas n).mk (F n) a ∂μ :=
λ n, lintegral_congr_ae (hF_meas n).ae_eq_mk,
simp_rw this,
apply tendsto_lintegral_of_dominated_convergence bound (λ n, (hF_meas n).measurable_mk) _ h_fin,
{ have : ∀ n, ∀ᵐ a ∂μ, (hF_meas n).mk (F n) a = F n a :=
λ n, (hF_meas n).ae_eq_mk.symm,
have : ∀ᵐ a ∂μ, ∀ n, (hF_meas n).mk (F n) a = F n a := ae_all_iff.mpr this,
filter_upwards [this, h_lim] with a H H',
simp_rw H,
exact H', },
{ assume n,
filter_upwards [h_bound n, (hF_meas n).ae_eq_mk] with a H H',
rwa H' at H, },
end
/-- Dominated convergence theorem for filters with a countable basis -/
lemma tendsto_lintegral_filter_of_dominated_convergence {ι} {l : filter ι}
[l.is_countably_generated]
{F : ι → α → ℝ≥0∞} {f : α → ℝ≥0∞} (bound : α → ℝ≥0∞)
(hF_meas : ∀ᶠ n in l, measurable (F n))
(h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, F n a ≤ bound a)
(h_fin : ∫⁻ a, bound a ∂μ ≠ ∞)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) :
tendsto (λn, ∫⁻ a, F n a ∂μ) l (𝓝 $ ∫⁻ a, f a ∂μ) :=
begin
rw tendsto_iff_seq_tendsto,
intros x xl,
have hxl, { rw tendsto_at_top' at xl, exact xl },
have h := inter_mem hF_meas h_bound,
replace h := hxl _ h,
rcases h with ⟨k, h⟩,
rw ← tendsto_add_at_top_iff_nat k,
refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _,
{ exact bound },
{ intro, refine (h _ _).1, exact nat.le_add_left _ _ },
{ intro, refine (h _ _).2, exact nat.le_add_left _ _ },
{ assumption },
{ refine h_lim.mono (λ a h_lim, _),
apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a),
{ assumption },
rw tendsto_add_at_top_iff_nat,
assumption }
end
section
open encodable
/-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/
theorem lintegral_supr_directed [encodable β] {f : β → α → ℝ≥0∞}
(hf : ∀b, measurable (f b)) (h_directed : directed (≤) f) :
∫⁻ a, ⨆b, f b a ∂μ = ⨆b, ∫⁻ a, f b a ∂μ :=
begin
casesI is_empty_or_nonempty β, { simp [supr_of_empty] },
inhabit β,
have : ∀a, (⨆ b, f b a) = (⨆ n, f (h_directed.sequence f n) a),
{ assume a,
refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _),
exact le_supr_of_le (encode b + 1) (h_directed.le_sequence b a) },
calc ∫⁻ a, ⨆ b, f b a ∂μ = ∫⁻ a, ⨆ n, f (h_directed.sequence f n) a ∂μ :
by simp only [this]
... = ⨆ n, ∫⁻ a, f (h_directed.sequence f n) a ∂μ :
lintegral_supr (assume n, hf _) h_directed.sequence_mono
... = ⨆ b, ∫⁻ a, f b a ∂μ :
begin
refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _),
{ exact le_supr (λb, ∫⁻ a, f b a ∂μ) _ },
{ exact le_supr_of_le (encode b + 1)
(lintegral_mono $ h_directed.le_sequence b) }
end
end
end
lemma lintegral_tsum [encodable β] {f : β → α → ℝ≥0∞} (hf : ∀i, measurable (f i)) :
∫⁻ a, ∑' i, f i a ∂μ = ∑' i, ∫⁻ a, f i a ∂μ :=
begin
simp only [ennreal.tsum_eq_supr_sum],
rw [lintegral_supr_directed],
{ simp [lintegral_finset_sum _ (λ i _, hf i)] },
{ assume b, exact finset.measurable_sum _ (λ i _, hf i) },
{ assume s t,
use [s ∪ t],
split,
exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _),
exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) }
end
open measure
lemma lintegral_Union₀ [encodable β] {s : β → set α} (hm : ∀ i, null_measurable_set (s i) μ)
(hd : pairwise (ae_disjoint μ on s)) (f : α → ℝ≥0∞) :
∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ :=
by simp only [measure.restrict_Union_ae hd hm, lintegral_sum_measure]
lemma lintegral_Union [encodable β] {s : β → set α} (hm : ∀ i, measurable_set (s i))
(hd : pairwise (disjoint on s)) (f : α → ℝ≥0∞) :
∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ :=
lintegral_Union₀ (λ i, (hm i).null_measurable_set) hd.ae_disjoint f
lemma lintegral_bUnion₀ {t : set β} {s : β → set α} (ht : t.countable)
(hm : ∀ i ∈ t, null_measurable_set (s i) μ)
(hd : t.pairwise (ae_disjoint μ on s)) (f : α → ℝ≥0∞) :
∫⁻ a in ⋃ i ∈ t, s i, f a ∂μ = ∑' i : t, ∫⁻ a in s i, f a ∂μ :=
begin
haveI := ht.to_encodable,
rw [bUnion_eq_Union, lintegral_Union₀ (set_coe.forall'.1 hm) (hd.subtype _ _)]
end
lemma lintegral_bUnion {t : set β} {s : β → set α} (ht : t.countable)
(hm : ∀ i ∈ t, measurable_set (s i)) (hd : t.pairwise_disjoint s) (f : α → ℝ≥0∞) :
∫⁻ a in ⋃ i ∈ t, s i, f a ∂μ = ∑' i : t, ∫⁻ a in s i, f a ∂μ :=
lintegral_bUnion₀ ht (λ i hi, (hm i hi).null_measurable_set) hd.ae_disjoint f
lemma lintegral_bUnion_finset₀ {s : finset β} {t : β → set α}
(hd : set.pairwise ↑s (ae_disjoint μ on t)) (hm : ∀ b ∈ s, null_measurable_set (t b) μ)
(f : α → ℝ≥0∞) :
∫⁻ a in ⋃ b ∈ s, t b, f a ∂μ = ∑ b in s, ∫⁻ a in t b, f a ∂μ :=
by simp only [← finset.mem_coe, lintegral_bUnion₀ s.countable_to_set hm hd, ← s.tsum_subtype']
lemma lintegral_bUnion_finset {s : finset β} {t : β → set α}
(hd : set.pairwise_disjoint ↑s t) (hm : ∀ b ∈ s, measurable_set (t b)) (f : α → ℝ≥0∞) :
∫⁻ a in ⋃ b ∈ s, t b, f a ∂μ = ∑ b in s, ∫⁻ a in t b, f a ∂μ :=
lintegral_bUnion_finset₀ hd.ae_disjoint (λ b hb, (hm b hb).null_measurable_set) f
lemma lintegral_Union_le [encodable β] (s : β → set α) (f : α → ℝ≥0∞) :
∫⁻ a in ⋃ i, s i, f a ∂μ ≤ ∑' i, ∫⁻ a in s i, f a ∂μ :=
begin
rw [← lintegral_sum_measure],
exact lintegral_mono' restrict_Union_le le_rfl
end
lemma lintegral_union {f : α → ℝ≥0∞} {A B : set α} (hB : measurable_set B) (hAB : disjoint A B) :
∫⁻ a in A ∪ B, f a ∂μ = ∫⁻ a in A, f a ∂μ + ∫⁻ a in B, f a ∂μ :=
by rw [restrict_union hAB hB, lintegral_add_measure]
lemma lintegral_inter_add_diff {B : set α} (f : α → ℝ≥0∞) (A : set α) (hB : measurable_set B) :
∫⁻ x in A ∩ B, f x ∂μ + ∫⁻ x in A \ B, f x ∂μ = ∫⁻ x in A, f x ∂μ :=
by rw [← lintegral_add_measure, restrict_inter_add_diff _ hB]
lemma lintegral_add_compl (f : α → ℝ≥0∞) {A : set α} (hA : measurable_set A) :
∫⁻ x in A, f x ∂μ + ∫⁻ x in Aᶜ, f x ∂μ = ∫⁻ x, f x ∂μ :=
by rw [← lintegral_add_measure, measure.restrict_add_restrict_compl hA]
lemma lintegral_max {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) :
∫⁻ x, max (f x) (g x) ∂μ = ∫⁻ x in {x | f x ≤ g x}, g x ∂μ + ∫⁻ x in {x | g x < f x}, f x ∂μ :=
begin
have hm : measurable_set {x | f x ≤ g x}, from measurable_set_le hf hg,
rw [← lintegral_add_compl (λ x, max (f x) (g x)) hm],
simp only [← compl_set_of, ← not_le],
refine congr_arg2 (+) (set_lintegral_congr_fun hm _) (set_lintegral_congr_fun hm.compl _),
exacts [ae_of_all _ (λ x, max_eq_right), ae_of_all _ (λ x hx, max_eq_left (not_le.1 hx).le)]
end
lemma set_lintegral_max {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) (s : set α) :
∫⁻ x in s, max (f x) (g x) ∂μ =
∫⁻ x in s ∩ {x | f x ≤ g x}, g x ∂μ + ∫⁻ x in s ∩ {x | g x < f x}, f x ∂μ :=
begin
rw [lintegral_max hf hg, restrict_restrict, restrict_restrict, inter_comm s, inter_comm s],
exacts [measurable_set_lt hg hf, measurable_set_le hf hg]
end
lemma lintegral_map {mβ : measurable_space β} {f : β → ℝ≥0∞} {g : α → β}
(hf : measurable f) (hg : measurable g) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ :=
begin
simp only [lintegral_eq_supr_eapprox_lintegral, hf, hf.comp hg],
congr' with n : 1,
convert simple_func.lintegral_map _ hg,
ext1 x, simp only [eapprox_comp hf hg, coe_comp]
end
lemma lintegral_map' {mβ : measurable_space β} {f : β → ℝ≥0∞} {g : α → β}
(hf : ae_measurable f (measure.map g μ)) (hg : ae_measurable g μ) :
∫⁻ a, f a ∂(measure.map g μ) = ∫⁻ a, f (g a) ∂μ :=
calc ∫⁻ a, f a ∂(measure.map g μ) = ∫⁻ a, hf.mk f a ∂(measure.map g μ) :
lintegral_congr_ae hf.ae_eq_mk
... = ∫⁻ a, hf.mk f a ∂(measure.map (hg.mk g) μ) :
by { congr' 1, exact measure.map_congr hg.ae_eq_mk }
... = ∫⁻ a, hf.mk f (hg.mk g a) ∂μ : lintegral_map hf.measurable_mk hg.measurable_mk
... = ∫⁻ a, hf.mk f (g a) ∂μ : lintegral_congr_ae $ hg.ae_eq_mk.symm.fun_comp _
... = ∫⁻ a, f (g a) ∂μ : lintegral_congr_ae (ae_eq_comp hg hf.ae_eq_mk.symm)
lemma lintegral_map_le {mβ : measurable_space β} (f : β → ℝ≥0∞) {g : α → β} (hg : measurable g) :
∫⁻ a, f a ∂(measure.map g μ) ≤ ∫⁻ a, f (g a) ∂μ :=
begin
rw [← supr_lintegral_measurable_le_eq_lintegral, ← supr_lintegral_measurable_le_eq_lintegral],
refine supr₂_le (λ i hi, supr_le $ λ h'i, _),
refine le_supr₂_of_le (i ∘ g) (hi.comp hg) _,
exact le_supr_of_le (λ x, h'i (g x)) (le_of_eq (lintegral_map hi hg))
end
lemma lintegral_comp [measurable_space β] {f : β → ℝ≥0∞} {g : α → β}
(hf : measurable f) (hg : measurable g) : lintegral μ (f ∘ g) = ∫⁻ a, f a ∂(map g μ) :=
(lintegral_map hf hg).symm
lemma set_lintegral_map [measurable_space β] {f : β → ℝ≥0∞} {g : α → β}
{s : set β} (hs : measurable_set s) (hf : measurable f) (hg : measurable g) :
∫⁻ y in s, f y ∂(map g μ) = ∫⁻ x in g ⁻¹' s, f (g x) ∂μ :=
by rw [restrict_map hg hs, lintegral_map hf hg]
/-- If `g : α → β` is a measurable embedding and `f : β → ℝ≥0∞` is any function (not necessarily
measurable), then `∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ`. Compare with `lintegral_map` wich
applies to any measurable `g : α → β` but requires that `f` is measurable as well. -/
lemma _root_.measurable_embedding.lintegral_map [measurable_space β] {g : α → β}
(hg : measurable_embedding g) (f : β → ℝ≥0∞) :
∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ :=
begin
rw [lintegral, lintegral],
refine le_antisymm (supr₂_le $ λ f₀ hf₀, _) (supr₂_le $ λ f₀ hf₀, _),
{ rw [simple_func.lintegral_map _ hg.measurable],
have : (f₀.comp g hg.measurable : α → ℝ≥0∞) ≤ f ∘ g, from λ x, hf₀ (g x),
exact le_supr_of_le (comp f₀ g hg.measurable) (le_supr _ this) },
{ rw [← f₀.extend_comp_eq hg (const _ 0), ← simple_func.lintegral_map,
← simple_func.lintegral_eq_lintegral, ← lintegral],
refine lintegral_mono_ae (hg.ae_map_iff.2 $ eventually_of_forall $ λ x, _),
exact (extend_apply _ _ _ _).trans_le (hf₀ _) }
end
/-- The `lintegral` transforms appropriately under a measurable equivalence `g : α ≃ᵐ β`.
(Compare `lintegral_map`, which applies to a wider class of functions `g : α → β`, but requires
measurability of the function being integrated.) -/
lemma lintegral_map_equiv [measurable_space β] (f : β → ℝ≥0∞) (g : α ≃ᵐ β) :
∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ :=
g.measurable_embedding.lintegral_map f
lemma measure_preserving.lintegral_comp {mb : measurable_space β} {ν : measure β} {g : α → β}
(hg : measure_preserving g μ ν) {f : β → ℝ≥0∞} (hf : measurable f) :
∫⁻ a, f (g a) ∂μ = ∫⁻ b, f b ∂ν :=
by rw [← hg.map_eq, lintegral_map hf hg.measurable]
lemma measure_preserving.lintegral_comp_emb {mb : measurable_space β} {ν : measure β} {g : α → β}
(hg : measure_preserving g μ ν) (hge : measurable_embedding g) (f : β → ℝ≥0∞) :
∫⁻ a, f (g a) ∂μ = ∫⁻ b, f b ∂ν :=
by rw [← hg.map_eq, hge.lintegral_map]
lemma measure_preserving.set_lintegral_comp_preimage {mb : measurable_space β} {ν : measure β}
{g : α → β} (hg : measure_preserving g μ ν) {s : set β} (hs : measurable_set s)
{f : β → ℝ≥0∞} (hf : measurable f) :
∫⁻ a in g ⁻¹' s, f (g a) ∂μ = ∫⁻ b in s, f b ∂ν :=
by rw [← hg.map_eq, set_lintegral_map hs hf hg.measurable]
lemma measure_preserving.set_lintegral_comp_preimage_emb {mb : measurable_space β} {ν : measure β}
{g : α → β} (hg : measure_preserving g μ ν) (hge : measurable_embedding g) (f : β → ℝ≥0∞)
(s : set β) :
∫⁻ a in g ⁻¹' s, f (g a) ∂μ = ∫⁻ b in s, f b ∂ν :=
by rw [← hg.map_eq, hge.restrict_map, hge.lintegral_map]
lemma measure_preserving.set_lintegral_comp_emb {mb : measurable_space β} {ν : measure β}
{g : α → β} (hg : measure_preserving g μ ν) (hge : measurable_embedding g) (f : β → ℝ≥0∞)
(s : set α) :
∫⁻ a in s, f (g a) ∂μ = ∫⁻ b in g '' s, f b ∂ν :=
by rw [← hg.set_lintegral_comp_preimage_emb hge, preimage_image_eq _ hge.injective]
section dirac_and_count
variable [measurable_space α]
lemma lintegral_dirac' (a : α) {f : α → ℝ≥0∞} (hf : measurable f) :
∫⁻ a, f a ∂(dirac a) = f a :=
by simp [lintegral_congr_ae (ae_eq_dirac' hf)]
lemma lintegral_dirac [measurable_singleton_class α] (a : α) (f : α → ℝ≥0∞) :
∫⁻ a, f a ∂(dirac a) = f a :=
by simp [lintegral_congr_ae (ae_eq_dirac f)]
lemma lintegral_count' {f : α → ℝ≥0∞} (hf : measurable f) :
∫⁻ a, f a ∂count = ∑' a, f a :=
begin
rw [count, lintegral_sum_measure],
congr,
exact funext (λ a, lintegral_dirac' a hf),
end
lemma lintegral_count [measurable_singleton_class α] (f : α → ℝ≥0∞) :
∫⁻ a, f a ∂count = ∑' a, f a :=
begin
rw [count, lintegral_sum_measure],
congr,
exact funext (λ a, lintegral_dirac a f),
end
end dirac_and_count
section countable
/-!
### Lebesgue integral over finite and countable types and sets
-/
lemma lintegral_encodable [encodable α] [measurable_singleton_class α] (f : α → ℝ≥0∞) :
∫⁻ a, f a ∂μ = ∑' a, f a * μ {a} :=
begin
conv_lhs { rw [← sum_smul_dirac μ, lintegral_sum_measure] },
congr' 1 with a : 1,
rw [lintegral_smul_measure, lintegral_dirac, mul_comm],
end
lemma lintegral_singleton' {f : α → ℝ≥0∞} (hf : measurable f) (a : α) :
∫⁻ x in {a}, f x ∂μ = f a * μ {a} :=
by simp only [restrict_singleton, lintegral_smul_measure, lintegral_dirac' _ hf, mul_comm]
lemma lintegral_singleton [measurable_singleton_class α] (f : α → ℝ≥0∞) (a : α) :
∫⁻ x in {a}, f x ∂μ = f a * μ {a} :=
by simp only [restrict_singleton, lintegral_smul_measure, lintegral_dirac, mul_comm]
lemma lintegral_countable [measurable_singleton_class α] (f : α → ℝ≥0∞) {s : set α}
(hs : s.countable) :
∫⁻ a in s, f a ∂μ = ∑' a : s, f a * μ {(a : α)} :=
calc ∫⁻ a in s, f a ∂μ = ∫⁻ a in ⋃ x ∈ s, {x}, f a ∂μ : by rw [bUnion_of_singleton]
... = ∑' a : s, ∫⁻ x in {a}, f x ∂μ :
lintegral_bUnion hs (λ _ _, measurable_set_singleton _) (pairwise_disjoint_fiber id s) _
... = ∑' a : s, f a * μ {(a : α)} : by simp only [lintegral_singleton]
lemma lintegral_insert [measurable_singleton_class α]
{a : α} {s : set α} (h : a ∉ s) (f : α → ℝ≥0∞) :
∫⁻ x in insert a s, f x ∂μ = f a * μ {a} + ∫⁻ x in s, f x ∂μ :=
begin
rw [← union_singleton, lintegral_union (measurable_set_singleton a), lintegral_singleton,
add_comm],
rwa disjoint_singleton_right
end
lemma lintegral_finset [measurable_singleton_class α] (s : finset α) (f : α → ℝ≥0∞) :
∫⁻ x in s, f x ∂μ = ∑ x in s, f x * μ {x} :=
by simp only [lintegral_countable _ s.countable_to_set, ← s.tsum_subtype']
lemma lintegral_fintype [measurable_singleton_class α] [fintype α] (f : α → ℝ≥0∞) :
∫⁻ x, f x ∂μ = ∑ x, f x * μ {x} :=
by rw [← lintegral_finset, finset.coe_univ, measure.restrict_univ]
lemma lintegral_unique [unique α] (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂μ = f default * μ univ :=
calc ∫⁻ x, f x ∂μ = ∫⁻ x, f default ∂μ : lintegral_congr $ unique.forall_iff.2 rfl
... = f default * μ univ : lintegral_const _
end countable
lemma ae_lt_top {f : α → ℝ≥0∞} (hf : measurable f) (h2f : ∫⁻ x, f x ∂μ ≠ ∞) :
∀ᵐ x ∂μ, f x < ∞ :=
begin
simp_rw [ae_iff, ennreal.not_lt_top], by_contra h, apply h2f.lt_top.not_le,
have : (f ⁻¹' {∞}).indicator ⊤ ≤ f,
{ intro x, by_cases hx : x ∈ f ⁻¹' {∞}; [simpa [hx], simp [hx]] },
convert lintegral_mono this,
rw [lintegral_indicator _ (hf (measurable_set_singleton ∞))], simp [ennreal.top_mul, preimage, h]
end
lemma ae_lt_top' {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (h2f : ∫⁻ x, f x ∂μ ≠ ∞) :
∀ᵐ x ∂μ, f x < ∞ :=
begin
have h2f_meas : ∫⁻ x, hf.mk f x ∂μ ≠ ∞, by rwa ← lintegral_congr_ae hf.ae_eq_mk,
exact (ae_lt_top hf.measurable_mk h2f_meas).mp (hf.ae_eq_mk.mono (λ x hx h, by rwa hx)),
end
lemma set_lintegral_lt_top_of_bdd_above
{s : set α} (hs : μ s ≠ ∞) {f : α → ℝ≥0} (hf : measurable f) (hbdd : bdd_above (f '' s)) :
∫⁻ x in s, f x ∂μ < ∞ :=
begin
obtain ⟨M, hM⟩ := hbdd,
rw mem_upper_bounds at hM,
refine lt_of_le_of_lt (set_lintegral_mono hf.coe_nnreal_ennreal
(@measurable_const _ _ _ _ ↑M) _) _,
{ simpa using hM },
{ rw lintegral_const,
refine ennreal.mul_lt_top ennreal.coe_lt_top.ne _,
simp [hs] }
end
lemma set_lintegral_lt_top_of_is_compact [topological_space α] [opens_measurable_space α]
{s : set α} (hs : μ s ≠ ∞) (hsc : is_compact s) {f : α → ℝ≥0} (hf : continuous f) :
∫⁻ x in s, f x ∂μ < ∞ :=
set_lintegral_lt_top_of_bdd_above hs hf.measurable (hsc.image hf).bdd_above
lemma _root_.is_finite_measure.lintegral_lt_top_of_bounded_to_ennreal {α : Type*}
[measurable_space α] (μ : measure α) [μ_fin : is_finite_measure μ]
{f : α → ℝ≥0∞} (f_bdd : ∃ c : ℝ≥0, ∀ x, f x ≤ c) : ∫⁻ x, f x ∂μ < ∞ :=
begin
cases f_bdd with c hc,
apply lt_of_le_of_lt (@lintegral_mono _ _ μ _ _ hc),
rw lintegral_const,
exact ennreal.mul_lt_top ennreal.coe_lt_top.ne μ_fin.measure_univ_lt_top.ne,
end
/-- Given a measure `μ : measure α` and a function `f : α → ℝ≥0∞`, `μ.with_density f` is the
measure such that for a measurable set `s` we have `μ.with_density f s = ∫⁻ a in s, f a ∂μ`. -/
def measure.with_density {m : measurable_space α} (μ : measure α) (f : α → ℝ≥0∞) : measure α :=
measure.of_measurable (λs hs, ∫⁻ a in s, f a ∂μ) (by simp) (λ s hs hd, lintegral_Union hs hd _)
@[simp] lemma with_density_apply (f : α → ℝ≥0∞) {s : set α} (hs : measurable_set s) :
μ.with_density f s = ∫⁻ a in s, f a ∂μ :=
measure.of_measurable_apply s hs
lemma with_density_congr_ae {f g : α → ℝ≥0∞} (h : f =ᵐ[μ] g) :
μ.with_density f = μ.with_density g :=
begin
apply measure.ext (λ s hs, _),
rw [with_density_apply _ hs, with_density_apply _ hs],
exact lintegral_congr_ae (ae_restrict_of_ae h)
end
lemma with_density_add_left {f : α → ℝ≥0∞} (hf : measurable f) (g : α → ℝ≥0∞) :
μ.with_density (f + g) = μ.with_density f + μ.with_density g :=
begin
refine measure.ext (λ s hs, _),
rw [with_density_apply _ hs, measure.add_apply,
with_density_apply _ hs, with_density_apply _ hs, ← lintegral_add_left hf],
refl,
end
lemma with_density_add_right (f : α → ℝ≥0∞) {g : α → ℝ≥0∞} (hg : measurable g) :
μ.with_density (f + g) = μ.with_density f + μ.with_density g :=
by simpa only [add_comm] using with_density_add_left hg f
lemma with_density_smul (r : ℝ≥0∞) {f : α → ℝ≥0∞} (hf : measurable f) :
μ.with_density (r • f) = r • μ.with_density f :=
begin
refine measure.ext (λ s hs, _),
rw [with_density_apply _ hs, measure.coe_smul, pi.smul_apply,
with_density_apply _ hs, smul_eq_mul, ← lintegral_const_mul r hf],
refl,
end
lemma with_density_smul' (r : ℝ≥0∞) (f : α → ℝ≥0∞) (hr : r ≠ ∞) :
μ.with_density (r • f) = r • μ.with_density f :=
begin
refine measure.ext (λ s hs, _),
rw [with_density_apply _ hs, measure.coe_smul, pi.smul_apply,
with_density_apply _ hs, smul_eq_mul, ← lintegral_const_mul' r f hr],
refl,
end
lemma is_finite_measure_with_density {f : α → ℝ≥0∞}
(hf : ∫⁻ a, f a ∂μ ≠ ∞) : is_finite_measure (μ.with_density f) :=
{ measure_univ_lt_top :=
by rwa [with_density_apply _ measurable_set.univ, measure.restrict_univ, lt_top_iff_ne_top] }
lemma with_density_absolutely_continuous
{m : measurable_space α} (μ : measure α) (f : α → ℝ≥0∞) : μ.with_density f ≪ μ :=
begin
refine absolutely_continuous.mk (λ s hs₁ hs₂, _),
rw with_density_apply _ hs₁,
exact set_lintegral_measure_zero _ _ hs₂
end
@[simp]
lemma with_density_zero : μ.with_density 0 = 0 :=
begin
ext1 s hs,
simp [with_density_apply _ hs],
end
@[simp]
lemma with_density_one : μ.with_density 1 = μ :=
begin
ext1 s hs,
simp [with_density_apply _ hs],
end
lemma with_density_tsum {f : ℕ → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) :
μ.with_density (∑' n, f n) = sum (λ n, μ.with_density (f n)) :=
begin
ext1 s hs,
simp_rw [sum_apply _ hs, with_density_apply _ hs],
change ∫⁻ x in s, (∑' n, f n) x ∂μ = ∑' (i : ℕ), ∫⁻ x, f i x ∂(μ.restrict s),
rw ← lintegral_tsum h,
refine lintegral_congr (λ x, tsum_apply (pi.summable.2 (λ _, ennreal.summable))),
end
lemma with_density_indicator {s : set α} (hs : measurable_set s) (f : α → ℝ≥0∞) :
μ.with_density (s.indicator f) = (μ.restrict s).with_density f :=
begin
ext1 t ht,
rw [with_density_apply _ ht, lintegral_indicator _ hs,
restrict_comm hs, ← with_density_apply _ ht]
end
lemma with_density_indicator_one {s : set α} (hs : measurable_set s) :
μ.with_density (s.indicator 1) = μ.restrict s :=
by rw [with_density_indicator hs, with_density_one]
lemma with_density_of_real_mutually_singular {f : α → ℝ} (hf : measurable f) :
μ.with_density (λ x, ennreal.of_real $ f x) ⊥ₘ μ.with_density (λ x, ennreal.of_real $ -f x) :=
begin
set S : set α := { x | f x < 0 } with hSdef,
have hS : measurable_set S := measurable_set_lt hf measurable_const,
refine ⟨S, hS, _, _⟩,
{ rw [with_density_apply _ hS, lintegral_eq_zero_iff hf.ennreal_of_real, eventually_eq],
exact (ae_restrict_mem hS).mono (λ x hx, ennreal.of_real_eq_zero.2 (le_of_lt hx)) },
{ rw [with_density_apply _ hS.compl, lintegral_eq_zero_iff hf.neg.ennreal_of_real, eventually_eq],
exact (ae_restrict_mem hS.compl).mono (λ x hx, ennreal.of_real_eq_zero.2
(not_lt.1 $ mt neg_pos.1 hx)) },
end
lemma restrict_with_density {s : set α} (hs : measurable_set s) (f : α → ℝ≥0∞) :
(μ.with_density f).restrict s = (μ.restrict s).with_density f :=
begin
ext1 t ht,
rw [restrict_apply ht, with_density_apply _ ht,
with_density_apply _ (ht.inter hs), restrict_restrict ht],
end
lemma with_density_eq_zero {f : α → ℝ≥0∞}
(hf : ae_measurable f μ) (h : μ.with_density f = 0) :
f =ᵐ[μ] 0 :=
by rw [← lintegral_eq_zero_iff' hf, ← set_lintegral_univ,
← with_density_apply _ measurable_set.univ, h, measure.coe_zero, pi.zero_apply]
lemma with_density_apply_eq_zero {f : α → ℝ≥0∞} {s : set α} (hf : measurable f) :
μ.with_density f s = 0 ↔ μ ({x | f x ≠ 0} ∩ s) = 0 :=
begin
split,
{ assume hs,
let t := to_measurable (μ.with_density f) s,
apply measure_mono_null
(inter_subset_inter_right _ (subset_to_measurable (μ.with_density f) s)),
have A : μ.with_density f t = 0, by rw [measure_to_measurable, hs],
rw [with_density_apply f (measurable_set_to_measurable _ s), lintegral_eq_zero_iff hf,
eventually_eq, ae_restrict_iff, ae_iff] at A,
swap, { exact hf (measurable_set_singleton 0) },
simp only [pi.zero_apply, mem_set_of_eq, filter.mem_mk] at A,
convert A,
ext x,
simp only [and_comm, exists_prop, mem_inter_eq, iff_self, mem_set_of_eq, mem_compl_eq,
not_forall] },
{ assume hs,
let t := to_measurable μ ({x | f x ≠ 0} ∩ s),
have A : s ⊆ t ∪ {x | f x = 0},
{ assume x hx,
rcases eq_or_ne (f x) 0 with fx|fx,
{ simp only [fx, mem_union_eq, mem_set_of_eq, eq_self_iff_true, or_true] },
{ left,
apply subset_to_measurable _ _,
exact ⟨fx, hx⟩ } },
apply measure_mono_null A (measure_union_null _ _),
{ apply with_density_absolutely_continuous,
rwa measure_to_measurable },
{ have M : measurable_set {x : α | f x = 0} := hf (measurable_set_singleton _),
rw [with_density_apply _ M, (lintegral_eq_zero_iff hf)],
filter_upwards [ae_restrict_mem M],
simp only [imp_self, pi.zero_apply, implies_true_iff] } }
end
lemma ae_with_density_iff {p : α → Prop} {f : α → ℝ≥0∞} (hf : measurable f) :
(∀ᵐ x ∂(μ.with_density f), p x) ↔ ∀ᵐ x ∂μ, f x ≠ 0 → p x :=
begin
rw [ae_iff, ae_iff, with_density_apply_eq_zero hf],
congr',
ext x,
simp only [exists_prop, mem_inter_eq, iff_self, mem_set_of_eq, not_forall],
end
lemma ae_with_density_iff_ae_restrict {p : α → Prop} {f : α → ℝ≥0∞} (hf : measurable f) :
(∀ᵐ x ∂(μ.with_density f), p x) ↔ (∀ᵐ x ∂(μ.restrict {x | f x ≠ 0}), p x) :=
begin
rw [ae_with_density_iff hf, ae_restrict_iff'],
{ refl },
{ exact hf (measurable_set_singleton 0).compl },
end
lemma ae_measurable_with_density_iff {E : Type*} [normed_add_comm_group E] [normed_space ℝ E]
[topological_space.second_countable_topology E] [measurable_space E] [borel_space E]
{f : α → ℝ≥0} (hf : measurable f) {g : α → E} :
ae_measurable g (μ.with_density (λ x, (f x : ℝ≥0∞))) ↔ ae_measurable (λ x, (f x : ℝ) • g x) μ :=
begin
split,
{ rintros ⟨g', g'meas, hg'⟩,
have A : measurable_set {x : α | f x ≠ 0} := (hf (measurable_set_singleton 0)).compl,
refine ⟨λ x, (f x : ℝ) • g' x, hf.coe_nnreal_real.smul g'meas, _⟩,
apply @ae_of_ae_restrict_of_ae_restrict_compl _ _ _ {x | f x ≠ 0},
{ rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal] at hg',
rw ae_restrict_iff' A,
filter_upwards [hg'],
assume a ha h'a,
have : (f a : ℝ≥0∞) ≠ 0, by simpa only [ne.def, coe_eq_zero] using h'a,
rw ha this },
{ filter_upwards [ae_restrict_mem A.compl],
assume x hx,
simp only [not_not, mem_set_of_eq, mem_compl_eq] at hx,
simp [hx] } },
{ rintros ⟨g', g'meas, hg'⟩,
refine ⟨λ x, (f x : ℝ)⁻¹ • g' x, hf.coe_nnreal_real.inv.smul g'meas, _⟩,
rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal],
filter_upwards [hg'],
assume x hx h'x,
rw [← hx, smul_smul, _root_.inv_mul_cancel, one_smul],
simp only [ne.def, coe_eq_zero] at h'x,
simpa only [nnreal.coe_eq_zero, ne.def] using h'x }
end
lemma ae_measurable_with_density_ennreal_iff {f : α → ℝ≥0} (hf : measurable f) {g : α → ℝ≥0∞} :
ae_measurable g (μ.with_density (λ x, (f x : ℝ≥0∞))) ↔
ae_measurable (λ x, (f x : ℝ≥0∞) * g x) μ :=
begin
split,
{ rintros ⟨g', g'meas, hg'⟩,
have A : measurable_set {x : α | f x ≠ 0} := (hf (measurable_set_singleton 0)).compl,
refine ⟨λ x, f x * g' x, hf.coe_nnreal_ennreal.smul g'meas, _⟩,
apply ae_of_ae_restrict_of_ae_restrict_compl {x | f x ≠ 0},
{ rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal] at hg',
rw ae_restrict_iff' A,
filter_upwards [hg'],
assume a ha h'a,
have : (f a : ℝ≥0∞) ≠ 0, by simpa only [ne.def, coe_eq_zero] using h'a,
rw ha this },
{ filter_upwards [ae_restrict_mem A.compl],
assume x hx,
simp only [not_not, mem_set_of_eq, mem_compl_eq] at hx,
simp [hx] } },
{ rintros ⟨g', g'meas, hg'⟩,
refine ⟨λ x, (f x)⁻¹ * g' x, hf.coe_nnreal_ennreal.inv.smul g'meas, _⟩,
rw [eventually_eq, ae_with_density_iff hf.coe_nnreal_ennreal],
filter_upwards [hg'],
assume x hx h'x,
rw [← hx, ← mul_assoc, ennreal.inv_mul_cancel h'x ennreal.coe_ne_top, one_mul] }
end
end lintegral
end measure_theory
open measure_theory measure_theory.simple_func
/-- To prove something for an arbitrary measurable function into `ℝ≥0∞`, it suffices to show
that the property holds for (multiples of) characteristic functions and is closed under addition
and supremum of increasing sequences of functions.
It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions
can be added once we need them (for example in `h_add` it is only necessary to consider the sum of
a simple function with a multiple of a characteristic function and that the intersection
of their images is a subset of `{0}`. -/
@[elab_as_eliminator]
theorem measurable.ennreal_induction {α} [measurable_space α] {P : (α → ℝ≥0∞) → Prop}
(h_ind : ∀ (c : ℝ≥0∞) ⦃s⦄, measurable_set s → P (indicator s (λ _, c)))
(h_add : ∀ ⦃f g : α → ℝ≥0∞⦄, disjoint (support f) (support g) → measurable f → measurable g →
P f → P g → P (f + g))
(h_supr : ∀ ⦃f : ℕ → α → ℝ≥0∞⦄ (hf : ∀n, measurable (f n)) (h_mono : monotone f)
(hP : ∀ n, P (f n)), P (λ x, ⨆ n, f n x))
⦃f : α → ℝ≥0∞⦄ (hf : measurable f) : P f :=
begin
convert h_supr (λ n, (eapprox f n).measurable) (monotone_eapprox f) _,
{ ext1 x, rw [supr_eapprox_apply f hf] },
{ exact λ n, simple_func.induction (λ c s hs, h_ind c hs)
(λ f g hfg hf hg, h_add hfg f.measurable g.measurable hf hg) (eapprox f n) }
end
namespace measure_theory
variables {α : Type*} {m m0 : measurable_space α}
include m
/-- This is Exercise 1.2.1 from [tao2010]. It allows you to express integration of a measurable
function with respect to `(μ.with_density f)` as an integral with respect to `μ`, called the base
measure. `μ` is often the Lebesgue measure, and in this circumstance `f` is the probability density
function, and `(μ.with_density f)` represents any continuous random variable as a
probability measure, such as the uniform distribution between 0 and 1, the Gaussian distribution,
the exponential distribution, the Beta distribution, or the Cauchy distribution (see Section 2.4
of [wasserman2004]). Thus, this method shows how to one can calculate expectations, variances,
and other moments as a function of the probability density function.
-/
lemma lintegral_with_density_eq_lintegral_mul (μ : measure α)
{f : α → ℝ≥0∞} (h_mf : measurable f) : ∀ {g : α → ℝ≥0∞}, measurable g →
∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ :=
begin
apply measurable.ennreal_induction,
{ intros c s h_ms,
simp [*, mul_comm _ c, ← indicator_mul_right], },
{ intros g h h_univ h_mea_g h_mea_h h_ind_g h_ind_h,
simp [mul_add, *, measurable.mul] },
{ intros g h_mea_g h_mono_g h_ind,
have : monotone (λ n a, f a * g n a) := λ m n hmn x, ennreal.mul_le_mul le_rfl (h_mono_g hmn x),
simp [lintegral_supr, ennreal.mul_supr, h_mf.mul (h_mea_g _), *] }
end
lemma set_lintegral_with_density_eq_set_lintegral_mul (μ : measure α) {f g : α → ℝ≥0∞}
(hf : measurable f) (hg : measurable g) {s : set α} (hs : measurable_set s) :
∫⁻ x in s, g x ∂μ.with_density f = ∫⁻ x in s, (f * g) x ∂μ :=
by rw [restrict_with_density hs, lintegral_with_density_eq_lintegral_mul _ hf hg]
/-- The Lebesgue integral of `g` with respect to the measure `μ.with_density f` coincides with
the integral of `f * g`. This version assumes that `g` is almost everywhere measurable. For a
version without conditions on `g` but requiring that `f` is almost everywhere finite, see
`lintegral_with_density_eq_lintegral_mul_non_measurable` -/
lemma lintegral_with_density_eq_lintegral_mul₀' {μ : measure α} {f : α → ℝ≥0∞}
(hf : ae_measurable f μ) {g : α → ℝ≥0∞} (hg : ae_measurable g (μ.with_density f)) :
∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ :=
begin
let f' := hf.mk f,
have : μ.with_density f = μ.with_density f' := with_density_congr_ae hf.ae_eq_mk,
rw this at ⊢ hg,
let g' := hg.mk g,
calc ∫⁻ a, g a ∂(μ.with_density f') = ∫⁻ a, g' a ∂(μ.with_density f') :
lintegral_congr_ae hg.ae_eq_mk
... = ∫⁻ a, (f' * g') a ∂μ :
lintegral_with_density_eq_lintegral_mul _ hf.measurable_mk hg.measurable_mk
... = ∫⁻ a, (f' * g) a ∂μ :
begin
apply lintegral_congr_ae,
apply ae_of_ae_restrict_of_ae_restrict_compl {x | f' x ≠ 0},
{ have Z := hg.ae_eq_mk,
rw [eventually_eq, ae_with_density_iff_ae_restrict hf.measurable_mk] at Z,
filter_upwards [Z],
assume x hx,
simp only [hx, pi.mul_apply] },
{ have M : measurable_set {x : α | f' x ≠ 0}ᶜ :=
(hf.measurable_mk (measurable_set_singleton 0).compl).compl,
filter_upwards [ae_restrict_mem M],
assume x hx,
simp only [not_not, mem_set_of_eq, mem_compl_eq] at hx,
simp only [hx, zero_mul, pi.mul_apply] }
end
... = ∫⁻ (a : α), (f * g) a ∂μ :
begin
apply lintegral_congr_ae,
filter_upwards [hf.ae_eq_mk],
assume x hx,
simp only [hx, pi.mul_apply],
end
end
lemma lintegral_with_density_eq_lintegral_mul₀ {μ : measure α} {f : α → ℝ≥0∞}
(hf : ae_measurable f μ) {g : α → ℝ≥0∞} (hg : ae_measurable g μ) :
∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ :=
lintegral_with_density_eq_lintegral_mul₀' hf (hg.mono' (with_density_absolutely_continuous μ f))
lemma lintegral_with_density_le_lintegral_mul (μ : measure α)
{f : α → ℝ≥0∞} (f_meas : measurable f) (g : α → ℝ≥0∞) :
∫⁻ a, g a ∂(μ.with_density f) ≤ ∫⁻ a, (f * g) a ∂μ :=
begin
rw [← supr_lintegral_measurable_le_eq_lintegral, ← supr_lintegral_measurable_le_eq_lintegral],
refine supr₂_le (λ i i_meas, supr_le (λ hi, _)),
have A : f * i ≤ f * g := λ x, ennreal.mul_le_mul le_rfl (hi x),
refine le_supr₂_of_le (f * i) (f_meas.mul i_meas) _,
exact le_supr_of_le A (le_of_eq (lintegral_with_density_eq_lintegral_mul _ f_meas i_meas))
end
lemma lintegral_with_density_eq_lintegral_mul_non_measurable (μ : measure α)
{f : α → ℝ≥0∞} (f_meas : measurable f) (hf : ∀ᵐ x ∂μ, f x < ∞) (g : α → ℝ≥0∞) :
∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ :=
begin
refine le_antisymm (lintegral_with_density_le_lintegral_mul μ f_meas g) _,
rw [← supr_lintegral_measurable_le_eq_lintegral, ← supr_lintegral_measurable_le_eq_lintegral],
refine supr₂_le (λ i i_meas, supr_le $ λ hi, _),
have A : (λ x, (f x)⁻¹ * i x) ≤ g,
{ assume x,
dsimp,
rw [mul_comm, ← div_eq_mul_inv],
exact div_le_of_le_mul' (hi x), },
refine le_supr_of_le (λ x, (f x)⁻¹ * i x) (le_supr_of_le (f_meas.inv.mul i_meas) _),
refine le_supr_of_le A _,
rw lintegral_with_density_eq_lintegral_mul _ f_meas (f_meas.inv.mul i_meas),
apply lintegral_mono_ae,
filter_upwards [hf],
assume x h'x,
rcases eq_or_ne (f x) 0 with hx|hx,
{ have := hi x,
simp only [hx, zero_mul, pi.mul_apply, nonpos_iff_eq_zero] at this,
simp [this] },
{ apply le_of_eq _,
dsimp,
rw [← mul_assoc, ennreal.mul_inv_cancel hx h'x.ne, one_mul] }
end
lemma set_lintegral_with_density_eq_set_lintegral_mul_non_measurable (μ : measure α)
{f : α → ℝ≥0∞} (f_meas : measurable f) (g : α → ℝ≥0∞)
{s : set α} (hs : measurable_set s) (hf : ∀ᵐ x ∂(μ.restrict s), f x < ∞) :
∫⁻ a in s, g a ∂(μ.with_density f) = ∫⁻ a in s, (f * g) a ∂μ :=
by rw [restrict_with_density hs, lintegral_with_density_eq_lintegral_mul_non_measurable _ f_meas hf]
lemma lintegral_with_density_eq_lintegral_mul_non_measurable₀ (μ : measure α)
{f : α → ℝ≥0∞} (hf : ae_measurable f μ) (h'f : ∀ᵐ x ∂μ, f x < ∞) (g : α → ℝ≥0∞) :
∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ :=
begin
let f' := hf.mk f,
calc
∫⁻ a, g a ∂(μ.with_density f)
= ∫⁻ a, g a ∂(μ.with_density f') : by rw with_density_congr_ae hf.ae_eq_mk
... = ∫⁻ a, (f' * g) a ∂μ :
begin
apply lintegral_with_density_eq_lintegral_mul_non_measurable _ hf.measurable_mk,
filter_upwards [h'f, hf.ae_eq_mk],
assume x hx h'x,
rwa ← h'x,
end
... = ∫⁻ a, (f * g) a ∂μ :
begin
apply lintegral_congr_ae,
filter_upwards [hf.ae_eq_mk],
assume x hx,
simp only [hx, pi.mul_apply],
end
end
lemma set_lintegral_with_density_eq_set_lintegral_mul_non_measurable₀ (μ : measure α)
{f : α → ℝ≥0∞} {s : set α} (hf : ae_measurable f (μ.restrict s)) (g : α → ℝ≥0∞)
(hs : measurable_set s) (h'f : ∀ᵐ x ∂(μ.restrict s), f x < ∞) :
∫⁻ a in s, g a ∂(μ.with_density f) = ∫⁻ a in s, (f * g) a ∂μ :=
by rw [restrict_with_density hs, lintegral_with_density_eq_lintegral_mul_non_measurable₀ _ hf h'f]
lemma with_density_mul (μ : measure α) {f g : α → ℝ≥0∞} (hf : measurable f) (hg : measurable g) :
μ.with_density (f * g) = (μ.with_density f).with_density g :=
begin
ext1 s hs,
simp [with_density_apply _ hs, restrict_with_density hs,
lintegral_with_density_eq_lintegral_mul _ hf hg],
end
/-- In a sigma-finite measure space, there exists an integrable function which is
positive everywhere (and with an arbitrarily small integral). -/
lemma exists_pos_lintegral_lt_of_sigma_finite
(μ : measure α) [sigma_finite μ] {ε : ℝ≥0∞} (ε0 : ε ≠ 0) :
∃ g : α → ℝ≥0, (∀ x, 0 < g x) ∧ measurable g ∧ (∫⁻ x, g x ∂μ < ε) :=
begin
/- Let `s` be a covering of `α` by pairwise disjoint measurable sets of finite measure. Let
`δ : ℕ → ℝ≥0` be a positive function such that `∑' i, μ (s i) * δ i < ε`. Then the function that
is equal to `δ n` on `s n` is a positive function with integral less than `ε`. -/
set s : ℕ → set α := disjointed (spanning_sets μ),
have : ∀ n, μ (s n) < ∞,
from λ n, (measure_mono $ disjointed_subset _ _).trans_lt (measure_spanning_sets_lt_top μ n),
obtain ⟨δ, δpos, δsum⟩ : ∃ δ : ℕ → ℝ≥0, (∀ i, 0 < δ i) ∧ ∑' i, μ (s i) * δ i < ε,
from ennreal.exists_pos_tsum_mul_lt_of_encodable ε0 _ (λ n, (this n).ne),
set N : α → ℕ := spanning_sets_index μ,
have hN_meas : measurable N := measurable_spanning_sets_index μ,
have hNs : ∀ n, N ⁻¹' {n} = s n := preimage_spanning_sets_index_singleton μ,
refine ⟨δ ∘ N, λ x, δpos _, measurable_from_nat.comp hN_meas, _⟩,
simpa [lintegral_comp measurable_from_nat.coe_nnreal_ennreal hN_meas, hNs,
lintegral_encodable, measurable_spanning_sets_index, mul_comm] using δsum,
end
lemma lintegral_trim {μ : measure α} (hm : m ≤ m0) {f : α → ℝ≥0∞} (hf : measurable[m] f) :
∫⁻ a, f a ∂(μ.trim hm) = ∫⁻ a, f a ∂μ :=
begin
refine @measurable.ennreal_induction α m (λ f, ∫⁻ a, f a ∂(μ.trim hm) = ∫⁻ a, f a ∂μ) _ _ _ f hf,
{ intros c s hs,
rw [lintegral_indicator _ hs, lintegral_indicator _ (hm s hs),
set_lintegral_const, set_lintegral_const],
suffices h_trim_s : μ.trim hm s = μ s, by rw h_trim_s,
exact trim_measurable_set_eq hm hs, },
{ intros f g hfg hf hg hf_prop hg_prop,
have h_m := lintegral_add_left hf g,
have h_m0 := lintegral_add_left (measurable.mono hf hm le_rfl) g,
rwa [hf_prop, hg_prop, ← h_m0] at h_m, },
{ intros f hf hf_mono hf_prop,
rw lintegral_supr hf hf_mono,
rw lintegral_supr (λ n, measurable.mono (hf n) hm le_rfl) hf_mono,
congr,
exact funext (λ n, hf_prop n), },
end
lemma lintegral_trim_ae {μ : measure α} (hm : m ≤ m0)
{f : α → ℝ≥0∞} (hf : ae_measurable f (μ.trim hm)) :
∫⁻ a, f a ∂(μ.trim hm) = ∫⁻ a, f a ∂μ :=
by rw [lintegral_congr_ae (ae_eq_of_ae_eq_trim hf.ae_eq_mk),
lintegral_congr_ae hf.ae_eq_mk, lintegral_trim hm hf.measurable_mk]
section sigma_finite
variables {E : Type*} [normed_add_comm_group E] [measurable_space E]
[opens_measurable_space E]
lemma univ_le_of_forall_fin_meas_le {μ : measure α} (hm : m ≤ m0) [sigma_finite (μ.trim hm)]
(C : ℝ≥0∞) {f : set α → ℝ≥0∞} (hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → f s ≤ C)
(h_F_lim : ∀ S : ℕ → set α,
(∀ n, measurable_set[m] (S n)) → monotone S → f (⋃ n, S n) ≤ ⨆ n, f (S n)) :
f univ ≤ C :=
begin
let S := @spanning_sets _ m (μ.trim hm) _,
have hS_mono : monotone S, from @monotone_spanning_sets _ m (μ.trim hm) _,
have hS_meas : ∀ n, measurable_set[m] (S n), from @measurable_spanning_sets _ m (μ.trim hm) _,
rw ← @Union_spanning_sets _ m (μ.trim hm),
refine (h_F_lim S hS_meas hS_mono).trans _,
refine supr_le (λ n, hf (S n) (hS_meas n) _),
exact ((le_trim hm).trans_lt (@measure_spanning_sets_lt_top _ m (μ.trim hm) _ n)).ne,
end
/-- If the Lebesgue integral of a function is bounded by some constant on all sets with finite
measure in a sub-σ-algebra and the measure is σ-finite on that sub-σ-algebra, then the integral
over the whole space is bounded by that same constant. Version for a measurable function.
See `lintegral_le_of_forall_fin_meas_le'` for the more general `ae_measurable` version. -/
lemma lintegral_le_of_forall_fin_meas_le_of_measurable {μ : measure α} (hm : m ≤ m0)
[sigma_finite (μ.trim hm)] (C : ℝ≥0∞) {f : α → ℝ≥0∞} (hf_meas : measurable f)
(hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, f x ∂μ ≤ C) :
∫⁻ x, f x ∂μ ≤ C :=
begin
have : ∫⁻ x in univ, f x ∂μ = ∫⁻ x, f x ∂μ, by simp only [measure.restrict_univ],
rw ← this,
refine univ_le_of_forall_fin_meas_le hm C hf (λ S hS_meas hS_mono, _),
rw ← lintegral_indicator,
swap, { exact hm (⋃ n, S n) (@measurable_set.Union _ _ m _ _ hS_meas), },
have h_integral_indicator : (⨆ n, ∫⁻ x in S n, f x ∂μ) = ⨆ n, ∫⁻ x, (S n).indicator f x ∂μ,
{ congr,
ext1 n,
rw lintegral_indicator _ (hm _ (hS_meas n)), },
rw [h_integral_indicator, ← lintegral_supr],
{ refine le_of_eq (lintegral_congr (λ x, _)),
simp_rw indicator_apply,
by_cases hx_mem : x ∈ Union S,
{ simp only [hx_mem, if_true],
obtain ⟨n, hxn⟩ := mem_Union.mp hx_mem,
refine le_antisymm (trans _ (le_supr _ n)) (supr_le (λ i, _)),
{ simp only [hxn, le_refl, if_true], },
{ by_cases hxi : x ∈ S i; simp [hxi], }, },
{ simp only [hx_mem, if_false],
rw mem_Union at hx_mem,
push_neg at hx_mem,
refine le_antisymm (zero_le _) (supr_le (λ n, _)),
simp only [hx_mem n, if_false, nonpos_iff_eq_zero], }, },
{ exact λ n, hf_meas.indicator (hm _ (hS_meas n)), },
{ intros n₁ n₂ hn₁₂ a,
simp_rw indicator_apply,
split_ifs,
{ exact le_rfl, },
{ exact absurd (mem_of_mem_of_subset h (hS_mono hn₁₂)) h_1, },
{ exact zero_le _, },
{ exact le_rfl, }, },
end
/-- If the Lebesgue integral of a function is bounded by some constant on all sets with finite
measure in a sub-σ-algebra and the measure is σ-finite on that sub-σ-algebra, then the integral
over the whole space is bounded by that same constant. -/
lemma lintegral_le_of_forall_fin_meas_le' {μ : measure α} (hm : m ≤ m0)
[sigma_finite (μ.trim hm)] (C : ℝ≥0∞) {f : _ → ℝ≥0∞} (hf_meas : ae_measurable f μ)
(hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, f x ∂μ ≤ C) :
∫⁻ x, f x ∂μ ≤ C :=
begin
let f' := hf_meas.mk f,
have hf' : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, f' x ∂μ ≤ C,
{ refine λ s hs hμs, (le_of_eq _).trans (hf s hs hμs),
refine lintegral_congr_ae (ae_restrict_of_ae (hf_meas.ae_eq_mk.mono (λ x hx, _))),
rw hx, },
rw lintegral_congr_ae hf_meas.ae_eq_mk,
exact lintegral_le_of_forall_fin_meas_le_of_measurable hm C hf_meas.measurable_mk hf',
end
omit m
/-- If the Lebesgue integral of a function is bounded by some constant on all sets with finite
measure and the measure is σ-finite, then the integral over the whole space is bounded by that same
constant. -/
lemma lintegral_le_of_forall_fin_meas_le [measurable_space α] {μ : measure α} [sigma_finite μ]
(C : ℝ≥0∞) {f : α → ℝ≥0∞} (hf_meas : ae_measurable f μ)
(hf : ∀ s, measurable_set s → μ s ≠ ∞ → ∫⁻ x in s, f x ∂μ ≤ C) :
∫⁻ x, f x ∂μ ≤ C :=
@lintegral_le_of_forall_fin_meas_le' _ _ _ _ _ (by rwa trim_eq_self) C _ hf_meas hf
local infixr ` →ₛ `:25 := simple_func
lemma simple_func.exists_lt_lintegral_simple_func_of_lt_lintegral
{m : measurable_space α} {μ : measure α} [sigma_finite μ] {f : α →ₛ ℝ≥0}
{L : ℝ≥0∞} (hL : L < ∫⁻ x, f x ∂μ) :
∃ g : α →ₛ ℝ≥0, (∀ x, g x ≤ f x) ∧ (∫⁻ x, g x ∂μ < ∞) ∧ (L < ∫⁻ x, g x ∂μ) :=
begin
induction f using measure_theory.simple_func.induction with c s hs f₁ f₂ H h₁ h₂ generalizing L,
{ simp only [hs, const_zero, coe_piecewise, coe_const, simple_func.coe_zero, univ_inter,
piecewise_eq_indicator, lintegral_indicator, lintegral_const, measure.restrict_apply',
coe_indicator, function.const_apply] at hL,
have c_ne_zero : c ≠ 0,
{ assume hc, simpa only [hc, ennreal.coe_zero, zero_mul, not_lt_zero] using hL },
have : L / c < μ s,
{ rwa [ennreal.div_lt_iff, mul_comm],
{ simp only [c_ne_zero, ne.def, coe_eq_zero, not_false_iff, true_or] },
{ simp only [ne.def, coe_ne_top, not_false_iff, true_or] } },
obtain ⟨t, ht, ts, mut, t_top⟩ :
∃ (t : set α), measurable_set t ∧ t ⊆ s ∧ L / ↑c < μ t ∧ μ t < ∞ :=
measure.exists_subset_measure_lt_top hs this,
refine ⟨piecewise t ht (const α c) (const α 0), λ x, _, _, _⟩,
{ apply indicator_le_indicator_of_subset ts (λ x, _), exact zero_le _ },
{ simp only [ht, const_zero, coe_piecewise, coe_const, simple_func.coe_zero, univ_inter,
piecewise_eq_indicator, coe_indicator, function.const_apply, lintegral_indicator,
lintegral_const, measure.restrict_apply', ennreal.mul_lt_top ennreal.coe_ne_top t_top.ne] },
{ simp only [ht, const_zero, coe_piecewise, coe_const, simple_func.coe_zero,
piecewise_eq_indicator, coe_indicator, function.const_apply, lintegral_indicator,
lintegral_const, measure.restrict_apply', univ_inter],
rwa [mul_comm, ← ennreal.div_lt_iff],
{ simp only [c_ne_zero, ne.def, coe_eq_zero, not_false_iff, true_or] },
{ simp only [ne.def, coe_ne_top, not_false_iff, true_or] } } },
{ replace hL : L < ∫⁻ x, f₁ x ∂μ + ∫⁻ x, f₂ x ∂μ,
{ rwa ← lintegral_add_left f₁.measurable.coe_nnreal_ennreal },
by_cases hf₁ : ∫⁻ x, f₁ x ∂μ = 0,
{ simp only [hf₁, zero_add] at hL,
rcases h₂ hL with ⟨g, g_le, g_top, gL⟩,
refine ⟨g, λ x, (g_le x).trans _, g_top, gL⟩,
simp only [simple_func.coe_add, pi.add_apply, le_add_iff_nonneg_left, zero_le'] },
by_cases hf₂ : ∫⁻ x, f₂ x ∂μ = 0,
{ simp only [hf₂, add_zero] at hL,
rcases h₁ hL with ⟨g, g_le, g_top, gL⟩,
refine ⟨g, λ x, (g_le x).trans _, g_top, gL⟩,
simp only [simple_func.coe_add, pi.add_apply, le_add_iff_nonneg_right, zero_le'] },
obtain ⟨L₁, L₂, hL₁, hL₂, hL⟩ :
∃ (L₁ L₂ : ℝ≥0∞), L₁ < ∫⁻ x, f₁ x ∂μ ∧ L₂ < ∫⁻ x, f₂ x ∂μ ∧ L < L₁ + L₂ :=
ennreal.exists_lt_add_of_lt_add hL hf₁ hf₂,
rcases h₁ hL₁ with ⟨g₁, g₁_le, g₁_top, hg₁⟩,
rcases h₂ hL₂ with ⟨g₂, g₂_le, g₂_top, hg₂⟩,
refine ⟨g₁ + g₂, λ x, add_le_add (g₁_le x) (g₂_le x), _, _⟩,
{ apply lt_of_le_of_lt _ (add_lt_top.2 ⟨g₁_top, g₂_top⟩),
rw ← lintegral_add_left g₁.measurable.coe_nnreal_ennreal,
exact le_rfl },
{ apply hL.trans ((ennreal.add_lt_add hg₁ hg₂).trans_le _),
rw ← lintegral_add_left g₁.measurable.coe_nnreal_ennreal,
exact le_rfl } }
end
lemma exists_lt_lintegral_simple_func_of_lt_lintegral
{m : measurable_space α} {μ : measure α} [sigma_finite μ] {f : α → ℝ≥0}
{L : ℝ≥0∞} (hL : L < ∫⁻ x, f x ∂μ) :
∃ g : α →ₛ ℝ≥0, (∀ x, g x ≤ f x) ∧ (∫⁻ x, g x ∂μ < ∞) ∧ (L < ∫⁻ x, g x ∂μ) :=
begin
simp_rw [lintegral_eq_nnreal, lt_supr_iff] at hL,
rcases hL with ⟨g₀, hg₀, g₀L⟩,
have h'L : L < ∫⁻ x, g₀ x ∂μ,
{ convert g₀L,
rw ← simple_func.lintegral_eq_lintegral,
refl },
rcases simple_func.exists_lt_lintegral_simple_func_of_lt_lintegral h'L with ⟨g, hg, gL, gtop⟩,
exact ⟨g, λ x, (hg x).trans (coe_le_coe.1 (hg₀ x)), gL, gtop⟩,
end
/-- A sigma-finite measure is absolutely continuous with respect to some finite measure. -/
lemma exists_absolutely_continuous_is_finite_measure
{m : measurable_space α} (μ : measure α) [sigma_finite μ] :
∃ (ν : measure α), is_finite_measure ν ∧ μ ≪ ν :=
begin
obtain ⟨g, gpos, gmeas, hg⟩ : ∃ (g : α → ℝ≥0), (∀ (x : α), 0 < g x) ∧
measurable g ∧ ∫⁻ (x : α), ↑(g x) ∂μ < 1 :=
exists_pos_lintegral_lt_of_sigma_finite μ (ennreal.zero_lt_one).ne',
refine ⟨μ.with_density (λ x, g x), is_finite_measure_with_density hg.ne_top, _⟩,
have : μ = (μ.with_density (λ x, g x)).with_density (λ x, (g x)⁻¹),
{ have A : (λ (x : α), (g x : ℝ≥0∞)) * (λ (x : α), (↑(g x))⁻¹) = 1,
{ ext1 x,
exact ennreal.mul_inv_cancel (ennreal.coe_ne_zero.2 ((gpos x).ne')) ennreal.coe_ne_top },
rw [← with_density_mul _ gmeas.coe_nnreal_ennreal gmeas.coe_nnreal_ennreal.inv, A,
with_density_one] },
conv_lhs { rw this },
exact with_density_absolutely_continuous _ _,
end
end sigma_finite
end measure_theory
|
43dd5fa2fb962e2701ed6b6a7abeeea15a316d3e | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /tests/lean/interactive/hoverDot.lean | 8b4b9cb0dde911261def5296acac75c4fdae5662 | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 541 | lean | structure Foo where
f₁ : Nat
def Foo.f₂ (f : Foo) : Nat :=
f.f₁
def Foo.foo : Foo := ⟨10⟩
#check Foo.foo.f₁.succ
--^ textDocument/hover
open Foo
#check foo.f₁.succ
--^ textDocument/hover
--^ textDocument/hover
#check foo.f₂.succ
--^ textDocument/hover
--^ textDocument/hover
#check (foo).f₂.succ
--^ textDocument/hover
--^ textDocument/hover
#check foo |>.f₂.succ
--^ textDocument/hover
--^ textDocument/hover
|
1bbdfada7007ee315a3db8b8a9dd56a2bf30643e | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /src/Lean/Data/Json/FromToJson.lean | 8594058ee18c4b677a83b60a2856017bc1142236 | [
"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,022 | lean | /-
Copyright (c) 2019 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Marc Huisinga
-/
import Lean.Data.Json.Basic
namespace Lean
universes u
class FromJson (α : Type u) where
fromJson? : Json → Option α
export FromJson (fromJson?)
class ToJson (α : Type u) where
toJson : α → Json
export ToJson (toJson)
instance : FromJson Json := ⟨some⟩
instance : ToJson Json := ⟨id⟩
instance : FromJson JsonNumber := ⟨Json.getNum?⟩
instance : ToJson JsonNumber := ⟨Json.num⟩
-- looks like id, but there are coercions happening
instance : FromJson Bool := ⟨Json.getBool?⟩
instance : ToJson Bool := ⟨fun b => b⟩
instance : FromJson Nat := ⟨Json.getNat?⟩
instance : ToJson Nat := ⟨fun n => n⟩
instance : FromJson Int := ⟨Json.getInt?⟩
instance : ToJson Int := ⟨fun n => Json.num n⟩
instance : FromJson String := ⟨Json.getStr?⟩
instance : ToJson String := ⟨fun s => s⟩
instance [FromJson α] : FromJson (Array α) := ⟨fun
| Json.arr a => a.mapM fromJson?
| _ => none⟩
instance [ToJson α] : ToJson (Array α) :=
⟨fun a => Json.arr (a.map toJson)⟩
instance [FromJson α] : FromJson (Option α) :=
⟨fun
| Json.null => some none
| j => some <$> fromJson? j⟩
instance [ToJson α] : ToJson (Option α) :=
⟨fun
| none => Json.null
| some a => toJson a⟩
namespace Json
instance : FromJson Structured := ⟨fun
| arr a => Structured.arr a
| obj o => Structured.obj o
| _ => none⟩
instance : ToJson Structured := ⟨fun
| Structured.arr a => arr a
| Structured.obj o => obj o⟩
def toStructured? [ToJson α] (v : α) : Option Structured :=
fromJson? (toJson v)
def getObjValAs? (j : Json) (α : Type u) [FromJson α] (k : String) : Option α :=
fromJson? <| j.getObjValD k
def opt [ToJson α] (k : String) : Option α → List (String × Json)
| none => []
| some o => [⟨k, toJson o⟩]
end Json
end Lean
|
f0bb297c04b18b88ee0c307601008eae3e289434 | f1b175e38ffc5cc1c7c5551a72d0dbaf70786f83 | /data/complex/basic.lean | c9691ad63a1bba633405c8ba27a146ac3a593123 | [
"Apache-2.0"
] | permissive | mjendrusch/mathlib | df3ae884dd5ce38c7edf452bcbfd3baf4e3a6214 | 5c209edb7eb616a26f64efe3500f2b1ba95b8d55 | refs/heads/master | 1,585,663,284,800 | 1,539,062,055,000 | 1,539,062,055,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,715 | lean | /-
Copyright (c) 2017 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Mario Carneiro
The complex numbers, modelled as R^2 in the obvious way.
-/
import data.real.basic tactic.ring algebra.field
structure complex : Type :=
(re : ℝ) (im : ℝ)
notation `ℂ` := complex
namespace complex
@[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z
| ⟨a, b⟩ := rfl
theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w
| ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl
theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im :=
⟨λ H, by simp [H], and.rec ext⟩
def of_real (r : ℝ) : ℂ := ⟨r, 0⟩
instance : has_coe ℝ ℂ := ⟨of_real⟩
@[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl
@[simp] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl
@[simp] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl
@[simp] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w :=
⟨congr_arg re, congr_arg _⟩
instance : has_zero ℂ := ⟨(0 : ℝ)⟩
instance : inhabited ℂ := ⟨0⟩
@[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl
@[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl
lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl
@[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj
@[simp] theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero
instance : has_one ℂ := ⟨(1 : ℝ)⟩
@[simp] lemma one_re : (1 : ℂ).re = 1 := rfl
@[simp] lemma one_im : (1 : ℂ).im = 0 := rfl
@[simp] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl
def I : ℂ := ⟨0, 1⟩
@[simp] lemma I_re : I.re = 0 := rfl
@[simp] lemma I_im : I.im = 1 := rfl
instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩
@[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl
@[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl
@[simp] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := rfl
@[simp] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := rfl
@[simp] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := rfl
instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩
@[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl
@[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl
@[simp] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := rfl
instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩
@[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl
@[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl
@[simp] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp
lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I :=
ext_iff.2 $ by simp
@[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z :=
ext_iff.2 $ by simp
def conj (z : ℂ) : ℂ := ⟨z.re, -z.im⟩
@[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl
@[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl
@[simp] lemma conj_of_real (r : ℝ) : conj r = r := rfl
@[simp] lemma conj_zero : conj 0 = 0 := rfl
@[simp] lemma conj_one : conj 1 = 1 := rfl
@[simp] lemma conj_I : conj I = -I := rfl
@[simp] lemma conj_add (z w : ℂ) : conj (z + w) = conj z + conj w :=
ext_iff.2 $ by simp
@[simp] lemma conj_neg (z : ℂ) : conj (-z) = -conj z := rfl
@[simp] lemma conj_mul (z w : ℂ) : conj (z * w) = conj z * conj w :=
ext_iff.2 $ by simp
@[simp] lemma conj_conj (z : ℂ) : conj (conj z) = z :=
ext_iff.2 $ by simp
lemma conj_bijective : function.bijective conj :=
⟨function.injective_of_has_left_inverse ⟨conj, conj_conj⟩,
function.surjective_of_has_right_inverse ⟨conj, conj_conj⟩⟩
lemma conj_inj {z w : ℂ} : conj z = conj w ↔ z = w :=
conj_bijective.1.eq_iff
@[simp] lemma conj_eq_zero {z : ℂ} : conj z = 0 ↔ z = 0 :=
by simpa using @conj_inj z 0
@[simp] lemma eq_conj_iff_real (z : ℂ) : conj z = z ↔ ∃ r : ℝ, z = r :=
⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩,
λ ⟨h, e⟩, e.symm ▸ rfl⟩
def norm_sq (z : ℂ) : ℝ := z.re * z.re + z.im * z.im
@[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r :=
by simp [norm_sq]
@[simp] lemma norm_sq_zero : norm_sq 0 = 0 := rfl
@[simp] lemma norm_sq_one : norm_sq 1 = 1 := rfl
@[simp] lemma norm_sq_I : norm_sq I = 1 := rfl
lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z :=
add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)
@[simp] lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 :=
⟨λ h, ext
(eq_zero_of_mul_self_add_mul_self_eq_zero h)
(eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h),
λ h, h.symm ▸ norm_sq_zero⟩
@[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 :=
by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg]
@[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z :=
by simp [norm_sq]
@[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z :=
by simp [norm_sq]
@[simp] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w :=
by dsimp [norm_sq]; ring
lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) =
norm_sq z + norm_sq w + 2 * (z * conj w).re :=
by dsimp [norm_sq]; ring
lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z :=
le_add_of_nonneg_right (mul_self_nonneg _)
lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z :=
le_add_of_nonneg_left (mul_self_nonneg _)
theorem mul_conj (z : ℂ) : z * conj z = norm_sq z :=
ext_iff.2 $ by simp [norm_sq, mul_comm]
theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) :=
ext_iff.2 $ by simp [two_mul]
instance : comm_ring ℂ :=
by refine { zero := 0, add := (+), neg := has_neg.neg, one := 1, mul := (*), ..};
{ intros, apply ext_iff.2; split; simp; ring }
@[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl
@[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl
@[simp] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := rfl
theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I :=
ext_iff.2 $ by simp [two_mul]
lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) =
norm_sq z + norm_sq w - 2 * (z * conj w).re :=
by rw [sub_eq_add_neg, norm_sq_add]; simp [-mul_re]
noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩
theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl
@[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def]
@[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def]
lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ :=
ext_iff.2 $ begin
simp,
by_cases r = 0, {simp [h]},
rw [← div_div_eq_div_mul, div_self h, one_div_eq_inv]
end
lemma inv_zero : (0⁻¹ : ℂ) = 0 :=
by rw [← of_real_zero, ← of_real_inv, inv_zero]
theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 :=
by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul,
mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one]
noncomputable instance : discrete_field ℂ :=
{ inv := has_inv.inv,
zero_ne_one := mt (congr_arg re) zero_ne_one,
mul_inv_cancel := @mul_inv_cancel,
inv_mul_cancel := λ z h, by rw [mul_comm, mul_inv_cancel h],
inv_zero := inv_zero,
has_decidable_eq := classical.dec_eq _,
..complex.comm_ring }
@[simp] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s :=
by rw [division_def, of_real_mul, division_def, of_real_inv]
@[simp] theorem of_real_int_cast : ∀ n : ℤ, ((n : ℝ) : ℂ) = n :=
int.eq_cast (λ n, ((n : ℝ) : ℂ)) rfl (by simp)
@[simp] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n :=
by rw [← int.cast_coe_nat, of_real_int_cast]; refl
@[simp] lemma conj_inv (z : ℂ) : conj z⁻¹ = (conj z)⁻¹ :=
if h : z = 0 then by simp [h] else
(domain.mul_left_inj (mt conj_eq_zero.1 h)).1 $
by rw [← conj_mul]; simp [h, -conj_mul]
@[simp] lemma conj_div (z w : ℂ) : conj (z / w) = conj z / conj w :=
by rw [division_def, conj_mul, conj_inv]; refl
@[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ :=
if h : z = 0 then by simp [h] else
(domain.mul_left_inj (mt norm_sq_eq_zero.1 h)).1 $
by rw [← norm_sq_mul]; simp [h, -norm_sq_mul]
@[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w :=
by rw [division_def, norm_sq_mul, norm_sq_inv]; refl
instance char_zero_complex : char_zero ℂ :=
add_group.char_zero_of_inj_zero $ λ n h,
by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h
@[simp] theorem of_real_rat_cast : ∀ n : ℚ, ((n : ℝ) : ℂ) = n :=
by apply rat.eq_cast (λ n, ((n : ℝ) : ℂ)); simp
theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 :=
by rw [add_conj]; simp; rw [mul_div_cancel_left (z.re:ℂ) two_ne_zero']
noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt
local notation `abs'` := _root_.abs
@[simp] lemma abs_of_real (r : ℝ) : abs r = abs' r :=
by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs]
lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r :=
(abs_of_real _).trans (abs_of_nonneg h)
lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z :=
real.mul_self_sqrt (norm_sq_nonneg _)
@[simp] lemma abs_zero : abs 0 = 0 := by simp [abs]
@[simp] lemma abs_one : abs 1 = 1 := by simp [abs]
@[simp] lemma abs_I : abs I = 1 := by simp [abs]
lemma abs_nonneg (z : ℂ) : 0 ≤ abs z :=
real.sqrt_nonneg _
@[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 :=
(real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero
@[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z :=
by simp [abs]
@[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w :=
by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl
lemma abs_re_le_abs (z : ℂ) : abs' z.re ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply re_sq_le_norm_sq
lemma abs_im_le_abs (z : ℂ) : abs' z.im ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply im_sq_le_norm_sq
lemma re_le_abs (z : ℂ) : z.re ≤ abs z :=
(abs_le.1 (abs_re_le_abs _)).2
lemma im_le_abs (z : ℂ) : z.im ≤ abs z :=
(abs_le.1 (abs_im_le_abs _)).2
lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w :=
(mul_self_le_mul_self_iff (abs_nonneg _)
(add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $
begin
rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs,
add_right_comm, norm_sq_add, add_le_add_iff_left,
mul_assoc, mul_le_mul_left (@two_pos ℝ _)],
simpa [-mul_re] using re_le_abs (z * conj w)
end
instance : is_absolute_value abs :=
{ abv_nonneg := abs_nonneg,
abv_eq_zero := λ _, abs_eq_zero,
abv_add := abs_add,
abv_mul := abs_mul }
open is_absolute_value
@[simp] lemma abs_abs (z : ℂ) : abs' (abs z) = abs z :=
_root_.abs_of_nonneg (abs_nonneg _)
@[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs
@[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs
lemma abs_sub : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs
lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs
@[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs
@[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs
lemma abs_abs_sub_le_abs_sub : ∀ z w, abs' (abs z - abs w) ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs
lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ abs' z.re + abs' z.im :=
by simpa [re_add_im] using abs_add z.re (z.im * I)
noncomputable def lim (f : ℕ → ℂ) : ℂ :=
⟨real.lim (λ n, (f n).re), real.lim (λ n, (f n).im)⟩
theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij)
theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij)
theorem equiv_lim (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim f) :=
λ ε ε0, (exists_forall_ge_and
(real.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0))
(real.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $
λ i H j ij, begin
cases H _ ij with H₁ H₂,
apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _),
simpa using add_lt_add H₁ H₂
end
end complex
|
3595273f03d4b3f50f33ea44a3edfbe8fd361f74 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/geometry/manifold/algebra/smooth_functions.lean | 68020c6288b2b18941ee36ea27b669ad35199720 | [
"Apache-2.0"
] | permissive | mcncm/mathlib | 8d25099344d9d2bee62822cb9ed43aa3e09fa05e | fde3d78cadeec5ef827b16ae55664ef115e66f57 | refs/heads/master | 1,672,743,316,277 | 1,602,618,514,000 | 1,602,618,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,310 | lean | /-
Copyright © 2020 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nicolò Cavalleri
-/
import geometry.manifold.algebra.structures
import geometry.manifold.times_cont_mdiff_map
/-!
# Algebraic structures over smooth functions
In this file, we define instances of algebraic structures over smooth functions.
-/
noncomputable theory
open_locale manifold
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{E' : Type*} [normed_group E'] [normed_space 𝕜 E']
{H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H}
{H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
{N : Type*} [topological_space N] [charted_space H N] [smooth_manifold_with_corners I N]
namespace smooth_map
@[to_additive]
instance has_mul {G : Type*} [has_mul G] [topological_space G] [has_continuous_mul G]
[charted_space H' G] [has_smooth_mul I' G] :
has_mul C^∞⟮I, N; I', G⟯ :=
⟨λ f g, ⟨f * g, smooth_mul.comp (f.smooth.prod_mk g.smooth)⟩⟩
@[to_additive]
instance {G : Type*} [monoid G] [topological_space G]
[charted_space H' G] [smooth_manifold_with_corners I' G] :
has_one C^∞⟮I, N; I', G⟯ :=
⟨times_cont_mdiff_map.const (1 : G)⟩
end smooth_map
section group_structure
/-!
### Group structure
In this section we show that smooth functions valued in a Lie group inherit a group structure
under pointwise multiplication.
-/
@[to_additive]
instance smooth_map_semigroup {G : Type*} [semigroup G] [topological_space G]
[has_continuous_mul G] [charted_space H' G] [has_smooth_mul I' G] :
semigroup C^∞⟮I, N; I', G⟯ :=
{ mul_assoc := λ a b c, by ext; exact mul_assoc _ _ _,
..smooth_map.has_mul}
@[to_additive]
instance smooth_map_monoid {G : Type*} [monoid G] [topological_space G]
[has_continuous_mul G] [charted_space H' G] [has_smooth_mul I' G] :
monoid C^∞⟮I, N; I', G⟯ :=
{ one_mul := λ a, by ext; exact one_mul _,
mul_one := λ a, by ext; exact mul_one _,
..smooth_map_semigroup,
..smooth_map.has_one }
@[to_additive]
instance smooth_map_comm_monoid {G : Type*} [comm_monoid G] [topological_space G]
[has_continuous_mul G] [charted_space H' G] [has_smooth_mul I' G] :
comm_monoid C^∞⟮I, N; I', G⟯ :=
{ mul_comm := λ a b, by ext; exact mul_comm _ _,
..smooth_map_monoid,
..smooth_map.has_one }
@[to_additive]
instance smooth_map_group {G : Type*} [group G] [topological_space G] [topological_group G]
[charted_space H' G] [smooth_manifold_with_corners I' G] [lie_group I' G] :
group C^∞⟮I, N; I', G⟯ :=
{ inv := λ f, ⟨λ x, (f x)⁻¹, smooth_inv.comp f.smooth⟩,
mul_left_inv := λ a, by ext; exact mul_left_inv _,
..smooth_map_monoid }
@[to_additive]
instance smooth_map_comm_group {G : Type*} [comm_group G] [topological_space G]
[topological_group G] [charted_space H' G] [lie_group I' G] :
comm_group C^∞⟮I, N; I', G⟯ :=
{ ..smooth_map_group,
..smooth_map_comm_monoid }
end group_structure
section ring_structure
/-!
### Ring stucture
In this section we show that smooth functions valued in a smooth ring `R` inherit a ring structure
under pointwise multiplication.
-/
instance smooth_map_semiring {R : Type*} [semiring R] [topological_space R]
[topological_semiring R] [charted_space H' R] [smooth_semiring I' R] :
semiring C^∞⟮I, N; I', R⟯ :=
{ left_distrib := λ a b c, by ext; exact left_distrib _ _ _,
right_distrib := λ a b c, by ext; exact right_distrib _ _ _,
zero_mul := λ a, by ext; exact zero_mul _,
mul_zero := λ a, by ext; exact mul_zero _,
..smooth_map_add_comm_monoid,
..smooth_map_monoid }
instance smooth_map_ring {R : Type*} [ring R] [topological_space R]
[topological_ring R] [charted_space H' R] [smooth_ring I' R] :
ring C^∞⟮I, N; I', R⟯ :=
{ ..smooth_map_semiring,
..smooth_map_add_comm_group, }
instance smooth_map_comm_ring {R : Type*} [comm_ring R] [topological_space R]
[topological_ring R] [charted_space H' R] [smooth_ring I' R] :
comm_ring C^∞⟮I, N; I', R⟯ :=
{ ..smooth_map_semiring,
..smooth_map_add_comm_group,
..smooth_map_comm_monoid,}
end ring_structure
section semimodule_structure
/-!
### Semiodule stucture
In this section we show that smooth functions valued in a vector space `M` over a normed
field `𝕜` inherit a vector space structure.
-/
instance smooth_map_has_scalar
{V : Type*} [normed_group V] [normed_space 𝕜 V] :
has_scalar 𝕜 C^∞⟮I, N; 𝓘(𝕜, V), V⟯ :=
⟨λ r f, ⟨r • f, smooth_const.smul f.smooth⟩⟩
instance smooth_map_semimodule
{V : Type*} [normed_group V] [normed_space 𝕜 V] :
vector_space 𝕜 C^∞⟮I, N; 𝓘(𝕜, V), V⟯ :=
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 𝕜 (f x), }
end semimodule_structure
section algebra_structure
/-!
### Algebra structure
In this section we show that smooth functions valued in a normed algebra `A` over a normed field `𝕜`
inherit an algebra structure.
-/
variables {A : Type*} [normed_ring A] [normed_algebra 𝕜 A] [smooth_ring 𝓘(𝕜, A) A]
/-- Smooth constant functions as a `ring_hom`. -/
def smooth_map.C : 𝕜 →+* C^∞⟮I, N; 𝓘(𝕜, A), A⟯ :=
{ to_fun := λ c : 𝕜, ⟨λ x, ((algebra_map 𝕜 A) c), smooth_const⟩,
map_one' := by ext x; exact (algebra_map 𝕜 A).map_one,
map_mul' := λ c₁ c₂, by ext x; exact (algebra_map 𝕜 A).map_mul _ _,
map_zero' := by ext x; exact (algebra_map 𝕜 A).map_zero,
map_add' := λ c₁ c₂, by ext x; exact (algebra_map 𝕜 A).map_add _ _ }
instance : algebra 𝕜 C^∞⟮I, N; 𝓘(𝕜, A), A⟯ :=
{ smul := λ r f,
⟨r • f, smooth_const.smul f.smooth⟩,
to_ring_hom := smooth_map.C,
commutes' := λ c f, by ext x; exact algebra.commutes' _ _,
smul_def' := λ c f, by ext x; exact algebra.smul_def' _ _,
..smooth_map_semiring }
end algebra_structure
section module_over_continuous_functions
/-!
### Structure as module over scalar functions
If `V` is a module over `𝕜`, then we show that the space of smooth functions from `N` to `V`
is naturally a vector space over the ring of smooth functions from `N` to `𝕜`. -/
instance smooth_map_has_scalar'
{V : Type*} [normed_group V] [normed_space 𝕜 V] :
has_scalar C^∞⟮I, N; 𝓘(𝕜), 𝕜⟯ C^∞⟮I, N; 𝓘(𝕜, V), V⟯ :=
⟨λ f g, ⟨λ x, (f x) • (g x), (smooth.smul f.2 g.2)⟩⟩
instance smooth_map_module'
{V : Type*} [normed_group V] [normed_space 𝕜 V] :
semimodule C^∞⟮I, N; 𝓘(𝕜), 𝕜⟯ C^∞⟮I, N; 𝓘(𝕜, V), V⟯ :=
{ 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 𝕜 (f x),
zero_smul := λ f, by ext x; exact zero_smul _ _,
smul_zero := λ r, by ext x; exact smul_zero _, }
end module_over_continuous_functions
|
3796a0d552b0a1619cf775bf259a28d94f48860a | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/model_theory/elementary_maps.lean | 376d30fcf96b91f034fd82631c519106800f6543 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 6,880 | lean | /-
Copyright (c) 2022 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn
-/
import model_theory.basic
/-!
#Elementary Maps Between First-Order Structures
## Main Definitions
* A `first_order.language.elementary_embedding` is an embedding that commutes with the
realizations of formulas.
*
-/
open_locale first_order
namespace first_order
namespace language
open Structure
variables (L : language) (M : Type*) (N : Type*) {P : Type*} {Q : Type*}
variables [L.Structure M] [L.Structure N] [L.Structure P] [L.Structure Q]
/-- An elementary embedding of first-order structures is an embedding that commutes with the
realizations of formulas. -/
structure elementary_embedding :=
(to_fun : M → N)
(map_formula' : ∀{n} (φ : L.formula (fin n)) (x : fin n → M),
realize_formula N φ (to_fun ∘ x) ↔ realize_formula M φ x . obviously)
localized "notation A ` ↪ₑ[`:25 L `] ` B := L.elementary_embedding A B" in first_order
variables {L} {M} {N}
namespace elementary_embedding
instance has_coe_to_fun : has_coe_to_fun (M ↪ₑ[L] N) (λ _, M → N) :=
⟨λ f, f.to_fun⟩
@[simp] lemma map_formula (f : M ↪ₑ[L] N) {α : Type} [fintype α] (φ : L.formula α)
(x : α → M) :
realize_formula N φ (f ∘ x) ↔ realize_formula M φ x :=
begin
have g := fintype.equiv_fin α,
have h := f.map_formula' (φ.relabel g) (x ∘ g.symm),
rw [realize_formula_relabel, realize_formula_relabel,
function.comp.assoc x g.symm g, g.symm_comp_self, function.comp.right_id] at h,
rw [← h, iff_eq_eq],
congr,
ext y,
simp,
end
@[simp] lemma map_fun (φ : M ↪ₑ[L] N) {n : ℕ} (f : L.functions n) (x : fin n → M) :
φ (fun_map f x) = fun_map f (φ ∘ x) :=
begin
have h := φ.map_formula (formula.graph f) (fin.snoc x (fun_map f x)),
rw [realize_graph, fin.comp_snoc, realize_graph] at h,
rw [eq_comm, h]
end
@[simp] lemma map_const (φ : M ↪ₑ[L] N) (c : L.const) : φ c = c :=
(φ.map_fun c fin.elim0).trans (congr rfl (funext fin.elim0))
@[simp] lemma map_rel (φ : M ↪ₑ[L] N) {n : ℕ} (r : L.relations n) (x : fin n → M) :
rel_map r (φ ∘ x) ↔ rel_map r x :=
begin
have h := φ.map_formula (bd_rel r (var ∘ sum.inl)) x,
exact h
end
@[simp] lemma injective (φ : M ↪ₑ[L] N) :
function.injective φ :=
begin
intros x y,
have h := φ.map_formula (formula.equal (var 0) (var 1) : L.formula (fin 2))
(λ i, if i = 0 then x else y),
rw [realize_equal, realize_equal] at h,
simp only [nat.one_ne_zero, realize_term, fin.one_eq_zero_iff, if_true, eq_self_iff_true,
function.comp_app, if_false] at h,
exact h.1,
end
/-- An elementary embedding is also a first-order embedding. -/
def to_embedding (f : M ↪ₑ[L] N) : M ↪[L] N :=
{ to_fun := f,
inj' := f.injective, }
/-- An elementary embedding is also a first-order homomorphism. -/
def to_hom (f : M ↪ₑ[L] N) : M →[L] N :=
{ to_fun := f }
@[simp] lemma to_embedding_to_hom (f : M ↪ₑ[L] N) : f.to_embedding.to_hom = f.to_hom := rfl
@[simp]
lemma coe_to_hom {f : M ↪ₑ[L] N} : (f.to_hom : M → N) = (f : M → N) := rfl
@[simp] lemma coe_to_embedding (f : M ↪ₑ[L] N) : (f.to_embedding : M → N) = (f : M → N) := rfl
lemma coe_injective : @function.injective (M ↪ₑ[L] N) (M → N) coe_fn
| f g h :=
begin
cases f,
cases g,
simp only,
ext x,
exact function.funext_iff.1 h x,
end
@[ext]
lemma ext ⦃f g : M ↪ₑ[L] N⦄ (h : ∀ x, f x = g x) : f = g :=
coe_injective (funext h)
lemma ext_iff {f g : M ↪ₑ[L] N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, ext h⟩
variables (L) (M)
/-- The identity elementary embedding from a structure to itself -/
@[refl] def refl : M ↪ₑ[L] M :=
{ to_fun := id }
variables {L} {M}
instance : inhabited (M ↪ₑ[L] M) := ⟨refl L M⟩
@[simp] lemma refl_apply (x : M) :
refl L M x = x := rfl
/-- Composition of elementary embeddings -/
@[trans] def comp (hnp : N ↪ₑ[L] P) (hmn : M ↪ₑ[L] N) : M ↪ₑ[L] P :=
{ to_fun := hnp ∘ hmn }
@[simp] lemma comp_apply (g : N ↪ₑ[L] P) (f : M ↪ₑ[L] N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of elementary embeddings is associative. -/
lemma comp_assoc (f : M ↪ₑ[L] N) (g : N ↪ₑ[L] P) (h : P ↪ₑ[L] Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
end elementary_embedding
namespace equiv
/-- A first-order equivalence is also an elementary embedding. -/
def to_elementary_embedding (f : M ≃[L] N) : M ↪ₑ[L] N :=
{ to_fun := f }
@[simp] lemma to_elementary_embedding_to_embedding (f : M ≃[L] N) :
f.to_elementary_embedding.to_embedding = f.to_embedding := rfl
@[simp] lemma coe_to_elementary_embedding (f : M ≃[L] N) :
(f.to_elementary_embedding : M → N) = (f : M → N) := rfl
end equiv
namespace substructure
/-- A substructure is elementary when every formula applied to a tuple in the subtructure
agrees with its value in the overall structure. -/
def is_elementary (S : L.substructure M) : Prop :=
∀{n} (φ : L.formula (fin n)) (x : fin n → S), realize_formula M φ (coe ∘ x) ↔ realize_formula S φ x
end substructure
variables (L) (M)
/-- An elementary substructure is one in which every formula applied to a tuple in the subtructure
agrees with its value in the overall structure. -/
structure elementary_substructure :=
(to_substructure : L.substructure M)
(is_elementary' : to_substructure.is_elementary)
variables {L} {M}
namespace elementary_substructure
instance : has_coe (L.elementary_substructure M) (L.substructure M) :=
⟨elementary_substructure.to_substructure⟩
instance : set_like (L.elementary_substructure M) M :=
⟨λ x, x.to_substructure.carrier, λ ⟨⟨s, hs1⟩, hs2⟩ ⟨⟨t, ht1⟩, ht2⟩ h, begin
congr,
exact h,
end⟩
@[simp] lemma is_elementary (S : L.elementary_substructure M) :
(S : L.substructure M).is_elementary := S.is_elementary'
/-- The natural embedding of an `L.substructure` of `M` into `M`. -/
def subtype (S : L.elementary_substructure M) : S ↪ₑ[L] M :=
{ to_fun := coe,
map_formula' := λ n, S.is_elementary }
@[simp] theorem coe_subtype {S : L.elementary_substructure M} : ⇑S.subtype = coe := rfl
/-- The substructure `M` of the structure `M` is elementary. -/
instance : has_top (L.elementary_substructure M) :=
⟨⟨⊤, λ n φ x, begin
rw formula at φ,
rw [realize_formula, realize_formula, realize_bounded_formula_top, iff_eq_eq],
exact congr rfl (funext fin_zero_elim),
end⟩⟩
instance : inhabited (L.elementary_substructure M) := ⟨⊤⟩
@[simp] lemma mem_top (x : M) : x ∈ (⊤ : L.elementary_substructure M) := set.mem_univ x
@[simp] lemma coe_top : ((⊤ : L.elementary_substructure M) : set M) = set.univ := rfl
end elementary_substructure
end language
end first_order
|
2f09c6506979a9a3ead7c502eeea684a5a993ae7 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/geometry/manifold/algebra/lie_group.lean | 7ae2fe920fc45f4931d560a2e7ef2f926ee4d863 | [] | 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 | 11,916 | lean | /-
Copyright © 2020 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Nicolò Cavalleri.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.geometry.manifold.algebra.monoid
import Mathlib.PostPort
universes u_1 u_2 u_3 u_4 l u_5 u_6 u_7 u_8
namespace Mathlib
/-!
# Lie groups
A Lie group is a group that is also a smooth manifold, in which the group operations of
multiplication and inversion are smooth maps. Smoothness of the group multiplication means that
multiplication is a smooth mapping of the product manifold `G` × `G` into `G`.
Note that, since a manifold here is not second-countable and Hausdorff a Lie group here is not
guaranteed to be second-countable (even though it can be proved it is Hausdorff). Note also that Lie
groups here are not necessarily finite dimensional.
## Main definitions and statements
* `lie_add_group I G` : a Lie additive group where `G` is a manifold on the model with corners `I`.
* `lie_group I G` : a Lie multiplicative group where `G` is a manifold on the model with
corners `I`.
* `lie_add_group_morphism I I' G G'` : morphism of addittive Lie groups
* `lie_group_morphism I I' G G'` : morphism of Lie groups
* `lie_add_group_core I G` : allows to define a Lie additive group without first proving
it is a topological additive group.
* `lie_group_core I G` : allows to define a Lie group without first proving
it is a topological group.
* `reals_lie_group` : real numbers are a Lie group
## Implementation notes
A priori, a Lie group here is a manifold with corners.
The definition of Lie group cannot require `I : model_with_corners 𝕜 E E` with the same space as the
model space and as the model vector space, as one might hope, beause in the product situation,
the model space is `model_prod E E'` and the model vector space is `E × E'`, which are not the same,
so the definition does not apply. Hence the definition should be more general, allowing
`I : model_with_corners 𝕜 E H`.
-/
/-- A Lie (additive) group is a group and a smooth manifold at the same time in which
the addition and negation operations are smooth. -/
class lie_add_group {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {H : Type u_2} [topological_space H] {E : Type u_3} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type u_4) [add_group G] [topological_space G] [topological_add_group G] [charted_space H G]
extends has_smooth_add I G
where
smooth_neg : smooth I I fun (a : G) => -a
/-- A Lie group is a group and a smooth manifold at the same time in which
the multiplication and inverse operations are smooth. -/
class lie_group {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {H : Type u_2} [topological_space H] {E : Type u_3} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type u_4) [group G] [topological_space G] [topological_group G] [charted_space H G]
extends has_smooth_mul I G
where
smooth_inv : smooth I I fun (a : G) => a⁻¹
theorem smooth_pow {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {H : Type u_2} [topological_space H] {E : Type u_3} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type u_5} [topological_space G] [charted_space H G] [group G] [topological_group G] [lie_group I G] (n : ℕ) : smooth I I fun (a : G) => a ^ n := sorry
theorem smooth_inv {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {H : Type u_2} [topological_space H] {E : Type u_3} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type u_5} [topological_space G] [charted_space H G] [group G] [topological_group G] [lie_group I G] : smooth I I fun (x : G) => x⁻¹ :=
lie_group.smooth_inv
theorem smooth.neg {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {H : Type u_2} [topological_space H] {E : Type u_3} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type u_5} [topological_space G] [charted_space H G] [add_group G] [topological_add_group G] [lie_add_group I G] {E' : Type u_6} [normed_group E'] [normed_space 𝕜 E'] {H' : Type u_7} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M : Type u_8} [topological_space M] [charted_space H' M] [smooth_manifold_with_corners I' M] {f : M → G} (hf : smooth I' I f) : smooth I' I fun (x : M) => -f x :=
times_cont_mdiff.comp lie_add_group.smooth_neg hf
theorem smooth_on.neg {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {H : Type u_2} [topological_space H] {E : Type u_3} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type u_5} [topological_space G] [charted_space H G] [add_group G] [topological_add_group G] [lie_add_group I G] {E' : Type u_6} [normed_group E'] [normed_space 𝕜 E'] {H' : Type u_7} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M : Type u_8} [topological_space M] [charted_space H' M] [smooth_manifold_with_corners I' M] {f : M → G} {s : set M} (hf : smooth_on I' I f s) : smooth_on I' I (fun (x : M) => -f x) s :=
smooth.comp_smooth_on smooth_neg hf
/- Instance of product group -/
protected instance prod.lie_group {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {H : Type u_2} [topological_space H] {E : Type u_3} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type u_4} [topological_space G] [charted_space H G] [group G] [topological_group G] [lie_group I G] {E' : Type u_5} [normed_group E'] [normed_space 𝕜 E'] {H' : Type u_6} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {G' : Type u_7} [topological_space G'] [charted_space H' G'] [group G'] [topological_group G'] [lie_group I' G'] : lie_group (model_with_corners.prod I I') (G × G') :=
lie_group.mk has_smooth_mul.compatible has_smooth_mul.smooth_mul
(smooth.prod_mk (smooth.inv smooth_fst) (smooth.inv smooth_snd))
/-- Morphism of additive Lie groups. -/
structure lie_add_group_morphism {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {E' : Type u_3} [normed_group E'] [normed_space 𝕜 E'] (I : model_with_corners 𝕜 E E) (I' : model_with_corners 𝕜 E' E') (G : Type u_4) [topological_space G] [charted_space E G] [add_group G] [topological_add_group G] [lie_add_group I G] (G' : Type u_5) [topological_space G'] [charted_space E' G'] [add_group G'] [topological_add_group G'] [lie_add_group I' G']
extends smooth_add_monoid_morphism I I' G G'
where
/-- Morphism of Lie groups. -/
structure lie_group_morphism {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {E' : Type u_3} [normed_group E'] [normed_space 𝕜 E'] (I : model_with_corners 𝕜 E E) (I' : model_with_corners 𝕜 E' E') (G : Type u_4) [topological_space G] [charted_space E G] [group G] [topological_group G] [lie_group I G] (G' : Type u_5) [topological_space G'] [charted_space E' G'] [group G'] [topological_group G'] [lie_group I' G']
extends smooth_monoid_morphism I I' G G'
where
protected instance lie_group_morphism.has_one {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {E' : Type u_3} [normed_group E'] [normed_space 𝕜 E'] {I : model_with_corners 𝕜 E E} {I' : model_with_corners 𝕜 E' E'} {G : Type u_4} [topological_space G] [charted_space E G] [group G] [topological_group G] [lie_group I G] {G' : Type u_5} [topological_space G'] [charted_space E' G'] [group G'] [topological_group G'] [lie_group I' G'] : HasOne (lie_group_morphism I I' G G') :=
{ one := lie_group_morphism.mk (smooth_monoid_morphism.mk (smooth_monoid_morphism.to_monoid_hom 1) sorry) }
protected instance lie_add_group_morphism.inhabited {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {E' : Type u_3} [normed_group E'] [normed_space 𝕜 E'] {I : model_with_corners 𝕜 E E} {I' : model_with_corners 𝕜 E' E'} {G : Type u_4} [topological_space G] [charted_space E G] [add_group G] [topological_add_group G] [lie_add_group I G] {G' : Type u_5} [topological_space G'] [charted_space E' G'] [add_group G'] [topological_add_group G'] [lie_add_group I' G'] : Inhabited (lie_add_group_morphism I I' G G') :=
{ default := 0 }
protected instance lie_add_group_morphism.has_coe_to_fun {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {E' : Type u_3} [normed_group E'] [normed_space 𝕜 E'] {I : model_with_corners 𝕜 E E} {I' : model_with_corners 𝕜 E' E'} {G : Type u_4} [topological_space G] [charted_space E G] [add_group G] [topological_add_group G] [lie_add_group I G] {G' : Type u_5} [topological_space G'] [charted_space E' G'] [add_group G'] [topological_add_group G'] [lie_add_group I' G'] : has_coe_to_fun (lie_add_group_morphism I I' G G') :=
has_coe_to_fun.mk (fun (a : lie_add_group_morphism I I' G G') => G → G')
fun (a : lie_add_group_morphism I I' G G') =>
add_monoid_hom.to_fun
(smooth_add_monoid_morphism.to_add_monoid_hom (lie_add_group_morphism.to_smooth_add_monoid_morphism a))
/-- Sometimes one might want to define a Lie additive group `G` without having proved previously
that `G` is a topological additive group. In such case it is possible to use `lie_add_group_core`
that does not require such instance, and then get a Lie group by invoking `to_lie_add_group`. -/
structure lie_add_group_core {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E E) (G : Type u_3) [add_group G] [topological_space G] [charted_space E G]
extends smooth_manifold_with_corners I G
where
smooth_add : smooth (model_with_corners.prod I I) I fun (p : G × G) => prod.fst p + prod.snd p
smooth_neg : smooth I I fun (a : G) => -a
/-- Sometimes one might want to define a Lie group `G` without having proved previously that `G` is
a topological group. In such case it is possible to use `lie_group_core` that does not require such
instance, and then get a Lie group by invoking `to_lie_group` defined below. -/
structure lie_group_core {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E E) (G : Type u_3) [group G] [topological_space G] [charted_space E G]
extends smooth_manifold_with_corners I G
where
smooth_mul : smooth (model_with_corners.prod I I) I fun (p : G × G) => prod.fst p * prod.snd p
smooth_inv : smooth I I fun (a : G) => a⁻¹
-- The linter does not recognize that the followings are structure projections, disable it
namespace lie_group_core
protected theorem Mathlib.lie_add_group_core.to_topological_add_group {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E E} {G : Type u_4} [topological_space G] [charted_space E G] [add_group G] (c : lie_add_group_core I G) : topological_add_group G :=
topological_add_group.mk (times_cont_mdiff.continuous (lie_add_group_core.smooth_neg c))
protected theorem to_lie_group {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E E} {G : Type u_4} [topological_space G] [charted_space E G] [group G] (c : lie_group_core I G) : lie_group I G :=
lie_group.mk smooth_manifold_with_corners.compatible (smooth_mul c) (smooth_inv c)
end lie_group_core
/-! ### Normed spaces are Lie groups -/
protected instance normed_space_lie_group {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] : lie_add_group (model_with_corners_self 𝕜 E) E := sorry
|
9a9d0a2f5100919e66f2f2e383ab89103bf000a5 | 947b78d97130d56365ae2ec264df196ce769371a | /stage0/src/Init/Control/EState.lean | 551eb9f722d63d595eef69570b0bd9bc108a43e8 | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,141 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Control.State
import Init.Control.Except
universes u v
namespace EStateM
inductive Result (ε σ α : Type u)
| ok : α → σ → Result
| error : ε → σ → Result
variables {ε σ α : Type u}
protected def Result.toString [HasToString ε] [HasToString α] : Result ε σ α → String
| Result.ok a _ => "ok: " ++ toString a
| Result.error e _ => "error: " ++ toString e
protected def Result.repr [HasRepr ε] [HasRepr α] : Result ε σ α → String
| Result.error e _ => "(error " ++ repr e ++ ")"
| Result.ok a _ => "(ok " ++ repr a ++ ")"
instance Result.hasToString [HasToString ε] [HasToString α] : HasToString (Result ε σ α) := ⟨Result.toString⟩
instance Result.hasRepr [HasRepr ε] [HasRepr α] : HasRepr (Result ε σ α) := ⟨Result.repr⟩
instance Result.inhabited [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) := ⟨Result.error (arbitrary _) (arbitrary _)⟩
end EStateM
def EStateM (ε σ α : Type u) := σ → EStateM.Result ε σ α
namespace EStateM
variables {ε σ α β : Type u}
instance [Inhabited ε] : Inhabited (EStateM ε σ α) :=
⟨fun s => Result.error (arbitrary ε) s⟩
@[inline] protected def pure (a : α) : EStateM ε σ α :=
fun s => Result.ok a s
@[inline] protected def set (s : σ) : EStateM ε σ PUnit :=
fun _ => Result.ok ⟨⟩ s
@[inline] protected def get : EStateM ε σ σ :=
fun s => Result.ok s s
@[inline] protected def modifyGet (f : σ → α × σ) : EStateM ε σ α :=
fun s =>
match f s with
| (a, s) => Result.ok a s
@[inline] protected def throw (e : ε) : EStateM ε σ α :=
fun s => Result.error e s
/-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/
class Backtrackable (δ : outParam $ Type u) (σ : Type u) :=
(save : σ → δ)
(restore : σ → δ → σ)
@[inline] protected def catch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α :=
fun s =>
let d := Backtrackable.save s;
match x s with
| Result.error e s => handle e (Backtrackable.restore s d)
| ok => ok
@[inline] protected def orelse {δ} [Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) : EStateM ε σ α :=
fun s =>
let d := Backtrackable.save s;
match x₁ s with
| Result.error _ s => x₂ (Backtrackable.restore s d)
| ok => ok
/-- Alternative orelse operator that allows to select which exception should be used.
The default is to use the first exception since the standard `orelse` uses the second. -/
@[inline] protected def orelse' {δ} [Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) (useFirstEx := true) : EStateM ε σ α :=
fun s =>
let d := Backtrackable.save s;
match x₁ s with
| Result.error e₁ s₁ =>
match x₂ (Backtrackable.restore s₁ d) with
| Result.error e₂ s₂ => Result.error (if useFirstEx then e₁ else e₂) s₂
| ok => ok
| ok => ok
@[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α :=
fun s => match x s with
| Result.error e s => Result.error (f e) s
| Result.ok a s => Result.ok a s
instance monadExceptAdapter {ε ε' σ} : MonadExceptAdapter ε ε' (EStateM ε σ) (EStateM ε' σ) :=
⟨fun α f x => adaptExcept f x⟩
@[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β :=
fun s => match x s with
| Result.ok a s => f a s
| Result.error e s => Result.error e s
@[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β :=
fun s => match x s with
| Result.ok a s => Result.ok (f a) s
| Result.error e s => Result.error e s
@[inline] protected def seqRight (x : EStateM ε σ PUnit) (y : EStateM ε σ β) : EStateM ε σ β :=
fun s => match x s with
| Result.ok _ s => y s
| Result.error e s => Result.error e s
instance : Monad (EStateM ε σ) :=
{ bind := @EStateM.bind _ _, pure := @EStateM.pure _ _, map := @EStateM.map _ _, seqRight := @EStateM.seqRight _ _ }
instance {δ} [Backtrackable δ σ] : HasOrelse (EStateM ε σ α) :=
{ orelse := @EStateM.orelse _ _ _ _ _ }
instance : MonadStateOf σ (EStateM ε σ) :=
{ set := @EStateM.set _ _, get := @EStateM.get _ _, modifyGet := @EStateM.modifyGet _ _ }
instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) :=
{ throw := @EStateM.throw _ _, catch := @EStateM.catch _ _ _ _ }
instance : MonadFinally (EStateM ε σ) :=
{ finally' := fun α β x h s =>
let r := x s;
match r with
| Result.ok a s => match h (some a) s with
| Result.ok b s => Result.ok (a, b) s
| Result.error e s => Result.error e s
| Result.error e₁ s => match h none s with
| Result.ok _ s => Result.error e₁ s
| Result.error e₂ s => Result.error e₂ s }
@[inline] def adaptState {σ₁ σ₂} (split : σ → σ₁ × σ₂) (merge : σ₁ → σ₂ → σ) (x : EStateM ε σ₁ α) : EStateM ε σ α :=
fun s =>
let (s₁, s₂) := split s;
match x s₁ with
| Result.ok a s₁ => Result.ok a (merge s₁ s₂)
| Result.error e s₁ => Result.error e (merge s₁ s₂)
instance {ε σ σ'} : MonadStateAdapter σ σ' (EStateM ε σ) (EStateM ε σ') :=
⟨fun σ'' α => EStateM.adaptState⟩
@[inline] def fromStateM {ε σ α : Type} (x : StateM σ α) : EStateM ε σ α :=
fun s =>
match x.run s with
| (a, s') => EStateM.Result.ok a s'
@[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α :=
x s
@[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α :=
match run x s with
| Result.ok v _ => some v
| Result.error _ _ => none
@[inline] def dummySave : σ → PUnit :=
fun _ => ⟨⟩
@[inline] def dummyRestore : σ → PUnit → σ :=
fun s _ => s
/- Dummy default instance -/
instance nonBacktrackable : Backtrackable PUnit σ :=
{ save := dummySave,
restore := dummyRestore }
end EStateM
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.