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
b4d1fa092b416c42419d0c1d438f217bcd382f46
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/constructions.lean
565bf50b7a7b704c144f46b222d639b5607b8c72
[ "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
58,023
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.maps import topology.locally_finite import order.filter.pi /-! # Constructions of new topological spaces from old ones This file constructs products, sums, subtypes and quotients of topological spaces and sets up their basic theory, such as criteria for maps into or out of these constructions to be continuous; descriptions of the open sets, neighborhood filters, and generators of these constructions; and their behavior with respect to embeddings and other specific classes of maps. ## Implementation note The constructed topologies are defined using induced and coinduced topologies along with the complete lattice structure on topologies. Their universal properties (for example, a map `X → Y × Z` is continuous if and only if both projections `X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of continuity. With more work we can also extract descriptions of the open sets, neighborhood filters and so on. ## Tags product, sum, disjoint union, subspace, quotient space -/ noncomputable theory open topological_space set filter function open_locale classical topological_space filter universes u v variables {α : Type u} {β : Type v} {γ δ ε ζ : Type*} section constructions instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := induced coe t instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) := coinduced (quot.mk r) t instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) := coinduced quotient.mk t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := induced prod.fst t₁ ⊓ induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨆a, coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨅a, induced (λf, f a) (t₂ a) instance ulift.topological_space [t : topological_space α] : topological_space (ulift.{v u} α) := t.induced ulift.down /-! ### `additive`, `multiplicative` The topology on those type synonyms is inherited without change. -/ section variables [topological_space α] open additive multiplicative instance : topological_space (additive α) := ‹topological_space α› instance : topological_space (multiplicative α) := ‹topological_space α› instance [discrete_topology α] : discrete_topology (additive α) := ‹discrete_topology α› instance [discrete_topology α] : discrete_topology (multiplicative α) := ‹discrete_topology α› lemma continuous_of_mul : continuous (of_mul : α → additive α) := continuous_id lemma continuous_to_mul : continuous (to_mul : additive α → α) := continuous_id lemma continuous_of_add : continuous (of_add : α → multiplicative α) := continuous_id lemma continuous_to_add : continuous (to_add : multiplicative α → α) := continuous_id lemma is_open_map_of_mul : is_open_map (of_mul : α → additive α) := is_open_map.id lemma is_open_map_to_mul : is_open_map (to_mul : additive α → α) := is_open_map.id lemma is_open_map_of_add : is_open_map (of_add : α → multiplicative α) := is_open_map.id lemma is_open_map_to_add : is_open_map (to_add : multiplicative α → α) := is_open_map.id lemma is_closed_map_of_mul : is_closed_map (of_mul : α → additive α) := is_closed_map.id lemma is_closed_map_to_mul : is_closed_map (to_mul : additive α → α) := is_closed_map.id lemma is_closed_map_of_add : is_closed_map (of_add : α → multiplicative α) := is_closed_map.id lemma is_closed_map_to_add : is_closed_map (to_add : multiplicative α → α) := is_closed_map.id lemma nhds_of_mul (a : α) : 𝓝 (of_mul a) = map of_mul (𝓝 a) := by { unfold nhds, refl, } lemma nhds_of_add (a : α) : 𝓝 (of_add a) = map of_add (𝓝 a) := by { unfold nhds, refl, } lemma nhds_to_mul (a : additive α) : 𝓝 (to_mul a) = map to_mul (𝓝 a) := by { unfold nhds, refl, } lemma nhds_to_add (a : multiplicative α) : 𝓝 (to_add a) = map to_add (𝓝 a) := by { unfold nhds, refl, } end /-! ### Order dual The topology on this type synonym is inherited without change. -/ section variables [topological_space α] open order_dual instance : topological_space αᵒᵈ := ‹topological_space α› instance [discrete_topology α] : discrete_topology (αᵒᵈ) := ‹discrete_topology α› lemma continuous_to_dual : continuous (to_dual : α → αᵒᵈ) := continuous_id lemma continuous_of_dual : continuous (of_dual : αᵒᵈ → α) := continuous_id lemma is_open_map_to_dual : is_open_map (to_dual : α → αᵒᵈ) := is_open_map.id lemma is_open_map_of_dual : is_open_map (of_dual : αᵒᵈ → α) := is_open_map.id lemma is_closed_map_to_dual : is_closed_map (to_dual : α → αᵒᵈ) := is_closed_map.id lemma is_closed_map_of_dual : is_closed_map (of_dual : αᵒᵈ → α) := is_closed_map.id lemma nhds_to_dual (a : α) : 𝓝 (to_dual a) = map to_dual (𝓝 a) := by { unfold nhds, refl, } lemma nhds_of_dual (a : α) : 𝓝 (of_dual a) = map of_dual (𝓝 a) := by { unfold nhds, refl, } end lemma quotient.preimage_mem_nhds [topological_space α] [s : setoid α] {V : set $ quotient s} {a : α} (hs : V ∈ 𝓝 (quotient.mk a)) : quotient.mk ⁻¹' V ∈ 𝓝 a := preimage_nhds_coinduced hs /-- The image of a dense set under `quotient.mk` is a dense set. -/ lemma dense.quotient [setoid α] [topological_space α] {s : set α} (H : dense s) : dense (quotient.mk '' s) := (surjective_quotient_mk α).dense_range.dense_image continuous_coinduced_rng H /-- The composition of `quotient.mk` and a function with dense range has dense range. -/ lemma dense_range.quotient [setoid α] [topological_space α] {f : β → α} (hf : dense_range f) : dense_range (quotient.mk ∘ f) := (surjective_quotient_mk α).dense_range.comp hf continuous_coinduced_rng instance {p : α → Prop} [topological_space α] [discrete_topology α] : discrete_topology (subtype p) := ⟨bot_unique $ assume s hs, ⟨coe '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.coe_injective)⟩⟩ instance sum.discrete_topology [topological_space α] [topological_space β] [hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) := ⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩ instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)] [h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) := ⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩ section topα variable [topological_space α] /- The 𝓝 filter and the subspace topology. -/ theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 (a : α), coe ⁻¹' u ⊆ t := mem_nhds_induced coe a t theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) : 𝓝 a = comap coe (𝓝 (a : α)) := nhds_induced coe a lemma nhds_within_subtype_eq_bot_iff {s t : set α} {x : s} : 𝓝[(coe : s → α) ⁻¹' t] x = ⊥ ↔ 𝓝[t] (x : α) ⊓ 𝓟 s = ⊥ := by rw [inf_principal_eq_bot_iff_comap, nhds_within, nhds_within, comap_inf, comap_principal, nhds_induced] lemma nhds_ne_subtype_eq_bot_iff {S : set α} {x : S} : 𝓝[{x}ᶜ] x = ⊥ ↔ 𝓝[{x}ᶜ] (x : α) ⊓ 𝓟 S = ⊥ := by rw [← nhds_within_subtype_eq_bot_iff, preimage_compl, ← image_singleton, subtype.coe_injective.preimage_image ] lemma nhds_ne_subtype_ne_bot_iff {S : set α} {x : S} : (𝓝[{x}ᶜ] x).ne_bot ↔ (𝓝[{x}ᶜ] (x : α) ⊓ 𝓟 S).ne_bot := by rw [ne_bot_iff, ne_bot_iff, not_iff_not, nhds_ne_subtype_eq_bot_iff] lemma discrete_topology_subtype_iff {S : set α} : discrete_topology S ↔ ∀ x ∈ S, 𝓝[≠] x ⊓ 𝓟 S = ⊥ := by simp_rw [discrete_topology_iff_nhds_ne, set_coe.forall', nhds_ne_subtype_eq_bot_iff] end topα /-- A type synonym equiped with the topology whose open sets are the empty set and the sets with finite complements. -/ def cofinite_topology (α : Type*) := α namespace cofinite_topology /-- The identity equivalence between `α` and `cofinite_topology α`. -/ def of : α ≃ cofinite_topology α := equiv.refl α instance [inhabited α] : inhabited (cofinite_topology α) := { default := of default } instance : topological_space (cofinite_topology α) := { is_open := λ s, s.nonempty → set.finite sᶜ, is_open_univ := by simp, is_open_inter := λ s t, begin rintros hs ht ⟨x, hxs, hxt⟩, rw compl_inter, exact (hs ⟨x, hxs⟩).union (ht ⟨x, hxt⟩), end, is_open_sUnion := begin rintros s h ⟨x, t, hts, hzt⟩, rw set.compl_sUnion, exact set.finite.sInter (mem_image_of_mem _ hts) (h t hts ⟨x, hzt⟩), end } lemma is_open_iff {s : set (cofinite_topology α)} : is_open s ↔ (s.nonempty → (sᶜ).finite) := iff.rfl lemma is_open_iff' {s : set (cofinite_topology α)} : is_open s ↔ (s = ∅ ∨ (sᶜ).finite) := by simp only [is_open_iff, nonempty_iff_ne_empty, or_iff_not_imp_left] lemma is_closed_iff {s : set (cofinite_topology α)} : is_closed s ↔ s = univ ∨ s.finite := by simp [← is_open_compl_iff, is_open_iff'] lemma nhds_eq (a : cofinite_topology α) : 𝓝 a = pure a ⊔ cofinite := begin ext U, rw mem_nhds_iff, split, { rintro ⟨V, hVU, V_op, haV⟩, exact mem_sup.mpr ⟨hVU haV, mem_of_superset (V_op ⟨_, haV⟩) hVU⟩ }, { rintros ⟨hU : a ∈ U, hU' : (Uᶜ).finite⟩, exact ⟨U, subset.rfl, λ h, hU', hU⟩ } end lemma mem_nhds_iff {a : cofinite_topology α} {s : set (cofinite_topology α)} : s ∈ 𝓝 a ↔ a ∈ s ∧ sᶜ.finite := by simp [nhds_eq] end cofinite_topology end constructions section prod variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] [topological_space ε] [topological_space ζ] @[continuity] lemma continuous_fst : continuous (@prod.fst α β) := continuous_inf_dom_left continuous_induced_dom /-- Postcomposing `f` with `prod.fst` is continuous -/ lemma continuous.fst {f : α → β × γ} (hf : continuous f) : continuous (λ a : α, (f a).1) := continuous_fst.comp hf /-- Precomposing `f` with `prod.fst` is continuous -/ lemma continuous.fst' {f : α → γ} (hf : continuous f) : continuous (λ x : α × β, f x.fst) := hf.comp continuous_fst lemma continuous_at_fst {p : α × β} : continuous_at prod.fst p := continuous_fst.continuous_at /-- Postcomposing `f` with `prod.fst` is continuous at `x` -/ lemma continuous_at.fst {f : α → β × γ} {x : α} (hf : continuous_at f x) : continuous_at (λ a : α, (f a).1) x := continuous_at_fst.comp hf /-- Precomposing `f` with `prod.fst` is continuous at `(x, y)` -/ lemma continuous_at.fst' {f : α → γ} {x : α} {y : β} (hf : continuous_at f x) : continuous_at (λ x : α × β, f x.fst) (x, y) := continuous_at.comp hf continuous_at_fst /-- Precomposing `f` with `prod.fst` is continuous at `x : α × β` -/ lemma continuous_at.fst'' {f : α → γ} {x : α × β} (hf : continuous_at f x.fst) : continuous_at (λ x : α × β, f x.fst) x := hf.comp continuous_at_fst @[continuity] lemma continuous_snd : continuous (@prod.snd α β) := continuous_inf_dom_right continuous_induced_dom /-- Postcomposing `f` with `prod.snd` is continuous -/ lemma continuous.snd {f : α → β × γ} (hf : continuous f) : continuous (λ a : α, (f a).2) := continuous_snd.comp hf /-- Precomposing `f` with `prod.snd` is continuous -/ lemma continuous.snd' {f : β → γ} (hf : continuous f) : continuous (λ x : α × β, f x.snd) := hf.comp continuous_snd lemma continuous_at_snd {p : α × β} : continuous_at prod.snd p := continuous_snd.continuous_at /-- Postcomposing `f` with `prod.snd` is continuous at `x` -/ lemma continuous_at.snd {f : α → β × γ} {x : α} (hf : continuous_at f x) : continuous_at (λ a : α, (f a).2) x := continuous_at_snd.comp hf /-- Precomposing `f` with `prod.snd` is continuous at `(x, y)` -/ lemma continuous_at.snd' {f : β → γ} {x : α} {y : β} (hf : continuous_at f y) : continuous_at (λ x : α × β, f x.snd) (x, y) := continuous_at.comp hf continuous_at_snd /-- Precomposing `f` with `prod.snd` is continuous at `x : α × β` -/ lemma continuous_at.snd'' {f : β → γ} {x : α × β} (hf : continuous_at f x.snd) : continuous_at (λ x : α × β, f x.snd) x := hf.comp continuous_at_snd @[continuity] lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, (f x, g x)) := continuous_inf_rng.2 ⟨continuous_induced_rng.2 hf, continuous_induced_rng.2 hg⟩ @[simp] lemma continuous_prod_mk {f : α → β} {g : α → γ} : continuous (λ x, (f x, g x)) ↔ continuous f ∧ continuous g := ⟨λ h, ⟨h.fst, h.snd⟩, λ h, h.1.prod_mk h.2⟩ @[continuity] lemma continuous.prod.mk (a : α) : continuous (λ b : β, (a, b)) := continuous_const.prod_mk continuous_id' @[continuity] lemma continuous.prod.mk_left (b : β) : continuous (λ a : α, (a, b)) := continuous_id'.prod_mk continuous_const lemma continuous.comp₂ {g : α × β → γ} (hg : continuous g) {e : δ → α} (he : continuous e) {f : δ → β} (hf : continuous f) : continuous (λ x, g (e x, f x)) := hg.comp $ he.prod_mk hf lemma continuous.comp₃ {g : α × β × γ → ε} (hg : continuous g) {e : δ → α} (he : continuous e) {f : δ → β} (hf : continuous f) {k : δ → γ} (hk : continuous k) : continuous (λ x, g (e x, f x, k x)) := hg.comp₂ he $ hf.prod_mk hk lemma continuous.comp₄ {g : α × β × γ × ζ → ε} (hg : continuous g) {e : δ → α} (he : continuous e) {f : δ → β} (hf : continuous f) {k : δ → γ} (hk : continuous k) {l : δ → ζ} (hl : continuous l) : continuous (λ x, g (e x, f x, k x, l x)) := hg.comp₃ he hf $ hk.prod_mk hl lemma continuous.prod_map {f : γ → α} {g : δ → β} (hf : continuous f) (hg : continuous g) : continuous (λ x : γ × δ, (f x.1, g x.2)) := hf.fst'.prod_mk hg.snd' /-- A version of `continuous_inf_dom_left` for binary functions -/ lemma continuous_inf_dom_left₂ {α β γ} {f : α → β → γ} {ta1 ta2 : topological_space α} {tb1 tb2 : topological_space β} {tc1 : topological_space γ} (h : by haveI := ta1; haveI := tb1; exact continuous (λ p : α × β, f p.1 p.2)) : by haveI := ta1 ⊓ ta2; haveI := tb1 ⊓ tb2; exact continuous (λ p : α × β, f p.1 p.2) := begin have ha := @continuous_inf_dom_left _ _ id ta1 ta2 ta1 (@continuous_id _ (id _)), have hb := @continuous_inf_dom_left _ _ id tb1 tb2 tb1 (@continuous_id _ (id _)), have h_continuous_id := @continuous.prod_map _ _ _ _ ta1 tb1 (ta1 ⊓ ta2) (tb1 ⊓ tb2) _ _ ha hb, exact @continuous.comp _ _ _ (id _) (id _) _ _ _ h h_continuous_id, end /-- A version of `continuous_inf_dom_right` for binary functions -/ lemma continuous_inf_dom_right₂ {α β γ} {f : α → β → γ} {ta1 ta2 : topological_space α} {tb1 tb2 : topological_space β} {tc1 : topological_space γ} (h : by haveI := ta2; haveI := tb2; exact continuous (λ p : α × β, f p.1 p.2)) : by haveI := ta1 ⊓ ta2; haveI := tb1 ⊓ tb2; exact continuous (λ p : α × β, f p.1 p.2) := begin have ha := @continuous_inf_dom_right _ _ id ta1 ta2 ta2 (@continuous_id _ (id _)), have hb := @continuous_inf_dom_right _ _ id tb1 tb2 tb2 (@continuous_id _ (id _)), have h_continuous_id := @continuous.prod_map _ _ _ _ ta2 tb2 (ta1 ⊓ ta2) (tb1 ⊓ tb2) _ _ ha hb, exact @continuous.comp _ _ _ (id _) (id _) _ _ _ h h_continuous_id, end /-- A version of `continuous_Inf_dom` for binary functions -/ lemma continuous_Inf_dom₂ {α β γ} {f : α → β → γ} {tas : set (topological_space α)} {tbs : set (topological_space β)} {ta : topological_space α} {tb : topological_space β} {tc : topological_space γ} (ha : ta ∈ tas) (hb : tb ∈ tbs) (hf : continuous (λ p : α × β, f p.1 p.2)): by haveI := Inf tas; haveI := Inf tbs; exact @continuous _ _ _ tc (λ p : α × β, f p.1 p.2) := begin let t : topological_space (α × β) := prod.topological_space, have ha := continuous_Inf_dom ha continuous_id, have hb := continuous_Inf_dom hb continuous_id, have h_continuous_id := @continuous.prod_map _ _ _ _ ta tb (Inf tas) (Inf tbs) _ _ ha hb, exact @continuous.comp _ _ _ (id _) (id _) _ _ _ hf h_continuous_id, end lemma filter.eventually.prod_inl_nhds {p : α → Prop} {a : α} (h : ∀ᶠ x in 𝓝 a, p x) (b : β) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).1 := continuous_at_fst h lemma filter.eventually.prod_inr_nhds {p : β → Prop} {b : β} (h : ∀ᶠ x in 𝓝 b, p x) (a : α) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).2 := continuous_at_snd h lemma filter.eventually.prod_mk_nhds {pa : α → Prop} {a} (ha : ∀ᶠ x in 𝓝 a, pa x) {pb : β → Prop} {b} (hb : ∀ᶠ y in 𝓝 b, pb y) : ∀ᶠ p in 𝓝 (a, b), pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl_nhds b).and (hb.prod_inr_nhds a) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous_snd.prod_mk continuous_fst lemma continuous_uncurry_left {f : α → β → γ} (a : α) (h : continuous (uncurry f)) : continuous (f a) := show continuous (uncurry f ∘ (λ b, (a, b))), from h.comp (by continuity) lemma continuous_uncurry_right {f : α → β → γ} (b : β) (h : continuous (uncurry f)) : continuous (λ a, f a b) := show continuous (uncurry f ∘ (λ a, (a, b))), from h.comp (by continuity) lemma continuous_curry {g : α × β → γ} (a : α) (h : continuous g) : continuous (curry g a) := show continuous (g ∘ (λ b, (a, b))), from h.comp (by continuity) lemma is_open.prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (s ×ˢ t) := (hs.preimage continuous_fst).inter (ht.preimage continuous_snd) lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = 𝓝 a ×ᶠ 𝓝 b := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced] /-- If a function `f x y` is such that `y ↦ f x y` is continuous for all `x`, and `x` lives in a discrete space, then `f` is continuous. -/ lemma continuous_uncurry_of_discrete_topology [discrete_topology α] {f : α → β → γ} (hf : ∀ a, continuous (f a)) : continuous (uncurry f) := begin apply continuous_iff_continuous_at.2, rintros ⟨a, x⟩, change map _ _ ≤ _, rw [nhds_prod_eq, nhds_discrete, filter.map_pure_prod], exact (hf a).continuous_at end lemma mem_nhds_prod_iff {a : α} {b : β} {s : set (α × β)} : s ∈ 𝓝 (a, b) ↔ ∃ (u ∈ 𝓝 a) (v ∈ 𝓝 b), u ×ˢ v ⊆ s := by rw [nhds_prod_eq, mem_prod_iff] lemma mem_nhds_prod_iff' {a : α} {b : β} {s : set (α × β)} : s ∈ 𝓝 (a, b) ↔ ∃ (u : set α) (v : set β), is_open u ∧ a ∈ u ∧ is_open v ∧ b ∈ v ∧ u ×ˢ v ⊆ s := begin rw mem_nhds_prod_iff, split, { rintros ⟨u, Hu, v, Hv, h⟩, rcases mem_nhds_iff.1 Hu with ⟨u', u'u, u'_open, Hu'⟩, rcases mem_nhds_iff.1 Hv with ⟨v', v'v, v'_open, Hv'⟩, exact ⟨u', v', u'_open, Hu', v'_open, Hv', (set.prod_mono u'u v'v).trans h⟩ }, { rintros ⟨u, v, u_open, au, v_open, bv, huv⟩, exact ⟨u, u_open.mem_nhds au, v, v_open.mem_nhds bv, huv⟩ } end lemma _root_.prod.tendsto_iff {α} (seq : α → β × γ) {f : filter α} (x : β × γ) : tendsto seq f (𝓝 x) ↔ tendsto (λ n, (seq n).fst) f (𝓝 x.fst) ∧ tendsto (λ n, (seq n).snd) f (𝓝 x.snd) := by { cases x, rw [nhds_prod_eq, filter.tendsto_prod_iff'], } lemma filter.has_basis.prod_nhds {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {a : α} {b : β} (ha : (𝓝 a).has_basis pa sa) (hb : (𝓝 b).has_basis pb sb) : (𝓝 (a, b)).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, sa i.1 ×ˢ sb i.2) := by { rw nhds_prod_eq, exact ha.prod hb } lemma filter.has_basis.prod_nhds' {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {ab : α × β} (ha : (𝓝 ab.1).has_basis pa sa) (hb : (𝓝 ab.2).has_basis pb sb) : (𝓝 ab).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, sa i.1 ×ˢ sb i.2) := by { cases ab, exact ha.prod_nhds hb } instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) := ⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩ lemma prod_mem_nhds_iff {s : set α} {t : set β} {a : α} {b : β} : s ×ˢ t ∈ 𝓝 (a, b) ↔ s ∈ 𝓝 a ∧ t ∈ 𝓝 b := by rw [nhds_prod_eq, prod_mem_prod_iff] lemma prod_mem_nhds {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : s ×ˢ t ∈ 𝓝 (a, b) := prod_mem_nhds_iff.2 ⟨ha, hb⟩ lemma filter.eventually.prod_nhds {p : α → Prop} {q : β → Prop} {a : α} {b : β} (ha : ∀ᶠ x in 𝓝 a, p x) (hb : ∀ᶠ y in 𝓝 b, q y) : ∀ᶠ z : α × β in 𝓝 (a, b), p z.1 ∧ q z.2 := prod_mem_nhds ha hb lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma filter.tendsto.prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) : tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma filter.eventually.curry_nhds {p : α × β → Prop} {x : α} {y : β} (h : ∀ᶠ x in 𝓝 (x, y), p x) : ∀ᶠ x' in 𝓝 x, ∀ᶠ y' in 𝓝 y, p (x', y') := by { rw [nhds_prod_eq] at h, exact h.curry } lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x := hf.prod_mk_nhds hg lemma continuous_at.prod_map {f : α → γ} {g : β → δ} {p : α × β} (hf : continuous_at f p.fst) (hg : continuous_at g p.snd) : continuous_at (λ p : α × β, (f p.1, g p.2)) p := hf.fst''.prod hg.snd'' lemma continuous_at.prod_map' {f : α → γ} {g : β → δ} {x : α} {y : β} (hf : continuous_at f x) (hg : continuous_at g y) : continuous_at (λ p : α × β, (f p.1, g p.2)) (x, y) := hf.fst'.prod hg.snd' lemma prod_generate_from_generate_from_eq {α β : Type*} {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃ u ∈ s, ∃ v ∈ t, g = u ×ˢ v} := let G := generate_from {g | ∃ u ∈ s, ∃ v ∈ t, g = u ×ˢ v} in le_antisymm (le_generate_from $ λ g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open.prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp $ le_generate_from $ λ u hu, have (⋃ v ∈ t, u ×ˢ v) = prod.fst ⁻¹' u, by simp_rw [← prod_Union, ← sUnion_eq_bUnion, ht, prod_univ], show G.is_open (prod.fst ⁻¹' u), by { rw [← this], exactI is_open_Union (λ v, is_open_Union $ λ hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) }) (coinduced_le_iff_le_induced.mp $ le_generate_from $ λ v hv, have (⋃ u ∈ s, u ×ˢ v) = prod.snd ⁻¹' v, by simp_rw [← Union_prod_const, ← sUnion_eq_bUnion, hs, univ_prod], show G.is_open (prod.snd ⁻¹' v), by { rw [← this], exactI is_open_Union (λ u, is_open_Union $ λ hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) })) lemma prod_eq_generate_from : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = s ×ˢ t} := le_antisymm (le_generate_from $ λ g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ hs.prod ht) (le_inf (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩) (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩)) lemma is_open_prod_iff {s : set (α × β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ u ×ˢ v ⊆ s) := begin rw [is_open_iff_nhds], simp_rw [le_principal_iff, prod.forall, ((nhds_basis_opens _).prod_nhds (nhds_basis_opens _)).mem_iff, prod.exists, exists_prop], simp only [and_assoc, and.left_comm] end /-- A product of induced topologies is induced by the product map -/ lemma prod_induced_induced {α γ : Type*} (f : α → β) (g : γ → δ) : @prod.topological_space α γ (induced f ‹_›) (induced g ‹_›) = induced (λ p, (f p.1, g p.2)) prod.topological_space := by simp_rw [prod.topological_space, induced_inf, induced_compose] lemma continuous_uncurry_of_discrete_topology_left [discrete_topology α] {f : α → β → γ} (h : ∀ a, continuous (f a)) : continuous (uncurry f) := continuous_iff_continuous_at.2 $ λ ⟨a, b⟩, by simp only [continuous_at, nhds_prod_eq, nhds_discrete α, pure_prod, tendsto_map'_iff, (∘), uncurry, (h a).tendsto] /-- Given a neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood that is a subset of `s`. -/ lemma exists_nhds_square {s : set (α × α)} {x : α} (hx : s ∈ 𝓝 (x, x)) : ∃ U : set α, is_open U ∧ x ∈ U ∧ U ×ˢ U ⊆ s := by simpa [nhds_prod_eq, (nhds_basis_opens x).prod_self.mem_iff, and.assoc, and.left_comm] using hx /-- `prod.fst` maps neighborhood of `x : α × β` within the section `prod.snd ⁻¹' {x.2}` to `𝓝 x.1`. -/ lemma map_fst_nhds_within (x : α × β) : map prod.fst (𝓝[prod.snd ⁻¹' {x.2}] x) = 𝓝 x.1 := begin refine le_antisymm (continuous_at_fst.mono_left inf_le_left) (λ s hs, _), rcases x with ⟨x, y⟩, rw [mem_map, nhds_within, mem_inf_principal, mem_nhds_prod_iff] at hs, rcases hs with ⟨u, hu, v, hv, H⟩, simp only [prod_subset_iff, mem_singleton_iff, mem_set_of_eq, mem_preimage] at H, exact mem_of_superset hu (λ z hz, H _ hz _ (mem_of_mem_nhds hv) rfl) end @[simp] lemma map_fst_nhds (x : α × β) : map prod.fst (𝓝 x) = 𝓝 x.1 := le_antisymm continuous_at_fst $ (map_fst_nhds_within x).symm.trans_le (map_mono inf_le_left) /-- The first projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_fst : is_open_map (@prod.fst α β) := is_open_map_iff_nhds_le.2 $ λ x, (map_fst_nhds x).ge /-- `prod.snd` maps neighborhood of `x : α × β` within the section `prod.fst ⁻¹' {x.1}` to `𝓝 x.2`. -/ lemma map_snd_nhds_within (x : α × β) : map prod.snd (𝓝[prod.fst ⁻¹' {x.1}] x) = 𝓝 x.2 := begin refine le_antisymm (continuous_at_snd.mono_left inf_le_left) (λ s hs, _), rcases x with ⟨x, y⟩, rw [mem_map, nhds_within, mem_inf_principal, mem_nhds_prod_iff] at hs, rcases hs with ⟨u, hu, v, hv, H⟩, simp only [prod_subset_iff, mem_singleton_iff, mem_set_of_eq, mem_preimage] at H, exact mem_of_superset hv (λ z hz, H _ (mem_of_mem_nhds hu) _ hz rfl) end @[simp] lemma map_snd_nhds (x : α × β) : map prod.snd (𝓝 x) = 𝓝 x.2 := le_antisymm continuous_at_snd $ (map_snd_nhds_within x).symm.trans_le (map_mono inf_le_left) /-- The second projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_snd : is_open_map (@prod.snd α β) := is_open_map_iff_nhds_le.2 $ λ x, (map_snd_nhds x).ge /-- A product set is open in a product space if and only if each factor is open, or one of them is empty -/ lemma is_open_prod_iff' {s : set α} {t : set β} : is_open (s ×ˢ t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) := begin cases (s ×ˢ t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s.nonempty ∧ t.nonempty, from prod_nonempty_iff.1 h, split, { assume H : is_open (s ×ˢ t), refine or.inl ⟨_, _⟩, show is_open s, { rw ← fst_image_prod s st.2, exact is_open_map_fst _ H }, show is_open t, { rw ← snd_image_prod st.1 t, exact is_open_map_snd _ H } }, { assume H, simp only [st.1.ne_empty, st.2.ne_empty, not_false_iff, or_false] at H, exact H.1.prod H.2 } } end lemma closure_prod_eq {s : set α} {t : set β} : closure (s ×ˢ t) = closure s ×ˢ closure t := set.ext $ assume ⟨a, b⟩, have (𝓝 a ×ᶠ 𝓝 b) ⊓ 𝓟 (s ×ˢ t) = (𝓝 a ⊓ 𝓟 s) ×ᶠ (𝓝 b ⊓ 𝓟 t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_cluster_pts, cluster_pt, nhds_prod_eq, this]; exact prod_ne_bot lemma interior_prod_eq (s : set α) (t : set β) : interior (s ×ˢ t) = interior s ×ˢ interior t := set.ext $ λ ⟨a, b⟩, by simp only [mem_interior_iff_mem_nhds, mem_prod, prod_mem_nhds_iff] lemma frontier_prod_eq (s : set α) (t : set β) : frontier (s ×ˢ t) = closure s ×ˢ frontier t ∪ frontier s ×ˢ closure t := by simp only [frontier, closure_prod_eq, interior_prod_eq, prod_diff_prod] @[simp] lemma frontier_prod_univ_eq (s : set α) : frontier (s ×ˢ (univ : set β)) = frontier s ×ˢ univ := by simp [frontier_prod_eq] @[simp] lemma frontier_univ_prod_eq (s : set β) : frontier ((univ : set α) ×ˢ s) = univ ×ˢ frontier s := by simp [frontier_prod_eq] lemma map_mem_closure₂ {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (uncurry f)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀ (a ∈ s) (b ∈ t), f a b ∈ u) : f a b ∈ closure u := have H₁ : (a, b) ∈ closure (s ×ˢ t), by simpa only [closure_prod_eq] using mk_mem_prod ha hb, have H₂ : maps_to (uncurry f) (s ×ˢ t) u, from forall_prod_set.2 h, H₂.closure hf H₁ lemma is_closed.prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ×ˢ s₂) := closure_eq_iff_is_closed.mp $ by simp only [h₁.closure_eq, h₂.closure_eq, closure_prod_eq] /-- The product of two dense sets is a dense set. -/ lemma dense.prod {s : set α} {t : set β} (hs : dense s) (ht : dense t) : dense (s ×ˢ t) := λ x, by { rw closure_prod_eq, exact ⟨hs x.1, ht x.2⟩ } /-- If `f` and `g` are maps with dense range, then `prod.map f g` has dense range. -/ lemma dense_range.prod_map {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ} (hf : dense_range f) (hg : dense_range g) : dense_range (prod.map f g) := by simpa only [dense_range, prod_range_range_eq] using hf.prod hg lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) : inducing (λx:α×γ, (f x.1, g x.2)) := ⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced, induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩ lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩, ..hf.to_inducing.prod_mk hg.to_inducing } protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) := begin rw [is_open_map_iff_nhds_le], rintros ⟨a, b⟩, rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq], exact filter.prod_mono (hf.nhds_le a) (hg.nhds_le b) end protected lemma open_embedding.prod {f : α → β} {g : γ → δ} (hf : open_embedding f) (hg : open_embedding g) : open_embedding (λ x : α × γ, (f x.1, g x.2)) := open_embedding_of_embedding_open (hf.1.prod_mk hg.1) (hf.is_open_map.prod hg.is_open_map) lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λ x, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id end prod section sum open sum variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] @[continuity] lemma continuous_inl : continuous (@inl α β) := continuous_sup_rng_left continuous_coinduced_rng @[continuity] lemma continuous_inr : continuous (@inr α β) := continuous_sup_rng_right continuous_coinduced_rng lemma is_open_sum_iff {s : set (α ⊕ β)} : is_open s ↔ is_open (inl ⁻¹' s) ∧ is_open (inr ⁻¹' s) := iff.rfl lemma is_open_map_inl : is_open_map (@inl α β) := λ u hu, by simpa [is_open_sum_iff, preimage_image_eq u sum.inl_injective] lemma is_open_map_inr : is_open_map (@inr α β) := λ u hu, by simpa [is_open_sum_iff, preimage_image_eq u sum.inr_injective] lemma open_embedding_inl : open_embedding (@inl α β) := open_embedding_of_continuous_injective_open continuous_inl inl_injective is_open_map_inl lemma open_embedding_inr : open_embedding (@inr α β) := open_embedding_of_continuous_injective_open continuous_inr inr_injective is_open_map_inr lemma embedding_inl : embedding (@inl α β) := open_embedding_inl.1 lemma embedding_inr : embedding (@inr α β) := open_embedding_inr.1 lemma is_open_range_inl : is_open (range (inl : α → α ⊕ β)) := open_embedding_inl.2 lemma is_open_range_inr : is_open (range (inr : β → α ⊕ β)) := open_embedding_inr.2 lemma is_closed_range_inl : is_closed (range (inl : α → α ⊕ β)) := by { rw [← is_open_compl_iff, compl_range_inl], exact is_open_range_inr } lemma is_closed_range_inr : is_closed (range (inr : β → α ⊕ β)) := by { rw [← is_open_compl_iff, compl_range_inr], exact is_open_range_inl } lemma closed_embedding_inl : closed_embedding (inl : α → α ⊕ β) := ⟨embedding_inl, is_closed_range_inl⟩ lemma closed_embedding_inr : closed_embedding (inr : β → α ⊕ β) := ⟨embedding_inr, is_closed_range_inr⟩ lemma nhds_inl (x : α) : 𝓝 (inl x : α ⊕ β) = map inl (𝓝 x) := (open_embedding_inl.map_nhds_eq _).symm lemma nhds_inr (x : β) : 𝓝 (inr x : α ⊕ β) = map inr (𝓝 x) := (open_embedding_inr.map_nhds_eq _).symm lemma continuous_sum_elim {f : α → γ} {g : β → γ} : continuous (sum.elim f g) ↔ continuous f ∧ continuous g := by simp only [continuous_sup_dom, continuous_coinduced_dom, sum.elim_comp_inl, sum.elim_comp_inr] @[continuity] lemma continuous.sum_elim {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : continuous (sum.elim f g) := continuous_sum_elim.2 ⟨hf, hg⟩ @[simp] lemma continuous_sum_map {f : α → β} {g : γ → δ} : continuous (sum.map f g) ↔ continuous f ∧ continuous g := continuous_sum_elim.trans $ embedding_inl.continuous_iff.symm.and embedding_inr.continuous_iff.symm @[continuity] lemma continuous.sum_map {f : α → β} {g : γ → δ} (hf : continuous f) (hg : continuous g) : continuous (sum.map f g) := continuous_sum_map.2 ⟨hf, hg⟩ lemma is_open_map_sum {f : α ⊕ β → γ} : is_open_map f ↔ is_open_map (λ a, f (inl a)) ∧ is_open_map (λ b, f (inr b)) := by simp only [is_open_map_iff_nhds_le, sum.forall, nhds_inl, nhds_inr, filter.map_map] @[simp] lemma is_open_map_sum_elim {f : α → γ} {g : β → γ} : is_open_map (sum.elim f g) ↔ is_open_map f ∧ is_open_map g := by simp only [is_open_map_sum, elim_inl, elim_inr] lemma is_open_map.sum_elim {f : α → γ} {g : β → γ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (sum.elim f g) := is_open_map_sum_elim.2 ⟨hf, hg⟩ end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma inducing_coe {b : set β} : inducing (coe : b → β) := ⟨rfl⟩ lemma inducing.of_cod_restrict {f : α → β} {b : set β} (hb : ∀ a, f a ∈ b) (h : inducing (b.cod_restrict f hb)) : inducing f := inducing_coe.comp h lemma embedding_subtype_coe : embedding (coe : subtype p → α) := ⟨⟨rfl⟩, subtype.coe_injective⟩ lemma closed_embedding_subtype_coe (h : is_closed {a | p a}) : closed_embedding (coe : subtype p → α) := ⟨embedding_subtype_coe, by rwa [subtype.range_coe_subtype]⟩ @[continuity] lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma continuous_subtype_coe : continuous (coe : subtype p → α) := continuous_subtype_val lemma continuous.subtype_coe {f : β → subtype p} (hf : continuous f) : continuous (λ x, (f x : α)) := continuous_subtype_coe.comp hf lemma is_open.open_embedding_subtype_coe {s : set α} (hs : is_open s) : open_embedding (coe : s → α) := { induced := rfl, inj := subtype.coe_injective, open_range := (subtype.range_coe : range coe = s).symm ▸ hs } lemma is_open.is_open_map_subtype_coe {s : set α} (hs : is_open s) : is_open_map (coe : s → α) := hs.open_embedding_subtype_coe.is_open_map lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) : is_open_map (s.restrict f) := hf.comp hs.is_open_map_subtype_coe lemma is_closed.closed_embedding_subtype_coe {s : set α} (hs : is_closed s) : closed_embedding (coe : {x // x ∈ s} → α) := { induced := rfl, inj := subtype.coe_injective, closed_range := (subtype.range_coe : range coe = s).symm ▸ hs } @[continuity] lemma continuous.subtype_mk {f : β → α} (h : continuous f) (hp : ∀x, p (f x)) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng.2 h lemma continuous.subtype_map {f : α → β} (h : continuous f) {q : β → Prop} (hpq : ∀ x, p x → q (f x)) : continuous (subtype.map f hpq) := (h.comp continuous_subtype_coe).subtype_mk _ lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) := continuous_id.subtype_map h lemma continuous_at_subtype_coe {p : α → Prop} {a : subtype p} : continuous_at (coe : subtype p → α) a := continuous_iff_continuous_at.mp continuous_subtype_coe _ lemma subtype.dense_iff {s : set α} {t : set s} : dense t ↔ s ⊆ closure (coe '' t) := by { rw [inducing_coe.dense_iff, set_coe.forall], refl } lemma map_nhds_subtype_coe_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) : map (coe : subtype p → α) (𝓝 ⟨a, ha⟩) = 𝓝 a := map_nhds_induced_of_mem $ by simpa only [subtype.coe_mk, subtype.range_coe] using h lemma nhds_subtype_eq_comap {a : α} {h : p a} : 𝓝 (⟨a, h⟩ : subtype p) = comap coe (𝓝 a) := nhds_induced _ _ lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} : ∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, (f x : α)) b (𝓝 (a : α)) | ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff, subtype.coe_mk] lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_continuous_at.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_mem_nhds c_sets⟩ in calc map f (𝓝 x) = map f (map coe (𝓝 x')) : congr_arg (map f) (map_nhds_subtype_coe_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x) (𝓝 x') : rfl ... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed ((coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from assume i, (closed_embedding_subtype_coe (h_is_closed _)).is_closed_map _ (hs.preimage (f_cont i)), have is_closed (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from locally_finite.is_closed_Union (h_lf.subset $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simpa [and.comm, @and.left_comm (c _ _), ← exists_and_distrib_right], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ (x : α) ∈ closure ((coe : _ → α) '' s) := closure_induced lemma continuous_at_cod_restrict_iff {f : α → β} {t : set β} (h1 : ∀ x, f x ∈ t) {x : α} : continuous_at (cod_restrict f t h1) x ↔ continuous_at f x := by simp_rw [inducing_coe.continuous_at_iff, function.comp, coe_cod_restrict_apply] alias continuous_at_cod_restrict_iff ↔ _ continuous_at.cod_restrict lemma continuous_at.restrict {f : α → β} {s : set α} {t : set β} (h1 : maps_to f s t) {x : s} (h2 : continuous_at f x) : continuous_at (h1.restrict f s t) x := (h2.comp continuous_at_subtype_coe).cod_restrict _ lemma continuous_at.restrict_preimage {f : α → β} {s : set β} {x : f ⁻¹' s} (h : continuous_at f x) : continuous_at (s.restrict_preimage f) x := h.restrict _ @[continuity] lemma continuous.cod_restrict {f : α → β} {s : set β} (hf : continuous f) (hs : ∀ a, f a ∈ s) : continuous (s.cod_restrict f hs) := hf.subtype_mk hs lemma inducing.cod_restrict {e : α → β} (he : inducing e) {s : set β} (hs : ∀ x, e x ∈ s) : inducing (cod_restrict e s hs) := inducing_of_inducing_compose (he.continuous.cod_restrict hs) continuous_subtype_coe he lemma embedding.cod_restrict {e : α → β} (he : embedding e) (s : set β) (hs : ∀ x, e x ∈ s) : embedding (cod_restrict e s hs) := embedding_of_embedding_compose (he.continuous.cod_restrict hs) continuous_subtype_coe he end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ @[continuity] lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng @[continuity] lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom.2 h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous.quotient_lift {f : α → β} (h : continuous f) (hs : ∀ a b, a ≈ b → f a = f b) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom.2 h lemma continuous.quotient_lift_on' {f : α → β} (h : continuous f) (hs : ∀ a b, @setoid.r _ s a b → f a = f b) : continuous (λ x, quotient.lift_on' x f hs : quotient s → β) := h.quotient_lift hs lemma continuous.quotient_map' {t : setoid β} {f : α → β} (hf : continuous f) (H : (s.r ⇒ t.r) f f) : continuous (quotient.map' f H) := (continuous_quotient_mk.comp hf).quotient_lift _ end quotient section pi variables {ι : Type*} {π : ι → Type*} {κ : Type*} [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} lemma continuous_pi_iff : continuous f ↔ ∀ i, continuous (λ a, f a i) := by simp only [continuous_infi_rng, continuous_induced_rng] @[continuity] lemma continuous_pi (h : ∀ i, continuous (λ a, f a i)) : continuous f := continuous_pi_iff.2 h @[continuity] lemma continuous_apply (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom @[continuity] lemma continuous_apply_apply {ρ : κ → ι → Type*} [∀ j i, topological_space (ρ j i)] (j : κ) (i : ι) : continuous (λ p : (Π j, Π i, ρ j i), p j i) := (continuous_apply i).comp (continuous_apply j) lemma continuous_at_apply (i : ι) (x : Π i, π i) : continuous_at (λ p : Π i, π i, p i) x := (continuous_apply i).continuous_at lemma filter.tendsto.apply {l : filter β} {f : β → Π i, π i} {x : Π i, π i} (h : tendsto f l (𝓝 x)) (i : ι) : tendsto (λ a, f a i) l (𝓝 $ x i) := (continuous_at_apply i _).tendsto.comp h lemma nhds_pi {a : Πi, π i} : 𝓝 a = pi (λ i, 𝓝 (a i)) := by simp only [nhds_infi, nhds_induced, filter.pi] lemma tendsto_pi_nhds {f : β → Πi, π i} {g : Πi, π i} {u : filter β} : tendsto f u (𝓝 g) ↔ ∀ x, tendsto (λ i, f i x) u (𝓝 (g x)) := by rw [nhds_pi, filter.tendsto_pi] lemma continuous_at_pi {f : α → Π i, π i} {x : α} : continuous_at f x ↔ ∀ i, continuous_at (λ y, f y i) x := tendsto_pi_nhds lemma filter.tendsto.update [decidable_eq ι] {l : filter β} {f : β → Π i, π i} {x : Π i, π i} (hf : tendsto f l (𝓝 x)) (i : ι) {g : β → π i} {xi : π i} (hg : tendsto g l (𝓝 xi)) : tendsto (λ a, update (f a) i (g a)) l (𝓝 $ update x i xi) := tendsto_pi_nhds.2 $ λ j, by { rcases em (j = i) with rfl|hj; simp [*, hf.apply] } lemma continuous_at.update [decidable_eq ι] {a : α} (hf : continuous_at f a) (i : ι) {g : α → π i} (hg : continuous_at g a) : continuous_at (λ a, update (f a) i (g a)) a := hf.update i hg lemma continuous.update [decidable_eq ι] (hf : continuous f) (i : ι) {g : α → π i} (hg : continuous g) : continuous (λ a, update (f a) i (g a)) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.update i hg.continuous_at /-- `update f i x` is continuous in `(f, x)`. -/ @[continuity] lemma continuous_update [decidable_eq ι] (i : ι) : continuous (λ f : (Π j, π j) × π i, update f.1 i f.2) := continuous_fst.update i continuous_snd lemma filter.tendsto.fin_insert_nth {n} {π : fin (n + 1) → Type*} [Π i, topological_space (π i)] (i : fin (n + 1)) {f : β → π i} {l : filter β} {x : π i} (hf : tendsto f l (𝓝 x)) {g : β → Π j : fin n, π (i.succ_above j)} {y : Π j, π (i.succ_above j)} (hg : tendsto g l (𝓝 y)) : tendsto (λ a, i.insert_nth (f a) (g a)) l (𝓝 $ i.insert_nth x y) := tendsto_pi_nhds.2 (λ j, fin.succ_above_cases i (by simpa) (by simpa using tendsto_pi_nhds.1 hg) j) lemma continuous_at.fin_insert_nth {n} {π : fin (n + 1) → Type*} [Π i, topological_space (π i)] (i : fin (n + 1)) {f : α → π i} {a : α} (hf : continuous_at f a) {g : α → Π j : fin n, π (i.succ_above j)} (hg : continuous_at g a) : continuous_at (λ a, i.insert_nth (f a) (g a)) a := hf.fin_insert_nth i hg lemma continuous.fin_insert_nth {n} {π : fin (n + 1) → Type*} [Π i, topological_space (π i)] (i : fin (n + 1)) {f : α → π i} (hf : continuous f) {g : α → Π j : fin n, π (i.succ_above j)} (hg : continuous g) : continuous (λ a, i.insert_nth (f a) (g a)) := continuous_iff_continuous_at.2 $ λ a, hf.continuous_at.fin_insert_nth i hg.continuous_at lemma is_open_set_pi {i : set ι} {s : Πa, set (π a)} (hi : i.finite) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, (hs _ ha).preimage (continuous_apply _)) lemma is_closed_set_pi {i : set ι} {s : Πa, set (π a)} (hs : ∀a∈i, is_closed (s a)) : is_closed (pi i s) := by rw [pi_def]; exact (is_closed_Inter $ λ a, is_closed_Inter $ λ ha, (hs _ ha).preimage (continuous_apply _)) lemma mem_nhds_of_pi_mem_nhds {I : set ι} {s : Π i, set (π i)} (a : Π i, π i) (hs : I.pi s ∈ 𝓝 a) {i : ι} (hi : i ∈ I) : s i ∈ 𝓝 (a i) := by { rw nhds_pi at hs, exact mem_of_pi_mem_pi hs hi } lemma set_pi_mem_nhds {i : set ι} {s : Π a, set (π a)} {x : Π a, π a} (hi : i.finite) (hs : ∀ a ∈ i, s a ∈ 𝓝 (x a)) : pi i s ∈ 𝓝 x := by { rw [pi_def, bInter_mem hi], exact λ a ha, (continuous_apply a).continuous_at (hs a ha) } lemma set_pi_mem_nhds_iff {I : set ι} (hI : I.finite) {s : Π i, set (π i)} (a : Π i, π i) : I.pi s ∈ 𝓝 a ↔ ∀ (i : ι), i ∈ I → s i ∈ 𝓝 (a i) := by { rw [nhds_pi, pi_mem_pi_iff hI], apply_instance } lemma interior_pi_set {I : set ι} (hI : I.finite) {s : Π i, set (π i)} : interior (pi I s) = I.pi (λ i, interior (s i)) := by { ext a, simp only [set.mem_pi, mem_interior_iff_mem_nhds, set_pi_mem_nhds_iff hI] } lemma exists_finset_piecewise_mem_of_mem_nhds [decidable_eq ι] {s : set (Π a, π a)} {x : Π a, π a} (hs : s ∈ 𝓝 x) (y : Π a, π a) : ∃ I : finset ι, I.piecewise x y ∈ s := begin simp only [nhds_pi, filter.mem_pi'] at hs, rcases hs with ⟨I, t, htx, hts⟩, refine ⟨I, hts $ λ i hi, _⟩, simpa [finset.mem_coe.1 hi] using mem_of_mem_nhds (htx i) end lemma pi_eq_generate_from : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) (le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨update (λa, univ) a t, {a}, by simpa using ht, s_eq ▸ by ext f; simp [set.pi]⟩) lemma pi_generate_from_eq {π : ι → Type*} {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩, { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine le_generate_from _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨update (λa, univ) a s, {a}, by simp [hs]⟩ } end lemma pi_generate_from_eq_finite {π : ι → Type*} {g : Πa, set (set (π a))} [finite ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := begin casesI nonempty_fintype ι, rw [pi_generate_from_eq], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩, { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, set.pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, set.pi] at * }, simpa [pi_if, hf] } } end /-- Suppose `π i` is a family of topological spaces indexed by `i : ι`, and `X` is a type endowed with a family of maps `f i : X → π i` for every `i : ι`, hence inducing a map `g : X → Π i, π i`. This lemma shows that infimum of the topologies on `X` induced by the `f i` as `i : ι` varies is simply the topology on `X` induced by `g : X → Π i, π i` where `Π i, π i` is endowed with the usual product topology. -/ lemma inducing_infi_to_pi {X : Type*} (f : Π i, X → π i) : @inducing X (Π i, π i) (⨅ i, induced (f i) infer_instance) _ (λ x i, f i x) := begin constructor, erw induced_infi, congr' 1, funext, erw induced_compose, end variables [finite ι] [∀ i, discrete_topology (π i)] /-- A finite product of discrete spaces is discrete. -/ instance Pi.discrete_topology : discrete_topology (Π i, π i) := singletons_open_iff_discrete.mp (λ x, begin rw show {x} = ⋂ i, {y : Π i, π i | y i = x i}, { ext, simp only [funext_iff, set.mem_singleton_iff, set.mem_Inter, set.mem_set_of_eq] }, exact is_open_Inter (λ i, (continuous_apply i).is_open_preimage {x i} (is_open_discrete {x i})) end) end pi section sigma variables {ι κ : Type*} {σ : ι → Type*} {τ : κ → Type*} [Π i, topological_space (σ i)] [Π k, topological_space (τ k)] [topological_space α] @[continuity] lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) := continuous_supr_rng continuous_coinduced_rng lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) := by simp only [is_open_supr_iff, is_open_coinduced] lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) := by simp only [← is_open_compl_iff, is_open_sigma_iff, preimage_compl] lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) := begin intros s hs, rw is_open_sigma_iff, intro j, rcases eq_or_ne j i with (rfl|hne), { rwa set.preimage_image_eq _ sigma_mk_injective }, { rw [preimage_image_sigma_mk_of_ne hne], exact is_open_empty } end lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) := is_open_map_sigma_mk.is_open_range lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) := begin intros s hs, rw is_closed_sigma_iff, intro j, rcases eq_or_ne j i with (rfl|hne), { rwa set.preimage_image_eq _ sigma_mk_injective }, { rw [preimage_image_sigma_mk_of_ne hne], exact is_closed_empty } end lemma is_closed_range_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) := is_closed_map_sigma_mk.closed_range lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) := open_embedding_of_continuous_injective_open continuous_sigma_mk sigma_mk_injective is_open_map_sigma_mk lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) := closed_embedding_of_continuous_injective_closed continuous_sigma_mk sigma_mk_injective is_closed_map_sigma_mk lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) := closed_embedding_sigma_mk.1 lemma sigma.nhds_mk (i : ι) (x : σ i) : 𝓝 (⟨i, x⟩ : sigma σ) = map (sigma.mk i) (𝓝 x) := (open_embedding_sigma_mk.map_nhds_eq x).symm lemma sigma.nhds_eq (x : sigma σ) : 𝓝 x = map (sigma.mk x.1) (𝓝 x.2) := by { cases x, apply sigma.nhds_mk } lemma comap_sigma_mk_nhds (i : ι) (x : σ i) : comap (sigma.mk i) (𝓝 ⟨i, x⟩) = 𝓝 x := (embedding_sigma_mk.to_inducing.nhds_eq_comap _).symm lemma is_open_sigma_fst_preimage (s : set ι) : is_open (sigma.fst ⁻¹' s : set (Σ a, σ a)) := begin rw [← bUnion_of_singleton s, preimage_Union₂], simp only [← range_sigma_mk], exact is_open_bUnion (λ _ _, is_open_range_sigma_mk) end /-- A map out of a sum type is continuous iff its restriction to each summand is. -/ @[simp] lemma continuous_sigma_iff {f : sigma σ → α} : continuous f ↔ ∀ i, continuous (λ a, f ⟨i, a⟩) := by simp only [continuous_supr_dom, continuous_coinduced_dom] /-- A map out of a sum type is continuous if its restriction to each summand is. -/ @[continuity] lemma continuous_sigma {f : sigma σ → α} (hf : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f := continuous_sigma_iff.2 hf @[simp] lemma continuous_sigma_map {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} : continuous (sigma.map f₁ f₂) ↔ ∀ i, continuous (f₂ i) := continuous_sigma_iff.trans $ by simp only [sigma.map, embedding_sigma_mk.continuous_iff] @[continuity] lemma continuous.sigma_map {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := continuous_sigma_map.2 hf lemma is_open_map_sigma {f : sigma σ → α} : is_open_map f ↔ ∀ i, is_open_map (λ a, f ⟨i, a⟩) := by simp only [is_open_map_iff_nhds_le, sigma.forall, sigma.nhds_eq, map_map] lemma is_open_map_sigma_map {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} : is_open_map (sigma.map f₁ f₂) ↔ ∀ i, is_open_map (f₂ i) := is_open_map_sigma.trans $ forall_congr $ λ i, (@open_embedding_sigma_mk _ _ _ (f₁ i)).is_open_map_iff.symm lemma inducing_sigma_map {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (h₁ : injective f₁) : inducing (sigma.map f₁ f₂) ↔ ∀ i, inducing (f₂ i) := by simp only [inducing_iff_nhds, sigma.forall, sigma.nhds_mk, sigma.map, ← map_sigma_mk_comap h₁, map_inj sigma_mk_injective] lemma embedding_sigma_map {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (h : injective f₁) : embedding (sigma.map f₁ f₂) ↔ ∀ i, embedding (f₂ i) := by simp only [embedding_iff, injective.sigma_map, inducing_sigma_map h, forall_and_distrib, h.sigma_map_iff] lemma open_embedding_sigma_map {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (h : injective f₁) : open_embedding (sigma.map f₁ f₂) ↔ ∀ i, open_embedding (f₂ i) := by simp only [open_embedding_iff_embedding_open, is_open_map_sigma_map, embedding_sigma_map h, forall_and_distrib] end sigma section ulift @[continuity] lemma continuous_ulift_down [topological_space α] : continuous (ulift.down : ulift.{v u} α → α) := continuous_induced_dom @[continuity] lemma continuous_ulift_up [topological_space α] : continuous (ulift.up : α → ulift.{v u} α) := continuous_induced_rng.2 continuous_id end ulift
47b4834c210a80aab95e76b18abc49dd3e66fdc1
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/examples/lean/abelian.lean
cf3d35dc43c2529b2dcd2056cdb41d87e66da189
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
7,424
lean
import macros definition associative {A : (Type U)} (f : A → A → A) := ∀ x y z, f (f x y) z = f x (f y z) definition is_identity {A : (Type U)} (f : A → A → A) (id : A) := ∀ x, f x id = x definition inverse_ex {A : (Type U)} (f : A → A → A) (id : A) := ∀ x, ∃ y, f x y = id universe s ≥ 1 definition group := sig A : (Type s), sig mul : A → A → A, sig one : A, (associative mul) # (is_identity mul one) # (inverse_ex mul one) definition to_group (A : (Type s)) (mul : A → A → A) (one : A) (H1 : associative mul) (H2 : is_identity mul one) (H3 : inverse_ex mul one) : group := pair A (pair mul (pair one (pair H1 (pair H2 H3)))) -- The following definitions can be generated automatically. definition carrier (g : group) := proj1 g definition G_mul {g : group} : carrier g → carrier g → carrier g := proj1 (proj2 g) infixl 70 * : G_mul definition one {g : group} : carrier g := proj1 (proj2 (proj2 g)) theorem G_assoc {g : group} (x y z : carrier g) : (x * y) * z = x * (y * z) := (proj1 (proj2 (proj2 (proj2 g)))) x y z theorem G_id {g : group} (x : carrier g) : x * one = x := (proj1 (proj2 (proj2 (proj2 (proj2 g))))) x theorem G_inv {g : group} (x : carrier g) : ∃ y, x * y = one := (proj2 (proj2 (proj2 (proj2 (proj2 g))))) x set_opaque group true set_opaque carrier true set_opaque G_mul true set_opaque one true -- First example: the pairwise product of two groups is a group definition product (g1 g2 : group) : group := let S := carrier g1 # carrier g2, -- It would be nice to be able to define local notation, and write _*_ instead of f f := λ x y, pair (proj1 x * proj1 y) (proj2 x * proj2 y), o := pair one one -- this is actually (pair (@one g1) (@one g2)) in have assoc : associative f, -- The elaborator failed to infer the type of the pairs. -- I had to annotate the pairs with their types. from take x y z : S, -- We don't really need to provide S, but it will make the elaborator to work much harder -- since * is an overloaded operator, we also have * as notation for Nat::mul in the context. calc f (f x y) z = (pair ((proj1 x * proj1 y) * proj1 z) ((proj2 x * proj2 y) * proj2 z) : S) : refl (f (f x y) z) ... = (pair (proj1 x * (proj1 y * proj1 z)) ((proj2 x * proj2 y) * proj2 z) : S) : { G_assoc (proj1 x) (proj1 y) (proj1 z) } ... = (pair (proj1 x * (proj1 y * proj1 z)) (proj2 x * (proj2 y * proj2 z)) : S) : { G_assoc (proj2 x) (proj2 y) (proj2 z) } ... = f x (f y z) : refl (f x (f y z)), have id : is_identity f o, from take x : S, calc f x o = (pair (proj1 x * one) (proj2 x * one) : S) : refl (f x o) ... = (pair (proj1 x) (proj2 x * one) : S) : { G_id (proj1 x) } ... = (pair (proj1 x) (proj2 x) : S) : { G_id (proj2 x) } ... = x : pair_proj_eq x, have inv : inverse_ex f o, from take x : S, obtain (y1 : carrier g1) (Hy1 : proj1 x * y1 = one), from G_inv (proj1 x), obtain (y2 : carrier g2) (Hy2 : proj2 x * y2 = one), from G_inv (proj2 x), show ∃ y, f x y = o, from exists_intro (pair y1 y2 : S) (calc f x (pair y1 y2 : S) = (pair (proj1 x * y1) (proj2 x * y2) : S) : refl (f x (pair y1 y2 : S)) ... = (pair one (proj2 x * y2) : S) : { Hy1 } ... = (pair one one : S) : { Hy2 } ... = o : refl o), to_group S f o assoc id inv set_opaque product true -- It would be nice to be able to write x.first and x.second instead of (proj1 x) and (proj2 x) -- Remark: * is overloaded since Lean loads Nat.lean by default. -- The type errors related to * are quite cryptic because of that -- Use 'star' for creating products infixr 50 ⋆ : product -- It would be nice to be able to write (p1 p2 : g1 ⋆ g2 ⋆ g3) check λ (g1 g2 g3 : group) (p1 p2 : carrier (g1 ⋆ g2 ⋆ g3)), p1 * p2 = p2 * p1 theorem group_inhab (g : group) : inhabited (carrier g) := inhabited_intro (@one g) definition inv {g : group} (a : carrier g) : carrier g := ε (group_inhab g) (λ x : carrier g, a * x = one) theorem G_idl {g : group} (x : carrier g) : x * one = x := G_id x theorem G_invl {g : group} (x : carrier g) : x * inv x = one := obtain (y : carrier g) (Hy : x * y = one), from G_inv x, eps_ax (group_inhab g) y Hy set_opaque inv true theorem G_inv_aux {g : group} (x : carrier g) : inv x = (inv x * x) * inv x := symm (calc (inv x * x) * inv x = inv x * (x * inv x) : G_assoc (inv x) x (inv x) ... = inv x * one : { G_invl x } ... = inv x : G_idl (inv x)) theorem G_invr {g : group} (x : carrier g) : inv x * x = one := calc inv x * x = (inv x * x) * one : symm (G_idl (inv x * x)) ... = (inv x * x) * (inv x * inv (inv x)) : { symm (G_invl (inv x)) } ... = ((inv x * x) * inv x) * inv (inv x) : symm (G_assoc (inv x * x) (inv x) (inv (inv x))) ... = (inv x * (x * inv x)) * inv (inv x) : { G_assoc (inv x) x (inv x) } ... = (inv x * one) * inv (inv x) : { G_invl x } ... = (inv x) * inv (inv x) : { G_idl (inv x) } ... = one : G_invl (inv x) theorem G_idr {g : group} (x : carrier g) : one * x = x := calc one * x = (x * inv x) * x : { symm (G_invl x) } ... = x * (inv x * x) : G_assoc x (inv x) x ... = x * one : { G_invr x } ... = x : G_idl x theorem G_inv_inv {g : group} (x : carrier g) : inv (inv x) = x := calc inv (inv x) = inv (inv x) * one : symm (G_idl (inv (inv x))) ... = inv (inv x) * (inv x * x) : { symm (G_invr x) } ... = (inv (inv x) * inv x) * x : symm (G_assoc (inv (inv x)) (inv x) x) ... = one * x : { G_invr (inv x) } ... = x : G_idr x definition commutative {A : (Type U)} (f : A → A → A) := ∀ x y, f x y = f y x definition abelian_group := sig g : group, commutative (@G_mul g) definition ab_to_g (ag : abelian_group) : group := proj1 ag -- Coercions currently only work with opaque types -- We must first define "extract" the information we want, and then -- mark abelian_group as opaque definition AG_comm {g : abelian_group} (x y : carrier (ab_to_g g)) : x * y = y * x := (proj2 g) x y set_opaque abelian_group true set_opaque ab_to_g true set_opaque AG_comm true coercion ab_to_g -- Now, we can use abelian groups where groups are expected. theorem AG_left_comm {g : abelian_group} (x y z : carrier g) : x * (y * z) = y * (x * z) := calc x * (y * z) = (x * y) * z : symm (G_assoc x y z) ... = (y * x) * z : { AG_comm x y } ... = y * (x * z) : G_assoc y x z
70ee77e53611a42c12c524125a61e7b7b6112f1d
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/setoid/partition.lean
b5120189338aa89b01aec53180cf7421ff437612
[ "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
8,973
lean
import data.setoid.basic import data.set.lattice /-! # Equivalence relations: partitions This file comprises properties of equivalence relations viewed as partitions. ## Tags setoid, equivalence, iseqv, relation, equivalence relation, partition, equivalence class -/ namespace setoid variables {α : Type*} /-- If x ∈ α is in 2 elements of a set of sets partitioning α, those 2 sets are equal. -/ lemma eq_of_mem_eqv_class {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x b b'} (hc : b ∈ c) (hb : x ∈ b) (hc' : b' ∈ c) (hb' : x ∈ b') : b = b' := (H x).unique2 hc hb hc' hb' /-- Makes an equivalence relation from a set of sets partitioning α. -/ def mk_classes (c : set (set α)) (H : ∀ a, ∃! b ∈ c, a ∈ b) : setoid α := ⟨λ x y, ∀ s ∈ c, x ∈ s → y ∈ s, ⟨λ _ _ _ hx, hx, λ x y h s hs hy, (H x).elim2 $ λ t ht hx _, have s = t, from eq_of_mem_eqv_class H hs hy ht (h t ht hx), this.symm ▸ hx, λ x y z h1 h2 s hs hx, (H y).elim2 $ λ t ht hy _, (H z).elim2 $ λ t' ht' hz _, have hst : s = t, from eq_of_mem_eqv_class H hs (h1 _ hs hx) ht hy, have htt' : t = t', from eq_of_mem_eqv_class H ht (h2 _ ht hy) ht' hz, (hst.trans htt').symm ▸ hz⟩⟩ /-- Makes the equivalence classes of an equivalence relation. -/ def classes (r : setoid α) : set (set α) := {s | ∃ y, s = {x | r.rel x y}} lemma mem_classes (r : setoid α) (y) : {x | r.rel x y} ∈ r.classes := ⟨y, rfl⟩ /-- Two equivalence relations are equal iff all their equivalence classes are equal. -/ lemma eq_iff_classes_eq {r₁ r₂ : setoid α} : r₁ = r₂ ↔ ∀ x, {y | r₁.rel x y} = {y | r₂.rel x y} := ⟨λ h x, h ▸ rfl, λ h, ext' $ λ x, set.ext_iff.1 $ h x⟩ lemma rel_iff_exists_classes (r : setoid α) {x y} : r.rel x y ↔ ∃ c ∈ r.classes, x ∈ c ∧ y ∈ c := ⟨λ h, ⟨_, r.mem_classes y, h, r.refl' y⟩, λ ⟨c, ⟨z, hz⟩, hx, hy⟩, by { subst c, exact r.trans' hx (r.symm' hy) }⟩ /-- Two equivalence relations are equal iff their equivalence classes are equal. -/ lemma classes_inj {r₁ r₂ : setoid α} : r₁ = r₂ ↔ r₁.classes = r₂.classes := ⟨λ h, h ▸ rfl, λ h, ext' $ λ a b, by simp only [rel_iff_exists_classes, exists_prop, h] ⟩ /-- The empty set is not an equivalence class. -/ lemma empty_not_mem_classes {r : setoid α} : ∅ ∉ r.classes := λ ⟨y, hy⟩, set.not_mem_empty y $ hy.symm ▸ r.refl' y /-- Equivalence classes partition the type. -/ lemma classes_eqv_classes {r : setoid α} (a) : ∃! b ∈ r.classes, a ∈ b := exists_unique.intro2 {x | r.rel x a} (r.mem_classes a) (r.refl' _) $ begin rintros _ ⟨y, rfl⟩ ha, ext x, exact ⟨λ hx, r.trans' hx (r.symm' ha), λ hx, r.trans' hx ha⟩ end /-- If x ∈ α is in 2 equivalence classes, the equivalence classes are equal. -/ lemma eq_of_mem_classes {r : setoid α} {x b} (hc : b ∈ r.classes) (hb : x ∈ b) {b'} (hc' : b' ∈ r.classes) (hb' : x ∈ b') : b = b' := eq_of_mem_eqv_class classes_eqv_classes hc hb hc' hb' /-- The elements of a set of sets partitioning α are the equivalence classes of the equivalence relation defined by the set of sets. -/ lemma eq_eqv_class_of_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {s y} (hs : s ∈ c) (hy : y ∈ s) : s = {x | (mk_classes c H).rel x y} := set.ext $ λ x, ⟨λ hs', symm' (mk_classes c H) $ λ b' hb' h', eq_of_mem_eqv_class H hs hy hb' h' ▸ hs', λ hx, (H x).elim2 $ λ b' hc' hb' h', (eq_of_mem_eqv_class H hs hy hc' $ hx b' hc' hb').symm ▸ hb'⟩ /-- The equivalence classes of the equivalence relation defined by a set of sets partitioning α are elements of the set of sets. -/ lemma eqv_class_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {y} : {x | (mk_classes c H).rel x y} ∈ c := (H y).elim2 $ λ b hc hy hb, eq_eqv_class_of_mem H hc hy ▸ hc /-- Distinct elements of a set of sets partitioning α are disjoint. -/ lemma eqv_classes_disjoint {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) : set.pairwise_disjoint c := λ b₁ h₁ b₂ h₂ h, set.disjoint_left.2 $ λ x hx1 hx2, (H x).elim2 $ λ b hc hx hb, h $ eq_of_mem_eqv_class H h₁ hx1 h₂ hx2 /-- A set of disjoint sets covering α partition α (classical). -/ lemma eqv_classes_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α) (H : set.pairwise_disjoint c) (a) : ∃! b ∈ c, a ∈ b := let ⟨b, hc, ha⟩ := set.mem_sUnion.1 $ show a ∈ _, by rw hu; exact set.mem_univ a in exists_unique.intro2 b hc ha $ λ b' hc' ha', H.elim hc' hc a ha' ha /-- Makes an equivalence relation from a set of disjoints sets covering α. -/ def setoid_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α) (H : set.pairwise_disjoint c) : setoid α := setoid.mk_classes c $ eqv_classes_of_disjoint_union hu H /-- The equivalence relation made from the equivalence classes of an equivalence relation r equals r. -/ theorem mk_classes_classes (r : setoid α) : mk_classes r.classes classes_eqv_classes = r := ext' $ λ x y, ⟨λ h, r.symm' (h {z | r.rel z x} (r.mem_classes x) $ r.refl' x), λ h b hb hx, eq_of_mem_classes (r.mem_classes x) (r.refl' x) hb hx ▸ r.symm' h⟩ @[simp] theorem sUnion_classes (r : setoid α) : ⋃₀ r.classes = set.univ := set.eq_univ_of_forall $ λ x, set.mem_sUnion.2 ⟨{ y | r.rel y x }, ⟨x, rfl⟩, setoid.refl _⟩ section partition /-- A collection `c : set (set α)` of sets is a partition of `α` into pairwise disjoint sets if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. -/ def is_partition (c : set (set α)) := ∅ ∉ c ∧ ∀ a, ∃! b ∈ c, a ∈ b /-- A partition of `α` does not contain the empty set. -/ lemma nonempty_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (h : s ∈ c) : s.nonempty := set.ne_empty_iff_nonempty.1 $ λ hs0, hc.1 $ hs0 ▸ h lemma is_partition_classes (r : setoid α) : is_partition r.classes := ⟨empty_not_mem_classes, classes_eqv_classes⟩ lemma is_partition.pairwise_disjoint {c : set (set α)} (hc : is_partition c) : c.pairwise_disjoint := eqv_classes_disjoint hc.2 lemma is_partition.sUnion_eq_univ {c : set (set α)} (hc : is_partition c) : ⋃₀ c = set.univ := set.eq_univ_of_forall $ λ x, set.mem_sUnion.2 $ let ⟨t, ht⟩ := hc.2 x in ⟨t, by clear_aux_decl; finish⟩ /-- All elements of a partition of α are the equivalence class of some y ∈ α. -/ lemma exists_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (hs : s ∈ c) : ∃ y, s = {x | (mk_classes c hc.2).rel x y} := let ⟨y, hy⟩ := nonempty_of_mem_partition hc hs in ⟨y, eq_eqv_class_of_mem hc.2 hs hy⟩ /-- The equivalence classes of the equivalence relation defined by a partition of α equal the original partition. -/ theorem classes_mk_classes (c : set (set α)) (hc : is_partition c) : (mk_classes c hc.2).classes = c := set.ext $ λ s, ⟨λ ⟨y, hs⟩, (hc.2 y).elim2 $ λ b hm hb hy, by rwa (show s = b, from hs.symm ▸ set.ext (λ x, ⟨λ hx, symm' (mk_classes c hc.2) hx b hm hb, λ hx b' hc' hx', eq_of_mem_eqv_class hc.2 hm hx hc' hx' ▸ hb⟩)), exists_of_mem_partition hc⟩ /-- Defining `≤` on partitions as the `≤` defined on their induced equivalence relations. -/ instance partition.le : has_le (subtype (@is_partition α)) := ⟨λ x y, mk_classes x.1 x.2.2 ≤ mk_classes y.1 y.2.2⟩ /-- Defining a partial order on partitions as the partial order on their induced equivalence relations. -/ instance partition.partial_order : partial_order (subtype (@is_partition α)) := { le := (≤), lt := λ x y, x ≤ y ∧ ¬y ≤ x, le_refl := λ _, @le_refl (setoid α) _ _, le_trans := λ _ _ _, @le_trans (setoid α) _ _ _ _, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ x y hx hy, let h := @le_antisymm (setoid α) _ _ _ hx hy in by rw [subtype.ext_iff_val, ←classes_mk_classes x.1 x.2, ←classes_mk_classes y.1 y.2, h] } variables (α) /-- The order-preserving bijection between equivalence relations and partitions of sets. -/ def partition.rel_iso : setoid α ≃o subtype (@is_partition α) := { to_fun := λ r, ⟨r.classes, empty_not_mem_classes, classes_eqv_classes⟩, inv_fun := λ x, mk_classes x.1 x.2.2, left_inv := mk_classes_classes, right_inv := λ x, by rw [subtype.ext_iff_val, ←classes_mk_classes x.1 x.2], map_rel_iff' := λ x y, by conv {to_lhs, rw [←mk_classes_classes x, ←mk_classes_classes y]}; refl } variables {α} /-- A complete lattice instance for partitions; there is more infrastructure for the equivalent complete lattice on equivalence relations. -/ instance partition.complete_lattice : complete_lattice (subtype (@is_partition α)) := galois_insertion.lift_complete_lattice $ @rel_iso.to_galois_insertion _ (subtype (@is_partition α)) _ (partial_order.to_preorder _) $ partition.rel_iso α end partition end setoid
4f3c13795263674d82c52a467484818cc175a761
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/calculus/parametric_integral.lean
70202a072b66af4356fc44807621fd5f00bf26e6
[ "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
14,720
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import measure_theory.set_integral import analysis.calculus.mean_value /-! # Derivatives of integrals depending on parameters A parametric integral is a function with shape `f = λ x : H, ∫ a : α, F x a ∂μ` for some `F : H → α → E`, where `H` and `E` are normed spaces and `α` is a measured space with measure `μ`. We already know from `continuous_of_dominated` in `measure_theory.bochner_integral` how to guarantee that `f` is continuous using the dominated convergence theorem. In this file, we want to express the derivative of `f` as the integral of the derivative of `F` with respect to `x`. ## Main results As explained above, all results express the derivative of a parametric integral as the integral of a derivative. The variations come from the assumptions and from the different ways of expressing derivative, especially Fréchet derivatives vs elementary derivative of function of one real variable. * `has_fderiv_at_of_dominated_loc_of_lip`: this version assumes `F x` is ae-measurable for x near `x₀`, `F x₀` is integrable, `λ x, F x a` has derivative `F' a : H →L[ℝ] E` at `x₀` which is ae-measurable, `λ x, F x a` is locally Lipschitz near `x₀` for almost every `a`, with a Lipschitz bound which is integrable with respect to `a`. A subtle point is that the "near x₀" in the last condition has to be uniform in `a`. This is controlled by a positive number `ε`. * `has_fderiv_at_of_dominated_of_fderiv_le`: this version assume `λ x, F x a` has derivative `F' x a` for `x` near `x₀` and `F' x` is bounded by an integrable function independent from `x` near `x₀`. `has_deriv_at_of_dominated_loc_of_lip` and `has_deriv_at_of_dominated_loc_of_deriv_le ` are versions of the above two results that assume `H = ℝ` and use the high-school derivative `deriv` instead of Fréchet derivative `fderiv`. -/ noncomputable theory open topological_space measure_theory filter metric open_locale topological_space filter variables {α : Type*} [measurable_space α] {μ : measure α} {E : Type*} [normed_group E] [normed_space ℝ E] [complete_space E] [second_countable_topology E] [measurable_space E] [borel_space E] {H : Type*} [normed_group H] [normed_space ℝ H] [second_countable_topology $ H →L[ℝ] E] /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` with integrable Lipschitz bound (with a ball radius independent of `a`), and `F x` is ae-measurable for `x` in the same ball. See `has_fderiv_at_of_dominated_loc_of_lip` for a slightly more general version. -/ lemma has_fderiv_at_of_dominated_loc_of_lip' {F : H → α → E} {F' : α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ x ∈ ball x₀ ε, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) (h_lipsch : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' a) x₀) : integrable F' μ ∧ has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have nneg : ∀ x, 0 ≤ ∥x - x₀∥⁻¹ := λ x, inv_nonneg.mpr (norm_nonneg _) , set b : α → ℝ := λ a, abs (bound a), have b_int : integrable b μ := bound_integrable.norm, have b_nonneg : ∀ a, 0 ≤ b a := λ a, abs_nonneg _, have hF_int' : ∀ x ∈ ball x₀ ε, integrable (F x) μ, { intros x x_in, have : ∀ᵐ a ∂μ, ∥F x₀ a - F x a∥ ≤ ε * ∥(bound a : ℝ)∥, { apply h_lipsch.mono, intros a ha, rw lipschitz_on_with_iff_norm_sub_le at ha, apply (ha x₀ x₀_in x x_in).trans, rw [mul_comm, nnreal.coe_nnabs, real.norm_eq_abs], rw [mem_ball, dist_eq_norm, norm_sub_rev] at x_in, exact mul_le_mul_of_nonneg_right (le_of_lt x_in) (abs_nonneg _) }, exact integrable_of_norm_sub_le (hF_meas x x_in) hF_int (integrable.const_mul bound_integrable.norm ε) this }, have hF'_int : integrable F' μ, { have : ∀ᵐ a ∂μ, ∥F' a∥ ≤ b a, { apply (h_diff.and h_lipsch).mono, rintros a ⟨ha_diff, ha_lip⟩, exact ha_diff.le_of_lip (ball_mem_nhds _ ε_pos) ha_lip }, exact b_int.mono' hF'_meas this }, refine ⟨hF'_int, _⟩, have h_ball: ball x₀ ε ∈ 𝓝 x₀ := ball_mem_nhds x₀ ε_pos, have : ∀ᶠ x in 𝓝 x₀, ∥x - x₀∥⁻¹ * ∥∫ a, F x a ∂μ - ∫ a, F x₀ a ∂μ - (∫ a, F' a ∂μ) (x - x₀)∥ = ∥∫ a, ∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀)) ∂μ∥, { apply mem_sets_of_superset (ball_mem_nhds _ ε_pos), intros x x_in, rw [set.mem_set_of_eq, ← norm_smul_of_nonneg (nneg _), integral_smul, integral_sub, integral_sub, ← continuous_linear_map.integral_apply hF'_int], exacts [hF_int' x x_in, hF_int, (hF_int' x x_in).sub hF_int, hF'_int.apply_continuous_linear_map _] }, rw [has_fderiv_at_iff_tendsto, tendsto_congr' this, ← tendsto_zero_iff_norm_tendsto_zero, ← show ∫ (a : α), ∥x₀ - x₀∥⁻¹ • (F x₀ a - F x₀ a - (F' a) (x₀ - x₀)) ∂μ = 0, by simp], apply tendsto_integral_filter_of_dominated_convergence, { apply is_countably_generated_nhds }, { filter_upwards [h_ball], intros x x_in, apply ae_measurable.const_smul, exact ((hF_meas _ x_in).sub (hF_meas _ x₀_in)).sub (hF'_meas.apply_continuous_linear_map _) }, { simp [measurable_const] }, { apply mem_sets_of_superset h_ball, intros x hx, apply (h_diff.and h_lipsch).mono, rintros a ⟨ha_deriv, ha_bound⟩, show ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥ ≤ b a + ∥F' a∥, replace ha_bound : ∥F x a - F x₀ a∥ ≤ b a * ∥x - x₀∥, { rw lipschitz_on_with_iff_norm_sub_le at ha_bound, exact ha_bound _ hx _ x₀_in }, calc ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥ = ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a) - ∥x - x₀∥⁻¹ • F' a (x - x₀)∥ : by rw smul_sub ... ≤ ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a)∥ + ∥∥x - x₀∥⁻¹ • F' a (x - x₀)∥ : norm_sub_le _ _ ... = ∥x - x₀∥⁻¹ * ∥F x a - F x₀ a∥ + ∥x - x₀∥⁻¹ * ∥F' a (x - x₀)∥ : by { rw [norm_smul_of_nonneg, norm_smul_of_nonneg] ; exact nneg _} ... ≤ ∥x - x₀∥⁻¹ * (b a * ∥x - x₀∥) + ∥x - x₀∥⁻¹ * (∥F' a∥ * ∥x - x₀∥) : add_le_add _ _ ... ≤ b a + ∥F' a∥ : _, exact mul_le_mul_of_nonneg_left ha_bound (nneg _), apply mul_le_mul_of_nonneg_left ((F' a).le_op_norm _) (nneg _), by_cases h : ∥x - x₀∥ = 0, { simpa [h] using add_nonneg (b_nonneg a) (norm_nonneg (F' a)) }, { field_simp [h] } }, { exact b_int.add hF'_int.norm }, { apply h_diff.mono, intros a ha, suffices : tendsto (λ x, ∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))) (𝓝 x₀) (𝓝 0), by simpa, rw tendsto_zero_iff_norm_tendsto_zero, have : (λ x, ∥x - x₀∥⁻¹ * ∥F x a - F x₀ a - F' a (x - x₀)∥) = λ x, ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥, { ext x, rw norm_smul_of_nonneg (nneg _) }, rwa [has_fderiv_at_iff_tendsto, this] at ha }, end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` (with a ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_of_dominated_loc_of_lip {F : H → α → E} {F' : α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) (h_lip : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' a) x₀) : integrable F' μ ∧ has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin obtain ⟨ε', ε'_pos, h'⟩ : ∃ ε' > 0, ∀ x ∈ ball x₀ ε', ae_measurable (F x) μ, by simpa using nhds_basis_ball.eventually_iff.mp hF_meas, set δ := min ε ε', have δ_pos : 0 < δ := lt_min ε_pos ε'_pos, replace h' : ∀ x, x ∈ ball x₀ δ → ae_measurable (F x) μ, { intros x x_in, exact h' _ (ball_subset_ball (min_le_right ε ε') x_in) }, replace h_lip : ∀ᵐ (a : α) ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ δ), { apply h_lip.mono, intros a lip, exact lip.mono (ball_subset_ball $ min_le_left ε ε') }, apply has_fderiv_at_of_dominated_loc_of_lip' δ_pos ; assumption end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on a ball around `x₀` for ae `a` with derivative norm uniformly bounded by an integrable function (the ball radius is independent of `a`), and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_of_dominated_of_fderiv_le {F : H → α → E} {F' : H → α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable (F' x₀) μ) (h_bound : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F' x a∥ ≤ bound a) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, has_fderiv_at (λ x, F x a) (F' x a) x) : has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' x₀ a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have diff_x₀ : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' x₀ a) x₀ := h_diff.mono (λ a ha, ha x₀ x₀_in), have : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs (bound a)) (λ x, F x a) (ball x₀ ε), { apply (h_diff.and h_bound).mono, rintros a ⟨ha_deriv, ha_bound⟩, have bound_nonneg : 0 ≤ bound a := (norm_nonneg (F' x₀ a)).trans (ha_bound x₀ x₀_in), rw show real.nnabs (bound a) = real.to_nnreal (bound a), by simp [bound_nonneg], apply convex.lipschitz_on_with_of_norm_has_fderiv_within_le _ ha_bound (convex_ball _ _), intros x x_in, exact (ha_deriv x x_in).has_fderiv_within_at, }, exact (has_fderiv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas this bound_integrable diff_x₀).2 end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : ℝ`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on an interval around `x₀` for ae `a` (with interval radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_of_dominated_loc_of_lip {F : ℝ → α → E} {F' : α → E} {x₀ : ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) {bound : α → ℝ} (h_lipsch : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_deriv_at (λ x, F x a) (F' a) x₀) : (integrable F' μ) ∧ has_deriv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin have hm := (continuous_linear_map.smul_rightL ℝ ℝ E 1).continuous.measurable.comp_ae_measurable hF'_meas, cases has_fderiv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hm h_lipsch bound_integrable h_diff with hF'_int key, replace hF'_int : integrable F' μ, { rw [← integrable_norm_iff hm] at hF'_int, simpa only [integrable_norm_iff, hF'_meas, one_mul, continuous_linear_map.norm_id_field', continuous_linear_map.norm_smul_rightL_apply] using hF'_int}, refine ⟨hF'_int, _⟩, simp_rw has_deriv_at_iff_has_fderiv_at at h_diff ⊢, rwa continuous_linear_map.integral_comp_comm _ hF'_int at key, end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : ℝ`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on an interval around `x₀` for ae `a` (with interval radius independent of `a`) with derivative uniformly bounded by an integrable function, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_of_dominated_loc_of_deriv_le {F : ℝ → α → E} {F' : ℝ → α → E} {x₀ : ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable (F' x₀) μ) {bound : α → ℝ} (h_bound : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F' x a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_diff : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, has_deriv_at (λ x, F x a) (F' x a) x) : (integrable (F' x₀) μ) ∧ has_deriv_at (λn, ∫ a, F n a ∂μ) (∫ a, F' x₀ a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have diff_x₀ : ∀ᵐ a ∂μ, has_deriv_at (λ x, F x a) (F' x₀ a) x₀ := h_diff.mono (λ a ha, ha x₀ x₀_in), have : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs (bound a)) (λ (x : ℝ), F x a) (ball x₀ ε), { apply (h_diff.and h_bound).mono, rintros a ⟨ha_deriv, ha_bound⟩, have bound_nonneg : 0 ≤ bound a := (norm_nonneg (F' x₀ a)).trans (ha_bound x₀ x₀_in), rw show real.nnabs (bound a) = real.to_nnreal (bound a), by simp [bound_nonneg], apply convex.lipschitz_on_with_of_norm_has_deriv_within_le (convex_ball _ _) (λ x x_in, (ha_deriv x x_in).has_deriv_within_at) ha_bound }, exact has_deriv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas this bound_integrable diff_x₀ end
ddd9bb957dd73e867033e7bc38b46cd19c283362
98beff2e97d91a54bdcee52f922c4e1866a6c9b9
/src/pullback_colimit.lean
1141a1f4d58805fe2d2677c2bec8017e9d21b004
[]
no_license
b-mehta/topos
c3fc43fb04ba16bae1965ce5c26c6461172e5bc6
c9032b11789e36038bc841a1e2b486972421b983
refs/heads/master
1,629,609,492,867
1,609,907,263,000
1,609,907,263,000
240,943,034
43
3
null
1,598,210,062,000
1,581,877,668,000
Lean
UTF-8
Lean
false
false
2,392
lean
import locally_cartesian_closed namespace category_theory open category limits noncomputable theory universes v u variables {C : Type u} [category.{v} C] variables {J : Type v} [small_category J] variables {K₁ K₂ : J ⥤ C} variables (c₁ : cocone K₁) {c₂ : cocone K₂} (t₂ : is_colimit c₂) variables (τ : K₁ ⟶ K₂) (f : c₁.X ⟶ c₂.X) variables (all_comm : ∀ (j : J), τ.app j ≫ c₂.ι.app j = c₁.ι.app j ≫ f) variables (all_pb : Π (j : J), is_limit (pullback_cone.mk _ _ (all_comm j))) variables [has_finite_limits C] [is_locally_cartesian_closed C] [has_colimits_of_shape J C] include t₂ all_comm all_pb def iso_diagrams : K₁ ≅ pullback_diagram f K₂ c₂ (𝟙 c₂.X) := begin apply nat_iso.of_components (λ j, _) _, { refine is_limit.cone_points_iso_of_nat_iso (all_pb j) (cone_is_pullback _ _) _, { apply nat_iso.of_components _ _, { intro j, refl }, { rintros X Y ⟨f⟩, dsimp, simp, cases f_1_1, dsimp, simp, dsimp, simp } } }, { intros X Y g, dsimp only [pullback_diagram_map, is_limit.cone_points_iso_of_nat_iso], ext1, { rw [assoc, assoc, pullback.lift_fst], change _ ≫ _ ≫ (pullback_cone.mk _ _ _).fst = _ ≫ (pullback_cone.mk _ _ _).fst ≫ _, rw is_limit.map_π, rw is_limit.map_π_assoc, dsimp, rw [comp_id, τ.naturality, id_comp] }, { rw [assoc, assoc, pullback.lift_snd], change _ ≫ _ ≫ (pullback_cone.mk _ _ _).snd = _ ≫ (pullback_cone.mk _ _ _).snd, rw is_limit.map_π, rw is_limit.map_π, dsimp, rw [comp_id, comp_id], rw c₁.w, } } end def pullback_colimit : is_colimit c₁ := begin apply is_colimit.of_iso_colimit ((is_colimit.precompose_hom_equiv (iso_diagrams c₁ t₂ τ f all_comm all_pb) _).inv_fun (pullback_preserves f c₂ t₂ (𝟙 _))), apply cocones.ext _ _, { refine {iso . hom := pullback.snd, inv := pullback.lift f (𝟙 _) (by simp), hom_inv_id' := _}, change _ = 𝟙 _, apply pullback.hom_ext, rw [assoc, pullback.lift_fst, ← pullback.condition, comp_id, id_comp], rw [assoc, pullback.lift_snd, comp_id, id_comp] }, { intro j, dsimp [iso_diagrams], rw [assoc], rw pullback.lift_snd, change _ ≫ (pullback_cone.mk _ _ _).snd = _, rw is_limit.map_π, dsimp, apply comp_id } end end category_theory
4ddb225a374945af08cb6f4d49d1da7abd92c286
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/algebra/group_power/lemmas.lean
c5f41361d61d3c93f102ec5be2d3871a8c809db3
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
35,935
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.group_power.basic import algebra.invertible import algebra.opposites import data.list.basic import data.int.cast import data.equiv.basic import data.equiv.mul_add /-! # Lemmas about power operations on monoids and groups This file contains lemmas about `monoid.pow`, `group.pow`, `nsmul`, `zsmul` which require additional imports besides those available in `algebra.group_power.basic`. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-! ### (Additive) monoid -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem nsmul_one [has_one A] : ∀ n : ℕ, n • (1 : A) = n := add_monoid_hom.eq_nat_cast ⟨λ n, n • (1 : A), zero_nsmul _, λ _ _, add_nsmul _ _ _⟩ (one_nsmul _) @[simp, norm_cast, to_additive] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n := (units.coe_hom M).map_pow u n instance invertible_pow (m : M) [invertible m] (n : ℕ) : invertible (m ^ n) := { inv_of := ⅟ m ^ n, inv_of_mul_self := by rw [← (commute_inv_of m).symm.mul_pow, inv_of_mul_self, one_pow], mul_inv_of_self := by rw [← (commute_inv_of m).mul_pow, mul_inv_of_self, one_pow] } lemma inv_of_pow (m : M) [invertible m] (n : ℕ) [invertible (m ^ n)] : ⅟(m ^ n) = ⅟m ^ n := @invertible_unique M _ (m ^ n) (m ^ n) rfl ‹_› (invertible_pow m n) lemma is_unit.pow {m : M} (n : ℕ) : is_unit m → is_unit (m ^ n) := λ ⟨u, hu⟩, ⟨u ^ n, by simp *⟩ @[simp] lemma is_unit_pow_succ_iff {m : M} {n : ℕ} : is_unit (m ^ (n + 1)) ↔ is_unit m := begin refine ⟨_, λ h, h.pow _⟩, rw [pow_succ, ((commute.refl _).pow_right _).is_unit_mul_iff], exact and.left end lemma is_unit_pos_pow_iff {m : M} : ∀ {n : ℕ} (h : 0 < n), is_unit (m ^ n) ↔ is_unit m | (n + 1) _ := is_unit_pow_succ_iff /-- If `x ^ n.succ = 1` then `x` has an inverse, `x^n`. -/ def invertible_of_pow_succ_eq_one (x : M) (n : ℕ) (hx : x ^ n.succ = 1) : invertible x := ⟨x ^ n, (pow_succ' x n).symm.trans hx, (pow_succ x n).symm.trans hx⟩ /-- If `x ^ n = 1` then `x` has an inverse, `x^(n - 1)`. -/ def invertible_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : invertible x := begin apply invertible_of_pow_succ_eq_one x (n - 1), convert hx, exact tsub_add_cancel_of_le (nat.succ_le_of_lt hn), end lemma is_unit_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : is_unit x := begin haveI := invertible_of_pow_eq_one x n hx hn, exact is_unit_of_invertible x end lemma smul_pow [mul_action M N] [is_scalar_tower M N N] [smul_comm_class M N N] (k : M) (x : N) (p : ℕ) : (k • x) ^ p = k ^ p • x ^ p := begin induction p with p IH, { simp }, { rw [pow_succ', IH, smul_mul_smul, ←pow_succ', ←pow_succ'] } end @[simp] lemma smul_pow' [mul_distrib_mul_action M N] (x : M) (m : N) (n : ℕ) : x • m ^ n = (x • m) ^ n := begin induction n with n ih, { rw [pow_zero, pow_zero], exact smul_one x }, { rw [pow_succ, pow_succ], exact (smul_mul' x m (m ^ n)).trans (congr_arg _ ih) } end end monoid section group variables [group G] [group H] [add_group A] [add_group B] open int local attribute [ematch] le_of_lt open nat theorem zsmul_one [has_one A] (n : ℤ) : n • (1 : A) = n := by cases n; simp @[to_additive add_one_zsmul] lemma zpow_add_one (a : G) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a | (of_nat n) := by simp [← int.coe_nat_succ, pow_succ'] | -[1+0] := by simp [int.neg_succ_of_nat_eq] | -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, zpow_neg, neg_add, neg_add_cancel_right, zpow_neg, ← int.coe_nat_succ, zpow_coe_nat, zpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev, inv_mul_cancel_right] @[to_additive zsmul_sub_one] lemma zpow_sub_one (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ := calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm ... = a^n * a⁻¹ : by rw [← zpow_add_one, sub_add_cancel] @[to_additive add_zsmul] lemma zpow_add (a : G) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, zpow_add_one, ihn, mul_assoc] }, { rw [zpow_sub_one, ← mul_assoc, ← ihn, ← zpow_sub_one, add_sub_assoc] } end @[to_additive add_zsmul_self] lemma mul_self_zpow (b : G) (m : ℤ) : b*b^m = b^(m+1) := by { conv_lhs {congr, rw ← zpow_one b }, rw [← zpow_add, add_comm] } @[to_additive add_self_zsmul] lemma mul_zpow_self (b : G) (m : ℤ) : b^m*b = b^(m+1) := by { conv_lhs {congr, skip, rw ← zpow_one b }, rw [← zpow_add, add_comm] } @[to_additive sub_zsmul] lemma zpow_sub (a : G) (m n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := by rw [sub_eq_add_neg, zpow_add, zpow_neg] @[to_additive one_add_zsmul] theorem zpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [zpow_add, zpow_one] @[to_additive] theorem zpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← zpow_add, ← zpow_add, add_comm] -- note that `mul_zsmul` and `zpow_mul` have the primes swapped since their argument order -- and therefore the more "natural" choice of lemma is reversed. @[to_additive mul_zsmul'] theorem zpow_mul (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ m) ^ n := int.induction_on n (by simp) (λ n ihn, by simp [mul_add, zpow_add, ihn]) (λ n ihn, by simp only [mul_sub, zpow_sub, ihn, mul_one, zpow_one]) @[to_additive mul_zsmul] theorem zpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, zpow_mul] @[to_additive bit0_zsmul] theorem zpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := zpow_add _ _ _ @[to_additive bit1_zsmul] theorem zpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, zpow_add, zpow_bit0, zpow_one] @[simp, norm_cast, to_additive] lemma units.coe_zpow (u : units G) (n : ℤ) : ((u ^ n : units G) : G) = u ^ n := (units.coe_hom G).map_zpow u n end group section ordered_add_comm_group variables [ordered_add_comm_group A] /-! Lemmas about `zsmul` under ordering, placed here (rather than in `algebra.group_power.order` with their friends) because they require facts from `data.int.basic`-/ open int lemma zsmul_pos {a : A} (ha : 0 < a) {k : ℤ} (hk : (0:ℤ) < k) : 0 < k • a := begin lift k to ℕ using int.le_of_lt hk, rw coe_nat_zsmul, apply nsmul_pos ha, exact (coe_nat_pos.mp hk).ne', end theorem zsmul_strict_mono_left {a : A} (ha : 0 < a) : strict_mono (λ n : ℤ, n • a) := λ n m h, calc n • a = n • a + 0 : (add_zero _).symm ... < n • a + (m - n) • a : add_lt_add_left (zsmul_pos ha (sub_pos.mpr h)) _ ... = m • a : by { rw [← add_zsmul], simp } theorem zsmul_mono_left {a : A} (ha : 0 ≤ a) : monotone (λ n : ℤ, n • a) := λ n m h, calc n • a = n • a + 0 : (add_zero _).symm ... ≤ n • a + (m - n) • a : add_le_add_left (zsmul_nonneg ha (sub_nonneg.mpr h)) _ ... = m • a : by { rw [← add_zsmul], simp } theorem zsmul_le_zsmul {a : A} {n m : ℤ} (ha : 0 ≤ a) (h : n ≤ m) : n • a ≤ m • a := zsmul_mono_left ha h theorem zsmul_lt_zsmul {a : A} {n m : ℤ} (ha : 0 < a) (h : n < m) : n • a < m • a := zsmul_strict_mono_left ha h theorem zsmul_le_zsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n • a ≤ m • a ↔ n ≤ m := (zsmul_strict_mono_left ha).le_iff_le theorem zsmul_lt_zsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n • a < m • a ↔ n < m := (zsmul_strict_mono_left ha).lt_iff_lt variables (A) lemma zsmul_strict_mono_right {n : ℤ} (hn : 0 < n) : strict_mono ((•) n : A → A) := λ a b hab, begin rw ← sub_pos at hab, rw [← sub_pos, ← zsmul_sub], exact zsmul_pos hab hn, end lemma zsmul_mono_right {n : ℤ} (hn : 0 ≤ n) : monotone ((•) n : A → A) := λ a b hab, begin rw ← sub_nonneg at hab, rw [← sub_nonneg, ← zsmul_sub], exact zsmul_nonneg hab hn, end variables {A} theorem zsmul_le_zsmul' {n : ℤ} (hn : 0 ≤ n) {a₁ a₂ : A} (h : a₁ ≤ a₂) : n • a₁ ≤ n • a₂ := zsmul_mono_right A hn h theorem zsmul_lt_zsmul' {n : ℤ} (hn : 0 < n) {a₁ a₂ : A} (h : a₁ < a₂) : n • a₁ < n • a₂ := zsmul_strict_mono_right A hn h lemma abs_nsmul {α : Type*} [linear_ordered_add_comm_group α] (n : ℕ) (a : α) : |n • a| = n • |a| := begin cases le_total a 0 with hneg hpos, { rw [abs_of_nonpos hneg, ← abs_neg, ← neg_nsmul, abs_of_nonneg], exact nsmul_nonneg (neg_nonneg.mpr hneg) n }, { rw [abs_of_nonneg hpos, abs_of_nonneg], exact nsmul_nonneg hpos n } end lemma abs_zsmul {α : Type*} [linear_ordered_add_comm_group α] (n : ℤ) (a : α) : |n • a| = |n| • |a| := begin by_cases n0 : 0 ≤ n, { lift n to ℕ using n0, simp only [abs_nsmul, coe_nat_abs, coe_nat_zsmul] }, { lift (- n) to ℕ using int.le_of_lt (neg_pos.mpr (not_le.mp n0)) with m h, rw [← abs_neg (n • a), ← neg_zsmul, ← abs_neg n, ← h, coe_nat_zsmul, coe_nat_abs, coe_nat_zsmul], exact abs_nsmul m _ }, end lemma abs_add_eq_add_abs_le {α : Type*} [linear_ordered_add_comm_group α] {a b : α} (hle : a ≤ b) : |a + b| = |a| + |b| ↔ (0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0) := begin by_cases a0 : 0 ≤ a; by_cases b0 : 0 ≤ b, { simp [a0, b0, abs_of_nonneg, add_nonneg a0 b0] }, { exact (lt_irrefl (0 : α) (a0.trans_lt (hle.trans_lt (not_le.mp b0)))).elim }, any_goals { simp [(not_le.mp a0).le, (not_le.mp b0).le, abs_of_nonpos, add_nonpos, add_comm] }, obtain F := (not_le.mp a0), have : (|a + b| = -a + b ↔ b ≤ 0) ↔ (|a + b| = |a| + |b| ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0), { simp [a0, b0, abs_of_neg, abs_of_nonneg, F, F.le] }, refine this.mp ⟨λ h, _, λ h, by simp only [le_antisymm h b0, abs_of_neg F, add_zero]⟩, by_cases ba : a + b ≤ 0, { refine le_of_eq (eq_zero_of_neg_eq _), rwa [abs_of_nonpos ba, neg_add_rev, add_comm, add_right_inj] at h }, { refine (lt_irrefl (0 : α) _).elim, rw [abs_of_pos (not_le.mp ba), add_left_inj] at h, rwa eq_zero_of_neg_eq h.symm at F } end lemma abs_add_eq_add_abs_iff {α : Type*} [linear_ordered_add_comm_group α] (a b : α) : |a + b| = |a| + |b| ↔ (0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0) := begin by_cases ab : a ≤ b, { exact abs_add_eq_add_abs_le ab }, { rw [add_comm a, add_comm (abs _), abs_add_eq_add_abs_le ((not_le.mp ab).le), and.comm, @and.comm (b ≤ 0 ) _] } end end ordered_add_comm_group section linear_ordered_add_comm_group variable [linear_ordered_add_comm_group A] theorem zsmul_le_zsmul_iff' {n : ℤ} (hn : 0 < n) {a₁ a₂ : A} : n • a₁ ≤ n • a₂ ↔ a₁ ≤ a₂ := (zsmul_strict_mono_right A hn).le_iff_le theorem zsmul_lt_zsmul_iff' {n : ℤ} (hn : 0 < n) {a₁ a₂ : A} : n • a₁ < n • a₂ ↔ a₁ < a₂ := (zsmul_strict_mono_right A hn).lt_iff_lt theorem nsmul_le_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n • a ≤ m • a ↔ n ≤ m := begin refine ⟨λ h, _, nsmul_le_nsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (nsmul_lt_nsmul ha (not_le.mp H)) h) end theorem nsmul_lt_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n • a < m • a ↔ n < m := begin refine ⟨λ h, _, nsmul_lt_nsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (nsmul_le_nsmul (le_of_lt ha) $ not_lt.mp H) h) end /-- See also `smul_right_injective`. TODO: provide a `no_zero_smul_divisors` instance. We can't do that here because importing that definition would create import cycles. -/ lemma zsmul_right_injective {m : ℤ} (hm : m ≠ 0) : function.injective ((•) m : A → A) := begin cases hm.symm.lt_or_lt, { exact (zsmul_strict_mono_right A h).injective, }, { intros a b hab, refine (zsmul_strict_mono_right A (neg_pos.mpr h)).injective _, rw [neg_zsmul, neg_zsmul, hab], }, end lemma zsmul_right_inj {a b : A} {m : ℤ} (hm : m ≠ 0) : m • a = m • b ↔ a = b := (zsmul_right_injective hm).eq_iff /-- Alias of `zsmul_right_inj`, for ease of discovery alongside `zsmul_le_zsmul_iff'` and `zsmul_lt_zsmul_iff'`. -/ lemma zsmul_eq_zsmul_iff' {a b : A} {m : ℤ} (hm : m ≠ 0) : m • a = m • b ↔ a = b := zsmul_right_inj hm end linear_ordered_add_comm_group @[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : ℕ) : ((n • a : A) : with_bot A) = n • a := add_monoid_hom.map_nsmul ⟨(coe : A → with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n theorem nsmul_eq_mul' [semiring R] (a : R) (n : ℕ) : n • a = a * n := by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero], rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]] @[simp] theorem nsmul_eq_mul [semiring R] (n : ℕ) (a : R) : n • a = n * a := by rw [nsmul_eq_mul', (n.cast_commute a).eq] theorem mul_nsmul_left [semiring R] (a b : R) (n : ℕ) : n • (a * b) = a * (n • b) := by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc] theorem mul_nsmul_assoc [semiring R] (a b : R) (n : ℕ) : n • (a * b) = n • a * b := by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc] @[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := begin induction m with m ih, { rw [pow_zero, pow_zero], exact nat.cast_one }, { rw [pow_succ', pow_succ', nat.cast_mul, ih] } end @[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [pow_succ', pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, pow_succ', ih]] -- The next four lemmas allow us to replace multiplication by a numeral with a `zsmul` expression. -- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`. lemma bit0_mul [ring R] {n r : R} : bit0 n * r = (2 : ℤ) • (n * r) := by { dsimp [bit0], rw [add_mul, add_zsmul, one_zsmul], } lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = (2 : ℤ) • (r * n) := by { dsimp [bit0], rw [mul_add, add_zsmul, one_zsmul], } lemma bit1_mul [ring R] {n r : R} : bit1 n * r = (2 : ℤ) • (n * r) + r := by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], } lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = (2 : ℤ) • (r * n) + r := by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], } @[simp] theorem zsmul_eq_mul [ring R] (a : R) : ∀ (n : ℤ), n • a = n * a | (n : ℕ) := by { rw [coe_nat_zsmul, nsmul_eq_mul], refl } | -[1+ n] := by simp [nat.cast_succ, neg_add_rev, int.cast_neg_succ_of_nat, add_mul] theorem zsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n • a = a * n := by rw [zsmul_eq_mul, (n.cast_commute a).eq] theorem mul_zsmul_left [ring R] (a b : R) (n : ℤ) : n • (a * b) = a * (n • b) := by rw [zsmul_eq_mul', zsmul_eq_mul', mul_assoc] theorem mul_zsmul_assoc [ring R] (a b : R) (n : ℤ) : n • (a * b) = n • a * b := by rw [zsmul_eq_mul, zsmul_eq_mul, mul_assoc] lemma zsmul_int_int (a b : ℤ) : a • b = a * b := by simp lemma zsmul_int_one (n : ℤ) : n • 1 = n := by simp @[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := begin induction m with m ih, { rw [pow_zero, pow_zero, int.cast_one] }, { rw [pow_succ, pow_succ, int.cast_mul, ih] } end lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = (-1) ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [sq] section ordered_semiring variables [ordered_semiring R] {a : R} /-- Bernoulli's inequality. This version works for semirings but requires additional hypotheses `0 ≤ a * a` and `0 ≤ (1 + a) * (1 + a)`. -/ theorem one_add_mul_le_pow' (Hsq : 0 ≤ a * a) (Hsq' : 0 ≤ (1 + a) * (1 + a)) (H : 0 ≤ 2 + a) : ∀ (n : ℕ), 1 + (n : R) * a ≤ (1 + a) ^ n | 0 := by simp | 1 := by simp | (n+2) := have 0 ≤ (n : R) * (a * a * (2 + a)) + a * a, from add_nonneg (mul_nonneg n.cast_nonneg (mul_nonneg Hsq H)) Hsq, calc 1 + (↑(n + 2) : R) * a ≤ 1 + ↑(n + 2) * a + (n * (a * a * (2 + a)) + a * a) : (le_add_iff_nonneg_right _).2 this ... = (1 + a) * (1 + a) * (1 + n * a) : by { simp [add_mul, mul_add, bit0, mul_assoc, (n.cast_commute (_ : R)).left_comm], ac_refl } ... ≤ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) Hsq' ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] private lemma pow_lt_pow_of_lt_one_aux (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin rw [←one_mul (a^i), add_zero, pow_succ], exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw [←one_mul (a^i), pow_succ], apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by { rw [←add_assoc, ←one_mul (a^i), pow_succ], exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one } lemma pow_lt_pow_of_lt_one (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_lt_pow_iff_of_lt_one {n m : ℕ} (hpos : 0 < a) (h : a < 1) : a ^ m < a ^ n ↔ n < m := begin have : strict_mono (λ (n : order_dual ℕ), a ^ (id n : ℕ)) := λ m n, pow_lt_pow_of_lt_one hpos h, exact this.lt_iff_lt end lemma pow_le_pow_of_le_one (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_of_le_one (h₀ : 0 ≤ a) (h₁ : a ≤ 1) {n : ℕ} (hn : n ≠ 0) : a ^ n ≤ a := (pow_one a).subst (pow_le_pow_of_le_one h₀ h₁ (nat.pos_of_ne_zero hn)) lemma sq_le (h₀ : 0 ≤ a) (h₁ : a ≤ 1) : a ^ 2 ≤ a := pow_le_of_le_one h₀ h₁ two_ne_zero end ordered_semiring section linear_ordered_semiring variables [linear_ordered_semiring R] lemma sign_cases_of_C_mul_pow_nonneg {C r : R} (h : ∀ n : ℕ, 0 ≤ C * r ^ n) : C = 0 ∨ (0 < C ∧ 0 ≤ r) := begin have : 0 ≤ C, by simpa only [pow_zero, mul_one] using h 0, refine this.eq_or_lt.elim (λ h, or.inl h.symm) (λ hC, or.inr ⟨hC, _⟩), refine nonneg_of_mul_nonneg_left _ hC, simpa only [pow_one] using h 1 end end linear_ordered_semiring section linear_ordered_ring variables [linear_ordered_ring R] {a : R} {n : ℕ} @[simp] lemma abs_pow (a : R) (n : ℕ) : |a ^ n| = |a| ^ n := (pow_abs a n).symm @[simp] theorem pow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ pow_nonneg h' _, λ ha, pow_bit1_neg ha n⟩ @[simp] theorem pow_bit1_nonneg_iff : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 pow_bit1_neg_iff @[simp] theorem pow_bit1_nonpos_iff : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := by simp only [le_iff_lt_or_eq, pow_bit1_neg_iff, pow_eq_zero_iff (bit1_pos (zero_le n))] @[simp] theorem pow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le pow_bit1_nonpos_iff lemma even.pow_nonneg (hn : even n) (a : R) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_nonneg a k lemma even.pow_pos (hn : even n) (ha : a ≠ 0) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using pow_bit0_pos ha k lemma odd.pow_nonpos (hn : odd n) (ha : a ≤ 0) : a ^ n ≤ 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_nonpos_iff.mpr ha lemma odd.pow_neg (hn : odd n) (ha : a < 0) : a ^ n < 0:= by cases hn with k hk; simpa only [hk, two_mul] using pow_bit1_neg_iff.mpr ha lemma odd.pow_nonneg_iff (hn : odd n) : 0 ≤ a ^ n ↔ 0 ≤ a := ⟨λ h, le_of_not_lt (λ ha, h.not_lt $ hn.pow_neg ha), λ ha, pow_nonneg ha n⟩ lemma odd.pow_nonpos_iff (hn : odd n) : a ^ n ≤ 0 ↔ a ≤ 0 := ⟨λ h, le_of_not_lt (λ ha, h.not_lt $ pow_pos ha _), hn.pow_nonpos⟩ lemma odd.pow_pos_iff (hn : odd n) : 0 < a ^ n ↔ 0 < a := ⟨λ h, lt_of_not_ge' (λ ha, h.not_le $ hn.pow_nonpos ha), λ ha, pow_pos ha n⟩ lemma odd.pow_neg_iff (hn : odd n) : a ^ n < 0 ↔ a < 0 := ⟨λ h, lt_of_not_ge' (λ ha, h.not_le $ pow_nonneg ha _), hn.pow_neg⟩ lemma even.pow_pos_iff (hn : even n) (h₀ : 0 < n) : 0 < a ^ n ↔ a ≠ 0 := ⟨λ h ha, by { rw [ha, zero_pow h₀] at h, exact lt_irrefl 0 h }, hn.pow_pos⟩ lemma even.pow_abs {p : ℕ} (hp : even p) (a : R) : |a| ^ p = a ^ p := begin rw [←abs_pow, abs_eq_self], exact hp.pow_nonneg _ end @[simp] lemma pow_bit0_abs (a : R) (p : ℕ) : |a| ^ bit0 p = a ^ bit0 p := (even_bit0 _).pow_abs _ lemma strict_mono_pow_bit1 (n : ℕ) : strict_mono (λ a : R, a ^ bit1 n) := begin intros a b hab, cases le_total a 0 with ha ha, { cases le_or_lt b 0 with hb hb, { rw [← neg_lt_neg_iff, ← neg_pow_bit1, ← neg_pow_bit1], exact pow_lt_pow_of_lt_left (neg_lt_neg hab) (neg_nonneg.2 hb) (bit1_pos (zero_le n)) }, { exact (pow_bit1_nonpos_iff.2 ha).trans_lt (pow_bit1_pos_iff.2 hb) } }, { exact pow_lt_pow_of_lt_left hab ha (bit1_pos (zero_le n)) } end lemma odd.strict_mono_pow (hn : odd n) : strict_mono (λ a : R, a ^ n) := by cases hn with k hk; simpa only [hk, two_mul] using strict_mono_pow_bit1 _ /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow (H : -2 ≤ a) (n : ℕ) : 1 + (n : R) * a ≤ (1 + a) ^ n := one_add_mul_le_pow' (mul_self_nonneg _) (mul_self_nonneg _) (neg_le_iff_add_nonneg'.1 H) _ /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_mul_sub_le_pow (H : -1 ≤ a) (n : ℕ) : 1 + (n : R) * (a - 1) ≤ a ^ n := have -2 ≤ a - 1, by rwa [bit0, neg_add, ← sub_eq_add_neg, sub_le_sub_iff_right], by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n end linear_ordered_ring /-- Bernoulli's inequality reformulated to estimate `(n : K)`. -/ theorem nat.cast_le_pow_sub_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ (a ^ n - 1) / (a - 1) := (le_div_iff (sub_pos.2 H)).2 $ le_sub_left_of_add_le $ one_add_mul_sub_le_pow ((neg_le_self $ @zero_le_one K _).trans H.le) _ /-- For any `a > 1` and a natural `n` we have `n ≤ a ^ n / (a - 1)`. See also `nat.cast_le_pow_sub_div_sub` for a stronger inequality with `a ^ n - 1` in the numerator. -/ theorem nat.cast_le_pow_div_sub {K : Type*} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : (n : K) ≤ a ^ n / (a - 1) := (n.cast_le_pow_sub_div_sub H).trans $ div_le_div_of_le (sub_nonneg.2 H.le) (sub_le_self _ zero_le_one) namespace int lemma units_sq (u : units ℤ) : u ^ 2 = 1 := (sq u).symm ▸ units_mul_self u alias int.units_sq ← int.units_pow_two lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_sq, one_pow, mul_one] @[simp] lemma nat_abs_sq (x : ℤ) : (x.nat_abs ^ 2 : ℤ) = x ^ 2 := by rw [sq, int.nat_abs_mul_self', sq] alias int.nat_abs_sq ← int.nat_abs_pow_two lemma abs_le_self_sq (a : ℤ) : (int.nat_abs a : ℤ) ≤ a ^ 2 := by { rw [← int.nat_abs_sq a, sq], norm_cast, apply nat.le_mul_self } alias int.abs_le_self_sq ← int.abs_le_self_pow_two lemma le_self_sq (b : ℤ) : b ≤ b ^ 2 := le_trans (le_nat_abs) (abs_le_self_sq _) alias int.le_self_sq ← int.le_self_pow_two lemma pow_right_injective {x : ℤ} (h : 1 < x.nat_abs) : function.injective ((^) x : ℕ → ℤ) := begin suffices : function.injective (nat_abs ∘ ((^) x : ℕ → ℤ)), { exact function.injective.of_comp this }, convert nat.pow_right_injective h, ext n, rw [function.comp_app, nat_abs_pow] end end int variables (M G A) /-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image of `multiplicative.of_add 1`. -/ def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, by { convert pow_zero x, exact to_add_one }, λ m n, pow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := pow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_nsmul] } } /-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image of `multiplicative.of_add 1`. -/ def zpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, zpow_zero x, λ m n, zpow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := zpow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_zpow, ← of_add_zsmul ] } } /-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/ def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) := { to_fun := λ x, ⟨λ n, n • x, zero_nsmul x, λ m n, add_nsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_nsmul, right_inv := λ f, add_monoid_hom.ext_nat $ one_nsmul (f 1) } /-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/ def zmultiples_hom [add_group A] : A ≃ (ℤ →+ A) := { to_fun := λ x, ⟨λ n, n • x, zero_zsmul x, λ m n, add_zsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_zsmul, right_inv := λ f, add_monoid_hom.ext_int $ one_zsmul (f 1) } attribute [to_additive multiples_hom] powers_hom attribute [to_additive zmultiples_hom] zpowers_hom variables {M G A} @[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) : powers_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) : (powers_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma zpowers_hom_apply [group G] (x : G) (n : multiplicative ℤ) : zpowers_hom G x n = x ^ n.to_add := rfl @[simp] lemma zpowers_hom_symm_apply [group G] (f : multiplicative ℤ →* G) : (zpowers_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_hom_apply [add_monoid A] (x : A) (n : ℕ) : multiples_hom A x n = n • x := rfl attribute [to_additive multiples_hom_apply] powers_hom_apply @[simp] lemma multiples_hom_symm_apply [add_monoid A] (f : ℕ →+ A) : (multiples_hom A).symm f = f 1 := rfl attribute [to_additive multiples_hom_symm_apply] powers_hom_symm_apply @[simp] lemma zmultiples_hom_apply [add_group A] (x : A) (n : ℤ) : zmultiples_hom A x n = n • x := rfl attribute [to_additive zmultiples_hom_apply] zpowers_hom_apply @[simp] lemma zmultiples_hom_symm_apply [add_group A] (f : ℤ →+ A) : (zmultiples_hom A).symm f = f 1 := rfl attribute [to_additive zmultiples_hom_symm_apply] zpowers_hom_symm_apply -- TODO use to_additive in the rest of this file lemma monoid_hom.apply_mnat [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply] @[ext] lemma monoid_hom.ext_mnat [monoid M] ⦃f g : multiplicative ℕ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [f.apply_mnat, g.apply_mnat, h] lemma monoid_hom.apply_mint [group M] (f : multiplicative ℤ →* M) (n : multiplicative ℤ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← zpowers_hom_symm_apply, ← zpowers_hom_apply, equiv.apply_symm_apply] /-! `monoid_hom.ext_mint` is defined in `data.int.cast` -/ lemma add_monoid_hom.apply_nat [add_monoid M] (f : ℕ →+ M) (n : ℕ) : f n = n • (f 1) := by rw [← multiples_hom_symm_apply, ← multiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_nat` is defined in `data.nat.cast` -/ lemma add_monoid_hom.apply_int [add_group M] (f : ℤ →+ M) (n : ℤ) : f n = n • (f 1) := by rw [← zmultiples_hom_symm_apply, ← zmultiples_hom_apply, equiv.apply_symm_apply] /-! `add_monoid_hom.ext_int` is defined in `data.int.cast` -/ variables (M G A) /-- If `M` is commutative, `powers_hom` is a multiplicative equivalence. -/ def powers_mul_hom [comm_monoid M] : M ≃* (multiplicative ℕ →* M) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_pow], ..powers_hom M} /-- If `M` is commutative, `zpowers_hom` is a multiplicative equivalence. -/ def zpowers_mul_hom [comm_group G] : G ≃* (multiplicative ℤ →* G) := { map_mul' := λ a b, monoid_hom.ext $ by simp [mul_zpow], ..zpowers_hom G} /-- If `M` is commutative, `multiples_hom` is an additive equivalence. -/ def multiples_add_hom [add_comm_monoid A] : A ≃+ (ℕ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [nsmul_add], ..multiples_hom A} /-- If `M` is commutative, `zmultiples_hom` is an additive equivalence. -/ def zmultiples_add_hom [add_comm_group A] : A ≃+ (ℤ →+ A) := { map_add' := λ a b, add_monoid_hom.ext $ by simp [zsmul_add], ..zmultiples_hom A} variables {M G A} @[simp] lemma powers_mul_hom_apply [comm_monoid M] (x : M) (n : multiplicative ℕ) : powers_mul_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_mul_hom_symm_apply [comm_monoid M] (f : multiplicative ℕ →* M) : (powers_mul_hom M).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma zpowers_mul_hom_apply [comm_group G] (x : G) (n : multiplicative ℤ) : zpowers_mul_hom G x n = x ^ n.to_add := rfl @[simp] lemma zpowers_mul_hom_symm_apply [comm_group G] (f : multiplicative ℤ →* G) : (zpowers_mul_hom G).symm f = f (multiplicative.of_add 1) := rfl @[simp] lemma multiples_add_hom_apply [add_comm_monoid A] (x : A) (n : ℕ) : multiples_add_hom A x n = n • x := rfl @[simp] lemma multiples_add_hom_symm_apply [add_comm_monoid A] (f : ℕ →+ A) : (multiples_add_hom A).symm f = f 1 := rfl @[simp] lemma zmultiples_add_hom_apply [add_comm_group A] (x : A) (n : ℤ) : zmultiples_add_hom A x n = n • x := rfl @[simp] lemma zmultiples_add_hom_symm_apply [add_comm_group A] (f : ℤ →+ A) : (zmultiples_add_hom A).symm f = f 1 := rfl /-! ### Commutativity (again) Facts about `semiconj_by` and `commute` that require `zpow` or `zsmul`, or the fact that integer multiplication equals semiring multiplication. -/ namespace semiconj_by section variables [semiring R] {a x y : R} @[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : ℕ) : semiconj_by a ((n : R) * x) (n * y) := semiconj_by.mul_right (nat.commute_cast _ _) h @[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : ℕ) : semiconj_by ((n : R) * a) x y := semiconj_by.mul_left (nat.cast_commute _ _) h @[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : ℕ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_nat_mul_left m).cast_nat_mul_right n end variables [monoid M] [group G] [ring R] @[simp, to_additive] lemma units_zpow_right {a : M} {x y : units M} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (↑(x^m)) (↑(y^m)) | (n : ℕ) := by simp only [zpow_coe_nat, units.coe_pow, h, pow_right] | -[1+n] := by simp only [zpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right] variables {a b x y x' y' : R} @[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : ℤ) : semiconj_by a ((m : ℤ) * x) (m * y) := semiconj_by.mul_right (int.commute_cast _ _) h @[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : ℤ) : semiconj_by ((m : R) * a) x y := semiconj_by.mul_left (int.cast_commute _ _) h @[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : ℤ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_int_mul_left m).cast_int_mul_right n end semiconj_by namespace commute section variables [semiring R] {a b : R} @[simp] theorem cast_nat_mul_right (h : commute a b) (n : ℕ) : commute a ((n : R) * b) := h.cast_nat_mul_right n @[simp] theorem cast_nat_mul_left (h : commute a b) (n : ℕ) : commute ((n : R) * a) b := h.cast_nat_mul_left n @[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : ℕ) : commute ((m : R) * a) (n * b) := h.cast_nat_mul_cast_nat_mul m n @[simp] theorem self_cast_nat_mul (n : ℕ) : commute a (n * a) := (commute.refl a).cast_nat_mul_right n @[simp] theorem cast_nat_mul_self (n : ℕ) : commute ((n : R) * a) a := (commute.refl a).cast_nat_mul_left n @[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : ℕ) : commute ((m : R) * a) (n * a) := (commute.refl a).cast_nat_mul_cast_nat_mul m n end variables [monoid M] [group G] [ring R] @[simp, to_additive] lemma units_zpow_right {a : M} {u : units M} (h : commute a u) (m : ℤ) : commute a (↑(u^m)) := h.units_zpow_right m @[simp, to_additive] lemma units_zpow_left {u : units M} {a : M} (h : commute ↑u a) (m : ℤ) : commute (↑(u^m)) a := (h.symm.units_zpow_right m).symm variables {a b : R} @[simp] lemma cast_int_mul_right (h : commute a b) (m : ℤ) : commute a (m * b) := h.cast_int_mul_right m @[simp] lemma cast_int_mul_left (h : commute a b) (m : ℤ) : commute ((m : R) * a) b := h.cast_int_mul_left m lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : ℤ) : commute ((m : R) * a) (n * b) := h.cast_int_mul_cast_int_mul m n variables (a) (m n : ℤ) @[simp] lemma cast_int_left : commute (m : R) a := by { rw [← mul_one (m : R)], exact (one_left a).cast_int_mul_left m } @[simp] lemma cast_int_right : commute a m := by { rw [← mul_one (m : R)], exact (one_right a).cast_int_mul_right m } @[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n @[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) := (commute.refl a).cast_int_mul_cast_int_mul m n end commute section multiplicative open multiplicative @[simp] lemma nat.to_add_pow (a : multiplicative ℕ) (b : ℕ) : to_add (a ^ b) = to_add a * b := begin induction b with b ih, { erw [pow_zero, to_add_one, mul_zero] }, { simp [*, pow_succ, add_comm, nat.mul_succ] } end @[simp] lemma nat.of_add_mul (a b : ℕ) : of_add (a * b) = of_add a ^ b := (nat.to_add_pow _ _).symm @[simp] lemma int.to_add_pow (a : multiplicative ℤ) (b : ℕ) : to_add (a ^ b) = to_add a * b := by induction b; simp [*, mul_add, pow_succ, add_comm] @[simp] lemma int.to_add_zpow (a : multiplicative ℤ) (b : ℤ) : to_add (a ^ b) = to_add a * b := int.induction_on b (by simp) (by simp [zpow_add, mul_add] {contextual := tt}) (by simp [zpow_add, mul_add, sub_eq_add_neg, -int.add_neg_one] {contextual := tt}) @[simp] lemma int.of_add_mul (a b : ℤ) : of_add (a * b) = of_add a ^ b := (int.to_add_zpow _ _).symm end multiplicative namespace units variables [monoid M] lemma conj_pow (u : units M) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) := (divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm lemma conj_pow' (u : units M) (x : M) (n : ℕ) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:= (u⁻¹).conj_pow x n end units namespace opposite /-- Moving to the opposite monoid commutes with taking powers. -/ @[simp] lemma op_pow [monoid M] (x : M) (n : ℕ) : op (x ^ n) = (op x) ^ n := rfl @[simp] lemma unop_pow [monoid M] (x : Mᵒᵖ) (n : ℕ) : unop (x ^ n) = (unop x) ^ n := rfl /-- Moving to the opposite group or group_with_zero commutes with taking powers. -/ @[simp] lemma op_zpow [div_inv_monoid M] (x : M) (z : ℤ) : op (x ^ z) = (op x) ^ z := rfl @[simp] lemma unop_zpow [div_inv_monoid M] (x : Mᵒᵖ) (z : ℤ) : unop (x ^ z) = (unop x) ^ z := rfl end opposite
0913dda796ab69d63e1d37de8b2376ea69ff4a8a
e151e9053bfd6d71740066474fc500a087837323
/src/hott/eq2.lean
40dea371bb5e874f56285343efc30ccb074a6f72
[ "Apache-2.0" ]
permissive
daniel-carranza/hott3
15bac2d90589dbb952ef15e74b2837722491963d
913811e8a1371d3a5751d7d32ff9dec8aa6815d9
refs/heads/master
1,610,091,349,670
1,596,222,336,000
1,596,222,336,000
241,957,822
0
0
Apache-2.0
1,582,222,839,000
1,582,222,838,000
null
UTF-8
Lean
false
false
9,479
lean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about 2-dimensional paths -/ import .cubical.square universes u v w hott_theory namespace hott open function hott.is_equiv hott.equiv namespace eq variables {A : Type _} {B : Type _} {C : Type _} {f : A → B} {a a' a₁ a₂ a₃ a₄ : A} {b b' : B} @[hott] theorem ap_is_constant_eq (p : Πx, f x = b) (q : a = a') : ap_is_constant f p q = eq_con_inv_of_con_eq ((eq_of_square (square_of_pathover (apd p q)))⁻¹ ⬝ whisker_left (p a) (ap_constant q b)) := begin induction q, dsimp [ap_constant, ap_is_constant, apd], hinduction p a, refl end @[hott] def ap_inv2 {p q : a = a'} (r : p = q) : square (ap (ap f) (inverse2 r)) (inverse2 (ap (ap f) r)) (ap_inv f p) (ap_inv f q) := by induction r;exact hrfl @[hott] def ap_con2 {p₁ q₁ : a₁ = a₂} {p₂ q₂ : a₂ = a₃} (r₁ : p₁ = q₁) (r₂ : p₂ = q₂) : square (ap (ap f) (r₁ ◾ r₂)) (ap (ap f) r₁ ◾ ap (ap f) r₂) (ap_con f p₁ p₂) (ap_con f q₁ q₂) := by induction r₂;induction r₁;exact hrfl @[hott] theorem ap_con_right_inv_sq {A B : Type _} {a1 a2 : A} (f : A → B) (p : a1 = a2) : square (ap (ap f) (con.right_inv p)) (con.right_inv (ap f p)) (ap_con f p p⁻¹ ⬝ whisker_left _ (ap_inv f p)) idp := by induction p;apply hrefl @[hott] theorem ap_con_left_inv_sq {A B : Type _} {a1 a2 : A} (f : A → B) (p : a1 = a2) : square (ap (ap f) (con.left_inv p)) (con.left_inv (ap f p)) (ap_con f p⁻¹ p ⬝ whisker_right _ (ap_inv f p)) idp := by induction p;apply vrefl @[hott] def ap02_compose {A B C : Type _} (g : B → C) (f : A → B) {a a' : A} {p₁ p₂ : a = a'} (q : p₁ = p₂) : square (ap_compose g f p₁) (ap_compose g f p₂) (ap02 (g ∘ f) q) (ap02 g (ap02 f q)) := by induction q; exact vrfl @[hott] def ap02_id {A : Type _} {a a' : A} {p₁ p₂ : a = a'} (q : p₁ = p₂) : square (ap_id p₁) (ap_id p₂) (ap02 id q) q := by induction q; exact vrfl @[hott] theorem ap_ap_is_constant {A B C : Type _} (g : B → C) {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : square (ap (ap g) (ap_is_constant f p q)) (by exact (ap_is_constant (g ∘ f) (λa, ap g (p a)) q)) (ap_compose g f q)⁻¹ (ap_con _ _ _ ⬝ whisker_left _ (ap_inv _ _)) := begin induction q, dsimp [ap_is_constant], hinduction (p x), apply ids end @[hott] theorem ap_ap_compose {A B C D : Type _} (h : C → D) (g : B → C) (f : A → B) {x y : A} (p : x = y) : square (ap_compose (h ∘ g) f p) (ap (ap h) (ap_compose g f p)) (ap_compose h (g ∘ f) p) (ap_compose h g (ap f p)) := by induction p; exact ids @[hott] def ap_compose_inv {A B C : Type _} (g : B → C) (f : A → B) {x y : A} (p : x = y) : square (ap_compose g f p⁻¹) (inverse2 (ap_compose g f p) ⬝ (ap_inv g (ap f p))⁻¹) (ap_inv (g ∘ f) p) (ap (ap g) (ap_inv f p)) := by induction p; exact ids @[hott] def ap_compose_con (g : B → C) (f : A → B) (p : a₁ = a₂) (q : a₂ = a₃) : square (ap_compose g f (p ⬝ q)) (ap_compose g f p ◾ ap_compose g f q ⬝ (ap_con g (ap f p) (ap f q))⁻¹) (ap_con (g ∘ f) p q) (ap (ap g) (ap_con f p q)) := by induction q; induction p; exact ids @[hott] theorem ap_compose_natural {A B C : Type _} (g : B → C) (f : A → B) {x y : A} {p q : x = y} (r : p = q) : square (ap (ap (g ∘ f)) r) (ap (ap g ∘ ap f) r) (ap_compose g f p) (ap_compose g f q) := natural_square_tr (ap_compose g f) r @[hott] theorem whisker_right_eq_of_con_inv_eq_idp {p q : a₁ = a₂} (r : p ⬝ q⁻¹ = idp) : whisker_right q⁻¹ (eq_of_con_inv_eq_idp r) ⬝ con.right_inv q = r := begin induction q, hinduction r using eq.rec_symm, reflexivity end @[hott] theorem ap_eq_of_con_inv_eq_idp (f : A → B) {p q : a₁ = a₂} (r : p ⬝ q⁻¹ = idp) : ap02 f (eq_of_con_inv_eq_idp r) = eq_of_con_inv_eq_idp (whisker_left _ (ap_inv _ _)⁻¹ ⬝ (ap_con _ _ _)⁻¹ ⬝ ap02 f r) := by induction q; hinduction r using eq.rec_symm; reflexivity @[hott] theorem eq_of_con_inv_eq_idp_con2 {p p' q q' : a₁ = a₂} (r : p = p') (s : q = q') (t : p' ⬝ q'⁻¹ = idp) : eq_of_con_inv_eq_idp (r ◾ inverse2 s ⬝ t) = r ⬝ eq_of_con_inv_eq_idp t ⬝ s⁻¹ := by induction s; induction r; induction q; reflexivity @[hott] def naturality_apd_eq {A : Type _} {B : A → Type _} {a a₂ : A} {f g : Πa, B a} (H : f ~ g) (p : a = a₂) : apd f p = concato_eq (eq_concato (H a) (apd g p)) (H a₂)⁻¹ := begin induction p, dsimp, hgeneralize : H a = p, revert p, hgeneralize : g a = x, intro p, induction p, reflexivity end @[hott] theorem con_tr_idp {P : A → Type _} {x y : A} (q : x = y) (u : P x) : con_tr idp q u = ap (λp, p ▸ u) (idp_con q) := by induction q;reflexivity @[hott] def whisker_left_idp_con_eq_assoc {A : Type _} {a₁ a₂ a₃ : A} (p : a₁ = a₂) (q : a₂ = a₃) : whisker_left p (idp_con q)⁻¹ = con.assoc p idp q := by induction q; reflexivity @[hott] def whisker_left_inverse2 {A : Type _} {a : A} {p : a = a} (q : p = idp) : whisker_left p q⁻² ⬝ q = con.right_inv p := by hinduction q using eq.rec_symm; reflexivity @[hott] def cast_fn_cast_square {A : Type _} {B C : A → Type _} (f : Π⦃a⦄, B a → C a) {a₁ a₂ : A} (p : a₁ = a₂) (q : a₂ = a₁) (r : p ⬝ q = idp) (b : B a₁) : cast (ap C q) (f (cast (ap B p) b)) = f b := have q⁻¹ = p, from inv_eq_of_idp_eq_con r⁻¹, begin induction this, induction q, reflexivity end @[hott] def ap011_ap_square_right {A B C : Type _} (f : A → B → C) {a a' : A} (p : a = a') {b₁ b₂ b₃ : B} {q₁₂ : b₁ = b₂} {q₂₃ : b₂ = b₃} {q₁₃ : b₁ = b₃} (r : q₁₂ ⬝ q₂₃ = q₁₃) : square (ap011 f p q₁₂) (ap (λx, f x b₃) p) (ap (f a) q₁₃) (ap (f a') q₂₃) := by induction r; induction q₂₃; induction q₁₂; induction p; exact ids @[hott] def ap011_ap_square_left {A B C : Type _} (f : B → A → C) {a a' : A} (p : a = a') {b₁ b₂ b₃ : B} {q₁₂ : b₁ = b₂} {q₂₃ : b₂ = b₃} {q₁₃ : b₁ = b₃} (r : q₁₂ ⬝ q₂₃ = q₁₃) : square (ap011 f q₁₂ p) (ap (f b₃) p) (ap (λx, f x a) q₁₃) (ap (λx, f x a') q₂₃) := by induction r; induction q₂₃; induction q₁₂; induction p; exact ids @[hott] def con2_assoc {A : Type _} {x y z t : A} {p p' : x = y} {q q' : y = z} {r r' : z = t} (h : p = p') (h' : q = q') (h'' : r = r') : square ((h ◾ h') ◾ h'') (h ◾ (h' ◾ h'')) (con.assoc p q r) (con.assoc p' q' r') := by induction h; induction h'; induction h''; exact hrfl @[hott] def con_left_inv_idp {A : Type _} {x : A} {p : x = x} (q : p = idp) : con.left_inv p = q⁻² ◾ q := by hinduction q using eq.rec_symm; reflexivity @[hott] def eckmann_hilton_con2 {A : Type _} {x : A} {p p' q q': idp = idp :> x = x} (h : p = p') (h' : q = q') : square (h ◾ h') (h' ◾ h) (eckmann_hilton p q) (eckmann_hilton p' q') := by induction h; induction h'; exact hrfl @[hott] def ap_con_fn {A B : Type _} {a a' : A} {b : B} (g h : A → b = b) (p : a = a') : ap (λa, g a ⬝ h a) p = ap g p ◾ ap h p := by induction p; reflexivity @[hott] def ap_eq_ap011 {A B C X : Type _} (f : A → B → C) (g : X → A) (h : X → B) {x x' : X} (p : x = x') : ap (λx, f (g x) (h x)) p = ap011 f (ap g p) (ap h p) := by induction p; reflexivity @[hott] def ap_is_weakly_constant {A B : Type _} {f : A → B} (h : is_weakly_constant f) {a a' : A} (p : a = a') : ap f p = (h a a)⁻¹ ⬝ h a a' := by induction p; exact (con.left_inv _)⁻¹ @[hott] def ap_is_constant_idp {A B : Type _} {f : A → B} {b : B} (p : Πa, f a = b) {a : A} (q : a = a) (r : q = idp) : ap_is_constant f p q = ap02 f r ⬝ (con.right_inv (p a))⁻¹ := by hinduction r using eq.rec_symm; exact (idp_con _)⁻¹ @[hott] def con_right_inv_natural {A : Type _} {a a' : A} {p p' : a = a'} (q : p = p') : con.right_inv p = q ◾ q⁻² ⬝ con.right_inv p' := by induction q; induction p; reflexivity @[hott] def whisker_right_ap {A B : Type _} {a a' : A}{b₁ b₂ b₃ : B} (q : b₂ = b₃) (f : A → b₁ = b₂) (p : a = a') : whisker_right q (ap f p) = ap (λa, f a ⬝ q) p := by induction p; reflexivity @[hott] def ap02_ap_constant {A B C : Type _} {a a' : A} (f : B → C) (b : B) (p : a = a') : square (ap_constant p (f b)) (ap02 f (ap_constant p b)) (ap_compose f (λx, b) p) idp := by induction p; exact ids @[hott] def ap_constant_compose {A B C : Type _} {a a' : A} (c : C) (f : A → B) (p : a = a') : square (ap_constant p c) (ap_constant (ap f p) c) (ap_compose (λx, c) f p) idp := by induction p; exact ids @[hott] def ap02_constant {A B : Type _} {a a' : A} (b : B) {p p' : a = a'} (q : p = p') : square (ap_constant p b) (ap_constant p' b) (ap02 (λx, b) q) idp := by induction q; exact vrfl end eq end hott
ddcb7ff0b64f9f20900d9495fed906b4d3c5695c
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/list.lean
0b2106f3a7affc80184d92340f12ed5660649401
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
8,722
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import topology.constructions import topology.algebra.monoid /-! # Topology on lists and vectors -/ open topological_space set filter open_locale topological_space filter variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] instance : topological_space (list α) := topological_space.mk_of_nhds (traverse nhds) lemma nhds_list (as : list α) : 𝓝 as = traverse 𝓝 as := begin refine nhds_mk_of_nhds _ _ _ _, { assume l, induction l, case list.nil { exact le_rfl }, case list.cons : a l ih { suffices : list.cons <$> pure a <*> pure l ≤ list.cons <$> 𝓝 a <*> traverse 𝓝 l, { simpa only [] with functor_norm using this }, exact filter.seq_mono (filter.map_mono $ pure_le_nhds a) ih } }, { assume l s hs, rcases (mem_traverse_iff _ _).1 hs with ⟨u, hu, hus⟩, clear as hs, have : ∃v:list (set α), l.forall₂ (λa s, is_open s ∧ a ∈ s) v ∧ sequence v ⊆ s, { induction hu generalizing s, case list.forall₂.nil : hs this { existsi [], simpa only [list.forall₂_nil_left_iff, exists_eq_left] }, case list.forall₂.cons : a s as ss ht h ih t hts { rcases mem_nhds_iff.1 ht with ⟨u, hut, hu⟩, rcases ih (subset.refl _) with ⟨v, hv, hvss⟩, exact ⟨u::v, list.forall₂.cons hu hv, subset.trans (set.seq_mono (set.image_subset _ hut) hvss) hts⟩ } }, rcases this with ⟨v, hv, hvs⟩, refine ⟨sequence v, mem_traverse _ _ _, hvs, _⟩, { exact hv.imp (assume a s ⟨hs, ha⟩, is_open.mem_nhds hs ha) }, { assume u hu, have hu := (list.mem_traverse _ _).1 hu, have : list.forall₂ (λa s, is_open s ∧ a ∈ s) u v, { refine list.forall₂.flip _, replace hv := hv.flip, simp only [list.forall₂_and_left, flip] at ⊢ hv, exact ⟨hv.1, hu.flip⟩ }, refine mem_of_superset _ hvs, exact mem_traverse _ _ (this.imp $ assume a s ⟨hs, ha⟩, is_open.mem_nhds hs ha) } } end @[simp] lemma nhds_nil : 𝓝 ([] : list α) = pure [] := by rw [nhds_list, list.traverse_nil _]; apply_instance lemma nhds_cons (a : α) (l : list α) : 𝓝 (a :: l) = list.cons <$> 𝓝 a <*> 𝓝 l := by rw [nhds_list, list.traverse_cons _, ← nhds_list]; apply_instance lemma list.tendsto_cons {a : α} {l : list α} : tendsto (λp:α×list α, list.cons p.1 p.2) (𝓝 a ×ᶠ 𝓝 l) (𝓝 (a :: l)) := by rw [nhds_cons, tendsto, map_prod]; exact le_rfl lemma filter.tendsto.cons {α : Type*} {f : α → β} {g : α → list β} {a : _root_.filter α} {b : β} {l : list β} (hf : tendsto f a (𝓝 b)) (hg : tendsto g a (𝓝 l)) : tendsto (λa, list.cons (f a) (g a)) a (𝓝 (b :: l)) := list.tendsto_cons.comp (tendsto.prod_mk hf hg) namespace list lemma tendsto_cons_iff {β : Type*} {f : list α → β} {b : _root_.filter β} {a : α} {l : list α} : tendsto f (𝓝 (a :: l)) b ↔ tendsto (λp:α×list α, f (p.1 :: p.2)) (𝓝 a ×ᶠ 𝓝 l) b := have 𝓝 (a :: l) = (𝓝 a ×ᶠ 𝓝 l).map (λp:α×list α, (p.1 :: p.2)), begin simp only [nhds_cons, filter.prod_eq, (filter.map_def _ _).symm, (filter.seq_eq_filter_seq _ _).symm], simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm, end, by rw [this, filter.tendsto_map'_iff] lemma continuous_cons : continuous (λ x : α × list α, (x.1 :: x.2 : list α)) := continuous_iff_continuous_at.mpr $ λ ⟨x, y⟩, continuous_at_fst.cons continuous_at_snd lemma tendsto_nhds {β : Type*} {f : list α → β} {r : list α → _root_.filter β} (h_nil : tendsto f (pure []) (r [])) (h_cons : ∀l a, tendsto f (𝓝 l) (r l) → tendsto (λp:α×list α, f (p.1 :: p.2)) (𝓝 a ×ᶠ 𝓝 l) (r (a::l))) : ∀l, tendsto f (𝓝 l) (r l) | [] := by rwa [nhds_nil] | (a::l) := by rw [tendsto_cons_iff]; exact h_cons l a (tendsto_nhds l) lemma continuous_at_length : ∀(l : list α), continuous_at list.length l := begin simp only [continuous_at, nhds_discrete], refine tendsto_nhds _ _, { exact tendsto_pure_pure _ _ }, { assume l a ih, dsimp only [list.length], refine tendsto.comp (tendsto_pure_pure (λx, x + 1) _) _, refine tendsto.comp ih tendsto_snd } end lemma tendsto_insert_nth' {a : α} : ∀{n : ℕ} {l : list α}, tendsto (λp:α×list α, insert_nth n p.1 p.2) (𝓝 a ×ᶠ 𝓝 l) (𝓝 (insert_nth n a l)) | 0 l := tendsto_cons | (n+1) [] := by simp | (n+1) (a'::l) := have 𝓝 a ×ᶠ 𝓝 (a' :: l) = (𝓝 a ×ᶠ (𝓝 a' ×ᶠ 𝓝 l)).map (λp:α×α×list α, (p.1, p.2.1 :: p.2.2)), begin simp only [nhds_cons, filter.prod_eq, ← filter.map_def, ← filter.seq_eq_filter_seq], simp [-filter.seq_eq_filter_seq, -filter.map_def, (∘)] with functor_norm end, begin rw [this, tendsto_map'_iff], exact (tendsto_fst.comp tendsto_snd).cons ((@tendsto_insert_nth' n l).comp $ tendsto_fst.prod_mk $ tendsto_snd.comp tendsto_snd) end lemma tendsto_insert_nth {β} {n : ℕ} {a : α} {l : list α} {f : β → α} {g : β → list α} {b : _root_.filter β} (hf : tendsto f b (𝓝 a)) (hg : tendsto g b (𝓝 l)) : tendsto (λb:β, insert_nth n (f b) (g b)) b (𝓝 (insert_nth n a l)) := tendsto_insert_nth'.comp (tendsto.prod_mk hf hg) lemma continuous_insert_nth {n : ℕ} : continuous (λp:α×list α, insert_nth n p.1 p.2) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth' lemma tendsto_remove_nth : ∀{n : ℕ} {l : list α}, tendsto (λl, remove_nth l n) (𝓝 l) (𝓝 (remove_nth l n)) | _ [] := by rw [nhds_nil]; exact tendsto_pure_nhds _ _ | 0 (a::l) := by rw [tendsto_cons_iff]; exact tendsto_snd | (n+1) (a::l) := begin rw [tendsto_cons_iff], dsimp [remove_nth], exact tendsto_fst.cons ((@tendsto_remove_nth n l).comp tendsto_snd) end lemma continuous_remove_nth {n : ℕ} : continuous (λl : list α, remove_nth l n) := continuous_iff_continuous_at.mpr $ assume a, tendsto_remove_nth @[to_additive] lemma tendsto_prod [monoid α] [has_continuous_mul α] {l : list α} : tendsto list.prod (𝓝 l) (𝓝 l.prod) := begin induction l with x l ih, { simp [nhds_nil, mem_of_mem_nhds, tendsto_pure_left] {contextual := tt} }, simp_rw [tendsto_cons_iff, prod_cons], have := continuous_iff_continuous_at.mp continuous_mul (x, l.prod), rw [continuous_at, nhds_prod_eq] at this, exact this.comp (tendsto_id.prod_map ih) end @[to_additive] lemma continuous_prod [monoid α] [has_continuous_mul α] : continuous (prod : list α → α) := continuous_iff_continuous_at.mpr $ λ l, tendsto_prod end list namespace vector open list instance (n : ℕ) : topological_space (vector α n) := by unfold vector; apply_instance lemma tendsto_cons {n : ℕ} {a : α} {l : vector α n}: tendsto (λp:α×vector α n, p.1 ::ᵥ p.2) (𝓝 a ×ᶠ 𝓝 l) (𝓝 (a ::ᵥ l)) := by { simp [tendsto_subtype_rng, ←subtype.val_eq_coe, cons_val], exact tendsto_fst.cons (tendsto.comp continuous_at_subtype_coe tendsto_snd) } lemma tendsto_insert_nth {n : ℕ} {i : fin (n+1)} {a:α} : ∀{l:vector α n}, tendsto (λp:α×vector α n, insert_nth p.1 i p.2) (𝓝 a ×ᶠ 𝓝 l) (𝓝 (insert_nth a i l)) | ⟨l, hl⟩ := begin rw [insert_nth, tendsto_subtype_rng], simp [insert_nth_val], exact list.tendsto_insert_nth tendsto_fst (tendsto.comp continuous_at_subtype_coe tendsto_snd : _) end lemma continuous_insert_nth' {n : ℕ} {i : fin (n+1)} : continuous (λp:α×vector α n, insert_nth p.1 i p.2) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, by rw [continuous_at, nhds_prod_eq]; exact tendsto_insert_nth lemma continuous_insert_nth {n : ℕ} {i : fin (n+1)} {f : β → α} {g : β → vector α n} (hf : continuous f) (hg : continuous g) : continuous (λb, insert_nth (f b) i (g b)) := continuous_insert_nth'.comp (hf.prod_mk hg : _) lemma continuous_at_remove_nth {n : ℕ} {i : fin (n+1)} : ∀{l:vector α (n+1)}, continuous_at (remove_nth i) l | ⟨l, hl⟩ := -- ∀{l:vector α (n+1)}, tendsto (remove_nth i) (𝓝 l) (𝓝 (remove_nth i l)) --| ⟨l, hl⟩ := begin rw [continuous_at, remove_nth, tendsto_subtype_rng], simp only [← subtype.val_eq_coe, vector.remove_nth_val], exact tendsto.comp list.tendsto_remove_nth continuous_at_subtype_coe, end lemma continuous_remove_nth {n : ℕ} {i : fin (n+1)} : continuous (remove_nth i : vector α (n+1) → vector α n) := continuous_iff_continuous_at.mpr $ assume ⟨a, l⟩, continuous_at_remove_nth end vector
6079b8bb77b46638207e8a49eaeb7c317e8afab9
a9fe717b93ccfa4b2e64faeb24f96dfefb390240
/main.lean
e0ce6b5fff22d8b2416f78163dad628f011c3a82
[]
no_license
skbaek/omega
ab1f4a6daadfc8c855f14c39d9459ab841527141
715e384ed14e8eb177a326700066e7c98269e078
refs/heads/master
1,588,000,876,352
1,552,645,917,000
1,552,645,917,000
174,442,914
1
0
null
null
null
null
UTF-8
Lean
false
false
113
lean
import .is_lia .int.main .nat.main meta def omega : tactic unit := monad.cond is_lia_goal int.omega nat.omega
f908b66b0286879005a70a20bd54ad126357f46b
e21db629d2e37a833531fdcb0b37ce4d71825408
/src/parlang/defs.lean
a7631a11836e45907589e4b54544b247453c8a64
[]
no_license
fischerman/GPU-transformation-verifier
614a28cb4606a05a0eb27e8d4eab999f4f5ea60c
75a5016f05382738ff93ce5859c4cfa47ccb63c1
refs/heads/master
1,586,985,789,300
1,579,290,514,000
1,579,290,514,000
165,031,073
1
0
null
null
null
null
UTF-8
Lean
false
false
8,423
lean
import data.list.basic -- basic operations on `list` import data.option.basic -- basic operations on `option` import data.set.basic import data.vector import data.vector2 import logic.function -- function update and inverses import aux namespace parlang variables {n : ℕ} {σ : Type} {ι : Type} {τ : ι → Type} [decidable_eq ι] /- We use the following conventions for type variables: `σ` -- thread internal states `ι` -- shared memory index `τ` -- shared memory type map -/ /-- Kernel of a parallel program. The general idea is to not have explicit expressions, but use Lean functions to compute values. What we are explicit shared loads and stores. Σ is constructor where the second argument may depend on the type of the first (in this case i). Can be constructed using ⟨...⟩ -/ inductive kernel {ι : Type} (σ : Type) (τ : ι → Type) : Type | load : (σ → (Σi:ι, (τ i → σ))) → kernel | store : (σ → (Σi:ι, τ i)) → kernel | compute {} : (σ → σ) → kernel | seq : kernel → kernel → kernel | ite : (σ → bool) → kernel → kernel → kernel | loop : (σ → bool) → kernel → kernel | sync {} : kernel infixr ` ;; `:90 := kernel.seq open kernel /-- Memory view -/ def memory {ι : Type} (τ : ι → Type) := Π (i : ι), τ i namespace memory def get (m : memory τ) (i : ι) : τ i := m i def update (m : memory τ) (i : ι) (v : τ i) : memory τ := function.update m i v end memory /-- Thread state inclusing a shared memory *view*, the list of loads and stores tells what should differ between differnet threads. -/ structure thread_state {ι : Type} (σ : Type) (τ : ι → Type) : Type := (tlocal : σ) (shared : memory τ) (loads : set ι := ∅) (stores : set ι := ∅) namespace thread_state def load (f : σ → (Σi:ι, (τ i → σ))) (t : thread_state σ τ) : thread_state σ τ := let ⟨i, tr⟩ := f t.tlocal in { tlocal := tr (t.shared.get i), loads := insert i t.loads, .. t } def store (f : σ → (Σi:ι, τ i)) (t : thread_state σ τ) : thread_state σ τ := let ⟨i, v⟩ := f t.tlocal in { shared := t.shared.update i v, stores := insert i t.stores, .. t} def compute (f : σ → σ) (t : thread_state σ τ) : thread_state σ τ := { tlocal := f t.tlocal, .. t} def sync (g : memory τ) (t : thread_state σ τ) : thread_state σ τ := { shared := g, loads := ∅, stores := ∅, .. t} def accesses (t : thread_state σ τ) : set ι := t.stores ∪ t.loads end thread_state def no_thread_active (ac : vector bool n) : bool := ¬ac.to_list.any id def any_thread_active (ac : vector bool n) : bool := ac.to_list.any id def all_threads_active (ac : vector bool n) : bool := ac.to_list.all id /-- thread can only be active either in ac₁ or ac₂ -/ def ac_distinct (ac₁ ac₂ : vector bool n) : Prop := ∀ (i : fin n), ac₁.nth i = ff ∨ ac₂.nth i = ff def ac_ge (ac' : vector bool n) (ac : vector bool n) : Prop := ∀ (t : fin n), ¬ (ac.nth t) → ¬ (ac'.nth t) instance : has_le (vector bool n) := ⟨ac_ge⟩ /-- shared program state -/ structure state {ι : Type} (n : ℕ) (σ : Type) (τ : ι → Type) : Type := (threads : vector (thread_state σ τ) n) namespace state def map_threads (f : thread_state σ τ → thread_state σ τ) (s : state n σ τ) : state n σ τ := { threads := s.threads.map f, ..s } -- we generally don't want to unfold this if possible -- this would for example happen when you do cases in (exec_state (compute f) ...) -- TODO: rename this to mat? It would shorten a lot of names @[irreducible] def map_active_threads (ac : vector bool n) (f : thread_state σ τ → thread_state σ τ) (s : state n σ τ) : state n σ τ := { threads := (s.threads.map₂ (λ t (a : bool), if a then f t else t) ac), ..s } def active_threads (ac : vector bool n) (s : state n σ τ) : list (thread_state σ τ) := ((s.threads.map₂ prod.mk ac).to_list.filter (λ c : (thread_state σ τ × bool), c.2)).map (λ ⟨t, a⟩, t) -- case 1: no thread changed ι and shadows must be equal at ι -- case 2: thread t changed ι and all other threads must not access ι def syncable (s : state n σ τ) (m : memory τ) : Prop := ∀i:ι, (∀ tid, i ∉ (s.threads.nth tid).stores ∧ m i = (s.threads.nth tid).shared i) ∨ (∃ tid, i ∈ (s.threads.nth tid).stores ∧ m i = (s.threads.nth tid).shared i ∧ (∀ tid', tid ≠ tid' → i ∉ (s.threads.nth tid').accesses)) def precedes (s u : state n σ τ) : Prop := ∀ (t : thread_state σ τ × thread_state σ τ), t ∈ (s.threads.map₂ prod.mk u.threads) → t.1.stores ⊆ t.2.stores ∧ t.1.loads ⊆ t.2.loads end state /-- If condition *f* evaluates to *tt*, the thread is deactivated -/ @[irreducible] def deactivate_threads (f : σ → bool) (ac : vector bool n) (s : state n σ τ) : vector bool n := ac.map₂ (λ a (ts : thread_state σ τ), (bnot ∘ f) ts.tlocal && a) s.threads def subkernel (q : kernel σ τ) : kernel σ τ → Prop | (seq k₁ k₂) := k₁ = q ∨ k₂ = q ∨ subkernel k₁ ∨ subkernel k₂ | (ite c th el) := th = q ∨ el = q ∨ subkernel th ∨ subkernel el | (loop c body) := body = q ∨ subkernel body | k := k = q /-- Execute a kernel on a shared state, i.e. a list of threads -/ inductive exec_state {n : ℕ} : kernel σ τ → vector bool n → state n σ τ → state n σ τ → Prop | load (f) (s : state n σ τ) (ac : vector bool n) : exec_state (load f) ac s (s.map_active_threads ac $ thread_state.load f) | store (f) (s : state n σ τ) (ac : vector bool n) : exec_state (store f) ac s (s.map_active_threads ac $ thread_state.store f) | compute (f : σ → σ) (s : state n σ τ) (ac : vector bool n) : exec_state (compute f) ac s (s.map_active_threads ac $ thread_state.compute f) | sync_all (s : state n σ τ) (ac : vector bool n) (m : memory τ) (hs : s.syncable m) (ha : all_threads_active ac) : exec_state sync ac s (s.map_threads $ thread_state.sync m) | sync_none (s : state n σ τ) (ac : vector bool n) (h : no_thread_active ac) : exec_state sync ac s s | seq (s t u : state n σ τ) (ac : vector bool n) (k₁ k₂ : kernel σ τ) : exec_state k₁ ac s t → exec_state k₂ ac t u → exec_state (seq k₁ k₂) ac s u -- in the then-branch we deactivate the threads where the condition is false and similar for else | ite (s t u : state n σ τ) (ac : vector bool n) (f : σ → bool) (k₁ k₂ : kernel σ τ) : exec_state k₁ (deactivate_threads (bnot ∘ f) ac s) s t → exec_state k₂ (deactivate_threads f ac s) t u → exec_state (ite f k₁ k₂) ac s u | loop_stop (s : state n σ τ) (ac : vector bool n) (f : σ → bool) (k : kernel σ τ) : no_thread_active (deactivate_threads (bnot ∘ f) ac s) → exec_state (loop f k) ac s s | loop_step (s t u : state n σ τ) (ac : vector bool n) (f : σ → bool) (k : kernel σ τ) : any_thread_active (deactivate_threads (bnot ∘ f) ac s) → exec_state k (deactivate_threads (bnot ∘ f) ac s) s t → exec_state (loop f k) (deactivate_threads (bnot ∘ f) ac s) t u → exec_state (loop f k) ac s u def kernel_transform_func (k) (f) (n) (ac) : Prop := ∀ (s u : state n σ τ), exec_state k ac s u ↔ (u = s.map_active_threads ac f) def contains_sync : kernel σ τ → Prop | (sync) := true | (seq k₁ k₂) := contains_sync k₁ ∨ contains_sync k₂ | (load _) := false | (store _) := false | (compute _) := false | (ite c k₁ k₂) := contains_sync k₁ ∨ contains_sync k₂ | (loop c k) := contains_sync k inductive program {ι : Type} (σ : Type) (τ : ι → Type) | intro (f : memory τ → ℕ) (k : kernel σ τ) : program def state_initializer := ℕ → σ @[reducible] def init_state (init : ℕ → σ) (f : memory τ → ℕ) (m : memory τ) : state (f m) σ τ := { threads := (vector.range (f m)).map (λ n, { tlocal := init n, shared := m, loads := ∅, stores := ∅ })} inductive exec_prog : (ℕ → σ) → program σ τ → memory τ → memory τ → Prop | intro (k : kernel σ τ) (f : memory τ → ℕ) (a b : memory τ) (init : ℕ → σ) (s' : state (f a) σ τ) (hsync : s'.syncable b) (he : exec_state k (vector.repeat tt (f a)) (init_state init f a) s') : exec_prog init (program.intro f k) a b def list_to_kernel_seq (ks : list (kernel σ τ)) : kernel σ τ := ks.foldl (λ k₁ k₂, k₁ ;; k₂) (kernel.compute id) end parlang
213b2cd8d96e1e5329ab1bf23d05afbf8e7ee8b9
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/matrix/basic.lean
3bf474a617d61859bb90cb3e78e3f6a4b045402d
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
12,043
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin Matrices -/ import algebra.module algebra.pi_instances import data.fintype universes u v def matrix (m n : Type u) [fintype m] [fintype n] (α : Type v) : Type (max u v) := m → n → α namespace matrix variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o] variables {α : Type v} section ext variables {M N : matrix m n α} theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N := ⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩ @[ext] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp end ext def transpose (M : matrix m n α) : matrix n m α | x y := M y x localized "postfix `ᵀ`:1500 := matrix.transpose" in matrix def col (w : m → α) : matrix m punit α | x y := w x def row (v : n → α) : matrix punit n α | x y := v y instance [has_add α] : has_add (matrix m n α) := pi.has_add instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg instance [add_group α] : add_group (matrix m n α) := pi.add_group instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group @[simp] theorem zero_val [has_zero α] (i j) : (0 : matrix m n α) i j = 0 := rfl @[simp] theorem neg_val [has_neg α] (M : matrix m n α) (i j) : (- M) i j = - M i j := rfl @[simp] theorem add_val [has_add α] (M N : matrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl section diagonal variables [decidable_eq n] def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0 @[simp] theorem diagonal_val_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i := by simp [diagonal] @[simp] theorem diagonal_val_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by simp [diagonal, h] theorem diagonal_val_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 := diagonal_val_ne h.symm @[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 := by simp [diagonal]; refl section one variables [has_zero α] [has_one α] instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩ @[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl theorem one_val {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl @[simp] theorem one_val_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_val_eq i @[simp] theorem one_val_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 := diagonal_val_ne theorem one_val_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 := diagonal_val_ne' end one end diagonal @[simp] theorem diagonal_add [decidable_eq n] [add_monoid α] (d₁ d₂ : n → α) : diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) := by ext i j; by_cases i = j; simp [h] protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := λ i k, finset.univ.sum (λ j, M i j * N j k) localized "infixl ` ⬝ `:75 := matrix.mul" in matrix theorem mul_val [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = finset.univ.sum (λ j, M i j * N j k) := rfl local attribute [simp] mul_val instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩ @[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) : M * N = M ⬝ N := rfl theorem mul_val' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} : (M * N) i k = finset.univ.sum (λ j, M i j * N j k) := rfl section semigroup variables [semiring α] protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : (L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) := by classical; funext i k; simp [finset.mul_sum, finset.sum_mul, mul_assoc]; rw finset.sum_comm instance : semigroup (matrix n n α) := { mul_assoc := matrix.mul_assoc, ..matrix.has_mul } end semigroup @[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) : -diagonal d = diagonal (λ i, -d i) := by ext i j; by_cases i = j; simp [h] section semiring variables [semiring α] @[simp] protected theorem mul_zero (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 := by ext i j; simp @[simp] protected theorem zero_mul (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 := by ext i j; simp protected theorem mul_add (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N := by ext i j; simp [finset.sum_add_distrib, mul_add] protected theorem add_mul (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N := by ext i j; simp [finset.sum_add_distrib, add_mul] @[simp] theorem diagonal_mul [decidable_eq m] (d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j := by simp; rw finset.sum_eq_single i; simp [diagonal_val_ne'] {contextual := tt} @[simp] theorem mul_diagonal [decidable_eq n] (d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j := by simp; rw finset.sum_eq_single j; simp {contextual := tt} @[simp] protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M := by ext i j; rw [← diagonal_one, diagonal_mul, one_mul] @[simp] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M := by ext i j; rw [← diagonal_one, mul_diagonal, mul_one] instance [decidable_eq n] : monoid (matrix n n α) := { one_mul := matrix.one_mul, mul_one := matrix.mul_one, ..matrix.has_one, ..matrix.semigroup } instance [decidable_eq n] : semiring (matrix n n α) := { mul_zero := matrix.mul_zero, zero_mul := matrix.zero_mul, left_distrib := matrix.mul_add, right_distrib := matrix.add_mul, ..matrix.add_comm_monoid, ..matrix.monoid } @[simp] theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) : (diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) := by ext i j; by_cases i = j; simp [h] theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) : diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) := diagonal_mul_diagonal' _ _ lemma is_add_monoid_hom_mul_left (M : matrix l m α) : is_add_monoid_hom (λ x : matrix m n α, M ⬝ x) := { to_is_add_hom := ⟨matrix.mul_add _⟩, map_zero := matrix.mul_zero _ } lemma is_add_monoid_hom_mul_right (M : matrix m n α) : is_add_monoid_hom (λ x : matrix l m α, x ⬝ M) := { to_is_add_hom := ⟨λ _ _, matrix.add_mul _ _ _⟩, map_zero := matrix.zero_mul _ } protected lemma sum_mul {β : Type*} (s : finset β) (f : β → matrix l m α) (M : matrix m n α) : s.sum f ⬝ M = s.sum (λ a, f a ⬝ M) := (@finset.sum_hom _ _ _ s f _ _ (λ x, x ⬝ M) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_right l _ _ _ _ _ _ _ M) : _)).symm protected lemma mul_sum {β : Type*} (s : finset β) (f : β → matrix m n α) (M : matrix l m α) : M ⬝ s.sum f = s.sum (λ a, M ⬝ f a) := (@finset.sum_hom _ _ _ s f _ _ (λ x, M ⬝ x) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_left _ _ n _ _ _ _ _ M) : _)).symm end semiring section ring variables [ring α] @[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) : (-M) ⬝ N = -(M ⬝ N) := by ext; simp [matrix.mul] @[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) : M ⬝ (-N) = -(M ⬝ N) := by ext; simp [matrix.mul] end ring instance [decidable_eq n] [ring α] : ring (matrix n n α) := { ..matrix.add_comm_group, ..matrix.semiring } instance [semiring α] : has_scalar α (matrix m n α) := pi.has_scalar instance [ring α] : module α (matrix m n α) := pi.module _ @[simp] lemma smul_val [semiring α] (a : α) (A : matrix m n α) (i : m) (j : n) : (a • A) i j = a * A i j := rfl section comm_ring variables [comm_ring α] @[simp] lemma mul_smul (M : matrix m n α) (a : α) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N := begin ext i j, unfold matrix.mul has_scalar.smul, rw finset.mul_sum, congr, ext, ac_refl end @[simp] lemma smul_mul (M : matrix m n α) (a : α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N := begin ext i j, unfold matrix.mul has_scalar.smul, rw finset.mul_sum, congr, ext, ac_refl end end comm_ring section semiring variables [semiring α] def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α | x y := w x * v y def mul_vec (M : matrix m n α) (v : n → α) : m → α | x := finset.univ.sum (λy:n, M x y * v y) def vec_mul (v : m → α) (M : matrix m n α) : n → α | y := finset.univ.sum (λx:m, v x * M x y) instance mul_vec.is_add_monoid_hom_left (v : n → α) : is_add_monoid_hom (λM:matrix m n α, mul_vec M v) := { map_zero := by ext; simp [mul_vec]; refl, map_add := begin intros x y, ext m, rw pi.add_apply (mul_vec x v) (mul_vec y v) m, simp [mul_vec, finset.sum_add_distrib, right_distrib] end } lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) : mul_vec (diagonal v) w x = v x * w x := begin transitivity, refine finset.sum_eq_single x _ _, { assume b _ ne, simp [diagonal, ne.symm] }, { simp }, { rw [diagonal_val_eq] } end lemma vec_mul_vec_eq (w : m → α) (v : n → α) : vec_mul_vec w v = (col w) ⬝ (row v) := by simp [matrix.mul]; refl end semiring section transpose open_locale matrix @[simp] lemma transpose_transpose (M : matrix m n α) : Mᵀᵀ = M := by ext; refl @[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 := by ext i j; refl @[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) : (M + N)ᵀ = Mᵀ + Nᵀ := begin ext i j, dsimp [transpose], refl end @[simp] lemma transpose_mul [comm_ring α] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ := begin ext i j, unfold matrix.mul transpose, congr, ext, ac_refl end @[simp] lemma transpose_neg [comm_ring α] (M : matrix m n α) : (- M)ᵀ = - Mᵀ := by ext i j; refl end transpose def minor (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α := λ i j, A (row i) (col j) @[reducible] def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α := minor A id (fin.cast_add r) @[reducible] def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α := minor A id (fin.nat_add l) @[reducible] def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α := minor A (fin.cast_add d) id @[reducible] def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α := minor A (fin.nat_add u) id @[reducible] def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin r) α := sub_up (sub_right A) @[reducible] def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin r) α := sub_down (sub_right A) @[reducible] def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin (l)) α := sub_up (sub_left A) @[reducible] def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin (l)) α := sub_down (sub_left A) end matrix
8e237f5b7bd3b5df7ecc26441c6c1c4a46581650
5a6ff5f8d173cbfe51967eb4c96837e3a791fe3d
/mm0-lean/x86/matching.lean
44b3dc049454362ce86e6390cfb128be5cf189fa
[ "CC0-1.0" ]
permissive
digama0/mm0
491ac09146708aa1bb775007bf3dbe339ffc0096
98496badaf6464e56ed7b4204e7d54b85667cb01
refs/heads/master
1,692,321,030,902
1,686,254,458,000
1,686,254,458,000
172,456,790
273
38
CC0-1.0
1,689,939,563,000
1,551,080,059,000
Rust
UTF-8
Lean
false
false
32,865
lean
import x86.lemmas data.set.lattice data.list.basic data.pfun data.list.alist namespace x86 inductive flag_place | CFP | ZFP | SFP | OFP def flag_place.read (f : flags) : flag_place → bool | flag_place.CFP := f.CF | flag_place.ZFP := f.ZF | flag_place.SFP := f.SF | flag_place.OFP := f.OF def flag_place.write (f : flags) (b : bool) : flag_place → flags | flag_place.CFP := {CF := b, ..f} | flag_place.ZFP := {ZF := b, ..f} | flag_place.SFP := {SF := b, ..f} | flag_place.OFP := {OF := b, ..f} inductive place | flag : flag_place → place | reg : regnum → place | rip : place | mem : qword → place inductive place.read (k : config) : place → ∀ {n}, bitvec n → Prop | flag {f} : place.read (place.flag f) (bitvec.singleton (f.read k.flags)) | reg {r} : place.read (place.reg r) (k.regs r) | rip : place.read place.rip k.rip | mem {a b} : k.mem.read1 perm.R a b → place.read (place.mem a) b inductive place.write (k : config) : place → ∀ {n}, bitvec n → config → Prop | flag {f b} : place.write (place.flag f) (bitvec.singleton b) {flags := f.write k.flags b, ..k} | reg {r n q} : place.write (place.reg r) q (k.write_reg r n q) | rip {q} : place.write place.rip q {rip := q, ..k} | mem {a b m'} : k.mem.write1 a b m' → place.write (place.mem a) b {mem := m', ..k} def place.stable (k k' : config) : place → Prop | (place.flag f) := f.read k.flags = f.read k'.flags | (place.reg r) := k.regs r = k'.regs r | place.rip := k.rip = k'.rip | (place.mem a) := roption.mk (k.mem.valid a) (λ h, (k.mem.mem a h, k.mem.perm a h)) = roption.mk (k'.mem.valid a) (λ h, (k'.mem.mem a h, k'.mem.perm a h)) theorem place.stable.refl (k p) : place.stable k k p := by cases p; exact rfl theorem place.stable.trans {k₁ k₂ k₃ p} (h₁ : place.stable k₁ k₂ p) (h₂ : place.stable k₂ k₃ p) : place.stable k₁ k₃ p := by cases p; exact eq.trans h₁ h₂ theorem mem.read1.stable {k k' a} (s : place.stable k k' (place.mem a)) {p b} : mem.read1 p k.mem a b → mem.read1 p k'.mem a b := @@eq.subst (λ o : roption (byte × perm), ∃ (h : o.1), b = (o.2 h).1 ∧ p ≤ (o.2 h).2) s theorem place.read.stable {k k'} : ∀ {p}, place.stable k k' p → ∀ {n v}, @place.read k p n v → place.read k' p v := begin rintro p s n v h, induction h, { rw show _=_, from s, constructor }, { rw show _=_, from s, constructor }, { rw show _=_, from s, constructor }, { exact place.read.mem (mem.read1.stable s h_a_1) } end def stability (k k' : config) : set place := {p | place.stable k k' p} def split {α} (H h₁ h₂ : set α) : Prop := H = h₁ ∪ h₂ ∧ disjoint h₁ h₂ def sProp := config → Prop def sProp.stable (P : sProp) (D : set place) : Prop := ∀ k k', D ⊆ stability k k' → P k → P k' def sProp.reserve (S : set place) : sProp := λ k, ∀ p ∈ S, ∃ n v, @place.read k p n v theorem sProp.reserve.stable {S D : set place} (h : S ⊆ D) : (sProp.reserve S).stable D := λ k k' h' H p hp, let ⟨n, v, hp'⟩ := H p hp in ⟨n, v, place.read.stable (h' (h hp)) hp'⟩ def mProp := config → config → Prop def mProp.exterior (P : mProp) : set place := {p | ∀ k k', P k k' → place.stable k k' p} def mProp.dom (P : mProp) : set place := (P.exterior)ᶜ def stable_at (D : set place) : mProp := λ k k', D ⊆ stability k k' theorem stable_at.refl {D k} : stable_at D k k := λ x _, place.stable.refl _ _ theorem stable_at.trans {D k₁ k₂ k₃} (h₁ : stable_at D k₁ k₂) (h₂ : stable_at D k₂ k₃) : stable_at D k₁ k₃ := λ x h, place.stable.trans (h₁ h) (h₂ h) def mProp.initial (Q : mProp) (P : sProp) : mProp := λ k k', Q k k' ∧ P k def mProp.final (Q : mProp) (P : sProp) : mProp := λ k k', Q k k' ∧ P k' def mProp.apply (Q : mProp) (P : sProp) : sProp := λ k', ∃ k, P k ∧ Q k k' def mProp.id : mProp := eq def mProp.comp (P Q : mProp) : mProp := λ k₁ k₃, ∃ k₂, P k₁ k₂ ∧ Q k₂ k₃ def mProp.imp (P Q : mProp) : mProp := λ k₂ k₃, ∀ k₁, P k₁ k₂ → Q k₁ k₃ def slift (p : Prop) : sProp := λ _, p def mlift (p : Prop) : mProp := λ _ _, p instance lattice.complete_lattice.sProp : complete_lattice sProp := pi.complete_lattice instance lattice.complete_lattice.mProp : complete_lattice mProp := pi.complete_lattice def sProp.with (p : sProp) (q : Prop) : sProp := p ⊓ slift q def mProp.with (p : mProp) (q : Prop) : mProp := p ⊓ mlift q def sProp.ex {α} (p : α → sProp) : sProp := λ k, ∃ a, p a k def mProp.ex {α} (p : α → mProp) : mProp := λ k k', ∃ a, p a k k' def sProp.all {α} (p : α → sProp) : sProp := λ k, ∀ a, p a k def mProp.all {α} (p : α → mProp) : mProp := λ k k', ∀ a, p a k k' def sProp.sn (p : place) {n} (v : bitvec n) : sProp := λ k, p.read k v def mProp.write (p : place) {n} (v' : bitvec n) : mProp := λ k k', p.write k v' k' def mProp.sn (p : place) {n} (v v' : bitvec n) : mProp := (mProp.write p v').initial (sProp.sn p v) def mProp.clob (p : place) {n} (v : bitvec n) : mProp := mProp.ex $ λ v', mProp.sn p v v' def sProp.flags (f : flags) : sProp := sProp.all $ λ p : flag_place, sProp.sn (place.flag p) (bitvec.singleton $ p.read f) inductive block | reg : regnum → wsize → block | mem : qword → qword → block | const : list byte → block def block.size : block → qword | (block.reg _ sz) := (sz.to_nat / 8 : ℕ) | (block.mem _ sz) := sz | (block.const l) := l.length inductive block.places : block → set place | reg {r sz} : block.places (block.reg r sz) (place.reg r) | mem {a b sz : qword} : (bitvec.sub b a).to_nat ≤ sz.to_nat → block.places (block.mem a sz) (place.mem b) def block.disj (b1 b2 : block) := disjoint b1.places b2.places def sProp.mem_block (p : perm) (a : qword) (v : list byte) : sProp := λ k, k.mem.read' p a v def block.read : block → list byte → sProp | (block.reg r sz) v := (sProp.reserve (block.reg r sz).places) ⊓ λ k, read_full_imm sz (k.regs r) v | (block.mem a sz) v := (sProp.reserve (block.mem a sz).places) ⊓ λ k, k.mem.read a v ∧ v.length = sz.to_nat | (block.const l) v := slift $ v = l def block.writable : block → sProp | (block.reg r sz) := sProp.reserve (block.reg r sz).places | (block.mem a sz) := (sProp.reserve (block.mem a sz).places) ⊓ λ k, ∃ v, k.mem.read' perm.W a v ∧ v.length = sz.to_nat | (block.const _) := slift false def block.write : block → list byte → mProp | (block.reg r sz) l k k' := ∃ v, @bits_to_byte (sz.to_nat * 8) sz.to_nat v l ∧ mProp.write (place.reg r) v k k' | (block.mem a sz) l k k' := ∃ m', k.mem.write a l m' ∧ k' = {mem := m', ..k} | (block.const _) _ _ _ := false theorem block.read.size : ∀ {b v k}, block.read b v k → v.length = b.size.to_nat := sorry theorem block.write.size : ∀ {b v k k'}, block.write b v k k' → v.length = b.size.to_nat := sorry theorem block.read_write : ∀ {b v k k'}, block.write b v k k' → block.read b v k' := sorry theorem block.read.stable {l v k k'} (h₁ : block.read l v k) (ss : places l ⊆ stability k k') : block.read l v k' := sorry def hoare (P : kcfg → Prop) (Q : kcfg → kcfg → Prop) := ∀ {{k}}, P k → hoare_p (Q k) k def mHoareIO (P : sProp) (Q : list byte → list byte → mProp) := hoare (λ k, P k.k) (λ k k', ∃ i' o', k.input = i' ++ k'.input ∧ k'.output = k.output ++ o' ∧ (Q i' o') k.k k'.k) def noIO (Q : mProp) (i o : list byte) : mProp := Q.with (i = [] ∧ o = []) def mHoare (P : sProp) (Q : mProp) := mHoareIO P (noIO Q) def locals_ctx := alist (λ _ : ℕ, block) def locals_ctx.get (Γ : locals_ctx) (n : ℕ) : option block := Γ.lookup n def labels_ctx := qword × list qword def labels_ctx.cons (q : qword) (L : labels_ctx) : labels_ctx := ⟨L.1, q :: L.2⟩ structure asm_ctx := (L : list qword) (Γ : alist (λ _ : ℕ, block)) (exit : qword) (die : ∃ l, mHoare (sProp.sn place.rip exit ⊓ sProp.mem_block (perm.R + perm.X) exit l) ⊥) def asm_ctx.read (A : asm_ctx) (n : ℕ) : option block := A.Γ.lookup n def asm_ctx.push_local (A : asm_ctx) (i : ℕ) (b : block) : asm_ctx := ⟨A.1, A.2.insert i b, A.3, A.4⟩ def asm_ctx.push_label (A : asm_ctx) (q : qword) : asm_ctx := ⟨q :: A.1, A.2, A.3, A.4⟩ inductive exit_kind | straight | label (n : ℕ) def exit_kind.result (A : asm_ctx) (pos : qword) : exit_kind → sProp | exit_kind.straight := sProp.sn place.rip pos | (exit_kind.label n) := sProp.ex $ λ h, sProp.sn place.rip (A.1.nth_le n h) def stmt : Type := asm_ctx → set place → ∀ rip : qword, list byte → Prop def stmt.hoareIO (A) (P : sProp) (C : stmt) (Q : exit_kind → list byte → list byte → mProp) : Prop := ∀ D rip l, C A D rip l → mHoareIO (P ⊓ sProp.sn place.rip rip ⊓ sProp.mem_block (perm.R + perm.X) rip l) (λ i o, stable_at D ⊓ mProp.ex (λ e, (Q e i o).final (e.result A (rip + l.length)))) def stmt.hoare (A) (P : sProp) (C : stmt) (Q : exit_kind → mProp) : Prop := stmt.hoareIO A P C (λ e i o, noIO (Q e) i o) def hstmt (P : sProp) (Q : mProp) : stmt := λ A D rip v, mHoare (sProp.sn place.rip rip ⊓ sProp.mem_block (perm.R + perm.X) rip v) ((Q ⊓ stable_at D).final (sProp.sn place.rip (rip + v.length))) instance complete_lattice.stmt : complete_lattice stmt := pi.complete_lattice def stmt.all {α} (s : α → stmt) : stmt := λ A D rip v, ∀ a, s a A D rip v def stmt.ex {α} (s : α → stmt) : stmt := λ A D rip v, ∃ a, s a A D rip v def stmt.with (p : Prop) (s : stmt) : stmt := stmt.ex $ λ h : p, s def stmt.or (s₁ s₂ : stmt) : stmt := λ A D rip v, s₁ A D rip v ∨ s₂ A D rip v def stmt.stabilize (S : set place) (s : stmt) : stmt := λ A D, s A (D ∪ S) def expr (α : Type) := block → stmt instance complete_lattice.expr {α} : complete_lattice (expr α) := pi.complete_lattice def expr.hoareIO {α} (A) (P : sProp) (E : expr α) (Q : block → list byte → list byte → mProp) : Prop := ∀ b, (E b).hoareIO A P $ λ e i o, (Q b i o).with (e = exit_kind.straight) def expr.hoare {α} (A) (P : sProp) (E : expr α) (Q : block → mProp) : Prop := expr.hoareIO A P E (λ ret i o, noIO (Q ret) i o) def expr.stabilize {α} (S : set place) (s : expr α) : expr α := λ b, (s b).stabilize S class value (α : Type*) := (size : ℕ) (eval : α → list byte → Prop) (eval_eq : ∀ {{a l}}, eval a l → l.length = size) def value.evalB {α} [value α] (x : α) (b : block) : sProp := λ k, ∃ l, block.read b l k ∧ value.eval x l def value.read_sized {α} [value α] (a : qword) (x : α) (b : block) : sProp := value.evalB x b ⊓ slift (b = block.mem a (value.size α)) class type (α : Type*) := (size : ℕ) (read : α → block → set place → sProp) (write : α → block → mProp) (read_eq : ∀ {{a l s k}}, read a l s k → l.size.to_nat = size) (write_eq : ∀ {{a l k k'}}, write a l k k' → l.size.to_nat = size) (read_write : ∀ {{a l k k'}}, write a l k k' → ∃ s, read a l s k') (read_stable : ∀ {{a l s k k'}}, read a l s k → s ⊆ stability k k' → read a l s k') def type.read' {α} [type α] (a : α) (b : block) : sProp := sProp.ex $ type.read a b instance (α) [value α] : type α := ⟨value.size α, λ a b s, sProp.ex $ λ v, block.read b v ⊓ slift (value.eval a v ∧ s = b.places), λ a b, mProp.ex $ λ v, block.write b v ⊓ mlift (value.eval a v), λ a b s k ⟨v, h₁, h₂, _⟩, by rw [← h₁.size, @value.eval_eq α _ a v h₂], λ a b k k' ⟨v, h₁, h₂⟩, by rw [← h₁.size, @value.eval_eq α _ a v h₂], λ a v k k' ⟨s, h₁, h₂⟩, ⟨_, _, block.read_write h₁, h₂, rfl⟩, λ a l s k k' ⟨v, h₁, h₂, e⟩ ss, ⟨v, h₁.stable (e ▸ ss), h₂, e⟩⟩ def bits.value {n} (m : ℕ) : value (bitvec n) := ⟨m, bits_to_byte m, λ a v h, h.1⟩ instance unit.value : value unit := ⟨0, λ _ v, v = [], by rintro _ _ ⟨⟩; refl⟩ instance byte.value : value byte := ⟨1, λ b v, v = [b], by rintro _ _ ⟨⟩; refl⟩ instance word.value : value word := bits.value 4 instance qword.value : value qword := bits.value 8 class box (α) [type α] := (deref : α) instance box.type (α) [type α] : type (box α) := ⟨8, λ x b s k, ∃ a l s', block.read b l k ∧ qword.to_list_byte a l ∧ type.read x.deref (block.mem a (type.size α)) s' k ∧ s = b.places ∪ s', λ x b k k', ∃ a l s', block.write b l k k' ∧ qword.to_list_byte a l ∧ type.read x.deref (block.mem a (type.size α)) s' k', λ x b s k ⟨a, l, s', h₁, h₂, _⟩, by rw [← h₁.size, h₂.1], λ x b k k' ⟨a, l, s', h₁, h₂, _⟩, by rw [← h₁.size, h₂.1], λ x b k k' ⟨a, l, s', h₁, h₂, h₃⟩, ⟨_, _, _, _, block.read_write h₁, h₂, h₃, rfl⟩, λ x b s k k' ⟨a, l, s', h₁, h₂, h₃, e⟩ ss, let ⟨ss₁, ss₂⟩ := set.union_subset_iff.1 (by rwa e at ss) in ⟨a, l, s', h₁.stable ss₁, h₂, type.read_stable h₃ ss₂, e⟩⟩ def ret (α) (b : block) : expr α := λ bl A D a v, bl = b ∧ v = [] def const (α) (l : list byte) : expr α := ret α (block.const l) def name (α : Type) := ℕ def var {α} (i : name α) : expr α := λ bl A D a v, bl ∈ A.read i ∧ v = [] def hexpr {α} (P : sProp) (Q : block → mProp) : expr α := λ ret, hstmt P (Q ret) def expr.all {α β} (e : α → expr β) : expr β := λ ret, stmt.all $ λ a, e a ret def expr.ex {α β} (e : α → expr β) : expr β := λ ret, stmt.ex $ λ a, e a ret def expr.with {α} (p : Prop) (s : expr α) : expr α := expr.ex $ λ h : p, s def const' {α} [type α] (a : α) : expr α := hexpr ⊤ $ λ b, mProp.final mProp.id (type.read' a b) inductive stmt.seq (s₁ s₂ : stmt) : stmt | mk {A D rip v₁ v₂} : s₁ A D rip v₁ → s₂ A D (rip + v₁.length) v₂ → stmt.seq A D rip (v₁ ++ v₂) inductive expr.bindS {α} (e₁ : expr α) (s₂ : block → stmt) : stmt | mk {b A D rip v₁ v₂} : e₁ b A D rip v₁ → s₂ b A D (rip + v₁.length) v₂ → expr.bindS A D rip (v₁ ++ v₂) def expr.bind {α β} (e₁ : expr α) (e₂ : block → expr β) : expr β := λ b₂, expr.bindS e₁ $ λ b₁, e₂ b₁ b₂ def block.mov (dst src : block) : stmt := stmt.with (dst.size = src.size) $ stmt.all $ λ val, hstmt (block.read src val) (block.write dst val) def expr.set {α} (e₁ e₂ : expr α) : stmt := expr.bindS e₁ $ λ dst, expr.bindS e₂ $ λ src, block.mov dst src inductive label | fail | label (n : ℕ) inductive label.loc (A : asm_ctx) : label → qword → Prop | fail : label.loc label.fail A.exit | label (n h) : label.loc (label.label n) (A.L.nth_le n h) def stmt.jump_cc (p : flags → bool) (l : label) : stmt := λ A D rip v, ∀ tgt, l.loc A tgt → mHoare (sProp.sn place.rip rip ⊓ sProp.mem_block (perm.R + perm.X) rip v) (λ k k', stable_at D k k' ∧ mProp.write place.rip (cond (p k.flags) tgt (rip + v.length)) k k') def stmt.jump : label → stmt := stmt.jump_cc (λ _, tt) def boolexpr := (flags → bool) → stmt def boolexpr.hoare (A) (P : sProp) (E : boolexpr) (Q : bool → mProp) : Prop := ∃ p, stmt.hoare A P (E p) (λ e k k', e = exit_kind.straight ∧ Q (p k'.flags) k k') def boolexpr.not (c : boolexpr) : boolexpr := λ p, c (bnot ∘ p) def boolexpr.jump_if (c : boolexpr) (l : label) : stmt := stmt.ex $ λ p, (c p).seq $ stmt.jump_cc p l def stmt.nop : stmt := λ A D rip v, v = [] def if_stmt (c : boolexpr) (s₁ s₂ : stmt) : stmt := stmt.ex $ λ p, stmt.seq (c p) $ λ A D rip v, ∃ v₁ v₂ v₃, v = v₁ ++ v₂ ++ v₃ ∧ let q₁ := rip + v₁.length, q₂ := q₁ + v₂.length in stmt.jump_cc (bnot ∘ p) (label.label 0) (A.push_label q₁) D rip v₁ ∧ s₁.seq (stmt.jump (label.label 0)) (A.push_label q₂) D q₁ v₂ ∧ s₂.seq (stmt.jump (label.label 0)) (A.push_label q₂) D q₂ v₃ def loop (s : stmt) : stmt := λ A D rip, s (A.push_label rip) D rip def block_stmt (s : stmt) : stmt := λ A D rip v, s (A.push_label (rip + v.length)) D rip v def while (c : boolexpr) (s : stmt) : stmt := block_stmt $ loop $ (c.not.jump_if (label.label 1)).seq $ s.seq $ stmt.jump (label.label 0) def decl_block {α} (b : block) (s : name α → stmt) : stmt := λ A D rip v, ∃ i, s i (A.push_local i b) D rip v def decl {α} (sz : qword) (s : name α → stmt) : stmt := stmt.ex $ λ b, stmt.with (block.size b = sz) $ decl_block b s def init {α} (e : expr α) (s : name α → stmt) : stmt := e.bindS $ λ b, decl_block b s def binop_expr {α β γ} [type α] [type β] [type γ] (f : α → β → γ) (e₁ : expr α) (e₂ : expr β) : expr γ := e₁.bind $ λ b₁, e₂.bind $ λ b₂ b, stmt.all $ λ x, stmt.all $ λ y, hstmt (type.read' x b₁ ⊓ type.read' y b₂) (type.write (f x y) b) def asn_binop {α β} [type α] [type β] (f : α → β → α) (e₁ : expr α) (e₂ : expr β) : stmt := e₁.bindS $ λ b₁, (ret α b₁).set (binop_expr f (ret α b₁) e₂) def unop_expr {α β} [type α] [type β] (f : α → β) (e : expr α) : expr β := e.bind $ λ b₁ b, stmt.ex $ λ x, hstmt (type.read' x b₁) (type.write (f x) b) def asn_unop {α} [type α] (f : α → α) (e : expr α) : stmt := e.bindS $ λ b, (ret α b).set (unop_expr f (ret α b)) def for {α} (start : expr α) (test : name α → boolexpr) (incr body : name α → stmt) : stmt := init start $ λ i, while (test i) $ (body i).seq (incr i) def incr {α} [type α] [has_add α] [has_one α] : expr α → stmt := asn_unop (+ 1) def bool_binop {α β} [type α] [type β] (f : α → β → bool) (e₁ : expr α) (e₂ : expr β) : boolexpr := λ p, e₁.bindS $ λ b₁, e₂.bindS $ λ b₂, stmt.ex $ λ x, stmt.ex $ λ y, hstmt (type.read' x b₁ ⊓ type.read' y b₂) (mProp.final mProp.id (λ k, p k.flags = f x y)) def ltq (e₁ e₂ : expr qword) : boolexpr := bool_binop (λ a b : qword, a.to_nat < b.to_nat) e₁ e₂ def for_seq (sz : qword) (max : expr qword) (body : name qword → stmt) : stmt := for (const' (0 : qword)) (λ i, ltq (const' 0) max) (λ i, incr (var i)) body ---------------------------------------- -- Program logic ---------------------------------------- theorem mProp.comp_imp {P Q} : mProp.comp P (mProp.imp P Q) ≤ Q := λ k₁ k₃ ⟨k₂, h₁, h₂⟩, h₂ _ h₁ theorem mProp.comp_ex_imp {α P Q} : mProp.comp (@mProp.ex α P) (mProp.all $ λ a, mProp.imp (P a) Q) ≤ Q := λ k₁ k₃ ⟨k₂, ⟨a, h₁⟩, h₂⟩, h₂ a _ h₁ theorem mProp.ex_apply {α Q P} : (@mProp.ex α Q).apply P = sProp.ex (λ a, (Q a).apply P) := funext $ λ k, propext ⟨λ ⟨k', h₁, a, h₂⟩, ⟨a, k', h₁, h₂⟩, λ ⟨a, k', h₁, h₂⟩, ⟨k', h₁, a, h₂⟩⟩ theorem mProp.ex_comp {α Q Q'} : (@mProp.ex α Q).comp Q' = mProp.ex (λ a, (Q a).comp Q') := funext $ λ k, funext $ λ k', propext ⟨λ ⟨k'', ⟨a, h₁⟩, h₂⟩, ⟨a, k'', h₁, h₂⟩, λ ⟨a, k'', h₁, h₂⟩, ⟨k'', ⟨a, h₁⟩, h₂⟩⟩ theorem mem.read'_left {m p a v₁ v₂} (ss : v₁ <+: v₂) : mem.read' m p a v₂ → mem.read' m p a v₁ := begin intro h, induction h generalizing v₁, { cases list.eq_nil_of_prefix_nil ss, constructor }, { cases v₁, constructor, rcases ss with ⟨_, ⟨⟩⟩, exact mem.read'.cons h_a (h_ih ⟨_, rfl⟩) } end theorem mem.read'_right {m p a v₁ v₂} : mem.read' m p a (v₁ ++ v₂) → mem.read' m p (a + v₁.length) v₂ := begin generalize e : v₁ ++ v₂ = v, intro h, induction h generalizing v₁ v₂, { cases list.eq_nil_of_suffix_nil ⟨_, e⟩, constructor }, { cases v₁; cases e, { simp, exact mem.read'.cons h_a h_a_1 }, { simp [-add_comm], rw [← add_assoc, add_right_comm], exact h_ih rfl } } end theorem hoare.zero {P : kcfg → Prop} {Q : kcfg → kcfg → Prop} (H : ∀ {{k}}, P k → Q k k) : hoare P Q := λ k p, hoare_p.zero (H p) theorem hoare.step {P P' : kcfg → Prop} {Q Q' : kcfg → kcfg → Prop} (h₁ : ∀ {{k}}, P k → ∃ k', k.step k') (h₂ : ∀ {{k}}, P k → ∀ {{k'}}, k.step k' → P' k' ∧ ∀ {{k''}}, Q' k' k'' → Q k k'') (h₃ : hoare P' Q') : hoare P Q := λ k p, hoare_p.step (h₁ p) (λ k' s, hoare_p.mono (h₂ p s).2 (h₃ (h₂ p s).1)) theorem hoare.mono_l {P P' : kcfg → Prop} {Q : kcfg → kcfg → Prop} (H : ∀ {{k}}, P k → P' k) : hoare P' Q → hoare P Q := λ H' k h, H' (H h) theorem hoare.mono_r {P : kcfg → Prop} {Q Q' : kcfg → kcfg → Prop} (H : ∀ {{k k'}}, P k → Q k k' → Q' k k') : hoare P Q → hoare P Q' := λ H' k h, hoare_p.mono (λ k' h', H h (by exact h')) (H' h) theorem hoare.comp {P : kcfg → Prop} {Q Q' : kcfg → kcfg → Prop} (H₁ : hoare P Q) (H₂ : hoare (λ k', ∃ k, Q k k' ∧ P k) Q') : hoare P (rel.comp Q Q') := λ k p, begin refine (hoare.mono_r _ H₁ p).bind _, exact (λ k k', Q k k' ∧ P k), rintro k' ⟨h₁, h₂⟩, refine (H₂ ⟨_, h₁, h₂⟩).mono (λ k₂ h, ⟨_, h₁, h⟩), exact λ k k' h₁ h₂, ⟨h₂, h₁⟩ end theorem mHoareIO.zero {P : sProp} {Q : list byte → list byte → mProp} (H : ∀ {{k}}, P k → Q [] [] k k) : mHoareIO P Q := hoare.zero $ λ k h, ⟨[], [], rfl, (list.append_nil _).symm, H h⟩ theorem mHoareIO.mono_l {P P' : sProp} {Q : list byte → list byte → mProp} (H : P ≤ P') : mHoareIO P' Q → mHoareIO P Q := λ h, hoare.mono_l (λ k h, H _ h) h theorem mHoareIO.mono_r {P : sProp} {Q Q' : list byte → list byte → mProp} (H : ∀ {{i o}}, Q i o ≤ Q' i o) : mHoareIO P Q → mHoareIO P Q' := λ h, hoare.mono_r (by exact λ k k' _ ⟨i', o', h₁, h₂, h₃⟩, ⟨i', o', h₁, h₂, H _ _ h₃⟩) h theorem mHoareIO.step {P P' : sProp} {Q Q' : list byte → list byte → mProp} (H₁ : ∀ ⦃k i o⦄, P k → ∃ k', kcfg.step ⟨i, o, k⟩ k') (H₂ : ∀ {{k₁ k₂ i o i₁ o₁}}, P k₁ → kcfg.step ⟨i₁ ++ i, o, k₁⟩ ⟨i, o ++ o₁, k₂⟩ → P' k₂ ∧ ∀ {{i₂ o₂ k₃}}, Q' i₂ o₂ k₂ k₃ → Q (i₁ ++ i₂) (o₁ ++ o₂) k₁ k₃) (H₃ : mHoareIO P' Q') : mHoareIO P Q := begin refine hoare.step (λ ⟨i', o', k⟩ h, H₁ h) _ H₃, rintro ⟨i₁, o₁, k₁⟩ h ⟨i₂, o₂, k₂⟩ h', rcases kcfg.step.io_part h' with ⟨⟨i, rfl⟩, ⟨o, rfl⟩⟩, rcases H₂ h h' with ⟨h₁, h₄⟩, refine ⟨h₁, _⟩, rintro k₃ ⟨i', o', e₁, e₂, h₅⟩, exact ⟨_, _, (congr_arg ((++) i) e₁).trans (list.append_assoc _ _ _).symm, e₂.trans (list.append_assoc _ _ _), h₄ h₅⟩ end theorem mHoareIO.comp {P : sProp} {Q Q' : list byte → list byte → mProp} (H₁ : mHoareIO P Q) (H₂ : mHoareIO (sProp.ex $ λ i, sProp.ex $ λ o, (Q i o).apply P) Q') : mHoareIO P (λ i o, mProp.ex $ λ i₁, mProp.ex $ λ i₂, mProp.ex $ λ o₁, mProp.ex $ λ o₂, ((Q i₁ o₁).comp (Q' i₂ o₂)).with (i = i₁ ++ i₂ ∧ o = o₁ ++ o₂)) := λ k p, begin refine (H₁ p).bind _, rintro k₁ ⟨i₁, o₁, e₁, e₂, h₁⟩, refine (H₂ ⟨_, _, _, p, h₁⟩).mono _, rintro k₂ ⟨i₂, o₂, e₃, e₄, h₂⟩, refine ⟨_, _, _, _, _, _, _, _, ⟨_, h₁, h₂⟩, rfl, rfl⟩, rw [e₁, list.append_assoc, e₃], rw [e₄, ← list.append_assoc, e₂], end theorem mHoareIO.ex_l {α} {P : α → sProp} {Q} : mHoareIO (sProp.ex P) Q ↔ ∀ a, mHoareIO (P a) Q := ⟨λ H a k h, H ⟨a, h⟩, λ H k ⟨a, h⟩, H a h⟩ theorem mHoare.zero {P : sProp} {Q : mProp} (H : ∀ {{k}}, P k → Q k k) : mHoare P Q := mHoareIO.zero $ λ k h, ⟨H h, rfl, rfl⟩ theorem mHoare.mono_l {P P' : sProp} {Q : mProp} (H : P ≤ P') : mHoare P' Q → mHoare P Q := mHoareIO.mono_l H theorem mHoare.mono_r {P : sProp} {Q Q' : mProp} (H : Q ≤ Q') : mHoare P Q → mHoare P Q' := mHoareIO.mono_r $ λ k k' i o ⟨h₁, h₂, h₃⟩, ⟨H _ _ h₁, h₂, h₃⟩ theorem mHoare.step {P P' : sProp} {Q Q' : mProp} (H₁ : ∀ ⦃k⦄, P k → ∃ k', config.step k k') (H₂ : ∀ {{k₁ k₂}}, P k₁ → config.step k₁ k₂ → P' k₂ ∧ ∀ {{k₃}}, Q' k₂ k₃ → Q k₁ k₃) : mHoare P' Q' → mHoare P Q := mHoareIO.step (λ k i o h, let ⟨k', h'⟩ := H₁ h in ⟨⟨i, o, k'⟩, kcfg.step.noio h'⟩) (λ k₁ k₂ i o i₁ o₁ h h', begin generalize_hyp ei : i₁ ++ i = i' at h', generalize_hyp eo : o ++ o₁ = o' at h', cases h', { cases (@list.append_left_inj _ _ [] i).1 ei, cases (@list.append_right_inj _ _ [] o).1 (by simpa using eo), exact ⟨(H₂ h h'_a).1, λ i₂ o₂ k₃ h'', ⟨(H₂ h h'_a).2 h''.1, h''.2⟩⟩ }, { cases H₁ h with k₂ h', cases config.step_noIO h' h'_a } end) theorem mHoare.comp {P : sProp} {Q Q' : mProp} (H₁ : mHoare P Q) (H₂ : mHoare (Q.apply P) Q') : mHoare P (Q.comp Q') := (H₁.comp (H₂.mono_l (λ k₂ ⟨_, _, k₁, h₁, h₂, rfl, rfl⟩, ⟨_, h₁, h₂⟩))).mono_r $ by rintro _ _ k₁ k₃ ⟨i₁, o₁, i₂, o₂, ⟨k₂, ⟨h₁, rfl, rfl⟩, ⟨h₂, rfl, rfl⟩⟩, rfl, rfl⟩; exact ⟨⟨_, h₁, h₂⟩, rfl, rfl⟩ theorem mHoare.ex_l {α} {P : α → sProp} {Q} : mHoare (sProp.ex P) Q ↔ ∀ a, mHoare (P a) Q := ⟨λ H a k h, H ⟨a, h⟩, λ H k ⟨a, h⟩, H a h⟩ theorem stmt.hoareIO.mono_s {A P Q s₁ s₂} (h : s₂ ≤ s₁) : stmt.hoareIO A P s₁ Q → stmt.hoareIO A P s₂ Q := λ H D rip l h', H _ _ _ (h _ _ _ _ h') theorem stmt.hoareIO.mono_l {A P₁ P₂ s Q} (h : P₂ ≤ P₁) : stmt.hoareIO A P₁ s Q → stmt.hoareIO A P₂ s Q := λ H D rip l h', (H _ _ _ h').mono_l (λ k ⟨⟨h₁, h₂⟩, h₃⟩, ⟨⟨h _ h₁, h₂⟩, h₃⟩) theorem stmt.hoareIO.mono_r {A P s} {Q₁ Q₂ : exit_kind → list byte → list byte → mProp} (h : ∀ {{e i o}}, Q₁ e i o ≤ Q₂ e i o) : stmt.hoareIO A P s Q₁ → stmt.hoareIO A P s Q₂ := λ H D rip l h', (H _ _ _ h').mono_r (λ i o k k', and.imp_right $ Exists.imp $ λ e, and.imp_left $ λ h₁, h _ _ h₁) theorem stmt.hoareIO.ex_l {α A s} {P : α → sProp} {Q} : stmt.hoareIO A (sProp.ex P) s Q ↔ ∀ a, stmt.hoareIO A (P a) s Q := ⟨λ H a, H.mono_l $ λ k h, ⟨a, h⟩, λ H S rip k h k ⟨⟨⟨a, h₁⟩, h₂⟩, h₃⟩, H a _ _ _ h ⟨⟨h₁, h₂⟩, h₃⟩⟩ theorem stmt.hoare_iff {A P s Q} : stmt.hoare A P s Q ↔ ∀ {{D rip l}}, s A D rip l → mHoare (P ⊓ sProp.sn place.rip rip ⊓ sProp.mem_block (perm.R + perm.X) rip l) (mProp.ex (λ e, stable_at D ⊓ (Q e).final (e.result A (rip + l.length)))) := forall_congr $ λ D, forall_congr $ λ rip, forall_congr $ λ l, forall_congr $ λ h, iff_of_eq begin congr, funext i o k k', exact propext ⟨λ ⟨h₁, e, ⟨h₂, ei, eo⟩, h₃⟩, ⟨⟨e, h₁, h₂, h₃⟩, ei, eo⟩, λ ⟨⟨e, h₁, h₂, h₃⟩, ei, eo⟩, ⟨h₁, e, ⟨h₂, ei, eo⟩, h₃⟩⟩, end theorem stmt.hoare.mono_s {A P Q s₁ s₂} (h : s₂ ≤ s₁) : stmt.hoare A P s₁ Q → stmt.hoare A P s₂ Q := λ H D rip l h', H _ _ _ (h _ _ _ _ h') theorem stmt.hoare.mono_l {A P₁ P₂ s Q} (h : P₂ ≤ P₁) : stmt.hoare A P₁ s Q → stmt.hoare A P₂ s Q := λ H D rip l h', (H _ _ _ h').mono_l (λ k ⟨⟨h₁, h₂⟩, h₃⟩, ⟨⟨h _ h₁, h₂⟩, h₃⟩) theorem stmt.hoare.mono_r {A P s} {Q₁ Q₂ : exit_kind → mProp} (h : ∀ {{e}}, Q₁ e ≤ Q₂ e) : stmt.hoare A P s Q₁ → stmt.hoare A P s Q₂ := stmt.hoareIO.mono_r $ λ e i o k k' ⟨h₁, h₂⟩, ⟨h _ _ h₁, h₂⟩ theorem stmt.hoare.zero {A P} {s : stmt} {p : Prop} (H : ∀ {{D rip l}}, s A D rip l → p ∧ l = []) : s.hoare A P (λ e, (mlift p).with (e = exit_kind.straight)) := stmt.hoare_iff.2 $ λ D rip l h', begin rcases H h' with ⟨h, rfl⟩, apply mHoare.zero, rintro k ⟨⟨h₁, h₂⟩, h₃⟩, refine ⟨_, stable_at.refl, ⟨h, rfl⟩, _⟩, simpa using h₂ end theorem stmt.hoare.ex_l {α A s} {P : α → sProp} {Q} : stmt.hoare A (sProp.ex P) s Q ↔ ∀ a, stmt.hoare A (P a) s Q := ⟨λ H a, H.mono_l $ λ k h, ⟨a, h⟩, λ H S rip k h k ⟨⟨⟨a, h₁⟩, h₂⟩, h₃⟩, H a _ _ _ h ⟨⟨h₁, h₂⟩, h₃⟩⟩ theorem expr.hoare_iff {α A P E Q} : @expr.hoare α A P E Q ↔ ∀ {{b}}, (E b).hoare A P $ λ e, (Q b).with (e = exit_kind.straight) := forall_congr $ λ b, iff_of_eq begin congr, funext e i o k k', exact propext ⟨λ ⟨⟨h, ei, eo⟩, ee⟩, ⟨⟨h, ee⟩, ei, eo⟩, λ ⟨⟨h, ee⟩, ei, eo⟩, ⟨⟨h, ei, eo⟩, ee⟩⟩ end theorem expr.hoare.zero {α A P} {e : expr α} {p : block → Prop} (H : ∀ {{b D rip l}}, e b A D rip l → p b ∧ l = []) : e.hoare A P (λ b, mlift (p b)) := expr.hoare_iff.2 $ λ b, stmt.hoare.zero (@H b) theorem expr.hoareIO.mono_e {α A P Q} {e₁ e₂ : expr α} (h : e₂ ≤ e₁) : expr.hoareIO A P e₁ Q → expr.hoareIO A P e₂ Q := λ H b, (H b).mono_s (@h b) theorem expr.hoareIO.mono_l {α A P₁ P₂ s Q} (h : P₂ ≤ P₁) : @expr.hoareIO α A P₁ s Q → expr.hoareIO A P₂ s Q := λ H b, (H b).mono_l h theorem expr.hoareIO.mono_r {α A P s} {Q₁ Q₂ : block → list byte → list byte → mProp} (h : ∀ {{b i o}}, Q₁ b i o ≤ Q₂ b i o) : @expr.hoareIO α A P s Q₁ → expr.hoareIO A P s Q₂ := λ H b, (H b).mono_r $ λ e i o, inf_le_inf (@h _ _ _) (le_refl _) theorem expr.hoareIO.ex_l {α β A} {e : expr β} {P : α → sProp} {Q} : expr.hoareIO A (sProp.ex P) e Q ↔ ∀ a, expr.hoareIO A (P a) e Q := iff.trans (forall_congr $ λ b, stmt.hoareIO.ex_l) forall_swap theorem expr.to_hoare {α A P} {e : expr α} {Q : block → mProp} (H : ∀ b, stmt.hoare A P (e b) (λ e, (Q b).with (e = exit_kind.straight))) : expr.hoare A P e Q := begin refine λ b, stmt.hoareIO.mono_r _ (H b), rintro e _ _ k k' ⟨⟨h, e'⟩, rfl, rfl⟩, exact ⟨⟨h, rfl, rfl⟩, e'⟩ end theorem expr.hoare.ex_l {α β A} {e : expr β} {P : α → sProp} {Q} : expr.hoare A (sProp.ex P) e Q ↔ ∀ a, expr.hoare A (P a) e Q := expr.hoareIO.ex_l theorem var.hoare {α} (i : name α) {A} (P : sProp) : (var i).hoare A P (λ b, mlift (b ∈ A.read i)) := expr.hoare.zero $ λ _ _ _ _, id theorem ret.hoare {α b A} (P : sProp) : (ret α b).hoare A P (λ b', mlift (b' = b)) := expr.hoare.zero $ λ _ _ _ _, id theorem hstmt.hoare {A} (P : sProp) (Q : mProp) : (hstmt P Q).hoare A P (λ e, Q.with (e = exit_kind.straight)) := stmt.hoare_iff.2 $ λ D rip l h', (mHoare.mono_l (by exact λ _, and.imp_left and.right) h').mono_r $ by rintro k k' ⟨⟨h₁, h₂⟩, h₃⟩; exact ⟨_, h₂, ⟨h₁, rfl⟩, h₃⟩ theorem hexpr.hoare {α A} (P : sProp) (Q : block → mProp) : (@hexpr α P Q).hoare A P Q := expr.to_hoare $ λ b, hstmt.hoare _ _ def comp_exit (Q₁ Q₂ : exit_kind → mProp) (e : exit_kind) : mProp := mProp.ex $ λ e₁, exit_kind.cases_on e₁ ((Q₁ e₁).comp (Q₂ e)) $ λ _, (Q₁ e₁).with (e₁ = e) /- theorem stmt.seq.hoare {A s₁ s₂} {P₁ P₂ : sProp} {Q₁ Q₂ : exit_kind → mProp} (H₁ : stmt.hoare A P₁ s₁ Q₁) (H₂ : stmt.hoare A P₂ s₂ Q₂) (H : (Q₁ exit_kind.straight).apply P₁ ≤ P₂) : (stmt.seq s₁ s₂).hoare A P₁ (comp_exit Q₁ Q₂) := stmt.hoare_iff.2 begin rintro D rip l ⟨_, _, _, v₁, v₂, h₁, h₂⟩, change v₁.append v₂ with v₁ ++ v₂ at a ⊢, have := stmt.hoare_iff.1 H₁ h₁, refine (((stmt.hoare_iff.1 H₁ h₁).mono_l _).comp _).mono_r mProp.comp_ex_imp, { refine inf_le_inf (le_refl _) _, exact λ k, mem.read'_left ⟨_, rfl⟩ }, rw [mProp.ex_apply, mHoare.ex_l], rintro (_|⟨n⟩), { refine ((stmt.hoare_iff.1 H₂ h₂).mono_l _).mono_r _, { rintro k₂ k₃ ⟨e₂, s₂, q₂, r₂⟩ e₁ k₁ ⟨s₁, q₁, r₁⟩, rw [list.length_append, ← bitvec.add_nat_assoc], refine ⟨e₂, s₁.trans s₂, ⟨exit_kind.straight, _, _, q₂⟩, r₂⟩, sorry }, { } }, { exact ⟨⟨exit_kind.label n, q₁, _⟩, r₂⟩ }, have:= (((stmt.hoare_iff.1 H₁ h₁).mono_l _).comp ((stmt.hoare_iff.1 H₂ h₂).mono_l _)).mono_r _, { rintro k₁ k₃ ⟨k₂, ⟨s₁, e₁, q₁, r₁⟩, ⟨s₂, e₂, q₂, r₂⟩⟩, cases e₁, { refine ⟨s₁.trans s₂, e₂, ⟨exit_kind.straight, _, q₁, q₂⟩, _⟩, rwa [list.length_append, ← bitvec.add_nat_assoc] }, { refine ⟨s₁.trans s₂, _, ⟨exit_kind.label e₁, _, rfl⟩, _⟩, } }, end -/ ---------------------------------------- -- Assembly ---------------------------------------- -- theorem var.asm {α} {i : name α} {A D rip bl} -- (h : bl ∈ locals_ctx.get Γ i) : var i bl A D rip [] := -- ⟨h, rfl⟩ theorem ret.asm {α A D rip bl} : ret α bl bl A D rip [] := ⟨rfl, rfl⟩ def stmt.asm (s : stmt) (D : set place) := Π A rip, ∃ v, s A D rip v end x86
032b0e15f9c629e10b5ae24bb286b4394e3f4068
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/equiv/functor.lean
71e568780ecfeb511d35e6472a386a8067e6918e
[ "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
2,646
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Simon Hudon, Scott Morrison -/ import data.equiv.basic import control.bifunctor /-! # Functor and bifunctors can be applied to `equiv`s. We define ```lean def functor.map_equiv (f : Type u → Type v) [functor f] [is_lawful_functor f] : α ≃ β → f α ≃ f β ``` and ```lean def bifunctor.map_equiv (F : Type u → Type v → Type w) [bifunctor F] [is_lawful_bifunctor F] : α ≃ β → α' ≃ β' → F α α' ≃ F β β' ``` -/ universes u v w variables {α β : Type u} open equiv namespace functor variables (f : Type u → Type v) [functor f] [is_lawful_functor f] /-- Apply a functor to an `equiv`. -/ def map_equiv (h : α ≃ β) : f α ≃ f β := { to_fun := map h, inv_fun := map h.symm, left_inv := λ x, by { rw map_map, convert is_lawful_functor.id_map x, ext a, apply symm_apply_apply }, right_inv := λ x, by { rw map_map, convert is_lawful_functor.id_map x, ext a, apply apply_symm_apply } } @[simp] lemma map_equiv_apply (h : α ≃ β) (x : f α) : (map_equiv f h : f α ≃ f β) x = map h x := rfl @[simp] lemma map_equiv_symm_apply (h : α ≃ β) (y : f β) : (map_equiv f h : f α ≃ f β).symm y = map h.symm y := rfl @[simp] lemma map_equiv_refl : map_equiv f (equiv.refl α) = equiv.refl (f α) := begin ext x, simp only [map_equiv_apply, refl_apply], exact is_lawful_functor.id_map x, end end functor namespace bifunctor variables {α' β' : Type v} (F : Type u → Type v → Type w) [bifunctor F] [is_lawful_bifunctor F] /-- Apply a bifunctor to a pair of `equiv`s. -/ def map_equiv (h : α ≃ β) (h' : α' ≃ β') : F α α' ≃ F β β' := { to_fun := bimap h h', inv_fun := bimap h.symm h'.symm, left_inv := λ x, by { rw bimap_bimap, convert is_lawful_bifunctor.id_bimap x; { ext a, apply symm_apply_apply } }, right_inv := λ x, by { rw bimap_bimap, convert is_lawful_bifunctor.id_bimap x; { ext a, apply apply_symm_apply } } } @[simp] lemma map_equiv_apply (h : α ≃ β) (h' : α' ≃ β') (x : F α α') : (map_equiv F h h' : F α α' ≃ F β β') x = bimap h h' x := rfl @[simp] lemma map_equiv_symm_apply (h : α ≃ β) (h' : α' ≃ β') (y : F β β') : (map_equiv F h h' : F α α' ≃ F β β').symm y = bimap h.symm h'.symm y := rfl @[simp] lemma map_equiv_refl_refl : map_equiv F (equiv.refl α) (equiv.refl α') = equiv.refl (F α α') := begin ext x, simp only [map_equiv_apply, refl_apply], exact is_lawful_bifunctor.id_bimap x, end end bifunctor
47c806f99eabae9e469437f87372ec4a2628d021
92bfaf170880e47d55bf51d5a782fffd76db2f5f
/melting_point/ens.lean
87d6bf7b1094c865351af84da99b04730d320e4b
[]
no_license
forked-from-1kasper/melting_point
d33403e1985d876a2c7c06859962cc0c37570189
e5ea4a0917de086b7e5b122e8d5aa90d2761d147
refs/heads/master
1,624,785,375,577
1,618,305,367,000
1,618,305,367,000
222,729,018
2
0
null
null
null
null
UTF-8
Lean
false
false
1,872
lean
noncomputable theory open classical axiom cls : Type axiom V : set cls def ens := subtype V namespace cls axiom contains : ens → cls → Prop instance : has_mem ens cls := ⟨contains⟩ axiom comp : (ens → Prop) → cls @[simp] axiom compβrule : Π (φ : ens → Prop) (x : ens), (x ∈ comp φ) = φ x axiom ext : ∀ {α β : cls}, (∀ x, x ∈ α ↔ x ∈ β) → α = β def empty := comp (λ _, false) def univ := comp (λ _, true) def insert (x : ens) (α : cls) := comp (λ y, x = y ∨ y ∈ α) instance : has_insert ens cls := ⟨insert⟩ def sep (φ : ens → Prop) (α : cls) := comp (λ x, x ∈ α ∧ φ x) instance : has_sep ens cls := ⟨sep⟩ def union (α β : cls) := comp {x | x ∈ α ∨ x ∈ β} def diff (α β : cls) := {x ∈ α | x ∉ β} def inter (α β : cls) := {x ∈ α | x ∈ β} def subset (α β : cls) := ∀ x, x ∈ α → x ∈ β def compl (α : cls) := comp {x | x ∉ α} instance : has_emptyc cls := ⟨empty⟩ instance : has_union cls := ⟨union⟩ instance : has_inter cls := ⟨inter⟩ instance : has_subset cls := ⟨subset⟩ instance : has_neg cls := ⟨compl⟩ instance : has_sdiff cls := ⟨diff⟩ instance : has_singleton ens cls := ⟨λ x, insert x ∅⟩ def powerset (α : cls) : cls := comp {β | β.val ⊆ α} prefix `𝒫`:100 := powerset end cls namespace ens axiom empty : ∅ ∈ V axiom singleton : ∀ x, {x} ∈ V axiom union : ∀ α β, α ∈ V → β ∈ V → α ∪ β ∈ V axiom inter : ∀ α β, α ∈ V → β ∈ V → α ∩ β ∈ V axiom diff : ∀ α β, α ∈ V → β ∈ V → α \ β ∈ V axiom powerset : ∀ (α : cls), α ∈ V → 𝒫 α ∈ V axiom sep : ∀ (φ : ens → Prop) (α : cls), α ∈ V → { x ∈ α | φ x } ∈ V end ens
49c57296774976861cc861a895e3897912705b6b
f1dc39e1c68f71465c8bf79910c4664d03824751
/library/init/data/int/order.lean
28436c94cb2a15e3b0b743ae67cf5b804265d04a
[ "Apache-2.0" ]
permissive
kckennylau/lean-2
6504f45da07bc98b098d726b74130103be25885c
c9a9368bc0fd600d832bd56c5cb2124b8a523ef9
refs/heads/master
1,659,140,308,864
1,589,361,166,000
1,589,361,166,000
263,748,786
0
0
null
1,589,405,915,000
1,589,405,915,000
null
UTF-8
Lean
false
false
11,818
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The order relation on the integers. -/ prelude import init.data.int.basic init.data.ordering.basic local attribute [simp] sub_eq_add_neg namespace int private def nonneg (a : ℤ) : Prop := int.cases_on a (assume n, true) (assume n, false) protected def le (a b : ℤ) : Prop := nonneg (b - a) instance : has_le int := ⟨int.le⟩ protected def lt (a b : ℤ) : Prop := (a + 1) ≤ b instance : has_lt int := ⟨int.lt⟩ private def decidable_nonneg (a : ℤ) : decidable (nonneg a) := int.cases_on a (assume a, decidable.true) (assume a, decidable.false) instance decidable_le (a b : ℤ) : decidable (a ≤ b) := decidable_nonneg _ instance decidable_lt (a b : ℤ) : decidable (a < b) := decidable_nonneg _ lemma lt_iff_add_one_le (a b : ℤ) : a < b ↔ a + 1 ≤ b := iff.refl _ private lemma nonneg.elim {a : ℤ} : nonneg a → ∃ n : ℕ, a = n := int.cases_on a (assume n H, exists.intro n rfl) (assume n', false.elim) private lemma nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) := int.cases_on a (assume n, or.inl trivial) (assume n, or.inr trivial) lemma le.intro_sub {a b : ℤ} {n : ℕ} (h : b - a = n) : a ≤ b := show nonneg (b - a), by rw h; trivial lemma le.intro {a b : ℤ} {n : ℕ} (h : a + n = b) : a ≤ b := le.intro_sub (by rw [← h, add_comm]; simp) lemma le.dest_sub {a b : ℤ} (h : a ≤ b) : ∃ n : ℕ, b - a = n := nonneg.elim h lemma le.dest {a b : ℤ} (h : a ≤ b) : ∃ n : ℕ, a + n = b := match (le.dest_sub h) with | ⟨n, h₁⟩ := exists.intro n begin rw [← h₁, add_comm], simp end end lemma le.elim {a b : ℤ} (h : a ≤ b) {P : Prop} (h' : ∀ n : ℕ, a + ↑n = b → P) : P := exists.elim (le.dest h) h' protected lemma le_total (a b : ℤ) : a ≤ b ∨ b ≤ a := or.imp_right (assume H : nonneg (-(b - a)), have -(b - a) = a - b, by simp, show nonneg (a - b), from this ▸ H) (nonneg_or_nonneg_neg (b - a)) lemma coe_nat_le_coe_nat_of_le {m n : ℕ} (h : m ≤ n) : (↑m : ℤ) ≤ ↑n := match nat.le.dest h with | ⟨k, (hk : m + k = n)⟩ := le.intro (begin rw [← hk], reflexivity end) end lemma le_of_coe_nat_le_coe_nat {m n : ℕ} (h : (↑m : ℤ) ≤ ↑n) : m ≤ n := le.elim h (assume k, assume hk : ↑m + ↑k = ↑n, have m + k = n, from int.coe_nat_inj ((int.coe_nat_add m k).trans hk), nat.le.intro this) lemma coe_nat_le_coe_nat_iff (m n : ℕ) : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := iff.intro le_of_coe_nat_le_coe_nat coe_nat_le_coe_nat_of_le lemma coe_zero_le (n : ℕ) : 0 ≤ (↑n : ℤ) := coe_nat_le_coe_nat_of_le n.zero_le lemma eq_coe_of_zero_le {a : ℤ} (h : 0 ≤ a) : ∃ n : ℕ, a = n := by have t := le.dest_sub h; simp at t; exact t lemma eq_succ_of_zero_lt {a : ℤ} (h : 0 < a) : ∃ n : ℕ, a = n.succ := let ⟨n, (h : ↑(1+n) = a)⟩ := le.dest h in ⟨n, by rw add_comm at h; exact h.symm⟩ lemma lt_add_succ (a : ℤ) (n : ℕ) : a < a + ↑(nat.succ n) := le.intro (show a + 1 + n = a + nat.succ n, begin simp [int.coe_nat_eq, add_comm, add_left_comm], reflexivity end) lemma lt.intro {a b : ℤ} {n : ℕ} (h : a + nat.succ n = b) : a < b := h ▸ lt_add_succ a n lemma lt.dest {a b : ℤ} (h : a < b) : ∃ n : ℕ, a + ↑(nat.succ n) = b := le.elim h (assume n, assume hn : a + 1 + n = b, exists.intro n begin rw [← hn, add_assoc, add_comm (1 : int)], reflexivity end) lemma lt.elim {a b : ℤ} (h : a < b) {P : Prop} (h' : ∀ n : ℕ, a + ↑(nat.succ n) = b → P) : P := exists.elim (lt.dest h) h' lemma coe_nat_lt_coe_nat_iff (n m : ℕ) : (↑n : ℤ) < ↑m ↔ n < m := begin rw [lt_iff_add_one_le, ← int.coe_nat_succ, coe_nat_le_coe_nat_iff], reflexivity end lemma lt_of_coe_nat_lt_coe_nat {m n : ℕ} (h : (↑m : ℤ) < ↑n) : m < n := (coe_nat_lt_coe_nat_iff _ _).mp h lemma coe_nat_lt_coe_nat_of_lt {m n : ℕ} (h : m < n) : (↑m : ℤ) < ↑n := (coe_nat_lt_coe_nat_iff _ _).mpr h /- show that the integers form an ordered additive group -/ protected lemma le_refl (a : ℤ) : a ≤ a := le.intro (add_zero a) protected lemma le_trans {a b c : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ c) : a ≤ c := le.elim h₁ (assume n, assume hn : a + n = b, le.elim h₂ (assume m, assume hm : b + m = c, begin apply le.intro, rw [← hm, ← hn, add_assoc], reflexivity end)) protected lemma le_antisymm {a b : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ a) : a = b := le.elim h₁ (assume n, assume hn : a + n = b, le.elim h₂ (assume m, assume hm : b + m = a, have a + ↑(n + m) = a + 0, by rw [int.coe_nat_add, ← add_assoc, hn, hm, add_zero a], have (↑(n + m) : ℤ) = 0, from add_left_cancel this, have n + m = 0, from int.coe_nat_inj this, have n = 0, from nat.eq_zero_of_add_eq_zero_right this, show a = b, begin rw [← hn, this, int.coe_nat_zero, add_zero a] end)) protected lemma lt_irrefl (a : ℤ) : ¬ a < a := assume : a < a, lt.elim this (assume n, assume hn : a + nat.succ n = a, have a + nat.succ n = a + 0, by rw [hn, add_zero], have nat.succ n = 0, from int.coe_nat_inj (add_left_cancel this), show false, from nat.succ_ne_zero _ this) protected lemma ne_of_lt {a b : ℤ} (h : a < b) : a ≠ b := (assume : a = b, absurd (begin rewrite this at h, exact h end) (int.lt_irrefl b)) lemma le_of_lt {a b : ℤ} (h : a < b) : a ≤ b := lt.elim h (assume n, assume hn : a + nat.succ n = b, le.intro hn) protected lemma lt_iff_le_and_ne (a b : ℤ) : a < b ↔ (a ≤ b ∧ a ≠ b) := iff.intro (assume h, ⟨le_of_lt h, int.ne_of_lt h⟩) (assume ⟨aleb, aneb⟩, le.elim aleb (assume n, assume hn : a + n = b, have n ≠ 0, from (assume : n = 0, aneb begin rw [← hn, this, int.coe_nat_zero, add_zero] end), have n = nat.succ (nat.pred n), from eq.symm (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero this)), lt.intro (begin rewrite this at hn, exact hn end))) lemma lt_succ (a : ℤ) : a < a + 1 := int.le_refl (a + 1) protected lemma add_le_add_left {a b : ℤ} (h : a ≤ b) (c : ℤ) : c + a ≤ c + b := le.elim h (assume n, assume hn : a + n = b, le.intro (show c + a + n = c + b, begin rw [add_assoc, hn] end)) protected lemma add_lt_add_left {a b : ℤ} (h : a < b) (c : ℤ) : c + a < c + b := iff.mpr (int.lt_iff_le_and_ne _ _) (and.intro (int.add_le_add_left (le_of_lt h) _) (assume heq, int.lt_irrefl b begin rw add_left_cancel heq at h, exact h end)) protected lemma mul_nonneg {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := le.elim ha (assume n, assume hn, le.elim hb (assume m, assume hm, le.intro (show 0 + ↑n * ↑m = a * b, begin rw [← hn, ← hm], simp [zero_add] end))) protected lemma mul_pos {a b : ℤ} (ha : 0 < a) (hb : 0 < b) : 0 < a * b := lt.elim ha (assume n, assume hn, lt.elim hb (assume m, assume hm, lt.intro (show 0 + ↑(nat.succ (nat.succ n * m + n)) = a * b, begin rw [← hn, ← hm], simp [int.coe_nat_zero], rw [← int.coe_nat_mul], simp [nat.mul_succ, nat.succ_add] end))) protected lemma zero_lt_one : (0 : ℤ) < 1 := trivial protected lemma lt_iff_le_not_le {a b : ℤ} : a < b ↔ (a ≤ b ∧ ¬ b ≤ a) := begin simp [int.lt_iff_le_and_ne], split; intro h, { cases h with hab hn, split, { assumption }, { intro hba, simp [int.le_antisymm hab hba] at *, contradiction } }, { cases h with hab hn, split, { assumption }, { intro h, simp [*] at * } } end instance : decidable_linear_ordered_comm_ring int := { le := int.le, le_refl := int.le_refl, le_trans := @int.le_trans, le_antisymm := @int.le_antisymm, lt := int.lt, lt_iff_le_not_le := @int.lt_iff_le_not_le, add_le_add_left := @int.add_le_add_left, zero_ne_one := int.zero_ne_one, mul_pos := @int.mul_pos, le_total := int.le_total, zero_lt_one := int.zero_lt_one, decidable_eq := int.decidable_eq, decidable_le := int.decidable_le, decidable_lt := int.decidable_lt, ..int.comm_ring } instance : decidable_linear_ordered_add_comm_group int := by apply_instance lemma eq_nat_abs_of_zero_le {a : ℤ} (h : 0 ≤ a) : a = nat_abs a := let ⟨n, e⟩ := eq_coe_of_zero_le h in by rw e; refl lemma le_nat_abs {a : ℤ} : a ≤ nat_abs a := or.elim (le_total 0 a) (λh, by rw eq_nat_abs_of_zero_le h; refl) (λh, le_trans h (coe_zero_le _)) lemma neg_succ_lt_zero (n : ℕ) : -[1+ n] < 0 := lt_of_not_ge $ λ h, let ⟨m, h⟩ := eq_coe_of_zero_le h in by contradiction lemma eq_neg_succ_of_lt_zero : ∀ {a : ℤ}, a < 0 → ∃ n : ℕ, a = -[1+ n] | (n : ℕ) h := absurd h (not_lt_of_ge (coe_zero_le _)) | -[1+ n] h := ⟨n, rfl⟩ /- more facts specific to int -/ theorem of_nat_nonneg (n : ℕ) : 0 ≤ of_nat n := trivial theorem coe_succ_pos (n : nat) : (nat.succ n : ℤ) > 0 := coe_nat_lt_coe_nat_of_lt (nat.succ_pos _) theorem exists_eq_neg_of_nat {a : ℤ} (H : a ≤ 0) : ∃n : ℕ, a = -n := let ⟨n, h⟩ := eq_coe_of_zero_le (neg_nonneg_of_nonpos H) in ⟨n, eq_neg_of_eq_neg h.symm⟩ theorem nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : (nat_abs a : ℤ) = a := match a, eq_coe_of_zero_le H with ._, ⟨n, rfl⟩ := rfl end theorem of_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : (nat_abs a : ℤ) = -a := by rw [← nat_abs_neg, nat_abs_of_nonneg (neg_nonneg_of_nonpos H)] theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a | (n : ℕ) := abs_of_nonneg $ coe_zero_le _ | -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _ theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := by rw [abs_eq_nat_abs]; refl theorem lt_of_add_one_le {a b : ℤ} (H : a + 1 ≤ b) : a < b := H theorem add_one_le_of_lt {a b : ℤ} (H : a < b) : a + 1 ≤ b := H theorem lt_add_one_of_le {a b : ℤ} (H : a ≤ b) : a < b + 1 := add_le_add_right H 1 theorem le_of_lt_add_one {a b : ℤ} (H : a < b + 1) : a ≤ b := le_of_add_le_add_right H theorem sub_one_le_of_lt {a b : ℤ} (H : a ≤ b) : a - 1 < b := sub_right_lt_of_lt_add $ lt_add_one_of_le H theorem lt_of_sub_one_le {a b : ℤ} (H : a - 1 < b) : a ≤ b := le_of_lt_add_one $ lt_add_of_sub_right_lt H theorem le_sub_one_of_lt {a b : ℤ} (H : a < b) : a ≤ b - 1 := le_sub_right_of_add_le H theorem lt_of_le_sub_one {a b : ℤ} (H : a ≤ b - 1) : a < b := add_le_of_le_sub_right H theorem sign_of_succ (n : nat) : sign (nat.succ n) = 1 := rfl theorem sign_eq_one_of_pos {a : ℤ} (h : 0 < a) : sign a = 1 := match a, eq_succ_of_zero_lt h with ._, ⟨n, rfl⟩ := rfl end theorem sign_eq_neg_one_of_neg {a : ℤ} (h : a < 0) : sign a = -1 := match a, eq_neg_succ_of_lt_zero h with ._, ⟨n, rfl⟩ := rfl end lemma eq_zero_of_sign_eq_zero : Π {a : ℤ}, sign a = 0 → a = 0 | 0 _ := rfl theorem pos_of_sign_eq_one : ∀ {a : ℤ}, sign a = 1 → 0 < a | (n+1:ℕ) _ := coe_nat_lt_coe_nat_of_lt (nat.succ_pos _) theorem neg_of_sign_eq_neg_one : ∀ {a : ℤ}, sign a = -1 → a < 0 | (n+1:ℕ) h := match h with end | 0 h := match h with end | -[1+ n] _ := neg_succ_lt_zero _ theorem sign_eq_one_iff_pos (a : ℤ) : sign a = 1 ↔ 0 < a := ⟨pos_of_sign_eq_one, sign_eq_one_of_pos⟩ theorem sign_eq_neg_one_iff_neg (a : ℤ) : sign a = -1 ↔ a < 0 := ⟨neg_of_sign_eq_neg_one, sign_eq_neg_one_of_neg⟩ theorem sign_eq_zero_iff_zero (a : ℤ) : sign a = 0 ↔ a = 0 := ⟨eq_zero_of_sign_eq_zero, λ h, by rw [h, sign_zero]⟩ theorem sign_mul_abs (a : ℤ) : sign a * abs a = a := by rw [abs_eq_nat_abs, sign_mul_nat_abs] theorem eq_one_of_mul_eq_self_left {a b : ℤ} (Hpos : a ≠ 0) (H : b * a = a) : b = 1 := eq_of_mul_eq_mul_right Hpos (by rw [one_mul, H]) theorem eq_one_of_mul_eq_self_right {a b : ℤ} (Hpos : b ≠ 0) (H : b * a = b) : a = 1 := eq_of_mul_eq_mul_left Hpos (by rw [mul_one, H]) end int
8af7e8155ad6775e1e4b7b128759a15401a8a8d6
a3db153d66921f9d5a199b60b52ab3c21cf0e023
/src/basic.lean
a8acd8a01546962b79968b15fb89e4723eac1b98
[ "MIT" ]
permissive
metalogical/sia-lean
3bd87a76b3ee6d910cbf182eb2a0e6d9eca3c056
f8e354dd2ff6c09c4e001c1f80f6112c62da8592
refs/heads/master
1,629,775,811,523
1,512,684,874,000
1,512,684,874,000
106,763,566
4
0
null
null
null
null
UTF-8
Lean
false
false
4,807
lean
import .sia namespace sia section parameters {R : Type} [sia R] variables {a b c : R} @[reducible] private def Delta := Delta R @[reducible] private def DeltaT := subtype Delta -- Useful properties of Delta lemma neg_delta : forall d: DeltaT, Delta (-d.val) := assume d, calc -d.val * -d.val = d.val * d.val : by rw [neg_mul_neg] ... = 0 : d.property instance : has_neg DeltaT := { neg := fun d : DeltaT, { val := -d.val, property := neg_delta d } } lemma mul_delta : forall d: DeltaT, forall a: R, Delta (d.val * a) := assume d, assume a, have d.val * d.val = 0, from d.property, show (d.val * a) * (d.val * a) = 0, from calc (d.val * a) * (d.val * a) = d.val * d.val * a * a : by simp ... = 0 * a * a : by rw this ... = 0 : by simp [zero_mul] instance : has_mul DeltaT := { mul := fun d e : DeltaT, { val := d.val * e.val, property := mul_delta d e.val } } -- Other theorems theorem microaffinity : forall f: R -> R, forall x: R, exists! a: R, forall d: DeltaT, f (x + d.val) = f x + a * d.val := assume f: R -> R, assume x: R, let g (d: DeltaT) : R := f (x + d.val) in have nice: f x = g 0, from eq.symm (eq.subst (add_group.add_zero x) (eq.refl _)), by {rewrite nice, apply kock_lawvere} theorem delta_near_zero : forall d: DeltaT, 0 <= d.val /\ d.val <= 0 := assume d, have left: not (d.val < 0), from assume bad, have 0 < -d.val, by {rw <-neg_zero, apply st_ordered_field.lt_neg_flip bad}, have 0 < d.val * d.val, by {rw <-neg_mul_neg, rw <-mul_zero, apply st_ordered_field.lt_mul_pos_left this, assumption}, absurd d.property (ne.symm (st_order.lt_ne this)), have right: not (0 < d.val), from assume bad, have 0 < d.val * d.val, by {rw <-mul_zero, apply st_ordered_field.lt_mul_pos_left bad bad}, absurd d.property (ne.symm (st_order.lt_ne this)), and.intro left right section -- Theorem 1.1 theorem delta_in_zero_interval : set.subset Delta [[(0: R) ... 0]] := assume a, assume a_in_Delta, delta_near_zero { val := a, property := a_in_Delta } @[reducible] def degenerate (S : set R) : Prop := forall x y : subtype S, x.val = y.val theorem delta_nondegenerate : not (degenerate Delta) := assume deg, have d_eq_zero: forall y: DeltaT, (0: R) = y.val, from deg 0, let f := fun r: R, r in have bad: exists! a: R, forall d: DeltaT, 0 + d.val = 0 + a * d.val, from microaffinity f 0, have pf_zero: forall d: DeltaT, 0 + d.val = 0 + 0 * d.val, from assume d, calc 0 + d.val = d.val + 0 * d.val : by simp ... = 0 + 0 * d.val : by rw d_eq_zero d, have pf_one: forall d: DeltaT, 0 + d.val = 0 + 1 * d.val, by simp, have (0: R) = 1, from unique_of_exists_unique bad pf_zero pf_one, absurd this (st_order.lt_ne (st_ordered_field.lt_zero_one R)) theorem delta_indistinguishable_zero : forall d: DeltaT, not (not (d.val = 0)) := assume d, assume bad: d.val != 0, have d.val < 0 \/ 0 < d.val, from st_order.ne_lt bad, have left: not (d.val < 0), from and.elim_left (delta_near_zero d), have right: not (0 < d.val), from and.elim_right (delta_near_zero d), or.elim this left right theorem not_lem_eq_delta_zero : not (forall d: DeltaT, d.val = 0 \/ d.val != 0) := assume bad, have forall d: DeltaT, d.val = 0, from assume d, or.resolve_right (bad d) (delta_indistinguishable_zero d), have forall x y: DeltaT, x.val = y.val, from assume x y, eq.trans (this x) (eq.symm (this y)), delta_nondegenerate this theorem microcancellation : forall {a b: R}, (forall d: DeltaT, a * d.val = b * d.val) -> a = b := assume a b, assume ea_eq_eb : forall d: DeltaT, a * d.val = b * d.val, let f (d : DeltaT) : R := a * d.val in begin apply (unique_of_exists_unique (kock_lawvere f)), show forall d, f d = a * 0 + a * d.val, simp, show forall d, f d = a * 0 + b * d.val, simp, show forall d, f d = b * d.val, intro d, apply eq.trans (ea_eq_eb d), reflexivity, end end end end sia
ab60e74c445f7b7754a669df6b190a2b75d002a8
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/sec_param_pp.lean
9e1a41360f2c64b7f2e215525f29c68d6c2be599
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
271
lean
section parameters {A : Type} (a : A) variable f : A → A → A definition id : A := a check id definition pr (b : A) : A := f a b check pr f id set_option pp.universes true check pr f id definition pr2 (B : Type) (b : B) : A := a check pr2 num 10 end
85d10ed2d34d48114f47cd1a1472c2a51ff5dc52
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/normed_space/star/exponential.lean
f7a147543e7816cd6f8673ccaf5210846ab74a3b
[ "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
2,435
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import analysis.normed_space.star.basic import algebra.star.module import analysis.special_functions.exponential /-! # The exponential map from selfadjoint to unitary In this file, we establish various propreties related to the map `λ a, exp ℂ A (I • a)` between the subtypes `self_adjoint A` and `unitary A`. ## TODO * Show that any exponential unitary is path-connected in `unitary A` to `1 : unitary A`. * Prove any unitary whose distance to `1 : unitary A` is less than `1` can be expressed as an exponential unitary. * A unitary is in the path component of `1` if and only if it is a finite product of exponential unitaries. -/ section star variables {A : Type*} [normed_ring A] [normed_algebra ℂ A] [star_ring A] [has_continuous_star A] [complete_space A] [star_module ℂ A] open complex lemma self_adjoint.exp_i_smul_unitary {a : A} (ha : a ∈ self_adjoint A) : exp ℂ (I • a) ∈ unitary A := begin rw [unitary.mem_iff, star_exp], simp only [star_smul, is_R_or_C.star_def, self_adjoint.mem_iff.mp ha, conj_I, neg_smul], rw ←@exp_add_of_commute ℂ A _ _ _ _ _ _ ((commute.refl (I • a)).neg_left), rw ←@exp_add_of_commute ℂ A _ _ _ _ _ _ ((commute.refl (I • a)).neg_right), simpa only [add_right_neg, add_left_neg, and_self] using (exp_zero : exp ℂ (0 : A) = 1), end /-- The map from the selfadjoint real subspace to the unitary group. This map only makes sense over ℂ. -/ @[simps] noncomputable def self_adjoint.exp_unitary (a : self_adjoint A) : unitary A := ⟨exp ℂ (I • a), self_adjoint.exp_i_smul_unitary (a.property)⟩ open self_adjoint lemma commute.exp_unitary_add {a b : self_adjoint A} (h : commute (a : A) (b : A)) : exp_unitary (a + b) = exp_unitary a * exp_unitary b := begin ext, have hcomm : commute (I • (a : A)) (I • (b : A)), calc _ = _ : by simp only [h.eq, algebra.smul_mul_assoc, algebra.mul_smul_comm], simpa only [exp_unitary_coe, add_subgroup.coe_add, smul_add] using exp_add_of_commute hcomm, end lemma commute.exp_unitary {a b : self_adjoint A} (h : commute (a : A) (b : A)) : commute (exp_unitary a) (exp_unitary b) := calc (exp_unitary a) * (exp_unitary b) = (exp_unitary b) * (exp_unitary a) : by rw [←h.exp_unitary_add, ←h.symm.exp_unitary_add, add_comm] end star
bcbc559719939a644c4a7aa348f5b0a50e0cf6a0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/matrix/charpoly/eigs.lean
684f1bb8e94be0b0de12b3f373db24af911bdf19
[ "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
3,739
lean
/- Copyright (c) 2023 Mohanad Ahmed. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mohanad Ahmed -/ import data.polynomial.basic import field_theory.is_alg_closed.basic /-! # Eigenvalues are characteristic polynomial roots. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In fields we show that: * `matrix.det_eq_prod_roots_charpoly_of_splits`: the determinant (in the field of the matrix) is the product of the roots of the characteristic polynomial if the polynomial splits in the field of the matrix. * `matrix.trace_eq_sum_roots_charpoly_of_splits`: the trace is the sum of the roots of the characteristic polynomial if the polynomial splits in the field of the matrix. In an algebraically closed field we show that: * `matrix.det_eq_prod_roots_charpoly`: the determinant is the product of the roots of the characteristic polynomial. * `matrix.trace_eq_sum_roots_charpoly`: the trace is the sum of the roots of the characteristic polynomial. Note that over other fields such as `ℝ`, these results can be used by using `A.map (algebra_map ℝ ℂ)` as the matrix, and then applying `ring_hom.map_det`. The two lemmas `matrix.det_eq_prod_roots_charpoly` and `matrix.trace_eq_sum_roots_charpoly` are more commonly stated as trace is the sum of eigenvalues and determinant is the product of eigenvalues. Mathlib has already defined eigenvalues in `linear_algebra.eigenspace` as the roots of the minimal polynomial of a linear endomorphism. These do not have correct multiplicity and cannot be used in the theorems above. Hence we express these theorems in terms of the roots of the characteristic polynomial directly. ## TODO The proofs of `det_eq_prod_roots_charpoly_of_splits` and `trace_eq_sum_roots_charpoly_of_splits` closely resemble `norm_gen_eq_prod_roots` and `trace_gen_eq_sum_roots` respectively, but the dependencies are not general enough to unify them. We should refactor `polynomial.prod_roots_eq_coeff_zero_of_monic_of_split` and `polynomial.sum_roots_eq_next_coeff_of_monic_of_split` to assume splitting over an arbitrary map. -/ variables {n : Type*} [fintype n] [decidable_eq n] variables {R : Type*} [field R] variables {A : matrix n n R} open matrix polynomial open_locale matrix big_operators namespace matrix lemma det_eq_prod_roots_charpoly_of_splits (hAps : A.charpoly.splits (ring_hom.id R)) : A.det = (matrix.charpoly A).roots.prod := begin rw [det_eq_sign_charpoly_coeff, ← (charpoly_nat_degree_eq_dim A), polynomial.prod_roots_eq_coeff_zero_of_monic_of_split A.charpoly_monic (hAps), ← mul_assoc, ← pow_two, pow_right_comm, neg_one_sq, one_pow, one_mul], end lemma trace_eq_sum_roots_charpoly_of_splits (hAps : A.charpoly.splits (ring_hom.id R)) : A.trace = (matrix.charpoly A).roots.sum := begin casesI is_empty_or_nonempty n, { rw [matrix.trace, fintype.sum_empty, matrix.charpoly, det_eq_one_of_card_eq_zero (fintype.card_eq_zero_iff.2 h), polynomial.roots_one, multiset.empty_eq_zero, multiset.sum_zero], }, { rw [trace_eq_neg_charpoly_coeff, neg_eq_iff_eq_neg, ← polynomial.sum_roots_eq_next_coeff_of_monic_of_split A.charpoly_monic (hAps), next_coeff, charpoly_nat_degree_eq_dim, if_neg (fintype.card_ne_zero : fintype.card n ≠ 0)], }, end variables (A) lemma det_eq_prod_roots_charpoly [is_alg_closed R] : A.det = (matrix.charpoly A).roots.prod := det_eq_prod_roots_charpoly_of_splits (is_alg_closed.splits A.charpoly) lemma trace_eq_sum_roots_charpoly [is_alg_closed R] : A.trace = (matrix.charpoly A).roots.sum := trace_eq_sum_roots_charpoly_of_splits (is_alg_closed.splits A.charpoly) end matrix
eaa9ff6c56825c520600007d3533a169963ac93f
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/ring_theory/polynomial/rational_root.lean
79dd1115324a8cc43b6069dfd4e775441e623fc3
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,041
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.integrally_closed import ring_theory.polynomial.scale_roots /-! # Rational root theorem and integral root theorem This file contains the rational root theorem and integral root theorem. The rational root theorem for a unique factorization domain `A` with localization `S`, states that the roots of `p : polynomial A` in `A`'s field of fractions are of the form `x / y` with `x y : A`, `x ∣ p.coeff 0` and `y ∣ p.leading_coeff`. The corollary is the integral root theorem `is_integer_of_is_root_of_monic`: if `p` is monic, its roots must be integers. Finally, we use this to show unique factorization domains are integrally closed. ## References * https://en.wikipedia.org/wiki/Rational_root_theorem -/ section scale_roots variables {A K R S : Type*} [comm_ring A] [field K] [comm_ring R] [comm_ring S] variables {M : submonoid A} [algebra A S] [is_localization M S] [algebra A K] [is_fraction_ring A K] open finsupp is_fraction_ring is_localization polynomial lemma scale_roots_aeval_eq_zero_of_aeval_mk'_eq_zero {p : polynomial A} {r : A} {s : M} (hr : aeval (mk' S r s) p = 0) : aeval (algebra_map A S r) (scale_roots p s) = 0 := begin convert scale_roots_eval₂_eq_zero (algebra_map A S) hr, rw [aeval_def, mk'_spec' _ r s] end variables [integral_domain A] lemma num_is_root_scale_roots_of_aeval_eq_zero [unique_factorization_monoid A] {p : polynomial A} {x : K} (hr : aeval x p = 0) : is_root (scale_roots p (denom A x)) (num A x) := begin apply is_root_of_eval₂_map_eq_zero (is_fraction_ring.injective A K), refine scale_roots_aeval_eq_zero_of_aeval_mk'_eq_zero _, rw mk'_num_denom, exact hr end end scale_roots section rational_root_theorem variables {A K : Type*} [comm_ring A] [integral_domain A] [unique_factorization_monoid A] [field K] variables [algebra A K] [is_fraction_ring A K] open is_fraction_ring is_localization polynomial unique_factorization_monoid /-- Rational root theorem part 1: if `r : f.codomain` is a root of a polynomial over the ufd `A`, then the numerator of `r` divides the constant coefficient -/ theorem num_dvd_of_is_root {p : polynomial A} {r : K} (hr : aeval r p = 0) : num A r ∣ p.coeff 0 := begin suffices : num A r ∣ (scale_roots p (denom A r)).coeff 0, { simp only [coeff_scale_roots, nat.sub_zero] at this, haveI := classical.prop_decidable, by_cases hr : num A r = 0, { obtain ⟨u, hu⟩ := (is_unit_denom_of_num_eq_zero hr).pow p.nat_degree, rw ←hu at this, exact units.dvd_mul_right.mp this }, { refine dvd_of_dvd_mul_left_of_no_prime_factors hr _ this, intros q dvd_num dvd_denom_pow hq, apply hq.not_unit, exact num_denom_reduced A r dvd_num (hq.dvd_of_dvd_pow dvd_denom_pow) } }, convert dvd_term_of_is_root_of_dvd_terms 0 (num_is_root_scale_roots_of_aeval_eq_zero hr) _, { rw [pow_zero, mul_one] }, intros j hj, apply dvd_mul_of_dvd_right, convert pow_dvd_pow (num A r) (nat.succ_le_of_lt (bot_lt_iff_ne_bot.mpr hj)), exact (pow_one _).symm end /-- Rational root theorem part 2: if `r : f.codomain` is a root of a polynomial over the ufd `A`, then the denominator of `r` divides the leading coefficient -/ theorem denom_dvd_of_is_root {p : polynomial A} {r : K} (hr : aeval r p = 0) : (denom A r : A) ∣ p.leading_coeff := begin suffices : (denom A r : A) ∣ p.leading_coeff * num A r ^ p.nat_degree, { refine dvd_of_dvd_mul_left_of_no_prime_factors (mem_non_zero_divisors_iff_ne_zero.mp (denom A r).2) _ this, intros q dvd_denom dvd_num_pow hq, apply hq.not_unit, exact num_denom_reduced A r (hq.dvd_of_dvd_pow dvd_num_pow) dvd_denom }, rw ←coeff_scale_roots_nat_degree, apply dvd_term_of_is_root_of_dvd_terms _ (num_is_root_scale_roots_of_aeval_eq_zero hr), intros j hj, by_cases h : j < p.nat_degree, { rw coeff_scale_roots, refine (dvd_mul_of_dvd_right _ _).mul_right _, convert pow_dvd_pow _ (nat.succ_le_iff.mpr (lt_sub_iff_left.mpr _)), { exact (pow_one _).symm }, simpa using h }, rw [←nat_degree_scale_roots p (denom A r)] at *, rw [coeff_eq_zero_of_nat_degree_lt (lt_of_le_of_ne (le_of_not_gt h) hj.symm), zero_mul], exact dvd_zero _ end /-- Integral root theorem: if `r : f.codomain` is a root of a monic polynomial over the ufd `A`, then `r` is an integer -/ theorem is_integer_of_is_root_of_monic {p : polynomial A} (hp : monic p) {r : K} (hr : aeval r p = 0) : is_integer A r := is_integer_of_is_unit_denom (is_unit_of_dvd_one _ (hp ▸ denom_dvd_of_is_root hr)) namespace unique_factorization_monoid lemma integer_of_integral {x : K} : is_integral A x → is_integer A x := λ ⟨p, hp, hx⟩, is_integer_of_is_root_of_monic hp hx @[priority 100] -- See library note [lower instance priority] instance : is_integrally_closed A := ⟨λ x, integer_of_integral⟩ end unique_factorization_monoid end rational_root_theorem
a0787e2fcf7cf2db063aa66a400d9c17c2c56d7b
92b50235facfbc08dfe7f334827d47281471333b
/tests/lean/run/tactic26.lean
70e229eba1a8d6e44113640de0b34e5ca8270f09
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
838
lean
import logic data.num open tactic inhabited namespace foo inductive sum (A : Type) (B : Type) : Type := | inl : A → sum A B | inr : B → sum A B theorem inl_inhabited {A : Type} (B : Type) (H : inhabited A) : inhabited (sum A B) := inhabited.destruct H (λ a, inhabited.mk (sum.inl B a)) theorem inr_inhabited (A : Type) {B : Type} (H : inhabited B) : inhabited (sum A B) := inhabited.destruct H (λ b, inhabited.mk (sum.inr A b)) notation `(` h `|` r:(foldl `|` (e r, tactic.or_else r e) h) `)` := r infixl `;`:15 := tactic.and_then definition my_tac := fixpoint (λ t, ( apply @inl_inhabited; t | apply @inr_inhabited; t | apply @num.is_inhabited )) tactic_hint my_tac theorem T : inhabited (sum false num) end foo
9f36d675c6b45b2028217b458f0714a66ae52e3c
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/linear_algebra/affine_space.lean
7c2556a36ce4cd4bf1a76d6e29de9530d33b4101
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
62,528
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import algebra.add_torsor import data.indicator_function import linear_algebra.basis noncomputable theory open_locale big_operators open_locale classical /-! # Affine spaces This file defines affine spaces (over modules) and subspaces, affine maps, affine combinations of points, and the affine span of a set of points. ## Implementation notes This file is very minimal and many things are surely omitted. Most results can be deduced from corresponding results for modules or vector spaces. The variables `k` and `V` are explicit rather than implicit arguments to lemmas because otherwise the elaborator sometimes has problems inferring appropriate types and type class instances. Definitions of affine spaces vary as to whether a space with no points is permitted; here, we require a nonempty type of points (via the definition of torsors requiring a nonempty type). ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ open add_action open add_torsor /-- `affine_space` is an abbreviation for `add_torsor` in the case where the group is a vector space, or more generally a module, but we omit the type classes `[ring k]` and `[module k V]` in the type synonym itself to simplify type class search.. -/ @[nolint unused_arguments] abbreviation affine_space (k : Type*) (V : Type*) (P : Type*) [add_comm_group V] := add_torsor V P namespace affine_space variables (k : Type*) (V : Type*) {P : Type*} [ring k] [add_comm_group V] [module k V] variables [affine_space k V P] /-- The submodule spanning the differences of a (possibly empty) set of points. -/ def vector_span (s : set P) : submodule k V := submodule.span k (vsub_set V s) /-- The definition of `vector_span`, for rewriting. -/ lemma vector_span_def (s : set P) : vector_span k V s = submodule.span k (vsub_set V s) := rfl variables (P) /-- The `vector_span` of the empty set is `⊥`. -/ @[simp] lemma vector_span_empty : vector_span k V (∅ : set P) = ⊥ := by rw [vector_span_def, vsub_set_empty, submodule.span_empty] variables {P} /-- The `vsub_set` lies within the `vector_span`. -/ lemma vsub_set_subset_vector_span (s : set P) : vsub_set V s ⊆ vector_span k V s := submodule.subset_span /-- Each pairwise difference is in the `vector_span`. -/ lemma vsub_mem_vector_span {s : set P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : p1 -ᵥ p2 ∈ vector_span k V s := begin rw ←submodule.mem_coe, exact set.mem_of_mem_of_subset (vsub_mem_vsub_set V hp1 hp2) (vsub_set_subset_vector_span k V s) end /-- The points in the affine span of a (possibly empty) set of points. Use `affine_span` instead to get an `affine_subspace k V P`. -/ def span_points (s : set P) : set P := {p | ∃ p1 ∈ s, ∃ v ∈ (vector_span k V s), p = v +ᵥ p1} /-- A point in a set is in its affine span. -/ lemma mem_span_points (p : P) (s : set P) : p ∈ s → p ∈ span_points k V s | hp := ⟨p, hp, 0, submodule.zero_mem _, (zero_vadd V p).symm⟩ /-- A set is contained in its `span_points`. -/ lemma subset_span_points (s : set P) : s ⊆ span_points k V s := λ p, mem_span_points k V p s /-- The `span_points` of a set is nonempty if and only if that set is. -/ @[simp] lemma span_points_nonempty (s : set P) : (span_points k V s).nonempty ↔ s.nonempty := begin split, { contrapose, rw [set.not_nonempty_iff_eq_empty, set.not_nonempty_iff_eq_empty], intro h, simp [h, span_points] }, { exact λ ⟨p, hp⟩, ⟨p, mem_span_points k V p s hp⟩ } end /-- Adding a point in the affine span and a vector in the spanning submodule produces a point in the affine span. -/ lemma vadd_mem_span_points_of_mem_span_points_of_mem_vector_span {s : set P} {p : P} {v : V} (hp : p ∈ span_points k V s) (hv : v ∈ vector_span k V s) : v +ᵥ p ∈ span_points k V s := begin rcases hp with ⟨p2, ⟨hp2, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv2p, vadd_assoc], use [p2, hp2, v + v2, (vector_span k V s).add_mem hv hv2, rfl] end /-- Subtracting two points in the affine span produces a vector in the spanning submodule. -/ lemma vsub_mem_vector_span_of_mem_span_points_of_mem_span_points {s : set P} {p1 p2 : P} (hp1 : p1 ∈ span_points k V s) (hp2 : p2 ∈ span_points k V s) : p1 -ᵥ p2 ∈ vector_span k V s := begin rcases hp1 with ⟨p1a, ⟨hp1a, ⟨v1, ⟨hv1, hv1p⟩⟩⟩⟩, rcases hp2 with ⟨p2a, ⟨hp2a, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv1p, hv2p, vsub_vadd_eq_vsub_sub V (v1 +ᵥ p1a), vadd_vsub_assoc, add_comm, add_sub_assoc], have hv1v2 : v1 - v2 ∈ vector_span k V s, { apply (vector_span k V s).add_mem hv1, rw ←neg_one_smul k v2, exact (vector_span k V s).smul_mem (-1 : k) hv2 }, refine (vector_span k V s).add_mem _ hv1v2, exact vsub_mem_vector_span k V hp1a hp2a end end affine_space open affine_space namespace finset variables {k : Type*} (V : Type*) {P : Type*} [ring k] [add_comm_group V] [module k V] variables [S : affine_space k V P] include S variables {ι : Type*} (s : finset ι) /-- A weighted sum of the results of subtracting a base point from the given points, as a linear map on the weights. The main cases of interest are where the sum of the weights is 0, in which case the sum is independent of the choice of base point, and where the sum of the weights is 1, in which case the sum added to the base point is independent of the choice of base point. -/ def weighted_vsub_of_point (p : ι → P) (b : P) : (ι → k) →ₗ[k] V := ∑ i in s, (linear_map.proj i : (ι → k) →ₗ[k] k).smul_right (p i -ᵥ b) @[simp] lemma weighted_vsub_of_point_apply (w : ι → k) (p : ι → P) (b : P) : s.weighted_vsub_of_point V p b w = ∑ i in s, w i • (p i -ᵥ b) := by simp [weighted_vsub_of_point, linear_map.sum_apply] /-- The weighted sum is independent of the base point when the sum of the weights is 0. -/ lemma weighted_vsub_of_point_eq_of_sum_eq_zero (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 0) (b₁ b₂ : P) : s.weighted_vsub_of_point V p b₁ w = s.weighted_vsub_of_point V p b₂ w := begin apply eq_of_sub_eq_zero, rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, ←finset.sum_sub_distrib], conv_lhs { congr, skip, funext, rw [←smul_sub, vsub_sub_vsub_cancel_left] }, rw [←finset.sum_smul, h, zero_smul] end /-- The weighted sum, added to the base point, is independent of the base point when the sum of the weights is 1. -/ lemma weighted_vsub_of_point_vadd_eq_of_sum_eq_one (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 1) (b₁ b₂ : P) : s.weighted_vsub_of_point V p b₁ w +ᵥ b₁ = s.weighted_vsub_of_point V p b₂ w +ᵥ b₂ := begin erw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, ←vsub_eq_zero_iff_eq V, vadd_vsub_assoc, vsub_vadd_eq_vsub_sub, ←add_sub_assoc, add_comm, add_sub_assoc, ←finset.sum_sub_distrib], conv_lhs { congr, skip, congr, skip, funext, rw [←smul_sub, vsub_sub_vsub_cancel_left] }, rw [←finset.sum_smul, h, one_smul, vsub_add_vsub_cancel, vsub_self] end /-- The weighted sum is unaffected by removing the base point, if present, from the set of points. -/ @[simp] lemma weighted_vsub_of_point_erase (w : ι → k) (p : ι → P) (i : ι) : (s.erase i).weighted_vsub_of_point V p (p i) w = s.weighted_vsub_of_point V p (p i) w := begin rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply], apply finset.sum_erase, rw [vsub_self, smul_zero] end /-- The weighted sum is unaffected by adding the base point, whether or not present, to the set of points. -/ @[simp] lemma weighted_vsub_of_point_insert (w : ι → k) (p : ι → P) (i : ι) : (insert i s).weighted_vsub_of_point V p (p i) w = s.weighted_vsub_of_point V p (p i) w := begin rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply], apply finset.sum_insert_zero, rw [vsub_self, smul_zero] end /-- The weighted sum is unaffected by changing the weights to the corresponding indicator function and adding points to the set. -/ lemma weighted_vsub_of_point_indicator_subset (w : ι → k) (p : ι → P) (b : P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) : s₁.weighted_vsub_of_point V p b w = s₂.weighted_vsub_of_point V p b (set.indicator ↑s₁ w) := begin rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply], exact set.sum_indicator_subset_of_eq_zero w (λ i wi, wi • (p i -ᵥ b : V)) h (λ i, zero_smul k _) end /-- A weighted sum of the results of subtracting a default base point from the given points, as a linear map on the weights. This is intended to be used when the sum of the weights is 0; that condition is specified as a hypothesis on those lemmas that require it. -/ def weighted_vsub (p : ι → P) : (ι → k) →ₗ[k] V := s.weighted_vsub_of_point V p (classical.choice S.nonempty) /-- Applying `weighted_vsub` with given weights. This is for the case where a result involving a default base point is OK (for example, when that base point will cancel out later); a more typical use case for `weighted_vsub` would involve selecting a preferred base point with `weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero` and then using `weighted_vsub_of_point_apply`. -/ lemma weighted_vsub_apply (w : ι → k) (p : ι → P) : s.weighted_vsub V p w = ∑ i in s, w i • (p i -ᵥ (classical.choice S.nonempty)) := by simp [weighted_vsub, linear_map.sum_apply] /-- `weighted_vsub` gives the sum of the results of subtracting any base point, when the sum of the weights is 0. -/ lemma weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 0) (b : P) : s.weighted_vsub V p w = s.weighted_vsub_of_point V p b w := s.weighted_vsub_of_point_eq_of_sum_eq_zero V w p h _ _ /-- The `weighted_vsub` for an empty set is 0. -/ @[simp] lemma weighted_vsub_empty (w : ι → k) (p : ι → P) : (∅ : finset ι).weighted_vsub V p w = 0 := by simp [weighted_vsub_apply] /-- The weighted sum is unaffected by changing the weights to the corresponding indicator function and adding points to the set. -/ lemma weighted_vsub_indicator_subset (w : ι → k) (p : ι → P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) : s₁.weighted_vsub V p w = s₂.weighted_vsub V p (set.indicator ↑s₁ w) := weighted_vsub_of_point_indicator_subset _ _ _ _ h /-- A weighted sum of the results of subtracting a default base point from the given points, added to that base point. This is intended to be used when the sum of the weights is 1, in which case it is an affine combination (barycenter) of the points with the given weights; that condition is specified as a hypothesis on those lemmas that require it. -/ def affine_combination (w : ι → k) (p : ι → P) : P := s.weighted_vsub_of_point V p (classical.choice S.nonempty) w +ᵥ (classical.choice S.nonempty) /-- Applying `affine_combination` with given weights. This is for the case where a result involving a default base point is OK (for example, when that base point will cancel out later); a more typical use case for `affine_combination` would involve selecting a preferred base point with `affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one` and then using `weighted_vsub_of_point_apply`. -/ lemma affine_combination_apply (w : ι → k) (p : ι → P) : s.affine_combination V w p = s.weighted_vsub_of_point V p (classical.choice S.nonempty) w +ᵥ (classical.choice S.nonempty) := rfl /-- `affine_combination` gives the sum with any base point, when the sum of the weights is 1. -/ lemma affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 1) (b : P) : s.affine_combination V w p = s.weighted_vsub_of_point V p b w +ᵥ b := s.weighted_vsub_of_point_vadd_eq_of_sum_eq_one V w p h _ _ /-- Adding a `weighted_vsub` to an `affine_combination`. -/ lemma weighted_vsub_vadd_affine_combination (w₁ w₂ : ι → k) (p : ι → P) : s.weighted_vsub V p w₁ +ᵥ s.affine_combination V w₂ p = s.affine_combination V (w₁ + w₂) p := begin erw vadd_assoc, congr, exact (linear_map.map_add _ _ _).symm end /-- Subtracting two `affine_combination`s. -/ lemma affine_combination_vsub (w₁ w₂ : ι → k) (p : ι → P) : s.affine_combination V w₁ p -ᵥ s.affine_combination V w₂ p = s.weighted_vsub V p (w₁ - w₂) := begin erw vadd_vsub_vadd_cancel_right, exact (linear_map.map_sub _ _ _).symm end /-- An `affine_combination` equals a point if that point is in the set and has weight 1 and the other points in the set have weight 0. -/ @[simp] lemma affine_combination_of_eq_one_of_eq_zero (w : ι → k) (p : ι → P) {i : ι} (his : i ∈ s) (hwi : w i = 1) (hw0 : ∀ i2 ∈ s, i2 ≠ i → w i2 = 0) : s.affine_combination V w p = p i := begin have h1 : ∑ i in s, w i = 1 := hwi ▸ finset.sum_eq_single i hw0 (λ h, false.elim (h his)), rw [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one V w p h1 (p i), weighted_vsub_of_point_apply], convert zero_vadd V (p i), convert finset.sum_eq_zero _, intros i2 hi2, by_cases h : i2 = i, { simp [h] }, { simp [hw0 i2 hi2 h] } end /-- An affine combination is unaffected by changing the weights to the corresponding indicator function and adding points to the set. -/ lemma affine_combination_indicator_subset (w : ι → k) (p : ι → P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) : s₁.affine_combination V w p = s₂.affine_combination V (set.indicator ↑s₁ w) p := by rw [affine_combination_apply, affine_combination_apply, weighted_vsub_of_point_indicator_subset _ _ _ _ h] end finset section affine_independent variables (k : Type*) (V : Type*) {P : Type*} [ring k] [add_comm_group V] [module k V] variables [affine_space k V P] {ι : Type*} /-- An indexed family is said to be affinely independent if no nontrivial weighted subtractions (where the sum of weights is 0) are 0. -/ def affine_independent (p : ι → P) : Prop := ∀ (s : finset ι) (w : ι → k), ∑ i in s, w i = 0 → s.weighted_vsub V p w = 0 → ∀ i ∈ s, w i = 0 /-- A family with at most one point is affinely independent. -/ lemma affine_independent_of_subsingleton [subsingleton ι] (p : ι → P) : affine_independent k V p := λ s w h hs i hi, fintype.eq_of_subsingleton_of_sum_eq h i hi /-- A family is affinely independent if and only if the differences from a base point in that family are linearly independent. -/ lemma affine_independent_iff_linear_independent_vsub (p : ι → P) (i1 : ι) : affine_independent k V p ↔ linear_independent k (λ i : {x // x ≠ i1}, (p i -ᵥ p i1 : V)) := begin split, { intro h, rw linear_independent_iff', intros s g hg i hi, set f : ι → k := λ x, if hx : x = i1 then -∑ y in s, g y else g ⟨x, hx⟩ with hfdef, let s2 : finset ι := insert i1 (s.map (function.embedding.subtype _)), have hfg : ∀ x : {x // x ≠ i1}, g x = f x, { intro x, rw hfdef, dsimp only [], erw [dif_neg x.property, subtype.coe_eta] }, rw hfg, have hf : ∑ ι in s2, f ι = 0, { rw [finset.sum_insert (finset.not_mem_map_subtype_of_not_property s (not_not.2 rfl)), finset.sum_subtype_map_embedding (λ x hx, (hfg x).symm)], rw hfdef, dsimp only [], rw dif_pos rfl, exact neg_add_self _ }, have hs2 : s2.weighted_vsub V p f = 0, { set f2 : ι → V := λ x, f x • (p x -ᵥ p i1) with hf2def, set g2 : {x // x ≠ i1} → V := λ x, g x • (p x -ᵥ p i1) with hg2def, have hf2g2 : ∀ x : {x // x ≠ i1}, f2 x = g2 x, { simp_rw [hf2def, hg2def, hfg], exact λ x, rfl }, rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero V s2 f p hf (p i1), finset.weighted_vsub_of_point_insert, finset.weighted_vsub_of_point_apply, finset.sum_subtype_map_embedding (λ x hx, hf2g2 x)], exact hg }, exact h s2 f hf hs2 i (finset.mem_insert_of_mem (finset.mem_map.2 ⟨i, hi, rfl⟩)) }, { intro h, rw linear_independent_iff' at h, intros s w hw hs i hi, rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero V s w p hw (p i1), ←s.weighted_vsub_of_point_erase V w p i1, finset.weighted_vsub_of_point_apply] at hs, let f : ι → V := λ i, w i • (p i -ᵥ p i1), have hs2 : ∑ i in (s.erase i1).subtype (λ i, i ≠ i1), f i = 0, { rw [←hs], convert finset.sum_subtype_of_mem f (λ x, finset.ne_of_mem_erase) }, have h2 := h ((s.erase i1).subtype (λ i, i ≠ i1)) (λ x, w x) hs2, simp_rw [finset.mem_subtype] at h2, have h2b : ∀ i ∈ s, i ≠ i1 → w i = 0 := λ i his hi, h2 ⟨i, hi⟩ (finset.mem_erase_of_ne_of_mem hi his), exact finset.eq_zero_of_sum_eq_zero hw h2b i hi } end end affine_independent /-- An `affine_subspace k V P` is a subset of an `affine_space k V P` that, if not empty, has an affine space structure induced by a corresponding subspace of the `module k V`. -/ structure affine_subspace (k : Type*) (V : Type*) (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space k V P] := (carrier : set P) (smul_vsub_vadd_mem : ∀ (c : k) (p1 p2 p3 ∈ carrier), c • (p1 -ᵥ p2 : V) +ᵥ p3 ∈ carrier) namespace affine_subspace variables (k : Type*) (V : Type*) (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space k V P] instance : has_coe (affine_subspace k V P) (set P) := ⟨carrier⟩ instance : has_mem P (affine_subspace k V P) := ⟨λ p s, p ∈ (s : set P)⟩ /-- A point is in an affine subspace coerced to a set if and only if it is in that affine subspace. -/ @[simp] lemma mem_coe (p : P) (s : affine_subspace k V P) : p ∈ (s : set P) ↔ p ∈ s := iff.rfl variables {k V P} /-- The direction of an affine subspace is the submodule spanned by the pairwise differences of points. (Except in the case of an empty affine subspace, where the direction is the zero submodule, every vector in the direction is the difference of two points in the affine subspace.) -/ def direction (s : affine_subspace k V P) : submodule k V := vector_span k V (s : set P) /-- The direction equals the `vector_span`. -/ lemma direction_eq_vector_span (s : affine_subspace k V P) : s.direction = vector_span k V (s : set P) := rfl /-- Alternative definition of the direction when the affine subspace is nonempty. This is defined so that the order on submodules (as used in the definition of `submodule.span`) can be used in the proof of `coe_direction_eq_vsub_set`, and is not intended to be used beyond that proof. -/ def direction_of_nonempty {s : affine_subspace k V P} (h : (s : set P).nonempty) : submodule k V := { carrier := vsub_set V (s : set P), zero_mem' := begin cases h with p hp, exact (vsub_self V p) ▸ vsub_mem_vsub_set V hp hp end, add_mem' := begin intros a b ha hb, rcases ha with ⟨p1, hp1, p2, hp2, ha⟩, rcases hb with ⟨p3, hp3, p4, hp4, hb⟩, rw [ha, hb, ←vadd_vsub_assoc], refine vsub_mem_vsub_set V _ hp4, convert s.smul_vsub_vadd_mem 1 p1 p2 p3 hp1 hp2 hp3, rw one_smul end, smul_mem' := begin intros c v hv, rcases hv with ⟨p1, hp1, p2, hp2, hv⟩, rw [hv, ←vadd_vsub V (c • (p1 -ᵥ p2)) p2], refine vsub_mem_vsub_set V _ hp2, exact s.smul_vsub_vadd_mem c p1 p2 p2 hp1 hp2 hp2 end } /-- `direction_of_nonempty` gives the same submodule as `direction`. -/ lemma direction_of_nonempty_eq_direction {s : affine_subspace k V P} (h : (s : set P).nonempty) : direction_of_nonempty h = s.direction := le_antisymm (vsub_set_subset_vector_span k V s) (submodule.span_le.2 set.subset.rfl) /-- The set of vectors in the direction of a nonempty affine subspace is given by `vsub_set`. -/ lemma coe_direction_eq_vsub_set {s : affine_subspace k V P} (h : (s : set P).nonempty) : (s.direction : set V) = vsub_set V (s : set P) := direction_of_nonempty_eq_direction h ▸ rfl /-- A vector is in the direction of a nonempty affine subspace if and only if it is the subtraction of two vectors in the subspace. -/ lemma mem_direction_iff_eq_vsub {s : affine_subspace k V P} (h : (s : set P).nonempty) (v : V) : v ∈ s.direction ↔ ∃ p1 ∈ s, ∃ p2 ∈ s, v = p1 -ᵥ p2 := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set h], exact iff.rfl end /-- Adding a vector in the direction to a point in the subspace produces a point in the subspace. -/ lemma vadd_mem_of_mem_direction {s : affine_subspace k V P} {v : V} (hv : v ∈ s.direction) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s := begin rw mem_direction_iff_eq_vsub ⟨p, hp⟩ at hv, rcases hv with ⟨p1, hp1, p2, hp2, hv⟩, rw hv, convert s.smul_vsub_vadd_mem 1 p1 p2 p hp1 hp2 hp, rw one_smul end /-- Subtracting two points in the subspace produces a vector in the direction. -/ lemma vsub_mem_direction {s : affine_subspace k V P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : (p1 -ᵥ p2) ∈ s.direction := vsub_mem_vector_span k V hp1 hp2 /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the right. -/ lemma coe_direction_eq_vsub_set_right {s : affine_subspace k V P} {p : P} (hp : p ∈ s) : (s.direction : set V) = {v | ∃ p2 ∈ s, v = p2 -ᵥ p} := begin rw coe_direction_eq_vsub_set ⟨p, hp⟩, refine le_antisymm _ _, { rintros v ⟨p1, hp1, p2, hp2, hv⟩, exact ⟨v +ᵥ p, vadd_mem_of_mem_direction (hv.symm ▸ vsub_mem_direction hp1 hp2) hp, (vadd_vsub _ _ _).symm⟩ }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p2, hp2, p, hp, hv⟩ } end /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the left. -/ lemma coe_direction_eq_vsub_set_left {s : affine_subspace k V P} {p : P} (hp : p ∈ s) : (s.direction : set V) = {v | ∃ p2 ∈ s, v = p -ᵥ p2} := begin ext v, rw [submodule.mem_coe, ←submodule.neg_mem_iff, ←submodule.mem_coe, coe_direction_eq_vsub_set_right hp, set.mem_set_of_eq, set.mem_set_of_eq], conv_lhs { congr, funext, rw [←neg_vsub_eq_vsub_rev, neg_inj] } end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the right. -/ lemma mem_direction_iff_eq_vsub_right {s : affine_subspace k V P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p2 -ᵥ p := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set_right hp], exact iff.rfl end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the left. -/ lemma mem_direction_iff_eq_vsub_left {s : affine_subspace k V P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p -ᵥ p2 := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set_left hp], exact iff.rfl end /-- Given a point in an affine subspace, a result of subtracting that point on the right is in the direction if and only if the other point is in the subspace. -/ lemma vsub_right_mem_direction_iff_mem {s : affine_subspace k V P} {p : P} (hp : p ∈ s) (p2 : P) : p2 -ᵥ p ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_right hp, simp end /-- Given a point in an affine subspace, a result of subtracting that point on the left is in the direction if and only if the other point is in the subspace. -/ lemma vsub_left_mem_direction_iff_mem {s : affine_subspace k V P} {p : P} (hp : p ∈ s) (p2 : P) : p -ᵥ p2 ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_left hp, simp end /-- Two affine subspaces are equal if they have the same points. -/ @[ext] lemma ext {s1 s2 : affine_subspace k V P} (h : (s1 : set P) = s2) : s1 = s2 := begin cases s1, cases s2, congr, exact h end /-- Two affine subspaces with the same direction and nonempty intersection are equal. -/ lemma ext_of_direction_eq {s1 s2 : affine_subspace k V P} (hd : s1.direction = s2.direction) (hn : ((s1 : set P) ∩ s2).nonempty) : s1 = s2 := begin ext p, have hq1 := set.mem_of_mem_inter_left hn.some_mem, have hq2 := set.mem_of_mem_inter_right hn.some_mem, split, { intro hp, rw ←vsub_vadd V p hn.some, refine vadd_mem_of_mem_direction _ hq2, rw ←hd, exact vsub_mem_direction hp hq1 }, { intro hp, rw ←vsub_vadd V p hn.some, refine vadd_mem_of_mem_direction _ hq1, rw hd, exact vsub_mem_direction hp hq2 } end /-- Construct an affine subspace from a point and a direction. -/ def mk' (p : P) (direction : submodule k V) : affine_subspace k V P := { carrier := {q | ∃ v ∈ direction, q = v +ᵥ p}, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, begin rcases hp1 with ⟨v1, hv1, hp1⟩, rcases hp2 with ⟨v2, hv2, hp2⟩, rcases hp3 with ⟨v3, hv3, hp3⟩, use [c • (v1 - v2) + v3, direction.add_mem (direction.smul_mem c (direction.sub_mem hv1 hv2)) hv3], simp [hp1, hp2, hp3, vadd_assoc] end } /-- An affine space constructed from a point and a direction contains that point. -/ lemma self_mem_mk' (p : P) (direction : submodule k V) : p ∈ mk' p direction := ⟨0, ⟨direction.zero_mem, (add_action.zero_vadd _ _).symm⟩⟩ /-- An affine space constructed from a point and a direction contains the result of adding a vector in that direction to that point. -/ lemma vadd_mem_mk' {v : V} (p : P) {direction : submodule k V} (hv : v ∈ direction) : v +ᵥ p ∈ mk' p direction := ⟨v, hv, rfl⟩ /-- An affine space constructed from a point and a direction is nonempty. -/ lemma mk'_nonempty (p : P) (direction : submodule k V) : (mk' p direction : set P).nonempty := ⟨p, self_mem_mk' p direction⟩ /-- The direction of an affine space constructed from a point and a direction. -/ @[simp] lemma direction_mk' (p : P) (direction : submodule k V) : (mk' p direction).direction = direction := begin ext v, rw mem_direction_iff_eq_vsub (mk'_nonempty _ _), split, { rintros ⟨p1, ⟨v1, hv1, hp1⟩, p2, ⟨v2, hv2, hp2⟩, hv⟩, rw [hv, hp1, hp2, vadd_vsub_vadd_cancel_right], exact direction.sub_mem hv1 hv2 }, { exact λ hv, ⟨v +ᵥ p, vadd_mem_mk' _ hv, p, self_mem_mk' _ _, (vadd_vsub _ _ _).symm⟩ } end /-- Constructing an affine subspace from a point in a subspace and that subspace's direction yields the original subspace. -/ @[simp] lemma mk'_eq {s : affine_subspace k V P} {p : P} (hp : p ∈ s) : mk' p s.direction = s := ext_of_direction_eq (direction_mk' p s.direction) ⟨p, set.mem_inter (self_mem_mk' _ _) hp⟩ /-- If an affine subspace contains a set of points, it contains the `span_points` of that set. -/ lemma span_points_subset_coe_of_subset_coe {s : set P} {s1 : affine_subspace k V P} (h : s ⊆ s1) : span_points k V s ⊆ s1 := begin rintros p ⟨p1, hp1, v, hv, hp⟩, rw hp, have hp1s1 : p1 ∈ (s1 : set P) := set.mem_of_mem_of_subset hp1 h, refine vadd_mem_of_mem_direction _ hp1s1, have hs : vector_span k V s ≤ s1.direction := submodule.span_mono (vsub_set_mono V h), rw submodule.le_def at hs, rw ←submodule.mem_coe, exact set.mem_of_mem_of_subset hv hs end end affine_subspace section affine_span variables (k : Type*) (V : Type*) {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space k V P] /-- The affine span of a set of points is the smallest affine subspace containing those points. (Actually defined here in terms of spans in modules.) -/ def affine_span (s : set P) : affine_subspace k V P := { carrier := span_points k V s, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, vadd_mem_span_points_of_mem_span_points_of_mem_vector_span k V hp3 ((vector_span k V s).smul_mem c (vsub_mem_vector_span_of_mem_span_points_of_mem_span_points k V hp1 hp2)) } /-- The affine span, converted to a set, is `span_points`. -/ @[simp] lemma coe_affine_span (s : set P) : (affine_span k V s : set P) = span_points k V s := rfl /-- The direction of the affine span is the `vector_span`. -/ lemma direction_affine_span (s : set P) : (affine_span k V s).direction = vector_span k V s := begin apply le_antisymm, { refine submodule.span_le.2 _, rintros v ⟨p1, ⟨p2, hp2, v1, hv1, hp1⟩, p3, ⟨p4, hp4, v2, hv2, hp3⟩, hv⟩, rw [hv, hp1, hp3, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, submodule.mem_coe], exact (vector_span k V s).sub_mem ((vector_span k V s).add_mem hv1 (vsub_mem_vector_span k V hp2 hp4)) hv2 }, { exact submodule.span_mono (vsub_set_mono V (subset_span_points k V s)) } end /-- A point in a set is in its affine span. -/ lemma mem_affine_span {p : P} {s : set P} (hp : p ∈ s) : p ∈ affine_span k V s := mem_span_points k V p s hp end affine_span namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [S : affine_space k V P] include S instance : complete_lattice (affine_subspace k V P) := { sup := λ s1 s2, affine_span k V (s1 ∪ s2), le_sup_left := λ s1 s2, set.subset.trans (set.subset_union_left s1 s2) (subset_span_points k V _), le_sup_right := λ s1 s2, set.subset.trans (set.subset_union_right s1 s2) (subset_span_points k V _), sup_le := λ s1 s2 s3 hs1 hs2, span_points_subset_coe_of_subset_coe (set.union_subset hs1 hs2), inf := λ s1 s2, mk (s1 ∩ s2) (λ c p1 p2 p3 hp1 hp2 hp3, ⟨s1.smul_vsub_vadd_mem c p1 p2 p3 hp1.1 hp2.1 hp3.1, s2.smul_vsub_vadd_mem c p1 p2 p3 hp1.2 hp2.2 hp3.2⟩), inf_le_left := λ _ _, set.inter_subset_left _ _, inf_le_right := λ _ _, set.inter_subset_right _ _, le_inf := λ _ _ _, set.subset_inter, top := { carrier := set.univ, smul_vsub_vadd_mem := λ _ _ _ _ _ _ _, set.mem_univ _ }, le_top := λ _ _ _, set.mem_univ _, bot := { carrier := ∅, smul_vsub_vadd_mem := λ _ _ _ _, false.elim }, bot_le := λ _ _, false.elim, Sup := λ s, affine_span k V (⋃ s' ∈ s, (s' : set P)), Inf := λ s, mk (⋂ s' ∈ s, (s' : set P)) (λ c p1 p2 p3 hp1 hp2 hp3, set.mem_bInter_iff.2 $ λ s2 hs2, s2.smul_vsub_vadd_mem c p1 p2 p3 (set.mem_bInter_iff.1 hp1 s2 hs2) (set.mem_bInter_iff.1 hp2 s2 hs2) (set.mem_bInter_iff.1 hp3 s2 hs2)), le_Sup := λ _ _ h, set.subset.trans (set.subset_bUnion_of_mem h) (subset_span_points k V _), Sup_le := λ _ _ h, span_points_subset_coe_of_subset_coe (set.bUnion_subset h), Inf_le := λ _ _, set.bInter_subset_of_mem, le_Inf := λ _ _, set.subset_bInter, .. partial_order.lift (coe : affine_subspace k V P → set P) (λ _ _, ext) } instance : inhabited (affine_subspace k V P) := ⟨⊤⟩ /-- The `≤` order on subspaces is the same as that on the corresponding sets. -/ lemma le_def (s1 s2 : affine_subspace k V P) : s1 ≤ s2 ↔ (s1 : set P) ⊆ s2 := iff.rfl /-- One subspace is less than or equal to another if and only if all its points are in the second subspace. -/ lemma le_def' (s1 s2 : affine_subspace k V P) : s1 ≤ s2 ↔ ∀ p ∈ s1, p ∈ s2 := iff.rfl /-- The `<` order on subspaces is the same as that on the corresponding sets. -/ lemma lt_def (s1 s2 : affine_subspace k V P) : s1 < s2 ↔ (s1 : set P) ⊂ s2 := iff.rfl /-- One subspace is not less than or equal to another if and only if it has a point not in the second subspace. -/ lemma not_le_iff_exists (s1 s2 : affine_subspace k V P) : ¬ s1 ≤ s2 ↔ ∃ p ∈ s1, p ∉ s2 := set.not_subset /-- If a subspace is less than another, there is a point only in the second. -/ lemma exists_of_lt {s1 s2 : affine_subspace k V P} (h : s1 < s2) : ∃ p ∈ s2, p ∉ s1 := set.exists_of_ssubset h /-- A subspace is less than another if and only if it is less than or equal to the second subspace and there is a point only in the second. -/ lemma lt_iff_le_and_exists (s1 s2 : affine_subspace k V P) : s1 < s2 ↔ s1 ≤ s2 ∧ ∃ p ∈ s2, p ∉ s1 := by rw [lt_iff_le_not_le, not_le_iff_exists] variables (k V) /-- The affine span is the `Inf` of subspaces containing the given points. -/ lemma affine_span_eq_Inf (s : set P) : affine_span k V s = Inf {s' | s ⊆ s'} := le_antisymm (span_points_subset_coe_of_subset_coe (set.subset_bInter (λ _ h, h))) (Inf_le (subset_span_points k V _)) variables (P) /-- The Galois insertion formed by `affine_span` and coercion back to a set. -/ protected def gi : galois_insertion (affine_span k V) (coe : affine_subspace k V P → set P) := { choice := λ s _, affine_span k V s, gc := λ s1 s2, ⟨λ h, set.subset.trans (subset_span_points k V s1) h, span_points_subset_coe_of_subset_coe⟩, le_l_u := λ _, subset_span_points k V _, choice_eq := λ _ _, rfl } /-- The span of the empty set is `⊥`. -/ @[simp] lemma span_empty : affine_span k V (∅ : set P) = ⊥ := (affine_subspace.gi k V P).gc.l_bot /-- The span of `univ` is `⊤`. -/ @[simp] lemma span_univ : affine_span k V (set.univ : set P) = ⊤ := eq_top_iff.2 $ subset_span_points k V _ variables {P} /-- The span of a union of sets is the sup of their spans. -/ lemma span_union (s t : set P) : affine_span k V (s ∪ t) = affine_span k V s ⊔ affine_span k V t := (affine_subspace.gi k V P).gc.l_sup /-- The span of a union of an indexed family of sets is the sup of their spans. -/ lemma span_Union {ι : Type*} (s : ι → set P) : affine_span k V (⋃ i, s i) = ⨆ i, affine_span k V (s i) := (affine_subspace.gi k V P).gc.l_supr variables (P) /-- `⊤`, coerced to a set, is the whole set of points. -/ @[simp] lemma top_coe : ((⊤ : affine_subspace k V P) : set P) = set.univ := rfl variables {P} /-- All points are in `⊤`. -/ lemma mem_top (p : P) : p ∈ (⊤ : affine_subspace k V P) := set.mem_univ p variables (P) /-- The direction of `⊤` is the whole module as a submodule. -/ @[simp] lemma direction_top : (⊤ : affine_subspace k V P).direction = ⊤ := begin cases S.nonempty with p, ext v, refine ⟨imp_intro submodule.mem_top, λ hv, _⟩, have hpv : (v +ᵥ p -ᵥ p : V) ∈ (⊤ : affine_subspace k V P).direction := vsub_mem_direction (mem_top k V _) (mem_top k V _), rwa vadd_vsub at hpv end /-- `⊥`, coerced to a set, is the empty set. -/ @[simp] lemma bot_coe : ((⊥ : affine_subspace k V P) : set P) = ∅ := rfl variables {P} /-- No points are in `⊥`. -/ lemma not_mem_bot (p : P) : p ∉ (⊥ : affine_subspace k V P) := set.not_mem_empty p variables (P) /-- The direction of `⊥` is the submodule `⊥`. -/ @[simp] lemma direction_bot : (⊥ : affine_subspace k V P).direction = ⊥ := by rw [direction_eq_vector_span, bot_coe, vector_span_def, vsub_set_empty, submodule.span_empty] variables {k V P} /-- The inf of two affine subspaces, coerced to a set, is the intersection of the two sets of points. -/ @[simp] lemma inf_coe (s1 s2 : affine_subspace k V P) : ((s1 ⊓ s2) : set P) = s1 ∩ s2 := rfl /-- A point is in the inf of two affine subspaces if and only if it is in both of them. -/ lemma mem_inf_iff (p : P) (s1 s2 : affine_subspace k V P) : p ∈ s1 ⊓ s2 ↔ p ∈ s1 ∧ p ∈ s2 := iff.rfl /-- The direction of the inf of two affine subspaces is less than or equal to the inf of their directions. -/ lemma direction_inf (s1 s2 : affine_subspace k V P) : (s1 ⊓ s2).direction ≤ s1.direction ⊓ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact le_inf (Inf_le_Inf (λ p hp, set.subset.trans (vsub_set_mono V (set.inter_subset_left _ _)) hp)) (Inf_le_Inf (λ p hp, set.subset.trans (vsub_set_mono V (set.inter_subset_right _ _)) hp)) end /-- If one affine subspace is less than or equal to another, the same applies to their directions. -/ lemma direction_le {s1 s2 : affine_subspace k V P} (h : s1 ≤ s2) : s1.direction ≤ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact submodule.span_mono (vsub_set_mono _ h) end /-- If one nonempty affine subspace is less than another, the same applies to their directions -/ lemma direction_lt_of_nonempty {s1 s2 : affine_subspace k V P} (h : s1 < s2) (hn : (s1 : set P).nonempty) : s1.direction < s2.direction := begin cases hn with p hp, rw lt_iff_le_and_exists at h, rcases h with ⟨hle, p2, hp2, hp2s1⟩, rw submodule.lt_iff_le_and_exists, use [direction_le hle, p2 -ᵥ p, vsub_mem_direction hp2 (hle hp)], intro hm, rw vsub_right_mem_direction_iff_mem hp p2 at hm, exact hp2s1 hm end /-- The sup of the directions of two affine subspaces is less than or equal to the direction of their sup. -/ lemma sup_direction_le (s1 s2 : affine_subspace k V P) : s1.direction ⊔ s2.direction ≤ (s1 ⊔ s2).direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact sup_le (Inf_le_Inf (λ p hp, set.subset.trans (vsub_set_mono V (le_sup_left : s1 ≤ s1 ⊔ s2)) hp)) (Inf_le_Inf (λ p hp, set.subset.trans (vsub_set_mono V (le_sup_right : s2 ≤ s1 ⊔ s2)) hp)) end /-- The sup of the directions of two nonempty affine subspaces with empty intersection is less than the direction of their sup. -/ lemma sup_direction_lt_of_nonempty_of_inter_empty {s1 s2 : affine_subspace k V P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (he : (s1 ∩ s2 : set P) = ∅) : s1.direction ⊔ s2.direction < (s1 ⊔ s2).direction := begin cases h1 with p1 hp1, cases h2 with p2 hp2, rw submodule.lt_iff_le_and_exists, use [sup_direction_le s1 s2, p2 -ᵥ p1, vsub_mem_direction ((le_sup_right : s2 ≤ s1 ⊔ s2) hp2) ((le_sup_left : s1 ≤ s1 ⊔ s2) hp1)], intro h, rw submodule.mem_sup at h, rcases h with ⟨v1, hv1, v2, hv2, hv1v2⟩, rw [←sub_eq_zero, sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm v1, add_assoc, ←vadd_vsub_assoc, ←neg_neg v2, add_comm, ←sub_eq_add_neg, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hv1v2, refine set.nonempty.ne_empty _ he, use [v1 +ᵥ p1, vadd_mem_of_mem_direction hv1 hp1], rw hv1v2, exact vadd_mem_of_mem_direction (submodule.neg_mem _ hv2) hp2 end /-- If the directions of two nonempty affine subspaces span the whole module, they have nonempty intersection. -/ lemma inter_nonempty_of_nonempty_of_sup_direction_eq_top {s1 s2 : affine_subspace k V P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : s1.direction ⊔ s2.direction = ⊤) : ((s1 : set P) ∩ s2).nonempty := begin by_contradiction h, rw set.not_nonempty_iff_eq_empty at h, have hlt := sup_direction_lt_of_nonempty_of_inter_empty h1 h2 h, rw hd at hlt, exact not_top_lt hlt end /-- If the directions of two nonempty affine subspaces are complements of each other, they intersect in exactly one point. -/ lemma inter_eq_singleton_of_nonempty_of_is_compl {s1 s2 : affine_subspace k V P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : is_compl s1.direction s2.direction) : ∃ p, (s1 : set P) ∩ s2 = {p} := begin cases inter_nonempty_of_nonempty_of_sup_direction_eq_top h1 h2 hd.sup_eq_top with p hp, use p, ext q, rw set.mem_singleton_iff, split, { rintros ⟨hq1, hq2⟩, have hqp : q -ᵥ p ∈ s1.direction ⊓ s2.direction := ⟨vsub_mem_direction hq1 hp.1, vsub_mem_direction hq2 hp.2⟩, rwa [hd.inf_eq_bot, submodule.mem_bot, vsub_eq_zero_iff_eq] at hqp }, { exact λ h, h.symm ▸ hp } end end affine_subspace namespace affine_space variables (k : Type*) (V : Type*) {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space k V P] variables {ι : Type*} /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_eq_span_vsub_set_left {s : set P} {p : P} (hp : p ∈ s) : vector_span k V s = submodule.span k {v | ∃ p2 ∈ s, v = p -ᵥ p2} := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, hp1, p2, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_left V p1 p2 p at hv, rw [hv, submodule.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p2, hp2, rfl⟩) (hm ⟨p1, hp1, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p, hp, p2, hp2, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_eq_span_vsub_set_right {s : set P} {p : P} (hp : p ∈ s) : vector_span k V s = submodule.span k {v | ∃ p2 ∈ s, v = p2 -ᵥ p} := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, hp1, p2, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_right V p1 p2 p at hv, rw [hv, submodule.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p1, hp1, rfl⟩) (hm ⟨p2, hp2, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p2, hp2, p, hp, hv⟩ } end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_range_eq_span_range_vsub_left (p : ι → P) (i0 : ι) : vector_span k V (set.range p) = submodule.span k (set.range (λ (i : ι), p i0 -ᵥ p i)) := begin simp_rw [vector_span_eq_span_vsub_set_left k V (set.mem_range_self i0), set.exists_range_iff], conv_lhs { congr, congr, funext, conv { congr, funext, rw eq_comm } }, refl end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_range_eq_span_range_vsub_right (p : ι → P) (i0 : ι) : vector_span k V (set.range p) = submodule.span k (set.range (λ (i : ι), p i -ᵥ p i0)) := begin simp_rw [vector_span_eq_span_vsub_set_right k V (set.mem_range_self i0), set.exists_range_iff], conv_lhs { congr, congr, funext, conv { congr, funext, rw eq_comm } }, refl end /-- The affine span of a set is nonempty if and only if that set is. -/ lemma affine_span_nonempty (s : set P) : (affine_span k V s : set P).nonempty ↔ s.nonempty := span_points_nonempty k V s variables {k} /-- A `weighted_vsub` with sum of weights 0 is in the `vector_span` of an indexed family. -/ lemma weighted_vsub_mem_vector_span {s : finset ι} {w : ι → k} (h : ∑ i in s, w i = 0) (p : ι → P) : s.weighted_vsub V p w ∈ vector_span k V (set.range p) := begin by_cases hn : nonempty ι, { cases hn with i0, rw [vector_span_range_eq_span_range_vsub_right k V p i0, ←set.image_univ, finsupp.mem_span_iff_total, finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero V s w p h (p i0), finset.weighted_vsub_of_point_apply], let w' := set.indicator ↑s w, have hwx : ∀ i, w' i ≠ 0 → i ∈ s := λ i, set.mem_of_indicator_ne_zero, use [finsupp.on_finset s w' hwx, set.subset_univ _], rw [finsupp.total_apply, finsupp.on_finset_sum hwx], { apply finset.sum_congr rfl, intros i hi, simp [w', set.indicator_apply, if_pos hi] }, { exact λ _, zero_smul k _ } }, { simp [finset.eq_empty_of_not_nonempty hn s] } end /-- An `affine_combination` with sum of weights 1 is in the `affine_span` of an indexed family, if the underlying ring is nontrivial. -/ lemma affine_combination_mem_affine_span [nontrivial k] {s : finset ι} {w : ι → k} (h : ∑ i in s, w i = 1) (p : ι → P) : s.affine_combination V w p ∈ affine_span k V (set.range p) := begin have hnz : ∑ i in s, w i ≠ 0 := h.symm ▸ one_ne_zero, have hn : s.nonempty := finset.nonempty_of_sum_ne_zero hnz, cases hn with i1 hi1, let w1 : ι → k := function.update (function.const ι 0) i1 1, have hw1 : ∑ i in s, w1 i = 1, { rw [finset.sum_update_of_mem hi1, finset.sum_const_zero, add_zero] }, have hw1s : s.affine_combination V w1 p = p i1 := s.affine_combination_of_eq_one_of_eq_zero V w1 p hi1 (function.update_same _ _ _) (λ _ _ hne, function.update_noteq hne _ _), have hv : s.affine_combination V w p -ᵥ p i1 ∈ (affine_span k V (set.range p)).direction, { rw [direction_affine_span, ←hw1s, finset.affine_combination_vsub], apply weighted_vsub_mem_vector_span, simp [pi.sub_apply, h, hw1] }, rw ←vsub_vadd V (s.affine_combination V w p) (p i1), exact affine_subspace.vadd_mem_of_mem_direction hv (mem_affine_span k V (set.mem_range_self _)) end variables (k) {V} /-- A vector is in the `vector_span` of an indexed family if and only if it is a `weighted_vsub` with sum of weights 0. -/ lemma mem_vector_span_iff_eq_weighted_vsub {v : V} {p : ι → P} : v ∈ vector_span k V (set.range p) ↔ ∃ (s : finset ι) (w : ι → k) (h : ∑ i in s, w i = 0), v = s.weighted_vsub V p w := begin split, { by_cases hn : nonempty ι, { cases hn with i0, rw [vector_span_range_eq_span_range_vsub_right k V p i0, ←set.image_univ, finsupp.mem_span_iff_total], rintros ⟨l, hl, hv⟩, use insert i0 l.support, set w := (l : ι → k) - function.update (function.const ι 0 : ι → k) i0 (∑ i in l.support, l i) with hwdef, use w, have hw : ∑ i in insert i0 l.support, w i = 0, { rw hwdef, simp_rw [pi.sub_apply, finset.sum_sub_distrib, finset.sum_update_of_mem (finset.mem_insert_self _ _), finset.sum_const_zero, finset.sum_insert_of_eq_zero_if_not_mem finsupp.not_mem_support_iff.1, add_zero, sub_self] }, use hw, have hz : w i0 • (p i0 -ᵥ p i0 : V) = 0 := (vsub_self V (p i0)).symm ▸ smul_zero _, change (λ i, w i • (p i -ᵥ p i0 : V)) i0 = 0 at hz, rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero V _ w p hw (p i0), finset.weighted_vsub_of_point_apply, ←hv, finsupp.total_apply, finset.sum_insert_zero hz], change ∑ i in l.support, l i • _ = _, congr, ext i, by_cases h : i = i0, { simp [h] }, { simp [hwdef, h] } }, { rw [set.range_eq_empty.2 hn, vector_span_empty, submodule.mem_bot], intro hv, use [∅], simp [hv] } }, { rintros ⟨s, w, hw, rfl⟩, exact weighted_vsub_mem_vector_span V hw p } end variables {k} /-- A point in the `affine_span` of an indexed family is an `affine_combination` with sum of weights 1. -/ lemma eq_affine_combination_of_mem_affine_span {p1 : P} {p : ι → P} (h : p1 ∈ affine_span k V (set.range p)) : ∃ (s : finset ι) (w : ι → k) (hw : ∑ i in s, w i = 1), p1 = s.affine_combination V w p := begin have hn : ((affine_span k V (set.range p)) : set P).nonempty := ⟨p1, h⟩, rw [affine_span_nonempty, set.range_nonempty_iff_nonempty] at hn, cases hn with i0, have h0 : p i0 ∈ affine_span k V (set.range p) := mem_affine_span k V (set.mem_range_self i0), have hd : p1 -ᵥ p i0 ∈ (affine_span k V (set.range p)).direction := affine_subspace.vsub_mem_direction h h0, rw [direction_affine_span, mem_vector_span_iff_eq_weighted_vsub] at hd, rcases hd with ⟨s, w, h, hs⟩, let s' := insert i0 s, let w' := set.indicator ↑s w, have h' : ∑ i in s', w' i = 0, { rw [←h, set.sum_indicator_subset _ (finset.subset_insert i0 s)] }, have hs' : s'.weighted_vsub V p w' = p1 -ᵥ p i0, { rw hs, exact (finset.weighted_vsub_indicator_subset _ _ _ (finset.subset_insert i0 s)).symm }, let w0 : ι → k := function.update (function.const ι 0) i0 1, have hw0 : ∑ i in s', w0 i = 1, { rw [finset.sum_update_of_mem (finset.mem_insert_self _ _), finset.sum_const_zero, add_zero] }, have hw0s : s'.affine_combination V w0 p = p i0 := s'.affine_combination_of_eq_one_of_eq_zero V w0 p (finset.mem_insert_self _ _) (function.update_same _ _ _) (λ _ _ hne, function.update_noteq hne _ _), use [s', w0 + w'], split, { simp [pi.add_apply, finset.sum_add_distrib, hw0, h'] }, { rw [add_comm, ←finset.weighted_vsub_vadd_affine_combination, hw0s, hs', vsub_vadd] } end variables (k V) /-- A point is in the `affine_span` of an indexed family if and only if it is an `affine_combination` with sum of weights 1, provided the underlying ring is nontrivial. -/ lemma mem_affine_span_iff_eq_affine_combination [nontrivial k] {p1 : P} {p : ι → P} : p1 ∈ affine_span k V (set.range p) ↔ ∃ (s : finset ι) (w : ι → k) (hw : ∑ i in s, w i = 1), p1 = s.affine_combination V w p := begin split, { exact eq_affine_combination_of_mem_affine_span }, { rintros ⟨s, w, hw, rfl⟩, exact affine_combination_mem_affine_span V hw p } end end affine_space /-- An `affine_map k V1 P1 V2 P2` is a map from `P1` to `P2` that induces a corresponding linear map from `V1` to `V2`. -/ structure affine_map (k : Type*) (V1 : Type*) (P1 : Type*) (V2 : Type*) (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space k V1 P1] [add_comm_group V2] [module k V2] [affine_space k V2 P2] := (to_fun : P1 → P2) (linear : linear_map k V1 V2) (map_vadd' : ∀ (p : P1) (v : V1), to_fun (v +ᵥ p) = linear v +ᵥ to_fun p) namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} {P2 : Type*} {V3 : Type*} {P3 : Type*} {V4 : Type*} {P4 : Type*} [ring k] [add_comm_group V1] [module k V1] [affine_space k V1 P1] [add_comm_group V2] [module k V2] [affine_space k V2 P2] [add_comm_group V3] [module k V3] [affine_space k V3 P3] [add_comm_group V4] [module k V4] [affine_space k V4 P4] instance: has_coe_to_fun (affine_map k V1 P1 V2 P2) := ⟨_, to_fun⟩ /-- Constructing an affine map and coercing back to a function produces the same map. -/ @[simp] lemma coe_mk (f : P1 → P2) (linear add) : ((mk f linear add : affine_map k V1 P1 V2 P2) : P1 → P2) = f := rfl /-- `to_fun` is the same as the result of coercing to a function. -/ @[simp] lemma to_fun_eq_coe (f : affine_map k V1 P1 V2 P2) : f.to_fun = ⇑f := rfl /-- An affine map on the result of adding a vector to a point produces the same result as the linear map applied to that vector, added to the affine map applied to that point. -/ @[simp] lemma map_vadd (f : affine_map k V1 P1 V2 P2) (p : P1) (v : V1) : f (v +ᵥ p) = f.linear v +ᵥ f p := f.map_vadd' p v /-- The linear map on the result of subtracting two points is the result of subtracting the result of the affine map on those two points. -/ @[simp] lemma linear_map_vsub (f : affine_map k V1 P1 V2 P2) (p1 p2 : P1) : f.linear (p1 -ᵥ p2) = f p1 -ᵥ f p2 := by conv_rhs { rw [←vsub_vadd V1 p1 p2, map_vadd, vadd_vsub] } /-- Two affine maps are equal if they coerce to the same function. -/ @[ext] lemma ext {f g : affine_map k V1 P1 V2 P2} (h : ∀ p, f p = g p) : f = g := begin rcases f with ⟨f, f_linear, f_add⟩, rcases g with ⟨g, g_linear, g_add⟩, have : f = g := funext h, subst g, congr', ext v, cases (add_torsor.nonempty V1 : nonempty P1) with p, apply vadd_right_cancel (f p), erw [← f_add, ← g_add] end lemma ext_iff {f g : affine_map k V1 P1 V2 P2} : f = g ↔ ∀ p, f p = g p := ⟨λ h p, h ▸ rfl, ext⟩ variables (k V1 P1 V2) /-- Constant function as an `affine_map`. -/ def const (p : P2) : affine_map k V1 P1 V2 P2 := { to_fun := function.const P1 p, linear := 0, map_vadd' := λ p v, by simp } @[simp] lemma coe_const (p : P2) : ⇑(const k V1 P1 V2 p) = function.const P1 p := rfl @[simp] lemma const_linear (p : P2) : (const k V1 P1 V2 p).linear = 0 := rfl variables {k V1 P1 V2} instance nonempty : nonempty (affine_map k V1 P1 V2 P2) := ⟨const k V1 P1 V2 (classical.choice $ add_torsor.nonempty V2)⟩ /-- Construct an affine map by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `f : P₁ → P₂`, a linear map `f' : V₁ →ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `f p' = f' (p' -ᵥ p) +ᵥ f p`. -/ def mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p : P1) (h : ∀ p' : P1, f p' = f' (p' -ᵥ p) +ᵥ f p) : affine_map k V1 P1 V2 P2 := { to_fun := f, linear := f', map_vadd' := λ p' v, by rw [h, h p', vadd_vsub_assoc, f'.map_add, add_action.vadd_assoc] } @[simp] lemma coe_mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : ⇑(mk' f f' p h) = f := rfl @[simp] lemma mk'_linear (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : (mk' f f' p h).linear = f' := rfl /-- The set of affine maps to a vector space is an additive commutative group. -/ instance : add_comm_group (affine_map k V1 P1 V2 V2) := { zero := ⟨0, 0, λ p v, (add_action.zero_vadd _ _).symm⟩, add := λ f g, ⟨f + g, f.linear + g.linear, λ p v, by simp [add_add_add_comm]⟩, neg := λ f, ⟨-f, -f.linear, λ p v, by simp [add_comm]⟩, add_assoc := λ f₁ f₂ f₃, ext $ λ p, add_assoc _ _ _, zero_add := λ f, ext $ λ p, zero_add (f p), add_zero := λ f, ext $ λ p, add_zero (f p), add_comm := λ f g, ext $ λ p, add_comm (f p) (g p), add_left_neg := λ f, ext $ λ p, add_left_neg (f p) } @[simp, norm_cast] lemma coe_zero : ⇑(0 : affine_map k V1 P1 V2 V2) = 0 := rfl @[simp] lemma zero_linear : (0 : affine_map k V1 P1 V2 V2).linear = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : affine_map k V1 P1 V2 V2) : ⇑(f + g) = f + g := rfl @[simp] lemma add_linear (f g : affine_map k V1 P1 V2 V2) : (f + g).linear = f.linear + g.linear := rfl /-- The space of affine maps from `P1` to `P2` is an affine space over the space of affine spaces from `P1` to the vector `V2` corresponding to `P2`. -/ instance : affine_space k (affine_map k V1 P1 V2 V2) (affine_map k V1 P1 V2 P2) := { vadd := λ f g, ⟨λ p, f p +ᵥ g p, f.linear + g.linear, λ p v, by simp [add_action.vadd_assoc, add_right_comm]⟩, zero_vadd' := λ f, ext $ λ p, add_action.zero_vadd _ (f p), vadd_assoc' := λ f₁ f₂ f₃, ext $ λ p, add_action.vadd_assoc V2 (f₁ p) (f₂ p) (f₃ p), vsub := λ f g, ⟨λ p, f p -ᵥ g p, f.linear - g.linear, λ p v, by simp [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, sub_add_eq_add_sub]⟩, vsub_vadd' := λ f g, ext $ λ p, vsub_vadd V2 (f p) (g p), vadd_vsub' := λ f g, ext $ λ p, vadd_vsub V2 (f p) (g p) } @[simp] lemma vadd_apply (f : affine_map k V1 P1 V2 V2) (g : affine_map k V1 P1 V2 P2) (p : P1) : (f +ᵥ g) p = f p +ᵥ g p := rfl @[simp] lemma vsub_apply (f g : affine_map k V1 P1 V2 P2) (p : P1) : (f -ᵥ g : affine_map k V1 P1 V2 V2) p = f p -ᵥ g p := rfl variables (k V1 P1) /-- Identity map as an affine map. -/ def id : affine_map k V1 P1 V1 P1 := { to_fun := id, linear := linear_map.id, map_vadd' := λ p v, rfl } /-- The identity affine map acts as the identity. -/ @[simp] lemma coe_id : ⇑(id k V1 P1) = _root_.id := rfl @[simp] lemma id_linear : (id k V1 P1).linear = linear_map.id := rfl variable {P1} /-- The identity affine map acts as the identity. -/ lemma id_apply (p : P1) : id k V1 P1 p = p := rfl variables {k V1 P1 V2} instance : inhabited (affine_map k V1 P1 V1 P1) := ⟨id k V1 P1⟩ /-- Composition of affine maps. -/ def comp (f : affine_map k V2 P2 V3 P3) (g : affine_map k V1 P1 V2 P2) : affine_map k V1 P1 V3 P3 := { to_fun := f ∘ g, linear := f.linear.comp g.linear, map_vadd' := begin intros p v, rw [function.comp_app, g.map_vadd, f.map_vadd], refl end } /-- Composition of affine maps acts as applying the two functions. -/ @[simp] lemma coe_comp (f : affine_map k V2 P2 V3 P3) (g : affine_map k V1 P1 V2 P2) : ⇑(f.comp g) = f ∘ g := rfl /-- Composition of affine maps acts as applying the two functions. -/ lemma comp_apply (f : affine_map k V2 P2 V3 P3) (g : affine_map k V1 P1 V2 P2) (p : P1) : f.comp g p = f (g p) := rfl @[simp] lemma comp_id (f : affine_map k V1 P1 V2 P2) : f.comp (id k V1 P1) = f := ext $ λ p, rfl @[simp] lemma id_comp (f : affine_map k V1 P1 V2 P2) : (id k V2 P2).comp f = f := ext $ λ p, rfl lemma comp_assoc (f₃₄ : affine_map k V3 P3 V4 P4) (f₂₃ : affine_map k V2 P2 V3 P3) (f₁₂ : affine_map k V1 P1 V2 P2) : (f₃₄.comp f₂₃).comp f₁₂ = f₃₄.comp (f₂₃.comp f₁₂) := rfl instance : monoid (affine_map k V1 P1 V1 P1) := { one := id k V1 P1, mul := comp, one_mul := id_comp, mul_one := comp_id, mul_assoc := comp_assoc } @[simp] lemma coe_mul (f g : affine_map k V1 P1 V1 P1) : ⇑(f * g) = f ∘ g := rfl @[simp] lemma coe_one : ⇑(1 : affine_map k V1 P1 V1 P1) = _root_.id := rfl /-- The affine map from `k` to `P1` sending `0` to `p` and `1` to `v +ᵥ p`. -/ def line_map (p : P1) (v : V1) : affine_map k k k V1 P1 := { to_fun := λ c, c • v +ᵥ p, linear := linear_map.id.smul_right v, map_vadd' := λ a b, by simp [add_smul, add_action.vadd_assoc] } lemma line_map_apply (p : P1) (v : V1) (c : k) : line_map p v c = c • v +ᵥ p := rfl @[simp] lemma line_map_linear (p : P1) (v : V1) : (line_map p v : affine_map k k k V1 P1).linear = linear_map.id.smul_right v := rfl @[simp] lemma line_map_zero (p : P1) : line_map p (0:V1) = const k k k V1 p := by { ext c, simp [line_map_apply] } @[simp] lemma line_map_apply_zero (p : P1) (v : V1) : line_map p v (0:k) = p := by simp [line_map_apply] @[simp] lemma affine_apply_line_map (f : affine_map k V1 P1 V2 P2) (p : P1) (v : V1) (c : k) : f (line_map p v c) = line_map (f p) (f.linear v) c := by simp [line_map_apply] @[simp] lemma affine_comp_line_map (f : affine_map k V1 P1 V2 P2) (p : P1) (v : V1) : f.comp (line_map p v) = line_map (f p) (f.linear v) := ext $ f.affine_apply_line_map p v lemma line_map_vadd_neg (p : P1) (v : V1) : line_map (v +ᵥ p) (-v) = (line_map p v).comp (line_map (1:k) (-1:k)) := by { rw [affine_comp_line_map], simp [line_map_apply] } end affine_map namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} [comm_ring k] [add_comm_group V1] [module k V1] [affine_space k V1 P1] [add_comm_group V2] [module k V2] /-- If `k` is a commutative ring, then the set of affine maps with codomain in a `k`-module is a `k`-module. -/ instance : module k (affine_map k V1 P1 V2 V2) := { smul := λ c f, ⟨c • f, c • f.linear, λ p v, by simp [smul_add]⟩, one_smul := λ f, ext $ λ p, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ p, mul_smul _ _ _, smul_add := λ c f g, ext $ λ p, smul_add _ _ _, smul_zero := λ c, ext $ λ p, smul_zero _, add_smul := λ c₁ c₂ f, ext $ λ p, add_smul _ _ _, zero_smul := λ f, ext $ λ p, zero_smul _ _ } @[simp] lemma coe_smul (c : k) (f : affine_map k V1 P1 V2 V2) : ⇑(c • f) = c • f := rfl variable (V1) /-- `homothety V c r` is the homothety about `c` with scale factor `r`. -/ def homothety (c : P1) (r : k) : affine_map k V1 P1 V1 P1 := r • (id k V1 P1 -ᵥ const k V1 P1 V1 c : affine_map k V1 P1 V1 V1) +ᵥ const k V1 P1 V1 c lemma homothety_def (c : P1) (r : k) : homothety V1 c r = r • (id k V1 P1 -ᵥ const k V1 P1 V1 c : affine_map k V1 P1 V1 V1) +ᵥ const k V1 P1 V1 c := rfl lemma homothety_apply (c : P1) (r : k) (p : P1) : homothety V1 c r p = r • (p -ᵥ c : V1) +ᵥ c := rfl @[simp] lemma homothety_one (c : P1) : homothety V1 c (1:k) = id k V1 P1 := by { ext p, simp [homothety_apply] } lemma homothety_mul (c : P1) (r₁ r₂ : k) : homothety V1 c (r₁ * r₂) = (homothety V1 c r₁).comp (homothety V1 c r₂) := by { ext p, simp [homothety_apply, mul_smul] } @[simp] lemma homothety_zero (c : P1) : homothety V1 c (0:k) = const k V1 P1 V1 c := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_add (c : P1) (r₁ r₂ : k) : homothety V1 c (r₁ + r₂) = r₁ • (id k V1 P1 -ᵥ const k V1 P1 V1 c : affine_map k V1 P1 V1 V1) +ᵥ homothety V1 c r₂ := by simp only [homothety_def, add_smul, add_action.vadd_assoc] /-- `homothety` as a multiplicative monoid homomorphism. -/ def homothety_hom (c : P1) : k →* affine_map k V1 P1 V1 P1 := ⟨homothety V1 c, homothety_one V1 c, homothety_mul V1 c⟩ @[simp] lemma coe_homothety_hom (c : P1) : ⇑(homothety_hom V1 c : k →* _) = homothety V1 c := rfl /-- `homothety` as an affine map. -/ def homothety_affine (c : P1) : affine_map k k k (affine_map k V1 P1 V1 V1) (affine_map k V1 P1 V1 P1) := ⟨homothety V1 c, (linear_map.lsmul k _).flip (id k V1 P1 -ᵥ const k V1 P1 V1 c), function.swap (homothety_add V1 c)⟩ @[simp] lemma coe_homothety_affine (c : P1) : ⇑(homothety_affine V1 c : affine_map k k k _ _) = homothety V1 c := rfl end affine_map namespace affine_map variables {k : Type*} (V : Type*) (P : Type*) [comm_ring k] [add_comm_group V] [module k V] variables [affine_space k V P] {ι : Type*} (s : finset ι) -- TODO: define `affine_map.proj`, `affine_map.fst`, `affine_map.snd` /-- A weighted sum, as an affine map on the points involved. -/ def weighted_vsub_of_point (w : ι → k) : affine_map k ((ι → V) × V) ((ι → P) × P) V V := { to_fun := λ p, s.weighted_vsub_of_point _ p.fst p.snd w, linear := ∑ i in s, w i • ((linear_map.proj i).comp (linear_map.fst _ _ _) - linear_map.snd _ _ _), map_vadd' := begin rintros ⟨p, b⟩ ⟨v, b'⟩, simp [linear_map.sum_apply, finset.weighted_vsub_of_point, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, ← sub_add_eq_add_sub, smul_add, finset.sum_add_distrib] end } end affine_map namespace linear_map variables {k : Type*} {V₁ : Type*} {V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_comm_group V₂] [module k V₂] (f : V₁ →ₗ[k] V₂) /-- Reinterpret a linear map as an affine map. -/ def to_affine_map : affine_map k V₁ V₁ V₂ V₂ := { to_fun := f, linear := f, map_vadd' := λ p v, f.map_add v p } @[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl @[simp] lemma to_affine_map_linear : f.to_affine_map.linear = f := rfl end linear_map
151680e55315bb0f2447a39d9975fbaf9560266c
761d983a78bc025071bac14a3facced881cf5e53
/new_affine/real_affine_space.lean
77b07603aab2f8fc0f2b70591d82c07f04f1c095
[]
no_license
rohanrajnair/affine_lib
bcf22ff892cf74ccb36a95bc9b7fff8e0adb2d0d
83076864245ac547b9d615bc6a23804b1b4a8f70
refs/heads/master
1,673,320,928,343
1,603,036,653,000
1,603,036,653,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,459
lean
import linear_algebra.affine_space.basic import ..new_affine.affine_coordinate_space import data.real.basic namespace real_affine abbreviation real_vec := aff_vec ℝ abbreviation real_pt := aff_pt ℝ abbreviation r3_vec := real_vec 3 abbreviation r3_pt := real_pt 3 universes u v w structure aff_struct := (X : Type u) (K : Type v) (V : Type w) (fld : ring K) (grp : add_comm_group V) (vec : module K V) (aff : affine_space V X) structure vec_struct := (K : Type u) (V : Type v) (fld : field K) (grp : add_comm_group V) (vec : vector_space K V) inductive Algebra | aff_space (a : aff_struct) | vec_space (v : vec_struct) | nat_monoid -- placeholder, commutative monoid with monus operator def real_aff_pt_n := λn : ℕ, aff_pt ℝ n def real_scalar := ℝ def real_aff_vec_n := λn : ℕ, aff_vec ℝ n def prf_ring := real.ring def prf_real_add_comm_grp_n := λn : ℕ, aff_comm_group ℝ n def prf_vec_module_n := λn : ℕ, aff_module ℝ n def prf_aff_crd_sp := λn : ℕ, aff_coord_is ℝ n --⟨aff_pt ℝ n, ℝ, aff_vec ℝ n, real.ring, aff_comm_group ℝ n, aff_module ℝ n, aff_coord_is ℝ n⟩ def to_affine : ℕ → aff_struct := λ n, ⟨real_aff_pt_n n, ℝ , (real_aff_vec_n n), real.ring, prf_real_add_comm_grp_n n,prf_vec_module_n n,prf_aff_crd_sp n⟩ noncomputable def to_vector : ℕ → vec_struct := λ n, ⟨ℝ, aff_vec ℝ n, real.field, aff_comm_group ℝ n, aff_module ℝ n⟩ end real_affine
1295b8cc000f3dab2d808cc982ffce16260c8884
aa101d73b1a3173c7ec56de02b96baa8ca64c42e
/src/my_exercises/07_first_negations.lean
edc2bae977561a16cadada2b70eeb85bfdbf2a1d
[ "Apache-2.0" ]
permissive
gihanmarasingha/tutorials
b554d4d53866c493c4341dc13e914b01444e95a6
56617114ef0f9f7b808476faffd11e22e4380918
refs/heads/master
1,671,141,758,153
1,599,173,318,000
1,599,173,318,000
282,405,870
0
0
Apache-2.0
1,595,666,751,000
1,595,666,750,000
null
UTF-8
Lean
false
false
9,929
lean
import tuto_lib import data.int.parity /- Negations, proof by contradiction and contraposition. This file introduces the logical rules and tactics related to negation: exfalso, by_contradiction, contrapose, by_cases and push_neg. There is a special statement denoted by `false` which, by definition, has no proof. So `false` implies everything. Indeed `false → P` means any proof of `false` could be turned into a proof of P. This fact is known by its latin name "ex falso quod libet" (from false follows whatever you want). Hence Lean's tactic to invoke this is called `exfalso`. -/ example : false → 0 = 1 := begin intro h, exfalso, exact h, end /- The preceding example suggests that this definition of `false` isn't very useful. But actually it allows us to define the negation of a statement P as "P implies false" that we can read as "if P were true, we would get a contradiction". Lean denotes this by `¬ P`. One can prove that (¬ P) ↔ (P ↔ false). But in practice we directly use the definition of `¬ P`. -/ example {x : ℝ} : ¬ x < x := begin intro hyp, rw lt_iff_le_and_ne at hyp, cases hyp with hyp_inf hyp_non, clear hyp_inf, -- we won't use that one, so let's discard it change x = x → false at hyp_non, -- Lean doesn't need this psychological line apply hyp_non, refl, end open int -- 0045 example (n : ℤ) (h_pair : even n) (h_non_pair : ¬ even n) : 0 = 1 := begin exfalso, exact h_non_pair h_pair, end -- 0046 /- I give two solutions. The second is longer and misses the obvious idea of trying proof by negation to derive ¬P . -/ example (P Q : Prop) (h₁ : P ∨ Q) (h₂ : ¬ (P ∧ Q)) : ¬ P ↔ Q := begin split, { intro hnp, cases h₁ with hp hq, exfalso, exact hnp hp, exact hq, }, { intros hq hp, exact h₂ ⟨hp,hq⟩, } end example (P Q : Prop) (h₁ : P ∨ Q) (h₂ : ¬ (P ∧ Q)) : ¬ P ↔ Q := begin split, { intro hnp, cases h₁ with hp hq, { exfalso, exact hnp hp, }, { exact hq, } }, { intro hq, cases h₁ with hp hq, { exfalso, exact h₂ ⟨hp, hq⟩, }, { intro hp, exact h₂ ⟨hp, hq⟩, } } end /- The definition of negation easily implies that, for every statement P, P → ¬ ¬ P The excluded middle axiom, which asserts P ∨ ¬ P allows us to prove the converse implication. Together those two implications form the principle of double negation elimination. not_not {P : Prop} : (¬ ¬ P) ↔ P The implication `¬ ¬ P → P` is the basis for proofs by contradiction: in order to prove P, it suffices to prove ¬¬ P, ie `¬ P → false`. Of course there is no need to keep explaining all this. The tactic `by_contradiction Hyp` will transform any goal P into `false` and add Hyp : ¬ P to the local context. Let's return to a proof from the 5th file: uniqueness of limits for a sequence. This cannot be proved without using some version of the excluded middle axiom. We used it secretely in eq_of_abs_sub_le_all (x y : ℝ) : (∀ ε > 0, |x - y| ≤ ε) → x = y (we'll prove a variation on this lemma below). -/ example (u : ℕ → ℝ) (l l' : ℝ) : seq_limit u l → seq_limit u l' → l = l' := begin intros hl hl', by_contradiction H, change l ≠ l' at H, -- Lean does not need this line have ineg : |l-l'| > 0, exact abs_pos_of_ne_zero (sub_ne_zero_of_ne H), cases hl ( |l-l'|/4 ) (by linarith) with N hN, cases hl' ( |l-l'|/4 ) (by linarith) with N' hN', let N₀ := max N N', -- this is a new tactic, whose effect should be clear specialize hN N₀ (le_max_left _ _), specialize hN' N₀ (le_max_right _ _), have clef : |l-l'| < |l-l'|, calc |l - l'| = |(l-u N₀) + (u N₀ -l')| : by ring ... ≤ |l - u N₀| + |u N₀ - l'| : by apply abs_add ... = |u N₀ - l| + |u N₀ - l'| : by rw abs_sub ... < |l-l'| : by linarith, linarith, -- linarith can also find simple numerical contradictions end /- Another incarnation of the excluded middle axiom is the principle of contraposition: in order to prove P ⇒ Q, it suffices to prove non Q ⇒ non P. -/ -- Using a proof by contradiction, let's prove the contraposition principle -- 0047 example (P Q : Prop) (h : ¬ Q → ¬ P) : P → Q := begin intro hnqp, by_contradiction hq, exact h hq hnqp, end /- Again Lean doesn't need to be explain this principle. We can use the `contrapose` tactic. -/ example (P Q : Prop) (h : ¬ Q → ¬ P) : P → Q := begin contrapose, exact h, end /- In the next exercise, we'll use odd n : ∃ k, n = 2*k + 1 not_even_iff_odd : ¬ even n ↔ odd n, -/ -- 0048 /- Again two solutions. The second improves on the first by using rcases with rfl. -/ example (n : ℤ) : even (n^2) ↔ even n := begin split, { contrapose, simp [not_even_iff_odd], intro nodd, cases nodd with k hk, rw hk, use (2*k^2 + 2*k), ring, }, { intro neven, cases neven with k hk, rw hk, use (2*k^2), ring, } end example (n : ℤ) : even (n^2) ↔ even n := begin split, { contrapose, simp [not_even_iff_odd], rintro ⟨k, rfl⟩, use (2*k^2 + 2*k), ring, }, { rintro ⟨k, rfl⟩, use (2*k^2), ring, } end /- As a last step on our law of the excluded middle tour, let's notice that, especially in pure logic exercises, it can sometimes be useful to use the excluded middle axiom in its original form: classical.em : ∀ P, P ∨ ¬ P Instead of applying this lemma and then using the `cases` tactic, we have the shortcut by_cases h : P, combining both steps to create two proof branches: one assuming h : P, and the other assuming h : ¬ P For instance, let's prove a reformulation of this implication relation, which is sometimes used as a definition in other logical foundations, especially those based on truth tables (hence very strongly using excluded middle from the very beginning). -/ variables (P Q : Prop) example : (P → Q) ↔ (¬ P ∨ Q) := begin split, { intro h, by_cases hP : P, { right, exact h hP }, { left, exact hP } }, { intros h hP, cases h with hnP hQ, { exfalso, exact hnP hP }, { exact hQ } }, end -- 0049 example : ¬ (P ∧ Q) ↔ ¬ P ∨ ¬ Q := begin split, { intro hnpq, by_cases hp : P, { right, intro hq, exact hnpq ⟨hp, hq⟩, }, { exact or.inl hp, } }, { rintros hnpq ⟨hp, hq⟩, cases hnpq with hnp hnq, { exact hnp hp, }, { exact hnq hq, } } end /- It is crucial to understand negation of quantifiers. Let's do it by hand for a little while. In the first exercise, only the definition of negation is needed. -/ -- 0050 /- Two proofs. The second is simpler: it uses rintros, an anoymous constructor for the existential quantifier, and uses 'application' rather than specialize. -/ example (n : ℤ) : ¬ (∃ k, n = 2*k) ↔ ∀ k, n ≠ 2*k := begin split, { intros hnex k hnk, apply hnex, use k, exact hnk, }, { intros hallk hexk, cases hexk with k hk, specialize hallk k, exact hallk hk, } end example (n : ℤ) : ¬ (∃ k, n = 2*k) ↔ ∀ k, n ≠ 2*k := begin split, { intros hnex k hnk, -- apply hnex, --exact ⟨k, hnk⟩, exact hnex ⟨k, hnk⟩, }, { rintros hallk ⟨k,hnk⟩, exact hallk k hnk, } end /- Contrary to negation of the existential quantifier, negation of the universal quantifier requires excluded middle for the first implication. In order to prove this, we can use either * a double proof by contradiction * a contraposition, not_not : (¬ ¬ P) ↔ P) and a proof by contradiction. -/ def even_fun (f : ℝ → ℝ) := ∀ x, f (-x) = f x -- 0051 /- Two solutions. The second is shorter. -/ example (f : ℝ → ℝ) : ¬ even_fun f ↔ ∃ x, f (-x) ≠ f x := begin split, { intro hnef, by_contradiction H, unfold even_fun at hnef, apply hnef, intro x, by_contradiction K, apply H, use x, }, { intros hex hnef, cases hex with x hef, apply hef, exact hnef x, } end example (f : ℝ → ℝ) : ¬ even_fun f ↔ ∃ x, f (-x) ≠ f x := begin split, { intro hnef, by_contradiction H, apply hnef, intro x, by_contradiction K, apply H, use x, }, { rintros ⟨x,hnef⟩ hef, exact hnef (hef x), } end /- Of course we can't keep repeating the above proofs, especially the second one. So we use the `push_neg` tactic. -/ example : ¬ even_fun (λ x, 2*x) := begin unfold even_fun, -- Here unfolding is important because push_neg won't do it. push_neg, use 42, linarith, end -- 0052 example (f : ℝ → ℝ) : ¬ even_fun f ↔ ∃ x, f (-x) ≠ f x := begin unfold even_fun, push_neg, end def bounded_above (f : ℝ → ℝ) := ∃ M, ∀ x, f x ≤ M example : ¬ bounded_above (λ x, x) := begin unfold bounded_above, push_neg, intro M, use M + 1, linarith, end -- Let's contrapose -- 0053 /- The following is shorter than that in the model solution. -/ example (x : ℝ) : (∀ ε > 0, x ≤ ε) → x ≤ 0 := begin contrapose, intros hxneg hε, specialize hε (x/2) (by linarith), linarith, end /- The "contrapose, push_neg" combo is so common that we can abreviate it to `contrapose!` Let's use this trick, together with: eq_or_lt_of_le : a ≤ b → a = b ∨ a < b -/ -- 0054 example (f : ℝ → ℝ) : (∀ x y, x < y → f x < f y) ↔ (∀ x y, (x ≤ y ↔ f x ≤ f y)) := begin split, { intros h x y, split , { intro hxy, cases (eq_or_lt_of_le hxy) with h₁ h₂, { rw h₁, }, { specialize h x y h₂, linarith, } }, { contrapose!, exact h y x, } }, { intros h x y, contrapose!, exact (h y x).mpr, } end
b62949f9f8010990d3beafd43690e18481ebef41
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/compiler/t4.lean
10785ed045bc0e07db0bd6ba20dd2fa2e19939ba
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
3,362
lean
/- Benchmark for new code generator -/ inductive Expr | Val : Int → Expr | Var : String → Expr | Add : Expr → Expr → Expr | Mul : Expr → Expr → Expr | Pow : Expr → Expr → Expr | Ln : Expr → Expr open Expr def Expr.toString : Expr → String | (Val n) := toString n | (Var x) := x | (Add f g) := "(" ++ Expr.toString f ++ " + " ++ Expr.toString g ++ ")" | (Mul f g) := "(" ++ Expr.toString f ++ " * " ++ Expr.toString g ++ ")" | (Pow f g) := "(" ++ Expr.toString f ++ " ^ " ++ Expr.toString g ++ ")" | (Ln f) := "ln(" ++ Expr.toString f ++ ")" instance : HasToString Expr := ⟨Expr.toString⟩ partial def pown : Int → Int → Int | a 0 := 1 | a 1 := a | a n := let b := pown a (n / 2) in b * b * (if n % 2 = 0 then 1 else a) partial def addAux : Expr → Expr → Expr | (Val n) (Val m) := Val (n + m) | (Val 0) f := f | f (Val 0) := f | f (Val n) := addAux (Val n) f | (Val n) (Add (Val m) f) := addAux (Val (n+m)) f | f (Add (Val n) g) := addAux (Val n) (addAux f g) | (Add f g) h := addAux f (addAux g h) | f g := Add f g def add (a b : Expr) : Expr := -- dbgTrace (">> add (" ++ toString a ++ ", " ++ toString b ++ ")") $ fun _ => addAux a b -- set_option trace.compiler.borrowed_inference true partial def mulAux : Expr → Expr → Expr | (Val n) (Val m) := Val (n*m) | (Val 0) _ := Val 0 | _ (Val 0) := Val 0 | (Val 1) f := f | f (Val 1) := f | f (Val n) := mulAux (Val n) f | (Val n) (Mul (Val m) f) := mulAux (Val (n*m)) f | f (Mul (Val n) g) := mulAux (Val n) (mulAux f g) | (Mul f g) h := mulAux f (mulAux g h) | f g := Mul f g def mul (a b : Expr) : Expr := -- dbgTrace (">> mul (" ++ toString a ++ ", " ++ toString b ++ ")") $ fun _ => mulAux a b def pow : Expr → Expr → Expr | (Val m) (Val n) := Val (pown m n) | _ (Val 0) := Val 1 | f (Val 1) := f | (Val 0) _ := Val 0 | f g := Pow f g def ln : Expr → Expr | (Val 1) := Val 0 | f := Ln f def d (x : String) : Expr → Expr | (Val _) := Val 0 | (Var y) := if x = y then Val 1 else Val 0 | (Add f g) := add (d f) (d g) | (Mul f g) := -- dbgTrace (">> d (" ++ toString f ++ ", " ++ toString g ++ ")") $ fun _ => add (mul f (d g)) (mul g (d f)) | (Pow f g) := mul (pow f g) (add (mul (mul g (d f)) (pow f (Val (-1)))) (mul (ln f) (d g))) | (Ln f) := mul (d f) (pow f (Val (-1))) def count : Expr → Nat | (Val _) := 1 | (Var _) := 1 | (Add f g) := count f + count g | (Mul f g) := count f + count g | (Pow f g) := count f + count g | (Ln f) := count f def nestAux (s : Nat) (f : Nat → Expr → IO Expr) : Nat → Expr → IO Expr | 0 x := pure x | m@(n+1) x := f (s - m) x >>= nestAux n def nest (f : Nat → Expr → IO Expr) (n : Nat) (e : Expr) : IO Expr := nestAux n f n e def deriv (i : Nat) (f : Expr) : IO Expr := do let d := d "x" f; IO.println (toString (i+1) ++ " count: " ++ (toString $ count d)); IO.println (toString d); pure d def main (xs : List String) : IO UInt32 := do let x := Var "x"; let f := add x (mul x (mul x (add x x))); IO.println f; nest deriv 3 f; pure 0 -- setOption profiler True -- #eval main []
e0e7f50ed379be3672aa0ad8df6659c1c90c8fd8
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/group_theory/submonoid/membership.lean
b08568d2c533f08eaf7f4f0a876f2429e15bccef
[ "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
9,534
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov -/ import group_theory.submonoid.operations import algebra.big_operators.basic import algebra.free_monoid /-! # Submonoids: membership criteria In this file we prove various facts about membership in a submonoid: * `list_prod_mem`, `multiset_prod_mem`, `prod_mem`: if each element of a collection belongs to a multiplicative submonoid, then so does their product; * `list_sum_mem`, `multiset_sum_mem`, `sum_mem`: if each element of a collection belongs to an additive submonoid, then so does their sum; * `pow_mem`, `nsmul_mem`: if `x ∈ S` where `S` is a multiplicative (resp., additive) submonoid and `n` is a natural number, then `x^n` (resp., `n •ℕ x`) belongs to `S`; * `mem_supr_of_directed`, `coe_supr_of_directed`, `mem_Sup_of_directed_on`, `coe_Sup_of_directed_on`: the supremum of a directed collection of submonoid is their union. * `sup_eq_range`, `mem_sup`: supremum of two submonoids `S`, `T` of a commutative monoid is the set of products; * `closure_singleton_eq`, `mem_closure_singleton`: the multiplicative (resp., additive) closure of `{x}` consists of powers (resp., natural multiples) of `x`. ## Tags submonoid, submonoids -/ open_locale big_operators variables {M : Type*} [monoid M] {s : set M} variables {A : Type*} [add_monoid A] {t : set A} namespace submonoid variables (S : submonoid M) /-- Product of a list of elements in a submonoid is in the submonoid. -/ @[to_additive "Sum of a list of elements in an `add_submonoid` is in the `add_submonoid`."] lemma list_prod_mem : ∀ {l : list M}, (∀x ∈ l, x ∈ S) → l.prod ∈ S | [] h := S.one_mem | (a::l) h := suffices a * l.prod ∈ S, by rwa [list.prod_cons], have a ∈ S ∧ (∀ x ∈ l, x ∈ S), from list.forall_mem_cons.1 h, S.mul_mem this.1 (list_prod_mem this.2) /-- Product of a multiset of elements in a submonoid of a `comm_monoid` is in the submonoid. -/ @[to_additive "Sum of a multiset of elements in an `add_submonoid` of an `add_comm_monoid` is in the `add_submonoid`."] lemma multiset_prod_mem {M} [comm_monoid M] (S : submonoid M) (m : multiset M) : (∀a ∈ m, a ∈ S) → m.prod ∈ S := begin refine quotient.induction_on m (assume l hl, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod], exact S.list_prod_mem hl end /-- Product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is in the submonoid. -/ @[to_additive "Sum of elements in an `add_submonoid` of an `add_comm_monoid` indexed by a `finset` is in the `add_submonoid`."] lemma prod_mem {M : Type*} [comm_monoid M] (S : submonoid M) {ι : Type*} {t : finset ι} {f : ι → M} (h : ∀c ∈ t, f c ∈ S) : ∏ c in t, f c ∈ S := S.multiset_prod_mem (t.1.map f) $ λ x hx, let ⟨i, hi, hix⟩ := multiset.mem_map.1 hx in hix ▸ h i hi lemma pow_mem {x : M} (hx : x ∈ S) : ∀ n:ℕ, x^n ∈ S | 0 := S.one_mem | (n+1) := S.mul_mem hx (pow_mem n) open set @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S) {x : M} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr S i) hi⟩, suffices : x ∈ closure (⋃ i, (S i : set M)) → ∃ i, x ∈ S i, by simpa only [closure_Union, closure_eq (S _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _), { exact hι.elim (λ i, ⟨i, (S i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hS i j with ⟨k, hki, hkj⟩, exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ } end @[to_additive] lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → submonoid M} (hS : directed (≤) S) : ((⨆ i, S i : submonoid M) : set M) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : M} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end @[to_additive] lemma coe_Sup_of_directed_on {S : set (submonoid M)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set M) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] @[to_additive] lemma mem_sup_left {S T : submonoid M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : submonoid M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mem_supr_of_mem {ι : Type*} {S : ι → submonoid M} (i : ι) : ∀ {x : M}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (submonoid M)} {s : submonoid M} (hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs end submonoid namespace free_monoid variables {α : Type*} open submonoid @[to_additive] theorem closure_range_of : closure (set.range $ @of α) = ⊤ := eq_top_iff.2 $ λ x hx, free_monoid.rec_on x (one_mem _) $ λ x xs hxs, mul_mem _ (subset_closure $ set.mem_range_self _) hxs end free_monoid namespace submonoid variables {N : Type*} [monoid N] open monoid_hom lemma closure_singleton_eq (x : M) : closure ({x} : set M) = (powers_hom M x).mrange := closure_eq_of_le (set.singleton_subset_iff.2 ⟨multiplicative.of_add 1, trivial, pow_one x⟩) $ λ x ⟨n, _, hn⟩, hn ▸ pow_mem _ (subset_closure $ set.mem_singleton _) _ /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ lemma mem_closure_singleton {x y : M} : y ∈ closure ({x} : set M) ↔ ∃ n:ℕ, x^n=y := by rw [closure_singleton_eq, mem_mrange]; refl lemma mem_closure_singleton_self {y : M} : y ∈ closure ({y} : set M) := mem_closure_singleton.2 ⟨1, pow_one y⟩ @[to_additive] lemma closure_eq_mrange (s : set M) : closure s = (free_monoid.lift (coe : s → M)).mrange := by rw [mrange, ← free_monoid.closure_range_of, map_mclosure, ← set.range_comp, free_monoid.lift_comp_of, subtype.range_coe] @[to_additive] lemma exists_list_of_mem_closure {s : set M} {x : M} (hx : x ∈ closure s) : ∃ (l : list M) (hl : ∀ y ∈ l, y ∈ s), l.prod = x := begin rw [closure_eq_mrange, mem_mrange] at hx, rcases hx with ⟨l, hx⟩, exact ⟨list.map coe l, λ y hy, let ⟨z, hz, hy⟩ := list.mem_map.1 hy in hy ▸ z.2, hx⟩ end /-- The submonoid generated by an element. -/ def powers (n : N) : submonoid N := submonoid.copy (powers_hom N n).mrange (set.range ((^) n : ℕ → N)) $ set.ext (λ n, exists_congr $ λ i, by simp; refl) @[simp] lemma mem_powers (n : N) : n ∈ powers n := ⟨1, pow_one _⟩ lemma powers_eq_closure (n : N) : powers n = closure {n} := by { ext, exact mem_closure_singleton.symm } lemma powers_subset {n : N} {P : submonoid N} (h : n ∈ P) : powers n ≤ P := λ x hx, match x, hx with _, ⟨i, rfl⟩ := P.pow_mem h i end end submonoid namespace submonoid variables {N : Type*} [comm_monoid N] open monoid_hom @[to_additive] lemma sup_eq_range (s t : submonoid N) : s ⊔ t = (s.subtype.coprod t.subtype).mrange := by rw [mrange, ← mrange_inl_sup_mrange_inr, map_sup, map_mrange, coprod_comp_inl, map_mrange, coprod_comp_inr, range_subtype, range_subtype] @[to_additive] lemma mem_sup {s t : submonoid N} {x : N} : x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x := by simp only [sup_eq_range, mem_mrange, coprod_apply, prod.exists, submonoid.exists, coe_subtype, subtype.coe_mk] end submonoid namespace add_submonoid open set lemma nsmul_mem (S : add_submonoid A) {x : A} (hx : x ∈ S) : ∀ n : ℕ, n •ℕ x ∈ S | 0 := S.zero_mem | (n+1) := S.add_mem hx (nsmul_mem n) lemma closure_singleton_eq (x : A) : closure ({x} : set A) = (multiples_hom A x).mrange := closure_eq_of_le (set.singleton_subset_iff.2 ⟨1, trivial, one_nsmul x⟩) $ λ x ⟨n, _, hn⟩, hn ▸ nsmul_mem _ (subset_closure $ set.mem_singleton _) _ /-- The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n:ℕ, n •ℕ x = y := by rw [closure_singleton_eq, add_monoid_hom.mem_mrange]; refl /-- The additive submonoid generated by an element. -/ def multiples (x : A) : add_submonoid A := add_submonoid.copy (multiples_hom A x).mrange (set.range (λ i, nsmul i x : ℕ → A)) $ set.ext (λ n, exists_congr $ λ i, by simp; refl) @[simp] lemma mem_multiples (x : A) : x ∈ multiples x := ⟨1, one_nsmul _⟩ lemma multiples_eq_closure (x : A) : multiples x = closure {x} := by { ext, exact mem_closure_singleton.symm } lemma multiples_subset {x : A} {P : add_submonoid A} (h : x ∈ P) : multiples x ≤ P := λ x hx, match x, hx with _, ⟨i, rfl⟩ := P.nsmul_mem h i end attribute [to_additive add_submonoid.multiples] submonoid.powers attribute [to_additive add_submonoid.mem_multiples] submonoid.mem_powers attribute [to_additive add_submonoid.multiples_eq_closure] submonoid.powers_eq_closure attribute [to_additive add_submonoid.multiples_subset] submonoid.powers_subset end add_submonoid
92f7b762a7272238748d056f94676f5ca74bc99a
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/ho.lean
8daa9d9e385d7ec96d8272cb139974d904c31bce
[ "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
207
lean
import data.nat inductive star : Type₁ := z : star, s : (nat → star) → star check @star.rec check @star.cases_on example (f : nat → star) : ¬ star.z = star.s f := assume H, star.no_confusion H
743d1e510a6792a0cab37a154397b39555bd3477
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/logic/unique.lean
9f1b2ae34b3b4099a3b98483cd0da0209ddde272
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
5,099
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 tactic.basic import logic.is_empty /-! # Types with a unique term In this file we define a typeclass `unique`, which expresses that a type has a unique term. In other words, a type that is `inhabited` and a `subsingleton`. ## Main declaration * `unique`: a typeclass that expresses that a type has a unique term. ## Main statements * `unique.mk'`: an inhabited subsingleton type is `unique`. This can not be an instance because it would lead to loops in typeclass inference. * `function.surjective.unique`: if the domain of a surjective function is `unique`, then its codomain is `unique` as well. * `function.injective.subsingleton`: if the codomain of an injective function is `subsingleton`, then its domain is `subsingleton` as well. * `function.injective.unique`: if the codomain of an injective function is `subsingleton` and its domain is `inhabited`, then its domain is `unique`. ## Implementation details The typeclass `unique α` is implemented as a type, rather than a `Prop`-valued predicate, for good definitional properties of the default term. -/ universes u v w variables {α : Sort u} {β : Sort v} {γ : Sort w} /-- `unique α` expresses that `α` is a type with a unique term `default α`. This is implemented as a type, rather than a `Prop`-valued predicate, for good definitional properties of the default term. -/ @[ext] structure unique (α : Sort u) extends inhabited α := (uniq : ∀ a:α, a = default) attribute [class] unique instance punit.unique : unique punit.{u} := { default := punit.star, uniq := λ x, punit_eq x _ } /-- Every provable proposition is unique, as all proofs are equal. -/ def unique_prop {p : Prop} (h : p) : unique p := { default := h, uniq := λ x, rfl } instance : unique true := unique_prop trivial lemma fin.eq_zero : ∀ n : fin 1, n = 0 | ⟨n, hn⟩ := fin.eq_of_veq (nat.eq_zero_of_le_zero (nat.le_of_lt_succ hn)) instance {n : ℕ} : inhabited (fin n.succ) := ⟨0⟩ instance inhabited_fin_one_add (n : ℕ) : inhabited (fin (1 + n)) := ⟨⟨0, nat.zero_lt_one_add n⟩⟩ @[simp] lemma fin.default_eq_zero (n : ℕ) : default (fin n.succ) = 0 := rfl instance fin.unique : unique (fin 1) := { uniq := fin.eq_zero, .. fin.inhabited } namespace unique open function section variables [unique α] @[priority 100] -- see Note [lower instance priority] instance : inhabited α := to_inhabited ‹unique α› lemma eq_default (a : α) : a = default α := uniq _ a lemma default_eq (a : α) : default α = a := (uniq _ a).symm @[priority 100] -- see Note [lower instance priority] instance : subsingleton α := subsingleton_of_forall_eq _ eq_default lemma forall_iff {p : α → Prop} : (∀ a, p a) ↔ p (default α) := ⟨λ h, h _, λ h x, by rwa [unique.eq_default x]⟩ lemma exists_iff {p : α → Prop} : Exists p ↔ p (default α) := ⟨λ ⟨a, ha⟩, eq_default a ▸ ha, exists.intro (default α)⟩ end @[ext] protected lemma subsingleton_unique' : ∀ (h₁ h₂ : unique α), h₁ = h₂ | ⟨⟨x⟩, h⟩ ⟨⟨y⟩, _⟩ := by congr; rw [h x, h y] instance subsingleton_unique : subsingleton (unique α) := ⟨unique.subsingleton_unique'⟩ /-- Construct `unique` from `inhabited` and `subsingleton`. Making this an instance would create a loop in the class inheritance graph. -/ def mk' (α : Sort u) [h₁ : inhabited α] [subsingleton α] : unique α := { uniq := λ x, subsingleton.elim _ _, .. h₁ } end unique @[simp] lemma pi.default_def {β : Π a : α, Sort v} [Π a, inhabited (β a)] : default (Π a, β a) = λ a, default (β a) := rfl lemma pi.default_apply {β : Π a : α, Sort v} [Π a, inhabited (β a)] (a : α) : default (Π a, β a) a = default (β a) := rfl instance pi.unique {β : Π a : α, Sort v} [Π a, unique (β a)] : unique (Π a, β a) := { uniq := λ f, funext $ λ x, unique.eq_default _, .. pi.inhabited α } /-- There is a unique function on an empty domain. -/ instance pi.unique_of_is_empty [is_empty α] (β : Π a : α, Sort v) : unique (Π a, β a) := { default := is_empty_elim, uniq := λ f, funext is_empty_elim } namespace function variable {f : α → β} /-- If the domain of a surjective function is a singleton, then the codomain is a singleton as well. -/ protected def surjective.unique (hf : surjective f) [unique α] : unique β := { default := f (default _), uniq := λ b, let ⟨a, ha⟩ := hf b in ha ▸ congr_arg f (unique.eq_default _) } /-- If the codomain of an injective function is a subsingleton, then the domain is a subsingleton as well. -/ protected lemma injective.subsingleton (hf : injective f) [subsingleton β] : subsingleton α := ⟨λ x y, hf $ subsingleton.elim _ _⟩ /-- If `α` is inhabited and admits an injective map to a subsingleton type, then `α` is `unique`. -/ protected def injective.unique [inhabited α] [subsingleton β] (hf : injective f) : unique α := @unique.mk' _ _ hf.subsingleton end function
b5afe14a3c52e26bedf56d345da38614f5aca631
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/kcomp.lean
d86373cfffe6c0d5faab9e230810548690521e69
[ "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
973
lean
set_option pp.notation false constant A : Type constants a b : A constant P : A → Type constant H₁ : a = a constant H₂ : P a constant H₃ : a = b constant f {A : Type} (a : A) : a = a #reduce (eq.rec H₂ (@f A a) : P a) #reduce (eq.rec H₂ H₁ : P a) #reduce (eq.rec H₂ H₃ : P b) #reduce (eq.rec H₂ (@eq.refl A a) : P a) -- eval λ (A : Type) (a b : A) (H₁ : a = a) (P : A → Prop) (H₂ : P a) (H₃ : a = a) (c : A), eq.rec (eq.rec H₂ H₁) H₃ #check @eq.rec A a P H₂ a #check λ H : a = a, H₂ inductive to_type {B : Type} : B → Type | mk : Π (b : B), to_type b noncomputable definition tst1 : to_type (λ H : a = a, H₂) := to_type.mk (@eq.rec A a P H₂ a) #check to_type.mk(λ H : a = a, H₂) #check to_type.mk(@eq.rec A a P H₂ a) #check to_type.mk(λ H : a = a, H₂) = to_type.mk(@eq.rec A a P H₂ a) -- #check to_type.mk(eq.rec H₂ H₁) = to_type.mk(H₂) -- #check to_type.mk(eq.rec H₂ (f a)) = to_type.mk(H₂)
132a73f3a82d0fb3db9d82c30028bfeee5c3bab1
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/algebraic_geometry/locally_ringed_space.lean
a48931df75a9cd01a395314078e8d6e6b3fc81a6
[ "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
4,881
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebraic_geometry.sheafed_space import algebra.category.CommRing.limits import algebra.category.CommRing.colimits import algebraic_geometry.stalks import ring_theory.ideal.basic /-! # The category of locally ringed spaces We define (bundled) locally ringed spaces (as `SheafedSpace CommRing` along with the fact that the stalks are local rings), and morphisms between these (morphisms in `SheafedSpace` with `is_local_ring_hom` on the stalk maps). ## Future work * Define the restriction along an open embedding -/ universes v u open category_theory open Top open topological_space open opposite open category_theory.category category_theory.functor namespace algebraic_geometry /-- A `LocallyRingedSpace` is a topological space equipped with a sheaf of commutative rings such that all the stalks are local rings. A morphism of locally ringed spaces is a morphism of ringed spaces such that the morphims induced on stalks are local ring homomorphisms. -/ @[nolint has_inhabited_instance] structure LocallyRingedSpace extends SheafedSpace CommRing := (local_ring : ∀ x, local_ring (presheaf.stalk x)) attribute [instance] LocallyRingedSpace.local_ring namespace LocallyRingedSpace variables (X : LocallyRingedSpace) /-- The underlying topological space of a locally ringed space. -/ def to_Top : Top := X.1.carrier instance : has_coe_to_sort LocallyRingedSpace := { S := Type u, coe := λ X : LocallyRingedSpace, (X.to_Top : Type u), } -- PROJECT: how about a typeclass "has_structure_sheaf" to mediate the 𝒪 notation, rather -- than defining it over and over for PresheafedSpace, LRS, Scheme, etc. /-- The structure sheaf of a locally ringed space. -/ def 𝒪 : sheaf CommRing X.to_Top := X.to_SheafedSpace.sheaf /-- A morphism of locally ringed spaces is a morphism of ringed spaces such that the morphims induced on stalks are local ring homomorphisms. -/ def hom (X Y : LocallyRingedSpace) : Type* := { f : X.to_SheafedSpace ⟶ Y.to_SheafedSpace // ∀ x, is_local_ring_hom (PresheafedSpace.stalk_map f x) } instance : has_hom LocallyRingedSpace := ⟨hom⟩ @[ext] lemma hom_ext {X Y : LocallyRingedSpace} (f g : hom X Y) (w : f.1 = g.1) : f = g := subtype.eq w /-- The stalk of a locally ringed space, just as a `CommRing`. -/ -- TODO perhaps we should make a bundled `LocalRing` and return one here? -- TODO define `sheaf.stalk` so we can write `X.𝒪.stalk` here? def stalk (X : LocallyRingedSpace) (x : X) : CommRing := X.presheaf.stalk x /-- A morphism of locally ringed spaces `f : X ⟶ Y` induces a local ring homomorphism from `Y.stalk (f x)` to `X.stalk x` for any `x : X`. -/ def stalk_map {X Y : LocallyRingedSpace} (f : X ⟶ Y) (x : X) : Y.stalk (f.1.1 x) ⟶ X.stalk x := PresheafedSpace.stalk_map f.1 x instance {X Y : LocallyRingedSpace} (f : X ⟶ Y) (x : X) : is_local_ring_hom (stalk_map f x) := f.2 x /-- The identity morphism on a locally ringed space. -/ @[simps] def id (X : LocallyRingedSpace) : hom X X := ⟨𝟙 _, λ x, by { erw PresheafedSpace.stalk_map.id, apply is_local_ring_hom_id, }⟩ instance (X : LocallyRingedSpace) : inhabited (hom X X) := ⟨id X⟩ /-- Composition of morphisms of locally ringed spaces. -/ @[simps] def comp {X Y Z : LocallyRingedSpace} (f : hom X Y) (g : hom Y Z) : hom X Z := ⟨f.val ≫ g.val, λ x, begin erw PresheafedSpace.stalk_map.comp, exact @is_local_ring_hom_comp _ _ _ _ _ _ _ _ (f.2 _) (g.2 _), end⟩ /-- The category of locally ringed spaces. -/ instance : category LocallyRingedSpace := { hom := hom, id := id, comp := λ X Y Z f g, comp f g, comp_id' := by { intros, ext1, simp, }, id_comp' := by { intros, ext1, simp, }, assoc' := by { intros, ext1, simp, }, }. /-- The forgetful functor from `LocallyRingedSpace` to `SheafedSpace CommRing`. -/ def forget_to_SheafedSpace : LocallyRingedSpace ⥤ SheafedSpace CommRing := { obj := λ X, X.to_SheafedSpace, map := λ X Y f, f.1, } instance : faithful forget_to_SheafedSpace := {} -- PROJECT: once we have `PresheafedSpace.restrict_stalk_iso` -- (that restriction doesn't change stalks) we can uncomment this. /- def restrict {U : Top} (X : LocallyRingedSpace) (f : U ⟶ X.to_Top) (h : open_embedding f) : LocallyRingedSpace := { local_ring := begin intro x, dsimp at *, -- We show that the stalk of the restriction is isomorphic to the original stalk, have := X.to_SheafedSpace.to_PresheafedSpace.restrict_stalk_iso f h x, -- and then transfer `local_ring` across the ring equivalence. apply (this.CommRing_iso_to_ring_equiv).local_ring, -- import data.equiv.transfer_instance apply X.local_ring, end, .. X.to_SheafedSpace.restrict _ f h } -/ end LocallyRingedSpace end algebraic_geometry
f88783f25dd67fc8f7d12d874067d704bea786a9
dc253be9829b840f15d96d986e0c13520b085033
/algebra/left_module.hlean
8bbb2246fc56678325ab6e1bc472d1517d19da68
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
26,663
hlean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Floris van Doorn Modules prod vector spaces over a ring. (We use "left_module," which is more precise, because "module" is a keyword.) -/ import algebra.field ..move_to_lib .exactness algebra.group_power open is_trunc pointed function sigma eq algebra prod is_equiv equiv group structure has_scalar [class] (F V : Type) := (smul : F → V → V) infixl ` • `:73 := has_scalar.smul /- modules over a ring -/ namespace left_module structure left_module (R M : Type) [ringR : ring R] extends has_scalar R M, ab_group M renaming mul → add mul_assoc → add_assoc one → zero one_mul → zero_add mul_one → add_zero inv → neg mul_left_inv → add_left_inv mul_comm → add_comm := (smul_left_distrib : Π (r : R) (x y : M), smul r (add x y) = (add (smul r x) (smul r y))) (smul_right_distrib : Π (r s : R) (x : M), smul (ring.add _ r s) x = (add (smul r x) (smul s x))) (mul_smul : Π r s x, smul (mul r s) x = smul r (smul s x)) (one_smul : Π x, smul one x = x) /- we make it a class now (and not as part of the structure) to avoid left_module.to_ab_group to be an instance -/ attribute left_module [class] definition add_ab_group_of_left_module [reducible] [trans_instance] (R M : Type) [K : ring R] [H : left_module R M] : add_ab_group M := @left_module.to_ab_group R M K H definition has_scalar_of_left_module [reducible] [trans_instance] (R M : Type) [K : ring R] [H : left_module R M] : has_scalar R M := @left_module.to_has_scalar R M K H section left_module variables {R M : Type} variable [ringR : ring R] variable [moduleRM : left_module R M] include ringR moduleRM -- Note: the anonymous include does not work in the propositions below. proposition smul_left_distrib (a : R) (u v : M) : a • (u + v) = a • u + a • v := !left_module.smul_left_distrib proposition smul_right_distrib (a b : R) (u : M) : (a + b) • u = a • u + b • u := !left_module.smul_right_distrib proposition mul_smul (a : R) (b : R) (u : M) : (a * b) • u = a • (b • u) := !left_module.mul_smul proposition one_smul (u : M) : (1 : R) • u = u := !left_module.one_smul proposition zero_smul (u : M) : (0 : R) • u = 0 := have (0 : R) • u + 0 • u = 0 • u + 0, by rewrite [-smul_right_distrib, *add_zero], !add.left_cancel this proposition smul_zero (a : R) : a • (0 : M) = 0 := have a • (0:M) + a • 0 = a • 0 + 0, by rewrite [-smul_left_distrib, *add_zero], !add.left_cancel this proposition neg_smul (a : R) (u : M) : (-a) • u = - (a • u) := eq_neg_of_add_eq_zero (by rewrite [-smul_right_distrib, add.left_inv, zero_smul]) proposition neg_one_smul (u : M) : -(1 : R) • u = -u := by rewrite [neg_smul, one_smul] proposition smul_neg (a : R) (u : M) : a • (-u) = -(a • u) := by rewrite [-neg_one_smul, -mul_smul, mul_neg_one_eq_neg, neg_smul] proposition smul_sub_left_distrib (a : R) (u v : M) : a • (u - v) = a • u - a • v := by rewrite [sub_eq_add_neg, smul_left_distrib, smul_neg] proposition sub_smul_right_distrib (a b : R) (v : M) : (a - b) • v = a • v - b • v := by rewrite [sub_eq_add_neg, smul_right_distrib, neg_smul] end left_module /- vector spaces -/ structure vector_space [class] (F V : Type) [fieldF : field F] extends left_module F V /- homomorphisms -/ definition is_smul_hom [class] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] (f : M₁ → M₂) : Type := ∀ r : R, ∀ a : M₁, f (r • a) = r • f a definition is_prop_is_smul_hom [instance] (R : Type) {M₁ M₂ : Type} [is_set M₂] [has_scalar R M₁] [has_scalar R M₂] (f : M₁ → M₂) : is_prop (is_smul_hom R f) := begin unfold is_smul_hom, apply _ end definition respect_smul (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] (f : M₁ → M₂) [H : is_smul_hom R f] : ∀ r : R, ∀ a : M₁, f (r • a) = r • f a := H definition is_module_hom [class] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) := is_add_hom f × is_smul_hom R f definition is_add_hom_of_is_module_hom [instance] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) [H : is_module_hom R f] : is_add_hom f := prod.pr1 H definition is_smul_hom_of_is_module_hom [instance] {R : Type} {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) [H : is_module_hom R f] : is_smul_hom R f := prod.pr2 H -- Why do we have to give the instance explicitly? definition is_prop_is_module_hom [instance] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) : is_prop (is_module_hom R f) := have h₁ : is_prop (is_add_hom f), from is_prop_is_add_hom f, begin unfold is_module_hom, apply _ end section module_hom variables {R : Type} {M₁ M₂ M₃ : Type} variables [has_scalar R M₁] [has_scalar R M₂] [has_scalar R M₃] variables [add_group M₁] [add_group M₂] [add_group M₃] variables (g : M₂ → M₃) (f : M₁ → M₂) [is_module_hom R g] [is_module_hom R f] proposition is_module_hom_id : is_module_hom R (@id M₁) := pair (λ a₁ a₂, rfl) (λ r a, rfl) proposition is_module_hom_comp : is_module_hom R (g ∘ f) := pair (take a₁ a₂, begin esimp, rewrite [respect_add f, respect_add g] end) (take r a, by esimp; rewrite [respect_smul R f, respect_smul R g]) proposition respect_smul_add_smul (a b : R) (u v : M₁) : f (a • u + b • v) = a • f u + b • f v := by rewrite [respect_add f, +respect_smul R f] end module_hom section hom_constant variables {R : Type} {M₁ M₂ : Type} variables [ring R] [has_scalar R M₁] [add_group M₁] [left_module R M₂] proposition is_module_hom_constant : is_module_hom R (const M₁ (0 : M₂)) := (λm₁ m₂, !add_zero⁻¹, λr m, (smul_zero r)⁻¹ᵖ) end hom_constant structure LeftModule (R : Ring) := (carrier : Type) (struct : left_module R carrier) attribute LeftModule.struct [instance] section local attribute LeftModule.carrier [coercion] definition AddAbGroup_of_LeftModule [coercion] {R : Ring} (M : LeftModule R) : AddAbGroup := AddAbGroup.mk M (LeftModule.struct M) end definition LeftModule.struct2 [instance] {R : Ring} (M : LeftModule R) : left_module R M := LeftModule.struct M -- definition LeftModule.struct3 [instance] {R : Ring} (M : LeftModule R) : -- left_module R (AddAbGroup_of_LeftModule M) := -- _ definition pointed_LeftModule_carrier [instance] {R : Ring} (M : LeftModule R) : pointed (LeftModule.carrier M) := pointed.mk zero definition pSet_of_LeftModule {R : Ring} (M : LeftModule R) : Set* := pSet.mk' (LeftModule.carrier M) definition left_module_AddAbGroup_of_LeftModule [instance] {R : Ring} (M : LeftModule R) : left_module R (AddAbGroup_of_LeftModule M) := LeftModule.struct M definition left_module_AddAbGroup_of_LeftModule2 [instance] {R : Ring} (M : LeftModule R) : left_module R (Group_of_AbGroup (AddAbGroup_of_LeftModule M)) := LeftModule.struct M definition left_module_of_ab_group {G : Type} [gG : add_ab_group G] {R : Type} [ring R] (smul : R → G → G) (h1 : Π (r : R) (x y : G), smul r (x + y) = (smul r x + smul r y)) (h2 : Π (r s : R) (x : G), smul (r + s) x = (smul r x + smul s x)) (h3 : Π r s x, smul (r * s) x = smul r (smul s x)) (h4 : Π x, smul 1 x = x) : left_module R G := left_module.mk smul _ add add.assoc 0 zero_add add_zero neg add.left_inv add.comm h1 h2 h3 h4 definition LeftModule_of_AddAbGroup {R : Ring} (G : AddAbGroup) (smul : R → G → G) (h1 h2 h3 h4) : LeftModule R := LeftModule.mk G (left_module_of_ab_group smul h1 h2 h3 h4) open unit definition trivial_LeftModule [constructor] (R : Ring) : LeftModule R := LeftModule_of_AddAbGroup trivial_ab_group (λr u, star) (λr u₁ u₂, idp) (λr₁ r₂ u, idp) (λr₁ r₂ u, idp) unit.eta section variables {R : Ring} {M M₁ M₂ M₃ : LeftModule R} definition smul_homomorphism [constructor] (M : LeftModule R) (r : R) : M →a M := add_homomorphism.mk (λg, r • g) (smul_left_distrib r) proposition to_smul_left_distrib (a : R) (u v : M) : a • (u + v) = a • u + a • v := !smul_left_distrib proposition to_smul_right_distrib (a b : R) (u : M) : (a + b) • u = a • u + b • u := !smul_right_distrib proposition to_mul_smul (a : R) (b : R) (u : M) : (a * b) • u = a • (b • u) := !mul_smul proposition to_one_smul (u : M) : (1 : R) • u = u := !one_smul structure homomorphism (M₁ M₂ : LeftModule R) : Type := (fn : LeftModule.carrier M₁ → LeftModule.carrier M₂) (p : is_module_hom R fn) infix ` →lm `:55 := homomorphism definition homomorphism_fn [unfold 4] [coercion] := @homomorphism.fn definition is_module_hom_of_homomorphism [unfold 4] [instance] [priority 900] {M₁ M₂ : LeftModule R} (φ : M₁ →lm M₂) : is_module_hom R φ := homomorphism.p φ section variable (φ : M₁ →lm M₂) definition to_respect_add (x y : M₁) : φ (x + y) = φ x + φ y := respect_add φ x y definition to_respect_smul (a : R) (x : M₁) : φ (a • x) = a • (φ x) := respect_smul R φ a x definition to_respect_sub (x y : M₁) : φ (x - y) = φ x - φ y := respect_sub φ x y definition is_embedding_of_homomorphism /- φ -/ (H : Π{x}, φ x = 0 → x = 0) : is_embedding φ := is_embedding_of_is_add_hom φ @H variables (M₁ M₂) definition is_set_homomorphism [instance] : is_set (M₁ →lm M₂) := begin have H : M₁ →lm M₂ ≃ Σ(f : LeftModule.carrier M₁ → LeftModule.carrier M₂), is_module_hom (Ring.carrier R) f, begin fapply equiv.MK, { intro φ, induction φ, constructor, exact p}, { intro v, induction v with f H, constructor, exact H}, { intro v, induction v, reflexivity}, { intro φ, induction φ, reflexivity} end, have ∀ f : LeftModule.carrier M₁ → LeftModule.carrier M₂, is_set (is_module_hom (Ring.carrier R) f), from _, exact is_trunc_equiv_closed_rev _ H _ end variables {M₁ M₂} definition pmap_of_homomorphism [constructor] /- φ -/ : pSet_of_LeftModule M₁ →* pSet_of_LeftModule M₂ := have H : φ 0 = 0, from respect_zero φ, pmap.mk φ begin esimp, exact H end definition homomorphism_change_fun [constructor] (φ : M₁ →lm M₂) (f : M₁ → M₂) (p : φ ~ f) : M₁ →lm M₂ := homomorphism.mk f (prod.mk (λx₁ x₂, (p (x₁ + x₂))⁻¹ ⬝ to_respect_add φ x₁ x₂ ⬝ ap011 _ (p x₁) (p x₂)) (λ a x, (p (a • x))⁻¹ ⬝ to_respect_smul φ a x ⬝ ap01 _ (p x))) definition homomorphism_eq (φ₁ φ₂ : M₁ →lm M₂) (p : φ₁ ~ φ₂) : φ₁ = φ₂ := begin induction φ₁ with φ₁ q₁, induction φ₂ with φ₂ q₂, esimp at p, induction p, exact ap (homomorphism.mk φ₁) !is_prop.elim end end section definition homomorphism.mk' [constructor] (φ : M₁ → M₂) (p : Π(g₁ g₂ : M₁), φ (g₁ + g₂) = φ g₁ + φ g₂) (q : Π(r : R) x, φ (r • x) = r • φ x) : M₁ →lm M₂ := homomorphism.mk φ (p, q) definition to_respect_zero (φ : M₁ →lm M₂) : φ 0 = 0 := respect_zero φ definition homomorphism_compose [reducible] [constructor] (f' : M₂ →lm M₃) (f : M₁ →lm M₂) : M₁ →lm M₃ := homomorphism.mk (f' ∘ f) !is_module_hom_comp variable (M) definition homomorphism_id [reducible] [constructor] [refl] : M →lm M := homomorphism.mk (@id M) !is_module_hom_id variable {M} abbreviation lmid [constructor] := homomorphism_id M infixr ` ∘lm `:75 := homomorphism_compose definition lm_constant [constructor] (M₁ M₂ : LeftModule R) : M₁ →lm M₂ := homomorphism.mk (const M₁ 0) !is_module_hom_constant definition trivial_image_of_is_contr {R} {M₁ M₂ : LeftModule R} {φ : M₁ →lm M₂} (H : is_contr M₁) ⦃m : M₂⦄ (hm : image φ m) : m = 0 := begin induction hm with m' p, induction p, exact ap φ (@eq_of_is_contr _ H _ _) ⬝ to_respect_zero φ end structure isomorphism (M₁ M₂ : LeftModule R) := (to_hom : M₁ →lm M₂) (is_equiv_to_hom : is_equiv to_hom) infix ` ≃lm `:25 := isomorphism attribute isomorphism.to_hom [coercion] attribute isomorphism.is_equiv_to_hom [instance] attribute isomorphism._trans_of_to_hom [unfold 4] definition equiv_of_isomorphism [constructor] (φ : M₁ ≃lm M₂) : M₁ ≃ M₂ := equiv.mk φ !isomorphism.is_equiv_to_hom section local attribute pSet_of_LeftModule [coercion] definition pequiv_of_isomorphism [constructor] (φ : M₁ ≃lm M₂) : M₁ ≃* M₂ := pequiv_of_equiv (equiv_of_isomorphism φ) (to_respect_zero φ) end definition isomorphism_of_equiv [constructor] (φ : M₁ ≃ M₂) (p : Π(g₁ g₂ : M₁), φ (g₁ + g₂) = φ g₁ + φ g₂) (q : Πr x, φ (r • x) = r • φ x) : M₁ ≃lm M₂ := isomorphism.mk (homomorphism.mk φ (p, q)) !to_is_equiv definition isomorphism_of_eq [constructor] {M₁ M₂ : LeftModule R} (p : M₁ = M₂ :> LeftModule R) : M₁ ≃lm M₂ := isomorphism_of_equiv (equiv_of_eq (ap LeftModule.carrier p)) begin intros, induction p, reflexivity end begin intros, induction p, reflexivity end -- definition pequiv_of_isomorphism_of_eq {M₁ M₂ : LeftModule R} (p : M₁ = M₂ :> LeftModule R) : -- pequiv_of_isomorphism (isomorphism_of_eq p) = pequiv_of_eq (ap pType_of_LeftModule p) := -- begin -- induction p, -- apply pequiv_eq, -- fapply pmap_eq, -- { intro g, reflexivity}, -- { apply is_prop.elim} -- end definition to_lminv [constructor] (φ : M₁ ≃lm M₂) : M₂ →lm M₁ := homomorphism.mk φ⁻¹ abstract begin split, intro g₁ g₂, apply inj' φ, rewrite [respect_add φ, +right_inv φ], intro r x, apply inj' φ, rewrite [to_respect_smul φ, +right_inv φ], end end variable (M) definition isomorphism.refl [refl] [constructor] : M ≃lm M := isomorphism.mk lmid !is_equiv_id variable {M} definition isomorphism.rfl [refl] [constructor] : M ≃lm M := isomorphism.refl M definition isomorphism.symm [symm] [constructor] (φ : M₁ ≃lm M₂) : M₂ ≃lm M₁ := isomorphism.mk (to_lminv φ) !is_equiv_inv definition isomorphism.trans [trans] [constructor] (φ : M₁ ≃lm M₂) (ψ : M₂ ≃lm M₃) : M₁ ≃lm M₃ := isomorphism.mk (ψ ∘lm φ) (is_equiv_compose ψ φ _ _) definition isomorphism.eq_trans [trans] [constructor] {M₁ M₂ : LeftModule R} {M₃ : LeftModule R} (φ : M₁ = M₂) (ψ : M₂ ≃lm M₃) : M₁ ≃lm M₃ := proof isomorphism.trans (isomorphism_of_eq φ) ψ qed definition isomorphism.trans_eq [trans] [constructor] {M₁ : LeftModule R} {M₂ M₃ : LeftModule R} (φ : M₁ ≃lm M₂) (ψ : M₂ = M₃) : M₁ ≃lm M₃ := isomorphism.trans φ (isomorphism_of_eq ψ) postfix `⁻¹ˡᵐ`:(max + 1) := isomorphism.symm infixl ` ⬝lm `:75 := isomorphism.trans infixl ` ⬝lmp `:75 := isomorphism.trans_eq infixl ` ⬝plm `:75 := isomorphism.eq_trans definition homomorphism_of_eq [constructor] {M₁ M₂ : LeftModule R} (p : M₁ = M₂ :> LeftModule R) : M₁ →lm M₂ := isomorphism_of_eq p definition group_homomorphism_of_lm_homomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : M₁ →lm M₂) : M₁ →a M₂ := add_homomorphism.mk φ (to_respect_add φ) definition lm_homomorphism_of_group_homomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : M₁ →a M₂) (h : Π(r : R) g, φ (r • g) = r • φ g) : M₁ →lm M₂ := homomorphism.mk' φ (group.to_respect_add φ) h definition group_isomorphism_of_lm_isomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : M₁ ≃lm M₂) : AddGroup_of_AddAbGroup M₁ ≃g AddGroup_of_AddAbGroup M₂ := group.isomorphism.mk (group_homomorphism_of_lm_homomorphism φ) (isomorphism.is_equiv_to_hom φ) definition lm_isomorphism_of_group_isomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : AddGroup_of_AddAbGroup M₁ ≃g AddGroup_of_AddAbGroup M₂) (h : Π(r : R) g, φ (r • g) = r • φ g) : M₁ ≃lm M₂ := isomorphism.mk (lm_homomorphism_of_group_homomorphism φ h) (group.isomorphism.is_equiv_to_hom φ) definition trivial_homomorphism [constructor] (M₁ M₂ : LeftModule R) : M₁ →lm M₂ := lm_homomorphism_of_group_homomorphism (group.trivial_add_homomorphism M₁ M₂) (λs m, (smul_zero s)⁻¹) section local attribute pSet_of_LeftModule [coercion] definition is_exact_mod (f : M₁ →lm M₂) (f' : M₂ →lm M₃) : Type := @is_exact M₁ M₂ M₃ (homomorphism_fn f) (homomorphism_fn f') definition is_exact_mod.mk {f : M₁ →lm M₂} {f' : M₂ →lm M₃} (h₁ : Πm, f' (f m) = 0) (h₂ : Πm, f' m = 0 → image f m) : is_exact_mod f f' := is_exact.mk h₁ h₂ structure short_exact_mod (A B C : LeftModule R) := (f : A →lm B) (g : B →lm C) (h : @is_short_exact A B C f g) structure five_exact_mod (A B C D E : LeftModule R) := (f₁ : A →lm B) (f₂ : B →lm C) (f₃ : C →lm D) (f₄ : D →lm E) (h₁ : @is_exact A B C f₁ f₂) (h₂ : @is_exact B C D f₂ f₃) (h₃ : @is_exact C D E f₃ f₄) local abbreviation g_of_lm := @group_homomorphism_of_lm_homomorphism definition short_exact_mod_of_is_exact {X A B C Y : LeftModule R} (k : X →lm A) (f : A →lm B) (g : B →lm C) (l : C →lm Y) (hX : is_contr X) (hY : is_contr Y) (kf : is_exact_mod k f) (fg : is_exact_mod f g) (gl : is_exact_mod g l) : short_exact_mod A B C := short_exact_mod.mk f g (is_short_exact_of_is_exact (g_of_lm k) (g_of_lm f) (g_of_lm g) (g_of_lm l) hX hY kf fg gl) definition short_exact_mod_isomorphism {A B A' B' C C' : LeftModule R} (eA : A ≃lm A') (eB : B ≃lm B') (eC : C ≃lm C') (H : short_exact_mod A' B' C') : short_exact_mod A B C := short_exact_mod.mk (eB⁻¹ˡᵐ ∘lm short_exact_mod.f H ∘lm eA) (eC⁻¹ˡᵐ ∘lm short_exact_mod.g H ∘lm eB) (is_short_exact_equiv _ _ (equiv_of_isomorphism eA) (equiv_of_isomorphism eB) (pequiv_of_isomorphism eC) (λa, to_right_inv (equiv_of_isomorphism eB) _) (λb, to_right_inv (equiv_of_isomorphism eC) _) (short_exact_mod.h H)) definition is_contr_middle_of_short_exact_mod {A B C : LeftModule R} (H : short_exact_mod A B C) (HA : is_contr A) (HC : is_contr C) : is_contr B := is_contr_middle_of_is_exact (is_exact_of_is_short_exact (short_exact_mod.h H)) definition is_contr_right_of_short_exact_mod {A B C : LeftModule R} (H : short_exact_mod A B C) (HB : is_contr B) : is_contr C := is_contr_right_of_is_short_exact (short_exact_mod.h H) _ _ definition is_contr_left_of_short_exact_mod {A B C : LeftModule R} (H : short_exact_mod A B C) (HB : is_contr B) : is_contr A := is_contr_left_of_is_short_exact (short_exact_mod.h H) _ pt definition isomorphism_of_is_contr_left {A B C : LeftModule R} (H : short_exact_mod A B C) (HA : is_contr A) : B ≃lm C := isomorphism.mk (short_exact_mod.g H) begin apply @is_equiv_right_of_is_short_exact _ _ _ (group_homomorphism_of_lm_homomorphism (short_exact_mod.f H)) (group_homomorphism_of_lm_homomorphism (short_exact_mod.g H)), rexact short_exact_mod.h H, exact HA, end definition isomorphism_of_is_contr_right {A B C : LeftModule R} (H : short_exact_mod A B C) (HC : is_contr C) : A ≃lm B := isomorphism.mk (short_exact_mod.f H) begin apply @is_equiv_left_of_is_short_exact _ _ _ (group_homomorphism_of_lm_homomorphism (short_exact_mod.f H)) (group_homomorphism_of_lm_homomorphism (short_exact_mod.g H)), rexact short_exact_mod.h H, exact HC, end end end end /- we say that an left module D is built from the sequence E if D is a "twisted sum" of the E, and E has only finitely many nontrivial values -/ open nat structure is_built_from.{u v w} {R : Ring} (D : LeftModule.{u v} R) (E : ℕ → LeftModule.{u w} R) : Type.{max u (v+1) w} := (part : ℕ → LeftModule.{u v} R) (ses : Πn, short_exact_mod (E n) (part n) (part (n+1))) (e0 : part 0 ≃lm D) (n₀ : ℕ) (HD' : Π(s : ℕ), n₀ ≤ s → is_contr (part s)) open is_built_from universe variables u v w variables {R : Ring.{u}} {D D' : LeftModule.{u v} R} {E E' : ℕ → LeftModule.{u w} R} definition is_built_from_shift (H : is_built_from D E) : is_built_from (part H 1) (λn, E (n+1)) := is_built_from.mk (λn, part H (n+1)) (λn, ses H (n+1)) isomorphism.rfl (pred (n₀ H)) (λs Hle, HD' H _ (le_succ_of_pred_le Hle)) definition is_built_from_isomorphism (e : D ≃lm D') (f : Πn, E n ≃lm E' n) (H : is_built_from D E) : is_built_from D' E' := ⦃is_built_from, H, e0 := e0 H ⬝lm e, ses := λn, short_exact_mod_isomorphism (f n)⁻¹ˡᵐ isomorphism.rfl isomorphism.rfl (ses H n)⦄ definition is_built_from_isomorphism_left (e : D ≃lm D') (H : is_built_from D E) : is_built_from D' E := ⦃is_built_from, H, e0 := e0 H ⬝lm e⦄ definition isomorphism_of_is_contr_submodule (H : is_built_from D E) (n : ℕ) (HE : is_contr (E n)) : part H n ≃lm part H (n+1) := isomorphism_of_is_contr_left (ses H n) HE definition isomorphism_of_is_contr_submodules_range (H : is_built_from D E) {n k : ℕ} (Hnk : n ≤ k) (HE : Πl, n ≤ l → l < k → is_contr (E l)) : part H n ≃lm part H k := begin induction Hnk with k Hnk IH, { reflexivity }, { refine IH (λl Hnl Hlk, HE l Hnl (lt.step Hlk)) ⬝lm isomorphism_of_is_contr_submodule H k (HE k Hnk !self_lt_succ), } end definition is_contr_quotients_of_is_contr_total (H : is_built_from D E) (HD : is_contr D) (n : ℕ) : is_contr (part H n) := begin induction n with n IH, { exact is_trunc_equiv_closed_rev -2 (equiv_of_isomorphism (e0 H)) _ }, { exact is_contr_right_of_short_exact_mod (ses H n) IH } end definition is_contr_quotients_of_is_contr_submodules (H : is_built_from D E) {n : ℕ} (HE : Πk, n ≤ k → is_contr (E k)) : is_contr (part H n) := begin refine is_contr_equiv_closed_rev _ (HD' H (max n (n₀ H)) !le_max_right), apply equiv_of_isomorphism, apply isomorphism_of_is_contr_submodules_range H !le_max_left, intros l Hnl Hl', exact HE l Hnl end /- alternate direct proof -/ -- nat.rec_down (λk, is_contr (part H (n + k))) _ (HD' H _ !nat.le_add_left) -- (λk H2, is_contr_middle_of_short_exact_mod (ses H (n + k)) (HE (n + k) !nat.le_add_right) -- proof H2 qed) definition isomorphism_of_is_contr_submodules (H : is_built_from D E) {n : ℕ} (HE : Πk, n < k → is_contr (E k)) : E n ≃lm part H n := isomorphism_of_is_contr_right (ses H n) (is_contr_quotients_of_is_contr_submodules H HE) -- definition is_contr_quotients_of_is_contr_submodules1 (H : is_built_from D E) (n : ℕ) -- (HE : Πk, n ≤ k → is_contr (E k)) : is_contr (part H n) := -- nat.rec_down (λk, is_contr (part H (n + k))) _ (HD' H _ !nat.le_add_left) -- (λk H2, is_contr_middle_of_short_exact_mod (ses H (n + k)) (HE (n + k) !nat.le_add_right) -- proof H2 qed) definition isomorphism_zero_of_is_built_from (H : is_built_from D E) (p : n₀ H = 1) : E 0 ≃lm D := isomorphism_of_is_contr_right (ses H 0) (HD' H 1 (le_of_eq p)) ⬝lm e0 H definition isomorphism_total_of_is_contr_submodules (H : is_built_from D E) {n : ℕ} (HE : Πk, k < n → is_contr (E k)) : D ≃lm part H n := (e0 H)⁻¹ˡᵐ ⬝lm isomorphism_of_is_contr_submodules_range H !zero_le (λk H0k Hkn, HE k Hkn) definition isomorphism_of_is_contr_submodules_but_one (H : is_built_from D E) {n : ℕ} (HE : Πk, k ≠ n → is_contr (E k)) : D ≃lm E n := (e0 H)⁻¹ˡᵐ ⬝lm isomorphism_of_is_contr_submodules_range H !zero_le (λk H0k Hkn, HE k (ne_of_lt Hkn)) ⬝lm (isomorphism_of_is_contr_submodules H (λk Hk, HE k (ne.symm (ne_of_lt Hk))))⁻¹ˡᵐ definition short_exact_mod_of_is_contr_submodules (H : is_built_from D E) {n m : ℕ} (Hnm : n < m) (HE : Πk, k ≠ n → k ≠ m → is_contr (E k)) : short_exact_mod (E n) D (E m) := begin refine short_exact_mod_isomorphism isomorphism.rfl _ _ (ses H n), { exact isomorphism_total_of_is_contr_submodules H (λk Hk, HE k (ne_of_lt Hk) (ne_of_lt (lt.trans Hk Hnm))) }, { exact isomorphism_of_is_contr_submodules H (λk Hk, HE k (ne.symm (ne_of_lt (lt.trans Hnm Hk))) (ne.symm (ne_of_lt Hk))) ⬝lm (isomorphism_of_is_contr_submodules_range H Hnm (λk Hnk Hkm, HE k (ne.symm (ne_of_lt Hnk)) (ne_of_lt Hkm)))⁻¹ˡᵐ } end definition is_contr_submodules (H : is_built_from D E) (HD : is_contr D) (n : ℕ) : is_contr (E n) := begin apply is_contr_left_of_short_exact_mod (ses H n), exact is_contr_quotients_of_is_contr_total H HD n end definition is_contr_total (H : is_built_from D E) (HE : Πn, is_contr (E n)) : is_contr D := have is_contr (part H 0), from is_contr_quotients_of_is_contr_submodules H (λn H, HE n), is_contr_equiv_closed (equiv_of_isomorphism (e0 H)) _ section int open int definition left_module_int_of_ab_group [constructor] (A : Type) [add_ab_group A] : left_module rℤ A := left_module_of_ab_group imul imul_add add_imul mul_imul one_imul definition LeftModule_int_of_AbGroup [constructor] (A : AddAbGroup) : LeftModule rℤ := LeftModule.mk A (left_module_int_of_ab_group A) definition lm_hom_int.mk [constructor] {A B : AbGroup} (φ : A →g B) : LeftModule_int_of_AbGroup A →lm LeftModule_int_of_AbGroup B := lm_homomorphism_of_group_homomorphism φ (to_respect_imul φ) definition lm_iso_int.mk [constructor] {A B : AbGroup} (φ : A ≃g B) : LeftModule_int_of_AbGroup A ≃lm LeftModule_int_of_AbGroup B := isomorphism.mk (lm_hom_int.mk φ) (group.isomorphism.is_equiv_to_hom φ) definition group_isomorphism_of_lm_isomorphism_int [constructor] {A B : AbGroup} (φ : LeftModule_int_of_AbGroup A ≃lm LeftModule_int_of_AbGroup B) : A ≃g B := group_isomorphism_of_lm_isomorphism φ end int end left_module
7fac0d900dcb7ccb9ef6a8a2426661e6339e22e7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/choiceMacroRules.lean
78284b5035012b468265fb2cb6f7a30aef212c28
[ "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
457
lean
syntax:65 (name := myAdd1) term "+++" term:65 : term syntax:65 (name := myAdd2) term "+++" term:65 : term macro_rules (kind := myAdd1) | `($a +++ $b) => `(Nat.add $a $b) macro_rules (kind := myAdd2) | `($a +++ $b) => `(Append.append $a $b) #check (1:Nat) +++ 3 theorem tst1 : ((1:Nat) +++ 3) = 1 + 3 := rfl #check fun (x : Nat) => if x +++ 3 = x then x else x + 1 #check [1, 2] +++ [3, 4] theorem tst2 : ([1, 2] +++ [3, 4]) = [1, 2] ++ [3, 4] := rfl
0ea898a6c3fba554f3f321ecdfb3afc76b38f119
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/smt/congruence_closure.lean
a8bb307d9de915402e751c414f267915fc99a2d8
[]
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
566
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.interactive_base import Mathlib.Lean3Lib.init.meta.tactic import Mathlib.Lean3Lib.init.meta.set_get_option_tactics universes l namespace Mathlib /- If tt, congruence closure will treat implicit instance arguments as constants. -/ structure cc_config where ignore_instances : Bool ac : Bool ho_fns : Option (List name) em : Bool
d2d8f0b39ac2bdcbcaaa5e02e6db6222ab14bad2
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/equiv/encodable/basic.lean
d6f36f012ed9fe55b91658e61262bd730ba0c823
[]
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
15,532
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Mario Carneiro Type class for encodable Types. Note that every encodable Type is countable. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.nat import Mathlib.order.rel_iso import Mathlib.order.directed import Mathlib.PostPort universes u_1 l u_2 u_3 namespace Mathlib /-- An encodable type is a "constructively countable" type. This is where we have an explicit injection `encode : α → nat` and a partial inverse `decode : nat → option α`. This makes the range of `encode` decidable, although it is not decidable if `α` is finite or not. -/ class encodable (α : Type u_1) where encode : α → ℕ decode : ℕ → Option α encodek : ∀ (a : α), decode (encode a) = some a namespace encodable theorem encode_injective {α : Type u_1} [encodable α] : function.injective encode := sorry /- This is not set as an instance because this is usually not the best way to infer decidability. -/ def decidable_eq_of_encodable (α : Type u_1) [encodable α] : DecidableEq α := sorry def of_left_injection {α : Type u_1} {β : Type u_2} [encodable α] (f : β → α) (finv : α → Option β) (linv : ∀ (b : β), finv (f b) = some b) : encodable β := mk (fun (b : β) => encode (f b)) (fun (n : ℕ) => option.bind (decode α n) finv) sorry def of_left_inverse {α : Type u_1} {β : Type u_2} [encodable α] (f : β → α) (finv : α → β) (linv : ∀ (b : β), finv (f b) = b) : encodable β := of_left_injection f (some ∘ finv) sorry /-- If `α` is encodable and `β ≃ α`, then so is `β` -/ def of_equiv {β : Type u_2} (α : Type u_1) [encodable α] (e : β ≃ α) : encodable β := of_left_inverse (⇑e) (⇑(equiv.symm e)) (equiv.left_inv e) @[simp] theorem encode_of_equiv {α : Type u_1} {β : Type u_2} [encodable α] (e : β ≃ α) (b : β) : encode b = encode (coe_fn e b) := rfl @[simp] theorem decode_of_equiv {α : Type u_1} {β : Type u_2} [encodable α] (e : β ≃ α) (n : ℕ) : decode β n = option.map (⇑(equiv.symm e)) (decode α n) := rfl protected instance nat : encodable ℕ := mk id some sorry @[simp] theorem encode_nat (n : ℕ) : encode n = n := rfl @[simp] theorem decode_nat (n : ℕ) : decode ℕ n = some n := rfl protected instance empty : encodable empty := mk (fun (a : empty) => empty.rec (fun (a : empty) => ℕ) a) (fun (n : ℕ) => none) sorry protected instance unit : encodable PUnit := mk (fun (_x : PUnit) => 0) (fun (n : ℕ) => nat.cases_on n (some PUnit.unit) fun (_x : ℕ) => none) sorry @[simp] theorem encode_star : encode PUnit.unit = 0 := rfl @[simp] theorem decode_unit_zero : decode PUnit 0 = some PUnit.unit := rfl @[simp] theorem decode_unit_succ (n : ℕ) : decode PUnit (Nat.succ n) = none := rfl protected instance option {α : Type u_1} [h : encodable α] : encodable (Option α) := mk (fun (o : Option α) => option.cases_on o 0 fun (a : α) => Nat.succ (encode a)) (fun (n : ℕ) => nat.cases_on n (some none) fun (m : ℕ) => option.map some (decode α m)) sorry @[simp] theorem encode_none {α : Type u_1} [encodable α] : encode none = 0 := rfl @[simp] theorem encode_some {α : Type u_1} [encodable α] (a : α) : encode (some a) = Nat.succ (encode a) := rfl @[simp] theorem decode_option_zero {α : Type u_1} [encodable α] : decode (Option α) 0 = some none := rfl @[simp] theorem decode_option_succ {α : Type u_1} [encodable α] (n : ℕ) : decode (Option α) (Nat.succ n) = option.map some (decode α n) := rfl def decode2 (α : Type u_1) [encodable α] (n : ℕ) : Option α := option.bind (decode α n) (option.guard fun (a : α) => encode a = n) theorem mem_decode2' {α : Type u_1} [encodable α] {n : ℕ} {a : α} : a ∈ decode2 α n ↔ a ∈ decode α n ∧ encode a = n := sorry theorem mem_decode2 {α : Type u_1} [encodable α] {n : ℕ} {a : α} : a ∈ decode2 α n ↔ encode a = n := iff.trans mem_decode2' (and_iff_right_of_imp fun (e : encode a = n) => e ▸ encodek a) theorem decode2_is_partial_inv {α : Type u_1} [encodable α] : function.is_partial_inv encode (decode2 α) := fun (a : α) (n : ℕ) => mem_decode2 theorem decode2_inj {α : Type u_1} [encodable α] {n : ℕ} {a₁ : α} {a₂ : α} (h₁ : a₁ ∈ decode2 α n) (h₂ : a₂ ∈ decode2 α n) : a₁ = a₂ := encode_injective (Eq.trans (iff.mp mem_decode2 h₁) (Eq.symm (iff.mp mem_decode2 h₂))) theorem encodek2 {α : Type u_1} [encodable α] (a : α) : decode2 α (encode a) = some a := iff.mpr mem_decode2 rfl def decidable_range_encode (α : Type u_1) [encodable α] : decidable_pred (set.range encode) := fun (x : ℕ) => decidable_of_iff ↥(option.is_some (decode2 α x)) sorry def equiv_range_encode (α : Type u_1) [encodable α] : α ≃ ↥(set.range encode) := equiv.mk (fun (a : α) => { val := encode a, property := sorry }) (fun (n : ↥(set.range encode)) => option.get sorry) sorry sorry def encode_sum {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] : α ⊕ β → ℕ := sorry def decode_sum {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] (n : ℕ) : Option (α ⊕ β) := sorry protected instance sum {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] : encodable (α ⊕ β) := mk encode_sum decode_sum sorry @[simp] theorem encode_inl {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] (a : α) : encode (sum.inl a) = bit0 (encode a) := rfl @[simp] theorem encode_inr {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] (b : β) : encode (sum.inr b) = bit1 (encode b) := rfl @[simp] theorem decode_sum_val {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] (n : ℕ) : decode (α ⊕ β) n = decode_sum n := rfl protected instance bool : encodable Bool := of_equiv (Unit ⊕ Unit) equiv.bool_equiv_punit_sum_punit @[simp] theorem encode_tt : encode tt = 1 := rfl @[simp] theorem encode_ff : encode false = 0 := rfl @[simp] theorem decode_zero : decode Bool 0 = some false := rfl @[simp] theorem decode_one : decode Bool 1 = some tt := rfl theorem decode_ge_two (n : ℕ) (h : bit0 1 ≤ n) : decode Bool n = none := sorry def encode_sigma {α : Type u_1} {γ : α → Type u_3} [encodable α] [(a : α) → encodable (γ a)] : sigma γ → ℕ := sorry def decode_sigma {α : Type u_1} {γ : α → Type u_3} [encodable α] [(a : α) → encodable (γ a)] (n : ℕ) : Option (sigma γ) := sorry protected instance sigma {α : Type u_1} {γ : α → Type u_3} [encodable α] [(a : α) → encodable (γ a)] : encodable (sigma γ) := mk encode_sigma decode_sigma sorry @[simp] theorem decode_sigma_val {α : Type u_1} {γ : α → Type u_3} [encodable α] [(a : α) → encodable (γ a)] (n : ℕ) : decode (sigma γ) n = option.bind (decode α (prod.fst (nat.unpair n))) fun (a : α) => option.map (sigma.mk a) (decode (γ a) (prod.snd (nat.unpair n))) := sorry @[simp] theorem encode_sigma_val {α : Type u_1} {γ : α → Type u_3} [encodable α] [(a : α) → encodable (γ a)] (a : α) (b : γ a) : encode (sigma.mk a b) = nat.mkpair (encode a) (encode b) := rfl protected instance prod {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] : encodable (α × β) := of_equiv (sigma fun (_x : α) => β) (equiv.symm (equiv.sigma_equiv_prod α β)) @[simp] theorem decode_prod_val {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] (n : ℕ) : decode (α × β) n = option.bind (decode α (prod.fst (nat.unpair n))) fun (a : α) => option.map (Prod.mk a) (decode β (prod.snd (nat.unpair n))) := sorry @[simp] theorem encode_prod_val {α : Type u_1} {β : Type u_2} [encodable α] [encodable β] (a : α) (b : β) : encode (a, b) = nat.mkpair (encode a) (encode b) := rfl def encode_subtype {α : Type u_1} {P : α → Prop} [encA : encodable α] : (Subtype fun (a : α) => P a) → ℕ := sorry def decode_subtype {α : Type u_1} {P : α → Prop} [encA : encodable α] [decP : decidable_pred P] (v : ℕ) : Option (Subtype fun (a : α) => P a) := option.bind (decode α v) fun (a : α) => dite (P a) (fun (h : P a) => some { val := a, property := h }) fun (h : ¬P a) => none protected instance subtype {α : Type u_1} {P : α → Prop} [encA : encodable α] [decP : decidable_pred P] : encodable (Subtype fun (a : α) => P a) := mk encode_subtype decode_subtype sorry theorem subtype.encode_eq {α : Type u_1} {P : α → Prop} [encA : encodable α] [decP : decidable_pred P] (a : Subtype P) : encode a = encode (subtype.val a) := subtype.cases_on a fun (a_val : α) (a_property : P a_val) => Eq.refl (encode { val := a_val, property := a_property }) protected instance fin (n : ℕ) : encodable (fin n) := of_equiv (Subtype fun (m : ℕ) => m < n) (equiv.fin_equiv_subtype n) protected instance int : encodable ℤ := of_equiv ℕ equiv.int_equiv_nat protected instance ulift {α : Type u_1} [encodable α] : encodable (ulift α) := of_equiv α equiv.ulift protected instance plift {α : Type u_1} [encodable α] : encodable (plift α) := of_equiv α equiv.plift def of_inj {α : Type u_1} {β : Type u_2} [encodable β] (f : α → β) (hf : function.injective f) : encodable α := of_left_injection f (function.partial_inv f) sorry end encodable /-- `ulower α : Type 0` is an equivalent type in the lowest universe, given `encodable α`. -/ def ulower (α : Type u_1) [encodable α] := ↥(set.range encodable.encode) namespace ulower /-- The equivalence between the encodable type `α` and `ulower α : Type 0`. -/ def equiv (α : Type u_1) [encodable α] : α ≃ ulower α := encodable.equiv_range_encode α /-- Lowers an `a : α` into `ulower α`. -/ def down {α : Type u_1} [encodable α] (a : α) : ulower α := coe_fn (equiv α) a protected instance inhabited {α : Type u_1} [encodable α] [Inhabited α] : Inhabited (ulower α) := { default := down Inhabited.default } /-- Lifts an `a : ulower α` into `α`. -/ def up {α : Type u_1} [encodable α] (a : ulower α) : α := coe_fn (equiv.symm (equiv α)) a @[simp] theorem down_up {α : Type u_1} [encodable α] {a : ulower α} : down (up a) = a := equiv.right_inv (equiv α) a @[simp] theorem up_down {α : Type u_1} [encodable α] {a : α} : up (down a) = a := equiv.left_inv (equiv α) a @[simp] theorem up_eq_up {α : Type u_1} [encodable α] {a : ulower α} {b : ulower α} : up a = up b ↔ a = b := equiv.apply_eq_iff_eq (equiv.symm (equiv α)) @[simp] theorem down_eq_down {α : Type u_1} [encodable α] {a : α} {b : α} : down a = down b ↔ a = b := equiv.apply_eq_iff_eq (equiv α) protected theorem ext {α : Type u_1} [encodable α] {a : ulower α} {b : ulower α} : up a = up b → a = b := iff.mp up_eq_up end ulower /- Choice function for encodable types and decidable predicates. We provide the following API choose {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] : (∃ x, p x) → α := choose_spec {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := -/ namespace encodable def choose_x {α : Type u_1} {p : α → Prop} [encodable α] [decidable_pred p] (h : ∃ (x : α), p x) : Subtype fun (x : α) => p x := (fun (this : ∃ (n : ℕ), good p (decode α n)) => sorry) sorry def choose {α : Type u_1} {p : α → Prop} [encodable α] [decidable_pred p] (h : ∃ (x : α), p x) : α := subtype.val (choose_x h) theorem choose_spec {α : Type u_1} {p : α → Prop} [encodable α] [decidable_pred p] (h : ∃ (x : α), p x) : p (choose h) := subtype.property (choose_x h) theorem axiom_of_choice {α : Type u_1} {β : α → Type u_2} {R : (x : α) → β x → Prop} [(a : α) → encodable (β a)] [(x : α) → (y : β x) → Decidable (R x y)] (H : ∀ (x : α), ∃ (y : β x), R x y) : ∃ (f : (a : α) → β a), ∀ (x : α), R x (f x) := Exists.intro (fun (x : α) => choose (H x)) fun (x : α) => choose_spec (H x) theorem skolem {α : Type u_1} {β : α → Type u_2} {P : (x : α) → β x → Prop} [c : (a : α) → encodable (β a)] [d : (x : α) → (y : β x) → Decidable (P x y)] : (∀ (x : α), ∃ (y : β x), P x y) ↔ ∃ (f : (a : α) → β a), ∀ (x : α), P x (f x) := sorry /- There is a total ordering on the elements of an encodable type, induced by the map to ℕ. -/ /-- The `encode` function, viewed as an embedding. -/ def encode' (α : Type u_1) [encodable α] : α ↪ ℕ := function.embedding.mk encode encode_injective protected instance order.preimage.is_trans {α : Type u_1} [encodable α] : is_trans α (⇑(encode' α) ⁻¹'o LessEq) := rel_embedding.is_trans (rel_embedding.preimage (encode' α) LessEq) protected instance order.preimage.is_antisymm {α : Type u_1} [encodable α] : is_antisymm α (⇑(encode' α) ⁻¹'o LessEq) := rel_embedding.is_antisymm (rel_embedding.preimage (encode' α) LessEq) protected instance order.preimage.is_total {α : Type u_1} [encodable α] : is_total α (⇑(encode' α) ⁻¹'o LessEq) := rel_embedding.is_total (rel_embedding.preimage (encode' α) LessEq) end encodable namespace directed /-- Given a `directed r` function `f : α → β` defined on an encodable inhabited type, construct a noncomputable sequence such that `r (f (x n)) (f (x (n + 1)))` and `r (f a) (f (x (encode a + 1))`. -/ protected def sequence {α : Type u_1} {β : Type u_2} [encodable α] [Inhabited α] {r : β → β → Prop} (f : α → β) (hf : directed r f) : ℕ → α := sorry theorem sequence_mono_nat {α : Type u_1} {β : Type u_2} [encodable α] [Inhabited α] {r : β → β → Prop} {f : α → β} (hf : directed r f) (n : ℕ) : r (f (directed.sequence f hf n)) (f (directed.sequence f hf (n + 1))) := sorry theorem rel_sequence {α : Type u_1} {β : Type u_2} [encodable α] [Inhabited α] {r : β → β → Prop} {f : α → β} (hf : directed r f) (a : α) : r (f a) (f (directed.sequence f hf (encodable.encode a + 1))) := sorry theorem sequence_mono {α : Type u_1} {β : Type u_2} [encodable α] [Inhabited α] [preorder β] {f : α → β} (hf : directed LessEq f) : monotone (f ∘ directed.sequence f hf) := monotone_of_monotone_nat (sequence_mono_nat hf) theorem le_sequence {α : Type u_1} {β : Type u_2} [encodable α] [Inhabited α] [preorder β] {f : α → β} (hf : directed LessEq f) (a : α) : f a ≤ f (directed.sequence f hf (encodable.encode a + 1)) := rel_sequence hf a end directed /-- Representative of an equivalence class. This is a computable version of `quot.out` for a setoid on an encodable type. -/ def quotient.rep {α : Type u_1} {s : setoid α} [DecidableRel has_equiv.equiv] [encodable α] (q : quotient s) : α := encodable.choose (quotient.exists_rep q) theorem quotient.rep_spec {α : Type u_1} {s : setoid α} [DecidableRel has_equiv.equiv] [encodable α] (q : quotient s) : quotient.mk (quotient.rep q) = q := encodable.choose_spec (quotient.exists_rep q) /-- The quotient of an encodable space by a decidable equivalence relation is encodable. -/ def encodable_quotient {α : Type u_1} {s : setoid α} [DecidableRel has_equiv.equiv] [encodable α] : encodable (quotient s) := encodable.mk (fun (q : quotient s) => encodable.encode (quotient.rep q)) (fun (n : ℕ) => quotient.mk <$> encodable.decode α n) sorry
afd79873ef223bfdf0364be37341394c483300fb
63abd62053d479eae5abf4951554e1064a4c45b4
/src/order/filter/cofinite.lean
2ef81659503488bec1645b1e862b01400ca2453e
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
2,811
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, Jeremy Avigad, Yury Kudryashov -/ import order.filter.at_top_bot /-! # The cofinite filter In this file we define `cofinite`: the filter of sets with finite complement and prove its basic properties. In particular, we prove that for `ℕ` it is equal to `at_top`. ## TODO Define filters for other cardinalities of the complement. -/ open set open_locale classical variables {α : Type*} namespace filter /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite : filter α := { sets := {s | finite sᶜ}, univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq], sets_of_superset := assume s t (hs : finite sᶜ) (st: s ⊆ t), hs.subset $ compl_subset_compl.2 st, inter_sets := assume s t (hs : finite sᶜ) (ht : finite (tᶜ)), by simp only [compl_inter, finite.union, ht, hs, mem_set_of_eq] } @[simp] lemma mem_cofinite {s : set α} : s ∈ (@cofinite α) ↔ finite sᶜ := iff.rfl instance cofinite_ne_bot [infinite α] : ne_bot (@cofinite α) := mt empty_in_sets_eq_bot.mpr $ by { simp only [mem_cofinite, compl_empty], exact infinite_univ } lemma frequently_cofinite_iff_infinite {p : α → Prop} : (∃ᶠ x in cofinite, p x) ↔ set.infinite {x | p x} := by simp only [filter.frequently, filter.eventually, mem_cofinite, compl_set_of, not_not, set.infinite] end filter open filter lemma set.finite.compl_mem_cofinite {s : set α} (hs : s.finite) : sᶜ ∈ (@cofinite α) := mem_cofinite.2 $ (compl_compl s).symm ▸ hs lemma set.finite.eventually_cofinite_nmem {s : set α} (hs : s.finite) : ∀ᶠ x in cofinite, x ∉ s := hs.compl_mem_cofinite lemma finset.eventually_cofinite_nmem (s : finset α) : ∀ᶠ x in cofinite, x ∉ s := s.finite_to_set.eventually_cofinite_nmem lemma set.infinite_iff_frequently_cofinite {s : set α} : set.infinite s ↔ (∃ᶠ x in cofinite, x ∈ s) := frequently_cofinite_iff_infinite.symm lemma filter.eventually_cofinite_ne (x : α) : ∀ᶠ a in cofinite, a ≠ x := (set.finite_singleton x).eventually_cofinite_nmem /-- For natural numbers the filters `cofinite` and `at_top` coincide. -/ lemma nat.cofinite_eq_at_top : @cofinite ℕ = at_top := begin ext s, simp only [mem_cofinite, mem_at_top_sets], split, { assume hs, use (hs.to_finset.sup id) + 1, assume b hb, by_contradiction hbs, have := hs.to_finset.subset_range_sup_succ (finite.mem_to_finset.2 hbs), exact not_lt_of_le hb (finset.mem_range.1 this) }, { rintros ⟨N, hN⟩, apply (finite_lt_nat N).subset, assume n hn, change n < N, exact lt_of_not_ge (λ hn', hn $ hN n hn') } end
4a7d90c4539c14a04cad81a291fb5fb1c2b5bb0b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/derive.lean
42879132647bbc1ac0fea25945da471ab69fefb2
[]
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
796
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich Attribute that can automatically derive typeclass instances. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.attribute import Mathlib.Lean3Lib.init.meta.interactive_base import Mathlib.Lean3Lib.init.meta.mk_has_reflect_instance import Mathlib.Lean3Lib.init.meta.mk_has_sizeof_instance import Mathlib.Lean3Lib.init.meta.mk_inhabited_instance namespace Mathlib /-- A handler that may or may not be able to implement the typeclass `cls` for `decl`. It should return `tt` if it was able to derive `cls` and `ff` if it does not know how to derive `cls`, in which case lower-priority handlers will be tried next. -/
26420dd10cd6d28cab3f1df62b8af79883b9dc4f
556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e
/src/starkware/cairo/common/cairo_secp/elliptic_curves.lean
a921869b62dea1107ad21e1c4c7844d5fcc0227a
[]
permissive
starkware-libs/formal-proofs
d6b731604461bf99e6ba820e68acca62a21709e8
f5fa4ba6a471357fd171175183203d0b437f6527
refs/heads/master
1,691,085,444,753
1,690,507,386,000
1,690,507,386,000
410,476,629
32
9
Apache-2.0
1,690,506,773,000
1,632,639,790,000
Lean
UTF-8
Lean
false
false
4,896
lean
import data.zmod.algebra import tactic class ec_field (F : Type*) extends field F := (deceqF : decidable_eq F) (two_ne_zero : (2 : F) ≠ 0) instance ec_field.decidable_eq (F : Type*) [h : ec_field F] : decidable_eq F := h.deceqF def on_ec {F : Type*} [field F] (p : F × F) := p.2^2 = p.1^3 + 7 lemma eq_or_eq_neg_of_eq_of_on_ec {F : Type*} [field F] {x1 y1 x2 y2 : F} (hp : on_ec (x1, y1)) (hq : on_ec (x2, y2)) (heq : x1 = x2 ) : y1 = y2 ∨ y1 = -y2 := begin have : y1^2 = y2^2, { apply hp.trans, symmetry, apply hq.trans, dsimp, rw heq }, apply eq_or_eq_neg_of_sq_eq_sq _ _ this end lemma eq_of_on_ec {F : Type*} [field F] {x1 y1 x2 y2 : F} (hp : on_ec (x1, y1)) (hq : on_ec (x2, y2)) (heq : x1 = x2 ) (hne : y1 ≠ -y2) : y1 = y2 := or.resolve_right (eq_or_eq_neg_of_eq_of_on_ec hp hq heq) hne @[ext] structure AffineECPoint (F : Type*) [field F] := (x y : F) (h : on_ec (x, y)) inductive ECPoint (F : Type*) [field F] | ZeroPoint : ECPoint | AffinePoint : AffineECPoint F → ECPoint variables {F : Type*} [ec_field F] def ec_double_slope (p : F × F) := 3 * p.1^2 / (2 * p.2) def ec_double (p : F × F) := let slope := ec_double_slope p, new_x := slope^2 - 2 * p.1 in (new_x, (p.1 - new_x) * slope - p.2) theorem on_ec_ec_double {p : F × F} (h : on_ec p) (h' : p.2 ≠ 0) : on_ec (ec_double p) := begin cases p with x y, have pow_three : ∀ z : F, z^3 = z * z * z, { intro z, simp [pow_succ, mul_assoc] }, simp [on_ec, ec_double, ec_double_slope] at *, apply eq_of_sub_eq_zero, field_simp [ec_field.two_ne_zero, h, h', pow_two, pow_three], ring_nf, simp [h], ring_nf, end def ec_add_slope (p1 p2 : F × F) := (p2.2 - p1.2) / (p2.1 - p1.1) def ec_add (p1 p2 : F × F) : F × F := let slope := ec_add_slope p1 p2, new_x := slope^2 - (p1.1 + p2.1) in (new_x, (p1.1 - new_x) * slope - p1.2) theorem on_ec_ec_add {p1 p2 : F × F} (h1 : on_ec p1) (h2 : on_ec p2) (h' : p1.1 ≠ p2.1) : on_ec (ec_add p1 p2) := begin cases p1 with x1 y1, cases p2 with x2 y2, have pow_three : ∀ z : F, z^3 = z * z^2, { intro z, simp [pow_succ, mul_assoc], }, have pow_four : ∀ z : F, z^4 = z^2 * z^2, { intro z, simp [pow_succ, mul_assoc], }, simp [on_ec, ec_add, ec_add_slope] at *, have : x2 - x1 ≠ 0, { contrapose! h', symmetry, apply eq_of_sub_eq_zero h' }, apply eq_of_sub_eq_zero, field_simp [ec_field.two_ne_zero, pow_two, pow_three, this], ring_nf, simp [h1, h2, pow_three, pow_four], ring_nf, simp [h1, h2], ring_nf end namespace ECPoint protected def add : ECPoint F → ECPoint F → ECPoint F | ZeroPoint b := b | a ZeroPoint := a | (AffinePoint a) (AffinePoint b) := if axbx: a.x = b.x then if ayby: a.y = -b.y then -- a = -b ZeroPoint else have a.y = b.y, from eq_of_on_ec a.h b.h axbx ayby, have a.y ≠ 0, by { contrapose! ayby, rw [←this, ayby, neg_zero] }, let p := ec_double (a.x, a.y) in AffinePoint ⟨p.1, p.2, on_ec_ec_double a.h this⟩ else let p := ec_add (a.x, a.y) (b.x, b.y) in AffinePoint ⟨p.1, p.2, on_ec_ec_add a.h b.h axbx⟩ protected def neg : ECPoint F → ECPoint F | ZeroPoint := ZeroPoint | (AffinePoint a) := AffinePoint ⟨a.x, -a.y, by { simp [on_ec], exact a.h} ⟩ protected theorem add_left_neg (a : ECPoint F) : a.neg.add a = ZeroPoint := by { cases a; simp [ECPoint.neg, ECPoint.add] } protected theorem add_comm (a b: ECPoint F) : a.add b = b.add a := begin cases a; cases b; simp [ECPoint.add], by_cases h : a.x = b.x, { rw [dif_pos h, dif_pos h.symm], simp [h], by_cases h': a.y = -b.y, { rw [dif_pos h', dif_pos (eq_neg_of_eq_neg h')] }, rw [dif_neg h', dif_neg (λ h'', h' (eq_neg_of_eq_neg h''))], simp [eq_of_on_ec a.h b.h h h'] }, rw [dif_neg h, dif_neg (ne.symm h)], have : ec_add_slope (a.x, a.y) (b.x, b.y) = ec_add_slope (b.x, b.y) (a.x, a.y), { simp [ec_add_slope], rw [←neg_sub b.y a.y, ←neg_sub b.x a.x, neg_div_neg_eq] }, congr' 1, ext; dsimp [ec_add]; simp [add_comm], { simp [this] }, have h1 : a.x - b.x ≠ 0, { rwa [ne, sub_eq_zero] }, have h2 : b.x - a.x ≠ 0, { rw [ne, sub_eq_zero], exact ne.symm h }, field_simp [ec_add_slope, h1, h2, pow_two], ring_nf end end ECPoint instance : add_comm_group (ECPoint F) := { add := ECPoint.add, neg := ECPoint.neg, zero := ECPoint.ZeroPoint, add_assoc := sorry, zero_add := by { intro a, cases a; simp [ECPoint.add] }, add_zero := by { intro a, cases a; simp [ECPoint.add] }, add_left_neg := ECPoint.add_left_neg, add_comm := ECPoint.add_comm } theorem ECPoint.add_def (x y : ECPoint F) : x + y = ECPoint.add x y := rfl theorem ECPoint.neg_def (x : ECPoint F) : - x = ECPoint.neg x := rfl theorem ECPoint.zero_def : (0 : ECPoint F) = ECPoint.ZeroPoint := rfl
758dd71c802dc58266d94ad0b839dd621f4cc679
bb31430994044506fa42fd667e2d556327e18dfe
/src/measure_theory/group/add_circle.lean
93388f293ccf4c6c97449de3ff92bd9a62929a3a
[ "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,356
lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import measure_theory.integral.periodic import data.zmod.quotient /-! # Measure-theoretic results about the additive circle The file is a place to collect measure-theoretic results about the additive circle. ## Main definitions: * `add_circle.closed_ball_ae_eq_ball`: open and closed balls in the additive circle are almost equal * `add_circle.is_add_fundamental_domain_of_ae_ball`: a ball is a fundamental domain for rational angle rotation in the additive circle -/ open set function filter measure_theory measure_theory.measure metric open_locale measure_theory pointwise big_operators topological_space ennreal namespace add_circle variables {T : ℝ} [hT : fact (0 < T)] include hT lemma closed_ball_ae_eq_ball {x : add_circle T} {ε : ℝ} : closed_ball x ε =ᵐ[volume] ball x ε := begin cases le_or_lt ε 0 with hε hε, { rw [ball_eq_empty.mpr hε, ae_eq_empty, volume_closed_ball, min_eq_right (by linarith [hT.out] : 2 * ε ≤ T), ennreal.of_real_eq_zero], exact mul_nonpos_of_nonneg_of_nonpos zero_le_two hε, }, { suffices : volume (closed_ball x ε) ≤ volume (ball x ε), { exact (ae_eq_of_subset_of_measure_ge ball_subset_closed_ball this measurable_set_ball (measure_ne_top _ _)).symm, }, have : tendsto (λ δ, volume (closed_ball x δ)) (𝓝[<] ε) (𝓝 $ volume (closed_ball x ε)), { simp_rw volume_closed_ball, refine ennreal.tendsto_of_real (tendsto.min tendsto_const_nhds $ tendsto.const_mul _ _), convert (@monotone_id ℝ _).tendsto_nhds_within_Iio ε, simp, }, refine le_of_tendsto this (mem_nhds_within_Iio_iff_exists_Ioo_subset.mpr ⟨0, hε, λ r hr, _⟩), exact measure_mono (closed_ball_subset_ball hr.2), }, end /-- Let `G` be the subgroup of `add_circle T` generated by a point `u` of finite order `n : ℕ`. Then any set `I` that is almost equal to a ball of radius `T / 2n` is a fundamental domain for the action of `G` on `add_circle T` by left addition. -/ lemma is_add_fundamental_domain_of_ae_ball (I : set $ add_circle T) (u x : add_circle T) (hu : is_of_fin_add_order u) (hI : I =ᵐ[volume] ball x (T / (2 * add_order_of u))) : is_add_fundamental_domain (add_subgroup.zmultiples u) I := begin set G := add_subgroup.zmultiples u, set n := add_order_of u, set B := ball x (T / (2 * n)), have hn : 1 ≤ (n : ℝ), { norm_cast, linarith [add_order_of_pos' hu], }, refine is_add_fundamental_domain.mk_of_measure_univ_le _ _ _ _, { -- `null_measurable_set I volume` exact (measurable_set_ball.null_measurable_set.congr hI.symm), }, { -- `∀ (g : G), g ≠ 0 → ae_disjoint volume (g +ᵥ I) I` rintros ⟨g, hg⟩ hg', replace hg' : g ≠ 0, by simpa only [ne.def, add_subgroup.mk_eq_zero_iff] using hg', change ae_disjoint volume (g +ᵥ I) I, refine ae_disjoint.congr (disjoint.ae_disjoint _) ((quasi_measure_preserving_add_left volume (-g)).vadd_ae_eq_of_ae_eq g hI) hI, have hBg : g +ᵥ B = ball (g + x) (T / (2 * n)), { rw [add_comm g x, ← singleton_add_ball _ x g, add_ball, thickening_singleton], }, rw hBg, apply ball_disjoint_ball, rw [dist_eq_norm, add_sub_cancel, div_mul_eq_div_div, ← add_div, ← add_div, add_self_div_two, div_le_iff' (by positivity : 0 < (n : ℝ)), ← nsmul_eq_mul], refine (le_add_order_smul_norm_of_is_of_fin_add_order (hu.of_mem_zmultiples hg) hg').trans (nsmul_le_nsmul (norm_nonneg g) _), exact nat.le_of_dvd (add_order_of_pos_iff.mpr hu) (add_order_of_dvd_of_mem_zmultiples hg), }, { -- `∀ (g : G), quasi_measure_preserving (has_vadd.vadd g) volume volume` exact (λ g, quasi_measure_preserving_add_left volume g), }, { -- `volume univ ≤ ∑' (g : G), volume (g +ᵥ I)` replace hI : I =ᵐ[volume] closed_ball x (T / (2 * ↑n)) := hI.trans closed_ball_ae_eq_ball.symm, haveI : fintype G := @fintype.of_finite _ hu.finite_zmultiples, have hG_card : (finset.univ : finset G).card = n, { show _ = add_order_of u, rw [add_order_eq_card_zmultiples', nat.card_eq_fintype_card], refl }, simp_rw [measure_vadd], rw [add_circle.measure_univ, tsum_fintype, finset.sum_const, measure_congr hI, volume_closed_ball, ← ennreal.of_real_nsmul, mul_div, mul_div_mul_comm, div_self (@two_ne_zero ℝ _ _ _ _), one_mul, min_eq_right (div_le_self hT.out.le hn), hG_card, nsmul_eq_mul, mul_div_cancel' T (lt_of_lt_of_le zero_lt_one hn).ne.symm], exact le_refl _, }, end lemma volume_of_add_preimage_eq (s I : set $ add_circle T) (u x : add_circle T) (hu : is_of_fin_add_order u) (hs : (u +ᵥ s : set $ add_circle T) =ᵐ[volume] s) (hI : I =ᵐ[volume] ball x (T / (2 * add_order_of u))) : volume s = add_order_of u • volume (s ∩ I) := begin let G := add_subgroup.zmultiples u, haveI : fintype G := @fintype.of_finite _ hu.finite_zmultiples, have hsG : ∀ (g : G), (g +ᵥ s : set $ add_circle T) =ᵐ[volume] s, { rintros ⟨y, hy⟩, exact (vadd_ae_eq_self_of_mem_zmultiples hs hy : _), }, rw [(is_add_fundamental_domain_of_ae_ball I u x hu hI).measure_eq_card_smul_of_vadd_ae_eq_self s hsG, add_order_eq_card_zmultiples' u, nat.card_eq_fintype_card], end end add_circle
347edc671c675554108802ac4d1e8ad5a5841078
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/hott/580.hlean
e48e83b3a3d5d4ccb62558f9cdeae2e79b6604ba
[ "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
359
hlean
section parameters (A : Type) (a b z : A) (add : A → A → A) (le : A → A → Type₀) local notation 0 := z local infix + := add local infix ≤ := le definition add_zero (x : A) : x + 0 = x := sorry set_option pp.universes true definition le_add_of_nonneg_right (H : a + 0 ≤ a + b) : a ≤ a + b := begin rewrite add_zero at H, exact H end end
18705930326df3884fb90b5ad21c35f421da8ae4
63abd62053d479eae5abf4951554e1064a4c45b4
/src/analysis/convex/extrema.lean
7cdb67adfffcf57ce208f83026c44b068eb815fc
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
5,441
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import analysis.calculus.local_extr import topology.algebra.affine /-! # Minima and maxima of convex functions We show that if a function `f : E → β` is convex, then a local minimum is also a global minimum, and likewise for concave functions. -/ variables {E β: Type*} [add_comm_group E] [topological_space E] [module ℝ E] [topological_add_group E] [topological_vector_space ℝ E] [linear_ordered_add_comm_group β] [semimodule ℝ β] [ordered_semimodule ℝ β] {s : set E} open set filter open_locale classical /-- Helper lemma for the more general case: `is_min_on.of_is_local_min_on_of_convex_on`. -/ lemma is_min_on.of_is_local_min_on_of_convex_on_Icc {f : ℝ → β} {a b : ℝ} (a_lt_b : a < b) (h_local_min : is_local_min_on f (Icc a b) a) (h_conv : convex_on (Icc a b) f) : ∀ x ∈ Icc a b, f a ≤ f x := begin by_contradiction H_cont, push_neg at H_cont, rcases H_cont with ⟨x, ⟨h_ax, h_xb⟩, fx_lt_fa⟩, obtain ⟨z, hz, ge_on_nhd⟩ : ∃ z > a, ∀ y ∈ (Icc a z), f y ≥ f a, { rcases eventually_iff_exists_mem.mp h_local_min with ⟨U, U_in_nhds_within, fy_ge_fa⟩, rw [nhds_within_Icc_eq_nhds_within_Ici a_lt_b, mem_nhds_within_Ici_iff_exists_Icc_subset] at U_in_nhds_within, rcases U_in_nhds_within with ⟨ε, ε_in_Ioi, Ioc_in_U⟩, exact ⟨ε, mem_Ioi.mp ε_in_Ioi, λ y y_in_Ioc, fy_ge_fa y $ Ioc_in_U y_in_Ioc⟩ }, have a_lt_x : a < x := lt_of_le_of_ne h_ax (λ H, by subst H; exact lt_irrefl (f a) fx_lt_fa), have lt_on_nhd : ∀ y ∈ Ioc a x, f y < f a, { intros y y_in_Ioc, rcases (convex.mem_Ioc a_lt_x).mp y_in_Ioc with ⟨ya, yx, ya_pos, yx_pos, yax, y_combo⟩, calc f y = f (ya * a + yx * x) : by rw [y_combo] ... ≤ ya • f a + yx • f x : h_conv.2 (left_mem_Icc.mpr (le_of_lt a_lt_b)) ⟨h_ax, h_xb⟩ (ya_pos) (le_of_lt yx_pos) yax ... < ya • f a + yx • f a : add_lt_add_left (smul_lt_smul_of_pos fx_lt_fa yx_pos) (ya • f a) ... = f a : by rw [←add_smul, yax, one_smul] }, by_cases h_xz : x ≤ z, { exact not_lt_of_ge (ge_on_nhd x (show x ∈ Icc a z, by exact ⟨h_ax, h_xz⟩)) fx_lt_fa, }, { have h₁ : z ∈ Ioc a x := ⟨hz, le_of_not_ge h_xz⟩, have h₂ : z ∈ Icc a z := ⟨le_of_lt hz, le_refl z⟩, exact not_lt_of_ge (ge_on_nhd z h₂) (lt_on_nhd z h₁) } end /-- A local minimum of a convex function is a global minimum, restricted to a set `s`. -/ lemma is_min_on.of_is_local_min_on_of_convex_on {f : E → β} {a : E} (a_in_s : a ∈ s) (h_localmin: is_local_min_on f s a) (h_conv : convex_on s f) : ∀ x ∈ s, f a ≤ f x := begin by_contradiction H_cont, push_neg at H_cont, rcases H_cont with ⟨x, ⟨x_in_s, fx_lt_fa⟩⟩, let g : ℝ →ᵃ[ℝ] E := affine_map.line_map a x, have hg0 : g 0 = a := affine_map.line_map_apply_zero a x, have hg1 : g 1 = x := affine_map.line_map_apply_one a x, have fg_local_min_on : is_local_min_on (f ∘ g) (g ⁻¹' s) 0, { rw ←hg0 at h_localmin, refine is_local_min_on.comp_continuous_on h_localmin subset.rfl (continuous.continuous_on (affine_map.line_map_continuous)) _, simp [mem_preimage, hg0, a_in_s] }, have fg_min_on : ∀ x ∈ (Icc 0 1 : set ℝ), (f ∘ g) 0 ≤ (f ∘ g) x, { have Icc_in_s' : Icc 0 1 ⊆ (g ⁻¹' s), { have h0 : (0 : ℝ) ∈ (g ⁻¹' s) := by simp [mem_preimage, a_in_s], have h1 : (1 : ℝ) ∈ (g ⁻¹' s) := by simp [mem_preimage, hg1, x_in_s], rw ←segment_eq_Icc (show (0 : ℝ) ≤ 1, by linarith), exact (convex.affine_preimage g h_conv.1).segment_subset (by simp [mem_preimage, hg0, a_in_s]) (by simp [mem_preimage, hg1, x_in_s]) }, have fg_local_min_on' : is_local_min_on (f ∘ g) (Icc 0 1) 0 := is_local_min_on.on_subset fg_local_min_on Icc_in_s', refine is_min_on.of_is_local_min_on_of_convex_on_Icc (by linarith) fg_local_min_on' _, exact (convex_on.comp_affine_map g h_conv).subset Icc_in_s' (convex_Icc 0 1) }, have gx_lt_ga : (f ∘ g) 1 < (f ∘ g) 0 := by simp [hg1, fx_lt_fa, hg0], exact not_lt_of_ge (fg_min_on 1 (mem_Icc.mpr ⟨zero_le_one, le_refl 1⟩)) gx_lt_ga, end /-- A local maximum of a concave function is a global maximum, restricted to a set `s`. -/ lemma is_max_on.of_is_local_max_on_of_concave_on {f : E → β} {a : E} (a_in_s : a ∈ s) (h_localmax: is_local_max_on f s a) (h_conc : concave_on s f) : ∀ x ∈ s, f x ≤ f a := @is_min_on.of_is_local_min_on_of_convex_on _ (order_dual β) _ _ _ _ _ _ _ _ s f a a_in_s h_localmax h_conc /-- A local minimum of a convex function is a global minimum. -/ lemma is_min_on.of_is_local_min_of_convex_univ {f : E → β} {a : E} (h_local_min : is_local_min f a) (h_conv : convex_on univ f) : ∀ x, f a ≤ f x := λ x, (is_min_on.of_is_local_min_on_of_convex_on (mem_univ a) (is_local_min.on h_local_min univ) h_conv) x (mem_univ x) /-- A local maximum of a concave function is a global maximum. -/ lemma is_max_on.of_is_local_max_of_convex_univ {f : E → β} {a : E} (h_local_max : is_local_max f a) (h_conc : concave_on univ f) : ∀ x, f x ≤ f a := @is_min_on.of_is_local_min_of_convex_univ _ (order_dual β) _ _ _ _ _ _ _ _ f a h_local_max h_conc
6188e999fc2d585b5a5817bed90872228571b10d
7fc0ec5c526f706107537a6e2e34ac4cdf88d232
/src/linear_algebra/monoid_star_algebra.lean
3e805bf0eee8498cedca52a6af61ce394e2ff2e4
[ "Apache-2.0" ]
permissive
fpvandoorn/group-representations
7440a81f2ac9e0d2defa44dc1643c3167f7a2d99
bd9d72311749187d3bd4f542d5eab83e8341856c
refs/heads/master
1,684,128,141,684
1,623,338,135,000
1,623,338,135,000
256,117,709
0
2
null
null
null
null
UTF-8
Lean
false
false
26,917
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 data.finsupp import ring_theory.algebra import linear_algebra.star_algebra import topology.algebra.infinite_sum import data.monoid_algebra /-! # Monoid star algebras This is formally parallel to monoid_star_algebra, but instead of taking finite formal combinations of the generators, we take L^1 combinations. We take the measure to be the sum over all elements. This makes the convolution product definable by restricting the sum ∑_x,y f(x) g(y) to x*y = a. Ideally we would take the definitions from monoid_algebra, interpreted formally, and check the summability conditions. This requires generalizing finsupp to summable or some stronger norm condition (we could also use ℓ_2). NOTE: we are trying to use summable as defined in topology.algebra.infinite_sum but this is NOT the same as ℓ_1 whose definition involves the sum of the norm of the elements. So we would rather use l1_space but using the discreteness to define the convolution. ## 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_star_algebra k G := monoid_star_algebra k (multiplicative G)`, but the definitional equality `multiplicative G = G` leaks through everywhere, and seems impossible to use. -/ noncomputable theory open_locale classical open finset finsupp universes u₁ u₂ u₃ variables (k : Type u₁) (G : Type u₂) section variables [add_comm_monoid k] [topological_space k] [monoid G] /-- 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. -/ -- this is not right but we want a similar class of summable functions. @[derive [inhabited, add_comm_monoid]] def monoid_star_algebra : Type (max u₁ u₂) := G →₀ k end namespace monoid_star_algebra variables {k G} local attribute [reducible] monoid_star_algebra section variables [add_comm_monoid k] [topological_space k] [monoid G] /-- The product of `f g : monoid_star_algebra k G` is the summable 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.) -/ def mul_def1 (f g : monoid_star_algebra k G) := (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) #check mul_def1 lemma mul_convergence (f g : monoid_star_algebra k G) (hf : summable f) (hg : summable g) : summable (mul_def1 f g) := begin unfold summable at *, unfold mul_def1, rcases hf, rcases hg, end instance : has_mul (monoid_star_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)⟩ lemma mul_def {f g : monoid_star_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) := rfl lemma mul_apply (f g : monoid_star_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 (f g : monoid_star_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 * p.2 = x) : (f * g) x = s.sum (λ p, f p.1 * g p.2) := let F : G × G → k := λ p, if p.1 * p.2 = x then f p.1 * g p.2 else 0 in calc (f * g) x = (f.support.sum $ λ a₁, g.support.sum $ λ a₂, F (a₁, a₂)) : mul_apply f g x ... = (f.support.product g.support).sum F : finset.sum_product.symm ... = ((f.support.product g.support).filter (λ p : G × G, p.1 * p.2 = x)).sum (λ p, f p.1 * g p.2) : (finset.sum_filter _ _).symm ... = (s.filter (λ p : G × G, p.1 ∈ f.support ∧ p.2 ∈ g.support)).sum (λ p, f p.1 * g p.2) : sum_congr (by { ext, simp [hs, and_comm] }) (λ _ _, rfl) ... = s.sum (λ p, 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 end section variables [semiring k] [monoid G] lemma support_mul (a b : monoid_star_algebra k G) : (a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ * a₂}) := subset.trans support_sum $ bind_mono $ assume a₁ _, subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset /-- 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_star_algebra k G) := ⟨single 1 1⟩ lemma one_def : (1 : monoid_star_algebra k G) = single 1 1 := rfl -- TODO: the simplifier unfolds 0 in the instance proof! protected lemma zero_mul (f : monoid_star_algebra k G) : 0 * f = 0 := by simp only [mul_def, sum_zero_index] protected lemma mul_zero (f : monoid_star_algebra k G) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero] private lemma left_distrib (a b c : monoid_star_algebra k G) : a * (b + c) = a * b + a * c := 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] private lemma right_distrib (a b c : monoid_star_algebra k G) : (a + b) * c = a * c + b * c := 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] instance : semiring (monoid_star_algebra k G) := { one := 1, mul := (*), 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], zero_mul := monoid_star_algebra.zero_mul, mul_zero := monoid_star_algebra.mul_zero, 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], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } @[simp] lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : monoid_star_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 {a : G} {b : k} : ∀ n : ℕ, (single a b : monoid_star_algebra k G)^n = single (a^n) (b ^ n) | 0 := rfl | (n+1) := by simp only [pow_succ, single_pow n, single_mul_single] section variables (k G) /-- Embedding of a monoid into its monoid algebra. -/ def of : G →* monoid_star_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, map_mul' := λ a b, by rw [single_mul_single, one_mul] } end @[simp] lemma of_apply (a : G) : of k G a = single a 1 := rfl lemma mul_single_apply_aux (f : monoid_star_algebra k G) {r : k} {x y z : G} (H : ∀ a, a * x = z ↔ a = y) : (f * single x r) z = f y * r := 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) : -- different `decidable` instances make it not trivial by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl } ... = 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 (f : monoid_star_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 (f : monoid_star_algebra k G) {r : k} {x y z : G} (H : ∀ a, x * a = y ↔ a = z) : (single x r * f) y = r * f z := 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 this ... = f.sum (λ a b, ite (a = z) (r * b) 0) : by { simp only [H], congr, ext; split_ifs; refl } ... = 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 (f : monoid_star_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] end instance [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_star_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_star_algebra.semiring } instance [ring k] : has_neg (monoid_star_algebra k G) := by apply_instance instance [ring k] [monoid G] : ring (monoid_star_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. monoid_star_algebra.semiring } instance [comm_ring k] [comm_monoid G] : comm_ring (monoid_star_algebra k G) := { mul_comm := mul_comm, .. monoid_star_algebra.ring} instance [semiring k] : has_scalar k (monoid_star_algebra k G) := finsupp.has_scalar instance [semiring k] : semimodule k (monoid_star_algebra k G) := finsupp.semimodule G k instance [ring k] : module k (monoid_star_algebra k G) := by {delta monoid_star_algebra, apply_instance } lemma single_one_comm [comm_semiring k] [monoid G] (r : k) (f : monoid_star_algebra k G) : single 1 r * f = f * single 1 r := by { ext, rw [single_one_mul_apply, mul_single_one_apply, mul_comm] } instance [comm_semiring k] [monoid G] : algebra k (monoid_star_algebra k G) := { to_fun := single 1, map_one' := rfl, map_mul' := λ x y, by rw [single_mul_single, one_mul], map_zero' := single_zero, map_add' := λ x y, single_add, smul_def' := λ r a, ext (λ _, smul_apply.trans (single_one_mul_apply _ _ _).symm), commutes' := λ r f, ext $ λ _, by rw [single_one_mul_apply, mul_single_one_apply, mul_comm] } @[simp] lemma coe_algebra_map [comm_semiring k] [monoid G] : (algebra_map k (monoid_star_algebra k G) : k → monoid_star_algebra k G) = single 1 := rfl lemma single_eq_algebra_map_mul_of [comm_semiring k] [monoid G] (a : G) (b : k) : single a b = (algebra_map k (monoid_star_algebra k G) : k → monoid_star_algebra k G) b * of k G a := by simp instance [group G] [semiring k] : distrib_mul_action G (monoid_star_algebra k G) := finsupp.comap_distrib_mul_action_self section lift variables (k G) [comm_semiring k] [monoid G] (R : Type u₃) [semiring R] [algebra k R] /-- Any monoid homomorphism `G →* R` can be lifted to an algebra homomorphism `monoid_star_algebra k G →ₐ[k] R`. -/ def lift : (G →* R) ≃ (monoid_star_algebra k G →ₐ[k] R) := { inv_fun := λ f, (f : monoid_star_algebra k G →* R).comp (of k G), to_fun := λ F, { to_fun := λ f, f.sum (λ a b, b • F a), map_one' := by { rw [one_def, sum_single_index, one_smul, F.map_one], apply zero_smul }, map_mul' := begin intros f g, rw [mul_def, finsupp.sum_mul, finsupp.sum_sum_index]; try { intros, simp only [zero_smul, add_smul], done }, refine finset.sum_congr rfl (λ a ha, _), simp only [], rw [finsupp.mul_sum, finsupp.sum_sum_index]; try { intros, simp only [zero_smul, add_smul], done }, refine finset.sum_congr rfl (λ a' ha', _), simp only [], rw [sum_single_index, F.map_mul, algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_smul, mul_comm], apply zero_smul end, map_zero' := sum_zero_index, map_add' := λ f g, by rw [sum_add_index]; intros; simp only [zero_smul, add_smul], commutes' := λ r, by rw [coe_algebra_map, sum_single_index, F.map_one, algebra.smul_def, mul_one]; apply zero_smul }, left_inv := λ f, begin ext x, simp [sum_single_index] end, right_inv := λ F, begin ext f, conv_rhs { rw ← f.sum_single }, simp [← F.map_smul, finsupp.sum, ← F.map_sum] end } variables {k G R} lemma lift_apply (F : G →* R) (f : monoid_star_algebra k G) : lift k G R F f = f.sum (λ a b, b • F a) := rfl @[simp] lemma lift_symm_apply (F : monoid_star_algebra k G →ₐ[k] R) (x : G) : (lift k G R).symm F x = F (single x 1) := rfl lemma lift_of (F : G →* R) (x) : lift k G R F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : G →* R) (a b) : lift k G R F (single a b) = b • F a := by rw [single_eq_algebra_map_mul_of, ← algebra.smul_def, alg_hom.map_smul, lift_of] lemma lift_unique' (F : monoid_star_algebra k G →ₐ[k] R) : F = lift k G R ((F : monoid_star_algebra k G →* R).comp (of k G)) := ((lift k G R).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_star_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : monoid_star_algebra k G →ₐ[k] R) (f : monoid_star_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } /-- A `k`-algebra homomorphism from `monoid_star_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma alg_hom_ext ⦃φ₁ φ₂ : monoid_star_algebra k G →ₐ[k] R⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := (lift k G R).symm.injective $ monoid_hom.ext h end lift section 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 [group G] [comm_ring k] (V : Type u₃) [add_comm_group V] [module (monoid_star_algebra k G) V] (g : G) : (module.restrict_scalars k (monoid_star_algebra k G) V) →ₗ[k] (module.restrict_scalars k (monoid_star_algebra k G) 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, by simp only [module.restrict_scalars_smul_def, coe_algebra_map, ←mul_smul, single_one_comm], }. @[simp] lemma group_smul.linear_map_apply [group G] [comm_ring k] (V : Type u₃) [add_comm_group V] [module (monoid_star_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 [group G] [comm_ring k] {V : Type u₃} {gV : add_comm_group V} {mV : module (monoid_star_algebra k G) V} {W : Type u₃} {gW : add_comm_group W} {mW : module (monoid_star_algebra k G) W} (f : (module.restrict_scalars k (monoid_star_algebra k G) V) →ₗ[k] (module.restrict_scalars k (monoid_star_algebra k G) 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_star_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, rw [add_smul, linear_map.map_add, w, add_smul, add_left_inj, single_eq_algebra_map_mul_of, ←smul_smul, ←smul_smul], erw [f.map_smul, h g v], refl, } end, } @[simp] lemma equivariant_of_linear_of_comm_apply (v : V) : (equivariant_of_linear_of_comm f h) v = f v := rfl end end universe ui variable {ι : Type ui} lemma prod_single [comm_semiring k] [comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : s.prod (λi, single (a i) (b i)) = single (s.prod a) (s.prod b) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, prod_insert has, prod_insert has] section -- We now prove some additional statements that hold for group algebras. variables [semiring k] [group G] @[simp] lemma mul_single_apply (f : monoid_star_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_star_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_star_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 (f a) * 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_star_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 (g a)) x) : by rw [← finsupp.sum_apply, ← finsupp.mul_sum, g.sum_single] ... = _ : by simp only [mul_single_apply, finsupp.sum] end end monoid_star_algebra 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_star_algebra := G →₀ k end namespace add_monoid_star_algebra variables {k G} local attribute [reducible] add_monoid_star_algebra section variables [semiring k] [add_monoid G] /-- The product of `f g : add_monoid_star_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_star_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_star_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl lemma mul_apply (f g : add_monoid_star_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 support_mul (a b : add_monoid_star_algebra k G) : (a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) := subset.trans support_sum $ bind_mono $ assume a₁ _, subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset /-- 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_star_algebra k G) := ⟨single 0 1⟩ lemma one_def : (1 : add_monoid_star_algebra k G) = single 0 1 := rfl -- TODO: the simplifier unfolds 0 in the instance proof! protected lemma zero_mul (f : add_monoid_star_algebra k G) : 0 * f = 0 := by simp only [mul_def, sum_zero_index] protected lemma mul_zero (f : add_monoid_star_algebra k G) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero] private lemma left_distrib (a b c : add_monoid_star_algebra k G) : a * (b + c) = a * b + a * c := 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] private lemma right_distrib (a b c : add_monoid_star_algebra k G) : (a + b) * c = a * c + b * c := 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] instance : semiring (add_monoid_star_algebra k G) := { one := 1, mul := (*), 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], zero_mul := add_monoid_star_algebra.zero_mul, mul_zero := add_monoid_star_algebra.mul_zero, 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], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : add_monoid_star_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])) section variables (k G) /-- Embedding of a monoid into its monoid algebra. -/ def of : multiplicative G →* add_monoid_star_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, map_mul' := λ a b, by { rw [single_mul_single, one_mul], refl } } end @[simp] lemma of_apply (a : G) : of k G a = single a 1 := rfl lemma mul_single_apply_aux (f : add_monoid_star_algebra k G) (r : k) (x y z : G) (H : ∀ a, a + x = z ↔ a = y) : (f * single x r) z = f y * r := 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) : -- different `decidable` instances make it not trivial by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl } ... = 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_zero_apply (f : add_monoid_star_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 (f : add_monoid_star_algebra k G) (r : k) (x y z : G) (H : ∀ a, x + a = y ↔ a = z) : (single x r * f) y = r * f z := 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 this ... = f.sum (λ a b, ite (a = z) (r * b) 0) : by { simp only [H], congr, ext; split_ifs; refl } ... = 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_zero_mul_apply (f : add_monoid_star_algebra k G) (r : k) (x : G) : (single 0 r * f) x = r * f x := f.single_mul_apply_aux r _ _ _ $ λ a, by rw [zero_add] end instance [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_star_algebra k G) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [add_comm] end, .. add_monoid_star_algebra.semiring } instance [ring k] : has_neg (add_monoid_star_algebra k G) := by apply_instance instance [ring k] [add_monoid G] : ring (add_monoid_star_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. add_monoid_star_algebra.semiring } instance [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_star_algebra k G) := { mul_comm := mul_comm, .. add_monoid_star_algebra.ring} instance [semiring k] : has_scalar k (add_monoid_star_algebra k G) := finsupp.has_scalar instance [semiring k] : semimodule k (add_monoid_star_algebra k G) := finsupp.semimodule G k instance [ring k] : module k (add_monoid_star_algebra k G) := by { delta add_monoid_star_algebra, apply_instance } instance [comm_semiring k] [add_monoid G] : algebra k (add_monoid_star_algebra k G) := { to_fun := single 0, map_one' := rfl, map_mul' := λ x y, by rw [single_mul_single, zero_add], map_zero' := single_zero, map_add' := λ x y, single_add, smul_def' := λ r a, by { ext x, exact smul_apply.trans (single_zero_mul_apply _ _ _).symm }, commutes' := λ r f, show single 0 r * f = f * single 0 r, by ext; rw [single_zero_mul_apply, mul_single_zero_apply, mul_comm] } @[simp] lemma coe_algebra_map [comm_semiring k] [add_monoid G] : (algebra_map k (add_monoid_star_algebra k G) : k → add_monoid_star_algebra k G) = single 0 := rfl /-- Any monoid homomorphism `multiplicative G →* R` can be lifted to an algebra homomorphism `add_monoid_star_algebra k G →ₐ[k] R`. -/ def lift [comm_semiring k] [add_monoid G] {R : Type u₃} [semiring R] [algebra k R] : (multiplicative G →* R) ≃ (add_monoid_star_algebra k G →ₐ[k] R) := { inv_fun := λ f, ((f : add_monoid_star_algebra k G →+* R) : add_monoid_star_algebra k G →* R).comp (of k G), to_fun := λ F, { to_fun := λ f, f.sum (λ a b, b • F a), map_one' := by { rw [one_def, sum_single_index, one_smul], erw [F.map_one], apply zero_smul }, map_mul' := begin intros f g, rw [mul_def, finsupp.sum_mul, finsupp.sum_sum_index]; try { intros, simp only [zero_smul, add_smul], done }, refine finset.sum_congr rfl (λ a ha, _), simp only [], rw [finsupp.mul_sum, finsupp.sum_sum_index]; try { intros, simp only [zero_smul, add_smul], done }, refine finset.sum_congr rfl (λ a' ha', _), simp only [], rw [sum_single_index], erw [F.map_mul], rw [algebra.mul_smul_comm, algebra.smul_mul_assoc, smul_smul, mul_comm], apply zero_smul end, map_zero' := sum_zero_index, map_add' := λ f g, by rw [sum_add_index]; intros; simp only [zero_smul, add_smul], commutes' := λ r, begin rw [coe_algebra_map, sum_single_index], erw [F.map_one], rw [algebra.smul_def, mul_one], apply zero_smul end, }, left_inv := λ f, begin ext x, simp [sum_single_index] end, right_inv := λ F, begin ext f, conv_rhs { rw ← f.sum_single }, simp [← F.map_smul, finsupp.sum, ← F.map_sum] end } -- It is hard to state the equivalent of `distrib_mul_action G (monoid_star_algebra k G)` -- because we've never discussed actions of additive groups. universe ui variable {ι : Type ui} lemma prod_single [comm_semiring k] [add_comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : s.prod (λi, single (a i) (b i)) = single (s.sum a) (s.prod b) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, sum_insert has, prod_insert has] end add_monoid_star_algebra
fdfb678691bba56b25a79be677772b9b37e4c6ae
618003631150032a5676f229d13a079ac875ff77
/src/linear_algebra/lagrange.lean
058eed1e48129eec201e10bc3f369aec1a7d7dd2
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
6,946
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau. -/ import ring_theory.polynomial algebra.big_operators /-! # Lagrange interpolation ## Main definitions * `lagrange.basis s x` where `s : finset F` and `x : F`: the Lagrange basis polynomial that evaluates to `1` at `x` and `0` at other elements of `s`. * `lagrange.interpolate s f` where `s : finset F` and `f : s → F`: the Lagrange interpolant that evaluates to `f x` at `x` for `x ∈ s`. -/ noncomputable theory open_locale big_operators classical universe u namespace lagrange variables {F : Type u} [decidable_eq F] [field F] (s : finset F) variables {F' : Type u} [field F'] (s' : finset F') open polynomial /-- Lagrange basis polynomials that evaluate to 1 at `x` and 0 at other elements of `s`. -/ def basis (x : F) : polynomial F := ∏ y in s.erase x, C (x - y)⁻¹ * (X - C y) @[simp] theorem basis_empty (x : F) : basis ∅ x = 1 := rfl @[simp] theorem eval_basis_self (x : F) : (basis s x).eval x = 1 := begin rw [basis, ← (s.erase x).prod_hom (eval x), finset.prod_eq_one], intros y hy, simp_rw [eval_mul, eval_sub, eval_C, eval_X], exact inv_mul_cancel (sub_ne_zero_of_ne (finset.ne_of_mem_erase hy).symm) end @[simp] theorem eval_basis_ne (x y : F) (h1 : y ∈ s) (h2 : y ≠ x) : (basis s x).eval y = 0 := begin rw [basis, ← (s.erase x).prod_hom (eval y), finset.prod_eq_zero (finset.mem_erase.2 ⟨h2, h1⟩)], simp_rw [eval_mul, eval_sub, eval_C, eval_X, sub_self, mul_zero] end theorem eval_basis (x y : F) (h : y ∈ s) : (basis s x).eval y = if y = x then 1 else 0 := by { split_ifs with H, { subst H, apply eval_basis_self }, { exact eval_basis_ne s x y h H } } @[simp] theorem nat_degree_basis (x : F) (hx : x ∈ s) : (basis s x).nat_degree = s.card - 1 := begin unfold basis, generalize hsx : s.erase x = sx, have : x ∉ sx := hsx ▸ finset.not_mem_erase x s, rw [← finset.insert_erase hx, hsx, finset.card_insert_of_not_mem this, nat.add_sub_cancel], clear hx hsx s, revert this, apply sx.induction_on, { intros hx, rw [finset.prod_empty, nat_degree_one], refl }, { intros y s hys ih hx, rw [finset.mem_insert, not_or_distrib] at hx, have h1 : C (x - y)⁻¹ ≠ C 0 := λ h, hx.1 (eq_of_sub_eq_zero $ inv_eq_zero.1 $ C_inj.1 h), have h2 : X ^ 1 - C y ≠ 0 := by convert X_pow_sub_C_ne_zero zero_lt_one y, rw C_0 at h1, rw pow_one at h2, rw [finset.prod_insert hys, nat_degree_mul_eq (mul_ne_zero h1 h2), ih hx.2, finset.card_insert_of_not_mem hys, nat_degree_mul_eq h1 h2, nat_degree_C, zero_add, nat_degree, degree_X_sub_C, add_comm], refl, rw [ne, finset.prod_eq_zero_iff], rintro ⟨z, hzs, hz⟩, rw mul_eq_zero at hz, cases hz with hz hz, { rw [← C_0, C_inj, inv_eq_zero, sub_eq_zero] at hz, exact hx.2 (hz.symm ▸ hzs) }, { rw ← pow_one (X : polynomial F) at hz, exact X_pow_sub_C_ne_zero zero_lt_one _ hz } } end variables (f : (↑s : set F) → F) /-- Lagrange interpolation: given a finset `s` and a function `f : s → F`, `interpolate s f` is the unique polynomial of degree `< s.card` that takes value `f x` on all `x` in `s`. -/ def interpolate : polynomial F := ∑ x in s.attach, C (f x) * basis s x @[simp] theorem interpolate_empty (f) : interpolate (∅ : finset F) f = 0 := rfl @[simp] theorem eval_interpolate (x) (H : x ∈ s) : eval x (interpolate s f) = f ⟨x, H⟩ := begin rw [interpolate, ← finset.sum_hom _ (eval x), finset.sum_eq_single (⟨x, H⟩ : { x // x ∈ s })], { rw [eval_mul, eval_C, subtype.coe_mk, eval_basis_self, mul_one] }, { rintros ⟨y, hy⟩ _ hyx, rw [eval_mul, subtype.coe_mk, eval_basis_ne s y x H, mul_zero], { rintros rfl, exact hyx rfl } }, { intro h, exact absurd (finset.mem_attach _ _) h } end theorem degree_interpolate_lt : (interpolate s f).degree < s.card := if H : s = ∅ then by { subst H, rw [interpolate_empty, degree_zero], exact with_bot.bot_lt_coe _ } else lt_of_le_of_lt (degree_sum_le _ _) $ (finset.sup_lt_iff $ with_bot.bot_lt_coe s.card).2 $ λ b _, calc (C (f b) * basis s b).degree ≤ (C (f b)).degree + (basis s b).degree : degree_mul_le _ _ ... ≤ 0 + (basis s b).degree : add_le_add_right' degree_C_le ... = (basis s b).degree : zero_add _ ... ≤ (basis s b).nat_degree : degree_le_nat_degree ... = (s.card - 1 : ℕ) : by { rw nat_degree_basis s b b.2 } ... < s.card : with_bot.coe_lt_coe.2 (nat.pred_lt $ mt finset.card_eq_zero.1 H) /-- Linear version of `interpolate`. -/ def linterpolate : ((↑s : set F) → F) →ₗ[F] polynomial F := { to_fun := interpolate s, add := λ f g, by { simp_rw [interpolate, ← finset.sum_add_distrib, ← add_mul, ← C_add], refl }, smul := λ c f, by { simp_rw [interpolate, finset.smul_sum, C_mul', smul_smul], refl } } @[simp] lemma interpolate_add (f g) : interpolate s (f + g) = interpolate s f + interpolate s g := (linterpolate s).map_add f g @[simp] lemma interpolate_zero : interpolate s 0 = 0 := (linterpolate s).map_zero @[simp] lemma interpolate_neg (f) : interpolate s (-f) = -interpolate s f := (linterpolate s).map_neg f @[simp] lemma interpolate_sub (f g) : interpolate s (f - g) = interpolate s f - interpolate s g := (linterpolate s).map_sub f g @[simp] lemma interpolate_smul (c : F) (f) : interpolate s (c • f) = c • interpolate s f := (linterpolate s).map_smul c f theorem eq_zero_of_eval_eq_zero {f : polynomial F'} (hf1 : f.degree < s'.card) (hf2 : ∀ x ∈ s', f.eval x = 0) : f = 0 := by_contradiction $ λ hf3, not_le_of_lt hf1 $ calc (s'.card : with_bot ℕ) ≤ f.roots.card : with_bot.coe_le_coe.2 $ finset.card_le_of_subset $ λ x hx, (mem_roots hf3).2 $ hf2 x hx ... ≤ f.degree : card_roots hf3 theorem eq_of_eval_eq {f g : polynomial F'} (hf : f.degree < s'.card) (hg : g.degree < s'.card) (hfg : ∀ x ∈ s', f.eval x = g.eval x) : f = g := eq_of_sub_eq_zero $ eq_zero_of_eval_eq_zero s' (lt_of_le_of_lt (degree_sub_le f g) $ max_lt hf hg) (λ x hx, by rw [eval_sub, hfg x hx, sub_self]) theorem eq_interpolate (f : polynomial F) (hf : f.degree < s.card) : interpolate s (λ x, f.eval x) = f := eq_of_eval_eq s (degree_interpolate_lt s _) hf $ λ x hx, eval_interpolate s _ x hx /-- Lagrange interpolation induces isomorphism between functions from `s` and polynomials of degree less than `s.card`. -/ def fun_equiv_degree_lt : degree_lt F s.card ≃ₗ[F] ((↑s : set F) → F) := { to_fun := λ f x, f.1.eval x, add := λ f g, funext $ λ x, eval_add, smul := λ c f, funext $ λ x, by { rw [pi.smul_apply, smul_eq_mul, ← @eval_C F c _ x, ← eval_mul, eval_C, C_mul'], refl }, inv_fun := λ f, ⟨interpolate s f, mem_degree_lt.2 $ degree_interpolate_lt s f⟩, left_inv := λ f, subtype.eq $ eq_interpolate s f $ mem_degree_lt.1 f.2, right_inv := λ f, funext $ λ ⟨x, hx⟩, eval_interpolate s f x hx } end lagrange
30e076b3aad20bcdbcc76ecdbd937317b4ea3629
3984ab8555ab1e1084e22ef652544acdfc231f27
/src/Regret Minimization in Games with Incomplete Information - template.lean
2be70c4492c764265b7cddb76e92ae06a0c6b191
[]
no_license
mrakgr/CFR-in-Lean
a35c7a478795cc794cc0caff3199cf28c8ee5448
720a3260297bcc158e08833d38964450dcaad2eb
refs/heads/master
1,598,515,917,940
1,572,612,355,000
1,572,612,355,000
217,296,108
0
0
null
null
null
null
UTF-8
Lean
false
false
4,499
lean
import data.rat -- `constant`s are axiomatic definitions. They are inherently noncomputable. constant Infoset : Type constant Policy : Type def maximize {α : Type} : α × list α → (α → ℚ) → ℚ | (x,xs) f := xs.foldl (fun s a, max s (f a)) (f x) def list.fsum {α : Type} : (α → ℚ) → list α → ℚ | f l := l.foldl (fun s a, s + f a) 0 constant Infoset.fsum : (Infoset → ℚ) → Infoset → ℚ -- Compared to the paper, here I am moving the indexing so it obeys the C notation. def nat.fsum (f : ℕ → ℚ) : ℕ → ℚ | 0 := 0 | (n+1) := n.fsum + f n constant σ : ℕ → Policy constant σ_all : (ℕ → Policy) × list (ℕ → Policy) constant Policy.at : Policy → Infoset → Policy → Policy constant Player : Type constant u : Player → Policy → Infoset → ℚ constant D : Infoset → Infoset constant Succ : Player → Infoset → Infoset constant SuccA : Player → Infoset → Policy → Infoset constant π : Player → Policy → Infoset → ℚ constant π_is_probability : ∀ i σ I, 0 <= π i σ I ∧ π i σ I <= 1 constant neg : Player → Player def R.template (update_policy : Policy → Infoset → Policy → Policy) (i : Player) (T : ℕ) (I : Infoset) : ℚ := let u := u i in 1 / T * maximize σ_all (fun σ', T.fsum (fun t, let (σ, σ') := (σ t, σ' t) in let σ' := update_policy σ' I σ in π (neg i) σ I * (u σ' I - u σ I) ) ) def R.full := R.template (fun σ' I σ, σ.at (D I) σ') def R.full.pos (i : Player) (T : ℕ) (I : Infoset) := max (R.full i T I) 0 def R.imm := R.template (fun σ' I σ, σ.at I σ') def R.imm.pos (i : Player) (T : ℕ) (I : Infoset) := max (R.imm i T I) 0 constant A : Infoset → Policy × list Policy constant succ : Player → Policy → Infoset → Policy → Infoset → rat constant succ_is_probability : ∀ i σ I a I', 0 <= succ i σ I a I' ∧ succ i σ I a I' <= 1 def R.full.expanded (i : Player) (T : ℕ) (I : Infoset) : ℚ := let u := u i in 1 / T * (maximize (A I) $ fun a, maximize σ_all $ fun σ', T.fsum $ fun t, let (σ, σ') := (σ t, σ' t) in π (neg i) σ I * (u (σ.at I a) I - u σ I + (Succ i I).fsum (fun I', succ i σ I a I' * (u (σ.at (D I) σ') I' - u σ I'))) ) constant Rfull_eq_expanded (i : Player) (T : ℕ) (I : Infoset) : R.full i T I = R.full.expanded i T I lemma five (i : Player) (T : ℕ) (I : Infoset) : R.full i T I <= R.imm i T I + (Succ i I).fsum (fun I', R.full.pos i T I) := let u := u i in calc R.full i T I = R.full.expanded i T I : Rfull_eq_expanded i T I ... <= 1 / T * (maximize (A I) $ fun a, maximize σ_all $ fun σ', T.fsum $ fun t, let (σ, σ') := (σ t, σ' t) in π (neg i) σ I * (u (σ.at I a) I - u σ I) ) + 1 / T * (maximize (A I) $ fun a, maximize σ_all $ fun σ', T.fsum $ fun t, let (σ, σ') := (σ t, σ' t) in π (neg i) σ I * (SuccA i I a).fsum (fun I', succ i σ I a I' * (u (σ.at (D I) σ') I' - u σ I')) ) : sorry ... = R.imm i T I + 1 / T * (maximize (A I) $ fun a, maximize σ_all $ fun σ', T.fsum $ fun t, let (σ, σ') := (σ t, σ' t) in (SuccA i I a).fsum (fun I', π (neg i) σ I * succ i σ I a I' * (u (σ.at (D I') σ') I' - u σ I')) ) : sorry ... = R.imm i T I + (maximize (A I) $ fun a, (SuccA i I a).fsum $ fun I', 1 / T * (maximize (A I) $ fun a, maximize σ_all $ fun σ', T.fsum $ fun t, let (σ, σ') := (σ t, σ' t) in π (neg i) σ I * succ i σ I a I' * (u (σ.at (D I') σ') I' - u σ I') ) ) : sorry ... = R.imm i T I + (maximize (A I) $ fun a, (SuccA i I a).fsum $ fun I', R.full i T I') : sorry ... <= R.imm i T I + (Succ i I).fsum (fun I', R.full.pos i T I) : sorry lemma six (i : Player) (T : ℕ) (I : Infoset) : R.full i T I <= (D I).fsum (fun I', R.full.pos i T I') := calc R.full i T I <= R.imm i T I + ((Succ i I).fsum $ fun I', (Succ i I').fsum $ fun I'', R.full.pos i T I'') : sorry ... <= R.imm.pos i T I + ((Succ i I).fsum $ fun I', (Succ i I').fsum $ fun I'', R.full.pos i T I'') : sorry ... <= (D I).fsum (fun I', R.full.pos i T I') : sorry
760253e13690a8813f0f791f88bbe1110eb087d1
4d7079ae603c07560e99d1ce35876f769cbb3e24
/src/stability.lean
a62b20c50252222263994123785cf31be16ebe9f
[]
no_license
chasenorman/Formalized-Voting
72493a08aa09d98d0fb589731b842e2d08c991d0
de04e630b83525b042db166670ba97f9952b5691
refs/heads/main
1,687,282,160,284
1,627,155,031,000
1,627,155,031,000
370,472,025
13
0
null
null
null
null
UTF-8
Lean
false
false
2,064
lean
import main import split_cycle open_locale classical variables {V X : Type} def minus_candidate (P : Prof V X) (b : X) : Prof V {x : X // x ≠ b} := λ v x y, P v x.val y.val def strong_stability [fintype V] (F : VSCC) (P : Prof V X) : Prop := ∀ (a b : X) (e : a ≠ b), 0 ≤ margin P a b → (⟨a, e⟩ : {x : X // x ≠ b}) ∈ F V {x : X // x ≠ b} (minus_candidate P b) → a ∈ F V X P lemma margin_eq_margin_minus_candidate [fintype V] {P : Prof V X} (b : X) {x y : X} (h : x ≠ b) (e : y ≠ b) : margin (minus_candidate P b) ⟨x, h⟩ ⟨y, e⟩ = margin P x y := begin obviously, end theorem split_cycle_strong_stability [fintype V] (P : Prof V X) : strong_stability split_cycle P := begin unfold strong_stability, intros a b e m w y, unfold split_cycle at *, unfold max_el_VSCC at *, simp at *, unfold split_cycle_VCCR, unfold split_cycle_CCR, simp at *, use _inst_1, --intro p, by_cases y ≠ b, {specialize w y, specialize w h, unfold split_cycle_VCCR at w, unfold split_cycle_CCR at w, simp at w, cases w with i2 w, intro m2, unfold margin_pos at m2, rw ←(margin_eq_margin_minus_candidate b h e) at m2, change margin_pos (minus_candidate P b) ⟨y, h⟩ ⟨a, e⟩ at m2, unfold margin_pos at w, rw margin_eq_margin i2 _inst_1 at w, specialize w m2, cases w with c w, cases w with y_mem w, cases w with a_mem w, use (c.map subtype.val), simp, use h, exact y_mem, use e, exact a_mem, rw ←margin_eq_margin_minus_candidate b h e, unfold cycle at *, cases w with n w, split, work_on_goal 1 {by_contradiction, push_neg at h, exact n (list.map_eq_nil.mp h),}, rw list.last_map subtype.val n, refine list.chain_map_of_chain subtype.val _ w, obviously, rw margin_eq_margin i2 _inst_1 at ᾰ, obviously,}, push_neg at h, rw h, intro m2, rw margin_antisymmetric at m, exfalso, simp at m, have o : ∀ (n : ℤ), n ≤ 0 → ¬ 0 < n := by omega, exact (o (margin P b a) m) m2, end
09a4479104d2ec349f18d13e3748b59ea75701ff
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/monotonicity/interactive.lean
be3ca23b63c6c8fa47dfaa29f547a6af8b52ce9e
[ "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
23,516
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.monotonicity.basic import control.traversable import control.traversable.derive import data.dlist variables {a b c p : Prop} namespace tactic.interactive open lean lean.parser interactive open interactive.types open tactic local postfix `?`:9001 := optional local postfix *:9001 := many meta inductive mono_function (elab : bool := tt) | non_assoc : expr elab → list (expr elab) → list (expr elab) → mono_function | assoc : expr elab → option (expr elab) → option (expr elab) → mono_function | assoc_comm : expr elab → expr elab → mono_function meta instance : decidable_eq mono_function := by mk_dec_eq_instance meta def mono_function.to_tactic_format : mono_function → tactic format | (mono_function.non_assoc fn xs ys) := do fn' ← pp fn, xs' ← mmap pp xs, ys' ← mmap pp ys, return format!"{fn'} {xs'} _ {ys'}" | (mono_function.assoc fn xs ys) := do fn' ← pp fn, xs' ← pp xs, ys' ← pp ys, return format!"{fn'} {xs'} _ {ys'}" | (mono_function.assoc_comm fn xs) := do fn' ← pp fn, xs' ← pp xs, return format!"{fn'} _ {xs'}" meta instance has_to_tactic_format_mono_function : has_to_tactic_format mono_function := { to_tactic_format := mono_function.to_tactic_format } @[derive traversable] meta structure ac_mono_ctx' (rel : Type) := (to_rel : rel) (function : mono_function) (left right rel_def : expr) @[reducible] meta def ac_mono_ctx := ac_mono_ctx' (option (expr → expr → expr)) @[reducible] meta def ac_mono_ctx_ne := ac_mono_ctx' (expr → expr → expr) meta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format := do fn ← pp ctx.function, l ← pp ctx.left, r ← pp ctx.right, rel ← pp ctx.rel_def, return format!"{{ function := {fn}\n, left := {l}\n, right := {r}\n, rel_def := {rel} }" meta instance has_to_tactic_format_mono_ctx : has_to_tactic_format ac_mono_ctx := { to_tactic_format := ac_mono_ctx.to_tactic_format } meta def as_goal (e : expr) (tac : tactic unit) : tactic unit := do gs ← get_goals, set_goals [e], tac, set_goals gs open list (hiding map) functor dlist section config parameter opt : mono_cfg parameter asms : list expr meta def unify_with_instance (e : expr) : tactic unit := as_goal e $ apply_instance <|> apply_opt_param <|> apply_auto_param <|> tactic.solve_by_elim { lemmas := some asms } <|> reflexivity <|> applyc ``id <|> return () private meta def match_rule_head (p : expr) : list expr → expr → expr → tactic expr | vs e t := (unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e) <|> do (expr.pi _ _ d b) ← return t | failed, v ← mk_meta_var d, match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v) meta def pi_head : expr → tactic expr | (expr.pi n _ t b) := do v ← mk_meta_var t, pi_head (b.instantiate_var v) | e := return e meta def delete_expr (e : expr) : list expr → tactic (option (list expr)) | [] := return none | (x :: xs) := (compare opt e x >> return (some xs)) <|> (map (cons x) <$> delete_expr xs) meta def match_ac' : list expr → list expr → tactic (list expr × list expr × list expr) | es (x :: xs) := do es' ← delete_expr x es, match es' with | (some es') := do (c,l,r) ← match_ac' es' xs, return (x::c,l,r) | none := do (c,l,r) ← match_ac' es xs, return (c,l,x::r) end | es [] := do return ([],es,[]) meta def match_ac (l : list expr) (r : list expr) : tactic (list expr × list expr × list expr) := do (s',l',r') ← match_ac' l r, s' ← mmap instantiate_mvars s', l' ← mmap instantiate_mvars l', r' ← mmap instantiate_mvars r', return (s',l',r') meta def match_prefix : list expr → list expr → tactic (list expr × list expr × list expr) | (x :: xs) (y :: ys) := (do compare opt x y, prod.map ((::) x) id <$> match_prefix xs ys) <|> return ([],x :: xs,y :: ys) | xs ys := return ([],xs,ys) /-- `(prefix,left,right,suffix) ← match_assoc unif l r` finds the longest prefix and suffix common to `l` and `r` and returns them along with the differences -/ meta def match_assoc (l : list expr) (r : list expr) : tactic (list expr × list expr × list expr × list expr) := do (pre,l₁,r₁) ← match_prefix l r, (suf,l₂,r₂) ← match_prefix (reverse l₁) (reverse r₁), return (pre,reverse l₂,reverse r₂,reverse suf) meta def check_ac : expr → tactic (bool × bool × option (expr × expr × expr) × expr) | (expr.app (expr.app f x) y) := do t ← infer_type x, a ← try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance, c ← try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance, i ← try_core (do v ← mk_meta_var t, l_inst_p ← to_expr ``(is_left_id %%t %%f %%v), r_inst_p ← to_expr ``(is_right_id %%t %%f %%v), l_v ← mk_meta_var l_inst_p, r_v ← mk_meta_var r_inst_p , l_id ← mk_mapp `is_left_id.left_id [some t,f,v,some l_v], mk_instance l_inst_p >>= unify l_v, r_id ← mk_mapp `is_right_id.right_id [none,f,v,some r_v], mk_instance r_inst_p >>= unify r_v, v' ← instantiate_mvars v, return (l_id,r_id,v')), return (a.is_some,c.is_some,i,f) | _ := return (ff,ff,none,expr.var 1) meta def parse_assoc_chain' (f : expr) : expr → tactic (dlist expr) | e := (do (expr.app (expr.app f' x) y) ← return e, is_def_eq f f', (++) <$> parse_assoc_chain' x <*> parse_assoc_chain' y) <|> return (singleton e) meta def parse_assoc_chain (f : expr) : expr → tactic (list expr) := map dlist.to_list ∘ parse_assoc_chain' f meta def fold_assoc (op : expr) : option (expr × expr × expr) → list expr → option (expr × list expr) | _ (x::xs) := some (foldl (expr.app ∘ expr.app op) x xs, []) | none [] := none | (some (l_id,r_id,x₀)) [] := some (x₀,[l_id,r_id]) meta def fold_assoc1 (op : expr) : list expr → option expr | (x::xs) := some $ foldl (expr.app ∘ expr.app op) x xs | [] := none meta def same_function_aux : list expr → list expr → expr → expr → tactic (expr × list expr × list expr) | xs₀ xs₁ (expr.app f₀ a₀) (expr.app f₁ a₁) := same_function_aux (a₀ :: xs₀) (a₁ :: xs₁) f₀ f₁ | xs₀ xs₁ e₀ e₁ := is_def_eq e₀ e₁ >> return (e₀,xs₀,xs₁) meta def same_function : expr → expr → tactic (expr × list expr × list expr) := same_function_aux [] [] meta def parse_ac_mono_function (l r : expr) : tactic (expr × expr × list expr × mono_function) := do (full_f,ls,rs) ← same_function l r, (a,c,i,f) ← check_ac l, if a then if c then do (s,ls,rs) ← monad.join (match_ac <$> parse_assoc_chain f l <*> parse_assoc_chain f r), (l',l_id) ← fold_assoc f i ls, (r',r_id) ← fold_assoc f i rs, s' ← fold_assoc1 f s, return (l',r',l_id ++ r_id,mono_function.assoc_comm f s') else do -- a ∧ ¬ c (pre,ls,rs,suff) ← monad.join (match_assoc <$> parse_assoc_chain f l <*> parse_assoc_chain f r), (l',l_id) ← fold_assoc f i ls, (r',r_id) ← fold_assoc f i rs, let pre' := fold_assoc1 f pre, let suff' := fold_assoc1 f suff, return (l',r',l_id ++ r_id,mono_function.assoc f pre' suff') else do -- ¬ a (xs₀,x₀,x₁,xs₁) ← find_one_difference opt ls rs, return (x₀,x₁,[],mono_function.non_assoc full_f xs₀ xs₁) meta def parse_ac_mono_function' (l r : pexpr) := do l' ← to_expr l, r' ← to_expr r, parse_ac_mono_function l' r' meta def ac_monotonicity_goal : expr → tactic (expr × expr × list expr × ac_mono_ctx) | `(%%e₀ → %%e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, t₀ ← infer_type e₀, t₁ ← infer_type e₁, rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) → (x₁ : %%t₁)), return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := some $ expr.pi `x binder_info.default , rel_def := rel_def }) | `(%%e₀ = %%e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, t₀ ← infer_type e₀, t₁ ← infer_type e₁, rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) = (x₁ : %%t₁)), return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := none , rel_def := rel_def }) | (expr.app (expr.app rel e₀) e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := expr.app ∘ expr.app rel , rel_def := rel }) | _ := fail "invalid monotonicity goal" meta def bin_op_left (f : expr) : option expr → expr → expr | none e := e | (some e₀) e₁ := f.mk_app [e₀,e₁] meta def bin_op (f a b : expr) : expr := f.mk_app [a,b] meta def bin_op_right (f : expr) : expr → option expr → expr | e none := e | e₀ (some e₁) := f.mk_app [e₀,e₁] meta def mk_fun_app : mono_function → expr → expr | (mono_function.non_assoc f x y) z := f.mk_app (x ++ z :: y) | (mono_function.assoc f x y) z := bin_op_left f x (bin_op_right f z y) | (mono_function.assoc_comm f x) z := f.mk_app [z,x] meta inductive mono_law /- `assoc (l₀,r₀) (r₁,l₁)` gives first how to find rules to prove x+(y₀+z) R x+(y₁+z); if that fails, helps prove (x+y₀)+z R (x+y₁)+z -/ | assoc : expr × expr → expr × expr → mono_law /- `congr r` gives the rule to prove `x = y → f x = f y` -/ | congr : expr → mono_law | other : expr → mono_law meta def mono_law.to_tactic_format : mono_law → tactic format | (mono_law.other e) := do e ← pp e, return format!"other {e}" | (mono_law.congr r) := do e ← pp r, return format!"congr {e}" | (mono_law.assoc (x₀,x₁) (y₀,y₁)) := do x₀ ← pp x₀, x₁ ← pp x₁, y₀ ← pp y₀, y₁ ← pp y₁, return format!"assoc {x₀}; {x₁} | {y₀}; {y₁}" meta instance has_to_tactic_format_mono_law : has_to_tactic_format mono_law := { to_tactic_format := mono_law.to_tactic_format } meta def mk_rel (ctx : ac_mono_ctx_ne) (f : expr → expr) : expr := ctx.to_rel (f ctx.left) (f ctx.right) meta def mk_congr_args (fn : expr) (xs₀ xs₁ : list expr) (l r : expr) : tactic expr := do p ← mk_app `eq [fn.mk_app $ xs₀ ++ l :: xs₁,fn.mk_app $ xs₀ ++ r :: xs₁], prod.snd <$> solve_aux p (do iterate_exactly (xs₁.length) (applyc `congr_fun), applyc `congr_arg) meta def mk_congr_law (ctx : ac_mono_ctx) : tactic expr := match ctx.function with | (mono_function.assoc f x₀ x₁) := if (x₀ <|> x₁).is_some then mk_congr_args f x₀.to_monad x₁.to_monad ctx.left ctx.right else failed | (mono_function.assoc_comm f x₀) := mk_congr_args f [x₀] [] ctx.left ctx.right | (mono_function.non_assoc f x₀ x₁) := mk_congr_args f x₀ x₁ ctx.left ctx.right end meta def mk_pattern (ctx : ac_mono_ctx) : tactic mono_law := match (sequence ctx : option (ac_mono_ctx' _)) with | (some ctx) := match ctx.function with | (mono_function.assoc f (some x) (some y)) := return $ mono_law.assoc ( mk_rel ctx (λ i, bin_op f x (bin_op f i y)) , mk_rel ctx (λ i, bin_op f i y)) ( mk_rel ctx (λ i, bin_op f (bin_op f x i) y) , mk_rel ctx (λ i, bin_op f x i)) | (mono_function.assoc f (some x) none) := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) | (mono_function.assoc f none (some y)) := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) | (mono_function.assoc f none none) := none | _ := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) end | none := mono_law.congr <$> mk_congr_law ctx end meta def match_rule (pat : expr) (r : name) : tactic expr := do r' ← mk_const r, t ← infer_type r', t ← expr.dsimp t { fail_if_unchanged := ff } tt [] [ simp_arg_type.expr ``(monotone), simp_arg_type.expr ``(strict_mono)], match_rule_head pat [] r' t meta def find_lemma (pat : expr) : list name → tactic (list expr) | [] := return [] | (r :: rs) := do (cons <$> match_rule pat r <|> pure id) <*> find_lemma rs meta def match_chaining_rules (ls : list name) (x₀ x₁ : expr) : tactic (list expr) := do x' ← to_expr ``(%%x₁ → %%x₀), r₀ ← find_lemma x' ls, r₁ ← find_lemma x₁ ls, return (expr.app <$> r₀ <*> r₁) meta def find_rule (ls : list name) : mono_law → tactic (list expr) | (mono_law.assoc (x₀,x₁) (y₀,y₁)) := (match_chaining_rules ls x₀ x₁) <|> (match_chaining_rules ls y₀ y₁) | (mono_law.congr r) := return [r] | (mono_law.other p) := find_lemma p ls universes u v def apply_rel {α : Sort u} (R : α → α → Sort v) {x y : α} (x' y' : α) (h : R x y) (hx : x = x') (hy : y = y') : R x' y' := by { rw [← hx,← hy], apply h } meta def ac_refine (e : expr) : tactic unit := refine ``(eq.mp _ %%e) ; ac_refl meta def one_line (e : expr) : tactic format := do lbl ← pp e, asm ← infer_type e >>= pp, return format!"\t{asm}\n" meta def side_conditions (e : expr) : tactic format := do let vs := e.list_meta_vars, ts ← mmap one_line vs.tail, let r := e.get_app_fn.const_name, return format!"{r}:\n{format.join ts}" open monad /-- tactic-facing function, similar to `interactive.tactic.generalize` with the exception that meta variables -/ private meta def monotonicity.generalize' (h : name) (v : expr) (x : name) : tactic (expr × expr) := do tgt ← target, t ← infer_type v, tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize v x >> target), to_expr ``(λ y : %%t, Π x, y = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(λ y : %%t, Π x, %%v = x → %%tgt), t ← head_beta (tgt' v) >>= assert h, swap, r ← mk_eq_refl v, solve1 $ tactic.exact (t v r), prod.mk <$> tactic.intro x <*> tactic.intro h private meta def hide_meta_vars (tac : list expr → tactic unit) : tactic unit := focus1 $ do tgt ← target >>= instantiate_mvars, tactic.change tgt, ctx ← local_context, let vs := tgt.list_meta_vars, vs' ← mmap (λ v, do h ← get_unused_name `h, x ← get_unused_name `x, prod.snd <$> monotonicity.generalize' h v x) vs, tac ctx; vs'.mmap' (try ∘ tactic.subst) meta def hide_meta_vars' (tac : itactic) : itactic := hide_meta_vars $ λ _, tac end config meta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit := do gs ← get_goals, set_goals [v], target >>= instantiate_mvars >>= tactic.change, tac, done, set_goals $ gs def list.minimum_on {α β} [linear_order β] (f : α → β) : list α → list α | [] := [] | (x :: xs) := prod.snd $ xs.foldl (λ ⟨k,a⟩ b, let k' := f b in if k < k' then (k,a) else if k' < k then (k', [b]) else (k,b :: a)) (f x, [x]) open format mono_selection meta def best_match {β} (xs : list expr) (tac : expr → tactic β) : tactic unit := do t ← target, xs ← xs.mmap (λ x, try_core $ prod.mk x <$> solve_aux t (tac x >> get_goals)), let xs := xs.filter_map id, let r := list.minimum_on (list.length ∘ prod.fst ∘ prod.snd) xs, match r with | [(_,gs,pr)] := tactic.exact pr >> set_goals gs | [] := fail "no good match found" | _ := do lmms ← r.mmap (λ ⟨l,gs,_⟩, do ts ← gs.mmap infer_type, msg ← ts.mmap pp, pure $ foldl compose "\n\n" (list.intersperse "\n" $ to_fmt l.get_app_fn.const_name :: msg)), let msg := foldl compose "" lmms, fail format!"ambiguous match: {msg}\n\nTip: try asserting a side condition to distinguish between the lemmas" end meta def mono_aux (dir : parse side) : tactic unit := do t ← target >>= instantiate_mvars, ns ← get_monotonicity_lemmas t dir, asms ← local_context, rs ← find_lemma asms t ns, focus1 $ () <$ best_match rs (λ law, tactic.refine $ to_pexpr law) /-- - `mono` applies a monotonicity rule. - `mono*` applies monotonicity rules repetitively. - `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed propositions. Those help to select the right monotonicity rule. - `mono left` or `mono right` is useful when proving strict orderings: for `x + y < w + z` could be broken down into either - left: `x ≤ w` and `y < z` or - right: `x < w` and `y ≤ z` - `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono. - The general syntax is `mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg? To use it, first import `tactic.monotonicity`. Here is an example of mono: ```lean example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := begin mono, -- unfold `(-)`, apply add_le_add { -- ⊢ k + 3 + x ≤ k + 4 + x mono, -- apply add_le_add, refl -- ⊢ k + 3 ≤ k + 4 mono }, { -- ⊢ -y ≤ -z mono /- apply neg_le_neg -/ } end ``` More succinctly, we can prove the same goal as: ```lean example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := by mono* ``` -/ meta def mono (many : parse (tk "*")?) (dir : parse side) (hyps : parse $ tk "with" *> pexpr_list_or_texpr <|> pure []) (simp_rules : parse $ tk "using" *> simp_arg_list <|> pure []) : tactic unit := do hyps ← hyps.mmap (λ p, to_expr p >>= mk_meta_var), hyps.mmap' (λ pr, do h ← get_unused_name `h, note h none pr), when (¬ simp_rules.empty) (simp_core { } failed tt simp_rules [] (loc.ns [none]) >> skip), if many.is_some then repeat $ mono_aux dir else mono_aux dir, gs ← get_goals, set_goals $ hyps ++ gs add_tactic_doc { name := "mono", category := doc_category.tactic, decl_names := [`tactic.interactive.mono], tags := ["monotonicity"] } /-- transforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas marked as `monotonic`. Special care is taken when `f` is the repeated application of an associative operator and if the operator is commutative -/ meta def ac_mono_aux (cfg : mono_cfg := { mono_cfg . }) : tactic unit := hide_meta_vars $ λ asms, do try `[simp only [sub_eq_add_neg]], tgt ← target >>= instantiate_mvars, (l,r,id_rs,g) ← ac_monotonicity_goal cfg tgt <|> fail "monotonic context not found", ns ← get_monotonicity_lemmas tgt both, p ← mk_pattern g, rules ← find_rule asms ns p <|> fail "no applicable rules found", when (rules = []) (fail "no applicable rules found"), err ← format.join <$> mmap side_conditions rules, focus1 $ best_match rules (λ rule, do t₀ ← mk_meta_var `(Prop), v₀ ← mk_meta_var t₀, t₁ ← mk_meta_var `(Prop), v₁ ← mk_meta_var t₁, tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v₀ %%v₁), solve_mvar v₀ (try (any_of id_rs rewrite_target) >> ( done <|> refl <|> ac_refl <|> `[simp only [is_associative.assoc]]) ), solve_mvar v₁ (try (any_of id_rs rewrite_target) >> ( done <|> refl <|> ac_refl <|> `[simp only [is_associative.assoc]]) ), n ← num_goals, iterate_exactly (n-1) (try $ solve1 $ apply_instance <|> tactic.solve_by_elim { lemmas := some asms })) open sum nat /-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/ meta def repeat_until_or_at_most : nat → tactic unit → tactic unit → tactic unit | 0 t _ := fail "too many applications" | (succ n) t u := u <|> (t >> repeat_until_or_at_most n t u) meta def repeat_until : tactic unit → tactic unit → tactic unit := repeat_until_or_at_most 100000 @[derive _root_.has_reflect, derive _root_.inhabited] inductive rep_arity : Type | one | exactly (n : ℕ) | many meta def repeat_or_not : rep_arity → tactic unit → option (tactic unit) → tactic unit | rep_arity.one tac none := tac | rep_arity.many tac none := repeat tac | (rep_arity.exactly n) tac none := iterate_exactly' n tac | rep_arity.one tac (some until) := tac >> until | rep_arity.many tac (some until) := repeat_until tac until | (rep_arity.exactly n) tac (some until) := iterate_exactly n tac >> until meta def assert_or_rule : lean.parser (pexpr ⊕ pexpr) := (tk ":=" *> inl <$> texpr <|> (tk ":" *> inr <$> texpr)) meta def arity : lean.parser rep_arity := rep_arity.many <$ tk "*" <|> rep_arity.exactly <$> (tk "^" *> small_nat) <|> pure rep_arity.one /-- `ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a monotonic function `f` to `x ≺ y`. `ac_mono*` unwraps monotonic functions until it can't. `ac_mono^k`, for some literal number `k` applies monotonicity `k` times. `ac_mono h`, with `h` a hypothesis, unwraps monotonic functions and uses `h` to solve the remaining goal. Can be combined with `*` or `^k`: `ac_mono* h` `ac_mono : p` asserts `p` and uses it to discharge the goal result unwrapping a series of monotonic functions. Can be combined with * or ^k: `ac_mono* : p` In the case where `f` is an associative or commutative operator, `ac_mono` will consider any possible permutation of its arguments and use the one the minimizes the difference between the left-hand side and the right-hand side. To use it, first import `tactic.monotonicity`. `ac_mono` can be used as follows: ```lean example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, -- ⊢ (m + x + n) * z ≤ z * (y + n + m) ac_mono, -- ⊢ m + x + n ≤ y + n + m ac_mono, end ``` As with `mono*`, `ac_mono*` solves the goal in one go and so does `ac_mono* h₁`. The latter syntax becomes especially interesting in the following example: ```lean example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : m + x + n ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by ac_mono* h₁. ``` By giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to stop earlier than it would normally would. -/ meta def ac_mono (rep : parse arity) : parse assert_or_rule? → opt_param mono_cfg { mono_cfg . } → tactic unit | none opt := focus1 $ repeat_or_not rep (ac_mono_aux opt) none | (some (inl h)) opt := do focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> to_expr h >>= ac_refine) | (some (inr t)) opt := do h ← i_to_expr t >>= assert `h, tactic.swap, focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> ac_refine h) /- TODO(Simon): with `ac_mono h` and `ac_mono : p` split the remaining gaol if the provided rule does not solve it completely. -/ add_tactic_doc { name := "ac_mono", category := doc_category.tactic, decl_names := [`tactic.interactive.ac_mono], tags := ["monotonicity"] } attribute [mono] and.imp or.imp end tactic.interactive
210b981341eeb015949b351dd2b878051c66f91a
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/lifting_properties.lean
4ebc2ffa9b26495f65ceb71111ec71e4084a5af3
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
5,342
lean
/- Copyright (c) 2021 Jakob Scholbach. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob Scholbach -/ import category_theory.arrow import category_theory.limits.preserves.shapes.terminal /-! # Lifting properties This file defines the lifting property of two arrows in a category and shows basic properties of this notion. We also construct the subcategory consisting of those morphisms which have the right lifting property with respect to arrows in a given diagram. ## Main results - `has_lifting_property`: the definition of the lifting property - `iso_has_right_lifting_property`: any isomorphism satisfies the right lifting property (rlp) - `id_has_right_lifting_property`: any identity has the rlp - `right_lifting_property_initial_iff`: spells out the rlp with respect to a map whose source is an initial object - `right_lifting_subcat`: given a set of arrows `F : D → arrow C`, we construct the subcategory of those morphisms `p` in `C` that satisfy the rlp w.r.t. `F i`, for any element `i` of `D`. ## Tags lifting property -/ open category_theory.limits namespace category_theory universes v u v₁ variables {C : Type u} [category.{v} C] variables {D : Type v₁} variables {X Y Z : C} /-- The lifting property of a morphism `i` with respect to a morphism `p`. This can be interpreted as the right lifting property of `i` with respect to `p`, or the left lifting property of `p` with respect to `i`. -/ class has_lifting_property (i p : arrow C) : Prop := (sq_has_lift : ∀ (sq : i ⟶ p), arrow.has_lift sq) @[priority 100] -- see Note [lower instance priority] instance has_lifting_property' {i p : arrow C} [has_lifting_property i p] (sq : i ⟶ p) : arrow.has_lift sq := has_lifting_property.sq_has_lift sq /-- Any isomorphism has the right lifting property with respect to any map. A → X ↓i ↓p≅ B → Y -/ lemma iso_has_right_lifting_property (i : arrow C) (p : X ≅ Y) : has_lifting_property i (arrow.mk p.hom) := ⟨λ sq, ⟨⟨{ lift := sq.right ≫ p.inv, }⟩⟩⟩ -- the lift is obtained by p⁻¹ ∘ (B → Y) /-- Any identity has the right lifting property with respect to any map. -/ lemma id_has_right_lifting_property (i : arrow C) : has_lifting_property i (arrow.mk (𝟙 X)) := iso_has_right_lifting_property i (iso.refl _) /-- An equivalent characterization for right lifting with respect to a map `i` whose source is initial. ∅ → X ↓ ↓ B → Y has a lifting iff there is a map B → X making the right part commute. -/ lemma right_lifting_property_initial_iff (i p : arrow C) (h : is_initial i.left) : has_lifting_property i p ↔ ∀ {e : i.right ⟶ p.right}, ∃ l : i.right ⟶ p.left, l ≫ p.hom = e := begin fsplit, { introsI hlift e, have comm : (is_initial.to h p.left) ≫ p.hom = i.hom ≫ e := is_initial.hom_ext h _ _, use arrow.lift (arrow.hom_mk comm), simp }, { refine λ hlift, ⟨λ sq, _⟩, obtain ⟨l, hl⟩ : ∃ (l : i.right ⟶ p.left), l ≫ p.hom = sq.right := hlift, exact arrow.has_lift.mk ⟨l, is_initial.hom_ext h _ _⟩, } end /-- The condition of having the rlp with respect to a morphism `i` is stable under composition. -/ lemma has_right_lifting_property_comp {i : arrow C} {f : X ⟶ Y} {g : Y ⟶ Z} (hf : has_lifting_property i (arrow.mk f)) (hg : has_lifting_property i (arrow.mk g)) : has_lifting_property i (arrow.mk (f ≫ g)) := { sq_has_lift := λ sq1, -- construct a square i ⟶ f let sq2 : i ⟶ (arrow.mk f) := ⟨sq1.left, arrow.lift (arrow.square_to_snd sq1)⟩ in -- show that the lift of this square is a lift of i with respect to g ∘ f ⟨⟨⟨(arrow.lift sq2 : _ ⟶ _), by simp⟩⟩⟩ } /-- The objects of the subcategory `right_lifting_subcategory` are the ones in the underlying category. -/ def right_lifting_subcat (R : Type u) := R instance right_lifting_subcat.inhabited (R : Type u) [inhabited R] : inhabited (right_lifting_subcat R) := { default := (default R : R) } /-- The objects of the subcategory `right_lifting_subcategory` are the ones in the underlying category. -/ def right_lifting_subcat.X {R : Type u} (x : right_lifting_subcat R) : R := x lemma id_has_right_lifting_property' {F : D → arrow C} (X : C) : ∀ i : D, has_lifting_property (F i) (arrow.mk (𝟙 X)) := λ i, id_has_right_lifting_property (F i) lemma has_right_lifting_property_comp' {F : D → arrow C} {f : X ⟶ Y} (hf : ∀ i : D, has_lifting_property (F i) (arrow.mk f)) {g : Y ⟶ Z} (hg : ∀ i : D, has_lifting_property (F i) (arrow.mk g)) : ∀ i : D, has_lifting_property (F i) (arrow.mk (f ≫ g)) := λ i, has_right_lifting_property_comp (hf i) (hg i) /-- Given a set of arrows in C, indexed by `F : D → arrow C`, we construct the (non-full) subcategory of `C` spanned by those morphisms that have the right lifting property relative to all maps of the form `F i`, where `i` is any element in `D`. -/ def right_lifting_subcategory (F : D → arrow C) : category (right_lifting_subcat C) := { hom := λ X Y, { p : X ⟶ Y // ∀ {i : D}, has_lifting_property (F i) (arrow.mk p) }, id := λ X, ⟨𝟙 X, id_has_right_lifting_property' X⟩, comp := λ X Y Z f g, ⟨f.val ≫ g.val, has_right_lifting_property_comp' f.property g.property⟩ } end category_theory
1f145690f27f4dfe37881398061e4df846193786
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/order/order_iso.lean
a9e7fad94bc65905a3be27b8ad0c3e33f6bb633d
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
14,861
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 logic.embedding import logic.function.iterate import order.rel_classes open function universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} /-- 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 order embedding with respect to a given pair of orders `r` and `s` is an embedding `f : α ↪ β` such that `r a b ↔ s (f a) (f b)`. -/ structure order_embedding {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ↪ β := (ord' : ∀ {a b}, r a b ↔ s (to_embedding a) (to_embedding b)) infix ` ≼o `:25 := order_embedding /-- the induced order on a subtype is an embedding under the natural inclusion. -/ definition subtype.order_embedding {X : Type*} (r : X → X → Prop) (p : X → Prop) : ((subtype.val : subtype p → X) ⁻¹'o r) ≼o r := ⟨⟨subtype.val,subtype.val_injective⟩,by intros;refl⟩ 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 order_embedding instance : has_coe_to_fun (r ≼o s) := ⟨λ _, α → β, λ o, o.to_embedding⟩ theorem injective (f : r ≼o s) : injective f := f.inj' theorem ord (f : r ≼o s) : ∀ {a b}, r a b ↔ s (f a) (f b) := f.ord' @[simp] theorem coe_fn_mk (f : α ↪ β) (o) : (@order_embedding.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_embedding (f : r ≼o s) : (f.to_embedding : α → β) = f := rfl /-- The map `coe_fn : (r ≼o s) → (r → s)` is injective. We can't use `function.injective` here but mimic its signature by using `⦃e₁ e₂⦄`. -/ theorem coe_fn_inj : ∀ ⦃e₁ e₂ : r ≼o s⦄, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨⟨f₁, h₁⟩, o₁⟩ ⟨⟨f₂, h₂⟩, o₂⟩ h := by { congr, exact h } @[refl] protected def refl (r : α → α → Prop) : r ≼o r := ⟨embedding.refl _, λ a b, iff.rfl⟩ @[trans] protected def trans (f : r ≼o s) (g : s ≼o t) : r ≼o t := ⟨f.1.trans g.1, λ a b, by rw [f.2, g.2]; simp⟩ @[simp] theorem refl_apply (x : α) : order_embedding.refl r x = x := rfl @[simp] theorem trans_apply (f : r ≼o s) (g : s ≼o t) (a : α) : (f.trans g) a = g (f a) := rfl /-- An order embedding is also an order embedding between dual orders. -/ def rsymm (f : r ≼o s) : swap r ≼o swap s := ⟨f.to_embedding, λ a b, f.ord⟩ /-- If `f` is injective, then it is an order embedding from the preimage order of `s` to `s`. -/ def preimage (f : α ↪ β) (s : β → β → Prop) : f ⁻¹'o s ≼o s := ⟨f, λ a b, iff.rfl⟩ theorem eq_preimage (f : r ≼o s) : r = f ⁻¹'o s := by { ext a b, exact f.ord } protected theorem is_irrefl : ∀ (f : r ≼o s) [is_irrefl β s], is_irrefl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a h, H _ (o.1 h)⟩ protected theorem is_refl : ∀ (f : r ≼o s) [is_refl β s], is_refl α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a, o.2 (H _)⟩ protected theorem is_symm : ∀ (f : r ≼o s) [is_symm β s], is_symm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h, o.2 (H _ _ (o.1 h))⟩ protected theorem is_asymm : ∀ (f : r ≼o s) [is_asymm β s], is_asymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, H _ _ (o.1 h₁) (o.1 h₂)⟩ protected theorem is_antisymm : ∀ (f : r ≼o s) [is_antisymm β s], is_antisymm α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b h₁ h₂, f.inj' (H _ _ (o.1 h₁) (o.1 h₂))⟩ protected theorem is_trans : ∀ (f : r ≼o s) [is_trans β s], is_trans α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b c h₁ h₂, o.2 (H _ _ _ (o.1 h₁) (o.1 h₂))⟩ protected theorem is_total : ∀ (f : r ≼o s) [is_total β s], is_total α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o o).2 (H _ _)⟩ protected theorem is_preorder : ∀ (f : r ≼o s) [is_preorder β s], is_preorder α r | f H := by exactI {..f.is_refl, ..f.is_trans} protected theorem is_partial_order : ∀ (f : r ≼o 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 ≼o 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 ≼o 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 ≼o s) [is_trichotomous β s], is_trichotomous α r | ⟨f, o⟩ ⟨H⟩ := ⟨λ a b, (or_congr o (or_congr f.inj'.eq_iff.symm o)).2 (H _ _)⟩ protected theorem is_strict_total_order' : ∀ (f : r ≼o 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 ≼o 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.ord.1 h) _ rfl⟩ end protected theorem well_founded : ∀ (f : r ≼o s) (h : well_founded s), well_founded r | f ⟨H⟩ := ⟨λ a, f.acc _ (H _)⟩ protected theorem is_well_order : ∀ (f : r ≼o s) [is_well_order β s], is_well_order α r | f H := by exactI {wf := f.well_founded H.wf, ..f.is_strict_total_order'} /-- It suffices to prove `f` is monotone between strict orders to show it is an order embedding. -/ def of_monotone [is_trichotomous α r] [is_asymm β s] (f : α → β) (H : ∀ a b, r a b → s (f a) (f b)) : r ≼o 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 -- If le is preserved by an order embedding of preorders, then lt is too def lt_embedding_of_le_embedding [preorder α] [preorder β] (f : (has_le.le : α → α → Prop) ≼o (has_le.le : β → β → Prop)) : (has_lt.lt : α → α → Prop) ≼o (has_lt.lt : β → β → Prop) := { ord' := by intros; simp [lt_iff_le_not_le,f.ord], .. f } end order_embedding /-- The inclusion map `fin n → ℕ` is an order embedding. -/ def fin.val.order_embedding (n) : @order_embedding (fin n) ℕ (<) (<) := ⟨⟨fin.val, @fin.eq_of_veq _⟩, λ a b, iff.rfl⟩ /-- The inclusion map `fin m → fin n` is an order embedding. -/ def fin_fin.order_embedding {m n} (h : m ≤ n) : @order_embedding (fin m) (fin n) (<) (<) := ⟨⟨λ ⟨x, h'⟩, ⟨x, lt_of_lt_of_le h' h⟩, λ ⟨a, _⟩ ⟨b, _⟩ h, by congr; injection h⟩, by intros; cases a; cases b; refl⟩ instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) := (fin.val.order_embedding _).is_well_order /-- An order isomorphism is an equivalence that is also an order embedding. -/ structure order_iso {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends α ≃ β := (ord' : ∀ {a b}, r a b ↔ s (to_equiv a) (to_equiv b)) infix ` ≃o `:25 := order_iso namespace order_iso /-- Convert an `order_iso` to an `order_embedding`. This function is also available as a coercion but often it is easier to write `f.to_order_embedding` than to write explicitly `r` and `s` in the target type. -/ def to_order_embedding (f : r ≃o s) : r ≼o s := ⟨f.to_equiv.to_embedding, f.ord'⟩ instance : has_coe (r ≃o s) (r ≼o s) := ⟨to_order_embedding⟩ -- see Note [function coercion] instance : has_coe_to_fun (r ≃o s) := ⟨λ _, α → β, λ f, f⟩ @[simp] lemma to_order_embedding_eq_coe (f : r ≃o s) : f.to_order_embedding = f := rfl @[simp] lemma coe_coe_fn (f : r ≃o s) : ((f : r ≼o s) : α → β) = f := rfl theorem ord (f : r ≃o s) : ∀ {a b}, r a b ↔ s (f a) (f b) := f.ord' lemma ord'' {r : α → α → Prop} {s : β → β → Prop} (f : r ≃o s) {x y : α} : r x y ↔ s ((↑f : r ≼o s) x) ((↑f : r ≼o s) y) := f.ord @[simp] theorem coe_fn_mk (f : α ≃ β) (o) : (@order_iso.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_equiv (f : r ≃o s) : (f.to_equiv : α → β) = f := rfl theorem to_equiv_injective : injective (to_equiv : (r ≃o s) → α ≃ β) | ⟨e₁, o₁⟩ ⟨e₂, o₂⟩ h := by { congr, exact h } /-- The map `coe_fn : (r ≃o s) → (r → s)` is injective. We can't use `function.injective` here but mimic its signature by using `⦃e₁ e₂⦄`. -/ theorem coe_fn_injective ⦃e₁ e₂ : r ≃o s⦄ (h : (e₁ : α → β) = e₂) : e₁ = e₂ := to_equiv_injective $ equiv.coe_fn_injective h @[ext] theorem ext {e₁ e₂ : r ≃o s} (h : ∀ x, e₁ x = e₂ x) : e₁ = e₂ := coe_fn_injective $ funext h /-- Identity map is an order isomorphism. -/ @[refl] protected def refl (r : α → α → Prop) : r ≃o r := ⟨equiv.refl _, λ a b, iff.rfl⟩ /-- Inverse map of an order isomorphism is an order isomorphism. -/ @[symm] protected def symm (f : r ≃o s) : s ≃o r := ⟨f.to_equiv.symm, λ a b, by cases f with f o; rw o; simp⟩ /-- Composition of two order isomorphisms is an order isomorphism. -/ @[trans] protected def trans (f₁ : r ≃o s) (f₂ : s ≃o t) : r ≃o t := ⟨f₁.to_equiv.trans f₂.to_equiv, λ a b, f₁.ord.trans f₂.ord⟩ /-- An order isomorphism is also an order isomorphism between dual orders. -/ def rsymm (f : r ≃o s) : (swap r) ≃o (swap s) := ⟨f.to_equiv, λ _ _, f.ord⟩ @[simp] theorem coe_fn_symm_mk (f o) : ((@order_iso.mk _ _ r s f o).symm : β → α) = f.symm := rfl @[simp] theorem refl_apply (x : α) : order_iso.refl r x = x := rfl @[simp] theorem trans_apply (f : r ≃o s) (g : s ≃o t) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_symm_apply (e : r ≃o s) (x : β) : e (e.symm x) = x := e.to_equiv.apply_symm_apply x @[simp] theorem symm_apply_apply (e : r ≃o s) (x : α) : e.symm (e x) = x := e.to_equiv.symm_apply_apply x theorem rel_symm_apply (e : r ≃o s) {x y} : r x (e.symm y) ↔ s (e x) y := by rw [e.ord, e.apply_symm_apply] theorem symm_apply_rel (e : r ≃o s) {x y} : r (e.symm x) y ↔ s x (e y) := by rw [e.ord, e.apply_symm_apply] protected lemma bijective (e : r ≃o s) : bijective e := e.to_equiv.bijective protected lemma injective (e : r ≃o s) : injective e := e.to_equiv.injective protected lemma surjective (e : r ≃o s) : surjective e := e.to_equiv.surjective /-- Any equivalence lifts to an order isomorphism between `s` and its preimage. -/ protected def preimage (f : α ≃ β) (s : β → β → Prop) : f ⁻¹'o s ≃o s := ⟨f, λ a b, iff.rfl⟩ /-- A surjective order embedding is an order isomorphism. -/ noncomputable def of_surjective (f : r ≼o s) (H : surjective f) : r ≃o s := ⟨equiv.of_bijective f ⟨f.injective, H⟩, by simp [f.ord']⟩ @[simp] theorem of_surjective_coe (f : r ≼o s) (H) : (of_surjective f H : α → β) = f := rfl def sum_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @order_iso α₁ α₂ r₁ r₂) (e₂ : @order_iso β₁ β₂ s₁ s₂) : sum.lex r₁ s₁ ≃o sum.lex r₂ 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]⟩ def prod_lex_congr {α₁ α₂ β₁ β₂ r₁ r₂ s₁ s₂} (e₁ : @order_iso α₁ α₂ r₁ r₂) (e₂ : @order_iso β₁ β₂ s₁ s₂) : prod.lex r₁ s₁ ≃o prod.lex r₂ s₂ := ⟨equiv.prod_congr e₁.to_equiv e₂.to_equiv, λ a b, begin cases e₁ with f hf; cases e₂ with g hg, cases a with a₁ a₂; cases b with b₁ b₂, suffices : prod.lex r₁ s₁ (a₁, a₂) (b₁, b₂) ↔ prod.lex r₂ s₂ (f a₁, g a₂) (f b₁, g b₂), {simpa [hf, hg]}, split, { intro h, cases h with _ _ _ _ h _ _ _ h, { left, exact hf.1 h }, { right, exact hg.1 h } }, { generalize e : f b₁ = fb₁, intro h, cases h with _ _ _ _ h _ _ _ h, { subst e, left, exact hf.2 h }, { have := f.injective e, subst b₁, right, exact hg.2 h } } end⟩ instance : group (r ≃o r) := { one := order_iso.refl r, mul := λ f₁ f₂, f₂.trans f₁, inv := order_iso.symm, mul_assoc := λ f₁ f₂ f₃, rfl, one_mul := λ f, ext $ λ _, rfl, mul_one := λ f, ext $ λ _, rfl, mul_left_inv := λ f, ext f.symm_apply_apply } @[simp] lemma coe_one : ⇑(1 : r ≃o r) = id := rfl @[simp] lemma coe_mul (e₁ e₂ : r ≃o r) : ⇑(e₁ * e₂) = e₁ ∘ e₂ := rfl lemma mul_apply (e₁ e₂ : r ≃o r) (x : α) : (e₁ * e₂) x = e₁ (e₂ x) := rfl @[simp] lemma inv_apply_self (e : r ≃o r) (x) : e⁻¹ (e x) = x := e.symm_apply_apply x @[simp] lemma apply_inv_self (e : r ≃o r) (x) : e (e⁻¹ x) = x := e.apply_symm_apply x end order_iso /-- A subset `p : set α` embeds into `α` -/ def set_coe_embedding {α : Type*} (p : set α) : p ↪ α := ⟨subtype.val, @subtype.eq _ _⟩ /-- `subrel r p` is the inherited relation on a subset. -/ def subrel (r : α → α → Prop) (p : set α) : p → p → Prop := @subtype.val _ p ⁻¹'o r @[simp] theorem subrel_val (r : α → α → Prop) (p : set α) {a b} : subrel r p a b ↔ r a.1 b.1 := iff.rfl namespace subrel protected def order_embedding (r : α → α → Prop) (p : set α) : subrel r p ≼o r := ⟨set_coe_embedding _, λ a b, iff.rfl⟩ @[simp] theorem order_embedding_apply (r : α → α → Prop) (p a) : subrel.order_embedding r p a = a.1 := rfl instance (r : α → α → Prop) [is_well_order α r] (p : set α) : is_well_order p (subrel r p) := order_embedding.is_well_order (subrel.order_embedding r p) end subrel /-- Restrict the codomain of an order embedding -/ def order_embedding.cod_restrict (p : set β) (f : r ≼o s) (H : ∀ a, f a ∈ p) : r ≼o subrel s p := ⟨f.to_embedding.cod_restrict p H, f.ord'⟩ @[simp] theorem order_embedding.cod_restrict_apply (p) (f : r ≼o s) (H a) : order_embedding.cod_restrict p f H a = ⟨f a, H a⟩ := rfl
066478548bb5a4447898c7ecdce2a7e4e2045842
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/do_match_else.lean
bf16e9dfd427b46c46d2c287b0c8737ebe5b5ccf
[ "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
566
lean
open tactic set_option pp.all true meta def app2 (f a b : expr) := expr.app (expr.app f a) b example (a b c x y : nat) (H : nat.add (nat.add x y) y = 0) : true := by do a ← get_local `a, b ← get_local `b, c ← get_local `c, H ← get_local `H >>= infer_type, (lhs, rhs) ← match_eq H, nat_add : expr ← mk_const `nat.add, p : pattern ← mk_pattern [] [a, b] (app2 nat_add a b) [] [app2 nat_add b a, a, b], trace (pattern.moutput p), [v₁, v₂, v₃] ← match_pattern p lhs | failed, trace v₁, trace v₂, trace v₃, constructor
78b7fe649367aadf641fed41a4e03894bfd29269
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/data/padics/ring_homs.lean
06ec8c3472d65d00c93443d0accd24d4f7fae22a
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
24,775
lean
/- Copyright (c) 2020 Johan Commelin and Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin and Robert Y. Lewis -/ import data.padics.padic_integers /-! # Relating `ℤ_[p]` to `zmod (p ^ n)` In this file we establish connections between the `p`-adic integers $\mathbb{Z}_p$ and the integers modulo powers of `p`, $\mathbb{Z}/p^n\mathbb{Z}$. ## Main declarations We show that $\mathbb{Z}_p$ has a ring hom to $\mathbb{Z}/p^n\mathbb{Z}$ for each `n`. The case for `n = 1` is handled separately, since it is used in the general construction and we may want to use it without the `^1` getting in the way. * `padic_int.to_zmod`: ring hom to `zmod p` * `padic_int.to_zmod_pow`: ring hom to `zmod (p^n)` * `padic_int.ker_to_zmod` / `padic_int.ker_to_zmod_pow`: the kernels of these maps are the ideals generated by `p^n` We also establish the universal property of $\mathbb{Z}_p$ as a projective limit. Given a family of compatible ring homs $f_k : R \to \mathbb{Z}/p^n\mathbb{Z}$, there is a unique limit $R \to \mathbb{Z}_p$. * `padic_int.lift`: the limit function * `padic_int.lift_spec` / `padic_int.lift_unique`: the universal property ## Implementation notes The ring hom constructions go through an auxiliary constructor `padic_int.to_zmod_hom`, which removes some boilerplate code. -/ noncomputable theory open_locale classical namespace padic_int open nat local_ring padic variables {p : ℕ} [hp_prime : fact (p.prime)] include hp_prime section ring_homs /-! ### Ring homomorphisms to `zmod p` and `zmod (p ^ n)` -/ variables (p) (r : ℚ) omit hp_prime /-- `mod_part p r` is an integer that satisfies `∥(r - mod_part p r : ℚ_[p])∥ < 1` when `∥(r : ℚ_[p])∥ ≤ 1`, see `padic_int.norm_sub_mod_part`. It is the unique non-negative integer that is `< p` with this property. (Note that this definition assumes `r : ℚ`. See `padic_int.zmod_repr` for a version that takes values in `ℕ` and works for arbitrary `x : ℤ_[p]`.) -/ def mod_part : ℤ := (r.num * gcd_a r.denom p) % p include hp_prime variable {p} lemma mod_part_lt_p : mod_part p r < p := begin convert int.mod_lt _ _, { simp }, { exact_mod_cast hp_prime.ne_zero } end lemma mod_part_nonneg : 0 ≤ mod_part p r := int.mod_nonneg _ $ by exact_mod_cast hp_prime.ne_zero lemma is_unit_denom (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : is_unit (r.denom : ℤ_[p]) := begin rw is_unit_iff, apply le_antisymm (r.denom : ℤ_[p]).2, rw [← not_lt, val_eq_coe, coe_coe], intro norm_denom_lt, have hr : ∥(r * r.denom : ℚ_[p])∥ = ∥(r.num : ℚ_[p])∥, { rw_mod_cast @rat.mul_denom_eq_num r, refl, }, rw padic_norm_e.mul at hr, have key : ∥(r.num : ℚ_[p])∥ < 1, { calc _ = _ : hr.symm ... < 1 * 1 : mul_lt_mul' h norm_denom_lt (norm_nonneg _) zero_lt_one ... = 1 : mul_one 1 }, have : ↑p ∣ r.num ∧ (p : ℤ) ∣ r.denom, { simp only [← norm_int_lt_one_iff_dvd, ← padic_norm_e_of_padic_int], norm_cast, exact ⟨key, norm_denom_lt⟩ }, apply hp_prime.not_dvd_one, rwa [← r.cop.gcd_eq_one, nat.dvd_gcd_iff, ← int.coe_nat_dvd_left, ← int.coe_nat_dvd], end lemma norm_sub_mod_part_aux (r : ℚ) (h : ∥(r : ℚ_[p])∥ ≤ 1) : ↑p ∣ r.num - r.num * r.denom.gcd_a p % p * ↑(r.denom) := begin rw ← zmod.int_coe_zmod_eq_zero_iff_dvd, simp only [int.cast_coe_nat, zmod.cast_mod_nat p, int.cast_mul, int.cast_sub], have := congr_arg (coe : ℤ → zmod p) (gcd_eq_gcd_ab r.denom p), simp only [int.cast_coe_nat, add_zero, int.cast_add, zmod.cast_self, int.cast_mul, zero_mul] at this, push_cast, rw [mul_right_comm, mul_assoc, ←this], suffices rdcp : r.denom.coprime p, { rw rdcp.gcd_eq_one, simp only [mul_one, cast_one, sub_self], }, apply coprime.symm, apply (coprime_or_dvd_of_prime ‹_› _).resolve_right, rw [← int.coe_nat_dvd, ← norm_int_lt_one_iff_dvd, not_lt], apply ge_of_eq, rw ← is_unit_iff, exact is_unit_denom r h, end lemma norm_sub_mod_part (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∥(⟨r,h⟩ - mod_part p r : ℤ_[p])∥ < 1 := begin let n := mod_part p r, by_cases aux : (⟨r,h⟩ - n : ℤ_[p]) = 0, { rw [aux, norm_zero], exact zero_lt_one, }, rw [norm_lt_one_iff_dvd, ← (is_unit_denom r h).dvd_mul_right], suffices : ↑p ∣ r.num - n * r.denom, { convert (int.cast_ring_hom ℤ_[p]).map_dvd this, simp only [sub_mul, int.cast_coe_nat, ring_hom.eq_int_cast, int.cast_mul, sub_left_inj, int.cast_sub], apply subtype.coe_injective, simp only [coe_mul, subtype.coe_mk, coe_coe], rw_mod_cast @rat.mul_denom_eq_num r, refl }, exact norm_sub_mod_part_aux r h end lemma exists_mem_range_of_norm_rat_le_one (h : ∥(r : ℚ_[p])∥ ≤ 1) : ∃ n : ℤ, 0 ≤ n ∧ n < p ∧ ∥(⟨r,h⟩ - n : ℤ_[p])∥ < 1 := ⟨mod_part p r, mod_part_nonneg _, mod_part_lt_p _, norm_sub_mod_part _ h⟩ lemma zmod_congr_of_sub_mem_span_aux (n : ℕ) (x : ℤ_[p]) (a b : ℤ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := begin rw [ideal.mem_span_singleton] at ha hb, rw [← sub_eq_zero, ← int.cast_sub, zmod.int_coe_zmod_eq_zero_iff_dvd, int.coe_nat_pow], rw [← dvd_neg, neg_sub] at ha, have := dvd_add ha hb, rwa [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, ← sub_eq_add_neg, ← int.cast_sub, pow_p_dvd_int_iff] at this, end lemma zmod_congr_of_sub_mem_span (n : ℕ) (x : ℤ_[p]) (a b : ℕ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := zmod_congr_of_sub_mem_span_aux n x a b ha hb lemma zmod_congr_of_sub_mem_max_ideal (x : ℤ_[p]) (m n : ℕ) (hm : x - m ∈ maximal_ideal ℤ_[p]) (hn : x - n ∈ maximal_ideal ℤ_[p]) : (m : zmod p) = n := begin rw maximal_ideal_eq_span_p at hm hn, have := zmod_congr_of_sub_mem_span_aux 1 x m n, simp only [_root_.pow_one] at this, specialize this hm hn, apply_fun zmod.cast_hom (show p ∣ p ^ 1, by rw nat.pow_one) (zmod p) at this, simpa only [ring_hom.map_int_cast], end variable (x : ℤ_[p]) lemma exists_mem_range : ∃ n : ℕ, n < p ∧ (x - n ∈ maximal_ideal ℤ_[p]) := begin simp only [maximal_ideal_eq_span_p, ideal.mem_span_singleton, ← norm_lt_one_iff_dvd], obtain ⟨r, hr⟩ := rat_dense (x : ℚ_[p]) zero_lt_one, have H : ∥(r : ℚ_[p])∥ ≤ 1, { rw norm_sub_rev at hr, calc _ = ∥(r : ℚ_[p]) - x + x∥ : by ring ... ≤ _ : padic_norm_e.nonarchimedean _ _ ... ≤ _ : max_le (le_of_lt hr) x.2 }, obtain ⟨n, hzn, hnp, hn⟩ := exists_mem_range_of_norm_rat_le_one r H, lift n to ℕ using hzn, use n, split, {exact_mod_cast hnp}, simp only [norm_def, coe_sub, subtype.coe_mk, coe_coe] at hn ⊢, rw show (x - n : ℚ_[p]) = (x - r) + (r - n), by ring, apply lt_of_le_of_lt (padic_norm_e.nonarchimedean _ _), apply max_lt hr, simpa using hn end /-- `zmod_repr x` is the unique natural number smaller than `p` satisfying `∥(x - zmod_repr x : ℤ_[p])∥ < 1`. -/ def zmod_repr : ℕ := classical.some (exists_mem_range x) lemma zmod_repr_spec : zmod_repr x < p ∧ (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := classical.some_spec (exists_mem_range x) lemma zmod_repr_lt_p : zmod_repr x < p := (zmod_repr_spec _).1 lemma sub_zmod_repr_mem : (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := (zmod_repr_spec _).2 /-- `to_zmod_hom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `zmod v`. -/ def to_zmod_hom (v : ℕ) (f : ℤ_[p] → ℕ) (f_spec : ∀ x, x - f x ∈ (ideal.span {v} : ideal ℤ_[p])) (f_congr : ∀ (x : ℤ_[p]) (a b : ℕ), x - a ∈ (ideal.span {v} : ideal ℤ_[p]) → x - b ∈ (ideal.span {v} : ideal ℤ_[p]) → (a : zmod v) = b) : ℤ_[p] →+* zmod v := { to_fun := λ x, f x, map_zero' := begin rw [f_congr (0 : ℤ_[p]) _ 0, cast_zero], { exact f_spec _ }, { simp only [sub_zero, cast_zero, submodule.zero_mem], } end, map_one' := begin rw [f_congr (1 : ℤ_[p]) _ 1, cast_one], { exact f_spec _ }, { simp only [sub_self, cast_one, submodule.zero_mem], } end, map_add' := begin intros x y, rw [f_congr (x + y) _ (f x + f y), cast_add], { exact f_spec _ }, { convert ideal.add_mem _ (f_spec x) (f_spec y), rw cast_add, ring, } end, map_mul' := begin intros x y, rw [f_congr (x * y) _ (f x * f y), cast_mul], { exact f_spec _ }, { let I : ideal ℤ_[p] := ideal.span {v}, have A : x * (y - f y) ∈ I := I.mul_mem_left (f_spec _), have B : (x - f x) * (f y) ∈ I := I.mul_mem_right (f_spec _), convert I.add_mem A B, rw cast_mul, ring, } end, } /-- `to_zmod` is a ring hom from `ℤ_[p]` to `zmod p`, with the equality `to_zmod x = (zmod_repr x : zmod p)`. -/ def to_zmod : ℤ_[p] →+* zmod p := to_zmod_hom p zmod_repr (by { rw ←maximal_ideal_eq_span_p, exact sub_zmod_repr_mem }) (by { rw ←maximal_ideal_eq_span_p, exact zmod_congr_of_sub_mem_max_ideal } ) /-- `z - (to_zmod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`. The coercion from `zmod p` to `ℤ_[p]` is `zmod.has_coe_t`, which coerces `zmod p` into artibrary rings. This is unfortunate, but a consequence of the fact that we allow `zmod p` to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`. This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides `p`. While this is not the case here we can still make use of the coercion. -/ lemma to_zmod_spec (z : ℤ_[p]) : z - (to_zmod z : ℤ_[p]) ∈ maximal_ideal ℤ_[p] := begin convert sub_zmod_repr_mem z using 2, dsimp [to_zmod, to_zmod_hom], unfreezingI { rcases (exists_eq_add_of_lt (hp_prime.pos)) with ⟨p', rfl⟩ }, change ↑(zmod.val _) = _, simp only [zmod.val_cast_nat, add_zero, add_def, cast_inj, zero_add], apply mod_eq_of_lt, simpa only [zero_add] using zmod_repr_lt_p z, end lemma ker_to_zmod : (to_zmod : ℤ_[p] →+* zmod p).ker = maximal_ideal ℤ_[p] := begin ext x, rw ring_hom.mem_ker, split, { intro h, simpa only [h, zmod.cast_zero, sub_zero] using to_zmod_spec x, }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod, to_zmod_hom], convert zmod_congr_of_sub_mem_max_ideal x _ 0 _ h, apply sub_zmod_repr_mem, } end /-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`. See `appr_spec`. -/ noncomputable def appr : ℤ_[p] → ℕ → ℕ | x 0 := 0 | x (n+1) := let y := x - appr x n in if hy : y = 0 then appr x n else let u := unit_coeff hy in appr x n + p ^ n * (to_zmod ((u : ℤ_[p]) * (p ^ (y.valuation - n).nat_abs))).val lemma appr_lt (x : ℤ_[p]) (n : ℕ) : x.appr n < p ^ n := begin induction n with n ih generalizing x, { simp only [appr, succ_pos', nat.pow_zero], }, simp only [appr, ring_hom.map_nat_cast, zmod.cast_self, ring_hom.map_pow, int.nat_abs, ring_hom.map_mul], have hp : p ^ n < p ^ (n + 1), { apply pow_lt_pow hp_prime.one_lt (lt_add_one n) }, split_ifs with h, { apply lt_trans (ih _) hp, }, { calc _ < p ^ n + p ^ n * (p - 1) : _ ... = p ^ (n + 1) : _, { apply add_lt_add_of_lt_of_le (ih _), apply nat.mul_le_mul_left, apply le_pred_of_lt, apply zmod.val_lt }, { rw [nat.mul_sub_left_distrib, mul_one, ← nat.pow_succ], apply nat.add_sub_cancel' (le_of_lt hp) } } end lemma appr_mono (x : ℤ_[p]) : monotone x.appr := begin apply monotone_of_monotone_nat, intro n, dsimp [appr], split_ifs, { refl, }, apply nat.le_add_right, end lemma dvd_appr_sub_appr (x : ℤ_[p]) (m n : ℕ) (h : m ≤ n) : p ^ m ∣ x.appr n - x.appr m := begin obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le h, clear h, induction k with k ih, { simp only [add_zero, nat.sub_self, dvd_zero], }, rw [nat.succ_eq_add_one, ← add_assoc], dsimp [appr], split_ifs with h, { exact ih }, rw [add_comm, nat.add_sub_assoc (appr_mono _ (nat.le_add_right m k))], apply dvd_add _ ih, apply dvd_mul_of_dvd_left, apply nat.pow_dvd_pow _ (nat.le_add_right m k), end lemma appr_spec (n : ℕ) : ∀ (x : ℤ_[p]), x - appr x n ∈ (ideal.span {p^n} : ideal ℤ_[p]) := begin simp only [ideal.mem_span_singleton], induction n with n ih, { simp only [is_unit_one, is_unit.dvd, pow_zero, forall_true_iff], }, { intro x, dsimp only [appr], split_ifs with h, { rw h, apply dvd_zero }, { push_cast, rw sub_add_eq_sub_sub, obtain ⟨c, hc⟩ := ih x, simp only [ring_hom.map_nat_cast, zmod.cast_self, ring_hom.map_pow, ring_hom.map_mul, zmod.nat_cast_val], have hc' : c ≠ 0, { rintro rfl, simp only [mul_zero] at hc, contradiction }, conv_rhs { congr, simp only [hc], }, rw show (x - ↑(appr x n)).valuation = (↑p ^ n * c).valuation, { rw hc }, rw [valuation_p_pow_mul _ _ hc', add_sub_cancel', pow_succ', ← mul_sub], apply mul_dvd_mul_left, by_cases hc0 : c.valuation.nat_abs = 0, { simp only [hc0, mul_one, pow_zero], rw [mul_comm, unit_coeff_spec h] at hc, suffices : c = unit_coeff h, { rw [← this, ← ideal.mem_span_singleton, ← maximal_ideal_eq_span_p], apply to_zmod_spec }, obtain ⟨c, rfl⟩ : is_unit c, -- TODO: write a can_lift instance for units { rw int.nat_abs_eq_zero at hc0, rw [is_unit_iff, norm_eq_pow_val hc', hc0, neg_zero, fpow_zero], }, rw discrete_valuation_ring.unit_mul_pow_congr_unit _ _ _ _ _ hc, exact irreducible_p }, { rw [_root_.zero_pow (nat.pos_of_ne_zero hc0)], simp only [sub_zero, zmod.cast_zero, mul_zero], rw unit_coeff_spec hc', apply dvd_mul_of_dvd_right, apply dvd_pow (dvd_refl _), exact hc0 } } } end attribute [irreducible] appr /-- A ring hom from `ℤ_[p]` to `zmod (p^n)`, with underlying function `padic_int.appr n`. -/ def to_zmod_pow (n : ℕ) : ℤ_[p] →+* zmod (p ^ n) := to_zmod_hom (p^n) (λ x, appr x n) (by { intros, convert appr_spec n _ using 1, simp }) (by { intros x a b ha hb, apply zmod_congr_of_sub_mem_span n x a b, { simpa using ha }, { simpa using hb } }) lemma ker_to_zmod_pow (n : ℕ) : (to_zmod_pow n : ℤ_[p] →+* zmod (p ^ n)).ker = ideal.span {p ^ n} := begin ext x, rw ring_hom.mem_ker, split, { intro h, suffices : x.appr n = 0, { convert appr_spec n x, simp only [this, sub_zero, cast_zero], }, dsimp [to_zmod_pow, to_zmod_hom] at h, rw zmod.nat_coe_zmod_eq_zero_iff_dvd at h, apply eq_zero_of_dvd_of_lt h (appr_lt _ _), }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod_pow, to_zmod_hom], rw [zmod_congr_of_sub_mem_span n x _ 0 _ h, cast_zero], apply appr_spec, } end @[simp] lemma zmod_cast_comp_to_zmod_pow (m n : ℕ) (h : m ≤ n) : (zmod.cast_hom (nat.pow_dvd_pow p h) (zmod (p ^ m))).comp (to_zmod_pow n) = to_zmod_pow m := begin apply zmod.ring_hom_eq_of_ker_eq, ext x, rw [ring_hom.mem_ker, ring_hom.mem_ker], simp only [function.comp_app, zmod.cast_hom_apply, ring_hom.coe_comp], simp only [to_zmod_pow, to_zmod_hom, ring_hom.coe_mk], rw [zmod.cast_nat_cast (nat.pow_dvd_pow p h), zmod_congr_of_sub_mem_span m (x.appr n) (x.appr n) (x.appr m)], { rw [sub_self], apply ideal.zero_mem _, }, { rw ideal.mem_span_singleton, rcases dvd_appr_sub_appr x m n h with ⟨c, hc⟩, use c, rw [← nat.cast_sub (appr_mono _ h), hc, nat.cast_mul, nat.cast_pow], }, { apply_instance } end @[simp] lemma cast_to_zmod_pow (m n : ℕ) (h : m ≤ n) (x : ℤ_[p]) : ↑(to_zmod_pow n x) = to_zmod_pow m x := by { rw ← zmod_cast_comp_to_zmod_pow _ _ h, refl } lemma dense_range_nat_cast : dense_range (nat.cast : ℕ → ℤ_[p]) := begin intro x, rw metric.mem_closure_range_iff, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, use (x.appr n), rw dist_eq_norm, apply lt_of_le_of_lt _ hn, rw norm_le_pow_iff_mem_span_pow, apply appr_spec, end lemma dense_range_int_cast : dense_range (int.cast : ℤ → ℤ_[p]) := begin intro x, apply dense_range_nat_cast.induction_on x, { exact is_closed_closure, }, { intro a, change (a.cast : ℤ_[p]) with (a : ℤ).cast, apply subset_closure, exact set.mem_range_self _ } end end ring_homs section lift /-! ### Universal property as projective limit -/ open cau_seq padic_seq variables {R : Type*} [comm_ring R] (f : Π k : ℕ, R →+* zmod (p^k)) (f_compat : ∀ k1 k2 (hk : k1 ≤ k2), (zmod.cast_hom (nat.pow_dvd_pow p hk) _).comp (f k2) = f k1) omit hp_prime /-- Given a family of ring homs `f : Π n : ℕ, R →+* zmod (p ^ n)`, `nth_hom f r` is an integer-valued sequence whose `n`th value is the unique integer `k` such that `0 ≤ k < p ^ n` and `f n r = (k : zmod (p ^ n))`. -/ def nth_hom (r : R) : ℕ → ℤ := λ n, (f n r : zmod (p^n)).val @[simp] lemma nth_hom_zero : nth_hom f 0 = 0 := by simp [nth_hom]; refl variable {f} include hp_prime include f_compat lemma pow_dvd_nth_hom_sub (r : R) (i j : ℕ) (h : i ≤ j) : ↑p ^ i ∣ nth_hom f r j - nth_hom f r i := begin specialize f_compat (i) (j) h, rw [← int.coe_nat_pow, ← zmod.int_coe_zmod_eq_zero_iff_dvd, int.cast_sub], dsimp [nth_hom], rw [← f_compat, ring_hom.comp_apply], have : fact (p ^ (i) > 0) := nat.pow_pos (nat.prime.pos ‹_›) _, have : fact (p ^ (j) > 0) := nat.pow_pos (nat.prime.pos ‹_›) _, unfreezingI { simp only [zmod.cast_id, zmod.cast_hom_apply, sub_self, zmod.nat_cast_val], }, end lemma is_cau_seq_nth_hom (r : R): is_cau_seq (padic_norm p) (λ n, nth_hom f r n) := begin intros ε hε, obtain ⟨k, hk⟩ : ∃ k : ℕ, (p ^ - (↑(k : ℕ) : ℤ) : ℚ) < ε := exists_pow_neg_lt_rat p hε, use k, intros j hj, refine lt_of_le_of_lt _ hk, norm_cast, rw ← padic_norm.dvd_iff_norm_le, exact_mod_cast pow_dvd_nth_hom_sub f_compat r k j hj end /-- `nth_hom_seq f_compat r` bundles `padic_int.nth_hom f r` as a Cauchy sequence of rationals with respect to the `p`-adic norm. The `n`th value of the sequence is `((f n r).val : ℚ)`. -/ def nth_hom_seq (r : R) : padic_seq p := ⟨λ n, nth_hom f r n, is_cau_seq_nth_hom f_compat r⟩ lemma nth_hom_seq_one : nth_hom_seq f_compat 1 ≈ 1 := begin intros ε hε, change _ < _ at hε, use 1, intros j hj, haveI : fact (1 < p^j) := nat.one_lt_pow _ _ (by linarith) (nat.prime.one_lt ‹_›), simp [nth_hom_seq, nth_hom, zmod.val_one, hε], end lemma nth_hom_seq_add (r s : R) : nth_hom_seq f_compat (r + s) ≈ nth_hom_seq f_compat r + nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_add, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], have : fact (p ^ n > 0) := nat.pow_pos (nat.prime.pos ‹_›) _, have : fact (p ^ j > 0) := nat.pow_pos (nat.prime.pos ‹_›) _, unfreezingI { simp only [int.cast_coe_nat, int.cast_add, ring_hom.map_add, int.cast_sub, zmod.nat_cast_val] }, rw [zmod.cast_add (show p ^ n ∣ p ^ j, from _), sub_self], { apply_instance }, { apply nat.pow_dvd_pow, linarith only [hj] }, end lemma nth_hom_seq_mul (r s : R) : nth_hom_seq f_compat (r * s) ≈ nth_hom_seq f_compat r * nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_mul, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], have : fact (p ^ n > 0) := nat.pow_pos (nat.prime.pos ‹_›) _, have : fact (p ^ j > 0) := nat.pow_pos (nat.prime.pos ‹_›) _, unfreezingI { simp only [int.cast_coe_nat, int.cast_mul, int.cast_sub, ring_hom.map_mul, zmod.nat_cast_val] }, rw [zmod.cast_mul (show p ^ n ∣ p ^ j, from _), sub_self], { apply_instance }, { apply nat.pow_dvd_pow, linarith only [hj] }, end /-- `lim_nth_hom f_compat r` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`. This is itself a ring hom: see `padic_int.lift`. -/ def lim_nth_hom (r : R) : ℤ_[p] := of_int_seq (nth_hom f r) (is_cau_seq_nth_hom f_compat r) lemma lim_nth_hom_spec (r : R) : ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ n ≥ N, ∥lim_nth_hom f_compat r - nth_hom f r n∥ < ε := begin intros ε hε, obtain ⟨ε', hε'0, hε'⟩ : ∃ v : ℚ, (0 : ℝ) < v ∧ ↑v < ε := exists_rat_btwn hε, norm_cast at hε'0, obtain ⟨N, hN⟩ := padic_norm_e.defn (nth_hom_seq f_compat r) hε'0, use N, intros n hn, apply lt.trans _ hε', change ↑(padic_norm_e _) < _, norm_cast, convert hN _ hn, simp [nth_hom, lim_nth_hom, nth_hom_seq, of_int_seq], end lemma lim_nth_hom_zero : lim_nth_hom f_compat 0 = 0 := by simp [lim_nth_hom]; refl lemma lim_nth_hom_one : lim_nth_hom f_compat 1 = 1 := subtype.ext $ quot.sound $ nth_hom_seq_one _ lemma lim_nth_hom_add (r s : R) : lim_nth_hom f_compat (r + s) = lim_nth_hom f_compat r + lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_add _ _ _ lemma lim_nth_hom_mul (r s : R) : lim_nth_hom f_compat (r * s) = lim_nth_hom f_compat r * lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_mul _ _ _ -- TODO: generalize this to arbitrary complete discrete valuation rings /-- `lift f_compat` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`, with the equality `lift f_compat r = padic_int.lim_nth_hom f_compat r`. -/ def lift : R →+* ℤ_[p] := { to_fun := lim_nth_hom f_compat, map_one' := lim_nth_hom_one f_compat, map_mul' := lim_nth_hom_mul f_compat, map_zero' := lim_nth_hom_zero f_compat, map_add' := lim_nth_hom_add f_compat } omit f_compat lemma lift_sub_val_mem_span (r : R) (n : ℕ) : (lift f_compat r - (f n r).val) ∈ (ideal.span {↑p ^ n} : ideal ℤ_[p]) := begin obtain ⟨k, hk⟩ := lim_nth_hom_spec f_compat r _ (show (0 : ℝ) < p ^ (-n : ℤ), from nat.fpow_pos_of_pos hp_prime.pos _), have := le_of_lt (hk (max n k) (le_max_right _ _)), rw norm_le_pow_iff_mem_span_pow at this, dsimp [lift], rw sub_eq_sub_add_sub (lim_nth_hom f_compat r) _ ↑(nth_hom f r (max n k)), apply ideal.add_mem _ _ this, rw [ideal.mem_span_singleton], simpa only [ring_hom.eq_int_cast, ring_hom.map_pow, int.cast_sub] using (int.cast_ring_hom ℤ_[p]).map_dvd (pow_dvd_nth_hom_sub f_compat r n (max n k) (le_max_left _ _)), end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_unique`. -/ lemma lift_spec (n : ℕ) : (to_zmod_pow n).comp (lift f_compat) = f n := begin ext r, haveI : fact (0 < p ^ n) := nat.pow_pos (nat.prime.pos ‹_›) n, rw [ring_hom.comp_apply, ← zmod.cast_val (f n r), ← (to_zmod_pow n).map_nat_cast, ← sub_eq_zero, ← ring_hom.map_sub, ← ring_hom.mem_ker, ker_to_zmod_pow], apply lift_sub_val_mem_span, end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_spec`. -/ lemma lift_unique (g : R →+* ℤ_[p]) (hg : ∀ n, (to_zmod_pow n).comp g = f n) : lift f_compat = g := begin ext1 r, apply eq_of_forall_dist_le, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, apply le_trans _ (le_of_lt hn), rw [dist_eq_norm, norm_le_pow_iff_mem_span_pow, ← ker_to_zmod_pow, ring_hom.mem_ker, ring_hom.map_sub, ← ring_hom.comp_apply, ← ring_hom.comp_apply, lift_spec, hg, sub_self], end @[simp] lemma lift_self (z : ℤ_[p]) : @lift p _ ℤ_[p] _ to_zmod_pow zmod_cast_comp_to_zmod_pow z = z := begin show _ = ring_hom.id _ z, rw @lift_unique p _ ℤ_[p] _ _ zmod_cast_comp_to_zmod_pow (ring_hom.id ℤ_[p]), intro, rw ring_hom.comp_id, end end lift lemma ext_of_to_zmod_pow {x y : ℤ_[p]} : (∀ n, to_zmod_pow n x = to_zmod_pow n y) ↔ x = y := begin split, { intro h, rw [← lift_self x, ← lift_self y], simp [lift, lim_nth_hom, nth_hom, h] }, { rintro rfl _, refl } end lemma to_zmod_pow_eq_iff_ext {R : Type*} [comm_ring R] {g g' : R →+* ℤ_[p]} : (∀ n, (to_zmod_pow n).comp g = (to_zmod_pow n).comp g') ↔ g = g' := begin split, { intro hg, ext x : 1, apply ext_of_to_zmod_pow.mp, intro n, show (to_zmod_pow n).comp g x = (to_zmod_pow n).comp g' x, rw hg n }, { rintro rfl _, refl } end end padic_int
2ed9e4243f17914fea1b72d9826c6b62e0eb5702
7490bf5d40d31857a58062614642bb5a41c36154
/dm_prod_test.lean
d62723a352d108169aa15e44dcdf8a252c29e188
[]
no_license
reesegrayallen/Lean-Discrete-Mathematics
9f1d6fe1c814cc9264ce868a67adcf5a82566e22
00c875284613ea12e0a729f519738aab8599456b
refs/heads/main
1,674,181,372,629
1,606,801,004,000
1,606,801,004,000
317,387,970
0
0
null
null
null
null
UTF-8
Lean
false
false
1,497
lean
/- HOMEWORK 3 Reese Allen (rga2uz) CS2102 - Sullivan -/ import .dm_prod -- defining ordered pairs to use in testing def p1 := dm_prod.mk 5 2 def p2 := dm_prod.mk 3 tt def p3 := dm_prod.mk ff tt #check p1 -- dm_prod ℕ ℕ #check p2 -- dm_prod ℕ bool #check p3 -- dm_prod bool bool -- additional ordered pairs def p4 := dm_prod.mk "yes" "no" def p5 := dm_prod.mk (3, 4) ff def p6 := dm_prod.mk "seven" 7 -- test cases for fst #reduce fst p1 #reduce fst p2 #reduce fst p3 #eval fst' p4 #reduce fst' p5 #eval fst' p6 #reduce fst'' p1 #reduce fst'' p3 #reduce fst'' p5 -- test cases for snd #reduce snd p1 #reduce snd p2 #reduce snd p3 #eval snd' p4 #reduce snd' p5 #eval snd' p6 #reduce snd'' p1 #reduce snd'' p3 #reduce snd'' p5 -- test cases for set_fst #reduce set_fst p1 ff #reduce set_fst p2 (1, 100) #reduce set_fst p3 1 #reduce set_fst' p1 7 #reduce set_fst' p2 (1, 100) #reduce set_fst' p3 tt #reduce set_fst'' p1 (100, 1) #reduce set_fst'' p2 ff #reduce set_fst'' p3 4 -- test cases for set_snd #reduce set_snd p1 ff #reduce set_snd p2 (1, 100) #reduce set_snd p3 1 #reduce set_snd' p1 7 #reduce set_snd' p2 (1, 100, 1000) #reduce set_snd' p3 (tt, 5) #reduce set_snd'' p5 (ff, tt) #reduce set_snd'' p3 ff #reduce set_snd'' p5 9 -- test cases for swap #reduce swap p1 #reduce swap p2 #reduce swap p3 #reduce swap' p3 #reduce swap' p5 #reduce swap' p1 #reduce swap'' p1 #reduce swap'' p2 #reduce swap'' p5
57e06b0984e00e05764e7a4e500f9a3cc2ef6c79
92b50235facfbc08dfe7f334827d47281471333b
/hott/init/num.hlean
5e67d8aa70eb65feabcf6386ed900ceb7350073c
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
3,360
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic init.bool open bool definition pos_num.is_inhabited [instance] : inhabited pos_num := inhabited.mk pos_num.one namespace pos_num definition is_one (a : pos_num) : bool := pos_num.rec_on a tt (λn r, ff) (λn r, ff) definition pred (a : pos_num) : pos_num := pos_num.rec_on a one (λn r, bit0 n) (λn r, cond (is_one n) one (bit1 r)) definition size (a : pos_num) : pos_num := pos_num.rec_on a one (λn r, succ r) (λn r, succ r) definition add (a b : pos_num) : pos_num := pos_num.rec_on a succ (λn f b, pos_num.rec_on b (succ (bit1 n)) (λm r, succ (bit1 (f m))) (λm r, bit1 (f m))) (λn f b, pos_num.rec_on b (bit1 n) (λm r, bit1 (f m)) (λm r, bit0 (f m))) b notation a + b := add a b definition mul (a b : pos_num) : pos_num := pos_num.rec_on a b (λn r, bit0 r + b) (λn r, bit0 r) notation a * b := mul a b definition lt (a b : pos_num) : bool := pos_num.rec_on a (λ b, pos_num.cases_on b ff (λm, tt) (λm, tt)) (λn f b, pos_num.cases_on b ff (λm, f m) (λm, f m)) (λn f b, pos_num.cases_on b ff (λm, f (succ m)) (λm, f m)) b definition le (a b : pos_num) : bool := lt a (succ b) definition equal (a b : pos_num) : bool := le a b && le b a end pos_num definition num.is_inhabited [instance] : inhabited num := inhabited.mk num.zero namespace num open pos_num definition pred (a : num) : num := num.rec_on a zero (λp, cond (is_one p) zero (pos (pred p))) definition size (a : num) : num := num.rec_on a (pos one) (λp, pos (size p)) definition add (a b : num) : num := num.rec_on a b (λpa, num.rec_on b (pos pa) (λpb, pos (pos_num.add pa pb))) definition mul (a b : num) : num := num.rec_on a zero (λpa, num.rec_on b zero (λpb, pos (pos_num.mul pa pb))) notation a + b := add a b notation a * b := mul a b definition le (a b : num) : bool := num.rec_on a tt (λpa, num.rec_on b ff (λpb, pos_num.le pa pb)) private definition psub (a b : pos_num) : num := pos_num.rec_on a (λb, zero) (λn f b, cond (pos_num.le (bit1 n) b) zero (pos_num.cases_on b (pos (bit0 n)) (λm, 2 * f m) (λm, 2 * f m + 1))) (λn f b, cond (pos_num.le (bit0 n) b) zero (pos_num.cases_on b (pos (pos_num.pred (bit0 n))) (λm, pred (2 * f m)) (λm, 2 * f m))) b definition sub (a b : num) : num := num.rec_on a zero (λpa, num.rec_on b a (λpb, psub pa pb)) notation a ≤ b := le a b notation a - b := sub a b end num -- the coercion from num to nat is defined here, -- so that it can already be used in init.trunc and init.tactic namespace nat definition add (a b : nat) : nat := nat.rec_on b a (λ b₁ r, succ r) notation a + b := add a b definition of_num [coercion] (n : num) : nat := num.rec zero (λ n, pos_num.rec (succ zero) (λ n r, r + r + (succ zero)) (λ n r, r + r) n) n end nat attribute nat.of_num [reducible] [constructor] -- of_num is also reducible if namespace "nat" is not opened
90e7a627b191e18545d9372491725e8f897615a4
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/list/chain.lean
29a547f48b65223b98a5a9e301caca543d09954e
[ "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
7,553
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau, Yury Kudryashov -/ import data.list.pairwise universes u v open nat variables {α : Type u} {β : Type v} namespace list /- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/ run_cmd tactic.mk_iff_of_inductive_prop `list.chain `list.chain_iff variable {R : α → α → Prop} theorem rel_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : R a b := (chain_cons.1 p).1 theorem chain_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : chain R b l := (chain_cons.1 p).2 theorem chain.imp' {S : α → α → Prop} (HRS : ∀ ⦃a b⦄, R a b → S a b) {a b : α} (Hab : ∀ ⦃c⦄, R a c → S b c) {l : list α} (p : chain R a l) : chain S b l := by induction p with _ a c l r p IH generalizing b; constructor; [exact Hab r, exact IH (@HRS _)] theorem chain.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l := p.imp' H (H a) theorem chain.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l := ⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩ theorem chain.iff_mem {a : α} {l : list α} : chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l := ⟨λ p, by induction p with _ a b l r p IH; constructor; [exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩, exact IH.imp (λ a b ⟨am, bm, h⟩, ⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)], chain.imp (λ a b h, h.2.2)⟩ theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b := by simp only [chain_cons, chain.nil, and_true] theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔ chain R a (l₁++[b]) ∧ chain R b l₂ := by induction l₁ with x l₁ IH generalizing a; simp only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, and_assoc] theorem chain_map (f : β → α) {b : β} {l : list β} : chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l := by induction l generalizing b; simp only [map, chain.nil, chain_cons, *] theorem chain_of_chain_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α} (p : chain S (f a) (map f l)) : chain R a l := ((chain_map f).1 p).imp H theorem chain_map_of_chain {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α} (p : chain R a l) : chain S (f a) (map f l) := (chain_map f).2 $ p.imp H theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l := begin cases pairwise_cons.1 p with r p', clear p, induction p' with b l r' p IH generalizing a, {exact chain.nil}, simp only [chain_cons, forall_mem_cons] at r, exact chain_cons.2 ⟨r.1, IH r'⟩ end theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} : chain R a l ↔ pairwise R (a::l) := ⟨λ c, begin induction c with b b c l r p IH, {exact pairwise_singleton _ _}, apply IH.cons _, simp only [mem_cons_iff, forall_mem_cons', r, true_and], show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)), end, chain_of_pairwise⟩ theorem chain_iff_nth_le {R} : ∀ {a : α} {l : list α}, chain R a l ↔ (∀ h : 0 < length l, R a (nth_le l 0 h)) ∧ (∀ i (h : i < length l - 1), R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h))) | a [] := by simp | a (b :: t) := begin rw [chain_cons, chain_iff_nth_le], split, { rintros ⟨R, ⟨h0, h⟩⟩, split, { intro w, exact R, }, { intros i w, cases i, { apply h0, }, { convert h i _ using 1, simp only [succ_eq_add_one, add_succ_sub_one, add_zero, length, add_lt_add_iff_right] at w, exact lt_pred_iff.mpr w, } } }, { rintros ⟨h0, h⟩, split, { apply h0, simp, }, { split, { apply h 0, }, { intros i w, convert h (i+1) _, exact lt_pred_iff.mp w, } } }, end theorem chain'.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} (p : chain' R l) : chain' S l := by cases l; [trivial, exact p.imp H] theorem chain'.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : chain' R l ↔ chain' S l := ⟨chain'.imp (λ a b, (H a b).1), chain'.imp (λ a b, (H a b).2)⟩ theorem chain'.iff_mem : ∀ {l : list α}, chain' R l ↔ chain' (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l | [] := iff.rfl | (x::l) := ⟨λ h, (chain.iff_mem.1 h).imp $ λ a b ⟨h₁, h₂, h₃⟩, ⟨h₁, or.inr h₂, h₃⟩, chain'.imp $ λ a b h, h.2.2⟩ @[simp] theorem chain'_nil : chain' R [] := trivial @[simp] theorem chain'_singleton (a : α) : chain' R [a] := chain.nil theorem chain'_split {a : α} : ∀ {l₁ l₂ : list α}, chain' R (l₁++a::l₂) ↔ chain' R (l₁++[a]) ∧ chain' R (a::l₂) | [] l₂ := (and_iff_right (chain'_singleton a)).symm | (b::l₁) l₂ := chain_split theorem chain'_map (f : β → α) {l : list β} : chain' R (map f l) ↔ chain' (λ a b : β, R (f a) (f b)) l := by cases l; [refl, exact chain_map _] theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : chain' S (map f l)) : chain' R l := ((chain'_map f).1 p).imp H theorem chain'_map_of_chain' {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : chain' R l) : chain' S (map f l) := (chain'_map f).2 $ p.imp H theorem pairwise.chain' : ∀ {l : list α}, pairwise R l → chain' R l | [] _ := trivial | (a::l) h := chain_of_pairwise h theorem chain'_iff_pairwise (tr : transitive R) : ∀ {l : list α}, chain' R l ↔ pairwise R l | [] := (iff_true_intro pairwise.nil).symm | (a::l) := chain_iff_pairwise tr @[simp] theorem chain'_cons {x y l} : chain' R (x :: y :: l) ↔ R x y ∧ chain' R (y :: l) := chain_cons theorem chain'.cons {x y l} (h₁ : R x y) (h₂ : chain' R (y :: l)) : chain' R (x :: y :: l) := chain'_cons.2 ⟨h₁, h₂⟩ theorem chain'.tail : ∀ {l} (h : chain' R l), chain' R l.tail | [] _ := trivial | [x] _ := trivial | (x :: y :: l) h := (chain'_cons.mp h).right theorem chain'_pair {x y} : chain' R [x, y] ↔ R x y := by simp only [chain'_singleton, chain'_cons, and_true] theorem chain'_reverse : ∀ {l}, chain' R (reverse l) ↔ chain' (flip R) l | [] := iff.rfl | [a] := by simp only [chain'_singleton, reverse_singleton] | (a :: b :: l) := by rw [chain'_cons, reverse_cons, reverse_cons, append_assoc, cons_append, nil_append, chain'_split, ← reverse_cons, @chain'_reverse (b :: l), and_comm, chain'_pair, flip] theorem chain'_iff_nth_le {R} : ∀ {l : list α}, chain' R l ↔ ∀ i (h : i < length l - 1), R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h)) | [] := by simp | (a :: nil) := by simp | (a :: b :: t) := begin rw [chain'_cons, chain'_iff_nth_le], split, { rintros ⟨R, h⟩ i w, cases i, { exact R, }, { convert h i _ using 1, simp only [succ_eq_add_one, add_succ_sub_one, add_zero, length, add_lt_add_iff_right] at w, simpa using w, }, }, { rintros h, split, { apply h 0, simp, }, { intros i w, convert h (i+1) _, simp only [add_zero, length, add_succ_sub_one] at w, simpa using w, } }, end end list
ba34740881e78e7631a3efcf036b41fbd65ff48c
8be24982c807641260370bd09243eac768750811
/src/test.lean
3b8aaa3c79bb1c61472cd9783a808017288f4cc5
[]
no_license
jjaassoonn/transcendental
8008813253af3aa80b5a5c56551317e7ab4246ab
99bc6ea6089f04ed90a0f55f0533ebb7f47b22ff
refs/heads/master
1,607,869,957,944
1,599,659,687,000
1,599,659,687,000
234,444,826
9
1
null
1,598,218,307,000
1,579,224,232,000
HTML
UTF-8
Lean
false
false
8,676
lean
import measure_theory.set_integral import measure_theory.bochner_integration import measure_theory.interval_integral import measure_theory.lebesgue_measure import analysis.special_functions.exp_log import small_things import tactic noncomputable theory open_locale classical open_locale big_operators notation α`[X]` := polynomial α -- F(x) = ∫ t in a .. x, f t -- F'(x) = f(x) for x in [a,b] private lemma ftc1 (f : ℝ -> ℝ) {hf : measurable f} {hf2 : continuous f} (a b : ℝ) (h : a ≤ b) {hf3 : measure_theory.integrable_on f (set.Icc a b)} (x0 : ℝ) (hx0 : x0 ∈ set.Icc a b) : has_deriv_at (λ (b : ℝ), ∫ (x : ℝ) in a..b, f x) (f x0) x0 := begin apply interval_integral.integral_has_deriv_at_of_tendsto_ae, simp only [], exact hf, unfold interval_integrable, split, apply measure_theory.integrable_on.mono hf3, intros y hy, simp only [set.mem_Ioc, set.mem_Icc] at ⊢ hy hx0, split, linarith, linarith, apply le_refl _, apply measure_theory.integrable_on.mono hf3, intros y hy, simp only [set.mem_Ioc, set.mem_Icc] at ⊢ hy hx0, split, linarith, linarith, apply le_refl _, apply filter.tendsto_inf_left, exact continuous.tendsto hf2 x0, end /-- # Assumption-/ /-Theorem fundamental theorem of calculus and integration by part is assumed. I am waiting for them to arrive in `mathlib` and I will update this part and prove relatvent additional assumptions. -/ theorem ftc' (F f: ℝ -> ℝ) {hF : differentiable ℝ F} {F_deriv : deriv F = f} {hf : measurable f} {hf1 : continuous f} (a b : ℝ) (h : b ≥ a) : (∫ x in a..b, f x) = F b - F a := begin by_cases hab : (a = b), rw hab, simp only [interval_integral.integral_same, sub_self], set G := (λ x, (∫ t in a..x, f t)) with hG, have prop := ftc1 f a b h, rw <-hG at prop, have hG1 : differentiable_on ℝ G (set.Icc a b), { intros x hx, have prop := ftc1 f a b h x hx, refine differentiable_at.differentiable_within_at _, rw hG, exact has_deriv_at.differentiable_at prop, exact hf, exact hf1, apply continuous.integrable_on_compact _ hf1, exact real.locally_finite_volume, exact compact_Icc, }, have H : (set.Icc a b).indicator (deriv G) = (set.Icc a b).indicator f, { apply set.indicator_congr, intros x0 hx0, replace prop := prop x0 hx0, exact has_deriv_at.deriv prop, }, have H2 : (set.Icc a b).indicator (deriv G) = (set.Icc a b).indicator (deriv F), { exact eq.trans H (congr_arg (set.Icc a b).indicator (eq.symm F_deriv)), }, replace H2 : ∀ y ∈ set.Icc a b, (deriv (F - G)) y = 0, { intros y hy, change deriv (λ t, F t - G t) y = 0, rw deriv_sub, rw sub_eq_zero, have eq1 : (set.Icc a b).indicator (deriv F) y = deriv F y, exact if_pos hy, rw <-eq1, have eq2 : (set.Icc a b).indicator (deriv G) y = deriv G y, exact if_pos hy, rw <-eq2, exact congr_fun H2.symm y, dsimp only [], exact hF y, dsimp only [], exact has_deriv_at.differentiable_at (prop y hy), }, have key : ∀ y ∈ set.Ioc a b, (F - G) y = (F - G) a, { intros y hy, have ineq : a < y, simp only [set.mem_Ioc] at hy, exact hy.1, have key := exists_deriv_eq_slope (F - G) ineq _ _, rcases key with ⟨c, hc, hc2⟩, have hc' : c ∈ set.Icc a b, simp only [set.mem_Icc, set.mem_Ioc, set.mem_Ioo] at hy ⊢ hc, split, linarith, linarith, rw H2 c hc' at hc2, replace hc2 := eq.symm hc2, rw div_eq_zero_iff at hc2, cases hc2, exact sub_eq_zero.mp hc2, simp only [set.mem_Icc, set.mem_Ioc, set.mem_Ioo] at hy ⊢ hc, linarith, apply continuous_on.sub, simp only [], apply continuous.continuous_on, apply differentiable.continuous hF, have hG1' : continuous_on G (set.Icc a b), apply differentiable_on.continuous_on hG1, simp only [], apply continuous_on.mono hG1', apply set.Icc_subset_Icc, exact le_refl a, exact hy.2, apply differentiable_on.sub, simp only [], exact differentiable.differentiable_on hF, simp only [], apply differentiable_on.mono hG1, intros z hz, simp only [set.mem_Icc, set.mem_Ioc, set.mem_Ioo] at *, split, linarith, linarith, }, have G_a : G a = 0, { rw hG, simp only [interval_integral.integral_same], }, have G_b : G b = ∫ x in a .. b, f x, { rw hG, }, rw <-G_b, have eq : G b = G b - 0, rw sub_zero, rw eq, rw <-G_a, rw sub_eq_sub_iff_sub_eq_sub, suffices : F b - G b = F a - G a, linarith, replace key := key b _, simp only [pi.sub_apply] at key ⊢, exact key, simp only [set.mem_Icc, set.mem_Ioc, set.mem_Ioo] at *, split, exact lt_of_le_of_ne h hab, exact le_refl b, exact hf, exact hf1, apply measure_theory.integrable_on.mono_set (continuous.integrable_on_compact (@compact_Icc a b) hf1), exact set.subset.rfl, exact real.locally_finite_volume, end theorem ftc (f: ℝ -> ℝ) {hf : differentiable ℝ f} {hf2 : measurable (deriv f)} {hf3 : continuous (deriv f)} (a b : ℝ) (h : b ≥ a) : (∫ x in a..b, (deriv f) x) = f b - f a := begin refine ftc' f (deriv f) a b h, simp only [], exact hf, refl, exact hf2, exact hf3, end theorem integrate_by_part (f g : ℝ -> ℝ) {hf : differentiable ℝ f} {hf2 : measurable (deriv f)} {hf3 : measurable f} {hf4 : continuous (deriv f)} {hg : differentiable ℝ g} {hg2 : measurable (deriv g)} {hg3 : measurable g} {hg4 : continuous (deriv g)} (a b : ℝ) (h : b ≥ a) : (∫ x in a..b, (f x)*(deriv g x)) = (f b) * (g b) - (f a) * (g a) - (∫ x in a..b, (deriv f x) * (g x)) := begin have eq1 := ftc (f * g) a b h, have eq2 : (∫ (x : ℝ) in a..b, deriv (f * g) x) = (∫ (x : ℝ) in a..b, (deriv f x) * g x + f x * (deriv g x)), { rw interval_integral.integral_of_le h, rw interval_integral.integral_of_le h, apply congr_arg, ext y, apply deriv_mul, simp only [], exact hf y, simp only [], exact hg y, }, rw eq2 at eq1, rw interval_integral.integral_add at eq1, simp only [pi.mul_apply] at eq1 ⊢, rw <-eq1, simp only [add_sub_cancel'], apply measurable.mul, simp only [], exact hf2, simp only [], exact hg3, rw interval_integrable, have H1 : continuous (λ x, (deriv f x) * g x), { apply continuous.mul _ _, exact normed_ring_top_monoid, exact hf4, apply @differentiable.continuous ℝ _ ℝ _ _ ℝ _ _ _, exact hg, }, split, apply measure_theory.integrable_on.mono_set (continuous.integrable_on_compact (@compact_Icc a b) H1), exact set.Ioc_subset_Icc_self, exact real.locally_finite_volume, apply measure_theory.integrable_on.mono_set (continuous.integrable_on_compact (@compact_Icc a b) H1), rw set.Ioc_eq_empty, exact (set.Icc a b).empty_subset, exact h, exact real.locally_finite_volume, apply measurable.mul, exact hf3, exact hg2, rw interval_integrable, have H2 : continuous (λ x, f x * deriv g x), { apply continuous.mul _ _, exact normed_ring_top_monoid, apply @differentiable.continuous ℝ _ ℝ _ _ ℝ _ _ _, exact hf, exact hg4, }, split, apply measure_theory.integrable_on.mono_set (continuous.integrable_on_compact (@compact_Icc a b) H2), exact set.Ioc_subset_Icc_self, exact real.locally_finite_volume, apply measure_theory.integrable_on.mono_set (continuous.integrable_on_compact (@compact_Icc a b) H2), rw set.Ioc_eq_empty, exact (set.Icc a b).empty_subset, exact h, exact real.locally_finite_volume, apply differentiable.mul hf hg, apply continuous.measurable, { have eq1 : deriv (f * g) = (deriv f) * g + f * (deriv g), ext, simp only [pi.add_apply, pi.mul_apply], change (deriv (λ x, (f x * g x))) x = deriv f x * g x + f x * deriv g x, rw deriv_mul, simp only [], exact hf x, simp only [], exact hg x, rw eq1, apply continuous.add _ _, exact normed_top_monoid, apply continuous.mul _ _, exact normed_ring_top_monoid, exact hf4, apply differentiable.continuous hg, apply continuous.mul _ _, exact normed_ring_top_monoid, apply differentiable.continuous hf, exact hg4, }, { have eq1 : deriv (f * g) = (deriv f) * g + f * (deriv g), ext, simp only [pi.add_apply, pi.mul_apply], change (deriv (λ x, (f x * g x))) x = deriv f x * g x + f x * deriv g x, rw deriv_mul, simp only [], exact hf x, simp only [], exact hg x, rw eq1, apply continuous.add _ _, exact normed_top_monoid, apply continuous.mul _ _, exact normed_ring_top_monoid, exact hf4, apply differentiable.continuous hg, apply continuous.mul _ _, exact normed_ring_top_monoid, apply differentiable.continuous hf, exact hg4, }, end
908f21c9b01bbd37f15d4a03d7b8dc0dd250cafc
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/mismatch.lean
9c18bf3502620466d96e4c629ac5370e3af3f74a
[ "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
82
lean
-- definition id {A : Type} {a : A} := a definition o : num := 1 check @id nat o
5e6c75c64cd3f43719ef477916221b4923a2ac0e
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/hhg/nat.lean
92358b313ddb59ae6786d334d8dee6a632d89de4
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
406
lean
inductive nat2 : Type | zero : nat2 | succ : nat2 -> nat2 --#print nat2 inductive aexp : Type | num : nat -> aexp -- TODO: need Z | var : string -> aexp | add : aexp -> aexp -> aexp | sub : aexp -> aexp -> aexp | mul : aexp -> aexp -> aexp | div : aexp -> aexp -> aexp lemma add_zero2 : ∀ (n : ℕ), 0 + n = n := begin intros n, induction n with n IH, {reflexivity}, {simp} end
a40b1a06efdda94c432601682b65650cd60d9f3a
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/real/pi/bounds.lean
48790c51e6d406b7a8e5c22549d5d37c7fc9e965
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
7,798
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Mario Carneiro -/ import analysis.special_functions.trigonometric.basic /-! # Pi This file contains lemmas which establish bounds on `real.pi`. Notably, these include `pi_gt_sqrt_two_add_series` and `pi_lt_sqrt_two_add_series`, which bound `π` using series; numerical bounds on `π` such as `pi_gt_314`and `pi_lt_315` (more precise versions are given, too). See also `data.real.pi.leibniz` and `data.real.pi.wallis` for infinite formulas for `π`. -/ open_locale real namespace real lemma pi_gt_sqrt_two_add_series (n : ℕ) : 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) < π := begin have : sqrt (2 - sqrt_two_add_series 0 n) / 2 * 2 ^ (n+2) < π, { rw [← lt_div_iff, ←sin_pi_over_two_pow_succ], apply sin_lt, apply div_pos pi_pos, all_goals { apply pow_pos, norm_num } }, apply lt_of_le_of_lt (le_of_eq _) this, rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num end lemma pi_lt_sqrt_two_add_series (n : ℕ) : π < 2 ^ (n+1) * sqrt (2 - sqrt_two_add_series 0 n) + 1 / 4 ^ n := begin have : π < (sqrt (2 - sqrt_two_add_series 0 n) / 2 + 1 / (2 ^ n) ^ 3 / 4) * 2 ^ (n+2), { rw [← div_lt_iff, ← sin_pi_over_two_pow_succ], refine lt_of_lt_of_le (lt_add_of_sub_right_lt (sin_gt_sub_cube _ _)) _, { apply div_pos pi_pos, apply pow_pos, norm_num }, { rw div_le_iff', { refine le_trans pi_le_four _, simp only [show ((4 : ℝ) = 2 ^ 2), by norm_num, mul_one], apply pow_le_pow, norm_num, apply le_add_of_nonneg_left, apply nat.zero_le }, { apply pow_pos, norm_num } }, apply add_le_add_left, rw div_le_div_right, rw [le_div_iff, ←mul_pow], refine le_trans _ (le_of_eq (one_pow 3)), apply pow_le_pow_of_le_left, { apply le_of_lt, apply mul_pos, apply div_pos pi_pos, apply pow_pos, norm_num, apply pow_pos, norm_num }, rw ← le_div_iff, refine le_trans ((div_le_div_right _).mpr pi_le_four) _, apply pow_pos, norm_num, rw [pow_succ, pow_succ, ←mul_assoc, ←div_div_eq_div_mul], convert le_rfl, all_goals { repeat {apply pow_pos}, norm_num }}, apply lt_of_lt_of_le this (le_of_eq _), rw [add_mul], congr' 1, { rw [pow_succ _ (n+1), ←mul_assoc, div_mul_cancel, mul_comm], norm_num }, rw [pow_succ, ←pow_mul, mul_comm n 2, pow_mul, show (2 : ℝ) ^ 2 = 4, by norm_num, pow_succ, pow_succ, ←mul_assoc (2 : ℝ), show (2 : ℝ) * 2 = 4, by norm_num, ←mul_assoc, div_mul_cancel, mul_comm ((2 : ℝ) ^ n), ←div_div_eq_div_mul, div_mul_cancel], apply pow_ne_zero, norm_num, norm_num end /-- From an upper bound on `sqrt_two_add_series 0 n = 2 cos (π / 2 ^ (n+1))` of the form `sqrt_two_add_series 0 n ≤ 2 - (a / 2 ^ (n + 1)) ^ 2)`, one can deduce the lower bound `a < π` thanks to basic trigonometric inequalities as expressed in `pi_gt_sqrt_two_add_series`. -/ theorem pi_lower_bound_start (n : ℕ) {a} (h : sqrt_two_add_series ((0:ℕ) / (1:ℕ)) n ≤ 2 - (a / 2 ^ (n + 1)) ^ 2) : a < π := begin refine lt_of_le_of_lt _ (pi_gt_sqrt_two_add_series n), rw [mul_comm], refine (div_le_iff (pow_pos (by norm_num) _ : (0 : ℝ) < _)).mp (le_sqrt_of_sq_le _), rwa [le_sub, show (0:ℝ) = (0:ℕ)/(1:ℕ), by rw [nat.cast_zero, zero_div]], end lemma sqrt_two_add_series_step_up (c d : ℕ) {a b n : ℕ} {z : ℝ} (hz : sqrt_two_add_series (c/d) n ≤ z) (hb : 0 < b) (hd : 0 < d) (h : (2 * b + a) * d ^ 2 ≤ c ^ 2 * b) : sqrt_two_add_series (a/b) (n+1) ≤ z := begin refine le_trans _ hz, rw sqrt_two_add_series_succ, apply sqrt_two_add_series_monotone_left, have hb' : 0 < (b:ℝ) := nat.cast_pos.2 hb, have hd' : 0 < (d:ℝ) := nat.cast_pos.2 hd, rw [sqrt_le_left (div_nonneg c.cast_nonneg d.cast_nonneg), div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hb'), div_le_div_iff hb' (pow_pos hd' _)], exact_mod_cast h end /-- Create a proof of `a < π` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `sqrt 2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `sqrt (2 + r i) ≤ r(i+1)`, where `r 0 = 0` and `sqrt (2 - r n) ≥ a/2^(n+1)`. -/ meta def pi_lower_bound (l : list ℚ) : tactic unit := do let n := l.length, tactic.apply `(@pi_lower_bound_start %%(reflect n)), l.mmap' (λ r, do let a := r.num.to_nat, let b := r.denom, (() <$ tactic.apply `(@sqrt_two_add_series_step_up %%(reflect a) %%(reflect b))); [tactic.skip, `[norm_num1], `[norm_num1], `[norm_num1]]), `[simp only [sqrt_two_add_series, nat.cast_bit0, nat.cast_bit1, nat.cast_one, nat.cast_zero]], `[norm_num1] /-- From a lower bound on `sqrt_two_add_series 0 n = 2 cos (π / 2 ^ (n+1))` of the form `2 - ((a - 1 / 4 ^ n) / 2 ^ (n + 1)) ^ 2 ≤ sqrt_two_add_series 0 n`, one can deduce the upper bound `π < a` thanks to basic trigonometric formulas as expressed in `pi_lt_sqrt_two_add_series`. -/ theorem pi_upper_bound_start (n : ℕ) {a} (h : 2 - ((a - 1 / 4 ^ n) / 2 ^ (n + 1)) ^ 2 ≤ sqrt_two_add_series ((0:ℕ) / (1:ℕ)) n) (h₂ : 1 / 4 ^ n ≤ a) : π < a := begin refine lt_of_lt_of_le (pi_lt_sqrt_two_add_series n) _, rw [← le_sub_iff_add_le, ← le_div_iff', sqrt_le_left, sub_le], { rwa [nat.cast_zero, zero_div] at h }, { exact div_nonneg (sub_nonneg.2 h₂) (pow_nonneg (le_of_lt zero_lt_two) _) }, { exact pow_pos zero_lt_two _ } end lemma sqrt_two_add_series_step_down (a b : ℕ) {c d n : ℕ} {z : ℝ} (hz : z ≤ sqrt_two_add_series (a/b) n) (hb : 0 < b) (hd : 0 < d) (h : a ^ 2 * d ≤ (2 * d + c) * b ^ 2) : z ≤ sqrt_two_add_series (c/d) (n+1) := begin apply le_trans hz, rw sqrt_two_add_series_succ, apply sqrt_two_add_series_monotone_left, apply le_sqrt_of_sq_le, have hb' : 0 < (b:ℝ) := nat.cast_pos.2 hb, have hd' : 0 < (d:ℝ) := nat.cast_pos.2 hd, rw [div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hd'), div_le_div_iff (pow_pos hb' _) hd'], exact_mod_cast h end /-- Create a proof of `π < a` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `sqrt 2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `sqrt (2 + r i) ≥ r(i+1)`, where `r 0 = 0` and `sqrt (2 - r n) ≥ (a - 1/4^n) / 2^(n+1)`. -/ meta def pi_upper_bound (l : list ℚ) : tactic unit := do let n := l.length, (() <$ tactic.apply `(@pi_upper_bound_start %%(reflect n))); [pure (), `[norm_num1]], l.mmap' (λ r, do let a := r.num.to_nat, let b := r.denom, (() <$ tactic.apply `(@sqrt_two_add_series_step_down %%(reflect a) %%(reflect b))); [pure (), `[norm_num1], `[norm_num1], `[norm_num1]]), `[simp only [sqrt_two_add_series, nat.cast_bit0, nat.cast_bit1, nat.cast_one, nat.cast_zero]], `[norm_num] lemma pi_gt_three : 3 < π := by pi_lower_bound [23/16] lemma pi_gt_314 : 3.14 < π := by pi_lower_bound [99/70, 874/473, 1940/989, 1447/727] lemma pi_lt_315 : π < 3.15 := by pi_upper_bound [140/99, 279/151, 51/26, 412/207] lemma pi_gt_31415 : 3.1415 < π := by pi_lower_bound [ 11482/8119, 5401/2923, 2348/1197, 11367/5711, 25705/12868, 23235/11621] lemma pi_lt_31416 : π < 3.1416 := by pi_upper_bound [ 4756/3363, 101211/54775, 505534/257719, 83289/41846, 411278/205887, 438142/219137, 451504/225769, 265603/132804, 849938/424971] lemma pi_gt_3141592 : 3.141592 < π := by pi_lower_bound [ 11482/8119, 7792/4217, 54055/27557, 949247/476920, 3310126/1657059, 2635492/1318143, 1580265/790192, 1221775/610899, 3612247/1806132, 849943/424972] lemma pi_lt_3141593 : π < 3.141593 := by pi_upper_bound [ 27720/19601, 56935/30813, 49359/25163, 258754/130003, 113599/56868, 1101994/551163, 8671537/4336095, 3877807/1938940, 52483813/26242030, 56946167/28473117, 23798415/11899211] end real
f0ccf372a3348af24fb2084aa64b696735bb24de
ac89c256db07448984849346288e0eeffe8b20d0
/src/Init/Prelude.lean
6861c0cfc0b658f6a830ecb73bcf0e5449d96c31
[ "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
75,439
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 universe u v w @[inline] def id {α : Sort u} (a : α) : α := a /- `idRhs` is an auxiliary declaration used to implement "smart unfolding". It is used as a marker. -/ @[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun x => a set_option checkBinderAnnotations false in @[reducible] def inferInstance {α : Sort u} [i : α] : α := i set_option checkBinderAnnotations false in @[reducible] def inferInstanceAs (α : Sort u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in inductive PUnit : Sort u where | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α inductive True : Prop where | intro : True inductive False : Prop inductive Empty : Type set_option bootstrap.inductiveCheckResultingUniverse false in inductive PEmpty : Sort u where def Not (a : Prop) : Prop := a → False @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := False.elim (h₂ h₁) inductive Eq {α : Sort u} (a : α) : α → Prop where | refl {} : Eq a a @[simp] abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := Eq.rec (motive := fun α _ => motive α) m h @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a @[simp] theorem id_eq (a : α) : Eq (id a) a := rfl theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : Eq a b) (h₂ : Eq b c) : Eq a c := h₂ ▸ h₁ @[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := Eq.rec (motive := fun α _ => α) a h theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : Eq f₁ f₂) (h₂ : Eq a₁ a₂) : Eq (f₁ a₁) (f₂ a₂) := h₁ ▸ h₂ ▸ rfl theorem congrFun {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x} (h : Eq f g) (a : α) : Eq (f a) (g a) := h ▸ rfl /- Initialize the Quotient Module, which effectively adds the following definitions: constant Quot {α : Sort u} (r : α → α → Prop) : Sort u constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ init_quot inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop where | refl {} : HEq a a @[matchPattern] protected def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eq_of_heq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b := fun α β a b h₁ => HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b) (fun (h₂ : Eq α α) => rfl) h₁ this α α a a' h rfl structure Prod (α : Type u) (β : Type v) where fst : α snd : β attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) where fst : α snd : β /-- Similar to `Prod`, but `α` and `β` are in the same universe. -/ structure MProd (α β : Type u) where fst : α snd : β structure And (a b : Prop) : Prop where intro :: (left : a) (right : b) inductive Or (a b : Prop) : Prop where | inl (h : a) : Or a b | inr (h : b) : Or a b inductive Bool : Type where | false : Bool | true : Bool export Bool (false true) /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) where val : α property : p val /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /-- Auxiliary Declaration used to implement the named patterns `x@p` -/ @[reducible] def namedPattern {α : Sort u} (x a : α) : α := a /- Auxiliary axiom used to implement `sorry`. -/ @[extern "lean_sorry", neverExtract] axiom sorryAx (α : Sort u) (synthetic := true) : α theorem eq_false_of_ne_true : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, h => rfl theorem eq_true_of_ne_false : {b : Bool} → Not (Eq b false) → Eq b true | true, h => rfl | false, h => False.elim (h rfl) theorem ne_false_of_eq_true : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem ne_true_of_eq_false : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h class Inhabited (α : Sort u) where mk {} :: (default : α) constant arbitrary [Inhabited α] : α := Inhabited.default instance : Inhabited (Sort u) where default := PUnit instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where default := fun _ => arbitrary instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where default := fun _ => arbitrary deriving instance Inhabited for Bool /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u where up :: (down : α) /- Bijection between α and PLift α -/ theorem PLift.up_down {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b | up a => rfl theorem PLift.down_up {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /- Pointed types -/ structure PointedType where (type : Type u) (val : type) instance : Inhabited PointedType.{u} where default := { type := PUnit.{u+1}, val := ⟨⟩ } /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) where up :: (down : α) /- Bijection between α and ULift.{v} α -/ theorem ULift.up_down {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b | up a => rfl theorem ULift.down_up {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl class inductive Decidable (p : Prop) where | isFalse (h : Not p) : Decidable p | isTrue (h : p) : Decidable p @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) := s a b theorem decide_eq_true : [s : Decidable p] → p → Eq (decide p) true | isTrue _, _ => rfl | isFalse h₁, h₂ => absurd h₂ h₁ theorem decide_eq_false : [s : Decidable p] → Not p → Eq (decide p) false | isTrue h₁, h₂ => absurd h₁ h₂ | isFalse h, _ => rfl theorem of_decide_eq_true [s : Decidable p] : Eq (decide p) true → p := fun h => match (generalizing := false) s with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (ne_true_of_eq_false (decide_eq_false h₁)) theorem of_decide_eq_false [s : Decidable p] : Eq (decide p) false → Not p := fun h => match (generalizing := false) s with | isTrue h₁ => absurd h (ne_false_of_eq_true (decide_eq_true h₁)) | isFalse h₁ => h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl class BEq (α : Type u) where beq : α → α → Bool open BEq (beq) instance [DecidableEq α] : BEq α where beq a b := decide (Eq a b) -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := Decidable.casesOn (motive := fun _ => α) h e t /- if-then-else -/ @[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α := Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) := match dp with | isTrue hp => match dq with | isTrue hq => isTrue ⟨hp, hq⟩ | isFalse hq => isFalse (fun h => hq (And.right h)) | isFalse hp => isFalse (fun h => hp (And.left h)) @[macroInline] instance [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) := match dp with | isTrue hp => isTrue (Or.inl hp) | isFalse hp => match dq with | isTrue hq => isTrue (Or.inr hq) | isFalse hq => isFalse fun h => match h with | Or.inl h => hp h | Or.inr h => hq h instance [dp : Decidable p] : Decidable (Not p) := match dp with | isTrue hp => isFalse (absurd hp) | isFalse hp => isTrue hp /- Boolean operators -/ @[macroInline] def cond {α : Type u} (c : Bool) (x y : α) : α := match c with | true => x | false => y @[macroInline] def or (x y : Bool) : Bool := match x with | true => true | false => y @[macroInline] def and (x y : Bool) : Bool := match x with | false => false | true => y @[inline] def not : Bool → Bool | true => false | false => true inductive Nat where | zero : Nat | succ (n : Nat) : Nat instance : Inhabited Nat where default := Nat.zero /- For numeric literals notation -/ class OfNat (α : Type u) (n : Nat) where ofNat : α @[defaultInstance 100] /- low prio -/ instance (n : Nat) : OfNat Nat n where ofNat := n class LE (α : Type u) where le : α → α → Prop class LT (α : Type u) where lt : α → α → Prop @[reducible] def GE.ge {α : Type u} [LE α] (a b : α) : Prop := LE.le b a @[reducible] def GT.gt {α : Type u} [LT α] (a b : α) : Prop := LT.lt b a @[inline] def max [LT α] [DecidableRel (@LT.lt α _)] (a b : α) : α := ite (LT.lt b a) a b @[inline] def min [LE α] [DecidableRel (@LE.le α _)] (a b : α) : α := ite (LE.le a b) a b class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAdd : α → β → γ class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where hSub : α → β → γ class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMul : α → β → γ class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where hDiv : α → β → γ class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMod : α → β → γ class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where hPow : α → β → γ class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAppend : α → β → γ class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOrElse : α → β → γ class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAndThen : α → β → γ class HAnd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAnd : α → β → γ class HXor (α : Type u) (β : Type v) (γ : outParam (Type w)) where hXor : α → β → γ class HOr (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOr : α → β → γ class HShiftLeft (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftLeft : α → β → γ class HShiftRight (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftRight : α → β → γ class Add (α : Type u) where add : α → α → α class Sub (α : Type u) where sub : α → α → α class Mul (α : Type u) where mul : α → α → α class Neg (α : Type u) where neg : α → α class Div (α : Type u) where div : α → α → α class Mod (α : Type u) where mod : α → α → α class Pow (α : Type u) (β : Type v) where pow : α → β → α class Append (α : Type u) where append : α → α → α class OrElse (α : Type u) where orElse : α → α → α class AndThen (α : Type u) where andThen : α → α → α class AndOp (α : Type u) where and : α → α → α class Xor (α : Type u) where xor : α → α → α class OrOp (α : Type u) where or : α → α → α class Complement (α : Type u) where complement : α → α class ShiftLeft (α : Type u) where shiftLeft : α → α → α class ShiftRight (α : Type u) where shiftRight : α → α → α @[defaultInstance] instance [Add α] : HAdd α α α where hAdd a b := Add.add a b @[defaultInstance] instance [Sub α] : HSub α α α where hSub a b := Sub.sub a b @[defaultInstance] instance [Mul α] : HMul α α α where hMul a b := Mul.mul a b @[defaultInstance] instance [Div α] : HDiv α α α where hDiv a b := Div.div a b @[defaultInstance] instance [Mod α] : HMod α α α where hMod a b := Mod.mod a b @[defaultInstance] instance [Pow α β] : HPow α β α where hPow a b := Pow.pow a b @[defaultInstance] instance [Append α] : HAppend α α α where hAppend a b := Append.append a b @[defaultInstance] instance [OrElse α] : HOrElse α α α where hOrElse a b := OrElse.orElse a b @[defaultInstance] instance [AndThen α] : HAndThen α α α where hAndThen a b := AndThen.andThen a b @[defaultInstance] instance [AndOp α] : HAnd α α α where hAnd a b := AndOp.and a b @[defaultInstance] instance [Xor α] : HXor α α α where hXor a b := Xor.xor a b @[defaultInstance] instance [OrOp α] : HOr α α α where hOr a b := OrOp.or a b @[defaultInstance] instance [ShiftLeft α] : HShiftLeft α α α where hShiftLeft a b := ShiftLeft.shiftLeft a b @[defaultInstance] instance [ShiftRight α] : HShiftRight α α α where hShiftRight a b := ShiftRight.shiftRight a b open HAdd (hAdd) open HMul (hMul) open HPow (hPow) open HAppend (hAppend) set_option bootstrap.genMatcherCode false in @[extern "lean_nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a, Nat.zero => a | a, Nat.succ b => Nat.succ (Nat.add a b) instance : Add Nat where add := Nat.add /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg set_option bootstrap.genMatcherCode false in @[extern "lean_nat_mul"] protected def Nat.mul : (@& Nat) → (@& Nat) → Nat | a, 0 => 0 | a, Nat.succ b => Nat.add (Nat.mul a b) a instance : Mul Nat where mul := Nat.mul set_option bootstrap.genMatcherCode false in @[extern "lean_nat_pow"] protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat | 0 => 1 | succ n => Nat.mul (Nat.pow m n) m instance : Pow Nat Nat where pow := Nat.pow set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_eq"] def Nat.beq : (@& Nat) → (@& Nat) → Bool | zero, zero => true | zero, succ m => false | succ n, zero => false | succ n, succ m => beq n m theorem Nat.eq_of_beq_eq_true : {n m : Nat} → Eq (beq n m) true → Eq n m | zero, zero, h => rfl | zero, succ m, h => Bool.noConfusion h | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have : Eq (beq n m) true := h have : Eq n m := eq_of_beq_eq_true this this ▸ rfl theorem Nat.ne_of_beq_eq_false : {n m : Nat} → Eq (beq n m) false → Not (Eq n m) | zero, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Nat.noConfusion h₂ | succ n, zero, h₁, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have : Eq (beq n m) false := h₁ Nat.noConfusion h₂ (fun h₂ => absurd h₂ (ne_of_beq_eq_false this)) @[extern "lean_nat_dec_eq"] protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) := match h:beq n m with | true => isTrue (eq_of_beq_eq_true h) | false => isFalse (ne_of_beq_eq_false h) @[inline] instance : DecidableEq Nat := Nat.decEq set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_le"] def Nat.ble : @& Nat → @& Nat → Bool | zero, zero => true | zero, succ m => true | succ n, zero => false | succ n, succ m => ble n m protected def Nat.le (n m : Nat) : Prop := Eq (ble n m) true instance : LE Nat where le := Nat.le protected def Nat.lt (n m : Nat) : Prop := Nat.le (succ n) m instance : LT Nat where lt := Nat.lt theorem Nat.not_succ_le_zero : ∀ (n : Nat), LE.le (succ n) 0 → False | 0, h => nomatch h | succ n, h => nomatch h theorem Nat.not_lt_zero (n : Nat) : Not (LT.lt n 0) := not_succ_le_zero n @[extern "lean_nat_dec_le"] instance Nat.decLe (n m : @& Nat) : Decidable (LE.le n m) := decEq (Nat.ble n m) true @[extern "lean_nat_dec_lt"] instance Nat.decLt (n m : @& Nat) : Decidable (LT.lt n m) := decLe (succ n) m theorem Nat.zero_le : (n : Nat) → LE.le 0 n | zero => rfl | succ n => rfl theorem Nat.succ_le_succ {n m : Nat} (h : LE.le n m) : LE.le (succ n) (succ m) := h theorem Nat.zero_lt_succ (n : Nat) : LT.lt 0 (succ n) := succ_le_succ (zero_le n) theorem Nat.le_step : {n m : Nat} → LE.le n m → LE.le n (succ m) | zero, zero, h => rfl | zero, succ n, h => rfl | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have : LE.le n m := h have : LE.le n (succ m) := le_step this succ_le_succ this protected theorem Nat.le_trans : {n m k : Nat} → LE.le n m → LE.le m k → LE.le n k | zero, m, k, h₁, h₂ => zero_le _ | succ n, zero, k, h₁, h₂ => Bool.noConfusion h₁ | succ n, succ m, zero, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, succ k, h₁, h₂ => have h₁' : LE.le n m := h₁ have h₂' : LE.le m k := h₂ show LE.le n k from Nat.le_trans h₁' h₂' protected theorem Nat.lt_trans {n m k : Nat} (h₁ : LT.lt n m) : LT.lt m k → LT.lt n k := Nat.le_trans (le_step h₁) theorem Nat.le_succ : (n : Nat) → LE.le n (succ n) | zero => rfl | succ n => le_succ n theorem Nat.le_succ_of_le {n m : Nat} (h : LE.le n m) : LE.le n (succ m) := Nat.le_trans h (le_succ m) protected theorem Nat.eq_or_lt_of_le : {n m: Nat} → LE.le n m → Or (Eq n m) (LT.lt n m) | zero, zero, h => Or.inl rfl | zero, succ n, h => Or.inr (zero_le n) | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have : LE.le n m := h match Nat.eq_or_lt_of_le this with | Or.inl h => Or.inl (h ▸ rfl) | Or.inr h => Or.inr (succ_le_succ h) protected def Nat.le_refl : (n : Nat) → LE.le n n | zero => rfl | succ n => Nat.le_refl n protected theorem Nat.lt_or_ge (n m : Nat) : Or (LT.lt n m) (GE.ge n m) := match m with | zero => Or.inr (zero_le n) | succ m => match Nat.lt_or_ge n m with | Or.inl h => Or.inl (le_succ_of_le h) | Or.inr h => match Nat.eq_or_lt_of_le h with | Or.inl h1 => Or.inl (h1 ▸ Nat.le_refl _) | Or.inr h1 => Or.inr h1 protected theorem Nat.le_antisymm : {n m : Nat} → LE.le n m → LE.le m n → Eq n m | zero, zero, h₁, h₂ => rfl | succ n, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, h₁, h₂ => have h₁' : LE.le n m := h₁ have h₂' : LE.le m n := h₂ (Nat.le_antisymm h₁' h₂') ▸ rfl protected theorem Nat.lt_of_le_of_ne {n m : Nat} (h₁ : LE.le n m) (h₂ : Not (Eq n m)) : LT.lt n m := match Nat.lt_or_ge n m with | Or.inl h₃ => h₃ | Or.inr h₃ => absurd (Nat.le_antisymm h₁ h₃) h₂ set_option bootstrap.genMatcherCode false in @[extern c inline "lean_nat_sub(#1, lean_box(1))"] def Nat.pred : (@& Nat) → Nat | 0 => 0 | succ a => a set_option bootstrap.genMatcherCode false in @[extern "lean_nat_sub"] protected def Nat.sub : (@& Nat) → (@& Nat) → Nat | a, 0 => a | a, succ b => pred (Nat.sub a b) instance : Sub Nat where sub := Nat.sub theorem Nat.pred_le_pred : {n m : Nat} → LE.le n m → LE.le (pred n) (pred m) | zero, zero, h => rfl | zero, succ n, h => zero_le n | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => h theorem Nat.le_of_succ_le_succ {n m : Nat} : LE.le (succ n) (succ m) → LE.le n m := pred_le_pred theorem Nat.le_of_lt_succ {m n : Nat} : LT.lt m (succ n) → LE.le m n := le_of_succ_le_succ @[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) := fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant def System.Platform.numBits : Nat := (getNumBits ()).val theorem System.Platform.numBits_eq : Or (Eq numBits 32) (Eq numBits 64) := (getNumBits ()).property structure Fin (n : Nat) where val : Nat isLt : LT.lt val n theorem Fin.eq_of_val_eq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Fin.val_eq_of_eq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val := h ▸ rfl theorem Fin.ne_of_val_ne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (val_eq_of_eq h') h instance (n : Nat) : DecidableEq (Fin n) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (Fin.eq_of_val_eq h) | isFalse h => isFalse (Fin.ne_of_val_ne h) instance {n} : LT (Fin n) where lt a b := LT.lt a.val b.val instance {n} : LE (Fin n) where le a b := LE.le a.val b.val instance Fin.decLt {n} (a b : Fin n) : Decidable (LT.lt a b) := Nat.decLt .. instance Fin.decLe {n} (a b : Fin n) : Decidable (LE.le a b) := Nat.decLe .. def UInt8.size : Nat := 256 structure UInt8 where val : Fin UInt8.size attribute [extern "lean_uint8_of_nat_mk"] UInt8.mk attribute [extern "lean_uint8_to_nat"] UInt8.val @[extern "lean_uint8_of_nat"] def UInt8.ofNatCore (n : @& Nat) (h : LT.lt n UInt8.size) : UInt8 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt8 := UInt8.decEq instance : Inhabited UInt8 where default := UInt8.ofNatCore 0 (by decide) def UInt16.size : Nat := 65536 structure UInt16 where val : Fin UInt16.size attribute [extern "lean_uint16_of_nat_mk"] UInt16.mk attribute [extern "lean_uint16_to_nat"] UInt16.val @[extern "lean_uint16_of_nat"] def UInt16.ofNatCore (n : @& Nat) (h : LT.lt n UInt16.size) : UInt16 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt16 := UInt16.decEq instance : Inhabited UInt16 where default := UInt16.ofNatCore 0 (by decide) def UInt32.size : Nat := 4294967296 structure UInt32 where val : Fin UInt32.size attribute [extern "lean_uint32_of_nat_mk"] UInt32.mk attribute [extern "lean_uint32_to_nat"] UInt32.val @[extern "lean_uint32_of_nat"] def UInt32.ofNatCore (n : @& Nat) (h : LT.lt n UInt32.size) : UInt32 := { val := { val := n, isLt := h } } @[extern "lean_uint32_to_nat"] def UInt32.toNat (n : UInt32) : Nat := n.val.val set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt32 := UInt32.decEq instance : Inhabited UInt32 where default := UInt32.ofNatCore 0 (by decide) instance : LT UInt32 where lt a b := LT.lt a.val b.val instance : LE UInt32 where le a b := LE.le a.val b.val set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def UInt32.decLt (a b : UInt32) : Decidable (LT.lt a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LT.lt n m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def UInt32.decLe (a b : UInt32) : Decidable (LE.le a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LE.le n m)) instance (a b : UInt32) : Decidable (LT.lt a b) := UInt32.decLt a b instance (a b : UInt32) : Decidable (LE.le a b) := UInt32.decLe a b def UInt64.size : Nat := 18446744073709551616 structure UInt64 where val : Fin UInt64.size attribute [extern "lean_uint64_of_nat_mk"] UInt64.mk attribute [extern "lean_uint64_to_nat"] UInt64.val @[extern "lean_uint64_of_nat"] def UInt64.ofNatCore (n : @& Nat) (h : LT.lt n UInt64.size) : UInt64 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt64 := UInt64.decEq instance : Inhabited UInt64 where default := UInt64.ofNatCore 0 (by decide) def USize.size : Nat := hPow 2 System.Platform.numBits theorem usize_size_eq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) := show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from match System.Platform.numBits, System.Platform.numBits_eq with | _, Or.inl rfl => Or.inl (by decide) | _, Or.inr rfl => Or.inr (by decide) structure USize where val : Fin USize.size attribute [extern "lean_usize_of_nat_mk"] USize.mk attribute [extern "lean_usize_to_nat"] USize.val @[extern "lean_usize_of_nat"] def USize.ofNatCore (n : @& Nat) (h : LT.lt n USize.size) : USize := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def USize.decEq (a b : USize) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq USize := USize.decEq instance : Inhabited USize where default := USize.ofNatCore 0 (match USize.size, usize_size_eq with | _, Or.inl rfl => by decide | _, Or.inr rfl => by decide) @[extern "lean_usize_of_nat"] def USize.ofNat32 (n : @& Nat) (h : LT.lt n 4294967296) : USize := { val := { val := n isLt := match USize.size, usize_size_eq with | _, Or.inl rfl => h | _, Or.inr rfl => Nat.lt_trans h (by decide) } } abbrev Nat.isValidChar (n : Nat) : Prop := Or (LT.lt n 0xd800) (And (LT.lt 0xdfff n) (LT.lt n 0x110000)) abbrev UInt32.isValidChar (n : UInt32) : Prop := n.toNat.isValidChar /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char where val : UInt32 valid : val.isValidChar private theorem isValidChar_UInt32 {n : Nat} (h : n.isValidChar) : LT.lt n UInt32.size := match h with | Or.inl h => Nat.lt_trans h (by decide) | Or.inr ⟨_, h⟩ => Nat.lt_trans h (by decide) @[extern "lean_uint32_of_nat"] private def Char.ofNatAux (n : @& Nat) (h : n.isValidChar) : Char := { val := ⟨{ val := n, isLt := isValidChar_UInt32 h }⟩, valid := h } @[noinline, matchPattern] def Char.ofNat (n : Nat) : Char := dite (n.isValidChar) (fun h => Char.ofNatAux n h) (fun _ => { val := ⟨{ val := 0, isLt := by decide }⟩, valid := Or.inl (by decide) }) theorem Char.eq_of_val_eq : ∀ {c d : Char}, Eq c.val d.val → Eq c d | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Char.val_eq_of_eq : ∀ {c d : Char}, Eq c d → Eq c.val d.val | _, _, rfl => rfl theorem Char.ne_of_val_ne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) := fun h' => absurd (val_eq_of_eq h') h theorem Char.val_ne_of_ne {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) := fun h' => absurd (eq_of_val_eq h') h instance : DecidableEq Char := fun c d => match decEq c.val d.val with | isTrue h => isTrue (Char.eq_of_val_eq h) | isFalse h => isFalse (Char.ne_of_val_ne h) def Char.utf8Size (c : Char) : UInt32 := let v := c.val ite (LE.le v (UInt32.ofNatCore 0x7F (by decide))) (UInt32.ofNatCore 1 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0x7FF (by decide))) (UInt32.ofNatCore 2 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0xFFFF (by decide))) (UInt32.ofNatCore 3 (by decide)) (UInt32.ofNatCore 4 (by decide)))) inductive Option (α : Type u) where | none : Option α | some (val : α) : Option α attribute [unbox] Option export Option (none some) instance {α} : Inhabited (Option α) where default := none @[macroInline] def Option.getD : Option α → α → α | some x, _ => x | none, e => e inductive List (α : Type u) where | nil : List α | cons (head : α) (tail : List α) : List α instance {α} : Inhabited (List α) where default := List.nil protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b) | nil, nil => isTrue rfl | cons a as, nil => isFalse (fun h => List.noConfusion h) | nil, cons b bs => isFalse (fun h => List.noConfusion h) | cons a as, cons b bs => match decEq a b with | isTrue hab => match List.hasDecEq as bs with | isTrue habs => isTrue (hab ▸ habs ▸ rfl) | isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs)) | isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab)) instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq @[specialize] def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α | a, nil => a | a, cons b l => foldl f (f a b) l def List.set : List α → Nat → α → List α | cons a as, 0, b => cons b as | cons a as, Nat.succ n, b => cons a (set as n b) | nil, _, _ => nil def List.lengthAux {α : Type u} : List α → Nat → Nat | nil, n => n | cons a as, n => lengthAux as (Nat.succ n) def List.length {α : Type u} (as : List α) : Nat := lengthAux as 0 @[simp] theorem List.length_cons {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ := let rec aux (a : α) (as : List α) : (n : Nat) → Eq ((cons a as).lengthAux n) (as.lengthAux n).succ := match as with | nil => fun _ => rfl | cons a as => fun n => aux a as n.succ aux a as 0 def List.concat {α : Type u} : List α → α → List α | nil, b => cons b nil | cons a as, b => cons a (concat as b) def List.get {α : Type u} : (as : List α) → (i : Nat) → LT.lt i as.length → α | nil, i, h => absurd h (Nat.not_lt_zero _) | cons a as, 0, h => a | cons a as, Nat.succ i, h => have : LT.lt i.succ as.length.succ := length_cons .. ▸ h get as i (Nat.le_of_succ_le_succ this) structure String where data : List Char attribute [extern "lean_string_mk"] String.mk attribute [extern "lean_string_data"] String.data @[extern "lean_string_dec_eq"] def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) := match s₁, s₂ with | ⟨s₁⟩, ⟨s₂⟩ => dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq String := String.decEq /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ abbrev String.Pos := Nat structure Substring where str : String startPos : String.Pos stopPos : String.Pos @[inline] def Substring.bsize : Substring → Nat | ⟨_, b, e⟩ => e.sub b def String.csize (c : Char) : Nat := c.utf8Size.toNat private def String.utf8ByteSizeAux : List Char → Nat → Nat | List.nil, r => r | List.cons c cs, r => utf8ByteSizeAux cs (hAdd r (csize c)) @[extern "lean_string_utf8_byte_size"] def String.utf8ByteSize : (@& String) → Nat | ⟨s⟩ => utf8ByteSizeAux s 0 @[inline] def String.bsize (s : String) : Nat := utf8ByteSize s @[inline] def String.toSubstring (s : String) : Substring := { str := s startPos := 0 stopPos := s.bsize } @[extern c inline "#3"] unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β := cast lcProof (PUnit.{v}) @[neverExtract, extern "lean_panic_fn"] constant panic {α : Type u} [Inhabited α] (msg : String) : α /- The Compiler has special support for arrays. They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array -/ structure Array (α : Type u) where data : List α attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_mk"] Array.mk /- The parameter `c` is the initial capacity -/ @[extern "lean_mk_empty_array_with_capacity"] def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := { data := List.nil } def Array.empty {α : Type u} : Array α := mkEmpty 0 @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.data.length @[extern "lean_array_fget"] def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α := a.data.get i.val i.isLt @[inline] def Array.getD (a : Array α) (i : Nat) (v₀ : α) : α := dite (LT.lt i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀) /- "Comfortable" version of `fget`. It performs a bound check at runtime. -/ @[extern "lean_array_get"] def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α := Array.getD a i arbitrary def Array.getOp {α : Type u} [Inhabited α] (self : Array α) (idx : Nat) : α := self.get! idx @[extern "lean_array_push"] def Array.push {α : Type u} (a : Array α) (v : α) : Array α := { data := List.concat a.data v } @[extern "lean_array_fset"] def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α := { data := a.data.set i.val v } @[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α := dite (LT.lt i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a) @[extern "lean_array_set"] def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α := Array.setD a i v -- Slower `Array.append` used in quotations. protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α := let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α := dite (LT.lt j bs.size) (fun hlt => match i with | 0 => as | Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩))) (fun _ => as) loop bs.size 0 as @[inlineIfReduce] def List.toArrayAux : List α → Array α → Array α | nil, r => r | cons a as, r => toArrayAux as (r.push a) @[inlineIfReduce] def List.redLength : List α → Nat | nil => 0 | cons _ as => as.redLength.succ @[inline, matchPattern, export lean_list_to_array] def List.toArray (as : List α) : Array α := as.toArrayAux (Array.mkEmpty as.redLength) class Bind (m : Type u → Type v) where bind : {α β : Type u} → m α → (α → m β) → m β export Bind (bind) class Pure (f : Type u → Type v) where pure {α : Type u} : α → f α export Pure (pure) class Functor (f : Type u → Type v) : Type (max (u+1) v) where map : {α β : Type u} → (α → β) → f α → f β mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _) class Seq (f : Type u → Type v) : Type (max (u+1) v) where seq : {α β : Type u} → f (α → β) → f α → f β class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where seqLeft : {α β : Type u} → f α → f β → f α class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where seqRight : {α β : Type u} → f α → f β → f β class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where map := fun x y => Seq.seq (pure x) y seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where map f x := bind x (Function.comp pure f) seq f x := bind f fun y => Functor.map y x seqLeft x y := bind x fun a => bind y (fun _ => pure a) seqRight x y := bind x fun _ => y instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where default := pure instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where default := pure arbitrary -- A fusion of Haskell's `sequence` and `map` def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) := let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) := dite (LT.lt j as.size) (fun hlt => match i with | 0 => pure bs | Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b)) (fun _ => bs) loop as.size 0 Array.empty /-- A Function for lifting a computation from an inner Monad to an outer Monad. Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html), but `n` does not have to be a monad transformer. Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/ class MonadLift (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α /-- The reflexive-transitive closure of `MonadLift`. `monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`. Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/ class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α export MonadLiftT (monadLift) abbrev liftM := @monadLift instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where monadLift x := MonadLift.monadLift (m := n) (monadLift x) instance (m) : MonadLiftT m m where monadLift x := x /-- A functor in the category of monads. Can be used to lift monad-transforming functions. Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html), but not restricted to monad transformers. Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/ class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift Monad morphisms -/ class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α export MonadFunctorT (monadMap) instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f) instance monadFunctorRefl (m) : MonadFunctorT m m where monadMap f := f inductive Except (ε : Type u) (α : Type v) where | error : ε → Except ε α | ok : α → Except ε α attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where default := Except.error arbitrary /-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/ class MonadExceptOf (ε : Type u) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α := MonadExceptOf.throw e abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α := MonadExceptOf.tryCatch x handle /-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α export MonadExcept (throw tryCatch) instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where throw := throwThe ε tryCatch := tryCatchThe ε namespace MonadExcept variable {ε : Type u} {m : Type v → Type w} @[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α := tryCatch t₁ fun _ => t₂ instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where orElse := MonadExcept.orelse end MonadExcept /-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where default := fun _ => arbitrary @[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r namespace ReaderT section variable {ρ : Type u} {m : Type u → Type v} {α : Type u} instance : MonadLift m (ReaderT ρ m) where monadLift x := fun _ => x instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where throw e := liftM (m := m) (throw e) tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r) end section variable {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def read : ReaderT ρ m ρ := pure @[inline] protected def pure (a : α) : ReaderT ρ m α := fun r => pure a @[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => bind (x r) fun a => f a r @[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β := fun r => Functor.map f (x r) instance : Monad (ReaderT ρ m) where pure := ReaderT.pure bind := ReaderT.bind map := ReaderT.map instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) where monadMap f x := fun ctx => f (x ctx) @[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) end end ReaderT /-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader). It does not contain `local` because this Function cannot be lifted using `monadLift`. Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) where lift {α : Type u} : ({m : Type u → Type u} → [Monad m] → ReaderT ρ m α) → n α ``` -/ class MonadReaderOf (ρ : Type u) (m : Type u → Type v) where read : m ρ @[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where read : m ρ export MonadReader (read) instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where read := readThe ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadReaderOf ρ m] : MonadReaderOf ρ n where read := liftM (m := m) read instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where read := ReaderT.read class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α @[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α := MonadWithReaderOf.withReader f x class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α export MonadWithReader (withReader) instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where withReader := withTheReader ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadFunctor m n] [MonadWithReaderOf ρ m] : MonadWithReaderOf ρ n where withReader f := monadMap (m := m) (withTheReader ρ f) instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where withReader f x := fun ctx => x (f ctx) /-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html). In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monadLift`. -/ class MonadStateOf (σ : Type u) (m : Type u → Type v) where /- Obtain the top-most State of a Monad stack. -/ get : m σ /- Set the top-most State of a Monad stack. -/ set : σ → m PUnit /- Map the top-most State of a Monad stack. Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a` because the latter does not use the State linearly (without sufficient inlining). -/ modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadStateOf (set) abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ := MonadStateOf.get @[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit := MonadStateOf.modifyGet fun s => (PUnit.unit, f s) @[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α := MonadStateOf.modifyGet f /-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/ class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where get : m σ set : σ → m PUnit modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadState (get modifyGet) instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where set := MonadStateOf.set get := getThe σ modifyGet f := MonadStateOf.modifyGet f @[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit := modifyGet fun s => (PUnit.unit, f s) @[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ := modifyGet fun s => (s, f s) -- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer -- will be picked first instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadStateOf σ m] : MonadStateOf σ n where get := liftM (m := m) MonadStateOf.get set s := liftM (m := m) (MonadStateOf.set s) modifyGet f := monadLift (m := m) (MonadState.modifyGet f) namespace EStateM inductive Result (ε σ α : Type u) where | ok : α → σ → Result ε σ α | error : ε → σ → Result ε σ α variable {ε σ α : Type u} instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where default := Result.error arbitrary arbitrary end EStateM open EStateM (Result) in def EStateM (ε σ α : Type u) := σ → Result ε σ α namespace EStateM variable {ε σ α β : Type u} instance [Inhabited ε] : Inhabited (EStateM ε σ α) where default := 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 : σ → Prod α σ) : 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) where save : σ → δ restore : σ → δ → σ @[inline] protected def tryCatch {δ} [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 @[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 @[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 ε σ α) (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 ε σ) where bind := EStateM.bind pure := EStateM.pure map := EStateM.map seqRight := EStateM.seqRight instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where orElse := EStateM.orElse instance : MonadStateOf σ (EStateM ε σ) where set := EStateM.set get := EStateM.get modifyGet := EStateM.modifyGet instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where throw := EStateM.throw tryCatch := EStateM.tryCatch @[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 σ where save := dummySave restore := dummyRestore end EStateM class Hashable (α : Sort u) where hash : α → UInt64 export Hashable (hash) @[extern c inline "(size_t)#1"] constant UInt64.toUSize (u : UInt64) : USize @[extern c inline "(uint64_t)#1"] constant USize.toUInt64 (u : USize) : UInt64 @[extern "lean_uint64_mix_hash"] constant mixHash (u₁ u₂ : UInt64) : UInt64 @[extern "lean_string_hash"] protected constant String.hash (s : @& String) : UInt64 instance : Hashable String where hash := String.hash namespace Lean /- Hierarchical names -/ inductive Name where | anonymous : Name | str : Name → String → UInt64 → Name | num : Name → Nat → UInt64 → Name instance : Inhabited Name where default := Name.anonymous protected def Name.hash : Name → UInt64 | Name.anonymous => UInt64.ofNatCore 1723 (by decide) | Name.str p s h => h | Name.num p v h => h instance : Hashable Name where hash := Name.hash namespace Name @[export lean_name_mk_string] def mkStr (p : Name) (s : String) : Name := Name.str p s (mixHash (hash p) (hash s)) @[export lean_name_mk_numeral] def mkNum (p : Name) (v : Nat) : Name := Name.num p v (mixHash (hash p) (dite (LT.lt v UInt64.size) (fun h => UInt64.ofNatCore v h) (fun _ => UInt64.ofNatCore 17 (by decide)))) def mkSimple (s : String) : Name := mkStr Name.anonymous s @[extern "lean_name_eq"] protected def beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁ _, str p₂ s₂ _ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂) | num p₁ n₁ _, num p₂ n₂ _ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂) | _, _ => false instance : BEq Name where beq := Name.beq protected def append : Name → Name → Name | n, anonymous => n | n, str p s _ => Name.mkStr (Name.append n p) s | n, num p d _ => Name.mkNum (Name.append n p) d instance : Append Name where append := Name.append end Name /- Syntax -/ /-- Source information of tokens. -/ inductive SourceInfo where /- Token from original input with whitespace and position information. `leading` will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ | original (leading : Substring) (pos : String.Pos) (trailing : Substring) (endPos : String.Pos) /- Synthesized token (e.g. from a quotation) annotated with a span from the original source. In the delaborator, we "misuse" this constructor to store synthetic positions identifying subterms. -/ | synthetic (pos : String.Pos) (endPos : String.Pos) /- Synthesized token without position information. -/ | protected none instance : Inhabited SourceInfo := ⟨SourceInfo.none⟩ namespace SourceInfo def getPos? (info : SourceInfo) (originalOnly := false) : Option String.Pos := match info, originalOnly with | original (pos := pos) .., _ => some pos | synthetic (pos := pos) .., false => some pos | _, _ => none end SourceInfo abbrev SyntaxNodeKind := Name /- Syntax AST -/ inductive Syntax where | missing : Syntax | node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | atom (info : SourceInfo) (val : String) : Syntax | ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax instance : Inhabited Syntax where default := Syntax.missing /- Builtin kinds -/ def choiceKind : SyntaxNodeKind := `choice def nullKind : SyntaxNodeKind := `null def groupKind : SyntaxNodeKind := `group def identKind : SyntaxNodeKind := `ident def strLitKind : SyntaxNodeKind := `strLit def charLitKind : SyntaxNodeKind := `charLit def numLitKind : SyntaxNodeKind := `numLit def scientificLitKind : SyntaxNodeKind := `scientificLit def nameLitKind : SyntaxNodeKind := `nameLit def fieldIdxKind : SyntaxNodeKind := `fieldIdx def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind namespace Syntax def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node k args => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => Name.mkSimple v | Syntax.ident .. => identKind def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node _ args => Syntax.node k args | _ => stx def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ args => args.getD i Syntax.missing | _ => Syntax.missing -- Add `stx[i]` as sugar for `stx.getArg i` @[inline] def getOp (self : Syntax) (idx : Nat) : Syntax := self.getArg idx def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ args => args | _ => Array.empty def getNumArgs (stx : Syntax) : Nat := match stx with | Syntax.node _ args => args.size | _ => 0 def isMissing : Syntax → Bool | Syntax.missing => true | _ => false def isNodeOf (stx : Syntax) (k : SyntaxNodeKind) (n : Nat) : Bool := and (stx.isOfKind k) (beq stx.getNumArgs n) def isIdent : Syntax → Bool | ident _ _ _ _ => true | _ => false def getId : Syntax → Name | ident _ _ val _ => val | _ => Name.anonymous def matchesNull (stx : Syntax) (n : Nat) : Bool := isNodeOf stx nullKind n def matchesIdent (stx : Syntax) (id : Name) : Bool := and stx.isIdent (beq stx.getId id) def setArgs (stx : Syntax) (args : Array Syntax) : Syntax := match stx with | node k _ => node k args | stx => stx def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax := match stx with | node k args => node k (args.setD i arg) | stx => stx /-- Retrieve the left-most leaf's info in the Syntax tree. -/ partial def getHeadInfo? : Syntax → Option SourceInfo | atom info _ => some info | ident info .. => some info | node _ args => let rec loop (i : Nat) : Option SourceInfo := match decide (LT.lt i args.size) with | true => match getHeadInfo? (args.get! i) with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _ => none /-- Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token. -/ partial def getHeadInfo (stx : Syntax) : SourceInfo := match stx.getHeadInfo? with | some info => info | none => SourceInfo.none def getPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := stx.getHeadInfo.getPos? originalOnly partial def getTailPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := match stx, originalOnly with | atom (SourceInfo.original (endPos := pos) ..) .., _ => some pos | atom (SourceInfo.synthetic (endPos := pos) ..) _, false => some pos | ident (SourceInfo.original (endPos := pos) ..) .., _ => some pos | ident (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node _ args, _ => let rec loop (i : Nat) : Option String.Pos := match decide (LT.lt i args.size) with | true => match getTailPos? (args.get! ((args.size.sub i).sub 1)) originalOnly with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _, _ => none /-- An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically remove/insert the separators. -/ structure SepArray (sep : String) where elemsAndSeps : Array Syntax end Syntax def SourceInfo.fromRef (ref : Syntax) : SourceInfo := match ref.getPos?, ref.getTailPos? with | some pos, some tailPos => SourceInfo.synthetic pos tailPos | _, _ => SourceInfo.none def mkAtom (val : String) : Syntax := Syntax.atom SourceInfo.none val def mkAtomFrom (src : Syntax) (val : String) : Syntax := Syntax.atom (SourceInfo.fromRef src) val /- Parser descriptions -/ inductive ParserDescr where | const (name : Name) | unary (name : Name) (p : ParserDescr) | binary (name : Name) (p₁ p₂ : ParserDescr) | node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) | trailingNode (kind : SyntaxNodeKind) (prec lhsPrec : Nat) (p : ParserDescr) | symbol (val : String) | nonReservedSymbol (val : String) (includeIdent : Bool) | cat (catName : Name) (rbp : Nat) | parser (declName : Name) | nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr) | sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) | sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) instance : Inhabited ParserDescr where default := ParserDescr.symbol "" abbrev TrailingParserDescr := ParserDescr /- Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := hAdd reservedMacroScope 1 class MonadRef (m : Type → Type) where getRef : m Syntax withRef {α} : Syntax → m α → m α export MonadRef (getRef) instance (m n : Type → Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where getRef := liftM (getRef : m _) withRef ref x := monadMap (m := m) (MonadRef.withRef ref) x def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax := match ref.getPos? with | some _ => ref | _ => oldRef @[inline] def withRef {m : Type → Type} [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α := bind getRef fun oldRef => let ref := replaceRef ref oldRef MonadRef.withRef ref x /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). We also apply the position of the result of `getRef` to each introduced symbol, which results in better error positions than not applying any position. -/ class MonadQuotation (m : Type → Type) extends MonadRef m where -- Get the fresh scope of the current macro invocation getCurrMacroScope : m MacroScope getMainModule : m Name /- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ withFreshMacroScope {α : Type} : m α → m α export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope) def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := do SourceInfo.fromRef (← getRef) instance {m n : Type → Type} [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where getCurrMacroScope := liftM (m := m) getCurrMacroScope getMainModule := liftM (m := m) getMainModule withFreshMacroScope := monadMap (m := m) withFreshMacroScope /- We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ def Name.hasMacroScopes : Name → Bool | str _ s _ => beq s "_hyg" | num p _ _ => hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | Name.str p s _ => match beq s "_@" with | true => p | false => eraseMacroScopesAux p | Name.num p _ _ => eraseMacroScopesAux p | Name.anonymous => Name.anonymous @[export lean_erase_macro_scopes] def Name.eraseMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => eraseMacroScopesAux n | false => n private def simpMacroScopesAux : Name → Name | Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i | n => eraseMacroScopesAux n /- Helper function we use to create binder names that do not need to be unique. -/ @[export lean_simp_macro_scopes] def Name.simpMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => simpMacroScopesAux n | false => n structure MacroScopesView where name : Name imported : Name mainModule : Name scopes : List MacroScope instance : Inhabited MacroScopesView where default := ⟨arbitrary, arbitrary, arbitrary, arbitrary⟩ def MacroScopesView.review (view : MacroScopesView) : Name := match view.scopes with | List.nil => view.name | List.cons _ _ => let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg") view.scopes.foldl Name.mkNum base private def assembleParts : List Name → Name → Name | List.nil, acc => acc | List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s) | List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n) | _, acc => panic "Error: unreachable @ assembleParts" private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } | false => extractImported scps mainModule p (List.cons n parts) | n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts) | _, _ => panic "Error: unreachable @ extractImported" private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } | false => extractMainModule scps p (List.cons n parts) | n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil | _, _ => panic "Error: unreachable @ extractMainModule" private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc) | Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg" | _, _ => panic "Error: unreachable @ extractMacroScopesAux" /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := match n.hasMacroScopes with | true => extractMacroScopesAux n List.nil | false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous } def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := match n.hasMacroScopes with | true => let view := extractMacroScopes n match beq view.mainModule mainModule with | true => Name.mkNum n scp | false => { view with imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule) mainModule := mainModule scopes := List.cons scp List.nil }.review | false => Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := bind getMainModule fun mainModule => bind getCurrMacroScope fun scp => pure (Lean.addMacroScope mainModule n scp) def defaultMaxRecDepth := 512 def maxRecDepthErrorMessage : String := "maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)" namespace Macro /- References -/ private constant MethodsRefPointed : PointedType.{0} private def MethodsRef : Type := MethodsRefPointed.type structure Context where methods : MethodsRef mainModule : Name currMacroScope : MacroScope currRecDepth : Nat := 0 maxRecDepth : Nat := defaultMaxRecDepth ref : Syntax inductive Exception where | error : Syntax → String → Exception | unsupportedSyntax : Exception structure State where macroScope : MacroScope traceMsgs : List (Prod Name String) := List.nil deriving Inhabited end Macro abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception Macro.State) abbrev Macro := Syntax → MacroM Syntax namespace Macro instance : MonadRef MacroM where getRef := bind read fun ctx => pure ctx.ref withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x def addMacroScope (n : Name) : MacroM Name := bind read fun ctx => pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope) def throwUnsupported {α} : MacroM α := throw Exception.unsupportedSyntax def throwError {α} (msg : String) : MacroM α := bind getRef fun ref => throw (Exception.error ref msg) def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α := withRef ref (throwError msg) @[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α := bind (modifyGet (fun s => (s.macroScope, { s with macroScope := hAdd s.macroScope 1 }))) fun fresh => withReader (fun ctx => { ctx with currMacroScope := fresh }) x @[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α := bind read fun ctx => match beq ctx.currRecDepth ctx.maxRecDepth with | true => throw (Exception.error ref maxRecDepthErrorMessage) | false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x instance : MonadQuotation MacroM where getCurrMacroScope ctx := pure ctx.currMacroScope getMainModule ctx := pure ctx.mainModule withFreshMacroScope := Macro.withFreshMacroScope structure Methods where expandMacro? : Syntax → MacroM (Option Syntax) getCurrNamespace : MacroM Name hasDecl : Name → MacroM Bool resolveNamespace? : Name → MacroM (Option Name) resolveGlobalName : Name → MacroM (List (Prod Name (List String))) deriving Inhabited unsafe def mkMethodsImp (methods : Methods) : MethodsRef := unsafeCast methods @[implementedBy mkMethodsImp] constant mkMethods (methods : Methods) : MethodsRef := MethodsRefPointed.val instance : Inhabited MethodsRef where default := mkMethods arbitrary unsafe def getMethodsImp : MacroM Methods := bind read fun ctx => pure (unsafeCast (ctx.methods)) @[implementedBy getMethodsImp] constant getMethods : MacroM Methods /-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/ def expandMacro? (stx : Syntax) : MacroM (Option Syntax) := do (← getMethods).expandMacro? stx /-- Return `true` if the environment contains a declaration with name `declName` -/ def hasDecl (declName : Name) : MacroM Bool := do (← getMethods).hasDecl declName def getCurrNamespace : MacroM Name := do (← getMethods).getCurrNamespace def resolveNamespace? (n : Name) : MacroM (Option Name) := do (← getMethods).resolveNamespace? n def resolveGlobalName (n : Name) : MacroM (List (Prod Name (List String))) := do (← getMethods).resolveGlobalName n def trace (clsName : Name) (msg : String) : MacroM Unit := do modify fun s => { s with traceMsgs := List.cons (Prod.mk clsName msg) s.traceMsgs } end Macro export Macro (expandMacro?) namespace PrettyPrinter abbrev UnexpandM := EStateM Unit Unit /-- Function that tries to reverse macro expansions as a post-processing step of delaboration. While less general than an arbitrary delaborator, it can be declared without importing `Lean`. Used by the `[appUnexpander]` attribute. -/ -- a `kindUnexpander` could reasonably be added later abbrev Unexpander := Syntax → UnexpandM Syntax -- unexpanders should not need to introduce new names instance : MonadQuotation UnexpandM where getRef := pure Syntax.missing withRef := fun _ => id getCurrMacroScope := pure 0 getMainModule := pure `_fakeMod withFreshMacroScope := id end PrettyPrinter end Lean
cae54bee826ad5fac2d63a24feabe8188e188c77
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/calculus/fderiv.lean
2dcaaae1573f0b4bfcfb22ea7a17390f26d00d63
[ "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
139,309
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import analysis.asymptotics.asymptotic_equivalent import analysis.calculus.tangent_cone import analysis.normed_space.bounded_linear_maps import analysis.normed_space.units /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` Finally, `has_strict_fderiv_at f f' x` means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability, i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse function theorem, and is defined here only to avoid proving theorems like `is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for `has_strict_fderiv_at`. ## Main results In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * sum of finitely many functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) * inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are translated to this more elementary point of view on the derivative in the file `deriv.lean`. The derivative of polynomials is handled there, as it is naturally one-dimensional. The simplifier is set up to prove automatically that some functions are differentiable, or differentiable at a point (but not differentiable on a set or within a set at a point, as checking automatically that the good domains are mapped one to the other when using composition is not something the simplifier can easily do). This means that one can write `example (x : ℝ) : differentiable ℝ (λ x, sin (exp (3 + x^2)) - 5 * cos x) := by simp`. If there are divisions, one needs to supply to the simplifier proofs that the denominators do not vanish, as in ```lean example (x : ℝ) (h : 1 + sin x ≠ 0) : differentiable_at ℝ (λ x, exp x / (1 + sin x)) x := by simp [h] ``` Of course, these examples only work once `exp`, `cos` and `sin` have been shown to be differentiable, in `analysis.special_functions.trigonometric`. The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general complicated multidimensional linear maps), but it will compute one-dimensional derivatives, see `deriv.lean`. ## Implementation details The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. To make sure that the simplifier can prove automatically that functions are differentiable, we tag many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable functions is differentiable, as well as their product, their cartesian product, and so on. A notable exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are differentiable, then their composition also is: `simp` would always be able to match this lemma, by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`), we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding some boilerplate lemmas, but these can also be useful in their own right. Tests for this ability of the simplifier (with more examples) are provided in `tests/differentiable.lean`. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set metric open_locale topological_space classical nnreal filter asymptotics ennreal noncomputable theory section variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_add_comm_group G'] [normed_space 𝕜 G'] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = 𝓝[s] x` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := (λ x', f x' - f x - f' (x' - x)) =o[L] (λ x', x' - x) /-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/ def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (𝓝[s] x) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) /-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability* if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required, e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/ def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) =o[𝓝 (x, x)] (λ p : E × E, p.1 - p.2) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s) (clim : tendsto (λ n, ‖c n‖) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (𝓝[s] x), { conv in (𝓝[s] x) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : (λ y, f y - f x - f' (y - x)) =o[𝓝[s] x] (λ y, y - x) := h, have : (λ n, f (x + d n) - f x - f' ((x + d n) - x)) =o[l] (λ n, (x + d n) - x) := this.comp_tendsto tendsto_arg, have : (λ n, f (x + d n) - f x - f' (d n)) =o[l] d := by simpa only [add_sub_cancel'], have : (λ n, c n • (f (x + d n) - f x - f' (d n))) =o[l] (λ n, c n • d n) := (is_O_refl c l).smul_is_o this, have : (λ n, c n • (f (x + d n) - f x - f' (d n))) =o[l] (λ n, (1:ℝ)) := this.trans_is_O (cdlim.is_O_one ℝ), have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) := (is_o_one_iff ℝ).1 this, have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) := tendsto.comp f'.cont.continuous_at cdlim, have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) l (𝓝 (0 + f' v)) := L1.add L2, have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) = (λn, c n • (f (x + d n) - f x)), by { ext n, simp [smul_add, smul_sub] }, rwa [this, zero_add] at L3 end /-- If `f'` and `f₁'` are two derivatives of `f` within `s` at `x`, then they are equal on the tangent cone to `s` at `x` -/ theorem has_fderiv_within_at.unique_on (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : eq_on f' f₁' (tangent_cone_at 𝕜 s x) := λ y ⟨c, d, dtop, clim, cdlim⟩, tendsto_nhds_unique (hf.lim at_top dtop clim cdlim) (hg.lim at_top dtop clim cdlim) /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x) (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : f' = f₁' := continuous_linear_map.ext_on H.1 (hf.unique_on hg) theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := (H x hx).eq h h₁ end derivative_uniqueness section fderiv_properties /-! ### Basic properties of the derivative -/ theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ‖x' - x‖⁻¹ * ‖f x' - f x - f' (x' - x)‖) L (𝓝 0) := have h : ∀ x', ‖x' - x‖ = 0 → ‖f x' - f x - f' (x' - x)‖ = 0, from λ x' hx', by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto_congr (λ _, div_eq_inv_mul _ _), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ‖x' - x‖⁻¹ * ‖f x' - f x - f' (x' - x)‖) (𝓝[s] x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ‖x' - x‖⁻¹ * ‖f x' - f x - f' (x' - x)‖) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ (λ h : E, f (x + h) - f x - f' h) =o[𝓝 0] (λh, h) := begin rw [has_fderiv_at, has_fderiv_at_filter, ← map_add_left_nhds_zero x, is_o_map], simp [(∘)] end /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. This version only assumes that `‖f x - f x₀‖ ≤ C * ‖x - x₀‖` in a neighborhood of `x`. -/ lemma has_fderiv_at.le_of_lip' {f : E → F} {f' : E →L[𝕜] F} {x₀ : E} (hf : has_fderiv_at f f' x₀) {C : ℝ} (hC₀ : 0 ≤ C) (hlip : ∀ᶠ x in 𝓝 x₀, ‖f x - f x₀‖ ≤ C * ‖x - x₀‖) : ‖f'‖ ≤ C := begin refine le_of_forall_pos_le_add (λ ε ε0, op_norm_le_of_nhds_zero _ _), exact add_nonneg hC₀ ε0.le, rw [← map_add_left_nhds_zero x₀, eventually_map] at hlip, filter_upwards [is_o_iff.1 (has_fderiv_at_iff_is_o_nhds_zero.1 hf) ε0, hlip] with y hy hyC, rw add_sub_cancel' at hyC, calc ‖f' y‖ ≤ ‖f (x₀ + y) - f x₀‖ + ‖f (x₀ + y) - f x₀ - f' y‖ : norm_le_insert _ _ ... ≤ C * ‖y‖ + ε * ‖y‖ : add_le_add hyC hy ... = (C + ε) * ‖y‖ : (add_mul _ _ _).symm end /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. -/ lemma has_fderiv_at.le_of_lip {f : E → F} {f' : E →L[𝕜] F} {x₀ : E} (hf : has_fderiv_at f f' x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ‖f'‖ ≤ C := begin refine hf.le_of_lip' C.coe_nonneg _, filter_upwards [hs] with x hx using hlip.norm_sub_le hx (mem_of_mem_nhds hs), end theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := h.mono hst theorem has_fderiv_within_at.mono_of_mem (h : has_fderiv_within_at f f' t x) (hst : t ∈ 𝓝[s] x) : has_fderiv_within_at f f' s x := h.mono $ nhds_within_le_iff.mpr hst theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono $ nhds_within_mono _ hst theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } alias has_fderiv_within_at_univ ↔ has_fderiv_within_at.has_fderiv_at_of_univ _ lemma has_fderiv_within_at_insert {y : E} {g' : E →L[𝕜] F} : has_fderiv_within_at g g' (insert y s) x ↔ has_fderiv_within_at g g' s x := begin rcases eq_or_ne x y with rfl|h, { simp_rw [has_fderiv_within_at, has_fderiv_at_filter], apply asymptotics.is_o_insert, simp only [sub_self, g'.map_zero] }, refine ⟨λ h, h.mono $ subset_insert y s, λ hg, hg.mono_of_mem _⟩, simp_rw [nhds_within_insert_of_ne h, self_mem_nhds_within] end alias has_fderiv_within_at_insert ↔ has_fderiv_within_at.of_insert has_fderiv_within_at.insert' lemma has_fderiv_within_at.insert {g' : E →L[𝕜] F} (h : has_fderiv_within_at g g' s x) : has_fderiv_within_at g g' (insert x s) x := h.insert' lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) : (λ p : E × E, f p.1 - f p.2) =O[𝓝 (x, x)] (λ p : E × E, p.1 - p.2) := hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _) lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : (λ x', f x' - f x) =O[L] (λ x', x' - x) := h.is_O.congr_of_sub.2 (f'.is_O_sub _ _) protected lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) : has_fderiv_at f f' x := begin rw [has_fderiv_at, has_fderiv_at_filter, is_o_iff], exact (λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (is_o_iff.1 hf hc)) end protected lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) : differentiable_at 𝕜 f x := hf.has_fderiv_at.differentiable_at /-- If `f` is strictly differentiable at `x` with derivative `f'` and `K > ‖f'‖₊`, then `f` is `K`-Lipschitz in a neighborhood of `x`. -/ lemma has_strict_fderiv_at.exists_lipschitz_on_with_of_nnnorm_lt (hf : has_strict_fderiv_at f f' x) (K : ℝ≥0) (hK : ‖f'‖₊ < K) : ∃ s ∈ 𝓝 x, lipschitz_on_with K f s := begin have := hf.add_is_O_with (f'.is_O_with_comp _ _) hK, simp only [sub_add_cancel, is_O_with] at this, rcases exists_nhds_square this with ⟨U, Uo, xU, hU⟩, exact ⟨U, Uo.mem_nhds xU, lipschitz_on_with_iff_norm_sub_le.2 $ λ x hx y hy, hU (mk_mem_prod hx hy)⟩ end /-- If `f` is strictly differentiable at `x` with derivative `f'`, then `f` is Lipschitz in a neighborhood of `x`. See also `has_strict_fderiv_at.exists_lipschitz_on_with_of_nnnorm_lt` for a more precise statement. -/ lemma has_strict_fderiv_at.exists_lipschitz_on_with (hf : has_strict_fderiv_at f f' x) : ∃ K (s ∈ 𝓝 x), lipschitz_on_with K f s := (exists_gt _).imp hf.exists_lipschitz_on_with_of_nnnorm_lt /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ‖c n‖) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ univ_mem hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_mem_nhds hU, dsimp only, rw [← mul_smul, mul_inv_cancel hy, one_smul] end theorem has_fderiv_at.unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.sup ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.differentiable_at (h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.imp (λ f' hf', hf'.has_fderiv_at hs) lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) : has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x := begin dunfold fderiv_within, dunfold differentiable_within_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) : has_fderiv_at f (fderiv 𝕜 f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_on.has_fderiv_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) : has_fderiv_at f (fderiv 𝕜 f x) x := ((h x (mem_of_mem_nhds hs)).differentiable_at hs).has_fderiv_at lemma differentiable_on.differentiable_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := (h.has_fderiv_at hs).differentiable_at lemma differentiable_on.eventually_differentiable_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) : ∀ᶠ y in 𝓝 x, differentiable_at 𝕜 f y := (eventually_eventually_nhds.2 hs).mono $ λ y, h.differentiable_at lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw h.unique h.differentiable_at.has_fderiv_at } lemma fderiv_eq {f' : E → E →L[𝕜] F} (h : ∀ x, has_fderiv_at f (f' x) x) : fderiv 𝕜 f = f' := funext $ λ x, (h x).fderiv /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. Version using `fderiv`. -/ lemma fderiv_at.le_of_lip {f : E → F} {x₀ : E} (hf : differentiable_at 𝕜 f x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ‖fderiv 𝕜 f x₀‖ ≤ C := hf.has_fderiv_at.le_of_lip hs hlip lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := (hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp only [mem_closure_iff_nhds_within_ne_bot, ne_bot_iff, ne.def, not_not] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at.mono_of_mem (h : differentiable_within_at 𝕜 f s x) {t : set E} (hst : s ∈ nhds_within x t) : differentiable_within_at 𝕜 f t x := (h.has_fderiv_within_at.mono_of_mem hst).differentiable_within_at lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_within_at.antimono (h : differentiable_within_at 𝕜 f s x) (hst : s ⊆ t) (hx : s ∈ 𝓝[t] x) : differentiable_within_at 𝕜 f t x := by rwa [← differentiable_within_at_inter' hx, inter_eq_self_of_subset_right hst] lemma has_fderiv_within_at.antimono (h : has_fderiv_within_at f f' s x) (hst : s ⊆ t) (hs : unique_diff_within_at 𝕜 s x) (hx : s ∈ 𝓝[t] x) : has_fderiv_within_at f f' t x := begin have h' : has_fderiv_within_at f _ t x := (h.differentiable_within_at.antimono hst hx).has_fderiv_within_at, rwa hs.eq h (h'.mono hst), end lemma differentiable_at.differentiable_within_at (h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := (differentiable_within_at_univ.2 h).mono (subset_univ _) lemma differentiable.differentiable_at (h : differentiable 𝕜 f) : differentiable_at 𝕜 f x := h x lemma differentiable_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := h.has_fderiv_at.has_fderiv_within_at.fderiv_within hxs lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) : differentiable_on 𝕜 f s := λ x hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f := by simp only [differentiable_on, differentiable, differentiable_within_at_univ, mem_univ, forall_true_left] lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s := (differentiable_on_univ.2 h).mono (subset_univ _) lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter (is_open.mem_nhds t_open xt)).1 (ht x ⟨xs, xt⟩) end lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := ((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht lemma fderiv_within_subset' (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (hx : s ∈ 𝓝[t] x) (h : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := fderiv_within_subset st ht (h.antimono st hx) @[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f := begin ext x : 1, by_cases h : differentiable_at 𝕜 f x, { apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ, rw has_fderiv_within_at_univ, apply h.has_fderiv_at }, { have : ¬ differentiable_within_at 𝕜 f univ x, { rwa differentiable_within_at_univ }, rw [fderiv_zero_of_not_differentiable_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x, { apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h), apply hs.inter ht }, { have : ¬ differentiable_within_at 𝕜 f s x, { rwa ←differentiable_within_at_inter ht }, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_of_mem_nhds (h : s ∈ 𝓝 x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin have : s = univ ∩ s, by simp only [univ_inter], rw [this, ← fderiv_within_univ], exact fderiv_within_inter h (unique_diff_on_univ _ (mem_univ _)) end lemma fderiv_within_of_open (hs : is_open s) (hx : x ∈ s) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := fderiv_within_of_mem_nhds (is_open.mem_nhds hs hx) lemma fderiv_within_eq_fderiv (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_at 𝕜 f x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin rw ← fderiv_within_univ, exact fderiv_within_subset (subset_univ _) hs h.differentiable_within_at end lemma fderiv_mem_iff {f : E → F} {s : set (E →L[𝕜] F)} {x : E} : fderiv 𝕜 f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ s) ∨ (¬differentiable_at 𝕜 f x ∧ (0 : E →L[𝕜] F) ∈ s) := by by_cases hx : differentiable_at 𝕜 f x; simp [fderiv_zero_of_not_differentiable_at, *] lemma fderiv_within_mem_iff {f : E → F} {t : set E} {s : set (E →L[𝕜] F)} {x : E} : fderiv_within 𝕜 f t x ∈ s ↔ (differentiable_within_at 𝕜 f t x ∧ fderiv_within 𝕜 f t x ∈ s) ∨ (¬differentiable_within_at 𝕜 f t x ∧ (0 : E →L[𝕜] F) ∈ s) := by by_cases hx : differentiable_within_at 𝕜 f t x; simp [fderiv_within_zero_of_not_differentiable_within_at, *] lemma asymptotics.is_O.has_fderiv_within_at {s : set E} {x₀ : E} {n : ℕ} (h : f =O[𝓝[s] x₀] λ x, ‖x - x₀‖^n) (hx₀ : x₀ ∈ s) (hn : 1 < n) : has_fderiv_within_at f (0 : E →L[𝕜] F) s x₀ := by simp_rw [has_fderiv_within_at, has_fderiv_at_filter, h.eq_zero_of_norm_pow_within hx₀ $ zero_lt_one.trans hn, zero_apply, sub_zero, h.trans_is_o ((is_o_pow_sub_sub x₀ hn).mono nhds_within_le_nhds)] lemma asymptotics.is_O.has_fderiv_at {x₀ : E} {n : ℕ} (h : f =O[𝓝 x₀] λ x, ‖x - x₀‖^n) (hn : 1 < n) : has_fderiv_at f (0 : E →L[𝕜] F) x₀ := begin rw [← nhds_within_univ] at h, exact (h.has_fderiv_within_at (mem_univ _) hn).has_fderiv_at_of_univ end lemma has_fderiv_within_at.is_O {f : E → F} {s : set E} {x₀ : E} {f' : E →L[𝕜] F} (h : has_fderiv_within_at f f' s x₀) : (λ x, f x - f x₀) =O[𝓝[s] x₀] λ x, x - x₀ := by simpa only [sub_add_cancel] using h.is_O.add (is_O_sub f' (𝓝[s] x₀) x₀) lemma has_fderiv_at.is_O {f : E → F} {x₀ : E} {f' : E →L[𝕜] F} (h : has_fderiv_at f f' x₀) : (λ x, f x - f x₀) =O[𝓝 x₀] λ x, x - x₀ := by simpa only [sub_add_cancel] using h.is_O.add (is_O_sub f' (𝓝 x₀) x₀) end fderiv_properties section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto.mono_left _ hL), rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds }, have := tendsto.add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp only [sub_add_cancel, eq_self_iff_true, forall_const]) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds le_rfl h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at protected lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) : continuous_at f x := hf.has_fderiv_at.continuous_at lemma has_strict_fderiv_at.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) x) : (λ p : E × E, p.1 - p.2) =O[𝓝 (x, x)](λ p : E × E, f p.1 - f p.2) := ((f'.is_O_comp_rev _ _).trans (hf.trans_is_O (f'.is_O_comp_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) lemma has_fderiv_at_filter.is_O_sub_rev (hf : has_fderiv_at_filter f f' x L) {C} (hf' : antilipschitz_with C f') : (λ x', x' - x) =O[L] (λ x', f x' - f x) := have (λ x', x' - x) =O[L] (λ x', f' (x' - x)), from is_O_iff.2 ⟨C, eventually_of_forall $ λ x', add_monoid_hom_class.bound_of_antilipschitz f' hf' _⟩, (this.trans (hf.trans_is_O this).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) end continuous section congr /-! ### congr properties of the derivative -/ theorem filter.eventually_eq.has_strict_fderiv_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) (h' : ∀ y, f₀' y = f₁' y) : has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x := begin refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall $ λ _, rfl), rintros p ⟨hp₁, hp₂⟩, simp only [*] end theorem has_strict_fderiv_at.congr_of_eventually_eq (h : has_strict_fderiv_at f f' x) (h₁ : f =ᶠ[𝓝 x] f₁) : has_strict_fderiv_at f₁ f' x := (h₁.has_strict_fderiv_at_iff (λ _, rfl)).1 h theorem filter.eventually_eq.has_fderiv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall $ λ _, rfl) lemma has_fderiv_at_filter.congr_of_eventually_eq (h : has_fderiv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := (hL.has_fderiv_at_filter_iff hx $ λ _, rfl).2 h theorem filter.eventually_eq.has_fderiv_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) : has_fderiv_at f₀ f' x ↔ has_fderiv_at f₁ f' x := h.has_fderiv_at_filter_iff h.eq_of_nhds (λ _, rfl) theorem filter.eventually_eq.differentiable_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) : differentiable_at 𝕜 f₀ x ↔ differentiable_at 𝕜 f₁ x := exists_congr $ λ f', h.has_fderiv_at_iff theorem filter.eventually_eq.has_fderiv_within_at_iff (h : f₀ =ᶠ[𝓝[s] x] f₁) (hx : f₀ x = f₁ x) : has_fderiv_within_at f₀ f' s x ↔ has_fderiv_within_at f₁ f' s x := h.has_fderiv_at_filter_iff hx (λ _, rfl) theorem filter.eventually_eq.has_fderiv_within_at_iff_of_mem (h : f₀ =ᶠ[𝓝[s] x] f₁) (hx : x ∈ s) : has_fderiv_within_at f₀ f' s x ↔ has_fderiv_within_at f₁ f' s x := h.has_fderiv_within_at_iff (h.eq_of_nhds_within hx) theorem filter.eventually_eq.differentiable_within_at_iff (h : f₀ =ᶠ[𝓝[s] x] f₁) (hx : f₀ x = f₁ x) : differentiable_within_at 𝕜 f₀ s x ↔ differentiable_within_at 𝕜 f₁ s x := exists_congr $ λ f', h.has_fderiv_within_at_iff hx theorem filter.eventually_eq.differentiable_within_at_iff_of_mem (h : f₀ =ᶠ[𝓝[s] x] f₁) (hx : x ∈ s) : differentiable_within_at 𝕜 f₀ s x ↔ differentiable_within_at 𝕜 f₁ s x := h.differentiable_within_at_iff (h.eq_of_nhds_within hx) lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr_of_eventually_eq (h.mono h₁) (filter.mem_inf_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr' (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : x ∈ s) : has_fderiv_within_at f₁ f' s x := h.congr hs (hs x hx) lemma has_fderiv_within_at.congr_of_eventually_eq (h : has_fderiv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_fderiv_at.congr_of_eventually_eq (h : has_fderiv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ (mem_of_mem_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_eventually_eq (h : differentiable_within_at 𝕜 f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_eventually_eq h₁ hx).differentiable_within_at lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s := λ x hx, (h x hx).congr h' (h' x hx) lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s := ⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm), λ h, differentiable_on.congr h h'⟩ lemma differentiable_at.congr_of_eventually_eq (h : differentiable_at 𝕜 f x) (hL : f₁ =ᶠ[𝓝 x] f) : differentiable_at 𝕜 f₁ x := hL.differentiable_at_iff.2 h lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma filter.eventually_eq.fderiv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then has_fderiv_within_at.fderiv_within (h.has_fderiv_within_at.congr_of_eventually_eq hL hx) hs else have h' : ¬ differentiable_within_at 𝕜 f₁ s x, from mt (λ h, h.congr_of_eventually_eq (hL.mono $ λ x, eq.symm) hx.symm) h, by rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at h'] lemma filter.eventually_eq.fderiv_within_eq_nhds (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝 x] f) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := (show f₁ =ᶠ[𝓝[s] x] f, from nhds_within_le_nhds hL).fderiv_within_eq hs (mem_of_mem_nhds hL : _) lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply filter.eventually_eq.fderiv_within_eq hs _ hx, apply mem_of_superset self_mem_nhds_within, exact hL end lemma filter.eventually_eq.fderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := hL.eq_of_nhds, rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact hL.fderiv_within_eq unique_diff_within_at_univ A end protected lemma filter.eventually_eq.fderiv (h : f₁ =ᶠ[𝓝 x] f) : fderiv 𝕜 f₁ =ᶠ[𝓝 x] fderiv 𝕜 f := h.eventually_eq_nhds.mono $ λ x h, h.fderiv_eq end congr section id /-! ### Derivative of the identity -/ theorem has_strict_fderiv_at_id (x : E) : has_strict_fderiv_at id (id 𝕜 E) x := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id 𝕜 E) x L := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_within_at_id (x : E) (s : set E) : has_fderiv_within_at id (id 𝕜 E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id 𝕜 E) x := has_fderiv_at_filter_id _ _ @[simp] lemma differentiable_at_id : differentiable_at 𝕜 id x := (has_fderiv_at_id x).differentiable_at @[simp] lemma differentiable_at_id' : differentiable_at 𝕜 (λ x, x) x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x := differentiable_at_id.differentiable_within_at @[simp] lemma differentiable_id : differentiable 𝕜 (id : E → E) := λx, differentiable_at_id @[simp] lemma differentiable_id' : differentiable 𝕜 (λ (x : E), x) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on 𝕜 id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv 𝕜 id x = id 𝕜 E := has_fderiv_at.fderiv (has_fderiv_at_id x) @[simp] lemma fderiv_id' : fderiv 𝕜 (λ (x : E), x) x = continuous_linear_map.id 𝕜 E := fderiv_id lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id 𝕜 E := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end lemma fderiv_within_id' (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ (x : E), x) s x = continuous_linear_map.id 𝕜 E := fderiv_within_id hxs end id section const /-! ### derivative of a constant function -/ theorem has_strict_fderiv_at_const (c : F) (x : E) : has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x := has_fderiv_at_filter_const _ _ _ @[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) @[simp] lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 := by { ext m, rw fderiv_const_apply, refl } lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const_apply _ end @[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on lemma has_fderiv_within_at_singleton (f : E → F) (x : E) : has_fderiv_within_at f (0 : E →L[𝕜] F) {x} x := by simp only [has_fderiv_within_at, nhds_within_singleton, has_fderiv_at_filter, is_o_pure, continuous_linear_map.zero_apply, sub_self] lemma has_fderiv_at_of_subsingleton [h : subsingleton E] (f : E → F) (x : E) : has_fderiv_at f (0 : E →L[𝕜] F) x := begin rw [← has_fderiv_within_at_univ, subsingleton_univ.eq_singleton_of_mem (mem_univ x)], exact has_fderiv_within_at_singleton f x end lemma differentiable_on_empty : differentiable_on 𝕜 f ∅ := λ x, false.elim lemma differentiable_on_singleton : differentiable_on 𝕜 f {x} := forall_eq.2 (has_fderiv_within_at_singleton f x).differentiable_within_at lemma set.subsingleton.differentiable_on (hs : s.subsingleton) : differentiable_on 𝕜 f s := hs.induction_on differentiable_on_empty (λ x, differentiable_on_singleton) lemma has_fderiv_at_zero_of_eventually_const (c : F) (hf : f =ᶠ[𝓝 x] (λ y, c)) : has_fderiv_at f (0 : E →L[𝕜] F) x := (has_fderiv_at_const _ _).congr_of_eventually_eq hf end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} : has_strict_fderiv_at e e x := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter @[simp] protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at @[simp] protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end @[simp] protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := h.to_continuous_linear_map.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on end continuous_linear_map section composition /-! ### Derivative of the composition of two functions For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G} {L' : filter F} (hg : has_fderiv_at_filter g g' (f x) L') (hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L L') : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in let eq₂ := (hg.comp_tendsto hL).trans_is_O hf.is_O_sub in by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp } /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := begin unfold has_fderiv_at_filter at hg, have := calc (λ x', g (f x') - g (f x) - g' (f x' - f x)) =o[L] (λ x', f x' - f x) : hg.comp_tendsto le_rfl ... =O[L] (λ x', x' - x) : hf.is_O_sub, refine this.triangle _, calc (λ x' : E, g' (f x' - f x) - g'.comp f' (x' - x)) =ᶠ[L] λ x', g' (f x' - f x - f' (x' - x)) : eventually_of_forall (λ x', by simp) ... =O[L] λ x', f x' - f x - f' (x' - x) : g'.is_O_comp _ _ ... =o[L] λ x', x' - x : hf end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : maps_to f s t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := hg.comp x hf $ hf.continuous_within_at.tendsto_nhds_within hst theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := hg.comp x hf hf.continuous_within_at theorem has_fderiv_within_at.comp_of_mem {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : tendsto f (𝓝[s] x) (𝓝[t] f x)) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := has_fderiv_at_filter.comp x hg hf hst /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := hg.comp x hf hf.continuous_at lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : maps_to f s t) : differentiable_within_at 𝕜 (g ∘ f) s x := (hg.has_fderiv_within_at.comp x hf.has_fderiv_within_at h).differentiable_within_at lemma differentiable_within_at.comp' {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma differentiable_at.comp_differentiable_within_at {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) s x := hg.differentiable_within_at.comp x hf (maps_to_univ _ _) lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) := (hg.has_fderiv_within_at.comp x (hf.has_fderiv_within_at) h).fderiv_within hxs /-- Ternary version of `fderiv_within.comp`, with equality assumptions of basepoints added, in order to apply more easily as a rewrite from right-to-left. -/ lemma fderiv_within.comp₃ {g' : G → G'} {g : F → G} {t : set F} {u : set G} {y : F} {y' : G} (hg' : differentiable_within_at 𝕜 g' u y') (hg : differentiable_within_at 𝕜 g t y) (hf : differentiable_within_at 𝕜 f s x) (h2g : maps_to g t u) (h2f : maps_to f s t) (h3g : g y = y') (h3f : f x = y) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g' ∘ g ∘ f) s x = (fderiv_within 𝕜 g' u y').comp ((fderiv_within 𝕜 g t y).comp (fderiv_within 𝕜 f s x)) := begin substs h3g h3f, exact (hg'.has_fderiv_within_at.comp x (hg.has_fderiv_within_at.comp x (hf.has_fderiv_within_at) h2f) $ h2g.comp h2f).fderiv_within hxs end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := (hg.has_fderiv_at.comp x hf.has_fderiv_at).fderiv lemma fderiv.comp_fderiv_within {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) := (hg.has_fderiv_at.comp_has_fderiv_within_at x hf.has_fderiv_within_at).fderiv_within hxs lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : maps_to f s t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (g ∘ f) s := hg.differentiable_on.comp hf (maps_to_univ _ _) /-- The chain rule for derivatives in the sense of strict differentiability. -/ protected lemma has_strict_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_strict_fderiv_at g g' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, g (f x)) (g'.comp f') x := ((hg.comp_tendsto (hf.continuous_at.prod_map' hf.continuous_at)).trans_is_O hf.is_O_sub).triangle $ by simpa only [g'.map_sub, f'.coe_comp'] using (g'.is_O_comp _ _).trans_is_o hf protected lemma differentiable.iterate {f : E → E} (hf : differentiable 𝕜 f) (n : ℕ) : differentiable 𝕜 (f^[n]) := nat.rec_on n differentiable_id (λ n ihn, ihn.comp hf) protected lemma differentiable_on.iterate {f : E → E} (hf : differentiable_on 𝕜 f s) (hs : maps_to f s s) (n : ℕ) : differentiable_on 𝕜 (f^[n]) s := nat.rec_on n differentiable_on_id (λ n ihn, ihn.comp hf hs) variable {x} protected lemma has_fderiv_at_filter.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_fderiv_at_filter (f^[n]) (f'^n) x L := begin induction n with n ihn, { exact has_fderiv_at_filter_id x L }, { rw [function.iterate_succ, pow_succ'], rw ← hx at ihn, exact ihn.comp x hf hL } end protected lemma has_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_fderiv_at (f^[n]) (f'^n) x := begin refine hf.iterate _ hx n, convert hf.continuous_at, exact hx.symm end protected lemma has_fderiv_within_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_fderiv_within_at (f^[n]) (f'^n) s x := begin refine hf.iterate _ hx n, convert tendsto_inf.2 ⟨hf.continuous_within_at, _⟩, exacts [hx.symm, (tendsto_principal_principal.2 hs).mono_left inf_le_right] end protected lemma has_strict_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_strict_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_fderiv_at (f^[n]) (f'^n) x := begin induction n with n ihn, { exact has_strict_fderiv_at_id x }, { rw [function.iterate_succ, pow_succ'], rw ← hx at ihn, exact ihn.comp x hf } end protected lemma differentiable_at.iterate {f : E → E} (hf : differentiable_at 𝕜 f x) (hx : f x = x) (n : ℕ) : differentiable_at 𝕜 (f^[n]) x := (hf.has_fderiv_at.iterate hx n).differentiable_at protected lemma differentiable_within_at.iterate {f : E → E} (hf : differentiable_within_at 𝕜 f s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : differentiable_within_at 𝕜 (f^[n]) s x := (hf.has_fderiv_within_at.iterate hx hs n).differentiable_within_at end composition section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ section prod variables {f₂ : E → G} {f₂' : E →L[𝕜] G} protected lemma has_strict_fderiv_at.prod (hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x := hf₁.prod_left hf₂ lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x L := hf₁.prod_left hf₂ lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x := hf₁.prod hf₂ lemma has_fderiv_at_prod_mk_left (e₀ : E) (f₀ : F) : has_fderiv_at (λ e : E, (e, f₀)) (inl 𝕜 E F) e₀ := (has_fderiv_at_id e₀).prod (has_fderiv_at_const f₀ e₀) lemma has_fderiv_at_prod_mk_right (e₀ : E) (f₀ : F) : has_fderiv_at (λ f : F, (e₀, f)) (inr 𝕜 E F) f₀ := (has_fderiv_at_const e₀ f₀).prod (has_fderiv_at_id f₀) lemma differentiable_within_at.prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) @[simp] lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = (fderiv 𝕜 f₁ x).prod (fderiv 𝕜 f₂ x) := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).fderiv lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = (fderiv_within 𝕜 f₁ s x).prod (fderiv_within 𝕜 f₂ s x) := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).fderiv_within hxs end prod section fst variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_fst : has_strict_fderiv_at (@prod.fst E F) (fst 𝕜 E F) p := (fst 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.fst (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := has_strict_fderiv_at_fst.comp x h lemma has_fderiv_at_filter_fst {L : filter (E × F)} : has_fderiv_at_filter (@prod.fst E F) (fst 𝕜 E F) p L := (fst 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.fst (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_fst.comp x h tendsto_map lemma has_fderiv_at_fst : has_fderiv_at (@prod.fst E F) (fst 𝕜 E F) p := has_fderiv_at_filter_fst protected lemma has_fderiv_at.fst (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := h.fst lemma has_fderiv_within_at_fst {s : set (E × F)} : has_fderiv_within_at (@prod.fst E F) (fst 𝕜 E F) s p := has_fderiv_at_filter_fst protected lemma has_fderiv_within_at.fst (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') s x := h.fst lemma differentiable_at_fst : differentiable_at 𝕜 prod.fst p := has_fderiv_at_fst.differentiable_at @[simp] protected lemma differentiable_at.fst (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).1) x := differentiable_at_fst.comp x h lemma differentiable_fst : differentiable 𝕜 (prod.fst : E × F → E) := λ x, differentiable_at_fst @[simp] protected lemma differentiable.fst (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).1) := differentiable_fst.comp h lemma differentiable_within_at_fst {s : set (E × F)} : differentiable_within_at 𝕜 prod.fst s p := differentiable_at_fst.differentiable_within_at protected lemma differentiable_within_at.fst (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).1) s x := differentiable_at_fst.comp_differentiable_within_at x h lemma differentiable_on_fst {s : set (E × F)} : differentiable_on 𝕜 prod.fst s := differentiable_fst.differentiable_on protected lemma differentiable_on.fst (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).1) s := differentiable_fst.comp_differentiable_on h lemma fderiv_fst : fderiv 𝕜 prod.fst p = fst 𝕜 E F := has_fderiv_at_fst.fderiv lemma fderiv.fst (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).1) x = (fst 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.fst.fderiv lemma fderiv_within_fst {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.fst s p = fst 𝕜 E F := has_fderiv_within_at_fst.fderiv_within hs lemma fderiv_within.fst (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).1) s x = (fst 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.fst.fderiv_within hs end fst section snd variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_snd : has_strict_fderiv_at (@prod.snd E F) (snd 𝕜 E F) p := (snd 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.snd (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := has_strict_fderiv_at_snd.comp x h lemma has_fderiv_at_filter_snd {L : filter (E × F)} : has_fderiv_at_filter (@prod.snd E F) (snd 𝕜 E F) p L := (snd 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.snd (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_snd.comp x h tendsto_map lemma has_fderiv_at_snd : has_fderiv_at (@prod.snd E F) (snd 𝕜 E F) p := has_fderiv_at_filter_snd protected lemma has_fderiv_at.snd (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := h.snd lemma has_fderiv_within_at_snd {s : set (E × F)} : has_fderiv_within_at (@prod.snd E F) (snd 𝕜 E F) s p := has_fderiv_at_filter_snd protected lemma has_fderiv_within_at.snd (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') s x := h.snd lemma differentiable_at_snd : differentiable_at 𝕜 prod.snd p := has_fderiv_at_snd.differentiable_at @[simp] protected lemma differentiable_at.snd (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).2) x := differentiable_at_snd.comp x h lemma differentiable_snd : differentiable 𝕜 (prod.snd : E × F → F) := λ x, differentiable_at_snd @[simp] protected lemma differentiable.snd (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).2) := differentiable_snd.comp h lemma differentiable_within_at_snd {s : set (E × F)} : differentiable_within_at 𝕜 prod.snd s p := differentiable_at_snd.differentiable_within_at protected lemma differentiable_within_at.snd (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).2) s x := differentiable_at_snd.comp_differentiable_within_at x h lemma differentiable_on_snd {s : set (E × F)} : differentiable_on 𝕜 prod.snd s := differentiable_snd.differentiable_on protected lemma differentiable_on.snd (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).2) s := differentiable_snd.comp_differentiable_on h lemma fderiv_snd : fderiv 𝕜 prod.snd p = snd 𝕜 E F := has_fderiv_at_snd.fderiv lemma fderiv.snd (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).2) x = (snd 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.snd.fderiv lemma fderiv_within_snd {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.snd s p = snd 𝕜 E F := has_fderiv_within_at_snd.fderiv_within hs lemma fderiv_within.snd (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).2) s x = (snd 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.snd.fderiv_within hs end snd section prod_map variables {f₂ : G → G'} {f₂' : G →L[𝕜] G'} {y : G} (p : E × G) protected theorem has_strict_fderiv_at.prod_map (hf : has_strict_fderiv_at f f' p.1) (hf₂ : has_strict_fderiv_at f₂ f₂' p.2) : has_strict_fderiv_at (prod.map f f₂) (f'.prod_map f₂') p := (hf.comp p has_strict_fderiv_at_fst).prod (hf₂.comp p has_strict_fderiv_at_snd) protected theorem has_fderiv_at.prod_map (hf : has_fderiv_at f f' p.1) (hf₂ : has_fderiv_at f₂ f₂' p.2) : has_fderiv_at (prod.map f f₂) (f'.prod_map f₂') p := (hf.comp p has_fderiv_at_fst).prod (hf₂.comp p has_fderiv_at_snd) @[simp] protected theorem differentiable_at.prod_map (hf : differentiable_at 𝕜 f p.1) (hf₂ : differentiable_at 𝕜 f₂ p.2) : differentiable_at 𝕜 (λ p : E × G, (f p.1, f₂ p.2)) p := (hf.comp p differentiable_at_fst).prod (hf₂.comp p differentiable_at_snd) end prod_map end cartesian_product section const_smul variables {R : Type*} [semiring R] [module R F] [smul_comm_class 𝕜 R F] [has_continuous_const_smul R F] /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : R) : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : R) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h tendsto_map theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : R) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : R) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : R) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : R) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : R) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : R) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : R) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : R) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ y, f y + g y) (f' + g') x := (hf.add hg).congr_left $ λ y, by { simp only [linear_map.sub_apply, linear_map.add_apply, map_sub, map_add, add_apply], abel } theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by { simp only [linear_map.sub_apply, linear_map.add_apply, map_sub, map_add, add_apply], abel } theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) @[simp] lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, f y + c) f' x := add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _) theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at @[simp] lemma differentiable_within_at_add_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at @[simp] lemma differentiable_at_add_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y + c) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c @[simp] lemma differentiable_on_add_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y + c) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c @[simp] lemma differentiable_add_const_iff (c : F) : differentiable 𝕜 (λ y, f y + c) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := if hf : differentiable_within_at 𝕜 f s x then (hf.has_fderiv_within_at.add_const c).fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf, fderiv_within_zero_of_not_differentiable_within_at], simpa } lemma fderiv_add_const (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_add_const unique_diff_within_at_univ] theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, c + f y) f' x := zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at @[simp] lemma differentiable_within_at_const_add_iff (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at @[simp] lemma differentiable_at_const_add_iff (c : F) : differentiable_at 𝕜 (λ y, c + f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c @[simp] lemma differentiable_on_const_add_iff (c : F) : differentiable_on 𝕜 (λ y, c + f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c @[simp] lemma differentiable_const_add_iff (c : F) : differentiable 𝕜 (λ y, c + f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := by simpa only [add_comm] using fderiv_within_add_const hxs c lemma fderiv_const_add (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := by simp only [add_comm c, fderiv_add_const] end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (E → F)} {A' : ι → (E →L[𝕜] F)} theorem has_strict_fderiv_at.sum (h : ∀ i ∈ u, has_strict_fderiv_at (A i) (A' i) x) : has_strict_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := begin dsimp [has_strict_fderiv_at] at *, convert is_o.sum h, simp [finset.sum_sub_distrib, continuous_linear_map.sum_apply] end theorem has_fderiv_at_filter.sum (h : ∀ i ∈ u, has_fderiv_at_filter (A i) (A' i) x L) : has_fderiv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := begin dsimp [has_fderiv_at_filter] at *, convert is_o.sum h, simp [continuous_linear_map.sum_apply] end theorem has_fderiv_within_at.sum (h : ∀ i ∈ u, has_fderiv_within_at (A i) (A' i) s x) : has_fderiv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_fderiv_at_filter.sum h theorem has_fderiv_at.sum (h : ∀ i ∈ u, has_fderiv_at (A i) (A' i) x) : has_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_fderiv_at_filter.sum h theorem differentiable_within_at.sum (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : differentiable_within_at 𝕜 (λ y, ∑ i in u, A i y) s x := has_fderiv_within_at.differentiable_within_at $ has_fderiv_within_at.sum $ λ i hi, (h i hi).has_fderiv_within_at @[simp] theorem differentiable_at.sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : differentiable_at 𝕜 (λ y, ∑ i in u, A i y) x := has_fderiv_at.differentiable_at $ has_fderiv_at.sum $ λ i hi, (h i hi).has_fderiv_at theorem differentiable_on.sum (h : ∀ i ∈ u, differentiable_on 𝕜 (A i) s) : differentiable_on 𝕜 (λ y, ∑ i in u, A i y) s := λ x hx, differentiable_within_at.sum $ λ i hi, h i hi x hx @[simp] theorem differentiable.sum (h : ∀ i ∈ u, differentiable 𝕜 (A i)) : differentiable 𝕜 (λ y, ∑ i in u, A i y) := λ x, differentiable_at.sum $ λ i hi, h i hi x theorem fderiv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : fderiv_within 𝕜 (λ y, ∑ i in u, A i y) s x = (∑ i in u, fderiv_within 𝕜 (A i) s x) := (has_fderiv_within_at.sum (λ i hi, (h i hi).has_fderiv_within_at)).fderiv_within hxs theorem fderiv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : fderiv 𝕜 (λ y, ∑ i in u, A i y) x = (∑ i in u, fderiv 𝕜 (A i) x) := (has_fderiv_at.sum (λ i hi, (h i hi).has_fderiv_at)).fderiv end sum section pi /-! ### Derivatives of functions `f : E → Π i, F' i` In this section we formulate `has_*fderiv*_pi` theorems as `iff`s, and provide two versions of each theorem: * the version without `'` deals with `φ : Π i, E → F' i` and `φ' : Π i, E →L[𝕜] F' i` and is designed to deduce differentiability of `λ x i, φ i x` from differentiability of each `φ i`; * the version with `'` deals with `Φ : E → Π i, F' i` and `Φ' : E →L[𝕜] Π i, F' i` and is designed to deduce differentiability of the components `λ x, Φ x i` from differentiability of `Φ`. -/ variables {ι : Type*} [fintype ι] {F' : ι → Type*} [Π i, normed_add_comm_group (F' i)] [Π i, normed_space 𝕜 (F' i)] {φ : Π i, E → F' i} {φ' : Π i, E →L[𝕜] F' i} {Φ : E → Π i, F' i} {Φ' : E →L[𝕜] Π i, F' i} @[simp] lemma has_strict_fderiv_at_pi' : has_strict_fderiv_at Φ Φ' x ↔ ∀ i, has_strict_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x := begin simp only [has_strict_fderiv_at, continuous_linear_map.coe_pi], exact is_o_pi end @[simp] lemma has_strict_fderiv_at_pi : has_strict_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔ ∀ i, has_strict_fderiv_at (φ i) (φ' i) x := has_strict_fderiv_at_pi' @[simp] lemma has_fderiv_at_filter_pi' : has_fderiv_at_filter Φ Φ' x L ↔ ∀ i, has_fderiv_at_filter (λ x, Φ x i) ((proj i).comp Φ') x L := begin simp only [has_fderiv_at_filter, continuous_linear_map.coe_pi], exact is_o_pi end lemma has_fderiv_at_filter_pi : has_fderiv_at_filter (λ x i, φ i x) (continuous_linear_map.pi φ') x L ↔ ∀ i, has_fderiv_at_filter (φ i) (φ' i) x L := has_fderiv_at_filter_pi' @[simp] lemma has_fderiv_at_pi' : has_fderiv_at Φ Φ' x ↔ ∀ i, has_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x := has_fderiv_at_filter_pi' lemma has_fderiv_at_pi : has_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔ ∀ i, has_fderiv_at (φ i) (φ' i) x := has_fderiv_at_filter_pi @[simp] lemma has_fderiv_within_at_pi' : has_fderiv_within_at Φ Φ' s x ↔ ∀ i, has_fderiv_within_at (λ x, Φ x i) ((proj i).comp Φ') s x := has_fderiv_at_filter_pi' lemma has_fderiv_within_at_pi : has_fderiv_within_at (λ x i, φ i x) (continuous_linear_map.pi φ') s x ↔ ∀ i, has_fderiv_within_at (φ i) (φ' i) s x := has_fderiv_at_filter_pi @[simp] lemma differentiable_within_at_pi : differentiable_within_at 𝕜 Φ s x ↔ ∀ i, differentiable_within_at 𝕜 (λ x, Φ x i) s x := ⟨λ h i, (has_fderiv_within_at_pi'.1 h.has_fderiv_within_at i).differentiable_within_at, λ h, (has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).differentiable_within_at⟩ @[simp] lemma differentiable_at_pi : differentiable_at 𝕜 Φ x ↔ ∀ i, differentiable_at 𝕜 (λ x, Φ x i) x := ⟨λ h i, (has_fderiv_at_pi'.1 h.has_fderiv_at i).differentiable_at, λ h, (has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).differentiable_at⟩ lemma differentiable_on_pi : differentiable_on 𝕜 Φ s ↔ ∀ i, differentiable_on 𝕜 (λ x, Φ x i) s := ⟨λ h i x hx, differentiable_within_at_pi.1 (h x hx) i, λ h x hx, differentiable_within_at_pi.2 (λ i, h i x hx)⟩ lemma differentiable_pi : differentiable 𝕜 Φ ↔ ∀ i, differentiable 𝕜 (λ x, Φ x i) := ⟨λ h i x, differentiable_at_pi.1 (h x) i, λ h x, differentiable_at_pi.2 (λ i, h i x)⟩ -- TODO: find out which version (`φ` or `Φ`) works better with `rw`/`simp` lemma fderiv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (φ i) s x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ x i, φ i x) s x = pi (λ i, fderiv_within 𝕜 (φ i) s x) := (has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).fderiv_within hs lemma fderiv_pi (h : ∀ i, differentiable_at 𝕜 (φ i) x) : fderiv 𝕜 (λ x i, φ i x) x = pi (λ i, fderiv 𝕜 (φ i) x) := (has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).fderiv end pi section neg /-! ### Derivative of the negative of a function -/ theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, -f x) (-f') x := (-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h tendsto_map theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at @[simp] lemma differentiable_within_at_neg_iff : differentiable_within_at 𝕜 (λy, -f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at @[simp] lemma differentiable_at_neg_iff : differentiable_at 𝕜 (λy, -f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg @[simp] lemma differentiable_on_neg_iff : differentiable_on 𝕜 (λy, -f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg @[simp] lemma differentiable_neg_iff : differentiable 𝕜 (λy, -f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then h.has_fderiv_within_at.neg.fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at, neg_zero], simpa } @[simp] lemma fderiv_neg : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_neg unique_diff_within_at_univ] end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_strict_fderiv_at.sub (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ x, f x - g x) (f' - g') x := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) @[simp] lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.sub_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, f x - c) f' x := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at @[simp] lemma differentiable_within_at_sub_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x ↔ differentiable_within_at 𝕜 f s x := by simp only [sub_eq_add_neg, differentiable_within_at_add_const_iff] lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at @[simp] lemma differentiable_at_sub_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y - c) x ↔ differentiable_at 𝕜 f x := by simp only [sub_eq_add_neg, differentiable_at_add_const_iff] lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c @[simp] lemma differentiable_on_sub_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y - c) s ↔ differentiable_on 𝕜 f s := by simp only [sub_eq_add_neg, differentiable_on_add_const_iff] lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c @[simp] lemma differentiable_sub_const_iff (c : F) : differentiable 𝕜 (λ y, f y - c) ↔ differentiable 𝕜 f := by simp only [sub_eq_add_neg, differentiable_add_const_iff] lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_add_const hxs] lemma fderiv_sub_const (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := by simp only [sub_eq_add_neg, fderiv_add_const] theorem has_strict_fderiv_at.const_sub (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, c - f x) (-f') x := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at @[simp] lemma differentiable_within_at_const_sub_iff (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x ↔ differentiable_within_at 𝕜 f s x := by simp [sub_eq_add_neg] lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at @[simp] lemma differentiable_at_const_sub_iff (c : F) : differentiable_at 𝕜 (λ y, c - f y) x ↔ differentiable_at 𝕜 f x := by simp [sub_eq_add_neg] lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c @[simp] lemma differentiable_on_const_sub_iff (c : F) : differentiable_on 𝕜 (λ y, c - f y) s ↔ differentiable_on 𝕜 f s := by simp [sub_eq_add_neg] lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c @[simp] lemma differentiable_const_sub_iff (c : F) : differentiable 𝕜 (λ y, c - f y) ↔ differentiable 𝕜 f := by simp [sub_eq_add_neg] lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_const_add, fderiv_within_neg, hxs] lemma fderiv_const_sub (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_const_sub unique_diff_within_at_univ] end sub section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_strict_fderiv_at b (h.deriv p) p := begin rw has_strict_fderiv_at, set T := (E × F) × (E × F), have : (λ q : T, b (q.1 - q.2)) =o[𝓝 (p, p)] (λ q : T, ‖q.1 - q.2‖ * 1), { refine (h.is_O'.comp_tendsto le_top).trans_is_o _, simp only [(∘)], refine (is_O_refl (λ q : T, ‖q.1 - q.2‖) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _), rw [← sub_self p], exact continuous_at_fst.sub continuous_at_snd }, simp only [mul_one, is_o_norm_right] at this, refine (is_o.congr_of_sub _).1 this, clear this, convert_to (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) =o[𝓝 (p, p)] (λ q : T, q.1 - q.2), { ext ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩, simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right], abel }, have : (λ q : T, p - q.2) =o[𝓝 (p, p)] (λ q, (1:ℝ)), from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd), apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o, refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right, refine is_o.mul_is_O _ (is_O_refl _ _), exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top : _).trans_is_o this).norm_left end lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := (h.has_strict_fderiv_at p).has_fderiv_at lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on end bilinear_map section clm_comp_apply /-! ### Derivative of the pointwise composition/application of continuous linear maps -/ variables {H : Type*} [normed_add_comm_group H] [normed_space 𝕜 H] {c : E → G →L[𝕜] H} {c' : E →L[𝕜] G →L[𝕜] H} {d : E → F →L[𝕜] G} {d' : E →L[𝕜] F →L[𝕜] G} {u : E → G} {u' : E →L[𝕜] G} lemma has_strict_fderiv_at.clm_comp (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, (c y).comp (d y)) ((compL 𝕜 F G H (c x)).comp d' + ((compL 𝕜 F G H).flip (d x)).comp c') x := (is_bounded_bilinear_map_comp.has_strict_fderiv_at (c x, d x)).comp x $ hc.prod hd lemma has_fderiv_within_at.clm_comp (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, (c y).comp (d y)) ((compL 𝕜 F G H (c x)).comp d' + ((compL 𝕜 F G H).flip (d x)).comp c') s x := (is_bounded_bilinear_map_comp.has_fderiv_at (c x, d x)).comp_has_fderiv_within_at x $ hc.prod hd lemma has_fderiv_at.clm_comp (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, (c y).comp (d y)) ((compL 𝕜 F G H (c x)).comp d' + ((compL 𝕜 F G H).flip (d x)).comp c') x := (is_bounded_bilinear_map_comp.has_fderiv_at (c x, d x)).comp x $ hc.prod hd lemma differentiable_within_at.clm_comp (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, (c y).comp (d y)) s x := (hc.has_fderiv_within_at.clm_comp hd.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.clm_comp (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, (c y).comp (d y)) x := (hc.has_fderiv_at.clm_comp hd.has_fderiv_at).differentiable_at lemma differentiable_on.clm_comp (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, (c y).comp (d y)) s := λx hx, (hc x hx).clm_comp (hd x hx) lemma differentiable.clm_comp (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, (c y).comp (d y)) := λx, (hc x).clm_comp (hd x) lemma fderiv_within_clm_comp (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, (c y).comp (d y)) s x = (compL 𝕜 F G H (c x)).comp (fderiv_within 𝕜 d s x) + ((compL 𝕜 F G H).flip (d x)).comp (fderiv_within 𝕜 c s x) := (hc.has_fderiv_within_at.clm_comp hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_clm_comp (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, (c y).comp (d y)) x = (compL 𝕜 F G H (c x)).comp (fderiv 𝕜 d x) + ((compL 𝕜 F G H).flip (d x)).comp (fderiv 𝕜 c x) := (hc.has_fderiv_at.clm_comp hd.has_fderiv_at).fderiv lemma has_strict_fderiv_at.clm_apply (hc : has_strict_fderiv_at c c' x) (hu : has_strict_fderiv_at u u' x) : has_strict_fderiv_at (λ y, (c y) (u y)) ((c x).comp u' + c'.flip (u x)) x := (is_bounded_bilinear_map_apply.has_strict_fderiv_at (c x, u x)).comp x (hc.prod hu) lemma has_fderiv_within_at.clm_apply (hc : has_fderiv_within_at c c' s x) (hu : has_fderiv_within_at u u' s x) : has_fderiv_within_at (λ y, (c y) (u y)) ((c x).comp u' + c'.flip (u x)) s x := (is_bounded_bilinear_map_apply.has_fderiv_at (c x, u x)).comp_has_fderiv_within_at x (hc.prod hu) lemma has_fderiv_at.clm_apply (hc : has_fderiv_at c c' x) (hu : has_fderiv_at u u' x) : has_fderiv_at (λ y, (c y) (u y)) ((c x).comp u' + c'.flip (u x)) x := (is_bounded_bilinear_map_apply.has_fderiv_at (c x, u x)).comp x (hc.prod hu) lemma differentiable_within_at.clm_apply (hc : differentiable_within_at 𝕜 c s x) (hu : differentiable_within_at 𝕜 u s x) : differentiable_within_at 𝕜 (λ y, (c y) (u y)) s x := (hc.has_fderiv_within_at.clm_apply hu.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.clm_apply (hc : differentiable_at 𝕜 c x) (hu : differentiable_at 𝕜 u x) : differentiable_at 𝕜 (λ y, (c y) (u y)) x := (hc.has_fderiv_at.clm_apply hu.has_fderiv_at).differentiable_at lemma differentiable_on.clm_apply (hc : differentiable_on 𝕜 c s) (hu : differentiable_on 𝕜 u s) : differentiable_on 𝕜 (λ y, (c y) (u y)) s := λx hx, (hc x hx).clm_apply (hu x hx) lemma differentiable.clm_apply (hc : differentiable 𝕜 c) (hu : differentiable 𝕜 u) : differentiable 𝕜 (λ y, (c y) (u y)) := λx, (hc x).clm_apply (hu x) lemma fderiv_within_clm_apply (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hu : differentiable_within_at 𝕜 u s x) : fderiv_within 𝕜 (λ y, (c y) (u y)) s x = ((c x).comp (fderiv_within 𝕜 u s x) + (fderiv_within 𝕜 c s x).flip (u x)) := (hc.has_fderiv_within_at.clm_apply hu.has_fderiv_within_at).fderiv_within hxs lemma fderiv_clm_apply (hc : differentiable_at 𝕜 c x) (hu : differentiable_at 𝕜 u x) : fderiv 𝕜 (λ y, (c y) (u y)) x = ((c x).comp (fderiv 𝕜 u x) + (fderiv 𝕜 c x).flip (u x)) := (hc.has_fderiv_at.clm_apply hu.has_fderiv_at).fderiv end clm_comp_apply section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function If `c` is a differentiable scalar-valued function and `f` is a differentiable vector-valued function, then `λ x, c x • f x` is differentiable as well. Lemmas in this section works for function `c` taking values in the base field, as well as in a normed algebra over the base field: e.g., they work for `c : E → ℂ` and `f : E → F` provided that `F` is a complex normed vector space. -/ variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] variables {c : E → 𝕜'} {c' : E →L[𝕜] 𝕜'} theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) @[simp] lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x) lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two functions -/ variables {𝔸 𝔸' : Type*} [normed_ring 𝔸] [normed_comm_ring 𝔸'] [normed_algebra 𝕜 𝔸] [normed_algebra 𝕜 𝔸'] {a b : E → 𝔸} {a' b' : E →L[𝕜] 𝔸} {c d : E → 𝔸'} {c' d' : E →L[𝕜] 𝔸'} theorem has_strict_fderiv_at.mul' {x : E} (ha : has_strict_fderiv_at a a' x) (hb : has_strict_fderiv_at b b' x) : has_strict_fderiv_at (λ y, a y * b y) (a x • b' + a'.smul_right (b x)) x := ((continuous_linear_map.mul 𝕜 𝔸).is_bounded_bilinear_map.has_strict_fderiv_at (a x, b x)).comp x (ha.prod hb) theorem has_strict_fderiv_at.mul (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.mul' hd, ext z, apply mul_comm } theorem has_fderiv_within_at.mul' (ha : has_fderiv_within_at a a' s x) (hb : has_fderiv_within_at b b' s x) : has_fderiv_within_at (λ y, a y * b y) (a x • b' + a'.smul_right (b x)) s x := ((continuous_linear_map.mul 𝕜 𝔸).is_bounded_bilinear_map.has_fderiv_at (a x, b x)).comp_has_fderiv_within_at x (ha.prod hb) theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := by { convert hc.mul' hd, ext z, apply mul_comm } theorem has_fderiv_at.mul' (ha : has_fderiv_at a a' x) (hb : has_fderiv_at b b' x) : has_fderiv_at (λ y, a y * b y) (a x • b' + a'.smul_right (b x)) x := ((continuous_linear_map.mul 𝕜 𝔸).is_bounded_bilinear_map.has_fderiv_at (a x, b x)).comp x (ha.prod hb) theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.mul' hd, ext z, apply mul_comm } lemma differentiable_within_at.mul (ha : differentiable_within_at 𝕜 a s x) (hb : differentiable_within_at 𝕜 b s x) : differentiable_within_at 𝕜 (λ y, a y * b y) s x := (ha.has_fderiv_within_at.mul' hb.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.mul (ha : differentiable_at 𝕜 a x) (hb : differentiable_at 𝕜 b x) : differentiable_at 𝕜 (λ y, a y * b y) x := (ha.has_fderiv_at.mul' hb.has_fderiv_at).differentiable_at lemma differentiable_on.mul (ha : differentiable_on 𝕜 a s) (hb : differentiable_on 𝕜 b s) : differentiable_on 𝕜 (λ y, a y * b y) s := λx hx, (ha x hx).mul (hb x hx) @[simp] lemma differentiable.mul (ha : differentiable 𝕜 a) (hb : differentiable 𝕜 b) : differentiable 𝕜 (λ y, a y * b y) := λx, (ha x).mul (hb x) lemma differentiable_within_at.pow (ha : differentiable_within_at 𝕜 a s x) : ∀ n : ℕ, differentiable_within_at 𝕜 (λ x, a x ^ n) s x | 0 := by simp only [pow_zero, differentiable_within_at_const] | (n + 1) := by simp only [pow_succ, differentiable_within_at.pow n, ha.mul] @[simp] lemma differentiable_at.pow (ha : differentiable_at 𝕜 a x) (n : ℕ) : differentiable_at 𝕜 (λ x, a x ^ n) x := differentiable_within_at_univ.mp $ ha.differentiable_within_at.pow n lemma differentiable_on.pow (ha : differentiable_on 𝕜 a s) (n : ℕ) : differentiable_on 𝕜 (λ x, a x ^ n) s := λ x h, (ha x h).pow n @[simp] lemma differentiable.pow (ha : differentiable 𝕜 a) (n : ℕ) : differentiable 𝕜 (λ x, a x ^ n) := λx, (ha x).pow n lemma fderiv_within_mul' (hxs : unique_diff_within_at 𝕜 s x) (ha : differentiable_within_at 𝕜 a s x) (hb : differentiable_within_at 𝕜 b s x) : fderiv_within 𝕜 (λ y, a y * b y) s x = a x • fderiv_within 𝕜 b s x + (fderiv_within 𝕜 a s x).smul_right (b x) := (ha.has_fderiv_within_at.mul' hb.has_fderiv_within_at).fderiv_within hxs lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul' (ha : differentiable_at 𝕜 a x) (hb : differentiable_at 𝕜 b x) : fderiv 𝕜 (λ y, a y * b y) x = a x • fderiv 𝕜 b x + (fderiv 𝕜 a x).smul_right (b x) := (ha.has_fderiv_at.mul' hb.has_fderiv_at).fderiv lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_strict_fderiv_at.mul_const' (ha : has_strict_fderiv_at a a' x) (b : 𝔸) : has_strict_fderiv_at (λ y, a y * b) (a'.smul_right b) x := (((continuous_linear_map.mul 𝕜 𝔸).flip b).has_strict_fderiv_at).comp x ha theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝔸') : has_strict_fderiv_at (λ y, c y * d) (d • c') x := by { convert hc.mul_const' d, ext z, apply mul_comm } theorem has_fderiv_within_at.mul_const' (ha : has_fderiv_within_at a a' s x) (b : 𝔸) : has_fderiv_within_at (λ y, a y * b) (a'.smul_right b) s x := (((continuous_linear_map.mul 𝕜 𝔸).flip b).has_fderiv_at).comp_has_fderiv_within_at x ha theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝔸') : has_fderiv_within_at (λ y, c y * d) (d • c') s x := by { convert hc.mul_const' d, ext z, apply mul_comm } theorem has_fderiv_at.mul_const' (ha : has_fderiv_at a a' x) (b : 𝔸) : has_fderiv_at (λ y, a y * b) (a'.smul_right b) x := (((continuous_linear_map.mul 𝕜 𝔸).flip b).has_fderiv_at).comp x ha theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝔸') : has_fderiv_at (λ y, c y * d) (d • c') x := by { convert hc.mul_const' d, ext z, apply mul_comm } lemma differentiable_within_at.mul_const (ha : differentiable_within_at 𝕜 a s x) (b : 𝔸) : differentiable_within_at 𝕜 (λ y, a y * b) s x := (ha.has_fderiv_within_at.mul_const' b).differentiable_within_at lemma differentiable_at.mul_const (ha : differentiable_at 𝕜 a x) (b : 𝔸) : differentiable_at 𝕜 (λ y, a y * b) x := (ha.has_fderiv_at.mul_const' b).differentiable_at lemma differentiable_on.mul_const (ha : differentiable_on 𝕜 a s) (b : 𝔸) : differentiable_on 𝕜 (λ y, a y * b) s := λx hx, (ha x hx).mul_const b lemma differentiable.mul_const (ha : differentiable 𝕜 a) (b : 𝔸) : differentiable 𝕜 (λ y, a y * b) := λx, (ha x).mul_const b lemma fderiv_within_mul_const' (hxs : unique_diff_within_at 𝕜 s x) (ha : differentiable_within_at 𝕜 a s x) (b : 𝔸) : fderiv_within 𝕜 (λ y, a y * b) s x = (fderiv_within 𝕜 a s x).smul_right b := (ha.has_fderiv_within_at.mul_const' b).fderiv_within hxs lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝔸') : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const' (ha : differentiable_at 𝕜 a x) (b : 𝔸) : fderiv 𝕜 (λ y, a y * b) x = (fderiv 𝕜 a x).smul_right b := (ha.has_fderiv_at.mul_const' b).fderiv lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝔸') : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_strict_fderiv_at.const_mul (ha : has_strict_fderiv_at a a' x) (b : 𝔸) : has_strict_fderiv_at (λ y, b * a y) (b • a') x := (((continuous_linear_map.mul 𝕜 𝔸) b).has_strict_fderiv_at).comp x ha theorem has_fderiv_within_at.const_mul (ha : has_fderiv_within_at a a' s x) (b : 𝔸) : has_fderiv_within_at (λ y, b * a y) (b • a') s x := (((continuous_linear_map.mul 𝕜 𝔸) b).has_fderiv_at).comp_has_fderiv_within_at x ha theorem has_fderiv_at.const_mul (ha : has_fderiv_at a a' x) (b : 𝔸) : has_fderiv_at (λ y, b * a y) (b • a') x := (((continuous_linear_map.mul 𝕜 𝔸) b).has_fderiv_at).comp x ha lemma differentiable_within_at.const_mul (ha : differentiable_within_at 𝕜 a s x) (b : 𝔸) : differentiable_within_at 𝕜 (λ y, b * a y) s x := (ha.has_fderiv_within_at.const_mul b).differentiable_within_at lemma differentiable_at.const_mul (ha : differentiable_at 𝕜 a x) (b : 𝔸) : differentiable_at 𝕜 (λ y, b * a y) x := (ha.has_fderiv_at.const_mul b).differentiable_at lemma differentiable_on.const_mul (ha : differentiable_on 𝕜 a s) (b : 𝔸) : differentiable_on 𝕜 (λ y, b * a y) s := λx hx, (ha x hx).const_mul b lemma differentiable.const_mul (ha : differentiable 𝕜 a) (b : 𝔸) : differentiable 𝕜 (λ y, b * a y) := λx, (ha x).const_mul b lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (ha : differentiable_within_at 𝕜 a s x) (b : 𝔸) : fderiv_within 𝕜 (λ y, b * a y) s x = b • fderiv_within 𝕜 a s x := (ha.has_fderiv_within_at.const_mul b).fderiv_within hxs lemma fderiv_const_mul (ha : differentiable_at 𝕜 a x) (b : 𝔸) : fderiv 𝕜 (λ y, b * a y) x = b • fderiv 𝕜 a x := (ha.has_fderiv_at.const_mul b).fderiv end mul section algebra_inverse variables {R : Type*} [normed_ring R] [normed_algebra 𝕜 R] [complete_space R] open normed_ring continuous_linear_map ring /-- At an invertible element `x` of a normed algebra `R`, the Fréchet derivative of the inversion operation is the linear map `λ t, - x⁻¹ * t * x⁻¹`. -/ lemma has_fderiv_at_ring_inverse (x : Rˣ) : has_fderiv_at ring.inverse (-mul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹) x := begin have h_is_o : (λ (t : R), inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) =o[𝓝 0] (λ (t : R), t), { refine (inverse_add_norm_diff_second_order x).trans_is_o ((is_o_norm_norm).mp _), simp only [norm_pow, norm_norm], have h12 : 1 < 2 := by norm_num, convert (asymptotics.is_o_pow_pow h12).comp_tendsto tendsto_norm_zero, ext, simp }, have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0), { refine tendsto_zero_iff_norm_tendsto_zero.mpr _, exact tendsto_iff_norm_tendsto_zero.mp tendsto_id }, simp only [has_fderiv_at, has_fderiv_at_filter], convert h_is_o.comp_tendsto h_lim, ext y, simp only [coe_comp', function.comp_app, mul_left_right_apply, neg_apply, inverse_unit x, units.inv_mul, add_sub_cancel'_right, mul_sub, sub_mul, one_mul, sub_neg_eq_add] end lemma differentiable_at_inverse (x : Rˣ) : differentiable_at 𝕜 (@ring.inverse R _) x := (has_fderiv_at_ring_inverse x).differentiable_at lemma fderiv_inverse (x : Rˣ) : fderiv 𝕜 (@ring.inverse R _) x = - mul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹ := (has_fderiv_at_ring_inverse x).fderiv end algebra_inverse namespace continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_strict_fderiv_at protected lemma has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := iso.to_continuous_linear_map.has_fderiv_within_at protected lemma has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := iso.to_continuous_linear_map.fderiv_within hxs protected lemma differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := begin refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩, have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x := iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H, rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this, end lemma comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ, iso.comp_differentiable_within_at_iff] lemma comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := begin rw [differentiable_on, differentiable_on], simp only [iso.comp_differentiable_within_at_iff], end lemma comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := begin rw [← differentiable_on_univ, ← differentiable_on_univ], exact iso.comp_differentiable_on_iff end lemma comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := begin refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩, have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl }, have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'), by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.id_comp], rw [A, B], exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H end lemma comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := begin refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩, convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm end lemma comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := by simp_rw [← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp] lemma comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := by simp_rw [← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := begin by_cases h : differentiable_within_at 𝕜 f s x, { rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] }, { have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x, from mt iso.comp_differentiable_within_at_iff.1 h, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this, continuous_linear_map.comp_zero] } end lemma comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := begin rw [← fderiv_within_univ, ← fderiv_within_univ], exact iso.comp_fderiv_within unique_diff_within_at_univ, end end continuous_linear_equiv namespace linear_isometry_equiv /-! ### Differentiability of linear isometry equivs, and invariance of differentiability -/ variable (iso : E ≃ₗᵢ[𝕜] F) protected lemma has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := (iso : E ≃L[𝕜] F).has_strict_fderiv_at protected lemma has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := (iso : E ≃L[𝕜] F).has_fderiv_within_at protected lemma has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := (iso : E ≃L[𝕜] F).has_fderiv_at protected lemma differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := (iso : E ≃L[𝕜] F).fderiv_within hxs protected lemma differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := (iso : E ≃L[𝕜] F).comp_differentiable_within_at_iff lemma comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := (iso : E ≃L[𝕜] F).comp_differentiable_at_iff lemma comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := (iso : E ≃L[𝕜] F).comp_differentiable_on_iff lemma comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := (iso : E ≃L[𝕜] F).comp_differentiable_iff lemma comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := (iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff lemma comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := (iso : E ≃L[𝕜] F).comp_has_strict_fderiv_at_iff lemma comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := (iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff lemma comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := (iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff' lemma comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := (iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff' lemma comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := (iso : E ≃L[𝕜] F).comp_fderiv_within hxs lemma comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := (iso : E ≃L[𝕜] F).comp_fderiv end linear_isometry_equiv /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin replace hg := hg.prod_map' hg, replace hfg := hfg.prod_mk_nhds hfg, have : (λ p : F × F, g p.1 - g p.2 - f'.symm (p.1 - p.2)) =O[𝓝 (a, a)] (λ p : F × F, f' (g p.1 - g p.2) - (p.1 - p.2)), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p ⟨hp1, hp2⟩, simp [hp1, hp2] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p ⟨hp1, hp2⟩, simp only [(∘), hp1, hp2] } end /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin have : (λ x : F, g x - g a - f'.symm (x - a)) =O[𝓝 a] (λ x : F, f' (g x - g a) - (x - a)), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p hp, simp [hp, hfg.self_of_nhds] }, { refine ((hf.is_O_sub_rev f'.antilipschitz).comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p hp, simp only [(∘), hp, hfg.self_of_nhds] } end /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` in the sense of strict differentiability at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_strict_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_strict_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_strict_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) lemma has_fderiv_within_at.eventually_ne (h : has_fderiv_within_at f f' s x) (hf' : ∃ C, ∀ z, ‖z‖ ≤ C * ‖f' z‖) : ∀ᶠ z in 𝓝[s \ {x}] x, f z ≠ f x := begin rw [nhds_within, diff_eq, ← inf_principal, ← inf_assoc, eventually_inf_principal], have A : (λ z, z - x) =O[𝓝[s] x] (λ z, f' (z - x)) := (is_O_iff.2 $ hf'.imp $ λ C hC, eventually_of_forall $ λ z, hC _), have : (λ z, f z - f x) ~[𝓝[s] x] (λ z, f' (z - x)) := h.trans_is_O A, simpa [not_imp_not, sub_eq_zero] using (A.trans this.is_O_symm).eq_zero_imp end lemma has_fderiv_at.eventually_ne (h : has_fderiv_at f f' x) (hf' : ∃ C, ∀ z, ‖z‖ ≤ C * ‖f' z‖) : ∀ᶠ z in 𝓝[≠] x, f z ≠ f x := by simpa only [compl_eq_univ_diff] using (has_fderiv_within_at_univ.2 h).eventually_ne hf' end section /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] variables {F : Type*} [normed_add_comm_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ‖x' - x‖⁻¹ * ‖f x' - f x - f' (x' - x)‖) L (𝓝 0) ↔ tendsto (λ x' : E, ‖x' - x‖⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ‖x' - x‖⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) : maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) := begin rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : dense_range f') : unique_diff_within_at 𝕜 (f '' s) (f x) := begin refine ⟨h'.dense_of_maps_to f'.continuous hs.1 _, h.continuous_within_at.mem_closure_image hs.2⟩, show submodule.span 𝕜 (tangent_cone_at 𝕜 s x) ≤ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))).comap f', rw [submodule.span_le], exact h.maps_to_tangent_cone.mono (subset.refl _) submodule.subset_span end lemma unique_diff_on.image {f' : E → E →L[𝕜] F} (hs : unique_diff_on 𝕜 s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hd : ∀ x ∈ s, dense_range (f' x)) : unique_diff_on 𝕜 (f '' s) := ball_image_iff.2 $ λ x hx, (hf' x hx).unique_diff_within_at (hs x hx) (hd x hx) lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := h.unique_diff_within_at hs e'.surjective.dense_range lemma continuous_linear_equiv.unique_diff_on_image (e : E ≃L[𝕜] F) (h : unique_diff_on 𝕜 s) : unique_diff_on 𝕜 (e '' s) := h.image (λ x _, e.has_fderiv_within_at) (λ x hx, e.surjective.dense_range) @[simp] lemma continuous_linear_equiv.unique_diff_on_image_iff (e : E ≃L[𝕜] F) : unique_diff_on 𝕜 (e '' s) ↔ unique_diff_on 𝕜 s := ⟨λ h, e.symm_image_image s ▸ e.symm.unique_diff_on_image h, e.unique_diff_on_image⟩ @[simp] lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) : unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s := by rw [← e.image_symm_eq_preimage, e.symm.unique_diff_on_image_iff] end tangent_cone section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is differentiable over `ℂ`, then it is differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜 : Type*) [nontrivially_normed_field 𝕜] variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [normed_space 𝕜' E] variables [is_scalar_tower 𝕜 𝕜' E] variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] [normed_space 𝕜' F] variables [is_scalar_tower 𝕜 𝕜' F] variables {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_at_filter.restrict_scalars {L} (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter f (f'.restrict_scalars 𝕜) x L := h lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) : has_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) : differentiable_at 𝕜 f x := (h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) : differentiable_within_at 𝕜 f s x := (h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) : differentiable_on 𝕜 f s := λx hx, (h x hx).restrict_scalars 𝕜 lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) : differentiable 𝕜 f := λx, (h x).restrict_scalars 𝕜 lemma has_fderiv_within_at_of_restrict_scalars {g' : E →L[𝕜] F} (h : has_fderiv_within_at f g' s x) (H : f'.restrict_scalars 𝕜 = g') : has_fderiv_within_at f f' s x := by { rw ← H at h, exact h } lemma has_fderiv_at_of_restrict_scalars {g' : E →L[𝕜] F} (h : has_fderiv_at f g' x) (H : f'.restrict_scalars 𝕜 = g') : has_fderiv_at f f' x := by { rw ← H at h, exact h } lemma differentiable_at.fderiv_restrict_scalars (h : differentiable_at 𝕜' f x) : fderiv 𝕜 f x = (fderiv 𝕜' f x).restrict_scalars 𝕜 := (h.has_fderiv_at.restrict_scalars 𝕜).fderiv lemma differentiable_within_at_iff_restrict_scalars (hf : differentiable_within_at 𝕜 f s x) (hs : unique_diff_within_at 𝕜 s x) : differentiable_within_at 𝕜' f s x ↔ ∃ (g' : E →L[𝕜'] F), g'.restrict_scalars 𝕜 = fderiv_within 𝕜 f s x := begin split, { rintros ⟨g', hg'⟩, exact ⟨g', hs.eq (hg'.restrict_scalars 𝕜) hf.has_fderiv_within_at⟩, }, { rintros ⟨f', hf'⟩, exact ⟨f', has_fderiv_within_at_of_restrict_scalars 𝕜 hf.has_fderiv_within_at hf'⟩, }, end lemma differentiable_at_iff_restrict_scalars (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜' f x ↔ ∃ (g' : E →L[𝕜'] F), g'.restrict_scalars 𝕜 = fderiv 𝕜 f x := begin rw [← differentiable_within_at_univ, ← fderiv_within_univ], exact differentiable_within_at_iff_restrict_scalars 𝕜 hf.differentiable_within_at unique_diff_within_at_univ, end end restrict_scalars /-! ### Support of derivatives -/ section support open function variables (𝕜 : Type*) {E F : Type*} [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] [normed_add_comm_group F] [normed_space 𝕜 F] {f : E → F} lemma support_fderiv_subset : support (fderiv 𝕜 f) ⊆ tsupport f := begin intros x, rw [← not_imp_not], intro h2x, rw [not_mem_tsupport_iff_eventually_eq] at h2x, exact nmem_support.mpr (h2x.fderiv_eq.trans $ fderiv_const_apply 0), end lemma has_compact_support.fderiv (hf : has_compact_support f) : has_compact_support (fderiv 𝕜 f) := hf.mono' $ support_fderiv_subset 𝕜 end support
3a8e52a11977b91b7e3bbc2386ec7347ef95ec84
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/jordan_holder.lean
ab622f412faaef6114b3ba70a42564f7575cd01f
[ "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
30,653
lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import order.lattice import data.list.sort import logic.equiv.fin import logic.equiv.functor import data.fintype.card /-! # Jordan-Hölder Theorem This file proves the Jordan Hölder theorem for a `jordan_holder_lattice`, a class also defined in this file. Examples of `jordan_holder_lattice` include `subgroup G` if `G` is a group, and `submodule R M` if `M` is an `R`-module. Using this approach the theorem need not be proved seperately for both groups and modules, the proof in this file can be applied to both. ## Main definitions The main definitions in this file are `jordan_holder_lattice` and `composition_series`, and the relation `equivalent` on `composition_series` A `jordan_holder_lattice` is the class for which the Jordan Hölder theorem is proved. A Jordan Hölder lattice is a lattice equipped with a notion of maximality, `is_maximal`, and a notion of isomorphism of pairs `iso`. In the example of subgroups of a group, `is_maximal H K` means that `H` is a maximal normal subgroup of `K`, and `iso (H₁, K₁) (H₂, K₂)` means that the quotient `H₁ / K₁` is isomorphic to the quotient `H₂ / K₂`. `iso` must be symmetric and transitive and must satisfy the second isomorphism theorem `iso (H, H ⊔ K) (H ⊓ K, K)`. A `composition_series X` is a finite nonempty series of elements of the lattice `X` such that each element is maximal inside the next. The length of a `composition_series X` is one less than the number of elements in the series. Note that there is no stipulation that a series start from the bottom of the lattice and finish at the top. For a composition series `s`, `s.top` is the largest element of the series, and `s.bot` is the least element. Two `composition_series X`, `s₁` and `s₂` are equivalent if there is a bijection `e : fin s₁.length ≃ fin s₂.length` such that for any `i`, `iso (s₁ i, s₁ i.succ) (s₂ (e i), s₂ (e i.succ))` ## Main theorems The main theorem is `composition_series.jordan_holder`, which says that if two composition series have the same least element and the same largest element, then they are `equivalent`. ## TODO Provide instances of `jordan_holder_lattice` for both submodules and subgroups, and potentially for modular lattices. It is not entirely clear how this should be done. Possibly there should be no global instances of `jordan_holder_lattice`, and the instances should only be defined locally in order to prove the Jordan-Hölder theorem for modules/groups and the API should be transferred because many of the theorems in this file will have stronger versions for modules. There will also need to be an API for mapping composition series across homomorphisms. It is also probably possible to provide an instance of `jordan_holder_lattice` for any `modular_lattice`, and in this case the Jordan-Hölder theorem will say that there is a well defined notion of length of a modular lattice. However an instance of `jordan_holder_lattice` for a modular lattice will not be able to contain the correct notion of isomorphism for modules, so a separate instance for modules will still be required and this will clash with the instance for modular lattices, and so at least one of these instances should not be a global instance. -/ universe u open set /-- A `jordan_holder_lattice` is the class for which the Jordan Hölder theorem is proved. A Jordan Hölder lattice is a lattice equipped with a notion of maximality, `is_maximal`, and a notion of isomorphism of pairs `iso`. In the example of subgroups of a group, `is_maximal H K` means that `H` is a maximal normal subgroup of `K`, and `iso (H₁, K₁) (H₂, K₂)` means that the quotient `H₁ / K₁` is isomorphic to the quotient `H₂ / K₂`. `iso` must be symmetric and transitive and must satisfy the second isomorphism theorem `iso (H, H ⊔ K) (H ⊓ K, K)`. Examples include `subgroup G` if `G` is a group, and `submodule R M` if `M` is an `R`-module. -/ class jordan_holder_lattice (X : Type u) [lattice X] := (is_maximal : X → X → Prop) (lt_of_is_maximal : ∀ {x y}, is_maximal x y → x < y) (sup_eq_of_is_maximal : ∀ {x y z}, is_maximal x z → is_maximal y z → x ≠ y → x ⊔ y = z) (is_maximal_inf_left_of_is_maximal_sup : ∀ {x y}, is_maximal x (x ⊔ y) → is_maximal y (x ⊔ y) → is_maximal (x ⊓ y) x) (iso : (X × X) → (X × X) → Prop) (iso_symm : ∀ {x y}, iso x y → iso y x) (iso_trans : ∀ {x y z}, iso x y → iso y z → iso x z) (second_iso : ∀ {x y}, is_maximal x (x ⊔ y) → iso (x, x ⊔ y) (x ⊓ y, y)) namespace jordan_holder_lattice variables {X : Type u} [lattice X] [jordan_holder_lattice X] lemma is_maximal_inf_right_of_is_maximal_sup {x y : X} (hxz : is_maximal x (x ⊔ y)) (hyz : is_maximal y (x ⊔ y)) : is_maximal (x ⊓ y) y := begin rw [inf_comm], rw [sup_comm] at hxz hyz, exact is_maximal_inf_left_of_is_maximal_sup hyz hxz end lemma is_maximal_of_eq_inf (x b : X) {a y : X} (ha : x ⊓ y = a) (hxy : x ≠ y) (hxb : is_maximal x b) (hyb : is_maximal y b) : is_maximal a y := begin have hb : x ⊔ y = b, from sup_eq_of_is_maximal hxb hyb hxy, substs a b, exact is_maximal_inf_right_of_is_maximal_sup hxb hyb end lemma second_iso_of_eq {x y a b : X} (hm : is_maximal x a) (ha : x ⊔ y = a) (hb : x ⊓ y = b) : iso (x, a) (b, y) := by substs a b; exact second_iso hm lemma is_maximal.iso_refl {x y : X} (h : is_maximal x y) : iso (x, y) (x, y) := second_iso_of_eq h (sup_eq_right.2 (le_of_lt (lt_of_is_maximal h))) (inf_eq_left.2 (le_of_lt (lt_of_is_maximal h))) end jordan_holder_lattice open jordan_holder_lattice attribute [symm] iso_symm attribute [trans] iso_trans /-- A `composition_series X` is a finite nonempty series of elements of a `jordan_holder_lattice` such that each element is maximal inside the next. The length of a `composition_series X` is one less than the number of elements in the series. Note that there is no stipulation that a series start from the bottom of the lattice and finish at the top. For a composition series `s`, `s.top` is the largest element of the series, and `s.bot` is the least element. -/ structure composition_series (X : Type u) [lattice X] [jordan_holder_lattice X] : Type u := (length : ℕ) (series : fin (length + 1) → X) (step' : ∀ i : fin length, is_maximal (series i.cast_succ) (series i.succ)) namespace composition_series variables {X : Type u} [lattice X] [jordan_holder_lattice X] instance : has_coe_to_fun (composition_series X) (λ x, fin (x.length + 1) → X) := { coe := composition_series.series } instance [inhabited X] : inhabited (composition_series X) := ⟨{ length := 0, series := default, step' := λ x, x.elim0 }⟩ variables {X} lemma step (s : composition_series X) : ∀ i : fin s.length, is_maximal (s i.cast_succ) (s i.succ) := s.step' @[simp] lemma coe_fn_mk (length : ℕ) (series step) : (@composition_series.mk X _ _ length series step : fin length.succ → X) = series := rfl theorem lt_succ (s : composition_series X) (i : fin s.length) : s i.cast_succ < s i.succ := lt_of_is_maximal (s.step _) protected theorem strict_mono (s : composition_series X) : strict_mono s := fin.strict_mono_iff_lt_succ.2 s.lt_succ protected theorem injective (s : composition_series X) : function.injective s := s.strict_mono.injective @[simp] protected theorem inj (s : composition_series X) {i j : fin s.length.succ} : s i = s j ↔ i = j := s.injective.eq_iff instance : has_mem X (composition_series X) := ⟨λ x s, x ∈ set.range s⟩ lemma mem_def {x : X} {s : composition_series X} : x ∈ s ↔ x ∈ set.range s := iff.rfl lemma total {s : composition_series X} {x y : X} (hx : x ∈ s) (hy : y ∈ s) : x ≤ y ∨ y ≤ x := begin rcases set.mem_range.1 hx with ⟨i, rfl⟩, rcases set.mem_range.1 hy with ⟨j, rfl⟩, rw [s.strict_mono.le_iff_le, s.strict_mono.le_iff_le], exact le_total i j end /-- The ordered `list X` of elements of a `composition_series X`. -/ def to_list (s : composition_series X) : list X := list.of_fn s /-- Two `composition_series` are equal if they are the same length and have the same `i`th element for every `i` -/ lemma ext_fun {s₁ s₂ : composition_series X} (hl : s₁.length = s₂.length) (h : ∀ i, s₁ i = s₂ (fin.cast (congr_arg nat.succ hl) i)) : s₁ = s₂ := begin cases s₁, cases s₂, dsimp at *, subst hl, simpa [function.funext_iff] using h end @[simp] lemma length_to_list (s : composition_series X) : s.to_list.length = s.length + 1 := by rw [to_list, list.length_of_fn] lemma to_list_ne_nil (s : composition_series X) : s.to_list ≠ [] := by rw [← list.length_pos_iff_ne_nil, length_to_list]; exact nat.succ_pos _ lemma to_list_injective : function.injective (@composition_series.to_list X _ _) := λ s₁ s₂ (h : list.of_fn s₁ = list.of_fn s₂), have h₁ : s₁.length = s₂.length, from nat.succ_injective ((list.length_of_fn s₁).symm.trans $ (congr_arg list.length h).trans $ list.length_of_fn s₂), have h₂ : ∀ i : fin s₁.length.succ, (s₁ i) = s₂ (fin.cast (congr_arg nat.succ h₁) i), begin assume i, rw [← list.nth_le_of_fn s₁ i, ← list.nth_le_of_fn s₂], simp [h] end, begin cases s₁, cases s₂, dsimp at *, subst h₁, simp only [heq_iff_eq, eq_self_iff_true, true_and], simp only [fin.cast_refl] at h₂, exact funext h₂ end lemma chain'_to_list (s : composition_series X) : list.chain' is_maximal s.to_list := list.chain'_iff_nth_le.2 begin assume i hi, simp only [to_list, list.nth_le_of_fn'], rw [length_to_list] at hi, exact s.step ⟨i, hi⟩ end lemma to_list_sorted (s : composition_series X) : s.to_list.sorted (<) := list.pairwise_iff_nth_le.2 (λ i j hi hij, begin dsimp [to_list], rw [list.nth_le_of_fn', list.nth_le_of_fn'], exact s.strict_mono hij end) lemma to_list_nodup (s : composition_series X) : s.to_list.nodup := s.to_list_sorted.nodup @[simp] lemma mem_to_list {s : composition_series X} {x : X} : x ∈ s.to_list ↔ x ∈ s := by rw [to_list, list.mem_of_fn, mem_def] /-- Make a `composition_series X` from the ordered list of its elements. -/ def of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : composition_series X := { length := l.length - 1, series := λ i, l.nth_le i begin conv_rhs { rw ← tsub_add_cancel_of_le (nat.succ_le_of_lt (list.length_pos_of_ne_nil hl)) }, exact i.2 end, step' := λ ⟨i, hi⟩, list.chain'_iff_nth_le.1 hc i hi } lemma length_of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : (of_list l hl hc).length = l.length - 1 := rfl lemma of_list_to_list (s : composition_series X) : of_list s.to_list s.to_list_ne_nil s.chain'_to_list = s := begin refine ext_fun _ _, { rw [length_of_list, length_to_list, nat.succ_sub_one] }, { rintros ⟨i, hi⟩, dsimp [of_list, to_list], rw [list.nth_le_of_fn'] } end @[simp] lemma of_list_to_list' (s : composition_series X) : of_list s.to_list s.to_list_ne_nil s.chain'_to_list = s := of_list_to_list s @[simp] lemma to_list_of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : to_list (of_list l hl hc) = l := begin refine list.ext_le _ _, { rw [length_to_list, length_of_list, tsub_add_cancel_of_le (nat.succ_le_of_lt $ list.length_pos_of_ne_nil hl)] }, { assume i hi hi', dsimp [of_list, to_list], rw [list.nth_le_of_fn'], refl } end /-- Two `composition_series` are equal if they have the same elements. See also `ext_fun`. -/ @[ext] lemma ext {s₁ s₂ : composition_series X} (h : ∀ x, x ∈ s₁ ↔ x ∈ s₂) : s₁ = s₂ := to_list_injective $ list.eq_of_perm_of_sorted (by classical; exact list.perm_of_nodup_nodup_to_finset_eq s₁.to_list_nodup s₂.to_list_nodup (finset.ext $ by simp *)) s₁.to_list_sorted s₂.to_list_sorted /-- The largest element of a `composition_series` -/ def top (s : composition_series X) : X := s (fin.last _) lemma top_mem (s : composition_series X) : s.top ∈ s := mem_def.2 (set.mem_range.2 ⟨fin.last _, rfl⟩) @[simp] lemma le_top {s : composition_series X} (i : fin (s.length + 1)) : s i ≤ s.top := s.strict_mono.monotone (fin.le_last _) lemma le_top_of_mem {s : composition_series X} {x : X} (hx : x ∈ s) : x ≤ s.top := let ⟨i, hi⟩ := set.mem_range.2 hx in hi ▸ le_top _ /-- The smallest element of a `composition_series` -/ def bot (s : composition_series X) : X := s 0 lemma bot_mem (s : composition_series X) : s.bot ∈ s := mem_def.2 (set.mem_range.2 ⟨0, rfl⟩) @[simp] lemma bot_le {s : composition_series X} (i : fin (s.length + 1)) : s.bot ≤ s i := s.strict_mono.monotone (fin.zero_le _) lemma bot_le_of_mem {s : composition_series X} {x : X} (hx : x ∈ s) : s.bot ≤ x := let ⟨i, hi⟩ := set.mem_range.2 hx in hi ▸ bot_le _ lemma length_pos_of_mem_ne {s : composition_series X} {x y : X} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) : 0 < s.length := let ⟨i, hi⟩ := hx, ⟨j, hj⟩ := hy in have hij : i ≠ j, from mt s.inj.2 $ λ h, hxy (hi ▸ hj ▸ h), hij.lt_or_lt.elim (λ hij, (lt_of_le_of_lt (zero_le i) (lt_of_lt_of_le hij (nat.le_of_lt_succ j.2)))) (λ hji, (lt_of_le_of_lt (zero_le j) (lt_of_lt_of_le hji (nat.le_of_lt_succ i.2)))) lemma forall_mem_eq_of_length_eq_zero {s : composition_series X} (hs : s.length = 0) {x y} (hx : x ∈ s) (hy : y ∈ s) : x = y := by_contradiction (λ hxy, pos_iff_ne_zero.1 (length_pos_of_mem_ne hx hy hxy) hs) /-- Remove the largest element from a `composition_series`. If the series `s` has length zero, then `s.erase_top = s` -/ @[simps] def erase_top (s : composition_series X) : composition_series X := { length := s.length - 1, series := λ i, s ⟨i, lt_of_lt_of_le i.2 (nat.succ_le_succ tsub_le_self)⟩, step' := λ i, begin have := s.step ⟨i, lt_of_lt_of_le i.2 tsub_le_self⟩, cases i, exact this end } lemma top_erase_top (s : composition_series X) : s.erase_top.top = s ⟨s.length - 1, lt_of_le_of_lt tsub_le_self (nat.lt_succ_self _)⟩ := show s _ = s _, from congr_arg s begin ext, simp only [erase_top_length, fin.coe_last, fin.coe_cast_succ, fin.coe_of_nat_eq_mod, fin.coe_mk, coe_coe] end lemma erase_top_top_le (s : composition_series X) : s.erase_top.top ≤ s.top := by simp [erase_top, top, s.strict_mono.le_iff_le, fin.le_iff_coe_le_coe, tsub_le_self] @[simp] lemma bot_erase_top (s : composition_series X) : s.erase_top.bot = s.bot := rfl lemma mem_erase_top_of_ne_of_mem {s : composition_series X} {x : X} (hx : x ≠ s.top) (hxs : x ∈ s) : x ∈ s.erase_top := begin rcases hxs with ⟨i, rfl⟩, have hi : (i : ℕ) < (s.length - 1).succ, { conv_rhs { rw [← nat.succ_sub (length_pos_of_mem_ne ⟨i, rfl⟩ s.top_mem hx), nat.succ_sub_one] }, exact lt_of_le_of_ne (nat.le_of_lt_succ i.2) (by simpa [top, s.inj, fin.ext_iff] using hx) }, refine ⟨i.cast_succ, _⟩, simp [fin.ext_iff, nat.mod_eq_of_lt hi] end lemma mem_erase_top {s : composition_series X} {x : X} (h : 0 < s.length) : x ∈ s.erase_top ↔ x ≠ s.top ∧ x ∈ s := begin simp only [mem_def], dsimp only [erase_top, coe_fn_mk], split, { rintros ⟨i, rfl⟩, have hi : (i : ℕ) < s.length, { conv_rhs { rw [← nat.succ_sub_one s.length, nat.succ_sub h] }, exact i.2 }, simp [top, fin.ext_iff, (ne_of_lt hi)] }, { intro h, exact mem_erase_top_of_ne_of_mem h.1 h.2 } end lemma lt_top_of_mem_erase_top {s : composition_series X} {x : X} (h : 0 < s.length) (hx : x ∈ s.erase_top) : x < s.top := lt_of_le_of_ne (le_top_of_mem ((mem_erase_top h).1 hx).2) ((mem_erase_top h).1 hx).1 lemma is_maximal_erase_top_top {s : composition_series X} (h : 0 < s.length) : is_maximal s.erase_top.top s.top := have s.length - 1 + 1 = s.length, by conv_rhs { rw [← nat.succ_sub_one s.length] }; rw nat.succ_sub h, begin rw [top_erase_top, top], convert s.step ⟨s.length - 1, nat.sub_lt h zero_lt_one⟩; ext; simp [this] end lemma append_cast_add_aux {s₁ s₂ : composition_series X} (i : fin s₁.length) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.cast_add s₂.length i).cast_succ = s₁ i.cast_succ := by { cases i, simp [fin.append, *] } lemma append_succ_cast_add_aux {s₁ s₂ : composition_series X} (i : fin s₁.length) (h : s₁ (fin.last _) = s₂ 0) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.cast_add s₂.length i).succ = s₁ i.succ := begin cases i with i hi, simp only [fin.append, hi, fin.succ_mk, function.comp_app, fin.cast_succ_mk, fin.coe_mk, fin.cast_add_mk], split_ifs, { refl }, { have : i + 1 = s₁.length, from le_antisymm hi (le_of_not_gt h_1), calc s₂ ⟨i + 1 - s₁.length, by simp [this]⟩ = s₂ 0 : congr_arg s₂ (by simp [fin.ext_iff, this]) ... = s₁ (fin.last _) : h.symm ... = _ : congr_arg s₁ (by simp [fin.ext_iff, this]) } end lemma append_nat_add_aux {s₁ s₂ : composition_series X} (i : fin s₂.length) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.nat_add s₁.length i).cast_succ = s₂ i.cast_succ := begin cases i, simp only [fin.append, nat.not_lt_zero, fin.nat_add_mk, add_lt_iff_neg_left, add_tsub_cancel_left, dif_neg, fin.cast_succ_mk, not_false_iff, fin.coe_mk] end lemma append_succ_nat_add_aux {s₁ s₂ : composition_series X} (i : fin s₂.length) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.nat_add s₁.length i).succ = s₂ i.succ := begin cases i with i hi, simp only [fin.append, add_assoc, nat.not_lt_zero, fin.nat_add_mk, add_lt_iff_neg_left, add_tsub_cancel_left, fin.succ_mk, dif_neg, not_false_iff, fin.coe_mk] end /-- Append two composition series `s₁` and `s₂` such that the least element of `s₁` is the maximum element of `s₂`. -/ @[simps length] def append (s₁ s₂ : composition_series X) (h : s₁.top = s₂.bot) : composition_series X := { length := s₁.length + s₂.length, series := fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂, step' := λ i, begin refine fin.add_cases _ _ i, { intro i, rw [append_succ_cast_add_aux _ h, append_cast_add_aux], exact s₁.step i }, { intro i, rw [append_nat_add_aux, append_succ_nat_add_aux], exact s₂.step i } end } @[simp] lemma append_cast_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₁.length) : append s₁ s₂ h (fin.cast_add s₂.length i).cast_succ = s₁ i.cast_succ := append_cast_add_aux i @[simp] lemma append_succ_cast_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₁.length) : append s₁ s₂ h (fin.cast_add s₂.length i).succ = s₁ i.succ := append_succ_cast_add_aux i h @[simp] lemma append_nat_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₂.length) : append s₁ s₂ h (fin.nat_add s₁.length i).cast_succ = s₂ i.cast_succ := append_nat_add_aux i @[simp] lemma append_succ_nat_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₂.length) : append s₁ s₂ h (fin.nat_add s₁.length i).succ = s₂ i.succ := append_succ_nat_add_aux i /-- Add an element to the top of a `composition_series` -/ @[simps length] def snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : composition_series X := { length := s.length + 1, series := fin.snoc s x, step' := λ i, begin refine fin.last_cases _ _ i, { rwa [fin.snoc_cast_succ, fin.succ_last, fin.snoc_last, ← top] }, { intro i, rw [fin.snoc_cast_succ, ← fin.cast_succ_fin_succ, fin.snoc_cast_succ], exact s.step _ } end } @[simp] lemma top_snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : (snoc s x hsat).top = x := fin.snoc_last _ _ @[simp] lemma snoc_last (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : snoc s x hsat (fin.last (s.length + 1)) = x := fin.snoc_last _ _ @[simp] lemma snoc_cast_succ (s : composition_series X) (x : X) (hsat : is_maximal s.top x) (i : fin (s.length + 1)) : snoc s x hsat (i.cast_succ) = s i := fin.snoc_cast_succ _ _ _ @[simp] lemma bot_snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : (snoc s x hsat).bot = s.bot := by rw [bot, bot, ← fin.cast_succ_zero, snoc_cast_succ] lemma mem_snoc {s : composition_series X} {x y: X} {hsat : is_maximal s.top x} : y ∈ snoc s x hsat ↔ y ∈ s ∨ y = x := begin simp only [snoc, mem_def], split, { rintros ⟨i, rfl⟩, refine fin.last_cases _ (λ i, _) i, { right, simp }, { left, simp } }, { intro h, rcases h with ⟨i, rfl⟩ | rfl, { use i.cast_succ, simp }, { use (fin.last _), simp } } end lemma eq_snoc_erase_top {s : composition_series X} (h : 0 < s.length) : s = snoc (erase_top s) s.top (is_maximal_erase_top_top h) := begin ext x, simp [mem_snoc, mem_erase_top h], by_cases h : x = s.top; simp [*, s.top_mem] end @[simp] lemma snoc_erase_top_top {s : composition_series X} (h : is_maximal s.erase_top.top s.top) : s.erase_top.snoc s.top h = s := have h : 0 < s.length, from nat.pos_of_ne_zero begin assume hs, refine ne_of_gt (lt_of_is_maximal h) _, simp [top, fin.ext_iff, hs] end, (eq_snoc_erase_top h).symm /-- Two `composition_series X`, `s₁` and `s₂` are equivalent if there is a bijection `e : fin s₁.length ≃ fin s₂.length` such that for any `i`, `iso (s₁ i) (s₁ i.succ) (s₂ (e i), s₂ (e i.succ))` -/ def equivalent (s₁ s₂ : composition_series X) : Prop := ∃ f : fin s₁.length ≃ fin s₂.length, ∀ i : fin s₁.length, iso (s₁ i.cast_succ, s₁ i.succ) (s₂ (f i).cast_succ, s₂ (f i).succ) namespace equivalent @[refl] lemma refl (s : composition_series X) : equivalent s s := ⟨equiv.refl _, λ _, (s.step _).iso_refl⟩ @[symm] lemma symm {s₁ s₂ : composition_series X} (h : equivalent s₁ s₂) : equivalent s₂ s₁ := ⟨h.some.symm, λ i, iso_symm (by simpa using h.some_spec (h.some.symm i))⟩ @[trans] lemma trans {s₁ s₂ s₃ : composition_series X} (h₁ : equivalent s₁ s₂) (h₂ : equivalent s₂ s₃) : equivalent s₁ s₃ := ⟨h₁.some.trans h₂.some, λ i, iso_trans (h₁.some_spec i) (h₂.some_spec (h₁.some i))⟩ lemma append {s₁ s₂ t₁ t₂ : composition_series X} (hs : s₁.top = s₂.bot) (ht : t₁.top = t₂.bot) (h₁ : equivalent s₁ t₁) (h₂ : equivalent s₂ t₂) : equivalent (append s₁ s₂ hs) (append t₁ t₂ ht) := let e : fin (s₁.length + s₂.length) ≃ fin (t₁.length + t₂.length) := calc fin (s₁.length + s₂.length) ≃ fin s₁.length ⊕ fin s₂.length : fin_sum_fin_equiv.symm ... ≃ fin t₁.length ⊕ fin t₂.length : equiv.sum_congr h₁.some h₂.some ... ≃ fin (t₁.length + t₂.length) : fin_sum_fin_equiv in ⟨e, begin assume i, refine fin.add_cases _ _ i, { assume i, simpa [top, bot] using h₁.some_spec i }, { assume i, simpa [top, bot] using h₂.some_spec i } end⟩ protected lemma snoc {s₁ s₂ : composition_series X} {x₁ x₂ : X} {hsat₁ : is_maximal s₁.top x₁} {hsat₂ : is_maximal s₂.top x₂} (hequiv : equivalent s₁ s₂) (htop : iso (s₁.top, x₁) (s₂.top, x₂)) : equivalent (s₁.snoc x₁ hsat₁) (s₂.snoc x₂ hsat₂) := let e : fin s₁.length.succ ≃ fin s₂.length.succ := calc fin (s₁.length + 1) ≃ option (fin s₁.length) : fin_succ_equiv_last ... ≃ option (fin s₂.length) : functor.map_equiv option hequiv.some ... ≃ fin (s₂.length + 1) : fin_succ_equiv_last.symm in ⟨e, λ i, begin refine fin.last_cases _ _ i, { simpa [top] using htop }, { assume i, simpa [fin.succ_cast_succ] using hequiv.some_spec i } end⟩ lemma length_eq {s₁ s₂ : composition_series X} (h : equivalent s₁ s₂) : s₁.length = s₂.length := by simpa using fintype.card_congr h.some lemma snoc_snoc_swap {s : composition_series X} {x₁ x₂ y₁ y₂ : X} {hsat₁ : is_maximal s.top x₁} {hsat₂ : is_maximal s.top x₂} {hsaty₁ : is_maximal (snoc s x₁ hsat₁).top y₁} {hsaty₂ : is_maximal (snoc s x₂ hsat₂).top y₂} (hr₁ : iso (s.top, x₁) (x₂, y₂)) (hr₂ : iso (x₁, y₁) (s.top, x₂)) : equivalent (snoc (snoc s x₁ hsat₁) y₁ hsaty₁) (snoc (snoc s x₂ hsat₂) y₂ hsaty₂) := let e : fin (s.length + 1 + 1) ≃ fin (s.length + 1 + 1) := equiv.swap (fin.last _) (fin.cast_succ (fin.last _)) in have h1 : ∀ {i : fin s.length}, i.cast_succ.cast_succ ≠ (fin.last _).cast_succ, from λ _, ne_of_lt (by simp [fin.cast_succ_lt_last]), have h2 : ∀ {i : fin s.length}, i.cast_succ.cast_succ ≠ (fin.last _), from λ _, ne_of_lt (by simp [fin.cast_succ_lt_last]), ⟨e, begin intro i, dsimp only [e], refine fin.last_cases _ (λ i, _) i, { erw [equiv.swap_apply_left, snoc_cast_succ, snoc_last, fin.succ_last, snoc_last, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_last, snoc_last], exact hr₂ }, { refine fin.last_cases _ (λ i, _) i, { erw [equiv.swap_apply_right, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_last, snoc_last, snoc_last, fin.succ_last, snoc_last], exact hr₁ }, { erw [equiv.swap_apply_of_ne_of_ne h2 h1, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ], exact (s.step i).iso_refl } } end⟩ end equivalent lemma length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) (hs₁ : s₁.length = 0) : s₂.length = 0 := begin have : s₁.bot = s₁.top, from congr_arg s₁ (fin.ext (by simp [hs₁])), have : (fin.last s₂.length) = (0 : fin s₂.length.succ), from s₂.injective (hb.symm.trans (this.trans ht)).symm, simpa [fin.ext_iff] end lemma length_pos_of_bot_eq_bot_of_top_eq_top_of_length_pos {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) : 0 < s₁.length → 0 < s₂.length := not_imp_not.1 begin simp only [pos_iff_ne_zero, ne.def, not_iff_not, not_not], exact length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb.symm ht.symm end lemma eq_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) (hs₁0 : s₁.length = 0) : s₁ = s₂ := have ∀ x, x ∈ s₁ ↔ x = s₁.top, from λ x, ⟨λ hx, forall_mem_eq_of_length_eq_zero hs₁0 hx s₁.top_mem, λ hx, hx.symm ▸ s₁.top_mem⟩, have ∀ x, x ∈ s₂ ↔ x = s₂.top, from λ x, ⟨λ hx, forall_mem_eq_of_length_eq_zero (length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb ht hs₁0) hx s₂.top_mem, λ hx, hx.symm ▸ s₂.top_mem⟩, by { ext, simp * } /-- Given a `composition_series`, `s`, and an element `x` such that `x` is maximal inside `s.top` there is a series, `t`, such that `t.top = x`, `t.bot = s.bot` and `snoc t s.top _` is equivalent to `s`. -/ lemma exists_top_eq_snoc_equivalant (s : composition_series X) (x : X) (hm : is_maximal x s.top) (hb : s.bot ≤ x) : ∃ t : composition_series X, t.bot = s.bot ∧ t.length + 1 = s.length ∧ ∃ htx : t.top = x, equivalent s (snoc t s.top (htx.symm ▸ hm)) := begin induction hn : s.length with n ih generalizing s x, { exact (ne_of_gt (lt_of_le_of_lt hb (lt_of_is_maximal hm)) (forall_mem_eq_of_length_eq_zero hn s.top_mem s.bot_mem)).elim }, { have h0s : 0 < s.length, from hn.symm ▸ nat.succ_pos _, by_cases hetx : s.erase_top.top = x, { use s.erase_top, simp [← hetx, hn] }, { have imxs : is_maximal (x ⊓ s.erase_top.top) s.erase_top.top, from is_maximal_of_eq_inf x s.top rfl (ne.symm hetx) hm (is_maximal_erase_top_top h0s), have := ih _ _ imxs (le_inf (by simpa) (le_top_of_mem s.erase_top.bot_mem)) (by simp [hn]), rcases this with ⟨t, htb, htl, htt, hteqv⟩, have hmtx : is_maximal t.top x, from is_maximal_of_eq_inf s.erase_top.top s.top (by rw [inf_comm, htt]) hetx (is_maximal_erase_top_top h0s) hm, use snoc t x hmtx, refine ⟨by simp [htb], by simp [htl], by simp, _⟩, have : s.equivalent ((snoc t s.erase_top.top (htt.symm ▸ imxs)).snoc s.top (by simpa using is_maximal_erase_top_top h0s)), { conv_lhs { rw eq_snoc_erase_top h0s }, exact equivalent.snoc hteqv (by simpa using (is_maximal_erase_top_top h0s).iso_refl) }, refine this.trans _, refine equivalent.snoc_snoc_swap _ _, { exact iso_symm (second_iso_of_eq hm (sup_eq_of_is_maximal hm (is_maximal_erase_top_top h0s) (ne.symm hetx)) htt.symm) }, { exact second_iso_of_eq (is_maximal_erase_top_top h0s) (sup_eq_of_is_maximal (is_maximal_erase_top_top h0s) hm hetx) (by rw [inf_comm, htt]) } } } end /-- The **Jordan-Hölder** theorem, stated for any `jordan_holder_lattice`. If two composition series start and finish at the same place, they are equivalent. -/ theorem jordan_holder (s₁ s₂ : composition_series X) (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) : equivalent s₁ s₂ := begin induction hle : s₁.length with n ih generalizing s₁ s₂, { rw [eq_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb ht hle] }, { have h0s₂ : 0 < s₂.length, from length_pos_of_bot_eq_bot_of_top_eq_top_of_length_pos hb ht (hle.symm ▸ nat.succ_pos _), rcases exists_top_eq_snoc_equivalant s₁ s₂.erase_top.top (ht.symm ▸ is_maximal_erase_top_top h0s₂) (hb.symm ▸ s₂.bot_erase_top ▸ bot_le_of_mem (top_mem _)) with ⟨t, htb, htl, htt, hteq⟩, have := ih t s₂.erase_top (by simp [htb, ← hb]) htt (nat.succ_inj'.1 (htl.trans hle)), refine hteq.trans _, conv_rhs { rw [eq_snoc_erase_top h0s₂] }, simp only [ht], exact equivalent.snoc this (by simp [htt, (is_maximal_erase_top_top h0s₂).iso_refl]) } end end composition_series
2f378d28d91c0f586758992f2c274b5304f9e42b
874a8d2247ab9a4516052498f80da2e32d0e3a48
/eulerv2.lean
fd2c36280d83c1aa7df22c230b71719cb780af40
[]
no_license
AlexKontorovich/Spring2020Math492
378b36c643ee029f5ab91c1677889baa591f5e85
659108c5d864ff5c75b9b3b13b847aa5cff4348a
refs/heads/master
1,610,780,595,457
1,588,174,859,000
1,588,174,859,000
243,017,788
0
1
null
null
null
null
UTF-8
Lean
false
false
6,148
lean
import analysis.normed_space.basic import topology.instances.ennreal import analysis.normed_space.basic import topology.instances.ennreal import algebra.archimedean algebra.geom_sum import data.nat.choose data.complex.basic import tactic.linarith import analysis.calculus.deriv import data.complex.exponential open finset open cau_seq namespace complex noncomputable theory lemma is_cau_abs_cos (z : ℂ) : is_cau_seq _root_.abs (λ n, (range n).sum (λ m, abs ( ((-1) ^ m) * z ^ (2 * m ) / nat.fact (2 * m )))) := begin sorry, end lemma is_cau_abs_sin (z : ℂ) : is_cau_seq _root_.abs (λ n, (range n).sum (λ m, abs ( ((-1) ^ m) * z ^ (2 * m + 1) / nat.fact (2 * m + 1)))) := begin sorry, /- let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) hn0) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.fact_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) -/ end lemma is_cau_sin (z : ℂ) : is_cau_seq abs (λ n, (range n).sum (λ m, ((-1) ^ m) * z ^ (2 * m + 1) / nat.fact (2 * m + 1))) := begin exact is_cau_series_of_abv_cau (is_cau_abs_sin z), end lemma is_cau_cos (z : ℂ) : is_cau_seq abs (λ n, (range n).sum (λ m, ((-1) ^ m) * z ^ (2 * m ) / nat.fact (2 * m))) := begin exact is_cau_series_of_abv_cau (is_cau_abs_cos z), end def sin' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, (range n).sum (λ m, ((-1) ^ m) * z ^ (2 * m + 1) / nat.fact (2 * m + 1)), is_cau_sin z⟩ def sin1 (z : ℂ) : ℂ := lim (sin' z) def cos' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, (range n).sum (λ m, (-1) ^ m * z ^ (2 * m) / nat.fact (2 * m)), is_cau_cos z⟩ def cos1 (z : ℂ) : ℂ := lim (cos' z) theorem euler : ∀ x, exp (x * I) = cos1 x + sin1 x * I := begin intros, have partials: ∀ n:ℕ , (exp' (x*I)).1 (2*n+1) = (cos' x).1 (n+1) + ((sin' x).1 n) * I, { intros, rw exp', simp, rw cos', simp, rw sin', simp, induction n with n0 hn, { -- case n0=0 simp, -- simp, }, { -- induction on n0 rw sum_range_succ _ _, -- takes out last term in cos have lastSin : sum (range (nat.succ n0)) (λ (x_1 : ℕ), (-1) ^ x_1 * x ^ (1 + 2 * x_1) / ↑(nat.fact (1 + 2 * x_1))) = (-1) ^ n0 * x ^ (1 + 2 * n0) / ↑(nat.fact (1 + 2 * n0)) + sum (range (n0)) (λ (x_1 : ℕ), (-1) ^ x_1 * x ^ (1 + 2 * x_1) / ↑(nat.fact (1 + 2 * x_1))) , { rw sum_range_succ _ _, }, have sinFactorial : sum (range (nat.succ n0)) (λ (x_1 : ℕ), (-1) ^ x_1 * x ^ (2 * x_1 + 1) / ((2 * ↑x_1 + 1) * ↑(nat.fact (2 * x_1)))) = sum (range (nat.succ n0)) (λ (x_1 : ℕ), (-1) ^ x_1 * x ^ (1 + 2 * x_1) / ↑(nat.fact (1 + 2 * x_1))), { rw add_comm, rw nat.fact_succ, by library_search, }, rw sinFactorial, rw lastSin, have twoFromExp: sum (range (nat.succ (2 * nat.succ n0))) (λ (x_1 : ℕ), (x * I) ^ x_1 / ↑(nat.fact x_1)) = (x * I) ^ ( 2 * nat.succ n0) / ↑(nat.fact ( 2 * nat.succ n0))+ sum (range ( 2 * nat.succ n0)) (λ (x_1 : ℕ), (x * I) ^ x_1 / ↑(nat.fact x_1)) , { rw sum_range_succ _ ( 2 * nat.succ n0), }, have twoFromExpv1 : (x * I) ^ ( 2 * nat.succ n0) / ↑(nat.fact ( 2 * nat.succ n0))+sum (range ( 2 * nat.succ n0)) (λ (x_1 : ℕ), (x * I) ^ x_1 / ↑(nat.fact x_1)) = sum (range (nat.succ (2 * nat.succ n0))) (λ (x_1 : ℕ), (x * I) ^ x_1 / ↑(nat.fact x_1)), { by exact eq.symm twoFromExp, }, have twoNP1 : 1+ (2 * nat.succ n0) =nat.succ (2 * nat.succ n0) , { exact add_comm 1 (2 * nat.succ n0), }, have twoNP1v1 : nat.succ ( 2 * nat.succ n0) = 1 + (2 * nat.succ n0), { by exact eq.symm twoNP1, }, --rw twoNP1v1, --rw twoFromExpv1, have oneFromExp: sum (range (2 * nat.succ n0)) (λ (x_1 : ℕ), (x * I) ^ x_1 / ↑(nat.fact x_1)) = (x * I) ^ (1+2 * n0) / ↑(nat.fact (1+2 * n0)) + sum (range (1+ 2 * n0)) (λ (x_1 : ℕ), (x * I) ^ x_1 / ↑(nat.fact x_1)) , { have stupid : 2 * nat.succ n0 = nat.succ(1+2*n0), { have RRS : nat.succ(1+2*n0) = 1+(1+2*n0) , { ring, }, rw RRS, have realSt : 1+(1+2*n0) = 1+1+2*n0, { simp, }, rw realSt, exact nat.add_comm (nat.mul 2 n0) 2, }, rw stupid, rw sum_range_succ _ (1 + 2 * n0), }, rw oneFromExp, --rw hn, simp, rw nat.succ_eq_add_one, ring, sorry, -- need (x*I)^(2 n0 )= x^(2n0) (-1)^n0 etc, commutativity }, }, have partialExp : lim (exp' (x * I)) = exp (x*I), { sorry, }, rw exp, rw partialExp, -- Now: need to take limits on both sides, they're same, -- but need to convince Lean that limit of exp' (2n+1) is same as -- limit of exp' (n) which is what exp is defined to be end end complex
eec770fd2b1058cf796e0500472edc8381d8ea34
6b10c15e653d49d146378acda9f3692e9b5b1950
/examples/logic/unnamed_293.lean
f9224b471228dc0411abcd8dc9e22fcbc5ead492
[]
no_license
gebner/mathematics_in_lean
3cf7f18767208ea6c3307ec3a67c7ac266d8514d
6d1462bba46d66a9b948fc1aef2714fd265cde0b
refs/heads/master
1,655,301,945,565
1,588,697,505,000
1,588,697,505,000
261,523,603
0
0
null
1,588,695,611,000
1,588,695,610,000
null
UTF-8
Lean
false
false
114
lean
variables A B : Prop -- BEGIN example : A ∧ B → B ∧ A := begin intro h, exact ⟨h.2, h.1⟩ end -- END
7a46146b954a8d7f968259d86662aa94bcf56a90
798dd332c1ad790518589a09bc82459fb12e5156
/tests/linarith.lean
a06c5a25555051a7a9edc180c680c34b064495a7
[ "Apache-2.0" ]
permissive
tobiasgrosser/mathlib
b040b7eb42d5942206149371cf92c61404de3c31
120635628368ec261e031cefc6d30e0304088b03
refs/heads/master
1,644,803,442,937
1,536,663,752,000
1,536,663,907,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,176
lean
import tactic.linarith example (h1 : (1 : ℚ) < 1) : false := by linarith example (e b c a v0 v1 : ℚ) (h1 : v0 = 5*a) (h2 : v1 = 3*b) (h3 : v0 + v1 + c = 10) : v0 + 5 + (v1 - 3) + (c - 2) = 10 := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 2 + ε / 3 + ε / 7 < ε := by linarith example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + z/2 < 0) (h3 : 12*y - z < 0) : false := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 2 < ε := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 3 + ε / 3 + ε / 3 = ε := by linarith example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false := by linarith {discharger := `[ring SOP]} example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false := by linarith example (a b c : ℚ) (x y : ℤ) (h1 : x ≤ 3*y) (h2 : b + 2 > 3 + b) : false := by linarith {restrict_type := ℚ} example (g v V c h : ℚ) (h1 : h = 0) (h2 : v = V) (h3 : V > 0) (h4 : g > 0) (h5 : 0 ≤ c) (h6 : c < 1) : v ≤ V := by linarith example (x y z : ℚ) (h1 : 2*x + ((-3)*y) < 0) (h2 : (-4)*x + 2*z < 0) (h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false := by linarith example (x y z : ℚ) (h1 : 2*1*x + (3)*(y*(-1)) < 0) (h2 : (-2)*x*2 < -(z + z)) (h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : 12*y - 4* z < 0) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) (h3 : 12*y - 4* z < 0) : false := by linarith example (w x y z : ℤ) (h1 : 4*x + (-3)*y + 6*w ≤ 0) (h2 : (-1)*x < 0) (h3 : y < 0) (h4 : w ≥ 0) (h5 : nat.prime x.nat_abs) : false := by linarith example (a b c : ℚ) (h1 : a > 0) (h2 : b > 5) (h3 : c < -10) (h4 : a + b - c < 3) : false := by linarith example (a b c : ℚ) (h2 : b > 0) (h3 : b < 0) : false := by linarith example (a b c : ℚ) (h2 : (2 : ℚ) > 3) : a + b - c ≥ 3 := by linarith example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false := by linarith using [rat.num_pos_iff_pos.mpr hx] example (x y z : ℚ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith
7834355a28c527bd51626636457cb57a195501f6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/category/Top/basic.lean
f212483491efe5c7391ea2e9f5aeddf7983fef38
[ "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
3,669
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Scott Morrison, Mario Carneiro -/ import category_theory.concrete_category.bundled_hom import category_theory.elementwise import topology.continuous_function.basic /-! # Category instance for topological spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We introduce the bundled category `Top` of topological spaces together with the functors `discrete` and `trivial` from the category of types to `Top` which equip a type with the corresponding discrete, resp. trivial, topology. For a proof that these functors are left, resp. right adjoint to the forgetful functor, see `topology.category.Top.adjunctions`. -/ open category_theory open topological_space universe u /-- The category of topological spaces and continuous maps. -/ def Top : Type (u+1) := bundled topological_space namespace Top instance bundled_hom : bundled_hom @continuous_map := ⟨@continuous_map.to_fun, @continuous_map.id, @continuous_map.comp, @continuous_map.coe_injective⟩ attribute [derive [large_category, concrete_category]] Top instance : has_coe_to_sort Top Type* := bundled.has_coe_to_sort instance topological_space_unbundled (x : Top) : topological_space x := x.str @[simp] lemma id_app (X : Top.{u}) (x : X) : (𝟙 X : X → X) x = x := rfl @[simp] lemma comp_app {X Y Z : Top.{u}} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g : X → Z) x = g (f x) := rfl /-- Construct a bundled `Top` from the underlying type and the typeclass. -/ def of (X : Type u) [topological_space X] : Top := ⟨X⟩ instance (X : Top) : topological_space X := X.str @[simp] lemma coe_of (X : Type u) [topological_space X] : (of X : Type u) = X := rfl instance : inhabited Top := ⟨Top.of empty⟩ /-- The discrete topology on any type. -/ def discrete : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊥⟩, map := λ X Y f, { to_fun := f, continuous_to_fun := continuous_bot } } instance {X : Type u} : discrete_topology (discrete.obj X) := ⟨rfl⟩ /-- The trivial topology on any type. -/ def trivial : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊤⟩, map := λ X Y f, { to_fun := f, continuous_to_fun := continuous_top } } /-- Any homeomorphisms induces an isomorphism in `Top`. -/ @[simps] def iso_of_homeo {X Y : Top.{u}} (f : X ≃ₜ Y) : X ≅ Y := { hom := ⟨f⟩, inv := ⟨f.symm⟩ } /-- Any isomorphism in `Top` induces a homeomorphism. -/ @[simps] def homeo_of_iso {X Y : Top.{u}} (f : X ≅ Y) : X ≃ₜ Y := { to_fun := f.hom, inv_fun := f.inv, left_inv := λ x, by simp, right_inv := λ x, by simp, continuous_to_fun := f.hom.continuous, continuous_inv_fun := f.inv.continuous } @[simp] lemma of_iso_of_homeo {X Y : Top.{u}} (f : X ≃ₜ Y) : homeo_of_iso (iso_of_homeo f) = f := by { ext, refl } @[simp] lemma of_homeo_of_iso {X Y : Top.{u}} (f : X ≅ Y) : iso_of_homeo (homeo_of_iso f) = f := by { ext, refl } @[simp] lemma open_embedding_iff_comp_is_iso {X Y Z : Top} (f : X ⟶ Y) (g : Y ⟶ Z) [is_iso g] : open_embedding (f ≫ g) ↔ open_embedding f := (Top.homeo_of_iso (as_iso g)).open_embedding.of_comp_iff f @[simp] lemma open_embedding_iff_is_iso_comp {X Y Z : Top} (f : X ⟶ Y) (g : Y ⟶ Z) [is_iso f] : open_embedding (f ≫ g) ↔ open_embedding g := begin split, { intro h, convert h.comp (Top.homeo_of_iso (as_iso f).symm).open_embedding, exact congr_arg _ (is_iso.inv_hom_id_assoc f g).symm }, { exact λ h, h.comp (Top.homeo_of_iso (as_iso f)).open_embedding } end end Top
691e5f72f2b9898c38cab9ed9af9cf6afe78355e
b70447c014d9e71cf619ebc9f539b262c19c2e0b
/hott/eq2.hlean
e3d239c094de2c7453272dba56bf5e8771f678cd
[ "Apache-2.0" ]
permissive
ia0/lean2
c20d8da69657f94b1d161f9590a4c635f8dc87f3
d86284da630acb78fa5dc3b0b106153c50ffccd0
refs/heads/master
1,611,399,322,751
1,495,751,007,000
1,495,751,007,000
93,104,167
0
0
null
1,496,355,488,000
1,496,355,487,000
null
UTF-8
Lean
false
false
5,612
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 Theorems about 2-dimensional paths -/ import .cubical.square open function namespace eq variables {A B C : Type} {f : A → B} {a a' a₁ a₂ a₃ a₄ : A} {b b' : B} theorem ap_is_constant_eq (p : Πx, f x = b) (q : a = a') : ap_is_constant p q = eq_con_inv_of_con_eq ((eq_of_square (square_of_pathover (apd p q)))⁻¹ ⬝ whisker_left (p a) (ap_constant q b)) := begin induction q, esimp, generalize (p a), intro p, cases p, apply idpath idp end definition ap_inv2 {p q : a = a'} (r : p = q) : square (ap (ap f) (inverse2 r)) (inverse2 (ap (ap f) r)) (ap_inv f p) (ap_inv f q) := by induction r;exact hrfl definition ap_con2 {p₁ q₁ : a₁ = a₂} {p₂ q₂ : a₂ = a₃} (r₁ : p₁ = q₁) (r₂ : p₂ = q₂) : square (ap (ap f) (r₁ ◾ r₂)) (ap (ap f) r₁ ◾ ap (ap f) r₂) (ap_con f p₁ p₂) (ap_con f q₁ q₂) := by induction r₂;induction r₁;exact hrfl theorem ap_con_right_inv_sq {A B : Type} {a1 a2 : A} (f : A → B) (p : a1 = a2) : square (ap (ap f) (con.right_inv p)) (con.right_inv (ap f p)) (ap_con f p p⁻¹ ⬝ whisker_left _ (ap_inv f p)) idp := by cases p;apply hrefl theorem ap_con_left_inv_sq {A B : Type} {a1 a2 : A} (f : A → B) (p : a1 = a2) : square (ap (ap f) (con.left_inv p)) (con.left_inv (ap f p)) (ap_con f p⁻¹ p ⬝ whisker_right _ (ap_inv f p)) idp := by cases p;apply vrefl definition ap02_compose {A B C : Type} (g : B → C) (f : A → B) {a a' : A} {p₁ p₂ : a = a'} (q : p₁ = p₂) : square (ap_compose g f p₁) (ap_compose g f p₂) (ap02 (g ∘ f) q) (ap02 g (ap02 f q)) := by induction q; exact vrfl definition ap02_id {A : Type} {a a' : A} {p₁ p₂ : a = a'} (q : p₁ = p₂) : square (ap_id p₁) (ap_id p₂) (ap02 id q) q := by induction q; exact vrfl theorem ap_ap_is_constant {A B C : Type} (g : B → C) {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : square (ap (ap g) (ap_is_constant p q)) (ap_is_constant (λa, ap g (p a)) q) (ap_compose g f q)⁻¹ (!ap_con ⬝ whisker_left _ !ap_inv) := begin induction q, esimp, generalize (p x), intro p, cases p, apply ids -- induction q, rewrite [↑ap_compose,ap_inv], apply hinverse, apply ap_con_right_inv_sq, end theorem ap_ap_compose {A B C D : Type} (h : C → D) (g : B → C) (f : A → B) {x y : A} (p : x = y) : square (ap_compose (h ∘ g) f p) (ap (ap h) (ap_compose g f p)) (ap_compose h (g ∘ f) p) (ap_compose h g (ap f p)) := by induction p;exact ids theorem ap_compose_inv {A B C : Type} (g : B → C) (f : A → B) {x y : A} (p : x = y) : square (ap_compose g f p⁻¹) (inverse2 (ap_compose g f p) ⬝ (ap_inv g (ap f p))⁻¹) (ap_inv (g ∘ f) p) (ap (ap g) (ap_inv f p)) := by induction p;exact ids theorem ap_compose_con (g : B → C) (f : A → B) (p : a₁ = a₂) (q : a₂ = a₃) : square (ap_compose g f (p ⬝ q)) (ap_compose g f p ◾ ap_compose g f q ⬝ (ap_con g (ap f p) (ap f q))⁻¹) (ap_con (g ∘ f) p q) (ap (ap g) (ap_con f p q)) := by induction q;induction p;exact ids theorem ap_compose_natural {A B C : Type} (g : B → C) (f : A → B) {x y : A} {p q : x = y} (r : p = q) : square (ap (ap (g ∘ f)) r) (ap (ap g ∘ ap f) r) (ap_compose g f p) (ap_compose g f q) := natural_square_tr (ap_compose g f) r theorem whisker_right_eq_of_con_inv_eq_idp {p q : a₁ = a₂} (r : p ⬝ q⁻¹ = idp) : whisker_right q⁻¹ (eq_of_con_inv_eq_idp r) ⬝ con.right_inv q = r := by induction q; esimp at r; cases r; reflexivity theorem ap_eq_of_con_inv_eq_idp (f : A → B) {p q : a₁ = a₂} (r : p ⬝ q⁻¹ = idp) : ap02 f (eq_of_con_inv_eq_idp r) = eq_of_con_inv_eq_idp (whisker_left _ !ap_inv⁻¹ ⬝ !ap_con⁻¹ ⬝ ap02 f r) := by induction q;esimp at *;cases r;reflexivity theorem eq_of_con_inv_eq_idp_con2 {p p' q q' : a₁ = a₂} (r : p = p') (s : q = q') (t : p' ⬝ q'⁻¹ = idp) : eq_of_con_inv_eq_idp (r ◾ inverse2 s ⬝ t) = r ⬝ eq_of_con_inv_eq_idp t ⬝ s⁻¹ := by induction s;induction r;induction q;reflexivity definition naturality_apd_eq {A : Type} {B : A → Type} {a a₂ : A} {f g : Πa, B a} (H : f ~ g) (p : a = a₂) : apd f p = concato_eq (eq_concato (H a) (apd g p)) (H a₂)⁻¹ := begin induction p, esimp, generalizes [H a, g a], intro ga Ha, induction Ha, reflexivity end theorem con_tr_idp {P : A → Type} {x y : A} (q : x = y) (u : P x) : con_tr idp q u = ap (λp, p ▸ u) (idp_con q) := by induction q;reflexivity definition eq_transport_Fl_idp_left {A B : Type} {a : A} {b : B} (f : A → B) (q : f a = b) : eq_transport_Fl idp q = !idp_con⁻¹ := by induction q; reflexivity definition whisker_left_idp_con_eq_assoc {A : Type} {a₁ a₂ a₃ : A} (p : a₁ = a₂) (q : a₂ = a₃) : whisker_left p (idp_con q)⁻¹ = con.assoc p idp q := by induction q; reflexivity definition whisker_left_inverse2 {A : Type} {a : A} {p : a = a} (q : p = idp) : whisker_left p q⁻² ⬝ q = con.right_inv p := by cases q; reflexivity end eq
5509c4f76cab4d7133bfa748fd3c19c6c4933401
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/convex/contractible.lean
88bf959d51e582c6625f67c583b722181d8aebd2
[ "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,738
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.convex.star import topology.homotopy.contractible /-! # A convex set is contractible > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove that a (star) convex set in a real topological vector space is a contractible topological space. -/ variables {E : Type*} [add_comm_group E] [module ℝ E] [topological_space E] [has_continuous_add E] [has_continuous_smul ℝ E] {s : set E} {x : E} /-- A non-empty star convex set is a contractible space. -/ protected lemma star_convex.contractible_space (h : star_convex ℝ x s) (hne : s.nonempty) : contractible_space s := begin refine (contractible_iff_id_nullhomotopic _).2 ⟨⟨x, h.mem hne⟩, ⟨⟨⟨λ p, ⟨p.1.1 • x + (1 - p.1.1) • p.2, _⟩, _⟩, λ x, _, λ x, _⟩⟩⟩, { exact h p.2.2 p.1.2.1 (sub_nonneg.2 p.1.2.2) (add_sub_cancel'_right _ _) }, { exact ((continuous_subtype_val.fst'.smul continuous_const).add ((continuous_const.sub continuous_subtype_val.fst').smul continuous_subtype_val.snd')).subtype_mk _ }, { ext1, simp }, { ext1, simp } end /-- A non-empty convex set is a contractible space. -/ protected lemma convex.contractible_space (hs : convex ℝ s) (hne : s.nonempty) : contractible_space s := let ⟨x, hx⟩ := hne in (hs.star_convex hx).contractible_space hne @[priority 100] instance real_topological_vector_space.contractible_space : contractible_space E := (homeomorph.set.univ E).contractible_space_iff.mp $ convex_univ.contractible_space set.univ_nonempty
120cad99360d3210091aa0af0d6cefb9eba1aeab
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/group/units.lean
978fa33f275847ae66273e5aaf37cb188c4c0703
[ "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
18,221
lean
/- Copyright (c) 2017 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johannes Hölzl, Chris Hughes, Jens Wagemaker -/ import algebra.group.basic import logic.nontrivial /-! # Units (i.e., invertible elements) of a monoid An element of a `monoid` is a unit if it has a two-sided inverse. ## Main declarations * `units M`: the group of units (i.e., invertible elements) of a monoid. * `is_unit x`: a predicate asserting that `x` is a unit (i.e., invertible element) of a monoid. For both declarations, there is an additive counterpart: `add_units` and `is_add_unit`. ## Notation We provide `Mˣ` as notation for `units M`, resembling the notation $R^{\times}$ for the units of a ring, which is common in mathematics. -/ open function universe u variable {α : Type u} /-- Units of a `monoid`, bundled version. Notation: `αˣ`. An element of a `monoid` is a unit if it has a two-sided inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_unit`. -/ structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) postfix `ˣ`:1025 := units -- We don't provide notation for the additive version, because its use is somewhat rare. /-- Units of an `add_monoid`, bundled version. An element of an `add_monoid` is a unit if it has a two-sided additive inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_add_unit`. -/ structure add_units (α : Type u) [add_monoid α] := (val : α) (neg : α) (val_neg : val + neg = 0) (neg_val : neg + val = 0) attribute [to_additive] units section has_elem @[to_additive] lemma unique_has_one {α : Type*} [unique α] [has_one α] : default = (1 : α) := unique.default_eq 1 end has_elem namespace units variables [monoid α] @[to_additive] instance : has_coe αˣ α := ⟨val⟩ @[to_additive] instance : has_inv αˣ := ⟨λ u, ⟨u.2, u.1, u.4, u.3⟩⟩ /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe (u : αˣ) : α := u /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe_inv (u : αˣ) : α := ↑(u⁻¹) initialize_simps_projections units (val → coe as_prefix, inv → coe_inv as_prefix) initialize_simps_projections add_units (val → coe as_prefix, neg → coe_neg as_prefix) @[simp, to_additive] lemma coe_mk (a : α) (b h₁ h₂) : ↑(units.mk a b h₁ h₂) = a := rfl @[ext, to_additive] theorem ext : function.injective (coe : αˣ → α) | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ @[norm_cast, to_additive] theorem eq_iff {a b : αˣ} : (a : α) = b ↔ a = b := ext.eq_iff @[to_additive] theorem ext_iff {a b : αˣ} : a = b ↔ (a : α) = b := eq_iff.symm @[to_additive] instance [decidable_eq α] : decidable_eq αˣ := λ a b, decidable_of_iff' _ ext_iff @[simp, to_additive] theorem mk_coe (u : αˣ) (y h₁ h₂) : mk (u : α) y h₁ h₂ = u := ext rfl /-- Copy a unit, adjusting definition equalities. -/ @[to_additive /-"Copy an `add_unit`, adjusting definitional equalities."-/, simps] def copy (u : αˣ) (val : α) (hv : val = u) (inv : α) (hi : inv = ↑(u⁻¹)) : αˣ := { val := val, inv := inv, inv_val := hv.symm ▸ hi.symm ▸ u.inv_val, val_inv := hv.symm ▸ hi.symm ▸ u.val_inv } @[to_additive] lemma copy_eq (u : αˣ) (val hv inv hi) : u.copy val hv inv hi = u := ext hv @[to_additive] instance : mul_one_class αˣ := { mul := λ u₁ u₂, ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, by rw [mul_assoc, ←mul_assoc u₂.val, val_inv, one_mul, val_inv], by rw [mul_assoc, ←mul_assoc u₁.inv, inv_val, one_mul, inv_val]⟩, one := ⟨1, 1, one_mul 1, one_mul 1⟩, one_mul := λ u, ext $ one_mul u, mul_one := λ u, ext $ mul_one u } /-- Units of a monoid form a group. -/ @[to_additive "Additive units of an additive monoid form an additive group."] instance : group αˣ := { mul := (*), one := 1, mul_assoc := λ u₁ u₂ u₃, ext $ mul_assoc u₁ u₂ u₃, inv := has_inv.inv, mul_left_inv := λ u, ext u.inv_val, ..units.mul_one_class } @[to_additive] instance {α} [comm_monoid α] : comm_group αˣ := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } @[to_additive] instance : inhabited αˣ := ⟨1⟩ @[to_additive] instance [has_repr α] : has_repr αˣ := ⟨repr ∘ val⟩ variables (a b c : αˣ) {u : αˣ} @[simp, norm_cast, to_additive] lemma coe_mul : (↑(a * b) : α) = a * b := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : αˣ) : α) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_eq_one {a : αˣ} : (a : α) = 1 ↔ a = 1 := by rw [←units.coe_one, eq_iff] @[simp, to_additive] lemma inv_mk (x y : α) (h₁ h₂) : (mk x y h₁ h₂)⁻¹ = mk y x h₂ h₁ := rfl @[simp, to_additive] lemma val_eq_coe : a.val = (↑a : α) := rfl @[simp, to_additive] lemma inv_eq_coe_inv : a.inv = ((a⁻¹ : αˣ) : α) := rfl @[simp, to_additive] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp, to_additive] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[to_additive] lemma inv_mul_of_eq {a : α} (h : ↑u = a) : ↑u⁻¹ * a = 1 := by rw [←h, u.inv_mul] @[to_additive] lemma mul_inv_of_eq {a : α} (h : ↑u = a) : a * ↑u⁻¹ = 1 := by rw [←h, u.mul_inv] @[simp, to_additive] lemma mul_inv_cancel_left (a : αˣ) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp, to_additive] lemma inv_mul_cancel_left (a : αˣ) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp, to_additive] lemma mul_inv_cancel_right (a : α) (b : αˣ) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp, to_additive] lemma inv_mul_cancel_right (a : α) (b : αˣ) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] @[simp, to_additive] theorem mul_right_inj (a : αˣ) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : αˣ)) h, congr_arg _⟩ @[simp, to_additive] theorem mul_left_inj (a : αˣ) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : αˣ)) h, congr_arg _⟩ @[to_additive] theorem eq_mul_inv_iff_mul_eq {a b : α} : 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 c : α} : 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 {b c : α} : ↑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 c : α} : a * ↑b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ @[to_additive] protected lemma inv_eq_of_mul_eq_one_left {a : α} (h : a * u = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = 1 * ↑u⁻¹ : by rw one_mul ... = a : by rw [←h, mul_inv_cancel_right] @[to_additive] protected lemma inv_eq_of_mul_eq_one_right {a : α} (h : ↑u * a = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = ↑u⁻¹ * 1 : by rw mul_one ... = a : by rw [←h, inv_mul_cancel_left] @[to_additive] protected lemma eq_inv_of_mul_eq_one_left {a : α} (h : ↑u * a = 1) : a = ↑u⁻¹ := (units.inv_eq_of_mul_eq_one_right h).symm @[to_additive] protected lemma eq_inv_of_mul_eq_one_right {a : α} (h : a * u = 1) : a = ↑u⁻¹ := (units.inv_eq_of_mul_eq_one_left h).symm @[simp, to_additive] lemma mul_inv_eq_one {a : α} : a * ↑u⁻¹ = 1 ↔ a = u := ⟨inv_inv u ▸ units.eq_inv_of_mul_eq_one_right, λ h, mul_inv_of_eq h.symm⟩ @[simp, to_additive] lemma inv_mul_eq_one {a : α} : ↑u⁻¹ * a = 1 ↔ ↑u = a := ⟨inv_inv u ▸ units.inv_eq_of_mul_eq_one_right, inv_mul_of_eq⟩ @[to_additive] lemma mul_eq_one_iff_eq_inv {a : α} : a * u = 1 ↔ a = ↑u⁻¹ := by rw [←mul_inv_eq_one, inv_inv] @[to_additive] lemma mul_eq_one_iff_inv_eq {a : α} : ↑u * a = 1 ↔ ↑u⁻¹ = a := by rw [←inv_mul_eq_one, inv_inv] lemma inv_unique {u₁ u₂ : αˣ} (h : (↑u₁ : α) = ↑u₂) : (↑u₁⁻¹ : α) = ↑u₂⁻¹ := units.inv_eq_of_mul_eq_one_right $ by rw [h, u₂.mul_inv] end units /-- For `a, b` in a `comm_monoid` such that `a * b = 1`, makes a unit out of `a`. -/ @[to_additive "For `a, b` in an `add_comm_monoid` such that `a + b = 0`, makes an add_unit out of `a`."] def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : αˣ := ⟨a, b, hab, (mul_comm b a).trans hab⟩ @[simp, to_additive] lemma units.coe_mk_of_mul_eq_one [comm_monoid α] {a b : α} (h : a * b = 1) : (units.mk_of_mul_eq_one a b h : α) = a := rfl section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : αˣ) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : αˣ) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : αˣ) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ @[simp] theorem divp_inv (u : αˣ) : a /ₚ u⁻¹ = a * u := rfl @[simp] theorem divp_mul_cancel (a : α) (u : αˣ) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : αˣ) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_left_inj (u : αˣ) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_left_inj _ theorem divp_divp_eq_divp_mul (x : α) (u₁ u₂ : αˣ) : (x /ₚ u₁) /ₚ u₂ = x /ₚ (u₂ * u₁) := by simp only [divp, mul_inv_rev, units.coe_mul, mul_assoc] theorem divp_eq_iff_mul_eq {x : α} {u : αˣ} {y : α} : x /ₚ u = y ↔ y * u = x := u.mul_left_inj.symm.trans $ by rw [divp_mul_cancel]; exact ⟨eq.symm, eq.symm⟩ theorem divp_eq_one_iff_eq {a : α} {u : αˣ} : a /ₚ u = 1 ↔ a = u := (units.mul_left_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : αˣ) : 1 /ₚ u = ↑u⁻¹ := one_mul _ end monoid section comm_monoid variables [comm_monoid α] theorem divp_eq_divp_iff {x y : α} {ux uy : αˣ} : x /ₚ ux = y /ₚ uy ↔ x * uy = y * ux := by rw [divp_eq_iff_mul_eq, mul_comm, ← divp_assoc, divp_eq_iff_mul_eq, mul_comm y ux] theorem divp_mul_divp (x y : α) (ux uy : αˣ) : (x /ₚ ux) * (y /ₚ uy) = (x * y) /ₚ (ux * uy) := by rw [← divp_divp_eq_divp_mul, divp_assoc, mul_comm x, divp_assoc, mul_comm] end comm_monoid /-! # `is_unit` predicate In this file we define the `is_unit` predicate on a `monoid`, and prove a few basic properties. For the bundled version see `units`. See also `prime`, `associated`, and `irreducible` in `algebra/associated`. -/ section is_unit variables {M : Type*} {N : Type*} /-- An element `a : M` of a monoid is a unit if it has a two-sided inverse. The actual definition says that `a` is equal to some `u : Mˣ`, where `Mˣ` is a bundled version of `is_unit`. -/ @[to_additive "An element `a : M` of an add_monoid is an `add_unit` if it has a two-sided additive inverse. The actual definition says that `a` is equal to some `u : add_units M`, where `add_units M` is a bundled version of `is_add_unit`."] def is_unit [monoid M] (a : M) : Prop := ∃ u : Mˣ, (u : M) = a @[nontriviality, to_additive] lemma is_unit_of_subsingleton [monoid M] [subsingleton M] (a : M) : is_unit a := ⟨⟨a, a, subsingleton.elim _ _, subsingleton.elim _ _⟩, rfl⟩ attribute [nontriviality] is_add_unit_of_subsingleton @[to_additive] instance [monoid M] : can_lift M Mˣ := { coe := coe, cond := is_unit, prf := λ _, id } @[to_additive] instance [monoid M] [subsingleton M] : unique Mˣ := { default := 1, uniq := λ a, units.coe_eq_one.mp $ subsingleton.elim (a : M) 1 } @[simp, to_additive is_add_unit_add_unit] protected lemma units.is_unit [monoid M] (u : Mˣ) : is_unit (u : M) := ⟨u, rfl⟩ @[simp, to_additive] theorem is_unit_one [monoid M] : is_unit (1:M) := ⟨1, rfl⟩ @[to_additive] theorem is_unit_of_mul_eq_one [comm_monoid M] (a b : M) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ @[to_additive is_add_unit.exists_neg] theorem is_unit.exists_right_inv [monoid M] {a : M} (h : is_unit a) : ∃ b, a * b = 1 := by { rcases h with ⟨⟨a, b, hab, _⟩, rfl⟩, exact ⟨b, hab⟩ } @[to_additive is_add_unit.exists_neg'] theorem is_unit.exists_left_inv [monoid M] {a : M} (h : is_unit a) : ∃ b, b * a = 1 := by { rcases h with ⟨⟨a, b, _, hba⟩, rfl⟩, exact ⟨b, hba⟩ } @[to_additive] theorem is_unit_iff_exists_inv [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, a * b = 1 := ⟨λ h, h.exists_right_inv, λ ⟨b, hab⟩, is_unit_of_mul_eq_one _ b hab⟩ @[to_additive] theorem is_unit_iff_exists_inv' [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] @[to_additive] lemma is_unit.mul [monoid M] {x y : M} : is_unit x → is_unit y → is_unit (x * y) := by { rintros ⟨x, rfl⟩ ⟨y, rfl⟩, exact ⟨x * y, units.coe_mul _ _⟩ } /-- Multiplication by a `u : Mˣ` on the right doesn't affect `is_unit`. -/ @[simp, to_additive "Addition of a `u : add_units M` on the right doesn't affect `is_add_unit`."] theorem units.is_unit_mul_units [monoid M] (a : M) (u : Mˣ) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [←hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (λ v, v.mul u.is_unit) /-- Multiplication by a `u : Mˣ` on the left doesn't affect `is_unit`. -/ @[simp, to_additive "Addition of a `u : add_units M` on the left doesn't affect `is_add_unit`."] theorem units.is_unit_units_mul {M : Type*} [monoid M] (u : Mˣ) (a : M) : is_unit (↑u * a) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (↑u⁻¹ * (↑u * a)), by existsi u⁻¹ * v; rw [←hv, units.coe_mul], by rwa [←mul_assoc, units.inv_mul, one_mul] at this) u.is_unit.mul @[to_additive] theorem is_unit_of_mul_is_unit_left [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ @[to_additive] theorem is_unit_of_mul_is_unit_right [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm @[simp, to_additive] lemma is_unit.mul_iff [comm_monoid M] {x y : M} : is_unit (x * y) ↔ is_unit x ∧ is_unit y := ⟨λ h, ⟨is_unit_of_mul_is_unit_left h, is_unit_of_mul_is_unit_right h⟩, λ h, is_unit.mul h.1 h.2⟩ /-- The element of the group of units, corresponding to an element of a monoid which is a unit. When `α` is a `division_monoid`, use `is_unit.unit'` instead. -/ @[to_additive "The element of the additive group of additive units, corresponding to an element of an additive monoid which is an additive unit. When `α` is a `subtraction_monoid`, use `is_add_unit.add_unit'` instead."] noncomputable def is_unit.unit [monoid M] {a : M} (h : is_unit a) : Mˣ := (classical.some h).copy a (classical.some_spec h).symm _ rfl @[simp, to_additive] lemma is_unit.unit_of_coe_units [monoid M] {a : Mˣ} (h : is_unit (a : M)) : h.unit = a := units.ext $ rfl @[simp, to_additive] lemma is_unit.unit_spec [monoid M] {a : M} (h : is_unit a) : ↑h.unit = a := rfl @[simp, to_additive] lemma is_unit.coe_inv_mul [monoid M] {a : M} (h : is_unit a) : ↑(h.unit)⁻¹ * a = 1 := units.mul_inv _ @[simp, to_additive] lemma is_unit.mul_coe_inv [monoid M] {a : M} (h : is_unit a) : a * ↑(h.unit)⁻¹ = 1 := begin convert units.mul_inv _, simp [h.unit_spec] end /-- `is_unit x` is decidable if we can decide if `x` comes from `Mˣ`. -/ instance [monoid M] (x : M) [h : decidable (∃ u : Mˣ, ↑u = x)] : decidable (is_unit x) := h section monoid variables [monoid M] {a b c : M} @[to_additive] lemma is_unit.mul_left_inj (h : is_unit a) : b * a = c * a ↔ b = c := let ⟨u, hu⟩ := h in hu ▸ u.mul_left_inj @[to_additive] lemma is_unit.mul_right_inj (h : is_unit a) : a * b = a * c ↔ b = c := let ⟨u, hu⟩ := h in hu ▸ u.mul_right_inj @[to_additive] protected lemma is_unit.mul_left_cancel (h : is_unit a) : a * b = a * c → b = c := h.mul_right_inj.1 @[to_additive] protected lemma is_unit.mul_right_cancel (h : is_unit b) : a * b = c * b → a = c := h.mul_left_inj.1 @[to_additive] protected lemma is_unit.mul_right_injective (h : is_unit a) : injective ((*) a) := λ _ _, h.mul_left_cancel @[to_additive] protected lemma is_unit.mul_left_injective (h : is_unit b) : injective (* b) := λ _ _, h.mul_right_cancel end monoid end is_unit section noncomputable_defs variables {M : Type*} /-- Constructs a `group` structure on a `monoid` consisting only of units. -/ noncomputable def group_of_is_unit [hM : monoid M] (h : ∀ (a : M), is_unit a) : group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } /-- Constructs a `comm_group` structure on a `comm_monoid` consisting only of units. -/ noncomputable def comm_group_of_is_unit [hM : comm_monoid M] (h : ∀ (a : M), is_unit a) : comm_group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } end noncomputable_defs
8477fcb3f06e12c844223c7af0f4f26d08df0bdb
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/tactic/congr.lean
e0d6f2672b6a8b9ce8ead01978c804b9a398c966
[ "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
8,641
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import tactic.lint import tactic.ext /-! # Congruence and related tactics This file contains the tactic `congr'`, which is an extension of `congr`, and various tactics using `congr'` internally. `congr'` has some advantages over `congr`: * It turns `↔` to equalities, before trying another congr lemma * You can write `congr' n` to give the maximal depth of recursive applications. This is useful if `congr` breaks down the goal to aggressively, and the resulting goals are false. * You can write `congr' with ...` to do `congr', ext ...` in a single tactic. Other tactics in this file: * `rcongr`: repeatedly apply `congr'` and `ext.` * `convert`: like `exact`, but produces an equality goal if the type doesn't match. * `convert_to`: changes the goal, if you prove an equality between the old goal and the new goal. * `ac_change`: like `convert_to`, but uses `ac_refl` to discharge the goals. -/ open tactic setup_tactic_parser namespace tactic /-- Apply the constant `iff_of_eq` to the goal. -/ meta def apply_iff_congr_core : tactic unit := applyc ``iff_of_eq /-- The main part of the body for the loop in `congr'`. This will try to replace a goal `f x = f y` with `x = y`. Also has support for `==` and `↔`. -/ meta def congr_core' : tactic unit := do tgt ← target, apply_eq_congr_core tgt <|> apply_heq_congr_core <|> apply_iff_congr_core <|> fail "congr tactic failed" /-- The main function in `convert_to`. Changes the goal to `r` and a proof obligation that the goal is equal to `r`. -/ meta def convert_to_core (r : pexpr) : tactic unit := do tgt ← target, h ← to_expr ``(_ : %%tgt = %%r), rewrite_target h, swap /-- Attempts to prove the goal by proof irrelevance, but avoids unifying universe metavariables to do so. -/ meta def by_proof_irrel : tactic unit := do tgt ← target, @expr.const tt n [level.zero] ← pure tgt.get_app_fn, if n = ``eq then `[apply proof_irrel] else if n = ``heq then `[apply proof_irrel_heq] else failed /-- Same as the `congr` tactic, but takes an optional argument which gives the depth of recursive applications. * This is useful when `congr` is too aggressive in breaking down the goal. * For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y` and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. * If, at any point, a subgoal matches a hypothesis then the subgoal will be closed. -/ meta def congr' : option ℕ → tactic unit | o := focus1 $ assumption <|> reflexivity transparency.none <|> by_proof_irrel <|> (guard (o ≠ some 0) >> congr_core' >> all_goals' (try (congr' (nat.pred <$> o)))) <|> reflexivity namespace interactive /-- Same as the `congr` tactic, but takes an optional argument which gives the depth of recursive applications. * This is useful when `congr` is too aggressive in breaking down the goal. * For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y` and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. * If, at any point, a subgoal matches a hypothesis then the subgoal will be closed. * You can use `congr' with p (: n)?` to call `ext p (: n)?` to all subgoals generated by `congr'`. For example, if the goal is `⊢ f '' s = g '' s` then `congr' with x` generates the goal `x : α ⊢ f x = g x`. -/ meta def congr' (n : parse (with_desc "n" small_nat)?) : parse (tk "with" *> prod.mk <$> rcases_patt_parse_hi* <*> (tk ":" *> small_nat)?)? → tactic unit | none := tactic.congr' n | (some ⟨p, m⟩) := focus1 (tactic.congr' n >> all_goals' (tactic.ext p m $> ())) /-- Repeatedly and apply `congr'` and `ext`, using the the given patterns as arguments for `ext`. There are two ways this tactic stops: * `congr'` fails (makes no progress), after having already applied `ext`. * `congr'` canceled out the last usage of `ext`. In this case, the state is reverted to before the `congr'` was applied. For example, when the goal is ```lean ⊢ (λ x, f x + 3) '' s = (λ x, g x + 3) '' s ``` then `rcongr x` produces the goal ```lean x : α ⊢ f x = g x ``` This gives the same result as `congr', ext x, congr'`. In contrast, `congr'` would produce ```lean ⊢ (λ x, f x + 3) = (λ x, g x + 3) ``` and `congr' with x` (or `congr', ext x`) would produce ```lean x : α ⊢ f x + 3 = g x + 3 ``` -/ meta def rcongr : parse rcases_patt_parse_hi* → tactic unit | ps := do t ← target, qs ← try_core (tactic.ext ps none), some () ← try_core (tactic.congr' none >> (done <|> do s ← target, guard $ ¬ s =ₐ t)) | skip, done <|> rcongr (qs.lhoare ps) add_tactic_doc { name := "congr'", category := doc_category.tactic, decl_names := [`tactic.interactive.congr', `tactic.interactive.congr, `tactic.interactive.rcongr], tags := ["congruence"], inherit_description_from := `tactic.interactive.congr' } /-- The `exact e` and `refine e` tactics require a term `e` whose type is definitionally equal to the goal. `convert e` is similar to `refine e`, but the type of `e` is not required to exactly match the goal. Instead, new goals are created for differences between the type of `e` and the goal. For example, in the proof state ```lean n : ℕ, e : prime (2 * n + 1) ⊢ prime (n + n + 1) ``` the tactic `convert e` will change the goal to ```lean ⊢ n + n = 2 * n ``` In this example, the new goal can be solved using `ring`. The `convert` tactic applies congruence lemmas eagerly before reducing, therefore it can fail in cases where `exact` succeeds: ```lean def p (n : ℕ) := true example (h : p 0) : p 1 := by exact h -- succeeds example (h : p 0) : p 1 := by convert h -- fails, with leftover goal `1 = 0` ``` If `x y : t`, and an instance `subsingleton t` is in scope, then any goals of the form `x = y` are solved automatically. The syntax `convert ← e` will reverse the direction of the new goals (producing `⊢ 2 * n = n + n` in this example). Internally, `convert e` works by creating a new goal asserting that the goal equals the type of `e`, then simplifying it using `congr'`. The syntax `convert e using n` can be used to control the depth of matching (like `congr' n`). In the example, `convert e using 1` would produce a new goal `⊢ n + n + 1 = 2 * n + 1`. -/ meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := do tgt ← target, u ← infer_type tgt, r ← i_to_expr ``(%%r : (_ : %%u)), src ← infer_type r, src ← simp_lemmas.mk.dsimplify [] src {fail_if_unchanged := ff}, v ← to_expr (if sym.is_some then ``(%%src = %%tgt) else ``(%%tgt = %%src)) tt ff >>= mk_meta_var, (if sym.is_some then mk_eq_mp v r else mk_eq_mpr v r) >>= tactic.exact, gs ← get_goals, set_goals [v], try (tactic.congr' n), gs' ← get_goals, set_goals $ gs' ++ gs add_tactic_doc { name := "convert", category := doc_category.tactic, decl_names := [`tactic.interactive.convert], tags := ["congruence"] } /-- `convert_to g using n` attempts to change the current goal to `g`, but unlike `change`, it will generate equality proof obligations using `congr' n` to resolve discrepancies. `convert_to g` defaults to using `congr' 1`. `convert_to` is similar to `convert`, but `convert_to` takes a type (the desired subgoal) while `convert` takes a proof term. That is, `convert_to g using n` is equivalent to `convert (_ : g) using n`. -/ meta def convert_to (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := match n with | none := convert_to_core r >> `[congr' 1] | (some 0) := convert_to_core r | (some o) := convert_to_core r >> tactic.congr' o end /-- `ac_change g using n` is `convert_to g using n` followed by `ac_refl`. It is useful for rearranging/reassociating e.g. sums: ```lean example (a b c d e f g N : ℕ) : (a + b) + (c + d) + (e + f) + g ≤ N := begin ac_change a + d + e + f + c + g + b ≤ _, -- ⊢ a + d + e + f + c + g + b ≤ N end ``` -/ meta def ac_change (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := convert_to r n; try ac_refl add_tactic_doc { name := "convert_to", category := doc_category.tactic, decl_names := [`tactic.interactive.convert_to, `tactic.interactive.ac_change], tags := ["congruence"], inherit_description_from := `tactic.interactive.convert_to } end interactive end tactic
7ae8d05607b0a754c10ae3710bef78f4decbf3f0
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/inner_product_space/spectrum.lean
ad3cca6d234c95513359217f851137ba3d4e36b0
[ "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
11,374
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.inner_product_space.rayleigh import analysis.inner_product_space.pi_L2 /-! # Spectral theory of self-adjoint operators This file covers the spectral theory of self-adjoint operators on an inner product space. The first part of the file covers general properties, true without any condition on boundedness or compactness of the operator or finite-dimensionality of the underlying space, notably: * `is_self_adjoint.conj_eigenvalue_eq_self`: the eigenvalues are real * `is_self_adjoint.orthogonal_family_eigenspaces`: the eigenspaces are orthogonal * `is_self_adjoint.orthogonal_supr_eigenspaces`: the restriction of the operator to the mutual orthogonal complement of the eigenspaces has, itself, no eigenvectors The second part of the file covers properties of self-adjoint operators in finite dimension. Letting `T` be a self-adjoint operator on a finite-dimensional inner product space `T`, * The definition `is_self_adjoint.diagonalization` provides a linear isometry equivalence `E` to the direct sum of the eigenspaces of `T`. The theorem `is_self_adjoint.diagonalization_apply_self_apply` states that, when `T` is transferred via this equivalence to an operator on the direct sum, it acts diagonally. * The definition `is_self_adjoint.eigenvector_basis` provides an orthonormal basis for `E` consisting of eigenvectors of `T`, with `is_self_adjoint.eigenvalues` giving the corresponding list of eigenvalues, as real numbers. The definition `is_self_adjoint.diagonalization_basis` gives the associated linear isometry equivalence from `E` to Euclidean space, and the theorem `is_self_adjoint.diagonalization_basis_apply_self_apply` states that, when `T` is transferred via this equivalence to an operator on Euclidean space, it acts diagonally. These are forms of the *diagonalization theorem* for self-adjoint operators on finite-dimensional inner product spaces. ## TODO Spectral theory for compact self-adjoint operators, bounded self-adjoint operators. ## Tags self-adjoint operator, spectral theorem, diagonalization theorem -/ variables {𝕜 : Type*} [is_R_or_C 𝕜] [dec_𝕜 : decidable_eq 𝕜] variables {E : Type*} [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y open_locale big_operators complex_conjugate open module.End namespace inner_product_space namespace is_self_adjoint variables {T : E →ₗ[𝕜] E} (hT : is_self_adjoint T) include hT /-- A self-adjoint operator preserves orthogonal complements of its eigenspaces. -/ lemma invariant_orthogonal_eigenspace (μ : 𝕜) (v : E) (hv : v ∈ (eigenspace T μ)ᗮ) : T v ∈ (eigenspace T μ)ᗮ := begin intros w hw, have : T w = (μ:𝕜) • w := by rwa mem_eigenspace_iff at hw, simp [← hT w, this, inner_smul_left, hv w hw] end /-- The eigenvalues of a self-adjoint operator are real. -/ lemma conj_eigenvalue_eq_self {μ : 𝕜} (hμ : has_eigenvalue T μ) : conj μ = μ := begin obtain ⟨v, hv₁, hv₂⟩ := hμ.exists_has_eigenvector, rw mem_eigenspace_iff at hv₁, simpa [hv₂, inner_smul_left, inner_smul_right, hv₁] using hT v v end /-- The eigenspaces of a self-adjoint operator are mutually orthogonal. -/ lemma orthogonal_family_eigenspaces : @orthogonal_family 𝕜 _ _ _ _ (λ μ, eigenspace T μ) _ (λ μ, (eigenspace T μ).subtypeₗᵢ) := begin rintros μ ν hμν ⟨v, hv⟩ ⟨w, hw⟩, by_cases hv' : v = 0, { simp [hv'] }, have H := hT.conj_eigenvalue_eq_self (has_eigenvalue_of_has_eigenvector ⟨hv, hv'⟩), rw mem_eigenspace_iff at hv hw, refine or.resolve_left _ hμν.symm, simpa [inner_smul_left, inner_smul_right, hv, hw, H] using (hT v w).symm end lemma orthogonal_family_eigenspaces' : @orthogonal_family 𝕜 _ _ _ _ (λ μ : eigenvalues T, eigenspace T μ) _ (λ μ, (eigenspace T μ).subtypeₗᵢ) := hT.orthogonal_family_eigenspaces.comp subtype.coe_injective /-- The mutual orthogonal complement of the eigenspaces of a self-adjoint operator on an inner product space is an invariant subspace of the operator. -/ lemma orthogonal_supr_eigenspaces_invariant ⦃v : E⦄ (hv : v ∈ (⨆ μ, eigenspace T μ)ᗮ) : T v ∈ (⨆ μ, eigenspace T μ)ᗮ := begin rw ← submodule.infi_orthogonal at ⊢ hv, exact T.infi_invariant hT.invariant_orthogonal_eigenspace v hv end /-- The mutual orthogonal complement of the eigenspaces of a self-adjoint operator on an inner product space has no eigenvalues. -/ lemma orthogonal_supr_eigenspaces (μ : 𝕜) : eigenspace (T.restrict hT.orthogonal_supr_eigenspaces_invariant) μ = ⊥ := begin set p : submodule 𝕜 E := (⨆ μ, eigenspace T μ)ᗮ, refine eigenspace_restrict_eq_bot hT.orthogonal_supr_eigenspaces_invariant _, have H₂ : p ≤ (eigenspace T μ)ᗮ := submodule.orthogonal_le (le_supr _ _), exact (eigenspace T μ).orthogonal_disjoint.mono_right H₂ end /-! ### Finite-dimensional theory -/ variables [finite_dimensional 𝕜 E] /-- The mutual orthogonal complement of the eigenspaces of a self-adjoint operator on a finite-dimensional inner product space is trivial. -/ lemma orthogonal_supr_eigenspaces_eq_bot : (⨆ μ, eigenspace T μ)ᗮ = ⊥ := begin have hT' : is_self_adjoint _ := hT.restrict_invariant hT.orthogonal_supr_eigenspaces_invariant, -- a self-adjoint operator on a nontrivial inner product space has an eigenvalue haveI := hT'.subsingleton_of_no_eigenvalue_finite_dimensional hT.orthogonal_supr_eigenspaces, exact submodule.eq_bot_of_subsingleton _, end lemma orthogonal_supr_eigenspaces_eq_bot' : (⨆ μ : eigenvalues T, eigenspace T μ)ᗮ = ⊥ := show (⨆ μ : {μ // (eigenspace T μ) ≠ ⊥}, eigenspace T μ)ᗮ = ⊥, by rw [supr_ne_bot_subtype, hT.orthogonal_supr_eigenspaces_eq_bot] include dec_𝕜 /-- The eigenspaces of a self-adjoint operator on a finite-dimensional inner product space `E` give an internal direct sum decomposition of `E`. -/ lemma direct_sum_submodule_is_internal : direct_sum.submodule_is_internal (λ μ : eigenvalues T, eigenspace T μ) := hT.orthogonal_family_eigenspaces'.submodule_is_internal_iff.mpr hT.orthogonal_supr_eigenspaces_eq_bot' section version1 /-- Isometry from an inner product space `E` to the direct sum of the eigenspaces of some self-adjoint operator `T` on `E`. -/ noncomputable def diagonalization : E ≃ₗᵢ[𝕜] pi_Lp 2 (λ μ : eigenvalues T, eigenspace T μ) := hT.direct_sum_submodule_is_internal.isometry_L2_of_orthogonal_family hT.orthogonal_family_eigenspaces' @[simp] lemma diagonalization_symm_apply (w : pi_Lp 2 (λ μ : eigenvalues T, eigenspace T μ)) : hT.diagonalization.symm w = ∑ μ, w μ := hT.direct_sum_submodule_is_internal.isometry_L2_of_orthogonal_family_symm_apply hT.orthogonal_family_eigenspaces' w /-- *Diagonalization theorem*, *spectral theorem*; version 1: A self-adjoint operator `T` on a finite-dimensional inner product space `E` acts diagonally on the decomposition of `E` into the direct sum of the eigenspaces of `T`. -/ lemma diagonalization_apply_self_apply (v : E) (μ : eigenvalues T) : hT.diagonalization (T v) μ = (μ : 𝕜) • hT.diagonalization v μ := begin suffices : ∀ w : pi_Lp 2 (λ μ : eigenvalues T, eigenspace T μ), (T (hT.diagonalization.symm w)) = hT.diagonalization.symm (λ μ, (μ : 𝕜) • w μ), { simpa [linear_isometry_equiv.symm_apply_apply, -is_self_adjoint.diagonalization_symm_apply] using congr_arg (λ w, hT.diagonalization w μ) (this (hT.diagonalization v)) }, intros w, have hwT : ∀ μ : eigenvalues T, T (w μ) = (μ : 𝕜) • w μ, { intros μ, simpa [mem_eigenspace_iff] using (w μ).prop }, simp [hwT], end end version1 section version2 variables {n : ℕ} (hn : finite_dimensional.finrank 𝕜 E = n) /-- A choice of orthonormal basis of eigenvectors for self-adjoint operator `T` on a finite-dimensional inner product space `E`. TODO Postcompose with a permutation so that these eigenvectors are listed in increasing order of eigenvalue. -/ noncomputable def eigenvector_basis : basis (fin n) 𝕜 E := hT.direct_sum_submodule_is_internal.subordinate_orthonormal_basis hn lemma eigenvector_basis_orthonormal : orthonormal 𝕜 (hT.eigenvector_basis hn) := hT.direct_sum_submodule_is_internal.subordinate_orthonormal_basis_orthonormal hn hT.orthogonal_family_eigenspaces' /-- The sequence of real eigenvalues associated to the standard orthonormal basis of eigenvectors for a self-adjoint operator `T` on `E`. TODO Postcompose with a permutation so that these eigenvalues are listed in increasing order. -/ noncomputable def eigenvalues (i : fin n) : ℝ := @is_R_or_C.re 𝕜 _ $ hT.direct_sum_submodule_is_internal.subordinate_orthonormal_basis_index hn i lemma has_eigenvector_eigenvector_basis (i : fin n) : has_eigenvector T (hT.eigenvalues hn i) (hT.eigenvector_basis hn i) := begin let v : E := hT.eigenvector_basis hn i, let μ : 𝕜 := hT.direct_sum_submodule_is_internal.subordinate_orthonormal_basis_index hn i, change has_eigenvector T (is_R_or_C.re μ) v, have key : has_eigenvector T μ v, { have H₁ : v ∈ eigenspace T μ, { exact hT.direct_sum_submodule_is_internal.subordinate_orthonormal_basis_subordinate hn i }, have H₂ : v ≠ 0 := (hT.eigenvector_basis_orthonormal hn).ne_zero i, exact ⟨H₁, H₂⟩ }, have re_μ : ↑(is_R_or_C.re μ) = μ, { rw ← is_R_or_C.eq_conj_iff_re, exact hT.conj_eigenvalue_eq_self (has_eigenvalue_of_has_eigenvector key) }, simpa [re_μ] using key, end attribute [irreducible] eigenvector_basis eigenvalues @[simp] lemma apply_eigenvector_basis (i : fin n) : T (hT.eigenvector_basis hn i) = (hT.eigenvalues hn i : 𝕜) • hT.eigenvector_basis hn i := mem_eigenspace_iff.mp (hT.has_eigenvector_eigenvector_basis hn i).1 /-- An isometry from an inner product space `E` to Euclidean space, induced by a choice of orthonormal basis of eigenvectors for a self-adjoint operator `T` on `E`. -/ noncomputable def diagonalization_basis : E ≃ₗᵢ[𝕜] euclidean_space 𝕜 (fin n) := (hT.eigenvector_basis hn).isometry_euclidean_of_orthonormal (hT.eigenvector_basis_orthonormal hn) @[simp] lemma diagonalization_basis_symm_apply (w : euclidean_space 𝕜 (fin n)) : (hT.diagonalization_basis hn).symm w = ∑ i, w i • hT.eigenvector_basis hn i := by simp [diagonalization_basis] /-- *Diagonalization theorem*, *spectral theorem*; version 2: A self-adjoint operator `T` on a finite-dimensional inner product space `E` acts diagonally on the identification of `E` with Euclidean space induced by an orthonormal basis of eigenvectors of `T`. -/ lemma diagonalization_basis_apply_self_apply (v : E) (i : fin n) : hT.diagonalization_basis hn (T v) i = hT.eigenvalues hn i * hT.diagonalization_basis hn v i := begin suffices : ∀ w : euclidean_space 𝕜 (fin n), T ((hT.diagonalization_basis hn).symm w) = (hT.diagonalization_basis hn).symm (λ i, hT.eigenvalues hn i * w i), { simpa [-diagonalization_basis_symm_apply] using congr_arg (λ v, hT.diagonalization_basis hn v i) (this (hT.diagonalization_basis hn v)) }, intros w, simp [mul_comm, mul_smul], end end version2 end is_self_adjoint end inner_product_space
6c35ea0890a7d78b3db24ee87056b1ddfa24e984
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/mv_polynomial/cardinal.lean
ff7a3335a6beef8c1807558c073cec036d86237f
[ "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,046
lean
/- Copyright (c) 2021 Chris Hughes, Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Junyan Xu -/ import data.finsupp.fintype import data.mv_polynomial.equiv import set_theory.cardinal.ordinal /-! # Cardinality of Multivariate Polynomial Ring The main result in this file is `mv_polynomial.cardinal_mk_le_max`, which says that the cardinality of `mv_polynomial σ R` is bounded above by the maximum of `#R`, `#σ` and `ℵ₀`. -/ universes u v open cardinal open_locale cardinal namespace mv_polynomial section two_universes variables {σ : Type u} {R : Type v} [comm_semiring R] @[simp] lemma cardinal_mk_eq_max_lift [nonempty σ] [nontrivial R] : #(mv_polynomial σ R) = max (max (cardinal.lift.{u} $ #R) $ cardinal.lift.{v} $ #σ) ℵ₀ := (mk_finsupp_lift_of_infinite _ R).trans $ by rw [mk_finsupp_nat, max_assoc, lift_max, lift_aleph_0, max_comm] @[simp] lemma cardinal_mk_eq_lift [is_empty σ] : #(mv_polynomial σ R) = cardinal.lift.{u} (#R) := ((is_empty_ring_equiv R σ).to_equiv.trans equiv.ulift.{u}.symm).cardinal_eq lemma cardinal_lift_mk_le_max {σ : Type u} {R : Type v} [comm_semiring R] : #(mv_polynomial σ R) ≤ max (max (cardinal.lift.{u} $ #R) $ cardinal.lift.{v} $ #σ) ℵ₀ := begin casesI subsingleton_or_nontrivial R, { exact (mk_eq_one _).trans_le (le_max_of_le_right one_le_aleph_0) }, casesI is_empty_or_nonempty σ, { exact cardinal_mk_eq_lift.trans_le (le_max_of_le_left $ le_max_left _ _) }, { exact cardinal_mk_eq_max_lift.le }, end end two_universes variables {σ R : Type u} [comm_semiring R] lemma cardinal_mk_eq_max [nonempty σ] [nontrivial R] : #(mv_polynomial σ R) = max (max (#R) (#σ)) ℵ₀ := by simp /-- The cardinality of the multivariate polynomial ring, `mv_polynomial σ R` is at most the maximum of `#R`, `#σ` and `ℵ₀` -/ lemma cardinal_mk_le_max : #(mv_polynomial σ R) ≤ max (max (#R) (#σ)) ℵ₀ := cardinal_lift_mk_le_max.trans $ by rw [lift_id, lift_id] end mv_polynomial
77ee3542c9c5d9df289f0ae63184ed2ccc72eb4a
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/353.lean
bc3ffd78ef9d6edf4d8a93917cfbae50ac4fb8c0
[ "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
478
lean
class ArrSort (α : Sort u1) where Arr : α → α → Sort u2 class Arr (α : Sort u1) (γ : Sort u2) where Arr : α → α → γ infix:70 " ~> " => Arr.Arr @[defaultInstance] instance inst1 {α : Sort _} [ArrSort α] : Arr α (Sort _) := { Arr := ArrSort.Arr } instance inst2 : ArrSort Prop := { Arr := λ a b => a → b } set_option pp.all true set_option trace.Meta.debug true structure Function' where map : ∀ {a₁ a₂ : Bool}, (a₁ ~> a₂) ~> (a₁ ~> a₂)
d0f13cafa569de37ad7ac19948273c4ca5245adc
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/analysis/calculus/inverse.lean
1e91b9213fe3dc837e35f36f741a69b715a7604f
[ "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
21,386
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov. -/ import analysis.calculus.deriv import topology.local_homeomorph import topology.metric_space.contracting /-! # Inverse function theorem In this file we prove the inverse function theorem. It says that if a map `f : E → F` has an invertible strict derivative `f'` at `a`, then it is locally invertible, and the inverse function has derivative `f' ⁻¹`. We define `has_strict_deriv_at.to_local_homeomorph` that repacks a function `f` with a `hf : has_strict_fderiv_at f f' a`, `f' : E ≃L[𝕜] F`, into a `local_homeomorph`. The `to_fun` of this `local_homeomorph` is `defeq` to `f`, so one can apply theorems about `local_homeomorph` to `hf.to_local_homeomorph f`, and get statements about `f`. Then we define `has_strict_fderiv_at.local_inverse` to be the `inv_fun` of this `local_homeomorph`, and prove two versions of the inverse function theorem: * `has_strict_fderiv_at.to_local_inverse`: if `f` has an invertible derivative `f'` at `a` in the strict sense (`hf`), then `hf.local_inverse f f' a` has derivative `f'.symm` at `f a` in the strict sense; * `has_strict_fderiv_at.to_local_left_inverse`: if `f` has an invertible derivative `f'` at `a` in the strict sense and `g` is locally left inverse to `f` near `a`, then `g` has derivative `f'.symm` at `f a` in the strict sense. In the one-dimensional case we reformulate these theorems in terms of `has_strict_deriv_at` and `f'⁻¹`. Some other versions of the theorem assuming that we already know the inverse function are formulated in `fderiv.lean` and `deriv.lean` ## Notations In the section about `approximates_linear_on` we introduce some `local notation` to make formulas shorter: * by `N` we denote `∥f'⁻¹∥`; * by `g` we denote the auxiliary contracting map `x ↦ x + f'.symm (y - f x)` used to prove that `{x | f x = y}` is nonempty. ## Tags derivative, strictly differentiable, inverse function -/ open function set filter metric open_locale topological_space classical nnreal noncomputable theory 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] variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G'] open asymptotics filter metric set open continuous_linear_map (id) /-! ### Non-linear maps approximating close to affine maps In this section we study a map `f` such that `∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥` on an open set `s`, where `f' : E ≃L[𝕜] F` is a continuous linear equivalence and `c < ∥f'⁻¹∥`. Maps of this type behave like `f a + f' (x - a)` near each `a ∈ s`. If `E` is a complete space, we prove that the image `f '' s` is open, and `f` is a homeomorphism between `s` and `f '' s`. More precisely, we define `approximates_linear_on.to_local_homeomorph` to be a `local_homeomorph` with `to_fun = f`, `source = s`, and `target = f '' s`. Maps of this type naturally appear in the proof of the inverse function theorem (see next section), and `approximates_linear_on.to_local_homeomorph` will imply that the locally inverse function exists. We define this auxiliary notion to split the proof of the inverse function theorem into small lemmas. This approach makes it possible - to prove a lower estimate on the size of the domain of the inverse function; - to reuse parts of the proofs in the case if a function is not strictly differentiable. E.g., for a function `f : E × F → G` with estimates on `f x y₁ - f x y₂` but not on `f x₁ y - f x₂ y`. -/ /-- We say that `f` approximates a continuous linear map `f'` on `s` with constant `c`, if `∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥` whenever `x, y ∈ s`. This predicate is defined to facilitate the splitting of the inverse function theorem into small lemmas. Some of these lemmas can be useful, e.g., to prove that the inverse function is defined on a specific set. -/ def approximates_linear_on (f : E → F) (f' : E →L[𝕜] F) (s : set E) (c : ℝ≥0) : Prop := ∀ (x ∈ s) (y ∈ s), ∥f x - f y - f' (x - y)∥ ≤ c * ∥x - y∥ namespace approximates_linear_on variables [cs : complete_space E] {f : E → F} /-! First we prove some properties of a function that `approximates_linear_on` a (not necessarily invertible) continuous linear map. -/ section variables {f' : E →L[𝕜] F} {s t : set E} {c c' : ℝ≥0} theorem mono_num (hc : c ≤ c') (hf : approximates_linear_on f f' s c) : approximates_linear_on f f' s c' := λ x hx y hy, le_trans (hf x hx y hy) (mul_le_mul_of_nonneg_right hc $ norm_nonneg _) theorem mono_set (hst : s ⊆ t) (hf : approximates_linear_on f f' t c) : approximates_linear_on f f' s c := λ x hx y hy, hf x (hst hx) y (hst hy) lemma lipschitz_sub (hf : approximates_linear_on f f' s c) : lipschitz_with c (λ x : s, f x - f' x) := begin refine lipschitz_with.of_dist_le_mul (λ x y, _), rw [dist_eq_norm, subtype.dist_eq, dist_eq_norm], convert hf x x.2 y y.2 using 2, rw [f'.map_sub], abel end protected lemma lipschitz (hf : approximates_linear_on f f' s c) : lipschitz_with (nnnorm f' + c) (s.restrict f) := by simpa only [restrict_apply, add_sub_cancel'_right] using (f'.lipschitz.restrict s).add hf.lipschitz_sub protected lemma continuous (hf : approximates_linear_on f f' s c) : continuous (s.restrict f) := hf.lipschitz.continuous protected lemma continuous_on (hf : approximates_linear_on f f' s c) : continuous_on f s := continuous_on_iff_continuous_restrict.2 hf.continuous end /-! From now on we assume that `f` approximates an invertible continuous linear map `f : E ≃L[𝕜] F`. We also assume that either `E = {0}`, or `c < ∥f'⁻¹∥⁻¹`. We use `N` as an abbreviation for `∥f'⁻¹∥`. -/ variables {f' : E ≃L[𝕜] F} {s : set E} {c : ℝ≥0} local notation `N` := nnnorm (f'.symm : F →L[𝕜] E) protected lemma antilipschitz (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : antilipschitz_with (N⁻¹ - c)⁻¹ (s.restrict f) := begin cases hc with hE hc, { haveI : subsingleton s := ⟨λ x y, subtype.eq $ @subsingleton.elim _ hE _ _⟩, exact antilipschitz_with.of_subsingleton }, convert (f'.antilipschitz.restrict s).add_lipschitz_with hf.lipschitz_sub hc, simp [restrict] end protected lemma injective (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : injective (s.restrict f) := (hf.antilipschitz hc).injective protected lemma inj_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : inj_on f s := inj_on_iff_injective.2 $ hf.injective hc /-- A map approximating a linear equivalence on a set defines a local equivalence on this set. Should not be used outside of this file, because it is superseded by `to_local_homeomorph` below. This is a first step towards the inverse function. -/ def to_local_equiv (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : local_equiv E F := by haveI : nonempty E := ⟨0⟩; exact (hf.inj_on hc).to_local_equiv _ _ /-- The inverse function is continuous on `f '' s`. Use properties of `local_homeomorph` instead. -/ lemma inverse_continuous_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) : continuous_on (hf.to_local_equiv hc).symm (f '' s) := begin apply continuous_on_iff_continuous_restrict.2, refine ((hf.antilipschitz hc).to_right_inv_on' _ (hf.to_local_equiv hc).right_inv').continuous, exact (λ x hx, (hf.to_local_equiv hc).map_target hx) end /-! Now we prove that `f '' s` is an open set. This follows from the fact that the restriction of `f` on `s` is an open map. More precisely, we show that the image of a closed ball $$\bar B(a, ε) ⊆ s$$ under `f` includes the closed ball $$\bar B\left(f(a), \frac{ε}{∥{f'}⁻¹∥⁻¹-c}\right)$$. In order to do this, we introduce an auxiliary map $$g_y(x) = x + {f'}⁻¹ (y - f x)$$. Provided that $$∥y - f a∥ ≤ \frac{ε}{∥{f'}⁻¹∥⁻¹-c}$$, we prove that $$g_y$$ contracts in $$\bar B(a, ε)$$ and `f` sends the fixed point of $$g_y$$ to `y`. -/ section variables (f f') /-- Iterations of this map converge to `f⁻¹ y`. The formula is very similar to the one used in Newton's method, but we use the same `f'.symm` for all `y` instead of evaluating the derivative at each point along the orbit. -/ def inverse_approx_map (y : F) (x : E) : E := x + f'.symm (y - f x) end section inverse_approx_map variables (y : F) {x x' : E} {ε : ℝ} local notation `g` := inverse_approx_map f f' y lemma inverse_approx_map_sub (x x' : E) : g x - g x' = (x - x') - f'.symm (f x - f x') := by { simp only [inverse_approx_map, f'.symm.map_sub], abel } lemma inverse_approx_map_dist_self (x : E) : dist (g x) x = dist (f'.symm $ f x) (f'.symm y) := by simp only [inverse_approx_map, dist_eq_norm, f'.symm.map_sub, add_sub_cancel', norm_sub_rev] lemma inverse_approx_map_dist_self_le (x : E) : dist (g x) x ≤ N * dist (f x) y := by { rw inverse_approx_map_dist_self, exact f'.symm.lipschitz.dist_le_mul (f x) y } lemma inverse_approx_map_fixed_iff {x : E} : g x = x ↔ f x = y := by rw [← dist_eq_zero, inverse_approx_map_dist_self, dist_eq_zero, f'.symm.injective.eq_iff] lemma inverse_approx_map_contracts_on (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) {x x'} (hx : x ∈ s) (hx' : x' ∈ s) : dist (g x) (g x') ≤ N * c * dist x x' := begin rw [dist_eq_norm, dist_eq_norm, inverse_approx_map_sub, norm_sub_rev], suffices : ∥f'.symm (f x - f x' - f' (x - x'))∥ ≤ N * (c * ∥x - x'∥), by simpa only [f'.symm.map_sub, f'.symm_apply_apply, mul_assoc] using this, exact (f'.symm : F →L[𝕜] E).le_op_norm_of_le (hf x hx x' hx') end variable {y} lemma inverse_approx_map_maps_to (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) {b : E} (hb : b ∈ s) (hε : closed_ball b ε ⊆ s) (hy : y ∈ closed_ball (f b) ((N⁻¹ - c) * ε)) : maps_to g (closed_ball b ε) (closed_ball b ε) := begin cases hc with hE hc, { exactI λ x hx, mem_preimage.2 (subsingleton.elim x (g x) ▸ hx) }, assume x hx, simp only [subset_def, mem_closed_ball, mem_preimage] at hx hy ⊢, rw [dist_comm] at hy, calc dist (inverse_approx_map f f' y x) b ≤ dist (inverse_approx_map f f' y x) (inverse_approx_map f f' y b) + dist (inverse_approx_map f f' y b) b : dist_triangle _ _ _ ... ≤ N * c * dist x b + N * dist (f b) y : add_le_add (hf.inverse_approx_map_contracts_on y (hε hx) hb) (inverse_approx_map_dist_self_le _ _) ... ≤ N * c * ε + N * ((N⁻¹ - c) * ε) : add_le_add (mul_le_mul_of_nonneg_left hx (mul_nonneg (nnreal.coe_nonneg _) c.coe_nonneg)) (mul_le_mul_of_nonneg_left hy (nnreal.coe_nonneg _)) ... = N * (c + (N⁻¹ - c)) * ε : by simp only [mul_add, add_mul, mul_assoc] ... = ε : by { rw [add_sub_cancel'_right, mul_inv_cancel, one_mul], exact ne_of_gt (inv_pos.1 $ lt_of_le_of_lt c.coe_nonneg hc) } end end inverse_approx_map include cs variable {ε : ℝ} theorem surj_on_closed_ball (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) {b : E} (ε0 : 0 ≤ ε) (hε : closed_ball b ε ⊆ s) : surj_on f (closed_ball b ε) (closed_ball (f b) ((N⁻¹ - c) * ε)) := begin cases hc with hE hc, { resetI, haveI hF : subsingleton F := f'.symm.to_linear_equiv.to_equiv.subsingleton, intros y hy, exact ⟨b, mem_closed_ball_self ε0, subsingleton.elim _ _⟩ }, intros y hy, have : contracting_with (N * c) ((hf.inverse_approx_map_maps_to (or.inr hc) (hε $ mem_closed_ball_self ε0) hε hy).restrict _ _ _), { split, { rwa [mul_comm, ← nnreal.lt_inv_iff_mul_lt], exact ne_of_gt (inv_pos.1 $ lt_of_le_of_lt c.coe_nonneg hc) }, { exact lipschitz_with.of_dist_le_mul (λ x x', hf.inverse_approx_map_contracts_on y (hε x.mem) (hε x'.mem)) } }, refine ⟨this.efixed_point' _ _ _ b (mem_closed_ball_self ε0) (edist_lt_top _ _), _, _⟩, { exact is_complete_of_is_closed is_closed_ball }, { apply contracting_with.efixed_point_mem' }, { exact (inverse_approx_map_fixed_iff y).1 (this.efixed_point_is_fixed' _ _ _ _) } end section variables (f s) /-- Given a function `f` that approximates a linear equivalence on an open set `s`, returns a local homeomorph with `to_fun = f` and `source = s`. -/ def to_local_homeomorph (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : local_homeomorph E F := { to_local_equiv := hf.to_local_equiv hc, open_source := hs, open_target := begin cases hc with hE hc, { resetI, haveI hF : subsingleton F := f'.to_linear_equiv.to_equiv.symm.subsingleton, apply is_open_discrete }, change is_open (f '' s), simp only [is_open_iff_mem_nhds, nhds_basis_closed_ball.mem_iff, ball_image_iff] at hs ⊢, intros x hx, rcases hs x hx with ⟨ε, ε0, hε⟩, refine ⟨(N⁻¹ - c) * ε, mul_pos (sub_pos.2 hc) ε0, _⟩, exact (hf.surj_on_closed_ball (or.inr hc) (le_of_lt ε0) hε).mono hε (subset.refl _) end, continuous_to_fun := hf.continuous_on, continuous_inv_fun := hf.inverse_continuous_on hc } end @[simp] lemma to_local_homeomorph_coe (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : (hf.to_local_homeomorph f s hc hs : E → F) = f := rfl @[simp] lemma to_local_homeomorph_source (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : (hf.to_local_homeomorph f s hc hs).source = s := rfl @[simp] lemma to_local_homeomorph_target (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) : (hf.to_local_homeomorph f s hc hs).target = f '' s := rfl lemma closed_ball_subset_target (hf : approximates_linear_on f (f' : E →L[𝕜] F) s c) (hc : subsingleton E ∨ c < N⁻¹) (hs : is_open s) {b : E} (ε0 : 0 ≤ ε) (hε : closed_ball b ε ⊆ s) : closed_ball (f b) ((N⁻¹ - c) * ε) ⊆ (hf.to_local_homeomorph f s hc hs).target := (hf.surj_on_closed_ball hc ε0 hε).mono hε (subset.refl _) end approximates_linear_on /-! ### Inverse function theorem Now we prove the inverse function theorem. Let `f : E → F` be a map defined on a complete vector space `E`. Assume that `f` has an invertible derivative `f' : E ≃L[𝕜] F` at `a : E` in the strict sense. Then `f` approximates `f'` in the sense of `approximates_linear_on` on an open neighborhood of `a`, and we can apply `approximates_linear_on.to_local_homeomorph` to construct the inverse function. -/ namespace has_strict_fderiv_at /-- If `f` has derivative `f'` at `a` in the strict sense and `c > 0`, then `f` approximates `f'` with constant `c` on some neighborhood of `a`. -/ lemma approximates_deriv_on_nhds {f : E → F} {f' : E →L[𝕜] F} {a : E} (hf : has_strict_fderiv_at f f' a) {c : ℝ≥0} (hc : subsingleton E ∨ 0 < c) : ∃ s ∈ 𝓝 a, approximates_linear_on f f' s c := begin cases hc with hE hc, { refine ⟨univ, mem_nhds_sets is_open_univ trivial, λ x hx y hy, _⟩, simp [@subsingleton.elim E hE x y] }, have := hf.def hc, rw [nhds_prod_eq, filter.eventually, mem_prod_same_iff] at this, rcases this with ⟨s, has, hs⟩, exact ⟨s, has, λ x hx y hy, hs (mk_mem_prod hx hy)⟩ end variables [cs : complete_space E] {f : E → F} {f' : E ≃L[𝕜] F} {a : E} lemma approximates_deriv_on_open_nhds (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : ∃ (s : set E) (hs : a ∈ s ∧ is_open s), approximates_linear_on f (f' : E →L[𝕜] F) s ((nnnorm (f'.symm : F →L[𝕜] E))⁻¹ / 2) := begin refine ((nhds_basis_opens a).exists_iff _).1 _, exact (λ s t, approximates_linear_on.mono_set), exact (hf.approximates_deriv_on_nhds $ f'.subsingleton_or_nnnorm_symm_pos.imp id $ λ hf', nnreal.half_pos $ nnreal.inv_pos.2 $ hf') end include cs variable (f) /-- Given a function with an invertible strict derivative at `a`, returns a `local_homeomorph` with `to_fun = f` and `a ∈ source`. This is a part of the inverse function theorem. The other part `has_strict_fderiv_at.to_local_inverse` states that the inverse function of this `local_homeomorph` has derivative `f'.symm`. -/ def to_local_homeomorph (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : local_homeomorph E F := approximates_linear_on.to_local_homeomorph f (classical.some hf.approximates_deriv_on_open_nhds) (classical.some_spec hf.approximates_deriv_on_open_nhds).snd (f'.subsingleton_or_nnnorm_symm_pos.imp id $ λ hf', nnreal.half_lt_self $ ne_of_gt $ nnreal.inv_pos.2 $ hf') (classical.some_spec hf.approximates_deriv_on_open_nhds).fst.2 variable {f} @[simp] lemma to_local_homeomorph_coe (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : (hf.to_local_homeomorph f : E → F) = f := rfl lemma mem_to_local_homeomorph_source (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : a ∈ (hf.to_local_homeomorph f).source := (classical.some_spec hf.approximates_deriv_on_open_nhds).fst.1 lemma image_mem_to_local_homeomorph_target (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : f a ∈ (hf.to_local_homeomorph f).target := (hf.to_local_homeomorph f).map_source hf.mem_to_local_homeomorph_source variables (f f' a) /-- Given a function `f` with an invertible derivative, returns a function that is locally inverse to `f`. -/ def local_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : F → E := (hf.to_local_homeomorph f).symm variables {f f' a} lemma eventually_left_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : ∀ᶠ x in 𝓝 a, hf.local_inverse f f' a (f x) = x := (hf.to_local_homeomorph f).eventually_left_inverse hf.mem_to_local_homeomorph_source lemma local_inverse_apply_image (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : hf.local_inverse f f' a (f a) = a := hf.eventually_left_inverse.self_of_nhds lemma eventually_right_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : ∀ᶠ y in 𝓝 (f a), f (hf.local_inverse f f' a y) = y := (hf.to_local_homeomorph f).eventually_right_inverse' hf.mem_to_local_homeomorph_source lemma local_inverse_continuous_at (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : continuous_at (hf.local_inverse f f' a) (f a) := (hf.to_local_homeomorph f).continuous_at_symm hf.image_mem_to_local_homeomorph_target /-- If `f` has an invertible derivative `f'` at `a` in the sense of strict differentiability `(hf)`, then the inverse function `hf.local_inverse f` has derivative `f'.symm` at `f a`. -/ theorem to_local_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) : has_strict_fderiv_at (hf.local_inverse f f' a) (f'.symm : F →L[𝕜] E) (f a) := begin have : has_strict_fderiv_at f (f' : E →L[𝕜] F) (hf.local_inverse f f' a (f a)), { rwa hf.local_inverse_apply_image }, exact this.of_local_left_inverse hf.local_inverse_continuous_at hf.eventually_right_inverse end /-- If `f : E → F` has an invertible derivative `f'` at `a` in the sense of strict differentiability and `g (f x) = x` in a neighborhood of `a`, then `g` has derivative `f'.symm` at `f a`. For a version assuming `f (g y) = y` and continuity of `g` at `f a` but not `[complete_space E]` see `of_local_left_inverse`. -/ theorem to_local_left_inverse (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) a) {g : F → E} (hg : ∀ᶠ x in 𝓝 a, g (f x) = x) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) (f a) := begin apply hf.to_local_inverse.congr_of_mem_sets, have := ((hf.to_local_homeomorph f).tendsto_symm hf.mem_to_local_homeomorph_source).eventually hg, refine this.mp (hf.eventually_right_inverse.mono $ λ y hy hy', _), exact hy'.symm.trans (congr_arg g hy) end end has_strict_fderiv_at /-! ### Inverse function theorem, 1D case In this case we prove a version of the inverse function theorem for maps `f : 𝕜 → 𝕜`. We use `continuous_linear_equiv.units_equiv_aut` to translate `has_strict_deriv_at f f' a` and `f' ≠ 0` into `has_strict_fderiv_at f (_ : 𝕜 ≃L[𝕜] 𝕜) a`. -/ namespace has_strict_deriv_at variables [cs : complete_space 𝕜] {f : 𝕜 → 𝕜} {f' a : 𝕜} (hf : has_strict_deriv_at f f' a) (hf' : f' ≠ 0) include cs variables (f f' a) /-- A function that is inverse to `f` near `a`. -/ @[reducible] def local_inverse : 𝕜 → 𝕜 := (hf.has_strict_fderiv_at_equiv hf').local_inverse _ _ _ variables {f f' a} theorem to_local_inverse : has_strict_deriv_at (hf.local_inverse f f' a hf') f'⁻¹ (f a) := (hf.has_strict_fderiv_at_equiv hf').to_local_inverse theorem to_local_left_inverse {g : 𝕜 → 𝕜} (hg : ∀ᶠ x in 𝓝 a, g (f x) = x) : has_strict_deriv_at g f'⁻¹ (f a) := (hf.has_strict_fderiv_at_equiv hf').to_local_left_inverse hg end has_strict_deriv_at
b52ba6d808a8e77a350e3dab9cc10176bd43fc12
fcf3ffa92a3847189ca669cb18b34ef6b2ec2859
/src/world6/level3.lean
bd72573157ccb010d7c7ba9bcf9b06fc6c8dc152
[ "Apache-2.0" ]
permissive
nomoid/lean-proofs
4a80a97888699dee42b092b7b959b22d9aa0c066
b9f03a24623d1a1d111d6c2bbf53c617e2596d6a
refs/heads/master
1,674,955,317,080
1,607,475,706,000
1,607,475,706,000
314,104,281
0
0
null
null
null
null
UTF-8
Lean
false
false
198
lean
lemma maze (P Q R S T U: Prop) (p : P) (h : P → Q) (i : Q → R) (j : Q → T) (k : S → T) (l : T → U) : U := begin have q := h(p), have t := j(q), have u := l(t), exact u, end
c4e3cf5cd26eef1abb3506a734e0353d4b8a84e2
8b9f17008684d796c8022dab552e42f0cb6fb347
/hott/hit/circle.hlean
694aa8208e47e69ea0d5c555f0101fb5fcd4b9db
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,698
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: hit.circle Authors: Floris van Doorn Declaration of the circle -/ import .sphere open eq suspension bool sphere_index equiv definition circle [reducible] := suspension bool --redefine this as sphere 1 namespace circle definition base1 : circle := !north definition base2 : circle := !south definition seg1 : base1 = base2 := merid tt definition seg2 : base2 = base1 := (merid ff)⁻¹ definition base : circle := base1 definition loop : base = base := seg1 ⬝ seg2 definition rec2 {P : circle → Type} (Pb1 : P base1) (Pb2 : P base2) (Ps1 : seg1 ▹ Pb1 = Pb2) (Ps2 : seg2 ▹ Pb2 = Pb1) (x : circle) : P x := begin fapply (suspension.rec_on x), { exact Pb1}, { exact Pb2}, { intro b, cases b, apply tr_eq_of_eq_inv_tr, exact Ps2⁻¹, exact Ps1}, end definition rec2_on [reducible] {P : circle → Type} (x : circle) (Pb1 : P base1) (Pb2 : P base2) (Ps1 : seg1 ▹ Pb1 = Pb2) (Ps2 : seg2 ▹ Pb2 = Pb1) : P x := circle.rec2 Pb1 Pb2 Ps1 Ps2 x definition rec2_seg1 {P : circle → Type} (Pb1 : P base1) (Pb2 : P base2) (Ps1 : seg1 ▹ Pb1 = Pb2) (Ps2 : seg2 ▹ Pb2 = Pb1) : apD (rec2 Pb1 Pb2 Ps1 Ps2) seg1 = sorry ⬝ Ps1 ⬝ sorry := sorry definition rec2_seg2 {P : circle → Type} (Pb1 : P base1) (Pb2 : P base2) (Ps1 : seg1 ▹ Pb1 = Pb2) (Ps2 : seg2 ▹ Pb2 = Pb1) : apD (rec2 Pb1 Pb2 Ps1 Ps2) seg2 = sorry ⬝ Ps2 ⬝ sorry := sorry definition elim2 {P : Type} (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb2 = Pb1) (x : circle) : P := rec2 Pb1 Pb2 (!tr_constant ⬝ Ps1) (!tr_constant ⬝ Ps2) x definition elim2_on [reducible] {P : Type} (x : circle) (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb2 = Pb1) : P := elim2 Pb1 Pb2 Ps1 Ps2 x definition elim2_seg1 {P : Type} (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb2 = Pb1) : ap (elim2 Pb1 Pb2 Ps1 Ps2) seg1 = sorry ⬝ Ps1 ⬝ sorry := sorry definition elim2_seg2 {P : Type} (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb2 = Pb1) : ap (elim2 Pb1 Pb2 Ps1 Ps2) seg2 = sorry ⬝ Ps2 ⬝ sorry := sorry protected definition rec {P : circle → Type} (Pbase : P base) (Ploop : loop ▹ Pbase = Pbase) (x : circle) : P x := begin fapply (rec2_on x), { exact Pbase}, { exact (transport P seg1 Pbase)}, { apply idp}, { apply eq_tr_of_inv_tr_eq, rewrite -tr_con, apply Ploop}, end protected definition rec_on [reducible] {P : circle → Type} (x : circle) (Pbase : P base) (Ploop : loop ▹ Pbase = Pbase) : P x := rec Pbase Ploop x definition rec_loop {P : circle → Type} (Pbase : P base) (Ploop : loop ▹ Pbase = Pbase) : ap (rec Pbase Ploop) loop = sorry ⬝ Ploop ⬝ sorry := sorry protected definition elim {P : Type} (Pbase : P) (Ploop : Pbase = Pbase) (x : circle) : P := rec Pbase (tr_constant loop Pbase ⬝ Ploop) x protected definition elim_on [reducible] {P : Type} (x : circle) (Pbase : P) (Ploop : Pbase = Pbase) : P := elim Pbase Ploop x definition elim_loop {P : Type} (Pbase : P) (Ploop : Pbase = Pbase) : ap (elim Pbase Ploop) loop = sorry ⬝ Ploop ⬝ sorry := sorry protected definition elim_type (Pbase : Type) (Ploop : Pbase ≃ Pbase) (x : circle) : Type := elim Pbase (ua Ploop) x protected definition elim_type_on [reducible] (x : circle) (Pbase : Type) (Ploop : Pbase ≃ Pbase) : Type := elim_type Pbase Ploop x definition elim_type_loop (Pbase : Type) (Ploop : Pbase ≃ Pbase) : transport (elim_type Pbase Ploop) loop = sorry /-Ploop-/ := sorry end circle
fef3eb862505514dbab555d46b55c4dc26283c1e
626e312b5c1cb2d88fca108f5933076012633192
/src/algebra/ordered_group.lean
f9c9372de4a1e90c3f9f465ddd7c5885a82b0d7b
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
45,594
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.ordered_monoid import order.rel_iso import order.order_dual /-! # Ordered groups This file develops the basics of ordered groups. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ set_option old_structure_cmd true open function universe u variable {α : Type u} @[to_additive] instance group.covariant_class_le.to_contravariant_class_le [group α] [has_le α] [covariant_class α α (*) (≤)] : contravariant_class α α (*) (≤) := group.covconv @[to_additive] instance group.swap.covariant_class_le.to_contravariant_class_le [group α] [has_le α] [covariant_class α α (swap (*)) (≤)] : contravariant_class α α (swap (*)) (≤) := { elim := λ a b c bc, calc b = b * a * a⁻¹ : eq_mul_inv_of_mul_eq rfl ... ≤ c * a * a⁻¹ : mul_le_mul_right' bc a⁻¹ ... = c : mul_inv_eq_of_eq_mul rfl } @[to_additive] instance group.covariant_class_lt.to_contravariant_class_lt [group α] [has_lt α] [covariant_class α α (*) (<)] : contravariant_class α α (*) (<) := { elim := λ a b c bc, calc b = a⁻¹ * (a * b) : eq_inv_mul_of_mul_eq rfl ... < a⁻¹ * (a * c) : mul_lt_mul_left' bc a⁻¹ ... = c : inv_mul_cancel_left a c } @[to_additive] instance group.swap.covariant_class_lt.to_contravariant_class_lt [group α] [has_lt α] [covariant_class α α (swap (*)) (<)] : contravariant_class α α (swap (*)) (<) := { elim := λ a b c bc, calc b = b * a * a⁻¹ : eq_mul_inv_of_mul_eq rfl ... < c * a * a⁻¹ : mul_lt_mul_right' bc a⁻¹ ... = c : mul_inv_eq_of_eq_mul rfl } /-- An ordered additive commutative group is an additive commutative group with a partial order in which addition is strictly monotone. -/ @[protect_proj, ancestor add_comm_group partial_order] class ordered_add_comm_group (α : Type u) extends add_comm_group α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) /-- An ordered commutative group is an commutative group with a partial order in which multiplication is strictly monotone. -/ @[protect_proj, ancestor comm_group partial_order] class ordered_comm_group (α : Type u) extends comm_group α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) attribute [to_additive] ordered_comm_group @[to_additive] instance ordered_comm_group.to_covariant_class_left_le (α : Type u) [ordered_comm_group α] : covariant_class α α (*) (≤) := { elim := λ a b c bc, ordered_comm_group.mul_le_mul_left b c bc a } /--The units of an ordered commutative monoid form an ordered commutative group. -/ @[to_additive] instance units.ordered_comm_group [ordered_comm_monoid α] : ordered_comm_group (units α) := { mul_le_mul_left := λ a b h c, (mul_le_mul_left' (h : (a : α) ≤ b) _ : (c : α) * a ≤ c * b), .. units.partial_order, .. units.comm_group } @[priority 100, to_additive] -- see Note [lower instance priority] instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u) [s : ordered_comm_group α] : ordered_cancel_comm_monoid α := { mul_left_cancel := λ a b c, (mul_right_inj a).mp, le_of_mul_le_mul_left := λ a b c, (mul_le_mul_iff_left a).mp, ..s } @[priority 100, to_additive] instance ordered_comm_group.has_exists_mul_of_le (α : Type u) [ordered_comm_group α] : has_exists_mul_of_le α := ⟨λ a b hab, ⟨b * a⁻¹, (mul_inv_cancel_comm_assoc a b).symm⟩⟩ @[to_additive] instance [h : has_inv α] : has_inv (order_dual α) := h @[to_additive] instance [h : has_div α] : has_div (order_dual α) := h @[to_additive] instance [h : div_inv_monoid α] : div_inv_monoid (order_dual α) := h @[to_additive] instance [h : group α] : group (order_dual α) := h @[to_additive] instance [h : comm_group α] : comm_group (order_dual α) := h @[to_additive] instance [ordered_comm_group α] : ordered_comm_group (order_dual α) := { .. order_dual.ordered_comm_monoid, .. order_dual.group } section group variables [group α] section typeclasses_left_le variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α} /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.neg_nonpos_iff] lemma left.inv_le_one_iff : a⁻¹ ≤ 1 ↔ 1 ≤ a := by { rw [← mul_le_mul_iff_left a], simp } /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.nonneg_neg_iff] lemma left.one_le_inv_iff : 1 ≤ a⁻¹ ↔ a ≤ 1 := by { rw [← mul_le_mul_iff_left a], simp } @[simp, to_additive] lemma le_inv_mul_iff_mul_le : b ≤ a⁻¹ * c ↔ a * b ≤ c := by { rw ← mul_le_mul_iff_left a, simp } @[simp, to_additive] lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≤ c ↔ a ≤ b * c := by rw [← mul_le_mul_iff_left b, mul_inv_cancel_left] @[to_additive neg_le_iff_add_nonneg'] lemma inv_le_iff_one_le_mul' : a⁻¹ ≤ b ↔ 1 ≤ a * b := (mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_iff_mul_le_one_left : a ≤ b⁻¹ ↔ b * a ≤ 1 := (mul_le_mul_iff_left b).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_mul_iff_le : 1 ≤ b⁻¹ * a ↔ b ≤ a := by rw [← mul_le_mul_iff_left b, mul_one, mul_inv_cancel_left] @[to_additive] lemma inv_mul_le_one_iff : a⁻¹ * b ≤ 1 ↔ b ≤ a := trans (inv_mul_le_iff_le_mul) $ by rw mul_one end typeclasses_left_le section typeclasses_left_lt variables [has_lt α] [covariant_class α α (*) (<)] {a b c : α} /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.neg_pos_iff] lemma left.one_lt_inv_iff : 1 < a⁻¹ ↔ a < 1 := by rw [← mul_lt_mul_iff_left a, mul_inv_self, mul_one] /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.neg_neg_iff] lemma left.inv_lt_one_iff : a⁻¹ < 1 ↔ 1 < a := by rw [← mul_lt_mul_iff_left a, mul_inv_self, mul_one] @[simp, to_additive] lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c := by { rw [← mul_lt_mul_iff_left a], simp } @[simp, to_additive] lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c := by rw [← mul_lt_mul_iff_left b, mul_inv_cancel_left] @[to_additive] lemma inv_lt_iff_one_lt_mul' : a⁻¹ < b ↔ 1 < a * b := (mul_lt_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma lt_inv_iff_mul_lt_one' : a < b⁻¹ ↔ b * a < 1 := (mul_lt_mul_iff_left b).symm.trans $ by rw mul_inv_self @[to_additive] lemma lt_inv_mul_iff_lt : 1 < b⁻¹ * a ↔ b < a := by rw [← mul_lt_mul_iff_left b, mul_one, mul_inv_cancel_left] @[to_additive] lemma inv_mul_lt_one_iff : a⁻¹ * b < 1 ↔ b < a := trans (inv_mul_lt_iff_lt_mul) $ by rw mul_one end typeclasses_left_lt section typeclasses_right_le variables [has_le α] [covariant_class α α (swap (*)) (≤)] {a b c : α} /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.neg_nonpos_iff] lemma right.inv_le_one_iff : a⁻¹ ≤ 1 ↔ 1 ≤ a := by { rw [← mul_le_mul_iff_right a], simp } /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.nonneg_neg_iff] lemma right.one_le_inv_iff : 1 ≤ a⁻¹ ↔ a ≤ 1 := by { rw [← mul_le_mul_iff_right a], simp } @[to_additive neg_le_iff_add_nonneg] lemma inv_le_iff_one_le_mul : a⁻¹ ≤ b ↔ 1 ≤ b * a := (mul_le_mul_iff_right a).symm.trans $ by rw inv_mul_self @[to_additive] lemma le_inv_iff_mul_le_one_right : a ≤ b⁻¹ ↔ a * b ≤ 1 := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self @[simp, to_additive] lemma mul_inv_le_iff_le_mul : a * b⁻¹ ≤ c ↔ a ≤ c * b := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right @[simp, to_additive] lemma le_mul_inv_iff_mul_le : c ≤ a * b⁻¹ ↔ c * b ≤ a := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right @[simp, to_additive] lemma mul_inv_le_one_iff_le : a * b⁻¹ ≤ 1 ↔ a ≤ b := mul_inv_le_iff_le_mul.trans $ by rw one_mul @[to_additive] lemma le_mul_inv_iff_le : 1 ≤ a * b⁻¹ ↔ b ≤ a := by rw [← mul_le_mul_iff_right b, one_mul, inv_mul_cancel_right] @[to_additive] lemma mul_inv_le_one_iff : b * a⁻¹ ≤ 1 ↔ b ≤ a := trans (mul_inv_le_iff_le_mul) $ by rw one_mul end typeclasses_right_le section typeclasses_right_lt variables [has_lt α] [covariant_class α α (swap (*)) (<)] {a b c : α} /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.neg_neg_iff] lemma right.inv_lt_one_iff : a⁻¹ < 1 ↔ 1 < a := by rw [← mul_lt_mul_iff_right a, inv_mul_self, one_mul] /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.neg_pos_iff] lemma right.one_lt_inv_iff : 1 < a⁻¹ ↔ a < 1 := by rw [← mul_lt_mul_iff_right a, inv_mul_self, one_mul] @[to_additive] lemma inv_lt_iff_one_lt_mul : a⁻¹ < b ↔ 1 < b * a := (mul_lt_mul_iff_right a).symm.trans $ by rw inv_mul_self @[to_additive] lemma lt_inv_iff_mul_lt_one : a < b⁻¹ ↔ a * b < 1 := (mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_self @[simp, to_additive] lemma mul_inv_lt_iff_lt_mul : a * b⁻¹ < c ↔ a < c * b := by rw [← mul_lt_mul_iff_right b, inv_mul_cancel_right] @[simp, to_additive] lemma lt_mul_inv_iff_mul_lt : c < a * b⁻¹ ↔ c * b < a := (mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right @[simp, to_additive] lemma inv_mul_lt_one_iff_lt : a * b⁻¹ < 1 ↔ a < b := by rw [← mul_lt_mul_iff_right b, inv_mul_cancel_right, one_mul] @[to_additive] lemma lt_mul_inv_iff_lt : 1 < a * b⁻¹ ↔ b < a := by rw [← mul_lt_mul_iff_right b, one_mul, inv_mul_cancel_right] @[to_additive] lemma mul_inv_lt_one_iff : b * a⁻¹ < 1 ↔ b < a := trans (mul_inv_lt_iff_lt_mul) $ by rw one_mul end typeclasses_right_lt section typeclasses_left_right_le variables [has_le α] [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] {a b c d : α} @[simp, to_additive] lemma inv_le_inv_iff : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by { rw [← mul_le_mul_iff_left a, ← mul_le_mul_iff_right b], simp } alias neg_le_neg_iff ↔ le_of_neg_le_neg _ section variable (α) /-- `x ↦ x⁻¹` as an order-reversing equivalence. -/ @[to_additive "`x ↦ -x` as an order-reversing equivalence.", simps] def order_iso.inv : α ≃o order_dual α := { to_equiv := (equiv.inv α).trans order_dual.to_dual, map_rel_iff' := λ a b, @inv_le_inv_iff α _ _ _ _ _ _ } end @[to_additive neg_le] lemma inv_le' : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := (order_iso.inv α).symm_apply_le alias inv_le' ↔ inv_le_of_inv_le' _ attribute [to_additive neg_le_of_neg_le] inv_le_of_inv_le' @[to_additive le_neg] lemma le_inv' : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := (order_iso.inv α).le_symm_apply @[to_additive] lemma mul_inv_le_inv_mul_iff : a * b⁻¹ ≤ d⁻¹ * c ↔ d * a ≤ c * b := by rw [← mul_le_mul_iff_left d, ← mul_le_mul_iff_right b, mul_inv_cancel_left, mul_assoc, inv_mul_cancel_right] @[simp, to_additive] lemma div_le_self_iff (a : α) {b : α} : a / b ≤ a ↔ 1 ≤ b := by simp [div_eq_mul_inv] alias sub_le_self_iff ↔ _ sub_le_self end typeclasses_left_right_le section typeclasses_left_right_lt variables [has_lt α] [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] {a b c d : α} @[simp, to_additive] lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a := by { rw [← mul_lt_mul_iff_left a, ← mul_lt_mul_iff_right b], simp } @[to_additive neg_lt] lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a := by rw [← inv_lt_inv_iff, inv_inv] @[to_additive lt_neg] lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ := by rw [← inv_lt_inv_iff, inv_inv] alias lt_inv' ↔ lt_inv_of_lt_inv _ attribute [to_additive] lt_inv_of_lt_inv alias inv_lt' ↔ inv_lt_of_inv_lt' _ attribute [to_additive neg_lt_of_neg_lt] inv_lt_of_inv_lt' @[to_additive] lemma mul_inv_lt_inv_mul_iff : a * b⁻¹ < d⁻¹ * c ↔ d * a < c * b := by rw [← mul_lt_mul_iff_left d, ← mul_lt_mul_iff_right b, mul_inv_cancel_left, mul_assoc, inv_mul_cancel_right] @[simp, to_additive] lemma div_lt_self_iff (a : α) {b : α} : a / b < a ↔ 1 < b := by simp [div_eq_mul_inv] alias sub_lt_self_iff ↔ _ sub_lt_self end typeclasses_left_right_lt section pre_order variable [preorder α] section left_le variables [covariant_class α α (*) (≤)] {a : α} @[to_additive] lemma left.inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (left.inv_le_one_iff.mpr h) h alias left.neg_le_self ← neg_le_self @[to_additive] lemma left.self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ := le_trans h (left.one_le_inv_iff.mpr h) end left_le section left_lt variables [covariant_class α α (*) (<)] {a : α} @[to_additive] lemma left.inv_lt_self (h : 1 < a) : a⁻¹ < a := (left.inv_lt_one_iff.mpr h).trans h alias left.neg_lt_self ← neg_lt_self @[to_additive] lemma left.self_lt_inv (h : a < 1) : a < a⁻¹ := lt_trans h (left.one_lt_inv_iff.mpr h) end left_lt section right_le variables [covariant_class α α (swap (*)) (≤)] {a : α} @[to_additive] lemma right.inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (right.inv_le_one_iff.mpr h) h @[to_additive] lemma right.self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ := le_trans h (right.one_le_inv_iff.mpr h) end right_le section right_lt variables [covariant_class α α (swap (*)) (<)] {a : α} @[to_additive] lemma right.inv_lt_self (h : 1 < a) : a⁻¹ < a := (right.inv_lt_one_iff.mpr h).trans h @[to_additive] lemma right.self_lt_inv (h : a < 1) : a < a⁻¹ := lt_trans h (right.one_lt_inv_iff.mpr h) end right_lt end pre_order end group section comm_group variables [comm_group α] section has_le variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α} @[to_additive] lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≤ b ↔ a ≤ b * c := by rw [inv_mul_le_iff_le_mul, mul_comm] @[simp, to_additive] lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [← inv_mul_le_iff_le_mul, mul_comm] @[to_additive add_neg_le_add_neg_iff] lemma mul_inv_le_mul_inv_iff' : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := by rw [mul_comm c, mul_inv_le_inv_mul_iff, mul_comm] end has_le section has_lt variables [has_lt α] [covariant_class α α (*) (<)] {a b c d : α} @[to_additive] lemma inv_mul_lt_iff_lt_mul' : c⁻¹ * a < b ↔ a < b * c := by rw [inv_mul_lt_iff_lt_mul, mul_comm] @[simp, to_additive] lemma mul_inv_lt_iff_le_mul' : a * b⁻¹ < c ↔ a < b * c := by rw [← inv_mul_lt_iff_lt_mul, mul_comm] @[to_additive add_neg_lt_add_neg_iff] lemma mul_inv_lt_mul_inv_iff' : a * b⁻¹ < c * d⁻¹ ↔ a * d < c * b := by rw [mul_comm c, mul_inv_lt_inv_mul_iff, mul_comm] end has_lt end comm_group alias le_inv' ↔ le_inv_of_le_inv _ attribute [to_additive] le_inv_of_le_inv alias left.inv_le_one_iff ↔ one_le_of_inv_le_one _ attribute [to_additive] one_le_of_inv_le_one alias left.one_le_inv_iff ↔ le_one_of_one_le_inv _ attribute [to_additive nonpos_of_neg_nonneg] le_one_of_one_le_inv alias inv_lt_inv_iff ↔ lt_of_inv_lt_inv _ attribute [to_additive] lt_of_inv_lt_inv alias left.inv_lt_one_iff ↔ one_lt_of_inv_lt_one _ attribute [to_additive] one_lt_of_inv_lt_one alias left.inv_lt_one_iff ← inv_lt_one_iff_one_lt attribute [to_additive] inv_lt_one_iff_one_lt alias left.inv_lt_one_iff ← inv_lt_one' attribute [to_additive neg_lt_zero] inv_lt_one' alias left.one_lt_inv_iff ↔ inv_of_one_lt_inv _ attribute [to_additive neg_of_neg_pos] inv_of_one_lt_inv alias left.one_lt_inv_iff ↔ _ one_lt_inv_of_inv attribute [to_additive neg_pos_of_neg] one_lt_inv_of_inv alias le_inv_mul_iff_mul_le ↔ mul_le_of_le_inv_mul _ attribute [to_additive] mul_le_of_le_inv_mul alias le_inv_mul_iff_mul_le ↔ _ le_inv_mul_of_mul_le attribute [to_additive] le_inv_mul_of_mul_le alias inv_mul_le_iff_le_mul ↔ _ inv_mul_le_of_le_mul attribute [to_additive] inv_mul_le_iff_le_mul alias lt_inv_mul_iff_mul_lt ↔ mul_lt_of_lt_inv_mul _ attribute [to_additive] mul_lt_of_lt_inv_mul alias lt_inv_mul_iff_mul_lt ↔ _ lt_inv_mul_of_mul_lt attribute [to_additive] lt_inv_mul_of_mul_lt alias inv_mul_lt_iff_lt_mul ↔ lt_mul_of_inv_mul_lt inv_mul_lt_of_lt_mul attribute [to_additive] lt_mul_of_inv_mul_lt attribute [to_additive] inv_mul_lt_of_lt_mul alias lt_mul_of_inv_mul_lt ← lt_mul_of_inv_mul_lt_left attribute [to_additive] lt_mul_of_inv_mul_lt_left alias left.inv_le_one_iff ← inv_le_one' attribute [to_additive neg_nonpos] inv_le_one' alias left.one_le_inv_iff ← one_le_inv' attribute [to_additive neg_nonneg] one_le_inv' alias left.one_lt_inv_iff ← one_lt_inv' attribute [to_additive neg_pos] one_lt_inv' alias mul_lt_mul_left' ← ordered_comm_group.mul_lt_mul_left' attribute [to_additive ordered_add_comm_group.add_lt_add_left] ordered_comm_group.mul_lt_mul_left' alias le_of_mul_le_mul_left' ← ordered_comm_group.le_of_mul_le_mul_left attribute [to_additive ordered_add_comm_group.le_of_add_le_add_left] ordered_comm_group.le_of_mul_le_mul_left alias lt_of_mul_lt_mul_left' ← ordered_comm_group.lt_of_mul_lt_mul_left attribute [to_additive ordered_add_comm_group.lt_of_add_lt_add_left] ordered_comm_group.lt_of_mul_lt_mul_left /-- Pullback an `ordered_comm_group` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.ordered_add_comm_group "Pullback an `ordered_add_comm_group` under an injective map."] def function.injective.ordered_comm_group [ordered_comm_group α] {β : Type*} [has_one β] [has_mul β] [has_inv β] [has_div β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : ordered_comm_group β := { ..partial_order.lift f hf, ..hf.ordered_comm_monoid f one mul, ..hf.comm_group f one mul inv div } /- Most of the lemmas that are primed in this section appear in ordered_field. -/ /- I (DT) did not try to minimise the assumptions. -/ section group variables [group α] [has_le α] section right variables [covariant_class α α (swap (*)) (≤)] {a b c d : α} @[simp, to_additive] lemma div_le_div_iff_right (c : α) : a / c ≤ b / c ↔ a ≤ b := by simpa only [div_eq_mul_inv] using mul_le_mul_iff_right _ @[to_additive sub_le_sub_right] lemma div_le_div_right' (h : a ≤ b) (c : α) : a / c ≤ b / c := (div_le_div_iff_right c).2 h @[simp, to_additive sub_nonneg] lemma one_le_div' : 1 ≤ a / b ↔ b ≤ a := by rw [← mul_le_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_nonneg ↔ le_of_sub_nonneg sub_nonneg_of_le @[simp, to_additive sub_nonpos] lemma div_le_one' : a / b ≤ 1 ↔ a ≤ b := by rw [← mul_le_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_nonpos ↔ le_of_sub_nonpos sub_nonpos_of_le @[to_additive] lemma le_div_iff_mul_le : a ≤ c / b ↔ a * b ≤ c := by rw [← mul_le_mul_iff_right b, div_eq_mul_inv, inv_mul_cancel_right] alias le_sub_iff_add_le ↔ add_le_of_le_sub_right le_sub_right_of_add_le @[to_additive] lemma div_le_iff_le_mul : a / c ≤ b ↔ a ≤ b * c := by rw [← mul_le_mul_iff_right c, div_eq_mul_inv, inv_mul_cancel_right] /-- `equiv.mul_right` as an `order_iso`. -/ @[to_additive "`equiv.add_right` as an `order_iso`.", simps to_equiv apply {simp_rhs := tt}] def order_iso.mul_right (a : α) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_iff_right a, to_equiv := equiv.mul_right a } @[simp, to_additive] lemma order_iso.mul_right_symm (a : α) : (order_iso.mul_right a).symm = order_iso.mul_right a⁻¹ := by { ext x, refl } end right section left variables [covariant_class α α (*) (≤)] /-- `equiv.mul_left` as an `order_iso`. -/ @[to_additive "`equiv.add_left` as an `order_iso`.", simps to_equiv apply {simp_rhs := tt}] def order_iso.mul_left (a : α) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_iff_left a, to_equiv := equiv.mul_left a } @[simp, to_additive] lemma order_iso.mul_left_symm (a : α) : (order_iso.mul_left a).symm = order_iso.mul_left a⁻¹ := by { ext x, refl } variables [covariant_class α α (swap (*)) (≤)] {a b c : α} @[simp, to_additive] lemma div_le_div_iff_left (a : α) : a / b ≤ a / c ↔ c ≤ b := by rw [div_eq_mul_inv, div_eq_mul_inv, ← mul_le_mul_iff_left a⁻¹, inv_mul_cancel_left, inv_mul_cancel_left, inv_le_inv_iff] @[to_additive sub_le_sub_left] lemma div_le_div_left' (h : a ≤ b) (c : α) : c / b ≤ c / a := (div_le_div_iff_left c).2 h end left end group section comm_group variables [comm_group α] section has_le variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α} @[to_additive sub_le_sub_iff] lemma div_le_div_iff' : a / b ≤ c / d ↔ a * d ≤ c * b := by simpa only [div_eq_mul_inv] using mul_inv_le_mul_inv_iff' @[to_additive] lemma le_div_iff_mul_le' : b ≤ c / a ↔ a * b ≤ c := by rw [le_div_iff_mul_le, mul_comm] alias le_sub_iff_add_le' ↔ add_le_of_le_sub_left le_sub_left_of_add_le @[to_additive] lemma div_le_iff_le_mul' : a / b ≤ c ↔ a ≤ b * c := by rw [div_le_iff_le_mul, mul_comm] alias sub_le_iff_le_add' ↔ le_add_of_sub_left_le sub_left_le_of_le_add @[simp, to_additive] lemma inv_le_div_iff_le_mul : b⁻¹ ≤ a / c ↔ c ≤ a * b := le_div_iff_mul_le.trans inv_mul_le_iff_le_mul' @[to_additive] lemma inv_le_div_iff_le_mul' : a⁻¹ ≤ b / c ↔ c ≤ a * b := by rw [inv_le_div_iff_le_mul, mul_comm] @[to_additive sub_le] lemma div_le'' : a / b ≤ c ↔ a / c ≤ b := div_le_iff_le_mul'.trans div_le_iff_le_mul.symm @[to_additive le_sub] lemma le_div'' : a ≤ b / c ↔ c ≤ b / a := le_div_iff_mul_le'.trans le_div_iff_mul_le.symm end has_le section preorder variables [preorder α] [covariant_class α α (*) (≤)] {a b c d : α} @[to_additive sub_le_sub] lemma div_le_div'' (hab : a ≤ b) (hcd : c ≤ d) : a / d ≤ b / c := begin rw [div_eq_mul_inv, div_eq_mul_inv, mul_comm b, mul_inv_le_inv_mul_iff, mul_comm], exact mul_le_mul' hab hcd end end preorder end comm_group /- Most of the lemmas that are primed in this section appear in ordered_field. -/ /- I (DT) did not try to minimise the assumptions. -/ section group variables [group α] [has_lt α] section right variables [covariant_class α α (swap (*)) (<)] {a b c d : α} @[simp, to_additive] lemma div_lt_div_iff_right (c : α) : a / c < b / c ↔ a < b := by simpa only [div_eq_mul_inv] using mul_lt_mul_iff_right _ @[to_additive sub_lt_sub_right] lemma div_lt_div_right' (h : a < b) (c : α) : a / c < b / c := (div_lt_div_iff_right c).2 h @[simp, to_additive sub_pos] lemma one_lt_div' : 1 < a / b ↔ b < a := by rw [← mul_lt_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_pos ↔ lt_of_sub_pos sub_pos_of_lt @[simp, to_additive sub_neg] lemma div_lt_one' : a / b < 1 ↔ a < b := by rw [← mul_lt_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_neg ↔ lt_of_sub_neg sub_neg_of_lt alias sub_neg ← sub_lt_zero @[to_additive] lemma lt_div_iff_mul_lt : a < c / b ↔ a * b < c := by rw [← mul_lt_mul_iff_right b, div_eq_mul_inv, inv_mul_cancel_right] alias lt_sub_iff_add_lt ↔ add_lt_of_lt_sub_right lt_sub_right_of_add_lt @[to_additive] lemma div_lt_iff_lt_mul : a / c < b ↔ a < b * c := by rw [← mul_lt_mul_iff_right c, div_eq_mul_inv, inv_mul_cancel_right] alias sub_lt_iff_lt_add ↔ lt_add_of_sub_right_lt sub_right_lt_of_lt_add end right section left variables [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] {a b c : α} @[simp, to_additive] lemma div_lt_div_iff_left (a : α) : a / b < a / c ↔ c < b := by rw [div_eq_mul_inv, div_eq_mul_inv, ← mul_lt_mul_iff_left a⁻¹, inv_mul_cancel_left, inv_mul_cancel_left, inv_lt_inv_iff] @[simp, to_additive] lemma inv_lt_div_iff_lt_mul : a⁻¹ < b / c ↔ c < a * b := by rw [div_eq_mul_inv, lt_mul_inv_iff_mul_lt, inv_mul_lt_iff_lt_mul] @[to_additive sub_lt_sub_left] lemma div_lt_div_left' (h : a < b) (c : α) : c / b < c / a := (div_lt_div_iff_left c).2 h end left end group section comm_group variables [comm_group α] section has_lt variables [has_lt α] [covariant_class α α (*) (<)] {a b c d : α} @[to_additive sub_lt_sub_iff] lemma div_lt_div_iff' : a / b < c / d ↔ a * d < c * b := by simpa only [div_eq_mul_inv] using mul_inv_lt_mul_inv_iff' @[to_additive] lemma lt_div_iff_mul_lt' : b < c / a ↔ a * b < c := by rw [lt_div_iff_mul_lt, mul_comm] alias lt_sub_iff_add_lt' ↔ add_lt_of_lt_sub_left lt_sub_left_of_add_lt @[to_additive] lemma div_lt_iff_lt_mul' : a / b < c ↔ a < b * c := by rw [div_lt_iff_lt_mul, mul_comm] alias sub_lt_iff_lt_add' ↔ lt_add_of_sub_left_lt sub_left_lt_of_lt_add @[to_additive] lemma inv_lt_div_iff_lt_mul' : b⁻¹ < a / c ↔ c < a * b := lt_div_iff_mul_lt.trans inv_mul_lt_iff_lt_mul' @[to_additive sub_lt] lemma div_lt'' : a / b < c ↔ a / c < b := div_lt_iff_lt_mul'.trans div_lt_iff_lt_mul.symm @[to_additive lt_sub] lemma lt_div'' : a < b / c ↔ c < b / a := lt_div_iff_mul_lt'.trans lt_div_iff_mul_lt.symm end has_lt section preorder variables [preorder α] [covariant_class α α (*) (<)] {a b c d : α} @[to_additive sub_lt_sub] lemma div_lt_div'' (hab : a < b) (hcd : c < d) : a / d < b / c := begin rw [div_eq_mul_inv, div_eq_mul_inv, mul_comm b, mul_inv_lt_inv_mul_iff, mul_comm], exact mul_lt_mul_of_lt_of_lt hab hcd end end preorder end comm_group section linear_order variables [group α] [linear_order α] [covariant_class α α (*) (≤)] section variable_names variables {a b c : α} @[to_additive] lemma le_of_forall_one_lt_lt_mul (h : ∀ ε : α, 1 < ε → a < b * ε) : a ≤ b := le_of_not_lt (λ h₁, lt_irrefl a (by simpa using (h _ (lt_inv_mul_iff_lt.mpr h₁)))) @[to_additive] lemma le_iff_forall_one_lt_lt_mul : a ≤ b ↔ ∀ ε, 1 < ε → a < b * ε := ⟨λ h ε, lt_mul_of_le_of_one_lt h, le_of_forall_one_lt_lt_mul⟩ /- I (DT) introduced this lemma to prove (the additive version `sub_le_sub_flip` of) `div_le_div_flip` below. Now I wonder what is the point of either of these lemmas... -/ @[to_additive] lemma div_le_inv_mul_iff [covariant_class α α (swap (*)) (≤)] : a / b ≤ a⁻¹ * b ↔ a ≤ b := begin rw [div_eq_mul_inv, mul_inv_le_inv_mul_iff], exact ⟨λ h, not_lt.mp (λ k, not_lt.mpr h (mul_lt_mul''' k k)), λ h, mul_le_mul' h h⟩, end /- What is the point of this lemma? See comment about `div_le_inv_mul_iff` above. -/ @[simp, to_additive] lemma div_le_div_flip {α : Type*} [comm_group α] [linear_order α] [covariant_class α α (*) (≤)] {a b : α}: a / b ≤ b / a ↔ a ≤ b := begin rw [div_eq_mul_inv b, mul_comm], exact div_le_inv_mul_iff, end @[simp, to_additive] lemma max_one_div_max_inv_one_eq_self (a : α) : max a 1 / max a⁻¹ 1 = a := by { rcases le_total a 1 with h|h; simp [h] } alias max_zero_sub_max_neg_zero_eq_self ← max_zero_sub_eq_self end variable_names section densely_ordered variables [densely_ordered α] {a b c : α} @[to_additive] lemma le_of_forall_one_lt_le_mul (h : ∀ ε : α, 1 < ε → a ≤ b * ε) : a ≤ b := le_of_forall_le_of_dense $ λ c hc, calc a ≤ b * (b⁻¹ * c) : h _ (lt_inv_mul_iff_lt.mpr hc) ... = c : mul_inv_cancel_left b c @[to_additive] lemma le_of_forall_lt_one_mul_le (h : ∀ ε < 1, a * ε ≤ b) : a ≤ b := @le_of_forall_one_lt_le_mul (order_dual α) _ _ _ _ _ _ h @[to_additive] lemma le_of_forall_one_lt_div_le (h : ∀ ε : α, 1 < ε → a / ε ≤ b) : a ≤ b := le_of_forall_lt_one_mul_le $ λ ε ε1, by simpa only [div_eq_mul_inv, inv_inv] using h ε⁻¹ (left.one_lt_inv_iff.2 ε1) @[to_additive] lemma le_iff_forall_one_lt_le_mul : a ≤ b ↔ ∀ ε, 1 < ε → a ≤ b * ε := ⟨λ h ε ε_pos, le_mul_of_le_of_one_le h ε_pos.le, le_of_forall_one_lt_le_mul⟩ @[to_additive] lemma le_iff_forall_lt_one_mul_le : a ≤ b ↔ ∀ ε < 1, a * ε ≤ b := @le_iff_forall_one_lt_le_mul (order_dual α) _ _ _ _ _ _ end densely_ordered end linear_order /-! ### Linearly ordered commutative groups -/ /-- A linearly ordered additive commutative group is an additive commutative group with a linear order in which addition is monotone. -/ @[protect_proj, ancestor ordered_add_comm_group linear_order] class linear_ordered_add_comm_group (α : Type u) extends ordered_add_comm_group α, linear_order α /-- A linearly ordered commutative monoid with an additively absorbing `⊤` element. Instances should include number systems with an infinite element adjoined.` -/ @[protect_proj, ancestor linear_ordered_add_comm_monoid_with_top sub_neg_monoid nontrivial] class linear_ordered_add_comm_group_with_top (α : Type*) extends linear_ordered_add_comm_monoid_with_top α, sub_neg_monoid α, nontrivial α := (neg_top : - (⊤ : α) = ⊤) (add_neg_cancel : ∀ a:α, a ≠ ⊤ → a + (- a) = 0) /-- A linearly ordered commutative group is a commutative group with a linear order in which multiplication is monotone. -/ @[protect_proj, ancestor ordered_comm_group linear_order, to_additive] class linear_ordered_comm_group (α : Type u) extends ordered_comm_group α, linear_order α @[to_additive] instance [linear_ordered_comm_group α] : linear_ordered_comm_group (order_dual α) := { .. order_dual.ordered_comm_group, .. order_dual.linear_order α } section linear_ordered_comm_group variables [linear_ordered_comm_group α] {a b c : α} @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_linear_ordered_cancel_comm_monoid : linear_ordered_cancel_comm_monoid α := { le_of_mul_le_mul_left := λ x y z, le_of_mul_le_mul_left', mul_left_cancel := λ x y z, mul_left_cancel, ..‹linear_ordered_comm_group α› } /-- Pullback a `linear_ordered_comm_group` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.linear_ordered_add_comm_group "Pullback a `linear_ordered_add_comm_group` under an injective map."] def function.injective.linear_ordered_comm_group {β : Type*} [has_one β] [has_mul β] [has_inv β] [has_div β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : linear_ordered_comm_group β := { ..linear_order.lift f hf, ..hf.ordered_comm_group f one mul inv div } @[to_additive linear_ordered_add_comm_group.add_lt_add_left] lemma linear_ordered_comm_group.mul_lt_mul_left' (a b : α) (h : a < b) (c : α) : c * a < c * b := mul_lt_mul_left' h c @[to_additive min_neg_neg] lemma min_inv_inv' (a b : α) : min (a⁻¹) (b⁻¹) = (max a b)⁻¹ := eq.symm $ @monotone.map_max α (order_dual α) _ _ has_inv.inv a b $ λ a b, inv_le_inv_iff.mpr @[to_additive max_neg_neg] lemma max_inv_inv' (a b : α) : max (a⁻¹) (b⁻¹) = (min a b)⁻¹ := eq.symm $ @monotone.map_min α (order_dual α) _ _ has_inv.inv a b $ λ a b, inv_le_inv_iff.mpr @[to_additive min_sub_sub_right] lemma min_div_div_right' (a b c : α) : min (a / c) (b / c) = min a b / c := by simpa only [div_eq_mul_inv] using min_mul_mul_right a b (c⁻¹) @[to_additive max_sub_sub_right] lemma max_div_div_right' (a b c : α) : max (a / c) (b / c) = max a b / c := by simpa only [div_eq_mul_inv] using max_mul_mul_right a b (c⁻¹) @[to_additive min_sub_sub_left] lemma min_div_div_left' (a b c : α) : min (a / b) (a / c) = a / max b c := by simp only [div_eq_mul_inv, min_mul_mul_left, min_inv_inv'] @[to_additive max_sub_sub_left] lemma max_div_div_left' (a b c : α) : max (a / b) (a / c) = a / min b c := by simp only [div_eq_mul_inv, max_mul_mul_left, max_inv_inv'] @[to_additive eq_zero_of_neg_eq] lemma eq_one_of_inv_eq' (h : a⁻¹ = a) : a = 1 := match lt_trichotomy a 1 with | or.inl h₁ := have 1 < a, from h ▸ one_lt_inv_of_inv h₁, absurd h₁ this.asymm | or.inr (or.inl h₁) := h₁ | or.inr (or.inr h₁) := have a < 1, from h ▸ inv_lt_one'.mpr h₁, absurd h₁ this.asymm end @[to_additive exists_zero_lt] lemma exists_one_lt' [nontrivial α] : ∃ (a:α), 1 < a := begin obtain ⟨y, hy⟩ := decidable.exists_ne (1 : α), cases hy.lt_or_lt, { exact ⟨y⁻¹, one_lt_inv'.mpr h⟩ }, { exact ⟨y, h⟩ } end @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_no_top_order [nontrivial α] : no_top_order α := ⟨ begin obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt', exact λ a, ⟨a * y, lt_mul_of_one_lt_right' a hy⟩ end ⟩ @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_no_bot_order [nontrivial α] : no_bot_order α := ⟨ begin obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt', exact λ a, ⟨a / y, (div_lt_self_iff a).mpr hy⟩ end ⟩ end linear_ordered_comm_group section covariant_add_le section has_neg variables [has_neg α] [linear_order α] {a b: α} /-- `mabs a` is the multiplicative absolute value of `a`. -/ @[to_additive abs "`abs a` is the additive absolute value of `a`." ] def mabs {α : Type*} [has_inv α] [lattice α] (a : α) : α := a ⊔ (a⁻¹) lemma abs_eq_max_neg {α : Type*} [has_neg α] [linear_order α] (a : α) : abs a = max a (-a) := begin exact rfl, end lemma abs_choice (x : α) : abs x = x ∨ abs x = -x := max_choice _ _ lemma abs_le' : abs a ≤ b ↔ a ≤ b ∧ -a ≤ b := max_le_iff lemma le_abs : a ≤ abs b ↔ a ≤ b ∨ a ≤ -b := le_max_iff lemma le_abs_self (a : α) : a ≤ abs a := le_max_left _ _ lemma neg_le_abs_self (a : α) : -a ≤ abs a := le_max_right _ _ lemma lt_abs : a < abs b ↔ a < b ∨ a < -b := lt_max_iff theorem abs_le_abs (h₀ : a ≤ b) (h₁ : -a ≤ b) : abs a ≤ abs b := (abs_le'.2 ⟨h₀, h₁⟩).trans (le_abs_self b) lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (abs a) := sup_ind _ _ h1 h2 end has_neg section add_group variables [add_group α] [linear_order α] @[simp] lemma abs_neg (a : α) : abs (-a) = abs a := begin rw [abs_eq_max_neg, max_comm, neg_neg, abs_eq_max_neg] end lemma eq_or_eq_neg_of_abs_eq {a b : α} (h : abs a = b) : a = b ∨ a = -b := by simpa only [← h, eq_comm, eq_neg_iff_eq_neg] using abs_choice a lemma abs_eq_abs {a b : α} : abs a = abs b ↔ a = b ∨ a = -b := begin refine ⟨λ h, _, λ h, _⟩, { obtain rfl | rfl := eq_or_eq_neg_of_abs_eq h; simpa only [neg_eq_iff_neg_eq, neg_inj, or.comm, @eq_comm _ (-b)] using abs_choice b }, { cases h; simp only [h, abs_neg] }, end lemma abs_sub_comm (a b : α) : abs (a - b) = abs (b - a) := calc abs (a - b) = abs (- (b - a)) : congr_arg _ (neg_sub b a).symm ... = abs (b - a) : abs_neg (b - a) variables [covariant_class α α (+) (≤)] {a b c : α} lemma abs_of_nonneg (h : 0 ≤ a) : abs a = a := max_eq_left $ (neg_nonpos.2 h).trans h lemma abs_of_pos (h : 0 < a) : abs a = a := abs_of_nonneg h.le lemma abs_of_nonpos (h : a ≤ 0) : abs a = -a := max_eq_right $ h.trans (neg_nonneg.2 h) lemma abs_of_neg (h : a < 0) : abs a = -a := abs_of_nonpos h.le @[simp] lemma abs_zero : abs 0 = (0:α) := abs_of_nonneg le_rfl @[simp] lemma abs_pos : 0 < abs a ↔ a ≠ 0 := begin rcases lt_trichotomy a 0 with (ha|rfl|ha), { simp [abs_of_neg ha, neg_pos, ha.ne, ha] }, { simp }, { simp [abs_of_pos ha, ha, ha.ne.symm] } end lemma abs_pos_of_pos (h : 0 < a) : 0 < abs a := abs_pos.2 h.ne.symm lemma abs_pos_of_neg (h : a < 0) : 0 < abs a := abs_pos.2 h.ne lemma neg_abs_le_self (a : α) : -abs a ≤ a := begin cases le_total 0 a with h h, { calc -abs a = - a : congr_arg (has_neg.neg) (abs_of_nonneg h) ... ≤ 0 : neg_nonpos.mpr h ... ≤ a : h }, { calc -abs a = - - a : congr_arg (has_neg.neg) (abs_of_nonpos h) ... ≤ a : (neg_neg a).le } end lemma abs_nonneg (a : α) : 0 ≤ abs a := (le_total 0 a).elim (λ h, h.trans (le_abs_self a)) (λ h, (neg_nonneg.2 h).trans $ neg_le_abs_self a) @[simp] lemma abs_abs (a : α) : abs (abs a) = abs a := abs_of_nonneg $ abs_nonneg a @[simp] lemma abs_eq_zero : abs a = 0 ↔ a = 0 := decidable.not_iff_not.1 $ ne_comm.trans $ (abs_nonneg a).lt_iff_ne.symm.trans abs_pos @[simp] lemma abs_nonpos_iff {a : α} : abs a ≤ 0 ↔ a = 0 := (abs_nonneg a).le_iff_eq.trans abs_eq_zero variable [covariant_class α α (swap (+)) (≤)] lemma abs_lt : abs a < b ↔ - b < a ∧ a < b := max_lt_iff.trans $ and.comm.trans $ by rw [neg_lt] lemma neg_lt_of_abs_lt (h : abs a < b) : -b < a := (abs_lt.mp h).1 lemma lt_of_abs_lt (h : abs a < b) : a < b := (abs_lt.mp h).2 lemma max_sub_min_eq_abs' (a b : α) : max a b - min a b = abs (a - b) := begin cases le_total a b with ab ba, { rw [max_eq_right ab, min_eq_left ab, abs_of_nonpos, neg_sub], rwa sub_nonpos }, { rw [max_eq_left ba, min_eq_right ba, abs_of_nonneg], rwa sub_nonneg } end lemma max_sub_min_eq_abs (a b : α) : max a b - min a b = abs (b - a) := by { rw abs_sub_comm, exact max_sub_min_eq_abs' _ _ } end add_group section add_comm_group variables [add_comm_group α] [linear_order α] [covariant_class α α (+) (≤)] {a b c d : α} lemma abs_le : abs a ≤ b ↔ - b ≤ a ∧ a ≤ b := by rw [abs_le', and.comm, neg_le] lemma neg_le_of_abs_le (h : abs a ≤ b) : -b ≤ a := (abs_le.mp h).1 lemma le_of_abs_le (h : abs a ≤ b) : a ≤ b := (abs_le.mp h).2 /-- The **triangle inequality** in `linear_ordered_add_comm_group`s. -/ lemma abs_add (a b : α) : abs (a + b) ≤ abs a + abs b := abs_le.2 ⟨(neg_add (abs a) (abs b)).symm ▸ add_le_add (neg_le.2 $ neg_le_abs_self _) (neg_le.2 $ neg_le_abs_self _), add_le_add (le_abs_self _) (le_abs_self _)⟩ theorem abs_sub (a b : α) : abs (a - b) ≤ abs a + abs b := by { rw [sub_eq_add_neg, ←abs_neg b], exact abs_add a _ } lemma abs_sub_le_iff : abs (a - b) ≤ c ↔ a - b ≤ c ∧ b - a ≤ c := by rw [abs_le, neg_le_sub_iff_le_add, sub_le_iff_le_add', and_comm, sub_le_iff_le_add'] lemma abs_sub_lt_iff : abs (a - b) < c ↔ a - b < c ∧ b - a < c := by rw [abs_lt, neg_lt_sub_iff_lt_add', sub_lt_iff_lt_add', and_comm, sub_lt_iff_lt_add'] lemma sub_le_of_abs_sub_le_left (h : abs (a - b) ≤ c) : b - c ≤ a := sub_le.1 $ (abs_sub_le_iff.1 h).2 lemma sub_le_of_abs_sub_le_right (h : abs (a - b) ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (abs_sub_comm a b ▸ h) lemma sub_lt_of_abs_sub_lt_left (h : abs (a - b) < c) : b - c < a := sub_lt.1 $ (abs_sub_lt_iff.1 h).2 lemma sub_lt_of_abs_sub_lt_right (h : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub_comm a b ▸ h) lemma abs_sub_abs_le_abs_sub (a b : α) : abs a - abs b ≤ abs (a - b) := sub_le_iff_le_add.2 $ calc abs a = abs (a - b + b) : by rw [sub_add_cancel] ... ≤ abs (a - b) + abs b : abs_add _ _ lemma abs_abs_sub_abs_le_abs_sub (a b : α) : abs (abs a - abs b) ≤ abs (a - b) := abs_sub_le_iff.2 ⟨abs_sub_abs_le_abs_sub _ _, by rw abs_sub_comm; apply abs_sub_abs_le_abs_sub⟩ lemma abs_eq (hb : 0 ≤ b) : abs a = b ↔ a = b ∨ a = -b := begin refine ⟨eq_or_eq_neg_of_abs_eq, _⟩, rintro (rfl|rfl); simp only [abs_neg, abs_of_nonneg hb] end lemma abs_le_max_abs_abs (hab : a ≤ b) (hbc : b ≤ c) : abs b ≤ max (abs a) (abs c) := abs_le'.2 ⟨by simp [hbc.trans (le_abs_self c)], by simp [(neg_le_neg_iff.mpr hab).trans (neg_le_abs_self a)]⟩ lemma eq_of_abs_sub_eq_zero {a b : α} (h : abs (a - b) = 0) : a = b := sub_eq_zero.1 $ abs_eq_zero.1 h lemma abs_sub_le (a b c : α) : abs (a - c) ≤ abs (a - b) + abs (b - c) := calc abs (a - c) = abs (a - b + (b - c)) : by rw [sub_add_sub_cancel] ... ≤ abs (a - b) + abs (b - c) : abs_add _ _ lemma abs_add_three (a b c : α) : abs (a + b + c) ≤ abs a + abs b + abs c := (abs_add _ _).trans (add_le_add_right (abs_add _ _) _) lemma dist_bdd_within_interval {a b lb ub : α} (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : abs (a - b) ≤ ub - lb := abs_sub_le_iff.2 ⟨sub_le_sub hau hbl, sub_le_sub hbu hal⟩ lemma eq_of_abs_sub_nonpos (h : abs (a - b) ≤ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b))) lemma abs_max_sub_max_le_abs (a b c : α) : abs (max a c - max b c) ≤ abs (a - b) := begin simp_rw [abs_le, le_sub_iff_add_le, sub_le_iff_le_add, ← max_add_add_left], split; apply max_le_max; simp only [← le_sub_iff_add_le, ← sub_le_iff_le_add, sub_self, neg_le, neg_le_abs_self, neg_zero, abs_nonneg, le_abs_self] end end add_comm_group end covariant_add_le section linear_ordered_add_comm_group variable [linear_ordered_add_comm_group α] instance with_top.linear_ordered_add_comm_group_with_top : linear_ordered_add_comm_group_with_top (with_top α) := { neg := option.map (λ a : α, -a), neg_top := @option.map_none _ _ (λ a : α, -a), add_neg_cancel := begin rintro (a | a) ha, { exact (ha rfl).elim }, { exact with_top.coe_add.symm.trans (with_top.coe_eq_coe.2 (add_neg_self a)) } end, .. with_top.linear_ordered_add_comm_monoid_with_top, .. option.nontrivial } end linear_ordered_add_comm_group /-- This is not so much a new structure as a construction mechanism for ordered groups, by specifying only the "positive cone" of the group. -/ class nonneg_add_comm_group (α : Type*) extends add_comm_group α := (nonneg : α → Prop) (pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (neg a)) (pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac) (zero_nonneg : nonneg 0) (add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b)) (nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0) namespace nonneg_add_comm_group variable [s : nonneg_add_comm_group α] include s @[reducible, priority 100] -- see Note [lower instance priority] instance to_ordered_add_comm_group : ordered_add_comm_group α := { le := λ a b, nonneg (b - a), lt := λ a b, pos (b - a), lt_iff_le_not_le := λ a b, by simp; rw [pos_iff]; simp, le_refl := λ a, by simp [zero_nonneg], le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg]; rw ← sub_add_sub_cancel; exact add_nonneg nbc nab, le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $ nonneg_antisymm nba (by rw neg_sub; exact nab), add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab, ..s } theorem nonneg_def {a : α} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem pos_def {a : α} : pos a ↔ 0 < a := show _ ↔ pos _, by simp theorem not_zero_pos : ¬ pos (0 : α) := mt pos_def.1 (lt_irrefl _) theorem zero_lt_iff_nonneg_nonneg {a : α} : 0 < a ↔ nonneg a ∧ ¬ nonneg (-a) := pos_def.symm.trans (pos_iff _) theorem nonneg_total_iff : (∀ a : α, nonneg a ∨ nonneg (-a)) ↔ (∀ a b : α, a ≤ b ∨ b ≤ a) := ⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this, λ h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩ /-- A `nonneg_add_comm_group` is a `linear_ordered_add_comm_group` if `nonneg` is total and decidable. -/ def to_linear_ordered_add_comm_group [decidable_pred (@nonneg α _)] (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : linear_ordered_add_comm_group α := { le := (≤), lt := (<), le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..@nonneg_add_comm_group.to_ordered_add_comm_group _ s } end nonneg_add_comm_group namespace prod variables {G H : Type*} @[to_additive] instance [ordered_comm_group G] [ordered_comm_group H] : ordered_comm_group (G × H) := { .. prod.comm_group, .. prod.partial_order G H, .. prod.ordered_cancel_comm_monoid } end prod section type_tags instance [ordered_add_comm_group α] : ordered_comm_group (multiplicative α) := { ..multiplicative.comm_group, ..multiplicative.ordered_comm_monoid } instance [ordered_comm_group α] : ordered_add_comm_group (additive α) := { ..additive.add_comm_group, ..additive.ordered_add_comm_monoid } instance [linear_ordered_add_comm_group α] : linear_ordered_comm_group (multiplicative α) := { ..multiplicative.linear_order, ..multiplicative.ordered_comm_group } instance [linear_ordered_comm_group α] : linear_ordered_add_comm_group (additive α) := { ..additive.linear_order, ..additive.ordered_add_comm_group } end type_tags section norm_num_lemmas /- The following lemmas are stated so that the `norm_num` tactic can use them with the expected signatures. -/ variables [ordered_comm_group α] {a b : α} @[to_additive neg_le_neg] lemma inv_le_inv' : a ≤ b → b⁻¹ ≤ a⁻¹ := inv_le_inv_iff.mpr @[to_additive neg_lt_neg] lemma inv_lt_inv' : a < b → b⁻¹ < a⁻¹ := inv_lt_inv_iff.mpr /- The additive version is also a `linarith` lemma. -/ @[to_additive] theorem inv_lt_one_of_one_lt : 1 < a → a⁻¹ < 1 := inv_lt_one_iff_one_lt.mpr /- The additive version is also a `linarith` lemma. -/ @[to_additive] lemma inv_le_one_of_one_le : 1 ≤ a → a⁻¹ ≤ 1 := inv_le_one'.mpr @[to_additive neg_nonneg_of_nonpos] lemma one_le_inv_of_le_one : a ≤ 1 → 1 ≤ a⁻¹ := one_le_inv'.mpr end norm_num_lemmas
e16d7a72412a4f5e3f15776cce9bd7b609cd3dde
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/leanpkg/cyclic/Cyclic.lean
5af4f224d95231cffe6adfe49d145aef68b8d0ea
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
16
lean
import Cyclic.A
4ea430c3bd0b47d5a84784a10edd9583e86c760e
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/affine_space/affine_subspace.lean
0aed92209fba84a643a6ba2cabc7cc8b0db19a02
[ "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
54,912
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import data.set.intervals.unordered_interval import linear_algebra.affine_space.affine_equiv /-! # Affine spaces This file defines affine subspaces (over modules) and the affine span of a set of points. ## Main definitions * `affine_subspace k P` is the type of affine subspaces. Unlike affine spaces, affine subspaces are allowed to be empty, and lemmas that do not apply to empty affine subspaces have `nonempty` hypotheses. There is a `complete_lattice` structure on affine subspaces. * `affine_subspace.direction` gives the `submodule` spanned by the pairwise differences of points in an `affine_subspace`. There are various lemmas relating to the set of vectors in the `direction`, and relating the lattice structure on affine subspaces to that on their directions. * `affine_span` gives the affine subspace spanned by a set of points, with `vector_span` giving its direction. `affine_span` is defined in terms of `span_points`, which gives an explicit description of the points contained in the affine span; `span_points` itself should generally only be used when that description is required, with `affine_span` being the main definition for other purposes. Two other descriptions of the affine span are proved equivalent: it is the `Inf` of affine subspaces containing the points, and (if `[nontrivial k]`) it contains exactly those points that are affine combinations of points in the given set. ## Implementation notes `out_param` is used in the definiton of `add_torsor V P` to make `V` an implicit argument (deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument rather than implied by `P` or `V`. This file only provides purely algebraic definitions and results. Those depending on analysis or topology are defined elsewhere; see `analysis.normed_space.add_torsor` and `topology.algebra.affine`. ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ noncomputable theory open_locale big_operators classical affine open set section variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] variables [affine_space V P] include V /-- The submodule spanning the differences of a (possibly empty) set of points. -/ def vector_span (s : set P) : submodule k V := submodule.span k (s -ᵥ s) /-- The definition of `vector_span`, for rewriting. -/ lemma vector_span_def (s : set P) : vector_span k s = submodule.span k (s -ᵥ s) := rfl /-- `vector_span` is monotone. -/ lemma vector_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : vector_span k s₁ ≤ vector_span k s₂ := submodule.span_mono (vsub_self_mono h) variables (P) /-- The `vector_span` of the empty set is `⊥`. -/ @[simp] lemma vector_span_empty : vector_span k (∅ : set P) = (⊥ : submodule k V) := by rw [vector_span_def, vsub_empty, submodule.span_empty] variables {P} /-- The `vector_span` of a single point is `⊥`. -/ @[simp] lemma vector_span_singleton (p : P) : vector_span k ({p} : set P) = ⊥ := by simp [vector_span_def] /-- The `s -ᵥ s` lies within the `vector_span k s`. -/ lemma vsub_set_subset_vector_span (s : set P) : s -ᵥ s ⊆ ↑(vector_span k s) := submodule.subset_span /-- Each pairwise difference is in the `vector_span`. -/ lemma vsub_mem_vector_span {s : set P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : p1 -ᵥ p2 ∈ vector_span k s := vsub_set_subset_vector_span k s (vsub_mem_vsub hp1 hp2) /-- The points in the affine span of a (possibly empty) set of points. Use `affine_span` instead to get an `affine_subspace k P`. -/ def span_points (s : set P) : set P := {p | ∃ p1 ∈ s, ∃ v ∈ (vector_span k s), p = v +ᵥ p1} /-- A point in a set is in its affine span. -/ lemma mem_span_points (p : P) (s : set P) : p ∈ s → p ∈ span_points k s | hp := ⟨p, hp, 0, submodule.zero_mem _, (zero_vadd V p).symm⟩ /-- A set is contained in its `span_points`. -/ lemma subset_span_points (s : set P) : s ⊆ span_points k s := λ p, mem_span_points k p s /-- The `span_points` of a set is nonempty if and only if that set is. -/ @[simp] lemma span_points_nonempty (s : set P) : (span_points k s).nonempty ↔ s.nonempty := begin split, { contrapose, rw [set.not_nonempty_iff_eq_empty, set.not_nonempty_iff_eq_empty], intro h, simp [h, span_points] }, { exact λ h, h.mono (subset_span_points _ _) } end /-- Adding a point in the affine span and a vector in the spanning submodule produces a point in the affine span. -/ lemma vadd_mem_span_points_of_mem_span_points_of_mem_vector_span {s : set P} {p : P} {v : V} (hp : p ∈ span_points k s) (hv : v ∈ vector_span k s) : v +ᵥ p ∈ span_points k s := begin rcases hp with ⟨p2, ⟨hp2, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv2p, vadd_vadd], use [p2, hp2, v + v2, (vector_span k s).add_mem hv hv2, rfl] end /-- Subtracting two points in the affine span produces a vector in the spanning submodule. -/ lemma vsub_mem_vector_span_of_mem_span_points_of_mem_span_points {s : set P} {p1 p2 : P} (hp1 : p1 ∈ span_points k s) (hp2 : p2 ∈ span_points k s) : p1 -ᵥ p2 ∈ vector_span k s := begin rcases hp1 with ⟨p1a, ⟨hp1a, ⟨v1, ⟨hv1, hv1p⟩⟩⟩⟩, rcases hp2 with ⟨p2a, ⟨hp2a, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv1p, hv2p, vsub_vadd_eq_vsub_sub (v1 +ᵥ p1a), vadd_vsub_assoc, add_comm, add_sub_assoc], have hv1v2 : v1 - v2 ∈ vector_span k s, { rw sub_eq_add_neg, apply (vector_span k s).add_mem hv1, rw ←neg_one_smul k v2, exact (vector_span k s).smul_mem (-1 : k) hv2 }, refine (vector_span k s).add_mem _ hv1v2, exact vsub_mem_vector_span k hp1a hp2a end end /-- An `affine_subspace k P` is a subset of an `affine_space V P` that, if not empty, has an affine space structure induced by a corresponding subspace of the `module k V`. -/ structure affine_subspace (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] := (carrier : set P) (smul_vsub_vadd_mem : ∀ (c : k) {p1 p2 p3 : P}, p1 ∈ carrier → p2 ∈ carrier → p3 ∈ carrier → c • (p1 -ᵥ p2 : V) +ᵥ p3 ∈ carrier) namespace submodule variables {k V : Type*} [ring k] [add_comm_group V] [module k V] /-- Reinterpret `p : submodule k V` as an `affine_subspace k V`. -/ def to_affine_subspace (p : submodule k V) : affine_subspace k V := { carrier := p, smul_vsub_vadd_mem := λ c p₁ p₂ p₃ h₁ h₂ h₃, p.add_mem (p.smul_mem _ (p.sub_mem h₁ h₂)) h₃ } end submodule namespace affine_subspace variables (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] include V -- TODO Refactor to use `instance : set_like (affine_subspace k P) P :=` instead instance : has_coe (affine_subspace k P) (set P) := ⟨carrier⟩ instance : has_mem P (affine_subspace k P) := ⟨λ p s, p ∈ (s : set P)⟩ /-- A point is in an affine subspace coerced to a set if and only if it is in that affine subspace. -/ @[simp] lemma mem_coe (p : P) (s : affine_subspace k P) : p ∈ (s : set P) ↔ p ∈ s := iff.rfl variables {k P} /-- The direction of an affine subspace is the submodule spanned by the pairwise differences of points. (Except in the case of an empty affine subspace, where the direction is the zero submodule, every vector in the direction is the difference of two points in the affine subspace.) -/ def direction (s : affine_subspace k P) : submodule k V := vector_span k (s : set P) /-- The direction equals the `vector_span`. -/ lemma direction_eq_vector_span (s : affine_subspace k P) : s.direction = vector_span k (s : set P) := rfl /-- Alternative definition of the direction when the affine subspace is nonempty. This is defined so that the order on submodules (as used in the definition of `submodule.span`) can be used in the proof of `coe_direction_eq_vsub_set`, and is not intended to be used beyond that proof. -/ def direction_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : submodule k V := { carrier := (s : set P) -ᵥ s, zero_mem' := begin cases h with p hp, exact (vsub_self p) ▸ vsub_mem_vsub hp hp end, add_mem' := begin intros a b ha hb, rcases ha with ⟨p1, p2, hp1, hp2, rfl⟩, rcases hb with ⟨p3, p4, hp3, hp4, rfl⟩, rw [←vadd_vsub_assoc], refine vsub_mem_vsub _ hp4, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp3, rw one_smul end, smul_mem' := begin intros c v hv, rcases hv with ⟨p1, p2, hp1, hp2, rfl⟩, rw [←vadd_vsub (c • (p1 -ᵥ p2)) p2], refine vsub_mem_vsub _ hp2, exact s.smul_vsub_vadd_mem c hp1 hp2 hp2 end } /-- `direction_of_nonempty` gives the same submodule as `direction`. -/ lemma direction_of_nonempty_eq_direction {s : affine_subspace k P} (h : (s : set P).nonempty) : direction_of_nonempty h = s.direction := le_antisymm (vsub_set_subset_vector_span k s) (submodule.span_le.2 set.subset.rfl) /-- The set of vectors in the direction of a nonempty affine subspace is given by `vsub_set`. -/ lemma coe_direction_eq_vsub_set {s : affine_subspace k P} (h : (s : set P).nonempty) : (s.direction : set V) = (s : set P) -ᵥ s := direction_of_nonempty_eq_direction h ▸ rfl /-- A vector is in the direction of a nonempty affine subspace if and only if it is the subtraction of two vectors in the subspace. -/ lemma mem_direction_iff_eq_vsub {s : affine_subspace k P} (h : (s : set P).nonempty) (v : V) : v ∈ s.direction ↔ ∃ p1 ∈ s, ∃ p2 ∈ s, v = p1 -ᵥ p2 := begin rw [←set_like.mem_coe, coe_direction_eq_vsub_set h], exact ⟨λ ⟨p1, p2, hp1, hp2, hv⟩, ⟨p1, hp1, p2, hp2, hv.symm⟩, λ ⟨p1, hp1, p2, hp2, hv⟩, ⟨p1, p2, hp1, hp2, hv.symm⟩⟩ end /-- Adding a vector in the direction to a point in the subspace produces a point in the subspace. -/ lemma vadd_mem_of_mem_direction {s : affine_subspace k P} {v : V} (hv : v ∈ s.direction) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s := begin rw mem_direction_iff_eq_vsub ⟨p, hp⟩ at hv, rcases hv with ⟨p1, hp1, p2, hp2, hv⟩, rw hv, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp, rw one_smul end /-- Subtracting two points in the subspace produces a vector in the direction. -/ lemma vsub_mem_direction {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : (p1 -ᵥ p2) ∈ s.direction := vsub_mem_vector_span k hp1 hp2 /-- Adding a vector to a point in a subspace produces a point in the subspace if and only if the vector is in the direction. -/ lemma vadd_mem_iff_mem_direction {s : affine_subspace k P} (v : V) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s ↔ v ∈ s.direction := ⟨λ h, by simpa using vsub_mem_direction h hp, λ h, vadd_mem_of_mem_direction h hp⟩ /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the right. -/ lemma coe_direction_eq_vsub_set_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ p) '' s := begin rw coe_direction_eq_vsub_set ⟨p, hp⟩, refine le_antisymm _ _, { rintros v ⟨p1, p2, hp1, hp2, rfl⟩, exact ⟨p1 -ᵥ p2 +ᵥ p, vadd_mem_of_mem_direction (vsub_mem_direction hp1 hp2) hp, (vadd_vsub _ _)⟩ }, { rintros v ⟨p2, hp2, rfl⟩, exact ⟨p2, p, hp2, hp, rfl⟩ } end /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the left. -/ lemma coe_direction_eq_vsub_set_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ) p '' s := begin ext v, rw [set_like.mem_coe, ←submodule.neg_mem_iff, ←set_like.mem_coe, coe_direction_eq_vsub_set_right hp, set.mem_image_iff_bex, set.mem_image_iff_bex], conv_lhs { congr, funext, rw [←neg_vsub_eq_vsub_rev, neg_inj] } end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the right. -/ lemma mem_direction_iff_eq_vsub_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p2 -ᵥ p := begin rw [←set_like.mem_coe, coe_direction_eq_vsub_set_right hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the left. -/ lemma mem_direction_iff_eq_vsub_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p -ᵥ p2 := begin rw [←set_like.mem_coe, coe_direction_eq_vsub_set_left hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a result of subtracting that point on the right is in the direction if and only if the other point is in the subspace. -/ lemma vsub_right_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p2 -ᵥ p ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_right hp, simp end /-- Given a point in an affine subspace, a result of subtracting that point on the left is in the direction if and only if the other point is in the subspace. -/ lemma vsub_left_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p -ᵥ p2 ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_left hp, simp end /-- Two affine subspaces are equal if they have the same points. -/ @[ext] lemma coe_injective : function.injective (coe : affine_subspace k P → set P) := λ s1 s2 h, begin cases s1, cases s2, congr, exact h end @[simp] lemma ext_iff (s₁ s₂ : affine_subspace k P) : (s₁ : set P) = s₂ ↔ s₁ = s₂ := ⟨λ h, coe_injective h, by tidy⟩ /-- Two affine subspaces with the same direction and nonempty intersection are equal. -/ lemma ext_of_direction_eq {s1 s2 : affine_subspace k P} (hd : s1.direction = s2.direction) (hn : ((s1 : set P) ∩ s2).nonempty) : s1 = s2 := begin ext p, have hq1 := set.mem_of_mem_inter_left hn.some_mem, have hq2 := set.mem_of_mem_inter_right hn.some_mem, split, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq2, rw ←hd, exact vsub_mem_direction hp hq1 }, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq1, rw hd, exact vsub_mem_direction hp hq2 } end instance to_add_torsor (s : affine_subspace k P) [nonempty s] : add_torsor s.direction s := { vadd := λ a b, ⟨(a:V) +ᵥ (b:P), vadd_mem_of_mem_direction a.2 b.2⟩, zero_vadd := by simp, add_vadd := λ a b c, by { ext, apply add_vadd }, vsub := λ a b, ⟨(a:P) -ᵥ (b:P), (vsub_left_mem_direction_iff_mem a.2 _).mpr b.2 ⟩, nonempty := by apply_instance, vsub_vadd' := λ a b, by { ext, apply add_torsor.vsub_vadd' }, vadd_vsub' := λ a b, by { ext, apply add_torsor.vadd_vsub' } } @[simp, norm_cast] lemma coe_vsub (s : affine_subspace k P) [nonempty s] (a b : s) : ↑(a -ᵥ b) = (a:P) -ᵥ (b:P) := rfl @[simp, norm_cast] lemma coe_vadd (s : affine_subspace k P) [nonempty s] (a : s.direction) (b : s) : ↑(a +ᵥ b) = (a:V) +ᵥ (b:P) := rfl /-- Two affine subspaces with nonempty intersection are equal if and only if their directions are equal. -/ lemma eq_iff_direction_eq_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : s₁ = s₂ ↔ s₁.direction = s₂.direction := ⟨λ h, h ▸ rfl, λ h, ext_of_direction_eq h ⟨p, h₁, h₂⟩⟩ /-- Construct an affine subspace from a point and a direction. -/ def mk' (p : P) (direction : submodule k V) : affine_subspace k P := { carrier := {q | ∃ v ∈ direction, q = v +ᵥ p}, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, begin rcases hp1 with ⟨v1, hv1, hp1⟩, rcases hp2 with ⟨v2, hv2, hp2⟩, rcases hp3 with ⟨v3, hv3, hp3⟩, use [c • (v1 - v2) + v3, direction.add_mem (direction.smul_mem c (direction.sub_mem hv1 hv2)) hv3], simp [hp1, hp2, hp3, vadd_vadd] end } /-- An affine subspace constructed from a point and a direction contains that point. -/ lemma self_mem_mk' (p : P) (direction : submodule k V) : p ∈ mk' p direction := ⟨0, ⟨direction.zero_mem, (zero_vadd _ _).symm⟩⟩ /-- An affine subspace constructed from a point and a direction contains the result of adding a vector in that direction to that point. -/ lemma vadd_mem_mk' {v : V} (p : P) {direction : submodule k V} (hv : v ∈ direction) : v +ᵥ p ∈ mk' p direction := ⟨v, hv, rfl⟩ /-- An affine subspace constructed from a point and a direction is nonempty. -/ lemma mk'_nonempty (p : P) (direction : submodule k V) : (mk' p direction : set P).nonempty := ⟨p, self_mem_mk' p direction⟩ /-- The direction of an affine subspace constructed from a point and a direction. -/ @[simp] lemma direction_mk' (p : P) (direction : submodule k V) : (mk' p direction).direction = direction := begin ext v, rw mem_direction_iff_eq_vsub (mk'_nonempty _ _), split, { rintros ⟨p1, ⟨v1, hv1, hp1⟩, p2, ⟨v2, hv2, hp2⟩, hv⟩, rw [hv, hp1, hp2, vadd_vsub_vadd_cancel_right], exact direction.sub_mem hv1 hv2 }, { exact λ hv, ⟨v +ᵥ p, vadd_mem_mk' _ hv, p, self_mem_mk' _ _, (vadd_vsub _ _).symm⟩ } end /-- Constructing an affine subspace from a point in a subspace and that subspace's direction yields the original subspace. -/ @[simp] lemma mk'_eq {s : affine_subspace k P} {p : P} (hp : p ∈ s) : mk' p s.direction = s := ext_of_direction_eq (direction_mk' p s.direction) ⟨p, set.mem_inter (self_mem_mk' _ _) hp⟩ /-- If an affine subspace contains a set of points, it contains the `span_points` of that set. -/ lemma span_points_subset_coe_of_subset_coe {s : set P} {s1 : affine_subspace k P} (h : s ⊆ s1) : span_points k s ⊆ s1 := begin rintros p ⟨p1, hp1, v, hv, hp⟩, rw hp, have hp1s1 : p1 ∈ (s1 : set P) := set.mem_of_mem_of_subset hp1 h, refine vadd_mem_of_mem_direction _ hp1s1, have hs : vector_span k s ≤ s1.direction := vector_span_mono k h, rw set_like.le_def at hs, rw ←set_like.mem_coe, exact set.mem_of_mem_of_subset hv hs end end affine_subspace lemma affine_map.line_map_mem {k V P : Type*} [ring k] [add_comm_group V] [module k V] [add_torsor V P] {Q : affine_subspace k P} {p₀ p₁ : P} (c : k) (h₀ : p₀ ∈ Q) (h₁ : p₁ ∈ Q) : affine_map.line_map p₀ p₁ c ∈ Q := begin rw affine_map.line_map_apply, exact Q.smul_vsub_vadd_mem c h₁ h₀ h₀, end section affine_span variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The affine span of a set of points is the smallest affine subspace containing those points. (Actually defined here in terms of spans in modules.) -/ def affine_span (s : set P) : affine_subspace k P := { carrier := span_points k s, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, vadd_mem_span_points_of_mem_span_points_of_mem_vector_span k hp3 ((vector_span k s).smul_mem c (vsub_mem_vector_span_of_mem_span_points_of_mem_span_points k hp1 hp2)) } /-- The affine span, converted to a set, is `span_points`. -/ @[simp] lemma coe_affine_span (s : set P) : (affine_span k s : set P) = span_points k s := rfl /-- A set is contained in its affine span. -/ lemma subset_affine_span (s : set P) : s ⊆ affine_span k s := subset_span_points k s /-- The direction of the affine span is the `vector_span`. -/ lemma direction_affine_span (s : set P) : (affine_span k s).direction = vector_span k s := begin apply le_antisymm, { refine submodule.span_le.2 _, rintros v ⟨p1, p3, ⟨p2, hp2, v1, hv1, hp1⟩, ⟨p4, hp4, v2, hv2, hp3⟩, rfl⟩, rw [hp1, hp3, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, set_like.mem_coe], exact (vector_span k s).sub_mem ((vector_span k s).add_mem hv1 (vsub_mem_vector_span k hp2 hp4)) hv2 }, { exact vector_span_mono k (subset_span_points k s) } end /-- A point in a set is in its affine span. -/ lemma mem_affine_span {p : P} {s : set P} (hp : p ∈ s) : p ∈ affine_span k s := mem_span_points k p s hp end affine_span namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [S : affine_space V P] include S instance : complete_lattice (affine_subspace k P) := { sup := λ s1 s2, affine_span k (s1 ∪ s2), le_sup_left := λ s1 s2, set.subset.trans (set.subset_union_left s1 s2) (subset_span_points k _), le_sup_right := λ s1 s2, set.subset.trans (set.subset_union_right s1 s2) (subset_span_points k _), sup_le := λ s1 s2 s3 hs1 hs2, span_points_subset_coe_of_subset_coe (set.union_subset hs1 hs2), inf := λ s1 s2, mk (s1 ∩ s2) (λ c p1 p2 p3 hp1 hp2 hp3, ⟨s1.smul_vsub_vadd_mem c hp1.1 hp2.1 hp3.1, s2.smul_vsub_vadd_mem c hp1.2 hp2.2 hp3.2⟩), inf_le_left := λ _ _, set.inter_subset_left _ _, inf_le_right := λ _ _, set.inter_subset_right _ _, le_inf := λ _ _ _, set.subset_inter, top := { carrier := set.univ, smul_vsub_vadd_mem := λ _ _ _ _ _ _ _, set.mem_univ _ }, le_top := λ _ _ _, set.mem_univ _, bot := { carrier := ∅, smul_vsub_vadd_mem := λ _ _ _ _, false.elim }, bot_le := λ _ _, false.elim, Sup := λ s, affine_span k (⋃ s' ∈ s, (s' : set P)), Inf := λ s, mk (⋂ s' ∈ s, (s' : set P)) (λ c p1 p2 p3 hp1 hp2 hp3, set.mem_Inter₂.2 $ λ s2 hs2, begin rw set.mem_Inter₂ at *, exact s2.smul_vsub_vadd_mem c (hp1 s2 hs2) (hp2 s2 hs2) (hp3 s2 hs2) end), le_Sup := λ _ _ h, set.subset.trans (set.subset_bUnion_of_mem h) (subset_span_points k _), Sup_le := λ _ _ h, span_points_subset_coe_of_subset_coe (set.Union₂_subset h), Inf_le := λ _ _, set.bInter_subset_of_mem, le_Inf := λ _ _, set.subset_Inter₂, .. partial_order.lift (coe : affine_subspace k P → set P) coe_injective } instance : inhabited (affine_subspace k P) := ⟨⊤⟩ /-- The `≤` order on subspaces is the same as that on the corresponding sets. -/ lemma le_def (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ (s1 : set P) ⊆ s2 := iff.rfl /-- One subspace is less than or equal to another if and only if all its points are in the second subspace. -/ lemma le_def' (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ ∀ p ∈ s1, p ∈ s2 := iff.rfl /-- The `<` order on subspaces is the same as that on the corresponding sets. -/ lemma lt_def (s1 s2 : affine_subspace k P) : s1 < s2 ↔ (s1 : set P) ⊂ s2 := iff.rfl /-- One subspace is not less than or equal to another if and only if it has a point not in the second subspace. -/ lemma not_le_iff_exists (s1 s2 : affine_subspace k P) : ¬ s1 ≤ s2 ↔ ∃ p ∈ s1, p ∉ s2 := set.not_subset /-- If a subspace is less than another, there is a point only in the second. -/ lemma exists_of_lt {s1 s2 : affine_subspace k P} (h : s1 < s2) : ∃ p ∈ s2, p ∉ s1 := set.exists_of_ssubset h /-- A subspace is less than another if and only if it is less than or equal to the second subspace and there is a point only in the second. -/ lemma lt_iff_le_and_exists (s1 s2 : affine_subspace k P) : s1 < s2 ↔ s1 ≤ s2 ∧ ∃ p ∈ s2, p ∉ s1 := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If an affine subspace is nonempty and contained in another with the same direction, they are equal. -/ lemma eq_of_direction_eq_of_nonempty_of_le {s₁ s₂ : affine_subspace k P} (hd : s₁.direction = s₂.direction) (hn : (s₁ : set P).nonempty) (hle : s₁ ≤ s₂) : s₁ = s₂ := let ⟨p, hp⟩ := hn in ext_of_direction_eq hd ⟨p, hp, hle hp⟩ variables (k V) /-- The affine span is the `Inf` of subspaces containing the given points. -/ lemma affine_span_eq_Inf (s : set P) : affine_span k s = Inf {s' | s ⊆ s'} := le_antisymm (span_points_subset_coe_of_subset_coe $ set.subset_Inter₂ $ λ _, id) (Inf_le (subset_span_points k _)) variables (P) /-- The Galois insertion formed by `affine_span` and coercion back to a set. -/ protected def gi : galois_insertion (affine_span k) (coe : affine_subspace k P → set P) := { choice := λ s _, affine_span k s, gc := λ s1 s2, ⟨λ h, set.subset.trans (subset_span_points k s1) h, span_points_subset_coe_of_subset_coe⟩, le_l_u := λ _, subset_span_points k _, choice_eq := λ _ _, rfl } /-- The span of the empty set is `⊥`. -/ @[simp] lemma span_empty : affine_span k (∅ : set P) = ⊥ := (affine_subspace.gi k V P).gc.l_bot /-- The span of `univ` is `⊤`. -/ @[simp] lemma span_univ : affine_span k (set.univ : set P) = ⊤ := eq_top_iff.2 $ subset_span_points k _ variables {k V P} lemma _root_.affine_span_le {s : set P} {Q : affine_subspace k P} : affine_span k s ≤ Q ↔ s ⊆ (Q : set P) := (affine_subspace.gi k V P).gc _ _ variables (k V) {P} /-- The affine span of a single point, coerced to a set, contains just that point. -/ @[simp] lemma coe_affine_span_singleton (p : P) : (affine_span k ({p} : set P) : set P) = {p} := begin ext x, rw [mem_coe, ←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_singleton p)) _, direction_affine_span], simp end /-- A point is in the affine span of a single point if and only if they are equal. -/ @[simp] lemma mem_affine_span_singleton (p1 p2 : P) : p1 ∈ affine_span k ({p2} : set P) ↔ p1 = p2 := by simp [←mem_coe] /-- The span of a union of sets is the sup of their spans. -/ lemma span_union (s t : set P) : affine_span k (s ∪ t) = affine_span k s ⊔ affine_span k t := (affine_subspace.gi k V P).gc.l_sup /-- The span of a union of an indexed family of sets is the sup of their spans. -/ lemma span_Union {ι : Type*} (s : ι → set P) : affine_span k (⋃ i, s i) = ⨆ i, affine_span k (s i) := (affine_subspace.gi k V P).gc.l_supr variables (P) /-- `⊤`, coerced to a set, is the whole set of points. -/ @[simp] lemma top_coe : ((⊤ : affine_subspace k P) : set P) = set.univ := rfl variables {P} /-- All points are in `⊤`. -/ lemma mem_top (p : P) : p ∈ (⊤ : affine_subspace k P) := set.mem_univ p variables (P) /-- The direction of `⊤` is the whole module as a submodule. -/ @[simp] lemma direction_top : (⊤ : affine_subspace k P).direction = ⊤ := begin cases S.nonempty with p, ext v, refine ⟨imp_intro submodule.mem_top, λ hv, _⟩, have hpv : (v +ᵥ p -ᵥ p : V) ∈ (⊤ : affine_subspace k P).direction := vsub_mem_direction (mem_top k V _) (mem_top k V _), rwa vadd_vsub at hpv end /-- `⊥`, coerced to a set, is the empty set. -/ @[simp] lemma bot_coe : ((⊥ : affine_subspace k P) : set P) = ∅ := rfl lemma bot_ne_top : (⊥ : affine_subspace k P) ≠ ⊤ := begin intros contra, rw [← ext_iff, bot_coe, top_coe] at contra, exact set.empty_ne_univ contra, end instance : nontrivial (affine_subspace k P) := ⟨⟨⊥, ⊤, bot_ne_top k V P⟩⟩ lemma nonempty_of_affine_span_eq_top {s : set P} (h : affine_span k s = ⊤) : s.nonempty := begin rw ← set.ne_empty_iff_nonempty, rintros rfl, rw affine_subspace.span_empty at h, exact bot_ne_top k V P h, end /-- If the affine span of a set is `⊤`, then the vector span of the same set is the `⊤`. -/ lemma vector_span_eq_top_of_affine_span_eq_top {s : set P} (h : affine_span k s = ⊤) : vector_span k s = ⊤ := by rw [← direction_affine_span, h, direction_top] /-- For a nonempty set, the affine span is `⊤` iff its vector span is `⊤`. -/ lemma affine_span_eq_top_iff_vector_span_eq_top_of_nonempty {s : set P} (hs : s.nonempty) : affine_span k s = ⊤ ↔ vector_span k s = ⊤ := begin refine ⟨vector_span_eq_top_of_affine_span_eq_top k V P, _⟩, intros h, suffices : nonempty (affine_span k s), { obtain ⟨p, hp : p ∈ affine_span k s⟩ := this, rw [eq_iff_direction_eq_of_mem hp (mem_top k V p), direction_affine_span, h, direction_top] }, obtain ⟨x, hx⟩ := hs, exact ⟨⟨x, mem_affine_span k hx⟩⟩, end /-- For a non-trivial space, the affine span of a set is `⊤` iff its vector span is `⊤`. -/ lemma affine_span_eq_top_iff_vector_span_eq_top_of_nontrivial {s : set P} [nontrivial P] : affine_span k s = ⊤ ↔ vector_span k s = ⊤ := begin cases s.eq_empty_or_nonempty with hs hs, { simp [hs, subsingleton_iff_bot_eq_top, add_torsor.subsingleton_iff V P, not_subsingleton], }, { rw affine_span_eq_top_iff_vector_span_eq_top_of_nonempty k V P hs, }, end lemma card_pos_of_affine_span_eq_top {ι : Type*} [fintype ι] {p : ι → P} (h : affine_span k (range p) = ⊤) : 0 < fintype.card ι := begin obtain ⟨-, ⟨i, -⟩⟩ := nonempty_of_affine_span_eq_top k V P h, exact fintype.card_pos_iff.mpr ⟨i⟩, end variables {P} /-- No points are in `⊥`. -/ lemma not_mem_bot (p : P) : p ∉ (⊥ : affine_subspace k P) := set.not_mem_empty p variables (P) /-- The direction of `⊥` is the submodule `⊥`. -/ @[simp] lemma direction_bot : (⊥ : affine_subspace k P).direction = ⊥ := by rw [direction_eq_vector_span, bot_coe, vector_span_def, vsub_empty, submodule.span_empty] variables {k V P} lemma subsingleton_of_subsingleton_span_eq_top {s : set P} (h₁ : s.subsingleton) (h₂ : affine_span k s = ⊤) : subsingleton P := begin obtain ⟨p, hp⟩ := affine_subspace.nonempty_of_affine_span_eq_top k V P h₂, have : s = {p}, { exact subset.antisymm (λ q hq, h₁ hq hp) (by simp [hp]), }, rw [this, ← affine_subspace.ext_iff, affine_subspace.coe_affine_span_singleton, affine_subspace.top_coe, eq_comm, ← subsingleton_iff_singleton (mem_univ _)] at h₂, exact subsingleton_of_univ_subsingleton h₂, end lemma eq_univ_of_subsingleton_span_eq_top {s : set P} (h₁ : s.subsingleton) (h₂ : affine_span k s = ⊤) : s = (univ : set P) := begin obtain ⟨p, hp⟩ := affine_subspace.nonempty_of_affine_span_eq_top k V P h₂, have : s = {p}, { exact subset.antisymm (λ q hq, h₁ hq hp) (by simp [hp]), }, rw [this, eq_comm, ← subsingleton_iff_singleton (mem_univ p), subsingleton_univ_iff], exact subsingleton_of_subsingleton_span_eq_top h₁ h₂, end /-- A nonempty affine subspace is `⊤` if and only if its direction is `⊤`. -/ @[simp] lemma direction_eq_top_iff_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : s.direction = ⊤ ↔ s = ⊤ := begin split, { intro hd, rw ←direction_top k V P at hd, refine ext_of_direction_eq hd _, simp [h] }, { rintro rfl, simp } end /-- The inf of two affine subspaces, coerced to a set, is the intersection of the two sets of points. -/ @[simp] lemma inf_coe (s1 s2 : affine_subspace k P) : ((s1 ⊓ s2) : set P) = s1 ∩ s2 := rfl /-- A point is in the inf of two affine subspaces if and only if it is in both of them. -/ lemma mem_inf_iff (p : P) (s1 s2 : affine_subspace k P) : p ∈ s1 ⊓ s2 ↔ p ∈ s1 ∧ p ∈ s2 := iff.rfl /-- The direction of the inf of two affine subspaces is less than or equal to the inf of their directions. -/ lemma direction_inf (s1 s2 : affine_subspace k P) : (s1 ⊓ s2).direction ≤ s1.direction ⊓ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact le_inf (Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_left _ _)) hp)) (Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_right _ _)) hp)) end /-- If two affine subspaces have a point in common, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := begin ext v, rw [submodule.mem_inf, ←vadd_mem_iff_mem_direction v h₁, ←vadd_mem_iff_mem_direction v h₂, ←vadd_mem_iff_mem_direction v ((mem_inf_iff p s₁ s₂).2 ⟨h₁, h₂⟩), mem_inf_iff] end /-- If two affine subspaces have a point in their inf, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem_inf {s₁ s₂ : affine_subspace k P} {p : P} (h : p ∈ s₁ ⊓ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := direction_inf_of_mem ((mem_inf_iff p s₁ s₂).1 h).1 ((mem_inf_iff p s₁ s₂).1 h).2 /-- If one affine subspace is less than or equal to another, the same applies to their directions. -/ lemma direction_le {s1 s2 : affine_subspace k P} (h : s1 ≤ s2) : s1.direction ≤ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact vector_span_mono k h end /-- If one nonempty affine subspace is less than another, the same applies to their directions -/ lemma direction_lt_of_nonempty {s1 s2 : affine_subspace k P} (h : s1 < s2) (hn : (s1 : set P).nonempty) : s1.direction < s2.direction := begin cases hn with p hp, rw lt_iff_le_and_exists at h, rcases h with ⟨hle, p2, hp2, hp2s1⟩, rw set_like.lt_iff_le_and_exists, use [direction_le hle, p2 -ᵥ p, vsub_mem_direction hp2 (hle hp)], intro hm, rw vsub_right_mem_direction_iff_mem hp p2 at hm, exact hp2s1 hm end /-- The sup of the directions of two affine subspaces is less than or equal to the direction of their sup. -/ lemma sup_direction_le (s1 s2 : affine_subspace k P) : s1.direction ⊔ s2.direction ≤ (s1 ⊔ s2).direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact sup_le (Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_left : s1 ≤ s1 ⊔ s2)) hp)) (Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_right : s2 ≤ s1 ⊔ s2)) hp)) end /-- The sup of the directions of two nonempty affine subspaces with empty intersection is less than the direction of their sup. -/ lemma sup_direction_lt_of_nonempty_of_inter_empty {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (he : (s1 ∩ s2 : set P) = ∅) : s1.direction ⊔ s2.direction < (s1 ⊔ s2).direction := begin cases h1 with p1 hp1, cases h2 with p2 hp2, rw set_like.lt_iff_le_and_exists, use [sup_direction_le s1 s2, p2 -ᵥ p1, vsub_mem_direction ((le_sup_right : s2 ≤ s1 ⊔ s2) hp2) ((le_sup_left : s1 ≤ s1 ⊔ s2) hp1)], intro h, rw submodule.mem_sup at h, rcases h with ⟨v1, hv1, v2, hv2, hv1v2⟩, rw [←sub_eq_zero, sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm v1, add_assoc, ←vadd_vsub_assoc, ←neg_neg v2, add_comm, ←sub_eq_add_neg, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hv1v2, refine set.nonempty.ne_empty _ he, use [v1 +ᵥ p1, vadd_mem_of_mem_direction hv1 hp1], rw hv1v2, exact vadd_mem_of_mem_direction (submodule.neg_mem _ hv2) hp2 end /-- If the directions of two nonempty affine subspaces span the whole module, they have nonempty intersection. -/ lemma inter_nonempty_of_nonempty_of_sup_direction_eq_top {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : s1.direction ⊔ s2.direction = ⊤) : ((s1 : set P) ∩ s2).nonempty := begin by_contradiction h, rw set.not_nonempty_iff_eq_empty at h, have hlt := sup_direction_lt_of_nonempty_of_inter_empty h1 h2 h, rw hd at hlt, exact not_top_lt hlt end /-- If the directions of two nonempty affine subspaces are complements of each other, they intersect in exactly one point. -/ lemma inter_eq_singleton_of_nonempty_of_is_compl {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : is_compl s1.direction s2.direction) : ∃ p, (s1 : set P) ∩ s2 = {p} := begin cases inter_nonempty_of_nonempty_of_sup_direction_eq_top h1 h2 hd.sup_eq_top with p hp, use p, ext q, rw set.mem_singleton_iff, split, { rintros ⟨hq1, hq2⟩, have hqp : q -ᵥ p ∈ s1.direction ⊓ s2.direction := ⟨vsub_mem_direction hq1 hp.1, vsub_mem_direction hq2 hp.2⟩, rwa [hd.inf_eq_bot, submodule.mem_bot, vsub_eq_zero_iff_eq] at hqp }, { exact λ h, h.symm ▸ hp } end /-- Coercing a subspace to a set then taking the affine span produces the original subspace. -/ @[simp] lemma affine_span_coe (s : affine_subspace k P) : affine_span k (s : set P) = s := begin refine le_antisymm _ (subset_span_points _ _), rintros p ⟨p1, hp1, v, hv, rfl⟩, exact vadd_mem_of_mem_direction hv hp1 end end affine_subspace section affine_space' variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] variables {ι : Type*} include V open affine_subspace set /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_eq_span_vsub_set_left {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_left p1 p2 p at hv, rw [←hv, set_like.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p2, hp2, rfl⟩) (hm ⟨p1, hp1, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p, p2, hp, hp2, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_eq_span_vsub_set_right {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_right p1 p2 p at hv, rw [←hv, set_like.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p1, hp1, rfl⟩) (hm ⟨p2, hp2, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p2, p, hp2, hp, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_left_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_right_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_finset_right_ne {s : finset P} {p : P} (hp : p ∈ s) : vector_span k (s : set P) = submodule.span k ((s.erase p).image (-ᵥ p)) := by simp [vector_span_eq_span_vsub_set_right_ne _ (finset.mem_coe.mpr hp)] /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_left_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ) (p i) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_right_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ (p i)) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_range_eq_span_range_vsub_left (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i0 -ᵥ p i)) := by rw [vector_span_eq_span_vsub_set_left k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_range_eq_span_range_vsub_right (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i -ᵥ p i0)) := by rw [vector_span_eq_span_vsub_set_right k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_left_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i₀ -ᵥ p i)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_left_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_right_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i -ᵥ p i₀)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_right_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The affine span of a set is nonempty if and only if that set is. -/ lemma affine_span_nonempty (s : set P) : (affine_span k s : set P).nonempty ↔ s.nonempty := span_points_nonempty k s /-- The affine span of a nonempty set is nonempty. -/ instance {s : set P} [nonempty s] : nonempty (affine_span k s) := ((affine_span_nonempty k s).mpr (nonempty_subtype.mp ‹_›)).to_subtype variables {k} /-- Suppose a set of vectors spans `V`. Then a point `p`, together with those vectors added to `p`, spans `P`. -/ lemma affine_span_singleton_union_vadd_eq_top_of_span_eq_top {s : set V} (p : P) (h : submodule.span k (set.range (coe : s → V)) = ⊤) : affine_span k ({p} ∪ (λ v, v +ᵥ p) '' s) = ⊤ := begin convert ext_of_direction_eq _ ⟨p, mem_affine_span k (set.mem_union_left _ (set.mem_singleton _)), mem_top k V p⟩, rw [direction_affine_span, direction_top, vector_span_eq_span_vsub_set_right k ((set.mem_union_left _ (set.mem_singleton _)) : p ∈ _), eq_top_iff, ←h], apply submodule.span_mono, rintros v ⟨v', rfl⟩, use (v' : V) +ᵥ p, simp end variables (k) /-- `affine_span` is monotone. -/ @[mono] lemma affine_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : affine_span k s₁ ≤ affine_span k s₂ := span_points_subset_coe_of_subset_coe (set.subset.trans h (subset_affine_span k _)) /-- Taking the affine span of a set, adding a point and taking the span again produces the same results as adding the point to the set and taking the span. -/ lemma affine_span_insert_affine_span (p : P) (ps : set P) : affine_span k (insert p (affine_span k ps : set P)) = affine_span k (insert p ps) := by rw [set.insert_eq, set.insert_eq, span_union, span_union, affine_span_coe] /-- If a point is in the affine span of a set, adding it to that set does not change the affine span. -/ lemma affine_span_insert_eq_affine_span {p : P} {ps : set P} (h : p ∈ affine_span k ps) : affine_span k (insert p ps) = affine_span k ps := begin rw ←mem_coe at h, rw [←affine_span_insert_affine_span, set.insert_eq_of_mem h, affine_span_coe] end end affine_space' namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The direction of the sup of two nonempty affine subspaces is the sup of the two directions and of any one difference between points in the two subspaces. -/ lemma direction_sup {s1 s2 : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s1) (hp2 : p2 ∈ s2) : (s1 ⊔ s2).direction = s1.direction ⊔ s2.direction ⊔ k ∙ (p2 -ᵥ p1) := begin refine le_antisymm _ _, { change (affine_span k ((s1 : set P) ∪ s2)).direction ≤ _, rw ←mem_coe at hp1, rw [direction_affine_span, vector_span_eq_span_vsub_set_right k (set.mem_union_left _ hp1), submodule.span_le], rintros v ⟨p3, hp3, rfl⟩, cases hp3, { rw [sup_assoc, sup_comm, set_like.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw zero_add }, { rw [sup_assoc, set_like.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1], rw [and_comm, zero_add], use rfl, rw [←vsub_add_vsub_cancel p3 p2 p1, submodule.mem_sup], use [p3 -ᵥ p2, vsub_mem_direction hp3 hp2, p2 -ᵥ p1, submodule.mem_span_singleton_self _] } }, { refine sup_le (sup_direction_le _ _) _, rw [direction_eq_vector_span, vector_span_def], exact Inf_le_Inf (λ p hp, set.subset.trans (set.singleton_subset_iff.2 (vsub_mem_vsub (mem_span_points k p2 _ (set.mem_union_right _ hp2)) (mem_span_points k p1 _ (set.mem_union_left _ hp1)))) hp) } end /-- The direction of the span of the result of adding a point to a nonempty affine subspace is the sup of the direction of that subspace and of any one difference between that point and a point in the subspace. -/ lemma direction_affine_span_insert {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) : (affine_span k (insert p2 (s : set P))).direction = submodule.span k {p2 -ᵥ p1} ⊔ s.direction := begin rw [sup_comm, ←set.union_singleton, ←coe_affine_span_singleton k V p2], change (s ⊔ affine_span k {p2}).direction = _, rw [direction_sup hp1 (mem_affine_span k (set.mem_singleton _)), direction_affine_span], simp end /-- Given a point `p1` in an affine subspace `s`, and a point `p2`, a point `p` is in the span of `s` with `p2` added if and only if it is a multiple of `p2 -ᵥ p1` added to a point in `s`. -/ lemma mem_affine_span_insert_iff {s : affine_subspace k P} {p1 : P} (hp1 : p1 ∈ s) (p2 p : P) : p ∈ affine_span k (insert p2 (s : set P)) ↔ ∃ (r : k) (p0 : P) (hp0 : p0 ∈ s), p = r • (p2 -ᵥ p1 : V) +ᵥ p0 := begin rw ←mem_coe at hp1, rw [←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_insert_of_mem _ hp1)), direction_affine_span_insert hp1, submodule.mem_sup], split, { rintros ⟨v1, hv1, v2, hv2, hp⟩, rw submodule.mem_span_singleton at hv1, rcases hv1 with ⟨r, rfl⟩, use [r, v2 +ᵥ p1, vadd_mem_of_mem_direction hv2 hp1], symmetry' at hp, rw [←sub_eq_zero, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hp, rw [hp, vadd_vadd] }, { rintros ⟨r, p3, hp3, rfl⟩, use [r • (p2 -ᵥ p1), submodule.mem_span_singleton.2 ⟨r, rfl⟩, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw [vadd_vsub_assoc, add_comm] } end end affine_subspace section map_comap variables {k V₁ P₁ V₂ P₂ V₃ P₃ : Type*} [ring k] variables [add_comm_group V₁] [module k V₁] [add_torsor V₁ P₁] variables [add_comm_group V₂] [module k V₂] [add_torsor V₂ P₂] variables [add_comm_group V₃] [module k V₃] [add_torsor V₃ P₃] include V₁ V₂ section variables (f : P₁ →ᵃ[k] P₂) @[simp] lemma affine_map.vector_span_image_eq_submodule_map {s : set P₁} : submodule.map f.linear (vector_span k s) = vector_span k (f '' s) := by simp [f.image_vsub_image, vector_span_def] namespace affine_subspace /-- The image of an affine subspace under an affine map as an affine subspace. -/ def map (s : affine_subspace k P₁) : affine_subspace k P₂ := { carrier := f '' s, smul_vsub_vadd_mem := begin rintros t - - - ⟨p₁, h₁, rfl⟩ ⟨p₂, h₂, rfl⟩ ⟨p₃, h₃, rfl⟩, use t • (p₁ -ᵥ p₂) +ᵥ p₃, suffices : t • (p₁ -ᵥ p₂) +ᵥ p₃ ∈ s, { by simp [this], }, exact s.smul_vsub_vadd_mem t h₁ h₂ h₃, end } @[simp] lemma coe_map (s : affine_subspace k P₁) : (s.map f : set P₂) = f '' s := rfl @[simp] lemma mem_map {f : P₁ →ᵃ[k] P₂} {x : P₂} {s : affine_subspace k P₁} : x ∈ s.map f ↔ ∃ y ∈ s, f y = x := mem_image_iff_bex @[simp] lemma map_bot : (⊥ : affine_subspace k P₁).map f = ⊥ := coe_injective $ image_empty f omit V₂ @[simp] lemma map_id (s : affine_subspace k P₁) : s.map (affine_map.id k P₁) = s := coe_injective $ image_id _ include V₂ V₃ lemma map_map (s : affine_subspace k P₁) (f : P₁ →ᵃ[k] P₂) (g : P₂ →ᵃ[k] P₃) : (s.map f).map g = s.map (g.comp f) := coe_injective $ image_image _ _ _ omit V₃ @[simp] lemma map_direction (s : affine_subspace k P₁) : (s.map f).direction = s.direction.map f.linear := by simp [direction_eq_vector_span] lemma map_span (s : set P₁) : (affine_span k s).map f = affine_span k (f '' s) := begin rcases s.eq_empty_or_nonempty with rfl | ⟨p, hp⟩, { simp, }, apply ext_of_direction_eq, { simp [direction_affine_span], }, { exact ⟨f p, mem_image_of_mem f (subset_affine_span k _ hp), subset_affine_span k _ (mem_image_of_mem f hp)⟩, }, end end affine_subspace namespace affine_map @[simp] lemma map_top_of_surjective (hf : function.surjective f) : affine_subspace.map f ⊤ = ⊤ := begin rw ← affine_subspace.ext_iff, exact image_univ_of_surjective hf, end lemma span_eq_top_of_surjective {s : set P₁} (hf : function.surjective f) (h : affine_span k s = ⊤) : affine_span k (f '' s) = ⊤ := by rw [← affine_subspace.map_span, h, map_top_of_surjective f hf] end affine_map lemma affine_equiv.span_eq_top_iff {s : set P₁} (e : P₁ ≃ᵃ[k] P₂) : affine_span k s = ⊤ ↔ affine_span k (e '' s) = ⊤ := begin refine ⟨(e : P₁ →ᵃ[k] P₂).span_eq_top_of_surjective e.surjective, _⟩, intros h, have : s = e.symm '' (e '' s), { simp [← image_comp], }, rw this, exact (e.symm : P₂ →ᵃ[k] P₁).span_eq_top_of_surjective e.symm.surjective h, end end namespace affine_subspace /-- The preimage of an affine subspace under an affine map as an affine subspace. -/ def comap (f : P₁ →ᵃ[k] P₂) (s : affine_subspace k P₂) : affine_subspace k P₁ := { carrier := f ⁻¹' s, smul_vsub_vadd_mem := λ t p₁ p₂ p₃ (hp₁ : f p₁ ∈ s) (hp₂ : f p₂ ∈ s) (hp₃ : f p₃ ∈ s), show f _ ∈ s, begin rw [affine_map.map_vadd, linear_map.map_smul, affine_map.linear_map_vsub], apply s.smul_vsub_vadd_mem _ hp₁ hp₂ hp₃, end } @[simp] lemma coe_comap (f : P₁ →ᵃ[k] P₂) (s : affine_subspace k P₂) : (s.comap f : set P₁) = f ⁻¹' ↑s := rfl @[simp] lemma mem_comap {f : P₁ →ᵃ[k] P₂} {x : P₁} {s : affine_subspace k P₂} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl lemma comap_mono {f : P₁ →ᵃ[k] P₂} {s t : affine_subspace k P₂} : s ≤ t → s.comap f ≤ t.comap f := preimage_mono @[simp] lemma comap_top {f : P₁ →ᵃ[k] P₂} : (⊤ : affine_subspace k P₂).comap f = ⊤ := by { rw ← ext_iff, exact preimage_univ, } omit V₂ @[simp] lemma comap_id (s : affine_subspace k P₁) : s.comap (affine_map.id k P₁) = s := coe_injective rfl include V₂ V₃ lemma comap_comap (s : affine_subspace k P₃) (f : P₁ →ᵃ[k] P₂) (g : P₂ →ᵃ[k] P₃) : (s.comap g).comap f = s.comap (g.comp f) := coe_injective rfl omit V₃ -- lemmas about map and comap derived from the galois connection lemma map_le_iff_le_comap {f : P₁ →ᵃ[k] P₂} {s : affine_subspace k P₁} {t : affine_subspace k P₂} : s.map f ≤ t ↔ s ≤ t.comap f := image_subset_iff lemma gc_map_comap (f : P₁ →ᵃ[k] P₂) : galois_connection (map f) (comap f) := λ _ _, map_le_iff_le_comap lemma map_comap_le (f : P₁ →ᵃ[k] P₂) (s : affine_subspace k P₂) : (s.comap f).map f ≤ s := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : P₁ →ᵃ[k] P₂) (s : affine_subspace k P₁) : s ≤ (s.map f).comap f := (gc_map_comap f).le_u_l _ lemma map_sup (s t : affine_subspace k P₁) (f : P₁ →ᵃ[k] P₂) : (s ⊔ t).map f = s.map f ⊔ t.map f := (gc_map_comap f).l_sup lemma map_supr {ι : Sort*} (f : P₁ →ᵃ[k] P₂) (s : ι → affine_subspace k P₁) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr lemma comap_inf (s t : affine_subspace k P₂) (f : P₁ →ᵃ[k] P₂) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f := (gc_map_comap f).u_inf lemma comap_supr {ι : Sort*} (f : P₁ →ᵃ[k] P₂) (s : ι → affine_subspace k P₂) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi end affine_subspace end map_comap
88a13bb13f66e8116510f50e69f54454eb6b36e0
0005a183d2afe3c7d097776749c13513cae91b66
/src/bigop.lean
c475a669bb708cf757e4d28aaff312d7a3951794
[]
no_license
PatrickMassot/bigop
9f85014752aa632c270bafbd96400512839220eb
af53ad615b619e3c05fe119f98f939ff010f7e6d
refs/heads/master
1,584,009,287,023
1,562,778,117,000
1,562,778,117,000
130,576,309
1
1
null
null
null
null
UTF-8
Lean
false
false
12,452
lean
import tactic.ext import tactic.linarith import pending_lemmas open list variables {R : Type*} {I : Type*} (op : R → R → R) (nil: R) (r : list I) (P : I → Prop) [decidable_pred P] (F : I → R) local infix ` ◆ `:70 := op -- type using \di /- Starting from `F : I → R`, `r : list I`, a composition law `op` on `R`, a element `nil` in R, and a decidable predicate `P` on `I`, `apply_bigop op nil r P F` is the big "product", for operation `op`, of all `F i` for `i` in `r` if `P i`. All parenthesis are closed after inserting `nil` at the very end, like in `(a op (b op (c op nil)))` (using infix notation for op) -/ def apply_bigop := foldr (λ i, op (F i)) nil (filter P r) -- alternate definition : foldr (λ i x, if P i then op (F i) x else x) nil r /- We now define a notation with many variations depending on the list, predicate, operation -/ /- variable in filtered list -/ notation `big[`:0 op`/`:0 nil`]_(`:0 binder `∈` r `|` P:(scoped p, p)`)` F:(scoped f, f) := apply_bigop op nil r P F notation `Σ_(`:0 binder `∈` r `|` P:(scoped p, p) `)` F:(scoped f, f) := apply_bigop (+) 0 r P F notation `Π_(`:0 binder `∈` r `|` P:(scoped p, p) `)` F:(scoped f, f) := apply_bigop (*) 1 r P F /- variable in unfiltered list -/ notation `big[`:0 op `/`:0 nil `]_(`:0 binder `∈` r `)` F:(scoped f, f) := apply_bigop op nil r (λ i, true) F notation `Σ_(`:0 binder `∈` r `)` F:(scoped f, f) := apply_bigop (+) 0 r (λ i, true) F notation `Π_(`:0 binder `∈` r `)` F:(scoped f, f) := apply_bigop (*) 1 r (λ i, true) F /- variable is integers from a to b, b exclued, filtered -/ notation `big[`op`/`:0 nil`]_(`:0 binder`=`a`..`b `|` P:(scoped p, p)`)` F:(scoped f, f) := apply_bigop op nil (int.range a b) P F notation `Σ_(`:0 binder`=`a`..`b `|` P:(scoped p, p)`)` F:(scoped f, f) := apply_bigop (+) 0 (int.range a b) P F notation `Π_(`:0 binder`=`a`..` b `|` P:(scoped p, p)`)` F:(scoped f, f) := apply_bigop (*) 1 (int.range a b) P F /- variable is integers from a to b, b exclued, unfiltered -/ notation `big[`:0 op `/`:0 nil `]_(`:0 binder `=` a `..` b `)` F:(scoped f, f) := apply_bigop op nil (int.range a b) (λ i, true) F notation `Σ_(`:0 binder `=` a `..` b `)` F:(scoped f, f) := apply_bigop (+) 0 (int.range a b) (λ i, true) F notation `Π_(`:0 binder `=` a `..` b `)` F:(scoped f, f) := apply_bigop (*) 1 (int.range a b) (λ i, true) F local notation `?(F` h`)` := if P h then F h else nil /- First lemmas, without assuming anything on `op` and `nil` -/ @[simp] lemma big.nil : (big[(◆)/nil]_(i ∈ [] | (P i)) (F i)) = nil := by simp [apply_bigop] lemma big.filter_mem [decidable_pred (λ i, i ∈ r)] : (big[(◆)/nil]_(i ∈ r) (F i)) = (big[(◆)/nil]_(i ∈ r | i ∈ r) (F i)) := by simp [apply_bigop] lemma big_cons_true {h} (t) (Ph : P h) : (big[(◆)/nil]_(i ∈ h::t | (P i)) (F i)) = F h ◆ (big[(◆)/nil]_(i ∈ t | (P i)) (F i)):= by simp [apply_bigop, Ph] lemma big_cons_false {h} (t) (Ph : ¬ P h) : (big[(◆)/nil]_(i ∈ h::t | (P i)) (F i)) = (big[(◆)/nil]_(i ∈ t | (P i)) (F i)) := by simp [apply_bigop, Ph] lemma big_rec (K : R → Prop) (Knil : K nil) (Kop : ∀ i x, P i → K x → K ((F i) ◆ x)) : K (big[(◆)/nil]_(i ∈ r | (P i)) (F i)) := begin induction r with h t IH, { simp[big.nil, Knil] }, { by_cases H : P h, { simp [big_cons_true, H, Kop _ _ H IH] }, { simp [big_cons_false, H, IH] } } end lemma big_ind (K : R → Prop) (Knil : K nil) (Kop : ∀ x y, K x → K y → K (x ◆ y)) (K_F : ∀ i, P i → K (F i)) : K (big[(◆)/nil]_(i ∈ r | (P i)) (F i)) := begin apply big_rec, exact Knil, intros i x P_i K_x, apply Kop ; tauto end lemma big_append_eq_of_not_mem [decidable_eq I] {j} (H : j ∉ r) : (big[(◆)/nil]_(i ∈ j::r | ((P i) ∧ i ≠ j)) (F i)) = big[(◆)/nil]_(i ∈ r | (P i)) (F i) := begin unfold apply_bigop, congr' 1, rw list.filter_cons_of_neg, apply list.filter_congr, { intros x x_in, simp [show x ≠ j, by { intro H', rw ←H' at H, contradiction }] }, { finish } end -- A version of extensionality where we assume same (◆)/nil and same list lemma big.ext (P') [decidable_pred P'] (F' : I → R) (HP : ∀ i ∈ r, P i ↔ P' i) (HF : ∀ i ∈ r, F i = F' i) : (big[(◆)/nil]_(i ∈ r | (P i)) (F i)) = (big[(◆)/nil]_(i ∈ r | (P' i)) (F' i)) := begin unfold apply_bigop, rw list.filter_congr HP, apply list.foldr_ext, intros _ i_r _, simp[HF, mem_filter.1 i_r] end lemma big.map {J : Type*} (f : I → J) (P : J → Prop) [decidable_pred P] (F : J → R) : (big[(◆)/nil]_(j ∈ map f r | (P j)) (F j)) = (big[(◆)/nil]_(i ∈ r | (P (f i))) (F (f i))) := by simp[apply_bigop, filter_map_comm, foldr_map] --set_option pp.all true lemma big.empty_range (P : ℤ → Prop) [decidable_pred P] (F : ℤ → R) (a b : ℤ) (H : b ≤ a) : (big[(◆)/nil]_(i=a..b | (P i)) (F i)) = nil := begin convert big.nil op nil P F, exact (int.range_eq_nil _ _).2 H end lemma big.shift (P : ℤ → Prop) [decidable_pred P] (F : ℤ → R) (a b k : ℤ) : (big[(◆)/nil]_(i=a..b | (P i)) (F i)) = (big[(◆)/nil]_(i=(a+k)..(b+k) | (P (i-k))) (F (i-k))) := begin rw [int.range_shift, big.map], congr ; ext ; ring end /- Now we go towards assuming (R, op, nil) is a monoid -/ /- Also need to make sure old hierarchy talks to new one. Associativity seems ok but we need: -/ instance add_monoid_is_left_id (α : Type*) [add_monoid α] : is_left_id α (+) 0 := ⟨by simp⟩ instance add_monoid_is_right_id (α : Type*) [add_monoid α] : is_right_id α (+) 0 := ⟨by simp⟩ instance monoid_is_left_id (α : Type*) [monoid α] : is_left_id α (*) 1 := ⟨by simp⟩ instance monoid_is_right_id (α : Type*) [monoid α] : is_right_id α (*) 1 := ⟨by simp⟩ section nil_left_id /- Assuming only that nil is left neutral for op -/ variable [is_left_id R op nil] open is_left_id lemma big.cons {h} (t) : (big[(◆)/nil]_(i ∈ h::t | (P i)) (F i)) = ?(F h) ◆ (big[(◆)/nil]_(i ∈ t | (P i)) (F i)):= begin by_cases H : P h, { simp [H, big_cons_true] }, { simp [H, big_cons_false, left_id op] } end end nil_left_id section nil_right_id /- Assuming only that nil is left neutral for op -/ variable [is_right_id R op nil] open is_right_id lemma big.one_term (i₀ : I) : (big[(◆)/nil]_(i ∈ [i₀]) F i) = F i₀ := by simp [apply_bigop, right_id op] lemma big.one_term' (i₀ : I) : (big[(◆)/nil]_(i ∈ [i₀] | P i) F i) = if P i₀ then F i₀ else nil := by by_cases H : P i₀; simp [H, apply_bigop, right_id op] end nil_right_id section left_monoid /- Assume that (R, op) is almost a monoid with neutral element nil -/ variables [is_left_id R op nil] [is_associative R op] open is_left_id is_associative lemma big.append (r₁ r₂ : list I) : (big[(◆)/nil]_(i ∈ r₁++r₂ | (P i)) (F i)) = (big[(◆)/nil]_(i ∈ r₁ | (P i)) (F i)) ◆ (big[(◆)/nil]_(i ∈ r₂ | (P i)) (F i)) := begin let Op := λ l, big[(◆)/nil]_(i ∈ l | (P i)) (F i), induction r₁ with h t IH, { exact (eq.symm $ calc Op [] ◆ Op r₂ = nil ◆ (big[(◆)/nil]_(i ∈ r₂ | P i)F i) : by {dsimp [Op], rw big.nil} ... = _ : left_id _ _ )}, { have : ?(F h) ◆ Op t = Op (h :: t) := eq.symm (big.cons _ _ _ _ _), exact calc Op (h :: t ++ r₂) = Op (h :: (t ++ r₂)) : rfl ... = ?(F h) ◆ Op (t ++ r₂) : big.cons _ _ _ _ _ ... = ?(F h) ◆ (Op t ◆ Op r₂) : by simp [Op, IH] ... = (?(F h) ◆ Op t) ◆ Op r₂ : eq.symm $ assoc _ _ _ _ ... = Op (h::t) ◆ Op r₂ : by rw this } end end left_monoid section monoid variables [is_left_id R op nil] [is_right_id R op nil] [is_associative R op] open is_left_id is_right_id is_associative lemma big.concat (i) : (big[(◆)/nil]_(j ∈ concat r i | (P j)) (F j)) = (big[(◆)/nil]_(j ∈ r | (P j)) (F j)) ◆ (if P i then F i else nil) := by simp [big.append,big.one_term'] lemma big.concat_true (i) : (big[(◆)/nil]_(i ∈ concat r i) (F i)) = (big[(◆)/nil]_(i ∈ r) (F i)) ◆ F i := by apply big.concat lemma big.concat_range_true (F : ℤ → R) {a b : ℤ} (h : a < b) : (big[(◆)/nil]_(i =a..b) (F i)) = (big[(◆)/nil]_(i =a..b-1) (F i)) ◆ F (b-1) := by rw int_range_eq_concat h ; apply big.concat_true lemma big.commute_through {a : R} (H : ∀ i, P i → a ◆ F i = F i ◆ a) : a ◆ (big[(◆)/nil]_(i ∈ r | (P i)) F i) = (big[(◆)/nil]_(i ∈ r | (P i)) (F i)) ◆ a := begin let K := λ x, (a ◆ x = x ◆ a), change K (big[(◆)/nil]_(i ∈ r | (P i)) F i), apply big_ind ; dsimp [K], { simp [left_id op, right_id op] }, { intros x y xop yop, rw [assoc op, ←assoc op, xop, ← yop, assoc op]}, { exact H } end lemma big.reverse_of_commute (H : ∀ i j, P i → P j → F i ◆ F j = F j ◆ F i) : (big[(◆)/nil]_(i ∈ r | (P i)) F i) = (big[(◆)/nil]_(i ∈ reverse r | (P i)) (F i)) := begin induction r with h t IH, { simp }, { rw [big.cons, reverse_cons, ←concat_eq_append, big.concat], by_cases Ph : P h, { simp only [Ph], rw IH, apply big.commute_through, simp * {contextual := true } }, { simp [Ph, left_id op, right_id op, IH, H] { contextual := true } } } end lemma big.reverse_range_of_commute (P : ℤ → Prop) [decidable_pred P] (F : ℤ → R) (a b : ℤ) (H : ∀ i j, P i → P j → F i ◆ F j = F j ◆ F i) : (big[(◆)/nil]_(i=a..b | (P i)) F i) = (big[(◆)/nil]_(i=a..b | (P (a+b-i-1))) (F (a+b-i-1))) := by rw [big.reverse_of_commute _ _ _ _ _ H, reverse_int_range_map_int_range, big.map] lemma big.gather_of_commute (F G : I → R) [decidable_eq I] (H : ∀ n n' (h : n < r.length) (h' : n' < r.length), n ≠ n' → F (r.nth_le n h) ◆ G (r.nth_le n' h') = G (r.nth_le n' h') ◆ F (r.nth_le n h)) : (big[(◆)/nil]_(i ∈ r) F i) ◆ (big[(◆)/nil]_(i ∈ r) G i) = big[(◆)/nil]_(i ∈ r) F i ◆ G i := begin induction r with a t IH, { simp, rw left_id op }, { have key : ∀ i ∈ t, G a ◆ F i = F i ◆ G a, { intros i i_in, rcases nth_le_of_mem i_in with ⟨n, h, Hn⟩, specialize H (n+1) 0 (nat.succ_lt_succ h) (nat.succ_pos _), simp at H, rw ←Hn, exact H.symm }, simp only [big_cons_true] , conv_lhs { rw assoc op, congr, skip, rw ←assoc op, congr, rw big.filter_mem, rw ←big.commute_through _ _ _ _ _ key, }, rw [assoc op, assoc op, ←big.filter_mem], congr, apply IH, introv neq, replace neq : n + 1 ≠ n' + 1 := λ hneq, neq (nat.succ_inj hneq), specialize H (n+1) (n'+1) (nat.succ_lt_succ h) (nat.succ_lt_succ h') neq, rwa nth_le_cons at H }, end lemma big.gather_of_commute_int (F G : ℤ → R) (a b) (H : ∀ i j, i ≠ j → F i ◆ G j = G j ◆ F i) : (big[(◆)/nil]_(i = a..b) F i) ◆ (big[(◆)/nil]_(i = a..b) G i) = big[(◆)/nil]_(i = a..b) F i ◆ G i := begin apply big.gather_of_commute, introv neq, apply H, simp [int.range, neq], end lemma apply_ite {nil : R} {φ : R → R} (Hnil : φ nil = nil) (h : I) : φ (ite (P h) (F h) nil) = ite (P h) (φ (F h)) nil := calc φ (ite (P h) (F h) nil) = ite (P h) (φ $ F h) (φ nil) : by { by_cases H : P h; simp[H] } ... = ite (P h) (φ $ F h) nil : by rw Hnil lemma big.mph {φ : R → R} (Hop : ∀ a b : R, φ (a ◆ b) = φ a ◆ φ b) (Hnil : φ nil = nil) : φ (big[(◆)/nil]_(i ∈ r | (P i)) F i) = big[(◆)/nil]_(i ∈ r | (P i)) φ (F i) := begin induction r with h t IH, { simp [big.nil, Hnil] }, { rw [big.cons, Hop, IH, apply_ite _ _ Hnil, ←(big.cons op nil P _ t)] } end lemma big.anti_mph {φ : R → R} (Hop : ∀ a b : R, φ (a ◆ b) = φ b ◆ φ a) (Hnil : φ nil = nil) : φ (big[(◆)/nil]_(i ∈ r | (P i)) F i) = big[(◆)/nil]_(i ∈ r.reverse | (P i)) φ (F i) := begin induction r with h t IH, { simp [big.nil, Hnil] }, { rw [big.cons, Hop, apply_ite _ _ Hnil, reverse_cons', concat_eq_append, big.append, IH, big.one_term'] } end lemma big.range_anti_mph {φ : R → R} (P : ℤ → Prop) [decidable_pred P] (F : ℤ → R) (a b : ℤ) (Hop : ∀ a b : R, φ (a ◆ b) = φ b ◆ φ a) (Hnil : φ nil = nil) : φ (big[(◆)/nil]_(i=a..b | (P i)) F i) = big[(◆)/nil]_(i=a..b | (P (a+b-i-1))) φ (F (a+b-i-1)) := by rw [big.anti_mph _ _ _ _ _ Hop Hnil, reverse_int_range_map_int_range, big.map] end monoid
9db95b32ef91c107b59b33e9936d3a2e23e3420e
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/format.lean
4d02e0d2958a443c2e5b17cc3c2bc8f355a4bc8b
[ "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
289
lean
import system.io open list #eval pp ([["aaa", "bbb", "ccc", "dddd", "eeeeee", "ffffff"], ["aaa", "bbb", "ccc", "dddd", "eeeeee", "ffffff"], ["aaa", "bbb", "ccc", "dddd", "eeeeee", "ffffff"], ["aaa", "bbb", "ccc", "dddd", "eeeeee", "ffffff"]], [(10:nat), 20, 30])
675511e42ea0a099c109a4616b1815bfc44b989a
491068d2ad28831e7dade8d6dff871c3e49d9431
/library/init/wf.lean
34b62313e1f4106803055326f6d18b51292d716f
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,384
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.relation init.tactic inductive acc {A : Type} (R : A → A → Prop) : A → Prop := intro : ∀x, (∀ y, R y x → acc R y) → acc R x namespace acc variables {A : Type} {R : A → A → Prop} definition inv {x y : A} (H₁ : acc R x) (H₂ : R y x) : acc R y := acc.rec_on H₁ (λ x₁ ac₁ iH H₂, ac₁ y H₂) H₂ -- dependent elimination for acc protected definition drec [recursor] {C : Π (a : A), acc R a → Type} (h₁ : Π (x : A) (acx : Π (y : A), R y x → acc R y), (Π (y : A) (ryx : R y x), C y (acx y ryx)) → C x (acc.intro x acx)) {a : A} (h₂ : acc R a) : C a h₂ := begin refine acc.rec _ h₂ h₂, intro x acx ih h₂, exact h₁ x acx (λ y ryx, ih y ryx (acx y ryx)) end end acc inductive well_founded [class] {A : Type} (R : A → A → Prop) : Prop := intro : (∀ a, acc R a) → well_founded R namespace well_founded definition apply [coercion] {A : Type} {R : A → A → Prop} (wf : well_founded R) : ∀a, acc R a := take a, well_founded.rec_on wf (λp, p) a section parameters {A : Type} {R : A → A → Prop} local infix `≺`:50 := R hypothesis [Hwf : well_founded R] theorem recursion {C : A → Type} (a : A) (H : Πx, (Πy, y ≺ x → C y) → C x) : C a := acc.rec_on (Hwf a) (λ x₁ ac₁ iH, H x₁ iH) theorem induction {C : A → Prop} (a : A) (H : ∀x, (∀y, y ≺ x → C y) → C x) : C a := recursion a H variable {C : A → Type} variable F : Πx, (Πy, y ≺ x → C y) → C x definition fix_F (x : A) (a : acc R x) : C x := acc.rec_on a (λ x₁ ac₁ iH, F x₁ iH) theorem fix_F_eq (x : A) (r : acc R x) : fix_F F x r = F x (λ (y : A) (p : y ≺ x), fix_F F y (acc.inv r p)) := begin induction r using acc.drec, reflexivity -- proof is trivial due to proof irrelevance end end variables {A : Type} {C : A → Type} {R : A → A → Prop} -- Well-founded fixpoint definition fix [Hwf : well_founded R] (F : Πx, (Πy, R y x → C y) → C x) (x : A) : C x := fix_F F x (Hwf x) -- Well-founded fixpoint satisfies fixpoint equation theorem fix_eq [Hwf : well_founded R] (F : Πx, (Πy, R y x → C y) → C x) (x : A) : fix F x = F x (λy h, fix F y) := fix_F_eq F x (Hwf x) end well_founded open well_founded -- Empty relation is well-founded definition empty.wf {A : Type} : well_founded empty_relation := well_founded.intro (λ (a : A), acc.intro a (λ (b : A) (lt : false), false.rec _ lt)) -- Subrelation of a well-founded relation is well-founded namespace subrelation section parameters {A : Type} {R Q : A → A → Prop} parameters (H₁ : subrelation Q R) parameters (H₂ : well_founded R) definition accessible {a : A} (ac : acc R a) : acc Q a := using H₁, begin induction ac with x ax ih, constructor, exact λ (y : A) (lt : Q y x), ih y (H₁ lt) end definition wf : well_founded Q := well_founded.intro (λ a, accessible (H₂ a)) end end subrelation -- The inverse image of a well-founded relation is well-founded namespace inv_image section parameters {A B : Type} {R : B → B → Prop} parameters (f : A → B) parameters (H : well_founded R) private definition acc_aux {b : B} (ac : acc R b) : ∀ x, f x = b → acc (inv_image R f) x := begin induction ac with x acx ih, intro z e, constructor, intro y lt, subst x, exact ih (f y) lt y rfl end definition accessible {a : A} (ac : acc R (f a)) : acc (inv_image R f) a := acc_aux ac a rfl definition wf : well_founded (inv_image R f) := well_founded.intro (λ a, accessible (H (f a))) end end inv_image -- The transitive closure of a well-founded relation is well-founded namespace tc section parameters {A : Type} {R : A → A → Prop} local notation `R⁺` := tc R definition accessible {z} (ac: acc R z) : acc R⁺ z := begin induction ac with x acx ih, constructor, intro y lt, induction lt with a b rab a b c rab rbc ih₁ ih₂, {exact ih a rab}, {exact acc.inv (ih₂ acx ih) rab} end definition wf (H : well_founded R) : well_founded R⁺ := well_founded.intro (λ a, accessible (H a)) end end tc
183c71e764a138c2c2cf2e19fbc6365b1a8ddd7b
ea7e4e10c8e02ca90fe014eb18bf5a44ce3a3502
/src/affine_algebraic_set.lean
dfc65bbf831affb609e4f01acb3bb96b82413a18
[ "Apache-2.0" ]
permissive
roro47/M4P33
d4f49cc1a45954e03b42eaca559c9ab8024b1a38
34a93f45035add9dc909203f7957ce3822c38cdd
refs/heads/master
1,607,563,697,384
1,578,860,560,000
1,578,860,560,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,029
lean
/- Copyright (c) 2020 Kevin Buzzard Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, and whoever else wants to join in. -/ import for_mathlib.algebraically_closed import data.mv_polynomial /-! # Affine algebraic sets This file defines affine algebraic subsets of affine n-space and proves basic properties about them. ## Important definitions * `affine_algebraic_set k` -- the type of affine algebraic sets over the field `k`. ## Notation None as yet -- do we need 𝔸ⁿ for affine n-space? ## Implementation notes Much, but not all, of this file assumes that `k` is algebraically closed. Remark: analysis/complex/polynomial.lean contains proof that ℂ is alg closed. ## References Martin Orr's lecture notes! ## Tags algebraic geometry, algebraic variety -/ -- let k be a field variables {k : Type*} [discrete_field k] -- and let n be a natural number variable {n : ℕ} -- In Lean, the multivariable polynomial ring k[X₁, X₂, ..., Xₙ] is -- denoted `mv_polynomial (fin n) k`. We could use better notation. -- The set kⁿ is denoted `fin n → k` (which means maps from {0,1,2,...,(n-1)} to k). -- We now make some definitions which we'll need in the course. namespace mv_polynomial -- means "multivariable polynomial" /-- The set of zeros in kⁿ of a function f ∈ k[X₁, X₂, ..., Xₙ] -/ def zeros (f : mv_polynomial (fin n) k) : set (fin n → k) := {x | f.eval x = 0} /-- x is in the zeros of f iff f(x) = 0 -/ @[simp] lemma mem_zeros (f : mv_polynomial (fin n) k) (x : fin n → k) : x ∈ f.zeros ↔ f.eval x = 0 := iff.rfl /-- The zeros of f * g are the union of the zeros of f and of g -/ lemma zeros_mul (f g : mv_polynomial (fin n) k) : zeros (f * g) = zeros f ∪ zeros g := begin -- two sets are equal if they have the same elements ext, -- and now it's not hard to prove using `mem_zeros` and other -- equalities known to Lean's simplifier. simp, end open mv_polynomial /-- An affine algebraic subset of kⁿ is the common zeros of a set of polynomials -/ structure affine_algebraic_set (k : Type*) [discrete_field k] (n : ℕ) := -- a subset of the set of maps {0,1,2,...,n-1} → k (called "carrier") (carrier : set (fin n → k)) -- ...such that there's a set of polynomials such that the carrier is equal to the -- intersection of the zeros of the polynomials in the set. (is_algebraic : ∃ S : set (mv_polynomial (fin n) k), carrier = ⋂ f ∈ S, zeros f) -- ...such that namespace affine_algebraic_set -- Now some basic facts about affine algebrai subsets. set_option trace.simplify.rewrite false set_option trace.simplify.rewrite true /-- Two affine algebraic subsets with the same carrier are equal! -/ lemma ext (V W : affine_algebraic_set k n) : V.carrier = W.carrier → V = W := begin intro h, cases V, cases W, simpa, end /-- We can talk about elements of affine algebraic subsets of kⁿ -/ instance : has_mem (fin n → k) (affine_algebraic_set k n) := ⟨λ x V, x ∈ V.carrier⟩ /-- The union of two algebraic subsets of kⁿ is an algebraic subset-/ def union (V W : affine_algebraic_set k n) : affine_algebraic_set k n := { carrier := V.carrier ∪ W.carrier, is_algebraic := begin -- say S is the set that defines V cases V.is_algebraic with S hS, -- and T is the set that defines W cases W.is_algebraic with T hT, use {u | ∃ (s ∈ S) (t ∈ T), u = s * t}, -- To prove that V ∪ W is defined by this set, we prove both inclusions apply set.subset.antisymm, { -- say x ∈ V ∪ W, intros x hx, -- it's either in V or W. cases hx with hxV hxW, { -- Say it's in V rw set.mem_Inter, -- we have to show it's a zero of all the s * t intro u, suffices : ∀ s ∈ S, ∀ t ∈ T, u = s * t → x ∈ zeros u, simpa using this, rintro s hs t ht rfl, sorry, }, { sorry } }, { sorry } end } end affine_algebraic_set
2c6d581590389ac9b7e0582683febfe9898b6a45
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Init/Prelude.lean
a6e7a6fad85bf945f209f7e55d46a9dfbd59784e
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
61,186
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 universes u v w @[inline] def id {α : Sort u} (a : α) : α := a abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun x => a @[reducible] def inferInstance {α : Type u} [i : α] : α := i @[reducible] def inferInstanceAs (α : Type u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in inductive PUnit : Sort u | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α inductive True : Prop | intro : True inductive False : Prop inductive Empty : Type def Not (a : Prop) : Prop := a → False @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := False.elim (h₂ h₁) inductive Eq {α : Sort u} (a : α) : α → Prop | refl {} : Eq a a abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := Eq.rec (motive := fun α _ => motive α) m h @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl @[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := Eq.rec (motive := fun α _ => α) a h theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl /- Initialize the Quotient Module, which effectively adds the following definitions: constant Quot {α : Sort u} (r : α → α → Prop) : Sort u constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ init_quot inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop | refl {} : HEq a a @[matchPattern] def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b from fun α β a b h₁ => HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b) (fun (h₂ : Eq α α) => rfl) h₁ this α α a a' h rfl structure Prod (α : Type u) (β : Type v) := (fst : α) (snd : β) attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) := (fst : α) (snd : β) /-- Similar to `Prod`, but `α` and `β` are in the same universe. -/ structure MProd (α β : Type u) := (fst : α) (snd : β) structure And (a b : Prop) : Prop := intro :: (left : a) (right : b) inductive Or (a b : Prop) : Prop | inl (h : a) : Or a b | inr (h : b) : Or a b inductive Bool : Type | false : Bool | true : Bool export Bool (false true) /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) := (val : α) (property : p val) /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /-- Auxiliary Declaration used to implement the named patterns `x@p` -/ @[reducible] def namedPattern {α : Sort u} (x a : α) : α := a /- Auxiliary axiom used to implement `sorry`. -/ axiom sorryAx (α : Sort u) (synthetic := true) : α theorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, h => rfl theorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → Eq b true | true, h => rfl | false, h => False.elim (h rfl) theorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h class Inhabited (α : Sort u) := mk {} :: (default : α) constant arbitrary (α : Sort u) [s : Inhabited α] : α := @Inhabited.default α s instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) := { default := fun _ => arbitrary β } instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) := { default := fun a => arbitrary (β a) } /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u := up :: (down : α) /- Bijection between α and PLift α -/ theorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b | up a => rfl theorem PLift.downUp {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /- Pointed types -/ structure PointedType := (type : Type u) (val : type) instance : Inhabited PointedType.{u} := { default := { type := PUnit.{u+1}, val := ⟨⟩ } } /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) := up :: (down : α) /- Bijection between α and ULift.{v} α -/ theorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b | up a => rfl theorem ULift.downUp {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl class inductive Decidable (p : Prop) | isFalse (h : Not p) : Decidable p | isTrue (h : p) : Decidable p @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) := s a b theorem decideEqTrue : {p : Prop} → [s : Decidable p] → p → Eq (decide p) true | _, isTrue _, _ => rfl | _, isFalse h₁, h₂ => absurd h₂ h₁ theorem decideEqFalse : {p : Prop} → [s : Decidable p] → Not p → Eq (decide p) false | _, isTrue h₁, h₂ => absurd h₁ h₂ | _, isFalse h, _ => rfl theorem ofDecideEqTrue {p : Prop} [s : Decidable p] : Eq (decide p) true → p := fun h => match s with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁)) theorem ofDecideEqFalse {p : Prop} [s : Decidable p] : Eq (decide p) false → Not p := fun h => match s with | isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁)) | isFalse h₁ => h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl class BEq (α : Type u) := (beq : α → α → Bool) open BEq (beq) instance {α : Type u} [DecidableEq α] : BEq α := ⟨fun a b => decide (Eq a b)⟩ -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := Decidable.casesOn (motive := fun _ => α) h e t /- if-then-else -/ @[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α := Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) := match dp with | isTrue hp => match dq with | isTrue hq => isTrue ⟨hp, hq⟩ | isFalse hq => isFalse (fun h => hq (And.right h)) | isFalse hp => isFalse (fun h => hp (And.left h)) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) := match dp with | isTrue hp => isTrue (Or.inl hp) | isFalse hp => match dq with | isTrue hq => isTrue (Or.inr hq) | isFalse hq => isFalse fun h => match h with | Or.inl h => hp h | Or.inr h => hq h instance {p} [dp : Decidable p] : Decidable (Not p) := match dp with | isTrue hp => isFalse (absurd hp) | isFalse hp => isTrue hp /- Boolean operators -/ @[macroInline] def cond {a : Type u} : Bool → a → a → a | true, x, y => x | false, x, y => y @[macroInline] def or : Bool → Bool → Bool | true, _ => true | false, b => b @[macroInline] def and : Bool → Bool → Bool | false, _ => false | true, b => b @[macroInline] def not : Bool → Bool | true => false | false => true inductive Nat | zero : Nat | succ (n : Nat) : Nat /- For numeric literals notation -/ class OfNat (α : Type u) := (ofNat : Nat → α) export OfNat (ofNat) instance : OfNat Nat := ⟨id⟩ instance : Inhabited Nat := { default := 0 } class HasLessEq (α : Type u) := (LessEq : α → α → Prop) class HasLess (α : Type u) := (Less : α → α → Prop) export HasLess (Less) export HasLessEq (LessEq) class Add (α : Type u) := (add : α → α → α) class Mul (α : Type u) := (mul : α → α → α) class Neg (α : Type u) := (neg : α → α) class Sub (α : Type u) := (sub : α → α → α) class Div (α : Type u) := (div : α → α → α) class Mod (α : Type u) := (mod : α → α → α) class ModN (α : Type u) := (modn : α → Nat → α) class Pow (α : Type u) (β : Type v) := (pow : α → β → α) class Append (α : Type u) := (append : α → α → α) class OrElse (α : Type u) := (orElse : α → α → α) class AndThen (α : Type u) := (andThen : α → α → α) open Add (add) open Mul (mul) open Pow (pow) open Append (append) @[reducible] def GreaterEq {α : Type u} [HasLessEq α] (a b : α) : Prop := LessEq b a @[reducible] def Greater {α : Type u} [HasLess α] (a b : α) : Prop := Less b a set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a, Nat.zero => a | a, Nat.succ b => Nat.succ (Nat.add a b) instance : Add Nat := { add := Nat.add } /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [matchPattern] Nat.add Add.add Neg.neg set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_mul"] protected def Nat.mul : (@& Nat) → (@& Nat) → Nat | a, 0 => 0 | a, Nat.succ b => Nat.add (Nat.mul a b) a instance : Mul Nat := { mul := Nat.mul } set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_pow"] protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat | 0 => 1 | succ n => Nat.mul (Nat.pow m n) m instance : Pow Nat Nat := { pow := Nat.pow } set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_dec_eq"] def Nat.beq : Nat → Nat → Bool | zero, zero => true | zero, succ m => false | succ n, zero => false | succ n, succ m => beq n m theorem Nat.eqOfBeqEqTrue : {n m : Nat} → Eq (beq n m) true → Eq n m | zero, zero, h => rfl | zero, succ m, h => Bool.noConfusion h | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have Eq (beq n m) true from h have Eq n m from eqOfBeqEqTrue this this ▸ rfl theorem Nat.neOfBeqEqFalse : {n m : Nat} → Eq (beq n m) false → Not (Eq n m) | zero, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Nat.noConfusion h₂ | succ n, zero, h₁, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have Eq (beq n m) false from h₁ Nat.noConfusion h₂ (fun h₂ => absurd h₂ (neOfBeqEqFalse this)) @[extern "lean_nat_dec_eq"] protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) := match h:beq n m with | true => isTrue (eqOfBeqEqTrue h) | false => isFalse (neOfBeqEqFalse h) @[inline] instance : DecidableEq Nat := Nat.decEq set_option bootstrap.gen_matcher_code false in @[extern "lean_nat_dec_le"] def Nat.ble : Nat → Nat → Bool | zero, zero => true | zero, succ m => true | succ n, zero => false | succ n, succ m => ble n m protected def Nat.le (n m : Nat) : Prop := Eq (ble n m) true instance : HasLessEq Nat := ⟨Nat.le⟩ protected def Nat.lt (n m : Nat) : Prop := Nat.le (succ n) m instance : HasLess Nat := ⟨Nat.lt⟩ theorem Nat.notSuccLeZero : ∀ (n : Nat), LessEq (succ n) 0 → False | 0, h => nomatch h | succ n, h => nomatch h theorem Nat.notLtZero (n : Nat) : Not (Less n 0) := notSuccLeZero n @[extern "lean_nat_dec_le"] instance Nat.decLe (n m : @& Nat) : Decidable (LessEq n m) := decEq (Nat.ble n m) true @[extern "lean_nat_dec_lt"] instance Nat.decLt (n m : @& Nat) : Decidable (Less n m) := decLe (succ n) m theorem Nat.zeroLe : (n : Nat) → LessEq 0 n | zero => rfl | succ n => rfl theorem Nat.succLeSucc {n m : Nat} (h : LessEq n m) : LessEq (succ n) (succ m) := h theorem Nat.zeroLtSucc (n : Nat) : Less 0 (succ n) := succLeSucc (zeroLe n) theorem Nat.leStep : {n m : Nat} → LessEq n m → LessEq n (succ m) | zero, zero, h => rfl | zero, succ n, h => rfl | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have LessEq n m from h have LessEq n (succ m) from leStep this succLeSucc this protected theorem Nat.leTrans : {n m k : Nat} → LessEq n m → LessEq m k → LessEq n k | zero, m, k, h₁, h₂ => zeroLe _ | succ n, zero, k, h₁, h₂ => Bool.noConfusion h₁ | succ n, succ m, zero, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, succ k, h₁, h₂ => have h₁' : LessEq n m from h₁ have h₂' : LessEq m k from h₂ Nat.leTrans h₁' h₂' protected theorem Nat.ltTrans {n m k : Nat} (h₁ : Less n m) : Less m k → Less n k := Nat.leTrans (leStep h₁) theorem Nat.leSucc : (n : Nat) → LessEq n (succ n) | zero => rfl | succ n => leSucc n theorem Nat.leSuccOfLe {n m : Nat} (h : LessEq n m) : LessEq n (succ m) := Nat.leTrans h (leSucc m) protected theorem Nat.eqOrLtOfLe : {n m: Nat} → LessEq n m → Or (Eq n m) (Less n m) | zero, zero, h => Or.inl rfl | zero, succ n, h => Or.inr (zeroLe n) | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have LessEq n m from h match Nat.eqOrLtOfLe this with | Or.inl h => Or.inl (h ▸ rfl) | Or.inr h => Or.inr (succLeSucc h) protected def Nat.leRefl : (n : Nat) → LessEq n n | zero => rfl | succ n => Nat.leRefl n protected theorem Nat.ltOrGe (n m : Nat) : Or (Less n m) (GreaterEq n m) := match m with | zero => Or.inr (zeroLe n) | succ m => match Nat.ltOrGe n m with | Or.inl h => Or.inl (leSuccOfLe h) | Or.inr h => match Nat.eqOrLtOfLe h with | Or.inl h1 => Or.inl (h1 ▸ Nat.leRefl _) | Or.inr h1 => Or.inr h1 protected theorem Nat.leAntisymm : {n m : Nat} → LessEq n m → LessEq m n → Eq n m | zero, zero, h₁, h₂ => rfl | succ n, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, h₁, h₂ => have h₁' : LessEq n m from h₁ have h₂' : LessEq m n from h₂ (Nat.leAntisymm h₁' h₂') ▸ rfl protected theorem Nat.ltOfLeOfNe {n m : Nat} (h₁ : LessEq n m) (h₂ : Not (Eq n m)) : Less n m := match Nat.ltOrGe n m with | Or.inl h₃ => h₃ | Or.inr h₃ => absurd (Nat.leAntisymm h₁ h₃) h₂ set_option bootstrap.gen_matcher_code false in @[extern c inline "lean_nat_sub(#1, lean_box(1))"] def Nat.pred : Nat → Nat | 0 => 0 | succ a => a theorem Nat.predLePred : {n m : Nat} → LessEq n m → LessEq (pred n) (pred m) | zero, zero, h => rfl | zero, succ n, h => zeroLe n | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => h theorem Nat.leOfSuccLeSucc {n m : Nat} : LessEq (succ n) (succ m) → LessEq n m := predLePred theorem Nat.leOfLtSucc {m n : Nat} : Less m (succ n) → LessEq m n := leOfSuccLeSucc @[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → { n : Nat // Or (Eq n 32) (Eq n 64) } := fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant def System.Platform.numBits : Nat := (getNumBits ()).val theorem System.Platform.numBitsEq : Or (Eq numBits 32) (Eq numBits 64) := (getNumBits ()).property structure Fin (n : Nat) := (val : Nat) (isLt : Less val n) theorem Fin.eqOfVeq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Fin.veqOfEq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val := h ▸ rfl theorem Fin.neOfVne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (veqOfEq h') h instance (n : Nat) : DecidableEq (Fin n) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (Fin.eqOfVeq h) | isFalse h => isFalse (Fin.neOfVne h) protected def Fin.lt {n} (a b : Fin n) : Prop := Less a.val b.val protected def Fin.le {n} (a b : Fin n) : Prop := LessEq a.val b.val instance {n} : HasLess (Fin n) := ⟨Fin.lt⟩ instance {n} : HasLessEq (Fin n) := ⟨Fin.le⟩ instance Fin.decLt {n} (a b : Fin n) : Decidable (Less a b) := Nat.decLt .. instance Fin.decLe {n} (a b : Fin n) : Decidable (LessEq a b) := Nat.decLe .. def uint8Sz : Nat := 256 structure UInt8 := (val : Fin uint8Sz) set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt8 := UInt8.decEq instance : Inhabited UInt8 := { default := { val := { val := 0, isLt := decide! } } } def uint16Sz : Nat := 65536 structure UInt16 := (val : Fin uint16Sz) set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt16 := UInt16.decEq instance : Inhabited UInt16 := { default := { val := { val := 0, isLt := decide! } } } def uint32Sz : Nat := 4294967296 structure UInt32 := (val : Fin uint32Sz) @[extern "lean_uint32_to_nat"] def UInt32.toNat (n : UInt32) : Nat := n.val.val set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt32 := UInt32.decEq instance : Inhabited UInt32 := { default := { val := { val := 0, isLt := decide! } } } def UInt32.lt (a b : UInt32) : Prop := Less a.val b.val def UInt32.le (a b : UInt32) : Prop := LessEq a.val b.val instance : HasLess UInt32 := ⟨UInt32.lt⟩ instance : HasLessEq UInt32 := ⟨UInt32.le⟩ set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 < #2"] def UInt32.decLt (a b : UInt32) : Decidable (Less a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (Less n m)) set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 <= #2"] def UInt32.decLe (a b : UInt32) : Decidable (LessEq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LessEq n m)) instance (a b : UInt32) : Decidable (Less a b) := UInt32.decLt a b instance (a b : UInt32) : Decidable (LessEq a b) := UInt32.decLe a b @[extern "lean_uint32_of_nat"] def UInt32.ofNatCore (n : @& Nat) (h : Less n uint32Sz) : UInt32 := { val := { val := n, isLt := h } } def uint64Sz : Nat := 18446744073709551616 structure UInt64 := (val : Fin uint64Sz) set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt64 := UInt64.decEq instance : Inhabited UInt64 := { default := { val := { val := 0, isLt := decide! } } } def usizeSz : Nat := pow 2 System.Platform.numBits theorem usizeSzEq : Or (Eq usizeSz 4294967296) (Eq usizeSz 18446744073709551616) := show Or (Eq (pow 2 System.Platform.numBits) 4294967296) (Eq (pow 2 System.Platform.numBits) 18446744073709551616) from match System.Platform.numBits, System.Platform.numBitsEq with | _, Or.inl rfl => Or.inl (decide! : (Eq (pow 2 32) (4294967296:Nat))) | _, Or.inr rfl => Or.inr (decide! : (Eq (pow 2 64) (18446744073709551616:Nat))) structure USize := (val : Fin usizeSz) set_option bootstrap.gen_matcher_code false in @[extern c inline "#1 == #2"] def USize.decEq (a b : USize) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq USize := USize.decEq instance : Inhabited USize := { default := { val := { val := 0, isLt := match usizeSz, usizeSzEq with | _, Or.inl rfl => decide! | _, Or.inr rfl => decide! } } } @[extern "lean_usize_of_nat"] def USize.ofNat32 (n : @& Nat) (h : Less n 4294967296) : USize := { val := { val := n, isLt := match usizeSz, usizeSzEq with | _, Or.inl rfl => h | _, Or.inr rfl => Nat.ltTrans h (decide! : Less 4294967296 18446744073709551616) } } @[extern "lean_usize_of_nat"] def USize.ofNatCore (n : @& Nat) (h : Less n usizeSz) : USize := { val := { val := n, isLt := h } } abbrev Nat.isValidChar (n : Nat) : Prop := Or (Less n 0xd800) (And (Less 0xdfff n) (Less n 0x110000)) abbrev UInt32.isValidChar (n : UInt32) : Prop := n.toNat.isValidChar /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char := (val : UInt32) (valid : val.isValidChar) private theorem validCharIsUInt32 {n : Nat} (h : n.isValidChar) : Less n uint32Sz := match h with | Or.inl h => Nat.ltTrans h (decide! : Less 55296 uint32Sz) | Or.inr ⟨_, h⟩ => Nat.ltTrans h (decide! : Less 1114112 uint32Sz) @[extern "lean_uint32_of_nat"] private def Char.ofNatAux (n : Nat) (h : n.isValidChar) : Char := { val := ⟨{ val := n, isLt := validCharIsUInt32 h }⟩, valid := h } @[noinline, matchPattern] def Char.ofNat (n : Nat) : Char := dite (n.isValidChar) (fun h => Char.ofNatAux n h) (fun _ => { val := ⟨{ val := 0, isLt := decide! }⟩, valid := Or.inl decide! }) theorem Char.eqOfVeq : ∀ {c d : Char}, Eq c.val d.val → Eq c d | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Char.veqOfEq : ∀ {c d : Char}, Eq c d → Eq c.val d.val | _, _, rfl => rfl theorem Char.neOfVne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) := fun h' => absurd (veqOfEq h') h theorem Char.vneOfNe {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) := fun h' => absurd (eqOfVeq h') h instance : DecidableEq Char := fun c d => match decEq c.val d.val with | isTrue h => isTrue (Char.eqOfVeq h) | isFalse h => isFalse (Char.neOfVne h) def Char.utf8Size (c : Char) : UInt32 := let v := c.val ite (LessEq v (UInt32.ofNatCore 0x7F decide!)) (UInt32.ofNatCore 1 decide!) (ite (LessEq v (UInt32.ofNatCore 0x7FF decide!)) (UInt32.ofNatCore 2 decide!) (ite (LessEq v (UInt32.ofNatCore 0xFFFF decide!)) (UInt32.ofNatCore 3 decide!) (UInt32.ofNatCore 4 decide!))) inductive Option (α : Type u) | none : Option α | some (val : α) : Option α attribute [unbox] Option export Option (none some) instance {α} : Inhabited (Option α) := { default := none } inductive List (α : Type u) | nil : List α | cons (head : α) (tail : List α) : List α instance {α} : Inhabited (List α) := { default := List.nil } protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b) | nil, nil => isTrue rfl | cons a as, nil => isFalse (fun h => List.noConfusion h) | nil, cons b bs => isFalse (fun h => List.noConfusion h) | cons a as, cons b bs => match decEq a b with | isTrue hab => match List.hasDecEq as bs with | isTrue habs => isTrue (hab ▸ habs ▸ rfl) | isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs)) | isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab)) instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq @[specialize] def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α | a, nil => a | a, cons b l => foldl f (f a b) l structure String := (data : List Char) attribute [extern "lean_string_mk"] String.mk attribute [extern "lean_string_data"] String.data @[extern "lean_string_dec_eq"] def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) := match s₁, s₂ with | ⟨s₁⟩, ⟨s₂⟩ => dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq String := String.decEq /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ abbrev String.Pos := Nat structure Substring := (str : String) (startPos : String.Pos) (stopPos : String.Pos) def String.csize (c : Char) : Nat := c.utf8Size.toNat private def String.utf8ByteSizeAux : List Char → Nat → Nat | List.nil, r => r | List.cons c cs, r => utf8ByteSizeAux cs (add r (csize c)) @[extern "lean_string_utf8_byte_size"] def String.utf8ByteSize : (@& String) → Nat | ⟨s⟩ => utf8ByteSizeAux s 0 @[inline] def String.bsize (s : String) : Nat := utf8ByteSize s @[inline] def String.toSubstring (s : String) : Substring := { str := s, startPos := 0, stopPos := s.bsize } @[extern c inline "#3"] unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β := cast lcProof (PUnit.{v}) @[neverExtract, extern "lean_panic_fn"] constant panic {α : Type u} [Inhabited α] (msg : String) : α /- The Compiler has special support for arrays. They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array -/ structure Array (α : Type u) := (sz : Nat) (data : Fin sz → α) attribute [extern "lean_array_mk"] Array.mk attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_sz"] Array.sz /- The parameter `c` is the initial capacity -/ @[extern "lean_mk_empty_array_with_capacity"] def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := { sz := 0, data := fun ⟨x, h⟩ => absurd h (Nat.notLtZero x) } def Array.empty {α : Type u} : Array α := mkEmpty 0 @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.sz @[extern "lean_array_fget"] def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α := a.data i /- "Comfortable" version of `fget`. It performs a bound check at runtime. -/ @[extern "lean_array_get"] def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α := dite (Less i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => arbitrary α) @[extern "lean_array_push"] def Array.push {α : Type u} (a : Array α) (v : α) : Array α := { sz := Nat.succ a.sz, data := fun ⟨j, h₁⟩ => dite (Eq j a.sz) (fun _ => v) (fun h₂ => a.data ⟨j, Nat.ltOfLeOfNe (Nat.leOfLtSucc h₁) h₂⟩) } class Bind (m : Type u → Type v) := (bind : {α β : Type u} → m α → (α → m β) → m β) export Bind (bind) class Pure (f : Type u → Type v) := (pure {α : Type u} : α → f α) export Pure (pure) class Functor (f : Type u → Type v) : Type (max (u+1) v) := (map : {α β : Type u} → (α → β) → f α → f β) (mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _)) class Seq (f : Type u → Type v) : Type (max (u+1) v) := (seq : {α β : Type u} → f (α → β) → f α → f β) class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) := (seqLeft : {α : Type u} → f α → f PUnit → f α) class SeqRight (f : Type u → Type v) : Type (max (u+1) v) := (seqRight : {β : Type u} → f PUnit → f β → f β) class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f := (map := fun x y => Seq.seq (pure x) y) (seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b) (seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b) class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) := (map := fun f x => bind x (Function.comp pure f)) (seq := fun f x => bind f (fun y => Functor.map y x)) (seqLeft := fun x y => bind x (fun a => bind y (fun _ => pure a))) (seqRight := fun x y => bind x (fun _ => y)) instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) := ⟨pure⟩ instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) := ⟨pure $ arbitrary _⟩ /-- A Function for lifting a computation from an inner Monad to an outer Monad. Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html), but `n` does not have to be a monad transformer. Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/ class MonadLift (m : Type u → Type v) (n : Type u → Type w) := (monadLift : {α : Type u} → m α → n α) /-- The reflexive-transitive closure of `MonadLift`. `monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`. Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/ class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) := (monadLift : {α : Type u} → m α → n α) export MonadLiftT (monadLift) abbrev liftM := @monadLift instance (m n o) [MonadLiftT m n] [MonadLift n o] : MonadLiftT m o := { monadLift := fun x => MonadLift.monadLift (m := n) (monadLift x) } instance (m) : MonadLiftT m m := { monadLift := fun x => x } /-- A functor in the category of monads. Can be used to lift monad-transforming functions. Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html), but not restricted to monad transformers. Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/ class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) := (monadMap {α : Type u} : (∀ {β}, m β → m β) → n α → n α) /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift Monad morphisms -/ class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) := (monadMap {α : Type u} : (∀ {β}, m β → m β) → n α → n α) export MonadFunctorT (monadMap) instance (m n o) [MonadFunctorT m n] [MonadFunctor n o] : MonadFunctorT m o := { monadMap := fun f => MonadFunctor.monadMap (m := n) (monadMap (m := m) f) } instance monadFunctorRefl (m) : MonadFunctorT m m := { monadMap := fun f => f } inductive Except (ε : Type u) (α : Type v) | error : ε → Except ε α | ok : α → Except ε α attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) := ⟨Except.error (arbitrary ε)⟩ /-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/ class MonadExceptOf (ε : Type u) (m : Type v → Type w) := (throw {α : Type v} : ε → m α) (tryCatch {α : Type v} : m α → (ε → m α) → m α) abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α := MonadExceptOf.throw e abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α := MonadExceptOf.tryCatch x handle /-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) := (throw {α : Type v} : ε → m α) (tryCatch {α : Type v} : m α → (ε → m α) → m α) export MonadExcept (throw tryCatch) instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m := { throw := throwThe ε, tryCatch := tryCatchThe ε } namespace MonadExcept variables {ε : Type u} {m : Type v → Type w} @[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α := tryCatch t₁ fun _ => t₂ instance [MonadExcept ε m] {α : Type v} : OrElse (m α) := ⟨MonadExcept.orelse⟩ end MonadExcept /-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) := ⟨fun _ => arbitrary _⟩ @[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r @[reducible] def Reader (ρ : Type u) := ReaderT ρ id namespace ReaderT section variables {ρ : Type u} {m : Type u → Type v} {α : Type u} @[inline] protected def lift (a : m α) : ReaderT ρ m α := fun r => a instance : MonadLift m (ReaderT ρ m) := ⟨ReaderT.lift⟩ instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) := { throw := Function.comp ReaderT.lift (throwThe ε), tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r) } end section variables {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def read : ReaderT ρ m ρ := pure @[inline] protected def pure (a : α) : ReaderT ρ m α := fun r => pure a @[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => bind (x r) fun a => f a r @[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β := fun r => Functor.map f (x r) instance : Monad (ReaderT ρ m) := { pure := ReaderT.pure, bind := ReaderT.bind, map := ReaderT.map } instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) := ⟨fun f x r => f (x r)⟩ @[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) end end ReaderT /-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader). It does not contain `local` because this Function cannot be lifted using `monadLift`. Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) := (lift {α : Type u} : (∀ {m : Type u → Type u} [Monad m], ReaderT ρ m α) → n α) ``` -/ class MonadReaderOf (ρ : Type u) (m : Type u → Type v) := (read : m ρ) @[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) := (read : m ρ) export MonadReader (read) instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m := ⟨readThe ρ⟩ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadReaderOf ρ m] [MonadLift m n] : MonadReaderOf ρ n := ⟨monadLift (MonadReader.read : m ρ)⟩ instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) := ⟨ReaderT.read⟩ class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) := (withReader {α : Type u} : (ρ → ρ) → m α → m α) @[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α := MonadWithReaderOf.withReader f x class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) := (withReader {α : Type u} : (ρ → ρ) → m α → m α) export MonadWithReader (withReader) instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m := ⟨withTheReader ρ⟩ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadWithReaderOf ρ m] [MonadFunctor m n] : MonadWithReaderOf ρ n := ⟨fun f => monadMap (m := m) (withTheReader ρ f)⟩ instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) := ⟨fun f x ctx => x (f ctx)⟩ /-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html). In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monadLift`. -/ class MonadStateOf (σ : Type u) (m : Type u → Type v) := /- Obtain the top-most State of a Monad stack. -/ (get : m σ) /- Set the top-most State of a Monad stack. -/ (set : σ → m PUnit) /- Map the top-most State of a Monad stack. Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a` because the latter does not use the State linearly (without sufficient inlining). -/ (modifyGet {α : Type u} : (σ → Prod α σ) → m α) export MonadStateOf (set) abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ := MonadStateOf.get @[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit := MonadStateOf.modifyGet fun s => (PUnit.unit, f s) @[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α := MonadStateOf.modifyGet f /-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/ class MonadState (σ : outParam (Type u)) (m : Type u → Type v) := (get : m σ) (set : σ → m PUnit) (modifyGet {α : Type u} : (σ → Prod α σ) → m α) export MonadState (get modifyGet) instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m := { set := MonadStateOf.set, get := getThe σ, modifyGet := fun f => MonadStateOf.modifyGet f } @[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit := modifyGet fun s => (PUnit.unit, f s) @[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ := modifyGet fun s => (s, f s) -- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer -- will be picked first instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadStateOf σ m] [MonadLift m n] : MonadStateOf σ n := { get := liftM (m := m) MonadStateOf.get, set := fun s => liftM (m := m) (MonadStateOf.set s), modifyGet := fun f => monadLift (m := m) (MonadState.modifyGet f) } namespace EStateM inductive Result (ε σ α : Type u) | ok : α → σ → Result ε σ α | error : ε → σ → Result ε σ α variables {ε σ α : Type u} instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) := ⟨Result.error (arbitrary _) (arbitrary _)⟩ end EStateM open EStateM (Result) in def EStateM (ε σ α : Type u) := σ → 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 : σ → Prod α σ) : 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 tryCatch {δ} [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 @[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 @[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 δ σ] : OrElse (EStateM ε σ α) := { orElse := EStateM.orElse } instance : MonadStateOf σ (EStateM ε σ) := { set := EStateM.set, get := EStateM.get, modifyGet := EStateM.modifyGet } instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) := { throw := EStateM.throw, tryCatch := EStateM.tryCatch } @[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 class Hashable (α : Type u) := (hash : α → USize) export Hashable (hash) @[extern "lean_usize_mix_hash"] constant mixHash (u₁ u₂ : USize) : USize @[extern "lean_string_hash"] protected constant String.hash (s : @& String) : USize instance : Hashable String := ⟨String.hash⟩ namespace Lean /- Hierarchical names -/ inductive Name | anonymous : Name | str : Name → String → USize → Name | num : Name → Nat → USize → Name instance : Inhabited Name := ⟨Name.anonymous⟩ protected def Name.hash : Name → USize | Name.anonymous => USize.ofNat32 1723 decide! | Name.str p s h => h | Name.num p v h => h instance : Hashable Name := ⟨Name.hash⟩ namespace Name @[export lean_name_mk_string] def mkStr (p : Name) (s : String) : Name := Name.str p s (mixHash (hash p) (hash s)) @[export lean_name_mk_numeral] def mkNum (p : Name) (v : Nat) : Name := Name.num p v (mixHash (hash p) (dite (Less v usizeSz) (fun h => USize.ofNatCore v h) (fun _ => USize.ofNat32 17 decide!))) def mkSimple (s : String) : Name := mkStr Name.anonymous s @[extern "lean_name_eq"] protected def beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁ _, str p₂ s₂ _ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂) | num p₁ n₁ _, num p₂ n₂ _ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂) | _, _ => false instance : BEq Name := ⟨Name.beq⟩ protected def append : Name → Name → Name | n, anonymous => n | n, str p s _ => Name.mkStr (Name.append n p) s | n, num p d _ => Name.mkNum (Name.append n p) d instance : Append Name := ⟨Name.append⟩ end Name /- Syntax -/ /-- Source information of syntax atoms. All information is generally set for unquoted syntax and unset for syntax in syntax quotations, but syntax transformations might want to invalidate only one side to make the pretty printer reformat it. In the special case of the delaborator, we also use purely synthetic position information without whitespace information. -/ structure SourceInfo := /- Will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ (leading : Option Substring := none) (pos : Option String.Pos := none) (trailing : Option Substring := none) instance : Inhabited SourceInfo := ⟨{}⟩ abbrev SyntaxNodeKind := Name /- Syntax AST -/ inductive Syntax | missing : Syntax | node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | atom (info : SourceInfo) (val : String) : Syntax | ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax instance : Inhabited Syntax := ⟨Syntax.missing⟩ /- Builtin kinds -/ def choiceKind : SyntaxNodeKind := `choice def nullKind : SyntaxNodeKind := `null def identKind : SyntaxNodeKind := `ident def strLitKind : SyntaxNodeKind := `strLit def charLitKind : SyntaxNodeKind := `charLit def numLitKind : SyntaxNodeKind := `numLit def nameLitKind : SyntaxNodeKind := `nameLit def fieldIdxKind : SyntaxNodeKind := `fieldIdx def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind namespace Syntax def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node k args => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => Name.mkSimple v | Syntax.ident _ _ _ _ => identKind def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node _ args => Syntax.node k args | _ => stx def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ args => args.get! i | _ => Syntax.missing -- panic! "Syntax.getArg: not a node" -- Add `stx[i]` as sugar for `stx.getArg i` @[inline] def getOp (self : Syntax) (idx : Nat) : Syntax := self.getArg idx def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ args => args | _ => Array.empty end Syntax inductive ParserDescr | andthen : ParserDescr → ParserDescr → ParserDescr | orelse : ParserDescr → ParserDescr → ParserDescr | optional : ParserDescr → ParserDescr | lookahead : ParserDescr → ParserDescr | «try» : ParserDescr → ParserDescr | many : ParserDescr → ParserDescr | many1 : ParserDescr → ParserDescr | sepBy : ParserDescr → ParserDescr → Bool → ParserDescr | sepBy1 : ParserDescr → ParserDescr → Bool → ParserDescr | node : Name → Nat → ParserDescr → ParserDescr | trailingNode : Name → Nat → ParserDescr → ParserDescr | symbol : String → ParserDescr | nonReservedSymbol : String → Bool → ParserDescr | noWs : ParserDescr | numLit : ParserDescr | strLit : ParserDescr | charLit : ParserDescr | nameLit : ParserDescr | interpolatedStr : ParserDescr → ParserDescr -- interpolated string | ident : ParserDescr | cat : Name → Nat → ParserDescr | parser : Name → ParserDescr | notFollowedBy : ParserDescr → ParserDescr | withPosition : ParserDescr → ParserDescr | checkCol : Bool → ParserDescr instance : Inhabited ParserDescr := ⟨ParserDescr.symbol ""⟩ abbrev TrailingParserDescr := ParserDescr /- Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := add reservedMacroScope 1 /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). -/ class MonadQuotation (m : Type → Type) := -- Get the fresh scope of the current macro invocation (getCurrMacroScope : m MacroScope) (getMainModule : m Name) /- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ (withFreshMacroScope {α : Type} : m α → m α) export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope) instance {m n : Type → Type} [MonadQuotation m] [MonadLift m n] [MonadFunctorT m n] : MonadQuotation n := { getCurrMacroScope := liftM (m := m) getCurrMacroScope, getMainModule := liftM (m := m) getMainModule, withFreshMacroScope := monadMap (m := m) withFreshMacroScope } /- We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ def Name.hasMacroScopes : Name → Bool | str _ s _ => beq s "_hyg" | num p _ _ => hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | Name.str p s _ => match beq s "_@" with | true => p | false => eraseMacroScopesAux p | Name.num p _ _ => eraseMacroScopesAux p | Name.anonymous => Name.anonymous @[export lean_erase_macro_scopes] def Name.eraseMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => eraseMacroScopesAux n | false => n private def simpMacroScopesAux : Name → Name | Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i | n => eraseMacroScopesAux n /- Helper function we use to create binder names that do not need to be unique. -/ @[export lean_simp_macro_scopes] def Name.simpMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => simpMacroScopesAux n | false => n structure MacroScopesView := (name : Name) (imported : Name) (mainModule : Name) (scopes : List MacroScope) instance : Inhabited MacroScopesView := ⟨⟨arbitrary _, arbitrary _, arbitrary _, arbitrary _⟩⟩ def MacroScopesView.review (view : MacroScopesView) : Name := match view.scopes with | List.nil => view.name | List.cons _ _ => let base := (Name.mkStr (append (append (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg") view.scopes.foldl Name.mkNum base private def assembleParts : List Name → Name → Name | List.nil, acc => acc | List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s) | List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n) | _, acc => panic "unreachable @ assembleParts" private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } | false => extractImported scps mainModule p (List.cons n parts) | n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts) | _, _ => panic "unreachable @ extractImported" private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } | false => extractMainModule scps p (List.cons n parts) | n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil | _, _ => panic "unreachable @ extractMainModule" private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc) | Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg" | _, _ => panic "unreachable @ extractMacroScopesAux" /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := match n.hasMacroScopes with | true => extractMacroScopesAux n List.nil | false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous } def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := match n.hasMacroScopes with | true => let view := extractMacroScopes n match beq view.mainModule mainModule with | true => Name.mkNum n scp | false => { view with imported := view.scopes.foldl Name.mkNum (append view.imported view.mainModule), mainModule := mainModule, scopes := List.cons scp List.nil }.review | false => Name.mkNum (Name.mkStr (append (Name.mkStr n "_@") mainModule) "_hyg") scp @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := bind getMainModule fun mainModule => bind getCurrMacroScope fun scp => pure (Lean.addMacroScope mainModule n scp) def defaultMaxRecDepth := 512 def maxRecDepthErrorMessage : String := "maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)" namespace Macro /- References -/ constant MacroEnvPointed : PointedType.{0} def MacroEnv : Type := MacroEnvPointed.type instance : Inhabited MacroEnv := ⟨MacroEnvPointed.val⟩ structure Context := (macroEnv : MacroEnv) (mainModule : Name) (currMacroScope : MacroScope) (currRecDepth : Nat := 0) (maxRecDepth : Nat := defaultMaxRecDepth) inductive Exception | error : Syntax → String → Exception | unsupportedSyntax : Exception end Macro abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception MacroScope) abbrev Macro := Syntax → MacroM Syntax namespace Macro def addMacroScope (n : Name) : MacroM Name := bind read fun ctx => pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope) def throwUnsupported {α} : MacroM α := throw Exception.unsupportedSyntax def throwError {α} (ref : Syntax) (msg : String) : MacroM α := throw (Exception.error ref msg) @[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α := bind (modifyGet (fun s => (s, add s 1))) fun fresh => withReader (fun ctx => { ctx with currMacroScope := fresh }) x @[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α := bind read fun ctx => match beq ctx.currRecDepth ctx.maxRecDepth with | true => throw (Exception.error ref maxRecDepthErrorMessage) | false => withReader (fun ctx => { ctx with currRecDepth := add ctx.currRecDepth 1 }) x instance : MonadQuotation MacroM := { getCurrMacroScope := fun ctx => pure ctx.currMacroScope, getMainModule := fun ctx => pure ctx.mainModule, withFreshMacroScope := Macro.withFreshMacroScope } unsafe def mkMacroEnvImp (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv := unsafeCast expandMacro? @[implementedBy mkMacroEnvImp] constant mkMacroEnv (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv def expandMacroNotAvailable? (stx : Syntax) : MacroM (Option Syntax) := throwError stx "expandMacro has not been set" def mkMacroEnvSimple : MacroEnv := mkMacroEnv expandMacroNotAvailable? unsafe def expandMacro?Imp (stx : Syntax) : MacroM (Option Syntax) := bind read fun ctx => let f : Syntax → MacroM (Option Syntax) := unsafeCast (ctx.macroEnv) f stx /-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/ @[implementedBy expandMacro?Imp] constant expandMacro? : Syntax → MacroM (Option Syntax) end Macro export Macro (expandMacro?) end Lean
b10b9c18d6791b74f528bd4be68a1882d9b384cd
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Lean/Meta/WHNF.lean
157b0544482540798c9babc3be548d722e7f3d1a
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,042
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ToExpr import Lean.AuxRecursor import Lean.ProjFns import Lean.Meta.Basic import Lean.Meta.LevelDefEq import Lean.Meta.GetConst import Lean.Meta.Match.MatcherInfo namespace Lean.Meta /- =========================== Smart unfolding support =========================== -/ def smartUnfoldingSuffix := "_sunfold" @[inline] def mkSmartUnfoldingNameFor (n : Name) : Name := Name.mkStr n smartUnfoldingSuffix register_builtin_option smartUnfolding : Bool := { defValue := true descr := "when computing weak head normal form, use auxiliary definition created for functions defined by structural recursion" } /- =========================== Helper methods =========================== -/ def isAuxDef (constName : Name) : MetaM Bool := do let env ← getEnv return isAuxRecursor env constName || isNoConfusion env constName @[inline] private def matchConstAux {α} (e : Expr) (failK : Unit → MetaM α) (k : ConstantInfo → List Level → MetaM α) : MetaM α := match e with | Expr.const name lvls _ => do let (some cinfo) ← getConst? name | failK () k cinfo lvls | _ => failK () /- =========================== Helper functions for reducing recursors =========================== -/ private def getFirstCtor (d : Name) : MetaM (Option Name) := do let some (ConstantInfo.inductInfo { ctors := ctor::_, ..}) ← getConstNoEx? d | pure none return some ctor private def mkNullaryCtor (type : Expr) (nparams : Nat) : MetaM (Option Expr) := match type.getAppFn with | Expr.const d lvls _ => do let (some ctor) ← getFirstCtor d | pure none return mkAppN (mkConst ctor lvls) (type.getAppArgs.shrink nparams) | _ => return none def toCtorIfLit : Expr → Expr | Expr.lit (Literal.natVal v) _ => if v == 0 then mkConst `Nat.zero else mkApp (mkConst `Nat.succ) (mkNatLit (v-1)) | Expr.lit (Literal.strVal v) _ => mkApp (mkConst `String.mk) (toExpr v.toList) | e => e private def getRecRuleFor (recVal : RecursorVal) (major : Expr) : Option RecursorRule := match major.getAppFn with | Expr.const fn _ _ => recVal.rules.find? fun r => r.ctor == fn | _ => none private def toCtorWhenK (recVal : RecursorVal) (major : Expr) : MetaM (Option Expr) := do let majorType ← inferType major let majorType ← whnf majorType let majorTypeI := majorType.getAppFn if !majorTypeI.isConstOf recVal.getInduct then return none else if majorType.hasExprMVar && majorType.getAppArgs[recVal.numParams:].any Expr.hasExprMVar then return none else do let (some newCtorApp) ← mkNullaryCtor majorType recVal.numParams | pure none let newType ← inferType newCtorApp if (← isDefEq majorType newType) then return newCtorApp else return none /-- Auxiliary function for reducing recursor applications. -/ private def reduceRec {α} (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let mut major ← whnf major if recVal.k then let newMajor ← toCtorWhenK recVal major major := newMajor.getD major let major := toCtorIfLit major match getRecRuleFor recVal major with | some rule => let majorArgs := major.getAppArgs if recLvls.length != recVal.levelParams.length then failK () else let rhs := rule.rhs.instantiateLevelParams recVal.levelParams recLvls -- Apply parameters, motives and minor premises from recursor application. let rhs := mkAppRange rhs 0 (recVal.numParams+recVal.numMotives+recVal.numMinors) recArgs /- The number of parameters in the constructor is not necessarily equal to the number of parameters in the recursor when we have nested inductive types. -/ let nparams := majorArgs.size - rule.nfields let rhs := mkAppRange rhs nparams majorArgs.size majorArgs let rhs := mkAppRange rhs (majorIdx + 1) recArgs.size recArgs successK rhs | none => failK () else failK () /- =========================== Helper functions for reducing Quot.lift and Quot.ind =========================== -/ /-- Auxiliary function for reducing `Quot.lift` and `Quot.ind` applications. -/ private def reduceQuotRec {α} (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let process (majorPos argPos : Nat) : MetaM α := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major match major with | Expr.app (Expr.app (Expr.app (Expr.const majorFn _ _) _ _) _ _) majorArg _ => do let some (ConstantInfo.quotInfo { kind := QuotKind.ctor, .. }) ← getConstNoEx? majorFn | failK () let f := recArgs[argPos] let r := mkApp f majorArg let recArity := majorPos + 1 successK $ mkAppRange r recArity recArgs.size recArgs | _ => failK () else failK () match recVal.kind with | QuotKind.lift => process 5 3 | QuotKind.ind => process 4 3 | _ => failK () /- =========================== Helper function for extracting "stuck term" =========================== -/ mutual private partial def isRecStuck? (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) : MetaM (Option MVarId) := if recVal.k then -- TODO: improve this case return none else do let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let major ← whnf major getStuckMVar? major else return none private partial def isQuotRecStuck? (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) : MetaM (Option MVarId) := let process? (majorPos : Nat) : MetaM (Option MVarId) := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major getStuckMVar? major else return none match recVal.kind with | QuotKind.lift => process? 5 | QuotKind.ind => process? 4 | _ => return none /-- Return `some (Expr.mvar mvarId)` if metavariable `mvarId` is blocking reduction. -/ partial def getStuckMVar? : Expr → MetaM (Option MVarId) | Expr.mdata _ e _ => getStuckMVar? e | Expr.proj _ _ e _ => do getStuckMVar? (← whnf e) | e@(Expr.mvar ..) => do let e ← instantiateMVars e match e with | Expr.mvar mvarId _ => pure (some mvarId) | _ => getStuckMVar? e | e@(Expr.app f _ _) => let f := f.getAppFn match f with | Expr.mvar mvarId _ => return some mvarId | Expr.const fName fLvls _ => do let cinfo? ← getConstNoEx? fName match cinfo? with | some $ ConstantInfo.recInfo recVal => isRecStuck? recVal fLvls e.getAppArgs | some $ ConstantInfo.quotInfo recVal => isQuotRecStuck? recVal fLvls e.getAppArgs | _ => return none | _ => return none | _ => return none end /- =========================== Weak Head Normal Form auxiliary combinators =========================== -/ /-- Auxiliary combinator for handling easy WHNF cases. It takes a function for handling the "hard" cases as an argument -/ @[specialize] private partial def whnfEasyCases (e : Expr) (k : Expr → MetaM Expr) : MetaM Expr := do match e with | Expr.forallE .. => return e | Expr.lam .. => return e | Expr.sort .. => return e | Expr.lit .. => return e | Expr.bvar .. => unreachable! | Expr.letE .. => k e | Expr.const .. => k e | Expr.app .. => k e | Expr.proj .. => k e | Expr.mdata _ e _ => whnfEasyCases e k | Expr.fvar fvarId _ => let decl ← getLocalDecl fvarId match decl with | LocalDecl.cdecl .. => return e | LocalDecl.ldecl (value := v) (nonDep := nonDep) .. => let cfg ← getConfig if nonDep && !cfg.zetaNonDep then return e else when cfg.trackZeta do modify fun s => { s with zetaFVarIds := s.zetaFVarIds.insert fvarId } whnfEasyCases v k | Expr.mvar mvarId _ => match (← getExprMVarAssignment? mvarId) with | some v => whnfEasyCases v k | none => return e /-- Return true iff term is of the form `idRhs ...` -/ private def isIdRhsApp (e : Expr) : Bool := e.isAppOf `idRhs /-- (@idRhs T f a_1 ... a_n) ==> (f a_1 ... a_n) -/ private def extractIdRhs (e : Expr) : Expr := if !isIdRhsApp e then e else let args := e.getAppArgs if args.size < 2 then e else mkAppRange args[1] 2 args.size args @[specialize] private def deltaDefinition {α} (c : ConstantInfo) (lvls : List Level) (failK : Unit → α) (successK : Expr → α) : α := if c.lparams.length != lvls.length then failK () else let val := c.instantiateValueLevelParams lvls successK (extractIdRhs val) @[specialize] private def deltaBetaDefinition {α} (c : ConstantInfo) (lvls : List Level) (revArgs : Array Expr) (failK : Unit → α) (successK : Expr → α) : α := if c.lparams.length != lvls.length then failK () else let val := c.instantiateValueLevelParams lvls let val := val.betaRev revArgs successK (extractIdRhs val) inductive ReduceMatcherResult where | reduced (val : Expr) | stuck (val : Expr) | notMatcher | partialApp def reduceMatcher? (e : Expr) : MetaM ReduceMatcherResult := do match e.getAppFn with | Expr.const declName declLevels _ => let some info ← getMatcherInfo? declName | return ReduceMatcherResult.notMatcher let args := e.getAppArgs let prefixSz := info.numParams + 1 + info.numDiscrs if args.size < prefixSz + info.numAlts then return ReduceMatcherResult.partialApp else let constInfo ← getConstInfo declName let f := constInfo.instantiateValueLevelParams declLevels let auxApp := mkAppN f args[0:prefixSz] let auxAppType ← inferType auxApp forallBoundedTelescope auxAppType info.numAlts fun hs _ => do let auxApp := mkAppN auxApp hs let auxApp ← whnf auxApp let auxAppFn := auxApp.getAppFn let mut i := prefixSz for h in hs do if auxAppFn == h then let result := mkAppN args[i] auxApp.getAppArgs let result := mkAppN result args[prefixSz + info.numAlts:args.size] return ReduceMatcherResult.reduced result.headBeta i := i + 1 return ReduceMatcherResult.stuck auxApp | _ => pure ReduceMatcherResult.notMatcher /- Given an expression `e`, compute its WHNF and if the result is a constructor, return field #i. -/ def project? (e : Expr) (i : Nat) : MetaM (Option Expr) := do let e ← whnf e matchConstCtor e.getAppFn (fun _ => pure none) fun ctorVal _ => let numArgs := e.getAppNumArgs let idx := ctorVal.numParams + i if idx < numArgs then return some (e.getArg! idx) else return none def reduceProj? (e : Expr) : MetaM (Option Expr) := do match e with | Expr.proj _ i c _ => project? c i | _ => return none /-- Apply beta-reduction, zeta-reduction (i.e., unfold let local-decls), iota-reduction, expand let-expressions, expand assigned meta-variables. -/ partial def whnfCore (e : Expr) : MetaM Expr := whnfEasyCases e fun e => do trace[Meta.whnf]! e match e with | Expr.const .. => pure e | Expr.letE _ _ v b _ => whnfCore $ b.instantiate1 v | Expr.app f .. => let f := f.getAppFn let f' ← whnfCore f if f'.isLambda then let revArgs := e.getAppRevArgs whnfCore <| f'.betaRev revArgs else match (← reduceMatcher? e) with | ReduceMatcherResult.reduced eNew => whnfCore eNew | ReduceMatcherResult.partialApp => pure e | ReduceMatcherResult.stuck _ => pure e | ReduceMatcherResult.notMatcher => let done : Unit → MetaM Expr := fun _ => if f == f' then pure e else pure $ e.updateFn f' matchConstAux f' done fun cinfo lvls => match cinfo with | ConstantInfo.recInfo rec => reduceRec rec lvls e.getAppArgs done whnfCore | ConstantInfo.quotInfo rec => reduceQuotRec rec lvls e.getAppArgs done whnfCore | c@(ConstantInfo.defnInfo _) => do if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs done whnfCore else done () | _ => done () | Expr.proj .. => match (← reduceProj? e) with | some e => whnfCore e | none => return e | _ => unreachable! mutual /-- Reduce `e` until `idRhs` application is exposed or it gets stuck. This is a helper method for implementing smart unfolding. -/ private partial def whnfUntilIdRhs (e : Expr) : MetaM Expr := do let e ← whnfCore e match (← getStuckMVar? e) with | some mvarId => /- Try to "unstuck" by resolving pending TC problems -/ if (← Meta.synthPending mvarId) then whnfUntilIdRhs e else return e -- failed because metavariable is blocking reduction | _ => if isIdRhsApp e then return e -- done else match (← unfoldDefinition? e) with | some e => whnfUntilIdRhs e | none => pure e -- failed because of symbolic argument /-- Auxiliary method for unfolding a class projection when transparency is set to `TransparencyMode.instances`. Recall that that class instance projections are not marked with `[reducible]` because we want them to be in "reducible canonical form". -/ private partial def unfoldProjInst (e : Expr) : MetaM (Option Expr) := do if (← getTransparency) != TransparencyMode.instances then return none else match e.getAppFn with | Expr.const declName .. => match (← getProjectionFnInfo? declName) with | some { fromClass := true, .. } => match (← withDefault <| unfoldDefinition? e) with | none => return none | some e => match (← reduceProj? e.getAppFn) with | none => return none | some r => return mkAppN r e.getAppArgs | _ => return none | _ => return none /-- Unfold definition using "smart unfolding" if possible. -/ partial def unfoldDefinition? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app f _ _ => matchConstAux f.getAppFn (fun _ => unfoldProjInst e) fun fInfo fLvls => do if fInfo.lparams.length != fLvls.length then return none else let unfoldDefault (_ : Unit) : MetaM (Option Expr) := if fInfo.hasValue then deltaBetaDefinition fInfo fLvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else return none if smartUnfolding.get (← getOptions) then let fAuxInfo? ← getConstNoEx? (mkSmartUnfoldingNameFor fInfo.name) match fAuxInfo? with | some fAuxInfo@(ConstantInfo.defnInfo _) => deltaBetaDefinition fAuxInfo fLvls e.getAppRevArgs (fun _ => pure none) fun e₁ => do let e₂ ← whnfUntilIdRhs e₁ if isIdRhsApp e₂ then return some (extractIdRhs e₂) else return none | _ => unfoldDefault () else unfoldDefault () | Expr.const name lvls _ => do let (some (cinfo@(ConstantInfo.defnInfo _))) ← getConstNoEx? name | pure none deltaDefinition cinfo lvls (fun _ => pure none) (fun e => pure (some e)) | _ => return none end def unfoldDefinition (e : Expr) : MetaM Expr := do let some e ← unfoldDefinition? e | throwError! "failed to unfold definition{indentExpr e}" return e @[specialize] partial def whnfHeadPred (e : Expr) (pred : Expr → MetaM Bool) : MetaM Expr := whnfEasyCases e fun e => do let e ← whnfCore e if (← pred e) then match (← unfoldDefinition? e) with | some e => whnfHeadPred e pred | none => return e else return e def whnfUntil (e : Expr) (declName : Name) : MetaM (Option Expr) := do let e ← whnfHeadPred e (fun e => return !e.isAppOf declName) if e.isAppOf declName then return e else return none /-- Try to reduce matcher/recursor/quot applications. We say they are all "morally" recursor applications. -/ def reduceRecMatcher? (e : Expr) : MetaM (Option Expr) := do if !e.isApp then return none else match (← reduceMatcher? e) with | ReduceMatcherResult.reduced e => return e | _ => matchConstAux e.getAppFn (fun _ => pure none) fun cinfo lvls => do match cinfo with | ConstantInfo.recInfo «rec» => reduceRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | ConstantInfo.quotInfo «rec» => reduceQuotRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | c@(ConstantInfo.defnInfo _) => if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else return none | _ => return none unsafe def reduceBoolNativeUnsafe (constName : Name) : MetaM Bool := evalConstCheck Bool `Bool constName unsafe def reduceNatNativeUnsafe (constName : Name) : MetaM Nat := evalConstCheck Nat `Nat constName @[implementedBy reduceBoolNativeUnsafe] constant reduceBoolNative (constName : Name) : MetaM Bool @[implementedBy reduceNatNativeUnsafe] constant reduceNatNative (constName : Name) : MetaM Nat def reduceNative? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app (Expr.const fName _ _) (Expr.const argName _ _) _ => if fName == `Lean.reduceBool then do return toExpr (← reduceBoolNative argName) else if fName == `Lean.reduceNat then do return toExpr (← reduceNatNative argName) else return none | _ => return none @[inline] def withNatValue {α} (a : Expr) (k : Nat → MetaM (Option α)) : MetaM (Option α) := do let a ← whnf a match a with | Expr.const `Nat.zero _ _ => k 0 | Expr.lit (Literal.natVal v) _ => k v | _ => return none def reduceUnaryNatOp (f : Nat → Nat) (a : Expr) : MetaM (Option Expr) := withNatValue a fun a => return mkNatLit <| f a def reduceBinNatOp (f : Nat → Nat → Nat) (a b : Expr) : MetaM (Option Expr) := withNatValue a fun a => withNatValue b fun b => do trace[Meta.isDefEq.whnf.reduceBinOp]! "{a} op {b}" return mkNatLit <| f a b def reduceBinNatPred (f : Nat → Nat → Bool) (a b : Expr) : MetaM (Option Expr) := do withNatValue a fun a => withNatValue b fun b => return toExpr <| f a b def reduceNat? (e : Expr) : MetaM (Option Expr) := if e.hasFVar || e.hasMVar then return none else match e with | Expr.app (Expr.const fn _ _) a _ => if fn == `Nat.succ then reduceUnaryNatOp Nat.succ a else return none | Expr.app (Expr.app (Expr.const fn _ _) a1 _) a2 _ => if fn == `Nat.add then reduceBinNatOp Nat.add a1 a2 else if fn == `Nat.sub then reduceBinNatOp Nat.sub a1 a2 else if fn == `Nat.mul then reduceBinNatOp Nat.mul a1 a2 else if fn == `Nat.div then reduceBinNatOp Nat.div a1 a2 else if fn == `Nat.mod then reduceBinNatOp Nat.mod a1 a2 else if fn == `Nat.beq then reduceBinNatPred Nat.beq a1 a2 else if fn == `Nat.ble then reduceBinNatPred Nat.ble a1 a2 else return none | _ => return none @[inline] private def useWHNFCache (e : Expr) : MetaM Bool := do -- We cache only closed terms without expr metavars. -- Potential refinement: cache if `e` is not stuck at a metavariable if e.hasFVar || e.hasExprMVar then return false else match (← getConfig).transparency with | TransparencyMode.default => true | TransparencyMode.all => true | _ => false @[inline] private def cached? (useCache : Bool) (e : Expr) : MetaM (Option Expr) := do if useCache then match (← getConfig).transparency with | TransparencyMode.default => return (← get).cache.whnfDefault.find? e | TransparencyMode.all => return (← get).cache.whnfAll.find? e | _ => unreachable! else return none private def cache (useCache : Bool) (e r : Expr) : MetaM Expr := do if useCache then match (← getConfig).transparency with | TransparencyMode.default => modify fun s => { s with cache.whnfDefault := s.cache.whnfDefault.insert e r } | TransparencyMode.all => modify fun s => { s with cache.whnfAll := s.cache.whnfAll.insert e r } | _ => unreachable! return r partial def whnfImp (e : Expr) : MetaM Expr := whnfEasyCases e fun e => do checkMaxHeartbeats "whnf" let useCache ← useWHNFCache e match (← cached? useCache e) with | some e' => pure e' | none => let e' ← whnfCore e match (← reduceNat? e') with | some v => cache useCache e v | none => match (← reduceNative? e') with | some v => cache useCache e v | none => match (← unfoldDefinition? e') with | some e => whnfImp e | none => cache useCache e e' @[builtinInit] def setWHNFRef : IO Unit := whnfRef.set whnfImp builtin_initialize registerTraceClass `Meta.whnf end Lean.Meta
4b6b86409d9fb4ca988b45f0204ce15fe898f67c
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/test/equiv_rw.lean
701c17160f95533a226d6caded093aaf722c8a9b
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
9,075
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.equiv_rw import control.equiv_functor.instances -- these make equiv_rw more powerful! -- Uncomment this line to observe the steps of constructing appropriate equivalences. -- set_option trace.equiv_rw_type true import tactic.equiv_rw -- This fails if we use `occurs` rather than `kdepends_on` in `equiv_rw_type`. instance : equiv_functor set := { map := λ α β e s, by { equiv_rw e.symm, assumption, } } -- Rewriting a hypothesis along an equivalence. example {α β : Type} (e : α ≃ β) (f : α → ℕ) (h : ∀ b : β, f (e.symm b) = 0) (i : α) : f i = 0 := begin equiv_rw e at i, apply h, end -- Check that dependent hypotheses are reverted and reintroduced. example {α β : Type} (e : α ≃ β) (Z : α → Type) (f : Π a, Z a → ℕ) (h : ∀ (b : β) (x : Z (e.symm b)), f (e.symm b) x = 0) (i : α) (x : Z i) : f i x = 0 := begin equiv_rw e at i, guard_hyp i := β, guard_target f (e.symm i) x = 0, guard_hyp x := Z ((e.symm) i), exact h i x, end -- Rewriting the goal along an equivalence. example {α β : Type} (e : α ≃ β) (b : β) : α := begin equiv_rw e, exact b, end -- Fail if the equivalence can't be used. example {α β γ : Type} (e : β ≃ γ) (a : α) : α := begin success_if_fail { equiv_rw e at a }, success_if_fail { equiv_rw e }, exact a, end -- Verify that `equiv_rw` will rewrite under `equiv_functor` instances. example {α β : Type} (u : unique α) (e : α ≃ β) : β := begin equiv_rw e at u, apply inhabited.default, end example {α β : Type} (p : equiv.perm α) (e : α ≃ β) : equiv.perm β := begin equiv_rw e at p, exact p, end -- We can rewrite the goal under functors. example {α β : Type} (e : α ≃ β) (b : β) : option α := begin equiv_rw e, exact some b, end -- We can rewrite hypotheses under functors. example {α β : Type} (e : α ≃ β) (b : option α) : option β := begin equiv_rw e at b, exact b, end -- We can rewrite hypotheses under compositions of functors. example {α β : Type} (e : α ≃ β) (b : list (list α)) : list β := begin equiv_rw e at b, exact b.join, end -- Check that we can rewrite in the target position of function types. example {α β γ : Type} (e : α ≃ β) (f : γ → β) : γ → α := begin equiv_rw e, exact f, end -- Check that we can rewrite in the source position of function types. example {α β γ : Type} (e : α ≃ β) (f : β → γ) : α → γ := begin equiv_rw e, exact f, end -- Rewriting under multiple functors. example {α β : Type} (e : α ≃ β) (b : β) : list (option α) := begin equiv_rw e, exact [none, some b], end -- Rewriting under multiple functors, including functions. example {α β γ : Type} (e : α ≃ β) (b : β) : γ → list (option α) := begin equiv_rw e, exact (λ g, [none, some b]), end -- Rewriting in multiple positions. example {α β : Type*} [has_add β] (e : α ≃ β) : α → α := begin have : (α → α) ≃ _, { apply equiv.arrow_congr, apply e, apply e, }, equiv_rw e, exact (@id β), end -- Rewriting in multiple positions. example {α β : Type} [has_add β] (e : α ≃ β) : β → α → α := begin equiv_rw e, exact (+), end -- Rewriting in multiple positions. example {α β : Type} [has_add β] (e : α ≃ β) : α → α → α := begin equiv_rw e, exact (+), end example {α β γ : Type} (e : α ≃ β) (s : β ⊕ γ) : α ⊕ γ := begin equiv_rw e, exact s, end example {α β γ : Type} (e : α ≃ β) (s : β ⊕ γ) : (α ⊕ γ) × (γ ⊕ α) := begin equiv_rw e, exact (s, s.swap), end example {α β γ : Type} (e : α ≃ β) (s : α ⊕ γ) : (β ⊕ γ) × (γ ⊕ β) := begin equiv_rw e at s, exact (s, s.swap), end example {α β γ : Type} (e : α ≃ β) (s : (α ⊕ γ) × β) : (β ⊕ γ) := begin success_if_fail { equiv_rw e at s {max_depth := 4} }, equiv_rw e at s, exact s.1, end -- Test generating the actual equivalence using `equiv_rw_type`. example {α β : Type} (e : α ≃ β) (b : β) : α × (ℕ ⊕ ℕ) := begin have e' : α × (ℕ ⊕ ℕ) ≃ _ := by equiv_rw_type e, apply e'.inv_fun, exact (b, sum.inl 0) end example {α β : Type} (e : α ≃ β) (P : α → Prop) (h : { a // P a }) : β := begin equiv_rw e at h, exact h.val, end example {α β : Type} (e : α ≃ β) (P : α → Prop) (h : ∀ a, P a) (b : β) : { a // P a } := begin equiv_rw e, use b, apply h, end example {α β : Type} (e : α ≃ β) (P : α → Prop) (h : ∀ a : α, P a) (b : β) : P (e.symm b) := begin equiv_rw e.symm at b, exact h b, end example {α β : Type} (e : α ≃ β) (P : α → Sort*) (h : Π a : α, P a) (b : β) : P (e.symm b) := begin -- this is a bit perverse, as `equiv_rw e.symm at b` is more natural, -- but this tests rewriting in the argument of a dependent function equiv_rw e at h, exact h _, end -- a poor example, rewriting in the base of a dependent pair example {α β : Type} (P : α → Type) (h : Σ a, P a) (e : α ≃ β) : β := begin equiv_rw e at h, exact h.1 end -- rewriting in the argument of a dependent function can't be done in one step example {α β γ : Type} (e : α ≃ β) (P : α → Type*) (h : Π a : α, (P a) × (option α)) (b : β) : option β := begin equiv_rw e at h, have t := h b, equiv_rw e at t, exact t.2, end -- Demonstrate using `equiv_rw` to build new instances of `equiv_functor` -- Observe that the next three declarations could easily be implemented by a tactic. -- This has been automated in the `transport` branch, -- so we won't attempt to write a deriver handler until we join with that. def semigroup.map {α β : Type} (e : α ≃ β) : semigroup α → semigroup β := begin intro S, refine_struct { .. }, -- transport data fields using `equiv_rw` { have mul := S.mul, equiv_rw e at mul, -- This `equiv_rw` performs the following steps: -- have e' := (equiv.arrow_congr' e (equiv.arrow_congr' e e)), -- have h := (e'.symm_apply_apply mul).symm, -- revert h, -- generalize : (e' mul) = mul', -- intro h, -- clear_dependent mul, -- rename mul' mul, exact mul, }, -- transport axioms by simplifying, and applying the original axiom { intros, dsimp, simp, apply S.mul_assoc, } end example {α β : Type} (e : α ≃ β) (S : semigroup α) : (semigroup.map e S).mul = (equiv.arrow_congr' e (equiv.arrow_congr' e e)) has_mul.mul := rfl example {α β : Type} (e : α ≃ β) (S : semigroup α) (x y : β) : begin haveI := semigroup.map e S, exact x * y = e (e.symm x * e.symm y) end := rfl attribute [ext] semigroup lemma semigroup.id_map (α : Type) : semigroup.map (equiv.refl α) = id := by { ext, refl, } lemma semigroup.map_map {α β γ : Type} (e : α ≃ β) (f : β ≃ γ) : semigroup.map (e.trans f) = (semigroup.map f) ∘ (semigroup.map e) := by { ext, dsimp [semigroup.map], simp, } -- TODO (after joining the `transport` branch) create a derive handler for this instance : equiv_functor semigroup := { map := λ α β e, semigroup.map e, map_refl' := semigroup.id_map, map_trans' := λ α β γ e f, semigroup.map_map e f, } -- Verify that we can now use `equiv_rw` under `semigroup`: example {α : Type} [I : semigroup α] {β : Type} (e : α ≃ β) : semigroup β := begin equiv_rw e at I, exact I, end -- Now we do `monoid`, to try out a structure with constants. -- The constructions and proofs here are written as uniformly as possible. -- This example is the blueprint for the `transport` tactic. mk_simp_attribute transport_simps "simps useful inside `transport`" attribute [transport_simps] eq_rec_constant eq_mpr_rfl equiv.to_fun_as_coe equiv.arrow_congr'_apply equiv.symm_apply_apply equiv.apply_eq_iff_eq_symm_apply def monoid.map {α β : Type} (e : α ≃ β) (S : monoid α) : monoid β := begin refine_struct { .. }, { have mul := S.mul, equiv_rw e at mul, exact mul, }, { try { unfold_projs }, simp only with transport_simps, have mul_assoc := S.mul_assoc, equiv_rw e at mul_assoc, solve_by_elim, }, { have one := S.one, equiv_rw e at one, exact one, }, { try { unfold_projs }, simp only with transport_simps, have one_mul := S.one_mul, equiv_rw e at one_mul, solve_by_elim, }, { try { unfold_projs }, simp only with transport_simps, have mul_one := S.mul_one, equiv_rw e at mul_one, solve_by_elim, }, end example {α β : Type} (e : α ≃ β) (S : monoid α) : (monoid.map e S).mul = (equiv.arrow_congr' e (equiv.arrow_congr' e e)) has_mul.mul := rfl example {α β : Type} (e : α ≃ β) (S : monoid α) (x y : β) : begin haveI := monoid.map e S, exact x * y = e (e.symm x * e.symm y) end := rfl example {α β : Type} (e : α ≃ β) (S : monoid α) : begin haveI := monoid.map e S, exact (1 : β) = e (1 : α) end := rfl
2316ba162a5aa34eb292ff5451b3158df8195223
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/alias1.lean
8b07b25a10486528bd3e3424c995eb99e5cf7587
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
54
lean
alias BB : Bool. variable x : BB. print environment 1.
7006ea84e3db611098a7db851f91157171672680
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Prelude.lean
4e2c2b9f8eec0e38e0acc83e2743efcdeaa5081d
[ "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
177,361
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, Mario Carneiro -/ prelude -- Don't import Init, because we're in Init itself set_option linter.missingDocs true -- keep it documented /-! # Init.Prelude This is the first file in the lean import hierarchy. It is responsible for setting up basic definitions, most of which lean already has "built in knowledge" about, so it is important that they be set up in exactly this way. (For example, lean will use `PUnit` in the desugaring of `do` notation, or in the pattern match compiler.) -/ universe u v w /-- The identity function. `id` takes an implicit argument `α : Sort u` (a type in any universe), and an argument `a : α`, and returns `a`. Although this may look like a useless function, one application of the identity function is to explicitly put a type on an expression. If `e` has type `T`, and `T'` is definitionally equal to `T`, then `@id T' e` typechecks, and lean knows that this expression has type `T'` rather than `T`. This can make a difference for typeclass inference, since `T` and `T'` may have different typeclass instances on them. `show T' from e` is sugar for an `@id T' e` expression. -/ @[inline] def id {α : Sort u} (a : α) : α := a /-- Function composition is the act of pipelining the result of one function, to the input of another, creating an entirely new function. Example: ``` #eval Function.comp List.reverse (List.drop 2) [3, 2, 4, 1] -- [1, 4] ``` You can use the notation `f ∘ g` as shorthand for `Function.comp f g`. ``` #eval (List.reverse ∘ List.drop 2) [3, 2, 4, 1] -- [1, 4] ``` A simpler way of thinking about it, is that `List.reverse ∘ List.drop 2` is equivalent to `fun xs => List.reverse (List.drop 2 xs)`, the benefit is that the meaning of composition is obvious, and the representation is compact. -/ @[inline] def Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) /-- The constant function. If `a : α`, then `Function.const β a : β → α` is the "constant function with value `a`", that is, `Function.const β a b = a`. ``` example (b : Bool) : Function.const Bool 10 b = 10 := rfl #check Function.const Bool 10 -- Bool → Nat ``` -/ @[inline] def Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun _ => a set_option checkBinderAnnotations false in /-- `inferInstance` synthesizes a value of any target type by typeclass inference. This function has the same type signature as the identity function, but the square brackets on the `[i : α]` argument means that it will attempt to construct this argument by typeclass inference. (This will fail if `α` is not a `class`.) Example: ``` #check (inferInstance : Inhabited Nat) -- Inhabited Nat def foo : Inhabited (Nat × Nat) := inferInstance example : foo.default = (default, default) := rfl ``` -/ abbrev inferInstance {α : Sort u} [i : α] : α := i set_option checkBinderAnnotations false in /-- `inferInstanceAs α` synthesizes a value of any target type by typeclass inference. This is just like `inferInstance` except that `α` is given explicitly instead of being inferred from the target type. It is especially useful when the target type is some `α'` which is definitionally equal to `α`, but the instance we are looking for is only registered for `α` (because typeclass search does not unfold most definitions, but definitional equality does.) Example: ``` #check inferInstanceAs (Inhabited Nat) -- Inhabited Nat ``` -/ abbrev inferInstanceAs (α : Sort u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in /-- The unit type, the canonical type with one element, named `unit` or `()`. This is the universe-polymorphic version of `Unit`; it is preferred to use `Unit` instead where applicable. For more information about universe levels: [Types as objects](https://leanprover.github.io/theorem_proving_in_lean4/dependent_type_theory.html#types-as-objects) -/ inductive PUnit : Sort u where /-- `PUnit.unit : PUnit` is the canonical element of the unit type. -/ | unit : PUnit /-- The unit type, the canonical type with one element, named `unit` or `()`. In other words, it describes only a single value, which consists of said constructor applied to no arguments whatsoever. The `Unit` type is similar to `void` in languages derived from C. `Unit` is actually defined as `PUnit.{0}` where `PUnit` is the universe polymorphic version. The `Unit` should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. In functional programming, `Unit` is the return type of things that "return nothing", since a type with one element conveys no additional information. When programming with monads, the type `m Unit` represents an action that has some side effects but does not return a value, while `m α` would be an action that has side effects and returns a value of type `α`. -/ abbrev Unit : Type := PUnit /-- `Unit.unit : Unit` is the canonical element of the unit type. It can also be written as `()`. -/ @[match_pattern] abbrev Unit.unit : Unit := PUnit.unit /-- Marker for information that has been erased by the code generator. -/ unsafe axiom lcErased : Type /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. It may look strange to have an axiom that says "every proposition is true", since this is obviously unsound, but the `unsafe` marker ensures that the kernel will not let this through into regular proofs. The lower levels of the code generator don't need proofs in terms, so this is used to stub the proofs out. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler when erasing casts. -/ unsafe axiom lcCast {α : Sort u} {β : Sort v} (a : α) : β /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. Like `lcProof`, this is an `unsafe axiom`, which means that even though it is not sound, the kernel will not let us use it for regular proofs. Executing this expression to actually synthesize a value of type `α` causes **immediate undefined behavior**, and the compiler does take advantage of this to optimize the code assuming that it is not called. If it is not optimized out, it is likely to appear as a print message saying "unreachable code", but this behavior is not guaranteed or stable in any way. -/ unsafe axiom lcUnreachable {α : Sort u} : α /-- `True` is a proposition and has only an introduction rule, `True.intro : True`. In other words, `True` is simply true, and has a canonical proof, `True.intro` For more information: [Propositional Logic](https://leanprover.github.io/theorem_proving_in_lean4/propositions_and_proofs.html#propositional-logic) -/ inductive True : Prop where /-- `True` is true, and `True.intro` (or more commonly, `trivial`) is the proof. -/ | intro : True /-- `False` is the empty proposition. Thus, it has no introduction rules. It represents a contradiction. `False` elimination rule, `False.rec`, expresses the fact that anything follows from a contradiction. This rule is sometimes called ex falso (short for ex falso sequitur quodlibet), or the principle of explosion. For more information: [Propositional Logic](https://leanprover.github.io/theorem_proving_in_lean4/propositions_and_proofs.html#propositional-logic) -/ inductive False : Prop /-- The empty type. It has no constructors. The `Empty.rec` eliminator expresses the fact that anything follows from the empty type. -/ inductive Empty : Type set_option bootstrap.inductiveCheckResultingUniverse false in /-- The universe-polymorphic empty type. Prefer `Empty` or `False` where possible. -/ inductive PEmpty : Sort u where /-- `Not p`, or `¬p`, is the negation of `p`. It is defined to be `p → False`, so if your goal is `¬p` you can use `intro h` to turn the goal into `h : p ⊢ False`, and if you have `hn : ¬p` and `h : p` then `hn h : False` and `(hn h).elim` will prove anything. For more information: [Propositional Logic](https://leanprover.github.io/theorem_proving_in_lean4/propositions_and_proofs.html#propositional-logic) -/ def Not (a : Prop) : Prop := a → False /-- `False.elim : False → C` says that from `False`, any desired proposition `C` holds. Also known as ex falso quodlibet (EFQ) or the principle of explosion. The target type is actually `C : Sort u` which means it works for both propositions and types. When executed, this acts like an "unreachable" instruction: it is **undefined behavior** to run, but it will probably print "unreachable code". (You would need to construct a proof of false to run it anyway, which you can only do using `sorry` or unsound axioms.) -/ @[macro_inline] def False.elim {C : Sort u} (h : False) : C := h.rec /-- Anything follows from two contradictory hypotheses. Example: ``` example (hp : p) (hnp : ¬p) : q := absurd hp hnp ``` For more information: [Propositional Logic](https://leanprover.github.io/theorem_proving_in_lean4/propositions_and_proofs.html#propositional-logic) -/ @[macro_inline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := (h₂ h₁).rec /-- The equality relation. It has one introduction rule, `Eq.refl`. We use `a = b` as notation for `Eq a b`. A fundamental property of equality is that it is an equivalence relation. ``` variable (α : Type) (a b c d : α) variable (hab : a = b) (hcb : c = b) (hcd : c = d) example : a = d := Eq.trans (Eq.trans hab (Eq.symm hcb)) hcd ``` Equality is much more than an equivalence relation, however. It has the important property that every assertion respects the equivalence, in the sense that we can substitute equal expressions without changing the truth value. That is, given `h1 : a = b` and `h2 : p a`, we can construct a proof for `p b` using substitution: `Eq.subst h1 h2`. Example: ``` example (α : Type) (a b : α) (p : α → Prop) (h1 : a = b) (h2 : p a) : p b := Eq.subst h1 h2 example (α : Type) (a b : α) (p : α → Prop) (h1 : a = b) (h2 : p a) : p b := h1 ▸ h2 ``` The triangle in the second presentation is a macro built on top of `Eq.subst` and `Eq.symm`, and you can enter it by typing `\t`. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ inductive Eq : α → α → Prop where /-- `Eq.refl a : a = a` is reflexivity, the unique constructor of the equality type. See also `rfl`, which is usually used instead. -/ | refl (a : α) : Eq a a /-- Non-dependent recursor for the equality type. -/ @[simp] abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := h.rec m /-- `rfl : a = a` is the unique constructor of the equality type. This is the same as `Eq.refl` except that it takes `a` implicitly instead of explicitly. This is a more powerful theorem than it may appear at first, because although the statement of the theorem is `a = a`, lean will allow anything that is definitionally equal to that type. So, for instance, `2 + 2 = 4` is proven in lean by `rfl`, because both sides are the same up to definitional equality. -/ @[match_pattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a /-- `id x = x`, as a `@[simp]` lemma. -/ @[simp] theorem id_eq (a : α) : Eq (id a) a := rfl /-- The substitution principle for equality. If `a = b ` and `P a` holds, then `P b` also holds. We conventionally use the name `motive` for `P` here, so that you can specify it explicitly using e.g. `Eq.subst (motive := fun x => x < 5)` if it is not otherwise inferred correctly. This theorem is the underlying mechanism behind the `rw` tactic, which is essentially a fancy algorithm for finding good `motive` arguments to usefully apply this theorem to replace occurrences of `a` with `b` in the goal or hypotheses. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ /-- Equality is symmetric: if `a = b` then `b = a`. Because this is in the `Eq` namespace, if you have a variable `h : a = b`, `h.symm` can be used as shorthand for `Eq.symm h` as a proof of `b = a`. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl /-- Equality is transitive: if `a = b` and `b = c` then `a = c`. Because this is in the `Eq` namespace, if you have variables or expressions `h₁ : a = b` and `h₂ : b = c`, you can use `h₁.trans h₂ : a = c` as shorthand for `Eq.trans h₁ h₂`. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : Eq a b) (h₂ : Eq b c) : Eq a c := h₂ ▸ h₁ /-- Cast across a type equality. If `h : α = β` is an equality of types, and `a : α`, then `a : β` will usually not typecheck directly, but this function will allow you to work around this and embed `a` in type `β` as `cast h a : β`. It is best to avoid this function if you can, because it is more complicated to reason about terms containing casts, but if the types don't match up definitionally sometimes there isn't anything better you can do. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ @[macro_inline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := h.rec a /-- Congruence in the function argument: if `a₁ = a₂` then `f a₁ = f a₂` for any (nondependent) function `f`. This is more powerful than it might look at first, because you can also use a lambda expression for `f` to prove that `<something containing a₁> = <something containing a₂>`. This function is used internally by tactics like `congr` and `simp` to apply equalities inside subterms. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl /-- Congruence in both function and argument. If `f₁ = f₂` and `a₁ = a₂` then `f₁ a₁ = f₂ a₂`. This only works for nondependent functions; the theorem statement is more complex in the dependent case. For more information: [Equality](https://leanprover.github.io/theorem_proving_in_lean4/quantifiers_and_equality.html#equality) -/ theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : Eq f₁ f₂) (h₂ : Eq a₁ a₂) : Eq (f₁ a₁) (f₂ a₂) := h₁ ▸ h₂ ▸ rfl /-- Congruence in the function part of an application: If `f = g` then `f a = g a`. -/ theorem congrFun {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x} (h : Eq f g) (a : α) : Eq (f a) (g a) := h ▸ rfl /-! Initialize the Quotient Module, which effectively adds the following definitions: ``` opaque Quot {α : Sort u} (r : α → α → Prop) : Sort u opaque Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r opaque Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β opaque Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q ``` -/ init_quot /-- Let `α` be any type, and let `r` be an equivalence relation on `α`. It is mathematically common to form the "quotient" `α / r`, that is, the type of elements of `α` "modulo" `r`. Set theoretically, one can view `α / r` as the set of equivalence classes of `α` modulo `r`. If `f : α → β` is any function that respects the equivalence relation in the sense that for every `x y : α`, `r x y` implies `f x = f y`, then f "lifts" to a function `f' : α / r → β` defined on each equivalence class `⟦x⟧` by `f' ⟦x⟧ = f x`. Lean extends the Calculus of Constructions with additional constants that perform exactly these constructions, and installs this last equation as a definitional reduction rule. Given a type `α` and any binary relation `r` on `α`, `Quot r` is a type. Note that `r` is not required to be an equivalence relation. `Quot` is the basic building block used to construct later the type `Quotient`. -/ add_decl_doc Quot /-- Given a type `α` and any binary relation `r` on `α`, `Quot.mk` maps `α` to `Quot r`. So that if `r : α → α → Prop` and `a : α`, then `Quot.mk r a` is an element of `Quot r`. See `Quot`. -/ add_decl_doc Quot.mk /-- Given a type `α` and any binary relation `r` on `α`, `Quot.ind` says that every element of `Quot r` is of the form `Quot.mk r a`. See `Quot` and `Quot.lift`. -/ add_decl_doc Quot.ind /-- Given a type `α`, any binary relation `r` on `α`, a function `f : α → β`, and a proof `h` that `f` respects the relation `r`, then `Quot.lift f h` is the corresponding function on `Quot r`. The idea is that for each element `a` in `α`, the function `Quot.lift f h` maps `Quot.mk r a` (the `r`-class containing `a`) to `f a`, wherein `h` shows that this function is well defined. In fact, the computation principle is declared as a reduction rule. -/ add_decl_doc Quot.lift /-- Unsafe auxiliary constant used by the compiler to erase `Quot.lift`. -/ unsafe axiom Quot.lcInv {α : Sort u} {r : α → α → Prop} (q : Quot r) : α /-- Heterogeneous equality. `HEq a b` asserts that `a` and `b` have the same type, and casting `a` across the equality yields `b`, and vice versa. You should avoid using this type if you can. Heterogeneous equality does not have all the same properties as `Eq`, because the assumption that the types of `a` and `b` are equal is often too weak to prove theorems of interest. One important non-theorem is the analogue of `congr`: If `HEq f g` and `HEq x y` and `f x` and `g y` are well typed it does not follow that `HEq (f x) (g y)`. (This does follow if you have `f = g` instead.) However if `a` and `b` have the same type then `a = b` and `HEq a b` are equivalent. -/ inductive HEq : {α : Sort u} → α → {β : Sort u} → β → Prop where /-- Reflexivity of heterogeneous equality. -/ | refl (a : α) : HEq a a /-- A version of `HEq.refl` with an implicit argument. -/ @[match_pattern] protected def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eq_of_heq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b := fun _ _ _ _ h₁ => h₁.rec (fun _ => rfl) this α α a a' h rfl /-- Product type (aka pair). You can use `α × β` as notation for `Prod α β`. Given `a : α` and `b : β`, `Prod.mk a b : Prod α β`. You can use `(a, b)` as notation for `Prod.mk a b`. Moreover, `(a, b, c)` is notation for `Prod.mk a (Prod.mk b c)`. Given `p : Prod α β`, `p.1 : α` and `p.2 : β`. They are short for `Prod.fst p` and `Prod.snd p` respectively. You can also write `p.fst` and `p.snd`. For more information: [Constructors with Arguments](https://leanprover.github.io/theorem_proving_in_lean4/inductive_types.html?highlight=Prod#constructors-with-arguments) -/ structure Prod (α : Type u) (β : Type v) where /-- The first projection out of a pair. if `p : α × β` then `p.1 : α`. -/ fst : α /-- The second projection out of a pair. if `p : α × β` then `p.2 : β`. -/ snd : β attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this type internally to automatically generate the `brecOn` recursor. -/ structure PProd (α : Sort u) (β : Sort v) where /-- The first projection out of a pair. if `p : PProd α β` then `p.1 : α`. -/ fst : α /-- The second projection out of a pair. if `p : PProd α β` then `p.2 : β`. -/ snd : β /-- Similar to `Prod`, but `α` and `β` are in the same universe. We say `MProd` is the universe monomorphic product type. -/ structure MProd (α β : Type u) where /-- The first projection out of a pair. if `p : MProd α β` then `p.1 : α`. -/ fst : α /-- The second projection out of a pair. if `p : MProd α β` then `p.2 : β`. -/ snd : β /-- `And a b`, or `a ∧ b`, is the conjunction of propositions. It can be constructed and destructed like a pair: if `ha : a` and `hb : b` then `⟨ha, hb⟩ : a ∧ b`, and if `h : a ∧ b` then `h.left : a` and `h.right : b`. -/ structure And (a b : Prop) : Prop where /-- `And.intro : a → b → a ∧ b` is the constructor for the And operation. -/ intro :: /-- Extract the left conjunct from a conjunction. `h : a ∧ b` then `h.left`, also notated as `h.1`, is a proof of `a`. -/ left : a /-- Extract the right conjunct from a conjunction. `h : a ∧ b` then `h.right`, also notated as `h.2`, is a proof of `b`. -/ right : b /-- `Or a b`, or `a ∨ b`, is the disjunction of propositions. There are two constructors for `Or`, called `Or.inl : a → a ∨ b` and `Or.inr : b → a ∨ b`, and you can use `match` or `cases` to destruct an `Or` assumption into the two cases. -/ inductive Or (a b : Prop) : Prop where /-- `Or.inl` is "left injection" into an `Or`. If `h : a` then `Or.inl h : a ∨ b`. -/ | inl (h : a) : Or a b /-- `Or.inr` is "right injection" into an `Or`. If `h : b` then `Or.inr h : a ∨ b`. -/ | inr (h : b) : Or a b /-- Alias for `Or.inl`. -/ theorem Or.intro_left (b : Prop) (h : a) : Or a b := Or.inl h /-- Alias for `Or.inr`. -/ theorem Or.intro_right (a : Prop) (h : b) : Or a b := Or.inr h /-- Proof by cases on an `Or`. If `a ∨ b`, and both `a` and `b` imply proposition `c`, then `c` is true. -/ theorem Or.elim {c : Prop} (h : Or a b) (left : a → c) (right : b → c) : c := match h with | Or.inl h => left h | Or.inr h => right h /-- `Bool` is the type of boolean values, `true` and `false`. Classically, this is equivalent to `Prop` (the type of propositions), but the distinction is important for programming, because values of type `Prop` are erased in the code generator, while `Bool` corresponds to the type called `bool` or `boolean` in most programming languages. -/ inductive Bool : Type where /-- The boolean value `false`, not to be confused with the proposition `False`. -/ | false : Bool /-- The boolean value `true`, not to be confused with the proposition `True`. -/ | true : Bool export Bool (false true) /-- `Subtype p`, usually written as `{x : α // p x}`, is a type which represents all the elements `x : α` for which `p x` is true. It is structurally a pair-like type, so if you have `x : α` and `h : p x` then `⟨x, h⟩ : {x // p x}`. An element `s : {x // p x}` will coerce to `α` but you can also make it explicit using `s.1` or `s.val`. -/ structure Subtype {α : Sort u} (p : α → Prop) where /-- If `s : {x // p x}` then `s.val : α` is the underlying element in the base type. You can also write this as `s.1`, or simply as `s` when the type is known from context. -/ val : α /-- If `s : {x // p x}` then `s.2` or `s.property` is the assertion that `p s.1`, that is, that `s` is in fact an element for which `p` holds. -/ property : p val set_option linter.unusedVariables.funArgs false in /-- Gadget for optional parameter support. A binder like `(x : α := default)` in a declaration is syntax sugar for `x : optParam α default`, and triggers the elaborator to attempt to use `default` to supply the argument if it is not supplied. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. For example, the `Membership` class is defined as: ``` class Membership (α : outParam (Type u)) (γ : Type v) ``` This means that whenever a typeclass goal of the form `Membership ?α ?γ` comes up, lean will wait to solve it until `?γ` is known, but then it will run typeclass inference, and take the first solution it finds, for any value of `?α`, which thereby determines what `?α` should be. This expresses that in a term like `a ∈ s`, `s` might be a `Set α` or `List α` or some other type with a membership operation, and in each case the "member" type `α` is determined by looking at the container type. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Gadget for marking semi output parameters in type classes. Semi-output parameters influence the order in which arguments to type class instances are processed. Lean determines an order where all non-(semi-)output parameters to the instance argument have to be figured out before attempting to synthesize an argument (that is, they do not contain assignable metavariables created during TC synthesis). This rules out instances such as `[Mul β] : Add α` (because `β` could be anything). Marking a parameter as semi-output is a promise that instances of the type class will always fill in a value for that parameter. For example, the `Coe` class is defined as: ``` class Coe (α : semiOutParam (Sort u)) (β : Sort v) ``` This means that all `Coe` instances should provide a concrete value for `α` (i.e., not an assignable metavariable). An instance like `Coe Nat Int` or `Coe α (Option α)` is fine, but `Coe α Nat` is not since it does not provide a value for `α`. -/ @[reducible] def semiOutParam (α : Sort u) : Sort u := α set_option linter.unusedVariables.funArgs false in /-- Auxiliary declaration used to implement named patterns like `x@h:p`. -/ @[reducible] def namedPattern {α : Sort u} (x a : α) (h : Eq x a) : α := a /-- Auxiliary axiom used to implement `sorry`. The `sorry` term/tactic expands to `sorryAx _ (synthetic := false)`. This is a proof of anything, which is intended for stubbing out incomplete parts of a proof while still having a syntactically correct proof skeleton. Lean will give a warning whenever a proof uses `sorry`, so you aren't likely to miss it, but you can double check if a theorem depends on `sorry` by using `#print axioms my_thm` and looking for `sorryAx` in the axiom list. The `synthetic` flag is false when written explicitly by the user, but it is set to `true` when a tactic fails to prove a goal, or if there is a type error in the expression. A synthetic `sorry` acts like a regular one, except that it suppresses follow-up errors in order to prevent one error from causing a cascade of other errors because the desired term was not constructed. -/ @[extern "lean_sorry", never_extract] axiom sorryAx (α : Sort u) (synthetic := false) : α theorem eq_false_of_ne_true : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, _ => rfl theorem eq_true_of_ne_false : {b : Bool} → Not (Eq b false) → Eq b true | true, _ => rfl | false, h => False.elim (h rfl) theorem ne_false_of_eq_true : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem ne_true_of_eq_false : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h /-- `Inhabited α` is a typeclass that says that `α` has a designated element, called `(default : α)`. This is sometimes referred to as a "pointed type". This class is used by functions that need to return a value of the type when called "out of domain". For example, `Array.get! arr i : α` returns a value of type `α` when `arr : Array α`, but if `i` is not in range of the array, it reports a panic message, but this does not halt the program, so it must still return a value of type `α` (and in fact this is required for logical consistency), so in this case it returns `default`. -/ class Inhabited (α : Sort u) where /-- `default` is a function that produces a "default" element of any `Inhabited` type. This element does not have any particular specified properties, but it is often an all-zeroes value. -/ default : α export Inhabited (default) /-- `Nonempty α` is a typeclass that says that `α` is not an empty type, that is, there exists an element in the type. It differs from `Inhabited α` in that `Nonempty α` is a `Prop`, which means that it does not actually carry an element of `α`, only a proof that *there exists* such an element. Given `Nonempty α`, you can construct an element of `α` *nonconstructively* using `Classical.choice`. -/ class inductive Nonempty (α : Sort u) : Prop where /-- If `val : α`, then `α` is nonempty. -/ | intro (val : α) : Nonempty α /-- **The axiom of choice**. `Nonempty α` is a proof that `α` has an element, but the element itself is erased. The axiom `choice` supplies a particular element of `α` given only this proof. The textbook axiom of choice normally makes a family of choices all at once, but that is implied from this formulation, because if `α : ι → Type` is a family of types and `h : ∀ i, Nonempty (α i)` is a proof that they are all nonempty, then `fun i => Classical.choice (h i) : ∀ i, α i` is a family of chosen elements. This is actually a bit stronger than the ZFC choice axiom; this is sometimes called "[global choice](https://en.wikipedia.org/wiki/Axiom_of_global_choice)". In lean, we use the axiom of choice to derive the law of excluded middle (see `Classical.em`), so it will often show up in axiom listings where you may not expect. You can use `#print axioms my_thm` to find out if a given theorem depends on this or other axioms. This axiom can be used to construct "data", but obviously there is no algorithm to compute it, so lean will require you to mark any definition that would involve executing `Classical.choice` or other axioms as `noncomputable`, and will not produce any executable code for such definitions. -/ axiom Classical.choice {α : Sort u} : Nonempty α → α /-- The elimination principle for `Nonempty α`. If `Nonempty α`, and we can prove `p` given any element `x : α`, then `p` holds. Note that it is essential that `p` is a `Prop` here; the version with `p` being a `Sort u` is equivalent to `Classical.choice`. -/ protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p := match h₁ with | intro a => h₂ a instance {α : Sort u} [Inhabited α] : Nonempty α := ⟨default⟩ /-- A variation on `Classical.choice` that uses typeclass inference to infer the proof of `Nonempty α`. -/ noncomputable def Classical.ofNonempty {α : Sort u} [Nonempty α] : α := Classical.choice inferInstance instance (α : Sort u) {β : Sort v} [Nonempty β] : Nonempty (α → β) := Nonempty.intro fun _ => Classical.ofNonempty instance (α : Sort u) {β : α → Sort v} [(a : α) → Nonempty (β a)] : Nonempty ((a : α) → β a) := Nonempty.intro fun _ => Classical.ofNonempty instance : Inhabited (Sort u) where default := PUnit instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where default := fun _ => default instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where default := fun _ => default deriving instance Inhabited for Bool /-- Universe lifting operation from `Sort u` to `Type u`. -/ structure PLift (α : Sort u) : Type u where /-- Lift a value into `PLift α` -/ up :: /-- Extract a value from `PLift α` -/ down : α /-- Bijection between `α` and `PLift α` -/ theorem PLift.up_down {α : Sort u} (b : PLift α) : Eq (up (down b)) b := rfl /-- Bijection between `α` and `PLift α` -/ theorem PLift.down_up {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /-- `NonemptyType.{u}` is the type of nonempty types in universe `u`. It is mainly used in constant declarations where we wish to introduce a type and simultaneously assert that it is nonempty, but otherwise make the type opaque. -/ def NonemptyType := Subtype fun α : Type u => Nonempty α /-- The underlying type of a `NonemptyType`. -/ abbrev NonemptyType.type (type : NonemptyType.{u}) : Type u := type.val /-- `NonemptyType` is inhabited, because `PUnit` is a nonempty type. -/ instance : Inhabited NonemptyType.{u} where default := ⟨PUnit, ⟨⟨⟩⟩⟩ /-- Universe lifting operation from a lower `Type` universe to a higher one. To express this using level variables, the input is `Type s` and the output is `Type (max s r)`, so if `s ≤ r` then the latter is (definitionally) `Type r`. The universe variable `r` is written first so that `ULift.{r} α` can be used when `s` can be inferred from the type of `α`. -/ structure ULift.{r, s} (α : Type s) : Type (max s r) where /-- Lift a value into `ULift α` -/ up :: /-- Extract a value from `ULift α` -/ down : α /-- Bijection between `α` and `ULift.{v} α` -/ theorem ULift.up_down {α : Type u} (b : ULift.{v} α) : Eq (up (down b)) b := rfl /-- Bijection between `α` and `ULift.{v} α` -/ theorem ULift.down_up {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl /-- `Decidable p` is a data-carrying class that supplies a proof that `p` is either `true` or `false`. It is equivalent to `Bool` (and in fact it has the same code generation as `Bool`) together with a proof that the `Bool` is true iff `p` is. `Decidable` instances are used to infer "computation strategies" for propositions, so that you can have the convenience of writing propositions inside `if` statements and executing them (which actually executes the inferred decidability instance instead of the proposition, which has no code). If a proposition `p` is `Decidable`, then `(by decide : p)` will prove it by evaluating the decidability instance to `isTrue h` and returning `h`. -/ class inductive Decidable (p : Prop) where /-- Prove that `p` is decidable by supplying a proof of `¬p` -/ | isFalse (h : Not p) : Decidable p /-- Prove that `p` is decidable by supplying a proof of `p` -/ | isTrue (h : p) : Decidable p /-- Convert a decidable proposition into a boolean value. If `p : Prop` is decidable, then `decide p : Bool` is the boolean value which is `true` if `p` is true and `false` if `p` is false. -/ @[inline_if_reduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := h.casesOn (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) /-- A decidable predicate. See `Decidable`. -/ abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) /-- A decidable relation. See `Decidable`. -/ abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) /-- Asserts that `α` has decidable equality, that is, `a = b` is decidable for all `a b : α`. See `Decidable`. -/ abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) /-- Proves that `a = b` is decidable given `DecidableEq α`. -/ def decEq {α : Sort u} [inst : DecidableEq α] (a b : α) : Decidable (Eq a b) := inst a b set_option linter.unusedVariables false in theorem decide_eq_true : [inst : Decidable p] → p → Eq (decide p) true | isTrue _, _ => rfl | isFalse h₁, h₂ => absurd h₂ h₁ theorem decide_eq_false : [Decidable p] → Not p → Eq (decide p) false | isTrue h₁, h₂ => absurd h₁ h₂ | isFalse _, _ => rfl theorem of_decide_eq_true [inst : Decidable p] : Eq (decide p) true → p := fun h => match (generalizing := false) inst with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (ne_true_of_eq_false (decide_eq_false h₁)) theorem of_decide_eq_false [inst : Decidable p] : Eq (decide p) false → Not p := fun h => match (generalizing := false) inst with | isTrue h₁ => absurd h (ne_false_of_eq_true (decide_eq_true h₁)) | isFalse h₁ => h₁ theorem of_decide_eq_self_eq_true [inst : DecidableEq α] (a : α) : Eq (decide (Eq a a)) true := match (generalizing := false) inst a a with | isTrue _ => rfl | isFalse h₁ => absurd rfl h₁ /-- Decidable equality for Bool -/ @[inline] def Bool.decEq (a b : Bool) : Decidable (Eq a b) := match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl @[inline] instance : DecidableEq Bool := Bool.decEq /-- `BEq α` is a typeclass for supplying a boolean-valued equality relation on `α`, notated as `a == b`. Unlike `DecidableEq α` (which uses `a = b`), this is `Bool` valued instead of `Prop` valued, and it also does not have any axioms like being reflexive or agreeing with `=`. It is mainly intended for programming applications. See `LawfulBEq` for a version that requires that `==` and `=` coincide. -/ class BEq (α : Type u) where /-- Boolean equality, notated as `a == b`. -/ beq : α → α → Bool open BEq (beq) instance [DecidableEq α] : BEq α where beq a b := decide (Eq a b) /-- "Dependent" if-then-else, normally written via the notation `if h : c then t(h) else e(h)`, is sugar for `dite c (fun h => t(h)) (fun h => e(h))`, and it is the same as `if c then t else e` except that `t` is allowed to depend on a proof `h : c`, and `e` can depend on `h : ¬c`. (Both branches use the same name for the hypothesis, even though it has different types in the two cases.) We use this to be able to communicate the if-then-else condition to the branches. For example, `Array.get arr ⟨i, h⟩` expects a proof `h : i < arr.size` in order to avoid a bounds check, so you can write `if h : i < arr.size then arr.get ⟨i, h⟩ else ...` to avoid the bounds check inside the if branch. (Of course in this case we have only lifted the check into an explicit `if`, but we could also use this proof multiple times or derive `i < arr.size` from some other proposition that we are checking in the `if`.) -/ @[macro_inline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := h.casesOn e t /-! # if-then-else -/ /-- `if c then t else e` is notation for `ite c t e`, "if-then-else", which decides to return `t` or `e` depending on whether `c` is true or false. The explicit argument `c : Prop` does not have any actual computational content, but there is an additional `[Decidable c]` argument synthesized by typeclass inference which actually determines how to evaluate `c` to true or false. Because lean uses a strict (call-by-value) evaluation strategy, the signature of this function is problematic in that it would require `t` and `e` to be evaluated before calling the `ite` function, which would cause both sides of the `if` to be evaluated. Even if the result is discarded, this would be a big performance problem, and is undesirable for users in any case. To resolve this, `ite` is marked as `@[macro_inline]`, which means that it is unfolded during code generation, and the definition of the function uses `fun _ => t` and `fun _ => e` so this recovers the expected "lazy" behavior of `if`: the `t` and `e` arguments delay evaluation until `c` is known. -/ @[macro_inline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α := h.casesOn (fun _ => e) (fun _ => t) @[macro_inline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) := match dp with | isTrue hp => match dq with | isTrue hq => isTrue ⟨hp, hq⟩ | isFalse hq => isFalse (fun h => hq (And.right h)) | isFalse hp => isFalse (fun h => hp (And.left h)) @[macro_inline] instance [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) := match dp with | isTrue hp => isTrue (Or.inl hp) | isFalse hp => match dq with | isTrue hq => isTrue (Or.inr hq) | isFalse hq => isFalse fun h => match h with | Or.inl h => hp h | Or.inr h => hq h instance [dp : Decidable p] : Decidable (Not p) := match dp with | isTrue hp => isFalse (absurd hp) | isFalse hp => isTrue hp /-! # Boolean operators -/ /-- `cond b x y` is the same as `if b then x else y`, but optimized for a boolean condition. It can also be written as `bif b then x else y`. This is `@[macro_inline]` because `x` and `y` should not be eagerly evaluated (see `ite`). -/ @[macro_inline] def cond {α : Type u} (c : Bool) (x y : α) : α := match c with | true => x | false => y /-- `or x y`, or `x || y`, is the boolean "or" operation (not to be confused with `Or : Prop → Prop → Prop`, which is the propositional connective). It is `@[macro_inline]` because it has C-like short-circuiting behavior: if `x` is true then `y` is not evaluated. -/ @[macro_inline] def or (x y : Bool) : Bool := match x with | true => true | false => y /-- `and x y`, or `x && y`, is the boolean "and" operation (not to be confused with `And : Prop → Prop → Prop`, which is the propositional connective). It is `@[macro_inline]` because it has C-like short-circuiting behavior: if `x` is false then `y` is not evaluated. -/ @[macro_inline] def and (x y : Bool) : Bool := match x with | false => false | true => y /-- `not x`, or `!x`, is the boolean "not" operation (not to be confused with `Not : Prop → Prop`, which is the propositional connective). -/ @[inline] def not : Bool → Bool | true => false | false => true /-- The type of natural numbers, starting at zero. It is defined as an inductive type freely generated by "zero is a natural number" and "the successor of a natural number is a natural number". You can prove a theorem `P n` about `n : Nat` by `induction n`, which will expect a proof of the theorem for `P 0`, and a proof of `P (succ i)` assuming a proof of `P i`. The same method also works to define functions by recursion on natural numbers: induction and recursion are two expressions of the same operation from lean's point of view. ``` open Nat example (n : Nat) : n < succ n := by induction n with | zero => show 0 < 1 decide | succ i ih => -- ih : i < succ i show succ i < succ (succ i) exact Nat.succ_lt_succ ih ``` This type is special-cased by both the kernel and the compiler: * The type of expressions contains "`Nat` literals" as a primitive constructor, and the kernel knows how to reduce zero/succ expressions to nat literals. * If implemented naively, this type would represent a numeral `n` in unary as a linked list with `n` links, which is horribly inefficient. Instead, the runtime itself has a special representation for `Nat` which stores numbers up to 2^63 directly and larger numbers use an arbitrary precision "bignum" library (usually [GMP](https://gmplib.org/)). -/ inductive Nat where /-- `Nat.zero`, normally written `0 : Nat`, is the smallest natural number. This is one of the two constructors of `Nat`. -/ | zero : Nat /-- The successor function on natural numbers, `succ n = n + 1`. This is one of the two constructors of `Nat`. -/ | succ (n : Nat) : Nat instance : Inhabited Nat where default := Nat.zero /-- The class `OfNat α n` powers the numeric literal parser. If you write `37 : α`, lean will attempt to synthesize `OfNat α 37`, and will generate the term `(OfNat.ofNat 37 : α)`. There is a bit of infinite regress here since the desugaring apparently still contains a literal `37` in it. The type of expressions contains a primitive constructor for "raw natural number literals", which you can directly access using the macro `nat_lit 37`. Raw number literals are always of type `Nat`. So it would be more correct to say that lean looks for an instance of `OfNat α (nat_lit 37)`, and it generates the term `(OfNat.ofNat (nat_lit 37) : α)`. -/ class OfNat (α : Type u) (_ : Nat) where /-- The `OfNat.ofNat` function is automatically inserted by the parser when the user writes a numeric literal like `1 : α`. Implementations of this typeclass can therefore customize the behavior of `n : α` based on `n` and `α`. -/ ofNat : α @[default_instance 100] /- low prio -/ instance (n : Nat) : OfNat Nat n where ofNat := n /-- `LE α` is the typeclass which supports the notation `x ≤ y` where `x y : α`.-/ class LE (α : Type u) where /-- The less-equal relation: `x ≤ y` -/ le : α → α → Prop /-- `LT α` is the typeclass which supports the notation `x < y` where `x y : α`.-/ class LT (α : Type u) where /-- The less-than relation: `x < y` -/ lt : α → α → Prop /-- `a ≥ b` is an abbreviation for `b ≤ a`. -/ @[reducible] def GE.ge {α : Type u} [LE α] (a b : α) : Prop := LE.le b a /-- `a > b` is an abbreviation for `b < a`. -/ @[reducible] def GT.gt {α : Type u} [LT α] (a b : α) : Prop := LT.lt b a /-- `Max α` is the typeclass which supports the operation `max x y` where `x y : α`.-/ class Max (α : Type u) where /-- The maximum operation: `max x y`. -/ max : α → α → α export Max (max) /-- Implementation of the `max` operation using `≤`. -/ -- Marked inline so that `min x y + max x y` can be optimized to a single branch. @[inline] def maxOfLe [LE α] [DecidableRel (@LE.le α _)] : Max α where max x y := ite (LE.le x y) y x /-- `Min α` is the typeclass which supports the operation `min x y` where `x y : α`.-/ class Min (α : Type u) where /-- The minimum operation: `min x y`. -/ min : α → α → α export Min (min) /-- Implementation of the `min` operation using `≤`. -/ -- Marked inline so that `min x y + max x y` can be optimized to a single branch. @[inline] def minOfLe [LE α] [DecidableRel (@LE.le α _)] : Min α where min x y := ite (LE.le x y) x y /-- Transitive chaining of proofs, used e.g. by `calc`. It takes two relations `r` and `s` as "input", and produces an "output" relation `t`, with the property that `r a b` and `s b c` implies `t a c`. The `calc` tactic uses this so that when it sees a chain with `a ≤ b` and `b < c` it knows that this should be a proof of `a < c` because there is an instance `Trans (·≤·) (·<·) (·<·)`. -/ class Trans (r : α → β → Sort u) (s : β → γ → Sort v) (t : outParam (α → γ → Sort w)) where /-- Compose two proofs by transitivity, generalized over the relations involved. -/ trans : r a b → s b c → t a c export Trans (trans) instance (r : α → γ → Sort u) : Trans Eq r r where trans heq h' := heq ▸ h' instance (r : α → β → Sort u) : Trans r Eq r where trans h' heq := heq ▸ h' /-- The notation typeclass for heterogeneous addition. This enables the notation `a + b : γ` where `a : α`, `b : β`. -/ class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a + b` computes the sum of `a` and `b`. The meaning of this notation is type-dependent. -/ hAdd : α → β → γ /-- The notation typeclass for heterogeneous subtraction. This enables the notation `a - b : γ` where `a : α`, `b : β`. -/ class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a - b` computes the difference of `a` and `b`. The meaning of this notation is type-dependent. * For natural numbers, this operator saturates at 0: `a - b = 0` when `a ≤ b`. -/ hSub : α → β → γ /-- The notation typeclass for heterogeneous multiplication. This enables the notation `a * b : γ` where `a : α`, `b : β`. -/ class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a * b` computes the product of `a` and `b`. The meaning of this notation is type-dependent. -/ hMul : α → β → γ /-- The notation typeclass for heterogeneous division. This enables the notation `a / b : γ` where `a : α`, `b : β`. -/ class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a / b` computes the result of dividing `a` by `b`. The meaning of this notation is type-dependent. * For most types like `Nat`, `Int`, `Rat`, `Real`, `a / 0` is defined to be `0`. * For `Nat` and `Int`, `a / b` rounds toward 0. * For `Float`, `a / 0` follows the IEEE 754 semantics for division, usually resulting in `inf` or `nan`. -/ hDiv : α → β → γ /-- The notation typeclass for heterogeneous modulo / remainder. This enables the notation `a % b : γ` where `a : α`, `b : β`. -/ class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a % b` computes the remainder upon dividing `a` by `b`. The meaning of this notation is type-dependent. * For `Nat` and `Int`, `a % 0` is defined to be `a`. -/ hMod : α → β → γ /-- The notation typeclass for heterogeneous exponentiation. This enables the notation `a ^ b : γ` where `a : α`, `b : β`. -/ class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a ^ b` computes `a` to the power of `b`. The meaning of this notation is type-dependent. -/ hPow : α → β → γ /-- The notation typeclass for heterogeneous append. This enables the notation `a ++ b : γ` where `a : α`, `b : β`. -/ class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a ++ b` is the result of concatenation of `a` and `b`, usually read "append". The meaning of this notation is type-dependent. -/ hAppend : α → β → γ /-- The typeclass behind the notation `a <|> b : γ` where `a : α`, `b : β`. Because `b` is "lazy" in this notation, it is passed as `Unit → β` to the implementation so it can decide when to evaluate it. -/ class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a <|> b` executes `a` and returns the result, unless it fails in which case it executes and returns `b`. Because `b` is not always executed, it is passed as a thunk so it can be forced only when needed. The meaning of this notation is type-dependent. -/ hOrElse : α → (Unit → β) → γ /-- The typeclass behind the notation `a >> b : γ` where `a : α`, `b : β`. Because `b` is "lazy" in this notation, it is passed as `Unit → β` to the implementation so it can decide when to evaluate it. -/ class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a >> b` executes `a`, ignores the result, and then executes `b`. If `a` fails then `b` is not executed. Because `b` is not always executed, it is passed as a thunk so it can be forced only when needed. The meaning of this notation is type-dependent. -/ hAndThen : α → (Unit → β) → γ /-- The typeclass behind the notation `a &&& b : γ` where `a : α`, `b : β`. -/ class HAnd (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a &&& b` computes the bitwise AND of `a` and `b`. The meaning of this notation is type-dependent. -/ hAnd : α → β → γ /-- The typeclass behind the notation `a ^^^ b : γ` where `a : α`, `b : β`. -/ class HXor (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a ^^^ b` computes the bitwise XOR of `a` and `b`. The meaning of this notation is type-dependent. -/ hXor : α → β → γ /-- The typeclass behind the notation `a ||| b : γ` where `a : α`, `b : β`. -/ class HOr (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a ||| b` computes the bitwise OR of `a` and `b`. The meaning of this notation is type-dependent. -/ hOr : α → β → γ /-- The typeclass behind the notation `a <<< b : γ` where `a : α`, `b : β`. -/ class HShiftLeft (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a <<< b` computes `a` shifted to the left by `b` places. The meaning of this notation is type-dependent. * On `Nat`, this is equivalent to `a * 2 ^ b`. * On `UInt8` and other fixed width unsigned types, this is the same but truncated to the bit width. -/ hShiftLeft : α → β → γ /-- The typeclass behind the notation `a >>> b : γ` where `a : α`, `b : β`. -/ class HShiftRight (α : Type u) (β : Type v) (γ : outParam (Type w)) where /-- `a >>> b` computes `a` shifted to the right by `b` places. The meaning of this notation is type-dependent. * On `Nat` and fixed width unsigned types like `UInt8`, this is equivalent to `a / 2 ^ b`. -/ hShiftRight : α → β → γ /-- The homogeneous version of `HAdd`: `a + b : α` where `a b : α`. -/ class Add (α : Type u) where /-- `a + b` computes the sum of `a` and `b`. See `HAdd`. -/ add : α → α → α /-- The homogeneous version of `HSub`: `a - b : α` where `a b : α`. -/ class Sub (α : Type u) where /-- `a - b` computes the difference of `a` and `b`. See `HSub`. -/ sub : α → α → α /-- The homogeneous version of `HMul`: `a * b : α` where `a b : α`. -/ class Mul (α : Type u) where /-- `a * b` computes the product of `a` and `b`. See `HMul`. -/ mul : α → α → α /-- The notation typeclass for negation. This enables the notation `-a : α` where `a : α`. -/ class Neg (α : Type u) where /-- `-a` computes the negative or opposite of `a`. The meaning of this notation is type-dependent. -/ neg : α → α /-- The homogeneous version of `HDiv`: `a / b : α` where `a b : α`. -/ class Div (α : Type u) where /-- `a / b` computes the result of dividing `a` by `b`. See `HDiv`. -/ div : α → α → α /-- The homogeneous version of `HMod`: `a % b : α` where `a b : α`. -/ class Mod (α : Type u) where /-- `a % b` computes the remainder upon dividing `a` by `b`. See `HMod`. -/ mod : α → α → α /-- The homogeneous version of `HPow`: `a ^ b : α` where `a : α`, `b : β`. (The right argument is not the same as the left since we often want this even in the homogeneous case.) -/ class Pow (α : Type u) (β : Type v) where /-- `a ^ b` computes `a` to the power of `b`. See `HPow`. -/ pow : α → β → α /-- The homogeneous version of `HAppend`: `a ++ b : α` where `a b : α`. -/ class Append (α : Type u) where /-- `a ++ b` is the result of concatenation of `a` and `b`. See `HAppend`. -/ append : α → α → α /-- The homogeneous version of `HOrElse`: `a <|> b : α` where `a b : α`. Because `b` is "lazy" in this notation, it is passed as `Unit → α` to the implementation so it can decide when to evaluate it. -/ class OrElse (α : Type u) where /-- The implementation of `a <|> b : α`. See `HOrElse`. -/ orElse : α → (Unit → α) → α /-- The homogeneous version of `HAndThen`: `a >> b : α` where `a b : α`. Because `b` is "lazy" in this notation, it is passed as `Unit → α` to the implementation so it can decide when to evaluate it. -/ class AndThen (α : Type u) where /-- The implementation of `a >> b : α`. See `HAndThen`. -/ andThen : α → (Unit → α) → α /-- The homogeneous version of `HAnd`: `a &&& b : α` where `a b : α`. (It is called `AndOp` because `And` is taken for the propositional connective.) -/ class AndOp (α : Type u) where /-- The implementation of `a &&& b : α`. See `HAnd`. -/ and : α → α → α /-- The homogeneous version of `HXor`: `a ^^^ b : α` where `a b : α`. -/ class Xor (α : Type u) where /-- The implementation of `a ^^^ b : α`. See `HXor`. -/ xor : α → α → α /-- The homogeneous version of `HOr`: `a ||| b : α` where `a b : α`. (It is called `OrOp` because `Or` is taken for the propositional connective.) -/ class OrOp (α : Type u) where /-- The implementation of `a ||| b : α`. See `HOr`. -/ or : α → α → α /-- The typeclass behind the notation `~~~a : α` where `a : α`. -/ class Complement (α : Type u) where /-- The implementation of `~~~a : α`. -/ complement : α → α /-- The homogeneous version of `HShiftLeft`: `a <<< b : α` where `a b : α`. -/ class ShiftLeft (α : Type u) where /-- The implementation of `a <<< b : α`. See `HShiftLeft`. -/ shiftLeft : α → α → α /-- The homogeneous version of `HShiftRight`: `a >>> b : α` where `a b : α`. -/ class ShiftRight (α : Type u) where /-- The implementation of `a >>> b : α`. See `HShiftRight`. -/ shiftRight : α → α → α @[default_instance] instance [Add α] : HAdd α α α where hAdd a b := Add.add a b @[default_instance] instance [Sub α] : HSub α α α where hSub a b := Sub.sub a b @[default_instance] instance [Mul α] : HMul α α α where hMul a b := Mul.mul a b @[default_instance] instance [Div α] : HDiv α α α where hDiv a b := Div.div a b @[default_instance] instance [Mod α] : HMod α α α where hMod a b := Mod.mod a b @[default_instance] instance [Pow α β] : HPow α β α where hPow a b := Pow.pow a b @[default_instance] instance [Append α] : HAppend α α α where hAppend a b := Append.append a b @[default_instance] instance [OrElse α] : HOrElse α α α where hOrElse a b := OrElse.orElse a b @[default_instance] instance [AndThen α] : HAndThen α α α where hAndThen a b := AndThen.andThen a b @[default_instance] instance [AndOp α] : HAnd α α α where hAnd a b := AndOp.and a b @[default_instance] instance [Xor α] : HXor α α α where hXor a b := Xor.xor a b @[default_instance] instance [OrOp α] : HOr α α α where hOr a b := OrOp.or a b @[default_instance] instance [ShiftLeft α] : HShiftLeft α α α where hShiftLeft a b := ShiftLeft.shiftLeft a b @[default_instance] instance [ShiftRight α] : HShiftRight α α α where hShiftRight a b := ShiftRight.shiftRight a b open HAdd (hAdd) open HMul (hMul) open HPow (hPow) open HAppend (hAppend) /-- The typeclass behind the notation `a ∈ s : Prop` where `a : α`, `s : γ`. Because `α` is an `outParam`, the "container type" `γ` determines the type of the elements of the container. -/ class Membership (α : outParam (Type u)) (γ : Type v) where /-- The membership relation `a ∈ s : Prop` where `a : α`, `s : γ`. -/ mem : α → γ → Prop set_option bootstrap.genMatcherCode false in /-- Addition of natural numbers. This definition is overridden in both the kernel and the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model (and it is soundness-critical that they coincide). -/ @[extern "lean_nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a, Nat.zero => a | a, Nat.succ b => Nat.succ (Nat.add a b) instance : Add Nat where add := Nat.add /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [match_pattern] Nat.add Add.add HAdd.hAdd Neg.neg set_option bootstrap.genMatcherCode false in /-- Multiplication of natural numbers. This definition is overridden in both the kernel and the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model (and it is soundness-critical that they coincide). -/ @[extern "lean_nat_mul"] protected def Nat.mul : (@& Nat) → (@& Nat) → Nat | _, 0 => 0 | a, Nat.succ b => Nat.add (Nat.mul a b) a instance : Mul Nat where mul := Nat.mul set_option bootstrap.genMatcherCode false in /-- The power operation on natural numbers. This definition is overridden in both the kernel and the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model. -/ @[extern "lean_nat_pow"] protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat | 0 => 1 | succ n => Nat.mul (Nat.pow m n) m instance : Pow Nat Nat where pow := Nat.pow set_option bootstrap.genMatcherCode false in /-- (Boolean) equality of natural numbers. This definition is overridden in both the kernel and the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model (and it is soundness-critical that they coincide). -/ @[extern "lean_nat_dec_eq"] def Nat.beq : (@& Nat) → (@& Nat) → Bool | zero, zero => true | zero, succ _ => false | succ _, zero => false | succ n, succ m => beq n m instance : BEq Nat where beq := Nat.beq theorem Nat.eq_of_beq_eq_true : {n m : Nat} → Eq (beq n m) true → Eq n m | zero, zero, _ => rfl | zero, succ _, h => Bool.noConfusion h | succ _, zero, h => Bool.noConfusion h | succ n, succ m, h => have : Eq (beq n m) true := h have : Eq n m := eq_of_beq_eq_true this this ▸ rfl theorem Nat.ne_of_beq_eq_false : {n m : Nat} → Eq (beq n m) false → Not (Eq n m) | zero, zero, h₁, _ => Bool.noConfusion h₁ | zero, succ _, _, h₂ => Nat.noConfusion h₂ | succ _, zero, _, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have : Eq (beq n m) false := h₁ Nat.noConfusion h₂ (fun h₂ => absurd h₂ (ne_of_beq_eq_false this)) /-- A decision procedure for equality of natural numbers. This definition is overridden in the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model. -/ @[reducible, extern "lean_nat_dec_eq"] protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) := match h:beq n m with | true => isTrue (eq_of_beq_eq_true h) | false => isFalse (ne_of_beq_eq_false h) @[inline] instance : DecidableEq Nat := Nat.decEq set_option bootstrap.genMatcherCode false in /-- The (Boolean) less-equal relation on natural numbers. This definition is overridden in both the kernel and the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model (and it is soundness-critical that they coincide). -/ @[extern "lean_nat_dec_le"] def Nat.ble : @& Nat → @& Nat → Bool | zero, zero => true | zero, succ _ => true | succ _, zero => false | succ n, succ m => ble n m /-- An inductive definition of the less-equal relation on natural numbers, characterized as the least relation `≤` such that `n ≤ n` and `n ≤ m → n ≤ m + 1`. -/ protected inductive Nat.le (n : Nat) : Nat → Prop /-- Less-equal is reflexive: `n ≤ n` -/ | refl : Nat.le n n /-- If `n ≤ m`, then `n ≤ m + 1`. -/ | step {m} : Nat.le n m → Nat.le n (succ m) instance : LE Nat where le := Nat.le /-- The strict less than relation on natural numbers is defined as `n < m := n + 1 ≤ m`. -/ protected def Nat.lt (n m : Nat) : Prop := Nat.le (succ n) m instance : LT Nat where lt := Nat.lt theorem Nat.not_succ_le_zero : ∀ (n : Nat), LE.le (succ n) 0 → False | 0, h => nomatch h | succ _, h => nomatch h theorem Nat.not_lt_zero (n : Nat) : Not (LT.lt n 0) := not_succ_le_zero n theorem Nat.zero_le : (n : Nat) → LE.le 0 n | zero => Nat.le.refl | succ n => Nat.le.step (zero_le n) theorem Nat.succ_le_succ : LE.le n m → LE.le (succ n) (succ m) | Nat.le.refl => Nat.le.refl | Nat.le.step h => Nat.le.step (succ_le_succ h) theorem Nat.zero_lt_succ (n : Nat) : LT.lt 0 (succ n) := succ_le_succ (zero_le n) theorem Nat.le_step (h : LE.le n m) : LE.le n (succ m) := Nat.le.step h protected theorem Nat.le_trans {n m k : Nat} : LE.le n m → LE.le m k → LE.le n k | h, Nat.le.refl => h | h₁, Nat.le.step h₂ => Nat.le.step (Nat.le_trans h₁ h₂) protected theorem Nat.lt_trans {n m k : Nat} (h₁ : LT.lt n m) : LT.lt m k → LT.lt n k := Nat.le_trans (le_step h₁) theorem Nat.le_succ (n : Nat) : LE.le n (succ n) := Nat.le.step Nat.le.refl theorem Nat.le_succ_of_le {n m : Nat} (h : LE.le n m) : LE.le n (succ m) := Nat.le_trans h (le_succ m) protected theorem Nat.le_refl (n : Nat) : LE.le n n := Nat.le.refl theorem Nat.succ_pos (n : Nat) : LT.lt 0 (succ n) := zero_lt_succ n set_option bootstrap.genMatcherCode false in /-- The predecessor function on natural numbers. This definition is overridden in the compiler to use `n - 1` instead. The definition provided here is the logical model. -/ @[extern "lean_nat_pred"] def Nat.pred : (@& Nat) → Nat | 0 => 0 | succ a => a theorem Nat.pred_le_pred : {n m : Nat} → LE.le n m → LE.le (pred n) (pred m) | _, _, Nat.le.refl => Nat.le.refl | 0, succ _, Nat.le.step h => h | succ _, succ _, Nat.le.step h => Nat.le_trans (le_succ _) h theorem Nat.le_of_succ_le_succ {n m : Nat} : LE.le (succ n) (succ m) → LE.le n m := pred_le_pred theorem Nat.le_of_lt_succ {m n : Nat} : LT.lt m (succ n) → LE.le m n := le_of_succ_le_succ protected theorem Nat.eq_or_lt_of_le : {n m: Nat} → LE.le n m → Or (Eq n m) (LT.lt n m) | zero, zero, _ => Or.inl rfl | zero, succ _, _ => Or.inr (Nat.succ_le_succ (Nat.zero_le _)) | succ _, zero, h => absurd h (not_succ_le_zero _) | succ n, succ m, h => have : LE.le n m := Nat.le_of_succ_le_succ h match Nat.eq_or_lt_of_le this with | Or.inl h => Or.inl (h ▸ rfl) | Or.inr h => Or.inr (succ_le_succ h) protected theorem Nat.lt_or_ge (n m : Nat) : Or (LT.lt n m) (GE.ge n m) := match m with | zero => Or.inr (zero_le n) | succ m => match Nat.lt_or_ge n m with | Or.inl h => Or.inl (le_succ_of_le h) | Or.inr h => match Nat.eq_or_lt_of_le h with | Or.inl h1 => Or.inl (h1 ▸ Nat.le_refl _) | Or.inr h1 => Or.inr h1 theorem Nat.not_succ_le_self : (n : Nat) → Not (LE.le (succ n) n) | 0 => not_succ_le_zero _ | succ n => fun h => absurd (le_of_succ_le_succ h) (not_succ_le_self n) protected theorem Nat.lt_irrefl (n : Nat) : Not (LT.lt n n) := Nat.not_succ_le_self n protected theorem Nat.lt_of_le_of_lt {n m k : Nat} (h₁ : LE.le n m) (h₂ : LT.lt m k) : LT.lt n k := Nat.le_trans (Nat.succ_le_succ h₁) h₂ protected theorem Nat.le_antisymm {n m : Nat} (h₁ : LE.le n m) (h₂ : LE.le m n) : Eq n m := match h₁ with | Nat.le.refl => rfl | Nat.le.step h => absurd (Nat.lt_of_le_of_lt h h₂) (Nat.lt_irrefl n) protected theorem Nat.lt_of_le_of_ne {n m : Nat} (h₁ : LE.le n m) (h₂ : Not (Eq n m)) : LT.lt n m := match Nat.lt_or_ge n m with | Or.inl h₃ => h₃ | Or.inr h₃ => absurd (Nat.le_antisymm h₁ h₃) h₂ theorem Nat.le_of_ble_eq_true (h : Eq (Nat.ble n m) true) : LE.le n m := match n, m with | 0, _ => Nat.zero_le _ | succ _, succ _ => Nat.succ_le_succ (le_of_ble_eq_true h) theorem Nat.ble_self_eq_true : (n : Nat) → Eq (Nat.ble n n) true | 0 => rfl | succ n => ble_self_eq_true n theorem Nat.ble_succ_eq_true : {n m : Nat} → Eq (Nat.ble n m) true → Eq (Nat.ble n (succ m)) true | 0, _, _ => rfl | succ n, succ _, h => ble_succ_eq_true (n := n) h theorem Nat.ble_eq_true_of_le (h : LE.le n m) : Eq (Nat.ble n m) true := match h with | Nat.le.refl => Nat.ble_self_eq_true n | Nat.le.step h => Nat.ble_succ_eq_true (ble_eq_true_of_le h) theorem Nat.not_le_of_not_ble_eq_true (h : Not (Eq (Nat.ble n m) true)) : Not (LE.le n m) := fun h' => absurd (Nat.ble_eq_true_of_le h') h @[extern "lean_nat_dec_le"] instance Nat.decLe (n m : @& Nat) : Decidable (LE.le n m) := dite (Eq (Nat.ble n m) true) (fun h => isTrue (Nat.le_of_ble_eq_true h)) (fun h => isFalse (Nat.not_le_of_not_ble_eq_true h)) @[extern "lean_nat_dec_lt"] instance Nat.decLt (n m : @& Nat) : Decidable (LT.lt n m) := decLe (succ n) m instance : Min Nat := minOfLe set_option bootstrap.genMatcherCode false in /-- (Truncated) subtraction of natural numbers. Because natural numbers are not closed under subtraction, we define `n - m` to be `0` when `n < m`. This definition is overridden in both the kernel and the compiler to efficiently evaluate using the "bignum" representation (see `Nat`). The definition provided here is the logical model (and it is soundness-critical that they coincide). -/ @[extern "lean_nat_sub"] protected def Nat.sub : (@& Nat) → (@& Nat) → Nat | a, 0 => a | a, succ b => pred (Nat.sub a b) instance : Sub Nat where sub := Nat.sub /-- Gets the word size of the platform. That is, whether the platform is 64 or 32 bits. This function is opaque because we cannot guarantee at compile time that the target will have the same size as the host, and also because we would like to avoid typechecking being architecture-dependent. Nevertheless, lean only works on 64 and 32 bit systems so we can encode this as a fact available for proof purposes. -/ @[extern "lean_system_platform_nbits"] opaque System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) := fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant /-- Gets the word size of the platform. That is, whether the platform is 64 or 32 bits. -/ def System.Platform.numBits : Nat := (getNumBits ()).val theorem System.Platform.numBits_eq : Or (Eq numBits 32) (Eq numBits 64) := (getNumBits ()).property /-- `Fin n` is a natural number `i` with the constraint that `0 ≤ i < n`. It is the "canonical type with `n` elements". -/ structure Fin (n : Nat) where /-- If `i : Fin n`, then `i.val : ℕ` is the described number. It can also be written as `i.1` or just `i` when the target type is known. -/ val : Nat /-- If `i : Fin n`, then `i.2` is a proof that `i.1 < n`. -/ isLt : LT.lt val n theorem Fin.eq_of_val_eq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j | ⟨_, _⟩, ⟨_, _⟩, rfl => rfl theorem Fin.val_eq_of_eq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val := h ▸ rfl theorem Fin.ne_of_val_ne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (val_eq_of_eq h') h instance (n : Nat) : DecidableEq (Fin n) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (Fin.eq_of_val_eq h) | isFalse h => isFalse (Fin.ne_of_val_ne h) instance {n} : LT (Fin n) where lt a b := LT.lt a.val b.val instance {n} : LE (Fin n) where le a b := LE.le a.val b.val instance Fin.decLt {n} (a b : Fin n) : Decidable (LT.lt a b) := Nat.decLt .. instance Fin.decLe {n} (a b : Fin n) : Decidable (LE.le a b) := Nat.decLe .. /-- The size of type `UInt8`, that is, `2^8 = 256`. -/ def UInt8.size : Nat := 256 /-- The type of unsigned 8-bit integers. This type has special support in the compiler to make it actually 8 bits rather than wrapping a `Nat`. -/ structure UInt8 where /-- Unpack a `UInt8` as a `Nat` less than `2^8`. This function is overridden with a native implementation. -/ val : Fin UInt8.size attribute [extern "lean_uint8_of_nat_mk"] UInt8.mk attribute [extern "lean_uint8_to_nat"] UInt8.val /-- Pack a `Nat` less than `2^8` into a `UInt8`. This function is overridden with a native implementation. -/ @[extern "lean_uint8_of_nat"] def UInt8.ofNatCore (n : @& Nat) (h : LT.lt n UInt8.size) : UInt8 where val := { val := n, isLt := h } set_option bootstrap.genMatcherCode false in /-- Decides equality on `UInt8`. This function is overridden with a native implementation. -/ @[extern "lean_uint8_dec_eq"] def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt8 := UInt8.decEq instance : Inhabited UInt8 where default := UInt8.ofNatCore 0 (by decide) /-- The size of type `UInt16`, that is, `2^16 = 65536`. -/ def UInt16.size : Nat := 65536 /-- The type of unsigned 16-bit integers. This type has special support in the compiler to make it actually 16 bits rather than wrapping a `Nat`. -/ structure UInt16 where /-- Unpack a `UInt16` as a `Nat` less than `2^16`. This function is overridden with a native implementation. -/ val : Fin UInt16.size attribute [extern "lean_uint16_of_nat_mk"] UInt16.mk attribute [extern "lean_uint16_to_nat"] UInt16.val /-- Pack a `Nat` less than `2^16` into a `UInt16`. This function is overridden with a native implementation. -/ @[extern "lean_uint16_of_nat"] def UInt16.ofNatCore (n : @& Nat) (h : LT.lt n UInt16.size) : UInt16 where val := { val := n, isLt := h } set_option bootstrap.genMatcherCode false in /-- Decides equality on `UInt16`. This function is overridden with a native implementation. -/ @[extern "lean_uint16_dec_eq"] def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt16 := UInt16.decEq instance : Inhabited UInt16 where default := UInt16.ofNatCore 0 (by decide) /-- The size of type `UInt32`, that is, `2^32 = 4294967296`. -/ def UInt32.size : Nat := 4294967296 /-- The type of unsigned 32-bit integers. This type has special support in the compiler to make it actually 32 bits rather than wrapping a `Nat`. -/ structure UInt32 where /-- Unpack a `UInt32` as a `Nat` less than `2^32`. This function is overridden with a native implementation. -/ val : Fin UInt32.size attribute [extern "lean_uint32_of_nat_mk"] UInt32.mk attribute [extern "lean_uint32_to_nat"] UInt32.val /-- Pack a `Nat` less than `2^32` into a `UInt32`. This function is overridden with a native implementation. -/ @[extern "lean_uint32_of_nat"] def UInt32.ofNatCore (n : @& Nat) (h : LT.lt n UInt32.size) : UInt32 where val := { val := n, isLt := h } /-- Unpack a `UInt32` as a `Nat`. This function is overridden with a native implementation. -/ @[extern "lean_uint32_to_nat"] def UInt32.toNat (n : UInt32) : Nat := n.val.val set_option bootstrap.genMatcherCode false in /-- Decides equality on `UInt32`. This function is overridden with a native implementation. -/ @[extern "lean_uint32_dec_eq"] def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt32 := UInt32.decEq instance : Inhabited UInt32 where default := UInt32.ofNatCore 0 (by decide) instance : LT UInt32 where lt a b := LT.lt a.val b.val instance : LE UInt32 where le a b := LE.le a.val b.val set_option bootstrap.genMatcherCode false in /-- Decides less-equal on `UInt32`. This function is overridden with a native implementation. -/ @[extern "lean_uint32_dec_lt"] def UInt32.decLt (a b : UInt32) : Decidable (LT.lt a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LT.lt n m)) set_option bootstrap.genMatcherCode false in /-- Decides less-than on `UInt32`. This function is overridden with a native implementation. -/ @[extern "lean_uint32_dec_le"] def UInt32.decLe (a b : UInt32) : Decidable (LE.le a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LE.le n m)) instance (a b : UInt32) : Decidable (LT.lt a b) := UInt32.decLt a b instance (a b : UInt32) : Decidable (LE.le a b) := UInt32.decLe a b instance : Max UInt32 := maxOfLe instance : Min UInt32 := minOfLe /-- The size of type `UInt64`, that is, `2^64 = 18446744073709551616`. -/ def UInt64.size : Nat := 18446744073709551616 /-- The type of unsigned 64-bit integers. This type has special support in the compiler to make it actually 64 bits rather than wrapping a `Nat`. -/ structure UInt64 where /-- Unpack a `UInt64` as a `Nat` less than `2^64`. This function is overridden with a native implementation. -/ val : Fin UInt64.size attribute [extern "lean_uint64_of_nat_mk"] UInt64.mk attribute [extern "lean_uint64_to_nat"] UInt64.val /-- Pack a `Nat` less than `2^64` into a `UInt64`. This function is overridden with a native implementation. -/ @[extern "lean_uint64_of_nat"] def UInt64.ofNatCore (n : @& Nat) (h : LT.lt n UInt64.size) : UInt64 where val := { val := n, isLt := h } set_option bootstrap.genMatcherCode false in /-- Decides equality on `UInt64`. This function is overridden with a native implementation. -/ @[extern "lean_uint64_dec_eq"] def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt64 := UInt64.decEq instance : Inhabited UInt64 where default := UInt64.ofNatCore 0 (by decide) /-- The size of type `UInt16`, that is, `2^System.Platform.numBits`, which may be either `2^32` or `2^64` depending on the platform's architecture. -/ def USize.size : Nat := hPow 2 System.Platform.numBits theorem usize_size_eq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) := show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from match System.Platform.numBits, System.Platform.numBits_eq with | _, Or.inl rfl => Or.inl (by decide) | _, Or.inr rfl => Or.inr (by decide) /-- A `USize` is an unsigned integer with the size of a word for the platform's architecture. For example, if running on a 32-bit machine, USize is equivalent to UInt32. Or on a 64-bit machine, UInt64. -/ structure USize where /-- Unpack a `USize` as a `Nat` less than `USize.size`. This function is overridden with a native implementation. -/ val : Fin USize.size attribute [extern "lean_usize_of_nat_mk"] USize.mk attribute [extern "lean_usize_to_nat"] USize.val /-- Pack a `Nat` less than `USize.size` into a `USize`. This function is overridden with a native implementation. -/ @[extern "lean_usize_of_nat"] def USize.ofNatCore (n : @& Nat) (h : LT.lt n USize.size) : USize := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in /-- Decides equality on `USize`. This function is overridden with a native implementation. -/ @[extern "lean_usize_dec_eq"] def USize.decEq (a b : USize) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq USize := USize.decEq instance : Inhabited USize where default := USize.ofNatCore 0 (match USize.size, usize_size_eq with | _, Or.inl rfl => by decide | _, Or.inr rfl => by decide) /-- Upcast a `Nat` less than `2^32` to a `USize`. This is lossless because `USize.size` is either `2^32` or `2^64`. This function is overridden with a native implementation. -/ @[extern "lean_usize_of_nat"] def USize.ofNat32 (n : @& Nat) (h : LT.lt n 4294967296) : USize where val := { val := n isLt := match USize.size, usize_size_eq with | _, Or.inl rfl => h | _, Or.inr rfl => Nat.lt_trans h (by decide) } /-- A `Nat` denotes a valid unicode codepoint if it is less than `0x110000`, and it is also not a "surrogate" character (the range `0xd800` to `0xdfff` inclusive). -/ abbrev Nat.isValidChar (n : Nat) : Prop := Or (LT.lt n 0xd800) (And (LT.lt 0xdfff n) (LT.lt n 0x110000)) /-- A `UInt32` denotes a valid unicode codepoint if it is less than `0x110000`, and it is also not a "surrogate" character (the range `0xd800` to `0xdfff` inclusive). -/ abbrev UInt32.isValidChar (n : UInt32) : Prop := n.toNat.isValidChar /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char where /-- The underlying unicode scalar value as a `UInt32`. -/ val : UInt32 /-- The value must be a legal codepoint. -/ valid : val.isValidChar private theorem isValidChar_UInt32 {n : Nat} (h : n.isValidChar) : LT.lt n UInt32.size := match h with | Or.inl h => Nat.lt_trans h (by decide) | Or.inr ⟨_, h⟩ => Nat.lt_trans h (by decide) /-- Pack a `Nat` encoding a valid codepoint into a `Char`. This function is overridden with a native implementation. -/ @[extern "lean_uint32_of_nat"] def Char.ofNatAux (n : @& Nat) (h : n.isValidChar) : Char := { val := ⟨{ val := n, isLt := isValidChar_UInt32 h }⟩, valid := h } /-- Convert a `Nat` into a `Char`. If the `Nat` does not encode a valid unicode scalar value, `'\0'` is returned instead. -/ @[noinline, match_pattern] def Char.ofNat (n : Nat) : Char := dite (n.isValidChar) (fun h => Char.ofNatAux n h) (fun _ => { val := ⟨{ val := 0, isLt := by decide }⟩, valid := Or.inl (by decide) }) theorem Char.eq_of_val_eq : ∀ {c d : Char}, Eq c.val d.val → Eq c d | ⟨_, _⟩, ⟨_, _⟩, rfl => rfl theorem Char.val_eq_of_eq : ∀ {c d : Char}, Eq c d → Eq c.val d.val | _, _, rfl => rfl theorem Char.ne_of_val_ne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) := fun h' => absurd (val_eq_of_eq h') h theorem Char.val_ne_of_ne {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) := fun h' => absurd (eq_of_val_eq h') h instance : DecidableEq Char := fun c d => match decEq c.val d.val with | isTrue h => isTrue (Char.eq_of_val_eq h) | isFalse h => isFalse (Char.ne_of_val_ne h) /-- Returns the number of bytes required to encode this `Char` in UTF-8. -/ def Char.utf8Size (c : Char) : UInt32 := let v := c.val ite (LE.le v (UInt32.ofNatCore 0x7F (by decide))) (UInt32.ofNatCore 1 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0x7FF (by decide))) (UInt32.ofNatCore 2 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0xFFFF (by decide))) (UInt32.ofNatCore 3 (by decide)) (UInt32.ofNatCore 4 (by decide)))) /-- `Option α` is the type of values which are either `some a` for some `a : α`, or `none`. In functional programming languages, this type is used to represent the possibility of failure, or sometimes nullability. For example, the function `HashMap.find? : HashMap α β → α → Option β` looks up a specified key `a : α` inside the map. Because we do not know in advance whether the key is actually in the map, the return type is `Option β`, where `none` means the value was not in the map, and `some b` means that the value was found and `b` is the value retrieved. To extract a value from an `Option α`, we use pattern matching: ``` def map (f : α → β) (x : Option α) : Option β := match x with | some a => some (f a) | none => none ``` We can also use `if let` to pattern match on `Option` and get the value in the branch: ``` def map (f : α → β) (x : Option α) : Option β := if let some a := x then some (f a) else none ``` -/ inductive Option (α : Type u) where /-- No value. -/ | none : Option α /-- Some value of type `α`. -/ | some (val : α) : Option α attribute [unbox] Option export Option (none some) instance {α} : Inhabited (Option α) where default := none /-- Get with default. If `opt : Option α` and `dflt : α`, then `opt.getD dflt` returns `a` if `opt = some a` and `dflt` otherwise. This function is `@[macro_inline]`, so `dflt` will not be evaluated unless `opt` turns out to be `none`. -/ @[macro_inline] def Option.getD : Option α → α → α | some x, _ => x | none, e => e /-- Map a function over an `Option` by applying the function to the contained value if present. -/ @[inline] protected def Option.map (f : α → β) : Option α → Option β | some x => some (f x) | none => none /-- `List α` is the type of ordered lists with elements of type `α`. It is implemented as a linked list. `List α` is isomorphic to `Array α`, but they are useful for different things: * `List α` is easier for reasoning, and `Array α` is modeled as a wrapper around `List α` * `List α` works well as a persistent data structure, when many copies of the tail are shared. When the value is not shared, `Array α` will have better performance because it can do destructive updates. -/ inductive List (α : Type u) where /-- `[]` is the empty list. -/ | nil : List α /-- If `a : α` and `l : List α`, then `cons a l`, or `a :: l`, is the list whose first element is `a` and with `l` as the rest of the list. -/ | cons (head : α) (tail : List α) : List α instance {α} : Inhabited (List α) where default := List.nil /-- Implements decidable equality for `List α`, assuming `α` has decidable equality. -/ protected def List.hasDecEq {α : Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b) | nil, nil => isTrue rfl | cons _ _, nil => isFalse (fun h => List.noConfusion h) | nil, cons _ _ => isFalse (fun h => List.noConfusion h) | cons a as, cons b bs => match decEq a b with | isTrue hab => match List.hasDecEq as bs with | isTrue habs => isTrue (hab ▸ habs ▸ rfl) | isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs)) | isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab)) instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq /-- Folds a function over a list from the left: `foldl f z [a, b, c] = f (f (f z a) b) c` -/ @[specialize] def List.foldl {α : Type u} {β : Type v} (f : α → β → α) : (init : α) → List β → α | a, nil => a | a, cons b l => foldl f (f a b) l /-- `l.set n a` sets the value of list `l` at (zero-based) index `n` to `a`: `[a, b, c, d].set 1 b' = [a, b', c, d]` -/ def List.set : List α → Nat → α → List α | cons _ as, 0, b => cons b as | cons a as, Nat.succ n, b => cons a (set as n b) | nil, _, _ => nil /-- The length of a list: `[].length = 0` and `(a :: l).length = l.length + 1`. This function is overridden in the compiler to `lengthTR`, which uses constant stack space, while leaving this function to use the "naive" recursion which is easier for reasoning. -/ def List.length : List α → Nat | nil => 0 | cons _ as => HAdd.hAdd (length as) 1 /-- Auxiliary function for `List.lengthTR`. -/ def List.lengthTRAux : List α → Nat → Nat | nil, n => n | cons _ as, n => lengthTRAux as (Nat.succ n) /-- A tail-recursive version of `List.length`, used to implement `List.length` without running out of stack space. -/ def List.lengthTR (as : List α) : Nat := lengthTRAux as 0 @[simp] theorem List.length_cons {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ := rfl /-- `l.concat a` appends `a` at the *end* of `l`, that is, `l ++ [a]`. -/ def List.concat {α : Type u} : List α → α → List α | nil, b => cons b nil | cons a as, b => cons a (concat as b) /-- `as.get i` returns the `i`'th element of the list `as`. This version of the function uses `i : Fin as.length` to ensure that it will not index out of bounds. -/ def List.get {α : Type u} : (as : List α) → Fin as.length → α | cons a _, ⟨0, _⟩ => a | cons _ as, ⟨Nat.succ i, h⟩ => get as ⟨i, Nat.le_of_succ_le_succ h⟩ /-- `String` is the type of (UTF-8 encoded) strings. The compiler overrides the data representation of this type to a byte sequence, and both `String.utf8ByteSize` and `String.length` are cached and O(1). -/ structure String where /-- Pack a `List Char` into a `String`. This function is overridden by the compiler and is O(n) in the length of the list. -/ mk :: /-- Unpack `String` into a `List Char`. This function is overridden by the compiler and is O(n) in the length of the list. -/ data : List Char attribute [extern "lean_string_mk"] String.mk attribute [extern "lean_string_data"] String.data /-- Decides equality on `String`. This function is overridden with a native implementation. -/ @[extern "lean_string_dec_eq"] def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) := match s₁, s₂ with | ⟨s₁⟩, ⟨s₂⟩ => dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq String := String.decEq /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ structure String.Pos where /-- Get the underlying byte index of a `String.Pos` -/ byteIdx : Nat := 0 instance : Inhabited String.Pos where default := {} instance : DecidableEq String.Pos := fun ⟨a⟩ ⟨b⟩ => match decEq a b with | isTrue h => isTrue (h ▸ rfl) | isFalse h => isFalse (fun he => String.Pos.noConfusion he fun he => absurd he h) /-- A `Substring` is a view into some subslice of a `String`. The actual string slicing is deferred because this would require copying the string; here we only store a reference to the original string for garbage collection purposes. -/ structure Substring where /-- The underlying string to slice. -/ str : String /-- The byte position of the start of the string slice. -/ startPos : String.Pos /-- The byte position of the end of the string slice. -/ stopPos : String.Pos instance : Inhabited Substring where default := ⟨"", {}, {}⟩ /-- The byte length of the substring. -/ @[inline] def Substring.bsize : Substring → Nat | ⟨_, b, e⟩ => e.byteIdx.sub b.byteIdx /-- Returns the number of bytes required to encode this `Char` in UTF-8. -/ def String.csize (c : Char) : Nat := c.utf8Size.toNat /-- The UTF-8 byte length of this string. This is overridden by the compiler to be cached and O(1). -/ @[extern "lean_string_utf8_byte_size"] def String.utf8ByteSize : (@& String) → Nat | ⟨s⟩ => go s where go : List Char → Nat | .nil => 0 | .cons c cs => hAdd (go cs) (csize c) instance : HAdd String.Pos String.Pos String.Pos where hAdd p₁ p₂ := { byteIdx := hAdd p₁.byteIdx p₂.byteIdx } instance : HSub String.Pos String.Pos String.Pos where hSub p₁ p₂ := { byteIdx := HSub.hSub p₁.byteIdx p₂.byteIdx } instance : HAdd String.Pos Char String.Pos where hAdd p c := { byteIdx := hAdd p.byteIdx (String.csize c) } instance : HAdd String.Pos String String.Pos where hAdd p s := { byteIdx := hAdd p.byteIdx s.utf8ByteSize } instance : LE String.Pos where le p₁ p₂ := LE.le p₁.byteIdx p₂.byteIdx instance : LT String.Pos where lt p₁ p₂ := LT.lt p₁.byteIdx p₂.byteIdx instance (p₁ p₂ : String.Pos) : Decidable (LE.le p₁ p₂) := inferInstanceAs (Decidable (LE.le p₁.byteIdx p₂.byteIdx)) instance (p₁ p₂ : String.Pos) : Decidable (LT.lt p₁ p₂) := inferInstanceAs (Decidable (LT.lt p₁.byteIdx p₂.byteIdx)) /-- A `String.Pos` pointing at the end of this string. -/ @[inline] def String.endPos (s : String) : String.Pos where byteIdx := utf8ByteSize s /-- Convert a `String` into a `Substring` denoting the entire string. -/ @[inline] def String.toSubstring (s : String) : Substring where str := s startPos := {} stopPos := s.endPos /-- `String.toSubstring` without `[inline]` annotation. -/ def String.toSubstring' (s : String) : Substring := s.toSubstring /-- This function will cast a value of type `α` to type `β`, and is a no-op in the compiler. This function is **extremely dangerous** because there is no guarantee that types `α` and `β` have the same data representation, and this can lead to memory unsafety. It is also logically unsound, since you could just cast `True` to `False`. For all those reasons this function is marked as `unsafe`. It is implemented by lifting both `α` and `β` into a common universe, and then using `cast (lcProof : ULift (PLift α) = ULift (PLift β))` to actually perform the cast. All these operations are no-ops in the compiler. Using this function correctly requires some knowledge of the data representation of the source and target types. Some general classes of casts which are safe in the current runtime: * `Array α` to `Array β` where `α` and `β` have compatible representations, or more generally for other inductive types. * `Quot α r` and `α`. * `@Subtype α p` and `α`, or generally any structure containing only one non-`Prop` field of type `α`. * Casting `α` to/from `NonScalar` when `α` is a boxed generic type (i.e. a function that accepts an arbitrary type `α` and is not specialized to a scalar type like `UInt8`). -/ unsafe def unsafeCast {α : Sort u} {β : Sort v} (a : α) : β := PLift.down (ULift.down.{max u v} (cast lcProof (ULift.up.{max u v} (PLift.up a)))) /-- Auxiliary definition for `panic`. -/ /- This is a workaround for `panic` occurring in monadic code. See issue #695. The `panicCore` definition cannot be specialized since it is an extern. When `panic` occurs in monadic code, the `Inhabited α` parameter depends on a `[inst : Monad m]` instance. The `inst` parameter will not be eliminated during specialization if it occurs inside of a binder (to avoid work duplication), and will prevent the actual monad from being "copied" to the code being specialized. When we reimplement the specializer, we may consider copying `inst` if it also occurs outside binders or if it is an instance. -/ @[never_extract, extern "lean_panic_fn"] def panicCore {α : Type u} [Inhabited α] (msg : String) : α := default /-- `(panic "msg" : α)` has a built-in implementation which prints `msg` to the error buffer. It *does not* terminate execution, and because it is a safe function, it still has to return an element of `α`, so it takes `[Inhabited α]` and returns `default`. It is primarily intended for debugging in pure contexts, and assertion failures. Because this is a pure function with side effects, it is marked as `@[never_extract]` so that the compiler will not perform common sub-expression elimination and other optimizations that assume that the expression is pure. -/ @[noinline, never_extract] def panic {α : Type u} [Inhabited α] (msg : String) : α := panicCore msg -- TODO: this be applied directly to `Inhabited`'s definition when we remove the above workaround attribute [nospecialize] Inhabited /-- The class `GetElem cont idx elem dom` implements the `xs[i]` notation. When you write this, given `xs : cont` and `i : idx`, lean looks for an instance of `GetElem cont idx elem dom`. Here `elem` is the type of `xs[i]`, while `dom` is whatever proof side conditions are required to make this applicable. For example, the instance for arrays looks like `GetElem (Array α) Nat α (fun xs i => i < xs.size)`. The proof side-condition `dom xs i` is automatically dispatched by the `get_elem_tactic` tactic, which can be extended by adding more clauses to `get_elem_tactic_trivial`. -/ class GetElem (cont : Type u) (idx : Type v) (elem : outParam (Type w)) (dom : outParam (cont → idx → Prop)) where /-- The syntax `arr[i]` gets the `i`'th element of the collection `arr`. If there are proof side conditions to the application, they will be automatically inferred by the `get_elem_tactic` tactic. The actual behavior of this class is type-dependent, but here are some important implementations: * `arr[i] : α` where `arr : Array α` and `i : Nat` or `i : USize`: does array indexing with no bounds check and a proof side goal `i < arr.size`. * `l[i] : α` where `l : List α` and `i : Nat`: index into a list, with proof side goal `i < l.length`. * `stx[i] : Syntax` where `stx : Syntax` and `i : Nat`: get a syntax argument, no side goal (returns `.missing` out of range) There are other variations on this syntax: * `arr[i]`: proves the proof side goal by `get_elem_tactic` * `arr[i]!`: panics if the side goal is false * `arr[i]?`: returns `none` if the side goal is false * `arr[i]'h`: uses `h` to prove the side goal -/ getElem (xs : cont) (i : idx) (h : dom xs i) : elem export GetElem (getElem) /-- `Array α` is the type of [dynamic arrays](https://en.wikipedia.org/wiki/Dynamic_array) with elements from `α`. This type has special support in the runtime. An array has a size and a capacity; the size is `Array.size` but the capacity is not observable from lean code. Arrays perform best when unshared; as long as they are used "linearly" all updates will be performed destructively on the array, so it has comparable performance to mutable arrays in imperative programming languages. -/ structure Array (α : Type u) where /-- Convert a `List α` into an `Array α`. This function is overridden to `List.toArray` and is O(n) in the length of the list. -/ mk :: /-- Convert an `Array α` into a `List α`. This function is overridden to `Array.toList` and is O(n) in the length of the list. -/ data : List α attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_mk"] Array.mk /-- Construct a new empty array with initial capacity `c`. -/ @[extern "lean_mk_empty_array_with_capacity"] def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α where data := List.nil /-- Construct a new empty array. -/ def Array.empty {α : Type u} : Array α := mkEmpty 0 /-- Get the size of an array. This is a cached value, so it is O(1) to access. -/ @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.data.length /-- Access an element from an array without bounds checks, using a `Fin` index. -/ @[extern "lean_array_fget"] def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α := a.data.get i /-- Access an element from an array, or return `v₀` if the index is out of bounds. -/ @[inline] abbrev Array.getD (a : Array α) (i : Nat) (v₀ : α) : α := dite (LT.lt i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀) /-- Access an element from an array, or panic if the index is out of bounds. -/ @[extern "lean_array_get"] def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α := Array.getD a i default instance : GetElem (Array α) Nat α fun xs i => LT.lt i xs.size where getElem xs i h := xs.get ⟨i, h⟩ /-- Push an element onto the end of an array. This is amortized O(1) because `Array α` is internally a dynamic array. -/ @[extern "lean_array_push"] def Array.push {α : Type u} (a : Array α) (v : α) : Array α where data := List.concat a.data v /-- Create array `#[]` -/ def Array.mkArray0 {α : Type u} : Array α := mkEmpty 0 /-- Create array `#[a₁]` -/ def Array.mkArray1 {α : Type u} (a₁ : α) : Array α := (mkEmpty 1).push a₁ /-- Create array `#[a₁, a₂]` -/ def Array.mkArray2 {α : Type u} (a₁ a₂ : α) : Array α := ((mkEmpty 2).push a₁).push a₂ /-- Create array `#[a₁, a₂, a₃]` -/ def Array.mkArray3 {α : Type u} (a₁ a₂ a₃ : α) : Array α := (((mkEmpty 3).push a₁).push a₂).push a₃ /-- Create array `#[a₁, a₂, a₃, a₄]` -/ def Array.mkArray4 {α : Type u} (a₁ a₂ a₃ a₄ : α) : Array α := ((((mkEmpty 4).push a₁).push a₂).push a₃).push a₄ /-- Create array `#[a₁, a₂, a₃, a₄, a₅]` -/ def Array.mkArray5 {α : Type u} (a₁ a₂ a₃ a₄ a₅ : α) : Array α := (((((mkEmpty 5).push a₁).push a₂).push a₃).push a₄).push a₅ /-- Create array `#[a₁, a₂, a₃, a₄, a₅, a₆]` -/ def Array.mkArray6 {α : Type u} (a₁ a₂ a₃ a₄ a₅ a₆ : α) : Array α := ((((((mkEmpty 6).push a₁).push a₂).push a₃).push a₄).push a₅).push a₆ /-- Create array `#[a₁, a₂, a₃, a₄, a₅, a₆, a₇]` -/ def Array.mkArray7 {α : Type u} (a₁ a₂ a₃ a₄ a₅ a₆ a₇ : α) : Array α := (((((((mkEmpty 7).push a₁).push a₂).push a₃).push a₄).push a₅).push a₆).push a₇ /-- Create array `#[a₁, a₂, a₃, a₄, a₅, a₆, a₇, a₈]` -/ def Array.mkArray8 {α : Type u} (a₁ a₂ a₃ a₄ a₅ a₆ a₇ a₈ : α) : Array α := ((((((((mkEmpty 8).push a₁).push a₂).push a₃).push a₄).push a₅).push a₆).push a₇).push a₈ /-- Set an element in an array without bounds checks, using a `Fin` index. This will perform the update destructively provided that `a` has a reference count of 1 when called. -/ @[extern "lean_array_fset"] def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α where data := a.data.set i.val v /-- Set an element in an array, or do nothing if the index is out of bounds. This will perform the update destructively provided that `a` has a reference count of 1 when called. -/ @[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α := dite (LT.lt i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a) /-- Set an element in an array, or panic if the index is out of bounds. This will perform the update destructively provided that `a` has a reference count of 1 when called. -/ @[extern "lean_array_set"] def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α := Array.setD a i v /-- Slower `Array.append` used in quotations. -/ protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α := let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α := dite (LT.lt j bs.size) (fun hlt => match i with | 0 => as | Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩))) (fun _ => as) loop bs.size 0 as /-- Returns the slice of `as` from indices `start` to `stop` (exclusive). If `start` is greater or equal to `stop`, the result is empty. If `stop` is greater than the length of `as`, the length is used instead. -/ -- NOTE: used in the quotation elaborator output def Array.extract (as : Array α) (start stop : Nat) : Array α := let rec loop (i : Nat) (j : Nat) (bs : Array α) : Array α := dite (LT.lt j as.size) (fun hlt => match i with | 0 => bs | Nat.succ i' => loop i' (hAdd j 1) (bs.push (as.get ⟨j, hlt⟩))) (fun _ => bs) let sz' := Nat.sub (min stop as.size) start loop sz' start (mkEmpty sz') /-- Auxiliary definition for `List.toArray`. -/ @[inline_if_reduce] def List.toArrayAux : List α → Array α → Array α | nil, r => r | cons a as, r => toArrayAux as (r.push a) /-- A non-tail-recursive version of `List.length`, used for `List.toArray`. -/ @[inline_if_reduce] def List.redLength : List α → Nat | nil => 0 | cons _ as => as.redLength.succ /-- Convert a `List α` into an `Array α`. This is O(n) in the length of the list. This function is exported to C, where it is called by `Array.mk` (the constructor) to implement this functionality. -/ @[inline, match_pattern, export lean_list_to_array] def List.toArray (as : List α) : Array α := as.toArrayAux (Array.mkEmpty as.redLength) /-- The typeclass which supplies the `>>=` "bind" function. See `Monad`. -/ class Bind (m : Type u → Type v) where /-- If `x : m α` and `f : α → m β`, then `x >>= f : m β` represents the result of executing `x` to get a value of type `α` and then passing it to `f`. -/ bind : {α β : Type u} → m α → (α → m β) → m β export Bind (bind) /-- The typeclass which supplies the `pure` function. See `Monad`. -/ class Pure (f : Type u → Type v) where /-- If `a : α`, then `pure a : f α` represents a monadic action that does nothing and returns `a`. -/ pure {α : Type u} : α → f α export Pure (pure) /-- In functional programming, a "functor" is a function on types `F : Type u → Type v` equipped with an operator called `map` or `<$>` such that if `f : α → β` then `map f : F α → F β`, so `f <$> x : F β` if `x : F α`. This corresponds to the category-theory notion of [functor](https://en.wikipedia.org/wiki/Functor) in the special case where the category is the category of types and functions between them, except that this class supplies only the operations and not the laws (see `LawfulFunctor`). -/ class Functor (f : Type u → Type v) : Type (max (u+1) v) where /-- If `f : α → β` and `x : F α` then `f <$> x : F β`. -/ map : {α β : Type u} → (α → β) → f α → f β /-- The special case `const a <$> x`, which can sometimes be implemented more efficiently. -/ mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _) /-- The typeclass which supplies the `<*>` "seq" function. See `Applicative`. -/ class Seq (f : Type u → Type v) : Type (max (u+1) v) where /-- If `mf : F (α → β)` and `mx : F α`, then `mf <*> mx : F β`. In a monad this is the same as `do let f ← mf; x ← mx; pure (f x)`: it evaluates first the function, then the argument, and applies one to the other. To avoid surprising evaluation semantics, `mx` is taken "lazily", using a `Unit → f α` function. -/ seq : {α β : Type u} → f (α → β) → (Unit → f α) → f β /-- The typeclass which supplies the `<*` "seqLeft" function. See `Applicative`. -/ class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where /-- If `x : F α` and `y : F β`, then `x <* y` evaluates `x`, then `y`, and returns the result of `x`. To avoid surprising evaluation semantics, `y` is taken "lazily", using a `Unit → f β` function. -/ seqLeft : {α β : Type u} → f α → (Unit → f β) → f α /-- The typeclass which supplies the `*>` "seqRight" function. See `Applicative`. -/ class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where /-- If `x : F α` and `y : F β`, then `x *> y` evaluates `x`, then `y`, and returns the result of `y`. To avoid surprising evaluation semantics, `y` is taken "lazily", using a `Unit → f β` function. -/ seqRight : {α β : Type u} → f α → (Unit → f β) → f β /-- An [applicative functor](https://en.wikipedia.org/wiki/Applicative_functor) is an intermediate structure between `Functor` and `Monad`. It mainly consists of two operations: * `pure : α → F α` * `seq : F (α → β) → F α → F β` (written as `<*>`) The `seq` operator gives a notion of evaluation order to the effects, where the first argument is executed before the second, but unlike a monad the results of earlier computations cannot be used to define later actions. -/ class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where map := fun x y => Seq.seq (pure x) fun _ => y seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b /-- A [monad](https://en.wikipedia.org/wiki/Monad_(functional_programming)) is a structure which abstracts the concept of sequential control flow. It mainly consists of two operations: * `pure : α → F α` * `bind : F α → (α → F β) → F β` (written as `>>=`) Like many functional programming languages, Lean makes extensive use of monads for structuring programs. In particular, the `do` notation is a very powerful syntax over monad operations, and it depends on a `Monad` instance. See [the `do` notation](https://leanprover.github.io/lean4/doc/do.html) chapter of the manual for details. -/ class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where map f x := bind x (Function.comp pure f) seq f x := bind f fun y => Functor.map y (x ()) seqLeft x y := bind x fun a => bind (y ()) (fun _ => pure a) seqRight x y := bind x fun _ => y () instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where default := pure instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where default := pure default instance [Monad m] : [Nonempty α] → Nonempty (m α) | ⟨x⟩ => ⟨pure x⟩ /-- A fusion of Haskell's `sequence` and `map`. Used in syntax quotations. -/ def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) := let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) := dite (LT.lt j as.size) (fun hlt => match i with | 0 => pure bs | Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b)) (fun _ => pure bs) loop as.size 0 (Array.mkEmpty as.size) /-- A function for lifting a computation from an inner `Monad` to an outer `Monad`. Like Haskell's [`MonadTrans`], but `n` does not have to be a monad transformer. Alternatively, an implementation of [`MonadLayer`] without `layerInvmap` (so far). [`MonadTrans`]: https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html [`MonadLayer`]: https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer -/ class MonadLift (m : semiOutParam (Type u → Type v)) (n : Type u → Type w) where /-- Lifts a value from monad `m` into monad `n`. -/ monadLift : {α : Type u} → m α → n α /-- The reflexive-transitive closure of `MonadLift`. `monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`. Corresponds to Haskell's [`MonadLift`]. [`MonadLift`]: https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift -/ class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where /-- Lifts a value from monad `m` into monad `n`. -/ monadLift : {α : Type u} → m α → n α export MonadLiftT (monadLift) /-- Lifts a value from monad `m` into monad `n`. -/ abbrev liftM := @monadLift @[always_inline] instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where monadLift x := MonadLift.monadLift (m := n) (monadLift x) instance (m) : MonadLiftT m m where monadLift x := x /-- A functor in the category of monads. Can be used to lift monad-transforming functions. Based on [`MFunctor`] from the `pipes` Haskell package, but not restricted to monad transformers. Alternatively, an implementation of [`MonadTransFunctor`]. [`MFunctor`]: https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html [`MonadTransFunctor`]: http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor -/ class MonadFunctor (m : semiOutParam (Type u → Type v)) (n : Type u → Type w) where /-- Lifts a monad morphism `f : {β : Type u} → m β → m β` to `monadMap f : {α : Type u} → n α → n α`. -/ monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift `Monad` morphisms. -/ class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where /-- Lifts a monad morphism `f : {β : Type u} → m β → m β` to `monadMap f : {α : Type u} → n α → n α`. -/ monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α export MonadFunctorT (monadMap) @[always_inline] instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f) instance monadFunctorRefl (m) : MonadFunctorT m m where monadMap f := f /-- `Except ε α` is a type which represents either an error of type `ε`, or an "ok" value of type `α`. The error type is listed first because `Except ε : Type → Type` is a `Monad`: the pure operation is `ok` and the bind operation returns the first encountered `error`. -/ inductive Except (ε : Type u) (α : Type v) where /-- A failure value of type `ε` -/ | error : ε → Except ε α /-- A success value of type `α` -/ | ok : α → Except ε α attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where default := Except.error default /-- An implementation of Haskell's [`MonadError`] class. A `MonadError ε m` is a monad `m` with two operations: * `throw : ε → m α` "throws an error" of type `ε` to the nearest enclosing catch block * `tryCatch (body : m α) (handler : ε → m α) : m α` will catch any errors in `body` and pass the resulting error to `handler`. Errors in `handler` will not be caught. The `try ... catch e => ...` syntax inside `do` blocks is sugar for the `tryCatch` operation. [`MonadError`]: https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError -/ class MonadExceptOf (ε : semiOutParam (Type u)) (m : Type v → Type w) where /-- `throw : ε → m α` "throws an error" of type `ε` to the nearest enclosing catch block. -/ throw {α : Type v} : ε → m α /-- `tryCatch (body : m α) (handler : ε → m α) : m α` will catch any errors in `body` and pass the resulting error to `handler`. Errors in `handler` will not be caught. -/ tryCatch {α : Type v} (body : m α) (handler : ε → m α) : m α /-- This is the same as `throw`, but allows specifying the particular error type in case the monad supports throwing more than one type of error. -/ abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α := MonadExceptOf.throw e /-- This is the same as `tryCatch`, but allows specifying the particular error type in case the monad supports throwing more than one type of error. -/ abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α := MonadExceptOf.tryCatch x handle /-- Similar to `MonadExceptOf`, but `ε` is an `outParam` for convenience. -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where /-- `throw : ε → m α` "throws an error" of type `ε` to the nearest enclosing catch block. -/ throw {α : Type v} : ε → m α /-- `tryCatch (body : m α) (handler : ε → m α) : m α` will catch any errors in `body` and pass the resulting error to `handler`. Errors in `handler` will not be caught. -/ tryCatch {α : Type v} : m α → (ε → m α) → m α /-- "Unwraps" an `Except ε α` to get the `α`, or throws the exception otherwise. -/ def MonadExcept.ofExcept [Monad m] [MonadExcept ε m] : Except ε α → m α | .ok a => pure a | .error e => throw e export MonadExcept (throw tryCatch ofExcept) instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where throw := throwThe ε tryCatch := tryCatchThe ε namespace MonadExcept variable {ε : Type u} {m : Type v → Type w} /-- A `MonadExcept` can implement `t₁ <|> t₂` as `try t₁ catch _ => t₂`. -/ @[inline] protected def orElse [MonadExcept ε m] {α : Type v} (t₁ : m α) (t₂ : Unit → m α) : m α := tryCatch t₁ fun _ => t₂ () instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where orElse := MonadExcept.orElse end MonadExcept /-- An implementation of Haskell's [`ReaderT`]. This is a monad transformer which equips a monad with additional read-only state, of type `ρ`. [`ReaderT`]: https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where default := fun _ => default /-- If `x : ReaderT ρ m α` and `r : ρ`, then `x.run r : ρ` runs the monad with the given reader state. -/ @[always_inline, inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r namespace ReaderT section variable {ρ : Type u} {m : Type u → Type v} {α : Type u} instance : MonadLift m (ReaderT ρ m) where monadLift x := fun _ => x @[always_inline] instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where throw e := liftM (m := m) (throw e) tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r) end section variable {ρ : Type u} {m : Type u → Type v} /-- `(← read) : ρ` gets the read-only state of a `ReaderT ρ`. -/ @[always_inline, inline] protected def read [Monad m] : ReaderT ρ m ρ := pure /-- The `pure` operation of the `ReaderT` monad. -/ @[always_inline, inline] protected def pure [Monad m] {α} (a : α) : ReaderT ρ m α := fun _ => pure a /-- The `bind` operation of the `ReaderT` monad. -/ @[always_inline, inline] protected def bind [Monad m] {α β} (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => bind (x r) fun a => f a r @[always_inline] instance [Monad m] : Functor (ReaderT ρ m) where map f x r := Functor.map f (x r) mapConst a x r := Functor.mapConst a (x r) @[always_inline] instance [Monad m] : Applicative (ReaderT ρ m) where pure := ReaderT.pure seq f x r := Seq.seq (f r) fun _ => x () r seqLeft a b r := SeqLeft.seqLeft (a r) fun _ => b () r seqRight a b r := SeqRight.seqRight (a r) fun _ => b () r instance [Monad m] : Monad (ReaderT ρ m) where bind := ReaderT.bind instance (ρ m) : MonadFunctor m (ReaderT ρ m) where monadMap f x := fun ctx => f (x ctx) /-- `adapt (f : ρ' → ρ)` precomposes function `f` on the reader state of a `ReaderT ρ`, yielding a `ReaderT ρ'`. -/ @[always_inline, inline] protected def adapt {ρ' α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) end end ReaderT /-- An implementation of Haskell's [`MonadReader`] (sans functional dependency; see also `MonadReader` in this module). It does not contain `local` because this function cannot be lifted using `monadLift`. `local` is instead provided by the `MonadWithReader` class as `withReader`. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReaderOf (ρ : Type u) (n : Type u → Type u) where lift {α : Type u} : ({m : Type u → Type u} → [Monad m] → ReaderT ρ m α) → n α ``` [`MonadReader`]: https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader -/ class MonadReaderOf (ρ : semiOutParam (Type u)) (m : Type u → Type v) where /-- `(← read) : ρ` reads the state out of monad `m`. -/ read : m ρ /-- Like `read`, but with `ρ` explicit. This is useful if a monad supports `MonadReaderOf` for multiple different types `ρ`. -/ @[always_inline, inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an `outParam` for convenience. -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where /-- `(← read) : ρ` reads the state out of monad `m`. -/ read : m ρ export MonadReader (read) instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where read := readThe ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadReaderOf ρ m] : MonadReaderOf ρ n where read := liftM (m := m) read instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where read := ReaderT.read /-- `MonadWithReaderOf ρ` adds the operation `withReader : (ρ → ρ) → m α → m α`. This runs the inner `x : m α` inside a modified context after applying the function `f : ρ → ρ`. In addition to `ReaderT` itself, this operation lifts over most monad transformers, so it allows us to apply `withReader` to monads deeper in the stack. -/ class MonadWithReaderOf (ρ : semiOutParam (Type u)) (m : Type u → Type v) where /-- `withReader (f : ρ → ρ) (x : m α) : m α` runs the inner `x : m α` inside a modified context after applying the function `f : ρ → ρ`.-/ withReader {α : Type u} : (ρ → ρ) → m α → m α /-- Like `withReader`, but with `ρ` explicit. This is useful if a monad supports `MonadWithReaderOf` for multiple different types `ρ`. -/ @[always_inline, inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α := MonadWithReaderOf.withReader f x /-- Similar to `MonadWithReaderOf`, but `ρ` is an `outParam` for convenience. -/ class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where /-- `withReader (f : ρ → ρ) (x : m α) : m α` runs the inner `x : m α` inside a modified context after applying the function `f : ρ → ρ`.-/ withReader {α : Type u} : (ρ → ρ) → m α → m α export MonadWithReader (withReader) instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where withReader := withTheReader ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadFunctor m n] [MonadWithReaderOf ρ m] : MonadWithReaderOf ρ n where withReader f := monadMap (m := m) (withTheReader ρ f) instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where withReader f x := fun ctx => x (f ctx) /-- An implementation of [`MonadState`]. In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monadLift`. [`MonadState`]: https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html -/ class MonadStateOf (σ : semiOutParam (Type u)) (m : Type u → Type v) where /-- `(← get) : σ` gets the state out of a monad `m`. -/ get : m σ /-- `set (s : σ)` replaces the state with value `s`. -/ set : σ → m PUnit /-- `modifyGet (f : σ → α × σ)` applies `f` to the current state, replaces the state with the return value, and returns a computed value. It is equivalent to `do let (a, s) := f (← get); put s; pure a`, but `modifyGet f` may be preferable because the former does not use the state linearly (without sufficient inlining). -/ modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadStateOf (set) /-- Like `withReader`, but with `ρ` explicit. This is useful if a monad supports `MonadWithReaderOf` for multiple different types `ρ`. -/ abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ := MonadStateOf.get /-- Like `modify`, but with `σ` explicit. This is useful if a monad supports `MonadStateOf` for multiple different types `σ`. -/ @[always_inline, inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit := MonadStateOf.modifyGet fun s => (PUnit.unit, f s) /-- Like `modifyGet`, but with `σ` explicit. This is useful if a monad supports `MonadStateOf` for multiple different types `σ`. -/ @[always_inline, inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α := MonadStateOf.modifyGet f /-- Similar to `MonadStateOf`, but `σ` is an `outParam` for convenience. -/ class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where /-- `(← get) : σ` gets the state out of a monad `m`. -/ get : m σ /-- `set (s : σ)` replaces the state with value `s`. -/ set : σ → m PUnit /-- `modifyGet (f : σ → α × σ)` applies `f` to the current state, replaces the state with the return value, and returns a computed value. It is equivalent to `do let (a, s) := f (← get); put s; pure a`, but `modifyGet f` may be preferable because the former does not use the state linearly (without sufficient inlining). -/ modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadState (get modifyGet) instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where set := MonadStateOf.set get := getThe σ modifyGet f := MonadStateOf.modifyGet f /-- `modify (f : σ → σ)` applies the function `f` to the state. It is equivalent to `do put (f (← get))`, but `modify f` may be preferable because the former does not use the state linearly (without sufficient inlining). -/ @[always_inline, inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit := modifyGet fun s => (PUnit.unit, f s) /-- `getModify f` gets the state, applies function `f`, and returns the old value of the state. It is equivalent to `get <* modify f` but may be more efficient. -/ @[always_inline, inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ := modifyGet fun s => (s, f s) -- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer -- will be picked first @[always_inline] instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadStateOf σ m] : MonadStateOf σ n where get := liftM (m := m) MonadStateOf.get set s := liftM (m := m) (MonadStateOf.set s) modifyGet f := monadLift (m := m) (MonadState.modifyGet f) namespace EStateM /-- `Result ε σ α` is equivalent to `Except ε α × σ`, but using a single combined inductive yields a more efficient data representation. -/ inductive Result (ε σ α : Type u) where /-- A success value of type `α`, and a new state `σ`. -/ | ok : α → σ → Result ε σ α /-- A failure value of type `ε`, and a new state `σ`. -/ | error : ε → σ → Result ε σ α variable {ε σ α : Type u} instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where default := Result.error default default end EStateM open EStateM (Result) in /-- `EStateM ε σ` is a combined error and state monad, equivalent to `ExceptT ε (StateM σ)` but more efficient. -/ def EStateM (ε σ α : Type u) := σ → Result ε σ α namespace EStateM variable {ε σ α β : Type u} instance [Inhabited ε] : Inhabited (EStateM ε σ α) where default := fun s => Result.error default s /-- The `pure` operation of the `EStateM` monad. -/ @[always_inline, inline] protected def pure (a : α) : EStateM ε σ α := fun s => Result.ok a s /-- The `set` operation of the `EStateM` monad. -/ @[always_inline, inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ => Result.ok ⟨⟩ s /-- The `get` operation of the `EStateM` monad. -/ @[always_inline, inline] protected def get : EStateM ε σ σ := fun s => Result.ok s s /-- The `modifyGet` operation of the `EStateM` monad. -/ @[always_inline, inline] protected def modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s => match f s with | (a, s) => Result.ok a s /-- The `throw` operation of the `EStateM` monad. -/ @[always_inline, inline] protected def throw (e : ε) : EStateM ε σ α := fun s => Result.error e s /-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. Here `σ` is the state, and `δ` is some subpart of it, and we have a getter and setter for it (a "lens" in the Haskell terminology). -/ class Backtrackable (δ : outParam (Type u)) (σ : Type u) where /-- `save s : δ` retrieves a copy of the backtracking state out of the state. -/ save : σ → δ /-- `restore (s : σ) (x : δ) : σ` applies the old backtracking state `x` to the state `s` to get a backtracked state `s'`. -/ restore : σ → δ → σ /-- Implementation of `tryCatch` for `EStateM` where the state is `Backtrackable`. -/ @[always_inline, inline] protected def tryCatch {δ} [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 /-- Implementation of `orElse` for `EStateM` where the state is `Backtrackable`. -/ @[always_inline, inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ : EStateM ε σ α) (x₂ : Unit → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s; match x₁ s with | Result.error _ s => x₂ () (Backtrackable.restore s d) | ok => ok /-- Map the exception type of a `EStateM ε σ α` by a function `f : ε → ε'`. -/ @[always_inline, 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 /-- The `bind` operation of the `EStateM` monad. -/ @[always_inline, 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 /-- The `map` operation of the `EStateM` monad. -/ @[always_inline, 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 /-- The `seqRight` operation of the `EStateM` monad. -/ @[always_inline, inline] protected def seqRight (x : EStateM ε σ α) (y : Unit → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok _ s => y () s | Result.error e s => Result.error e s @[always_inline] instance : Monad (EStateM ε σ) where bind := EStateM.bind pure := EStateM.pure map := EStateM.map seqRight := EStateM.seqRight instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where orElse := EStateM.orElse instance : MonadStateOf σ (EStateM ε σ) where set := EStateM.set get := EStateM.get modifyGet := EStateM.modifyGet instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where throw := EStateM.throw tryCatch := EStateM.tryCatch /-- Execute an `EStateM` on initial state `s` to get a `Result`. -/ @[always_inline, inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α := x s /-- Execute an `EStateM` on initial state `s` for the returned value `α`. If the monadic action throws an exception, returns `none` instead. -/ @[always_inline, inline] def run' (x : EStateM ε σ α) (s : σ) : Option α := match run x s with | Result.ok v _ => some v | Result.error .. => none /-- The `save` implementation for `Backtrackable PUnit σ`. -/ @[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩ /-- The `restore` implementation for `Backtrackable PUnit σ`. -/ @[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s /-- Dummy default instance. This makes every `σ` trivially "backtrackable" by doing nothing on backtrack. Because this is the first declared instance of `Backtrackable _ σ`, it will be picked only if there are no other `Backtrackable _ σ` instances registered. -/ instance nonBacktrackable : Backtrackable PUnit σ where save := dummySave restore := dummyRestore end EStateM /-- A class for types that can be hashed into a `UInt64`. -/ class Hashable (α : Sort u) where /-- Hashes the value `a : α` into a `UInt64`. -/ hash : α → UInt64 export Hashable (hash) /-- Converts a `UInt64` to a `USize` by reducing modulo `USize.size`. -/ @[extern "lean_uint64_to_usize"] opaque UInt64.toUSize (u : UInt64) : USize /-- Upcast a `USize` to a `UInt64`. This is lossless because `USize.size` is either `2^32` or `2^64`. This function is overridden with a native implementation. -/ @[extern "lean_usize_to_uint64"] def USize.toUInt64 (u : USize) : UInt64 where val := { val := u.val.val isLt := let ⟨n, h⟩ := u show LT.lt n _ from match USize.size, usize_size_eq, h with | _, Or.inl rfl, h => Nat.lt_trans h (by decide) | _, Or.inr rfl, h => h } /-- An opaque hash mixing operation, used to implement hashing for tuples. -/ @[extern "lean_uint64_mix_hash"] opaque mixHash (u₁ u₂ : UInt64) : UInt64 instance [Hashable α] {p : α → Prop} : Hashable (Subtype p) where hash a := hash a.val /-- An opaque string hash function. -/ @[extern "lean_string_hash"] protected opaque String.hash (s : @& String) : UInt64 instance : Hashable String where hash := String.hash namespace Lean /-- Hierarchical names. We use hierarchical names to name declarations and for creating unique identifiers for free variables and metavariables. You can create hierarchical names using the following quotation notation. ``` `Lean.Meta.whnf ``` It is short for `.str (.str (.str .anonymous "Lean") "Meta") "whnf"` You can use double quotes to request Lean to statically check whether the name corresponds to a Lean declaration in scope. ``` ``Lean.Meta.whnf ``` If the name is not in scope, Lean will report an error. -/ inductive Name where /-- The "anonymous" name. -/ | anonymous : Name /-- A string name. The name `Lean.Meta.run` is represented at ```lean .str (.str (.str .anonymous "Lean") "Meta") "run" ``` -/ | str (pre : Name) (str : String) /-- A numerical name. This kind of name is used, for example, to create hierarchical names for free variables and metavariables. The identifier `_uniq.231` is represented as ```lean .num (.str .anonymous "_uniq") 231 ``` -/ | num (pre : Name) (i : Nat) with /-- A hash function for names, which is stored inside the name itself as a computed field. -/ @[computed_field] hash : Name → UInt64 | .anonymous => .ofNatCore 1723 (by decide) | .str p s => mixHash p.hash s.hash | .num p v => mixHash p.hash (dite (LT.lt v UInt64.size) (fun h => UInt64.ofNatCore v h) (fun _ => UInt64.ofNatCore 17 (by decide))) instance : Inhabited Name where default := Name.anonymous instance : Hashable Name where hash := Name.hash namespace Name /-- `.str p s` is now the preferred form. -/ @[export lean_name_mk_string] abbrev mkStr (p : Name) (s : String) : Name := Name.str p s /-- `.num p v` is now the preferred form. -/ @[export lean_name_mk_numeral] abbrev mkNum (p : Name) (v : Nat) : Name := Name.num p v /-- Short for `.str .anonymous s`. -/ abbrev mkSimple (s : String) : Name := .str .anonymous s /-- Make name `s₁` -/ @[reducible] def mkStr1 (s₁ : String) : Name := .str .anonymous s₁ /-- Make name `s₁.s₂` -/ @[reducible] def mkStr2 (s₁ s₂ : String) : Name := .str (.str .anonymous s₁) s₂ /-- Make name `s₁.s₂.s₃` -/ @[reducible] def mkStr3 (s₁ s₂ s₃ : String) : Name := .str (.str (.str .anonymous s₁) s₂) s₃ /-- Make name `s₁.s₂.s₃.s₄` -/ @[reducible] def mkStr4 (s₁ s₂ s₃ s₄ : String) : Name := .str (.str (.str (.str .anonymous s₁) s₂) s₃) s₄ /-- Make name `s₁.s₂.s₃.s₄.s₅` -/ @[reducible] def mkStr5 (s₁ s₂ s₃ s₄ s₅ : String) : Name := .str (.str (.str (.str (.str .anonymous s₁) s₂) s₃) s₄) s₅ /-- Make name `s₁.s₂.s₃.s₄.s₅.s₆` -/ @[reducible] def mkStr6 (s₁ s₂ s₃ s₄ s₅ s₆ : String) : Name := .str (.str (.str (.str (.str (.str .anonymous s₁) s₂) s₃) s₄) s₅) s₆ /-- Make name `s₁.s₂.s₃.s₄.s₅.s₆.s₇` -/ @[reducible] def mkStr7 (s₁ s₂ s₃ s₄ s₅ s₆ s₇ : String) : Name := .str (.str (.str (.str (.str (.str (.str .anonymous s₁) s₂) s₃) s₄) s₅) s₆) s₇ /-- Make name `s₁.s₂.s₃.s₄.s₅.s₆.s₇.s₈` -/ @[reducible] def mkStr8 (s₁ s₂ s₃ s₄ s₅ s₆ s₇ s₈ : String) : Name := .str (.str (.str (.str (.str (.str (.str (.str .anonymous s₁) s₂) s₃) s₄) s₅) s₆) s₇) s₈ /-- (Boolean) equality comparator for names. -/ @[extern "lean_name_eq"] protected def beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁, str p₂ s₂ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂) | num p₁ n₁, num p₂ n₂ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂) | _, _ => false instance : BEq Name where beq := Name.beq /-- This function does not have special support for macro scopes. See `Name.append`. -/ def appendCore : Name → Name → Name | n, .anonymous => n | n, .str p s => .str (appendCore n p) s | n, .num p d => .num (appendCore n p) d end Name /-! # Syntax -/ /-- Source information of tokens. -/ inductive SourceInfo where /-- Token from original input with whitespace and position information. `leading` will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ | original (leading : Substring) (pos : String.Pos) (trailing : Substring) (endPos : String.Pos) /-- Synthesized syntax (e.g. from a quotation) annotated with a span from the original source. In the delaborator, we "misuse" this constructor to store synthetic positions identifying subterms. The `canonical` flag on synthetic syntax is enabled for syntax that is not literally part of the original input syntax but should be treated "as if" the user really wrote it for the purpose of hovers and error messages. This is usually used on identifiers, to connect the binding site to the user's original syntax even if the name of the identifier changes during expansion, as well as on tokens where we will attach targeted messages. The syntax `token%$stx` in a syntax quotation will annotate the token `token` with the span from `stx` and also mark it as canonical. As a rough guide, a macro expansion should only use a given piece of input syntax in a single canonical token, although this is sometimes violated when the same identifier is used to declare two binders, as in the macro expansion for dependent if: ``` `(if $h : $cond then $t else $e) ~> `(dite $cond (fun $h => $t) (fun $h => $t)) ``` In these cases if the user hovers over `h` they will see information about both binding sites. -/ | synthetic (pos : String.Pos) (endPos : String.Pos) (canonical := false) /-- Synthesized token without position information. -/ | protected none instance : Inhabited SourceInfo := ⟨SourceInfo.none⟩ namespace SourceInfo /-- Gets the position information from a `SourceInfo`, if available. If `originalOnly` is true, then `.synthetic` syntax will also return `none`. -/ def getPos? (info : SourceInfo) (canonicalOnly := false) : Option String.Pos := match info, canonicalOnly with | original (pos := pos) .., _ | synthetic (pos := pos) (canonical := true) .., _ | synthetic (pos := pos) .., false => some pos | _, _ => none end SourceInfo /-- A `SyntaxNodeKind` classifies `Syntax.node` values. It is an abbreviation for `Name`, and you can use name literals to construct `SyntaxNodeKind`s, but they need not refer to declarations in the environment. Conventionally, a `SyntaxNodeKind` will correspond to the `Parser` or `ParserDesc` declaration that parses it. -/ abbrev SyntaxNodeKind := Name /-! # Syntax AST -/ /-- Binding information resolved and stored at compile time of a syntax quotation. Note: We do not statically know whether a syntax expects a namespace or term name, so a `Syntax.ident` may contain both preresolution kinds. -/ inductive Syntax.Preresolved where /-- A potential namespace reference -/ | namespace (ns : Name) /-- A potential global constant or section variable reference, with additional field accesses -/ | decl (n : Name) (fields : List String) /-- Syntax objects used by the parser, macro expander, delaborator, etc. -/ inductive Syntax where /-- A `missing` syntax corresponds to a portion of the syntax tree that is missing because of a parse error. The indexing operator on Syntax also returns `missing` for indexing out of bounds. -/ | missing : Syntax /-- Node in the syntax tree. The `info` field is used by the delaborator to store the position of the subexpression corresponding to this node. The parser sets the `info` field to `none`. The parser sets the `info` field to `none`, with position retrieval continuing recursively. Nodes created by quotations use the result from `SourceInfo.fromRef` so that they are marked as synthetic even when the leading/trailing token is not. The delaborator uses the `info` field to store the position of the subexpression corresponding to this node. (Remark: the `node` constructor did not have an `info` field in previous versions. This caused a bug in the interactive widgets, where the popup for `a + b` was the same as for `a`. The delaborator used to associate subexpressions with pretty-printed syntax by setting the (string) position of the first atom/identifier to the (expression) position of the subexpression. For example, both `a` and `a + b` have the same first identifier, and so their infos got mixed up.) -/ | node (info : SourceInfo) (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax /-- An `atom` corresponds to a keyword or piece of literal unquoted syntax. These correspond to quoted strings inside `syntax` declarations. For example, in `(x + y)`, `"("`, `"+"` and `")"` are `atom` and `x` and `y` are `ident`. -/ | atom (info : SourceInfo) (val : String) : Syntax /-- An `ident` corresponds to an identifier as parsed by the `ident` or `rawIdent` parsers. * `rawVal` is the literal substring from the input file * `val` is the parsed identifier (with hygiene) * `preresolved` is the list of possible declarations this could refer to -/ | ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List Syntax.Preresolved) : Syntax /-- Create syntax node with 1 child -/ def Syntax.node1 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray1 a₁) /-- Create syntax node with 2 children -/ def Syntax.node2 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray2 a₁ a₂) /-- Create syntax node with 3 children -/ def Syntax.node3 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ a₃ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray3 a₁ a₂ a₃) /-- Create syntax node with 4 children -/ def Syntax.node4 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ a₃ a₄ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray4 a₁ a₂ a₃ a₄) /-- Create syntax node with 5 children -/ def Syntax.node5 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ a₃ a₄ a₅ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray5 a₁ a₂ a₃ a₄ a₅) /-- Create syntax node with 6 children -/ def Syntax.node6 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ a₃ a₄ a₅ a₆ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray6 a₁ a₂ a₃ a₄ a₅ a₆) /-- Create syntax node with 7 children -/ def Syntax.node7 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ a₃ a₄ a₅ a₆ a₇ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray7 a₁ a₂ a₃ a₄ a₅ a₆ a₇) /-- Create syntax node with 8 children -/ def Syntax.node8 (info : SourceInfo) (kind : SyntaxNodeKind) (a₁ a₂ a₃ a₄ a₅ a₆ a₇ a₈ : Syntax) : Syntax := Syntax.node info kind (Array.mkArray8 a₁ a₂ a₃ a₄ a₅ a₆ a₇ a₈) /-- `SyntaxNodeKinds` is a set of `SyntaxNodeKind` (implemented as a list). -/ def SyntaxNodeKinds := List SyntaxNodeKind /-- A `Syntax` value of one of the given syntax kinds. Note that while syntax quotations produce/expect `TSyntax` values of the correct kinds, this is not otherwise enforced and can easily be circumvented by direct use of the constructor. The namespace `TSyntax.Compat` can be opened to expose a general coercion from `Syntax` to any `TSyntax ks` for porting older code. -/ structure TSyntax (ks : SyntaxNodeKinds) where /-- The underlying `Syntax` value. -/ raw : Syntax instance : Inhabited Syntax where default := Syntax.missing instance : Inhabited (TSyntax ks) where default := ⟨default⟩ /-! # Builtin kinds -/ /-- The `choice` kind is used when a piece of syntax has multiple parses, and the determination of which to use is deferred until typing information is available. -/ abbrev choiceKind : SyntaxNodeKind := `choice /-- The null kind is used for raw list parsers like `many`. -/ abbrev nullKind : SyntaxNodeKind := `null /-- The `group` kind is by the `group` parser, to avoid confusing with the null kind when used inside `optional`. -/ abbrev groupKind : SyntaxNodeKind := `group /-- `ident` is not actually used as a node kind, but it is returned by `getKind` in the `ident` case so that things that handle different node kinds can also handle `ident`. -/ abbrev identKind : SyntaxNodeKind := `ident /-- `str` is the node kind of string literals like `"foo"`. -/ abbrev strLitKind : SyntaxNodeKind := `str /-- `char` is the node kind of character literals like `'A'`. -/ abbrev charLitKind : SyntaxNodeKind := `char /-- `num` is the node kind of number literals like `42`. -/ abbrev numLitKind : SyntaxNodeKind := `num /-- `scientific` is the node kind of floating point literals like `1.23e-3`. -/ abbrev scientificLitKind : SyntaxNodeKind := `scientific /-- `name` is the node kind of name literals like `` `foo ``. -/ abbrev nameLitKind : SyntaxNodeKind := `name /-- `fieldIdx` is the node kind of projection indices like the `2` in `x.2`. -/ abbrev fieldIdxKind : SyntaxNodeKind := `fieldIdx /-- `hygieneInfo` is the node kind of the `hygieneInfo` parser, which is an "invisible token" which captures the hygiene information at the current point without parsing anything. They can be used to generate identifiers (with `Lean.HygieneInfo.mkIdent`) as if they were introduced by the calling context, not the called macro. -/ abbrev hygieneInfoKind : SyntaxNodeKind := `hygieneInfo /-- `interpolatedStrLitKind` is the node kind of interpolated string literal fragments like `"value = {` and `}"` in `s!"value = {x}"`. -/ abbrev interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind /-- `interpolatedStrKind` is the node kind of an interpolated string literal like `"value = {x}"` in `s!"value = {x}"`. -/ abbrev interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind /-- Creates an info-less node of the given kind and children. -/ @[inline] def mkNode (k : SyntaxNodeKind) (args : Array Syntax) : TSyntax (.cons k .nil) := ⟨Syntax.node SourceInfo.none k args⟩ /-- Creates an info-less `nullKind` node with the given children, if any. -/ -- NOTE: used by the quotation elaborator output @[inline] def mkNullNode (args : Array Syntax := Array.empty) : Syntax := mkNode nullKind args |>.raw namespace Syntax /-- Gets the kind of a `Syntax` node. For non-`node` syntax, we use "pseudo kinds": `identKind` for `ident`, `missing` for `missing`, and the atom's string literal for atoms. -/ def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node _ k _ => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => Name.mkSimple v | Syntax.ident .. => identKind /-- Changes the kind at the root of a `Syntax` node to `k`. Does nothing for non-`node` nodes. -/ def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node info _ args => Syntax.node info k args | _ => stx /-- Is this a syntax with node kind `k`? -/ def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k /-- Gets the `i`'th argument of the syntax node. This can also be written `stx[i]`. Returns `missing` if `i` is out of range. -/ def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ _ args => args.getD i Syntax.missing | _ => Syntax.missing instance : GetElem Syntax Nat Syntax fun _ _ => True where getElem stx i _ := stx.getArg i /-- Gets the list of arguments of the syntax node, or `#[]` if it's not a `node`. -/ def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ _ args => args | _ => Array.empty /-- Gets the number of arguments of the syntax node, or `0` if it's not a `node`. -/ def getNumArgs (stx : Syntax) : Nat := match stx with | Syntax.node _ _ args => args.size | _ => 0 /-- Assuming `stx` was parsed by `optional`, returns the enclosed syntax if it parsed something and `none` otherwise. -/ def getOptional? (stx : Syntax) : Option Syntax := match stx with | Syntax.node _ k args => match and (beq k nullKind) (beq args.size 1) with | true => some (args.get! 0) | false => none | _ => none /-- Is this syntax `.missing`? -/ def isMissing : Syntax → Bool | Syntax.missing => true | _ => false /-- Is this syntax a `node` with kind `k`? -/ def isNodeOf (stx : Syntax) (k : SyntaxNodeKind) (n : Nat) : Bool := and (stx.isOfKind k) (beq stx.getNumArgs n) /-- `stx.isIdent` is `true` iff `stx` is an identifier. -/ def isIdent : Syntax → Bool | ident .. => true | _ => false /-- If this is an `ident`, return the parsed value, else `.anonymous`. -/ def getId : Syntax → Name | ident _ _ val _ => val | _ => Name.anonymous /-- Updates the argument list without changing the node kind. Does nothing for non-`node` nodes. -/ def setArgs (stx : Syntax) (args : Array Syntax) : Syntax := match stx with | node info k _ => node info k args | stx => stx /-- Updates the `i`'th argument of the syntax. Does nothing for non-`node` nodes, or if `i` is out of bounds of the node list. -/ def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax := match stx with | node info k args => node info k (args.setD i arg) | stx => stx /-- Retrieve the left-most node or leaf's info in the Syntax tree. -/ partial def getHeadInfo? : Syntax → Option SourceInfo | atom info _ => some info | ident info .. => some info | node SourceInfo.none _ args => let rec loop (i : Nat) : Option SourceInfo := match decide (LT.lt i args.size) with | true => match getHeadInfo? (args.get! i) with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | node info _ _ => some info | _ => none /-- Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token. -/ partial def getHeadInfo (stx : Syntax) : SourceInfo := match stx.getHeadInfo? with | some info => info | none => SourceInfo.none /-- Get the starting position of the syntax, if possible. If `canonicalOnly` is true, non-canonical `synthetic` nodes are treated as not carrying position information. -/ def getPos? (stx : Syntax) (canonicalOnly := false) : Option String.Pos := stx.getHeadInfo.getPos? canonicalOnly /-- Get the ending position of the syntax, if possible. If `canonicalOnly` is true, non-canonical `synthetic` nodes are treated as not carrying position information. -/ partial def getTailPos? (stx : Syntax) (canonicalOnly := false) : Option String.Pos := match stx, canonicalOnly with | atom (SourceInfo.original (endPos := pos) ..) .., _ | atom (SourceInfo.synthetic (endPos := pos) (canonical := true) ..) _, _ | atom (SourceInfo.synthetic (endPos := pos) ..) _, false | ident (SourceInfo.original (endPos := pos) ..) .., _ | ident (SourceInfo.synthetic (endPos := pos) (canonical := true) ..) .., _ | ident (SourceInfo.synthetic (endPos := pos) ..) .., false | node (SourceInfo.original (endPos := pos) ..) .., _ | node (SourceInfo.synthetic (endPos := pos) (canonical := true) ..) .., _ | node (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node _ _ args, _ => let rec loop (i : Nat) : Option String.Pos := match decide (LT.lt i args.size) with | true => match getTailPos? (args.get! ((args.size.sub i).sub 1)) canonicalOnly with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _, _ => none /-- An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically remove/insert the separators. -/ structure SepArray (sep : String) where /-- The array of elements and separators, ordered like `#[el1, sep1, el2, sep2, el3]`. -/ elemsAndSeps : Array Syntax /-- A typed version of `SepArray`. -/ structure TSepArray (ks : SyntaxNodeKinds) (sep : String) where /-- The array of elements and separators, ordered like `#[el1, sep1, el2, sep2, el3]`. -/ elemsAndSeps : Array Syntax end Syntax /-- An array of syntaxes of kind `ks`. -/ abbrev TSyntaxArray (ks : SyntaxNodeKinds) := Array (TSyntax ks) /-- Implementation of `TSyntaxArray.raw`. -/ unsafe def TSyntaxArray.rawImpl : TSyntaxArray ks → Array Syntax := unsafeCast /-- Converts a `TSyntaxArray` to an `Array Syntax`, without reallocation. -/ @[implemented_by TSyntaxArray.rawImpl] opaque TSyntaxArray.raw (as : TSyntaxArray ks) : Array Syntax := Array.empty /-- Implementation of `TSyntaxArray.mk`. -/ unsafe def TSyntaxArray.mkImpl : Array Syntax → TSyntaxArray ks := unsafeCast /-- Converts an `Array Syntax` to a `TSyntaxArray`, without reallocation. -/ @[implemented_by TSyntaxArray.mkImpl] opaque TSyntaxArray.mk (as : Array Syntax) : TSyntaxArray ks := Array.empty /-- Constructs a synthetic `SourceInfo` using a `ref : Syntax` for the span. -/ def SourceInfo.fromRef (ref : Syntax) (canonical := false) : SourceInfo := let noncanonical ref := match ref.getPos?, ref.getTailPos? with | some pos, some tailPos => .synthetic pos tailPos | _, _ => .none match canonical with | true => match ref.getPos? true, ref.getTailPos? true with | some pos, some tailPos => .synthetic pos tailPos true | _, _ => noncanonical ref | false => noncanonical ref /-- Constructs a synthetic `atom` with no source info. -/ def mkAtom (val : String) : Syntax := Syntax.atom SourceInfo.none val /-- Constructs a synthetic `atom` with source info coming from `src`. -/ def mkAtomFrom (src : Syntax) (val : String) (canonical := false) : Syntax := Syntax.atom (SourceInfo.fromRef src canonical) val /-! # Parser descriptions -/ /-- A `ParserDescr` is a grammar for parsers. This is used by the `syntax` command to produce parsers without having to `import Lean`. -/ inductive ParserDescr where /-- A (named) nullary parser, like `ppSpace` -/ | const (name : Name) /-- A (named) unary parser, like `group(p)` -/ | unary (name : Name) (p : ParserDescr) /-- A (named) binary parser, like `orelse` or `andthen` (written as `p1 <|> p2` and `p1 p2` respectively in `syntax`) -/ | binary (name : Name) (p₁ p₂ : ParserDescr) /-- Parses using `p`, then pops the stack to create a new node with kind `kind`. The precedence `prec` is used to determine whether the parser should apply given the current precedence level. -/ | node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) /-- Like `node` but for trailing parsers (which start with a nonterminal). Assumes the lhs is already on the stack, and parses using `p`, then pops the stack including the lhs to create a new node with kind `kind`. The precedence `prec` and `lhsPrec` are used to determine whether the parser should apply. -/ | trailingNode (kind : SyntaxNodeKind) (prec lhsPrec : Nat) (p : ParserDescr) /-- A literal symbol parser: parses `val` as a literal. This parser does not work on identifiers, so `symbol` arguments are declared as "keywords" and cannot be used as identifiers anywhere in the file. -/ | symbol (val : String) /-- Like `symbol`, but without reserving `val` as a keyword. If `includeIdent` is true then `ident` will be reinterpreted as `atom` if it matches. -/ | nonReservedSymbol (val : String) (includeIdent : Bool) /-- Parses using the category parser `catName` with right binding power (i.e. precedence) `rbp`. -/ | cat (catName : Name) (rbp : Nat) /-- Parses using another parser `declName`, which can be either a `Parser` or `ParserDescr`. -/ | parser (declName : Name) /-- Like `node`, but also declares that the body can be matched using an antiquotation with name `name`. For example, `def $id:declId := 1` uses an antiquotation with name `declId` in the place where a `declId` is expected. -/ | nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr) /-- A `sepBy(p, sep)` parses 0 or more occurrences of `p` separated by `sep`. `psep` is usually the same as `symbol sep`, but it can be overridden. `sep` is only used in the antiquot syntax: `$x;*` would match if `sep` is `";"`. `allowTrailingSep` is true if e.g. `a, b,` is also allowed to match. -/ | sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) /-- `sepBy1` is just like `sepBy`, except it takes 1 or more instead of 0 or more occurrences of `p`. -/ | sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) instance : Inhabited ParserDescr where default := ParserDescr.symbol "" /-- Although `TrailingParserDescr` is an abbreviation for `ParserDescr`, Lean will look at the declared type in order to determine whether to add the parser to the leading or trailing parser table. The determination is done automatically by the `syntax` command. -/ abbrev TrailingParserDescr := ParserDescr /-! Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ /-- A macro scope identifier is just a `Nat` that gets bumped every time we enter a new macro scope. Within a macro scope, all occurrences of identifier `x` parse to the same thing, but `x` parsed from different macro scopes will produce different identifiers. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := hAdd reservedMacroScope 1 /-- A `MonadRef` is a monad that has a `ref : Syntax` in the read-only state. This is used to keep track of the location where we are working; if an exception is thrown, the `ref` gives the location where the error will be reported, assuming no more specific location is provided. -/ class MonadRef (m : Type → Type) where /-- Get the current value of the `ref` -/ getRef : m Syntax /-- Run `x : m α` with a modified value for the `ref` -/ withRef {α} : Syntax → m α → m α export MonadRef (getRef) instance (m n : Type → Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where getRef := liftM (getRef : m _) withRef ref x := monadMap (m := m) (MonadRef.withRef ref) x /-- Replaces `oldRef` with `ref`, unless `ref` has no position info. This biases us to having a valid span to report an error on. -/ def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax := match ref.getPos? with | some _ => ref | _ => oldRef /-- Run `x : m α` with a modified value for the `ref`. This is not exactly the same as `MonadRef.withRef`, because it uses `replaceRef` to avoid putting syntax with bad spans in the state. -/ @[always_inline, inline] def withRef [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α := bind getRef fun oldRef => let ref := replaceRef ref oldRef MonadRef.withRef ref x /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). We also apply the position of the result of `getRef` to each introduced symbol, which results in better error positions than not applying any position. -/ class MonadQuotation (m : Type → Type) extends MonadRef m where /-- Get the fresh scope of the current macro invocation -/ getCurrMacroScope : m MacroScope /-- Get the module name of the current file. This is used to ensure that hygienic names don't clash across multiple files. -/ getMainModule : m Name /-- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ withFreshMacroScope {α : Type} : m α → m α export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope) /-- Construct a synthetic `SourceInfo` from the `ref` in the monad state. -/ @[inline] def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := return SourceInfo.fromRef (← getRef) instance [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where getCurrMacroScope := liftM (m := m) getCurrMacroScope getMainModule := liftM (m := m) getMainModule withFreshMacroScope := monadMap (m := m) withFreshMacroScope /-! We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right-most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr._hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ /-- Does this name have hygienic macro scopes? -/ def Name.hasMacroScopes : Name → Bool | str _ s => beq s "_hyg" | num p _ => hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | .str p s => match beq s "_@" with | true => p | false => eraseMacroScopesAux p | .num p _ => eraseMacroScopesAux p | .anonymous => Name.anonymous /-- Remove the macro scopes from the name. -/ @[export lean_erase_macro_scopes] def Name.eraseMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => eraseMacroScopesAux n | false => n private def simpMacroScopesAux : Name → Name | .num p i => Name.mkNum (simpMacroScopesAux p) i | n => eraseMacroScopesAux n /-- Helper function we use to create binder names that do not need to be unique. -/ @[export lean_simp_macro_scopes] def Name.simpMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => simpMacroScopesAux n | false => n /-- A `MacroScopesView` represents a parsed hygienic name. `extractMacroScopes` will decode it from a `Name`, and `.review` will re-encode it. The grammar of a hygienic name is: ``` <name>._@.(<module_name>.<scopes>)*.<mainModule>._hyg.<scopes> ``` -/ structure MacroScopesView where /-- The original (unhygienic) name. -/ name : Name /-- All the name components `(<module_name>.<scopes>)*` from the imports concatenated together. -/ imported : Name /-- The main module in which this identifier was parsed. -/ mainModule : Name /-- The list of macro scopes. -/ scopes : List MacroScope instance : Inhabited MacroScopesView where default := ⟨default, default, default, default⟩ /-- Encode a hygienic name from the parsed pieces. -/ def MacroScopesView.review (view : MacroScopesView) : Name := match view.scopes with | List.nil => view.name | List.cons _ _ => let base := (Name.mkStr (Name.appendCore (Name.appendCore (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg") view.scopes.foldl Name.mkNum base private def assembleParts : List Name → Name → Name | .nil, acc => acc | .cons (.str _ s) ps, acc => assembleParts ps (Name.mkStr acc s) | .cons (.num _ n) ps, acc => assembleParts ps (Name.mkNum acc n) | _, _ => panic "Error: unreachable @ assembleParts" private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str), parts => match beq str "_@" with | true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } | false => extractImported scps mainModule p (List.cons n parts) | n@(Name.num p _), parts => extractImported scps mainModule p (List.cons n parts) | _, _ => panic "Error: unreachable @ extractImported" private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str), parts => match beq str "_@" with | true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } | false => extractMainModule scps p (List.cons n parts) | n@(Name.num _ _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil | _, _ => panic "Error: unreachable @ extractMainModule" private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp, acc => extractMacroScopesAux p (List.cons scp acc) | Name.str p _ , acc => extractMainModule acc p List.nil -- str must be "_hyg" | _, _ => panic "Error: unreachable @ extractMacroScopesAux" /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := match n.hasMacroScopes with | true => extractMacroScopesAux n List.nil | false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous } /-- Add a new macro scope onto the name `n`, in the given `mainModule`. -/ def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := match n.hasMacroScopes with | true => let view := extractMacroScopes n match beq view.mainModule mainModule with | true => Name.mkNum n scp | false => { view with imported := view.scopes.foldl Name.mkNum (Name.appendCore view.imported view.mainModule) mainModule := mainModule scopes := List.cons scp List.nil }.review | false => Name.mkNum (Name.mkStr (Name.appendCore (Name.mkStr n "_@") mainModule) "_hyg") scp /-- Append two names that may have macro scopes. The macro scopes in `b` are always erased. If `a` has macro scopes, then they are propagated to the result of `append a b`. -/ def Name.append (a b : Name) : Name := match a.hasMacroScopes, b.hasMacroScopes with | true, true => panic "Error: invalid `Name.append`, both arguments have macro scopes, consider using `eraseMacroScopes`" | true, false => let view := extractMacroScopes a { view with name := appendCore view.name b }.review | false, true => let view := extractMacroScopes b { view with name := appendCore a view.name }.review | false, false => appendCore a b instance : Append Name where append := Name.append /-- Add a new macro scope onto the name `n`, using the monad state to supply the main module and current macro scope. -/ @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := bind getMainModule fun mainModule => bind getCurrMacroScope fun scp => pure (Lean.addMacroScope mainModule n scp) /-- The default maximum recursion depth. This is adjustable using the `maxRecDepth` option. -/ def defaultMaxRecDepth := 512 /-- The message to display on stack overflow. -/ def maxRecDepthErrorMessage : String := "maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)" namespace Syntax /-- Is this syntax a null `node`? -/ def matchesNull (stx : Syntax) (n : Nat) : Bool := stx.isNodeOf nullKind n /-- Function used for determining whether a syntax pattern `` `(id) `` is matched. There are various conceivable notions of when two syntactic identifiers should be regarded as identical, but semantic definitions like whether they refer to the same global name cannot be implemented without context information (i.e. `MonadResolveName`). Thus in patterns we default to the structural solution of comparing the identifiers' `Name` values, though we at least do so modulo macro scopes so that identifiers that "look" the same match. This is particularly useful when dealing with identifiers that do not actually refer to Lean bindings, e.g. in the `stx` pattern `` `(many($p)) ``. -/ def matchesIdent (stx : Syntax) (id : Name) : Bool := and stx.isIdent (beq stx.getId.eraseMacroScopes id.eraseMacroScopes) /-- Is this syntax a node kind `k` wrapping an `atom _ val`? -/ def matchesLit (stx : Syntax) (k : SyntaxNodeKind) (val : String) : Bool := match stx with | Syntax.node _ k' args => and (beq k k') (match args.getD 0 Syntax.missing with | Syntax.atom _ val' => beq val val' | _ => false) | _ => false end Syntax namespace Macro /-- References -/ private opaque MethodsRefPointed : NonemptyType.{0} private def MethodsRef : Type := MethodsRefPointed.type instance : Nonempty MethodsRef := MethodsRefPointed.property /-- The read-only context for the `MacroM` monad. -/ structure Context where /-- An opaque reference to the `Methods` object. This is done to break a dependency cycle: the `Methods` involve `MacroM` which has not been defined yet. -/ methods : MethodsRef /-- The currently parsing module. -/ mainModule : Name /-- The current macro scope. -/ currMacroScope : MacroScope /-- The current recursion depth. -/ currRecDepth : Nat := 0 /-- The maximum recursion depth. -/ maxRecDepth : Nat := defaultMaxRecDepth /-- The syntax which supplies the position of error messages. -/ ref : Syntax /-- An exception in the `MacroM` monad. -/ inductive Exception where /-- A general error, given a message and a span (expressed as a `Syntax`). -/ | error : Syntax → String → Exception /-- An unsupported syntax exception. We keep this separate because it is used for control flow: if one macro does not support a syntax then we try the next one. -/ | unsupportedSyntax : Exception /-- The mutable state for the `MacroM` monad. -/ structure State where /-- The global macro scope counter, used for producing fresh scope names. -/ macroScope : MacroScope /-- The list of trace messages that have been produced, each with a trace class and a message. -/ traceMsgs : List (Prod Name String) := List.nil deriving Inhabited end Macro /-- The `MacroM` monad is the main monad for macro expansion. It has the information needed to handle hygienic name generation, and is the monad that `macro` definitions live in. Notably, this is a (relatively) pure monad: there is no `IO` and no access to the `Environment`. That means that things like declaration lookup are impossible here, as well as `IO.Ref` or other side-effecting operations. For more capabilities, macros can instead be written as `elab` using `adaptExpander`. -/ abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception Macro.State) /-- A `macro` has type `Macro`, which is a `Syntax → MacroM Syntax`: it receives an input syntax and is supposed to "expand" it into another piece of syntax. -/ abbrev Macro := Syntax → MacroM Syntax namespace Macro instance : MonadRef MacroM where getRef := bind read fun ctx => pure ctx.ref withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x /-- Add a new macro scope to the name `n`. -/ def addMacroScope (n : Name) : MacroM Name := bind read fun ctx => pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope) /-- Throw an `unsupportedSyntax` exception. -/ def throwUnsupported {α} : MacroM α := throw Exception.unsupportedSyntax /-- Throw an error with the given message, using the `ref` for the location information. -/ def throwError {α} (msg : String) : MacroM α := bind getRef fun ref => throw (Exception.error ref msg) /-- Throw an error with the given message and location information. -/ def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α := withRef ref (throwError msg) /-- Increments the macro scope counter so that inside the body of `x` the macro scope is fresh. -/ @[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α := bind (modifyGet (fun s => (s.macroScope, { s with macroScope := hAdd s.macroScope 1 }))) fun fresh => withReader (fun ctx => { ctx with currMacroScope := fresh }) x /-- Run `x` with an incremented recursion depth counter. -/ @[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α := bind read fun ctx => match beq ctx.currRecDepth ctx.maxRecDepth with | true => throw (Exception.error ref maxRecDepthErrorMessage) | false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x instance : MonadQuotation MacroM where getCurrMacroScope ctx := pure ctx.currMacroScope getMainModule ctx := pure ctx.mainModule withFreshMacroScope := Macro.withFreshMacroScope /-- The opaque methods that are available to `MacroM`. -/ structure Methods where /-- Expands macros in the given syntax. A return value of `none` means there was nothing to expand. -/ expandMacro? : Syntax → MacroM (Option Syntax) /-- Get the current namespace in the file. -/ getCurrNamespace : MacroM Name /-- Check if a given name refers to a declaration. -/ hasDecl : Name → MacroM Bool /-- Resolves the given name to an overload list of namespaces. -/ resolveNamespace : Name → MacroM (List Name) /-- Resolves the given name to an overload list of global definitions. The `List String` in each alternative is the deduced list of projections (which are ambiguous with name components). -/ resolveGlobalName : Name → MacroM (List (Prod Name (List String))) deriving Inhabited /-- Implementation of `mkMethods`. -/ unsafe def mkMethodsImp (methods : Methods) : MethodsRef := unsafeCast methods /-- Make an opaque reference to a `Methods`. -/ @[implemented_by mkMethodsImp] opaque mkMethods (methods : Methods) : MethodsRef instance : Inhabited MethodsRef where default := mkMethods default /-- Implementation of `getMethods`. -/ unsafe def getMethodsImp : MacroM Methods := bind read fun ctx => pure (unsafeCast (ctx.methods)) /-- Extract the methods list from the `MacroM` state. -/ @[implemented_by getMethodsImp] opaque getMethods : MacroM Methods /-- `expandMacro? stx` returns `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/ def expandMacro? (stx : Syntax) : MacroM (Option Syntax) := do (← getMethods).expandMacro? stx /-- Returns `true` if the environment contains a declaration with name `declName` -/ def hasDecl (declName : Name) : MacroM Bool := do (← getMethods).hasDecl declName /-- Gets the current namespace given the position in the file. -/ def getCurrNamespace : MacroM Name := do (← getMethods).getCurrNamespace /-- Resolves the given name to an overload list of namespaces. -/ def resolveNamespace (n : Name) : MacroM (List Name) := do (← getMethods).resolveNamespace n /-- Resolves the given name to an overload list of global definitions. The `List String` in each alternative is the deduced list of projections (which are ambiguous with name components). -/ def resolveGlobalName (n : Name) : MacroM (List (Prod Name (List String))) := do (← getMethods).resolveGlobalName n /-- Add a new trace message, with the given trace class and message. -/ def trace (clsName : Name) (msg : String) : MacroM Unit := do modify fun s => { s with traceMsgs := List.cons (Prod.mk clsName msg) s.traceMsgs } end Macro export Macro (expandMacro?) namespace PrettyPrinter /-- The unexpander monad, essentially `Syntax → Option α`. The `Syntax` is the `ref`, and it has the possibility of failure without an error message. -/ abbrev UnexpandM := ReaderT Syntax (EStateM Unit Unit) /-- Function that tries to reverse macro expansions as a post-processing step of delaboration. While less general than an arbitrary delaborator, it can be declared without importing `Lean`. Used by the `[app_unexpander]` attribute. -/ -- a `kindUnexpander` could reasonably be added later abbrev Unexpander := Syntax → UnexpandM Syntax instance : MonadQuotation UnexpandM where getRef := read withRef ref x := withReader (fun _ => ref) x -- unexpanders should not need to introduce new names getCurrMacroScope := pure 0 getMainModule := pure `_fakeMod withFreshMacroScope := id end PrettyPrinter end Lean
7be47ca50842eb0e7a4871c885c0752ced71791b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/mutualdef1.lean
c24deb843cff494fcccd668fd04354abb7a2d9f0
[ "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
462
lean
-- mutual def f (x : Nat) : Nat → Nat | 0 => 1 | x+1 => g x theorem g (x : Nat) : Nat → Nat -- cannot mix theorems and definitions | 0 => 2 | x+1 => f x end mutual def f : Nat → Nat | 0 => 1 | x+1 => g x example : Nat := -- cannot mix examples and definitions g 10 end mutual def f (x : Nat) : Nat → Nat | 0 => 1 | x+1 => g x unsafe def g (x : Nat) : Nat → Nat -- cannot mix safe and unsafe definitions | 0 => 2 | x+1 => f x end
f97b9cb58a8b84226cc1bf072696f2e9f5142023
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/category_theory/isomorphism.lean
16206c5ca7ea69c8ace3257d2fae81fe814be43d
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,213
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor /-! # Isomorphisms This file defines isomorphisms between objects of a category. ## Main definitions - `structure iso` : a bundled isomorphism between two objects of a category; - `class is_iso` : an unbundled version of `iso`; note that `is_iso f` is a `Prop`, and only asserts the existence of an inverse. Of course, this inverse is unique, so it doesn't cost us much to use choice to retrieve it. - `inv f`, for the inverse of a morphism with `[is_iso f]` - `as_iso` : convert from `is_iso` to `iso` (noncomputable); - `of_iso` : convert from `iso` to `is_iso`; - standard operations on isomorphisms (composition, inverse etc) ## Notations - `X ≅ Y` : same as `iso X Y`; - `α ≪≫ β` : composition of two isomorphisms; it is called `iso.trans` ## Tags category, category theory, isomorphism -/ universes v u -- morphism levels before object levels. See note [category_theory universes]. namespace category_theory open category /-- An isomorphism (a.k.a. an invertible morphism) between two objects of a category. The inverse morphism is bundled. See also `category_theory.core` for the category with the same objects and isomorphisms playing the role of morphisms. See https://stacks.math.columbia.edu/tag/0017. -/ structure iso {C : Type u} [category.{v} C] (X Y : C) := (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id' : hom ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ hom = 𝟙 Y . obviously) restate_axiom iso.hom_inv_id' restate_axiom iso.inv_hom_id' attribute [simp, reassoc] iso.hom_inv_id iso.inv_hom_id infixr ` ≅ `:10 := iso -- type as \cong or \iso variables {C : Type u} [category.{v} C] variables {X Y Z : C} namespace iso @[ext] lemma ext ⦃α β : X ≅ Y⦄ (w : α.hom = β.hom) : α = β := suffices α.inv = β.inv, by cases α; cases β; cc, calc α.inv = α.inv ≫ (β.hom ≫ β.inv) : by rw [iso.hom_inv_id, category.comp_id] ... = (α.inv ≫ α.hom) ≫ β.inv : by rw [category.assoc, ←w] ... = β.inv : by rw [iso.inv_hom_id, category.id_comp] /-- Inverse isomorphism. -/ @[symm] def symm (I : X ≅ Y) : Y ≅ X := { hom := I.inv, inv := I.hom, hom_inv_id' := I.inv_hom_id', inv_hom_id' := I.hom_inv_id' } @[simp] lemma symm_hom (α : X ≅ Y) : α.symm.hom = α.inv := rfl @[simp] lemma symm_inv (α : X ≅ Y) : α.symm.inv = α.hom := rfl @[simp] lemma symm_mk {X Y : C} (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id) : iso.symm {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} = {hom := inv, inv := hom, hom_inv_id' := inv_hom_id, inv_hom_id' := hom_inv_id} := rfl @[simp] lemma symm_symm_eq {X Y : C} (α : X ≅ Y) : α.symm.symm = α := by cases α; refl @[simp] lemma symm_eq_iff {X Y : C} {α β : X ≅ Y} : α.symm = β.symm ↔ α = β := ⟨λ h, symm_symm_eq α ▸ symm_symm_eq β ▸ congr_arg symm h, congr_arg symm⟩ /-- Identity isomorphism. -/ @[refl, simps] def refl (X : C) : X ≅ X := { hom := 𝟙 X, inv := 𝟙 X } instance : inhabited (X ≅ X) := ⟨iso.refl X⟩ @[simp] lemma refl_symm (X : C) : (iso.refl X).symm = iso.refl X := rfl /-- Composition of two isomorphisms -/ @[trans, simps] def trans (α : X ≅ Y) (β : Y ≅ Z) : X ≅ Z := { hom := α.hom ≫ β.hom, inv := β.inv ≫ α.inv } infixr ` ≪≫ `:80 := iso.trans -- type as `\ll \gg`. @[simp] lemma trans_mk {X Y Z : C} (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id) (hom' : Y ⟶ Z) (inv' : Z ⟶ Y) (hom_inv_id') (inv_hom_id') (hom_inv_id'') (inv_hom_id'') : iso.trans {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} {hom := hom', inv := inv', hom_inv_id' := hom_inv_id', inv_hom_id' := inv_hom_id'} = { hom := hom ≫ hom', inv := inv' ≫ inv, hom_inv_id' := hom_inv_id'', inv_hom_id' := inv_hom_id''} := rfl @[simp] lemma trans_symm (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).symm = β.symm ≪≫ α.symm := rfl @[simp] lemma trans_assoc {Z' : C} (α : X ≅ Y) (β : Y ≅ Z) (γ : Z ≅ Z') : (α ≪≫ β) ≪≫ γ = α ≪≫ β ≪≫ γ := by ext; simp only [trans_hom, category.assoc] @[simp] lemma refl_trans (α : X ≅ Y) : (iso.refl X) ≪≫ α = α := by ext; apply category.id_comp @[simp] lemma trans_refl (α : X ≅ Y) : α ≪≫ (iso.refl Y) = α := by ext; apply category.comp_id @[simp] lemma symm_self_id (α : X ≅ Y) : α.symm ≪≫ α = iso.refl Y := ext α.inv_hom_id @[simp] lemma self_symm_id (α : X ≅ Y) : α ≪≫ α.symm = iso.refl X := ext α.hom_inv_id @[simp] lemma symm_self_id_assoc (α : X ≅ Y) (β : Y ≅ Z) : α.symm ≪≫ α ≪≫ β = β := by rw [← trans_assoc, symm_self_id, refl_trans] @[simp] lemma self_symm_id_assoc (α : X ≅ Y) (β : X ≅ Z) : α ≪≫ α.symm ≪≫ β = β := by rw [← trans_assoc, self_symm_id, refl_trans] lemma inv_comp_eq (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : α.inv ≫ f = g ↔ f = α.hom ≫ g := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_inv_comp (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : g = α.inv ≫ f ↔ α.hom ≫ g = f := (inv_comp_eq α.symm).symm lemma comp_inv_eq (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : f ≫ α.inv = g ↔ f = g ≫ α.hom := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_comp_inv (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : g = f ≫ α.inv ↔ g ≫ α.hom = f := (comp_inv_eq α.symm).symm lemma inv_eq_inv (f g : X ≅ Y) : f.inv = g.inv ↔ f.hom = g.hom := have ∀{X Y : C} (f g : X ≅ Y), f.hom = g.hom → f.inv = g.inv, from λ X Y f g h, by rw [ext h], ⟨this f.symm g.symm, this f g⟩ lemma hom_comp_eq_id (α : X ≅ Y) {f : Y ⟶ X} : α.hom ≫ f = 𝟙 X ↔ f = α.inv := by rw [←eq_inv_comp, comp_id] lemma comp_hom_eq_id (α : X ≅ Y) {f : Y ⟶ X} : f ≫ α.hom = 𝟙 Y ↔ f = α.inv := by rw [←eq_comp_inv, id_comp] lemma hom_eq_inv (α : X ≅ Y) (β : Y ≅ X) : α.hom = β.inv ↔ β.hom = α.inv := by { erw [inv_eq_inv α.symm β, eq_comm], refl } end iso /-- `is_iso` typeclass expressing that a morphism is invertible. -/ class is_iso (f : X ⟶ Y) : Prop := (out : ∃ inv : Y ⟶ X, f ≫ inv = 𝟙 X ∧ inv ≫ f = 𝟙 Y) /-- The inverse of a morphism `f` when we have `[is_iso f]`. -/ noncomputable def inv (f : X ⟶ Y) [I : is_iso f] := classical.some I.1 namespace is_iso @[simp, reassoc] lemma hom_inv_id (f : X ⟶ Y) [I : is_iso f] : f ≫ inv f = 𝟙 X := (classical.some_spec I.1).left @[simp, reassoc] lemma inv_hom_id (f : X ⟶ Y) [I : is_iso f] : inv f ≫ f = 𝟙 Y := (classical.some_spec I.1).right end is_iso open is_iso /-- Reinterpret a morphism `f` with an `is_iso f` instance as an `iso`. -/ noncomputable def as_iso (f : X ⟶ Y) [h : is_iso f] : X ≅ Y := ⟨f, inv f, hom_inv_id f, inv_hom_id f⟩ @[simp] lemma as_iso_hom (f : X ⟶ Y) [is_iso f] : (as_iso f).hom = f := rfl @[simp] lemma as_iso_inv (f : X ⟶ Y) [is_iso f] : (as_iso f).inv = inv f := rfl namespace is_iso @[priority 100] -- see Note [lower instance priority] instance epi_of_iso (f : X ⟶ Y) [is_iso f] : epi f := { left_cancellation := λ Z g h w, -- This is an interesting test case for better rewrite automation. by rw [← is_iso.inv_hom_id_assoc f g, w, is_iso.inv_hom_id_assoc f h] } @[priority 100] -- see Note [lower instance priority] instance mono_of_iso (f : X ⟶ Y) [is_iso f] : mono f := { right_cancellation := λ Z g h w, by rw [← category.comp_id g, ← category.comp_id h, ← is_iso.hom_inv_id f, ← category.assoc, w, ← category.assoc] } @[ext] lemma inv_eq_of_hom_inv_id {f : X ⟶ Y} [is_iso f] {g : Y ⟶ X} (hom_inv_id : f ≫ g = 𝟙 X) : inv f = g := begin apply (cancel_epi f).mp, simp [hom_inv_id], end lemma inv_eq_of_inv_hom_id {f : X ⟶ Y} [is_iso f] {g : Y ⟶ X} (inv_hom_id : g ≫ f = 𝟙 Y) : inv f = g := begin apply (cancel_mono f).mp, simp [inv_hom_id], end @[ext] lemma eq_inv_of_hom_inv_id {f : X ⟶ Y} [is_iso f] {g : Y ⟶ X} (hom_inv_id : f ≫ g = 𝟙 X) : g = inv f := (inv_eq_of_hom_inv_id hom_inv_id).symm lemma eq_inv_of_inv_hom_id {f : X ⟶ Y} [is_iso f] {g : Y ⟶ X} (inv_hom_id : g ≫ f = 𝟙 Y) : g = inv f := (inv_eq_of_inv_hom_id inv_hom_id).symm instance id (X : C) : is_iso (𝟙 X) := ⟨⟨𝟙 X, by simp⟩⟩ instance of_iso (f : X ≅ Y) : is_iso f.hom := ⟨⟨f.inv, by simp⟩⟩ instance of_iso_inv (f : X ≅ Y) : is_iso f.inv := is_iso.of_iso f.symm variables {f g : X ⟶ Y} {h : Y ⟶ Z} instance inv_is_iso [is_iso f] : is_iso (inv f) := is_iso.of_iso_inv (as_iso f) instance comp_is_iso [is_iso f] [is_iso h] : is_iso (f ≫ h) := is_iso.of_iso $ (as_iso f) ≪≫ (as_iso h) @[simp] lemma inv_id : inv (𝟙 X) = 𝟙 X := by { ext, simp, } @[simp] lemma inv_comp [is_iso f] [is_iso h] : inv (f ≫ h) = inv h ≫ inv f := by { ext, simp, } @[simp] lemma inv_inv [is_iso f] : inv (inv f) = f := by { ext, simp, } @[simp] lemma iso.inv_inv (f : X ≅ Y) : inv (f.inv) = f.hom := by { ext, simp, } @[simp] lemma iso.inv_hom (f : X ≅ Y) : inv (f.hom) = f.inv := by { ext, simp, } @[simp] lemma inv_comp_eq (α : X ⟶ Y) [is_iso α] {f : X ⟶ Z} {g : Y ⟶ Z} : inv α ≫ f = g ↔ f = α ≫ g := (as_iso α).inv_comp_eq @[simp] lemma eq_inv_comp (α : X ⟶ Y) [is_iso α] {f : X ⟶ Z} {g : Y ⟶ Z} : g = inv α ≫ f ↔ α ≫ g = f := (as_iso α).eq_inv_comp @[simp] lemma comp_inv_eq (α : X ⟶ Y) [is_iso α] {f : Z ⟶ Y} {g : Z ⟶ X} : f ≫ inv α = g ↔ f = g ≫ α := (as_iso α).comp_inv_eq @[simp] lemma eq_comp_inv (α : X ⟶ Y) [is_iso α] {f : Z ⟶ Y} {g : Z ⟶ X} : g = f ≫ inv α ↔ g ≫ α = f := (as_iso α).eq_comp_inv end is_iso open is_iso lemma eq_of_inv_eq_inv {f g : X ⟶ Y} [is_iso f] [is_iso g] (p : inv f = inv g) : f = g := begin apply (cancel_epi (inv f)).1, erw [inv_hom_id, p, inv_hom_id], end lemma is_iso.inv_eq_inv {f g : X ⟶ Y} [is_iso f] [is_iso g] : inv f = inv g ↔ f = g := iso.inv_eq_inv (as_iso f) (as_iso g) lemma hom_comp_eq_id (g : X ⟶ Y) [is_iso g] {f : Y ⟶ X} : g ≫ f = 𝟙 X ↔ f = inv g := (as_iso g).hom_comp_eq_id lemma comp_hom_eq_id (g : X ⟶ Y) [is_iso g] {f : Y ⟶ X} : f ≫ g = 𝟙 Y ↔ f = inv g := (as_iso g).comp_hom_eq_id namespace iso @[ext] lemma inv_ext {f : X ≅ Y} {g : Y ⟶ X} (hom_inv_id : f.hom ≫ g = 𝟙 X) : f.inv = g := begin apply (cancel_epi f.hom).mp, simp [hom_inv_id], end @[ext] lemma inv_ext' {f : X ≅ Y} {g : Y ⟶ X} (hom_inv_id : f.hom ≫ g = 𝟙 X) : g = f.inv := by { symmetry, ext, assumption, } /-! All these cancellation lemmas can be solved by `simp [cancel_mono]` (or `simp [cancel_epi]`), but with the current design `cancel_mono` is not a good `simp` lemma, because it generates a typeclass search. When we can see syntactically that a morphism is a `mono` or an `epi` because it came from an isomorphism, it's fine to do the cancellation via `simp`. In the longer term, it might be worth exploring making `mono` and `epi` structures, rather than typeclasses, with coercions back to `X ⟶ Y`. Presumably we could write `X ↪ Y` and `X ↠ Y`. -/ @[simp] lemma cancel_iso_hom_left {X Y Z : C} (f : X ≅ Y) (g g' : Y ⟶ Z) : f.hom ≫ g = f.hom ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_iso_inv_left {X Y Z : C} (f : Y ≅ X) (g g' : Y ⟶ Z) : f.inv ≫ g = f.inv ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_iso_hom_right {X Y Z : C} (f f' : X ⟶ Y) (g : Y ≅ Z) : f ≫ g.hom = f' ≫ g.hom ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_iso_inv_right {X Y Z : C} (f f' : X ⟶ Y) (g : Z ≅ Y) : f ≫ g.inv = f' ≫ g.inv ↔ f = f' := by simp only [cancel_mono] /- Unfortunately cancelling an isomorphism from the right of a chain of compositions is awkward. We would need separate lemmas for each chain length (worse: for each pair of chain lengths). We provide two more lemmas, for case of three morphisms, because this actually comes up in practice, but then stop. -/ @[simp] lemma cancel_iso_hom_right_assoc {W X X' Y Z : C} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) (h : Y ≅ Z) : f ≫ g ≫ h.hom = f' ≫ g' ≫ h.hom ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_iso_inv_right_assoc {W X X' Y Z : C} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) (h : Z ≅ Y) : f ≫ g ≫ h.inv = f' ≫ g' ≫ h.inv ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] end iso namespace functor universes u₁ v₁ u₂ v₂ variables {D : Type u₂} variables [category.{v₂} D] /-- A functor `F : C ⥤ D` sends isomorphisms `i : X ≅ Y` to isomorphisms `F.obj X ≅ F.obj Y` -/ @[simps] def map_iso (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.obj X ≅ F.obj Y := { hom := F.map i.hom, inv := F.map i.inv, hom_inv_id' := by rw [←map_comp, iso.hom_inv_id, ←map_id], inv_hom_id' := by rw [←map_comp, iso.inv_hom_id, ←map_id] } @[simp] lemma map_iso_symm (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.map_iso i.symm = (F.map_iso i).symm := rfl @[simp] lemma map_iso_trans (F : C ⥤ D) {X Y Z : C} (i : X ≅ Y) (j : Y ≅ Z) : F.map_iso (i ≪≫ j) = (F.map_iso i) ≪≫ (F.map_iso j) := by ext; apply functor.map_comp @[simp] lemma map_iso_refl (F : C ⥤ D) (X : C) : F.map_iso (iso.refl X) = iso.refl (F.obj X) := iso.ext $ F.map_id X instance map_is_iso (F : C ⥤ D) (f : X ⟶ Y) [is_iso f] : is_iso (F.map f) := is_iso.of_iso $ F.map_iso (as_iso f) @[simp] lemma map_inv (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map (inv f) = inv (F.map f) := by { ext, simp [←F.map_comp], } lemma map_hom_inv (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map f ≫ F.map (inv f) = 𝟙 (F.obj X) := by simp lemma map_inv_hom (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map (inv f) ≫ F.map f = 𝟙 (F.obj Y) := by simp end functor end category_theory
0295af615e4e5641936d5754e3354290eb780479
217bb195841a8be2d1b4edd2084d6b69ccd62f50
/tests/playground/parser/syntax.lean
1e014bf661c9bf26796ef2500f6627c48e5c1814
[ "Apache-2.0" ]
permissive
frank-lesser/lean4
717f56c9bacd5bf3a67542d2f5cea721d4743a30
79e2abe33f73162f773ea731265e456dbfe822f9
refs/heads/master
1,589,741,267,933
1,556,424,200,000
1,556,424,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,625
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich, Leonardo de Moura -/ prelude import init.lean.name init.lean.format init.data.array -- namespace Lean namespace Parser open Lean /-- A hygiene marker introduced by a macro expansion. -/ @[derive DecidableEq HasToFormat] def MacroScope := Nat abbrev MacroScopes := List MacroScope structure SourceInfo := /- Will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ (leading : Substring) (pos : String.Pos) (trailing : Substring) def SourceInfo.updateTrailing : SourceInfo → Substring → SourceInfo | ⟨leading, pos, _⟩ trailing := ⟨leading, pos, trailing⟩ /- Node kind generation -/ def mkUniqIdRef : IO (IO.Ref Nat) := IO.mkRef 0 @[init mkUniqIdRef] constant nextUniqId : IO.Ref Nat := default _ structure SyntaxNodeKind := (name : Name) (id : Nat) instance stxKindInh : Inhabited SyntaxNodeKind := ⟨{name := default _, id := default _}⟩ instance stxKindBeq : HasBeq SyntaxNodeKind := ⟨λ k₁ k₂, k₁.id == k₂.id⟩ def mkNameToKindTable : IO (IO.Ref (NameMap Nat)) := IO.mkRef {} @[init mkNameToKindTable] constant nameToKindTable : IO.Ref (NameMap Nat) := default _ def nextKind (k : Name) : IO SyntaxNodeKind := do m ← nameToKindTable.get, when (m.contains k) (throw $ IO.userError ("kind '" ++ toString k ++ "' already exists")), id ← nextUniqId.get, nameToKindTable.set (m.insert k id), nextUniqId.set (id+1), pure { name := k, id := id } /- Basic node kinds -/ def mkNullKind : IO SyntaxNodeKind := nextKind `null @[init mkNullKind] constant nullKind : SyntaxNodeKind := default _ def mkChoiceKind : IO SyntaxNodeKind := nextKind `choice @[init mkChoiceKind] constant choiceKind : SyntaxNodeKind := default _ def mkOptionSomeKind : IO SyntaxNodeKind := nextKind `some @[init mkOptionSomeKind] constant optionSomeKind : SyntaxNodeKind := default _ def mkOptionNoneKind : IO SyntaxNodeKind := nextKind `none @[init mkOptionNoneKind] constant optionNoneKind : SyntaxNodeKind := default _ def mkManyKind : IO SyntaxNodeKind := nextKind `many @[init mkManyKind] constant manyKind : SyntaxNodeKind := default _ def mkHoleKind : IO SyntaxNodeKind := nextKind `hole /- Syntax AST -/ inductive Syntax | missing | node (kind : SyntaxNodeKind) (args : Array Syntax) (scopes : MacroScopes) | atom (info : Option SourceInfo) (val : String) | ident (info : Option SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List Name) (scopes : MacroScopes) instance stxInh : Inhabited Syntax := ⟨Syntax.missing⟩ def SyntaxNodeKind.fix : SyntaxNodeKind → IO SyntaxNodeKind | {name := n, ..} := do m ← nameToKindTable.get, match m.find n with | some id := pure {name := n, id := id} | none := throw $ IO.userError ("Error unknown Syntax kind '" ++ toString n ++ "'") partial def Syntax.fixKinds : Syntax → IO Syntax | (Syntax.node k args scopes) := do k ← k.fix, args ← args.mmap Syntax.fixKinds, pure (Syntax.node k args scopes) | other := pure other inductive IsNode : Syntax → Prop | mk (kind : SyntaxNodeKind) (args : Array Syntax) (scopes : MacroScopes) : IsNode (Syntax.node kind args scopes) def SyntaxNode : Type := {s : Syntax // IsNode s } def notIsNodeMissing (h : IsNode Syntax.missing) : False := match h with end def notIsNodeAtom {info val} (h : IsNode (Syntax.atom info val)) : False := match h with end def notIsNodeIdent {info rawVal val preresolved scopes} (h : IsNode (Syntax.ident info rawVal val preresolved scopes)) : False := match h with end def unreachIsNodeMissing {α : Type} (h : IsNode Syntax.missing) : α := False.elim (notIsNodeMissing h) def unreachIsNodeAtom {α : Type} {info val} (h : IsNode (Syntax.atom info val)) : α := False.elim (notIsNodeAtom h) def unreachIsNodeIdent {α : Type} {info rawVal val preresolved scopes} (h : IsNode (Syntax.ident info rawVal val preresolved scopes)) : α := False.elim (match h with end) @[inline] def withArgs {α : Type} (n : SyntaxNode) (fn : Array Syntax → α) : α := match n with | ⟨Syntax.node _ args _, _⟩ := fn args | ⟨Syntax.missing, h⟩ := unreachIsNodeMissing h | ⟨Syntax.atom _ _, h⟩ := unreachIsNodeAtom h | ⟨Syntax.ident _ _ _ _ _, h⟩ := unreachIsNodeIdent h @[inline] def updateArgs (n : SyntaxNode) (fn : Array Syntax → Array Syntax) : Syntax := match n with | ⟨Syntax.node kind args scopes, _⟩ := Syntax.node kind (fn args) scopes | ⟨Syntax.missing, h⟩ := unreachIsNodeMissing h | ⟨Syntax.atom _ _, h⟩ := unreachIsNodeAtom h | ⟨Syntax.ident _ _ _ _ _, h⟩ := unreachIsNodeIdent h -- TODO(Sebastian): exhaustively argue why (if?) this is correct -- The basic idea is List concatenation with elimination of adjacent identical scopes def MacroScopes.flip : MacroScopes → MacroScopes → MacroScopes | ys [] := ys | ys (x::xs) := match MacroScopes.flip ys xs with | y::ys := if x == y then ys else x::y::ys | [] := [x] namespace Syntax def isIdent : Syntax → Bool | (Syntax.ident _ _ _ _ _) := true | _ := false def isOfKind : Syntax → SyntaxNodeKind → Bool | (Syntax.node kind _ _) k := k == kind | other _ := false def flipScopes (scopes : MacroScopes) : Syntax → Syntax | (Syntax.ident info rawVal val pre scopes) := Syntax.ident info rawVal val pre (scopes.flip scopes) | (Syntax.node kind args scopes) := Syntax.node kind args (scopes.flip scopes) | other := other @[inline] def toSyntaxNode {α : Type} (s : Syntax) (base : α) (fn : SyntaxNode → α) : α := match s with | Syntax.node kind args [] := fn ⟨Syntax.node kind args [], IsNode.mk _ _ _⟩ | Syntax.node kind args scopes := fn ⟨Syntax.node kind (args.hmap (flipScopes scopes)) [], IsNode.mk _ _ _⟩ | other := base local attribute [instance] monadInhabited @[specialize] partial def mreplace {m : Type → Type} [Monad m] (fn : Syntax → m (Option Syntax)) : Syntax → m Syntax | stx@(node kind args scopes) := do o ← fn stx, (match o with | some stx := pure stx | none := do args ← args.mmap mreplace, pure (node kind args scopes)) | stx := do o ← fn stx, pure (o.getOrElse stx) @[inline] def replace {m : Type → Type} [Monad m] (fn : Syntax → m (Option Syntax)) := @mreplace Id _ private def updateInfo : SourceInfo → String.Pos → SourceInfo | {leading := {str := s, startPos := _, stopPos := _}, pos := pos, trailing := trailing} last := {leading := {str := s, startPos := last, stopPos := pos}, pos := pos, trailing := trailing} /- Remark: the State `String.Pos` is the `SourceInfo.trailing.endPos` of the previous token, or the beginning of the String. -/ @[inline] private def updateLeadingAux : Syntax → State String.Pos (Option Syntax) | (atom (some info) val) := do last ← get, set info.trailing.stopPos, let newInfo := updateInfo info last in pure $ some (atom (some newInfo) val) | (ident (some info) rawVal val pre scopes) := do last ← get, set info.trailing.stopPos, let newInfo := updateInfo info last in pure $ some (ident (some newInfo) rawVal val pre scopes) | _ := pure none /-- Set `SourceInfo.leading` according to the trailing stop of the preceding token. The Result is a round-tripping Syntax tree IF, in the input Syntax tree, * all leading stops, atom contents, and trailing starts are correct * trailing stops are between the trailing start and the next leading stop. Remark: after parsing all `SourceInfo.leading` fields are Empty. The Syntax argument is the output produced by the Parser for `source`. This Function "fixes" the `source.leanding` field. Note that, the `SourceInfo.trailing` fields are correct. The implementation of this Function relies on this property. -/ def updateLeading : Syntax → Syntax := λ stx, Prod.fst <$> (mreplace updateLeadingAux stx).run 0 partial def updateTrailing (trailing : Substring) : Syntax → Syntax | (Syntax.atom (some info) val) := Syntax.atom (some (info.updateTrailing trailing)) val | (Syntax.ident (some info) rawVal val pre scopes) := Syntax.ident (some (info.updateTrailing trailing)) rawVal val pre scopes | n@(Syntax.node k args scopes) := if args.size == 0 then n else let i := args.size - 1 in let last := updateTrailing (args.get i) in let args := args.set i last in Syntax.node k args scopes | other := other /-- Retrieve the left-most leaf's info in the Syntax tree. -/ partial def getHeadInfo : Syntax → Option SourceInfo | (atom info _) := info | (ident info _ _ _ _ ) := info | (node _ args _) := args.find getHeadInfo | _ := none def getPos (stx : Syntax) : Option String.Pos := SourceInfo.pos <$> stx.getHeadInfo private def reprintLeaf : Option SourceInfo → String → String | none val := val | (some info) val := info.leading.toString ++ val ++ info.trailing.toString partial def reprint : Syntax → Option String | (atom info val) := reprintLeaf info val | (ident info rawVal _ _ _) := reprintLeaf info rawVal.toString | (node kind args _) := if kind == choiceKind then if args.size == 0 then failure else do s ← reprint (args.get 0), args.mfoldlFrom s (λ stx s, do s' ← reprint stx, guard (s == s'), pure s) 1 else args.mfoldl "" (λ stx r, do s ← reprint stx, pure $ r ++ s) | missing := "" open Lean.Format protected partial def toFormat : Syntax → Format | (atom info val) := toFmt $ repr val | (ident _ _ val pre scopes) := let scopes := pre.map toFmt ++ scopes.reverse.map toFmt in let scopes := match scopes with [] := toFmt "" | _ := bracket "{" (joinSep scopes ", ") "}" in toFmt "`" ++ toFmt val ++ scopes | (node kind args scopes) := let scopes := match scopes with [] := toFmt "" | _ := bracket "{" (joinSep scopes.reverse ", ") "}" in if kind.name = `Lean.Parser.noKind then sbracket $ scopes ++ joinSep (args.toList.map toFormat) line else let shorterName := kind.name.replacePrefix `Lean.Parser Name.anonymous in paren $ joinSep ((toFmt shorterName ++ scopes) :: args.toList.map toFormat) line | missing := "<missing>" instance : HasToFormat Syntax := ⟨Syntax.toFormat⟩ instance : HasToString Syntax := ⟨toString ∘ toFmt⟩ end Syntax end Parser -- end Lean
a94d04e6b1f9b7572d5a6ffe11c186a0d934309f
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Meta/Tactic/Util.lean
d7cdc693807713960f7eb57e5105980a7e1aba6f
[ "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,328
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.ForEachExpr import Lean.Meta.Basic import Lean.Meta.AppBuilder import Lean.Meta.PPGoal namespace Lean.Meta /-- Get the user name of the given metavariable. -/ def _root_.Lean.MVarId.getTag (mvarId : MVarId) : MetaM Name := return (← mvarId.getDecl).userName @[deprecated MVarId.getTag] def getMVarTag (mvarId : MVarId) : MetaM Name := mvarId.getTag def _root_.Lean.MVarId.setTag (mvarId : MVarId) (tag : Name) : MetaM Unit := do modify fun s => { s with mctx := s.mctx.setMVarUserName mvarId tag } @[deprecated MVarId.setTag] def setMVarTag (mvarId : MVarId) (tag : Name) : MetaM Unit := do mvarId.setTag tag def appendTag (tag : Name) (suffix : Name) : Name := tag.modifyBase (· ++ suffix.eraseMacroScopes) def appendTagSuffix (mvarId : MVarId) (suffix : Name) : MetaM Unit := do let tag ← mvarId.getTag mvarId.setTag (appendTag tag suffix) def mkFreshExprSyntheticOpaqueMVar (type : Expr) (tag : Name := Name.anonymous) : MetaM Expr := mkFreshExprMVar type MetavarKind.syntheticOpaque tag def throwTacticEx (tacticName : Name) (mvarId : MVarId) (msg : MessageData) : MetaM α := withPPForTacticGoal do if msg.isEmpty then throwError "tactic '{tacticName}' failed\n{mvarId}" else throwError "tactic '{tacticName}' failed, {msg}\n{mvarId}" def throwNestedTacticEx {α} (tacticName : Name) (ex : Exception) : MetaM α := do throwError "tactic '{tacticName}' failed, nested error:\n{ex.toMessageData}" /-- Throw a tactic exception with given tactic name if the given metavariable is assigned. -/ def _root_.Lean.MVarId.checkNotAssigned (mvarId : MVarId) (tacticName : Name) : MetaM Unit := do if (← mvarId.isAssigned) then throwTacticEx tacticName mvarId "metavariable has already been assigned" @[deprecated MVarId.checkNotAssigned] def checkNotAssigned (mvarId : MVarId) (tacticName : Name) : MetaM Unit := do mvarId.checkNotAssigned tacticName /-- Get the type the given metavariable. -/ def _root_.Lean.MVarId.getType (mvarId : MVarId) : MetaM Expr := return (← mvarId.getDecl).type @[deprecated MVarId.getType] def getMVarType (mvarId : MVarId) : MetaM Expr := mvarId.getType /-- Get the type the given metavariable after instantiating metavariables and reducing to weak head normal form. -/ def _root_.Lean.MVarId.getType' (mvarId : MVarId) : MetaM Expr := do whnf (← instantiateMVars (← mvarId.getType)) @[deprecated MVarId.getType'] def getMVarType' (mvarId : MVarId) : MetaM Expr := do mvarId.getType' builtin_initialize registerTraceClass `Meta.Tactic /-- Assign `mvarId` to `sorryAx` -/ def _root_.Lean.MVarId.admit (mvarId : MVarId) (synthetic := true) : MetaM Unit := mvarId.withContext do mvarId.checkNotAssigned `admit let mvarType ← mvarId.getType let val ← mkSorry mvarType synthetic mvarId.assign val @[deprecated MVarId.admit] def admit (mvarId : MVarId) (synthetic := true) : MetaM Unit := mvarId.admit synthetic /-- Beta reduce the metavariable type head -/ def _root_.Lean.MVarId.headBetaType (mvarId : MVarId) : MetaM Unit := do mvarId.setType (← mvarId.getType).headBeta @[deprecated MVarId.headBetaType] def headBetaMVarType (mvarId : MVarId) : MetaM Unit := do mvarId.headBetaType /-- Collect nondependent hypotheses that are propositions. -/ def _root_.Lean.MVarId.getNondepPropHyps (mvarId : MVarId) : MetaM (Array FVarId) := let removeDeps (e : Expr) (candidates : FVarIdHashSet) : MetaM FVarIdHashSet := do let e ← instantiateMVars e let visit : StateRefT FVarIdHashSet MetaM FVarIdHashSet := do e.forEach fun | Expr.fvar fvarId => modify fun s => s.erase fvarId | _ => pure () get visit |>.run' candidates mvarId.withContext do let mut candidates : FVarIdHashSet := {} for localDecl in (← getLCtx) do unless localDecl.isAuxDecl do candidates ← removeDeps localDecl.type candidates match localDecl.value? with | none => pure () | some value => candidates ← removeDeps value candidates if (← isProp localDecl.type) && !localDecl.hasValue then candidates := candidates.insert localDecl.fvarId candidates ← removeDeps (← mvarId.getType) candidates if candidates.isEmpty then return #[] else let mut result := #[] for localDecl in (← getLCtx) do if candidates.contains localDecl.fvarId then result := result.push localDecl.fvarId return result @[deprecated MVarId.getNondepPropHyps] def getNondepPropHyps (mvarId : MVarId) : MetaM (Array FVarId) := mvarId.getNondepPropHyps partial def saturate (mvarId : MVarId) (x : MVarId → MetaM (Option (List MVarId))) : MetaM (List MVarId) := do let (_, r) ← go mvarId |>.run #[] return r.toList where go (mvarId : MVarId) : StateRefT (Array MVarId) MetaM Unit := withIncRecDepth do match (← x mvarId) with | none => modify fun s => s.push mvarId | some mvarIds => mvarIds.forM go def exactlyOne (mvarIds : List MVarId) (msg : MessageData := "unexpected number of goals") : MetaM MVarId := match mvarIds with | [mvarId] => return mvarId | _ => throwError msg def ensureAtMostOne (mvarIds : List MVarId) (msg : MessageData := "unexpected number of goals") : MetaM (Option MVarId) := match mvarIds with | [] => return none | [mvarId] => return some mvarId | _ => throwError msg /-- Return all propositions in the local context. -/ def getPropHyps : MetaM (Array FVarId) := do let mut result := #[] for localDecl in (← getLCtx) do unless localDecl.isAuxDecl do if (← isProp localDecl.type) then result := result.push localDecl.fvarId return result def _root_.Lean.MVarId.inferInstance (mvarId : MVarId) : MetaM Unit := mvarId.withContext do mvarId.checkNotAssigned `infer_instance let synthVal ← synthInstance (← mvarId.getType) unless (← isDefEq (mkMVar mvarId) synthVal) do throwTacticEx `infer_instance mvarId "`infer_instance` tactic failed to assign instance" inductive TacticResultCNM where | closed | noChange | modified (mvarId : MVarId) end Lean.Meta
d70228a107e11ce7597ebfa854d7f0abcc0d5083
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/init/reserved_notation.lean
55cad3d402002f1456ff1a623866b27e1fd61bc6
[ "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
7,421
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn -/ prelude import init.datatypes notation `assume` binders `,` r:(scoped f, f) := r notation `take` binders `,` r:(scoped f, f) := r structure has_zero [class] (A : Type) := (zero : A) structure has_one [class] (A : Type) := (one : A) structure has_add [class] (A : Type) := (add : A → A → A) structure has_mul [class] (A : Type) := (mul : A → A → A) structure has_inv [class] (A : Type) := (inv : A → A) structure has_neg [class] (A : Type) := (neg : A → A) structure has_sub [class] (A : Type) := (sub : A → A → A) structure has_div [class] (A : Type) := (div : A → A → A) structure has_dvd [class] (A : Type) := (dvd : A → A → Prop) structure has_mod [class] (A : Type) := (mod : A → A → A) structure has_le [class] (A : Type) := (le : A → A → Prop) structure has_lt [class] (A : Type) := (lt : A → A → Prop) definition zero {A : Type} [s : has_zero A] : A := has_zero.zero A definition one {A : Type} [s : has_one A] : A := has_one.one A definition add {A : Type} [s : has_add A] : A → A → A := has_add.add definition mul {A : Type} [s : has_mul A] : A → A → A := has_mul.mul definition sub {A : Type} [s : has_sub A] : A → A → A := has_sub.sub definition div {A : Type} [s : has_div A] : A → A → A := has_div.div definition dvd {A : Type} [s : has_dvd A] : A → A → Prop := has_dvd.dvd definition mod {A : Type} [s : has_mod A] : A → A → A := has_mod.mod definition neg {A : Type} [s : has_neg A] : A → A := has_neg.neg definition inv {A : Type} [s : has_inv A] : A → A := has_inv.inv definition le {A : Type} [s : has_le A] : A → A → Prop := has_le.le definition lt {A : Type} [s : has_lt A] : A → A → Prop := has_lt.lt definition ge [reducible] {A : Type} [s : has_le A] (a b : A) : Prop := le b a definition gt [reducible] {A : Type} [s : has_lt A] (a b : A) : Prop := lt b a definition bit0 {A : Type} [s : has_add A] (a : A) : A := add a a definition bit1 {A : Type} [s₁ : has_one A] [s₂ : has_add A] (a : A) : A := add (bit0 a) one definition num_has_zero [instance] : has_zero num := has_zero.mk num.zero definition num_has_one [instance] : has_one num := has_one.mk (num.pos pos_num.one) definition pos_num_has_one [instance] : has_one pos_num := has_one.mk (pos_num.one) namespace pos_num open bool definition is_one (a : pos_num) : bool := pos_num.rec_on a tt (λn r, ff) (λn r, ff) definition pred (a : pos_num) : pos_num := pos_num.rec_on a one (λn r, bit0 n) (λn r, bool.rec_on (is_one n) (bit1 r) one) definition size (a : pos_num) : pos_num := pos_num.rec_on a one (λn r, succ r) (λn r, succ r) definition add (a b : pos_num) : pos_num := pos_num.rec_on a succ (λn f b, pos_num.rec_on b (succ (bit1 n)) (λm r, succ (bit1 (f m))) (λm r, bit1 (f m))) (λn f b, pos_num.rec_on b (bit1 n) (λm r, bit1 (f m)) (λm r, bit0 (f m))) b end pos_num definition pos_num_has_add [instance] : has_add pos_num := has_add.mk pos_num.add namespace num open pos_num definition add (a b : num) : num := num.rec_on a b (λpa, num.rec_on b (pos pa) (λpb, pos (pos_num.add pa pb))) end num definition num_has_add [instance] : has_add num := has_add.mk num.add definition std.priority.default : num := 1000 definition std.priority.max : num := 4294967295 namespace nat protected definition prio := num.add std.priority.default 100 protected definition add (a b : nat) : nat := nat.rec a (λ b₁ r, succ r) b definition of_num (n : num) : nat := num.rec zero (λ n, pos_num.rec (succ zero) (λ n r, nat.add (nat.add r r) (succ zero)) (λ n r, nat.add r r) n) n end nat attribute pos_num_has_add pos_num_has_one num_has_zero num_has_one num_has_add [instance] [priority nat.prio] definition nat_has_zero [instance] [priority nat.prio] : has_zero nat := has_zero.mk nat.zero definition nat_has_one [instance] [priority nat.prio] : has_one nat := has_one.mk (nat.succ (nat.zero)) definition nat_has_add [instance] [priority nat.prio] : has_add nat := has_add.mk nat.add /- Global declarations of right binding strength If a module reassigns these, it will be incompatible with other modules that adhere to these conventions. When hovering over a symbol, use "C-c C-k" to see how to input it. -/ definition std.prec.max : num := 1024 -- the strength of application, identifiers, (, [, etc. definition std.prec.arrow : num := 25 /- The next definition is "max + 10". It can be used e.g. for postfix operations that should be stronger than application. -/ definition std.prec.max_plus := num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ std.prec.max))))))))) /- Logical operations and relations -/ reserve prefix `¬`:40 reserve prefix `~`:40 reserve infixr ` ∧ `:35 reserve infixr ` /\ `:35 reserve infixr ` \/ `:30 reserve infixr ` ∨ `:30 reserve infix ` <-> `:20 reserve infix ` ↔ `:20 reserve infix ` = `:50 reserve infix ` ≠ `:50 reserve infix ` ≈ `:50 reserve infix ` ~ `:50 reserve infix ` ≡ `:50 reserve infixr ` ∘ `:60 -- input with \comp reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv reserve infixl ` ⬝ `:75 reserve infixr ` ▸ `:75 reserve infixr ` ▹ `:75 /- types and type constructors -/ reserve infixl ` ⊎ `:25 reserve infixl ` × `:30 /- arithmetic operations -/ reserve infixl ` + `:65 reserve infixl ` - `:65 reserve infixl ` * `:70 reserve infixl ` / `:70 reserve infixl ` % `:70 reserve prefix `-`:100 reserve infix ` ^ `:80 reserve infix ` <= `:50 reserve infix ` ≤ `:50 reserve infix ` < `:50 reserve infix ` >= `:50 reserve infix ` ≥ `:50 reserve infix ` > `:50 /- boolean operations -/ reserve infixl ` && `:70 reserve infixl ` || `:65 /- set operations -/ reserve infix ` ∈ `:50 reserve infix ` ∉ `:50 reserve infixl ` ∩ `:70 reserve infixl ` ∪ `:65 reserve infix ` ⊆ `:50 reserve infix ` ⊇ `:50 reserve infix ` ' `:75 -- for the image of a set under a function reserve infix ` '- `:75 -- for the preimage of a set under a function /- other symbols -/ reserve infix ` ∣ `:50 reserve infixl ` ++ `:65 reserve infixr ` :: `:67 infix + := add infix * := mul infix - := sub infix / := div infix ∣ := dvd infix % := mod prefix - := neg postfix ⁻¹ := inv infix ≤ := le infix ≥ := ge infix < := lt infix > := gt notation [parsing_only] x ` +[`:65 A:0 `] `:0 y:65 := @add A _ x y notation [parsing_only] x ` -[`:65 A:0 `] `:0 y:65 := @sub A _ x y notation [parsing_only] x ` *[`:70 A:0 `] `:0 y:70 := @mul A _ x y notation [parsing_only] x ` /[`:70 A:0 `] `:0 y:70 := @div A _ x y notation [parsing_only] x ` ∣[`:70 A:0 `] `:0 y:70 := @dvd A _ x y notation [parsing_only] x ` %[`:70 A:0 `] `:0 y:70 := @mod A _ x y notation [parsing_only] x ` ≤[`:50 A:0 `] `:0 y:50 := @le A _ x y notation [parsing_only] x ` ≥[`:50 A:0 `] `:0 y:50 := @ge A _ x y notation [parsing_only] x ` <[`:50 A:0 `] `:0 y:50 := @lt A _ x y notation [parsing_only] x ` >[`:50 A:0 `] `:0 y:50 := @gt A _ x y
014bf410eec7a01229000c201e4305eafdb06a6e
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Lean/Compiler/IR/Basic.lean
6b34ef8551987975a5dd35b329200bdfc2e65525
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,708
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.KVMap import Lean.Data.Name import Lean.Data.Format import Lean.Compiler.ExternAttr /- Implements (extended) λPure and λRc proposed in the article "Counting Immutable Beans", Sebastian Ullrich and Leonardo de Moura. The Lean to IR transformation produces λPure code, and this part is implemented in C++. The procedures described in the paper above are implemented in Lean. -/ namespace Lean namespace IR /- Function identifier -/ abbrev FunId := Name abbrev Index := Nat /- Variable identifier -/ structure VarId := (idx : Index) /- Join point identifier -/ structure JoinPointId := (idx : Index) abbrev Index.lt (a b : Index) : Bool := a < b namespace VarId instance : HasBeq VarId := ⟨fun a b => a.idx == b.idx⟩ instance : HasToString VarId := ⟨fun a => "x_" ++ toString a.idx⟩ instance : HasFormat VarId := ⟨fun a => toString a⟩ instance : Hashable VarId := ⟨fun a => hash a.idx⟩ end VarId namespace JoinPointId instance : HasBeq JoinPointId := ⟨fun a b => a.idx == b.idx⟩ instance : HasToString JoinPointId := ⟨fun a => "block_" ++ toString a.idx⟩ instance : HasFormat JoinPointId := ⟨fun a => toString a⟩ instance : Hashable JoinPointId := ⟨fun a => hash a.idx⟩ end JoinPointId abbrev MData := KVMap namespace MData abbrev empty : MData := { : KVMap } instance : HasEmptyc MData := ⟨empty⟩ end MData /- Low Level IR types. Most are self explanatory. - `usize` represents the C++ `size_t` Type. We have it here because it is 32-bit in 32-bit machines, and 64-bit in 64-bit machines, and we want the C++ backend for our Compiler to generate platform independent code. - `irrelevant` for Lean types, propositions and proofs. - `object` a pointer to a value in the heap. - `tobject` a pointer to a value in the heap or tagged pointer (i.e., the least significant bit is 1) storing a scalar value. - `struct` and `union` are used to return small values (e.g., `Option`, `Prod`, `Except`) on the stack. Remark: the RC operations for `tobject` are slightly more expensive because we first need to test whether the `tobject` is really a pointer or not. Remark: the Lean runtime assumes that sizeof(void*) == sizeof(sizeT). Lean cannot be compiled on old platforms where this is not True. Since values of type `struct` and `union` are only used to return values, We assume they must be used/consumed "linearly". We use the term "linear" here to mean "exactly once" in each execution. That is, given `x : S`, where `S` is a struct, then one of the following must hold in each (execution) branch. 1- `x` occurs only at a single `ret x` instruction. That is, it is being consumed by being returned. 2- `x` occurs only at a single `ctor`. That is, it is being "consumed" by being stored into another `struct/union`. 3- We extract (aka project) every single field of `x` exactly once. That is, we are consuming `x` by consuming each of one of its components. Minor refinement: we don't need to consume scalar fields or struct/union fields that do not contain object fields. -/ inductive IRType | float | uint8 | uint16 | uint32 | uint64 | usize | irrelevant | object | tobject | struct (leanTypeName : Option Name) (types : Array IRType) : IRType | union (leanTypeName : Name) (types : Array IRType) : IRType namespace IRType partial def beq : IRType → IRType → Bool | float, float => true | uint8, uint8 => true | uint16, uint16 => true | uint32, uint32 => true | uint64, uint64 => true | usize, usize => true | irrelevant, irrelevant => true | object, object => true | tobject, tobject => true | struct n₁ tys₁, struct n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq | union n₁ tys₁, union n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq | _, _ => false instance HasBeq : HasBeq IRType := ⟨beq⟩ def isScalar : IRType → Bool | float => true | uint8 => true | uint16 => true | uint32 => true | uint64 => true | usize => true | _ => false def isObj : IRType → Bool | object => true | tobject => true | _ => false def isIrrelevant : IRType → Bool | irrelevant => true | _ => false def isStruct : IRType → Bool | struct _ _ => true | _ => false def isUnion : IRType → Bool | union _ _ => true | _ => false end IRType /- Arguments to applications, constructors, etc. We use `irrelevant` for Lean types, propositions and proofs that have been erased. Recall that for a Function `f`, we also generate `f._rarg` which does not take `irrelevant` arguments. However, `f._rarg` is only safe to be used in full applications. -/ inductive Arg | var (id : VarId) | irrelevant namespace Arg protected def beq : Arg → Arg → Bool | var x, var y => x == y | irrelevant, irrelevant => true | _, _ => false instance : HasBeq Arg := ⟨Arg.beq⟩ instance : Inhabited Arg := ⟨irrelevant⟩ end Arg @[export lean_ir_mk_var_arg] def mkVarArg (id : VarId) : Arg := Arg.var id inductive LitVal | num (v : Nat) | str (v : String) def LitVal.beq : LitVal → LitVal → Bool | LitVal.num v₁, LitVal.num v₂ => v₁ == v₂ | LitVal.str v₁, LitVal.str v₂ => v₁ == v₂ | _, _ => false instance LitVal.HasBeq : HasBeq LitVal := ⟨LitVal.beq⟩ /- Constructor information. - `name` is the Name of the Constructor in Lean. - `cidx` is the Constructor index (aka tag). - `size` is the number of arguments of type `object/tobject`. - `usize` is the number of arguments of type `usize`. - `ssize` is the number of bytes used to store scalar values. Recall that a Constructor object contains a header, then a sequence of pointers to other Lean objects, a sequence of `USize` (i.e., `size_t`) scalar values, and a sequence of other scalar values. -/ structure CtorInfo := (name : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) def CtorInfo.beq : CtorInfo → CtorInfo → Bool | ⟨n₁, cidx₁, size₁, usize₁, ssize₁⟩, ⟨n₂, cidx₂, size₂, usize₂, ssize₂⟩ => n₁ == n₂ && cidx₁ == cidx₂ && size₁ == size₂ && usize₁ == usize₂ && ssize₁ == ssize₂ instance CtorInfo.HasBeq : HasBeq CtorInfo := ⟨CtorInfo.beq⟩ def CtorInfo.isRef (info : CtorInfo) : Bool := info.size > 0 || info.usize > 0 || info.ssize > 0 def CtorInfo.isScalar (info : CtorInfo) : Bool := !info.isRef inductive Expr /- We use `ctor` mainly for constructing Lean object/tobject values `lean_ctor_object` in the runtime. This instruction is also used to creat `struct` and `union` return values. For `union`, only `i.cidx` is relevant. For `struct`, `i` is irrelevant. -/ | ctor (i : CtorInfo) (ys : Array Arg) | reset (n : Nat) (x : VarId) /- `reuse x in ctor_i ys` instruction in the paper. -/ | reuse (x : VarId) (i : CtorInfo) (updtHeader : Bool) (ys : Array Arg) /- Extract the `tobject` value at Position `sizeof(void*)*i` from `x`. We also use `proj` for extracting fields from `struct` return values, and casting `union` return values. -/ | proj (i : Nat) (x : VarId) /- Extract the `Usize` value at Position `sizeof(void*)*i` from `x`. -/ | uproj (i : Nat) (x : VarId) /- Extract the scalar value at Position `sizeof(void*)*n + offset` from `x`. -/ | sproj (n : Nat) (offset : Nat) (x : VarId) /- Full application. -/ | fap (c : FunId) (ys : Array Arg) /- Partial application that creates a `pap` value (aka closure in our nonstandard terminology). -/ | pap (c : FunId) (ys : Array Arg) /- Application. `x` must be a `pap` value. -/ | ap (x : VarId) (ys : Array Arg) /- Given `x : ty` where `ty` is a scalar type, this operation returns a value of Type `tobject`. For small scalar values, the Result is a tagged pointer, and no memory allocation is performed. -/ | box (ty : IRType) (x : VarId) /- Given `x : [t]object`, obtain the scalar value. -/ | unbox (x : VarId) | lit (v : LitVal) /- Return `1 : uint8` Iff `RC(x) > 1` -/ | isShared (x : VarId) /- Return `1 : uint8` Iff `x : tobject` is a tagged pointer (storing a scalar value). -/ | isTaggedPtr (x : VarId) @[export lean_ir_mk_ctor_expr] def mkCtorExpr (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (ys : Array Arg) : Expr := Expr.ctor ⟨n, cidx, size, usize, ssize⟩ ys @[export lean_ir_mk_proj_expr] def mkProjExpr (i : Nat) (x : VarId) : Expr := Expr.proj i x @[export lean_ir_mk_uproj_expr] def mkUProjExpr (i : Nat) (x : VarId) : Expr := Expr.uproj i x @[export lean_ir_mk_sproj_expr] def mkSProjExpr (n : Nat) (offset : Nat) (x : VarId) : Expr := Expr.sproj n offset x @[export lean_ir_mk_fapp_expr] def mkFAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.fap c ys @[export lean_ir_mk_papp_expr] def mkPAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.pap c ys @[export lean_ir_mk_app_expr] def mkAppExpr (x : VarId) (ys : Array Arg) : Expr := Expr.ap x ys @[export lean_ir_mk_num_expr] def mkNumExpr (v : Nat) : Expr := Expr.lit (LitVal.num v) @[export lean_ir_mk_str_expr] def mkStrExpr (v : String) : Expr := Expr.lit (LitVal.str v) structure Param := (x : VarId) (borrow : Bool) (ty : IRType) instance paramInh : Inhabited Param := ⟨{ x := { idx := 0 }, borrow := false, ty := IRType.object }⟩ @[export lean_ir_mk_param] def mkParam (x : VarId) (borrow : Bool) (ty : IRType) : Param := ⟨x, borrow, ty⟩ inductive AltCore (FnBody : Type) : Type | ctor (info : CtorInfo) (b : FnBody) : AltCore | default (b : FnBody) : AltCore inductive FnBody /- `let x : ty := e; b` -/ | vdecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) /- Join point Declaration `block_j (xs) := e; b` -/ | jdecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) /- Store `y` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. This operation is not part of λPure is only used during optimization. -/ | set (x : VarId) (i : Nat) (y : Arg) (b : FnBody) | setTag (x : VarId) (cidx : Nat) (b : FnBody) /- Store `y : Usize` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. -/ | uset (x : VarId) (i : Nat) (y : VarId) (b : FnBody) /- Store `y : ty` at Position `sizeof(void*)*i + offset` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. `ty` must not be `object`, `tobject`, `irrelevant` nor `Usize`. -/ | sset (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) /- RC increment for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not. If `persistent == true` then `x` is statically known to be a persistent object. -/ | inc (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody) /- RC decrement for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not. If `persistent == true` then `x` is statically known to be a persistent object. -/ | dec (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody) | del (x : VarId) (b : FnBody) | mdata (d : MData) (b : FnBody) | case (tid : Name) (x : VarId) (xType : IRType) (cs : Array (AltCore FnBody)) | ret (x : Arg) /- Jump to join point `j` -/ | jmp (j : JoinPointId) (ys : Array Arg) | unreachable instance : Inhabited FnBody := ⟨FnBody.unreachable⟩ abbrev FnBody.nil := FnBody.unreachable @[export lean_ir_mk_vdecl] def mkVDecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : FnBody := FnBody.vdecl x ty e b @[export lean_ir_mk_jdecl] def mkJDecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) : FnBody := FnBody.jdecl j xs v b @[export lean_ir_mk_uset] def mkUSet (x : VarId) (i : Nat) (y : VarId) (b : FnBody) : FnBody := FnBody.uset x i y b @[export lean_ir_mk_sset] def mkSSet (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) : FnBody := FnBody.sset x i offset y ty b @[export lean_ir_mk_case] def mkCase (tid : Name) (x : VarId) (cs : Array (AltCore FnBody)) : FnBody := -- Tyhe field `xType` is set by `explicitBoxing` compiler pass. FnBody.case tid x IRType.object cs @[export lean_ir_mk_ret] def mkRet (x : Arg) : FnBody := FnBody.ret x @[export lean_ir_mk_jmp] def mkJmp (j : JoinPointId) (ys : Array Arg) : FnBody := FnBody.jmp j ys @[export lean_ir_mk_unreachable] def mkUnreachable : Unit → FnBody := fun _ => FnBody.unreachable abbrev Alt := AltCore FnBody @[matchPattern] abbrev Alt.ctor := @AltCore.ctor FnBody @[matchPattern] abbrev Alt.default := @AltCore.default FnBody instance altInh : Inhabited Alt := ⟨Alt.default (arbitrary _)⟩ def FnBody.isTerminal : FnBody → Bool | FnBody.case _ _ _ _ => true | FnBody.ret _ => true | FnBody.jmp _ _ => true | FnBody.unreachable => true | _ => false def FnBody.body : FnBody → FnBody | FnBody.vdecl _ _ _ b => b | FnBody.jdecl _ _ _ b => b | FnBody.set _ _ _ b => b | FnBody.uset _ _ _ b => b | FnBody.sset _ _ _ _ _ b => b | FnBody.setTag _ _ b => b | FnBody.inc _ _ _ _ b => b | FnBody.dec _ _ _ _ b => b | FnBody.del _ b => b | FnBody.mdata _ b => b | other => other def FnBody.setBody : FnBody → FnBody → FnBody | FnBody.vdecl x t v _, b => FnBody.vdecl x t v b | FnBody.jdecl j xs v _, b => FnBody.jdecl j xs v b | FnBody.set x i y _, b => FnBody.set x i y b | FnBody.uset x i y _, b => FnBody.uset x i y b | FnBody.sset x i o y t _, b => FnBody.sset x i o y t b | FnBody.setTag x i _, b => FnBody.setTag x i b | FnBody.inc x n c p _, b => FnBody.inc x n c p b | FnBody.dec x n c p _, b => FnBody.dec x n c p b | FnBody.del x _, b => FnBody.del x b | FnBody.mdata d _, b => FnBody.mdata d b | other, b => other @[inline] def FnBody.resetBody (b : FnBody) : FnBody := b.setBody FnBody.nil /- If b is a non terminal, then return a pair `(c, b')` s.t. `b == c <;> b'`, and c.body == FnBody.nil -/ @[inline] def FnBody.split (b : FnBody) : FnBody × FnBody := let b' := b.body; let c := b.resetBody; (c, b') def AltCore.body : Alt → FnBody | Alt.ctor _ b => b | Alt.default b => b def AltCore.setBody : Alt → FnBody → Alt | Alt.ctor c _, b => Alt.ctor c b | Alt.default _, b => Alt.default b @[inline] def AltCore.modifyBody (f : FnBody → FnBody) : AltCore FnBody → Alt | Alt.ctor c b => Alt.ctor c (f b) | Alt.default b => Alt.default (f b) @[inline] def AltCore.mmodifyBody {m : Type → Type} [Monad m] (f : FnBody → m FnBody) : AltCore FnBody → m Alt | Alt.ctor c b => Alt.ctor c <$> f b | Alt.default b => Alt.default <$> f b def Alt.isDefault : Alt → Bool | Alt.ctor _ _ => false | Alt.default _ => true def push (bs : Array FnBody) (b : FnBody) : Array FnBody := let b := b.resetBody; bs.push b partial def flattenAux : FnBody → Array FnBody → (Array FnBody) × FnBody | b, r => if b.isTerminal then (r, b) else flattenAux b.body (push r b) def FnBody.flatten (b : FnBody) : (Array FnBody) × FnBody := flattenAux b #[] partial def reshapeAux : Array FnBody → Nat → FnBody → FnBody | a, i, b => if i == 0 then b else let i := i - 1; let (curr, a) := a.swapAt! i (arbitrary _); let b := curr.setBody b; reshapeAux a i b def reshape (bs : Array FnBody) (term : FnBody) : FnBody := reshapeAux bs bs.size term @[inline] def modifyJPs (bs : Array FnBody) (f : FnBody → FnBody) : Array FnBody := bs.map $ fun b => match b with | FnBody.jdecl j xs v k => FnBody.jdecl j xs (f v) k | other => other @[inline] def mmodifyJPs {m : Type → Type} [Monad m] (bs : Array FnBody) (f : FnBody → m FnBody) : m (Array FnBody) := bs.mapM $ fun b => match b with | FnBody.jdecl j xs v k => do v ← f v; pure $ FnBody.jdecl j xs v k | other => pure other @[export lean_ir_mk_alt] def mkAlt (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (b : FnBody) : Alt := Alt.ctor ⟨n, cidx, size, usize, ssize⟩ b inductive Decl | fdecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) | extern (f : FunId) (xs : Array Param) (ty : IRType) (ext : ExternAttrData) namespace Decl instance : Inhabited Decl := ⟨fdecl (arbitrary _) (arbitrary _) IRType.irrelevant (arbitrary _)⟩ def name : Decl → FunId | Decl.fdecl f _ _ _ => f | Decl.extern f _ _ _ => f def params : Decl → Array Param | Decl.fdecl _ xs _ _ => xs | Decl.extern _ xs _ _ => xs def resultType : Decl → IRType | Decl.fdecl _ _ t _ => t | Decl.extern _ _ t _ => t def isExtern : Decl → Bool | Decl.extern _ _ _ _ => true | _ => false end Decl @[export lean_ir_mk_decl] def mkDecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) : Decl := Decl.fdecl f xs ty b @[export lean_ir_mk_extern_decl] def mkExternDecl (f : FunId) (xs : Array Param) (ty : IRType) (e : ExternAttrData) : Decl := Decl.extern f xs ty e open Std (RBTree RBTree.empty RBMap) /-- Set of variable and join point names -/ abbrev IndexSet := RBTree Index Index.lt instance vsetInh : Inhabited IndexSet := ⟨{}⟩ def mkIndexSet (idx : Index) : IndexSet := RBTree.empty.insert idx inductive LocalContextEntry | param : IRType → LocalContextEntry | localVar : IRType → Expr → LocalContextEntry | joinPoint : Array Param → FnBody → LocalContextEntry abbrev LocalContext := RBMap Index LocalContextEntry Index.lt def LocalContext.addLocal (ctx : LocalContext) (x : VarId) (t : IRType) (v : Expr) : LocalContext := ctx.insert x.idx (LocalContextEntry.localVar t v) def LocalContext.addJP (ctx : LocalContext) (j : JoinPointId) (xs : Array Param) (b : FnBody) : LocalContext := ctx.insert j.idx (LocalContextEntry.joinPoint xs b) def LocalContext.addParam (ctx : LocalContext) (p : Param) : LocalContext := ctx.insert p.x.idx (LocalContextEntry.param p.ty) def LocalContext.addParams (ctx : LocalContext) (ps : Array Param) : LocalContext := ps.foldl LocalContext.addParam ctx def LocalContext.isJP (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.joinPoint _ _) => true | other => false def LocalContext.getJPBody (ctx : LocalContext) (j : JoinPointId) : Option FnBody := match ctx.find? j.idx with | some (LocalContextEntry.joinPoint _ b) => some b | other => none def LocalContext.getJPParams (ctx : LocalContext) (j : JoinPointId) : Option (Array Param) := match ctx.find? j.idx with | some (LocalContextEntry.joinPoint ys _) => some ys | other => none def LocalContext.isParam (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.param _) => true | other => false def LocalContext.isLocalVar (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.localVar _ _) => true | other => false def LocalContext.contains (ctx : LocalContext) (idx : Index) : Bool := ctx.contains idx def LocalContext.eraseJoinPointDecl (ctx : LocalContext) (j : JoinPointId) : LocalContext := ctx.erase j.idx def LocalContext.getType (ctx : LocalContext) (x : VarId) : Option IRType := match ctx.find? x.idx with | some (LocalContextEntry.param t) => some t | some (LocalContextEntry.localVar t _) => some t | other => none def LocalContext.getValue (ctx : LocalContext) (x : VarId) : Option Expr := match ctx.find? x.idx with | some (LocalContextEntry.localVar _ v) => some v | other => none abbrev IndexRenaming := RBMap Index Index Index.lt class HasAlphaEqv (α : Type) := (aeqv : IndexRenaming → α → α → Bool) export HasAlphaEqv (aeqv) def VarId.alphaEqv (ρ : IndexRenaming) (v₁ v₂ : VarId) : Bool := match ρ.find? v₁.idx with | some v => v == v₂.idx | none => v₁ == v₂ instance VarId.hasAeqv : HasAlphaEqv VarId := ⟨VarId.alphaEqv⟩ def Arg.alphaEqv (ρ : IndexRenaming) : Arg → Arg → Bool | Arg.var v₁, Arg.var v₂ => aeqv ρ v₁ v₂ | Arg.irrelevant, Arg.irrelevant => true | _, _ => false instance Arg.hasAeqv : HasAlphaEqv Arg := ⟨Arg.alphaEqv⟩ def args.alphaEqv (ρ : IndexRenaming) (args₁ args₂ : Array Arg) : Bool := Array.isEqv args₁ args₂ (fun a b => aeqv ρ a b) instance args.hasAeqv : HasAlphaEqv (Array Arg) := ⟨args.alphaEqv⟩ def Expr.alphaEqv (ρ : IndexRenaming) : Expr → Expr → Bool | Expr.ctor i₁ ys₁, Expr.ctor i₂ ys₂ => i₁ == i₂ && aeqv ρ ys₁ ys₂ | Expr.reset n₁ x₁, Expr.reset n₂ x₂ => n₁ == n₂ && aeqv ρ x₁ x₂ | Expr.reuse x₁ i₁ u₁ ys₁, Expr.reuse x₂ i₂ u₂ ys₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && u₁ == u₂ && aeqv ρ ys₁ ys₂ | Expr.proj i₁ x₁, Expr.proj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂ | Expr.uproj i₁ x₁, Expr.uproj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂ | Expr.sproj n₁ o₁ x₁, Expr.sproj n₂ o₂ x₂ => n₁ == n₂ && o₁ == o₂ && aeqv ρ x₁ x₂ | Expr.fap c₁ ys₁, Expr.fap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂ | Expr.pap c₁ ys₁, Expr.pap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂ | Expr.ap x₁ ys₁, Expr.ap x₂ ys₂ => aeqv ρ x₁ x₂ && aeqv ρ ys₁ ys₂ | Expr.box ty₁ x₁, Expr.box ty₂ x₂ => ty₁ == ty₂ && aeqv ρ x₁ x₂ | Expr.unbox x₁, Expr.unbox x₂ => aeqv ρ x₁ x₂ | Expr.lit v₁, Expr.lit v₂ => v₁ == v₂ | Expr.isShared x₁, Expr.isShared x₂ => aeqv ρ x₁ x₂ | Expr.isTaggedPtr x₁, Expr.isTaggedPtr x₂ => aeqv ρ x₁ x₂ | _, _ => false instance Expr.hasAeqv : HasAlphaEqv Expr:= ⟨Expr.alphaEqv⟩ def addVarRename (ρ : IndexRenaming) (x₁ x₂ : Nat) := if x₁ == x₂ then ρ else ρ.insert x₁ x₂ def addParamRename (ρ : IndexRenaming) (p₁ p₂ : Param) : Option IndexRenaming := if p₁.ty == p₂.ty && p₁.borrow = p₂.borrow then some (addVarRename ρ p₁.x.idx p₂.x.idx) else none def addParamsRename (ρ : IndexRenaming) (ps₁ ps₂ : Array Param) : Option IndexRenaming := if ps₁.size != ps₂.size then none else Array.foldl₂ (fun ρ p₁ p₂ => do ρ ← ρ; addParamRename ρ p₁ p₂) (some ρ) ps₁ ps₂ partial def FnBody.alphaEqv : IndexRenaming → FnBody → FnBody → Bool | ρ, FnBody.vdecl x₁ t₁ v₁ b₁, FnBody.vdecl x₂ t₂ v₂ b₂ => t₁ == t₂ && aeqv ρ v₁ v₂ && FnBody.alphaEqv (addVarRename ρ x₁.idx x₂.idx) b₁ b₂ | ρ, FnBody.jdecl j₁ ys₁ v₁ b₁, FnBody.jdecl j₂ ys₂ v₂ b₂ => match addParamsRename ρ ys₁ ys₂ with | some ρ' => FnBody.alphaEqv ρ' v₁ v₂ && FnBody.alphaEqv (addVarRename ρ j₁.idx j₂.idx) b₁ b₂ | none => false | ρ, FnBody.set x₁ i₁ y₁ b₁, FnBody.set x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && FnBody.alphaEqv ρ b₁ b₂ | ρ, FnBody.uset x₁ i₁ y₁ b₁, FnBody.uset x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && FnBody.alphaEqv ρ b₁ b₂ | ρ, FnBody.sset x₁ i₁ o₁ y₁ t₁ b₁, FnBody.sset x₂ i₂ o₂ y₂ t₂ b₂ => aeqv ρ x₁ x₂ && i₁ = i₂ && o₁ = o₂ && aeqv ρ y₁ y₂ && t₁ == t₂ && FnBody.alphaEqv ρ b₁ b₂ | ρ, FnBody.setTag x₁ i₁ b₁, FnBody.setTag x₂ i₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && FnBody.alphaEqv ρ b₁ b₂ | ρ, FnBody.inc x₁ n₁ c₁ p₁ b₁, FnBody.inc x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && FnBody.alphaEqv ρ b₁ b₂ | ρ, FnBody.dec x₁ n₁ c₁ p₁ b₁, FnBody.dec x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && FnBody.alphaEqv ρ b₁ b₂ | ρ, FnBody.del x₁ b₁, FnBody.del x₂ b₂ => aeqv ρ x₁ x₂ && FnBody.alphaEqv ρ b₁ b₂ | ρ, FnBody.mdata m₁ b₁, FnBody.mdata m₂ b₂ => m₁ == m₂ && FnBody.alphaEqv ρ b₁ b₂ | ρ, FnBody.case n₁ x₁ _ alts₁, FnBody.case n₂ x₂ _ alts₂ => n₁ == n₂ && aeqv ρ x₁ x₂ && Array.isEqv alts₁ alts₂ (fun alt₁ alt₂ => match alt₁, alt₂ with | Alt.ctor i₁ b₁, Alt.ctor i₂ b₂ => i₁ == i₂ && FnBody.alphaEqv ρ b₁ b₂ | Alt.default b₁, Alt.default b₂ => FnBody.alphaEqv ρ b₁ b₂ | _, _ => false) | ρ, FnBody.jmp j₁ ys₁, FnBody.jmp j₂ ys₂ => j₁ == j₂ && aeqv ρ ys₁ ys₂ | ρ, FnBody.ret x₁, FnBody.ret x₂ => aeqv ρ x₁ x₂ | _, FnBody.unreachable, FnBody.unreachable => true | _, _, _ => false def FnBody.beq (b₁ b₂ : FnBody) : Bool := FnBody.alphaEqv ∅ b₁ b₂ instance FnBody.HasBeq : HasBeq FnBody := ⟨FnBody.beq⟩ abbrev VarIdSet := RBTree VarId (fun x y => x.idx < y.idx) namespace VarIdSet instance : Inhabited VarIdSet := ⟨{}⟩ end VarIdSet def mkIf (x : VarId) (t e : FnBody) : FnBody := FnBody.case `Bool x IRType.uint8 #[ Alt.ctor {name := `Bool.false, cidx := 0, size := 0, usize := 0, ssize := 0} e, Alt.ctor {name := `Bool.true, cidx := 1, size := 0, usize := 0, ssize := 0} t ] end IR end Lean
d605ac7fc040bcf2316c491c817f3c88565cfa5b
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Meta/Match/Basic.lean
8a7109ce18eb50f74a5e4591c542ca707eddcfd7
[ "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
14,436
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Check import Lean.Meta.CollectFVars import Lean.Meta.Match.MatcherInfo import Lean.Meta.Match.CaseArraySizes namespace Lean.Meta.Match def mkNamedPattern (x h p : Expr) : MetaM Expr := mkAppM ``namedPattern #[x, p, h] def isNamedPattern? (e : Expr) : Option Expr := let e := e.consumeMData if e.getAppNumArgs == 4 && e.getAppFn.consumeMData.isConstOf ``namedPattern then some e else none inductive Pattern : Type where | inaccessible (e : Expr) : Pattern | var (fvarId : FVarId) : Pattern | ctor (ctorName : Name) (us : List Level) (params : List Expr) (fields : List Pattern) : Pattern | val (e : Expr) : Pattern | arrayLit (type : Expr) (xs : List Pattern) : Pattern | as (varId : FVarId) (p : Pattern) (hId : FVarId) : Pattern deriving Inhabited namespace Pattern partial def toMessageData : Pattern → MessageData | inaccessible e => m!".({e})" | var varId => mkFVar varId | ctor ctorName _ _ [] => ctorName | ctor ctorName _ _ pats => m!"({ctorName}{pats.foldl (fun (msg : MessageData) pat => msg ++ " " ++ toMessageData pat) Format.nil})" | val e => e | arrayLit _ pats => m!"#[{MessageData.joinSep (pats.map toMessageData) ", "}]" | as varId p _ => m!"{mkFVar varId}@{toMessageData p}" partial def toExpr (p : Pattern) (annotate := false) : MetaM Expr := visit p where visit (p : Pattern) := do match p with | inaccessible e => if annotate then pure (mkInaccessible e) else pure e | var fvarId => pure $ mkFVar fvarId | val e => pure e | as fvarId p hId => -- TODO if annotate then mkNamedPattern (mkFVar fvarId) (mkFVar hId) (← visit p) else visit p | arrayLit type xs => let xs ← xs.mapM visit mkArrayLit type xs | ctor ctorName us params fields => let fields ← fields.mapM visit pure $ mkAppN (mkConst ctorName us) (params ++ fields).toArray /-- Apply the free variable substitution `s` to the given pattern -/ partial def applyFVarSubst (s : FVarSubst) : Pattern → Pattern | inaccessible e => inaccessible $ s.apply e | ctor n us ps fs => ctor n us (ps.map s.apply) $ fs.map (applyFVarSubst s) | val e => val $ s.apply e | arrayLit t xs => arrayLit (s.apply t) $ xs.map (applyFVarSubst s) | var fvarId => match s.find? fvarId with | some e => inaccessible e | none => var fvarId | as fvarId p hId => match s.find? fvarId with | none => as fvarId (applyFVarSubst s p) hId | some _ => applyFVarSubst s p def replaceFVarId (fvarId : FVarId) (v : Expr) (p : Pattern) : Pattern := let s : FVarSubst := {} p.applyFVarSubst (s.insert fvarId v) partial def hasExprMVar : Pattern → Bool | inaccessible e => e.hasExprMVar | ctor _ _ ps fs => ps.any (·.hasExprMVar) || fs.any hasExprMVar | val e => e.hasExprMVar | as _ p _ => hasExprMVar p | arrayLit t xs => t.hasExprMVar || xs.any hasExprMVar | _ => false partial def collectFVars (p : Pattern) : StateRefT CollectFVars.State MetaM Unit := do match p with | inaccessible e => e.collectFVars | ctor _ _ ps fs => ps.forM fun p => p.collectFVars fs.forM collectFVars | val e => e.collectFVars | arrayLit t xs => t.collectFVars; xs.forM collectFVars | as fvarId₁ p fvarId₂ => modify (·.add fvarId₁ |>.add fvarId₂); p.collectFVars | var fvarId => modify (·.add fvarId) end Pattern partial def instantiatePatternMVars : Pattern → MetaM Pattern | Pattern.inaccessible e => return Pattern.inaccessible (← instantiateMVars e) | Pattern.val e => return Pattern.val (← instantiateMVars e) | Pattern.ctor n us ps fields => return Pattern.ctor n us (← ps.mapM instantiateMVars) (← fields.mapM instantiatePatternMVars) | Pattern.as x p h => return Pattern.as x (← instantiatePatternMVars p) h | Pattern.arrayLit t xs => return Pattern.arrayLit (← instantiateMVars t) (← xs.mapM instantiatePatternMVars) | p => return p structure AltLHS where ref : Syntax fvarDecls : List LocalDecl -- Free variables used in the patterns. patterns : List Pattern -- We use `List Pattern` since we have nary match-expressions. def AltLHS.collectFVars (altLHS: AltLHS) : StateRefT CollectFVars.State MetaM Unit := do altLHS.fvarDecls.forM fun fvarDecl => fvarDecl.collectFVars altLHS.patterns.forM fun p => p.collectFVars def instantiateAltLHSMVars (altLHS : AltLHS) : MetaM AltLHS := return { altLHS with fvarDecls := (← altLHS.fvarDecls.mapM instantiateLocalDeclMVars), patterns := (← altLHS.patterns.mapM instantiatePatternMVars) } /-- `Match` alternative -/ structure Alt where /-- `Syntax` object for providing position information -/ ref : Syntax /-- Orginal alternative index. Alternatives can be split, this index is the original position of the alternative that generated this one. -/ idx : Nat /-- Right-hand-side of the alternative. -/ rhs : Expr /-- Alternative pattern variables. -/ fvarDecls : List LocalDecl /-- Alternative patterns. -/ patterns : List Pattern /-- Pending constraints `lhs ≋ rhs` that need to be solved before the alternative is considered acceptable. We generate them when processing inaccessible patterns. Note that `lhs` and `rhs` often have different types. After we perform additional case analysis, their types become definitionally equal. -/ cnstrs : List (Expr × Expr) deriving Inhabited namespace Alt partial def toMessageData (alt : Alt) : MetaM MessageData := do withExistingLocalDecls alt.fvarDecls do let msg := alt.fvarDecls.map fun d => m!"{d.toExpr}:({d.type})" let mut msg := m!"{msg} |- {alt.patterns.map Pattern.toMessageData} => {alt.rhs}" for (lhs, rhs) in alt.cnstrs do msg := m!"{msg}\n | {lhs} ≋ {rhs}" addMessageContext msg def applyFVarSubst (s : FVarSubst) (alt : Alt) : Alt := { alt with patterns := alt.patterns.map fun p => p.applyFVarSubst s, fvarDecls := alt.fvarDecls.map fun d => d.applyFVarSubst s, rhs := alt.rhs.applyFVarSubst s cnstrs := alt.cnstrs.map fun (lhs, rhs) => (lhs.applyFVarSubst s, rhs.applyFVarSubst s) } def replaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : Alt := { alt with patterns := alt.patterns.map fun p => p.replaceFVarId fvarId v, rhs := alt.rhs.replaceFVarId fvarId v fvarDecls := let decls := alt.fvarDecls.filter fun d => d.fvarId != fvarId decls.map (·.replaceFVarId fvarId v) cnstrs := alt.cnstrs.map fun (lhs, rhs) => (lhs.replaceFVarId fvarId v, rhs.replaceFVarId fvarId v) } /-- Return `true` if `fvarId` is one of the alternative pattern variables -/ def isLocalDecl (fvarId : FVarId) (alt : Alt) : Bool := alt.fvarDecls.any fun d => d.fvarId == fvarId /-- Similar to `checkAndReplaceFVarId`, but ensures type of `v` is definitionally equal to type of `fvarId`. This extra check is necessary when performing dependent elimination and inaccessible terms have been used. For example, consider the following code fragment: ``` inductive Vec (α : Type u) : Nat → Type u where | nil : Vec α 0 | cons {n} (head : α) (tail : Vec α n) : Vec α (n+1) inductive VecPred {α : Type u} (P : α → Prop) : {n : Nat} → Vec α n → Prop where | nil : VecPred P Vec.nil | cons {n : Nat} {head : α} {tail : Vec α n} : P head → VecPred P tail → VecPred P (Vec.cons head tail) theorem ex {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P | _, Vec.cons head _, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩ ``` Recall that `_` in a pattern can be elaborated into pattern variable or an inaccessible term. The elaborator uses an inaccessible term when typing constraints restrict its value. Thus, in the example above, the `_` at `Vec.cons head _` becomes the inaccessible pattern `.(Vec.nil)` because the type ascription `(w : VecPred P Vec.nil)` propagates typing constraints that restrict its value to be `Vec.nil`. After elaboration the alternative becomes: ``` | .(0), @Vec.cons .(α) .(0) head .(Vec.nil), @VecPred.cons .(α) .(P) .(0) .(head) .(Vec.nil) h w => ⟨head, h⟩ ``` where ``` (head : α), (h: P head), (w : VecPred P Vec.nil) ``` Then, when we process this alternative in this module, the following check will detect that `w` has type `VecPred P Vec.nil`, when it is supposed to have type `VecPred P tail`. Note that if we had written ``` theorem ex {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P | _, Vec.cons head Vec.nil, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩ ``` we would get the easier to digest error message ``` missing cases: _, (Vec.cons _ _ (Vec.cons _ _ _)), _ ``` -/ def checkAndReplaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : MetaM Alt := do match alt.fvarDecls.find? fun (fvarDecl : LocalDecl) => fvarDecl.fvarId == fvarId with | none => throwErrorAt alt.ref "unknown free pattern variable" | some fvarDecl => do let vType ← inferType v unless (← isDefEqGuarded fvarDecl.type vType) do withExistingLocalDecls alt.fvarDecls do let (expectedType, givenType) ← addPPExplicitToExposeDiff vType fvarDecl.type throwErrorAt alt.ref "type mismatch during dependent match-elimination at pattern variable '{mkFVar fvarDecl.fvarId}' with type{indentExpr givenType}\nexpected type{indentExpr expectedType}" return replaceFVarId fvarId v alt end Alt inductive Example where | var : FVarId → Example | underscore : Example | ctor : Name → List Example → Example | val : Expr → Example | arrayLit : List Example → Example namespace Example partial def replaceFVarId (fvarId : FVarId) (ex : Example) : Example → Example | var x => if x == fvarId then ex else var x | ctor n exs => ctor n $ exs.map (replaceFVarId fvarId ex) | arrayLit exs => arrayLit $ exs.map (replaceFVarId fvarId ex) | ex => ex partial def applyFVarSubst (s : FVarSubst) : Example → Example | var fvarId => match s.get fvarId with | Expr.fvar fvarId' => var fvarId' | _ => underscore | ctor n exs => ctor n $ exs.map (applyFVarSubst s) | arrayLit exs => arrayLit $ exs.map (applyFVarSubst s) | ex => ex partial def varsToUnderscore : Example → Example | var _ => underscore | ctor n exs => ctor n $ exs.map varsToUnderscore | arrayLit exs => arrayLit $ exs.map varsToUnderscore | ex => ex partial def toMessageData : Example → MessageData | var fvarId => mkFVar fvarId | ctor ctorName [] => mkConst ctorName | ctor ctorName exs => m!"({mkConst ctorName}{exs.foldl (fun msg pat => m!"{msg} {toMessageData pat}") Format.nil})" | arrayLit exs => "#" ++ MessageData.ofList (exs.map toMessageData) | val e => e | underscore => "_" end Example def examplesToMessageData (cex : List Example) : MessageData := MessageData.joinSep (cex.map (Example.toMessageData ∘ Example.varsToUnderscore)) ", " structure Problem where mvarId : MVarId vars : List Expr alts : List Alt examples : List Example deriving Inhabited def withGoalOf {α} (p : Problem) (x : MetaM α) : MetaM α := p.mvarId.withContext x def Problem.toMessageData (p : Problem) : MetaM MessageData := withGoalOf p do let alts ← p.alts.mapM Alt.toMessageData let vars ← p.vars.mapM fun x => do let xType ← inferType x; pure m!"{x}:({xType})" return m!"remaining variables: {vars}\nalternatives:{indentD (MessageData.joinSep alts Format.line)}\nexamples:{examplesToMessageData p.examples}\n" abbrev CounterExample := List Example def counterExampleToMessageData (cex : CounterExample) : MessageData := examplesToMessageData cex def counterExamplesToMessageData (cexs : List CounterExample) : MessageData := MessageData.joinSep (cexs.map counterExampleToMessageData) Format.line structure MatcherResult where matcher : Expr -- The matcher. It is not just `Expr.const matcherName` because the type of the major premises may contain free variables. counterExamples : List CounterExample unusedAltIdxs : List Nat addMatcher : MetaM Unit /-- Convert a expression occurring as the argument of a `match` motive application back into a `Pattern` For example, we can use this method to convert `x::y::xs` at ``` ... (motive : List Nat → Sort u_1) (xs : List Nat) (h_1 : (x y : Nat) → (xs : List Nat) → motive (x :: y :: xs)) ... ``` into a pattern object -/ partial def toPattern (e : Expr) : MetaM Pattern := do match inaccessible? e with | some t => return Pattern.inaccessible t | none => match e.arrayLit? with | some (α, lits) => return Pattern.arrayLit α (← lits.mapM toPattern) | none => if let some e := isNamedPattern? e then let p ← toPattern <| e.getArg! 2 match e.getArg! 1, e.getArg! 3 with | Expr.fvar x, Expr.fvar h => return Pattern.as x p h | _, _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" else if isMatchValue e then return Pattern.val e else if e.isFVar then return Pattern.var e.fvarId! else let newE ← whnf e if newE != e then toPattern newE else matchConstCtor e.getAppFn (fun _ => throwError "unexpected pattern{indentExpr e}") fun v us => do let args := e.getAppArgs unless args.size == v.numParams + v.numFields do throwError "unexpected pattern{indentExpr e}" let params := args.extract 0 v.numParams let fields := args.extract v.numParams args.size let fields ← fields.mapM toPattern return Pattern.ctor v.name us params.toList fields.toList end Lean.Meta.Match
abb314b2c12adb6af08d27c9faadbcefacf5ef07
3268ab3a126f0fef71459fbf170dc38efe5d0506
/algebra/left_module.hlean
83ee6eaa0b258470b9b7c18749b6de381d6a8516
[ "Apache-2.0" ]
permissive
soraismus/Spectral
f043fed1a4e02ddfeba531769b2980eb817471f4
32512bf47db3a1b932856e7ed7c7830b1fc07ef0
refs/heads/master
1,585,628,705,579
1,538,609,948,000
1,538,609,974,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,818
hlean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Floris van Doorn Modules prod vector spaces over a ring. (We use "left_module," which is more precise, because "module" is a keyword.) -/ import algebra.field ..move_to_lib .exactness algebra.group_power open is_trunc pointed function sigma eq algebra prod is_equiv equiv group structure has_scalar [class] (F V : Type) := (smul : F → V → V) infixl ` • `:73 := has_scalar.smul /- modules over a ring -/ namespace left_module structure left_module (R M : Type) [ringR : ring R] extends has_scalar R M, ab_group M renaming mul → add mul_assoc → add_assoc one → zero one_mul → zero_add mul_one → add_zero inv → neg mul_left_inv → add_left_inv mul_comm → add_comm := (smul_left_distrib : Π (r : R) (x y : M), smul r (add x y) = (add (smul r x) (smul r y))) (smul_right_distrib : Π (r s : R) (x : M), smul (ring.add _ r s) x = (add (smul r x) (smul s x))) (mul_smul : Π r s x, smul (mul r s) x = smul r (smul s x)) (one_smul : Π x, smul one x = x) /- we make it a class now (and not as part of the structure) to avoid left_module.to_ab_group to be an instance -/ attribute left_module [class] definition add_ab_group_of_left_module [reducible] [trans_instance] (R M : Type) [K : ring R] [H : left_module R M] : add_ab_group M := @left_module.to_ab_group R M K H definition has_scalar_of_left_module [reducible] [trans_instance] (R M : Type) [K : ring R] [H : left_module R M] : has_scalar R M := @left_module.to_has_scalar R M K H section left_module variables {R M : Type} variable [ringR : ring R] variable [moduleRM : left_module R M] include ringR moduleRM -- Note: the anonymous include does not work in the propositions below. proposition smul_left_distrib (a : R) (u v : M) : a • (u + v) = a • u + a • v := !left_module.smul_left_distrib proposition smul_right_distrib (a b : R) (u : M) : (a + b) • u = a • u + b • u := !left_module.smul_right_distrib proposition mul_smul (a : R) (b : R) (u : M) : (a * b) • u = a • (b • u) := !left_module.mul_smul proposition one_smul (u : M) : (1 : R) • u = u := !left_module.one_smul proposition zero_smul (u : M) : (0 : R) • u = 0 := have (0 : R) • u + 0 • u = 0 • u + 0, by rewrite [-smul_right_distrib, *add_zero], !add.left_cancel this proposition smul_zero (a : R) : a • (0 : M) = 0 := have a • (0:M) + a • 0 = a • 0 + 0, by rewrite [-smul_left_distrib, *add_zero], !add.left_cancel this proposition neg_smul (a : R) (u : M) : (-a) • u = - (a • u) := eq_neg_of_add_eq_zero (by rewrite [-smul_right_distrib, add.left_inv, zero_smul]) proposition neg_one_smul (u : M) : -(1 : R) • u = -u := by rewrite [neg_smul, one_smul] proposition smul_neg (a : R) (u : M) : a • (-u) = -(a • u) := by rewrite [-neg_one_smul, -mul_smul, mul_neg_one_eq_neg, neg_smul] proposition smul_sub_left_distrib (a : R) (u v : M) : a • (u - v) = a • u - a • v := by rewrite [sub_eq_add_neg, smul_left_distrib, smul_neg] proposition sub_smul_right_distrib (a b : R) (v : M) : (a - b) • v = a • v - b • v := by rewrite [sub_eq_add_neg, smul_right_distrib, neg_smul] end left_module /- vector spaces -/ structure vector_space [class] (F V : Type) [fieldF : field F] extends left_module F V /- homomorphisms -/ definition is_smul_hom [class] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] (f : M₁ → M₂) : Type := ∀ r : R, ∀ a : M₁, f (r • a) = r • f a definition is_prop_is_smul_hom [instance] (R : Type) {M₁ M₂ : Type} [is_set M₂] [has_scalar R M₁] [has_scalar R M₂] (f : M₁ → M₂) : is_prop (is_smul_hom R f) := begin unfold is_smul_hom, apply _ end definition respect_smul (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] (f : M₁ → M₂) [H : is_smul_hom R f] : ∀ r : R, ∀ a : M₁, f (r • a) = r • f a := H definition is_module_hom [class] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) := is_add_hom f × is_smul_hom R f definition is_add_hom_of_is_module_hom [instance] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) [H : is_module_hom R f] : is_add_hom f := prod.pr1 H definition is_smul_hom_of_is_module_hom [instance] {R : Type} {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) [H : is_module_hom R f] : is_smul_hom R f := prod.pr2 H -- Why do we have to give the instance explicitly? definition is_prop_is_module_hom [instance] (R : Type) {M₁ M₂ : Type} [has_scalar R M₁] [has_scalar R M₂] [add_group M₁] [add_group M₂] (f : M₁ → M₂) : is_prop (is_module_hom R f) := have h₁ : is_prop (is_add_hom f), from is_prop_is_add_hom f, begin unfold is_module_hom, apply _ end section module_hom variables {R : Type} {M₁ M₂ M₃ : Type} variables [has_scalar R M₁] [has_scalar R M₂] [has_scalar R M₃] variables [add_group M₁] [add_group M₂] [add_group M₃] variables (g : M₂ → M₃) (f : M₁ → M₂) [is_module_hom R g] [is_module_hom R f] proposition is_module_hom_id : is_module_hom R (@id M₁) := pair (λ a₁ a₂, rfl) (λ r a, rfl) proposition is_module_hom_comp : is_module_hom R (g ∘ f) := pair (take a₁ a₂, begin esimp, rewrite [respect_add f, respect_add g] end) (take r a, by esimp; rewrite [respect_smul R f, respect_smul R g]) proposition respect_smul_add_smul (a b : R) (u v : M₁) : f (a • u + b • v) = a • f u + b • f v := by rewrite [respect_add f, +respect_smul R f] end module_hom section hom_constant variables {R : Type} {M₁ M₂ : Type} variables [ring R] [has_scalar R M₁] [add_group M₁] [left_module R M₂] proposition is_module_hom_constant : is_module_hom R (const M₁ (0 : M₂)) := (λm₁ m₂, !add_zero⁻¹, λr m, (smul_zero r)⁻¹ᵖ) end hom_constant structure LeftModule (R : Ring) := (carrier : Type) (struct : left_module R carrier) attribute LeftModule.struct [instance] section local attribute LeftModule.carrier [coercion] definition AddAbGroup_of_LeftModule [coercion] {R : Ring} (M : LeftModule R) : AddAbGroup := AddAbGroup.mk M (LeftModule.struct M) end definition LeftModule.struct2 [instance] {R : Ring} (M : LeftModule R) : left_module R M := LeftModule.struct M -- definition LeftModule.struct3 [instance] {R : Ring} (M : LeftModule R) : -- left_module R (AddAbGroup_of_LeftModule M) := -- _ definition pointed_LeftModule_carrier [instance] {R : Ring} (M : LeftModule R) : pointed (LeftModule.carrier M) := pointed.mk zero definition pSet_of_LeftModule {R : Ring} (M : LeftModule R) : Set* := pSet.mk' (LeftModule.carrier M) definition left_module_AddAbGroup_of_LeftModule [instance] {R : Ring} (M : LeftModule R) : left_module R (AddAbGroup_of_LeftModule M) := LeftModule.struct M definition left_module_of_ab_group {G : Type} [gG : add_ab_group G] {R : Type} [ring R] (smul : R → G → G) (h1 : Π (r : R) (x y : G), smul r (x + y) = (smul r x + smul r y)) (h2 : Π (r s : R) (x : G), smul (r + s) x = (smul r x + smul s x)) (h3 : Π r s x, smul (r * s) x = smul r (smul s x)) (h4 : Π x, smul 1 x = x) : left_module R G := left_module.mk smul _ add add.assoc 0 zero_add add_zero neg add.left_inv add.comm h1 h2 h3 h4 definition LeftModule_of_AddAbGroup {R : Ring} (G : AddAbGroup) (smul : R → G → G) (h1 h2 h3 h4) : LeftModule R := LeftModule.mk G (left_module_of_ab_group smul h1 h2 h3 h4) open unit definition trivial_LeftModule [constructor] (R : Ring) : LeftModule R := LeftModule_of_AddAbGroup trivial_ab_group (λr u, star) (λr u₁ u₂, idp) (λr₁ r₂ u, idp) (λr₁ r₂ u, idp) unit.eta section variables {R : Ring} {M M₁ M₂ M₃ : LeftModule R} definition smul_homomorphism [constructor] (M : LeftModule R) (r : R) : M →a M := add_homomorphism.mk (λg, r • g) (smul_left_distrib r) proposition to_smul_left_distrib (a : R) (u v : M) : a • (u + v) = a • u + a • v := !smul_left_distrib proposition to_smul_right_distrib (a b : R) (u : M) : (a + b) • u = a • u + b • u := !smul_right_distrib proposition to_mul_smul (a : R) (b : R) (u : M) : (a * b) • u = a • (b • u) := !mul_smul proposition to_one_smul (u : M) : (1 : R) • u = u := !one_smul structure homomorphism (M₁ M₂ : LeftModule R) : Type := (fn : LeftModule.carrier M₁ → LeftModule.carrier M₂) (p : is_module_hom R fn) infix ` →lm `:55 := homomorphism definition homomorphism_fn [unfold 4] [coercion] := @homomorphism.fn definition is_module_hom_of_homomorphism [unfold 4] [instance] [priority 900] {M₁ M₂ : LeftModule R} (φ : M₁ →lm M₂) : is_module_hom R φ := homomorphism.p φ section variable (φ : M₁ →lm M₂) definition to_respect_add (x y : M₁) : φ (x + y) = φ x + φ y := respect_add φ x y definition to_respect_smul (a : R) (x : M₁) : φ (a • x) = a • (φ x) := respect_smul R φ a x definition to_respect_sub (x y : M₁) : φ (x - y) = φ x - φ y := respect_sub φ x y definition is_embedding_of_homomorphism /- φ -/ (H : Π{x}, φ x = 0 → x = 0) : is_embedding φ := is_embedding_of_is_add_hom φ @H variables (M₁ M₂) definition is_set_homomorphism [instance] : is_set (M₁ →lm M₂) := begin have H : M₁ →lm M₂ ≃ Σ(f : LeftModule.carrier M₁ → LeftModule.carrier M₂), is_module_hom (Ring.carrier R) f, begin fapply equiv.MK, { intro φ, induction φ, constructor, exact p}, { intro v, induction v with f H, constructor, exact H}, { intro v, induction v, reflexivity}, { intro φ, induction φ, reflexivity} end, have ∀ f : LeftModule.carrier M₁ → LeftModule.carrier M₂, is_set (is_module_hom (Ring.carrier R) f), from _, exact is_trunc_equiv_closed_rev _ H _ end variables {M₁ M₂} definition pmap_of_homomorphism [constructor] /- φ -/ : pSet_of_LeftModule M₁ →* pSet_of_LeftModule M₂ := have H : φ 0 = 0, from respect_zero φ, pmap.mk φ begin esimp, exact H end definition homomorphism_change_fun [constructor] (φ : M₁ →lm M₂) (f : M₁ → M₂) (p : φ ~ f) : M₁ →lm M₂ := homomorphism.mk f (prod.mk (λx₁ x₂, (p (x₁ + x₂))⁻¹ ⬝ to_respect_add φ x₁ x₂ ⬝ ap011 _ (p x₁) (p x₂)) (λ a x, (p (a • x))⁻¹ ⬝ to_respect_smul φ a x ⬝ ap01 _ (p x))) definition homomorphism_eq (φ₁ φ₂ : M₁ →lm M₂) (p : φ₁ ~ φ₂) : φ₁ = φ₂ := begin induction φ₁ with φ₁ q₁, induction φ₂ with φ₂ q₂, esimp at p, induction p, exact ap (homomorphism.mk φ₁) !is_prop.elim end end section definition homomorphism.mk' [constructor] (φ : M₁ → M₂) (p : Π(g₁ g₂ : M₁), φ (g₁ + g₂) = φ g₁ + φ g₂) (q : Π(r : R) x, φ (r • x) = r • φ x) : M₁ →lm M₂ := homomorphism.mk φ (p, q) definition to_respect_zero (φ : M₁ →lm M₂) : φ 0 = 0 := respect_zero φ definition homomorphism_compose [reducible] [constructor] (f' : M₂ →lm M₃) (f : M₁ →lm M₂) : M₁ →lm M₃ := homomorphism.mk (f' ∘ f) !is_module_hom_comp variable (M) definition homomorphism_id [reducible] [constructor] [refl] : M →lm M := homomorphism.mk (@id M) !is_module_hom_id variable {M} abbreviation lmid [constructor] := homomorphism_id M infixr ` ∘lm `:75 := homomorphism_compose definition lm_constant [constructor] (M₁ M₂ : LeftModule R) : M₁ →lm M₂ := homomorphism.mk (const M₁ 0) !is_module_hom_constant structure isomorphism (M₁ M₂ : LeftModule R) := (to_hom : M₁ →lm M₂) (is_equiv_to_hom : is_equiv to_hom) infix ` ≃lm `:25 := isomorphism attribute isomorphism.to_hom [coercion] attribute isomorphism.is_equiv_to_hom [instance] attribute isomorphism._trans_of_to_hom [unfold 4] definition equiv_of_isomorphism [constructor] (φ : M₁ ≃lm M₂) : M₁ ≃ M₂ := equiv.mk φ !isomorphism.is_equiv_to_hom section local attribute pSet_of_LeftModule [coercion] definition pequiv_of_isomorphism [constructor] (φ : M₁ ≃lm M₂) : M₁ ≃* M₂ := pequiv_of_equiv (equiv_of_isomorphism φ) (to_respect_zero φ) end definition isomorphism_of_equiv [constructor] (φ : M₁ ≃ M₂) (p : Π(g₁ g₂ : M₁), φ (g₁ + g₂) = φ g₁ + φ g₂) (q : Πr x, φ (r • x) = r • φ x) : M₁ ≃lm M₂ := isomorphism.mk (homomorphism.mk φ (p, q)) !to_is_equiv definition isomorphism_of_eq [constructor] {M₁ M₂ : LeftModule R} (p : M₁ = M₂ :> LeftModule R) : M₁ ≃lm M₂ := isomorphism_of_equiv (equiv_of_eq (ap LeftModule.carrier p)) begin intros, induction p, reflexivity end begin intros, induction p, reflexivity end -- definition pequiv_of_isomorphism_of_eq {M₁ M₂ : LeftModule R} (p : M₁ = M₂ :> LeftModule R) : -- pequiv_of_isomorphism (isomorphism_of_eq p) = pequiv_of_eq (ap pType_of_LeftModule p) := -- begin -- induction p, -- apply pequiv_eq, -- fapply pmap_eq, -- { intro g, reflexivity}, -- { apply is_prop.elim} -- end definition to_lminv [constructor] (φ : M₁ ≃lm M₂) : M₂ →lm M₁ := homomorphism.mk φ⁻¹ abstract begin split, intro g₁ g₂, apply inj' φ, rewrite [respect_add φ, +right_inv φ], intro r x, apply inj' φ, rewrite [to_respect_smul φ, +right_inv φ], end end variable (M) definition isomorphism.refl [refl] [constructor] : M ≃lm M := isomorphism.mk lmid !is_equiv_id variable {M} definition isomorphism.rfl [refl] [constructor] : M ≃lm M := isomorphism.refl M definition isomorphism.symm [symm] [constructor] (φ : M₁ ≃lm M₂) : M₂ ≃lm M₁ := isomorphism.mk (to_lminv φ) !is_equiv_inv definition isomorphism.trans [trans] [constructor] (φ : M₁ ≃lm M₂) (ψ : M₂ ≃lm M₃) : M₁ ≃lm M₃ := isomorphism.mk (ψ ∘lm φ) (is_equiv_compose ψ φ _ _) definition isomorphism.eq_trans [trans] [constructor] {M₁ M₂ : LeftModule R} {M₃ : LeftModule R} (φ : M₁ = M₂) (ψ : M₂ ≃lm M₃) : M₁ ≃lm M₃ := proof isomorphism.trans (isomorphism_of_eq φ) ψ qed definition isomorphism.trans_eq [trans] [constructor] {M₁ : LeftModule R} {M₂ M₃ : LeftModule R} (φ : M₁ ≃lm M₂) (ψ : M₂ = M₃) : M₁ ≃lm M₃ := isomorphism.trans φ (isomorphism_of_eq ψ) postfix `⁻¹ˡᵐ`:(max + 1) := isomorphism.symm infixl ` ⬝lm `:75 := isomorphism.trans infixl ` ⬝lmp `:75 := isomorphism.trans_eq infixl ` ⬝plm `:75 := isomorphism.eq_trans definition homomorphism_of_eq [constructor] {M₁ M₂ : LeftModule R} (p : M₁ = M₂ :> LeftModule R) : M₁ →lm M₂ := isomorphism_of_eq p definition group_homomorphism_of_lm_homomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : M₁ →lm M₂) : M₁ →a M₂ := add_homomorphism.mk φ (to_respect_add φ) definition lm_homomorphism_of_group_homomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : M₁ →a M₂) (h : Π(r : R) g, φ (r • g) = r • φ g) : M₁ →lm M₂ := homomorphism.mk' φ (group.to_respect_add φ) h definition group_isomorphism_of_lm_isomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : M₁ ≃lm M₂) : AddGroup_of_AddAbGroup M₁ ≃g AddGroup_of_AddAbGroup M₂ := group.isomorphism.mk (group_homomorphism_of_lm_homomorphism φ) (isomorphism.is_equiv_to_hom φ) definition lm_isomorphism_of_group_isomorphism [constructor] {M₁ M₂ : LeftModule R} (φ : AddGroup_of_AddAbGroup M₁ ≃g AddGroup_of_AddAbGroup M₂) (h : Π(r : R) g, φ (r • g) = r • φ g) : M₁ ≃lm M₂ := isomorphism.mk (lm_homomorphism_of_group_homomorphism φ h) (group.isomorphism.is_equiv_to_hom φ) section local attribute pSet_of_LeftModule [coercion] definition is_exact_mod (f : M₁ →lm M₂) (f' : M₂ →lm M₃) : Type := @is_exact M₁ M₂ M₃ (homomorphism_fn f) (homomorphism_fn f') definition is_exact_mod.mk {f : M₁ →lm M₂} {f' : M₂ →lm M₃} (h₁ : Πm, f' (f m) = 0) (h₂ : Πm, f' m = 0 → image f m) : is_exact_mod f f' := is_exact.mk h₁ h₂ structure short_exact_mod (A B C : LeftModule R) := (f : A →lm B) (g : B →lm C) (h : @is_short_exact A B C f g) local abbreviation g_of_lm := @group_homomorphism_of_lm_homomorphism definition short_exact_mod_of_is_exact {X A B C Y : LeftModule R} (k : X →lm A) (f : A →lm B) (g : B →lm C) (l : C →lm Y) (hX : is_contr X) (hY : is_contr Y) (kf : is_exact_mod k f) (fg : is_exact_mod f g) (gl : is_exact_mod g l) : short_exact_mod A B C := short_exact_mod.mk f g (is_short_exact_of_is_exact (g_of_lm k) (g_of_lm f) (g_of_lm g) (g_of_lm l) hX hY kf fg gl) definition short_exact_mod_isomorphism {A B A' B' C C' : LeftModule R} (eA : A ≃lm A') (eB : B ≃lm B') (eC : C ≃lm C') (H : short_exact_mod A' B' C') : short_exact_mod A B C := short_exact_mod.mk (eB⁻¹ˡᵐ ∘lm short_exact_mod.f H ∘lm eA) (eC⁻¹ˡᵐ ∘lm short_exact_mod.g H ∘lm eB) (is_short_exact_equiv _ _ (equiv_of_isomorphism eA) (equiv_of_isomorphism eB) (pequiv_of_isomorphism eC) (λa, to_right_inv (equiv_of_isomorphism eB) _) (λb, to_right_inv (equiv_of_isomorphism eC) _) (short_exact_mod.h H)) definition is_contr_middle_of_short_exact_mod {A B C : LeftModule R} (H : short_exact_mod A B C) (HA : is_contr A) (HC : is_contr C) : is_contr B := is_contr_middle_of_is_exact (is_exact_of_is_short_exact (short_exact_mod.h H)) definition is_contr_right_of_short_exact_mod {A B C : LeftModule R} (H : short_exact_mod A B C) (HB : is_contr B) : is_contr C := is_contr_right_of_is_short_exact (short_exact_mod.h H) _ _ definition is_contr_left_of_short_exact_mod {A B C : LeftModule R} (H : short_exact_mod A B C) (HB : is_contr B) : is_contr A := is_contr_left_of_is_short_exact (short_exact_mod.h H) _ pt definition isomorphism_of_is_contr_left {A B C : LeftModule R} (H : short_exact_mod A B C) (HA : is_contr A) : B ≃lm C := isomorphism.mk (short_exact_mod.g H) begin apply @is_equiv_right_of_is_short_exact _ _ _ (group_homomorphism_of_lm_homomorphism (short_exact_mod.f H)) (group_homomorphism_of_lm_homomorphism (short_exact_mod.g H)), rexact short_exact_mod.h H, exact HA, end definition isomorphism_of_is_contr_right {A B C : LeftModule R} (H : short_exact_mod A B C) (HC : is_contr C) : A ≃lm B := isomorphism.mk (short_exact_mod.f H) begin apply @is_equiv_left_of_is_short_exact _ _ _ (group_homomorphism_of_lm_homomorphism (short_exact_mod.f H)) (group_homomorphism_of_lm_homomorphism (short_exact_mod.g H)), rexact short_exact_mod.h H, exact HC, end end end end /- we say that an left module D is built from the sequence E if D is a "twisted sum" of the E, and E has only finitely many nontrivial values -/ open nat structure is_built_from.{u v w} {R : Ring} (D : LeftModule.{u v} R) (E : ℕ → LeftModule.{u w} R) : Type.{max u (v+1) w} := (part : ℕ → LeftModule.{u v} R) (ses : Πn, short_exact_mod (E n) (part n) (part (n+1))) (e0 : part 0 ≃lm D) (n₀ : ℕ) (HD' : Π(s : ℕ), n₀ ≤ s → is_contr (part s)) open is_built_from universe variables u v w variables {R : Ring.{u}} {D D' : LeftModule.{u v} R} {E E' : ℕ → LeftModule.{u w} R} definition is_built_from_shift (H : is_built_from D E) : is_built_from (part H 1) (λn, E (n+1)) := is_built_from.mk (λn, part H (n+1)) (λn, ses H (n+1)) isomorphism.rfl (pred (n₀ H)) (λs Hle, HD' H _ (le_succ_of_pred_le Hle)) definition isomorphism_of_is_contr_part (H : is_built_from D E) (n : ℕ) (HE : is_contr (E n)) : part H n ≃lm part H (n+1) := isomorphism_of_is_contr_left (ses H n) HE definition is_contr_submodules (H : is_built_from D E) (HD : is_contr D) (n : ℕ) : is_contr (part H n) := begin induction n with n IH, { exact is_trunc_equiv_closed_rev -2 (equiv_of_isomorphism (e0 H)) _ }, { exact is_contr_right_of_short_exact_mod (ses H n) IH } end definition is_contr_quotients (H : is_built_from D E) (HD : is_contr D) (n : ℕ) : is_contr (E n) := begin apply is_contr_left_of_short_exact_mod (ses H n), exact is_contr_submodules H HD n end definition is_contr_total (H : is_built_from D E) (HE : Πn, is_contr (E n)) : is_contr D := have is_contr (part H 0), from nat.rec_down (λn, is_contr (part H n)) _ (HD' H _ !le.refl) (λn H2, is_contr_middle_of_short_exact_mod (ses H n) (HE n) H2), is_contr_equiv_closed (equiv_of_isomorphism (e0 H)) _ definition is_built_from_isomorphism (e : D ≃lm D') (f : Πn, E n ≃lm E' n) (H : is_built_from D E) : is_built_from D' E' := ⦃is_built_from, H, e0 := e0 H ⬝lm e, ses := λn, short_exact_mod_isomorphism (f n)⁻¹ˡᵐ isomorphism.rfl isomorphism.rfl (ses H n)⦄ definition is_built_from_isomorphism_left (e : D ≃lm D') (H : is_built_from D E) : is_built_from D' E := ⦃is_built_from, H, e0 := e0 H ⬝lm e⦄ definition isomorphism_zero_of_is_built_from (H : is_built_from D E) (p : n₀ H = 1) : E 0 ≃lm D := isomorphism_of_is_contr_right (ses H 0) (HD' H 1 (le_of_eq p)) ⬝lm e0 H section int open int definition left_module_int_of_ab_group [constructor] (A : Type) [add_ab_group A] : left_module rℤ A := left_module_of_ab_group imul imul_add add_imul mul_imul one_imul definition LeftModule_int_of_AbGroup [constructor] (A : AddAbGroup) : LeftModule rℤ := LeftModule.mk A (left_module_int_of_ab_group A) definition lm_hom_int.mk [constructor] {A B : AbGroup} (φ : A →g B) : LeftModule_int_of_AbGroup A →lm LeftModule_int_of_AbGroup B := lm_homomorphism_of_group_homomorphism φ (to_respect_imul φ) definition lm_iso_int.mk [constructor] {A B : AbGroup} (φ : A ≃g B) : LeftModule_int_of_AbGroup A ≃lm LeftModule_int_of_AbGroup B := isomorphism.mk (lm_hom_int.mk φ) (group.isomorphism.is_equiv_to_hom φ) definition group_isomorphism_of_lm_isomorphism_int [constructor] {A B : AbGroup} (φ : LeftModule_int_of_AbGroup A ≃lm LeftModule_int_of_AbGroup B) : A ≃g B := group_isomorphism_of_lm_isomorphism φ end int end left_module
7bfc15237dee80244c795577cca001b4fe52523d
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/ring_theory/finiteness.lean
01258563d0d99e5b73f50be13f5a372bd2ce98fa
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,185
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import ring_theory.noetherian import ring_theory.ideal.operations import ring_theory.algebra_tower /-! # Finiteness conditions in commutative algebra In this file we define several notions of finiteness that are common in commutative algebra. ## Main declarations - `module.finite`, `algebra.finite`, `ring_hom.finite`, `alg_hom.finite` all of these express that some object is finitely generated *as module* over some base ring. - `algebra.finite_type`, `ring_hom.finite_type`, `alg_hom.finite_type` all of these express that some object is finitely generated *as algebra* over some base ring. - `algebra.finite_presentation`, `ring_hom.finite_presentation`, `alg_hom.finite_presentation` all of these express that some object is finitely presented *as algebra* over some base ring. -/ open function (surjective) open_locale big_operators section module_and_algebra variables (R A B M N : Type*) [comm_ring R] variables [comm_ring A] [algebra R A] [comm_ring B] [algebra R B] variables [add_comm_group M] [module R M] variables [add_comm_group N] [module R N] /-- A module over a commutative ring is `finite` if it is finitely generated as a module. -/ class module.finite : Prop := (out : (⊤ : submodule R M).fg) /-- An algebra over a commutative ring is of `finite_type` if it is finitely generated over the base ring as algebra. -/ class algebra.finite_type : Prop := (out : (⊤ : subalgebra R A).fg) /-- An algebra over a commutative ring is `finite_presentation` if it is the quotient of a polynomial ring in `n` variables by a finitely generated ideal. -/ def algebra.finite_presentation : Prop := ∃ (n : ℕ) (f : mv_polynomial (fin n) R →ₐ[R] A), surjective f ∧ f.to_ring_hom.ker.fg namespace module variables {R M N} lemma finite_def : finite R M ↔ (⊤ : submodule R M).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ variables (R M N) @[priority 100] -- see Note [lower instance priority] instance is_noetherian.finite [is_noetherian R M] : finite R M := ⟨is_noetherian.noetherian ⊤⟩ namespace finite variables {R M N} lemma of_surjective [hM : finite R M] (f : M →ₗ[R] N) (hf : surjective f) : finite R N := ⟨begin rw [← linear_map.range_eq_top.2 hf, ← submodule.map_top], exact submodule.fg_map hM.1 end⟩ lemma of_injective [is_noetherian R N] (f : M →ₗ[R] N) (hf : function.injective f) : finite R M := ⟨fg_of_injective f $ linear_map.ker_eq_bot.2 hf⟩ variables (R) instance self : finite R R := ⟨⟨{1}, by simpa only [finset.coe_singleton] using ideal.span_singleton_one⟩⟩ variables {R} instance prod [hM : finite R M] [hN : finite R N] : finite R (M × N) := ⟨begin rw ← submodule.prod_top, exact submodule.fg_prod hM.1 hN.1 end⟩ lemma equiv [hM : finite R M] (e : M ≃ₗ[R] N) : finite R N := of_surjective (e : M →ₗ[R] N) e.surjective section algebra lemma trans [algebra A B] [is_scalar_tower R A B] : ∀ [finite R A] [finite A B], finite R B | ⟨⟨s, hs⟩⟩ ⟨⟨t, ht⟩⟩ := ⟨submodule.fg_def.2 ⟨set.image2 (•) (↑s : set A) (↑t : set B), set.finite.image2 _ s.finite_to_set t.finite_to_set, by rw [set.image2_smul, submodule.span_smul hs (↑t : set B), ht, submodule.restrict_scalars_top]⟩⟩ @[priority 100] -- see Note [lower instance priority] instance finite_type [hRA : finite R A] : algebra.finite_type R A := ⟨subalgebra.fg_of_submodule_fg hRA.1⟩ end algebra end finite end module namespace algebra namespace finite_type lemma self : finite_type R R := ⟨⟨{1}, subsingleton.elim _ _⟩⟩ section open_locale classical protected lemma mv_polynomial (ι : Type*) [fintype ι] : finite_type R (mv_polynomial ι R) := ⟨⟨finset.univ.image mv_polynomial.X, begin rw eq_top_iff, refine λ p, mv_polynomial.induction_on' p (λ u x, finsupp.induction u (subalgebra.algebra_map_mem _ x) (λ i n f hif hn ih, _)) (λ p q ihp ihq, subalgebra.add_mem _ ihp ihq), rw [add_comm, mv_polynomial.monomial_add_single], exact subalgebra.mul_mem _ ih (subalgebra.pow_mem _ (subset_adjoin $ finset.mem_image_of_mem _ $ finset.mem_univ _) _) end⟩⟩ end variables {R A B} lemma of_surjective (hRA : finite_type R A) (f : A →ₐ[R] B) (hf : surjective f) : finite_type R B := ⟨begin convert subalgebra.fg_map _ f hRA.1, simpa only [map_top f, @eq_comm _ ⊤, eq_top_iff, alg_hom.mem_range] using hf end⟩ lemma equiv (hRA : finite_type R A) (e : A ≃ₐ[R] B) : finite_type R B := hRA.of_surjective e e.surjective lemma trans [algebra A B] [is_scalar_tower R A B] (hRA : finite_type R A) (hAB : finite_type A B) : finite_type R B := ⟨fg_trans' hRA.1 hAB.1⟩ /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring whose variables are indexed by a finset. -/ lemma iff_quotient_mv_polynomial : (finite_type R A) ↔ ∃ (s : finset A) (f : (mv_polynomial {x // x ∈ s} R) →ₐ[R] A), (surjective f) := begin split, { rintro ⟨s, hs⟩, use [s, mv_polynomial.aeval coe], intro x, have hrw : (↑s : set A) = (λ (x : A), x ∈ s.val) := rfl, rw [← set.mem_range, ← alg_hom.coe_range, ← adjoin_eq_range, ← hrw, hs], exact mem_top }, { rintro ⟨s, ⟨f, hsur⟩⟩, exact finite_type.of_surjective (finite_type.mv_polynomial R {x // x ∈ s}) f hsur } end /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring whose variables are indexed by a fintype. -/ lemma iff_quotient_mv_polynomial' : (finite_type R A) ↔ ∃ (ι : Type u_2) [fintype ι] (f : (mv_polynomial ι R) →ₐ[R] A), (surjective f) := begin split, { rw iff_quotient_mv_polynomial, rintro ⟨s, ⟨f, hsur⟩⟩, use [{x // x ∈ s}, by apply_instance, f, hsur] }, { rintro ⟨ι, ⟨hfintype, ⟨f, hsur⟩⟩⟩, letI : fintype ι := hfintype, exact finite_type.of_surjective (finite_type.mv_polynomial R ι) f hsur } end /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring in `n` variables. -/ lemma iff_quotient_mv_polynomial'' : (finite_type R A) ↔ ∃ (n : ℕ) (f : (mv_polynomial (fin n) R) →ₐ[R] A), (surjective f) := begin split, { rw iff_quotient_mv_polynomial', rintro ⟨ι, hfintype, ⟨f, hsur⟩⟩, obtain ⟨n, equiv⟩ := @fintype.exists_equiv_fin ι hfintype, replace equiv := mv_polynomial.rename_equiv R (nonempty.some equiv), exact ⟨n, alg_hom.comp f equiv.symm, function.surjective.comp hsur (alg_equiv.symm equiv).surjective⟩ }, { rintro ⟨n, ⟨f, hsur⟩⟩, exact finite_type.of_surjective (finite_type.mv_polynomial R (fin n)) f hsur } end /-- A finitely presented algebra is of finite type. -/ lemma of_finite_presentation : finite_presentation R A → finite_type R A := begin rintro ⟨n, f, hf⟩, apply (finite_type.iff_quotient_mv_polynomial'').2, exact ⟨n, f, hf.1⟩ end end finite_type namespace finite_presentation variables {R A B} /-- An algebra over a Noetherian ring is finitely generated if and only if it is finitely presented. -/ lemma of_finite_type [is_noetherian_ring R] : finite_type R A ↔ finite_presentation R A := begin refine ⟨λ h, _, algebra.finite_type.of_finite_presentation⟩, obtain ⟨n, f, hf⟩ := algebra.finite_type.iff_quotient_mv_polynomial''.1 h, refine ⟨n, f, hf, _⟩, have hnoet : is_noetherian_ring (mv_polynomial (fin n) R) := by apply_instance, replace hnoet := (is_noetherian_ring_iff.1 hnoet).noetherian, exact hnoet f.to_ring_hom.ker, end /-- If `e : A ≃ₐ[R] B` and `A` is finitely presented, then so is `B`. -/ lemma equiv (hfp : finite_presentation R A) (e : A ≃ₐ[R] B) : finite_presentation R B := begin obtain ⟨n, f, hf⟩ := hfp, use [n, alg_hom.comp ↑e f], split, { exact function.surjective.comp e.surjective hf.1 }, suffices hker : (alg_hom.comp ↑e f).to_ring_hom.ker = f.to_ring_hom.ker, { rw hker, exact hf.2 }, { have hco : (alg_hom.comp ↑e f).to_ring_hom = ring_hom.comp ↑e.to_ring_equiv f.to_ring_hom, { have h : (alg_hom.comp ↑e f).to_ring_hom = e.to_alg_hom.to_ring_hom.comp f.to_ring_hom := rfl, have h1 : ↑(e.to_ring_equiv) = (e.to_alg_hom).to_ring_hom := rfl, rw [h, h1] }, rw [ring_hom.ker_eq_comap_bot, hco, ← ideal.comap_comap, ← ring_hom.ker_eq_comap_bot, ring_hom.ker_coe_equiv (alg_equiv.to_ring_equiv e), ring_hom.ker_eq_comap_bot] } end variable (R) /-- The ring of polynomials in finitely many variables is finitely presented. -/ lemma mv_polynomial (ι : Type u_2) [fintype ι] : finite_presentation R (mv_polynomial ι R) := begin obtain ⟨n, equiv⟩ := @fintype.exists_equiv_fin ι _, replace equiv := mv_polynomial.rename_equiv R (nonempty.some equiv), use [n, alg_equiv.to_alg_hom equiv.symm], split, { exact (alg_equiv.symm equiv).surjective }, suffices hinj : function.injective equiv.symm.to_alg_hom.to_ring_hom, { rw [(ring_hom.injective_iff_ker_eq_bot _).1 hinj], exact submodule.fg_bot }, exact (alg_equiv.symm equiv).injective end /-- `R` is finitely presented as `R`-algebra. -/ lemma self : finite_presentation R R := equiv (mv_polynomial R pempty) (mv_polynomial.pempty_alg_equiv R) variable {R} /-- The quotient of a finitely presented algebra by a finitely generated ideal is finitely presented. -/ lemma quotient {I : ideal A} (h : submodule.fg I) (hfp : finite_presentation R A) : finite_presentation R I.quotient := begin obtain ⟨n, f, hf⟩ := hfp, refine ⟨n, (ideal.quotient.mkₐ R I).comp f, _, _⟩, { exact (ideal.quotient.mkₐ_surjective R I).comp hf.1 }, { refine submodule.fg_ker_ring_hom_comp _ _ hf.2 _ hf.1, rwa ideal.quotient.mkₐ_ker R I } end /-- If `f : A →ₐ[R] B` is surjective with finitely generated kernel and `A` is finitely presented, then so is `B`. -/ lemma of_surjective {f : A →ₐ[R] B} (hf : function.surjective f) (hker : f.to_ring_hom.ker.fg) (hfp : finite_presentation R A) : finite_presentation R B := equiv (quotient hker hfp) (ideal.quotient_ker_alg_equiv_of_surjective hf) lemma iff : finite_presentation R A ↔ ∃ n (I : ideal (_root_.mv_polynomial (fin n) R)) (e : I.quotient ≃ₐ[R] A), I.fg := begin refine ⟨λ h,_, λ h, _⟩, { obtain ⟨n, f, hf⟩ := h, use [n, f.to_ring_hom.ker, ideal.quotient_ker_alg_equiv_of_surjective hf.1, hf.2] }, { obtain ⟨n, I, e, hfg⟩ := h, exact equiv (quotient hfg (mv_polynomial R _)) e } end /-- An algebra is finitely presented if and only if it is a quotient of a polynomial ring whose variables are indexed by a fintype by a finitely generated ideal. -/ lemma iff_quotient_mv_polynomial' : finite_presentation R A ↔ ∃ (ι : Type u_2) [fintype ι] (f : (_root_.mv_polynomial ι R) →ₐ[R] A), (surjective f) ∧ f.to_ring_hom.ker.fg := begin split, { rintro ⟨n, f, hfs, hfk⟩, set ulift_var := mv_polynomial.rename_equiv R equiv.ulift, refine ⟨ulift (fin n), infer_instance, f.comp ulift_var.to_alg_hom, hfs.comp ulift_var.surjective, submodule.fg_ker_ring_hom_comp _ _ _ hfk ulift_var.surjective⟩, convert submodule.fg_bot, exact ring_hom.ker_coe_equiv ulift_var.to_ring_equiv, }, { rintro ⟨ι, hfintype, f, hf⟩, haveI : fintype ι := hfintype, obtain ⟨n, equiv⟩ := fintype.exists_equiv_fin ι, replace equiv := mv_polynomial.rename_equiv R (nonempty.some equiv), refine ⟨n, f.comp equiv.symm, hf.1.comp (alg_equiv.symm equiv).surjective, submodule.fg_ker_ring_hom_comp _ f _ hf.2 equiv.symm.surjective⟩, convert submodule.fg_bot, exact ring_hom.ker_coe_equiv (equiv.symm.to_ring_equiv), } end /-- If `A` is a finitely presented `R`-algebra, then `mv_polynomial (fin n) A` is finitely presented as `R`-algebra. -/ lemma mv_polynomial_of_finite_presentation (hfp : finite_presentation R A) (ι : Type*) [fintype ι] : finite_presentation R (_root_.mv_polynomial ι A) := begin obtain ⟨n, e⟩ := fintype.exists_equiv_fin ι, replace e := (mv_polynomial.rename_equiv A (nonempty.some e)).restrict_scalars R, refine equiv _ e.symm, obtain ⟨m, I, e, hfg⟩ := iff.1 hfp, refine equiv _ (mv_polynomial.map_alg_equiv (fin n) e), -- typeclass inference seems to struggle to find this path letI : is_scalar_tower R (_root_.mv_polynomial (fin m) R) (_root_.mv_polynomial (fin m) R) := is_scalar_tower.right, letI : is_scalar_tower R (_root_.mv_polynomial (fin m) R) (_root_.mv_polynomial (fin n) (_root_.mv_polynomial (fin m) R)) := mv_polynomial.is_scalar_tower, refine equiv _ ((@mv_polynomial.quotient_equiv_quotient_mv_polynomial _ (fin n) _ I).restrict_scalars R).symm, refine quotient (submodule.map_fg_of_fg I hfg _) _, refine equiv _ (mv_polynomial.sum_alg_equiv _ _ _), exact equiv (mv_polynomial R (fin (n + m))) (mv_polynomial.rename_equiv R fin_sum_fin_equiv).symm end /-- If `A` is an `R`-algebra and `S` is an `A`-algebra, both finitely presented, then `S` is finitely presented as `R`-algebra. -/ lemma trans [algebra A B] [is_scalar_tower R A B] (hfpA : finite_presentation R A) (hfpB : finite_presentation A B) : finite_presentation R B := begin obtain ⟨n, I, e, hfg⟩ := iff.1 hfpB, exact equiv (quotient hfg (mv_polynomial_of_finite_presentation hfpA _)) (e.restrict_scalars R) end end finite_presentation end algebra end module_and_algebra namespace ring_hom variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C] /-- A ring morphism `A →+* B` is `finite` if `B` is finitely generated as `A`-module. -/ def finite (f : A →+* B) : Prop := by letI : algebra A B := f.to_algebra; exact module.finite A B /-- A ring morphism `A →+* B` is of `finite_type` if `B` is finitely generated as `A`-algebra. -/ def finite_type (f : A →+* B) : Prop := @algebra.finite_type A B _ _ f.to_algebra /-- A ring morphism `A →+* B` is of `finite_presentation` if `B` is finitely presented as `A`-algebra. -/ def finite_presentation (f : A →+* B) : Prop := @algebra.finite_presentation A B _ _ f.to_algebra namespace finite variables (A) lemma id : finite (ring_hom.id A) := module.finite.self A variables {A} lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite := begin letI := f.to_algebra, exact module.finite.of_surjective (algebra.of_id A B).to_linear_map hf end lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite := @module.finite.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra begin fconstructor, intros a b c, simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end hf hg lemma finite_type {f : A →+* B} (hf : f.finite) : finite_type f := @module.finite.finite_type _ _ _ _ f.to_algebra hf end finite namespace finite_type variables (A) lemma id : finite_type (ring_hom.id A) := algebra.finite_type.self A variables {A} lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_type) (hg : surjective g) : (g.comp f).finite_type := @algebra.finite_type.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra hf { to_fun := g, commutes' := λ a, rfl, .. g } hg lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite_type := by { rw ← f.comp_id, exact (id A).comp_surjective hf } lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_type) (hf : f.finite_type) : (g.comp f).finite_type := @algebra.finite_type.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra begin fconstructor, intros a b c, simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end hf hg lemma of_finite_presentation {f : A →+* B} (hf : f.finite_presentation) : f.finite_type := @algebra.finite_type.of_finite_presentation A B _ _ f.to_algebra hf end finite_type namespace finite_presentation variables (A) lemma id : finite_presentation (ring_hom.id A) := algebra.finite_presentation.self A variables {A} lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_presentation) (hg : surjective g) (hker : g.ker.fg) : (g.comp f).finite_presentation := @algebra.finite_presentation.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra { to_fun := g, commutes' := λ a, rfl, .. g } hg hker hf lemma of_surjective (f : A →+* B) (hf : surjective f) (hker : f.ker.fg) : f.finite_presentation := by { rw ← f.comp_id, exact (id A).comp_surjective hf hker} lemma of_finite_type [is_noetherian_ring A] {f : A →+* B} : f.finite_type ↔ f.finite_presentation := @algebra.finite_presentation.of_finite_type A B _ _ f.to_algebra _ lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_presentation) (hf : f.finite_presentation) : (g.comp f).finite_presentation := @algebra.finite_presentation.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra { smul_assoc := λ a b c, begin simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end } hf hg end finite_presentation end ring_hom namespace alg_hom variables {R A B C : Type*} [comm_ring R] variables [comm_ring A] [comm_ring B] [comm_ring C] variables [algebra R A] [algebra R B] [algebra R C] /-- An algebra morphism `A →ₐ[R] B` is finite if it is finite as ring morphism. In other words, if `B` is finitely generated as `A`-module. -/ def finite (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite /-- An algebra morphism `A →ₐ[R] B` is of `finite_type` if it is of finite type as ring morphism. In other words, if `B` is finitely generated as `A`-algebra. -/ def finite_type (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_type /-- An algebra morphism `A →ₐ[R] B` is of `finite_presentation` if it is of finite presentation as ring morphism. In other words, if `B` is finitely presented as `A`-algebra. -/ def finite_presentation (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_presentation namespace finite variables (R A) lemma id : finite (alg_hom.id R A) := ring_hom.finite.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite := ring_hom.finite.comp hg hf lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite := ring_hom.finite.of_surjective f hf lemma finite_type {f : A →ₐ[R] B} (hf : f.finite) : finite_type f := ring_hom.finite.finite_type hf end finite namespace finite_type variables (R A) lemma id : finite_type (alg_hom.id R A) := ring_hom.finite_type.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_type) (hf : f.finite_type) : (g.comp f).finite_type := ring_hom.finite_type.comp hg hf lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_type) (hg : surjective g) : (g.comp f).finite_type := ring_hom.finite_type.comp_surjective hf hg lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite_type := ring_hom.finite_type.of_surjective f hf lemma of_finite_presentation {f : A →ₐ[R] B} (hf : f.finite_presentation) : f.finite_type := ring_hom.finite_type.of_finite_presentation hf end finite_type namespace finite_presentation variables (R A) lemma id : finite_presentation (alg_hom.id R A) := ring_hom.finite_presentation.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_presentation) (hf : f.finite_presentation) : (g.comp f).finite_presentation := ring_hom.finite_presentation.comp hg hf lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_presentation) (hg : surjective g) (hker : g.to_ring_hom.ker.fg) : (g.comp f).finite_presentation := ring_hom.finite_presentation.comp_surjective hf hg hker lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) (hker : f.to_ring_hom.ker.fg) : f.finite_presentation := ring_hom.finite_presentation.of_surjective f hf hker lemma of_finite_type [is_noetherian_ring A] {f : A →ₐ[R] B} : f.finite_type ↔ f.finite_presentation := ring_hom.finite_presentation.of_finite_type end finite_presentation end alg_hom
403ad20ba8da08c88edfbe619266d0748a5def8b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/function/uniform_integrable.lean
789d0c95688e220d7657817d3acce57301e84620
[ "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
48,695
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.function.convergence_in_measure import measure_theory.function.l1_space /-! # Uniform integrability This file contains the definitions for uniform integrability (both in the measure theory sense as well as the probability theory sense). This file also contains the Vitali convergence theorem which estabishes a relation between uniform integrability, convergence in measure and Lp convergence. Uniform integrability plays a vital role in the theory of martingales most notably is used to fomulate the martingale convergence theorem. ## Main definitions * `measure_theory.unif_integrable`: uniform integrability in the measure theory sense. In particular, a sequence of functions `f` is uniformly integrable if for all `ε > 0`, there exists some `δ > 0` such that for all sets `s` of smaller measure than `δ`, the Lp-norm of `f i` restricted `s` is smaller than `ε` for all `i`. * `measure_theory.uniform_integrable`: uniform integrability in the probability theory sense. In particular, a sequence of measurable functions `f` is uniformly integrable in the probability theory sense if it is uniformly integrable in the measure theory sense and has uniformly bounded Lp-norm. # Main results * `measure_theory.unif_integrable_fintype`: a finite sequence of Lp functions is uniformly integrable. * `measure_theory.tendsto_Lp_of_tendsto_ae`: a sequence of Lp functions which is uniformly integrable converges in Lp if they converge almost everywhere. * `measure_theory.tendsto_in_measure_iff_tendsto_Lp`: Vitali convergence theorem: a sequence of Lp functions converges in Lp if and only if it is uniformly integrable and converges in measure. ## Tags uniform integrable, uniformly absolutely continuous integral, Vitali convergence theorem -/ noncomputable theory open_locale classical measure_theory nnreal ennreal topological_space big_operators namespace measure_theory open set filter topological_space variables {α β ι : Type*} {m : measurable_space α} {μ : measure α} [normed_add_comm_group β] /-- Uniform integrability in the measure theory sense. A sequence of functions `f` is said to be uniformly integrable if for all `ε > 0`, there exists some `δ > 0` such that for all sets `s` with measure less than `δ`, the Lp-norm of `f i` restricted on `s` is less than `ε`. Uniform integrablility is also known as uniformly absolutely continuous integrals. -/ def unif_integrable {m : measurable_space α} (f : ι → α → β) (p : ℝ≥0∞) (μ : measure α) : Prop := ∀ ⦃ε : ℝ⦄ (hε : 0 < ε), ∃ (δ : ℝ) (hδ : 0 < δ), ∀ i s, measurable_set s → μ s ≤ ennreal.of_real δ → snorm (s.indicator (f i)) p μ ≤ ennreal.of_real ε /-- In probability theory, a family of measurable functions is uniformly integrable if it is uniformly integrable in the measure theory sense and is uniformly bounded. -/ def uniform_integrable {m : measurable_space α} (f : ι → α → β) (p : ℝ≥0∞) (μ : measure α) : Prop := (∀ i, ae_strongly_measurable (f i) μ) ∧ unif_integrable f p μ ∧ ∃ C : ℝ≥0, ∀ i, snorm (f i) p μ ≤ C namespace uniform_integrable protected lemma ae_strongly_measurable {f : ι → α → β} {p : ℝ≥0∞} (hf : uniform_integrable f p μ) (i : ι) : ae_strongly_measurable (f i) μ := hf.1 i protected lemma unif_integrable {f : ι → α → β} {p : ℝ≥0∞} (hf : uniform_integrable f p μ) : unif_integrable f p μ := hf.2.1 protected lemma mem_ℒp {f : ι → α → β} {p : ℝ≥0∞} (hf : uniform_integrable f p μ) (i : ι) : mem_ℒp (f i) p μ := ⟨hf.1 i, let ⟨_, _, hC⟩ := hf.2 in lt_of_le_of_lt (hC i) ennreal.coe_lt_top⟩ end uniform_integrable section unif_integrable /-! ### `unif_integrable` This section deals with uniform integrability in the measure theory sense. -/ namespace unif_integrable variables {f g : ι → α → β} {p : ℝ≥0∞} protected lemma add (hf : unif_integrable f p μ) (hg : unif_integrable g p μ) (hp : 1 ≤ p) (hf_meas : ∀ i, ae_strongly_measurable (f i) μ) (hg_meas : ∀ i, ae_strongly_measurable (g i) μ) : unif_integrable (f + g) p μ := begin intros ε hε, have hε2 : 0 < ε / 2 := half_pos hε, obtain ⟨δ₁, hδ₁_pos, hfδ₁⟩ := hf hε2, obtain ⟨δ₂, hδ₂_pos, hgδ₂⟩ := hg hε2, refine ⟨min δ₁ δ₂, lt_min hδ₁_pos hδ₂_pos, λ i s hs hμs, _⟩, simp_rw [pi.add_apply, indicator_add'], refine (snorm_add_le ((hf_meas i).indicator hs) ((hg_meas i).indicator hs) hp).trans _, have hε_halves : ennreal.of_real ε = ennreal.of_real (ε / 2) + ennreal.of_real (ε / 2), by rw [← ennreal.of_real_add hε2.le hε2.le, add_halves], rw hε_halves, exact add_le_add (hfδ₁ i s hs (hμs.trans (ennreal.of_real_le_of_real (min_le_left _ _)))) (hgδ₂ i s hs (hμs.trans (ennreal.of_real_le_of_real (min_le_right _ _)))), end protected lemma neg (hf : unif_integrable f p μ) : unif_integrable (-f) p μ := by { simp_rw [unif_integrable, pi.neg_apply, indicator_neg', snorm_neg], exact hf, } protected lemma sub (hf : unif_integrable f p μ) (hg : unif_integrable g p μ) (hp : 1 ≤ p) (hf_meas : ∀ i, ae_strongly_measurable (f i) μ) (hg_meas : ∀ i, ae_strongly_measurable (g i) μ) : unif_integrable (f - g) p μ := by { rw sub_eq_add_neg, exact hf.add hg.neg hp hf_meas (λ i, (hg_meas i).neg), } protected lemma ae_eq (hf : unif_integrable f p μ) (hfg : ∀ n, f n =ᵐ[μ] g n) : unif_integrable g p μ := begin intros ε hε, obtain ⟨δ, hδ_pos, hfδ⟩ := hf hε, refine ⟨δ, hδ_pos, λ n s hs hμs, (le_of_eq $ snorm_congr_ae _).trans (hfδ n s hs hμs)⟩, filter_upwards [hfg n] with x hx, simp_rw [indicator_apply, hx], end end unif_integrable lemma unif_integrable_zero_meas [measurable_space α] {p : ℝ≥0∞} {f : ι → α → β} : unif_integrable f p (0 : measure α) := λ ε hε, ⟨1, one_pos, λ i s hs hμs, by simp⟩ lemma unif_integrable_congr_ae {p : ℝ≥0∞} {f g : ι → α → β} (hfg : ∀ n, f n =ᵐ[μ] g n) : unif_integrable f p μ ↔ unif_integrable g p μ := ⟨λ hf, hf.ae_eq hfg, λ hg, hg.ae_eq (λ n, (hfg n).symm)⟩ lemma tendsto_indicator_ge (f : α → β) (x : α): tendsto (λ M : ℕ, {x | (M : ℝ) ≤ ‖f x‖₊}.indicator f x) at_top (𝓝 0) := begin refine @tendsto_at_top_of_eventually_const _ _ _ _ _ _ _ (nat.ceil (‖f x‖₊ : ℝ) + 1) (λ n hn, _), rw indicator_of_not_mem, simp only [not_le, mem_set_of_eq], refine lt_of_le_of_lt (nat.le_ceil _) _, refine lt_of_lt_of_le (lt_add_one _) _, norm_cast, rwa [ge_iff_le, coe_nnnorm] at hn, end variables (μ) {p : ℝ≥0∞} section variables {f : α → β} /-- This lemma is weaker than `measure_theory.mem_ℒp.integral_indicator_norm_ge_nonneg_le` as the latter provides `0 ≤ M` and does not require the measurability of `f`. -/ lemma mem_ℒp.integral_indicator_norm_ge_le (hf : mem_ℒp f 1 μ) (hmeas : strongly_measurable f) {ε : ℝ} (hε : 0 < ε) : ∃ M : ℝ, ∫⁻ x, ‖{x | M ≤ ‖f x‖₊}.indicator f x‖₊ ∂μ ≤ ennreal.of_real ε := begin have htendsto : ∀ᵐ x ∂μ, tendsto (λ M : ℕ, {x | (M : ℝ) ≤ ‖f x‖₊}.indicator f x) at_top (𝓝 0) := univ_mem' (id $ λ x, tendsto_indicator_ge f x), have hmeas : ∀ M : ℕ, ae_strongly_measurable ({x | (M : ℝ) ≤ ‖f x‖₊}.indicator f) μ, { assume M, apply hf.1.indicator, apply strongly_measurable.measurable_set_le strongly_measurable_const hmeas.nnnorm.measurable.coe_nnreal_real.strongly_measurable }, have hbound : has_finite_integral (λ x, ‖f x‖) μ, { rw mem_ℒp_one_iff_integrable at hf, exact hf.norm.2 }, have := tendsto_lintegral_norm_of_dominated_convergence hmeas hbound _ htendsto, { rw ennreal.tendsto_at_top_zero at this, obtain ⟨M, hM⟩ := this (ennreal.of_real ε) (ennreal.of_real_pos.2 hε), simp only [true_and, ge_iff_le, zero_tsub, zero_le, sub_zero, zero_add, coe_nnnorm, mem_Icc] at hM, refine ⟨M, _⟩, convert hM M le_rfl, ext1 x, simp only [coe_nnnorm, ennreal.of_real_eq_coe_nnreal (norm_nonneg _)], refl }, { refine λ n, univ_mem' (id $ λ x, _), by_cases hx : (n : ℝ) ≤ ‖f x‖, { dsimp, rwa indicator_of_mem }, { dsimp, rw [indicator_of_not_mem, norm_zero], { exact norm_nonneg _ }, { assumption } } } end /-- This lemma is superceded by `measure_theory.mem_ℒp.integral_indicator_norm_ge_nonneg_le` which does not require measurability. -/ lemma mem_ℒp.integral_indicator_norm_ge_nonneg_le_of_meas (hf : mem_ℒp f 1 μ) (hmeas : strongly_measurable f) {ε : ℝ} (hε : 0 < ε) : ∃ M : ℝ, 0 ≤ M ∧ ∫⁻ x, ‖{x | M ≤ ‖f x‖₊}.indicator f x‖₊ ∂μ ≤ ennreal.of_real ε := let ⟨M, hM⟩ := hf.integral_indicator_norm_ge_le μ hmeas hε in ⟨max M 0, le_max_right _ _, by simpa⟩ lemma mem_ℒp.integral_indicator_norm_ge_nonneg_le (hf : mem_ℒp f 1 μ) {ε : ℝ} (hε : 0 < ε) : ∃ M : ℝ, 0 ≤ M ∧ ∫⁻ x, ‖{x | M ≤ ‖f x‖₊}.indicator f x‖₊ ∂μ ≤ ennreal.of_real ε := begin have hf_mk : mem_ℒp (hf.1.mk f) 1 μ := (mem_ℒp_congr_ae hf.1.ae_eq_mk).mp hf, obtain ⟨M, hM_pos, hfM⟩ := hf_mk.integral_indicator_norm_ge_nonneg_le_of_meas μ hf.1.strongly_measurable_mk hε, refine ⟨M, hM_pos, (le_of_eq _).trans hfM⟩, refine lintegral_congr_ae _, filter_upwards [hf.1.ae_eq_mk] with x hx, simp only [indicator_apply, coe_nnnorm, mem_set_of_eq, ennreal.coe_eq_coe, hx.symm], end lemma mem_ℒp.snorm_ess_sup_indicator_norm_ge_eq_zero (hf : mem_ℒp f ∞ μ) (hmeas : strongly_measurable f) : ∃ M : ℝ, snorm_ess_sup ({x | M ≤ ‖f x‖₊}.indicator f) μ = 0 := begin have hbdd : snorm_ess_sup f μ < ∞ := hf.snorm_lt_top, refine ⟨(snorm f ∞ μ + 1).to_real, _⟩, rw snorm_ess_sup_indicator_eq_snorm_ess_sup_restrict, have : μ.restrict {x : α | (snorm f ⊤ μ + 1).to_real ≤ ‖f x‖₊} = 0, { simp only [coe_nnnorm, snorm_exponent_top, measure.restrict_eq_zero], have : {x : α | (snorm_ess_sup f μ + 1).to_real ≤ ‖f x‖} ⊆ {x : α | snorm_ess_sup f μ < ‖f x‖₊}, { intros x hx, rw [mem_set_of_eq, ← ennreal.to_real_lt_to_real hbdd.ne ennreal.coe_lt_top.ne, ennreal.coe_to_real, coe_nnnorm], refine lt_of_lt_of_le _ hx, rw ennreal.to_real_lt_to_real hbdd.ne, { exact ennreal.lt_add_right hbdd.ne one_ne_zero }, { exact (ennreal.add_lt_top.2 ⟨hbdd, ennreal.one_lt_top⟩).ne } }, rw ← nonpos_iff_eq_zero, refine (measure_mono this).trans _, have hle := coe_nnnorm_ae_le_snorm_ess_sup f μ, simp_rw [ae_iff, not_le] at hle, exact nonpos_iff_eq_zero.2 hle }, rw [this, snorm_ess_sup_measure_zero], exact measurable_set_le measurable_const hmeas.nnnorm.measurable.subtype_coe, end /- This lemma is slightly weaker than `measure_theory.mem_ℒp.snorm_indicator_norm_ge_pos_le` as the latter provides `0 < M`. -/ lemma mem_ℒp.snorm_indicator_norm_ge_le (hf : mem_ℒp f p μ) (hmeas : strongly_measurable f) {ε : ℝ} (hε : 0 < ε) : ∃ M : ℝ, snorm ({x | M ≤ ‖f x‖₊}.indicator f) p μ ≤ ennreal.of_real ε := begin by_cases hp_ne_zero : p = 0, { refine ⟨1, hp_ne_zero.symm ▸ _⟩, simp [snorm_exponent_zero] }, by_cases hp_ne_top : p = ∞, { subst hp_ne_top, obtain ⟨M, hM⟩ := hf.snorm_ess_sup_indicator_norm_ge_eq_zero μ hmeas, refine ⟨M, _⟩, simp only [snorm_exponent_top, hM, zero_le] }, obtain ⟨M, hM', hM⟩ := @mem_ℒp.integral_indicator_norm_ge_nonneg_le _ _ _ μ _ (λ x, ‖f x‖^p.to_real) (hf.norm_rpow hp_ne_zero hp_ne_top) _ (real.rpow_pos_of_pos hε p.to_real), refine ⟨M ^(1 / p.to_real), _⟩, rw [snorm_eq_lintegral_rpow_nnnorm hp_ne_zero hp_ne_top, ← ennreal.rpow_one (ennreal.of_real ε)], conv_rhs { rw ← mul_one_div_cancel (ennreal.to_real_pos hp_ne_zero hp_ne_top).ne.symm }, rw [ennreal.rpow_mul, ennreal.rpow_le_rpow_iff (one_div_pos.2 $ ennreal.to_real_pos hp_ne_zero hp_ne_top), ennreal.of_real_rpow_of_pos hε], convert hM, ext1 x, rw [ennreal.coe_rpow_of_nonneg _ ennreal.to_real_nonneg, nnnorm_indicator_eq_indicator_nnnorm, nnnorm_indicator_eq_indicator_nnnorm], have hiff : M ^ (1 / p.to_real) ≤ ‖f x‖₊ ↔ M ≤ ‖‖f x‖ ^ p.to_real‖₊, { rw [coe_nnnorm, coe_nnnorm, real.norm_rpow_of_nonneg (norm_nonneg _), norm_norm, ← real.rpow_le_rpow_iff hM' (real.rpow_nonneg_of_nonneg (norm_nonneg _) _) (one_div_pos.2 $ ennreal.to_real_pos hp_ne_zero hp_ne_top), ← real.rpow_mul (norm_nonneg _), mul_one_div_cancel (ennreal.to_real_pos hp_ne_zero hp_ne_top).ne.symm, real.rpow_one] }, by_cases hx : x ∈ {x : α | M ^ (1 / p.to_real) ≤ ‖f x‖₊}, { rw [set.indicator_of_mem hx,set.indicator_of_mem, real.nnnorm_of_nonneg], refl, change _ ≤ _, rwa ← hiff }, { rw [set.indicator_of_not_mem hx, set.indicator_of_not_mem], { simp [(ennreal.to_real_pos hp_ne_zero hp_ne_top).ne.symm] }, { change ¬ _ ≤ _, rwa ← hiff } } end /-- This lemma implies that a single function is uniformly integrable (in the probability sense). -/ lemma mem_ℒp.snorm_indicator_norm_ge_pos_le (hf : mem_ℒp f p μ) (hmeas : strongly_measurable f) {ε : ℝ} (hε : 0 < ε) : ∃ M : ℝ, 0 < M ∧ snorm ({x | M ≤ ‖f x‖₊}.indicator f) p μ ≤ ennreal.of_real ε := begin obtain ⟨M, hM⟩ := hf.snorm_indicator_norm_ge_le μ hmeas hε, refine ⟨max M 1, lt_of_lt_of_le zero_lt_one (le_max_right _ _), le_trans (snorm_mono (λ x, _)) hM⟩, rw [norm_indicator_eq_indicator_norm, norm_indicator_eq_indicator_norm], refine indicator_le_indicator_of_subset (λ x hx, _) (λ x, norm_nonneg _) x, change max _ _ ≤ _ at hx, -- removing the `change` breaks the proof! exact (max_le_iff.1 hx).1, end end lemma snorm_indicator_le_of_bound {f : α → β} (hp_top : p ≠ ∞) {ε : ℝ} (hε : 0 < ε) {M : ℝ} (hf : ∀ x, ‖f x‖ < M) : ∃ (δ : ℝ) (hδ : 0 < δ), ∀ s, measurable_set s → μ s ≤ ennreal.of_real δ → snorm (s.indicator f) p μ ≤ ennreal.of_real ε := begin by_cases hM : M ≤ 0, { refine ⟨1, zero_lt_one, λ s hs hμ, _⟩, rw (_ : f = 0), { simp [hε.le] }, { ext x, rw [pi.zero_apply, ← norm_le_zero_iff], exact (lt_of_lt_of_le (hf x) hM).le } }, rw not_le at hM, refine ⟨(ε / M) ^ p.to_real, real.rpow_pos_of_pos (div_pos hε hM) _, λ s hs hμ, _⟩, by_cases hp : p = 0, { simp [hp] }, rw snorm_indicator_eq_snorm_restrict hs, have haebdd : ∀ᵐ x ∂μ.restrict s, ‖f x‖ ≤ M, { filter_upwards, exact (λ x, (hf x).le) }, refine le_trans (snorm_le_of_ae_bound haebdd) _, rw [measure.restrict_apply measurable_set.univ, univ_inter, ← ennreal.le_div_iff_mul_le (or.inl _) (or.inl ennreal.of_real_ne_top)], { rw [← one_div, ennreal.rpow_one_div_le_iff (ennreal.to_real_pos hp hp_top)], refine le_trans hμ _, rw [← ennreal.of_real_rpow_of_pos (div_pos hε hM), ennreal.rpow_le_rpow_iff (ennreal.to_real_pos hp hp_top), ennreal.of_real_div_of_pos hM], exact le_rfl }, { simpa only [ennreal.of_real_eq_zero, not_le, ne.def] }, end section variables {f : α → β} /-- Auxiliary lemma for `measure_theory.mem_ℒp.snorm_indicator_le`. -/ lemma mem_ℒp.snorm_indicator_le' (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) (hf : mem_ℒp f p μ) (hmeas : strongly_measurable f) {ε : ℝ} (hε : 0 < ε) : ∃ (δ : ℝ) (hδ : 0 < δ), ∀ s, measurable_set s → μ s ≤ ennreal.of_real δ → snorm (s.indicator f) p μ ≤ 2 * ennreal.of_real ε := begin obtain ⟨M, hMpos, hM⟩ := hf.snorm_indicator_norm_ge_pos_le μ hmeas hε, obtain ⟨δ, hδpos, hδ⟩ := @snorm_indicator_le_of_bound _ _ _ μ _ _ ({x | ‖f x‖ < M}.indicator f) hp_top _ hε M _, { refine ⟨δ, hδpos, λ s hs hμs, _⟩, rw (_ : f = {x : α | M ≤ ‖f x‖₊}.indicator f + {x : α | ‖f x‖ < M}.indicator f), { rw snorm_indicator_eq_snorm_restrict hs, refine le_trans (snorm_add_le _ _ hp_one) _, { exact strongly_measurable.ae_strongly_measurable (hmeas.indicator (measurable_set_le measurable_const hmeas.nnnorm.measurable.subtype_coe)) }, { exact strongly_measurable.ae_strongly_measurable (hmeas.indicator (measurable_set_lt hmeas.nnnorm.measurable.subtype_coe measurable_const)) }, { rw two_mul, refine add_le_add (le_trans (snorm_mono_measure _ measure.restrict_le_self) hM) _, rw ← snorm_indicator_eq_snorm_restrict hs, exact hδ s hs hμs } }, { ext x, by_cases hx : M ≤ ‖f x‖, { rw [pi.add_apply, indicator_of_mem, indicator_of_not_mem, add_zero]; simpa }, { rw [pi.add_apply, indicator_of_not_mem, indicator_of_mem, zero_add]; simpa using hx } } }, { intros x, rw [norm_indicator_eq_indicator_norm, indicator_apply], split_ifs, exacts [h, hMpos] } end /-- This lemma is superceded by `measure_theory.mem_ℒp.snorm_indicator_le` which does not require measurability on `f`. -/ lemma mem_ℒp.snorm_indicator_le_of_meas (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) (hf : mem_ℒp f p μ) (hmeas : strongly_measurable f) {ε : ℝ} (hε : 0 < ε) : ∃ (δ : ℝ) (hδ : 0 < δ), ∀ s, measurable_set s → μ s ≤ ennreal.of_real δ → snorm (s.indicator f) p μ ≤ ennreal.of_real ε := begin obtain ⟨δ, hδpos, hδ⟩ := hf.snorm_indicator_le' μ hp_one hp_top hmeas (half_pos hε), refine ⟨δ, hδpos, λ s hs hμs, le_trans (hδ s hs hμs) _⟩, rw [ennreal.of_real_div_of_pos zero_lt_two, (by norm_num : ennreal.of_real 2 = 2), ennreal.mul_div_cancel']; norm_num, end lemma mem_ℒp.snorm_indicator_le (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) (hf : mem_ℒp f p μ) {ε : ℝ} (hε : 0 < ε) : ∃ (δ : ℝ) (hδ : 0 < δ), ∀ s, measurable_set s → μ s ≤ ennreal.of_real δ → snorm (s.indicator f) p μ ≤ ennreal.of_real ε := begin have hℒp := hf, obtain ⟨⟨f', hf', heq⟩, hnorm⟩ := hf, obtain ⟨δ, hδpos, hδ⟩ := (hℒp.ae_eq heq).snorm_indicator_le_of_meas μ hp_one hp_top hf' hε, refine ⟨δ, hδpos, λ s hs hμs, _⟩, convert hδ s hs hμs using 1, rw [snorm_indicator_eq_snorm_restrict hs, snorm_indicator_eq_snorm_restrict hs], refine snorm_congr_ae heq.restrict, end /-- A constant function is uniformly integrable. -/ lemma unif_integrable_const {g : α → β} (hp : 1 ≤ p) (hp_ne_top : p ≠ ∞) (hg : mem_ℒp g p μ) : unif_integrable (λ n : ι, g) p μ := begin intros ε hε, obtain ⟨δ, hδ_pos, hgδ⟩ := hg.snorm_indicator_le μ hp hp_ne_top hε, exact ⟨δ, hδ_pos, λ i, hgδ⟩, end /-- A single function is uniformly integrable. -/ lemma unif_integrable_subsingleton [subsingleton ι] (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) {f : ι → α → β} (hf : ∀ i, mem_ℒp (f i) p μ) : unif_integrable f p μ := begin intros ε hε, by_cases hι : nonempty ι, { cases hι with i, obtain ⟨δ, hδpos, hδ⟩ := (hf i).snorm_indicator_le μ hp_one hp_top hε, refine ⟨δ, hδpos, λ j s hs hμs, _⟩, convert hδ s hs hμs }, { exact ⟨1, zero_lt_one, λ i, false.elim $ hι $ nonempty.intro i⟩ } end /-- This lemma is less general than `measure_theory.unif_integrable_fintype` which applies to all sequences indexed by a finite type. -/ lemma unif_integrable_fin (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) {n : ℕ} {f : fin n → α → β} (hf : ∀ i, mem_ℒp (f i) p μ) : unif_integrable f p μ := begin revert f, induction n with n h, { exact (λ f hf, unif_integrable_subsingleton μ hp_one hp_top hf) }, intros f hfLp ε hε, set g : fin n → α → β := λ k, f k with hg, have hgLp : ∀ i, mem_ℒp (g i) p μ := λ i, hfLp i, obtain ⟨δ₁, hδ₁pos, hδ₁⟩ := h hgLp hε, obtain ⟨δ₂, hδ₂pos, hδ₂⟩ := (hfLp n).snorm_indicator_le μ hp_one hp_top hε, refine ⟨min δ₁ δ₂, lt_min hδ₁pos hδ₂pos, λ i s hs hμs, _⟩, by_cases hi : i.val < n, { rw (_ : f i = g ⟨i.val, hi⟩), { exact hδ₁ _ s hs (le_trans hμs $ ennreal.of_real_le_of_real $ min_le_left _ _) }, { rw hg, simp } }, { rw (_ : i = n), { exact hδ₂ _ hs (le_trans hμs $ ennreal.of_real_le_of_real $ min_le_right _ _) }, { have hi' := fin.is_lt i, rw nat.lt_succ_iff at hi', rw not_lt at hi, simp [← le_antisymm hi' hi] } } end /-- A finite sequence of Lp functions is uniformly integrable. -/ lemma unif_integrable_finite [finite ι] (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) {f : ι → α → β} (hf : ∀ i, mem_ℒp (f i) p μ) : unif_integrable f p μ := begin obtain ⟨n, hn⟩ := finite.exists_equiv_fin ι, intros ε hε, set g : fin n → α → β := f ∘ hn.some.symm with hgeq, have hg : ∀ i, mem_ℒp (g i) p μ := λ _, hf _, obtain ⟨δ, hδpos, hδ⟩ := unif_integrable_fin μ hp_one hp_top hg hε, refine ⟨δ, hδpos, λ i s hs hμs, _⟩, specialize hδ (hn.some i) s hs hμs, simp_rw [hgeq, function.comp_app, equiv.symm_apply_apply] at hδ, assumption, end end lemma snorm_sub_le_of_dist_bdd {p : ℝ≥0∞} (hp' : p ≠ ∞) {s : set α} (hs : measurable_set[m] s) {f g : α → β} {c : ℝ} (hc : 0 ≤ c) (hf : ∀ x ∈ s, dist (f x) (g x) ≤ c) : snorm (s.indicator (f - g)) p μ ≤ ennreal.of_real c * μ s ^ (1 / p.to_real) := begin by_cases hp : p = 0, { simp [hp], }, have : ∀ x, ‖s.indicator (f - g) x‖ ≤ ‖s.indicator (λ x, c) x‖, { intro x, by_cases hx : x ∈ s, { rw [indicator_of_mem hx, indicator_of_mem hx, pi.sub_apply, ← dist_eq_norm, real.norm_eq_abs, abs_of_nonneg hc], exact hf x hx }, { simp [indicator_of_not_mem hx] } }, refine le_trans (snorm_mono this) _, rw snorm_indicator_const hs hp hp', refine ennreal.mul_le_mul (le_of_eq _) le_rfl, rw [← of_real_norm_eq_coe_nnnorm, real.norm_eq_abs, abs_of_nonneg hc], end /-- A sequence of uniformly integrable functions which converges μ-a.e. converges in Lp. -/ lemma tendsto_Lp_of_tendsto_ae_of_meas [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) {f : ℕ → α → β} {g : α → β} (hf : ∀ n, strongly_measurable (f n)) (hg : strongly_measurable g) (hg' : mem_ℒp g p μ) (hui : unif_integrable f p μ) (hfg : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) : tendsto (λ n, snorm (f n - g) p μ) at_top (𝓝 0) := begin rw ennreal.tendsto_at_top_zero, intros ε hε, by_cases ε < ∞, swap, { rw [not_lt, top_le_iff] at h, exact ⟨0, λ n hn, by simp [h]⟩ }, by_cases hμ : μ = 0, { exact ⟨0, λ n hn, by simp [hμ]⟩ }, have hε' : 0 < ε.to_real / 3 := div_pos (ennreal.to_real_pos (gt_iff_lt.1 hε).ne.symm h.ne) (by norm_num), have hdivp : 0 ≤ 1 / p.to_real, { refine one_div_nonneg.2 _, rw [← ennreal.zero_to_real, ennreal.to_real_le_to_real ennreal.zero_ne_top hp'], exact le_trans ennreal.zero_lt_one.le hp }, have hpow : 0 < (measure_univ_nnreal μ) ^ (1 / p.to_real) := real.rpow_pos_of_pos (measure_univ_nnreal_pos hμ) _, obtain ⟨δ₁, hδ₁, hsnorm₁⟩ := hui hε', obtain ⟨δ₂, hδ₂, hsnorm₂⟩ := hg'.snorm_indicator_le μ hp hp' hε', obtain ⟨t, htm, ht₁, ht₂⟩ := tendsto_uniformly_on_of_ae_tendsto' hf hg hfg (lt_min hδ₁ hδ₂), rw metric.tendsto_uniformly_on_iff at ht₂, specialize ht₂ (ε.to_real / (3 * measure_univ_nnreal μ ^ (1 / p.to_real))) (div_pos (ennreal.to_real_pos (gt_iff_lt.1 hε).ne.symm h.ne) (mul_pos (by norm_num) hpow)), obtain ⟨N, hN⟩ := eventually_at_top.1 ht₂, clear ht₂, refine ⟨N, λ n hn, _⟩, rw [← t.indicator_self_add_compl (f n - g)], refine le_trans (snorm_add_le ((((hf n).sub hg).indicator htm).ae_strongly_measurable) (((hf n).sub hg).indicator htm.compl).ae_strongly_measurable hp) _, rw [sub_eq_add_neg, indicator_add' t, indicator_neg'], refine le_trans (add_le_add_right (snorm_add_le ((hf n).indicator htm).ae_strongly_measurable (hg.indicator htm).neg.ae_strongly_measurable hp) _) _, have hnf : snorm (t.indicator (f n)) p μ ≤ ennreal.of_real (ε.to_real / 3), { refine hsnorm₁ n t htm (le_trans ht₁ _), rw ennreal.of_real_le_of_real_iff hδ₁.le, exact min_le_left _ _ }, have hng : snorm (t.indicator g) p μ ≤ ennreal.of_real (ε.to_real / 3), { refine hsnorm₂ t htm (le_trans ht₁ _), rw ennreal.of_real_le_of_real_iff hδ₂.le, exact min_le_right _ _ }, have hlt : snorm (tᶜ.indicator (f n - g)) p μ ≤ ennreal.of_real (ε.to_real / 3), { specialize hN n hn, have := snorm_sub_le_of_dist_bdd μ hp' htm.compl _ (λ x hx, (dist_comm (g x) (f n x) ▸ (hN x hx).le : dist (f n x) (g x) ≤ ε.to_real / (3 * measure_univ_nnreal μ ^ (1 / p.to_real)))), refine le_trans this _, rw [div_mul_eq_div_mul_one_div, ← ennreal.of_real_to_real (measure_lt_top μ tᶜ).ne, ennreal.of_real_rpow_of_nonneg ennreal.to_real_nonneg hdivp, ← ennreal.of_real_mul, mul_assoc], { refine ennreal.of_real_le_of_real (mul_le_of_le_one_right hε'.le _), rw [mul_comm, mul_one_div, div_le_one], { refine real.rpow_le_rpow ennreal.to_real_nonneg (ennreal.to_real_le_of_le_of_real (measure_univ_nnreal_pos hμ).le _) hdivp, rw [ennreal.of_real_coe_nnreal, coe_measure_univ_nnreal], exact measure_mono (subset_univ _) }, { exact real.rpow_pos_of_pos (measure_univ_nnreal_pos hμ) _ } }, { refine mul_nonneg (hε').le (one_div_nonneg.2 hpow.le) }, { rw div_mul_eq_div_mul_one_div, exact mul_nonneg hε'.le (one_div_nonneg.2 hpow.le) } }, have : ennreal.of_real (ε.to_real / 3) = ε / 3, { rw [ennreal.of_real_div_of_pos (show (0 : ℝ) < 3, by norm_num), ennreal.of_real_to_real h.ne], simp }, rw this at hnf hng hlt, rw [snorm_neg, ← ennreal.add_thirds ε, ← sub_eq_add_neg], exact add_le_add_three hnf hng hlt end /-- A sequence of uniformly integrable functions which converges μ-a.e. converges in Lp. -/ lemma tendsto_Lp_of_tendsto_ae [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) {f : ℕ → α → β} {g : α → β} (hf : ∀ n, ae_strongly_measurable (f n) μ) (hg : mem_ℒp g p μ) (hui : unif_integrable f p μ) (hfg : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) : tendsto (λ n, snorm (f n - g) p μ) at_top (𝓝 0) := begin suffices : tendsto (λ (n : ℕ), snorm ((hf n).mk (f n) - (hg.1.mk g)) p μ) at_top (𝓝 0), { convert this, exact funext (λ n, snorm_congr_ae ((hf n).ae_eq_mk.sub hg.1.ae_eq_mk)), }, refine tendsto_Lp_of_tendsto_ae_of_meas μ hp hp' (λ n, (hf n).strongly_measurable_mk) hg.1.strongly_measurable_mk (hg.ae_eq hg.1.ae_eq_mk) (hui.ae_eq (λ n, (hf n).ae_eq_mk)) _, have h_ae_forall_eq : ∀ᵐ x ∂μ, ∀ n, f n x = (hf n).mk (f n) x, { rw ae_all_iff, exact λ n, (hf n).ae_eq_mk, }, filter_upwards [hfg, h_ae_forall_eq, hg.1.ae_eq_mk] with x hx_tendsto hxf_eq hxg_eq, rw ← hxg_eq, convert hx_tendsto, ext1 n, exact (hxf_eq n).symm, end variables {f : ℕ → α → β} {g : α → β} lemma unif_integrable_of_tendsto_Lp_zero (hp : 1 ≤ p) (hp' : p ≠ ∞) (hf : ∀ n, mem_ℒp (f n) p μ) (hf_tendsto : tendsto (λ n, snorm (f n) p μ) at_top (𝓝 0)) : unif_integrable f p μ := begin intros ε hε, rw ennreal.tendsto_at_top_zero at hf_tendsto, obtain ⟨N, hN⟩ := hf_tendsto (ennreal.of_real ε) (by simpa), set F : fin N → α → β := λ n, f n, have hF : ∀ n, mem_ℒp (F n) p μ := λ n, hf n, obtain ⟨δ₁, hδpos₁, hδ₁⟩ := unif_integrable_fin μ hp hp' hF hε, refine ⟨δ₁, hδpos₁, λ n s hs hμs, _⟩, by_cases hn : n < N, { exact hδ₁ ⟨n, hn⟩ s hs hμs }, { exact (snorm_indicator_le _).trans (hN n (not_lt.1 hn)) }, end /-- Convergence in Lp implies uniform integrability. -/ lemma unif_integrable_of_tendsto_Lp (hp : 1 ≤ p) (hp' : p ≠ ∞) (hf : ∀ n, mem_ℒp (f n) p μ) (hg : mem_ℒp g p μ) (hfg : tendsto (λ n, snorm (f n - g) p μ) at_top (𝓝 0)) : unif_integrable f p μ := begin have : f = (λ n, g) + λ n, f n - g, by { ext1 n, simp, }, rw this, refine unif_integrable.add _ _ hp (λ _, hg.ae_strongly_measurable) (λ n, (hf n).1.sub hg.ae_strongly_measurable), { exact unif_integrable_const μ hp hp' hg, }, { exact unif_integrable_of_tendsto_Lp_zero μ hp hp' (λ n, (hf n).sub hg) hfg, }, end /-- Forward direction of Vitali's convergence theorem: if `f` is a sequence of uniformly integrable functions that converge in measure to some function `g` in a finite measure space, then `f` converge in Lp to `g`. -/ lemma tendsto_Lp_of_tendsto_in_measure [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) (hf : ∀ n, ae_strongly_measurable (f n) μ) (hg : mem_ℒp g p μ) (hui : unif_integrable f p μ) (hfg : tendsto_in_measure μ f at_top g) : tendsto (λ n, snorm (f n - g) p μ) at_top (𝓝 0) := begin refine tendsto_of_subseq_tendsto (λ ns hns, _), obtain ⟨ms, hms, hms'⟩ := tendsto_in_measure.exists_seq_tendsto_ae (λ ε hε, (hfg ε hε).comp hns), exact ⟨ms, tendsto_Lp_of_tendsto_ae μ hp hp' (λ _, hf _) hg (λ ε hε, let ⟨δ, hδ, hδ'⟩ := hui hε in ⟨δ, hδ, λ i s hs hμs, hδ' _ s hs hμs⟩) hms'⟩, end /-- **Vitali's convergence theorem**: A sequence of functions `f` converges to `g` in Lp if and only if it is uniformly integrable and converges to `g` in measure. -/ lemma tendsto_in_measure_iff_tendsto_Lp [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) (hf : ∀ n, mem_ℒp (f n) p μ) (hg : mem_ℒp g p μ) : tendsto_in_measure μ f at_top g ∧ unif_integrable f p μ ↔ tendsto (λ n, snorm (f n - g) p μ) at_top (𝓝 0) := ⟨λ h, tendsto_Lp_of_tendsto_in_measure μ hp hp' (λ n, (hf n).1) hg h.2 h.1, λ h, ⟨tendsto_in_measure_of_tendsto_snorm (lt_of_lt_of_le ennreal.zero_lt_one hp).ne.symm (λ n, (hf n).ae_strongly_measurable) hg.ae_strongly_measurable h, unif_integrable_of_tendsto_Lp μ hp hp' hf hg h⟩⟩ /-- This lemma is superceded by `unif_integrable_of` which do not require `C` to be positive. -/ lemma unif_integrable_of' (hp : 1 ≤ p) (hp' : p ≠ ∞) {f : ι → α → β} (hf : ∀ i, strongly_measurable (f i)) (h : ∀ ε : ℝ, 0 < ε → ∃ C : ℝ≥0, 0 < C ∧ ∀ i, snorm ({x | C ≤ ‖f i x‖₊}.indicator (f i)) p μ ≤ ennreal.of_real ε) : unif_integrable f p μ := begin have hpzero := (lt_of_lt_of_le ennreal.zero_lt_one hp).ne.symm, by_cases hμ : μ set.univ = 0, { rw measure.measure_univ_eq_zero at hμ, exact hμ.symm ▸ unif_integrable_zero_meas }, intros ε hε, obtain ⟨C, hCpos, hC⟩ := h (ε / 2) (half_pos hε), refine ⟨(ε / (2 * C)) ^ ennreal.to_real p, real.rpow_pos_of_pos (div_pos hε (mul_pos two_pos (nnreal.coe_pos.2 hCpos))) _, λ i s hs hμs, _⟩, by_cases hμs' : μ s = 0, { rw (snorm_eq_zero_iff ((hf i).indicator hs).ae_strongly_measurable hpzero).2 (indicator_meas_zero hμs'), norm_num }, calc snorm (indicator s (f i)) p μ ≤ snorm (indicator (s ∩ {x | C ≤ ‖f i x‖₊}) (f i)) p μ + snorm (indicator (s ∩ {x | ‖f i x‖₊ < C}) (f i)) p μ : begin refine le_trans (eq.le _) (snorm_add_le (strongly_measurable.ae_strongly_measurable ((hf i).indicator (hs.inter (strongly_measurable_const.measurable_set_le (hf i).nnnorm)))) (strongly_measurable.ae_strongly_measurable ((hf i).indicator (hs.inter ((hf i).nnnorm.measurable_set_lt strongly_measurable_const)))) hp), congr, change _ = λ x, (s ∩ {x : α | C ≤ ‖f i x‖₊}).indicator (f i) x + (s ∩ {x : α | ‖f i x‖₊ < C}).indicator (f i) x, rw ← set.indicator_union_of_disjoint, { congr, rw [← inter_union_distrib_left, (by { ext, simp [le_or_lt] } : {x : α | C ≤ ‖f i x‖₊} ∪ {x : α | ‖f i x‖₊ < C} = set.univ), inter_univ] }, { refine (disjoint.inf_right' _ _).inf_left' _, rw disjoint_iff_inf_le, rintro x ⟨hx₁ : _ ≤ _, hx₂ : _ < _⟩, exact false.elim (hx₂.ne (eq_of_le_of_not_lt hx₁ (not_lt.2 hx₂.le)).symm) } end ... ≤ snorm (indicator ({x | C ≤ ‖f i x‖₊}) (f i)) p μ + C * μ s ^ (1 / ennreal.to_real p) : begin refine add_le_add (snorm_mono $ λ x, norm_indicator_le_of_subset (inter_subset_right _ _) _ _) _, rw ← indicator_indicator, rw snorm_indicator_eq_snorm_restrict, have : ∀ᵐ x ∂(μ.restrict s), ‖({x : α | ‖f i x‖₊ < C}).indicator (f i) x‖ ≤ C, { refine ae_of_all _ _, simp_rw norm_indicator_eq_indicator_norm, exact indicator_le' (λ x (hx : _ < _), hx.le) (λ _ _, nnreal.coe_nonneg _) }, refine le_trans (snorm_le_of_ae_bound this) _, rw [mul_comm, measure.restrict_apply' hs, univ_inter, ennreal.of_real_coe_nnreal, one_div], exacts [le_rfl, hs], end ... ≤ ennreal.of_real (ε / 2) + C * ennreal.of_real (ε / (2 * C)) : begin refine add_le_add (hC i) (mul_le_mul_left' _ _), rwa [ennreal.rpow_one_div_le_iff (ennreal.to_real_pos hpzero hp'), ennreal.of_real_rpow_of_pos (div_pos hε (mul_pos two_pos (nnreal.coe_pos.2 hCpos)))] end ... ≤ ennreal.of_real (ε / 2) + ennreal.of_real (ε / 2) : begin refine add_le_add_left _ _, rw [← ennreal.of_real_coe_nnreal, ← ennreal.of_real_mul (nnreal.coe_nonneg _), ← div_div, mul_div_cancel' _ (nnreal.coe_pos.2 hCpos).ne.symm], exact le_rfl, end ... ≤ ennreal.of_real ε : begin rw [← ennreal.of_real_add (half_pos hε).le (half_pos hε).le, add_halves], exact le_rfl, end end lemma unif_integrable_of (hp : 1 ≤ p) (hp' : p ≠ ∞) {f : ι → α → β} (hf : ∀ i, ae_strongly_measurable (f i) μ) (h : ∀ ε : ℝ, 0 < ε → ∃ C : ℝ≥0, ∀ i, snorm ({x | C ≤ ‖f i x‖₊}.indicator (f i)) p μ ≤ ennreal.of_real ε) : unif_integrable f p μ := begin set g : ι → α → β := λ i, (hf i).some, refine (unif_integrable_of' μ hp hp' (λ i, (Exists.some_spec $hf i).1) (λ ε hε, _)).ae_eq (λ i, (Exists.some_spec $ hf i).2.symm), obtain ⟨C, hC⟩ := h ε hε, have hCg : ∀ i, snorm ({x | C ≤ ‖g i x‖₊}.indicator (g i)) p μ ≤ ennreal.of_real ε, { intro i, refine le_trans (le_of_eq $ snorm_congr_ae _) (hC i), filter_upwards [(Exists.some_spec $ hf i).2] with x hx, by_cases hfx : x ∈ {x | C ≤ ‖f i x‖₊}, { rw [indicator_of_mem hfx, indicator_of_mem, hx], rwa [mem_set_of, hx] at hfx }, { rw [indicator_of_not_mem hfx, indicator_of_not_mem], rwa [mem_set_of, hx] at hfx } }, refine ⟨max C 1, lt_max_of_lt_right one_pos, λ i, le_trans (snorm_mono (λ x, _)) (hCg i)⟩, rw [norm_indicator_eq_indicator_norm, norm_indicator_eq_indicator_norm], exact indicator_le_indicator_of_subset (λ x hx, le_trans (le_max_left _ _) hx) (λ _, norm_nonneg _) _, end end unif_integrable section uniform_integrable /-! `uniform_integrable` In probability theory, uniform integrability normally refers to the condition that a sequence of function `(fₙ)` satisfies for all `ε > 0`, there exists some `C ≥ 0` such that `∫ x in {|fₙ| ≥ C}, fₙ x ∂μ ≤ ε` for all `n`. In this section, we will develope some API for `uniform_integrable` and prove that `uniform_integrable` is equivalent to this definition of uniform integrability. -/ variables {p : ℝ≥0∞} {f : ι → α → β} lemma uniform_integrable_zero_meas [measurable_space α] : uniform_integrable f p (0 : measure α) := ⟨λ n, ae_strongly_measurable_zero_measure _, unif_integrable_zero_meas, 0, λ i, snorm_measure_zero.le⟩ lemma uniform_integrable.ae_eq {g : ι → α → β} (hf : uniform_integrable f p μ) (hfg : ∀ n, f n =ᵐ[μ] g n) : uniform_integrable g p μ := begin obtain ⟨hfm, hunif, C, hC⟩ := hf, refine ⟨λ i, (hfm i).congr (hfg i), (unif_integrable_congr_ae hfg).1 hunif, C, λ i, _⟩, rw ← snorm_congr_ae (hfg i), exact hC i end lemma uniform_integrable_congr_ae {g : ι → α → β} (hfg : ∀ n, f n =ᵐ[μ] g n) : uniform_integrable f p μ ↔ uniform_integrable g p μ := ⟨λ h, h.ae_eq hfg, λ h, h.ae_eq (λ i, (hfg i).symm)⟩ /-- A finite sequence of Lp functions is uniformly integrable in the probability sense. -/ lemma uniform_integrable_finite [finite ι] (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) (hf : ∀ i, mem_ℒp (f i) p μ) : uniform_integrable f p μ := begin casesI nonempty_fintype ι, refine ⟨λ n, (hf n).1, unif_integrable_finite μ hp_one hp_top hf, _⟩, by_cases hι : nonempty ι, { choose ae_meas hf using hf, set C := (finset.univ.image (λ i : ι, snorm (f i) p μ)).max' ⟨snorm (f hι.some) p μ, finset.mem_image.2 ⟨hι.some, finset.mem_univ _, rfl⟩⟩, refine ⟨C.to_nnreal, λ i, _⟩, rw ennreal.coe_to_nnreal, { exact finset.le_max' _ _ (finset.mem_image.2 ⟨i, finset.mem_univ _, rfl⟩) }, { refine ne_of_lt ((finset.max'_lt_iff _ _).2 (λ y hy, _)), rw finset.mem_image at hy, obtain ⟨i, -, rfl⟩ := hy, exact hf i } }, { exact ⟨0, λ i, false.elim $ hι $ nonempty.intro i⟩ } end /-- A single function is uniformly integrable in the probability sense. -/ lemma uniform_integrable_subsingleton [subsingleton ι] (hp_one : 1 ≤ p) (hp_top : p ≠ ∞) (hf : ∀ i, mem_ℒp (f i) p μ) : uniform_integrable f p μ := uniform_integrable_finite hp_one hp_top hf /-- A constant sequence of functions is uniformly integrable in the probability sense. -/ lemma uniform_integrable_const {g : α → β} (hp : 1 ≤ p) (hp_ne_top : p ≠ ∞) (hg : mem_ℒp g p μ) : uniform_integrable (λ n : ι, g) p μ := ⟨λ i, hg.1, unif_integrable_const μ hp hp_ne_top hg, ⟨(snorm g p μ).to_nnreal, λ i, le_of_eq (ennreal.coe_to_nnreal hg.2.ne).symm⟩⟩ /-- This lemma is superceded by `uniform_integrable_of` which only requires `ae_strongly_measurable`. -/ lemma uniform_integrable_of' [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) (hf : ∀ i, strongly_measurable (f i)) (h : ∀ ε : ℝ, 0 < ε → ∃ C : ℝ≥0, ∀ i, snorm ({x | C ≤ ‖f i x‖₊}.indicator (f i)) p μ ≤ ennreal.of_real ε) : uniform_integrable f p μ := begin refine ⟨λ i, (hf i).ae_strongly_measurable, unif_integrable_of μ hp hp' (λ i, (hf i).ae_strongly_measurable) h, _⟩, obtain ⟨C, hC⟩ := h 1 one_pos, refine ⟨(C * (μ univ ^ (p.to_real⁻¹)) + 1 : ℝ≥0∞).to_nnreal, λ i, _⟩, calc snorm (f i) p μ ≤ snorm ({x : α | ‖f i x‖₊ < C}.indicator (f i)) p μ + snorm ({x : α | C ≤ ‖f i x‖₊}.indicator (f i)) p μ : begin refine le_trans (snorm_mono (λ x, _)) (snorm_add_le (strongly_measurable.ae_strongly_measurable ((hf i).indicator ((hf i).nnnorm.measurable_set_lt strongly_measurable_const))) (strongly_measurable.ae_strongly_measurable ((hf i).indicator (strongly_measurable_const.measurable_set_le (hf i).nnnorm))) hp), { rw [pi.add_apply, indicator_apply], split_ifs with hx, { rw [indicator_of_not_mem, add_zero], simpa using hx }, { rw [indicator_of_mem, zero_add], simpa using hx } } end ... ≤ C * μ univ ^ (p.to_real⁻¹) + 1 : begin have : ∀ᵐ x ∂μ, ‖{x : α | ‖f i x‖₊ < C}.indicator (f i) x‖₊ ≤ C, { refine eventually_of_forall _, simp_rw nnnorm_indicator_eq_indicator_nnnorm, exact indicator_le (λ x (hx : _ < _), hx.le) }, refine add_le_add (le_trans (snorm_le_of_ae_bound this) _) (ennreal.of_real_one ▸ (hC i)), rw [ennreal.of_real_coe_nnreal, mul_comm], exact le_rfl, end ... = (C * (μ univ ^ (p.to_real⁻¹)) + 1 : ℝ≥0∞).to_nnreal : begin rw ennreal.coe_to_nnreal, exact ennreal.add_ne_top.2 ⟨ennreal.mul_ne_top ennreal.coe_ne_top (ennreal.rpow_ne_top_of_nonneg (inv_nonneg.2 ennreal.to_real_nonneg) (measure_lt_top _ _).ne), ennreal.one_ne_top⟩, end end /-- A sequene of functions `(fₙ)` is uniformly integrable in the probability sense if for all `ε > 0`, there exists some `C` such that `∫ x in {|fₙ| ≥ C}, fₙ x ∂μ ≤ ε` for all `n`. -/ lemma uniform_integrable_of [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) (hf : ∀ i, ae_strongly_measurable (f i) μ) (h : ∀ ε : ℝ, 0 < ε → ∃ C : ℝ≥0, ∀ i, snorm ({x | C ≤ ‖f i x‖₊}.indicator (f i)) p μ ≤ ennreal.of_real ε) : uniform_integrable f p μ := begin set g : ι → α → β := λ i, (hf i).some, have hgmeas : ∀ i, strongly_measurable (g i) := λ i, (Exists.some_spec $ hf i).1, have hgeq : ∀ i, g i =ᵐ[μ] f i := λ i, (Exists.some_spec $ hf i).2.symm, refine (uniform_integrable_of' hp hp' hgmeas $ λ ε hε, _).ae_eq hgeq, obtain ⟨C, hC⟩ := h ε hε, refine ⟨C, λ i, le_trans (le_of_eq $ snorm_congr_ae _) (hC i)⟩, filter_upwards [(Exists.some_spec $ hf i).2] with x hx, by_cases hfx : x ∈ {x | C ≤ ‖f i x‖₊}, { rw [indicator_of_mem hfx, indicator_of_mem, hx], rwa [mem_set_of, hx] at hfx }, { rw [indicator_of_not_mem hfx, indicator_of_not_mem], rwa [mem_set_of, hx] at hfx } end /-- This lemma is superceded by `uniform_integrable.spec` which does not require measurability. -/ lemma uniform_integrable.spec' (hp : p ≠ 0) (hp' : p ≠ ∞) (hf : ∀ i, strongly_measurable (f i)) (hfu : uniform_integrable f p μ) {ε : ℝ} (hε : 0 < ε) : ∃ C : ℝ≥0, ∀ i, snorm ({x | C ≤ ‖f i x‖₊}.indicator (f i)) p μ ≤ ennreal.of_real ε := begin obtain ⟨-, hfu, M, hM⟩ := hfu, obtain ⟨δ, hδpos, hδ⟩ := hfu hε, obtain ⟨C, hC⟩ : ∃ C : ℝ≥0, ∀ i, μ {x | C ≤ ‖f i x‖₊} ≤ ennreal.of_real δ, { by_contra hcon, push_neg at hcon, choose ℐ hℐ using hcon, lift δ to ℝ≥0 using hδpos.le, have : ∀ C : ℝ≥0, C • (δ : ℝ≥0∞) ^ (1 / p.to_real) ≤ snorm (f (ℐ C)) p μ, { intros C, calc C • (δ : ℝ≥0∞) ^ (1 / p.to_real) ≤ C • μ {x | C ≤ ‖f (ℐ C) x‖₊} ^ (1 / p.to_real): begin rw [ennreal.smul_def, ennreal.smul_def, smul_eq_mul, smul_eq_mul], simp_rw ennreal.of_real_coe_nnreal at hℐ, refine ennreal.mul_le_mul le_rfl (ennreal.rpow_le_rpow (hℐ C).le (one_div_nonneg.2 ennreal.to_real_nonneg)), end ... ≤ snorm ({x | C ≤ ‖f (ℐ C) x‖₊}.indicator (f (ℐ C))) p μ : begin refine snorm_indicator_ge_of_bdd_below hp hp' _ (measurable_set_le measurable_const (hf _).nnnorm.measurable) (eventually_of_forall $ λ x hx, _), rwa [nnnorm_indicator_eq_indicator_nnnorm, indicator_of_mem hx], end ... ≤ snorm (f (ℐ C)) p μ : snorm_indicator_le _ }, specialize this ((2 * (max M 1) * (δ⁻¹ ^ (1 / p.to_real)))), rw [ennreal.coe_rpow_of_nonneg _ (one_div_nonneg.2 ennreal.to_real_nonneg), ← ennreal.coe_smul, smul_eq_mul, mul_assoc, nnreal.inv_rpow, inv_mul_cancel (nnreal.rpow_pos (nnreal.coe_pos.1 hδpos)).ne.symm, mul_one, ennreal.coe_mul, ← nnreal.inv_rpow] at this, refine (lt_of_le_of_lt (le_trans (hM $ ℐ $ 2 * (max M 1) * (δ⁻¹ ^ (1 / p.to_real))) (le_max_left M 1)) (lt_of_lt_of_le _ this)).ne rfl, rw [← ennreal.coe_one, ← with_top.coe_max, ← ennreal.coe_mul, ennreal.coe_lt_coe], exact lt_two_mul_self (lt_max_of_lt_right one_pos) }, exact ⟨C, λ i, hδ i _ (measurable_set_le measurable_const (hf i).nnnorm.measurable) (hC i)⟩, end lemma uniform_integrable.spec (hp : p ≠ 0) (hp' : p ≠ ∞) (hfu : uniform_integrable f p μ) {ε : ℝ} (hε : 0 < ε) : ∃ C : ℝ≥0, ∀ i, snorm ({x | C ≤ ‖f i x‖₊}.indicator (f i)) p μ ≤ ennreal.of_real ε := begin set g : ι → α → β := λ i, (hfu.1 i).some, have hgmeas : ∀ i, strongly_measurable (g i) := λ i, (Exists.some_spec $ hfu.1 i).1, have hgunif : uniform_integrable g p μ := hfu.ae_eq (λ i, (Exists.some_spec $ hfu.1 i).2), obtain ⟨C, hC⟩ := hgunif.spec' hp hp' hgmeas hε, refine ⟨C, λ i, le_trans (le_of_eq $ snorm_congr_ae _) (hC i)⟩, filter_upwards [(Exists.some_spec $ hfu.1 i).2] with x hx, by_cases hfx : x ∈ {x | C ≤ ‖f i x‖₊}, { rw [indicator_of_mem hfx, indicator_of_mem, hx], rwa [mem_set_of, hx] at hfx }, { rw [indicator_of_not_mem hfx, indicator_of_not_mem], rwa [mem_set_of, hx] at hfx } end /-- The definition of uniform integrable in mathlib is equivalent to the definition commonly found in literature. -/ lemma uniform_integrable_iff [is_finite_measure μ] (hp : 1 ≤ p) (hp' : p ≠ ∞) : uniform_integrable f p μ ↔ (∀ i, ae_strongly_measurable (f i) μ) ∧ ∀ ε : ℝ, 0 < ε → ∃ C : ℝ≥0, ∀ i, snorm ({x | C ≤ ‖f i x‖₊}.indicator (f i)) p μ ≤ ennreal.of_real ε := ⟨λ h, ⟨h.1, λ ε, h.spec (lt_of_lt_of_le ennreal.zero_lt_one hp).ne.symm hp'⟩, λ h, uniform_integrable_of hp hp' h.1 h.2⟩ /-- The averaging of a uniformly integrable sequence is also uniformly integrable. -/ lemma uniform_integrable_average (hp : 1 ≤ p) {f : ℕ → α → ℝ} (hf : uniform_integrable f p μ) : uniform_integrable (λ n, (∑ i in finset.range n, f i) / n) p μ := begin obtain ⟨hf₁, hf₂, hf₃⟩ := hf, refine ⟨λ n, _, λ ε hε, _, _⟩, { simp_rw div_eq_mul_inv, exact (finset.ae_strongly_measurable_sum' _ (λ i _, hf₁ i)).mul (ae_strongly_measurable_const : ae_strongly_measurable (λ x, (↑n : ℝ)⁻¹) μ) }, { obtain ⟨δ, hδ₁, hδ₂⟩ := hf₂ hε, refine ⟨δ, hδ₁, λ n s hs hle, _⟩, simp_rw [div_eq_mul_inv, finset.sum_mul, set.indicator_finset_sum], refine le_trans (snorm_sum_le (λ i hi, ((hf₁ i).mul_const (↑n)⁻¹).indicator hs) hp) _, have : ∀ i, s.indicator (f i * (↑n)⁻¹) = (↑n : ℝ)⁻¹ • s.indicator (f i), { intro i, rw [mul_comm, (_ : (↑n)⁻¹ * f i = λ ω, (↑n : ℝ)⁻¹ • f i ω)], { rw set.indicator_const_smul s (↑n)⁻¹ (f i), refl }, { refl } }, simp_rw [this, snorm_const_smul, ← finset.mul_sum, nnnorm_inv, real.nnnorm_coe_nat], by_cases hn : (↑(↑n : ℝ≥0)⁻¹ : ℝ≥0∞) = 0, { simp only [hn, zero_mul, zero_le] }, refine le_trans _ (_ : ↑(↑n : ℝ≥0)⁻¹ * (n • ennreal.of_real ε) ≤ ennreal.of_real ε), { refine (ennreal.mul_le_mul_left hn ennreal.coe_ne_top).2 _, conv_rhs { rw ← finset.card_range n }, exact finset.sum_le_card_nsmul _ _ _ (λ i hi, hδ₂ _ _ hs hle) }, { simp only [ennreal.coe_eq_zero, inv_eq_zero, nat.cast_eq_zero] at hn, rw [nsmul_eq_mul, ← mul_assoc, ennreal.coe_inv, ennreal.coe_nat, ennreal.inv_mul_cancel _ (ennreal.nat_ne_top _), one_mul], { exact le_rfl }, all_goals { simpa only [ne.def, nat.cast_eq_zero] } } }, { obtain ⟨C, hC⟩ := hf₃, simp_rw [div_eq_mul_inv, finset.sum_mul], refine ⟨C, λ n, (snorm_sum_le (λ i hi, (hf₁ i).mul_const (↑n)⁻¹) hp).trans _⟩, have : ∀ i, (λ ω, f i ω * (↑n)⁻¹) = (↑n : ℝ)⁻¹ • λ ω, f i ω, { intro i, ext ω, simp only [mul_comm, pi.smul_apply, algebra.id.smul_eq_mul] }, simp_rw [this, snorm_const_smul, ← finset.mul_sum, nnnorm_inv, real.nnnorm_coe_nat], by_cases hn : (↑(↑n : ℝ≥0)⁻¹ : ℝ≥0∞) = 0, { simp only [hn, zero_mul, zero_le] }, refine le_trans _ (_ : ↑(↑n : ℝ≥0)⁻¹ * (n • C : ℝ≥0∞) ≤ C), { refine (ennreal.mul_le_mul_left hn ennreal.coe_ne_top).2 _, conv_rhs { rw ← finset.card_range n }, exact finset.sum_le_card_nsmul _ _ _ (λ i hi, hC i) }, { simp only [ennreal.coe_eq_zero, inv_eq_zero, nat.cast_eq_zero] at hn, rw [nsmul_eq_mul, ← mul_assoc, ennreal.coe_inv, ennreal.coe_nat, ennreal.inv_mul_cancel _ (ennreal.nat_ne_top _), one_mul], { exact le_rfl }, all_goals { simpa only [ne.def, nat.cast_eq_zero] } } } end end uniform_integrable end measure_theory
3a60b527b2dc7873f896d334524dff1dddbcedc4
8930e38ac0fae2e5e55c28d0577a8e44e2639a6d
/data/equiv/encodable.lean
120a0f47e4e44f4c868275b66f3209392a8dc16e
[ "Apache-2.0" ]
permissive
SG4316/mathlib
3d64035d02a97f8556ad9ff249a81a0a51a3321a
a7846022507b531a8ab53b8af8a91953fceafd3a
refs/heads/master
1,584,869,960,527
1,530,718,645,000
1,530,724,110,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,923
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Mario Carneiro Type class for encodable Types. Note that every encodable Type is countable. -/ import data.equiv.nat open option list nat function /-- An encodable type is a "constructively countable" type. This is where we have an explicit injection `encode : α → nat` and a partial inverse `decode : nat → option α`. This makes the range of `encode` decidable, although it is not decidable if `α` is finite or not. -/ class encodable (α : Type*) := (encode : α → nat) (decode : nat → option α) (encodek : ∀ a, decode (encode a) = some a) namespace encodable variables {α : Type*} {β : Type*} universe u open encodable theorem encode_injective [encodable α] : function.injective (@encode α _) | x y e := option.some.inj $ by rw [← encodek, e, encodek] /- This is not set as an instance because this is usually not the best way to infer decidability. -/ def decidable_eq_of_encodable (α) [encodable α] : decidable_eq α | a b := decidable_of_iff _ encode_injective.eq_iff def of_left_injection [encodable α] (f : β → α) (finv : α → option β) (linv : ∀ b, finv (f b) = some b) : encodable β := ⟨λ b, encode (f b), λ n, (decode α n).bind finv, λ b, by simp [encodable.encodek, option.bind, linv]⟩ def of_left_inverse [encodable α] (f : β → α) (finv : α → β) (linv : ∀ b, finv (f b) = b) : encodable β := of_left_injection f (some ∘ finv) (λ b, congr_arg some (linv b)) def of_equiv (α) [encodable α] (e : β ≃ α) : encodable β := of_left_inverse e e.symm e.left_inv @[simp] theorem encode_of_equiv {α β} [encodable α] (e : β ≃ α) (b : β) : @encode _ (of_equiv _ e) b = encode (e b) := rfl @[simp] theorem decode_of_equiv {α β} [encodable α] (e : β ≃ α) (n : ℕ) : @decode _ (of_equiv _ e) n = (decode α n).map e.symm := rfl instance nat : encodable nat := ⟨id, some, λ a, rfl⟩ @[simp] theorem encode_nat (n : ℕ) : encode n = n := rfl @[simp] theorem decode_nat (n : ℕ) : decode ℕ n = some n := rfl instance empty : encodable empty := ⟨λ a, a.rec _, λ n, none, λ a, a.rec _⟩ instance unit : encodable punit := ⟨λ_, zero, λn, nat.cases_on n (some punit.star) (λ _, none), λ⟨⟩, by simp⟩ @[simp] theorem encode_star : encode punit.star = 0 := rfl @[simp] theorem decode_unit_zero : decode punit 0 = some punit.star := rfl @[simp] theorem decode_unit_succ (n) : decode punit (succ n) = none := rfl instance option {α : Type*} [h : encodable α] : encodable (option α) := ⟨λ o, option.cases_on o nat.zero (λ a, succ (encode a)), λ n, nat.cases_on n (some none) (λ m, (decode α m).map some), λ o, by cases o; dsimp; simp [encodek, nat.succ_ne_zero]⟩ @[simp] theorem encode_none [encodable α] : encode (@none α) = 0 := rfl @[simp] theorem encode_some [encodable α] (a : α) : encode (some a) = succ (encode a) := rfl @[simp] theorem decode_option_zero [encodable α] : decode (option α) 0 = some none := rfl @[simp] theorem decode_option_succ [encodable α] (n) : decode (option α) (succ n) = (decode α n).map some := rfl def decode2 (α) [encodable α] (n : ℕ) : option α := (decode α n).bind (option.guard (λ a, encode a = n)) theorem mem_decode2 [encodable α] {n : ℕ} {a : α} : a ∈ decode2 α n ↔ a ∈ decode α n ∧ encode a = n := by simp [decode2]; exact ⟨λ ⟨_, h₁, rfl, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨_, h₁, rfl, h₂⟩⟩ theorem decode2_inj [encodable α] {n : ℕ} {a₁ a₂ : α} (h₁ : a₁ ∈ decode2 α n) (h₂ : a₂ ∈ decode2 α n) : a₁ = a₂ := encode_injective $ (mem_decode2.1 h₁).2.trans (mem_decode2.1 h₂).2.symm theorem encodek2 [encodable α] (a : α) : decode2 α (encode a) = some a := mem_decode2.2 ⟨encodek _, rfl⟩ section sum variables [encodable α] [encodable β] def encode_sum : α ⊕ β → nat | (sum.inl a) := bit0 $ encode a | (sum.inr b) := bit1 $ encode b def decode_sum (n : nat) : option (α ⊕ β) := match bodd_div2 n with | (ff, m) := (decode α m).map sum.inl | (tt, m) := (decode β m).map sum.inr end instance sum : encodable (α ⊕ β) := ⟨encode_sum, decode_sum, λ s, by cases s; simp [encode_sum, decode_sum, encodek]; refl⟩ @[simp] theorem encode_inl (a : α) : @encode (α ⊕ β) _ (sum.inl a) = bit0 (encode a) := rfl @[simp] theorem encode_inr (b : β) : @encode (α ⊕ β) _ (sum.inr b) = bit1 (encode b) := rfl @[simp] theorem decode_sum_val (n : ℕ) : decode (α ⊕ β) n = decode_sum n := rfl end sum instance bool : encodable bool := of_equiv (unit ⊕ unit) equiv.bool_equiv_unit_sum_unit @[simp] theorem encode_tt : encode tt = 1 := rfl @[simp] theorem encode_ff : encode ff = 0 := rfl @[simp] theorem decode_zero : decode bool 0 = some ff := rfl @[simp] theorem decode_one : decode bool 1 = some tt := rfl theorem decode_ge_two (n) (h : 2 ≤ n) : decode bool n = none := begin suffices : decode_sum n = none, { change (decode_sum n).map _ = none, rw this, refl }, have : 1 ≤ div2 n, { rw [div2_val, nat.le_div_iff_mul_le], exacts [h, dec_trivial] }, cases exists_eq_succ_of_ne_zero (ne_of_gt this) with m e, simp [decode_sum]; cases bodd n; simp [decode_sum]; rw e; refl end section sigma variables {γ : α → Type*} [encodable α] [∀ a, encodable (γ a)] def encode_sigma : sigma γ → ℕ | ⟨a, b⟩ := mkpair (encode a) (encode b) def decode_sigma (n : ℕ) : option (sigma γ) := let (n₁, n₂) := unpair n in (decode α n₁).bind $ λ a, (decode (γ a) n₂).map $ sigma.mk a instance sigma : encodable (sigma γ) := ⟨encode_sigma, decode_sigma, λ ⟨a, b⟩, by simp [encode_sigma, decode_sigma, option.bind, option.map, unpair_mkpair, encodek]⟩ @[simp] theorem decode_sigma_val (n : ℕ) : decode (sigma γ) n = (decode α n.unpair.1).bind (λ a, (decode (γ a) n.unpair.2).map $ sigma.mk a) := show decode_sigma._match_1 _ = _, by cases n.unpair; refl @[simp] theorem encode_sigma_val (a b) : @encode (sigma γ) _ ⟨a, b⟩ = mkpair (encode a) (encode b) := rfl end sigma section prod variables [encodable α] [encodable β] instance prod : encodable (α × β) := of_equiv _ (equiv.sigma_equiv_prod α β).symm @[simp] theorem decode_prod_val (n : ℕ) : decode (α × β) n = (decode α n.unpair.1).bind (λ a, (decode β n.unpair.2).map $ prod.mk a) := show (decode (sigma (λ _, β)) n).map (equiv.sigma_equiv_prod α β) = _, by simp; cases decode α n.unpair.1; simp [option.bind]; cases decode β n.unpair.2; refl @[simp] theorem encode_prod_val (a b) : @encode (α × β) _ (a, b) = mkpair (encode a) (encode b) := rfl end prod section subtype open subtype decidable variable {P : α → Prop} variable [encA : encodable α] variable [decP : decidable_pred P] include encA def encode_subtype : {a : α // P a} → nat | ⟨v, h⟩ := encode v include decP def decode_subtype (v : nat) : option {a : α // P a} := (decode α v).bind $ λ a, if h : P a then some ⟨a, h⟩ else none instance subtype : encodable {a : α // P a} := ⟨encode_subtype, decode_subtype, λ ⟨v, h⟩, by simp [encode_subtype, decode_subtype, encodek, h]⟩ end subtype instance fin (n) : encodable (fin n) := of_equiv _ (equiv.fin_equiv_subtype _) instance int : encodable ℤ := of_equiv _ equiv.int_equiv_nat instance ulift [encodable α] : encodable (ulift α) := of_equiv _ equiv.ulift instance plift [encodable α] : encodable (plift α) := of_equiv _ equiv.plift noncomputable def of_inj [encodable β] (f : α → β) (hf : injective f) : encodable α := of_left_injection f (partial_inv f) (λ x, (partial_inv_of_injective hf _ _).2 rfl) end encodable /- Choice function for encodable types and decidable predicates. We provide the following API choose {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] : (∃ x, p x) → α := choose_spec {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := -/ namespace encodable section find_a variables {α : Type*} (p : α → Prop) [encodable α] [decidable_pred p] private def good : option α → Prop | (some a) := p a | none := false private def decidable_good : decidable_pred (good p) | n := by cases n; unfold good; apply_instance local attribute [instance] decidable_good open encodable variable {p} def choose_x (h : ∃ x, p x) : {a:α // p a} := have ∃ n, good p (decode α n), from let ⟨w, pw⟩ := h in ⟨encode w, by simp [good, encodek, pw]⟩, match _, nat.find_spec this : ∀ o, good p o → {a // p a} with | some a, h := ⟨a, h⟩ end def choose (h : ∃ x, p x) : α := (choose_x h).1 lemma choose_spec (h : ∃ x, p x) : p (choose h) := (choose_x h).2 end find_a theorem axiom_of_choice {α : Type*} {β : α → Type*} {R : Π x, β x → Prop} [Π a, encodable (β a)] [∀ x y, decidable (R x y)] (H : ∀x, ∃y, R x y) : ∃f:Πa, β a, ∀x, R x (f x) := ⟨λ x, choose (H x), λ x, choose_spec (H x)⟩ theorem skolem {α : Type*} {β : α → Type*} {P : Π x, β x → Prop} [c : Π a, encodable (β a)] [d : ∀ x y, decidable (P x y)] : (∀x, ∃y, P x y) ↔ ∃f : Π a, β a, (∀x, P x (f x)) := ⟨axiom_of_choice, λ ⟨f, H⟩ x, ⟨_, H x⟩⟩ end encodable namespace quot open encodable variables {α : Type*} {s : setoid α} [@decidable_rel α (≈)] [encodable α] -- Choose equivalence class representative def rep (q : quotient s) : α := choose (exists_rep q) theorem rep_spec (q : quotient s) : ⟦rep q⟧ = q := choose_spec (exists_rep q) def encodable_quotient : encodable (quotient s) := ⟨λ q, encode (rep q), λ n, quotient.mk <$> decode α n, λ q, quot.induction_on q $ λ l, by rw encodek; exact congr_arg some (rep_spec _)⟩ end quot
db36eec42aeaedb4552a5a285317be10bc4d5b7c
367134ba5a65885e863bdc4507601606690974c1
/src/control/bitraversable/instances.lean
37b46e8e5e6a6c3ea84c63aefd238da2ea9f71cd
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
4,396
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import control.bitraversable.lemmas import control.traversable.lemmas /-! # bitraversable instances ## Instances * prod * sum * const * flip * bicompl * bicompr ## References * Hackage: <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html> ## Tags traversable bitraversable functor bifunctor applicative -/ universes u v w variables {t : Type u → Type u → Type u} [bitraversable t] section variables {F : Type u → Type u} [applicative F] def prod.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α × β → F (α' × β') | (x,y) := prod.mk <$> f x <*> f' y instance : bitraversable prod := { bitraverse := @prod.bitraverse } instance : is_lawful_bitraversable prod := by constructor; introsI; cases x; simp [bitraverse,prod.bitraverse] with functor_norm; refl open functor def sum.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α ⊕ β → F (α' ⊕ β') | (sum.inl x) := sum.inl <$> f x | (sum.inr x) := sum.inr <$> f' x instance : bitraversable sum := { bitraverse := @sum.bitraverse } instance : is_lawful_bitraversable sum := by constructor; introsI; cases x; simp [bitraverse,sum.bitraverse] with functor_norm; refl def const.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : const α β → F (const α' β') := f instance bitraversable.const : bitraversable const := { bitraverse := @const.bitraverse } instance is_lawful_bitraversable.const : is_lawful_bitraversable const := by constructor; introsI; simp [bitraverse,const.bitraverse] with functor_norm; refl def flip.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : flip t α β → F (flip t α' β') := (bitraverse f' f : t β α → F (t β' α')) instance bitraversable.flip : bitraversable (flip t) := { bitraverse := @flip.bitraverse t _ } open is_lawful_bitraversable instance is_lawful_bitraversable.flip [is_lawful_bitraversable t] : is_lawful_bitraversable (flip t) := by constructor; intros; unfreezingI { casesm is_lawful_bitraversable t }; tactic.apply_assumption open bitraversable functor @[priority 10] instance bitraversable.traversable {α} : traversable (t α) := { traverse := @tsnd t _ _ } @[priority 10] instance bitraversable.is_lawful_traversable [is_lawful_bitraversable t] {α} : is_lawful_traversable (t α) := by { constructor; introsI; simp [traverse,comp_tsnd] with functor_norm, { refl }, { simp [tsnd_eq_snd_id], refl }, { simp [tsnd,binaturality,function.comp] with functor_norm } } end open bifunctor traversable is_lawful_traversable is_lawful_bitraversable open function (bicompl bicompr) section bicompl variables (F G : Type u → Type u) [traversable F] [traversable G] def bicompl.bitraverse {m} [applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') : bicompl t F G α α' → m (bicompl t F G β β') := (bitraverse (traverse f) (traverse f') : t (F α) (G α') → m _) instance : bitraversable (bicompl t F G) := { bitraverse := @bicompl.bitraverse t _ F G _ _ } instance [is_lawful_traversable F] [is_lawful_traversable G] [is_lawful_bitraversable t] : is_lawful_bitraversable (bicompl t F G) := begin constructor; introsI; simp [bitraverse, bicompl.bitraverse, bimap, traverse_id, bitraverse_id_id, comp_bitraverse] with functor_norm, { simp [traverse_eq_map_id',bitraverse_eq_bimap_id], }, { revert x, dunfold bicompl, simp [binaturality,naturality_pf] } end end bicompl section bicompr variables (F : Type u → Type u) [traversable F] def bicompr.bitraverse {m} [applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') : bicompr F t α α' → m (bicompr F t β β') := (traverse (bitraverse f f') : F (t α α') → m _) instance : bitraversable (bicompr F t) := { bitraverse := @bicompr.bitraverse t _ F _ } instance [is_lawful_traversable F] [is_lawful_bitraversable t] : is_lawful_bitraversable (bicompr F t) := begin constructor; introsI; simp [bitraverse,bicompr.bitraverse,bitraverse_id_id] with functor_norm, { simp [bitraverse_eq_bimap_id',traverse_eq_map_id'], refl }, { revert x, dunfold bicompr, intro, simp [naturality,binaturality'] } end end bicompr
a7c634fccec3c326289b17c733569c8520a5b027
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/metric_space/completion.lean
f9271f26ee2b8318f89aca9f277155284e8cc27d
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
8,096
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 topology.uniform_space.completion import topology.metric_space.isometry import topology.instances.real /-! # The completion of a metric space Completion of uniform spaces are already defined in `topology.uniform_space.completion`. We show here that the uniform space completion of a metric space inherits a metric space structure, by extending the distance to the completion and checking that it is indeed a distance, and that it defines the same uniformity as the already defined uniform structure on the completion -/ open set filter uniform_space metric open_locale filter topological_space uniformity noncomputable theory universes u v variables {α : Type u} {β : Type v} [pseudo_metric_space α] namespace uniform_space.completion /-- The distance on the completion is obtained by extending the distance on the original space, by uniform continuity. -/ instance : has_dist (completion α) := ⟨completion.extension₂ dist⟩ /-- The new distance is uniformly continuous. -/ protected lemma uniform_continuous_dist : uniform_continuous (λp:completion α × completion α, dist p.1 p.2) := uniform_continuous_extension₂ dist /-- The new distance is continuous. -/ protected lemma continuous_dist [topological_space β] {f g : β → completion α} (hf : continuous f) (hg : continuous g) : continuous (λ x, dist (f x) (g x)) := completion.uniform_continuous_dist.continuous.comp (hf.prod_mk hg : _) /-- The new distance is an extension of the original distance. -/ @[simp] protected lemma dist_eq (x y : α) : dist (x : completion α) y = dist x y := completion.extension₂_coe_coe uniform_continuous_dist _ _ /- Let us check that the new distance satisfies the axioms of a distance, by starting from the properties on α and extending them to `completion α` by continuity. -/ protected lemma dist_self (x : completion α) : dist x x = 0 := begin apply induction_on x, { refine is_closed_eq _ continuous_const, exact completion.continuous_dist continuous_id continuous_id }, { assume a, rw [completion.dist_eq, dist_self] } end protected lemma dist_comm (x y : completion α) : dist x y = dist y x := begin apply induction_on₂ x y, { exact is_closed_eq (completion.continuous_dist continuous_fst continuous_snd) (completion.continuous_dist continuous_snd continuous_fst) }, { assume a b, rw [completion.dist_eq, completion.dist_eq, dist_comm] } end protected lemma dist_triangle (x y z : completion α) : dist x z ≤ dist x y + dist y z := begin apply induction_on₃ x y z, { refine is_closed_le _ (continuous.add _ _); apply_rules [completion.continuous_dist, continuous.fst, continuous.snd, continuous_id] }, { assume a b c, rw [completion.dist_eq, completion.dist_eq, completion.dist_eq], exact dist_triangle a b c } end /-- Elements of the uniformity (defined generally for completions) can be characterized in terms of the distance. -/ protected lemma mem_uniformity_dist (s : set (completion α × completion α)) : s ∈ 𝓤 (completion α) ↔ (∃ε>0, ∀{a b}, dist a b < ε → (a, b) ∈ s) := begin split, { /- Start from an entourage `s`. It contains a closed entourage `t`. Its pullback in `α` is an entourage, so it contains an `ε`-neighborhood of the diagonal by definition of the entourages in metric spaces. Then `t` contains an `ε`-neighborhood of the diagonal in `completion α`, as closed properties pass to the completion. -/ assume hs, rcases mem_uniformity_is_closed hs with ⟨t, ht, ⟨tclosed, ts⟩⟩, have A : {x : α × α | (coe (x.1), coe (x.2)) ∈ t} ∈ uniformity α := uniform_continuous_def.1 (uniform_continuous_coe α) t ht, rcases mem_uniformity_dist.1 A with ⟨ε, εpos, hε⟩, refine ⟨ε, εpos, λx y hxy, _⟩, have : ε ≤ dist x y ∨ (x, y) ∈ t, { apply induction_on₂ x y, { have : {x : completion α × completion α | ε ≤ dist (x.fst) (x.snd) ∨ (x.fst, x.snd) ∈ t} = {p : completion α × completion α | ε ≤ dist p.1 p.2} ∪ t, by ext; simp, rw this, apply is_closed.union _ tclosed, exact is_closed_le continuous_const completion.uniform_continuous_dist.continuous }, { assume x y, rw completion.dist_eq, by_cases h : ε ≤ dist x y, { exact or.inl h }, { have Z := hε (not_le.1 h), simp only [set.mem_set_of_eq] at Z, exact or.inr Z }}}, simp only [not_le.mpr hxy, false_or, not_le] at this, exact ts this }, { /- Start from a set `s` containing an ε-neighborhood of the diagonal in `completion α`. To show that it is an entourage, we use the fact that `dist` is uniformly continuous on `completion α × completion α` (this is a general property of the extension of uniformly continuous functions). Therefore, the preimage of the ε-neighborhood of the diagonal in ℝ is an entourage in `completion α × completion α`. Massaging this property, it follows that the ε-neighborhood of the diagonal is an entourage in `completion α`, and therefore this is also the case of `s`. -/ rintros ⟨ε, εpos, hε⟩, let r : set (ℝ × ℝ) := {p | dist p.1 p.2 < ε}, have : r ∈ uniformity ℝ := metric.dist_mem_uniformity εpos, have T := uniform_continuous_def.1 (@completion.uniform_continuous_dist α _) r this, simp only [uniformity_prod_eq_prod, mem_prod_iff, exists_prop, filter.mem_map, set.mem_set_of_eq] at T, rcases T with ⟨t1, ht1, t2, ht2, ht⟩, refine mem_of_superset ht1 _, have A : ∀a b : completion α, (a, b) ∈ t1 → dist a b < ε, { assume a b hab, have : ((a, b), (a, a)) ∈ t1 ×ˢ t2 := ⟨hab, refl_mem_uniformity ht2⟩, have I := ht this, simp [completion.dist_self, real.dist_eq, completion.dist_comm] at I, exact lt_of_le_of_lt (le_abs_self _) I }, show t1 ⊆ s, { rintros ⟨a, b⟩ hp, have : dist a b < ε := A a b hp, exact hε this }} end /-- If two points are at distance 0, then they coincide. -/ protected lemma eq_of_dist_eq_zero (x y : completion α) (h : dist x y = 0) : x = y := begin /- This follows from the separation of `completion α` and from the description of entourages in terms of the distance. -/ have : separated_space (completion α) := by apply_instance, refine separated_def.1 this x y (λs hs, _), rcases (completion.mem_uniformity_dist s).1 hs with ⟨ε, εpos, hε⟩, rw ← h at εpos, exact hε εpos end /-- Reformulate `completion.mem_uniformity_dist` in terms that are suitable for the definition of the metric space structure. -/ protected lemma uniformity_dist' : 𝓤 (completion α) = (⨅ε:{ε : ℝ // 0 < ε}, 𝓟 {p | dist p.1 p.2 < ε.val}) := begin ext s, rw mem_infi_of_directed, { simp [completion.mem_uniformity_dist, subset_def] }, { rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩, simp [lt_min_iff, (≥)] {contextual := tt} } end protected lemma uniformity_dist : 𝓤 (completion α) = (⨅ ε>0, 𝓟 {p | dist p.1 p.2 < ε}) := by simpa [infi_subtype] using @completion.uniformity_dist' α _ /-- Metric space structure on the completion of a pseudo_metric space. -/ instance : metric_space (completion α) := { dist_self := completion.dist_self, eq_of_dist_eq_zero := completion.eq_of_dist_eq_zero, dist_comm := completion.dist_comm, dist_triangle := completion.dist_triangle, to_uniform_space := by apply_instance, uniformity_dist := completion.uniformity_dist } /-- The embedding of a metric space in its completion is an isometry. -/ lemma coe_isometry : isometry (coe : α → completion α) := isometry_emetric_iff_metric.2 completion.dist_eq @[simp] protected lemma edist_eq (x y : α) : edist (x : completion α) y = edist x y := coe_isometry x y end uniform_space.completion
a6c109f8653d56b8ca87dc7f2a98f960ad287ff9
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/polynomial/induction.lean
10f7f2a91162fe554df8fa1939154667fe4e270d
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
3,067
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.coeff import ring_theory.ideal.basic /-! # Induction on polynomials This file contains lemmas dealing with different flavours of induction on polynomials. See also `data/polynomial/inductions.lean` (with an `s`!). The main result is `polynomial.induction_on`. -/ noncomputable theory open finsupp finset namespace polynomial open_locale polynomial universes u v w x y z variables {R : Type u} {S : Type v} {T : Type w} {ι : Type x} {k : Type y} {A : Type z} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : R[X]} @[elab_as_eliminator] protected lemma induction_on {M : R[X] → Prop} (p : R[X]) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : R), M (C a * X^n) → M (C a * X^(n+1))) : M p := begin have A : ∀{n:ℕ} {a}, M (C a * X^n), { assume n a, induction n with n ih, { simp only [pow_zero, mul_one, h_C] }, { exact h_monomial _ _ ih } }, have B : ∀ (s : finset ℕ), M (s.sum (λ (n : ℕ), C (p.coeff n) * X ^ n)), { apply finset.induction, { convert h_C 0, exact C_0.symm }, { assume n s ns ih, rw sum_insert ns, exact h_add _ _ A ih, } }, rw [← sum_C_mul_X_eq p, polynomial.sum], exact B _ end /-- To prove something about polynomials, it suffices to show the condition is closed under taking sums, and it holds for monomials. -/ @[elab_as_eliminator] protected lemma induction_on' {M : R[X] → Prop} (p : R[X]) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : R), M (monomial n a)) : M p := polynomial.induction_on p (h_monomial 0) h_add (λ n a h, by { rw ← monomial_eq_C_mul_X at ⊢, exact h_monomial _ _ }) open submodule polynomial set variables {f : R[X]} {I : ideal R[X]} /-- If the coefficients of a polynomial belong to an ideal, then that ideal contains the ideal spanned by the coefficients of the polynomial. -/ lemma span_le_of_C_coeff_mem (cf : ∀ (i : ℕ), C (f.coeff i) ∈ I) : ideal.span {g | ∃ i, g = C (f.coeff i)} ≤ I := begin simp only [@eq_comm _ _ (C _)] {single_pass := tt}, exact (ideal.span_le.trans range_subset_iff).mpr cf, end lemma mem_span_C_coeff : f ∈ ideal.span {g : R[X] | ∃ i : ℕ, g = C (coeff f i)} := begin let p := ideal.span {g : R[X] | ∃ i : ℕ, g = C (coeff f i)}, nth_rewrite 0 (sum_C_mul_X_eq f).symm, refine submodule.sum_mem _ (λ n hn, _), dsimp, have : C (coeff f n) ∈ p, by { apply subset_span, simp }, have : (monomial n (1 : R)) • C (coeff f n) ∈ p := p.smul_mem _ this, convert this using 1, simp only [monomial_mul_C, one_mul, smul_eq_mul], rw monomial_eq_C_mul_X, end lemma exists_C_coeff_not_mem : f ∉ I → ∃ i : ℕ, C (coeff f i) ∉ I := not.imp_symm $ λ cf, span_le_of_C_coeff_mem (not_exists_not.mp cf) mem_span_C_coeff end semiring end polynomial
ac27f3448f0462b6fd4724fabdbc558387e14e04
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/linear_algebra/matrix/determinant.lean
01ca391f7a7ccfa833435ec0fc0a2e0fd3684cb5
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,361
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Tim Baanen -/ import data.matrix.pequiv import data.matrix.block import data.fintype.card import group_theory.perm.fin import group_theory.perm.sign import algebra.algebra.basic import tactic.ring import linear_algebra.alternating import linear_algebra.pi /-! # Determinant of a matrix This file defines the determinant of a matrix, `matrix.det`, and its essential properties. ## Main definitions - `matrix.det`: the determinant of a square matrix, as a sum over permutations - `matrix.det_row_multilinear`: the determinant, as an `alternating_map` in the rows of the matrix ## Main results - `det_mul`: the determinant of `A ⬝ B` is the product of determinants - `det_zero_of_row_eq`: the determinant is zero if there is a repeated row - `det_block_diagonal`: the determinant of a block diagonal matrix is a product of the blocks' determinants ## Implementation notes It is possible to configure `simp` to compute determinants. See the file `test/matrix.lean` for some examples. -/ universes u v w z open equiv equiv.perm finset function namespace matrix open_locale matrix big_operators variables {m n : Type*} [decidable_eq n] [fintype n] [decidable_eq m] [fintype m] variables {R : Type v} [comm_ring R] local notation `ε` σ:max := ((sign σ : ℤ ) : R) /-- `det` is an `alternating_map` in the rows of the matrix. -/ def det_row_multilinear : alternating_map R (n → R) R n := ((multilinear_map.mk_pi_algebra R n R).comp_linear_map (linear_map.proj)).alternatization /-- The determinant of a matrix given by the Leibniz formula. -/ abbreviation det (M : matrix n n R) : R := det_row_multilinear M lemma det_apply (M : matrix n n R) : M.det = ∑ σ : perm n, σ.sign • ∏ i, M (σ i) i := multilinear_map.alternatization_apply _ M -- This is what the old definition was. We use it to avoid having to change the old proofs below lemma det_apply' (M : matrix n n R) : M.det = ∑ σ : perm n, ε σ * ∏ i, M (σ i) i := by simp [det_apply, units.smul_def] @[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = ∏ i, d i := begin rw det_apply', refine (finset.sum_eq_single 1 _ _).trans _, { intros σ h1 h2, cases not_forall.1 (mt equiv.ext h2) with x h3, convert mul_zero _, apply finset.prod_eq_zero, { change x ∈ _, simp }, exact if_neg h3 }, { simp }, { simp } end @[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 := (det_row_multilinear : alternating_map R (n → R) R n).map_zero @[simp] lemma det_one : det (1 : matrix n n R) = 1 := by rw [← diagonal_one]; simp [-diagonal_one] @[simp] lemma det_is_empty [is_empty n] {A : matrix n n R} : det A = 1 := by simp [det_apply] lemma det_eq_one_of_card_eq_zero {A : matrix n n R} (h : fintype.card n = 0) : det A = 1 := begin haveI : is_empty n := fintype.card_eq_zero_iff.mp h, exact det_is_empty, end /-- If `n` has only one element, the determinant of an `n` by `n` matrix is just that element. Although `unique` implies `decidable_eq` and `fintype`, the instances might not be syntactically equal. Thus, we need to fill in the args explicitly. -/ @[simp] lemma det_unique {n : Type*} [unique n] [decidable_eq n] [fintype n] (A : matrix n n R) : det A = A (default n) (default n) := by simp [det_apply, univ_unique] lemma det_eq_elem_of_subsingleton [subsingleton n] (A : matrix n n R) (k : n) : det A = A k k := begin convert det_unique _, exact unique_of_subsingleton k end lemma det_eq_elem_of_card_eq_one {A : matrix n n R} (h : fintype.card n = 1) (k : n) : det A = A k k := begin haveI : subsingleton n := fintype.card_le_one_iff_subsingleton.mp h.le, exact det_eq_elem_of_subsingleton _ _ end lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) : ∑ σ : perm n, (ε σ) * ∏ x, (M (σ x) (p x) * N (p x) x) = 0 := begin obtain ⟨i, j, hpij, hij⟩ : ∃ i j, p i = p j ∧ i ≠ j, { rw [← fintype.injective_iff_bijective, injective] at H, push_neg at H, exact H }, exact sum_involution (λ σ _, σ * swap i j) (λ σ _, have ∏ x, M (σ x) (p x) = ∏ x, M ((σ * swap i j) x) (p x), from fintype.prod_equiv (swap i j) _ _ (by simp [apply_swap_eq_self hpij]), by simp [this, sign_swap hij, prod_mul_distrib]) (λ σ _ _, (not_congr mul_swap_eq_iff).mpr hij) (λ _ _, mem_univ _) (λ σ _, mul_swap_involutive i j σ) end @[simp] lemma det_mul (M N : matrix n n R) : det (M ⬝ N) = det M * det N := calc det (M ⬝ N) = ∑ p : n → n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) : by simp only [det_apply', mul_apply, prod_univ_sum, mul_sum, fintype.pi_finset_univ]; rw [finset.sum_comm] ... = ∑ p in (@univ (n → n) _).filter bijective, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) : eq.symm $ sum_subset (filter_subset _ _) (λ f _ hbij, det_mul_aux $ by simpa only [true_and, mem_filter, mem_univ] using hbij) ... = ∑ τ : perm n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (τ i) * N (τ i) i) : sum_bij (λ p h, equiv.of_bijective p (mem_filter.1 h).2) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ h, by injection h) (λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, coe_fn_injective rfl⟩) ... = ∑ σ : perm n, ∑ τ : perm n, (∏ i, N (σ i) i) * ε τ * (∏ j, M (τ j) (σ j)) : by simp only [mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc] ... = ∑ σ : perm n, ∑ τ : perm n, (((∏ i, N (σ i) i) * (ε σ * ε τ)) * ∏ i, M (τ i) i) : sum_congr rfl (λ σ _, fintype.sum_equiv (equiv.mul_right σ⁻¹) _ _ (λ τ, have ∏ j, M (τ j) (σ j) = ∏ j, M ((τ * σ⁻¹) j) j, by { rw ← σ⁻¹.prod_comp, simp only [equiv.perm.coe_mul, apply_inv_self] }, have h : ε σ * ε (τ * σ⁻¹) = ε τ := calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) : by { rw [mul_comm, sign_mul (τ * σ⁻¹)], simp only [int.cast_mul, units.coe_mul] } ... = ε τ : by simp only [inv_mul_cancel_right], by { simp_rw [equiv.coe_mul_right, h], simp only [this] })) ... = det M * det N : by simp only [det_apply', finset.mul_sum, mul_comm, mul_left_comm] /-- The determinant of a matrix, as a monoid homomorphism. -/ def det_monoid_hom : matrix n n R →* R := { to_fun := det, map_one' := det_one, map_mul' := det_mul } @[simp] lemma coe_det_monoid_hom : (det_monoid_hom : matrix n n R → R) = det := rfl /-- On square matrices, `mul_comm` applies under `det`. -/ lemma det_mul_comm (M N : matrix m m R) : det (M ⬝ N) = det (N ⬝ M) := by rw [det_mul, det_mul, mul_comm] /-- On square matrices, `mul_left_comm` applies under `det`. -/ lemma det_mul_left_comm (M N P : matrix m m R) : det (M ⬝ (N ⬝ P)) = det (N ⬝ (M ⬝ P)) := by rw [←matrix.mul_assoc, ←matrix.mul_assoc, det_mul, det_mul_comm M N, ←det_mul] /-- On square matrices, `mul_right_comm` applies under `det`. -/ lemma det_mul_right_comm (M N P : matrix m m R) : det (M ⬝ N ⬝ P) = det (M ⬝ P ⬝ N) := by rw [matrix.mul_assoc, matrix.mul_assoc, det_mul, det_mul_comm N P, ←det_mul] lemma det_units_conj (M : units (matrix m m R)) (N : matrix m m R) : det (↑M ⬝ N ⬝ ↑M⁻¹ : matrix m m R) = det N := by rw [det_mul_right_comm, ←mul_eq_mul, ←mul_eq_mul, units.mul_inv, one_mul] lemma det_units_conj' (M : units (matrix m m R)) (N : matrix m m R) : det (↑M⁻¹ ⬝ N ⬝ ↑M : matrix m m R) = det N := det_units_conj M⁻¹ N /-- Transposing a matrix preserves the determinant. -/ @[simp] lemma det_transpose (M : matrix n n R) : Mᵀ.det = M.det := begin rw [det_apply', det_apply'], refine fintype.sum_bijective _ inv_involutive.bijective _ _ _, intros σ, rw sign_inv, congr' 1, apply fintype.prod_equiv σ, intros, simp end /-- Permuting the columns changes the sign of the determinant. -/ lemma det_permute (σ : perm n) (M : matrix n n R) : matrix.det (λ i, M (σ i)) = σ.sign * M.det := ((det_row_multilinear : alternating_map R (n → R) R n).map_perm M σ).trans (by simp [units.smul_def]) /-- Permuting rows and columns with the same equivalence has no effect. -/ @[simp] lemma det_minor_equiv_self (e : n ≃ m) (A : matrix m m R) : det (A.minor e e) = det A := begin rw [det_apply', det_apply'], apply fintype.sum_equiv (equiv.perm_congr e), intro σ, rw equiv.perm.sign_perm_congr e σ, congr' 1, apply fintype.prod_equiv e, intro i, rw [equiv.perm_congr_apply, equiv.symm_apply_apply, minor_apply], end /-- Reindexing both indices along the same equivalence preserves the determinant. For the `simp` version of this lemma, see `det_minor_equiv_self`; this one is unsuitable because `matrix.reindex_apply` unfolds `reindex` first. -/ lemma det_reindex_self (e : m ≃ n) (A : matrix m m R) : det (reindex e e A) = det A := det_minor_equiv_self e.symm A /-- The determinant of a permutation matrix equals its sign. -/ @[simp] lemma det_permutation (σ : perm n) : matrix.det (σ.to_pequiv.to_matrix : matrix n n R) = σ.sign := by rw [←matrix.mul_one (σ.to_pequiv.to_matrix : matrix n n R), pequiv.to_pequiv_mul_matrix, det_permute, det_one, mul_one] @[simp] lemma det_smul (A : matrix n n R) (c : R) : det (c • A) = c ^ fintype.card n * det A := calc det (c • A) = det (matrix.mul (diagonal (λ _, c)) A) : by rw [smul_eq_diagonal_mul] ... = det (diagonal (λ _, c)) * det A : det_mul _ _ ... = c ^ fintype.card n * det A : by simp [card_univ] /-- Multiplying each row by a fixed `v i` multiplies the determinant by the product of the `v`s. -/ lemma det_mul_row (v : n → R) (A : matrix n n R) : det (λ i j, v j * A i j) = (∏ i, v i) * det A := calc det (λ i j, v j * A i j) = det (A ⬝ diagonal v) : congr_arg det $ by { ext, simp [mul_comm] } ... = (∏ i, v i) * det A : by rw [det_mul, det_diagonal, mul_comm] /-- Multiplying each column by a fixed `v j` multiplies the determinant by the product of the `v`s. -/ lemma det_mul_column (v : n → R) (A : matrix n n R) : det (λ i j, v i * A i j) = (∏ i, v i) * det A := multilinear_map.map_smul_univ _ v A @[simp] lemma det_pow (M : matrix m m R) (n : ℕ) : det (M ^ n) = (det M) ^ n := (det_monoid_hom : matrix m m R →* R).map_pow M n section hom_map variables {S : Type w} [comm_ring S] lemma _root_.ring_hom.map_det (f : R →+* S) (M : matrix n n R) : f M.det = matrix.det (f.map_matrix M) := by simp [matrix.det_apply', f.map_sum, f.map_prod] lemma _root_.ring_equiv.map_det (f : R ≃+* S) (M : matrix n n R) : f M.det = matrix.det (f.map_matrix M) := f.to_ring_hom.map_det _ lemma _root_.alg_hom.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T] (f : S →ₐ[R] T) (M : matrix n n S) : f M.det = matrix.det ((f : S →+* T).map_matrix M) := f.to_ring_hom.map_det _ lemma _root_.alg_equiv.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T] (f : S ≃ₐ[R] T) (M : matrix n n S) : f M.det = matrix.det ((f : S →+* T).map_matrix M) := f.to_alg_hom.map_det _ end hom_map @[simp] lemma det_conj_transpose [star_ring R] (M : matrix m m R) : det (Mᴴ) = star (det M) := ((star_ring_aut : ring_aut R).map_det _).symm.trans $ congr_arg star M.det_transpose section det_zero /-! ### `det_zero` section Prove that a matrix with a repeated column has determinant equal to zero. -/ lemma det_eq_zero_of_row_eq_zero {A : matrix n n R} (i : n) (h : ∀ j, A i j = 0) : det A = 0 := (det_row_multilinear : alternating_map R (n → R) R n).map_coord_zero i (funext h) lemma det_eq_zero_of_column_eq_zero {A : matrix n n R} (j : n) (h : ∀ i, A i j = 0) : det A = 0 := by { rw ← det_transpose, exact det_eq_zero_of_row_eq_zero j h, } variables {M : matrix n n R} {i j : n} /-- If a matrix has a repeated row, the determinant will be zero. -/ theorem det_zero_of_row_eq (i_ne_j : i ≠ j) (hij : M i = M j) : M.det = 0 := (det_row_multilinear : alternating_map R (n → R) R n).map_eq_zero_of_eq M hij i_ne_j /-- If a matrix has a repeated column, the determinant will be zero. -/ theorem det_zero_of_column_eq (i_ne_j : i ≠ j) (hij : ∀ k, M k i = M k j) : M.det = 0 := by { rw [← det_transpose, det_zero_of_row_eq i_ne_j], exact funext hij } end det_zero lemma det_update_row_add (M : matrix n n R) (j : n) (u v : n → R) : det (update_row M j $ u + v) = det (update_row M j u) + det (update_row M j v) := (det_row_multilinear : alternating_map R (n → R) R n).map_add M j u v lemma det_update_column_add (M : matrix n n R) (j : n) (u v : n → R) : det (update_column M j $ u + v) = det (update_column M j u) + det (update_column M j v) := begin rw [← det_transpose, ← update_row_transpose, det_update_row_add], simp [update_row_transpose, det_transpose] end lemma det_update_row_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_row M j $ s • u) = s * det (update_row M j u) := (det_row_multilinear : alternating_map R (n → R) R n).map_smul M j s u lemma det_update_column_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_column M j $ s • u) = s * det (update_column M j u) := begin rw [← det_transpose, ← update_row_transpose, det_update_row_smul], simp [update_row_transpose, det_transpose] end lemma det_update_row_smul' (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_row (s • M) j u) = s ^ (fintype.card n - 1) * det (update_row M j u) := multilinear_map.map_update_smul _ M j s u lemma det_update_column_smul' (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_column (s • M) j u) = s ^ (fintype.card n - 1) * det (update_column M j u) := begin rw [← det_transpose, ← update_row_transpose, transpose_smul, det_update_row_smul'], simp [update_row_transpose, det_transpose] end section det_eq /-! ### `det_eq` section Lemmas showing the determinant is invariant under a variety of operations. -/ lemma det_eq_of_eq_mul_det_one {A B : matrix n n R} (C : matrix n n R) (hC : det C = 1) (hA : A = B ⬝ C) : det A = det B := calc det A = det (B ⬝ C) : congr_arg _ hA ... = det B * det C : det_mul _ _ ... = det B : by rw [hC, mul_one] lemma det_eq_of_eq_det_one_mul {A B : matrix n n R} (C : matrix n n R) (hC : det C = 1) (hA : A = C ⬝ B) : det A = det B := calc det A = det (C ⬝ B) : congr_arg _ hA ... = det C * det B : det_mul _ _ ... = det B : by rw [hC, one_mul] lemma det_update_row_add_self (A : matrix n n R) {i j : n} (hij : i ≠ j) : det (update_row A i (A i + A j)) = det A := by simp [det_update_row_add, det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)] lemma det_update_column_add_self (A : matrix n n R) {i j : n} (hij : i ≠ j) : det (update_column A i (λ k, A k i + A k j)) = det A := by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A], exact det_update_row_add_self Aᵀ hij } lemma det_update_row_add_smul_self (A : matrix n n R) {i j : n} (hij : i ≠ j) (c : R) : det (update_row A i (A i + c • A j)) = det A := by simp [det_update_row_add, det_update_row_smul, det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)] lemma det_update_column_add_smul_self (A : matrix n n R) {i j : n} (hij : i ≠ j) (c : R) : det (update_column A i (λ k, A k i + c • A k j)) = det A := by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A], exact det_update_row_add_smul_self Aᵀ hij c } lemma det_eq_of_forall_row_eq_smul_add_const_aux {A B : matrix n n R} {s : finset n} : ∀ (c : n → R) (hs : ∀ i, i ∉ s → c i = 0) (k : n) (hk : k ∉ s) (A_eq : ∀ i j, A i j = B i j + c i * B k j), det A = det B := begin revert B, refine s.induction_on _ _, { intros A c hs k hk A_eq, have : ∀ i, c i = 0, { intros i, specialize hs i, contrapose! hs, simp [hs] }, congr, ext i j, rw [A_eq, this, zero_mul, add_zero], }, { intros i s hi ih B c hs k hk A_eq, have hAi : A i = B i + c i • B k := funext (A_eq i), rw [@ih (update_row B i (A i)) (function.update c i 0), hAi, det_update_row_add_smul_self], { exact mt (λ h, show k ∈ insert i s, from h ▸ finset.mem_insert_self _ _) hk }, { intros i' hi', rw function.update_apply, split_ifs with hi'i, { refl }, { exact hs i' (λ h, hi' ((finset.mem_insert.mp h).resolve_left hi'i)) } }, { exact λ h, hk (finset.mem_insert_of_mem h) }, { intros i' j', rw [update_row_apply, function.update_apply], split_ifs with hi'i, { simp [hi'i] }, rw [A_eq, update_row_ne (λ (h : k = i), hk $ h ▸ finset.mem_insert_self k s)] } } end /-- If you add multiples of row `B k` to other rows, the determinant doesn't change. -/ lemma det_eq_of_forall_row_eq_smul_add_const {A B : matrix n n R} (c : n → R) (k : n) (hk : c k = 0) (A_eq : ∀ i j, A i j = B i j + c i * B k j) : det A = det B := det_eq_of_forall_row_eq_smul_add_const_aux c (λ i, not_imp_comm.mp $ λ hi, finset.mem_erase.mpr ⟨mt (λ (h : i = k), show c i = 0, from h.symm ▸ hk) hi, finset.mem_univ i⟩) k (finset.not_mem_erase k finset.univ) A_eq lemma det_eq_of_forall_row_eq_smul_add_pred_aux {n : ℕ} (k : fin (n + 1)) : ∀ (c : fin n → R) (hc : ∀ (i : fin n), k < i.succ → c i = 0) {M N : matrix (fin n.succ) (fin n.succ) R} (h0 : ∀ j, M 0 j = N 0 j) (hsucc : ∀ (i : fin n) j, M i.succ j = N i.succ j + c i * M i.cast_succ j), det M = det N := begin refine fin.induction _ (λ k ih, _) k; intros c hc M N h0 hsucc, { congr, ext i j, refine fin.cases (h0 j) (λ i, _) i, rw [hsucc, hc i (fin.succ_pos _), zero_mul, add_zero] }, set M' := update_row M k.succ (N k.succ) with hM', have hM : M = update_row M' k.succ (M' k.succ + c k • M k.cast_succ), { ext i j, by_cases hi : i = k.succ, { simp [hi, hM', hsucc, update_row_self] }, rw [update_row_ne hi, hM', update_row_ne hi] }, have k_ne_succ : k.cast_succ ≠ k.succ := (fin.cast_succ_lt_succ k).ne, have M_k : M k.cast_succ = M' k.cast_succ := (update_row_ne k_ne_succ).symm, rw [hM, M_k, det_update_row_add_smul_self M' k_ne_succ.symm, ih (function.update c k 0)], { intros i hi, rw [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff] at hi, rw function.update_apply, split_ifs with hik, { refl }, exact hc _ (fin.succ_lt_succ_iff.mpr (lt_of_le_of_ne hi (ne.symm hik))) }, { rwa [hM', update_row_ne (fin.succ_ne_zero _).symm] }, intros i j, rw function.update_apply, split_ifs with hik, { rw [zero_mul, add_zero, hM', hik, update_row_self] }, rw [hM', update_row_ne ((fin.succ_injective _).ne hik), hsucc], by_cases hik2 : k < i, { simp [hc i (fin.succ_lt_succ_iff.mpr hik2)] }, rw update_row_ne, apply ne_of_lt, rwa [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff, ← not_lt] end /-- If you add multiples of previous rows to the next row, the determinant doesn't change. -/ lemma det_eq_of_forall_row_eq_smul_add_pred {n : ℕ} {A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n → R) (A_zero : ∀ j, A 0 j = B 0 j) (A_succ : ∀ (i : fin n) j, A i.succ j = B i.succ j + c i * A i.cast_succ j) : det A = det B := det_eq_of_forall_row_eq_smul_add_pred_aux (fin.last _) c (λ i hi, absurd hi (not_lt_of_ge (fin.le_last _))) A_zero A_succ /-- If you add multiples of previous columns to the next columns, the determinant doesn't change. -/ lemma det_eq_of_forall_col_eq_smul_add_pred {n : ℕ} {A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n → R) (A_zero : ∀ i, A i 0 = B i 0) (A_succ : ∀ i (j : fin n), A i j.succ = B i j.succ + c j * A i j.cast_succ) : det A = det B := by { rw [← det_transpose A, ← det_transpose B], exact det_eq_of_forall_row_eq_smul_add_pred c A_zero (λ i j, A_succ j i) } end det_eq @[simp] lemma det_block_diagonal {o : Type*} [fintype o] [decidable_eq o] (M : o → matrix n n R) : (block_diagonal M).det = ∏ k, (M k).det := begin -- Rewrite the determinants as a sum over permutations. simp_rw [det_apply'], -- The right hand side is a product of sums, rewrite it as a sum of products. rw finset.prod_sum, simp_rw [finset.mem_univ, finset.prod_attach_univ, finset.univ_pi_univ], -- We claim that the only permutations contributing to the sum are those that -- preserve their second component. let preserving_snd : finset (equiv.perm (n × o)) := finset.univ.filter (λ σ, ∀ x, (σ x).snd = x.snd), have mem_preserving_snd : ∀ {σ : equiv.perm (n × o)}, σ ∈ preserving_snd ↔ ∀ x, (σ x).snd = x.snd := λ σ, finset.mem_filter.trans ⟨λ h, h.2, λ h, ⟨finset.mem_univ _, h⟩⟩, rw ← finset.sum_subset (finset.subset_univ preserving_snd) _, -- And that these are in bijection with `o → equiv.perm m`. rw (finset.sum_bij (λ (σ : ∀ (k : o), k ∈ finset.univ → equiv.perm n) _, prod_congr_left (λ k, σ k (finset.mem_univ k))) _ _ _ _).symm, { intros σ _, rw mem_preserving_snd, rintros ⟨k, x⟩, simp only [prod_congr_left_apply] }, { intros σ _, rw [finset.prod_mul_distrib, ←finset.univ_product_univ, finset.prod_product, finset.prod_comm], simp only [sign_prod_congr_left, units.coe_prod, int.cast_prod, block_diagonal_apply_eq, prod_congr_left_apply] }, { intros σ σ' _ _ eq, ext x hx k, simp only at eq, have : ∀ k x, prod_congr_left (λ k, σ k (finset.mem_univ _)) (k, x) = prod_congr_left (λ k, σ' k (finset.mem_univ _)) (k, x) := λ k x, by rw eq, simp only [prod_congr_left_apply, prod.mk.inj_iff] at this, exact (this k x).1 }, { intros σ hσ, rw mem_preserving_snd at hσ, have hσ' : ∀ x, (σ⁻¹ x).snd = x.snd, { intro x, conv_rhs { rw [← perm.apply_inv_self σ x, hσ] } }, have mk_apply_eq : ∀ k x, ((σ (x, k)).fst, k) = σ (x, k), { intros k x, ext, { simp only}, { simp only [hσ] } }, have mk_inv_apply_eq : ∀ k x, ((σ⁻¹ (x, k)).fst, k) = σ⁻¹ (x, k), { intros k x, conv_lhs { rw ← perm.apply_inv_self σ (x, k) }, ext, { simp only [apply_inv_self] }, { simp only [hσ'] } }, refine ⟨λ k _, ⟨λ x, (σ (x, k)).fst, λ x, (σ⁻¹ (x, k)).fst, _, _⟩, _, _⟩, { intro x, simp only [mk_apply_eq, inv_apply_self] }, { intro x, simp only [mk_inv_apply_eq, apply_inv_self] }, { apply finset.mem_univ }, { ext ⟨k, x⟩, { simp only [coe_fn_mk, prod_congr_left_apply] }, { simp only [prod_congr_left_apply, hσ] } } }, { intros σ _ hσ, rw mem_preserving_snd at hσ, obtain ⟨⟨k, x⟩, hkx⟩ := not_forall.mp hσ, rw [finset.prod_eq_zero (finset.mem_univ (k, x)), mul_zero], rw [← @prod.mk.eta _ _ (σ (k, x)), block_diagonal_apply_ne], exact hkx } end /-- The determinant of a 2x2 block matrix with the lower-left block equal to zero is the product of the determinants of the diagonal blocks. For the generalization to any number of blocks, see `matrix.upper_block_triangular_det`. -/ lemma upper_two_block_triangular_det (A : matrix m m R) (B : matrix m n R) (D : matrix n n R) : (matrix.from_blocks A B 0 D).det = A.det * D.det := begin classical, simp_rw det_apply', convert (sum_subset (subset_univ ((sum_congr_hom m n).range : set (perm (m ⊕ n))).to_finset) _).symm, rw sum_mul_sum, simp_rw univ_product_univ, rw (sum_bij (λ (σ : perm m × perm n) _, equiv.sum_congr σ.fst σ.snd) _ _ _ _).symm, { intros σ₁₂ h, simp only [], erw [set.mem_to_finset, monoid_hom.mem_range], use σ₁₂, simp only [sum_congr_hom_apply] }, { simp only [forall_prop_of_true, prod.forall, mem_univ], intros σ₁ σ₂, rw fintype.prod_sum_type, simp_rw [equiv.sum_congr_apply, sum.map_inr, sum.map_inl, from_blocks_apply₁₁, from_blocks_apply₂₂], have hr : ∀ (a b c d : R), (a * b) * (c * d) = a * c * (b * d), { intros, ac_refl }, rw hr, congr, rw [sign_sum_congr, units.coe_mul, int.cast_mul] }, { intros σ₁ σ₂ h₁ h₂, dsimp only [], intro h, have h2 : ∀ x, perm.sum_congr σ₁.fst σ₁.snd x = perm.sum_congr σ₂.fst σ₂.snd x, { intro x, exact congr_fun (congr_arg to_fun h) x }, simp only [sum.map_inr, sum.map_inl, perm.sum_congr_apply, sum.forall] at h2, ext, { exact h2.left x }, { exact h2.right x }}, { intros σ hσ, erw [set.mem_to_finset, monoid_hom.mem_range] at hσ, obtain ⟨σ₁₂, hσ₁₂⟩ := hσ, use σ₁₂, rw ←hσ₁₂, simp }, { intros σ hσ hσn, have h1 : ¬ (∀ x, ∃ y, sum.inl y = σ (sum.inl x)), { by_contradiction, rw set.mem_to_finset at hσn, apply absurd (mem_sum_congr_hom_range_of_perm_maps_to_inl _) hσn, rintros x ⟨a, ha⟩, rw [←ha], exact h a }, obtain ⟨a, ha⟩ := not_forall.mp h1, cases hx : σ (sum.inl a) with a2 b, { have hn := (not_exists.mp ha) a2, exact absurd hx.symm hn }, { rw [finset.prod_eq_zero (finset.mem_univ (sum.inl a)), mul_zero], rw [hx, from_blocks_apply₂₁], refl }} end /-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along column 0. -/ lemma det_succ_column_zero {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) : det A = ∑ i : fin n.succ, (-1) ^ (i : ℕ) * A i 0 * det (A.minor i.succ_above fin.succ) := begin rw [matrix.det_apply, finset.univ_perm_fin_succ, ← finset.univ_product_univ], simp only [finset.sum_map, equiv.to_embedding_apply, finset.sum_product, matrix.minor], refine finset.sum_congr rfl (λ i _, fin.cases _ (λ i, _) i), { simp only [fin.prod_univ_succ, matrix.det_apply, finset.mul_sum, equiv.perm.decompose_fin_symm_apply_zero, fin.coe_zero, one_mul, equiv.perm.decompose_fin.symm_sign, equiv.swap_self, if_true, id.def, eq_self_iff_true, equiv.perm.decompose_fin_symm_apply_succ, fin.succ_above_zero, equiv.coe_refl, pow_zero, mul_smul_comm] }, -- `univ_perm_fin_succ` gives a different embedding of `perm (fin n)` into -- `perm (fin n.succ)` than the determinant of the submatrix we want, -- permute `A` so that we get the correct one. have : (-1 : R) ^ (i : ℕ) = i.cycle_range.sign, { simp [fin.sign_cycle_range] }, rw [fin.coe_succ, pow_succ, this, mul_assoc, mul_assoc, mul_left_comm ↑(equiv.perm.sign _), ← det_permute, matrix.det_apply, finset.mul_sum, finset.mul_sum], -- now we just need to move the corresponding parts to the same place refine finset.sum_congr rfl (λ σ _, _), rw [equiv.perm.decompose_fin.symm_sign, if_neg (fin.succ_ne_zero i)], calc ((-1) * σ.sign : ℤ) • ∏ i', A (equiv.perm.decompose_fin.symm (fin.succ i, σ) i') i' = ((-1) * σ.sign : ℤ) • (A (fin.succ i) 0 * ∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (σ i'))) i'.succ) : by simp only [fin.prod_univ_succ, fin.succ_above_cycle_range, equiv.perm.decompose_fin_symm_apply_zero, equiv.perm.decompose_fin_symm_apply_succ] ... = (-1) * (A (fin.succ i) 0 * (σ.sign : ℤ) • ∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (σ i'))) i'.succ) : by simp only [mul_assoc, mul_comm, neg_mul_eq_neg_mul_symm, one_mul, gsmul_eq_mul, neg_inj, neg_smul, fin.succ_above_cycle_range], end /-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along row 0. -/ lemma det_succ_row_zero {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) : det A = ∑ j : fin n.succ, (-1) ^ (j : ℕ) * A 0 j * det (A.minor fin.succ j.succ_above) := by { rw [← det_transpose A, det_succ_column_zero], refine finset.sum_congr rfl (λ i _, _), rw [← det_transpose], simp only [transpose_apply, transpose_minor, transpose_transpose] } /-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along row `i`. -/ lemma det_succ_row {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) (i : fin n.succ) : det A = ∑ j : fin n.succ, (-1) ^ (i + j : ℕ) * A i j * det (A.minor i.succ_above j.succ_above) := begin simp_rw [pow_add, mul_assoc, ← mul_sum], have : det A = (-1 : R) ^ (i : ℕ) * (i.cycle_range⁻¹).sign * det A, { calc det A = ↑((-1 : units ℤ) ^ (i : ℕ) * (-1 : units ℤ) ^ (i : ℕ) : units ℤ) * det A : by simp ... = (-1 : R) ^ (i : ℕ) * (i.cycle_range⁻¹).sign * det A : by simp [-int.units_mul_self] }, rw [this, mul_assoc], congr, rw [← det_permute, det_succ_row_zero], refine finset.sum_congr rfl (λ j _, _), rw [mul_assoc, matrix.minor, matrix.minor], congr, { rw [equiv.perm.inv_def, fin.cycle_range_symm_zero] }, { ext i' j', rw [equiv.perm.inv_def, fin.cycle_range_symm_succ] }, end /-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along column `j`. -/ lemma det_succ_column {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) (j : fin n.succ) : det A = ∑ i : fin n.succ, (-1) ^ (i + j : ℕ) * A i j * det (A.minor i.succ_above j.succ_above) := by { rw [← det_transpose, det_succ_row _ j], refine finset.sum_congr rfl (λ i _, _), rw [add_comm, ← det_transpose, transpose_apply, transpose_minor, transpose_transpose] } /-- Determinant of 0x0 matrix -/ @[simp] lemma det_fin_zero {A : matrix (fin 0) (fin 0) R} : det A = 1 := det_is_empty /-- Determinant of 1x1 matrix -/ lemma det_fin_one (A : matrix (fin 1) (fin 1) R) : det A = A 0 0 := det_unique A /-- Determinant of 2x2 matrix -/ lemma det_fin_two (A : matrix (fin 2) (fin 2) R) : det A = A 0 0 * A 1 1 - A 0 1 * A 1 0 := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], ring end /-- Determinant of 3x3 matrix -/ lemma det_fin_three (A : matrix (fin 3) (fin 3) R) : det A = A 0 0 * A 1 1 * A 2 2 - A 0 0 * A 1 2 * A 2 1 - A 0 1 * A 1 0 * A 2 2 + A 0 1 * A 1 2 * A 2 0 + A 0 2 * A 1 0 * A 2 1 - A 0 2 * A 1 1 * A 2 0 := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], ring end end matrix