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
a62e5fa2b8db702527031736401f760299c10682
59aed81a2ce7741e690907fc374be338f4f88b6f
/src/walks.lean
c93257a9e9f9d2f04555db1c91e142f316928570
[]
no_license
agusakov/math-688-lean
c84d5e1423eb208a0281135f0214b91b30d0ef48
67dc27ebff55a74c6b5a1c469ba04e7981d2e550
refs/heads/main
1,679,699,340,788
1,616,602,782,000
1,616,602,782,000
332,894,454
0
0
null
null
null
null
UTF-8
Lean
false
false
19,688
lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kyle Miller -/ import data.finset.basic import combinatorics.simple_graph.basic import tactic.omega /-! # Walks and paths A walk in a simple graph is a finite sequence of adjacent vertices. A path is a walk that visits each vertex only once. ## Main definitions * `simple_graph.walk` is the type of walks between pairs of vertices * `simple_graph.walk.is_path` is a predicate that determines whether a walk is a path. * `simple_graph.walk.to_path` constructs a path from a walk with the same endpoints. * `simple_graph.exists_walk` is the walk-connectivity relation. * `simple_graph.connected_components` is the quotient of the vertex type by walk-connectivity. * `simple_graph.exists_walk_eq_exists_path` and `simple_graph.exists_walk_eq_eqv_gen` give that walk-connectivity, path-connectivity, and `eqv_gen G.adj` are the each the same relation. * `simple_graph.walk.get_vert` parameterizes the vertices of a walk by natural numbers. * `simple_graph.walk.is_path_iff` characterizes paths as walks for which `get_vert` is injective. ## Tags walks, paths -/ universes u namespace simple_graph variables {V : Type u} (G : simple_graph V) -- lemma that says card of support is equal to length iff it's a path /-- A walk is a sequence of incident edges in a graph, represented here as a sequence of adjacent vertices. -/ inductive walk : V β†’ V β†’ Type u | nil {u : V} : walk u u | cons {u v w : V} (h : G.adj u v) (p : walk v w) : walk u w attribute [refl] walk.nil instance walk.inhabited (v : V) : inhabited (G.walk v v) := ⟨walk.nil⟩ namespace walk variables {G} /-- The length of a walk is the number of edges along it. -/ def length : Ξ  {u v : V}, G.walk u v β†’ β„• | _ _ nil := 0 | _ _ (cons _ q) := q.length.succ /-- The concatenation of two compatible walks. -/ @[trans] def concat : Ξ  {u v w : V}, G.walk u v β†’ G.walk v w β†’ G.walk u w | _ _ _ nil q := q | _ _ _ (cons h p) q := cons h (concat p q) /-- The concatenation of the reverse of the first walk with the second walk. -/ protected def reverse_aux : Ξ  {u v w : V}, G.walk u v β†’ G.walk u w β†’ G.walk v w | _ _ _ nil q := q | _ _ _ (cons h p) q := reverse_aux p (cons (G.sym h) q) /-- Reverse the orientation of a walk. -/ @[symm] def reverse {u v : V} (w : G.walk u v) : G.walk v u := w.reverse_aux nil /-- Get the nth vertex from a path, where if i is greater than the length of the path the result is the endpoint of the path. -/ def get_vert : Ξ  {u v : V} (p : G.walk u v) (i : β„•), V | u v nil _ := u | u v (cons _ _) 0 := u | u v (cons _ q) (i+1) := q.get_vert i variables [decidable_eq V] /-- The support of a walk is the finite set of vertices it visits. -/ def support : Ξ  {u v : V}, G.walk u v β†’ finset V | u v nil := {u} | u v (cons h p) := insert u p.support -- ????? def count (w : V) : Ξ  {u v : V}, G.walk u v β†’ β„• | u v nil := if u = w ∨ v = w then 1 else 0 | u v (cons h p) := if u = w then nat.succ (count p) else (count p) /-- A path is a walk that visits each vertex at most once. -/ def is_path : Ξ  {u v : V}, G.walk u v β†’ Prop | u v nil := true | u v (cons h p) := p.is_path ∧ Β¬ u ∈ p.support end walk /-- The relation on vertices of whether there exists a walk between them. This is an equivalence relation. -/ def exists_walk : V β†’ V β†’ Prop := Ξ» v w, nonempty (G.walk v w) /-- The relation on vertices of whether there exists a path between them. This is equal to `simple_graph.exists_walk`. -/ def exists_path [decidable_eq V]: V β†’ V β†’ Prop := Ξ» v w, βˆƒ (p : G.walk v w), p.is_path @[refl] lemma exists_walk.refl (v : V) : G.exists_walk v v := by { fsplit, refl, } @[symm] lemma exists_walk.symm ⦃v w : V⦄ (hvw : G.exists_walk v w) : G.exists_walk w v := by { tactic.unfreeze_local_instances, cases hvw, use hvw.reverse, } @[trans] lemma exists_walk.trans ⦃u v w : V⦄ (huv : G.exists_walk u v) (hvw : G.exists_walk v w) : G.exists_walk u w := by { tactic.unfreeze_local_instances, cases hvw, cases huv, use huv.concat hvw, } lemma exists_walk.is_equivalence : equivalence G.exists_walk := mk_equivalence _ (exists_walk.refl G) (exists_walk.symm G) (exists_walk.trans G) /-- The equivalence relation on vertices given by `simple_graph.exists_walk`. -/ def exists_walk.setoid : setoid V := setoid.mk _ (exists_walk.is_equivalence G) /-- A connected component is an element of the quotient of the vertex type by the relation `simple_graph.exists_walk`. -/ def connected_components := quotient (exists_walk.setoid G) /-- A graph is connected if every vertex is connected to every other by a walk. -/ def is_connected : Prop := βˆ€ v w, exists_walk G v w instance connected_components.inhabited [inhabited V]: inhabited G.connected_components := ⟨@quotient.mk _ (exists_walk.setoid G) (default _)⟩ namespace walk variables {G} @[simp] lemma nil_length {u : V} : (nil : G.walk u u).length = 0 := rfl @[simp] lemma cons_length {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).length = p.length + 1 := rfl @[simp] lemma nil_reverse {u : V} : (nil : G.walk u u).reverse = nil := rfl lemma singleton_reverse {u v : V} (h : G.adj u v) : (cons h nil).reverse = cons (G.sym h) nil := rfl @[simp] lemma cons_concat {u v w x : V} (h : G.adj u v) (p : G.walk v w) (q : G.walk w x) : (cons h p).concat q = cons h (p.concat q) := rfl lemma cons_as_concat {u v w : V} (h : G.adj u v) (p : G.walk v w) : cons h p = concat (cons h nil) p := rfl @[simp] lemma concat_nil : Ξ  {u v : V} (p : G.walk u v), p.concat nil = p | _ _ nil := rfl | _ _ (cons h p) := by rw [cons_concat, concat_nil] @[simp] lemma nil_concat {u v : V} (p : G.walk u v) : nil.concat p = p := rfl lemma concat_assoc : Ξ  {u v w x : V} (p : G.walk u v) (q : G.walk v w) (r : G.walk w x), p.concat (q.concat r) = (p.concat q).concat r | _ _ _ _ nil _ _ := rfl | _ _ _ _ (cons h p') q r := by { dsimp only [concat], rw concat_assoc, } @[simp] protected lemma reverse_aux_eq_reverse_concat {u v w : V} (p : G.walk u v) (q : G.walk u w) : p.reverse_aux q = p.reverse.concat q := begin induction p generalizing q w, { refl }, { dsimp [walk.reverse_aux, walk.reverse], repeat { rw p_ih }, rw ←concat_assoc, refl, } end @[simp] lemma concat_reverse {u v w : V} (p : G.walk u v) (q : G.walk v w) : (p.concat q).reverse = q.reverse.concat p.reverse := begin induction p generalizing q w, { simp }, { dsimp only [cons_concat, reverse, walk.reverse_aux], simp only [p_ih, walk.reverse_aux_eq_reverse_concat, concat_nil], rw concat_assoc, } end @[simp] lemma cons_reverse {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).reverse = p.reverse.concat (cons (G.sym h) nil) := begin dsimp [reverse, walk.reverse_aux], simp only [walk.reverse_aux_eq_reverse_concat, concat_nil], end @[simp] lemma reverse_reverse : Ξ  {u v : V} (p : G.walk u v), p.reverse.reverse = p | _ _ nil := rfl | _ _ (cons h p) := by simp [reverse_reverse] @[simp] lemma concat_length : Ξ  {u v w : V} (p : G.walk u v) (q : G.walk v w), (p.concat q).length = p.length + q.length | _ _ _ nil _ := by simp | _ _ _ (cons _ p') _ := by simp [concat_length, add_left_comm, add_comm] protected lemma reverse_aux_length {u v w : V} (p : G.walk u v) (q : G.walk u w) : (p.reverse_aux q).length = p.length + q.length := begin induction p, { dunfold walk.reverse_aux, simp, }, { dunfold reverse_aux, rw p_ih, simp only [cons_length], ring, }, end @[simp] lemma reverse_length {u v : V} (p : G.walk u v) : p.reverse.length = p.length := by { convert walk.reverse_aux_length p nil } @[simp] lemma get_vert_0 {u v : V} (p : G.walk u v) : p.get_vert 0 = u := by { cases p; refl } @[simp] lemma get_vert_n {u v : V} (p : G.walk u v) : p.get_vert p.length = v := by { induction p, refl, exact p_ih } @[simp] lemma get_vert_nil {u : V} (i : β„•) : (nil : G.walk u u).get_vert i = u := by cases i; simp [get_vert] @[simp] lemma get_vert_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) (i : β„•) : (cons h p).get_vert (i + 1) = p.get_vert i := rfl lemma concat_get_vert {u v w : V} (p : G.walk u v) (p' : G.walk v w) (i : β„•) : (p.concat p').get_vert i = if i ≀ p.length then p.get_vert i else p'.get_vert (i - p.length) := begin induction p generalizing i, { simp only [get_vert_nil, nil_length, nil_concat, nat.sub_zero, nonpos_iff_eq_zero], split_ifs, { subst i, simp, }, { refl } }, { simp only [cons_length, cons_concat], cases i, { simp, }, { simp [p_ih, nat.succ_le_succ_iff], } } end @[simp] lemma get_vert_reverse {u v : V} (p : G.walk u v) (i : β„•) : p.reverse.get_vert i = p.get_vert (p.length - i) := begin induction i generalizing u v, { simp }, { induction p, { simp }, { simp only [cons_reverse, concat_get_vert, p_ih, i_ih, cons_length, reverse_length, nat.succ_sub_succ_eq_sub, cons_reverse], split_ifs, { have h' : p_p.length - i_n = (p_p.length - i_n.succ).succ := by omega, simp [h'], }, { have h' : p_p.length - i_n = 0 := by omega, have h'' : i_n.succ - p_p.length = (i_n - p_p.length).succ := by omega, simp [h', h''], } } } end protected lemma ext_aux : Ξ  {u v : V} (n : β„•) (p p' : G.walk u v) (h₁ : p.length = n) (h₁' : p'.length = n) (hβ‚‚ : βˆ€ i, i ≀ n β†’ p.get_vert i = p'.get_vert i), p = p' | _ _ 0 nil nil _ _ _ := rfl | u v (n+1) (@cons _ _ _ w _ huw q) (@cons _ _ _ w' _ huw' q') h₁ h₁' hβ‚‚ := begin have hw : w = w', { specialize hβ‚‚ 1 (nat.le_add_left _ _), simpa using hβ‚‚, }, subst w', congr, apply ext_aux n q q' (nat.succ.inj h₁) (nat.succ.inj h₁'), intros i h, exact hβ‚‚ i.succ (nat.succ_le_succ h), end @[ext] lemma ext {u v : V} (p p' : G.walk u v) (h₁ : p.length = p'.length) (hβ‚‚ : βˆ€ i, i ≀ p.length β†’ p.get_vert i = p'.get_vert i) : p = p' := walk.ext_aux p.length p p' rfl h₁.symm hβ‚‚ lemma adj_get_vert : Ξ  {u v : V} (p : G.walk u v) (i : β„•) (h : i < p.length), G.adj (p.get_vert i) (p.get_vert (i + 1)) | u v (cons huv p) 0 _ := by simp [huv] | u v (cons huv p) (i+1) h := begin rw cons_length at h, simp only [get_vert_cons], exact adj_get_vert _ i (nat.lt_of_succ_lt_succ h), end section paths variables [decidable_eq V] @[simp] lemma nil_support {u : V} : (nil : G.walk u u).support = {u} := rfl @[simp] lemma cons_support {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).support = insert u p.support := rfl @[simp] lemma start_mem_support {u v : V} (p : G.walk u v) : u ∈ p.support := by cases p; simp [support] @[simp] lemma end_mem_support {u v : V} (p : G.walk u v) : v ∈ p.support := begin induction p, { simp [support], }, { simp [support, p_ih], }, end /-- Given a walk and a vertex in that walk, give a sub-walk starting at that vertex. -/ def subwalk_from : Ξ  {u v w : V} (p : G.walk u v), w ∈ p.support β†’ G.walk w v | _ _ w nil h := by { rw [nil_support, finset.mem_singleton] at h, subst w } | u v w (@cons _ _ _ x _ ha p) hs := begin rw [cons_support, finset.mem_insert] at hs, by_cases hw : w = u, { subst w, exact cons ha p }, { have : w ∈ p.support, { cases hs, exact false.elim (hw hs), exact hs }, exact p.subwalk_from this, }, end lemma subwalk_from_path_is_path {u v w : V} (p : G.walk u v) (h : p.is_path) (hs : w ∈ p.support) : (p.subwalk_from hs).is_path := begin induction p, { rw [nil_support, finset.mem_singleton] at hs, subst w, trivial }, { rw [cons_support, finset.mem_insert] at hs, dsimp only [is_path] at h, simp only [subwalk_from], split_ifs, { subst p_u, simp [is_path, h] }, { cases hs, { exact false.elim (h_1 hs_1), }, { exact p_ih h.1 _, } } }, end /-- Given a walk, form a path between the same endpoints by splicing out unnecessary detours. See `simple_graph.walk.to_path_is_path` -/ def to_path : Ξ  {u v : V}, G.walk u v β†’ G.walk u v | u v nil := nil | u v (@cons _ _ _ x _ ha p) := let p' := p.to_path in if hs : u ∈ p'.support then p'.subwalk_from hs else cons ha p' lemma subwalk_from_support_subset.aux (n' : β„•) : Ξ  {u v w : V} (p : G.walk u v) (hl : p.length = n') (h : w ∈ p.support), (p.subwalk_from h).support βŠ† p.support := begin refine nat.strong_induction_on n' (Ξ» n ih, _), intros u v w p hl h, cases p, { rw [nil_support, finset.mem_singleton] at h, subst w, trivial, }, { dsimp only [subwalk_from, support], rw [cons_support, finset.mem_insert] at h, split_ifs, { subst h_1, simp, }, { have h' : w ∈ p_p.support := by cc, refine finset.subset.trans _ (finset.subset_insert _ _), convert_to (p_p.subwalk_from h').support βŠ† p_p.support, rw cons_length at hl, apply ih p_p.length (by linarith) _ rfl, }, }, end lemma subwalk_from_support_subset {u v w : V} (p : G.walk u v) (h : w ∈ p.support) : (p.subwalk_from h).support βŠ† p.support := subwalk_from_support_subset.aux p.length p rfl h lemma to_path_support_subset {u v : V} (p : G.walk u v) : p.to_path.support βŠ† p.support := begin induction p, { trivial, }, { dsimp only [to_path, support], split_ifs, { refine finset.subset.trans (finset.subset.trans _ p_ih) (finset.subset_insert _ _), apply subwalk_from_support_subset, }, { intro x, simp only [cons_support, finset.mem_insert], intro h, cases h, { subst p_u, exact or.inl rfl, }, { exact or.inr (p_ih h_1), }, }, }, end lemma to_path_is_path {u v : V} (p : G.walk u v) : p.to_path.is_path := begin induction p, { trivial, }, { dsimp [to_path, is_path], split_ifs, { apply subwalk_from_path_is_path _ p_ih, }, { use p_ih, }, }, end @[simp] lemma nil_is_path {u : V} : (nil : G.walk u u).is_path := by trivial @[simp] lemma singleton_is_path {u v : V} (h : G.adj u v) : (cons h nil).is_path := begin simp only [is_path, true_and, nil_support, finset.mem_singleton], intro h', subst u, exact G.loopless _ h, end @[simp] lemma concat_support {u v w : V} (p : G.walk u v) (p' : G.walk v w) : (p.concat p').support = p.support βˆͺ p'.support := begin induction p generalizing p' w, { simp, }, { simp only [finset.insert_union, cons_concat, cons_support], apply congr_arg _ (p_ih _), }, end @[simp] lemma reverse_support {u v : V} (p : G.walk u v) : p.reverse.support = p.support := begin induction p, { trivial, }, { simp only [support, finset.insert_eq_of_mem, end_mem_support, concat_support, true_or, cons_reverse, finset.mem_union, finset.union_insert], rw [finset.union_comm, ←finset.insert_eq], apply congr_arg _ p_ih, }, end lemma get_vert_mem_support {u v} (p : G.walk u v) (i : β„•) : p.get_vert i ∈ p.support := begin induction p generalizing i, { simp, }, { cases i, { simp, }, { simp only [cons_support, finset.mem_insert, get_vert_cons], right, apply p_ih, }, }, end lemma mem_support_exists_get_vert {u v w} (p : G.walk u v) (h : w ∈ p.support) : βˆƒ i, i ≀ p.length ∧ p.get_vert i = w := begin induction p, { rw [nil_support, finset.mem_singleton] at h, subst w, simp, }, { rw [cons_support, finset.mem_insert] at h, cases h, { subst w, use 0, simp, }, { specialize p_ih h, rcases p_ih with ⟨i, hi, hv⟩, use i+1, subst w, simp [hi],}, }, end protected lemma is_path_iff.aux {u v : V} (p : G.walk u v) : p.is_path ↔ βˆ€ (i k : β„•) (hi : i ≀ p.length) (hk : i + k ≀ p.length), p.get_vert i = p.get_vert (i + k) β†’ k = 0 := begin split, { intros hp i, induction i generalizing u v, { intro k, induction k generalizing u v, { simp }, { simp only [forall_prop_of_true, get_vert_0, zero_le, zero_add], intros hk hu, cases p, { simpa using hk }, { simp only [get_vert_cons] at hu, subst u, exact false.elim (hp.2 (get_vert_mem_support _ _)) } } }, { cases p, { simp, }, { simp only [cons_length, get_vert_cons], simp only [is_path] at hp, intros k hi hk, rw [add_comm, nat.add_succ], simp [get_vert], intro hv, rw [add_comm, nat.add_succ, add_comm] at hk, apply i_ih p_p hp.1 _ (nat.succ_le_succ_iff.mp hi) (nat.succ_le_succ_iff.mp hk), rw [hv, add_comm], } } }, { intro h, induction p, { simp }, { simp only [is_path], split, { apply p_ih, intros i k hi hk hv, apply h i.succ k (nat.succ_le_succ hi) _, rw [add_comm, nat.add_succ, add_comm], simp only [get_vert, hv, cons_length], rw [add_comm, nat.add_succ, add_comm], exact nat.succ_le_succ hk, }, { intro hs, rcases mem_support_exists_get_vert _ hs with ⟨i, hl, rfl⟩, have h' := h 0 i.succ, simp only [cons_length, forall_prop_of_true, get_vert_0, zero_le, zero_add, get_vert_cons] at h', specialize h' (nat.succ_le_succ hl), exact nat.succ_ne_zero _ h', } } } end lemma is_path_iff {u v : V} (p : G.walk u v) : p.is_path ↔ βˆ€ (i j : β„•) (hi : i ≀ p.length) (hj : j ≀ p.length), p.get_vert i = p.get_vert j β†’ i = j := begin convert walk.is_path_iff.aux p, simp only [eq_iff_iff], split, { intros h i k hi hk hv, specialize h i (i+k) hi hk hv, linarith, }, { intros h i j hi hj hv, wlog : i ≀ j using i j, specialize h i (j-i) hi, rw nat.add_sub_of_le case at h, specialize h hj hv, rw [(nat.sub_eq_iff_eq_add case).mp h, zero_add], } end lemma reverse_path {u v : V} (p : G.walk u v) (h : p.is_path) : p.reverse.is_path := begin rw is_path_iff, simp only [reverse_length, get_vert_reverse], intros i j hi hj hp, have hi' : p.length - i ≀ p.length := by omega, have hj' : p.length - j ≀ p.length := by omega, have h' := (is_path_iff p).mp h _ _ hi' hj' hp, omega, end lemma is_path_if_concat_is_path {u v w} (p : G.walk u v) (p' : G.walk v w) (h : (p.concat p').is_path) : p.is_path := begin rw is_path_iff at h, rw is_path_iff, simp only [concat_get_vert, concat_length] at h, intros i j hi hj hp, specialize h i j (by omega) (by omega), simp only [hi, hj, if_true] at h, exact h hp, end lemma get_vert_image {u v} (p : G.walk u v) : finset.image (Ξ» i, p.get_vert i) (finset.range (p.length + 1)) = p.support := begin ext w, simp only [exists_prop, finset.mem_image, finset.mem_range], split, { simp only [and_imp, exists_imp_distrib], rintros i ih rfl, apply get_vert_mem_support, }, { intro hw, rcases mem_support_exists_get_vert p hw with ⟨i, hi, hw'⟩, exact ⟨i, by linarith, hw'⟩, }, end end paths end walk variables (G) lemma exists_walk_eq_exists_path [decidable_eq V] : exists_walk G = exists_path G := begin ext u v, dsimp [exists_walk, exists_path], split, { intro p, cases p, fsplit, use p.to_path, apply walk.to_path_is_path, }, { intro p, cases p, fsplit, use p_w, }, end lemma exists_walk_eq_eqv_gen : exists_walk G = eqv_gen G.adj := begin ext v w, split, { intro h, cases h, induction h, { exact eqv_gen.refl _ }, { exact eqv_gen.trans _ _ _ (eqv_gen.rel _ _ h_h) h_ih } }, { intro h, induction h with x y h _ x y he h_ih x y z hxy hyz hxy_ih hyz_ih, { exact ⟨walk.cons h walk.nil⟩, }, { refl, }, { cases h_ih, exact ⟨h_ih.reverse⟩, }, { cases hxy_ih, cases hyz_ih, exact ⟨hxy_ih.concat hyz_ih⟩, } } end end simple_graph
6cc0844fa47aad8c22451c0eb99c0831faf2db9a
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/interactive/533.lean
e96fe253f32367452c612b0e88522d9a896cfb0b
[ "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
67
lean
inductive Foo where | bar : F --^ textDocument/completion
90d59bb6bda70164372aa6e0f74bd83410f47dae
c777c32c8e484e195053731103c5e52af26a25d1
/src/geometry/euclidean/angle/unoriented/basic.lean
d332c358a4407f9a6a8ab4d6ab14239f75e6f13b
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
15,403
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Manuel Candales -/ import analysis.inner_product_space.basic import analysis.special_functions.trigonometric.inverse /-! # Angles between vectors This file defines unoriented angles in real inner product spaces. ## Main definitions * `inner_product_geometry.angle` is the undirected angle between two vectors. -/ assert_not_exists has_fderiv_at assert_not_exists conformal_at noncomputable theory open real set open_locale big_operators open_locale real open_locale real_inner_product_space namespace inner_product_geometry variables {V : Type*} [normed_add_comm_group V] [inner_product_space ℝ V] {x y : V} /-- The undirected angle between two vectors. If either vector is 0, this is Ο€/2. See `orientation.oangle` for the corresponding oriented angle definition. -/ def angle (x y : V) : ℝ := real.arccos (βŸͺx, y⟫ / (β€–xβ€– * β€–yβ€–)) lemma continuous_at_angle {x : V Γ— V} (hx1 : x.1 β‰  0) (hx2 : x.2 β‰  0) : continuous_at (Ξ» y : V Γ— V, angle y.1 y.2) x := real.continuous_arccos.continuous_at.comp $ continuous_inner.continuous_at.div ((continuous_norm.comp continuous_fst).mul (continuous_norm.comp continuous_snd)).continuous_at (by simp [hx1, hx2]) lemma angle_smul_smul {c : ℝ} (hc : c β‰  0) (x y : V) : angle (c β€’ x) (c β€’ y) = angle x y := have c * c β‰  0, from mul_ne_zero hc hc, by rw [angle, angle, real_inner_smul_left, inner_smul_right, norm_smul, norm_smul, real.norm_eq_abs, mul_mul_mul_comm _ (β€–xβ€–), abs_mul_abs_self, ← mul_assoc c c, mul_div_mul_left _ _ this] @[simp] lemma _root_.linear_isometry.angle_map {E F : Type*} [normed_add_comm_group E] [normed_add_comm_group F] [inner_product_space ℝ E] [inner_product_space ℝ F] (f : E β†’β‚—α΅’[ℝ] F) (u v : E) : angle (f u) (f v) = angle u v := by rw [angle, angle, f.inner_map_map, f.norm_map, f.norm_map] @[simp, norm_cast] lemma _root_.submodule.angle_coe {s : submodule ℝ V} (x y : s) : angle (x : V) (y : V) = angle x y := s.subtypeβ‚—α΅’.angle_map x y /-- The cosine of the angle between two vectors. -/ lemma cos_angle (x y : V) : real.cos (angle x y) = βŸͺx, y⟫ / (β€–xβ€– * β€–yβ€–) := real.cos_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 /-- The angle between two vectors does not depend on their order. -/ lemma angle_comm (x y : V) : angle x y = angle y x := begin unfold angle, rw [real_inner_comm, mul_comm] end /-- The angle between the negation of two vectors. -/ @[simp] lemma angle_neg_neg (x y : V) : angle (-x) (-y) = angle x y := begin unfold angle, rw [inner_neg_neg, norm_neg, norm_neg] end /-- The angle between two vectors is nonnegative. -/ lemma angle_nonneg (x y : V) : 0 ≀ angle x y := real.arccos_nonneg _ /-- The angle between two vectors is at most Ο€. -/ lemma angle_le_pi (x y : V) : angle x y ≀ Ο€ := real.arccos_le_pi _ /-- The angle between a vector and the negation of another vector. -/ lemma angle_neg_right (x y : V) : angle x (-y) = Ο€ - angle x y := begin unfold angle, rw [←real.arccos_neg, norm_neg, inner_neg_right, neg_div] end /-- The angle between the negation of a vector and another vector. -/ lemma angle_neg_left (x y : V) : angle (-x) y = Ο€ - angle x y := by rw [←angle_neg_neg, neg_neg, angle_neg_right] /-- The angle between the zero vector and a vector. -/ @[simp] lemma angle_zero_left (x : V) : angle 0 x = Ο€ / 2 := begin unfold angle, rw [inner_zero_left, zero_div, real.arccos_zero] end /-- The angle between a vector and the zero vector. -/ @[simp] lemma angle_zero_right (x : V) : angle x 0 = Ο€ / 2 := begin unfold angle, rw [inner_zero_right, zero_div, real.arccos_zero] end /-- The angle between a nonzero vector and itself. -/ @[simp] lemma angle_self {x : V} (hx : x β‰  0) : angle x x = 0 := begin unfold angle, rw [←real_inner_self_eq_norm_mul_norm, div_self (inner_self_ne_zero.2 hx : βŸͺx, x⟫ β‰  0), real.arccos_one] end /-- The angle between a nonzero vector and its negation. -/ @[simp] lemma angle_self_neg_of_nonzero {x : V} (hx : x β‰  0) : angle x (-x) = Ο€ := by rw [angle_neg_right, angle_self hx, sub_zero] /-- The angle between the negation of a nonzero vector and that vector. -/ @[simp] lemma angle_neg_self_of_nonzero {x : V} (hx : x β‰  0) : angle (-x) x = Ο€ := by rw [angle_comm, angle_self_neg_of_nonzero hx] /-- The angle between a vector and a positive multiple of a vector. -/ @[simp] lemma angle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle x (r β€’ y) = angle x y := begin unfold angle, rw [inner_smul_right, norm_smul, real.norm_eq_abs, abs_of_nonneg (le_of_lt hr), ←mul_assoc, mul_comm _ r, mul_assoc, mul_div_mul_left _ _ (ne_of_gt hr)] end /-- The angle between a positive multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle (r β€’ x) y = angle x y := by rw [angle_comm, angle_smul_right_of_pos y x hr, angle_comm] /-- The angle between a vector and a negative multiple of a vector. -/ @[simp] lemma angle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle x (r β€’ y) = angle x (-y) := by rw [←neg_neg r, neg_smul, angle_neg_right, angle_smul_right_of_pos x y (neg_pos_of_neg hr), angle_neg_right] /-- The angle between a negative multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle (r β€’ x) y = angle (-x) y := by rw [angle_comm, angle_smul_right_of_neg y x hr, angle_comm] /-- The cosine of the angle between two vectors, multiplied by the product of their norms. -/ lemma cos_angle_mul_norm_mul_norm (x y : V) : real.cos (angle x y) * (β€–xβ€– * β€–yβ€–) = βŸͺx, y⟫ := begin rw [cos_angle, div_mul_cancel_of_imp], simp [or_imp_distrib] { contextual := tt }, end /-- The sine of the angle between two vectors, multiplied by the product of their norms. -/ lemma sin_angle_mul_norm_mul_norm (x y : V) : real.sin (angle x y) * (β€–xβ€– * β€–yβ€–) = real.sqrt (βŸͺx, x⟫ * βŸͺy, y⟫ - βŸͺx, y⟫ * βŸͺx, y⟫) := begin unfold angle, rw [real.sin_arccos, ←real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), ←real.sqrt_mul' _ (mul_self_nonneg _), sq, real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), real_inner_self_eq_norm_mul_norm, real_inner_self_eq_norm_mul_norm], by_cases h : (β€–xβ€– * β€–yβ€–) = 0, { rw [(show β€–xβ€– * β€–xβ€– * (β€–yβ€– * β€–yβ€–) = (β€–xβ€– * β€–yβ€–) * (β€–xβ€– * β€–yβ€–), by ring), h, mul_zero, mul_zero, zero_sub], cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy, { rw norm_eq_zero at hx, rw [hx, inner_zero_left, zero_mul, neg_zero] }, { rw norm_eq_zero at hy, rw [hy, inner_zero_right, zero_mul, neg_zero] } }, { field_simp [h], ring_nf } end /-- The angle between two vectors is zero if and only if they are nonzero and one is a positive multiple of the other. -/ lemma angle_eq_zero_iff {x y : V} : angle x y = 0 ↔ (x β‰  0 ∧ βˆƒ (r : ℝ), 0 < r ∧ y = r β€’ x) := begin rw [angle, ← real_inner_div_norm_mul_norm_eq_one_iff, real.arccos_eq_zero, has_le.le.le_iff_eq, eq_comm], exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 end /-- The angle between two vectors is Ο€ if and only if they are nonzero and one is a negative multiple of the other. -/ lemma angle_eq_pi_iff {x y : V} : angle x y = Ο€ ↔ (x β‰  0 ∧ βˆƒ (r : ℝ), r < 0 ∧ y = r β€’ x) := begin rw [angle, ← real_inner_div_norm_mul_norm_eq_neg_one_iff, real.arccos_eq_pi, has_le.le.le_iff_eq], exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 end /-- If the angle between two vectors is Ο€, the angles between those vectors and a third vector add to Ο€. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi {x y : V} (z : V) (h : angle x y = Ο€) : angle x z + angle y z = Ο€ := begin rcases angle_eq_pi_iff.1 h with ⟨hx, ⟨r, ⟨hr, rfl⟩⟩⟩, rw [angle_smul_left_of_neg x z hr, angle_neg_left, add_sub_cancel'_right] end /-- Two vectors have inner product 0 if and only if the angle between them is Ο€/2. -/ lemma inner_eq_zero_iff_angle_eq_pi_div_two (x y : V) : βŸͺx, y⟫ = 0 ↔ angle x y = Ο€ / 2 := iff.symm $ by simp [angle, or_imp_distrib] { contextual := tt } /-- If the angle between two vectors is Ο€, the inner product equals the negative product of the norms. -/ lemma inner_eq_neg_mul_norm_of_angle_eq_pi {x y : V} (h : angle x y = Ο€) : βŸͺx, y⟫ = - (β€–xβ€– * β€–yβ€–) := by simp [← cos_angle_mul_norm_mul_norm, h] /-- If the angle between two vectors is 0, the inner product equals the product of the norms. -/ lemma inner_eq_mul_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : βŸͺx, y⟫ = β€–xβ€– * β€–yβ€– := by simp [← cos_angle_mul_norm_mul_norm, h] /-- The inner product of two non-zero vectors equals the negative product of their norms if and only if the angle between the two vectors is Ο€. -/ lemma inner_eq_neg_mul_norm_iff_angle_eq_pi {x y : V} (hx : x β‰  0) (hy : y β‰  0) : βŸͺx, y⟫ = - (β€–xβ€– * β€–yβ€–) ↔ angle x y = Ο€ := begin refine ⟨λ h, _, inner_eq_neg_mul_norm_of_angle_eq_pi⟩, have h₁ : (β€–xβ€– * β€–yβ€–) β‰  0 := (mul_pos (norm_pos_iff.mpr hx) (norm_pos_iff.mpr hy)).ne', rw [angle, h, neg_div, div_self h₁, real.arccos_neg_one], end /-- The inner product of two non-zero vectors equals the product of their norms if and only if the angle between the two vectors is 0. -/ lemma inner_eq_mul_norm_iff_angle_eq_zero {x y : V} (hx : x β‰  0) (hy : y β‰  0) : βŸͺx, y⟫ = β€–xβ€– * β€–yβ€– ↔ angle x y = 0 := begin refine ⟨λ h, _, inner_eq_mul_norm_of_angle_eq_zero⟩, have h₁ : (β€–xβ€– * β€–yβ€–) β‰  0 := (mul_pos (norm_pos_iff.mpr hx) (norm_pos_iff.mpr hy)).ne', rw [angle, h, div_self h₁, real.arccos_one], end /-- If the angle between two vectors is Ο€, the norm of their difference equals the sum of their norms. -/ lemma norm_sub_eq_add_norm_of_angle_eq_pi {x y : V} (h : angle x y = Ο€) : β€–x - yβ€– = β€–xβ€– + β€–yβ€– := begin rw ← sq_eq_sq (norm_nonneg (x - y)) (add_nonneg (norm_nonneg x) (norm_nonneg y)), rw [norm_sub_pow_two_real, inner_eq_neg_mul_norm_of_angle_eq_pi h], ring, end /-- If the angle between two vectors is 0, the norm of their sum equals the sum of their norms. -/ lemma norm_add_eq_add_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : β€–x + yβ€– = β€–xβ€– + β€–yβ€– := begin rw ← sq_eq_sq (norm_nonneg (x + y)) (add_nonneg (norm_nonneg x) (norm_nonneg y)), rw [norm_add_pow_two_real, inner_eq_mul_norm_of_angle_eq_zero h], ring, end /-- If the angle between two vectors is 0, the norm of their difference equals the absolute value of the difference of their norms. -/ lemma norm_sub_eq_abs_sub_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : β€–x - yβ€– = |β€–xβ€– - β€–yβ€–| := begin rw [← sq_eq_sq (norm_nonneg (x - y)) (abs_nonneg (β€–xβ€– - β€–yβ€–)), norm_sub_pow_two_real, inner_eq_mul_norm_of_angle_eq_zero h, sq_abs (β€–xβ€– - β€–yβ€–)], ring, end /-- The norm of the difference of two non-zero vectors equals the sum of their norms if and only the angle between the two vectors is Ο€. -/ lemma norm_sub_eq_add_norm_iff_angle_eq_pi {x y : V} (hx : x β‰  0) (hy : y β‰  0) : β€–x - yβ€– = β€–xβ€– + β€–yβ€– ↔ angle x y = Ο€ := begin refine ⟨λ h, _, norm_sub_eq_add_norm_of_angle_eq_pi⟩, rw ← inner_eq_neg_mul_norm_iff_angle_eq_pi hx hy, obtain ⟨hxy₁, hxyβ‚‚βŸ© := ⟨norm_nonneg (x - y), add_nonneg (norm_nonneg x) (norm_nonneg y)⟩, rw [← sq_eq_sq hxy₁ hxyβ‚‚, norm_sub_pow_two_real] at h, calc βŸͺx, y⟫ = (β€–xβ€– ^ 2 + β€–yβ€– ^ 2 - (β€–xβ€– + β€–yβ€–) ^ 2) / 2 : by linarith ... = -(β€–xβ€– * β€–yβ€–) : by ring, end /-- The norm of the sum of two non-zero vectors equals the sum of their norms if and only the angle between the two vectors is 0. -/ lemma norm_add_eq_add_norm_iff_angle_eq_zero {x y : V} (hx : x β‰  0) (hy : y β‰  0) : β€–x + yβ€– = β€–xβ€– + β€–yβ€– ↔ angle x y = 0 := begin refine ⟨λ h, _, norm_add_eq_add_norm_of_angle_eq_zero⟩, rw ← inner_eq_mul_norm_iff_angle_eq_zero hx hy, obtain ⟨hxy₁, hxyβ‚‚βŸ© := ⟨norm_nonneg (x + y), add_nonneg (norm_nonneg x) (norm_nonneg y)⟩, rw [← sq_eq_sq hxy₁ hxyβ‚‚, norm_add_pow_two_real] at h, calc βŸͺx, y⟫ = ((β€–xβ€– + β€–yβ€–) ^ 2 - β€–xβ€– ^ 2 - β€–yβ€– ^ 2)/ 2 : by linarith ... = β€–xβ€– * β€–yβ€– : by ring, end /-- The norm of the difference of two non-zero vectors equals the absolute value of the difference of their norms if and only the angle between the two vectors is 0. -/ lemma norm_sub_eq_abs_sub_norm_iff_angle_eq_zero {x y : V} (hx : x β‰  0) (hy : y β‰  0) : β€–x - yβ€– = |β€–xβ€– - β€–yβ€–| ↔ angle x y = 0 := begin refine ⟨λ h, _, norm_sub_eq_abs_sub_norm_of_angle_eq_zero⟩, rw ← inner_eq_mul_norm_iff_angle_eq_zero hx hy, have h1 : β€–x - yβ€– ^ 2 = (β€–xβ€– - β€–yβ€–) ^ 2, { rw h, exact sq_abs (β€–xβ€– - β€–yβ€–) }, rw norm_sub_pow_two_real at h1, calc βŸͺx, y⟫ = ((β€–xβ€– + β€–yβ€–) ^ 2 - β€–xβ€– ^ 2 - β€–yβ€– ^ 2)/ 2 : by linarith ... = β€–xβ€– * β€–yβ€– : by ring, end /-- The norm of the sum of two vectors equals the norm of their difference if and only if the angle between them is Ο€/2. -/ lemma norm_add_eq_norm_sub_iff_angle_eq_pi_div_two (x y : V) : β€–x + yβ€– = β€–x - yβ€– ↔ angle x y = Ο€ / 2 := begin rw [← sq_eq_sq (norm_nonneg (x + y)) (norm_nonneg (x - y)), ← inner_eq_zero_iff_angle_eq_pi_div_two x y, norm_add_pow_two_real, norm_sub_pow_two_real], split; intro h; linarith, end /-- The cosine of the angle between two vectors is 1 if and only if the angle is 0. -/ lemma cos_eq_one_iff_angle_eq_zero : cos (angle x y) = 1 ↔ angle x y = 0 := begin rw ← cos_zero, exact inj_on_cos.eq_iff ⟨angle_nonneg x y, angle_le_pi x y⟩ (left_mem_Icc.2 pi_pos.le), end /-- The cosine of the angle between two vectors is 0 if and only if the angle is Ο€ / 2. -/ lemma cos_eq_zero_iff_angle_eq_pi_div_two : cos (angle x y) = 0 ↔ angle x y = Ο€ / 2 := begin rw ← cos_pi_div_two, apply inj_on_cos.eq_iff ⟨angle_nonneg x y, angle_le_pi x y⟩, split; linarith [pi_pos], end /-- The cosine of the angle between two vectors is -1 if and only if the angle is Ο€. -/ lemma cos_eq_neg_one_iff_angle_eq_pi : cos (angle x y) = -1 ↔ angle x y = Ο€ := begin rw ← cos_pi, exact inj_on_cos.eq_iff ⟨angle_nonneg x y, angle_le_pi x y⟩ (right_mem_Icc.2 pi_pos.le), end /-- The sine of the angle between two vectors is 0 if and only if the angle is 0 or Ο€. -/ lemma sin_eq_zero_iff_angle_eq_zero_or_angle_eq_pi : sin (angle x y) = 0 ↔ angle x y = 0 ∨ angle x y = Ο€ := by rw [sin_eq_zero_iff_cos_eq, cos_eq_one_iff_angle_eq_zero, cos_eq_neg_one_iff_angle_eq_pi] /-- The sine of the angle between two vectors is 1 if and only if the angle is Ο€ / 2. -/ lemma sin_eq_one_iff_angle_eq_pi_div_two : sin (angle x y) = 1 ↔ angle x y = Ο€ / 2 := begin refine ⟨λ h, _, Ξ» h, by rw [h, sin_pi_div_two]⟩, rw [←cos_eq_zero_iff_angle_eq_pi_div_two, ←abs_eq_zero, abs_cos_eq_sqrt_one_sub_sin_sq, h], simp, end end inner_product_geometry
545dbc35a619b2be3cd9b317b61abdfa1b08b343
82e44445c70db0f03e30d7be725775f122d72f3e
/src/linear_algebra/char_poly/coeff.lean
6c60c04cc0c7785d12030a062fc4f09c899d8254
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
10,825
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark -/ import algebra.polynomial.big_operators import data.matrix.char_p import field_theory.finite.basic import group_theory.perm.cycles import linear_algebra.char_poly.basic import linear_algebra.matrix.trace import ring_theory.polynomial.basic import ring_theory.power_basis /-! # Characteristic polynomials We give methods for computing coefficients of the characteristic polynomial. ## Main definitions - `char_poly_degree_eq_dim` proves that the degree of the characteristic polynomial over a nonzero ring is the dimension of the matrix - `det_eq_sign_char_poly_coeff` proves that the determinant is the constant term of the characteristic polynomial, up to sign. - `trace_eq_neg_char_poly_coeff` proves that the trace is the negative of the (d-1)th coefficient of the characteristic polynomial, where d is the dimension of the matrix. For a nonzero ring, this is the second-highest coefficient. -/ noncomputable theory universes u v w z open polynomial matrix open_locale big_operators variables {R : Type u} [comm_ring R] variables {n G : Type v} [decidable_eq n] [fintype n] variables {Ξ± Ξ² : Type v} [decidable_eq Ξ±] open finset open polynomial variable {M : matrix n n R} lemma char_matrix_apply_nat_degree [nontrivial R] (i j : n) : (char_matrix M i j).nat_degree = ite (i = j) 1 0 := by { by_cases i = j; simp [h, ← degree_eq_iff_nat_degree_eq_of_pos (nat.succ_pos 0)], } lemma char_matrix_apply_nat_degree_le (i j : n) : (char_matrix M i j).nat_degree ≀ ite (i = j) 1 0 := by split_ifs; simp [h, nat_degree_X_sub_C_le] variable (M) lemma char_poly_sub_diagonal_degree_lt : (char_poly M - ∏ (i : n), (X - C (M i i))).degree < ↑(fintype.card n - 1) := begin rw [char_poly, det_apply', ← insert_erase (mem_univ (equiv.refl n)), sum_insert (not_mem_erase (equiv.refl n) univ), add_comm], simp only [char_matrix_apply_eq, one_mul, equiv.perm.sign_refl, id.def, int.cast_one, units.coe_one, add_sub_cancel, equiv.coe_refl], rw ← mem_degree_lt, apply submodule.sum_mem (degree_lt R (fintype.card n - 1)), intros c hc, rw [← C_eq_int_cast, C_mul'], apply submodule.smul_mem (degree_lt R (fintype.card n - 1)) ↑↑(equiv.perm.sign c), rw mem_degree_lt, apply lt_of_le_of_lt degree_le_nat_degree _, rw with_bot.coe_lt_coe, apply lt_of_le_of_lt _ (equiv.perm.fixed_point_card_lt_of_ne_one (ne_of_mem_erase hc)), apply le_trans (polynomial.nat_degree_prod_le univ (Ξ» i : n, (char_matrix M (c i) i))) _, rw card_eq_sum_ones, rw sum_filter, apply sum_le_sum, intros, apply char_matrix_apply_nat_degree_le, end lemma char_poly_coeff_eq_prod_coeff_of_le {k : β„•} (h : fintype.card n - 1 ≀ k) : (char_poly M).coeff k = (∏ i : n, (X - C (M i i))).coeff k := begin apply eq_of_sub_eq_zero, rw ← coeff_sub, apply polynomial.coeff_eq_zero_of_degree_lt, apply lt_of_lt_of_le (char_poly_sub_diagonal_degree_lt M) _, rw with_bot.coe_le_coe, apply h, end lemma det_of_card_zero (h : fintype.card n = 0) (M : matrix n n R) : M.det = 1 := by { rw fintype.card_eq_zero_iff at h, suffices : M = 1, { simp [this] }, ext i, exact h.elim i } theorem char_poly_degree_eq_dim [nontrivial R] (M : matrix n n R) : (char_poly M).degree = fintype.card n := begin by_cases fintype.card n = 0, { rw h, unfold char_poly, rw det_of_card_zero, {simp}, {assumption} }, rw ← sub_add_cancel (char_poly M) (∏ (i : n), (X - C (M i i))), have h1 : (∏ (i : n), (X - C (M i i))).degree = fintype.card n, { rw degree_eq_iff_nat_degree_eq_of_pos, swap, apply nat.pos_of_ne_zero h, rw nat_degree_prod', simp_rw nat_degree_X_sub_C, unfold fintype.card, simp, simp_rw (monic_X_sub_C _).leading_coeff, simp, }, rw degree_add_eq_right_of_degree_lt, exact h1, rw h1, apply lt_trans (char_poly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe, rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h, end theorem char_poly_nat_degree_eq_dim [nontrivial R] (M : matrix n n R) : (char_poly M).nat_degree = fintype.card n := nat_degree_eq_of_degree_eq_some (char_poly_degree_eq_dim M) lemma char_poly_monic (M : matrix n n R) : monic (char_poly M) := begin nontriviality, by_cases fintype.card n = 0, {rw [char_poly, det_of_card_zero h], apply monic_one}, have mon : (∏ (i : n), (X - C (M i i))).monic, { apply monic_prod_of_monic univ (Ξ» i : n, (X - C (M i i))), simp [monic_X_sub_C], }, rw ← sub_add_cancel (∏ (i : n), (X - C (M i i))) (char_poly M) at mon, rw monic at *, rw leading_coeff_add_of_degree_lt at mon, rw ← mon, rw char_poly_degree_eq_dim, rw ← neg_sub, rw degree_neg, apply lt_trans (char_poly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe, rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h, end theorem trace_eq_neg_char_poly_coeff [nonempty n] (M : matrix n n R) : (matrix.trace n R R) M = -(char_poly M).coeff (fintype.card n - 1) := begin nontriviality, rw char_poly_coeff_eq_prod_coeff_of_le, swap, refl, rw [fintype.card, prod_X_sub_C_coeff_card_pred univ (Ξ» i : n, M i i)], simp, rw [← fintype.card, fintype.card_pos_iff], apply_instance, end -- I feel like this should use polynomial.alg_hom_evalβ‚‚_algebra_map lemma mat_poly_equiv_eval (M : matrix n n (polynomial R)) (r : R) (i j : n) : (mat_poly_equiv M).eval ((scalar n) r) i j = (M i j).eval r := begin unfold polynomial.eval, unfold evalβ‚‚, transitivity polynomial.sum (mat_poly_equiv M) (Ξ» (e : β„•) (a : matrix n n R), (a * (scalar n) r ^ e) i j), { unfold polynomial.sum, rw matrix.sum_apply, dsimp, refl }, { simp_rw [←ring_hom.map_pow, ←(matrix.scalar.commute _ _).eq], simp only [coe_scalar, matrix.one_mul, ring_hom.id_apply, pi.smul_apply, smul_eq_mul, mul_eq_mul, algebra.smul_mul_assoc], have h : βˆ€ x : β„•, (Ξ» (e : β„•) (a : R), r ^ e * a) x 0 = 0 := by simp, simp only [polynomial.sum, mat_poly_equiv_coeff_apply, mul_comm], apply (finset.sum_subset (support_subset_support_mat_poly_equiv _ _ _) _).symm, assume n hn h'n, rw not_mem_support_iff at h'n, simp only [h'n, zero_mul] } end lemma eval_det (M : matrix n n (polynomial R)) (r : R) : polynomial.eval r M.det = (polynomial.eval (matrix.scalar n r) (mat_poly_equiv M)).det := begin rw [polynomial.eval, ← coe_evalβ‚‚_ring_hom, ring_hom.map_det], apply congr_arg det, ext, symmetry, convert mat_poly_equiv_eval _ _ _ _, end theorem det_eq_sign_char_poly_coeff (M : matrix n n R) : M.det = (-1)^(fintype.card n) * (char_poly M).coeff 0:= begin rw [coeff_zero_eq_eval_zero, char_poly, eval_det, mat_poly_equiv_char_matrix, ← det_smul], simp end variables {p : β„•} [fact p.prime] lemma mat_poly_equiv_eq_X_pow_sub_C {K : Type*} (k : β„•) [field K] (M : matrix n n K) : mat_poly_equiv ((expand K (k) : polynomial K β†’+* polynomial K).map_matrix (char_matrix (M ^ k))) = X ^ k - C (M ^ k) := begin ext m, rw [coeff_sub, coeff_C, mat_poly_equiv_coeff_apply, ring_hom.map_matrix_apply, matrix.map_apply, alg_hom.coe_to_ring_hom, dmatrix.sub_apply, coeff_X_pow], by_cases hij : i = j, { rw [hij, char_matrix_apply_eq, alg_hom.map_sub, expand_C, expand_X, coeff_sub, coeff_X_pow, coeff_C], split_ifs with mp m0; simp only [matrix.one_apply_eq, dmatrix.zero_apply] }, { rw [char_matrix_apply_ne _ _ _ hij, alg_hom.map_neg, expand_C, coeff_neg, coeff_C], split_ifs with m0 mp; simp only [hij, zero_sub, dmatrix.zero_apply, sub_zero, neg_zero, matrix.one_apply_ne, ne.def, not_false_iff] } end @[simp] lemma finite_field.char_poly_pow_card {K : Type*} [field K] [fintype K] (M : matrix n n K) : char_poly (M ^ (fintype.card K)) = char_poly M := begin casesI (is_empty_or_nonempty n).symm, { cases char_p.exists K with p hp, letI := hp, rcases finite_field.card K p with ⟨⟨k, kpos⟩, ⟨hp, hk⟩⟩, haveI : fact p.prime := ⟨hp⟩, dsimp at hk, rw hk at *, apply (frobenius_inj (polynomial K) p).iterate k, repeat { rw iterate_frobenius, rw ← hk }, rw ← finite_field.expand_card, unfold char_poly, rw [alg_hom.map_det, ← coe_det_monoid_hom, ← (det_monoid_hom : matrix n n (polynomial K) β†’* polynomial K).map_pow], apply congr_arg det, refine mat_poly_equiv.injective _, rw [alg_equiv.map_pow, mat_poly_equiv_char_matrix, hk, sub_pow_char_pow_of_commute, ← C_pow], { exact (id (mat_poly_equiv_eq_X_pow_sub_C (p ^ k) M) : _) }, { exact (C M).commute_X } }, { -- TODO[gh-6025]: remove this `haveI` once `subsingleton_of_empty_right` is a global instance haveI : subsingleton (matrix n n K) := matrix.subsingleton_of_empty_right, exact congr_arg _ (subsingleton.elim _ _), }, end @[simp] lemma zmod.char_poly_pow_card (M : matrix n n (zmod p)) : char_poly (M ^ p) = char_poly M := by { have h := finite_field.char_poly_pow_card M, rwa zmod.card at h, } lemma finite_field.trace_pow_card {K : Type*} [field K] [fintype K] [nonempty n] (M : matrix n n K) : trace n K K (M ^ (fintype.card K)) = (trace n K K M) ^ (fintype.card K) := by rw [trace_eq_neg_char_poly_coeff, trace_eq_neg_char_poly_coeff, finite_field.char_poly_pow_card, finite_field.pow_card] lemma zmod.trace_pow_card {p:β„•} [fact p.prime] [nonempty n] (M : matrix n n (zmod p)) : trace n (zmod p) (zmod p) (M ^ p) = (trace n (zmod p) (zmod p) M)^p := by { have h := finite_field.trace_pow_card M, rwa zmod.card at h, } namespace matrix theorem is_integral : is_integral R M := ⟨char_poly M, ⟨char_poly_monic M, aeval_self_char_poly M⟩⟩ theorem min_poly_dvd_char_poly {K : Type*} [field K] (M : matrix n n K) : (minpoly K M) ∣ char_poly M := minpoly.dvd _ _ (aeval_self_char_poly M) end matrix section power_basis open algebra /-- The characteristic polynomial of the map `Ξ» x, a * x` is the minimal polynomial of `a`. In combination with `det_eq_sign_char_poly_coeff` or `trace_eq_neg_char_poly_coeff` and a bit of rewriting, this will allow us to conclude the field norm resp. trace of `x` is the product resp. sum of `x`'s conjugates. -/ lemma char_poly_left_mul_matrix {K S : Type*} [field K] [comm_ring S] [algebra K S] (h : power_basis K S) : char_poly (left_mul_matrix h.basis h.gen) = minpoly K h.gen := begin apply minpoly.unique, { apply char_poly_monic }, { apply (left_mul_matrix _).injective_iff.mp (left_mul_matrix_injective h.basis), rw [← polynomial.aeval_alg_hom_apply, aeval_self_char_poly] }, { intros q q_monic root_q, rw [char_poly_degree_eq_dim, fintype.card_fin, degree_eq_nat_degree q_monic.ne_zero], apply with_bot.some_le_some.mpr, exact h.dim_le_nat_degree_of_root q_monic.ne_zero root_q } end end power_basis
810247d9df224121300ab1d8a64393a19cd143f4
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/category_theory/limits/cones.lean
32a42ae4b3b2406ef01bf11990f091e9a7ed0178
[ "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
13,327
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.const import category_theory.yoneda universes v u u' -- declare the `v`'s first; see `category_theory.category` for an explanation open category_theory -- There is an awkward difficulty with universes here. -- If we allowed `J` to be a small category in `Prop`, we'd run into trouble -- because `yoneda.obj (F : (J β₯€ C)α΅’α΅–)` will be a functor into `Sort (max v 1)`, -- not into `Sort v`. -- So we don't allow this case; it's not particularly useful anyway. variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] open category_theory open category_theory.category open category_theory.functor open opposite namespace category_theory namespace functor variables {J C} (F : J β₯€ C) /-- `F.cones` is the functor assigning to an object `X` the type of natural transformations from the constant functor with value `X` to `F`. An object representing this functor is a limit of `F`. -/ def cones : Cα΅’α΅– β₯€ Type v := (const J).op β‹™ (yoneda.obj F) lemma cones_obj (X : Cα΅’α΅–) : F.cones.obj X = ((const J).obj (unop X) ⟢ F) := rfl @[simp] lemma cones_map_app {X₁ Xβ‚‚ : Cα΅’α΅–} (f : X₁ ⟢ Xβ‚‚) (t : F.cones.obj X₁) (j : J) : (F.cones.map f t).app j = f.unop ≫ t.app j := rfl /-- `F.cocones` is the functor assigning to an object `X` the type of natural transformations from `F` to the constant functor with value `X`. An object corepresenting this functor is a colimit of `F`. -/ def cocones : C β₯€ Type v := const J β‹™ coyoneda.obj (op F) lemma cocones_obj (X : C) : F.cocones.obj X = (F ⟢ (const J).obj X) := rfl @[simp] lemma cocones_map_app {X₁ Xβ‚‚ : C} (f : X₁ ⟢ Xβ‚‚) (t : F.cocones.obj X₁) (j : J) : (F.cocones.map f t).app j = t.app j ≫ f := rfl end functor section variables (J C) /-- Functorially associated to each functor `J β₯€ C`, we have the `C`-presheaf consisting of cones with a given cone point. -/ @[simps] def cones : (J β₯€ C) β₯€ (Cα΅’α΅– β₯€ Type v) := { obj := functor.cones, map := Ξ» F G f, whisker_left (const J).op (yoneda.map f) } /-- Contravariantly associated to each functor `J β₯€ C`, we have the `C`-copresheaf consisting of cocones with a given cocone point. -/ @[simps] def cocones : (J β₯€ C)α΅’α΅– β₯€ (C β₯€ Type v) := { obj := Ξ» F, functor.cocones (unop F), map := Ξ» F G f, whisker_left (const J) (coyoneda.map f) } end namespace limits /-- A `c : cone F` is: * an object `c.X` and * a natural transformation `c.Ο€ : c.X ⟢ F` from the constant `c.X` functor to `F`. `cone F` is equivalent, via `cone.equiv` below, to `Ξ£ X, F.cones.obj X`. -/ structure cone (F : J β₯€ C) := (X : C) (Ο€ : (const J).obj X ⟢ F) @[simp] lemma cone.w {F : J β₯€ C} (c : cone F) {j j' : J} (f : j ⟢ j') : c.Ο€.app j ≫ F.map f = c.Ο€.app j' := by convert ←(c.Ο€.naturality f).symm; apply id_comp /-- A `c : cocone F` is * an object `c.X` and * a natural transformation `c.ΞΉ : F ⟢ c.X` from `F` to the constant `c.X` functor. `cocone F` is equivalent, via `cone.equiv` below, to `Ξ£ X, F.cocones.obj X`. -/ structure cocone (F : J β₯€ C) := (X : C) (ΞΉ : F ⟢ (const J).obj X) @[simp] lemma cocone.w {F : J β₯€ C} (c : cocone F) {j j' : J} (f : j ⟢ j') : F.map f ≫ c.ΞΉ.app j' = c.ΞΉ.app j := by convert ←(c.ΞΉ.naturality f); apply comp_id variables {F : J β₯€ C} namespace cone def equiv (F : J β₯€ C) : cone F β‰… Ξ£ X, F.cones.obj X := { hom := Ξ» c, ⟨op c.X, c.Ο€βŸ©, inv := Ξ» c, { X := unop c.1, Ο€ := c.2 }, hom_inv_id' := begin ext, cases x, refl, end, inv_hom_id' := begin ext, cases x, refl, end } @[simp] def extensions (c : cone F) : yoneda.obj c.X ⟢ F.cones := { app := Ξ» X f, ((const J).map f) ≫ c.Ο€ } /-- A map to the vertex of a cone induces a cone by composition. -/ @[simp] def extend (c : cone F) {X : C} (f : X ⟢ c.X) : cone F := { X := X, Ο€ := c.extensions.app (op X) f } @[simp] lemma extend_Ο€ (c : cone F) {X : Cα΅’α΅–} (f : unop X ⟢ c.X) : (extend c f).Ο€ = c.extensions.app X f := rfl @[simps] def whisker {K : Type v} [small_category K] (E : K β₯€ J) (c : cone F) : cone (E β‹™ F) := { X := c.X, Ο€ := whisker_left E c.Ο€ } end cone namespace cocone def equiv (F : J β₯€ C) : cocone F β‰… Ξ£ X, F.cocones.obj X := { hom := Ξ» c, ⟨c.X, c.ι⟩, inv := Ξ» c, { X := c.1, ΞΉ := c.2 }, hom_inv_id' := begin ext, cases x, refl, end, inv_hom_id' := begin ext, cases x, refl, end } @[simp] def extensions (c : cocone F) : coyoneda.obj (op c.X) ⟢ F.cocones := { app := Ξ» X f, c.ΞΉ ≫ (const J).map f } /-- A map from the vertex of a cocone induces a cocone by composition. -/ @[simp] def extend (c : cocone F) {X : C} (f : c.X ⟢ X) : cocone F := { X := X, ΞΉ := c.extensions.app X f } @[simp] lemma extend_ΞΉ (c : cocone F) {X : C} (f : c.X ⟢ X) : (extend c f).ΞΉ = c.extensions.app X f := rfl @[simps] def whisker {K : Type v} [small_category K] (E : K β₯€ J) (c : cocone F) : cocone (E β‹™ F) := { X := c.X, ΞΉ := whisker_left E c.ΞΉ } end cocone @[ext] structure cone_morphism (A B : cone F) := (hom : A.X ⟢ B.X) (w' : βˆ€ j : J, hom ≫ B.Ο€.app j = A.Ο€.app j . obviously) restate_axiom cone_morphism.w' attribute [simp] cone_morphism.w @[simps] instance cone.category : category.{v} (cone F) := { hom := Ξ» A B, cone_morphism A B, comp := Ξ» X Y Z f g, { hom := f.hom ≫ g.hom, w' := by intro j; rw [assoc, g.w, f.w] }, id := Ξ» B, { hom := πŸ™ B.X } } namespace cones /-- To give an isomorphism between cones, it suffices to give an isomorphism between their vertices which commutes with the cone maps. -/ @[ext, simps] def ext {c c' : cone F} (Ο† : c.X β‰… c'.X) (w : βˆ€ j, c.Ο€.app j = Ο†.hom ≫ c'.Ο€.app j) : c β‰… c' := { hom := { hom := Ο†.hom }, inv := { hom := Ο†.inv, w' := Ξ» j, Ο†.inv_comp_eq.mpr (w j) } } @[simps] def postcompose {G : J β₯€ C} (Ξ± : F ⟢ G) : cone F β₯€ cone G := { obj := Ξ» c, { X := c.X, Ο€ := c.Ο€ ≫ Ξ± }, map := Ξ» c₁ cβ‚‚ f, { hom := f.hom, w' := by intro; erw ← category.assoc; simp [-category.assoc] } } def postcompose_comp {G H : J β₯€ C} (Ξ± : F ⟢ G) (Ξ² : G ⟢ H) : postcompose (Ξ± ≫ Ξ²) β‰… postcompose Ξ± β‹™ postcompose Ξ² := by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously } def postcompose_id : postcompose (πŸ™ F) β‰… 𝟭 (cone F) := by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously } def postcompose_equivalence {G : J β₯€ C} (Ξ± : F β‰… G) : cone F β‰Œ cone G := begin refine equivalence.mk (postcompose Ξ±.hom) (postcompose Ξ±.inv) _ _, { symmetry, refine (postcompose_comp _ _).symm.trans _, rw [iso.hom_inv_id], exact postcompose_id }, { refine (postcompose_comp _ _).symm.trans _, rw [iso.inv_hom_id], exact postcompose_id } end section variable (F) @[simps] def forget : cone F β₯€ C := { obj := Ξ» t, t.X, map := Ξ» s t f, f.hom } variables {D : Type u'} [category.{v} D] @[simps] def functoriality (G : C β₯€ D) : cone F β₯€ cone (F β‹™ G) := { obj := Ξ» A, { X := G.obj A.X, Ο€ := { app := Ξ» j, G.map (A.Ο€.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := Ξ» X Y f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, f.w] } } end end cones @[ext] structure cocone_morphism (A B : cocone F) := (hom : A.X ⟢ B.X) (w' : βˆ€ j : J, A.ΞΉ.app j ≫ hom = B.ΞΉ.app j . obviously) restate_axiom cocone_morphism.w' attribute [simp] cocone_morphism.w @[simps] instance cocone.category : category.{v} (cocone F) := { hom := Ξ» A B, cocone_morphism A B, comp := Ξ» _ _ _ f g, { hom := f.hom ≫ g.hom, w' := by intro j; rw [←assoc, f.w, g.w] }, id := Ξ» B, { hom := πŸ™ B.X } } namespace cocones /-- To give an isomorphism between cocones, it suffices to give an isomorphism between their vertices which commutes with the cocone maps. -/ @[ext, simps] def ext {c c' : cocone F} (Ο† : c.X β‰… c'.X) (w : βˆ€ j, c.ΞΉ.app j ≫ Ο†.hom = c'.ΞΉ.app j) : c β‰… c' := { hom := { hom := Ο†.hom }, inv := { hom := Ο†.inv, w' := Ξ» j, Ο†.comp_inv_eq.mpr (w j).symm } } @[simps] def precompose {G : J β₯€ C} (Ξ± : G ⟢ F) : cocone F β₯€ cocone G := { obj := Ξ» c, { X := c.X, ΞΉ := Ξ± ≫ c.ΞΉ }, map := Ξ» c₁ cβ‚‚ f, { hom := f.hom } } def precompose_comp {G H : J β₯€ C} (Ξ± : F ⟢ G) (Ξ² : G ⟢ H) : precompose (Ξ± ≫ Ξ²) β‰… precompose Ξ² β‹™ precompose Ξ± := by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously } def precompose_id : precompose (πŸ™ F) β‰… 𝟭 (cocone F) := by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously } def precompose_equivalence {G : J β₯€ C} (Ξ± : G β‰… F) : cocone F β‰Œ cocone G := begin refine equivalence.mk (precompose Ξ±.hom) (precompose Ξ±.inv) _ _, { symmetry, refine (precompose_comp _ _).symm.trans _, rw [iso.inv_hom_id], exact precompose_id }, { refine (precompose_comp _ _).symm.trans _, rw [iso.hom_inv_id], exact precompose_id } end section variable (F) @[simps] def forget : cocone F β₯€ C := { obj := Ξ» t, t.X, map := Ξ» s t f, f.hom } variables {D : Type u'} [category.{v} D] @[simps] def functoriality (G : C β₯€ D) : cocone F β₯€ cocone (F β‹™ G) := { obj := Ξ» A, { X := G.obj A.X, ΞΉ := { app := Ξ» j, G.map (A.ΞΉ.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := Ξ» _ _ f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, cocone_morphism.w] } } end end cocones end limits namespace functor variables {D : Type u'} [category.{v} D] variables {F : J β₯€ C} {G : J β₯€ C} (H : C β₯€ D) open category_theory.limits /-- The image of a cone in C under a functor G : C β₯€ D is a cone in D. -/ def map_cone (c : cone F) : cone (F β‹™ H) := (cones.functoriality F H).obj c /-- The image of a cocone in C under a functor G : C β₯€ D is a cocone in D. -/ def map_cocone (c : cocone F) : cocone (F β‹™ H) := (cocones.functoriality F H).obj c @[simp] lemma map_cone_X (c : cone F) : (H.map_cone c).X = H.obj c.X := rfl @[simp] lemma map_cocone_X (c : cocone F) : (H.map_cocone c).X = H.obj c.X := rfl @[simps] def map_cone_inv [is_equivalence H] (c : cone (F β‹™ H)) : cone F := let t := (inv H).map_cone c in let Ξ± : (F β‹™ H) β‹™ inv H ⟢ F := ((whisker_left F is_equivalence.unit_iso.inv) : F β‹™ (H β‹™ inv H) ⟢ _) ≫ (functor.right_unitor _).hom in { X := t.X, Ο€ := ((category_theory.cones J C).map Ξ±).app (op t.X) t.Ο€ } def map_cone_morphism {c c' : cone F} (f : c ⟢ c') : (H.map_cone c) ⟢ (H.map_cone c') := (cones.functoriality F H).map f def map_cocone_morphism {c c' : cocone F} (f : c ⟢ c') : (H.map_cocone c) ⟢ (H.map_cocone c') := (cocones.functoriality F H).map f @[simp] lemma map_cone_Ο€ (c : cone F) (j : J) : (map_cone H c).Ο€.app j = H.map (c.Ο€.app j) := rfl @[simp] lemma map_cocone_ΞΉ (c : cocone F) (j : J) : (map_cocone H c).ΞΉ.app j = H.map (c.ΞΉ.app j) := rfl /-- `map_cone` is the left inverse to `map_cone_inv`. -/ def map_cone_map_cone_inv {F : J β₯€ D} (H : D β₯€ C) [is_equivalence H] (c : cone (F β‹™ H)) : map_cone H (map_cone_inv H c) β‰… c := begin apply cones.ext _ (Ξ» j, _), { exact H.inv_fun_id.app c.X }, { dsimp, erw [comp_id, ← H.inv_fun_id.hom.naturality (c.Ο€.app j), comp_map, H.map_comp], congr' 1, erw [← cancel_epi (H.inv_fun_id.inv.app (H.obj (F.obj j))), nat_iso.inv_hom_id_app, ← (functor.as_equivalence H).functor_unit _, ← H.map_comp, nat_iso.hom_inv_id_app, H.map_id], refl } end end functor end category_theory namespace category_theory.limits variables {F : J β₯€ Cα΅’α΅–} -- Here and below we only automatically generate the `@[simp]` lemma for the `X` field, -- as we can be a simpler `rfl` lemma for the components of the natural transformation by hand. @[simps X] def cone_of_cocone_left_op (c : cocone F.left_op) : cone F := { X := op c.X, Ο€ := nat_trans.right_op (c.ΞΉ ≫ (const.op_obj_unop (op c.X)).hom) } @[simp] lemma cone_of_cocone_left_op_Ο€_app (c : cocone F.left_op) (j) : (cone_of_cocone_left_op c).Ο€.app j = (c.ΞΉ.app (op j)).op := by { dsimp [cone_of_cocone_left_op], simp } @[simps X] def cocone_left_op_of_cone (c : cone F) : cocone (F.left_op) := { X := unop c.X, ΞΉ := nat_trans.left_op c.Ο€ } @[simp] lemma cocone_left_op_of_cone_ΞΉ_app (c : cone F) (j) : (cocone_left_op_of_cone c).ΞΉ.app j = (c.Ο€.app (unop j)).unop := by { dsimp [cocone_left_op_of_cone], simp } @[simps X] def cocone_of_cone_left_op (c : cone F.left_op) : cocone F := { X := op c.X, ΞΉ := nat_trans.right_op ((const.op_obj_unop (op c.X)).hom ≫ c.Ο€) } @[simp] lemma cocone_of_cone_left_op_ΞΉ_app (c : cone F.left_op) (j) : (cocone_of_cone_left_op c).ΞΉ.app j = (c.Ο€.app (op j)).op := by { dsimp [cocone_of_cone_left_op], simp } @[simps X] def cone_left_op_of_cocone (c : cocone F) : cone (F.left_op) := { X := unop c.X, Ο€ := nat_trans.left_op c.ΞΉ } @[simp] lemma cone_left_op_of_cocone_Ο€_app (c : cocone F) (j) : (cone_left_op_of_cocone c).Ο€.app j = (c.ΞΉ.app (unop j)).unop := by { dsimp [cone_left_op_of_cocone], simp } end category_theory.limits
aecf6d57879e55fe648f71a1d1e32e8d03046f54
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/bad_structures.lean
f0aeab7cce60fdb70e5eda9cc4a1fc4e4c29bae9
[ "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
341
lean
prelude namespace foo structure {l} prod (A : Sort l) (B : Sort l) := (pr1 : A) (pr2 : B) structure {l} prod1 (A : Sort l) (B : Sort l) : Type := (pr1 : A) (pr2 : B) structure {l} prod2 (A : Sort l) (B : Sort l) : Sort l := (pr1 : A) (pr2 : B) structure {l} prod3 (A : Sort l) (B : Sort l) : Sort (max 1 l) := (pr1 : A) (pr2 : B) end foo
ee46d639a4f65a1e980e8b99742d7bfa71a373b0
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/real/cau_seq.lean
82fee058380cf365e3e5f1313e413cc05415be87
[ "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
30,777
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.order.absolute_value import algebra.big_operators.order /-! # Cauchy sequences A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where applicable, lemmas that will be reused in other contexts have been stated in extra generality. There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology. This is a concrete implementation that is useful for simplicity and computability reasons. ## Important definitions * `is_cau_seq`: a predicate that says `f : β„• β†’ Ξ²` is Cauchy. * `cau_seq`: the type of Cauchy sequences valued in type `Ξ²` with respect to an absolute value function `abv`. ## Tags sequence, cauchy, abs val, absolute value -/ open_locale big_operators open is_absolute_value theorem exists_forall_ge_and {Ξ±} [linear_order Ξ±] {P Q : Ξ± β†’ Prop} : (βˆƒ i, βˆ€ j β‰₯ i, P j) β†’ (βˆƒ i, βˆ€ j β‰₯ i, Q j) β†’ βˆƒ i, βˆ€ j β‰₯ i, P j ∧ Q j | ⟨a, hβ‚βŸ© ⟨b, hβ‚‚βŸ© := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in ⟨c, Ξ» j hj, ⟨h₁ _ (le_trans ac hj), hβ‚‚ _ (le_trans bc hj)⟩⟩ section variables {Ξ± : Type*} [linear_ordered_field Ξ±] {Ξ² : Type*} [ring Ξ²] (abv : Ξ² β†’ Ξ±) [is_absolute_value abv] theorem rat_add_continuous_lemma {Ξ΅ : Ξ±} (Ξ΅0 : 0 < Ξ΅) : βˆƒ Ξ΄ > 0, βˆ€ {a₁ aβ‚‚ b₁ bβ‚‚ : Ξ²}, abv (a₁ - b₁) < Ξ΄ β†’ abv (aβ‚‚ - bβ‚‚) < Ξ΄ β†’ abv (a₁ + aβ‚‚ - (b₁ + bβ‚‚)) < Ξ΅ := ⟨Ρ / 2, half_pos Ξ΅0, Ξ» a₁ aβ‚‚ b₁ bβ‚‚ h₁ hβ‚‚, by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm, add_assoc] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ hβ‚‚)⟩ theorem rat_mul_continuous_lemma {Ξ΅ K₁ Kβ‚‚ : Ξ±} (Ξ΅0 : 0 < Ξ΅) : βˆƒ Ξ΄ > 0, βˆ€ {a₁ aβ‚‚ b₁ bβ‚‚ : Ξ²}, abv a₁ < K₁ β†’ abv bβ‚‚ < Kβ‚‚ β†’ abv (a₁ - b₁) < Ξ΄ β†’ abv (aβ‚‚ - bβ‚‚) < Ξ΄ β†’ abv (a₁ * aβ‚‚ - b₁ * bβ‚‚) < Ξ΅ := begin have K0 : (0 : Ξ±) < max 1 (max K₁ Kβ‚‚) := lt_of_lt_of_le zero_lt_one (le_max_left _ _), have Ξ΅K := div_pos (half_pos Ξ΅0) K0, refine ⟨_, Ξ΅K, Ξ» a₁ aβ‚‚ b₁ bβ‚‚ ha₁ hbβ‚‚ h₁ hβ‚‚, _⟩, replace ha₁ := lt_of_lt_of_le ha₁ (le_trans (le_max_left _ Kβ‚‚) (le_max_right 1 _)), replace hbβ‚‚ := lt_of_lt_of_le hbβ‚‚ (le_trans (le_max_right K₁ _) (le_max_right 1 _)), have := add_lt_add (mul_lt_mul' (le_of_lt h₁) hbβ‚‚ (abv_nonneg abv _) Ξ΅K) (mul_lt_mul' (le_of_lt hβ‚‚) ha₁ (abv_nonneg abv _) Ξ΅K), rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this, simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm] using lt_of_le_of_lt (abv_add abv _ _) this end theorem rat_inv_continuous_lemma {Ξ² : Type*} [field Ξ²] (abv : Ξ² β†’ Ξ±) [is_absolute_value abv] {Ξ΅ K : Ξ±} (Ξ΅0 : 0 < Ξ΅) (K0 : 0 < K) : βˆƒ Ξ΄ > 0, βˆ€ {a b : Ξ²}, K ≀ abv a β†’ K ≀ abv b β†’ abv (a - b) < Ξ΄ β†’ abv (a⁻¹ - b⁻¹) < Ξ΅ := begin have KK := mul_pos K0 K0, have Ξ΅K := mul_pos Ξ΅0 KK, refine ⟨_, Ξ΅K, Ξ» a b ha hb h, _⟩, have a0 := lt_of_lt_of_le K0 ha, have b0 := lt_of_lt_of_le K0 hb, rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0), abv_div abv, abv_mul abv, mul_comm, abv_sub abv, ← mul_div_cancel Ξ΅ (ne_of_gt KK)], exact div_lt_div h (mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _)) (le_of_lt $ mul_pos Ξ΅0 KK) KK end end /-- A sequence is Cauchy if the distance between its entries tends to zero. -/ def is_cau_seq {Ξ± : Type*} [linear_ordered_field Ξ±] {Ξ² : Type*} [ring Ξ²] (abv : Ξ² β†’ Ξ±) (f : β„• β†’ Ξ²) : Prop := βˆ€ Ξ΅ > 0, βˆƒ i, βˆ€ j β‰₯ i, abv (f j - f i) < Ξ΅ namespace is_cau_seq variables {Ξ± : Type*} [linear_ordered_field Ξ±] {Ξ² : Type*} [ring Ξ²] {abv : Ξ² β†’ Ξ±} [is_absolute_value abv] {f : β„• β†’ Ξ²} @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchyβ‚‚ (hf : is_cau_seq abv f) {Ξ΅ : Ξ±} (Ξ΅0 : 0 < Ξ΅) : βˆƒ i, βˆ€ j k β‰₯ i, abv (f j - f k) < Ξ΅ := begin refine (hf _ (half_pos Ξ΅0)).imp (Ξ» i hi j ij k ik, _), rw ← add_halves Ξ΅, refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _), rw abv_sub abv, exact hi _ ik end theorem cauchy₃ (hf : is_cau_seq abv f) {Ξ΅ : Ξ±} (Ξ΅0 : 0 < Ξ΅) : βˆƒ i, βˆ€ j β‰₯ i, βˆ€ k β‰₯ j, abv (f k - f j) < Ξ΅ := let ⟨i, H⟩ := hf.cauchyβ‚‚ Ξ΅0 in ⟨i, Ξ» j ij k jk, H _ (le_trans ij jk) _ ij⟩ end is_cau_seq /-- `cau_seq Ξ² abv` is the type of `Ξ²`-valued Cauchy sequences, with respect to the absolute value function `abv`. -/ def cau_seq {Ξ± : Type*} [linear_ordered_field Ξ±] (Ξ² : Type*) [ring Ξ²] (abv : Ξ² β†’ Ξ±) : Type* := {f : β„• β†’ Ξ² // is_cau_seq abv f} namespace cau_seq variables {Ξ± : Type*} [linear_ordered_field Ξ±] section ring variables {Ξ² : Type*} [ring Ξ²] {abv : Ξ² β†’ Ξ±} instance : has_coe_to_fun (cau_seq Ξ² abv) (Ξ» _, β„• β†’ Ξ²) := ⟨subtype.val⟩ @[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) : @coe_fn (cau_seq Ξ² abv) _ _ ⟨f, hf⟩ = f := rfl theorem ext {f g : cau_seq Ξ² abv} (h : βˆ€ i, f i = g i) : f = g := subtype.eq (funext h) theorem is_cau (f : cau_seq Ξ² abv) : is_cau_seq abv f := f.2 theorem cauchy (f : cau_seq Ξ² abv) : βˆ€ {Ξ΅}, 0 < Ξ΅ β†’ βˆƒ i, βˆ€ j β‰₯ i, abv (f j - f i) < Ξ΅ := f.2 /-- Given a Cauchy sequence `f`, create a Cauchy sequence from a sequence `g` with the same values as `f`. -/ def of_eq (f : cau_seq Ξ² abv) (g : β„• β†’ Ξ²) (e : βˆ€ i, f i = g i) : cau_seq Ξ² abv := ⟨g, Ξ» Ξ΅, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩ variable [is_absolute_value abv] @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchyβ‚‚ (f : cau_seq Ξ² abv) {Ξ΅} : 0 < Ξ΅ β†’ βˆƒ i, βˆ€ j k β‰₯ i, abv (f j - f k) < Ξ΅ := f.2.cauchyβ‚‚ theorem cauchy₃ (f : cau_seq Ξ² abv) {Ξ΅} : 0 < Ξ΅ β†’ βˆƒ i, βˆ€ j β‰₯ i, βˆ€ k β‰₯ j, abv (f k - f j) < Ξ΅ := f.2.cauchy₃ theorem bounded (f : cau_seq Ξ² abv) : βˆƒ r, βˆ€ i, abv (f i) < r := begin cases f.cauchy zero_lt_one with i h, let R := βˆ‘ j in finset.range (i+1), abv (f j), have : βˆ€ j ≀ i, abv (f j) ≀ R, { intros j ij, change (Ξ» j, abv (f j)) j ≀ R, apply finset.single_le_sum, { intros, apply abv_nonneg abv }, { rwa [finset.mem_range, nat.lt_succ_iff] } }, refine ⟨R + 1, Ξ» j, _⟩, cases lt_or_le j i with ij ij, { exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) }, { have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add_of_le_of_lt (this _ le_rfl) (h _ ij)), rw [add_sub, add_comm] at this, simpa } end theorem bounded' (f : cau_seq Ξ² abv) (x : Ξ±) : βˆƒ r > x, βˆ€ i, abv (f i) < r := let ⟨r, h⟩ := f.bounded in ⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _), Ξ» i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩ instance : has_add (cau_seq Ξ² abv) := ⟨λ f g, ⟨λ i, (f i + g i : Ξ²), Ξ» Ξ΅ Ξ΅0, let ⟨δ, Ξ΄0, Hδ⟩ := rat_add_continuous_lemma abv Ξ΅0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ Ξ΄0) (g.cauchy₃ Ξ΄0) in ⟨i, Ξ» j ij, let ⟨H₁, Hβ‚‚βŸ© := H _ le_rfl in HΞ΄ (H₁ _ ij) (Hβ‚‚ _ ij)⟩⟩⟩ @[simp] theorem add_apply (f g : cau_seq Ξ² abv) (i : β„•) : (f + g) i = f i + g i := rfl variable (abv) /-- The constant Cauchy sequence. -/ def const (x : Ξ²) : cau_seq Ξ² abv := ⟨λ i, x, Ξ» Ξ΅ Ξ΅0, ⟨0, Ξ» j ij, by simpa [abv_zero abv] using Ξ΅0⟩⟩ variable {abv} local notation `const` := const abv @[simp] theorem const_apply (x : Ξ²) (i : β„•) : (const x : β„• β†’ Ξ²) i = x := rfl theorem const_inj {x y : Ξ²} : (const x : cau_seq Ξ² abv) = const y ↔ x = y := ⟨λ h, congr_arg (Ξ» f:cau_seq Ξ² abv, (f:β„•β†’Ξ²) 0) h, congr_arg _⟩ instance : has_zero (cau_seq Ξ² abv) := ⟨const 0⟩ instance : has_one (cau_seq Ξ² abv) := ⟨const 1⟩ instance : inhabited (cau_seq Ξ² abv) := ⟨0⟩ @[simp] theorem zero_apply (i) : (0 : cau_seq Ξ² abv) i = 0 := rfl @[simp] theorem one_apply (i) : (1 : cau_seq Ξ² abv) i = 1 := rfl @[simp] theorem const_zero : const 0 = 0 := rfl theorem const_add (x y : Ξ²) : const (x + y) = const x + const y := rfl instance : has_mul (cau_seq Ξ² abv) := ⟨λ f g, ⟨λ i, (f i * g i : Ξ²), Ξ» Ξ΅ Ξ΅0, let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0, ⟨δ, Ξ΄0, Hδ⟩ := rat_mul_continuous_lemma abv Ξ΅0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ Ξ΄0) (g.cauchy₃ Ξ΄0) in ⟨i, Ξ» j ij, let ⟨H₁, Hβ‚‚βŸ© := H _ le_rfl in HΞ΄ (hF j) (hG i) (H₁ _ ij) (Hβ‚‚ _ ij)⟩⟩⟩ @[simp] theorem mul_apply (f g : cau_seq Ξ² abv) (i : β„•) : (f * g) i = f i * g i := rfl theorem const_mul (x y : Ξ²) : const (x * y) = const x * const y := ext $ Ξ» i, rfl instance : has_neg (cau_seq Ξ² abv) := ⟨λ f, of_eq (const (-1) * f) (Ξ» x, -f x) (Ξ» i, by simp)⟩ @[simp] theorem neg_apply (f : cau_seq Ξ² abv) (i) : (-f) i = -f i := rfl theorem const_neg (x : Ξ²) : const (-x) = -const x := ext $ Ξ» i, rfl instance : has_sub (cau_seq Ξ² abv) := ⟨λ f g, of_eq (f + -g) (Ξ» x, f x - g x) (Ξ» i, by simp [sub_eq_add_neg])⟩ @[simp] theorem sub_apply (f g : cau_seq Ξ² abv) (i : β„•) : (f - g) i = f i - g i := rfl theorem const_sub (x y : Ξ²) : const (x - y) = const x - const y := ext $ Ξ» i, rfl instance : add_group (cau_seq Ξ² abv) := by refine_struct { add := (+), neg := has_neg.neg, zero := (0 : cau_seq Ξ² abv), sub := has_sub.sub, zsmul := @zsmul_rec (cau_seq Ξ² abv) ⟨0⟩ ⟨(+)⟩ ⟨has_neg.neg⟩, nsmul := @nsmul_rec (cau_seq Ξ² abv) ⟨0⟩ ⟨(+)⟩ }; intros; try { refl }; apply ext; simp [add_comm, add_left_comm, sub_eq_add_neg] instance : add_group_with_one (cau_seq Ξ² abv) := { one := 1, nat_cast := Ξ» n, const n, nat_cast_zero := congr_arg const nat.cast_zero, nat_cast_succ := Ξ» n, congr_arg const (nat.cast_succ n), int_cast := Ξ» n, const n, int_cast_of_nat := Ξ» n, congr_arg const (int.cast_of_nat n), int_cast_neg_succ_of_nat := Ξ» n, congr_arg const (int.cast_neg_succ_of_nat n), .. cau_seq.add_group } instance : ring (cau_seq Ξ² abv) := by refine_struct { add := (+), zero := (0 : cau_seq Ξ² abv), mul := (*), one := 1, npow := @npow_rec (cau_seq Ξ² abv) ⟨1⟩ ⟨(*)⟩, .. cau_seq.add_group_with_one }; intros; try { refl }; apply ext; simp [mul_add, mul_assoc, add_mul, add_comm, add_left_comm, sub_eq_add_neg] instance {Ξ² : Type*} [comm_ring Ξ²] {abv : Ξ² β†’ Ξ±} [is_absolute_value abv] : comm_ring (cau_seq Ξ² abv) := { mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm], ..cau_seq.ring } /-- `lim_zero f` holds when `f` approaches 0. -/ def lim_zero {abv : Ξ² β†’ Ξ±} (f : cau_seq Ξ² abv) : Prop := βˆ€ Ξ΅ > 0, βˆƒ i, βˆ€ j β‰₯ i, abv (f j) < Ξ΅ theorem add_lim_zero {f g : cau_seq Ξ² abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g) | Ξ΅ Ξ΅0 := (exists_forall_ge_and (hf _ $ half_pos Ξ΅0) (hg _ $ half_pos Ξ΅0)).imp $ Ξ» i H j ij, let ⟨H₁, Hβ‚‚βŸ© := H _ ij in by simpa [add_halves Ξ΅] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ Hβ‚‚) theorem mul_lim_zero_right (f : cau_seq Ξ² abv) {g} (hg : lim_zero g) : lim_zero (f * g) | Ξ΅ Ξ΅0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in (hg _ $ div_pos Ξ΅0 F0).imp $ Ξ» i H j ij, by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0; rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this theorem mul_lim_zero_left {f} (g : cau_seq Ξ² abv) (hg : lim_zero f) : lim_zero (f * g) | Ξ΅ Ξ΅0 := let ⟨G, G0, hG⟩ := g.bounded' 0 in (hg _ $ div_pos Ξ΅0 G0).imp $ Ξ» i H j ij, by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _); rwa [div_mul_cancel _ (ne_of_gt G0), ← abv_mul abv] at this theorem neg_lim_zero {f : cau_seq Ξ² abv} (hf : lim_zero f) : lim_zero (-f) := by rw ← neg_one_mul; exact mul_lim_zero_right _ hf theorem sub_lim_zero {f g : cau_seq Ξ² abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) := by simpa only [sub_eq_add_neg] using add_lim_zero hf (neg_lim_zero hg) theorem lim_zero_sub_rev {f g : cau_seq Ξ² abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) := by simpa using neg_lim_zero hfg theorem zero_lim_zero : lim_zero (0 : cau_seq Ξ² abv) | Ξ΅ Ξ΅0 := ⟨0, Ξ» j ij, by simpa [abv_zero abv] using Ξ΅0⟩ theorem const_lim_zero {x : Ξ²} : lim_zero (const x) ↔ x = 0 := ⟨λ H, (abv_eq_zero abv).1 $ eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $ Ξ» Ξ΅ Ξ΅0, let ⟨i, hi⟩ := H _ Ξ΅0 in le_of_lt $ hi _ le_rfl, Ξ» e, e.symm β–Έ zero_lim_zero⟩ instance equiv : setoid (cau_seq Ξ² abv) := ⟨λ f g, lim_zero (f - g), ⟨λ f, by simp [zero_lim_zero], Ξ» f g h, by simpa using neg_lim_zero h, Ξ» f g h fg gh, by simpa [sub_eq_add_neg, add_assoc] using add_lim_zero fg gh⟩⟩ lemma add_equiv_add {f1 f2 g1 g2 : cau_seq Ξ² abv} (hf : f1 β‰ˆ f2) (hg : g1 β‰ˆ g2) : f1 + g1 β‰ˆ f2 + g2 := by simpa only [←add_sub_add_comm] using add_lim_zero hf hg lemma neg_equiv_neg {f g : cau_seq Ξ² abv} (hf : f β‰ˆ g) : -f β‰ˆ -g := by simpa only [neg_sub'] using neg_lim_zero hf lemma sub_equiv_sub {f1 f2 g1 g2 : cau_seq Ξ² abv} (hf : f1 β‰ˆ f2) (hg : g1 β‰ˆ g2) : f1 - g1 β‰ˆ f2 - g2 := by simpa only [sub_eq_add_neg] using add_equiv_add hf (neg_equiv_neg hg) theorem equiv_def₃ {f g : cau_seq Ξ² abv} (h : f β‰ˆ g) {Ξ΅ : Ξ±} (Ξ΅0 : 0 < Ξ΅) : βˆƒ i, βˆ€ j β‰₯ i, βˆ€ k β‰₯ j, abv (f k - g j) < Ξ΅ := (exists_forall_ge_and (h _ $ half_pos Ξ΅0) (f.cauchy₃ $ half_pos Ξ΅0)).imp $ Ξ» i H j ij k jk, let ⟨h₁, hβ‚‚βŸ© := H _ ij in by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (hβ‚‚ _ jk)); rwa [sub_add_sub_cancel', add_halves] at this theorem lim_zero_congr {f g : cau_seq Ξ² abv} (h : f β‰ˆ g) : lim_zero f ↔ lim_zero g := ⟨λ l, by simpa using add_lim_zero (setoid.symm h) l, Ξ» l, by simpa using add_lim_zero h l⟩ theorem abv_pos_of_not_lim_zero {f : cau_seq Ξ² abv} (hf : Β¬ lim_zero f) : βˆƒ K > 0, βˆƒ i, βˆ€ j β‰₯ i, K ≀ abv (f j) := begin haveI := classical.prop_decidable, by_contra nk, refine hf (Ξ» Ξ΅ Ξ΅0, _), simp [not_forall] at nk, cases f.cauchy₃ (half_pos Ξ΅0) with i hi, rcases nk _ (half_pos Ξ΅0) i with ⟨j, ij, hj⟩, refine ⟨j, Ξ» k jk, _⟩, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj), rwa [sub_add_cancel, add_halves] at this end theorem of_near (f : β„• β†’ Ξ²) (g : cau_seq Ξ² abv) (h : βˆ€ Ξ΅ > 0, βˆƒ i, βˆ€ j β‰₯ i, abv (f j - g j) < Ξ΅) : is_cau_seq abv f | Ξ΅ Ξ΅0 := let ⟨i, hi⟩ := exists_forall_ge_and (h _ (half_pos $ half_pos Ξ΅0)) (g.cauchy₃ $ half_pos Ξ΅0) in ⟨i, Ξ» j ij, begin cases hi _ le_rfl with h₁ hβ‚‚, rw abv_sub abv at h₁, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁), have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (hβ‚‚ _ ij)), rwa [add_halves, add_halves, add_right_comm, sub_add_sub_cancel, sub_add_sub_cancel] at this end⟩ lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : Β¬ f β‰ˆ 0) : Β¬ lim_zero f := assume : lim_zero f, have lim_zero (f - 0), by simpa, hf this lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f β‰ˆ 0) : g * f β‰ˆ 0 := have lim_zero (f - 0), from hf, have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa, show lim_zero (g*f - 0), by simpa lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : Β¬ f β‰ˆ 0) (hg : Β¬ g β‰ˆ 0) : Β¬ (f * g) β‰ˆ 0 := assume : lim_zero (f*g - 0), have hlz : lim_zero (f*g), by simpa, have hf' : Β¬ lim_zero f, by simpa using (show Β¬ lim_zero (f - 0), from hf), have hg' : Β¬ lim_zero g, by simpa using (show Β¬ lim_zero (g - 0), from hg), begin rcases abv_pos_of_not_lim_zero hf' with ⟨a1, ha1, N1, hN1⟩, rcases abv_pos_of_not_lim_zero hg' with ⟨a2, ha2, N2, hN2⟩, have : 0 < a1 * a2, from mul_pos ha1 ha2, cases hlz _ this with N hN, let i := max N (max N1 N2), have hN' := hN i (le_max_left _ _), have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)), have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)), apply not_le_of_lt hN', change _ ≀ abv (_ * _), rw is_absolute_value.abv_mul abv, apply mul_le_mul; try { assumption }, { apply le_of_lt ha2 }, { apply is_absolute_value.abv_nonneg abv } end theorem const_equiv {x y : Ξ²} : const x β‰ˆ const y ↔ x = y := show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero] end ring section comm_ring variables {Ξ² : Type*} [comm_ring Ξ²] {abv : Ξ² β†’ Ξ±} [is_absolute_value abv] lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f β‰ˆ 0) : f * g β‰ˆ 0 := by rw mul_comm; apply mul_equiv_zero _ hf lemma mul_equiv_mul {f1 f2 g1 g2 : cau_seq Ξ² abv} (hf : f1 β‰ˆ f2) (hg : g1 β‰ˆ g2) : f1 * g1 β‰ˆ f2 * g2 := by simpa only [mul_sub, mul_comm, sub_add_sub_cancel] using add_lim_zero (mul_lim_zero_right g1 hf) (mul_lim_zero_right f2 hg) end comm_ring section is_domain variables {Ξ² : Type*} [ring Ξ²] [is_domain Ξ²] (abv : Ξ² β†’ Ξ±) [is_absolute_value abv] lemma one_not_equiv_zero : Β¬ (const abv 1) β‰ˆ (const abv 0) := assume h, have βˆ€ Ξ΅ > 0, βˆƒ i, βˆ€ k, i ≀ k β†’ abv (1 - 0) < Ξ΅, from h, have h1 : abv 1 ≀ 0, from le_of_not_gt $ assume h2 : 0 < abv 1, exists.elim (this _ h2) $ Ξ» i hi, lt_irrefl (abv 1) $ by simpa using hi _ le_rfl, have h2 : 0 ≀ abv 1, from is_absolute_value.abv_nonneg _ _, have abv 1 = 0, from le_antisymm h1 h2, have (1 : Ξ²) = 0, from (is_absolute_value.abv_eq_zero abv).1 this, absurd this one_ne_zero end is_domain section field variables {Ξ² : Type*} [field Ξ²] {abv : Ξ² β†’ Ξ±} [is_absolute_value abv] theorem inv_aux {f : cau_seq Ξ² abv} (hf : Β¬ lim_zero f) : βˆ€ Ξ΅ > 0, βˆƒ i, βˆ€ j β‰₯ i, abv ((f j)⁻¹ - (f i)⁻¹) < Ξ΅ | Ξ΅ Ξ΅0 := let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf, ⟨δ, Ξ΄0, Hδ⟩ := rat_inv_continuous_lemma abv Ξ΅0 K0, ⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ Ξ΄0) in ⟨i, Ξ» j ij, let ⟨iK, H'⟩ := H _ le_rfl in HΞ΄ (H _ ij).1 iK (H' _ ij)⟩ /-- Given a Cauchy sequence `f` with nonzero limit, create a Cauchy sequence with values equal to the inverses of the values of `f`. -/ def inv (f : cau_seq Ξ² abv) (hf : Β¬ lim_zero f) : cau_seq Ξ² abv := ⟨_, inv_aux hf⟩ @[simp] theorem inv_apply {f : cau_seq Ξ² abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl theorem inv_mul_cancel {f : cau_seq Ξ² abv} (hf) : inv f hf * f β‰ˆ 1 := Ξ» Ξ΅ Ξ΅0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in ⟨i, Ξ» j ij, by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)), abv_zero abv] using Ξ΅0⟩ theorem const_inv {x : Ξ²} (hx : x β‰  0) : const abv (x⁻¹) = inv (const abv x) (by rwa const_lim_zero) := ext (assume n, by simp[inv_apply, const_apply]) end field section abs local notation `const` := const abs /-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/ def pos (f : cau_seq Ξ± abs) : Prop := βˆƒ K > 0, βˆƒ i, βˆ€ j β‰₯ i, K ≀ f j theorem not_lim_zero_of_pos {f : cau_seq Ξ± abs} : pos f β†’ Β¬ lim_zero f | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0), ⟨h₁, hβ‚‚βŸ© := h _ le_rfl in not_lt_of_le h₁ (abs_lt.1 hβ‚‚).2 theorem const_pos {x : Ξ±} : pos (const x) ↔ 0 < x := ⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ le_rfl), Ξ» h, ⟨x, h, 0, Ξ» j _, le_rfl⟩⟩ theorem add_pos {f g : cau_seq Ξ± abs} : pos f β†’ pos g β†’ pos (f + g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.add_pos F0 G0, i, Ξ» j ij, let ⟨h₁, hβ‚‚βŸ© := h _ ij in add_le_add h₁ hβ‚‚βŸ© theorem pos_add_lim_zero {f g : cau_seq Ξ± abs} : pos f β†’ lim_zero g β†’ pos (f + g) | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in ⟨_, half_pos F0, i, Ξ» j ij, begin cases h j ij with h₁ hβ‚‚, have := add_le_add h₁ (le_of_lt (abs_lt.1 hβ‚‚).1), rwa [← sub_eq_add_neg, sub_self_div_two] at this end⟩ protected theorem mul_pos {f g : cau_seq Ξ± abs} : pos f β†’ pos g β†’ pos (f * g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.mul_pos F0 G0, i, Ξ» j ij, let ⟨h₁, hβ‚‚βŸ© := h _ ij in mul_le_mul h₁ hβ‚‚ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩ theorem trichotomy (f : cau_seq Ξ± abs) : pos f ∨ lim_zero f ∨ pos (-f) := begin cases classical.em (lim_zero f); simp *, rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩, rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩, refine (le_total 0 (f i)).imp _ _; refine (Ξ» h, ⟨K, K0, i, Ξ» j ij, _⟩); have := (hi _ ij).1; cases hi _ le_rfl with h₁ hβ‚‚, { rwa abs_of_nonneg at this, rw abs_of_nonneg h at h₁, exact (le_add_iff_nonneg_right _).1 (le_trans h₁ $ neg_le_sub_iff_le_add'.1 $ le_of_lt (abs_lt.1 $ hβ‚‚ _ ij).1) }, { rwa abs_of_nonpos at this, rw abs_of_nonpos h at h₁, rw [← sub_le_sub_iff_right, zero_sub], exact le_trans (le_of_lt (abs_lt.1 $ hβ‚‚ _ ij).2) h₁ } end instance : has_lt (cau_seq Ξ± abs) := ⟨λ f g, pos (g - f)⟩ instance : has_le (cau_seq Ξ± abs) := ⟨λ f g, f < g ∨ f β‰ˆ g⟩ theorem lt_of_lt_of_eq {f g h : cau_seq Ξ± abs} (fg : f < g) (gh : g β‰ˆ h) : f < h := show pos (h - f), by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh) theorem lt_of_eq_of_lt {f g h : cau_seq Ξ± abs} (fg : f β‰ˆ g) (gh : g < h) : f < h := by have := pos_add_lim_zero gh (neg_lim_zero fg); rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this theorem lt_trans {f g h : cau_seq Ξ± abs} (fg : f < g) (gh : g < h) : f < h := show pos (h - f), by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh theorem lt_irrefl {f : cau_seq Ξ± abs} : Β¬ f < f | h := not_lim_zero_of_pos h (by simp [zero_lim_zero]) lemma le_of_eq_of_le {f g h : cau_seq Ξ± abs} (hfg : f β‰ˆ g) (hgh : g ≀ h) : f ≀ h := hgh.elim (or.inl ∘ cau_seq.lt_of_eq_of_lt hfg) (or.inr ∘ setoid.trans hfg) lemma le_of_le_of_eq {f g h : cau_seq Ξ± abs} (hfg : f ≀ g) (hgh : g β‰ˆ h) : f ≀ h := hfg.elim (Ξ» h, or.inl (cau_seq.lt_of_lt_of_eq h hgh)) (Ξ» h, or.inr (setoid.trans h hgh)) instance : preorder (cau_seq Ξ± abs) := { lt := (<), le := Ξ» f g, f < g ∨ f β‰ˆ g, le_refl := Ξ» f, or.inr (setoid.refl _), le_trans := Ξ» f g h fg, match fg with | or.inl fg, or.inl gh := or.inl $ lt_trans fg gh | or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh | or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh | or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh end, lt_iff_le_not_le := Ξ» f g, ⟨λ h, ⟨or.inl h, not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩, Ξ» ⟨h₁, hβ‚‚βŸ©, h₁.resolve_right (mt (Ξ» h, or.inr (setoid.symm h)) hβ‚‚)⟩ } theorem le_antisymm {f g : cau_seq Ξ± abs} (fg : f ≀ g) (gf : g ≀ f) : f β‰ˆ g := fg.resolve_left (not_lt_of_le gf) theorem lt_total (f g : cau_seq Ξ± abs) : f < g ∨ f β‰ˆ g ∨ g < f := (trichotomy (g - f)).imp_right (Ξ» h, h.imp (Ξ» h, setoid.symm h) (Ξ» h, by rwa neg_sub at h)) theorem le_total (f g : cau_seq Ξ± abs) : f ≀ g ∨ g ≀ f := (or.assoc.2 (lt_total f g)).imp_right or.inl theorem const_lt {x y : Ξ±} : const x < const y ↔ x < y := show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos] theorem const_le {x y : Ξ±} : const x ≀ const y ↔ x ≀ y := by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv lemma le_of_exists {f g : cau_seq Ξ± abs} (h : βˆƒ i, βˆ€ j β‰₯ i, f j ≀ g j) : f ≀ g := let ⟨i, hi⟩ := h in (or.assoc.2 (cau_seq.lt_total f g)).elim id (Ξ» hgf, false.elim (let ⟨K, hK0, j, hKj⟩ := hgf in not_lt_of_ge (hi (max i j) (le_max_left _ _)) (sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _)))))) theorem exists_gt (f : cau_seq Ξ± abs) : βˆƒ a : Ξ±, f < const a := let ⟨K, H⟩ := f.bounded in ⟨K + 1, 1, zero_lt_one, 0, Ξ» i _, begin rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right], exact le_of_lt (abs_lt.1 (H _)).2 end⟩ theorem exists_lt (f : cau_seq Ξ± abs) : βˆƒ a : Ξ±, const a < f := let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _, by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩ -- so named to match `rat_add_continuous_lemma` theorem _root_.rat_sup_continuous_lemma {Ξ΅ : Ξ±} {a₁ aβ‚‚ b₁ bβ‚‚ : Ξ±} : abs (a₁ - b₁) < Ξ΅ β†’ abs (aβ‚‚ - bβ‚‚) < Ξ΅ β†’ abs (a₁ βŠ” aβ‚‚ - (b₁ βŠ” bβ‚‚)) < Ξ΅ := Ξ» h₁ hβ‚‚, (abs_max_sub_max_le_max _ _ _ _).trans_lt (max_lt h₁ hβ‚‚) -- so named to match `rat_add_continuous_lemma` theorem _root_.rat_inf_continuous_lemma {Ξ΅ : Ξ±} {a₁ aβ‚‚ b₁ bβ‚‚ : Ξ±} : abs (a₁ - b₁) < Ξ΅ β†’ abs (aβ‚‚ - bβ‚‚) < Ξ΅ β†’ abs (a₁ βŠ“ aβ‚‚ - (b₁ βŠ“ bβ‚‚)) < Ξ΅ := Ξ» h₁ hβ‚‚, (abs_min_sub_min_le_max _ _ _ _).trans_lt (max_lt h₁ hβ‚‚) instance : has_sup (cau_seq Ξ± abs) := ⟨λ f g, ⟨f βŠ” g, Ξ» Ξ΅ Ξ΅0, (exists_forall_ge_and (f.cauchy₃ Ξ΅0) (g.cauchy₃ Ξ΅0)).imp $ Ξ» i H j ij, let ⟨H₁, Hβ‚‚βŸ© := H _ le_rfl in rat_sup_continuous_lemma (H₁ _ ij) (Hβ‚‚ _ ij)⟩⟩ instance : has_inf (cau_seq Ξ± abs) := ⟨λ f g, ⟨f βŠ“ g, Ξ» Ξ΅ Ξ΅0, (exists_forall_ge_and (f.cauchy₃ Ξ΅0) (g.cauchy₃ Ξ΅0)).imp $ Ξ» i H j ij, let ⟨H₁, Hβ‚‚βŸ© := H _ le_rfl in rat_inf_continuous_lemma (H₁ _ ij) (Hβ‚‚ _ ij)⟩⟩ @[simp, norm_cast] lemma coe_sup (f g : cau_seq Ξ± abs) : ⇑(f βŠ” g) = f βŠ” g := rfl @[simp, norm_cast] lemma coe_inf (f g : cau_seq Ξ± abs) : ⇑(f βŠ“ g) = f βŠ“ g := rfl theorem sup_lim_zero {f g : cau_seq Ξ± abs} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f βŠ” g) | Ξ΅ Ξ΅0 := (exists_forall_ge_and (hf _ Ξ΅0) (hg _ Ξ΅0)).imp $ Ξ» i H j ij, let ⟨H₁, Hβ‚‚βŸ© := H _ ij in begin rw abs_lt at H₁ Hβ‚‚ ⊒, exact ⟨lt_sup_iff.mpr (or.inl H₁.1), sup_lt_iff.mpr ⟨H₁.2, Hβ‚‚.2⟩⟩ end theorem inf_lim_zero {f g : cau_seq Ξ± abs} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f βŠ“ g) | Ξ΅ Ξ΅0 := (exists_forall_ge_and (hf _ Ξ΅0) (hg _ Ξ΅0)).imp $ Ξ» i H j ij, let ⟨H₁, Hβ‚‚βŸ© := H _ ij in begin rw abs_lt at H₁ Hβ‚‚ ⊒, exact ⟨lt_inf_iff.mpr ⟨H₁.1, Hβ‚‚.1⟩, inf_lt_iff.mpr (or.inl H₁.2), ⟩ end lemma sup_equiv_sup {a₁ b₁ aβ‚‚ bβ‚‚ : cau_seq Ξ± abs} (ha : a₁ β‰ˆ aβ‚‚) (hb : b₁ β‰ˆ bβ‚‚) : a₁ βŠ” b₁ β‰ˆ aβ‚‚ βŠ” bβ‚‚ := begin intros Ξ΅ Ξ΅0, obtain ⟨ai, hai⟩ := ha Ξ΅ Ξ΅0, obtain ⟨bi, hbi⟩ := hb Ξ΅ Ξ΅0, exact ⟨ai βŠ” bi, Ξ» i hi, (abs_max_sub_max_le_max (a₁ i) (b₁ i) (aβ‚‚ i) (bβ‚‚ i)).trans_lt (max_lt (hai i (sup_le_iff.mp hi).1) (hbi i (sup_le_iff.mp hi).2))⟩, end lemma inf_equiv_inf {a₁ b₁ aβ‚‚ bβ‚‚ : cau_seq Ξ± abs} (ha : a₁ β‰ˆ aβ‚‚) (hb : b₁ β‰ˆ bβ‚‚) : a₁ βŠ“ b₁ β‰ˆ aβ‚‚ βŠ“ bβ‚‚ := begin intros Ξ΅ Ξ΅0, obtain ⟨ai, hai⟩ := ha Ξ΅ Ξ΅0, obtain ⟨bi, hbi⟩ := hb Ξ΅ Ξ΅0, exact ⟨ai βŠ” bi, Ξ» i hi, (abs_min_sub_min_le_max (a₁ i) (b₁ i) (aβ‚‚ i) (bβ‚‚ i)).trans_lt (max_lt (hai i (sup_le_iff.mp hi).1) (hbi i (sup_le_iff.mp hi).2))⟩, end protected lemma sup_lt {a b c : cau_seq Ξ± abs} (ha : a < c) (hb : b < c) : a βŠ” b < c := begin obtain ⟨⟨Ρa, Ξ΅a0, ia, ha⟩, ⟨Ρb, Ξ΅b0, ib, hb⟩⟩ := ⟨ha, hb⟩, refine ⟨Ρa βŠ“ Ξ΅b, lt_inf_iff.mpr ⟨Ρa0, Ξ΅b0⟩, ia βŠ” ib, Ξ» i hi, _⟩, have := min_le_min (ha _ (sup_le_iff.mp hi).1) (hb _ (sup_le_iff.mp hi).2), exact this.trans_eq (min_sub_sub_left _ _ _) end protected lemma lt_inf {a b c : cau_seq Ξ± abs} (hb : a < b) (hc : a < c) : a < b βŠ“ c := begin obtain ⟨⟨Ρb, Ξ΅b0, ib, hb⟩, ⟨Ρc, Ξ΅c0, ic, hc⟩⟩ := ⟨hb, hc⟩, refine ⟨Ρb βŠ“ Ξ΅c, lt_inf_iff.mpr ⟨Ρb0, Ξ΅c0⟩, ib βŠ” ic, Ξ» i hi, _⟩, have := min_le_min (hb _ (sup_le_iff.mp hi).1) (hc _ (sup_le_iff.mp hi).2), exact this.trans_eq (min_sub_sub_right _ _ _), end @[simp] protected lemma sup_idem (a : cau_seq Ξ± abs) : a βŠ” a = a := subtype.ext sup_idem @[simp] protected lemma inf_idem (a : cau_seq Ξ± abs) : a βŠ“ a = a := subtype.ext inf_idem protected lemma sup_comm (a b : cau_seq Ξ± abs) : a βŠ” b = b βŠ” a := subtype.ext sup_comm protected lemma inf_comm (a b : cau_seq Ξ± abs) : a βŠ“ b = b βŠ“ a := subtype.ext inf_comm protected lemma sup_eq_right {a b : cau_seq Ξ± abs} (h : a ≀ b) : a βŠ” b β‰ˆ b := begin obtain ⟨Ρ, Ξ΅0 : _ < _, i, h⟩ | h := h, { intros _ _, refine ⟨i, Ξ» j hj, _⟩, dsimp, erw ←max_sub_sub_right, rwa [sub_self, max_eq_right, abs_zero], rw [sub_nonpos, ←sub_nonneg], exact Ξ΅0.le.trans (h _ hj) }, { refine setoid.trans (sup_equiv_sup h (setoid.refl _)) _, rw cau_seq.sup_idem, exact setoid.refl _ }, end protected lemma inf_eq_right {a b : cau_seq Ξ± abs} (h : b ≀ a) : a βŠ“ b β‰ˆ b := begin obtain ⟨Ρ, Ξ΅0 : _ < _, i, h⟩ | h := h, { intros _ _, refine ⟨i, Ξ» j hj, _⟩, dsimp, erw ←min_sub_sub_right, rwa [sub_self, min_eq_right, abs_zero], exact Ξ΅0.le.trans (h _ hj) }, { refine setoid.trans (inf_equiv_inf (setoid.symm h) (setoid.refl _)) _, rw cau_seq.inf_idem, exact setoid.refl _ }, end protected lemma sup_eq_left {a b : cau_seq Ξ± abs} (h : b ≀ a) : a βŠ” b β‰ˆ a := by simpa only [cau_seq.sup_comm] using cau_seq.sup_eq_right h protected lemma inf_eq_left {a b : cau_seq Ξ± abs} (h : a ≀ b) : a βŠ“ b β‰ˆ a := by simpa only [cau_seq.inf_comm] using cau_seq.inf_eq_right h protected lemma sup_le {a b c : cau_seq Ξ± abs} (ha : a ≀ c) (hb : b ≀ c) : a βŠ” b ≀ c := begin cases ha with ha ha, { cases hb with hb hb, { exact or.inl (cau_seq.sup_lt ha hb) }, { replace ha := le_of_le_of_eq ha.le (setoid.symm hb), refine le_of_le_of_eq (or.inr _) hb, exact cau_seq.sup_eq_right ha }, }, { replace hb := le_of_le_of_eq hb (setoid.symm ha), refine le_of_le_of_eq (or.inr _) ha, exact cau_seq.sup_eq_left hb } end protected lemma le_inf {a b c : cau_seq Ξ± abs} (hb : a ≀ b) (hc : a ≀ c) : a ≀ b βŠ“ c := begin cases hb with hb hb, { cases hc with hc hc, { exact or.inl (cau_seq.lt_inf hb hc) }, { replace hb := le_of_eq_of_le (setoid.symm hc) hb.le, refine le_of_eq_of_le hc (or.inr _), exact setoid.symm (cau_seq.inf_eq_right hb) }, }, { replace hc := le_of_eq_of_le (setoid.symm hb) hc, refine le_of_eq_of_le hb (or.inr _), exact setoid.symm (cau_seq.inf_eq_left hc) } end /-! Note that `distrib_lattice (cau_seq Ξ± abs)` is not true because there is no `partial_order`. -/ end abs end cau_seq
c53845c03fb876973470d58a58994025e84f8778
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/normed/group/quotient.lean
856999c847c2c52507c0cce970becc70a252593b
[ "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
21,869
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Riccardo Brasca -/ import analysis.normed.group.hom /-! # Quotients of seminormed groups For any `semi_normed_group M` and any `S : add_subgroup M`, we provide a `semi_normed_group` the group quotient `M β§Έ S`. If `S` is closed, we provide `normed_group (M β§Έ S)` (regardless of whether `M` itself is separated). The two main properties of these structures are the underlying topology is the quotient topology and the projection is a normed group homomorphism which is norm non-increasing (better, it has operator norm exactly one unless `S` is dense in `M`). The corresponding universal property is that every normed group hom defined on `M` which vanishes on `S` descends to a normed group hom defined on `M β§Έ S`. This file also introduces a predicate `is_quotient` characterizing normed group homs that are isomorphic to the canonical projection onto a normed group quotient. ## Main definitions We use `M` and `N` to denote seminormed groups and `S : add_subgroup M`. All the following definitions are in the `add_subgroup` namespace. Hence we can access `add_subgroup.normed_mk S` as `S.normed_mk`. * `semi_normed_group_quotient` : The seminormed group structure on the quotient by an additive subgroup. This is an instance so there is no need to explictly use it. * `normed_group_quotient` : The normed group structure on the quotient by a closed additive subgroup. This is an instance so there is no need to explictly use it. * `normed_mk S` : the normed group hom from `M` to `M β§Έ S`. * `lift S f hf`: implements the universal property of `M β§Έ S`. Here `(f : normed_group_hom M N)`, `(hf : βˆ€ s ∈ S, f s = 0)` and `lift S f hf : normed_group_hom (M β§Έ S) N`. * `is_quotient`: given `f : normed_group_hom M N`, `is_quotient f` means `N` is isomorphic to a quotient of `M` by a subgroup, with projection `f`. Technically it asserts `f` is surjective and the norm of `f x` is the infimum of the norms of `x + m` for `m` in `f.ker`. ## Main results * `norm_normed_mk` : the operator norm of the projection is `1` if the subspace is not dense. * `is_quotient.norm_lift`: Provided `f : normed_hom M N` satisfies `is_quotient f`, for every `n : N` and positive `Ξ΅`, there exists `m` such that `f m = n ∧ βˆ₯mβˆ₯ < βˆ₯nβˆ₯ + Ξ΅`. ## Implementation details For any `semi_normed_group M` and any `S : add_subgroup M` we define a norm on `M β§Έ S` by `βˆ₯xβˆ₯ = Inf (norm '' {m | mk' S m = x})`. This formula is really an implementation detail, it shouldn't be needed outside of this file setting up the theory. Since `M β§Έ S` is automatically a topological space (as any quotient of a topological space), one needs to be careful while defining the `semi_normed_group` instance to avoid having two different topologies on this quotient. This is not purely a technological issue. Mathematically there is something to prove. The main point is proved in the auxiliary lemma `quotient_nhd_basis` that has no use beyond this verification and states that zero in the quotient admits as basis of neighborhoods in the quotient topology the sets `{x | βˆ₯xβˆ₯ < Ξ΅}` for positive `Ξ΅`. Once this mathematical point it settled, we have two topologies that are propositionaly equal. This is not good enough for the type class system. As usual we ensure *definitional* equality using forgetful inheritance, see Note [forgetful inheritance]. A (semi)-normed group structure includes a uniform space structure which includes a topological space structure, together with propositional fields asserting compatibility conditions. The usual way to define a `semi_normed_group` is to let Lean build a uniform space structure using the provided norm, and then trivially build a proof that the norm and uniform structure are compatible. Here the uniform structure is provided using `topological_add_group.to_uniform_space` which uses the topological structure and the group structure to build the uniform structure. This uniform structure induces the correct topological structure by construction, but the fact that it is compatible with the norm is not obvious; this is where the mathematical content explained in the previous paragraph kicks in. -/ noncomputable theory open quotient_add_group metric set open_locale topological_space nnreal variables {M N : Type*} [semi_normed_group M] [semi_normed_group N] /-- The definition of the norm on the quotient by an additive subgroup. -/ noncomputable instance norm_on_quotient (S : add_subgroup M) : has_norm (M β§Έ S) := { norm := Ξ» x, Inf (norm '' {m | mk' S m = x}) } lemma image_norm_nonempty {S : add_subgroup M} : βˆ€ x : M β§Έ S, (norm '' {m | mk' S m = x}).nonempty := begin rintro ⟨m⟩, rw set.nonempty_image_iff, use m, change mk' S m = _, refl end lemma bdd_below_image_norm (s : set M) : bdd_below (norm '' s) := begin use 0, rintro _ ⟨x, hx, rfl⟩, apply norm_nonneg end /-- The norm on the quotient satisfies `βˆ₯-xβˆ₯ = βˆ₯xβˆ₯`. -/ lemma quotient_norm_neg {S : add_subgroup M} (x : M β§Έ S) : βˆ₯-xβˆ₯ = βˆ₯xβˆ₯ := begin suffices : norm '' {m | mk' S m = x} = norm '' {m | mk' S m = -x}, by simp only [this, norm], ext r, split, { rintros ⟨m, hm : mk' S m = x, rfl⟩, subst hm, rw ← norm_neg, exact ⟨-m, by simp only [(mk' S).map_neg, set.mem_set_of_eq], rfl⟩ }, { rintros ⟨m, hm : mk' S m = -x, rfl⟩, use -m, simp at hm, simp [hm], } end lemma quotient_norm_sub_rev {S : add_subgroup M} (x y : M β§Έ S) : βˆ₯x - yβˆ₯ = βˆ₯y - xβˆ₯ := by rw [show x - y = -(y - x), by abel, quotient_norm_neg] /-- The norm of the projection is smaller or equal to the norm of the original element. -/ lemma quotient_norm_mk_le (S : add_subgroup M) (m : M) : βˆ₯mk' S mβˆ₯ ≀ βˆ₯mβˆ₯ := begin apply cInf_le, use 0, { rintros _ ⟨n, h, rfl⟩, apply norm_nonneg }, { apply set.mem_image_of_mem, rw set.mem_set_of_eq } end /-- The norm of the projection is smaller or equal to the norm of the original element. -/ lemma quotient_norm_mk_le' (S : add_subgroup M) (m : M) : βˆ₯(m : M β§Έ S)βˆ₯ ≀ βˆ₯mβˆ₯ := quotient_norm_mk_le S m /-- The norm of the image under the natural morphism to the quotient. -/ lemma quotient_norm_mk_eq (S : add_subgroup M) (m : M) : βˆ₯mk' S mβˆ₯ = Inf ((Ξ» x, βˆ₯m + xβˆ₯) '' S) := begin change Inf _ = _, congr' 1, ext r, simp_rw [coe_mk', eq_iff_sub_mem], split, { rintros ⟨y, h, rfl⟩, use [y - m, h], simp }, { rintros ⟨y, h, rfl⟩, use m + y, simpa using h }, end /-- The quotient norm is nonnegative. -/ lemma quotient_norm_nonneg (S : add_subgroup M) : βˆ€ x : M β§Έ S, 0 ≀ βˆ₯xβˆ₯ := begin rintros ⟨m⟩, change 0 ≀ βˆ₯mk' S mβˆ₯, apply le_cInf (image_norm_nonempty _), rintros _ ⟨n, h, rfl⟩, apply norm_nonneg end /-- The quotient norm is nonnegative. -/ lemma norm_mk_nonneg (S : add_subgroup M) (m : M) : 0 ≀ βˆ₯mk' S mβˆ₯ := quotient_norm_nonneg S _ /-- The norm of the image of `m : M` in the quotient by `S` is zero if and only if `m` belongs to the closure of `S`. -/ lemma quotient_norm_eq_zero_iff (S : add_subgroup M) (m : M) : βˆ₯mk' S mβˆ₯ = 0 ↔ m ∈ closure (S : set M) := begin have : 0 ≀ βˆ₯mk' S mβˆ₯ := norm_mk_nonneg S m, rw [← this.le_iff_eq, quotient_norm_mk_eq, real.Inf_le_iff], simp_rw [zero_add], { calc (βˆ€ Ξ΅ > (0 : ℝ), βˆƒ r ∈ (Ξ» x, βˆ₯m + xβˆ₯) '' (S : set M), r < Ξ΅) ↔ (βˆ€ Ξ΅ > 0, (βˆƒ x ∈ S, βˆ₯m + xβˆ₯ < Ξ΅)) : by simp [set.bex_image_iff] ... ↔ βˆ€ Ξ΅ > 0, (βˆƒ x ∈ S, βˆ₯m + -xβˆ₯ < Ξ΅) : _ ... ↔ βˆ€ Ξ΅ > 0, (βˆƒ x ∈ S, x ∈ metric.ball m Ξ΅) : by simp [dist_eq_norm, ← sub_eq_add_neg, norm_sub_rev] ... ↔ m ∈ closure ↑S : by simp [metric.mem_closure_iff, dist_comm], refine forallβ‚‚_congr (Ξ» Ξ΅ Ξ΅_pos, _), rw [← S.exists_neg_mem_iff_exists_mem], simp }, { use 0, rintro _ ⟨x, x_in, rfl⟩, apply norm_nonneg }, rw set.nonempty_image_iff, use [0, S.zero_mem] end /-- For any `x : M β§Έ S` and any `0 < Ξ΅`, there is `m : M` such that `mk' S m = x` and `βˆ₯mβˆ₯ < βˆ₯xβˆ₯ + Ξ΅`. -/ lemma norm_mk_lt {S : add_subgroup M} (x : M β§Έ S) {Ξ΅ : ℝ} (hΞ΅ : 0 < Ξ΅) : βˆƒ (m : M), mk' S m = x ∧ βˆ₯mβˆ₯ < βˆ₯xβˆ₯ + Ξ΅ := begin obtain ⟨_, ⟨m : M, H : mk' S m = x, rfl⟩, hnorm : βˆ₯mβˆ₯ < βˆ₯xβˆ₯ + Ρ⟩ := real.lt_Inf_add_pos (image_norm_nonempty x) hΞ΅, subst H, exact ⟨m, rfl, hnorm⟩, end /-- For any `m : M` and any `0 < Ξ΅`, there is `s ∈ S` such that `βˆ₯m + sβˆ₯ < βˆ₯mk' S mβˆ₯ + Ξ΅`. -/ lemma norm_mk_lt' (S : add_subgroup M) (m : M) {Ξ΅ : ℝ} (hΞ΅ : 0 < Ξ΅) : βˆƒ s ∈ S, βˆ₯m + sβˆ₯ < βˆ₯mk' S mβˆ₯ + Ξ΅ := begin obtain ⟨n : M, hn : mk' S n = mk' S m, hn' : βˆ₯nβˆ₯ < βˆ₯mk' S mβˆ₯ + Ρ⟩ := norm_mk_lt (quotient_add_group.mk' S m) hΞ΅, erw [eq_comm, quotient_add_group.eq] at hn, use [- m + n, hn], rwa [add_neg_cancel_left] end /-- The quotient norm satisfies the triangle inequality. -/ lemma quotient_norm_add_le (S : add_subgroup M) (x y : M β§Έ S) : βˆ₯x + yβˆ₯ ≀ βˆ₯xβˆ₯ + βˆ₯yβˆ₯ := begin refine le_of_forall_pos_le_add (Ξ» Ξ΅ hΞ΅, _), replace hΞ΅ := half_pos hΞ΅, obtain ⟨m, rfl, hm : βˆ₯mβˆ₯ < βˆ₯mk' S mβˆ₯ + Ξ΅ / 2⟩ := norm_mk_lt x hΞ΅, obtain ⟨n, rfl, hn : βˆ₯nβˆ₯ < βˆ₯mk' S nβˆ₯ + Ξ΅ / 2⟩ := norm_mk_lt y hΞ΅, calc βˆ₯mk' S m + mk' S nβˆ₯ = βˆ₯mk' S (m + n)βˆ₯ : by rw (mk' S).map_add ... ≀ βˆ₯m + nβˆ₯ : quotient_norm_mk_le S (m + n) ... ≀ βˆ₯mβˆ₯ + βˆ₯nβˆ₯ : norm_add_le _ _ ... ≀ βˆ₯mk' S mβˆ₯ + βˆ₯mk' S nβˆ₯ + Ξ΅ : by linarith end /-- The quotient norm of `0` is `0`. -/ lemma norm_mk_zero (S : add_subgroup M) : βˆ₯(0 : M β§Έ S)βˆ₯ = 0 := begin erw quotient_norm_eq_zero_iff, exact subset_closure S.zero_mem end /-- If `(m : M)` has norm equal to `0` in `M β§Έ S` for a closed subgroup `S` of `M`, then `m ∈ S`. -/ lemma norm_zero_eq_zero (S : add_subgroup M) (hS : is_closed (S : set M)) (m : M) (h : βˆ₯mk' S mβˆ₯ = 0) : m ∈ S := by rwa [quotient_norm_eq_zero_iff, hS.closure_eq] at h lemma quotient_nhd_basis (S : add_subgroup M) : (𝓝 (0 : M β§Έ S)).has_basis (Ξ» Ξ΅ : ℝ, 0 < Ξ΅) (Ξ» Ξ΅, {x | βˆ₯xβˆ₯ < Ξ΅}) := ⟨begin intros U, split, { intros U_in, rw ← (mk' S).map_zero at U_in, have := preimage_nhds_coinduced U_in, rcases metric.mem_nhds_iff.mp this with ⟨Ρ, Ξ΅_pos, H⟩, use [Ξ΅/2, half_pos Ξ΅_pos], intros x x_in, dsimp at x_in, rcases norm_mk_lt x (half_pos Ξ΅_pos) with ⟨y, rfl, ry⟩, apply H, rw ball_zero_eq, dsimp, linarith }, { rintros ⟨Ρ, Ξ΅_pos, h⟩, have : (mk' S) '' (ball (0 : M) Ξ΅) βŠ† {x | βˆ₯xβˆ₯ < Ξ΅}, { rintros - ⟨x, x_in, rfl⟩, rw mem_ball_zero_iff at x_in, exact lt_of_le_of_lt (quotient_norm_mk_le S x) x_in }, apply filter.mem_of_superset _ (set.subset.trans this h), clear h U this, apply is_open.mem_nhds, { change is_open ((mk' S) ⁻¹' _), erw quotient_add_group.preimage_image_coe, apply is_open_Union, rintros ⟨s, s_in⟩, exact (continuous_add_right s).is_open_preimage _ is_open_ball }, { exact ⟨(0 : M), mem_ball_self Ξ΅_pos, (mk' S).map_zero⟩ } }, end⟩ /-- The seminormed group structure on the quotient by an additive subgroup. -/ noncomputable instance add_subgroup.semi_normed_group_quotient (S : add_subgroup M) : semi_normed_group (M β§Έ S) := { dist := Ξ» x y, βˆ₯x - yβˆ₯, dist_self := Ξ» x, by simp only [norm_mk_zero, sub_self], dist_comm := quotient_norm_sub_rev, dist_triangle := Ξ» x y z, begin unfold dist, have : x - z = (x - y) + (y - z) := by abel, rw this, exact quotient_norm_add_le S (x - y) (y - z) end, dist_eq := Ξ» x y, rfl, to_uniform_space := topological_add_group.to_uniform_space (M β§Έ S), uniformity_dist := begin rw uniformity_eq_comap_nhds_zero', have := (quotient_nhd_basis S).comap (Ξ» (p : (M β§Έ S) Γ— M β§Έ S), p.2 - p.1), apply this.eq_of_same_basis, have : βˆ€ Ξ΅ : ℝ, (Ξ» (p : (M β§Έ S) Γ— M β§Έ S), p.snd - p.fst) ⁻¹' {x | βˆ₯xβˆ₯ < Ξ΅} = {p : (M β§Έ S) Γ— M β§Έ S | βˆ₯p.fst - p.sndβˆ₯ < Ξ΅}, { intro Ξ΅, ext x, dsimp, rw quotient_norm_sub_rev }, rw funext this, refine filter.has_basis_binfi_principal _ set.nonempty_Ioi, rintros Ξ΅ (Ξ΅_pos : 0 < Ξ΅) Ξ· (Ξ·_pos : 0 < Ξ·), refine ⟨min Ξ΅ Ξ·, lt_min Ξ΅_pos Ξ·_pos, _, _⟩, { suffices : βˆ€ (a b : M β§Έ S), βˆ₯a - bβˆ₯ < Ξ΅ β†’ βˆ₯a - bβˆ₯ < Ξ· β†’ βˆ₯a - bβˆ₯ < Ξ΅, by simpa, exact Ξ» a b h h', h }, { simp } end } -- This is a sanity check left here on purpose to ensure that potential refactors won't destroy -- this important property. example (S : add_subgroup M) : (quotient.topological_space : topological_space $ M β§Έ S) = S.semi_normed_group_quotient.to_uniform_space.to_topological_space := rfl /-- The quotient in the category of normed groups. -/ noncomputable instance add_subgroup.normed_group_quotient (S : add_subgroup M) [hS : is_closed (S : set M)] : normed_group (M β§Έ S) := { eq_of_dist_eq_zero := begin rintros ⟨m⟩ ⟨m'⟩ (h : βˆ₯mk' S m - mk' S m'βˆ₯ = 0), erw [← (mk' S).map_sub, quotient_norm_eq_zero_iff, hS.closure_eq, ← quotient_add_group.eq_iff_sub_mem] at h, exact h end, .. add_subgroup.semi_normed_group_quotient S } -- This is a sanity check left here on purpose to ensure that potential refactors won't destroy -- this important property. example (S : add_subgroup M) [is_closed (S : set M)] : S.semi_normed_group_quotient = normed_group.to_semi_normed_group := rfl namespace add_subgroup open normed_group_hom /-- The morphism from a seminormed group to the quotient by a subgroup. -/ noncomputable def normed_mk (S : add_subgroup M) : normed_group_hom M (M β§Έ S) := { bound' := ⟨1, Ξ» m, by simpa [one_mul] using quotient_norm_mk_le _ m⟩, .. quotient_add_group.mk' S } /-- `S.normed_mk` agrees with `quotient_add_group.mk' S`. -/ @[simp] lemma normed_mk.apply (S : add_subgroup M) (m : M) : normed_mk S m = quotient_add_group.mk' S m := rfl /-- `S.normed_mk` is surjective. -/ lemma surjective_normed_mk (S : add_subgroup M) : function.surjective (normed_mk S) := surjective_quot_mk _ /-- The kernel of `S.normed_mk` is `S`. -/ lemma ker_normed_mk (S : add_subgroup M) : S.normed_mk.ker = S := quotient_add_group.ker_mk _ /-- The operator norm of the projection is at most `1`. -/ lemma norm_normed_mk_le (S : add_subgroup M) : βˆ₯S.normed_mkβˆ₯ ≀ 1 := normed_group_hom.op_norm_le_bound _ zero_le_one (Ξ» m, by simp [quotient_norm_mk_le']) /-- The operator norm of the projection is `1` if the subspace is not dense. -/ lemma norm_normed_mk (S : add_subgroup M) (h : (S.topological_closure : set M) β‰  univ) : βˆ₯S.normed_mkβˆ₯ = 1 := begin obtain ⟨x, hx⟩ := set.nonempty_compl.2 h, let y := S.normed_mk x, have hy : βˆ₯yβˆ₯ β‰  0, { intro h0, exact set.not_mem_of_mem_compl hx ((quotient_norm_eq_zero_iff S x).1 h0) }, refine le_antisymm (norm_normed_mk_le S) (le_of_forall_pos_le_add (Ξ» Ξ΅ hΞ΅, _)), suffices : 1 ≀ βˆ₯S.normed_mkβˆ₯ + min Ξ΅ ((1 : ℝ)/2), { exact le_add_of_le_add_left this (min_le_left Ξ΅ ((1 : ℝ)/2)) }, have hΞ΄ := sub_pos.mpr (lt_of_le_of_lt (min_le_right Ξ΅ ((1 : ℝ)/2)) one_half_lt_one), have hΞ΄pos : 0 < min Ξ΅ ((1 : ℝ)/2) := lt_min hΞ΅ one_half_pos, have hΞ΄norm := mul_pos (div_pos hΞ΄pos hΞ΄) (lt_of_le_of_ne (norm_nonneg y) hy.symm), obtain ⟨m, hm, hlt⟩ := norm_mk_lt y hΞ΄norm, have hrw : βˆ₯yβˆ₯ + min Ξ΅ (1 / 2) / (1 - min Ξ΅ (1 / 2)) * βˆ₯yβˆ₯ = βˆ₯yβˆ₯ * (1 + min Ξ΅ (1 / 2) / (1 - min Ξ΅ (1 / 2))) := by ring, rw [hrw] at hlt, have hm0 : βˆ₯mβˆ₯ β‰  0, { intro h0, have hnorm := quotient_norm_mk_le S m, rw [h0, hm] at hnorm, replace hnorm := le_antisymm hnorm (norm_nonneg _), simpa [hnorm] using hy }, replace hlt := (div_lt_div_right (lt_of_le_of_ne (norm_nonneg m) hm0.symm)).2 hlt, simp only [hm0, div_self, ne.def, not_false_iff] at hlt, have hrw₁ : βˆ₯yβˆ₯ * (1 + min Ξ΅ (1 / 2) / (1 - min Ξ΅ (1 / 2))) / βˆ₯mβˆ₯ = (βˆ₯yβˆ₯ / βˆ₯mβˆ₯) * (1 + min Ξ΅ (1 / 2) / (1 - min Ξ΅ (1 / 2))) := by ring, rw [hrw₁] at hlt, replace hlt := (inv_pos_lt_iff_one_lt_mul (lt_trans (div_pos hΞ΄pos hΞ΄) (lt_one_add _))).2 hlt, suffices : βˆ₯S.normed_mkβˆ₯ β‰₯ 1 - min Ξ΅ (1 / 2), { exact sub_le_iff_le_add.mp this }, calc βˆ₯S.normed_mkβˆ₯ β‰₯ βˆ₯(S.normed_mk) mβˆ₯ / βˆ₯mβˆ₯ : ratio_le_op_norm S.normed_mk m ... = βˆ₯yβˆ₯ / βˆ₯mβˆ₯ : by rw [normed_mk.apply, hm] ... β‰₯ (1 + min Ξ΅ (1 / 2) / (1 - min Ξ΅ (1 / 2)))⁻¹ : le_of_lt hlt ... = 1 - min Ξ΅ (1 / 2) : by field_simp [(ne_of_lt hΞ΄).symm] end /-- The operator norm of the projection is `0` if the subspace is dense. -/ lemma norm_trivial_quotient_mk (S : add_subgroup M) (h : (S.topological_closure : set M) = set.univ) : βˆ₯S.normed_mkβˆ₯ = 0 := begin refine le_antisymm (op_norm_le_bound _ le_rfl (Ξ» x, _)) (norm_nonneg _), have hker : x ∈ (S.normed_mk).ker.topological_closure, { rw [S.ker_normed_mk], exact set.mem_of_eq_of_mem h trivial }, rw [ker_normed_mk] at hker, simp only [(quotient_norm_eq_zero_iff S x).mpr hker, normed_mk.apply, zero_mul], end end add_subgroup namespace normed_group_hom /-- `is_quotient f`, for `f : M ⟢ N` means that `N` is isomorphic to the quotient of `M` by the kernel of `f`. -/ structure is_quotient (f : normed_group_hom M N) : Prop := (surjective : function.surjective f) (norm : βˆ€ x, βˆ₯f xβˆ₯ = Inf ((Ξ» m, βˆ₯x + mβˆ₯) '' f.ker)) /-- Given `f : normed_group_hom M N` such that `f s = 0` for all `s ∈ S`, where, `S : add_subgroup M` is closed, the induced morphism `normed_group_hom (M β§Έ S) N`. -/ noncomputable def lift {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : βˆ€ s ∈ S, f s = 0) : normed_group_hom (M β§Έ S) N := { bound' := begin obtain ⟨c : ℝ, hcpos : (0 : ℝ) < c, hc : βˆ€ x, βˆ₯f xβˆ₯ ≀ c * βˆ₯xβˆ₯⟩ := f.bound, refine ⟨c, Ξ» mbar, le_of_forall_pos_le_add (Ξ» Ξ΅ hΞ΅, _)⟩, obtain ⟨m : M, rfl : mk' S m = mbar, hmnorm : βˆ₯mβˆ₯ < βˆ₯mk' S mβˆ₯ + Ξ΅/c⟩ := norm_mk_lt mbar (div_pos hΞ΅ hcpos), calc βˆ₯f mβˆ₯ ≀ c * βˆ₯mβˆ₯ : hc m ... ≀ c*(βˆ₯mk' S mβˆ₯ + Ξ΅/c) : ((mul_lt_mul_left hcpos).mpr hmnorm).le ... = c * βˆ₯mk' S mβˆ₯ + Ξ΅ : by rw [mul_add, mul_div_cancel' _ hcpos.ne.symm] end, .. quotient_add_group.lift S f.to_add_monoid_hom hf } lemma lift_mk {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : βˆ€ s ∈ S, f s = 0) (m : M) : lift S f hf (S.normed_mk m) = f m := rfl lemma lift_unique {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : βˆ€ s ∈ S, f s = 0) (g : normed_group_hom (M β§Έ S) N) : g.comp (S.normed_mk) = f β†’ g = lift S f hf := begin intro h, ext, rcases add_subgroup.surjective_normed_mk _ x with ⟨x,rfl⟩, change (g.comp (S.normed_mk) x) = _, simpa only [h] end /-- `S.normed_mk` satisfies `is_quotient`. -/ lemma is_quotient_quotient (S : add_subgroup M) : is_quotient (S.normed_mk) := ⟨S.surjective_normed_mk, Ξ» m, by simpa [S.ker_normed_mk] using quotient_norm_mk_eq _ m⟩ lemma is_quotient.norm_lift {f : normed_group_hom M N} (hquot : is_quotient f) {Ξ΅ : ℝ} (hΞ΅ : 0 < Ξ΅) (n : N) : βˆƒ (m : M), f m = n ∧ βˆ₯mβˆ₯ < βˆ₯nβˆ₯ + Ξ΅ := begin obtain ⟨m, rfl⟩ := hquot.surjective n, have nonemp : ((Ξ» m', βˆ₯m + m'βˆ₯) '' f.ker).nonempty, { rw set.nonempty_image_iff, exact ⟨0, f.ker.zero_mem⟩ }, rcases real.lt_Inf_add_pos nonemp hΞ΅ with ⟨_, ⟨⟨x, hx, rfl⟩, H : βˆ₯m + xβˆ₯ < Inf ((Ξ» (m' : M), βˆ₯m + m'βˆ₯) '' f.ker) + Ρ⟩⟩, exact ⟨m+x, by rw [f.map_add,(normed_group_hom.mem_ker f x).mp hx, add_zero], by rwa hquot.norm⟩, end lemma is_quotient.norm_le {f : normed_group_hom M N} (hquot : is_quotient f) (m : M) : βˆ₯f mβˆ₯ ≀ βˆ₯mβˆ₯ := begin rw hquot.norm, apply cInf_le, { use 0, rintros _ ⟨m', hm', rfl⟩, apply norm_nonneg }, { exact ⟨0, f.ker.zero_mem, by simp⟩ } end lemma lift_norm_le {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : βˆ€ s ∈ S, f s = 0) {c : ℝβ‰₯0} (fb : βˆ₯fβˆ₯ ≀ c) : βˆ₯lift S f hfβˆ₯ ≀ c := begin apply op_norm_le_bound _ c.coe_nonneg, intros x, by_cases hc : c = 0, { simp only [hc, nnreal.coe_zero, zero_mul] at fb ⊒, obtain ⟨x, rfl⟩ := surjective_quot_mk _ x, show βˆ₯f xβˆ₯ ≀ 0, calc βˆ₯f xβˆ₯ ≀ 0 * βˆ₯xβˆ₯ : f.le_of_op_norm_le fb x ... = 0 : zero_mul _ }, { replace hc : 0 < c := pos_iff_ne_zero.mpr hc, apply le_of_forall_pos_le_add, intros Ξ΅ hΞ΅, have aux : 0 < (Ξ΅ / c) := div_pos hΞ΅ hc, obtain ⟨x, rfl, Hx⟩ : βˆƒ x', S.normed_mk x' = x ∧ βˆ₯x'βˆ₯ < βˆ₯xβˆ₯ + (Ξ΅ / c) := (is_quotient_quotient _).norm_lift aux _, rw lift_mk, calc βˆ₯f xβˆ₯ ≀ c * βˆ₯xβˆ₯ : f.le_of_op_norm_le fb x ... ≀ c * (βˆ₯S.normed_mk xβˆ₯ + Ξ΅ / c) : (mul_le_mul_left _).mpr Hx.le ... = c * _ + Ξ΅ : _, { exact_mod_cast hc }, { rw [mul_add, mul_div_cancel'], exact_mod_cast hc.ne' } }, end lemma lift_norm_noninc {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : βˆ€ s ∈ S, f s = 0) (fb : f.norm_noninc) : (lift S f hf).norm_noninc := Ξ» x, begin have fb' : βˆ₯fβˆ₯ ≀ (1 : ℝβ‰₯0) := norm_noninc.norm_noninc_iff_norm_le_one.mp fb, simpa using le_of_op_norm_le _ (f.lift_norm_le _ _ fb') _, end end normed_group_hom
df3c71d6564ab23a3cc3c47a8b63e644a74cbddc
69bc7d0780be17e452d542a93f9599488f1c0c8e
/10-17-2019.lean
fe073c377ee4974f6b5ea826f125cbb72169c06c
[]
no_license
joek13/cs2102-notes
b7352285b1d1184fae25594f89f5926d74e6d7b4
25bb18788641b20af9cf3c429afe1da9b2f5eafb
refs/heads/master
1,673,461,162,867
1,575,561,090,000
1,575,561,090,000
207,573,549
0
0
null
null
null
null
UTF-8
Lean
false
false
1,675
lean
-- Notes 10/17/2019 -- Most of the work for today is in ./prop_logic.lean ./prop_logic_test.lean /- Notes on operator syntax Prefix, infix, and postfix Prefix: (+ 3 5) Infix: 3 + 5 Postfix (3 5 +) Functions are supplied in prefix notation Infix is standard for arithmetic, etc. Postfix -- accessor operator '.' , subscripting/indexing operator '[]' Some terms that are relevant to boolean algebra: - satisfiable -- whether an interpretation exists that makes this true - unsatisfiable -- no interpretation exists that makes this true - valid -- the value is true regardless of interpretation Example: X ∧ Β¬X -- unsatisfiable X ∨ Β¬X -- valid x | y | (x ∧ y) ∨ (Β¬y) ---+-----+--------------- tt | tt | t tt | ff | t ff | tt | f ff | ff | t There is one interpretation that makes the expression true, so it is satisfiable ... but it's not always true (under any interpretation), so it isn't valid Boolean satisfiability problem: given a boolean expression, determine if at least one interpretation exists to make it true ... boolean satisfiability problems have O(2^n) worst-case time complexityβ€”an NP-complete problem Let's describe these terms in predicate logic Unsatisfiable: unsat e ↔ Β¬ βˆƒ (i: var β†’ bool), pEval e i = tt -- "there does not exist an interpretation such that the expression evaluates to true" sat e ↔ Β¬ unsat e ↔ βˆƒ (i: var β†’ bool), pEval e i = tt -- "there exists an interpretation such that the expression evaluates to true" valid e ↔ βˆ€ (i: var β†’ bool), pEval e i = tt -- "for every interpretation, the expression evaluates to true" -/
c0c8d65c69c7d8ee35b93b0322187c249ca40a86
1d02a718c550dba762f0c3d2ad13d16a43649ca1
/src/ast.lean
b7a15ffe7c6799b219141d456cb15e32ec3603c4
[ "Apache-2.0" ]
permissive
mhuisi/rc-correctness
48488dfbbe18e222399b0c5252d2803a9dd1be74
2b7878ac594ba285b0b5cdabe96f41c6e3bbcc87
refs/heads/master
1,590,988,773,033
1,585,334,858,000
1,585,334,858,000
190,653,803
0
1
null
null
null
null
UTF-8
Lean
false
false
4,089
lean
import util namespace rc_correctness -- ast defs def var := β„• def const := β„• def cnstr := β„• inductive expr : Type | const_app_full (c : const) (ys : list var) : expr | const_app_part (c : const) (ys : list var) : expr | var_app (x : var) (y : var) : expr | ctor (i : cnstr) (ys : list var) : expr | proj (i : cnstr) (x : var) : expr inductive fn_body : Type | ret (x : var) : fn_body | Β«letΒ» (x : var) (e : expr) (F : fn_body) : fn_body | case (x : var) (Fs : list fn_body) : fn_body | inc (x : var) (F : fn_body) : fn_body | dec (x : var) (F : fn_body) : fn_body structure fn := (ys : list var) (F : fn_body) def program := const β†’ fn inductive rc : Type | expr (e : expr) : rc | fn_body (F : fn_body) : rc -- notation open rc_correctness.expr open rc_correctness.fn_body -- expr notation c `⟦` ys `…` `⟧` := expr.const_app_full c ys notation c `⟦` ys `…` `, ` `_` `⟧` := expr.const_app_part c ys notation x `⟦` y `⟧` := expr.var_app x y notation `βŸͺ` ys `⟫` i := expr.ctor i ys notation x `[` i `]` := expr.proj i x -- fn_body notation x ` ≔ ` e `; `F := fn_body.let x e F notation `case ` x ` of ` Fs := fn_body.case x Fs notation `inc ` x `; ` F := fn_body.inc x F notation `dec ` x `; ` F := fn_body.dec x F -- rc instance expr_to_rc : has_coe expr rc := ⟨rc.expr⟩ instance fn_body_to_rc : has_coe fn_body rc := ⟨rc.fn_body⟩ -- fn_body recursor, courtesy of Sebastian Ullrich def {l} fn_body.rec_wf (C : fn_body β†’ Sort l) (Β«retΒ» : Ξ  (x : var), C (ret x)) (Β«letΒ» : Ξ  (x : var) (e : expr) (F : fn_body) (F_ih : C F), C (x ≔ e; F)) (Β«caseΒ» : Ξ  (x : var) (Fs : list fn_body) (Fs_ih : βˆ€ F ∈ Fs, C F), C (case x of Fs)) (Β«incΒ» : Ξ  (x : var) (F : fn_body) (F_ih : C F), C (inc x; F)) (Β«decΒ» : Ξ  (x : var) (F : fn_body) (F_ih : C F), C (dec x; F)) : Ξ  (x : fn_body), C x | (fn_body.ret x) := Β«retΒ» x | (x ≔ e; F) := Β«letΒ» x e F (fn_body.rec_wf F) | (case x of Fs) := Β«caseΒ» x Fs (Ξ» F h, have sizeof F < 1 + sizeof Fs, from nat.lt_add_left _ _ _ (list.sizeof_lt_sizeof_of_mem h), fn_body.rec_wf F) | (inc x; F) := Β«incΒ» x F (fn_body.rec_wf F) | (dec x; F) := Β«decΒ» x F (fn_body.rec_wf F) -- free variables def FV_expr : expr β†’ finset var | (c⟦xsβ€¦βŸ§) := xs.to_finset | (c⟦xs…, _⟧) := xs.to_finset | (x⟦y⟧) := {x, y} | (βŸͺxs⟫i) := xs.to_finset | (x[i]) := {x} def FV : fn_body β†’ finset var | (ret x) := {x} | (x ≔ e; F) := FV_expr e βˆͺ ((FV F).erase x) | (case x of Fs) := insert x (finset.join (Fs.map_wf (Ξ» F h, FV F))) | (inc x; F) := insert x (FV F) | (dec x; F) := insert x (FV F) -- var order local attribute [reducible] var abbreviation var_le : var β†’ var β†’ Prop := nat.le instance var_le_is_trans : is_trans var var_le := ⟨@nat.le_trans⟩ instance var_le_is_antisymm : is_antisymm var var_le := ⟨@nat.le_antisymm⟩ instance var_le_is_total : is_total var var_le := ⟨@nat.le_total⟩ local attribute [semireducible] var -- repr -- var local attribute [reducible] var instance var_has_repr : has_repr var := ⟨repr⟩ local attribute [semireducible] var -- const local attribute [reducible] const instance const_has_repr : has_repr const := ⟨repr⟩ local attribute [semireducible] const -- expr def expr_repr : expr β†’ string | (c⟦ysβ€¦βŸ§) := c.repr ++ "⟦" ++ ys.repr ++ "β€¦βŸ§" | (c⟦ys…, _⟧) := c.repr ++ "⟦" ++ ys.repr ++ "…, _⟧" | (x⟦y⟧) := x.repr ++ "⟦" ++ y.repr ++ "⟧" | (βŸͺys⟫i) := "βŸͺ" ++ ys.repr ++ "⟫" ++ i.repr | (x[i]) := x.repr ++ "[" ++ i.repr ++ "]" instance expr_has_repr : has_repr expr := ⟨expr_repr⟩ -- fn_body def fn_body_repr : fn_body β†’ string | (ret x) := "ret " ++ x.repr | (x ≔ e; F) := x.repr ++ " ≔ " ++ repr e ++ "; " ++ fn_body_repr F | (case x of Fs) := "case " ++ x.repr ++ " of " ++ (Fs.map_wf (Ξ» F h, fn_body_repr F)).repr | (inc x; F) := "inc " ++ x.repr ++ "; " ++ fn_body_repr F | (dec x; F) := "dec " ++ x.repr ++ "; " ++ fn_body_repr F instance fn_body_has_repr : has_repr fn_body := ⟨fn_body_repr⟩ end rc_correctness
bd714b5fd0ff5e777051da2b740b599a400e81fb
5883d9218e6f144e20eee6ca1dab8529fa1a97c0
/src/aeq/equiv.lean
c40595670ddfdbe1b4eefaca84327d94f3f0e5a0
[]
no_license
spl/alpha-conversion-is-easy
0d035bc570e52a6345d4890e4d0c9e3f9b8126c1
ed937fe85d8495daffd9412a5524c77b9fcda094
refs/heads/master
1,607,649,280,020
1,517,380,240,000
1,517,380,240,000
52,174,747
4
0
null
1,456,052,226,000
1,456,001,163,000
Lean
UTF-8
Lean
false
false
3,757
lean
/- This file contains equivalence properties of `aeq`. -/ import .map namespace acie ------------------------------------------------------------------ namespace aeq ------------------------------------------------------------------ variables {V : Type} [decidable_eq V] -- Type of variable names variables {vs : Type β†’ Type} [vset vs V] -- Type of variable name sets variables {X Y Z : vs V} -- Variable name sets variables {R : X Γ—Ξ½ Y} {S : Y Γ—Ξ½ Z} -- Variable name set relations variables {eX : exp X} {eY eY₁ eYβ‚‚ : exp Y} {eZ : exp Z} -- Expressions -- Reflexivity -- Paper: Proposition 2.1 @[refl] protected theorem refl (e : exp X) : e β‰‘Ξ±βŸ¨vrel.id X⟩ e := begin induction e with /- var -/ X x /- app -/ X f e rf re /- lam -/ X a e r, begin /- var -/ exact var (vrel.refl x) end, begin /- app -/ exact app rf re end, begin /- lam -/ exact lam (map.simple (Ξ» x y, vrel.update.of_id) r) end end -- Symmetry -- Paper: Proposition 2.2 @[symm] protected theorem symm : eX β‰‘Ξ±βŸ¨R⟩ eY β†’ eY β‰‘Ξ±βŸ¨R°⟩ eX := begin intro H, induction H with /- var -/ X Y R x y x_R_y /- app -/ X Y R fX eX fY eY af ae rf re /- lam -/ X Y R a b eX eY ae r, begin /- var -/ exact var (vrel.symm x_R_y) end, begin /- app -/ exact app rf re end, begin /- lam -/ exact lam (map.simple (Ξ» x y, vrel.update.of_inv) r) end end -- Transitivity implementation private theorem trans.core (P : eY₁ = eYβ‚‚) (aR : eX β‰‘Ξ±βŸ¨R⟩ eY₁) (aS : eYβ‚‚ β‰‘Ξ±βŸ¨S⟩ eZ) : eX β‰‘Ξ±βŸ¨R β¨Ύ S⟩ eZ := begin induction aR with /- var -/ X Y R x y₁ x_R_y₁ /- app -/ X Y R fX eX fY₁ eY₁ afXY aeXY rf re /- lam -/ X Y R x y₁ eX eY₁ aXY r generalizing Z S eYβ‚‚ eZ P aS, begin /- aR: var -/ cases aS with /- var -/ Y Z S yβ‚‚ z yβ‚‚_S_z /- app -/ Y Z S fYβ‚‚ eYβ‚‚ fZ eZ afYZ aeYZ /- lam -/ Y Z S yβ‚‚ z eYβ‚‚ eZ aYZ, begin /- aS: var -/ injection P with y₁_eq_yβ‚‚ _, induction y₁_eq_yβ‚‚, exact var (vrel.trans x_R_y₁ yβ‚‚_S_z) end, begin /- aS: app -/ exact exp.no_confusion P end, begin /- aS: lam -/ exact exp.no_confusion P end end, begin /- aR: app -/ cases aS with /- var -/ Y Z S yβ‚‚ z yβ‚‚_S_z /- app -/ Y Z S fYβ‚‚ eYβ‚‚ fZ eZ afYZ aeYZ /- lam -/ Y Z S yβ‚‚ z eYβ‚‚ eZ aYZ, begin /- aS: var -/ exact exp.no_confusion P end, begin /- aS: app -/ injection P with fY₁_eq_fYβ‚‚ eY₁_eq_eYβ‚‚, exact app (rf fY₁_eq_fYβ‚‚ afYZ) (re eY₁_eq_eYβ‚‚ aeYZ) end, begin /- aS: lam -/ exact exp.no_confusion P end end, begin /- aR: lam -/ cases aS with /- var -/ Y Z S yβ‚‚ z yβ‚‚_S_z /- app -/ Y Z S fYβ‚‚ eYβ‚‚ fZ eZ afYZ aeYZ /- lam -/ Y Z S yβ‚‚ z eYβ‚‚ eZ aYZ, begin /- aS: var -/ exact exp.no_confusion P end, begin /- aS: app -/ exact exp.no_confusion P end, begin /- aS: lam -/ injection P with y₁_eq_yβ‚‚ eY₁_heq_eYβ‚‚, induction y₁_eq_yβ‚‚, exact lam (map.simple (Ξ» x z, vrel.update.of_comp) (r (eq_of_heq eY₁_heq_eYβ‚‚) aYZ)) end end end -- Transitivity -- Paper: Proposition 2.3 @[trans] protected theorem trans : eX β‰‘Ξ±βŸ¨R⟩ eY β†’ eY β‰‘Ξ±βŸ¨S⟩ eZ β†’ eX β‰‘Ξ±βŸ¨R β¨Ύ S⟩ eZ := trans.core (eq.refl eY) end /- namespace -/ aeq -------------------------------------------------------- end /- namespace -/ acie -------------------------------------------------------
3ef6d3daacbd0ced95be1ba7a02611694998e65b
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/tactic/linarith/preprocessing.lean
c2296c93c274d8b0fb7ee4ffd7229161d8fe455c
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
12,225
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import tactic.linarith.datatypes import tactic.zify import tactic.cancel_denoms /-! # Linarith preprocessing This file contains methods used to preprocess inputs to `linarith`. In particular, `linarith` works over comparisons of the form `t R 0`, where `R ∈ {<,≀,=}`. It assumes that expressions in `t` have integer coefficients and that the type of `t` has well-behaved subtraction. ## Implementation details A `global_preprocessor` is a function `list expr β†’ tactic(list expr)`. Users can add custom preprocessing steps by adding them to the `linarith_config` object. `linarith.default_preprocessors` is the main list, and generally none of these should be skipped unless you know what you're doing. -/ open native tactic expr namespace linarith /-! ### Preprocessing -/ open tactic set_option eqn_compiler.max_steps 50000 /-- If `prf` is a proof of `Β¬ e`, where `e` is a comparison, `rem_neg prf e` flips the comparison in `e` and returns a proof. For example, if `prf : Β¬ a < b`, ``rem_neg prf `(a < b)`` returns a proof of `a β‰₯ b`. -/ meta def rem_neg (prf : expr) : expr β†’ tactic expr | `(_ ≀ _) := mk_app ``lt_of_not_ge [prf] | `(_ < _) := mk_app ``le_of_not_gt [prf] | `(_ > _) := mk_app ``le_of_not_gt [prf] | `(_ β‰₯ _) := mk_app ``lt_of_not_ge [prf] | e := failed private meta def rearr_comp_aux : expr β†’ expr β†’ tactic expr | prf `(%%a ≀ 0) := return prf | prf `(%%a < 0) := return prf | prf `(%%a = 0) := return prf | prf `(%%a β‰₯ 0) := mk_app ``neg_nonpos_of_nonneg [prf] | prf `(%%a > 0) := mk_app `neg_neg_of_pos [prf] | prf `(0 β‰₯ %%a) := to_expr ``(id_rhs (%%a ≀ 0) %%prf) | prf `(0 > %%a) := to_expr ``(id_rhs (%%a < 0) %%prf) | prf `(0 = %%a) := mk_app `eq.symm [prf] | prf `(0 ≀ %%a) := mk_app ``neg_nonpos_of_nonneg [prf] | prf `(0 < %%a) := mk_app `neg_neg_of_pos [prf] | prf `(%%a ≀ %%b) := mk_app ``sub_nonpos_of_le [prf] | prf `(%%a < %%b) := mk_app `sub_neg_of_lt [prf] | prf `(%%a = %%b) := mk_app `sub_eq_zero_of_eq [prf] | prf `(%%a > %%b) := mk_app `sub_neg_of_lt [prf] | prf `(%%a β‰₯ %%b) := mk_app ``sub_nonpos_of_le [prf] | prf `(Β¬ %%t) := do nprf ← rem_neg prf t, tp ← infer_type nprf, rearr_comp_aux nprf tp | prf a := trace a >> fail "couldn't rearrange comp" /-- `rearr_comp e` takes a proof `e` of an equality, inequality, or negation thereof, and turns it into a proof of a comparison `_ R 0`, where `R ∈ {=, ≀, <}`. -/ meta def rearr_comp (e : expr) : tactic expr := infer_type e >>= rearr_comp_aux e /-- If `e` is of the form `((n : β„•) : β„€)`, `is_nat_int_coe e` returns `n : β„•`. -/ meta def is_nat_int_coe : expr β†’ option expr | `(@coe β„• β„€ %%_ %%n) := some n | _ := none /-- If `e : β„•`, returns a proof of `0 ≀ (e : β„€)`. -/ meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr := mk_app `int.coe_nat_nonneg [e] /-- `get_nat_comps e` returns a list of all subexpressions of `e` of the form `((t : β„•) : β„€)`. -/ meta def get_nat_comps : expr β†’ list expr | `(%%a + %%b) := (get_nat_comps a).append (get_nat_comps b) | `(%%a * %%b) := (get_nat_comps a).append (get_nat_comps b) | e := match is_nat_int_coe e with | some e' := [e'] | none := [] end /-- If `pf` is a proof of a strict inequality `(a : β„€) < b`, `mk_non_strict_int_pf_of_strict_int_pf pf` returns a proof of `a + 1 ≀ b`, and similarly if `pf` proves a negated weak inequality. -/ meta def mk_non_strict_int_pf_of_strict_int_pf (pf : expr) : tactic expr := do tp ← infer_type pf, match tp with | `(%%a < %%b) := to_expr ``(int.add_one_le_iff.mpr %%pf) | `(%%a > %%b) := to_expr ``(int.add_one_le_iff.mpr %%pf) | `(Β¬ %%a ≀ %%b) := to_expr ``(int.add_one_le_iff.mpr (le_of_not_gt %%pf)) | `(Β¬ %%a β‰₯ %%b) := to_expr ``(int.add_one_le_iff.mpr (le_of_not_gt %%pf)) | _ := fail "mk_non_strict_int_pf_of_strict_int_pf failed: proof is not an inequality" end /-- `is_nat_prop tp` is true iff `tp` is an inequality or equality between natural numbers or the negation thereof. -/ meta def is_nat_prop : expr β†’ bool | `(@eq β„• %%_ _) := tt | `(@has_le.le β„• %%_ _ _) := tt | `(@has_lt.lt β„• %%_ _ _) := tt | `(@ge β„• %%_ _ _) := tt | `(@gt β„• %%_ _ _) := tt | `(Β¬ %%p) := is_nat_prop p | _ := ff /-- `is_strict_int_prop tp` is true iff `tp` is a strict inequality between integers or the negation of a weak inequality between integers. -/ meta def is_strict_int_prop : expr β†’ bool | `(@has_lt.lt β„€ %%_ _ _) := tt | `(@gt β„€ %%_ _ _) := tt | `(Β¬ @has_le.le β„€ %%_ _ _) := tt | `(Β¬ @ge β„€ %%_ _ _) := tt | _ := ff private meta def filter_comparisons_aux : expr β†’ bool | `(Β¬ %%p) := p.app_symbol_in [`has_lt.lt, `has_le.le, `gt, `ge] | tp := tp.app_symbol_in [`has_lt.lt, `has_le.le, `gt, `ge, `eq] /-- Removes any expressions that are not proofs of inequalities, equalities, or negations thereof. -/ meta def filter_comparisons : preprocessor := { name := "filter terms that are not proofs of comparisons", transform := Ξ» h, (do tp ← infer_type h, is_prop tp >>= guardb, guardb (filter_comparisons_aux tp), return [h]) <|> return [] } /-- Replaces proofs of negations of comparisons with proofs of the reversed comparisons. For example, a proof of `Β¬ a < b` will become a proof of `a β‰₯ b`. -/ meta def remove_negations : preprocessor := { name := "replace negations of comparisons", transform := Ξ» h, do tp ← infer_type h, match tp with | `(Β¬ %%p) := singleton <$> rem_neg h p | _ := return [h] end } /-- If `h` is an equality or inequality between natural numbers, `nat_to_int` lifts this inequality to the integers. It also adds the facts that the integers involved are nonnegative. To avoid adding the same nonnegativity facts many times, it is a global preprocessor. -/ meta def nat_to_int : global_preprocessor := { name := "move nats to ints", transform := Ξ» l, do l ← l.mmap (Ξ» h, infer_type h >>= guardb ∘ is_nat_prop >> zify_proof [] h <|> return h), nonnegs ← l.mfoldl (Ξ» (es : expr_set) h, do (a, b) ← infer_type h >>= get_rel_sides, return $ (es.insert_list (get_nat_comps a)).insert_list (get_nat_comps b)) mk_rb_set, (++) l <$> nonnegs.to_list.mmap mk_coe_nat_nonneg_prf } /-- `strengthen_strict_int h` turns a proof `h` of a strict integer inequality `t1 < t2` into a proof of `t1 ≀ t2 + 1`. -/ meta def strengthen_strict_int : preprocessor := { name := "strengthen strict inequalities over int", transform := Ξ» h, do tp ← infer_type h, guardb (is_strict_int_prop tp) >> singleton <$> mk_non_strict_int_pf_of_strict_int_pf h <|> return [h] } /-- `mk_comp_with_zero h` takes a proof `h` of an equality, inequality, or negation thereof, and turns it into a proof of a comparison `_ R 0`, where `R ∈ {=, ≀, <}`. -/ meta def make_comp_with_zero : preprocessor := { name := "make comparisons with zero", transform := Ξ» e, singleton <$> rearr_comp e <|> return [] } /-- `normalize_denominators_in_lhs h lhs` assumes that `h` is a proof of `lhs R 0`. It creates a proof of `lhs' R 0`, where all numeric division in `lhs` has been cancelled. -/ meta def normalize_denominators_in_lhs (h lhs : expr) : tactic expr := do (v, lhs') ← cancel_factors.derive lhs, if v = 1 then return h else do (ih, h'') ← mk_single_comp_zero_pf v h, (_, nep, _) ← infer_type h'' >>= rewrite_core lhs', mk_eq_mp nep h'' /-- `cancel_denoms pf` assumes `pf` is a proof of `t R 0`. If `t` contains the division symbol `/`, it tries to scale `t` to cancel out division by numerals. -/ meta def cancel_denoms : preprocessor := { name := "cancel denominators", transform := Ξ» pf, (do some (_, lhs) ← parse_into_comp_and_expr <$> infer_type pf, guardb $ lhs.contains_constant (= `has_div.div), singleton <$> normalize_denominators_in_lhs pf lhs) <|> return [pf] } /-- `find_squares m e` collects all terms of the form `a ^ 2` and `a * a` that appear in `e` and adds them to the set `m`. A pair `(a, tt)` is added to `m` when `a^2` appears in `e`, and `(a, ff)` is added to `m` when `a*a` appears in `e`. -/ meta def find_squares : rb_set (expr Γ— bool) β†’ expr β†’ tactic (rb_set (expr Γ— bool)) | s `(%%a ^ 2) := do s ← find_squares s a, return (s.insert (a, tt)) | s e@`(%%e1 * %%e2) := if e1 = e2 then do s ← find_squares s e1, return (s.insert (e1, ff)) else e.mfoldl find_squares s | s e := e.mfoldl find_squares s /-- `nlinarith_extras` is the preprocessor corresponding to the `nlinarith` tactic. * For every term `t` such that `t^2` or `t*t` appears in the input, adds a proof of `t^2 β‰₯ 0` or `t*t β‰₯ 0`. * For every pair of comparisons `t1 R1 0` and `t2 R2 0`, adds a proof of `t1*t2 R 0`. This preprocessor is typically run last, after all inputs have been canonized. -/ meta def nlinarith_extras : global_preprocessor := { name := "nonlinear arithmetic extras", transform := Ξ» ls, do s ← ls.mfoldr (Ξ» h s', infer_type h >>= find_squares s') mk_rb_set, new_es ← s.mfold ([] : list expr) $ Ξ» ⟨e, is_sq⟩ new_es, ((do p ← mk_app (if is_sq then ``sq_nonneg else ``mul_self_nonneg) [e], return $ p::new_es) <|> return new_es), new_es ← make_comp_with_zero.globalize.transform new_es, linarith_trace "nlinarith preprocessing found squares", linarith_trace s, linarith_trace_proofs "so we added proofs" new_es, with_comps ← (new_es ++ ls).mmap (Ξ» e, do tp ← infer_type e, return $ (parse_into_comp_and_expr tp).elim (ineq.lt, e) (Ξ» ⟨ine, _⟩, (ine, e))), products ← with_comps.mmap_upper_triangle $ Ξ» ⟨posa, a⟩ ⟨posb, b⟩, some <$> match posa, posb with | ineq.eq, _ := mk_app ``zero_mul_eq [a, b] | _, ineq.eq := mk_app ``mul_zero_eq [a, b] | ineq.lt, ineq.lt := mk_app ``mul_pos_of_neg_of_neg [a, b] | ineq.lt, ineq.le := do a ← mk_app ``le_of_lt [a], mk_app ``mul_nonneg_of_nonpos_of_nonpos [a, b] | ineq.le, ineq.lt := do b ← mk_app ``le_of_lt [b], mk_app ``mul_nonneg_of_nonpos_of_nonpos [a, b] | ineq.le, ineq.le := mk_app ``mul_nonneg_of_nonpos_of_nonpos [a, b] end <|> return none, products ← make_comp_with_zero.globalize.transform products.reduce_option, return $ new_es ++ ls ++ products } /-- `remove_ne_aux` case splits on any proof `h : a β‰  b` in the input, turning it into `a < b ∨ a > b`. This produces `2^n` branches when there are `n` such hypotheses in the input. -/ meta def remove_ne_aux : list expr β†’ tactic (list branch) := Ξ» hs, (do e ← hs.mfind (Ξ» e : expr, do e ← infer_type e, guard $ e.is_ne.is_some), [(_, ng1), (_, ng2)] ← to_expr ``(or.elim (lt_or_gt_of_ne %%e)) >>= apply, let do_goal : expr β†’ tactic (list branch) := Ξ» g, do set_goals [g], h ← intro1, ls ← remove_ne_aux $ hs.remove_all [e], return $ ls.map (Ξ» b : branch, (b.1, h::b.2)) in (++) <$> do_goal ng1 <*> do_goal ng2) <|> do g ← get_goal, return [(g, hs)] /-- `remove_ne` case splits on any proof `h : a β‰  b` in the input, turning it into `a < b ∨ a > b`, by calling `linarith.remove_ne_aux`. This produces `2^n` branches when there are `n` such hypotheses in the input. -/ meta def remove_ne : global_branching_preprocessor := { name := "remove_ne", transform := remove_ne_aux } /-- The default list of preprocessors, in the order they should typically run. -/ meta def default_preprocessors : list global_branching_preprocessor := [filter_comparisons, remove_negations, nat_to_int, strengthen_strict_int, make_comp_with_zero, cancel_denoms] /-- `preprocess pps l` takes a list `l` of proofs of propositions. It maps each preprocessor `pp ∈ pps` over this list. The preprocessors are run sequentially: each recieves the output of the previous one. Note that a preprocessor may produce multiple or no expressions from each input expression, so the size of the list may change. -/ meta def preprocess (pps : list global_branching_preprocessor) (l : list expr) : tactic (list branch) := do g ← get_goal, pps.mfoldl (Ξ» ls pp, list.join <$> (ls.mmap $ Ξ» b, set_goals [b.1] >> pp.process b.2)) [(g, l)] end linarith
bdad18461f568c82460274959dadce8d5d777947
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/src/uexp/rules/mergeJoinFilter.lean
2a90ff8f8f67c29b0cc4dd3f4dd0a1892ad2d545
[ "BSD-2-Clause" ]
permissive
ReinierKoops/Cosette
e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb
eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29
refs/heads/master
1,686,483,953,198
1,624,293,498,000
1,624,293,498,000
378,997,885
0
0
BSD-2-Clause
1,624,293,485,000
1,624,293,484,000
null
UTF-8
Lean
false
false
1,591
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..meta.ucongr import ..meta.TDP set_option profiler true open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int variable integer_10: const datatypes.int theorem rule: forall ( Ξ“ scm_dept scm_emp: Schema) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL ((SELECT * FROM1 ((SELECT1 (combine (rightβ‹…rightβ‹…dept_deptno) (rightβ‹…leftβ‹…emp_ename)) FROM1 (product (table rel_emp) (table rel_dept)) WHERE (and (equal (uvariable (rightβ‹…leftβ‹…emp_deptno)) (uvariable (rightβ‹…rightβ‹…dept_deptno))) (equal (uvariable (rightβ‹…rightβ‹…dept_deptno)) (constantExpr integer_10))))) WHERE (equal (uvariable (rightβ‹…left)) (constantExpr integer_10))) :SQL Ξ“ _) = denoteSQL ((SELECT1 (combine (rightβ‹…rightβ‹…dept_deptno) (rightβ‹…leftβ‹…emp_ename)) FROM1 (product (table rel_emp) ((SELECT * FROM1 (table rel_dept) WHERE (equal (uvariable (rightβ‹…dept_deptno)) (constantExpr integer_10))))) WHERE (equal (uvariable (rightβ‹…leftβ‹…emp_deptno)) (uvariable (rightβ‹…rightβ‹…dept_deptno)))) :SQL Ξ“ _) := begin intros, unfold_all_denotations, funext, simp, print_size, TDP' ucongr, end
c2525d575d1569062a1f1fb3bdbc9bfc8d3595cf
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/category/Mon/filtered_colimits.lean
8372540ebe6f1f33aaef0d382d3547a4f98d1216
[ "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
14,290
lean
/- Copyright (c) 2021 Justus Springer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Justus Springer -/ import algebra.category.Mon.basic import category_theory.limits.concrete_category import category_theory.limits.preserves.filtered /-! # The forgetful functor from (commutative) (additive) monoids preserves filtered colimits. Forgetful functors from algebraic categories usually don't preserve colimits. However, they tend to preserve _filtered_ colimits. In this file, we start with a small filtered category `J` and a functor `F : J β₯€ Mon`. We then construct a monoid structure on the colimit of `F β‹™ forget Mon` (in `Type`), thereby showing that the forgetful functor `forget Mon` preserves filtered colimits. Similarly for `AddMon`, `CommMon` and `AddCommMon`. -/ universe v noncomputable theory open_locale classical open category_theory open category_theory.limits open category_theory.is_filtered (renaming max β†’ max') -- avoid name collision with `_root_.max`. namespace Mon.filtered_colimits section -- We use parameters here, mainly so we can have the abbreviations `M` and `M.mk` below, without -- passing around `F` all the time. parameters {J : Type v} [small_category J] (F : J β₯€ Mon.{v}) /-- The colimit of `F β‹™ forget Mon` in the category of types. In the following, we will construct a monoid structure on `M`. -/ @[to_additive "The colimit of `F β‹™ forget AddMon` in the category of types. In the following, we will construct an additive monoid structure on `M`."] abbreviation M : Type v := types.quot (F β‹™ forget Mon) /-- The canonical projection into the colimit, as a quotient type. -/ @[to_additive "The canonical projection into the colimit, as a quotient type."] abbreviation M.mk : (Ξ£ j, F.obj j) β†’ M := quot.mk (types.quot.rel (F β‹™ forget Mon)) @[to_additive] lemma M.mk_eq (x y : Ξ£ j, F.obj j) (h : βˆƒ (k : J) (f : x.1 ⟢ k) (g : y.1 ⟢ k), F.map f x.2 = F.map g y.2) : M.mk x = M.mk y := quot.eqv_gen_sound (types.filtered_colimit.eqv_gen_quot_rel_of_rel (F β‹™ forget Mon) x y h) variables [is_filtered J] /-- As `J` is nonempty, we can pick an arbitrary object `jβ‚€ : J`. We use this object to define the "one" in the colimit as the equivalence class of `⟨jβ‚€, 1 : F.obj jβ‚€βŸ©`. -/ @[to_additive "As `J` is nonempty, we can pick an arbitrary object `jβ‚€ : J`. We use this object to define the \"zero\" in the colimit as the equivalence class of `⟨jβ‚€, 0 : F.obj jβ‚€βŸ©`."] instance colimit_has_one : has_one M := { one := M.mk ⟨is_filtered.nonempty.some, 1⟩ } /-- The definition of the "one" in the colimit is independent of the chosen object of `J`. In particular, this lemma allows us to "unfold" the definition of `colimit_one` at a custom chosen object `j`. -/ @[to_additive "The definition of the \"zero\" in the colimit is independent of the chosen object of `J`. In particular, this lemma allows us to \"unfold\" the definition of `colimit_zero` at a custom chosen object `j`."] lemma colimit_one_eq (j : J) : (1 : M) = M.mk ⟨j, 1⟩ := begin apply M.mk_eq, refine ⟨max' _ j, left_to_max _ j, right_to_max _ j, _⟩, simp, end /-- The "unlifted" version of multiplication in the colimit. To multiply two dependent pairs `⟨j₁, x⟩` and `⟨jβ‚‚, y⟩`, we pass to a common successor of `j₁` and `jβ‚‚` (given by `is_filtered.max`) and multiply them there. -/ @[to_additive "The \"unlifted\" version of addition in the colimit. To add two dependent pairs `⟨j₁, x⟩` and `⟨jβ‚‚, y⟩`, we pass to a common successor of `j₁` and `jβ‚‚` (given by `is_filtered.max`) and add them there."] def colimit_mul_aux (x y : Ξ£ j, F.obj j) : M := M.mk ⟨max' x.1 y.1, F.map (left_to_max x.1 y.1) x.2 * F.map (right_to_max x.1 y.1) y.2⟩ /-- Multiplication in the colimit is well-defined in the left argument. -/ @[to_additive "Addition in the colimit is well-defined in the left argument."] lemma colimit_mul_aux_eq_of_rel_left {x x' y : Ξ£ j, F.obj j} (hxx' : types.filtered_colimit.rel (F β‹™ forget Mon) x x') : colimit_mul_aux x y = colimit_mul_aux x' y := begin cases x with j₁ x, cases y with jβ‚‚ y, cases x' with j₃ x', obtain ⟨l, f, g, hfg⟩ := hxx', simp at hfg, obtain ⟨s, Ξ±, Ξ², Ξ³, h₁, hβ‚‚, hβ‚ƒβŸ© := tulip (left_to_max j₁ jβ‚‚) (right_to_max j₁ jβ‚‚) (right_to_max j₃ jβ‚‚) (left_to_max j₃ jβ‚‚) f g, apply M.mk_eq, use [s, Ξ±, Ξ³], dsimp, simp_rw [monoid_hom.map_mul, ← comp_apply, ← F.map_comp, h₁, hβ‚‚, h₃, F.map_comp, comp_apply, hfg] end /-- Multiplication in the colimit is well-defined in the right argument. -/ @[to_additive "Addition in the colimit is well-defined in the right argument."] lemma colimit_mul_aux_eq_of_rel_right {x y y' : Ξ£ j, F.obj j} (hyy' : types.filtered_colimit.rel (F β‹™ forget Mon) y y') : colimit_mul_aux x y = colimit_mul_aux x y' := begin cases y with j₁ y, cases x with jβ‚‚ x, cases y' with j₃ y', obtain ⟨l, f, g, hfg⟩ := hyy', simp at hfg, obtain ⟨s, Ξ±, Ξ², Ξ³, h₁, hβ‚‚, hβ‚ƒβŸ© := tulip (right_to_max jβ‚‚ j₁) (left_to_max jβ‚‚ j₁) (left_to_max jβ‚‚ j₃) (right_to_max jβ‚‚ j₃) f g, apply M.mk_eq, use [s, Ξ±, Ξ³], dsimp, simp_rw [monoid_hom.map_mul, ← comp_apply, ← F.map_comp, h₁, hβ‚‚, h₃, F.map_comp, comp_apply, hfg] end /-- Multiplication in the colimit. See also `colimit_mul_aux`. -/ @[to_additive "Addition in the colimit. See also `colimit_add_aux`."] instance colimit_has_mul : has_mul M := { mul := Ξ» x y, begin refine quot.liftβ‚‚ (colimit_mul_aux F) _ _ x y, { intros x y y' h, apply colimit_mul_aux_eq_of_rel_right, apply types.filtered_colimit.rel_of_quot_rel, exact h }, { intros x x' y h, apply colimit_mul_aux_eq_of_rel_left, apply types.filtered_colimit.rel_of_quot_rel, exact h }, end } /-- Multiplication in the colimit is independent of the chosen "maximum" in the filtered category. In particular, this lemma allows us to "unfold" the definition of the multiplication of `x` and `y`, using a custom object `k` and morphisms `f : x.1 ⟢ k` and `g : y.1 ⟢ k`. -/ @[to_additive "Addition in the colimit is independent of the chosen \"maximum\" in the filtered category. In particular, this lemma allows us to \"unfold\" the definition of the addition of `x` and `y`, using a custom object `k` and morphisms `f : x.1 ⟢ k` and `g : y.1 ⟢ k`."] lemma colimit_mul_mk_eq (x y : Ξ£ j, F.obj j) (k : J) (f : x.1 ⟢ k) (g : y.1 ⟢ k) : (M.mk x) * (M.mk y) = M.mk ⟨k, F.map f x.2 * F.map g y.2⟩ := begin cases x with j₁ x, cases y with jβ‚‚ y, obtain ⟨s, Ξ±, Ξ², h₁, hβ‚‚βŸ© := bowtie (left_to_max j₁ jβ‚‚) f (right_to_max j₁ jβ‚‚) g, apply M.mk_eq, use [s, Ξ±, Ξ²], dsimp, simp_rw [monoid_hom.map_mul, ← comp_apply, ← F.map_comp, h₁, hβ‚‚], end @[to_additive] instance colimit_monoid : monoid M := { one_mul := Ξ» x, begin apply quot.induction_on x, clear x, intro x, cases x with j x, rw [colimit_one_eq F j, colimit_mul_mk_eq F ⟨j, 1⟩ ⟨j, x⟩ j (πŸ™ j) (πŸ™ j), monoid_hom.map_one, one_mul, F.map_id, id_apply], end, mul_one := Ξ» x, begin apply quot.induction_on x, clear x, intro x, cases x with j x, rw [colimit_one_eq F j, colimit_mul_mk_eq F ⟨j, x⟩ ⟨j, 1⟩ j (πŸ™ j) (πŸ™ j), monoid_hom.map_one, mul_one, F.map_id, id_apply], end, mul_assoc := Ξ» x y z, begin apply quot.induction_on₃ x y z, clear x y z, intros x y z, cases x with j₁ x, cases y with jβ‚‚ y, cases z with j₃ z, rw [colimit_mul_mk_eq F ⟨j₁, x⟩ ⟨jβ‚‚, y⟩ _ (first_to_max₃ j₁ jβ‚‚ j₃) (second_to_max₃ j₁ jβ‚‚ j₃), colimit_mul_mk_eq F ⟨max₃ j₁ jβ‚‚ j₃, _⟩ ⟨j₃, z⟩ _ (πŸ™ _) (third_to_max₃ j₁ jβ‚‚ j₃), colimit_mul_mk_eq F ⟨jβ‚‚, y⟩ ⟨j₃, z⟩ _ (second_to_max₃ j₁ jβ‚‚ j₃) (third_to_max₃ j₁ jβ‚‚ j₃), colimit_mul_mk_eq F ⟨j₁, x⟩ ⟨max₃ j₁ jβ‚‚ j₃, _⟩ _ (first_to_max₃ j₁ jβ‚‚ j₃) (πŸ™ _)], simp only [F.map_id, id_apply, mul_assoc], end, ..colimit_has_one, ..colimit_has_mul } /-- The bundled monoid giving the filtered colimit of a diagram. -/ @[to_additive "The bundled additive monoid giving the filtered colimit of a diagram."] def colimit : Mon := Mon.of M /-- The monoid homomorphism from a given monoid in the diagram to the colimit monoid. -/ @[to_additive "The additive monoid homomorphism from a given additive monoid in the diagram to the colimit additive monoid."] def cocone_morphism (j : J) : F.obj j ⟢ colimit := { to_fun := (types.colimit_cocone (F β‹™ forget Mon)).ΞΉ.app j, map_one' := (colimit_one_eq j).symm, map_mul' := Ξ» x y, begin convert (colimit_mul_mk_eq F ⟨j, x⟩ ⟨j, y⟩ j (πŸ™ j) (πŸ™ j)).symm, rw [F.map_id, id_apply, id_apply], refl, end } @[simp, to_additive] lemma cocone_naturality {j j' : J} (f : j ⟢ j') : F.map f ≫ (cocone_morphism j') = cocone_morphism j := monoid_hom.coe_inj ((types.colimit_cocone (F β‹™ forget Mon)).ΞΉ.naturality f) /-- The cocone over the proposed colimit monoid. -/ @[to_additive "The cocone over the proposed colimit additive monoid."] def colimit_cocone : cocone F := { X := colimit, ΞΉ := { app := cocone_morphism } }. /-- Given a cocone `t` of `F`, the induced monoid homomorphism from the colimit to the cocone point. As a function, this is simply given by the induced map of the corresponding cocone in `Type`. The only thing left to see is that it is a monoid homomorphism. -/ @[to_additive "Given a cocone `t` of `F`, the induced additive monoid homomorphism from the colimit to the cocone point. As a function, this is simply given by the induced map of the corresponding cocone in `Type`. The only thing left to see is that it is an additive monoid homomorphism."] def colimit_desc (t : cocone F) : colimit ⟢ t.X := { to_fun := (types.colimit_cocone_is_colimit (F β‹™ forget Mon)).desc ((forget Mon).map_cocone t), map_one' := begin rw colimit_one_eq F is_filtered.nonempty.some, exact monoid_hom.map_one _, end, map_mul' := Ξ» x y, begin apply quot.induction_onβ‚‚ x y, clear x y, intros x y, cases x with i x, cases y with j y, rw colimit_mul_mk_eq F ⟨i, x⟩ ⟨j, y⟩ (max' i j) (left_to_max i j) (right_to_max i j), dsimp [types.colimit_cocone_is_colimit], rw [monoid_hom.map_mul, t.w_apply, t.w_apply], end } /-- The proposed colimit cocone is a colimit in `Mon`. -/ @[to_additive "The proposed colimit cocone is a colimit in `AddMon`."] def colimit_cocone_is_colimit : is_colimit colimit_cocone := { desc := colimit_desc, fac' := Ξ» t j, monoid_hom.coe_inj ((types.colimit_cocone_is_colimit (F β‹™ forget Mon)).fac ((forget Mon).map_cocone t) j), uniq' := Ξ» t m h, monoid_hom.coe_inj $ (types.colimit_cocone_is_colimit (F β‹™ forget Mon)).uniq ((forget Mon).map_cocone t) m (Ξ» j, funext $ Ξ» x, monoid_hom.congr_fun (h j) x) } @[to_additive] instance forget_preserves_filtered_colimits : preserves_filtered_colimits (forget Mon) := { preserves_filtered_colimits := Ξ» J _ _, by exactI { preserves_colimit := Ξ» F, preserves_colimit_of_preserves_colimit_cocone (colimit_cocone_is_colimit F) (types.colimit_cocone_is_colimit (F β‹™ forget Mon)) } } end end Mon.filtered_colimits namespace CommMon.filtered_colimits open Mon.filtered_colimits (colimit_mul_mk_eq) section -- We use parameters here, mainly so we can have the abbreviation `M` below, without -- passing around `F` all the time. parameters {J : Type v} [small_category J] [is_filtered J] (F : J β₯€ CommMon.{v}) /-- The colimit of `F β‹™ forgetβ‚‚ CommMon Mon` in the category `Mon`. In the following, we will show that this has the structure of a _commutative_ monoid. -/ @[to_additive "The colimit of `F β‹™ forgetβ‚‚ AddCommMon AddMon` in the category `AddMon`. In the following, we will show that this has the structure of a _commutative_ additive monoid."] abbreviation M : Mon := Mon.filtered_colimits.colimit (F β‹™ forgetβ‚‚ CommMon Mon.{v}) @[to_additive] instance colimit_comm_monoid : comm_monoid M := { mul_comm := Ξ» x y, begin apply quot.induction_onβ‚‚ x y, clear x y, intros x y, let k := max' x.1 y.1, let f := left_to_max x.1 y.1, let g := right_to_max x.1 y.1, rw [colimit_mul_mk_eq _ x y k f g, colimit_mul_mk_eq _ y x k g f], dsimp, rw mul_comm, end ..M.monoid } /-- The bundled commutative monoid giving the filtered colimit of a diagram. -/ @[to_additive "The bundled additive commutative monoid giving the filtered colimit of a diagram."] def colimit : CommMon := CommMon.of M /-- The cocone over the proposed colimit commutative monoid. -/ @[to_additive "The cocone over the proposed colimit additive commutative monoid."] def colimit_cocone : cocone F := { X := colimit, ΞΉ := { ..(Mon.filtered_colimits.colimit_cocone (F β‹™ forgetβ‚‚ CommMon Mon.{v})).ΞΉ } } /-- The proposed colimit cocone is a colimit in `CommMon`. -/ @[to_additive "The proposed colimit cocone is a colimit in `AddCommMon`."] def colimit_cocone_is_colimit : is_colimit colimit_cocone := { desc := Ξ» t, Mon.filtered_colimits.colimit_desc (F β‹™ forgetβ‚‚ CommMon Mon.{v}) ((forgetβ‚‚ CommMon Mon.{v}).map_cocone t), fac' := Ξ» t j, monoid_hom.coe_inj $ (types.colimit_cocone_is_colimit (F β‹™ forget CommMon)).fac ((forget CommMon).map_cocone t) j, uniq' := Ξ» t m h, monoid_hom.coe_inj $ (types.colimit_cocone_is_colimit (F β‹™ forget CommMon)).uniq ((forget CommMon).map_cocone t) m ((Ξ» j, funext $ Ξ» x, monoid_hom.congr_fun (h j) x)) } @[to_additive forgetβ‚‚_AddMon_preserves_filtered_colimits] instance forgetβ‚‚_Mon_preserves_filtered_colimits : preserves_filtered_colimits (forgetβ‚‚ CommMon Mon.{v}) := { preserves_filtered_colimits := Ξ» J _ _, by exactI { preserves_colimit := Ξ» F, preserves_colimit_of_preserves_colimit_cocone (colimit_cocone_is_colimit F) (Mon.filtered_colimits.colimit_cocone_is_colimit (F β‹™ forgetβ‚‚ CommMon Mon.{v})) } } @[to_additive] instance forget_preserves_filtered_colimits : preserves_filtered_colimits (forget CommMon) := limits.comp_preserves_filtered_colimits (forgetβ‚‚ CommMon Mon) (forget Mon) end end CommMon.filtered_colimits
5d26216270dcc6c38626149f4f45b58f0c11d4a9
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/scratch/dead_simplex.lean
5a740a69843c0304707ff712008e77446b67b1e6
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
43,408
lean
import tableau order.lexicographic open matrix fintype finset function pequiv partition variables {m n : β„•} local notation `rvec`:2000 n := matrix (fin 1) (fin n) β„š local notation `cvec`:2000 m := matrix (fin m) (fin 1) β„š local infix ` ⬝ `:70 := matrix.mul local postfix `α΅€` : 1500 := transpose namespace tableau def pivot_linear_order (T : tableau m n) : decidable_linear_order (fin n) := decidable_linear_order.lift T.to_partition.colg (injective_colg _) (by apply_instance) def pivot_col (T : tableau m n) (obj : fin m) : option (fin n) := option.cases_on (fin.find (Ξ» c : fin n, T.to_matrix obj c β‰  0 ∧ T.to_partition.colg c βˆ‰ T.restricted ∧ c βˆ‰ T.dead)) (((list.fin_range n).filter (Ξ» c : fin n, 0 < T.to_matrix obj c ∧ c βˆ‰ T.dead)).argmin T.to_partition.colg) some def pivot_row_linear_order (T : tableau m n) (c : fin n) : decidable_linear_order (fin m) := decidable_linear_order.lift (show fin m β†’ lex β„š (fin (m + n)), from Ξ» r', (abs (T.const r' 0 / T.to_matrix r' c), T.to_partition.rowg r')) (Ξ» x y, by simp [T.to_partition.injective_rowg.eq_iff]) (by apply_instance) section local attribute [instance, priority 0] fin.has_le fin.decidable_linear_order lemma pivot_row_linear_order_le_def (T : tableau m n) (c : fin n) : @has_le.le (fin m) (by haveI := pivot_row_linear_order T c; apply_instance) = (Ξ» i i', abs (T.const i 0 / T.to_matrix i c) < abs (T.const i' 0 / T.to_matrix i' c) ∨ (abs (T.const i 0 / T.to_matrix i c) = abs (T.const i' 0 / T.to_matrix i' c) ∧ T.to_partition.rowg i ≀ T.to_partition.rowg i')) := funext $ Ξ» i, funext $ Ξ» i', propext $ prod.lex_def _ _ end def pivot_row (T : tableau m n) (obj: fin m) (c : fin n) : option (fin m) := let l := (list.fin_range m).filter (Ξ» r : fin m, obj β‰  r ∧ T.to_partition.rowg r ∈ T.restricted ∧ T.to_matrix obj c / T.to_matrix r c < 0) in @list.minimum _ (pivot_row_linear_order T c) l lemma pivot_col_spec {T : tableau m n} {obj : fin m} {c : fin n} : c ∈ pivot_col T obj β†’ ((T.to_matrix obj c β‰  0 ∧ T.to_partition.colg c βˆ‰ T.restricted) ∨ (0 < T.to_matrix obj c ∧ T.to_partition.colg c ∈ T.restricted)) ∧ c βˆ‰ T.dead := begin simp [pivot_col], cases h : fin.find (Ξ» c : fin n, T.to_matrix obj c β‰  0 ∧ T.to_partition.colg c βˆ‰ T.restricted ∧ c βˆ‰ T.dead), { finish [h, fin.find_eq_some_iff, fin.find_eq_none_iff, lt_irrefl, list.argmin_eq_some_iff] }, { finish [fin.find_eq_some_iff] } end lemma nonpos_of_lt_pivot_col {T : tableau m n} {obj : fin m} {c j : fin n} (hc : c ∈ pivot_col T obj) (hcres : T.to_partition.colg c ∈ T.restricted) (hdead : j βˆ‰ T.dead) (hjc : T.to_partition.colg j < T.to_partition.colg c) : T.to_matrix obj j ≀ 0 := begin rw [pivot_col] at hc, cases h : fin.find (Ξ» c, T.to_matrix obj c β‰  0 ∧ colg (T.to_partition) c βˆ‰ T.restricted ∧ c βˆ‰ T.dead), { rw h at hc, refine le_of_not_lt (Ξ» hj0, _), exact not_le_of_gt hjc ((list.mem_argmin_iff.1 hc).2.1 j (list.mem_filter.2 (by simp [hj0, hdead]))) }, { rw h at hc, simp [*, fin.find_eq_some_iff] at * } end lemma pivot_col_eq_none {T : tableau m n} {obj : fin m} (hT : T.feasible) (h : pivot_col T obj = none) : T.is_optimal (T.of_col 0) (T.to_partition.rowg obj) := is_optimal_of_col_zero hT begin revert h, simp [pivot_col], cases h : fin.find (Ξ» c : fin n, T.to_matrix obj c β‰  0 ∧ T.to_partition.colg c βˆ‰ T.restricted ∧ c βˆ‰ T.dead), { simp only [list.filter_eq_nil, forall_prop_of_true, list.argmin_eq_none, list.mem_fin_range, not_and, not_not, fin.find_eq_none_iff] at *, assume hj j hdead, exact ⟨le_of_not_gt (Ξ» h0, hdead (hj j h0)), by finish⟩ }, { simp [h] } end lemma pivot_row_spec {T : tableau m n} {obj r : fin m} {c : fin n} : r ∈ pivot_row T obj c β†’ obj β‰  r ∧ T.to_partition.rowg r ∈ T.restricted ∧ T.to_matrix obj c / T.to_matrix r c < 0 ∧ (βˆ€ r' : fin m, obj β‰  r' β†’ T.to_partition.rowg r' ∈ T.restricted β†’ T.to_matrix obj c / T.to_matrix r' c < 0 β†’ abs (T.const r 0 / T.to_matrix r c) ≀ abs (T.const r' 0 / T.to_matrix r' c)) := begin simp only [list.mem_filter, pivot_row, option.mem_def, with_bot.some_eq_coe, list.minimum_eq_coe_iff, list.mem_fin_range, true_and, and_imp], rw [pivot_row_linear_order_le_def], intros hor hres hr0 h, simp only [*, true_and, ne.def, not_false_iff], intros r' hor' hres' hr0', cases h r' hor' hres' hr0', { exact le_of_lt (by assumption) }, { exact le_of_eq (by tauto) } end lemma nonneg_of_lt_pivot_row {T : tableau m n} {obj : fin m} {r i : fin m} {c : fin n} (hc0 : 0 < T.to_matrix obj c) (hres : T.to_partition.rowg i ∈ T.restricted) (hc : c ∈ pivot_col T obj) (hr : r ∈ pivot_row T obj c) (hconst : T.const i 0 = 0) (hjc : T.to_partition.rowg i < T.to_partition.rowg r) : 0 ≀ T.to_matrix i c := if hobj : obj = i then le_of_lt $ hobj β–Έ hc0 else le_of_not_gt $ Ξ» hic, not_le_of_lt hjc begin have := ((@list.minimum_eq_coe_iff _ (id _) _ _).1 hr).2 i (list.mem_filter.2 ⟨list.mem_fin_range _, hobj, hres, div_neg_of_pos_of_neg hc0 hic⟩), rw [pivot_row_linear_order_le_def] at this, simp [hconst, not_lt_of_ge (abs_nonneg _), *] at * end lemma ne_zero_of_mem_pivot_row {T : tableau m n} {obj r : fin m} {c : fin n} (hr : r ∈ pivot_row T obj c) : T.to_matrix r c β‰  0 := assume hrc, by simpa [lt_irrefl, hrc] using pivot_row_spec hr lemma ne_zero_of_mem_pivot_col {T : tableau m n} {obj : fin m} {c : fin n} (hc : c ∈ pivot_col T obj) : T.to_matrix obj c β‰  0 := Ξ» h, by simpa [h, lt_irrefl] using pivot_col_spec hc lemma pivot_row_eq_none_aux {T : tableau m n} {obj : fin m} {c : fin n} (hrow : pivot_row T obj c = none) (hs : c ∈ pivot_col T obj) : βˆ€ r, obj β‰  r β†’ T.to_partition.rowg r ∈ T.restricted β†’ 0 ≀ T.to_matrix obj c / T.to_matrix r c := by simpa [pivot_row, list.filter_eq_nil] using hrow lemma pivot_row_eq_none {T : tableau m n} {obj : fin m} {c : fin n} (hT : T.feasible) (hrow : pivot_row T obj c = none) (hs : c ∈ pivot_col T obj) : T.is_unbounded_above (T.to_partition.rowg obj) := have hrow : βˆ€ r, obj β‰  r β†’ T.to_partition.rowg r ∈ T.restricted β†’ 0 ≀ T.to_matrix obj c / T.to_matrix r c, from pivot_row_eq_none_aux hrow hs, have hc : ((T.to_matrix obj c β‰  0 ∧ T.to_partition.colg c βˆ‰ T.restricted) ∨ (0 < T.to_matrix obj c ∧ T.to_partition.colg c ∈ T.restricted)) ∧ c βˆ‰ T.dead, from pivot_col_spec hs, have hToc : T.to_matrix obj c β‰  0, from Ξ» h, by simpa [h, lt_irrefl] using hc, (lt_or_gt_of_ne hToc).elim (Ξ» hToc : T.to_matrix obj c < 0, is_unbounded_above_rowg_of_nonpos hT c (hc.1.elim and.right (Ξ» h, (not_lt_of_gt hToc h.1).elim)) hc.2 (Ξ» i hi, classical.by_cases (Ξ» hoi : obj = i, le_of_lt (hoi β–Έ hToc)) (Ξ» hoi : obj β‰  i, inv_nonpos.1 $ nonpos_of_mul_nonneg_right (hrow _ hoi hi) hToc)) hToc) (Ξ» hToc : 0 < T.to_matrix obj c, is_unbounded_above_rowg_of_nonneg hT c (Ξ» i hi, classical.by_cases (Ξ» hoi : obj = i, le_of_lt (hoi β–Έ hToc)) (Ξ» hoi : obj β‰  i, inv_nonneg.1 $ nonneg_of_mul_nonneg_left (hrow _ hoi hi) hToc)) hc.2 hToc) def feasible_of_mem_pivot_row_and_col {T : tableau m n} {obj : fin m} (hT : T.feasible) {c} (hc : c ∈ pivot_col T obj) {r} (hr : r ∈ pivot_row T obj c) : feasible (T.pivot r c) := begin have := pivot_col_spec hc, have := pivot_row_spec hr, have := @feasible_simplex_pivot _ _ _ obj hT r c, tauto end section blands_rule local attribute [instance, priority 0] classical.dec variable (obj : fin m) lemma not_unique_row_and_unique_col {T T' : tableau m n} {r c c'} (hcobj0 : 0 < T.to_matrix obj c) (hc'obj0 : 0 < T'.to_matrix obj c') (hrc0 : T.to_matrix r c < 0) (hflat : T.flat = T'.flat) (hs : T.to_partition.rowg r = T'.to_partition.colg c') (hrobj : T.to_partition.rowg obj = T'.to_partition.rowg obj) (hfickle : βˆ€ i, T.to_partition.rowg i β‰  T'.to_partition.rowg i β†’ T.const i 0 = 0) (hobj : T.const obj 0 = T'.const obj 0) (nonpos_of_colg_ne : βˆ€ j, T'.to_partition.colg j β‰  T.to_partition.colg j β†’ j β‰  c' β†’ T'.to_matrix obj j ≀ 0) (nonpos_of_colg_eq : βˆ€ j, j β‰  c' β†’ T'.to_partition.colg j = T.to_partition.colg c β†’ T'.to_matrix obj j ≀ 0) (unique_row : βˆ€ i β‰  r, T.const i 0 = 0 β†’ T.to_partition.rowg i β‰  T'.to_partition.rowg i β†’ 0 ≀ T.to_matrix i c) : false := let objr := T.to_partition.rowg obj in let x := Ξ» y : β„š, T.of_col (y β€’ (single c 0).to_matrix) in have hxflatT' : βˆ€ {y}, x y ∈ flat T', from hflat β–Έ Ξ» _, of_col_mem_flat _ _, have hxrow : βˆ€ y i, x y (T.to_partition.rowg i) 0 = T.const i 0 + y * T.to_matrix i c, by simp [x, of_col_single_rowg], have hxcol : βˆ€ {y j}, j β‰  c β†’ x y (T.to_partition.colg j) 0 = 0, from Ξ» y j hjc, by simp [x, of_col_colg, pequiv.to_matrix, single_apply_of_ne hjc.symm], have hxcolc : βˆ€ {y}, x y (T.to_partition.colg c) 0 = y, by simp [x, of_col_colg, pequiv.to_matrix], let c_star : fin (m + n) β†’ β„š := Ξ» v, option.cases_on (T'.to_partition.colp.symm v) 0 (T'.to_matrix obj) in have hxobj : βˆ€ y, x y objr 0 = T.const obj 0 + y * T.to_matrix obj c, from Ξ» y, hxrow _ _, have hgetr : βˆ€ {y v}, c_star v * x y v 0 β‰  0 β†’ (T'.to_partition.colp.symm v).is_some, from Ξ» y v, by cases h : T'.to_partition.colp.symm v; dsimp [c_star]; rw h; simp, have c_star_eq_get : βˆ€ {v} (hv : (T'.to_partition.colp.symm v).is_some), c_star v = T'.to_matrix obj (option.get hv), from Ξ» v hv, by dsimp only [c_star]; conv_lhs{rw [← option.some_get hv]}; refl, have hsummmn : βˆ€ {y}, sum univ (Ξ» j, T'.to_matrix obj j * x y (T'.to_partition.colg j) 0) = sum univ (Ξ» v, c_star v * x y v 0), from Ξ» y, sum_bij_ne_zero (Ξ» j _ _, T'.to_partition.colg j) (Ξ» _ _ _, mem_univ _) (Ξ» _ _ _ _ _ _ h, T'.to_partition.injective_colg h) (Ξ» v _ h0, ⟨option.get (hgetr h0), mem_univ _, by rw [← c_star_eq_get (hgetr h0)]; simpa using h0, by simp⟩) (Ξ» _ _ h0, by dsimp [c_star]; rw [colp_colg]), have hgetc : βˆ€ {y v}, c_star v * x y v 0 β‰  0 β†’ v β‰  T.to_partition.colg c β†’ (T.to_partition.rowp.symm v).is_some, from Ξ» y v, (eq_rowg_or_colg T.to_partition v).elim (Ξ» ⟨i, hi⟩, by rw [hi, rowp_rowg]; simp) (Ξ» ⟨j, hj⟩ h0 hvc, by rw [hj, hxcol (mt (congr_arg T.to_partition.colg) (hvc ∘ hj.trans)), mul_zero] at h0; exact (h0 rfl).elim), have hsummmnn : βˆ€ {y}, (univ.erase (T.to_partition.colg c)).sum (Ξ» v, c_star v * x y v 0) = univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * x y (T.to_partition.rowg i) 0), from Ξ» y, eq.symm $ sum_bij_ne_zero (Ξ» i _ _, T.to_partition.rowg i) (by simp) (Ξ» _ _ _ _ _ _ h, T.to_partition.injective_rowg h) (Ξ» v hvc h0, ⟨option.get (hgetc h0 (mem_erase.1 hvc).1), mem_univ _, by simpa using h0⟩) (by intros; refl), have hsumm : βˆ€ {y}, univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * x y (T.to_partition.rowg i) 0) = univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.const i 0) + y * univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.to_matrix i c), from Ξ» y, by simp only [hxrow, mul_add, add_mul, sum_add_distrib, mul_assoc, mul_left_comm _ y, mul_sum.symm], have hxobj' : βˆ€ y, x y objr 0 = univ.sum (Ξ» v, c_star v * x y v 0) + T'.const obj 0, from Ξ» y, by dsimp [objr]; rw [hrobj, mem_flat_iff.1 hxflatT', hsummmn], have hy : βˆ€ {y}, y * T.to_matrix obj c = c_star (T.to_partition.colg c) * y + univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.const i 0) + y * univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.to_matrix i c), from Ξ» y, by rw [← add_left_inj (T.const obj 0), ← hxobj, hxobj', ← insert_erase (mem_univ (T.to_partition.colg c)), sum_insert (not_mem_erase _ _), hsummmnn, hobj, hsumm, hxcolc]; simp, have hy' : βˆ€ (y), y * (T.to_matrix obj c - c_star (T.to_partition.colg c) - univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.to_matrix i c)) = univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.const i 0), from Ξ» y, by rw [mul_sub, mul_sub, hy]; simp [mul_comm, mul_assoc, mul_left_comm], have h0 : T.to_matrix obj c - c_star (T.to_partition.colg c) - univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.to_matrix i c) = 0, by rw [← (domain.mul_left_inj (@one_ne_zero β„š _)), hy', ← hy' 0, zero_mul, mul_zero], have hcolnec' : T'.to_partition.colp.symm (T.to_partition.colg c) β‰  some c', from Ξ» h, by simpa [hs.symm] using congr_arg T'.to_partition.colg (option.eq_some_iff_get_eq.1 h).snd, have eq_of_roweqc' : βˆ€ {i}, T'.to_partition.colp.symm (T.to_partition.rowg i) = some c' β†’ i = r, from Ξ» i h, by simpa [hs.symm, T.to_partition.injective_rowg.eq_iff] using congr_arg T'.to_partition.colg (option.eq_some_iff_get_eq.1 h).snd, have sumpos : 0 < univ.sum (Ξ» i, c_star (T.to_partition.rowg i) * T.to_matrix i c), by rw [← sub_eq_zero.1 h0]; exact add_pos_of_pos_of_nonneg hcobj0 (begin simp only [c_star, neg_nonneg], cases h : T'.to_partition.colp.symm (T.to_partition.colg c) with j, { refl }, { exact nonpos_of_colg_eq j (mt (congr_arg some) (h β–Έ hcolnec')) (by rw [← (option.eq_some_iff_get_eq.1 h).snd]; simp) } end), have hexi : βˆƒ i, 0 < c_star (T.to_partition.rowg i) * T.to_matrix i c, from imp_of_not_imp_not _ _ (by simpa using @sum_nonpos _ _ (@univ (fin m) _) (Ξ» i, c_star (T.to_partition.rowg i) * T.to_matrix i c) _ _) sumpos, let ⟨i, hi⟩ := hexi in have hi0 : T.const i 0 = 0, from hfickle i (Ξ» h, by dsimp [c_star] at hi; rw [h, colp_rowg_eq_none] at hi; simpa [lt_irrefl] using hi), have hi_some : (T'.to_partition.colp.symm (T.to_partition.rowg i)).is_some, from option.ne_none_iff_is_some.1 (Ξ» h, by dsimp only [c_star] at hi; rw h at hi; simpa [lt_irrefl] using hi), have hi' : 0 < T'.to_matrix obj (option.get hi_some) * T.to_matrix i c, by dsimp only [c_star] at hi; rwa [← option.some_get hi_some] at hi, have hir : i β‰  r, from Ξ» hir, begin have : option.get hi_some = c', from T'.to_partition.injective_colg (by rw [colg_get_colp_symm, ← hs, hir]), rw [this, hir] at hi', exact not_lt_of_gt hi' (mul_neg_of_pos_of_neg hc'obj0 hrc0) end, have hnec' : option.get hi_some β‰  c', from Ξ» eq_c', hir $ @eq_of_roweqc' i (eq_c' β–Έ by simp), have hic0 : T.to_matrix i c < 0, from neg_of_mul_pos_right hi' (nonpos_of_colg_ne _ (by simp) hnec'), not_le_of_gt hic0 (unique_row _ hir hi0 (by rw [← colg_get_colp_symm _ _ hi_some]; exact colg_ne_rowg _ _ _)) inductive rel : tableau m n β†’ tableau m n β†’ Prop | pivot : βˆ€ {T}, feasible T β†’ βˆ€ {r c}, c ∈ pivot_col T obj β†’ r ∈ pivot_row T obj c β†’ rel (T.pivot r c) T | trans_pivot : βˆ€ {T₁ Tβ‚‚ r c}, rel T₁ Tβ‚‚ β†’ c ∈ pivot_col T₁ obj β†’ r ∈ pivot_row T₁ obj c β†’ rel (T₁.pivot r c) Tβ‚‚ lemma feasible_of_rel_right {T T' : tableau m n} (h : rel obj T' T) : T.feasible := rel.rec_on h (by tauto) (by tauto) lemma feasible_of_rel_left {T T' : tableau m n} (h : rel obj T' T) : T'.feasible := rel.rec_on h (Ξ» _ hT _ _ hc hr, feasible_of_mem_pivot_row_and_col hT hc hr) (Ξ» _ _ _ _ _ hc hr hT, feasible_of_mem_pivot_row_and_col hT hc hr) /-- Slightly stronger recursor than the default recursor -/ @[elab_as_eliminator] lemma rel.rec_on' {obj : fin m} {C : tableau m n β†’ tableau m n β†’ Prop} {T T' : tableau m n} (hrel : rel obj T T') (hpivot : βˆ€ {T : tableau m n} {r : fin m} {c : fin n}, feasible T β†’ c ∈ pivot_col T obj β†’ r ∈ pivot_row T obj c β†’ C (pivot T r c) T) (hpivot_trans : βˆ€ {T₁ Tβ‚‚ : tableau m n} {r : fin m} {c : fin n}, rel obj (T₁.pivot r c) T₁ β†’ rel obj T₁ Tβ‚‚ β†’ c ∈ pivot_col T₁ obj β†’ r ∈ pivot_row T₁ obj c β†’ C (T₁.pivot r c) T₁ β†’ C T₁ Tβ‚‚ β†’ C (pivot T₁ r c) Tβ‚‚) : C T T' := rel.rec_on hrel (Ξ» T hT r c hc hr, hpivot hT hc hr) (Ξ» T₁ Tβ‚‚ r c hrelT₁₂ hc hr ih, hpivot_trans (rel.pivot (feasible_of_rel_left obj hrelT₁₂) hc hr) hrelT₁₂ hc hr (hpivot (feasible_of_rel_left obj hrelT₁₂) hc hr) ih) lemma rel.trans {obj : fin m} {T₁ Tβ‚‚ T₃ : tableau m n} (h₁₂ : rel obj T₁ Tβ‚‚) : rel obj Tβ‚‚ T₃ β†’ rel obj T₁ T₃ := rel.rec_on h₁₂ (Ξ» T r c hT hc hr hrelT, rel.trans_pivot hrelT hc hr) (Ξ» T₁ Tβ‚‚ r c hrelT₁₂ hc hr ih hrelT₂₃, rel.trans_pivot (ih hrelT₂₃) hc hr) instance : is_trans (tableau m n) (rel obj) := ⟨@rel.trans _ _ obj⟩ lemma flat_eq_of_rel {T T' : tableau m n} (h : rel obj T' T) : flat T' = flat T := rel.rec_on' h (Ξ» _ _ _ _ _ hr, flat_pivot (ne_zero_of_mem_pivot_row hr)) (Ξ» _ _ _ _ _ _ _ _, eq.trans) lemma rowg_obj_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.to_partition.rowg obj = T'.to_partition.rowg obj := rel.rec_on' h (Ξ» T r c hfT hc hr, by simp [rowg_swap_of_ne _ (pivot_row_spec hr).1]) (Ξ» _ _ _ _ _ _ _ _, eq.trans) lemma restricted_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.restricted = T'.restricted := rel.rec_on' h (Ξ» _ _ _ _ _ _, rfl) (Ξ» _ _ _ _ _ _ _ _, eq.trans) lemma dead_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.dead = T'.dead := rel.rec_on' h (Ξ» _ _ _ _ _ _, rfl) (Ξ» _ _ _ _ _ _ _ _, eq.trans) lemma dead_eq_of_rel_or_eq {T T' : tableau m n} (h : T = T' ∨ rel obj T T') : T.dead = T'.dead := h.elim (congr_arg _) $ dead_eq_of_rel _ lemma exists_mem_pivot_row_col_of_rel {T T' : tableau m n} (h : rel obj T' T) : βˆƒ r c, c ∈ pivot_col T obj ∧ r ∈ pivot_row T obj c := rel.rec_on' h (Ξ» _ r c _ hc hr, ⟨r, c, hc, hr⟩) (Ξ» _ _ _ _ _ _ _ _ _, id) lemma exists_mem_pivot_row_of_rel {T T' : tableau m n} (h : rel obj T' T) {c : fin n} (hc : c ∈ pivot_col T obj) : βˆƒ r, r ∈ pivot_row T obj c := let ⟨r, c', hc', hr⟩ := exists_mem_pivot_row_col_of_rel obj h in ⟨r, by simp * at *⟩ lemma colg_eq_or_exists_mem_pivot_col {T₁ Tβ‚‚ : tableau m n} (h : rel obj Tβ‚‚ T₁) {c : fin n} : T₁.to_partition.colg c = Tβ‚‚.to_partition.colg c ∨ βˆƒ T₃, (T₃ = T₁ ∨ rel obj T₃ T₁) ∧ (rel obj Tβ‚‚ T₃) ∧ T₃.to_partition.colg c = T₁.to_partition.colg c ∧ c ∈ pivot_col T₃ obj := rel.rec_on' h begin assume T r c' hT hc' hr, by_cases hcc : c = c', { subst hcc, exact or.inr ⟨T, or.inl rfl, rel.pivot hT hc' hr, rfl, hc'⟩ }, { simp [colg_swap_of_ne _ hcc] } end (Ξ» T₁ Tβ‚‚ r c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂, ih₁₂.elim (Ξ» ih₁₂, ihp₁.elim (Ξ» ihp₁, or.inl (ih₁₂.trans ihp₁)) (Ξ» ⟨T₃, hTβ‚ƒβŸ©, or.inr ⟨T₃, hT₃.1.elim (Ξ» h, h.symm β–Έ or.inr hrel₁₂) (Ξ» h, or.inr $ h.trans hrel₁₂), hT₃.2.1, hT₃.2.2.1.trans ih₁₂.symm, hT₃.2.2.2⟩)) (Ξ» ⟨T₃, hTβ‚ƒβŸ©, or.inr ⟨T₃, hT₃.1, hrelp₁.trans hT₃.2.1, hT₃.2.2⟩)) lemma rowg_eq_or_exists_mem_pivot_row {T₁ Tβ‚‚ : tableau m n} (h : rel obj Tβ‚‚ T₁) (r : fin m) : T₁.to_partition.rowg r = Tβ‚‚.to_partition.rowg r ∨ βˆƒ (T₃ : tableau m n) c, (T₃ = T₁ ∨ rel obj T₃ T₁) ∧ (rel obj Tβ‚‚ T₃) ∧ T₃.to_partition.rowg r = T₁.to_partition.rowg r ∧ c ∈ pivot_col T₃ obj ∧ r ∈ pivot_row T₃ obj c := rel.rec_on' h begin assume T r' c hT hc hr', by_cases hrr : r = r', { subst hrr, exact or.inr ⟨T, c, or.inl rfl, rel.pivot hT hc hr', rfl, hc, hr'⟩ }, { simp [rowg_swap_of_ne _ hrr] } end (Ξ» T₁ Tβ‚‚ r c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂, ih₁₂.elim (Ξ» ih₁₂, ihp₁.elim (Ξ» ihp₁, or.inl $ ih₁₂.trans ihp₁) (Ξ» ⟨T₃, c', hTβ‚ƒβŸ©, or.inr ⟨T₃, c', hT₃.1.elim (Ξ» h, h.symm β–Έ or.inr hrel₁₂) (Ξ» h, or.inr $ h.trans hrel₁₂), hT₃.2.1, ih₁₂.symm β–Έ hT₃.2.2.1, hT₃.2.2.2⟩)) (Ξ» ⟨T₃, c', hTβ‚ƒβŸ©, or.inr ⟨T₃, c', hT₃.1, (rel.pivot (feasible_of_rel_left _ hrel₁₂) hc hr).trans hT₃.2.1, hT₃.2.2⟩)) lemma eq_or_rel_pivot_of_rel {T₁ Tβ‚‚ : tableau m n} (h : rel obj T₁ Tβ‚‚) : βˆ€ {r c} (hc : c ∈ pivot_col Tβ‚‚ obj) (hr : r ∈ pivot_row Tβ‚‚ obj c), T₁ = Tβ‚‚.pivot r c ∨ rel obj T₁ (Tβ‚‚.pivot r c) := rel.rec_on' h (Ξ» T r c hT hc hr r' c' hc' hr', by simp * at *) (Ξ» T₁ Tβ‚‚ r c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂ r' c' hc' hr', (ih₁₂ hc' hr').elim (Ξ» ih₁₂, or.inr $ ih₁₂ β–Έ rel.pivot (feasible_of_rel_left _ hrel₁₂) hc hr) (Ξ» ih₁₂, or.inr $ (rel.pivot (feasible_of_rel_left _ hrel₁₂) hc hr).trans ih₁₂)) lemma exists_mem_pivot_col_of_mem_pivot_row {T : tableau m n} (hrelTT : rel obj T T) {r c} (hc : c ∈ pivot_col T obj) (hr : r ∈ pivot_row T obj c) : βˆƒ (T' : tableau m n), c ∈ pivot_col T' obj ∧ T'.to_partition.colg c = T.to_partition.rowg r ∧ rel obj T' T ∧ rel obj T T' := have hrelTTp : rel obj T (T.pivot r c), from (eq_or_rel_pivot_of_rel _ hrelTT hc hr).elim (Ξ» h, h β–Έ hrelTT ) id, let ⟨T', hT'⟩ := (colg_eq_or_exists_mem_pivot_col obj hrelTTp).resolve_left (show (T.pivot r c).to_partition.colg c β‰  T.to_partition.colg c, by simp) in ⟨T', hT'.2.2.2, by simp [hT'.2.2.1], hT'.1.elim (Ξ» h, h.symm β–Έ rel.pivot (feasible_of_rel_left _ hrelTT) hc hr) (Ξ» h, h.trans $ rel.pivot (feasible_of_rel_left _ hrelTT) hc hr), hT'.2.1⟩ lemma exists_mem_pivot_col_of_rowg_ne {T T' : tableau m n} (hrelTT' : rel obj T T') {r : fin m} (hrelT'T : rel obj T' T) (hrow : T.to_partition.rowg r β‰  T'.to_partition.rowg r) : βˆƒ (T₃ : tableau m n) c, c ∈ pivot_col T₃ obj ∧ T₃.to_partition.colg c = T.to_partition.rowg r ∧ rel obj T₃ T ∧ rel obj T T₃ := let ⟨T₃, c, hT₃, hrelT₃T, hrow₃, hc, hr⟩ := (rowg_eq_or_exists_mem_pivot_row obj hrelT'T _).resolve_left hrow in let ⟨Tβ‚„, hTβ‚„βŸ© := exists_mem_pivot_col_of_mem_pivot_row obj (show rel obj T₃ T₃, from hT₃.elim (Ξ» h, h.symm β–Έ hrelTT'.trans hrelT'T) (Ξ» h, h.trans $ hrelTT'.trans hrelT₃T)) hc hr in ⟨Tβ‚„, c, hTβ‚„.1, hTβ‚„.2.1.trans hrow₃, hTβ‚„.2.2.1.trans $ hT₃.elim (Ξ» h, h.symm β–Έ hrelTT'.trans hrelT'T) (Ξ» h, h.trans $ hrelTT'.trans hrelT'T), hrelTT'.trans (hrelT₃T.trans hTβ‚„.2.2.2)⟩ lemma const_obj_le_of_rel {T₁ Tβ‚‚ : tableau m n} (h : rel obj T₁ Tβ‚‚) : Tβ‚‚.const obj 0 ≀ T₁.const obj 0 := rel.rec_on' h (Ξ» T r c hT hc hr, have hr' : _ := pivot_row_spec hr, simplex_const_obj_le hT (by tauto) (by tauto)) (Ξ» _ _ _ _ _ _ _ _ h₁ hβ‚‚, le_trans hβ‚‚ h₁) lemma const_obj_eq_of_rel_of_rel {T₁ Tβ‚‚ : tableau m n} (h₁₂ : rel obj T₁ Tβ‚‚) (h₂₁ : rel obj Tβ‚‚ T₁) : T₁.const obj 0 = Tβ‚‚.const obj 0 := le_antisymm (const_obj_le_of_rel _ h₂₁) (const_obj_le_of_rel _ h₁₂) lemma const_eq_const_of_const_obj_eq {T₁ Tβ‚‚ : tableau m n} (h₁₂ : rel obj T₁ Tβ‚‚) : βˆ€ (hobj : T₁.const obj 0 = Tβ‚‚.const obj 0) (i : fin m), T₁.const i 0 = Tβ‚‚.const i 0 := rel.rec_on' h₁₂ (Ξ» T r c hfT hc hr hobj i, have hr0 : T.const r 0 = 0, from const_eq_zero_of_const_obj_eq hfT (ne_zero_of_mem_pivot_col hc) (ne_zero_of_mem_pivot_row hr) (pivot_row_spec hr).1 hobj, if hir : i = r then by simp [hir, hr0] else by simp [const_pivot_of_ne _ hir, hr0]) (Ξ» T₁ Tβ‚‚ r c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂ hobj i, have hobjp : (pivot T₁ r c).const obj 0 = T₁.const obj 0, from le_antisymm (hobj.symm β–Έ const_obj_le_of_rel _ hrel₁₂) (const_obj_le_of_rel _ hrelp₁), by rw [ihp₁ hobjp, ih₁₂ (hobjp.symm.trans hobj)]) lemma const_eq_zero_of_rowg_ne_of_rel_self {T T' : tableau m n} (hrelTT' : rel obj T T') (hrelT'T : rel obj T' T) (i : fin m) (hrow : T.to_partition.rowg i β‰  T'.to_partition.rowg i) : T.const i 0 = 0 := let ⟨T₃, c, hT₃₁, hT'₃, hrow₃, hc, hi⟩ := (rowg_eq_or_exists_mem_pivot_row obj hrelT'T _).resolve_left hrow in have T₃.const i 0 = 0, from const_eq_zero_of_const_obj_eq (feasible_of_rel_right _ hT'₃) (ne_zero_of_mem_pivot_col hc) (ne_zero_of_mem_pivot_row hi) (pivot_row_spec hi).1 (const_obj_eq_of_rel_of_rel _ (rel.pivot (feasible_of_rel_right _ hT'₃) hc hi) ((eq_or_rel_pivot_of_rel _ hT'₃ hc hi).elim (Ξ» h, h β–Έ hT₃₁.elim (Ξ» h, h.symm β–Έ hrelTT') (Ξ» h, h.trans hrelTT')) (Ξ» hrelT'p, hT₃₁.elim (Ξ» h, h.symm β–Έ hrelTT'.trans (h β–Έ hrelT'p)) (Ξ» h, h.trans $ hrelTT'.trans hrelT'p)))), have hobj : T₃.const obj 0 = T.const obj 0, from hT₃₁.elim (Ξ» h, h β–Έ rfl) (Ξ» h, const_obj_eq_of_rel_of_rel _ h (hrelTT'.trans hT'₃)), hT₃₁.elim (Ξ» h, h β–Έ this) (Ξ» h, const_eq_const_of_const_obj_eq obj h hobj i β–Έ this) lemma colg_mem_restricted_of_rel_self {T : tableau m n} (hrelTT : rel obj T T) {c} (hc : c ∈ pivot_col T obj) : T.to_partition.colg c ∈ T.restricted := let ⟨r, hr⟩ := exists_mem_pivot_row_of_rel obj hrelTT hc in let ⟨T', c', hT', hrelTT', hrowcol, _, hr'⟩ := (rowg_eq_or_exists_mem_pivot_row obj ((eq_or_rel_pivot_of_rel _ hrelTT hc hr).elim (Ξ» h, show rel obj T (T.pivot r c), from h β–Έ hrelTT) id) _).resolve_left (show (T.pivot r c).to_partition.rowg r β‰  T.to_partition.rowg r, by simp) in (restricted_eq_of_rel _ hrelTT').symm β–Έ by convert (pivot_row_spec hr').2.1; simp [hrowcol] lemma eq_zero_of_not_mem_restricted_of_rel_self {T : tableau m n} (hrelTT : rel obj T T) {j} (hjres : T.to_partition.colg j βˆ‰ T.restricted) (hdead : j βˆ‰ T.dead) : T.to_matrix obj j = 0 := let ⟨r, c, hc, hr⟩ := exists_mem_pivot_row_col_of_rel obj hrelTT in have hcres : T.to_partition.colg c ∈ T.restricted, from colg_mem_restricted_of_rel_self obj hrelTT hc, by_contradiction $ Ξ» h0, begin simp [pivot_col] at hc, cases h : fin.find (Ξ» c, T.to_matrix obj c β‰  0 ∧ colg (T.to_partition) c βˆ‰ T.restricted ∧ c βˆ‰ T.dead), { simp [*, fin.find_eq_none_iff] at * }, { rw h at hc, clear_aux_decl, have := (fin.find_eq_some_iff.1 h).1, simp * at * } end lemma rel.irrefl {obj : fin m} : βˆ€ (T : tableau m n), Β¬ rel obj T T := Ξ» T1 hrelT1, let ⟨rT1 , cT1, hrT1, hcT1⟩ := exists_mem_pivot_row_col_of_rel obj hrelT1 in let ⟨t, ht⟩ := finset.max_of_mem (show T1.to_partition.colg cT1 ∈ univ.filter (Ξ» v, βˆƒ (T' : tableau m n) (c : fin n), rel obj T' T' ∧ c ∈ pivot_col T' obj ∧ T'.to_partition.colg c = v), by simp only [true_and, mem_filter, mem_univ, exists_and_distrib_left]; exact ⟨T1, hrelT1, cT1, hrT1, rfl⟩) in let ⟨_, T', c', hrelTT'', hcT', hct⟩ := finset.mem_filter.1 (finset.mem_of_max ht) in have htmax : βˆ€ (s : fin (m + n)) (T : tableau m n), rel obj T T β†’ βˆ€ (j : fin n), pivot_col T obj = some j β†’ T.to_partition.colg j = s β†’ s ≀ t, by simpa using Ξ» s (h : s ∈ _), finset.le_max_of_mem h ht, let ⟨r, hrT'⟩ := exists_mem_pivot_row_of_rel obj hrelTT'' hcT' in have hrelTT''p : rel obj T' (T'.pivot r c'), from (eq_or_rel_pivot_of_rel obj hrelTT'' hcT' hrT').elim (Ξ» h, h β–Έ hrelTT'') id, let ⟨T, c, hTT', hrelT'T, hT'Tr, hc, hr⟩ := (rowg_eq_or_exists_mem_pivot_row obj hrelTT''p r).resolve_left (by simp) in have hfT' : feasible T', from feasible_of_rel_left _ hrelTT'', have hfT : feasible T, from feasible_of_rel_right _ hrelT'T, have hrelT'pT' : rel obj (T'.pivot r c') T', from rel.pivot hfT' hcT' hrT', have hrelTT' : rel obj T T', from hTT'.elim (Ξ» h, h.symm β–Έ hrelT'pT') (Ξ» h, h.trans hrelT'pT'), have hrelTT : rel obj T T, from hrelTT'.trans hrelT'T, have hc't : T.to_partition.colg c ≀ t, from htmax _ T hrelTT _ hc rfl, have hoT'T : T'.const obj 0 = T.const obj 0, from const_obj_eq_of_rel_of_rel _ hrelT'T hrelTT', have hfickle : βˆ€ i, T.to_partition.rowg i β‰  T'.to_partition.rowg i β†’ T.const i 0 = 0, from const_eq_zero_of_rowg_ne_of_rel_self obj hrelTT' hrelT'T, have hobj : T.const obj 0 = T'.const obj 0, from const_obj_eq_of_rel_of_rel _ hrelTT' hrelT'T, have hflat : T.flat = T'.flat, from flat_eq_of_rel obj hrelTT', have hrobj : T.to_partition.rowg obj = T'.to_partition.rowg obj, from rowg_obj_eq_of_rel _ hrelTT', have hs : T.to_partition.rowg r = T'.to_partition.colg c', by simpa using hT'Tr, have hc'res : T'.to_partition.colg c' ∈ T'.restricted, from hs β–Έ restricted_eq_of_rel _ hrelTT' β–Έ (pivot_row_spec hr).2.1, have hc'obj0 : 0 < T'.to_matrix obj c' ∧ c' βˆ‰ T'.dead, by simpa [hc'res] using pivot_col_spec hcT', have hcres : T.to_partition.colg c ∈ T.restricted, from colg_mem_restricted_of_rel_self obj hrelTT hc, have hcobj0 : 0 < to_matrix T obj c ∧ c βˆ‰ T.dead, by simpa [hcres] using pivot_col_spec hc, have hrc0 : T.to_matrix r c < 0, from inv_neg'.1 $ neg_of_mul_neg_left (pivot_row_spec hr).2.2.1 (le_of_lt hcobj0.1), have nonpos_of_colg_ne : βˆ€ j, T'.to_partition.colg j β‰  T.to_partition.colg j β†’ j β‰  c' β†’ T'.to_matrix obj j ≀ 0, from Ξ» j hj hjc', let ⟨T₃, hTβ‚ƒβŸ© := (colg_eq_or_exists_mem_pivot_col obj hrelTT').resolve_left hj in nonpos_of_lt_pivot_col hcT' hc'res (dead_eq_of_rel_or_eq obj hT₃.1 β–Έ (pivot_col_spec hT₃.2.2.2).2) (lt_of_le_of_ne (hct.symm β–Έ hT₃.2.2.1 β–Έ htmax _ T₃ (hT₃.1.elim (Ξ» h, h.symm β–Έ hrelTT'') (Ξ» h, h.trans (hrelT'T.trans hT₃.2.1))) _ hT₃.2.2.2 rfl) (by rwa [ne.def, T'.to_partition.injective_colg.eq_iff])), have nonpos_of_colg_eq : βˆ€ j, j β‰  c' β†’ T'.to_partition.colg j = T.to_partition.colg c β†’ T'.to_matrix obj j ≀ 0, from Ξ» j hjc' hj, if hjc : j = c then by clear_aux_decl; subst j; exact nonpos_of_lt_pivot_col hcT' hc'res (dead_eq_of_rel obj hrelTT' β–Έ hcobj0.2) (lt_of_le_of_ne (hj.symm β–Έ hct.symm β–Έ htmax _ _ hrelTT _ hc rfl) (hs β–Έ hj.symm β–Έ colg_ne_rowg _ _ _)) else let ⟨T₃, hTβ‚ƒβŸ© := (colg_eq_or_exists_mem_pivot_col obj hrelTT').resolve_left (show T'.to_partition.colg j β‰  T.to_partition.colg j, by simpa [hj, T.to_partition.injective_colg.eq_iff, eq_comm] using hjc) in nonpos_of_lt_pivot_col hcT' hc'res (dead_eq_of_rel_or_eq obj hT₃.1 β–Έ (pivot_col_spec hT₃.2.2.2).2) (lt_of_le_of_ne (hct.symm β–Έ hT₃.2.2.1 β–Έ htmax _ T₃ (hT₃.1.elim (Ξ» h, h.symm β–Έ hrelTT'') (Ξ» h, h.trans (hrelT'T.trans hT₃.2.1))) _ hT₃.2.2.2 rfl) (by rwa [ne.def, T'.to_partition.injective_colg.eq_iff])), have unique_row : βˆ€ i β‰  r, T.const i 0 = 0 β†’ T.to_partition.rowg i β‰  T'.to_partition.rowg i β†’ 0 ≀ T.to_matrix i c, from Ξ» i hir hi0 hrow, let ⟨T₃, c₃, hc₃, hrow₃, hrelT₃T, hrelTTβ‚ƒβŸ© := exists_mem_pivot_col_of_rowg_ne _ hrelTT' hrelT'T hrow in have hrelT₃T₃ : rel obj T₃ T₃, from hrelT₃T.trans hrelTT₃, nonneg_of_lt_pivot_row (by exact hcobj0.1) (by rw [← hrow₃, ← restricted_eq_of_rel _ hrelT₃T]; exact colg_mem_restricted_of_rel_self _ hrelT₃T₃ hc₃) hc hr hi0 (lt_of_le_of_ne (by rw [hs, hct, ← hrow₃]; exact htmax _ _ hrelT₃T₃ _ hc₃ rfl) (by simpa [T.to_partition.injective_rowg.eq_iff])), not_unique_row_and_unique_col obj hcobj0.1 hc'obj0.1 hrc0 hflat hs hrobj hfickle hobj nonpos_of_colg_ne nonpos_of_colg_eq unique_row noncomputable instance fintype_rel (T : tableau m n) : fintype {T' | rel obj T' T} := fintype.of_injective (Ξ» T', T'.val.to_partition) (Ξ» T₁ Tβ‚‚ h, subtype.eq $ tableau.ext (by rw [flat_eq_of_rel _ T₁.2, flat_eq_of_rel _ Tβ‚‚.2]) h (by rw [dead_eq_of_rel _ T₁.2, dead_eq_of_rel _ Tβ‚‚.2]) (by rw [restricted_eq_of_rel _ T₁.2, restricted_eq_of_rel _ Tβ‚‚.2])) lemma rel_wf (m n : β„•) (obj : fin m): well_founded (@rel m n obj) := subrelation.wf (show subrelation (@rel m n obj) (measure (Ξ» T, fintype.card {T' | rel obj T' T})), from assume T₁ Tβ‚‚ h, set.card_lt_card (set.ssubset_iff_subset_not_subset.2 ⟨λ T' hT', hT'.trans h, classical.not_forall.2 ⟨T₁, Ξ» h', rel.irrefl _ (h' h)⟩⟩)) (measure_wf (Ξ» T, fintype.card {T' | rel obj T' T})) end blands_rule @[derive _root_.decidable_eq] inductive termination : Type | while : termination | unbounded : termination | optimal : termination open termination instance : has_repr termination := ⟨λ t, termination.cases_on t "while" "unbounded" "optimal"⟩ instance : fintype termination := ⟨⟨quotient.mk [while, unbounded, optimal], dec_trivial⟩, Ξ» x, by cases x; exact dec_trivial⟩ open termination /-- The simplex algorithm -/ def simplex (w : tableau m n β†’ bool) (obj : fin m) : Ξ  (T : tableau m n) (hT : feasible T), tableau m n Γ— termination | T := Ξ» hT, cond (w T) (match pivot_col T obj, @feasible_of_mem_pivot_row_and_col _ _ _ obj hT, @rel.pivot m n obj _ hT with | none, hc, hrel := (T, optimal) | some c, hc, hrel := match pivot_row T obj c, @hc _ rfl, (Ξ» r, @hrel r c rfl) with | none, hr, hrel := (T, unbounded) | some r, hr, hrel := have wf : rel obj (pivot T r c) T, from hrel _ rfl, simplex (T.pivot r c) (hr rfl) end end) (T, while) using_well_founded {rel_tac := Ξ» _ _, `[exact ⟨_, rel_wf m n obj⟩], dec_tac := tactic.assumption} lemma simplex_pivot {w : tableau m n β†’ bool} {T : tableau m n} (hT : feasible T) (hw : w T = tt) {obj : fin m} {r : fin m} {c : fin n} (hc : c ∈ pivot_col T obj) (hr : r ∈ pivot_row T obj c) : (T.pivot r c).simplex w obj (feasible_of_mem_pivot_row_and_col hT hc hr) = T.simplex w obj hT := by conv_rhs { rw simplex }; simp [hw, show _ = _, from hr, show _ = _, from hc, simplex._match_1, simplex._match_2] lemma simplex_spec_aux (w : tableau m n β†’ bool) (obj : fin m) : Ξ  (T : tableau m n) (hT : feasible T), ((T.simplex w obj hT).2 = while ∧ w (T.simplex w obj hT).1 = ff) ∨ ((T.simplex w obj hT).2 = optimal ∧ w (T.simplex w obj hT).1 = tt ∧ pivot_col (T.simplex w obj hT).1 obj = none) ∨ ((T.simplex w obj hT).2 = unbounded ∧ w (T.simplex w obj hT).1 = tt ∧ βˆƒ c, c ∈ pivot_col (T.simplex w obj hT).1 obj ∧ pivot_row (T.simplex w obj hT).1 obj c = none) | T := Ξ» hT, begin cases hw : w T, { rw simplex, simp [hw] }, { cases hc : pivot_col T obj with c, { rw simplex, simp [hc, hw, simplex._match_1] }, { cases hr : pivot_row T obj c with r, { rw simplex, simp [hr, hc, hw, simplex._match_1, simplex._match_2] }, { rw [← simplex_pivot hT hw hc hr], exact have wf : rel obj (T.pivot r c) T, from rel.pivot hT hc hr, simplex_spec_aux _ _ } } } end using_well_founded {rel_tac := Ξ» _ _, `[exact ⟨_, rel_wf m n obj⟩], dec_tac := tactic.assumption} lemma simplex_while_eq_ff {w : tableau m n β†’ bool} {T : tableau m n} {hT : feasible T} {obj : fin m} (hw : w T = ff) : T.simplex w obj hT = (T, while) := by rw [simplex, hw]; refl lemma simplex_pivot_col_eq_none {w : tableau m n β†’ bool} {T : tableau m n} {hT : feasible T} (hw : w T = tt) {obj : fin m} (hc : pivot_col T obj = none) : T.simplex w obj hT = (T, optimal) := by rw simplex; simp [hc, hw, simplex._match_1] lemma simplex_pivot_row_eq_none {w : tableau m n β†’ bool} {T : tableau m n} {hT : feasible T} {obj : fin m} (hw : w T = tt) {c} (hc : c ∈ pivot_col T obj) (hr : pivot_row T obj c = none) : T.simplex w obj hT = (T, unbounded) := by rw simplex; simp [hw, show _ = _, from hc, hr, simplex._match_1, simplex._match_2] lemma simplex_induction (P : tableau m n β†’ Prop) (w : tableau m n β†’ bool) (obj : fin m): Ξ  {T : tableau m n} (hT : feasible T) (h0 : P T) (hpivot : βˆ€ {T' r c}, w T' = tt β†’ c ∈ pivot_col T' obj β†’ r ∈ pivot_row T' obj c β†’ feasible T' β†’ P T' β†’ P (T'.pivot r c)), P (T.simplex w obj hT).1 | T := Ξ» hT h0 hpivot, begin cases hw : w T, { rwa [simplex_while_eq_ff hw] }, { cases hc : pivot_col T obj with c, { rwa [simplex_pivot_col_eq_none hw hc] }, { cases hr : pivot_row T obj c with r, { rwa simplex_pivot_row_eq_none hw hc hr }, { rw [← simplex_pivot _ hw hc hr], exact have wf : rel obj (pivot T r c) T, from rel.pivot hT hc hr, simplex_induction (feasible_of_mem_pivot_row_and_col hT hc hr) (hpivot hw hc hr hT h0) @hpivot } } } end using_well_founded {rel_tac := Ξ» _ _, `[exact ⟨_, rel_wf m n obj⟩], dec_tac := `[tauto]} @[simp] lemma feasible_simplex {w : tableau m n β†’ bool} {T : tableau m n} {hT : feasible T} {obj : fin m} : feasible (T.simplex w obj hT).1 := simplex_induction feasible _ _ hT hT (Ξ» _ _ _ _ hc hr _ hT', feasible_of_mem_pivot_row_and_col hT' hc hr) @[simp] lemma simplex_simplex {w : tableau m n β†’ bool} {T : tableau m n} {hT : feasible T} {obj : fin m} : (T.simplex w obj hT).1.simplex w obj feasible_simplex = T.simplex w obj hT := simplex_induction (Ξ» T', βˆ€ (hT' : feasible T'), T'.simplex w obj hT' = T.simplex w obj hT) w _ _ (Ξ» _, rfl) (Ξ» T' r c hw hc hr hT' ih hpivot, by rw [simplex_pivot hT' hw hc hr, ih]) _ /-- `simplex` does not move the row variable it is trying to maximise. -/ @[simp] lemma rowg_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β†’ bool) (obj : fin m) : (T.simplex w obj hT).1.to_partition.rowg obj = T.to_partition.rowg obj := simplex_induction (Ξ» T', T'.to_partition.rowg obj = T.to_partition.rowg obj) _ _ _ rfl (Ξ» T' r c hw hc hr, by simp [rowg_swap_of_ne _ (pivot_row_spec hr).1]) @[simp] lemma colg_simplex_of_dead_aux {T : tableau m n} {hT : feasible T} {w : tableau m n β†’ bool} {obj : fin m} {c' : fin n} : c' ∈ (T.simplex w obj hT).1.dead β†’ (T.simplex w obj hT).1.to_partition.colg c' = T.to_partition.colg c' := simplex_induction (Ξ» T', c' ∈ T'.dead β†’ T'.to_partition.colg c' = T.to_partition.colg c') _ obj _ (Ξ» _, rfl) (Ξ» T' r c hw hc hr hfT' ih hdead, have c' β‰  c, from Ξ» hcc, (pivot_col_spec hc).2 (by simp * at *), by simp [colg_swap_of_ne _ this, ih hdead]) @[simp] lemma flat_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β†’ bool) (obj : fin m) : (T.simplex w obj hT).1.flat = T.flat := simplex_induction (Ξ» T', T'.flat = T.flat) w obj _ rfl (Ξ» T' r c hw hc hr hT' ih, have T'.to_matrix r c β‰  0, from Ξ» h, by simpa [h, lt_irrefl] using pivot_row_spec hr, by rw [flat_pivot this, ih]) @[simp] lemma restricted_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β†’ bool) (obj : fin m) : (T.simplex w obj hT).1.restricted = T.restricted := simplex_induction (Ξ» T', T'.restricted = T.restricted) _ _ _ rfl (by simp { contextual := tt }) @[simp] lemma dead_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β†’ bool) (obj : fin m) : (T.simplex w obj hT).1.dead = T.dead := simplex_induction (Ξ» T', T'.dead = T.dead) _ _ _ rfl (by simp { contextual := tt }) @[simp] lemma res_set_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β†’ bool) (obj : fin m) : (T.simplex w obj hT).1.res_set = T.res_set := simplex_induction (Ξ» T', T'.res_set = T.res_set) w obj _ rfl (Ξ» T' r c hw hc hr, by simp [res_set_pivot (ne_zero_of_mem_pivot_row hr)] {contextual := tt}) @[simp] lemma dead_set_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β†’ bool) (obj : fin m) : (T.simplex w obj hT).1.dead_set = T.dead_set := simplex_induction (Ξ» T', T'.dead_set = T.dead_set) w obj _ rfl (Ξ» T' r c hw hc hr, by simp [dead_set_pivot (ne_zero_of_mem_pivot_row hr) (pivot_col_spec hc).2] {contextual := tt}) @[simp] lemma sol_set_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n β†’ bool) (obj : fin m) : (T.simplex w obj hT).1.sol_set = T.sol_set := by simp [sol_set_eq_res_set_inter_dead_set] @[simp] lemma of_col_simplex_zero_mem_sol_set {w : tableau m n β†’ bool} {T : tableau m n} {hT : feasible T} {obj : fin m} : (T.simplex w obj hT).1.of_col 0 ∈ sol_set T := by rw [← sol_set_simplex, of_col_zero_mem_sol_set_iff]; exact feasible_simplex @[simp] lemma of_col_simplex_rowg {w : tableau m n β†’ bool} {T : tableau m n} {hT : feasible T} {obj : fin m} (x : cvec n) : (T.simplex w obj hT).1.of_col x (T.to_partition.rowg obj) = ((T.simplex w obj hT).1.to_matrix ⬝ x + (T.simplex w obj hT).1.const) obj := by rw [← of_col_rowg (T.simplex w obj hT).1 x obj, rowg_simplex] @[simp] lemma is_unbounded_above_simplex {T : tableau m n} {hT : feasible T} {w : tableau m n β†’ bool} {obj : fin m} {v : fin (m + n)} : is_unbounded_above (T.simplex w obj hT).1 v ↔ is_unbounded_above T v := by simp [is_unbounded_above] @[simp] lemma is_optimal_simplex {T : tableau m n} {hT : feasible T} {w : tableau m n β†’ bool} {obj : fin m} {x : cvec (m + n)} {v : fin (m + n)} : is_optimal (T.simplex w obj hT).1 x v ↔ is_optimal T x v := by simp [is_optimal] lemma termination_eq_while_iff {T : tableau m n} {hT : feasible T} {w : tableau m n β†’ bool} {obj : fin m} : (T.simplex w obj hT).2 = while ↔ w (T.simplex w obj hT).1 = ff := by have := simplex_spec_aux w obj T hT; finish lemma termination_eq_optimal_iff_pivot_col_eq_none {T : tableau m n} {hT : feasible T} {w : tableau m n β†’ bool} {obj : fin m} : (T.simplex w obj hT).2 = optimal ↔ w (T.simplex w obj hT).1 = tt ∧ pivot_col (T.simplex w obj hT).1 obj = none := by have := simplex_spec_aux w obj T hT; finish lemma termination_eq_unbounded_iff_pivot_row_eq_none {T : tableau m n} {hT : feasible T} {w : tableau m n β†’ bool} {obj : fin m} : (T.simplex w obj hT).2 = unbounded ↔ w (T.simplex w obj hT).1 = tt ∧ βˆƒ c, c ∈ pivot_col (T.simplex w obj hT).1 obj ∧ pivot_row (T.simplex w obj hT).1 obj c = none := by have := simplex_spec_aux w obj T hT; finish lemma termination_eq_unbounded_iff_aux {T : tableau m n} {hT : feasible T} {w : tableau m n β†’ bool} {obj : fin m} : (T.simplex w obj hT).2 = unbounded β†’ w (T.simplex w obj hT).1 = tt ∧ is_unbounded_above T (T.to_partition.rowg obj) := begin rw termination_eq_unbounded_iff_pivot_row_eq_none, rintros ⟨_, c, hc⟩, simpa * using pivot_row_eq_none feasible_simplex hc.2 hc.1 end lemma termination_eq_optimal_iff {T : tableau m n} {hT : feasible T} {w : tableau m n β†’ bool} {obj : fin m} : (T.simplex w obj hT).2 = optimal ↔ w (T.simplex w obj hT).1 = tt ∧ is_optimal T ((T.simplex w obj hT).1.of_col 0) (T.to_partition.rowg obj) := begin rw [termination_eq_optimal_iff_pivot_col_eq_none], split, { rintros ⟨_, hc⟩, simpa * using pivot_col_eq_none feasible_simplex hc }, { cases ht : (T.simplex w obj hT).2, { simp [*, termination_eq_while_iff] at * }, { cases termination_eq_unbounded_iff_aux ht, simp [*, not_optimal_of_unbounded_above right] }, { simp [*, termination_eq_optimal_iff_pivot_col_eq_none] at * } } end lemma termination_eq_unbounded_iff {T : tableau m n} {hT : feasible T} {w : tableau m n β†’ bool} {obj : fin m} : (T.simplex w obj hT).2 = unbounded ↔ w (T.simplex w obj hT).1 = tt ∧ is_unbounded_above T (T.to_partition.rowg obj) := ⟨termination_eq_unbounded_iff_aux, begin have := @not_optimal_of_unbounded_above m n (T.simplex w obj hT).1 (T.to_partition.rowg obj) ((T.simplex w obj hT).1.of_col 0), cases ht : (T.simplex w obj hT).2; simp [termination_eq_optimal_iff, termination_eq_while_iff, *] at * end⟩ end tableau
60496af9a7df5cf67e726ad85e7c948c7cffdcb0
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/free_group.lean
bf1a9fd72c30a7759a5635ad2099dbfb530f25c4
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,569
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.fintype.basic import group_theory.subgroup.basic /-! # Free groups This file defines free groups over a type. Furthermore, it is shown that the free group construction is an instance of a monad. For the result that `free_group` is the left adjoint to the forgetful functor from groups to types, see `algebra/category/Group/adjunctions`. ## Main definitions * `free_group`: the free group associated to a type `Ξ±` defined as the words over `a : Ξ± Γ— bool ` modulo the relation `a * x * x⁻¹ * b = a * b`. * `mk`: the canonical quotient map `list (Ξ± Γ— bool) β†’ free_group Ξ±`. * `of`: the canoical injection `Ξ± β†’ free_group Ξ±`. * `lift f`: the canonical group homomorphism `free_group Ξ± β†’* G` given a group `G` and a function `f : Ξ± β†’ G`. ## Main statements * `church_rosser`: The Church-Rosser theorem for word reduction (also known as Newman's diamond lemma). * `free_group_unit_equiv_int`: The free group over the one-point type is isomorphic to the integers. * The free group construction is an instance of a monad. ## Implementation details First we introduce the one step reduction relation `free_group.red.step`: `w * x * x⁻¹ * v ~> w * v`, its reflexive transitive closure `free_group.red.trans` and prove that its join is an equivalence relation. Then we introduce `free_group Ξ±` as a quotient over `free_group.red.step`. ## Tags free group, Newman's diamond lemma, Church-Rosser theorem -/ open relation universes u v w variables {Ξ± : Type u} local attribute [simp] list.append_eq_has_append namespace free_group variables {L L₁ Lβ‚‚ L₃ Lβ‚„ : list (Ξ± Γ— bool)} /-- Reduction step: `w * x * x⁻¹ * v ~> w * v` -/ inductive red.step : list (Ξ± Γ— bool) β†’ list (Ξ± Γ— bool) β†’ Prop | bnot {L₁ Lβ‚‚ x b} : red.step (L₁ ++ (x, b) :: (x, bnot b) :: Lβ‚‚) (L₁ ++ Lβ‚‚) attribute [simp] red.step.bnot /-- Reflexive-transitive closure of red.step -/ def red : list (Ξ± Γ— bool) β†’ list (Ξ± Γ— bool) β†’ Prop := refl_trans_gen red.step @[refl] lemma red.refl : red L L := refl_trans_gen.refl @[trans] lemma red.trans : red L₁ Lβ‚‚ β†’ red Lβ‚‚ L₃ β†’ red L₁ L₃ := refl_trans_gen.trans namespace red /-- Predicate asserting that word `w₁` can be reduced to `wβ‚‚` in one step, i.e. there are words `w₃ wβ‚„` and letter `x` such that `w₁ = w₃xx⁻¹wβ‚„` and `wβ‚‚ = w₃wβ‚„` -/ theorem step.length : βˆ€ {L₁ Lβ‚‚ : list (Ξ± Γ— bool)}, step L₁ Lβ‚‚ β†’ Lβ‚‚.length + 2 = L₁.length | _ _ (@red.step.bnot _ L1 L2 x b) := by rw [list.length_append, list.length_append]; refl @[simp] lemma step.bnot_rev {x b} : step (L₁ ++ (x, bnot b) :: (x, b) :: Lβ‚‚) (L₁ ++ Lβ‚‚) := by cases b; from step.bnot @[simp] lemma step.cons_bnot {x b} : red.step ((x, b) :: (x, bnot b) :: L) L := @step.bnot _ [] _ _ _ @[simp] lemma step.cons_bnot_rev {x b} : red.step ((x, bnot b) :: (x, b) :: L) L := @red.step.bnot_rev _ [] _ _ _ theorem step.append_left : βˆ€ {L₁ Lβ‚‚ L₃ : list (Ξ± Γ— bool)}, step Lβ‚‚ L₃ β†’ step (L₁ ++ Lβ‚‚) (L₁ ++ L₃) | _ _ _ red.step.bnot := by rw [← list.append_assoc, ← list.append_assoc]; constructor theorem step.cons {x} (H : red.step L₁ Lβ‚‚) : red.step (x :: L₁) (x :: Lβ‚‚) := @step.append_left _ [x] _ _ H theorem step.append_right : βˆ€ {L₁ Lβ‚‚ L₃ : list (Ξ± Γ— bool)}, step L₁ Lβ‚‚ β†’ step (L₁ ++ L₃) (Lβ‚‚ ++ L₃) | _ _ _ red.step.bnot := by simp lemma not_step_nil : Β¬ step [] L := begin generalize h' : [] = L', assume h, cases h with L₁ Lβ‚‚, simp [list.nil_eq_append_iff] at h', contradiction end lemma step.cons_left_iff {a : Ξ±} {b : bool} : step ((a, b) :: L₁) Lβ‚‚ ↔ (βˆƒL, step L₁ L ∧ Lβ‚‚ = (a, b) :: L) ∨ (L₁ = (a, bnot b)::Lβ‚‚) := begin split, { generalize hL : ((a, b) :: L₁ : list _) = L, assume h, rcases h with ⟨_ | ⟨p, s'⟩, e, a', b'⟩, { simp at hL, simp [*] }, { simp at hL, rcases hL with ⟨rfl, rfl⟩, refine or.inl ⟨s' ++ e, step.bnot, _⟩, simp } }, { assume h, rcases h with ⟨L, h, rfl⟩ | rfl, { exact step.cons h }, { exact step.cons_bnot } } end lemma not_step_singleton : βˆ€ {p : Ξ± Γ— bool}, Β¬ step [p] L | (a, b) := by simp [step.cons_left_iff, not_step_nil] lemma step.cons_cons_iff : βˆ€{p : Ξ± Γ— bool}, step (p :: L₁) (p :: Lβ‚‚) ↔ step L₁ Lβ‚‚ := by simp [step.cons_left_iff, iff_def, or_imp_distrib] {contextual := tt} lemma step.append_left_iff : βˆ€L, step (L ++ L₁) (L ++ Lβ‚‚) ↔ step L₁ Lβ‚‚ | [] := by simp | (p :: l) := by simp [step.append_left_iff l, step.cons_cons_iff] private theorem step.diamond_aux : βˆ€ {L₁ Lβ‚‚ L₃ Lβ‚„ : list (Ξ± Γ— bool)} {x1 b1 x2 b2}, L₁ ++ (x1, b1) :: (x1, bnot b1) :: Lβ‚‚ = L₃ ++ (x2, b2) :: (x2, bnot b2) :: Lβ‚„ β†’ L₁ ++ Lβ‚‚ = L₃ ++ Lβ‚„ ∨ βˆƒ Lβ‚…, red.step (L₁ ++ Lβ‚‚) Lβ‚… ∧ red.step (L₃ ++ Lβ‚„) Lβ‚… | [] _ [] _ _ _ _ _ H := by injections; subst_vars; simp | [] _ [(x3,b3)] _ _ _ _ _ H := by injections; subst_vars; simp | [(x3,b3)] _ [] _ _ _ _ _ H := by injections; subst_vars; simp | [] _ ((x3,b3)::(x4,b4)::tl) _ _ _ _ _ H := by injections; subst_vars; simp; right; exact ⟨_, red.step.bnot, red.step.cons_bnot⟩ | ((x3,b3)::(x4,b4)::tl) _ [] _ _ _ _ _ H := by injections; subst_vars; simp; right; exact ⟨_, red.step.cons_bnot, red.step.bnot⟩ | ((x3,b3)::tl) _ ((x4,b4)::tl2) _ _ _ _ _ H := let ⟨H1, H2⟩ := list.cons.inj H in match step.diamond_aux H2 with | or.inl H3 := or.inl $ by simp [H1, H3] | or.inr ⟨Lβ‚…, H3, H4⟩ := or.inr ⟨_, step.cons H3, by simpa [H1] using step.cons H4⟩ end theorem step.diamond : βˆ€ {L₁ Lβ‚‚ L₃ Lβ‚„ : list (Ξ± Γ— bool)}, red.step L₁ L₃ β†’ red.step Lβ‚‚ Lβ‚„ β†’ L₁ = Lβ‚‚ β†’ L₃ = Lβ‚„ ∨ βˆƒ Lβ‚…, red.step L₃ Lβ‚… ∧ red.step Lβ‚„ Lβ‚… | _ _ _ _ red.step.bnot red.step.bnot H := step.diamond_aux H lemma step.to_red : step L₁ Lβ‚‚ β†’ red L₁ Lβ‚‚ := refl_trans_gen.single /-- **Church-Rosser theorem** for word reduction: If `w1 w2 w3` are words such that `w1` reduces to `w2` and `w3` respectively, then there is a word `w4` such that `w2` and `w3` reduce to `w4` respectively. This is also known as Newman's diamond lemma. -/ theorem church_rosser : red L₁ Lβ‚‚ β†’ red L₁ L₃ β†’ join red Lβ‚‚ L₃ := relation.church_rosser (assume a b c hab hac, match b, c, red.step.diamond hab hac rfl with | b, _, or.inl rfl := ⟨b, by refl, by refl⟩ | b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, hcd.to_red⟩ end) lemma cons_cons {p} : red L₁ Lβ‚‚ β†’ red (p :: L₁) (p :: Lβ‚‚) := refl_trans_gen.lift (list.cons p) (assume a b, step.cons) lemma cons_cons_iff (p) : red (p :: L₁) (p :: Lβ‚‚) ↔ red L₁ Lβ‚‚ := iff.intro begin generalize eq₁ : (p :: L₁ : list _) = LL₁, generalize eqβ‚‚ : (p :: Lβ‚‚ : list _) = LLβ‚‚, assume h, induction h using relation.refl_trans_gen.head_induction_on with L₁ Lβ‚‚ h₁₂ h ih generalizing L₁ Lβ‚‚, { subst_vars, cases eqβ‚‚, constructor }, { subst_vars, cases p with a b, rw [step.cons_left_iff] at h₁₂, rcases h₁₂ with ⟨L, h₁₂, rfl⟩ | rfl, { exact (ih rfl rfl).head h₁₂ }, { exact (cons_cons h).tail step.cons_bnot_rev } } end cons_cons lemma append_append_left_iff : βˆ€L, red (L ++ L₁) (L ++ Lβ‚‚) ↔ red L₁ Lβ‚‚ | [] := iff.rfl | (p :: L) := by simp [append_append_left_iff L, cons_cons_iff] lemma append_append (h₁ : red L₁ L₃) (hβ‚‚ : red Lβ‚‚ Lβ‚„) : red (L₁ ++ Lβ‚‚) (L₃ ++ Lβ‚„) := (h₁.lift (Ξ»L, L ++ Lβ‚‚) (assume a b, step.append_right)).trans ((append_append_left_iff _).2 hβ‚‚) lemma to_append_iff : red L (L₁ ++ Lβ‚‚) ↔ (βˆƒL₃ Lβ‚„, L = L₃ ++ Lβ‚„ ∧ red L₃ L₁ ∧ red Lβ‚„ Lβ‚‚) := iff.intro begin generalize eq : L₁ ++ Lβ‚‚ = L₁₂, assume h, induction h with L' L₁₂ hLL' h ih generalizing L₁ Lβ‚‚, { exact ⟨_, _, eq.symm, by refl, by refl⟩ }, { cases h with s e a b, rcases list.append_eq_append_iff.1 eq with ⟨s', rfl, rfl⟩ | ⟨e', rfl, rfl⟩, { have : L₁ ++ (s' ++ ((a, b) :: (a, bnot b) :: e)) = (L₁ ++ s') ++ ((a, b) :: (a, bnot b) :: e), { simp }, rcases ih this with ⟨w₁, wβ‚‚, rfl, h₁, hβ‚‚βŸ©, exact ⟨w₁, wβ‚‚, rfl, h₁, hβ‚‚.tail step.bnot⟩ }, { have : (s ++ ((a, b) :: (a, bnot b) :: e')) ++ Lβ‚‚ = s ++ ((a, b) :: (a, bnot b) :: (e' ++ Lβ‚‚)), { simp }, rcases ih this with ⟨w₁, wβ‚‚, rfl, h₁, hβ‚‚βŸ©, exact ⟨w₁, wβ‚‚, rfl, h₁.tail step.bnot, hβ‚‚βŸ© }, } end (assume ⟨L₃, Lβ‚„, eq, h₃, hβ‚„βŸ©, eq.symm β–Έ append_append h₃ hβ‚„) /-- The empty word `[]` only reduces to itself. -/ theorem nil_iff : red [] L ↔ L = [] := refl_trans_gen_iff_eq (assume l, red.not_step_nil) /-- A letter only reduces to itself. -/ theorem singleton_iff {x} : red [x] L₁ ↔ L₁ = [x] := refl_trans_gen_iff_eq (assume l, not_step_singleton) /-- If `x` is a letter and `w` is a word such that `xw` reduces to the empty word, then `w` reduces to `x⁻¹` -/ theorem cons_nil_iff_singleton {x b} : red ((x, b) :: L) [] ↔ red L [(x, bnot b)] := iff.intro (assume h, have h₁ : red ((x, bnot b) :: (x, b) :: L) [(x, bnot b)], from cons_cons h, have hβ‚‚ : red ((x, bnot b) :: (x, b) :: L) L, from refl_trans_gen.single step.cons_bnot_rev, let ⟨L', h₁, hβ‚‚βŸ© := church_rosser h₁ hβ‚‚ in by rw [singleton_iff] at h₁; subst L'; assumption) (assume h, (cons_cons h).tail step.cons_bnot) theorem red_iff_irreducible {x1 b1 x2 b2} (h : (x1, b1) β‰  (x2, b2)) : red [(x1, bnot b1), (x2, b2)] L ↔ L = [(x1, bnot b1), (x2, b2)] := begin apply refl_trans_gen_iff_eq, generalize eq : [(x1, bnot b1), (x2, b2)] = L', assume L h', cases h', simp [list.cons_eq_append_iff, list.nil_eq_append_iff] at eq, rcases eq with ⟨rfl, ⟨rfl, rfl⟩, ⟨rfl, rfl⟩, rfl⟩, subst_vars, simp at h, contradiction end /-- If `x` and `y` are distinct letters and `w₁ wβ‚‚` are words such that `xw₁` reduces to `ywβ‚‚`, then `w₁` reduces to `x⁻¹ywβ‚‚`. -/ theorem inv_of_red_of_ne {x1 b1 x2 b2} (H1 : (x1, b1) β‰  (x2, b2)) (H2 : red ((x1, b1) :: L₁) ((x2, b2) :: Lβ‚‚)) : red L₁ ((x1, bnot b1) :: (x2, b2) :: Lβ‚‚) := begin have : red ((x1, b1) :: L₁) ([(x2, b2)] ++ Lβ‚‚), from H2, rcases to_append_iff.1 this with ⟨_ | ⟨p, Lβ‚ƒβŸ©, Lβ‚„, eq, h₁, hβ‚‚βŸ©, { simp [nil_iff] at h₁, contradiction }, { cases eq, show red (L₃ ++ Lβ‚„) ([(x1, bnot b1), (x2, b2)] ++ Lβ‚‚), apply append_append _ hβ‚‚, have h₁ : red ((x1, bnot b1) :: (x1, b1) :: L₃) [(x1, bnot b1), (x2, b2)], { exact cons_cons h₁ }, have hβ‚‚ : red ((x1, bnot b1) :: (x1, b1) :: L₃) L₃, { exact step.cons_bnot_rev.to_red }, rcases church_rosser h₁ hβ‚‚ with ⟨L', h₁, hβ‚‚βŸ©, rw [red_iff_irreducible H1] at h₁, rwa [h₁] at hβ‚‚ } end theorem step.sublist (H : red.step L₁ Lβ‚‚) : Lβ‚‚ <+ L₁ := by cases H; simp; constructor; constructor; refl /-- If `w₁ wβ‚‚` are words such that `w₁` reduces to `wβ‚‚`, then `wβ‚‚` is a sublist of `w₁`. -/ theorem sublist : red L₁ Lβ‚‚ β†’ Lβ‚‚ <+ L₁ := refl_trans_gen_of_transitive_reflexive (Ξ»l, list.sublist.refl l) (Ξ»a b c hab hbc, list.sublist.trans hbc hab) (Ξ»a b, red.step.sublist) theorem sizeof_of_step : βˆ€ {L₁ Lβ‚‚ : list (Ξ± Γ— bool)}, step L₁ Lβ‚‚ β†’ Lβ‚‚.sizeof < L₁.sizeof | _ _ (@step.bnot _ L1 L2 x b) := begin induction L1 with hd tl ih, case list.nil { dsimp [list.sizeof], have H : 1 + sizeof (x, b) + (1 + sizeof (x, bnot b) + list.sizeof L2) = (list.sizeof L2 + 1) + (sizeof (x, b) + sizeof (x, bnot b) + 1), { ac_refl }, rw H, exact nat.le_add_right _ _ }, case list.cons { dsimp [list.sizeof], exact nat.add_lt_add_left ih _ } end theorem length (h : red L₁ Lβ‚‚) : βˆƒ n, L₁.length = Lβ‚‚.length + 2 * n := begin induction h with Lβ‚‚ L₃ h₁₂ h₂₃ ih, { exact ⟨0, rfl⟩ }, { rcases ih with ⟨n, eq⟩, existsi (1 + n), simp [mul_add, eq, (step.length h₂₃).symm, add_assoc] } end theorem antisymm (h₁₂ : red L₁ Lβ‚‚) : red Lβ‚‚ L₁ β†’ L₁ = Lβ‚‚ := match L₁, h₁₂.cases_head with | _, or.inl rfl := assume h, rfl | L₁, or.inr ⟨L₃, h₁₃, hβ‚ƒβ‚‚βŸ© := assume h₂₁, let ⟨n, eq⟩ := length (h₃₂.trans h₂₁) in have list.length L₃ + 0 = list.length L₃ + (2 * n + 2), by simpa [(step.length h₁₃).symm, add_comm, add_assoc] using eq, (nat.no_confusion $ nat.add_left_cancel this) end end red theorem equivalence_join_red : equivalence (join (@red Ξ±)) := equivalence_join_refl_trans_gen $ assume a b c hab hac, (match b, c, red.step.diamond hab hac rfl with | b, _, or.inl rfl := ⟨b, by refl, by refl⟩ | b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, refl_trans_gen.single hcd⟩ end) theorem join_red_of_step (h : red.step L₁ Lβ‚‚) : join red L₁ Lβ‚‚ := join_of_single reflexive_refl_trans_gen h.to_red theorem eqv_gen_step_iff_join_red : eqv_gen red.step L₁ Lβ‚‚ ↔ join red L₁ Lβ‚‚ := iff.intro (assume h, have eqv_gen (join red) L₁ Lβ‚‚ := h.mono (assume a b, join_red_of_step), equivalence_join_red.eqv_gen_iff.1 this) (join_of_equivalence (eqv_gen.is_equivalence _) $ assume a b, refl_trans_gen_of_equivalence (eqv_gen.is_equivalence _) eqv_gen.rel) end free_group /-- The free group over a type, i.e. the words formed by the elements of the type and their formal inverses, quotient by one step reduction. -/ def free_group (Ξ± : Type u) : Type u := quot $ @free_group.red.step Ξ± namespace free_group variables {Ξ±} {L L₁ Lβ‚‚ L₃ Lβ‚„ : list (Ξ± Γ— bool)} /-- The canonical map from `list (Ξ± Γ— bool)` to the free group on `Ξ±`. -/ def mk (L) : free_group Ξ± := quot.mk red.step L @[simp] lemma quot_mk_eq_mk : quot.mk red.step L = mk L := rfl @[simp] lemma quot_lift_mk (Ξ² : Type v) (f : list (Ξ± Γ— bool) β†’ Ξ²) (H : βˆ€ L₁ Lβ‚‚, red.step L₁ Lβ‚‚ β†’ f L₁ = f Lβ‚‚) : quot.lift f H (mk L) = f L := rfl @[simp] lemma quot_lift_on_mk (Ξ² : Type v) (f : list (Ξ± Γ— bool) β†’ Ξ²) (H : βˆ€ L₁ Lβ‚‚, red.step L₁ Lβ‚‚ β†’ f L₁ = f Lβ‚‚) : quot.lift_on (mk L) f H = f L := rfl instance : has_one (free_group Ξ±) := ⟨mk []⟩ lemma one_eq_mk : (1 : free_group Ξ±) = mk [] := rfl instance : inhabited (free_group Ξ±) := ⟨1⟩ instance : has_mul (free_group Ξ±) := ⟨λ x y, quot.lift_on x (Ξ» L₁, quot.lift_on y (Ξ» Lβ‚‚, mk $ L₁ ++ Lβ‚‚) (Ξ» Lβ‚‚ L₃ H, quot.sound $ red.step.append_left H)) (Ξ» L₁ Lβ‚‚ H, quot.induction_on y $ Ξ» L₃, quot.sound $ red.step.append_right H)⟩ @[simp] lemma mul_mk : mk L₁ * mk Lβ‚‚ = mk (L₁ ++ Lβ‚‚) := rfl instance : has_inv (free_group Ξ±) := ⟨λx, quot.lift_on x (Ξ» L, mk (L.map $ Ξ» x : Ξ± Γ— bool, (x.1, bnot x.2)).reverse) (assume a b h, quot.sound $ by cases h; simp)⟩ @[simp] lemma inv_mk : (mk L)⁻¹ = mk (L.map $ Ξ» x : Ξ± Γ— bool, (x.1, bnot x.2)).reverse := rfl instance : group (free_group Ξ±) := { mul := (*), one := 1, inv := has_inv.inv, mul_assoc := by rintros ⟨Lβ‚βŸ© ⟨Lβ‚‚βŸ© ⟨Lβ‚ƒβŸ©; simp, one_mul := by rintros ⟨L⟩; refl, mul_one := by rintros ⟨L⟩; simp [one_eq_mk], mul_left_inv := by rintros ⟨L⟩; exact (list.rec_on L rfl $ Ξ» ⟨x, b⟩ tl ih, eq.trans (quot.sound $ by simp [one_eq_mk]) ih) } /-- `of` is the canonical injection from the type to the free group over that type by sending each element to the equivalence class of the letter that is the element. -/ def of (x : Ξ±) : free_group Ξ± := mk [(x, tt)] theorem red.exact : mk L₁ = mk Lβ‚‚ ↔ join red L₁ Lβ‚‚ := calc (mk L₁ = mk Lβ‚‚) ↔ eqv_gen red.step L₁ Lβ‚‚ : iff.intro (quot.exact _) quot.eqv_gen_sound ... ↔ join red L₁ Lβ‚‚ : eqv_gen_step_iff_join_red /-- The canonical injection from the type to the free group is an injection. -/ theorem of_injective : function.injective (@of Ξ±) := Ξ» _ _ H, let ⟨L₁, hx, hy⟩ := red.exact.1 H in by simp [red.singleton_iff] at hx hy; cc section lift variables {Ξ² : Type v} [group Ξ²] (f : Ξ± β†’ Ξ²) {x y : free_group Ξ±} /-- Given `f : Ξ± β†’ Ξ²` with `Ξ²` a group, the canonical map `list (Ξ± Γ— bool) β†’ Ξ²` -/ def lift.aux : list (Ξ± Γ— bool) β†’ Ξ² := Ξ» L, list.prod $ L.map $ Ξ» x, cond x.2 (f x.1) (f x.1)⁻¹ theorem red.step.lift {f : Ξ± β†’ Ξ²} (H : red.step L₁ Lβ‚‚) : lift.aux f L₁ = lift.aux f Lβ‚‚ := by cases H with _ _ _ b; cases b; simp [lift.aux] /-- If `Ξ²` is a group, then any function from `Ξ±` to `Ξ²` extends uniquely to a group homomorphism from the free group over `Ξ±` to `Ξ²` -/ @[simps symm_apply] def lift : (Ξ± β†’ Ξ²) ≃ (free_group Ξ± β†’* Ξ²) := { to_fun := Ξ» f, monoid_hom.mk' (quot.lift (lift.aux f) $ Ξ» L₁ Lβ‚‚, red.step.lift) $ begin rintros ⟨Lβ‚βŸ© ⟨Lβ‚‚βŸ©, simp [lift.aux], end, inv_fun := Ξ» g, g ∘ of, left_inv := Ξ» f, one_mul _, right_inv := Ξ» g, monoid_hom.ext $ begin rintros ⟨L⟩, apply list.rec_on L, { exact g.map_one.symm, }, { rintros ⟨x, _ | _⟩ t (ih : _ = g (mk t)), { show _ = g ((of x)⁻¹ * mk t), simpa [lift.aux] using ih }, { show _ = g (of x * mk t), simpa [lift.aux] using ih }, }, end } variable {f} @[simp] lemma lift.mk : lift f (mk L) = list.prod (L.map $ Ξ» x, cond x.2 (f x.1) (f x.1)⁻¹) := rfl @[simp] lemma lift.of {x} : lift f (of x) = f x := one_mul _ theorem lift.unique (g : free_group Ξ± β†’* Ξ²) (hg : βˆ€ x, g (of x) = f x) : βˆ€{x}, g x = lift f x := monoid_hom.congr_fun $ (lift.symm_apply_eq).mp (funext hg : g ∘ of = f) /-- Two homomorphisms out of a free group are equal if they are equal on generators. See note [partially-applied ext lemmas]. -/ @[ext] lemma ext_hom {G : Type*} [group G] (f g : free_group Ξ± β†’* G) (h : βˆ€ a, f (of a) = g (of a)) : f = g := lift.symm.injective $ funext h theorem lift.of_eq (x : free_group Ξ±) : lift of x = x := monoid_hom.congr_fun (lift.apply_symm_apply (monoid_hom.id _)) x theorem lift.range_subset {s : subgroup Ξ²} (H : set.range f βŠ† s) : set.range (lift f) βŠ† s := by rintros _ ⟨⟨L⟩, rfl⟩; exact list.rec_on L s.one_mem (Ξ» ⟨x, b⟩ tl ih, bool.rec_on b (by simp at ih ⊒; from s.mul_mem (s.inv_mem $ H ⟨x, rfl⟩) ih) (by simp at ih ⊒; from s.mul_mem (H ⟨x, rfl⟩) ih)) theorem closure_subset {G : Type*} [group G] {s : set G} {t : subgroup G} (h : s βŠ† t) : subgroup.closure s ≀ t := begin simp only [h, subgroup.closure_le], end theorem lift.range_eq_closure : set.range (lift f) = subgroup.closure (set.range f) := set.subset.antisymm (lift.range_subset subgroup.subset_closure) begin suffices : (subgroup.closure (set.range f)) ≀ monoid_hom.range (lift f), simpa, rw subgroup.closure_le, rintros y ⟨x, hx⟩, exact ⟨of x, by simpa⟩ end end lift section map variables {Ξ² : Type v} (f : Ξ± β†’ Ξ²) {x y : free_group Ξ±} /-- Given `f : Ξ± β†’ Ξ²`, the canonical map `list (Ξ± Γ— bool) β†’ list (Ξ² Γ— bool)`. -/ def map.aux (L : list (Ξ± Γ— bool)) : list (Ξ² Γ— bool) := L.map $ Ξ» x, (f x.1, x.2) /-- Any function from `Ξ±` to `Ξ²` extends uniquely to a group homomorphism from the free group over `Ξ±` to the free group over `Ξ²`. Note that this is the bare function; for the group homomorphism use `map`. -/ def map.to_fun (x : free_group Ξ±) : free_group Ξ² := x.lift_on (Ξ» L, mk $ map.aux f L) $ Ξ» L₁ Lβ‚‚ H, quot.sound $ by cases H; simp [map.aux] /-- Any function from `Ξ±` to `Ξ²` extends uniquely to a group homomorphism from the free group ver `Ξ±` to the free group over `Ξ²`. -/ def map : free_group Ξ± β†’* free_group Ξ² := monoid_hom.mk' (map.to_fun f) begin rintros ⟨Lβ‚βŸ© ⟨Lβ‚‚βŸ©, simp [map.to_fun, map.aux] end --by rintros ⟨Lβ‚βŸ© ⟨Lβ‚‚βŸ©; simp [map, map.aux] variable {f} @[simp] lemma map.mk : map f (mk L) = mk (L.map (Ξ» x, (f x.1, x.2))) := rfl @[simp] lemma map.id : map id x = x := have H1 : (Ξ» (x : Ξ± Γ— bool), x) = id := rfl, by rcases x with ⟨L⟩; simp [H1] @[simp] lemma map.id' : map (Ξ» z, z) x = x := map.id theorem map.comp {Ξ³ : Type w} {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ³} {x} : map g (map f x) = map (g ∘ f) x := by rcases x with ⟨L⟩; simp @[simp] lemma map.of {x} : map f (of x) = of (f x) := rfl theorem map.unique (g : free_group Ξ± β†’* free_group Ξ²) (hg : βˆ€ x, g (of x) = of (f x)) : βˆ€{x}, g x = map f x := by rintros ⟨L⟩; exact list.rec_on L g.map_one (Ξ» ⟨x, b⟩ t (ih : g (mk t) = map f (mk t)), bool.rec_on b (show g ((of x)⁻¹ * mk t) = map f ((of x)⁻¹ * mk t), by simp [g.map_mul, g.map_inv, hg, ih]) (show g (of x * mk t) = map f (of x * mk t), by simp [g.map_mul, hg, ih])) /-- Equivalent types give rise to equivalent free groups. -/ def free_group_congr {Ξ± Ξ²} (e : Ξ± ≃ Ξ²) : free_group Ξ± ≃ free_group Ξ² := ⟨map e, map e.symm, Ξ» x, by simp [function.comp, map.comp], Ξ» x, by simp [function.comp, map.comp]⟩ theorem map_eq_lift : map f x = lift (of ∘ f) x := eq.symm $ map.unique _ $ Ξ» x, by simp end map section prod variables [group Ξ±] (x y : free_group Ξ±) /-- If `Ξ±` is a group, then any function from `Ξ±` to `Ξ±` extends uniquely to a homomorphism from the free group over `Ξ±` to `Ξ±`. This is the multiplicative version of `sum`. -/ def prod : free_group Ξ± β†’* Ξ± := lift id variables {x y} @[simp] lemma prod_mk : prod (mk L) = list.prod (L.map $ Ξ» x, cond x.2 x.1 x.1⁻¹) := rfl @[simp] lemma prod.of {x : Ξ±} : prod (of x) = x := lift.of lemma prod.unique (g : free_group Ξ± β†’* Ξ±) (hg : βˆ€ x, g (of x) = x) {x} : g x = prod x := lift.unique g hg end prod theorem lift_eq_prod_map {Ξ² : Type v} [group Ξ²] {f : Ξ± β†’ Ξ²} {x} : lift f x = prod (map f x) := begin rw ←lift.unique (prod.comp (map f)), { refl }, { simp } end section sum variables [add_group Ξ±] (x y : free_group Ξ±) /-- If `Ξ±` is a group, then any function from `Ξ±` to `Ξ±` extends uniquely to a homomorphism from the free group over `Ξ±` to `Ξ±`. This is the additive version of `prod`. -/ def sum : Ξ± := @prod (multiplicative _) _ x variables {x y} @[simp] lemma sum_mk : sum (mk L) = list.sum (L.map $ Ξ» x, cond x.2 x.1 (-x.1)) := rfl @[simp] lemma sum.of {x : Ξ±} : sum (of x) = x := prod.of -- note: there are no bundled homs with different notation in the domain and codomain, so we copy -- these manually @[simp] lemma sum.map_mul : sum (x * y) = sum x + sum y := (@prod (multiplicative _) _).map_mul _ _ @[simp] lemma sum.map_one : sum (1:free_group Ξ±) = 0 := (@prod (multiplicative _) _).map_one @[simp] lemma sum.map_inv : sum x⁻¹ = -sum x := (@prod (multiplicative _) _).map_inv _ end sum /-- The bijection between the free group on the empty type, and a type with one element. -/ def free_group_empty_equiv_unit : free_group empty ≃ unit := { to_fun := Ξ» _, (), inv_fun := Ξ» _, 1, left_inv := by rintros ⟨_ | ⟨⟨⟨⟩, _⟩, _⟩⟩; refl, right_inv := Ξ» ⟨⟩, rfl } /-- The bijection between the free group on a singleton, and the integers. -/ def free_group_unit_equiv_int : free_group unit ≃ β„€ := { to_fun := Ξ» x, sum begin revert x, apply monoid_hom.to_fun, apply map (Ξ» _, (1 : β„€)), end, inv_fun := Ξ» x, of () ^ x, left_inv := begin rintros ⟨L⟩, refine list.rec_on L rfl _, exact (Ξ» ⟨⟨⟩, b⟩ tl ih, by cases b; simp [zpow_add] at ih ⊒; rw ih; refl), end, right_inv := Ξ» x, int.induction_on x (by simp) (Ξ» i ih, by simp at ih; simp [zpow_add, ih]) (Ξ» i ih, by simp at ih; simp [zpow_add, ih, sub_eq_add_neg, -int.add_neg_one]) } section category variables {Ξ² : Type u} instance : monad free_group.{u} := { pure := Ξ» Ξ±, of, map := Ξ» Ξ± Ξ² f, (map f), bind := Ξ» Ξ± Ξ² x f, lift f x } @[elab_as_eliminator] protected theorem induction_on {C : free_group Ξ± β†’ Prop} (z : free_group Ξ±) (C1 : C 1) (Cp : βˆ€ x, C $ pure x) (Ci : βˆ€ x, C (pure x) β†’ C (pure x)⁻¹) (Cm : βˆ€ x y, C x β†’ C y β†’ C (x * y)) : C z := quot.induction_on z $ Ξ» L, list.rec_on L C1 $ Ξ» ⟨x, b⟩ tl ih, bool.rec_on b (Cm _ _ (Ci _ $ Cp x) ih) (Cm _ _ (Cp x) ih) @[simp] lemma map_pure (f : Ξ± β†’ Ξ²) (x : Ξ±) : f <$> (pure x : free_group Ξ±) = pure (f x) := map.of @[simp] lemma map_one (f : Ξ± β†’ Ξ²) : f <$> (1 : free_group Ξ±) = 1 := (map f).map_one @[simp] lemma map_mul (f : Ξ± β†’ Ξ²) (x y : free_group Ξ±) : f <$> (x * y) = f <$> x * f <$> y := (map f).map_mul x y @[simp] lemma map_inv (f : Ξ± β†’ Ξ²) (x : free_group Ξ±) : f <$> (x⁻¹) = (f <$> x)⁻¹ := (map f).map_inv x @[simp] lemma pure_bind (f : Ξ± β†’ free_group Ξ²) (x) : pure x >>= f = f x := lift.of @[simp] lemma one_bind (f : Ξ± β†’ free_group Ξ²) : 1 >>= f = 1 := (lift f).map_one @[simp] lemma mul_bind (f : Ξ± β†’ free_group Ξ²) (x y : free_group Ξ±) : x * y >>= f = (x >>= f) * (y >>= f) := (lift f).map_mul _ _ @[simp] lemma inv_bind (f : Ξ± β†’ free_group Ξ²) (x : free_group Ξ±) : x⁻¹ >>= f = (x >>= f)⁻¹ := (lift f).map_inv _ instance : is_lawful_monad free_group.{u} := { id_map := Ξ» Ξ± x, free_group.induction_on x (map_one id) (Ξ» x, map_pure id x) (Ξ» x ih, by rw [map_inv, ih]) (Ξ» x y ihx ihy, by rw [map_mul, ihx, ihy]), pure_bind := Ξ» Ξ± Ξ² x f, pure_bind f x, bind_assoc := Ξ» Ξ± Ξ² Ξ³ x f g, free_group.induction_on x (by iterate 3 { rw one_bind }) (Ξ» x, by iterate 2 { rw pure_bind }) (Ξ» x ih, by iterate 3 { rw inv_bind }; rw ih) (Ξ» x y ihx ihy, by iterate 3 { rw mul_bind }; rw [ihx, ihy]), bind_pure_comp_eq_map := Ξ» Ξ± Ξ² f x, free_group.induction_on x (by rw [one_bind, map_one]) (Ξ» x, by rw [pure_bind, map_pure]) (Ξ» x ih, by rw [inv_bind, map_inv, ih]) (Ξ» x y ihx ihy, by rw [mul_bind, map_mul, ihx, ihy]) } end category section reduce variable [decidable_eq Ξ±] /-- The maximal reduction of a word. It is computable iff `Ξ±` has decidable equality. -/ def reduce (L : list (Ξ± Γ— bool)) : list (Ξ± Γ— bool) := list.rec_on L [] $ Ξ» hd1 tl1 ih, list.cases_on ih [hd1] $ Ξ» hd2 tl2, if hd1.1 = hd2.1 ∧ hd1.2 = bnot hd2.2 then tl2 else hd1 :: hd2 :: tl2 @[simp] lemma reduce.cons (x) : reduce (x :: L) = list.cases_on (reduce L) [x] (Ξ» hd tl, if x.1 = hd.1 ∧ x.2 = bnot hd.2 then tl else x :: hd :: tl) := rfl /-- The first theorem that characterises the function `reduce`: a word reduces to its maximal reduction. -/ theorem reduce.red : red L (reduce L) := begin induction L with hd1 tl1 ih, case list.nil { constructor }, case list.cons { dsimp, revert ih, generalize htl : reduce tl1 = TL, intro ih, cases TL with hd2 tl2, case list.nil { exact red.cons_cons ih }, case list.cons { dsimp, by_cases h : hd1.fst = hd2.fst ∧ hd1.snd = bnot (hd2.snd), { rw [if_pos h], transitivity, { exact red.cons_cons ih }, { cases hd1, cases hd2, cases h, dsimp at *, subst_vars, exact red.step.cons_bnot_rev.to_red } }, { rw [if_neg h], exact red.cons_cons ih } } } end theorem reduce.not {p : Prop} : βˆ€ {L₁ Lβ‚‚ L₃ : list (Ξ± Γ— bool)} {x b}, reduce L₁ = Lβ‚‚ ++ (x, b) :: (x, bnot b) :: L₃ β†’ p | [] L2 L3 _ _ := Ξ» h, by cases L2; injections | ((x,b)::L1) L2 L3 x' b' := begin dsimp, cases r : reduce L1, { dsimp, intro h, have := congr_arg list.length h, simp [-add_comm] at this, exact absurd this dec_trivial }, cases hd with y c, by_cases x = y ∧ b = bnot c; simp [h]; intro H, { rw H at r, exact @reduce.not L1 ((y,c)::L2) L3 x' b' r }, rcases L2 with _|⟨a, L2⟩, { injections, subst_vars, simp at h, cc }, { refine @reduce.not L1 L2 L3 x' b' _, injection H with _ H, rw [r, H], refl } end /-- The second theorem that characterises the function `reduce`: the maximal reduction of a word only reduces to itself. -/ theorem reduce.min (H : red (reduce L₁) Lβ‚‚) : reduce L₁ = Lβ‚‚ := begin induction H with L1 L' L2 H1 H2 ih, { refl }, { cases H1 with L4 L5 x b, exact reduce.not H2 } end /-- `reduce` is idempotent, i.e. the maximal reduction of the maximal reduction of a word is the maximal reduction of the word. -/ theorem reduce.idem : reduce (reduce L) = reduce L := eq.symm $ reduce.min reduce.red theorem reduce.step.eq (H : red.step L₁ Lβ‚‚) : reduce L₁ = reduce Lβ‚‚ := let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (reduce.red.head H) in (reduce.min HR13).trans (reduce.min HR23).symm /-- If a word reduces to another word, then they have a common maximal reduction. -/ theorem reduce.eq_of_red (H : red L₁ Lβ‚‚) : reduce L₁ = reduce Lβ‚‚ := let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (red.trans H reduce.red) in (reduce.min HR13).trans (reduce.min HR23).symm /-- If two words correspond to the same element in the free group, then they have a common maximal reduction. This is the proof that the function that sends an element of the free group to its maximal reduction is well-defined. -/ theorem reduce.sound (H : mk L₁ = mk Lβ‚‚) : reduce L₁ = reduce Lβ‚‚ := let ⟨L₃, H13, H23⟩ := red.exact.1 H in (reduce.eq_of_red H13).trans (reduce.eq_of_red H23).symm /-- If two words have a common maximal reduction, then they correspond to the same element in the free group. -/ theorem reduce.exact (H : reduce L₁ = reduce Lβ‚‚) : mk L₁ = mk Lβ‚‚ := red.exact.2 ⟨reduce Lβ‚‚, H β–Έ reduce.red, reduce.red⟩ /-- A word and its maximal reduction correspond to the same element of the free group. -/ theorem reduce.self : mk (reduce L) = mk L := reduce.exact reduce.idem /-- If words `w₁ wβ‚‚` are such that `w₁` reduces to `wβ‚‚`, then `wβ‚‚` reduces to the maximal reduction of `w₁`. -/ theorem reduce.rev (H : red L₁ Lβ‚‚) : red Lβ‚‚ (reduce L₁) := (reduce.eq_of_red H).symm β–Έ reduce.red /-- The function that sends an element of the free group to its maximal reduction. -/ def to_word : free_group Ξ± β†’ list (Ξ± Γ— bool) := quot.lift reduce $ Ξ» L₁ Lβ‚‚ H, reduce.step.eq H lemma to_word.mk : βˆ€{x : free_group Ξ±}, mk (to_word x) = x := by rintros ⟨L⟩; exact reduce.self lemma to_word.inj : βˆ€(x y : free_group Ξ±), to_word x = to_word y β†’ x = y := by rintros ⟨Lβ‚βŸ© ⟨Lβ‚‚βŸ©; exact reduce.exact /-- Constructive Church-Rosser theorem (compare `church_rosser`). -/ def reduce.church_rosser (H12 : red L₁ Lβ‚‚) (H13 : red L₁ L₃) : { Lβ‚„ // red Lβ‚‚ Lβ‚„ ∧ red L₃ Lβ‚„ } := ⟨reduce L₁, reduce.rev H12, reduce.rev H13⟩ instance : decidable_eq (free_group Ξ±) := function.injective.decidable_eq to_word.inj instance red.decidable_rel : decidable_rel (@red Ξ±) | [] [] := is_true red.refl | [] (hd2::tl2) := is_false $ Ξ» H, list.no_confusion (red.nil_iff.1 H) | ((x,b)::tl) [] := match red.decidable_rel tl [(x, bnot b)] with | is_true H := is_true $ red.trans (red.cons_cons H) $ (@red.step.bnot _ [] [] _ _).to_red | is_false H := is_false $ Ξ» H2, H $ red.cons_nil_iff_singleton.1 H2 end | ((x1,b1)::tl1) ((x2,b2)::tl2) := if h : (x1, b1) = (x2, b2) then match red.decidable_rel tl1 tl2 with | is_true H := is_true $ h β–Έ red.cons_cons H | is_false H := is_false $ Ξ» H2, H $ h β–Έ (red.cons_cons_iff _).1 $ H2 end else match red.decidable_rel tl1 ((x1,bnot b1)::(x2,b2)::tl2) with | is_true H := is_true $ (red.cons_cons H).tail red.step.cons_bnot | is_false H := is_false $ Ξ» H2, H $ red.inv_of_red_of_ne h H2 end /-- A list containing every word that `w₁` reduces to. -/ def red.enum (L₁ : list (Ξ± Γ— bool)) : list (list (Ξ± Γ— bool)) := list.filter (Ξ» Lβ‚‚, red L₁ Lβ‚‚) (list.sublists L₁) theorem red.enum.sound (H : Lβ‚‚ ∈ red.enum L₁) : red L₁ Lβ‚‚ := list.of_mem_filter H theorem red.enum.complete (H : red L₁ Lβ‚‚) : Lβ‚‚ ∈ red.enum L₁ := list.mem_filter_of_mem (list.mem_sublists.2 $ red.sublist H) H instance : fintype { Lβ‚‚ // red L₁ Lβ‚‚ } := fintype.subtype (list.to_finset $ red.enum L₁) $ Ξ» Lβ‚‚, ⟨λ H, red.enum.sound $ list.mem_to_finset.1 H, Ξ» H, list.mem_to_finset.2 $ red.enum.complete H⟩ end reduce end free_group
262761bbddcb09f450f6ee7db10931049972c53a
46125763b4dbf50619e8846a1371029346f4c3db
/src/measure_theory/outer_measure.lean
c565884aa0b996361af55c9adfd12bd3ce55aa71
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
19,690
lean
/- Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl, Mario Carneiro Outer measures -- overapproximations of measures -/ import algebra.big_operators algebra.module topology.instances.ennreal analysis.specific_limits measure_theory.measurable_space noncomputable theory open set lattice finset function filter encodable open_locale classical namespace measure_theory structure outer_measure (Ξ± : Type*) := (measure_of : set Ξ± β†’ ennreal) (empty : measure_of βˆ… = 0) (mono : βˆ€{s₁ sβ‚‚}, s₁ βŠ† sβ‚‚ β†’ measure_of s₁ ≀ measure_of sβ‚‚) (Union_nat : βˆ€(s:β„• β†’ set Ξ±), measure_of (⋃i, s i) ≀ (βˆ‘i, measure_of (s i))) namespace outer_measure instance {Ξ±} : has_coe_to_fun (outer_measure Ξ±) := ⟨_, Ξ» m, m.measure_of⟩ section basic variables {Ξ± : Type*} {ms : set (outer_measure Ξ±)} {m : outer_measure Ξ±} @[simp] theorem empty' (m : outer_measure Ξ±) : m βˆ… = 0 := m.empty theorem mono' (m : outer_measure Ξ±) {s₁ sβ‚‚} (h : s₁ βŠ† sβ‚‚) : m s₁ ≀ m sβ‚‚ := m.mono h theorem Union_aux (m : set Ξ± β†’ ennreal) (m0 : m βˆ… = 0) {Ξ²} [encodable Ξ²] (s : Ξ² β†’ set Ξ±) : (βˆ‘ b, m (s b)) = βˆ‘ i, m (⋃ b ∈ decode2 Ξ² i, s b) := begin have H : βˆ€ n, m (⋃ b ∈ decode2 Ξ² n, s b) β‰  0 β†’ (decode2 Ξ² n).is_some, { intros n h, cases decode2 Ξ² n with b, { exact (h (by simp [m0])).elim }, { exact rfl } }, refine tsum_eq_tsum_of_ne_zero_bij (Ξ» n h, option.get (H n h)) _ _ _, { intros m n hm hn e, have := mem_decode2.1 (option.get_mem (H n hn)), rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨encode b, _, _⟩, { convert h, simp [ext_iff, encodek2] }, { exact option.get_of_mem _ (encodek2 _) } }, { intros n h, transitivity, swap, rw [show decode2 Ξ² n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end protected theorem Union (m : outer_measure Ξ±) {Ξ²} [encodable Ξ²] (s : Ξ² β†’ set Ξ±) : m (⋃i, s i) ≀ (βˆ‘i, m (s i)) := by rw [Union_decode2, Union_aux _ m.empty' s]; exact m.Union_nat _ lemma Union_null (m : outer_measure Ξ±) {Ξ²} [encodable Ξ²] {s : Ξ² β†’ set Ξ±} (h : βˆ€ i, m (s i) = 0) : m (⋃i, s i) = 0 := by simpa [h] using m.Union s protected lemma union (m : outer_measure Ξ±) (s₁ sβ‚‚ : set Ξ±) : m (s₁ βˆͺ sβ‚‚) ≀ m s₁ + m sβ‚‚ := begin convert m.Union (Ξ» b, cond b s₁ sβ‚‚), { simp [union_eq_Union] }, { rw tsum_fintype, change _ = _ + _, simp } end lemma union_null (m : outer_measure Ξ±) {s₁ sβ‚‚ : set Ξ±} (h₁ : m s₁ = 0) (hβ‚‚ : m sβ‚‚ = 0) : m (s₁ βˆͺ sβ‚‚) = 0 := by simpa [h₁, hβ‚‚] using m.union s₁ sβ‚‚ @[ext] lemma ext : βˆ€{μ₁ ΞΌβ‚‚ : outer_measure Ξ±}, (βˆ€s, μ₁ s = ΞΌβ‚‚ s) β†’ μ₁ = ΞΌβ‚‚ | ⟨m₁, e₁, _, uβ‚βŸ© ⟨mβ‚‚, eβ‚‚, _, uβ‚‚βŸ© h := by congr; exact funext h instance : has_zero (outer_measure Ξ±) := ⟨{ measure_of := Ξ»_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, zero_le _ }⟩ @[simp] theorem zero_apply (s : set Ξ±) : (0 : outer_measure Ξ±) s = 0 := rfl instance : inhabited (outer_measure Ξ±) := ⟨0⟩ instance : has_add (outer_measure Ξ±) := ⟨λm₁ mβ‚‚, { measure_of := Ξ»s, m₁ s + mβ‚‚ s, empty := show m₁ βˆ… + mβ‚‚ βˆ… = 0, by simp [outer_measure.empty], mono := assume s₁ sβ‚‚ h, add_le_add' (m₁.mono h) (mβ‚‚.mono h), Union_nat := assume s, calc m₁ (⋃i, s i) + mβ‚‚ (⋃i, s i) ≀ (βˆ‘i, m₁ (s i)) + (βˆ‘i, mβ‚‚ (s i)) : add_le_add' (m₁.Union_nat s) (mβ‚‚.Union_nat s) ... = _ : ennreal.tsum_add.symm}⟩ @[simp] theorem add_apply (m₁ mβ‚‚ : outer_measure Ξ±) (s : set Ξ±) : (m₁ + mβ‚‚) s = m₁ s + mβ‚‚ s := rfl instance add_comm_monoid : add_comm_monoid (outer_measure Ξ±) := { zero := 0, add := (+), add_comm := assume a b, ext $ assume s, add_comm _ _, add_assoc := assume a b c, ext $ assume s, add_assoc _ _ _, add_zero := assume a, ext $ assume s, add_zero _, zero_add := assume a, ext $ assume s, zero_add _ } instance : has_bot (outer_measure Ξ±) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure Ξ±) := { le := Ξ»m₁ mβ‚‚, βˆ€s, m₁ s ≀ mβ‚‚ s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, zero_le _ } section supremum instance : has_Sup (outer_measure Ξ±) := ⟨λms, { measure_of := Ξ»s, ⨆m:ms, m.val s, empty := le_zero_iff_eq.1 $ supr_le $ Ξ» ⟨m, h⟩, le_of_eq m.empty, mono := assume s₁ sβ‚‚ hs, supr_le_supr $ assume ⟨m, hm⟩, m.mono hs, Union_nat := assume f, supr_le $ assume m, calc m.val (⋃i, f i) ≀ (βˆ‘ (i : β„•), m.val (f i)) : m.val.Union_nat _ ... ≀ (βˆ‘i, ⨆m:ms, m.val (f i)) : ennreal.tsum_le_tsum $ assume i, le_supr (Ξ»m:ms, m.val (f i)) m }⟩ private lemma le_Sup (hm : m ∈ ms) : m ≀ Sup ms := Ξ» s, le_supr (Ξ»m:ms, m.val s) ⟨m, hm⟩ private lemma Sup_le (hm : βˆ€m' ∈ ms, m' ≀ m) : Sup ms ≀ m := Ξ» s, (supr_le $ assume ⟨m', h'⟩, (hm m' h') s) instance : has_Inf (outer_measure Ξ±) := ⟨λs, Sup {m | βˆ€m'∈s, m ≀ m'}⟩ private lemma Inf_le (hm : m ∈ ms) : Inf ms ≀ m := Sup_le $ assume m' h', h' _ hm private lemma le_Inf (hm : βˆ€m' ∈ ms, m ≀ m') : m ≀ Inf ms := le_Sup hm instance : complete_lattice (outer_measure Ξ±) := { top := Sup univ, le_top := assume a, le_Sup (mem_univ a), Sup := Sup, Sup_le := assume s m, Sup_le, le_Sup := assume s m, le_Sup, Inf := Inf, Inf_le := assume s m, Inf_le, le_Inf := assume s m, le_Inf, sup := Ξ»a b, Sup {a, b}, le_sup_left := assume a b, le_Sup $ by simp, le_sup_right := assume a b, le_Sup $ by simp, sup_le := assume a b c ha hb, Sup_le $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, inf := Ξ»a b, Inf {a, b}, inf_le_left := assume a b, Inf_le $ by simp, inf_le_right := assume a b, Inf_le $ by simp, le_inf := assume a b c ha hb, le_Inf $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, .. outer_measure.order_bot } @[simp] theorem Sup_apply (ms : set (outer_measure Ξ±)) (s : set Ξ±) : (Sup ms) s = ⨆ m : ms, m s := rfl @[simp] theorem supr_apply {ΞΉ} (f : ΞΉ β†’ outer_measure Ξ±) (s : set Ξ±) : (⨆ i : ΞΉ, f i) s = ⨆ i, f i s := le_antisymm (supr_le $ Ξ» ⟨_, i, rfl⟩, le_supr _ i) (supr_le $ Ξ» i, le_supr (Ξ» (m : {a : outer_measure Ξ± // βˆƒ i, f i = a}), m.1 s) ⟨f i, i, rfl⟩) @[simp] theorem sup_apply (m₁ mβ‚‚ : outer_measure Ξ±) (s : set Ξ±) : (m₁ βŠ” mβ‚‚) s = m₁ s βŠ” mβ‚‚ s := by have := supr_apply (Ξ» b, cond b m₁ mβ‚‚) s; rwa [supr_bool_eq, supr_bool_eq] at this end supremum def map {Ξ²} (f : Ξ± β†’ Ξ²) (m : outer_measure Ξ±) : outer_measure Ξ² := { measure_of := Ξ»s, m (f ⁻¹' s), empty := m.empty, mono := Ξ» s t h, m.mono (preimage_mono h), Union_nat := Ξ» s, by rw [preimage_Union]; exact m.Union_nat (Ξ» i, f ⁻¹' s i) } @[simp] theorem map_apply {Ξ²} (f : Ξ± β†’ Ξ²) (m : outer_measure Ξ±) (s : set Ξ²) : map f m s = m (f ⁻¹' s) := rfl @[simp] theorem map_id (m : outer_measure Ξ±) : map id m = m := ext $ Ξ» s, rfl @[simp] theorem map_map {Ξ² Ξ³} (f : Ξ± β†’ Ξ²) (g : Ξ² β†’ Ξ³) (m : outer_measure Ξ±) : map g (map f m) = map (g ∘ f) m := ext $ Ξ» s, rfl instance : functor outer_measure := {map := Ξ» Ξ± Ξ², map} instance : is_lawful_functor outer_measure := { id_map := Ξ» Ξ±, map_id, comp_map := Ξ» Ξ± Ξ² Ξ³ f g m, (map_map f g m).symm } /-- The dirac outer measure. -/ def dirac (a : Ξ±) : outer_measure Ξ± := { measure_of := Ξ»s, ⨆ h : a ∈ s, 1, empty := by simp, mono := Ξ» s t h, supr_le_supr2 (Ξ» h', ⟨h h', le_refl _⟩), Union_nat := Ξ» s, supr_le $ Ξ» h, let ⟨i, h⟩ := mem_Union.1 h in le_trans (by exact le_supr _ h) (ennreal.le_tsum i) } @[simp] theorem dirac_apply (a : Ξ±) (s : set Ξ±) : dirac a s = ⨆ h : a ∈ s, 1 := rfl def sum {ΞΉ} (f : ΞΉ β†’ outer_measure Ξ±) : outer_measure Ξ± := { measure_of := Ξ»s, βˆ‘ i, f i s, empty := by simp, mono := Ξ» s t h, ennreal.tsum_le_tsum (Ξ» i, (f i).mono' h), Union_nat := Ξ» s, by rw ennreal.tsum_comm; exact ennreal.tsum_le_tsum (Ξ» i, (f i).Union_nat _) } @[simp] theorem sum_apply {ΞΉ} (f : ΞΉ β†’ outer_measure Ξ±) (s : set Ξ±) : sum f s = βˆ‘ i, f i s := rfl instance : has_scalar ennreal (outer_measure Ξ±) := ⟨λ a m, { measure_of := Ξ»s, a * m s, empty := by simp, mono := Ξ» s t h, canonically_ordered_semiring.mul_le_mul (le_refl _) (m.mono' h), Union_nat := Ξ» s, by rw ennreal.mul_tsum; exact canonically_ordered_semiring.mul_le_mul (le_refl _) (m.Union_nat _) }⟩ @[simp] theorem smul_apply (a : ennreal) (m : outer_measure Ξ±) (s : set Ξ±) : (a β€’ m) s = a * m s := rfl instance : semimodule ennreal (outer_measure Ξ±) := { smul_add := Ξ» a m₁ mβ‚‚, ext $ Ξ» s, mul_add _ _ _, add_smul := Ξ» a b m, ext $ Ξ» s, add_mul _ _ _, mul_smul := Ξ» a b m, ext $ Ξ» s, mul_assoc _ _ _, one_smul := Ξ» m, ext $ Ξ» s, one_mul _, zero_smul := Ξ» m, ext $ Ξ» s, zero_mul _, smul_zero := Ξ» a, ext $ Ξ» s, mul_zero _, ..outer_measure.has_scalar } theorem smul_dirac_apply (a : ennreal) (b : Ξ±) (s : set Ξ±) : (a β€’ dirac b) s = ⨆ h : b ∈ s, a := by by_cases b ∈ s; simp [h] theorem top_apply {s : set Ξ±} (h : s.nonempty) : (⊀ : outer_measure Ξ±) s = ⊀ := let ⟨a, as⟩ := h in top_unique $ le_supr_of_le ⟨(⊀ : ennreal) β€’ dirac a, trivial⟩ $ by simp [smul_dirac_apply, as] end basic section of_function set_option eqn_compiler.zeta true /-- Given any function `m` assigning measures to sets satisying `m βˆ… = 0`, there is a unique maximal outer measure `ΞΌ` satisfying `ΞΌ s ≀ m s` for all `s : set Ξ±`. -/ protected def of_function {Ξ± : Type*} (m : set Ξ± β†’ ennreal) (m_empty : m βˆ… = 0) : outer_measure Ξ± := let ΞΌ := Ξ»s, β¨…{f : β„• β†’ set Ξ±} (h : s βŠ† ⋃i, f i), βˆ‘i, m (f i) in { measure_of := ΞΌ, empty := le_antisymm (infi_le_of_le (Ξ»_, βˆ…) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ sβ‚‚ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ begin assume Ξ΅ hΞ΅ (hb : (βˆ‘i, ΞΌ (s i)) < ⊀), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hΞ΅) β„• with ⟨Ρ', hΞ΅', hl⟩, refine le_trans _ (add_le_add_left' (le_of_lt hl)), rw ← ennreal.tsum_add, choose f hf using show βˆ€i, βˆƒf:β„• β†’ set Ξ±, s i βŠ† (⋃i, f i) ∧ (βˆ‘i, m (f i)) < ΞΌ (s i) + Ξ΅' i, { intro, have : ΞΌ (s i) < ΞΌ (s i) + Ξ΅' i := ennreal.lt_add_right (lt_of_le_of_lt (by apply ennreal.le_tsum) hb) (by simpa using hΞ΅' i), simpa [ΞΌ, infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ Ξ» i, le_of_lt (hf i).2), rw [← ennreal.tsum_prod, ← tsum_equiv equiv.nat_prod_nat_equiv_nat.symm], swap, {apply_instance}, refine infi_le_of_le _ (infi_le _ _), exact Union_subset (Ξ» i, subset.trans (hf i).1 $ Union_subset $ Ξ» j, subset.trans (by simp) $ subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)), end } theorem of_function_le {Ξ± : Type*} (m : set Ξ± β†’ ennreal) (m_empty s) : outer_measure.of_function m m_empty s ≀ m s := let f : β„• β†’ set Ξ± := Ξ»i, nat.rec_on i s (Ξ»n s, βˆ…) in infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $ calc (βˆ‘i, m (f i)) = ({0} : finset β„•).sum (Ξ»i, m (f i)) : tsum_eq_sum $ by intro i; cases i; simp [m_empty] ... = m s : by simp; refl theorem le_of_function {Ξ± : Type*} {m m_empty} {ΞΌ : outer_measure Ξ±} : ΞΌ ≀ outer_measure.of_function m m_empty ↔ βˆ€ s, ΞΌ s ≀ m s := ⟨λ H s, le_trans (H _) (of_function_le _ _ _), Ξ» H s, le_infi $ Ξ» f, le_infi $ Ξ» hs, le_trans (ΞΌ.mono hs) $ le_trans (ΞΌ.Union f) $ ennreal.tsum_le_tsum $ Ξ» i, H _⟩ end of_function section caratheodory_measurable universe u parameters {Ξ± : Type u} (m : outer_measure Ξ±) include m local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ sβ‚‚ : set Ξ±} private def C (s : set Ξ±) := βˆ€t, m t = m (t ∩ s) + m (t \ s) private lemma C_iff_le {s : set Ξ±} : C s ↔ βˆ€t, m (t ∩ s) + m (t \ s) ≀ m t := forall_congr $ Ξ» t, le_antisymm_iff.trans $ and_iff_right $ by convert m.union _ _; rw inter_union_diff t s @[simp] private lemma C_empty : C βˆ… := by simp [C, m.empty, diff_empty] private lemma C_compl : C s₁ β†’ C (- s₁) := by simp [C, diff_eq, add_comm] @[simp] private lemma C_compl_iff : C (- s) ↔ C s := ⟨λ h, by simpa using C_compl m h, C_compl⟩ private lemma C_union (h₁ : C s₁) (hβ‚‚ : C sβ‚‚) : C (s₁ βˆͺ sβ‚‚) := Ξ» t, begin rw [h₁ t, hβ‚‚ (t ∩ s₁), hβ‚‚ (t \ s₁), h₁ (t ∩ (s₁ βˆͺ sβ‚‚)), inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁, inter_eq_self_of_subset_right (set.subset_union_left _ _), union_diff_left, hβ‚‚ (t ∩ s₁)], simp [diff_eq] end private lemma measure_inter_union (h : s₁ ∩ sβ‚‚ βŠ† βˆ…) (h₁ : C s₁) {t : set Ξ±} : m (t ∩ (s₁ βˆͺ sβ‚‚)) = m (t ∩ s₁) + m (t ∩ sβ‚‚) := by rw [h₁, set.inter_assoc, set.union_inter_cancel_left, inter_diff_assoc, union_diff_cancel_left h] private lemma C_Union_lt {s : β„• β†’ set Ξ±} : βˆ€{n:β„•}, (βˆ€i<n, C (s i)) β†’ C (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := by rw Union_lt_succ; exact C_union m (h n (le_refl (n + 1))) (C_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) private lemma C_inter (h₁ : C s₁) (hβ‚‚ : C sβ‚‚) : C (s₁ ∩ sβ‚‚) := by rw [← C_compl_iff, compl_inter]; from C_union _ (C_compl _ h₁) (C_compl _ hβ‚‚) private lemma C_sum {s : β„• β†’ set Ξ±} (h : βˆ€i, C (s i)) (hd : pairwise (disjoint on s)) {t : set Ξ±} : βˆ€ {n}, (finset.range n).sum (Ξ»i, m (t ∩ s i)) = m (t ∩ ⋃i<n, s i) | 0 := by simp [nat.not_lt_zero, m.empty] | (nat.succ n) := begin simp [Union_lt_succ, range_succ], rw [measure_inter_union m _ (h n), C_sum], intro a, simpa [range_succ] using Ξ» h₁ i hi hβ‚‚, hd _ _ (ne_of_gt hi) ⟨h₁, hβ‚‚βŸ© end private lemma C_Union_nat {s : β„• β†’ set Ξ±} (h : βˆ€i, C (s i)) (hd : pairwise (disjoint on s)) : C (⋃i, s i) := C_iff_le.2 $ Ξ» t, begin have hp : m (t ∩ ⋃i, s i) ≀ (⨆n, m (t ∩ ⋃i<n, s i)), { convert m.Union (Ξ» i, t ∩ s i), { rw inter_Union }, { simp [ennreal.tsum_eq_supr_nat, C_sum m h hd] } }, refine le_trans (add_le_add_right' hp) _, rw ennreal.supr_add, refine supr_le (Ξ» n, le_trans (add_le_add_left' _) (ge_of_eq (C_Union_lt m (Ξ» i _, h i) _))), refine m.mono (diff_subset_diff_right _), exact bUnion_subset (Ξ» i _, subset_Union _ i), end private lemma f_Union {s : β„• β†’ set Ξ±} (h : βˆ€i, C (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = βˆ‘i, m (s i) := begin refine le_antisymm (m.Union_nat s) _, rw ennreal.tsum_eq_supr_nat, refine supr_le (Ξ» n, _), have := @C_sum _ m _ h hd univ n, simp at this, simp [this], exact m.mono (bUnion_subset (Ξ» i _, subset_Union _ i)), end private def caratheodory_dynkin : measurable_space.dynkin_system Ξ± := { has := C, has_empty := C_empty, has_compl := assume s, C_compl, has_Union_nat := assume f hf hn, C_Union_nat hn hf } /-- Given an outer measure `ΞΌ`, the Caratheodory measurable space is defined such that `s` is measurable if `βˆ€t, ΞΌ t = ΞΌ (t ∩ s) + ΞΌ (t \ s)`. -/ protected def caratheodory : measurable_space Ξ± := caratheodory_dynkin.to_measurable_space $ assume s₁ sβ‚‚, C_inter lemma is_caratheodory {s : set Ξ±} : caratheodory.is_measurable s ↔ βˆ€t, m t = m (t ∩ s) + m (t \ s) := iff.rfl lemma is_caratheodory_le {s : set Ξ±} : caratheodory.is_measurable s ↔ βˆ€t, m (t ∩ s) + m (t \ s) ≀ m t := C_iff_le protected lemma Union_eq_of_caratheodory {s : β„• β†’ set Ξ±} (h : βˆ€i, caratheodory.is_measurable (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = βˆ‘i, m (s i) := f_Union h hd end caratheodory_measurable variables {Ξ± : Type*} lemma caratheodory_is_measurable {m : set Ξ± β†’ ennreal} {s : set Ξ±} {hβ‚€ : m βˆ… = 0} (hs : βˆ€t, m (t ∩ s) + m (t \ s) ≀ m t) : (outer_measure.of_function m hβ‚€).caratheodory.is_measurable s := let o := (outer_measure.of_function m hβ‚€) in (is_caratheodory_le o).2 $ Ξ» t, le_infi $ Ξ» f, le_infi $ Ξ» hf, begin refine le_trans (add_le_add' (infi_le_of_le (Ξ»i, f i ∩ s) $ infi_le _ _) (infi_le_of_le (Ξ»i, f i \ s) $ infi_le _ _)) _, { rw ← Union_inter, exact inter_subset_inter_left _ hf }, { rw ← Union_diff, exact diff_subset_diff_left hf }, { rw ← ennreal.tsum_add, exact ennreal.tsum_le_tsum (Ξ» i, hs _) } end @[simp] theorem zero_caratheodory : (0 : outer_measure Ξ±).caratheodory = ⊀ := top_unique $ Ξ» s _ t, (add_zero _).symm theorem top_caratheodory : (⊀ : outer_measure Ξ±).caratheodory = ⊀ := top_unique $ assume s hs, (is_caratheodory_le _).2 $ assume t, t.eq_empty_or_nonempty.elim (Ξ» ht, by simp [ht]) (Ξ» ht, by simp only [ht, top_apply, le_top]) theorem le_add_caratheodory (m₁ mβ‚‚ : outer_measure Ξ±) : m₁.caratheodory βŠ“ mβ‚‚.caratheodory ≀ (m₁ + mβ‚‚ : outer_measure Ξ±).caratheodory := Ξ» s ⟨hs₁, hsβ‚‚βŸ© t, by simp [hs₁ t, hsβ‚‚ t, add_left_comm] theorem le_sum_caratheodory {ΞΉ} (m : ΞΉ β†’ outer_measure Ξ±) : (β¨… i, (m i).caratheodory) ≀ (sum m).caratheodory := Ξ» s h t, by simp [Ξ» i, measurable_space.is_measurable_infi.1 h i t, ennreal.tsum_add] theorem le_smul_caratheodory (a : ennreal) (m : outer_measure Ξ±) : m.caratheodory ≀ (a β€’ m).caratheodory := Ξ» s h t, by simp [h t, mul_add] @[simp] theorem dirac_caratheodory (a : Ξ±) : (dirac a).caratheodory = ⊀ := top_unique $ Ξ» s _ t, begin by_cases a ∈ t; simp [h], by_cases a ∈ s; simp [h] end section Inf_gen def Inf_gen (m : set (outer_measure Ξ±)) (s : set Ξ±) : ennreal := ⨆(h : s.nonempty), β¨… (ΞΌ : outer_measure Ξ±) (h : ΞΌ ∈ m), ΞΌ s @[simp] lemma Inf_gen_empty (m : set (outer_measure Ξ±)) : Inf_gen m βˆ… = 0 := by simp [Inf_gen, empty_not_nonempty] lemma Inf_gen_nonempty1 (m : set (outer_measure Ξ±)) (t : set Ξ±) (h : t.nonempty) : Inf_gen m t = (β¨… (ΞΌ : outer_measure Ξ±) (h : ΞΌ ∈ m), ΞΌ t) := by rw [Inf_gen, supr_pos h] lemma Inf_gen_nonempty2 (m : set (outer_measure Ξ±)) (ΞΌ) (h : ΞΌ ∈ m) (t) : Inf_gen m t = (β¨… (ΞΌ : outer_measure Ξ±) (h : ΞΌ ∈ m), ΞΌ t) := begin cases t.eq_empty_or_nonempty with ht ht, { simp [ht], refine (bot_unique $ infi_le_of_le ΞΌ $ _).symm, refine infi_le_of_le h (le_refl βŠ₯) }, { exact Inf_gen_nonempty1 m t ht } end lemma Inf_eq_of_function_Inf_gen (m : set (outer_measure Ξ±)) : Inf m = outer_measure.of_function (Inf_gen m) (Inf_gen_empty m) := begin refine le_antisymm (assume t', le_of_function.2 (assume t, _) _) (lattice.le_Inf $ assume ΞΌ hΞΌ t, le_trans (outer_measure.of_function_le _ _ _) _); cases t.eq_empty_or_nonempty with ht ht; simp [ht, Inf_gen_nonempty1], { assume ΞΌ hΞΌ, exact (show Inf m ≀ ΞΌ, from lattice.Inf_le hΞΌ) t }, { exact infi_le_of_le ΞΌ (infi_le _ hΞΌ) } end end Inf_gen end outer_measure end measure_theory
c7a4d9aa23b3fbd356248f3b58a4f38c517e2031
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/dfinsupp.lean
d00a035aa27e214f585d25f60f37c2bbaec55aac
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
32,058
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl, Kenny Lau Dependent functions with finite support (see `data/finsupp.lean`). -/ import data.finset data.set.finite algebra.big_operators algebra.module algebra.pi_instances universes u u₁ uβ‚‚ v v₁ vβ‚‚ v₃ w x y l variables (ΞΉ : Type u) (Ξ² : ΞΉ β†’ Type v) def decidable_zero_symm {Ξ³ : Type w} [has_zero Ξ³] [decidable_pred (eq (0 : Ξ³))] : decidable_pred (Ξ» x, x = (0:Ξ³)) := Ξ» x, decidable_of_iff (0 = x) eq_comm local attribute [instance] decidable_zero_symm namespace dfinsupp variable [Ξ  i, has_zero (Ξ² i)] structure pre : Type (max u v) := (to_fun : Ξ  i, Ξ² i) (pre_support : multiset ΞΉ) (zero : βˆ€ i, i ∈ pre_support ∨ to_fun i = 0) instance : setoid (pre ΞΉ Ξ²) := { r := Ξ» x y, βˆ€ i, x.to_fun i = y.to_fun i, iseqv := ⟨λ f i, rfl, Ξ» f g H i, (H i).symm, Ξ» f g h H1 H2 i, (H1 i).trans (H2 i)⟩ } end dfinsupp variable {ΞΉ} @[reducible] def dfinsupp [Ξ  i, has_zero (Ξ² i)] : Type* := quotient (dfinsupp.setoid ΞΉ Ξ²) variable {Ξ²} notation `Ξ β‚€` binders `, ` r:(scoped f, dfinsupp f) := r infix ` β†’β‚š `:25 := dfinsupp namespace dfinsupp section basic variables [Ξ  i, has_zero (Ξ² i)] variables {β₁ : ΞΉ β†’ Type v₁} {Ξ²β‚‚ : ΞΉ β†’ Type vβ‚‚} variables [Ξ  i, has_zero (β₁ i)] [Ξ  i, has_zero (Ξ²β‚‚ i)] instance : has_coe_to_fun (Ξ β‚€ i, Ξ² i) := ⟨λ _, Ξ  i, Ξ² i, Ξ» f, quotient.lift_on f pre.to_fun $ Ξ» _ _, funext⟩ instance : has_zero (Ξ β‚€ i, Ξ² i) := ⟨⟦⟨λ i, 0, βˆ…, Ξ» i, or.inr rfl⟩⟧⟩ instance : inhabited (Ξ β‚€ i, Ξ² i) := ⟨0⟩ @[simp] lemma zero_apply {i : ΞΉ} : (0 : Ξ β‚€ i, Ξ² i) i = 0 := rfl @[extensionality] lemma ext {f g : Ξ β‚€ i, Ξ² i} (H : βˆ€ i, f i = g i) : f = g := quotient.induction_onβ‚‚ f g (Ξ» _ _ H, quotient.sound H) H /-- The composition of `f : β₁ β†’ Ξ²β‚‚` and `g : Ξ β‚€ i, β₁ i` is `map_range f hf g : Ξ β‚€ i, Ξ²β‚‚ i`, well defined when `f 0 = 0`. -/ def map_range (f : Ξ  i, β₁ i β†’ Ξ²β‚‚ i) (hf : βˆ€ i, f i 0 = 0) (g : Ξ β‚€ i, β₁ i) : Ξ β‚€ i, Ξ²β‚‚ i := quotient.lift_on g (Ξ» x, ⟦(⟨λ i, f i (x.1 i), x.2, Ξ» i, or.cases_on (x.3 i) or.inl $ Ξ» H, or.inr $ by rw [H, hf]⟩ : pre ΞΉ Ξ²β‚‚)⟧) $ Ξ» x y H, quotient.sound $ Ξ» i, by simp only [H i] @[simp] lemma map_range_apply {f : Ξ  i, β₁ i β†’ Ξ²β‚‚ i} {hf : βˆ€ i, f i 0 = 0} {g : Ξ β‚€ i, β₁ i} {i : ΞΉ} : map_range f hf g i = f i (g i) := quotient.induction_on g $ Ξ» x, rfl def zip_with (f : Ξ  i, β₁ i β†’ Ξ²β‚‚ i β†’ Ξ² i) (hf : βˆ€ i, f i 0 0 = 0) (g₁ : Ξ β‚€ i, β₁ i) (gβ‚‚ : Ξ β‚€ i, Ξ²β‚‚ i) : (Ξ β‚€ i, Ξ² i) := begin refine quotient.lift_onβ‚‚ g₁ gβ‚‚ (Ξ» x y, ⟦(⟨λ i, f i (x.1 i) (y.1 i), x.2 + y.2, Ξ» i, _⟩ : pre ΞΉ Ξ²)⟧) _, { cases x.3 i with h1 h1, { left, rw multiset.mem_add, left, exact h1 }, cases y.3 i with h2 h2, { left, rw multiset.mem_add, right, exact h2 }, right, rw [h1, h2, hf] }, exact Ξ» x₁ xβ‚‚ y₁ yβ‚‚ H1 H2, quotient.sound $ Ξ» i, by simp only [H1 i, H2 i] end @[simp] lemma zip_with_apply {f : Ξ  i, β₁ i β†’ Ξ²β‚‚ i β†’ Ξ² i} {hf : βˆ€ i, f i 0 0 = 0} {g₁ : Ξ β‚€ i, β₁ i} {gβ‚‚ : Ξ β‚€ i, Ξ²β‚‚ i} {i : ΞΉ} : zip_with f hf g₁ gβ‚‚ i = f i (g₁ i) (gβ‚‚ i) := quotient.induction_onβ‚‚ g₁ gβ‚‚ $ Ξ» _ _, rfl end basic section algebra instance [Ξ  i, add_monoid (Ξ² i)] : has_add (Ξ β‚€ i, Ξ² i) := ⟨zip_with (Ξ» _, (+)) (Ξ» _, add_zero 0)⟩ @[simp] lemma add_apply [Ξ  i, add_monoid (Ξ² i)] {g₁ gβ‚‚ : Ξ β‚€ i, Ξ² i} {i : ΞΉ} : (g₁ + gβ‚‚) i = g₁ i + gβ‚‚ i := zip_with_apply instance [Ξ  i, add_monoid (Ξ² i)] : add_monoid (Ξ β‚€ i, Ξ² i) := { add_monoid . zero := 0, add := (+), add_assoc := Ξ» f g h, ext $ Ξ» i, by simp only [add_apply, add_assoc], zero_add := Ξ» f, ext $ Ξ» i, by simp only [add_apply, zero_apply, zero_add], add_zero := Ξ» f, ext $ Ξ» i, by simp only [add_apply, zero_apply, add_zero] } instance [Ξ  i, add_monoid (Ξ² i)] {i : ΞΉ} : is_add_monoid_hom (Ξ» g : Ξ β‚€ i : ΞΉ, Ξ² i, g i) := { map_add := Ξ» _ _, add_apply, map_zero := zero_apply } instance [Ξ  i, add_group (Ξ² i)] : has_neg (Ξ β‚€ i, Ξ² i) := ⟨λ f, f.map_range (Ξ» _, has_neg.neg) (Ξ» _, neg_zero)⟩ instance [Ξ  i, add_comm_monoid (Ξ² i)] : add_comm_monoid (Ξ β‚€ i, Ξ² i) := { add_comm := Ξ» f g, ext $ Ξ» i, by simp only [add_apply, add_comm], .. dfinsupp.add_monoid } @[simp] lemma neg_apply [Ξ  i, add_group (Ξ² i)] {g : Ξ β‚€ i, Ξ² i} {i : ΞΉ} : (- g) i = - g i := map_range_apply instance [Ξ  i, add_group (Ξ² i)] : add_group (Ξ β‚€ i, Ξ² i) := { add_left_neg := Ξ» f, ext $ Ξ» i, by simp only [add_apply, neg_apply, zero_apply, add_left_neg], .. dfinsupp.add_monoid, .. (infer_instance : has_neg (Ξ β‚€ i, Ξ² i)) } @[simp] lemma sub_apply [Ξ  i, add_group (Ξ² i)] {g₁ gβ‚‚ : Ξ β‚€ i, Ξ² i} {i : ΞΉ} : (g₁ - gβ‚‚) i = g₁ i - gβ‚‚ i := by rw [sub_eq_add_neg]; simp instance [Ξ  i, add_comm_group (Ξ² i)] : add_comm_group (Ξ β‚€ i, Ξ² i) := { add_comm := Ξ» f g, ext $ Ξ» i, by simp only [add_apply, add_comm], ..dfinsupp.add_group } def to_has_scalar {Ξ³ : Type w} [ring Ξ³] [Ξ  i, add_comm_group (Ξ² i)] [Ξ  i, module Ξ³ (Ξ² i)] : has_scalar Ξ³ (Ξ β‚€ i, Ξ² i) := ⟨λc v, v.map_range (Ξ» _, (β€’) c) (Ξ» _, smul_zero _)⟩ local attribute [instance] to_has_scalar @[simp] lemma smul_apply {Ξ³ : Type w} [ring Ξ³] [Ξ  i, add_comm_group (Ξ² i)] [Ξ  i, module Ξ³ (Ξ² i)] {i : ΞΉ} {b : Ξ³} {v : Ξ β‚€ i, Ξ² i} : (b β€’ v) i = b β€’ (v i) := map_range_apply def to_module {Ξ³ : Type w} [ring Ξ³] [Ξ  i, add_comm_group (Ξ² i)] [Ξ  i, module Ξ³ (Ξ² i)] : module Ξ³ (Ξ β‚€ i, Ξ² i) := module.of_core { smul_add := Ξ» c x y, ext $ Ξ» i, by simp only [add_apply, smul_apply, smul_add], add_smul := Ξ» c x y, ext $ Ξ» i, by simp only [add_apply, smul_apply, add_smul], one_smul := Ξ» x, ext $ Ξ» i, by simp only [smul_apply, one_smul], mul_smul := Ξ» r s x, ext $ Ξ» i, by simp only [smul_apply, smul_smul], .. (infer_instance : has_scalar Ξ³ (Ξ β‚€ i, Ξ² i)) } end algebra section filter_and_subtype_domain /-- `filter p f` is the function which is `f i` if `p i` is true and 0 otherwise. -/ def filter [Ξ  i, has_zero (Ξ² i)] (p : ΞΉ β†’ Prop) [decidable_pred p] (f : Ξ β‚€ i, Ξ² i) : Ξ β‚€ i, Ξ² i := quotient.lift_on f (Ξ» x, ⟦(⟨λ i, if p i then x.1 i else 0, x.2, Ξ» i, or.cases_on (x.3 i) or.inl $ Ξ» H, or.inr $ by rw [H, if_t_t]⟩ : pre ΞΉ Ξ²)⟧) $ Ξ» x y H, quotient.sound $ Ξ» i, by simp only [H i] @[simp] lemma filter_apply [Ξ  i, has_zero (Ξ² i)] {p : ΞΉ β†’ Prop} [decidable_pred p] {i : ΞΉ} {f : Ξ β‚€ i, Ξ² i} : f.filter p i = if p i then f i else 0 := quotient.induction_on f $ Ξ» x, rfl @[simp] lemma filter_apply_pos [Ξ  i, has_zero (Ξ² i)] {p : ΞΉ β†’ Prop} [decidable_pred p] {f : Ξ β‚€ i, Ξ² i} {i : ΞΉ} (h : p i) : f.filter p i = f i := by simp only [filter_apply, if_pos h] @[simp] lemma filter_apply_neg [Ξ  i, has_zero (Ξ² i)] {p : ΞΉ β†’ Prop} [decidable_pred p] {f : Ξ β‚€ i, Ξ² i} {i : ΞΉ} (h : Β¬ p i) : f.filter p i = 0 := by simp only [filter_apply, if_neg h] lemma filter_pos_add_filter_neg [Ξ  i, add_monoid (Ξ² i)] {f : Ξ β‚€ i, Ξ² i} {p : ΞΉ β†’ Prop} [decidable_pred p] : f.filter p + f.filter (Ξ»i, Β¬ p i) = f := ext $ Ξ» i, by simp only [add_apply, filter_apply]; split_ifs; simp only [add_zero, zero_add] /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain [Ξ  i, has_zero (Ξ² i)] (p : ΞΉ β†’ Prop) [decidable_pred p] (f : Ξ β‚€ i, Ξ² i) : Ξ β‚€ i : subtype p, Ξ² i.1 := begin fapply quotient.lift_on f, { intro x, refine ⟦⟨λ i, x.1 i.1, (x.2.filter p).attach.map $ Ξ» j, ⟨j.1, (multiset.mem_filter.1 j.2).2⟩, _⟩⟧, refine Ξ» i, or.cases_on (x.3 i.1) (Ξ» H, _) or.inr, left, rw multiset.mem_map, refine ⟨⟨i.1, multiset.mem_filter.2 ⟨H, i.2⟩⟩, _, subtype.eta _ _⟩, apply multiset.mem_attach }, intros x y H, exact quotient.sound (Ξ» i, H i.1) end @[simp] lemma subtype_domain_zero [Ξ  i, has_zero (Ξ² i)] {p : ΞΉ β†’ Prop} [decidable_pred p] : subtype_domain p (0 : Ξ β‚€ i, Ξ² i) = 0 := rfl @[simp] lemma subtype_domain_apply [Ξ  i, has_zero (Ξ² i)] {p : ΞΉ β†’ Prop} [decidable_pred p] {i : subtype p} {v : Ξ β‚€ i, Ξ² i} : (subtype_domain p v) i = v (i.val) := quotient.induction_on v $ Ξ» x, rfl @[simp] lemma subtype_domain_add [Ξ  i, add_monoid (Ξ² i)] {p : ΞΉ β†’ Prop} [decidable_pred p] {v v' : Ξ β‚€ i, Ξ² i} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ Ξ» i, by simp only [add_apply, subtype_domain_apply] instance subtype_domain.is_add_monoid_hom [Ξ  i, add_monoid (Ξ² i)] {p : ΞΉ β†’ Prop} [decidable_pred p] : is_add_monoid_hom (subtype_domain p : (Ξ β‚€ i : ΞΉ, Ξ² i) β†’ Ξ β‚€ i : subtype p, Ξ² i) := { map_add := Ξ» _ _, subtype_domain_add, map_zero := subtype_domain_zero } @[simp] lemma subtype_domain_neg [Ξ  i, add_group (Ξ² i)] {p : ΞΉ β†’ Prop} [decidable_pred p] {v : Ξ β‚€ i, Ξ² i} : (- v).subtype_domain p = - v.subtype_domain p := ext $ Ξ» i, by simp only [neg_apply, subtype_domain_apply] @[simp] lemma subtype_domain_sub [Ξ  i, add_group (Ξ² i)] {p : ΞΉ β†’ Prop} [decidable_pred p] {v v' : Ξ β‚€ i, Ξ² i} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ Ξ» i, by simp only [sub_apply, subtype_domain_apply] end filter_and_subtype_domain variable [decidable_eq ΞΉ] section basic variable [Ξ  i, has_zero (Ξ² i)] lemma finite_supp (f : Ξ β‚€ i, Ξ² i) : set.finite {i | f i β‰  0} := quotient.induction_on f $ Ξ» x, set.finite_subset (finset.finite_to_set x.2.to_finset) $ Ξ» i H, multiset.mem_to_finset.2 $ (x.3 i).resolve_right H def mk (s : finset ΞΉ) (x : Ξ  i : (↑s : set ΞΉ), Ξ² i.1) : Ξ β‚€ i, Ξ² i := ⟦⟨λ i, if H : i ∈ s then x ⟨i, H⟩ else 0, s.1, Ξ» i, if H : i ∈ s then or.inl H else or.inr $ dif_neg H⟩⟧ @[simp] lemma mk_apply {s : finset ΞΉ} {x : Ξ  i : (↑s : set ΞΉ), Ξ² i.1} {i : ΞΉ} : (mk s x : Ξ  i, Ξ² i) i = if H : i ∈ s then x ⟨i, H⟩ else 0 := rfl theorem mk_inj (s : finset ΞΉ) : function.injective (@mk ΞΉ Ξ² _ _ s) := begin intros x y H, ext i, have h1 : (mk s x : Ξ  i, Ξ² i) i = (mk s y : Ξ  i, Ξ² i) i, {rw H}, cases i with i hi, change i ∈ s at hi, dsimp only [mk_apply, subtype.coe_mk] at h1, simpa only [dif_pos hi] using h1 end def single (i : ΞΉ) (b : Ξ² i) : Ξ β‚€ i, Ξ² i := mk (finset.singleton i) $ Ξ» j, eq.rec_on (finset.mem_singleton.1 j.2).symm b @[simp] lemma single_apply {i i' b} : (single i b : Ξ β‚€ i, Ξ² i) i' = (if h : i = i' then eq.rec_on h b else 0) := begin dsimp only [single], by_cases h : i = i', { have h1 : i' ∈ finset.singleton i, { simp only [h, finset.mem_singleton] }, simp only [mk_apply, dif_pos h, dif_pos h1] }, { have h1 : i' βˆ‰ finset.singleton i, { simp only [ne.symm h, finset.mem_singleton, not_false_iff] }, simp only [mk_apply, dif_neg h, dif_neg h1] } end @[simp] lemma single_zero {i} : (single i 0 : Ξ β‚€ i, Ξ² i) = 0 := quotient.sound $ Ξ» j, if H : j ∈ finset.singleton i then by dsimp only; rw [dif_pos H]; cases finset.mem_singleton.1 H; refl else dif_neg H @[simp] lemma single_eq_same {i b} : (single i b : Ξ β‚€ i, Ξ² i) i = b := by simp only [single_apply, dif_pos rfl] @[simp] lemma single_eq_of_ne {i i' b} (h : i β‰  i') : (single i b : Ξ β‚€ i, Ξ² i) i' = 0 := by simp only [single_apply, dif_neg h] def erase (i : ΞΉ) (f : Ξ β‚€ i, Ξ² i) : Ξ β‚€ i, Ξ² i := quotient.lift_on f (Ξ» x, ⟦(⟨λ j, if j = i then 0 else x.1 j, x.2, Ξ» j, or.cases_on (x.3 j) or.inl $ Ξ» H, or.inr $ by simp only [H, if_t_t]⟩ : pre ΞΉ Ξ²)⟧) $ Ξ» x y H, quotient.sound $ Ξ» j, if h : j = i then by simp only [if_pos h] else by simp only [if_neg h, H j] @[simp] lemma erase_apply {i j : ΞΉ} {f : Ξ β‚€ i, Ξ² i} : (f.erase i) j = if j = i then 0 else f j := quotient.induction_on f $ Ξ» x, rfl @[simp] lemma erase_same {i : ΞΉ} {f : Ξ β‚€ i, Ξ² i} : (f.erase i) i = 0 := by simp @[simp] lemma erase_ne {i i' : ΞΉ} {f : Ξ β‚€ i, Ξ² i} (h : i' β‰  i) : (f.erase i) i' = f i' := by simp [h] end basic section add_monoid variable [Ξ  i, add_monoid (Ξ² i)] @[simp] lemma single_add {i : ΞΉ} {b₁ bβ‚‚ : Ξ² i} : single i (b₁ + bβ‚‚) = single i b₁ + single i bβ‚‚ := ext $ assume i', begin by_cases h : i = i', { subst h, simp only [add_apply, single_eq_same] }, { simp only [add_apply, single_eq_of_ne h, zero_add] } end lemma single_add_erase {i : ΞΉ} {f : Ξ β‚€ i, Ξ² i} : single i (f i) + f.erase i = f := ext $ Ξ» i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, add_zero] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), zero_add] lemma erase_add_single {i : ΞΉ} {f : Ξ β‚€ i, Ξ² i} : f.erase i + single i (f i) = f := ext $ Ξ» i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, zero_add] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), add_zero] protected theorem induction {p : (Ξ β‚€ i, Ξ² i) β†’ Prop} (f : Ξ β‚€ i, Ξ² i) (h0 : p 0) (ha : βˆ€i b (f : Ξ β‚€ i, Ξ² i), f i = 0 β†’ b β‰  0 β†’ p f β†’ p (single i b + f)) : p f := begin refine quotient.induction_on f (Ξ» x, _), cases x with f s H, revert f H, apply multiset.induction_on s, { intros f H, convert h0, ext i, exact (H i).resolve_left id }, intros i s ih f H, by_cases H1 : i ∈ s, { have H2 : βˆ€ j, j ∈ s ∨ f j = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { left, rw H3, exact H1 }, { left, exact H3 } }, right, exact H2 }, have H3 : (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Ξ β‚€ i, Ξ² i) = ⟦{to_fun := f, pre_support := s, zero := H2}⟧, { exact quotient.sound (Ξ» i, rfl) }, rw H3, apply ih }, have H2 : p (erase i ⟦{to_fun := f, pre_support := i :: s, zero := H}⟧), { dsimp only [erase, quotient.lift_on_beta], have H2 : βˆ€ j, j ∈ s ∨ ite (j = i) 0 (f j) = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { right, exact if_pos H3 }, { left, exact H3 } }, right, split_ifs; [refl, exact H2] }, have H3 : (⟦{to_fun := Ξ» (j : ΞΉ), ite (j = i) 0 (f j), pre_support := i :: s, zero := _}⟧ : Ξ β‚€ i, Ξ² i) = ⟦{to_fun := Ξ» (j : ΞΉ), ite (j = i) 0 (f j), pre_support := s, zero := H2}⟧ := quotient.sound (Ξ» i, rfl), rw H3, apply ih }, have H3 : single i _ + _ = (⟦{to_fun := f, pre_support := i :: s, zero := H}⟧ : Ξ β‚€ i, Ξ² i) := single_add_erase, rw ← H3, change p (single i (f i) + _), cases classical.em (f i = 0) with h h, { rw [h, single_zero, zero_add], exact H2 }, refine ha _ _ _ _ h H2, rw erase_same end lemma inductionβ‚‚ {p : (Ξ β‚€ i, Ξ² i) β†’ Prop} (f : Ξ β‚€ i, Ξ² i) (h0 : p 0) (ha : βˆ€i b (f : Ξ β‚€ i, Ξ² i), f i = 0 β†’ b β‰  0 β†’ p f β†’ p (f + single i b)) : p f := dfinsupp.induction f h0 $ Ξ» i b f h1 h2 h3, have h4 : f + single i b = single i b + f, { ext j, by_cases H : i = j, { subst H, simp [h1] }, { simp [H] } }, eq.rec_on h4 $ ha i b f h1 h2 h3 end add_monoid @[simp] lemma mk_add [Ξ  i, add_monoid (Ξ² i)] {s : finset ΞΉ} {x y : Ξ  i : (↑s : set ΞΉ), Ξ² i.1} : mk s (x + y) = mk s x + mk s y := ext $ Ξ» i, by simp only [add_apply, mk_apply]; split_ifs; [refl, rw zero_add] @[simp] lemma mk_zero [Ξ  i, has_zero (Ξ² i)] {s : finset ΞΉ} : mk s (0 : Ξ  i : (↑s : set ΞΉ), Ξ² i.1) = 0 := ext $ Ξ» i, by simp only [mk_apply]; split_ifs; refl @[simp] lemma mk_neg [Ξ  i, add_group (Ξ² i)] {s : finset ΞΉ} {x : Ξ  i : (↑s : set ΞΉ), Ξ² i.1} : mk s (-x) = -mk s x := ext $ Ξ» i, by simp only [neg_apply, mk_apply]; split_ifs; [refl, rw neg_zero] @[simp] lemma mk_sub [Ξ  i, add_group (Ξ² i)] {s : finset ΞΉ} {x y : Ξ  i : (↑s : set ΞΉ), Ξ² i.1} : mk s (x - y) = mk s x - mk s y := ext $ Ξ» i, by simp only [sub_apply, mk_apply]; split_ifs; [refl, rw sub_zero] instance [Ξ  i, add_group (Ξ² i)] {s : finset ΞΉ} : is_add_group_hom (@mk ΞΉ Ξ² _ _ s) := ⟨λ _ _, mk_add⟩ section local attribute [instance] to_module variables (Ξ³ : Type w) [ring Ξ³] [Ξ  i, add_comm_group (Ξ² i)] [Ξ  i, module Ξ³ (Ξ² i)] include Ξ³ @[simp] lemma mk_smul {s : finset ΞΉ} {c : Ξ³} (x : Ξ  i : (↑s : set ΞΉ), Ξ² i.1) : mk s (c β€’ x) = c β€’ mk s x := ext $ Ξ» i, by simp only [smul_apply, mk_apply]; split_ifs; [refl, rw smul_zero] @[simp] lemma single_smul {i : ΞΉ} {c : Ξ³} {x : Ξ² i} : single i (c β€’ x) = c β€’ single i x := ext $ Ξ» i, by simp only [smul_apply, single_apply]; split_ifs; [cases h, rw smul_zero]; refl variable Ξ² def lmk (s : finset ΞΉ) : (Ξ  i : (↑s : set ΞΉ), Ξ² i.1) β†’β‚—[Ξ³] Ξ β‚€ i, Ξ² i := ⟨mk s, Ξ» _ _, mk_add, Ξ» c x, by rw [mk_smul Ξ³ x]⟩ def lsingle (i) : Ξ² i β†’β‚—[Ξ³] Ξ β‚€ i, Ξ² i := ⟨single i, Ξ» _ _, single_add, Ξ» _ _, single_smul _⟩ variable {Ξ²} @[simp] lemma lmk_apply {s : finset ΞΉ} {x} : lmk Ξ² Ξ³ s x = mk s x := rfl @[simp] lemma lsingle_apply {i : ΞΉ} {x : Ξ² i} : lsingle Ξ² Ξ³ i x = single i x := rfl end section support_basic variables [Ξ  i, has_zero (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] def support (f : Ξ β‚€ i, Ξ² i) : finset ΞΉ := quotient.lift_on f (Ξ» x, x.2.to_finset.filter $ Ξ» i, x.1 i β‰  0) $ begin intros x y Hxy, ext i, split, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (y.3 i).resolve_right h2, h2⟩ }, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw ← Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (x.3 i).resolve_right h2, h2⟩ }, end @[simp] theorem support_mk_subset {s : finset ΞΉ} {x : Ξ  i : (↑s : set ΞΉ), Ξ² i.1} : (mk s x).support βŠ† s := Ξ» i H, multiset.mem_to_finset.1 (finset.mem_filter.1 H).1 @[simp] theorem mem_support_to_fun (f : Ξ β‚€ i, Ξ² i) (i) : i ∈ f.support ↔ f i β‰  0 := begin refine quotient.induction_on f (Ξ» x, _), dsimp only [support, quotient.lift_on_beta], rw [finset.mem_filter, multiset.mem_to_finset], exact and_iff_right_of_imp (x.3 i).resolve_right end theorem eq_mk_support (f : Ξ β‚€ i, Ξ² i) : f = mk f.support (Ξ» i, f i.1) := by ext i; by_cases h : f i = 0; try {simp at h}; simp [h] @[simp] lemma support_zero : (0 : Ξ β‚€ i, Ξ² i).support = βˆ… := rfl @[simp] lemma mem_support_iff (f : Ξ β‚€ i, Ξ² i) : βˆ€i:ΞΉ, i ∈ f.support ↔ f i β‰  0 := f.mem_support_to_fun @[simp] lemma support_eq_empty {f : Ξ β‚€ i, Ξ² i} : f.support = βˆ… ↔ f = 0 := ⟨λ H, ext $ by simpa [finset.ext] using H, by simp {contextual:=tt}⟩ instance decidable_zero : decidable_pred (eq (0 : Ξ β‚€ i, Ξ² i)) := Ξ» f, decidable_of_iff _ $ support_eq_empty.trans eq_comm lemma support_subset_iff {s : set ΞΉ} {f : Ξ β‚€ i, Ξ² i} : ↑f.support βŠ† s ↔ (βˆ€iβˆ‰s, f i = 0) := by simp [set.subset_def]; exact forall_congr (assume i, @not_imp_comm _ _ (classical.dec _) (classical.dec _)) lemma support_single_ne_zero {i : ΞΉ} {b : Ξ² i} (hb : b β‰  0) : (single i b).support = {i} := begin ext j, by_cases h : i = j, { subst h, simp [hb] }, simp [ne.symm h, h] end lemma support_single_subset {i : ΞΉ} {b : Ξ² i} : (single i b).support βŠ† {i} := support_mk_subset section map_range_and_zip_with variables {β₁ : ΞΉ β†’ Type v₁} {Ξ²β‚‚ : ΞΉ β†’ Type vβ‚‚} variables [Ξ  i, has_zero (β₁ i)] [Ξ  i, has_zero (Ξ²β‚‚ i)] variables [Ξ  i, decidable_pred (eq (0 : β₁ i))] [Ξ  i, decidable_pred (eq (0 : Ξ²β‚‚ i))] lemma map_range_def {f : Ξ  i, β₁ i β†’ Ξ²β‚‚ i} {hf : βˆ€ i, f i 0 = 0} {g : Ξ β‚€ i, β₁ i} : map_range f hf g = mk g.support (Ξ» i, f i.1 (g i.1)) := begin ext i, by_cases h : g i = 0, { simp [h, hf] }, { simp at h, simp [h, hf] } end lemma support_map_range {f : Ξ  i, β₁ i β†’ Ξ²β‚‚ i} {hf : βˆ€ i, f i 0 = 0} {g : Ξ β‚€ i, β₁ i} : (map_range f hf g).support βŠ† g.support := by simp [map_range_def] @[simp] lemma map_range_single {f : Ξ  i, β₁ i β†’ Ξ²β‚‚ i} {hf : βˆ€ i, f i 0 = 0} {i : ΞΉ} {b : β₁ i} : map_range f hf (single i b) = single i (f i b) := dfinsupp.ext $ Ξ» i', by by_cases i = i'; [{subst i', simp}, simp [h, hf]] lemma zip_with_def {f : Ξ  i, β₁ i β†’ Ξ²β‚‚ i β†’ Ξ² i} {hf : βˆ€ i, f i 0 0 = 0} {g₁ : Ξ β‚€ i, β₁ i} {gβ‚‚ : Ξ β‚€ i, Ξ²β‚‚ i} : zip_with f hf g₁ gβ‚‚ = mk (g₁.support βˆͺ gβ‚‚.support) (Ξ» i, f i.1 (g₁ i.1) (gβ‚‚ i.1)) := begin ext i, by_cases h1 : g₁ i = 0; by_cases h2 : gβ‚‚ i = 0; try {simp at h1 h2}; simp [h1, h2, hf] end lemma support_zip_with {f : Ξ  i, β₁ i β†’ Ξ²β‚‚ i β†’ Ξ² i} {hf : βˆ€ i, f i 0 0 = 0} {g₁ : Ξ β‚€ i, β₁ i} {gβ‚‚ : Ξ β‚€ i, Ξ²β‚‚ i} : (zip_with f hf g₁ gβ‚‚).support βŠ† g₁.support βˆͺ gβ‚‚.support := by simp [zip_with_def] end map_range_and_zip_with lemma erase_def (i : ΞΉ) (f : Ξ β‚€ i, Ξ² i) : f.erase i = mk (f.support.erase i) (Ξ» j, f j.1) := begin ext j, by_cases h1 : j = i; by_cases h2 : f j = 0; try {simp at h2}; simp [h1, h2] end @[simp] lemma support_erase (i : ΞΉ) (f : Ξ β‚€ i, Ξ² i) : (f.erase i).support = f.support.erase i := begin ext j, by_cases h1 : j = i; by_cases h2 : f j = 0; try {simp at h2}; simp [h1, h2] end section filter_and_subtype_domain variables {p : ΞΉ β†’ Prop} [decidable_pred p] lemma filter_def (f : Ξ β‚€ i, Ξ² i) : f.filter p = mk (f.support.filter p) (Ξ» i, f i.1) := by ext i; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; simp [h1, h2] @[simp] lemma support_filter (f : Ξ β‚€ i, Ξ² i) : (f.filter p).support = f.support.filter p := by ext i; by_cases h : p i; simp [h] lemma subtype_domain_def (f : Ξ β‚€ i, Ξ² i) : f.subtype_domain p = mk (f.support.subtype p) (Ξ» i, f i.1) := by ext i; cases i with i hi; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; dsimp; simp [h1, h2] @[simp] lemma support_subtype_domain {f : Ξ β‚€ i, Ξ² i} : (subtype_domain p f).support = f.support.subtype p := by ext i; cases i with i hi; by_cases h1 : p i; by_cases h2 : f i = 0; try {simp at h2}; dsimp; simp [h1, h2] end filter_and_subtype_domain end support_basic lemma support_add [Ξ  i, add_monoid (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] {g₁ gβ‚‚ : Ξ β‚€ i, Ξ² i} : (g₁ + gβ‚‚).support βŠ† g₁.support βˆͺ gβ‚‚.support := support_zip_with @[simp] lemma support_neg [Ξ  i, add_group (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] {f : Ξ β‚€ i, Ξ² i} : support (-f) = support f := by ext i; simp instance [decidable_eq ΞΉ] [Ξ  i, has_zero (Ξ² i)] [Ξ  i, decidable_eq (Ξ² i)] : decidable_eq (Ξ β‚€ i, Ξ² i) := assume f g, decidable_of_iff (f.support = g.support ∧ (βˆ€i∈f.support, f i = g i)) ⟨assume ⟨h₁, hβ‚‚βŸ©, ext $ assume i, if h : i ∈ f.support then hβ‚‚ i h else have hf : f i = 0, by rwa [f.mem_support_iff, not_not] at h, have hg : g i = 0, by rwa [h₁, g.mem_support_iff, not_not] at h, by rw [hf, hg], by intro h; subst h; simp⟩ section prod_and_sum variables {Ξ³ : Type w} -- [to_additive dfinsupp.sum] for dfinsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g i (f i)` over the support of `f`. -/ def sum [Ξ  i, has_zero (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] [add_comm_monoid Ξ³] (f : Ξ β‚€ i, Ξ² i) (g : Ξ  i, Ξ² i β†’ Ξ³) : Ξ³ := f.support.sum (Ξ»i, g i (f i)) /-- `prod f g` is the product of `g i (f i)` over the support of `f`. -/ @[to_additive dfinsupp.sum] def prod [Ξ  i, has_zero (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] [comm_monoid Ξ³] (f : Ξ β‚€ i, Ξ² i) (g : Ξ  i, Ξ² i β†’ Ξ³) : Ξ³ := f.support.prod (Ξ»i, g i (f i)) attribute [to_additive dfinsupp.sum.equations._eqn_1] dfinsupp.prod.equations._eqn_1 @[to_additive dfinsupp.sum_map_range_index] lemma prod_map_range_index {β₁ : ΞΉ β†’ Type v₁} {Ξ²β‚‚ : ΞΉ β†’ Type vβ‚‚} [Ξ  i, has_zero (β₁ i)] [Ξ  i, has_zero (Ξ²β‚‚ i)] [Ξ  i, decidable_pred (eq (0 : β₁ i))] [Ξ  i, decidable_pred (eq (0 : Ξ²β‚‚ i))] [comm_monoid Ξ³] {f : Ξ  i, β₁ i β†’ Ξ²β‚‚ i} {hf : βˆ€ i, f i 0 = 0} {g : Ξ β‚€ i, β₁ i} {h : Ξ  i, Ξ²β‚‚ i β†’ Ξ³} (h0 : βˆ€i, h i 0 = 1) : (map_range f hf g).prod h = g.prod (Ξ»i b, h i (f i b)) := begin rw [map_range_def], refine (finset.prod_subset support_mk_subset _).trans _, { intros i h1 h2, dsimp, simp [h1] at h2, dsimp at h2, simp [h1, h2, h0] }, { refine finset.prod_congr rfl _, intros i h1, simp [h1] } end @[to_additive dfinsupp.sum_zero_index] lemma prod_zero_index [Ξ  i, add_comm_monoid (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] [comm_monoid Ξ³] {h : Ξ  i, Ξ² i β†’ Ξ³} : (0 : Ξ β‚€ i, Ξ² i).prod h = 1 := rfl @[to_additive dfinsupp.sum_single_index] lemma prod_single_index [Ξ  i, has_zero (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] [comm_monoid Ξ³] {i : ΞΉ} {b : Ξ² i} {h : Ξ  i, Ξ² i β†’ Ξ³} (h_zero : h i 0 = 1) : (single i b).prod h = h i b := begin by_cases h : b = 0, { simp [h, prod_zero_index, h_zero], refl }, { simp [dfinsupp.prod, support_single_ne_zero h] } end @[to_additive dfinsupp.sum_neg_index] lemma prod_neg_index [Ξ  i, add_group (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] [comm_monoid Ξ³] {g : Ξ β‚€ i, Ξ² i} {h : Ξ  i, Ξ² i β†’ Ξ³} (h0 : βˆ€i, h i 0 = 1) : (-g).prod h = g.prod (Ξ»i b, h i (- b)) := prod_map_range_index h0 @[simp] lemma sum_apply {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ β†’ Type v₁} [Ξ  i₁, has_zero (β₁ i₁)] [Ξ  i, decidable_pred (eq (0 : β₁ i))] [Ξ  i, add_comm_monoid (Ξ² i)] {f : Ξ β‚€ i₁, β₁ i₁} {g : Ξ  i₁, β₁ i₁ β†’ Ξ β‚€ i, Ξ² i} {iβ‚‚ : ΞΉ} : (f.sum g) iβ‚‚ = f.sum (Ξ»i₁ b, g i₁ b iβ‚‚) := (finset.sum_hom (Ξ»f : Ξ β‚€ i, Ξ² i, f iβ‚‚)).symm lemma support_sum {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ β†’ Type v₁} [Ξ  i₁, has_zero (β₁ i₁)] [Ξ  i, decidable_pred (eq (0 : β₁ i))] [Ξ  i, add_comm_monoid (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] {f : Ξ β‚€ i₁, β₁ i₁} {g : Ξ  i₁, β₁ i₁ β†’ Ξ β‚€ i, Ξ² i} : (f.sum g).support βŠ† f.support.bind (Ξ»i, (g i (f i)).support) := have βˆ€i₁ : ΞΉ, f.sum (Ξ» (i : ι₁) (b : β₁ i), (g i b) i₁) β‰  0 β†’ (βˆƒ (i : ι₁), f i β‰  0 ∧ Β¬ (g i (f i)) i₁ = 0), from assume i₁ h, let ⟨i, hi, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨i, (f.mem_support_iff i).mp hi, ne⟩, by simpa [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply] using this @[simp] lemma sum_zero [Ξ  i, add_comm_monoid (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] [add_comm_monoid Ξ³] {f : Ξ β‚€ i, Ξ² i} : f.sum (Ξ»i b, (0 : Ξ³)) = 0 := finset.sum_const_zero @[simp] lemma sum_add [Ξ  i, add_comm_monoid (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] [add_comm_monoid Ξ³] {f : Ξ β‚€ i, Ξ² i} {h₁ hβ‚‚ : Ξ  i, Ξ² i β†’ Ξ³} : f.sum (Ξ»i b, h₁ i b + hβ‚‚ i b) = f.sum h₁ + f.sum hβ‚‚ := finset.sum_add_distrib @[simp] lemma sum_neg [Ξ  i, add_comm_monoid (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] [add_comm_group Ξ³] {f : Ξ β‚€ i, Ξ² i} {h : Ξ  i, Ξ² i β†’ Ξ³} : f.sum (Ξ»i b, - h i b) = - f.sum h := finset.sum_hom (@has_neg.neg Ξ³ _) @[to_additive dfinsupp.sum_add_index] lemma prod_add_index [Ξ  i, add_comm_monoid (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] [comm_monoid Ξ³] {f g : Ξ β‚€ i, Ξ² i} {h : Ξ  i, Ξ² i β†’ Ξ³} (h_zero : βˆ€i, h i 0 = 1) (h_add : βˆ€i b₁ bβ‚‚, h i (b₁ + bβ‚‚) = h i b₁ * h i bβ‚‚) : (f + g).prod h = f.prod h * g.prod h := have f_eq : (f.support βˆͺ g.support).prod (Ξ»i, h i (f i)) = f.prod h, from (finset.prod_subset (finset.subset_union_left _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, have g_eq : (f.support βˆͺ g.support).prod (Ξ»i, h i (g i)) = g.prod h, from (finset.prod_subset (finset.subset_union_right _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, calc (f + g).support.prod (Ξ»i, h i ((f + g) i)) = (f.support βˆͺ g.support).prod (Ξ»i, h i ((f + g) i)) : finset.prod_subset support_add $ by simp [mem_support_iff, h_zero] {contextual := tt} ... = (f.support βˆͺ g.support).prod (Ξ»i, h i (f i)) * (f.support βˆͺ g.support).prod (Ξ»i, h i (g i)) : by simp [h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] lemma sum_sub_index [Ξ  i, add_comm_group (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] [add_comm_group Ξ³] {f g : Ξ β‚€ i, Ξ² i} {h : Ξ  i, Ξ² i β†’ Ξ³} (h_sub : βˆ€i b₁ bβ‚‚, h i (b₁ - bβ‚‚) = h i b₁ - h i bβ‚‚) : (f - g).sum h = f.sum h - g.sum h := have h_zero : βˆ€i, h i 0 = 0, from assume i, have h i (0 - 0) = h i 0 - h i 0, from h_sub i 0 0, by simpa using this, have h_neg : βˆ€i b, h i (- b) = - h i b, from assume i b, have h i (0 - b) = h i 0 - h i b, from h_sub i 0 b, by simpa [h_zero] using this, have h_add : βˆ€i b₁ bβ‚‚, h i (b₁ + bβ‚‚) = h i b₁ + h i bβ‚‚, from assume i b₁ bβ‚‚, have h i (b₁ - (- bβ‚‚)) = h i b₁ - h i (- bβ‚‚), from h_sub i b₁ (-bβ‚‚), by simpa [h_neg] using this, by simp [@sum_add_index ΞΉ Ξ² _ Ξ³ _ _ _ f (-g) h h_zero h_add]; simp [@sum_neg_index ΞΉ Ξ² _ Ξ³ _ _ _ g h h_zero, h_neg]; simp [@sum_neg ΞΉ Ξ² _ Ξ³ _ _ _ g h] @[to_additive dfinsupp.sum_finset_sum_index] lemma prod_finset_sum_index {Ξ³ : Type w} {Ξ± : Type x} [Ξ  i, add_comm_monoid (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] [comm_monoid Ξ³] [decidable_eq Ξ±] {s : finset Ξ±} {g : Ξ± β†’ Ξ β‚€ i, Ξ² i} {h : Ξ  i, Ξ² i β†’ Ξ³} (h_zero : βˆ€i, h i 0 = 1) (h_add : βˆ€i b₁ bβ‚‚, h i (b₁ + bβ‚‚) = h i b₁ * h i bβ‚‚): s.prod (Ξ»i, (g i).prod h) = (s.sum g).prod h := finset.induction_on s (by simp [prod_zero_index]) (by simp [prod_add_index, h_zero, h_add] {contextual := tt}) @[to_additive dfinsupp.sum_sum_index] lemma prod_sum_index {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ β†’ Type v₁} [Ξ  i₁, has_zero (β₁ i₁)] [Ξ  i, decidable_pred (eq (0 : β₁ i))] [Ξ  i, add_comm_monoid (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] [comm_monoid Ξ³] {f : Ξ β‚€ i₁, β₁ i₁} {g : Ξ  i₁, β₁ i₁ β†’ Ξ β‚€ i, Ξ² i} {h : Ξ  i, Ξ² i β†’ Ξ³} (h_zero : βˆ€i, h i 0 = 1) (h_add : βˆ€i b₁ bβ‚‚, h i (b₁ + bβ‚‚) = h i b₁ * h i bβ‚‚): (f.sum g).prod h = f.prod (Ξ»i b, (g i b).prod h) := (prod_finset_sum_index h_zero h_add).symm @[simp] lemma sum_single [Ξ  i, add_comm_monoid (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] {f : Ξ β‚€ i, Ξ² i} : f.sum single = f := begin apply dfinsupp.induction f, {rw [sum_zero_index]}, intros i b f H hb ih, rw [sum_add_index, ih, sum_single_index], all_goals { intros, simp } end @[to_additive dfinsupp.sum_subtype_domain_index] lemma prod_subtype_domain_index [Ξ  i, has_zero (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] [comm_monoid Ξ³] {v : Ξ β‚€ i, Ξ² i} {p : ΞΉ β†’ Prop} [decidable_pred p] {h : Ξ  i, Ξ² i β†’ Ξ³} (hp : βˆ€x∈v.support, p x) : (v.subtype_domain p).prod (Ξ»i b, h i.1 b) = v.prod h := finset.prod_bij (Ξ»p _, p.val) (by simp) (by simp) (assume ⟨aβ‚€, haβ‚€βŸ© ⟨a₁, haβ‚βŸ©, by simp) (Ξ» i hi, ⟨⟨i, hp i hi⟩, by simpa using hi, rfl⟩) lemma subtype_domain_sum [Ξ  i, add_comm_monoid (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] {s : finset Ξ³} {h : Ξ³ β†’ Ξ β‚€ i, Ξ² i} {p : ΞΉ β†’ Prop} [decidable_pred p] : (s.sum h).subtype_domain p = s.sum (Ξ»c, (h c).subtype_domain p) := eq.symm (finset.sum_hom _) lemma subtype_domain_finsupp_sum {Ξ΄ : Ξ³ β†’ Type x} [decidable_eq Ξ³] [Ξ  c, has_zero (Ξ΄ c)] [Ξ  c, decidable_pred (eq (0 : Ξ΄ c))] [Ξ  i, add_comm_monoid (Ξ² i)] [Ξ  i, decidable_pred (eq (0 : Ξ² i))] {p : ΞΉ β†’ Prop} [decidable_pred p] {s : Ξ β‚€ c, Ξ΄ c} {h : Ξ  c, Ξ΄ c β†’ Ξ β‚€ i, Ξ² i} : (s.sum h).subtype_domain p = s.sum (Ξ»c d, (h c d).subtype_domain p) := subtype_domain_sum end prod_and_sum end dfinsupp
397b7f6dee8cb0c16f39e9fd5adde20e1f76df45
c09f5945267fd905e23a77be83d9a78580e04a4a
/src/data/equiv/basic.lean
c6619b8dc28d8b64ec35ea0cc51aa4abf54b04f5
[ "Apache-2.0" ]
permissive
OHIHIYA20/mathlib
023a6df35355b5b6eb931c404f7dd7535dccfa89
1ec0a1f49db97d45e8666a3bf33217ff79ca1d87
refs/heads/master
1,587,964,529,965
1,551,819,319,000
1,551,819,319,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,862
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro In the standard library we cannot assume the univalence axiom. We say two types are equivalent if they are isomorphic. Two equivalent types have the same cardinality. -/ import logic.function logic.unique data.set.basic data.bool data.quot open function universes u v w variables {Ξ± : Sort u} {Ξ² : Sort v} {Ξ³ : Sort w} /-- `Ξ± ≃ Ξ²` is the type of functions from `Ξ± β†’ Ξ²` with a two-sided inverse. -/ structure equiv (Ξ± : Sort*) (Ξ² : Sort*) := (to_fun : Ξ± β†’ Ξ²) (inv_fun : Ξ² β†’ Ξ±) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) namespace equiv /-- `perm Ξ±` is the type of bijections from `Ξ±` to itself. -/ @[reducible] def perm (Ξ± : Sort*) := equiv Ξ± Ξ± infix ` ≃ `:50 := equiv instance : has_coe_to_fun (Ξ± ≃ Ξ²) := ⟨_, to_fun⟩ @[simp] theorem coe_fn_mk (f : Ξ± β†’ Ξ²) (g l r) : (equiv.mk f g l r : Ξ± β†’ Ξ²) = f := rfl theorem eq_of_to_fun_eq : βˆ€ {e₁ eβ‚‚ : equiv Ξ± Ξ²}, (e₁ : Ξ± β†’ Ξ²) = eβ‚‚ β†’ e₁ = eβ‚‚ | ⟨f₁, g₁, l₁, rβ‚βŸ© ⟨fβ‚‚, gβ‚‚, lβ‚‚, rβ‚‚βŸ© h := have f₁ = fβ‚‚, from h, have g₁ = gβ‚‚, from funext $ assume x, have f₁ (g₁ x) = fβ‚‚ (gβ‚‚ x), from (r₁ x).trans (rβ‚‚ x).symm, have f₁ (g₁ x) = f₁ (gβ‚‚ x), by subst fβ‚‚; exact this, show g₁ x = gβ‚‚ x, from injective_of_left_inverse l₁ this, by simp * @[extensionality] lemma ext (f g : equiv Ξ± Ξ²) (H : βˆ€ x, f x = g x) : f = g := eq_of_to_fun_eq (funext H) @[extensionality] lemma perm.ext (Οƒ Ο„ : equiv.perm Ξ±) (H : βˆ€ x, Οƒ x = Ο„ x) : Οƒ = Ο„ := equiv.ext _ _ H @[refl] protected def refl (Ξ± : Sort*) : Ξ± ≃ Ξ± := ⟨id, id, Ξ» x, rfl, Ξ» x, rfl⟩ @[symm] protected def symm (e : Ξ± ≃ Ξ²) : Ξ² ≃ Ξ± := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ @[trans] protected def trans (e₁ : Ξ± ≃ Ξ²) (eβ‚‚ : Ξ² ≃ Ξ³) : Ξ± ≃ Ξ³ := ⟨eβ‚‚.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ eβ‚‚.inv_fun, eβ‚‚.left_inv.comp e₁.left_inv, eβ‚‚.right_inv.comp e₁.right_inv⟩ protected theorem bijective : βˆ€ f : Ξ± ≃ Ξ², bijective f | ⟨f, g, h₁, hβ‚‚βŸ© := ⟨injective_of_left_inverse h₁, surjective_of_has_right_inverse ⟨_, hβ‚‚βŸ©βŸ© protected theorem subsingleton (e : Ξ± ≃ Ξ²) : βˆ€ [subsingleton Ξ²], subsingleton Ξ± | ⟨H⟩ := ⟨λ a b, e.bijective.1 (H _ _)⟩ protected def decidable_eq (e : Ξ± ≃ Ξ²) [H : decidable_eq Ξ²] : decidable_eq Ξ± | a b := decidable_of_iff _ e.bijective.1.eq_iff protected def cast {Ξ± Ξ² : Sort*} (h : Ξ± = Ξ²) : Ξ± ≃ Ξ² := ⟨cast h, cast h.symm, Ξ» x, by cases h; refl, Ξ» x, by cases h; refl⟩ @[simp] theorem coe_fn_symm_mk (f : Ξ± β†’ Ξ²) (g l r) : ((equiv.mk f g l r).symm : Ξ² β†’ Ξ±) = g := rfl @[simp] theorem refl_apply (x : Ξ±) : equiv.refl Ξ± x = x := rfl @[simp] theorem trans_apply (f : Ξ± ≃ Ξ²) (g : Ξ² ≃ Ξ³) (a : Ξ±) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_inverse_apply : βˆ€ (e : Ξ± ≃ Ξ²) (x : Ξ²), e (e.symm x) = x | ⟨f₁, g₁, l₁, rβ‚βŸ© x := by simp [equiv.symm]; rw r₁ @[simp] theorem inverse_apply_apply : βˆ€ (e : Ξ± ≃ Ξ²) (x : Ξ±), e.symm (e x) = x | ⟨f₁, g₁, l₁, rβ‚βŸ© x := by simp [equiv.symm]; rw l₁ @[simp] lemma inverse_trans_apply (f : Ξ± ≃ Ξ²) (g : Ξ² ≃ Ξ³) (a : Ξ³) : (f.trans g).symm a = f.symm (g.symm a) := rfl @[simp] theorem apply_eq_iff_eq : βˆ€ (f : Ξ± ≃ Ξ²) (x y : Ξ±), f x = f y ↔ x = y | ⟨f₁, g₁, l₁, rβ‚βŸ© x y := (injective_of_left_inverse l₁).eq_iff @[simp] theorem cast_apply {Ξ± Ξ²} (h : Ξ± = Ξ²) (x : Ξ±) : equiv.cast h x = cast h x := rfl lemma symm_apply_eq {Ξ± Ξ²} (e : Ξ± ≃ Ξ²) {x y} : e.symm x = y ↔ x = e y := ⟨λ H, by simp [H.symm], Ξ» H, by simp [H]⟩ lemma eq_symm_apply {Ξ± Ξ²} (e : Ξ± ≃ Ξ²) {x y} : y = e.symm x ↔ e y = x := (eq_comm.trans e.symm_apply_eq).trans eq_comm @[simp] theorem symm_symm (e : Ξ± ≃ Ξ²) : e.symm.symm = e := by cases e; refl @[simp] theorem trans_refl (e : Ξ± ≃ Ξ²) : e.trans (equiv.refl Ξ²) = e := by cases e; refl @[simp] theorem refl_trans (e : Ξ± ≃ Ξ²) : (equiv.refl Ξ±).trans e = e := by cases e; refl @[simp] theorem symm_trans (e : Ξ± ≃ Ξ²) : e.symm.trans e = equiv.refl Ξ² := ext _ _ (by simp) @[simp] theorem trans_symm (e : Ξ± ≃ Ξ²) : e.trans e.symm = equiv.refl Ξ± := ext _ _ (by simp) lemma trans_assoc {Ξ΄} (ab : Ξ± ≃ Ξ²) (bc : Ξ² ≃ Ξ³) (cd : Ξ³ ≃ Ξ΄) : (ab.trans bc).trans cd = ab.trans (bc.trans cd) := equiv.ext _ _ $ assume a, rfl theorem left_inverse_symm (f : equiv Ξ± Ξ²) : left_inverse f.symm f := f.left_inv theorem right_inverse_symm (f : equiv Ξ± Ξ²) : function.right_inverse f.symm f := f.right_inv def equiv_congr {Ξ΄} (ab : Ξ± ≃ Ξ²) (cd : Ξ³ ≃ Ξ΄) : (Ξ± ≃ Ξ³) ≃ (Ξ² ≃ Ξ΄) := ⟨ Ξ»ac, (ab.symm.trans ac).trans cd, Ξ»bd, ab.trans $ bd.trans $ cd.symm, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, ⟩ def perm_congr {Ξ± : Type*} {Ξ² : Type*} (e : Ξ± ≃ Ξ²) : perm Ξ± ≃ perm Ξ² := equiv_congr e e protected lemma image_eq_preimage {Ξ± Ξ²} (e : Ξ± ≃ Ξ²) (s : set Ξ±) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv protected lemma subset_image {Ξ± Ξ²} (e : Ξ± ≃ Ξ²) (s : set Ξ±) (t : set Ξ²) : t βŠ† e '' s ↔ e.symm '' t βŠ† s := by rw [set.image_subset_iff, e.image_eq_preimage] lemma symm_image_image {Ξ± Ξ²} (f : equiv Ξ± Ξ²) (s : set Ξ±) : f.symm '' (f '' s) = s := by rw [← set.image_comp]; simpa using set.image_id s protected lemma image_compl {Ξ± Ξ²} (f : equiv Ξ± Ξ²) (s : set Ξ±) : f '' -s = -(f '' s) := set.image_compl_eq f.bijective /- The group of permutations (self-equivalences) of a type `Ξ±` -/ namespace perm instance perm_group {Ξ± : Type u} : group (perm Ξ±) := begin refine { mul := Ξ» f g, equiv.trans g f, one := equiv.refl Ξ±, inv:= equiv.symm, ..}; intros; apply equiv.ext; try { apply trans_apply }, apply inverse_apply_apply end @[simp] theorem mul_apply {Ξ± : Type u} (f g : perm Ξ±) (x) : (f * g) x = f (g x) := equiv.trans_apply _ _ _ @[simp] theorem one_apply {Ξ± : Type u} (x) : (1 : perm Ξ±) x = x := rfl @[simp] lemma inv_apply_self {Ξ± : Type u} (f : perm Ξ±) (x) : f⁻¹ (f x) = x := equiv.inverse_apply_apply _ _ @[simp] lemma apply_inv_self {Ξ± : Type u} (f : perm Ξ±) (x) : f (f⁻¹ x) = x := equiv.apply_inverse_apply _ _ lemma one_def {Ξ± : Type u} : (1 : perm Ξ±) = equiv.refl Ξ± := rfl lemma mul_def {Ξ± : Type u} (f g : perm Ξ±) : f * g = g.trans f := rfl lemma inv_def {Ξ± : Type u} (f : perm Ξ±) : f⁻¹ = f.symm := rfl end perm def equiv_empty (h : Ξ± β†’ false) : Ξ± ≃ empty := ⟨λ x, (h x).elim, Ξ» e, e.rec _, Ξ» x, (h x).elim, Ξ» e, e.rec _⟩ def false_equiv_empty : false ≃ empty := equiv_empty _root_.id def equiv_pempty (h : Ξ± β†’ false) : Ξ± ≃ pempty := ⟨λ x, (h x).elim, Ξ» e, e.rec _, Ξ» x, (h x).elim, Ξ» e, e.rec _⟩ def false_equiv_pempty : false ≃ pempty := equiv_pempty _root_.id def empty_equiv_pempty : empty ≃ pempty := equiv_pempty $ empty.rec _ def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} := equiv_pempty pempty.elim def empty_of_not_nonempty {Ξ± : Sort*} (h : Β¬ nonempty Ξ±) : Ξ± ≃ empty := equiv_empty $ assume a, h ⟨a⟩ def pempty_of_not_nonempty {Ξ± : Sort*} (h : Β¬ nonempty Ξ±) : Ξ± ≃ pempty := equiv_pempty $ assume a, h ⟨a⟩ def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit := ⟨λ x, (), Ξ» x, h, Ξ» _, rfl, Ξ» ⟨⟩, rfl⟩ def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial protected def ulift {Ξ± : Type u} : ulift Ξ± ≃ Ξ± := ⟨ulift.down, ulift.up, ulift.up_down, Ξ» a, rfl⟩ protected def plift : plift Ξ± ≃ Ξ± := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ @[congr] def arrow_congr {α₁ β₁ Ξ±β‚‚ Ξ²β‚‚ : Sort*} : α₁ ≃ Ξ±β‚‚ β†’ β₁ ≃ Ξ²β‚‚ β†’ (α₁ β†’ β₁) ≃ (Ξ±β‚‚ β†’ Ξ²β‚‚) | ⟨f₁, g₁, l₁, rβ‚βŸ© ⟨fβ‚‚, gβ‚‚, lβ‚‚, rβ‚‚βŸ© := ⟨λ (h : α₁ β†’ β₁) (a : Ξ±β‚‚), fβ‚‚ (h (g₁ a)), Ξ» (h : Ξ±β‚‚ β†’ Ξ²β‚‚) (a : α₁), gβ‚‚ (h (f₁ a)), Ξ» h, by funext a; dsimp; rw [l₁, lβ‚‚], Ξ» h, by funext a; dsimp; rw [r₁, rβ‚‚]⟩ def punit_equiv_punit : punit.{v} ≃ punit.{w} := ⟨λ _, punit.star, Ξ» _, punit.star, Ξ» u, by cases u; refl, Ξ» u, by cases u; reflexivity⟩ section @[simp] def arrow_punit_equiv_punit (Ξ± : Sort*) : (Ξ± β†’ punit.{v}) ≃ punit.{w} := ⟨λ f, punit.star, Ξ» u f, punit.star, Ξ» f, by funext x; cases f x; refl, Ξ» u, by cases u; reflexivity⟩ @[simp] def punit_arrow_equiv (Ξ± : Sort*) : (punit.{u} β†’ Ξ±) ≃ Ξ± := ⟨λ f, f punit.star, Ξ» a u, a, Ξ» f, by funext x; cases x; refl, Ξ» u, rfl⟩ @[simp] def empty_arrow_equiv_punit (Ξ± : Sort*) : (empty β†’ Ξ±) ≃ punit.{u} := ⟨λ f, punit.star, Ξ» u e, e.rec _, Ξ» f, funext $ Ξ» x, x.rec _, Ξ» u, by cases u; refl⟩ @[simp] def pempty_arrow_equiv_punit (Ξ± : Sort*) : (pempty β†’ Ξ±) ≃ punit.{u} := ⟨λ f, punit.star, Ξ» u e, e.rec _, Ξ» f, funext $ Ξ» x, x.rec _, Ξ» u, by cases u; refl⟩ @[simp] def false_arrow_equiv_punit (Ξ± : Sort*) : (false β†’ Ξ±) ≃ punit.{u} := calc (false β†’ Ξ±) ≃ (empty β†’ Ξ±) : arrow_congr false_equiv_empty (equiv.refl _) ... ≃ punit : empty_arrow_equiv_punit _ end @[congr] def prod_congr {α₁ β₁ Ξ±β‚‚ Ξ²β‚‚ : Sort*} (e₁ : α₁ ≃ Ξ±β‚‚) (eβ‚‚ :β₁ ≃ Ξ²β‚‚) : (α₁ Γ— β₁) ≃ (Ξ±β‚‚ Γ— Ξ²β‚‚) := ⟨λp, (e₁ p.1, eβ‚‚ p.2), Ξ»p, (e₁.symm p.1, eβ‚‚.symm p.2), Ξ» ⟨a, b⟩, show (e₁.symm (e₁ a), eβ‚‚.symm (eβ‚‚ b)) = (a, b), by rw [inverse_apply_apply, inverse_apply_apply], Ξ» ⟨a, b⟩, show (e₁ (e₁.symm a), eβ‚‚ (eβ‚‚.symm b)) = (a, b), by rw [apply_inverse_apply, apply_inverse_apply]⟩ @[simp] theorem prod_congr_apply {α₁ β₁ Ξ±β‚‚ Ξ²β‚‚ : Sort*} (e₁ : α₁ ≃ Ξ±β‚‚) (eβ‚‚ : β₁ ≃ Ξ²β‚‚) (a : α₁) (b : β₁) : prod_congr e₁ eβ‚‚ (a, b) = (e₁ a, eβ‚‚ b) := rfl @[simp] def prod_comm (Ξ± Ξ² : Sort*) : (Ξ± Γ— Ξ²) ≃ (Ξ² Γ— Ξ±) := ⟨λ p, (p.2, p.1), Ξ» p, (p.2, p.1), λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ @[simp] def prod_assoc (Ξ± Ξ² Ξ³ : Sort*) : ((Ξ± Γ— Ξ²) Γ— Ξ³) ≃ (Ξ± Γ— (Ξ² Γ— Ξ³)) := ⟨λ p, ⟨p.1.1, ⟨p.1.2, p.2⟩⟩, Ξ»p, ⟨⟨p.1, p.2.1⟩, p.2.2⟩, Ξ» ⟨⟨a, b⟩, c⟩, rfl, Ξ» ⟨a, ⟨b, c⟩⟩, rfl⟩ @[simp] theorem prod_assoc_apply {Ξ± Ξ² Ξ³ : Sort*} (p : (Ξ± Γ— Ξ²) Γ— Ξ³) : prod_assoc Ξ± Ξ² Ξ³ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl section @[simp] def prod_punit (Ξ± : Sort*) : (Ξ± Γ— punit.{u+1}) ≃ Ξ± := ⟨λ p, p.1, Ξ» a, (a, punit.star), Ξ» ⟨_, punit.star⟩, rfl, Ξ» a, rfl⟩ @[simp] theorem prod_punit_apply {Ξ± : Sort*} (a : Ξ± Γ— punit.{u+1}) : prod_punit Ξ± a = a.1 := rfl @[simp] def punit_prod (Ξ± : Sort*) : (punit.{u+1} Γ— Ξ±) ≃ Ξ± := calc (punit Γ— Ξ±) ≃ (Ξ± Γ— punit) : prod_comm _ _ ... ≃ Ξ± : prod_punit _ @[simp] theorem punit_prod_apply {Ξ± : Sort*} (a : punit.{u+1} Γ— Ξ±) : punit_prod Ξ± a = a.2 := rfl @[simp] def prod_empty (Ξ± : Sort*) : (Ξ± Γ— empty) ≃ empty := equiv_empty (Ξ» ⟨_, e⟩, e.rec _) @[simp] def empty_prod (Ξ± : Sort*) : (empty Γ— Ξ±) ≃ empty := equiv_empty (Ξ» ⟨e, _⟩, e.rec _) @[simp] def prod_pempty (Ξ± : Sort*) : (Ξ± Γ— pempty) ≃ pempty := equiv_pempty (Ξ» ⟨_, e⟩, e.rec _) @[simp] def pempty_prod (Ξ± : Sort*) : (pempty Γ— Ξ±) ≃ pempty := equiv_pempty (Ξ» ⟨e, _⟩, e.rec _) end section open sum def psum_equiv_sum (Ξ± Ξ² : Sort*) : psum Ξ± Ξ² ≃ (Ξ± βŠ• Ξ²) := ⟨λ s, psum.cases_on s inl inr, Ξ» s, sum.cases_on s psum.inl psum.inr, Ξ» s, by cases s; refl, Ξ» s, by cases s; refl⟩ def sum_congr {α₁ β₁ Ξ±β‚‚ Ξ²β‚‚ : Sort*} : α₁ ≃ Ξ±β‚‚ β†’ β₁ ≃ Ξ²β‚‚ β†’ (α₁ βŠ• β₁) ≃ (Ξ±β‚‚ βŠ• Ξ²β‚‚) | ⟨f₁, g₁, l₁, rβ‚βŸ© ⟨fβ‚‚, gβ‚‚, lβ‚‚, rβ‚‚βŸ© := ⟨λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (fβ‚‚ b₁) end, Ξ» s, match s with inl aβ‚‚ := inl (g₁ aβ‚‚) | inr bβ‚‚ := inr (gβ‚‚ bβ‚‚) end, Ξ» s, match s with inl a := congr_arg inl (l₁ a) | inr a := congr_arg inr (lβ‚‚ a) end, Ξ» s, match s with inl a := congr_arg inl (r₁ a) | inr a := congr_arg inr (rβ‚‚ a) end⟩ @[simp] theorem sum_congr_apply_inl {α₁ β₁ Ξ±β‚‚ Ξ²β‚‚ : Sort*} (e₁ : α₁ ≃ Ξ±β‚‚) (eβ‚‚ : β₁ ≃ Ξ²β‚‚) (a : α₁) : sum_congr e₁ eβ‚‚ (inl a) = inl (e₁ a) := by cases e₁; cases eβ‚‚; refl @[simp] theorem sum_congr_apply_inr {α₁ β₁ Ξ±β‚‚ Ξ²β‚‚ : Sort*} (e₁ : α₁ ≃ Ξ±β‚‚) (eβ‚‚ : β₁ ≃ Ξ²β‚‚) (b : β₁) : sum_congr e₁ eβ‚‚ (inr b) = inr (eβ‚‚ b) := by cases e₁; cases eβ‚‚; refl def bool_equiv_punit_sum_punit : bool ≃ (punit.{u+1} βŠ• punit.{v+1}) := ⟨λ b, cond b (inr punit.star) (inl punit.star), Ξ» s, sum.rec_on s (Ξ»_, ff) (Ξ»_, tt), Ξ» b, by cases b; refl, Ξ» s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), Ξ» b, b, Ξ» p, by simp, Ξ» b, by simp⟩ @[simp] def sum_comm (Ξ± Ξ² : Sort*) : (Ξ± βŠ• Ξ²) ≃ (Ξ² βŠ• Ξ±) := ⟨λ s, match s with inl a := inr a | inr b := inl b end, Ξ» s, match s with inl b := inr b | inr a := inl a end, Ξ» s, by cases s; refl, Ξ» s, by cases s; refl⟩ @[simp] def sum_assoc (Ξ± Ξ² Ξ³ : Sort*) : ((Ξ± βŠ• Ξ²) βŠ• Ξ³) ≃ (Ξ± βŠ• (Ξ² βŠ• Ξ³)) := ⟨λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end, Ξ» s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end, Ξ» s, by rcases s with ⟨_ | _⟩ | _; refl, Ξ» s, by rcases s with _ | _ | _; refl⟩ @[simp] theorem sum_assoc_apply_in1 {Ξ± Ξ² Ξ³} (a) : sum_assoc Ξ± Ξ² Ξ³ (inl (inl a)) = inl a := rfl @[simp] theorem sum_assoc_apply_in2 {Ξ± Ξ² Ξ³} (b) : sum_assoc Ξ± Ξ² Ξ³ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sum_assoc_apply_in3 {Ξ± Ξ² Ξ³} (c) : sum_assoc Ξ± Ξ² Ξ³ (inr c) = inr (inr c) := rfl @[simp] def sum_empty (Ξ± : Sort*) : (Ξ± βŠ• empty) ≃ Ξ± := ⟨λ s, match s with inl a := a | inr e := empty.rec _ e end, inl, Ξ» s, by rcases s with _ | ⟨⟨⟩⟩; refl, Ξ» a, rfl⟩ @[simp] def empty_sum (Ξ± : Sort*) : (empty βŠ• Ξ±) ≃ Ξ± := (sum_comm _ _).trans $ sum_empty _ @[simp] def sum_pempty (Ξ± : Sort*) : (Ξ± βŠ• pempty) ≃ Ξ± := ⟨λ s, match s with inl a := a | inr e := pempty.rec _ e end, inl, Ξ» s, by rcases s with _ | ⟨⟨⟩⟩; refl, Ξ» a, rfl⟩ @[simp] def pempty_sum (Ξ± : Sort*) : (pempty βŠ• Ξ±) ≃ Ξ± := (sum_comm _ _).trans $ sum_pempty _ @[simp] def option_equiv_sum_punit (Ξ± : Sort*) : option Ξ± ≃ (Ξ± βŠ• punit.{u+1}) := ⟨λ o, match o with none := inr punit.star | some a := inl a end, Ξ» s, match s with inr _ := none | inl a := some a end, Ξ» o, by cases o; refl, Ξ» s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ def sum_equiv_sigma_bool (Ξ± Ξ² : Sort*) : (Ξ± βŠ• Ξ²) ≃ (Ξ£ b: bool, cond b Ξ± Ξ²) := ⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end, Ξ» s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, Ξ» s, by cases s; refl, Ξ» s, by rcases s with ⟨_|_, _⟩; refl⟩ def equiv_fib {Ξ± Ξ² : Type*} (f : Ξ± β†’ Ξ²) : Ξ± ≃ Ξ£ y : Ξ², {x // f x = y} := ⟨λ x, ⟨f x, x, rfl⟩, Ξ» x, x.2.1, Ξ» x, rfl, Ξ» ⟨y, x, rfl⟩, rfl⟩ end section def Pi_congr_right {Ξ±} {β₁ Ξ²β‚‚ : Ξ± β†’ Sort*} (F : βˆ€ a, β₁ a ≃ Ξ²β‚‚ a) : (Ξ  a, β₁ a) ≃ (Ξ  a, Ξ²β‚‚ a) := ⟨λ H a, F a (H a), Ξ» H a, (F a).symm (H a), Ξ» H, funext $ by simp, Ξ» H, funext $ by simp⟩ end section def psigma_equiv_sigma {Ξ±} (Ξ² : Ξ± β†’ Sort*) : psigma Ξ² ≃ sigma Ξ² := ⟨λ ⟨a, b⟩, ⟨a, b⟩, Ξ» ⟨a, b⟩, ⟨a, b⟩, Ξ» ⟨a, b⟩, rfl, Ξ» ⟨a, b⟩, rfl⟩ def sigma_congr_right {Ξ±} {β₁ Ξ²β‚‚ : Ξ± β†’ Sort*} (F : βˆ€ a, β₁ a ≃ Ξ²β‚‚ a) : sigma β₁ ≃ sigma Ξ²β‚‚ := ⟨λ ⟨a, b⟩, ⟨a, F a b⟩, Ξ» ⟨a, b⟩, ⟨a, (F a).symm b⟩, Ξ» ⟨a, b⟩, congr_arg (sigma.mk a) $ inverse_apply_apply (F a) b, Ξ» ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_inverse_apply (F a) b⟩ def sigma_congr_left {α₁ Ξ±β‚‚} {Ξ² : Ξ±β‚‚ β†’ Sort*} : βˆ€ f : α₁ ≃ Ξ±β‚‚, (Ξ£ a:α₁, Ξ² (f a)) ≃ (Ξ£ a:Ξ±β‚‚, Ξ² a) | ⟨f, g, l, r⟩ := ⟨λ ⟨a, b⟩, ⟨f a, b⟩, Ξ» ⟨a, b⟩, ⟨g a, @@eq.rec Ξ² b (r a).symm⟩, Ξ» ⟨a, b⟩, match g (f a), l a : βˆ€ a' (h : a' = a), @sigma.mk _ (Ξ² ∘ f) _ (@@eq.rec Ξ² b (congr_arg f h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, Ξ» ⟨a, b⟩, match f (g a), _ : βˆ€ a' (h : a' = a), sigma.mk a' (@@eq.rec Ξ² b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ def sigma_equiv_prod (Ξ± Ξ² : Sort*) : (Ξ£_:Ξ±, Ξ²) ≃ (Ξ± Γ— Ξ²) := ⟨λ ⟨a, b⟩, ⟨a, b⟩, Ξ» ⟨a, b⟩, ⟨a, b⟩, Ξ» ⟨a, b⟩, rfl, Ξ» ⟨a, b⟩, rfl⟩ def sigma_equiv_prod_of_equiv {Ξ± Ξ²} {β₁ : Ξ± β†’ Sort*} (F : βˆ€ a, β₁ a ≃ Ξ²) : sigma β₁ ≃ (Ξ± Γ— Ξ²) := (sigma_congr_right F).trans (sigma_equiv_prod Ξ± Ξ²) end section def arrow_prod_equiv_prod_arrow (Ξ± Ξ² Ξ³ : Type*) : (Ξ³ β†’ Ξ± Γ— Ξ²) ≃ ((Ξ³ β†’ Ξ±) Γ— (Ξ³ β†’ Ξ²)) := ⟨λ f, (Ξ» c, (f c).1, Ξ» c, (f c).2), Ξ» p c, (p.1 c, p.2 c), Ξ» f, funext $ Ξ» c, prod.mk.eta, Ξ» p, by cases p; refl⟩ def arrow_arrow_equiv_prod_arrow (Ξ± Ξ² Ξ³ : Sort*) : (Ξ± β†’ Ξ² β†’ Ξ³) ≃ (Ξ± Γ— Ξ² β†’ Ξ³) := ⟨λ f, Ξ» p, f p.1 p.2, Ξ» f, Ξ» a b, f (a, b), Ξ» f, rfl, Ξ» f, by funext p; cases p; refl⟩ open sum def sum_arrow_equiv_prod_arrow (Ξ± Ξ² Ξ³ : Type*) : ((Ξ± βŠ• Ξ²) β†’ Ξ³) ≃ ((Ξ± β†’ Ξ³) Γ— (Ξ² β†’ Ξ³)) := ⟨λ f, (f ∘ inl, f ∘ inr), Ξ» p s, sum.rec_on s p.1 p.2, Ξ» f, by funext s; cases s; refl, Ξ» p, by cases p; refl⟩ def sum_prod_distrib (Ξ± Ξ² Ξ³ : Sort*) : ((Ξ± βŠ• Ξ²) Γ— Ξ³) ≃ ((Ξ± Γ— Ξ³) βŠ• (Ξ² Γ— Ξ³)) := ⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end, Ξ» s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end, Ξ» p, by rcases p with ⟨_ | _, _⟩; refl, Ξ» s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩ @[simp] theorem sum_prod_distrib_apply_left {Ξ± Ξ² Ξ³} (a : Ξ±) (c : Ξ³) : sum_prod_distrib Ξ± Ξ² Ξ³ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {Ξ± Ξ² Ξ³} (b : Ξ²) (c : Ξ³) : sum_prod_distrib Ξ± Ξ² Ξ³ (sum.inr b, c) = sum.inr (b, c) := rfl def prod_sum_distrib (Ξ± Ξ² Ξ³ : Sort*) : (Ξ± Γ— (Ξ² βŠ• Ξ³)) ≃ ((Ξ± Γ— Ξ²) βŠ• (Ξ± Γ— Ξ³)) := calc (Ξ± Γ— (Ξ² βŠ• Ξ³)) ≃ ((Ξ² βŠ• Ξ³) Γ— Ξ±) : prod_comm _ _ ... ≃ ((Ξ² Γ— Ξ±) βŠ• (Ξ³ Γ— Ξ±)) : sum_prod_distrib _ _ _ ... ≃ ((Ξ± Γ— Ξ²) βŠ• (Ξ± Γ— Ξ³)) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {Ξ± Ξ² Ξ³} (a : Ξ±) (b : Ξ²) : prod_sum_distrib Ξ± Ξ² Ξ³ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {Ξ± Ξ² Ξ³} (a : Ξ±) (c : Ξ³) : prod_sum_distrib Ξ± Ξ² Ξ³ (a, sum.inr c) = sum.inr (a, c) := rfl def bool_prod_equiv_sum (Ξ± : Type u) : (bool Γ— Ξ±) ≃ (Ξ± βŠ• Ξ±) := calc (bool Γ— Ξ±) ≃ ((unit βŠ• unit) Γ— Ξ±) : prod_congr bool_equiv_punit_sum_punit (equiv.refl _) ... ≃ (Ξ± Γ— (unit βŠ• unit)) : prod_comm _ _ ... ≃ ((Ξ± Γ— unit) βŠ• (Ξ± Γ— unit)) : prod_sum_distrib _ _ _ ... ≃ (Ξ± βŠ• Ξ±) : sum_congr (prod_punit _) (prod_punit _) end section open sum nat def nat_equiv_nat_sum_punit : β„• ≃ (β„• βŠ• punit.{u+1}) := ⟨λ n, match n with zero := inr punit.star | succ a := inl a end, Ξ» s, match s with inl n := succ n | inr punit.star := zero end, Ξ» n, begin cases n, repeat { refl } end, Ξ» s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩ @[simp] def nat_sum_punit_equiv_nat : (β„• βŠ• punit.{u+1}) ≃ β„• := nat_equiv_nat_sum_punit.symm def int_equiv_nat_sum_nat : β„€ ≃ (β„• βŠ• β„•) := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} end def list_equiv_of_equiv {Ξ± Ξ² : Type*} : Ξ± ≃ Ξ² β†’ list Ξ± ≃ list Ξ² | ⟨f, g, l, r⟩ := by refine ⟨list.map f, list.map g, Ξ» x, _, Ξ» x, _⟩; simp [id_of_left_inverse l, id_of_right_inverse r] def fin_equiv_subtype (n : β„•) : fin n ≃ {m // m < n} := ⟨λ x, ⟨x.1, x.2⟩, Ξ» x, ⟨x.1, x.2⟩, Ξ» ⟨a, b⟩, rfl,Ξ» ⟨a, b⟩, rfl⟩ def decidable_eq_of_equiv [decidable_eq Ξ²] (e : Ξ± ≃ Ξ²) : decidable_eq Ξ± | a₁ aβ‚‚ := decidable_of_iff (e a₁ = e aβ‚‚) e.bijective.1.eq_iff def inhabited_of_equiv [inhabited Ξ²] (e : Ξ± ≃ Ξ²) : inhabited Ξ± := ⟨e.symm (default _)⟩ def unique_of_equiv (e : Ξ± ≃ Ξ²) (h : unique Ξ²) : unique Ξ± := unique.of_surjective e.symm.bijective.2 def unique_congr (e : Ξ± ≃ Ξ²) : unique Ξ± ≃ unique Ξ² := { to_fun := e.symm.unique_of_equiv, inv_fun := e.unique_of_equiv, left_inv := Ξ» _, subsingleton.elim _ _, right_inv := Ξ» _, subsingleton.elim _ _ } section open subtype def subtype_congr {p : Ξ± β†’ Prop} {q : Ξ² β†’ Prop} (e : Ξ± ≃ Ξ²) (h : βˆ€ a, p a ↔ q (e a)) : {a : Ξ± // p a} ≃ {b : Ξ² // q b} := ⟨λ x, ⟨e x.1, (h _).1 x.2⟩, Ξ» y, ⟨e.symm y.1, (h _).2 (by simp; exact y.2)⟩, Ξ» ⟨x, h⟩, subtype.eq' $ by simp, Ξ» ⟨y, h⟩, subtype.eq' $ by simp⟩ def subtype_equiv_of_subtype' {p : Ξ± β†’ Prop} (e : Ξ± ≃ Ξ²) : {a : Ξ± // p a} ≃ {b : Ξ² // p (e.symm b)} := subtype_congr e $ by simp def subtype_congr_prop {Ξ± : Type*} {p q : Ξ± β†’ Prop} (h : p = q) : subtype p ≃ subtype q := subtype_congr (equiv.refl Ξ±) (assume a, h β–Έ iff.refl _) def set_congr {Ξ± : Type*} {s t : set Ξ±} (h : s = t) : s ≃ t := subtype_congr_prop h def subtype_subtype_equiv_subtype {Ξ± : Type u} (p : Ξ± β†’ Prop) (q : subtype p β†’ Prop) : subtype q ≃ {a : Ξ± // βˆƒh:p a, q ⟨a, h⟩ } := ⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩, λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by cases ha; exact ha_h⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, hβ‚‚βŸ©, rfl⟩ /-- aka coimage -/ def equiv_sigma_subtype {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β†’ Ξ²) : Ξ± ≃ Ξ£ b, {x : Ξ± // f x = b} := ⟨λ x, ⟨f x, x, rfl⟩, Ξ» x, x.2.1, Ξ» x, rfl, Ξ» ⟨b, x, H⟩, sigma.eq H $ eq.drec_on H $ subtype.eq rfl⟩ def pi_equiv_subtype_sigma (ΞΉ : Type*) (Ο€ : ΞΉ β†’ Type*) : (Ξ i, Ο€ i) ≃ {f : ΞΉ β†’ Ξ£i, Ο€ i | βˆ€i, (f i).1 = i } := ⟨ Ξ»f, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, Ξ»f i, begin rw ← f.2 i, exact (f.1 i).2 end, assume f, funext $ assume i, rfl, assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $ eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩ def subtype_pi_equiv_pi {Ξ± : Sort u} {Ξ² : Ξ± β†’ Sort v} {p : Ξ a, Ξ² a β†’ Prop} : {f : Ξ a, Ξ² a // βˆ€a, p a (f a) } ≃ Ξ a, { b : Ξ² a // p a b } := ⟨λf a, ⟨f.1 a, f.2 a⟩, Ξ»f, ⟨λa, (f a).1, Ξ»a, (f a).2⟩, by rintro ⟨f, h⟩; refl, by rintro f; funext a; exact subtype.eq' rfl⟩ end section local attribute [elab_with_expected_type] quot.lift def quot_equiv_of_quot' {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} (e : Ξ± ≃ Ξ²) (h : βˆ€ a a', r a a' ↔ s (e a) (e a')) : quot r ≃ quot s := ⟨quot.lift (Ξ» a, quot.mk _ (e a)) (Ξ» a a' H, quot.sound ((h a a').mp H)), quot.lift (Ξ» b, quot.mk _ (e.symm b)) (Ξ» b b' H, quot.sound ((h _ _).mpr (by convert H; simp))), quot.ind $ by simp, quot.ind $ by simp⟩ def quot_equiv_of_quot {r : Ξ± β†’ Ξ± β†’ Prop} (e : Ξ± ≃ Ξ²) : quot r ≃ quot (Ξ» b b', r (e.symm b) (e.symm b')) := quot_equiv_of_quot' e (by simp) end namespace set open set protected def univ (Ξ±) : @univ Ξ± ≃ Ξ± := ⟨subtype.val, Ξ» a, ⟨a, trivial⟩, Ξ» ⟨a, _⟩, rfl, Ξ» a, rfl⟩ protected def empty (Ξ±) : (βˆ… : set Ξ±) ≃ empty := equiv_empty $ Ξ» ⟨x, h⟩, not_mem_empty x h protected def pempty (Ξ±) : (βˆ… : set Ξ±) ≃ pempty := equiv_pempty $ Ξ» ⟨x, h⟩, not_mem_empty x h protected def union' {Ξ±} {s t : set Ξ±} (p : Ξ± β†’ Prop) [decidable_pred p] (hs : βˆ€ x ∈ s, p x) (ht : βˆ€ x ∈ t, Β¬ p x) : (s βˆͺ t : set Ξ±) ≃ (s βŠ• t) := ⟨λ ⟨x, h⟩, if hp : p x then sum.inl ⟨_, h.resolve_right (Ξ» xt, ht _ xt hp)⟩ else sum.inr ⟨_, h.resolve_left (Ξ» xs, hp (hs _ xs))⟩, Ξ» o, match o with | (sum.inl ⟨x, h⟩) := ⟨x, or.inl h⟩ | (sum.inr ⟨x, h⟩) := ⟨x, or.inr h⟩ end, Ξ» ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, union'._match_2, h]; congr, Ξ» o, by rcases o with ⟨x, h⟩ | ⟨x, h⟩; simp [union'._match_1, union'._match_2, h]; [simp [hs _ h], simp [ht _ h]]⟩ protected def union {Ξ±} {s t : set Ξ±} [decidable_pred s] (H : s ∩ t = βˆ…) : (s βˆͺ t : set Ξ±) ≃ (s βŠ• t) := set.union' s (Ξ» _, id) (Ξ» x xt xs, subset_empty_iff.2 H ⟨xs, xt⟩) protected def singleton {Ξ±} (a : Ξ±) : ({a} : set Ξ±) ≃ punit.{u} := ⟨λ _, punit.star, Ξ» _, ⟨a, mem_singleton _⟩, Ξ» ⟨x, h⟩, by simp at h; subst x, Ξ» ⟨⟩, rfl⟩ protected def insert {Ξ±} {s : set.{u} Ξ±} [decidable_pred s] {a : Ξ±} (H : a βˆ‰ s) : (insert a s : set Ξ±) ≃ (s βŠ• punit.{u+1}) := by rw ← union_singleton; exact (set.union $ inter_singleton_eq_empty.2 H).trans (sum_congr (equiv.refl _) (set.singleton _)) protected def sum_compl {Ξ±} (s : set Ξ±) [decidable_pred s] : (s βŠ• (-s : set Ξ±)) ≃ Ξ± := (set.union (inter_compl_self _)).symm.trans (by rw union_compl_self; exact set.univ _) protected def union_sum_inter {Ξ± : Type u} (s t : set Ξ±) [decidable_pred s] : ((s βˆͺ t : set Ξ±) βŠ• (s ∩ t : set Ξ±)) ≃ (s βŠ• t) := calc ((s βˆͺ t : set Ξ±) βŠ• (s ∩ t : set Ξ±)) ≃ ((s βˆͺ t \ s : set Ξ±) βŠ• (s ∩ t : set Ξ±)) : by rw [union_diff_self] ... ≃ ((s βŠ• (t \ s : set Ξ±)) βŠ• (s ∩ t : set Ξ±)) : sum_congr (set.union (inter_diff_self _ _)) (equiv.refl _) ... ≃ (s βŠ• (t \ s : set Ξ±) βŠ• (s ∩ t : set Ξ±)) : sum_assoc _ _ _ ... ≃ (s βŠ• (t \ s βˆͺ s ∩ t : set Ξ±)) : sum_congr (equiv.refl _) begin refine (set.union' (βˆ‰ s) _ _).symm, exacts [Ξ» x hx, hx.2, Ξ» x hx, not_not_intro hx.1] end ... ≃ (s βŠ• t) : by rw (_ : t \ s βˆͺ s ∩ t = t); rw [union_comm, inter_comm, inter_union_diff] protected def prod {Ξ± Ξ²} (s : set Ξ±) (t : set Ξ²) : (s.prod t) ≃ (s Γ— t) := ⟨λp, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩, Ξ»p, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩, Ξ» ⟨⟨x, y⟩, ⟨h₁, hβ‚‚βŸ©βŸ©, rfl, Ξ» ⟨⟨x, hβ‚βŸ©, ⟨y, hβ‚‚βŸ©βŸ©, rfl⟩ protected noncomputable def image {Ξ± Ξ²} (f : Ξ± β†’ Ξ²) (s : set Ξ±) (H : injective f) : s ≃ (f '' s) := ⟨λ ⟨x, h⟩, ⟨f x, mem_image_of_mem _ h⟩, Ξ» ⟨y, h⟩, ⟨classical.some h, (classical.some_spec h).1⟩, Ξ» ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).2), Ξ» ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ @[simp] theorem image_apply {Ξ± Ξ²} (f : Ξ± β†’ Ξ²) (s : set Ξ±) (H : injective f) (a h) : set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl protected noncomputable def range {Ξ± Ξ²} (f : Ξ± β†’ Ξ²) (H : injective f) : Ξ± ≃ range f := (set.univ _).symm.trans $ (set.image f univ H).trans (equiv.cast $ by rw image_univ) @[simp] theorem range_apply {Ξ± Ξ²} (f : Ξ± β†’ Ξ²) (H : injective f) (a) : set.range f H a = ⟨f a, set.mem_range_self _⟩ := by dunfold equiv.set.range equiv.set.univ; simp [set_coe_cast, -image_univ, image_univ.symm] end set noncomputable def of_bijective {Ξ± Ξ²} {f : Ξ± β†’ Ξ²} (hf : bijective f) : Ξ± ≃ Ξ² := ⟨f, Ξ» x, classical.some (hf.2 x), Ξ» x, hf.1 (classical.some_spec (hf.2 (f x))), Ξ» x, classical.some_spec (hf.2 x)⟩ @[simp] theorem of_bijective_to_fun {Ξ± Ξ²} {f : Ξ± β†’ Ξ²} (hf : bijective f) : (of_bijective hf : Ξ± β†’ Ξ²) = f := rfl lemma subtype_quotient_equiv_quotient_subtype (p₁ : Ξ± β†’ Prop) [s₁ : setoid Ξ±] [sβ‚‚ : setoid (subtype p₁)] (pβ‚‚ : quotient s₁ β†’ Prop) (hpβ‚‚ : βˆ€ a, p₁ a ↔ pβ‚‚ ⟦a⟧) (h : βˆ€ x y : subtype p₁, @setoid.r _ sβ‚‚ x y ↔ (x : Ξ±) β‰ˆ y) : {x // pβ‚‚ x} ≃ quotient sβ‚‚ := { to_fun := Ξ» a, quotient.hrec_on a.1 (Ξ» a h, ⟦⟨a, (hpβ‚‚ _).2 h⟩⟧) (Ξ» a b hab, hfunext (by rw quotient.sound hab) (Ξ» h₁ hβ‚‚ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2, inv_fun := Ξ» a, quotient.lift_on a (Ξ» a, (⟨⟦a.1⟧, (hpβ‚‚ _).1 a.2⟩ : {x // pβ‚‚ x})) (Ξ» a b hab, subtype.eq' (quotient.sound ((h _ _).1 hab))), left_inv := Ξ» ⟨a, ha⟩, quotient.induction_on a (Ξ» a ha, rfl) ha, right_inv := Ξ» a, quotient.induction_on a (Ξ» ⟨a, ha⟩, rfl) } section swap variable [decidable_eq Ξ±] open decidable def swap_core (a b r : Ξ±) : Ξ± := if r = a then b else if r = b then a else r theorem swap_core_self (r a : Ξ±) : swap_core a a r = r := by unfold swap_core; split_ifs; cc theorem swap_core_swap_core (r a b : Ξ±) : swap_core a b (swap_core a b r) = r := by unfold swap_core; split_ifs; cc theorem swap_core_comm (r a b : Ξ±) : swap_core a b r = swap_core b a r := by unfold swap_core; split_ifs; cc /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : Ξ±) : perm Ξ± := ⟨swap_core a b, swap_core a b, Ξ»r, swap_core_swap_core r a b, Ξ»r, swap_core_swap_core r a b⟩ theorem swap_self (a : Ξ±) : swap a a = equiv.refl _ := eq_of_to_fun_eq $ funext $ Ξ» r, swap_core_self r a theorem swap_comm (a b : Ξ±) : swap a b = swap b a := eq_of_to_fun_eq $ funext $ Ξ» r, swap_core_comm r _ _ theorem swap_apply_def (a b x : Ξ±) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : Ξ±) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : Ξ±) : swap a b b = a := by by_cases b = a; simp [swap_apply_def, *] theorem swap_apply_of_ne_of_ne {a b x : Ξ±} : x β‰  a β†’ x β‰  b β†’ swap a b x = x := by simp [swap_apply_def] {contextual := tt} @[simp] theorem swap_swap (a b : Ξ±) : (swap a b).trans (swap a b) = equiv.refl _ := eq_of_to_fun_eq $ funext $ Ξ» x, swap_core_swap_core _ _ _ theorem swap_comp_apply {a b x : Ξ±} (Ο€ : perm Ξ±) : Ο€.trans (swap a b) x = if Ο€ x = a then b else if Ο€ x = b then a else Ο€ x := by cases Ο€; refl @[simp] lemma swap_inv {Ξ± : Type*} [decidable_eq Ξ±] (x y : Ξ±) : (swap x y)⁻¹ = swap x y := rfl @[simp] lemma symm_trans_swap_trans [decidable_eq Ξ±] [decidable_eq Ξ²] (a b : Ξ±) (e : Ξ± ≃ Ξ²) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext _ _ (Ξ» x, begin have : βˆ€ a, e.symm x = a ↔ x = e a := Ξ» a, by rw @eq_comm _ (e.symm x); split; intros; simp * at *, simp [swap_apply_def, this], split_ifs; simp end) @[simp] lemma swap_mul_self {Ξ± : Type*} [decidable_eq Ξ±] (i j : Ξ±) : swap i j * swap i j = 1 := equiv.swap_swap i j @[simp] lemma swap_apply_self {Ξ± : Type*} [decidable_eq Ξ±] (i j a : Ξ±) : swap i j (swap i j a) = a := by rw [← perm.mul_apply, swap_mul_self, perm.one_apply] /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : Ξ± ≃ Ξ²) (a : Ξ±) (b : Ξ²) : Ξ± ≃ Ξ² := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : Ξ± ≃ Ξ²) (a : Ξ±) (b : Ξ²) : set_value f a b a = b := by dsimp [set_value]; simp [swap_apply_left] end swap end equiv instance {Ξ±} [subsingleton Ξ±] : subsingleton (ulift Ξ±) := equiv.ulift.subsingleton instance {Ξ±} [subsingleton Ξ±] : subsingleton (plift Ξ±) := equiv.plift.subsingleton instance {Ξ±} [decidable_eq Ξ±] : decidable_eq (ulift Ξ±) := equiv.ulift.decidable_eq instance {Ξ±} [decidable_eq Ξ±] : decidable_eq (plift Ξ±) := equiv.plift.decidable_eq def unique_unique_equiv : unique (unique Ξ±) ≃ unique Ξ± := { to_fun := Ξ» h, h.default, inv_fun := Ξ» h, { default := h, uniq := Ξ» _, subsingleton.elim _ _ }, left_inv := Ξ» _, subsingleton.elim _ _, right_inv := Ξ» _, subsingleton.elim _ _ } def equiv_of_unique_of_unique [unique Ξ±] [unique Ξ²] : Ξ± ≃ Ξ² := { to_fun := Ξ» _, default Ξ², inv_fun := Ξ» _, default Ξ±, left_inv := Ξ» _, subsingleton.elim _ _, right_inv := Ξ» _, subsingleton.elim _ _ } def equiv_punit_of_unique [unique Ξ±] : Ξ± ≃ punit.{v} := equiv_of_unique_of_unique namespace quot /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr {Ξ±} {r r' : Ξ± β†’ Ξ± β†’ Prop} (eq : βˆ€a b, r a b ↔ r' a b) : quot r ≃ quot r' := ⟨quot.map r r' (assume a b, (eq a b).1), quot.map r' r (assume a b, (eq a b).2), by rintros ⟨a⟩; refl, by rintros ⟨a⟩; refl⟩ end quot namespace quotient protected def congr {Ξ±} {r r' : setoid Ξ±} (eq : βˆ€a b, @setoid.r Ξ± r a b ↔ @setoid.r Ξ± r' a b) : quotient r ≃ quotient r' := quot.congr eq end quotient
9ba90c99b46f57e6bf2a27021d977a22ca233b76
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/polynomial/scale_roots.lean
1db0705f98b5b574cc0c7e9c309d7d66a4d4363e
[ "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
5,325
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Devon Tuma -/ import ring_theory.non_zero_divisors import data.polynomial.algebra_map /-! # Scaling the roots of a polynomial This file defines `scale_roots p s` for a polynomial `p` in one variable and a ring element `s` to be the polynomial with root `r * s` for each root `r` of `p` and proves some basic results about it. -/ section scale_roots variables {A K R S : Type*} [comm_ring A] [is_domain A] [field K] [comm_ring R] [comm_ring S] variables {M : submonoid A} open polynomial open_locale big_operators /-- `scale_roots p s` is a polynomial with root `r * s` for each root `r` of `p`. -/ noncomputable def scale_roots (p : polynomial R) (s : R) : polynomial R := βˆ‘ i in p.support, monomial i (p.coeff i * s ^ (p.nat_degree - i)) @[simp] lemma coeff_scale_roots (p : polynomial R) (s : R) (i : β„•) : (scale_roots p s).coeff i = coeff p i * s ^ (p.nat_degree - i) := by simp [scale_roots, coeff_monomial] {contextual := tt} lemma coeff_scale_roots_nat_degree (p : polynomial R) (s : R) : (scale_roots p s).coeff p.nat_degree = p.leading_coeff := by rw [leading_coeff, coeff_scale_roots, tsub_self, pow_zero, mul_one] @[simp] lemma zero_scale_roots (s : R) : scale_roots 0 s = 0 := by { ext, simp } lemma scale_roots_ne_zero {p : polynomial R} (hp : p β‰  0) (s : R) : scale_roots p s β‰  0 := begin intro h, have : p.coeff p.nat_degree β‰  0 := mt leading_coeff_eq_zero.mp hp, have : (scale_roots p s).coeff p.nat_degree = 0 := congr_fun (congr_arg (coeff : polynomial R β†’ β„• β†’ R) h) p.nat_degree, rw [coeff_scale_roots_nat_degree] at this, contradiction end lemma support_scale_roots_le (p : polynomial R) (s : R) : (scale_roots p s).support ≀ p.support := by { intro, simpa using left_ne_zero_of_mul } lemma support_scale_roots_eq (p : polynomial R) {s : R} (hs : s ∈ non_zero_divisors R) : (scale_roots p s).support = p.support := le_antisymm (support_scale_roots_le p s) begin intro i, simp only [coeff_scale_roots, polynomial.mem_support_iff], intros p_ne_zero ps_zero, have := ((non_zero_divisors R).pow_mem hs (p.nat_degree - i)) _ ps_zero, contradiction end @[simp] lemma degree_scale_roots (p : polynomial R) {s : R} : degree (scale_roots p s) = degree p := begin haveI := classical.prop_decidable, by_cases hp : p = 0, { rw [hp, zero_scale_roots] }, have := scale_roots_ne_zero hp s, refine le_antisymm (finset.sup_mono (support_scale_roots_le p s)) (degree_le_degree _), rw coeff_scale_roots_nat_degree, intro h, have := leading_coeff_eq_zero.mp h, contradiction, end @[simp] lemma nat_degree_scale_roots (p : polynomial R) (s : R) : nat_degree (scale_roots p s) = nat_degree p := by simp only [nat_degree, degree_scale_roots] lemma monic_scale_roots_iff {p : polynomial R} (s : R) : monic (scale_roots p s) ↔ monic p := by simp only [monic, leading_coeff, nat_degree_scale_roots, coeff_scale_roots_nat_degree] lemma scale_roots_evalβ‚‚_eq_zero {p : polynomial S} (f : S β†’+* R) {r : R} {s : S} (hr : evalβ‚‚ f r p = 0) : evalβ‚‚ f (f s * r) (scale_roots p s) = 0 := calc evalβ‚‚ f (f s * r) (scale_roots p s) = (scale_roots p s).support.sum (Ξ» i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : by simp [evalβ‚‚_eq_sum, sum_def] ... = p.support.sum (Ξ» i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : finset.sum_subset (support_scale_roots_le p s) (Ξ» i hi hi', let this : coeff p i * s ^ (p.nat_degree - i) = 0 := by simpa using hi' in by simp [this]) ... = p.support.sum (Ξ» (i : β„•), f (p.coeff i) * f s ^ (p.nat_degree - i + i) * r ^ i) : finset.sum_congr rfl (Ξ» i hi, by simp_rw [f.map_mul, f.map_pow, pow_add, mul_pow, mul_assoc]) ... = p.support.sum (Ξ» (i : β„•), f s ^ p.nat_degree * (f (p.coeff i) * r ^ i)) : finset.sum_congr rfl (Ξ» i hi, by { rw [mul_assoc, mul_left_comm, tsub_add_cancel_of_le], exact le_nat_degree_of_ne_zero (polynomial.mem_support_iff.mp hi) }) ... = f s ^ p.nat_degree * p.support.sum (Ξ» (i : β„•), (f (p.coeff i) * r ^ i)) : finset.mul_sum.symm ... = f s ^ p.nat_degree * evalβ‚‚ f r p : by { simp [evalβ‚‚_eq_sum, sum_def] } ... = 0 : by rw [hr, _root_.mul_zero] lemma scale_roots_aeval_eq_zero [algebra S R] {p : polynomial S} {r : R} {s : S} (hr : aeval r p = 0) : aeval (algebra_map S R s * r) (scale_roots p s) = 0 := scale_roots_evalβ‚‚_eq_zero (algebra_map S R) hr lemma scale_roots_evalβ‚‚_eq_zero_of_evalβ‚‚_div_eq_zero {p : polynomial A} {f : A β†’+* K} (hf : function.injective f) {r s : A} (hr : evalβ‚‚ f (f r / f s) p = 0) (hs : s ∈ non_zero_divisors A) : evalβ‚‚ f (f r) (scale_roots p s) = 0 := begin convert scale_roots_evalβ‚‚_eq_zero f hr, rw [←mul_div_assoc, mul_comm, mul_div_cancel], exact map_ne_zero_of_mem_non_zero_divisors _ hf hs end lemma scale_roots_aeval_eq_zero_of_aeval_div_eq_zero [algebra A K] (inj : function.injective (algebra_map A K)) {p : polynomial A} {r s : A} (hr : aeval (algebra_map A K r / algebra_map A K s) p = 0) (hs : s ∈ non_zero_divisors A) : aeval (algebra_map A K r) (scale_roots p s) = 0 := scale_roots_evalβ‚‚_eq_zero_of_evalβ‚‚_div_eq_zero inj hr hs end scale_roots
4f23476748a7a82c73513b7e23081c8475af857b
d450724ba99f5b50b57d244eb41fef9f6789db81
/src/mywork/lectures/lecture_27b copy.lean
e9d9ce87aa4b71caa00d0afc7eb3099e93426aa7
[]
no_license
jakekauff/CS2120F21
4f009adeb4ce4a148442b562196d66cc6c04530c
e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad
refs/heads/main
1,693,841,880,030
1,637,604,848,000
1,637,604,848,000
399,946,698
0
0
null
null
null
null
UTF-8
Lean
false
false
18,912
lean
import .lecture_26 import data.set namespace relations section functions variables {Ξ± Ξ² Ξ³ : Type} (r : Ξ± β†’ Ξ² β†’ Prop) local infix `β‰Ί`:50 := r /- SINGLE-VALUED BINARY RELATION -/ def single_valued := βˆ€ {x : Ξ±} {y z : Ξ²}, r x y β†’ r x z β†’ y = z #check @single_valued -- property of a relation /- Exercises: Which of the following are single-valued? - r = {(0,1), (0,2)} - r = {(1,0), (2,0)} - the unit circle on ℝ - r = {(-1,0), (0,-1), (1,0), (0,1)} - y = x^2 - x = y^2 - y = + / - square root x - f(x) = 3x+1 - y = sin x - x = sin y -/ /- FUNCTION A single-valued binary relation is also called a function (sometimes a functional binary relation). -/ def function := single_valued r /- One possible property of a relation, r, is the property of being a function, i.e., of r being single-valued. Single-valuedness is a predicate on relations. (This idea is isn't definable in first order predicate logic.) -/ #check @function /- The same vocabulary applies to functions as to relations, as functions are just special cases (single-valued) of otherwise arbitrary binary relations. As with any relation, for example, a function has a domain, Ξ±, a domain of definition, and a co-domain, Ξ². As with any relation, the set of pairs of a function (that we're specifying) is is some subset of Ξ± Γ— Ξ²; or equivalently it is in the powerset of Ξ± Γ— Ξ². When you want to express the idea that you have an arbitrary relation (possible a function) from Ξ± to Ξ², you may write either of the following: - let r βŠ† Ξ± Γ— Ξ² be any relation from Ξ± β†’ Ξ² - let r ∈ 𝒫 (Ξ± Γ— Ξ²) be any relation, Ξ± β†’ Ξ² - let r : Ξ± β†’ Ξ² be any binary relation Be sure you see that these are equivalent statements! A key point is that in addition to a set of pairs a function (or relation) has a domain of definition and a co-domain. Keeping track of exactly how a set of pairs relates to its domain and codomain sets is essential. -/ /- FOR A RELATION TO BE "DEFINED" FOR A VALUE Property: We say that a function is "defined" for some value, (a : Ξ±), if there is some (b : Ξ²), such that the pair, (a,b) is "in" r, i.e., (r a b) is true. -/ def defined (a : Ξ±) := βˆƒ (b : Ξ²), r a b /- Examples: Which is partial, which is total? - the positive square root function for x ∈ ℝ (dom def) - the positive square root function for x ∈ ℝ, x β‰₯ 0 -/ /- THE TOTAL vs PARTIAL FUNCTION DICHOTOMY Property: We say that a function is "total" if it is defined for every value in its domain. Note that this usage of the word "total" is completely distinct from what we learned earlier for relations in general. It's thus better to use "strongly connected" for relations to mean every object is related to another in at least one direction, and to use total to refer to a function that is defined on every element of its domain. -/ def total_function := function r ∧ βˆ€ (a : Ξ±), defined r a /- At this point we expect that for a total function, r, dom_of_def r = domain r. At one key juncture you use the axiom of set extensionality to convert the goal as an equality into that goal as a bi-implication. After that it's basic predicate logical reasoning, rather than more reasoning in set theory terms. -/ example : total_function r β†’ dom_of_def r = dom r := begin assume total_r, cases total_r with func_r defall, unfold dom_of_def, unfold dom, apply set.ext, assume x, split, -- forwards assume h, unfold defined at defall, unfold defined at defall, -- goal completed -- backwards assume h, exact defall x, end /- With that proof down as an example, we return to complete our list of properties of functions: - total - partial - strictly partial Here are the definitions for the remaning two. -/ def strictly_partial_fun := function r ∧ Β¬total_function r def partial_function := function r -- includes total funs /- Mathematicians generally consider the set of partial functions to include the total functions. We will use the term "strictly partial" function to mean a function, f, that is not total, where dom_of_def f ⊊ dom f. (Be sure you see that the subset symbol here means subset but not equal. That's what the slash through the bottom line in the symbol means: strict subset.) -/ /- SURJECTIVE FUNCTIONS A function that "covers" its codomain (where every value in the codomain is an "output" for some value in its domain) is said to map its domain *onto* its entire codomain. Mathematicians will say that such a function is "onto," or "surjective." -/ def surjective := total_function r ∧ βˆ€ (b : Ξ²), βˆƒ a : Ξ±, r a b /- Should this be true? -/ example : surjective r β†’ image_set r (dom r) = { b : Ξ² | true } := begin -- homework (on your own ungraded but please do it!) end /- Which of the following functions are surjective? - y = log x, viewed as a function from ℝ β†’ ℝ⁺ As written, the question is, um, tricky. Let's analyze it. Then we'll give simpler questions. First a little background on logarithmic and exponential functions. Simply put, exponentiation raises a base to an exponent to produce an output, while the logarithm takes and converts it into the exponent to which the base is raised to give the input. From basic algebra, the log (base 10) function, y = log(x), is defined for any positive real, x, and is equal to the exponent to which the base (here 10) must be raised to produce x. Therefore as usually defined its domain of definition is the *positive reals* and its co-domain is (*all of*) the reals. Now consider the question again. The domain of definition of log is the positive reals, so if we expand the domain to all the reals, then the resulting function becomes partial. On the other side, if we restrict the range to the positive reals, then we are excluding from the function all those values in the interval (0,1) from the input side in order to restrict the output to values greater than 0. Self homework: Graph this function. - Ξ» x, log x : ℝ+ β†’ ℝ, bijective? - y = x^2, viewed as a function from ℝ β†’ ℝ - y = x, viewed as a function from ℝ β†’ ℝ - y = sin x, viewed as a function from ℝ β†’ ℝ - y = sin x, as a function from ℝ to [-1,1] ∈ ℝ -/ /- INJECTIVE FUNCTION We have seen that for a relation to be a function, it cannot be "one-to-many" (some x value is associated with more than one y value). On the other hand, it is possible for a function to associate many x values with a single y value. There can be no fan-out from x/domain values to y/codomain values, but there can be fan-in from x to y values. Which is the following functions exhibits "fan-in", with different x values associated with the same y values? y = x y = sin x x = 1 (trick question) y = 1 y = x^2 on ℝ y = x^2 on ℝ⁺ (the positive reals) -/ def injective := total_function r ∧ βˆ€ {x y : Ξ±} {z : Ξ²}, r x z β†’ r y z β†’ x = y /- We will often want to know that a function does not map multiple x values to the same y value. Example: in a company, we will very like want a function that maps each employee to an employee ID number *unique* to that employee. Rather than being "many to one" we call such a function "one-to-one." We also say that such a function has the property of being *injective*. -/ /- We will often want to know that a function does not map multiple x values to the same y value. Example: in a company, we will very like want a function that maps each employee to an employee ID number *unique* to that employee. Rather than being "many to one" we call such a function "one-to-one." We also say that such a function has the property of being *injective*. There is yet another way to understand the concept. -/ /- BIJECTIVE FUNCTIONS -/ /- Finally, a function is called one-to-one and onto, or *bijective* if it is both surjective and injective. In this case, it has to map every element of its domain -/ def bijective := surjective r ∧ injective r /- An essential property of any bijective relation is that it puts the elements of the domain and codomain into a one-to-one correspondence. That we've assumed that a function is total is important here. Here's a counterexample: consider the relation from dom = {1,2,3} to codom = {A, B} with r = {(1,A), (2,B)}. This function is injective and surjective but it clearly does not establish a 1-1 correspondence. We can define what it means for a strictly partial function to be surjective or injective (we don't do it formally here). We say that a partial function is surjective or injective if its domain restriction to its domain of definition (making it total) meets the definitions given above. Note that our use of the term, one-to-one, here is completely distinct from its use in the definition of an injective function. An injective function is said to be "one-to-one" in the sense that it's not many to one: you can't have f(x) = k and f(y)=k where x β‰  y. A one-to-one correspondence *between two sets*, on the other hand, is a pairing of elements that associates each element of one set with a unique single element of the other set, and vice versa. -/ /- Question: Is the inverse of a function always a function. Think about the function, y = x^2. What is its inverse? Is it's inverse a function? There's your answer. A critical property of a bijective function, on the other hand, is that its inverse is also a bijective function. It is easy to see: just reverse the "arrows" in a one-to-one correspondence between two sets. A function who inverse is a function is said to be invertible (as a function, as every relation has and inverse that is again a relation). -/ /- EXERCISE #1: Prove that the inverse of a bijective function is a function. Ok, yes, we will work this one out for you! But you should really read and understand it. Then the rest shouldn't be too bad. -/ example : bijective r β†’ function (inverse r) := begin /- Assume hypothesis -/ assume r_bij, /- Unfold definitions and, from definitions, deduce all the basic facts we'll have to work with. -/ cases r_bij with r_sur r_inj, cases r_inj with r_tot r_one_to_one, cases r_sur with r_tot r_onto, unfold total_function at r_tot, cases r_tot with r_fun alldef, unfold function at r_fun, unfold single_valued at r_fun, unfold defined at alldef, /- What remains to be shown is that the inverse of r is function. Expanding the definition of function, that means r inverse is single-valued. Let's see. -/ unfold function, unfold single_valued, /- To show that r inverse (mapping Ξ² values back to Ξ± values) r is single-valued, assume that b is some value of type Ξ² (in the codomain of r) and show that if r inverse maps b is mapped to both a1 and a2 then a1 = a2. -/ assume b a1 a2 irba1 irba2, /- Key insight: (inverse r) b a means r a b. In other words, r b a is in r inverse (it contains the pair (b, a)) if and only if (a, b) is in r, i.e., r a b. -/ unfold inverse at irba1 irba2, /- With those pairs now turned around, by the injectivity of r, we're there! -/ apply r_one_to_one irba1 irba2, end /- Just to set expectations: The reality is that I explored numerous ways of writing this proof. Often a first proof will be confusing, messy, etc. Most proofs of theorems you see in most mathematics books are gems, polished in their presentations by generations of mathematicians. It took me a little while to get to this proof script and the sequence of reasoning steps and intermediate proof states it traverses. -/ /- INJECTIVE AND SURJECTIVE *PARTIAL* FUNCTIONS Okay, we actually are now able to to define just what is means for a *partial* function to be injective, surjective, bijective, which is that it is so when its domain is restricted to its domain of definition, rendering it total (at which point the preceding definition applies). -/ def injectivep := function r ∧ injective (dom_res r (dom_of_def r)) def surjectivep := function r ∧ surjective (dom_res r (dom_of_def r)) def bijectivep := function r ∧ bijective (dom_res r (dom_of_def r)) -- EXERCISE #2: Prove that the inverse of a bijective function is bijective. example : bijective r β†’ bijective (inverse r) := begin assume bij_r, unfold bijective, unfold bijective at bij_r, cases bij_r with surj_r inj_r, unfold surjective at surj_r, unfold injective at inj_r, cases surj_r with r_tot r_onto, cases inj_r with r_tot r_one_to_one, cases r_tot with r_fun alldef, unfold function at r_fun, unfold single_valued at r_fun, apply and.intro _ _, unfold surjective, unfold total_function, split, split, unfold function, unfold single_valued, unfold inverse, assume b a x rab rxb, apply r_one_to_one rab, exact rxb, assume b, apply r_onto b, unfold inverse, unfold defined at alldef, exact alldef, unfold injective inverse, split, unfold total_function, split, unfold function, unfold single_valued, assume b a z rab rzb, apply r_one_to_one rab rzb, assume b, unfold defined at alldef, apply r_onto b, assume c b a rac rab, apply r_fun rac rab, end /- EXERCISE #3: Prove that the inverse of the inverse of a bijective function is that function. -/ example : bijective r β†’ (r = inverse (inverse r)) := begin assume bijr, unfold inverse, end /- EXERCISE #4: Formally state and prove that every injective function has a *function* as an inverse. -/ example : injective r β†’ function (inverse r) := begin assume injr,-- hint: remember recent work unfold function, unfold single_valued, cases injr with r_tot r_one_to_one, unfold total_function at r_tot, unfold function at r_tot, unfold single_valued at r_tot, unfold defined at r_tot, cases r_tot with r_fun alldef, assume x y z rxy rxz, unfold inverse at rxy, unfold inverse at rxz, apply r_one_to_one rxy rxz, end /- EXERCISE #5. Is bijectivity transitive? In other words, if the relations, s and r, are both bijective, then is the composition, s after r, also always bijective? Now we'll see. -/ open relations -- for definition of composition /- Check the following proposition. True? prove it for all. False? Present a counterexample. -/ def bij_trans (s : Ξ² β†’ Ξ³ β†’ Prop) (r : Ξ± β†’ Ξ² β†’ Prop) : bijective r β†’ bijective s β†’ bijective (composition s r) := begin assume bijr bijs, unfold bijective, apply and.intro _ _, unfold bijective at bijr bijs, cases bijr with r_sur r_inj, cases bijs with s_sur s_inj, unfold surjective, unfold total_function, unfold function, unfold single_valued, unfold surjective at r_sur s_sur, unfold total_function at r_sur s_sur, cases r_sur with r_tot r_onto, cases s_sur with s_tot s_onto, unfold function at r_tot s_tot, unfold single_valued at r_tot s_tot, cases r_tot with r_fun r_alldef, cases s_tot with s_fun s_alldef, unfold injective at r_inj s_inj, cases r_inj with r_tot r_one_to_one, cases s_inj with s_tot s_one_to_one, unfold total_function at r_tot s_tot, unfold function at r_tot s_tot, unfold single_valued at r_tot s_tot, unfold defined at r_tot s_tot r_alldef s_alldef, cases r_tot with r_fun alldef_r, cases s_tot with s_fun alldef_s, split, split, unfold composition, assume x y z, assume h i, apply exists.elim h, apply exists.elim i, assume b sbz_rxb, assume t sty_rxt, have rxb := sbz_rxb.right, have rxt := sty_rxt.right, have bt := r_fun rxb rxt, have sbz := sbz_rxb.left, have sty := sty_rxt.left, have stz : s t z := eq.subst bt sbz, apply s_fun sty stz, assume i, unfold defined, have sr := composition s r, have idd := sr i, have idd2 := alldef_r i, unfold composition, cases idd2 with beta ribeta, have idd3 := alldef_s beta, cases idd3 with g sbetag, apply exists.intro, apply exists.intro, apply and.intro sbetag ribeta, assume g, unfold composition, have sr := composition s r, have idd := s_onto g, cases idd with b sbg, have idd2:= r_onto b, cases idd2 with a rab, apply exists.intro, apply exists.intro, apply and.intro sbg rab, unfold bijective at bijr bijs, cases bijr with r_sur r_inj, cases bijs with s_sur s_inj, unfold injective, unfold total_function, unfold function, unfold single_valued, unfold surjective at r_sur s_sur, unfold total_function at r_sur s_sur, cases r_sur with r_tot r_onto, cases s_sur with s_tot s_onto, unfold function at r_tot s_tot, unfold single_valued at r_tot s_tot, cases r_tot with r_fun r_alldef, cases s_tot with s_fun s_alldef, unfold injective at r_inj s_inj, cases r_inj with r_tot r_one_to_one, cases s_inj with s_tot s_one_to_one, unfold total_function at r_tot s_tot, unfold function at r_tot s_tot, unfold single_valued at r_tot s_tot, unfold defined at r_tot s_tot r_alldef s_alldef, cases r_tot with r_fun alldef_r, cases s_tot with s_fun alldef_s, split, split, unfold composition, assume x y z, assume h i, apply exists.elim h, apply exists.elim i, assume b sbz_rxb, assume t sty_rxt, have sbz := sbz_rxb.left, have sty := sty_rxt.left, have rxb := sbz_rxb.right, have rxt := sty_rxt.right, have bt := r_fun rxb rxt, have stz : s t z := eq.subst bt sbz, apply s_fun sty stz, assume i, unfold defined, have sr := composition s r, have idd := sr i, have idd2 := alldef_r i, unfold composition, cases idd2 with beta ribeta, have idd3 := alldef_s beta, cases idd3 with g sbetag, apply exists.intro, apply exists.intro, apply and.intro sbetag ribeta, assume i, unfold composition, have sr := composition s r, assume a g, assume e_sbg_rib e_sbg_rab, cases e_sbg_rib with b sbg_rib, cases e_sbg_rab with t stg_rat, have sbg := sbg_rib.left, have stg := stg_rat.left, have rib := sbg_rib.right, have rat := stg_rat.right, have bt := s_one_to_one sbg stg, have rit : r i t := eq.subst bt rib, apply r_one_to_one rit rat, end /- In general, an operation (such as inverse, here) that, when applied twice, is the identity, is said to be an involution. Relational inverse on bijective functions is involutive in this sense. A visualization: each green ball here goes to a red ball there and the inverse takes each red ball right back to the green ball from which it came, leaving the original green ball as the end result, as well. An identity function. -/ end functions end relations
a8fff60a75d41d03aeb2d04f246e78b2ec9091ed
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/special_functions/log/base.lean
55ad5d89c3c362c58fbaaf0ed25d9764b62369b4
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
12,413
lean
/- Copyright (c) 2022 Bolton Bailey. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bolton Bailey, Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle SΓΆnne -/ import analysis.special_functions.pow import data.int.log /-! # Real logarithm base `b` In this file we define `real.logb` to be the logarithm of a real number in a given base `b`. We define this as the division of the natural logarithms of the argument and the base, so that we have a globally defined function with `logb b 0 = 0`, `logb b (-x) = logb b x` `logb 0 x = 0` and `logb (-b) x = logb b x`. We prove some basic properties of this function and its relation to `rpow`. ## Tags logarithm, continuity -/ open set filter function open_locale topology noncomputable theory namespace real variables {b x y : ℝ} /-- The real logarithm in a given base. As with the natural logarithm, we define `logb b x` to be `logb b |x|` for `x < 0`, and `0` for `x = 0`.-/ @[pp_nodot] noncomputable def logb (b x : ℝ) : ℝ := log x / log b lemma log_div_log : log x / log b = logb b x := rfl @[simp] lemma logb_zero : logb b 0 = 0 := by simp [logb] @[simp] lemma logb_one : logb b 1 = 0 := by simp [logb] @[simp] lemma logb_abs (x : ℝ) : logb b (|x|) = logb b x := by rw [logb, logb, log_abs] @[simp] lemma logb_neg_eq_logb (x : ℝ) : logb b (-x) = logb b x := by rw [← logb_abs x, ← logb_abs (-x), abs_neg] lemma logb_mul (hx : x β‰  0) (hy : y β‰  0) : logb b (x * y) = logb b x + logb b y := by simp_rw [logb, log_mul hx hy, add_div] lemma logb_div (hx : x β‰  0) (hy : y β‰  0) : logb b (x / y) = logb b x - logb b y := by simp_rw [logb, log_div hx hy, sub_div] @[simp] lemma logb_inv (x : ℝ) : logb b (x⁻¹) = -logb b x := by simp [logb, neg_div] section b_pos_and_ne_one variable (b_pos : 0 < b) variable (b_ne_one : b β‰  1) include b_pos b_ne_one private lemma log_b_ne_zero : log b β‰  0 := begin have b_ne_zero : b β‰  0, linarith, have b_ne_minus_one : b β‰  -1, linarith, simp [b_ne_one, b_ne_zero, b_ne_minus_one], end @[simp] lemma logb_rpow : logb b (b ^ x) = x := begin rw [logb, div_eq_iff, log_rpow b_pos], exact log_b_ne_zero b_pos b_ne_one, end lemma rpow_logb_eq_abs (hx : x β‰  0) : b ^ (logb b x) = |x| := begin apply log_inj_on_pos, simp only [set.mem_Ioi], apply rpow_pos_of_pos b_pos, simp only [abs_pos, mem_Ioi, ne.def, hx, not_false_iff], rw [log_rpow b_pos, logb, log_abs], field_simp [log_b_ne_zero b_pos b_ne_one], end @[simp] lemma rpow_logb (hx : 0 < x) : b ^ (logb b x) = x := by { rw rpow_logb_eq_abs b_pos b_ne_one (hx.ne'), exact abs_of_pos hx, } lemma rpow_logb_of_neg (hx : x < 0) : b ^ (logb b x) = -x := by { rw rpow_logb_eq_abs b_pos b_ne_one (ne_of_lt hx), exact abs_of_neg hx } lemma surj_on_logb : surj_on (logb b) (Ioi 0) univ := Ξ» x _, ⟨rpow b x, rpow_pos_of_pos b_pos x, logb_rpow b_pos b_ne_one⟩ lemma logb_surjective : surjective (logb b) := Ξ» x, ⟨b ^ x, logb_rpow b_pos b_ne_one⟩ @[simp] lemma range_logb : range (logb b) = univ := (logb_surjective b_pos b_ne_one).range_eq lemma surj_on_logb' : surj_on (logb b) (Iio 0) univ := begin intros x x_in_univ, use -b ^ x, split, { simp only [right.neg_neg_iff, set.mem_Iio], apply rpow_pos_of_pos b_pos, }, { rw [logb_neg_eq_logb, logb_rpow b_pos b_ne_one], }, end end b_pos_and_ne_one section one_lt_b variable (hb : 1 < b) include hb private lemma b_pos : 0 < b := by linarith private lemma b_ne_one : b β‰  1 := by linarith @[simp] lemma logb_le_logb (h : 0 < x) (h₁ : 0 < y) : logb b x ≀ logb b y ↔ x ≀ y := by { rw [logb, logb, div_le_div_right (log_pos hb), log_le_log h h₁], } lemma logb_lt_logb (hx : 0 < x) (hxy : x < y) : logb b x < logb b y := by { rw [logb, logb, div_lt_div_right (log_pos hb)], exact log_lt_log hx hxy, } @[simp] lemma logb_lt_logb_iff (hx : 0 < x) (hy : 0 < y) : logb b x < logb b y ↔ x < y := by { rw [logb, logb, div_lt_div_right (log_pos hb)], exact log_lt_log_iff hx hy, } lemma logb_le_iff_le_rpow (hx : 0 < x) : logb b x ≀ y ↔ x ≀ b ^ y := by rw [←rpow_le_rpow_left_iff hb, rpow_logb (b_pos hb) (b_ne_one hb) hx] lemma logb_lt_iff_lt_rpow (hx : 0 < x) : logb b x < y ↔ x < b ^ y := by rw [←rpow_lt_rpow_left_iff hb, rpow_logb (b_pos hb) (b_ne_one hb) hx] lemma le_logb_iff_rpow_le (hy : 0 < y) : x ≀ logb b y ↔ b ^ x ≀ y := by rw [←rpow_le_rpow_left_iff hb, rpow_logb (b_pos hb) (b_ne_one hb) hy] lemma lt_logb_iff_rpow_lt (hy : 0 < y) : x < logb b y ↔ b ^ x < y := by rw [←rpow_lt_rpow_left_iff hb, rpow_logb (b_pos hb) (b_ne_one hb) hy] lemma logb_pos_iff (hx : 0 < x) : 0 < logb b x ↔ 1 < x := by { rw ← @logb_one b, rw logb_lt_logb_iff hb zero_lt_one hx, } lemma logb_pos (hx : 1 < x) : 0 < logb b x := by { rw logb_pos_iff hb (lt_trans zero_lt_one hx), exact hx, } lemma logb_neg_iff (h : 0 < x) : logb b x < 0 ↔ x < 1 := by { rw ← logb_one, exact logb_lt_logb_iff hb h zero_lt_one, } lemma logb_neg (h0 : 0 < x) (h1 : x < 1) : logb b x < 0 := (logb_neg_iff hb h0).2 h1 lemma logb_nonneg_iff (hx : 0 < x) : 0 ≀ logb b x ↔ 1 ≀ x := by rw [← not_lt, logb_neg_iff hb hx, not_lt] lemma logb_nonneg (hx : 1 ≀ x) : 0 ≀ logb b x := (logb_nonneg_iff hb (zero_lt_one.trans_le hx)).2 hx lemma logb_nonpos_iff (hx : 0 < x) : logb b x ≀ 0 ↔ x ≀ 1 := by rw [← not_lt, logb_pos_iff hb hx, not_lt] lemma logb_nonpos_iff' (hx : 0 ≀ x) : logb b x ≀ 0 ↔ x ≀ 1 := begin rcases hx.eq_or_lt with (rfl|hx), { simp [le_refl, zero_le_one] }, exact logb_nonpos_iff hb hx, end lemma logb_nonpos (hx : 0 ≀ x) (h'x : x ≀ 1) : logb b x ≀ 0 := (logb_nonpos_iff' hb hx).2 h'x lemma strict_mono_on_logb : strict_mono_on (logb b) (set.Ioi 0) := Ξ» x hx y hy hxy, logb_lt_logb hb hx hxy lemma strict_anti_on_logb : strict_anti_on (logb b) (set.Iio 0) := begin rintros x (hx : x < 0) y (hy : y < 0) hxy, rw [← logb_abs y, ← logb_abs x], refine logb_lt_logb hb (abs_pos.2 hy.ne) _, rwa [abs_of_neg hy, abs_of_neg hx, neg_lt_neg_iff], end lemma logb_inj_on_pos : set.inj_on (logb b) (set.Ioi 0) := (strict_mono_on_logb hb).inj_on lemma eq_one_of_pos_of_logb_eq_zero (h₁ : 0 < x) (hβ‚‚ : logb b x = 0) : x = 1 := logb_inj_on_pos hb (set.mem_Ioi.2 h₁) (set.mem_Ioi.2 zero_lt_one) (hβ‚‚.trans real.logb_one.symm) lemma logb_ne_zero_of_pos_of_ne_one (hx_pos : 0 < x) (hx : x β‰  1) : logb b x β‰  0 := mt (eq_one_of_pos_of_logb_eq_zero hb hx_pos) hx lemma tendsto_logb_at_top : tendsto (logb b) at_top at_top := tendsto.at_top_div_const (log_pos hb) tendsto_log_at_top end one_lt_b section b_pos_and_b_lt_one variable (b_pos : 0 < b) variable (b_lt_one : b < 1) include b_lt_one private lemma b_ne_one : b β‰  1 := by linarith include b_pos @[simp] lemma logb_le_logb_of_base_lt_one (h : 0 < x) (h₁ : 0 < y) : logb b x ≀ logb b y ↔ y ≀ x := by { rw [logb, logb, div_le_div_right_of_neg (log_neg b_pos b_lt_one), log_le_log h₁ h], } lemma logb_lt_logb_of_base_lt_one (hx : 0 < x) (hxy : x < y) : logb b y < logb b x := by { rw [logb, logb, div_lt_div_right_of_neg (log_neg b_pos b_lt_one)], exact log_lt_log hx hxy, } @[simp] lemma logb_lt_logb_iff_of_base_lt_one (hx : 0 < x) (hy : 0 < y) : logb b x < logb b y ↔ y < x := by { rw [logb, logb, div_lt_div_right_of_neg (log_neg b_pos b_lt_one)], exact log_lt_log_iff hy hx } lemma logb_le_iff_le_rpow_of_base_lt_one (hx : 0 < x) : logb b x ≀ y ↔ b ^ y ≀ x := by rw [←rpow_le_rpow_left_iff_of_base_lt_one b_pos b_lt_one, rpow_logb b_pos (b_ne_one b_lt_one) hx] lemma logb_lt_iff_lt_rpow_of_base_lt_one (hx : 0 < x) : logb b x < y ↔ b ^ y < x := by rw [←rpow_lt_rpow_left_iff_of_base_lt_one b_pos b_lt_one, rpow_logb b_pos (b_ne_one b_lt_one) hx] lemma le_logb_iff_rpow_le_of_base_lt_one (hy : 0 < y) : x ≀ logb b y ↔ y ≀ b ^ x := by rw [←rpow_le_rpow_left_iff_of_base_lt_one b_pos b_lt_one, rpow_logb b_pos (b_ne_one b_lt_one) hy] lemma lt_logb_iff_rpow_lt_of_base_lt_one (hy : 0 < y) : x < logb b y ↔ y < b ^ x := by rw [←rpow_lt_rpow_left_iff_of_base_lt_one b_pos b_lt_one, rpow_logb b_pos (b_ne_one b_lt_one) hy] lemma logb_pos_iff_of_base_lt_one (hx : 0 < x) : 0 < logb b x ↔ x < 1 := by rw [← @logb_one b, logb_lt_logb_iff_of_base_lt_one b_pos b_lt_one zero_lt_one hx] lemma logb_pos_of_base_lt_one (hx : 0 < x) (hx' : x < 1) : 0 < logb b x := by { rw logb_pos_iff_of_base_lt_one b_pos b_lt_one hx, exact hx', } lemma logb_neg_iff_of_base_lt_one (h : 0 < x) : logb b x < 0 ↔ 1 < x := by rw [← @logb_one b, logb_lt_logb_iff_of_base_lt_one b_pos b_lt_one h zero_lt_one] lemma logb_neg_of_base_lt_one (h1 : 1 < x) : logb b x < 0 := (logb_neg_iff_of_base_lt_one b_pos b_lt_one (lt_trans zero_lt_one h1)).2 h1 lemma logb_nonneg_iff_of_base_lt_one (hx : 0 < x) : 0 ≀ logb b x ↔ x ≀ 1 := by rw [← not_lt, logb_neg_iff_of_base_lt_one b_pos b_lt_one hx, not_lt] lemma logb_nonneg_of_base_lt_one (hx : 0 < x) (hx' : x ≀ 1) : 0 ≀ logb b x := by {rw [logb_nonneg_iff_of_base_lt_one b_pos b_lt_one hx], exact hx' } lemma logb_nonpos_iff_of_base_lt_one (hx : 0 < x) : logb b x ≀ 0 ↔ 1 ≀ x := by rw [← not_lt, logb_pos_iff_of_base_lt_one b_pos b_lt_one hx, not_lt] lemma strict_anti_on_logb_of_base_lt_one : strict_anti_on (logb b) (set.Ioi 0) := Ξ» x hx y hy hxy, logb_lt_logb_of_base_lt_one b_pos b_lt_one hx hxy lemma strict_mono_on_logb_of_base_lt_one : strict_mono_on (logb b) (set.Iio 0) := begin rintros x (hx : x < 0) y (hy : y < 0) hxy, rw [← logb_abs y, ← logb_abs x], refine logb_lt_logb_of_base_lt_one b_pos b_lt_one (abs_pos.2 hy.ne) _, rwa [abs_of_neg hy, abs_of_neg hx, neg_lt_neg_iff], end lemma logb_inj_on_pos_of_base_lt_one : set.inj_on (logb b) (set.Ioi 0) := (strict_anti_on_logb_of_base_lt_one b_pos b_lt_one).inj_on lemma eq_one_of_pos_of_logb_eq_zero_of_base_lt_one (h₁ : 0 < x) (hβ‚‚ : logb b x = 0) : x = 1 := logb_inj_on_pos_of_base_lt_one b_pos b_lt_one (set.mem_Ioi.2 h₁) (set.mem_Ioi.2 zero_lt_one) (hβ‚‚.trans real.logb_one.symm) lemma logb_ne_zero_of_pos_of_ne_one_of_base_lt_one (hx_pos : 0 < x) (hx : x β‰  1) : logb b x β‰  0 := mt (eq_one_of_pos_of_logb_eq_zero_of_base_lt_one b_pos b_lt_one hx_pos) hx lemma tendsto_logb_at_top_of_base_lt_one : tendsto (logb b) at_top at_bot := begin rw tendsto_at_top_at_bot, intro e, use 1 βŠ” b ^ e, intro a, simp only [and_imp, sup_le_iff], intro ha, rw logb_le_iff_le_rpow_of_base_lt_one b_pos b_lt_one, tauto, exact lt_of_lt_of_le zero_lt_one ha, end end b_pos_and_b_lt_one lemma floor_logb_nat_cast {b : β„•} {r : ℝ} (hb : 1 < b) (hr : 0 ≀ r) : ⌊logb b rβŒ‹ = int.log b r := begin obtain rfl | hr := hr.eq_or_lt, { rw [logb_zero, int.log_zero_right, int.floor_zero] }, have hb1' : 1 < (b : ℝ) := nat.one_lt_cast.mpr hb, apply le_antisymm, { rw [←int.zpow_le_iff_le_log hb hr, ←rpow_int_cast b], refine le_of_le_of_eq _ (rpow_logb (zero_lt_one.trans hb1') hb1'.ne' hr), exact rpow_le_rpow_of_exponent_le hb1'.le (int.floor_le _) }, { rw [int.le_floor, le_logb_iff_rpow_le hb1' hr, rpow_int_cast], exact int.zpow_log_le_self hb hr } end lemma ceil_logb_nat_cast {b : β„•} {r : ℝ} (hb : 1 < b) (hr : 0 ≀ r) : ⌈logb b rβŒ‰ = int.clog b r := begin obtain rfl | hr := hr.eq_or_lt, { rw [logb_zero, int.clog_zero_right, int.ceil_zero] }, have hb1' : 1 < (b : ℝ) := nat.one_lt_cast.mpr hb, apply le_antisymm, { rw [int.ceil_le, logb_le_iff_le_rpow hb1' hr, rpow_int_cast], refine int.self_le_zpow_clog hb r }, { rw [←int.le_zpow_iff_clog_le hb hr, ←rpow_int_cast b], refine (rpow_logb (zero_lt_one.trans hb1') hb1'.ne' hr).symm.trans_le _, exact rpow_le_rpow_of_exponent_le hb1'.le (int.le_ceil _) }, end @[simp] lemma logb_eq_zero : logb b x = 0 ↔ b = 0 ∨ b = 1 ∨ b = -1 ∨ x = 0 ∨ x = 1 ∨ x = -1 := begin simp_rw [logb, div_eq_zero_iff, log_eq_zero], tauto, end /- TODO add other limits and continuous API lemmas analogous to those in log.lean -/ open_locale big_operators lemma logb_prod {Ξ± : Type*} (s : finset Ξ±) (f : Ξ± β†’ ℝ) (hf : βˆ€ x ∈ s, f x β‰  0): logb b (∏ i in s, f i) = βˆ‘ i in s, logb b (f i) := begin classical, induction s using finset.induction_on with a s ha ih, { simp }, simp only [finset.mem_insert, forall_eq_or_imp] at hf, simp [ha, ih hf.2, logb_mul hf.1 (finset.prod_ne_zero_iff.2 hf.2)], end end real
5a3f3f0b0472612bb7234bfa2268c27d405dc48a
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Data/Json/Parser.lean
c3d8b434fc95ff8799ee02fe7133d8722d983a6d
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
7,410
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Marc Huisinga -/ import Lean.Data.Json.Basic namespace Lean open Std (RBNode RBNode.singleton RBNode.leaf) inductive Quickparse.Result (Ξ± : Type) where | success (pos : String.Iterator) (res : Ξ±) : Result Ξ± | error (pos : String.Iterator) (err : String) : Result Ξ± def Quickparse (Ξ± : Type) : Type := String.Iterator β†’ Lean.Quickparse.Result Ξ± instance (Ξ± : Type) : Inhabited (Quickparse Ξ±) := ⟨fun it => Quickparse.Result.error it ""⟩ namespace Quickparse open Result partial def skipWs (it : String.Iterator) : String.Iterator := if it.hasNext then let c := it.curr if c = '\u0009' ∨ c = '\u000a' ∨ c = '\u000d' ∨ c = '\u0020' then skipWs it.next else it else it @[inline] protected def pure (a : Ξ±) : Quickparse Ξ± := fun it => success it a @[inline] protected def bind {Ξ± Ξ² : Type} (f : Quickparse Ξ±) (g : Ξ± β†’ Quickparse Ξ²) : Quickparse Ξ² := fun it => match f it with | success rem a => g a rem | error pos msg => error pos msg @[inline] def fail (msg : String) : Quickparse Ξ± := fun it => error it msg @[inline] instance : Monad Quickparse := { pure := @Quickparse.pure, bind := @Quickparse.bind } def unexpectedEndOfInput := "unexpected end of input" @[inline] def peek? : Quickparse (Option Char) := fun it => if it.hasNext then success it it.curr else success it none @[inline] def peek! : Quickparse Char := do let some c ← peek? | fail unexpectedEndOfInput c @[inline] def skip : Quickparse Unit := fun it => success it.next () @[inline] def next : Quickparse Char := do let c ← peek! skip c def expect (s : String) : Quickparse Unit := fun it => if it.extract (it.forward s.length) = s then success (it.forward s.length) () else error it s!"expected: {s}" @[inline] def ws : Quickparse Unit := fun it => success (skipWs it) () def expectedEndOfInput := "expected end of input" @[inline] def eoi : Quickparse Unit := fun it => if it.hasNext then error it expectedEndOfInput else success it () end Quickparse namespace Json.Parser open Quickparse @[inline] def hexChar : Quickparse Nat := do let c ← next if '0' ≀ c ∧ c ≀ '9' then pure $ c.val.toNat - '0'.val.toNat else if 'a' ≀ c ∧ c ≀ 'f' then pure $ c.val.toNat - 'a'.val.toNat else if 'A' ≀ c ∧ c ≀ 'F' then pure $ c.val.toNat - 'A'.val.toNat else fail "invalid hex character" def escapedChar : Quickparse Char := do let c ← next match c with | '\\' => '\\' | '"' => '"' | '/' => '/' | 'b' => '\x08' | 'f' => '\x0c' | 'n' => '\n' | 'r' => '\x0d' | 't' => '\t' | 'u' => let u1 ← hexChar; let u2 ← hexChar; let u3 ← hexChar; let u4 ← hexChar Char.ofNat $ 4096*u1 + 256*u2 + 16*u3 + u4 | _ => fail "illegal \\u escape" partial def strCore (acc : String) : Quickparse String := do let c ← peek! if c = '"' then -- " skip acc else let c ← next let ec ← if c = '\\' then escapedChar -- as to whether c.val > 0xffff should be split up and encoded with multiple \u, -- the JSON standard is not definite: both directly printing the character -- and encoding it with multiple \u is allowed. we choose the former. else if 0x0020 ≀ c.val ∧ c.val ≀ 0x10ffff then c else fail "unexpected character in string" strCore (acc.push ec) def str : Quickparse String := strCore "" partial def natCore (acc digits : Nat) : Quickparse (Nat Γ— Nat) := do let some c ← peek? | (acc, digits) if '0' ≀ c ∧ c ≀ '9' then skip let acc' := 10*acc + (c.val.toNat - '0'.val.toNat) natCore acc' (digits+1) else (acc, digits) @[inline] def lookahead (p : Char β†’ Prop) (desc : String) [DecidablePred p] : Quickparse Unit := do let c ← peek! if p c then () else fail $ "expected " ++ desc @[inline] def natNonZero : Quickparse Nat := do lookahead (fun c => '1' ≀ c ∧ c ≀ '9') "1-9" let (n, _) ← natCore 0 0 n @[inline] def natNumDigits : Quickparse (Nat Γ— Nat) := do lookahead (fun c => '0' ≀ c ∧ c ≀ '9') "digit" natCore 0 0 @[inline] def natMaybeZero : Quickparse Nat := do let (n, _) ← natNumDigits n def num : Quickparse JsonNumber := do let c ← peek! let sign : Int ← if c = '-' then skip pure (-1 : Int) else pure 1 let c ← peek! let res ← if c = '0' then skip pure 0 else natNonZero let c? ← peek? let res : JsonNumber ← if c? = some '.' then skip let (n, d) ← natNumDigits if d > USize.size then fail "too many decimals" let mantissa' := sign * (res * (10^d : Nat) + n) let exponent' := d JsonNumber.mk mantissa' exponent' else JsonNumber.fromInt (sign * res) let c? ← peek? if c? = some 'e' ∨ c? = some 'E' then skip let c ← peek! if c = '-' then skip let n ← natMaybeZero res.shiftr n else if c = '+' then skip let n ← natMaybeZero if n > USize.size then fail "exp too large" res.shiftl n else res partial def arrayCore (anyCore : Unit β†’ Quickparse Json) (acc : Array Json) : Quickparse (Array Json) := do let hd ← anyCore () let acc' := acc.push hd let c ← next if c = ']' then ws acc' else if c = ',' then ws arrayCore anyCore acc' else fail "unexpected character in array" partial def objectCore (anyCore : Unit β†’ Quickparse Json) : Quickparse (RBNode String (fun _ => Json)) := do lookahead (fun c => c = '"') "\""; skip; -- " let k ← strCore ""; ws lookahead (fun c => c = ':') ":"; skip; ws let v ← anyCore () let c ← next if c = '}' then ws RBNode.singleton k v else if c = ',' then ws let kvs ← objectCore anyCore kvs.insert compare k v else fail "unexpected character in object" -- takes a unit parameter so that -- we can use the equation compiler and recursion partial def anyCore (u : Unit) : Quickparse Json := do let c ← peek! if c = '[' then skip; ws let c ← peek! if c = ']' then skip; ws Json.arr (Array.mkEmpty 0) else let a ← arrayCore anyCore (Array.mkEmpty 4) Json.arr a else if c = '{' then skip; ws let c ← peek! if c = '}' then skip; ws Json.obj (RBNode.leaf) else let kvs ← objectCore anyCore Json.obj kvs else if c = '\"' then skip let s ← strCore "" ws Json.str s else if c = 'f' then expect "false"; ws Json.bool false else if c = 't' then expect "true"; ws Json.bool true else if c = 'n' then expect "null"; ws Json.null else if c = '-' ∨ ('0' ≀ c ∧ c ≀ '9') then let n ← num ws Json.num n else fail "unexpected input" def any : Quickparse Json := do ws let res ← anyCore () eoi res end Json.Parser namespace Json def parse (s : String) : Except String Lean.Json := match Json.Parser.any s.mkIterator with | Quickparse.Result.success _ res => Except.ok res | Quickparse.Result.error it err => Except.error s!"offset {it.i.repr}: {err}" end Json end Lean
9c7283a30c10fb786cdfa373a2fb3bf0834b8e5c
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/opaque_hint_bug.lean
12df20a2900703524ac64a7941cd6b84e2bd19b6
[ "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
245
lean
inductive list (T : Type) : Type := | nil {} : list T | cons : T β†’ list T β†’ list T section variable {T : Type} definition concat (s t : list T) : list T := list.rec t (fun x l u, list.cons x u) s attribute concat [reducible] end
e42b7623bbafe153155f05712f11e5d01e8740e7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/normed_space/ordered.lean
83fda0a83baf30b1678d65c734d93ef9169c3055
[]
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
2,429
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.normed_space.basic import Mathlib.algebra.ring.basic import Mathlib.analysis.asymptotics import Mathlib.PostPort universes u_1 l namespace Mathlib /-! # Ordered normed spaces In this file, we define classes for fields and groups that are both normed and ordered. These are mostly useful to avoid diamonds during type class inference. -/ /-- A `normed_linear_ordered_group` is an additive group that is both a `normed_group` and a `linear_ordered_add_comm_group`. This class is necessary to avoid diamonds. -/ class normed_linear_ordered_group (Ξ± : Type u_1) extends has_norm Ξ±, linear_ordered_add_comm_group Ξ±, metric_space Ξ± where dist_eq : βˆ€ (x y : Ξ±), dist x y = norm (x - y) protected instance normed_linear_ordered_group.to_normed_group (Ξ± : Type u_1) [normed_linear_ordered_group Ξ±] : normed_group Ξ± := normed_group.mk normed_linear_ordered_group.dist_eq /-- A `normed_linear_ordered_field` is a field that is both a `normed_field` and a `linear_ordered_field`. This class is necessary to avoid diamonds. -/ class normed_linear_ordered_field (Ξ± : Type u_1) extends linear_ordered_field Ξ±, metric_space Ξ±, has_norm Ξ± where dist_eq : βˆ€ (x y : Ξ±), dist x y = norm (x - y) norm_mul' : βˆ€ (a b : Ξ±), norm (a * b) = norm a * norm b protected instance normed_linear_ordered_field.to_normed_field (Ξ± : Type u_1) [normed_linear_ordered_field Ξ±] : normed_field Ξ± := normed_field.mk normed_linear_ordered_field.dist_eq normed_linear_ordered_field.norm_mul' protected instance normed_linear_ordered_field.to_normed_linear_ordered_group (Ξ± : Type u_1) [normed_linear_ordered_field Ξ±] : normed_linear_ordered_group Ξ± := normed_linear_ordered_group.mk normed_linear_ordered_field.dist_eq theorem tendsto_pow_div_pow_at_top_of_lt {Ξ± : Type u_1} [normed_linear_ordered_field Ξ±] [order_topology Ξ±] {p : β„•} {q : β„•} (hpq : p < q) : filter.tendsto (fun (x : Ξ±) => x ^ p / x ^ q) filter.at_top (nhds 0) := sorry theorem is_o_pow_pow_at_top_of_lt {Ξ± : Type} [normed_linear_ordered_field Ξ±] [order_topology Ξ±] {p : β„•} {q : β„•} (hpq : p < q) : asymptotics.is_o (fun (x : Ξ±) => x ^ p) (fun (x : Ξ±) => x ^ q) filter.at_top := sorry
543a83670898f72b2221aa95e3123fdc23b5d23b
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/init/coe.lean
f9a9e13264906a901b10c3deeef0ff4360a64052
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
6,606
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 -/ /- The elaborator tries to insert coercions automatically. Only instances of has_coe type class are considered in the process. Lean also provides a "lifting" operator: ↑a. It uses all instances of has_lift type class. Every has_coe instance is also a has_lift instance. We recommend users only use has_coe for coercions that do not produce a lot of ambiguity. All coercions and lifts can be identified with the constant coe. We use the has_coe_to_fun type class for encoding coercions from a type to a function space. We use the has_coe_to_sort type class for encoding coercions from a type to a sort. -/ prelude import init.data.list.basic init.data.subtype.basic init.data.prod universes u v class has_lift (a : Sort u) (b : Sort v) := (lift : a β†’ b) /- Auxiliary class that contains the transitive closure of has_lift. -/ class has_lift_t (a : Sort u) (b : Sort v) := (lift : a β†’ b) class has_coe (a : Sort u) (b : Sort v) := (coe : a β†’ b) /- Auxiliary class that contains the transitive closure of has_coe. -/ class has_coe_t (a : Sort u) (b : Sort v) := (coe : a β†’ b) class has_coe_to_fun (a : Sort u) : Sort (max u (v+1)) := (F : a β†’ Sort v) (coe : Ξ  x, F x) class has_coe_to_sort (a : Sort u) : Type (max u (v+1)) := (S : Sort v) (coe : a β†’ S) def lift {a : Sort u} {b : Sort v} [has_lift a b] : a β†’ b := @has_lift.lift a b _ def lift_t {a : Sort u} {b : Sort v} [has_lift_t a b] : a β†’ b := @has_lift_t.lift a b _ def coe_b {a : Sort u} {b : Sort v} [has_coe a b] : a β†’ b := @has_coe.coe a b _ def coe_t {a : Sort u} {b : Sort v} [has_coe_t a b] : a β†’ b := @has_coe_t.coe a b _ def coe_fn_b {a : Sort u} [has_coe_to_fun.{u v} a] : Ξ  x : a, has_coe_to_fun.F.{u v} x := has_coe_to_fun.coe /- User level coercion operators -/ @[reducible] def coe {a : Sort u} {b : Sort v} [has_lift_t a b] : a β†’ b := lift_t @[reducible] def coe_fn {a : Sort u} [has_coe_to_fun.{u v} a] : Ξ  x : a, has_coe_to_fun.F.{u v} x := has_coe_to_fun.coe @[reducible] def coe_sort {a : Sort u} [has_coe_to_sort.{u v} a] : a β†’ has_coe_to_sort.S.{u v} a := has_coe_to_sort.coe /- Notation -/ notation `↑`:max x:max := coe x notation `⇑`:max x:max := coe_fn x notation `β†₯`:max x:max := coe_sort x universes u₁ uβ‚‚ u₃ /- Transitive closure for has_lift, has_coe, has_coe_to_fun -/ instance lift_trans {a : Sort u₁} {b : Sort uβ‚‚} {c : Sort u₃} [has_lift a b] [has_lift_t b c] : has_lift_t a c := ⟨λ x, lift_t (lift x : b)⟩ instance lift_base {a : Sort u} {b : Sort v} [has_lift a b] : has_lift_t a b := ⟨lift⟩ instance coe_trans {a : Sort u₁} {b : Sort uβ‚‚} {c : Sort u₃} [has_coe a b] [has_coe_t b c] : has_coe_t a c := ⟨λ x, coe_t (coe_b x : b)⟩ instance coe_base {a : Sort u} {b : Sort v} [has_coe a b] : has_coe_t a b := ⟨coe_b⟩ /- We add this instance directly into has_coe_t to avoid non-termination. Suppose coe_option had type (has_coe a (option a)). Then, we can loop when searching a coercion from Ξ± to Ξ² (has_coe_t Ξ± Ξ²) 1- coe_trans at (has_coe_t Ξ± Ξ²) (has_coe Ξ± ?b₁) and (has_coe_t ?b₁ c) 2- coe_option at (has_coe Ξ± ?b₁) ?b₁ := option Ξ± 3- coe_trans at (has_coe_t (option Ξ±) Ξ²) (has_coe (option Ξ±) ?bβ‚‚) and (has_coe_t ?bβ‚‚ Ξ²) 4- coe_option at (has_coe (option Ξ±) ?bβ‚‚) ?bβ‚‚ := option (option Ξ±)) ... -/ instance coe_option {a : Type u} : has_coe_t a (option a) := ⟨λ x, some x⟩ /- Auxiliary transitive closure for has_coe which does not contain instances such as coe_option. They would produce non-termination when combined with coe_fn_trans and coe_sort_trans. -/ class has_coe_t_aux (a : Sort u) (b : Sort v) := (coe : a β†’ b) instance coe_trans_aux {a : Sort u₁} {b : Sort uβ‚‚} {c : Sort u₃} [has_coe a b] [has_coe_t_aux b c] : has_coe_t_aux a c := ⟨λ x : a, @has_coe_t_aux.coe b c _ (coe_b x)⟩ instance coe_base_aux {a : Sort u} {b : Sort v} [has_coe a b] : has_coe_t_aux a b := ⟨coe_b⟩ instance coe_fn_trans {a : Sort u₁} {b : Sort uβ‚‚} [has_coe_t_aux a b] [has_coe_to_fun.{uβ‚‚ u₃} b] : has_coe_to_fun.{u₁ u₃} a := { F := Ξ» x, @has_coe_to_fun.F.{uβ‚‚ u₃} b _ (@has_coe_t_aux.coe a b _ x), coe := Ξ» x, coe_fn (@has_coe_t_aux.coe a b _ x) } instance coe_sort_trans {a : Sort u₁} {b : Sort uβ‚‚} [has_coe_t_aux a b] [has_coe_to_sort.{uβ‚‚ u₃} b] : has_coe_to_sort.{u₁ u₃} a := { S := has_coe_to_sort.S.{uβ‚‚ u₃} b, coe := Ξ» x, coe_sort (@has_coe_t_aux.coe a b _ x) } /- Every coercion is also a lift -/ instance coe_to_lift {a : Sort u} {b : Sort v} [has_coe_t a b] : has_lift_t a b := ⟨coe_t⟩ /- basic coercions -/ instance coe_bool_to_Prop : has_coe bool Prop := ⟨λ y, y = tt⟩ instance coe_decidable_eq (x : bool) : decidable (coe x) := show decidable (x = tt), from bool.decidable_eq x tt instance coe_subtype {a : Type u} {p : a β†’ Prop} : has_coe {x // p x} a := ⟨subtype.val⟩ /- basic lifts -/ universes ua ua₁ uaβ‚‚ ub ub₁ ubβ‚‚ /- Remark: we cant use [has_lift_t aβ‚‚ a₁] since it will produce non-termination whenever a type class resolution problem does not have a solution. -/ instance lift_fn {a₁ : Sort ua₁} {aβ‚‚ : Sort uaβ‚‚} {b₁ : Sort ub₁} {bβ‚‚ : Sort ubβ‚‚} [has_lift aβ‚‚ a₁] [has_lift_t b₁ bβ‚‚] : has_lift (a₁ β†’ b₁) (aβ‚‚ β†’ bβ‚‚) := ⟨λ f x, ↑(f ↑x)⟩ instance lift_fn_range {a : Sort ua} {b₁ : Sort ub₁} {bβ‚‚ : Sort ubβ‚‚} [has_lift_t b₁ bβ‚‚] : has_lift (a β†’ b₁) (a β†’ bβ‚‚) := ⟨λ f x, ↑(f x)⟩ instance lift_fn_dom {a₁ : Sort ua₁} {aβ‚‚ : Sort uaβ‚‚} {b : Sort ub} [has_lift aβ‚‚ a₁] : has_lift (a₁ β†’ b) (aβ‚‚ β†’ b) := ⟨λ f x, f ↑x⟩ instance lift_pair {a₁ : Type ua₁} {aβ‚‚ : Type ubβ‚‚} {b₁ : Type ub₁} {bβ‚‚ : Type ubβ‚‚} [has_lift_t a₁ aβ‚‚] [has_lift_t b₁ bβ‚‚] : has_lift (a₁ Γ— b₁) (aβ‚‚ Γ— bβ‚‚) := ⟨λ p, prod.cases_on p (Ξ» x y, (↑x, ↑y))⟩ instance lift_pair₁ {a₁ : Type ua₁} {aβ‚‚ : Type uaβ‚‚} {b : Type ub} [has_lift_t a₁ aβ‚‚] : has_lift (a₁ Γ— b) (aβ‚‚ Γ— b) := ⟨λ p, prod.cases_on p (Ξ» x y, (↑x, y))⟩ instance lift_pairβ‚‚ {a : Type ua} {b₁ : Type ub₁} {bβ‚‚ : Type ubβ‚‚} [has_lift_t b₁ bβ‚‚] : has_lift (a Γ— b₁) (a Γ— bβ‚‚) := ⟨λ p, prod.cases_on p (Ξ» x y, (x, ↑y))⟩ instance lift_list {a : Type u} {b : Type v} [has_lift_t a b] : has_lift (list a) (list b) := ⟨λ l, list.map (@coe a b _) l⟩
2e815b08aaf31a60254048f1c706cc049f26c1c4
cabd1ea95170493667c024ef2045eb86d981b133
/src/super/prover_state.lean
72796ee3d62e1197907b51b1cd1dc7d339749c19
[]
no_license
semorrison/super
31db4b5aa5ef4c2313dc5803b8c79a95f809815b
0c6c03ba9c7470f801eb4d055294f424ff090308
refs/heads/master
1,630,272,140,541
1,511,054,739,000
1,511,054,756,000
114,317,807
0
0
null
1,513,304,776,000
1,513,304,775,000
null
UTF-8
Lean
false
false
15,641
lean
/- Copyright (c) 2017 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .lpo .cdcl_solver open tactic functor monad expr native namespace super structure score := (priority : β„•) (in_sos : bool) (cost : β„•) (age : β„•) namespace score def prio.immediate : β„• := 0 def prio.default : β„• := 1 def prio.never : β„• := 2 def sched_default (sc : score) : score := { sc with priority := prio.default } def sched_now (sc : score) : score := { sc with priority := prio.immediate } def inc_cost (sc : score) (n : β„•) : score := { sc with cost := sc.cost + n } def min (a b : score) : score := { priority := nat.min a.priority b.priority, in_sos := a.in_sos && b.in_sos, cost := nat.min a.cost b.cost, age := nat.min a.age b.age } def combine (a b : score) : score := { priority := nat.max a.priority b.priority, in_sos := a.in_sos && b.in_sos, cost := a.cost + b.cost, age := nat.max a.age b.age } end score namespace score meta instance : has_to_string score := ⟨λe, "[" ++ to_string e.priority ++ "," ++ to_string e.cost ++ "," ++ to_string e.age ++ ",sos=" ++ to_string e.in_sos ++ "]"⟩ end score def clause_id := β„• namespace clause_id def to_nat (id : clause_id) : β„• := id instance : decidable_eq clause_id := nat.decidable_eq instance : has_lt clause_id := nat.has_lt instance : decidable_rel ((<) : clause_id β†’ clause_id β†’ Prop) := nat.decidable_lt end clause_id meta structure derived_clause := (id : clause_id) (c : clause) (selected : list β„•) (assertions : list expr) (sc : score) namespace derived_clause meta instance : has_to_tactic_format derived_clause := ⟨λc, do prf_fmt ← pp c.c.proof, c_fmt ← pp c.c, ass_fmt ← pp (c.assertions.map (Ξ»a, a.local_type)), return $ to_string c.sc ++ " " ++ prf_fmt ++ " " ++ c_fmt ++ " <- " ++ ass_fmt ++ " (selected: " ++ to_fmt c.selected ++ ")" ⟩ meta def clause_with_assertions (ac : derived_clause) : clause := ac.c.close_constn ac.assertions meta def update_proof (dc : derived_clause) (p : expr) : derived_clause := { dc with c := { (dc.c) with proof := p } } end derived_clause meta structure locked_clause := (dc : derived_clause) (reasons : list (list expr)) namespace locked_clause meta instance : has_to_tactic_format locked_clause := ⟨λc, do c_fmt ← pp c.dc, reasons_fmt ← pp (c.reasons.map (Ξ»r, r.map (Ξ»a, a.local_type))), return $ c_fmt ++ " (locked in case of: " ++ reasons_fmt ++ ")" ⟩ end locked_clause meta structure prover_state := (active : rb_map clause_id derived_clause) (passive : rb_map clause_id derived_clause) (newly_derived : list derived_clause) (prec : list expr) (locked : list locked_clause) (local_false : expr) (sat_solver : cdcl.state) (current_model : rb_map expr bool) (sat_hyps : rb_map expr (expr Γ— expr)) (needs_sat_run : bool) (clause_counter : nat) open prover_state private meta def join_with_nl : list format β†’ format := list.foldl (Ξ»x y, x ++ format.line ++ y) format.nil private meta def prover_state_tactic_fmt (s : prover_state) : tactic format := do active_fmts ← mapm pp $ rb_map.values s.active, passive_fmts ← mapm pp $ rb_map.values s.passive, new_fmts ← mapm pp s.newly_derived, locked_fmts ← mapm pp s.locked, sat_fmts ← mapm pp s.sat_solver.clauses, sat_model_fmts ← s.current_model.to_list.mmap (Ξ»x, if x.2 = tt then pp x.1 else pp `(not %%x.1)), prec_fmts ← mapm pp s.prec, return (join_with_nl ([to_fmt "active:"] ++ ((append (to_fmt " ")) <$> active_fmts) ++ [to_fmt "passive:"] ++ ((append (to_fmt " ")) <$> passive_fmts) ++ [to_fmt "new:"] ++ ((append (to_fmt " ")) <$> new_fmts) ++ [to_fmt "locked:"] ++ ((append (to_fmt " ")) <$> locked_fmts) ++ [to_fmt "sat formulas:"] ++ ((append (to_fmt " ")) <$> sat_fmts) ++ [to_fmt "sat model:"] ++ ((append (to_fmt " ")) <$> sat_model_fmts) ++ [to_fmt "precedence order: " ++ to_fmt prec_fmts])) meta instance : has_to_tactic_format prover_state := ⟨prover_state_tactic_fmt⟩ meta def prover := state_t prover_state tactic namespace prover meta instance : monad prover := state_t.monad _ _ meta instance : has_monad_lift tactic prover := monad.monad_transformer_lift (state_t prover_state) tactic meta instance (Ξ± : Type) : has_coe (tactic Ξ±) (prover Ξ±) := ⟨monad.monad_lift⟩ meta def fail {Ξ± Ξ² : Type} [has_to_format Ξ²] (msg : Ξ²) : prover Ξ± := tactic.fail msg meta def orelse (A : Type) (p1 p2 : prover A) : prover A := assume state, p1 state <|> p2 state meta instance : alternative prover := { prover.monad with failure := λα, fail "failed", orelse := orelse } end prover meta def selection_strategy := derived_clause β†’ prover derived_clause meta def get_active : prover (rb_map clause_id derived_clause) := do state ← state_t.read, return state.active meta def add_active (a : derived_clause) : prover unit := do state ← state_t.read, state_t.write { state with active := state.active.insert a.id a } meta def get_passive : prover (rb_map clause_id derived_clause) := lift passive state_t.read meta def get_precedence : prover (list expr) := do state ← state_t.read, return state.prec meta def get_term_order : prover (expr β†’ expr β†’ bool) := do state ← state_t.read, return $ mk_lpo (name_of_funsym <$> state.prec) private meta def set_precedence (new_prec : list expr) : prover unit := do state ← state_t.read, state_t.write { state with prec := new_prec } meta def register_consts_in_precedence (consts : list expr) := do p ← get_precedence, p_set ← return (rb_map.set_of_list (name_of_funsym <$> p)), new_syms ← return $ list.filter (Ξ»c, Β¬p_set.contains (name_of_funsym c)) consts, set_precedence (new_syms ++ p) meta def in_sat_solver {A} (cmd : cdcl.solver A) : prover A := do state ← state_t.read, result ← cmd state.sat_solver, state_t.write { state with sat_solver := result.2 }, return result.1 meta def collect_ass_hyps (c : clause) : prover (list expr) := let lcs := contained_lconsts c.proof in do st ← state_t.read, return (do hs ← st.sat_hyps.values, h ← [hs.1, hs.2], guard $ lcs.contains h.local_uniq_name, [h]) meta def get_clause_count : prover β„• := do s ← state_t.read, return s.clause_counter meta def get_new_cls_id : prover clause_id := do state ← state_t.read, state_t.write { state with clause_counter := state.clause_counter + 1 }, return state.clause_counter meta def mk_derived (c : clause) (sc : score) : prover derived_clause := do ass ← collect_ass_hyps c, id ← get_new_cls_id, return { id := id, c := c, selected := [], assertions := ass, sc := sc } meta def add_inferred (c : derived_clause) : prover unit := do c' ← c.c.normalize, c' ← return { c with c := c' }, register_consts_in_precedence (contained_funsyms c'.c.type).values, state ← state_t.read, state_t.write { state with newly_derived := c' :: state.newly_derived } -- FIXME: what if we've seen the variable before, but with a weaker score? meta def mk_sat_var (v : expr) (suggested_ph : bool) (suggested_ev : score) : prover unit := do st ← state_t.read, if st.sat_hyps.contains v then return () else do hpv ← mk_local_def `h v, hnv ← mk_local_def `hn $ imp v st.local_false, state_t.modify $ Ξ»st, { st with sat_hyps := st.sat_hyps.insert v (hpv, hnv) }, in_sat_solver $ cdcl.mk_var_core v suggested_ph, match v with | (pi _ _ _ _) := do c ← clause.of_proof st.local_false hpv, mk_derived c suggested_ev >>= add_inferred | _ := do cp ← clause.of_proof st.local_false hpv, mk_derived cp suggested_ev >>= add_inferred, cn ← clause.of_proof st.local_false hnv, mk_derived cn suggested_ev >>= add_inferred end meta def get_sat_hyp_core (v : expr) (ph : bool) : prover (option expr) := flip monad.lift state_t.read $ Ξ»st, match st.sat_hyps.find v with | some (hp, hn) := some $ if ph then hp else hn | none := none end meta def get_sat_hyp (v : expr) (ph : bool) : prover expr := do hyp_opt ← get_sat_hyp_core v ph, match hyp_opt with | some hyp := return hyp | none := fail $ "unknown sat variable: " ++ v.to_string end meta def add_sat_clause (c : clause) (suggested_ev : score) : prover unit := do c ← c.distinct, already_added ← flip monad.lift state_t.read $ Ξ»st, decidable.to_bool $ c.type ∈ st.sat_solver.clauses.map (Ξ»d, d.type), if already_added then return () else do c.get_lits.mmap' $ Ξ»l, mk_sat_var l.formula l.is_neg suggested_ev, in_sat_solver $ cdcl.mk_clause c, state_t.modify $ Ξ»st, { st with needs_sat_run := tt } meta def sat_eval_lit (v : expr) (pol : bool) : prover bool := do v_st ← flip monad.lift state_t.read $ Ξ»st, st.current_model.find v, match v_st with | some ph := return $ if pol then ph else bnot ph | none := return tt end meta def sat_eval_assertion (assertion : expr) : prover bool := do lf ← flip monad.lift state_t.read $ Ξ»st, st.local_false, match is_local_not lf assertion.local_type with | some v := sat_eval_lit v ff | none := sat_eval_lit assertion.local_type tt end meta def sat_eval_assertions : list expr β†’ prover bool | (a::ass) := do v_a ← sat_eval_assertion a, if v_a then sat_eval_assertions ass else return ff | [] := return tt private meta def intern_clause (c : derived_clause) : prover derived_clause := do hyp_name ← get_unused_name (mk_simple_name $ "clause_" ++ to_string c.id.to_nat) none, c' ← return $ c.c.close_constn c.assertions, assertv hyp_name c'.type c'.proof, proof' ← get_local hyp_name, type ← infer_type proof', -- FIXME: otherwise "" return $ c.update_proof $ app_of_list proof' c.assertions meta def register_as_passive (c : derived_clause) : prover unit := do c ← intern_clause c, ass_v ← sat_eval_assertions c.assertions, if c.c.num_quants = 0 ∧ c.c.num_lits = 0 then add_sat_clause c.clause_with_assertions c.sc else if Β¬ass_v then do state_t.modify $ Ξ»st, { st with locked := ⟨c, []⟩ :: st.locked } else do state_t.modify $ Ξ»st, { st with passive := st.passive.insert c.id c } meta def remove_passive (id : clause_id) : prover unit := do state ← state_t.read, state_t.write { state with passive := state.passive.erase id } meta def move_locked_to_passive : prover unit := do locked ← flip monad.lift state_t.read (Ξ»st, st.locked), new_locked ← flip filter locked (Ξ»lc, do reason_vals ← mapm sat_eval_assertions lc.reasons, c_val ← sat_eval_assertions lc.dc.assertions, if reason_vals.for_all (Ξ»r, r = ff) ∧ c_val then do state_t.modify $ Ξ»st, { st with passive := st.passive.insert lc.dc.id lc.dc }, return ff else return tt ), state_t.modify $ Ξ»st, { st with locked := new_locked } meta def move_active_to_locked : prover unit := do active ← get_active, active.values.mmap' $ Ξ»ac, do c_val ← sat_eval_assertions ac.assertions, if Β¬c_val then do state_t.modify $ Ξ»st, { st with active := st.active.erase ac.id, locked := ⟨ac, []⟩ :: st.locked } else return () meta def move_passive_to_locked : prover unit := do passive ← flip monad.lift state_t.read $ Ξ»st, st.passive, passive.to_list.mmap' $ Ξ»pc, do c_val ← sat_eval_assertions pc.2.assertions, if Β¬c_val then do state_t.modify $ Ξ»st, { st with passive := st.passive.erase pc.1, locked := ⟨pc.2, []⟩ :: st.locked } else return () def super_cc_config : cc_config := { em := ff } meta def do_sat_run : prover (option expr) := do sat_result ← in_sat_solver $ cdcl.run (cdcl.theory_solver_of_tactic $ using_smt $ return ()), state_t.modify $ Ξ»st, { st with needs_sat_run := ff }, old_model ← lift prover_state.current_model state_t.read, match sat_result with | (cdcl.result.unsat proof) := return (some proof) | (cdcl.result.sat new_model) := do state_t.modify $ Ξ»st, { st with current_model := new_model }, move_locked_to_passive, move_active_to_locked, move_passive_to_locked, return none end meta def take_newly_derived : prover (list derived_clause) := do state ← state_t.read, state_t.write { state with newly_derived := [] }, return state.newly_derived meta def remove_redundant (id : clause_id) (parents : list derived_clause) : prover unit := do when (not $ parents.for_all $ Ξ»p, p.id β‰  id) (fail "clause is redundant because of itself"), red ← flip monad.lift state_t.read (Ξ»st, st.active.find id), match red with | none := return () | some red := do let reasons := parents.map (Ξ»p, p.assertions), let assertion := red.assertions, if reasons.for_all $ Ξ»r, r.subset_of assertion then do state_t.modify $ Ξ»st, { st with active := st.active.erase id } else do state_t.modify $ Ξ»st, { st with active := st.active.erase id, locked := ⟨red, reasons⟩ :: st.locked } end meta def inference := derived_clause β†’ prover unit meta structure inf_decl := (prio : β„•) (inf : inference) @[user_attribute] meta def inf_attr : user_attribute := {name := `super.inf, descr := "inference for the super prover"} meta def seq_inferences : list inference β†’ inference | [] := Ξ»given, return () | (inf::infs) := Ξ»given, do inf given, now_active ← get_active, if rb_map.contains now_active given.id then seq_inferences infs given else return () meta def simp_inference (simpl : derived_clause β†’ prover (option clause)) : inference := Ξ»given, do maybe_simpld ← simpl given, match maybe_simpld with | some simpld := do derived_simpld ← mk_derived simpld given.sc.sched_now, add_inferred derived_simpld, remove_redundant given.id [] | none := return () end meta def preprocessing_rule (f : list derived_clause β†’ prover (list derived_clause)) : prover unit := do state ← state_t.read, newly_derived' ← f state.newly_derived, state' ← state_t.read, state_t.write { state' with newly_derived := newly_derived' } meta def clause_selection_strategy := β„• β†’ prover clause_id namespace prover_state meta def empty (local_false : expr) : prover_state := { active := rb_map.mk _ _, passive := rb_map.mk _ _, newly_derived := [], prec := [], clause_counter := 0, local_false := local_false, locked := [], sat_solver := cdcl.state.initial local_false, current_model := rb_map.mk _ _, sat_hyps := rb_map.mk _ _, needs_sat_run := ff } meta def initial (local_false : expr) (clauses : list clause) : tactic prover_state := do after_setup ← clauses.mmap' (Ξ»c : clause, let in_sos := ((contained_lconsts c.proof).erase local_false.local_uniq_name).size = 0 in do mk_derived c { priority := score.prio.immediate, in_sos := in_sos, age := 0, cost := 0 } >>= add_inferred ) $ empty local_false, return after_setup.2 end prover_state meta def inf_score (add_cost : β„•) (scores : list score) : prover score := do age ← get_clause_count, return $ list.foldl score.combine { priority := score.prio.default, in_sos := tt, age := age, cost := add_cost } scores meta def inf_if_successful (add_cost : β„•) (parent : derived_clause) (tac : tactic (list clause)) : prover unit := (do inferred ← tac, inferred.mmap' $ Ξ»c, inf_score add_cost [parent.sc] >>= mk_derived c >>= add_inferred) <|> return () meta def simp_if_successful (parent : derived_clause) (tac : tactic (list clause)) : prover unit := (do inferred ← tac, inferred.mmap' $ Ξ»c, mk_derived c parent.sc.sched_now >>= add_inferred, remove_redundant parent.id []) <|> return () end super
7dfb9848362c48d3f0a1cf4c203270083e0cc2a3
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/control/traversable/basic.lean
0d2ac30d2ac111d853381f22ebf289d1f9bd757e
[ "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
9,533
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.functor /-! # Traversable type class Type classes for traversing collections. The concepts and laws are taken from <http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-Traversable.html> Traversable collections are a generalization of functors. Whereas functors (such as `list`) allow us to apply a function to every element, it does not allow functions which external effects encoded in a monad. Consider for instance a functor `invite : email β†’ io response` that takes an email address, sends an email and waits for a response. If we have a list `guests : list email`, using calling `invite` using `map` gives us the following: `map invite guests : list (io response)`. It is not what we need. We need something of type `io (list response)`. Instead of using `map`, we can use `traverse` to send all the invites: `traverse invite guests : io (list response)`. `traverse` applies `invite` to every element of `guests` and combines all the resulting effects. In the example, the effect is encoded in the monad `io` but any applicative functor is accepted by `traverse`. For more on how to use traversable, consider the Haskell tutorial: <https://en.wikibooks.org/wiki/Haskell/Traversable> ## Main definitions * `traversable` type class - exposes the `traverse` function * `sequence` - based on `traverse`, turns a collection of effects into an effect returning a collection * `is_lawful_traversable` - laws for a traversable functor * `applicative_transformation` - the notion of a natural transformation for applicative functors ## Tags traversable iterator functor applicative ## References * "Applicative Programming with Effects", by Conor McBride and Ross Paterson, Journal of Functional Programming 18:1 (2008) 1-13, online at <http://www.soi.city.ac.uk/~ross/papers/Applicative.html> * "The Essence of the Iterator Pattern", by Jeremy Gibbons and Bruno Oliveira, in Mathematically-Structured Functional Programming, 2006, online at <http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator> * "An Investigation of the Laws of Traversals", by Mauro Jaskelioff and Ondrej Rypacek, in Mathematically-Structured Functional Programming, 2012, online at <http://arxiv.org/pdf/1202.2919> -/ open function (hiding comp) universes u v w section applicative_transformation variables (F : Type u β†’ Type v) [applicative F] [is_lawful_applicative F] variables (G : Type u β†’ Type w) [applicative G] [is_lawful_applicative G] /-- A transformation between applicative functors. It a natural transformation such that `app` preserves the `has_pure.pure` and `functor.map` (`<*>`) operations. See `applicative_transformation.preserves_map` for naturality. -/ structure applicative_transformation : Type (max (u+1) v w) := (app : Ξ  Ξ± : Type u, F Ξ± β†’ G Ξ±) (preserves_pure' : βˆ€ {Ξ± : Type u} (x : Ξ±), app _ (pure x) = pure x) (preserves_seq' : βˆ€ {Ξ± Ξ² : Type u} (x : F (Ξ± β†’ Ξ²)) (y : F Ξ±), app _ (x <*> y) = app _ x <*> app _ y) end applicative_transformation namespace applicative_transformation variables (F : Type u β†’ Type v) [applicative F] [is_lawful_applicative F] variables (G : Type u β†’ Type w) [applicative G] [is_lawful_applicative G] instance : has_coe_to_fun (applicative_transformation F G) := { F := Ξ» _, Ξ  {Ξ±}, F Ξ± β†’ G Ξ±, coe := Ξ» a, a.app } variables {F G} @[simp] lemma app_eq_coe (Ξ· : applicative_transformation F G) : Ξ·.app = Ξ· := rfl @[simp] lemma coe_mk (f : Ξ  (Ξ± : Type u), F Ξ± β†’ G Ξ±) (pp ps) : ⇑(applicative_transformation.mk f pp ps) = f := rfl protected lemma congr_fun (Ξ· Ξ·' : applicative_transformation F G) (h : Ξ· = Ξ·') {Ξ± : Type u} (x : F Ξ±) : Ξ· x = Ξ·' x := congr_arg (Ξ» Ξ·'' : applicative_transformation F G, Ξ·'' x) h protected lemma congr_arg (Ξ· : applicative_transformation F G) {Ξ± : Type u} {x y : F Ξ±} (h : x = y) : Ξ· x = Ξ· y := congr_arg (Ξ» z : F Ξ±, Ξ· z) h lemma coe_inj ⦃η Ξ·' : applicative_transformation F G⦄ (h : (Ξ· : Ξ  Ξ±, F Ξ± β†’ G Ξ±) = Ξ·') : Ξ· = Ξ·' := by { cases Ξ·, cases Ξ·', congr, exact h } @[ext] lemma ext ⦃η Ξ·' : applicative_transformation F G⦄ (h : βˆ€ (Ξ± : Type u) (x : F Ξ±), Ξ· x = Ξ·' x) : Ξ· = Ξ·' := by { apply coe_inj, ext1 Ξ±, exact funext (h Ξ±) } lemma ext_iff {Ξ· Ξ·' : applicative_transformation F G} : Ξ· = Ξ·' ↔ βˆ€ (Ξ± : Type u) (x : F Ξ±), Ξ· x = Ξ·' x := ⟨λ h Ξ± x, h β–Έ rfl, Ξ» h, ext h⟩ section preserves variables (Ξ· : applicative_transformation F G) @[functor_norm] lemma preserves_pure : βˆ€ {Ξ±} (x : Ξ±), Ξ· (pure x) = pure x := Ξ·.preserves_pure' @[functor_norm] lemma preserves_seq : βˆ€ {Ξ± Ξ² : Type u} (x : F (Ξ± β†’ Ξ²)) (y : F Ξ±), Ξ· (x <*> y) = Ξ· x <*> Ξ· y := Ξ·.preserves_seq' @[functor_norm] lemma preserves_map {Ξ± Ξ²} (x : Ξ± β†’ Ξ²) (y : F Ξ±) : Ξ· (x <$> y) = x <$> Ξ· y := by rw [← pure_seq_eq_map, Ξ·.preserves_seq]; simp with functor_norm lemma preserves_map' {Ξ± Ξ²} (x : Ξ± β†’ Ξ²) : @Ξ· _ ∘ functor.map x = functor.map x ∘ @Ξ· _ := by { ext y, exact preserves_map Ξ· x y } end preserves /-- The identity applicative transformation from an applicative functor to itself. -/ def id_transformation : applicative_transformation F F := { app := Ξ» Ξ±, id, preserves_pure' := by simp, preserves_seq' := Ξ» Ξ± Ξ² x y, by simp } instance : inhabited (applicative_transformation F F) := ⟨id_transformation⟩ universes s t variables {H : Type u β†’ Type s} [applicative H] [is_lawful_applicative H] /-- The composition of applicative transformations. -/ def comp (Ξ·' : applicative_transformation G H) (Ξ· : applicative_transformation F G) : applicative_transformation F H := { app := Ξ» Ξ± x, Ξ·' (Ξ· x), preserves_pure' := Ξ» Ξ± x, by simp with functor_norm, preserves_seq' := Ξ» Ξ± Ξ² x y, by simp with functor_norm } @[simp] lemma comp_apply (Ξ·' : applicative_transformation G H) (Ξ· : applicative_transformation F G) {Ξ± : Type u} (x : F Ξ±) : Ξ·'.comp Ξ· x = Ξ·' (Ξ· x) := rfl lemma comp_assoc {I : Type u β†’ Type t} [applicative I] [is_lawful_applicative I] (Ξ·'' : applicative_transformation H I) (Ξ·' : applicative_transformation G H) (Ξ· : applicative_transformation F G) : (Ξ·''.comp Ξ·').comp Ξ· = Ξ·''.comp (Ξ·'.comp Ξ·) := rfl @[simp] lemma comp_id (Ξ· : applicative_transformation F G) : Ξ·.comp id_transformation = Ξ· := ext $ Ξ» Ξ± x, rfl @[simp] lemma id_comp (Ξ· : applicative_transformation F G) : id_transformation.comp Ξ· = Ξ· := ext $ Ξ» Ξ± x, rfl end applicative_transformation open applicative_transformation /-- A traversable functor is a functor along with a way to commute with all applicative functors (see `sequence`). For example, if `t` is the traversable functor `list` and `m` is the applicative functor `io`, then given a function `f : Ξ± β†’ io Ξ²`, the function `functor.map f` is `list Ξ± β†’ list (io Ξ²)`, but `traverse f` is `list Ξ± β†’ io (list Ξ²)`. -/ class traversable (t : Type u β†’ Type u) extends functor t := (traverse : Ξ  {m : Type u β†’ Type u} [applicative m] {Ξ± Ξ²}, (Ξ± β†’ m Ξ²) β†’ t Ξ± β†’ m (t Ξ²)) open functor export traversable (traverse) section functions variables {t : Type u β†’ Type u} variables {m : Type u β†’ Type v} [applicative m] variables {Ξ± Ξ² : Type u} variables {f : Type u β†’ Type u} [applicative f] /-- A traversable functor commutes with all applicative functors. -/ def sequence [traversable t] : t (f Ξ±) β†’ f (t Ξ±) := traverse id end functions /-- A traversable functor is lawful if its `traverse` satisfies a number of additional properties. It must send `id.mk` to `id.mk`, send the composition of applicative functors to the composition of the `traverse` of each, send each function `f` to `Ξ» x, f <$> x`, and satisfy a naturality condition with respect to applicative transformations. -/ class is_lawful_traversable (t : Type u β†’ Type u) [traversable t] extends is_lawful_functor t : Type (u+1) := (id_traverse : βˆ€ {Ξ±} (x : t Ξ±), traverse id.mk x = x ) (comp_traverse : βˆ€ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {Ξ± Ξ² Ξ³} (f : Ξ² β†’ F Ξ³) (g : Ξ± β†’ G Ξ²) (x : t Ξ±), traverse (comp.mk ∘ map f ∘ g) x = comp.mk (map (traverse f) (traverse g x))) (traverse_eq_map_id : βˆ€ {Ξ± Ξ²} (f : Ξ± β†’ Ξ²) (x : t Ξ±), traverse (id.mk ∘ f) x = id.mk (f <$> x)) (naturality : βˆ€ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] (Ξ· : applicative_transformation F G) {Ξ± Ξ²} (f : Ξ± β†’ F Ξ²) (x : t Ξ±), Ξ· (traverse f x) = traverse (@Ξ· _ ∘ f) x) instance : traversable id := ⟨λ _ _ _ _, id⟩ instance : is_lawful_traversable id := by refine {..}; intros; refl section variables {F : Type u β†’ Type v} [applicative F] instance : traversable option := ⟨@option.traverse⟩ instance : traversable list := ⟨@list.traverse⟩ end namespace sum variables {Οƒ : Type u} variables {F : Type u β†’ Type u} variables [applicative F] /-- Defines a `traverse` function on the second component of a sum type. This is used to give a `traversable` instance for the functor `Οƒ βŠ• -`. -/ protected def traverse {Ξ± Ξ²} (f : Ξ± β†’ F Ξ²) : Οƒ βŠ• Ξ± β†’ F (Οƒ βŠ• Ξ²) | (sum.inl x) := pure (sum.inl x) | (sum.inr x) := sum.inr <$> f x end sum instance {Οƒ : Type u} : traversable.{u} (sum Οƒ) := ⟨@sum.traverse _⟩
d8bf16c30a61c13f787cff766c387a464cec455f
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/Mathlib/Data/Prod.lean
36b1a39181abd24a50ca9a01d7a1d0538e143faa
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
6,764
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 -/ import Mathlib.Init.Function import Mathlib.Logic.Basic import Mathlib.Logic.Function.Basic import Mathlib.Tactic.Basic import Mathlib.Tactic.Ext /-! # Extra facts about `Prod` This file defines `Prod.swap : Ξ± Γ— Ξ² β†’ Ξ² Γ— Ξ±` and proves various simple lemmas about `Prod`. -/ variable {Ξ± : Type _} {Ξ² : Type _} {Ξ³ : Type _} {Ξ΄ : Type _} @[simp] lemma prod_map (f : Ξ± β†’ Ξ³) (g : Ξ² β†’ Ξ΄) (p : Ξ± Γ— Ξ²) : Prod.map f g p = (f p.1, g p.2) := by have : p = ⟨p.1, p.2⟩ := (Prod.ext _).symm rw [this] exact rfl namespace Prod @[simp] theorem Β«forallΒ» {p : Ξ± Γ— Ξ² β†’ Prop} : (βˆ€ x, p x) ↔ (βˆ€ a b, p (a, b)) := ⟨λ h a b => h (a, b), Ξ» h ⟨a, b⟩ => h a b⟩ @[simp] theorem Β«existsΒ» {p : Ξ± Γ— Ξ² β†’ Prop} : (βˆƒ x, p x) ↔ (βˆƒ a b, p (a, b)) := ⟨λ ⟨⟨a, b⟩, h⟩ => ⟨a, b, h⟩, Ξ» ⟨a, b, h⟩ => ⟨⟨a, b⟩, h⟩⟩ theorem forall' {p : Ξ± β†’ Ξ² β†’ Prop} : (βˆ€ x : Ξ± Γ— Ξ², p x.1 x.2) ↔ βˆ€ a b, p a b := Prod.forall theorem exists' {p : Ξ± β†’ Ξ² β†’ Prop} : (βˆƒ x : Ξ± Γ— Ξ², p x.1 x.2) ↔ βˆƒ a b, p a b := Prod.exists @[simp] lemma map_mk (f : Ξ± β†’ Ξ³) (g : Ξ² β†’ Ξ΄) (a : Ξ±) (b : Ξ²) : map f g (a, b) = (f a, g b) := rfl @[simp] lemma map_fst (f : Ξ± β†’ Ξ³) (g : Ξ² β†’ Ξ΄) (p : Ξ± Γ— Ξ²) : (map f g p).1 = f (p.1) := by simp @[simp] lemma map_snd (f : Ξ± β†’ Ξ³) (g : Ξ² β†’ Ξ΄) (p : Ξ± Γ— Ξ²) : (map f g p).2 = g (p.2) := by simp lemma map_fst' (f : Ξ± β†’ Ξ³) (g : Ξ² β†’ Ξ΄) : (Prod.fst ∘ map f g) = f ∘ Prod.fst := funext $ map_fst f g lemma map_snd' (f : Ξ± β†’ Ξ³) (g : Ξ² β†’ Ξ΄) : (Prod.snd ∘ map f g) = g ∘ Prod.snd := funext $ map_snd f g /-- Composing a `prod.map` with another `prod.map` is equal to a single `prod.map` of composed functions. -/ lemma map_comp_map {Ξ΅ ΞΆ : Type _} (f : Ξ± β†’ Ξ²) (f' : Ξ³ β†’ Ξ΄) (g : Ξ² β†’ Ξ΅) (g' : Ξ΄ β†’ ΞΆ) : Prod.map g g' ∘ Prod.map f f' = Prod.map (g ∘ f) (g' ∘ f') := by ext x; simp /-- Composing a `prod.map` with another `prod.map` is equal to a single `prod.map` of composed functions, fully applied. -/ lemma map_map {Ξ΅ ΞΆ : Type _} (f : Ξ± β†’ Ξ²) (f' : Ξ³ β†’ Ξ΄) (g : Ξ² β†’ Ξ΅) (g' : Ξ΄ β†’ ΞΆ) (x : Ξ± Γ— Ξ³) : Prod.map g g' (Prod.map f f' x) = Prod.map (g ∘ f) (g' ∘ f') x := by simp @[simp] theorem mk.inj_iff {a₁ aβ‚‚ : Ξ±} {b₁ bβ‚‚ : Ξ²} : (a₁, b₁) = (aβ‚‚, bβ‚‚) ↔ (a₁ = aβ‚‚ ∧ b₁ = bβ‚‚) := ⟨Prod.mk.inj, by intro hab; rw [hab.left, hab.right]⟩ lemma mk.inj_left {Ξ± Ξ² : Type _} (a : Ξ±) : Function.injective (Prod.mk a : Ξ² β†’ Ξ± Γ— Ξ²) := fun h => (Prod.mk.inj h).right lemma mk.inj_right {Ξ± Ξ² : Type _} (b : Ξ²) : Function.injective (Ξ» a => Prod.mk a b : Ξ± β†’ Ξ± Γ— Ξ²) := fun h => (Prod.mk.inj h).left -- Port note: this lemma comes from lean3/library/init/data/prod.lean. @[simp] lemma mk.eta : βˆ€{p : Ξ± Γ— Ξ²}, (p.1, p.2) = p | (a,b) => rfl lemma ext_iff {p q : Ξ± Γ— Ξ²} : p = q ↔ p.1 = q.1 ∧ p.2 = q.2 := by rw [← @mk.eta _ _ p, ← @mk.eta _ _ q, mk.inj_iff] -- Port note: in mathlib this is named `ext`, but Lean4 has already defined that to be something -- with a slightly different signature. @[ext] lemma ext' {Ξ± Ξ²} {p q : Ξ± Γ— Ξ²} (h₁ : p.1 = q.1) (hβ‚‚ : p.2 = q.2) : p = q := ext_iff.2 ⟨h₁, hβ‚‚βŸ© lemma map_def {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ΄} : Prod.map f g = Ξ» p => (f p.1, g p.2) := by ext <;> simp lemma id_prod : (Ξ» (p : Ξ± Γ— Ξ±) => (p.1, p.2)) = id := funext $ Ξ» ⟨a, b⟩ => rfl lemma fst_surjective [h : Nonempty Ξ²] : Function.surjective (@fst Ξ± Ξ²) := Ξ» x => h.elim $ Ξ» y => ⟨⟨x, y⟩, rfl⟩ lemma snd_surjective [h : Nonempty Ξ±] : Function.surjective (@snd Ξ± Ξ²) := Ξ» y => h.elim $ Ξ» x => ⟨⟨x, y⟩, rfl⟩ lemma fst_injective [Subsingleton Ξ²] : Function.injective (@fst Ξ± Ξ²) := Ξ» {x y} h => ext' h (Subsingleton.elim x.snd y.snd) lemma snd_injective [Subsingleton Ξ±] : Function.injective (@snd Ξ± Ξ²) := Ξ» {x y} h => ext' (Subsingleton.elim _ _) h /-- Swap the factors of a product. `swap (a, b) = (b, a)` -/ def swap : Ξ± Γ— Ξ² β†’ Ξ² Γ— Ξ± := Ξ»p => (p.2, p.1) @[simp] lemma swap_swap : βˆ€ x : Ξ± Γ— Ξ², swap (swap x) = x | ⟨a, b⟩ => rfl @[simp] lemma fst_swap {p : Ξ± Γ— Ξ²} : (swap p).1 = p.2 := rfl @[simp] lemma snd_swap {p : Ξ± Γ— Ξ²} : (swap p).2 = p.1 := rfl @[simp] lemma swap_prod_mk {a : Ξ±} {b : Ξ²} : swap (a, b) = (b, a) := rfl @[simp] lemma swap_swap_eq : swap ∘ swap = @id (Ξ± Γ— Ξ²) := funext swap_swap @[simp] lemma swap_left_inverse : Function.left_inverse (@swap Ξ± Ξ²) swap := swap_swap @[simp] lemma swap_right_inverse : Function.right_inverse (@swap Ξ± Ξ²) swap := swap_swap lemma swap_injective : Function.injective (@swap Ξ± Ξ²) := swap_left_inverse.injective lemma swap_surjective : Function.surjective (@swap Ξ± Ξ²) := Function.right_inverse.surjective swap_left_inverse lemma swap_bijective : Function.bijective (@swap Ξ± Ξ²) := ⟨swap_injective, swap_surjective⟩ @[simp] lemma swap_inj {p q : Ξ± Γ— Ξ²} : swap p = swap q ↔ p = q := swap_injective.eq_iff lemma eq_iff_fst_eq_snd_eq : βˆ€{p q : Ξ± Γ— Ξ²}, p = q ↔ (p.1 = q.1 ∧ p.2 = q.2) | ⟨p₁, pβ‚‚βŸ©, ⟨q₁, qβ‚‚βŸ© => by simp lemma fst_eq_iff : βˆ€ {p : Ξ± Γ— Ξ²} {x : Ξ±}, p.1 = x ↔ p = (x, p.2) | ⟨a, b⟩, x => by simp lemma snd_eq_iff : βˆ€ {p : Ξ± Γ— Ξ²} {x : Ξ²}, p.2 = x ↔ p = (p.1, x) | ⟨a, b⟩, x => by simp theorem lex_def (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) {p q : Ξ± Γ— Ξ²} : Prod.Lex r s p q ↔ r p.1 q.1 ∨ p.1 = q.1 ∧ s p.2 q.2 := ⟨(Ξ» h => match h with | Lex.left b1 b2 h1 => by simp [h1] | Lex.right a h1 => by simp [h1] ), Ξ» h => match p, q, h with | (a, b), (c, d), Or.inl h => Lex.left _ _ h | (a, b), (c, d), Or.inr ⟨e, h⟩ => by subst e; exact Lex.right _ h ⟩ instance Lex.decidable [DecidableEq Ξ±] (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) [DecidableRel r] [DecidableRel s] : DecidableRel (Prod.Lex r s) := Ξ» p q => decidable_of_decidable_of_iff (by infer_instance) (lex_def r s).symm end Prod open Function lemma Function.injective.prod_map {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ΄} (hf : injective f) (hg : injective g) : injective (Prod.map f g) := by intros x y h have h1 := (Prod.ext_iff.1 h).1 rw [Prod.map_fst, Prod.map_fst] at h1 have h2 := (Prod.ext_iff.1 h).2 rw [Prod.map_snd, Prod.map_snd] at h2 exact Prod.ext' (hf h1) (hg h2) lemma Function.surjective.prod_map {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ΄} (hf : surjective f) (hg : surjective g) : surjective (Prod.map f g) := Ξ» p => let ⟨x, hx⟩ := hf p.1 let ⟨y, hy⟩ := hg p.2 ⟨(x, y), Prod.ext' hx hy⟩
474100eb97649df356f46c568aeaa297b47cae87
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/is_tensor_product.lean
dceb63548b86c501da2f9331173e849d9296cae7
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
18,211
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import ring_theory.tensor_product import algebra.module.ulift /-! # The characteristice predicate of tensor product ## Main definitions - `is_tensor_product`: A predicate on `f : M₁ β†’β‚—[R] Mβ‚‚ β†’β‚—[R] M` expressing that `f` realizes `M` as the tensor product of `M₁ βŠ—[R] Mβ‚‚`. This is defined by requiring the lift `M₁ βŠ—[R] Mβ‚‚ β†’ M` to be bijective. - `is_base_change`: A predicate on an `R`-algebra `S` and a map `f : M β†’β‚—[R] N` with `N` being a `S`-module, expressing that `f` realizes `N` as the base change of `M` along `R β†’ S`. - `algebra.is_pushout`: A predicate on the following diagram of scalar towers ``` R β†’ S ↓ ↓ R' β†’ S' ``` asserting that is a pushout diagram (i.e. `S' = S βŠ—[R] R'`) ## Main results - `tensor_product.is_base_change`: `S βŠ—[R] M` is the base change of `M` along `R β†’ S`. -/ universes u v₁ vβ‚‚ v₃ vβ‚„ open_locale tensor_product open tensor_product section is_tensor_product variables {R : Type*} [comm_ring R] variables {M₁ Mβ‚‚ M M' : Type*} variables [add_comm_monoid M₁] [add_comm_monoid Mβ‚‚] [add_comm_monoid M] [add_comm_monoid M'] variables [module R M₁] [module R Mβ‚‚] [module R M] [module R M'] variable (f : M₁ β†’β‚—[R] Mβ‚‚ β†’β‚—[R] M) variables {N₁ Nβ‚‚ N : Type*} [add_comm_monoid N₁] [add_comm_monoid Nβ‚‚] [add_comm_monoid N] variables [module R N₁] [module R Nβ‚‚] [module R N] variable {g : N₁ β†’β‚—[R] Nβ‚‚ β†’β‚—[R] N} /-- Given a bilinear map `f : M₁ β†’β‚—[R] Mβ‚‚ β†’β‚—[R] M`, `is_tensor_product f` means that `M` is the tensor product of `M₁` and `Mβ‚‚` via `f`. This is defined by requiring the lift `M₁ βŠ—[R] Mβ‚‚ β†’ M` to be bijective. -/ def is_tensor_product : Prop := function.bijective (tensor_product.lift f) variables (R M N) {f} lemma tensor_product.is_tensor_product : is_tensor_product (tensor_product.mk R M N) := begin delta is_tensor_product, convert_to function.bijective linear_map.id using 2, { apply tensor_product.ext', simp }, { exact function.bijective_id } end variables {R M N} /-- If `M` is the tensor product of `M₁` and `Mβ‚‚`, it is linearly equivalent to `M₁ βŠ—[R] Mβ‚‚`. -/ @[simps apply] noncomputable def is_tensor_product.equiv (h : is_tensor_product f) : M₁ βŠ—[R] Mβ‚‚ ≃ₗ[R] M := linear_equiv.of_bijective _ h @[simp] lemma is_tensor_product.equiv_to_linear_map (h : is_tensor_product f) : h.equiv.to_linear_map = tensor_product.lift f := rfl @[simp] lemma is_tensor_product.equiv_symm_apply (h : is_tensor_product f) (x₁ : M₁) (xβ‚‚ : Mβ‚‚) : h.equiv.symm (f x₁ xβ‚‚) = x₁ βŠ—β‚œ xβ‚‚ := begin apply h.equiv.injective, refine (h.equiv.apply_symm_apply _).trans _, simp end /-- If `M` is the tensor product of `M₁` and `Mβ‚‚`, we may lift a bilinear map `M₁ β†’β‚—[R] Mβ‚‚ β†’β‚—[R] M'` to a `M β†’β‚—[R] M'`. -/ noncomputable def is_tensor_product.lift (h : is_tensor_product f) (f' : M₁ β†’β‚—[R] Mβ‚‚ β†’β‚—[R] M') : M β†’β‚—[R] M' := (tensor_product.lift f').comp h.equiv.symm.to_linear_map lemma is_tensor_product.lift_eq (h : is_tensor_product f) (f' : M₁ β†’β‚—[R] Mβ‚‚ β†’β‚—[R] M') (x₁ : M₁) (xβ‚‚ : Mβ‚‚) : h.lift f' (f x₁ xβ‚‚) = f' x₁ xβ‚‚ := begin delta is_tensor_product.lift, simp, end /-- The tensor product of a pair of linear maps between modules. -/ noncomputable def is_tensor_product.map (hf : is_tensor_product f) (hg : is_tensor_product g) (i₁ : M₁ β†’β‚—[R] N₁) (iβ‚‚ : Mβ‚‚ β†’β‚—[R] Nβ‚‚) : M β†’β‚—[R] N := hg.equiv.to_linear_map.comp ((tensor_product.map i₁ iβ‚‚).comp hf.equiv.symm.to_linear_map) lemma is_tensor_product.map_eq (hf : is_tensor_product f) (hg : is_tensor_product g) (i₁ : M₁ β†’β‚—[R] N₁) (iβ‚‚ : Mβ‚‚ β†’β‚—[R] Nβ‚‚) (x₁ : M₁) (xβ‚‚ : Mβ‚‚) : hf.map hg i₁ iβ‚‚ (f x₁ xβ‚‚) = g (i₁ x₁) (iβ‚‚ xβ‚‚) := begin delta is_tensor_product.map, simp end lemma is_tensor_product.induction_on (h : is_tensor_product f) {C : M β†’ Prop} (m : M) (h0 : C 0) (htmul : βˆ€ x y, C (f x y)) (hadd : βˆ€ x y, C x β†’ C y β†’ C (x + y)) : C m := begin rw ← h.equiv.right_inv m, generalize : h.equiv.inv_fun m = y, change C (tensor_product.lift f y), induction y using tensor_product.induction_on, { rwa map_zero }, { rw tensor_product.lift.tmul, apply htmul }, { rw map_add, apply hadd; assumption } end end is_tensor_product section is_base_change variables {R : Type*} {M : Type v₁} {N : Type vβ‚‚} (S : Type v₃) variables [add_comm_monoid M] [add_comm_monoid N] [comm_ring R] variables [comm_ring S] [algebra R S] [module R M] [module R N] [module S N] [is_scalar_tower R S N] variables (f : M β†’β‚—[R] N) include f /-- Given an `R`-algebra `S` and an `R`-module `M`, an `S`-module `N` together with a map `f : M β†’β‚—[R] N` is the base change of `M` to `S` if the map `S Γ— M β†’ N, (s, m) ↦ s β€’ f m` is the tensor product. -/ def is_base_change : Prop := is_tensor_product (((algebra.of_id S $ module.End S (M β†’β‚—[R] N)).to_linear_map.flip f).restrict_scalars R) variables {S f} (h : is_base_change S f) variables {P Q : Type*} [add_comm_monoid P] [module R P] variables [add_comm_monoid Q] [module S Q] section variables [module R Q] [is_scalar_tower R S Q] /-- Suppose `f : M β†’β‚—[R] N` is the base change of `M` along `R β†’ S`. Then any `R`-linear map from `M` to an `S`-module factors thorugh `f`. -/ noncomputable def is_base_change.lift (g : M β†’β‚—[R] Q) : N β†’β‚—[S] Q := { map_smul' := Ξ» r x, begin let F := ((algebra.of_id S $ module.End S (M β†’β‚—[R] Q)) .to_linear_map.flip g).restrict_scalars R, have hF : βˆ€ (s : S) (m : M), h.lift F (s β€’ f m) = s β€’ g m := h.lift_eq F, change h.lift F (r β€’ x) = r β€’ h.lift F x, apply h.induction_on x, { rw [smul_zero, map_zero, smul_zero] }, { intros s m, change h.lift F (r β€’ s β€’ f m) = r β€’ h.lift F (s β€’ f m), rw [← mul_smul, hF, hF, mul_smul] }, { intros x₁ xβ‚‚ e₁ eβ‚‚, rw [map_add, smul_add, map_add, smul_add, e₁, eβ‚‚] } end, ..(h.lift (((algebra.of_id S $ module.End S (M β†’β‚—[R] Q)) .to_linear_map.flip g).restrict_scalars R)) } lemma is_base_change.lift_eq (g : M β†’β‚—[R] Q) (x : M) : h.lift g (f x) = g x := begin have hF : βˆ€ (s : S) (m : M), h.lift g (s β€’ f m) = s β€’ g m := h.lift_eq _, convert hF 1 x; rw one_smul, end lemma is_base_change.lift_comp (g : M β†’β‚—[R] Q) : ((h.lift g).restrict_scalars R).comp f = g := linear_map.ext (h.lift_eq g) end include h @[elab_as_eliminator] lemma is_base_change.induction_on (x : N) (P : N β†’ Prop) (h₁ : P 0) (hβ‚‚ : βˆ€ m : M, P (f m)) (h₃ : βˆ€ (s : S) n, P n β†’ P (s β€’ n)) (hβ‚„ : βˆ€ n₁ nβ‚‚, P n₁ β†’ P nβ‚‚ β†’ P (n₁ + nβ‚‚)) : P x := h.induction_on x h₁ (Ξ» s y, h₃ _ _ (hβ‚‚ _)) hβ‚„ lemma is_base_change.alg_hom_ext (g₁ gβ‚‚ : N β†’β‚—[S] Q) (e : βˆ€ x, g₁ (f x) = gβ‚‚ (f x)) : g₁ = gβ‚‚ := begin ext x, apply h.induction_on x, { rw [map_zero, map_zero] }, { assumption }, { intros s n e', rw [g₁.map_smul, gβ‚‚.map_smul, e'] }, { intros x y e₁ eβ‚‚, rw [map_add, map_add, e₁, eβ‚‚] } end lemma is_base_change.alg_hom_ext' [module R Q] [is_scalar_tower R S Q] (g₁ gβ‚‚ : N β†’β‚—[S] Q) (e : (g₁.restrict_scalars R).comp f = (gβ‚‚.restrict_scalars R).comp f) : g₁ = gβ‚‚ := h.alg_hom_ext g₁ gβ‚‚ (linear_map.congr_fun e) variables (R M N S) omit h f lemma tensor_product.is_base_change : is_base_change S (tensor_product.mk R S M 1) := begin delta is_base_change, convert tensor_product.is_tensor_product R S M using 1, ext s x, change s β€’ 1 βŠ—β‚œ x = s βŠ—β‚œ x, rw tensor_product.smul_tmul', congr' 1, exact mul_one _, end variables {R M N S} /-- The base change of `M` along `R β†’ S` is linearly equivalent to `S βŠ—[R] M`. -/ noncomputable def is_base_change.equiv : S βŠ—[R] M ≃ₗ[S] N := { map_smul' := Ξ» r x, begin change h.equiv (r β€’ x) = r β€’ h.equiv x, apply tensor_product.induction_on x, { rw [smul_zero, map_zero, smul_zero] }, { intros x y, simp [smul_tmul', algebra.of_id_apply] }, { intros x y hx hy, rw [map_add, smul_add, map_add, smul_add, hx, hy] }, end, ..h.equiv } lemma is_base_change.equiv_tmul (s : S) (m : M) : h.equiv (s βŠ—β‚œ m) = s β€’ (f m) := tensor_product.lift.tmul s m lemma is_base_change.equiv_symm_apply (m : M) : h.equiv.symm (f m) = 1 βŠ—β‚œ m := by rw [h.equiv.symm_apply_eq, h.equiv_tmul, one_smul] variable (f) lemma is_base_change.of_lift_unique (h : βˆ€ (Q : Type (max v₁ vβ‚‚ v₃)) [add_comm_monoid Q], by exactI βˆ€ [module R Q] [module S Q], by exactI βˆ€ [is_scalar_tower R S Q], by exactI βˆ€ (g : M β†’β‚—[R] Q), βˆƒ! (g' : N β†’β‚—[S] Q), (g'.restrict_scalars R).comp f = g) : is_base_change S f := begin obtain ⟨g, hg, -⟩ := h (ulift.{vβ‚‚} $ S βŠ—[R] M) (ulift.module_equiv.symm.to_linear_map.comp $ tensor_product.mk R S M 1), let f' : S βŠ—[R] M β†’β‚—[R] N := _, change function.bijective f', let f'' : S βŠ—[R] M β†’β‚—[S] N, { refine { to_fun := f', map_smul' := Ξ» s x, tensor_product.induction_on x _ (Ξ» s' y, smul_assoc s s' _) (Ξ» x y hx hy, _), .. f' }, { rw [map_zero, smul_zero, map_zero, smul_zero] }, { rw [smul_add, map_add, map_add, smul_add, hx, hy] } }, simp_rw [fun_like.ext_iff, linear_map.comp_apply, linear_map.restrict_scalars_apply] at hg, let fe : S βŠ—[R] M ≃ₗ[S] N := linear_equiv.of_linear f'' (ulift.module_equiv.to_linear_map.comp g) _ _, { exact fe.bijective }, { rw ← (linear_map.cancel_left (ulift.module_equiv : ulift.{max v₁ v₃} N ≃ₗ[S] N).symm.injective), refine (h (ulift.{max v₁ v₃} N) $ ulift.module_equiv.symm.to_linear_map.comp f).unique _ rfl, { apply_instance }, ext x, simp only [linear_map.comp_apply, linear_map.restrict_scalars_apply, hg], apply one_smul }, { ext x, change (g $ (1 : S) β€’ f x).down = _, rw [one_smul, hg], refl }, end variable {f} lemma is_base_change.iff_lift_unique : is_base_change S f ↔ βˆ€ (Q : Type (max v₁ vβ‚‚ v₃)) [add_comm_monoid Q], by exactI βˆ€ [module R Q] [module S Q], by exactI βˆ€ [is_scalar_tower R S Q], by exactI βˆ€ (g : M β†’β‚—[R] Q), βˆƒ! (g' : N β†’β‚—[S] Q), (g'.restrict_scalars R).comp f = g := ⟨λ h, by { introsI, exact ⟨h.lift g, h.lift_comp g, Ξ» g' e, h.alg_hom_ext' _ _ (e.trans (h.lift_comp g).symm)⟩ }, is_base_change.of_lift_unique f⟩ lemma is_base_change.of_equiv (e : M ≃ₗ[R] N) : is_base_change R e.to_linear_map := begin apply is_base_change.of_lift_unique, introsI Q I₁ Iβ‚‚ I₃ Iβ‚„ g, have : Iβ‚‚ = I₃, { ext r q, rw [← one_smul R q, smul_smul, ← smul_assoc, smul_eq_mul, mul_one] }, unfreezingI { cases this }, refine ⟨g.comp e.symm.to_linear_map, by { ext, simp }, _⟩, rintros y (rfl : _ = _), ext, simp, end variables {T O : Type*} [comm_ring T] [algebra R T] [algebra S T] [is_scalar_tower R S T] variables [add_comm_monoid O] [module R O] [module S O] [module T O] [is_scalar_tower S T O] variables [is_scalar_tower R S O] [is_scalar_tower R T O] lemma is_base_change.comp {f : M β†’β‚—[R] N} (hf : is_base_change S f) {g : N β†’β‚—[S] O} (hg : is_base_change T g) : is_base_change T ((g.restrict_scalars R).comp f) := begin apply is_base_change.of_lift_unique, introsI Q _ _ _ _ i, letI := module.comp_hom Q (algebra_map S T), haveI : is_scalar_tower S T Q := ⟨λ x y z, by { rw [algebra.smul_def, mul_smul], refl }⟩, haveI : is_scalar_tower R S Q, { refine ⟨λ x y z, _⟩, change (is_scalar_tower.to_alg_hom R S T) (x β€’ y) β€’ z = x β€’ (algebra_map S T y β€’ z), rw [alg_hom.map_smul, smul_assoc], refl }, refine ⟨hg.lift (hf.lift i), by { ext, simp [is_base_change.lift_eq] }, _⟩, rintros g' (e : _ = _), refine hg.alg_hom_ext' _ _ (hf.alg_hom_ext' _ _ _), rw [is_base_change.lift_comp, is_base_change.lift_comp, ← e], ext, refl end variables {R' S' : Type*} [comm_ring R'] [comm_ring S'] variables [algebra R R'] [algebra S S'] [algebra R' S'] [algebra R S'] variables [is_scalar_tower R R' S'] [is_scalar_tower R S S'] open is_scalar_tower (to_alg_hom) variables (R S R' S') /-- A type-class stating that the following diagram of scalar towers R β†’ S ↓ ↓ R' β†’ S' is a pushout diagram (i.e. `S' = S βŠ—[R] R'`) -/ @[mk_iff] class algebra.is_pushout : Prop := (out : is_base_change S (to_alg_hom R R' S').to_linear_map) variables {R S R' S'} lemma algebra.is_pushout.symm (h : algebra.is_pushout R S R' S') : algebra.is_pushout R R' S S' := begin letI := (algebra.tensor_product.include_right : R' →ₐ[R] S βŠ— R').to_ring_hom.to_algebra, let e : R' βŠ—[R] S ≃ₗ[R'] S', { refine { map_smul' := _, ..(tensor_product.comm R R' S).trans $ h.1.equiv.restrict_scalars R }, intros r x, change h.1.equiv (tensor_product.comm R R' S (r β€’ x)) = r β€’ h.1.equiv (tensor_product.comm R R' S x), apply tensor_product.induction_on x, { simp only [smul_zero, map_zero] }, { intros x y, simp [smul_tmul', algebra.smul_def, ring_hom.algebra_map_to_algebra, h.1.equiv_tmul], ring }, { intros x y hx hy, simp only [map_add, smul_add, hx, hy] } }, have : (to_alg_hom R S S').to_linear_map = (e.to_linear_map.restrict_scalars R).comp (tensor_product.mk R R' S 1), { ext, simp [e, h.1.equiv_tmul, algebra.smul_def] }, constructor, rw this, exact (tensor_product.is_base_change R S R').comp (is_base_change.of_equiv e), end variables (R S R' S') lemma algebra.is_pushout.comm : algebra.is_pushout R S R' S' ↔ algebra.is_pushout R R' S S' := ⟨algebra.is_pushout.symm, algebra.is_pushout.symm⟩ variables {R S R'} local attribute [instance] algebra.tensor_product.right_algebra instance tensor_product.is_pushout {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T] [algebra R S] [algebra R T] : algebra.is_pushout R S T (tensor_product R S T) := ⟨tensor_product.is_base_change R T S⟩ instance tensor_product.is_pushout' {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T] [algebra R S] [algebra R T] : algebra.is_pushout R T S (tensor_product R S T) := algebra.is_pushout.symm infer_instance /-- If `S' = S βŠ—[R] R'`, then any pair of `R`-algebra homomorphisms `f : S β†’ A` and `g : R' β†’ A` such that `f x` and `g y` commutes for all `x, y` descends to a (unique) homomoprhism `S' β†’ A`. -/ @[simps apply (lemmas_only)] noncomputable def algebra.pushout_desc [H : algebra.is_pushout R S R' S'] {A : Type*} [semiring A] [algebra R A] (f : S →ₐ[R] A) (g : R' →ₐ[R] A) (hf : βˆ€ x y, f x * g y = g y * f x) : S' →ₐ[R] A := begin letI := module.comp_hom A f.to_ring_hom, haveI : is_scalar_tower R S A := { smul_assoc := Ξ» r s a, show f (r β€’ s) * a = r β€’ (f s * a), by rw [f.map_smul, smul_mul_assoc] }, haveI : is_scalar_tower S A A := { smul_assoc := Ξ» r a b, mul_assoc _ _ _ }, have : βˆ€ x, H.out.lift g.to_linear_map (algebra_map R' S' x) = g x := H.out.lift_eq _, refine alg_hom.of_linear_map ((H.out.lift g.to_linear_map).restrict_scalars R) _ _, { dsimp only [linear_map.restrict_scalars_apply], rw [← (algebra_map R' S').map_one, this, g.map_one] }, { intros x y, apply H.out.induction_on x, { rw [zero_mul, map_zero, zero_mul] }, rotate, { intros s s' e, dsimp only [linear_map.restrict_scalars_apply] at e ⊒, rw [linear_map.map_smul, smul_mul_assoc, linear_map.map_smul, e, smul_mul_assoc] }, { intros s s' e₁ eβ‚‚, dsimp only [linear_map.restrict_scalars_apply] at e₁ eβ‚‚ ⊒, rw [add_mul, map_add, map_add, add_mul, e₁, eβ‚‚] }, intro x, dsimp, rw this, apply H.out.induction_on y, { rw [mul_zero, map_zero, mul_zero] }, { intro y, dsimp, rw [← _root_.map_mul, this, this, _root_.map_mul] }, { intros s s' e, rw [mul_comm, smul_mul_assoc, linear_map.map_smul, linear_map.map_smul, mul_comm, e], change f s * (g x * _) = g x * (f s * _), rw [← mul_assoc, ← mul_assoc, hf] }, { intros s s' e₁ eβ‚‚, rw [mul_add, map_add, map_add, mul_add, e₁, eβ‚‚] }, } end @[simp] lemma algebra.pushout_desc_left [H : algebra.is_pushout R S R' S'] {A : Type*} [semiring A] [algebra R A] (f : S →ₐ[R] A) (g : R' →ₐ[R] A) (H) (x : S) : algebra.pushout_desc S' f g H (algebra_map S S' x) = f x := begin rw [algebra.pushout_desc_apply, algebra.algebra_map_eq_smul_one, linear_map.map_smul, ← algebra.pushout_desc_apply S' f g H, _root_.map_one], exact mul_one (f x) end lemma algebra.lift_alg_hom_comp_left [H : algebra.is_pushout R S R' S'] {A : Type*} [semiring A] [algebra R A] (f : S →ₐ[R] A) (g : R' →ₐ[R] A) (H) : (algebra.pushout_desc S' f g H).comp (to_alg_hom R S S') = f := alg_hom.ext (Ξ» x, (algebra.pushout_desc_left S' f g H x : _)) @[simp] lemma algebra.pushout_desc_right [H : algebra.is_pushout R S R' S'] {A : Type*} [semiring A] [algebra R A] (f : S →ₐ[R] A) (g : R' →ₐ[R] A) (H) (x : R') : algebra.pushout_desc S' f g H (algebra_map R' S' x) = g x := begin apply_with @@is_base_change.lift_eq { instances := ff }, end lemma algebra.lift_alg_hom_comp_right [H : algebra.is_pushout R S R' S'] {A : Type*} [semiring A] [algebra R A] (f : S →ₐ[R] A) (g : R' →ₐ[R] A) (H) : (algebra.pushout_desc S' f g H).comp (to_alg_hom R R' S') = g := alg_hom.ext (Ξ» x, (algebra.pushout_desc_right S' f g H x : _)) @[ext] lemma algebra.is_pushout.alg_hom_ext [H : algebra.is_pushout R S R' S'] {A : Type*} [semiring A] [algebra R A] {f g : S' →ₐ[R] A} (h₁ : f.comp (to_alg_hom R R' S') = g.comp (to_alg_hom R R' S')) (hβ‚‚ : f.comp (to_alg_hom R S S') = g.comp (to_alg_hom R S S')) : f = g := begin ext x, apply H.1.induction_on x, { simp only [map_zero] }, { exact alg_hom.congr_fun h₁ }, { intros s s' e, rw [algebra.smul_def, f.map_mul, g.map_mul, e], congr' 1, exact (alg_hom.congr_fun hβ‚‚ s : _) }, { intros s₁ sβ‚‚ e₁ eβ‚‚, rw [map_add, map_add, e₁, eβ‚‚] } end end is_base_change
29d6a81643be7ad7e85df5aa97822aa5f97d0beb
c777c32c8e484e195053731103c5e52af26a25d1
/src/topology/metric_space/isometry.lean
ef29d1dcb320098192d07d857becf26a7cc892fc
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
20,544
lean
/- Copyright (c) 2018 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Isometries of emetric and metric spaces Authors: SΓ©bastien GouΓ«zel -/ import topology.metric_space.antilipschitz /-! # Isometries > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define isometries, i.e., maps between emetric spaces that preserve the edistance (on metric spaces, these are exactly the maps that preserve distances), and prove their basic properties. We also introduce isometric bijections. Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the theory for `pseudo_metric_space` and we specialize to `metric_space` when needed. -/ noncomputable theory universes u v w variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} open function set open_locale topology ennreal /-- An isometry (also known as isometric embedding) is a map preserving the edistance between pseudoemetric spaces, or equivalently the distance between pseudometric space. -/ def isometry [pseudo_emetric_space Ξ±] [pseudo_emetric_space Ξ²] (f : Ξ± β†’ Ξ²) : Prop := βˆ€x1 x2 : Ξ±, edist (f x1) (f x2) = edist x1 x2 /-- On pseudometric spaces, a map is an isometry if and only if it preserves nonnegative distances. -/ lemma isometry_iff_nndist_eq [pseudo_metric_space Ξ±] [pseudo_metric_space Ξ²] {f : Ξ± β†’ Ξ²} : isometry f ↔ (βˆ€x y, nndist (f x) (f y) = nndist x y) := by simp only [isometry, edist_nndist, ennreal.coe_eq_coe] /-- On pseudometric spaces, a map is an isometry if and only if it preserves distances. -/ lemma isometry_iff_dist_eq [pseudo_metric_space Ξ±] [pseudo_metric_space Ξ²] {f : Ξ± β†’ Ξ²} : isometry f ↔ (βˆ€x y, dist (f x) (f y) = dist x y) := by simp only [isometry_iff_nndist_eq, ← coe_nndist, nnreal.coe_eq] /-- An isometry preserves distances. -/ alias isometry_iff_dist_eq ↔ isometry.dist_eq _ /-- A map that preserves distances is an isometry -/ alias isometry_iff_dist_eq ↔ _ isometry.of_dist_eq /-- An isometry preserves non-negative distances. -/ alias isometry_iff_nndist_eq ↔ isometry.nndist_eq _ /-- A map that preserves non-negative distances is an isometry. -/ alias isometry_iff_nndist_eq ↔ _ isometry.of_nndist_eq namespace isometry section pseudo_emetric_isometry variables [pseudo_emetric_space Ξ±] [pseudo_emetric_space Ξ²] [pseudo_emetric_space Ξ³] variables {f : Ξ± β†’ Ξ²} {x y z : Ξ±} {s : set Ξ±} /-- An isometry preserves edistances. -/ theorem edist_eq (hf : isometry f) (x y : Ξ±) : edist (f x) (f y) = edist x y := hf x y lemma lipschitz (h : isometry f) : lipschitz_with 1 f := lipschitz_with.of_edist_le $ Ξ» x y, (h x y).le lemma antilipschitz (h : isometry f) : antilipschitz_with 1 f := Ξ» x y, by simp only [h x y, ennreal.coe_one, one_mul, le_refl] /-- Any map on a subsingleton is an isometry -/ @[nontriviality] theorem _root_.isometry_subsingleton [subsingleton Ξ±] : isometry f := Ξ»x y, by rw subsingleton.elim x y; simp /-- The identity is an isometry -/ lemma _root_.isometry_id : isometry (id : Ξ± β†’ Ξ±) := Ξ» x y, rfl lemma prod_map {Ξ΄} [pseudo_emetric_space Ξ΄] {f : Ξ± β†’ Ξ²} {g : Ξ³ β†’ Ξ΄} (hf : isometry f) (hg : isometry g) : isometry (prod.map f g) := Ξ» x y, by simp only [prod.edist_eq, hf.edist_eq, hg.edist_eq, prod_map] lemma _root_.isometry_dcomp {ΞΉ} [fintype ΞΉ] {Ξ± Ξ² : ΞΉ β†’ Type*} [Ξ  i, pseudo_emetric_space (Ξ± i)] [Ξ  i, pseudo_emetric_space (Ξ² i)] (f : Ξ  i, Ξ± i β†’ Ξ² i) (hf : βˆ€ i, isometry (f i)) : isometry (dcomp f) := Ξ» x y, by simp only [edist_pi_def, (hf _).edist_eq] /-- The composition of isometries is an isometry. -/ theorem comp {g : Ξ² β†’ Ξ³} {f : Ξ± β†’ Ξ²} (hg : isometry g) (hf : isometry f) : isometry (g ∘ f) := Ξ» x y, (hg _ _).trans (hf _ _) /-- An isometry from a metric space is a uniform continuous map -/ protected theorem uniform_continuous (hf : isometry f) : uniform_continuous f := hf.lipschitz.uniform_continuous /-- An isometry from a metric space is a uniform inducing map -/ protected theorem uniform_inducing (hf : isometry f) : uniform_inducing f := hf.antilipschitz.uniform_inducing hf.uniform_continuous lemma tendsto_nhds_iff {ΞΉ : Type*} {f : Ξ± β†’ Ξ²} {g : ΞΉ β†’ Ξ±} {a : filter ΞΉ} {b : Ξ±} (hf : isometry f) : filter.tendsto g a (𝓝 b) ↔ filter.tendsto (f ∘ g) a (𝓝 (f b)) := hf.uniform_inducing.inducing.tendsto_nhds_iff /-- An isometry is continuous. -/ protected lemma continuous (hf : isometry f) : continuous f := hf.lipschitz.continuous /-- The right inverse of an isometry is an isometry. -/ lemma right_inv {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ±} (h : isometry f) (hg : right_inverse g f) : isometry g := Ξ» x y, by rw [← h, hg _, hg _] lemma preimage_emetric_closed_ball (h : isometry f) (x : Ξ±) (r : ℝβ‰₯0∞) : f ⁻¹' (emetric.closed_ball (f x) r) = emetric.closed_ball x r := by { ext y, simp [h.edist_eq] } lemma preimage_emetric_ball (h : isometry f) (x : Ξ±) (r : ℝβ‰₯0∞) : f ⁻¹' (emetric.ball (f x) r) = emetric.ball x r := by { ext y, simp [h.edist_eq] } /-- Isometries preserve the diameter in pseudoemetric spaces. -/ lemma ediam_image (hf : isometry f) (s : set Ξ±) : emetric.diam (f '' s) = emetric.diam s := eq_of_forall_ge_iff $ Ξ» d, by simp only [emetric.diam_le_iff, ball_image_iff, hf.edist_eq] lemma ediam_range (hf : isometry f) : emetric.diam (range f) = emetric.diam (univ : set Ξ±) := by { rw ← image_univ, exact hf.ediam_image univ } lemma maps_to_emetric_ball (hf : isometry f) (x : Ξ±) (r : ℝβ‰₯0∞) : maps_to f (emetric.ball x r) (emetric.ball (f x) r) := (hf.preimage_emetric_ball x r).ge lemma maps_to_emetric_closed_ball (hf : isometry f) (x : Ξ±) (r : ℝβ‰₯0∞) : maps_to f (emetric.closed_ball x r) (emetric.closed_ball (f x) r) := (hf.preimage_emetric_closed_ball x r).ge /-- The injection from a subtype is an isometry -/ lemma _root_.isometry_subtype_coe {s : set Ξ±} : isometry (coe : s β†’ Ξ±) := Ξ»x y, rfl lemma comp_continuous_on_iff {Ξ³} [topological_space Ξ³] (hf : isometry f) {g : Ξ³ β†’ Ξ±} {s : set Ξ³} : continuous_on (f ∘ g) s ↔ continuous_on g s := hf.uniform_inducing.inducing.continuous_on_iff.symm lemma comp_continuous_iff {Ξ³} [topological_space Ξ³] (hf : isometry f) {g : Ξ³ β†’ Ξ±} : continuous (f ∘ g) ↔ continuous g := hf.uniform_inducing.inducing.continuous_iff.symm end pseudo_emetric_isometry --section section emetric_isometry variables [emetric_space Ξ±] [pseudo_emetric_space Ξ²] {f : Ξ± β†’ Ξ²} /-- An isometry from an emetric space is injective -/ protected lemma injective (h : isometry f) : injective f := h.antilipschitz.injective /-- An isometry from an emetric space is a uniform embedding -/ protected theorem uniform_embedding (hf : isometry f) : uniform_embedding f := hf.antilipschitz.uniform_embedding hf.lipschitz.uniform_continuous /-- An isometry from an emetric space is an embedding -/ protected theorem embedding (hf : isometry f) : embedding f := hf.uniform_embedding.embedding /-- An isometry from a complete emetric space is a closed embedding -/ theorem closed_embedding [complete_space Ξ±] [emetric_space Ξ³] {f : Ξ± β†’ Ξ³} (hf : isometry f) : closed_embedding f := hf.antilipschitz.closed_embedding hf.lipschitz.uniform_continuous end emetric_isometry --section section pseudo_metric_isometry variables [pseudo_metric_space Ξ±] [pseudo_metric_space Ξ²] {f : Ξ± β†’ Ξ²} /-- An isometry preserves the diameter in pseudometric spaces. -/ lemma diam_image (hf : isometry f) (s : set Ξ±) : metric.diam (f '' s) = metric.diam s := by rw [metric.diam, metric.diam, hf.ediam_image] lemma diam_range (hf : isometry f) : metric.diam (range f) = metric.diam (univ : set Ξ±) := by { rw ← image_univ, exact hf.diam_image univ } lemma preimage_set_of_dist (hf : isometry f) (x : Ξ±) (p : ℝ β†’ Prop) : f ⁻¹' {y | p (dist y (f x))} = {y | p (dist y x)} := by { ext y, simp [hf.dist_eq] } lemma preimage_closed_ball (hf : isometry f) (x : Ξ±) (r : ℝ) : f ⁻¹' (metric.closed_ball (f x) r) = metric.closed_ball x r := hf.preimage_set_of_dist x (≀ r) lemma preimage_ball (hf : isometry f) (x : Ξ±) (r : ℝ) : f ⁻¹' (metric.ball (f x) r) = metric.ball x r := hf.preimage_set_of_dist x (< r) lemma preimage_sphere (hf : isometry f) (x : Ξ±) (r : ℝ) : f ⁻¹' (metric.sphere (f x) r) = metric.sphere x r := hf.preimage_set_of_dist x (= r) lemma maps_to_ball (hf : isometry f) (x : Ξ±) (r : ℝ) : maps_to f (metric.ball x r) (metric.ball (f x) r) := (hf.preimage_ball x r).ge lemma maps_to_sphere (hf : isometry f) (x : Ξ±) (r : ℝ) : maps_to f (metric.sphere x r) (metric.sphere (f x) r) := (hf.preimage_sphere x r).ge lemma maps_to_closed_ball (hf : isometry f) (x : Ξ±) (r : ℝ) : maps_to f (metric.closed_ball x r) (metric.closed_ball (f x) r) := (hf.preimage_closed_ball x r).ge end pseudo_metric_isometry -- section end isometry -- namespace /-- A uniform embedding from a uniform space to a metric space is an isometry with respect to the induced metric space structure on the source space. -/ lemma uniform_embedding.to_isometry {Ξ± Ξ²} [uniform_space Ξ±] [metric_space Ξ²] {f : Ξ± β†’ Ξ²} (h : uniform_embedding f) : @isometry Ξ± Ξ² (@pseudo_metric_space.to_pseudo_emetric_space Ξ± (@metric_space.to_pseudo_metric_space Ξ± (h.comap_metric_space f))) (by apply_instance) f := begin apply isometry.of_dist_eq, assume x y, refl end /-- An embedding from a topological space to a metric space is an isometry with respect to the induced metric space structure on the source space. -/ lemma embedding.to_isometry {Ξ± Ξ²} [topological_space Ξ±] [metric_space Ξ²] {f : Ξ± β†’ Ξ²} (h : embedding f) : @isometry Ξ± Ξ² (@pseudo_metric_space.to_pseudo_emetric_space Ξ± (@metric_space.to_pseudo_metric_space Ξ± (h.comap_metric_space f))) (by apply_instance) f := begin apply isometry.of_dist_eq, assume x y, refl end /-- `Ξ±` and `Ξ²` are isometric if there is an isometric bijection between them. -/ @[nolint has_nonempty_instance] -- such a bijection need not exist structure isometry_equiv (Ξ± Ξ² : Type*) [pseudo_emetric_space Ξ±] [pseudo_emetric_space Ξ²] extends Ξ± ≃ Ξ² := (isometry_to_fun : isometry to_fun) infix ` ≃ᡒ `:25 := isometry_equiv namespace isometry_equiv section pseudo_emetric_space variables [pseudo_emetric_space Ξ±] [pseudo_emetric_space Ξ²] [pseudo_emetric_space Ξ³] instance : has_coe_to_fun (Ξ± ≃ᡒ Ξ²) (Ξ» _, Ξ± β†’ Ξ²) := ⟨λe, e.to_equiv⟩ lemma coe_eq_to_equiv (h : Ξ± ≃ᡒ Ξ²) (a : Ξ±) : h a = h.to_equiv a := rfl @[simp] lemma coe_to_equiv (h : Ξ± ≃ᡒ Ξ²) : ⇑h.to_equiv = h := rfl protected lemma isometry (h : Ξ± ≃ᡒ Ξ²) : isometry h := h.isometry_to_fun protected lemma bijective (h : Ξ± ≃ᡒ Ξ²) : bijective h := h.to_equiv.bijective protected lemma injective (h : Ξ± ≃ᡒ Ξ²) : injective h := h.to_equiv.injective protected lemma surjective (h : Ξ± ≃ᡒ Ξ²) : surjective h := h.to_equiv.surjective protected lemma edist_eq (h : Ξ± ≃ᡒ Ξ²) (x y : Ξ±) : edist (h x) (h y) = edist x y := h.isometry.edist_eq x y protected lemma dist_eq {Ξ± Ξ² : Type*} [pseudo_metric_space Ξ±] [pseudo_metric_space Ξ²] (h : Ξ± ≃ᡒ Ξ²) (x y : Ξ±) : dist (h x) (h y) = dist x y := h.isometry.dist_eq x y protected lemma nndist_eq {Ξ± Ξ² : Type*} [pseudo_metric_space Ξ±] [pseudo_metric_space Ξ²] (h : Ξ± ≃ᡒ Ξ²) (x y : Ξ±) : nndist (h x) (h y) = nndist x y := h.isometry.nndist_eq x y protected lemma continuous (h : Ξ± ≃ᡒ Ξ²) : continuous h := h.isometry.continuous @[simp] lemma ediam_image (h : Ξ± ≃ᡒ Ξ²) (s : set Ξ±) : emetric.diam (h '' s) = emetric.diam s := h.isometry.ediam_image s lemma to_equiv_inj : βˆ€ ⦃h₁ hβ‚‚ : Ξ± ≃ᡒ β⦄, (h₁.to_equiv = hβ‚‚.to_equiv) β†’ h₁ = hβ‚‚ | ⟨e₁, hβ‚βŸ© ⟨eβ‚‚, hβ‚‚βŸ© H := by { dsimp at H, subst e₁ } @[ext] lemma ext ⦃h₁ hβ‚‚ : Ξ± ≃ᡒ β⦄ (H : βˆ€ x, h₁ x = hβ‚‚ x) : h₁ = hβ‚‚ := to_equiv_inj $ equiv.ext H /-- Alternative constructor for isometric bijections, taking as input an isometry, and a right inverse. -/ def mk' {Ξ± : Type u} [emetric_space Ξ±] (f : Ξ± β†’ Ξ²) (g : Ξ² β†’ Ξ±) (hfg : βˆ€ x, f (g x) = x) (hf : isometry f) : Ξ± ≃ᡒ Ξ² := { to_fun := f, inv_fun := g, left_inv := Ξ» x, hf.injective $ hfg _, right_inv := hfg, isometry_to_fun := hf } /-- The identity isometry of a space. -/ protected def refl (Ξ± : Type*) [pseudo_emetric_space Ξ±] : Ξ± ≃ᡒ Ξ± := { isometry_to_fun := isometry_id, .. equiv.refl Ξ± } /-- The composition of two isometric isomorphisms, as an isometric isomorphism. -/ protected def trans (h₁ : Ξ± ≃ᡒ Ξ²) (hβ‚‚ : Ξ² ≃ᡒ Ξ³) : Ξ± ≃ᡒ Ξ³ := { isometry_to_fun := hβ‚‚.isometry_to_fun.comp h₁.isometry_to_fun, .. equiv.trans h₁.to_equiv hβ‚‚.to_equiv } @[simp] lemma trans_apply (h₁ : Ξ± ≃ᡒ Ξ²) (hβ‚‚ : Ξ² ≃ᡒ Ξ³) (x : Ξ±) : h₁.trans hβ‚‚ x = hβ‚‚ (h₁ x) := rfl /-- The inverse of an isometric isomorphism, as an isometric isomorphism. -/ protected def symm (h : Ξ± ≃ᡒ Ξ²) : Ξ² ≃ᡒ Ξ± := { isometry_to_fun := h.isometry.right_inv h.right_inv, to_equiv := h.to_equiv.symm } /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : Ξ± ≃ᡒ Ξ²) : Ξ± β†’ Ξ² := h /-- See Note [custom simps projection] -/ def simps.symm_apply (h : Ξ± ≃ᡒ Ξ²) : Ξ² β†’ Ξ± := h.symm initialize_simps_projections isometry_equiv (to_equiv_to_fun β†’ apply, to_equiv_inv_fun β†’ symm_apply) @[simp] lemma symm_symm (h : Ξ± ≃ᡒ Ξ²) : h.symm.symm = h := to_equiv_inj h.to_equiv.symm_symm @[simp] lemma apply_symm_apply (h : Ξ± ≃ᡒ Ξ²) (y : Ξ²) : h (h.symm y) = y := h.to_equiv.apply_symm_apply y @[simp] lemma symm_apply_apply (h : Ξ± ≃ᡒ Ξ²) (x : Ξ±) : h.symm (h x) = x := h.to_equiv.symm_apply_apply x lemma symm_apply_eq (h : Ξ± ≃ᡒ Ξ²) {x : Ξ±} {y : Ξ²} : h.symm y = x ↔ y = h x := h.to_equiv.symm_apply_eq lemma eq_symm_apply (h : Ξ± ≃ᡒ Ξ²) {x : Ξ±} {y : Ξ²} : x = h.symm y ↔ h x = y := h.to_equiv.eq_symm_apply lemma symm_comp_self (h : Ξ± ≃ᡒ Ξ²) : ⇑h.symm ∘ ⇑h = id := funext $ assume a, h.to_equiv.left_inv a lemma self_comp_symm (h : Ξ± ≃ᡒ Ξ²) : ⇑h ∘ ⇑h.symm = id := funext $ assume a, h.to_equiv.right_inv a @[simp] lemma range_eq_univ (h : Ξ± ≃ᡒ Ξ²) : range h = univ := h.to_equiv.range_eq_univ lemma image_symm (h : Ξ± ≃ᡒ Ξ²) : image h.symm = preimage h := image_eq_preimage_of_inverse h.symm.to_equiv.left_inv h.symm.to_equiv.right_inv lemma preimage_symm (h : Ξ± ≃ᡒ Ξ²) : preimage h.symm = image h := (image_eq_preimage_of_inverse h.to_equiv.left_inv h.to_equiv.right_inv).symm @[simp] lemma symm_trans_apply (h₁ : Ξ± ≃ᡒ Ξ²) (hβ‚‚ : Ξ² ≃ᡒ Ξ³) (x : Ξ³) : (h₁.trans hβ‚‚).symm x = h₁.symm (hβ‚‚.symm x) := rfl lemma ediam_univ (h : Ξ± ≃ᡒ Ξ²) : emetric.diam (univ : set Ξ±) = emetric.diam (univ : set Ξ²) := by rw [← h.range_eq_univ, h.isometry.ediam_range] @[simp] lemma ediam_preimage (h : Ξ± ≃ᡒ Ξ²) (s : set Ξ²) : emetric.diam (h ⁻¹' s) = emetric.diam s := by rw [← image_symm, ediam_image] @[simp] lemma preimage_emetric_ball (h : Ξ± ≃ᡒ Ξ²) (x : Ξ²) (r : ℝβ‰₯0∞) : h ⁻¹' (emetric.ball x r) = emetric.ball (h.symm x) r := by rw [← h.isometry.preimage_emetric_ball (h.symm x) r, h.apply_symm_apply] @[simp] lemma preimage_emetric_closed_ball (h : Ξ± ≃ᡒ Ξ²) (x : Ξ²) (r : ℝβ‰₯0∞) : h ⁻¹' (emetric.closed_ball x r) = emetric.closed_ball (h.symm x) r := by rw [← h.isometry.preimage_emetric_closed_ball (h.symm x) r, h.apply_symm_apply] @[simp] lemma image_emetric_ball (h : Ξ± ≃ᡒ Ξ²) (x : Ξ±) (r : ℝβ‰₯0∞) : h '' (emetric.ball x r) = emetric.ball (h x) r := by rw [← h.preimage_symm, h.symm.preimage_emetric_ball, symm_symm] @[simp] lemma image_emetric_closed_ball (h : Ξ± ≃ᡒ Ξ²) (x : Ξ±) (r : ℝβ‰₯0∞) : h '' (emetric.closed_ball x r) = emetric.closed_ball (h x) r := by rw [← h.preimage_symm, h.symm.preimage_emetric_closed_ball, symm_symm] /-- The (bundled) homeomorphism associated to an isometric isomorphism. -/ @[simps to_equiv] protected def to_homeomorph (h : Ξ± ≃ᡒ Ξ²) : Ξ± β‰ƒβ‚œ Ξ² := { continuous_to_fun := h.continuous, continuous_inv_fun := h.symm.continuous, to_equiv := h.to_equiv } @[simp] lemma coe_to_homeomorph (h : Ξ± ≃ᡒ Ξ²) : ⇑(h.to_homeomorph) = h := rfl @[simp] lemma coe_to_homeomorph_symm (h : Ξ± ≃ᡒ Ξ²) : ⇑(h.to_homeomorph.symm) = h.symm := rfl @[simp] lemma comp_continuous_on_iff {Ξ³} [topological_space Ξ³] (h : Ξ± ≃ᡒ Ξ²) {f : Ξ³ β†’ Ξ±} {s : set Ξ³} : continuous_on (h ∘ f) s ↔ continuous_on f s := h.to_homeomorph.comp_continuous_on_iff _ _ @[simp] lemma comp_continuous_iff {Ξ³} [topological_space Ξ³] (h : Ξ± ≃ᡒ Ξ²) {f : Ξ³ β†’ Ξ±} : continuous (h ∘ f) ↔ continuous f := h.to_homeomorph.comp_continuous_iff @[simp] lemma comp_continuous_iff' {Ξ³} [topological_space Ξ³] (h : Ξ± ≃ᡒ Ξ²) {f : Ξ² β†’ Ξ³} : continuous (f ∘ h) ↔ continuous f := h.to_homeomorph.comp_continuous_iff' /-- The group of isometries. -/ instance : group (Ξ± ≃ᡒ Ξ±) := { one := isometry_equiv.refl _, mul := Ξ» e₁ eβ‚‚, eβ‚‚.trans e₁, inv := isometry_equiv.symm, mul_assoc := Ξ» e₁ eβ‚‚ e₃, rfl, one_mul := Ξ» e, ext $ Ξ» _, rfl, mul_one := Ξ» e, ext $ Ξ» _, rfl, mul_left_inv := Ξ» e, ext e.symm_apply_apply } @[simp] lemma coe_one : ⇑(1 : Ξ± ≃ᡒ Ξ±) = id := rfl @[simp] lemma coe_mul (e₁ eβ‚‚ : Ξ± ≃ᡒ Ξ±) : ⇑(e₁ * eβ‚‚) = e₁ ∘ eβ‚‚ := rfl lemma mul_apply (e₁ eβ‚‚ : Ξ± ≃ᡒ Ξ±) (x : Ξ±) : (e₁ * eβ‚‚) x = e₁ (eβ‚‚ x) := rfl @[simp] lemma inv_apply_self (e : Ξ± ≃ᡒ Ξ±) (x: Ξ±) : e⁻¹ (e x) = x := e.symm_apply_apply x @[simp] lemma apply_inv_self (e : Ξ± ≃ᡒ Ξ±) (x: Ξ±) : e (e⁻¹ x) = x := e.apply_symm_apply x protected lemma complete_space [complete_space Ξ²] (e : Ξ± ≃ᡒ Ξ²) : complete_space Ξ± := complete_space_of_is_complete_univ $ is_complete_of_complete_image e.isometry.uniform_inducing $ by rwa [set.image_univ, isometry_equiv.range_eq_univ, ← complete_space_iff_is_complete_univ] lemma complete_space_iff (e : Ξ± ≃ᡒ Ξ²) : complete_space Ξ± ↔ complete_space Ξ² := by { split; introI H, exacts [e.symm.complete_space, e.complete_space] } end pseudo_emetric_space section pseudo_metric_space variables [pseudo_metric_space Ξ±] [pseudo_metric_space Ξ²] (h : Ξ± ≃ᡒ Ξ²) @[simp] lemma diam_image (s : set Ξ±) : metric.diam (h '' s) = metric.diam s := h.isometry.diam_image s @[simp] lemma diam_preimage (s : set Ξ²) : metric.diam (h ⁻¹' s) = metric.diam s := by rw [← image_symm, diam_image] lemma diam_univ : metric.diam (univ : set Ξ±) = metric.diam (univ : set Ξ²) := congr_arg ennreal.to_real h.ediam_univ @[simp] lemma preimage_ball (h : Ξ± ≃ᡒ Ξ²) (x : Ξ²) (r : ℝ) : h ⁻¹' (metric.ball x r) = metric.ball (h.symm x) r := by rw [← h.isometry.preimage_ball (h.symm x) r, h.apply_symm_apply] @[simp] lemma preimage_sphere (h : Ξ± ≃ᡒ Ξ²) (x : Ξ²) (r : ℝ) : h ⁻¹' (metric.sphere x r) = metric.sphere (h.symm x) r := by rw [← h.isometry.preimage_sphere (h.symm x) r, h.apply_symm_apply] @[simp] lemma preimage_closed_ball (h : Ξ± ≃ᡒ Ξ²) (x : Ξ²) (r : ℝ) : h ⁻¹' (metric.closed_ball x r) = metric.closed_ball (h.symm x) r := by rw [← h.isometry.preimage_closed_ball (h.symm x) r, h.apply_symm_apply] @[simp] lemma image_ball (h : Ξ± ≃ᡒ Ξ²) (x : Ξ±) (r : ℝ) : h '' (metric.ball x r) = metric.ball (h x) r := by rw [← h.preimage_symm, h.symm.preimage_ball, symm_symm] @[simp] lemma image_sphere (h : Ξ± ≃ᡒ Ξ²) (x : Ξ±) (r : ℝ) : h '' (metric.sphere x r) = metric.sphere (h x) r := by rw [← h.preimage_symm, h.symm.preimage_sphere, symm_symm] @[simp] lemma image_closed_ball (h : Ξ± ≃ᡒ Ξ²) (x : Ξ±) (r : ℝ) : h '' (metric.closed_ball x r) = metric.closed_ball (h x) r := by rw [← h.preimage_symm, h.symm.preimage_closed_ball, symm_symm] end pseudo_metric_space end isometry_equiv /-- An isometry induces an isometric isomorphism between the source space and the range of the isometry. -/ @[simps to_equiv apply { simp_rhs := tt }] def isometry.isometry_equiv_on_range [emetric_space Ξ±] [pseudo_emetric_space Ξ²] {f : Ξ± β†’ Ξ²} (h : isometry f) : Ξ± ≃ᡒ range f := { isometry_to_fun := Ξ»x y, by simpa [subtype.edist_eq] using h x y, to_equiv := equiv.of_injective f h.injective }
611186ddef4f0eccd6ce5a3751e8ea32456c42c9
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/algebra/bilinear.lean
ab8021367987bb9c99292a757e47aaa62d48805d
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,367
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.algebra.basic import algebra.hom.iterate import linear_algebra.tensor_product /-! # Facts about algebras involving bilinear maps and tensor products We move a few basic statements about algebras out of `algebra.algebra.basic`, in order to avoid importing `linear_algebra.bilinear_map` and `linear_algebra.tensor_product` unnecessarily. -/ universes u v w namespace algebra open_locale tensor_product open module section variables (R A : Type*) [comm_semiring R] [semiring A] [algebra R A] /-- The multiplication in an algebra is a bilinear map. A weaker version of this for semirings exists as `add_monoid_hom.mul`. -/ def lmul : A →ₐ[R] (End R A) := { map_one' := by { ext a, exact one_mul a }, map_mul' := by { intros a b, ext c, exact mul_assoc a b c }, map_zero' := by { ext a, exact zero_mul a }, commutes' := by { intro r, ext a, dsimp, rw [smul_def] }, .. (show A β†’β‚—[R] A β†’β‚—[R] A, from linear_map.mkβ‚‚ R (*) (Ξ» x y z, add_mul x y z) (Ξ» c x y, by rw [smul_def, smul_def, mul_assoc _ x y]) (Ξ» x y z, mul_add x y z) (Ξ» c x y, by rw [smul_def, smul_def, left_comm])) } variables {R A} @[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl variables (R) /-- The multiplication on the left in an algebra is a linear map. -/ def lmul_left (r : A) : A β†’β‚—[R] A := lmul R A r @[simp] lemma lmul_left_to_add_monoid_hom (r : A) : (lmul_left R r : A β†’+ A) = add_monoid_hom.mul_left r := fun_like.coe_injective rfl /-- The multiplication on the right in an algebra is a linear map. -/ def lmul_right (r : A) : A β†’β‚—[R] A := (lmul R A).to_linear_map.flip r @[simp] lemma lmul_right_to_add_monoid_hom (r : A) : (lmul_right R r : A β†’+ A) = add_monoid_hom.mul_right r := fun_like.coe_injective rfl /-- Simultaneous multiplication on the left and right is a linear map. -/ def lmul_left_right (vw: A Γ— A) : A β†’β‚—[R] A := (lmul_right R vw.2).comp (lmul_left R vw.1) lemma commute_lmul_left_right (a b : A) : commute (lmul_left R a) (lmul_right R b) := by { ext c, exact (mul_assoc a c b).symm, } /-- The multiplication map on an algebra, as an `R`-linear map from `A βŠ—[R] A` to `A`. -/ def lmul' : A βŠ—[R] A β†’β‚—[R] A := tensor_product.lift (lmul R A).to_linear_map variables {R A} @[simp] lemma lmul'_apply {x y : A} : lmul' R (x βŠ—β‚œ y) = x * y := by simp only [algebra.lmul', tensor_product.lift.tmul, alg_hom.to_linear_map_apply, lmul_apply] @[simp] lemma lmul_left_apply (p q : A) : lmul_left R p q = p * q := rfl @[simp] lemma lmul_right_apply (p q : A) : lmul_right R p q = q * p := rfl @[simp] lemma lmul_left_right_apply (vw : A Γ— A) (p : A) : lmul_left_right R vw p = vw.1 * p * vw.2 := rfl @[simp] lemma lmul_left_one : lmul_left R (1:A) = linear_map.id := by { ext, simp only [linear_map.id_coe, one_mul, id.def, lmul_left_apply] } @[simp] lemma lmul_left_mul (a b : A) : lmul_left R (a * b) = (lmul_left R a).comp (lmul_left R b) := by { ext, simp only [lmul_left_apply, linear_map.comp_apply, mul_assoc] } @[simp] lemma lmul_right_one : lmul_right R (1:A) = linear_map.id := by { ext, simp only [linear_map.id_coe, mul_one, id.def, lmul_right_apply] } @[simp] lemma lmul_right_mul (a b : A) : lmul_right R (a * b) = (lmul_right R b).comp (lmul_right R a) := by { ext, simp only [lmul_right_apply, linear_map.comp_apply, mul_assoc] } @[simp] lemma lmul_left_zero_eq_zero : lmul_left R (0 : A) = 0 := (lmul R A).map_zero @[simp] lemma lmul_right_zero_eq_zero : lmul_right R (0 : A) = 0 := (lmul R A).to_linear_map.flip.map_zero @[simp] lemma lmul_left_eq_zero_iff (a : A) : lmul_left R a = 0 ↔ a = 0 := begin split; intros h, { rw [← mul_one a, ← lmul_left_apply a 1, h, linear_map.zero_apply], }, { rw h, exact lmul_left_zero_eq_zero, }, end @[simp] lemma lmul_right_eq_zero_iff (a : A) : lmul_right R a = 0 ↔ a = 0 := begin split; intros h, { rw [← one_mul a, ← lmul_right_apply a 1, h, linear_map.zero_apply], }, { rw h, exact lmul_right_zero_eq_zero, }, end @[simp] lemma pow_lmul_left (a : A) (n : β„•) : (lmul_left R a) ^ n = lmul_left R (a ^ n) := ((lmul R A).map_pow a n).symm @[simp] lemma pow_lmul_right (a : A) (n : β„•) : (lmul_right R a) ^ n = lmul_right R (a ^ n) := linear_map.coe_injective $ ((lmul_right R a).coe_pow n).symm β–Έ (mul_right_iterate a n) end section variables {R A : Type*} [comm_semiring R] [ring A] [algebra R A] lemma lmul_left_injective [no_zero_divisors A] {x : A} (hx : x β‰  0) : function.injective (lmul_left R x) := by { letI : is_domain A := { exists_pair_ne := ⟨x, 0, hx⟩, ..β€Ήring Aβ€Ί, ..β€Ήno_zero_divisors Aβ€Ί }, exact mul_right_injectiveβ‚€ hx } lemma lmul_right_injective [no_zero_divisors A] {x : A} (hx : x β‰  0) : function.injective (lmul_right R x) := by { letI : is_domain A := { exists_pair_ne := ⟨x, 0, hx⟩, ..β€Ήring Aβ€Ί, ..β€Ήno_zero_divisors Aβ€Ί }, exact mul_left_injectiveβ‚€ hx } lemma lmul_injective [no_zero_divisors A] {x : A} (hx : x β‰  0) : function.injective (lmul R A x) := by { letI : is_domain A := { exists_pair_ne := ⟨x, 0, hx⟩, ..β€Ήring Aβ€Ί, ..β€Ήno_zero_divisors Aβ€Ί }, exact mul_right_injectiveβ‚€ hx } end end algebra
ea6cfc7445ed46adbb6bd73398dfdeae81c7104b
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Meta/Match/Match.lean
e9bd6efbef9e9b792114f5147faecfe54f694c84
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
43,880
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.Closure import Lean.Meta.Tactic.Cases import Lean.Meta.Tactic.Contradiction import Lean.Meta.GeneralizeTelescope import Lean.Meta.Match.Basic namespace Lean.Meta.Match /-- The number of patterns in each AltLHS must be equal to the number of discriminants. -/ private def checkNumPatterns (numDiscrs : Nat) (lhss : List AltLHS) : MetaM Unit := do if lhss.any fun lhs => lhs.patterns.length != numDiscrs then throwError "incorrect number of patterns" /-- Execute `k hs` where `hs` contains new equalities `h : lhs[i] = rhs[i]` for each `discrInfos[i] = some h`. Assume `lhs.size == rhs.size == discrInfos.size` -/ private partial def withEqs (lhs rhs : Array Expr) (discrInfos : Array DiscrInfo) (k : Array Expr β†’ MetaM Ξ±) : MetaM Ξ± := do go 0 #[] where go (i : Nat) (hs : Array Expr) : MetaM Ξ± := do if i < lhs.size then if let some hName := discrInfos[i]!.hName? then withLocalDeclD hName (← mkEqHEq lhs[i]! rhs[i]!) fun h => go (i+1) (hs.push h) else go (i+1) hs else k hs /-- Given a list of `AltLHS`, create a minor premise for each one, convert them into `Alt`, and then execute `k` -/ private def withAlts {Ξ±} (motive : Expr) (discrs : Array Expr) (discrInfos : Array DiscrInfo) (lhss : List AltLHS) (k : List Alt β†’ Array (Expr Γ— Nat) β†’ MetaM Ξ±) : MetaM Ξ± := loop lhss [] #[] where mkMinorType (xs : Array Expr) (lhs : AltLHS) : MetaM Expr := withExistingLocalDecls lhs.fvarDecls do let args ← lhs.patterns.toArray.mapM (Pattern.toExpr Β· (annotate := true)) let minorType := mkAppN motive args withEqs discrs args discrInfos fun eqs => do mkForallFVars (xs ++ eqs) minorType loop (lhss : List AltLHS) (alts : List Alt) (minors : Array (Expr Γ— Nat)) : MetaM Ξ± := do match lhss with | [] => k alts.reverse minors | lhs::lhss => let xs := lhs.fvarDecls.toArray.map LocalDecl.toExpr let minorType ← mkMinorType xs lhs let hasParams := !xs.isEmpty || discrInfos.any fun info => info.hName?.isSome let (minorType, minorNumParams) := if hasParams then (minorType, xs.size) else (mkSimpleThunkType minorType, 1) let idx := alts.length let minorName := (`h).appendIndexAfter (idx+1) trace[Meta.Match.debug] "minor premise {minorName} : {minorType}" withLocalDeclD minorName minorType fun minor => do let rhs := if hasParams then mkAppN minor xs else mkApp minor (mkConst `Unit.unit) let minors := minors.push (minor, minorNumParams) let fvarDecls ← lhs.fvarDecls.mapM instantiateLocalDeclMVars let alts := { ref := lhs.ref, idx := idx, rhs := rhs, fvarDecls := fvarDecls, patterns := lhs.patterns, cnstrs := [] } :: alts loop lhss alts minors structure State where used : HashSet Nat := {} -- used alternatives counterExamples : List (List Example) := [] /-- Return true if the given (sub-)problem has been solved. -/ private def isDone (p : Problem) : Bool := p.vars.isEmpty /-- Return true if the next element on the `p.vars` list is a variable. -/ private def isNextVar (p : Problem) : Bool := match p.vars with | .fvar _ :: _ => true | _ => false private def hasAsPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | .as .. :: _ => true | _ => false private def hasCtorPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | .ctor .. :: _ => true | _ => false private def hasValPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | .val _ :: _ => true | _ => false private def hasNatValPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | .val v :: _ => v.isNatLit | _ => false private def hasVarPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | .var _ :: _ => true | _ => false private def hasArrayLitPattern (p : Problem) : Bool := p.alts.any fun alt => match alt.patterns with | .arrayLit .. :: _ => true | _ => false private def isVariableTransition (p : Problem) : Bool := p.alts.all fun alt => match alt.patterns with | .inaccessible _ :: _ => true | .var _ :: _ => true | _ => false private def isConstructorTransition (p : Problem) : Bool := (hasCtorPattern p || p.alts.isEmpty) && p.alts.all fun alt => match alt.patterns with | .ctor .. :: _ => true | .var _ :: _ => true | .inaccessible _ :: _ => true | _ => false private def isValueTransition (p : Problem) : Bool := hasVarPattern p && hasValPattern p && p.alts.all fun alt => match alt.patterns with | .val _ :: _ => true | .var _ :: _ => true | _ => false private def isArrayLitTransition (p : Problem) : Bool := hasArrayLitPattern p && hasVarPattern p && p.alts.all fun alt => match alt.patterns with | .arrayLit .. :: _ => true | .var _ :: _ => true | _ => false private def isNatValueTransition (p : Problem) : Bool := hasNatValPattern p && (!isNextVar p || p.alts.any fun alt => match alt.patterns with | .ctor .. :: _ => true | .inaccessible _ :: _ => true | _ => false) private def processSkipInaccessible (p : Problem) : Problem := Id.run do let x :: xs := p.vars | unreachable! let alts := p.alts.map fun alt => Id.run do let .inaccessible e :: ps := alt.patterns | unreachable! { alt with patterns := ps, cnstrs := (x, e) :: alt.cnstrs } { p with alts := alts, vars := xs } /-- If contraint is of the form `e ≋ x` where `x` is a free variable, reorient it as `x ≋ e` If - `x` is an `alt`-local declaration - `e` is not a free variable. -/ private def reorientCnstrs (alt : Alt) : Alt := let cnstrs := alt.cnstrs.map fun (lhs, rhs) => if rhs.isFVar && alt.isLocalDecl rhs.fvarId! then (rhs, lhs) else if !lhs.isFVar && rhs.isFVar then (rhs, lhs) else (lhs, rhs) { alt with cnstrs } /-- Remove constraints of the form `lhs ≋ rhs` where `lhs` and `rhs` are definitionally equal, or `lhs` is a free variable. -/ private def filterTrivialCnstrs (alt : Alt) : MetaM Alt := do let cnstrs ← withExistingLocalDecls alt.fvarDecls do alt.cnstrs.filterM fun (lhs, rhs) => do if (← isDefEqGuarded lhs rhs) then return false else if lhs.isFVar then return false else return true return { alt with cnstrs } /-- Find an alternative constraint of the form `x ≋ e` where `x` is an alternative local declarations, and `x` and `e` have definitionally equal types. Then, replace `x` with `e` in the alternative, and return it. Return `none` if the alternative does not contain a constraint of this form. -/ private def solveSomeLocalFVarIdCnstr? (alt : Alt) : MetaM (Option Alt) := withExistingLocalDecls alt.fvarDecls do let (some (fvarId, val), cnstrs) ← go alt.cnstrs | return none trace[Meta.Match.match] "found cnstr to solve {mkFVar fvarId} ↦ {val}" return some <| { alt with cnstrs }.replaceFVarId fvarId val where go (cnstrs : List (Expr Γ— Expr)) := do match cnstrs with | [] => return (none, []) | (lhs, rhs) :: cnstrs => if lhs.isFVar && alt.isLocalDecl lhs.fvarId! then if !(← dependsOn rhs lhs.fvarId!) && (← isDefEqGuarded (← inferType lhs) (← inferType rhs)) then return (some (lhs.fvarId!, rhs), cnstrs) let (p, cnstrs) ← go cnstrs return (p, (lhs, rhs) :: cnstrs) /-- Solve pending alternative constraints. If all constraints can be solved perform assignment `mvarId := alt.rhs`, and return true. -/ private partial def solveCnstrs (mvarId : MVarId) (alt : Alt) : StateRefT State MetaM Bool := do go (reorientCnstrs alt) where go (alt : Alt) : StateRefT State MetaM Bool := do match (← solveSomeLocalFVarIdCnstr? alt) with | some alt => go alt | none => let alt ← filterTrivialCnstrs alt if alt.cnstrs.isEmpty then let eType ← inferType alt.rhs let targetType ← mvarId.getType unless (← isDefEqGuarded targetType eType) do trace[Meta.Match.match] "assignGoalOf failed {eType} =?= {targetType}" throwError "dependent elimination failed, type mismatch when solving alternative with type{indentExpr eType}\nbut expected{indentExpr targetType}" mvarId.assign alt.rhs modify fun s => { s with used := s.used.insert alt.idx } return true else trace[Meta.Match.match] "alt has unsolved cnstrs:\n{← alt.toMessageData}" return false /-- Try to solve the problem by using the first alternative whose pending constraints can be resolved. -/ private def processLeaf (p : Problem) : StateRefT State MetaM Unit := p.mvarId.withContext do withPPForTacticGoal do trace[Meta.Match.match] "local context at processLeaf:\n{(← mkFreshTypeMVar).mvarId!}" go p.alts where go (alts : List Alt) : StateRefT State MetaM Unit := do match alts with | [] => /- TODO: allow users to configure which tactic is used to close leaves. -/ unless (← p.mvarId.contradictionCore {}) do trace[Meta.Match.match] "missing alternative" p.mvarId.admit modify fun s => { s with counterExamples := p.examples :: s.counterExamples } | alt :: alts => unless (← solveCnstrs p.mvarId alt) do go alts private def processAsPattern (p : Problem) : MetaM Problem := withGoalOf p do let x :: _ := p.vars | unreachable! let alts ← p.alts.mapM fun alt => do match alt.patterns with | .as fvarId p h :: ps => /- We used to use `checkAndReplaceFVarId` here, but `x` and `fvarId` may have different types when dependent types are beind used. Let's consider the repro for issue #471 ``` inductive vec : Nat β†’ Type | nil : vec 0 | cons : Int β†’ vec n β†’ vec n.succ def vec_len : vec n β†’ Nat | vec.nil => 0 | x@(vec.cons h t) => vec_len t + 1 ``` we reach the state ``` [Meta.Match.match] remaining variables: [x✝:(vec n✝)] alternatives: [n:(Nat), x:(vec (Nat.succ n)), h:(Int), t:(vec n)] |- [x@(vec.cons n h t)] => h_1 n x h t [x✝:(vec n✝)] |- [x✝] => h_2 n✝ x✝ ``` The variables `x✝:(vec n✝)` and `x:(vec (Nat.succ n))` have different types, but we perform the substitution anyway, because we claim the "discrepancy" will be corrected after we process the pattern `(vec.cons n h t)`. The right-hand-side is temporarily type incorrect, but we claim this is fine because it will be type correct again after we the pattern `(vec.cons n h t)`. TODO: try to find a cleaner solution. -/ let r ← mkEqRefl x return { alt with patterns := p :: ps }.replaceFVarId fvarId x |>.replaceFVarId h r | _ => return alt return { p with alts := alts } private def processVariable (p : Problem) : MetaM Problem := withGoalOf p do let x :: xs := p.vars | unreachable! let alts ← p.alts.mapM fun alt => do match alt.patterns with | .inaccessible e :: ps => return { alt with patterns := ps, cnstrs := (x, e) :: alt.cnstrs } | .var fvarId :: ps => withExistingLocalDecls alt.fvarDecls do if (← isDefEqGuarded (← fvarId.getType) (← inferType x)) then return { alt with patterns := ps }.replaceFVarId fvarId x else return { alt with patterns := ps, cnstrs := (mkFVar fvarId, x) :: alt.cnstrs } | _ => unreachable! return { p with alts := alts, vars := xs } /-! Note that we decided to store pending constraints to address issues exposed by #1279 and #1361. Here is a simplified version of the example on this issue (see test: `1279_simplified.lean`) ```lean inductive Arrow : Type β†’ Type β†’ Type 1 | id : Arrow a a | unit : Arrow Unit Unit | comp : Arrow Ξ² Ξ³ β†’ Arrow Ξ± Ξ² β†’ Arrow Ξ± Ξ³ deriving Repr def Arrow.compose (f : Arrow Ξ² Ξ³) (g : Arrow Ξ± Ξ²) : Arrow Ξ± Ξ³ := match f, g with | id, g => g | f, id => f | f, g => comp f g ``` The initial state for the `match`-expression above is ```lean [Meta.Match.match] remaining variables: [β✝:(Type), γ✝:(Type), f✝:(Arrow β✝ γ✝), g✝:(Arrow Ξ± β✝)] alternatives: [Ξ²:(Type), g:(Arrow Ξ± Ξ²)] |- [Ξ², .(Ξ²), (Arrow.id .(Ξ²)), g] => h_1 Ξ² g [Ξ³:(Type), f:(Arrow Ξ± Ξ³)] |- [.(Ξ±), Ξ³, f, (Arrow.id .(Ξ±))] => h_2 Ξ³ f [Ξ²:(Type), Ξ³:(Type), f:(Arrow Ξ² Ξ³), g:(Arrow Ξ± Ξ²)] |- [Ξ², Ξ³, f, g] => h_3 Ξ² Ξ³ f g ``` The first step is a variable-transition which replaces `Ξ²` with `β✝` in the first and third alternatives. The constraint `β✝ ≋ Ξ±` in the second alternative used to be discarded. We now store it at the alternative `cnstrs` field. -/ private def inLocalDecls (localDecls : List LocalDecl) (fvarId : FVarId) : Bool := localDecls.any fun d => d.fvarId == fvarId private def expandVarIntoCtor? (alt : Alt) (fvarId : FVarId) (ctorName : Name) : MetaM (Option Alt) := withExistingLocalDecls alt.fvarDecls do trace[Meta.Match.unify] "expandVarIntoCtor? fvarId: {mkFVar fvarId}, ctorName: {ctorName}, alt:\n{← alt.toMessageData}" let expectedType ← inferType (mkFVar fvarId) let expectedType ← whnfD expectedType let (ctorLevels, ctorParams) ← getInductiveUniverseAndParams expectedType let ctor := mkAppN (mkConst ctorName ctorLevels) ctorParams let ctorType ← inferType ctor forallTelescopeReducing ctorType fun ctorFields resultType => do let ctor := mkAppN ctor ctorFields let alt := alt.replaceFVarId fvarId ctor let ctorFieldDecls ← ctorFields.mapM fun ctorField => ctorField.fvarId!.getDecl let newAltDecls := ctorFieldDecls.toList ++ alt.fvarDecls let mut cnstrs := alt.cnstrs unless (← isDefEqGuarded resultType expectedType) do cnstrs := (resultType, expectedType) :: cnstrs trace[Meta.Match.unify] "expandVarIntoCtor? {mkFVar fvarId} : {expectedType}, ctor: {ctor}" let ctorFieldPatterns := ctorFieldDecls.toList.map fun decl => Pattern.var decl.fvarId return some { alt with fvarDecls := newAltDecls, patterns := ctorFieldPatterns ++ alt.patterns, cnstrs } private def getInductiveVal? (x : Expr) : MetaM (Option InductiveVal) := do let xType ← inferType x let xType ← whnfD xType match xType.getAppFn with | Expr.const constName _ => let cinfo ← getConstInfo constName match cinfo with | ConstantInfo.inductInfo val => return some val | _ => return none | _ => return none private def hasRecursiveType (x : Expr) : MetaM Bool := do match (← getInductiveVal? x) with | some val => return val.isRec | _ => return false /-- Given `alt` s.t. the next pattern is an inaccessible pattern `e`, try to normalize `e` into a constructor application. If it is not a constructor, throw an error. Otherwise, if it is a constructor application of `ctorName`, update the next patterns with the fields of the constructor. Otherwise, return none. -/ def processInaccessibleAsCtor (alt : Alt) (ctorName : Name) : MetaM (Option Alt) := do let env ← getEnv match alt.patterns with | p@(.inaccessible e) :: ps => trace[Meta.Match.match] "inaccessible in ctor step {e}" withExistingLocalDecls alt.fvarDecls do -- Try to push inaccessible annotations. let e ← whnfD e match e.constructorApp? env with | some (ctorVal, ctorArgs) => if ctorVal.name == ctorName then let fields := ctorArgs.extract ctorVal.numParams ctorArgs.size let fields := fields.toList.map .inaccessible return some { alt with patterns := fields ++ ps } else return none | _ => throwErrorAt alt.ref "dependent match elimination failed, inaccessible pattern found{indentD p.toMessageData}\nconstructor expected" | _ => unreachable! private def hasNonTrivialExample (p : Problem) : Bool := p.examples.any fun | Example.underscore => false | _ => true private def throwCasesException (p : Problem) (ex : Exception) : MetaM Ξ± := do match ex with | .error ref msg => let exampleMsg := if hasNonTrivialExample p then m!" after processing{indentD <| examplesToMessageData p.examples}" else "" throw <| Exception.error ref <| m!"{msg}{exampleMsg}\n" ++ "the dependent pattern matcher can solve the following kinds of equations\n" ++ "- <var> = <term> and <term> = <var>\n" ++ "- <term> = <term> where the terms are definitionally equal\n" ++ "- <constructor> = <constructor>, examples: List.cons x xs = List.cons y ys, and List.cons x xs = List.nil" | _ => throw ex private def processConstructor (p : Problem) : MetaM (Array Problem) := do trace[Meta.Match.match] "constructor step" let x :: xs := p.vars | unreachable! let subgoals? ← commitWhenSome? do let subgoals ← try p.mvarId.cases x.fvarId! catch ex => if p.alts.isEmpty then /- If we have no alternatives and dependent pattern matching fails, then a "missing cases" error is bettern than a "stuck" error message. -/ return none else throwCasesException p ex if subgoals.isEmpty then /- Easy case: we have solved problem `p` since there are no subgoals -/ return some #[] else if !p.alts.isEmpty then return some subgoals else do let isRec ← withGoalOf p <| hasRecursiveType x /- If there are no alternatives and the type of the current variable is recursive, we do NOT consider a constructor-transition to avoid nontermination. TODO: implement a more general approach if this is not sufficient in practice -/ if isRec then return none else return some subgoals let some subgoals := subgoals? | return #[{ p with vars := xs }] subgoals.mapM fun subgoal => subgoal.mvarId.withContext do let subst := subgoal.subst let fields := subgoal.fields.toList let newVars := fields ++ xs let newVars := newVars.map fun x => x.applyFVarSubst subst let subex := Example.ctor subgoal.ctorName <| fields.map fun field => match field with | .fvar fvarId => Example.var fvarId | _ => Example.underscore -- This case can happen due to dependent elimination let examples := p.examples.map <| Example.replaceFVarId x.fvarId! subex let examples := examples.map <| Example.applyFVarSubst subst let newAlts := p.alts.filter fun alt => match alt.patterns with | .ctor n .. :: _ => n == subgoal.ctorName | .var _ :: _ => true | .inaccessible _ :: _ => true | _ => false let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst let newAlts ← newAlts.filterMapM fun alt => do match alt.patterns with | .ctor _ _ _ fields :: ps => return some { alt with patterns := fields ++ ps } | .var fvarId :: ps => expandVarIntoCtor? { alt with patterns := ps } fvarId subgoal.ctorName | .inaccessible _ :: _ => processInaccessibleAsCtor alt subgoal.ctorName | _ => unreachable! return { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples } private def altsAreCtorLike (p : Problem) : MetaM Bool := withGoalOf p do p.alts.allM fun alt => do match alt.patterns with | .ctor .. :: _ => return true | .inaccessible e :: _ => return (← whnfD e).isConstructorApp (← getEnv) | _ => return false private def processNonVariable (p : Problem) : MetaM Problem := withGoalOf p do let x :: xs := p.vars | unreachable! if let some (ctorVal, xArgs) := (← whnfD x).constructorApp? (← getEnv) then if (← altsAreCtorLike p) then let alts ← p.alts.filterMapM fun alt => do match alt.patterns with | .ctor ctorName _ _ fields :: ps => if ctorName != ctorVal.name then return none else return some { alt with patterns := fields ++ ps } | .inaccessible _ :: _ => processInaccessibleAsCtor alt ctorVal.name | _ => unreachable! let xFields := xArgs.extract ctorVal.numParams xArgs.size return { p with alts := alts, vars := xFields.toList ++ xs } let alts ← p.alts.mapM fun alt => do match alt.patterns with | p :: ps => return { alt with patterns := ps, cnstrs := (x, ← p.toExpr) :: alt.cnstrs } | _ => unreachable! return { p with alts := alts, vars := xs } private def collectValues (p : Problem) : Array Expr := p.alts.foldl (init := #[]) fun values alt => match alt.patterns with | .val v :: _ => if values.contains v then values else values.push v | _ => values private def isFirstPatternVar (alt : Alt) : Bool := match alt.patterns with | .var _ :: _ => true | _ => false private def processValue (p : Problem) : MetaM (Array Problem) := do trace[Meta.Match.match] "value step" let x :: xs := p.vars | unreachable! let values := collectValues p let subgoals ← caseValues p.mvarId x.fvarId! values (substNewEqs := true) subgoals.mapIdxM fun i subgoal => do trace[Meta.Match.match] "processValue subgoal\n{MessageData.ofGoal subgoal.mvarId}" if h : i.val < values.size then let value := values.get ⟨i, h⟩ -- (x = value) branch let subst := subgoal.subst trace[Meta.Match.match] "processValue subst: {subst.map.toList.map fun p => mkFVar p.1}, {subst.map.toList.map fun p => p.2}" let examples := p.examples.map <| Example.replaceFVarId x.fvarId! (Example.val value) let examples := examples.map <| Example.applyFVarSubst subst let newAlts := p.alts.filter fun alt => match alt.patterns with | .val v :: _ => v == value | .var _ :: _ => true | _ => false let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst let newAlts := newAlts.map fun alt => match alt.patterns with | .val _ :: ps => { alt with patterns := ps } | .var fvarId :: ps => let alt := { alt with patterns := ps } alt.replaceFVarId fvarId value | _ => unreachable! let newVars := xs.map fun x => x.applyFVarSubst subst return { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples } else -- else branch for value let newAlts := p.alts.filter isFirstPatternVar return { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs } private def collectArraySizes (p : Problem) : Array Nat := p.alts.foldl (init := #[]) fun sizes alt => match alt.patterns with | .arrayLit _ ps :: _ => let sz := ps.length; if sizes.contains sz then sizes else sizes.push sz | _ => sizes private def expandVarIntoArrayLit (alt : Alt) (fvarId : FVarId) (arrayElemType : Expr) (arraySize : Nat) : MetaM Alt := withExistingLocalDecls alt.fvarDecls do let fvarDecl ← fvarId.getDecl let varNamePrefix := fvarDecl.userName let rec loop (n : Nat) (newVars : Array Expr) := do match n with | n+1 => withLocalDeclD (varNamePrefix.appendIndexAfter (n+1)) arrayElemType fun x => loop n (newVars.push x) | 0 => let arrayLit ← mkArrayLit arrayElemType newVars.toList let alt := alt.replaceFVarId fvarId arrayLit let newDecls ← newVars.toList.mapM fun newVar => newVar.fvarId!.getDecl let newPatterns := newVars.toList.map fun newVar => .var newVar.fvarId! return { alt with fvarDecls := newDecls ++ alt.fvarDecls, patterns := newPatterns ++ alt.patterns } loop arraySize #[] private def processArrayLit (p : Problem) : MetaM (Array Problem) := do trace[Meta.Match.match] "array literal step" let x :: xs := p.vars | unreachable! let sizes := collectArraySizes p let subgoals ← caseArraySizes p.mvarId x.fvarId! sizes subgoals.mapIdxM fun i subgoal => do if i.val < sizes.size then let size := sizes.get! i let subst := subgoal.subst let elems := subgoal.elems.toList let newVars := elems.map mkFVar ++ xs let newVars := newVars.map fun x => x.applyFVarSubst subst let subex := Example.arrayLit <| elems.map Example.var let examples := p.examples.map <| Example.replaceFVarId x.fvarId! subex let examples := examples.map <| Example.applyFVarSubst subst let newAlts := p.alts.filter fun alt => match alt.patterns with | .arrayLit _ ps :: _ => ps.length == size | .var _ :: _ => true | _ => false let newAlts := newAlts.map fun alt => alt.applyFVarSubst subst let newAlts ← newAlts.mapM fun alt => do match alt.patterns with | .arrayLit _ pats :: ps => return { alt with patterns := pats ++ ps } | .var fvarId :: ps => let Ξ± ← getArrayArgType <| subst.apply x expandVarIntoArrayLit { alt with patterns := ps } fvarId Ξ± size | _ => unreachable! return { mvarId := subgoal.mvarId, vars := newVars, alts := newAlts, examples := examples } else -- else branch let newAlts := p.alts.filter isFirstPatternVar return { p with mvarId := subgoal.mvarId, alts := newAlts, vars := x::xs } private def expandNatValuePattern (p : Problem) : Problem := let alts := p.alts.map fun alt => match alt.patterns with | .val (.lit (.natVal 0)) :: ps => { alt with patterns := .ctor ``Nat.zero [] [] [] :: ps } | .val (.lit (.natVal (n+1))) :: ps => { alt with patterns := .ctor ``Nat.succ [] [] [.val (mkRawNatLit n)] :: ps } | _ => alt { p with alts := alts } private def traceStep (msg : String) : StateRefT State MetaM Unit := do trace[Meta.Match.match] "{msg} step" private def traceState (p : Problem) : MetaM Unit := withGoalOf p (traceM `Meta.Match.match p.toMessageData) private def throwNonSupported (p : Problem) : MetaM Unit := withGoalOf p do let msg ← p.toMessageData throwError "failed to compile pattern matching, stuck at{indentD msg}" def isCurrVarInductive (p : Problem) : MetaM Bool := do match p.vars with | [] => return false | x::_ => withGoalOf p do let val? ← getInductiveVal? x return val?.isSome private def checkNextPatternTypes (p : Problem) : MetaM Unit := do match p.vars with | [] => return () | x::_ => withGoalOf p do for alt in p.alts do withRef alt.ref do match alt.patterns with | [] => return () | p::_ => let e ← p.toExpr let xType ← inferType x let eType ← inferType e unless (← isDefEq xType eType) do throwError "pattern{indentExpr e}\n{← mkHasTypeButIsExpectedMsg eType xType}" private partial def process (p : Problem) : StateRefT State MetaM Unit := do traceState p let isInductive ← isCurrVarInductive p if isDone p then traceStep ("leaf") processLeaf p else if hasAsPattern p then traceStep ("as-pattern") let p ← processAsPattern p process p else if isNatValueTransition p then traceStep ("nat value to constructor") process (expandNatValuePattern p) else if !isNextVar p then traceStep ("non variable") let p ← processNonVariable p process p else if isInductive && isConstructorTransition p then let ps ← processConstructor p ps.forM process else if isVariableTransition p then traceStep ("variable") let p ← processVariable p process p else if isValueTransition p then let ps ← processValue p ps.forM process else if isArrayLitTransition p then let ps ← processArrayLit p ps.forM process else if hasNatValPattern p then -- This branch is reachable when `p`, for example, is just values without an else-alternative. -- We added it just to get better error messages. traceStep ("nat value to constructor") process (expandNatValuePattern p) else checkNextPatternTypes p throwNonSupported p private def getUElimPos? (matcherLevels : List Level) (uElim : Level) : MetaM (Option Nat) := if uElim == levelZero then return none else match matcherLevels.toArray.indexOf? uElim with | none => throwError "dependent match elimination failed, universe level not found" | some pos => return some pos.val /- See comment at `mkMatcher` before `mkAuxDefinition` -/ register_builtin_option bootstrap.genMatcherCode : Bool := { defValue := true group := "bootstrap" descr := "disable code generation for auxiliary matcher function" } builtin_initialize matcherExt : EnvExtension (PHashMap (Expr Γ— Bool) Name) ← registerEnvExtension (pure {}) /-- Similar to `mkAuxDefinition`, but uses the cache `matcherExt`. It also returns an Boolean that indicates whether a new matcher function was added to the environment or not. -/ def mkMatcherAuxDefinition (name : Name) (type : Expr) (value : Expr) : MetaM (Expr Γ— Option (MatcherInfo β†’ MetaM Unit)) := do trace[Meta.Match.debug] "{name} : {type} := {value}" let compile := bootstrap.genMatcherCode.get (← getOptions) let result ← Closure.mkValueTypeClosure type value (zeta := false) let env ← getEnv let mkMatcherConst name := mkAppN (mkConst name result.levelArgs.toList) result.exprArgs match (matcherExt.getState env).find? (result.value, compile) with | some nameNew => return (mkMatcherConst nameNew, none) | none => let decl := Declaration.defnDecl { name levelParams := result.levelParams.toList type := result.type value := result.value hints := ReducibilityHints.abbrev safety := if env.hasUnsafe result.type || env.hasUnsafe result.value then DefinitionSafety.unsafe else DefinitionSafety.safe } trace[Meta.Match.debug] "{name} : {result.type} := {result.value}" let addMatcher : MatcherInfo β†’ MetaM Unit := fun mi => do addDecl decl modifyEnv fun env => matcherExt.modifyState env fun s => s.insert (result.value, compile) name addMatcherInfo name mi setInlineAttribute name if compile then compileDecl decl return (mkMatcherConst name, some addMatcher) structure MkMatcherInput where matcherName : Name matchType : Expr discrInfos : Array DiscrInfo lhss : List AltLHS def MkMatcherInput.numDiscrs (m : MkMatcherInput) := m.discrInfos.size def MkMatcherInput.collectFVars (m : MkMatcherInput) : StateRefT CollectFVars.State MetaM Unit := do m.matchType.collectFVars m.lhss.forM fun alt => alt.collectFVars def MkMatcherInput.collectDependencies (m : MkMatcherInput) : MetaM FVarIdSet := do let (_, s) ← m.collectFVars |>.run {} let s ← s.addDependencies return s.fvarSet /-- Auxiliary method used at `mkMatcher`. It executes `k` in a local context that contains only the local declarations `m` depends on. This is important because otherwise dependent elimination may "refine" the types of unnecessary declarations and accidentally introduce unnecessary dependencies in the auto-generated auxiliary declaration. Note that this is not just an optimization because the unnecessary dependencies may prevent the termination checker from succeeding. For an example, see issue #1237. -/ def withCleanLCtxFor (m : MkMatcherInput) (k : MetaM Ξ±) : MetaM Ξ± := do let s ← m.collectDependencies let lctx ← getLCtx let lctx := lctx.foldr (init := lctx) fun localDecl lctx => if s.contains localDecl.fvarId then lctx else lctx.erase localDecl.fvarId let localInstances := (← getLocalInstances).filter fun localInst => s.contains localInst.fvar.fvarId! withLCtx lctx localInstances k /-- Create a dependent matcher for `matchType` where `matchType` is of the form `(a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> B[a_1, ..., a_n]` where `n = numDiscrs`, and the `lhss` are the left-hand-sides of the `match`-expression alternatives. Each `AltLHS` has a list of local declarations and a list of patterns. The number of patterns must be the same in each `AltLHS`. The generated matcher has the structure described at `MatcherInfo`. The motive argument is of the form `(motive : (a_1 : A_1) -> (a_2 : A_2[a_1]) -> ... -> (a_n : A_n[a_1, a_2, ... a_{n-1}]) -> Sort v)` where `v` is a universe parameter or 0 if `B[a_1, ..., a_n]` is a proposition. -/ def mkMatcher (input : MkMatcherInput) : MetaM MatcherResult := withCleanLCtxFor input do let ⟨matcherName, matchType, discrInfos, lhss⟩ := input let numDiscrs := discrInfos.size let numEqs := getNumEqsFromDiscrInfos discrInfos checkNumPatterns numDiscrs lhss forallBoundedTelescope matchType numDiscrs fun discrs matchTypeBody => do /- We generate an matcher that can eliminate using different motives with different universe levels. `uElim` is the universe level the caller wants to eliminate to. If it is not levelZero, we create a matcher that can eliminate in any universe level. This is useful for implementing `MatcherApp.addArg` because it may have to change the universe level. -/ let uElim ← getLevel matchTypeBody let uElimGen ← if uElim == levelZero then pure levelZero else mkFreshLevelMVar let mkMatcher (type val : Expr) (minors : Array (Expr Γ— Nat)) (s : State) : MetaM MatcherResult := do trace[Meta.Match.debug] "matcher value: {val}\ntype: {type}" trace[Meta.Match.debug] "minors num params: {minors.map (Β·.2)}" /- The option `bootstrap.gen_matcher_code` is a helper hack. It is useful, for example, for compiling `src/Init/Data/Int`. It is needed because the compiler uses `Int.decLt` for generating code for `Int.casesOn` applications, but `Int.casesOn` is used to give the reference implementation for ``` @[extern "lean_int_neg"] def neg (n : @& Int) : Int := match n with | ofNat n => negOfNat n | negSucc n => succ n ``` which is defined **before** `Int.decLt` -/ let (matcher, addMatcher) ← mkMatcherAuxDefinition matcherName type val trace[Meta.Match.debug] "matcher levels: {matcher.getAppFn.constLevels!}, uElim: {uElimGen}" let uElimPos? ← getUElimPos? matcher.getAppFn.constLevels! uElimGen discard <| isLevelDefEq uElimGen uElim let addMatcher := match addMatcher with | some addMatcher => addMatcher <| { numParams := matcher.getAppNumArgs altNumParams := minors.map fun minor => minor.2 + numEqs discrInfos numDiscrs uElimPos? } | none => pure () trace[Meta.Match.debug] "matcher: {matcher}" let unusedAltIdxs := lhss.length.fold (init := []) fun i r => if s.used.contains i then r else i::r return { matcher, counterExamples := s.counterExamples, unusedAltIdxs := unusedAltIdxs.reverse, addMatcher } let motiveType ← mkForallFVars discrs (mkSort uElimGen) trace[Meta.Match.debug] "motiveType: {motiveType}" withLocalDeclD `motive motiveType fun motive => do if discrInfos.any fun info => info.hName?.isSome then forallBoundedTelescope matchType numDiscrs fun discrs' _ => do let (mvarType, isEqMask) ← withEqs discrs discrs' discrInfos fun eqs => do let mvarType ← mkForallFVars eqs (mkAppN motive discrs') let isEqMask ← eqs.mapM fun eq => return (← inferType eq).isEq return (mvarType, isEqMask) trace[Meta.Match.debug] "target: {mvarType}" withAlts motive discrs discrInfos lhss fun alts minors => do let mvar ← mkFreshExprMVar mvarType trace[Meta.Match.debug] "goal\n{mvar.mvarId!}" let examples := discrs'.toList.map fun discr => Example.var discr.fvarId! let (_, s) ← (process { mvarId := mvar.mvarId!, vars := discrs'.toList, alts := alts, examples := examples }).run {} let val ← mkLambdaFVars discrs' mvar trace[Meta.Match.debug] "matcher\nvalue: {val}\ntype: {← inferType val}" let mut rfls := #[] let mut isEqMaskIdx := 0 for discr in discrs, info in discrInfos do if info.hName?.isSome then if isEqMask[isEqMaskIdx]! then rfls := rfls.push (← mkEqRefl discr) else rfls := rfls.push (← mkHEqRefl discr) isEqMaskIdx := isEqMaskIdx + 1 let val := mkAppN (mkAppN val discrs) rfls let args := #[motive] ++ discrs ++ minors.map Prod.fst let val ← mkLambdaFVars args val let type ← mkForallFVars args (mkAppN motive discrs) mkMatcher type val minors s else let mvarType := mkAppN motive discrs trace[Meta.Match.debug] "target: {mvarType}" withAlts motive discrs discrInfos lhss fun alts minors => do let mvar ← mkFreshExprMVar mvarType let examples := discrs.toList.map fun discr => Example.var discr.fvarId! let (_, s) ← (process { mvarId := mvar.mvarId!, vars := discrs.toList, alts := alts, examples := examples }).run {} let args := #[motive] ++ discrs ++ minors.map Prod.fst let type ← mkForallFVars args mvarType let val ← mkLambdaFVars args mvar mkMatcher type val minors s def getMkMatcherInputInContext (matcherApp : MatcherApp) : MetaM MkMatcherInput := do let matcherName := matcherApp.matcherName let some matcherInfo ← getMatcherInfo? matcherName | throwError "not a matcher: {matcherName}" let matcherConst ← getConstInfo matcherName let matcherType ← instantiateForall matcherConst.type <| matcherApp.params ++ #[matcherApp.motive] let matchType ← do let u := if let some idx := matcherInfo.uElimPos? then mkLevelParam matcherConst.levelParams.toArray[idx]! else levelZero forallBoundedTelescope matcherType (some matcherInfo.numDiscrs) fun discrs _ => do mkForallFVars discrs (mkConst ``PUnit [u]) let matcherType ← instantiateForall matcherType matcherApp.discrs let lhss ← forallBoundedTelescope matcherType (some matcherApp.alts.size) fun alts _ => alts.mapM fun alt => do let ty ← inferType alt forallTelescope ty fun xs body => do let xs ← xs.filterM fun x => dependsOn body x.fvarId! body.withApp fun _ args => do let ctx ← getLCtx let localDecls := xs.map ctx.getFVar! let patterns ← args.mapM Match.toPattern return { ref := Syntax.missing fvarDecls := localDecls.toList patterns := patterns.toList : Match.AltLHS } return { matcherName, matchType, discrInfos := matcherInfo.discrInfos, lhss := lhss.toList } /-- This function is only used for testing purposes -/ def withMkMatcherInput (matcherName : Name) (k : MkMatcherInput β†’ MetaM Ξ±) : MetaM Ξ± := do let some matcherInfo ← getMatcherInfo? matcherName | throwError "not a matcher: {matcherName}" let matcherConst ← getConstInfo matcherName forallBoundedTelescope matcherConst.type (some matcherInfo.arity) fun xs _ => do let matcherApp ← mkConstWithLevelParams matcherConst.name let matcherApp := mkAppN matcherApp xs let some matcherApp ← matchMatcherApp? matcherApp | throwError "not a matcher app: {matcherApp}" let mkMatcherInput ← getMkMatcherInputInContext matcherApp k mkMatcherInput end Match /-- Auxiliary function for MatcherApp.addArg -/ private partial def updateAlts (typeNew : Expr) (altNumParams : Array Nat) (alts : Array Expr) (i : Nat) : MetaM (Array Nat Γ— Array Expr) := do if h : i < alts.size then let alt := alts.get ⟨i, h⟩ let numParams := altNumParams[i]! let typeNew ← whnfD typeNew match typeNew with | Expr.forallE _ d b _ => let alt ← forallBoundedTelescope d (some numParams) fun xs d => do let alt ← try instantiateLambda alt xs catch _ => throwError "unexpected matcher application, insufficient number of parameters in alternative" forallBoundedTelescope d (some 1) fun x _ => do let alt ← mkLambdaFVars x alt -- x is the new argument we are adding to the alternative mkLambdaFVars xs alt updateAlts (b.instantiate1 alt) (altNumParams.set! i (numParams+1)) (alts.set ⟨i, h⟩ alt) (i+1) | _ => throwError "unexpected type at MatcherApp.addArg" else return (altNumParams, alts) /-- Given - matcherApp `match_i As (fun xs => motive[xs]) discrs (fun ys_1 => (alt_1 : motive (C_1[ys_1])) ... (fun ys_n => (alt_n : motive (C_n[ys_n]) remaining`, and - expression `e : B[discrs]`, Construct the term `match_i As (fun xs => B[xs] -> motive[xs]) discrs (fun ys_1 (y : B[C_1[ys_1]]) => alt_1) ... (fun ys_n (y : B[C_n[ys_n]]) => alt_n) e remaining`, and We use `kabstract` to abstract the discriminants from `B[discrs]`. This method assumes - the `matcherApp.motive` is a lambda abstraction where `xs.size == discrs.size` - each alternative is a lambda abstraction where `ys_i.size == matcherApp.altNumParams[i]` -/ def MatcherApp.addArg (matcherApp : MatcherApp) (e : Expr) : MetaM MatcherApp := lambdaTelescope matcherApp.motive fun motiveArgs motiveBody => do unless motiveArgs.size == matcherApp.discrs.size do -- This error can only happen if someone implemented a transformation that rewrites the motive created by `mkMatcher`. throwError "unexpected matcher application, motive must be lambda expression with #{matcherApp.discrs.size} arguments" let eType ← inferType e let eTypeAbst ← matcherApp.discrs.size.foldRevM (init := eType) fun i eTypeAbst => do let motiveArg := motiveArgs[i]! let discr := matcherApp.discrs[i]! let eTypeAbst ← kabstract eTypeAbst discr return eTypeAbst.instantiate1 motiveArg let motiveBody ← mkArrow eTypeAbst motiveBody let matcherLevels ← match matcherApp.uElimPos? with | none => pure matcherApp.matcherLevels | some pos => let uElim ← getLevel motiveBody pure <| matcherApp.matcherLevels.set! pos uElim let motive ← mkLambdaFVars motiveArgs motiveBody -- Construct `aux` `match_i As (fun xs => B[xs] β†’ motive[xs]) discrs`, and infer its type `auxType`. -- We use `auxType` to infer the type `B[C_i[ys_i]]` of the new argument in each alternative. let aux := mkAppN (mkConst matcherApp.matcherName matcherLevels.toList) matcherApp.params let aux := mkApp aux motive let aux := mkAppN aux matcherApp.discrs unless (← isTypeCorrect aux) do throwError "failed to add argument to matcher application, type error when constructing the new motive" let auxType ← inferType aux let (altNumParams, alts) ← updateAlts auxType matcherApp.altNumParams matcherApp.alts 0 return { matcherApp with matcherLevels := matcherLevels, motive := motive, alts := alts, altNumParams := altNumParams, remaining := #[e] ++ matcherApp.remaining } /-- Similar `MatcherApp.addArg?`, but returns `none` on failure. -/ def MatcherApp.addArg? (matcherApp : MatcherApp) (e : Expr) : MetaM (Option MatcherApp) := try return some (← matcherApp.addArg e) catch _ => return none builtin_initialize registerTraceClass `Meta.Match.match registerTraceClass `Meta.Match.debug registerTraceClass `Meta.Match.unify end Lean.Meta
5af891bc8eab8daee0cf56fca331a5618430f302
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Parser/Tactic.lean
339eb4d78a66f7a96a1315312491d2e6adb2fc71
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
1,235
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, Sebastian Ullrich -/ import Lean.Parser.Term namespace Lean namespace Parser namespace Tactic builtin_initialize register_parser_alias tacticSeq @[builtinTacticParser] def Β«unknownΒ» := leading_parser withPosition (ident >> errorAtSavedPos "unknown tactic" true) @[builtinTacticParser] def nestedTactic := tacticSeqBracketed /- Auxiliary parser for expanding `match` tactic -/ @[builtinTacticParser] def eraseAuxDiscrs := leading_parser:maxPrec "eraseAuxDiscrs!" def matchRhs := Term.hole <|> Term.syntheticHole <|> tacticSeq def matchAlts := Term.matchAlts (rhsParser := matchRhs) @[builtinTacticParser] def Β«matchΒ» := leading_parser:leadPrec "match " >> optional Term.generalizingParam >> sepBy1 Term.matchDiscr ", " >> Term.optType >> " with " >> matchAlts @[builtinTacticParser] def introMatch := leading_parser nonReservedSymbol "intro " >> matchAlts @[builtinTacticParser] def decide := leading_parser nonReservedSymbol "decide" @[builtinTacticParser] def nativeDecide := leading_parser nonReservedSymbol "nativeDecide" end Tactic end Parser end Lean
7b21266b4a69f88c647787495d7113f16c04ef4d
66a6486e19b71391cc438afee5f081a4257564ec
/algebra/quotient_group.hlean
575b4797693ef7371aab5057ed6cf26f816fe713
[ "Apache-2.0" ]
permissive
spiceghello/Spectral
c8ccd1e32d4b6a9132ccee20fcba44b477cd0331
20023aa3de27c22ab9f9b4a177f5a1efdec2b19f
refs/heads/master
1,611,263,374,078
1,523,349,717,000
1,523,349,717,000
92,312,239
0
0
null
1,495,642,470,000
1,495,642,470,000
null
UTF-8
Lean
false
false
28,857
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke, Jeremy Avigad Constructions with groups -/ import hit.set_quotient .subgroup ..move_to_lib types.equiv open eq algebra is_trunc set_quotient relation sigma sigma.ops prod trunc function equiv is_equiv open property namespace group variables {G G' : Group} (H : property G) [is_subgroup G H] (N : property G) [is_normal_subgroup G N] {g g' h h' k : G} (N' : property G') [is_normal_subgroup G' N'] variables {A B : AbGroup} /- Quotient Group -/ definition homotopy_of_homomorphism_eq {f g : G β†’g G'}(p : f = g) : f ~ g := Ξ»x : G , ap010 group_fun p x definition quotient_rel [constructor] (g h : G) : Prop := g * h⁻¹ ∈ N variable {N} -- We prove that quotient_rel is an equivalence relation theorem quotient_rel_refl (g : G) : quotient_rel N g g := transport (Ξ»x, N x) !mul.right_inv⁻¹ (subgroup_one_mem N) theorem quotient_rel_symm (r : quotient_rel N g h) : quotient_rel N h g := transport (Ξ»x, N x) (!mul_inv ⬝ ap (Ξ»x, x * _) !inv_inv) begin apply subgroup_inv_mem r end theorem quotient_rel_trans (r : quotient_rel N g h) (s : quotient_rel N h k) : quotient_rel N g k := have H1 : N ((g * h⁻¹) * (h * k⁻¹)), from subgroup_mul_mem r s, have H2 : (g * h⁻¹) * (h * k⁻¹) = g * k⁻¹, from calc (g * h⁻¹) * (h * k⁻¹) = ((g * h⁻¹) * h) * k⁻¹ : by rewrite [mul.assoc (g * h⁻¹)] ... = g * k⁻¹ : by rewrite inv_mul_cancel_right, show N (g * k⁻¹), by rewrite [-H2]; exact H1 theorem is_equivalence_quotient_rel : is_equivalence (quotient_rel N) := is_equivalence.mk quotient_rel_refl (Ξ»g h, quotient_rel_symm) (Ξ»g h k, quotient_rel_trans) -- We prove that quotient_rel respects inverses and multiplication, so -- it is a congruence relation theorem quotient_rel_resp_inv (r : quotient_rel N g h) : quotient_rel N g⁻¹ h⁻¹ := have H1 : g⁻¹ * (h * g⁻¹) * g ∈ N, from is_normal_subgroup' g (quotient_rel_symm r), have H2 : g⁻¹ * (h * g⁻¹) * g = g⁻¹ * h⁻¹⁻¹, from calc g⁻¹ * (h * g⁻¹) * g = g⁻¹ * h * g⁻¹ * g : by rewrite -mul.assoc ... = g⁻¹ * h : inv_mul_cancel_right ... = g⁻¹ * h⁻¹⁻¹ : by rewrite algebra.inv_inv, show g⁻¹ * h⁻¹⁻¹ ∈ N, by rewrite [-H2]; exact H1 theorem quotient_rel_resp_mul (r : quotient_rel N g h) (r' : quotient_rel N g' h') : quotient_rel N (g * g') (h * h') := have H1 : g * ((g' * h'⁻¹) * h⁻¹) ∈ N, from normal_subgroup_insert r' r, have H2 : g * ((g' * h'⁻¹) * h⁻¹) = (g * g') * (h * h')⁻¹, from calc g * ((g' * h'⁻¹) * h⁻¹) = g * (g' * (h'⁻¹ * h⁻¹)) : by rewrite [mul.assoc] ... = (g * g') * (h'⁻¹ * h⁻¹) : mul.assoc ... = (g * g') * (h * h')⁻¹ : by rewrite [mul_inv], show N ((g * g') * (h * h')⁻¹), from transport (Ξ»x, N x) H2 H1 local attribute is_equivalence_quotient_rel [instance] variable (N) definition qg : Type := set_quotient (quotient_rel N) variable {N} local attribute qg [reducible] definition quotient_one [constructor] : qg N := class_of one definition quotient_inv [unfold 3] : qg N β†’ qg N := quotient_unary_map has_inv.inv (Ξ»g g' r, quotient_rel_resp_inv r) definition quotient_mul [unfold 3 4] : qg N β†’ qg N β†’ qg N := quotient_binary_map has_mul.mul (Ξ»g g' r h h' r', quotient_rel_resp_mul r r') section local notation 1 := quotient_one local postfix ⁻¹ := quotient_inv local infix * := quotient_mul theorem quotient_mul_assoc (g₁ gβ‚‚ g₃ : qg N) : g₁ * gβ‚‚ * g₃ = g₁ * (gβ‚‚ * g₃) := begin refine set_quotient.rec_prop _ g₁, refine set_quotient.rec_prop _ gβ‚‚, refine set_quotient.rec_prop _ g₃, clear g₁ gβ‚‚ g₃, intro g₁ gβ‚‚ g₃, exact ap class_of !mul.assoc end theorem quotient_one_mul (g : qg N) : 1 * g = g := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !one_mul end theorem quotient_mul_one (g : qg N) : g * 1 = g := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !mul_one end theorem quotient_mul_left_inv (g : qg N) : g⁻¹ * g = 1 := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !mul.left_inv end theorem quotient_mul_comm {G : AbGroup} {N : property G} [is_normal_subgroup G N] (g h : qg N) : g * h = h * g := begin refine set_quotient.rec_prop _ g, clear g, intro g, refine set_quotient.rec_prop _ h, clear h, intro h, apply ap class_of, esimp, apply mul.comm end end variable (N) definition group_qg [constructor] : group (qg N) := group.mk _ quotient_mul quotient_mul_assoc quotient_one quotient_one_mul quotient_mul_one quotient_inv quotient_mul_left_inv definition quotient_group [constructor] : Group := Group.mk _ (group_qg N) definition ab_group_qg [constructor] {G : AbGroup} (N : property G) [is_normal_subgroup G N] : ab_group (qg N) := ⦃ab_group, group_qg N, mul_comm := quotient_mul_comm⦄ definition quotient_ab_group [constructor] {G : AbGroup} (N : property G) [is_subgroup G N] : AbGroup := AbGroup.mk _ (@ab_group_qg G N (is_normal_subgroup_ab _)) definition qg_map [constructor] : G β†’g quotient_group N := homomorphism.mk class_of (Ξ» g h, idp) definition ab_qg_map {G : AbGroup} (N : property G) [is_subgroup G N] : G β†’g quotient_ab_group N := @qg_map _ N (is_normal_subgroup_ab _) definition is_surjective_ab_qg_map {A : AbGroup} (N : property A) [is_subgroup A N] : is_surjective (ab_qg_map N) := begin intro x, induction x, fapply image.mk, exact a, reflexivity, apply is_prop.elimo end namespace quotient notation `⟦`:max a `⟧`:0 := qg_map _ a end quotient open quotient variables {N N'} definition qg_map_eq_one (g : G) (H : N g) : qg_map N g = 1 := begin apply eq_of_rel, have e : (g * 1⁻¹ = g), from calc g * 1⁻¹ = g * 1 : one_inv ... = g : mul_one, unfold quotient_rel, rewrite e, exact H end definition ab_qg_map_eq_one {K : property A} [is_subgroup A K] (g :A) (H : K g) : ab_qg_map K g = 1 := begin apply eq_of_rel, have e : (g * 1⁻¹ = g), from calc g * 1⁻¹ = g * 1 : one_inv ... = g : mul_one, unfold quotient_rel, xrewrite e, exact H end --- there should be a smarter way to do this!! Please have a look, Floris. definition rel_of_qg_map_eq_one (g : G) (H : qg_map N g = 1) : g ∈ N := begin have e : (g * 1⁻¹ = g), from calc g * 1⁻¹ = g * 1 : one_inv ... = g : mul_one, rewrite (inverse e), apply rel_of_eq _ H end definition rel_of_ab_qg_map_eq_one {K : property A} [is_subgroup A K] (a :A) (H : ab_qg_map K a = 1) : a ∈ K := begin have e : (a * 1⁻¹ = a), from calc a * 1⁻¹ = a * 1 : one_inv ... = a : mul_one, rewrite (inverse e), have is_normal_subgroup A K, from is_normal_subgroup_ab _, apply rel_of_eq (quotient_rel K) H end definition quotient_group_elim_fun [unfold 6] (f : G β†’g G') (H : Π⦃g⦄, N g β†’ f g = 1) (g : quotient_group N) : G' := begin refine set_quotient.elim f _ g, intro g h K, apply eq_of_mul_inv_eq_one, have e : f (g * h⁻¹) = f g * (f h)⁻¹, from calc f (g * h⁻¹) = f g * (f h⁻¹) : to_respect_mul ... = f g * (f h)⁻¹ : to_respect_inv, rewrite (inverse e), apply H, exact K end definition quotient_group_elim [constructor] (f : G β†’g G') (H : Π⦃g⦄, g ∈ N β†’ f g = 1) : quotient_group N β†’g G' := begin fapply homomorphism.mk, -- define function { exact quotient_group_elim_fun f H }, { intro g h, induction g using set_quotient.rec_prop with g, induction h using set_quotient.rec_prop with h, krewrite (inverse (to_respect_mul (qg_map N) g h)), unfold qg_map, esimp, exact to_respect_mul f g h } end example {K : property A} [is_subgroup A K] : quotient_ab_group K = @quotient_group A K (is_normal_subgroup_ab _) := rfl definition quotient_ab_group_elim [constructor] {K : property A} [is_subgroup A K] (f : A β†’g B) (H : Π⦃g⦄, g ∈ K β†’ f g = 1) : quotient_ab_group K β†’g B := @quotient_group_elim A B K (is_normal_subgroup_ab _) f H definition quotient_group_compute (f : G β†’g G') (H : Π⦃g⦄, N g β†’ f g = 1) (g : G) : quotient_group_elim f H (qg_map N g) = f g := begin reflexivity end definition gelim_unique (f : G β†’g G') (H : Π⦃g⦄, g ∈ N β†’ f g = 1) (k : quotient_group N β†’g G') : ( k ∘g qg_map N ~ f ) β†’ k ~ quotient_group_elim f H := begin intro K cg, induction cg using set_quotient.rec_prop with g, exact K g end definition ab_gelim_unique {K : property A} [is_subgroup A K] (f : A β†’g B) (H : Ξ  (a :A), a ∈ K β†’ f a = 1) (k : quotient_ab_group K β†’g B) : ( k ∘g ab_qg_map K ~ f) β†’ k ~ quotient_ab_group_elim f H := --@quotient_group_elim A B K (is_normal_subgroup_ab _) f H := @gelim_unique _ _ K (is_normal_subgroup_ab _) f H _ definition qg_universal_property (f : G β†’g G') (H : Π⦃g⦄, N g β†’ f g = 1) : is_contr (Ξ£(g : quotient_group N β†’g G'), g ∘ qg_map N ~ f) := begin fapply is_contr.mk, -- give center of contraction { fapply sigma.mk, exact quotient_group_elim f H, exact quotient_group_compute f H }, -- give contraction { intro pair, induction pair with g p, fapply sigma_eq, {esimp, apply homomorphism_eq, symmetry, exact gelim_unique f H g p}, {fapply is_prop.elimo} } end definition ab_qg_universal_property {K : property A} [is_subgroup A K] (f : A β†’g B) (H : Ξ  (a :A), K a β†’ f a = 1) : is_contr ((Ξ£(g : quotient_ab_group K β†’g B), g ∘g ab_qg_map K ~ f) ) := begin fapply @qg_universal_property _ _ K (is_normal_subgroup_ab _), exact H end definition quotient_group_functor_contr {K L : property A} [is_subgroup A K] [is_subgroup A L] (H : Ξ  (a : A), K a β†’ L a) : is_contr ((Ξ£(g : quotient_ab_group K β†’g quotient_ab_group L), g ∘g ab_qg_map K ~ ab_qg_map L) ) := begin fapply ab_qg_universal_property, intro a p, fapply ab_qg_map_eq_one, exact H a p end definition quotient_group_functor_id {K : property A} [is_subgroup A K] (H : Ξ  (a : A), K a β†’ K a) : center' (@quotient_group_functor_contr _ K K _ _ H) = ⟨gid (quotient_ab_group K), Ξ» x, rfl⟩ := begin note p := @quotient_group_functor_contr _ K K _ _ H, fapply eq_of_is_contr, end section quotient_group_iso_ua set_option pp.universes true definition subgroup_rel_eq' {K L : property A} [HK : is_subgroup A K] [HL : is_subgroup A L] (htpy : Ξ  (a : A), K a ≃ L a) : K = L := begin induction HK with Rone Rmul Rinv, induction HL with Rone' Rmul' Rinv', esimp at *, assert q : K = L, begin fapply eq_of_homotopy, intro a, fapply tua, exact htpy a, end, induction q, assert q : Rone = Rone', begin fapply is_prop.elim, end, induction q, assert q2 : @Rmul = @Rmul', begin fapply is_prop.elim, end, induction q2, assert q : @Rinv = @Rinv', begin fapply is_prop.elim, end, induction q, reflexivity end definition subgroup_rel_eq {K L : property A} [is_subgroup A K] [is_subgroup A L] (K_in_L : Ξ  (a : A), a ∈ K β†’ a ∈ L) (L_in_K : Ξ  (a : A), a ∈ L β†’ a ∈ K) : K = L := begin have htpy : Ξ  (a : A), K a ≃ L a, begin intro a, apply @equiv_of_is_prop (a ∈ K) (a ∈ L) _ _ (K_in_L a) (L_in_K a), end, exact subgroup_rel_eq' htpy, end definition eq_of_ab_qg_group' {K L : property A} [HK : is_subgroup A K] [HL : is_subgroup A L] (p : K = L) : quotient_ab_group K = quotient_ab_group L := begin revert HK, revert HL, induction p, intros, have HK = HL, begin apply @is_prop.elim _ _ HK HL end, rewrite this end definition iso_of_eq {B : AbGroup} (p : A = B) : A ≃g B := begin induction p, fapply isomorphism.mk, exact gid A, fapply adjointify, exact id, intro a, reflexivity, intro a, reflexivity end definition iso_of_ab_qg_group' {K L : property A} [is_subgroup A K] [is_subgroup A L] (p : K = L) : quotient_ab_group K ≃g quotient_ab_group L := iso_of_eq (eq_of_ab_qg_group' p) /- definition htpy_of_ab_qg_group' {K L : property A} [HK : is_subgroup A K] [HL : is_subgroup A L] (p : K = L) : (iso_of_ab_qg_group' p) ∘g ab_qg_map K ~ ab_qg_map L := begin revert HK, revert HL, induction p, intros HK HL, unfold iso_of_ab_qg_group', unfold ab_qg_map -- have HK = HL, begin apply @is_prop.elim _ _ HK HL end, -- rewrite this -- induction p, reflexivity end -/ definition eq_of_ab_qg_group {K L : property A} [is_subgroup A K] [is_subgroup A L] (K_in_L : Ξ  (a : A), K a β†’ L a) (L_in_K : Ξ  (a : A), L a β†’ K a) : quotient_ab_group K = quotient_ab_group L := eq_of_ab_qg_group' (subgroup_rel_eq K_in_L L_in_K) definition iso_of_ab_qg_group {K L : property A} [is_subgroup A K] [is_subgroup A L] (K_in_L : Ξ  (a : A), K a β†’ L a) (L_in_K : Ξ  (a : A), L a β†’ K a) : quotient_ab_group K ≃g quotient_ab_group L := iso_of_eq (eq_of_ab_qg_group K_in_L L_in_K) /- definition htpy_of_ab_qg_group {K L : property A} [is_subgroup A K] [is_subgroup A L] (K_in_L : Ξ  (a : A), K a β†’ L a) (L_in_K : Ξ  (a : A), L a β†’ K a) : iso_of_ab_qg_group K_in_L L_in_K ∘g ab_qg_map K ~ ab_qg_map L := begin fapply htpy_of_ab_qg_group' end -/ end quotient_group_iso_ua section quotient_group_iso variables {K L : property A} [is_subgroup A K] [is_subgroup A L] (H1 : Ξ  (a : A), K a β†’ L a) (H2 : Ξ  (a : A), L a β†’ K a) include H1 include H2 definition quotient_group_iso_contr_KL_map : quotient_ab_group K β†’g quotient_ab_group L := pr1 (center' (quotient_group_functor_contr H1)) definition quotient_group_iso_contr_KL_triangle : quotient_group_iso_contr_KL_map H1 H2 ∘g ab_qg_map K ~ ab_qg_map L := pr2 (center' (quotient_group_functor_contr H1)) definition quotient_group_iso_contr_KK : is_contr (Ξ£ (g : quotient_ab_group K β†’g quotient_ab_group K), g ∘g ab_qg_map K ~ ab_qg_map K) := @quotient_group_functor_contr A K K _ _ (Ξ» a, H2 a ∘ H1 a) definition quotient_group_iso_contr_LK : quotient_ab_group L β†’g quotient_ab_group K := pr1 (center' (@quotient_group_functor_contr A L K _ _ H2)) definition quotient_group_iso_contr_LL : quotient_ab_group L β†’g quotient_ab_group L := pr1 (center' (@quotient_group_functor_contr A L L _ _ (Ξ» a, H1 a ∘ H2 a))) /- definition quotient_group_iso : quotient_ab_group K ≃g quotient_ab_group L := begin fapply isomorphism.mk, exact pr1 (center' (quotient_group_iso_contr_KL H1 H2)), fapply adjointify, exact quotient_group_iso_contr_LK H1 H2, intro x, induction x, reflexivity, end -/ definition quotient_group_iso_contr_aux : is_contr (Ξ£(gh : Ξ£ (g : quotient_ab_group K β†’g quotient_ab_group L), g ∘g ab_qg_map K ~ ab_qg_map L), is_equiv (group_fun (pr1 gh))) := begin fapply is_trunc_sigma, exact quotient_group_functor_contr H1, intro a, induction a with g h, fapply is_contr_of_inhabited_prop, fapply adjointify, rexact group_fun (pr1 (center' (@quotient_group_functor_contr A L K _ _ H2))), note htpy := homotopy_of_eq (ap group_fun (ap sigma.pr1 (@quotient_group_functor_id _ L _ (Ξ» a, (H1 a) ∘ (H2 a))))), have KK : is_contr ((Ξ£(g' : quotient_ab_group K β†’g quotient_ab_group K), g' ∘g ab_qg_map K ~ ab_qg_map K) ), from quotient_group_functor_contr (Ξ» a, (H2 a) ∘ (H1 a)), -- have KK_path : ⟨g, h⟩ = ⟨id, Ξ» a, refl (ab_qg_map K a)⟩, from eq_of_is_contr ⟨g, h⟩ ⟨id, Ξ» a, refl (ab_qg_map K a)⟩, repeat exact sorry end /- definition quotient_group_iso_contr {K L : property A} [is_subgroup A K] [is_subgroup A L] (H1 : Ξ  (a : A), K a β†’ L a) (H2 : Ξ  (a : A), L a β†’ K a) : is_contr (Ξ£ (g : quotient_ab_group K ≃g quotient_ab_group L), g ∘g ab_qg_map K ~ ab_qg_map L) := begin refine @is_trunc_equiv_closed (Ξ£(gh : Ξ£ (g : quotient_ab_group K β†’g quotient_ab_group L), g ∘g ab_qg_map K ~ ab_qg_map L), is_equiv (group_fun (pr1 gh))) (Ξ£ (g : quotient_ab_group K ≃g quotient_ab_group L), g ∘g ab_qg_map K ~ ab_qg_map L) -2 _ (quotient_group_iso_contr_aux H1 H2), exact calc (Ξ£ gh, is_equiv (group_fun gh.1)) ≃ Ξ£ (g : quotient_ab_group K β†’g quotient_ab_group L) (h : g ∘g ab_qg_map K ~ ab_qg_map L), is_equiv (group_fun g) : by exact (sigma_assoc_equiv (Ξ» gh, is_equiv (group_fun gh.1)))⁻¹ ... ≃ (Ξ£ (g : quotient_ab_group K ≃g quotient_ab_group L), g ∘g ab_qg_map K ~ ab_qg_map L) : _ end -/ end quotient_group_iso definition quotient_group_functor [constructor] (Ο† : G β†’g G') (h : Ξ g, g ∈ N β†’ Ο† g ∈ N') : quotient_group N β†’g quotient_group N' := begin apply quotient_group_elim (qg_map N' ∘g Ο†), intro g Ng, esimp, refine qg_map_eq_one (Ο† g) (h g Ng) end ------------------------------------------------ -- FIRST ISOMORPHISM THEOREM ------------------------------------------------ definition kernel_quotient_extension {A B : AbGroup} (f : A β†’g B) : quotient_ab_group (kernel f) β†’g B := begin unfold quotient_ab_group, fapply @quotient_group_elim A B _ (@is_normal_subgroup_ab _ (kernel f) _) f, intro a, intro p, exact p end definition kernel_quotient_extension_triangle {A B : AbGroup} (f : A β†’g B) : kernel_quotient_extension f ∘ ab_qg_map (kernel f) ~ f := begin intro a, apply @quotient_group_compute _ _ _ (@is_normal_subgroup_ab _ (kernel f) _) end definition is_embedding_kernel_quotient_extension {A B : AbGroup} (f : A β†’g B) : is_embedding (kernel_quotient_extension f) := begin fapply is_embedding_of_is_mul_hom, intro x, note H := is_surjective_ab_qg_map (kernel f) x, induction H, induction p, intro q, apply @qg_map_eq_one _ _ (@is_normal_subgroup_ab _ (kernel f) _), refine _ ⬝ q, symmetry, rexact kernel_quotient_extension_triangle f a end definition ab_group_quotient_homomorphism (A B : AbGroup)(K : property A)(L : property B) [is_subgroup A K] [is_subgroup B L] (f : A β†’g B) (p : Ξ (a:A), a ∈ K β†’ f a ∈ L) : quotient_ab_group K β†’g quotient_ab_group L := begin fapply @quotient_group_elim, exact (ab_qg_map L) ∘g f, intro a, intro k, exact @ab_qg_map_eq_one B L _ (f a) (p a k), end definition ab_group_kernel_factor {A B C: AbGroup} (f : A β†’g B)(g : A β†’g C){i : C β†’g B}(H : f = i ∘g g ) : kernel g βŠ† kernel f := begin intro a, intro p, exact calc f a = i (g a) : homotopy_of_eq (ap group_fun H) a ... = i 1 : ap i p ... = 1 : respect_one i end definition ab_group_triv_kernel_factor {A B C: AbGroup} (f : A β†’g B)(g : A β†’g C){i : C β†’g B}(H : f = i ∘g g ) : kernel f βŠ† '{1} β†’ kernel g βŠ† '{1} := Ξ» p, subproperty.trans (ab_group_kernel_factor f g H) p definition is_embedding_of_kernel_subproperty_one {A B : AbGroup} (f : A β†’g B) : kernel f βŠ† '{1} β†’ is_embedding f := Ξ» p, is_embedding_of_is_mul_hom _ (take x, assume h : f x = 1, show x = 1, from eq_of_mem_singleton (p _ h)) definition kernel_subproperty_one {A B : AbGroup} (f : A β†’g B) : is_embedding f β†’ kernel f βŠ† '{1} := Ξ» h x hx, have x = 1, from eq_one_of_is_mul_hom hx, show x ∈ '{1}, from mem_singleton_of_eq this definition ab_group_kernel_equivalent {A B : AbGroup} (C : AbGroup) (f : A β†’g B)(g : A β†’g C)(i : C β†’g B)(H : f = i ∘g g )(K : is_embedding i) : Ξ  a:A, a ∈ kernel g ↔ a ∈ kernel f := exteq_of_subproperty_of_subproperty (show kernel g βŠ† kernel f, from ab_group_kernel_factor f g H) (show kernel f βŠ† kernel g, from take a, suppose f a = 1, have i (g a) = i 1, from calc i (g a) = f a : (homotopy_of_eq (ap group_fun H) a)⁻¹ ... = 1 : this ... = i 1 : (respect_one i)⁻¹, is_injective_of_is_embedding this) definition ab_group_kernel_image_lift (A B : AbGroup) (f : A β†’g B) : Ξ  a : A, a ∈ kernel (image_lift f) ↔ a ∈ kernel f := begin fapply ab_group_kernel_equivalent (ab_Image f) (f) (image_lift(f)) (image_incl(f)), exact image_factor f, exact is_embedding_of_is_injective (image_incl_injective(f)), end definition ab_group_kernel_quotient_to_image {A B : AbGroup} (f : A β†’g B) : quotient_ab_group (kernel f) β†’g ab_Image (f) := begin fapply quotient_ab_group_elim (image_lift f), intro a, intro p, apply iff.mpr (ab_group_kernel_image_lift _ _ f a) p end definition ab_group_kernel_quotient_to_image_domain_triangle {A B : AbGroup} (f : A β†’g B) : ab_group_kernel_quotient_to_image (f) ∘g ab_qg_map (kernel f) ~ image_lift(f) := begin intros a, esimp, end definition ab_group_kernel_quotient_to_image_codomain_triangle {A B : AbGroup} (f : A β†’g B) : image_incl f ∘g ab_group_kernel_quotient_to_image f ~ kernel_quotient_extension f := begin intro x, induction x, reflexivity, fapply is_prop.elimo end definition is_surjective_kernel_quotient_to_image {A B : AbGroup} (f : A β†’g B) : is_surjective (ab_group_kernel_quotient_to_image f) := begin fapply is_surjective_factor (group_fun (ab_qg_map (kernel f))), exact image_lift f, apply @quotient_group_compute _ _ _ (@is_normal_subgroup_ab _ (kernel f) _), exact is_surjective_image_lift f end definition is_embedding_kernel_quotient_to_image {A B : AbGroup} (f : A β†’g B) : is_embedding (ab_group_kernel_quotient_to_image f) := begin fapply is_embedding_factor (ab_group_kernel_quotient_to_image f) (image_incl f) (kernel_quotient_extension f), exact ab_group_kernel_quotient_to_image_codomain_triangle f, exact is_embedding_kernel_quotient_extension f end definition ab_group_first_iso_thm {A B : AbGroup} (f : A β†’g B) : quotient_ab_group (kernel f) ≃g ab_Image f := begin fapply isomorphism.mk, exact ab_group_kernel_quotient_to_image f, fapply is_equiv_of_is_surjective_of_is_embedding, exact is_embedding_kernel_quotient_to_image f, exact is_surjective_kernel_quotient_to_image f end definition codomain_surjection_is_quotient {A B : AbGroup} (f : A β†’g B)( H : is_surjective f) : quotient_ab_group (kernel f) ≃g B := begin exact (ab_group_first_iso_thm f) ⬝g (iso_surjection_ab_image_incl f H) end definition codomain_surjection_is_quotient_triangle {A B : AbGroup} (f : A β†’g B)( H : is_surjective f) : codomain_surjection_is_quotient (f)(H) ∘g ab_qg_map (kernel f) ~ f := begin intro a, esimp end -- print iff.mpr /- set generating normal subgroup -/ section parameters {A₁ : AbGroup} (S : A₁ β†’ Prop) variable {Aβ‚‚ : AbGroup} inductive generating_relation' : A₁ β†’ Type := | rincl : Ξ {g}, S g β†’ generating_relation' g | rmul : Ξ {g h}, generating_relation' g β†’ generating_relation' h β†’ generating_relation' (g * h) | rinv : Ξ {g}, generating_relation' g β†’ generating_relation' g⁻¹ | rone : generating_relation' 1 open generating_relation' definition generating_relation (g : A₁) : Prop := βˆ₯ generating_relation' g βˆ₯ local abbreviation R := generating_relation definition gr_one : R 1 := tr (rone S) definition gr_inv (g : A₁) : R g β†’ R g⁻¹ := trunc_functor -1 rinv definition gr_mul (g h : A₁) : R g β†’ R h β†’ R (g * h) := trunc_functor2 rmul definition normal_generating_relation [instance] : is_subgroup A₁ generating_relation := ⦃ is_subgroup, one_mem := gr_one, inv_mem := gr_inv, mul_mem := gr_mul⦄ parameter (A₁) definition quotient_ab_group_gen : AbGroup := quotient_ab_group generating_relation definition gqg_map [constructor] : A₁ β†’g quotient_ab_group_gen := ab_qg_map _ parameter {A₁} definition gqg_eq_of_rel {g h : A₁} (H : S (g * h⁻¹)) : gqg_map g = gqg_map h := eq_of_rel (tr (rincl H)) -- this one might work if the previous one doesn't (maybe make this the default one?) definition gqg_eq_of_rel' {g h : A₁} (H : S (g * h⁻¹)) : class_of g = class_of h :> quotient_ab_group_gen := gqg_eq_of_rel H definition gqg_elim [constructor] (f : A₁ β†’g Aβ‚‚) (H : Π⦃g⦄, S g β†’ f g = 1) : quotient_ab_group_gen β†’g Aβ‚‚ := begin apply quotient_ab_group_elim f, intro g r, induction r with r, induction r with g s g h r r' IH1 IH2 g r IH, { exact H s }, { exact !respect_mul ⬝ ap011 mul IH1 IH2 ⬝ !one_mul }, { exact !respect_inv ⬝ ap inv IH ⬝ !one_inv }, { apply respect_one } end definition gqg_elim_compute (f : A₁ β†’g Aβ‚‚) (H : Π⦃g⦄, S g β†’ f g = 1) : gqg_elim f H ∘ gqg_map ~ f := begin intro g, reflexivity end definition gqg_elim_unique (f : A₁ β†’g Aβ‚‚) (H : Π⦃g⦄, S g β†’ f g = 1) (k : quotient_ab_group_gen β†’g Aβ‚‚) : ( k ∘g gqg_map ~ f ) β†’ k ~ gqg_elim f H := !ab_gelim_unique end end group namespace group variables {G H K : Group} {R : property G} [is_normal_subgroup G R] {S : property H} [is_normal_subgroup H S] {T : property K} [is_normal_subgroup K T] theorem quotient_group_functor_compose (ψ : H β†’g K) (Ο† : G β†’g H) (hψ : Ξ g, g ∈ S β†’ ψ g ∈ T) (hΟ† : Ξ g, g ∈ R β†’ Ο† g ∈ S) : quotient_group_functor ψ hψ ∘g quotient_group_functor Ο† hΟ† ~ quotient_group_functor (ψ ∘g Ο†) (Ξ»g, proof hψ (Ο† g) qed ∘ hΟ† g) := begin intro g, induction g using set_quotient.rec_prop with g hg, reflexivity end definition quotient_group_functor_gid : quotient_group_functor (gid G) (Ξ»g, id) ~ gid (quotient_group R) := begin intro g, induction g using set_quotient.rec_prop with g hg, reflexivity end definition quotient_group_functor_homotopy {ψ Ο† : G β†’g H} (hψ : Ξ g, R g β†’ S (ψ g)) (hΟ† : Ξ g, g ∈ R β†’ Ο† g ∈ S) (p : Ο† ~ ψ) : quotient_group_functor Ο† hΟ† ~ quotient_group_functor ψ hψ := begin intro g, induction g using set_quotient.rec_prop with g hg, exact ap set_quotient.class_of (p g) end end group namespace group variables {G H K : AbGroup} {R : property G} [is_subgroup G R] {S : property H} [is_subgroup H S] {T : property K} [is_subgroup K T] definition quotient_ab_group_functor [constructor] (Ο† : G β†’g H) (h : Ξ g, g ∈ R β†’ Ο† g ∈ S) : quotient_ab_group R β†’g quotient_ab_group S := @quotient_group_functor G H R (is_normal_subgroup_ab _) S (is_normal_subgroup_ab _) Ο† h definition quotient_ab_group_functor_mul (ψ Ο† : G β†’g H) (hψ : Ξ g, g ∈ R β†’ ψ g ∈ S) (hΟ† : Ξ g, g ∈ R β†’ Ο† g ∈ S) : homomorphism_mul (quotient_ab_group_functor ψ hψ) (quotient_ab_group_functor Ο† hΟ†) ~ quotient_ab_group_functor (homomorphism_mul ψ Ο†) (Ξ»g hg, is_subgroup.mul_mem (hψ g hg) (hΟ† g hg)) := begin intro g, induction g using set_quotient.rec_prop with g hg, reflexivity end theorem quotient_ab_group_functor_compose (ψ : H β†’g K) (Ο† : G β†’g H) (hψ : Ξ g, g ∈ S β†’ ψ g ∈ T) (hΟ† : Ξ g, g ∈ R β†’ Ο† g ∈ S) : quotient_ab_group_functor ψ hψ ∘g quotient_ab_group_functor Ο† hΟ† ~ quotient_ab_group_functor (ψ ∘g Ο†) (Ξ»g, proof hψ (Ο† g) qed ∘ hΟ† g) := @quotient_group_functor_compose G H K R _ S _ T _ ψ Ο† hψ hΟ† definition quotient_ab_group_functor_gid : quotient_ab_group_functor (gid G) (Ξ»g, id) ~ gid (quotient_ab_group R) := @quotient_group_functor_gid G R _ definition quotient_ab_group_functor_homotopy {ψ Ο† : G β†’g H} (hψ : Ξ g, R g β†’ S (ψ g)) (hΟ† : Ξ g, g ∈ R β†’ Ο† g ∈ S) (p : Ο† ~ ψ) : quotient_ab_group_functor Ο† hΟ† ~ quotient_ab_group_functor ψ hψ := @quotient_group_functor_homotopy G H R _ S _ ψ Ο† hψ hΟ† p end group
55be21c78fc8e5cbdff8e33d360b140be60551b4
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/analysis/hofer.lean
ee80f85a31ce1277c5ec931ae0a158eff2857d7c
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
4,585
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import analysis.specific_limits /-! # Hofer's lemma This is an elementary lemma about complete metric spaces. It is motivated by an application to the bubbling-off analysis for holomorphic curves in symplectic topology. We are *very* far away from having these applications, but the proof here is a nice example of a proof needing to construct a sequence by induction in the middle of the proof. ## References: * H. Hofer and C. Viterbo, *The Weinstein conjecture in the presence of holomorphic spheres* -/ open_locale classical topological_space big_operators open filter finset local notation `d` := dist lemma hofer {X: Type*} [metric_space X] [complete_space X] (x : X) (Ξ΅ : ℝ) (Ξ΅_pos : 0 < Ξ΅) {Ο• : X β†’ ℝ} (cont : continuous Ο•) (nonneg : βˆ€ y, 0 ≀ Ο• y) : βˆƒ (Ξ΅' > 0) (x' : X), Ξ΅' ≀ Ξ΅ ∧ d x' x ≀ 2*Ξ΅ ∧ Ξ΅ * Ο•(x) ≀ Ξ΅' * Ο• x' ∧ βˆ€ y, d x' y ≀ Ξ΅' β†’ Ο• y ≀ 2*Ο• x' := begin by_contradiction H, have reformulation : βˆ€ x' (k : β„•), Ξ΅ * Ο• x ≀ Ξ΅ / 2 ^ k * Ο• x' ↔ 2^k * Ο• x ≀ Ο• x', { intros x' k, rw [div_mul_eq_mul_div, le_div_iff, mul_assoc, mul_le_mul_left Ξ΅_pos, mul_comm], exact pow_pos (by norm_num) k, }, -- Now let's specialize to `Ξ΅/2^k` replace H : βˆ€ k : β„•, βˆ€ x', d x' x ≀ 2 * Ξ΅ ∧ 2^k * Ο• x ≀ Ο• x' β†’ βˆƒ y, d x' y ≀ Ξ΅/2^k ∧ 2 * Ο• x' < Ο• y, { intros k x', push_neg at H, simpa [reformulation] using H (Ξ΅/2^k) (by simp [Ξ΅_pos, zero_lt_two]) x' (by simp [Ξ΅_pos, zero_lt_two, one_le_two]) }, clear reformulation, haveI : nonempty X := ⟨x⟩, choose! F hF using H, -- Use the axiom of choice -- Now define u by induction starting at x, with u_{n+1} = F(n, u_n) let u : β„• β†’ X := Ξ» n, nat.rec_on n x F, have hu0 : u 0 = x := rfl, -- The properties of F translate to properties of u have hu : βˆ€ n, d (u n) x ≀ 2 * Ξ΅ ∧ 2^n * Ο• x ≀ Ο• (u n) β†’ d (u n) (u $ n + 1) ≀ Ξ΅ / 2 ^ n ∧ 2 * Ο• (u n) < Ο• (u $ n + 1), { intro n, exact hF n (u n) }, clear hF, -- Key properties of u, to be proven by induction have key : βˆ€ n, d (u n) (u (n + 1)) ≀ Ξ΅ / 2 ^ n ∧ 2 * Ο• (u n) < Ο• (u (n + 1)), { intro n, induction n using nat.case_strong_induction_on with n IH, { specialize hu 0, simpa [hu0, mul_nonneg_iff, zero_le_one, Ξ΅_pos.le] using hu }, have A : d (u (n+1)) x ≀ 2 * Ξ΅, { rw [dist_comm], let r := range (n+1), -- range (n+1) = {0, ..., n} calc d (u 0) (u (n + 1)) ≀ βˆ‘ i in r, d (u i) (u $ i+1) : dist_le_range_sum_dist u (n + 1) ... ≀ βˆ‘ i in r, Ξ΅/2^i : sum_le_sum (Ξ» i i_in, (IH i $ nat.lt_succ_iff.mp $ finset.mem_range.mp i_in).1) ... = βˆ‘ i in r, (1/2)^i*Ξ΅ : by { congr' with i, field_simp } ... = (βˆ‘ i in r, (1/2)^i)*Ξ΅ : finset.sum_mul.symm ... ≀ 2*Ξ΅ : mul_le_mul_of_nonneg_right (sum_geometric_two_le _) (le_of_lt Ξ΅_pos), }, have B : 2^(n+1) * Ο• x ≀ Ο• (u (n + 1)), { refine @geom_le (Ο• ∘ u) _ zero_le_two (n + 1) (Ξ» m hm, _), exact (IH _ $ nat.lt_add_one_iff.1 hm).2.le }, exact hu (n+1) ⟨A, B⟩, }, cases forall_and_distrib.mp key with key₁ keyβ‚‚, clear hu key, -- Hence u is Cauchy have cauchy_u : cauchy_seq u, { refine cauchy_seq_of_le_geometric _ Ξ΅ one_half_lt_one (Ξ» n, _), simpa only [one_div, inv_pow'] using key₁ n }, -- So u converges to some y obtain ⟨y, limy⟩ : βˆƒ y, tendsto u at_top (𝓝 y), from complete_space.complete cauchy_u, -- And Ο• ∘ u goes to +∞ have lim_top : tendsto (Ο• ∘ u) at_top at_top, { let v := Ξ» n, (Ο• ∘ u) (n+1), suffices : tendsto v at_top at_top, by rwa tendsto_add_at_top_iff_nat at this, have hvβ‚€ : 0 < v 0, { have : 0 ≀ Ο• (u 0) := nonneg x, calc 0 ≀ 2 * Ο• (u 0) : by linarith ... < Ο• (u (0 + 1)) : keyβ‚‚ 0 }, apply tendsto_at_top_of_geom_le hvβ‚€ one_lt_two, exact Ξ» n, (keyβ‚‚ (n+1)).le }, -- But Ο• ∘ u also needs to go to Ο•(y) have lim : tendsto (Ο• ∘ u) at_top (𝓝 (Ο• y)), from tendsto.comp cont.continuous_at limy, -- So we have our contradiction! exact not_tendsto_at_top_of_tendsto_nhds lim lim_top, end
0c9f20a61618bfec0d41e33cf7f8f6da6a65ce2b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/filter/interval.lean
a55264d92dec7fe47a231d2b244632da010f6599
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,817
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import data.set.intervals.ord_connected import order.filter.lift import order.filter.at_top_bot /-! # Convergence of intervals If both `a` and `b` tend to some filter `l₁`, sometimes this implies that `Ixx a b` tends to `lβ‚‚.lift' powerset`, i.e., for any `s ∈ lβ‚‚` eventually `Ixx a b` becomes a subset of `s`. Here and below `Ixx` is one of `Icc`, `Ico`, `Ioc`, and `Ioo`. We define `filter.tendsto_Ixx_class Ixx l₁ lβ‚‚` to be a typeclass representing this property. The instances provide the best `lβ‚‚` for a given `l₁`. In many cases `l₁ = lβ‚‚` but sometimes we can drop an endpoint from an interval: e.g., we prove `tendsto_Ixx_class Ico (π“Ÿ $ Iic a) (π“Ÿ $ Iio a)`, i.e., if `u₁ n` and `uβ‚‚ n` belong eventually to `Iic a`, then the interval `Ico (u₁ n) (uβ‚‚ n)` is eventually included in `Iio a`. The next table shows β€œoutput” filters `lβ‚‚` for different values of `Ixx` and `l₁`. The instances that need topology are defined in `topology/algebra/ordered`. | Input filter | `Ixx = Icc` | `Ixx = Ico` | `Ixx = Ioc` | `Ixx = Ioo` | | -----------: | :-----------: | :-----------: | :-----------: | :-----------: | | `at_top` | `at_top` | `at_top` | `at_top` | `at_top` | | `at_bot` | `at_bot` | `at_bot` | `at_bot` | `at_bot` | | `pure a` | `pure a` | `βŠ₯` | `βŠ₯` | `βŠ₯` | | `π“Ÿ (Iic a)` | `π“Ÿ (Iic a)` | `π“Ÿ (Iio a)` | `π“Ÿ (Iic a)` | `π“Ÿ (Iio a)` | | `π“Ÿ (Ici a)` | `π“Ÿ (Ici a)` | `π“Ÿ (Ici a)` | `π“Ÿ (Ioi a)` | `π“Ÿ (Ioi a)` | | `π“Ÿ (Ioi a)` | `π“Ÿ (Ioi a)` | `π“Ÿ (Ioi a)` | `π“Ÿ (Ioi a)` | `π“Ÿ (Ioi a)` | | `π“Ÿ (Iio a)` | `π“Ÿ (Iio a)` | `π“Ÿ (Iio a)` | `π“Ÿ (Iio a)` | `π“Ÿ (Iio a)` | | `𝓝 a` | `𝓝 a` | `𝓝 a` | `𝓝 a` | `𝓝 a` | | `𝓝[Iic a] b` | `𝓝[Iic a] b` | `𝓝[Iio a] b` | `𝓝[Iic a] b` | `𝓝[Iio a] b` | | `𝓝[Ici a] b` | `𝓝[Ici a] b` | `𝓝[Ici a] b` | `𝓝[Ioi a] b` | `𝓝[Ioi a] b` | | `𝓝[Ioi a] b` | `𝓝[Ioi a] b` | `𝓝[Ioi a] b` | `𝓝[Ioi a] b` | `𝓝[Ioi a] b` | | `𝓝[Iio a] b` | `𝓝[Iio a] b` | `𝓝[Iio a] b` | `𝓝[Iio a] b` | `𝓝[Iio a] b` | -/ variables {Ξ± Ξ² : Type*} open_locale classical filter interval open set function namespace filter section preorder variables [preorder Ξ±] /-- A pair of filters `l₁`, `lβ‚‚` has `tendsto_Ixx_class Ixx` property if `Ixx a b` tends to `lβ‚‚.lift' powerset` as `a` and `b` tend to `l₁`. In all instances `Ixx` is one of `Icc`, `Ico`, `Ioc`, or `Ioo`. The instances provide the best `lβ‚‚` for a given `l₁`. In many cases `l₁ = lβ‚‚` but sometimes we can drop an endpoint from an interval: e.g., we prove `tendsto_Ixx_class Ico (π“Ÿ $ Iic a) (π“Ÿ $ Iio a)`, i.e., if `u₁ n` and `uβ‚‚ n` belong eventually to `Iic a`, then the interval `Ico (u₁ n) (uβ‚‚ n)` is eventually included in `Iio a`. We mark `lβ‚‚` as an `out_param` so that Lean can automatically find an appropriate `lβ‚‚` based on `Ixx` and `l₁`. This way, e.g., `tendsto.Ico h₁ hβ‚‚` works without specifying explicitly `lβ‚‚`. -/ class tendsto_Ixx_class (Ixx : Ξ± β†’ Ξ± β†’ set Ξ±) (l₁ : filter Ξ±) (lβ‚‚ : out_param $ filter Ξ±) : Prop := (tendsto_Ixx : tendsto (Ξ» p : Ξ± Γ— Ξ±, Ixx p.1 p.2) (l₁ Γ—αΆ  l₁) (lβ‚‚.lift' powerset)) lemma tendsto.Icc {l₁ lβ‚‚ : filter Ξ±} [tendsto_Ixx_class Icc l₁ lβ‚‚] {lb : filter Ξ²} {u₁ uβ‚‚ : Ξ² β†’ Ξ±} (h₁ : tendsto u₁ lb l₁) (hβ‚‚ : tendsto uβ‚‚ lb l₁) : tendsto (Ξ» x, Icc (u₁ x) (uβ‚‚ x)) lb (lβ‚‚.lift' powerset) := tendsto_Ixx_class.tendsto_Ixx.comp $ h₁.prod_mk hβ‚‚ lemma tendsto.Ioc {l₁ lβ‚‚ : filter Ξ±} [tendsto_Ixx_class Ioc l₁ lβ‚‚] {lb : filter Ξ²} {u₁ uβ‚‚ : Ξ² β†’ Ξ±} (h₁ : tendsto u₁ lb l₁) (hβ‚‚ : tendsto uβ‚‚ lb l₁) : tendsto (Ξ» x, Ioc (u₁ x) (uβ‚‚ x)) lb (lβ‚‚.lift' powerset) := tendsto_Ixx_class.tendsto_Ixx.comp $ h₁.prod_mk hβ‚‚ lemma tendsto.Ico {l₁ lβ‚‚ : filter Ξ±} [tendsto_Ixx_class Ico l₁ lβ‚‚] {lb : filter Ξ²} {u₁ uβ‚‚ : Ξ² β†’ Ξ±} (h₁ : tendsto u₁ lb l₁) (hβ‚‚ : tendsto uβ‚‚ lb l₁) : tendsto (Ξ» x, Ico (u₁ x) (uβ‚‚ x)) lb (lβ‚‚.lift' powerset) := tendsto_Ixx_class.tendsto_Ixx.comp $ h₁.prod_mk hβ‚‚ lemma tendsto.Ioo {l₁ lβ‚‚ : filter Ξ±} [tendsto_Ixx_class Ioo l₁ lβ‚‚] {lb : filter Ξ²} {u₁ uβ‚‚ : Ξ² β†’ Ξ±} (h₁ : tendsto u₁ lb l₁) (hβ‚‚ : tendsto uβ‚‚ lb l₁) : tendsto (Ξ» x, Ioo (u₁ x) (uβ‚‚ x)) lb (lβ‚‚.lift' powerset) := tendsto_Ixx_class.tendsto_Ixx.comp $ h₁.prod_mk hβ‚‚ lemma tendsto_Ixx_class_principal {s t : set Ξ±} {Ixx : Ξ± β†’ Ξ± β†’ set Ξ±} : tendsto_Ixx_class Ixx (π“Ÿ s) (π“Ÿ t) ↔ βˆ€ (x ∈ s) (y ∈ s), Ixx x y βŠ† t := begin refine iff.trans ⟨λ h, h.1, Ξ» h, ⟨h⟩⟩ _, simp [lift'_principal monotone_powerset, -mem_prod, -prod.forall, forall_prod_set] end lemma tendsto_Ixx_class_inf {l₁ l₁' lβ‚‚ lβ‚‚' : filter Ξ±} {Ixx} [h : tendsto_Ixx_class Ixx l₁ lβ‚‚] [h' : tendsto_Ixx_class Ixx l₁' lβ‚‚'] : tendsto_Ixx_class Ixx (l₁ βŠ“ l₁') (lβ‚‚ βŠ“ lβ‚‚') := ⟨by simpa only [prod_inf_prod, lift'_inf_powerset] using h.1.inf h'.1⟩ lemma tendsto_Ixx_class_of_subset {l₁ lβ‚‚ : filter Ξ±} {Ixx Ixx' : Ξ± β†’ Ξ± β†’ set Ξ±} (h : βˆ€ a b, Ixx a b βŠ† Ixx' a b) [h' : tendsto_Ixx_class Ixx' l₁ lβ‚‚] : tendsto_Ixx_class Ixx l₁ lβ‚‚ := ⟨tendsto_lift'_powerset_mono h'.1 $ eventually_of_forall $ prod.forall.2 h⟩ lemma has_basis.tendsto_Ixx_class {ΞΉ : Type*} {p : ΞΉ β†’ Prop} {s} {l : filter Ξ±} (hl : l.has_basis p s) {Ixx : Ξ± β†’ Ξ± β†’ set Ξ±} (H : βˆ€ i, p i β†’ βˆ€ (x ∈ s i) (y ∈ s i), Ixx x y βŠ† s i) : tendsto_Ixx_class Ixx l l := ⟨(hl.prod_self.tendsto_iff (hl.lift' monotone_powerset)).2 $ Ξ» i hi, ⟨i, hi, Ξ» x hx, H i hi _ hx.1 _ hx.2⟩⟩ instance tendsto_Icc_at_top_at_top : tendsto_Ixx_class Icc (at_top : filter Ξ±) at_top := (has_basis_infi_principal_finite _).tendsto_Ixx_class $ Ξ» s hs, set.ord_connected.out $ ord_connected_bInter $ Ξ» i hi, ord_connected_Ici instance tendsto_Ico_at_top_at_top : tendsto_Ixx_class Ico (at_top : filter Ξ±) at_top := tendsto_Ixx_class_of_subset (Ξ» _ _, Ico_subset_Icc_self) instance tendsto_Ioc_at_top_at_top : tendsto_Ixx_class Ioc (at_top : filter Ξ±) at_top := tendsto_Ixx_class_of_subset (Ξ» _ _, Ioc_subset_Icc_self) instance tendsto_Ioo_at_top_at_top : tendsto_Ixx_class Ioo (at_top : filter Ξ±) at_top := tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Icc_self) instance tendsto_Icc_at_bot_at_bot : tendsto_Ixx_class Icc (at_bot : filter Ξ±) at_bot := (has_basis_infi_principal_finite _).tendsto_Ixx_class $ Ξ» s hs, set.ord_connected.out $ ord_connected_bInter $ Ξ» i hi, ord_connected_Iic instance tendsto_Ico_at_bot_at_bot : tendsto_Ixx_class Ico (at_bot : filter Ξ±) at_bot := tendsto_Ixx_class_of_subset (Ξ» _ _, Ico_subset_Icc_self) instance tendsto_Ioc_at_bot_at_bot : tendsto_Ixx_class Ioc (at_bot : filter Ξ±) at_bot := tendsto_Ixx_class_of_subset (Ξ» _ _, Ioc_subset_Icc_self) instance tendsto_Ioo_at_bot_at_bot : tendsto_Ixx_class Ioo (at_bot : filter Ξ±) at_bot := tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Icc_self) instance ord_connected.tendsto_Icc {s : set Ξ±} [hs : ord_connected s] : tendsto_Ixx_class Icc (π“Ÿ s) (π“Ÿ s) := tendsto_Ixx_class_principal.2 hs.out instance tendsto_Ico_Ici_Ici {a : Ξ±} : tendsto_Ixx_class Ico (π“Ÿ (Ici a)) (π“Ÿ (Ici a)) := tendsto_Ixx_class_of_subset (Ξ» _ _, Ico_subset_Icc_self) instance tendsto_Ico_Ioi_Ioi {a : Ξ±} : tendsto_Ixx_class Ico (π“Ÿ (Ioi a)) (π“Ÿ (Ioi a)) := tendsto_Ixx_class_of_subset (Ξ» _ _, Ico_subset_Icc_self) instance tendsto_Ico_Iic_Iio {a : Ξ±} : tendsto_Ixx_class Ico (π“Ÿ (Iic a)) (π“Ÿ (Iio a)) := tendsto_Ixx_class_principal.2 $ Ξ» a ha b hb x hx, lt_of_lt_of_le hx.2 hb instance tendsto_Ico_Iio_Iio {a : Ξ±} : tendsto_Ixx_class Ico (π“Ÿ (Iio a)) (π“Ÿ (Iio a)) := tendsto_Ixx_class_of_subset (Ξ» _ _, Ico_subset_Icc_self) instance tendsto_Ioc_Ici_Ioi {a : Ξ±} : tendsto_Ixx_class Ioc (π“Ÿ (Ici a)) (π“Ÿ (Ioi a)) := tendsto_Ixx_class_principal.2 $ Ξ» x hx y hy t ht, lt_of_le_of_lt hx ht.1 instance tendsto_Ioc_Iic_Iic {a : Ξ±} : tendsto_Ixx_class Ioc (π“Ÿ (Iic a)) (π“Ÿ (Iic a)) := tendsto_Ixx_class_of_subset (Ξ» _ _, Ioc_subset_Icc_self) instance tendsto_Ioc_Iio_Iio {a : Ξ±} : tendsto_Ixx_class Ioc (π“Ÿ (Iio a)) (π“Ÿ (Iio a)) := tendsto_Ixx_class_of_subset (Ξ» _ _, Ioc_subset_Icc_self) instance tendsto_Ioc_Ioi_Ioi {a : Ξ±} : tendsto_Ixx_class Ioc (π“Ÿ (Ioi a)) (π“Ÿ (Ioi a)) := tendsto_Ixx_class_of_subset (Ξ» _ _, Ioc_subset_Icc_self) instance tendsto_Ioo_Ici_Ioi {a : Ξ±} : tendsto_Ixx_class Ioo (π“Ÿ (Ici a)) (π“Ÿ (Ioi a)) := tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Ioc_self) instance tendsto_Ioo_Iic_Iio {a : Ξ±} : tendsto_Ixx_class Ioo (π“Ÿ (Iic a)) (π“Ÿ (Iio a)) := tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Ico_self) instance tendsto_Ioo_Ioi_Ioi {a : Ξ±} : tendsto_Ixx_class Ioo (π“Ÿ (Ioi a)) (π“Ÿ (Ioi a)) := tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Ioc_self) instance tendsto_Ioo_Iio_Iio {a : Ξ±} : tendsto_Ixx_class Ioo (π“Ÿ (Iio a)) (π“Ÿ (Iio a)) := tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Ioc_self) instance tendsto_Icc_Icc_icc {a b : Ξ±} : tendsto_Ixx_class Icc (π“Ÿ (Icc a b)) (π“Ÿ (Icc a b)) := tendsto_Ixx_class_principal.mpr $ Ξ» x hx y hy, Icc_subset_Icc hx.1 hy.2 instance tendsto_Ioc_Icc_Icc {a b : Ξ±} : tendsto_Ixx_class Ioc (π“Ÿ (Icc a b)) (π“Ÿ (Icc a b)) := tendsto_Ixx_class_of_subset $ Ξ» _ _, Ioc_subset_Icc_self end preorder section partial_order variable [partial_order Ξ±] instance tendsto_Icc_pure_pure {a : Ξ±} : tendsto_Ixx_class Icc (pure a) (pure a : filter Ξ±) := by { rw ← principal_singleton, exact tendsto_Ixx_class_principal.2 ord_connected_singleton.out } instance tendsto_Ico_pure_bot {a : Ξ±} : tendsto_Ixx_class Ico (pure a) βŠ₯ := ⟨by simp [lift'_bot monotone_powerset]⟩ instance tendsto_Ioc_pure_bot {a : Ξ±} : tendsto_Ixx_class Ioc (pure a) βŠ₯ := ⟨by simp [lift'_bot monotone_powerset]⟩ instance tendsto_Ioo_pure_bot {a : Ξ±} : tendsto_Ixx_class Ioo (pure a) βŠ₯ := tendsto_Ixx_class_of_subset (Ξ» _ _, Ioo_subset_Ioc_self) end partial_order section linear_order variables [linear_order Ξ±] instance tendsto_Icc_interval_interval {a b : Ξ±} : tendsto_Ixx_class Icc (π“Ÿ [a, b]) (π“Ÿ [a, b]) := filter.tendsto_Icc_Icc_icc instance tendsto_Ioc_interval_interval {a b : Ξ±} : tendsto_Ixx_class Ioc (π“Ÿ [a, b]) (π“Ÿ [a, b]) := tendsto_Ixx_class_of_subset $ Ξ» _ _, Ioc_subset_Icc_self end linear_order end filter
1921ce4c134279134481457583532cefc167be92
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/continued_fractions/convergents_equiv.lean
0197e0112a302ab24acb5874969b7377d86fcaaa
[ "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
20,583
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.continuants_recurrence import algebra.continued_fractions.terminated_stable import tactic.linarith /-! # Equivalence of Recursive and Direct Computations of `gcf` Convergents ## Summary We show the equivalence of two computations of convergents (recurrence relation (`convergents`) vs. direct evaluation (`convergents'`)) for `gcf`s on linear ordered fields. We follow the proof from [hardy2008introduction], Chapter 10. Here's a sketch: Let `c` be a continued fraction `[h; (aβ‚€, bβ‚€), (a₁, b₁), (aβ‚‚, bβ‚‚),...]`, visually: aβ‚€ h + --------------------------- a₁ bβ‚€ + -------------------- aβ‚‚ b₁ + -------------- a₃ bβ‚‚ + -------- b₃ + ... One can compute the convergents of `c` in two ways: 1. Directly evaluating the fraction described by `c` up to a given `n` (`convergents'`) 2. Using the recurrence (`convergents`): - `A₋₁ = 1, Aβ‚€ = h, Aβ‚™ = bₙ₋₁ * Aₙ₋₁ + aₙ₋₁ * Aβ‚™β‚‹β‚‚`, and - `B₋₁ = 0, Bβ‚€ = 1, Bβ‚™ = bₙ₋₁ * Bₙ₋₁ + aₙ₋₁ * Bβ‚™β‚‹β‚‚`. To show the equivalence of the computations in the main theorem of this file `convergents_eq_convergents'`, we proceed by induction. The case `n = 0` is trivial. For `n + 1`, we first "squash" the `n + 1`th position of `c` into the `n`th position to obtain another continued fraction `c' := [h; (aβ‚€, bβ‚€),..., (aβ‚™-₁, bβ‚™-₁), (aβ‚™, bβ‚™ + aβ‚™β‚Šβ‚ / bβ‚™β‚Šβ‚), (aβ‚™β‚Šβ‚, bβ‚™β‚Šβ‚),...]`. This squashing process is formalised in section `squash`. Note that directly evaluating `c` up to position `n + 1` is equal to evaluating `c'` up to `n`. This is shown in lemma `succ_nth_convergent'_eq_squash_gcf_nth_convergent'`. By the inductive hypothesis, the two computations for the `n`th convergent of `c` coincide. So all that is left to show is that the recurrence relation for `c` at `n + 1` and and `c'` at `n` coincide. This can be shown by another induction. The corresponding lemma in this file is `succ_nth_convergent_eq_squash_gcf_nth_convergent`. ## Main Theorems - `generalized_continued_fraction.convergents_eq_convergents'` shows the equivalence under a strict positivity restriction on the sequence. - `continued_fractions.convergents_eq_convergents'` shows the equivalence for (regular) continued fractions. ## References - https://en.wikipedia.org/wiki/Generalized_continued_fraction - [*Hardy, GH and Wright, EM and Heath-Brown, Roger and Silverman, Joseph*][hardy2008introduction] ## Tags fractions, recurrence, equivalence -/ variables {K : Type*} {n : β„•} namespace generalized_continued_fraction open generalized_continued_fraction as gcf variables {g : gcf K} {s : seq $ gcf.pair K} section squash /-! We will show the equivalence of the computations by induction. To make the induction work, we need to be able to *squash* the nth and (n + 1)th value of a sequence. This squashing itself and the lemmas about it are not very interesting. As a reader, you hence might want to skip this section. -/ section with_division_ring variable [division_ring K] /-- Given a sequence of gcf.pairs `s = [(aβ‚€, bβ‚’), (a₁, b₁), ...]`, `squash_seq s n` combines `⟨aβ‚™, bβ‚™βŸ©` and `⟨aβ‚™β‚Šβ‚, bβ‚™β‚Šβ‚βŸ©` at position `n` to `⟨aβ‚™, bβ‚™ + aβ‚™β‚Šβ‚ / bβ‚™β‚Šβ‚βŸ©`. For example, `squash_seq s 0 = [(aβ‚€, bβ‚’ + a₁ / b₁), (a₁, b₁),...]`. If `s.terminated_at (n + 1)`, then `squash_seq s n = s`. -/ def squash_seq (s : seq $ gcf.pair K) (n : β„•) : seq (gcf.pair K) := match prod.mk (s.nth n) (s.nth (n + 1)) with | ⟨some gp_n, some gp_succ_n⟩ := seq.nats.zip_with -- return the squashed value at position `n`; otherwise, do nothing. (Ξ» n' gp, if n' = n then ⟨gp_n.a, gp_n.b + gp_succ_n.a / gp_succ_n.b⟩ else gp) s | _ := s end /-! We now prove some simple lemmas about the squashed sequence -/ /-- If the sequence already terminated at position `n + 1`, nothing gets squashed. -/ lemma squash_seq_eq_self_of_terminated (terminated_at_succ_n : s.terminated_at (n + 1)) : squash_seq s n = s := begin change s.nth (n + 1) = none at terminated_at_succ_n, cases s_nth_eq : (s.nth n); simp only [*, squash_seq] end /-- If the sequence has not terminated before position `n + 1`, the value at `n + 1` gets squashed into position `n`. -/ lemma squash_seq_nth_of_not_terminated {gp_n gp_succ_n : gcf.pair K} (s_nth_eq : s.nth n = some gp_n) (s_succ_nth_eq : s.nth (n + 1) = some gp_succ_n) : (squash_seq s n).nth n = some ⟨gp_n.a, gp_n.b + gp_succ_n.a / gp_succ_n.b⟩ := by simp [*, squash_seq, (seq.zip_with_nth_some (seq.nats_nth n) s_nth_eq _)] /-- The values before the squashed position stay the same. -/ lemma squash_seq_nth_of_lt {m : β„•} (m_lt_n : m < n) : (squash_seq s n).nth m = s.nth m := begin cases s_succ_nth_eq : s.nth (n + 1), case option.none { rw (squash_seq_eq_self_of_terminated s_succ_nth_eq) }, case option.some { obtain ⟨gp_n, s_nth_eq⟩ : βˆƒ gp_n, s.nth n = some gp_n, from s.ge_stable n.le_succ s_succ_nth_eq, obtain ⟨gp_m, s_mth_eq⟩ : βˆƒ gp_m, s.nth m = some gp_m, from s.ge_stable (le_of_lt m_lt_n) s_nth_eq, simp [*, squash_seq, (seq.zip_with_nth_some (seq.nats_nth m) s_mth_eq _), (ne_of_lt m_lt_n)] } end /-- Squashing at position `n + 1` and taking the tail is the same as squashing the tail of the sequence at position `n`. -/ lemma squash_seq_succ_n_tail_eq_squash_seq_tail_n : (squash_seq s (n + 1)).tail = squash_seq s.tail n := begin cases s_succ_succ_nth_eq : s.nth (n + 2) with gp_succ_succ_n, case option.none { have : squash_seq s (n + 1) = s, from squash_seq_eq_self_of_terminated s_succ_succ_nth_eq, cases s_succ_nth_eq : (s.nth (n + 1)); simp only [squash_seq, seq.nth_tail, s_succ_nth_eq, s_succ_succ_nth_eq] }, case option.some { obtain ⟨gp_succ_n, s_succ_nth_eq⟩ : βˆƒ gp_succ_n, s.nth (n + 1) = some gp_succ_n, from s.ge_stable (n + 1).le_succ s_succ_succ_nth_eq, -- apply extensionality with `m` and continue by cases `m = n`. ext m, cases decidable.em (m = n) with m_eq_n m_ne_n, { have : s.tail.nth n = some gp_succ_n, from (s.nth_tail n).trans s_succ_nth_eq, simp [*, squash_seq, seq.nth_tail, (seq.zip_with_nth_some (seq.nats_nth n) this), (seq.zip_with_nth_some (seq.nats_nth (n + 1)) s_succ_nth_eq)] }, { have : s.tail.nth m = s.nth (m + 1), from s.nth_tail m, cases s_succ_mth_eq : s.nth (m + 1), all_goals { have s_tail_mth_eq, from this.trans s_succ_mth_eq }, { simp only [*, squash_seq, seq.nth_tail, (seq.zip_with_nth_none' s_succ_mth_eq), (seq.zip_with_nth_none' s_tail_mth_eq)] }, { simp [*, squash_seq, seq.nth_tail, (seq.zip_with_nth_some (seq.nats_nth (m + 1)) s_succ_mth_eq), (seq.zip_with_nth_some (seq.nats_nth m) s_tail_mth_eq)] } } } end /-- The auxiliary function `convergents'_aux` returns the same value for a sequence and the corresponding squashed sequence at the squashed position. -/ lemma succ_succ_nth_convergent'_aux_eq_succ_nth_convergent'_aux_squash_seq : convergents'_aux s (n + 2) = convergents'_aux (squash_seq s n) (n + 1) := begin cases s_succ_nth_eq : (s.nth $ n + 1) with gp_succ_n, case option.none { rw [(squash_seq_eq_self_of_terminated s_succ_nth_eq), (convergents'_aux_stable_step_of_terminated s_succ_nth_eq)] }, case option.some { induction n with m IH generalizing s gp_succ_n, case nat.zero { obtain ⟨gp_head, s_head_eq⟩ : βˆƒ gp_head, s.head = some gp_head, from s.ge_stable zero_le_one s_succ_nth_eq, have : (squash_seq s 0).head = some ⟨gp_head.a, gp_head.b + gp_succ_n.a / gp_succ_n.b⟩, from squash_seq_nth_of_not_terminated s_head_eq s_succ_nth_eq, simp [*, convergents'_aux, seq.head, seq.nth_tail] }, case nat.succ { obtain ⟨gp_head, s_head_eq⟩ : βˆƒ gp_head, s.head = some gp_head, from s.ge_stable (m + 2).zero_le s_succ_nth_eq, suffices : gp_head.a / (gp_head.b + convergents'_aux s.tail (m + 2)) = convergents'_aux (squash_seq s (m + 1)) (m + 2), by simpa only [convergents'_aux, s_head_eq], have : convergents'_aux s.tail (m + 2) = convergents'_aux (squash_seq s.tail m) (m + 1), by { have : s.tail.nth (m + 1) = some gp_succ_n, by simpa [seq.nth_tail] using s_succ_nth_eq, exact (IH _ this) }, have : (squash_seq s (m + 1)).head = some gp_head, from (squash_seq_nth_of_lt m.succ_pos).trans s_head_eq, simp only [*, convergents'_aux, squash_seq_succ_n_tail_eq_squash_seq_tail_n] } } end /-! Let us now lift the squashing operation to gcfs. -/ /-- Given a gcf `g = [h; (aβ‚€, bβ‚’), (a₁, b₁), ...]`, we have - `squash_nth.gcf g 0 = [h + aβ‚€ / bβ‚€); (aβ‚€, bβ‚’), ...]`, - `squash_nth.gcf g (n + 1) = ⟨g.h, squash_seq g.s n⟩` -/ def squash_gcf (g : gcf K) : β„• β†’ gcf K | 0 := match g.s.nth 0 with | none := g | some gp := ⟨g.h + gp.a / gp.b, g.s⟩ end | (n + 1) := ⟨g.h, squash_seq g.s n⟩ /-! Again, we derive some simple lemmas that are not really of interest. This time for the squashed gcf. -/ /-- If the gcf already terminated at position `n`, nothing gets squashed. -/ lemma squash_gcf_eq_self_of_terminated (terminated_at_n : terminated_at g n) : squash_gcf g n = g := begin cases n, case nat.zero { change g.s.nth 0 = none at terminated_at_n, simp only [convergents', squash_gcf, convergents'_aux, terminated_at_n] }, case nat.succ { cases g, simp [(squash_seq_eq_self_of_terminated terminated_at_n), squash_gcf] } end /-- The values before the squashed position stay the same. -/ lemma squash_gcf_nth_of_lt {m : β„•} (m_lt_n : m < n) : (squash_gcf g (n + 1)).s.nth m = g.s.nth m := by simp only [squash_gcf, (squash_seq_nth_of_lt m_lt_n)] /-- `convergents'` returns the same value for a gcf and the corresponding squashed gcf at the squashed position. -/ lemma succ_nth_convergent'_eq_squash_gcf_nth_convergent' : g.convergents' (n + 1) = (squash_gcf g n).convergents' n := begin cases n, case nat.zero { cases g_s_head_eq : (g.s.nth 0); simp [g_s_head_eq, squash_gcf, convergents', convergents'_aux, seq.head] }, case nat.succ { simp only [succ_succ_nth_convergent'_aux_eq_succ_nth_convergent'_aux_squash_seq, convergents', squash_gcf] } end /-- The auxiliary continuants before the squashed position stay the same. -/ lemma continuants_aux_eq_continuants_aux_squash_gcf_of_le {m : β„•} : m ≀ n β†’ continuants_aux g m = (squash_gcf g n).continuants_aux m := nat.strong_induction_on m (begin clear m, assume m IH m_le_n, cases m with m', { refl }, { cases n with n', { have : false, from m'.not_succ_le_zero m_le_n, contradiction }, -- 1 β‰° 0 { cases m' with m'', { refl }, { -- get some inequalities to instantiate the IH for m'' and m'' + 1 have m'_lt_n : m'' + 1 < n' + 1, from m_le_n, have : m'' + 1 < m'' + 2, by linarith, have succ_m''th_conts_aux_eq := IH (m'' + 1) this (le_of_lt m'_lt_n), have : m'' < m'' + 2, by linarith, have m''th_conts_aux_eq := IH m'' this (le_of_lt $ lt_of_lt_of_le (by linarith) n'.le_succ), have : (squash_gcf g (n' + 1)).s.nth m'' = g.s.nth m'', from squash_gcf_nth_of_lt (by linarith), simp [continuants_aux, succ_m''th_conts_aux_eq, m''th_conts_aux_eq, this] } } } end) end with_division_ring /-- The convergents coincide in the expected way at the squashed position if the partial denominator at the squashed position is not zero. -/ lemma succ_nth_convergent_eq_squash_gcf_nth_convergent [field K] (nth_part_denom_ne_zero : βˆ€ {b : K}, g.partial_denominators.nth n = some b β†’ b β‰  0) : g.convergents (n + 1) = (squash_gcf g n).convergents n := begin cases decidable.em (g.terminated_at n) with terminated_at_n not_terminated_at_n, { have : squash_gcf g n = g, from squash_gcf_eq_self_of_terminated terminated_at_n, simp only [this, (convergents_stable_of_terminated n.le_succ terminated_at_n)] }, { obtain ⟨⟨a, b⟩, s_nth_eq⟩ : βˆƒ gp_n, g.s.nth n = some gp_n, from option.ne_none_iff_exists'.mp not_terminated_at_n, have b_ne_zero : b β‰  0, from nth_part_denom_ne_zero (part_denom_eq_s_b s_nth_eq), cases n with n', case nat.zero { suffices : (b * g.h + a) / b = g.h + a / b, by simpa [squash_gcf, s_nth_eq, convergent_eq_conts_a_div_conts_b, (continuants_recurrence_aux s_nth_eq zeroth_continuant_aux_eq_one_zero first_continuant_aux_eq_h_one)], calc (b * g.h + a) / b = b * g.h / b + a / b : by ring -- requires `field` rather than `division_ring` ... = g.h + a / b : by rw (mul_div_cancel_left _ b_ne_zero) }, case nat.succ { obtain ⟨⟨pa, pb⟩, s_n'th_eq⟩ : βˆƒ gp_n', g.s.nth n' = some gp_n' := g.s.ge_stable n'.le_succ s_nth_eq, -- Notations let g' := squash_gcf g (n' + 1), set pred_conts := g.continuants_aux (n' + 1) with succ_n'th_conts_aux_eq, set ppred_conts := g.continuants_aux n' with n'th_conts_aux_eq, let pA := pred_conts.a, let pB := pred_conts.b, let ppA := ppred_conts.a, let ppB := ppred_conts.b, set pred_conts' := g'.continuants_aux (n' + 1) with succ_n'th_conts_aux_eq', set ppred_conts' := g'.continuants_aux n' with n'th_conts_aux_eq', let pA' := pred_conts'.a, let pB' := pred_conts'.b, let ppA' := ppred_conts'.a, let ppB' := ppred_conts'.b, -- first compute the convergent of the squashed gcf have : g'.convergents (n' + 1) = ((pb + a / b) * pA' + pa * ppA') / ((pb + a / b) * pB' + pa * ppB'), { have : g'.s.nth n' = some ⟨pa, pb + a / b⟩, { simpa only [squash_nth_gcf] using (squash_seq_nth_of_not_terminated s_n'th_eq s_nth_eq) }, rw [convergent_eq_conts_a_div_conts_b, (continuants_recurrence_aux this n'th_conts_aux_eq'.symm succ_n'th_conts_aux_eq'.symm)], }, rw this, -- then compute the convergent of the original gcf by recursively unfolding the continuants -- computation twice have : g.convergents (n' + 2) = (b * (pb * pA + pa * ppA) + a * pA) / (b * (pb * pB + pa * ppB) + a * pB), { -- use the recurrence once have : g.continuants_aux (n' + 2) = ⟨pb * pA + pa * ppA, pb * pB + pa * ppB⟩ := continuants_aux_recurrence s_n'th_eq n'th_conts_aux_eq.symm succ_n'th_conts_aux_eq.symm, -- and a second time rw [convergent_eq_conts_a_div_conts_b, (continuants_recurrence_aux s_nth_eq succ_n'th_conts_aux_eq.symm this)] }, rw this, suffices : ((pb + a / b) * pA + pa * ppA) / ((pb + a / b) * pB + pa * ppB) = (b * (pb * pA + pa * ppA) + a * pA) / (b * (pb * pB + pa * ppB) + a * pB), { obtain ⟨eq1, eq2, eq3, eq4⟩ : pA' = pA ∧ pB' = pB ∧ ppA' = ppA ∧ ppB' = ppB, { simp [*, (continuants_aux_eq_continuants_aux_squash_gcf_of_le $ le_refl $ n' + 1).symm, (continuants_aux_eq_continuants_aux_squash_gcf_of_le n'.le_succ).symm] }, symmetry, simpa only [eq1, eq2, eq3, eq4, mul_div_cancel _ b_ne_zero] }, field_simp [b_ne_zero], congr' 1; ring } } end end squash /-- Shows that the recurrence relation (`convergents`) and direct evaluation (`convergents'`) of the gcf coincide at position `n` if the sequence of fractions contains strictly positive values only. Requiring positivity of all values is just one possible condition to obtain this result. For example, the dual - sequences with strictly negative values only - would also work. In practice, one most commonly deals with (regular) continued fractions, which satisfy the positivity criterion required here. The analogous result for them (see `continued_fractions.convergents_eq_convergents`) hence follows directly from this theorem. -/ theorem convergents_eq_convergents' [linear_ordered_field K] (s_pos : βˆ€ {gp : gcf.pair K} {m : β„•}, m < n β†’ g.s.nth m = some gp β†’ 0 < gp.a ∧ 0 < gp.b) : g.convergents n = g.convergents' n := begin induction n with n IH generalizing g, case nat.zero { simp }, case nat.succ { let g' := squash_gcf g n, -- first replace the rhs with the squashed computation suffices : g.convergents (n + 1) = g'.convergents' n, by rwa [succ_nth_convergent'_eq_squash_gcf_nth_convergent'], cases decidable.em (terminated_at g n) with terminated_at_n not_terminated_at_n, { have g'_eq_g : g' = g, from squash_gcf_eq_self_of_terminated terminated_at_n, have : βˆ€ ⦃gp m⦄, m < n β†’ g.s.nth m = some gp β†’ 0 < gp.a ∧ 0 < gp.b, by { assume _ _ m_lt_n s_mth_eq, exact (s_pos (nat.lt.step m_lt_n) s_mth_eq) }, rw [(convergents_stable_of_terminated n.le_succ terminated_at_n), g'_eq_g, (IH this)] }, { suffices : g.convergents (n + 1) = g'.convergents n, by -- invoke the IH for the squashed gcf { have : βˆ€ ⦃gp' m⦄, m < n β†’ g'.s.nth m = some gp' β†’ 0 < gp'.a ∧ 0 < gp'.b, by { assume gp' m m_lt_n s_mth_eq', -- case distinction on m + 1 = n or m + 1 < n cases m_lt_n with n succ_m_lt_n, { -- the difficult case at the squashed position: we first obtain the values from -- the sequence obtain ⟨gp_succ_m, s_succ_mth_eq⟩ : βˆƒ gp_succ_m, g.s.nth (m + 1) = some gp_succ_m, from option.ne_none_iff_exists'.mp not_terminated_at_n, obtain ⟨gp_m, mth_s_eq⟩ : βˆƒ gp_m, g.s.nth m = some gp_m, from g.s.ge_stable m.le_succ s_succ_mth_eq, -- we then plug them into the recurrence suffices : 0 < gp_m.a ∧ 0 < gp_m.b + gp_succ_m.a / gp_succ_m.b, by { have : g'.s.nth m = some ⟨gp_m.a, gp_m.b + gp_succ_m.a / gp_succ_m.b⟩, from squash_seq_nth_of_not_terminated mth_s_eq s_succ_mth_eq, have : gp' = ⟨gp_m.a, gp_m.b + gp_succ_m.a / gp_succ_m.b⟩, by cc, rwa this }, split, { exact (s_pos (nat.lt.step m_lt_n) mth_s_eq).left }, { have : 0 < gp_m.b, from (s_pos (nat.lt.step m_lt_n) mth_s_eq).right, have : 0 < gp_succ_m.a / gp_succ_m.b, by { have : 0 < gp_succ_m.a ∧ 0 < gp_succ_m.b, from s_pos (lt_add_one $ m + 1) s_succ_mth_eq, exact (div_pos this.left this.right) }, linarith } }, { -- the easy case: before the squashed position, nothing changes have : g.s.nth m = some gp', by { have : g'.s.nth m = g.s.nth m, from squash_gcf_nth_of_lt succ_m_lt_n, rwa this at s_mth_eq' }, exact s_pos (nat.lt.step $ nat.lt.step succ_m_lt_n) this } }, rwa [(IH this).symm] }, -- now the result follows from the fact that the convergents coincide at the squashed position -- as established in `succ_nth_convergent_eq_squash_gcf_nth_convergent`. have : βˆ€ ⦃b⦄, g.partial_denominators.nth n = some b β†’ b β‰  0, by { assume b nth_part_denom_eq, obtain ⟨gp, s_nth_eq, ⟨refl⟩⟩ : βˆƒ gp, g.s.nth n = some gp ∧ gp.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, exact (ne_of_lt (s_pos (lt_add_one n) s_nth_eq).right).symm }, exact succ_nth_convergent_eq_squash_gcf_nth_convergent this } } end end generalized_continued_fraction namespace continued_fraction open generalized_continued_fraction as gcf open simple_continued_fraction as scf open continued_fraction as cf /-- Shows that the recurrence relation (`convergents`) and direct evaluation (`convergents'`) of a (regular) continued fraction coincide. -/ theorem convergents_eq_convergents' [linear_ordered_field K] {c : cf K} : (↑c : gcf K).convergents = (↑c : gcf K).convergents' := begin ext n, apply gcf.convergents_eq_convergents', assume gp m m_lt_n s_nth_eq, split, { have : gp.a = 1, from (c : scf K).property m gp.a (gcf.part_num_eq_s_a s_nth_eq), simp only [zero_lt_one, this] }, { exact (c.property m gp.b $ gcf.part_denom_eq_s_b s_nth_eq) } end end continued_fraction
551a953cce7838e59334dfd9072622cc25158312
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/compact_open_auto.lean
24d2ca54ace62a4a6a68ac8b7d55433f5478ea3d
[]
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
2,621
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton Type of continuous maps and the compact-open topology on them. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.subset_properties import Mathlib.topology.continuous_map import Mathlib.tactic.tidy import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib namespace continuous_map def compact_open.gen {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²] (s : set Ξ±) (u : set Ξ²) : set (continuous_map Ξ± Ξ²) := set_of fun (f : continuous_map Ξ± Ξ²) => ⇑f '' s βŠ† u -- The compact-open topology on the space of continuous maps Ξ± β†’ Ξ². protected instance compact_open {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²] : topological_space (continuous_map Ξ± Ξ²) := topological_space.generate_from (set_of fun (m : set (continuous_map Ξ± Ξ²)) => βˆƒ (s : set Ξ±), βˆƒ (hs : is_compact s), βˆƒ (u : set Ξ²), βˆƒ (hu : is_open u), m = sorry) def induced {Ξ± : Type u_1} {Ξ² : Type u_2} {Ξ³ : Type u_3} [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³] {g : Ξ² β†’ Ξ³} (hg : continuous g) (f : continuous_map Ξ± Ξ²) : continuous_map Ξ± Ξ³ := mk (g ∘ ⇑f) /-- C(Ξ±, -) is a functor. -/ theorem continuous_induced {Ξ± : Type u_1} {Ξ² : Type u_2} {Ξ³ : Type u_3} [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³] {g : Ξ² β†’ Ξ³} (hg : continuous g) : continuous (induced hg) := sorry def ev (Ξ± : Type u_1) (Ξ² : Type u_2) [topological_space Ξ±] [topological_space Ξ²] (p : continuous_map Ξ± Ξ² Γ— Ξ±) : Ξ² := coe_fn (prod.fst p) (prod.snd p) -- The evaluation map C(Ξ±, Ξ²) Γ— Ξ± β†’ Ξ² is continuous if Ξ± is locally compact. theorem continuous_ev {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²] [locally_compact_space Ξ±] : continuous (ev Ξ± Ξ²) := sorry def coev (Ξ± : Type u_1) (Ξ² : Type u_2) [topological_space Ξ±] [topological_space Ξ²] (b : Ξ²) : continuous_map Ξ± (Ξ² Γ— Ξ±) := mk fun (a : Ξ±) => (b, a) theorem image_coev {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²] {y : Ξ²} (s : set Ξ±) : ⇑(coev Ξ± Ξ² y) '' s = set.prod (singleton y) s := sorry -- The coevaluation map Ξ² β†’ C(Ξ±, Ξ² Γ— Ξ±) is continuous (always). theorem continuous_coev {Ξ± : Type u_1} {Ξ² : Type u_2} [topological_space Ξ±] [topological_space Ξ²] : continuous (coev Ξ± Ξ²) := sorry end Mathlib
5c2b83a9268675081953d5507a4f44480ee3ce63
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebra/direct_limit.lean
7ade971ce2a4a6d5682a1ad2b2cfcefcf2e3efc2
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
25,237
lean
/- Copyright (c) 2019 Kenny Lau, Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes Direct limit of modules, abelian groups, rings, and fields. See Atiyah-Macdonald PP.32-33, Matsumura PP.269-270 Generalizes the notion of "union", or "gluing", of incomparable modules over the same ring, or incomparable abelian groups, or rings, or fields. It is constructed as a quotient of the free module (for the module case) or quotient of the free commutative ring (for the ring case) instead of a quotient of the disjoint union so as to make the operations (addition etc.) "computable". -/ import ring_theory.free_comm_ring universes u v w u₁ open submodule variables {R : Type u} [ring R] variables {ΞΉ : Type v} [nonempty ΞΉ] variables [decidable_eq ΞΉ] [directed_order ΞΉ] variables (G : ΞΉ β†’ Type w) [Ξ  i, decidable_eq (G i)] /-- A directed system is a functor from the category (directed poset) to another category. This is used for abelian groups and rings and fields because their maps are not bundled. See module.directed_system -/ class directed_system (f : Ξ  i j, i ≀ j β†’ G i β†’ G j) : Prop := (map_self [] : βˆ€ i x h, f i i h x = x) (map_map [] : βˆ€ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) namespace module variables [Ξ  i, add_comm_group (G i)] [Ξ  i, module R (G i)] /-- A directed system is a functor from the category (directed poset) to the category of R-modules. -/ class directed_system (f : Ξ  i j, i ≀ j β†’ G i β†’β‚—[R] G j) : Prop := (map_self [] : βˆ€ i x h, f i i h x = x) (map_map [] : βˆ€ i j k hij hjk x, f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x) variables (f : Ξ  i j, i ≀ j β†’ G i β†’β‚—[R] G j) [directed_system G f] /-- The direct limit of a directed system is the modules glued together along the maps. -/ def direct_limit : Type (max v w) := (span R $ { a | βˆƒ (i j) (H : i ≀ j) x, direct_sum.lof R ΞΉ G i x - direct_sum.lof R ΞΉ G j (f i j H x) = a }).quotient namespace direct_limit instance : add_comm_group (direct_limit G f) := quotient.add_comm_group _ instance : semimodule R (direct_limit G f) := quotient.semimodule _ variables (R ΞΉ) /-- The canonical map from a component to the direct limit. -/ def of (i) : G i β†’β‚—[R] direct_limit G f := (mkq _).comp $ direct_sum.lof R ΞΉ G i variables {R ΞΉ G f} @[simp] lemma of_f {i j hij x} : (of R ΞΉ G f j (f i j hij x)) = of R ΞΉ G f i x := eq.symm $ (submodule.quotient.eq _).2 $ subset_span ⟨i, j, hij, x, rfl⟩ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of (z : direct_limit G f) : βˆƒ i x, of R ΞΉ G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ΞΉ, quotient.induction_on' z $ Ξ» z, direct_sum.induction_on z ⟨ind, 0, linear_map.map_zero _⟩ (Ξ» i x, ⟨i, x, rfl⟩) (Ξ» p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x + f j k hjk y, by rw [linear_map.map_add, of_f, of_f, ihx, ihy]; refl⟩) @[elab_as_eliminator] protected theorem induction_on {C : direct_limit G f β†’ Prop} (z : direct_limit G f) (ih : βˆ€ i x, C (of R ΞΉ G f i x)) : C z := let ⟨i, x, h⟩ := exists_of z in h β–Έ ih i x variables {P : Type u₁} [add_comm_group P] [module R P] (g : Ξ  i, G i β†’β‚—[R] P) variables (Hg : βˆ€ i j hij x, g j (f i j hij x) = g i x) include Hg variables (R ΞΉ G f) /-- The universal property of the direct limit: maps from the components to another module that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f β†’β‚—[R] P := liftq _ (direct_sum.to_module R ΞΉ P g) (span_le.2 $ Ξ» a ⟨i, j, hij, x, hx⟩, by rw [← hx, mem_coe, linear_map.sub_mem_ker_iff, direct_sum.to_module_lof, direct_sum.to_module_lof, Hg]) variables {R ΞΉ G f} omit Hg lemma lift_of {i} (x) : lift R ΞΉ G f g Hg (of R ΞΉ G f i x) = g i x := direct_sum.to_module_lof R _ _ theorem lift_unique (F : direct_limit G f β†’β‚—[R] P) (x) : F x = lift R ΞΉ G f (Ξ» i, F.comp $ of R ΞΉ G f i) (Ξ» i j hij x, by rw [linear_map.comp_apply, of_f]; refl) x := direct_limit.induction_on x $ Ξ» i x, by rw lift_of; refl section totalize open_locale classical variables (G f) noncomputable def totalize : Ξ  i j, G i β†’β‚—[R] G j := Ξ» i j, if h : i ≀ j then f i j h else 0 variables {G f} lemma totalize_apply (i j x) : totalize G f i j x = if h : i ≀ j then f i j h x else 0 := if h : i ≀ j then by dsimp only [totalize]; rw [dif_pos h, dif_pos h] else by dsimp only [totalize]; rw [dif_neg h, dif_neg h, linear_map.zero_apply] end totalize lemma to_module_totalize_of_le {x : direct_sum ΞΉ G} {i j : ΞΉ} (hij : i ≀ j) (hx : βˆ€ k ∈ x.support, k ≀ i) : direct_sum.to_module R ΞΉ (G j) (Ξ» k, totalize G f k j) x = f i j hij (direct_sum.to_module R ΞΉ (G i) (Ξ» k, totalize G f k i) x) := begin rw [← @dfinsupp.sum_single ΞΉ G _ _ _ x], unfold dfinsupp.sum, simp only [linear_map.map_sum], refine finset.sum_congr rfl (Ξ» k hk, _), rw direct_sum.single_eq_lof R k (x k), simp [totalize_apply, hx k hk, le_trans (hx k hk) hij, directed_system.map_map f] end lemma of.zero_exact_aux {x : direct_sum ΞΉ G} (H : submodule.quotient.mk x = (0 : direct_limit G f)) : βˆƒ j, (βˆ€ k ∈ x.support, k ≀ j) ∧ direct_sum.to_module R ΞΉ (G j) (Ξ» i, totalize G f i j) x = (0 : G j) := nonempty.elim (by apply_instance) $ assume ind : ΞΉ, span_induction ((quotient.mk_eq_zero _).1 H) (Ξ» x ⟨i, j, hij, y, hxy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, begin clear_, subst hxy, split, { intros i0 hi0, rw [dfinsupp.mem_support_iff, dfinsupp.sub_apply, ← direct_sum.single_eq_lof, ← direct_sum.single_eq_lof, dfinsupp.single_apply, dfinsupp.single_apply] at hi0, split_ifs at hi0 with hi hj hj, { rwa hi at hik }, { rwa hi at hik }, { rwa hj at hjk }, exfalso, apply hi0, rw sub_zero }, simp [linear_map.map_sub, totalize_apply, hik, hjk, directed_system.map_map f, direct_sum.apply_eq_component, direct_sum.component.of], end⟩) ⟨ind, Ξ» _ h, (finset.not_mem_empty _ h).elim, linear_map.map_zero _⟩ (Ξ» x y ⟨i, hi, hxi⟩ ⟨j, hj, hyj⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, Ξ» l hl, (finset.mem_union.1 (dfinsupp.support_add hl)).elim (Ξ» hl, le_trans (hi _ hl) hik) (Ξ» hl, le_trans (hj _ hl) hjk), by simp [linear_map.map_add, hxi, hyj, to_module_totalize_of_le hik hi, to_module_totalize_of_le hjk hj]⟩) (Ξ» a x ⟨i, hi, hxi⟩, ⟨i, Ξ» k hk, hi k (dfinsupp.support_smul hk), by simp [linear_map.map_smul, hxi]⟩) /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact {i x} (H : of R ΞΉ G f i x = 0) : βˆƒ j hij, f i j hij x = (0 : G j) := let ⟨j, hj, hxj⟩ := of.zero_exact_aux H in if hx0 : x = 0 then ⟨i, le_refl _, by simp [hx0]⟩ else have hij : i ≀ j, from hj _ $ by simp [direct_sum.apply_eq_component, hx0], ⟨j, hij, by simpa [totalize_apply, hij] using hxj⟩ end direct_limit end module namespace add_comm_group variables [Ξ  i, add_comm_group (G i)] /-- The direct limit of a directed system is the abelian groups glued together along the maps. -/ def direct_limit (f : Ξ  i j, i ≀ j β†’ G i β†’ G j) [Ξ  i j hij, is_add_group_hom (f i j hij)] [directed_system G f] : Type* := @module.direct_limit β„€ _ ΞΉ _ _ _ G _ _ _ (Ξ» i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) ⟨directed_system.map_self f, directed_system.map_map f⟩ namespace direct_limit variables (f : Ξ  i j, i ≀ j β†’ G i β†’ G j) variables [Ξ  i j hij, is_add_group_hom (f i j hij)] [directed_system G f] lemma directed_system : module.directed_system G (Ξ» i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) := ⟨directed_system.map_self f, directed_system.map_map f⟩ local attribute [instance] directed_system instance : add_comm_group (direct_limit G f) := module.direct_limit.add_comm_group G (Ξ» i j hij, (add_monoid_hom.of $f i j hij).to_int_linear_map) /-- The canonical map from a component to the direct limit. -/ def of (i) : G i β†’ direct_limit G f := module.direct_limit.of β„€ ΞΉ G (Ξ» i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) i variables {G f} instance of.is_add_group_hom (i) : is_add_group_hom (of G f i) := linear_map.is_add_group_hom _ @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := module.direct_limit.of_f @[simp] lemma of_zero (i) : of G f i 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma of_add (i x y) : of G f i (x + y) = of G f i x + of G f i y := is_add_hom.map_add _ _ _ @[simp] lemma of_neg (i x) : of G f i (-x) = -of G f i x := is_add_group_hom.map_neg _ _ @[simp] lemma of_sub (i x y) : of G f i (x - y) = of G f i x - of G f i y := is_add_group_hom.map_sub _ _ _ @[elab_as_eliminator] protected theorem induction_on {C : direct_limit G f β†’ Prop} (z : direct_limit G f) (ih : βˆ€ i x, C (of G f i x)) : C z := module.direct_limit.induction_on z ih /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ theorem of.zero_exact (i x) (h : of G f i x = 0) : βˆƒ j hij, f i j hij x = 0 := module.direct_limit.of.zero_exact h variables (P : Type u₁) [add_comm_group P] variables (g : Ξ  i, G i β†’ P) [Ξ  i, is_add_group_hom (g i)] variables (Hg : βˆ€ i j hij x, g j (f i j hij x) = g i x) variables (G f) /-- The universal property of the direct limit: maps from the components to another abelian group that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f β†’ P := module.direct_limit.lift β„€ ΞΉ G (Ξ» i j hij, (add_monoid_hom.of $ f i j hij).to_int_linear_map) (Ξ» i, (add_monoid_hom.of $ g i).to_int_linear_map) Hg variables {G f} instance lift.is_add_group_hom : is_add_group_hom (lift G f P g Hg) := linear_map.is_add_group_hom _ @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := module.direct_limit.lift_of _ _ _ @[simp] lemma lift_zero : lift G f P g Hg 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma lift_add (x y) : lift G f P g Hg (x + y) = lift G f P g Hg x + lift G f P g Hg y := is_add_hom.map_add _ _ _ @[simp] lemma lift_neg (x) : lift G f P g Hg (-x) = -lift G f P g Hg x := is_add_group_hom.map_neg _ _ @[simp] lemma lift_sub (x y) : lift G f P g Hg (x - y) = lift G f P g Hg x - lift G f P g Hg y := is_add_group_hom.map_sub _ _ _ lemma lift_unique (F : direct_limit G f β†’ P) [is_add_group_hom F] (x) : F x = @lift _ _ _ _ G _ _ f _ _ P _ (Ξ» i x, F $ of G f i x) (Ξ» i, is_add_group_hom.comp _ _) (Ξ» i j hij x, by dsimp; rw of_f) x := direct_limit.induction_on x $ Ξ» i x, by rw lift_of end direct_limit end add_comm_group namespace ring variables [Ξ  i, comm_ring (G i)] variables (f : Ξ  i j, i ≀ j β†’ G i β†’ G j) variables [Ξ  i j hij, is_ring_hom (f i j hij)] variables [directed_system G f] open free_comm_ring /-- The direct limit of a directed system is the rings glued together along the maps. -/ def direct_limit : Type (max v w) := (ideal.span { a | (βˆƒ i j H x, of (⟨j, f i j H x⟩ : Ξ£ i, G i) - of ⟨i, x⟩ = a) ∨ (βˆƒ i, of (⟨i, 1⟩ : Ξ£ i, G i) - 1 = a) ∨ (βˆƒ i x y, of (⟨i, x + y⟩ : Ξ£ i, G i) - (of ⟨i, x⟩ + of ⟨i, y⟩) = a) ∨ (βˆƒ i x y, of (⟨i, x * y⟩ : Ξ£ i, G i) - (of ⟨i, x⟩ * of ⟨i, y⟩) = a) }).quotient namespace direct_limit instance : comm_ring (direct_limit G f) := ideal.quotient.comm_ring _ instance : ring (direct_limit G f) := comm_ring.to_ring _ /-- The canonical map from a component to the direct limit. -/ def of (i) (x : G i) : direct_limit G f := ideal.quotient.mk _ $ of ⟨i, x⟩ variables {G f} instance of.is_ring_hom (i) : is_ring_hom (of G f i) := { map_one := ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inl ⟨i, rfl⟩, map_mul := Ξ» x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inr ⟨i, x, y, rfl⟩, map_add := Ξ» x y, ideal.quotient.eq.2 $ subset_span $ or.inr $ or.inr $ or.inl ⟨i, x, y, rfl⟩ } @[simp] lemma of_f {i j} (hij) (x) : of G f j (f i j hij x) = of G f i x := ideal.quotient.eq.2 $ subset_span $ or.inl ⟨i, j, hij, x, rfl⟩ @[simp] lemma of_zero (i) : of G f i 0 = 0 := is_ring_hom.map_zero _ @[simp] lemma of_one (i) : of G f i 1 = 1 := is_ring_hom.map_one _ @[simp] lemma of_add (i x y) : of G f i (x + y) = of G f i x + of G f i y := is_ring_hom.map_add _ @[simp] lemma of_neg (i x) : of G f i (-x) = -of G f i x := is_ring_hom.map_neg _ @[simp] lemma of_sub (i x y) : of G f i (x - y) = of G f i x - of G f i y := is_ring_hom.map_sub _ @[simp] lemma of_mul (i x y) : of G f i (x * y) = of G f i x * of G f i y := is_ring_hom.map_mul _ @[simp] lemma of_pow (i x) (n : β„•) : of G f i (x ^ n) = of G f i x ^ n := is_semiring_hom.map_pow _ _ _ /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of (z : direct_limit G f) : βˆƒ i x, of G f i x = z := nonempty.elim (by apply_instance) $ assume ind : ΞΉ, quotient.induction_on' z $ Ξ» x, free_abelian_group.induction_on x ⟨ind, 0, of_zero ind⟩ (Ξ» s, multiset.induction_on s ⟨ind, 1, of_one ind⟩ (Ξ» a s ih, let ⟨i, x⟩ := a, ⟨j, y, hs⟩ := ih, ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x * f j k hjk y, by rw [of_mul, of_f, of_f, hs]; refl⟩)) (Ξ» s ⟨i, x, ih⟩, ⟨i, -x, by rw [of_neg, ih]; refl⟩) (Ξ» p q ⟨i, x, ihx⟩ ⟨j, y, ihy⟩, let ⟨k, hik, hjk⟩ := directed_order.directed i j in ⟨k, f i k hik x + f j k hjk y, by rw [of_add, of_f, of_f, ihx, ihy]; refl⟩) @[elab_as_eliminator] theorem induction_on {C : direct_limit G f β†’ Prop} (z : direct_limit G f) (ih : βˆ€ i x, C (of G f i x)) : C z := let ⟨i, x, hx⟩ := exists_of z in hx β–Έ ih i x section of_zero_exact open_locale classical variables (G f) lemma of.zero_exact_aux2 {x : free_comm_ring Ξ£ i, G i} {s t} (hxs : is_supported x s) {j k} (hj : βˆ€ z : Ξ£ i, G i, z ∈ s β†’ z.1 ≀ j) (hk : βˆ€ z : Ξ£ i, G i, z ∈ t β†’ z.1 ≀ k) (hjk : j ≀ k) (hst : s βŠ† t) : f j k hjk (lift (Ξ» ix : s, f ix.1.1 j (hj ix ix.2) ix.1.2) (restriction s x)) = lift (Ξ» ix : t, f ix.1.1 k (hk ix ix.2) ix.1.2) (restriction t x) := begin refine ring.in_closure.rec_on hxs _ _ _ _, { rw [restriction_one, lift_one, is_ring_hom.map_one (f j k hjk), restriction_one, lift_one] }, { rw [restriction_neg, restriction_one, lift_neg, lift_one, is_ring_hom.map_neg (f j k hjk), is_ring_hom.map_one (f j k hjk), restriction_neg, restriction_one, lift_neg, lift_one] }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [restriction_mul, lift_mul, is_ring_hom.map_mul (f j k hjk), ih, restriction_mul, lift_mul, restriction_of, dif_pos hps, lift_of, restriction_of, dif_pos (hst hps), lift_of], dsimp only, rw directed_system.map_map f, refl }, { rintros x y ihx ihy, rw [restriction_add, lift_add, is_ring_hom.map_add (f j k hjk), ihx, ihy, restriction_add, lift_add] } end variables {G f} lemma of.zero_exact_aux {x : free_comm_ring Ξ£ i, G i} (H : ideal.quotient.mk _ x = (0 : direct_limit G f)) : βˆƒ j s, βˆƒ H : (βˆ€ k : Ξ£ i, G i, k ∈ s β†’ k.1 ≀ j), is_supported x s ∧ lift (Ξ» ix : s, f ix.1.1 j (H ix ix.2) ix.1.2) (restriction s x) = (0 : G j) := begin refine span_induction (ideal.quotient.eq_zero_iff_mem.1 H) _ _ _ _, { rintros x (⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩), { refine ⟨j, {⟨i, x⟩, ⟨j, f i j hij x⟩}, _, is_supported_sub (is_supported_of.2 $ or.inr rfl) (is_supported_of.2 $ or.inl rfl), _⟩, { rintros k (rfl | ⟨rfl | _⟩), exact hij, refl }, { rw [restriction_sub, lift_sub, restriction_of, dif_pos, restriction_of, dif_pos, lift_of, lift_of], dsimp only, rw directed_system.map_map f, exact sub_self _, exacts [or.inr rfl, or.inl rfl] } }, { refine ⟨i, {⟨i, 1⟩}, _, is_supported_sub (is_supported_of.2 rfl) is_supported_one, _⟩, { rintros k (rfl|h), refl }, { rw [restriction_sub, lift_sub, restriction_of, dif_pos, restriction_one, lift_of, lift_one], dsimp only, rw [is_ring_hom.map_one (f i i _), sub_self], exacts [_inst_7 i i _, rfl] } }, { refine ⟨i, {⟨i, x+y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_add (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [restriction_sub, restriction_add, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, lift_sub, lift_add, lift_of, lift_of, lift_of], dsimp only, rw is_ring_hom.map_add (f i i _), exact sub_self _, exacts [or.inl rfl, by apply_instance, or.inr (or.inr rfl), or.inr (or.inl rfl)] } }, { refine ⟨i, {⟨i, x*y⟩, ⟨i, x⟩, ⟨i, y⟩}, _, is_supported_sub (is_supported_of.2 $ or.inl rfl) (is_supported_mul (is_supported_of.2 $ or.inr $ or.inl rfl) (is_supported_of.2 $ or.inr $ or.inr rfl)), _⟩, { rintros k (rfl | ⟨rfl | ⟨rfl | hk⟩⟩); refl }, { rw [restriction_sub, restriction_mul, restriction_of, restriction_of, restriction_of, dif_pos, dif_pos, dif_pos, lift_sub, lift_mul, lift_of, lift_of, lift_of], dsimp only, rw is_ring_hom.map_mul (f i i _), exacts [sub_self _, or.inl rfl, by apply_instance, or.inr (or.inr rfl), or.inr (or.inl rfl)] } } }, { refine nonempty.elim (by apply_instance) (assume ind : ΞΉ, _), refine ⟨ind, βˆ…, Ξ» _, false.elim, is_supported_zero, _⟩, rw [restriction_zero, lift_zero] }, { rintros x y ⟨i, s, hi, hxs, ihs⟩ ⟨j, t, hj, hyt, iht⟩, rcases directed_order.directed i j with ⟨k, hik, hjk⟩, have : βˆ€ z : Ξ£ i, G i, z ∈ s βˆͺ t β†’ z.1 ≀ k, { rintros z (hz | hz), exact le_trans (hi z hz) hik, exact le_trans (hj z hz) hjk }, refine ⟨k, s βˆͺ t, this, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hyt $ set.subset_union_right s t), _⟩, { rw [restriction_add, lift_add, ← of.zero_exact_aux2 G f hxs hi this hik (set.subset_union_left s t), ← of.zero_exact_aux2 G f hyt hj this hjk (set.subset_union_right s t), ihs, is_ring_hom.map_zero (f i k hik), iht, is_ring_hom.map_zero (f j k hjk), zero_add] } }, { rintros x y ⟨j, t, hj, hyt, iht⟩, rw smul_eq_mul, rcases exists_finset_support x with ⟨s, hxs⟩, rcases (s.image sigma.fst).exists_le with ⟨i, hi⟩, rcases directed_order.directed i j with ⟨k, hik, hjk⟩, have : βˆ€ z : Ξ£ i, G i, z ∈ ↑s βˆͺ t β†’ z.1 ≀ k, { rintros z (hz | hz), exact le_trans (hi z.1 $ finset.mem_image.2 ⟨z, hz, rfl⟩) hik, exact le_trans (hj z hz) hjk }, refine ⟨k, ↑s βˆͺ t, this, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left ↑s t) (is_supported_upwards hyt $ set.subset_union_right ↑s t), _⟩, rw [restriction_mul, lift_mul, ← of.zero_exact_aux2 G f hyt hj this hjk (set.subset_union_right ↑s t), iht, is_ring_hom.map_zero (f j k hjk), mul_zero] } end /-- A component that corresponds to zero in the direct limit is already zero in some bigger module in the directed system. -/ lemma of.zero_exact {i x} (hix : of G f i x = 0) : βˆƒ j, βˆƒ hij : i ≀ j, f i j hij x = 0 := let ⟨j, s, H, hxs, hx⟩ := of.zero_exact_aux hix in have hixs : (⟨i, x⟩ : Ξ£ i, G i) ∈ s, from is_supported_of.1 hxs, ⟨j, H ⟨i, x⟩ hixs, by rw [restriction_of, dif_pos hixs, lift_of] at hx; exact hx⟩ end of_zero_exact /-- If the maps in the directed system are injective, then the canonical maps from the components to the direct limits are injective. -/ theorem of_injective (hf : βˆ€ i j hij, function.injective (f i j hij)) (i) : function.injective (of G f i) := begin suffices : βˆ€ x, of G f i x = 0 β†’ x = 0, { intros x y hxy, rw ← sub_eq_zero_iff_eq, apply this, rw [is_ring_hom.map_sub (of G f i), hxy, sub_self] }, intros x hx, rcases of.zero_exact hx with ⟨j, hij, hfx⟩, apply hf i j hij, rw [hfx, is_ring_hom.map_zero (f i j hij)] end variables (P : Type u₁) [comm_ring P] variables (g : Ξ  i, G i β†’ P) [Ξ  i, is_ring_hom (g i)] variables (Hg : βˆ€ i j hij x, g j (f i j hij x) = g i x) include Hg open free_comm_ring variables (G f) /-- The universal property of the direct limit: maps from the components to another ring that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. We don't use this function as the canonical form because Lean 3 fails to automatically coerce it to a function; use `lift` instead. -/ def lift_hom : direct_limit G f β†’+* P := ideal.quotient.lift _ (free_comm_ring.lift_hom $ Ξ» x, g x.1 x.2) begin suffices : ideal.span _ ≀ ideal.comap (free_comm_ring.lift_hom (Ξ» (x : Ξ£ (i : ΞΉ), G i), g (x.fst) (x.snd))) βŠ₯, { intros x hx, exact (mem_bot P).1 (this hx) }, rw ideal.span_le, intros x hx, rw [mem_coe, ideal.mem_comap, mem_bot], rcases hx with ⟨i, j, hij, x, rfl⟩ | ⟨i, rfl⟩ | ⟨i, x, y, rfl⟩ | ⟨i, x, y, rfl⟩; simp only [coe_lift_hom, lift_sub, lift_of, Hg, lift_one, lift_add, lift_mul, is_ring_hom.map_one (g i), is_ring_hom.map_add (g i), is_ring_hom.map_mul (g i), sub_self] end /-- The universal property of the direct limit: maps from the components to another ring that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f β†’ P := lift_hom G f P g Hg instance lift_is_ring_hom : is_ring_hom (lift G f P g Hg) := (lift_hom G f P g Hg).is_ring_hom variables {G f} omit Hg @[simp] lemma lift_of (i x) : lift G f P g Hg (of G f i x) = g i x := free_comm_ring.lift_of _ _ @[simp] lemma lift_zero : lift G f P g Hg 0 = 0 := (lift_hom G f P g Hg).map_zero @[simp] lemma lift_one : lift G f P g Hg 1 = 1 := (lift_hom G f P g Hg).map_one @[simp] lemma lift_add (x y) : lift G f P g Hg (x + y) = lift G f P g Hg x + lift G f P g Hg y := (lift_hom G f P g Hg).map_add x y @[simp] lemma lift_neg (x) : lift G f P g Hg (-x) = -lift G f P g Hg x := (lift_hom G f P g Hg).map_neg x @[simp] lemma lift_sub (x y) : lift G f P g Hg (x - y) = lift G f P g Hg x - lift G f P g Hg y := (lift_hom G f P g Hg).map_sub x y @[simp] lemma lift_mul (x y) : lift G f P g Hg (x * y) = lift G f P g Hg x * lift G f P g Hg y := (lift_hom G f P g Hg).map_mul x y @[simp] lemma lift_pow (x) (n : β„•) : lift G f P g Hg (x ^ n) = lift G f P g Hg x ^ n := (lift_hom G f P g Hg).map_pow x n local attribute [instance, priority 100] is_ring_hom.comp theorem lift_unique (F : direct_limit G f β†’ P) [is_ring_hom F] (x) : F x = lift G f P (Ξ» i x, F $ of G f i x) (Ξ» i j hij x, by rw [of_f]) x := direct_limit.induction_on x $ Ξ» i x, by rw lift_of end direct_limit end ring namespace field variables [Ξ  i, field (G i)] variables (f : Ξ  i j, i ≀ j β†’ G i β†’ G j) [Ξ  i j hij, is_ring_hom (f i j hij)] variables [directed_system G f] namespace direct_limit instance nontrivial : nontrivial (ring.direct_limit G f) := ⟨⟨0, 1, nonempty.elim (by apply_instance) $ assume i : ΞΉ, begin change (0 : ring.direct_limit G f) β‰  1, rw ← ring.direct_limit.of_one, intros H, rcases ring.direct_limit.of.zero_exact H.symm with ⟨j, hij, hf⟩, rw is_ring_hom.map_one (f i j hij) at hf, exact one_ne_zero hf end ⟩⟩ theorem exists_inv {p : ring.direct_limit G f} : p β‰  0 β†’ βˆƒ y, p * y = 1 := ring.direct_limit.induction_on p $ Ξ» i x H, ⟨ring.direct_limit.of G f i (x⁻¹), by erw [← ring.direct_limit.of_mul, mul_inv_cancel (assume h : x = 0, H $ by rw [h, ring.direct_limit.of_zero]), ring.direct_limit.of_one]⟩ section open_locale classical noncomputable def inv (p : ring.direct_limit G f) : ring.direct_limit G f := if H : p = 0 then 0 else classical.some (direct_limit.exists_inv G f H) protected theorem mul_inv_cancel {p : ring.direct_limit G f} (hp : p β‰  0) : p * inv G f p = 1 := by rw [inv, dif_neg hp, classical.some_spec (direct_limit.exists_inv G f hp)] protected theorem inv_mul_cancel {p : ring.direct_limit G f} (hp : p β‰  0) : inv G f p * p = 1 := by rw [_root_.mul_comm, direct_limit.mul_inv_cancel G f hp] protected noncomputable def field : field (ring.direct_limit G f) := { inv := inv G f, mul_inv_cancel := Ξ» p, direct_limit.mul_inv_cancel G f, inv_zero := dif_pos rfl, .. ring.direct_limit.comm_ring G f, .. direct_limit.nontrivial G f } end end direct_limit end field
309fcebb03f8dfdd180310d06ebf64b4c83dd14a
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/tests/lean/run/rewrite10.lean
38597d1308468d9e3394780dbd87d03b91d05374
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
818
lean
import data.nat open nat section variables (a b c d e : nat) theorem T (H1 : a = b) (H2 : b = c + 1) (H3 : c = d) (H4 : e = 1 + d) : a = e := by rewrite ⟨H1, H2, H3, add.comm, -H4⟩ end example (x y : β„•) : (x + y) * (x + y) = x * x + y * x + x * y + y * y := by rewrite ⟨*mul.left_distrib, *mul.right_distrib, -add.assoc⟩ definition even (a : nat) := βˆƒb, a = 2*b theorem even_plus_even {a b : nat} (H1 : even a) (H2 : even b) : even (a + b) := exists.elim H1 (fun (w1 : nat) (Hw1 : a = 2*w1), exists.elim H2 (fun (w2 : nat) (Hw2 : b = 2*w2), exists.intro (w1 + w2) begin rewrite ⟨Hw1, Hw2, mul.left_distrib⟩ end)) theorem T2 (a b c : nat) (H1 : a = b) (H2 : b = c + 1) : a β‰  0 := calc a = succ c : by rewrite ⟨H1, H2, add_one⟩ ... β‰  0 : succ_ne_zero c
5ffbc90f578f4a02a99ed83bfc07fa5629759215
c76cc4eaee3c806716844e49b5175747d1aa170a
/src/solutions_sheet_two.lean
7771ede67a2b555e1b1bd067a73988a7dd7b460a
[]
no_license
ImperialCollegeLondon/M40002
0fb55848adbb0d8bc4a65ca5d7ed6edd18764c28
a499db70323bd5ccae954c680ec9afbf15ffacca
refs/heads/master
1,674,878,059,748
1,607,624,828,000
1,607,624,828,000
309,696,750
3
0
null
null
null
null
UTF-8
Lean
false
false
13,458
lean
import data.real.basic import data.nat.choose.sum -- binomial theorem import data.real.ereal import data.pnat.basic -- namespace problem_sheet_two section Q2 /-! # Q2 -/ /- 2. Fix nonempty sets S_n βŠ† R, n= 1,2,3,.... Prove that sup{sup S1,sup S2,sup S3,...} = sup(⋃_{n=1}^{infty} S_n), in the sense that if either exists then so does the other, and they are equal. -/ /- Let's first answer a better question with fewer restrictions, using extended reals. Then Sup {Sup (S_i) : i ∈ I} = Sup (⋃_{i ∈ I} S_i) is *always* true -/ example (I : Type) (S : I β†’ set (ereal)) : Sup (set.range (Ξ» i, Sup (S i))) = Sup (⋃ i, S i) := begin apply le_antisymm, { rw Sup_le_iff, rintro - ⟨i, rfl⟩, dsimp only, refine Sup_le_Sup _, exact set.subset_Union S i }, { rw Sup_le_iff, rintros x ⟨-, ⟨i, rfl⟩, (hix : x ∈ S i)⟩, apply le_trans (le_Sup hix), apply le_Sup _, use i } end lemma exists_lub (S : set ℝ) : S.nonempty ∧ (upper_bounds S).nonempty β†’ (βˆƒ B, is_lub S B) := begin rintros ⟨h1, h2⟩, cases real.exists_sup S h1 h2 with B hB, use B, split, { apply (hB B).1, refl }, { intros x hx, rw hB, exact hx } end -- "All the S_i have a sup and the set {sup S1, sup S2, ...} has a sup, if and -- only if the union of the S_i has a sup" theorem Q2a (S : β„•+ β†’ set ℝ) (hS : βˆ€ i : β„•+, (S i).nonempty) : (βˆ€ n : β„•+, βˆƒ B, is_lub (S n) B) ∧ (βˆƒ B, is_lub (set.range (Ξ» i, Sup (S i))) B) ↔ βˆƒ B, is_lub (⋃ i, S i) B := begin split, { rintro ⟨h1, B, hB1, hB2⟩, apply exists_lub, cases hS 37 with x hx, use [x, S 37, 37, hx], use B, rintros y ⟨-, ⟨i, rfl⟩, (hiY : y ∈ S i)⟩, specialize hB1 ⟨i, rfl⟩, refine le_trans _ hB1, apply real.le_Sup _ _ hiY, rcases h1 i with ⟨C, hC1, hC2⟩, use C, exact hC1 }, { rintro ⟨B, hB1, hB2⟩, split, { intro n, apply exists_lub, use hS n, use B, apply upper_bounds_mono_set _ hB1, exact set.subset_Union S n }, { apply exists_lub, split, { apply set.range_nonempty }, { use B, rintro - ⟨i, rfl⟩, dsimp only, rw real.Sup_le _ (hS i), { intros z hz, apply hB1, use [S i, i, hz] }, { use B, intros z hz, apply hB1, use [S i, i, hz] } } } } end -- assuming both sides make sense, prove the sups are equal theorem Q2b (S : β„•+ β†’ set ℝ) (hS : βˆ€ i : β„•+, (S i).nonempty) (hLHS: βˆ€ n : β„•+, βˆƒ B, is_lub (S n) B) (hLHS' : βˆƒ B, is_lub (set.range (Ξ» i, Sup (S i))) B) (hRHS : βˆƒ B, is_lub (⋃ i, S i) B) : Sup (set.range (Ξ» i, Sup (S i))) = Sup (⋃ i, S i) := begin -- suffices to prove LHS ≀ RHS and RHS ≀ LHS apply le_antisymm, { -- to prove Sup ≀ something, suffices to prove all elements are ≀ it rw real.Sup_le, rintro - ⟨j, rfl⟩, dsimp only, -- so it suffices to prove Sup (S j) ≀ Sup (⋃_i S i) rw real.Sup_le, -- so it even suffices to prove every element of S j is ≀ the Sup intros x hx, -- but this is clear because the elements are in the set apply real.le_Sup, swap, use [S j, j, hx], -- now just check that all sets were nonempty and had least upper bounds, -- this follows from our assumptions. { rcases hRHS with ⟨B, hB1, hB2⟩, use B, exact hB1 }, { exact hS j}, { rcases hLHS j with ⟨B, hB1, hB2⟩, use B, exact hB1 }, { apply set.range_nonempty }, { rcases hLHS' with ⟨B, hB1, hB2⟩, use B, exact hB1 } }, { -- to prove Sup ≀ somthing, suffices to prove all elements are ≀ it rw real.Sup_le, -- so assume z is in one of the S i's, call it S j rintro z ⟨-, ⟨j, rfl⟩, (hzj : z ∈ S j)⟩, -- then z ≀ Sup (S j) apply le_trans (real.le_Sup _ _ hzj), -- so it's certainly ≀ Sup of a set containing Sup (S j) apply real.le_Sup, -- now tidy up { rcases hLHS' with ⟨B, hB1, hB2⟩, use B, exact hB1 }, { use j }, { rcases hLHS j with ⟨B, hB1, hB2⟩, use B, exact hB1 }, { cases hS 37 with x hx, use [x, S 37, 37, hx], }, { rcases hRHS with ⟨B, hB1, hB2⟩, use B, exact hB1 } } end end Q2 /-! # Q3 Take bounded, nonempty `S, T βŠ† ℝ`. Define `S + T := { s + t : s ∈ S, t ∈ T}`. Prove `sup(S+T) = sup(S)+ sup(T)` -/ theorem is_lub_def {S : set ℝ} {a : ℝ} : is_lub S a ↔ a ∈ upper_bounds S ∧ βˆ€ x, x ∈ upper_bounds S β†’ a ≀ x := begin refl end -- #check mem_upper_bounds -- a ∈ upper_bounds S ↔ βˆ€ x, x ∈ S β†’ x ≀ a --example (P Q : Prop) : P β†’ Q ↔ Β¬ Q β†’ Β¬ P := --by library_search theorem useful_lemma {S : set ℝ} {a : ℝ} (haS : is_lub S a) (t : ℝ) (ht : t < a) : βˆƒ s, s ∈ S ∧ t < s := begin rw is_lub_def at haS, cases haS with haS1 haS2, specialize haS2 t, replace haS2 := mt haS2, push_neg at haS2, specialize haS2 ht, rw mem_upper_bounds at haS2, push_neg at haS2, exact haS2, end theorem problem_sheet_two.Q3 (S T : set ℝ) (a b : ℝ) : is_lub S a β†’ is_lub T b β†’ is_lub (S + T) (a + b) := begin intros hSa hTb, rw is_lub_def, split, { rw mem_upper_bounds, intro x, intro hx, rcases hx with ⟨s, t, hsS, htT, rfl⟩, rw is_lub_def at hSa hTb, rcases hSa with ⟨ha1, ha2⟩, rcases hTb with ⟨hb1, hb2⟩, rw mem_upper_bounds at ha1 hb1, specialize ha1 s hsS, specialize hb1 t htT, linarith, }, { intro x, intro hx, rw mem_upper_bounds at hx, by_contra, push_neg at h, set Ξ΅ := a + b - x with hΞ΅, have hΞ΅2 : 0 < Ξ΅, linarith, set a' := a - Ξ΅/2 with ha', set b' := b - Ξ΅/2 with hb', rcases useful_lemma hSa a' (by linarith) with ⟨s', hs', hs'2⟩, rcases useful_lemma hTb b' (by linarith) with ⟨t', ht', ht'2⟩, specialize hx (s' + t') ⟨s', t', hs', ht', rfl⟩, linarith, } end /-! # Q4 Fix `a ∈ (0,∞)` and `n : β„•`. We will prove `βˆƒ x : ℝ, x^n = a`. -/ section Q4 noncomputable theory section one -- this first section, a and n are going to be variables variables {a : ℝ} (ha : 0 < a) {n : β„•} (hn : 0 < n) include ha hn /- Note: We do things in a slightly different order to the question on the sheet, because the way it's set up on the sheet, `x` is defined to be `Sup(S_a)` very early on, which technically forces us to prove that `1/x` is `Sup(S_{1/a})` -- this is unnecessary with the approach below. I broke this question into five "parts". -/ /- 2) For `Ξ΅ ∈ (0,1)` and arbitrary `x β‰₯ 0` show `(x+Ξ΅)ⁿ ≀ x^n + Ξ΅[(x + 1)ⁿ βˆ’ xⁿ].` (Hint: multiply out.) -/ theorem part2 {x : ℝ} (x_nonneg : 0 ≀ x) (Ξ΅ : ℝ) (hΞ΅0 : 0 < Ξ΅) (hΞ΅1 : Ξ΅ < 1) : (x + Ξ΅)^n ≀ x^n + Ξ΅ * ((x + 1)^n - x^n) := begin rw [ add_pow, add_pow ], simp_rw [one_pow, mul_one], rw [finset.sum_range_succ, nat.sub_self, pow_zero, mul_one], rw [nat.choose_self, nat.cast_one, mul_one], apply add_le_add_left, rw [finset.sum_range_succ, nat.choose_self, nat.cast_one, mul_one], rw [add_sub_cancel', finset.mul_sum], apply finset.sum_le_sum, intros i hi, rw [finset.mem_range, nat.lt_iff_add_one_le, le_iff_exists_add] at hi, -- rcases hi with ⟨c, rfl⟩, -- rcases bug? cases hi with c hc, have hni : n - i = c + 1, omega, rw [hni, mul_comm (x ^ i), mul_assoc, pow_succ, mul_comm Ξ΅, mul_assoc], apply mul_le_of_le_one_left, { apply mul_nonneg (le_of_lt hΞ΅0), apply mul_nonneg (pow_nonneg x_nonneg i), norm_cast, simp }, { apply pow_le_one; linarith } end /- 3) Hence show that if `x β‰₯ 0` and `xⁿ < a` then `βˆƒ Ξ΅ ∈ (0,1)` such that `(x+Ξ΅)ⁿ < a.` (*) -/ theorem part3 {x : ℝ} (x_nonneg : 0 ≀ x) (h : x ^ n < a) : βˆƒ Ξ΅ : ℝ, 0 < Ξ΅ ∧ Ξ΅ < 1 ∧ (x+Ξ΅)^n < a := begin set Ξ΅ := min (1 / 2) ((a - x ^ n) / ((x + 1) ^ n - x ^ n) / 2) with hΞ΅, use Ξ΅, have hx1 : 0 < (x + 1) ^ n - x ^ n, rw sub_pos, apply pow_lt_pow_of_lt_left (lt_add_one _) x_nonneg hn, have hΞ΅0 : 0 < Ξ΅, rw [hΞ΅, lt_min_iff], split, { linarith }, refine div_pos _ (by linarith), refine div_pos (by linarith) hx1, use hΞ΅0, have hΞ΅1 : Ξ΅ < 1, suffices : Ξ΅ ≀ 1/2, linarith, rw hΞ΅, exact min_le_left _ _, use hΞ΅1, apply lt_of_le_of_lt (part2 ha hn x_nonneg Ξ΅ hΞ΅0 hΞ΅1), rw ← lt_sub_iff_add_lt', rw ← lt_div_iff hx1, apply lt_of_le_of_lt (min_le_right _ _), apply div_two_lt_of_pos, exact div_pos (by linarith) hx1, end /- 4) If `x > 0` is arbitrary and `xⁿ > a`, deduce from (βˆ—) (i.e. part 3) that `βˆƒ Ξ΅ ∈ (0,1)` such that `(1/x+Ξ΅)ⁿ < 1/a`. (βˆ—βˆ—) Note that here it makes life much easier to have x a variable and not the fixed Sup(S_a); with the approach on the sheet one would have to technical prove that 1/x is Sup(S_{1/a}), which is not necessary with this approach. -/ theorem part4 {x : ℝ} (hx : 0 < x) (h : a < x^n) : βˆƒ Ξ΅ : ℝ, 0 < Ξ΅ ∧ Ξ΅ < 1 ∧ (1/x + Ξ΅)^n < 1/a := begin have h1x_pos : 0 < 1/x, rwa one_div_pos, have h1xa : (1/x)^n < 1/a, rw [div_pow, one_pow], apply div_lt_div_of_lt_left ha h zero_lt_one, exact part3 (one_div_pos.2 ha) hn (le_of_lt h1x_pos) h1xa, end end one section two -- in this section, a and n are going to be fixed parameters parameters {a : ℝ} (ha : 0 < a) {n : β„•} (hn : 0 < n) include ha hn /- 1) Set `Sₐ := {s ∈ [0,∞) : s^n < a}` and show `Sₐ` is nonempty and bounded above, so we may define `x := sup Sₐ` -/ def S := {s : ℝ | 0 ≀ s ∧ s ^ n < a} theorem part1 : (βˆƒ s : ℝ, s ∈ S) ∧ (βˆƒ B : ℝ, βˆ€ s ∈ S, s ≀ B ) := begin split, { use 0, split, { refl }, convert ha, simp [hn] }, { use a + 1, rintro s ⟨hs1, hs2⟩, by_contra hsa, push_neg at hsa, have hs3 : 1 ≀ s, linarith, have hs4 : s ≀ s ^ n, cases n, cases hn, suffices : 1 ≀ s ^ n, convert mul_le_mul (le_refl s) this (by linarith) hs1, { simp }, exact one_le_pow_of_one_le hs3 _, linarith, } end def x := Sup S theorem is_lub_x : is_lub S x := begin cases part1 with nonempty bdd, cases nonempty with x hx, cases bdd with y hy, exact real.is_lub_Sup hx hy, end lemma x_nonneg : 0 ≀ x := begin rcases is_lub_x with ⟨h, -⟩, apply h, split, refl, convert ha, simp [hn], end lemma easy (h : a < x^n) : x β‰  0 := begin intro hx, rw hx at h, suffices : a < 0, linarith, convert h, symmetry, -- todo add simp lemma to mathlib simp [hn], end /- 5) Deduce contradictions from (βˆ—) and (βˆ—βˆ—) to show that `xⁿ = a`. -/ -- lemma le_of_pow_le_pow (n : β„•) (hn : 0 < n) (x y : ℝ) (h : x^n ≀ y^n) : x ≀ y := -- begin -- by_contra hxy, -- push_neg at hxy, -- sorry, -- -- have h2 : pow_lt_pow -- end theorem part5 : x^n = a := begin rcases lt_trichotomy (x^n) a with (hlt | heq | hgt), { exfalso, obtain ⟨Ρ, hΞ΅0, -, hΡ⟩ := part3 ha hn (x_nonneg) hlt, have ZZZ := is_lub_x.1 ⟨_, hΡ⟩, linarith, linarith [x_nonneg] }, { assumption }, { exfalso, have hxpow : 0 < x, rw lt_iff_le_and_ne, exact ⟨x_nonneg, (easy hgt).symm⟩, obtain ⟨Ρ, hΞ΅0, -, hΡ⟩ := part4 ha hn hxpow hgt, have huseful : 0 < 1 / x + Ξ΅, refine add_pos _ hΞ΅0, exact one_div_pos.mpr hxpow, have ha' : a < (1 / (1 / x + Ξ΅)) ^ n, { rw [div_pow, one_pow], rwa lt_one_div _ ha at hΞ΅, apply pow_pos, assumption }, have hproblem : (1 / (1 / x + Ξ΅)) ∈ upper_bounds S, { rintro t ⟨ht0, hta⟩, apply le_of_lt, apply lt_of_pow_lt_pow n, { apply le_of_lt, rwa one_div_pos }, { linarith } }, have ZZZ := is_lub_x.2 hproblem, rw le_one_div at ZZZ, { linarith }, { assumption }, { assumption } } end end two end Q4 section Q6 /-! # Q6 "Do (a) from first principles and then do parts (b)-(g) from (a)" -/ -- We introduce the usual mathematical notation for absolute value local notation `|` x `|` := abs x /- Useful for this one: `unfold`, `split_ifs` if you want to prove from first principles, or guessing the name of the library function if you want to use the library. -/ theorem Q6a (x y : ℝ) : | x + y | ≀ | x | + | y | := begin unfold abs max, split_ifs; linarith end -- all the rest you're supposed to do using Q6a somehow: -- `simp` and `linarith` are useful. theorem Q6b (x y : ℝ) : |x + y| β‰₯ |x| - |y| := begin have h := Q6a (x + y) (-y), simp at h, linarith, end theorem Q6c (x y : ℝ) : |x + y| β‰₯ |y| - |x| := begin have h := Q6a (x + y) (-x), simp at h, linarith, end theorem Q6d (x y : ℝ) : |x - y| β‰₯ | |x| - |y| | := begin show _ ≀ _, rw abs_le, split, { -- |y|<=|x|+|y-x| have h := Q6a x (y-x), simp at h, rw abs_sub, linarith }, { have h := Q6a (x-y) y, simp at h, linarith } end theorem Q6e (x y : ℝ) : |x| ≀ |y| + |x - y| := begin have h := Q6a y (x-y), convert h, ring, end theorem Q6f (x y : ℝ) : |x| β‰₯ |y| - |x - y| := begin have h := Q6a x (y-x), simp at h, rw abs_sub at h, linarith, end theorem Q6g (x y z : ℝ) : |x - y| ≀ |x - z| + |y - z| := begin have h := Q6a (x-z) (z-y), rw abs_sub z y at h, convert h, ring, end end Q6
067382034884a4bba72af24eacd4f212486a9c6d
e61a235b8468b03aee0120bf26ec615c045005d2
/tests/lean/run/parseCore.lean
a6953f6b2cd4b83f0fd1b95e5633b9979a8ea2f0
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
330
lean
import Init.Lean.Parser def test : IO Unit := if System.Platform.isWindows then pure () -- TODO investigate why the following doesn't work on Windows else do env ← Lean.mkEmptyEnvironment; _ ← Lean.Parser.parseFile env (System.mkFilePath ["..", "..", "..", "src", "Init", "Core.lean"]); IO.println "done" #eval test
fc8fac4a0c6378e9321f8905c1734c8d59dcf7ee
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/PrePort.lean
c0fdd880d1fdd980b51cdb1471d8545d82613080
[]
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
191
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import Mathlib.PrePort.Numbers
41253d00d310c3324734d1783f775b0f2a6db916
4727251e0cd73359b15b664c3170e5d754078599
/src/data/set/pointwise.lean
2aee3dc85b08b1d3daf06d7fe792fd2549bb1307
[ "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
57,604
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Floris van Doorn -/ import algebra.module.basic import data.set.finite import group_theory.submonoid.basic /-! # Pointwise operations of sets This file defines pointwise algebraic operations on sets. ## Main declarations For sets `s` and `t` and scalar `a`: * `s * t`: Multiplication, set of all `x * y` where `x ∈ s` and `y ∈ t`. * `s + t`: Addition, set of all `x + y` where `x ∈ s` and `y ∈ t`. * `s⁻¹`: Inversion, set of all `x⁻¹` where `x ∈ s`. * `-s`: Negation, set of all `-x` where `x ∈ s`. * `s / t`: Division, set of all `x / y` where `x ∈ s` and `y ∈ t`. * `s - t`: Subtraction, set of all `x - y` where `x ∈ s` and `y ∈ t`. * `s β€’ t`: Scalar multiplication, set of all `x β€’ y` where `x ∈ s` and `y ∈ t`. * `s +α΅₯ t`: Scalar addition, set of all `x +α΅₯ y` where `x ∈ s` and `y ∈ t`. * `s -α΅₯ t`: Scalar subtraction, set of all `x -α΅₯ y` where `x ∈ s` and `y ∈ t`. * `a β€’ s`: Scaling, set of all `a β€’ x` where `x ∈ s`. * `a +α΅₯ s`: Translation, set of all `a +α΅₯ x` where `x ∈ s`. For `Ξ±` a semigroup/monoid, `set Ξ±` is a semigroup/monoid. As an unfortunate side effect, this means that `n β€’ s`, where `n : β„•`, is ambiguous between pointwise scaling and repeated pointwise addition; the former has `(2 : β„•) β€’ {1, 2} = {2, 4}`, while the latter has `(2 : β„•) β€’ {1, 2} = {2, 3, 4}`. We define `set_semiring Ξ±`, an alias of `set Ξ±`, which we endow with `βˆͺ` as addition and `*` as multiplication. If `Ξ±` is a (commutative) monoid, `set_semiring Ξ±` is a (commutative) semiring. Appropriate definitions and results are also transported to the additive theory via `to_additive`. ## Implementation notes * The following expressions are considered in simp-normal form in a group: `(Ξ» h, h * g) ⁻¹' s`, `(Ξ» h, g * h) ⁻¹' s`, `(Ξ» h, h * g⁻¹) ⁻¹' s`, `(Ξ» h, g⁻¹ * h) ⁻¹' s`, `s * t`, `s⁻¹`, `(1 : set _)` (and similarly for additive variants). Expressions equal to one of these will be simplified. * We put all instances in the locale `pointwise`, so that these instances are not available by default. Note that we do not mark them as reducible (as argued by note [reducible non-instances]) since we expect the locale to be open whenever the instances are actually used (and making the instances reducible changes the behavior of `simp`. ## Tags set multiplication, set addition, pointwise addition, pointwise multiplication, pointwise subtraction -/ open function variables {F Ξ± Ξ² Ξ³ : Type*} namespace set /-! ### `0`/`1` as sets -/ section one variables [has_one Ξ±] {s : set Ξ±} {a : Ξ±} /-- The set `1 : set Ξ±` is defined as `{1}` in locale `pointwise`. -/ @[to_additive "The set `0 : set Ξ±` is defined as `{0}` in locale `pointwise`."] protected def has_one : has_one (set Ξ±) := ⟨{1}⟩ localized "attribute [instance] set.has_one set.has_zero" in pointwise @[to_additive] lemma singleton_one : ({1} : set Ξ±) = 1 := rfl @[simp, to_additive] lemma mem_one : a ∈ (1 : set Ξ±) ↔ a = 1 := iff.rfl @[to_additive] lemma one_mem_one : (1 : Ξ±) ∈ (1 : set Ξ±) := eq.refl _ @[simp, to_additive] lemma one_subset : 1 βŠ† s ↔ (1 : Ξ±) ∈ s := singleton_subset_iff @[to_additive] lemma one_nonempty : (1 : set Ξ±).nonempty := ⟨1, rfl⟩ @[simp, to_additive] lemma image_one {f : Ξ± β†’ Ξ²} : f '' 1 = {f 1} := image_singleton @[to_additive] lemma subset_one_iff_eq : s βŠ† 1 ↔ s = βˆ… ∨ s = 1 := subset_singleton_iff_eq @[to_additive] lemma nonempty.subset_one_iff (h : s.nonempty) : s βŠ† 1 ↔ s = 1 := h.subset_singleton_iff end one /-! ### Set negation/inversion -/ section inv /-- The pointwise inversion of set `s⁻¹` is defined as `{x | x⁻¹ ∈ s}` in locale `pointwise`. It i equal to `{x⁻¹ | x ∈ s}`, see `set.image_inv`. -/ @[to_additive "The pointwise negation of set `-s` is defined as `{x | -x ∈ s}` in locale `pointwise`. It is equal to `{-x | x ∈ s}`, see `set.image_neg`."] protected def has_inv [has_inv Ξ±] : has_inv (set Ξ±) := ⟨preimage has_inv.inv⟩ localized "attribute [instance] set.has_inv set.has_neg" in pointwise section has_inv variables {ΞΉ : Sort*} [has_inv Ξ±] {s t : set Ξ±} {a : Ξ±} @[simp, to_additive] lemma mem_inv : a ∈ s⁻¹ ↔ a⁻¹ ∈ s := iff.rfl @[simp, to_additive] lemma inv_preimage : has_inv.inv ⁻¹' s = s⁻¹ := rfl @[simp, to_additive] lemma inv_empty : (βˆ… : set Ξ±)⁻¹ = βˆ… := rfl @[simp, to_additive] lemma inv_univ : (univ : set Ξ±)⁻¹ = univ := rfl @[simp, to_additive] lemma inter_inv : (s ∩ t)⁻¹ = s⁻¹ ∩ t⁻¹ := preimage_inter @[simp, to_additive] lemma union_inv : (s βˆͺ t)⁻¹ = s⁻¹ βˆͺ t⁻¹ := preimage_union @[simp, to_additive] lemma Inter_inv (s : ΞΉ β†’ set Ξ±) : (β‹‚ i, s i)⁻¹ = β‹‚ i, (s i)⁻¹ := preimage_Inter @[simp, to_additive] lemma Union_inv (s : ΞΉ β†’ set Ξ±) : (⋃ i, s i)⁻¹ = ⋃ i, (s i)⁻¹ := preimage_Union @[simp, to_additive] lemma compl_inv : (sᢜ)⁻¹ = (s⁻¹)ᢜ := preimage_compl end has_inv section has_involutive_inv variables [has_involutive_inv Ξ±] {s t : set Ξ±} {a : Ξ±} @[to_additive] lemma inv_mem_inv : a⁻¹ ∈ s⁻¹ ↔ a ∈ s := by simp only [mem_inv, inv_inv] @[simp, to_additive] lemma nonempty_inv : s⁻¹.nonempty ↔ s.nonempty := inv_involutive.surjective.nonempty_preimage @[to_additive] lemma nonempty.inv (h : s.nonempty) : s⁻¹.nonempty := nonempty_inv.2 h @[to_additive] lemma finite.inv (hs : finite s) : finite s⁻¹ := hs.preimage $ inv_injective.inj_on _ @[simp, to_additive] lemma image_inv : has_inv.inv '' s = s⁻¹ := congr_fun (image_eq_preimage_of_inverse inv_involutive.left_inverse inv_involutive.right_inverse) _ @[simp, to_additive] instance : has_involutive_inv (set Ξ±) := { inv := has_inv.inv, inv_inv := Ξ» s, by { simp only [← inv_preimage, preimage_preimage, inv_inv, preimage_id'] } } @[simp, to_additive] lemma inv_subset_inv : s⁻¹ βŠ† t⁻¹ ↔ s βŠ† t := (equiv.inv Ξ±).surjective.preimage_subset_preimage_iff @[to_additive] lemma inv_subset : s⁻¹ βŠ† t ↔ s βŠ† t⁻¹ := by { rw [← inv_subset_inv, inv_inv] } @[simp, to_additive] lemma inv_singleton (a : Ξ±) : ({a} : set Ξ±)⁻¹ = {a⁻¹} := by rw [←image_inv, image_singleton] open mul_opposite @[to_additive] lemma image_op_inv : op '' s⁻¹ = (op '' s)⁻¹ := by simp_rw [←image_inv, image_comm op_inv] end has_involutive_inv end inv open_locale pointwise /-! ### Set addition/multiplication -/ section has_mul variables {ΞΉ : Sort*} {ΞΊ : ΞΉ β†’ Sort*} [has_mul Ξ±] {s s₁ sβ‚‚ t t₁ tβ‚‚ u : set Ξ±} {a b : Ξ±} /-- The pointwise multiplication of sets `s * t` and `t` is defined as `{x * y | x ∈ s, y ∈ t}` in locale `pointwise`. -/ @[to_additive "The pointwise addition of sets `s + t` is defined as `{x + y | x ∈ s, y ∈ t}` in locale `pointwise`."] protected def has_mul : has_mul (set Ξ±) := ⟨image2 (*)⟩ localized "attribute [instance] set.has_mul set.has_add" in pointwise @[simp, to_additive] lemma image2_mul : image2 has_mul.mul s t = s * t := rfl @[to_additive] lemma mem_mul : a ∈ s * t ↔ βˆƒ x y, x ∈ s ∧ y ∈ t ∧ x * y = a := iff.rfl @[to_additive] lemma mul_mem_mul : a ∈ s β†’ b ∈ t β†’ a * b ∈ s * t := mem_image2_of_mem @[to_additive add_image_prod] lemma image_mul_prod : (Ξ» x : Ξ± Γ— Ξ±, x.fst * x.snd) '' s Γ—Λ’ t = s * t := image_prod _ @[simp, to_additive] lemma empty_mul : βˆ… * s = βˆ… := image2_empty_left @[simp, to_additive] lemma mul_empty : s * βˆ… = βˆ… := image2_empty_right @[simp, to_additive] lemma mul_eq_empty : s * t = βˆ… ↔ s = βˆ… ∨ t = βˆ… := image2_eq_empty_iff @[simp, to_additive] lemma mul_nonempty : (s * t).nonempty ↔ s.nonempty ∧ t.nonempty := image2_nonempty_iff @[to_additive] lemma nonempty.mul : s.nonempty β†’ t.nonempty β†’ (s * t).nonempty := nonempty.image2 @[to_additive] lemma nonempty.of_mul_left : (s * t).nonempty β†’ s.nonempty := nonempty.of_image2_left @[to_additive] lemma nonempty.of_mul_right : (s * t).nonempty β†’ t.nonempty := nonempty.of_image2_right @[simp, to_additive] lemma mul_singleton : s * {b} = (* b) '' s := image2_singleton_right @[simp, to_additive] lemma singleton_mul : {a} * t = ((*) a) '' t := image2_singleton_left @[simp, to_additive] lemma singleton_mul_singleton : ({a} : set Ξ±) * {b} = {a * b} := image2_singleton @[to_additive, mono] lemma mul_subset_mul : s₁ βŠ† t₁ β†’ sβ‚‚ βŠ† tβ‚‚ β†’ s₁ * sβ‚‚ βŠ† t₁ * tβ‚‚ := image2_subset @[to_additive] lemma mul_subset_mul_left : t₁ βŠ† tβ‚‚ β†’ s * t₁ βŠ† s * tβ‚‚ := image2_subset_left @[to_additive] lemma mul_subset_mul_right : s₁ βŠ† sβ‚‚ β†’ s₁ * t βŠ† sβ‚‚ * t := image2_subset_right @[to_additive] lemma mul_subset_iff : s * t βŠ† u ↔ βˆ€ (x ∈ s) (y ∈ t), x * y ∈ u := image2_subset_iff attribute [mono] add_subset_add @[to_additive] lemma union_mul : (s₁ βˆͺ sβ‚‚) * t = s₁ * t βˆͺ sβ‚‚ * t := image2_union_left @[to_additive] lemma mul_union : s * (t₁ βˆͺ tβ‚‚) = s * t₁ βˆͺ s * tβ‚‚ := image2_union_right @[to_additive] lemma inter_mul_subset : (s₁ ∩ sβ‚‚) * t βŠ† s₁ * t ∩ (sβ‚‚ * t) := image2_inter_subset_left @[to_additive] lemma mul_inter_subset : s * (t₁ ∩ tβ‚‚) βŠ† s * t₁ ∩ (s * tβ‚‚) := image2_inter_subset_right @[to_additive] lemma Union_mul_left_image : (⋃ a ∈ s, ((*) a) '' t) = s * t := Union_image_left _ @[to_additive] lemma Union_mul_right_image : (⋃ a ∈ t, (* a) '' s) = s * t := Union_image_right _ @[to_additive] lemma Union_mul (s : ΞΉ β†’ set Ξ±) (t : set Ξ±) : (⋃ i, s i) * t = ⋃ i, s i * t := image2_Union_left _ _ _ @[to_additive] lemma mul_Union (s : set Ξ±) (t : ΞΉ β†’ set Ξ±) : s * (⋃ i, t i) = ⋃ i, s * t i := image2_Union_right _ _ _ @[to_additive] lemma Unionβ‚‚_mul (s : Ξ  i, ΞΊ i β†’ set Ξ±) (t : set Ξ±) : (⋃ i j, s i j) * t = ⋃ i j, s i j * t := image2_Unionβ‚‚_left _ _ _ @[to_additive] lemma mul_Unionβ‚‚ (s : set Ξ±) (t : Ξ  i, ΞΊ i β†’ set Ξ±) : s * (⋃ i j, t i j) = ⋃ i j, s * t i j := image2_Unionβ‚‚_right _ _ _ @[to_additive] lemma Inter_mul_subset (s : ΞΉ β†’ set Ξ±) (t : set Ξ±) : (β‹‚ i, s i) * t βŠ† β‹‚ i, s i * t := image2_Inter_subset_left _ _ _ @[to_additive] lemma mul_Inter_subset (s : set Ξ±) (t : ΞΉ β†’ set Ξ±) : s * (β‹‚ i, t i) βŠ† β‹‚ i, s * t i := image2_Inter_subset_right _ _ _ @[to_additive] lemma Interβ‚‚_mul_subset (s : Ξ  i, ΞΊ i β†’ set Ξ±) (t : set Ξ±) : (β‹‚ i j, s i j) * t βŠ† β‹‚ i j, s i j * t := image2_Interβ‚‚_subset_left _ _ _ @[to_additive] lemma mul_Interβ‚‚_subset (s : set Ξ±) (t : Ξ  i, ΞΊ i β†’ set Ξ±) : s * (β‹‚ i j, t i j) βŠ† β‹‚ i j, s * t i j := image2_Interβ‚‚_subset_right _ _ _ @[to_additive] lemma finite.mul : finite s β†’ finite t β†’ finite (s * t) := finite.image2 _ /-- Multiplication preserves finiteness. -/ @[to_additive "Addition preserves finiteness."] def fintype_mul [decidable_eq Ξ±] (s t : set Ξ±) [fintype s] [fintype t] : fintype (s * t : set Ξ±) := set.fintype_image2 _ _ _ /-- Under `[has_mul M]`, the `singleton` map from `M` to `set M` as a `mul_hom`, that is, a map which preserves multiplication. -/ @[to_additive "Under `[has_add A]`, the `singleton` map from `A` to `set A` as an `add_hom`, that is, a map which preserves addition.", simps] def singleton_mul_hom : Ξ± β†’β‚™* (set Ξ±) := { to_fun := singleton, map_mul' := Ξ» a b, singleton_mul_singleton.symm } open mul_opposite @[simp, to_additive] lemma image_op_mul : op '' (s * t) = op '' t * op '' s := image_image2_antidistrib op_mul end has_mul /-! ### Set subtraction/division -/ section has_div variables {ΞΉ : Sort*} {ΞΊ : ΞΉ β†’ Sort*} [has_div Ξ±] {s s₁ sβ‚‚ t t₁ tβ‚‚ u : set Ξ±} {a b : Ξ±} /-- The pointwise division of sets `s / t` is defined as `{x / y | x ∈ s, y ∈ t}` in locale `pointwise`. -/ @[to_additive "The pointwise subtraction of sets `s - t` is defined as `{x - y | x ∈ s, y ∈ t}` in locale `pointwise`."] protected def has_div : has_div (set Ξ±) := ⟨image2 (/)⟩ localized "attribute [instance] set.has_div set.has_sub" in pointwise @[simp, to_additive] lemma image2_div : image2 has_div.div s t = s / t := rfl @[to_additive] lemma mem_div : a ∈ s / t ↔ βˆƒ x y, x ∈ s ∧ y ∈ t ∧ x / y = a := iff.rfl @[to_additive] lemma div_mem_div : a ∈ s β†’ b ∈ t β†’ a / b ∈ s / t := mem_image2_of_mem @[to_additive add_image_prod] lemma image_div_prod : (Ξ» x : Ξ± Γ— Ξ±, x.fst / x.snd) '' s Γ—Λ’ t = s / t := image_prod _ @[simp, to_additive] lemma empty_div : βˆ… / s = βˆ… := image2_empty_left @[simp, to_additive] lemma div_empty : s / βˆ… = βˆ… := image2_empty_right @[simp, to_additive] lemma div_eq_empty : s / t = βˆ… ↔ s = βˆ… ∨ t = βˆ… := image2_eq_empty_iff @[simp, to_additive] lemma div_nonempty : (s / t).nonempty ↔ s.nonempty ∧ t.nonempty := image2_nonempty_iff @[to_additive] lemma nonempty.div : s.nonempty β†’ t.nonempty β†’ (s / t).nonempty := nonempty.image2 @[to_additive] lemma nonempty.of_div_left : (s / t).nonempty β†’ s.nonempty := nonempty.of_image2_left @[to_additive] lemma nonempty.of_div_right : (s / t).nonempty β†’ t.nonempty := nonempty.of_image2_right @[simp, to_additive] lemma div_singleton : s / {b} = (/ b) '' s := image2_singleton_right @[simp, to_additive] lemma singleton_div : {a} / t = ((/) a) '' t := image2_singleton_left @[simp, to_additive] lemma singleton_div_singleton : ({a} : set Ξ±) / {b} = {a / b} := image2_singleton @[to_additive, mono] lemma div_subset_div : s₁ βŠ† t₁ β†’ sβ‚‚ βŠ† tβ‚‚ β†’ s₁ / sβ‚‚ βŠ† t₁ / tβ‚‚ := image2_subset @[to_additive] lemma div_subset_div_left : t₁ βŠ† tβ‚‚ β†’ s / t₁ βŠ† s / tβ‚‚ := image2_subset_left @[to_additive] lemma div_subset_div_right : s₁ βŠ† sβ‚‚ β†’ s₁ / t βŠ† sβ‚‚ / t := image2_subset_right @[to_additive] lemma div_subset_iff : s / t βŠ† u ↔ βˆ€ (x ∈ s) (y ∈ t), x / y ∈ u := image2_subset_iff attribute [mono] sub_subset_sub @[to_additive] lemma union_div : (s₁ βˆͺ sβ‚‚) / t = s₁ / t βˆͺ sβ‚‚ / t := image2_union_left @[to_additive] lemma div_union : s / (t₁ βˆͺ tβ‚‚) = s / t₁ βˆͺ s / tβ‚‚ := image2_union_right @[to_additive] lemma inter_div_subset : (s₁ ∩ sβ‚‚) / t βŠ† s₁ / t ∩ (sβ‚‚ / t) := image2_inter_subset_left @[to_additive] lemma div_inter_subset : s / (t₁ ∩ tβ‚‚) βŠ† s / t₁ ∩ (s / tβ‚‚) := image2_inter_subset_right @[to_additive] lemma Union_div_left_image : (⋃ a ∈ s, ((/) a) '' t) = s / t := Union_image_left _ @[to_additive] lemma Union_div_right_image : (⋃ a ∈ t, (/ a) '' s) = s / t := Union_image_right _ @[to_additive] lemma Union_div (s : ΞΉ β†’ set Ξ±) (t : set Ξ±) : (⋃ i, s i) / t = ⋃ i, s i / t := image2_Union_left _ _ _ @[to_additive] lemma div_Union (s : set Ξ±) (t : ΞΉ β†’ set Ξ±) : s / (⋃ i, t i) = ⋃ i, s / t i := image2_Union_right _ _ _ @[to_additive] lemma Unionβ‚‚_div (s : Ξ  i, ΞΊ i β†’ set Ξ±) (t : set Ξ±) : (⋃ i j, s i j) / t = ⋃ i j, s i j / t := image2_Unionβ‚‚_left _ _ _ @[to_additive] lemma div_Unionβ‚‚ (s : set Ξ±) (t : Ξ  i, ΞΊ i β†’ set Ξ±) : s / (⋃ i j, t i j) = ⋃ i j, s / t i j := image2_Unionβ‚‚_right _ _ _ @[to_additive] lemma Inter_div_subset (s : ΞΉ β†’ set Ξ±) (t : set Ξ±) : (β‹‚ i, s i) / t βŠ† β‹‚ i, s i / t := image2_Inter_subset_left _ _ _ @[to_additive] lemma div_Inter_subset (s : set Ξ±) (t : ΞΉ β†’ set Ξ±) : s / (β‹‚ i, t i) βŠ† β‹‚ i, s / t i := image2_Inter_subset_right _ _ _ @[to_additive] lemma Interβ‚‚_div_subset (s : Ξ  i, ΞΊ i β†’ set Ξ±) (t : set Ξ±) : (β‹‚ i j, s i j) / t βŠ† β‹‚ i j, s i j / t := image2_Interβ‚‚_subset_left _ _ _ @[to_additive] lemma div_Interβ‚‚_subset (s : set Ξ±) (t : Ξ  i, ΞΊ i β†’ set Ξ±) : s / (β‹‚ i j, t i j) βŠ† β‹‚ i j, s / t i j := image2_Interβ‚‚_subset_right _ _ _ end has_div /-- `set Ξ±` is a `semigroup` under pointwise operations if `Ξ±` is. -/ @[to_additive "`set Ξ±` is an `add_semigroup` under pointwise operations if `Ξ±` is."] protected def semigroup [semigroup Ξ±] : semigroup (set Ξ±) := { mul_assoc := Ξ» _ _ _, image2_assoc mul_assoc, ..set.has_mul } /-- `set Ξ±` is a `comm_semigroup` under pointwise operations if `Ξ±` is. -/ @[to_additive "`set Ξ±` is an `add_comm_semigroup` under pointwise operations if `Ξ±` is."] protected def comm_semigroup [comm_semigroup Ξ±] : comm_semigroup (set Ξ±) := { mul_comm := Ξ» s t, image2_comm mul_comm ..set.semigroup } section mul_one_class variables [mul_one_class Ξ±] /-- `set Ξ±` is a `mul_one_class` under pointwise operations if `Ξ±` is. -/ @[to_additive "`set Ξ±` is an `add_zero_class` under pointwise operations if `Ξ±` is."] protected def mul_one_class : mul_one_class (set Ξ±) := { mul_one := Ξ» s, by { simp only [← singleton_one, mul_singleton, mul_one, image_id'] }, one_mul := Ξ» s, by { simp only [← singleton_one, singleton_mul, one_mul, image_id'] }, ..set.has_one, ..set.has_mul } localized "attribute [instance] set.mul_one_class set.add_zero_class set.semigroup set.add_semigroup set.comm_semigroup set.add_comm_semigroup" in pointwise @[to_additive] lemma subset_mul_left (s : set Ξ±) {t : set Ξ±} (ht : (1 : Ξ±) ∈ t) : s βŠ† s * t := Ξ» x hx, ⟨x, 1, hx, ht, mul_one _⟩ @[to_additive] lemma subset_mul_right {s : set Ξ±} (t : set Ξ±) (hs : (1 : Ξ±) ∈ s) : t βŠ† s * t := Ξ» x hx, ⟨1, x, hs, hx, one_mul _⟩ end mul_one_class section monoid variables [monoid Ξ±] {s t : set Ξ±} {a : Ξ±} /-- `set Ξ±` is a `monoid` under pointwise operations if `Ξ±` is. -/ @[to_additive "`set Ξ±` is an `add_monoid` under pointwise operations if `Ξ±` is."] protected def monoid : monoid (set Ξ±) := { ..set.semigroup, ..set.mul_one_class } localized "attribute [instance] set.monoid set.add_monoid" in pointwise @[to_additive] lemma pow_mem_pow (ha : a ∈ s) : βˆ€ n : β„•, a ^ n ∈ s ^ n | 0 := by { rw pow_zero, exact one_mem_one } | (n + 1) := by { rw pow_succ, exact mul_mem_mul ha (pow_mem_pow _) } @[to_additive] lemma pow_subset_pow (hst : s βŠ† t) : βˆ€ n : β„•, s ^ n βŠ† t ^ n | 0 := by { rw pow_zero, exact subset.rfl } | (n + 1) := by { rw pow_succ, exact mul_subset_mul hst (pow_subset_pow _) } @[to_additive] lemma empty_pow (n : β„•) (hn : n β‰  0) : (βˆ… : set Ξ±) ^ n = βˆ… := by rw [← tsub_add_cancel_of_le (nat.succ_le_of_lt $ nat.pos_of_ne_zero hn), pow_succ, empty_mul] @[to_additive] instance decidable_mem_mul [fintype Ξ±] [decidable_eq Ξ±] [decidable_pred (∈ s)] [decidable_pred (∈ t)] : decidable_pred (∈ s * t) := Ξ» _, decidable_of_iff _ mem_mul.symm @[to_additive] instance decidable_mem_pow [fintype Ξ±] [decidable_eq Ξ±] [decidable_pred (∈ s)] (n : β„•) : decidable_pred (∈ (s ^ n)) := begin induction n with n ih, { simp_rw [pow_zero, mem_one], apply_instance }, { letI := ih, rw pow_succ, apply_instance } end @[simp, to_additive] lemma univ_mul_univ : (univ : set Ξ±) * univ = univ := begin have : βˆ€ x, βˆƒ a b : Ξ±, a * b = x := Ξ» x, ⟨x, 1, mul_one x⟩, simpa only [mem_mul, eq_univ_iff_forall, mem_univ, true_and] end end monoid /-- `set Ξ±` is a `comm_monoid` under pointwise operations if `Ξ±` is. -/ @[to_additive "`set Ξ±` is an `add_comm_monoid` under pointwise operations if `Ξ±` is."] protected def comm_monoid [comm_monoid Ξ±] : comm_monoid (set Ξ±) := { ..set.monoid, ..set.comm_semigroup } localized "attribute [instance] set.comm_monoid set.add_comm_monoid" in pointwise open_locale pointwise section group variables [group Ξ±] {s t : set Ξ±} {a b : Ξ±} /-! Note that `set` is not a `group` because `s / s β‰  1` in general. -/ @[simp, to_additive] lemma image_mul_left : ((*) a) '' t = ((*) a⁻¹) ⁻¹' t := by { rw image_eq_preimage_of_inverse; intro c; simp } @[simp, to_additive] lemma image_mul_right : (* b) '' t = (* b⁻¹) ⁻¹' t := by { rw image_eq_preimage_of_inverse; intro c; simp } @[to_additive] lemma image_mul_left' : (Ξ» b, a⁻¹ * b) '' t = (Ξ» b, a * b) ⁻¹' t := by simp @[to_additive] lemma image_mul_right' : (* b⁻¹) '' t = (* b) ⁻¹' t := by simp @[simp, to_additive] lemma preimage_mul_left_singleton : ((*) a) ⁻¹' {b} = {a⁻¹ * b} := by rw [← image_mul_left', image_singleton] @[simp, to_additive] lemma preimage_mul_right_singleton : (* a) ⁻¹' {b} = {b * a⁻¹} := by rw [← image_mul_right', image_singleton] @[simp, to_additive] lemma preimage_mul_left_one : ((*) a) ⁻¹' 1 = {a⁻¹} := by rw [← image_mul_left', image_one, mul_one] @[simp, to_additive] lemma preimage_mul_right_one : (* b) ⁻¹' 1 = {b⁻¹} := by rw [← image_mul_right', image_one, one_mul] @[to_additive] lemma preimage_mul_left_one' : (Ξ» b, a⁻¹ * b) ⁻¹' 1 = {a} := by simp @[to_additive] lemma preimage_mul_right_one' : (* b⁻¹) ⁻¹' 1 = {b} := by simp @[simp, to_additive] lemma mul_univ (hs : s.nonempty) : s * (univ : set Ξ±) = univ := let ⟨a, ha⟩ := hs in eq_univ_of_forall $ Ξ» b, ⟨a, a⁻¹ * b, ha, trivial, mul_inv_cancel_left _ _⟩ @[simp, to_additive] lemma univ_mul (ht : t.nonempty) : (univ : set Ξ±) * t = univ := let ⟨a, ha⟩ := ht in eq_univ_of_forall $ Ξ» b, ⟨b * a⁻¹, a, trivial, ha, inv_mul_cancel_right _ _⟩ end group @[to_additive] lemma bdd_above_mul [ordered_comm_monoid Ξ±] {A B : set Ξ±} : bdd_above A β†’ bdd_above B β†’ bdd_above (A * B) := begin rintro ⟨bA, hbA⟩ ⟨bB, hbB⟩, use bA * bB, rintro x ⟨xa, xb, hxa, hxb, rfl⟩, exact mul_le_mul' (hbA hxa) (hbB hxb), end open_locale pointwise section big_operators open_locale big_operators variables {ΞΉ : Type*} [comm_monoid Ξ±] /-- The n-ary version of `set.mem_mul`. -/ @[to_additive /-" The n-ary version of `set.mem_add`. "-/] lemma mem_finset_prod (t : finset ΞΉ) (f : ΞΉ β†’ set Ξ±) (a : Ξ±) : a ∈ ∏ i in t, f i ↔ βˆƒ (g : ΞΉ β†’ Ξ±) (hg : βˆ€ {i}, i ∈ t β†’ g i ∈ f i), ∏ i in t, g i = a := begin classical, induction t using finset.induction_on with i is hi ih generalizing a, { simp_rw [finset.prod_empty, set.mem_one], exact ⟨λ h, ⟨λ i, a, Ξ» i, false.elim, h.symm⟩, Ξ» ⟨f, _, hf⟩, hf.symm⟩ }, rw [finset.prod_insert hi, set.mem_mul], simp_rw [finset.prod_insert hi], simp_rw ih, split, { rintro ⟨x, y, hx, ⟨g, hg, rfl⟩, rfl⟩, refine ⟨function.update g i x, Ξ» j hj, _, _⟩, obtain rfl | hj := finset.mem_insert.mp hj, { rw function.update_same, exact hx }, { rw update_noteq (ne_of_mem_of_not_mem hj hi), exact hg hj, }, rw [finset.prod_update_of_not_mem hi, function.update_same], }, { rintro ⟨g, hg, rfl⟩, exact ⟨g i, is.prod g, hg (is.mem_insert_self _), ⟨g, Ξ» i hi, hg (finset.mem_insert_of_mem hi), rfl⟩, rfl⟩ }, end /-- A version of `set.mem_finset_prod` with a simpler RHS for products over a fintype. -/ @[to_additive /-" A version of `set.mem_finset_sum` with a simpler RHS for sums over a fintype. "-/] lemma mem_fintype_prod [fintype ΞΉ] (f : ΞΉ β†’ set Ξ±) (a : Ξ±) : a ∈ ∏ i, f i ↔ βˆƒ (g : ΞΉ β†’ Ξ±) (hg : βˆ€ i, g i ∈ f i), ∏ i, g i = a := by { rw mem_finset_prod, simp } /-- The n-ary version of `set.mul_mem_mul`. -/ @[to_additive /-" The n-ary version of `set.add_mem_add`. "-/] lemma finset_prod_mem_finset_prod (t : finset ΞΉ) (f : ΞΉ β†’ set Ξ±) (g : ΞΉ β†’ Ξ±) (hg : βˆ€ i ∈ t, g i ∈ f i) : ∏ i in t, g i ∈ ∏ i in t, f i := by { rw mem_finset_prod, exact ⟨g, hg, rfl⟩ } /-- The n-ary version of `set.mul_subset_mul`. -/ @[to_additive /-" The n-ary version of `set.add_subset_add`. "-/] lemma finset_prod_subset_finset_prod (t : finset ΞΉ) (f₁ fβ‚‚ : ΞΉ β†’ set Ξ±) (hf : βˆ€ {i}, i ∈ t β†’ f₁ i βŠ† fβ‚‚ i) : ∏ i in t, f₁ i βŠ† ∏ i in t, fβ‚‚ i := begin intro a, rw [mem_finset_prod, mem_finset_prod], rintro ⟨g, hg, rfl⟩, exact ⟨g, Ξ» i hi, hf hi $ hg hi, rfl⟩ end @[to_additive] lemma finset_prod_singleton {M ΞΉ : Type*} [comm_monoid M] (s : finset ΞΉ) (I : ΞΉ β†’ M) : ∏ (i : ΞΉ) in s, ({I i} : set M) = {∏ (i : ΞΉ) in s, I i} := begin letI := classical.dec_eq ΞΉ, refine finset.induction_on s _ _, { simpa }, { intros _ _ H ih, rw [finset.prod_insert H, finset.prod_insert H, ih], simp } end /-! TODO: define `decidable_mem_finset_prod` and `decidable_mem_finset_sum`. -/ end big_operators open_locale pointwise /-- Repeated pointwise addition (not the same as pointwise repeated addition!) of a `finset`. -/ protected def has_nsmul [has_zero Ξ±] [has_add Ξ±] : has_scalar β„• (set Ξ±) := ⟨nsmul_rec⟩ /-- Repeated pointwise multiplication (not the same as pointwise repeated multiplication!) of a `set`. -/ @[to_additive] protected def has_npow [has_one Ξ±] [has_mul Ξ±] : has_pow (set Ξ±) β„• := ⟨λ s n, npow_rec n s⟩ /-- Repeated pointwise addition/subtraction (not the same as pointwise repeated addition/subtraction!) of a `set`. -/ protected def has_zsmul [has_zero Ξ±] [has_add Ξ±] [has_neg Ξ±] : has_scalar β„€ (set Ξ±) := ⟨zsmul_rec⟩ /-- Repeated pointwise multiplication/division (not the same as pointwise repeated multiplication/division!) of a `set`. -/ @[to_additive] protected def has_zpow [has_one Ξ±] [has_mul Ξ±] [has_inv Ξ±] : has_pow (set Ξ±) β„€ := ⟨λ s n, zpow_rec n s⟩ -- TODO: Generalize the duplicated lemmas and instances below to `division_monoid` @[to_additive] protected lemma mul_inv_rev [group Ξ±] (s t : set Ξ±) : (s * t)⁻¹ = t⁻¹ * s⁻¹ := by { simp_rw ←image_inv, exact image_image2_antidistrib mul_inv_rev } protected lemma mul_inv_revβ‚€ [group_with_zero Ξ±] (s t : set Ξ±) : (s * t)⁻¹ = t⁻¹ * s⁻¹ := by { simp_rw ←image_inv, exact image_image2_antidistrib mul_inv_rev } /-- `s / t = s * t⁻¹` for all `s t : set Ξ±` if `a / b = a * b⁻¹` for all `a b : Ξ±`. -/ @[to_additive "`s - t = s + -t` for all `s t : set Ξ±` if `a - b = a + -b` for all `a b : Ξ±`."] protected def div_inv_monoid [group Ξ±] : div_inv_monoid (set Ξ±) := { div_eq_mul_inv := Ξ» s t, by { rw [←image_id (s / t), ←image_inv], exact image_image2_distrib_right div_eq_mul_inv }, ..set.monoid, ..set.has_inv, ..set.has_div } /-- `s / t = s * t⁻¹` for all `s t : set Ξ±` if `a / b = a * b⁻¹` for all `a b : Ξ±`. -/ protected def div_inv_monoid' [group_with_zero Ξ±] : div_inv_monoid (set Ξ±) := { div_eq_mul_inv := Ξ» s t, by { rw [←image_id (s / t), ←image_inv], exact image_image2_distrib_right div_eq_mul_inv }, ..set.monoid, ..set.has_inv, ..set.has_div } localized "attribute [instance] set.has_nsmul set.has_npow set.has_zsmul set.has_zpow set.div_inv_monoid set.div_inv_monoid' set.sub_neg_add_monoid" in pointwise /-! ### Translation/scaling of sets -/ section smul /-- The dilation of set `x β€’ s` is defined as `{x β€’ y | y ∈ s}` in locale `pointwise`. -/ @[to_additive has_vadd_set "The translation of set `x +α΅₯ s` is defined as `{x +α΅₯ y | y ∈ s}` in locale `pointwise`."] protected def has_scalar_set [has_scalar Ξ± Ξ²] : has_scalar Ξ± (set Ξ²) := ⟨λ a, image (has_scalar.smul a)⟩ /-- The pointwise scalar multiplication of sets `s β€’ t` is defined as `{x β€’ y | x ∈ s, y ∈ t}` in locale `pointwise`. -/ @[to_additive has_vadd "The pointwise scalar addition of sets `s +α΅₯ t` is defined as `{x +α΅₯ y | x ∈ s, y ∈ t}` in locale `pointwise`."] protected def has_scalar [has_scalar Ξ± Ξ²] : has_scalar (set Ξ±) (set Ξ²) := ⟨image2 has_scalar.smul⟩ localized "attribute [instance] set.has_scalar_set set.has_scalar" in pointwise localized "attribute [instance] set.has_vadd_set set.has_vadd" in pointwise section has_scalar variables {ΞΉ : Sort*} {ΞΊ : ΞΉ β†’ Sort*} [has_scalar Ξ± Ξ²] {s s₁ sβ‚‚ : set Ξ±} {t t₁ tβ‚‚ u : set Ξ²} {a : Ξ±} {b : Ξ²} @[simp, to_additive] lemma image2_smul : image2 has_scalar.smul s t = s β€’ t := rfl @[to_additive add_image_prod] lemma image_smul_prod : (Ξ» x : Ξ± Γ— Ξ², x.fst β€’ x.snd) '' s Γ—Λ’ t = s β€’ t := image_prod _ @[to_additive] lemma mem_smul : b ∈ s β€’ t ↔ βˆƒ x y, x ∈ s ∧ y ∈ t ∧ x β€’ y = b := iff.rfl @[to_additive] lemma smul_mem_smul : a ∈ s β†’ b ∈ t β†’ a β€’ b ∈ s β€’ t := mem_image2_of_mem @[simp, to_additive] lemma empty_smul : (βˆ… : set Ξ±) β€’ t = βˆ… := image2_empty_left @[simp, to_additive] lemma smul_empty : s β€’ (βˆ… : set Ξ²) = βˆ… := image2_empty_right @[simp, to_additive] lemma smul_eq_empty : s β€’ t = βˆ… ↔ s = βˆ… ∨ t = βˆ… := image2_eq_empty_iff @[simp, to_additive] lemma smul_nonempty : (s β€’ t).nonempty ↔ s.nonempty ∧ t.nonempty := image2_nonempty_iff @[to_additive] lemma nonempty.smul : s.nonempty β†’ t.nonempty β†’ (s β€’ t).nonempty := nonempty.image2 @[to_additive] lemma nonempty.of_smul_left : (s β€’ t).nonempty β†’ s.nonempty := nonempty.of_image2_left @[to_additive] lemma nonempty.of_smul_right : (s β€’ t).nonempty β†’ t.nonempty := nonempty.of_image2_right @[simp, to_additive] lemma smul_singleton : s β€’ {b} = (β€’ b) '' s := image2_singleton_right @[simp, to_additive] lemma singleton_smul : ({a} : set Ξ±) β€’ t = a β€’ t := image2_singleton_left @[simp, to_additive] lemma singleton_smul_singleton : ({a} : set Ξ±) β€’ ({b} : set Ξ²) = {a β€’ b} := image2_singleton @[to_additive, mono] lemma smul_subset_smul : s₁ βŠ† sβ‚‚ β†’ t₁ βŠ† tβ‚‚ β†’ s₁ β€’ t₁ βŠ† sβ‚‚ β€’ tβ‚‚ := image2_subset @[to_additive] lemma smul_subset_smul_left : t₁ βŠ† tβ‚‚ β†’ s β€’ t₁ βŠ† s β€’ tβ‚‚ := image2_subset_left @[to_additive] lemma smul_subset_smul_right : s₁ βŠ† sβ‚‚ β†’ s₁ β€’ t βŠ† sβ‚‚ β€’ t := image2_subset_right @[to_additive] lemma smul_subset_iff : s β€’ t βŠ† u ↔ βˆ€ (a ∈ s) (b ∈ t), a β€’ b ∈ u := image2_subset_iff attribute [mono] vadd_subset_vadd @[to_additive] lemma union_smul : (s₁ βˆͺ sβ‚‚) β€’ t = s₁ β€’ t βˆͺ sβ‚‚ β€’ t := image2_union_left @[to_additive] lemma smul_union : s β€’ (t₁ βˆͺ tβ‚‚) = s β€’ t₁ βˆͺ s β€’ tβ‚‚ := image2_union_right @[to_additive] lemma inter_smul_subset : (s₁ ∩ sβ‚‚) β€’ t βŠ† s₁ β€’ t ∩ sβ‚‚ β€’ t := image2_inter_subset_left @[to_additive] lemma smul_inter_subset : s β€’ (t₁ ∩ tβ‚‚) βŠ† s β€’ t₁ ∩ s β€’ tβ‚‚ := image2_inter_subset_right @[to_additive] lemma Union_smul_left_image : (⋃ a ∈ s, a β€’ t) = s β€’ t := Union_image_left _ @[to_additive] lemma Union_smul_right_image : (⋃ a ∈ t, (β€’ a) '' s) = s β€’ t := Union_image_right _ @[to_additive] lemma Union_smul (s : ΞΉ β†’ set Ξ±) (t : set Ξ²) : (⋃ i, s i) β€’ t = ⋃ i, s i β€’ t := image2_Union_left _ _ _ @[to_additive] lemma smul_Union (s : set Ξ±) (t : ΞΉ β†’ set Ξ²) : s β€’ (⋃ i, t i) = ⋃ i, s β€’ t i := image2_Union_right _ _ _ @[to_additive] lemma Unionβ‚‚_smul (s : Ξ  i, ΞΊ i β†’ set Ξ±) (t : set Ξ²) : (⋃ i j, s i j) β€’ t = ⋃ i j, s i j β€’ t := image2_Unionβ‚‚_left _ _ _ @[to_additive] lemma smul_Unionβ‚‚ (s : set Ξ±) (t : Ξ  i, ΞΊ i β†’ set Ξ²) : s β€’ (⋃ i j, t i j) = ⋃ i j, s β€’ t i j := image2_Unionβ‚‚_right _ _ _ @[to_additive] lemma Inter_smul_subset (s : ΞΉ β†’ set Ξ±) (t : set Ξ²) : (β‹‚ i, s i) β€’ t βŠ† β‹‚ i, s i β€’ t := image2_Inter_subset_left _ _ _ @[to_additive] lemma smul_Inter_subset (s : set Ξ±) (t : ΞΉ β†’ set Ξ²) : s β€’ (β‹‚ i, t i) βŠ† β‹‚ i, s β€’ t i := image2_Inter_subset_right _ _ _ @[to_additive] lemma Interβ‚‚_smul_subset (s : Ξ  i, ΞΊ i β†’ set Ξ±) (t : set Ξ²) : (β‹‚ i j, s i j) β€’ t βŠ† β‹‚ i j, s i j β€’ t := image2_Interβ‚‚_subset_left _ _ _ @[to_additive] lemma smul_Interβ‚‚_subset (s : set Ξ±) (t : Ξ  i, ΞΊ i β†’ set Ξ²) : s β€’ (β‹‚ i j, t i j) βŠ† β‹‚ i j, s β€’ t i j := image2_Interβ‚‚_subset_right _ _ _ @[to_additive] lemma finite.smul : finite s β†’ finite t β†’ finite (s β€’ t) := finite.image2 _ end has_scalar section has_scalar_set variables {ΞΉ : Sort*} {ΞΊ : ΞΉ β†’ Sort*} [has_scalar Ξ± Ξ²] {s t t₁ tβ‚‚ : set Ξ²} {a : Ξ±} {b : Ξ²} {x y : Ξ²} @[simp, to_additive] lemma image_smul : (Ξ» x, a β€’ x) '' t = a β€’ t := rfl @[to_additive] lemma mem_smul_set : x ∈ a β€’ t ↔ βˆƒ y, y ∈ t ∧ a β€’ y = x := iff.rfl @[to_additive] lemma smul_mem_smul_set : b ∈ s β†’ a β€’ b ∈ a β€’ s := mem_image_of_mem _ @[simp, to_additive] lemma smul_set_empty : a β€’ (βˆ… : set Ξ²) = βˆ… := image_empty _ @[simp, to_additive] lemma smul_set_eq_empty : a β€’ s = βˆ… ↔ s = βˆ… := image_eq_empty @[simp, to_additive] lemma smul_set_nonempty : (a β€’ s).nonempty ↔ s.nonempty := nonempty_image_iff @[simp, to_additive] lemma smul_set_singleton : a β€’ ({b} : set Ξ²) = {a β€’ b} := image_singleton @[to_additive] lemma smul_set_mono (h : s βŠ† t) : a β€’ s βŠ† a β€’ t := image_subset _ h @[to_additive] lemma smul_set_union : a β€’ (t₁ βˆͺ tβ‚‚) = a β€’ t₁ βˆͺ a β€’ tβ‚‚ := image_union _ _ _ @[to_additive] lemma smul_set_inter_subset : a β€’ (t₁ ∩ tβ‚‚) βŠ† a β€’ t₁ ∩ (a β€’ tβ‚‚) := image_inter_subset _ _ _ @[to_additive] lemma smul_set_Union (a : Ξ±) (s : ΞΉ β†’ set Ξ²) : a β€’ (⋃ i, s i) = ⋃ i, a β€’ s i := image_Union @[to_additive] lemma smul_set_Unionβ‚‚ (a : Ξ±) (s : Ξ  i, ΞΊ i β†’ set Ξ²) : a β€’ (⋃ i j, s i j) = ⋃ i j, a β€’ s i j := image_Unionβ‚‚ _ _ @[to_additive] lemma smul_set_Inter_subset (a : Ξ±) (t : ΞΉ β†’ set Ξ²) : a β€’ (β‹‚ i, t i) βŠ† β‹‚ i, a β€’ t i := image_Inter_subset _ _ @[to_additive] lemma smul_set_Interβ‚‚_subset (a : Ξ±) (t : Ξ  i, ΞΊ i β†’ set Ξ²) : a β€’ (β‹‚ i j, t i j) βŠ† β‹‚ i j, a β€’ t i j := image_Interβ‚‚_subset _ _ @[to_additive] lemma nonempty.smul_set : s.nonempty β†’ (a β€’ s).nonempty := nonempty.image _ @[to_additive] lemma finite.smul_set : finite s β†’ finite (a β€’ s) := finite.image _ end has_scalar_set variables {s s₁ sβ‚‚ : set Ξ±} {t t₁ tβ‚‚ : set Ξ²} {a : Ξ±} {b : Ξ²} @[to_additive] lemma smul_set_inter [group Ξ±] [mul_action Ξ± Ξ²] {s t : set Ξ²} : a β€’ (s ∩ t) = a β€’ s ∩ a β€’ t := (image_inter $ mul_action.injective a).symm lemma smul_set_interβ‚€ [group_with_zero Ξ±] [mul_action Ξ± Ξ²] {s t : set Ξ²} (ha : a β‰  0) : a β€’ (s ∩ t) = a β€’ s ∩ a β€’ t := show units.mk0 a ha β€’ _ = _, from smul_set_inter @[simp, to_additive] lemma smul_set_univ [group Ξ±] [mul_action Ξ± Ξ²] {a : Ξ±} : a β€’ (univ : set Ξ²) = univ := eq_univ_of_forall $ Ξ» b, ⟨a⁻¹ β€’ b, trivial, smul_inv_smul _ _⟩ @[simp, to_additive] lemma smul_univ [group Ξ±] [mul_action Ξ± Ξ²] {s : set Ξ±} (hs : s.nonempty) : s β€’ (univ : set Ξ²) = univ := let ⟨a, ha⟩ := hs in eq_univ_of_forall $ Ξ» b, ⟨a, a⁻¹ β€’ b, ha, trivial, smul_inv_smul _ _⟩ @[to_additive] theorem range_smul_range {ΞΉ ΞΊ : Type*} [has_scalar Ξ± Ξ²] (b : ΞΉ β†’ Ξ±) (c : ΞΊ β†’ Ξ²) : range b β€’ range c = range (Ξ» p : ΞΉ Γ— ΞΊ, b p.1 β€’ c p.2) := ext $ Ξ» x, ⟨λ hx, let ⟨p, q, ⟨i, hi⟩, ⟨j, hj⟩, hpq⟩ := set.mem_smul.1 hx in ⟨(i, j), hpq β–Έ hi β–Έ hj β–Έ rfl⟩, Ξ» ⟨⟨i, j⟩, h⟩, set.mem_smul.2 ⟨b i, c j, ⟨i, rfl⟩, ⟨j, rfl⟩, h⟩⟩ @[to_additive] instance smul_comm_class_set [has_scalar Ξ± Ξ³] [has_scalar Ξ² Ξ³] [smul_comm_class Ξ± Ξ² Ξ³] : smul_comm_class Ξ± (set Ξ²) (set Ξ³) := ⟨λ _ _ _, image_image2_distrib_right $ smul_comm _⟩ @[to_additive] instance smul_comm_class_set' [has_scalar Ξ± Ξ³] [has_scalar Ξ² Ξ³] [smul_comm_class Ξ± Ξ² Ξ³] : smul_comm_class (set Ξ±) Ξ² (set Ξ³) := by haveI := smul_comm_class.symm Ξ± Ξ² Ξ³; exact smul_comm_class.symm _ _ _ @[to_additive] instance smul_comm_class [has_scalar Ξ± Ξ³] [has_scalar Ξ² Ξ³] [smul_comm_class Ξ± Ξ² Ξ³] : smul_comm_class (set Ξ±) (set Ξ²) (set Ξ³) := ⟨λ _ _ _, image2_left_comm smul_comm⟩ instance is_scalar_tower [has_scalar Ξ± Ξ²] [has_scalar Ξ± Ξ³] [has_scalar Ξ² Ξ³] [is_scalar_tower Ξ± Ξ² Ξ³] : is_scalar_tower Ξ± Ξ² (set Ξ³) := { smul_assoc := Ξ» a b T, by simp only [←image_smul, image_image, smul_assoc] } instance is_scalar_tower' [has_scalar Ξ± Ξ²] [has_scalar Ξ± Ξ³] [has_scalar Ξ² Ξ³] [is_scalar_tower Ξ± Ξ² Ξ³] : is_scalar_tower Ξ± (set Ξ²) (set Ξ³) := ⟨λ _ _ _, image2_image_left_comm $ smul_assoc _⟩ instance is_scalar_tower'' [has_scalar Ξ± Ξ²] [has_scalar Ξ± Ξ³] [has_scalar Ξ² Ξ³] [is_scalar_tower Ξ± Ξ² Ξ³] : is_scalar_tower (set Ξ±) (set Ξ²) (set Ξ³) := { smul_assoc := Ξ» T T' T'', image2_assoc smul_assoc } instance is_central_scalar [has_scalar Ξ± Ξ²] [has_scalar αᡐᡒᡖ Ξ²] [is_central_scalar Ξ± Ξ²] : is_central_scalar Ξ± (set Ξ²) := ⟨λ a S, congr_arg (Ξ» f, f '' S) $ by exact funext (Ξ» _, op_smul_eq_smul _ _)⟩ /-- A multiplicative action of a monoid `Ξ±` on a type `Ξ²` gives a multiplicative action of `set Ξ±` on `set Ξ²`. -/ @[to_additive "An additive action of an additive monoid `Ξ±` on a type `Ξ²` gives an additive action of `set Ξ±` on `set Ξ²`"] protected def mul_action [monoid Ξ±] [mul_action Ξ± Ξ²] : mul_action (set Ξ±) (set Ξ²) := { mul_smul := Ξ» _ _ _, image2_assoc mul_smul, one_smul := Ξ» s, image2_singleton_left.trans $ by simp_rw [one_smul, image_id'] } /-- A multiplicative action of a monoid on a type `Ξ²` gives a multiplicative action on `set Ξ²`. -/ @[to_additive "An additive action of an additive monoid on a type `Ξ²` gives an additive action on `set Ξ²`."] protected def mul_action_set [monoid Ξ±] [mul_action Ξ± Ξ²] : mul_action Ξ± (set Ξ²) := { mul_smul := by { intros, simp only [← image_smul, image_image, ← mul_smul] }, one_smul := by { intros, simp only [← image_smul, one_smul, image_id'] } } localized "attribute [instance] set.mul_action_set set.add_action_set set.mul_action set.add_action" in pointwise /-- A distributive multiplicative action of a monoid on an additive monoid `Ξ²` gives a distributive multiplicative action on `set Ξ²`. -/ protected def distrib_mul_action_set [monoid Ξ±] [add_monoid Ξ²] [distrib_mul_action Ξ± Ξ²] : distrib_mul_action Ξ± (set Ξ²) := { smul_add := Ξ» _ _ _, image_image2_distrib $ smul_add _, smul_zero := Ξ» _, image_singleton.trans $ by rw [smul_zero, singleton_zero] } /-- A multiplicative action of a monoid on a monoid `Ξ²` gives a multiplicative action on `set Ξ²`. -/ protected def mul_distrib_mul_action_set [monoid Ξ±] [monoid Ξ²] [mul_distrib_mul_action Ξ± Ξ²] : mul_distrib_mul_action Ξ± (set Ξ²) := { smul_mul := Ξ» _ _ _, image_image2_distrib $ smul_mul' _, smul_one := Ξ» _, image_singleton.trans $ by rw [smul_one, singleton_one] } localized "attribute [instance] set.distrib_mul_action_set set.mul_distrib_mul_action_set" in pointwise end smul section vsub variables {ΞΉ : Sort*} {ΞΊ : ΞΉ β†’ Sort*} [has_vsub Ξ± Ξ²] {s s₁ sβ‚‚ t t₁ tβ‚‚ : set Ξ²} {u : set Ξ±} {a : Ξ±} {b c : Ξ²} include Ξ± instance has_vsub : has_vsub (set Ξ±) (set Ξ²) := ⟨image2 (-α΅₯)⟩ @[simp] lemma image2_vsub : (image2 has_vsub.vsub s t : set Ξ±) = s -α΅₯ t := rfl lemma image_vsub_prod : (Ξ» x : Ξ² Γ— Ξ², x.fst -α΅₯ x.snd) '' s Γ—Λ’ t = s -α΅₯ t := image_prod _ lemma mem_vsub : a ∈ s -α΅₯ t ↔ βˆƒ x y, x ∈ s ∧ y ∈ t ∧ x -α΅₯ y = a := iff.rfl lemma vsub_mem_vsub (hb : b ∈ s) (hc : c ∈ t) : b -α΅₯ c ∈ s -α΅₯ t := mem_image2_of_mem hb hc @[simp] lemma empty_vsub (t : set Ξ²) : βˆ… -α΅₯ t = βˆ… := image2_empty_left @[simp] lemma vsub_empty (s : set Ξ²) : s -α΅₯ βˆ… = βˆ… := image2_empty_right @[simp] lemma vsub_eq_empty : s -α΅₯ t = βˆ… ↔ s = βˆ… ∨ t = βˆ… := image2_eq_empty_iff @[simp] lemma vsub_nonempty : (s -α΅₯ t : set Ξ±).nonempty ↔ s.nonempty ∧ t.nonempty := image2_nonempty_iff lemma nonempty.vsub : s.nonempty β†’ t.nonempty β†’ (s -α΅₯ t : set Ξ±).nonempty := nonempty.image2 lemma nonempty.of_vsub_left : (s -α΅₯ t :set Ξ±).nonempty β†’ s.nonempty := nonempty.of_image2_left lemma nonempty.of_vsub_right : (s -α΅₯ t : set Ξ±).nonempty β†’ t.nonempty := nonempty.of_image2_right @[simp] lemma vsub_singleton (s : set Ξ²) (b : Ξ²) : s -α΅₯ {b} = (-α΅₯ b) '' s := image2_singleton_right @[simp] lemma singleton_vsub (t : set Ξ²) (b : Ξ²) : {b} -α΅₯ t = ((-α΅₯) b) '' t := image2_singleton_left @[simp] lemma singleton_vsub_singleton : ({b} : set Ξ²) -α΅₯ {c} = {b -α΅₯ c} := image2_singleton @[mono] lemma vsub_subset_vsub : s₁ βŠ† sβ‚‚ β†’ t₁ βŠ† tβ‚‚ β†’ s₁ -α΅₯ t₁ βŠ† sβ‚‚ -α΅₯ tβ‚‚ := image2_subset lemma vsub_subset_vsub_left : t₁ βŠ† tβ‚‚ β†’ s -α΅₯ t₁ βŠ† s -α΅₯ tβ‚‚ := image2_subset_left lemma vsub_subset_vsub_right : s₁ βŠ† sβ‚‚ β†’ s₁ -α΅₯ t βŠ† sβ‚‚ -α΅₯ t := image2_subset_right lemma vsub_subset_iff : s -α΅₯ t βŠ† u ↔ βˆ€ (x ∈ s) (y ∈ t), x -α΅₯ y ∈ u := image2_subset_iff lemma vsub_self_mono (h : s βŠ† t) : s -α΅₯ s βŠ† t -α΅₯ t := vsub_subset_vsub h h lemma union_vsub : (s₁ βˆͺ sβ‚‚) -α΅₯ t = s₁ -α΅₯ t βˆͺ (sβ‚‚ -α΅₯ t) := image2_union_left lemma vsub_union : s -α΅₯ (t₁ βˆͺ tβ‚‚) = s -α΅₯ t₁ βˆͺ (s -α΅₯ tβ‚‚) := image2_union_right lemma inter_vsub_subset : s₁ ∩ sβ‚‚ -α΅₯ t βŠ† (s₁ -α΅₯ t) ∩ (sβ‚‚ -α΅₯ t) := image2_inter_subset_left lemma vsub_inter_subset : s -α΅₯ t₁ ∩ tβ‚‚ βŠ† (s -α΅₯ t₁) ∩ (s -α΅₯ tβ‚‚) := image2_inter_subset_right lemma Union_vsub_left_image : (⋃ a ∈ s, ((-α΅₯) a) '' t) = s -α΅₯ t := Union_image_left _ lemma Union_vsub_right_image : (⋃ a ∈ t, (-α΅₯ a) '' s) = s -α΅₯ t := Union_image_right _ lemma Union_vsub (s : ΞΉ β†’ set Ξ²) (t : set Ξ²) : (⋃ i, s i) -α΅₯ t = ⋃ i, s i -α΅₯ t := image2_Union_left _ _ _ lemma vsub_Union (s : set Ξ²) (t : ΞΉ β†’ set Ξ²) : s -α΅₯ (⋃ i, t i) = ⋃ i, s -α΅₯ t i := image2_Union_right _ _ _ lemma Unionβ‚‚_vsub (s : Ξ  i, ΞΊ i β†’ set Ξ²) (t : set Ξ²) : (⋃ i j, s i j) -α΅₯ t = ⋃ i j, s i j -α΅₯ t := image2_Unionβ‚‚_left _ _ _ lemma vsub_Unionβ‚‚ (s : set Ξ²) (t : Ξ  i, ΞΊ i β†’ set Ξ²) : s -α΅₯ (⋃ i j, t i j) = ⋃ i j, s -α΅₯ t i j := image2_Unionβ‚‚_right _ _ _ lemma Inter_vsub_subset (s : ΞΉ β†’ set Ξ²) (t : set Ξ²) : (β‹‚ i, s i) -α΅₯ t βŠ† β‹‚ i, s i -α΅₯ t := image2_Inter_subset_left _ _ _ lemma vsub_Inter_subset (s : set Ξ²) (t : ΞΉ β†’ set Ξ²) : s -α΅₯ (β‹‚ i, t i) βŠ† β‹‚ i, s -α΅₯ t i := image2_Inter_subset_right _ _ _ lemma Interβ‚‚_vsub_subset (s : Ξ  i, ΞΊ i β†’ set Ξ²) (t : set Ξ²) : (β‹‚ i j, s i j) -α΅₯ t βŠ† β‹‚ i j, s i j -α΅₯ t := image2_Interβ‚‚_subset_left _ _ _ lemma vsub_Interβ‚‚_subset (s : set Ξ²) (t : Ξ  i, ΞΊ i β†’ set Ξ²) : s -α΅₯ (β‹‚ i j, t i j) βŠ† β‹‚ i j, s -α΅₯ t i j := image2_Interβ‚‚_subset_right _ _ _ lemma finite.vsub (hs : finite s) (ht : finite t) : finite (s -α΅₯ t) := hs.image2 _ ht end vsub open_locale pointwise section ring variables [ring Ξ±] [add_comm_group Ξ²] [module Ξ± Ξ²] {s : set Ξ±} {t : set Ξ²} {a : Ξ±} @[simp] lemma neg_smul_set : -a β€’ t = -(a β€’ t) := by simp_rw [←image_smul, ←image_neg, image_image, neg_smul] @[simp] lemma smul_set_neg : a β€’ -t = -(a β€’ t) := by simp_rw [←image_smul, ←image_neg, image_image, smul_neg] @[simp] protected lemma neg_smul : -s β€’ t = -(s β€’ t) := by simp_rw [←image2_smul, ←image_neg, image2_image_left, image_image2, neg_smul] @[simp] protected lemma smul_neg : s β€’ -t = -(s β€’ t) := by simp_rw [←image2_smul, ←image_neg, image2_image_right, image_image2, smul_neg] end ring section monoid /-! ### `set Ξ±` as a `(βˆͺ, *)`-semiring -/ /-- An alias for `set Ξ±`, which has a semiring structure given by `βˆͺ` as "addition" and pointwise multiplication `*` as "multiplication". -/ @[derive [inhabited, partial_order, order_bot]] def set_semiring (Ξ± : Type*) : Type* := set Ξ± /-- The identity function `set Ξ± β†’ set_semiring Ξ±`. -/ protected def up (s : set Ξ±) : set_semiring Ξ± := s /-- The identity function `set_semiring Ξ± β†’ set Ξ±`. -/ protected def set_semiring.down (s : set_semiring Ξ±) : set Ξ± := s @[simp] protected lemma down_up {s : set Ξ±} : s.up.down = s := rfl @[simp] protected lemma up_down {s : set_semiring Ξ±} : s.down.up = s := rfl /- This lemma is not tagged `simp`, since otherwise the linter complains. -/ lemma up_le_up {s t : set Ξ±} : s.up ≀ t.up ↔ s βŠ† t := iff.rfl /- This lemma is not tagged `simp`, since otherwise the linter complains. -/ lemma up_lt_up {s t : set Ξ±} : s.up < t.up ↔ s βŠ‚ t := iff.rfl @[simp] lemma down_subset_down {s t : set_semiring Ξ±} : s.down βŠ† t.down ↔ s ≀ t := iff.rfl @[simp] lemma down_ssubset_down {s t : set_semiring Ξ±} : s.down βŠ‚ t.down ↔ s < t := iff.rfl instance set_semiring.add_comm_monoid : add_comm_monoid (set_semiring Ξ±) := { add := Ξ» s t, (s βˆͺ t : set Ξ±), zero := (βˆ… : set Ξ±), add_assoc := union_assoc, zero_add := empty_union, add_zero := union_empty, add_comm := union_comm, } instance set_semiring.non_unital_non_assoc_semiring [has_mul Ξ±] : non_unital_non_assoc_semiring (set_semiring Ξ±) := { zero_mul := Ξ» s, empty_mul, mul_zero := Ξ» s, mul_empty, left_distrib := Ξ» _ _ _, mul_union, right_distrib := Ξ» _ _ _, union_mul, ..set.has_mul, ..set_semiring.add_comm_monoid } instance set_semiring.non_assoc_semiring [mul_one_class Ξ±] : non_assoc_semiring (set_semiring Ξ±) := { ..set_semiring.non_unital_non_assoc_semiring, ..set.mul_one_class } instance set_semiring.non_unital_semiring [semigroup Ξ±] : non_unital_semiring (set_semiring Ξ±) := { ..set_semiring.non_unital_non_assoc_semiring, ..set.semigroup } instance set_semiring.semiring [monoid Ξ±] : semiring (set_semiring Ξ±) := { ..set_semiring.non_assoc_semiring, ..set_semiring.non_unital_semiring } instance set_semiring.non_unital_comm_semiring [comm_semigroup Ξ±] : non_unital_comm_semiring (set_semiring Ξ±) := { ..set_semiring.non_unital_semiring, ..set.comm_semigroup } instance set_semiring.comm_semiring [comm_monoid Ξ±] : comm_semiring (set_semiring Ξ±) := { ..set.comm_monoid, ..set_semiring.semiring } section mul_hom variables [has_mul Ξ±] [has_mul Ξ²] [mul_hom_class F Ξ± Ξ²] (m : F) {s t : set Ξ±} @[to_additive] lemma image_mul : (m : Ξ± β†’ Ξ²) '' (s * t) = m '' s * m '' t := image_image2_distrib $ map_mul m @[to_additive] lemma preimage_mul_preimage_subset {s t : set Ξ²} : (m : Ξ± β†’ Ξ²) ⁻¹' s * m ⁻¹' t βŠ† m ⁻¹' (s * t) := by { rintro _ ⟨_, _, _, _, rfl⟩, exact ⟨_, _, β€Ή_β€Ί, β€Ή_β€Ί, (map_mul m _ _).symm ⟩ } instance set_semiring.no_zero_divisors : no_zero_divisors (set_semiring Ξ±) := ⟨λ a b ab, a.eq_empty_or_nonempty.imp_right $ Ξ» ha, b.eq_empty_or_nonempty.resolve_right $ Ξ» hb, nonempty.ne_empty ⟨_, mul_mem_mul ha.some_mem hb.some_mem⟩ ab⟩ /- Since addition on `set_semiring` is commutative (it is set union), there is no need to also have the instance `covariant_class (set_semiring Ξ±) (set_semiring Ξ±) (swap (+)) (≀)`. -/ instance set_semiring.covariant_class_add : covariant_class (set_semiring Ξ±) (set_semiring Ξ±) (+) (≀) := { elim := Ξ» a b c, union_subset_union_right _ } instance set_semiring.covariant_class_mul_left : covariant_class (set_semiring Ξ±) (set_semiring Ξ±) (*) (≀) := { elim := Ξ» a b c, mul_subset_mul_left } instance set_semiring.covariant_class_mul_right : covariant_class (set_semiring Ξ±) (set_semiring Ξ±) (swap (*)) (≀) := { elim := Ξ» a b c, mul_subset_mul_right } end mul_hom /-- The image of a set under a multiplicative homomorphism is a ring homomorphism with respect to the pointwise operations on sets. -/ def image_hom [monoid Ξ±] [monoid Ξ²] (f : Ξ± β†’* Ξ²) : set_semiring Ξ± β†’+* set_semiring Ξ² := { to_fun := image f, map_zero' := image_empty _, map_one' := by simp only [← singleton_one, image_singleton, f.map_one], map_add' := image_union _, map_mul' := Ξ» _ _, image_mul f } end monoid section comm_monoid variable [comm_monoid Ξ±] instance : canonically_ordered_comm_semiring (set_semiring Ξ±) := { add_le_add_left := Ξ» a b, add_le_add_left, le_iff_exists_add := Ξ» a b, ⟨λ ab, ⟨b, (union_eq_right_iff_subset.2 ab).symm⟩, by { rintro ⟨c, rfl⟩, exact subset_union_left _ _ }⟩, ..(infer_instance : comm_semiring (set_semiring Ξ±)), ..(infer_instance : partial_order (set_semiring Ξ±)), ..(infer_instance : order_bot (set_semiring Ξ±)), ..(infer_instance : no_zero_divisors (set_semiring Ξ±)) } end comm_monoid end set open set open_locale pointwise section section smul_with_zero variables [has_zero Ξ±] [has_zero Ξ²] [smul_with_zero Ξ± Ξ²] /-- A nonempty set is scaled by zero to the singleton set containing 0. -/ lemma zero_smul_set {s : set Ξ²} (h : s.nonempty) : (0 : Ξ±) β€’ s = (0 : set Ξ²) := by simp only [← image_smul, image_eta, zero_smul, h.image_const, singleton_zero] lemma zero_smul_subset (s : set Ξ²) : (0 : Ξ±) β€’ s βŠ† 0 := image_subset_iff.2 $ Ξ» x _, zero_smul Ξ± x lemma subsingleton_zero_smul_set (s : set Ξ²) : ((0 : Ξ±) β€’ s).subsingleton := subsingleton_singleton.mono (zero_smul_subset s) lemma zero_mem_smul_set {t : set Ξ²} {a : Ξ±} (h : (0 : Ξ²) ∈ t) : (0 : Ξ²) ∈ a β€’ t := ⟨0, h, smul_zero' _ _⟩ variables [no_zero_smul_divisors Ξ± Ξ²] {s : set Ξ±} {t : set Ξ²} {a : Ξ±} lemma zero_mem_smul_iff : (0 : Ξ²) ∈ s β€’ t ↔ (0 : Ξ±) ∈ s ∧ t.nonempty ∨ (0 : Ξ²) ∈ t ∧ s.nonempty := begin split, { rintro ⟨a, b, ha, hb, h⟩, obtain rfl | rfl := eq_zero_or_eq_zero_of_smul_eq_zero h, { exact or.inl ⟨ha, b, hb⟩ }, { exact or.inr ⟨hb, a, ha⟩ } }, { rintro (⟨hs, b, hb⟩ | ⟨ht, a, ha⟩), { exact ⟨0, b, hs, hb, zero_smul _ _⟩ }, { exact ⟨a, 0, ha, ht, smul_zero' _ _⟩ } } end lemma zero_mem_smul_set_iff (ha : a β‰  0) : (0 : Ξ²) ∈ a β€’ t ↔ (0 : Ξ²) ∈ t := begin refine ⟨_, zero_mem_smul_set⟩, rintro ⟨b, hb, h⟩, rwa (eq_zero_or_eq_zero_of_smul_eq_zero h).resolve_left ha at hb, end end smul_with_zero lemma smul_add_set [monoid Ξ±] [add_monoid Ξ²] [distrib_mul_action Ξ± Ξ²] (c : Ξ±) (s t : set Ξ²) : c β€’ (s + t) = c β€’ s + c β€’ t := image_add (distrib_mul_action.to_add_monoid_hom Ξ² c).to_add_hom section group variables [group Ξ±] [mul_action Ξ± Ξ²] {A B : set Ξ²} {a : Ξ±} {x : Ξ²} @[simp, to_additive] lemma smul_mem_smul_set_iff : a β€’ x ∈ a β€’ A ↔ x ∈ A := ⟨λ h, begin rw [←inv_smul_smul a x, ←inv_smul_smul a A], exact smul_mem_smul_set h, end, smul_mem_smul_set⟩ @[to_additive] lemma mem_smul_set_iff_inv_smul_mem : x ∈ a β€’ A ↔ a⁻¹ β€’ x ∈ A := show x ∈ mul_action.to_perm a '' A ↔ _, from mem_image_equiv @[to_additive] lemma mem_inv_smul_set_iff : x ∈ a⁻¹ β€’ A ↔ a β€’ x ∈ A := by simp only [← image_smul, mem_image, inv_smul_eq_iff, exists_eq_right] @[to_additive] lemma preimage_smul (a : Ξ±) (t : set Ξ²) : (Ξ» x, a β€’ x) ⁻¹' t = a⁻¹ β€’ t := ((mul_action.to_perm a).symm.image_eq_preimage _).symm @[to_additive] lemma preimage_smul_inv (a : Ξ±) (t : set Ξ²) : (Ξ» x, a⁻¹ β€’ x) ⁻¹' t = a β€’ t := preimage_smul (to_units a)⁻¹ t @[simp, to_additive] lemma set_smul_subset_set_smul_iff : a β€’ A βŠ† a β€’ B ↔ A βŠ† B := image_subset_image_iff $ mul_action.injective _ @[to_additive] lemma set_smul_subset_iff : a β€’ A βŠ† B ↔ A βŠ† a⁻¹ β€’ B := (image_subset_iff).trans $ iff_of_eq $ congr_arg _ $ preimage_equiv_eq_image_symm _ $ mul_action.to_perm _ @[to_additive] lemma subset_set_smul_iff : A βŠ† a β€’ B ↔ a⁻¹ β€’ A βŠ† B := iff.symm $ (image_subset_iff).trans $ iff.symm $ iff_of_eq $ congr_arg _ $ image_equiv_eq_preimage_symm _ $ mul_action.to_perm _ end group section group_with_zero variables [group_with_zero Ξ±] [mul_action Ξ± Ξ²] {s : set Ξ±} {a : Ξ±} @[simp] lemma smul_mem_smul_set_iffβ‚€ (ha : a β‰  0) (A : set Ξ²) (x : Ξ²) : a β€’ x ∈ a β€’ A ↔ x ∈ A := show units.mk0 a ha β€’ _ ∈ _ ↔ _, from smul_mem_smul_set_iff lemma mem_smul_set_iff_inv_smul_memβ‚€ (ha : a β‰  0) (A : set Ξ²) (x : Ξ²) : x ∈ a β€’ A ↔ a⁻¹ β€’ x ∈ A := show _ ∈ units.mk0 a ha β€’ _ ↔ _, from mem_smul_set_iff_inv_smul_mem lemma mem_inv_smul_set_iffβ‚€ (ha : a β‰  0) (A : set Ξ²) (x : Ξ²) : x ∈ a⁻¹ β€’ A ↔ a β€’ x ∈ A := show _ ∈ (units.mk0 a ha)⁻¹ β€’ _ ↔ _, from mem_inv_smul_set_iff lemma preimage_smulβ‚€ (ha : a β‰  0) (t : set Ξ²) : (Ξ» x, a β€’ x) ⁻¹' t = a⁻¹ β€’ t := preimage_smul (units.mk0 a ha) t lemma preimage_smul_invβ‚€ (ha : a β‰  0) (t : set Ξ²) : (Ξ» x, a⁻¹ β€’ x) ⁻¹' t = a β€’ t := preimage_smul ((units.mk0 a ha)⁻¹) t @[simp] lemma set_smul_subset_set_smul_iffβ‚€ (ha : a β‰  0) {A B : set Ξ²} : a β€’ A βŠ† a β€’ B ↔ A βŠ† B := show units.mk0 a ha β€’ _ βŠ† _ ↔ _, from set_smul_subset_set_smul_iff lemma set_smul_subset_iffβ‚€ (ha : a β‰  0) {A B : set Ξ²} : a β€’ A βŠ† B ↔ A βŠ† a⁻¹ β€’ B := show units.mk0 a ha β€’ _ βŠ† _ ↔ _, from set_smul_subset_iff lemma subset_set_smul_iffβ‚€ (ha : a β‰  0) {A B : set Ξ²} : A βŠ† a β€’ B ↔ a⁻¹ β€’ A βŠ† B := show _ βŠ† units.mk0 a ha β€’ _ ↔ _, from subset_set_smul_iff lemma smul_univβ‚€ (hs : Β¬ s βŠ† 0) : s β€’ (univ : set Ξ²) = univ := let ⟨a, ha, haβ‚€βŸ© := not_subset.1 hs in eq_univ_of_forall $ Ξ» b, ⟨a, a⁻¹ β€’ b, ha, trivial, smul_inv_smulβ‚€ haβ‚€ _⟩ lemma smul_set_univβ‚€ (ha : a β‰  0) : a β€’ (univ : set Ξ²) = univ := eq_univ_of_forall $ Ξ» b, ⟨a⁻¹ β€’ b, trivial, smul_inv_smulβ‚€ ha _⟩ end group_with_zero end /-! Some lemmas about pointwise multiplication and submonoids. Ideally we put these in `group_theory.submonoid.basic`, but currently we cannot because that file is imported by this. -/ namespace submonoid variables {M : Type*} [monoid M] {s t u : set M} @[to_additive] lemma mul_subset {S : submonoid M} (hs : s βŠ† S) (ht : t βŠ† S) : s * t βŠ† S := by { rintro _ ⟨p, q, hp, hq, rfl⟩, exact submonoid.mul_mem _ (hs hp) (ht hq) } @[to_additive] lemma mul_subset_closure (hs : s βŠ† u) (ht : t βŠ† u) : s * t βŠ† submonoid.closure u := mul_subset (subset.trans hs submonoid.subset_closure) (subset.trans ht submonoid.subset_closure) @[to_additive] lemma coe_mul_self_eq (s : submonoid M) : (s : set M) * s = s := begin ext x, refine ⟨_, Ξ» h, ⟨x, 1, h, s.one_mem, mul_one x⟩⟩, rintro ⟨a, b, ha, hb, rfl⟩, exact s.mul_mem ha hb end @[to_additive] lemma closure_mul_le (S T : set M) : closure (S * T) ≀ closure S βŠ” closure T := Inf_le $ Ξ» x ⟨s, t, hs, ht, hx⟩, hx β–Έ (closure S βŠ” closure T).mul_mem (set_like.le_def.mp le_sup_left $ subset_closure hs) (set_like.le_def.mp le_sup_right $ subset_closure ht) @[to_additive] lemma sup_eq_closure (H K : submonoid M) : H βŠ” K = closure (H * K) := le_antisymm (sup_le (Ξ» h hh, subset_closure ⟨h, 1, hh, K.one_mem, mul_one h⟩) (Ξ» k hk, subset_closure ⟨1, k, H.one_mem, hk, one_mul k⟩)) (by conv_rhs { rw [← closure_eq H, ← closure_eq K] }; apply closure_mul_le) lemma pow_smul_mem_closure_smul {N : Type*} [comm_monoid N] [mul_action M N] [is_scalar_tower M N N] (r : M) (s : set N) {x : N} (hx : x ∈ closure s) : βˆƒ n : β„•, r ^ n β€’ x ∈ closure (r β€’ s) := begin apply @closure_induction N _ s (Ξ» (x : N), βˆƒ n : β„•, r ^ n β€’ x ∈ closure (r β€’ s)) _ hx, { intros x hx, exact ⟨1, subset_closure ⟨_, hx, by rw pow_one⟩⟩ }, { exact ⟨0, by simpa using one_mem _⟩ }, { rintro x y ⟨nx, hx⟩ ⟨ny, hy⟩, use nx + ny, convert mul_mem hx hy, rw [pow_add, smul_mul_assoc, mul_smul, mul_comm, ← smul_mul_assoc, mul_comm] } end end submonoid namespace group lemma card_pow_eq_card_pow_card_univ_aux {f : β„• β†’ β„•} (h1 : monotone f) {B : β„•} (h2 : βˆ€ n, f n ≀ B) (h3 : βˆ€ n, f n = f (n + 1) β†’ f (n + 1) = f (n + 2)) : βˆ€ k, B ≀ k β†’ f k = f B := begin have key : βˆƒ n : β„•, n ≀ B ∧ f n = f (n + 1), { contrapose! h2, suffices : βˆ€ n : β„•, n ≀ B + 1 β†’ n ≀ f n, { exact ⟨B + 1, this (B + 1) (le_refl (B + 1))⟩ }, exact Ξ» n, nat.rec (Ξ» h, nat.zero_le (f 0)) (Ξ» n ih h, lt_of_le_of_lt (ih (n.le_succ.trans h)) (lt_of_le_of_ne (h1 n.le_succ) (h2 n (nat.succ_le_succ_iff.mp h)))) n }, { obtain ⟨n, hn1, hn2⟩ := key, replace key : βˆ€ k : β„•, f (n + k) = f (n + k + 1) ∧ f (n + k) = f n := Ξ» k, nat.rec ⟨hn2, rfl⟩ (Ξ» k ih, ⟨h3 _ ih.1, ih.1.symm.trans ih.2⟩) k, replace key : βˆ€ k : β„•, n ≀ k β†’ f k = f n := Ξ» k hk, (congr_arg f (add_tsub_cancel_of_le hk)).symm.trans (key (k - n)).2, exact Ξ» k hk, (key k (hn1.trans hk)).trans (key B hn1).symm }, end variables {G : Type*} [group G] [fintype G] (S : set G) @[to_additive] lemma card_pow_eq_card_pow_card_univ [βˆ€ (k : β„•), decidable_pred (∈ (S ^ k))] : βˆ€ k, fintype.card G ≀ k β†’ fintype.card β†₯(S ^ k) = fintype.card β†₯(S ^ (fintype.card G)) := begin have hG : 0 < fintype.card G := fintype.card_pos_iff.mpr ⟨1⟩, by_cases hS : S = βˆ…, { refine Ξ» k hk, fintype.card_congr _, rw [hS, empty_pow _ (ne_of_gt (lt_of_lt_of_le hG hk)), empty_pow _ (ne_of_gt hG)] }, obtain ⟨a, ha⟩ := set.ne_empty_iff_nonempty.mp hS, classical, have key : βˆ€ a (s t : set G), (βˆ€ b : G, b ∈ s β†’ a * b ∈ t) β†’ fintype.card s ≀ fintype.card t, { refine Ξ» a s t h, fintype.card_le_of_injective (Ξ» ⟨b, hb⟩, ⟨a * b, h b hb⟩) _, rintro ⟨b, hb⟩ ⟨c, hc⟩ hbc, exact subtype.ext (mul_left_cancel (subtype.ext_iff.mp hbc)) }, have mono : monotone (Ξ» n, fintype.card β†₯(S ^ n) : β„• β†’ β„•) := monotone_nat_of_le_succ (Ξ» n, key a _ _ (Ξ» b hb, set.mul_mem_mul ha hb)), convert card_pow_eq_card_pow_card_univ_aux mono (Ξ» n, set_fintype_card_le_univ (S ^ n)) (Ξ» n h, le_antisymm (mono (n + 1).le_succ) (key a⁻¹ _ _ _)), { simp only [finset.filter_congr_decidable, fintype.card_of_finset] }, replace h : {a} * S ^ n = S ^ (n + 1), { refine set.eq_of_subset_of_card_le _ (le_trans (ge_of_eq h) _), { exact mul_subset_mul (set.singleton_subset_iff.mpr ha) set.subset.rfl }, { convert key a (S ^ n) ({a} * S ^ n) (Ξ» b hb, set.mul_mem_mul (set.mem_singleton a) hb) } }, rw [pow_succ', ←h, mul_assoc, ←pow_succ', h], rintro _ ⟨b, c, hb, hc, rfl⟩, rwa [set.mem_singleton_iff.mp hb, inv_mul_cancel_left], end end group
019c167fbad4b05a091120d25a0d3795f6b122d7
f1a12d4db0f46eee317d703e3336d33950a2fe7e
/lia/common/correctness.lean
956009ae7837eab1e6cd1e706a2c8139e8741a41
[ "Apache-2.0" ]
permissive
avigad/qelim
bce89b79c717b7649860d41a41a37e37c982624f
b7d22864f1f0a2d21adad0f4fb3fc7ba665f8e60
refs/heads/master
1,584,548,938,232
1,526,773,708,000
1,526,773,708,000
134,967,693
2
0
null
null
null
null
UTF-8
Lean
false
false
4,868
lean
import .atom import ...common.lnq ...common.ldq ...common.predicates variables {Ξ± Ξ² : Type} namespace lia lemma down_closed_fnormal : @down_closed (lia.atom) (fnormal int) | ⊀' _ hd _ := by cases hd | βŠ₯' _ hd _ := by cases hd | (A' a) _ hd _ := by cases hd | (p ∧' q) r hd hn := by {unfold fnormal at hn, cases hn, cases hd; assumption} | (p ∨' q) r hd hn := by {unfold fnormal at hn, cases hn, cases hd; assumption} | (Β¬' p) r hd hn := by {cases hd, apply hn} | (βˆƒ' p) r hd hn := by {cases hd, apply hn} lemma prop_up_closed_fnormal : @prop_up_closed (lia.atom) (fnormal int) | ⊀' := trivial | βŠ₯' := trivial | (A' a) := trivial | (p ∧' q) := begin intros hp hq, apply and.intro hp hq end | (p ∨' q) := begin intros hp hq, apply and.intro hp hq end | (Β¬' p) := id | (βˆƒ' p) := trivial lemma fnormal_and_o : βˆ€ (p q : fm atom), fnormal int p β†’ fnormal int q β†’ fnormal int (and_o p q) := pred_and_o (fnormal int) prop_up_closed_fnormal lemma fnormal_or_o : βˆ€ (p q : fm atom), fnormal int p β†’ fnormal int q β†’ fnormal int (or_o p q) := pred_or_o (fnormal int) prop_up_closed_fnormal lemma fnormal_list_disj : βˆ€ (ps : list (fm atom)), (βˆ€ p ∈ ps, fnormal int p) β†’ fnormal int (list_disj ps) := pred_list_disj _ prop_up_closed_fnormal lemma fnormal_disj : βˆ€ (bs : list Ξ²) (f : Ξ² β†’ fm atom), (βˆ€ b ∈ bs, fnormal int (f b)) β†’ fnormal int (disj bs f) := pred_disj _ prop_up_closed_fnormal meta def nnf_closed_fnormal_aux := `[unfold nnf, unfold fnormal, unfold fnormal at hn, cases hn with hnp hnq, cases (nnf_closed_fnormal_core hnp) with hnp1 hnp2, cases (nnf_closed_fnormal_core hnq) with hnq1 hnq2, apply and.intro; apply and.intro; assumption] lemma nnf_closed_fnormal_core : βˆ€ {p : fm lia.atom}, fnormal int p β†’ fnormal int (nnf int p) ∧ fnormal int (nnf int (Β¬' p)) | ⊀' hn := and.intro trivial trivial | βŠ₯' hn := and.intro trivial trivial | (A' a) hn := begin unfold nnf, apply and.intro, apply hn, rewrite fnormal_iff_fnormal_alt, apply atom_type.neg_prsv_normal, apply hn end | (p ∧' q) hn := by nnf_closed_fnormal_aux | (p ∨' q) hn := by nnf_closed_fnormal_aux | (Β¬' p) hn := begin apply and.symm, unfold fnormal at hn, unfold nnf, apply nnf_closed_fnormal_core hn end | (βˆƒ' p) hn := begin unfold nnf, apply and.intro; trivial end lemma nnf_closed_fnormal : preserves (@nnf lia.atom int _) (fnormal int) := Ξ» p hn, (nnf_closed_fnormal_core hn)^.elim_left lemma atoms_and_o_subset {p q : fm lia.atom} : atoms (and_o p q) βŠ† atoms p βˆͺ atoms q := begin apply cases_and_o' (Ξ» p' q' r, atoms r βŠ† atoms p' βˆͺ atoms q') p q; intros a ha, apply list.mem_union_right, apply ha, apply list.mem_union_left, apply ha, apply list.mem_union_left, apply ha, apply list.mem_union_right, apply ha, apply ha end lemma lnq_closed_fnormal (f : fm atom β†’ fm atom) (hc : preserves f (fnormal β„€)) : preserves (lift_nnf_qe β„€ f) (fnormal β„€) | ⊀' hn := trivial | βŠ₯' hn := trivial | (A' a) hn := by {unfold lift_nnf_qe, apply hn} | (p ∧' q) hn := begin unfold fnormal at hn , cases hn with hnp hnq, unfold lift_nnf_qe, apply cases_and_o, trivial, apply lnq_closed_fnormal, apply hnp, apply lnq_closed_fnormal, apply hnq, apply and.intro; apply lnq_closed_fnormal; assumption, end | (p ∨' q) hn := begin unfold fnormal at hn , cases hn with hnp hnq, unfold lift_nnf_qe, apply cases_or_o, trivial, apply lnq_closed_fnormal, apply hnp, apply lnq_closed_fnormal, apply hnq, apply and.intro; apply lnq_closed_fnormal; assumption, end | (Β¬' p) hn := begin unfold fnormal at hn, unfold lift_nnf_qe, apply cases_not_o, trivial, trivial, apply lnq_closed_fnormal, apply hn end | (βˆƒ' p) hn := begin unfold lift_nnf_qe, apply hc, apply nnf_closed_fnormal, apply lnq_closed_fnormal, apply hn end theorem lnq_prsv (qe : fm lia.atom β†’ fm lia.atom) (hqe : preserves qe (fnormal int)) (hqf : qfree_res_of_nqfree_arg qe) (hi : βˆ€ p, nqfree p β†’ fnormal int p β†’ βˆ€ (bs : list int), I (qe p) bs ↔ βˆƒ b, (I p (b::bs))) : βˆ€ p, fnormal int p β†’ βˆ€ (bs : list int), I (lift_nnf_qe int qe p) bs ↔ I p bs := @lnq_prsv_gen lia.atom int lia.atom_type qe hqf (fnormal int) down_closed_fnormal hqe nnf_closed_fnormal lnq_closed_fnormal hi theorem ldq_prsv (qe : list lia.atom β†’ fm lia.atom) (hqf : βˆ€ as, (βˆ€ a ∈ as, dep0 a) β†’ qfree (qe as)) (hn : βˆ€ as, (βˆ€ a ∈ as, dep0 a) β†’ (βˆ€ a ∈ as, normal a) β†’ fnormal int (qe as)) (he : βˆ€ as, (βˆ€ a ∈ as, dep0 a) β†’ (βˆ€ a ∈ as, normal a) β†’ qe_prsv int qe as) : βˆ€ p, fnormal int p β†’ βˆ€ (bs : list int), I (lift_dnf_qe int qe p) bs ↔ I p bs := @ldq_prsv_gen lia.atom int lia.atom_type _ hqf hn he end lia
14f30052864407dd58e47896dd25fcb89da06e8e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/multilinear.lean
52658d431157afad6fa6afc8694cf3714cd403d7
[ "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
54,408
lean
/- Copyright (c) 2020 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: SΓ©bastien GouΓ«zel -/ import linear_algebra.basic import algebra.algebra.basic import algebra.big_operators.order import data.fintype.sort /-! # Multilinear maps We define multilinear maps as maps from `Ξ (i : ΞΉ), M₁ i` to `Mβ‚‚` which are linear in each coordinate. Here, `M₁ i` and `Mβ‚‚` are modules over a ring `R`, and `ΞΉ` is an arbitrary type (although some statements will require it to be a fintype). This space, denoted by `multilinear_map R M₁ Mβ‚‚`, inherits a module structure by pointwise addition and multiplication. ## Main definitions * `multilinear_map R M₁ Mβ‚‚` is the space of multilinear maps from `Ξ (i : ΞΉ), M₁ i` to `Mβ‚‚`. * `f.map_smul` is the multiplicativity of the multilinear map `f` along each coordinate. * `f.map_add` is the additivity of the multilinear map `f` along each coordinate. * `f.map_smul_univ` expresses the multiplicativity of `f` over all coordinates at the same time, writing `f (Ξ»i, c i β€’ m i)` as `(∏ i, c i) β€’ f m`. * `f.map_add_univ` expresses the additivity of `f` over all coordinates at the same time, writing `f (m + m')` as the sum over all subsets `s` of `ΞΉ` of `f (s.piecewise m m')`. * `f.map_sum` expresses `f (Ξ£_{j₁} g₁ j₁, ..., Ξ£_{jβ‚™} gβ‚™ jβ‚™)` as the sum of `f (g₁ (r 1), ..., gβ‚™ (r n))` where `r` ranges over all possible functions. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a multilinear function `f` on `n+1` variables into a linear function taking values in multilinear functions in `n` variables, and into a multilinear function in `n` variables taking values in linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). These operations induce linear equivalences between spaces of multilinear functions in `n+1` variables and spaces of linear functions into multilinear functions in `n` variables (resp. multilinear functions in `n` variables taking values in linear functions), called respectively `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. ## Implementation notes Expressing that a map is linear along the `i`-th coordinate when all other coordinates are fixed can be done in two (equivalent) different ways: * fixing a vector `m : Ξ (j : ΞΉ - i), M₁ j.val`, and then choosing separately the `i`-th coordinate * fixing a vector `m : Ξ j, M₁ j`, and then modifying its `i`-th coordinate The second way is more artificial as the value of `m` at `i` is not relevant, but it has the advantage of avoiding subtype inclusion issues. This is the definition we use, based on `function.update` that allows to change the value of `m` at `i`. -/ open function fin set open_locale big_operators universes u v v' v₁ vβ‚‚ v₃ w u' variables {R : Type u} {ΞΉ : Type u'} {n : β„•} {M : fin n.succ β†’ Type v} {M₁ : ΞΉ β†’ Type v₁} {Mβ‚‚ : Type vβ‚‚} {M₃ : Type v₃} {M' : Type v'} [decidable_eq ΞΉ] /-- Multilinear maps over the ring `R`, from `Ξ i, M₁ i` to `Mβ‚‚` where `M₁ i` and `Mβ‚‚` are modules over `R`. -/ structure multilinear_map (R : Type u) {ΞΉ : Type u'} (M₁ : ΞΉ β†’ Type v) (Mβ‚‚ : Type w) [decidable_eq ΞΉ] [semiring R] [βˆ€i, add_comm_monoid (M₁ i)] [add_comm_monoid Mβ‚‚] [βˆ€i, module R (M₁ i)] [module R Mβ‚‚] := (to_fun : (Ξ i, M₁ i) β†’ Mβ‚‚) (map_add' : βˆ€(m : Ξ i, M₁ i) (i : ΞΉ) (x y : M₁ i), to_fun (update m i (x + y)) = to_fun (update m i x) + to_fun (update m i y)) (map_smul' : βˆ€(m : Ξ i, M₁ i) (i : ΞΉ) (c : R) (x : M₁ i), to_fun (update m i (c β€’ x)) = c β€’ to_fun (update m i x)) namespace multilinear_map section semiring variables [semiring R] [βˆ€i, add_comm_monoid (M i)] [βˆ€i, add_comm_monoid (M₁ i)] [add_comm_monoid Mβ‚‚] [add_comm_monoid M₃] [add_comm_monoid M'] [βˆ€i, module R (M i)] [βˆ€i, module R (M₁ i)] [module R Mβ‚‚] [module R M₃] [module R M'] (f f' : multilinear_map R M₁ Mβ‚‚) instance : has_coe_to_fun (multilinear_map R M₁ Mβ‚‚) := ⟨_, to_fun⟩ initialize_simps_projections multilinear_map (to_fun β†’ apply) @[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl @[simp] lemma coe_mk (f : (Ξ  i, M₁ i) β†’ Mβ‚‚) (h₁ hβ‚‚ ) : ⇑(⟨f, h₁, hβ‚‚βŸ© : multilinear_map R M₁ Mβ‚‚) = f := rfl theorem congr_fun {f g : multilinear_map R M₁ Mβ‚‚} (h : f = g) (x : Ξ  i, M₁ i) : f x = g x := congr_arg (Ξ» h : multilinear_map R M₁ Mβ‚‚, h x) h theorem congr_arg (f : multilinear_map R M₁ Mβ‚‚) {x y : Ξ  i, M₁ i} (h : x = y) : f x = f y := congr_arg (Ξ» x : Ξ  i, M₁ i, f x) h theorem coe_inj ⦃f g : multilinear_map R M₁ M₂⦄ (h : ⇑f = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext {f f' : multilinear_map R M₁ Mβ‚‚} (H : βˆ€ x, f x = f' x) : f = f' := coe_inj (funext H) theorem ext_iff {f g : multilinear_map R M₁ Mβ‚‚} : f = g ↔ βˆ€ x, f x = g x := ⟨λ h x, h β–Έ rfl, Ξ» h, ext h⟩ @[simp] lemma map_add (m : Ξ i, M₁ i) (i : ΞΉ) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.map_add' m i x y @[simp] lemma map_smul (m : Ξ i, M₁ i) (i : ΞΉ) (c : R) (x : M₁ i) : f (update m i (c β€’ x)) = c β€’ f (update m i x) := f.map_smul' m i c x lemma map_coord_zero {m : Ξ i, M₁ i} (i : ΞΉ) (h : m i = 0) : f m = 0 := begin have : (0 : R) β€’ (0 : M₁ i) = 0, by simp, rw [← update_eq_self i m, h, ← this, f.map_smul, zero_smul] end @[simp] lemma map_update_zero (m : Ξ i, M₁ i) (i : ΞΉ) : f (update m i 0) = 0 := f.map_coord_zero i (update_same i 0 m) @[simp] lemma map_zero [nonempty ΞΉ] : f 0 = 0 := begin obtain ⟨i, _⟩ : βˆƒi:ΞΉ, i ∈ set.univ := set.exists_mem_of_nonempty ΞΉ, exact map_coord_zero f i rfl end instance : has_add (multilinear_map R M₁ Mβ‚‚) := ⟨λf f', ⟨λx, f x + f' x, Ξ»m i x y, by simp [add_left_comm, add_assoc], Ξ»m i c x, by simp [smul_add]⟩⟩ @[simp] lemma add_apply (m : Ξ i, M₁ i) : (f + f') m = f m + f' m := rfl instance : has_zero (multilinear_map R M₁ Mβ‚‚) := ⟨⟨λ _, 0, Ξ»m i x y, by simp, Ξ»m i c x, by simp⟩⟩ instance : inhabited (multilinear_map R M₁ Mβ‚‚) := ⟨0⟩ @[simp] lemma zero_apply (m : Ξ i, M₁ i) : (0 : multilinear_map R M₁ Mβ‚‚) m = 0 := rfl instance : add_comm_monoid (multilinear_map R M₁ Mβ‚‚) := { zero := (0 : multilinear_map R M₁ Mβ‚‚), add := (+), add_assoc := by intros; ext; simp [add_comm, add_left_comm], zero_add := by intros; ext; simp [add_comm, add_left_comm], add_zero := by intros; ext; simp [add_comm, add_left_comm], add_comm := by intros; ext; simp [add_comm, add_left_comm], nsmul := Ξ» n f, ⟨λ m, n β€’ f m, Ξ»m i x y, by simp [smul_add], Ξ»l i x d, by simp [←smul_comm x n] ⟩, nsmul_zero' := Ξ» f, by { ext, simp }, nsmul_succ' := Ξ» n f, by { ext, simp [add_smul, nat.succ_eq_one_add] } } @[simp] lemma sum_apply {Ξ± : Type*} (f : Ξ± β†’ multilinear_map R M₁ Mβ‚‚) (m : Ξ i, M₁ i) : βˆ€ {s : finset Ξ±}, (βˆ‘ a in s, f a) m = βˆ‘ a in s, f a m := begin classical, apply finset.induction, { rw finset.sum_empty, simp }, { assume a s has H, rw finset.sum_insert has, simp [H, has] } end /-- If `f` is a multilinear map, then `f.to_linear_map m i` is the linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_linear_map (m : Ξ i, M₁ i) (i : ΞΉ) : M₁ i β†’β‚—[R] Mβ‚‚ := { to_fun := Ξ»x, f (update m i x), map_add' := Ξ»x y, by simp, map_smul' := Ξ»c x, by simp } /-- The cartesian product of two multilinear maps, as a multilinear map. -/ def prod (f : multilinear_map R M₁ Mβ‚‚) (g : multilinear_map R M₁ M₃) : multilinear_map R M₁ (Mβ‚‚ Γ— M₃) := { to_fun := Ξ» m, (f m, g m), map_add' := Ξ» m i x y, by simp, map_smul' := Ξ» m i c x, by simp } /-- Combine a family of multilinear maps with the same domain and codomains `M' i` into a multilinear map taking values in the space of functions `Ξ  i, M' i`. -/ @[simps] def pi {ΞΉ' : Type*} {M' : ΞΉ' β†’ Type*} [Ξ  i, add_comm_monoid (M' i)] [Ξ  i, module R (M' i)] (f : Ξ  i, multilinear_map R M₁ (M' i)) : multilinear_map R M₁ (Ξ  i, M' i) := { to_fun := Ξ» m i, f i m, map_add' := Ξ» m i x y, funext $ Ξ» j, (f j).map_add _ _ _ _, map_smul' := Ξ» m i c x, funext $ Ξ» j, (f j).map_smul _ _ _ _ } /-- Given a multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ def restr {k n : β„•} (f : multilinear_map R (Ξ» i : fin n, M') Mβ‚‚) (s : finset (fin n)) (hk : s.card = k) (z : M') : multilinear_map R (Ξ» i : fin k, M') Mβ‚‚ := { to_fun := Ξ» v, f (Ξ» j, if h : j ∈ s then v ((s.order_iso_of_fin hk).symm ⟨j, h⟩) else z), map_add' := Ξ» v i x y, by { erw [dite_comp_equiv_update, dite_comp_equiv_update, dite_comp_equiv_update], simp }, map_smul' := Ξ» v i c x, by { erw [dite_comp_equiv_update, dite_comp_equiv_update], simp } } variable {R} /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Ξ (i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : multilinear_map R M Mβ‚‚) (m : Ξ (i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := by rw [← update_cons_zero x m (x+y), f.map_add, update_cons_zero, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Ξ (i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : multilinear_map R M Mβ‚‚) (m : Ξ (i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c β€’ x) m) = c β€’ f (cons x m) := by rw [← update_cons_zero x m (c β€’ x), f.map_smul, update_cons_zero] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Ξ (i : fin (n+1)), M i` using `snoc`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma snoc_add (f : multilinear_map R M Mβ‚‚) (m : Ξ (i : fin n), M i.cast_succ) (x y : M (last n)) : f (snoc m (x+y)) = f (snoc m x) + f (snoc m y) := by rw [← update_snoc_last x m (x+y), f.map_add, update_snoc_last, update_snoc_last] /-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Ξ (i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma snoc_smul (f : multilinear_map R M Mβ‚‚) (m : Ξ (i : fin n), M i.cast_succ) (c : R) (x : M (last n)) : f (snoc m (c β€’ x)) = c β€’ f (snoc m x) := by rw [← update_snoc_last x m (c β€’ x), f.map_smul, update_snoc_last] section variables {M₁' : ΞΉ β†’ Type*} [Ξ  i, add_comm_monoid (M₁' i)] [Ξ  i, module R (M₁' i)] /-- If `g` is a multilinear map and `f` is a collection of linear maps, then `g (f₁ m₁, ..., fβ‚™ mβ‚™)` is again a multilinear map, that we call `g.comp_linear_map f`. -/ def comp_linear_map (g : multilinear_map R M₁' Mβ‚‚) (f : Ξ  i, M₁ i β†’β‚—[R] M₁' i) : multilinear_map R M₁ Mβ‚‚ := { to_fun := Ξ» m, g $ Ξ» i, f i (m i), map_add' := Ξ» m i x y, have βˆ€ j z, f j (update m i z j) = update (Ξ» k, f k (m k)) i (f i z) j := Ξ» j z, function.apply_update (Ξ» k, f k) _ _ _ _, by simp [this], map_smul' := Ξ» m i c x, have βˆ€ j z, f j (update m i z j) = update (Ξ» k, f k (m k)) i (f i z) j := Ξ» j z, function.apply_update (Ξ» k, f k) _ _ _ _, by simp [this] } @[simp] lemma comp_linear_map_apply (g : multilinear_map R M₁' Mβ‚‚) (f : Ξ  i, M₁ i β†’β‚—[R] M₁' i) (m : Ξ  i, M₁ i) : g.comp_linear_map f m = g (Ξ» i, f i (m i)) := rfl end /-- If one adds to a vector `m'` another vector `m`, but only for coordinates in a finset `t`, then the image under a multilinear map `f` is the sum of `f (s.piecewise m m')` along all subsets `s` of `t`. This is mainly an auxiliary statement to prove the result when `t = univ`, given in `map_add_univ`, although it can be useful in its own right as it does not require the index set `ΞΉ` to be finite.-/ lemma map_piecewise_add (m m' : Ξ i, M₁ i) (t : finset ΞΉ) : f (t.piecewise (m + m') m') = βˆ‘ s in t.powerset, f (s.piecewise m m') := begin revert m', refine finset.induction_on t (by simp) _, assume i t hit Hrec m', have A : (insert i t).piecewise (m + m') m' = update (t.piecewise (m + m') m') i (m i + m' i) := t.piecewise_insert _ _ _, have B : update (t.piecewise (m + m') m') i (m' i) = t.piecewise (m + m') m', { ext j, by_cases h : j = i, { rw h, simp [hit] }, { simp [h] } }, let m'' := update m' i (m i), have C : update (t.piecewise (m + m') m') i (m i) = t.piecewise (m + m'') m'', { ext j, by_cases h : j = i, { rw h, simp [m'', hit] }, { by_cases h' : j ∈ t; simp [h, hit, m'', h'] } }, rw [A, f.map_add, B, C, finset.sum_powerset_insert hit, Hrec, Hrec, add_comm], congr' 1, apply finset.sum_congr rfl (Ξ»s hs, _), have : (insert i s).piecewise m m' = s.piecewise m m'', { ext j, by_cases h : j = i, { rw h, simp [m'', finset.not_mem_of_mem_powerset_of_not_mem hs hit] }, { by_cases h' : j ∈ s; simp [h, m'', h'] } }, rw this end /-- Additivity of a multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ΞΉ] (m m' : Ξ i, M₁ i) : f (m + m') = βˆ‘ s : finset ΞΉ, f (s.piecewise m m') := by simpa using f.map_piecewise_add m m' finset.univ section apply_sum variables {Ξ± : ΞΉ β†’ Type*} (g : Ξ  i, Ξ± i β†’ M₁ i) (A : Ξ  i, finset (Ξ± i)) open_locale classical open fintype finset /-- If `f` is multilinear, then `f (Ξ£_{j₁ ∈ A₁} g₁ j₁, ..., Ξ£_{jβ‚™ ∈ Aβ‚™} gβ‚™ jβ‚™)` is the sum of `f (g₁ (r 1), ..., gβ‚™ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aβ‚™`. This follows from multilinearity by expanding successively with respect to each coordinate. Here, we give an auxiliary statement tailored for an inductive proof. Use instead `map_sum_finset`. -/ lemma map_sum_finset_aux [fintype ΞΉ] {n : β„•} (h : βˆ‘ i, (A i).card = n) : f (Ξ» i, βˆ‘ j in A i, g i j) = βˆ‘ r in pi_finset A, f (Ξ» i, g i (r i)) := begin induction n using nat.strong_induction_on with n IH generalizing A, -- If one of the sets is empty, then all the sums are zero by_cases Ai_empty : βˆƒ i, A i = βˆ…, { rcases Ai_empty with ⟨i, hi⟩, have : βˆ‘ j in A i, g i j = 0, by convert sum_empty, rw f.map_coord_zero i this, have : pi_finset A = βˆ…, { apply finset.eq_empty_of_forall_not_mem (Ξ» r hr, _), have : r i ∈ A i := mem_pi_finset.mp hr i, rwa hi at this }, convert sum_empty.symm }, push_neg at Ai_empty, -- Otherwise, if all sets are at most singletons, then they are exactly singletons and the result -- is again straightforward by_cases Ai_singleton : βˆ€ i, (A i).card ≀ 1, { have Ai_card : βˆ€ i, (A i).card = 1, { assume i, have pos : finset.card (A i) β‰  0, by simp [finset.card_eq_zero, Ai_empty i], have : finset.card (A i) ≀ 1 := Ai_singleton i, exact le_antisymm this (nat.succ_le_of_lt (_root_.pos_iff_ne_zero.mpr pos)) }, have : βˆ€ (r : Ξ  i, Ξ± i), r ∈ pi_finset A β†’ f (Ξ» i, g i (r i)) = f (Ξ» i, βˆ‘ j in A i, g i j), { assume r hr, unfold_coes, congr' with i, have : βˆ€ j ∈ A i, g i j = g i (r i), { assume j hj, congr, apply finset.card_le_one_iff.1 (Ai_singleton i) hj, exact mem_pi_finset.mp hr i }, simp only [finset.sum_congr rfl this, finset.mem_univ, finset.sum_const, Ai_card i, one_nsmul] }, simp only [sum_congr rfl this, Ai_card, card_pi_finset, prod_const_one, one_nsmul, finset.sum_const] }, -- Remains the interesting case where one of the `A i`, say `A iβ‚€`, has cardinality at least 2. -- We will split into two parts `B iβ‚€` and `C iβ‚€` of smaller cardinality, let `B i = C i = A i` -- for `i β‰  iβ‚€`, apply the inductive assumption to `B` and `C`, and add up the corresponding -- parts to get the sum for `A`. push_neg at Ai_singleton, obtain ⟨iβ‚€, hiβ‚€βŸ© : βˆƒ i, 1 < (A i).card := Ai_singleton, obtain ⟨j₁, jβ‚‚, hj₁, hjβ‚‚, j₁_ne_jβ‚‚βŸ© : βˆƒ j₁ jβ‚‚, (j₁ ∈ A iβ‚€) ∧ (jβ‚‚ ∈ A iβ‚€) ∧ j₁ β‰  jβ‚‚ := finset.one_lt_card_iff.1 hiβ‚€, let B := function.update A iβ‚€ (A iβ‚€ \ {jβ‚‚}), let C := function.update A iβ‚€ {jβ‚‚}, have B_subset_A : βˆ€ i, B i βŠ† A i, { assume i, by_cases hi : i = iβ‚€, { rw hi, simp only [B, sdiff_subset, update_same]}, { simp only [hi, B, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, have C_subset_A : βˆ€ i, C i βŠ† A i, { assume i, by_cases hi : i = iβ‚€, { rw hi, simp only [C, hjβ‚‚, finset.singleton_subset_iff, update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff, finset.subset.refl] } }, -- split the sum at `iβ‚€` as the sum over `B iβ‚€` plus the sum over `C iβ‚€`, to use additivity. have A_eq_BC : (Ξ» i, βˆ‘ j in A i, g i j) = function.update (Ξ» i, βˆ‘ j in A i, g i j) iβ‚€ (βˆ‘ j in B iβ‚€, g iβ‚€ j + βˆ‘ j in C iβ‚€, g iβ‚€ j), { ext i, by_cases hi : i = iβ‚€, { rw [hi], simp only [function.update_same], have : A iβ‚€ = B iβ‚€ βˆͺ C iβ‚€, { simp only [B, C, function.update_same, finset.sdiff_union_self_eq_union], symmetry, simp only [hjβ‚‚, finset.singleton_subset_iff, union_eq_left_iff_subset] }, rw this, apply finset.sum_union, apply finset.disjoint_right.2 (Ξ» j hj, _), have : j = jβ‚‚, by { dsimp [C] at hj, simpa using hj }, rw this, dsimp [B], simp only [mem_sdiff, eq_self_iff_true, not_true, not_false_iff, finset.mem_singleton, update_same, and_false] }, { simp [hi] } }, have Beq : function.update (Ξ» i, βˆ‘ j in A i, g i j) iβ‚€ (βˆ‘ j in B iβ‚€, g iβ‚€ j) = (Ξ» i, βˆ‘ j in B i, g i j), { ext i, by_cases hi : i = iβ‚€, { rw hi, simp only [update_same] }, { simp only [hi, B, update_noteq, ne.def, not_false_iff] } }, have Ceq : function.update (Ξ» i, βˆ‘ j in A i, g i j) iβ‚€ (βˆ‘ j in C iβ‚€, g iβ‚€ j) = (Ξ» i, βˆ‘ j in C i, g i j), { ext i, by_cases hi : i = iβ‚€, { rw hi, simp only [update_same] }, { simp only [hi, C, update_noteq, ne.def, not_false_iff] } }, -- Express the inductive assumption for `B` have Brec : f (Ξ» i, βˆ‘ j in B i, g i j) = βˆ‘ r in pi_finset B, f (Ξ» i, g i (r i)), { have : βˆ‘ i, finset.card (B i) < βˆ‘ i, finset.card (A i), { refine finset.sum_lt_sum (Ξ» i hi, finset.card_le_of_subset (B_subset_A i)) ⟨iβ‚€, finset.mem_univ _, _⟩, have : {jβ‚‚} βŠ† A iβ‚€, by simp [hjβ‚‚], simp only [B, finset.card_sdiff this, function.update_same, finset.card_singleton], exact nat.pred_lt (ne_of_gt (lt_trans nat.zero_lt_one hiβ‚€)) }, rw h at this, exact IH _ this B rfl }, -- Express the inductive assumption for `C` have Crec : f (Ξ» i, βˆ‘ j in C i, g i j) = βˆ‘ r in pi_finset C, f (Ξ» i, g i (r i)), { have : βˆ‘ i, finset.card (C i) < βˆ‘ i, finset.card (A i) := finset.sum_lt_sum (Ξ» i hi, finset.card_le_of_subset (C_subset_A i)) ⟨iβ‚€, finset.mem_univ _, by simp [C, hiβ‚€]⟩, rw h at this, exact IH _ this C rfl }, have D : disjoint (pi_finset B) (pi_finset C), { have : disjoint (B iβ‚€) (C iβ‚€), by simp [B, C], exact pi_finset_disjoint_of_disjoint B C this }, have pi_BC : pi_finset A = pi_finset B βˆͺ pi_finset C, { apply finset.subset.antisymm, { assume r hr, by_cases hriβ‚€ : r iβ‚€ = jβ‚‚, { apply finset.mem_union_right, apply mem_pi_finset.2 (Ξ» i, _), by_cases hi : i = iβ‚€, { have : r iβ‚€ ∈ C iβ‚€, by simp [C, hriβ‚€], convert this }, { simp [C, hi, mem_pi_finset.1 hr i] } }, { apply finset.mem_union_left, apply mem_pi_finset.2 (Ξ» i, _), by_cases hi : i = iβ‚€, { have : r iβ‚€ ∈ B iβ‚€, by simp [B, hriβ‚€, mem_pi_finset.1 hr iβ‚€], convert this }, { simp [B, hi, mem_pi_finset.1 hr i] } } }, { exact finset.union_subset (pi_finset_subset _ _ (Ξ» i, B_subset_A i)) (pi_finset_subset _ _ (Ξ» i, C_subset_A i)) } }, rw A_eq_BC, simp only [multilinear_map.map_add, Beq, Ceq, Brec, Crec, pi_BC], rw ← finset.sum_union D, end /-- If `f` is multilinear, then `f (Ξ£_{j₁ ∈ A₁} g₁ j₁, ..., Ξ£_{jβ‚™ ∈ Aβ‚™} gβ‚™ jβ‚™)` is the sum of `f (g₁ (r 1), ..., gβ‚™ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aβ‚™`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset [fintype ΞΉ] : f (Ξ» i, βˆ‘ j in A i, g i j) = βˆ‘ r in pi_finset A, f (Ξ» i, g i (r i)) := f.map_sum_finset_aux _ _ rfl /-- If `f` is multilinear, then `f (Ξ£_{j₁} g₁ j₁, ..., Ξ£_{jβ‚™} gβ‚™ jβ‚™)` is the sum of `f (g₁ (r 1), ..., gβ‚™ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [fintype ΞΉ] [βˆ€ i, fintype (Ξ± i)] : f (Ξ» i, βˆ‘ j, g i j) = βˆ‘ r : Ξ  i, Ξ± i, f (Ξ» i, g i (r i)) := f.map_sum_finset g (Ξ» i, finset.univ) lemma map_update_sum {Ξ± : Type*} (t : finset Ξ±) (i : ΞΉ) (g : Ξ± β†’ M₁ i) (m : Ξ  i, M₁ i): f (update m i (βˆ‘ a in t, g a)) = βˆ‘ a in t, f (update m i (g a)) := begin induction t using finset.induction with a t has ih h, { simp }, { simp [finset.sum_insert has, ih] } end end apply_sum section restrict_scalar variables (R) {A : Type*} [semiring A] [has_scalar R A] [Ξ  (i : ΞΉ), module A (M₁ i)] [module A Mβ‚‚] [βˆ€ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A Mβ‚‚] /-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R` and their actions on all involved modules agree with the action of `R` on `A`. -/ def restrict_scalars (f : multilinear_map A M₁ Mβ‚‚) : multilinear_map R M₁ Mβ‚‚ := { to_fun := f, map_add' := f.map_add, map_smul' := Ξ» m i, (f.to_linear_map m i).map_smul_of_tower } @[simp] lemma coe_restrict_scalars (f : multilinear_map A M₁ Mβ‚‚) : ⇑(f.restrict_scalars R) = f := rfl end restrict_scalar section variables {ι₁ ΞΉβ‚‚ ι₃ : Type*} [decidable_eq ι₁] [decidable_eq ΞΉβ‚‚] [decidable_eq ι₃] /-- Transfer the arguments to a map along an equivalence between argument indices. The naming is derived from `finsupp.dom_congr`, noting that here the permutation applies to the domain of the domain. -/ @[simps apply] def dom_dom_congr (Οƒ : ι₁ ≃ ΞΉβ‚‚) (m : multilinear_map R (Ξ» i : ι₁, Mβ‚‚) M₃) : multilinear_map R (Ξ» i : ΞΉβ‚‚, Mβ‚‚) M₃ := { to_fun := Ξ» v, m (Ξ» i, v (Οƒ i)), map_add' := Ξ» v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_add, }, map_smul' := Ξ» v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_smul, }, } lemma dom_dom_congr_trans (σ₁ : ι₁ ≃ ΞΉβ‚‚) (Οƒβ‚‚ : ΞΉβ‚‚ ≃ ι₃) (m : multilinear_map R (Ξ» i : ι₁, Mβ‚‚) M₃) : m.dom_dom_congr (σ₁.trans Οƒβ‚‚) = (m.dom_dom_congr σ₁).dom_dom_congr Οƒβ‚‚ := rfl lemma dom_dom_congr_mul (σ₁ : equiv.perm ι₁) (Οƒβ‚‚ : equiv.perm ι₁) (m : multilinear_map R (Ξ» i : ι₁, Mβ‚‚) M₃) : m.dom_dom_congr (Οƒβ‚‚ * σ₁) = (m.dom_dom_congr σ₁).dom_dom_congr Οƒβ‚‚ := rfl /-- `multilinear_map.dom_dom_congr` as an equivalence. This is declared separately because it does not work with dot notation. -/ @[simps apply symm_apply] def dom_dom_congr_equiv (Οƒ : ι₁ ≃ ΞΉβ‚‚) : multilinear_map R (Ξ» i : ι₁, Mβ‚‚) M₃ ≃+ multilinear_map R (Ξ» i : ΞΉβ‚‚, Mβ‚‚) M₃ := { to_fun := dom_dom_congr Οƒ, inv_fun := dom_dom_congr Οƒ.symm, left_inv := Ξ» m, by {ext, simp}, right_inv := Ξ» m, by {ext, simp}, map_add' := Ξ» a b, by {ext, simp} } end end semiring end multilinear_map namespace linear_map variables [semiring R] [Ξ i, add_comm_monoid (M₁ i)] [add_comm_monoid Mβ‚‚] [add_comm_monoid M₃] [add_comm_monoid M'] [βˆ€i, module R (M₁ i)] [module R Mβ‚‚] [module R M₃] [module R M'] /-- Composing a multilinear map with a linear map gives again a multilinear map. -/ def comp_multilinear_map (g : Mβ‚‚ β†’β‚—[R] M₃) (f : multilinear_map R M₁ Mβ‚‚) : multilinear_map R M₁ M₃ := { to_fun := g ∘ f, map_add' := Ξ» m i x y, by simp, map_smul' := Ξ» m i c x, by simp } @[simp] lemma coe_comp_multilinear_map (g : Mβ‚‚ β†’β‚—[R] M₃) (f : multilinear_map R M₁ Mβ‚‚) : ⇑(g.comp_multilinear_map f) = g ∘ f := rfl lemma comp_multilinear_map_apply (g : Mβ‚‚ β†’β‚—[R] M₃) (f : multilinear_map R M₁ Mβ‚‚) (m : Ξ  i, M₁ i) : g.comp_multilinear_map f m = g (f m) := rfl variables {ι₁ ΞΉβ‚‚ : Type*} [decidable_eq ι₁] [decidable_eq ΞΉβ‚‚] @[simp] lemma comp_multilinear_map_dom_dom_congr (Οƒ : ι₁ ≃ ΞΉβ‚‚) (g : Mβ‚‚ β†’β‚—[R] M₃) (f : multilinear_map R (Ξ» i : ι₁, M') Mβ‚‚) : (g.comp_multilinear_map f).dom_dom_congr Οƒ = g.comp_multilinear_map (f.dom_dom_congr Οƒ) := by { ext, simp } end linear_map namespace multilinear_map section comm_semiring variables [comm_semiring R] [βˆ€i, add_comm_monoid (M₁ i)] [βˆ€i, add_comm_monoid (M i)] [add_comm_monoid Mβ‚‚] [βˆ€i, module R (M i)] [βˆ€i, module R (M₁ i)] [module R Mβ‚‚] (f f' : multilinear_map R M₁ Mβ‚‚) /-- If one multiplies by `c i` the coordinates in a finset `s`, then the image under a multilinear map is multiplied by `∏ i in s, c i`. This is mainly an auxiliary statement to prove the result when `s = univ`, given in `map_smul_univ`, although it can be useful in its own right as it does not require the index set `ΞΉ` to be finite. -/ lemma map_piecewise_smul (c : ΞΉ β†’ R) (m : Ξ i, M₁ i) (s : finset ΞΉ) : f (s.piecewise (Ξ»i, c i β€’ m i) m) = (∏ i in s, c i) β€’ f m := begin refine s.induction_on (by simp) _, assume j s j_not_mem_s Hrec, have A : function.update (s.piecewise (Ξ»i, c i β€’ m i) m) j (m j) = s.piecewise (Ξ»i, c i β€’ m i) m, { ext i, by_cases h : i = j, { rw h, simp [j_not_mem_s] }, { simp [h] } }, rw [s.piecewise_insert, f.map_smul, A, Hrec], simp [j_not_mem_s, mul_smul] end /-- Multiplicativity of a multilinear map along all coordinates at the same time, writing `f (Ξ»i, c i β€’ m i)` as `(∏ i, c i) β€’ f m`. -/ lemma map_smul_univ [fintype ΞΉ] (c : ΞΉ β†’ R) (m : Ξ i, M₁ i) : f (Ξ»i, c i β€’ m i) = (∏ i, c i) β€’ f m := by simpa using map_piecewise_smul f c m finset.univ section distrib_mul_action variables {R' A : Type*} [monoid R'] [semiring A] [Ξ  i, module A (M₁ i)] [distrib_mul_action R' Mβ‚‚] [module A Mβ‚‚] [smul_comm_class A R' Mβ‚‚] instance : has_scalar R' (multilinear_map A M₁ Mβ‚‚) := ⟨λ c f, ⟨λ m, c β€’ f m, Ξ»m i x y, by simp [smul_add], Ξ»l i x d, by simp [←smul_comm x c] ⟩⟩ @[simp] lemma smul_apply (f : multilinear_map A M₁ Mβ‚‚) (c : R') (m : Ξ i, M₁ i) : (c β€’ f) m = c β€’ f m := rfl instance : distrib_mul_action R' (multilinear_map A M₁ Mβ‚‚) := { one_smul := Ξ» f, ext $ Ξ» x, one_smul _ _, mul_smul := Ξ» c₁ cβ‚‚ f, ext $ Ξ» x, mul_smul _ _ _, smul_zero := Ξ» r, ext $ Ξ» x, smul_zero _, smul_add := Ξ» r f₁ fβ‚‚, ext $ Ξ» x, smul_add _ _ _ } end distrib_mul_action section module variables {R' A : Type*} [semiring R'] [semiring A] [Ξ  i, module A (M₁ i)] [module A Mβ‚‚] [add_comm_monoid M₃] [module R' M₃] [module A M₃] [smul_comm_class A R' M₃] /-- The space of multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance [module R' Mβ‚‚] [smul_comm_class A R' Mβ‚‚] : module R' (multilinear_map A M₁ Mβ‚‚) := { add_smul := Ξ» r₁ rβ‚‚ f, ext $ Ξ» x, add_smul _ _ _, zero_smul := Ξ» f, ext $ Ξ» x, zero_smul _ _ } variables (Mβ‚‚ M₃ R' A) /-- `multilinear_map.dom_dom_congr` as a `linear_equiv`. -/ @[simps apply symm_apply] def dom_dom_congr_linear_equiv {ι₁ ΞΉβ‚‚} [decidable_eq ι₁] [decidable_eq ΞΉβ‚‚] (Οƒ : ι₁ ≃ ΞΉβ‚‚) : multilinear_map A (Ξ» i : ι₁, Mβ‚‚) M₃ ≃ₗ[R'] multilinear_map A (Ξ» i : ΞΉβ‚‚, Mβ‚‚) M₃ := { map_smul' := Ξ» c f, by { ext, simp }, .. (dom_dom_congr_equiv Οƒ : multilinear_map A (Ξ» i : ι₁, Mβ‚‚) M₃ ≃+ multilinear_map A (Ξ» i : ΞΉβ‚‚, Mβ‚‚) M₃) } end module section dom_coprod open_locale tensor_product variables {ι₁ ΞΉβ‚‚ ι₃ ΞΉβ‚„ : Type*} variables [decidable_eq ι₁] [decidable_eq ΞΉβ‚‚][decidable_eq ι₃] [decidable_eq ΞΉβ‚„] variables {N₁ : Type*} [add_comm_monoid N₁] [module R N₁] variables {Nβ‚‚ : Type*} [add_comm_monoid Nβ‚‚] [module R Nβ‚‚] variables {N : Type*} [add_comm_monoid N] [module R N] /-- Given two multilinear maps `(ι₁ β†’ N) β†’ N₁` and `(ΞΉβ‚‚ β†’ N) β†’ Nβ‚‚`, this produces the map `(ι₁ βŠ• ΞΉβ‚‚ β†’ N) β†’ N₁ βŠ— Nβ‚‚` by taking the coproduct of the domain and the tensor product of the codomain. This can be thought of as combining `equiv.sum_arrow_equiv_prod_arrow.symm` with `tensor_product.map`, noting that the two operations can't be separated as the intermediate result is not a `multilinear_map`. While this can be generalized to work for dependent `Ξ  i : ι₁, N'₁ i` instead of `ι₁ β†’ N`, doing so introduces `sum.elim N'₁ N'β‚‚` types in the result which are difficult to work with and not defeq to the simple case defined here. See [this zulip thread]( https://leanprover.zulipchat.com/#narrow/stream/217875-Is-there.20code.20for.20X.3F/topic/Instances.20on.20.60sum.2Eelim.20A.20B.20i.60/near/218484619). -/ @[simps apply] def dom_coprod (a : multilinear_map R (Ξ» _ : ι₁, N) N₁) (b : multilinear_map R (Ξ» _ : ΞΉβ‚‚, N) Nβ‚‚) : multilinear_map R (Ξ» _ : ι₁ βŠ• ΞΉβ‚‚, N) (N₁ βŠ—[R] Nβ‚‚) := { to_fun := Ξ» v, a (Ξ» i, v (sum.inl i)) βŠ—β‚œ b (Ξ» i, v (sum.inr i)), map_add' := Ξ» v i p q, by cases i; simp [tensor_product.add_tmul, tensor_product.tmul_add], map_smul' := Ξ» v i c p, by cases i; simp [tensor_product.smul_tmul', tensor_product.tmul_smul] } /-- A more bundled version of `multilinear_map.dom_coprod` that maps `((ι₁ β†’ N) β†’ N₁) βŠ— ((ΞΉβ‚‚ β†’ N) β†’ Nβ‚‚)` to `(ι₁ βŠ• ΞΉβ‚‚ β†’ N) β†’ N₁ βŠ— Nβ‚‚`. -/ def dom_coprod' : multilinear_map R (Ξ» _ : ι₁, N) N₁ βŠ—[R] multilinear_map R (Ξ» _ : ΞΉβ‚‚, N) Nβ‚‚ β†’β‚—[R] multilinear_map R (Ξ» _ : ι₁ βŠ• ΞΉβ‚‚, N) (N₁ βŠ—[R] Nβ‚‚) := tensor_product.lift $ linear_map.mkβ‚‚ R (dom_coprod) (Ξ» m₁ mβ‚‚ n, by { ext, simp only [dom_coprod_apply, tensor_product.add_tmul, add_apply] }) (Ξ» c m n, by { ext, simp only [dom_coprod_apply, tensor_product.smul_tmul', smul_apply] }) (Ξ» m n₁ nβ‚‚, by { ext, simp only [dom_coprod_apply, tensor_product.tmul_add, add_apply] }) (Ξ» c m n, by { ext, simp only [dom_coprod_apply, tensor_product.tmul_smul, smul_apply] }) @[simp] lemma dom_coprod'_apply (a : multilinear_map R (Ξ» _ : ι₁, N) N₁) (b : multilinear_map R (Ξ» _ : ΞΉβ‚‚, N) Nβ‚‚) : dom_coprod' (a βŠ—β‚œ[R] b) = dom_coprod a b := rfl /-- When passed an `equiv.sum_congr`, `multilinear_map.dom_dom_congr` distributes over `multilinear_map.dom_coprod`. -/ lemma dom_coprod_dom_dom_congr_sum_congr (a : multilinear_map R (Ξ» _ : ι₁, N) N₁) (b : multilinear_map R (Ξ» _ : ΞΉβ‚‚, N) Nβ‚‚) (Οƒa : ι₁ ≃ ι₃) (Οƒb : ΞΉβ‚‚ ≃ ΞΉβ‚„) : (a.dom_coprod b).dom_dom_congr (Οƒa.sum_congr Οƒb) = (a.dom_dom_congr Οƒa).dom_coprod (b.dom_dom_congr Οƒb) := rfl end dom_coprod section variables (R ΞΉ) (A : Type*) [comm_semiring A] [algebra R A] [fintype ΞΉ] /-- Given an `R`-algebra `A`, `mk_pi_algebra` is the multilinear map on `A^ΞΉ` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra_fin` for a version that works with a non-commutative algebra `A` but requires `ΞΉ = fin n`. -/ protected def mk_pi_algebra : multilinear_map R (Ξ» i : ΞΉ, A) A := { to_fun := Ξ» m, ∏ i, m i, map_add' := Ξ» m i x y, by simp [finset.prod_update_of_mem, add_mul], map_smul' := Ξ» m i c x, by simp [finset.prod_update_of_mem] } variables {R A ΞΉ} @[simp] lemma mk_pi_algebra_apply (m : ΞΉ β†’ A) : multilinear_map.mk_pi_algebra R ΞΉ A m = ∏ i, m i := rfl end section variables (R n) (A : Type*) [semiring A] [algebra R A] /-- Given an `R`-algebra `A`, `mk_pi_algebra_fin` is the multilinear map on `A^n` associating to `m` the product of all the `m i`. See also `multilinear_map.mk_pi_algebra` for a version that assumes `[comm_semiring A]` but works for `A^ΞΉ` with any finite type `ΞΉ`. -/ protected def mk_pi_algebra_fin : multilinear_map R (Ξ» i : fin n, A) A := { to_fun := Ξ» m, (list.of_fn m).prod, map_add' := begin intros m i x y, have : (list.fin_range n).index_of i < n, by simpa using list.index_of_lt_length.2 (list.mem_fin_range i), simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, add_mul, this, mul_add, add_mul] end, map_smul' := begin intros m i c x, have : (list.fin_range n).index_of i < n, by simpa using list.index_of_lt_length.2 (list.mem_fin_range i), simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, this] end } variables {R A n} @[simp] lemma mk_pi_algebra_fin_apply (m : fin n β†’ A) : multilinear_map.mk_pi_algebra_fin R n A m = (list.of_fn m).prod := rfl lemma mk_pi_algebra_fin_apply_const (a : A) : multilinear_map.mk_pi_algebra_fin R n A (Ξ» _, a) = a ^ n := by simp end /-- Given an `R`-multilinear map `f` taking values in `R`, `f.smul_right z` is the map sending `m` to `f m β€’ z`. -/ def smul_right (f : multilinear_map R M₁ R) (z : Mβ‚‚) : multilinear_map R M₁ Mβ‚‚ := (linear_map.smul_right linear_map.id z).comp_multilinear_map f @[simp] lemma smul_right_apply (f : multilinear_map R M₁ R) (z : Mβ‚‚) (m : Ξ  i, M₁ i) : f.smul_right z m = f m β€’ z := rfl variables (R ΞΉ) /-- The canonical multilinear map on `R^ΞΉ` when `ΞΉ` is finite, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module). See also `mk_pi_algebra` for a more general version. -/ protected def mk_pi_ring [fintype ΞΉ] (z : Mβ‚‚) : multilinear_map R (Ξ»(i : ΞΉ), R) Mβ‚‚ := (multilinear_map.mk_pi_algebra R ΞΉ R).smul_right z variables {R ΞΉ} @[simp] lemma mk_pi_ring_apply [fintype ΞΉ] (z : Mβ‚‚) (m : ΞΉ β†’ R) : (multilinear_map.mk_pi_ring R ΞΉ z : (ΞΉ β†’ R) β†’ Mβ‚‚) m = (∏ i, m i) β€’ z := rfl lemma mk_pi_ring_apply_one_eq_self [fintype ΞΉ] (f : multilinear_map R (Ξ»(i : ΞΉ), R) Mβ‚‚) : multilinear_map.mk_pi_ring R ΞΉ (f (Ξ»i, 1)) = f := begin ext m, have : m = (Ξ»i, m i β€’ 1), by { ext j, simp }, conv_rhs { rw [this, f.map_smul_univ] }, refl end end comm_semiring section range_add_comm_group variables [semiring R] [βˆ€i, add_comm_monoid (M₁ i)] [add_comm_group Mβ‚‚] [βˆ€i, module R (M₁ i)] [module R Mβ‚‚] (f g : multilinear_map R M₁ Mβ‚‚) instance : has_neg (multilinear_map R M₁ Mβ‚‚) := ⟨λ f, ⟨λ m, - f m, Ξ»m i x y, by simp [add_comm], Ξ»m i c x, by simp⟩⟩ @[simp] lemma neg_apply (m : Ξ i, M₁ i) : (-f) m = - (f m) := rfl instance : has_sub (multilinear_map R M₁ Mβ‚‚) := ⟨λ f g, ⟨λ m, f m - g m, Ξ» m i x y, by { simp only [map_add, sub_eq_add_neg, neg_add], cc }, Ξ» m i c x, by { simp only [map_smul, smul_sub] }⟩⟩ @[simp] lemma sub_apply (m : Ξ i, M₁ i) : (f - g) m = f m - g m := rfl instance : add_comm_group (multilinear_map R M₁ Mβ‚‚) := by refine { zero := (0 : multilinear_map R M₁ Mβ‚‚), add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, nsmul := Ξ» n f, ⟨λ m, n β€’ f m, Ξ»m i x y, by simp [smul_add], Ξ»l i x d, by simp [←smul_comm x n] ⟩, gsmul := Ξ» n f, ⟨λ m, n β€’ f m, Ξ»m i x y, by simp [smul_add], Ξ»l i x d, by simp [←smul_comm x n] ⟩, gsmul_zero' := _, gsmul_succ' := _, gsmul_neg' := _, .. multilinear_map.add_comm_monoid, .. }; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one] end range_add_comm_group section add_comm_group variables [semiring R] [βˆ€i, add_comm_group (M₁ i)] [add_comm_group Mβ‚‚] [βˆ€i, module R (M₁ i)] [module R Mβ‚‚] (f : multilinear_map R M₁ Mβ‚‚) @[simp] lemma map_neg (m : Ξ i, M₁ i) (i : ΞΉ) (x : M₁ i) : f (update m i (-x)) = -f (update m i x) := eq_neg_of_add_eq_zero $ by rw [←map_add, add_left_neg, f.map_coord_zero i (update_same i 0 m)] @[simp] lemma map_sub (m : Ξ i, M₁ i) (i : ΞΉ) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := by rw [sub_eq_add_neg, sub_eq_add_neg, map_add, map_neg] end add_comm_group section comm_semiring variables [comm_semiring R] [βˆ€i, add_comm_monoid (M₁ i)] [add_comm_monoid Mβ‚‚] [βˆ€i, module R (M₁ i)] [module R Mβ‚‚] /-- When `ΞΉ` is finite, multilinear maps on `R^ΞΉ` with values in `Mβ‚‚` are in bijection with `Mβ‚‚`, as such a multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `multilinear_map.pi_ring_equiv`. -/ protected def pi_ring_equiv [fintype ΞΉ] : Mβ‚‚ ≃ₗ[R] (multilinear_map R (Ξ»(i : ΞΉ), R) Mβ‚‚) := { to_fun := Ξ» z, multilinear_map.mk_pi_ring R ΞΉ z, inv_fun := Ξ» f, f (Ξ»i, 1), map_add' := Ξ» z z', by { ext m, simp [smul_add] }, map_smul' := Ξ» c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := Ξ» z, by simp, right_inv := Ξ» f, f.mk_pi_ring_apply_one_eq_self } end comm_semiring end multilinear_map section currying /-! ### Currying We associate to a multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a linear map on `E 0` taking values in multilinear maps in `n` variables) and `f.curry_right` (wich is a multilinear map in `n` variables taking values in linear maps on `E 0`). In both constructions, the variable that is singled out is `0`, to take advantage of the operations `cons` and `tail` on `fin n`. The inverse operations are called `uncurry_left` and `uncurry_right`. We also register linear equiv versions of these correspondences, in `multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`. -/ open multilinear_map variables {R M Mβ‚‚} [comm_semiring R] [βˆ€i, add_comm_monoid (M i)] [add_comm_monoid M'] [add_comm_monoid Mβ‚‚] [βˆ€i, module R (M i)] [module R M'] [module R Mβ‚‚] /-! #### Left currying -/ /-- Given a linear map `f` from `M 0` to multilinear maps on `n` variables, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def linear_map.uncurry_left (f : M 0 β†’β‚—[R] (multilinear_map R (Ξ»(i : fin n), M i.succ) Mβ‚‚)) : multilinear_map R M Mβ‚‚ := { to_fun := Ξ»m, f (m 0) (tail m), map_add' := Ξ»m i x y, begin by_cases h : i = 0, { subst i, rw [update_same, update_same, update_same, f.map_add, add_apply, tail_update_zero, tail_update_zero, tail_update_zero] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x y, rw ← succ_pred i h, assume x y, rw [tail_update_succ, map_add, tail_update_succ, tail_update_succ] } end, map_smul' := Ξ»m i c x, begin by_cases h : i = 0, { subst i, rw [update_same, update_same, tail_update_zero, tail_update_zero, ← smul_apply, f.map_smul] }, { rw [update_noteq (ne.symm h), update_noteq (ne.symm h)], revert x, rw ← succ_pred i h, assume x, rw [tail_update_succ, tail_update_succ, map_smul] } end } @[simp] lemma linear_map.uncurry_left_apply (f : M 0 β†’β‚—[R] (multilinear_map R (Ξ»(i : fin n), M i.succ) Mβ‚‚)) (m : Ξ i, M i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the first variable to obtain a linear map into multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def multilinear_map.curry_left (f : multilinear_map R M Mβ‚‚) : M 0 β†’β‚—[R] (multilinear_map R (Ξ»(i : fin n), M i.succ) Mβ‚‚) := { to_fun := Ξ»x, { to_fun := Ξ»m, f (cons x m), map_add' := Ξ»m i y y', by simp, map_smul' := Ξ»m i y c, by simp }, map_add' := Ξ»x y, by { ext m, exact cons_add f m x y }, map_smul' := Ξ»c x, by { ext m, exact cons_smul f m c x } } @[simp] lemma multilinear_map.curry_left_apply (f : multilinear_map R M Mβ‚‚) (x : M 0) (m : Ξ (i : fin n), M i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma linear_map.curry_uncurry_left (f : M 0 β†’β‚—[R] (multilinear_map R (Ξ»(i : fin n), M i.succ) Mβ‚‚)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, linear_map.uncurry_left_apply, multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma multilinear_map.uncurry_curry_left (f : multilinear_map R M Mβ‚‚) : f.curry_left.uncurry_left = f := by { ext m, simp, } variables (R M Mβ‚‚) /-- The space of multilinear maps on `Ξ (i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from `M 0` to the space of multilinear maps on `Ξ (i : fin n), M i.succ `, by separating the first variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_left_equiv R M Mβ‚‚`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_left_equiv : (M 0 β†’β‚—[R] (multilinear_map R (Ξ»(i : fin n), M i.succ) Mβ‚‚)) ≃ₗ[R] (multilinear_map R M Mβ‚‚) := { to_fun := linear_map.uncurry_left, map_add' := Ξ»f₁ fβ‚‚, by { ext m, refl }, map_smul' := Ξ»c f, by { ext m, refl }, inv_fun := multilinear_map.curry_left, left_inv := linear_map.curry_uncurry_left, right_inv := multilinear_map.uncurry_curry_left } variables {R M Mβ‚‚} /-! #### Right currying -/ /-- Given a multilinear map `f` in `n` variables to the space of linear maps from `M (last n)` to `Mβ‚‚`, construct the corresponding multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`-/ def multilinear_map.uncurry_right (f : (multilinear_map R (Ξ»(i : fin n), M i.cast_succ) (M (last n) β†’β‚—[R] Mβ‚‚))) : multilinear_map R M Mβ‚‚ := { to_fun := Ξ»m, f (init m) (m (last n)), map_add' := Ξ»m i x y, begin by_cases h : i.val < n, { have : last n β‰  i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this, update_noteq this], revert x y, rw [(cast_succ_cast_lt i h).symm], assume x y, rw [init_update_cast_succ, map_add, init_update_cast_succ, init_update_cast_succ, linear_map.add_apply] }, { revert x y, rw eq_last_of_not_lt h, assume x y, rw [init_update_last, init_update_last, init_update_last, update_same, update_same, update_same, linear_map.map_add] } end, map_smul' := Ξ»m i c x, begin by_cases h : i.val < n, { have : last n β‰  i := ne.symm (ne_of_lt h), rw [update_noteq this, update_noteq this], revert x, rw [(cast_succ_cast_lt i h).symm], assume x, rw [init_update_cast_succ, init_update_cast_succ, map_smul, linear_map.smul_apply] }, { revert x, rw eq_last_of_not_lt h, assume x, rw [update_same, update_same, init_update_last, init_update_last, linear_map.map_smul] } end } @[simp] lemma multilinear_map.uncurry_right_apply (f : (multilinear_map R (Ξ»(i : fin n), M i.cast_succ) ((M (last n)) β†’β‚—[R] Mβ‚‚))) (m : Ξ i, M i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a multilinear map `f` in `n+1` variables, split the last variable to obtain a multilinear map in `n` variables taking values in linear maps from `M (last n)` to `Mβ‚‚`, given by `m ↦ (x ↦ f (snoc m x))`. -/ def multilinear_map.curry_right (f : multilinear_map R M Mβ‚‚) : multilinear_map R (Ξ»(i : fin n), M (fin.cast_succ i)) ((M (last n)) β†’β‚—[R] Mβ‚‚) := { to_fun := Ξ»m, { to_fun := Ξ»x, f (snoc m x), map_add' := Ξ»x y, by rw f.snoc_add, map_smul' := Ξ»c x, by rw f.snoc_smul }, map_add' := Ξ»m i x y, begin ext z, change f (snoc (update m i (x + y)) z) = f (snoc (update m i x) z) + f (snoc (update m i y) z), rw [snoc_update, snoc_update, snoc_update, f.map_add] end, map_smul' := Ξ»m i c x, begin ext z, change f (snoc (update m i (c β€’ x)) z) = c β€’ f (snoc (update m i x) z), rw [snoc_update, snoc_update, f.map_smul] end } @[simp] lemma multilinear_map.curry_right_apply (f : multilinear_map R M Mβ‚‚) (m : Ξ (i : fin n), M i.cast_succ) (x : M (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma multilinear_map.curry_uncurry_right (f : (multilinear_map R (Ξ»(i : fin n), M i.cast_succ) ((M (last n)) β†’β‚—[R] Mβ‚‚))) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, multilinear_map.curry_right_apply, multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma multilinear_map.uncurry_curry_right (f : multilinear_map R M Mβ‚‚) : f.curry_right.uncurry_right = f := by { ext m, simp } variables (R M Mβ‚‚) /-- The space of multilinear maps on `Ξ (i : fin (n+1)), M i` is canonically isomorphic to the space of linear maps from the space of multilinear maps on `Ξ (i : fin n), M i.cast_succ` to the space of linear maps on `M (last n)`, by separating the last variable. We register this isomorphism as a linear isomorphism in `multilinear_curry_right_equiv R M Mβ‚‚`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear equivs. -/ def multilinear_curry_right_equiv : (multilinear_map R (Ξ»(i : fin n), M i.cast_succ) ((M (last n)) β†’β‚—[R] Mβ‚‚)) ≃ₗ[R] (multilinear_map R M Mβ‚‚) := { to_fun := multilinear_map.uncurry_right, map_add' := Ξ»f₁ fβ‚‚, by { ext m, refl }, map_smul' := Ξ»c f, by { ext m, rw [smul_apply], refl }, inv_fun := multilinear_map.curry_right, left_inv := multilinear_map.curry_uncurry_right, right_inv := multilinear_map.uncurry_curry_right } namespace multilinear_map variables {ΞΉ' : Type*} [decidable_eq ΞΉ'] [decidable_eq (ΞΉ βŠ• ΞΉ')] {R Mβ‚‚} /-- A multilinear map on `Ξ  i : ΞΉ βŠ• ΞΉ', M'` defines a multilinear map on `Ξ  i : ΞΉ, M'` taking values in the space of multilinear maps on `Ξ  i : ΞΉ', M'`. -/ def curry_sum (f : multilinear_map R (Ξ» x : ΞΉ βŠ• ΞΉ', M') Mβ‚‚) : multilinear_map R (Ξ» x : ΞΉ, M') (multilinear_map R (Ξ» x : ΞΉ', M') Mβ‚‚) := { to_fun := Ξ» u, { to_fun := Ξ» v, f (sum.elim u v), map_add' := Ξ» v i x y, by simp only [← sum.update_elim_inr, f.map_add], map_smul' := Ξ» v i c x, by simp only [← sum.update_elim_inr, f.map_smul] }, map_add' := Ξ» u i x y, ext $ Ξ» v, by simp only [multilinear_map.coe_mk, add_apply, ← sum.update_elim_inl, f.map_add], map_smul' := Ξ» u i c x, ext $ Ξ» v, by simp only [multilinear_map.coe_mk, smul_apply, ← sum.update_elim_inl, f.map_smul] } @[simp] lemma curry_sum_apply (f : multilinear_map R (Ξ» x : ΞΉ βŠ• ΞΉ', M') Mβ‚‚) (u : ΞΉ β†’ M') (v : ΞΉ' β†’ M') : f.curry_sum u v = f (sum.elim u v) := rfl /-- A multilinear map on `Ξ  i : ΞΉ, M'` taking values in the space of multilinear maps on `Ξ  i : ΞΉ', M'` defines a multilinear map on `Ξ  i : ΞΉ βŠ• ΞΉ', M'`. -/ def uncurry_sum (f : multilinear_map R (Ξ» x : ΞΉ, M') (multilinear_map R (Ξ» x : ΞΉ', M') Mβ‚‚)) : multilinear_map R (Ξ» x : ΞΉ βŠ• ΞΉ', M') Mβ‚‚ := { to_fun := Ξ» u, f (u ∘ sum.inl) (u ∘ sum.inr), map_add' := Ξ» u i x y, by cases i; simp only [map_add, add_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr, sum.update_inr_comp_inl, sum.update_inr_comp_inr], map_smul' := Ξ» u i c x, by cases i; simp only [map_smul, smul_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr, sum.update_inr_comp_inl, sum.update_inr_comp_inr] } @[simp] lemma uncurry_sum_aux_apply (f : multilinear_map R (Ξ» x : ΞΉ, M') (multilinear_map R (Ξ» x : ΞΉ', M') Mβ‚‚)) (u : ΞΉ βŠ• ΞΉ' β†’ M') : f.uncurry_sum u = f (u ∘ sum.inl) (u ∘ sum.inr) := rfl variables (ΞΉ ΞΉ' R Mβ‚‚ M') /-- Linear equivalence between the space of multilinear maps on `Ξ  i : ΞΉ βŠ• ΞΉ', M'` and the space of multilinear maps on `Ξ  i : ΞΉ, M'` taking values in the space of multilinear maps on `Ξ  i : ΞΉ', M'`. -/ def curry_sum_equiv : multilinear_map R (Ξ» x : ΞΉ βŠ• ΞΉ', M') Mβ‚‚ ≃ₗ[R] multilinear_map R (Ξ» x : ΞΉ, M') (multilinear_map R (Ξ» x : ΞΉ', M') Mβ‚‚) := { to_fun := curry_sum, inv_fun := uncurry_sum, left_inv := Ξ» f, ext $ Ξ» u, by simp, right_inv := Ξ» f, by { ext, simp }, map_add' := Ξ» f g, by { ext, refl }, map_smul' := Ξ» c f, by { ext, refl } } variables {ΞΉ ΞΉ' R Mβ‚‚ M'} @[simp] lemma coe_curry_sum_equiv : ⇑(curry_sum_equiv R ΞΉ Mβ‚‚ M' ΞΉ') = curry_sum := rfl @[simp] lemma coe_curr_sum_equiv_symm : ⇑(curry_sum_equiv R ΞΉ Mβ‚‚ M' ΞΉ').symm = uncurry_sum := rfl variables (R Mβ‚‚ M') /-- If `s : finset (fin n)` is a finite set of cardinality `k` and its complement has cardinality `l`, then the space of multilinear maps on `Ξ» i : fin n, M'` is isomorphic to the space of multilinear maps on `Ξ» i : fin k, M'` taking values in the space of multilinear maps on `Ξ» i : fin l, M'`. -/ def curry_fin_finset {k l n : β„•} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᢜ.card = l) : multilinear_map R (Ξ» x : fin n, M') Mβ‚‚ ≃ₗ[R] multilinear_map R (Ξ» x : fin k, M') (multilinear_map R (Ξ» x : fin l, M') Mβ‚‚) := (dom_dom_congr_linear_equiv M' Mβ‚‚ R R (fin_sum_equiv_of_finset hk hl).symm).trans (curry_sum_equiv R (fin k) Mβ‚‚ M' (fin l)) variables {R Mβ‚‚ M'} @[simp] lemma curry_fin_finset_apply {k l n : β„•} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᢜ.card = l) (f : multilinear_map R (Ξ» x : fin n, M') Mβ‚‚) (mk : fin k β†’ M') (ml : fin l β†’ M') : curry_fin_finset R Mβ‚‚ M' hk hl f mk ml = f (Ξ» i, sum.elim mk ml ((fin_sum_equiv_of_finset hk hl).symm i)) := rfl @[simp] lemma curry_fin_finset_symm_apply {k l n : β„•} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᢜ.card = l) (f : multilinear_map R (Ξ» x : fin k, M') (multilinear_map R (Ξ» x : fin l, M') Mβ‚‚)) (m : fin n β†’ M') : (curry_fin_finset R Mβ‚‚ M' hk hl).symm f m = f (Ξ» i, m $ fin_sum_equiv_of_finset hk hl (sum.inl i)) (Ξ» i, m $ fin_sum_equiv_of_finset hk hl (sum.inr i)) := rfl @[simp] lemma curry_fin_finset_symm_apply_piecewise_const {k l n : β„•} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᢜ.card = l) (f : multilinear_map R (Ξ» x : fin k, M') (multilinear_map R (Ξ» x : fin l, M') Mβ‚‚)) (x y : M') : (curry_fin_finset R Mβ‚‚ M' hk hl).symm f (s.piecewise (Ξ» _, x) (Ξ» _, y)) = f (Ξ» _, x) (Ξ» _, y) := begin rw curry_fin_finset_symm_apply, congr, { ext i, rw [fin_sum_equiv_of_finset_inl, finset.piecewise_eq_of_mem], apply finset.order_emb_of_fin_mem }, { ext i, rw [fin_sum_equiv_of_finset_inr, finset.piecewise_eq_of_not_mem], exact finset.mem_compl.1 (finset.order_emb_of_fin_mem _ _ _) } end @[simp] lemma curry_fin_finset_symm_apply_const {k l n : β„•} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᢜ.card = l) (f : multilinear_map R (Ξ» x : fin k, M') (multilinear_map R (Ξ» x : fin l, M') Mβ‚‚)) (x : M') : (curry_fin_finset R Mβ‚‚ M' hk hl).symm f (Ξ» _, x) = f (Ξ» _, x) (Ξ» _, x) := rfl @[simp] lemma curry_fin_finset_apply_const {k l n : β„•} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᢜ.card = l) (f : multilinear_map R (Ξ» x : fin n, M') Mβ‚‚) (x y : M') : curry_fin_finset R Mβ‚‚ M' hk hl f (Ξ» _, x) (Ξ» _, y) = f (s.piecewise (Ξ» _, x) (Ξ» _, y)) := begin refine (curry_fin_finset_symm_apply_piecewise_const hk hl _ _ _).symm.trans _, -- `rw` fails rw linear_equiv.symm_apply_apply end end multilinear_map end currying section submodule variables {R M Mβ‚‚} [ring R] [βˆ€i, add_comm_monoid (M₁ i)] [add_comm_monoid M'] [add_comm_monoid Mβ‚‚] [βˆ€i, module R (M₁ i)] [module R M'] [module R Mβ‚‚] namespace multilinear_map /-- The pushforward of an indexed collection of submodule `p i βŠ† M₁ i` by `f : M₁ β†’ Mβ‚‚`. Note that this is not a submodule - it is not closed under addition. -/ def map [nonempty ΞΉ] (f : multilinear_map R M₁ Mβ‚‚) (p : Ξ  i, submodule R (M₁ i)) : sub_mul_action R Mβ‚‚ := { carrier := f '' { v | βˆ€ i, v i ∈ p i}, smul_mem' := Ξ» c _ ⟨x, hx, hf⟩, let ⟨i⟩ := β€Ήnonempty ΞΉβ€Ί in by { refine ⟨update x i (c β€’ x i), Ξ» j, if hij : j = i then _ else _, hf β–Έ _⟩, { rw [hij, update_same], exact (p i).smul_mem _ (hx i) }, { rw [update_noteq hij], exact hx j }, { rw [f.map_smul, update_eq_self] } } } /-- The map is always nonempty. This lemma is needed to apply `sub_mul_action.zero_mem`. -/ lemma map_nonempty [nonempty ΞΉ] (f : multilinear_map R M₁ Mβ‚‚) (p : Ξ  i, submodule R (M₁ i)) : (map f p : set Mβ‚‚).nonempty := ⟨f 0, 0, Ξ» i, (p i).zero_mem, rfl⟩ /-- The range of a multilinear map, closed under scalar multiplication. -/ def range [nonempty ΞΉ] (f : multilinear_map R M₁ Mβ‚‚) : sub_mul_action R Mβ‚‚ := f.map (Ξ» i, ⊀) end multilinear_map end submodule
7d4cc6cb09d4b92d5a55ee5ff588f1f7eca05574
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/ring_theory/polynomial/chebyshev/defs.lean
c4418ed557c10a4b9b87a8bf90d6d00fb0e369ba
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,242
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 data.polynomial.derivative import tactic.ring /-! # Chebyshev polynomials The Chebyshev polynomials are two families of polynomials indexed by `β„•`, with integral coefficients. See the file `ring_theory.polynomial.chebyshev.basic` for more properties. ## Main definitions * `polynomial.chebyshev₁`: the Chebyshev polynomials of the first kind. * `polynomial.chebyshevβ‚‚`: the Chebyshev polynomials of the second kind. ## Main statements * The formal derivative of the Chebyshev polynomials of the first kind is a scalar multiple of the Chebyshev polynomials of the second kind. ## Implementation details In this file we only give definitions and some very elementary simp-lemmas. This way, we can import this file in `analysis.special_functions.trigonometric`, and import that file in turn, in `ring_theory.polynomial.chebyshev.basic`. ## References [Lionel Ponton, _Roots of the Chebyshev polynomials: A purely algebraic approach_] [ponton2020chebyshev] ## TODO * Redefine and/or relate the definition of Chebyshev polynomials to `linear_recurrence`. * Add explicit formula involving square roots for Chebyshev polynomials `ring_theory.polynomial.chebyshev.basic`. * Compute zeroes and extrema of Chebyshev polynomials. * Prove that the roots of the Chebyshev polynomials (except 0) are irrational. * Prove minimax properties of Chebyshev polynomials. -/ noncomputable theory namespace polynomial variables (R S : Type*) [comm_ring R] [comm_ring S] /-- `chebyshev₁ n` is the `n`-th Chebyshev polynomial of the first kind -/ noncomputable def chebyshev₁ : β„• β†’ polynomial R | 0 := 1 | 1 := X | (n + 2) := 2 * X * chebyshev₁ (n + 1) - chebyshev₁ n @[simp] lemma chebyshev₁_zero : chebyshev₁ R 0 = 1 := rfl @[simp] lemma chebyshev₁_one : chebyshev₁ R 1 = X := rfl lemma chebyshev₁_two : chebyshev₁ R 2 = 2 * X ^ 2 - 1 := by simp only [chebyshev₁, sub_left_inj, pow_two, mul_assoc] @[simp] lemma chebyshev₁_add_two (n : β„•) : chebyshev₁ R (n + 2) = 2 * X * chebyshev₁ R (n + 1) - chebyshev₁ R n := by rw chebyshev₁ lemma chebyshev₁_of_two_le (n : β„•) (h : 2 ≀ n) : chebyshev₁ R n = 2 * X * chebyshev₁ R (n - 1) - chebyshev₁ R (n - 2) := begin obtain ⟨n, rfl⟩ := nat.exists_eq_add_of_le h, rw add_comm, exact chebyshev₁_add_two R n end variables {R S} lemma map_chebyshev₁ (f : R β†’+* S) : βˆ€ (n : β„•), map f (chebyshev₁ R n) = chebyshev₁ S n | 0 := by simp only [chebyshev₁_zero, map_one] | 1 := by simp only [chebyshev₁_one, map_X] | (n + 2) := begin simp only [chebyshev₁_add_two, map_mul, map_sub, map_X, bit0, map_add, map_one], rw [map_chebyshev₁ (n + 1), map_chebyshev₁ n], end end polynomial namespace polynomial variables (R S : Type*) [comm_ring R] [comm_ring S] /-- `chebyshevβ‚‚ n` is the `n`-th Chebyshev polynomial of the second kind -/ noncomputable def chebyshevβ‚‚ : β„• β†’ polynomial R | 0 := 1 | 1 := 2 * X | (n + 2) := 2 * X * chebyshevβ‚‚ (n + 1) - chebyshevβ‚‚ n @[simp] lemma chebyshevβ‚‚_zero : chebyshevβ‚‚ R 0 = 1 := rfl @[simp] lemma chebyshevβ‚‚_one : chebyshevβ‚‚ R 1 = 2 * X := rfl lemma chebyshevβ‚‚_two : chebyshevβ‚‚ R 2 = 4 * X ^ 2 - 1 := by { simp only [chebyshevβ‚‚], ring, } @[simp] lemma chebyshevβ‚‚_add_two (n : β„•) : chebyshevβ‚‚ R (n + 2) = 2 * X * chebyshevβ‚‚ R (n + 1) - chebyshevβ‚‚ R n := by rw chebyshevβ‚‚ lemma chebyshevβ‚‚_of_two_le (n : β„•) (h : 2 ≀ n) : chebyshevβ‚‚ R n = 2 * X * chebyshevβ‚‚ R (n - 1) - chebyshevβ‚‚ R (n - 2) := begin obtain ⟨n, rfl⟩ := nat.exists_eq_add_of_le h, rw add_comm, exact chebyshevβ‚‚_add_two R n end lemma chebyshevβ‚‚_eq_X_mul_chebyshevβ‚‚_add_chebyshev₁ : βˆ€ (n : β„•), chebyshevβ‚‚ R (n+1) = X * chebyshevβ‚‚ R n + chebyshev₁ R (n+1) | 0 := by { simp only [chebyshevβ‚‚_zero, chebyshevβ‚‚_one, chebyshev₁_one], ring } | 1 := by { simp only [chebyshevβ‚‚_one, chebyshev₁_two, chebyshevβ‚‚_two], ring } | (n + 2) := calc chebyshevβ‚‚ R (n + 2 + 1) = 2 * X * (X * chebyshevβ‚‚ R (n + 1) + chebyshev₁ R (n + 2)) - (X * chebyshevβ‚‚ R n + chebyshev₁ R (n + 1)) : by simp only [chebyshevβ‚‚_add_two, chebyshevβ‚‚_eq_X_mul_chebyshevβ‚‚_add_chebyshev₁ n, chebyshevβ‚‚_eq_X_mul_chebyshevβ‚‚_add_chebyshev₁ (n + 1)] ... = X * (2 * X * chebyshevβ‚‚ R (n + 1) - chebyshevβ‚‚ R n) + (2 * X * chebyshev₁ R (n + 2) - chebyshev₁ R (n + 1)) : by ring ... = X * chebyshevβ‚‚ R (n + 2) + chebyshev₁ R (n + 2 + 1) : by simp only [chebyshevβ‚‚_add_two, chebyshev₁_add_two] lemma chebyshev₁_eq_chebyshevβ‚‚_sub_X_mul_chebyshevβ‚‚ (n : β„•) : chebyshev₁ R (n+1) = chebyshevβ‚‚ R (n+1) - X * chebyshevβ‚‚ R n := by rw [chebyshevβ‚‚_eq_X_mul_chebyshevβ‚‚_add_chebyshev₁, add_comm (X * chebyshevβ‚‚ R n), add_sub_cancel] lemma chebyshev₁_eq_X_mul_chebyshev₁_sub_pol_chebyshevβ‚‚ : βˆ€ (n : β„•), chebyshev₁ R (n+2) = X * chebyshev₁ R (n+1) - (1 - X ^ 2) * chebyshevβ‚‚ R n | 0 := by { simp only [chebyshev₁_one, chebyshev₁_two, chebyshevβ‚‚_zero], ring } | 1 := by { simp only [chebyshev₁_add_two, chebyshev₁_zero, chebyshev₁_add_two, chebyshevβ‚‚_one, chebyshev₁_one], ring } | (n + 2) := calc chebyshev₁ R (n + 2 + 2) = 2 * X * chebyshev₁ R (n + 2 + 1) - chebyshev₁ R (n + 2) : chebyshev₁_add_two _ _ ... = 2 * X * (X * chebyshev₁ R (n + 2) - (1 - X ^ 2) * chebyshevβ‚‚ R (n + 1)) - (X * chebyshev₁ R (n + 1) - (1 - X ^ 2) * chebyshevβ‚‚ R n) : by simp only [chebyshev₁_eq_X_mul_chebyshev₁_sub_pol_chebyshevβ‚‚] ... = X * (2 * X * chebyshev₁ R (n + 2) - chebyshev₁ R (n + 1)) - (1 - X ^ 2) * (2 * X * chebyshevβ‚‚ R (n + 1) - chebyshevβ‚‚ R n) : by ring ... = X * chebyshev₁ R (n + 2 + 1) - (1 - X ^ 2) * chebyshevβ‚‚ R (n + 2) : by rw [chebyshev₁_add_two _ (n + 1), chebyshevβ‚‚_add_two] lemma one_sub_X_pow_two_mul_chebyshevβ‚‚_eq_pol_in_chebyshev₁ (n : β„•) : (1 - X ^ 2) * chebyshevβ‚‚ R n = X * chebyshev₁ R (n + 1) - chebyshev₁ R (n + 2) := by rw [chebyshev₁_eq_X_mul_chebyshev₁_sub_pol_chebyshevβ‚‚, ←sub_add, sub_self, zero_add] variables {R S} @[simp] lemma map_chebyshevβ‚‚ (f : R β†’+* S) : βˆ€ (n : β„•), map f (chebyshevβ‚‚ R n) = chebyshevβ‚‚ S n | 0 := by simp only [chebyshevβ‚‚_zero, map_one] | 1 := begin simp only [chebyshevβ‚‚_one, map_X, map_mul, map_add, map_one], change map f (1+1) * X = 2 * X, simpa only [map_add, map_one] end | (n + 2) := begin simp only [chebyshevβ‚‚_add_two, map_mul, map_sub, map_X, bit0, map_add, map_one], rw [map_chebyshevβ‚‚ (n + 1), map_chebyshevβ‚‚ n], end lemma chebyshev₁_derivative_eq_chebyshevβ‚‚ : βˆ€ (n : β„•), derivative (chebyshev₁ R (n + 1)) = (n + 1) * chebyshevβ‚‚ R n | 0 := by simp only [chebyshev₁_one, chebyshevβ‚‚_zero, derivative_X, nat.cast_zero, zero_add, mul_one] | 1 := by { simp only [chebyshev₁_two, chebyshevβ‚‚_one, derivative_sub, derivative_one, derivative_mul, derivative_X_pow, nat.cast_one, nat.cast_two], norm_num } | (n + 2) := calc derivative (chebyshev₁ R (n + 2 + 1)) = 2 * chebyshev₁ R (n + 2) + 2 * X * derivative (chebyshev₁ R (n + 1 + 1)) - derivative (chebyshev₁ R (n + 1)) : by simp only [chebyshev₁_add_two _ (n + 1), derivative_sub, derivative_mul, derivative_X, derivative_bit0, derivative_one, bit0_zero, zero_mul, zero_add, mul_one] ... = 2 * (chebyshevβ‚‚ R (n + 1 + 1) - X * chebyshevβ‚‚ R (n + 1)) + 2 * X * ((n + 1 + 1) * chebyshevβ‚‚ R (n + 1)) - (n + 1) * chebyshevβ‚‚ R n : by rw_mod_cast [chebyshev₁_derivative_eq_chebyshevβ‚‚, chebyshev₁_derivative_eq_chebyshevβ‚‚, chebyshev₁_eq_chebyshevβ‚‚_sub_X_mul_chebyshevβ‚‚] ... = (n + 1) * (2 * X * chebyshevβ‚‚ R (n + 1) - chebyshevβ‚‚ R n) + 2 * chebyshevβ‚‚ R (n + 2) : by ring ... = (n + 1) * chebyshevβ‚‚ R (n + 2) + 2 * chebyshevβ‚‚ R (n + 2) : by rw chebyshevβ‚‚_add_two ... = (n + 2 + 1) * chebyshevβ‚‚ R (n + 2) : by ring ... = (↑(n + 2) + 1) * chebyshevβ‚‚ R (n + 2) : by norm_cast lemma one_sub_X_pow_two_mul_derivative_chebyshev₁_eq_poly_in_chebyshev₁ (n : β„•) : (1 - X ^ 2) * (derivative (chebyshev₁ R (n+1))) = (n + 1) * (chebyshev₁ R n - X * chebyshev₁ R (n+1)) := calc (1 - X ^ 2) * (derivative (chebyshev₁ R (n+1))) = (1 - X ^ 2 ) * ((n + 1) * chebyshevβ‚‚ R n) : by rw chebyshev₁_derivative_eq_chebyshevβ‚‚ ... = (n + 1) * ((1 - X ^ 2) * chebyshevβ‚‚ R n) : by ring ... = (n + 1) * (X * chebyshev₁ R (n + 1) - (2 * X * chebyshev₁ R (n + 1) - chebyshev₁ R n)) : by rw [one_sub_X_pow_two_mul_chebyshevβ‚‚_eq_pol_in_chebyshev₁, chebyshev₁_add_two] ... = (n + 1) * (chebyshev₁ R n - X * chebyshev₁ R (n+1)) : by ring lemma add_one_mul_chebyshev₁_eq_poly_in_chebyshevβ‚‚ (n : β„•) : ((n : polynomial R) + 1) * chebyshev₁ R (n+1) = X * chebyshevβ‚‚ R n - (1 - X ^ 2) * derivative ( chebyshevβ‚‚ R n) := begin have h : derivative (chebyshev₁ R (n + 2)) = (chebyshevβ‚‚ R (n + 1) - X * chebyshevβ‚‚ R n) + X * derivative (chebyshev₁ R (n + 1)) + 2 * X * chebyshevβ‚‚ R n - (1 - X ^ 2) * derivative (chebyshevβ‚‚ R n), { conv_lhs { rw chebyshev₁_eq_X_mul_chebyshev₁_sub_pol_chebyshevβ‚‚ }, simp only [derivative_sub, derivative_mul, derivative_X, derivative_one, derivative_X_pow, one_mul, chebyshev₁_derivative_eq_chebyshevβ‚‚], rw [chebyshev₁_eq_chebyshevβ‚‚_sub_X_mul_chebyshevβ‚‚, nat.cast_bit0, nat.cast_one], ring }, calc ((n : polynomial R) + 1) * chebyshev₁ R (n + 1) = ((n : polynomial R) + 1 + 1) * (X * chebyshevβ‚‚ R n + chebyshev₁ R (n + 1)) - X * ((n + 1) * chebyshevβ‚‚ R n) - (X * chebyshevβ‚‚ R n + chebyshev₁ R (n + 1)) : by ring ... = derivative (chebyshev₁ R (n + 2)) - X * derivative (chebyshev₁ R (n + 1)) - chebyshevβ‚‚ R (n + 1) : by rw [←chebyshevβ‚‚_eq_X_mul_chebyshevβ‚‚_add_chebyshev₁, ←chebyshev₁_derivative_eq_chebyshevβ‚‚, ←nat.cast_one, ←nat.cast_add, nat.cast_one, ←chebyshev₁_derivative_eq_chebyshevβ‚‚ (n + 1)] ... = (chebyshevβ‚‚ R (n + 1) - X * chebyshevβ‚‚ R n) + X * derivative (chebyshev₁ R (n + 1)) + 2 * X * chebyshevβ‚‚ R n - (1 - X ^ 2) * derivative (chebyshevβ‚‚ R n) - X * derivative (chebyshev₁ R (n + 1)) - chebyshevβ‚‚ R (n + 1) : by rw h ... = X * chebyshevβ‚‚ R n - (1 - X ^ 2) * derivative (chebyshevβ‚‚ R n) : by ring, end end polynomial
4b69ea3aff3fbb3ba1352a33d47be825a8767c14
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/adjunctions/default.lean
b7803a8d37ce248bd8df2115fa9d9fdec4a62e97
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
3,479
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import ..natural_transformation import ..opposites import ..types open categories open categories.functor open categories.natural_transformation open categories.types namespace categories.adjunctions structure Adjunction { C D : Category } ( L : Functor C D ) ( R : Functor D C ) := ( unit : NaturalTransformation (IdentityFunctor C) (FunctorComposition L R) ) ( counit : NaturalTransformation (FunctorComposition R L) (IdentityFunctor D) ) ( triangle_1 : βˆ€ X : D.Obj, C.compose (unit.components (R.onObjects X)) (R.onMorphisms (counit.components X)) = C.identity (R.onObjects X) ) ( triangle_2 : βˆ€ X : C.Obj, D.compose (L.onMorphisms (unit.components X)) (counit.components (L.onObjects X)) = D.identity (L.onObjects X) ) attribute [simp,ematch] Adjunction.triangle_1 Adjunction.triangle_2 @[applicable] lemma Adjunctions_pointwise_equal { C D : Category } ( L : Functor C D ) ( R : Functor D C ) ( A B : Adjunction L R ) ( w1 : A.unit = B.unit ) ( w2 : A.counit = B.counit ) : A = B := begin induction A, induction B, blast end -- PROJECT: from an adjunction construct the triangles as equations between natural transformations. -- definition Triangle_1 -- { C D : Category } -- { L : Functor C D } -- { R : Functor D C } -- ( unit : NaturalTransformation (IdentityFunctor C) (FunctorComposition L R) ) -- ( counit : NaturalTransformation (FunctorComposition R L) (IdentityFunctor D) ) := -- @vertical_composition_of_NaturalTransformations D C R (FunctorComposition (FunctorComposition R L) R) R ⟦ whisker_on_left R unit ⟧ ⟦ whisker_on_right counit R ⟧ -- = IdentityNaturalTransformation R -- definition Triangle_2 -- { C D : Category } -- { L : Functor C D } -- { R : Functor D C } -- ( unit : NaturalTransformation (IdentityFunctor C) (FunctorComposition L R) ) -- ( counit : NaturalTransformation (FunctorComposition R L) (IdentityFunctor D) ) := -- @vertical_composition_of_NaturalTransformations C D L (FunctorComposition (FunctorComposition L R) L) L ⟦ whisker_on_right unit L ⟧ ⟦ whisker_on_left L counit ⟧ -- = IdentityNaturalTransformation L @[simp,ematch] lemma Adjunction.unit_naturality { C D : Category } { L : Functor C D } { R : Functor D C } ( A : Adjunction L R ) { X Y : C.Obj } ( f : C.Hom X Y ) : C.compose (A.unit.components X) (R.onMorphisms (L.onMorphisms f)) = C.compose f (A.unit.components Y) := begin refine ( cast _ (A.unit.naturality f) ), blast end @[simp,ematch] lemma Adjunction.counit_naturality { C D : Category } { L : Functor C D } { R : Functor D C } ( A : Adjunction L R ) { X Y : D.Obj } ( f : D.Hom X Y ) : D.compose (L.onMorphisms (R.onMorphisms f)) (A.counit.components Y) = D.compose (A.counit.components X) f := begin refine ( cast _ (A.counit.naturality f) ), blast end -- PROJECT examples -- PROJECT existence in terms of initial objects in comma categories -- PROJECT adjoints for functors between functor categories -- PROJECT adjoints are unique -- PROJECT equivalences can be lifted to adjoint equivalences -- PROJECT universal properties of adjunctions -- PROJECT show these are a special case of a duality in a 2-category. -- PROJECT adjoints of monoidal functors are (op)lax end categories.adjunctions
aab7da89b0294d8de88b55f8199a71ffd2f522f9
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/euclidean_domain/instances.lean
3d1841412230d0ca80486aabad126a6705fe9ada
[ "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,001
lean
/- Copyright (c) 2018 Louis Carlin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Louis Carlin, Mario Carneiro -/ import algebra.euclidean_domain.defs import algebra.field.defs import algebra.group_with_zero.units.lemmas import data.nat.order.basic import data.int.order.basic /-! # Instances for Euclidean domains * `int.euclidean_domain`: shows that `β„€` is a Euclidean domain. * `field.to_euclidean_domain`: shows that any field is a Euclidean domain. -/ instance int.euclidean_domain : euclidean_domain β„€ := { add := (+), mul := (*), one := 1, zero := 0, neg := has_neg.neg, quotient := (/), quotient_zero := int.div_zero, remainder := (%), quotient_mul_add_remainder_eq := Ξ» a b, int.div_add_mod _ _, r := Ξ» a b, a.nat_abs < b.nat_abs, r_well_founded := measure_wf (Ξ» a, int.nat_abs a), remainder_lt := Ξ» a b b0, int.coe_nat_lt.1 $ by { rw [int.nat_abs_of_nonneg (int.mod_nonneg _ b0), ← int.abs_eq_nat_abs], exact int.mod_lt _ b0 }, mul_left_not_lt := Ξ» a b b0, not_lt_of_ge $ by {rw [← mul_one a.nat_abs, int.nat_abs_mul], exact mul_le_mul_of_nonneg_left (int.nat_abs_pos_of_ne_zero b0) (nat.zero_le _) }, .. int.comm_ring, .. int.nontrivial } @[priority 100] -- see Note [lower instance priority] instance field.to_euclidean_domain {K : Type*} [field K] : euclidean_domain K := { add := (+), mul := (*), one := 1, zero := 0, neg := has_neg.neg, quotient := (/), remainder := Ξ» a b, a - a * b / b, quotient_zero := div_zero, quotient_mul_add_remainder_eq := Ξ» a b, by { classical, by_cases b = 0; simp [h, mul_div_cancel'] }, r := Ξ» a b, a = 0 ∧ b β‰  0, r_well_founded := well_founded.intro $ Ξ» a, acc.intro _ $ Ξ» b ⟨hb, hna⟩, acc.intro _ $ Ξ» c ⟨hc, hnb⟩, false.elim $ hnb hb, remainder_lt := Ξ» a b hnb, by simp [hnb], mul_left_not_lt := Ξ» a b hnb ⟨hab, hna⟩, or.cases_on (mul_eq_zero.1 hab) hna hnb, .. β€Ήfield Kβ€Ί }
edb22dea9f53f56ec455cd30bd541b80062532c0
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Elab/App.lean
6b2bf774c9399c9d42b93664fb5282cc87b48cc4
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
66,607
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.FindMVar import Lean.Parser.Term import Lean.Meta.KAbstract import Lean.Meta.Tactic.ElimInfo import Lean.Elab.Term import Lean.Elab.Binders import Lean.Elab.SyntheticMVars import Lean.Elab.Arg import Lean.Elab.RecAppSyntax namespace Lean.Elab.Term open Meta builtin_initialize elabWithoutExpectedTypeAttr : TagAttribute ← registerTagAttribute `elabWithoutExpectedType "mark that applications of the given declaration should be elaborated without the expected type" def hasElabWithoutExpectedType (env : Environment) (declName : Name) : Bool := elabWithoutExpectedTypeAttr.hasTag env declName instance : ToString Arg where toString | .stx val => toString val | .expr val => toString val instance : ToString NamedArg where toString s := "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")" def throwInvalidNamedArg (namedArg : NamedArg) (fn? : Option Name) : TermElabM Ξ± := withRef namedArg.ref <| match fn? with | some fn => throwError "invalid argument name '{namedArg.name}' for function '{fn}'" | none => throwError "invalid argument name '{namedArg.name}' for function" private def ensureArgType (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do try ensureHasTypeAux expectedType (← inferType arg) arg f catch | ex@(.error ..) => if (← read).errToSorry then exceptionToSorry ex expectedType else throw ex | ex => throw ex private def mkProjAndCheck (structName : Name) (idx : Nat) (e : Expr) : MetaM Expr := do let r := mkProj structName idx e let eType ← inferType e if (← isProp eType) then let rType ← inferType r if !(← isProp rType) then throwError "invalid projection, the expression{indentExpr e}\nis a proposition and has type{indentExpr eType}\nbut the projected value is not, it has type{indentExpr rType}" return r /-- Relevant definitions: ``` class CoeFun (Ξ± : Sort u) (Ξ³ : Ξ± β†’ outParam (Sort v)) ``` -/ private def tryCoeFun? (Ξ± : Expr) (a : Expr) : TermElabM (Option Expr) := do let v ← mkFreshLevelMVar let type ← mkArrow Ξ± (mkSort v) let Ξ³ ← mkFreshExprMVar type let u ← getLevel Ξ± let coeFunInstType := mkAppN (Lean.mkConst ``CoeFun [u, v]) #[Ξ±, Ξ³] let mvar ← mkFreshExprMVar coeFunInstType MetavarKind.synthetic let mvarId := mvar.mvarId! try if (← synthesizeCoeInstMVarCore mvarId) then expandCoe <| mkAppN (Lean.mkConst ``CoeFun.coe [u, v]) #[Ξ±, Ξ³, mvar, a] else return none catch _ => return none def synthesizeAppInstMVars (instMVars : Array MVarId) (app : Expr) : TermElabM Unit := for mvarId in instMVars do unless (← synthesizeInstMVarCore mvarId) do registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass registerMVarErrorImplicitArgInfo mvarId (← getRef) app /-- Return `some namedArg` if `namedArgs` contains an entry for `binderName`. -/ private def findBinderName? (namedArgs : List NamedArg) (binderName : Name) : Option NamedArg := namedArgs.find? fun namedArg => namedArg.name == binderName /-- Erase entry for `binderName` from `namedArgs`. -/ def eraseNamedArg (namedArgs : List NamedArg) (binderName : Name) : List NamedArg := namedArgs.filter (Β·.name != binderName) /-- Return true if the given type contains `OptParam` or `AutoParams` -/ private def hasOptAutoParams (type : Expr) : MetaM Bool := do forallTelescopeReducing type fun xs _ => xs.anyM fun x => do let xType ← inferType x return xType.getOptParamDefault?.isSome || xType.getAutoParamTactic?.isSome /-! # Default application elaborator -/ namespace ElabAppArgs structure Context where /-- `true` if `..` was used -/ ellipsis : Bool -- /-- `true` if `@` modifier was used -/ explicit : Bool /-- If the result type of an application is the `outParam` of some local instance, then special support may be needed because type class resolution interacts poorly with coercions in this kind of situation. This flag enables the special support. The idea is quite simple, if the result type is the `outParam` of some local instance, we simply execute `synthesizeSyntheticMVarsUsingDefault`. We added this feature to make sure examples as follows are correctly elaborated. ```lean class GetElem (Cont : Type u) (Idx : Type v) (Elem : outParam (Type w)) where getElem (xs : Cont) (i : Idx) : Elem export GetElem (getElem) instance : GetElem (Array Ξ±) Nat Ξ± where getElem xs i := xs.get ⟨i, sorry⟩ opaque f : Option Bool β†’ Bool opaque g : Bool β†’ Bool def bad (xs : Array Bool) : Bool := let x := getElem xs 0 f x && g x ``` Without the special support, Lean fails at `g x` saying `x` has type `Option Bool` but is expected to have type `Bool`. From the users point of view this is a bug, since `let x := getElem xs 0` clearly constraints `x` to be `Bool`, but we only obtain this information after we apply the `OfNat` default instance for `0`. Before converging to this solution, we have tried to create a "coercion placeholder" when `resultIsOutParamSupport = true`, but it did not work well in practice. For example, it failed in the example above. -/ resultIsOutParamSupport : Bool /-- Auxiliary structure for elaborating the application `f args namedArgs`. -/ structure State where f : Expr fType : Expr /-- Remaining regular arguments. -/ args : List Arg /-- remaining named arguments to be processed. -/ namedArgs : List NamedArg expectedType? : Option Expr /-- When named arguments are provided and explicit arguments occurring before them are missing, the elaborator eta-expands the declaration. For example, ``` def f (x y : Nat) := x + y #check f (y := 5) -- fun x => f x 5 ``` `etaArgs` stores the fresh free variables for implementing the eta-expansion. When `..` is used, eta-expansion is disabled, and missing arguments are treated as `_`. -/ etaArgs : Array Expr := #[] /-- Metavariables that we need the set the error context using the application being built. -/ toSetErrorCtx : Array MVarId := #[] /-- Metavariables for the instance implicit arguments that have already been processed. -/ instMVars : Array MVarId := #[] /-- The following field is used to implement the `propagateExpectedType` heuristic. It is set to `true` true when `expectedType` still has to be propagated. -/ propagateExpected : Bool /-- If the result type may be the `outParam` of some local instance. See comment at `Context.resultIsOutParamSupport` -/ resultTypeOutParam? : Option MVarId := none abbrev M := ReaderT Context (StateRefT State TermElabM) /-- Add the given metavariable to the collection of metavariables associated with instance-implicit arguments. -/ private def addInstMVar (mvarId : MVarId) : M Unit := modify fun s => { s with instMVars := s.instMVars.push mvarId } /-- Try to synthesize metavariables are `instMVars` using type class resolution. The ones that cannot be synthesized yet are registered. Remark: we use this method before trying to apply coercions to function. -/ def synthesizeAppInstMVars : M Unit := do let s ← get let instMVars := s.instMVars modify fun s => { s with instMVars := #[] } Term.synthesizeAppInstMVars instMVars s.f /-- fType may become a forallE after we synthesize pending metavariables. -/ private def synthesizePendingAndNormalizeFunType : M Unit := do synthesizeAppInstMVars synthesizeSyntheticMVars let s ← get let fType ← whnfForall s.fType if fType.isForall then modify fun s => { s with fType } else match (← tryCoeFun? fType s.f) with | some f => let fType ← inferType f modify fun s => { s with f, fType } | none => for namedArg in s.namedArgs do let f := s.f.getAppFn if f.isConst then throwInvalidNamedArg namedArg f.constName! else throwInvalidNamedArg namedArg none throwError "function expected at{indentExpr s.f}\nterm has type{indentExpr fType}" /-- Normalize and return the function type. -/ private def normalizeFunType : M Expr := do let s ← get let fType ← whnfForall s.fType modify fun s => { s with fType } return fType /-- Return the binder name at `fType`. This method assumes `fType` is a function type. -/ private def getBindingName : M Name := return (← get).fType.bindingName! /-- Return the next argument expected type. This method assumes `fType` is a function type. -/ private def getArgExpectedType : M Expr := return (← get).fType.bindingDomain! /-- Remove named argument with name `binderName` from `namedArgs`. -/ def eraseNamedArg (binderName : Name) : M Unit := modify fun s => { s with namedArgs := Term.eraseNamedArg s.namedArgs binderName } /-- Add a new argument to the result. That is, `f := f arg`, update `fType`. This method assumes `fType` is a function type. -/ private def addNewArg (argName : Name) (arg : Expr) : M Unit := do modify fun s => { s with f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg } if arg.isMVar then let mvarId := arg.mvarId! if let some mvarErrorInfo ← getMVarErrorInfo? mvarId then registerMVarErrorInfo { mvarErrorInfo with argName? := argName } /-- Elaborate the given `Arg` and add it to the result. See `addNewArg`. Recall that, `Arg` may be wrapping an already elaborated `Expr`. -/ private def elabAndAddNewArg (argName : Name) (arg : Arg) : M Unit := do let s ← get let expectedType := (← getArgExpectedType).consumeTypeAnnotations match arg with | Arg.expr val => let arg ← ensureArgType s.f val expectedType addNewArg argName arg | Arg.stx stx => let val ← elabTerm stx expectedType let arg ← withRef stx <| ensureArgType s.f val expectedType addNewArg argName arg /-- Return true if `fType` contains `OptParam` or `AutoParams` -/ private def fTypeHasOptAutoParams : M Bool := do hasOptAutoParams (← get).fType /-- Auxiliary function for retrieving the resulting type of a function application. See `propagateExpectedType`. Remark: `(explicit : Bool) == true` when `@` modifier is used. -/ private partial def getForallBody (explicit : Bool) : Nat β†’ List NamedArg β†’ Expr β†’ Option Expr | i, namedArgs, type@(.forallE n d b bi) => match findBinderName? namedArgs n with | some _ => getForallBody explicit i (Term.eraseNamedArg namedArgs n) b | none => if !explicit && !bi.isExplicit then getForallBody explicit i namedArgs b else if i > 0 then getForallBody explicit (i-1) namedArgs b else if d.isAutoParam || d.isOptParam then getForallBody explicit i namedArgs b else some type | 0, [], type => some type | _, _, _ => none private def shouldPropagateExpectedTypeFor (nextArg : Arg) : Bool := match nextArg with | .expr _ => false -- it has already been elaborated | .stx stx => -- TODO: make this configurable? stx.getKind != ``Lean.Parser.Term.hole && stx.getKind != ``Lean.Parser.Term.syntheticHole && stx.getKind != ``Lean.Parser.Term.byTactic /-- Auxiliary method for propagating the expected type. We call it as soon as we find the first explict argument. The goal is to propagate the expected type in applications of functions such as ```lean Add.add {Ξ± : Type u} : Ξ± β†’ Ξ± β†’ Ξ± List.cons {Ξ± : Type u} : Ξ± β†’ List Ξ± β†’ List Ξ± ``` This is particularly useful when there applicable coercions. For example, assume we have a coercion from `Nat` to `Int`, and we have `(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function, the elaborator will fail to elaborate ``` List.cons x [] ``` First, the elaborator creates a new metavariable `?Ξ±` for the implicit argument `{Ξ± : Type u}`. Then, when it processes `x`, it assigns `?Ξ± := Nat`, and then obtain the resultant type `List Nat` which is **not** definitionally equal to `List Int`. We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example). This method infers that the resultant type is `List ?Ξ±` and unifies it with `List Int`. Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the term ``` @List.cons Int (coe x) (@List.nil Int) ``` is produced. The method will do nothing if 1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`). 2- The resultant type contains optional/auto params. We have considered adding the following extra conditions a) The resultant type does not contain any type metavariable. b) The resultant type contains a nontype metavariable. These two conditions would restrict the method to simple functions that are "morally" in the Hindley&Milner fragment. If users need to disable expected type propagation, we can add an attribute `[elabWithoutExpectedType]`. -/ private def propagateExpectedType (arg : Arg) : M Unit := do if shouldPropagateExpectedTypeFor arg then let s ← get -- TODO: handle s.etaArgs.size > 0 unless !s.etaArgs.isEmpty || !s.propagateExpected do match s.expectedType? with | none => pure () | some expectedType => /- We don't propagate `Prop` because we often use `Prop` as a more general "Bool" (e.g., `if-then-else`). If we propagate `expectedType == Prop` in the following examples, the elaborator would fail ``` def f1 (s : Nat Γ— Bool) : Bool := if s.2 then false else true def f2 (s : List Bool) : Bool := if s.head! then false else true def f3 (s : List Bool) : Bool := if List.head! (s.map not) then false else true ``` They would all fail for the same reason. So, let's focus on the first one. We would elaborate `s.2` with `expectedType == Prop`. Before we elaborate `s`, this method would be invoked, and `s.fType` is `?Ξ± Γ— ?Ξ² β†’ ?Ξ²` and after propagation we would have `?Ξ± Γ— Prop β†’ Prop`. Then, when we would try to elaborate `s`, and get a type error because `?Ξ± Γ— Prop` cannot be unified with `Nat Γ— Bool` Most users would have a hard time trying to understand why these examples failed. Here is a possible alternative workarounds. We give up the idea of using `Prop` at `if-then-else`. Drawback: users use `if-then-else` with conditions that are not Decidable. So, users would have to embrace `propDecidable` and `choice`. This may not be that bad since the developers and users don't seem to care about constructivism. We currently use a different workaround, we just don't propagate the expected type when it is `Prop`. -/ if expectedType.isProp then modify fun s => { s with propagateExpected := false } else let numRemainingArgs := s.args.length trace[Elab.app.propagateExpectedType] "etaArgs.size: {s.etaArgs.size}, numRemainingArgs: {numRemainingArgs}, fType: {s.fType}" match getForallBody (← read).explicit numRemainingArgs s.namedArgs s.fType with | none => pure () | some fTypeBody => unless fTypeBody.hasLooseBVars do unless (← hasOptAutoParams fTypeBody) do trace[Elab.app.propagateExpectedType] "{expectedType} =?= {fTypeBody}" if (← isDefEq expectedType fTypeBody) then /- Note that we only set `propagateExpected := false` when propagation has succeeded. -/ modify fun s => { s with propagateExpected := false } /-- This method executes after all application arguments have been processed. -/ private def finalize : M Expr := do let s ← get let mut e := s.f -- all user explicit arguments have been consumed trace[Elab.app.finalize] e let ref ← getRef -- Register the error context of implicits for mvarId in s.toSetErrorCtx do registerMVarErrorImplicitArgInfo mvarId ref e if !s.etaArgs.isEmpty then e ← mkLambdaFVars s.etaArgs e /- Remark: we should not use `s.fType` as `eType` even when `s.etaArgs.isEmpty`. Reason: it may have been unfolded. -/ let eType ← inferType e trace[Elab.app.finalize] "after etaArgs, {e} : {eType}" /- Recall that `resultTypeOutParam? = some mvarId` if the function result type is the output parameter of a local instance. The value of this parameter may be inferable using other arguments. For example, suppose we have ```lean def add_one {X} [Trait X] [One (Trait.R X)] [HAdd X (Trait.R X) X] (x : X) : X := x + (One.one : (Trait.R X)) ``` from test `948.lean`. There are multiple ways to infer `X`, and we don't want to mark it as `syntheticOpaque`. -/ if let some outParamMVarId := s.resultTypeOutParam? then synthesizeAppInstMVars /- If `eType != mkMVar outParamMVarId`, then the function is partially applied, and we do not apply default instances. -/ if !(← outParamMVarId.isAssigned) && eType.isMVar && eType.mvarId! == outParamMVarId then synthesizeSyntheticMVarsUsingDefault return e else return e if let some expectedType := s.expectedType? then -- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it. trace[Elab.app.finalize] "expected type: {expectedType}" discard <| isDefEq expectedType eType synthesizeAppInstMVars return e /-- Return `true` if there is a named argument that depends on the next argument. -/ private def anyNamedArgDependsOnCurrent : M Bool := do let s ← get if s.namedArgs.isEmpty then return false else forallTelescopeReducing s.fType fun xs _ => do let curr := xs[0]! for i in [1:xs.size] do let xDecl ← xs[i]!.fvarId!.getDecl if s.namedArgs.any fun arg => arg.name == xDecl.userName then if (← localDeclDependsOn xDecl curr.fvarId!) then return true return false /-- Return `true` if there are regular or named arguments to be processed. -/ private def hasArgsToProcess : M Bool := do let s ← get return !s.args.isEmpty || !s.namedArgs.isEmpty /-- Return `true` if the next argument at `args` is of the form `_` -/ private def isNextArgHole : M Bool := do match (← get).args with | Arg.stx (Syntax.node _ ``Lean.Parser.Term.hole _) :: _ => pure true | _ => pure false /-- Return `true` if the next argument to be processed is the outparam of a local instance, and it the result type of the function. For example, suppose we have the class ```lean class Get (Cont : Type u) (Idx : Type v) (Elem : outParam (Type w)) where get (xs : Cont) (i : Idx) : Elem ``` And the current value of `fType` is ``` {Cont : Type u_1} β†’ {Idx : Type u_2} β†’ {Elem : Type u_3} β†’ [self : Get Cont Idx Elem] β†’ Cont β†’ Idx β†’ Elem ``` then the result returned by this method is `false` since `Cont` is not the output param of any local instance. Now assume `fType` is ``` {Elem : Type u_3} β†’ [self : Get Cont Idx Elem] β†’ Cont β†’ Idx β†’ Elem ``` then, the method returns `true` because `Elem` is an output parameter for the local instance `[self : Get Cont Idx Elem]`. Remark: if `resultIsOutParamSupport` is `false`, this method returns `false`. -/ private partial def isNextOutParamOfLocalInstanceAndResult : M Bool := do if !(← read).resultIsOutParamSupport then return false let type := (← get).fType.bindingBody! unless isResultType type 0 do return false if (← hasLocalInstaceWithOutParams type) then let x := mkFVar (← mkFreshFVarId) isOutParamOfLocalInstance x (type.instantiate1 x) else return false where isResultType (type : Expr) (i : Nat) : Bool := match type with | .forallE _ _ b _ => isResultType b (i + 1) | .bvar idx => idx == i | _ => false /-- (quick filter) Return true if `type` constains a binder `[C ...]` where `C` is a class containing outparams. -/ hasLocalInstaceWithOutParams (type : Expr) : CoreM Bool := do let .forallE _ d b bi := type | return false if bi.isInstImplicit then if let .const declName .. := d.getAppFn then if hasOutParams (← getEnv) declName then return true hasLocalInstaceWithOutParams b isOutParamOfLocalInstance (x : Expr) (type : Expr) : MetaM Bool := do let .forallE _ d b bi := type | return false if bi.isInstImplicit then if let .const declName .. := d.getAppFn then if hasOutParams (← getEnv) declName then let cType ← inferType d.getAppFn if (← isOutParamOf x 0 d.getAppArgs cType) then return true isOutParamOfLocalInstance x b isOutParamOf (x : Expr) (i : Nat) (args : Array Expr) (cType : Expr) : MetaM Bool := do if h : i < args.size then match (← whnf cType) with | .forallE _ d b _ => let arg := args.get ⟨i, h⟩ if arg == x && d.isOutParam then return true isOutParamOf x (i+1) args b | _ => return false else return false mutual /-- Create a fresh local variable with the current binder name and argument type, add it to `etaArgs` and `f`, and then execute the main loop.-/ private partial def addEtaArg (argName : Name) : M Expr := do let n ← getBindingName let type ← getArgExpectedType withLocalDeclD n type fun x => do modify fun s => { s with etaArgs := s.etaArgs.push x } addNewArg argName x main private partial def addImplicitArg (argName : Name) : M Expr := do let argType ← getArgExpectedType let arg ← if (← isNextOutParamOfLocalInstanceAndResult) then let arg ← mkFreshExprMVar argType /- When the result type is an output parameter, we don't want to propagate the expected type. So, we just mark `propagateExpected := false` to disable it. At `finalize`, we check whether `arg` is still unassigned, if it is, we apply default instances, and try to synthesize pending mvars. -/ modify fun s => { s with resultTypeOutParam? := some arg.mvarId!, propagateExpected := false } pure arg else mkFreshExprMVar argType modify fun s => { s with toSetErrorCtx := s.toSetErrorCtx.push arg.mvarId! } addNewArg argName arg main /-- Process a `fType` of the form `(x : A) β†’ B x`. This method assume `fType` is a function type -/ private partial def processExplictArg (argName : Name) : M Expr := do match (← get).args with | arg::args => propagateExpectedType arg modify fun s => { s with args } elabAndAddNewArg argName arg main | _ => let argType ← getArgExpectedType match (← read).explicit, argType.getOptParamDefault?, argType.getAutoParamTactic? with | false, some defVal, _ => addNewArg argName defVal; main | false, _, some (.const tacticDecl _) => let env ← getEnv let opts ← getOptions match evalSyntaxConstant env opts tacticDecl with | Except.error err => throwError err | Except.ok tacticSyntax => -- TODO(Leo): does this work correctly for tactic sequences? let tacticBlock ← `(by $(⟨tacticSyntax⟩)) let argNew := Arg.stx tacticBlock propagateExpectedType argNew elabAndAddNewArg argName argNew main | false, _, some _ => throwError "invalid autoParam, argument must be a constant" | _, _, _ => if !(← get).namedArgs.isEmpty then if (← anyNamedArgDependsOnCurrent) then addImplicitArg argName else if (← read).ellipsis then addImplicitArg argName else addEtaArg argName else if !(← read).explicit then if (← read).ellipsis then addImplicitArg argName else if (← fTypeHasOptAutoParams) then addEtaArg argName else finalize else finalize /-- Process a `fType` of the form `{x : A} β†’ B x`. This method assume `fType` is a function type -/ private partial def processImplicitArg (argName : Name) : M Expr := do if (← read).explicit then processExplictArg argName else addImplicitArg argName /-- Process a `fType` of the form `{{x : A}} β†’ B x`. This method assume `fType` is a function type -/ private partial def processStrictImplicitArg (argName : Name) : M Expr := do if (← read).explicit then processExplictArg argName else if (← hasArgsToProcess) then addImplicitArg argName else finalize /-- Process a `fType` of the form `[x : A] β†’ B x`. This method assume `fType` is a function type -/ private partial def processInstImplicitArg (argName : Name) : M Expr := do if (← read).explicit then if (← isNextArgHole) then /- Recall that if '@' has been used, and the argument is '_', then we still use type class resolution -/ let arg ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.synthetic modify fun s => { s with args := s.args.tail! } addInstMVar arg.mvarId! addNewArg argName arg main else processExplictArg argName else let arg ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.synthetic addInstMVar arg.mvarId! addNewArg argName arg main /-- Elaborate function application arguments. -/ partial def main : M Expr := do let fType ← normalizeFunType if fType.isForall then let binderName := fType.bindingName! let binfo := fType.bindingInfo! let s ← get match findBinderName? s.namedArgs binderName with | some namedArg => propagateExpectedType namedArg.val eraseNamedArg binderName elabAndAddNewArg binderName namedArg.val main | none => match binfo with | .implicit => processImplicitArg binderName | .instImplicit => processInstImplicitArg binderName | .strictImplicit => processStrictImplicitArg binderName | _ => processExplictArg binderName else if (← hasArgsToProcess) then synthesizePendingAndNormalizeFunType main else finalize end end ElabAppArgs builtin_initialize elabAsElim : TagAttribute ← registerTagAttribute `elabAsElim "instructs elaborator that the arguments of the function application should be elaborated as were an eliminator" fun declName => do let go : MetaM Unit := do discard <| getElimInfo declName let info ← getConstInfo declName if (← hasOptAutoParams info.type) then throwError "[elabAsElim] attribute cannot be used in declarations containing optional and auto parameters" go.run' {} {} /-! # Eliminator-like function application elaborator -/ namespace ElabElim /-- Context of the `elabAsElim` elaboration procedure. -/ structure Context where elimInfo : ElimInfo expectedType : Expr /-- State of the `elabAsElim` elaboration procedure. -/ structure State where /-- The resultant expression being built. -/ f : Expr /-- `f : fType -/ fType : Expr /-- User-provided named arguments that still have to be processed. -/ namedArgs : List NamedArg /-- User-providedarguments that still have to be processed. -/ args : List Arg /-- Discriminants processed so far. -/ discrs : Array Expr := #[] /-- Instance implicit arguments collected so far. -/ instMVars : Array MVarId := #[] /-- Position of the next argument to be processed. We use it to decide whether the argument is the motive or a discriminant. -/ idx : Nat := 0 /-- Store the metavariable used to represent the motive that will be computed at `finalize`. -/ motive? : Option Expr := none abbrev M := ReaderT Context $ StateRefT State TermElabM /-- Infer the `motive` using the expected type by `kabstract`ing the discriminants. -/ def mkMotive (discrs : Array Expr) (expectedType : Expr): MetaM Expr := do discrs.foldrM (init := expectedType) fun discr motive => do let discr ← instantiateMVars discr let motiveBody ← kabstract motive discr /- We use `transform (usedLetOnly := true)` to eliminate unnecessary let-expressions. -/ let discrType ← transform (usedLetOnly := true) (← instantiateMVars (← inferType discr)) return Lean.mkLambda (← mkFreshBinderName) BinderInfo.default discrType motiveBody /-- If the eliminator is over-applied, we "revert" the extra arguments. -/ def revertArgs (args : List Arg) (f : Expr) (expectedType : Expr) : TermElabM (Expr Γ— Expr) := args.foldrM (init := (f, expectedType)) fun arg (f, expectedType) => do let val ← match arg with | .expr val => pure val | .stx stx => elabTerm stx none let val ← instantiateMVars val let expectedTypeBody ← kabstract expectedType val /- We use `transform (usedLetOnly := true)` to eliminate unnecessary let-expressions. -/ let valType ← transform (usedLetOnly := true) (← instantiateMVars (← inferType val)) return (mkApp f val, mkForall (← mkFreshBinderName) BinderInfo.default valType expectedTypeBody) /-- Contruct the resulting application after all discriminants have bee elaborated, and we have consumed as many given arguments as possible. -/ def finalize : M Expr := do unless (← get).namedArgs.isEmpty do throwError "failed to elaborate eliminator, unused named arguments: {(← get).namedArgs.map (Β·.name)}" let some motive := (← get).motive? | throwError "failed to elaborate eliminator, insufficient number of arguments" forallTelescope (← get).fType fun xs _ => do let mut expectedType := (← read).expectedType let mut f := (← get).f if xs.size > 0 then assert! (← get).args.isEmpty try expectedType ← instantiateForall expectedType xs catch _ => throwError "failed to elaborate eliminator, insufficient number of arguments, expected type:{indentExpr expectedType}" else -- over-application, simulate `revert` (f, expectedType) ← revertArgs (← get).args f expectedType let result := mkAppN f xs let mut discrs := (← get).discrs let idx := (← get).idx if (← get).discrs.size < (← read).elimInfo.targetsPos.size then for i in [idx:idx + xs.size], x in xs do if (← read).elimInfo.targetsPos.contains i then discrs := discrs.push x let motiveVal ← mkMotive discrs expectedType unless (← isDefEq motive motiveVal) do throwError "failed to elaborate eliminator, invalid motive{indentExpr motiveVal}" synthesizeAppInstMVars (← get).instMVars result let result ← mkLambdaFVars xs (← instantiateMVars result) return result /-- Return the next argument to be processed. The result is `.none` if it is an implicit argument which was not provided using a named argument. The result is `.undef` if `args` is empty and `namedArgs` does contain an entry for `binderName`. -/ def getNextArg? (binderName : Name) (binderInfo : BinderInfo) : M (LOption Arg) := do match findBinderName? (← get).namedArgs binderName with | some namedArg => modify fun s => { s with namedArgs := eraseNamedArg s.namedArgs binderName } return .some namedArg.val | none => if binderInfo.isExplicit then match (← get).args with | [] => return .undef | arg :: args => modify fun s => { s with args } return .some arg else return .none /-- Set the `motive` field in the state. -/ def setMotive (motive : Expr) : M Unit := modify fun s => { s with motive? := motive } /-- Push the given expression into the `discrs` field in the state. -/ def addDiscr (discr : Expr) : M Unit := modify fun s => { s with discrs := s.discrs.push discr } /-- Elaborate the given argument with the given expected type. -/ private def elabArg (arg : Arg) (argExpectedType : Expr) : M Expr := do match arg with | Arg.expr val => ensureArgType (← get).f val argExpectedType | Arg.stx stx => let val ← elabTerm stx argExpectedType withRef stx <| ensureArgType (← get).f val argExpectedType /-- Save information for producing error messages. -/ def saveArgInfo (arg : Expr) (binderName : Name) : M Unit := do if arg.isMVar then let mvarId := arg.mvarId! if let some mvarErrorInfo ← getMVarErrorInfo? mvarId then registerMVarErrorInfo { mvarErrorInfo with argName? := binderName } /-- Create an implicit argument using the given `BinderInfo`. -/ def mkImplicitArg (argExpectedType : Expr) (bi : BinderInfo) : M Expr := do let arg ← mkFreshExprMVar argExpectedType (if bi.isInstImplicit then .synthetic else .natural) if bi.isInstImplicit then modify fun s => { s with instMVars := s.instMVars.push arg.mvarId! } return arg /-- Main loop of the `elimAsElab` procedure. -/ partial def main : M Expr := do let .forallE binderName binderType body binderInfo ← whnfForall (← get).fType | finalize let addArgAndContinue (arg : Expr) : M Expr := do modify fun s => { s with idx := s.idx + 1, f := mkApp s.f arg, fType := body.instantiate1 arg } saveArgInfo arg binderName main let idx := (← get).idx if (← read).elimInfo.motivePos == idx then let motive ← mkImplicitArg binderType binderInfo setMotive motive addArgAndContinue motive else if (← read).elimInfo.targetsPos.contains idx then match (← getNextArg? binderName binderInfo) with | .some arg => let discr ← elabArg arg binderType; addDiscr discr; addArgAndContinue discr | .undef => finalize | .none => let discr ← mkImplicitArg binderType binderInfo; addDiscr discr; addArgAndContinue discr else match (← getNextArg? binderName binderInfo) with | .some (.stx stx) => addArgAndContinue (← postponeElabTerm stx binderType) | .some (.expr val) => addArgAndContinue (← ensureArgType (← get).f val binderType) | .undef => finalize | .none => addArgAndContinue (← mkImplicitArg binderType binderInfo) end ElabElim /-- Return `true` if `declName` is a candidate for `ElabElim.main` elaboration. -/ private def shouldElabAsElim (declName : Name) : CoreM Bool := do if (← isRec declName) then return true let env ← getEnv if isCasesOnRecursor env declName then return true if isBRecOnRecursor env declName then return true if isRecOnRecursor env declName then return true return elabAsElim.hasTag env declName private def propagateExpectedTypeFor (f : Expr) : TermElabM Bool := match f.getAppFn.constName? with | some declName => return !hasElabWithoutExpectedType (← getEnv) declName | _ => return true /-! # Function application elaboration -/ /-- Elaborate a `f`-application using `namedArgs` and `args` as the arguments. - `expectedType?` the expected type if available. It is used to propagate typing information only. This method does **not** ensure the result has this type. - `explicit = true` when notation `@` is used, and implicit arguments are assumed to be provided at `namedArgs` and `args`. - `ellipsis = true` when notation `..` is used. That is, we add `_` for missing arguments. - `resultIsOutParamSupport` is used to control whether special support is used when processing applications of functions that return output parameter of some local instance. Example: ``` GetElem.getElem : {Cont : Type u_1} β†’ {Idx : Type u_2} β†’ {elem : Type u_3} β†’ {dom : cont β†’ idx β†’ Prop} β†’ [self : GetElem cont idx elem dom] β†’ (xs : cont) β†’ (i : idx) β†’ dom xs i β†’ elem ``` The result type `elem` is the output parameter of the local instance `self`. When this parameter is set to `true`, we execute `synthesizeSyntheticMVarsUsingDefault`. For additional details, see comment at `ElabAppArgs.resultIsOutParam`. -/ def elabAppArgs (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) (resultIsOutParamSupport := true) : TermElabM Expr := do -- Coercions must be available to use this flag. -- If `@` is used (i.e., `explicit = true`), we disable `resultIsOutParamSupport`. let resultIsOutParamSupport := ((← getEnv).contains ``Lean.Internal.coeM) && resultIsOutParamSupport && !explicit let fType ← inferType f let fType ← instantiateMVars fType unless namedArgs.isEmpty && args.isEmpty do tryPostponeIfMVar fType trace[Elab.app.args] "explicit: {explicit}, ellipsis: {ellipsis}, {f} : {fType}" trace[Elab.app.args] "namedArgs: {namedArgs}" trace[Elab.app.args] "args: {args}" if let some elimInfo ← elabAsElim? then tryPostponeIfNoneOrMVar expectedType? let some expectedType := expectedType? | throwError "failed to elaborate eliminator, expected type is not available" let expectedType ← instantiateMVars expectedType if expectedType.getAppFn.isMVar then throwError "failed to elaborate eliminator, expected type is not available" ElabElim.main.run { elimInfo, expectedType } |>.run' { f, fType args := args.toList namedArgs := namedArgs.toList } else ElabAppArgs.main.run { explicit, ellipsis, resultIsOutParamSupport } |>.run' { args := args.toList expectedType?, f, fType namedArgs := namedArgs.toList propagateExpected := (← propagateExpectedTypeFor f) } where /-- Return `some info` if we should elaborate as an eliminator. -/ elabAsElim? : TermElabM (Option ElimInfo) := do if explicit || ellipsis then return none let .const declName _ := f | return none unless (← shouldElabAsElim declName) do return none let elimInfo ← getElimInfo declName forallTelescopeReducing (← inferType f) fun xs _ => do if h : elimInfo.motivePos < xs.size then let x := xs[elimInfo.motivePos] let localDecl ← x.fvarId!.getDecl if findBinderName? namedArgs.toList localDecl.userName matches some _ then -- motive has been explicitly provided, so we should use standard app elaborator return none return some elimInfo else return none /-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/ inductive LValResolution where | projFn (baseStructName : Name) (structName : Name) (fieldName : Name) | projIdx (structName : Name) (idx : Nat) | const (baseStructName : Name) (structName : Name) (constName : Name) | localRec (baseName : Name) (fullName : Name) (fvar : Expr) private def throwLValError (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM Ξ± := throwError "{msg}{indentExpr e}\nhas type{indentExpr eType}" /-- `findMethod? env S fName`. - If `env` contains `S ++ fName`, return `(S, S++fName)` - Otherwise if `env` contains private name `prv` for `S ++ fName`, return `(S, prv)`, o - Otherwise for each parent structure `S'` of `S`, we try `findMethod? env S' fname` -/ private partial def findMethod? (env : Environment) (structName fieldName : Name) : Option (Name Γ— Name) := let fullName := structName ++ fieldName match env.find? fullName with | some _ => some (structName, fullName) | none => let fullNamePrv := mkPrivateName env fullName match env.find? fullNamePrv with | some _ => some (structName, fullNamePrv) | none => if isStructure env structName then (getParentStructures env structName).findSome? fun parentStructName => findMethod? env parentStructName fieldName else none /-- Return `some (structName', fullName)` if `structName ++ fieldName` is an alias for `fullName`, and `fullName` is of the form `structName' ++ fieldName`. TODO: if there is more than one applicable alias, it returns `none`. We should consider throwing an error or warning. -/ private def findMethodAlias? (env : Environment) (structName fieldName : Name) : Option (Name Γ— Name) := let fullName := structName ++ fieldName -- We never skip `protected` aliases when resolving dot-notation. let aliasesCandidates := getAliases env fullName (skipProtected := false) |>.filterMap fun alias => match alias.eraseSuffix? fieldName with | none => none | some structName' => some (structName', alias) match aliasesCandidates with | [r] => some r | _ => none private def throwInvalidFieldNotation (e eType : Expr) : TermElabM Ξ± := throwLValError e eType "invalid field notation, type is not of the form (C ...) where C is a constant" private def resolveLValAux (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := do if eType.isForall then match lval with | LVal.fieldName _ fieldName _ _ => let fullName := `Function ++ fieldName if (← getEnv).contains fullName then return LValResolution.const `Function `Function fullName | _ => pure () match eType.getAppFn.constName?, lval with | some structName, LVal.fieldIdx _ idx => if idx == 0 then throwError "invalid projection, index must be greater than 0" let env ← getEnv unless isStructureLike env structName do throwLValError e eType "invalid projection, structure expected" let numFields := getStructureLikeNumFields env structName if idx - 1 < numFields then if isStructure env structName then let fieldNames := getStructureFields env structName return LValResolution.projFn structName structName fieldNames[idx - 1]! else /- `structName` was declared using `inductive` command. So, we don't projection functions for it. Thus, we use `Expr.proj` -/ return LValResolution.projIdx structName (idx - 1) else throwLValError e eType m!"invalid projection, structure has only {numFields} field(s)" | some structName, LVal.fieldName _ fieldName _ _ => let env ← getEnv let searchEnv : Unit β†’ TermElabM LValResolution := fun _ => do if let some (baseStructName, fullName) := findMethod? env structName fieldName then return LValResolution.const baseStructName structName fullName else if let some (structName', fullName) := findMethodAlias? env structName fieldName then return LValResolution.const structName' structName' fullName else throwLValError e eType m!"invalid field '{fieldName}', the environment does not contain '{Name.mkStr structName fieldName}'" -- search local context first, then environment let searchCtx : Unit β†’ TermElabM LValResolution := fun _ => do let fullName := Name.mkStr structName fieldName for localDecl in (← getLCtx) do if localDecl.binderInfo == BinderInfo.auxDecl then if let some localDeclFullName := (← read).auxDeclToFullName.find? localDecl.fvarId then if fullName == (privateToUserName? localDeclFullName).getD localDeclFullName then /- LVal notation is being used to make a "local" recursive call. -/ return LValResolution.localRec structName fullName localDecl.toExpr searchEnv () if isStructure env structName then match findField? env structName (Name.mkSimple fieldName) with | some baseStructName => return LValResolution.projFn baseStructName structName (Name.mkSimple fieldName) | none => searchCtx () else searchCtx () | none, LVal.fieldName _ _ (some suffix) _ => if e.isConst then throwUnknownConstant (e.constName! ++ suffix) else throwInvalidFieldNotation e eType | _, _ => throwInvalidFieldNotation e eType /-- whnfCore + implicit consumption. Example: given `e` with `eType := {Ξ± : Type} β†’ (fun Ξ² => List Ξ²) Ξ± `, it produces `(e ?m, List ?m)` where `?m` is fresh metavariable. -/ private partial def consumeImplicits (stx : Syntax) (e eType : Expr) (hasArgs : Bool) : TermElabM (Expr Γ— Expr) := do let eType ← whnfCore eType match eType with | .forallE _ d b bi => if bi.isImplicit || (hasArgs && bi.isStrictImplicit) then let mvar ← mkFreshExprMVar d registerMVarErrorHoleInfo mvar.mvarId! stx consumeImplicits stx (mkApp e mvar) (b.instantiate1 mvar) hasArgs else if bi.isInstImplicit then let mvar ← mkInstMVar d let r := mkApp e mvar registerMVarErrorImplicitArgInfo mvar.mvarId! stx r consumeImplicits stx r (b.instantiate1 mvar) hasArgs else match d.getOptParamDefault? with | some defVal => consumeImplicits stx (mkApp e defVal) (b.instantiate1 defVal) hasArgs -- TODO: we do not handle autoParams here. | _ => return (e, eType) | _ => return (e, eType) private partial def resolveLValLoop (lval : LVal) (e eType : Expr) (previousExceptions : Array Exception) (hasArgs : Bool) : TermElabM (Expr Γ— LValResolution) := do let (e, eType) ← consumeImplicits lval.getRef e eType hasArgs tryPostponeIfMVar eType /- If `eType` is still a metavariable application, we try to apply default instances to "unblock" it. -/ if (← isMVarApp eType) then synthesizeSyntheticMVarsUsingDefault let eType ← instantiateMVars eType try let lvalRes ← resolveLValAux e eType lval return (e, lvalRes) catch | ex@(Exception.error _ _) => let eType? ← unfoldDefinition? eType match eType? with | some eType => resolveLValLoop lval e eType (previousExceptions.push ex) hasArgs | none => previousExceptions.forM fun ex => logException ex throw ex | ex@(Exception.internal _ _) => throw ex private def resolveLVal (e : Expr) (lval : LVal) (hasArgs : Bool) : TermElabM (Expr Γ— LValResolution) := do let eType ← inferType e resolveLValLoop lval e eType #[] hasArgs private partial def mkBaseProjections (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do let env ← getEnv match getPathToBaseStructure? env baseStructName structName with | none => throwError "failed to access field in parent structure" | some path => let mut e := e for projFunName in path do let projFn ← mkConst projFunName e ← elabAppArgs projFn #[{ name := `self, val := Arg.expr e }] (args := #[]) (expectedType? := none) (explicit := false) (ellipsis := false) return e private def typeMatchesBaseName (type : Expr) (baseName : Name) : MetaM Bool := do if baseName == `Function then return (← whnfR type).isForall else if type.consumeMData.isAppOf baseName then return true else return (← whnfR type).isAppOf baseName /-- Auxiliary method for field notation. It tries to add `e` as a new argument to `args` or `namedArgs`. This method first finds the parameter with a type of the form `(baseName ...)`. When the parameter is found, if it an explicit one and `args` is big enough, we add `e` to `args`. Otherwise, if there isn't another parameter with the same name, we add `e` to `namedArgs`. Remark: `fullName` is the name of the resolved "field" access function. It is used for reporting errors -/ private def addLValArg (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) (namedArgs : Array NamedArg) (fType : Expr) : TermElabM (Array Arg Γ— Array NamedArg) := forallTelescopeReducing fType fun xs _ => do let mut argIdx := 0 -- position of the next explicit argument let mut remainingNamedArgs := namedArgs for i in [:xs.size] do let x := xs[i]! let xDecl ← x.fvarId!.getDecl /- If there is named argument with name `xDecl.userName`, then we skip it. -/ match remainingNamedArgs.findIdx? (fun namedArg => namedArg.name == xDecl.userName) with | some idx => remainingNamedArgs := remainingNamedArgs.eraseIdx idx | none => let type := xDecl.type if (← typeMatchesBaseName type baseName) then /- We found a type of the form (baseName ...). First, we check if the current argument is an explicit one, and the current explicit position "fits" at `args` (i.e., it must be ≀ arg.size) -/ if argIdx ≀ args.size && xDecl.binderInfo.isExplicit then /- We insert `e` as an explicit argument -/ return (args.insertAt! argIdx (Arg.expr e), namedArgs) /- If we can't add `e` to `args`, we try to add it using a named argument, but this is only possible if there isn't an argument with the same name occurring before it. -/ for j in [:i] do let prev := xs[j]! let prevDecl ← prev.fvarId!.getDecl if prevDecl.userName == xDecl.userName then throwError "invalid field notation, function '{fullName}' has argument with the expected type{indentExpr type}\nbut it cannot be used" return (args, namedArgs.push { name := xDecl.userName, val := Arg.expr e }) if xDecl.binderInfo.isExplicit then -- advance explicit argument position argIdx := argIdx + 1 throwError "invalid field notation, function '{fullName}' does not have argument with type ({baseName} ...) that can be used, it must be explicit or implicit with an unique name" private def elabAppLValsAux (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) (f : Expr) (lvals : List LVal) : TermElabM Expr := let rec loop : Expr β†’ List LVal β†’ TermElabM Expr | f, [] => elabAppArgs f namedArgs args expectedType? explicit ellipsis | f, lval::lvals => do if let LVal.fieldName (ref := fieldStx) (targetStx := targetStx) .. := lval then addDotCompletionInfo targetStx f expectedType? fieldStx let hasArgs := !namedArgs.isEmpty || !args.isEmpty let (f, lvalRes) ← resolveLVal f lval hasArgs match lvalRes with | LValResolution.projIdx structName idx => let f ← mkProjAndCheck structName idx f let f ← addTermInfo lval.getRef f loop f lvals | LValResolution.projFn baseStructName structName fieldName => let f ← mkBaseProjections baseStructName structName f if let some info := getFieldInfo? (← getEnv) baseStructName fieldName then if isPrivateNameFromImportedModule (← getEnv) info.projFn then throwError "field '{fieldName}' from structure '{structName}' is private" let projFn ← mkConst info.projFn let projFn ← addTermInfo lval.getRef projFn if lvals.isEmpty then let namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f } elabAppArgs projFn namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs projFn #[{ name := `self, val := Arg.expr f }] #[] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals else unreachable! | LValResolution.const baseStructName structName constName => let f ← if baseStructName != structName then mkBaseProjections baseStructName structName f else pure f let projFn ← mkConst constName let projFn ← addTermInfo lval.getRef projFn if lvals.isEmpty then let projFnType ← inferType projFn let (args, namedArgs) ← addLValArg baseStructName constName f args namedArgs projFnType elabAppArgs projFn namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs projFn #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals | LValResolution.localRec baseName fullName fvar => let fvar ← addTermInfo lval.getRef fvar if lvals.isEmpty then let fvarType ← inferType fvar let (args, namedArgs) ← addLValArg baseName fullName f args namedArgs fvarType elabAppArgs fvar namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs fvar #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals loop f lvals private def elabAppLVals (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) : TermElabM Expr := do if !lvals.isEmpty && explicit then throwError "invalid use of field notation with `@` modifier" elabAppLValsAux namedArgs args expectedType? explicit ellipsis f lvals def elabExplicitUnivs (lvls : Array Syntax) : TermElabM (List Level) := do lvls.foldrM (init := []) fun stx lvls => return (← elabLevel stx)::lvls /-! # Interaction between `errToSorry` and `observing`. - The method `elabTerm` catches exceptions, log them, and returns a synthetic sorry (IF `ctx.errToSorry` == true). - When we elaborate choice nodes (and overloaded identifiers), we track multiple results using the `observing x` combinator. The `observing x` executes `x` and returns a `TermElabResult`. `observing `x does not check for synthetic sorry's, just an exception. Thus, it may think `x` worked when it didn't if a synthetic sorry was introduced. We decided that checking for synthetic sorrys at `observing` is not a good solution because it would not be clear to decide what the "main" error message for the alternative is. When the result contains a synthetic `sorry`, it is not clear which error message corresponds to the `sorry`. Moreover, while executing `x`, many error messages may have been logged. Recall that we need an error per alternative at `mergeFailures`. Thus, we decided to set `errToSorry` to `false` whenever processing choice nodes and overloaded symbols. Important: we rely on the property that after `errToSorry` is set to false, no elaboration function executed by `x` will reset it to `true`. -/ private partial def elabAppFnId (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := do let funLVals ← withRef fIdent <| resolveName' fIdent fExplicitUnivs expectedType? let overloaded := overloaded || funLVals.length > 1 -- Set `errToSorry` to `false` if `funLVals` > 1. See comment above about the interaction between `errToSorry` and `observing`. withReader (fun ctx => { ctx with errToSorry := funLVals.length == 1 && ctx.errToSorry }) do funLVals.foldlM (init := acc) fun acc (f, fIdent, fields) => do let lvals' := toLVals fields (first := true) let s ← observing do let f ← addTermInfo fIdent f expectedType? let e ← elabAppLVals f (lvals' ++ lvals) namedArgs args expectedType? explicit ellipsis if overloaded then ensureHasType expectedType? e else return e return acc.push s where toName (fields : List Syntax) : Name := let rec go | [] => .anonymous | field :: fields => .mkStr (go fields) field.getId.toString go fields.reverse toLVals : List Syntax β†’ (first : Bool) β†’ List LVal | [], _ => [] | field::fields, true => .fieldName field field.getId.toString (toName (field::fields)) fIdent :: toLVals fields false | field::fields, false => .fieldName field field.getId.toString none fIdent :: toLVals fields false /-- Resolve `(.$id:ident)` using the expected type to infer namespace. -/ private partial def resolveDotName (id : Syntax) (expectedType? : Option Expr) : TermElabM Name := do tryPostponeIfNoneOrMVar expectedType? let some expectedType := expectedType? | throwError "invalid dotted identifier notation, expected type must be known" forallTelescopeReducing expectedType fun _ resultType => do go resultType expectedType #[] where go (resultType : Expr) (expectedType : Expr) (previousExceptions : Array Exception) : TermElabM Name := do let resultType ← instantiateMVars resultType let resultTypeFn := resultType.cleanupAnnotations.getAppFn try tryPostponeIfMVar resultTypeFn let .const declName .. := resultTypeFn.cleanupAnnotations | throwError "invalid dotted identifier notation, expected type is not of the form (... β†’ C ...) where C is a constant{indentExpr expectedType}" let idNew := declName ++ id.getId.eraseMacroScopes unless (← getEnv).contains idNew do throwError "invalid dotted identifier notation, unknown identifier `{idNew}` from expected type{indentExpr expectedType}" return idNew catch | ex@(.error ..) => match (← unfoldDefinition? resultType) with | some resultType => go (← whnfCore resultType) expectedType (previousExceptions.push ex) | none => previousExceptions.forM fun ex => logException ex throw ex | ex@(.internal _ _) => throw ex private partial def elabAppFn (f : Syntax) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := do if f.getKind == choiceKind then -- Set `errToSorry` to `false` when processing choice nodes. See comment above about the interaction between `errToSorry` and `observing`. withReader (fun ctx => { ctx with errToSorry := false }) do f.getArgs.foldlM (init := acc) fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit ellipsis true acc else let elabFieldName (e field : Syntax) := do let newLVals := field.identComponents.map fun comp => -- We use `none` in `suffix?` since `field` can't be part of a composite name LVal.fieldName comp (toString comp.getId) none e elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit ellipsis overloaded acc let elabFieldIdx (e idxStx : Syntax) := do let idx := idxStx.isFieldIdx?.get! elabAppFn e (LVal.fieldIdx idxStx idx :: lvals) namedArgs args expectedType? explicit ellipsis overloaded acc match f with | `($(e).$idx:fieldIdx) => elabFieldIdx e idx | `($e |>.$idx:fieldIdx) => elabFieldIdx e idx | `($(e).$field:ident) => elabFieldName e field | `($e |>.$field:ident) => elabFieldName e field | `($_:ident@$_:term) => throwError "unexpected occurrence of named pattern" | `($id:ident) => do elabAppFnId id [] lvals namedArgs args expectedType? explicit ellipsis overloaded acc | `($id:ident.{$us,*}) => do let us ← elabExplicitUnivs us elabAppFnId id us lvals namedArgs args expectedType? explicit ellipsis overloaded acc | `(@$id:ident) => elabAppFn id lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc | `(@$_:ident.{$_us,*}) => elabAppFn (f.getArg 1) lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc | `(@$_) => throwUnsupportedSyntax -- invalid occurrence of `@` | `(_) => throwError "placeholders '_' cannot be used where a function is expected" | `(.$id:ident) => addCompletionInfo <| CompletionInfo.dotId f id.getId (← getLCtx) expectedType? let fConst ← mkConst (← resolveDotName id expectedType?) let s ← observing do -- Use (force := true) because we want to record the result of .ident resolution even in patterns let fConst ← addTermInfo f fConst expectedType? (force := true) let e ← elabAppLVals fConst lvals namedArgs args expectedType? explicit ellipsis if overloaded then ensureHasType expectedType? e else return e return acc.push s | _ => do let catchPostpone := !overloaded /- If we are processing a choice node, then we should use `catchPostpone == false` when elaborating terms. Recall that `observing` does not catch `postponeExceptionId`. -/ if lvals.isEmpty && namedArgs.isEmpty && args.isEmpty then /- Recall that elabAppFn is used for elaborating atomics terms **and** choice nodes that may contain arbitrary terms. If they are not being used as a function, we should elaborate using the expectedType. -/ let s ← observing do if overloaded then elabTermEnsuringType f expectedType? catchPostpone else elabTerm f expectedType? return acc.push s else let s ← observing do let f ← elabTerm f none catchPostpone let e ← elabAppLVals f lvals namedArgs args expectedType? explicit ellipsis if overloaded then ensureHasType expectedType? e else return e return acc.push s /-- Return the successful candidates. Recall we have Syntax `choice` nodes and overloaded symbols when we open multiple namespaces. -/ private def getSuccesses (candidates : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := do let r₁ := candidates.filter fun | EStateM.Result.ok .. => true | _ => false if r₁.size ≀ 1 then return r₁ let rβ‚‚ ← candidates.filterM fun | .ok e s => do if e.isMVar then /- Make sure `e` is not a delayed coercion. Recall that coercion insertion may be delayed when the type and expected type contains metavariables that block TC resolution. When processing overloaded notation, we disallow delayed coercions at `e`. -/ try s.restore synthesizeSyntheticMVars -- Tries to process pending coercions (and elaboration tasks) let e ← instantiateMVars e if e.isMVar then /- If `e` is still a metavariable, and its `SyntheticMVarDecl` is a coercion, we discard this solution -/ if let some synDecl ← getSyntheticMVarDecl? e.mvarId! then if synDecl.kind matches SyntheticMVarKind.coe .. then return false catch _ => -- If `synthesizeSyntheticMVars` failed, we just eliminate the candidate. return false return true | _ => return false if rβ‚‚.size == 0 then return r₁ else return rβ‚‚ /-- Throw an error message that describes why each possible interpretation for the overloaded notation and symbols did not work. We use a nested error message to aggregate the exceptions produced by each failure. -/ private def mergeFailures (failures : Array (TermElabResult Expr)) : TermElabM Ξ± := do let exs := failures.map fun | .error ex _ => ex | _ => unreachable! throwErrorWithNestedErrors "overloaded" exs private def elabAppAux (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) (expectedType? : Option Expr) : TermElabM Expr := do let candidates ← elabAppFn f [] namedArgs args expectedType? (explicit := false) (ellipsis := ellipsis) (overloaded := false) #[] if candidates.size == 1 then applyResult candidates[0]! else let successes ← getSuccesses candidates if successes.size == 1 then applyResult successes[0]! else if successes.size > 1 then let msgs : Array MessageData ← successes.mapM fun success => do match success with | .ok e s => withMCtx s.meta.meta.mctx <| withEnv s.meta.core.env do addMessageContext m!"{e} : {← inferType e}" | _ => unreachable! throwErrorAt f "ambiguous, possible interpretations {toMessageList msgs}" else withRef f <| mergeFailures candidates /-- We annotate recursive applications with their `Syntax` node to make sure we can produce error messages with correct position information at `WF` and `Structural`. -/ -- TODO: It is overkill to store the whole `Syntax` object, and we have to make sure we erase it later. -- We should store only the position information in the future. -- Recall that we will need to have a compact way of storing position information in the future anyway, if we -- want to support debugging information private def annotateIfRec (stx : Syntax) (e : Expr) : TermElabM Expr := do if (← read).saveRecAppSyntax then let resultFn := e.getAppFn if resultFn.isFVar then let localDecl ← resultFn.fvarId!.getDecl if localDecl.isAuxDecl then return mkRecAppWithSyntax e stx return e @[builtinTermElab app] def elabApp : TermElab := fun stx expectedType? => universeConstraintsCheckpoint do let (f, namedArgs, args, ellipsis) ← expandApp stx annotateIfRec stx (← elabAppAux f namedArgs args (ellipsis := ellipsis) expectedType?) private def elabAtom : TermElab := fun stx expectedType? => do annotateIfRec stx (← elabAppAux stx #[] #[] (ellipsis := false) expectedType?) @[builtinTermElab ident] def elabIdent : TermElab := elabAtom @[builtinTermElab namedPattern] def elabNamedPattern : TermElab := elabAtom @[builtinTermElab dotIdent] def elabDotIdent : TermElab := elabAtom @[builtinTermElab explicitUniv] def elabExplicitUniv : TermElab := elabAtom @[builtinTermElab pipeProj] def elabPipeProj : TermElab | `($e |>.$f $args*), expectedType? => universeConstraintsCheckpoint do let (namedArgs, args, ellipsis) ← expandArgs args elabAppAux (← `($e |>.$f)) namedArgs args (ellipsis := ellipsis) expectedType? | _, _ => throwUnsupportedSyntax @[builtinTermElab explicit] def elabExplicit : TermElab := fun stx expectedType? => match stx with | `(@$_:ident) => elabAtom stx expectedType? -- Recall that `elabApp` also has support for `@` | `(@$_:ident.{$_us,*}) => elabAtom stx expectedType? | `(@($t)) => elabTerm t expectedType? (implicitLambda := false) -- `@` is being used just to disable implicit lambdas | `(@$t) => elabTerm t expectedType? (implicitLambda := false) -- `@` is being used just to disable implicit lambdas | _ => throwUnsupportedSyntax @[builtinTermElab choice] def elabChoice : TermElab := elabAtom @[builtinTermElab proj] def elabProj : TermElab := elabAtom builtin_initialize registerTraceClass `Elab.app end Lean.Elab.Term
d6113a33af29835d9c396bb6286e69d776e3265e
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Init/Data/Array/Basic.lean
c6ad928274a8debef67f842a7356ce7b16f4e484
[ "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
29,879
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Basic import Init.Data.Fin.Basic import Init.Data.UInt import Init.Data.Repr import Init.Data.ToString import Init.Control.Id import Init.Util universes u v w /- 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 @[reducible, extern "lean_array_get_size"] def Array.size {Ξ± : Type u} (a : @& Array Ξ±) : Nat := a.sz namespace Array variables {Ξ± : Type u} /- The parameter `c` is the initial capacity -/ @[extern "lean_mk_empty_array_with_capacity"] def mkEmpty (c : @& Nat) : Array Ξ± := { sz := 0, data := fun ⟨x, h⟩ => absurd h (Nat.notLtZero x) } @[extern "lean_array_push"] def push (a : Array Ξ±) (v : Ξ±) : Array Ξ± := { sz := Nat.succ a.sz, data := fun ⟨j, hβ‚βŸ© => if hβ‚‚ : j = a.sz then v else a.data ⟨j, Nat.ltOfLeOfNe (Nat.leOfLtSucc h₁) hβ‚‚βŸ© } @[extern "lean_mk_array"] def mkArray {Ξ± : Type u} (n : Nat) (v : Ξ±) : Array Ξ± := { sz := n, data := fun _ => v} theorem szMkArrayEq {Ξ± : Type u} (n : Nat) (v : Ξ±) : (mkArray n v).sz = n := rfl def empty : Array Ξ± := mkEmpty 0 instance : HasEmptyc (Array Ξ±) := ⟨Array.empty⟩ instance : Inhabited (Array Ξ±) := ⟨Array.empty⟩ def isEmpty (a : Array Ξ±) : Bool := a.size = 0 def singleton (v : Ξ±) : Array Ξ± := mkArray 1 v @[extern "lean_array_fget"] def get (a : @& Array Ξ±) (i : @& Fin a.size) : Ξ± := a.data i /- Low-level version of `fget` which is as fast as a C array read. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fget` may be slightly slower than `uget`. -/ @[extern "lean_array_uget"] def uget (a : @& Array Ξ±) (i : USize) (h : i.toNat < a.size) : Ξ± := a.get ⟨i.toNat, h⟩ /- "Comfortable" version of `fget`. It performs a bound check at runtime. -/ @[extern "lean_array_get"] def get! [Inhabited Ξ±] (a : @& Array Ξ±) (i : @& Nat) : Ξ± := if h : i < a.size then a.get ⟨i, h⟩ else arbitrary Ξ± def back [Inhabited Ξ±] (a : Array Ξ±) : Ξ± := a.get! (a.size - 1) def get? (a : Array Ξ±) (i : Nat) : Option Ξ± := if h : i < a.size then some (a.get ⟨i, h⟩) else none def getD (a : Array Ξ±) (i : Nat) (vβ‚€ : Ξ±) : Ξ± := if h : i < a.size then a.get ⟨i, h⟩ else vβ‚€ def getOp [Inhabited Ξ±] (self : Array Ξ±) (idx : Nat) : Ξ± := self.get! idx -- auxiliary declaration used in the equation compiler when pattern matching array literals. abbrev getLit {Ξ± : Type u} {n : Nat} (a : Array Ξ±) (i : Nat) (h₁ : a.size = n) (hβ‚‚ : i < n) : Ξ± := a.get ⟨i, h₁.symm β–Έ hβ‚‚βŸ© @[extern "lean_array_fset"] def set (a : Array Ξ±) (i : @& Fin a.size) (v : Ξ±) : Array Ξ± := { sz := a.sz, data := fun j => if h : i = j then v else a.data j } theorem szFSetEq (a : Array Ξ±) (i : Fin a.size) (v : Ξ±) : (set a i v).size = a.size := rfl theorem szPushEq (a : Array Ξ±) (v : Ξ±) : (push a v).size = a.size + 1 := rfl /- Low-level version of `fset` which is as fast as a C array fset. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fset` may be slightly slower than `uset`. -/ @[extern "lean_array_uset"] def uset (a : Array Ξ±) (i : USize) (v : Ξ±) (h : i.toNat < a.size) : Array Ξ± := a.set ⟨i.toNat, h⟩ v /- "Comfortable" version of `fset`. It performs a bound check at runtime. -/ @[extern "lean_array_set"] def set! (a : Array Ξ±) (i : @& Nat) (v : Ξ±) : Array Ξ± := if h : i < a.size then a.set ⟨i, h⟩ v else panic! "index out of bounds" @[extern "lean_array_fswap"] def swap (a : Array Ξ±) (i j : @& Fin a.size) : Array Ξ± := let v₁ := a.get i; let vβ‚‚ := a.get j; let a := a.set i vβ‚‚; a.set j v₁ @[extern "lean_array_swap"] def swap! (a : Array Ξ±) (i j : @& Nat) : Array Ξ± := if h₁ : i < a.size then if hβ‚‚ : j < a.size then swap a ⟨i, hβ‚βŸ© ⟨j, hβ‚‚βŸ© else panic! "index out of bounds" else panic! "index out of bounds" @[inline] def swapAt {Ξ± : Type} (a : Array Ξ±) (i : Fin a.size) (v : Ξ±) : Ξ± Γ— Array Ξ± := let e := a.get i; let a := a.set i v; (e, a) -- TODO: delete as soon as we can define local instances @[neverExtract] private def swapAtPanic! [Inhabited Ξ±] (i : Nat) : Ξ± Γ— Array Ξ± := panic! ("index " ++ toString i ++ " out of bounds") @[inline] def swapAt! {Ξ± : Type} (a : Array Ξ±) (i : Nat) (v : Ξ±) : Ξ± Γ— Array Ξ± := if h : i < a.size then swapAt a ⟨i, h⟩ v else @swapAtPanic! _ ⟨v⟩ i @[extern "lean_array_pop"] def pop (a : Array Ξ±) : Array Ξ± := { sz := Nat.pred a.size, data := fun ⟨j, h⟩ => a.get ⟨j, Nat.ltOfLtOfLe h (Nat.predLe _)⟩ } -- TODO(Leo): justify termination using wf-rec partial def shrink : Array Ξ± β†’ Nat β†’ Array Ξ± | a, n => if n β‰₯ a.size then a else shrink a.pop n section variables {m : Type v β†’ Type w} [Monad m] variables {Ξ² : Type v} {Οƒ : Type u} -- TODO(Leo): justify termination using wf-rec @[specialize] partial def iterateMAux (a : Array Ξ±) (f : βˆ€ (i : Fin a.size), Ξ± β†’ Ξ² β†’ m Ξ²) : Nat β†’ Ξ² β†’ m Ξ² | i, b => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; f idx (a.get idx) b >>= iterateMAux (i+1) else pure b @[inline] def iterateM (a : Array Ξ±) (b : Ξ²) (f : βˆ€ (i : Fin a.size), Ξ± β†’ Ξ² β†’ m Ξ²) : m Ξ² := iterateMAux a f 0 b @[inline] def foldlM (f : Ξ² β†’ Ξ± β†’ m Ξ²) (init : Ξ²) (a : Array Ξ±) : m Ξ² := iterateM a init (fun _ b a => f a b) @[inline] def foldlFromM (f : Ξ² β†’ Ξ± β†’ m Ξ²) (init : Ξ²) (beginIdx : Nat) (a : Array Ξ±) : m Ξ² := iterateMAux a (fun _ b a => f a b) beginIdx init -- TODO(Leo): justify termination using wf-rec @[specialize] partial def iterateMβ‚‚Aux (a₁ : Array Ξ±) (aβ‚‚ : Array Οƒ) (f : βˆ€ (i : Fin a₁.size), Ξ± β†’ Οƒ β†’ Ξ² β†’ m Ξ²) : Nat β†’ Ξ² β†’ m Ξ² | i, b => if h₁ : i < a₁.size then let idx₁ : Fin a₁.size := ⟨i, hβ‚βŸ©; if hβ‚‚ : i < aβ‚‚.size then let idxβ‚‚ : Fin aβ‚‚.size := ⟨i, hβ‚‚βŸ©; f idx₁ (a₁.get idx₁) (aβ‚‚.get idxβ‚‚) b >>= iterateMβ‚‚Aux (i+1) else pure b else pure b @[inline] def iterateMβ‚‚ (a₁ : Array Ξ±) (aβ‚‚ : Array Οƒ) (b : Ξ²) (f : βˆ€ (i : Fin a₁.size), Ξ± β†’ Οƒ β†’ Ξ² β†’ m Ξ²) : m Ξ² := iterateMβ‚‚Aux a₁ aβ‚‚ f 0 b @[inline] def foldlMβ‚‚ (f : Ξ² β†’ Ξ± β†’ Οƒ β†’ m Ξ²) (b : Ξ²) (a₁ : Array Ξ±) (aβ‚‚ : Array Οƒ): m Ξ² := iterateMβ‚‚ a₁ aβ‚‚ b (fun _ a₁ aβ‚‚ b => f b a₁ aβ‚‚) @[specialize] partial def findSomeMAux (a : Array Ξ±) (f : Ξ± β†’ m (Option Ξ²)) : Nat β†’ m (Option Ξ²) | i => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; do r ← f (a.get idx); match r with | some v => pure r | none => findSomeMAux (i+1) else pure none @[inline] def findSomeM? (a : Array Ξ±) (f : Ξ± β†’ m (Option Ξ²)) : m (Option Ξ²) := findSomeMAux a f 0 @[specialize] partial def findSomeRevMAux (a : Array Ξ±) (f : Ξ± β†’ m (Option Ξ²)) : βˆ€ (idx : Nat), idx ≀ a.size β†’ m (Option Ξ²) | i, h => if hLt : 0 < i then have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0); have i - 1 < a.size from Nat.ltOfLtOfLe this h; let idx : Fin a.size := ⟨i - 1, this⟩; do r ← f (a.get idx); match r with | some v => pure r | none => have i - 1 ≀ a.size from Nat.leOfLt this; findSomeRevMAux (i-1) this else pure none @[inline] def findSomeRevM? (a : Array Ξ±) (f : Ξ± β†’ m (Option Ξ²)) : m (Option Ξ²) := findSomeRevMAux a f a.size (Nat.leRefl _) end -- TODO(Leo): justify termination using wf-rec @[specialize] partial def findMAux {Ξ± : Type} {m : Type β†’ Type} [Monad m] (a : Array Ξ±) (p : Ξ± β†’ m Bool) : Nat β†’ m (Option Ξ±) | i => if h : i < a.size then do let v := a.get ⟨i, h⟩; condM (p v) (pure (some v)) (findMAux (i+1)) else pure none @[inline] def findM? {Ξ± : Type} {m : Type β†’ Type} [Monad m] (a : Array Ξ±) (p : Ξ± β†’ m Bool) : m (Option Ξ±) := findMAux a p 0 @[inline] def find? {Ξ± : Type} (a : Array Ξ±) (p : Ξ± β†’ Bool) : Option Ξ± := Id.run $ a.findM? p @[specialize] partial def findRevMAux {Ξ± : Type} {m : Type β†’ Type} [Monad m] (a : Array Ξ±) (p : Ξ± β†’ m Bool) : βˆ€ (idx : Nat), idx ≀ a.size β†’ m (Option Ξ±) | i, h => if hLt : 0 < i then have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0); have i - 1 < a.size from Nat.ltOfLtOfLe this h; let v := a.get ⟨i - 1, this⟩; do { condM (p v) (pure (some v)) $ have i - 1 ≀ a.size from Nat.leOfLt this; findRevMAux (i-1) this } else pure none @[inline] def findRevM? {Ξ± : Type} {m : Type β†’ Type} [Monad m] (a : Array Ξ±) (p : Ξ± β†’ m Bool) : m (Option Ξ±) := findRevMAux a p a.size (Nat.leRefl _) @[inline] def findRev? {Ξ± : Type} (a : Array Ξ±) (p : Ξ± β†’ Bool) : Option Ξ± := Id.run $ a.findRevM? p section variables {Ξ² : Type w} {Οƒ : Type u} @[inline] def iterate (a : Array Ξ±) (b : Ξ²) (f : βˆ€ (i : Fin a.size), Ξ± β†’ Ξ² β†’ Ξ²) : Ξ² := Id.run $ iterateMAux a f 0 b @[inline] def iterateFrom (a : Array Ξ±) (b : Ξ²) (i : Nat) (f : βˆ€ (i : Fin a.size), Ξ± β†’ Ξ² β†’ Ξ²) : Ξ² := Id.run $ iterateMAux a f i b @[inline] def foldl (f : Ξ² β†’ Ξ± β†’ Ξ²) (init : Ξ²) (a : Array Ξ±) : Ξ² := iterate a init (fun _ a b => f b a) @[inline] def foldlFrom (f : Ξ² β†’ Ξ± β†’ Ξ²) (init : Ξ²) (beginIdx : Nat) (a : Array Ξ±) : Ξ² := Id.run $ foldlFromM f init beginIdx a @[inline] def iterateβ‚‚ (a₁ : Array Ξ±) (aβ‚‚ : Array Οƒ) (b : Ξ²) (f : βˆ€ (i : Fin a₁.size), Ξ± β†’ Οƒ β†’ Ξ² β†’ Ξ²) : Ξ² := Id.run $ iterateMβ‚‚Aux a₁ aβ‚‚ f 0 b @[inline] def foldlβ‚‚ (f : Ξ² β†’ Ξ± β†’ Οƒ β†’ Ξ²) (b : Ξ²) (a₁ : Array Ξ±) (aβ‚‚ : Array Οƒ) : Ξ² := iterateβ‚‚ a₁ aβ‚‚ b (fun _ a₁ aβ‚‚ b => f b a₁ aβ‚‚) @[inline] def findSome? (a : Array Ξ±) (f : Ξ± β†’ Option Ξ²) : Option Ξ² := Id.run $ findSomeMAux a f 0 @[inline] def findSome! [Inhabited Ξ²] (a : Array Ξ±) (f : Ξ± β†’ Option Ξ²) : Ξ² := match findSome? a f with | some b => b | none => panic! "failed to find element" @[inline] def findSomeRev? (a : Array Ξ±) (f : Ξ± β†’ Option Ξ²) : Option Ξ² := Id.run $ findSomeRevMAux a f a.size (Nat.leRefl _) @[inline] def findSomeRev! [Inhabited Ξ²] (a : Array Ξ±) (f : Ξ± β†’ Option Ξ²) : Ξ² := match findSomeRev? a f with | some b => b | none => panic! "failed to find element" @[specialize] partial def findIdxMAux {m : Type β†’ Type u} [Monad m] (a : Array Ξ±) (p : Ξ± β†’ m Bool) : Nat β†’ m (Option Nat) | i => if h : i < a.size then condM (p (a.get ⟨i, h⟩)) (pure (some i)) (findIdxMAux (i+1)) else pure none @[inline] def findIdxM? {m : Type β†’ Type u} [Monad m] (a : Array Ξ±) (p : Ξ± β†’ m Bool) : m (Option Nat) := findIdxMAux a p 0 @[specialize] partial def findIdxAux (a : Array Ξ±) (p : Ξ± β†’ Bool) : Nat β†’ Option Nat | i => if h : i < a.size then if p (a.get ⟨i, h⟩) then some i else findIdxAux (i+1) else none @[inline] def findIdx? (a : Array Ξ±) (p : Ξ± β†’ Bool) : Option Nat := findIdxAux a p 0 @[inline] def findIdx! (a : Array Ξ±) (p : Ξ± β†’ Bool) : Nat := match findIdxAux a p 0 with | some i => i | none => panic! "failed to find element" def getIdx? [HasBeq Ξ±] (a : Array Ξ±) (v : Ξ±) : Option Nat := a.findIdx? $ fun a => a == v end section variables {m : Type β†’ Type w} [Monad m] @[specialize] partial def anyRangeMAux (a : Array Ξ±) (endIdx : Nat) (hlt : endIdx ≀ a.size) (p : Ξ± β†’ m Bool) : Nat β†’ m Bool | i => if h : i < endIdx then let idx : Fin a.size := ⟨i, Nat.ltOfLtOfLe h hlt⟩; do b ← p (a.get idx); match b with | true => pure true | false => anyRangeMAux (i+1) else pure false @[inline] def anyM (a : Array Ξ±) (p : Ξ± β†’ m Bool) : m Bool := anyRangeMAux a a.size (Nat.leRefl _) p 0 @[inline] def allM (a : Array Ξ±) (p : Ξ± β†’ m Bool) : m Bool := do b ← anyM a (fun v => do b ← p v; pure (!b)); pure (!b) @[inline] def anyRangeM (a : Array Ξ±) (beginIdx endIdx : Nat) (p : Ξ± β†’ m Bool) : m Bool := if h : endIdx ≀ a.size then anyRangeMAux a endIdx h p beginIdx else anyRangeMAux a a.size (Nat.leRefl _) p beginIdx @[inline] def allRangeM (a : Array Ξ±) (beginIdx endIdx : Nat) (p : Ξ± β†’ m Bool) : m Bool := do b ← anyRangeM a beginIdx endIdx (fun v => do b ← p v; pure b); pure (!b) end @[inline] def any (a : Array Ξ±) (p : Ξ± β†’ Bool) : Bool := Id.run $ anyM a p @[inline] def anyRange (a : Array Ξ±) (beginIdx endIdx : Nat) (p : Ξ± β†’ Bool) : Bool := Id.run $ anyRangeM a beginIdx endIdx p @[inline] def anyFrom (a : Array Ξ±) (beginIdx : Nat) (p : Ξ± β†’ Bool) : Bool := Id.run $ anyRangeM a beginIdx a.size p @[inline] def all (a : Array Ξ±) (p : Ξ± β†’ Bool) : Bool := !any a (fun v => !p v) @[inline] def allRange (a : Array Ξ±) (beginIdx endIdx : Nat) (p : Ξ± β†’ Bool) : Bool := !anyRange a beginIdx endIdx (fun v => !p v) section variables {m : Type v β†’ Type w} [Monad m] variable {Ξ² : Type v} @[specialize] private def iterateRevMAux (a : Array Ξ±) (f : βˆ€ (i : Fin a.size), Ξ± β†’ Ξ² β†’ m Ξ²) : βˆ€ (i : Nat), i ≀ a.size β†’ Ξ² β†’ m Ξ² | 0, h, b => pure b | j+1, h, b => do let i : Fin a.size := ⟨j, h⟩; b ← f i (a.get i) b; iterateRevMAux j (Nat.leOfLt h) b @[inline] def iterateRevM (a : Array Ξ±) (b : Ξ²) (f : βˆ€ (i : Fin a.size), Ξ± β†’ Ξ² β†’ m Ξ²) : m Ξ² := iterateRevMAux a f a.size (Nat.leRefl _) b @[inline] def foldrM (f : Ξ± β†’ Ξ² β†’ m Ξ²) (init : Ξ²) (a : Array Ξ±) : m Ξ² := iterateRevM a init (fun _ => f) @[specialize] private def foldrRangeMAux (a : Array Ξ±) (f : Ξ± β†’ Ξ² β†’ m Ξ²) (beginIdx : Nat) : βˆ€ (i : Nat), i ≀ a.size β†’ Ξ² β†’ m Ξ² | 0, h, b => pure b | j+1, h, b => do let i : Fin a.size := ⟨j, h⟩; b ← f (a.get i) b; if j == beginIdx then pure b else foldrRangeMAux j (Nat.leOfLt h) b @[inline] def foldrRangeM (beginIdx endIdx : Nat) (f : Ξ± β†’ Ξ² β†’ m Ξ²) (ini : Ξ²) (a : Array Ξ±) : m Ξ² := if h : endIdx ≀ a.size then foldrRangeMAux a f beginIdx endIdx h ini else foldrRangeMAux a f beginIdx a.size (Nat.leRefl _) ini @[specialize] partial def foldlStepMAux (step : Nat) (a : Array Ξ±) (f : Ξ² β†’ Ξ± β†’ m Ξ²) : Nat β†’ Ξ² β†’ m Ξ² | i, b => if h : i < a.size then do let curr := a.get ⟨i, h⟩; b ← f b curr; foldlStepMAux (i+step) b else pure b @[inline] def foldlStepM (f : Ξ² β†’ Ξ± β†’ m Ξ²) (init : Ξ²) (step : Nat) (a : Array Ξ±) : m Ξ² := foldlStepMAux step a f 0 init end @[inline] def iterateRev {Ξ²} (a : Array Ξ±) (b : Ξ²) (f : βˆ€ (i : Fin a.size), Ξ± β†’ Ξ² β†’ Ξ²) : Ξ² := Id.run $ iterateRevM a b f @[inline] def foldr {Ξ²} (f : Ξ± β†’ Ξ² β†’ Ξ²) (init : Ξ²) (a : Array Ξ±) : Ξ² := Id.run $ foldrM f init a @[inline] def foldrRange {Ξ²} (beginIdx endIdx : Nat) (f : Ξ± β†’ Ξ² β†’ Ξ²) (init : Ξ²) (a : Array Ξ±) : Ξ² := Id.run $ foldrRangeM beginIdx endIdx f init a @[inline] def foldlStep {Ξ²} (f : Ξ² β†’ Ξ± β†’ Ξ²) (init : Ξ²) (step : Nat) (a : Array Ξ±) : Ξ² := Id.run $ foldlStepM f init step a @[inline] def getEvenElems (a : Array Ξ±) : Array Ξ± := a.foldlStep (fun r a => Array.push r a) empty 2 def toList (a : Array Ξ±) : List Ξ± := a.foldr List.cons [] instance [HasRepr Ξ±] : HasRepr (Array Ξ±) := ⟨fun a => "#" ++ repr a.toList⟩ instance [HasToString Ξ±] : HasToString (Array Ξ±) := ⟨fun a => "#" ++ toString a.toList⟩ section variables {m : Type v β†’ Type w} [Monad m] variable {Ξ² : Type v} @[specialize] unsafe partial def umapMAux (f : Nat β†’ Ξ± β†’ m Ξ²) : Nat β†’ Array NonScalar β†’ m (Array PNonScalar.{v}) | i, a => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; let v : NonScalar := a.get idx; let a := a.set idx (arbitrary _); do newV ← f i (unsafeCast v); umapMAux (i+1) (a.set idx (unsafeCast newV)) else pure (unsafeCast a) @[inline] unsafe partial def umapM (f : Ξ± β†’ m Ξ²) (as : Array Ξ±) : m (Array Ξ²) := @unsafeCast (m (Array PNonScalar.{v})) (m (Array Ξ²)) $ umapMAux (fun i a => f a) 0 (unsafeCast as) @[inline] unsafe partial def umapIdxM (f : Nat β†’ Ξ± β†’ m Ξ²) (as : Array Ξ±) : m (Array Ξ²) := @unsafeCast (m (Array PNonScalar.{v})) (m (Array Ξ²)) $ umapMAux f 0 (unsafeCast as) @[implementedBy Array.umapM] def mapM (f : Ξ± β†’ m Ξ²) (as : Array Ξ±) : m (Array Ξ²) := as.foldlM (fun bs a => do b ← f a; pure (bs.push b)) (mkEmpty as.size) @[implementedBy Array.umapIdxM] def mapIdxM (f : Nat β†’ Ξ± β†’ m Ξ²) (as : Array Ξ±) : m (Array Ξ²) := as.iterateM (mkEmpty as.size) (fun i a bs => do b ← f i.val a; pure (bs.push b)) end section variables {m : Type u β†’ Type v} [Monad m] @[inline] def modifyM [Inhabited Ξ±] (a : Array Ξ±) (i : Nat) (f : Ξ± β†’ m Ξ±) : m (Array Ξ±) := if h : i < a.size then do let idx : Fin a.size := ⟨i, h⟩; let v := a.get idx; let a := a.set idx (arbitrary Ξ±); v ← f v; pure $ (a.set idx v) else pure a end section variable {Ξ² : Type v} @[inline] def modify [Inhabited Ξ±] (a : Array Ξ±) (i : Nat) (f : Ξ± β†’ Ξ±) : Array Ξ± := Id.run $ a.modifyM i f @[inline] def modifyOp [Inhabited Ξ±] (self : Array Ξ±) (idx : Nat) (f : Ξ± β†’ Ξ±) : Array Ξ± := self.modify idx f @[inline] def mapIdx (f : Nat β†’ Ξ± β†’ Ξ²) (a : Array Ξ±) : Array Ξ² := Id.run $ mapIdxM f a @[inline] def map (f : Ξ± β†’ Ξ²) (as : Array Ξ±) : Array Ξ² := Id.run $ mapM f as end section variables {m : Type v β†’ Type w} [Monad m] variable {Ξ² : Type v} @[specialize] partial def forMAux (f : Ξ± β†’ m PUnit) (a : Array Ξ±) : Nat β†’ m PUnit | i => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; let v : Ξ± := a.get idx; do f v; forMAux (i+1) else pure ⟨⟩ @[inline] def forM (f : Ξ± β†’ m PUnit) (a : Array Ξ±) : m PUnit := a.forMAux f 0 @[inline] def forFromM (f : Ξ± β†’ m PUnit) (beginIdx : Nat) (a : Array Ξ±) : m PUnit := a.forMAux f beginIdx @[specialize] partial def forRevMAux (f : Ξ± β†’ m PUnit) (a : Array Ξ±) : forall (i : Nat), i ≀ a.size β†’ m PUnit | i, h => if hLt : 0 < i then have i - 1 < i from Nat.subLt hLt (Nat.zeroLtSucc 0); have i - 1 < a.size from Nat.ltOfLtOfLe this h; let v : Ξ± := a.get ⟨i-1, this⟩; have i - 1 ≀ a.size from Nat.leOfLt this; do f v; forRevMAux (i-1) this else pure ⟨⟩ @[inline] def forRevM (f : Ξ± β†’ m PUnit) (a : Array Ξ±) : m PUnit := a.forRevMAux f a.size (Nat.leRefl _) end -- TODO(Leo): justify termination using wf-rec partial def extractAux (a : Array Ξ±) : Nat β†’ βˆ€ (e : Nat), e ≀ a.size β†’ Array Ξ± β†’ Array Ξ± | i, e, hle, r => if hlt : i < e then let idx : Fin a.size := ⟨i, Nat.ltOfLtOfLe hlt hle⟩; extractAux (i+1) e hle (r.push (a.get idx)) else r def extract (a : Array Ξ±) (b e : Nat) : Array Ξ± := let r : Array Ξ± := mkEmpty (e - b); if h : e ≀ a.size then extractAux a b e h r else r protected def append (a : Array Ξ±) (b : Array Ξ±) : Array Ξ± := b.foldl (fun a v => a.push v) a instance : HasAppend (Array Ξ±) := ⟨Array.append⟩ -- TODO(Leo): justify termination using wf-rec @[specialize] partial def isEqvAux (a b : Array Ξ±) (hsz : a.size = b.size) (p : Ξ± β†’ Ξ± β†’ Bool) : Nat β†’ Bool | i => if h : i < a.size then let aidx : Fin a.size := ⟨i, h⟩; let bidx : Fin b.size := ⟨i, hsz β–Έ h⟩; match p (a.get aidx) (b.get bidx) with | true => isEqvAux (i+1) | false => false else true @[inline] def isEqv (a b : Array Ξ±) (p : Ξ± β†’ Ξ± β†’ Bool) : Bool := if h : a.size = b.size then isEqvAux a b h p 0 else false instance [HasBeq Ξ±] : HasBeq (Array Ξ±) := ⟨fun a b => isEqv a b HasBeq.beq⟩ -- TODO(Leo): justify termination using wf-rec, and use `swap` partial def reverseAux : Array Ξ± β†’ Nat β†’ Array Ξ± | a, i => let n := a.size; if i < n / 2 then reverseAux (a.swap! i (n - i - 1)) (i+1) else a def reverse (a : Array Ξ±) : Array Ξ± := reverseAux a 0 -- TODO(Leo): justify termination using wf-rec @[specialize] partial def filterAux (p : Ξ± β†’ Bool) : Array Ξ± β†’ Nat β†’ Nat β†’ Array Ξ± | a, i, j => if h₁ : i < a.size then if p (a.get ⟨i, hβ‚βŸ©) then if hβ‚‚ : j < i then filterAux (a.swap ⟨i, hβ‚βŸ© ⟨j, Nat.ltTrans hβ‚‚ hβ‚βŸ©) (i+1) (j+1) else filterAux a (i+1) (j+1) else filterAux a (i+1) j else a.shrink j @[inline] def filter (p : Ξ± β†’ Bool) (as : Array Ξ±) : Array Ξ± := filterAux p as 0 0 @[specialize] partial def filterMAux {m : Type β†’ Type} [Monad m] {Ξ± : Type} (p : Ξ± β†’ m Bool) : Array Ξ± β†’ Nat β†’ Nat β†’ m (Array Ξ±) | a, i, j => if h₁ : i < a.size then condM (p (a.get ⟨i, hβ‚βŸ©)) (if hβ‚‚ : j < i then filterMAux (a.swap ⟨i, hβ‚βŸ© ⟨j, Nat.ltTrans hβ‚‚ hβ‚βŸ©) (i+1) (j+1) else filterMAux a (i+1) (j+1)) (filterMAux a (i+1) j) else pure $ a.shrink j @[inline] def filterM {m : Type β†’ Type} [Monad m] {Ξ± : Type} (p : Ξ± β†’ m Bool) (as : Array Ξ±) : m (Array Ξ±) := filterMAux p as 0 0 @[inline] def filterFromM {m : Type β†’ Type} [Monad m] {Ξ± : Type} (p : Ξ± β†’ m Bool) (beginIdx : Nat) (as : Array Ξ±) : m (Array Ξ±) := filterMAux p as beginIdx beginIdx @[specialize] partial def filterMapMAux {m : Type u β†’ Type v} [Monad m] {Ξ± Ξ² : Type u} (f : Ξ± β†’ m (Option Ξ²)) (as : Array Ξ±) : Nat β†’ Array Ξ² β†’ m (Array Ξ²) | i, bs => if h : i < as.size then do let a := as.get ⟨i, h⟩; b? ← f a; match b? with | none => filterMapMAux (i+1) bs | some b => filterMapMAux (i+1) (bs.push b) else pure bs @[inline] def filterMapM {m : Type u β†’ Type v} [Monad m] {Ξ± Ξ² : Type u} (f : Ξ± β†’ m (Option Ξ²)) (as : Array Ξ±) : m (Array Ξ²) := filterMapMAux f as 0 Array.empty @[inline] def filterMap {Ξ± Ξ² : Type u} (f : Ξ± β†’ Option Ξ²) (as : Array Ξ±) : Array Ξ² := Id.run $ filterMapM f as partial def indexOfAux {Ξ±} [HasBeq Ξ±] (a : Array Ξ±) (v : Ξ±) : Nat β†’ Option (Fin a.size) | i => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; if a.get idx == v then some idx else indexOfAux (i+1) else none def indexOf {Ξ±} [HasBeq Ξ±] (a : Array Ξ±) (v : Ξ±) : Option (Fin a.size) := indexOfAux a v 0 partial def eraseIdxAux {Ξ±} : Nat β†’ Array Ξ± β†’ Array Ξ± | i, a => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; let idx1 : Fin a.size := ⟨i - 1, Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxAux (i+1) (a.swap idx idx1) else a.pop def feraseIdx {Ξ±} (a : Array Ξ±) (i : Fin a.size) : Array Ξ± := eraseIdxAux (i.val + 1) a def eraseIdx {Ξ±} (a : Array Ξ±) (i : Nat) : Array Ξ± := if i < a.size then eraseIdxAux (i+1) a else a theorem szFSwapEq (a : Array Ξ±) (i j : Fin a.size) : (a.swap i j).size = a.size := rfl theorem szPopEq (a : Array Ξ±) : a.pop.size = a.size - 1 := rfl section /- Instance for justifying `partial` declaration. We should be able to delete it as soon as we restore support for well-founded recursion. -/ instance eraseIdxSzAuxInstance (a : Array Ξ±) : Inhabited { r : Array Ξ± // r.size = a.size - 1 } := ⟨⟨a.pop, szPopEq a⟩⟩ partial def eraseIdxSzAux {Ξ±} (a : Array Ξ±) : βˆ€ (i : Nat) (r : Array Ξ±), r.size = a.size β†’ { r : Array Ξ± // r.size = a.size - 1 } | i, r, heq => if h : i < r.size then let idx : Fin r.size := ⟨i, h⟩; let idx1 : Fin r.size := ⟨i - 1, Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxSzAux (i+1) (r.swap idx idx1) ((szFSwapEq r idx idx1).trans heq) else ⟨r.pop, (szPopEq r).trans (heq β–Έ rfl)⟩ end def eraseIdx' {Ξ±} (a : Array Ξ±) (i : Fin a.size) : { r : Array Ξ± // r.size = a.size - 1 } := eraseIdxSzAux a (i.val + 1) a rfl def contains [HasBeq Ξ±] (as : Array Ξ±) (a : Ξ±) : Bool := as.any $ fun b => a == b def elem [HasBeq Ξ±] (a : Ξ±) (as : Array Ξ±) : Bool := as.contains a def erase [HasBeq Ξ±] (as : Array Ξ±) (a : Ξ±) : Array Ξ± := match as.indexOf a with | none => as | some i => as.feraseIdx i partial def insertAtAux {Ξ±} (i : Nat) : Array Ξ± β†’ Nat β†’ Array Ξ± | as, j => if i == j then as else let as := as.swap! (j-1) j; insertAtAux as (j-1) /-- Insert element `a` at position `i`. Pre: `i < as.size` -/ def insertAt {Ξ±} (as : Array Ξ±) (i : Nat) (a : Ξ±) : Array Ξ± := if i > as.size then panic! "invalid index" else let as := as.push a; as.insertAtAux i as.size theorem ext {Ξ± : Type u} (a b : Array Ξ±) : a.size = b.size β†’ (βˆ€ (i : Nat) (hi₁ : i < a.size) (hiβ‚‚ : i < b.size) , a.get ⟨i, hiβ‚βŸ© = b.get ⟨i, hiβ‚‚βŸ©) β†’ a = b := match a, b with | ⟨sz₁, fβ‚βŸ©, ⟨szβ‚‚, fβ‚‚βŸ© => show sz₁ = szβ‚‚ β†’ (βˆ€ (i : Nat) (hi₁ : i < sz₁) (hiβ‚‚ : i < szβ‚‚) , f₁ ⟨i, hiβ‚βŸ© = fβ‚‚ ⟨i, hiβ‚‚βŸ©) β†’ Array.mk sz₁ f₁ = Array.mk szβ‚‚ fβ‚‚ from fun h₁ hβ‚‚ => match sz₁, szβ‚‚, f₁, fβ‚‚, h₁, hβ‚‚ with | sz, _, f₁, fβ‚‚, rfl, hβ‚‚ => have f₁ = fβ‚‚ from funext $ fun ⟨i, hiβ‚βŸ© => hβ‚‚ i hi₁ hi₁; congrArg _ this theorem extLit {Ξ± : Type u} {n : Nat} (a b : Array Ξ±) (hsz₁ : a.size = n) (hszβ‚‚ : b.size = n) (h : βˆ€ (i : Nat) (hi : i < n), a.getLit i hsz₁ hi = b.getLit i hszβ‚‚ hi) : a = b := Array.ext a b (hsz₁.trans hszβ‚‚.symm) $ fun i hi₁ hiβ‚‚ => h i (hsz₁ β–Έ hi₁) end Array export Array (mkArray) @[inlineIfReduce] def List.toArrayAux {Ξ± : Type u} : List Ξ± β†’ Array Ξ± β†’ Array Ξ± | [], r => r | a::as, r => List.toArrayAux as (r.push a) @[inlineIfReduce] def List.redLength {Ξ± : Type u} : List Ξ± β†’ Nat | [] => 0 | _::as => as.redLength + 1 @[inline, matchPattern] def List.toArray {Ξ± : Type u} (as : List Ξ±) : Array Ξ± := as.toArrayAux (Array.mkEmpty as.redLength) namespace Array def toListLitAux {Ξ± : Type u} (a : Array Ξ±) (n : Nat) (hsz : a.size = n) : βˆ€ (i : Nat), i ≀ a.size β†’ List Ξ± β†’ List Ξ± | 0, hi, acc => acc | (i+1), hi, acc => toListLitAux i (Nat.leOfSuccLe hi) (a.getLit i hsz (Nat.ltOfLtOfEq (Nat.ltOfLtOfLe (Nat.ltSuccSelf i) hi) hsz) :: acc) def toArrayLit {Ξ± : Type u} (a : Array Ξ±) (n : Nat) (hsz : a.size = n) : Array Ξ± := List.toArray $ toListLitAux a n hsz n (hsz β–Έ Nat.leRefl _) [] theorem toArrayLitEq {Ξ± : Type u} (a : Array Ξ±) (n : Nat) (hsz : a.size = n) : a = toArrayLit a n hsz := -- TODO: this is painful to prove without proper automation sorry /- First, we need to prove βˆ€ i j acc, i ≀ a.size β†’ (toListLitAux a n hsz (i+1) hi acc).index j = if j < i then a.getLit j hsz _ else acc.index (j - i) by induction Base case is trivial (j : Nat) (acc : List Ξ±) (hi : 0 ≀ a.size) |- (toListLitAux a n hsz 0 hi acc).index j = if j < 0 then a.getLit j hsz _ else acc.index (j - 0) ... |- acc.index j = acc.index j Induction (j : Nat) (acc : List Ξ±) (hi : i+1 ≀ a.size) |- (toListLitAux a n hsz (i+1) hi acc).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) ... |- (toListLitAux a n hsz i hi' (a.getLit i hsz _ :: acc)).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) * by def ... |- if j < i then a.getLit j hsz _ else (a.getLit i hsz _ :: acc).index (j-i) * by induction hypothesis = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) If j < i, then both are a.getLit j hsz _ If j = i, then lhs reduces else-branch to (a.getLit i hsz _) and rhs is then-brachn (a.getLit i hsz _) If j >= i + 1, we use - j - i >= 1 > 0 - (a::as).index k = as.index (k-1) If k > 0 - j - (i + 1) = (j - i) - 1 Then lhs = (a.getLit i hsz _ :: acc).index (j-i) = acc.index (j-i-1) = acc.index (j-(i+1)) = rhs With this proof, we have βˆ€ j, j < n β†’ (toListLitAux a n hsz n _ []).index j = a.getLit j hsz _ We also need - (toListLitAux a n hsz n _ []).length = n - j < n -> (List.toArray as).getLit j _ _ = as.index j Then using Array.extLit, we have that a = List.toArray $ toListLitAux a n hsz n _ [] -/ @[specialize] def getMax? {Ξ± : Type u} (as : Array Ξ±) (lt : Ξ± β†’ Ξ± β†’ Bool) : Option Ξ± := if h : 0 < as.size then let a0 := as.get ⟨0, h⟩; some $ as.foldlFrom (fun best a => if lt best a then a else best) a0 1 else none @[specialize] partial def partitionAux {Ξ± : Type u} (p : Ξ± β†’ Bool) (as : Array Ξ±) : Nat β†’ Array Ξ± β†’ Array Ξ± β†’ Array Ξ± Γ— Array Ξ± | i, bs, cs => if h : i < as.size then let a := as.get ⟨i, h⟩; match p a with | true => partitionAux (i+1) (bs.push a) cs | false => partitionAux (i+1) bs (cs.push a) else (bs, cs) @[inline] def partition {Ξ± : Type u} (p : Ξ± β†’ Bool) (as : Array Ξ±) : Array Ξ± Γ— Array Ξ± := partitionAux p as 0 #[] #[] partial def isPrefixOfAux {Ξ± : Type u} [HasBeq Ξ±] (as bs : Array Ξ±) (hle : as.size ≀ bs.size) : Nat β†’ Bool | i => if h : i < as.size then let a := as.get ⟨i, h⟩; let b := bs.get ⟨i, Nat.ltOfLtOfLe h hle⟩; if a == b then isPrefixOfAux (i+1) else false else true /- Return true iff `as` is a prefix of `bs` -/ def isPrefixOf {Ξ± : Type u} [HasBeq Ξ±] (as bs : Array Ξ±) : Bool := if h : as.size ≀ bs.size then isPrefixOfAux as bs h 0 else false private def allDiffAuxAux {Ξ±} [HasBeq Ξ±] (as : Array Ξ±) (a : Ξ±) : forall (i : Nat), i < as.size β†’ Bool | 0, h => true | i+1, h => have i < as.size from Nat.ltTrans (Nat.ltSuccSelf _) h; a != as.get ⟨i, this⟩ && allDiffAuxAux i this private partial def allDiffAux {Ξ±} [HasBeq Ξ±] (as : Array Ξ±) : Nat β†’ Bool | i => if h : i < as.size then allDiffAuxAux as (as.get ⟨i, h⟩) i h && allDiffAux (i+1) else true def allDiff {Ξ±} [HasBeq Ξ±] (as : Array Ξ±) : Bool := allDiffAux as 0 end Array
621ed55d0f54012f6c6ee27cbb86b2663e3db9e8
26ac254ecb57ffcb886ff709cf018390161a9225
/src/group_theory/submonoid/basic.lean
e59e7d70bec65ccb242698279dde6c01a7f91f48
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
15,985
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 algebra.group.basic import data.set.lattice /-! # Submonoids: definition and `complete_lattice` structure This file defines bundled multiplicative and additive submonoids. We also define a `complete_lattice` structure on `submonoid`s, define the closure of a set as the minimal submonoid that includes this set, and prove a few results about extending properties from a dense set (i.e. a set with `closure s = ⊀`) to the whole monoid, see `submonoid.dense_induction` and `monoid_hom.of_mdense`. ## Main definitions * `submonoid M`: the type of bundled submonoids of a monoid `M`; the underlying set is given in the `carrier` field of the structure, and should be accessed through coercion as in `(S : set M)`. * `add_submonoid M` : the type of bundled submonoids of an additive monoid `M`. For each of the following definitions in the `submonoid` namespace, there is a corresponding definition in the `add_submonoid` namespace. * `submonoid.copy` : copy of a submonoid with `carrier` replaced by a set that is equal but possibly not definitionally equal to the carrier of the original `submonoid`. * `submonoid.closure` : monoid closure of a set, i.e., the least submonoid that includes the set. * `submonoid.gi` : `closure : set M β†’ submonoid M` and coercion `coe : submonoid M β†’ set M` form a `galois_insertion`; * `monoid_hom.eq_mlocus`: the submonoid of elements `x : M` such that `f x = g x`; * `monoid_hom.of_mdense`: if a map `f : M β†’ N` between two monoids satisfies `f 1 = 1` and `f (x * y) = f x * f y` for `y` from some dense set `s`, then `f` is a monoid homomorphism. E.g., if `f : β„• β†’ M` satisfies `f 0 = 0` and `f (x + 1) = f x + f 1`, then `f` is an additive monoid homomorphism. ## Implementation notes Submonoid inclusion is denoted `≀` rather than `βŠ†`, although `∈` is defined as membership of a submonoid's underlying set. This file is designed to have very few dependencies. In particular, it should not use natural numbers. ## Tags submonoid, submonoids -/ variables {M : Type*} [monoid M] {s : set M} variables {A : Type*} [add_monoid A] {t : set A} /-- A submonoid of a monoid `M` is a subset containing 1 and closed under multiplication. -/ structure submonoid (M : Type*) [monoid M] := (carrier : set M) (one_mem' : (1 : M) ∈ carrier) (mul_mem' {a b} : a ∈ carrier β†’ b ∈ carrier β†’ a * b ∈ carrier) /-- An additive submonoid of an additive monoid `M` is a subset containing 0 and closed under addition. -/ structure add_submonoid (M : Type*) [add_monoid M] := (carrier : set M) (zero_mem' : (0 : M) ∈ carrier) (add_mem' {a b} : a ∈ carrier β†’ b ∈ carrier β†’ a + b ∈ carrier) attribute [to_additive add_submonoid] submonoid namespace submonoid @[to_additive] instance : has_coe (submonoid M) (set M) := ⟨submonoid.carrier⟩ @[to_additive] instance : has_coe_to_sort (submonoid M) := ⟨Type*, Ξ» S, S.carrier⟩ @[to_additive] instance : has_mem M (submonoid M) := ⟨λ m S, m ∈ (S:set M)⟩ @[simp, to_additive] lemma mem_carrier {s : submonoid M} {x : M} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp, norm_cast, to_additive] lemma mem_coe {S : submonoid M} {m : M} : m ∈ (S : set M) ↔ m ∈ S := iff.rfl @[simp, norm_cast, to_additive] lemma coe_coe (s : submonoid M) : β†₯(s : set M) = s := rfl attribute [norm_cast] add_submonoid.mem_coe add_submonoid.coe_coe @[to_additive] protected lemma Β«existsΒ» {s : submonoid M} {p : s β†’ Prop} : (βˆƒ x : s, p x) ↔ βˆƒ x ∈ s, p ⟨x, β€Ήx ∈ sβ€ΊβŸ© := set_coe.exists @[to_additive] protected lemma Β«forallΒ» {s : submonoid M} {p : s β†’ Prop} : (βˆ€ x : s, p x) ↔ βˆ€ x ∈ s, p ⟨x, β€Ήx ∈ sβ€ΊβŸ© := set_coe.forall /-- Two submonoids are equal if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if the underlying subsets are equal."] theorem ext' ⦃S T : submonoid M⦄ (h : (S : set M) = T) : S = T := by cases S; cases T; congr' /-- Two submonoids are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {S T : submonoid M} : S = T ↔ (S : set M) = T := ⟨λ h, h β–Έ rfl, Ξ» h, ext' h⟩ /-- Two submonoids are equal if they have the same elements. -/ @[ext, to_additive "Two `add_submonoid`s are equal if they have the same elements."] theorem ext {S T : submonoid M} (h : βˆ€ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h attribute [ext] add_submonoid.ext /-- Copy a submonoid replacing `carrier` with a set that is equal to it. -/ @[to_additive "Copy an additive submonoid replacing `carrier` with a set that is equal to it."] def copy (S : submonoid M) (s : set M) (hs : s = S) : submonoid M := { carrier := s, one_mem' := hs.symm β–Έ S.one_mem', mul_mem' := hs.symm β–Έ S.mul_mem' } variable {S : submonoid M} @[simp, to_additive] lemma coe_copy {s : set M} (hs : s = S) : (S.copy s hs : set M) = s := rfl @[to_additive] lemma copy_eq {s : set M} (hs : s = S) : S.copy s hs = S := ext' hs variable (S) /-- A submonoid contains the monoid's 1. -/ @[to_additive "An `add_submonoid` contains the monoid's 0."] theorem one_mem : (1 : M) ∈ S := S.one_mem' /-- A submonoid is closed under multiplication. -/ @[to_additive "An `add_submonoid` is closed under addition."] theorem mul_mem {x y : M} : x ∈ S β†’ y ∈ S β†’ x * y ∈ S := submonoid.mul_mem' S @[to_additive] lemma coe_injective : function.injective (coe : S β†’ M) := subtype.val_injective @[simp, to_additive] lemma coe_eq_coe (x y : S) : (x : M) = y ↔ x = y := set_coe.ext_iff attribute [norm_cast] coe_eq_coe add_submonoid.coe_eq_coe @[to_additive] instance : has_le (submonoid M) := ⟨λ S T, βˆ€ ⦃x⦄, x ∈ S β†’ x ∈ T⟩ @[to_additive] lemma le_def {S T : submonoid M} : S ≀ T ↔ βˆ€ ⦃x : M⦄, x ∈ S β†’ x ∈ T := iff.rfl @[simp, norm_cast, to_additive] lemma coe_subset_coe {S T : submonoid M} : (S : set M) βŠ† T ↔ S ≀ T := iff.rfl @[to_additive] instance : partial_order (submonoid M) := { le := Ξ» S T, βˆ€ ⦃x⦄, x ∈ S β†’ x ∈ T, .. partial_order.lift (coe : submonoid M β†’ set M) ext' } @[simp, norm_cast, to_additive] lemma coe_ssubset_coe {S T : submonoid M} : (S : set M) βŠ‚ T ↔ S < T := iff.rfl attribute [norm_cast] add_submonoid.coe_subset_coe add_submonoid.coe_ssubset_coe /-- The submonoid `M` of the monoid `M`. -/ @[to_additive "The additive submonoid `M` of the `add_monoid M`."] instance : has_top (submonoid M) := ⟨{ carrier := set.univ, one_mem' := set.mem_univ 1, mul_mem' := Ξ» _ _ _ _, set.mem_univ _ }⟩ /-- The trivial submonoid `{1}` of an monoid `M`. -/ @[to_additive "The trivial `add_submonoid` `{0}` of an `add_monoid` `M`."] instance : has_bot (submonoid M) := ⟨{ carrier := {1}, one_mem' := set.mem_singleton 1, mul_mem' := Ξ» a b ha hb, by { simp only [set.mem_singleton_iff] at *, rw [ha, hb, mul_one] }}⟩ @[to_additive] instance : inhabited (submonoid M) := ⟨βŠ₯⟩ @[simp, to_additive] lemma mem_bot {x : M} : x ∈ (βŠ₯ : submonoid M) ↔ x = 1 := set.mem_singleton_iff @[simp, to_additive] lemma mem_top (x : M) : x ∈ (⊀ : submonoid M) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊀ : submonoid M) : set M) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((βŠ₯ : submonoid M) : set M) = {1} := rfl /-- The inf of two submonoids is their intersection. -/ @[to_additive "The inf of two `add_submonoid`s is their intersection."] instance : has_inf (submonoid M) := ⟨λ S₁ Sβ‚‚, { carrier := S₁ ∩ Sβ‚‚, one_mem' := ⟨S₁.one_mem, Sβ‚‚.one_mem⟩, mul_mem' := Ξ» _ _ ⟨hx, hx'⟩ ⟨hy, hy'⟩, ⟨S₁.mul_mem hx hy, Sβ‚‚.mul_mem hx' hy'⟩ }⟩ @[simp, to_additive] lemma coe_inf (p p' : submonoid M) : ((p βŠ“ p' : submonoid M) : set M) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : submonoid M} {x : M} : x ∈ p βŠ“ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (submonoid M) := ⟨λ s, { carrier := β‹‚ t ∈ s, ↑t, one_mem' := set.mem_bInter $ Ξ» i h, i.one_mem, mul_mem' := Ξ» x y hx hy, set.mem_bInter $ Ξ» i h, i.mul_mem (by apply set.mem_bInter_iff.1 hx i h) (by apply set.mem_bInter_iff.1 hy i h) }⟩ @[simp, to_additive] lemma coe_Inf (S : set (submonoid M)) : ((Inf S : submonoid M) : set M) = β‹‚ s ∈ S, ↑s := rfl @[to_additive] lemma mem_Inf {S : set (submonoid M)} {x : M} : x ∈ Inf S ↔ βˆ€ p ∈ S, x ∈ p := set.mem_bInter_iff @[to_additive] lemma mem_infi {ΞΉ : Sort*} {S : ΞΉ β†’ submonoid M} {x : M} : (x ∈ β¨… i, S i) ↔ βˆ€ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, to_additive] lemma coe_infi {ΞΉ : Sort*} {S : ΞΉ β†’ submonoid M} : (↑(β¨… i, S i) : set M) = β‹‚ i, S i := by simp only [infi, coe_Inf, set.bInter_range] attribute [norm_cast] coe_Inf coe_infi /-- Submonoids of a monoid form a complete lattice. -/ @[to_additive "The `add_submonoid`s of an `add_monoid` form a complete lattice."] instance : complete_lattice (submonoid M) := { le := (≀), lt := (<), bot := (βŠ₯), bot_le := Ξ» S x hx, (mem_bot.1 hx).symm β–Έ S.one_mem, top := (⊀), le_top := Ξ» S x hx, mem_top x, inf := (βŠ“), Inf := has_Inf.Inf, le_inf := Ξ» a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := Ξ» a b x, and.left, inf_le_right := Ξ» a b x, and.right, .. complete_lattice_of_Inf (submonoid M) $ Ξ» s, is_glb.of_image (Ξ» S T, show (S : set M) ≀ T ↔ S ≀ T, from coe_subset_coe) is_glb_binfi } /-- The `submonoid` generated by a set. -/ @[to_additive "The `add_submonoid` generated by a set"] def closure (s : set M) : submonoid M := Inf {S | s βŠ† S} @[to_additive] lemma mem_closure {x : M} : x ∈ closure s ↔ βˆ€ S : submonoid M, s βŠ† S β†’ x ∈ S := mem_Inf /-- The submonoid generated by a set includes the set. -/ @[simp, to_additive "The `add_submonoid` generated by a set includes the set."] lemma subset_closure : s βŠ† closure s := Ξ» x hx, mem_closure.2 $ Ξ» S hS, hS hx variable {S} open set /-- A submonoid `S` includes `closure s` if and only if it includes `s`. -/ @[simp, to_additive "An additive submonoid `S` includes `closure s` if and only if it includes `s`"] lemma closure_le : closure s ≀ S ↔ s βŠ† S := ⟨subset.trans subset_closure, Ξ» h, Inf_le h⟩ /-- Submonoid closure of a set is monotone in its argument: if `s βŠ† t`, then `closure s ≀ closure t`. -/ @[to_additive "Additive submonoid closure of a set is monotone in its argument: if `s βŠ† t`, then `closure s ≀ closure t`"] lemma closure_mono ⦃s t : set M⦄ (h : s βŠ† t) : closure s ≀ closure t := closure_le.2 $ subset.trans h subset_closure @[to_additive] lemma closure_eq_of_le (h₁ : s βŠ† S) (hβ‚‚ : S ≀ closure s) : closure s = S := le_antisymm (closure_le.2 h₁) hβ‚‚ variable (S) /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `s`, and is preserved under multiplication, then `p` holds for all elements of the closure of `s`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `s`, and is preserved under addition, then `p` holds for all elements of the additive closure of `s`."] lemma closure_induction {p : M β†’ Prop} {x} (h : x ∈ closure s) (Hs : βˆ€ x ∈ s, p x) (H1 : p 1) (Hmul : βˆ€ x y, p x β†’ p y β†’ p (x * y)) : p x := (@closure_le _ _ _ ⟨p, H1, Hmul⟩).2 Hs h attribute [elab_as_eliminator] submonoid.closure_induction add_submonoid.closure_induction /-- If `s` is a dense set in a monoid `M`, `submonoid.closure s = ⊀`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 1`, and verify that `p x` and `p y` imply `p (x * y)`. -/ @[to_additive] lemma dense_induction {p : M β†’ Prop} (x : M) {s : set M} (hs : closure s = ⊀) (Hs : βˆ€ x ∈ s, p x) (H1 : p 1) (Hmul : βˆ€ x y, p x β†’ p y β†’ p (x * y)) : p x := have βˆ€ x ∈ closure s, p x, from Ξ» x hx, closure_induction hx Hs H1 Hmul, by simpa [hs] using this x /-- If `s` is a dense set in an additive monoid `M`, `add_submonoid.closure s = ⊀`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 0`, and verify that `p x` and `p y` imply `p (x + y)`. -/ add_decl_doc add_submonoid.dense_induction attribute [elab_as_eliminator] dense_induction add_submonoid.dense_induction variable (M) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure M _) coe := { choice := Ξ» s _, closure s, gc := Ξ» s t, closure_le, le_l_u := Ξ» s, subset_closure, choice_eq := Ξ» s h, rfl } variable {M} /-- Closure of a submonoid `S` equals `S`. -/ @[simp, to_additive "Additive closure of an additive submonoid `S` equals `S`"] lemma closure_eq : closure (S : set M) = S := (submonoid.gi M).l_u_eq S @[simp, to_additive] lemma closure_empty : closure (βˆ… : set M) = βŠ₯ := (submonoid.gi M).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set M) = ⊀ := @coe_top M _ β–Έ closure_eq ⊀ @[to_additive] lemma closure_union (s t : set M) : closure (s βˆͺ t) = closure s βŠ” closure t := (submonoid.gi M).gc.l_sup @[to_additive] lemma closure_Union {ΞΉ} (s : ΞΉ β†’ set M) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (submonoid.gi M).gc.l_supr end submonoid namespace monoid_hom variables {N : Type*} {P : Type*} [monoid N] [monoid P] (S : submonoid M) open submonoid /-- The submonoid of elements `x : M` such that `f x = g x` -/ @[to_additive "The additive submonoid of elements `x : M` such that `f x = g x`"] def eq_mlocus (f g : M β†’* N) : submonoid M := { carrier := {x | f x = g x}, one_mem' := by rw [set.mem_set_of_eq, f.map_one, g.map_one], mul_mem' := Ξ» x y (hx : _ = _) (hy : _ = _), by simp [*] } /-- If two monoid homomorphisms are equal on a set, then they are equal on its submonoid closure. -/ @[to_additive] lemma eq_on_mclosure {f g : M β†’* N} {s : set M} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≀ f.eq_mlocus g, from closure_le.2 h @[to_additive] lemma eq_of_eq_on_mtop {f g : M β†’* N} (h : set.eq_on f g (⊀ : submonoid M)) : f = g := ext $ Ξ» x, h trivial @[to_additive] lemma eq_of_eq_on_mdense {s : set M} (hs : closure s = ⊀) {f g : M β†’* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_mtop $ hs β–Έ eq_on_mclosure h /-- Let `s` be a subset of a monoid `M` such that the closure of `s` is the whole monoid. Then `monoid_hom.of_mdense` defines a monoid homomorphism from `M` asking for a proof of `f (x * y) = f x * f y` only for `y ∈ s`. -/ @[to_additive] def of_mdense (f : M β†’ N) (hs : closure s = ⊀) (h1 : f 1 = 1) (hmul : βˆ€ x (y ∈ s), f (x * y) = f x * f y) : M β†’* N := { to_fun := f, map_one' := h1, map_mul' := Ξ» x y, dense_induction y hs (Ξ» y hy x, hmul x y hy) (by simp [h1]) (Ξ» y₁ yβ‚‚ h₁ hβ‚‚ x, by simp only [← mul_assoc, h₁, hβ‚‚]) x } /-- Let `s` be a subset of an additive monoid `M` such that the closure of `s` is the whole monoid. Then `add_monoid_hom.of_mdense` defines an additive monoid homomorphism from `M` asking for a proof of `f (x + y) = f x + f y` only for `y ∈ s`. -/ add_decl_doc add_monoid_hom.of_mdense @[simp, to_additive] lemma coe_of_mdense (f : M β†’ N) (hs : closure s = ⊀) (h1 hmul) : ⇑(of_mdense f hs h1 hmul) = f := rfl attribute [norm_cast] coe_of_mdense add_monoid_hom.coe_of_mdense end monoid_hom
430a8179b515613f8e78034198f944da77a13638
fc086f79b20cf002d6f34b023749998408e94fbf
/test/tidy_problem.lean
9f6a4abe51f56ff44e05b1526a69929c32710469
[]
no_license
semorrison/lean-tidy
f039460136b898fb282f75efedd92f2d5c5d90f8
6c1d46de6cff05e1c2c4c9692af812bca3e13b6c
refs/heads/master
1,624,461,332,392
1,559,655,744,000
1,559,655,744,000
96,569,994
9
4
null
1,538,287,895,000
1,499,455,306,000
Lean
UTF-8
Lean
false
false
612
lean
import data.polynomial -- compare the result when you uncomment this import -- error! -- import tidy.tidy -- This is now broken without this include, too! class algebra (R : out_param $ Type*) [comm_ring R] (A : Type*) extends ring A := (f : R β†’ A) [hom : is_ring_hom f] (commutes : βˆ€ r s, s * f r = f r * s) variables (R : Type*) [ring R] -- instance ring.to_β„€_algebra : algebra β„€ R := -- { f := coe, -- hom := by constructor; intros; simp, -- commutes := Ξ» n r, int.induction_on n (by simp) -- (Ξ» i ih, by simp [mul_add, add_mul, ih]) -- (Ξ» i ih, by simp [mul_add, add_mul, ih]), }
17db5bd79c987acd6d01ce7be77a09b56caeae50
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/limits/opposites.lean
0b0e88529db86081593860da84ed44fdaa4d1a84
[ "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
25,753
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Floris van Doorn -/ import category_theory.limits.shapes.finite_products import category_theory.discrete_category import tactic.equiv_rw /-! # Limits in `C` give colimits in `Cα΅’α΅–`. We also give special cases for (co)products, (co)equalizers, and pullbacks / pushouts. -/ universes v₁ vβ‚‚ u₁ uβ‚‚ noncomputable theory open category_theory open category_theory.functor open opposite namespace category_theory.limits variables {C : Type u₁} [category.{v₁} C] variables {J : Type uβ‚‚} [category.{vβ‚‚} J] /-- Turn a colimit for `F : J β₯€ C` into a limit for `F.op : Jα΅’α΅– β₯€ Cα΅’α΅–`. -/ @[simps] def is_limit_cocone_op (F : J β₯€ C) {c : cocone F} (hc : is_colimit c) : is_limit c.op := { lift := Ξ» s, (hc.desc s.unop).op, fac' := Ξ» s j, quiver.hom.unop_inj (by simpa), uniq' := Ξ» s m w, begin refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)), simpa only [quiver.hom.unop_op, is_colimit.fac] using w (op j) end } /-- Turn a limit for `F : J β₯€ C` into a colimit for `F.op : Jα΅’α΅– β₯€ Cα΅’α΅–`. -/ @[simps] def is_colimit_cone_op (F : J β₯€ C) {c : cone F} (hc : is_limit c) : is_colimit c.op := { desc := Ξ» s, (hc.lift s.unop).op, fac' := Ξ» s j, quiver.hom.unop_inj (by simpa), uniq' := Ξ» s m w, begin refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)), simpa only [quiver.hom.unop_op, is_limit.fac] using w (op j) end } /-- Turn a colimit for `F : J β₯€ Cα΅’α΅–` into a limit for `F.left_op : Jα΅’α΅– β₯€ C`. -/ @[simps] def is_limit_cone_left_op_of_cocone (F : J β₯€ Cα΅’α΅–) {c : cocone F} (hc : is_colimit c) : is_limit (cone_left_op_of_cocone c) := { lift := Ξ» s, (hc.desc (cocone_of_cone_left_op s)).unop, fac' := Ξ» s j, quiver.hom.op_inj $ by simpa only [cone_left_op_of_cocone_Ο€_app, op_comp, quiver.hom.op_unop, is_colimit.fac, cocone_of_cone_left_op_ΞΉ_app], uniq' := Ξ» s m w, begin refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)), simpa only [quiver.hom.op_unop, is_colimit.fac, cocone_of_cone_left_op_ΞΉ_app] using w (op j) end } /-- Turn a limit of `F : J β₯€ Cα΅’α΅–` into a colimit of `F.left_op : Jα΅’α΅– β₯€ C`. -/ @[simps] def is_colimit_cocone_left_op_of_cone (F : J β₯€ Cα΅’α΅–) {c : cone F} (hc : is_limit c) : is_colimit (cocone_left_op_of_cone c) := { desc := Ξ» s, (hc.lift (cone_of_cocone_left_op s)).unop, fac' := Ξ» s j, quiver.hom.op_inj $ by simpa only [cocone_left_op_of_cone_ΞΉ_app, op_comp, quiver.hom.op_unop, is_limit.fac, cone_of_cocone_left_op_Ο€_app], uniq' := Ξ» s m w, begin refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)), simpa only [quiver.hom.op_unop, is_limit.fac, cone_of_cocone_left_op_Ο€_app] using w (op j) end } /-- Turn a colimit for `F : Jα΅’α΅– β₯€ C` into a limit for `F.right_op : J β₯€ Cα΅’α΅–`. -/ @[simps] def is_limit_cone_right_op_of_cocone (F : Jα΅’α΅– β₯€ C) {c : cocone F} (hc : is_colimit c) : is_limit (cone_right_op_of_cocone c) := { lift := Ξ» s, (hc.desc (cocone_of_cone_right_op s)).op, fac' := Ξ» s j, quiver.hom.unop_inj (by simpa), uniq' := Ξ» s m w, begin refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)), simpa only [quiver.hom.unop_op, is_colimit.fac] using w (unop j) end } /-- Turn a limit for `F : Jα΅’α΅– β₯€ C` into a colimit for `F.right_op : J β₯€ Cα΅’α΅–`. -/ @[simps] def is_colimit_cocone_right_op_of_cone (F : Jα΅’α΅– β₯€ C) {c : cone F} (hc : is_limit c) : is_colimit (cocone_right_op_of_cone c) := { desc := Ξ» s, (hc.lift (cone_of_cocone_right_op s)).op, fac' := Ξ» s j, quiver.hom.unop_inj (by simpa), uniq' := Ξ» s m w, begin refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)), simpa only [quiver.hom.unop_op, is_limit.fac] using w (unop j) end } /-- Turn a colimit for `F : Jα΅’α΅– β₯€ Cα΅’α΅–` into a limit for `F.unop : J β₯€ C`. -/ @[simps] def is_limit_cone_unop_of_cocone (F : Jα΅’α΅– β₯€ Cα΅’α΅–) {c : cocone F} (hc : is_colimit c) : is_limit (cone_unop_of_cocone c) := { lift := Ξ» s, (hc.desc (cocone_of_cone_unop s)).unop, fac' := Ξ» s j, quiver.hom.op_inj (by simpa), uniq' := Ξ» s m w, begin refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)), simpa only [quiver.hom.op_unop, is_colimit.fac] using w (unop j) end } /-- Turn a limit of `F : Jα΅’α΅– β₯€ Cα΅’α΅–` into a colimit of `F.unop : J β₯€ C`. -/ @[simps] def is_colimit_cocone_unop_of_cone (F : Jα΅’α΅– β₯€ Cα΅’α΅–) {c : cone F} (hc : is_limit c) : is_colimit (cocone_unop_of_cone c) := { desc := Ξ» s, (hc.lift (cone_of_cocone_unop s)).unop, fac' := Ξ» s j, quiver.hom.op_inj (by simpa), uniq' := Ξ» s m w, begin refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)), simpa only [quiver.hom.op_unop, is_limit.fac] using w (unop j) end } /-- Turn a colimit for `F.op : Jα΅’α΅– β₯€ Cα΅’α΅–` into a limit for `F : J β₯€ C`. -/ @[simps] def is_limit_cocone_unop (F : J β₯€ C) {c : cocone F.op} (hc : is_colimit c) : is_limit c.unop := { lift := Ξ» s, (hc.desc s.op).unop, fac' := Ξ» s j, quiver.hom.op_inj (by simpa), uniq' := Ξ» s m w, begin refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)), simpa only [quiver.hom.op_unop, is_colimit.fac] using w (unop j) end } /-- Turn a limit for `F.op : Jα΅’α΅– β₯€ Cα΅’α΅–` into a colimit for `F : J β₯€ C`. -/ @[simps] def is_colimit_cone_unop (F : J β₯€ C) {c : cone F.op} (hc : is_limit c) : is_colimit c.unop := { desc := Ξ» s, (hc.lift s.op).unop, fac' := Ξ» s j, quiver.hom.op_inj (by simpa), uniq' := Ξ» s m w, begin refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)), simpa only [quiver.hom.op_unop, is_limit.fac] using w (unop j) end } /-- Turn a colimit for `F.left_op : Jα΅’α΅– β₯€ C` into a limit for `F : J β₯€ Cα΅’α΅–`. -/ @[simps] def is_limit_cone_of_cocone_left_op (F : J β₯€ Cα΅’α΅–) {c : cocone F.left_op} (hc : is_colimit c) : is_limit (cone_of_cocone_left_op c) := { lift := Ξ» s, (hc.desc (cocone_left_op_of_cone s)).op, fac' := Ξ» s j, quiver.hom.unop_inj $ by simpa only [cone_of_cocone_left_op_Ο€_app, unop_comp, quiver.hom.unop_op, is_colimit.fac, cocone_left_op_of_cone_ΞΉ_app], uniq' := Ξ» s m w, begin refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)), simpa only [quiver.hom.unop_op, is_colimit.fac, cone_of_cocone_left_op_Ο€_app] using w (unop j) end } /-- Turn a limit of `F.left_op : Jα΅’α΅– β₯€ C` into a colimit of `F : J β₯€ Cα΅’α΅–`. -/ @[simps] def is_colimit_cocone_of_cone_left_op (F : J β₯€ Cα΅’α΅–) {c : cone (F.left_op)} (hc : is_limit c) : is_colimit (cocone_of_cone_left_op c) := { desc := Ξ» s, (hc.lift (cone_left_op_of_cocone s)).op, fac' := Ξ» s j, quiver.hom.unop_inj $ by simpa only [cocone_of_cone_left_op_ΞΉ_app, unop_comp, quiver.hom.unop_op, is_limit.fac, cone_left_op_of_cocone_Ο€_app], uniq' := Ξ» s m w, begin refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)), simpa only [quiver.hom.unop_op, is_limit.fac, cocone_of_cone_left_op_ΞΉ_app] using w (unop j) end } /-- Turn a colimit for `F.right_op : J β₯€ Cα΅’α΅–` into a limit for `F : Jα΅’α΅– β₯€ C`. -/ @[simps] def is_limit_cone_of_cocone_right_op (F : Jα΅’α΅– β₯€ C) {c : cocone F.right_op} (hc : is_colimit c) : is_limit (cone_of_cocone_right_op c) := { lift := Ξ» s, (hc.desc (cocone_right_op_of_cone s)).unop, fac' := Ξ» s j, quiver.hom.op_inj (by simpa), uniq' := Ξ» s m w, begin refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)), simpa only [quiver.hom.op_unop, is_colimit.fac] using w (op j) end } /-- Turn a limit for `F.right_op : J β₯€ Cα΅’α΅–` into a limit for `F : Jα΅’α΅– β₯€ C`. -/ @[simps] def is_colimit_cocone_of_cone_right_op (F : Jα΅’α΅– β₯€ C) {c : cone F.right_op} (hc : is_limit c) : is_colimit (cocone_of_cone_right_op c) := { desc := Ξ» s, (hc.lift (cone_right_op_of_cocone s)).unop, fac' := Ξ» s j, quiver.hom.op_inj (by simpa), uniq' := Ξ» s m w, begin refine quiver.hom.op_inj (hc.hom_ext (Ξ» j, quiver.hom.unop_inj _)), simpa only [quiver.hom.op_unop, is_limit.fac] using w (op j) end } /-- Turn a colimit for `F.unop : J β₯€ C` into a limit for `F : Jα΅’α΅– β₯€ Cα΅’α΅–`. -/ @[simps] def is_limit_cone_of_cocone_unop (F : Jα΅’α΅– β₯€ Cα΅’α΅–) {c : cocone F.unop} (hc : is_colimit c) : is_limit (cone_of_cocone_unop c) := { lift := Ξ» s, (hc.desc (cocone_unop_of_cone s)).op, fac' := Ξ» s j, quiver.hom.unop_inj (by simpa), uniq' := Ξ» s m w, begin refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)), simpa only [quiver.hom.unop_op, is_colimit.fac] using w (op j) end } /-- Turn a limit for `F.unop : J β₯€ C` into a colimit for `F : Jα΅’α΅– β₯€ Cα΅’α΅–`. -/ @[simps] def is_colimit_cone_of_cocone_unop (F : Jα΅’α΅– β₯€ Cα΅’α΅–) {c : cone F.unop} (hc : is_limit c) : is_colimit (cocone_of_cone_unop c) := { desc := Ξ» s, (hc.lift (cone_unop_of_cocone s)).op, fac' := Ξ» s j, quiver.hom.unop_inj (by simpa), uniq' := Ξ» s m w, begin refine quiver.hom.unop_inj (hc.hom_ext (Ξ» j, quiver.hom.op_inj _)), simpa only [quiver.hom.unop_op, is_limit.fac] using w (op j) end } /-- If `F.left_op : Jα΅’α΅– β₯€ C` has a colimit, we can construct a limit for `F : J β₯€ Cα΅’α΅–`. -/ lemma has_limit_of_has_colimit_left_op (F : J β₯€ Cα΅’α΅–) [has_colimit F.left_op] : has_limit F := has_limit.mk { cone := cone_of_cocone_left_op (colimit.cocone F.left_op), is_limit := is_limit_cone_of_cocone_left_op _ (colimit.is_colimit _) } /-- If `C` has colimits of shape `Jα΅’α΅–`, we can construct limits in `Cα΅’α΅–` of shape `J`. -/ lemma has_limits_of_shape_op_of_has_colimits_of_shape [has_colimits_of_shape Jα΅’α΅– C] : has_limits_of_shape J Cα΅’α΅– := { has_limit := Ξ» F, has_limit_of_has_colimit_left_op F } local attribute [instance] has_limits_of_shape_op_of_has_colimits_of_shape /-- If `C` has colimits, we can construct limits for `Cα΅’α΅–`. -/ instance has_limits_op_of_has_colimits [has_colimits C] : has_limits Cα΅’α΅– := ⟨infer_instance⟩ /-- If `F.left_op : Jα΅’α΅– β₯€ C` has a limit, we can construct a colimit for `F : J β₯€ Cα΅’α΅–`. -/ lemma has_colimit_of_has_limit_left_op (F : J β₯€ Cα΅’α΅–) [has_limit F.left_op] : has_colimit F := has_colimit.mk { cocone := cocone_of_cone_left_op (limit.cone F.left_op), is_colimit := is_colimit_cocone_of_cone_left_op _ (limit.is_limit _) } /-- If `C` has colimits of shape `Jα΅’α΅–`, we can construct limits in `Cα΅’α΅–` of shape `J`. -/ lemma has_colimits_of_shape_op_of_has_limits_of_shape [has_limits_of_shape Jα΅’α΅– C] : has_colimits_of_shape J Cα΅’α΅– := { has_colimit := Ξ» F, has_colimit_of_has_limit_left_op F } local attribute [instance] has_colimits_of_shape_op_of_has_limits_of_shape /-- If `C` has limits, we can construct colimits for `Cα΅’α΅–`. -/ instance has_colimits_op_of_has_limits [has_limits C] : has_colimits Cα΅’α΅– := ⟨infer_instance⟩ variables (X : Type v₁) /-- If `C` has products indexed by `X`, then `Cα΅’α΅–` has coproducts indexed by `X`. -/ instance has_coproducts_opposite [has_products_of_shape X C] : has_coproducts_of_shape X Cα΅’α΅– := begin haveI : has_limits_of_shape (discrete X)α΅’α΅– C := has_limits_of_shape_of_equivalence (discrete.opposite X).symm, apply_instance end /-- If `C` has coproducts indexed by `X`, then `Cα΅’α΅–` has products indexed by `X`. -/ instance has_products_opposite [has_coproducts_of_shape X C] : has_products_of_shape X Cα΅’α΅– := begin haveI : has_colimits_of_shape (discrete X)α΅’α΅– C := has_colimits_of_shape_of_equivalence (discrete.opposite X).symm, apply_instance end instance has_finite_coproducts_opposite [has_finite_products C] : has_finite_coproducts Cα΅’α΅– := { out := Ξ» J π’Ÿ, begin resetI, haveI : has_limits_of_shape (discrete J)α΅’α΅– C := has_limits_of_shape_of_equivalence (discrete.opposite J).symm, apply_instance, end } instance has_finite_products_opposite [has_finite_coproducts C] : has_finite_products Cα΅’α΅– := { out := Ξ» J π’Ÿ, begin resetI, haveI : has_colimits_of_shape (discrete J)α΅’α΅– C := has_colimits_of_shape_of_equivalence (discrete.opposite J).symm, apply_instance, end } instance has_equalizers_opposite [has_coequalizers C] : has_equalizers Cα΅’α΅– := begin haveI : has_colimits_of_shape walking_parallel_pairα΅’α΅– C := has_colimits_of_shape_of_equivalence walking_parallel_pair_op_equiv, apply_instance end instance has_coequalizers_opposite [has_equalizers C] : has_coequalizers Cα΅’α΅– := begin haveI : has_limits_of_shape walking_parallel_pairα΅’α΅– C := has_limits_of_shape_of_equivalence walking_parallel_pair_op_equiv, apply_instance end instance has_finite_colimits_opposite [has_finite_limits C] : has_finite_colimits Cα΅’α΅– := { out := Ξ» J π’Ÿ π’₯, by { resetI, apply_instance, }, } instance has_finite_limits_opposite [has_finite_colimits C] : has_finite_limits Cα΅’α΅– := { out := Ξ» J π’Ÿ π’₯, by { resetI, apply_instance, }, } instance has_pullbacks_opposite [has_pushouts C] : has_pullbacks Cα΅’α΅– := begin haveI : has_colimits_of_shape walking_cospanα΅’α΅– C := has_colimits_of_shape_of_equivalence walking_cospan_op_equiv.symm, apply has_limits_of_shape_op_of_has_colimits_of_shape, end instance has_pushouts_opposite [has_pullbacks C] : has_pushouts Cα΅’α΅– := begin haveI : has_limits_of_shape walking_spanα΅’α΅– C := has_limits_of_shape_of_equivalence walking_span_op_equiv.symm, apply has_colimits_of_shape_op_of_has_limits_of_shape, end /-- The canonical isomorphism relating `span f.op g.op` and `(cospan f g).op` -/ @[simps] def span_op {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) : span f.op g.op β‰… walking_cospan_op_equiv.inverse β‹™ (cospan f g).op := nat_iso.of_components (by { rintro (_|_|_); refl, }) (by { rintros (_|_|_) (_|_|_) f; cases f; tidy, }) /-- The canonical isomorphism relating `(cospan f g).op` and `span f.op g.op` -/ @[simps] def op_cospan {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) : (cospan f g).op β‰… walking_cospan_op_equiv.functor β‹™ span f.op g.op := calc (cospan f g).op β‰… 𝟭 _ β‹™ (cospan f g).op : by refl ... β‰… (walking_cospan_op_equiv.functor β‹™ walking_cospan_op_equiv.inverse) β‹™ (cospan f g).op : iso_whisker_right walking_cospan_op_equiv.unit_iso _ ... β‰… walking_cospan_op_equiv.functor β‹™ (walking_cospan_op_equiv.inverse β‹™ (cospan f g).op) : functor.associator _ _ _ ... β‰… walking_cospan_op_equiv.functor β‹™ span f.op g.op : iso_whisker_left _ (span_op f g).symm /-- The canonical isomorphism relating `cospan f.op g.op` and `(span f g).op` -/ @[simps] def cospan_op {X Y Z : C} (f : X ⟢ Y) (g : X ⟢ Z) : cospan f.op g.op β‰… walking_span_op_equiv.inverse β‹™ (span f g).op := nat_iso.of_components (by { rintro (_|_|_); refl, }) (by { rintros (_|_|_) (_|_|_) f; cases f; tidy, }) /-- The canonical isomorphism relating `(span f g).op` and `cospan f.op g.op` -/ @[simps] def op_span {X Y Z : C} (f : X ⟢ Y) (g : X ⟢ Z) : (span f g).op β‰… walking_span_op_equiv.functor β‹™ cospan f.op g.op := calc (span f g).op β‰… 𝟭 _ β‹™ (span f g).op : by refl ... β‰… (walking_span_op_equiv.functor β‹™ walking_span_op_equiv.inverse) β‹™ (span f g).op : iso_whisker_right walking_span_op_equiv.unit_iso _ ... β‰… walking_span_op_equiv.functor β‹™ (walking_span_op_equiv.inverse β‹™ (span f g).op) : functor.associator _ _ _ ... β‰… walking_span_op_equiv.functor β‹™ cospan f.op g.op : iso_whisker_left _ (cospan_op f g).symm namespace pushout_cocone /-- The obvious map `pushout_cocone f g β†’ pullback_cone f.unop g.unop` -/ @[simps (lemmas_only)] def unop {X Y Z : Cα΅’α΅–} {f : X ⟢ Y} {g : X ⟢ Z} (c : pushout_cocone f g) : pullback_cone f.unop g.unop := cocone.unop ((cocones.precompose (op_cospan f.unop g.unop).hom).obj (cocone.whisker walking_cospan_op_equiv.functor c)) @[simp] lemma unop_fst {X Y Z : Cα΅’α΅–} {f : X ⟢ Y} {g : X ⟢ Z} (c : pushout_cocone f g) : c.unop.fst = c.inl.unop := by { change (_ : limits.cone _).Ο€.app _ = _, simp only [pushout_cocone.ΞΉ_app_left, pushout_cocone.unop_Ο€_app], tidy } @[simp] lemma unop_snd {X Y Z : Cα΅’α΅–} {f : X ⟢ Y} {g : X ⟢ Z} (c : pushout_cocone f g) : c.unop.snd = c.inr.unop := by { change (_ : limits.cone _).Ο€.app _ = _, simp only [pushout_cocone.unop_Ο€_app, pushout_cocone.ΞΉ_app_right], tidy, } /-- The obvious map `pushout_cocone f.op g.op β†’ pullback_cone f g` -/ @[simps (lemmas_only)] def op {X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} (c : pushout_cocone f g) : pullback_cone f.op g.op := (cones.postcompose ((cospan_op f g).symm).hom).obj (cone.whisker walking_span_op_equiv.inverse (cocone.op c)) @[simp] lemma op_fst {X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} (c : pushout_cocone f g) : c.op.fst = c.inl.op := by { change (_ : limits.cone _).Ο€.app _ = _, apply category.comp_id, } @[simp] lemma op_snd {X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} (c : pushout_cocone f g) : c.op.snd = c.inr.op := by { change (_ : limits.cone _).Ο€.app _ = _, apply category.comp_id, } end pushout_cocone namespace pullback_cone /-- The obvious map `pullback_cone f g β†’ pushout_cocone f.unop g.unop` -/ @[simps (lemmas_only)] def unop {X Y Z : Cα΅’α΅–} {f : X ⟢ Z} {g : Y ⟢ Z} (c : pullback_cone f g) : pushout_cocone f.unop g.unop := cone.unop ((cones.postcompose (op_span f.unop g.unop).symm.hom).obj (cone.whisker walking_span_op_equiv.functor c)) @[simp] lemma unop_inl {X Y Z : Cα΅’α΅–} {f : X ⟢ Z} {g : Y ⟢ Z} (c : pullback_cone f g) : c.unop.inl = c.fst.unop := begin change ((_ : limits.cocone _).ΞΉ.app _) = _, dsimp only [unop, op_span], simp, dsimp, simp, dsimp, simp end @[simp] lemma unop_inr {X Y Z : Cα΅’α΅–} {f : X ⟢ Z} {g : Y ⟢ Z} (c : pullback_cone f g) : c.unop.inr = c.snd.unop := begin change ((_ : limits.cocone _).ΞΉ.app _) = _, apply quiver.hom.op_inj, simp [unop_ΞΉ_app], dsimp, simp, apply category.comp_id, end /-- The obvious map `pullback_cone f g β†’ pushout_cocone f.op g.op` -/ @[simps (lemmas_only)] def op {X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} (c : pullback_cone f g) : pushout_cocone f.op g.op := (cocones.precompose (span_op f g).hom).obj (cocone.whisker walking_cospan_op_equiv.inverse (cone.op c)) @[simp] lemma op_inl {X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} (c : pullback_cone f g) : c.op.inl = c.fst.op := by { change (_ : limits.cocone _).ΞΉ.app _ = _, apply category.id_comp, } @[simp] lemma op_inr {X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} (c : pullback_cone f g) : c.op.inr = c.snd.op := by { change (_ : limits.cocone _).ΞΉ.app _ = _, apply category.id_comp, } /-- If `c` is a pullback cone, then `c.op.unop` is isomorphic to `c`. -/ def op_unop {X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} (c : pullback_cone f g) : c.op.unop β‰… c := pullback_cone.ext (iso.refl _) (by simp) (by simp) /-- If `c` is a pullback cone in `Cα΅’α΅–`, then `c.unop.op` is isomorphic to `c`. -/ def unop_op {X Y Z : Cα΅’α΅–} {f : X ⟢ Z} {g : Y ⟢ Z} (c : pullback_cone f g) : c.unop.op β‰… c := pullback_cone.ext (iso.refl _) (by simp) (by simp) end pullback_cone namespace pushout_cocone /-- If `c` is a pushout cocone, then `c.op.unop` is isomorphic to `c`. -/ def op_unop {X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} (c : pushout_cocone f g) : c.op.unop β‰… c := pushout_cocone.ext (iso.refl _) (by simp) (by simp) /-- If `c` is a pushout cocone in `Cα΅’α΅–`, then `c.unop.op` is isomorphic to `c`. -/ def unop_op {X Y Z : Cα΅’α΅–} {f : X ⟢ Y} {g : X ⟢ Z} (c : pushout_cocone f g) : c.unop.op β‰… c := pushout_cocone.ext (iso.refl _) (by simp) (by simp) /-- A pushout cone is a colimit cocone if and only if the corresponding pullback cone in the opposite category is a limit cone. -/ def is_colimit_equiv_is_limit_op {X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} (c : pushout_cocone f g) : is_colimit c ≃ is_limit c.op := begin apply equiv_of_subsingleton_of_subsingleton, { intro h, equiv_rw is_limit.postcompose_hom_equiv _ _, equiv_rw (is_limit.whisker_equivalence_equiv walking_span_op_equiv.symm).symm, exact is_limit_cocone_op _ h, }, { intro h, equiv_rw is_colimit.equiv_iso_colimit c.op_unop.symm, apply is_colimit_cone_unop, equiv_rw is_limit.postcompose_hom_equiv _ _, equiv_rw (is_limit.whisker_equivalence_equiv _).symm, exact h, } end /-- A pushout cone is a colimit cocone in `Cα΅’α΅–` if and only if the corresponding pullback cone in `C` is a limit cone. -/ def is_colimit_equiv_is_limit_unop {X Y Z : Cα΅’α΅–} {f : X ⟢ Y} {g : X ⟢ Z} (c : pushout_cocone f g) : is_colimit c ≃ is_limit c.unop := begin apply equiv_of_subsingleton_of_subsingleton, { intro h, apply is_limit_cocone_unop, equiv_rw is_colimit.precompose_hom_equiv _ _, equiv_rw (is_colimit.whisker_equivalence_equiv _).symm, exact h, }, { intro h, equiv_rw is_colimit.equiv_iso_colimit c.unop_op.symm, equiv_rw is_colimit.precompose_hom_equiv _ _, equiv_rw (is_colimit.whisker_equivalence_equiv walking_cospan_op_equiv.symm).symm, exact is_colimit_cone_op _ h, }, end end pushout_cocone namespace pullback_cone /-- A pullback cone is a limit cone if and only if the corresponding pushout cocone in the opposite category is a colimit cocone. -/ def is_limit_equiv_is_colimit_op {X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} (c : pullback_cone f g) : is_limit c ≃ is_colimit c.op := (is_limit.equiv_iso_limit c.op_unop).symm.trans c.op.is_colimit_equiv_is_limit_unop.symm /-- A pullback cone is a limit cone in `Cα΅’α΅–` if and only if the corresponding pushout cocone in `C` is a colimit cocone. -/ def is_limit_equiv_is_colimit_unop {X Y Z : Cα΅’α΅–} {f : X ⟢ Z} {g : Y ⟢ Z} (c : pullback_cone f g) : is_limit c ≃ is_colimit c.unop := (is_limit.equiv_iso_limit c.unop_op).symm.trans c.unop.is_colimit_equiv_is_limit_op.symm end pullback_cone section pullback open opposite /-- The pullback of `f` and `g` in `C` is isomorphic to the pushout of `f.op` and `g.op` in `Cα΅’α΅–`. -/ noncomputable def pullback_iso_unop_pushout {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) [has_pullback f g] [has_pushout f.op g.op] : pullback f g β‰… unop (pushout f.op g.op) := is_limit.cone_point_unique_up_to_iso (limit.is_limit _) ((pushout_cocone.is_colimit_equiv_is_limit_unop _) (colimit.is_colimit (span f.op g.op))) @[simp, reassoc] lemma pullback_iso_unop_pushout_inv_fst {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) [has_pullback f g] [has_pushout f.op g.op] : (pullback_iso_unop_pushout f g).inv ≫ pullback.fst = (pushout.inl : _ ⟢ pushout f.op g.op).unop := (is_limit.cone_point_unique_up_to_iso_inv_comp _ _ _).trans (by simp) @[simp, reassoc] lemma pullback_iso_unop_pushout_inv_snd {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) [has_pullback f g] [has_pushout f.op g.op] : (pullback_iso_unop_pushout f g).inv ≫ pullback.snd = (pushout.inr : _ ⟢ pushout f.op g.op).unop := (is_limit.cone_point_unique_up_to_iso_inv_comp _ _ _).trans (by simp) @[simp, reassoc] lemma pullback_iso_unop_pushout_hom_inl {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) [has_pullback f g] [has_pushout f.op g.op] : pushout.inl ≫ (pullback_iso_unop_pushout f g).hom.op = pullback.fst.op := begin apply quiver.hom.unop_inj, dsimp, rw [← pullback_iso_unop_pushout_inv_fst, iso.hom_inv_id_assoc], end @[simp, reassoc] lemma pullback_iso_unop_pushout_hom_inr {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) [has_pullback f g] [has_pushout f.op g.op] : pushout.inr ≫ (pullback_iso_unop_pushout f g).hom.op = pullback.snd.op := begin apply quiver.hom.unop_inj, dsimp, rw [← pullback_iso_unop_pushout_inv_snd, iso.hom_inv_id_assoc], end end pullback section pushout /-- The pushout of `f` and `g` in `C` is isomorphic to the pullback of `f.op` and `g.op` in `Cα΅’α΅–`. -/ noncomputable def pushout_iso_unop_pullback {X Y Z : C} (f : X ⟢ Z) (g : X ⟢ Y) [has_pushout f g] [has_pullback f.op g.op] : pushout f g β‰… unop (pullback f.op g.op) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) ((pullback_cone.is_limit_equiv_is_colimit_unop _) (limit.is_limit (cospan f.op g.op))) . @[simp, reassoc] lemma pushout_iso_unop_pullback_inl_hom {X Y Z : C} (f : X ⟢ Z) (g : X ⟢ Y) [has_pushout f g] [has_pullback f.op g.op] : pushout.inl ≫ (pushout_iso_unop_pullback f g).hom = (pullback.fst : pullback f.op g.op ⟢ _).unop := (is_colimit.comp_cocone_point_unique_up_to_iso_hom _ _ _).trans (by simp) @[simp, reassoc] lemma pushout_iso_unop_pullback_inr_hom {X Y Z : C} (f : X ⟢ Z) (g : X ⟢ Y) [has_pushout f g] [has_pullback f.op g.op] : pushout.inr ≫ (pushout_iso_unop_pullback f g).hom = (pullback.snd : pullback f.op g.op ⟢ _).unop := (is_colimit.comp_cocone_point_unique_up_to_iso_hom _ _ _).trans (by simp) @[simp] lemma pushout_iso_unop_pullback_inv_fst {X Y Z : C} (f : X ⟢ Z) (g : X ⟢ Y) [has_pushout f g] [has_pullback f.op g.op] : (pushout_iso_unop_pullback f g).inv.op ≫ pullback.fst = pushout.inl.op := begin apply quiver.hom.unop_inj, dsimp, rw [← pushout_iso_unop_pullback_inl_hom, category.assoc, iso.hom_inv_id, category.comp_id], end @[simp] lemma pushout_iso_unop_pullback_inv_snd {X Y Z : C} (f : X ⟢ Z) (g : X ⟢ Y) [has_pushout f g] [has_pullback f.op g.op] : (pushout_iso_unop_pullback f g).inv.op ≫ pullback.snd = pushout.inr.op := begin apply quiver.hom.unop_inj, dsimp, rw [← pushout_iso_unop_pullback_inr_hom, category.assoc, iso.hom_inv_id, category.comp_id], end end pushout end category_theory.limits
9873bf419662aa2df7dbbea95761cd6388afd0b5
f0f12a5b81106a798deda31dca238c11997a605e
/Playlean4/Group/Subgroup.lean
662b119b3a8cbb739962a8b6e99ea9e2ecf46999
[ "MIT" ]
permissive
thejohncrafter/playlean4
fe7119d492aab07048f78333eeda9862f6471740
81df180a71b8d84d0f45bc98db367aad203cf5df
refs/heads/master
1,683,152,783,765
1,621,879,382,000
1,621,879,382,000
366,563,501
2
0
null
null
null
null
UTF-8
Lean
false
false
2,839
lean
import Playlean4.Group.Basic namespace Group section variable (G : Type) (law : G β†’ G β†’ G) [grp : Group G law] (H : Set G) local infixl:70 " * " => id' law @[appUnexpander id'] def subgroup.unexpandMul : Lean.PrettyPrinter.Unexpander | `(id' law G $x $y) => `($x * $y) | _ => throw () local notation "one" => grp.one' -- HACK local notation g"⁻¹" => grp.inv g class Subgroup where oneMem : one ∈ H mulMem : βˆ€ {g}, g ∈ H β†’ βˆ€ {g'}, g' ∈ H β†’ g * g' ∈ H invMem : βˆ€ {g}, g ∈ H β†’ (g⁻¹) ∈ H end namespace Subgroup variable {G : Type} (law : G β†’ G β†’ G) [grp : Group G law] local infixl:70 " * " => id' law @[appUnexpander id'] def unexpandGMul : Lean.PrettyPrinter.Unexpander | `(id' Magma.law G $x $y) => `($x * $y) | _ => throw () local notation "one" => grp.one' -- HACK local notation g"⁻¹" => grp.inv g def subgroupLaw (H : Set G) [Subgroup G law H] : H β†’ H β†’ H := Ξ» g g' => ⟨ (g : G) * (g' : G), mulMem g.2 g'.2 ⟩ instance GroupOfSubgroup (H : Set G) [Subgroup G law H] : Group H (subgroupLaw law H) where one' := ⟨ one, oneMem ⟩ assoc := Ξ» g g' g'' => Subtype.eq <| grp.assoc g.val g'.val g''.val oneNeutralRight := Ξ» g => Subtype.eq <| grp.oneNeutralRight g.val invertible := Ξ» g => ⟨ ⟨ (g.val)⁻¹, invMem g.2 ⟩, Subtype.eq <| invCancelRight (g.val : G) ⟩ section -- "variable" doesn't work here for some reason theorem lemma₁ {H : G β†’ Prop} (inhabited : βˆƒ g : G, g ∈ H) (mulInvStable : βˆ€ {g}, g ∈ H β†’ βˆ€ {g'}, g' ∈ H β†’ g * g'⁻¹ ∈ H) : one ∈ H := match inhabited with | ⟨ g, h ⟩ => invCancelRight g β–Έ mulInvStable h h theorem lemmaβ‚‚ {H : G β†’ Prop} (inhabited : βˆƒ g : G, g ∈ H) (mulInvStable : βˆ€ {g}, g ∈ H β†’ βˆ€ {g'}, g' ∈ H β†’ g * g'⁻¹ ∈ H) : βˆ€ {g}, g ∈ H β†’ g⁻¹ ∈ H := Ξ» {g} hg => oneNeutralLeft (g⁻¹) β–Έ mulInvStable (lemma₁ law inhabited mulInvStable) hg theorem lemma₃ {H : G β†’ Prop} (inhabited : βˆƒ g : G, g ∈ H) (mulInvStable : βˆ€ {g : G}, g ∈ H β†’ βˆ€ {g' : G}, g' ∈ H β†’ g * g'⁻¹ ∈ H) : βˆ€ {g}, g ∈ H β†’ βˆ€ {g'}, g' ∈ H β†’ g * g' ∈ H := Ξ» {g} hg {g'} hg' => invInvolutive g' β–Έ mulInvStable hg (lemmaβ‚‚ law inhabited mulInvStable hg') end instance ofInhabitedMulInvStable {H : G β†’ Prop} (inhabited : βˆƒ g : G, g ∈ H) (mulInvStable : βˆ€ {g}, g ∈ H β†’ βˆ€ {g'}, g' ∈ H β†’ g * g'⁻¹ ∈ H) : Subgroup G law H where oneMem := lemma₁ law inhabited mulInvStable mulMem := lemma₃ law inhabited mulInvStable invMem := lemmaβ‚‚ law inhabited mulInvStable variable (H : Set G) [sg : Subgroup G law H] instance opIsSubgroup : Subgroup G (lawα΅’α΅–) H where oneMem := sg.oneMem mulMem := Ξ» {g} hg {g'} hg' => sg.mulMem hg' hg invMem := sg.invMem end Subgroup end Group
5f46413c6d91317c694f3679ddc1b82d1f56969d
6b5bcacd7d748a6e81562eac1e2e89819ea3b1d8
/src/compiler.lean
d07b86a10e9d21961ccf663b2ff18b37aba51953
[]
no_license
hermetique/compiler.lean
7a481e289ee8315ecd3bcfd7d97ba817135b9692
bdb80356d668d7a8a31e477ab7fd2d6d648af4f4
refs/heads/main
1,674,374,677,132
1,606,671,179,000
1,606,671,179,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,344
lean
import tactic namespace compiler /- expressions are values and add-expressions -/ inductive Expr | Val : β„• -> Expr | Add : Expr -> Expr -> Expr open Expr /-- evaluate an expression directly -/ @[simp] def eval : Expr -> β„• | (Val n) := n | (Add a b) := eval a + eval b /- we'll compile our expressions to instructions of a stack machine which supports push and add operations -/ inductive Instr | PUSH : β„• -> Instr | ADD : Instr open Instr /-- compile an expression to an instruction list -/ @[simp] def compile : Expr -> list Instr | (Val n) := [PUSH n] | (Add a b) := compile a ++ compile b ++ [ADD] /-- execute a list of instructions on a stack -/ @[simp] def exec : list Instr -> list β„• -> list β„• | ((PUSH n) :: rest) s := exec rest (n :: s) | (ADD :: rest) (a :: b :: s) := exec rest ((a + b) :: s) | _ s := s /-- compiled expressions only add to the stack when `exec`d -/ @[simp] lemma exec_compile_concat (e : Expr) : βˆ€ instrs stack, exec (compile e ++ instrs) stack = exec instrs (eval e :: stack) := begin induction e with n a b iha ihb, case Val { intros, simp, }, case Add { intros, simp [iha, ihb, add_comm], } end /-- exec (compile e) = eval e -/ theorem exec_compile_eq_eval (e : Expr) : exec (compile e) [] = [eval e] := by simpa using exec_compile_concat e [] [] end compiler
a143529973cf27221e3239074540119e0b538bae
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/bicategory/free.lean
6b78babfdbf1cfbeb1616c1fb499a6ada23c0307
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
13,055
lean
/- Copyright (c) 2022 Yuma Mizuno. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yuma Mizuno -/ import category_theory.bicategory.functor /-! # Free bicategories We define the free bicategory over a quiver. In this bicategory, the 1-morphisms are freely generated by the arrows in the quiver, and the 2-morphisms are freely generated by the formal identities, the formal unitors, and the formal associators modulo the relation derived from the axioms of a bicategory. ## Main definitions * `free_bicategory B`: the free bicategory over a quiver `B`. * `free_bicategory.lift F`: the pseudofunctor from `free_bicategory B` to `C` associated with a prefunctor `F` from `B` to `C`. -/ universes w w₁ wβ‚‚ v v₁ vβ‚‚ u u₁ uβ‚‚ namespace category_theory open category bicategory open_locale bicategory /-- Free bicategory over a quiver. Its objects are the same as those in the underlying quiver. -/ def free_bicategory (B : Type u) := B instance (B : Type u) : Ξ  [inhabited B], inhabited (free_bicategory B) := id namespace free_bicategory section variables {B : Type u} [quiver.{v+1} B] /-- 1-morphisms in the free bicategory. -/ inductive hom : B β†’ B β†’ Type (max u v) | of {a b : B} (f : a ⟢ b) : hom a b | id (a : B) : hom a a | comp {a b c : B} (f : hom a b) (g : hom b c) : hom a c instance (a b : B) [inhabited (a ⟢ b)] : inhabited (hom a b) := ⟨hom.of default⟩ /-- Representatives of 2-morphisms in the free bicategory. -/ @[nolint has_inhabited_instance] inductive homβ‚‚ : Ξ  {a b : B}, hom a b β†’ hom a b β†’ Type (max u v) | id {a b} (f : hom a b) : homβ‚‚ f f | vcomp {a b} {f g h : hom a b} (Ξ· : homβ‚‚ f g) (ΞΈ : homβ‚‚ g h) : homβ‚‚ f h | whisker_left {a b c} (f : hom a b) {g h : hom b c} (Ξ· : homβ‚‚ g h) : homβ‚‚ (f.comp g) (f.comp h) -- `Ξ·` cannot be earlier than `h` since it is a recursive argument. | whisker_right {a b c} {f g : hom a b} (h : hom b c) (Ξ· : homβ‚‚ f g) : homβ‚‚ (f.comp h) (g.comp h) | associator {a b c d} (f : hom a b) (g : hom b c) (h : hom c d) : homβ‚‚ ((f.comp g).comp h) (f.comp (g.comp h)) | associator_inv {a b c d} (f : hom a b) (g : hom b c) (h : hom c d) : homβ‚‚ (f.comp (g.comp h)) ((f.comp g).comp h) | right_unitor {a b} (f : hom a b) : homβ‚‚ (f.comp (hom.id b)) f | right_unitor_inv {a b} (f : hom a b) : homβ‚‚ f (f.comp (hom.id b)) | left_unitor {a b} (f : hom a b) : homβ‚‚ ((hom.id a).comp f) f | left_unitor_inv {a b} (f : hom a b) : homβ‚‚ f ((hom.id a).comp f) section variables {B} -- The following notations are only used in the definition of `rel` to simplify the notation. local infixr ` ≫ ` := homβ‚‚.vcomp local notation `πŸ™` := homβ‚‚.id local notation f ` ◁ ` Ξ· := homβ‚‚.whisker_left f Ξ· local notation Ξ· ` β–· ` h := homβ‚‚.whisker_right h Ξ· local notation `Ξ±_` := homβ‚‚.associator local notation `Ξ»_` := homβ‚‚.left_unitor local notation `ρ_` := homβ‚‚.right_unitor local notation `α⁻¹_` := homβ‚‚.associator_inv local notation `λ⁻¹_` := homβ‚‚.left_unitor_inv local notation `ρ⁻¹_` := homβ‚‚.right_unitor_inv /-- Relations between 2-morphisms in the free bicategory. -/ inductive rel : Ξ  {a b : B} {f g : hom a b}, homβ‚‚ f g β†’ homβ‚‚ f g β†’ Prop | vcomp_right {a b} {f g h : hom a b} (Ξ· : homβ‚‚ f g) (θ₁ ΞΈβ‚‚ : homβ‚‚ g h) : rel θ₁ ΞΈβ‚‚ β†’ rel (Ξ· ≫ θ₁) (Ξ· ≫ ΞΈβ‚‚) | vcomp_left {a b} {f g h : hom a b} (η₁ Ξ·β‚‚ : homβ‚‚ f g) (ΞΈ : homβ‚‚ g h) : rel η₁ Ξ·β‚‚ β†’ rel (η₁ ≫ ΞΈ) (Ξ·β‚‚ ≫ ΞΈ) | id_comp {a b} {f g : hom a b} (Ξ· : homβ‚‚ f g) : rel (πŸ™ f ≫ Ξ·) Ξ· | comp_id {a b} {f g : hom a b} (Ξ· : homβ‚‚ f g) : rel (Ξ· ≫ πŸ™ g) Ξ· | assoc {a b} {f g h i : hom a b} (Ξ· : homβ‚‚ f g) (ΞΈ : homβ‚‚ g h) (ΞΉ : homβ‚‚ h i) : rel ((Ξ· ≫ ΞΈ) ≫ ΞΉ) (Ξ· ≫ (ΞΈ ≫ ΞΉ)) | whisker_left {a b c} (f : hom a b) (g h : hom b c) (Ξ· Ξ·' : homβ‚‚ g h) : rel Ξ· Ξ·' β†’ rel (f ◁ Ξ·) (f ◁ Ξ·') | whisker_left_id {a b c} (f : hom a b) (g : hom b c) : rel (f ◁ πŸ™ g) (πŸ™ (f.comp g)) | whisker_left_comp {a b c} (f : hom a b) {g h i : hom b c} (Ξ· : homβ‚‚ g h) (ΞΈ : homβ‚‚ h i) : rel (f ◁ (Ξ· ≫ ΞΈ)) (f ◁ Ξ· ≫ f ◁ ΞΈ) | id_whisker_left {a b} {f g : hom a b} (Ξ· : homβ‚‚ f g) : rel (hom.id a ◁ Ξ·) (Ξ»_ f ≫ Ξ· ≫ λ⁻¹_ g) | comp_whisker_left {a b c d} (f : hom a b) (g : hom b c) {h h' : hom c d} (Ξ· : homβ‚‚ h h') : rel ((f.comp g) ◁ Ξ·) (Ξ±_ f g h ≫ f ◁ g ◁ Ξ· ≫ α⁻¹_ f g h') | whisker_right {a b c} (f g : hom a b) (h : hom b c) (Ξ· Ξ·' : homβ‚‚ f g) : rel Ξ· Ξ·' β†’ rel (Ξ· β–· h) (Ξ·' β–· h) | id_whisker_right {a b c} (f : hom a b) (g : hom b c) : rel (πŸ™ f β–· g) (πŸ™ (f.comp g)) | comp_whisker_right {a b c} {f g h : hom a b} (i : hom b c) (Ξ· : homβ‚‚ f g) (ΞΈ : homβ‚‚ g h) : rel ((Ξ· ≫ ΞΈ) β–· i) (Ξ· β–· i ≫ ΞΈ β–· i) | whisker_right_id {a b} {f g : hom a b} (Ξ· : homβ‚‚ f g) : rel (Ξ· β–· hom.id b) (ρ_ f ≫ Ξ· ≫ ρ⁻¹_ g) | whisker_right_comp {a b c d} {f f' : hom a b} (g : hom b c) (h : hom c d) (Ξ· : homβ‚‚ f f') : rel (Ξ· β–· (g.comp h)) (α⁻¹_ f g h ≫ Ξ· β–· g β–· h ≫ Ξ±_ f' g h) | whisker_assoc {a b c d} (f : hom a b) {g g' : hom b c} (Ξ· : homβ‚‚ g g') (h : hom c d) : rel ((f ◁ Ξ·) β–· h) (Ξ±_ f g h ≫ f ◁ (Ξ· β–· h)≫ α⁻¹_ f g' h) | whisker_exchange {a b c} {f g : hom a b} {h i : hom b c} (Ξ· : homβ‚‚ f g) (ΞΈ : homβ‚‚ h i) : rel (f ◁ ΞΈ ≫ Ξ· β–· i) (Ξ· β–· h ≫ g ◁ ΞΈ) | associator_hom_inv {a b c d} (f : hom a b) (g : hom b c) (h : hom c d) : rel (Ξ±_ f g h ≫ α⁻¹_ f g h) (πŸ™ ((f.comp g).comp h)) | associator_inv_hom {a b c d} (f : hom a b) (g : hom b c) (h : hom c d) : rel (α⁻¹_ f g h ≫ Ξ±_ f g h) (πŸ™ (f.comp (g.comp h))) | left_unitor_hom_inv {a b} (f : hom a b) : rel (Ξ»_ f ≫ λ⁻¹_ f) (πŸ™ ((hom.id a).comp f)) | left_unitor_inv_hom {a b} (f : hom a b) : rel (λ⁻¹_ f ≫ Ξ»_ f) (πŸ™ f) | right_unitor_hom_inv {a b} (f : hom a b) : rel (ρ_ f ≫ ρ⁻¹_ f) (πŸ™ (f.comp (hom.id b))) | right_unitor_inv_hom {a b} (f : hom a b) : rel (ρ⁻¹_ f ≫ ρ_ f) (πŸ™ f) | pentagon {a b c d e} (f : hom a b) (g : hom b c) (h : hom c d) (i : hom d e) : rel (Ξ±_ f g h β–· i ≫ Ξ±_ f (g.comp h) i ≫ f ◁ Ξ±_ g h i) (Ξ±_ (f.comp g) h i ≫ Ξ±_ f g (h.comp i)) | triangle {a b c} (f : hom a b) (g : hom b c) : rel (Ξ±_ f (hom.id b) g ≫ f ◁ Ξ»_ g) (ρ_ f β–· g) end variables {B} instance hom_category (a b : B) : category (hom a b) := { hom := Ξ» f g, quot (@rel _ _ _ _ f g), id := Ξ» f, quot.mk rel (homβ‚‚.id f), comp := Ξ» f g h, quot.mapβ‚‚ homβ‚‚.vcomp rel.vcomp_right rel.vcomp_left, id_comp' := by { rintros f g ⟨η⟩, exact quot.sound (rel.id_comp Ξ·) }, comp_id' := by { rintros f g ⟨η⟩, exact quot.sound (rel.comp_id Ξ·) }, assoc' := by { rintros f g h i ⟨η⟩ ⟨θ⟩ ⟨ι⟩, exact quot.sound (rel.assoc Ξ· ΞΈ ΞΉ) } } /-- Bicategory structure on the free bicategory. -/ instance bicategory : bicategory (free_bicategory B) := { hom := Ξ» a b : B, hom a b, id := hom.id, comp := Ξ» a b c, hom.comp, hom_category := free_bicategory.hom_category, whisker_left := Ξ» a b c f g h Ξ·, quot.map (homβ‚‚.whisker_left f) (rel.whisker_left f g h) Ξ·, whisker_left_id' := Ξ» a b c f g, quot.sound (rel.whisker_left_id f g), whisker_left_comp' := by { rintros a b c f g h i ⟨η⟩ ⟨θ⟩, exact quot.sound (rel.whisker_left_comp f Ξ· ΞΈ) }, id_whisker_left' := by { rintros a b f g ⟨η⟩, exact quot.sound (rel.id_whisker_left Ξ·) }, comp_whisker_left' := by { rintros a b c d f g h h' ⟨η⟩, exact quot.sound (rel.comp_whisker_left f g Ξ·) }, whisker_right := Ξ» a b c f g Ξ· h, quot.map (homβ‚‚.whisker_right h) (rel.whisker_right f g h) Ξ·, id_whisker_right' := Ξ» a b c f g, quot.sound (rel.id_whisker_right f g), comp_whisker_right' := by { rintros a b c f g h ⟨η⟩ ⟨θ⟩ i, exact quot.sound (rel.comp_whisker_right i Ξ· ΞΈ) }, whisker_right_id' := by { rintros a b f g ⟨η⟩, exact quot.sound (rel.whisker_right_id Ξ·) }, whisker_right_comp' := by { rintros a b c d f f' ⟨η⟩ g h, exact quot.sound (rel.whisker_right_comp g h Ξ·) }, whisker_assoc' := by { rintros a b c d f g g' ⟨η⟩ h, exact quot.sound (rel.whisker_assoc f Ξ· h) }, whisker_exchange' := by { rintros a b c f g h i ⟨η⟩ ⟨θ⟩, exact quot.sound (rel.whisker_exchange Ξ· ΞΈ) }, associator := Ξ» a b c d f g h, { hom := quot.mk rel (homβ‚‚.associator f g h), inv := quot.mk rel (homβ‚‚.associator_inv f g h), hom_inv_id' := quot.sound (rel.associator_hom_inv f g h), inv_hom_id' := quot.sound (rel.associator_inv_hom f g h) }, left_unitor := Ξ» a b f, { hom := quot.mk rel (homβ‚‚.left_unitor f), inv := quot.mk rel (homβ‚‚.left_unitor_inv f), hom_inv_id' := quot.sound (rel.left_unitor_hom_inv f), inv_hom_id' := quot.sound (rel.left_unitor_inv_hom f) }, right_unitor := Ξ» a b f, { hom := quot.mk rel (homβ‚‚.right_unitor f), inv := quot.mk rel (homβ‚‚.right_unitor_inv f), hom_inv_id' := quot.sound (rel.right_unitor_hom_inv f), inv_hom_id' := quot.sound (rel.right_unitor_inv_hom f) }, pentagon' := Ξ» a b c d e f g h i, quot.sound (rel.pentagon f g h i), triangle' := Ξ» a b c f g, quot.sound (rel.triangle f g) } variables {a b c d : free_bicategory B} @[simp] lemma mk_vcomp {f g h : a ⟢ b} (Ξ· : homβ‚‚ f g) (ΞΈ : homβ‚‚ g h) : quot.mk rel (Ξ·.vcomp ΞΈ) = (quot.mk rel Ξ· ≫ quot.mk rel ΞΈ : f ⟢ h) := rfl @[simp] lemma mk_whisker_left (f : a ⟢ b) {g h : b ⟢ c} (Ξ· : homβ‚‚ g h) : quot.mk rel (homβ‚‚.whisker_left f Ξ·) = (f ◁ quot.mk rel Ξ· : f ≫ g ⟢ f ≫ h) := rfl @[simp] lemma mk_whisker_right {f g : a ⟢ b} (Ξ· : homβ‚‚ f g) (h : b ⟢ c) : quot.mk rel (homβ‚‚.whisker_right h Ξ·) = (quot.mk rel Ξ· β–· h : f ≫ h ⟢ g ≫ h) := rfl variables (f : a ⟢ b) (g : b ⟢ c) (h : c ⟢ d) lemma id_def : hom.id a = πŸ™ a := rfl lemma comp_def : hom.comp f g = f ≫ g := rfl @[simp] lemma mk_id : quot.mk _ (homβ‚‚.id f) = πŸ™ f := rfl @[simp] lemma mk_associator_hom : quot.mk _ (homβ‚‚.associator f g h) = (Ξ±_ f g h).hom := rfl @[simp] lemma mk_associator_inv : quot.mk _ (homβ‚‚.associator_inv f g h) = (Ξ±_ f g h).inv := rfl @[simp] lemma mk_left_unitor_hom : quot.mk _ (homβ‚‚.left_unitor f) = (Ξ»_ f).hom := rfl @[simp] lemma mk_left_unitor_inv : quot.mk _ (homβ‚‚.left_unitor_inv f) = (Ξ»_ f).inv := rfl @[simp] lemma mk_right_unitor_hom : quot.mk _ (homβ‚‚.right_unitor f) = (ρ_ f).hom := rfl @[simp] lemma mk_right_unitor_inv : quot.mk _ (homβ‚‚.right_unitor_inv f) = (ρ_ f).inv := rfl /-- Canonical prefunctor from `B` to `free_bicategory B`. -/ @[simps] def of : prefunctor B (free_bicategory B) := { obj := id, map := Ξ» a b, hom.of } end section variables {B : Type u₁} [quiver.{v₁+1} B] {C : Type uβ‚‚} [category_struct.{vβ‚‚} C] variables (F : prefunctor B C) /-- Auxiliary definition for `lift`. -/ @[simp] def lift_hom : βˆ€ {a b : B}, hom a b β†’ (F.obj a ⟢ F.obj b) | _ _ (hom.of f) := F.map f | _ _ (hom.id a) := πŸ™ (F.obj a) | _ _ (hom.comp f g) := lift_hom f ≫ lift_hom g @[simp] lemma lift_hom_id (a : free_bicategory B) : lift_hom F (πŸ™ a) = πŸ™ (F.obj a) := rfl @[simp] lemma lift_hom_comp {a b c : free_bicategory B} (f : a ⟢ b) (g : b ⟢ c) : lift_hom F (f ≫ g) = lift_hom F f ≫ lift_hom F g := rfl end section variables {B : Type u₁} [quiver.{v₁+1} B] {C : Type uβ‚‚} [bicategory.{wβ‚‚ vβ‚‚} C] variables (F : prefunctor B C) /-- Auxiliary definition for `lift`. -/ @[simp] def lift_homβ‚‚ : βˆ€ {a b : B} {f g : hom a b}, homβ‚‚ f g β†’ (lift_hom F f ⟢ lift_hom F g) | _ _ _ _ (homβ‚‚.id _) := πŸ™ _ | _ _ _ _ (homβ‚‚.associator _ _ _) := (Ξ±_ _ _ _).hom | _ _ _ _ (homβ‚‚.associator_inv _ _ _) := (Ξ±_ _ _ _).inv | _ _ _ _ (homβ‚‚.left_unitor _) := (Ξ»_ _).hom | _ _ _ _ (homβ‚‚.left_unitor_inv _) := (Ξ»_ _).inv | _ _ _ _ (homβ‚‚.right_unitor _) := (ρ_ _).hom | _ _ _ _ (homβ‚‚.right_unitor_inv _) := (ρ_ _).inv | _ _ _ _ (homβ‚‚.vcomp Ξ· ΞΈ) := lift_homβ‚‚ Ξ· ≫ lift_homβ‚‚ ΞΈ | _ _ _ _ (homβ‚‚.whisker_left f Ξ·) := lift_hom F f ◁ lift_homβ‚‚ Ξ· | _ _ _ _ (homβ‚‚.whisker_right h Ξ·) := lift_homβ‚‚ Ξ· β–· lift_hom F h local attribute [simp] whisker_exchange lemma lift_homβ‚‚_congr {a b : B} {f g : hom a b} {Ξ· ΞΈ : homβ‚‚ f g} (H : rel Ξ· ΞΈ) : lift_homβ‚‚ F Ξ· = lift_homβ‚‚ F ΞΈ := by induction H; tidy /-- A prefunctor from a quiver `B` to a bicategory `C` can be lifted to a pseudofunctor from `free_bicategory B` to `C`. -/ @[simps] def lift : pseudofunctor (free_bicategory B) C := { obj := F.obj, map := Ξ» a b, lift_hom F, mapβ‚‚ := Ξ» a b f g, quot.lift (lift_homβ‚‚ F) (Ξ» Ξ· ΞΈ H, lift_homβ‚‚_congr F H), map_id := Ξ» a, iso.refl _, map_comp := Ξ» a b c f g, iso.refl _ } end end free_bicategory end category_theory
5ccc99067fed0721d83638c044bacfbc6f0a4443
39ef80a23ca45a679ce3047fabd002248e3ee410
/src/real-analysis/09_limits_final.lean
8936bce5f605f610a3519cce7e400a450a1e67ae
[ "MIT" ]
permissive
sanjitdp/lean-projects
5baa4d97f38b0d5af41e4960dc69ecc7c65a1e4c
05b9a58e8bda3baebd4269536db39815a73cb123
refs/heads/main
1,690,059,014,811
1,630,696,075,000
1,630,696,075,000
399,831,128
0
1
null
null
null
null
UTF-8
Lean
false
false
7,196
lean
import tuto_lib set_option pp.beta true set_option pp.coercions false /- This is the final file in the series. Here we use everything covered in previous files to prove a couple of famous theorems from elementary real analysis. Of course they all have more general versions in mathlib. As usual, keep in mind the following: abs_le (x y : ℝ) : |x| ≀ y ↔ -y ≀ x ∧ x ≀ y ge_max_iff (p q r) : r β‰₯ max p q ↔ r β‰₯ p ∧ r β‰₯ q le_max_left p q : p ≀ max p q le_max_right p q : q ≀ max p q as well as a lemma from the previous file: le_of_le_add_all : (βˆ€ Ξ΅ > 0, y ≀ x + Ξ΅) β†’ y ≀ x Let's start with a variation on a known exercise. -/ -- 0071 lemma le_lim {x y : ℝ} {u : β„• β†’ ℝ} (hu : seq_limit u x) (ineg : βˆƒ N, βˆ€ n β‰₯ N, y ≀ u n) : y ≀ x := begin sorry end /- Let's now return to the result proved in the `00_` file of this series, and prove again the sequential characterization of upper bounds (with a slighly different proof). For this, and other exercises below, we'll need many things that we proved in previous files, and a couple of extras. From the 5th file: limit_const (x : ℝ) : seq_limit (Ξ» n, x) x squeeze (lim_u : seq_limit u l) (lim_w : seq_limit w l) (hu : βˆ€ n, u n ≀ v n) (hw : βˆ€ n, v n ≀ w n) : seq_limit v l From the 8th: def upper_bound (A : set ℝ) (x : ℝ) := βˆ€ a ∈ A, a ≀ x def is_sup (A : set ℝ) (x : ℝ) := upper_bound A x ∧ βˆ€ y, upper_bound A y β†’ x ≀ y lt_sup (hx : is_sup A x) : βˆ€ y, y < x β†’ βˆƒ a ∈ A, y < a := You can also use: nat.one_div_pos_of_nat {n : β„•} : 0 < 1 / (n + 1 : ℝ) inv_succ_le_all : βˆ€ Ξ΅ > 0, βˆƒ N : β„•, βˆ€ n β‰₯ N, 1/(n + 1 : ℝ) ≀ Ξ΅ and their easy consequences: limit_of_sub_le_inv_succ (h : βˆ€ n, |u n - x| ≀ 1/(n+1)) : seq_limit u x limit_const_add_inv_succ (x : ℝ) : seq_limit (Ξ» n, x + 1/(n+1)) x limit_const_sub_inv_succ (x : ℝ) : seq_limit (Ξ» n, x - 1/(n+1)) x The structure of the proof is offered. It features a new tactic: `choose` which invokes the axiom of choice (observing the tactic state before and after using it should be enough to understand everything). -/ -- 0072 lemma is_sup_iff (A : set ℝ) (x : ℝ) : (is_sup A x) ↔ (upper_bound A x ∧ βˆƒ u : β„• β†’ ℝ, seq_limit u x ∧ βˆ€ n, u n ∈ A ) := begin split, { intro h, split, { sorry }, { have : βˆ€ n : β„•, βˆƒ a ∈ A, x - 1/(n+1) < a, { intros n, have : 1/(n+1 : ℝ) > 0, exact nat.one_div_pos_of_nat, sorry }, choose u hu using this, sorry } }, { rintro ⟨maj, u, limu, u_in⟩, sorry }, end /-- Continuity of a function at a point -/ def continuous_at_pt (f : ℝ β†’ ℝ) (xβ‚€ : ℝ) : Prop := βˆ€ Ξ΅ > 0, βˆƒ Ξ΄ > 0, βˆ€ x, |x - xβ‚€| ≀ Ξ΄ β†’ |f x - f xβ‚€| ≀ Ξ΅ variables {f : ℝ β†’ ℝ} {xβ‚€ : ℝ} {u : β„• β†’ ℝ} -- 0073 lemma seq_continuous_of_continuous (hf : continuous_at_pt f xβ‚€) (hu : seq_limit u xβ‚€) : seq_limit (f ∘ u) (f xβ‚€) := begin sorry end -- 0074 example : (βˆ€ u : β„• β†’ ℝ, seq_limit u xβ‚€ β†’ seq_limit (f ∘ u) (f xβ‚€)) β†’ continuous_at_pt f xβ‚€ := begin sorry end /- Recall from the 6th file: def extraction (Ο† : β„• β†’ β„•) := βˆ€ n m, n < m β†’ Ο† n < Ο† m def cluster_point (u : β„• β†’ ℝ) (a : ℝ) := βˆƒ Ο†, extraction Ο† ∧ seq_limit (u ∘ Ο†) a id_le_extraction : extraction Ο† β†’ βˆ€ n, n ≀ Ο† n and from the 8th file: def tendsto_infinity (u : β„• β†’ ℝ) := βˆ€ A, βˆƒ N, βˆ€ n β‰₯ N, u n β‰₯ A not_seq_limit_of_tendstoinfinity : tendsto_infinity u β†’ βˆ€ l, Β¬ seq_limit u l -/ variables {Ο† : β„• β†’ β„•} -- 0075 lemma subseq_tendstoinfinity (h : tendsto_infinity u) (hΟ† : extraction Ο†) : tendsto_infinity (u ∘ Ο†) := begin sorry end -- 0076 lemma squeeze_infinity {u v : β„• β†’ ℝ} (hu : tendsto_infinity u) (huv : βˆ€ n, u n ≀ v n) : tendsto_infinity v := begin sorry end /- We will use segments: Icc a b := { x | a ≀ x ∧ x ≀ b } The notation stands for Interval-closed-closed. Variations exist with o or i instead of c, where o stands for open and i for infinity. We will use the following version of Bolzano-Weierstrass bolzano_weierstrass (h : βˆ€ n, u n ∈ [a, b]) : βˆƒ c ∈ [a, b], cluster_point u c as well as the obvious seq_limit_id : tendsto_infinity (Ξ» n, n) -/ open set -- 0077 lemma bdd_above_segment {f : ℝ β†’ ℝ} {a b : ℝ} (hf : βˆ€ x ∈ Icc a b, continuous_at_pt f x) : βˆƒ M, βˆ€ x ∈ Icc a b, f x ≀ M := begin sorry end /- In the next exercise, we can use: abs_neg x : |-x| = |x| -/ -- 0078 lemma continuous_opposite {f : ℝ β†’ ℝ} {xβ‚€ : ℝ} (h : continuous_at_pt f xβ‚€) : continuous_at_pt (Ξ» x, -f x) xβ‚€ := begin sorry end /- Now let's combine the two exercises above -/ -- 0079 lemma bdd_below_segment {f : ℝ β†’ ℝ} {a b : ℝ} (hf : βˆ€ x ∈ Icc a b, continuous_at_pt f x) : βˆƒ m, βˆ€ x ∈ Icc a b, m ≀ f x := begin sorry end /- Remember from the 5th file: unique_limit : seq_limit u l β†’ seq_limit u l' β†’ l = l' and from the 6th one: subseq_tendsto_of_tendsto (h : seq_limit u l) (hΟ† : extraction Ο†) : seq_limit (u ∘ Ο†) l We now admit the following version of the least upper bound theorem (that cannot be proved without discussing the construction of real numbers or admitting another strong theorem). sup_segment {a b : ℝ} {A : set ℝ} (hnonvide : βˆƒ x, x ∈ A) (h : A βŠ† Icc a b) : βˆƒ x ∈ Icc a b, is_sup A x In the next exercise, it can be useful to prove inclusions of sets of real number. By definition, A βŠ† B means : βˆ€ x, x ∈ A β†’ x ∈ B. Hence one can start a proof of A βŠ† B by `intros x x_in`, which brings `x : ℝ` and `x_in : x ∈ A` in the local context, and then prove `x ∈ B`. Note also the use of {x | P x} which denotes the set of x satisfying predicate P. Hence `x' ∈ { x | P x} ↔ P x'`, by definition. -/ -- 0080 example {a b : ℝ} (hab : a ≀ b) (hf : βˆ€ x ∈ Icc a b, continuous_at_pt f x) : βˆƒ xβ‚€ ∈ Icc a b, βˆ€ x ∈ Icc a b, f x ≀ f xβ‚€ := begin sorry end lemma stupid {a b x : ℝ} (h : x ∈ Icc a b) (h' : x β‰  b) : x < b := lt_of_le_of_ne h.right h' /- And now the final boss... -/ def I := (Icc 0 1 : set ℝ) -- the type ascription makes sure 0 and 1 are real numbers here -- 0081 example (f : ℝ β†’ ℝ) (hf : βˆ€ x, continuous_at_pt f x) (hβ‚€ : f 0 < 0) (h₁ : f 1 > 0) : βˆƒ xβ‚€ ∈ I, f xβ‚€ = 0 := begin let A := { x | x ∈ I ∧ f x < 0}, have ex_xβ‚€ : βˆƒ xβ‚€ ∈ I, is_sup A xβ‚€, { sorry }, rcases ex_xβ‚€ with ⟨xβ‚€, xβ‚€_in, xβ‚€_sup⟩, use [xβ‚€, xβ‚€_in], have : f xβ‚€ ≀ 0, { sorry }, have xβ‚€_1: xβ‚€ < 1, { sorry }, have : f xβ‚€ β‰₯ 0, { have in_I : βˆƒ N : β„•, βˆ€ n β‰₯ N, xβ‚€ + 1/(n+1) ∈ I, { have : βˆƒ N : β„•, βˆ€ nβ‰₯ N, 1/(n+1 : ℝ) ≀ 1-xβ‚€, { sorry }, sorry }, have not_in : βˆ€ n : β„•, xβ‚€ + 1/(n+1) βˆ‰ A, -- By definition, x βˆ‰ A means Β¬ (x ∈ A). { sorry }, dsimp [A] at not_in, sorry }, linarith, end
03737caffc772f5212a7cc50353074a0e1f05dc9
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/analysis/calculus/darboux.lean
6a63b6fe8e464df0358fa898ab2feaa9955bcd80
[ "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
4,668
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.mean_value /-! # Darboux's theorem In this file we prove that the derivative of a differentiable function on an interval takes all intermediate values. The proof is based on the [Wikipedia](https://en.wikipedia.org/wiki/Darboux%27s_theorem_(analysis)) page about this theorem. -/ open filter set open_locale topological_space classical variables {a b : ℝ} {f f' : ℝ β†’ ℝ} /-- Darboux's theorem: if `a ≀ b` and `f' a < m < f' b`, then `f' c = m` for some `c ∈ [a, b]`. -/ theorem exists_has_deriv_within_at_eq_of_gt_of_lt (hab : a ≀ b) (hf : βˆ€ x ∈ (Icc a b), has_deriv_within_at f (f' x) (Icc a b) x) {m : ℝ} (hma : f' a < m) (hmb : m < f' b) : m ∈ f' '' (Icc a b) := begin have hab' : a < b, { refine lt_of_le_of_ne hab (Ξ» hab', _), subst b, exact lt_asymm hma hmb }, set g : ℝ β†’ ℝ := Ξ» x, f x - m * x, have hg : βˆ€ x ∈ Icc a b, has_deriv_within_at g (f' x - m) (Icc a b) x, { intros x hx, simpa using (hf x hx).sub ((has_deriv_within_at_id x _).const_mul m) }, obtain ⟨c, cmem, hc⟩ : βˆƒ c ∈ Icc a b, is_min_on g (Icc a b) c, from compact_Icc.exists_forall_le (nonempty_Icc.2 $ hab) (Ξ» x hx, (hg x hx).continuous_within_at), have cmem' : c ∈ Ioo a b, { cases eq_or_lt_of_le cmem.1 with hac hac, -- Show that `c` can't be equal to `a` { subst c, refine absurd (sub_nonneg.1 $ nonneg_of_mul_nonneg_left _ (sub_pos.2 hab')) (not_le_of_lt hma), have : b - a ∈ pos_tangent_cone_at (Icc a b) a, from mem_pos_tangent_cone_at_of_segment_subset (segment_eq_Icc hab β–Έ subset.refl _), simpa using hc.localize.has_fderiv_within_at_nonneg (hg a (left_mem_Icc.2 hab)) this }, cases eq_or_lt_of_le cmem.2 with hbc hbc, -- Show that `c` can't be equal to `a` { subst c, refine absurd (sub_nonpos.1 $ nonpos_of_mul_nonneg_right _ (sub_lt_zero.2 hab')) (not_le_of_lt hmb), have : a - b ∈ pos_tangent_cone_at (Icc a b) b, from mem_pos_tangent_cone_at_of_segment_subset (by rw [segment_symm, segment_eq_Icc hab]), simpa using hc.localize.has_fderiv_within_at_nonneg (hg b (right_mem_Icc.2 hab)) this }, exact ⟨hac, hbc⟩ }, use [c, cmem], rw [← sub_eq_zero], have : Icc a b ∈ 𝓝 c, by rwa [← mem_interior_iff_mem_nhds, interior_Icc], exact (hc.is_local_min this).has_deriv_at_eq_zero ((hg c cmem).has_deriv_at this) end /-- Darboux's theorem: if `a ≀ b` and `f' a > m > f' b`, then `f' c = m` for some `c ∈ [a, b]`. -/ theorem exists_has_deriv_within_at_eq_of_lt_of_gt (hab : a ≀ b) (hf : βˆ€ x ∈ (Icc a b), has_deriv_within_at f (f' x) (Icc a b) x) {m : ℝ} (hma : m < f' a) (hmb : f' b < m) : m ∈ f' '' (Icc a b) := let ⟨c, cmem, hc⟩ := exists_has_deriv_within_at_eq_of_gt_of_lt hab (Ξ» x hx, (hf x hx).neg) (neg_lt_neg hma) (neg_lt_neg hmb) in ⟨c, cmem, neg_inj hc⟩ /-- Darboux's theorem: the image of a convex set under `f'` is a convex set. -/ theorem convex_image_has_deriv_at {s : set ℝ} (hs : convex s) (hf : βˆ€ x ∈ s, has_deriv_at f (f' x) x) : convex (f' '' s) := begin refine convex_real_iff.2 _, rintros _ _ ⟨a, ha, rfl⟩ ⟨b, hb, rfl⟩ m ⟨hma, hmb⟩, cases eq_or_lt_of_le hma with hma hma, by exact hma β–Έ mem_image_of_mem f' ha, cases eq_or_lt_of_le hmb with hmb hmb, by exact hmb.symm β–Έ mem_image_of_mem f' hb, cases le_total a b with hab hab, { have : Icc a b βŠ† s, from convex_real_iff.1 hs ha hb, rcases exists_has_deriv_within_at_eq_of_gt_of_lt hab (Ξ» x hx, (hf x $ this hx).has_deriv_within_at) hma hmb with ⟨c, cmem, hc⟩, exact ⟨c, this cmem, hc⟩ }, { have : Icc b a βŠ† s, from convex_real_iff.1 hs hb ha, rcases exists_has_deriv_within_at_eq_of_lt_of_gt hab (Ξ» x hx, (hf x $ this hx).has_deriv_within_at) hmb hma with ⟨c, cmem, hc⟩, exact ⟨c, this cmem, hc⟩ } end /-- If the derivative of a function is never equal to `m`, then either it is always greater than `m`, or it is always less than `m`. -/ theorem deriv_forall_lt_or_forall_gt_of_forall_ne {s : set ℝ} (hs : convex s) (hf : βˆ€ x ∈ s, has_deriv_at f (f' x) x) {m : ℝ} (hf' : βˆ€ x ∈ s, f' x β‰  m) : (βˆ€ x ∈ s, f' x < m) ∨ (βˆ€ x ∈ s, m < f' x) := begin contrapose! hf', rcases hf' with ⟨⟨b, hb, hmb⟩, ⟨a, ha, hma⟩⟩, exact convex_real_iff.1 (convex_image_has_deriv_at hs hf) (mem_image_of_mem f' ha) (mem_image_of_mem f' hb) ⟨hma, hmb⟩ end
b2623bfe11b1ca750730c5cc53dbd2c06082c7d2
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/locally_convex/with_seminorms.lean
12bef187ce7d9c200c182424bc68f4f5c631667a
[ "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
19,142
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll, Anatole Dedecker -/ import analysis.seminorm import analysis.locally_convex.bounded /-! # Topology induced by a family of seminorms ## Main definitions * `seminorm_family.basis_sets`: The set of open seminorm balls for a family of seminorms. * `seminorm_family.module_filter_basis`: A module filter basis formed by the open balls. * `seminorm.is_bounded`: A linear map `f : E β†’β‚—[π•œ] F` is bounded iff every seminorm in `F` can be bounded by a finite number of seminorms in `E`. ## Main statements * `continuous_from_bounded`: A bounded linear map `f : E β†’β‚—[π•œ] F` is continuous. * `seminorm_family.to_locally_convex_space`: A space equipped with a family of seminorms is locally convex. ## TODO Show that for any locally convex space there exist seminorms that induce the topology. ## Tags seminorm, locally convex -/ open normed_field set seminorm open_locale big_operators nnreal pointwise topological_space variables {π•œ E F G ΞΉ ΞΉ' : Type*} section filter_basis variables [normed_field π•œ] [add_comm_group E] [module π•œ E] variables (π•œ E ΞΉ) /-- An abbreviation for indexed families of seminorms. This is mainly to allow for dot-notation. -/ abbreviation seminorm_family := ΞΉ β†’ seminorm π•œ E variables {π•œ E ΞΉ} namespace seminorm_family /-- The sets of a filter basis for the neighborhood filter of 0. -/ def basis_sets (p : seminorm_family π•œ E ΞΉ) : set (set E) := ⋃ (s : finset ΞΉ) r (hr : 0 < r), singleton $ ball (s.sup p) (0 : E) r variables (p : seminorm_family π•œ E ΞΉ) lemma basis_sets_iff {U : set E} : U ∈ p.basis_sets ↔ βˆƒ (i : finset ΞΉ) r (hr : 0 < r), U = ball (i.sup p) 0 r := by simp only [basis_sets, mem_Union, mem_singleton_iff] lemma basis_sets_mem (i : finset ΞΉ) {r : ℝ} (hr : 0 < r) : (i.sup p).ball 0 r ∈ p.basis_sets := (basis_sets_iff _).mpr ⟨i,_,hr,rfl⟩ lemma basis_sets_singleton_mem (i : ΞΉ) {r : ℝ} (hr : 0 < r) : (p i).ball 0 r ∈ p.basis_sets := (basis_sets_iff _).mpr ⟨{i},_,hr, by rw finset.sup_singleton⟩ lemma basis_sets_nonempty [nonempty ΞΉ] : p.basis_sets.nonempty := begin let i := classical.arbitrary ΞΉ, refine set.nonempty_def.mpr ⟨(p i).ball 0 1, _⟩, exact p.basis_sets_singleton_mem i zero_lt_one, end lemma basis_sets_intersect (U V : set E) (hU : U ∈ p.basis_sets) (hV : V ∈ p.basis_sets) : βˆƒ (z : set E) (H : z ∈ p.basis_sets), z βŠ† U ∩ V := begin classical, rcases p.basis_sets_iff.mp hU with ⟨s, r₁, hr₁, hU⟩, rcases p.basis_sets_iff.mp hV with ⟨t, rβ‚‚, hrβ‚‚, hV⟩, use ((s βˆͺ t).sup p).ball 0 (min r₁ rβ‚‚), refine ⟨p.basis_sets_mem (s βˆͺ t) (lt_min_iff.mpr ⟨hr₁, hrβ‚‚βŸ©), _⟩, rw [hU, hV, ball_finset_sup_eq_Inter _ _ _ (lt_min_iff.mpr ⟨hr₁, hrβ‚‚βŸ©), ball_finset_sup_eq_Inter _ _ _ hr₁, ball_finset_sup_eq_Inter _ _ _ hrβ‚‚], exact set.subset_inter (set.Interβ‚‚_mono' $ Ξ» i hi, ⟨i, finset.subset_union_left _ _ hi, ball_mono $ min_le_left _ _⟩) (set.Interβ‚‚_mono' $ Ξ» i hi, ⟨i, finset.subset_union_right _ _ hi, ball_mono $ min_le_right _ _⟩), end lemma basis_sets_zero (U) (hU : U ∈ p.basis_sets) : (0 : E) ∈ U := begin rcases p.basis_sets_iff.mp hU with ⟨ι', r, hr, hU⟩, rw [hU, mem_ball_zero, (ΞΉ'.sup p).zero], exact hr, end lemma basis_sets_add (U) (hU : U ∈ p.basis_sets) : βˆƒ (V : set E) (H : V ∈ p.basis_sets), V + V βŠ† U := begin rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, use (s.sup p).ball 0 (r/2), refine ⟨p.basis_sets_mem s (div_pos hr zero_lt_two), _⟩, refine set.subset.trans (ball_add_ball_subset (s.sup p) (r/2) (r/2) 0 0) _, rw [hU, add_zero, add_halves'], end lemma basis_sets_neg (U) (hU' : U ∈ p.basis_sets) : βˆƒ (V : set E) (H : V ∈ p.basis_sets), V βŠ† (Ξ» (x : E), -x) ⁻¹' U := begin rcases p.basis_sets_iff.mp hU' with ⟨s, r, hr, hU⟩, rw [hU, neg_preimage, neg_ball (s.sup p), neg_zero], exact ⟨U, hU', eq.subset hU⟩, end /-- The `add_group_filter_basis` induced by the filter basis `seminorm_basis_zero`. -/ protected def add_group_filter_basis [nonempty ΞΉ] : add_group_filter_basis E := add_group_filter_basis_of_comm p.basis_sets p.basis_sets_nonempty p.basis_sets_intersect p.basis_sets_zero p.basis_sets_add p.basis_sets_neg lemma basis_sets_smul_right (v : E) (U : set E) (hU : U ∈ p.basis_sets) : βˆ€αΆ  (x : π•œ) in 𝓝 0, x β€’ v ∈ U := begin rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, rw [hU, filter.eventually_iff], simp_rw [(s.sup p).mem_ball_zero, (s.sup p).smul], by_cases h : 0 < (s.sup p) v, { simp_rw (lt_div_iff h).symm, rw ←_root_.ball_zero_eq, exact metric.ball_mem_nhds 0 (div_pos hr h) }, simp_rw [le_antisymm (not_lt.mp h) ((s.sup p).nonneg v), mul_zero, hr], exact is_open.mem_nhds is_open_univ (mem_univ 0), end variables [nonempty ΞΉ] lemma basis_sets_smul (U) (hU : U ∈ p.basis_sets) : βˆƒ (V : set π•œ) (H : V ∈ 𝓝 (0 : π•œ)) (W : set E) (H : W ∈ p.add_group_filter_basis.sets), V β€’ W βŠ† U := begin rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, refine ⟨metric.ball 0 r.sqrt, metric.ball_mem_nhds 0 (real.sqrt_pos.mpr hr), _⟩, refine ⟨(s.sup p).ball 0 r.sqrt, p.basis_sets_mem s (real.sqrt_pos.mpr hr), _⟩, refine set.subset.trans (ball_smul_ball (s.sup p) r.sqrt r.sqrt) _, rw [hU, real.mul_self_sqrt (le_of_lt hr)], end lemma basis_sets_smul_left (x : π•œ) (U : set E) (hU : U ∈ p.basis_sets) : βˆƒ (V : set E) (H : V ∈ p.add_group_filter_basis.sets), V βŠ† (Ξ» (y : E), x β€’ y) ⁻¹' U := begin rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, rw hU, by_cases h : x β‰  0, { rw [(s.sup p).smul_ball_preimage 0 r x h, smul_zero], use (s.sup p).ball 0 (r / βˆ₯xβˆ₯), exact ⟨p.basis_sets_mem s (div_pos hr (norm_pos_iff.mpr h)), subset.rfl⟩ }, refine ⟨(s.sup p).ball 0 r, p.basis_sets_mem s hr, _⟩, simp only [not_ne_iff.mp h, subset_def, mem_ball_zero, hr, mem_univ, seminorm.zero, implies_true_iff, preimage_const_of_mem, zero_smul], end /-- The `module_filter_basis` induced by the filter basis `seminorm_basis_zero`. -/ protected def module_filter_basis : module_filter_basis π•œ E := { to_add_group_filter_basis := p.add_group_filter_basis, smul' := p.basis_sets_smul, smul_left' := p.basis_sets_smul_left, smul_right' := p.basis_sets_smul_right } lemma filter_eq_infi (p : seminorm_family π•œ E ΞΉ) : p.module_filter_basis.to_filter_basis.filter = β¨… i, (𝓝 0).comap (p i) := begin refine le_antisymm (le_infi $ Ξ» i, _) _, { rw p.module_filter_basis.to_filter_basis.has_basis.le_basis_iff (metric.nhds_basis_ball.comap _), intros Ξ΅ hΞ΅, refine ⟨(p i).ball 0 Ξ΅, _, _⟩, { rw ← (finset.sup_singleton : _ = p i), exact p.basis_sets_mem {i} hΞ΅, }, { rw [id, (p i).ball_zero_eq_preimage_ball] } }, { rw p.module_filter_basis.to_filter_basis.has_basis.ge_iff, rintros U (hU : U ∈ p.basis_sets), rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, rfl⟩, rw [id, seminorm.ball_finset_sup_eq_Inter _ _ _ hr, s.Inter_mem_sets], exact Ξ» i hi, filter.mem_infi_of_mem i ⟨metric.ball 0 r, metric.ball_mem_nhds 0 hr, eq.subset ((p i).ball_zero_eq_preimage_ball).symm⟩, }, end end seminorm_family end filter_basis section bounded namespace seminorm variables [normed_field π•œ] [add_comm_group E] [module π•œ E] [add_comm_group F] [module π•œ F] -- Todo: This should be phrased entirely in terms of the von Neumann bornology. /-- The proposition that a linear map is bounded between spaces with families of seminorms. -/ def is_bounded (p : ΞΉ β†’ seminorm π•œ E) (q : ΞΉ' β†’ seminorm π•œ F) (f : E β†’β‚—[π•œ] F) : Prop := βˆ€ i, βˆƒ s : finset ΞΉ, βˆƒ C : ℝβ‰₯0, C β‰  0 ∧ (q i).comp f ≀ C β€’ s.sup p lemma is_bounded_const (ΞΉ' : Type*) [nonempty ΞΉ'] {p : ΞΉ β†’ seminorm π•œ E} {q : seminorm π•œ F} (f : E β†’β‚—[π•œ] F) : is_bounded p (Ξ» _ : ΞΉ', q) f ↔ βˆƒ (s : finset ΞΉ) C : ℝβ‰₯0, C β‰  0 ∧ q.comp f ≀ C β€’ s.sup p := by simp only [is_bounded, forall_const] lemma const_is_bounded (ΞΉ : Type*) [nonempty ΞΉ] {p : seminorm π•œ E} {q : ΞΉ' β†’ seminorm π•œ F} (f : E β†’β‚—[π•œ] F) : is_bounded (Ξ» _ : ΞΉ, p) q f ↔ βˆ€ i, βˆƒ C : ℝβ‰₯0, C β‰  0 ∧ (q i).comp f ≀ C β€’ p := begin split; intros h i, { rcases h i with ⟨s, C, hC, h⟩, exact ⟨C, hC, le_trans h (smul_le_smul (finset.sup_le (Ξ» _ _, le_rfl)) le_rfl)⟩ }, use [{classical.arbitrary ΞΉ}], simp only [h, finset.sup_singleton], end lemma is_bounded_sup {p : ΞΉ β†’ seminorm π•œ E} {q : ΞΉ' β†’ seminorm π•œ F} {f : E β†’β‚—[π•œ] F} (hf : is_bounded p q f) (s' : finset ΞΉ') : βˆƒ (C : ℝβ‰₯0) (s : finset ΞΉ), 0 < C ∧ (s'.sup q).comp f ≀ C β€’ (s.sup p) := begin classical, by_cases hs' : Β¬s'.nonempty, { refine ⟨1, βˆ…, zero_lt_one, _⟩, rw [finset.not_nonempty_iff_eq_empty.mp hs', finset.sup_empty, seminorm.bot_eq_zero, zero_comp], exact seminorm.nonneg _ }, rw not_not at hs', choose fβ‚› fC hf using hf, use [s'.card β€’ s'.sup fC, finset.bUnion s' fβ‚›], split, { refine nsmul_pos _ (ne_of_gt (finset.nonempty.card_pos hs')), cases finset.nonempty.bex hs' with j hj, exact lt_of_lt_of_le (zero_lt_iff.mpr (and.elim_left (hf j))) (finset.le_sup hj) }, have hs : βˆ€ i : ΞΉ', i ∈ s' β†’ (q i).comp f ≀ s'.sup fC β€’ ((finset.bUnion s' fβ‚›).sup p) := begin intros i hi, refine le_trans (and.elim_right (hf i)) (smul_le_smul _ (finset.le_sup hi)), exact finset.sup_mono (finset.subset_bUnion_of_mem fβ‚› hi), end, refine le_trans (comp_mono f (finset_sup_le_sum q s')) _, simp_rw [←pullback_apply, add_monoid_hom.map_sum, pullback_apply], refine le_trans (finset.sum_le_sum hs) _, rw [finset.sum_const, smul_assoc], exact le_rfl, end end seminorm end bounded section topology variables [normed_field π•œ] [add_comm_group E] [module π•œ E] [nonempty ΞΉ] /-- The proposition that the topology of `E` is induced by a family of seminorms `p`. -/ class with_seminorms (p : seminorm_family π•œ E ΞΉ) [t : topological_space E] : Prop := (topology_eq_with_seminorms : t = p.module_filter_basis.topology) lemma seminorm_family.with_seminorms_eq (p : seminorm_family π•œ E ΞΉ) [t : topological_space E] [with_seminorms p] : t = p.module_filter_basis.topology := with_seminorms.topology_eq_with_seminorms variables [topological_space E] variables (p : seminorm_family π•œ E ΞΉ) [with_seminorms p] lemma seminorm_family.has_basis : (𝓝 (0 : E)).has_basis (Ξ» (s : set E), s ∈ p.basis_sets) id := begin rw (congr_fun (congr_arg (@nhds E) p.with_seminorms_eq) 0), exact add_group_filter_basis.nhds_zero_has_basis _, end end topology section topological_add_group variables [normed_field π•œ] [add_comm_group E] [module π•œ E] variables [topological_space E] [topological_add_group E] variables [nonempty ΞΉ] lemma seminorm_family.with_seminorms_of_nhds (p : seminorm_family π•œ E ΞΉ) (h : 𝓝 (0 : E) = p.module_filter_basis.to_filter_basis.filter) : with_seminorms p := begin refine ⟨topological_add_group.ext (by apply_instance) (p.add_group_filter_basis.is_topological_add_group) _⟩, rw add_group_filter_basis.nhds_zero_eq, exact h, end lemma seminorm_family.with_seminorms_of_has_basis (p : seminorm_family π•œ E ΞΉ) (h : (𝓝 (0 : E)).has_basis (Ξ» (s : set E), s ∈ p.basis_sets) id) : with_seminorms p := p.with_seminorms_of_nhds $ filter.has_basis.eq_of_same_basis h p.add_group_filter_basis.to_filter_basis.has_basis lemma seminorm_family.with_seminorms_iff_nhds_eq_infi (p : seminorm_family π•œ E ΞΉ) : with_seminorms p ↔ (𝓝 0 : filter E) = β¨… i, (𝓝 0).comap (p i) := begin rw ← p.filter_eq_infi, refine ⟨λ h, _, p.with_seminorms_of_nhds⟩, rw h.topology_eq_with_seminorms, exact add_group_filter_basis.nhds_zero_eq _, end end topological_add_group section normed_space /-- The topology of a `normed_space π•œ E` is induced by the seminorm `norm_seminorm π•œ E`. -/ instance norm_with_seminorms (π•œ E) [normed_field π•œ] [semi_normed_group E] [normed_space π•œ E] : with_seminorms (Ξ» (_ : fin 1), norm_seminorm π•œ E) := begin let p : seminorm_family π•œ E (fin 1) := Ξ» _, norm_seminorm π•œ E, refine ⟨topological_add_group.ext normed_top_group (p.add_group_filter_basis.is_topological_add_group) _⟩, refine filter.has_basis.eq_of_same_basis metric.nhds_basis_ball _, rw ←ball_norm_seminorm π•œ E, refine filter.has_basis.to_has_basis p.add_group_filter_basis.nhds_zero_has_basis _ (Ξ» r hr, ⟨(norm_seminorm π•œ E).ball 0 r, p.basis_sets_singleton_mem 0 hr, rfl.subset⟩), rintros U (hU : U ∈ p.basis_sets), rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, use [r, hr], rw [hU, id.def], by_cases h : s.nonempty, { rw finset.sup_const h }, rw [finset.not_nonempty_iff_eq_empty.mp h, finset.sup_empty, ball_bot _ hr], exact set.subset_univ _, end end normed_space section nondiscrete_normed_field variables [nondiscrete_normed_field π•œ] [add_comm_group E] [module π•œ E] [nonempty ΞΉ] variables (p : seminorm_family π•œ E ΞΉ) variables [topological_space E] [with_seminorms p] lemma bornology.is_vonN_bounded_iff_finset_seminorm_bounded {s : set E} : bornology.is_vonN_bounded π•œ s ↔ βˆ€ I : finset ΞΉ, βˆƒ r (hr : 0 < r), βˆ€ (x ∈ s), I.sup p x < r := begin rw (p.has_basis).is_vonN_bounded_basis_iff, split, { intros h I, simp only [id.def] at h, specialize h ((I.sup p).ball 0 1) (p.basis_sets_mem I zero_lt_one), rcases h with ⟨r, hr, h⟩, cases normed_field.exists_lt_norm π•œ r with a ha, specialize h a (le_of_lt ha), rw [seminorm.smul_ball_zero (lt_trans hr ha), mul_one] at h, refine ⟨βˆ₯aβˆ₯, lt_trans hr ha, _⟩, intros x hx, specialize h hx, exact (finset.sup I p).mem_ball_zero.mp h }, intros h s' hs', rcases p.basis_sets_iff.mp hs' with ⟨I, r, hr, hs'⟩, rw [id.def, hs'], rcases h I with ⟨r', hr', h'⟩, simp_rw ←(I.sup p).mem_ball_zero at h', refine absorbs.mono_right _ h', exact (finset.sup I p).ball_zero_absorbs_ball_zero hr, end lemma bornology.is_vonN_bounded_iff_seminorm_bounded {s : set E} : bornology.is_vonN_bounded π•œ s ↔ βˆ€ i : ΞΉ, βˆƒ r (hr : 0 < r), βˆ€ (x ∈ s), p i x < r := begin rw bornology.is_vonN_bounded_iff_finset_seminorm_bounded p, split, { intros hI i, convert hI {i}, rw [finset.sup_singleton] }, intros hi I, by_cases hI : I.nonempty, { choose r hr h using hi, have h' : 0 < I.sup' hI r := by { rcases hI.bex with ⟨i, hi⟩, exact lt_of_lt_of_le (hr i) (finset.le_sup' r hi) }, refine ⟨I.sup' hI r, h', Ξ» x hx, finset_sup_apply_lt h' (Ξ» i hi, _)⟩, refine lt_of_lt_of_le (h i x hx) _, simp only [finset.le_sup'_iff, exists_prop], exact ⟨i, hi, (eq.refl _).le⟩ }, simp only [finset.not_nonempty_iff_eq_empty.mp hI, finset.sup_empty, coe_bot, pi.zero_apply, exists_prop], exact ⟨1, zero_lt_one, Ξ» _ _, zero_lt_one⟩, end end nondiscrete_normed_field section continuous_bounded namespace seminorm variables [normed_field π•œ] [add_comm_group E] [module π•œ E] [add_comm_group F] [module π•œ F] variables [nonempty ΞΉ] [nonempty ΞΉ'] lemma continuous_from_bounded (p : seminorm_family π•œ E ΞΉ) (q : seminorm_family π•œ F ΞΉ') [uniform_space E] [uniform_add_group E] [with_seminorms p] [uniform_space F] [uniform_add_group F] [with_seminorms q] (f : E β†’β‚—[π•œ] F) (hf : seminorm.is_bounded p q f) : continuous f := begin refine uniform_continuous.continuous _, refine add_monoid_hom.uniform_continuous_of_continuous_at_zero f.to_add_monoid_hom _, rw [f.to_add_monoid_hom_coe, continuous_at_def, f.map_zero, p.with_seminorms_eq], intros U hU, rw [q.with_seminorms_eq, add_group_filter_basis.nhds_zero_eq, filter_basis.mem_filter_iff] at hU, rcases hU with ⟨V, hV : V ∈ q.basis_sets, hU⟩, rcases q.basis_sets_iff.mp hV with ⟨sβ‚‚, r, hr, hV⟩, rw hV at hU, rw [p.add_group_filter_basis.nhds_zero_eq, filter_basis.mem_filter_iff], rcases (seminorm.is_bounded_sup hf sβ‚‚) with ⟨C, s₁, hC, hf⟩, refine ⟨(s₁.sup p).ball 0 (r/C), p.basis_sets_mem _ (div_pos hr (nnreal.coe_pos.mpr hC)), _⟩, refine subset.trans _ (preimage_mono hU), simp_rw [←linear_map.map_zero f, ←ball_comp], refine subset.trans _ (ball_antitone hf), rw ball_smul (s₁.sup p) hC, end lemma cont_with_seminorms_normed_space (F) [semi_normed_group F] [normed_space π•œ F] [uniform_space E] [uniform_add_group E] (p : ΞΉ β†’ seminorm π•œ E) [with_seminorms p] (f : E β†’β‚—[π•œ] F) (hf : βˆƒ (s : finset ΞΉ) C : ℝβ‰₯0, C β‰  0 ∧ (norm_seminorm π•œ F).comp f ≀ C β€’ s.sup p) : continuous f := begin rw ←seminorm.is_bounded_const (fin 1) at hf, exact continuous_from_bounded p (Ξ» _ : fin 1, norm_seminorm π•œ F) f hf, end lemma cont_normed_space_to_with_seminorms (E) [semi_normed_group E] [normed_space π•œ E] [uniform_space F] [uniform_add_group F] (q : ΞΉ β†’ seminorm π•œ F) [with_seminorms q] (f : E β†’β‚—[π•œ] F) (hf : βˆ€ i : ΞΉ, βˆƒ C : ℝβ‰₯0, C β‰  0 ∧ (q i).comp f ≀ C β€’ (norm_seminorm π•œ E)) : continuous f := begin rw ←seminorm.const_is_bounded (fin 1) at hf, exact continuous_from_bounded (Ξ» _ : fin 1, norm_seminorm π•œ E) q f hf, end end seminorm end continuous_bounded section locally_convex_space open locally_convex_space variables [nonempty ΞΉ] [normed_field π•œ] [normed_space ℝ π•œ] [add_comm_group E] [module π•œ E] [module ℝ E] [is_scalar_tower ℝ π•œ E] [topological_space E] [topological_add_group E] lemma seminorm_family.to_locally_convex_space (p : seminorm_family π•œ E ΞΉ) [with_seminorms p] : locally_convex_space ℝ E := begin apply of_basis_zero ℝ E id (Ξ» s, s ∈ p.basis_sets), { rw [p.with_seminorms_eq, add_group_filter_basis.nhds_eq _, add_group_filter_basis.N_zero], exact filter_basis.has_basis _ }, { intros s hs, change s ∈ set.Union _ at hs, simp_rw [set.mem_Union, set.mem_singleton_iff] at hs, rcases hs with ⟨I, r, hr, rfl⟩, exact convex_ball _ _ _ } end end locally_convex_space section normed_space variables (π•œ) [normed_field π•œ] [normed_space ℝ π•œ] [semi_normed_group E] /-- Not an instance since `π•œ` can't be inferred. See `normed_space.to_locally_convex_space` for a slightly weaker instance version. -/ lemma normed_space.to_locally_convex_space' [normed_space π•œ E] [module ℝ E] [is_scalar_tower ℝ π•œ E] : locally_convex_space ℝ E := seminorm_family.to_locally_convex_space (Ξ» _ : fin 1, norm_seminorm π•œ E) /-- See `normed_space.to_locally_convex_space'` for a slightly stronger version which is not an instance. -/ instance normed_space.to_locally_convex_space [normed_space ℝ E] : locally_convex_space ℝ E := normed_space.to_locally_convex_space' ℝ end normed_space
d3e3fbb467007ebde6f8baae4426075a8a833e8f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/euclidean_domain.lean
ff05debc3a231830aea906a9dd695453dd455635
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,490
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.coprime import Mathlib.ring_theory.ideal.basic import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Lemmas about Euclidean domains Various about Euclidean domains are proved; all of them seem to be true more generally for principal ideal domains, so these lemmas should probably be reproved in more generality and this file perhaps removed? ## Tags euclidean domain -/ -- TODO -- this should surely be proved for PIDs instead? theorem span_gcd {Ξ± : Type u_1} [euclidean_domain Ξ±] (x : Ξ±) (y : Ξ±) : ideal.span (singleton (euclidean_domain.gcd x y)) = ideal.span (insert x (singleton y)) := sorry -- this should be proved for PIDs? theorem gcd_is_unit_iff {Ξ± : Type u_1} [euclidean_domain Ξ±] {x : Ξ±} {y : Ξ±} : is_unit (euclidean_domain.gcd x y) ↔ is_coprime x y := sorry -- this should be proved for UFDs surely? theorem is_coprime_of_dvd {Ξ± : Type u_1} [euclidean_domain Ξ±] {x : Ξ±} {y : Ξ±} (z : Β¬(x = 0 ∧ y = 0)) (H : βˆ€ (z : Ξ±), z ∈ nonunits Ξ± β†’ z β‰  0 β†’ z ∣ x β†’ Β¬z ∣ y) : is_coprime x y := sorry -- this should be proved for UFDs surely? theorem dvd_or_coprime {Ξ± : Type u_1} [euclidean_domain Ξ±] (x : Ξ±) (y : Ξ±) (h : irreducible x) : x ∣ y ∨ is_coprime x y := sorry
db492c1c079082ac3e80082cb72a2199bdcd420e
ea4aee6b11f86433e69bb5e50d0259e056d0ae61
/src/tidy/fsplit.lean
4743086cd057f48850128b2caec5f5bf5ffc931b
[]
no_license
timjb/lean-tidy
e18feff0b7f0aad08c614fb4d34aaf527bf21e20
e767e259bf76c69edfd4ab8af1b76e6f1ed67f48
refs/heads/master
1,624,861,693,182
1,504,411,006,000
1,504,411,006,000
103,740,824
0
0
null
1,505,553,968,000
1,505,553,968,000
null
UTF-8
Lean
false
false
372
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison open tactic meta def fsplit : tactic unit := do [c] ← target >>= get_constructors_for | tactic.fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= fapply
b47cb458bf9bdb9d50dcb627516f574bcb18cd25
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/logic/examples/propositional/deceq.lean
e998bf56705fa9d5e970b3a9525162d3fbbbc763
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
1,869
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 PropF has decidable equality -/ import .soundness open bool decidable nat namespace PropF -- Show that PropF has decidable equality definition equal : PropF β†’ PropF β†’ bool | (Var x) (Var y) := if x = y then tt else ff | Bot Bot := tt | (Conj p₁ pβ‚‚) (Conj q₁ qβ‚‚) := equal p₁ q₁ && equal pβ‚‚ qβ‚‚ | (Disj p₁ pβ‚‚) (Disj q₁ qβ‚‚) := equal p₁ q₁ && equal pβ‚‚ qβ‚‚ | (Impl p₁ pβ‚‚) (Impl q₁ qβ‚‚) := equal p₁ q₁ && equal pβ‚‚ qβ‚‚ | _ _ := ff lemma equal_refl : βˆ€ p, equal p p = tt | (Var x) := if_pos rfl | Bot := rfl | (Conj p₁ pβ‚‚) := begin change (equal p₁ p₁ && equal pβ‚‚ pβ‚‚ = tt), rewrite *equal_refl end | (Disj p₁ pβ‚‚) := begin change (equal p₁ p₁ && equal pβ‚‚ pβ‚‚ = tt), rewrite *equal_refl end | (Impl p₁ pβ‚‚) := begin change (equal p₁ p₁ && equal pβ‚‚ pβ‚‚ = tt), rewrite *equal_refl end lemma equal_to_eq : βˆ€ ⦃p q⦄, equal p q = tt β†’ p = q | (Var x) (Var y) H := if H₁ : x = y then congr_arg Var H₁ else by rewrite [β–Έ (if x = y then tt else ff) = tt at H, if_neg H₁ at H]; exact (absurd H ff_ne_tt) | Bot Bot H := rfl | (Conj p₁ pβ‚‚) (Conj q₁ qβ‚‚) H := by rewrite [equal_to_eq (band_elim_left H), equal_to_eq (band_elim_right H)] | (Disj p₁ pβ‚‚) (Disj q₁ qβ‚‚) H := by rewrite [equal_to_eq (band_elim_left H), equal_to_eq (band_elim_right H)] | (Impl p₁ pβ‚‚) (Impl q₁ qβ‚‚) H := by rewrite [equal_to_eq (band_elim_left H), equal_to_eq (band_elim_right H)] lemma has_decidable_eq [instance] : decidable_eq PropF := decidable_eq_of_bool_pred equal_to_eq equal_refl end PropF
361c0da57fa0724f7e59a3cfd48050ba7b618419
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/tactic/positivity.lean
65443879731441adb63f6ae5c53b14acb11f7e32
[ "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
33,466
lean
/- Copyright (c) 2022 Mario Carneiro, Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Heather Macbeth, YaΓ«l Dillies -/ import tactic.norm_num import algebra.order.field.power import algebra.order.hom.basic import data.nat.factorial.basic /-! # `positivity` tactic The `positivity` tactic in this file solves goals of the form `0 ≀ x`, `0 < x` and `x β‰  0`. The tactic works recursively according to the syntax of the expression `x`. For example, a goal of the form `0 ≀ 3 * a ^ 2 + b * c` can be solved either * by a hypothesis such as `5 ≀ 3 * a ^ 2 + b * c` which directly implies the nonegativity of `3 * a ^ 2 + b * c`; or, * by the application of the lemma `add_nonneg` and the success of the `positivity` tactic on the two sub-expressions `3 * a ^ 2` and `b * c`. For each supported operation, one must write a small tactic, tagged with the attribute `@[positivity]`, which operates only on goals whose leading function application is that operation. Typically, this small tactic will run the full `positivity` tactic on one or more of the function's arguments (which is where the recursion comes in), and if successful will combine this with an appropriate lemma to give positivity of the full expression. This file contains the core `positivity` logic and the small tactics handling the basic operations: `min`, `max`, `+`, `*`, `/`, `⁻¹`, raising to natural powers, and taking absolute values. Further extensions, e.g. to handle `real.sqrt` and norms, can be found in the files of the library which introduce these operations. ## Main declarations * `tactic.norm_num.positivity` tries to prove positivity of an expression by running `norm_num` on it. This is one of the base cases of the recursion. * `tactic.positivity.compare_hyp` tries to prove positivity of an expression by comparing with a provided hypothesis. If the hypothesis is of the form `a ≀ b` or similar, with `b` matching the expression whose proof of positivity is desired, then it will check whether `a` can be proved positive via `tactic.norm_num.positivity` and if so apply a transitivity lemma. This is the other base case of the recursion. * `tactic.positivity.attr` creates the `positivity` user attribute for tagging the extension tactics handling specific operations, and specifies the behaviour for a single step of the recursion * `tactic.positivity.core` collects the list of tactics with the `@[positivity]` attribute and calls the first recursion step as specified in `tactic.positivity.attr`. Its input is `e : expr` and its output (if it succeeds) is a term of a custom inductive type `tactic.positivity.strictness`, containing an `expr` which is a proof of the strict-positivity/nonnegativity of `e` as well as an indication of whether what could be proved was strict-positivity or nonnegativity * `tactic.positivity.order_rel` is a custom inductive type recording whether the goal is `0 ≀ e`/`e β‰₯ 0`, `0 < e`/`e > 0`, `e β‰  0` or `0 β‰  e`. * `tactic.interactive.positivity` is the user-facing tactic. It parses the goal and, if it is of one of the forms `0 ≀ e`, `0 < e`, `e > 0`, `e β‰₯ 0`, `e β‰  0`, `0 β‰  e`, it sends `e` to `tactic.positivity.core`. ## TODO Implement extensions for other operations (raising to non-numeral powers, `log`). -/ namespace tactic /-- Inductive type recording either `positive` and an expression (typically a proof of a fact `0 < x`) or `nonnegative` and an expression (typically a proof of a fact `0 ≀ x`). -/ @[derive [decidable_eq]] meta inductive positivity.strictness : Type | positive : expr β†’ positivity.strictness | nonnegative : expr β†’ positivity.strictness | nonzero : expr β†’ positivity.strictness export positivity.strictness (positive nonnegative nonzero) meta instance : has_to_string strictness := ⟨λ s, match s with | positive p := "strictness.positive (" ++ to_string p ++ ")" | nonnegative p := "strictness.nonnegative (" ++ to_string p ++ ")" | nonzero p := "strictness.nonzero (" ++ to_string p ++ ")" end⟩ meta instance : has_to_format strictness := ⟨λ s, to_string s⟩ private lemma lt_of_eq_of_lt'' {Ξ±} [preorder Ξ±] {b b' a : Ξ±} : b = b' β†’ a < b' β†’ a < b := Ξ» h1 h2, lt_of_lt_of_eq h2 h1.symm /-- First base case of the `positivity` tactic. We try `norm_num` to prove directly that an expression `e` is positive, nonnegative or non-zero. -/ meta def norm_num.positivity (e : expr) : tactic strictness := do (e', p) ← norm_num.derive e <|> refl_conv e, e'' ← e'.to_rat, typ ← infer_type e', ic ← mk_instance_cache typ, if e'' > 0 then do (ic, p₁) ← norm_num.prove_pos ic e', positive <$> mk_app ``lt_of_eq_of_lt'' [p, p₁] else if e'' = 0 then nonnegative <$> mk_app ``ge_of_eq [p] else do (ic, p₁) ← norm_num.prove_ne_zero' ic e', nonzero <$> to_expr ``(ne_of_eq_of_ne %%p %%p₁) /-- Second base case of the `positivity` tactic: Any element of a canonically ordered additive monoid is nonnegative. -/ meta def positivity_canon : expr β†’ tactic strictness | `(%%a) := nonnegative <$> mk_app ``zero_le [a] namespace positivity /-- Inductive type recording whether the goal `positivity` is called on is nonnegativity, positivity or different from `0`. -/ @[derive inhabited] inductive order_rel : Type | le : order_rel -- `0 ≀ a` | lt : order_rel -- `0 < a` | ne : order_rel -- `a β‰  0` | ne' : order_rel -- `0 β‰  a` meta instance : has_to_format order_rel := ⟨λ r, match r with | order_rel.le := "order_rel.le" | order_rel.lt := "order_rel.lt" | order_rel.ne := "order_rel.ne" | order_rel.ne' := "order_rel.ne'" end⟩ /-- Given two tactics whose result is `strictness`, report a `strictness`: - if at least one gives `positive`, report `positive` and one of the expressions giving a proof of positivity - if one reports `nonnegative` and the other reports `nonzero`, report `positive` - else if at least one reports `nonnegative`, report `nonnegative` and one of the expressions giving a proof of nonnegativity - else if at least one reports `nonzero`, report `nonzero` and one of the expressions giving a proof of nonzeroness - if both fail, fail -/ protected meta def orelse (tac1 tac2 : tactic strictness) : tactic strictness := do res1 ← try_core tac1, match res1 with | none := tac2 | some p1@(positive _) := pure p1 | some (nonnegative e1) := do res2 ← try_core tac2, match res2 with | some p2@(positive _) := pure p2 | some (nonzero e2) := positive <$> mk_app ``lt_of_le_of_ne' [e1, e2] | _ := pure (nonnegative e1) end | some (nonzero e1) := do res2 ← try_core tac2, match res2 with | some p2@(positive _) := pure p2 | some (nonnegative e2) := positive <$> mk_app ``lt_of_le_of_ne' [e2, e1] | _ := pure (nonzero e1) end end localized "infixr ` ≀|β‰₯ `:2 := tactic.positivity.orelse" in positivity /-- This tactic fails with a message saying that `positivity` couldn't prove anything about `e` if we only know that `a` and `b` are positive/nonnegative/nonzero (according to `pa` and `pb`). -/ meta def positivity_fail {Ξ± : Type*} (e a b : expr) (pa pb : strictness) : tactic Ξ± := do e' ← pp e, a' ← pp a, b' ← pp b, let f : strictness β†’ format β†’ format := Ξ» p c, match p with | positive _ := "0 < " ++ c | nonnegative _ := "0 ≀ " ++ c | nonzero _ := c ++ " β‰  0" end, fail (↑"`positivity` can't say anything about `" ++ e' ++ "` knowing only `" ++ f pa a' ++ "` and `" ++ f pb b' ++ "`") /-! ### Core logic of the `positivity` tactic -/ private lemma ne_of_ne_of_eq' {Ξ± : Type*} {a b c : Ξ±} (ha : a β‰  c) (h : a = b) : b β‰  c := by rwa ←h /-- Calls `norm_num` on `a` to prove positivity/nonnegativity of `e` assuming `b` is defeq to `e` and `pβ‚‚ : a ≀ b`. -/ meta def compare_hyp_le (e a b pβ‚‚ : expr) : tactic strictness := do is_def_eq e b, strict_a ← norm_num.positivity a, match strict_a with | positive p₁ := positive <$> mk_app ``lt_of_lt_of_le [p₁, pβ‚‚] | nonnegative p₁ := nonnegative <$> mk_app ``le_trans [p₁, pβ‚‚] | _ := do e' ← pp e, pβ‚‚' ← pp pβ‚‚, fail (↑"`norm_num` can't prove nonnegativity of " ++ e' ++ " using " ++ pβ‚‚') end /-- Calls `norm_num` on `a` to prove positivity/nonnegativity of `e` assuming `b` is defeq to `e` and `pβ‚‚ : a < b`. -/ meta def compare_hyp_lt (e a b pβ‚‚ : expr) : tactic strictness := do is_def_eq e b, strict_a ← norm_num.positivity a, match strict_a with | positive p₁ := positive <$> mk_app ``lt_trans [p₁, pβ‚‚] | nonnegative p₁ := positive <$> mk_app ``lt_of_le_of_lt [p₁, pβ‚‚] | _ := do e' ← pp e, pβ‚‚' ← pp pβ‚‚, fail (↑"`norm_num` can't prove positivity of " ++ e' ++ " using " ++ pβ‚‚') end /-- Calls `norm_num` on `a` to prove positivity/nonnegativity/nonzeroness of `e` assuming `b` is defeq to `e` and `pβ‚‚ : a = b`. -/ meta def compare_hyp_eq (e a b pβ‚‚ : expr) : tactic strictness := do is_def_eq e b, strict_a ← norm_num.positivity a, match strict_a with | positive p₁ := positive <$> mk_app ``lt_of_lt_of_eq [p₁, pβ‚‚] | nonnegative p₁ := nonnegative <$> mk_app ``le_of_le_of_eq [p₁, pβ‚‚] | nonzero p₁ := nonzero <$> to_expr ``(ne_of_ne_of_eq' %%p₁ %%pβ‚‚) end /-- Calls `norm_num` on `a` to prove nonzeroness of `e` assuming `b` is defeq to `e` and `pβ‚‚ : b β‰  a`. -/ meta def compare_hyp_ne (e a b pβ‚‚ : expr) : tactic strictness := do is_def_eq e b, (a', p₁) ← norm_num.derive a <|> refl_conv a, a'' ← a'.to_rat, if a'' = 0 then nonzero <$> mk_mapp ``ne_of_ne_of_eq [none, none, none, none, pβ‚‚, p₁] else do e' ← pp e, pβ‚‚' ← pp pβ‚‚, a' ← pp a, fail (↑"`norm_num` can't prove non-zeroness of " ++ e' ++ " using " ++ pβ‚‚' ++ " because " ++ a' ++ " is non-zero") /-- Third base case of the `positivity` tactic. Prove an expression `e` is positive/nonnegative/nonzero by finding a hypothesis of the form `a < e`, `a ≀ e` or `a = e` in which `a` can be proved positive/nonnegative/nonzero by `norm_num`. -/ meta def compare_hyp (e pβ‚‚ : expr) : tactic strictness := do p_typ ← infer_type pβ‚‚, match p_typ with | `(%%lo ≀ %%hi) := compare_hyp_le e lo hi pβ‚‚ | `(%%hi β‰₯ %%lo) := compare_hyp_le e lo hi pβ‚‚ | `(%%lo < %%hi) := compare_hyp_lt e lo hi pβ‚‚ | `(%%hi > %%lo) := compare_hyp_lt e lo hi pβ‚‚ | `(%%lo = %%hi) := compare_hyp_eq e lo hi pβ‚‚ <|> do pβ‚‚' ← mk_app ``eq.symm [pβ‚‚], compare_hyp_eq e hi lo pβ‚‚' | `(%%hi β‰  %%lo) := compare_hyp_ne e lo hi pβ‚‚ <|> do pβ‚‚' ← mk_mapp ``ne.symm [none, none, none, pβ‚‚], compare_hyp_ne e hi lo pβ‚‚' | e := do pβ‚‚' ← pp pβ‚‚, fail (pβ‚‚' ++ "is not of the form `a ≀ b`, `a < b`, `a = b` or `a β‰  b`") end /-- Attribute allowing a user to tag a tactic as an extension for `tactic.interactive.positivity`. The main (recursive) step of this tactic is to try successively all the extensions tagged with this attribute on the expression at hand, and also to try the two "base case" tactics `tactic.norm_num.positivity`, `tactic.positivity.compare_hyp` on the expression at hand. -/ @[user_attribute] meta def attr : user_attribute (expr β†’ tactic strictness) unit := { name := `positivity, descr := "extensions handling particular operations for the `positivity` tactic", cache_cfg := { mk_cache := Ξ» ns, do { t ← ns.mfoldl (Ξ» (t : expr β†’ tactic strictness) n, do t' ← eval_expr (expr β†’ tactic strictness) (expr.const n []), pure (Ξ» e, t' e ≀|β‰₯ t e)) (Ξ» _, failed), pure $ Ξ» e, t e -- run all the extensions on `e` ≀|β‰₯ norm_num.positivity e -- directly try `norm_num` on `e` ≀|β‰₯ positivity_canon e -- try showing nonnegativity from canonicity of the order -- loop over hypotheses and try to compare with `e` ≀|β‰₯ local_context >>= list.foldl (Ξ» tac h, tac ≀|β‰₯ compare_hyp e h) (fail "no applicable positivity extension found") }, dependencies := [] } } /-- Look for a proof of positivity/nonnegativity of an expression `e`; if found, return the proof together with a `strictness` stating whether the proof found was for strict positivity (`positive p`), nonnegativity (`nonnegative p`), or nonzeroness (`nonzero p`). -/ meta def core (e : expr) : tactic strictness := do f ← attr.get_cache, f e <|> fail "failed to prove positivity/nonnegativity/nonzeroness" end positivity open positivity open_locale positivity namespace interactive setup_tactic_parser /-- Tactic solving goals of the form `0 ≀ x`, `0 < x` and `x β‰  0`. The tactic works recursively according to the syntax of the expression `x`, if the atoms composing the expression all have numeric lower bounds which can be proved positive/nonnegative/nonzero by `norm_num`. This tactic either closes the goal or fails. Examples: ``` example {a : β„€} (ha : 3 < a) : 0 ≀ a ^ 3 + a := by positivity example {a : β„€} (ha : 1 < a) : 0 < |(3:β„€) + a| := by positivity example {b : β„€} : 0 ≀ max (-3) (b ^ 2) := by positivity ``` -/ meta def positivity : tactic unit := focus1 $ do t ← target >>= instantiate_mvars, (rel_desired, a) ← match t with | `(0 ≀ %%e) := pure (order_rel.le, e) | `(%%e β‰₯ 0) := pure (order_rel.le, e) | `(0 < %%e) := pure (order_rel.lt, e) | `(%%e > 0) := pure (order_rel.lt, e) | `(%%e₁ β‰  %%eβ‚‚) := do match eβ‚‚ with | `(has_zero.zero) := pure (order_rel.ne, e₁) | _ := match e₁ with | `(has_zero.zero) := pure (order_rel.ne', eβ‚‚) | _ := fail "not a positivity/nonnegativity/nonzeroness goal" end end | _ := fail "not a positivity/nonnegativity/nonzeroness goal" end, strictness_proved ← tactic.positivity.core a, match rel_desired, strictness_proved with | order_rel.lt, positive p := pure p | order_rel.lt, nonnegative _ := fail ("failed to prove strict positivity, but it would be " ++ "possible to prove nonnegativity if desired") | order_rel.lt, nonzero _ := fail ("failed to prove strict positivity, but it would be " ++ "possible to prove nonzeroness if desired") | order_rel.le, positive p := mk_app ``le_of_lt [p] | order_rel.le, nonnegative p := pure p | order_rel.le, nonzero _ := fail ("failed to prove nonnegativity, but it would be " ++ "possible to prove nonzeroness if desired") | order_rel.ne, positive p := to_expr ``(ne_of_gt %%p) | order_rel.ne, nonnegative _ := fail ("failed to prove nonzeroness, but it would be " ++ "possible to prove nonnegativity if desired") | order_rel.ne, nonzero p := pure p | order_rel.ne', positive p := to_expr ``(ne_of_lt %%p) | order_rel.ne', nonnegative _ := fail ("failed to prove nonzeroness, but it would be " ++ "possible to prove nonnegativity if desired") | order_rel.ne', nonzero p := to_expr ``(ne.symm %%p) end >>= tactic.exact add_tactic_doc { name := "positivity", category := doc_category.tactic, decl_names := [`tactic.interactive.positivity], tags := ["arithmetic", "monotonicity", "finishing"] } end interactive variables {ΞΉ Ξ± R : Type*} /-! ### `positivity` extensions for particular arithmetic operations -/ section linear_order variables [linear_order R] {a b c : R} private lemma le_min_of_lt_of_le (ha : a < b) (hb : a ≀ c) : a ≀ min b c := le_min ha.le hb private lemma le_min_of_le_of_lt (ha : a ≀ b) (hb : a < c) : a ≀ min b c := le_min ha hb.le private lemma min_ne (ha : a β‰  c) (hb : b β‰  c) : min a b β‰  c := by { rw min_def, split_ifs; assumption } private lemma min_ne_of_ne_of_lt (ha : a β‰  c) (hb : c < b) : min a b β‰  c := min_ne ha hb.ne' private lemma min_ne_of_lt_of_ne (ha : c < a) (hb : b β‰  c) : min a b β‰  c := min_ne ha.ne' hb private lemma max_ne (ha : a β‰  c) (hb : b β‰  c) : max a b β‰  c := by { rw max_def, split_ifs; assumption } end linear_order /-- Extension for the `positivity` tactic: the `min` of two numbers is nonnegative if both are nonnegative, and strictly positive if both are. -/ @[positivity] meta def positivity_min : expr β†’ tactic strictness | e@`(min %%a %%b) := do strictness_a ← core a, strictness_b ← core b, match strictness_a, strictness_b with | (positive pa), (positive pb) := positive <$> mk_app ``lt_min [pa, pb] | (positive pa), (nonnegative pb) := nonnegative <$> mk_app ``le_min_of_lt_of_le [pa, pb] | (nonnegative pa), (positive pb) := nonnegative <$> mk_app ``le_min_of_le_of_lt [pa, pb] | (nonnegative pa), (nonnegative pb) := nonnegative <$> mk_app ``le_min [pa, pb] | positive pa, nonzero pb := nonzero <$> to_expr ``(min_ne_of_lt_of_ne %%pa %%pb) | nonzero pa, positive pb := nonzero <$> to_expr ``(min_ne_of_ne_of_lt %%pa %%pb) | nonzero pa, nonzero pb := nonzero <$> to_expr ``(min_ne %%pa %%pb) | sa@_, sb@ _ := positivity_fail e a b sa sb end | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `min a b`" /-- Extension for the `positivity` tactic: the `max` of two numbers is nonnegative if at least one is nonnegative, strictly positive if at least one is positive, and nonzero if both are nonzero. -/ @[positivity] meta def positivity_max : expr β†’ tactic strictness | `(max %%a %%b) := do strictness_a ← try_core (core a), (do match strictness_a with | some (positive pa) := positive <$> mk_mapp ``lt_max_of_lt_left [none, none, none, a, b, pa] | some (nonnegative pa) := nonnegative <$> mk_mapp ``le_max_of_le_left [none, none, none, a, b, pa] | _ := failed -- If `a β‰  0`, we might prove `max a b β‰  0` if `b β‰  0` but we don't want to evaluate -- `b` before having ruled out `0 < a`, for performance. So we do that in the second branch -- of the `orelse'`. end) ≀|β‰₯ (do strictness_b ← core b, match strictness_b with | (positive pb) := positive <$> mk_mapp ``lt_max_of_lt_right [none, none, none, a, b, pb] | (nonnegative pb) := nonnegative <$> mk_mapp ``le_max_of_le_right [none, none, none, a, b, pb] | nonzero pb := do nonzero pa ← strictness_a, nonzero <$> to_expr ``(max_ne %%pa %%pb) end) | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `max a b`" /-- Extension for the `positivity` tactic: addition is nonnegative if both summands are nonnegative, and strictly positive if at least one summand is. -/ @[positivity] meta def positivity_add : expr β†’ tactic strictness | e@`(%%a + %%b) := do strictness_a ← core a, strictness_b ← core b, match strictness_a, strictness_b with | (positive pa), (positive pb) := positive <$> mk_app ``add_pos [pa, pb] | (positive pa), (nonnegative pb) := positive <$> mk_app ``lt_add_of_pos_of_le [pa, pb] | (nonnegative pa), (positive pb) := positive <$> mk_app ``lt_add_of_le_of_pos [pa, pb] | (nonnegative pa), (nonnegative pb) := nonnegative <$> mk_app ``add_nonneg [pa, pb] | sa@_, sb@ _ := positivity_fail e a b sa sb end | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `a + b`" section ordered_semiring variables [ordered_semiring R] {a b : R} private lemma mul_nonneg_of_pos_of_nonneg (ha : 0 < a) (hb : 0 ≀ b) : 0 ≀ a * b := mul_nonneg ha.le hb private lemma mul_nonneg_of_nonneg_of_pos (ha : 0 ≀ a) (hb : 0 < b) : 0 ≀ a * b := mul_nonneg ha hb.le private lemma mul_ne_zero_of_pos_of_ne_zero [no_zero_divisors R] (ha : 0 < a) (hb : b β‰  0) : a * b β‰  0 := mul_ne_zero ha.ne' hb private lemma mul_ne_zero_of_ne_zero_of_pos [no_zero_divisors R] (ha : a β‰  0) (hb : 0 < b) : a * b β‰  0 := mul_ne_zero ha hb.ne' end ordered_semiring /-- Extension for the `positivity` tactic: multiplication is nonnegative/positive/nonzero if both multiplicands are. -/ @[positivity] meta def positivity_mul : expr β†’ tactic strictness | e@`(%%a * %%b) := do strictness_a ← core a, strictness_b ← core b, match strictness_a, strictness_b with | (positive pa), (positive pb) := positive <$> mk_app ``mul_pos [pa, pb] | (positive pa), (nonnegative pb) := nonnegative <$> mk_app ``mul_nonneg_of_pos_of_nonneg [pa, pb] | (nonnegative pa), (positive pb) := nonnegative <$> mk_app ``mul_nonneg_of_nonneg_of_pos [pa, pb] | (nonnegative pa), (nonnegative pb) := nonnegative <$> mk_app ``mul_nonneg [pa, pb] | positive pa, nonzero pb := nonzero <$> to_expr ``(mul_ne_zero_of_pos_of_ne_zero %%pa %%pb) | nonzero pa, positive pb := nonzero <$> to_expr ``(mul_ne_zero_of_ne_zero_of_pos %%pa %%pb) | nonzero pa, nonzero pb := nonzero <$> to_expr ``(mul_ne_zero %%pa %%pb) | sa@_, sb@ _ := positivity_fail e a b sa sb end | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `a * b`" section linear_ordered_semifield variables [linear_ordered_semifield R] {a b : R} private lemma div_nonneg_of_pos_of_nonneg (ha : 0 < a) (hb : 0 ≀ b) : 0 ≀ a / b := div_nonneg ha.le hb private lemma div_nonneg_of_nonneg_of_pos (ha : 0 ≀ a) (hb : 0 < b) : 0 ≀ a / b := div_nonneg ha hb.le private lemma div_ne_zero_of_pos_of_ne_zero (ha : 0 < a) (hb : b β‰  0) : a / b β‰  0 := div_ne_zero ha.ne' hb private lemma div_ne_zero_of_ne_zero_of_pos (ha : a β‰  0) (hb : 0 < b) : a / b β‰  0 := div_ne_zero ha hb.ne' end linear_ordered_semifield private lemma int_div_self_pos {a : β„€} (ha : 0 < a) : 0 < a / a := by { rw int.div_self ha.ne', exact zero_lt_one } private lemma int_div_nonneg_of_pos_of_nonneg {a b : β„€} (ha : 0 < a) (hb : 0 ≀ b) : 0 ≀ a / b := int.div_nonneg ha.le hb private lemma int_div_nonneg_of_nonneg_of_pos {a b : β„€} (ha : 0 ≀ a) (hb : 0 < b) : 0 ≀ a / b := int.div_nonneg ha hb.le private lemma int_div_nonneg_of_pos_of_pos {a b : β„€} (ha : 0 < a) (hb : 0 < b) : 0 ≀ a / b := int.div_nonneg ha.le hb.le /-- Extension for the `positivity` tactic: division is nonnegative if both numerator and denominator are nonnegative, and strictly positive if both numerator and denominator are. -/ @[positivity] meta def positivity_div : expr β†’ tactic strictness | e@`(@has_div.div β„€ _ %%a %%b) := do strictness_a ← core a, strictness_b ← core b, match strictness_a, strictness_b with | positive pa, positive pb := if a = b then -- Only attempts to prove `0 < a / a`, otherwise falls back to `0 ≀ a / b` positive <$> mk_app ``int_div_self_pos [pa] else nonnegative <$> mk_app ``int_div_nonneg_of_pos_of_pos [pa, pb] | positive pa, nonnegative pb := nonnegative <$> mk_app ``int_div_nonneg_of_pos_of_nonneg [pa, pb] | nonnegative pa, positive pb := nonnegative <$> mk_app ``int_div_nonneg_of_nonneg_of_pos [pa, pb] | nonnegative pa, nonnegative pb := nonnegative <$> mk_app ``int.div_nonneg [pa, pb] | sa@_, sb@ _ := positivity_fail e a b sa sb end | e@`(%%a / %%b) := do strictness_a ← core a, strictness_b ← core b, match strictness_a, strictness_b with | positive pa, positive pb := positive <$> mk_app ``div_pos [pa, pb] | positive pa, nonnegative pb := nonnegative <$> mk_app ``div_nonneg_of_pos_of_nonneg [pa, pb] | nonnegative pa, positive pb := nonnegative <$> mk_app ``div_nonneg_of_nonneg_of_pos [pa, pb] | nonnegative pa, nonnegative pb := nonnegative <$> mk_app ``div_nonneg [pa, pb] | positive pa, nonzero pb := nonzero <$> to_expr ``(div_ne_zero_of_pos_of_ne_zero %%pa %%pb) | nonzero pa, positive pb := nonzero <$> to_expr ``(div_ne_zero_of_ne_zero_of_pos %%pa %%pb) | nonzero pa, nonzero pb := nonzero <$> to_expr ``(div_ne_zero %%pa %%pb) | sa@_, sb@ _ := positivity_fail e a b sa sb end | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `a / b`" /-- Extension for the `positivity` tactic: an inverse of a positive number is positive, an inverse of a nonnegative number is nonnegative. -/ @[positivity] meta def positivity_inv : expr β†’ tactic strictness | `((%%a)⁻¹) := do strictness_a ← core a, match strictness_a with | (positive pa) := positive <$> mk_app ``inv_pos_of_pos [pa] | (nonnegative pa) := nonnegative <$> mk_app ``inv_nonneg_of_nonneg [pa] | nonzero pa := nonzero <$> to_expr ``(inv_ne_zero %%pa) end | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `a⁻¹`" private lemma pow_zero_pos [ordered_semiring R] [nontrivial R] (a : R) : 0 < a ^ 0 := zero_lt_one.trans_le (pow_zero a).ge private lemma zpow_zero_pos [linear_ordered_semifield R] (a : R) : 0 < a ^ (0 : β„€) := zero_lt_one.trans_le (zpow_zero a).ge /-- Extension for the `positivity` tactic: raising a number `a` to a natural/integer power `n` is positive if `n = 0` (since `a ^ 0 = 1`) or if `0 < a`, and is nonnegative if `n` is even (squares are nonnegative) or if `0 ≀ a`. -/ @[positivity] meta def positivity_pow : expr β†’ tactic strictness | e@`(%%a ^ %%n) := do typ ← infer_type n, (do unify typ `(β„•), if n = `(0) then positive <$> mk_app ``pow_zero_pos [a] else do -- even powers are nonnegative -- Note this is automatically strengthened to `0 < a ^ n` when `a β‰  0` thanks to the `orelse'` match n with -- TODO: Decision procedure for parity | `(bit0 %% n) := nonnegative <$> mk_app ``pow_bit0_nonneg [a, n] | _ := do e' ← pp e, fail (e' ++ "is not an even power so positivity can't prove it's nonnegative") end ≀|β‰₯ do -- `a ^ n` is positive if `a` is, and nonnegative if `a` is strictness_a ← core a, match strictness_a with | positive p := positive <$> mk_app ``pow_pos [p, n] | nonnegative p := nonnegative <$> mk_app `pow_nonneg [p, n] | nonzero p := nonzero <$> to_expr ``(pow_ne_zero %%n %%p) end) <|> (do unify typ `(β„€), if n = `(0 : β„€) then positive <$> mk_app ``zpow_zero_pos [a] else do -- even powers are nonnegative -- Note this is automatically strengthened to `0 < a ^ n` when `a β‰  0` thanks to the `orelse'` match n with -- TODO: Decision procedure for parity | `(bit0 %%n) := nonnegative <$> mk_app ``zpow_bit0_nonneg [a, n] | _ := do e' ← pp e, fail (e' ++ "is not an even power so positivity can't prove it's nonnegative") end ≀|β‰₯ do -- `a ^ n` is positive if `a` is, and nonnegative if `a` is strictness_a ← core a, match strictness_a with | positive p := positive <$> mk_app ``zpow_pos_of_pos [p, n] | nonnegative p := nonnegative <$> mk_app ``zpow_nonneg [p, n] | nonzero p := nonzero <$> to_expr ``(zpow_ne_zero %%n %%p) end) | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `a ^ n`" /-- Extension for the `positivity` tactic: raising a positive number in a canonically ordered semiring gives a positive number. -/ @[positivity] meta def positivity_canon_pow : expr β†’ tactic strictness | `(%%r ^ %%n) := do typ_n ← infer_type n, unify typ_n `(β„•), positive p ← core r, positive <$> mk_app ``canonically_ordered_comm_semiring.pow_pos [p, n] -- The nonzero never happens because of `tactic.positivity_canon` | e := pp e >>= fail ∘ format.bracket "The expression `" "` is not of the form `a ^ n` for `a` in a `canonically_ordered_comm_semiring` and `n : β„•`" private alias abs_pos ↔ _ abs_pos_of_ne_zero /-- Extension for the `positivity` tactic: an absolute value is nonnegative, and is strictly positive if its input is nonzero. -/ @[positivity] meta def positivity_abs : expr β†’ tactic strictness | `(|%%a|) := do (do -- if can prove `0 < a` or `a β‰  0`, report positivity strict_a ← core a, match strict_a with | positive p := positive <$> mk_app ``abs_pos_of_pos [p] | nonzero p := positive <$> mk_app ``abs_pos_of_ne_zero [p] | _ := failed end) <|> nonnegative <$> mk_app ``abs_nonneg [a] -- else report nonnegativity | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `|a|`" private lemma int_nat_abs_pos {n : β„€} (hn : 0 < n) : 0 < n.nat_abs := int.nat_abs_pos_of_ne_zero hn.ne' /-- Extension for the `positivity` tactic: `int.nat_abs` is positive when its input is. Since the output type of `int.nat_abs` is `β„•`, the nonnegative case is handled by the default `positivity` tactic. -/ @[positivity] meta def positivity_nat_abs : expr β†’ tactic strictness | `(int.nat_abs %%a) := do strict_a ← core a, match strict_a with | positive p := positive <$> mk_app ``int_nat_abs_pos [p] | nonzero p := positive <$> mk_app ``int.nat_abs_pos_of_ne_zero [p] | _ := failed end | _ := failed private lemma nat_cast_pos [ordered_semiring Ξ±] [nontrivial Ξ±] {n : β„•} : 0 < n β†’ 0 < (n : Ξ±) := nat.cast_pos.2 private lemma int_coe_nat_nonneg (n : β„•) : 0 ≀ (n : β„€) := n.cast_nonneg private lemma int_coe_nat_pos {n : β„•} : 0 < n β†’ 0 < (n : β„€) := nat.cast_pos.2 private lemma int_cast_ne_zero [add_group_with_one Ξ±] [char_zero Ξ±] {n : β„€} : n β‰  0 β†’ (n : Ξ±) β‰  0 := int.cast_ne_zero.2 private lemma int_cast_nonneg [ordered_ring Ξ±] {n : β„€} (hn : 0 ≀ n) : 0 ≀ (n : Ξ±) := by { rw ←int.cast_zero, exact int.cast_mono hn } private lemma int_cast_pos [ordered_ring Ξ±] [nontrivial Ξ±] {n : β„€} : 0 < n β†’ 0 < (n : Ξ±) := int.cast_pos.2 private lemma rat_cast_ne_zero [division_ring Ξ±] [char_zero Ξ±] {q : β„š} : q β‰  0 β†’ (q : Ξ±) β‰  0 := rat.cast_ne_zero.2 private lemma rat_cast_nonneg [linear_ordered_field Ξ±] {q : β„š} : 0 ≀ q β†’ 0 ≀ (q : Ξ±) := rat.cast_nonneg.2 private lemma rat_cast_pos [linear_ordered_field Ξ±] {q : β„š} : 0 < q β†’ 0 < (q : Ξ±) := rat.cast_pos.2 /-- Extension for the `positivity` tactic: casts from `β„•`, `β„€`, `β„š`. -/ @[positivity] meta def positivity_coe : expr β†’ tactic strictness | `(@coe _ %%typ %%inst %%a) := do -- TODO: Using `match` here might turn out too strict since we really want the instance to *unify* -- with one of the instances below rather than being equal on the nose. -- If this turns out to indeed be a problem, we should figure out the right way to pattern match -- up to defeq rather than equality of expressions. -- See also "Reflexive tactics for algebra, revisited" by Kazuhiko Sakaguchi at ITP 2022. match inst with | `(@coe_to_lift _ _ %%inst) := do strictness_a ← core a, match inst, strictness_a with -- `mk_mapp` is necessary in some places. Why? | `(nat.cast_coe), positive p := positive <$> mk_mapp ``nat_cast_pos [typ, none, none, none, p] | `(nat.cast_coe), _ := nonnegative <$> mk_mapp ``nat.cast_nonneg [typ, none, a] | `(int.cast_coe), positive p := positive <$> mk_mapp ``int_cast_pos [typ, none, none, none, p] | `(int.cast_coe), nonnegative p := nonnegative <$> mk_mapp ``int_cast_nonneg [typ, none, none, p] | `(int.cast_coe), nonzero p := nonzero <$> mk_mapp ``int_cast_ne_zero [typ, none, none, none, p] | `(rat.cast_coe), positive p := positive <$> mk_mapp ``rat_cast_pos [typ, none, none, p] | `(rat.cast_coe), nonnegative p := nonnegative <$> mk_mapp ``rat_cast_nonneg [typ, none, none, p] | `(rat.cast_coe), nonzero p := nonzero <$> mk_mapp ``rat_cast_ne_zero [typ, none, none, none, p] | `(@coe_base _ _ int.has_coe), positive p := positive <$> mk_app ``int_coe_nat_pos [p] | `(@coe_base _ _ int.has_coe), _ := nonnegative <$> mk_app ``int_coe_nat_nonneg [a] | _, _ := failed end | _ := failed end | _ := failed /-- Extension for the `positivity` tactic: `nat.succ` is always positive. -/ @[positivity] meta def positivity_succ : expr β†’ tactic strictness | `(nat.succ %%a) := positive <$> mk_app `nat.succ_pos [a] | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `nat.succ n`" /-- Extension for the `positivity` tactic: `nat.factorial` is always positive. -/ @[positivity] meta def positivity_factorial : expr β†’ tactic strictness | `(nat.factorial %%a) := positive <$> mk_app ``nat.factorial_pos [a] | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `n!`" /-- Extension for the `positivity` tactic: `nat.asc_factorial` is always positive. -/ @[positivity] meta def positivity_asc_factorial : expr β†’ tactic strictness | `(nat.asc_factorial %%a %%b) := positive <$> mk_app ``nat.asc_factorial_pos [a, b] | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `nat.asc_factorial n k`" /-- Extension for the `positivity` tactic: nonnegative maps take nonnegative values. -/ @[positivity] meta def positivity_map : expr β†’ tactic strictness | (expr.app `(⇑%%f) `(%%a)) := nonnegative <$> mk_app ``map_nonneg [f, a] | _ := failed end tactic
0a9cf9040cfbe2fc219617a2b880ada29819f1c0
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/ring_theory/polynomial/scale_roots.lean
28d4d573eeccbeb809fb294714c3b951ff2d41c2
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
5,350
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Devon Tuma -/ import ring_theory.polynomial.basic import ring_theory.non_zero_divisors /-! # Scaling the roots of a polynomial This file defines `scale_roots p s` for a polynomial `p` in one variable and a ring element `s` to be the polynomial with root `r * s` for each root `r` of `p` and proves some basic results about it. -/ section scale_roots variables {A K R S : Type*} [integral_domain A] [field K] [comm_ring R] [comm_ring S] variables {M : submonoid A} open finsupp polynomial /-- `scale_roots p s` is a polynomial with root `r * s` for each root `r` of `p`. -/ noncomputable def scale_roots (p : polynomial R) (s : R) : polynomial R := on_finset p.support (Ξ» i, coeff p i * s ^ (p.nat_degree - i)) (Ξ» i h, mem_support_iff.mpr (left_ne_zero_of_mul h)) @[simp] lemma coeff_scale_roots (p : polynomial R) (s : R) (i : β„•) : (scale_roots p s).coeff i = coeff p i * s ^ (p.nat_degree - i) := rfl lemma coeff_scale_roots_nat_degree (p : polynomial R) (s : R) : (scale_roots p s).coeff p.nat_degree = p.leading_coeff := by rw [leading_coeff, coeff_scale_roots, nat.sub_self, pow_zero, mul_one] @[simp] lemma zero_scale_roots (s : R) : scale_roots 0 s = 0 := by { ext, simp } lemma scale_roots_ne_zero {p : polynomial R} (hp : p β‰  0) (s : R) : scale_roots p s β‰  0 := begin intro h, have : p.coeff p.nat_degree β‰  0 := mt leading_coeff_eq_zero.mp hp, have : (scale_roots p s).coeff p.nat_degree = 0 := congr_fun (congr_arg (coeff : polynomial R β†’ β„• β†’ R) h) p.nat_degree, rw [coeff_scale_roots_nat_degree] at this, contradiction end lemma support_scale_roots_le (p : polynomial R) (s : R) : (scale_roots p s).support ≀ p.support := begin intros i, simp only [mem_support_iff, scale_roots, on_finset_apply], exact left_ne_zero_of_mul end lemma support_scale_roots_eq (p : polynomial R) {s : R} (hs : s ∈ non_zero_divisors R) : (scale_roots p s).support = p.support := le_antisymm (support_scale_roots_le p s) begin intro i, simp only [mem_support_iff, scale_roots, on_finset_apply], intros p_ne_zero ps_zero, have := ((non_zero_divisors R).pow_mem hs (p.nat_degree - i)) _ ps_zero, contradiction end @[simp] lemma degree_scale_roots (p : polynomial R) {s : R} : degree (scale_roots p s) = degree p := begin haveI := classical.prop_decidable, by_cases hp : p = 0, { rw [hp, zero_scale_roots] }, have := scale_roots_ne_zero hp s, refine le_antisymm (finset.sup_mono (support_scale_roots_le p s)) (degree_le_degree _), rw coeff_scale_roots_nat_degree, intro h, have := leading_coeff_eq_zero.mp h, contradiction, end @[simp] lemma nat_degree_scale_roots (p : polynomial R) (s : R) : nat_degree (scale_roots p s) = nat_degree p := by simp only [nat_degree, degree_scale_roots] lemma monic_scale_roots_iff {p : polynomial R} (s : R) : monic (scale_roots p s) ↔ monic p := by simp only [monic, leading_coeff, nat_degree_scale_roots, coeff_scale_roots_nat_degree] lemma scale_roots_evalβ‚‚_eq_zero {p : polynomial S} (f : S β†’+* R) {r : R} {s : S} (hr : evalβ‚‚ f r p = 0) : evalβ‚‚ f (f s * r) (scale_roots p s) = 0 := calc evalβ‚‚ f (f s * r) (scale_roots p s) = (scale_roots p s).support.sum (Ξ» i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : evalβ‚‚_eq_sum ... = p.support.sum (Ξ» i, f (coeff p i * s ^ (p.nat_degree - i)) * (f s * r) ^ i) : finset.sum_subset (support_scale_roots_le p s) (Ξ» i hi hi', let this : coeff p i * s ^ (p.nat_degree - i) = 0 := by simpa using hi' in by simp [this]) ... = p.support.sum (Ξ» (i : β„•), f (p.coeff i) * f s ^ (p.nat_degree - i + i) * r ^ i) : finset.sum_congr rfl (Ξ» i hi, by simp_rw [f.map_mul, f.map_pow, pow_add, mul_pow, mul_assoc]) ... = p.support.sum (Ξ» (i : β„•), f s ^ p.nat_degree * (f (p.coeff i) * r ^ i)) : finset.sum_congr rfl (Ξ» i hi, by { rw [mul_assoc, mul_left_comm, nat.sub_add_cancel], exact le_nat_degree_of_ne_zero (mem_support_iff.mp hi) }) ... = f s ^ p.nat_degree * p.support.sum (Ξ» (i : β„•), (f (p.coeff i) * r ^ i)) : finset.mul_sum.symm ... = f s ^ p.nat_degree * evalβ‚‚ f r p : by { rw [evalβ‚‚_eq_sum], refl } ... = 0 : by rw [hr, _root_.mul_zero] lemma scale_roots_aeval_eq_zero [algebra S R] {p : polynomial S} {r : R} {s : S} (hr : aeval r p = 0) : aeval (algebra_map S R s * r) (scale_roots p s) = 0 := scale_roots_evalβ‚‚_eq_zero (algebra_map S R) hr lemma scale_roots_evalβ‚‚_eq_zero_of_evalβ‚‚_div_eq_zero {p : polynomial A} {f : A β†’+* K} (hf : function.injective f) {r s : A} (hr : evalβ‚‚ f (f r / f s) p = 0) (hs : s ∈ non_zero_divisors A) : evalβ‚‚ f (f r) (scale_roots p s) = 0 := begin convert scale_roots_evalβ‚‚_eq_zero f hr, rw [←mul_div_assoc, mul_comm, mul_div_cancel], exact @map_ne_zero_of_mem_non_zero_divisors _ _ _ _ _ _ hf ⟨s, hs⟩ end lemma scale_roots_aeval_eq_zero_of_aeval_div_eq_zero [algebra A K] (inj : function.injective (algebra_map A K)) {p : polynomial A} {r s : A} (hr : aeval (algebra_map A K r / algebra_map A K s) p = 0) (hs : s ∈ non_zero_divisors A) : aeval (algebra_map A K r) (scale_roots p s) = 0 := scale_roots_evalβ‚‚_eq_zero_of_evalβ‚‚_div_eq_zero inj hr hs end scale_roots
5f29123c4dc9e7c75dcf07c5675b51993a9cfa30
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/ring/units.lean
5005f799cbd520200dd7d953d7d25b6a3b591b8d
[ "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
3,537
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Yury Kudryashov, Neil Strickland -/ import algebra.ring.inj_surj import algebra.group.units /-! # Units in semirings and rings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/746 > Any changes to this file require a corresponding PR to mathlib4. -/ universes u v w x variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} {R : Type x} open function namespace units section has_distrib_neg variables [monoid Ξ±] [has_distrib_neg Ξ±] {a b : Ξ±} /-- Each element of the group of units of a ring has an additive inverse. -/ instance : has_neg Ξ±Λ£ := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩ /-- Representing an element of a ring's unit group as an element of the ring commutes with mapping this element to its additive inverse. -/ @[simp, norm_cast] protected theorem coe_neg (u : Ξ±Λ£) : (↑-u : Ξ±) = -u := rfl @[simp, norm_cast] protected theorem coe_neg_one : ((-1 : Ξ±Λ£) : Ξ±) = -1 := rfl instance : has_distrib_neg Ξ±Λ£ := units.ext.has_distrib_neg _ units.coe_neg units.coe_mul @[field_simps] lemma neg_divp (a : Ξ±) (u : Ξ±Λ£) : -(a /β‚š u) = (-a) /β‚š u := by simp only [divp, neg_mul] end has_distrib_neg section ring variables [ring Ξ±] {a b : Ξ±} @[field_simps] lemma divp_add_divp_same (a b : Ξ±) (u : Ξ±Λ£) : a /β‚š u + b /β‚š u = (a + b) /β‚š u := by simp only [divp, add_mul] @[field_simps] lemma divp_sub_divp_same (a b : Ξ±) (u : Ξ±Λ£) : a /β‚š u - b /β‚š u = (a - b) /β‚š u := by rw [sub_eq_add_neg, sub_eq_add_neg, neg_divp, divp_add_divp_same] @[field_simps] lemma add_divp (a b : Ξ±) (u : Ξ±Λ£) : a + b /β‚š u = (a * u + b) /β‚š u := by simp only [divp, add_mul, units.mul_inv_cancel_right] @[field_simps] lemma sub_divp (a b : Ξ±) (u : Ξ±Λ£) : a - b /β‚š u = (a * u - b) /β‚š u := by simp only [divp, sub_mul, units.mul_inv_cancel_right] @[field_simps] lemma divp_add (a b : Ξ±) (u : Ξ±Λ£) : a /β‚š u + b = (a + b * u) /β‚š u := by simp only [divp, add_mul, units.mul_inv_cancel_right] @[field_simps] lemma divp_sub (a b : Ξ±) (u : Ξ±Λ£) : a /β‚š u - b = (a - b * u) /β‚š u := begin simp only [divp, sub_mul, sub_right_inj], assoc_rw [units.mul_inv, mul_one], end end ring end units lemma is_unit.neg [monoid Ξ±] [has_distrib_neg Ξ±] {a : Ξ±} : is_unit a β†’ is_unit (-a) | ⟨x, hx⟩ := hx β–Έ (-x).is_unit @[simp] lemma is_unit.neg_iff [monoid Ξ±] [has_distrib_neg Ξ±] (a : Ξ±) : is_unit (-a) ↔ is_unit a := ⟨λ h, neg_neg a β–Έ h.neg, is_unit.neg⟩ lemma is_unit.sub_iff [ring Ξ±] {x y : Ξ±} : is_unit (x - y) ↔ is_unit (y - x) := (is_unit.neg_iff _).symm.trans $ neg_sub x y β–Έ iff.rfl namespace units @[field_simps] lemma divp_add_divp [comm_ring Ξ±] (a b : Ξ±) (u₁ uβ‚‚ : Ξ±Λ£) : a /β‚š u₁ + b /β‚š uβ‚‚ = (a * uβ‚‚ + u₁ * b) /β‚š (u₁ * uβ‚‚) := begin simp only [divp, add_mul, mul_inv_rev, coe_mul], rw [mul_comm (↑u₁ * b), mul_comm b], assoc_rw [mul_inv, mul_inv, mul_one, mul_one], end @[field_simps] lemma divp_sub_divp [comm_ring Ξ±] (a b : Ξ±) (u₁ uβ‚‚ : Ξ±Λ£) : (a /β‚š u₁) - (b /β‚š uβ‚‚) = ((a * uβ‚‚) - (u₁ * b)) /β‚š (u₁ * uβ‚‚) := by simp_rw [sub_eq_add_neg, neg_divp, divp_add_divp, mul_neg] lemma add_eq_mul_one_add_div [semiring R] {a : RΛ£} {b : R} : ↑a + b = a * (1 + ↑a⁻¹ * b) := by rwa [mul_add, mul_one, ← mul_assoc, units.mul_inv, one_mul] end units
359ceac22f0d7d3fd8b923a34a7636d9a892fa44
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/univ_problem.lean
08d91e52be3e1beee498c883b6ab6360f3bd9364
[ "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
3,104
lean
import logic data.nat.basic data.prod data.unit open nat prod inductive vector (A : Type) : nat β†’ Type := vnil {} : vector A zero, vcons : Ξ  {n : nat}, A β†’ vector A n β†’ vector A (succ n) namespace vector print definition no_confusion infixr `::` := vcons namespace play section universe variables l₁ lβ‚‚ variable {A : Type.{l₁}} variable {C : Ξ  (n : nat), vector A n β†’ Type.{lβ‚‚+1}} definition brec_on {n : nat} (v : vector A n) (H : Ξ  (n : nat) (v : vector A n), @below A C n v β†’ C n v) : C n v := have general : C n v Γ— @below A C n v, from rec_on v (pair (H zero vnil unit.star) unit.star) (Ξ» (n₁ : nat) (a₁ : A) (v₁ : vector A n₁) (r₁ : C n₁ v₁ Γ— @below A C n₁ v₁), have b : @below A C _ (vcons a₁ v₁), from r₁, have c : C (succ n₁) (vcons a₁ v₁), from H (succ n₁) (vcons a₁ v₁) b, pair c b), pr₁ general end end play print "=====================" definition append {A : Type} {n m : nat} (w : vector A m) (v : vector A n) : vector A (n + m) := brec_on w (Ξ» (n : nat) (w : vector A n), cases_on w (Ξ» (B : below vnil), v) (Ξ» (n₁ : nat) (a₁ : A) (v₁ : vector A n₁) (B : below (vcons a₁ v₁)), vcons a₁ (pr₁ B))) exit check brec_on definition bw := @below definition sum {n : nat} (v : vector nat n) : nat := brec_on v (Ξ» (n : nat) (v : vector nat n), cases_on v (Ξ» (B : bw vnil), zero) (Ξ» (n₁ : nat) (a : nat) (v₁ : vector nat n₁) (B : bw (vcons a v₁)), a + pr₁ B)) example : sum (10 :: 20 :: vnil) = 30 := rfl definition addk {n : nat} (v : vector nat n) (k : nat) : vector nat n := brec_on v (Ξ» (n : nat) (v : vector nat n), cases_on v (Ξ» (B : bw vnil), vnil) (Ξ» (n₁ : nat) (a₁ : nat) (v₁ : vector nat n₁) (B : bw (vcons a₁ v₁)), vcons (a₁+k) (pr₁ B))) example : addk (1 :: 2 :: vnil) 3 = 4 :: 5 :: vnil := rfl example : append (1 :: 2 :: vnil) (3 :: vnil) = 1 :: 2 :: 3 :: vnil := rfl definition head {A : Type} {n : nat} (v : vector A (succ n)) : A := cases_on v (Ξ» H : succ n = 0, nat.no_confusion H) (Ξ»n' h t (H : succ n = succ n'), h) rfl definition tail {A : Type} {n : nat} (v : vector A (succ n)) : vector A n := @cases_on A (Ξ»n' v, succ n = n' β†’ vector A (pred n')) (succ n) v (Ξ» H : succ n = 0, nat.no_confusion H) (Ξ» (n' : nat) (h : A) (t : vector A n') (H : succ n = succ n'), t) rfl definition add {n : nat} (w v : vector nat n) : vector nat n := @brec_on nat (Ξ» (n : nat) (v : vector nat n), vector nat n β†’ vector nat n) n w (Ξ» (n : nat) (w : vector nat n), cases_on w (Ξ» (B : bw vnil) (w : vector nat zero), vnil) (Ξ» (n₁ : nat) (a₁ : nat) (v₁ : vector nat n₁) (B : bw (vcons a₁ v₁)) (v : vector nat (succ n₁)), vcons (a₁ + head v) (pr₁ B (tail v)))) v example : add (1 :: 2 :: vnil) (3 :: 5 :: vnil) = 4 :: 7 :: vnil := rfl end vector
54e1063173201d6d89b5163b7a7b71b04377a252
6b9565799c5c4b76978fc138a9aa7becedecd541
/library/standard/nat.lean
e97127b5757c291a497085554c764afca048f3ea
[ "Apache-2.0" ]
permissive
leanparikshit/libraries
657c9c09723523592b1d2021496f6f8041659130
cbe08140e93fbde4cc81ef212fc65fbe357c5b59
refs/heads/master
1,586,305,043,220
1,401,535,624,000
1,401,535,624,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,911
lean
---------------------------------------------------------------------------------------------------- -- Copyright (c) 2014 Floris van Doorn. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Floris van Doorn ---------------------------------------------------------------------------------------------------- --TODO: --more about minus --replace positivity requirement (succ _ ==> _ > 0) -------------------------------------------------- axioms import kernel import macros variable nat : Type alias β„• : nat --builtin numeral -- When transitioning to numerals, first replace "(succ zero)" and "succ zero" by "1" and then "zero" by "0" (except in names) namespace nat variable zero : nat alias z : zero variable succ : nat -> nat alias s : succ axiom nat_rec {P : nat β†’ Type} (x : P zero) (f : βˆ€m : nat, P m β†’ P (s m)) (m:nat) : P m axiom nat_rec_zero {P : nat β†’ Type} (x : P zero) (f : βˆ€m : nat, P m β†’ P (s m)) : nat_rec x f zero = x axiom nat_rec_succ {P : nat β†’ Type} (x : P zero) (f : βˆ€m : nat, P m β†’ P (s m)) (n : nat) : nat_rec x f (succ n) = f n (nat_rec x f n) -------------------------------------------------- succ pred theorem induction_on {P : nat β†’ Bool} (a : nat) (H1 : P zero) (H2 : βˆ€ (n : nat) (IH : P n), P (succ n)) : P a := nat_rec H1 H2 a theorem succ_ne_zero (n : nat) : succ n β‰  zero := not_intro (take H : succ n = zero, have H2 : true = false, from (let f : nat -> Bool := (nat_rec false (fun a b,true)) in calc true = f (succ n) : symm (nat_rec_succ _ _ _) ... = f zero : {H} ... = false : nat_rec_zero _ _), absurd H2 true_ne_false) definition pred (n : nat) := nat_rec zero (fun m x, m) n theorem pred_zero : pred zero = zero := nat_rec_zero _ _ theorem pred_succ (n : nat) : pred (succ n) = n := nat_rec_succ _ _ _ set_opaque pred true theorem zero_or_succ (n : nat) : n = zero ∨ n = succ (pred n) := induction_on n (or_intro_left _ (refl zero)) (take m IH, or_intro_right _ (show succ m = succ (pred (succ m)), from congr2 succ (symm (pred_succ m)))) theorem zero_or_succ2 (n : nat) : n = zero ∨ βˆƒk, n = succ k := or_imp_or (zero_or_succ n) (assume H, H) (assume H : n = succ (pred n), exists_intro (pred n) H) theorem nat_case {P : nat β†’ Bool} (n : nat) (H1: P zero) (H2 : βˆ€m, P (succ m)) : P n := induction_on n H1 (take m IH, H2 m) theorem nat_discriminate {B : Bool} {n : nat} (H1: n = zero β†’ B) (H2 : βˆ€m, n = succ m β†’ B) : B := or_elim (zero_or_succ n) (take H3 : n = zero, H1 H3) (take H3 : n = succ (pred n), H2 (pred n) H3) theorem succ_inj {n m : nat} (H : succ n = succ m) : n = m := calc n = pred (succ n) : symm (pred_succ n) ... = pred (succ m) : {H} ... = m : pred_succ m theorem succ_ne_self (n : nat) : succ n β‰  n := not_intro (induction_on n (take H : succ zero = zero, have ne : succ zero β‰  zero, from succ_ne_zero zero, absurd H ne) (take k IH H, IH (succ_inj H))) theorem decidable_equality (n m : nat) : n = m ∨ n β‰  m := have general : βˆ€n, n = m ∨ n β‰  m, from induction_on m (take n : nat, nat_discriminate (assume H : n = zero, or_intro_left _ H) (take l : nat, assume H : n = succ l, have H2 : n β‰  zero, from subst (succ_ne_zero l) (symm H), or_intro_right _ H2)) (take k : nat, assume IH : βˆ€n, n = k ∨ n β‰  k, take n : nat, nat_discriminate (assume H : n = zero, have H2 : n β‰  succ k, from subst (ne_symm (succ_ne_zero k)) (symm H), or_intro_right _ H2) (take l : nat, assume H : n = succ l, or_imp_or (IH l) (take H2 : l = k, show n = succ k, from trans H (congr2 succ H2)) (take H2 : l β‰  k, show n β‰  succ k, from not_intro (take H4 : n = succ k, have H5 : succ l = succ k, from trans (symm H) H4, have H6 : l = k, from succ_inj H5, absurd H6 H2)))), general n theorem two_step_induction_on {P : nat β†’ Bool} (a : nat) (H1 : P zero) (H2 : P (succ zero)) (H3 : βˆ€ (n : nat) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : P a := have stronger : P a ∧ P (succ a), from induction_on a (and_intro H1 H2) (take k IH, have IH1 : P k, from and_elim_left IH, have IH2 : P (succ k), from and_elim_right IH, and_intro IH2 (H3 k IH1 IH2)), and_elim_left stronger --theorem nat_double_induction {P : nat β†’ nat β†’ Bool} (n m : nat) (H1 : βˆ€n, P zero n) -- (H2 : βˆ€n, P (succ n) zero) (H3 : βˆ€n m, P n m β†’ P (succ n) (succ m)) : P n m --:= _ -------------------------------------------------- add definition add (n m : nat) := nat_rec n (fun k x, succ x) m infixl 65 + : add theorem add_zero_right (n:nat) : n + zero = n := nat_rec_zero _ _ theorem add_succ_right (n m:nat) : n + succ m = succ (n + m) := nat_rec_succ _ _ _ set_opaque add true ---------- comm, assoc theorem add_zero_left (n:nat) : zero + n = n := induction_on n (add_zero_right zero) (take m IH, show zero + succ m = succ m, from calc zero + succ m = succ (zero + m) : add_succ_right _ _ ... = succ m : {IH}) theorem add_succ_left (n m:nat) : (succ n) + m = succ (n + m) := induction_on m (calc succ n + zero = succ n : add_zero_right (succ n) ... = succ (n + zero) : {symm (add_zero_right n)}) (take k IH, calc succ n + succ k = succ (succ n + k) : add_succ_right _ _ ... = succ (succ (n + k)) : {IH} ... = succ (n + succ k) : {symm (add_succ_right _ _)}) theorem add_comm (n m:nat) : n + m = m + n := induction_on m (trans (add_zero_right _) (symm (add_zero_left _))) (take k IH, calc n + succ k = succ (n+k) : add_succ_right _ _ ... = succ (k + n) : {IH} ... = succ k + n : symm (add_succ_left _ _)) theorem add_move_succ (n m:nat) : succ n + m = n + succ m := calc succ n + m = succ (n + m) : add_succ_left n m ... = n +succ m : symm (add_succ_right n m) theorem add_comm_succ (n m:nat) : n + succ m = m + succ n := calc n + succ m = succ n + m : symm (add_move_succ n m) ... = m + succ n : add_comm (succ n) m theorem add_assoc (n m k:nat) : (n + m) + k = n + (m + k) := induction_on k (calc (n + m) + zero = n + m : add_zero_right _ ... = n + (m + zero) : {symm (add_zero_right m)}) (take l IH, calc (n + m) + succ l = succ ((n + m) + l) : add_succ_right _ _ ... = succ (n + (m + l)) : {IH} ... = n + succ (m + l) : symm (add_succ_right _ _) ... = n + (m + succ l) : {symm (add_succ_right _ _)}) theorem add_comm_left (n m k : nat) : n + (m + k) = m + (n + k) := left_comm add_comm add_assoc n m k theorem add_comm_right (n m k : nat) : n + m + k = n + k + m := right_comm add_comm add_assoc n m k ---------- inversion theorem add_right_inj {n m k : nat} : n + m = n + k β†’ m = k := induction_on n (take H : zero + m = zero + k, calc m = zero + m : symm (add_zero_left m) ... = zero + k : H ... = k : add_zero_left k) (take (n : nat) (IH : n + m = n + k β†’ m = k) (H : succ n + m = succ n + k), have H2 : succ (n + m) = succ (n + k), from calc succ (n + m) = succ n + m : symm (add_succ_left n m) ... = succ n + k : H ... = succ (n + k) : add_succ_left n k, have H3 : n + m = n + k, from succ_inj H2, IH H3) theorem add_left_inj {n m k : nat} (H : n + m = k + m) : n = k := have H2 : m + n = m + k, from calc m + n = n + m : add_comm m n ... = k + m : H ... = m + k : add_comm k m, add_right_inj H2 theorem add_eq_zero_left {n m : nat} : n + m = zero β†’ n = zero := induction_on n (take (H : zero + m = zero), refl zero) (take k IH, assume (H : succ k + m = zero), absurd_elim (succ k = zero) (show succ (k + m) = zero, from calc succ (k + m) = succ k + m : symm (add_succ_left k m) ... = zero : H) (succ_ne_zero (k + m))) theorem add_eq_zero_right {n m : nat} (H : n + m = zero) : m = zero := add_eq_zero_left (trans (add_comm m n) H) theorem add_eq_zero {n m : nat} (H : n + m = zero) : n = zero ∧ m = zero := and_intro (add_eq_zero_left H) (add_eq_zero_right H) -- add_eq_self below ---------- misc theorem add_one (n:nat) : n + succ zero = succ n := calc n + succ zero = succ (n + zero) : add_succ_right _ _ ... = succ n : {add_zero_right _} theorem add_one_left (n:nat) : succ zero + n = succ n := calc succ zero + n = succ (zero + n) : add_succ_left _ _ ... = succ n : {add_zero_left _} --the following theorem has a terrible name, but since the name is not a substring or superstring of another name, it is at least easy to globally replace it theorem induction_plus_one {P : nat β†’ Bool} (a : nat) (H1 : P zero) (H2 : βˆ€ (n : nat) (IH : P n), P (n + succ zero)) : P a := nat_rec H1 (take n IH, subst (H2 n IH) (add_one n)) a -------------------------------------------------- mul definition mul (n m : nat) := nat_rec zero (fun m x, x + n) m infixl 70 * : mul theorem mul_zero_right (n:nat) : n * zero = zero := nat_rec_zero _ _ theorem mul_succ_right (n m:nat) : n * succ m = n * m + n := nat_rec_succ _ _ _ set_opaque mul true ---------- comm, distr, assoc, identity theorem mul_zero_left (n:nat) : zero * n = zero := induction_on n (mul_zero_right zero) (take m IH, calc zero * succ m = zero * m + zero : mul_succ_right _ _ ... = zero * m : add_zero_right _ ... = zero : IH) theorem mul_succ_left (n m:nat) : (succ n) * m = (n * m) + m := induction_on m (calc succ n * zero = zero : mul_zero_right _ ... = n * zero : symm (mul_zero_right _) ... = n * zero + zero : symm (add_zero_right _)) (take k IH, calc succ n * succ k = (succ n * k) + succ n : mul_succ_right _ _ ... = (n * k) + k + succ n : { IH } ... = (n * k) + (k + succ n) : add_assoc _ _ _ -- ... = (n * k) + succ (k + n) : {add_succ_right _ _} -- ... = (n * k) + (succ k + n) : {symm (add_succ_left _ _)} -- ... = (n * k) + (n + succ k) : {add_comm _ _} --use either next line or three previous lines ... = (n * k) + (n + succ k) : {add_comm_succ _ _} ... = (n * k) + n + succ k : symm (add_assoc _ _ _) ... = (n * succ k) + succ k : {symm (mul_succ_right n k)}) theorem mul_comm (n m:nat) : n * m = m * n := induction_on m (trans (mul_zero_right _) (symm (mul_zero_left _))) (take k IH, calc n * succ k = n * k + n : mul_succ_right _ _ ... = k * n + n : {IH} ... = (succ k) * n : symm (mul_succ_left _ _)) theorem mul_add_distr_left (n m k : nat) : (n + m) * k = n * k + m * k := induction_on k (calc (n + m) * zero = zero : mul_zero_right _ ... = zero + zero : symm (add_zero_right _) ... = n * zero + zero : {symm (mul_zero_right _)} ... = n * zero + m * zero : {symm (mul_zero_right _)}) (take l IH, calc (n + m) * succ l = (n + m) * l + (n + m) : mul_succ_right _ _ ... = n * l + m * l + (n + m) : {IH} ... = n * l + m * l + n + m : symm (add_assoc _ _ _) ... = n * l + n + m * l + m : {add_comm_right _ _ _} ... = n * l + n + (m * l + m) : add_assoc _ _ _ ... = n * succ l + (m * l + m) : {symm (mul_succ_right _ _)} ... = n * succ l + m * succ l : {symm (mul_succ_right _ _)}) theorem mul_add_distr_right (n m k : nat) : n * (m + k) = n * m + n * k := calc n * (m + k) = (m + k) * n : mul_comm _ _ ... = m * n + k * n : mul_add_distr_left _ _ _ ... = n * m + k * n : {mul_comm _ _} ... = n * m + n * k : {mul_comm _ _} theorem mul_assoc (n m k:nat) : (n * m) * k = n * (m * k) := induction_on k (calc (n * m) * zero = zero : mul_zero_right _ ... = n * zero : symm (mul_zero_right _) ... = n * (m * zero) : {symm (mul_zero_right _)}) (take l IH, calc (n * m) * succ l = (n * m) * l + n * m : mul_succ_right _ _ ... = n * (m * l) + n * m : {IH} ... = n * (m * l + m) : symm (mul_add_distr_right _ _ _) ... = n * (m * succ l) : {symm (mul_succ_right _ _)}) theorem mul_comm_left (n m k : nat) : n * (m * k) = m * (n * k) := left_comm mul_comm mul_assoc n m k theorem mul_comm_right (n m k : nat) : n * m * k = n * k * m := right_comm mul_comm mul_assoc n m k theorem mul_one_right (n : nat) : n * succ zero = n := calc n * succ zero = n * zero + n : mul_succ_right n zero ... = zero + n : {mul_zero_right n} ... = n : add_zero_left n theorem mul_one_left (n : nat) : succ zero * n = n := calc succ zero * n = n * succ zero : mul_comm _ _ ... = n : mul_one_right n ---------- inversion theorem mul_eq_zero {n m : nat} (H : n * m = zero) : n = zero ∨ m = zero := nat_discriminate (take Hn : n = zero, or_intro_left _ Hn) (take (k : nat), assume (Hk : n = succ k), nat_discriminate (take (Hm : m = zero), or_intro_right _ Hm) (take (l : nat), assume (Hl : m = succ l), have Heq : succ (k * succ l + l) = n * m, from symm (calc n * m = n * succ l : { Hl } ... = succ k * succ l : { Hk } ... = k * succ l + succ l : mul_succ_left _ _ ... = succ (k * succ l + l) : add_succ_right _ _), absurd_elim _ (trans Heq H) (succ_ne_zero _))) theorem mul_eq_succ_left {n m k : nat} (H : n * m = succ k) : exists l, n = succ l := nat_discriminate (assume H2 : n = zero, absurd_elim _ (calc succ k = n * m : symm H ... = zero * m : {H2} ... = zero : mul_zero_left m) (succ_ne_zero k)) (take l Hl, exists_intro l Hl) theorem mul_eq_succ_right {n m k : nat} (H : n * m = succ k) : exists l, m = succ l := mul_eq_succ_left (subst H (mul_comm n m)) theorem mul_left_inj {n m k : nat} (H : succ n * m = succ n * k) : m = k := have general : βˆ€ m, succ n * m = succ n * k β†’ m = k, from induction_on k (take m:nat, assume H : succ n * m = succ n * zero, have H2 : succ n * m = zero, from calc succ n * m = succ n * zero : H ... = zero : mul_zero_right (succ n), have H3 : succ n = zero ∨ m = zero, from mul_eq_zero H2, resolve_right H3 (succ_ne_zero n)) (take (l : nat), assume (IH : βˆ€ m, succ n * m = succ n * l β†’ m = l), take (m : nat), assume (H : succ n * m = succ n * succ l), have H2 : succ n * m = succ (succ n * l + n), from calc succ n * m = succ n * succ l : H ... = succ n * l + succ n : mul_succ_right (succ n) l ... = succ (succ n * l + n) : add_succ_right _ n, obtain (l2:nat) (Hm : m = succ l2), from mul_eq_succ_right H2, have H3 : succ n * l2 + succ n = succ n * l + succ n, from calc succ n * l2 + succ n = succ n * succ l2 : symm (mul_succ_right (succ n) l2) ... = succ n * m : {symm Hm} ... = succ n * succ l : H ... = succ n * l + succ n : mul_succ_right (succ n) l, have H4 : succ n * l2 = succ n * l, from add_left_inj H3, calc m = succ l2 : Hm ... = succ l : {IH l2 H4}), general m H theorem mul_right_inj {n m k : nat} (H : n * succ m = k * succ m) : n = k := have H2 : succ m * n = succ m * k, from calc succ m * n = n * succ m : mul_comm (succ m) n ... = k * succ m : H ... = succ m * k : mul_comm k (succ m), mul_left_inj H2 theorem mul_eq_one_left {n m : nat} (H : n * m = succ zero) : n = succ zero := obtain (k : nat) (Hm : m = succ k), from (mul_eq_succ_right H), obtain (l1 : nat) (Hn : n = succ l1), from (mul_eq_succ_left H), nat_discriminate (take Hl : l1 = zero, calc n = succ l1 : Hn ... = succ zero : {Hl}) (take (l2 : nat), assume (Hl : l1 = succ l2), have H2 : succ zero = succ (succ (succ (succ l2) * k + l2)), from calc succ zero = n * m : symm H ... = n * succ k : { Hm } ... = succ l1 * succ k : { Hn } ... = succ (succ l2) * succ k : { Hl } ... = succ (succ l2) * k + succ (succ l2) : { mul_succ_right _ _ } ... = succ (succ (succ l2) * k + succ l2): add_succ_right _ _ ... = succ (succ (succ (succ l2) * k + l2)) : { add_succ_right _ _ }, have H3 : zero = succ (succ (succ l2) * k + l2), from succ_inj H2, absurd_elim _ (symm H3) (succ_ne_zero _)) theorem mul_eq_one_right {n m : nat} (H : n * m = succ zero) : m = succ zero := mul_eq_one_left (subst H (mul_comm n m)) theorem mul_eq_one {n m : nat} (H : n * m = succ zero) : n = succ zero ∧ m = succ zero := and_intro (mul_eq_one_left H) (mul_eq_one_right H) -------------------------------------------------- le definition le (n m:nat) : Bool := exists k:nat, n + k = m infix 50 <= : le infix 50 ≀ : le theorem le_intro {n m k : nat} (H : n + k = m) : n ≀ m := exists_intro k H theorem le_elim {n m : nat} (H : n ≀ m) : βˆƒ k, n + k = m := H set_opaque le true ---------- partial order (totality is part of lt) theorem le_intro2 (n m : nat) : n ≀ n + m := le_intro (refl (n + m)) theorem le_refl (n : nat) : n ≀ n := le_intro (add_zero_right n) theorem le_zero (n : nat) : zero ≀ n := le_intro (add_zero_left n) theorem le_zero_inv {n:nat} (H : n ≀ zero) : n = zero := obtain (k : nat) (Hk : n + k = zero), from le_elim H, add_eq_zero_left Hk theorem le_trans {n m k : nat} (H1 : n ≀ m) (H2 : m ≀ k) : n ≀ k := obtain (l1 : nat) (Hl1 : n + l1 = m), from le_elim H1, obtain (l2 : nat) (Hl2 : m + l2 = k), from le_elim H2, le_intro (calc n + (l1 + l2) = n + l1 + l2 : symm (add_assoc n l1 l2) ... = m + l2 : { Hl1 } ... = k : Hl2) theorem le_antisym {n m : nat} (H1 : n ≀ m) (H2 : m ≀ n) : n = m := obtain (k : nat) (Hk : n + k = m), from (le_elim H1), obtain (l : nat) (Hl : m + l = n), from (le_elim H2), have L1 : k + l = zero, from add_right_inj (calc n + (k + l) = n + k + l : { symm (add_assoc n k l) } ... = m + l : { Hk } ... = n : Hl ... = n + zero : symm (add_zero_right n)), have L2 : k = zero, from add_eq_zero_left L1, calc n = n + zero : symm (add_zero_right n) ... = n + k : { symm L2 } ... = m : Hk ---------- interaction with add theorem add_le_left {n m : nat} (H : n ≀ m) (k : nat) : k + n ≀ k + m := obtain (l : nat) (Hl : n + l = m), from (le_elim H), le_intro (calc k + n + l = k + (n + l) : add_assoc k n l ... = k + m : { Hl }) theorem add_le_right {n m : nat} (H : n ≀ m) (k : nat) : n + k ≀ m + k := subst (subst (add_le_left H k) (add_comm k n)) (add_comm k m) theorem add_le {n m k l : nat} (H1 : n ≀ k) (H2 : m ≀ l) : n + m ≀ k + l := le_trans (add_le_right H1 m) (add_le_left H2 k) theorem add_le_left_inv {n m k : nat} (H : k + n ≀ k + m) : n ≀ m := obtain (l : nat) (Hl : k + n + l = k + m), from (le_elim H), le_intro (add_right_inj calc k + (n + l) = k + n + l : symm (add_assoc k n l) ... = k + m : Hl ) theorem add_le_right_inv {n m k : nat} (H : n + k ≀ m + k) : n ≀ m := add_le_left_inv (subst (subst H (add_comm n k)) (add_comm m k)) ---------- interaction with succ and pred theorem succ_le {n m : nat} (H : n ≀ m) : succ n ≀ succ m := subst (subst (add_le_right H (succ zero)) (add_one n)) (add_one m) theorem succ_le_inv {n m : nat} (H : succ n ≀ succ m) : n ≀ m := add_le_right_inv (subst (subst H (symm (add_one n))) (symm (add_one m))) theorem le_self_succ (n : nat) : n ≀ succ n := le_intro (add_one n) theorem succ_le_right {n m : nat} (H : n ≀ m) : n ≀ succ m := le_trans H (le_self_succ m) theorem succ_le_left_or {n m : nat} (H : n ≀ m) : succ n ≀ m ∨ n = m := obtain (k : nat) (Hk : n + k = m), from (le_elim H), nat_discriminate (assume H3 : k = zero, have Heq : n = m, from calc n = n + zero : symm (add_zero_right n) ... = n + k : {symm H3} ... = m : Hk, or_intro_right _ Heq) (take l:nat, assume H3 : k = succ l, have Hlt : succ n ≀ m, from (le_intro (calc succ n + l = n + succ l : add_move_succ n l ... = n + k : {symm H3} ... = m : Hk)), or_intro_left _ Hlt) theorem succ_le_left {n m : nat} (H1 : n ≀ m) (H2 : n β‰  m) : succ n ≀ m := resolve_left (succ_le_left_or H1) H2 theorem succ_le_right_inv {n m : nat} (H : n ≀ succ m) : n ≀ m ∨ n = succ m := or_imp_or (succ_le_left_or H) (take H2 : succ n ≀ succ m, show n ≀ m, from succ_le_inv H2) (take H2 : n = succ m, H2) theorem succ_le_left_inv {n m : nat} (H : succ n ≀ m) : n ≀ m ∧ n β‰  m := obtain (k : nat) (H2 : succ n + k = m), from (le_elim H), and_intro (have H3 : n + succ k = m, from calc n + succ k = succ n + k : symm (add_move_succ n k) ... = m : H2, show n ≀ m, from le_intro H3) (not_intro (assume H3 : n = m, have H4 : succ n ≀ n, from subst H (symm H3), have H5 : succ n = n, from le_antisym H4 (le_self_succ n), show false, from absurd H5 (succ_ne_self n))) theorem le_pred_self (n : nat) : pred n ≀ n := nat_case n (subst (le_refl zero) (symm pred_zero)) (take k : nat, subst (le_self_succ k) (symm (pred_succ k))) theorem pred_le {n m : nat} (H : n ≀ m) : pred n ≀ pred m := nat_discriminate (take Hn : n = zero, have H2 : pred n = zero, from calc pred n = pred zero : {Hn} ... = zero : pred_zero, subst (le_zero (pred m)) (symm H2)) (take k : nat, assume Hn : n = succ k, obtain (l : nat) (Hl : n + l = m), from le_elim H, have H2 : pred n + l = pred m, from calc pred n + l = pred (succ k) + l : {Hn} ... = k + l : {pred_succ k} ... = pred (succ (k + l)) : symm (pred_succ (k + l)) ... = pred (succ k + l) : {symm (add_succ_left k l)} ... = pred (n + l) : {symm Hn} ... = pred m : {Hl}, le_intro H2) theorem pred_le_left_inv {n m : nat} (H : pred n ≀ m) : n ≀ m ∨ n = succ m := nat_discriminate (take Hn : n = zero, or_intro_left _ (subst (le_zero m) (symm Hn))) (take k : nat, assume Hn : n = succ k, have H2 : pred n = k, from calc pred n = pred (succ k) : {Hn} ... = k : pred_succ k, have H3 : k ≀ m, from subst H H2, have H4 : succ k ≀ m ∨ k = m, from succ_le_left_or H3, show n ≀ m ∨ n = succ m, from or_imp_or H4 (take H5 : succ k ≀ m, show n ≀ m, from subst H5 (symm Hn)) (take H5 : k = m, show n = succ m, from subst Hn H5)) ---------- interaction with mul theorem mul_le_left {n m : nat} (H : n ≀ m) (k : nat) : k * n ≀ k * m := obtain (l : nat) (Hl : n + l = m), from (le_elim H), induction_on k (have H2 : zero * n = zero * m, from calc zero * n = zero : mul_zero_left n ... = zero * m : symm (mul_zero_left m), show zero * n ≀ zero * m, from subst (le_refl (zero * n)) H2) (take (l : nat), assume IH : l * n ≀ l * m, have H2 : l * n + n ≀ l * m + m, from add_le IH H, have H3 : succ l * n ≀ l * m + m, from subst H2 (symm (mul_succ_left l n)), show succ l * n ≀ succ l * m, from subst H3 (symm (mul_succ_left l m))) theorem mul_le_right {n m : nat} (H : n ≀ m) (k : nat) : n * k ≀ m * k := subst (subst (mul_le_left H k) (mul_comm k n)) (mul_comm k m) theorem mul_le {n m k l : nat} (H1 : n ≀ k) (H2 : m ≀ l) : n * m ≀ k * l := le_trans (mul_le_right H1 m) (mul_le_left H2 k) -- mul_le_[left|right]_inv below -------------------------------------------------- lt definition lt (n m : nat) := succ n ≀ m infix 50 < : lt theorem lt_intro {n m k : nat} (H : succ n + k = m) : n < m := le_intro H theorem lt_elim {n m : nat} (H : n < m) : βˆƒ k, succ n + k = m := le_elim H theorem lt_intro2 (n m : nat) : n < n + succ m := lt_intro (add_move_succ n m) ---------- basic facts theorem lt_ne {n m : nat} (H : n < m) : n β‰  m := and_elim_right (succ_le_left_inv H) theorem lt_irrefl (n : nat) : Β¬ n < n := not_intro (assume H : n < n, absurd (refl n) (lt_ne H)) theorem lt_zero (n : nat) : zero < succ n := succ_le (le_zero n) theorem lt_zero_inv (n : nat) : Β¬ n < zero := not_intro (assume H : n < zero, have H2 : succ n = zero, from le_zero_inv H, absurd H2 (succ_ne_zero n)) theorem lt_positive {n m : nat} (H : n < m) : exists k, m = succ k := nat_discriminate (take (Hm : m = zero), absurd_elim _ (subst H Hm) (lt_zero_inv n)) (take (l : nat) (Hm : m = succ l), exists_intro l Hm) ---------- interaction with le theorem lt_le_succ {n m : nat} (H : n < m) : succ n ≀ m := H theorem le_succ_lt {n m : nat} (H : succ n ≀ m) : n < m := H theorem lt_le {n m : nat} (H : n < m) : n ≀ m := and_elim_left (succ_le_left_inv H) theorem le_lt_or {n m : nat} (H : n ≀ m) : n < m ∨ n = m := succ_le_left_or H theorem le_lt {n m : nat} (H1 : n ≀ m) (H2 : n β‰  m) : n < m := succ_le_left H1 H2 theorem le_lt_succ {n m : nat} (H : n ≀ m) : n < succ m := succ_le H theorem lt_succ_le {n m : nat} (H : n < succ m) : n ≀ m := succ_le_inv H ---------- trans, antisym theorem lt_le_trans {n m k : nat} (H1 : n < m) (H2 : m ≀ k) : n < k := le_trans H1 H2 theorem lt_trans {n m k : nat} (H1 : n < m) (H2 : m < k) : n < k := lt_le_trans H1 (lt_le H2) theorem le_lt_trans {n m k : nat} (H1 : n ≀ m) (H2 : m < k) : n < k := le_trans (succ_le H1) H2 theorem lt_antisym {n m : nat} (H : n < m) : Β¬ m < n := not_intro (take H2 : m < n, absurd (lt_trans H H2) (lt_irrefl n)) ---------- interaction with add theorem add_lt_left {n m : nat} (H : n < m) (k : nat) : k + n < k + m := @subst _ _ _ (fun x, x ≀ k + m) (add_le_left H k) (add_succ_right k n) theorem add_lt_right {n m : nat} (H : n < m) (k : nat) : n + k < m + k := subst (subst (add_lt_left H k) (add_comm k n)) (add_comm k m) theorem add_le_lt {n m k l : nat} (H1 : n ≀ k) (H2 : m < l) : n + m < k + l := le_lt_trans (add_le_right H1 m) (add_lt_left H2 k) theorem add_lt_le {n m k l : nat} (H1 : n < k) (H2 : m ≀ l) : n + m < k + l := lt_le_trans (add_lt_right H1 m) (add_le_left H2 k) theorem add_lt {n m k l : nat} (H1 : n < k) (H2 : m < l) : n + m < k + l := add_lt_le H1 (lt_le H2) theorem add_lt_left_inv {n m k : nat} (H : k + n < k + m) : n < m := add_le_left_inv (subst H (symm (add_succ_right k n))) theorem add_lt_right_inv {n m k : nat} (H : n + k < m + k) : n < m := add_lt_left_inv (subst (subst H (add_comm n k)) (add_comm m k)) ---------- interaction with succ (see also the interaction with le) theorem succ_lt {n m : nat} (H : n < m) : succ n < succ m := subst (subst (add_lt_right H (succ zero)) (add_one n)) (add_one m) theorem succ_lt_inv {n m : nat} (H : succ n < succ m) : n < m := add_lt_right_inv (subst (subst H (symm (add_one n))) (symm (add_one m))) theorem lt_self_succ (n : nat) : n < succ n := le_refl (succ n) theorem succ_lt_right {n m : nat} (H : n < m) : n < succ m := lt_trans H (lt_self_succ m) ---------- totality of lt and le theorem le_or_lt (n m : nat) : n ≀ m ∨ m < n := induction_on n (or_intro_left _ (le_zero m)) (take (k : nat), assume IH : k ≀ m ∨ m < k, or_elim IH (assume H : k ≀ m, obtain (l : nat) (Hl : k + l = m), from le_elim H, nat_discriminate (assume H2 : l = zero, have H3 : m = k, from calc m = k + l : symm Hl ... = k + zero : {H2} ... = k : add_zero_right k, have H4 : m < succ k, from subst (lt_self_succ m) H3, or_intro_right _ H4) (take l2 : nat, assume H2 : l = succ l2, have H3 : succ k + l2 = m, from calc succ k + l2 = k + succ l2 : add_move_succ k l2 ... = k + l : {symm H2} ... = m : Hl, or_intro_left _ (le_intro H3))) (assume H : m < k, or_intro_right _ (succ_lt_right H))) theorem trichotomy_alt (n m : nat) : (n < m ∨ n = m) ∨ m < n := or_imp_or (le_or_lt n m) (assume H : n ≀ m, le_lt_or H) (assume H : m < n, H) theorem trichotomy (n m : nat) : n < m ∨ n = m ∨ m < n := iff_elim_left (or_assoc _ _ _) (trichotomy_alt n m) theorem le_total (n m : nat) : n ≀ m ∨ m ≀ n := or_imp_or (le_or_lt n m) (assume H : n ≀ m, H) (assume H : m < n, lt_le H) ---------- interaction with mul theorem mul_lt_left {n m : nat} (H : n < m) (k : nat) : succ k * n < succ k * m := have H2 : succ k * n < succ k * n + succ k, from lt_intro2 _ _, have H3 : succ k * n + succ k ≀ succ k * m, from subst (mul_le_left H (succ k)) (mul_succ_right (succ k) n), lt_le_trans H2 H3 theorem mul_lt_right {n m : nat} (H : n < m) (k : nat) : n * succ k < m * succ k := subst (subst (mul_lt_left H k) (mul_comm (succ k) n)) (mul_comm (succ k) m) theorem mul_le_lt {n m k l : nat} (H1 : n ≀ succ k) (H2 : m < l) : n * m < succ k * l := le_lt_trans (mul_le_right H1 m) (mul_lt_left H2 k) theorem mul_lt_le {n m k l : nat} (H1 : n < k) (H2 : m ≀ succ l) : n * m < k * succ l := le_lt_trans (mul_le_left H2 n) (mul_lt_right H1 l) theorem mul_lt {n m k l : nat} (H1 : n < k) (H2 : m < l) : n * m < k * l := obtain (k2 : nat) (Hk : k = succ k2), from lt_positive H1, have H3 : n * m ≀ k * m, from mul_le_right (lt_le H1) m, have H4 : k * m < k * l, from subst (mul_lt_left H2 k2) (symm Hk), le_lt_trans H3 H4 theorem mul_lt_left_inv {n m k : nat} (H : k * n < k * m) : n < m := have general : βˆ€ m, k * n < k * m β†’ n < m, from induction_on n (take m : nat, assume H2 : k * zero < k * m, obtain (l : nat) (Hl : k * m = succ l), from lt_positive H2, obtain (l2 : nat) (Hl2 : m = succ l2), from mul_eq_succ_right Hl, show zero < m, from subst (lt_zero l2) (symm Hl2)) (take l : nat, assume IH : βˆ€ m, k * l < k * m β†’ l < m, take m : nat, assume H2 : k * succ l < k * m, obtain (l' : nat) (Hl : k * m = succ l'), from lt_positive H2, obtain (l2 : nat) (Hl2 : m = succ l2), from mul_eq_succ_right Hl, have H3 : k * l + k < k * m, from subst H2 (mul_succ_right k l), have H4 : k * l + k < k * succ l2, from subst H3 Hl2, have H5 : k * l + k < k * l2 + k, from subst H4 (mul_succ_right k l2), have H6 : k * l < k * l2, from add_lt_right_inv H5, have H7 : l < l2, from IH l2 H6, have H8 : succ l < succ l2, from succ_lt H7, show succ l < m, from subst H8 (symm Hl2)), general m H theorem mul_lt_right_inv {n m k : nat} (H : n * k < m * k) : n < m := mul_lt_left_inv (subst (subst H (mul_comm n k)) (mul_comm m k)) theorem mul_le_left_inv {n m k : nat} (H : succ k * n ≀ succ k * m) : n ≀ m := have H2 : succ k * n < succ k * m + succ k, from le_lt_trans H (lt_intro2 _ _), have H3 : succ k * n < succ k * succ m, from subst H2 (symm (mul_succ_right (succ k) m)), have H4 : n < succ m, from mul_lt_left_inv H3, show n ≀ m, from lt_succ_le H4 theorem mul_le_right_inv {n m k : nat} (H : n * succ m ≀ k * succ m) : n ≀ k := mul_le_left_inv (subst (subst H (mul_comm n (succ m))) (mul_comm k (succ m))) theorem strong_induction {P : nat β†’ Bool} (n : nat) (IH : βˆ€n, (βˆ€m, m < n β†’ P m) β†’ P n) : P n := have stronger : βˆ€k, k ≀ n β†’ P k, from induction_on n (take (k : nat), assume H : k ≀ zero, have H2 : k = zero, from le_zero_inv H, have H3 : βˆ€m, m < k β†’ P m, from (take m : nat, assume H4 : m < k, have H5 : m < zero, from subst H4 H2, absurd_elim _ H5 (lt_zero_inv m)), show P k, from IH k H3) (take l : nat, assume IHl : βˆ€k, k ≀ l β†’ P k, take k : nat, assume H : k ≀ succ l, or_elim (succ_le_right_inv H) (assume H2 : k ≀ l, show P k, from IHl k H2) (assume H2 : k = succ l, have H3 : βˆ€m, m < k β†’ P m, from (take m : nat, assume H4 : m < k, have H5 : m ≀ l, from lt_succ_le (subst H4 H2), show P m, from IHl m H5), show P k, from IH k H3)), stronger n (le_refl n) theorem add_eq_self {n m : nat} (H : n + m = n) : m = zero := nat_discriminate (take Hm : m = zero, Hm) (take k : nat, assume Hm : m = succ k, have H2 : succ n + k = n, from calc succ n + k = n + succ k : add_move_succ n k ... = n + m : {symm Hm} ... = n : H, have H3 : n < n, from lt_intro H2, have H4 : n β‰  n, from lt_ne H3, absurd_elim _ (refl n) H4) set_opaque lt true -------------------------------------------------- ge, gt definition ge (n m : nat) := m ≀ n infix 50 >= : ge infix 50 β‰₯ : ge definition gt (n m : nat) := m < n infix 50 > : gt -- prove some theorems, like ge_le le_ge lt_gt gt_lt -------------------------------------------------- minus definition minus (n m : nat) : nat := nat_rec n (fun m x, pred x) m infixl 65 - : minus theorem minus_zero_right (n : nat) : n - zero = n := nat_rec_zero _ _ theorem minus_succ_right (n m : nat) : n - succ m = pred (n - m) := nat_rec_succ _ _ _ set_opaque minus true theorem minus_zero_left (n : nat) : zero - n = zero := induction_on n (minus_zero_right zero) (take k : nat, assume IH : zero - k = zero, calc zero - succ k = pred (zero - k) : minus_succ_right zero k ... = pred zero : {IH} ... = zero : pred_zero) --theorem minus_succ_left (n m : nat) : pred (succ n - m) = n - m -- := -- induction_on m -- (calc -- pred (succ n - zero) = pred (succ n) : {minus_zero_right (succ n)} -- ... = n : pred_succ n -- ... = n - zero : symm (minus_zero_right n)) -- (take k : nat, -- assume IH : pred (succ n - k) = n - k, -- _) theorem minus_succ_succ (n m : nat) : succ n - succ m = n - m := induction_on m (calc succ n - succ zero = pred (succ n - zero) : minus_succ_right (succ n) zero ... = pred (succ n) : {minus_zero_right (succ n)} ... = n : pred_succ n ... = n - zero : symm (minus_zero_right n)) (take k : nat, assume IH : succ n - succ k = n - k, calc succ n - succ (succ k) = pred (succ n - succ k) : minus_succ_right (succ n) (succ k) ... = pred (n - k) : {IH} ... = n - succ k : symm (minus_succ_right n k)) theorem minus_one (n : nat) : n - succ zero = pred n := calc n - succ zero = pred (n - zero) : minus_succ_right n zero ... = pred n : {minus_zero_right n} theorem minus_self (n : nat) : n - n = zero := induction_on n (minus_zero_right zero) (take k IH, trans (minus_succ_succ k k) IH) theorem minus_add_add_right (n m k : nat) : (n + k) - (m + k) = n - m := induction_on k (calc (n + zero) - (m + zero) = n - (m + zero) : {add_zero_right _} ... = n - m : {add_zero_right _}) (take l : nat, assume IH : (n + l) - (m + l) = n - m, calc (n + succ l) - (m + succ l) = succ (n + l) - (m + succ l) : {add_succ_right _ _} ... = succ (n + l) - succ (m + l) : {add_succ_right _ _} ... = (n + l) - (m + l) : minus_succ_succ _ _ ... = n - m : IH) theorem minus_add_add_left (n m k : nat) : (k + n) - (k + m) = n - m := subst (subst (minus_add_add_right n m k) (add_comm n k)) (add_comm m k) theorem minus_add_left (n m : nat) : n + m - m = n := induction_on m (subst (minus_zero_right n) (symm (add_zero_right n))) (take k : nat, assume IH : n + k - k = n, calc n + succ k - succ k = succ (n + k) - succ k : {add_succ_right n k} ... = n + k - k : minus_succ_succ _ _ ... = n : IH) theorem minus_minus (n m k : nat) : n - m - k = n - (m + k) := induction_on k (calc n - m - zero = n - m : minus_zero_right _ ... = n - (m + zero) : {symm (add_zero_right m)}) (take l : nat, assume IH : n - m - l = n - (m + l), calc n - m - succ l = pred (n - m - l) : minus_succ_right (n - m) l ... = pred (n - (m + l)) : {IH} ... = n - succ (m + l) : symm (minus_succ_right n (m + l)) ... = n - (m + succ l) : {symm (add_succ_right m l)}) theorem succ_minus_minus (n m k : nat) : succ n - m - succ k = n - m - k := calc succ n - m - succ k = succ n - (m + succ k) : minus_minus _ _ _ ... = succ n - succ (m + k) : {add_succ_right m k} ... = n - (m + k) : minus_succ_succ _ _ ... = n - m - k : symm (minus_minus n m k) theorem minus_add_right (n m : nat) : n - (n + m) = zero := calc n - (n + m) = n - n - m : symm (minus_minus n n m) ... = zero - m : {minus_self n} ... = zero : minus_zero_left m theorem minus_comm (m n k : nat) : m - n - k = m - k - n := calc m - n - k = m - (n + k) : minus_minus m n k ... = m - (k + n) : {add_comm n k} ... = m - k - n : symm (minus_minus m k n) theorem succ_minus_one (n : nat) : succ n - succ zero = n := trans (minus_succ_succ n zero) (minus_zero_right n) ---------- mul theorem mul_pred_left (n m : nat) : pred n * m = n * m - m := induction_on n (calc pred zero * m = zero * m : {pred_zero} ... = zero : mul_zero_left _ ... = zero - m : symm (minus_zero_left m) ... = zero * m - m : {symm (mul_zero_left m)}) (take k : nat, assume IH : pred k * m = k * m - m, calc pred (succ k) * m = k * m : {pred_succ k} ... = k * m + m - m : symm (minus_add_left _ _) ... = succ k * m - m : {symm (mul_succ_left k m)}) theorem mul_pred_right (n m : nat) : n * pred m = n * m - n := calc n * pred m = pred m * n : mul_comm _ _ ... = m * n - n : mul_pred_left m n ... = n * m - n : {mul_comm m n} theorem mul_minus_distr_left (n m k : nat) : (n - m) * k = n * k - m * k := induction_on m (calc (n - zero) * k = n * k : {minus_zero_right n} ... = n * k - zero : symm (minus_zero_right _) ... = n * k - zero * k : {symm (mul_zero_left _)}) (take l : nat, assume IH : (n - l) * k = n * k - l * k, calc (n - succ l) * k = pred (n - l) * k : {minus_succ_right n l} ... = (n - l) * k - k : mul_pred_left _ _ ... = n * k - l * k - k : {IH} ... = n * k - (l * k + k) : minus_minus _ _ _ ... = n * k - (succ l * k) : {symm (mul_succ_left l k)}) theorem mul_minus_distr_right (n m k : nat) : n * (m - k) = n * m - n * k := calc n * (m - k) = (m - k) * n : mul_comm _ _ ... = m * n - k * n : mul_minus_distr_left _ _ _ ... = n * m - k * n : {mul_comm _ _} ... = n * m - n * k : {mul_comm _ _} -------------------------------------------------- max, min, iteration, maybe: minus, div -- n - m + m = max n m end --namespace nat
a1b2252d7ab4658c849bf249200df97e5aa9ddb9
8cd68b0e4eb405ef573e16a6d92dcbcdb92d1c29
/library/init/meta/level.lean
aa56420cac34b431afb31ef1fe8c19d87dcd78b7
[ "Apache-2.0" ]
permissive
ratmice/lean
5d7a7bbaa652899941fe73dff2154ddc5ab2f20a
139ac0d773dbf0f54cc682612bf8f02297c211dd
refs/heads/master
1,590,259,859,627
1,557,951,491,000
1,558,099,319,000
186,896,142
0
0
Apache-2.0
1,557,951,143,000
1,557,951,143,000
null
UTF-8
Lean
false
false
2,144
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.name init.meta.format /-- A type universe term. eg `max u v`. Reflect a C++ level object. The VM replaces it with the C++ implementation. -/ meta inductive level | zero : level | succ : level β†’ level | max : level β†’ level β†’ level | imax : level β†’ level β†’ level | param : name β†’ level | mvar : name β†’ level meta instance : inhabited level := ⟨level.zero⟩ /- TODO(Leo): provide a definition in Lean. -/ meta constant level.has_decidable_eq : decidable_eq level attribute [instance] level.has_decidable_eq meta constant level.lt : level β†’ level β†’ bool meta constant level.lex_lt : level β†’ level β†’ bool meta constant level.fold {Ξ± :Type} : level β†’ Ξ± β†’ (level β†’ Ξ± β†’ Ξ±) β†’ Ξ± /-- Return the given level expression normal form -/ meta constant level.normalize : level β†’ level /-- Return tt iff lhs and rhs denote the same level. The check is done by normalization. -/ meta constant level.eqv : level β†’ level β†’ bool /-- Return tt iff the first level occurs in the second -/ meta constant level.occurs : level β†’ level β†’ bool /-- Replace a parameter named n with l in the first level if the list contains the pair (n, l) -/ meta constant level.instantiate : level β†’ list (name Γ— level) β†’ list level meta constant level.to_format : level β†’ options β†’ format meta constant level.to_string : level β†’ string meta instance : has_to_string level := ⟨level.to_string⟩ meta instance : has_to_format level := ⟨λ l, level.to_format l options.mk⟩ meta def level.of_nat : nat β†’ level | 0 := level.zero | (nat.succ n) := level.succ (level.of_nat n) meta def level.has_param : level β†’ name β†’ bool | (level.succ l) n := level.has_param l n | (level.max l₁ lβ‚‚) n := level.has_param l₁ n || level.has_param lβ‚‚ n | (level.imax l₁ lβ‚‚) n := level.has_param l₁ n || level.has_param lβ‚‚ n | (level.param n₁) n := n₁ = n | l n := ff
c99bc1efab79a9459e494ad44af471e66ff08714
7850aae797be6c31052ce4633d86f5991178d3df
/stage0/src/Lean/Elab/Do.lean
66961b5d789f3b45722ce76820f9ff87366ec2b7
[ "Apache-2.0" ]
permissive
miriamgoetze/lean4
4dc24d4dbd360cc969713647c2958c6691947d16
062cc5d5672250be456a168e9c7b9299a9c69bdb
refs/heads/master
1,685,865,971,011
1,624,107,703,000
1,624,107,703,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
69,607
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.Elab.Term import Lean.Elab.Binders import Lean.Elab.Match import Lean.Elab.Quotation.Util import Lean.Parser.Do namespace Lean.Elab.Term open Lean.Parser.Term open Meta private def getDoSeqElems (doSeq : Syntax) : List Syntax := if doSeq.getKind == `Lean.Parser.Term.doSeqBracketed then doSeq[1].getArgs.toList.map fun arg => arg[0] else if doSeq.getKind == `Lean.Parser.Term.doSeqIndent then doSeq[0].getArgs.toList.map fun arg => arg[0] else [] private def getDoSeq (doStx : Syntax) : Syntax := doStx[1] @[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ => throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression" /-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/ private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool := k == ``Lean.Parser.Term.do || k == ``Lean.Parser.Term.doSeqIndent || k == ``Lean.Parser.Term.doSeqBracketed || k == ``Lean.Parser.Term.termReturn || k == ``Lean.Parser.Term.termUnless || k == ``Lean.Parser.Term.termTry || k == ``Lean.Parser.Term.termFor /-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/ private def letDeclArgHasBinders (letDeclArg : Syntax) : Bool := let k := letDeclArg.getKind if k == ``Lean.Parser.Term.letPatDecl then false else if k == ``Lean.Parser.Term.letEqnsDecl then true else if k == ``Lean.Parser.Term.letIdDecl then -- letIdLhs := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType let binders := letDeclArg[1] binders.getNumArgs > 0 else false /-- Return `true` if the given `letDecl` contains binders. -/ private def letDeclHasBinders (letDecl : Syntax) : Bool := letDeclArgHasBinders letDecl[0] /-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/ private def liftMethodForbiddenBinder (stx : Syntax) : Bool := let k := stx.getKind if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts || k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec then -- It is never ok to lift over this kind of binder true -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not else if k == ``Lean.Parser.Term.let then letDeclHasBinders stx[1] else if k == ``Lean.Parser.Term.doLet then letDeclHasBinders stx[2] else if k == ``Lean.Parser.Term.doLetArrow then letDeclArgHasBinders stx[2] else false private partial def hasLiftMethod : Syntax β†’ Bool | Syntax.node k args => if liftMethodDelimiter k then false -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a -- bit slower else if k == `Lean.Parser.Term.liftMethod then true else args.any hasLiftMethod | _ => false structure ExtractMonadResult where m : Expr Ξ± : Expr hasBindInst : Expr expectedType : Expr private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do let u ← getDecLevel type let id := Lean.mkConst `Id [u] let idBindVal := Lean.mkConst `Id.hasBind [u] pure { m := id, hasBindInst := idBindVal, Ξ± := type, expectedType := mkApp id type } private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do match expectedType? with | none => throwError "invalid 'do' notation, expected type is not available" | some expectedType => let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do match type with | Expr.app m Ξ± _ => try let bindInstType ← mkAppM `Bind #[m] let bindInstVal ← Meta.synthInstance bindInstType return some { m := m, hasBindInst := bindInstVal, Ξ± := Ξ±, expectedType := expectedType } catch _ => return none | _ => return none let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do match (← extractStep? type) with | some r => return r | none => let typeNew ← whnfCore type if typeNew != type then extract? typeNew else if typeNew.getAppFn.isMVar then throwError "invalid 'do' notation, expected type is not available" match (← unfoldDefinition? typeNew) with | some typeNew => extract? typeNew | none => return none match (← extract? expectedType) with | some r => return r | none => mkIdBindFor expectedType namespace Do /- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/ structure Alt (Οƒ : Type) where ref : Syntax vars : Array Name patterns : Syntax rhs : Οƒ deriving Inhabited /- Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`). We convert `Code` into a `Syntax` term representing the: - `do`-block, or - the visitor argument for the `forIn` combinator. We say the following constructors are terminals: - `break`: for interrupting a `for x in s` - `continue`: for interrupting the current iteration of a `for x in s` - `return e`: for returning `e` as the result for the whole `do` computation block - `action a`: for executing action `a` as a terminal - `ite`: if-then-else - `match`: pattern matching - `jmp` a goto to a join-point We say the terminals `break`, `continue`, `action`, and `return` are "exit points" Note that, `return e` is not equivalent to `action (pure e)`. Here is an example: ``` def f (x : Nat) : IO Unit := do if x == 0 then return () IO.println "hello" ``` Executing `#eval f 0` will not print "hello". Now, consider ``` def g (x : Nat) : IO Unit := do if x == 0 then pure () IO.println "hello" ``` The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`. - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`). The field `stx` is the actual `doElem`, `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block. `vars` is an array since we have declarations such as `let (a, b) := s`. - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`). - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow. - `seq a k` executes action `a`, ignores its result, and then executes `k`. We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`. A code block `C` is well-formed if - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and `ps.size == as.size` -/ inductive Code where | decl (xs : Array Name) (doElem : Syntax) (k : Code) | reassign (xs : Array Name) (doElem : Syntax) (k : Code) /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/ | joinpoint (name : Name) (params : Array (Name Γ— Bool)) (body : Code) (k : Code) | seq (action : Syntax) (k : Code) | action (action : Syntax) | Β«breakΒ» (ref : Syntax) | Β«continueΒ» (ref : Syntax) | Β«returnΒ» (ref : Syntax) (val : Syntax) /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/ | ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code) | Β«matchΒ» (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code)) | jmp (ref : Syntax) (jpName : Name) (args : Array Syntax) deriving Inhabited /- A code block, and the collection of variables updated by it. -/ structure CodeBlock where code : Code uvars : NameSet := {} -- set of variables updated by `code` private def nameSetToArray (s : NameSet) : Array Name := s.fold (fun (xs : Array Name) x => xs.push x) #[] private def varsToMessageData (vars : Array Name) : MessageData := MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " " partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData := let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName let rec loop : Code β†’ MessageData | Code.decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}" | Code.reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}" | Code.joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}" | Code.seq e k => m!"{e}\n{loop k}" | Code.action e => e | Code.ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}" | Code.jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}" | Code.Β«breakΒ» _ => m!"break {us}" | Code.Β«continueΒ» _ => m!"continue {us}" | Code.Β«returnΒ» _ v => m!"return {v} {us}" | Code.Β«matchΒ» _ _ ds t alts => m!"match {ds} with" ++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}" loop codeBlock.code /- Return true if the give code contains an exit point that satisfies `p` -/ @[inline] partial def hasExitPointPred (c : Code) (p : Code β†’ Bool) : Bool := let rec @[specialize] loop : Code β†’ Bool | Code.decl _ _ k => loop k | Code.reassign _ _ k => loop k | Code.joinpoint _ _ b k => loop b || loop k | Code.seq _ k => loop k | Code.ite _ _ _ _ t e => loop t || loop e | Code.Β«matchΒ» _ _ _ _ alts => alts.any (loop Β·.rhs) | Code.jmp _ _ _ => false | c => p c loop c def hasExitPoint (c : Code) : Bool := hasExitPointPred c fun c => true def hasReturn (c : Code) : Bool := hasExitPointPred c fun | Code.Β«returnΒ» _ _ => true | _ => false def hasTerminalAction (c : Code) : Bool := hasExitPointPred c fun | Code.Β«actionΒ» _ => true | _ => false def hasBreakContinue (c : Code) : Bool := hasExitPointPred c fun | Code.Β«breakΒ» _ => true | Code.Β«continueΒ» _ => true | _ => false def hasBreakContinueReturn (c : Code) : Bool := hasExitPointPred c fun | Code.Β«breakΒ» _ => true | Code.Β«continueΒ» _ => true | Code.Β«returnΒ» _ _ => true | _ => false def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax β†’ m Code) : m Code := withRef e <| withFreshMacroScope do let y ← `(y) let yName := y.getId let doElem ← `(doElem| let y ← $e:term) -- Add elaboration hint for producing sane error message let y ← `(ensureExpectedType% "type mismatch, result value" $y) let k ← mkCont y pure $ Code.decl #[yName] doElem k /- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/ partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code := let rec loop : Code β†’ MacroM Code | Code.decl xs stx k => do Code.decl xs stx (← loop k) | Code.reassign xs stx k => do Code.reassign xs stx (← loop k) | Code.joinpoint n ps b k => do Code.joinpoint n ps (← loop b) (← loop k) | Code.seq e k => do Code.seq e (← loop k) | Code.ite ref x? h c t e => do Code.ite ref x? h c (← loop t) (← loop e) | Code.Β«matchΒ» ref g ds t alts => do Code.Β«matchΒ» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) }) | Code.action e => mkAuxDeclFor e fun y => let ref := e -- We jump to `jp` with xs **and** y let jmpArgs := xs.map $ mkIdentFrom ref let jmpArgs := jmpArgs.push y pure $ Code.jmp ref jp jmpArgs | c => pure c loop code structure JPDecl where name : Name params : Array (Name Γ— Bool) body : Code def attachJP (jpDecl : JPDecl) (k : Code) : Code := Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code := jpDecls.foldr attachJP k def mkFreshJP (ps : Array (Name Γ— Bool)) (body : Code) : TermElabM JPDecl := do let ps ← if ps.isEmpty then let y ← mkFreshUserName `y pure #[(y, false)] else pure ps -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by -- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp` -- We will remove this hack when we re-implement the compiler frontend in Lean. let name ← mkFreshUserName `_do_jp pure { name := name, params := ps, body := body } def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl := mkFreshJP (xs.map fun x => (x, true)) body def addFreshJP (ps : Array (Name Γ— Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do let jp ← mkFreshJP ps body modify fun (jps : Array JPDecl) => jps.push jp pure jp.name def insertVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (Β·.insert Β·) rs def eraseVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (Β·.erase Β·) rs def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet := match x? with | none => rs | some x => rs.insert x /- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/ def mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let jp ← addFreshJP (xs.map fun x => (x, true)) c if xs.isEmpty then let unit ← ``(Unit.unit) return Code.jmp ref jp #[unit] else return Code.jmp ref jp (xs.map $ mkIdentFrom ref) /- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value. The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh` is a fresh variable created by this method. -/ def mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax β†’ MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let args := xs.map $ mkIdentFrom ref let args := args.push val let yFresh ← mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (yFresh, false) let jpBody ← liftMacroM $ mkJPBody (mkIdentFrom ref yFresh) let jp ← addFreshJP ps jpBody pure $ Code.jmp ref jp args /- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/ partial def pullExitPointsAux : NameSet β†’ Code β†’ StateRefT (Array JPDecl) TermElabM Code | rs, Code.decl xs stx k => do Code.decl xs stx (← pullExitPointsAux (eraseVars rs xs) k) | rs, Code.reassign xs stx k => do Code.reassign xs stx (← pullExitPointsAux (insertVars rs xs) k) | rs, Code.joinpoint j ps b k => do Code.joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k) | rs, Code.seq e k => do Code.seq e (← pullExitPointsAux rs k) | rs, Code.ite ref x? o c t e => do Code.ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e) | rs, Code.Β«matchΒ» ref g ds t alts => do Code.Β«matchΒ» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) }) | rs, c@(Code.jmp _ _ _) => pure c | rs, Code.Β«breakΒ» ref => mkSimpleJmp ref rs (Code.Β«breakΒ» ref) | rs, Code.Β«continueΒ» ref => mkSimpleJmp ref rs (Code.Β«continueΒ» ref) | rs, Code.Β«returnΒ» ref val => mkJmp ref rs val (fun y => pure $ Code.Β«returnΒ» ref y) | rs, Code.action e => -- We use `mkAuxDeclFor` because `e` is not pure. mkAuxDeclFor e fun y => let ref := e mkJmp ref rs y (fun yFresh => do pure $ Code.action (← ``(Pure.pure $yFresh))) /- Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock. When a new variable is not already in the collection, but is shadowed by some declaration in `c`, we create auxiliary join points to make sure we preserve the semantics of the code block. Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it with the reassignment `x := x + 1`. We first use `pullExitPoints` to create ``` let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` and then we add the reassignment ``` x := x + 1 let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` Note that we created a fresh variable `x!1` to avoid accidental name capture. As another example, consider ``` print x; let x := 10 y := y + 1; return x; ``` We transform it into ``` let jp (y x!1) := return x!1; print x; let x := 10 y := y + 1; jmp jp y x ``` and then we add the reassignment as in the previous example. We need to include `y` in the jump, because each exit point is implicitly returning the set of update variables. We implement the method as follows. Let `us` be `c.uvars`, then 1- for each `return _ y` in `c`, we create a join point `let j (us y!1) := return y!1` and replace the `return _ y` with `jmp us y` 2- for each `break`, we create a join point `let j (us) := break` and replace the `break` with `jmp us`. 3- Same as 2 for `continue`. -/ def pullExitPoints (c : Code) : TermElabM Code := do if hasExitPoint c then let (c, jpDecls) ← (pullExitPointsAux {} c).run #[] pure $ attachJPs jpDecls c else pure c partial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code := let rec update : Code β†’ TermElabM Code | Code.joinpoint j ps b k => do Code.joinpoint j ps (← update b) (← update k) | Code.seq e k => do Code.seq e (← update k) | c@(Code.Β«matchΒ» ref g ds t alts) => do if alts.any fun alt => alt.vars.any fun x => ws.contains x then -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints` pullExitPoints c else Code.Β«matchΒ» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) }) | Code.ite ref none o c t e => do Code.ite ref none o c (← update t) (← update e) | c@(Code.ite ref (some h) o cond t e) => do if ws.contains h then -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints` pullExitPoints c else Code.ite ref (some h) o cond (← update t) (← update e) | Code.reassign xs stx k => do Code.reassign xs stx (← update k) | c@(Code.decl xs stx k) => do if xs.any fun x => ws.contains x then -- One the declared variables is shadowing a variable in `ws` pullExitPoints c else Code.decl xs stx (← update k) | c => pure c update c /- Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`. We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`. See discussion at `pullExitPoints`. -/ partial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do if ws.any fun x => !c.uvars.contains x then -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed) pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws } else pure { c with uvars := ws } private def union (s₁ sβ‚‚ : NameSet) : NameSet := s₁.fold (Β·.insert Β·) sβ‚‚ /- Given two code blocks `c₁` and `cβ‚‚`, make sure they have the same set of updated variables. Let `ws` the union of the updated variables in `c₁‡ and ‡cβ‚‚`. We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars cβ‚‚ ws` -/ def homogenize (c₁ cβ‚‚ : CodeBlock) : TermElabM (CodeBlock Γ— CodeBlock) := do let ws := union c₁.uvars cβ‚‚.uvars let c₁ ← extendUpdatedVars c₁ ws let cβ‚‚ ← extendUpdatedVars cβ‚‚ ws pure (c₁, cβ‚‚) /- Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`. We remove `x` from the collection of updated varibles. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `let (x, y) := t` -/ def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := { code := Code.decl xs stx c.code, uvars := eraseVars c.uvars xs } /- Extending code blocks with reassignments: `x : t := v` and `x : t ← v`. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `(x, y) ← t` -/ def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do let us := c.uvars let ws := insertVars us xs -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`. -- See discussion at `pullExitPoints` let code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code pure { code := Code.reassign xs stx code, uvars := ws } def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock := { c with code := Code.seq action c.code } def mkTerminalAction (action : Syntax) : CodeBlock := { code := Code.action action } def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock := { code := Code.Β«returnΒ» ref val } def mkBreak (ref : Syntax) : CodeBlock := { code := Code.Β«breakΒ» ref } def mkContinue (ref : Syntax) : CodeBlock := { code := Code.Β«continueΒ» ref } def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do let x? := if optIdent.isNone then none else some optIdent[0].getId let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch pure { code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code, uvars := thenBranch.uvars, } private def mkUnit : MacroM Syntax := ``((⟨⟩ : PUnit)) private def mkPureUnit : MacroM Syntax := ``(pure PUnit.unit) def mkPureUnitAction : MacroM CodeBlock := do mkTerminalAction (← mkPureUnit) def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do let thenBranch ← mkPureUnitAction pure { c with code := Code.ite (← getRef) none mkNullNode cond thenBranch.code c.code } def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do -- nary version of homogenize let ws := alts.foldl (union Β· Β·.rhs.uvars) {} let alts ← alts.mapM fun alt => do let rhs ← extendUpdatedVars alt.rhs ws pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code } pure { code := Code.Β«matchΒ» ref genParam discrs optType alts, uvars := ws } /- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`. This method assumes `terminal` is a terminal -/ def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do unless hasTerminalAction terminal.code do throwErrorAt kRef "'do' element is unreachable" let (terminal, k) ← homogenize terminal k let xs := nameSetToArray k.uvars let y ← match y? with | some y => pure y | none => mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (y, false) let jpDecl ← mkFreshJP ps k.code let jp := jpDecl.name let terminal ← liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs pure { code := attachJP jpDecl terminal, uvars := k.uvars } def getLetIdDeclVar (letIdDecl : Syntax) : Name := letIdDecl[0].getId -- support both regular and syntax match def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternVars pattern <|> Array.map Syntax.getId <$> Quotation.getPatternVars pattern def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternsVars patterns <|> Array.map Syntax.getId <$> Quotation.getPatternsVars patterns def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := letPatDecl[0] getPatternVarsEx pattern def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name := letEqnsDecl[0].getId def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do let arg := letDecl[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == `Lean.Parser.Term.letEqnsDecl then pure #[getLetEqnsDeclVar arg] else throwError "unexpected kind of let declaration" def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) := -- leading_parser "let " >> optional "mut " >> letDecl getLetDeclVars doLet[2] def getDoHaveVar (doHave : Syntax) : Name := /- `leading_parser "have " >> Term.haveDecl` where ``` haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic) optIdent := optional (try (ident >> " : ")) ``` -/ let optIdent := doHave[1][0] if optIdent.isNone then `this else optIdent[0].getId def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do -- letRecDecls is an array of `(group (optional attributes >> letDecl))` let letRecDecls := doLetRec[1][0].getSepArgs let letDecls := letRecDecls.map fun p => p[2] let mut allVars := #[] for letDecl in letDecls do let vars ← getLetDeclVars letDecl allVars := allVars ++ vars pure allVars -- ident >> optType >> leftArrow >> termParser def getDoIdDeclVar (doIdDecl : Syntax) : Name := doIdDecl[0].getId -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := doPatDecl[0] getPatternVarsEx pattern -- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do let decl := doLetArrow[2] if decl.getKind == `Lean.Parser.Term.doIdDecl then pure #[getDoIdDeclVar decl] else if decl.getKind == `Lean.Parser.Term.doPatDecl then getDoPatDeclVars decl else throwError "unexpected kind of 'do' declaration" def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do let arg := doReassign[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else throwError "unexpected kind of reassignment" def mkDoSeq (doElems : Array Syntax) : Syntax := mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]] def mkSingletonDoSeq (doElem : Syntax) : Syntax := mkDoSeq #[doElem] /- If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s. -/ private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(doElem|if $p:doIfProp then $t else $e) => pure none | `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do let mut e := e?.getD (← `(doSeq|pure PUnit.unit)) let mut eIsSeq := true for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do e ← if eIsSeq then e else `(doSeq|$e:doElem) e ← withRef cond <| match cond with | `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e) | `(doIfCond|let $pat ← $d) => `(doElem| match%$i ← $d with | $pat:term => $t | _ => $e) | `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e) | _ => `(doElem| if%$i $(Syntax.missing) then $t else $e) eIsSeq := false return some e | _ => pure none structure DoIfView where ref : Syntax optIdent : Syntax cond : Syntax thenBranch : Syntax elseBranch : Syntax /- This method assumes `expandDoIf?` is not applicable. -/ private def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do pure { ref := doIf, optIdent := doIf[1][0], cond := doIf[1][1], thenBranch := doIf[3], elseBranch := doIf[5][1] } /- We use `MProd` instead of `Prod` to group values when expanding the `do` notation. `MProd` is a universe monomorphic product. The motivation is to generate simpler universe constraints in code that was not written by the user. Note that we are not restricting the macro power since the `Bind.bind` combinator already forces values computed by monadic actions to be in the same universe. -/ private def mkTuple (elems : Array Syntax) : MacroM Syntax := do if elems.size == 0 then mkUnit else if elems.size == 1 then pure elems[0] else (elems.extract 0 (elems.size - 1)).foldrM (fun elem tuple => ``(MProd.mk $elem $tuple)) (elems.back) /- Return `some action` if `doElem` is a `doExpr <action>`-/ def isDoExpr? (doElem : Syntax) : Option Syntax := if doElem.getKind == `Lean.Parser.Term.doExpr then some doElem[0] else none /-- Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term ``` let a_1 := x.1 let x := x.2 let a_2 := x.1 let x := x.2 ... let a_n := x.1 let a_{n+1} := x.2 body ``` Special cases - `uvars := #[]` => `body` - `uvars := #[a]` => `let a := x; body` We use this method when expanding the `for-in` notation. -/ private def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do if uvars.size == 0 then return body else if uvars.size == 1 then `(let $(← mkIdentFromRef uvars[0]):ident := $x; $body) else destruct uvars.toList x body where destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do match as with | [a, b] => `(let $(← mkIdentFromRef a):ident := $x.1; let $(← mkIdentFromRef b):ident := $x.2; $body) | a :: as => withFreshMacroScope do let rest ← destruct as (← `(x)) body `(let $(← mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest) | _ => unreachable! /- The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term. We use this method to convert 1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of `CodeBlock` never contains `break` nor `continue`. Moreover, the collection of updated variables is not packed into the result. Thus, we have two kinds of exit points - `Code.action e` which is converted into `e` - `Code.return _ e` which is converted into `pure e` We use `Kind.regular` for this case. 2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate a `Syntax` term representing a function for the `xs.forIn` combinator. a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term has type `m (ForInStep (Option Ξ± Γ— Οƒ))`, where `a : Ξ±`, and the `Οƒ` is the type of the tuple of variables reassigned by `b`. We use `Kind.forInWithReturn` for this case b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated `Syntax` term has type `m (ForInStep Οƒ)`. We use `Kind.forIn` for this case. 3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`). The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`, `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information. For example, the auxiliary type `DoResultPBC Ξ± Οƒ` is used for a code block that exits with `Code.action`, **and** `Code.break`/`Code.continue`, `Ξ±` is the type of values produced by the exit `action`, and `Οƒ` is the type of the tuple of reassigned variables. The type `DoResult Ξ± Ξ² Οƒ` is usedf for code blocks that exit with `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `Ξ²` is the type of the returned values. We don't use `DoResult Ξ± Ξ² Οƒ` for all cases because: a) The elaborator would not be able to infer all type parameters without extra annotations. For example, if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `Ξ²`. b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`), but we don't want to consider "unreachable" cases. We do not distinguish between cases that contain `break`, but not `continue`, and vice versa. When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`, and `b/c` for a code block that contains `Code.break _` or `Code.continue _`. - `a`: `Kind.regular`, type `m (Ξ± Γ— Οƒ)` - `r`: `Kind.regular`, type `m (Ξ± Γ— Οƒ)` Note that the code that pattern matches on the result will behave differently in this case. It produces `return a` for this case, and `pure a` for the previous one. - `b/c`: `Kind.nestedBC`, type `m (DoResultBC Οƒ)` - `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR Ξ± Ξ² Οƒ)` - `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC Ξ± Οƒ)` - `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC Ξ± Οƒ)` Again the code that pattern matches on the result will behave differently in this case and the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for this case, and `pure a` for the previous case. - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC Ξ± Ξ² Οƒ)` Here is the recipe for adding new combinators with nested `do`s. Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m Ξ± β†’ m Ξ±` 1- Convert `doSeq` into `codeBlock : CodeBlock` 2- Create term `term` using `mkNestedTerm code m uvars a r bc` where `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`, `m` is a `Syntax` representing the Monad, and `a` is true if `code` contains `Code.action _`, `r` is true if `code` contains `Code.return _ _`, `bc` is true if `code` contains `Code.break _` or `Code.continue _`. Remark: for combinators such as `repeat` that take a single `doSeq`, all arguments, but `m`, are extracted from `codeBlock`. 3- Create the term `repeat $term` 4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc` -/ namespace ToTerm inductive Kind where | regular | forIn | forInWithReturn | nestedBC | nestedPR | nestedSBC | nestedPRBC instance : Inhabited Kind := ⟨Kind.regular⟩ def Kind.isRegular : Kind β†’ Bool | Kind.regular => true | _ => false structure Context where m : Syntax -- Syntax to reference the monad associated with the do notation. uvars : Array Name kind : Kind abbrev M := ReaderT Context MacroM def mkUVarTuple : M Syntax := do let ctx ← read let uvarIdents ← ctx.uvars.mapM mkIdentFromRef mkTuple uvarIdents def returnToTerm (val : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u)) | Kind.forIn => ``(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => ``(Pure.pure (DoResultPR.Β«returnΒ» $val $u)) | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.Β«pureReturnΒ» $val $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.Β«returnΒ» $val $u)) def continueToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => ``(Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => ``(Pure.pure (DoResultBC.Β«continueΒ» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.Β«continueΒ» $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.Β«continueΒ» $u)) def breakToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => ``(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u))) | Kind.nestedBC => ``(Pure.pure (DoResultBC.Β«breakΒ» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.Β«breakΒ» $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.Β«breakΒ» $u)) def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u)) | Kind.forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.Β«pureΒ» y $u))) | Kind.nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.Β«pureReturnΒ» y $u))) | Kind.nestedPRBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.Β«pureΒ» y $u))) def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do if action.getKind == `Lean.Parser.Term.doDbgTrace then let msg := action[1] `(dbg_trace $msg; $k) else if action.getKind == `Lean.Parser.Term.doAssert then let cond := action[1] `(assert! $cond; $k) else let action ← withRef action ``(($action : $((←read).m) PUnit)) ``(Bind.bind $action (fun (_ : PUnit) => $k)) def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do let kind := decl.getKind if kind == `Lean.Parser.Term.doLet then let letDecl := decl[2] `(let $letDecl:letDecl; $k) else if kind == `Lean.Parser.Term.doLetRec then let letRecToken := decl[0] let letRecDecls := decl[1] pure $ mkNode `Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k] else if kind == `Lean.Parser.Term.doLetArrow then let arg := decl[2] let ref := arg if arg.getKind == `Lean.Parser.Term.doIdDecl then let id := arg[0] let type := expandOptType ref arg[1] let doElem := arg[3] -- `doElem` must be a `doExpr action`. See `doLetArrowToCode` match isDoExpr? doElem with | some action => let action ← withRef action `(($action : $((← read).m) $type)) ``(Bind.bind $action (fun ($id:ident : $type) => $k)) | none => Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else if kind == `Lean.Parser.Term.doHave then -- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser` let args := decl.getArgs let args := args ++ #[mkNullNode /- optional ';' -/, k] pure $ mkNode `Lean.Parser.Term.Β«haveΒ» args else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do let kind := reassign.getKind if kind == `Lean.Parser.Term.doReassign then -- doReassign := leading_parser (letIdDecl <|> letPatDecl) let arg := reassign[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then -- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >> " := " >> termParser let x := arg[0] let val := arg[4] let newVal ← `(ensureTypeOf% $x $(quote "invalid reassignment, value") $val) let arg := arg.setArg 4 newVal let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- TODO: ensure the types did not change let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode Macro.throwErrorAt reassign "unexpected kind of 'do' reassignment" def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do if optIdent.isNone then ``(ite $cond $thenBranch $elseBranch) else let h := optIdent[0] ``(dite $cond (fun $h => $thenBranch) (fun $h => $elseBranch)) def mkJoinPoint (j : Name) (ps : Array (Name Γ— Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(typeOf% $(← mkIdentFromRef id)) else `(_) let ps ← ps.mapM fun ⟨id, useTypeOf⟩ => mkIdentFromRef id /- We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`. By elaborating `$k` first, we "learn" more about `$body`'s type. For example, consider the following example `do` expression ``` def f (x : Nat) : IO Unit := do if x > 0 then IO.println "x is not zero" -- Error is here IO.mkRef true ``` it is expanded into ``` def f (x : Nat) : IO Unit := do let jp (u : Unit) : IO _ := IO.mkRef true; if x > 0 then IO.println "not zero" jp () else jp () ``` If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit β†’ IO (IO.Ref Bool)`. Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit β†’ IO Unit`. Then, we get the expected type mismatch error at `IO.mkRef true`. -/ `(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k) def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax := Syntax.mkApp (mkIdentFrom ref j) args partial def toTerm : Code β†’ M Syntax | Code.Β«returnΒ» ref val => withRef ref <| returnToTerm val | Code.Β«continueΒ» ref => withRef ref continueToTerm | Code.Β«breakΒ» ref => withRef ref breakToTerm | Code.action e => actionTerminalToTerm e | Code.joinpoint j ps b k => do mkJoinPoint j ps (← toTerm b) (← toTerm k) | Code.jmp ref j args => pure $ mkJmp ref j args | Code.decl _ stx k => do declToTerm stx (← toTerm k) | Code.reassign _ stx k => do reassignToTerm stx (← toTerm k) | Code.seq stx k => do seqToTerm stx (← toTerm k) | Code.ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e) | Code.Β«matchΒ» ref genParam discrs optType alts => do let mut termAlts := #[] for alt in alts do let rhs ← toTerm alt.rhs let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", alt.patterns, mkAtomFrom alt.ref "=>", rhs] termAlts := termAlts.push termAlt let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts] pure $ mkNode `Lean.Parser.Term.Β«matchΒ» #[mkAtomFrom ref "match", genParam, discrs, optType, mkAtomFrom ref "with", termMatchAlts] def run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do let term ← toTerm code { m := m, kind := kind, uvars := uvars } pure term /- Given - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point generate Kind. See comment at the beginning of the `ToTerm` namespace. -/ def mkNestedKind (a r bc : Bool) : Kind := match a, r, bc with | true, false, false => Kind.regular | false, true, false => Kind.regular | false, false, true => Kind.nestedBC | true, true, false => Kind.nestedPR | true, false, true => Kind.nestedSBC | false, true, true => Kind.nestedSBC | true, true, true => Kind.nestedPRBC | false, false, false => unreachable! def mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do ToTerm.run code m uvars (mkNestedKind a r bc) /- Given a term `term` produced by `ToTerm.run`, pattern match on its result. See comment at the beginning of the `ToTerm` namespace. - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point The result is a sequence of `doElem` -/ def matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo) let u ← mkTuple (← uvars.mapM mkIdentFromRef) match a, r, bc with | true, false, false => if uvars.isEmpty then toDoElems (← `(do $term:term)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1)) | false, true, false => if uvars.isEmpty then toDoElems (← `(do let r ← $term:term; return r)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1)) | false, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultBC.Β«breakΒ» u => $u:term := u; break | DoResultBC.Β«continueΒ» u => $u:term := u; continue) | true, true, false => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPR.Β«pureΒ» a u => $u:term := u; pure a | DoResultPR.Β«returnΒ» b u => $u:term := u; return b) | true, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.Β«pureReturnΒ» a u => $u:term := u; pure a | DoResultSBC.Β«breakΒ» u => $u:term := u; break | DoResultSBC.Β«continueΒ» u => $u:term := u; continue) | false, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.Β«pureReturnΒ» a u => $u:term := u; return a | DoResultSBC.Β«breakΒ» u => $u:term := u; break | DoResultSBC.Β«continueΒ» u => $u:term := u; continue) | true, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPRBC.Β«pureΒ» a u => $u:term := u; pure a | DoResultPRBC.Β«returnΒ» a u => $u:term := u; return a | DoResultPRBC.Β«breakΒ» u => $u:term := u; break | DoResultPRBC.Β«continueΒ» u => $u:term := u; continue) | false, false, false => unreachable! end ToTerm def isMutableLet (doElem : Syntax) : Bool := let kind := doElem.getKind (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet) && !doElem[1].isNone namespace ToCodeBlock structure Context where ref : Syntax m : Syntax -- Syntax representing the monad associated with the do notation. mutableVars : NameSet := {} insideFor : Bool := false abbrev M := ReaderT Context TermElabM @[inline] def withNewMutableVars {Ξ±} (newVars : Array Name) (mutable : Bool) (x : M Ξ±) : M Ξ± := withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x def checkReassignable (xs : Array Name) : M Unit := do let throwInvalidReassignment (x : Name) : M Unit := throwError "'{x.simpMacroScopes}' cannot be reassigned" let ctx ← read for x in xs do unless ctx.mutableVars.contains x do throwInvalidReassignment x def checkNotShadowingMutable (xs : Array Name) : M Unit := do let throwInvalidShadowing (x : Name) : M Unit := throwError "mutable variable '{x.simpMacroScopes}' cannot be shadowed" let ctx ← read for x in xs do if ctx.mutableVars.contains x then throwInvalidShadowing x @[inline] def withFor {Ξ±} (x : M Ξ±) : M Ξ± := withReader (fun ctx => { ctx with insideFor := true }) x structure ToForInTermResult where uvars : Array Name term : Syntax def mkForInBody (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do let ctx ← read let uvars := forInBody.uvars let uvars := nameSetToArray uvars let term ← liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn) pure ⟨uvars, term⟩ def ensureInsideFor : M Unit := unless (← read).insideFor do throwError "invalid 'do' element, it must be inside 'for'" def ensureEOS (doElems : List Syntax) : M Unit := unless doElems.isEmpty do throwError "must be last element in a 'do' sequence" private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax β†’ StateT (List Syntax) MacroM Syntax | stx@(Syntax.node k args) => if liftMethodDelimiter k then return stx else if k == `Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do if inBinder then Macro.throwErrorAt stx "cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`" let term := args[1] let term ← expandLiftMethodAux inQuot inBinder term let auxDoElem ← `(doElem| let a ← $term:term) modify fun s => s ++ [auxDoElem] `(a) else do let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot let inBinder := inBinder || (!inQuot && liftMethodForbiddenBinder stx) let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder) return Syntax.node k args | stx => pure stx def expandLiftMethod (doElem : Syntax) : MacroM (List Syntax Γ— Syntax) := do if !hasLiftMethod doElem then pure ([], doElem) else let (doElem, doElemsNew) ← (expandLiftMethodAux false false doElem).run [] pure (doElemsNew, doElem) def checkLetArrowRHS (doElem : Syntax) : M Unit := do let kind := doElem.getKind if kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet || kind == `Lean.Parser.Term.doLetRec || kind == `Lean.Parser.Term.doHave || kind == `Lean.Parser.Term.doReassign || kind == `Lean.Parser.Term.doReassignArrow then throwErrorAt doElem "invalid kind of value '{kind}' in an assignment" /- Generate `CodeBlock` for `doReturn` which is of the form ``` "return " >> optional termParser ``` `doElems` is only used for sanity checking. -/ def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do ensureEOS doElems let argOpt := doReturn[1] let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0] return mkReturn (← getRef) arg structure Catch where x : Syntax optType : Syntax codeBlock : CodeBlock def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet := let ws := tryCode.uvars let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws let ws := match finallyCode? with | none => ws | some c => union c.uvars ws ws def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code β†’ Bool) : Bool := p tryCode.code || catches.any (fun Β«catchΒ» => p Β«catchΒ».codeBlock.code) || match finallyCode? with | none => false | some finallyCode => p finallyCode.code mutual /- "Concatenate" `c` with `doSeqToCode doElems` -/ partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock := match doElems with | [] => pure c | nextDoElem :: _ => do let k ← doSeqToCode doElems let ref := nextDoElem concat c ref none k /- Generate `CodeBlock` for `doLetArrow; doElems` `doLetArrow` is of the form ``` "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) ``` where ``` def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser) ``` -/ partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doLetArrow let decl := doLetArrow[2] if decl.getKind == `Lean.Parser.Term.doIdDecl then let y := decl[0].getId checkNotShadowingMutable #[y] let doElem := decl[3] let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems) match isDoExpr? doElem with | some action => pure $ mkVarDeclCore #[y] doLetArrow k | none => checkLetArrowRHS doElem let c ← doSeqToCode [doElem] match doElems with | [] => pure c | kRef::_ => concat c kRef y k else if decl.getKind == `Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← if isMutableLet doLetArrow then `(do let discr ← $doElem; let mut $pattern:term := discr) else `(do let discr ← $doElem; let $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if isMutableLet doLetArrow then throwError "'mut' is currently not supported in let-decls with 'else' case" let contSeq := mkDoSeq doElems.toArray let elseSeq := mkSingletonDoSeq optElse[1] let auxDo ← `(do let discr ← $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else throwError "unexpected kind of 'do' declaration" /- Generate `CodeBlock` for `doReassignArrow; doElems` `doReassignArrow` is of the form ``` (doIdDecl <|> doPatDecl) ``` -/ partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doReassignArrow let decl := doReassignArrow[0] if decl.getKind == `Lean.Parser.Term.doIdDecl then let doElem := decl[3] let y := decl[0] let auxDo ← `(do let r ← $doElem; $y:ident := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if decl.getKind == `Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← `(do let discr ← $doElem; $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported" else throwError "unexpected kind of 'do' reassignment" /- Generate `CodeBlock` for `doIf; doElems` `doIf` is of the form ``` "if " >> optIdent >> termParser >> " then " >> doSeq >> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq)) >> optional (" else " >> doSeq) ``` -/ partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do let view ← liftMacroM $ mkDoIfView doIf let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch) let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch) let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch concatWith ite doElems /- Generate `CodeBlock` for `doUnless; doElems` `doUnless` is of the form ``` "unless " >> termParser >> "do " >> doSeq ``` -/ partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do let ref := doUnless let cond := doUnless[1] let doSeq := doUnless[3] let body ← doSeqToCode (getDoSeqElems doSeq) let unlessCode ← liftMacroM <| mkUnless cond body concatWith unlessCode doElems /- Generate `CodeBlock` for `doFor; doElems` `doFor` is of the form ``` def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq ``` -/ partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do let doForDecls := doFor[1].getSepArgs if doForDecls.size > 1 then /- Expand ``` for x in xs, y in ys do body ``` into ``` let s := toStream ys for x in xs do match Stream.next? s with | none => break | some (y, s') => s := s' body ``` -/ -- Extract second element let doForDecl := doForDecls[1] let y := doForDecl[0] let ys := doForDecl[2] let doForDecls := doForDecls.eraseIdx 1 let body := doFor[3] withFreshMacroScope do let toStreamFn ← withRef ys ``(toStream) let auxDo ← `(do let mut s := $toStreamFn:ident $ys for $doForDecls:doForDecl,* do match Stream.next? s with | none => break | some ($y, s') => s := s' do $body) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else withRef doFor do let x := doForDecls[0][0] withRef x <| checkNotShadowingMutable (← getPatternVarsEx x) let xs := doForDecls[0][2] let forElems := getDoSeqElems doFor[3] let forInBodyCodeBlock ← withFor (doSeqToCode forElems) let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock let uvarsTuple ← liftMacroM do mkTuple (← uvars.mapM mkIdentFromRef) if hasReturn forInBodyCodeBlock.code then let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(forIn% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody) let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r.2; match r.1 with | none => Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit) | some a => return ensureExpectedType% "type mismatch, 'for'" a) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(forIn% $(xs) $uvarsTuple fun $x r => $forInBody) if doElems.isEmpty then let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r; Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit)) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems /-- Generate `CodeBlock` for `doMatch; doElems` -/ partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doMatch let genParam := doMatch[1] let discrs := doMatch[2] let optType := doMatch[3] let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt` let alts ← matchAlts.mapM fun matchAlt => do let patterns := matchAlt[1] let vars ← getPatternsVarsEx patterns.getSepArgs withRef patterns <| checkNotShadowingMutable vars let rhs := matchAlt[3] let rhs ← doSeqToCode (getDoSeqElems rhs) pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock } let matchCode ← mkMatch ref genParam discrs optType alts concatWith matchCode doElems /-- Generate `CodeBlock` for `doTry; doElems` ``` def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq ``` -/ partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doTry let tryCode ← doSeqToCode (getDoSeqElems doTry[1]) let optFinally := doTry[3] let catches ← doTry[2].getArgs.mapM fun catchStx => do if catchStx.getKind == `Lean.Parser.Term.doCatch then let x := catchStx[1] if x.isIdent then withRef x <| checkNotShadowingMutable #[x.getId] let optType := catchStx[2] let c ← doSeqToCode (getDoSeqElems catchStx[4]) pure { x := x, optType := optType, codeBlock := c : Catch } else if catchStx.getKind == `Lean.Parser.Term.doCatchMatch then let matchAlts := catchStx[1] let x ← `(ex) let auxDo ← `(do match ex with $matchAlts) let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo)) pure { x := x, codeBlock := c, optType := mkNullNode : Catch } else throwError "unexpected kind of 'catch'" let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1]) if catches.isEmpty && finallyCode?.isNone then throwError "invalid 'try', it must have a 'catch' or 'finally'" let ctx ← read let ws := getTryCatchUpdatedVars tryCode catches finallyCode? let uvars := nameSetToArray ws let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction let r := tryCatchPred tryCode catches finallyCode? hasReturn let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue let toTerm (codeBlock : CodeBlock) : M Syntax := do let codeBlock ← liftM $ extendUpdatedVars codeBlock ws liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc let term ← toTerm tryCode let term ← catches.foldlM (fun term Β«catchΒ» => do let catchTerm ← toTerm Β«catchΒ».codeBlock if catch.optType.isNone then ``(MonadExcept.tryCatch $term (fun $(Β«catchΒ».x):ident => $catchTerm)) else let type := Β«catchΒ».optType[1] ``(tryCatchThe $type $term (fun $(Β«catchΒ».x):ident => $catchTerm))) term let term ← match finallyCode? with | none => pure term | some finallyCode => withRef optFinally do unless finallyCode.uvars.isEmpty do throwError "'finally' currently does not support reassignments" if hasBreakContinueReturn finallyCode.code then throwError "'finally' currently does 'return', 'break', nor 'continue'" let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular ``(tryFinally $term $finallyTerm) let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc doSeqToCode (doElemsNew ++ doElems) partial def doSeqToCode : List Syntax β†’ M CodeBlock | [] => do liftMacroM mkPureUnitAction | doElem::doElems => withIncRecDepth <| withRef doElem do checkMaxHeartbeats "'do'-expander" match (← liftMacroM <| expandMacro? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => match (← liftMacroM <| expandDoIf? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => let (liftedDoElems, doElem) ← liftM (liftMacroM <| expandLiftMethod doElem : TermElabM _) if !liftedDoElems.isEmpty then doSeqToCode (liftedDoElems ++ [doElem] ++ doElems) else let ref := doElem let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems let k := doElem.getKind if k == `Lean.Parser.Term.doLet then let vars ← getDoLetVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems) else if k == `Lean.Parser.Term.doHave then let var := getDoHaveVar doElem checkNotShadowingMutable #[var] mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems) else if k == `Lean.Parser.Term.doLetRec then let vars ← getDoLetRecVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == `Lean.Parser.Term.doReassign then let vars ← getDoReassignVars doElem checkReassignable vars let k ← doSeqToCode doElems mkReassignCore vars doElem k else if k == `Lean.Parser.Term.doLetArrow then doLetArrowToCode doElem doElems else if k == `Lean.Parser.Term.doReassignArrow then doReassignArrowToCode doElem doElems else if k == `Lean.Parser.Term.doIf then doIfToCode doElem doElems else if k == `Lean.Parser.Term.doUnless then doUnlessToCode doElem doElems else if k == `Lean.Parser.Term.doFor then withFreshMacroScope do doForToCode doElem doElems else if k == `Lean.Parser.Term.doMatch then doMatchToCode doElem doElems else if k == `Lean.Parser.Term.doTry then doTryToCode doElem doElems else if k == `Lean.Parser.Term.doBreak then ensureInsideFor ensureEOS doElems return mkBreak ref else if k == `Lean.Parser.Term.doContinue then ensureInsideFor ensureEOS doElems return mkContinue ref else if k == `Lean.Parser.Term.doReturn then doReturnToCode doElem doElems else if k == `Lean.Parser.Term.doDbgTrace then return mkSeq doElem (← doSeqToCode doElems) else if k == `Lean.Parser.Term.doAssert then return mkSeq doElem (← doSeqToCode doElems) else if k == `Lean.Parser.Term.doNested then let nestedDoSeq := doElem[1] doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems) else if k == `Lean.Parser.Term.doExpr then let term := doElem[0] if doElems.isEmpty then return mkTerminalAction term else return mkSeq term (← doSeqToCode doElems) else throwError "unexpected do-element of kind {doElem.getKind}:\n{doElem}" end def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock := (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m := m } end ToCodeBlock /- Create a synthetic metavariable `?m` and assign `m` to it. We use `?m` to refer to `m` when expanding the `do` notation. -/ private def mkMonadAlias (m : Expr) : TermElabM Syntax := do let result ← `(?m) let mType ← inferType m let mvar ← elabTerm result mType assignExprMVar mvar.mvarId! m pure result @[builtinTermElab Β«doΒ»] def elabDo : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? let bindInfo ← extractBind expectedType? let m ← mkMonadAlias bindInfo.m let codeBlock ← ToCodeBlock.run stx m let stxNew ← liftMacroM $ ToTerm.run codeBlock.code m trace[Elab.do] stxNew withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType end Do builtin_initialize registerTraceClass `Elab.do private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do let stx := stx.setKind newKind withRef stx `(do $stx:doElem) @[builtinMacro Lean.Parser.Term.termFor] def expandTermFor : Macro := toDoElem `Lean.Parser.Term.doFor @[builtinMacro Lean.Parser.Term.termTry] def expandTermTry : Macro := toDoElem `Lean.Parser.Term.doTry @[builtinMacro Lean.Parser.Term.termUnless] def expandTermUnless : Macro := toDoElem `Lean.Parser.Term.doUnless @[builtinMacro Lean.Parser.Term.termReturn] def expandTermReturn : Macro := toDoElem `Lean.Parser.Term.doReturn end Lean.Elab.Term
94c799ff3bb800e25ccd0fe42bf1359a2c1c617b
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/measure_theory/indicator_function.lean
8be40ceae035fbf85ccd1f429cb307837266a5ab
[ "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
5,641
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import data.indicator_function import measure_theory.measure_space import analysis.normed_space.basic /-! # Indicator function Properties of indicator functions. ## Tags indicator, characteristic -/ noncomputable theory open_locale classical open set measure_theory filter universes u v variables {Ξ± : Type u} {Ξ² : Type v} section has_zero variables [has_zero Ξ²] {s t : set Ξ±} {f g : Ξ± β†’ Ξ²} {a : Ξ±} lemma indicator_congr_ae [measure_space Ξ±] (h : βˆ€β‚˜ a, a ∈ s β†’ f a = g a) : βˆ€β‚˜ a, indicator s f a = indicator s g a := begin filter_upwards [h], simp only [mem_set_of_eq, indicator], assume a ha, split_ifs with h₁, { exact ha h₁ }, refl end lemma indicator_congr_of_set [measure_space Ξ±] (h : βˆ€β‚˜ a, a ∈ s ↔ a ∈ t) : βˆ€β‚˜ a, indicator s f a = indicator t f a := begin filter_upwards [h], simp only [mem_set_of_eq, indicator], assume a ha, split_ifs with h₁ hβ‚‚ hβ‚‚, { refl }, { have := ha.1 h₁, contradiction }, { have := ha.2 hβ‚‚, contradiction }, refl end end has_zero section has_add variables [add_monoid Ξ²] {s t : set Ξ±} {f g : Ξ± β†’ Ξ²} {a : Ξ±} lemma indicator_union_ae [measure_space Ξ±] {Ξ² : Type*} [add_monoid Ξ²] (h : βˆ€β‚˜ a, a βˆ‰ s ∩ t) (f : Ξ± β†’ Ξ²) : βˆ€β‚˜ a, indicator (s βˆͺ t) f a = indicator s f a + indicator t f a := begin filter_upwards [h], simp only [mem_set_of_eq], assume a ha, exact indicator_union_of_not_mem_inter ha _ end end has_add section norm variables [normed_group Ξ²] {s t : set Ξ±} {f g : Ξ± β†’ Ξ²} {a : Ξ±} lemma norm_indicator_le_of_subset (h : s βŠ† t) (f : Ξ± β†’ Ξ²) (a : Ξ±) : βˆ₯indicator s f aβˆ₯ ≀ βˆ₯indicator t f aβˆ₯ := begin simp only [indicator], split_ifs with h₁ hβ‚‚, { refl }, { exact absurd (h h₁) hβ‚‚ }, { simp only [norm_zero, norm_nonneg] }, refl end lemma norm_indicator_le_norm_self (f : Ξ± β†’ Ξ²) (a : Ξ±) : βˆ₯indicator s f aβˆ₯ ≀ βˆ₯f aβˆ₯ := by { convert norm_indicator_le_of_subset (subset_univ s) f a, rw indicator_univ } lemma norm_indicator_eq_indicator_norm (f : Ξ± β†’ Ξ²) (a : Ξ±) : βˆ₯indicator s f aβˆ₯ = indicator s (Ξ»a, βˆ₯f aβˆ₯) a := by { simp only [indicator], split_ifs, { refl }, rw norm_zero } lemma indicator_norm_le_norm_self (f : Ξ± β†’ Ξ²) (a : Ξ±) : indicator s (Ξ»a, βˆ₯f aβˆ₯) a ≀ βˆ₯f aβˆ₯ := by { rw ← norm_indicator_eq_indicator_norm, exact norm_indicator_le_norm_self _ _ } end norm section order variables [has_zero Ξ²] [preorder Ξ²] {s t : set Ξ±} {f g : Ξ± β†’ Ξ²} {a : Ξ±} lemma indicator_le_indicator_ae [measure_space Ξ±] (h : βˆ€β‚˜ a, a ∈ s β†’ f a ≀ g a) : βˆ€β‚˜ a, indicator s f a ≀ indicator s g a := begin refine h.mono (Ξ» a h, _), simp only [indicator], split_ifs with ha, { exact h ha }, refl end end order section tendsto variables {ΞΉ : Type*} [semilattice_sup ΞΉ] [has_zero Ξ²] lemma tendsto_indicator_of_monotone [nonempty ΞΉ] (s : ΞΉ β†’ set Ξ±) (hs : monotone s) (f : Ξ± β†’ Ξ²) (a : Ξ±) : tendsto (Ξ»i, indicator (s i) f a) at_top (pure $ indicator (Union s) f a) := begin by_cases h : βˆƒi, a ∈ s i, { simp only [tendsto_pure, mem_at_top_sets, mem_set_of_eq], rcases h with ⟨i, hi⟩, use i, assume n hn, rw [indicator_of_mem (hs hn hi) _, indicator_of_mem ((subset_Union _ _) hi) _] }, { rw [not_exists] at h, have : (Ξ»i, indicator (s i) f a) = Ξ»i, 0 := funext (Ξ»i, indicator_of_not_mem (h i) _), rw this, have : indicator (Union s) f a = 0, { apply indicator_of_not_mem, simpa only [not_exists, mem_Union] }, rw this, exact tendsto_const_pure } end lemma tendsto_indicator_of_antimono [nonempty ΞΉ] (s : ΞΉ β†’ set Ξ±) (hs : βˆ€i j, i ≀ j β†’ s j βŠ† s i) (f : Ξ± β†’ Ξ²) (a : Ξ±) : tendsto (Ξ»i, indicator (s i) f a) at_top (pure $ indicator (Inter s) f a) := begin by_cases h : βˆƒi, a βˆ‰ s i, { simp only [tendsto_pure, mem_at_top_sets, mem_set_of_eq], rcases h with ⟨i, hi⟩, use i, assume n hn, rw [indicator_of_not_mem _ _, indicator_of_not_mem _ _], { simp only [mem_Inter, not_forall], exact ⟨i, hi⟩ }, { assume h, have := hs i _ hn h, contradiction } }, { simp only [not_exists, not_not_mem] at h, have : (Ξ»i, indicator (s i) f a) = Ξ»i, f a := funext (Ξ»i, indicator_of_mem (h i) _), rw this, have : indicator (Inter s) f a = f a, { apply indicator_of_mem, simpa only [mem_Inter] }, rw this, exact tendsto_const_pure } end lemma tendsto_indicator_bUnion_finset (s : ΞΉ β†’ set Ξ±) (f : Ξ± β†’ Ξ²) (a : Ξ±) : tendsto (Ξ» (n : finset ΞΉ), indicator (⋃i∈n, s i) f a) at_top (pure $ indicator (Union s) f a) := begin by_cases h : βˆƒi, a ∈ s i, { simp only [mem_at_top_sets, tendsto_pure, mem_set_of_eq, ge_iff_le, finset.le_iff_subset], rcases h with ⟨i, hi⟩, use {i}, assume n hn, replace hn : i ∈ n := hn (finset.mem_singleton_self _), rw [indicator_of_mem, indicator_of_mem], { rw [mem_Union], use i, assumption }, { rw [mem_Union], use i, rw [mem_Union], use hn, assumption } }, { rw [not_exists] at h, have : (Ξ» (n : finset ΞΉ), indicator (⋃ (i : ΞΉ) (H : i ∈ n), s i) f a) = Ξ»i, 0, { funext, rw indicator_of_not_mem, simp only [not_exists, exists_prop, mem_Union, not_and], intros, apply h }, rw this, have : indicator (Union s) f a = 0, { apply indicator_of_not_mem, simpa only [not_exists, mem_Union] }, rw this, exact tendsto_const_pure } end end tendsto
4036e6be766b3895effd0bb449367f2463a412da
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/constructions/finite_products_of_binary_products.lean
b85b98d01021d3e812e8e07307e3a1c7e683c38e
[ "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
12,065
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.preserves.shapes.binary_products import category_theory.limits.preserves.shapes.products import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.finite_products import logic.equiv.fin /-! # Constructing finite products from binary products and terminal. If a category has binary products and a terminal object then it has finite products. If a functor preserves binary products and the terminal object then it preserves finite products. # TODO Provide the dual results. Show the analogous results for functors which reflect or create (co)limits. -/ universes v v' u u' noncomputable theory open category_theory category_theory.category category_theory.limits namespace category_theory variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] variables {D : Type u'} [category.{v'} D] /-- Given `n+1` objects of `C`, a fan for the last `n` with point `c₁.X` and a binary fan on `c₁.X` and `f 0`, we can build a fan for all `n+1`. In `extend_fan_is_limit` we show that if the two given fans are limits, then this fan is also a limit. -/ @[simps {rhs_md := semireducible}] def extend_fan {n : β„•} {f : fin (n+1) β†’ C} (c₁ : fan (Ξ» (i : fin n), f i.succ)) (cβ‚‚ : binary_fan (f 0) c₁.X) : fan f := fan.mk cβ‚‚.X begin refine fin.cases _ _, { apply cβ‚‚.fst }, { intro i, apply cβ‚‚.snd ≫ c₁.Ο€.app ⟨i⟩ }, end /-- Show that if the two given fans in `extend_fan` are limits, then the constructed fan is also a limit. -/ def extend_fan_is_limit {n : β„•} (f : fin (n+1) β†’ C) {c₁ : fan (Ξ» (i : fin n), f i.succ)} {cβ‚‚ : binary_fan (f 0) c₁.X} (t₁ : is_limit c₁) (tβ‚‚ : is_limit cβ‚‚) : is_limit (extend_fan c₁ cβ‚‚) := { lift := Ξ» s, begin apply (binary_fan.is_limit.lift' tβ‚‚ (s.Ο€.app ⟨0⟩) _).1, apply t₁.lift ⟨_, discrete.nat_trans (Ξ» ⟨i⟩, s.Ο€.app ⟨i.succ⟩)⟩ end, fac' := Ξ» s ⟨j⟩, begin apply fin.induction_on j, { apply (binary_fan.is_limit.lift' tβ‚‚ _ _).2.1 }, { rintro i -, dsimp only [extend_fan_Ο€_app], rw [fin.cases_succ, ← assoc, (binary_fan.is_limit.lift' tβ‚‚ _ _).2.2, t₁.fac], refl } end, uniq' := Ξ» s m w, begin apply binary_fan.is_limit.hom_ext tβ‚‚, { rw (binary_fan.is_limit.lift' tβ‚‚ _ _).2.1, apply w ⟨0⟩ }, { rw (binary_fan.is_limit.lift' tβ‚‚ _ _).2.2, apply t₁.uniq ⟨_, _⟩, rintro ⟨j⟩, rw assoc, dsimp only [discrete.nat_trans_app, extend_fan_is_limit._match_1], rw ← w ⟨j.succ⟩, dsimp only [extend_fan_Ο€_app], rw fin.cases_succ } end } section variables [has_binary_products C] [has_terminal C] /-- If `C` has a terminal object and binary products, then it has a product for objects indexed by `fin n`. This is a helper lemma for `has_finite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_product_fin : Ξ  (n : β„•) (f : fin n β†’ C), has_product f | 0 := Ξ» f, begin letI : has_limits_of_shape (discrete (fin 0)) C := has_limits_of_shape_of_equivalence (discrete.equivalence.{0} fin_zero_equiv'.symm), apply_instance, end | (n+1) := Ξ» f, begin haveI := has_product_fin n, apply has_limit.mk ⟨_, extend_fan_is_limit f (limit.is_limit _) (limit.is_limit _)⟩, end /-- If `C` has a terminal object and binary products, then it has finite products. -/ lemma has_finite_products_of_has_binary_and_terminal : has_finite_products C := begin refine ⟨λ n, ⟨λ K, _⟩⟩, letI := has_product_fin n (Ξ» n, K.obj ⟨n⟩), let : discrete.functor (Ξ» n, K.obj ⟨n⟩) β‰… K := discrete.nat_iso (Ξ» ⟨i⟩, iso.refl _), apply has_limit_of_iso this, end end section preserves variables (F : C β₯€ D) variables [preserves_limits_of_shape (discrete walking_pair) F] variables [preserves_limits_of_shape (discrete.{0} pempty) F] variables [has_finite_products.{v} C] /-- If `F` preserves the terminal object and binary products, then it preserves products indexed by `fin n` for any `n`. -/ noncomputable def preserves_fin_of_preserves_binary_and_terminal : Ξ  (n : β„•) (f : fin n β†’ C), preserves_limit (discrete.functor f) F | 0 := Ξ» f, begin letI : preserves_limits_of_shape (discrete (fin 0)) F := preserves_limits_of_shape_of_equiv.{0 0} (discrete.equivalence fin_zero_equiv'.symm) _, apply_instance, end | (n+1) := begin haveI := preserves_fin_of_preserves_binary_and_terminal n, intro f, refine preserves_limit_of_preserves_limit_cone (extend_fan_is_limit f (limit.is_limit _) (limit.is_limit _)) _, apply (is_limit_map_cone_fan_mk_equiv _ _ _).symm _, let := extend_fan_is_limit (Ξ» i, F.obj (f i)) (is_limit_of_has_product_of_preserves_limit F _) (is_limit_of_has_binary_product_of_preserves_limit F _ _), refine is_limit.of_iso_limit this _, apply cones.ext _ _, apply iso.refl _, rintro ⟨j⟩, apply fin.induction_on j, { apply (category.id_comp _).symm }, { rintro i -, dsimp only [extend_fan_Ο€_app, iso.refl_hom, fan.mk_Ο€_app], rw [fin.cases_succ, fin.cases_succ], change F.map _ ≫ _ = πŸ™ _ ≫ _, rw [id_comp, ←F.map_comp], refl } end /-- If `F` preserves the terminal object and binary products, then it preserves limits of shape `discrete (fin n)`. -/ def preserves_shape_fin_of_preserves_binary_and_terminal (n : β„•) : preserves_limits_of_shape (discrete (fin n)) F := { preserves_limit := Ξ» K, begin let : discrete.functor (Ξ» n, K.obj ⟨n⟩) β‰… K := discrete.nat_iso (Ξ» ⟨i⟩, iso.refl _), haveI := preserves_fin_of_preserves_binary_and_terminal F n (Ξ» n, K.obj ⟨n⟩), apply preserves_limit_of_iso_diagram F this, end } /-- If `F` preserves the terminal object and binary products then it preserves finite products. -/ def preserves_finite_products_of_preserves_binary_and_terminal (J : Type) [fintype J] : preserves_limits_of_shape (discrete J) F := begin classical, let e := fintype.equiv_fin J, haveI := preserves_shape_fin_of_preserves_binary_and_terminal F (fintype.card J), apply preserves_limits_of_shape_of_equiv.{0 0} (discrete.equivalence e).symm, end end preserves /-- Given `n+1` objects of `C`, a cofan for the last `n` with point `c₁.X` and a binary cofan on `c₁.X` and `f 0`, we can build a cofan for all `n+1`. In `extend_cofan_is_colimit` we show that if the two given cofans are colimits, then this cofan is also a colimit. -/ @[simps {rhs_md := semireducible}] def extend_cofan {n : β„•} {f : fin (n+1) β†’ C} (c₁ : cofan (Ξ» (i : fin n), f i.succ)) (cβ‚‚ : binary_cofan (f 0) c₁.X) : cofan f := cofan.mk cβ‚‚.X begin refine fin.cases _ _, { apply cβ‚‚.inl }, { intro i, apply c₁.ΞΉ.app ⟨i⟩ ≫ cβ‚‚.inr }, end /-- Show that if the two given cofans in `extend_cofan` are colimits, then the constructed cofan is also a colimit. -/ def extend_cofan_is_colimit {n : β„•} (f : fin (n+1) β†’ C) {c₁ : cofan (Ξ» (i : fin n), f i.succ)} {cβ‚‚ : binary_cofan (f 0) c₁.X} (t₁ : is_colimit c₁) (tβ‚‚ : is_colimit cβ‚‚) : is_colimit (extend_cofan c₁ cβ‚‚) := { desc := Ξ» s, begin apply (binary_cofan.is_colimit.desc' tβ‚‚ (s.ΞΉ.app ⟨0⟩) _).1, apply t₁.desc ⟨_, discrete.nat_trans (Ξ» i, s.ΞΉ.app ⟨i.as.succ⟩)⟩ end, fac' := Ξ» s, begin rintro ⟨j⟩, apply fin.induction_on j, { apply (binary_cofan.is_colimit.desc' tβ‚‚ _ _).2.1 }, { rintro i -, dsimp only [extend_cofan_ΞΉ_app], rw [fin.cases_succ, assoc, (binary_cofan.is_colimit.desc' tβ‚‚ _ _).2.2, t₁.fac], refl } end, uniq' := Ξ» s m w, begin apply binary_cofan.is_colimit.hom_ext tβ‚‚, { rw (binary_cofan.is_colimit.desc' tβ‚‚ _ _).2.1, apply w ⟨0⟩ }, { rw (binary_cofan.is_colimit.desc' tβ‚‚ _ _).2.2, apply t₁.uniq ⟨_, _⟩, rintro ⟨j⟩, dsimp only [discrete.nat_trans_app], rw ← w ⟨j.succ⟩, dsimp only [extend_cofan_ΞΉ_app], rw [fin.cases_succ, assoc], } end } section variables [has_binary_coproducts C] [has_initial C] /-- If `C` has an initial object and binary coproducts, then it has a coproduct for objects indexed by `fin n`. This is a helper lemma for `has_cofinite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_coproduct_fin : Ξ  (n : β„•) (f : fin n β†’ C), has_coproduct f | 0 := Ξ» f, begin letI : has_colimits_of_shape (discrete (fin 0)) C := has_colimits_of_shape_of_equivalence (discrete.equivalence.{0} fin_zero_equiv'.symm), apply_instance, end | (n+1) := Ξ» f, begin haveI := has_coproduct_fin n, apply has_colimit.mk ⟨_, extend_cofan_is_colimit f (colimit.is_colimit _) (colimit.is_colimit _)⟩, end /-- If `C` has an initial object and binary coproducts, then it has finite coproducts. -/ lemma has_finite_coproducts_of_has_binary_and_initial : has_finite_coproducts C := begin refine ⟨λ n, ⟨λ K, _⟩⟩, letI := has_coproduct_fin n (Ξ» n, K.obj ⟨n⟩), let : K β‰… discrete.functor (Ξ» n, K.obj ⟨n⟩) := discrete.nat_iso (Ξ» ⟨i⟩, iso.refl _), apply has_colimit_of_iso this, end end section preserves variables (F : C β₯€ D) variables [preserves_colimits_of_shape (discrete walking_pair) F] variables [preserves_colimits_of_shape (discrete.{0} pempty) F] variables [has_finite_coproducts.{v} C] /-- If `F` preserves the initial object and binary coproducts, then it preserves products indexed by `fin n` for any `n`. -/ noncomputable def preserves_fin_of_preserves_binary_and_initial : Ξ  (n : β„•) (f : fin n β†’ C), preserves_colimit (discrete.functor f) F | 0 := Ξ» f, begin letI : preserves_colimits_of_shape (discrete (fin 0)) F := preserves_colimits_of_shape_of_equiv.{0 0} (discrete.equivalence fin_zero_equiv'.symm) _, apply_instance, end | (n+1) := begin haveI := preserves_fin_of_preserves_binary_and_initial n, intro f, refine preserves_colimit_of_preserves_colimit_cocone (extend_cofan_is_colimit f (colimit.is_colimit _) (colimit.is_colimit _)) _, apply (is_colimit_map_cocone_cofan_mk_equiv _ _ _).symm _, let := extend_cofan_is_colimit (Ξ» i, F.obj (f i)) (is_colimit_of_has_coproduct_of_preserves_colimit F _) (is_colimit_of_has_binary_coproduct_of_preserves_colimit F _ _), refine is_colimit.of_iso_colimit this _, apply cocones.ext _ _, apply iso.refl _, rintro ⟨j⟩, apply fin.induction_on j, { apply category.comp_id }, { rintro i -, dsimp only [extend_cofan_ΞΉ_app, iso.refl_hom, cofan.mk_ΞΉ_app], rw [fin.cases_succ, fin.cases_succ], erw [comp_id, ←F.map_comp], refl, } end /-- If `F` preserves the initial object and binary coproducts, then it preserves colimits of shape `discrete (fin n)`. -/ def preserves_shape_fin_of_preserves_binary_and_initial (n : β„•) : preserves_colimits_of_shape (discrete (fin n)) F := { preserves_colimit := Ξ» K, begin let : discrete.functor (Ξ» n, K.obj ⟨n⟩) β‰… K := discrete.nat_iso (Ξ» ⟨i⟩, iso.refl _), haveI := preserves_fin_of_preserves_binary_and_initial F n (Ξ» n, K.obj ⟨n⟩), apply preserves_colimit_of_iso_diagram F this, end } /-- If `F` preserves the initial object and binary coproducts then it preserves finite products. -/ def preserves_finite_coproducts_of_preserves_binary_and_initial (J : Type) [fintype J] : preserves_colimits_of_shape (discrete J) F := begin classical, let e := fintype.equiv_fin J, haveI := preserves_shape_fin_of_preserves_binary_and_initial F (fintype.card J), apply preserves_colimits_of_shape_of_equiv.{0 0} (discrete.equivalence e).symm, end end preserves end category_theory
4abaa97ff49af047565c2305778e1536fa13de78
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/measure_theory/integration.lean
993b025888c5ec5d0dd5b62be63075a651ea52d2
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
70,178
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes HΓΆlzl -/ import measure_theory.measure_space import measure_theory.borel_space import data.indicator_function import data.support /-! # Lebesgue integral for `ennreal`-valued functions We define simple functions and show that each Borel measurable function on `ennreal` can be approximated by a sequence of simple functions. To prove something for an arbitrary measurable function into `ennreal`, the theorem `measurable.ennreal_induction` shows that is it sufficient to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. ## Notation We introduce the following notation for the lower Lebesgue integral of a function `f : Ξ± β†’ ennreal`. * `∫⁻ x, f x βˆ‚ΞΌ`: integral of a function `f : Ξ± β†’ ennreal` with respect to a measure `ΞΌ`; * `∫⁻ x, f x`: integral of a function `f : Ξ± β†’ ennreal` with respect to the canonical measure `volume` on `Ξ±`; * `∫⁻ x in s, f x βˆ‚ΞΌ`: integral of a function `f : Ξ± β†’ ennreal` over a set `s` with respect to a measure `ΞΌ`, defined as `∫⁻ x, f x βˆ‚(ΞΌ.restrict s)`; * `∫⁻ x in s, f x`: integral of a function `f : Ξ± β†’ ennreal` over a set `s` with respect to the canonical measure `volume`, defined as `∫⁻ x, f x βˆ‚(volume.restrict s)`. -/ noncomputable theory open set (hiding restrict restrict_apply) filter ennreal open_locale classical topological_space big_operators nnreal namespace measure_theory variables {Ξ± Ξ² Ξ³ Ξ΄ : Type*} /-- A function `f` from a measurable space to any type is called *simple*, if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles a function with these properties. -/ structure {u v} simple_func (Ξ± : Type u) [measurable_space Ξ±] (Ξ² : Type v) := (to_fun : Ξ± β†’ Ξ²) (is_measurable_fiber' : βˆ€ x, is_measurable (to_fun ⁻¹' {x})) (finite_range' : (set.range to_fun).finite) local infixr ` β†’β‚› `:25 := simple_func namespace simple_func section measurable variables [measurable_space Ξ±] instance has_coe_to_fun : has_coe_to_fun (Ξ± β†’β‚› Ξ²) := ⟨_, to_fun⟩ lemma coe_injective ⦃f g : Ξ± β†’β‚› β⦄ (H : ⇑f = g) : f = g := by cases f; cases g; congr; exact H @[ext] theorem ext {f g : Ξ± β†’β‚› Ξ²} (H : βˆ€ a, f a = g a) : f = g := coe_injective $ funext H lemma finite_range (f : Ξ± β†’β‚› Ξ²) : (set.range f).finite := f.finite_range' lemma is_measurable_fiber (f : Ξ± β†’β‚› Ξ²) (x : Ξ²) : is_measurable (f ⁻¹' {x}) := f.is_measurable_fiber' x /-- Range of a simple function `Ξ± β†’β‚› Ξ²` as a `finset Ξ²`. -/ protected def range (f : Ξ± β†’β‚› Ξ²) : finset Ξ² := f.finite_range.to_finset @[simp] theorem mem_range {f : Ξ± β†’β‚› Ξ²} {b} : b ∈ f.range ↔ b ∈ range f := finite.mem_to_finset theorem mem_range_self (f : Ξ± β†’β‚› Ξ²) (x : Ξ±) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ @[simp] lemma coe_range (f : Ξ± β†’β‚› Ξ²) : (↑f.range : set Ξ²) = set.range f := f.finite_range.coe_to_finset theorem mem_range_of_measure_ne_zero {f : Ξ± β†’β‚› Ξ²} {x : Ξ²} {ΞΌ : measure Ξ±} (H : ΞΌ (f ⁻¹' {x}) β‰  0) : x ∈ f.range := let ⟨a, ha⟩ := nonempty_of_measure_ne_zero H in mem_range.2 ⟨a, ha⟩ lemma forall_range_iff {f : Ξ± β†’β‚› Ξ²} {p : Ξ² β†’ Prop} : (βˆ€ y ∈ f.range, p y) ↔ βˆ€ x, p (f x) := by simp only [mem_range, set.forall_range_iff] lemma exists_range_iff {f : Ξ± β†’β‚› Ξ²} {p : Ξ² β†’ Prop} : (βˆƒ y ∈ f.range, p y) ↔ βˆƒ x, p (f x) := by simpa only [mem_range, exists_prop] using set.exists_range_iff lemma preimage_eq_empty_iff (f : Ξ± β†’β‚› Ξ²) (b : Ξ²) : f ⁻¹' {b} = βˆ… ↔ b βˆ‰ f.range := preimage_singleton_eq_empty.trans $ not_congr mem_range.symm /-- Constant function as a `simple_func`. -/ def const (Ξ±) {Ξ²} [measurable_space Ξ±] (b : Ξ²) : Ξ± β†’β‚› Ξ² := ⟨λ a, b, Ξ» x, is_measurable.const _, finite_range_const⟩ instance [inhabited Ξ²] : inhabited (Ξ± β†’β‚› Ξ²) := ⟨const _ (default _)⟩ theorem const_apply (a : Ξ±) (b : Ξ²) : (const Ξ± b) a = b := rfl @[simp] theorem coe_const (b : Ξ²) : ⇑(const Ξ± b) = function.const Ξ± b := rfl @[simp] lemma range_const (Ξ±) [measurable_space Ξ±] [nonempty Ξ±] (b : Ξ²) : (const Ξ± b).range = {b} := finset.coe_injective $ by simp lemma is_measurable_cut (r : Ξ± β†’ Ξ² β†’ Prop) (f : Ξ± β†’β‚› Ξ²) (h : βˆ€b, is_measurable {a | r a b}) : is_measurable {a | r a (f a)} := begin have : {a | r a (f a)} = ⋃ b ∈ range f, {a | r a b} ∩ f ⁻¹' {b}, { ext a, suffices : r a (f a) ↔ βˆƒ i, r a (f i) ∧ f a = f i, by simpa, exact ⟨λ h, ⟨a, ⟨h, rfl⟩⟩, Ξ» ⟨a', ⟨h', e⟩⟩, e.symm β–Έ h'⟩ }, rw this, exact is_measurable.bUnion f.finite_range.countable (Ξ» b _, is_measurable.inter (h b) (f.is_measurable_fiber _)) end theorem is_measurable_preimage (f : Ξ± β†’β‚› Ξ²) (s) : is_measurable (f ⁻¹' s) := is_measurable_cut (Ξ» _ b, b ∈ s) f (Ξ» b, is_measurable.const (b ∈ s)) /-- A simple function is measurable -/ protected theorem measurable [measurable_space Ξ²] (f : Ξ± β†’β‚› Ξ²) : measurable f := Ξ» s _, is_measurable_preimage f s protected lemma sum_measure_preimage_singleton (f : Ξ± β†’β‚› Ξ²) {ΞΌ : measure Ξ±} (s : finset Ξ²) : βˆ‘ y in s, ΞΌ (f ⁻¹' {y}) = ΞΌ (f ⁻¹' ↑s) := sum_measure_preimage_singleton _ (Ξ» _ _, f.is_measurable_fiber _) lemma sum_range_measure_preimage_singleton (f : Ξ± β†’β‚› Ξ²) (ΞΌ : measure Ξ±) : βˆ‘ y in f.range, ΞΌ (f ⁻¹' {y}) = ΞΌ univ := by rw [f.sum_measure_preimage_singleton, coe_range, preimage_range] /-- If-then-else as a `simple_func`. -/ def piecewise (s : set Ξ±) (hs : is_measurable s) (f g : Ξ± β†’β‚› Ξ²) : Ξ± β†’β‚› Ξ² := ⟨s.piecewise f g, Ξ» x, by letI : measurable_space Ξ² := ⊀; exact f.measurable.piecewise hs g.measurable trivial, (f.finite_range.union g.finite_range).subset range_ite_subset⟩ @[simp] theorem coe_piecewise {s : set Ξ±} (hs : is_measurable s) (f g : Ξ± β†’β‚› Ξ²) : ⇑(piecewise s hs f g) = s.piecewise f g := rfl theorem piecewise_apply {s : set Ξ±} (hs : is_measurable s) (f g : Ξ± β†’β‚› Ξ²) (a) : piecewise s hs f g a = if a ∈ s then f a else g a := rfl @[simp] lemma piecewise_compl {s : set Ξ±} (hs : is_measurable sᢜ) (f g : Ξ± β†’β‚› Ξ²) : piecewise sᢜ hs f g = piecewise s hs.of_compl g f := coe_injective $ by simp [hs] @[simp] lemma piecewise_univ (f g : Ξ± β†’β‚› Ξ²) : piecewise univ is_measurable.univ f g = f := coe_injective $ by simp @[simp] lemma piecewise_empty (f g : Ξ± β†’β‚› Ξ²) : piecewise βˆ… is_measurable.empty f g = g := coe_injective $ by simp lemma measurable_bind [measurable_space Ξ³] (f : Ξ± β†’β‚› Ξ²) (g : Ξ² β†’ Ξ± β†’ Ξ³) (hg : βˆ€ b, measurable (g b)) : measurable (Ξ» a, g (f a) a) := Ξ» s hs, f.is_measurable_cut (Ξ» a b, g b a ∈ s) $ Ξ» b, hg b hs /-- If `f : Ξ± β†’β‚› Ξ²` is a simple function and `g : Ξ² β†’ Ξ± β†’β‚› Ξ³` is a family of simple functions, then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/ def bind (f : Ξ± β†’β‚› Ξ²) (g : Ξ² β†’ Ξ± β†’β‚› Ξ³) : Ξ± β†’β‚› Ξ³ := ⟨λa, g (f a) a, Ξ» c, f.is_measurable_cut (Ξ» a b, g b a = c) $ Ξ» b, (g b).is_measurable_preimage {c}, (f.finite_range.bUnion (Ξ» b _, (g b).finite_range)).subset $ by rintro _ ⟨a, rfl⟩; simp; exact ⟨a, a, rfl⟩⟩ @[simp] theorem bind_apply (f : Ξ± β†’β‚› Ξ²) (g : Ξ² β†’ Ξ± β†’β‚› Ξ³) (a) : f.bind g a = g (f a) a := rfl /-- Given a function `g : Ξ² β†’ Ξ³` and a simple function `f : Ξ± β†’β‚› Ξ²`, `f.map g` return the simple function `g ∘ f : Ξ± β†’β‚› Ξ³` -/ def map (g : Ξ² β†’ Ξ³) (f : Ξ± β†’β‚› Ξ²) : Ξ± β†’β‚› Ξ³ := bind f (const Ξ± ∘ g) theorem map_apply (g : Ξ² β†’ Ξ³) (f : Ξ± β†’β‚› Ξ²) (a) : f.map g a = g (f a) := rfl theorem map_map (g : Ξ² β†’ Ξ³) (h: Ξ³ β†’ Ξ΄) (f : Ξ± β†’β‚› Ξ²) : (f.map g).map h = f.map (h ∘ g) := rfl @[simp] theorem coe_map (g : Ξ² β†’ Ξ³) (f : Ξ± β†’β‚› Ξ²) : (f.map g : Ξ± β†’ Ξ³) = g ∘ f := rfl @[simp] theorem range_map [decidable_eq Ξ³] (g : Ξ² β†’ Ξ³) (f : Ξ± β†’β‚› Ξ²) : (f.map g).range = f.range.image g := finset.coe_injective $ by simp [range_comp] @[simp] theorem map_const (g : Ξ² β†’ Ξ³) (b : Ξ²) : (const Ξ± b).map g = const Ξ± (g b) := rfl lemma map_preimage (f : Ξ± β†’β‚› Ξ²) (g : Ξ² β†’ Ξ³) (s : set Ξ³) : (f.map g) ⁻¹' s = f ⁻¹' ↑(f.range.filter (Ξ»b, g b ∈ s)) := by { simp only [coe_range, sep_mem_eq, set.mem_range, function.comp_app, coe_map, finset.coe_filter, ← mem_preimage, inter_comm, preimage_inter_range], apply preimage_comp } lemma map_preimage_singleton (f : Ξ± β†’β‚› Ξ²) (g : Ξ² β†’ Ξ³) (c : Ξ³) : (f.map g) ⁻¹' {c} = f ⁻¹' ↑(f.range.filter (Ξ» b, g b = c)) := map_preimage _ _ _ /-- Composition of a `simple_fun` and a measurable function is a `simple_func`. -/ def comp [measurable_space Ξ²] (f : Ξ² β†’β‚› Ξ³) (g : Ξ± β†’ Ξ²) (hgm : measurable g) : Ξ± β†’β‚› Ξ³ := { to_fun := f ∘ g, finite_range' := f.finite_range.subset $ set.range_comp_subset_range _ _, is_measurable_fiber' := Ξ» z, hgm (f.is_measurable_fiber z) } @[simp] lemma coe_comp [measurable_space Ξ²] (f : Ξ² β†’β‚› Ξ³) {g : Ξ± β†’ Ξ²} (hgm : measurable g) : ⇑(f.comp g hgm) = f ∘ g := rfl lemma range_comp_subset_range [measurable_space Ξ²] (f : Ξ² β†’β‚› Ξ³) {g : Ξ± β†’ Ξ²} (hgm : measurable g) : (f.comp g hgm).range βŠ† f.range := finset.coe_subset.1 $ by simp only [coe_range, coe_comp, set.range_comp_subset_range] /-- If `f` is a simple function taking values in `Ξ² β†’ Ξ³` and `g` is another simple function with the same domain and codomain `Ξ²`, then `f.seq g = f a (g a)`. -/ def seq (f : Ξ± β†’β‚› (Ξ² β†’ Ξ³)) (g : Ξ± β†’β‚› Ξ²) : Ξ± β†’β‚› Ξ³ := f.bind (Ξ»f, g.map f) @[simp] lemma seq_apply (f : Ξ± β†’β‚› (Ξ² β†’ Ξ³)) (g : Ξ± β†’β‚› Ξ²) (a : Ξ±) : f.seq g a = f a (g a) := rfl /-- Combine two simple functions `f : Ξ± β†’β‚› Ξ²` and `g : Ξ± β†’β‚› Ξ²` into `Ξ» a, (f a, g a)`. -/ def pair (f : Ξ± β†’β‚› Ξ²) (g : Ξ± β†’β‚› Ξ³) : Ξ± β†’β‚› (Ξ² Γ— Ξ³) := (f.map prod.mk).seq g @[simp] lemma pair_apply (f : Ξ± β†’β‚› Ξ²) (g : Ξ± β†’β‚› Ξ³) (a) : pair f g a = (f a, g a) := rfl lemma pair_preimage (f : Ξ± β†’β‚› Ξ²) (g : Ξ± β†’β‚› Ξ³) (s : set Ξ²) (t : set Ξ³) : (pair f g) ⁻¹' (set.prod s t) = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl /- A special form of `pair_preimage` -/ lemma pair_preimage_singleton (f : Ξ± β†’β‚› Ξ²) (g : Ξ± β†’β‚› Ξ³) (b : Ξ²) (c : Ξ³) : (pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) := by { rw ← singleton_prod_singleton, exact pair_preimage _ _ _ _ } theorem bind_const (f : Ξ± β†’β‚› Ξ²) : f.bind (const Ξ±) = f := by ext; simp instance [has_zero Ξ²] : has_zero (Ξ± β†’β‚› Ξ²) := ⟨const Ξ± 0⟩ instance [has_add Ξ²] : has_add (Ξ± β†’β‚› Ξ²) := ⟨λf g, (f.map (+)).seq g⟩ instance [has_mul Ξ²] : has_mul (Ξ± β†’β‚› Ξ²) := ⟨λf g, (f.map (*)).seq g⟩ instance [has_sup Ξ²] : has_sup (Ξ± β†’β‚› Ξ²) := ⟨λf g, (f.map (βŠ”)).seq g⟩ instance [has_inf Ξ²] : has_inf (Ξ± β†’β‚› Ξ²) := ⟨λf g, (f.map (βŠ“)).seq g⟩ instance [has_le Ξ²] : has_le (Ξ± β†’β‚› Ξ²) := ⟨λf g, βˆ€a, f a ≀ g a⟩ @[simp, norm_cast] lemma coe_zero [has_zero Ξ²] : ⇑(0 : Ξ± β†’β‚› Ξ²) = 0 := rfl @[simp] lemma const_zero [has_zero Ξ²] : const Ξ± (0:Ξ²) = 0 := rfl @[simp, norm_cast] lemma coe_add [has_add Ξ²] (f g : Ξ± β†’β‚› Ξ²) : ⇑(f + g) = f + g := rfl @[simp, norm_cast] lemma coe_mul [has_mul Ξ²] (f g : Ξ± β†’β‚› Ξ²) : ⇑(f * g) = f * g := rfl @[simp, norm_cast] lemma coe_le [preorder Ξ²] {f g : Ξ± β†’β‚› Ξ²} : (f : Ξ± β†’ Ξ²) ≀ g ↔ f ≀ g := iff.rfl @[simp] lemma range_zero [nonempty Ξ±] [has_zero Ξ²] : (0 : Ξ± β†’β‚› Ξ²).range = {0} := finset.ext $ Ξ» x, by simp [eq_comm] lemma eq_zero_of_mem_range_zero [has_zero Ξ²] : βˆ€ {y : Ξ²}, y ∈ (0 : Ξ± β†’β‚› Ξ²).range β†’ y = 0 := forall_range_iff.2 $ Ξ» x, rfl lemma sup_apply [has_sup Ξ²] (f g : Ξ± β†’β‚› Ξ²) (a : Ξ±) : (f βŠ” g) a = f a βŠ” g a := rfl lemma mul_apply [has_mul Ξ²] (f g : Ξ± β†’β‚› Ξ²) (a : Ξ±) : (f * g) a = f a * g a := rfl lemma add_apply [has_add Ξ²] (f g : Ξ± β†’β‚› Ξ²) (a : Ξ±) : (f + g) a = f a + g a := rfl lemma add_eq_mapβ‚‚ [has_add Ξ²] (f g : Ξ± β†’β‚› Ξ²) : f + g = (pair f g).map (Ξ»p:Ξ²Γ—Ξ², p.1 + p.2) := rfl lemma mul_eq_mapβ‚‚ [has_mul Ξ²] (f g : Ξ± β†’β‚› Ξ²) : f * g = (pair f g).map (Ξ»p:Ξ²Γ—Ξ², p.1 * p.2) := rfl lemma sup_eq_mapβ‚‚ [has_sup Ξ²] (f g : Ξ± β†’β‚› Ξ²) : f βŠ” g = (pair f g).map (Ξ»p:Ξ²Γ—Ξ², p.1 βŠ” p.2) := rfl lemma const_mul_eq_map [has_mul Ξ²] (f : Ξ± β†’β‚› Ξ²) (b : Ξ²) : const Ξ± b * f = f.map (Ξ»a, b * a) := rfl instance [add_monoid Ξ²] : add_monoid (Ξ± β†’β‚› Ξ²) := function.injective.add_monoid (Ξ» f, show Ξ± β†’ Ξ², from f) coe_injective coe_zero coe_add instance add_comm_monoid [add_comm_monoid Ξ²] : add_comm_monoid (Ξ± β†’β‚› Ξ²) := function.injective.add_comm_monoid (Ξ» f, show Ξ± β†’ Ξ², from f) coe_injective coe_zero coe_add instance [has_neg Ξ²] : has_neg (Ξ± β†’β‚› Ξ²) := ⟨λf, f.map (has_neg.neg)⟩ @[simp, norm_cast] lemma coe_neg [has_neg Ξ²] (f : Ξ± β†’β‚› Ξ²) : ⇑(-f) = -f := rfl instance [add_group Ξ²] : add_group (Ξ± β†’β‚› Ξ²) := function.injective.add_group (Ξ» f, show Ξ± β†’ Ξ², from f) coe_injective coe_zero coe_add coe_neg @[simp, norm_cast] lemma coe_sub [add_group Ξ²] (f g : Ξ± β†’β‚› Ξ²) : ⇑(f - g) = f - g := rfl instance [add_comm_group Ξ²] : add_comm_group (Ξ± β†’β‚› Ξ²) := function.injective.add_comm_group (Ξ» f, show Ξ± β†’ Ξ², from f) coe_injective coe_zero coe_add coe_neg variables {K : Type*} instance [has_scalar K Ξ²] : has_scalar K (Ξ± β†’β‚› Ξ²) := ⟨λk f, f.map ((β€’) k)⟩ @[simp] lemma coe_smul [has_scalar K Ξ²] (c : K) (f : Ξ± β†’β‚› Ξ²) : ⇑(c β€’ f) = c β€’ f := rfl lemma smul_apply [has_scalar K Ξ²] (k : K) (f : Ξ± β†’β‚› Ξ²) (a : Ξ±) : (k β€’ f) a = k β€’ f a := rfl instance [semiring K] [add_comm_monoid Ξ²] [semimodule K Ξ²] : semimodule K (Ξ± β†’β‚› Ξ²) := function.injective.semimodule K ⟨λ f, show Ξ± β†’ Ξ², from f, coe_zero, coe_add⟩ coe_injective coe_smul lemma smul_eq_map [has_scalar K Ξ²] (k : K) (f : Ξ± β†’β‚› Ξ²) : k β€’ f = f.map ((β€’) k) := rfl instance [preorder Ξ²] : preorder (Ξ± β†’β‚› Ξ²) := { le_refl := Ξ»f a, le_refl _, le_trans := Ξ»f g h hfg hgh a, le_trans (hfg _) (hgh a), .. simple_func.has_le } instance [partial_order Ξ²] : partial_order (Ξ± β†’β‚› Ξ²) := { le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a), .. simple_func.preorder } instance [order_bot Ξ²] : order_bot (Ξ± β†’β‚› Ξ²) := { bot := const Ξ± βŠ₯, bot_le := Ξ»f a, bot_le, .. simple_func.partial_order } instance [order_top Ξ²] : order_top (Ξ± β†’β‚› Ξ²) := { top := const Ξ± ⊀, le_top := Ξ»f a, le_top, .. simple_func.partial_order } instance [semilattice_inf Ξ²] : semilattice_inf (Ξ± β†’β‚› Ξ²) := { inf := (βŠ“), inf_le_left := assume f g a, inf_le_left, inf_le_right := assume f g a, inf_le_right, le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup Ξ²] : semilattice_sup (Ξ± β†’β‚› Ξ²) := { sup := (βŠ”), le_sup_left := assume f g a, le_sup_left, le_sup_right := assume f g a, le_sup_right, sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup_bot Ξ²] : semilattice_sup_bot (Ξ± β†’β‚› Ξ²) := { .. simple_func.semilattice_sup,.. simple_func.order_bot } instance [lattice Ξ²] : lattice (Ξ± β†’β‚› Ξ²) := { .. simple_func.semilattice_sup,.. simple_func.semilattice_inf } instance [bounded_lattice Ξ²] : bounded_lattice (Ξ± β†’β‚› Ξ²) := { .. simple_func.lattice, .. simple_func.order_bot, .. simple_func.order_top } lemma finset_sup_apply [semilattice_sup_bot Ξ²] {f : Ξ³ β†’ Ξ± β†’β‚› Ξ²} (s : finset Ξ³) (a : Ξ±) : s.sup f a = s.sup (Ξ»c, f c a) := begin refine finset.induction_on s rfl _, assume a s hs ih, rw [finset.sup_insert, finset.sup_insert, sup_apply, ih] end section restrict variables [has_zero Ξ²] /-- Restrict a simple function `f : Ξ± β†’β‚› Ξ²` to a set `s`. If `s` is measurable, then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const Ξ± 0`. -/ def restrict (f : Ξ± β†’β‚› Ξ²) (s : set Ξ±) : Ξ± β†’β‚› Ξ² := if hs : is_measurable s then piecewise s hs f 0 else 0 theorem restrict_of_not_measurable {f : Ξ± β†’β‚› Ξ²} {s : set Ξ±} (hs : Β¬is_measurable s) : restrict f s = 0 := dif_neg hs @[simp] theorem coe_restrict (f : Ξ± β†’β‚› Ξ²) {s : set Ξ±} (hs : is_measurable s) : ⇑(restrict f s) = indicator s f := by { rw [restrict, dif_pos hs], refl } @[simp] theorem restrict_univ (f : Ξ± β†’β‚› Ξ²) : restrict f univ = f := by simp [restrict] @[simp] theorem restrict_empty (f : Ξ± β†’β‚› Ξ²) : restrict f βˆ… = 0 := by simp [restrict] theorem map_restrict_of_zero [has_zero Ξ³] {g : Ξ² β†’ Ξ³} (hg : g 0 = 0) (f : Ξ± β†’β‚› Ξ²) (s : set Ξ±) : (f.restrict s).map g = (f.map g).restrict s := ext $ Ξ» x, if hs : is_measurable s then by simp [hs, set.indicator_comp_of_zero hg] else by simp [restrict_of_not_measurable hs, hg] theorem map_coe_ennreal_restrict (f : Ξ± β†’β‚› nnreal) (s : set Ξ±) : (f.restrict s).map (coe : nnreal β†’ ennreal) = (f.map coe).restrict s := map_restrict_of_zero ennreal.coe_zero _ _ theorem map_coe_nnreal_restrict (f : Ξ± β†’β‚› nnreal) (s : set Ξ±) : (f.restrict s).map (coe : nnreal β†’ ℝ) = (f.map coe).restrict s := map_restrict_of_zero nnreal.coe_zero _ _ theorem restrict_apply (f : Ξ± β†’β‚› Ξ²) {s : set Ξ±} (hs : is_measurable s) (a) : restrict f s a = if a ∈ s then f a else 0 := by simp only [hs, coe_restrict] theorem restrict_preimage (f : Ξ± β†’β‚› Ξ²) {s : set Ξ±} (hs : is_measurable s) {t : set Ξ²} (ht : (0:Ξ²) βˆ‰ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by simp [hs, indicator_preimage_of_not_mem _ _ ht] theorem restrict_preimage_singleton (f : Ξ± β†’β‚› Ξ²) {s : set Ξ±} (hs : is_measurable s) {r : Ξ²} (hr : r β‰  0) : restrict f s ⁻¹' {r} = s ∩ f ⁻¹' {r} := f.restrict_preimage hs hr.symm lemma mem_restrict_range {r : Ξ²} {s : set Ξ±} {f : Ξ± β†’β‚› Ξ²} (hs : is_measurable s) : r ∈ (restrict f s).range ↔ (r = 0 ∧ s β‰  univ) ∨ (r ∈ f '' s) := by rw [← finset.mem_coe, coe_range, coe_restrict _ hs, mem_range_indicator] lemma mem_image_of_mem_range_restrict {r : Ξ²} {s : set Ξ±} {f : Ξ± β†’β‚› Ξ²} (hr : r ∈ (restrict f s).range) (h0 : r β‰  0) : r ∈ f '' s := if hs : is_measurable s then by simpa [mem_restrict_range hs, h0] using hr else by { rw [restrict_of_not_measurable hs] at hr, exact (h0 $ eq_zero_of_mem_range_zero hr).elim } @[mono] lemma restrict_mono [preorder Ξ²] (s : set Ξ±) {f g : Ξ± β†’β‚› Ξ²} (H : f ≀ g) : f.restrict s ≀ g.restrict s := if hs : is_measurable s then Ξ» x, by simp only [coe_restrict _ hs, indicator_le_indicator (H x)] else by simp only [restrict_of_not_measurable hs, le_refl] end restrict section approx section variables [semilattice_sup_bot Ξ²] [has_zero Ξ²] /-- Fix a sequence `i : β„• β†’ Ξ²`. Given a function `Ξ± β†’ Ξ²`, its `n`-th approximation by simple functions is defined so that in case `Ξ² = ennreal` it sends each `a` to the supremum of the set `{i k | k ≀ n ∧ i k ≀ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/ def approx (i : β„• β†’ Ξ²) (f : Ξ± β†’ Ξ²) (n : β„•) : Ξ± β†’β‚› Ξ² := (finset.range n).sup (Ξ»k, restrict (const Ξ± (i k)) {a:Ξ± | i k ≀ f a}) lemma approx_apply [topological_space Ξ²] [order_closed_topology Ξ²] [measurable_space Ξ²] [opens_measurable_space Ξ²] {i : β„• β†’ Ξ²} {f : Ξ± β†’ Ξ²} {n : β„•} (a : Ξ±) (hf : measurable f) : (approx i f n : Ξ± β†’β‚› Ξ²) a = (finset.range n).sup (Ξ»k, if i k ≀ f a then i k else 0) := begin dsimp only [approx], rw [finset_sup_apply], congr, funext k, rw [restrict_apply], refl, exact (hf is_measurable_Ici) end lemma monotone_approx (i : β„• β†’ Ξ²) (f : Ξ± β†’ Ξ²) : monotone (approx i f) := assume n m h, finset.sup_mono $ finset.range_subset.2 h lemma approx_comp [topological_space Ξ²] [order_closed_topology Ξ²] [measurable_space Ξ²] [opens_measurable_space Ξ²] [measurable_space Ξ³] {i : β„• β†’ Ξ²} {f : Ξ³ β†’ Ξ²} {g : Ξ± β†’ Ξ³} {n : β„•} (a : Ξ±) (hf : measurable f) (hg : measurable g) : (approx i (f ∘ g) n : Ξ± β†’β‚› Ξ²) a = (approx i f n : Ξ³ β†’β‚› Ξ²) (g a) := by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)] end lemma supr_approx_apply [topological_space Ξ²] [complete_lattice Ξ²] [order_closed_topology Ξ²] [has_zero Ξ²] [measurable_space Ξ²] [opens_measurable_space Ξ²] (i : β„• β†’ Ξ²) (f : Ξ± β†’ Ξ²) (a : Ξ±) (hf : measurable f) (h_zero : (0 : Ξ²) = βŠ₯) : (⨆n, (approx i f n : Ξ± β†’β‚› Ξ²) a) = (⨆k (h : i k ≀ f a), i k) := begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _), { rw [approx_apply a hf, h_zero], refine finset.sup_le (assume k hk, _), split_ifs, exact le_supr_of_le k (le_supr _ h), exact bot_le }, { refine le_supr_of_le (k+1) _, rw [approx_apply a hf], have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _), refine le_trans (le_of_eq _) (finset.le_sup this), rw [if_pos hk] } end end approx section eapprox /-- A sequence of `ennreal`s such that its range is the set of non-negative rational numbers. -/ def ennreal_rat_embed (n : β„•) : ennreal := ennreal.of_real ((encodable.decode β„š n).get_or_else (0 : β„š)) lemma ennreal_rat_embed_encode (q : β„š) : ennreal_rat_embed (encodable.encode q) = nnreal.of_real q := by rw [ennreal_rat_embed, encodable.encodek]; refl /-- Approximate a function `Ξ± β†’ ennreal` by a sequence of simple functions. -/ def eapprox : (Ξ± β†’ ennreal) β†’ β„• β†’ Ξ± β†’β‚› ennreal := approx ennreal_rat_embed lemma monotone_eapprox (f : Ξ± β†’ ennreal) : monotone (eapprox f) := monotone_approx _ f lemma supr_eapprox_apply (f : Ξ± β†’ ennreal) (hf : measurable f) (a : Ξ±) : (⨆n, (eapprox f n : Ξ± β†’β‚› ennreal) a) = f a := begin rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl], refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _), assume h, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩, have : (nnreal.of_real q : ennreal) ≀ (⨆ (k : β„•) (h : ennreal_rat_embed k ≀ f a), ennreal_rat_embed k), { refine le_supr_of_le (encodable.encode q) _, rw [ennreal_rat_embed_encode q], refine le_supr_of_le (le_of_lt q_lt) _, exact le_refl _ }, exact lt_irrefl _ (lt_of_le_of_lt this lt_q) end lemma eapprox_comp [measurable_space Ξ³] {f : Ξ³ β†’ ennreal} {g : Ξ± β†’ Ξ³} {n : β„•} (hf : measurable f) (hg : measurable g) : (eapprox (f ∘ g) n : Ξ± β†’ ennreal) = (eapprox f n : Ξ³ β†’β‚› ennreal) ∘ g := funext $ assume a, approx_comp a hf hg end eapprox end measurable section measure variables [measurable_space Ξ±] {ΞΌ : measure Ξ±} /-- Integral of a simple function whose codomain is `ennreal`. -/ def lintegral (f : Ξ± β†’β‚› ennreal) (ΞΌ : measure Ξ±) : ennreal := βˆ‘ x in f.range, x * ΞΌ (f ⁻¹' {x}) lemma lintegral_eq_of_subset (f : Ξ± β†’β‚› ennreal) {s : finset ennreal} (hs : βˆ€ x, f x β‰  0 β†’ ΞΌ (f ⁻¹' {f x}) β‰  0 β†’ f x ∈ s) : f.lintegral ΞΌ = βˆ‘ x in s, x * ΞΌ (f ⁻¹' {x}) := begin refine finset.sum_bij_ne_zero (Ξ»r _ _, r) _ _ _ _, { simpa only [forall_range_iff, mul_ne_zero_iff, and_imp] }, { intros, assumption }, { intros b _ hb, refine ⟨b, _, hb, rfl⟩, rw [mem_range, ← preimage_singleton_nonempty], exact nonempty_of_measure_ne_zero (mul_ne_zero_iff.1 hb).2 }, { intros, refl } end /-- Calculate the integral of `(g ∘ f)`, where `g : Ξ² β†’ ennreal` and `f : Ξ± β†’β‚› Ξ²`. -/ lemma map_lintegral (g : Ξ² β†’ ennreal) (f : Ξ± β†’β‚› Ξ²) : (f.map g).lintegral ΞΌ = βˆ‘ x in f.range, g x * ΞΌ (f ⁻¹' {x}) := begin simp only [lintegral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, ← f.sum_measure_preimage_singleton, finset.mul_sum], refine finset.sum_congr _ _, { congr }, { assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h }, end lemma add_lintegral (f g : Ξ± β†’β‚› ennreal) : (f + g).lintegral ΞΌ = f.lintegral ΞΌ + g.lintegral ΞΌ := calc (f + g).lintegral ΞΌ = βˆ‘ x in (pair f g).range, (x.1 * ΞΌ (pair f g ⁻¹' {x}) + x.2 * ΞΌ (pair f g ⁻¹' {x})) : by rw [add_eq_mapβ‚‚, map_lintegral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _) ... = βˆ‘ x in (pair f g).range, x.1 * ΞΌ (pair f g ⁻¹' {x}) + βˆ‘ x in (pair f g).range, x.2 * ΞΌ (pair f g ⁻¹' {x}) : by rw [finset.sum_add_distrib] ... = ((pair f g).map prod.fst).lintegral ΞΌ + ((pair f g).map prod.snd).lintegral ΞΌ : by rw [map_lintegral, map_lintegral] ... = lintegral f ΞΌ + lintegral g ΞΌ : rfl lemma const_mul_lintegral (f : Ξ± β†’β‚› ennreal) (x : ennreal) : (const Ξ± x * f).lintegral ΞΌ = x * f.lintegral ΞΌ := calc (f.map (Ξ»a, x * a)).lintegral ΞΌ = βˆ‘ r in f.range, x * r * ΞΌ (f ⁻¹' {r}) : map_lintegral _ _ ... = βˆ‘ r in f.range, x * (r * ΞΌ (f ⁻¹' {r})) : finset.sum_congr rfl (assume a ha, mul_assoc _ _ _) ... = x * f.lintegral ΞΌ : finset.mul_sum.symm /-- Integral of a simple function `Ξ± β†’β‚› ennreal` as a bilinear map. -/ def lintegralβ‚— : (Ξ± β†’β‚› ennreal) β†’β‚—[ennreal] measure Ξ± β†’β‚—[ennreal] ennreal := { to_fun := Ξ» f, { to_fun := lintegral f, map_add' := by simp [lintegral, mul_add, finset.sum_add_distrib], map_smul' := Ξ» c ΞΌ, by simp [lintegral, mul_left_comm _ c, finset.mul_sum] }, map_add' := Ξ» f g, linear_map.ext (Ξ» ΞΌ, add_lintegral f g), map_smul' := Ξ» c f, linear_map.ext (Ξ» ΞΌ, const_mul_lintegral f c) } @[simp] lemma zero_lintegral : (0 : Ξ± β†’β‚› ennreal).lintegral ΞΌ = 0 := linear_map.ext_iff.1 lintegralβ‚—.map_zero ΞΌ lemma lintegral_add {Ξ½} (f : Ξ± β†’β‚› ennreal) : f.lintegral (ΞΌ + Ξ½) = f.lintegral ΞΌ + f.lintegral Ξ½ := (lintegralβ‚— f).map_add ΞΌ Ξ½ lemma lintegral_smul (f : Ξ± β†’β‚› ennreal) (c : ennreal) : f.lintegral (c β€’ ΞΌ) = c β€’ f.lintegral ΞΌ := (lintegralβ‚— f).map_smul c ΞΌ @[simp] lemma lintegral_zero (f : Ξ± β†’β‚› ennreal) : f.lintegral 0 = 0 := (lintegralβ‚— f).map_zero lemma lintegral_sum {ΞΉ} (f : Ξ± β†’β‚› ennreal) (ΞΌ : ΞΉ β†’ measure Ξ±) : f.lintegral (measure.sum ΞΌ) = βˆ‘' i, f.lintegral (ΞΌ i) := begin simp only [lintegral, measure.sum_apply, f.is_measurable_preimage, ← finset.tsum_subtype, ← ennreal.tsum_mul_left], apply ennreal.tsum_comm end lemma restrict_lintegral (f : Ξ± β†’β‚› ennreal) {s : set Ξ±} (hs : is_measurable s) : (restrict f s).lintegral ΞΌ = βˆ‘ r in f.range, r * ΞΌ (f ⁻¹' {r} ∩ s) := calc (restrict f s).lintegral ΞΌ = βˆ‘ r in f.range, r * ΞΌ (restrict f s ⁻¹' {r}) : lintegral_eq_of_subset _ $ Ξ» x hx, if hxs : x ∈ s then by simp [f.restrict_apply hs, if_pos hxs, mem_range_self] else false.elim $ hx $ by simp [*] ... = βˆ‘ r in f.range, r * ΞΌ (f ⁻¹' {r} ∩ s) : finset.sum_congr rfl $ forall_range_iff.2 $ Ξ» b, if hb : f b = 0 then by simp only [hb, zero_mul] else by rw [restrict_preimage_singleton _ hs hb, inter_comm] lemma lintegral_restrict (f : Ξ± β†’β‚› ennreal) (s : set Ξ±) (ΞΌ : measure Ξ±) : f.lintegral (ΞΌ.restrict s) = βˆ‘ y in f.range, y * ΞΌ (f ⁻¹' {y} ∩ s) := by simp only [lintegral, measure.restrict_apply, f.is_measurable_preimage] lemma restrict_lintegral_eq_lintegral_restrict (f : Ξ± β†’β‚› ennreal) {s : set Ξ±} (hs : is_measurable s) : (restrict f s).lintegral ΞΌ = f.lintegral (ΞΌ.restrict s) := by rw [f.restrict_lintegral hs, lintegral_restrict] lemma const_lintegral (c : ennreal) : (const Ξ± c).lintegral ΞΌ = c * ΞΌ univ := begin rw [lintegral], by_cases ha : nonempty Ξ±, { resetI, simp [preimage_const_of_mem] }, { simp [ΞΌ.eq_zero_of_not_nonempty ha] } end lemma const_lintegral_restrict (c : ennreal) (s : set Ξ±) : (const Ξ± c).lintegral (ΞΌ.restrict s) = c * ΞΌ s := by rw [const_lintegral, measure.restrict_apply is_measurable.univ, univ_inter] lemma restrict_const_lintegral (c : ennreal) {s : set Ξ±} (hs : is_measurable s) : ((const Ξ± c).restrict s).lintegral ΞΌ = c * ΞΌ s := by rw [restrict_lintegral_eq_lintegral_restrict _ hs, const_lintegral_restrict] lemma le_sup_lintegral (f g : Ξ± β†’β‚› ennreal) : f.lintegral ΞΌ βŠ” g.lintegral ΞΌ ≀ (f βŠ” g).lintegral ΞΌ := calc f.lintegral ΞΌ βŠ” g.lintegral ΞΌ = ((pair f g).map prod.fst).lintegral ΞΌ βŠ” ((pair f g).map prod.snd).lintegral ΞΌ : rfl ... ≀ βˆ‘ x in (pair f g).range, (x.1 βŠ” x.2) * ΞΌ (pair f g ⁻¹' {x}) : begin rw [map_lintegral, map_lintegral], refine sup_le _ _; refine finset.sum_le_sum (Ξ» a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)), exact le_sup_left, exact le_sup_right end ... = (f βŠ” g).lintegral ΞΌ : by rw [sup_eq_mapβ‚‚, map_lintegral] /-- `simple_func.lintegral` is monotone both in function and in measure. -/ @[mono] lemma lintegral_mono {f g : Ξ± β†’β‚› ennreal} (hfg : f ≀ g) {ΞΌ Ξ½ : measure Ξ±} (hΞΌΞ½ : ΞΌ ≀ Ξ½) : f.lintegral ΞΌ ≀ g.lintegral Ξ½ := calc f.lintegral ΞΌ ≀ f.lintegral ΞΌ βŠ” g.lintegral ΞΌ : le_sup_left ... ≀ (f βŠ” g).lintegral ΞΌ : le_sup_lintegral _ _ ... = g.lintegral ΞΌ : by rw [sup_of_le_right hfg] ... ≀ g.lintegral Ξ½ : finset.sum_le_sum $ Ξ» y hy, ennreal.mul_left_mono $ hΞΌΞ½ _ (g.is_measurable_preimage _) /-- `simple_func.lintegral` depends only on the measures of `f ⁻¹' {y}`. -/ lemma lintegral_eq_of_measure_preimage [measurable_space Ξ²] {f : Ξ± β†’β‚› ennreal} {g : Ξ² β†’β‚› ennreal} {Ξ½ : measure Ξ²} (H : βˆ€ y, ΞΌ (f ⁻¹' {y}) = Ξ½ (g ⁻¹' {y})) : f.lintegral ΞΌ = g.lintegral Ξ½ := begin simp only [lintegral, ← H], apply lintegral_eq_of_subset, simp only [H], intros, exact mem_range_of_measure_ne_zero β€Ή_β€Ί end /-- If two simple functions are equal a.e., then their `lintegral`s are equal. -/ lemma lintegral_congr {f g : Ξ± β†’β‚› ennreal} (h : f =ᡐ[ΞΌ] g) : f.lintegral ΞΌ = g.lintegral ΞΌ := lintegral_eq_of_measure_preimage $ Ξ» y, measure_congr $ eventually.set_eq $ h.mono $ Ξ» x hx, by simp [hx] lemma lintegral_map {Ξ²} [measurable_space Ξ²] {ΞΌ' : measure Ξ²} (f : Ξ± β†’β‚› ennreal) (g : Ξ² β†’β‚› ennreal) (m : Ξ± β†’ Ξ²) (eq : βˆ€a:Ξ±, f a = g (m a)) (h : βˆ€s:set Ξ², is_measurable s β†’ ΞΌ' s = ΞΌ (m ⁻¹' s)) : f.lintegral ΞΌ = g.lintegral ΞΌ' := lintegral_eq_of_measure_preimage $ Ξ» y, by { simp only [preimage, eq], exact (h (g ⁻¹' {y}) (g.is_measurable_preimage _)).symm } end measure section fin_meas_supp variables [measurable_space Ξ±] [has_zero Ξ²] [has_zero Ξ³] {ΞΌ : measure Ξ±} open finset ennreal function lemma support_eq (f : Ξ± β†’β‚› Ξ²) : support f = ⋃ y ∈ f.range.filter (Ξ» y, y β‰  0), f ⁻¹' {y} := set.ext $ Ξ» x, by simp only [finset.bUnion_preimage_singleton, mem_support, set.mem_preimage, finset.mem_coe, mem_filter, mem_range_self, true_and] /-- A `simple_func` has finite measure support if it is equal to `0` outside of a set of finite measure. -/ protected def fin_meas_supp (f : Ξ± β†’β‚› Ξ²) (ΞΌ : measure Ξ±) : Prop := f =αΆ [ΞΌ.cofinite] 0 lemma fin_meas_supp_iff_support {f : Ξ± β†’β‚› Ξ²} {ΞΌ : measure Ξ±} : f.fin_meas_supp ΞΌ ↔ ΞΌ (support f) < ⊀ := iff.rfl lemma fin_meas_supp_iff {f : Ξ± β†’β‚› Ξ²} {ΞΌ : measure Ξ±} : f.fin_meas_supp ΞΌ ↔ βˆ€ y β‰  0, ΞΌ (f ⁻¹' {y}) < ⊀ := begin split, { refine Ξ» h y hy, lt_of_le_of_lt (measure_mono _) h, exact Ξ» x hx (H : f x = 0), hy $ H β–Έ eq.symm hx }, { intro H, rw [fin_meas_supp_iff_support, support_eq], refine lt_of_le_of_lt (measure_bUnion_finset_le _ _) (sum_lt_top _), exact Ξ» y hy, H y (finset.mem_filter.1 hy).2 } end namespace fin_meas_supp lemma meas_preimage_singleton_ne_zero {f : Ξ± β†’β‚› Ξ²} (h : f.fin_meas_supp ΞΌ) {y : Ξ²} (hy : y β‰  0) : ΞΌ (f ⁻¹' {y}) < ⊀ := fin_meas_supp_iff.1 h y hy protected lemma map {f : Ξ± β†’β‚› Ξ²} {g : Ξ² β†’ Ξ³} (hf : f.fin_meas_supp ΞΌ) (hg : g 0 = 0) : (f.map g).fin_meas_supp ΞΌ := flip lt_of_le_of_lt hf (measure_mono $ support_comp_subset hg f) lemma of_map {f : Ξ± β†’β‚› Ξ²} {g : Ξ² β†’ Ξ³} (h : (f.map g).fin_meas_supp ΞΌ) (hg : βˆ€b, g b = 0 β†’ b = 0) : f.fin_meas_supp ΞΌ := flip lt_of_le_of_lt h $ measure_mono $ support_subset_comp hg _ lemma map_iff {f : Ξ± β†’β‚› Ξ²} {g : Ξ² β†’ Ξ³} (hg : βˆ€ {b}, g b = 0 ↔ b = 0) : (f.map g).fin_meas_supp ΞΌ ↔ f.fin_meas_supp ΞΌ := ⟨λ h, h.of_map $ Ξ» b, hg.1, Ξ» h, h.map $ hg.2 rfl⟩ protected lemma pair {f : Ξ± β†’β‚› Ξ²} {g : Ξ± β†’β‚› Ξ³} (hf : f.fin_meas_supp ΞΌ) (hg : g.fin_meas_supp ΞΌ) : (pair f g).fin_meas_supp ΞΌ := calc ΞΌ (support $ pair f g) = ΞΌ (support f βˆͺ support g) : congr_arg ΞΌ $ support_prod_mk f g ... ≀ ΞΌ (support f) + ΞΌ (support g) : measure_union_le _ _ ... < _ : add_lt_top.2 ⟨hf, hg⟩ protected lemma mapβ‚‚ [has_zero Ξ΄] {ΞΌ : measure Ξ±} {f : Ξ± β†’β‚› Ξ²} (hf : f.fin_meas_supp ΞΌ) {g : Ξ± β†’β‚› Ξ³} (hg : g.fin_meas_supp ΞΌ) {op : Ξ² β†’ Ξ³ β†’ Ξ΄} (H : op 0 0 = 0) : ((pair f g).map (function.uncurry op)).fin_meas_supp ΞΌ := (hf.pair hg).map H protected lemma add {Ξ²} [add_monoid Ξ²] {f g : Ξ± β†’β‚› Ξ²} (hf : f.fin_meas_supp ΞΌ) (hg : g.fin_meas_supp ΞΌ) : (f + g).fin_meas_supp ΞΌ := by { rw [add_eq_mapβ‚‚], exact hf.mapβ‚‚ hg (zero_add 0) } protected lemma mul {Ξ²} [monoid_with_zero Ξ²] {f g : Ξ± β†’β‚› Ξ²} (hf : f.fin_meas_supp ΞΌ) (hg : g.fin_meas_supp ΞΌ) : (f * g).fin_meas_supp ΞΌ := by { rw [mul_eq_mapβ‚‚], exact hf.mapβ‚‚ hg (zero_mul 0) } lemma lintegral_lt_top {f : Ξ± β†’β‚› ennreal} (hm : f.fin_meas_supp ΞΌ) (hf : βˆ€α΅ a βˆ‚ΞΌ, f a < ⊀) : f.lintegral ΞΌ < ⊀ := begin refine sum_lt_top (Ξ» a ha, _), rcases eq_or_lt_of_le (le_top : a ≀ ⊀) with rfl|ha, { simp only [ae_iff, lt_top_iff_ne_top, ne.def, not_not] at hf, simp [set.preimage, hf] }, { by_cases ha0 : a = 0, { subst a, rwa [zero_mul] }, { exact mul_lt_top ha (fin_meas_supp_iff.1 hm _ ha0) } } end lemma of_lintegral_lt_top {f : Ξ± β†’β‚› ennreal} (h : f.lintegral ΞΌ < ⊀) : f.fin_meas_supp ΞΌ := begin refine fin_meas_supp_iff.2 (Ξ» b hb, _), rw [lintegral, sum_lt_top_iff] at h, by_cases b_mem : b ∈ f.range, { rw ennreal.lt_top_iff_ne_top, have h : Β¬ _ = ⊀ := ennreal.lt_top_iff_ne_top.1 (h b b_mem), simp only [mul_eq_top, not_or_distrib, not_and_distrib] at h, rcases h with ⟨h, h'⟩, refine or.elim h (Ξ»h, by contradiction) (Ξ»h, h) }, { rw ← preimage_eq_empty_iff at b_mem, rw [b_mem, measure_empty], exact with_top.zero_lt_top } end lemma iff_lintegral_lt_top {f : Ξ± β†’β‚› ennreal} (hf : βˆ€α΅ a βˆ‚ΞΌ, f a < ⊀) : f.fin_meas_supp ΞΌ ↔ f.lintegral ΞΌ < ⊀ := ⟨λ h, h.lintegral_lt_top hf, Ξ» h, of_lintegral_lt_top h⟩ end fin_meas_supp end fin_meas_supp /-- To prove something for an arbitrary simple function, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition (of functions with disjoint support). It is possible to make the hypotheses in `h_sum` a bit stronger, and such conditions can be added once we need them (for example it is only necessary to consider the case where `g` is a multiple of a characteristic function, and that this multiple doesn't appear in the image of `f`) -/ @[elab_as_eliminator] protected lemma induction {Ξ± Ξ³} [measurable_space Ξ±] [add_monoid Ξ³] {P : simple_func Ξ± Ξ³ β†’ Prop} (h_ind : βˆ€ c {s} (hs : is_measurable s), P (simple_func.piecewise s hs (simple_func.const _ c) (simple_func.const _ 0))) (h_sum : βˆ€ ⦃f g : simple_func Ξ± γ⦄, set.univ βŠ† f ⁻¹' {0} βˆͺ g ⁻¹' {0} β†’ P f β†’ P g β†’ P (f + g)) (f : simple_func Ξ± Ξ³) : P f := begin generalize' h : f.range \ {0} = s, rw [← finset.coe_inj, finset.coe_sdiff, finset.coe_singleton, simple_func.coe_range] at h, revert s f h, refine finset.induction _ _, { intros f hf, rw [finset.coe_empty, diff_eq_empty, range_subset_singleton] at hf, convert h_ind 0 is_measurable.univ, ext x, simp [hf] }, { intros x s hxs ih f hf, have mx := f.is_measurable_preimage {x}, let g := simple_func.piecewise (f ⁻¹' {x}) mx 0 f, have Pg : P g, { apply ih, simp only [g, simple_func.coe_piecewise, range_piecewise], rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, hf, finset.coe_insert, insert_diff_self_of_not_mem, diff_eq_empty.mpr, set.empty_union], { rw [set.image_subset_iff], convert set.subset_univ _, exact preimage_const_of_mem (mem_singleton _) }, { rwa [finset.mem_coe] }}, convert h_sum _ Pg (h_ind x mx), { ext1 y, by_cases hy : y ∈ f ⁻¹' {x}; [simpa [hy], simp [hy]] }, { rintro y -, by_cases hy : y ∈ f ⁻¹' {x}; simp [hy] } } end end simple_func section lintegral open simple_func variables [measurable_space Ξ±] {ΞΌ : measure Ξ±} /-- The lower Lebesgue integral of a function `f` with respect to a measure `ΞΌ`. -/ def lintegral (ΞΌ : measure Ξ±) (f : Ξ± β†’ ennreal) : ennreal := ⨆ (g : Ξ± β†’β‚› ennreal) (hf : ⇑g ≀ f), g.lintegral ΞΌ notation `∫⁻` binders `, ` r:(scoped:60 f, f) ` βˆ‚` ΞΌ:70 := lintegral ΞΌ r notation `∫⁻` binders `, ` r:(scoped:60 f, lintegral volume f) := r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, f) ` βˆ‚` ΞΌ:70 := lintegral (measure.restrict ΞΌ s) r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, lintegral (measure.restrict volume s) f) := r theorem simple_func.lintegral_eq_lintegral (f : Ξ± β†’β‚› ennreal) (ΞΌ : measure Ξ±) : ∫⁻ a, f a βˆ‚ ΞΌ = f.lintegral ΞΌ := le_antisymm (bsupr_le $ Ξ» g hg, lintegral_mono hg $ le_refl _) (le_supr_of_le f $ le_supr_of_le (le_refl _) (le_refl _)) @[mono] lemma lintegral_mono' ⦃μ Ξ½ : measure α⦄ (hΞΌΞ½ : ΞΌ ≀ Ξ½) ⦃f g : Ξ± β†’ ennreal⦄ (hfg : f ≀ g) : ∫⁻ a, f a βˆ‚ΞΌ ≀ ∫⁻ a, g a βˆ‚Ξ½ := supr_le_supr $ Ξ» Ο†, supr_le_supr2 $ Ξ» hΟ†, ⟨le_trans hΟ† hfg, lintegral_mono (le_refl Ο†) hμν⟩ lemma lintegral_mono ⦃f g : Ξ± β†’ ennreal⦄ (hfg : f ≀ g) : ∫⁻ a, f a βˆ‚ΞΌ ≀ ∫⁻ a, g a βˆ‚ΞΌ := lintegral_mono' (le_refl ΞΌ) hfg lemma monotone_lintegral (ΞΌ : measure Ξ±) : monotone (lintegral ΞΌ) := lintegral_mono @[simp] lemma lintegral_const (c : ennreal) : ∫⁻ a, c βˆ‚ΞΌ = c * ΞΌ univ := by rw [← simple_func.const_lintegral, ← simple_func.lintegral_eq_lintegral, simple_func.coe_const] lemma set_lintegral_one (s) : ∫⁻ a in s, 1 βˆ‚ΞΌ = ΞΌ s := by rw [lintegral_const, one_mul, measure.restrict_apply_univ] /-- `∫⁻ a in s, f a βˆ‚ΞΌ` is defined as the supremum of integrals of simple functions `Ο† : Ξ± β†’β‚› ennreal` such that `Ο† ≀ f`. This lemma says that it suffices to take functions `Ο† : Ξ± β†’β‚› ℝβ‰₯0`. -/ lemma lintegral_eq_nnreal (f : Ξ± β†’ ennreal) (ΞΌ : measure Ξ±) : (∫⁻ a, f a βˆ‚ΞΌ) = (⨆ (Ο† : Ξ± β†’β‚› ℝβ‰₯0) (hf : βˆ€ x, ↑(Ο† x) ≀ f x), (Ο†.map (coe : nnreal β†’ ennreal)).lintegral ΞΌ) := begin refine le_antisymm (bsupr_le $ assume Ο† hΟ†, _) (supr_le_supr2 $ Ξ» Ο†, βŸ¨Ο†.map (coe : ℝβ‰₯0 β†’ ennreal), le_refl _⟩), by_cases h : βˆ€α΅ a βˆ‚ΞΌ, Ο† a β‰  ⊀, { let ψ := Ο†.map ennreal.to_nnreal, replace h : ψ.map (coe : ℝβ‰₯0 β†’ ennreal) =ᡐ[ΞΌ] Ο† := h.mono (Ξ» a, ennreal.coe_to_nnreal), have : βˆ€ x, ↑(ψ x) ≀ f x := Ξ» x, le_trans ennreal.coe_to_nnreal_le_self (hΟ† x), exact le_supr_of_le (Ο†.map ennreal.to_nnreal) (le_supr_of_le this (ge_of_eq $ lintegral_congr h)) }, { have h_meas : ΞΌ (Ο† ⁻¹' {⊀}) β‰  0, from mt measure_zero_iff_ae_nmem.1 h, refine le_trans le_top (ge_of_eq $ (supr_eq_top _).2 $ Ξ» b hb, _), obtain ⟨n, hn⟩ : βˆƒ n : β„•, b < n * ΞΌ (Ο† ⁻¹' {⊀}), from exists_nat_mul_gt h_meas (ne_of_lt hb), use (const Ξ± (n : ℝβ‰₯0)).restrict (Ο† ⁻¹' {⊀}), simp only [lt_supr_iff, exists_prop, coe_restrict, Ο†.is_measurable_preimage, coe_const, ennreal.coe_indicator, map_coe_ennreal_restrict, map_const, ennreal.coe_nat, restrict_const_lintegral], refine ⟨indicator_le (Ξ» x hx, le_trans _ (hΟ† _)), hn⟩, simp only [mem_preimage, mem_singleton_iff] at hx, simp only [hx, le_top] } end theorem supr_lintegral_le {ΞΉ : Sort*} (f : ΞΉ β†’ Ξ± β†’ ennreal) : (⨆i, ∫⁻ a, f i a βˆ‚ΞΌ) ≀ (∫⁻ a, ⨆i, f i a βˆ‚ΞΌ) := begin simp only [← supr_apply], exact (monotone_lintegral ΞΌ).le_map_supr end theorem supr2_lintegral_le {ΞΉ : Sort*} {ΞΉ' : ΞΉ β†’ Sort*} (f : Ξ  i, ΞΉ' i β†’ Ξ± β†’ ennreal) : (⨆i (h : ΞΉ' i), ∫⁻ a, f i h a βˆ‚ΞΌ) ≀ (∫⁻ a, ⨆i (h : ΞΉ' i), f i h a βˆ‚ΞΌ) := by { convert (monotone_lintegral ΞΌ).le_map_supr2 f, ext1 a, simp only [supr_apply] } theorem le_infi_lintegral {ΞΉ : Sort*} (f : ΞΉ β†’ Ξ± β†’ ennreal) : (∫⁻ a, β¨…i, f i a βˆ‚ΞΌ) ≀ (β¨…i, ∫⁻ a, f i a βˆ‚ΞΌ) := by { simp only [← infi_apply], exact (monotone_lintegral ΞΌ).map_infi_le } theorem le_infi2_lintegral {ΞΉ : Sort*} {ΞΉ' : ΞΉ β†’ Sort*} (f : Ξ  i, ΞΉ' i β†’ Ξ± β†’ ennreal) : (∫⁻ a, β¨… i (h : ΞΉ' i), f i h a βˆ‚ΞΌ) ≀ (β¨… i (h : ΞΉ' i), ∫⁻ a, f i h a βˆ‚ΞΌ) := by { convert (monotone_lintegral ΞΌ).map_infi2_le f, ext1 a, simp only [infi_apply] } /-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence. See `lintegral_supr_directed` for a more general form. -/ theorem lintegral_supr {f : β„• β†’ Ξ± β†’ ennreal} (hf : βˆ€n, measurable (f n)) (h_mono : monotone f) : (∫⁻ a, ⨆n, f n a βˆ‚ΞΌ) = (⨆n, ∫⁻ a, f n a βˆ‚ΞΌ) := begin set c : nnreal β†’ ennreal := coe, set F := Ξ» a:Ξ±, ⨆n, f n a, have hF : measurable F := measurable_supr hf, refine le_antisymm _ (supr_lintegral_le _), rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_lt (assume a ha, _), rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩, have ha : r < 1 := ennreal.coe_lt_coe.1 ha, let rs := s.map (Ξ»a, r * a), have eq_rs : (const Ξ± r : Ξ± β†’β‚› ennreal) * map c s = rs.map c, { ext1 a, exact ennreal.coe_mul.symm }, have eq : βˆ€p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≀ f n a}), { assume p, rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]}, refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _), by_cases p_eq : p = 0, { simp [p_eq] }, simp at hx, subst hx, have : r * s x β‰  0, { rwa [(β‰ ), ← ennreal.coe_eq_zero] }, have : s x β‰  0, { refine mt _ this, assume h, rw [h, mul_zero] }, have : (rs.map c) x < ⨆ (n : β„•), f n x, { refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x), suffices : r * s x < 1 * s x, simpa [rs], exact mul_lt_mul_of_pos_right ha (zero_lt_iff_ne_zero.2 this) }, rcases lt_supr_iff.1 this with ⟨i, hi⟩, exact mem_Union.2 ⟨i, le_of_lt hi⟩ }, have mono : βˆ€r:ennreal, monotone (Ξ»n, (rs.map c) ⁻¹' {r} ∩ {a | r ≀ f n a}), { assume r i j h, refine inter_subset_inter (subset.refl _) _, assume x hx, exact le_trans hx (h_mono h x) }, have h_meas : βˆ€n, is_measurable {a : Ξ± | ⇑(map c rs) a ≀ f n a} := assume n, is_measurable_le (simple_func.measurable _) (hf n), calc (r:ennreal) * (s.map c).lintegral ΞΌ = βˆ‘ r in (rs.map c).range, r * ΞΌ ((rs.map c) ⁻¹' {r}) : by rw [← const_mul_lintegral, eq_rs, simple_func.lintegral] ... ≀ βˆ‘ r in (rs.map c).range, r * ΞΌ (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≀ f n a}) : le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq) ... ≀ βˆ‘ r in (rs.map c).range, (⨆n, r * ΞΌ ((rs.map c) ⁻¹' {r} ∩ {a | r ≀ f n a})) : le_of_eq (finset.sum_congr rfl $ assume x hx, begin rw [measure_Union_eq_supr _ (directed_of_sup $ mono x), ennreal.mul_supr], { assume i, refine ((rs.map c).is_measurable_preimage _).inter _, exact hf i is_measurable_Ici } end) ... ≀ ⨆n, βˆ‘ r in (rs.map c).range, r * ΞΌ ((rs.map c) ⁻¹' {r} ∩ {a | r ≀ f n a}) : begin refine le_of_eq _, rw [ennreal.finset_sum_supr_nat], assume p i j h, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (measure_mono $ mono p h) end ... ≀ (⨆n:β„•, ((rs.map c).restrict {a | (rs.map c) a ≀ f n a}).lintegral ΞΌ) : begin refine supr_le_supr (assume n, _), rw [restrict_lintegral _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2 with a, refine and_congr_right _, simp {contextual := tt} } end ... ≀ (⨆n, ∫⁻ a, f n a βˆ‚ΞΌ) : begin refine supr_le_supr (assume n, _), rw [← simple_func.lintegral_eq_lintegral], refine lintegral_mono (assume a, _), dsimp, rw [restrict_apply], split_ifs; simp, simpa using h, exact h_meas n end end lemma lintegral_eq_supr_eapprox_lintegral {f : Ξ± β†’ ennreal} (hf : measurable f) : (∫⁻ a, f a βˆ‚ΞΌ) = (⨆n, (eapprox f n).lintegral ΞΌ) := calc (∫⁻ a, f a βˆ‚ΞΌ) = (∫⁻ a, ⨆n, (eapprox f n : Ξ± β†’ ennreal) a βˆ‚ΞΌ) : by congr; ext a; rw [supr_eapprox_apply f hf] ... = (⨆n, ∫⁻ a, (eapprox f n : Ξ± β†’ ennreal) a βˆ‚ΞΌ) : begin rw [lintegral_supr], { assume n, exact (eapprox f n).measurable }, { assume i j h, exact (monotone_eapprox f h) } end ... = (⨆n, (eapprox f n).lintegral ΞΌ) : by congr; ext n; rw [(eapprox f n).lintegral_eq_lintegral] @[simp] lemma lintegral_add {f g : Ξ± β†’ ennreal} (hf : measurable f) (hg : measurable g) : (∫⁻ a, f a + g a βˆ‚ΞΌ) = (∫⁻ a, f a βˆ‚ΞΌ) + (∫⁻ a, g a βˆ‚ΞΌ) := calc (∫⁻ a, f a + g a βˆ‚ΞΌ) = (∫⁻ a, (⨆n, (eapprox f n : Ξ± β†’ ennreal) a) + (⨆n, (eapprox g n : Ξ± β†’ ennreal) a) βˆ‚ΞΌ) : by congr; funext a; rw [supr_eapprox_apply f hf, supr_eapprox_apply g hg] ... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : Ξ± β†’ ennreal) a) βˆ‚ΞΌ) : begin congr, funext a, rw [ennreal.supr_add_supr_of_monotone], { refl }, { assume i j h, exact monotone_eapprox _ h a }, { assume i j h, exact monotone_eapprox _ h a }, end ... = (⨆n, (eapprox f n).lintegral ΞΌ + (eapprox g n).lintegral ΞΌ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_lintegral, ← simple_func.lintegral_eq_lintegral], refl }, { assume n, exact measurable.add (eapprox f n).measurable (eapprox g n).measurable }, { assume i j h a, exact add_le_add (monotone_eapprox _ h _) (monotone_eapprox _ h _) } end ... = (⨆n, (eapprox f n).lintegral ΞΌ) + (⨆n, (eapprox g n).lintegral ΞΌ) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.lintegral_mono (monotone_eapprox _ h) (le_refl ΞΌ) } ... = (∫⁻ a, f a βˆ‚ΞΌ) + (∫⁻ a, g a βˆ‚ΞΌ) : by rw [lintegral_eq_supr_eapprox_lintegral hf, lintegral_eq_supr_eapprox_lintegral hg] lemma lintegral_zero : (∫⁻ a:Ξ±, 0 βˆ‚ΞΌ) = 0 := by simp @[simp] lemma lintegral_smul_measure (c : ennreal) (f : Ξ± β†’ ennreal) : ∫⁻ a, f a βˆ‚ (c β€’ ΞΌ) = c * ∫⁻ a, f a βˆ‚ΞΌ := by simp only [lintegral, supr_subtype', simple_func.lintegral_smul, ennreal.mul_supr, smul_eq_mul] @[simp] lemma lintegral_sum_measure {ΞΉ} (f : Ξ± β†’ ennreal) (ΞΌ : ΞΉ β†’ measure Ξ±) : ∫⁻ a, f a βˆ‚(measure.sum ΞΌ) = βˆ‘' i, ∫⁻ a, f a βˆ‚(ΞΌ i) := begin simp only [lintegral, supr_subtype', simple_func.lintegral_sum, ennreal.tsum_eq_supr_sum], rw [supr_comm], congr, funext s, induction s using finset.induction_on with i s hi hs, { apply bot_unique, simp }, simp only [finset.sum_insert hi, ← hs], refine (ennreal.supr_add_supr _).symm, intros Ο† ψ, exact βŸ¨βŸ¨Ο† βŠ” ψ, Ξ» x, sup_le (Ο†.2 x) (ψ.2 x)⟩, add_le_add (simple_func.lintegral_mono le_sup_left (le_refl _)) (finset.sum_le_sum $ Ξ» j hj, simple_func.lintegral_mono le_sup_right (le_refl _))⟩ end @[simp] lemma lintegral_add_measure (f : Ξ± β†’ ennreal) (ΞΌ Ξ½ : measure Ξ±) : ∫⁻ a, f a βˆ‚ (ΞΌ + Ξ½) = ∫⁻ a, f a βˆ‚ΞΌ + ∫⁻ a, f a βˆ‚Ξ½ := by simpa [tsum_fintype] using lintegral_sum_measure f (Ξ» b, cond b ΞΌ Ξ½) @[simp] lemma lintegral_zero_measure (f : Ξ± β†’ ennreal) : ∫⁻ a, f a βˆ‚0 = 0 := bot_unique $ by simp [lintegral] lemma lintegral_finset_sum (s : finset Ξ²) {f : Ξ² β†’ Ξ± β†’ ennreal} (hf : βˆ€b, measurable (f b)) : (∫⁻ a, βˆ‘ b in s, f b a βˆ‚ΞΌ) = βˆ‘ b in s, ∫⁻ a, f b a βˆ‚ΞΌ := begin refine finset.induction_on s _ _, { simp }, { assume a s has ih, simp only [finset.sum_insert has], rw [lintegral_add (hf _) (s.measurable_sum hf), ih] } end @[simp] lemma lintegral_const_mul (r : ennreal) {f : Ξ± β†’ ennreal} (hf : measurable f) : (∫⁻ a, r * f a βˆ‚ΞΌ) = r * (∫⁻ a, f a βˆ‚ΞΌ) := calc (∫⁻ a, r * f a βˆ‚ΞΌ) = (∫⁻ a, (⨆n, (const Ξ± r * eapprox f n) a) βˆ‚ΞΌ) : by { congr, funext a, rw [← supr_eapprox_apply f hf, ennreal.mul_supr], refl } ... = (⨆n, r * (eapprox f n).lintegral ΞΌ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_lintegral, ← simple_func.lintegral_eq_lintegral] }, { assume n, exact simple_func.measurable _ }, { assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (monotone_eapprox _ h _) } end ... = r * (∫⁻ a, f a βˆ‚ΞΌ) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_lintegral hf] lemma lintegral_const_mul_le (r : ennreal) (f : Ξ± β†’ ennreal) : r * (∫⁻ a, f a βˆ‚ΞΌ) ≀ (∫⁻ a, r * f a βˆ‚ΞΌ) := begin rw [lintegral, ennreal.mul_supr], refine supr_le (Ξ»s, _), rw [ennreal.mul_supr], simp only [supr_le_iff, ge_iff_le], assume hs, rw ← simple_func.const_mul_lintegral, refine le_supr_of_le (const Ξ± r * s) (le_supr_of_le (Ξ»x, _) (le_refl _)), exact canonically_ordered_semiring.mul_le_mul (le_refl _) (hs x) end lemma lintegral_const_mul' (r : ennreal) (f : Ξ± β†’ ennreal) (hr : r β‰  ⊀) : (∫⁻ a, r * f a βˆ‚ΞΌ) = r * (∫⁻ a, f a βˆ‚ΞΌ) := begin by_cases h : r = 0, { simp [h] }, apply le_antisymm _ (lintegral_const_mul_le r f), have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr, have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv }, have := lintegral_const_mul_le (r⁻¹) (Ξ»x, r * f x), simp [(mul_assoc _ _ _).symm, rinv'] at this, simpa [(mul_assoc _ _ _).symm, rinv] using canonically_ordered_semiring.mul_le_mul (le_refl r) this end lemma lintegral_mono_ae {f g : Ξ± β†’ ennreal} (h : βˆ€α΅ a βˆ‚ΞΌ, f a ≀ g a) : (∫⁻ a, f a βˆ‚ΞΌ) ≀ (∫⁻ a, g a βˆ‚ΞΌ) := begin rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t, hts, ht, ht0⟩, have : βˆ€α΅ x βˆ‚ΞΌ, x βˆ‰ t := measure_zero_iff_ae_nmem.1 ht0, refine (supr_le $ assume s, supr_le $ assume hfs, le_supr_of_le (s.restrict tᢜ) $ le_supr_of_le _ _), { assume a, by_cases a ∈ t; simp [h, restrict_apply, ht.compl], exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) }, { refine le_of_eq (simple_func.lintegral_congr $ this.mono $ Ξ» a hnt, _), by_cases hat : a ∈ t; simp [hat, ht.compl], exact (hnt hat).elim } end lemma lintegral_congr_ae {f g : Ξ± β†’ ennreal} (h : f =ᡐ[ΞΌ] g) : (∫⁻ a, f a βˆ‚ΞΌ) = (∫⁻ a, g a βˆ‚ΞΌ) := le_antisymm (lintegral_mono_ae $ h.le) (lintegral_mono_ae $ h.symm.le) lemma lintegral_congr {f g : Ξ± β†’ ennreal} (h : βˆ€ a, f a = g a) : (∫⁻ a, f a βˆ‚ΞΌ) = (∫⁻ a, g a βˆ‚ΞΌ) := by simp only [h] lemma set_lintegral_congr {f : Ξ± β†’ ennreal} {s t : set Ξ±} (h : s =ᡐ[ΞΌ] t) : ∫⁻ x in s, f x βˆ‚ΞΌ = ∫⁻ x in t, f x βˆ‚ΞΌ := by rw [restrict_congr_set h] -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₁ {f f' : Ξ± β†’ Ξ²} (h : f =ᡐ[ΞΌ] f') (g : Ξ² β†’ ennreal) : (∫⁻ a, g (f a) βˆ‚ΞΌ) = (∫⁻ a, g (f' a) βˆ‚ΞΌ) := lintegral_congr_ae $ h.mono $ Ξ» a h, by rw h -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rwβ‚‚ {f₁ f₁' : Ξ± β†’ Ξ²} {fβ‚‚ fβ‚‚' : Ξ± β†’ Ξ³} (h₁ : f₁ =ᡐ[ΞΌ] f₁') (hβ‚‚ : fβ‚‚ =ᡐ[ΞΌ] fβ‚‚') (g : Ξ² β†’ Ξ³ β†’ ennreal) : (∫⁻ a, g (f₁ a) (fβ‚‚ a) βˆ‚ΞΌ) = (∫⁻ a, g (f₁' a) (fβ‚‚' a) βˆ‚ΞΌ) := lintegral_congr_ae $ h₁.mp $ hβ‚‚.mono $ Ξ» _ hβ‚‚ h₁, by rw [h₁, hβ‚‚] @[simp] lemma lintegral_indicator (f : Ξ± β†’ ennreal) {s : set Ξ±} (hs : is_measurable s) : ∫⁻ a, s.indicator f a βˆ‚ΞΌ = ∫⁻ a in s, f a βˆ‚ΞΌ := begin simp only [lintegral, ← restrict_lintegral_eq_lintegral_restrict _ hs, supr_subtype'], apply le_antisymm; refine supr_le_supr2 (subtype.forall.2 $ Ξ» Ο† hΟ†, _), { refine βŸ¨βŸ¨Ο†, le_trans hΟ† (indicator_le_self _ _)⟩, _⟩, refine simple_func.lintegral_mono (Ξ» x, _) (le_refl _), by_cases hx : x ∈ s, { simp [hx, hs, le_refl] }, { apply le_trans (hΟ† x), simp [hx, hs, le_refl] } }, { refine βŸ¨βŸ¨Ο†.restrict s, Ξ» x, _⟩, le_refl _⟩, simp [hΟ† x, hs, indicator_le_indicator] } end /-- Chebyshev's inequality -/ lemma mul_meas_ge_le_lintegral {f : Ξ± β†’ ennreal} (hf : measurable f) (Ξ΅ : ennreal) : Ξ΅ * ΞΌ {x | Ξ΅ ≀ f x} ≀ ∫⁻ a, f a βˆ‚ΞΌ := begin have : is_measurable {a : Ξ± | Ξ΅ ≀ f a }, from hf is_measurable_Ici, rw [← simple_func.restrict_const_lintegral _ this, ← simple_func.lintegral_eq_lintegral], refine lintegral_mono (Ξ» a, _), simp only [restrict_apply _ this], split_ifs; [assumption, exact zero_le _] end lemma meas_ge_le_lintegral_div {f : Ξ± β†’ ennreal} (hf : measurable f) {Ξ΅ : ennreal} (hΞ΅ : Ξ΅ β‰  0) (hΞ΅' : Ξ΅ β‰  ⊀) : ΞΌ {x | Ξ΅ ≀ f x} ≀ (∫⁻ a, f a βˆ‚ΞΌ) / Ξ΅ := (ennreal.le_div_iff_mul_le (or.inl hΞ΅) (or.inl hΞ΅')).2 $ by { rw [mul_comm], exact mul_meas_ge_le_lintegral hf Ξ΅ } @[simp] lemma lintegral_eq_zero_iff {f : Ξ± β†’ ennreal} (hf : measurable f) : ∫⁻ a, f a βˆ‚ΞΌ = 0 ↔ (f =ᡐ[ΞΌ] 0) := begin refine iff.intro (assume h, _) (assume h, _), { have : βˆ€n:β„•, βˆ€α΅ a βˆ‚ΞΌ, f a < n⁻¹, { assume n, rw [ae_iff, ← le_zero_iff_eq, ← @ennreal.zero_div n⁻¹, ennreal.le_div_iff_mul_le, mul_comm], simp only [not_lt], -- TODO: why `rw ← h` fails with "not an equality or an iff"? exacts [h β–Έ mul_meas_ge_le_lintegral hf n⁻¹, or.inl (ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top), or.inr ennreal.zero_ne_top] }, refine (ae_all_iff.2 this).mono (Ξ» a ha, _), by_contradiction h, rcases ennreal.exists_inv_nat_lt h with ⟨n, hn⟩, exact (lt_irrefl _ $ lt_trans hn $ ha n).elim }, { calc ∫⁻ a, f a βˆ‚ΞΌ = ∫⁻ a, 0 βˆ‚ΞΌ : lintegral_congr_ae h ... = 0 : lintegral_zero } end lemma lintegral_pos_iff_support {f : Ξ± β†’ ennreal} (hf : measurable f) : 0 < ∫⁻ a, f a βˆ‚ΞΌ ↔ 0 < ΞΌ (function.support f) := by simp [zero_lt_iff_ne_zero, hf, filter.eventually_eq, ae_iff, function.support] /-- Weaker version of the monotone convergence theorem-/ lemma lintegral_supr_ae {f : β„• β†’ Ξ± β†’ ennreal} (hf : βˆ€n, measurable (f n)) (h_mono : βˆ€n, βˆ€α΅ a βˆ‚ΞΌ, f n a ≀ f n.succ a) : (∫⁻ a, ⨆n, f n a βˆ‚ΞΌ) = (⨆n, ∫⁻ a, f n a βˆ‚ΞΌ) := let ⟨s, hs⟩ := exists_is_measurable_superset_of_measure_eq_zero (ae_iff.1 (ae_all_iff.2 h_mono)) in let g := Ξ» n a, if a ∈ s then 0 else f n a in have g_eq_f : βˆ€α΅ a βˆ‚ΞΌ, βˆ€n, g n a = f n a, from (measure_zero_iff_ae_nmem.1 hs.2.2).mono (assume a ha n, if_neg ha), calc ∫⁻ a, ⨆n, f n a βˆ‚ΞΌ = ∫⁻ a, ⨆n, g n a βˆ‚ΞΌ : lintegral_congr_ae $ g_eq_f.mono $ Ξ» a ha, by simp only [ha] ... = ⨆n, (∫⁻ a, g n a βˆ‚ΞΌ) : lintegral_supr (assume n, measurable_const.piecewise hs.2.1 (hf n)) (monotone_of_monotone_nat $ assume n a, classical.by_cases (assume h : a ∈ s, by simp [g, if_pos h]) (assume h : a βˆ‰ s, begin simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h, simp only [not_not, mem_set_of_eq] at this, exact this n end)) ... = ⨆n, (∫⁻ a, f n a βˆ‚ΞΌ) : by simp only [lintegral_congr_ae (g_eq_f.mono $ Ξ» a ha, ha _)] lemma lintegral_sub {f g : Ξ± β†’ ennreal} (hf : measurable f) (hg : measurable g) (hg_fin : ∫⁻ a, g a βˆ‚ΞΌ < ⊀) (h_le : g ≀ᡐ[ΞΌ] f) : ∫⁻ a, f a - g a βˆ‚ΞΌ = ∫⁻ a, f a βˆ‚ΞΌ - ∫⁻ a, g a βˆ‚ΞΌ := begin rw [← ennreal.add_left_inj hg_fin, ennreal.sub_add_cancel_of_le (lintegral_mono_ae h_le), ← lintegral_add (hf.ennreal_sub hg) hg], refine lintegral_congr_ae (h_le.mono $ Ξ» x hx, _), exact ennreal.sub_add_cancel_of_le hx end /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi_ae {f : β„• β†’ Ξ± β†’ ennreal} (h_meas : βˆ€n, measurable (f n)) (h_mono : βˆ€n:β„•, f n.succ ≀ᡐ[ΞΌ] f n) (h_fin : ∫⁻ a, f 0 a βˆ‚ΞΌ < ⊀) : ∫⁻ a, β¨…n, f n a βˆ‚ΞΌ = β¨…n, ∫⁻ a, f n a βˆ‚ΞΌ := have fn_le_f0 : ∫⁻ a, β¨…n, f n a βˆ‚ΞΌ ≀ ∫⁻ a, f 0 a βˆ‚ΞΌ, from lintegral_mono (assume a, infi_le_of_le 0 (le_refl _)), have fn_le_f0' : (β¨…n, ∫⁻ a, f n a βˆ‚ΞΌ) ≀ ∫⁻ a, f 0 a βˆ‚ΞΌ, from infi_le_of_le 0 (le_refl _), (ennreal.sub_right_inj h_fin fn_le_f0 fn_le_f0').1 $ show ∫⁻ a, f 0 a βˆ‚ΞΌ - ∫⁻ a, β¨…n, f n a βˆ‚ΞΌ = ∫⁻ a, f 0 a βˆ‚ΞΌ - (β¨…n, ∫⁻ a, f n a βˆ‚ΞΌ), from calc ∫⁻ a, f 0 a βˆ‚ΞΌ - (∫⁻ a, β¨…n, f n a βˆ‚ΞΌ) = ∫⁻ a, f 0 a - β¨…n, f n a βˆ‚ΞΌ: (lintegral_sub (h_meas 0) (measurable_infi h_meas) (calc (∫⁻ a, β¨…n, f n a βˆ‚ΞΌ) ≀ ∫⁻ a, f 0 a βˆ‚ΞΌ : lintegral_mono (assume a, infi_le _ _) ... < ⊀ : h_fin ) (ae_of_all _ $ assume a, infi_le _ _)).symm ... = ∫⁻ a, ⨆n, f 0 a - f n a βˆ‚ΞΌ : congr rfl (funext (assume a, ennreal.sub_infi)) ... = ⨆n, ∫⁻ a, f 0 a - f n a βˆ‚ΞΌ : lintegral_supr_ae (assume n, (h_meas 0).ennreal_sub (h_meas n)) (assume n, (h_mono n).mono $ assume a ha, ennreal.sub_le_sub (le_refl _) ha) ... = ⨆n, ∫⁻ a, f 0 a βˆ‚ΞΌ - ∫⁻ a, f n a βˆ‚ΞΌ : have h_mono : βˆ€α΅ a βˆ‚ΞΌ, βˆ€n:β„•, f n.succ a ≀ f n a := ae_all_iff.2 h_mono, have h_mono : βˆ€n, βˆ€α΅ a βˆ‚ΞΌ, f n a ≀ f 0 a := assume n, h_mono.mono $ assume a h, begin induction n with n ih, {exact le_refl _}, {exact le_trans (h n) ih} end, congr rfl (funext $ assume n, lintegral_sub (h_meas _) (h_meas _) (calc ∫⁻ a, f n a βˆ‚ΞΌ ≀ ∫⁻ a, f 0 a βˆ‚ΞΌ : lintegral_mono_ae $ h_mono n ... < ⊀ : h_fin) (h_mono n)) ... = ∫⁻ a, f 0 a βˆ‚ΞΌ - β¨…n, ∫⁻ a, f n a βˆ‚ΞΌ : ennreal.sub_infi.symm /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi {f : β„• β†’ Ξ± β†’ ennreal} (h_meas : βˆ€n, measurable (f n)) (h_mono : βˆ€ ⦃m n⦄, m ≀ n β†’ f n ≀ f m) (h_fin : ∫⁻ a, f 0 a βˆ‚ΞΌ < ⊀) : ∫⁻ a, β¨…n, f n a βˆ‚ΞΌ = β¨…n, ∫⁻ a, f n a βˆ‚ΞΌ := lintegral_infi_ae h_meas (Ξ» n, ae_of_all _ $ h_mono $ le_of_lt n.lt_succ_self) h_fin /-- Known as Fatou's lemma -/ lemma lintegral_liminf_le {f : β„• β†’ Ξ± β†’ ennreal} (h_meas : βˆ€n, measurable (f n)) : ∫⁻ a, liminf at_top (Ξ» n, f n a) βˆ‚ΞΌ ≀ liminf at_top (Ξ» n, ∫⁻ a, f n a βˆ‚ΞΌ) := calc ∫⁻ a, liminf at_top (Ξ» n, f n a) βˆ‚ΞΌ = ∫⁻ a, ⨆n:β„•, β¨…iβ‰₯n, f i a βˆ‚ΞΌ : by simp only [liminf_eq_supr_infi_of_nat] ... = ⨆n:β„•, ∫⁻ a, β¨…iβ‰₯n, f i a βˆ‚ΞΌ : lintegral_supr (assume n, measurable_binfi _ (countable_encodable _) h_meas) (assume n m hnm a, infi_le_infi_of_subset $ Ξ» i hi, le_trans hnm hi) ... ≀ ⨆n:β„•, β¨…iβ‰₯n, ∫⁻ a, f i a βˆ‚ΞΌ : supr_le_supr $ Ξ» n, le_infi2_lintegral _ ... = liminf at_top (Ξ» n, ∫⁻ a, f n a βˆ‚ΞΌ) : liminf_eq_supr_infi_of_nat.symm lemma limsup_lintegral_le {f : β„• β†’ Ξ± β†’ ennreal} {g : Ξ± β†’ ennreal} (hf_meas : βˆ€ n, measurable (f n)) (h_bound : βˆ€n, f n ≀ᡐ[ΞΌ] g) (h_fin : ∫⁻ a, g a βˆ‚ΞΌ < ⊀) : limsup at_top (Ξ»n, ∫⁻ a, f n a βˆ‚ΞΌ) ≀ ∫⁻ a, limsup at_top (Ξ»n, f n a) βˆ‚ΞΌ := calc limsup at_top (Ξ»n, ∫⁻ a, f n a βˆ‚ΞΌ) = β¨…n:β„•, ⨆iβ‰₯n, ∫⁻ a, f i a βˆ‚ΞΌ : limsup_eq_infi_supr_of_nat ... ≀ β¨…n:β„•, ∫⁻ a, ⨆iβ‰₯n, f i a βˆ‚ΞΌ : infi_le_infi $ assume n, supr2_lintegral_le _ ... = ∫⁻ a, β¨…n:β„•, ⨆iβ‰₯n, f i a βˆ‚ΞΌ : begin refine (lintegral_infi _ _ _).symm, { assume n, exact measurable_bsupr _ (countable_encodable _) hf_meas }, { assume n m hnm a, exact (supr_le_supr_of_subset $ Ξ» i hi, le_trans hnm hi) }, { refine lt_of_le_of_lt (lintegral_mono_ae _) h_fin, refine (ae_all_iff.2 h_bound).mono (Ξ» n hn, _), exact supr_le (Ξ» i, supr_le $ Ξ» hi, hn i) } end ... = ∫⁻ a, limsup at_top (Ξ»n, f n a) βˆ‚ΞΌ : by simp only [limsup_eq_infi_supr_of_nat] /-- Dominated convergence theorem for nonnegative functions -/ lemma tendsto_lintegral_of_dominated_convergence {F : β„• β†’ Ξ± β†’ ennreal} {f : Ξ± β†’ ennreal} (bound : Ξ± β†’ ennreal) (hF_meas : βˆ€n, measurable (F n)) (h_bound : βˆ€n, F n ≀ᡐ[ΞΌ] bound) (h_fin : ∫⁻ a, bound a βˆ‚ΞΌ < ⊀) (h_lim : βˆ€α΅ a βˆ‚ΞΌ, tendsto (Ξ» n, F n a) at_top (𝓝 (f a))) : tendsto (Ξ»n, ∫⁻ a, F n a βˆ‚ΞΌ) at_top (𝓝 (∫⁻ a, f a βˆ‚ΞΌ)) := tendsto_of_le_liminf_of_limsup_le (calc ∫⁻ a, f a βˆ‚ΞΌ = ∫⁻ a, liminf at_top (Ξ» (n : β„•), F n a) βˆ‚ΞΌ : lintegral_congr_ae $ h_lim.mono $ assume a h, h.liminf_eq.symm ... ≀ liminf at_top (Ξ» n, ∫⁻ a, F n a βˆ‚ΞΌ) : lintegral_liminf_le hF_meas) (calc limsup at_top (Ξ» (n : β„•), ∫⁻ a, F n a βˆ‚ΞΌ) ≀ ∫⁻ a, limsup at_top (Ξ»n, F n a) βˆ‚ΞΌ : limsup_lintegral_le hF_meas h_bound h_fin ... = ∫⁻ a, f a βˆ‚ΞΌ : lintegral_congr_ae $ h_lim.mono $ Ξ» a h, h.limsup_eq) /-- Dominated convergence theorem for filters with a countable basis -/ lemma tendsto_lintegral_filter_of_dominated_convergence {ΞΉ} {l : filter ΞΉ} {F : ΞΉ β†’ Ξ± β†’ ennreal} {f : Ξ± β†’ ennreal} (bound : Ξ± β†’ ennreal) (hl_cb : l.is_countably_generated) (hF_meas : βˆ€αΆ  n in l, measurable (F n)) (h_bound : βˆ€αΆ  n in l, βˆ€α΅ a βˆ‚ΞΌ, F n a ≀ bound a) (h_fin : ∫⁻ a, bound a βˆ‚ΞΌ < ⊀) (h_lim : βˆ€α΅ a βˆ‚ΞΌ, tendsto (Ξ» n, F n a) l (𝓝 (f a))) : tendsto (Ξ»n, ∫⁻ a, F n a βˆ‚ΞΌ) l (𝓝 $ ∫⁻ a, f a βˆ‚ΞΌ) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { assumption }, { refine h_lim.mono (Ξ» a h_lim, _), apply @tendsto.comp _ _ _ (Ξ»n, x (n + k)) (Ξ»n, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, end section open encodable /-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/ theorem lintegral_supr_directed [encodable Ξ²] {f : Ξ² β†’ Ξ± β†’ ennreal} (hf : βˆ€b, measurable (f b)) (h_directed : directed (≀) f) : ∫⁻ a, ⨆b, f b a βˆ‚ΞΌ = ⨆b, ∫⁻ a, f b a βˆ‚ΞΌ := begin by_cases hΞ² : nonempty Ξ², swap, { simp [supr_of_empty hΞ²] }, resetI, inhabit Ξ², have : βˆ€a, (⨆ b, f b a) = (⨆ n, f (h_directed.sequence f n) a), { assume a, refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (Ξ»n, f n a) _), exact le_supr_of_le (encode b + 1) (h_directed.le_sequence b a) }, calc ∫⁻ a, ⨆ b, f b a βˆ‚ΞΌ = ∫⁻ a, ⨆ n, f (h_directed.sequence f n) a βˆ‚ΞΌ : by simp only [this] ... = ⨆ n, ∫⁻ a, f (h_directed.sequence f n) a βˆ‚ΞΌ : lintegral_supr (assume n, hf _) h_directed.sequence_mono ... = ⨆ b, ∫⁻ a, f b a βˆ‚ΞΌ : begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _), { exact le_supr (Ξ»b, ∫⁻ a, f b a βˆ‚ΞΌ) _ }, { exact le_supr_of_le (encode b + 1) (lintegral_mono $ h_directed.le_sequence b) } end end end lemma lintegral_tsum [encodable Ξ²] {f : Ξ² β†’ Ξ± β†’ ennreal} (hf : βˆ€i, measurable (f i)) : ∫⁻ a, βˆ‘' i, f i a βˆ‚ΞΌ = βˆ‘' i, ∫⁻ a, f i a βˆ‚ΞΌ := begin simp only [ennreal.tsum_eq_supr_sum], rw [lintegral_supr_directed], { simp [lintegral_finset_sum _ hf] }, { assume b, exact finset.measurable_sum _ hf }, { assume s t, use [s βˆͺ t], split, exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _), exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) } end open measure lemma lintegral_Union [encodable Ξ²] {s : Ξ² β†’ set Ξ±} (hm : βˆ€ i, is_measurable (s i)) (hd : pairwise (disjoint on s)) (f : Ξ± β†’ ennreal) : ∫⁻ a in ⋃ i, s i, f a βˆ‚ΞΌ = βˆ‘' i, ∫⁻ a in s i, f a βˆ‚ΞΌ := by simp only [measure.restrict_Union hd hm, lintegral_sum_measure] lemma lintegral_Union_le [encodable Ξ²] (s : Ξ² β†’ set Ξ±) (f : Ξ± β†’ ennreal) : ∫⁻ a in ⋃ i, s i, f a βˆ‚ΞΌ ≀ βˆ‘' i, ∫⁻ a in s i, f a βˆ‚ΞΌ := begin rw [← lintegral_sum_measure], exact lintegral_mono' restrict_Union_le (le_refl _) end lemma lintegral_map [measurable_space Ξ²] {f : Ξ² β†’ ennreal} {g : Ξ± β†’ Ξ²} (hf : measurable f) (hg : measurable g) : ∫⁻ a, f a βˆ‚(map g ΞΌ) = ∫⁻ a, f (g a) βˆ‚ΞΌ := begin simp only [lintegral_eq_supr_eapprox_lintegral, hf, hf.comp hg], { congr, funext n, symmetry, apply simple_func.lintegral_map, { assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a }, { assume s hs, exact map_apply hg hs } }, end lemma set_lintegral_map [measurable_space Ξ²] {f : Ξ² β†’ ennreal} {g : Ξ± β†’ Ξ²} {s : set Ξ²} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : ∫⁻ y in s, f y βˆ‚(map g ΞΌ) = ∫⁻ x in g ⁻¹' s, f (g x) βˆ‚ΞΌ := by rw [restrict_map hg hs, lintegral_map hf hg] lemma lintegral_dirac (a : Ξ±) {f : Ξ± β†’ ennreal} (hf : measurable f) : ∫⁻ a, f a βˆ‚(dirac a) = f a := by simp [lintegral_congr_ae (eventually_eq_dirac hf)] /-- Given a measure `ΞΌ : measure Ξ±` and a function `f : Ξ± β†’ ennreal`, `ΞΌ.with_density f` is the measure such that for a measurable set `s` we have `ΞΌ.with_density f s = ∫⁻ a in s, f a βˆ‚ΞΌ`. -/ def measure.with_density (ΞΌ : measure Ξ±) (f : Ξ± β†’ ennreal) : measure Ξ± := measure.of_measurable (Ξ»s hs, ∫⁻ a in s, f a βˆ‚ΞΌ) (by simp) (Ξ» s hs hd, lintegral_Union hs hd _) @[simp] lemma with_density_apply (f : Ξ± β†’ ennreal) {s : set Ξ±} (hs : is_measurable s) : ΞΌ.with_density f s = ∫⁻ a in s, f a βˆ‚ΞΌ := measure.of_measurable_apply s hs end lintegral end measure_theory open measure_theory measure_theory.simple_func /-- To prove something for an arbitrary measurable function into `ennreal`, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of a simple function with a multiple of a characteristic function and that the intersection of their images is a subset of `{0}`. -/ @[elab_as_eliminator] theorem measurable.ennreal_induction {Ξ±} [measurable_space Ξ±] {P : (Ξ± β†’ ennreal) β†’ Prop} (h_ind : βˆ€ (c : ennreal) ⦃s⦄, is_measurable s β†’ P (indicator s (Ξ» _, c))) (h_sum : βˆ€ ⦃f g : Ξ± β†’ ennreal⦄, set.univ βŠ† f ⁻¹' {0} βˆͺ g ⁻¹' {0} β†’ measurable f β†’ measurable g β†’ P f β†’ P g β†’ P (f + g)) (h_supr : βˆ€ ⦃f : β„• β†’ Ξ± β†’ ennreal⦄ (hf : βˆ€n, measurable (f n)) (h_mono : monotone f) (hP : βˆ€ n, P (f n)), P (Ξ» x, ⨆ n, f n x)) ⦃f : Ξ± β†’ ennreal⦄ (hf : measurable f) : P f := begin convert h_supr (Ξ» n, (eapprox f n).measurable) (monotone_eapprox f) _, { ext1 x, rw [supr_eapprox_apply f hf] }, { exact Ξ» n, simple_func.induction (Ξ» c s hs, h_ind c hs) (Ξ» f g hfg hf hg, h_sum hfg f.measurable g.measurable hf hg) (eapprox f n) } end namespace measure_theory /-- This is Exercise 1.2.1 from [tao2010]. It allows you to express integration of a measurable function with respect to `(ΞΌ.with_density f)` as an integral with respect to `ΞΌ`, called the base measure. `ΞΌ` is often the Lebesgue measure, and in this circumstance `f` is the probability density function, and `(ΞΌ.with_density f)` represents any continuous random variable as a probability measure, such as the uniform distribution between 0 and 1, the Gaussian distribution, the exponential distribution, the Beta distribution, or the Cauchy distribution (see Section 2.4 of [wasserman2004]). Thus, this method shows how to one can calculate expectations, variances, and other moments as a function of the probability density function. -/ lemma lintegral_with_density_eq_lintegral_mul {Ξ±} [measurable_space Ξ±] (ΞΌ : measure Ξ±) {f : Ξ± β†’ ennreal} (h_mf : measurable f) : βˆ€ {g : Ξ± β†’ ennreal}, measurable g β†’ ∫⁻ a, g a βˆ‚(ΞΌ.with_density f) = ∫⁻ a, (f * g) a βˆ‚ΞΌ := begin apply measurable.ennreal_induction, { intros c s h_ms, simp [*, mul_comm _ c] }, { intros g h h_univ h_mea_g h_mea_h h_ind_g h_ind_h, simp [mul_add, *, measurable.ennreal_mul] }, { intros g h_mea_g h_mono_g h_ind, have : monotone (Ξ» n a, f a * g n a) := Ξ» m n hmn x, ennreal.mul_le_mul le_rfl (h_mono_g hmn x), simp [lintegral_supr, ennreal.mul_supr, h_mf.ennreal_mul (h_mea_g _), *] } end end measure_theory
654e30a66e92ec27b79f4fa42687318361abc29d
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/list.lean
dcd1539fa2661797bed80b929a4a34184ffe5eed
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,731
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.group /-! # 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_refl _ }, 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_refl _ 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
46c54d67e2e55a9140ca001b733260e8b2fec349
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/computability/partrec.lean
f0256177417382aab0357557bd8cece9bd9aeb58
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
28,358
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import computability.primrec data.pfun /-! # The partial recursive functions The partial recursive functions are defined similarly to the primitive recursive functions, but now all functions are partial, implemented using the `roption` monad, and there is an additional operation, called ΞΌ-recursion, which performs unbounded minimization. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open encodable denumerable roption namespace nat section rfind parameter (p : β„• β†’. bool) private def lbp (m n : β„•) : Prop := m = n + 1 ∧ βˆ€ k ≀ n, ff ∈ p k parameter (H : βˆƒ n, tt ∈ p n ∧ βˆ€ k < n, (p k).dom) private def wf_lbp : well_founded lbp := ⟨let ⟨n, pn⟩ := H in begin suffices : βˆ€m k, n ≀ k + m β†’ acc (lbp p) k, { from Ξ»a, this _ _ (nat.le_add_left _ _) }, intros m k kn, induction m with m IH generalizing k; refine ⟨_, Ξ» y r, _⟩; rcases r with ⟨rfl, a⟩, { injection mem_unique pn.1 (a _ kn) }, { exact IH _ (by rw nat.add_right_comm; exact kn) } end⟩ def rfind_x : {n // tt ∈ p n ∧ βˆ€m < n, ff ∈ p m} := suffices βˆ€ k, (βˆ€n < k, ff ∈ p n) β†’ {n // tt ∈ p n ∧ βˆ€m < n, ff ∈ p m}, from this 0 (Ξ» n, (nat.not_lt_zero _).elim), @well_founded.fix _ _ lbp wf_lbp begin intros m IH al, have pm : (p m).dom, { rcases H with ⟨n, h₁, hβ‚‚βŸ©, rcases decidable.lt_trichotomy m n with h₃|h₃|h₃, { exact hβ‚‚ _ h₃ }, { rw h₃, exact h₁.fst }, { injection mem_unique h₁ (al _ h₃) } }, cases e : (p m).get pm, { suffices, exact IH _ ⟨rfl, this⟩ (Ξ» n h, this _ (le_of_lt_succ h)), intros n h, cases decidable.lt_or_eq_of_le h with h h, { exact al _ h }, { rw h, exact ⟨_, e⟩ } }, { exact ⟨m, ⟨_, e⟩, al⟩ } end end rfind def rfind (p : β„• β†’. bool) : roption β„• := ⟨_, Ξ» h, (rfind_x p h).1⟩ theorem rfind_spec {p : β„• β†’. bool} {n : β„•} (h : n ∈ rfind p) : tt ∈ p n := h.snd β–Έ (rfind_x p h.fst).2.1 theorem rfind_min {p : β„• β†’. bool} {n : β„•} (h : n ∈ rfind p) : βˆ€ {m : β„•}, m < n β†’ ff ∈ p m := h.snd β–Έ (rfind_x p h.fst).2.2 @[simp] theorem rfind_dom {p : β„• β†’. bool} : (rfind p).dom ↔ βˆƒ n, tt ∈ p n ∧ βˆ€ {m : β„•}, m < n β†’ (p m).dom := iff.rfl theorem rfind_dom' {p : β„• β†’. bool} : (rfind p).dom ↔ βˆƒ n, tt ∈ p n ∧ βˆ€ {m : β„•}, m ≀ n β†’ (p m).dom := exists_congr $ Ξ» n, and_congr_right $ Ξ» pn, ⟨λ H m h, (eq_or_lt_of_le h).elim (Ξ» e, e.symm β–Έ pn.fst) (H _), Ξ» H m h, H (le_of_lt h)⟩ @[simp] theorem mem_rfind {p : β„• β†’. bool} {n : β„•} : n ∈ rfind p ↔ tt ∈ p n ∧ βˆ€ {m : β„•}, m < n β†’ ff ∈ p m := ⟨λ h, ⟨rfind_spec h, @rfind_min _ _ h⟩, Ξ» ⟨h₁, hβ‚‚βŸ©, let ⟨m, hm⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨_, h₁, Ξ» m mn, (hβ‚‚ mn).fst⟩ in begin rcases lt_trichotomy m n with h|h|h, { injection mem_unique (hβ‚‚ h) (rfind_spec hm) }, { rwa ← h }, { injection mem_unique h₁ (rfind_min hm h) }, end⟩ theorem rfind_min' {p : β„• β†’ bool} {m : β„•} (pm : p m) : βˆƒ n ∈ rfind p, n ≀ m := have tt ∈ (p : β„• β†’. bool) m, from ⟨trivial, pm⟩, let ⟨n, hn⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨m, this, Ξ» k h, ⟨⟩⟩ in ⟨n, hn, not_lt.1 $ Ξ» h, by injection mem_unique this (rfind_min hn h)⟩ theorem rfind_zero_none (p : β„• β†’. bool) (p0 : p 0 = none) : rfind p = none := eq_none_iff.2 $ Ξ» a h, let ⟨n, h₁, hβ‚‚βŸ© := rfind_dom'.1 h.fst in (p0 β–Έ hβ‚‚ (zero_le _) : (@roption.none bool).dom) def rfind_opt {Ξ±} (f : β„• β†’ option Ξ±) : roption Ξ± := (rfind (Ξ» n, (f n).is_some)).bind (Ξ» n, f n) theorem rfind_opt_spec {Ξ±} {f : β„• β†’ option Ξ±} {a} (h : a ∈ rfind_opt f) : βˆƒ n, a ∈ f n := let ⟨n, h₁, hβ‚‚βŸ© := mem_bind_iff.1 h in ⟨n, mem_coe.1 hβ‚‚βŸ© theorem rfind_opt_dom {Ξ±} {f : β„• β†’ option Ξ±} : (rfind_opt f).dom ↔ βˆƒ n a, a ∈ f n := ⟨λ h, (rfind_opt_spec ⟨h, rfl⟩).imp (Ξ» n h, ⟨_, h⟩), Ξ» h, begin have h' : βˆƒ n, (f n).is_some := h.imp (Ξ» n, option.is_some_iff_exists.2), have s := nat.find_spec h', have fd : (rfind (Ξ» n, (f n).is_some)).dom := ⟨nat.find h', by simpa using s.symm, Ξ» _ _, trivial⟩, refine ⟨fd, _⟩, have := rfind_spec (get_mem fd), simp at this ⊒, cases option.is_some_iff_exists.1 this.symm with a e, rw e, trivial end⟩ theorem rfind_opt_mono {Ξ±} {f : β„• β†’ option Ξ±} (H : βˆ€ {a m n}, m ≀ n β†’ a ∈ f m β†’ a ∈ f n) {a} : a ∈ rfind_opt f ↔ βˆƒ n, a ∈ f n := ⟨rfind_opt_spec, Ξ» ⟨n, h⟩, begin have h' := rfind_opt_dom.2 ⟨_, _, h⟩, cases rfind_opt_spec ⟨h', rfl⟩ with k hk, have := (H (le_max_left _ _) h).symm.trans (H (le_max_right _ _) hk), simp at this, simp [this, get_mem] end⟩ inductive partrec : (β„• β†’. β„•) β†’ Prop | zero : partrec (pure 0) | succ : partrec succ | left : partrec (Ξ» n, n.unpair.1) | right : partrec (Ξ» n, n.unpair.2) | pair {f g} : partrec f β†’ partrec g β†’ partrec (Ξ» n, mkpair <$> f n <*> g n) | comp {f g} : partrec f β†’ partrec g β†’ partrec (Ξ» n, g n >>= f) | prec {f g} : partrec f β†’ partrec g β†’ partrec (unpaired (Ξ» a n, n.elim (f a) (Ξ» y IH, do i ← IH, g (mkpair a (mkpair y i))))) | rfind {f} : partrec f β†’ partrec (Ξ» a, rfind (Ξ» n, (Ξ» m, m = 0) <$> f (mkpair a n))) namespace partrec theorem of_eq {f g : β„• β†’. β„•} (hf : partrec f) (H : βˆ€ n, f n = g n) : partrec g := (funext H : f = g) β–Έ hf theorem of_eq_tot {f : β„• β†’. β„•} {g : β„• β†’ β„•} (hf : partrec f) (H : βˆ€ n, g n ∈ f n) : partrec g := hf.of_eq (Ξ» n, eq_some_iff.2 (H n)) theorem of_primrec {f : β„• β†’ β„•} (hf : primrec f) : partrec f := begin induction hf, case nat.primrec.zero { exact zero }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact left }, case nat.primrec.right { exact right }, case nat.primrec.pair : f g hf hg pf pg { refine (pf.pair pg).of_eq_tot (Ξ» n, _), simp [has_seq.seq] }, case nat.primrec.comp : f g hf hg pf pg { refine (pf.comp pg).of_eq_tot (Ξ» n, _), simp }, case nat.primrec.prec : f g hf hg pf pg { refine (pf.prec pg).of_eq_tot (Ξ» n, _), simp, induction n.unpair.2 with m IH, {simp}, simp, exact ⟨_, IH, rfl⟩ }, end protected theorem some : partrec some := of_primrec primrec.id theorem none : partrec (Ξ» n, none) := (of_primrec (nat.primrec.const 1)).rfind.of_eq $ Ξ» n, eq_none_iff.2 $ Ξ» a ⟨h, e⟩, by simpa using h theorem prec' {f g h} (hf : partrec f) (hg : partrec g) (hh : partrec h) : partrec (Ξ» a, (f a).bind (Ξ» n, n.elim (g a) (Ξ» y IH, do i ← IH, h (mkpair a (mkpair y i))))) := ((prec hg hh).comp (pair partrec.some hf)).of_eq $ Ξ» a, ext $ Ξ» s, by simp [(<*>)]; exact ⟨λ ⟨n, h₁, hβ‚‚βŸ©, ⟨_, ⟨_, h₁, rfl⟩, by simpa using hβ‚‚βŸ©, Ξ» ⟨_, ⟨n, h₁, rfl⟩, hβ‚‚βŸ©, ⟨_, h₁, by simpa using hβ‚‚βŸ©βŸ© theorem ppred : partrec (Ξ» n, ppred n) := have primrecβ‚‚ (Ξ» n m, if n = nat.succ m then 0 else 1), from (primrec.ite (@@primrec_rel.comp _ _ _ _ _ _ _ primrec.eq primrec.fst (_root_.primrec.succ.comp primrec.snd)) (_root_.primrec.const 0) (_root_.primrec.const 1)).toβ‚‚, (of_primrec (primrecβ‚‚.unpaired'.2 this)).rfind.of_eq $ Ξ» n, begin cases n; simp, { exact eq_none_iff.2 (Ξ» a ⟨⟨m, h, _⟩, _⟩, by simpa [show 0 β‰  m.succ, by intro h; injection h] using h) }, { refine eq_some_iff.2 _, simp, intros m h, simp [ne_of_gt h] } end end partrec end nat def partrec {Ξ± Οƒ} [primcodable Ξ±] [primcodable Οƒ] (f : Ξ± β†’. Οƒ) := nat.partrec (Ξ» n, roption.bind (decode Ξ± n) (Ξ» a, (f a).map encode)) def partrecβ‚‚ {Ξ± Ξ² Οƒ} [primcodable Ξ±] [primcodable Ξ²] [primcodable Οƒ] (f : Ξ± β†’ Ξ² β†’. Οƒ) := partrec (Ξ» p : Ξ± Γ— Ξ², f p.1 p.2) def computable {Ξ± Οƒ} [primcodable Ξ±] [primcodable Οƒ] (f : Ξ± β†’ Οƒ) := partrec (f : Ξ± β†’. Οƒ) def computableβ‚‚ {Ξ± Ξ² Οƒ} [primcodable Ξ±] [primcodable Ξ²] [primcodable Οƒ] (f : Ξ± β†’ Ξ² β†’ Οƒ) := computable (Ξ» p : Ξ± Γ— Ξ², f p.1 p.2) theorem primrec.to_comp {Ξ± Οƒ} [primcodable Ξ±] [primcodable Οƒ] {f : Ξ± β†’ Οƒ} (hf : primrec f) : computable f := (nat.partrec.ppred.comp (nat.partrec.of_primrec hf)).of_eq $ Ξ» n, by simp; cases decode Ξ± n; simp theorem primrecβ‚‚.to_comp {Ξ± Ξ² Οƒ} [primcodable Ξ±] [primcodable Ξ²] [primcodable Οƒ] {f : Ξ± β†’ Ξ² β†’ Οƒ} (hf : primrecβ‚‚ f) : computableβ‚‚ f := hf.to_comp theorem computable.part {Ξ± Οƒ} [primcodable Ξ±] [primcodable Οƒ] {f : Ξ± β†’ Οƒ} (hf : computable f) : partrec (f : Ξ± β†’. Οƒ) := hf theorem computableβ‚‚.part {Ξ± Ξ² Οƒ} [primcodable Ξ±] [primcodable Ξ²] [primcodable Οƒ] {f : Ξ± β†’ Ξ² β†’ Οƒ} (hf : computableβ‚‚ f) : partrecβ‚‚ (Ξ» a, (f a : Ξ² β†’. Οƒ)) := hf namespace computable variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Οƒ : Type*} variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Οƒ] theorem of_eq {f g : Ξ± β†’ Οƒ} (hf : computable f) (H : βˆ€ n, f n = g n) : computable g := (funext H : f = g) β–Έ hf theorem const (s : Οƒ) : computable (Ξ» a : Ξ±, s) := (primrec.const _).to_comp theorem of_option {f : Ξ± β†’ option Ξ²} (hf : computable f) : partrec (Ξ» a, (f a : roption Ξ²)) := (nat.partrec.ppred.comp hf).of_eq $ Ξ» n, begin cases decode Ξ± n with a; simp, cases f a with b; simp end theorem toβ‚‚ {f : Ξ± Γ— Ξ² β†’ Οƒ} (hf : computable f) : computableβ‚‚ (Ξ» a b, f (a, b)) := hf.of_eq $ Ξ» ⟨a, b⟩, rfl protected theorem id : computable (@id Ξ±) := primrec.id.to_comp theorem fst : computable (@prod.fst Ξ± Ξ²) := primrec.fst.to_comp theorem snd : computable (@prod.snd Ξ± Ξ²) := primrec.snd.to_comp theorem pair {f : Ξ± β†’ Ξ²} {g : Ξ± β†’ Ξ³} (hf : computable f) (hg : computable g) : computable (Ξ» a, (f a, g a)) := (hf.pair hg).of_eq $ Ξ» n, by cases decode Ξ± n; simp [(<*>)] theorem unpair : computable nat.unpair := primrec.unpair.to_comp theorem succ : computable nat.succ := primrec.succ.to_comp theorem pred : computable nat.pred := primrec.pred.to_comp theorem nat_bodd : computable nat.bodd := primrec.nat_bodd.to_comp theorem nat_div2 : computable nat.div2 := primrec.nat_div2.to_comp theorem sum_inl : computable (@sum.inl Ξ± Ξ²) := primrec.sum_inl.to_comp theorem sum_inr : computable (@sum.inr Ξ± Ξ²) := primrec.sum_inr.to_comp theorem list_cons : computableβ‚‚ (@list.cons Ξ±) := primrec.list_cons.to_comp theorem list_reverse : computable (@list.reverse Ξ±) := primrec.list_reverse.to_comp theorem list_nth : computableβ‚‚ (@list.nth Ξ±) := primrec.list_nth.to_comp theorem list_append : computableβ‚‚ ((++) : list Ξ± β†’ list Ξ± β†’ list Ξ±) := primrec.list_append.to_comp theorem list_concat : computableβ‚‚ (Ξ» l (a:Ξ±), l ++ [a]) := primrec.list_concat.to_comp theorem list_length : computable (@list.length Ξ±) := primrec.list_length.to_comp theorem vector_cons {n} : computableβ‚‚ (@vector.cons Ξ± n) := primrec.vector_cons.to_comp theorem vector_to_list {n} : computable (@vector.to_list Ξ± n) := primrec.vector_to_list.to_comp theorem vector_length {n} : computable (@vector.length Ξ± n) := primrec.vector_length.to_comp theorem vector_head {n} : computable (@vector.head Ξ± n) := primrec.vector_head.to_comp theorem vector_tail {n} : computable (@vector.tail Ξ± n) := primrec.vector_tail.to_comp theorem vector_nth {n} : computableβ‚‚ (@vector.nth Ξ± n) := primrec.vector_nth.to_comp theorem vector_nth' {n} : computable (@vector.nth Ξ± n) := primrec.vector_nth'.to_comp theorem vector_of_fn' {n} : computable (@vector.of_fn Ξ± n) := primrec.vector_of_fn'.to_comp theorem fin_app {n} : computableβ‚‚ (@id (fin n β†’ Οƒ)) := primrec.fin_app.to_comp protected theorem encode : computable (@encode Ξ± _) := primrec.encode.to_comp protected theorem decode : computable (decode Ξ±) := primrec.decode.to_comp protected theorem of_nat (Ξ±) [denumerable Ξ±] : computable (of_nat Ξ±) := (primrec.of_nat _).to_comp theorem encode_iff {f : Ξ± β†’ Οƒ} : computable (Ξ» a, encode (f a)) ↔ computable f := iff.rfl theorem option_some : computable (@option.some Ξ±) := primrec.option_some.to_comp end computable namespace partrec variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Οƒ : Type*} variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Οƒ] open computable theorem of_eq {f g : Ξ± β†’. Οƒ} (hf : partrec f) (H : βˆ€ n, f n = g n) : partrec g := (funext H : f = g) β–Έ hf theorem of_eq_tot {f : Ξ± β†’. Οƒ} {g : Ξ± β†’ Οƒ} (hf : partrec f) (H : βˆ€ n, g n ∈ f n) : computable g := hf.of_eq (Ξ» a, eq_some_iff.2 (H a)) theorem none : partrec (Ξ» a : Ξ±, @roption.none Οƒ) := nat.partrec.none.of_eq $ Ξ» n, by cases decode Ξ± n; simp protected theorem some : partrec (@roption.some Ξ±) := computable.id theorem const' (s : roption Οƒ) : partrec (Ξ» a : Ξ±, s) := by haveI := classical.dec s.dom; exact (of_option (const (to_option s))).of_eq (Ξ» a, of_to_option s) protected theorem bind {f : Ξ± β†’. Ξ²} {g : Ξ± β†’ Ξ² β†’. Οƒ} (hf : partrec f) (hg : partrecβ‚‚ g) : partrec (Ξ» a, (f a).bind (g a)) := (hg.comp (nat.partrec.some.pair hf)).of_eq $ Ξ» n, by simp [(<*>)]; cases e : decode Ξ± n with a; simp [e, encodek] theorem map {f : Ξ± β†’. Ξ²} {g : Ξ± β†’ Ξ² β†’ Οƒ} (hf : partrec f) (hg : computableβ‚‚ g) : partrec (Ξ» a, (f a).map (g a)) := by simpa [bind_some_eq_map] using @@partrec.bind _ _ _ (Ξ» a b, roption.some (g a b)) hf hg theorem toβ‚‚ {f : Ξ± Γ— Ξ² β†’. Οƒ} (hf : partrec f) : partrecβ‚‚ (Ξ» a b, f (a, b)) := hf.of_eq $ Ξ» ⟨a, b⟩, rfl theorem nat_elim {f : Ξ± β†’ β„•} {g : Ξ± β†’. Οƒ} {h : Ξ± β†’ β„• Γ— Οƒ β†’. Οƒ} (hf : computable f) (hg : partrec g) (hh : partrecβ‚‚ h) : partrec (Ξ» a, (f a).elim (g a) (Ξ» y IH, IH.bind (Ξ» i, h a (y, i)))) := (nat.partrec.prec' hf hg hh).of_eq $ Ξ» n, begin cases e : decode Ξ± n with a; simp [e], induction f a with m IH; simp, rw [IH, bind_map], congr, funext s, simp [encodek] end theorem comp {f : Ξ² β†’. Οƒ} {g : Ξ± β†’ Ξ²} (hf : partrec f) (hg : computable g) : partrec (Ξ» a, f (g a)) := (hf.comp hg).of_eq $ Ξ» n, by simp; cases e : decode Ξ± n with a; simp [e, encodek] theorem nat_iff {f : β„• β†’. β„•} : partrec f ↔ nat.partrec f := by simp [partrec, map_id'] theorem map_encode_iff {f : Ξ± β†’. Οƒ} : partrec (Ξ» a, (f a).map encode) ↔ partrec f := iff.rfl end partrec namespace partrecβ‚‚ variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ξ΄ : Type*} {Οƒ : Type*} variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Ξ΄] [primcodable Οƒ] theorem unpaired {f : β„• β†’ β„• β†’. Ξ±} : partrec (nat.unpaired f) ↔ partrecβ‚‚ f := ⟨λ h, by simpa using h.comp primrecβ‚‚.mkpair.to_comp, Ξ» h, h.comp primrec.unpair.to_comp⟩ theorem unpaired' {f : β„• β†’ β„• β†’. β„•} : nat.partrec (nat.unpaired f) ↔ partrecβ‚‚ f := partrec.nat_iff.symm.trans unpaired theorem comp {f : Ξ² β†’ Ξ³ β†’. Οƒ} {g : Ξ± β†’ Ξ²} {h : Ξ± β†’ Ξ³} (hf : partrecβ‚‚ f) (hg : computable g) (hh : computable h) : partrec (Ξ» a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem compβ‚‚ {f : Ξ³ β†’ Ξ΄ β†’. Οƒ} {g : Ξ± β†’ Ξ² β†’ Ξ³} {h : Ξ± β†’ Ξ² β†’ Ξ΄} (hf : partrecβ‚‚ f) (hg : computableβ‚‚ g) (hh : computableβ‚‚ h) : partrecβ‚‚ (Ξ» a b, f (g a b) (h a b)) := hf.comp hg hh end partrecβ‚‚ namespace computable variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Οƒ : Type*} variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Οƒ] theorem comp {f : Ξ² β†’ Οƒ} {g : Ξ± β†’ Ξ²} (hf : computable f) (hg : computable g) : computable (Ξ» a, f (g a)) := hf.comp hg theorem compβ‚‚ {f : Ξ³ β†’ Οƒ} {g : Ξ± β†’ Ξ² β†’ Ξ³} (hf : computable f) (hg : computableβ‚‚ g) : computableβ‚‚ (Ξ» a b, f (g a b)) := hf.comp hg end computable namespace computableβ‚‚ variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ξ΄ : Type*} {Οƒ : Type*} variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Ξ΄] [primcodable Οƒ] theorem comp {f : Ξ² β†’ Ξ³ β†’ Οƒ} {g : Ξ± β†’ Ξ²} {h : Ξ± β†’ Ξ³} (hf : computableβ‚‚ f) (hg : computable g) (hh : computable h) : computable (Ξ» a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem compβ‚‚ {f : Ξ³ β†’ Ξ΄ β†’ Οƒ} {g : Ξ± β†’ Ξ² β†’ Ξ³} {h : Ξ± β†’ Ξ² β†’ Ξ΄} (hf : computableβ‚‚ f) (hg : computableβ‚‚ g) (hh : computableβ‚‚ h) : computableβ‚‚ (Ξ» a b, f (g a b) (h a b)) := hf.comp hg hh end computableβ‚‚ namespace partrec variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Οƒ : Type*} variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Οƒ] open computable theorem rfind {p : Ξ± β†’ β„• β†’. bool} (hp : partrecβ‚‚ p) : partrec (Ξ» a, nat.rfind (p a)) := (nat.partrec.rfind $ hp.map ((primrec.dom_bool (Ξ» b, cond b 0 1)) .comp primrec.snd).toβ‚‚.to_comp).of_eq $ Ξ» n, begin cases e : decode Ξ± n with a; simp [e, nat.rfind_zero_none, map_id'], congr, funext n, simp [roption.map_map, (∘)], apply map_id' (Ξ» b, _), cases b; refl end theorem rfind_opt {f : Ξ± β†’ β„• β†’ option Οƒ} (hf : computableβ‚‚ f) : partrec (Ξ» a, nat.rfind_opt (f a)) := (rfind (primrec.option_is_some.to_comp.comp hf).part.toβ‚‚).bind (of_option hf) theorem nat_cases_right {f : Ξ± β†’ β„•} {g : Ξ± β†’ Οƒ} {h : Ξ± β†’ β„• β†’. Οƒ} (hf : computable f) (hg : computable g) (hh : partrecβ‚‚ h) : partrec (Ξ» a, (f a).cases (some (g a)) (h a)) := (nat_elim hf hg (hh.comp fst (pred.comp $ hf.comp fst)).toβ‚‚).of_eq $ Ξ» a, begin simp, cases f a; simp, refine ext (Ξ» b, ⟨λ H, _, Ξ» H, _⟩), { rcases mem_bind_iff.1 H with ⟨c, h₁, hβ‚‚βŸ©, exact hβ‚‚ }, { have : βˆ€ m, (nat.elim (roption.some (g a)) (Ξ» y IH, IH.bind (Ξ» _, h a n)) m).dom, { intro, induction m; simp [*, H.fst] }, exact ⟨⟨this n, H.fst⟩, H.snd⟩ } end theorem bind_decode2_iff {f : Ξ± β†’. Οƒ} : partrec f ↔ nat.partrec (Ξ» n, roption.bind (decode2 Ξ± n) (Ξ» a, (f a).map encode)) := ⟨λ hf, nat_iff.1 $ (of_option primrec.decode2.to_comp).bind $ (map hf (computable.encode.comp snd).toβ‚‚).comp snd, Ξ» h, map_encode_iff.1 $ by simpa [encodek2] using (nat_iff.2 h).comp (@computable.encode Ξ± _)⟩ theorem vector_m_of_fn : βˆ€ {n} {f : fin n β†’ Ξ± β†’. Οƒ}, (βˆ€ i, partrec (f i)) β†’ partrec (Ξ» (a : Ξ±), vector.m_of_fn (Ξ» i, f i a)) | 0 f hf := const _ | (n+1) f hf := by simp [vector.m_of_fn]; exact (hf 0).bind (partrec.bind ((vector_m_of_fn (Ξ» i, hf i.succ)).comp fst) (primrec.vector_cons.to_comp.comp (snd.comp fst) snd)) end partrec @[simp] theorem vector.m_of_fn_roption_some {Ξ± n} : βˆ€ (f : fin n β†’ Ξ±), vector.m_of_fn (Ξ» i, roption.some (f i)) = roption.some (vector.of_fn f) := vector.m_of_fn_pure namespace computable variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Οƒ : Type*} variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Οƒ] theorem option_some_iff {f : Ξ± β†’ Οƒ} : computable (Ξ» a, some (f a)) ↔ computable f := ⟨λ h, encode_iff.1 $ primrec.pred.to_comp.comp $ encode_iff.2 h, option_some.comp⟩ theorem bind_decode_iff {f : Ξ± β†’ Ξ² β†’ option Οƒ} : computableβ‚‚ (Ξ» a n, (decode Ξ² n).bind (f a)) ↔ computableβ‚‚ f := ⟨λ hf, nat.partrec.of_eq (((partrec.nat_iff.2 (nat.partrec.ppred.comp $ nat.partrec.of_primrec $ primcodable.prim Ξ²)).comp snd).bind (computable.comp hf fst).toβ‚‚.part) $ Ξ» n, by simp; cases decode Ξ± n.unpair.1; simp; cases decode Ξ² n.unpair.2; simp, Ξ» hf, begin have : partrec (Ξ» a : Ξ± Γ— β„•, (encode (decode Ξ² a.2)).cases (some option.none) (Ξ» n, roption.map (f a.1) (decode Ξ² n))) := partrec.nat_cases_right (primrec.encdec.to_comp.comp snd) (const none) ((of_option (computable.decode.comp snd)).map (hf.comp (fst.comp $ fst.comp fst) snd).toβ‚‚), refine this.of_eq (Ξ» a, _), simp, cases decode Ξ² a.2; simp [encodek] end⟩ theorem map_decode_iff {f : Ξ± β†’ Ξ² β†’ Οƒ} : computableβ‚‚ (Ξ» a n, (decode Ξ² n).map (f a)) ↔ computableβ‚‚ f := bind_decode_iff.trans option_some_iff theorem nat_elim {f : Ξ± β†’ β„•} {g : Ξ± β†’ Οƒ} {h : Ξ± β†’ β„• Γ— Οƒ β†’ Οƒ} (hf : computable f) (hg : computable g) (hh : computableβ‚‚ h) : computable (Ξ» a, (f a).elim (g a) (Ξ» y IH, h a (y, IH))) := (partrec.nat_elim hf hg hh.part).of_eq $ Ξ» a, by simp; induction f a; simp * theorem nat_cases {f : Ξ± β†’ β„•} {g : Ξ± β†’ Οƒ} {h : Ξ± β†’ β„• β†’ Οƒ} (hf : computable f) (hg : computable g) (hh : computableβ‚‚ h) : computable (Ξ» a, (f a).cases (g a) (h a)) := nat_elim hf hg (hh.comp fst $ fst.comp snd).toβ‚‚ theorem cond {c : Ξ± β†’ bool} {f : Ξ± β†’ Οƒ} {g : Ξ± β†’ Οƒ} (hc : computable c) (hf : computable f) (hg : computable g) : computable (Ξ» a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).toβ‚‚).of_eq $ Ξ» a, by cases c a; refl theorem option_cases {o : Ξ± β†’ option Ξ²} {f : Ξ± β†’ Οƒ} {g : Ξ± β†’ Ξ² β†’ Οƒ} (ho : computable o) (hf : computable f) (hg : computableβ‚‚ g) : @computable _ Οƒ _ _ (Ξ» a, option.cases_on (o a) (f a) (g a)) := option_some_iff.1 $ (nat_cases (encode_iff.2 ho) (option_some_iff.2 hf) (map_decode_iff.2 hg)).of_eq $ Ξ» a, by cases o a; simp [encodek]; refl theorem option_bind {f : Ξ± β†’ option Ξ²} {g : Ξ± β†’ Ξ² β†’ option Οƒ} (hf : computable f) (hg : computableβ‚‚ g) : computable (Ξ» a, (f a).bind (g a)) := (option_cases hf (const option.none) hg).of_eq $ Ξ» a, by cases f a; refl theorem option_map {f : Ξ± β†’ option Ξ²} {g : Ξ± β†’ Ξ² β†’ Οƒ} (hf : computable f) (hg : computableβ‚‚ g) : computable (Ξ» a, (f a).map (g a)) := option_bind hf (option_some.compβ‚‚ hg) theorem sum_cases {f : Ξ± β†’ Ξ² βŠ• Ξ³} {g : Ξ± β†’ Ξ² β†’ Οƒ} {h : Ξ± β†’ Ξ³ β†’ Οƒ} (hf : computable f) (hg : computableβ‚‚ g) (hh : computableβ‚‚ h) : @computable _ Οƒ _ _ (Ξ» a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ Ξ» a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem nat_strong_rec (f : Ξ± β†’ β„• β†’ Οƒ) {g : Ξ± β†’ list Οƒ β†’ option Οƒ} (hg : computableβ‚‚ g) (H : βˆ€ a n, g a ((list.range n).map (f a)) = some (f a n)) : computableβ‚‚ f := suffices computableβ‚‚ (Ξ» a n, (list.range n).map (f a)), from option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).toβ‚‚.of_eq $ Ξ» a, by simp [list.nth_range (nat.lt_succ_self a.2)]; refl, option_some_iff.1 $ (nat_elim snd (const (option.some [])) (toβ‚‚ $ option_bind (snd.comp snd) $ toβ‚‚ $ option_map (hg.comp (fst.comp $ fst.comp fst) snd) (toβ‚‚ $ list_concat.comp (snd.comp fst) snd))).of_eq $ Ξ» a, begin simp, induction a.2 with n IH, {refl}, simp [IH, H, list.range_concat] end theorem list_of_fn : βˆ€ {n} {f : fin n β†’ Ξ± β†’ Οƒ}, (βˆ€ i, computable (f i)) β†’ computable (Ξ» a, list.of_fn (Ξ» i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (Ξ» i, hf i.succ)) theorem vector_of_fn {n} {f : fin n β†’ Ξ± β†’ Οƒ} (hf : βˆ€ i, computable (f i)) : computable (Ξ» a, vector.of_fn (Ξ» i, f i a)) := (partrec.vector_m_of_fn hf).of_eq $ Ξ» a, by simp end computable namespace partrec variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Οƒ : Type*} variables [primcodable Ξ±] [primcodable Ξ²] [primcodable Ξ³] [primcodable Οƒ] open computable theorem option_some_iff {f : Ξ± β†’. Οƒ} : partrec (Ξ» a, (f a).map option.some) ↔ partrec f := ⟨λ h, (nat.partrec.ppred.comp h).of_eq $ Ξ» n, by simp [roption.bind_assoc, bind_some_eq_map], Ξ» hf, hf.map (option_some.comp snd).toβ‚‚βŸ© theorem option_cases_right {o : Ξ± β†’ option Ξ²} {f : Ξ± β†’ Οƒ} {g : Ξ± β†’ Ξ² β†’. Οƒ} (ho : computable o) (hf : computable f) (hg : partrecβ‚‚ g) : @partrec _ Οƒ _ _ (Ξ» a, option.cases_on (o a) (some (f a)) (g a)) := have partrec (Ξ» (a : Ξ±), nat.cases (roption.some (f a)) (Ξ» n, roption.bind (decode Ξ² n) (g a)) (encode (o a))) := nat_cases_right (encode_iff.2 ho) hf.part $ ((@computable.decode Ξ² _).comp snd).of_option.bind (hg.comp (fst.comp fst) snd).toβ‚‚, this.of_eq $ Ξ» a, by cases o a with b; simp [encodek] theorem sum_cases_right {f : Ξ± β†’ Ξ² βŠ• Ξ³} {g : Ξ± β†’ Ξ² β†’ Οƒ} {h : Ξ± β†’ Ξ³ β†’. Οƒ} (hf : computable f) (hg : computableβ‚‚ g) (hh : partrecβ‚‚ h) : @partrec _ Οƒ _ _ (Ξ» a, sum.cases_on (f a) (Ξ» b, some (g a b)) (h a)) := have partrec (Ξ» a, (option.cases_on (sum.cases_on (f a) (Ξ» b, option.none) option.some : option Ξ³) (some (sum.cases_on (f a) (Ξ» b, some (g a b)) (Ξ» c, option.none))) (Ξ» c, (h a c).map option.some) : roption (option Οƒ))) := option_cases_right (sum_cases hf (const option.none).toβ‚‚ (option_some.comp snd).toβ‚‚) (sum_cases hf (option_some.comp hg) (const option.none).toβ‚‚) (option_some_iff.2 hh), option_some_iff.1 $ this.of_eq $ Ξ» a, by cases f a; simp theorem sum_cases_left {f : Ξ± β†’ Ξ² βŠ• Ξ³} {g : Ξ± β†’ Ξ² β†’. Οƒ} {h : Ξ± β†’ Ξ³ β†’ Οƒ} (hf : computable f) (hg : partrecβ‚‚ g) (hh : computableβ‚‚ h) : @partrec _ Οƒ _ _ (Ξ» a, sum.cases_on (f a) (g a) (Ξ» c, some (h a c))) := (sum_cases_right (sum_cases hf (sum_inr.comp snd).toβ‚‚ (sum_inl.comp snd).toβ‚‚) hh hg).of_eq $ Ξ» a, by cases f a; simp private lemma fix_aux {f : Ξ± β†’. Οƒ βŠ• Ξ±} (hf : partrec f) (a : Ξ±) (b : Οƒ) : let F : Ξ± β†’ β„• β†’. Οƒ βŠ• Ξ± := Ξ» a n, n.elim (some (sum.inr a)) $ Ξ» y IH, IH.bind $ Ξ» s, sum.cases_on s (Ξ» _, roption.some s) f in (βˆƒ (n : β„•), ((βˆƒ (b' : Οƒ), sum.inl b' ∈ F a n) ∧ βˆ€ {m : β„•}, m < n β†’ (βˆƒ (b : Ξ±), sum.inr b ∈ F a m)) ∧ sum.inl b ∈ F a n) ↔ b ∈ pfun.fix f a := begin intro, refine ⟨λ h, _, Ξ» h, _⟩, { rcases h with ⟨n, ⟨_x, hβ‚βŸ©, hβ‚‚βŸ©, have : βˆ€ m a' (_: sum.inr a' ∈ F a m) (_: b ∈ pfun.fix f a'), b ∈ pfun.fix f a, { intros m a' am ba, induction m with m IH generalizing a'; simp [F] at am, { rwa ← am }, rcases am with ⟨aβ‚‚, amβ‚‚, faβ‚‚βŸ©, exact IH _ amβ‚‚ (pfun.mem_fix_iff.2 (or.inr ⟨_, faβ‚‚, ba⟩)) }, cases n; simp [F] at hβ‚‚, {cases hβ‚‚}, rcases hβ‚‚ with hβ‚‚ | ⟨a', am', fa'⟩, { cases h₁ (nat.lt_succ_self _) with a' h, injection mem_unique h hβ‚‚ }, { exact this _ _ am' (pfun.mem_fix_iff.2 (or.inl fa')) } }, { suffices : βˆ€ a' (_: b ∈ pfun.fix f a') k (_: sum.inr a' ∈ F a k), βˆƒ n, sum.inl b ∈ F a n ∧ βˆ€ (m < n) (_ : k ≀ m), βˆƒ aβ‚‚, sum.inr aβ‚‚ ∈ F a m, { rcases this _ h 0 (by simp [F]) with ⟨n, hn₁, hnβ‚‚βŸ©, exact ⟨_, ⟨⟨_, hnβ‚βŸ©, Ξ» m mn, hnβ‚‚ m mn (nat.zero_le _)⟩, hnβ‚βŸ© }, intros a₁ h₁, apply pfun.fix_induction h₁, intros aβ‚‚ hβ‚‚ IH k hk, rcases pfun.mem_fix_iff.1 hβ‚‚ with hβ‚‚ | ⟨a₃, am₃, faβ‚ƒβŸ©, { refine ⟨k.succ, _, Ξ» m mk km, ⟨aβ‚‚, _⟩⟩, { simp [F], exact or.inr ⟨_, hk, hβ‚‚βŸ© }, { rwa le_antisymm (nat.le_of_lt_succ mk) km } }, { rcases IH _ fa₃ am₃ k.succ _ with ⟨n, hn₁, hnβ‚‚βŸ©, { refine ⟨n, hn₁, Ξ» m mn km, _⟩, cases lt_or_eq_of_le km with km km, { exact hnβ‚‚ _ mn km }, { exact km β–Έ ⟨_, hk⟩ } }, { simp [F], exact ⟨_, hk, amβ‚ƒβŸ© } } } end theorem fix {f : Ξ± β†’. Οƒ βŠ• Ξ±} (hf : partrec f) : partrec (pfun.fix f) := let F : Ξ± β†’ β„• β†’. Οƒ βŠ• Ξ± := Ξ» a n, n.elim (some (sum.inr a)) $ Ξ» y IH, IH.bind $ Ξ» s, sum.cases_on s (Ξ» _, roption.some s) f in have hF : partrecβ‚‚ F := partrec.nat_elim snd (sum_inr.comp fst).part (sum_cases_right (snd.comp snd) (snd.comp $ snd.comp fst).toβ‚‚ (hf.comp snd).toβ‚‚).toβ‚‚, let p := Ξ» a n, @roption.map _ bool (Ξ» s, sum.cases_on s (Ξ»_, tt) (Ξ» _, ff)) (F a n) in have hp : partrecβ‚‚ p := hF.map ((sum_cases computable.id (const tt).toβ‚‚ (const ff).toβ‚‚).comp snd).toβ‚‚, (hp.rfind.bind (hF.bind (sum_cases_right snd snd.toβ‚‚ none.toβ‚‚).toβ‚‚).toβ‚‚).of_eq $ Ξ» a, ext $ Ξ» b, by simp; apply fix_aux hf end partrec
84071c8bd303046b5f20a8db6250f611d794d343
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/nat/cast/prod.lean
4c218abee4acdb9b4e4afb6fa9bdf36c7683e500
[ "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
813
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.nat.cast.basic import algebra.group.prod /-! # The product of two `add_monoid_with_one`s. -/ variables {Ξ± Ξ² : Type*} namespace prod variables [add_monoid_with_one Ξ±] [add_monoid_with_one Ξ²] instance : add_monoid_with_one (Ξ± Γ— Ξ²) := { nat_cast := Ξ» n, (n, n), nat_cast_zero := congr_arg2 prod.mk nat.cast_zero nat.cast_zero, nat_cast_succ := Ξ» n, congr_arg2 prod.mk (nat.cast_succ _) (nat.cast_succ _), .. prod.add_monoid, .. prod.has_one } @[simp] lemma fst_nat_cast (n : β„•) : (n : Ξ± Γ— Ξ²).fst = n := by induction n; simp * @[simp] lemma snd_nat_cast (n : β„•) : (n : Ξ± Γ— Ξ²).snd = n := by induction n; simp * end prod
e1b7a3a6e7b79a9e0093c8f001381231d8ba0d0f
76df16d6c3760cb415f1294caee997cc4736e09b
/lean/src/generation/printer.lean
9836160a2f693d57b1b801230a5f4db5bbd38647
[ "MIT" ]
permissive
uw-unsat/leanette-popl22-artifact
70409d9cbd8921d794d27b7992bf1d9a4087e9fe
80fea2519e61b45a283fbf7903acdf6d5528dbe7
refs/heads/master
1,681,592,449,670
1,637,037,431,000
1,637,037,431,000
414,331,908
6
1
null
null
null
null
UTF-8
Lean
false
false
4,603
lean
import ..op.sym open op.sym def vars.to_str : list β„• β†’ string | [] := "" | (x :: xs) := " " ++ to_string x ++ vars.to_str xs def op.sym.typedop_int.to_str : typedop type.int β†’ string | typedop.add := "add" | typedop.mul := "mul" def op.sym.typedop_bool.to_str : typedop type.bool β†’ string | typedop.lt := "lt" | typedop.eq := "eq" def op.lang.op.to_str : op.lang.op β†’ string | (op.lang.op.int_2 op.lang.op_int_2.add) := "+" | (op.lang.op.int_2 op.lang.op_int_2.mul) := "*" | (op.lang.op.int_2 op.lang.op_int_2.lt) := "<" | (op.lang.op.int_2 op.lang.op_int_2.eq) := "=" | (op.lang.op.list_proj op.lang.op_list_proj.first) := "first" | (op.lang.op.list_proj op.lang.op_list_proj.rest) := "rest" | op.lang.op.list_null := "make-null" | op.lang.op.list_cons := "link" | op.lang.op.list_is_null := "null?" def op.lang.exp.to_str : op.lang.exp β†’ string | (lang.exp.let0 x e_v e_b) := "(let0 " ++ to_string x ++ " " ++ op.lang.exp.to_str e_v ++ " " ++ op.lang.exp.to_str e_b ++ ")" | (lang.exp.datum (op.lang.datum.int z)) := "(datum (op.lang.datum.int " ++ to_string z ++ "))" | (lang.exp.datum op.lang.datum.undef) := "undef" | (lang.exp.app o xs) := "(app " ++ o.to_str ++ vars.to_str xs ++ ")" | (lang.exp.call x y) := "(call " ++ to_string x ++ " " ++ to_string y ++ ")" | (lang.exp.var x) := "(var " ++ to_string x ++ ")" | (lang.exp.if0 x e_t e_e) := "(if0 " ++ to_string x ++ " " ++ op.lang.exp.to_str e_t ++ " " ++ op.lang.exp.to_str e_e ++ ")" | (lang.exp.bool tt) := "#t" | (lang.exp.bool ff) := "#f" | (lang.exp.lam x e_b) := "(Ξ» " ++ to_string x ++ " " ++ op.lang.exp.to_str e_b ++ ")" | lang.exp.error := "(make-error)" | lang.exp.abort := "(make-abort)" mutual def op.sym.term_int.to_str, op.sym.term_bool.to_str with op.sym.term_int.to_str : term type.int β†’ string | (term.lit (lit.int z)) := to_string z | (term.var (@var.mk type.int x)) := "(var " ++ to_string x ++ ")" | (term.ite c t e) := "(ite " ++ op.sym.term_bool.to_str c ++ " " ++ op.sym.term_int.to_str t ++ " " ++ op.sym.term_int.to_str e ++ ")" | (term.expr o l r) := "(expr " ++ op.sym.typedop_int.to_str o ++ " " ++ op.sym.term_int.to_str l ++ " " ++ op.sym.term_int.to_str r ++ ")" with op.sym.term_bool.to_str : term type.bool β†’ string | (term.lit (lit.bool tt)) := "#t" | (term.lit (lit.bool ff)) := "#f" | (term.var (@var.mk type.bool x)) := "(var " ++ to_string x ++ ")" | (term.ite c t e) := "(ite " ++ op.sym.term_bool.to_str c ++ " " ++ op.sym.term_bool.to_str t ++ " " ++ op.sym.term_bool.to_str e ++ ")" | (term.expr o l r) := "(expr " ++ op.sym.typedop_bool.to_str o ++ " " ++ op.sym.term_int.to_str l ++ " " ++ op.sym.term_int.to_str r ++ ")" mutual def op.sym.val_atom.to_str, op.sym.val.to_str, op.sym.vals.to_str, op.sym.vals.to_str_aux, op.sym.choices'.to_str with op.sym.val_atom.to_str : val_atom β†’ string | (op.sym.val_atom.list vs) := op.sym.vals.to_str vs | (@op.sym.val_atom.term type.int t) := "(term_int " ++ op.sym.term_int.to_str t ++ ")" | (@op.sym.val_atom.term type.bool t) := "(term_bool " ++ op.sym.term_bool.to_str t ++ ")" | (op.sym.val_atom.clos x e_b Ξ΅) := "(clos " ++ to_string x ++ " " ++ e_b.to_str ++ " " ++ op.sym.vals.to_str Ξ΅ ++ ")" with op.sym.val.to_str : val β†’ string | (op.sym.val.atom a) := a.to_str | (op.sym.val.union gvs) := "(union" ++ gvs.to_str ++ ")" with op.sym.vals.to_str : list val β†’ string -- we really need only one case, but the well-foundedness for mutual recursion -- is stupid, so let's unroll one more iteration | [] := "(list)" | (v :: vs) := "(list " ++ op.sym.val.to_str v ++ op.sym.vals.to_str_aux vs ++ ")" with op.sym.vals.to_str_aux : list val β†’ string | [] := "" | (v :: vs) := " " ++ op.sym.val.to_str v ++ op.sym.vals.to_str_aux vs with op.sym.choices'.to_str : choices' val_atom β†’ string | [] := "" | (⟨g, va⟩ :: xs) := " (choice " ++ op.sym.term_bool.to_str g ++ " " ++ op.sym.val_atom.to_str va ++ ")" ++ op.sym.choices'.to_str xs def sym.state.to_str : sym.state (term type.bool) β†’ string | ⟨assumes, asserts⟩ := "(state " ++ op.sym.term_bool.to_str assumes ++ " " ++ op.sym.term_bool.to_str asserts ++ ")" def result.to_str : option op.sym.result β†’ string | none := "none" | (some (sym.result.ans Οƒ v)) := "(ans " ++ Οƒ.to_str ++ " " ++ v.to_str ++ ")" | (some (sym.result.halt Οƒ)) := "(halt " ++ Οƒ.to_str ++ ")"
f990027ccd68068af7d2dc8366a426baa35aaca2
9028d228ac200bbefe3a711342514dd4e4458bff
/src/ring_theory/integral_closure.lean
873207d98da7ffe7961f44f82e239225b9d56cf9
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,482
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.algebra_tower import ring_theory.polynomial.scale_roots /-! # Integral closure of a subring. If A is an R-algebra then `a : A` is integral over R if it is a root of a monic polynomial with coefficients in R. Enough theory is developed to prove that integral elements form a sub-R-algebra of A. ## Main definitions Let `R` be a `comm_ring` and let `A` be an R-algebra. * `ring_hom.is_integral_elem (f : R β†’+* A) (x : A)` : `x` is integral with respect to the map `f`, * `is_integral (x : A)` : `x` is integral over `R`, i.e., is a root of a monic polynomial with coefficients in `R`. * `integral_closure R A` : the integral closure of `R` in `A`, regarded as a sub-`R`-algebra of `A`. -/ open_locale classical open_locale big_operators open polynomial submodule section ring variables {R A : Type*} variables [comm_ring R] [ring A] /-- An element `x` of `A` is said to be integral over `R` with respect to `f` if it is a root of a monic polynomial `p : polynomial R` evaluated under `f` -/ def ring_hom.is_integral_elem (f : R β†’+* A) (x : A) := βˆƒ p : polynomial R, monic p ∧ evalβ‚‚ f x p = 0 /-- A ring homomorphism `f : R β†’+* A` is said to be integral if every element `A` is integral with respect to the map `f` -/ def ring_hom.is_integral (f : R β†’+* A) := βˆ€ x : A, f.is_integral_elem x variables [algebra R A] (R) /-- An element `x` of an algebra `A` over a commutative ring `R` is said to be *integral*, if it is a root of some monic polynomial `p : polynomial R`. Equivalently, the element is integral over `R` with respect to the induced `algebra_map` -/ def is_integral (x : A) : Prop := (algebra_map R A).is_integral_elem x variable (A) /-- An algebra is integral if every element of the extension is integral over the base ring -/ def algebra.is_integral : Prop := (algebra_map R A).is_integral variables {R A} theorem is_integral_algebra_map {x : R} : is_integral R (algebra_map R A x) := ⟨X - C x, monic_X_sub_C _, by simp⟩ theorem is_integral_of_noetherian (H : is_noetherian R A) (x : A) : is_integral R x := begin let leval : @linear_map R (polynomial R) A _ _ _ _ _ := (aeval x).to_linear_map, let D : β„• β†’ submodule R A := Ξ» n, (degree_le R n).map leval, let M := well_founded.min (is_noetherian_iff_well_founded.1 H) (set.range D) ⟨_, ⟨0, rfl⟩⟩, have HM : M ∈ set.range D := well_founded.min_mem _ _ _, cases HM with N HN, have HM : Β¬M < D (N+1) := well_founded.not_lt_min (is_noetherian_iff_well_founded.1 H) (set.range D) _ ⟨N+1, rfl⟩, rw ← HN at HM, have HN2 : D (N+1) ≀ D N := classical.by_contradiction (Ξ» H, HM (lt_of_le_not_le (map_mono (degree_le_mono (with_bot.coe_le_coe.2 (nat.le_succ N)))) H)), have HN3 : leval (X^(N+1)) ∈ D N, { exact HN2 (mem_map_of_mem (mem_degree_le.2 (degree_X_pow_le _))) }, rcases HN3 with ⟨p, hdp, hpe⟩, refine ⟨X^(N+1) - p, monic_X_pow_sub (mem_degree_le.1 hdp), _⟩, show leval (X ^ (N + 1) - p) = 0, rw [linear_map.map_sub, hpe, sub_self] end theorem is_integral_of_submodule_noetherian (S : subalgebra R A) (H : is_noetherian R (S : submodule R A)) (x : A) (hx : x ∈ S) : is_integral R x := begin letI : algebra R S := S.algebra, letI : ring S := S.ring R A, suffices : is_integral R (⟨x, hx⟩ : S), { rcases this with ⟨p, hpm, hpx⟩, replace hpx := congr_arg subtype.val hpx, refine ⟨p, hpm, eq.trans _ hpx⟩, simp only [aeval_def, evalβ‚‚, finsupp.sum], rw ← p.support.sum_hom subtype.val, { refine finset.sum_congr rfl (Ξ» n hn, _), change _ = _ * _, rw is_monoid_hom.map_pow coe, refl, split; intros; refl }, refine { map_add := _, map_zero := _ }; intros; refl }, refine is_integral_of_noetherian H ⟨x, hx⟩ end end ring section variables {R : Type*} {A : Type*} {B : Type*} variables [comm_ring R] [comm_ring A] [comm_ring B] variables [algebra R A] [algebra R B] theorem is_integral_alg_hom (f : A →ₐ[R] B) {x : A} (hx : is_integral R x) : is_integral R (f x) := let ⟨p, hp, hpx⟩ := hx in ⟨p, hp, by rw [← aeval_def, aeval_alg_hom_apply, aeval_def, hpx, f.map_zero]⟩ theorem is_integral_of_is_scalar_tower [algebra A B] [is_scalar_tower R A B] (x : B) (hx : is_integral R x) : is_integral A x := let ⟨p, hp, hpx⟩ := hx in ⟨p.map $ algebra_map R A, monic_map _ hp, by rw [← aeval_def, ← is_scalar_tower.aeval_apply, aeval_def, hpx]⟩ theorem is_integral_of_subring {x : A} (T : set R) [is_subring T] (hx : is_integral T x) : is_integral R x := is_integral_of_is_scalar_tower x hx theorem is_integral_iff_is_integral_closure_finite {r : A} : is_integral R r ↔ βˆƒ s : set R, s.finite ∧ is_integral (ring.closure s) r := begin split; intro hr, { rcases hr with ⟨p, hmp, hpr⟩, refine ⟨_, set.finite_mem_finset _, p.restriction, subtype.eq hmp, _⟩, erw [← aeval_def, is_scalar_tower.aeval_apply _ R, map_restriction, aeval_def, hpr] }, rcases hr with ⟨s, hs, hsr⟩, exact is_integral_of_subring _ hsr end theorem fg_adjoin_singleton_of_integral (x : A) (hx : is_integral R x) : (algebra.adjoin R ({x} : set A) : submodule R A).fg := begin rcases hx with ⟨f, hfm, hfx⟩, existsi finset.image ((^) x) (finset.range (nat_degree f + 1)), apply le_antisymm, { rw span_le, intros s hs, rw finset.mem_coe at hs, rcases finset.mem_image.1 hs with ⟨k, hk, rfl⟩, clear hk, exact is_submonoid.pow_mem (algebra.subset_adjoin (set.mem_singleton _)) }, intros r hr, change r ∈ algebra.adjoin R ({x} : set A) at hr, rw algebra.adjoin_singleton_eq_range at hr, rcases (aeval x).mem_range.mp hr with ⟨p, rfl⟩, rw ← mod_by_monic_add_div p hfm, rw ← aeval_def at hfx, rw [alg_hom.map_add, alg_hom.map_mul, hfx, zero_mul, add_zero], have : degree (p %β‚˜ f) ≀ degree f := degree_mod_by_monic_le p hfm, generalize_hyp : p %β‚˜ f = q at this ⊒, rw [← sum_C_mul_X_eq q, aeval_def, evalβ‚‚_sum, finsupp.sum], refine sum_mem _ (Ξ» k hkq, _), rw [evalβ‚‚_mul, evalβ‚‚_C, evalβ‚‚_pow, evalβ‚‚_X, ← algebra.smul_def], refine smul_mem _ _ (subset_span _), rw finset.mem_coe, refine finset.mem_image.2 ⟨_, _, rfl⟩, rw [finset.mem_range, nat.lt_succ_iff], refine le_of_not_lt (Ξ» hk, _), rw [degree_le_iff_coeff_zero] at this, rw [finsupp.mem_support_iff] at hkq, apply hkq, apply this, exact lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 hk) end theorem fg_adjoin_of_finite {s : set A} (hfs : s.finite) (his : βˆ€ x ∈ s, is_integral R x) : (algebra.adjoin R s : submodule R A).fg := set.finite.induction_on hfs (Ξ» _, ⟨{1}, submodule.ext $ Ξ» x, by { erw [algebra.adjoin_empty, finset.coe_singleton, ← one_eq_span, one_eq_map_top, map_top, linear_map.mem_range, algebra.mem_bot], refl }⟩) (Ξ» a s has hs ih his, by rw [← set.union_singleton, algebra.adjoin_union_coe_submodule]; exact fg_mul _ _ (ih $ Ξ» i hi, his i $ set.mem_insert_of_mem a hi) (fg_adjoin_singleton_of_integral _ $ his a $ set.mem_insert a s)) his theorem is_integral_of_mem_of_fg (S : subalgebra R A) (HS : (S : submodule R A).fg) (x : A) (hx : x ∈ S) : is_integral R x := begin cases HS with y hy, obtain ⟨lx, hlx1, hlx2⟩ : βˆƒ (l : A β†’β‚€ R) (H : l ∈ finsupp.supported R R ↑y), (finsupp.total A A R id) l = x, { rwa [←(@finsupp.mem_span_iff_total A A R _ _ _ id ↑y x), set.image_id ↑y, hy] }, have hyS : βˆ€ {p}, p ∈ y β†’ p ∈ S := Ξ» p hp, show p ∈ (S : submodule R A), by { rw ← hy, exact subset_span hp }, have : βˆ€ (jk : (↑(y.product y) : set (A Γ— A))), jk.1.1 * jk.1.2 ∈ (S : submodule R A) := Ξ» jk, S.mul_mem (hyS (finset.mem_product.1 jk.2).1) (hyS (finset.mem_product.1 jk.2).2), rw [← hy, ← set.image_id ↑y] at this, simp only [finsupp.mem_span_iff_total] at this, choose ly hly1 hly2, let Sβ‚€ : set R := ring.closure ↑(lx.frange βˆͺ finset.bind finset.univ (finsupp.frange ∘ ly)), refine is_integral_of_subring Sβ‚€ _, have : span Sβ‚€ (insert 1 ↑y : set A) * span Sβ‚€ (insert 1 ↑y : set A) ≀ span Sβ‚€ (insert 1 ↑y : set A), { rw span_mul_span, refine span_le.2 (Ξ» z hz, _), rcases set.mem_mul.1 hz with ⟨p, q, rfl | hp, hq, rfl⟩, { rw one_mul, exact subset_span hq }, rcases hq with rfl | hq, { rw mul_one, exact subset_span (or.inr hp) }, erw ← hly2 ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, rw [finsupp.total_apply, finsupp.sum], refine (span Sβ‚€ (insert 1 ↑y : set A)).sum_mem (Ξ» t ht, _), have : ly ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩ t ∈ Sβ‚€ := ring.subset_closure (finset.mem_union_right _ $ finset.mem_bind.2 ⟨⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, finset.mem_univ _, finsupp.mem_frange.2 ⟨finsupp.mem_support_iff.1 ht, _, rfl⟩⟩), change (⟨_, this⟩ : Sβ‚€) β€’ t ∈ _, exact smul_mem _ _ (subset_span $ or.inr $ hly1 _ ht) }, haveI : is_subring (span Sβ‚€ (insert 1 ↑y : set A) : set A) := { one_mem := subset_span $ or.inl rfl, mul_mem := Ξ» p q hp hq, this $ mul_mem_mul hp hq, zero_mem := (span Sβ‚€ (insert 1 ↑y : set A)).zero_mem, add_mem := Ξ» _ _, (span Sβ‚€ (insert 1 ↑y : set A)).add_mem, neg_mem := Ξ» _, (span Sβ‚€ (insert 1 ↑y : set A)).neg_mem }, have : span Sβ‚€ (insert 1 ↑y : set A) = algebra.adjoin Sβ‚€ (↑y : set A), { refine le_antisymm (span_le.2 $ set.insert_subset.2 ⟨(algebra.adjoin Sβ‚€ ↑y).one_mem, algebra.subset_adjoin⟩) (Ξ» z hz, _), rw [subalgebra.mem_to_submodule, algebra.mem_adjoin_iff] at hz, rw ← submodule.mem_coe, refine ring.closure_subset (set.union_subset (set.range_subset_iff.2 $ Ξ» t, _) (Ξ» t ht, subset_span $ or.inr ht)) hz, rw algebra.algebra_map_eq_smul_one, exact smul_mem (span Sβ‚€ (insert 1 ↑y : set A)) _ (subset_span $ or.inl rfl) }, haveI : is_noetherian_ring β†₯Sβ‚€ := is_noetherian_ring_closure _ (finset.finite_to_set _), refine is_integral_of_submodule_noetherian (algebra.adjoin Sβ‚€ ↑y) (is_noetherian_of_fg_of_noetherian _ ⟨insert 1 y, by rw [finset.coe_insert, this]⟩) _ _, rw [← hlx2, finsupp.total_apply, finsupp.sum], refine subalgebra.sum_mem _ (Ξ» r hr, _), have : lx r ∈ Sβ‚€ := ring.subset_closure (finset.mem_union_left _ (finset.mem_image_of_mem _ hr)), change (⟨_, this⟩ : Sβ‚€) β€’ r ∈ _, rw finsupp.mem_supported at hlx1, exact subalgebra.smul_mem _ (algebra.subset_adjoin $ hlx1 hr) _ end theorem is_integral_of_mem_closure {x y z : A} (hx : is_integral R x) (hy : is_integral R y) (hz : z ∈ ring.closure ({x, y} : set A)) : is_integral R z := begin have := fg_mul _ _ (fg_adjoin_singleton_of_integral x hx) (fg_adjoin_singleton_of_integral y hy), rw [← algebra.adjoin_union_coe_submodule, set.singleton_union] at this, exact is_integral_of_mem_of_fg (algebra.adjoin R {x, y}) this z (algebra.mem_adjoin_iff.2 $ ring.closure_mono (set.subset_union_right _ _) hz) end theorem is_integral_zero : is_integral R (0:A) := (algebra_map R A).map_zero β–Έ is_integral_algebra_map theorem is_integral_one : is_integral R (1:A) := (algebra_map R A).map_one β–Έ is_integral_algebra_map theorem is_integral_add {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x + y) := is_integral_of_mem_closure hx hy (is_add_submonoid.add_mem (ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl))) theorem is_integral_neg {x : A} (hx : is_integral R x) : is_integral R (-x) := is_integral_of_mem_closure hx hx (is_add_subgroup.neg_mem (ring.subset_closure (or.inl rfl))) theorem is_integral_sub {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x - y) := is_integral_add hx (is_integral_neg hy) theorem is_integral_mul {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x * y) := is_integral_of_mem_closure hx hy (is_submonoid.mul_mem (ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl))) variables (R A) /-- The integral closure of R in an R-algebra A. -/ def integral_closure : subalgebra R A := { carrier := { r | is_integral R r }, zero_mem' := is_integral_zero, one_mem' := is_integral_one, add_mem' := Ξ» _ _, is_integral_add, mul_mem' := Ξ» _ _, is_integral_mul, algebra_map_mem' := Ξ» x, is_integral_algebra_map } theorem mem_integral_closure_iff_mem_fg {r : A} : r ∈ integral_closure R A ↔ βˆƒ M : subalgebra R A, (M : submodule R A).fg ∧ r ∈ M := ⟨λ hr, ⟨algebra.adjoin R {r}, fg_adjoin_singleton_of_integral _ hr, algebra.subset_adjoin rfl⟩, Ξ» ⟨M, Hf, hrM⟩, is_integral_of_mem_of_fg M Hf _ hrM⟩ variables {R} {A} /-- Mapping an integral closure along an `alg_equiv` gives the integral closure. -/ lemma integral_closure_map_alg_equiv (f : A ≃ₐ[R] B) : (integral_closure R A).map (f : A →ₐ[R] B) = integral_closure R B := begin ext y, rw subalgebra.mem_map, split, { rintros ⟨x, hx, rfl⟩, exact is_integral_alg_hom f hx }, { intro hy, use [f.symm y, is_integral_alg_hom (f.symm : B →ₐ[R] A) hy], simp } end lemma integral_closure.is_integral (x : integral_closure R A) : is_integral R x := let ⟨p, hpm, hpx⟩ := x.2 in ⟨p, hpm, subtype.eq $ by rwa [← aeval_def, subtype.val_eq_coe, ← subalgebra.val_apply, aeval_alg_hom_apply] at hpx⟩ theorem is_integral_of_is_integral_mul_unit {x y : A} {r : R} (hr : algebra_map R A r * y = 1) (hx : is_integral R (x * y)) : is_integral R x := begin obtain ⟨p, ⟨p_monic, hp⟩⟩ := hx, refine ⟨scale_roots p r, ⟨(monic_scale_roots_iff r).2 p_monic, _⟩⟩, convert scale_roots_aeval_eq_zero hp, rw [mul_comm x y, ← mul_assoc, hr, one_mul], end end section algebra open algebra variables {R : Type*} {A : Type*} {B : Type*} variables [comm_ring R] [comm_ring A] [comm_ring B] variables [algebra A B] [algebra R B] lemma is_integral_trans_aux (x : B) {p : polynomial A} (pmonic : monic p) (hp : aeval x p = 0) : is_integral (adjoin R (↑(p.map $ algebra_map A B).frange : set B)) x := begin generalize hS : (↑(p.map $ algebra_map A B).frange : set B) = S, have coeffs_mem : βˆ€ i, (p.map $ algebra_map A B).coeff i ∈ adjoin R S, { intro i, by_cases hi : (p.map $ algebra_map A B).coeff i = 0, { rw hi, exact subalgebra.zero_mem _ }, rw ← hS, exact subset_adjoin (finsupp.mem_frange.2 ⟨hi, i, rfl⟩) }, obtain ⟨q, hq⟩ : βˆƒ q : polynomial (adjoin R S), q.map (algebra_map (adjoin R S) B) = (p.map $ algebra_map A B), { rw ← set.mem_range, exact (polynomial.mem_map_range _).2 (Ξ» i, ⟨⟨_, coeffs_mem i⟩, rfl⟩) }, use q, split, { suffices h : (q.map (algebra_map (adjoin R S) B)).monic, { refine monic_of_injective _ h, exact subtype.val_injective }, { rw hq, exact monic_map _ pmonic } }, { convert hp using 1, replace hq := congr_arg (eval x) hq, convert hq using 1; symmetry; apply eval_map }, end variables [algebra R A] [is_scalar_tower R A B] /-- If A is an R-algebra all of whose elements are integral over R, and x is an element of an A-algebra that is integral over A, then x is integral over R.-/ lemma is_integral_trans (A_int : is_integral R A) (x : B) (hx : is_integral A x) : is_integral R x := begin rcases hx with ⟨p, pmonic, hp⟩, let S : set B := ↑(p.map $ algebra_map A B).frange, refine is_integral_of_mem_of_fg (adjoin R (S βˆͺ {x})) _ _ (subset_adjoin $ or.inr rfl), refine fg_trans (fg_adjoin_of_finite (finset.finite_to_set _) (Ξ» x hx, _)) _, { rw [finset.mem_coe, finsupp.mem_frange] at hx, rcases hx with ⟨_, i, rfl⟩, show is_integral R ((p.map $ algebra_map A B).coeff i), rw coeff_map, convert is_integral_alg_hom (is_scalar_tower.to_alg_hom R A B) (A_int _) }, { apply fg_adjoin_singleton_of_integral, exact is_integral_trans_aux _ pmonic hp } end /-- If A is an R-algebra all of whose elements are integral over R, and B is an A-algebra all of whose elements are integral over A, then all elements of B are integral over R.-/ lemma algebra.is_integral_trans (hA : is_integral R A) (hB : is_integral A B) : is_integral R B := Ξ» x, is_integral_trans hA x (hB x) lemma is_integral_of_surjective (h : function.surjective (algebra_map R A)) : is_integral R A := Ξ» x, (h x).rec_on (Ξ» y hy, (hy β–Έ is_integral_algebra_map : is_integral R x)) /-- If `R β†’ A β†’ B` is an algebra tower with `A β†’ B` injective, then if the entire tower is an integral extension so is `R β†’ A` -/ lemma is_integral_tower_bot_of_is_integral (H : function.injective (algebra_map A B)) {x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x := begin rcases h with ⟨p, ⟨hp, hp'⟩⟩, refine ⟨p, ⟨hp, _⟩⟩, rw [is_scalar_tower.algebra_map_eq R A B, ← evalβ‚‚_map, evalβ‚‚_hom, ← ring_hom.map_zero (algebra_map A B)] at hp', rw [evalβ‚‚_eq_eval_map], exact H hp', end lemma is_integral_tower_bot_of_is_integral_field {R A B : Type*} [comm_ring R] [field A] [comm_ring B] [nontrivial B] [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B] {x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x := is_integral_tower_bot_of_is_integral (algebra_map A B).injective h /-- If `R β†’ A β†’ B` is an algebra tower, then if the entire tower is an integral extension so is `A β†’ B` -/ lemma is_integral_tower_top_of_is_integral {x : B} (h : is_integral R x) : is_integral A x := begin rcases h with ⟨p, ⟨hp, hp'⟩⟩, refine ⟨p.map (algebra_map R A), ⟨monic_map (algebra_map R A) hp, _⟩⟩, rw [is_scalar_tower.algebra_map_eq R A B, ← evalβ‚‚_map] at hp', exact hp', end lemma is_integral_quotient_of_is_integral {I : ideal A} (hRA : is_integral R A) : is_integral (I.comap (algebra_map R A)).quotient I.quotient := begin rintros ⟨x⟩, obtain ⟨p, ⟨p_monic, hpx⟩⟩ := hRA x, refine ⟨p.map (ideal.quotient.mk _), ⟨monic_map _ p_monic, _⟩⟩, simpa only [aeval_def, hom_evalβ‚‚, evalβ‚‚_map] using congr_arg (ideal.quotient.mk I) hpx end /-- If the integral extension `R β†’ S` is injective, and `S` is a field, then `R` is also a field -/ lemma is_field_of_is_integral_of_is_field {R S : Type*} [integral_domain R] [integral_domain S] [algebra R S] (H : is_integral R S) (hRS : function.injective (algebra_map R S)) (hS : is_field S) : is_field R := begin refine ⟨⟨0, 1, zero_ne_one⟩, mul_comm, Ξ» a ha, _⟩, -- Let `a_inv` be the inverse of `algebra_map R S a`, -- then we need to show that `a_inv` is of the form `algebra_map R S b`. obtain ⟨a_inv, ha_inv⟩ := hS.mul_inv_cancel (Ξ» h, ha (hRS (trans h (ring_hom.map_zero _).symm))), -- Let `p : polynomial R` be monic with root `a_inv`, -- and `q` be `p` with coefficients reversed (so `q(a) = q'(a) * a + 1`). -- We claim that `q(a) = 0`, so `-q'(a)` is the inverse of `a`. obtain ⟨p, p_monic, hp⟩ := H a_inv, use -βˆ‘ (i : β„•) in finset.range p.nat_degree, (p.coeff i) * a ^ (p.nat_degree - i - 1), -- `q(a) = 0`, because multiplying everything with `a_inv^n` gives `p(a_inv) = 0`. -- TODO: this could be a lemma for `polynomial.reverse`. have hq : βˆ‘ (i : β„•) in finset.range (p.nat_degree + 1), (p.coeff i) * a ^ (p.nat_degree - i) = 0, { apply (algebra_map R S).injective_iff.mp hRS, have a_inv_ne_zero : a_inv β‰  0 := right_ne_zero_of_mul (mt ha_inv.symm.trans one_ne_zero), refine (mul_eq_zero.mp _).resolve_right (pow_ne_zero p.nat_degree a_inv_ne_zero), rw [evalβ‚‚_eq_sum_range] at hp, rw [ring_hom.map_sum, finset.sum_mul], refine (finset.sum_congr rfl (Ξ» i hi, _)).trans hp, rw [ring_hom.map_mul, mul_assoc], congr, have : a_inv ^ p.nat_degree = a_inv ^ (p.nat_degree - i) * a_inv ^ i, { rw [← pow_add a_inv, nat.sub_add_cancel (nat.le_of_lt_succ (finset.mem_range.mp hi))] }, rw [ring_hom.map_pow, this, ← mul_assoc, ← mul_pow, ha_inv, one_pow, one_mul] }, -- Since `q(a) = 0` and `q(a) = q'(a) * a + 1`, we have `a * -q'(a) = 1`. -- TODO: we could use a lemma for `polynomial.div_X` here. rw [finset.sum_range_succ, p_monic.coeff_nat_degree, one_mul, nat.sub_self, pow_zero, add_eq_zero_iff_eq_neg, eq_comm] at hq, rw [mul_comm, ← neg_mul_eq_neg_mul, finset.sum_mul], convert hq using 2, refine finset.sum_congr rfl (Ξ» i hi, _), have : 1 ≀ p.nat_degree - i := nat.le_sub_left_of_add_le (finset.mem_range.mp hi), rw [mul_assoc, ← pow_succ', nat.sub_add_cancel this] end end algebra theorem integral_closure_idem {R : Type*} {A : Type*} [comm_ring R] [comm_ring A] [algebra R A] : integral_closure (integral_closure R A : set A) A = βŠ₯ := eq_bot_iff.2 $ Ξ» x hx, algebra.mem_bot.2 ⟨⟨x, @is_integral_trans _ _ _ _ _ _ _ _ (integral_closure R A).algebra _ integral_closure.is_integral x hx⟩, rfl⟩ section integral_domain variables {R S : Type*} [comm_ring R] [integral_domain S] [algebra R S] instance : integral_domain (integral_closure R S) := { exists_pair_ne := ⟨0, 1, mt subtype.ext_iff_val.mp zero_ne_one⟩, eq_zero_or_eq_zero_of_mul_eq_zero := Ξ» ⟨a, ha⟩ ⟨b, hb⟩ h, or.imp subtype.ext_iff_val.mpr subtype.ext_iff_val.mpr (eq_zero_or_eq_zero_of_mul_eq_zero (subtype.ext_iff_val.mp h)), ..(integral_closure R S).comm_ring R S } end integral_domain
53f89687c95c4989c20dd8ce8ec146660d638b43
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/group/action.lean
3fa13676beccd56843931d082288294504f19887
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
10,566
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import measure_theory.group.measurable_equiv import measure_theory.measure.regular import dynamics.ergodic.measure_preserving import dynamics.minimal /-! # Measures invariant under group actions A measure `ΞΌ : measure Ξ±` is said to be *invariant* under an action of a group `G` if scalar multiplication by `c : G` is a measure preserving map for all `c`. In this file we define a typeclass for measures invariant under action of an (additive or multiplicative) group and prove some basic properties of such measures. -/ open_locale ennreal nnreal pointwise topology open measure_theory measure_theory.measure set function namespace measure_theory variables {G M Ξ± : Type*} {s : set Ξ±} /-- A measure `ΞΌ : measure Ξ±` is invariant under an additive action of `M` on `Ξ±` if for any measurable set `s : set Ξ±` and `c : M`, the measure of its preimage under `Ξ» x, c +α΅₯ x` is equal to the measure of `s`. -/ class vadd_invariant_measure (M Ξ± : Type*) [has_vadd M Ξ±] {_ : measurable_space Ξ±} (ΞΌ : measure Ξ±) : Prop := (measure_preimage_vadd [] : βˆ€ (c : M) ⦃s : set α⦄, measurable_set s β†’ ΞΌ ((Ξ» x, c +α΅₯ x) ⁻¹' s) = ΞΌ s) /-- A measure `ΞΌ : measure Ξ±` is invariant under a multiplicative action of `M` on `Ξ±` if for any measurable set `s : set Ξ±` and `c : M`, the measure of its preimage under `Ξ» x, c β€’ x` is equal to the measure of `s`. -/ @[to_additive] class smul_invariant_measure (M Ξ± : Type*) [has_smul M Ξ±] {_ : measurable_space Ξ±} (ΞΌ : measure Ξ±) : Prop := (measure_preimage_smul [] : βˆ€ (c : M) ⦃s : set α⦄, measurable_set s β†’ ΞΌ ((Ξ» x, c β€’ x) ⁻¹' s) = ΞΌ s) namespace smul_invariant_measure @[to_additive] instance zero [measurable_space Ξ±] [has_smul M Ξ±] : smul_invariant_measure M Ξ± 0 := ⟨λ _ _ _, rfl⟩ variables [has_smul M Ξ±] {m : measurable_space Ξ±} {ΞΌ Ξ½ : measure Ξ±} @[to_additive] instance add [smul_invariant_measure M Ξ± ΞΌ] [smul_invariant_measure M Ξ± Ξ½] : smul_invariant_measure M Ξ± (ΞΌ + Ξ½) := ⟨λ c s hs, show _ + _ = _ + _, from congr_arg2 (+) (measure_preimage_smul ΞΌ c hs) (measure_preimage_smul Ξ½ c hs)⟩ @[to_additive] instance smul [smul_invariant_measure M Ξ± ΞΌ] (c : ℝβ‰₯0∞) : smul_invariant_measure M Ξ± (c β€’ ΞΌ) := ⟨λ a s hs, show c β€’ _ = c β€’ _, from congr_arg ((β€’) c) (measure_preimage_smul ΞΌ a hs)⟩ @[to_additive] instance smul_nnreal [smul_invariant_measure M Ξ± ΞΌ] (c : ℝβ‰₯0) : smul_invariant_measure M Ξ± (c β€’ ΞΌ) := smul_invariant_measure.smul c end smul_invariant_measure section has_measurable_smul variables {m : measurable_space Ξ±} [measurable_space M] [has_smul M Ξ±] [has_measurable_smul M Ξ±] (c : M) (ΞΌ : measure Ξ±) [smul_invariant_measure M Ξ± ΞΌ] @[simp, to_additive] lemma measure_preserving_smul : measure_preserving ((β€’) c) ΞΌ ΞΌ := { measurable := measurable_const_smul c, map_eq := begin ext1 s hs, rw map_apply (measurable_const_smul c) hs, exact smul_invariant_measure.measure_preimage_smul ΞΌ c hs, end } @[simp, to_additive] lemma map_smul : map ((β€’) c) ΞΌ = ΞΌ := (measure_preserving_smul c ΞΌ).map_eq end has_measurable_smul variables (G) {m : measurable_space Ξ±} [group G] [mul_action G Ξ±] [measurable_space G] [has_measurable_smul G Ξ±] (c : G) (ΞΌ : measure Ξ±) /-- Equivalent definitions of a measure invariant under a multiplicative action of a group. - 0: `smul_invariant_measure G Ξ± ΞΌ`; - 1: for every `c : G` and a measurable set `s`, the measure of the preimage of `s` under scalar multiplication by `c` is equal to the measure of `s`; - 2: for every `c : G` and a measurable set `s`, the measure of the image `c β€’ s` of `s` under scalar multiplication by `c` is equal to the measure of `s`; - 3, 4: properties 2, 3 for any set, including non-measurable ones; - 5: for any `c : G`, scalar multiplication by `c` maps `ΞΌ` to `ΞΌ`; - 6: for any `c : G`, scalar multiplication by `c` is a measure preserving map. -/ @[to_additive] lemma smul_invariant_measure_tfae : tfae [smul_invariant_measure G Ξ± ΞΌ, βˆ€ (c : G) s, measurable_set s β†’ ΞΌ (((β€’) c) ⁻¹' s) = ΞΌ s, βˆ€ (c : G) s, measurable_set s β†’ ΞΌ (c β€’ s) = ΞΌ s, βˆ€ (c : G) s, ΞΌ (((β€’) c) ⁻¹' s) = ΞΌ s, βˆ€ (c : G) s, ΞΌ (c β€’ s) = ΞΌ s, βˆ€ c : G, measure.map ((β€’) c) ΞΌ = ΞΌ, βˆ€ c : G, measure_preserving ((β€’) c) ΞΌ ΞΌ] := begin tfae_have : 1 ↔ 2, from ⟨λ h, h.1, Ξ» h, ⟨h⟩⟩, tfae_have : 1 β†’ 6, { introsI h c, exact (measure_preserving_smul c ΞΌ).map_eq, }, tfae_have : 6 β†’ 7, from Ξ» H c, ⟨measurable_const_smul c, H c⟩, tfae_have : 7 β†’ 4, from Ξ» H c, (H c).measure_preimage_emb (measurable_embedding_const_smul c), tfae_have : 4 β†’ 5, from Ξ» H c s, by { rw [← preimage_smul_inv], apply H }, tfae_have : 5 β†’ 3, from Ξ» H c s hs, H c s, tfae_have : 3 β†’ 2, { intros H c s hs, rw preimage_smul, exact H c⁻¹ s hs }, tfae_finish end /-- Equivalent definitions of a measure invariant under an additive action of a group. - 0: `vadd_invariant_measure G Ξ± ΞΌ`; - 1: for every `c : G` and a measurable set `s`, the measure of the preimage of `s` under vector addition `(+α΅₯) c` is equal to the measure of `s`; - 2: for every `c : G` and a measurable set `s`, the measure of the image `c +α΅₯ s` of `s` under vector addition `(+α΅₯) c` is equal to the measure of `s`; - 3, 4: properties 2, 3 for any set, including non-measurable ones; - 5: for any `c : G`, vector addition of `c` maps `ΞΌ` to `ΞΌ`; - 6: for any `c : G`, vector addition of `c` is a measure preserving map. -/ add_decl_doc vadd_invariant_measure_tfae variables {G} [smul_invariant_measure G Ξ± ΞΌ] @[simp, to_additive] lemma measure_preimage_smul (s : set Ξ±) : ΞΌ ((β€’) c ⁻¹' s) = ΞΌ s := ((smul_invariant_measure_tfae G ΞΌ).out 0 3).mp β€Ή_β€Ί c s @[simp, to_additive] lemma measure_smul (s : set Ξ±) : ΞΌ (c β€’ s) = ΞΌ s := ((smul_invariant_measure_tfae G ΞΌ).out 0 4).mp β€Ή_β€Ί c s variable {ΞΌ} @[to_additive] lemma null_measurable_set.smul {s} (hs : null_measurable_set s ΞΌ) (c : G) : null_measurable_set (c β€’ s) ΞΌ := by simpa only [← preimage_smul_inv] using hs.preimage (measure_preserving_smul _ _).quasi_measure_preserving lemma measure_smul_null {s} (h : ΞΌ s = 0) (c : G) : ΞΌ (c β€’ s) = 0 := by rwa measure_smul section is_minimal variables (G) [topological_space Ξ±] [has_continuous_const_smul G Ξ±] [mul_action.is_minimal G Ξ±] {K U : set Ξ±} /-- If measure `ΞΌ` is invariant under a group action and is nonzero on a compact set `K`, then it is positive on any nonempty open set. In case of a regular measure, one can assume `ΞΌ β‰  0` instead of `ΞΌ K β‰  0`, see `measure_theory.measure_is_open_pos_of_smul_invariant_of_ne_zero`. -/ @[to_additive] lemma measure_is_open_pos_of_smul_invariant_of_compact_ne_zero (hK : is_compact K) (hΞΌK : ΞΌ K β‰  0) (hU : is_open U) (hne : U.nonempty) : 0 < ΞΌ U := let ⟨t, ht⟩ := hK.exists_finite_cover_smul G hU hne in pos_iff_ne_zero.2 $ Ξ» hΞΌU, hΞΌK $ measure_mono_null ht $ (measure_bUnion_null_iff t.countable_to_set).2 $ Ξ» _ _, by rwa measure_smul /-- If measure `ΞΌ` is invariant under an additive group action and is nonzero on a compact set `K`, then it is positive on any nonempty open set. In case of a regular measure, one can assume `ΞΌ β‰  0` instead of `ΞΌ K β‰  0`, see `measure_theory.measure_is_open_pos_of_vadd_invariant_of_ne_zero`. -/ add_decl_doc measure_is_open_pos_of_vadd_invariant_of_compact_ne_zero @[to_additive] lemma is_locally_finite_measure_of_smul_invariant (hU : is_open U) (hne : U.nonempty) (hΞΌU : ΞΌ U β‰  ∞) : is_locally_finite_measure ΞΌ := ⟨λ x, let ⟨g, hg⟩ := hU.exists_smul_mem G x hne in ⟨(β€’) g ⁻¹' U, (hU.preimage (continuous_id.const_smul _)).mem_nhds hg, ne.lt_top $ by rwa [measure_preimage_smul]⟩⟩ variables [measure.regular ΞΌ] @[to_additive] lemma measure_is_open_pos_of_smul_invariant_of_ne_zero (hΞΌ : ΞΌ β‰  0) (hU : is_open U) (hne : U.nonempty) : 0 < ΞΌ U := let ⟨K, hK, hΞΌK⟩ := regular.exists_compact_not_null.mpr hΞΌ in measure_is_open_pos_of_smul_invariant_of_compact_ne_zero G hK hΞΌK hU hne @[to_additive] lemma measure_pos_iff_nonempty_of_smul_invariant (hΞΌ : ΞΌ β‰  0) (hU : is_open U) : 0 < ΞΌ U ↔ U.nonempty := ⟨λ h, nonempty_of_measure_ne_zero h.ne', measure_is_open_pos_of_smul_invariant_of_ne_zero G hΞΌ hU⟩ include G @[to_additive] lemma measure_eq_zero_iff_eq_empty_of_smul_invariant (hΞΌ : ΞΌ β‰  0) (hU : is_open U) : ΞΌ U = 0 ↔ U = βˆ… := by rw [← not_iff_not, ← ne.def, ← pos_iff_ne_zero, measure_pos_iff_nonempty_of_smul_invariant G hΞΌ hU, nonempty_iff_ne_empty] end is_minimal lemma smul_ae_eq_self_of_mem_zpowers {x y : G} (hs : (x β€’ s : set Ξ±) =ᡐ[ΞΌ] s) (hy : y ∈ subgroup.zpowers x) : (y β€’ s : set Ξ±) =ᡐ[ΞΌ] s := begin obtain ⟨k, rfl⟩ := subgroup.mem_zpowers_iff.mp hy, let e : Ξ± ≃ Ξ± := mul_action.to_perm_hom G Ξ± x, have he : quasi_measure_preserving e ΞΌ ΞΌ := (measure_preserving_smul x ΞΌ).quasi_measure_preserving, have he' : quasi_measure_preserving e.symm ΞΌ ΞΌ := (measure_preserving_smul x⁻¹ ΞΌ).quasi_measure_preserving, simpa only [mul_action.to_perm_hom_apply, mul_action.to_perm_apply, image_smul, ← monoid_hom.map_zpow] using he.image_zpow_ae_eq he' k hs, end lemma vadd_ae_eq_self_of_mem_zmultiples {G : Type*} [measurable_space G] [add_group G] [add_action G Ξ±] [vadd_invariant_measure G Ξ± ΞΌ] [has_measurable_vadd G Ξ±] {x y : G} (hs : (x +α΅₯ s : set Ξ±) =ᡐ[ΞΌ] s) (hy : y ∈ add_subgroup.zmultiples x) : (y +α΅₯ s : set Ξ±) =ᡐ[ΞΌ] s := begin letI : measurable_space (multiplicative G) := (by apply_instance : measurable_space G), letI : smul_invariant_measure (multiplicative G) Ξ± ΞΌ := ⟨λ g, vadd_invariant_measure.measure_preimage_vadd ΞΌ (multiplicative.to_add g)⟩, letI : has_measurable_smul (multiplicative G) Ξ± := { measurable_const_smul := Ξ» g, measurable_const_vadd (multiplicative.to_add g), measurable_smul_const := Ξ» a, @measurable_vadd_const (multiplicative G) Ξ± (by apply_instance : has_vadd G Ξ±) _ _ (by apply_instance : has_measurable_vadd G Ξ±) a }, exact @smul_ae_eq_self_of_mem_zpowers (multiplicative G) Ξ± _ _ _ _ _ _ _ _ _ _ hs hy, end attribute [to_additive vadd_ae_eq_self_of_mem_zmultiples] smul_ae_eq_self_of_mem_zpowers end measure_theory
13966a2289c83a39e05f398626845e375c78fa96
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/computability/partrec_code.lean
80f8f4f17aa3a42213d8befc94c9ad19ba6a1269
[ "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
38,823
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Godel numbering for partial recursive functions. -/ import computability.partrec open encodable denumerable namespace nat.partrec open nat (mkpair) theorem rfind' {f} (hf : nat.partrec f) : nat.partrec (nat.unpaired (Ξ» a m, (nat.rfind (Ξ» n, (Ξ» m, m = 0) <$> f (mkpair a (n + m)))).map (+ m))) := partrecβ‚‚.unpaired'.2 $ begin refine partrec.map ((@partrecβ‚‚.unpaired' (Ξ» (a b : β„•), nat.rfind (Ξ» n, (Ξ» m, m = 0) <$> f (mkpair a (n + b))))).1 _) (primrec.nat_add.comp primrec.snd $ primrec.snd.comp primrec.fst).to_comp.toβ‚‚, have := rfind (partrecβ‚‚.unpaired'.2 ((partrec.nat_iff.2 hf).comp (primrecβ‚‚.mkpair.comp (primrec.fst.comp $ primrec.unpair.comp primrec.fst) (primrec.nat_add.comp primrec.snd (primrec.snd.comp $ primrec.unpair.comp primrec.fst))).to_comp).toβ‚‚), simp at this, exact this end inductive code : Type | zero : code | succ : code | left : code | right : code | pair : code β†’ code β†’ code | comp : code β†’ code β†’ code | prec : code β†’ code β†’ code | rfind' : code β†’ code end nat.partrec namespace nat.partrec.code open nat (mkpair unpair) open nat.partrec (code) instance : inhabited code := ⟨zero⟩ protected def const : β„• β†’ code | 0 := zero | (n+1) := comp succ (const n) theorem const_inj : Ξ  {n₁ nβ‚‚}, nat.partrec.code.const n₁ = nat.partrec.code.const nβ‚‚ β†’ n₁ = nβ‚‚ | 0 0 h := by simp | (n₁+1) (nβ‚‚+1) h := by { dsimp [nat.partrec.code.const] at h, injection h with h₁ hβ‚‚, simp only [const_inj hβ‚‚] } protected def id : code := pair left right def curry (c : code) (n : β„•) : code := comp c (pair (code.const n) code.id) def encode_code : code β†’ β„• | zero := 0 | succ := 1 | left := 2 | right := 3 | (pair cf cg) := bit0 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (comp cf cg) := bit0 (bit1 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (prec cf cg) := bit1 (bit0 $ mkpair (encode_code cf) (encode_code cg)) + 4 | (rfind' cf) := bit1 (bit1 $ encode_code cf) + 4 def of_nat_code : β„• β†’ code | 0 := zero | 1 := succ | 2 := left | 3 := right | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, match n.bodd, n.div2.bodd with | ff, ff := pair (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | ff, tt := comp (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, ff := prec (of_nat_code m.unpair.1) (of_nat_code m.unpair.2) | tt, tt := rfind' (of_nat_code m) end private theorem encode_of_nat_code : βˆ€ n, encode_code (of_nat_code n) = n | 0 := by simp [of_nat_code, encode_code] | 1 := by simp [of_nat_code, encode_code] | 2 := by simp [of_nat_code, encode_code] | 3 := by simp [of_nat_code, encode_code] | (n+4) := let m := n.div2.div2 in have hm : m < n + 4, by simp [m, nat.div2_val]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, have IH : _ := encode_of_nat_code m, have IH1 : _ := encode_of_nat_code m.unpair.1, have IH2 : _ := encode_of_nat_code m.unpair.2, begin transitivity, swap, rw [← nat.bit_decomp n, ← nat.bit_decomp n.div2], simp [encode_code, of_nat_code, -add_comm], cases n.bodd; cases n.div2.bodd; simp [encode_code, of_nat_code, -add_comm, IH, IH1, IH2, m, nat.bit] end instance : denumerable code := mk' ⟨encode_code, of_nat_code, Ξ» c, by induction c; try {refl}; simp [ encode_code, of_nat_code, -add_comm, *], encode_of_nat_code⟩ theorem encode_code_eq : encode = encode_code := rfl theorem of_nat_code_eq : of_nat code = of_nat_code := rfl theorem encode_lt_pair (cf cg) : encode cf < encode (pair cf cg) ∧ encode cg < encode (pair cf cg) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≀ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, have := lt_of_le_of_lt this (lt_add_of_pos_right _ (dec_trivial:0<4)), exact ⟨ lt_of_le_of_lt (nat.left_le_mkpair _ _) this, lt_of_le_of_lt (nat.right_le_mkpair _ _) this⟩ end theorem encode_lt_comp (cf cg) : encode cf < encode (comp cf cg) ∧ encode cg < encode (comp cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (Ξ» h, lt_trans h this) (Ξ» h, lt_trans h this), change _, simp [encode_code_eq, encode_code] end theorem encode_lt_prec (cf cg) : encode cf < encode (prec cf cg) ∧ encode cg < encode (prec cf cg) := begin suffices, exact (encode_lt_pair cf cg).imp (Ξ» h, lt_trans h this) (Ξ» h, lt_trans h this), change _, simp [encode_code_eq, encode_code], end theorem encode_lt_rfind' (cf) : encode cf < encode (rfind' cf) := begin simp [encode_code_eq, encode_code, -add_comm], have := nat.mul_le_mul_right _ (dec_trivial : 1 ≀ 2*2), rw [one_mul, mul_assoc, ← bit0_eq_two_mul, ← bit0_eq_two_mul] at this, refine lt_of_le_of_lt (le_trans this _) (lt_add_of_pos_right _ (dec_trivial:0<4)), exact le_of_lt (nat.bit0_lt_bit1 $ le_of_lt $ nat.bit0_lt_bit1 $ le_rfl), end section open primrec theorem pair_prim : primrecβ‚‚ pair := primrecβ‚‚.of_nat_iff.2 $ primrecβ‚‚.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit0.comp $ primrecβ‚‚.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrecβ‚‚.const 4) theorem comp_prim : primrecβ‚‚ comp := primrecβ‚‚.of_nat_iff.2 $ primrecβ‚‚.encode_iff.1 $ nat_add.comp (nat_bit0.comp $ nat_bit1.comp $ primrecβ‚‚.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrecβ‚‚.const 4) theorem prec_prim : primrecβ‚‚ prec := primrecβ‚‚.of_nat_iff.2 $ primrecβ‚‚.encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit0.comp $ primrecβ‚‚.mkpair.comp (encode_iff.2 $ (primrec.of_nat code).comp fst) (encode_iff.2 $ (primrec.of_nat code).comp snd)) (primrecβ‚‚.const 4) theorem rfind_prim : primrec rfind' := of_nat_iff.2 $ encode_iff.1 $ nat_add.comp (nat_bit1.comp $ nat_bit1.comp $ encode_iff.2 $ primrec.of_nat code) (const 4) theorem rec_prim' {Ξ± Οƒ} [primcodable Ξ±] [primcodable Οƒ] {c : Ξ± β†’ code} (hc : primrec c) {z : Ξ± β†’ Οƒ} (hz : primrec z) {s : Ξ± β†’ Οƒ} (hs : primrec s) {l : Ξ± β†’ Οƒ} (hl : primrec l) {r : Ξ± β†’ Οƒ} (hr : primrec r) {pr : Ξ± β†’ code Γ— code Γ— Οƒ Γ— Οƒ β†’ Οƒ} (hpr : primrecβ‚‚ pr) {co : Ξ± β†’ code Γ— code Γ— Οƒ Γ— Οƒ β†’ Οƒ} (hco : primrecβ‚‚ co) {pc : Ξ± β†’ code Γ— code Γ— Οƒ Γ— Οƒ β†’ Οƒ} (hpc : primrecβ‚‚ pc) {rf : Ξ± β†’ code Γ— Οƒ β†’ Οƒ} (hrf : primrecβ‚‚ rf) : let PR (a) := Ξ» cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := Ξ» cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := Ξ» cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := Ξ» cf hf, rf a (cf, hf), F (a : Ξ±) (c : code) : Οƒ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in primrec (Ξ» a, F a (c a) : Ξ± β†’ Οƒ) := begin intros, let G₁ : (Ξ± Γ— list Οƒ) Γ— β„• Γ— β„• β†’ option Οƒ := Ξ» p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ Ξ» s, (IH.nth m.unpair.1).bind $ Ξ» s₁, (IH.nth m.unpair.2).map $ Ξ» sβ‚‚, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, sβ‚‚))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, sβ‚‚)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, sβ‚‚))), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have mβ‚‚ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have sβ‚‚ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((primrec.of_nat code).comp m).pair s)) (hpc.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp mβ‚‚).pair $ s₁.pair sβ‚‚))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp mβ‚‚).pair $ s₁.pair sβ‚‚)) (hpr.comp a (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp mβ‚‚).pair $ s₁.pair sβ‚‚))) }, let G : Ξ± β†’ list Οƒ β†’ option Οƒ := Ξ» a IH, IH.length.cases (some (z a)) $ Ξ» n, n.cases (some (s a)) $ Ξ» n, n.cases (some (l a)) $ Ξ» n, n.cases (some (r a)) $ Ξ» n, G₁ ((a, IH), n, n.div2.div2), have : primrecβ‚‚ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (Ξ» a n, F a (of_nat code n)) this.toβ‚‚ $ Ξ» a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (Ξ» a, by simp), simp, iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (Ξ» n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end theorem rec_prim {Ξ± Οƒ} [primcodable Ξ±] [primcodable Οƒ] {c : Ξ± β†’ code} (hc : primrec c) {z : Ξ± β†’ Οƒ} (hz : primrec z) {s : Ξ± β†’ Οƒ} (hs : primrec s) {l : Ξ± β†’ Οƒ} (hl : primrec l) {r : Ξ± β†’ Οƒ} (hr : primrec r) {pr : Ξ± β†’ code β†’ code β†’ Οƒ β†’ Οƒ β†’ Οƒ} (hpr : primrec (Ξ» a : Ξ± Γ— code Γ— code Γ— Οƒ Γ— Οƒ, pr a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {co : Ξ± β†’ code β†’ code β†’ Οƒ β†’ Οƒ β†’ Οƒ} (hco : primrec (Ξ» a : Ξ± Γ— code Γ— code Γ— Οƒ Γ— Οƒ, co a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {pc : Ξ± β†’ code β†’ code β†’ Οƒ β†’ Οƒ β†’ Οƒ} (hpc : primrec (Ξ» a : Ξ± Γ— code Γ— code Γ— Οƒ Γ— Οƒ, pc a.1 a.2.1 a.2.2.1 a.2.2.2.1 a.2.2.2.2)) {rf : Ξ± β†’ code β†’ Οƒ β†’ Οƒ} (hrf : primrec (Ξ» a : Ξ± Γ— code Γ— Οƒ, rf a.1 a.2.1 a.2.2)) : let F (a : Ξ±) (c : code) : Οƒ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (pr a) (co a) (pc a) (rf a) in primrec (Ξ» a, F a (c a)) := begin intros, let G₁ : (Ξ± Γ— list Οƒ) Γ— β„• Γ— β„• β†’ option Οƒ := Ξ» p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ Ξ» s, (IH.nth m.unpair.1).bind $ Ξ» s₁, (IH.nth m.unpair.2).map $ Ξ» sβ‚‚, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m) s) (pc a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ sβ‚‚)) (cond n.div2.bodd (co a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ sβ‚‚) (pr a (of_nat code m.unpair.1) (of_nat code m.unpair.2) s₁ sβ‚‚)), have : primrec G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ primrec.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ primrec.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (primrec.unpair.comp m), have mβ‚‚ := snd.comp (primrec.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have sβ‚‚ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp $ a.pair (((primrec.of_nat code).comp m).pair s)) (hpc.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp mβ‚‚).pair $ s₁.pair sβ‚‚))) (primrec.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp mβ‚‚).pair $ s₁.pair sβ‚‚)) (hpr.comp $ a.pair (((primrec.of_nat code).comp m₁).pair $ ((primrec.of_nat code).comp mβ‚‚).pair $ s₁.pair sβ‚‚))) }, let G : Ξ± β†’ list Οƒ β†’ option Οƒ := Ξ» a IH, IH.length.cases (some (z a)) $ Ξ» n, n.cases (some (s a)) $ Ξ» n, n.cases (some (l a)) $ Ξ» n, n.cases (some (r a)) $ Ξ» n, G₁ ((a, IH), n, n.div2.div2), have : primrecβ‚‚ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (Ξ» a n, F a (of_nat code n)) this.toβ‚‚ $ Ξ» a n, _).comp primrec.id $ encode_iff.2 hc).of_eq (Ξ» a, by simp), simp, iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (Ξ» n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end section open computable /- TODO(Mario): less copy-paste from previous proof -/ theorem rec_computable {Ξ± Οƒ} [primcodable Ξ±] [primcodable Οƒ] {c : Ξ± β†’ code} (hc : computable c) {z : Ξ± β†’ Οƒ} (hz : computable z) {s : Ξ± β†’ Οƒ} (hs : computable s) {l : Ξ± β†’ Οƒ} (hl : computable l) {r : Ξ± β†’ Οƒ} (hr : computable r) {pr : Ξ± β†’ code Γ— code Γ— Οƒ Γ— Οƒ β†’ Οƒ} (hpr : computableβ‚‚ pr) {co : Ξ± β†’ code Γ— code Γ— Οƒ Γ— Οƒ β†’ Οƒ} (hco : computableβ‚‚ co) {pc : Ξ± β†’ code Γ— code Γ— Οƒ Γ— Οƒ β†’ Οƒ} (hpc : computableβ‚‚ pc) {rf : Ξ± β†’ code Γ— Οƒ β†’ Οƒ} (hrf : computableβ‚‚ rf) : let PR (a) := Ξ» cf cg hf hg, pr a (cf, cg, hf, hg), CO (a) := Ξ» cf cg hf hg, co a (cf, cg, hf, hg), PC (a) := Ξ» cf cg hf hg, pc a (cf, cg, hf, hg), RF (a) := Ξ» cf hf, rf a (cf, hf), F (a : Ξ±) (c : code) : Οƒ := nat.partrec.code.rec_on c (z a) (s a) (l a) (r a) (PR a) (CO a) (PC a) (RF a) in computable (Ξ» a, F a (c a)) := begin intros, let G₁ : (Ξ± Γ— list Οƒ) Γ— β„• Γ— β„• β†’ option Οƒ := Ξ» p, let a := p.1.1, IH := p.1.2, n := p.2.1, m := p.2.2 in (IH.nth m).bind $ Ξ» s, (IH.nth m.unpair.1).bind $ Ξ» s₁, (IH.nth m.unpair.2).map $ Ξ» sβ‚‚, cond n.bodd (cond n.div2.bodd (rf a (of_nat code m, s)) (pc a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, sβ‚‚))) (cond n.div2.bodd (co a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, sβ‚‚)) (pr a (of_nat code m.unpair.1, of_nat code m.unpair.2, s₁, sβ‚‚))), have : computable G₁, { refine option_bind (list_nth.comp (snd.comp fst) (snd.comp snd)) _, refine option_bind ((list_nth.comp (snd.comp fst) (fst.comp $ computable.unpair.comp (snd.comp snd))).comp fst) _, refine option_map ((list_nth.comp (snd.comp fst) (snd.comp $ computable.unpair.comp (snd.comp snd))).comp $ fst.comp fst) _, have a := fst.comp (fst.comp $ fst.comp $ fst.comp fst), have n := fst.comp (snd.comp $ fst.comp $ fst.comp fst), have m := snd.comp (snd.comp $ fst.comp $ fst.comp fst), have m₁ := fst.comp (computable.unpair.comp m), have mβ‚‚ := snd.comp (computable.unpair.comp m), have s := snd.comp (fst.comp fst), have s₁ := snd.comp fst, have sβ‚‚ := snd, exact (nat_bodd.comp n).cond ((nat_bodd.comp $ nat_div2.comp n).cond (hrf.comp a (((computable.of_nat code).comp m).pair s)) (hpc.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp mβ‚‚).pair $ s₁.pair sβ‚‚))) (computable.cond (nat_bodd.comp $ nat_div2.comp n) (hco.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp mβ‚‚).pair $ s₁.pair sβ‚‚)) (hpr.comp a (((computable.of_nat code).comp m₁).pair $ ((computable.of_nat code).comp mβ‚‚).pair $ s₁.pair sβ‚‚))) }, let G : Ξ± β†’ list Οƒ β†’ option Οƒ := Ξ» a IH, IH.length.cases (some (z a)) $ Ξ» n, n.cases (some (s a)) $ Ξ» n, n.cases (some (l a)) $ Ξ» n, n.cases (some (r a)) $ Ξ» n, G₁ ((a, IH), n, n.div2.div2), have : computableβ‚‚ G := (nat_cases (list_length.comp snd) (option_some_iff.2 (hz.comp fst)) $ nat_cases snd (option_some_iff.2 (hs.comp (fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hl.comp (fst.comp $ fst.comp fst))) $ nat_cases snd (option_some_iff.2 (hr.comp (fst.comp $ fst.comp $ fst.comp fst))) (this.comp $ ((fst.pair snd).comp $ fst.comp $ fst.comp $ fst.comp $ fst).pair $ snd.pair $ nat_div2.comp $ nat_div2.comp snd)), refine ((nat_strong_rec (Ξ» a n, F a (of_nat code n)) this.toβ‚‚ $ Ξ» a n, _).comp computable.id $ encode_iff.2 hc).of_eq (Ξ» a, by simp), simp, iterate 4 {cases n with n, {simp [of_nat_code_eq, of_nat_code]; refl}}, simp [G], rw [list.length_map, list.length_range], let m := n.div2.div2, show G₁ ((a, (list.range (n+4)).map (Ξ» n, F a (of_nat code n))), n, m) = some (F a (of_nat code (n+4))), have hm : m < n + 4, by simp [nat.div2_val, m]; from lt_of_le_of_lt (le_trans (nat.div_le_self _ _) (nat.div_le_self _ _)) (nat.succ_le_succ (nat.le_add_right _ _)), have m1 : m.unpair.1 < n + 4, from lt_of_le_of_lt m.unpair_left_le hm, have m2 : m.unpair.2 < n + 4, from lt_of_le_of_lt m.unpair_right_le hm, simp [G₁], simp [list.nth_map, list.nth_range, hm, m1, m2], change of_nat code (n+4) with of_nat_code (n+4), simp [of_nat_code], cases n.bodd; cases n.div2.bodd; refl end end def eval : code β†’ β„• β†’. β„• | zero := pure 0 | succ := nat.succ | left := ↑(Ξ» n : β„•, n.unpair.1) | right := ↑(Ξ» n : β„•, n.unpair.2) | (pair cf cg) := Ξ» n, mkpair <$> eval cf n <*> eval cg n | (comp cf cg) := Ξ» n, eval cg n >>= eval cf | (prec cf cg) := nat.unpaired (Ξ» a n, n.elim (eval cf a) (Ξ» y IH, do i ← IH, eval cg (mkpair a (mkpair y i)))) | (rfind' cf) := nat.unpaired (Ξ» a m, (nat.rfind (Ξ» n, (Ξ» m, m = 0) <$> eval cf (mkpair a (n + m)))).map (+ m)) instance : has_mem (β„• β†’. β„•) code := ⟨λ f c, eval c = f⟩ @[simp] theorem eval_const : βˆ€ n m, eval (code.const n) m = part.some n | 0 m := rfl | (n+1) m := by simp! * @[simp] theorem eval_id (n) : eval code.id n = part.some n := by simp! [(<*>)] @[simp] theorem eval_curry (c n x) : eval (curry c n) x = eval c (mkpair n x) := by simp! [(<*>)] theorem const_prim : primrec code.const := (primrec.id.nat_iterate (primrec.const zero) (comp_prim.comp (primrec.const succ) primrec.snd).toβ‚‚).of_eq $ Ξ» n, by simp; induction n; simp [*, code.const, function.iterate_succ'] theorem curry_prim : primrecβ‚‚ curry := comp_prim.comp primrec.fst $ pair_prim.comp (const_prim.comp primrec.snd) (primrec.const code.id) theorem curry_inj {c₁ cβ‚‚ n₁ nβ‚‚} (h : curry c₁ n₁ = curry cβ‚‚ nβ‚‚) : c₁ = cβ‚‚ ∧ n₁ = nβ‚‚ := ⟨by injection h, by { injection h, injection h with h₁ hβ‚‚, injection hβ‚‚ with h₃ hβ‚„, exact const_inj h₃ }⟩ theorem smn : βˆƒ f : code β†’ β„• β†’ code, computableβ‚‚ f ∧ βˆ€ c n x, eval (f c n) x = eval c (mkpair n x) := ⟨curry, primrecβ‚‚.to_comp curry_prim, eval_curry⟩ theorem exists_code {f : β„• β†’. β„•} : nat.partrec f ↔ βˆƒ c : code, eval c = f := ⟨λ h, begin induction h, case nat.partrec.zero { exact ⟨zero, rfl⟩ }, case nat.partrec.succ { exact ⟨succ, rfl⟩ }, case nat.partrec.left { exact ⟨left, rfl⟩ }, case nat.partrec.right { exact ⟨right, rfl⟩ }, case nat.partrec.pair : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨pair cf cg, rfl⟩ }, case nat.partrec.comp : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨comp cf cg, rfl⟩ }, case nat.partrec.prec : f g pf pg hf hg { rcases hf with ⟨cf, rfl⟩, rcases hg with ⟨cg, rfl⟩, exact ⟨prec cf cg, rfl⟩ }, case nat.partrec.rfind : f pf hf { rcases hf with ⟨cf, rfl⟩, refine ⟨comp (rfind' cf) (pair code.id zero), _⟩, simp [eval, (<*>), pure, pfun.pure, part.map_id'] }, end, Ξ» h, begin rcases h with ⟨c, rfl⟩, induction c, case nat.partrec.code.zero { exact nat.partrec.zero }, case nat.partrec.code.succ { exact nat.partrec.succ }, case nat.partrec.code.left { exact nat.partrec.left }, case nat.partrec.code.right { exact nat.partrec.right }, case nat.partrec.code.pair : cf cg pf pg { exact pf.pair pg }, case nat.partrec.code.comp : cf cg pf pg { exact pf.comp pg }, case nat.partrec.code.prec : cf cg pf pg { exact pf.prec pg }, case nat.partrec.code.rfind' : cf pf { exact pf.rfind' }, end⟩ def evaln : βˆ€ k : β„•, code β†’ β„• β†’ option β„• | 0 _ := Ξ» m, none | (k+1) zero := Ξ» n, guard (n ≀ k) >> pure 0 | (k+1) succ := Ξ» n, guard (n ≀ k) >> pure (nat.succ n) | (k+1) left := Ξ» n, guard (n ≀ k) >> pure n.unpair.1 | (k+1) right := Ξ» n, guard (n ≀ k) >> pure n.unpair.2 | (k+1) (pair cf cg) := Ξ» n, guard (n ≀ k) >> mkpair <$> evaln (k+1) cf n <*> evaln (k+1) cg n | (k+1) (comp cf cg) := Ξ» n, guard (n ≀ k) >> do x ← evaln (k+1) cg n, evaln (k+1) cf x | (k+1) (prec cf cg) := Ξ» n, guard (n ≀ k) >> n.unpaired (Ξ» a n, n.cases (evaln (k+1) cf a) $ Ξ» y, do i ← evaln k (prec cf cg) (mkpair a y), evaln (k+1) cg (mkpair a (mkpair y i))) | (k+1) (rfind' cf) := Ξ» n, guard (n ≀ k) >> n.unpaired (Ξ» a m, do x ← evaln (k+1) cf (mkpair a m), if x = 0 then pure m else evaln k (rfind' cf) (mkpair a (m+1))) theorem evaln_bound : βˆ€ {k c n x}, x ∈ evaln k c n β†’ n < k | 0 c n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin suffices : βˆ€ {o : option β„•}, x ∈ guard (n ≀ k) >> o β†’ n < k + 1, { cases c; rw [evaln] at h; exact this h }, simpa [(>>)] using nat.lt_succ_of_le end theorem evaln_mono : βˆ€ {k₁ kβ‚‚ c n x}, k₁ ≀ kβ‚‚ β†’ x ∈ evaln k₁ c n β†’ x ∈ evaln kβ‚‚ c n | 0 kβ‚‚ c n x hl h := by simp [evaln] at h; cases h | (k+1) (kβ‚‚+1) c n x hl h := begin have hl' := nat.le_of_succ_le_succ hl, have : βˆ€ {k kβ‚‚ n x : β„•} {o₁ oβ‚‚ : option β„•}, k ≀ kβ‚‚ β†’ (x ∈ o₁ β†’ x ∈ oβ‚‚) β†’ x ∈ guard (n ≀ k) >> o₁ β†’ x ∈ guard (n ≀ kβ‚‚) >> oβ‚‚, { simp [(>>)], introv h h₁ hβ‚‚ h₃, exact ⟨le_trans hβ‚‚ h, h₁ hβ‚ƒβŸ© }, simp at h ⊒, induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; rw [evaln] at h ⊒; refine this hl' (Ξ» h, _) h, iterate 4 {exact h}, { -- pair cf cg simp [(<*>)] at h ⊒, exact h.imp (Ξ» a, and.imp (hf _ _) $ Exists.imp $ Ξ» b, and.imp_left (hg _ _)) }, { -- comp cf cg simp at h ⊒, exact h.imp (Ξ» a, and.imp (hg _ _) (hf _ _)) }, { -- prec cf cg revert h, simp, induction n.unpair.2; simp, { apply hf }, { exact Ξ» y h₁ hβ‚‚, ⟨y, evaln_mono hl' h₁, hg _ _ hβ‚‚βŸ© } }, { -- rfind' cf simp at h ⊒, refine h.imp (Ξ» x, and.imp (hf _ _) _), by_cases x0 : x = 0; simp [x0], exact evaln_mono hl' } end theorem evaln_sound : βˆ€ {k c n x}, x ∈ evaln k c n β†’ x ∈ eval c n | 0 _ n x h := by simp [evaln] at h; cases h | (k+1) c n x h := begin induction c with cf cg hf hg cf cg hf hg cf cg hf hg cf hf generalizing x n; simp [eval, evaln, (>>), (<*>)] at h ⊒; cases h with _ h, iterate 4 {simpa [pure, pfun.pure, eq_comm] using h}, { -- pair cf cg rcases h with ⟨y, ef, z, eg, rfl⟩, exact ⟨_, hf _ _ ef, _, hg _ _ eg, rfl⟩ }, { --comp hf hg rcases h with ⟨y, eg, ef⟩, exact ⟨_, hg _ _ eg, hf _ _ ef⟩ }, { -- prec cf cg revert h, induction n.unpair.2 with m IH generalizing x; simp, { apply hf }, { refine Ξ» y h₁ hβ‚‚, ⟨y, IH _ _, _⟩, { have := evaln_mono k.le_succ h₁, simp [evaln, (>>)] at this, exact this.2 }, { exact hg _ _ hβ‚‚ } } }, { -- rfind' cf rcases h with ⟨m, h₁, hβ‚‚βŸ©, by_cases m0 : m = 0; simp [m0] at hβ‚‚, { exact ⟨0, ⟨by simpa [m0] using hf _ _ h₁, Ξ» m, (nat.not_lt_zero _).elim⟩, by injection hβ‚‚ with hβ‚‚; simp [hβ‚‚]⟩ }, { have := evaln_sound hβ‚‚, simp [eval] at this, rcases this with ⟨y, ⟨hy₁, hyβ‚‚βŸ©, rfl⟩, refine ⟨ y+1, ⟨by simpa [add_comm, add_left_comm] using hy₁, Ξ» i im, _⟩, by simp [add_comm, add_left_comm] ⟩, cases i with i, { exact ⟨m, by simpa using hf _ _ h₁, m0⟩ }, { rcases hyβ‚‚ (nat.lt_of_succ_lt_succ im) with ⟨z, hz, z0⟩, exact ⟨z, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hz, z0⟩ } } } end theorem evaln_complete {c n x} : x ∈ eval c n ↔ βˆƒ k, x ∈ evaln k c n := ⟨λ h, begin suffices : βˆƒ k, x ∈ evaln (k+1) c n, { exact let ⟨k, h⟩ := this in ⟨k+1, h⟩ }, induction c generalizing n x; simp [eval, evaln, pure, pfun.pure, (<*>), (>>)] at h ⊒, iterate 4 { exact ⟨⟨_, le_rfl⟩, h.symm⟩ }, case nat.partrec.code.pair : cf cg hf hg { rcases h with ⟨x, hx, y, hy, rfl⟩, rcases hf hx with ⟨k₁, hkβ‚βŸ©, rcases hg hy with ⟨kβ‚‚, hkβ‚‚βŸ©, refine ⟨max k₁ kβ‚‚, _⟩, refine ⟨le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hkβ‚‚, rfl⟩ }, case nat.partrec.code.comp : cf cg hf hg { rcases h with ⟨y, hy, hx⟩, rcases hg hy with ⟨k₁, hkβ‚βŸ©, rcases hf hx with ⟨kβ‚‚, hkβ‚‚βŸ©, refine ⟨max k₁ kβ‚‚, _⟩, exact ⟨le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hk₁, _, evaln_mono (nat.succ_le_succ $ le_max_left _ _) hk₁, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hkβ‚‚βŸ© }, case nat.partrec.code.prec : cf cg hf hg { revert h, generalize : n.unpair.1 = n₁, generalize : n.unpair.2 = nβ‚‚, induction nβ‚‚ with m IH generalizing x n; simp, { intro, rcases hf h with ⟨k, hk⟩, exact ⟨_, le_max_left _ _, evaln_mono (nat.succ_le_succ $ le_max_right _ _) hk⟩ }, { intros y hy hx, rcases IH hy with ⟨k₁, nk₁, hkβ‚βŸ©, rcases hg hx with ⟨kβ‚‚, hkβ‚‚βŸ©, refine ⟨(max k₁ kβ‚‚).succ, nat.le_succ_of_le $ le_max_of_le_left $ le_trans (le_max_left _ (mkpair n₁ m)) nk₁, y, evaln_mono (nat.succ_le_succ $ le_max_left _ _) _, evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_right _ _) hkβ‚‚βŸ©, simp [evaln, (>>)], exact ⟨le_trans (le_max_right _ _) nk₁, hkβ‚βŸ© } }, case nat.partrec.code.rfind' : cf hf { rcases h with ⟨y, ⟨hy₁, hyβ‚‚βŸ©, rfl⟩, suffices : βˆƒ k, y + n.unpair.2 ∈ evaln (k+1) (rfind' cf) (mkpair n.unpair.1 n.unpair.2), {simpa [evaln, (>>)]}, revert hy₁ hyβ‚‚, generalize : n.unpair.2 = m, intros, induction y with y IH generalizing m; simp [evaln, (>>)], { simp at hy₁, rcases hf hy₁ with ⟨k, hk⟩, exact ⟨_, nat.le_of_lt_succ $ evaln_bound hk, _, hk, by simp; refl⟩ }, { rcases hyβ‚‚ (nat.succ_pos _) with ⟨a, ha, a0⟩, rcases hf ha with ⟨k₁, hkβ‚βŸ©, rcases IH m.succ (by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hy₁) (Ξ» i hi, by simpa [nat.succ_eq_add_one, add_comm, add_left_comm] using hyβ‚‚ (nat.succ_lt_succ hi)) with ⟨kβ‚‚, hkβ‚‚βŸ©, use (max k₁ kβ‚‚).succ, rw [zero_add] at hk₁, use (nat.le_succ_of_le $ le_max_of_le_left $ nat.le_of_lt_succ $ evaln_bound hk₁), use a, use evaln_mono (nat.succ_le_succ $ nat.le_succ_of_le $ le_max_left _ _) hk₁, simpa [nat.succ_eq_add_one, a0, -max_eq_left, -max_eq_right, add_comm, add_left_comm] using evaln_mono (nat.succ_le_succ $ le_max_right _ _) hkβ‚‚ } } end, Ξ» ⟨k, h⟩, evaln_sound h⟩ section open primrec private def lup (L : list (list (option β„•))) (p : β„• Γ— code) (n : β„•) := do l ← L.nth (encode p), o ← l.nth n, o private lemma hlup : primrec (Ξ» p:_Γ—(_Γ—_)Γ—_, lup p.1 p.2.1 p.2.2) := option_bind (list_nth.comp fst (primrec.encode.comp $ fst.comp snd)) (option_bind (list_nth.comp snd $ snd.comp $ snd.comp fst) snd) private def G (L : list (list (option β„•))) : option (list (option β„•)) := option.some $ let a := of_nat (β„• Γ— code) L.length, k := a.1, c := a.2 in (list.range k).map (Ξ» n, k.cases none $ Ξ» k', nat.partrec.code.rec_on c (some 0) -- zero (some (nat.succ n)) (some n.unpair.1) (some n.unpair.2) (Ξ» cf cg _ _, do x ← lup L (k, cf) n, y ← lup L (k, cg) n, some (mkpair x y)) (Ξ» cf cg _ _, do x ← lup L (k, cg) n, lup L (k, cf) x) (Ξ» cf cg _ _, let z := n.unpair.1 in n.unpair.2.cases (lup L (k, cf) z) (Ξ» y, do i ← lup L (k', c) (mkpair z y), lup L (k, cg) (mkpair z (mkpair y i)))) (Ξ» cf _, let z := n.unpair.1, m := n.unpair.2 in do x ← lup L (k, cf) (mkpair z m), x.cases (some m) (Ξ» _, lup L (k', c) (mkpair z (m+1))))) private lemma hG : primrec G := begin have a := (primrec.of_nat (β„• Γ— code)).comp list_length, have k := fst.comp a, refine option_some.comp (list_map (list_range.comp k) (_ : primrec _)), replace k := k.comp fst, have n := snd, refine nat_cases k (const none) (_ : primrec _), have k := k.comp fst, have n := n.comp fst, have k' := snd, have c := snd.comp (a.comp $ fst.comp fst), apply rec_prim c (const (some 0)) (option_some.comp (primrec.succ.comp n)) (option_some.comp (fst.comp $ primrec.unpair.comp n)) (option_some.comp (snd.comp $ primrec.unpair.comp n)), { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cf).pair n) (option_map ((hlup.comp $ L.pair $ (k.pair cg).pair n).comp fst) (primrecβ‚‚.mkpair.comp (snd.comp fst) snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, exact option_bind (hlup.comp $ L.pair $ (k.pair cg).pair n) (hlup.comp ((L.comp fst).pair $ ((k.pair cf).comp fst).pair snd)) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have cg := (fst.comp snd).comp snd, have z := fst.comp (primrec.unpair.comp n), refine nat_cases (snd.comp (primrec.unpair.comp n)) (hlup.comp $ L.pair $ (k.pair cf).pair z) (_ : primrec _), have L := L.comp fst, have z := z.comp fst, have y := snd, refine option_bind (hlup.comp $ L.pair $ (((k'.pair c).comp fst).comp fst).pair (primrecβ‚‚.mkpair.comp z y)) (_ : primrec _), have z := z.comp fst, have y := y.comp fst, have i := snd, exact hlup.comp ((L.comp fst).pair $ ((k.pair cg).comp $ fst.comp fst).pair $ primrecβ‚‚.mkpair.comp z $ primrecβ‚‚.mkpair.comp y i) }, { have L := (fst.comp fst).comp fst, have k := k.comp fst, have n := n.comp fst, have cf := fst.comp snd, have z := fst.comp (primrec.unpair.comp n), have m := snd.comp (primrec.unpair.comp n), refine option_bind (hlup.comp $ L.pair $ (k.pair cf).pair (primrecβ‚‚.mkpair.comp z m)) (_ : primrec _), have m := m.comp fst, exact nat_cases snd (option_some.comp m) ((hlup.comp ((L.comp fst).pair $ ((k'.pair c).comp $ fst.comp fst).pair (primrecβ‚‚.mkpair.comp (z.comp fst) (primrec.succ.comp m)))).comp fst) } end private lemma evaln_map (k c n) : (((list.range k).nth n).map (evaln k c)).bind (Ξ» b, b) = evaln k c n := begin by_cases kn : n < k, { simp [list.nth_range kn] }, { rw list.nth_len_le, { cases e : evaln k c n, {refl}, exact kn.elim (evaln_bound e) }, simpa using kn } end theorem evaln_prim : primrec (Ξ» (a : (β„• Γ— code) Γ— β„•), evaln a.1.1 a.1.2 a.2) := have primrecβ‚‚ (Ξ» (_:unit) (n : β„•), let a := of_nat (β„• Γ— code) n in (list.range a.1).map (evaln a.1 a.2)), from primrec.nat_strong_rec _ (hG.comp snd).toβ‚‚ $ Ξ» _ p, begin simp [G], rw (_ : (of_nat (β„• Γ— code) _).snd = of_nat code p.unpair.2), swap, {simp}, apply list.map_congr (Ξ» n, _), rw (by simp : list.range p = list.range (mkpair p.unpair.1 (encode (of_nat code p.unpair.2)))), generalize : p.unpair.1 = k, generalize : of_nat code p.unpair.2 = c, intro nk, cases k with k', {simp [evaln]}, let k := k'+1, change k'.succ with k, simp [nat.lt_succ_iff] at nk, have hg : βˆ€ {k' c' n}, mkpair k' (encode c') < mkpair k (encode c) β†’ lup ((list.range (mkpair k (encode c))).map (Ξ» n, (list.range n.unpair.1).map (evaln n.unpair.1 (of_nat code n.unpair.2)))) (k', c') n = evaln k' c' n, { intros k₁ c₁ n₁ hl, simp [lup, list.nth_range hl, evaln_map, (>>=)] }, cases c with cf cg cf cg cf cg cf; simp [evaln, nk, (>>), (>>=), (<$>), (<*>), pure], { cases encode_lt_pair cf cg with lf lg, rw [hg (nat.mkpair_lt_mkpair_right _ lf), hg (nat.mkpair_lt_mkpair_right _ lg)], cases evaln k cf n, {refl}, cases evaln k cg n; refl }, { cases encode_lt_comp cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lg), cases evaln k cg n, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lf)] }, { cases encode_lt_prec cf cg with lf lg, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases n.unpair.2, {refl}, simp, rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self), cases evaln k' _ _, {refl}, simp [hg (nat.mkpair_lt_mkpair_right _ lg)] }, { have lf := encode_lt_rfind' cf, rw hg (nat.mkpair_lt_mkpair_right _ lf), cases evaln k cf n with x, {refl}, simp, cases x; simp [nat.succ_ne_zero], rw hg (nat.mkpair_lt_mkpair_left _ k'.lt_succ_self) } end, (option_bind (list_nth.comp (this.comp (const ()) (encode_iff.2 fst)) snd) snd.toβ‚‚).of_eq $ Ξ» ⟨⟨k, c⟩, n⟩, by simp [evaln_map] end section open partrec computable theorem eval_eq_rfind_opt (c n) : eval c n = nat.rfind_opt (Ξ» k, evaln k c n) := part.ext $ Ξ» x, begin refine evaln_complete.trans (nat.rfind_opt_mono _).symm, intros a m n hl, apply evaln_mono hl, end theorem eval_part : partrecβ‚‚ eval := (rfind_opt (evaln_prim.to_comp.comp ((snd.pair (fst.comp fst)).pair (snd.comp fst))).toβ‚‚).of_eq $ Ξ» a, by simp [eval_eq_rfind_opt] theorem fixed_point {f : code β†’ code} (hf : computable f) : βˆƒ c : code, eval (f c) = eval c := let g (x y : β„•) : part β„• := eval (of_nat code x) x >>= Ξ» b, eval (of_nat code b) y in have partrecβ‚‚ g := (eval_part.comp ((computable.of_nat _).comp fst) fst).bind (eval_part.comp ((computable.of_nat _).comp snd) (snd.comp fst)).toβ‚‚, let ⟨cg, eg⟩ := exists_code.1 this in have eg' : βˆ€ a n, eval cg (mkpair a n) = part.map encode (g a n) := by simp [eg], let F (x : β„•) : code := f (curry cg x) in have computable F := hf.comp (curry_prim.comp (primrec.const cg) primrec.id).to_comp, let ⟨cF, eF⟩ := exists_code.1 this in have eF' : eval cF (encode cF) = part.some (encode (F (encode cF))), by simp [eF], ⟨curry cg (encode cF), funext (Ξ» n, show eval (f (curry cg (encode cF))) n = eval (curry cg (encode cF)) n, by simp [eg', eF', part.map_id', g])⟩ theorem fixed_pointβ‚‚ {f : code β†’ β„• β†’. β„•} (hf : partrecβ‚‚ f) : βˆƒ c : code, eval c = f c := let ⟨cf, ef⟩ := exists_code.1 hf in (fixed_point (curry_prim.comp (primrec.const cf) primrec.encode).to_comp).imp $ Ξ» c e, funext $ Ξ» n, by simp [e.symm, ef, part.map_id'] end end nat.partrec.code
6285cf4e87f67a724dd95ca0a5a7b49f2cf388f8
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/evalconst.lean
f054de2a8f9fb012b20cdb0d372682703e26aaed
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
340
lean
import Init.Lean open Lean def x := 10 unsafe def tst : MetaIO Unit := do env ← MetaIO.getEnv; IO.println $ env.evalConst Nat `x; pure () #eval tst def f (x : Nat) := x + 1 unsafe def tst2 : MetaIO Unit := do env ← MetaIO.getEnv; f ← liftM $ IO.ofExcept $ env.evalConst (Nat β†’ Nat) `f; IO.println $ (f 10); pure () #eval tst2
c10127039924eb4f0400fb6b093dc9c94690c41f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/968.lean
1710d734856ff5b2251d59aa9b4aa32cc10ade5a
[ "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
224
lean
variables (A : Type) [inhabited A] definition f (a : A) : A := a check @f nat nat.is_inhabited structure foo := (a : A) check @foo nat nat.is_inhabited inductive bla := | mk : A β†’ bla check @bla nat nat.is_inhabited
898a541cae70b6e0d2609a26cde597062a21d46a
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/concrete_category/bundled_hom.lean
4a012f2a5c1f2294706ef1698d1dc795ce7d8162
[ "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
5,778
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Yury Kudryashov -/ import category_theory.concrete_category.basic import category_theory.concrete_category.bundled import category_theory.fully_faithful /-! # Category instances for algebraic structures that use bundled homs. Many algebraic structures in Lean initially used unbundled homs (e.g. a bare function between types, along with an `is_monoid_hom` typeclass), but the general trend is towards using bundled homs. This file provides a basic infrastructure to define concrete categories using bundled homs, and define forgetful functors between them. -/ universes u namespace category_theory variables {c : Type u β†’ Type u} (hom : Ξ  ⦃α Ξ² : Type u⦄ (IΞ± : c Ξ±) (IΞ² : c Ξ²), Type u) /-- Class for bundled homs. Note that the arguments order follows that of lemmas for `monoid_hom`. This way we can use `⟨@monoid_hom.to_fun, @monoid_hom.id ...⟩` in an instance. -/ structure bundled_hom := (to_fun : Ξ  {Ξ± Ξ² : Type u} (IΞ± : c Ξ±) (IΞ² : c Ξ²), hom IΞ± IΞ² β†’ Ξ± β†’ Ξ²) (id : Ξ  {Ξ± : Type u} (I : c Ξ±), hom I I) (comp : Ξ  {Ξ± Ξ² Ξ³ : Type u} (IΞ± : c Ξ±) (IΞ² : c Ξ²) (IΞ³ : c Ξ³), hom IΞ² IΞ³ β†’ hom IΞ± IΞ² β†’ hom IΞ± IΞ³) (hom_ext : βˆ€ {Ξ± Ξ² : Type u} (IΞ± : c Ξ±) (IΞ² : c Ξ²), function.injective (to_fun IΞ± IΞ²) . obviously) (id_to_fun : βˆ€ {Ξ± : Type u} (I : c Ξ±), to_fun I I (id I) = _root_.id . obviously) (comp_to_fun : βˆ€ {Ξ± Ξ² Ξ³ : Type u} (IΞ± : c Ξ±) (IΞ² : c Ξ²) (IΞ³ : c Ξ³) (f : hom IΞ± IΞ²) (g : hom IΞ² IΞ³), to_fun IΞ± IΞ³ (comp IΞ± IΞ² IΞ³ g f) = (to_fun IΞ² IΞ³ g) ∘ (to_fun IΞ± IΞ² f) . obviously) attribute [class] bundled_hom attribute [simp] bundled_hom.id_to_fun bundled_hom.comp_to_fun namespace bundled_hom variable [π’ž : bundled_hom hom] include π’ž /-- Every `@bundled_hom c _` defines a category with objects in `bundled c`. This instance generates the type-class problem `bundled_hom ?m` (which is why this is marked as `[nolint]`). Currently that is not a problem, as there are almost no instances of `bundled_hom`. -/ @[nolint dangerous_instance] instance category : category (bundled c) := by refine { hom := Ξ» X Y, @hom X Y X.str Y.str, id := Ξ» X, @bundled_hom.id c hom π’ž X X.str, comp := Ξ» X Y Z f g, @bundled_hom.comp c hom π’ž X Y Z X.str Y.str Z.str g f, comp_id' := _, id_comp' := _, assoc' := _}; intros; apply π’ž.hom_ext; simp only [π’ž.id_to_fun, π’ž.comp_to_fun, function.left_id, function.right_id] /-- A category given by `bundled_hom` is a concrete category. This instance generates the type-class problem `bundled_hom ?m` (which is why this is marked as `[nolint]`). Currently that is not a problem, as there are almost no instances of `bundled_hom`. -/ @[nolint dangerous_instance] instance : concrete_category.{u} (bundled c) := { forget := { obj := Ξ» X, X, map := Ξ» X Y f, π’ž.to_fun X.str Y.str f, map_id' := Ξ» X, π’ž.id_to_fun X.str, map_comp' := by intros; erw π’ž.comp_to_fun; refl }, forget_faithful := { map_injective' := by intros; apply π’ž.hom_ext } } variables {hom} local attribute [instance] concrete_category.has_coe_to_fun /-- A version of `has_forgetβ‚‚.mk'` for categories defined using `@bundled_hom`. -/ def mk_has_forgetβ‚‚ {d : Type u β†’ Type u} {hom_d : Ξ  ⦃α Ξ² : Type u⦄ (IΞ± : d Ξ±) (IΞ² : d Ξ²), Type u} [bundled_hom hom_d] (obj : Ξ  ⦃α⦄, c Ξ± β†’ d Ξ±) (map : Ξ  {X Y : bundled c}, (X ⟢ Y) β†’ ((bundled.map obj X) ⟢ (bundled.map obj Y))) (h_map : βˆ€ {X Y : bundled c} (f : X ⟢ Y), (map f : X β†’ Y) = f) : has_forgetβ‚‚ (bundled c) (bundled d) := has_forgetβ‚‚.mk' (bundled.map @obj) (Ξ» _, rfl) @map (by intros; apply heq_of_eq; apply h_map) variables {d : Type u β†’ Type u} variables (hom) section omit π’ž /-- The `hom` corresponding to first forgetting along `F`, then taking the `hom` associated to `c`. For typical usage, see the construction of `CommMon` from `Mon`. -/ @[reducible] def map_hom (F : Ξ  {Ξ±}, d Ξ± β†’ c Ξ±) : Ξ  ⦃α Ξ² : Type u⦄ (IΞ± : d Ξ±) (IΞ² : d Ξ²), Type u := Ξ» Ξ± Ξ² iΞ± iΞ², hom (F iΞ±) (F iΞ²) end /-- Construct the `bundled_hom` induced by a map between type classes. This is useful for building categories such as `CommMon` from `Mon`. -/ def map (F : Ξ  {Ξ±}, d Ξ± β†’ c Ξ±) : bundled_hom (map_hom hom @F) := { to_fun := Ξ» Ξ± Ξ² iΞ± iΞ² f, π’ž.to_fun (F iΞ±) (F iΞ²) f, id := Ξ» Ξ± iΞ±, π’ž.id (F iΞ±), comp := Ξ» Ξ± Ξ² Ξ³ iΞ± iΞ² iΞ³ f g, π’ž.comp (F iΞ±) (F iΞ²) (F iΞ³) f g, hom_ext := Ξ» Ξ± Ξ² iΞ± iΞ² f g h, π’ž.hom_ext (F iΞ±) (F iΞ²) h } section omit π’ž /-- We use the empty `parent_projection` class to label functions like `comm_monoid.to_monoid`, which we would like to use to automatically construct `bundled_hom` instances from. Once we've set up `Mon` as the category of bundled monoids, this allows us to set up `CommMon` by defining an instance ```instance : parent_projection (comm_monoid.to_monoid) := ⟨⟩``` -/ class parent_projection (F : Ξ  {Ξ±}, d Ξ± β†’ c Ξ±) end @[nolint unused_arguments] -- The `parent_projection` typeclass is just a marker, so won't be used. instance bundled_hom_of_parent_projection (F : Ξ  {Ξ±}, d Ξ± β†’ c Ξ±) [parent_projection @F] : bundled_hom (map_hom hom @F) := map hom @F instance forgetβ‚‚ (F : Ξ  {Ξ±}, d Ξ± β†’ c Ξ±) [parent_projection @F] : has_forgetβ‚‚ (bundled d) (bundled c) := { forgetβ‚‚ := { obj := Ξ» X, ⟨X, F X.2⟩, map := Ξ» X Y f, f } } instance forgetβ‚‚_full (F : Ξ  {Ξ±}, d Ξ± β†’ c Ξ±) [parent_projection @F] : full (forgetβ‚‚ (bundled d) (bundled c)) := { preimage := Ξ» X Y f, f } end bundled_hom end category_theory
dccdbbb14ff4afaecc3e34cb7cf4c9cdff1224b9
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/polynomial/basic.lean
3841580de0b4824bdca2b6eed75dfc22ac624968
[ "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
32,299
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 algebra.monoid_algebra.basic /-! # Theory of univariate polynomials This file defines `polynomial R`, the type of univariate polynomials over the semiring `R`, builds a semiring structure on it, and gives basic definitions that are expanded in other files in this directory. ## Main definitions * `monomial n a` is the polynomial `a X^n`. Note that `monomial n` is defined as an `R`-linear map. * `C a` is the constant polynomial `a`. Note that `C` is defined as a ring homomorphism. * `X` is the polynomial `X`, i.e., `monomial 1 1`. * `p.sum f` is `βˆ‘ n in p.support, f n (p.coeff n)`, i.e., one sums the values of functions applied to coefficients of the polynomial `p`. * `p.erase n` is the polynomial `p` in which one removes the `c X^n` term. There are often two natural variants of lemmas involving sums, depending on whether one acts on the polynomials, or on the function. The naming convention is that one adds `index` when acting on the polynomials. For instance, * `sum_add_index` states that `(p + q).sum f = p.sum f + q.sum f`; * `sum_add` states that `p.sum (Ξ» n x, f n x + g n x) = p.sum f + p.sum g`. * Notation to refer to `polynomial R`, as `R[X]` or `R[t]`. ## Implementation Polynomials are defined using `add_monoid_algebra R β„•`, where `R` is a semiring. The variable `X` commutes with every polynomial `p`: lemma `X_mul` proves the identity `X * p = `p * X`. The relationship to `add_monoid_algebra R β„•` is through a structure to make polynomials irreducible from the point of view of the kernel. Most operations are irreducible since Lean can not compute anyway with `add_monoid_algebra`. There are two exceptions that we make semireducible: * The zero polynomial, so that its coefficients are definitionally equal to `0`. * The scalar action, to permit typeclass search to unfold it to resolve potential instance diamonds. The raw implementation of the equivalence between `polynomial R` and `add_monoid_algebra R β„•` is done through `of_finsupp` and `to_finsupp` (or, equivalently, `rcases p` when `p` is a polynomial gives an element `q` of `add_monoid_algebra R β„•`, and conversely `⟨q⟩` gives back `p`). The equivalence is also registered as a ring equiv in `polynomial.to_finsupp_iso`. These should in general not be used once the basic API for polynomials is constructed. -/ noncomputable theory /-- `polynomial R` is the type of univariate polynomials over `R`. Polynomials should be seen as (semi-)rings with the additional constructor `X`. The embedding from `R` is called `C`. -/ structure polynomial (R : Type*) [semiring R] := of_finsupp :: (to_finsupp : add_monoid_algebra R β„•) localized "notation R`[X]`:9000 := polynomial R" in polynomial open finsupp add_monoid_algebra open_locale big_operators polynomial namespace polynomial universes u variables {R : Type u} {a b : R} {m n : β„•} section semiring variables [semiring R] {p q : R[X]} lemma forall_iff_forall_finsupp (P : R[X] β†’ Prop) : (βˆ€ p, P p) ↔ βˆ€ (q : add_monoid_algebra R β„•), P ⟨q⟩ := ⟨λ h q, h ⟨q⟩, Ξ» h ⟨p⟩, h p⟩ lemma exists_iff_exists_finsupp (P : R[X] β†’ Prop) : (βˆƒ p, P p) ↔ βˆƒ (q : add_monoid_algebra R β„•), P ⟨q⟩ := ⟨λ ⟨⟨p⟩, hp⟩, ⟨p, hp⟩, Ξ» ⟨q, hq⟩, ⟨⟨q⟩, hq⟩ ⟩ /-! ### Conversions to and from `add_monoid_algebra` Since `polynomial R` is not defeq to `add_monoid_algebra R β„•`, but instead is a structure wrapping it, we have to copy across all the arithmetic operators manually, along with the lemmas about how they unfold around `polynomial.of_finsupp` and `polynomial.to_finsupp`. -/ section add_monoid_algebra /-- The function version of `monomial`. Use `monomial` instead of this one. -/ @[irreducible] def monomial_fun (n : β„•) (a : R) : R[X] := ⟨finsupp.single n a⟩ @[irreducible] private def add : R[X] β†’ R[X] β†’ R[X] | ⟨a⟩ ⟨b⟩ := ⟨a + b⟩ @[irreducible] private def neg {R : Type u} [ring R] : R[X] β†’ R[X] | ⟨a⟩ := ⟨-a⟩ @[irreducible] private def mul : R[X] β†’ R[X] β†’ R[X] | ⟨a⟩ ⟨b⟩ := ⟨a * b⟩ instance : has_zero R[X] := ⟨⟨0⟩⟩ instance : has_one R[X] := ⟨monomial_fun 0 (1 : R)⟩ instance : has_add R[X] := ⟨add⟩ instance {R : Type u} [ring R] : has_neg R[X] := ⟨neg⟩ instance {R : Type u} [ring R] : has_sub R[X] := ⟨λ a b, a + -b⟩ instance : has_mul R[X] := ⟨mul⟩ instance {S : Type*} [monoid S] [distrib_mul_action S R] : has_smul S R[X] := ⟨λ r p, ⟨r β€’ p.to_finsupp⟩⟩ @[priority 1] -- to avoid a bug in the `ring` tactic instance has_pow : has_pow R[X] β„• := { pow := Ξ» p n, npow_rec n p } @[simp] lemma of_finsupp_zero : (⟨0⟩ : R[X]) = 0 := rfl @[simp] lemma of_finsupp_one : (⟨1⟩ : R[X]) = 1 := begin change (⟨1⟩ : R[X]) = monomial_fun 0 (1 : R), rw [monomial_fun], refl end @[simp] lemma of_finsupp_add {a b} : (⟨a + b⟩ : R[X]) = ⟨a⟩ + ⟨b⟩ := show _ = add _ _, by rw add @[simp] lemma of_finsupp_neg {R : Type u} [ring R] {a} : (⟨-a⟩ : R[X]) = -⟨a⟩ := show _ = neg _, by rw neg @[simp] lemma of_finsupp_sub {R : Type u} [ring R] {a b} : (⟨a - b⟩ : R[X]) = ⟨a⟩ - ⟨b⟩ := by { rw [sub_eq_add_neg, of_finsupp_add, of_finsupp_neg], refl } @[simp] lemma of_finsupp_mul (a b) : (⟨a * b⟩ : R[X]) = ⟨a⟩ * ⟨b⟩ := show _ = mul _ _, by rw mul @[simp] lemma of_finsupp_smul {S : Type*} [monoid S] [distrib_mul_action S R] (a : S) (b) : (⟨a β€’ b⟩ : R[X]) = (a β€’ ⟨b⟩ : R[X]) := rfl @[simp] lemma of_finsupp_pow (a) (n : β„•) : (⟨a ^ n⟩ : R[X]) = ⟨a⟩ ^ n := begin change _ = npow_rec n _, induction n, { simp [npow_rec], } , { simp [npow_rec, n_ih, pow_succ] } end @[simp] lemma to_finsupp_zero : (0 : R[X]).to_finsupp = 0 := rfl @[simp] lemma to_finsupp_one : (1 : R[X]).to_finsupp = 1 := begin change to_finsupp (monomial_fun _ _) = _, rw monomial_fun, refl, end @[simp] lemma to_finsupp_add (a b : R[X]) : (a + b).to_finsupp = a.to_finsupp + b.to_finsupp := by { cases a, cases b, rw ←of_finsupp_add } @[simp] lemma to_finsupp_neg {R : Type u} [ring R] (a : R[X]) : (-a).to_finsupp = -a.to_finsupp := by { cases a, rw ←of_finsupp_neg } @[simp] lemma to_finsupp_sub {R : Type u} [ring R] (a b : R[X]) : (a - b).to_finsupp = a.to_finsupp - b.to_finsupp := by { rw [sub_eq_add_neg, ←to_finsupp_neg, ←to_finsupp_add], refl } @[simp] lemma to_finsupp_mul (a b : R[X]) : (a * b).to_finsupp = a.to_finsupp * b.to_finsupp := by { cases a, cases b, rw ←of_finsupp_mul } @[simp] lemma to_finsupp_smul {S : Type*} [monoid S] [distrib_mul_action S R] (a : S) (b : R[X]) : (a β€’ b).to_finsupp = a β€’ b.to_finsupp := rfl @[simp] lemma to_finsupp_pow (a : R[X]) (n : β„•) : (a ^ n).to_finsupp = a.to_finsupp ^ n := by { cases a, rw ←of_finsupp_pow } lemma _root_.is_smul_regular.polynomial {S : Type*} [monoid S] [distrib_mul_action S R] {a : S} (ha : is_smul_regular R a) : is_smul_regular R[X] a | ⟨x⟩ ⟨y⟩ h := congr_arg _ $ ha.finsupp (polynomial.of_finsupp.inj h) lemma to_finsupp_injective : function.injective (to_finsupp : R[X] β†’ add_monoid_algebra _ _) := Ξ» ⟨x⟩ ⟨y⟩, congr_arg _ @[simp] lemma to_finsupp_inj {a b : R[X]} : a.to_finsupp = b.to_finsupp ↔ a = b := to_finsupp_injective.eq_iff @[simp] lemma to_finsupp_eq_zero {a : R[X]} : a.to_finsupp = 0 ↔ a = 0 := by rw [←to_finsupp_zero, to_finsupp_inj] @[simp] lemma to_finsupp_eq_one {a : R[X]} : a.to_finsupp = 1 ↔ a = 1 := by rw [←to_finsupp_one, to_finsupp_inj] /-- A more convenient spelling of `polynomial.of_finsupp.inj_eq` in terms of `iff`. -/ lemma of_finsupp_inj {a b} : (⟨a⟩ : R[X]) = ⟨b⟩ ↔ a = b := iff_of_eq of_finsupp.inj_eq @[simp] lemma of_finsupp_eq_zero {a} : (⟨a⟩ : R[X]) = 0 ↔ a = 0 := by rw [←of_finsupp_zero, of_finsupp_inj] @[simp] lemma of_finsupp_eq_one {a} : (⟨a⟩ : R[X]) = 1 ↔ a = 1 := by rw [←of_finsupp_one, of_finsupp_inj] instance : inhabited R[X] := ⟨0⟩ instance : has_nat_cast R[X] := ⟨λ n, polynomial.of_finsupp n⟩ instance : semiring R[X] := function.injective.semiring to_finsupp to_finsupp_injective to_finsupp_zero to_finsupp_one to_finsupp_add to_finsupp_mul (Ξ» _ _, to_finsupp_smul _ _) to_finsupp_pow (Ξ» _, rfl) instance {S} [monoid S] [distrib_mul_action S R] : distrib_mul_action S R[X] := function.injective.distrib_mul_action ⟨to_finsupp, to_finsupp_zero, to_finsupp_add⟩ to_finsupp_injective to_finsupp_smul instance {S} [monoid S] [distrib_mul_action S R] [has_faithful_smul S R] : has_faithful_smul S R[X] := { eq_of_smul_eq_smul := Ξ» s₁ sβ‚‚ h, eq_of_smul_eq_smul $ Ξ» a : β„• β†’β‚€ R, congr_arg to_finsupp (h ⟨a⟩) } instance {S} [semiring S] [module S R] : module S R[X] := function.injective.module _ ⟨to_finsupp, to_finsupp_zero, to_finsupp_add⟩ to_finsupp_injective to_finsupp_smul instance {S₁ Sβ‚‚} [monoid S₁] [monoid Sβ‚‚] [distrib_mul_action S₁ R] [distrib_mul_action Sβ‚‚ R] [smul_comm_class S₁ Sβ‚‚ R] : smul_comm_class S₁ Sβ‚‚ R[X] := ⟨by { rintros _ _ ⟨⟩, simp_rw [←of_finsupp_smul, smul_comm] }⟩ instance {S₁ Sβ‚‚} [has_smul S₁ Sβ‚‚] [monoid S₁] [monoid Sβ‚‚] [distrib_mul_action S₁ R] [distrib_mul_action Sβ‚‚ R] [is_scalar_tower S₁ Sβ‚‚ R] : is_scalar_tower S₁ Sβ‚‚ R[X] := ⟨by { rintros _ _ ⟨⟩, simp_rw [←of_finsupp_smul, smul_assoc] }⟩ instance {S} [monoid S] [distrib_mul_action S R] [distrib_mul_action Sᡐᡒᡖ R] [is_central_scalar S R] : is_central_scalar S R[X] := ⟨by { rintros _ ⟨⟩, simp_rw [←of_finsupp_smul, op_smul_eq_smul] }⟩ instance [subsingleton R] : unique R[X] := { uniq := by { rintros ⟨x⟩, refine congr_arg of_finsupp _, simp }, .. polynomial.inhabited } variable (R) /-- Ring isomorphism between `R[X]` and `add_monoid_algebra R β„•`. This is just an implementation detail, but it can be useful to transfer results from `finsupp` to polynomials. -/ @[simps apply symm_apply] def to_finsupp_iso : R[X] ≃+* add_monoid_algebra R β„• := { to_fun := to_finsupp, inv_fun := of_finsupp, left_inv := Ξ» ⟨p⟩, rfl, right_inv := Ξ» p, rfl, map_mul' := to_finsupp_mul, map_add' := to_finsupp_add } end add_monoid_algebra variable {R} lemma of_finsupp_sum {ΞΉ : Type*} (s : finset ΞΉ) (f : ΞΉ β†’ add_monoid_algebra R β„•) : (βŸ¨βˆ‘ i in s, f i⟩ : R[X]) = βˆ‘ i in s, ⟨f i⟩ := map_sum (to_finsupp_iso R).symm f s lemma to_finsupp_sum {ΞΉ : Type*} (s : finset ΞΉ) (f : ΞΉ β†’ R[X]) : (βˆ‘ i in s, f i : R[X]).to_finsupp = βˆ‘ i in s, (f i).to_finsupp := map_sum (to_finsupp_iso R) f s /-- The set of all `n` such that `X^n` has a non-zero coefficient. -/ @[simp] def support : R[X] β†’ finset β„• | ⟨p⟩ := p.support @[simp] lemma support_of_finsupp (p) : support (⟨p⟩ : R[X]) = p.support := by rw support @[simp] lemma support_zero : (0 : R[X]).support = βˆ… := rfl @[simp] lemma support_eq_empty : p.support = βˆ… ↔ p = 0 := by { rcases p, simp [support] } lemma card_support_eq_zero : p.support.card = 0 ↔ p = 0 := by simp /-- `monomial s a` is the monomial `a * X^s` -/ def monomial (n : β„•) : R β†’β‚—[R] R[X] := { to_fun := monomial_fun n, map_add' := by simp [monomial_fun], map_smul' := by simp [monomial_fun, ←of_finsupp_smul] } @[simp] lemma to_finsupp_monomial (n : β„•) (r : R) : (monomial n r).to_finsupp = finsupp.single n r := by simp [monomial, monomial_fun] @[simp] lemma of_finsupp_single (n : β„•) (r : R) : (⟨finsupp.single n r⟩ : R[X]) = monomial n r := by simp [monomial, monomial_fun] @[simp] lemma monomial_zero_right (n : β„•) : monomial n (0 : R) = 0 := (monomial n).map_zero -- This is not a `simp` lemma as `monomial_zero_left` is more general. lemma monomial_zero_one : monomial 0 (1 : R) = 1 := rfl -- TODO: can't we just delete this one? lemma monomial_add (n : β„•) (r s : R) : monomial n (r + s) = monomial n r + monomial n s := (monomial n).map_add _ _ lemma monomial_mul_monomial (n m : β„•) (r s : R) : monomial n r * monomial m s = monomial (n + m) (r * s) := to_finsupp_injective $ by simp only [to_finsupp_monomial, to_finsupp_mul, add_monoid_algebra.single_mul_single] @[simp] lemma monomial_pow (n : β„•) (r : R) (k : β„•) : (monomial n r)^k = monomial (n*k) (r^k) := begin induction k with k ih, { simp [pow_zero, monomial_zero_one], }, { simp [pow_succ, ih, monomial_mul_monomial, nat.succ_eq_add_one, mul_add, add_comm] }, end lemma smul_monomial {S} [monoid S] [distrib_mul_action S R] (a : S) (n : β„•) (b : R) : a β€’ monomial n b = monomial n (a β€’ b) := to_finsupp_injective $ by simp lemma monomial_injective (n : β„•) : function.injective (monomial n : R β†’ R[X]) := begin convert (to_finsupp_iso R).symm.injective.comp (single_injective n), ext, simp end @[simp] lemma monomial_eq_zero_iff (t : R) (n : β„•) : monomial n t = 0 ↔ t = 0 := linear_map.map_eq_zero_iff _ (polynomial.monomial_injective n) lemma support_add : (p + q).support βŠ† p.support βˆͺ q.support := begin rcases p, rcases q, simp only [←of_finsupp_add, support], exact support_add end /-- `C a` is the constant polynomial `a`. `C` is provided as a ring homomorphism. -/ def C : R β†’+* R[X] := { map_one' := by simp [monomial_zero_one], map_mul' := by simp [monomial_mul_monomial], map_zero' := by simp, .. monomial 0 } @[simp] lemma monomial_zero_left (a : R) : monomial 0 a = C a := rfl @[simp] lemma to_finsupp_C (a : R) : (C a).to_finsupp = single 0 a := by rw [←monomial_zero_left, to_finsupp_monomial] lemma C_0 : C (0 : R) = 0 := by simp lemma C_1 : C (1 : R) = 1 := rfl lemma C_mul : C (a * b) = C a * C b := C.map_mul a b lemma C_add : C (a + b) = C a + C b := C.map_add a b @[simp] lemma smul_C {S} [monoid S] [distrib_mul_action S R] (s : S) (r : R) : s β€’ C r = C (s β€’ r) := smul_monomial _ _ r @[simp] lemma C_bit0 : C (bit0 a) = bit0 (C a) := C_add @[simp] lemma C_bit1 : C (bit1 a) = bit1 (C a) := by simp [bit1, C_bit0] lemma C_pow : C (a ^ n) = C a ^ n := C.map_pow a n @[simp] lemma C_eq_nat_cast (n : β„•) : C (n : R) = (n : R[X]) := map_nat_cast C n @[simp] lemma C_mul_monomial : C a * monomial n b = monomial n (a * b) := by simp only [←monomial_zero_left, monomial_mul_monomial, zero_add] @[simp] lemma monomial_mul_C : monomial n a * C b = monomial n (a * b) := by simp only [←monomial_zero_left, monomial_mul_monomial, add_zero] /-- `X` is the polynomial variable (aka indeterminate). -/ def X : R[X] := monomial 1 1 lemma monomial_one_one_eq_X : monomial 1 (1 : R) = X := rfl lemma monomial_one_right_eq_X_pow (n : β„•) : monomial n (1 : R) = X^n := begin induction n with n ih, { simp [monomial_zero_one], }, { rw [pow_succ, ←ih, ←monomial_one_one_eq_X, monomial_mul_monomial, add_comm, one_mul], } end /-- `X` commutes with everything, even when the coefficients are noncommutative. -/ lemma X_mul : X * p = p * X := begin rcases p, simp only [X, ←of_finsupp_single, ←of_finsupp_mul, linear_map.coe_mk], ext, simp [add_monoid_algebra.mul_apply, sum_single_index, add_comm], end lemma X_pow_mul {n : β„•} : X^n * p = p * X^n := begin induction n with n ih, { simp, }, { conv_lhs { rw pow_succ', }, rw [mul_assoc, X_mul, ←mul_assoc, ih, mul_assoc, ←pow_succ'], } end /-- Prefer putting constants to the left of `X`. This lemma is the loop-avoiding `simp` version of `polynomial.X_mul`. -/ @[simp] lemma X_mul_C (r : R) : X * C r = C r * X := X_mul /-- Prefer putting constants to the left of `X ^ n`. This lemma is the loop-avoiding `simp` version of `X_pow_mul`. -/ @[simp] lemma X_pow_mul_C (r : R) (n : β„•) : X^n * C r = C r * X^n := X_pow_mul lemma X_pow_mul_assoc {n : β„•} : (p * X^n) * q = (p * q) * X^n := by rw [mul_assoc, X_pow_mul, ←mul_assoc] /-- Prefer putting constants to the left of `X ^ n`. This lemma is the loop-avoiding `simp` version of `X_pow_mul_assoc`. -/ @[simp] lemma X_pow_mul_assoc_C {n : β„•} (r : R) : (p * X^n) * C r = p * C r * X^n := X_pow_mul_assoc lemma commute_X (p : R[X]) : commute X p := X_mul lemma commute_X_pow (p : R[X]) (n : β„•) : commute (X ^ n) p := X_pow_mul @[simp] lemma monomial_mul_X (n : β„•) (r : R) : monomial n r * X = monomial (n+1) r := by erw [monomial_mul_monomial, mul_one] @[simp] lemma monomial_mul_X_pow (n : β„•) (r : R) (k : β„•) : monomial n r * X^k = monomial (n+k) r := begin induction k with k ih, { simp, }, { simp [ih, pow_succ', ←mul_assoc, add_assoc], }, end @[simp] lemma X_mul_monomial (n : β„•) (r : R) : X * monomial n r = monomial (n+1) r := by rw [X_mul, monomial_mul_X] @[simp] lemma X_pow_mul_monomial (k n : β„•) (r : R) : X^k * monomial n r = monomial (n+k) r := by rw [X_pow_mul, monomial_mul_X_pow] /-- `coeff p n` (often denoted `p.coeff n`) is the coefficient of `X^n` in `p`. -/ @[simp] def coeff : R[X] β†’ β„• β†’ R | ⟨p⟩ := p lemma coeff_monomial : coeff (monomial n a) m = if n = m then a else 0 := by { simp only [←of_finsupp_single, coeff, linear_map.coe_mk], rw finsupp.single_apply } @[simp] lemma coeff_zero (n : β„•) : coeff (0 : R[X]) n = 0 := rfl @[simp] lemma coeff_one_zero : coeff (1 : R[X]) 0 = 1 := by { rw [← monomial_zero_one, coeff_monomial], simp } @[simp] lemma coeff_X_one : coeff (X : R[X]) 1 = 1 := coeff_monomial @[simp] lemma coeff_X_zero : coeff (X : R[X]) 0 = 0 := coeff_monomial @[simp] lemma coeff_monomial_succ : coeff (monomial (n+1) a) 0 = 0 := by simp [coeff_monomial] lemma coeff_X : coeff (X : R[X]) n = if 1 = n then 1 else 0 := coeff_monomial lemma coeff_X_of_ne_one {n : β„•} (hn : n β‰  1) : coeff (X : R[X]) n = 0 := by rw [coeff_X, if_neg hn.symm] @[simp] lemma mem_support_iff : n ∈ p.support ↔ p.coeff n β‰  0 := by { rcases p, simp } lemma not_mem_support_iff : n βˆ‰ p.support ↔ p.coeff n = 0 := by simp lemma coeff_C : coeff (C a) n = ite (n = 0) a 0 := by { convert coeff_monomial using 2, simp [eq_comm], } @[simp] lemma coeff_C_zero : coeff (C a) 0 = a := coeff_monomial lemma coeff_C_ne_zero (h : n β‰  0) : (C a).coeff n = 0 := by rw [coeff_C, if_neg h] theorem nontrivial.of_polynomial_ne (h : p β‰  q) : nontrivial R := nontrivial_of_ne 0 1 $ Ξ» h01, h $ by rw [← mul_one p, ← mul_one q, ← C_1, ← h01, C_0, mul_zero, mul_zero] lemma monomial_eq_C_mul_X : βˆ€{n}, monomial n a = C a * X^n | 0 := (mul_one _).symm | (n+1) := calc monomial (n + 1) a = monomial n a * X : by { rw [X, monomial_mul_monomial, mul_one], } ... = (C a * X^n) * X : by rw [monomial_eq_C_mul_X] ... = C a * X^(n+1) : by simp only [pow_add, mul_assoc, pow_one] @[simp] lemma C_inj : C a = C b ↔ a = b := ⟨λ h, coeff_C_zero.symm.trans (h.symm β–Έ coeff_C_zero), congr_arg C⟩ @[simp] lemma C_eq_zero : C a = 0 ↔ a = 0 := calc C a = 0 ↔ C a = C 0 : by rw C_0 ... ↔ a = 0 : C_inj theorem ext_iff {p q : R[X]} : p = q ↔ βˆ€ n, coeff p n = coeff q n := by { rcases p, rcases q, simp [coeff, finsupp.ext_iff] } @[ext] lemma ext {p q : R[X]} : (βˆ€ n, coeff p n = coeff q n) β†’ p = q := ext_iff.2 /-- Monomials generate the additive monoid of polynomials. -/ lemma add_submonoid_closure_set_of_eq_monomial : add_submonoid.closure {p : R[X] | βˆƒ n a, p = monomial n a} = ⊀ := begin apply top_unique, rw [← add_submonoid.map_equiv_top (to_finsupp_iso R).symm.to_add_equiv, ← finsupp.add_closure_set_of_eq_single, add_monoid_hom.map_mclosure], refine add_submonoid.closure_mono (set.image_subset_iff.2 _), rintro _ ⟨n, a, rfl⟩, exact ⟨n, a, polynomial.of_finsupp_single _ _⟩, end lemma add_hom_ext {M : Type*} [add_monoid M] {f g : R[X] β†’+ M} (h : βˆ€ n a, f (monomial n a) = g (monomial n a)) : f = g := add_monoid_hom.eq_of_eq_on_mdense add_submonoid_closure_set_of_eq_monomial $ by { rintro p ⟨n, a, rfl⟩, exact h n a } @[ext] lemma add_hom_ext' {M : Type*} [add_monoid M] {f g : R[X] β†’+ M} (h : βˆ€ n, f.comp (monomial n).to_add_monoid_hom = g.comp (monomial n).to_add_monoid_hom) : f = g := add_hom_ext (Ξ» n, add_monoid_hom.congr_fun (h n)) @[ext] lemma lhom_ext' {M : Type*} [add_comm_monoid M] [module R M] {f g : R[X] β†’β‚—[R] M} (h : βˆ€ n, f.comp (monomial n) = g.comp (monomial n)) : f = g := linear_map.to_add_monoid_hom_injective $ add_hom_ext $ Ξ» n, linear_map.congr_fun (h n) -- this has the same content as the subsingleton lemma eq_zero_of_eq_zero (h : (0 : R) = (1 : R)) (p : R[X]) : p = 0 := by rw [←one_smul R p, ←h, zero_smul] section fewnomials lemma support_monomial (n) {a : R} (H : a β‰  0) : (monomial n a).support = singleton n := by rw [←of_finsupp_single, support, finsupp.support_single_ne_zero _ H] lemma support_monomial' (n) (a : R) : (monomial n a).support βŠ† singleton n := by { rw [←of_finsupp_single, support], exact finsupp.support_single_subset } lemma support_C_mul_X_pow (n : β„•) {c : R} (h : c β‰  0) : (C c * X ^ n).support = singleton n := by rw [←monomial_eq_C_mul_X, support_monomial n h] lemma support_C_mul_X_pow' (n : β„•) (c : R) : (C c * X ^ n).support βŠ† singleton n := begin rw ← monomial_eq_C_mul_X, exact support_monomial' n c, end open finset lemma support_binomial' (k m : β„•) (x y : R) : (C x * X ^ k + C y * X ^ m).support βŠ† {k, m} := support_add.trans (union_subset ((support_C_mul_X_pow' k x).trans (singleton_subset_iff.mpr (mem_insert_self k {m}))) ((support_C_mul_X_pow' m y).trans (singleton_subset_iff.mpr (mem_insert_of_mem (mem_singleton_self m))))) lemma support_trinomial' (k m n : β„•) (x y z : R) : (C x * X ^ k + C y * X ^ m + C z * X ^ n).support βŠ† {k, m, n} := support_add.trans (union_subset (support_add.trans (union_subset ((support_C_mul_X_pow' k x).trans (singleton_subset_iff.mpr (mem_insert_self k {m, n}))) ((support_C_mul_X_pow' m y).trans (singleton_subset_iff.mpr (mem_insert_of_mem (mem_insert_self m {n})))))) ((support_C_mul_X_pow' n z).trans (singleton_subset_iff.mpr (mem_insert_of_mem (mem_insert_of_mem (mem_singleton_self n)))))) end fewnomials lemma X_pow_eq_monomial (n) : X ^ n = monomial n (1:R) := begin induction n with n hn, { rw [pow_zero, monomial_zero_one] }, { rw [pow_succ', hn, X, monomial_mul_monomial, one_mul] }, end lemma monomial_eq_smul_X {n} : monomial n (a : R) = a β€’ X^n := calc monomial n a = monomial n (a * 1) : by simp ... = a β€’ monomial n 1 : by rw [smul_monomial, smul_eq_mul] ... = a β€’ X^n : by rw X_pow_eq_monomial lemma support_X_pow (H : Β¬ (1:R) = 0) (n : β„•) : (X^n : R[X]).support = singleton n := begin convert support_monomial n H, exact X_pow_eq_monomial n, end lemma support_X_empty (H : (1:R)=0) : (X : R[X]).support = βˆ… := begin rw [X, H, monomial_zero_right, support_zero], end lemma support_X (H : Β¬ (1 : R) = 0) : (X : R[X]).support = singleton 1 := begin rw [← pow_one X, support_X_pow H 1], end lemma monomial_left_inj {a : R} (ha : a β‰  0) {i j : β„•} : (monomial i a) = (monomial j a) ↔ i = j := by simp_rw [←of_finsupp_single, finsupp.single_left_inj ha] lemma binomial_eq_binomial {k l m n : β„•} {u v : R} (hu : u β‰  0) (hv : v β‰  0) : C u * X ^ k + C v * X ^ l = C u * X ^ m + C v * X ^ n ↔ (k = m ∧ l = n) ∨ (u = v ∧ k = n ∧ l = m) ∨ (u + v = 0 ∧ k = l ∧ m = n) := begin simp_rw [←monomial_eq_C_mul_X, ←to_finsupp_inj, to_finsupp_add, to_finsupp_monomial], exact finsupp.single_add_single_eq_single_add_single hu hv, end lemma nat_cast_mul (n : β„•) (p : R[X]) : (n : R[X]) * p = n β€’ p := (nsmul_eq_mul _ _).symm /-- Summing the values of a function applied to the coefficients of a polynomial -/ def sum {S : Type*} [add_comm_monoid S] (p : R[X]) (f : β„• β†’ R β†’ S) : S := βˆ‘ n in p.support, f n (p.coeff n) lemma sum_def {S : Type*} [add_comm_monoid S] (p : R[X]) (f : β„• β†’ R β†’ S) : p.sum f = βˆ‘ n in p.support, f n (p.coeff n) := rfl lemma sum_eq_of_subset {S : Type*} [add_comm_monoid S] (p : R[X]) (f : β„• β†’ R β†’ S) (hf : βˆ€ i, f i 0 = 0) (s : finset β„•) (hs : p.support βŠ† s) : p.sum f = βˆ‘ n in s, f n (p.coeff n) := begin apply finset.sum_subset hs (Ξ» n hn h'n, _), rw not_mem_support_iff at h'n, simp [h'n, hf] end /-- Expressing the product of two polynomials as a double sum. -/ lemma mul_eq_sum_sum : p * q = βˆ‘ i in p.support, q.sum (Ξ» j a, (monomial (i + j)) (p.coeff i * a)) := begin apply to_finsupp_injective, rcases p, rcases q, simp [support, sum, coeff, to_finsupp_sum], refl end @[simp] lemma sum_zero_index {S : Type*} [add_comm_monoid S] (f : β„• β†’ R β†’ S) : (0 : R[X]).sum f = 0 := by simp [sum] @[simp] lemma sum_monomial_index {S : Type*} [add_comm_monoid S] (n : β„•) (a : R) (f : β„• β†’ R β†’ S) (hf : f n 0 = 0) : (monomial n a : R[X]).sum f = f n a := begin by_cases h : a = 0, { simp [h, hf] }, { simp [sum, support_monomial, h, coeff_monomial] } end @[simp] lemma sum_C_index {a} {Ξ²} [add_comm_monoid Ξ²] {f : β„• β†’ R β†’ Ξ²} (h : f 0 0 = 0) : (C a).sum f = f 0 a := sum_monomial_index 0 a f h -- the assumption `hf` is only necessary when the ring is trivial @[simp] lemma sum_X_index {S : Type*} [add_comm_monoid S] {f : β„• β†’ R β†’ S} (hf : f 1 0 = 0) : (X : R[X]).sum f = f 1 1 := sum_monomial_index 1 1 f hf lemma sum_add_index {S : Type*} [add_comm_monoid S] (p q : R[X]) (f : β„• β†’ R β†’ S) (hf : βˆ€ i, f i 0 = 0) (h_add : βˆ€a b₁ bβ‚‚, f a (b₁ + bβ‚‚) = f a b₁ + f a bβ‚‚) : (p + q).sum f = p.sum f + q.sum f := begin rcases p, rcases q, simp only [←of_finsupp_add, sum, support, coeff, pi.add_apply, coe_add], exact finsupp.sum_add_index' hf h_add, end lemma sum_add' {S : Type*} [add_comm_monoid S] (p : R[X]) (f g : β„• β†’ R β†’ S) : p.sum (f + g) = p.sum f + p.sum g := by simp [sum_def, finset.sum_add_distrib] lemma sum_add {S : Type*} [add_comm_monoid S] (p : R[X]) (f g : β„• β†’ R β†’ S) : p.sum (Ξ» n x, f n x + g n x) = p.sum f + p.sum g := sum_add' _ _ _ lemma sum_smul_index {S : Type*} [add_comm_monoid S] (p : R[X]) (b : R) (f : β„• β†’ R β†’ S) (hf : βˆ€ i, f i 0 = 0) : (b β€’ p).sum f = p.sum (Ξ» n a, f n (b * a)) := begin rcases p, simpa [sum, support, coeff] using finsupp.sum_smul_index hf, end /-- `erase p n` is the polynomial `p` in which the `X^n` term has been erased. -/ @[irreducible] definition erase (n : β„•) : R[X] β†’ R[X] | ⟨p⟩ := ⟨p.erase n⟩ @[simp] lemma to_finsupp_erase (p : R[X]) (n : β„•) : to_finsupp (p.erase n) = (p.to_finsupp).erase n := by { rcases p, simp only [erase] } @[simp] lemma of_finsupp_erase (p : add_monoid_algebra R β„•) (n : β„•) : (⟨p.erase n⟩ : R[X]) = (⟨p⟩ : R[X]).erase n := by { rcases p, simp only [erase] } @[simp] lemma support_erase (p : R[X]) (n : β„•) : support (p.erase n) = (support p).erase n := by { rcases p, simp only [support, erase, support_erase] } lemma monomial_add_erase (p : R[X]) (n : β„•) : monomial n (coeff p n) + p.erase n = p := to_finsupp_injective $ begin rcases p, rw [to_finsupp_add, to_finsupp_monomial, to_finsupp_erase, coeff], exact finsupp.single_add_erase _ _, end lemma coeff_erase (p : R[X]) (n i : β„•) : (p.erase n).coeff i = if i = n then 0 else p.coeff i := begin rcases p, simp only [erase, coeff], convert rfl end @[simp] lemma erase_zero (n : β„•) : (0 : R[X]).erase n = 0 := to_finsupp_injective $ by simp @[simp] lemma erase_monomial {n : β„•} {a : R} : erase n (monomial n a) = 0 := to_finsupp_injective $ by simp @[simp] lemma erase_same (p : R[X]) (n : β„•) : coeff (p.erase n) n = 0 := by simp [coeff_erase] @[simp] lemma erase_ne (p : R[X]) (n i : β„•) (h : i β‰  n) : coeff (p.erase n) i = coeff p i := by simp [coeff_erase, h] section update /-- Replace the coefficient of a `p : polynomial p` at a given degree `n : β„•` by a given value `a : R`. If `a = 0`, this is equal to `p.erase n` If `p.nat_degree < n` and `a β‰  0`, this increases the degree to `n`. -/ def update (p : R[X]) (n : β„•) (a : R) : R[X] := polynomial.of_finsupp (p.to_finsupp.update n a) lemma coeff_update (p : R[X]) (n : β„•) (a : R) : (p.update n a).coeff = function.update p.coeff n a := begin ext, cases p, simp only [coeff, update, function.update_apply, coe_update], end lemma coeff_update_apply (p : R[X]) (n : β„•) (a : R) (i : β„•) : (p.update n a).coeff i = if (i = n) then a else p.coeff i := by rw [coeff_update, function.update_apply] @[simp] lemma coeff_update_same (p : R[X]) (n : β„•) (a : R) : (p.update n a).coeff n = a := by rw [p.coeff_update_apply, if_pos rfl] lemma coeff_update_ne (p : R[X]) {n : β„•} (a : R) {i : β„•} (h : i β‰  n) : (p.update n a).coeff i = p.coeff i := by rw [p.coeff_update_apply, if_neg h] @[simp] lemma update_zero_eq_erase (p : R[X]) (n : β„•) : p.update n 0 = p.erase n := by { ext, rw [coeff_update_apply, coeff_erase] } lemma support_update (p : R[X]) (n : β„•) (a : R) [decidable (a = 0)] : support (p.update n a) = if a = 0 then p.support.erase n else insert n p.support := by { cases p, simp only [support, update, support_update], congr } lemma support_update_zero (p : R[X]) (n : β„•) : support (p.update n 0) = p.support.erase n := by rw [update_zero_eq_erase, support_erase] lemma support_update_ne_zero (p : R[X]) (n : β„•) {a : R} (ha : a β‰  0) : support (p.update n a) = insert n p.support := by classical; rw [support_update, if_neg ha] end update end semiring section comm_semiring variables [comm_semiring R] instance : comm_semiring R[X] := function.injective.comm_semiring to_finsupp to_finsupp_injective to_finsupp_zero to_finsupp_one to_finsupp_add to_finsupp_mul (Ξ» _ _, to_finsupp_smul _ _) to_finsupp_pow (Ξ» _, rfl) end comm_semiring section ring variables [ring R] instance : has_int_cast R[X] := ⟨λ n, of_finsupp n⟩ instance : ring R[X] := function.injective.ring to_finsupp to_finsupp_injective to_finsupp_zero to_finsupp_one to_finsupp_add to_finsupp_mul to_finsupp_neg to_finsupp_sub (Ξ» _ _, to_finsupp_smul _ _) (Ξ» _ _, to_finsupp_smul _ _) to_finsupp_pow (Ξ» _, rfl) (Ξ» _, rfl) @[simp] lemma coeff_neg (p : R[X]) (n : β„•) : coeff (-p) n = -coeff p n := by { rcases p, rw [←of_finsupp_neg, coeff, coeff, finsupp.neg_apply] } @[simp] lemma coeff_sub (p q : R[X]) (n : β„•) : coeff (p - q) n = coeff p n - coeff q n := by { rcases p, rcases q, rw [←of_finsupp_sub, coeff, coeff, coeff, finsupp.sub_apply] } @[simp] lemma monomial_neg (n : β„•) (a : R) : monomial n (-a) = -(monomial n a) := by rw [eq_neg_iff_add_eq_zero, ←monomial_add, neg_add_self, monomial_zero_right] @[simp] lemma support_neg {p : R[X]} : (-p).support = p.support := by { rcases p, rw [←of_finsupp_neg, support, support, finsupp.support_neg] } @[simp] lemma C_eq_int_cast (n : β„€) : C (n : R) = n := (C : R β†’+* _).map_int_cast n end ring instance [comm_ring R] : comm_ring R[X] := function.injective.comm_ring to_finsupp to_finsupp_injective to_finsupp_zero to_finsupp_one to_finsupp_add to_finsupp_mul to_finsupp_neg to_finsupp_sub (Ξ» _ _, to_finsupp_smul _ _) (Ξ» _ _, to_finsupp_smul _ _) to_finsupp_pow (Ξ» _, rfl) (Ξ» _, rfl) section nonzero_semiring variables [semiring R] [nontrivial R] instance : nontrivial R[X] := begin have h : nontrivial (add_monoid_algebra R β„•) := by apply_instance, rcases h.exists_pair_ne with ⟨x, y, hxy⟩, refine ⟨⟨⟨x⟩, ⟨y⟩, _⟩⟩, simp [hxy], end lemma X_ne_zero : (X : R[X]) β‰  0 := mt (congr_arg (Ξ» p, coeff p 1)) (by simp) end nonzero_semiring @[simp] lemma nontrivial_iff [semiring R] : nontrivial R[X] ↔ nontrivial R := ⟨λ h, let ⟨r, s, hrs⟩ := @exists_pair_ne _ h in nontrivial.of_polynomial_ne hrs, Ξ» h, @polynomial.nontrivial _ _ h⟩ section repr variables [semiring R] open_locale classical instance [has_repr R] : has_repr R[X] := ⟨λ p, if p = 0 then "0" else (p.support.sort (≀)).foldr (Ξ» n a, a ++ (if a = "" then "" else " + ") ++ if n = 0 then "C (" ++ repr (coeff p n) ++ ")" else if n = 1 then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X" else if (coeff p n) = 1 then "X ^ " ++ repr n else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""⟩ end repr end polynomial
c343006aafe253e403cfc67635da502ccee098bf
64874bd1010548c7f5a6e3e8902efa63baaff785
/library/data/nat/div.lean
9d8fbc300a44c321bddfe6faaf9d36ce34906664
[ "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
19,274
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.nat.div Authors: Jeremy Avigad, Leonardo de Moura Definitions of div, mod, and gcd on the natural numbers. -/ import data.nat.sub data.nat.comm_semiring tools.fake_simplifier open eq.ops well_founded decidable fake_simplifier prod namespace nat /- div and mod -/ -- auxiliary lemma used to justify div private definition div_rec_lemma {x y : nat} (H : 0 < y ∧ y ≀ x) : x - y < x := and.rec_on H (Ξ» ypos ylex, sub_lt (lt_of_lt_of_le ypos ylex) ypos) private definition div.F (x : nat) (f : Ξ  x₁, x₁ < x β†’ nat β†’ nat) (y : nat) : nat := if H : 0 < y ∧ y ≀ x then f (x - y) (div_rec_lemma H) y + 1 else zero definition divide (x y : nat) := fix div.F x y theorem divide_def (x y : nat) : divide x y = if 0 < y ∧ y ≀ x then divide (x - y) y + 1 else 0 := congr_fun (fix_eq div.F x) y notation a div b := divide a b theorem div_zero (a : β„•) : a div 0 = 0 := divide_def a 0 ⬝ if_neg (!not_and_of_not_left (lt.irrefl 0)) theorem div_eq_zero_of_lt {a b : β„•} (h : a < b) : a div b = 0 := divide_def a b ⬝ if_neg (!not_and_of_not_right (not_le_of_lt h)) theorem zero_div (b : β„•) : 0 div b = 0 := divide_def 0 b ⬝ if_neg (Ξ» h, and.rec_on h (Ξ» l r, absurd (lt_of_lt_of_le l r) (lt.irrefl 0))) theorem div_eq_succ_sub_div {a b : β„•} (h₁ : b > 0) (hβ‚‚ : a β‰₯ b) : a div b = succ ((a - b) div b) := divide_def a b ⬝ if_pos (and.intro h₁ hβ‚‚) theorem add_div_left {x z : β„•} (H : z > 0) : (x + z) div z = succ (x div z) := calc (x + z) div z = if 0 < z ∧ z ≀ x + z then (x + z - z) div z + 1 else 0 : !divide_def ... = (x + z - z) div z + 1 : if_pos (and.intro H (le_add_left z x)) ... = succ (x div z) : {!add_sub_cancel} theorem add_div_right {x z : β„•} (H : x > 0) : (x + z) div x = succ (z div x) := !add.comm β–Έ add_div_left H theorem add_mul_div_left {x y z : β„•} (H : z > 0) : (x + y * z) div z = x div z + y := induction_on y (calc (x + zero * z) div z = (x + zero) div z : zero_mul ... = x div z : add_zero ... = x div z + zero : add_zero) (take y, assume IH : (x + y * z) div z = x div z + y, calc (x + succ y * z) div z = (x + y * z + z) div z : by simp ... = succ ((x + y * z) div z) : add_div_left H ... = x div z + succ y : by simp) theorem add_mul_div_right {x y z : β„•} (H : y > 0) : (x + y * z) div y = x div y + z := !mul.comm β–Έ add_mul_div_left H private definition mod.F (x : nat) (f : Ξ  x₁, x₁ < x β†’ nat β†’ nat) (y : nat) : nat := if H : 0 < y ∧ y ≀ x then f (x - y) (div_rec_lemma H) y else x definition modulo (x y : nat) := fix mod.F x y notation a mod b := modulo a b theorem modulo_def (x y : nat) : modulo x y = if 0 < y ∧ y ≀ x then modulo (x - y) y else x := congr_fun (fix_eq mod.F x) y theorem mod_zero (a : β„•) : a mod 0 = a := modulo_def a 0 ⬝ if_neg (!not_and_of_not_left (lt.irrefl 0)) theorem mod_eq_of_lt {a b : β„•} (h : a < b) : a mod b = a := modulo_def a b ⬝ if_neg (!not_and_of_not_right (not_le_of_lt h)) theorem zero_mod (b : β„•) : 0 mod b = 0 := modulo_def 0 b ⬝ if_neg (Ξ» h, and.rec_on h (Ξ» l r, absurd (lt_of_lt_of_le l r) (lt.irrefl 0))) theorem mod_eq_sub_mod {a b : β„•} (h₁ : b > 0) (hβ‚‚ : a β‰₯ b) : a mod b = (a - b) mod b := modulo_def a b ⬝ if_pos (and.intro h₁ hβ‚‚) theorem add_mod_left {x z : β„•} (H : z > 0) : (x + z) mod z = x mod z := calc (x + z) mod z = if 0 < z ∧ z ≀ x + z then (x + z - z) mod z else _ : modulo_def ... = (x + z - z) mod z : if_pos (and.intro H (le_add_left z x)) ... = x mod z : add_sub_cancel theorem add_mod_right {x z : β„•} (H : x > 0) : (x + z) mod x = z mod x := !add.comm β–Έ add_mod_left H theorem add_mul_mod_left {x y z : β„•} (H : z > 0) : (x + y * z) mod z = x mod z := induction_on y (calc (x + zero * z) mod z = (x + zero) mod z : zero_mul ... = x mod z : add_zero) (take y, assume IH : (x + y * z) mod z = x mod z, calc (x + succ y * z) mod z = (x + (y * z + z)) mod z : succ_mul ... = (x + y * z + z) mod z : add.assoc ... = (x + y * z) mod z : add_mod_left H ... = x mod z : IH) theorem add_mul_mod_right {x y z : β„•} (H : y > 0) : (x + y * z) mod y = x mod y := !mul.comm β–Έ add_mul_mod_left H theorem mul_mod_left {m n : β„•} : (m * n) mod n = 0 := by_cases_zero_pos n (by simp) (take n, assume npos : n > 0, (by simp) β–Έ (@add_mul_mod_left 0 m _ npos)) theorem mul_mod_right {m n : β„•} : (m * n) mod m = 0 := !mul.comm β–Έ !mul_mod_left theorem mod_lt {x y : β„•} (H : y > 0) : x mod y < y := case_strong_induction_on x (show 0 mod y < y, from !zero_mod⁻¹ β–Έ H) (take x, assume IH : βˆ€x', x' ≀ x β†’ x' mod y < y, show succ x mod y < y, from by_cases -- (succ x < y) (assume H1 : succ x < y, have H2 : succ x mod y = succ x, from mod_eq_of_lt H1, show succ x mod y < y, from H2⁻¹ β–Έ H1) (assume H1 : Β¬ succ x < y, have H2 : y ≀ succ x, from le_of_not_lt H1, have H3 : succ x mod y = (succ x - y) mod y, from mod_eq_sub_mod H H2, have H4 : succ x - y < succ x, from sub_lt !succ_pos H, have H5 : succ x - y ≀ x, from le_of_lt_succ H4, show succ x mod y < y, from H3⁻¹ β–Έ IH _ H5)) /- properties of div and mod together -/ -- the quotient / remainder theorem theorem eq_div_mul_add_mod {x y : β„•} : x = x div y * y + x mod y := by_cases_zero_pos y (show x = x div 0 * 0 + x mod 0, from (calc x div 0 * 0 + x mod 0 = 0 + x mod 0 : mul_zero ... = x mod 0 : zero_add ... = x : mod_zero)⁻¹) (take y, assume H : y > 0, show x = x div y * y + x mod y, from case_strong_induction_on x (show 0 = (0 div y) * y + 0 mod y, by simp) (take x, assume IH : βˆ€x', x' ≀ x β†’ x' = x' div y * y + x' mod y, show succ x = succ x div y * y + succ x mod y, from by_cases -- (succ x < y) (assume H1 : succ x < y, have H2 : succ x div y = 0, from div_eq_zero_of_lt H1, have H3 : succ x mod y = succ x, from mod_eq_of_lt H1, by simp) (assume H1 : Β¬ succ x < y, have H2 : y ≀ succ x, from le_of_not_lt H1, have H3 : succ x div y = succ ((succ x - y) div y), from div_eq_succ_sub_div H H2, have H4 : succ x mod y = (succ x - y) mod y, from mod_eq_sub_mod H H2, have H5 : succ x - y < succ x, from sub_lt !succ_pos H, have H6 : succ x - y ≀ x, from le_of_lt_succ H5, (calc succ x div y * y + succ x mod y = succ ((succ x - y) div y) * y + succ x mod y : H3 ... = ((succ x - y) div y) * y + y + succ x mod y : succ_mul ... = ((succ x - y) div y) * y + y + (succ x - y) mod y : H4 ... = ((succ x - y) div y) * y + (succ x - y) mod y + y : add.right_comm ... = succ x - y + y : {!(IH _ H6)⁻¹} ... = succ x : sub_add_cancel H2)⁻¹))) theorem mod_le {x y : β„•} : x mod y ≀ x := eq_div_mul_add_mod⁻¹ β–Έ !le_add_left theorem eq_remainder {y : β„•} (H : y > 0) {q1 r1 q2 r2 : β„•} (H1 : r1 < y) (H2 : r2 < y) (H3 : q1 * y + r1 = q2 * y + r2) : r1 = r2 := calc r1 = r1 mod y : by simp ... = (r1 + q1 * y) mod y : (add_mul_mod_left H)⁻¹ ... = (q1 * y + r1) mod y : add.comm ... = (r2 + q2 * y) mod y : by simp ... = r2 mod y : add_mul_mod_left H ... = r2 : by simp theorem eq_quotient {y : β„•} (H : y > 0) {q1 r1 q2 r2 : β„•} (H1 : r1 < y) (H2 : r2 < y) (H3 : q1 * y + r1 = q2 * y + r2) : q1 = q2 := have H4 : q1 * y + r2 = q2 * y + r2, from (eq_remainder H H1 H2 H3) β–Έ H3, have H5 : q1 * y = q2 * y, from add.cancel_right H4, have H6 : y > 0, from lt_of_le_of_lt !zero_le H1, show q1 = q2, from eq_of_mul_eq_mul_right H6 H5 theorem mul_div_mul_left {z x y : β„•} (zpos : z > 0) : (z * x) div (z * y) = x div y := by_cases -- (y = 0) (assume H : y = 0, by simp) (assume H : y β‰  0, have ypos : y > 0, from pos_of_ne_zero H, have zypos : z * y > 0, from mul_pos zpos ypos, have H1 : (z * x) mod (z * y) < z * y, from mod_lt zypos, have H2 : z * (x mod y) < z * y, from mul_lt_mul_of_pos_left (mod_lt ypos) zpos, eq_quotient zypos H1 H2 (calc ((z * x) div (z * y)) * (z * y) + (z * x) mod (z * y) = z * x : eq_div_mul_add_mod ... = z * (x div y * y + x mod y) : eq_div_mul_add_mod ... = z * (x div y * y) + z * (x mod y) : mul.left_distrib ... = (x div y) * (z * y) + z * (x mod y) : mul.left_comm)) theorem mul_div_mul_right {x z y : β„•} (zpos : z > 0) : (x * z) div (y * z) = x div y := !mul.comm β–Έ !mul.comm β–Έ mul_div_mul_left zpos theorem mul_mod_mul_left {z x y : β„•} (zpos : z > 0) : (z * x) mod (z * y) = z * (x mod y) := by_cases -- (y = 0) (assume H : y = 0, by simp) (assume H : y β‰  0, have ypos : y > 0, from pos_of_ne_zero H, have zypos : z * y > 0, from mul_pos zpos ypos, have H1 : (z * x) mod (z * y) < z * y, from mod_lt zypos, have H2 : z * (x mod y) < z * y, from mul_lt_mul_of_pos_left (mod_lt ypos) zpos, eq_remainder zypos H1 H2 (calc ((z * x) div (z * y)) * (z * y) + (z * x) mod (z * y) = z * x : eq_div_mul_add_mod ... = z * (x div y * y + x mod y) : eq_div_mul_add_mod ... = z * (x div y * y) + z * (x mod y) : mul.left_distrib ... = (x div y) * (z * y) + z * (x mod y) : mul.left_comm)) theorem mul_mod_mul_right {x z y : β„•} (zpos : z > 0) : (x * z) mod (y * z) = (x mod y) * z := mul.comm z x β–Έ mul.comm z y β–Έ !mul.comm β–Έ mul_mod_mul_left zpos theorem mod_one (x : β„•) : x mod 1 = 0 := have H1 : x mod 1 < 1, from mod_lt !succ_pos, eq_zero_of_le_zero (le_of_lt_succ H1) theorem mod_self (n : β„•) : n mod n = 0 := cases_on n (by simp) (take n, have H : (succ n * 1) mod (succ n * 1) = succ n * (1 mod 1), from mul_mod_mul_left !succ_pos, (by simp) β–Έ H) theorem div_one (n : β„•) : n div 1 = n := have H : n div 1 * 1 + n mod 1 = n, from eq_div_mul_add_mod⁻¹, (by simp) β–Έ H theorem div_self {n : β„•} (H : n > 0) : n div n = 1 := have H1 : (n * 1) div (n * 1) = 1 div 1, from mul_div_mul_left H, (by simp) β–Έ H1 theorem div_mul_eq_of_mod_eq_zero {x y : β„•} (H : x mod y = 0) : x div y * y = x := (calc x = x div y * y + x mod y : eq_div_mul_add_mod ... = x div y * y + 0 : H ... = x div y * y : !add_zero)⁻¹ /- divides -/ theorem dvd_of_mod_eq_zero {x y : β„•} (H : y mod x = 0) : x | y := dvd.intro (!mul.comm β–Έ div_mul_eq_of_mod_eq_zero H) theorem mod_eq_zero_of_dvd {x y : β„•} (H : x | y) : y mod x = 0 := dvd.elim H (take z, assume H1 : x * z = y, H1 β–Έ !mul_mod_right) theorem dvd_iff_mod_eq_zero (x y : β„•) : x | y ↔ y mod x = 0 := iff.intro mod_eq_zero_of_dvd dvd_of_mod_eq_zero definition dvd.decidable_rel [instance] : decidable_rel dvd := take m n, decidable_of_decidable_of_iff _ (iff.symm !dvd_iff_mod_eq_zero) theorem div_mul_eq_of_dvd {x y : β„•} (H : y | x) : x div y * y = x := div_mul_eq_of_mod_eq_zero (mod_eq_zero_of_dvd H) theorem dvd_of_dvd_add_left {m n1 n2 : β„•} : m | (n1 + n2) β†’ m | n1 β†’ m | n2 := by_cases_zero_pos m (assume (H1 : 0 | n1 + n2) (H2 : 0 | n1), have H3 : n1 + n2 = 0, from eq_zero_of_zero_dvd H1, have H4 : n1 = 0, from eq_zero_of_zero_dvd H2, have H5 : n2 = 0, from calc n2 = 0 + n2 : zero_add ... = n1 + n2 : H4 ... = 0 : H3, show 0 | n2, from H5 β–Έ dvd.refl n2) (take m, assume mpos : m > 0, assume H1 : m | (n1 + n2), assume H2 : m | n1, have H3 : n1 + n2 = n1 + n2 div m * m, from calc n1 + n2 = (n1 + n2) div m * m : div_mul_eq_of_dvd H1 ... = (n1 div m * m + n2) div m * m : div_mul_eq_of_dvd H2 ... = (n2 + n1 div m * m) div m * m : add.comm ... = (n2 div m + n1 div m) * m : add_mul_div_left mpos ... = n2 div m * m + n1 div m * m : mul.right_distrib ... = n1 div m * m + n2 div m * m : add.comm ... = n1 + n2 div m * m : div_mul_eq_of_dvd H2, have H4 : n2 = n2 div m * m, from add.cancel_left H3, have H5 : m * (n2 div m) = n2, from !mul.comm β–Έ H4⁻¹, dvd.intro H5) theorem dvd_of_dvd_add_right {m n1 n2 : β„•} (H : m | (n1 + n2)) : m | n2 β†’ m | n1 := dvd_of_dvd_add_left (!add.comm β–Έ H) theorem dvd_sub {m n1 n2 : β„•} (H1 : m | n1) (H2 : m | n2) : m | (n1 - n2) := by_cases (assume H3 : n1 β‰₯ n2, have H4 : n1 = n1 - n2 + n2, from (sub_add_cancel H3)⁻¹, show m | n1 - n2, from dvd_of_dvd_add_right (H4 β–Έ H1) H2) (assume H3 : Β¬ (n1 β‰₯ n2), have H4 : n1 - n2 = 0, from sub_eq_zero_of_le (le_of_lt (lt_of_not_le H3)), show m | n1 - n2, from H4⁻¹ β–Έ dvd_zero _) theorem dvd.antisymm {m n : β„•} : m | n β†’ n | m β†’ m = n := by_cases_zero_pos n (assume H1, assume H2 : 0 | m, eq_zero_of_zero_dvd H2) (take n, assume Hpos : n > 0, assume H1 : m | n, assume H2 : n | m, obtain k (Hk : m * k = n), from dvd.ex H1, obtain l (Hl : n * l = m), from dvd.ex H2, have H3 : n * (l * k) = n, from !mul.assoc β–Έ Hl⁻¹ β–Έ Hk, have H4 : l * k = 1, from eq_one_of_mul_eq_self_right Hpos H3, have H5 : k = 1, from eq_one_of_mul_eq_one_left H4, show m = n, from (mul_one m)⁻¹ ⬝ (H5 β–Έ Hk)) /- gcd and lcm -/ private definition pair_nat.lt : nat Γ— nat β†’ nat Γ— nat β†’ Prop := measure prβ‚‚ private definition pair_nat.lt.wf : well_founded pair_nat.lt := intro_k (measure.wf prβ‚‚) 20 -- we use intro_k to be able to execute gcd efficiently in the kernel local attribute pair_nat.lt.wf [instance] -- instance will not be saved in .olean local infixl `β‰Ί`:50 := pair_nat.lt private definition gcd.lt.dec (x y₁ : nat) : (succ y₁, x mod succ y₁) β‰Ί (x, succ y₁) := mod_lt (succ_pos y₁) definition gcd.F (p₁ : nat Γ— nat) : (Ξ  pβ‚‚ : nat Γ— nat, pβ‚‚ β‰Ί p₁ β†’ nat) β†’ nat := prod.cases_on p₁ (Ξ»x y, cases_on y (Ξ» f, x) (Ξ» y₁ (f : Ξ pβ‚‚, pβ‚‚ β‰Ί (x, succ y₁) β†’ nat), f (succ y₁, x mod succ y₁) !gcd.lt.dec)) definition gcd (x y : nat) := fix gcd.F (pair x y) theorem gcd_zero (x : nat) : gcd x 0 = x := well_founded.fix_eq gcd.F (x, 0) theorem gcd_succ (x y : nat) : gcd x (succ y) = gcd (succ y) (x mod succ y) := well_founded.fix_eq gcd.F (x, succ y) theorem gcd_one (n : β„•) : gcd n 1 = 1 := calc gcd n 1 = gcd 1 (n mod 1) : gcd_succ n zero ... = gcd 1 0 : mod_one ... = 1 : gcd_zero theorem gcd_def (x y : β„•) : gcd x y = if y = 0 then x else gcd y (x mod y) := cases_on y (calc gcd x 0 = x : gcd_zero x ... = if 0 = 0 then x else gcd zero (x mod zero) : (if_pos rfl)⁻¹) (Ξ»y₁, calc gcd x (succ y₁) = gcd (succ y₁) (x mod succ y₁) : gcd_succ x y₁ ... = if succ y₁ = 0 then x else gcd (succ y₁) (x mod succ y₁) : (if_neg (succ_ne_zero y₁))⁻¹) theorem gcd_rec (m : β„•) {n : β„•} (H : n > 0) : gcd m n = gcd n (m mod n) := gcd_def m n ⬝ if_neg (ne_zero_of_pos H) theorem gcd_self (n : β„•) : gcd n n = n := cases_on n rfl (Ξ»n₁, calc gcd (succ n₁) (succ n₁) = gcd (succ n₁) (succ n₁ mod succ n₁) : gcd_succ (succ n₁) n₁ ... = gcd (succ n₁) 0 : mod_self (succ n₁) ... = succ n₁ : gcd_zero) theorem gcd_zero_left (n : nat) : gcd 0 n = n := cases_on n rfl (Ξ» n₁, calc gcd 0 (succ n₁) = gcd (succ n₁) (0 mod succ n₁) : gcd_succ ... = gcd (succ n₁) 0 : zero_mod ... = (succ n₁) : gcd_zero) theorem gcd.induction {P : β„• β†’ β„• β†’ Prop} (m n : β„•) (H0 : βˆ€m, P m 0) (H1 : βˆ€m n, 0 < n β†’ P n (m mod n) β†’ P m n) : P m n := let Q : nat Γ— nat β†’ Prop := Ξ» p : nat Γ— nat, P (pr₁ p) (prβ‚‚ p) in have aux : Q (m, n), from well_founded.induction (m, n) (Ξ»p, prod.cases_on p (Ξ»m n, cases_on n (Ξ» ih, show P (pr₁ (m, 0)) (prβ‚‚ (m, 0)), from H0 m) (Ξ» n₁ (ih : βˆ€pβ‚‚, pβ‚‚ β‰Ί (m, succ n₁) β†’ P (pr₁ pβ‚‚) (prβ‚‚ pβ‚‚)), have hlt₁ : 0 < succ n₁, from succ_pos n₁, have hltβ‚‚ : (succ n₁, m mod succ n₁) β‰Ί (m, succ n₁), from gcd.lt.dec _ _, have hp : P (succ n₁) (m mod succ n₁), from ih _ hltβ‚‚, show P m (succ n₁), from H1 m (succ n₁) hlt₁ hp))), aux theorem gcd_dvd (m n : β„•) : (gcd m n | m) ∧ (gcd m n | n) := gcd.induction m n (take m, show (gcd m 0 | m) ∧ (gcd m 0 | 0), by simp) (take m n, assume npos : 0 < n, assume IH : (gcd n (m mod n) | n) ∧ (gcd n (m mod n) | (m mod n)), have H : gcd n (m mod n) | (m div n * n + m mod n), from dvd_add (dvd.trans (and.elim_left IH) !dvd_mul_left) (and.elim_right IH), have H1 : gcd n (m mod n) | m, from eq_div_mul_add_mod⁻¹ β–Έ H, have gcd_eq : gcd n (m mod n) = gcd m n, from (gcd_rec _ npos)⁻¹, show (gcd m n | m) ∧ (gcd m n | n), from gcd_eq β–Έ (and.intro H1 (and.elim_left IH))) theorem gcd_dvd_left (m n : β„•) : (gcd m n | m) := and.elim_left !gcd_dvd theorem gcd_dvd_right (m n : β„•) : (gcd m n | n) := and.elim_right !gcd_dvd theorem dvd_gcd {m n k : β„•} : k | m β†’ k | n β†’ k | (gcd m n) := gcd.induction m n (take m, assume (h₁ : k | m) (hβ‚‚ : k | 0), show k | gcd m 0, from !gcd_zero⁻¹ β–Έ h₁) (take m n, assume npos : n > 0, assume IH : k | n β†’ k | (m mod n) β†’ k | gcd n (m mod n), assume H1 : k | m, assume H2 : k | n, have H3 : k | m div n * n + m mod n, from eq_div_mul_add_mod β–Έ H1, have H4 : k | m mod n, from nat.dvd_of_dvd_add_left H3 (dvd.trans H2 (by simp)), have gcd_eq : gcd n (m mod n) = gcd m n, from (gcd_rec _ npos)⁻¹, show k | gcd m n, from gcd_eq β–Έ IH H2 H4) theorem gcd.comm (m n : β„•) : gcd m n = gcd n m := dvd.antisymm (dvd_gcd !gcd_dvd_right !gcd_dvd_left) (dvd_gcd !gcd_dvd_right !gcd_dvd_left) theorem gcd.assoc (m n k : β„•) : gcd (gcd m n) k = gcd m (gcd n k) := dvd.antisymm (dvd_gcd (dvd.trans !gcd_dvd_left !gcd_dvd_left) (dvd_gcd (dvd.trans !gcd_dvd_left !gcd_dvd_right) !gcd_dvd_right)) (dvd_gcd (dvd_gcd !gcd_dvd_left (dvd.trans !gcd_dvd_right !gcd_dvd_left)) (dvd.trans !gcd_dvd_right !gcd_dvd_right)) end nat
46ba294c5f91bf28585593701e4e35dfc9d8b013
b392eb79fb36952401156496daa60628ccb07438
/MathPort/Number.lean
aa317ac77764cd06452984fc7f0cf83edf96cc18
[ "Apache-2.0" ]
permissive
AurelienSaue/mathportsource
d9eabe74e3ab7774baa6a10a6dc8d4855ff92266
1a164e4fff7204c522c1f4ecc5024fd909be3b0b
refs/heads/master
1,685,214,377,305
1,623,621,223,000
1,623,621,223,000
364,191,042
0
0
null
null
null
null
UTF-8
Lean
false
false
1,868
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam These functions mimic the ones in lean3/src/library/num.cpp and must be called *before* translating the constants into Lean4. -/ import MathPort.Util import MathPort.Basic import MathPort.ActionItem import MathPort.Rules import MathPort.OldRecursor import Lean namespace MathPort open Lean partial def isConcreteNat? (e : Expr) : Option Nat := OptionM.run $ if e.isConstOf `Nat.zero then some 0 else if e.isAppOfArity `Nat.succ 1 then do let n ← isConcreteNat? e.appArg! some (n+1) else none structure NumInfo where number : Nat level : Level type : Expr hasZero? : Option Expr := none hasOne? : Option Expr := none hasAdd? : Option Expr := none partial def isNumber? (e : Expr) : Option NumInfo := do if e.isAppOfArity `Mathlib.HasZero.zero 2 then some { number := 0, level := e.getAppFn.constLevels!.head!, type := e.getArg! 0 hasZero? := e.getArg! 1 } else if e.isAppOfArity `Mathlib.HasOne.one 2 then some { number := 1, level := e.getAppFn.constLevels!.head!, type := e.getArg! 0, hasOne? := e.getArg! 1 } -- TODO: may need to check if these instances are def-eq -- (I am hoping that mathlib does not produce terms in which they are not) else if e.isAppOfArity `bit0 3 then OptionM.run $ do let info ← isNumber? $ e.getArg! 2 some { info with number := info.number * 2, hasAdd? := info.hasAdd? <|> e.getArg! 1 } else if e.isAppOfArity `bit1 4 then OptionM.run $ do let info ← isNumber? $ e.getArg! 2 some { info with number := info.number * 2 + 1, hasAdd? := info.hasAdd? <|> e.getArg! 2 } else none end MathPort
ec2aed196d5507eaab7ba4fb71ee3ee7ef0b5fe9
e61a235b8468b03aee0120bf26ec615c045005d2
/src/Init/Control/Reader.lean
887c71ee13c2e6a745ea4c2d4afec137a6aa0c21
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,365
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich The Reader monad transformer for passing immutable State. -/ prelude import Init.Control.Lift import Init.Control.Id import Init.Control.Alternative import Init.Control.Except universes u v w /-- 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 Ξ± @[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} [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 => do a ← x r; f a r @[inline] protected def map (f : Ξ± β†’ Ξ²) (x : ReaderT ρ m Ξ±) : ReaderT ρ m Ξ² := fun r => f <$> x r instance : Monad (ReaderT ρ m) := { pure := @ReaderT.pure _ _ _, bind := @ReaderT.bind _ _ _, map := @ReaderT.map _ _ _ } @[inline] protected def lift (a : m Ξ±) : ReaderT ρ m Ξ± := fun r => a instance (m) [Monad m] : HasMonadLift m (ReaderT ρ m) := ⟨@ReaderT.lift ρ m _⟩ instance (ρ m m') [Monad m] [Monad m'] : MonadFunctor m m' (ReaderT ρ 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) @[inline] protected def orelse [Alternative m] {Ξ± : Type u} (x₁ xβ‚‚ : ReaderT ρ m Ξ±) : ReaderT ρ m Ξ± := fun s => x₁ s <|> xβ‚‚ s @[inline] protected def failure [Alternative m] {Ξ± : Type u} : ReaderT ρ m Ξ± := fun s => failure instance [Alternative m] : Alternative (ReaderT ρ m) := { ReaderT.Monad with failure := @ReaderT.failure _ _ _ _, orelse := @ReaderT.orelse _ _ _ _ } instance (Ξ΅) [Monad m] [MonadExcept Ξ΅ m] : MonadExcept Ξ΅ (ReaderT ρ m) := { throw := fun Ξ± => ReaderT.lift ∘ throw, catch := fun Ξ± x c r => catch (x r) (fun e => (c e) 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 MonadReader (ρ : outParam (Type u)) (m : Type u β†’ Type v) := (read : m ρ) export MonadReader (read) instance monadReaderTrans {ρ : Type u} {m : Type u β†’ Type v} {n : Type u β†’ Type w} [MonadReader ρ m] [HasMonadLift m n] : MonadReader ρ n := ⟨monadLift (MonadReader.read : m ρ)⟩ instance {ρ : Type u} {m : Type u β†’ Type v} [Monad m] : MonadReader ρ (ReaderT ρ m) := ⟨ReaderT.read⟩ /-- Adapt a Monad stack, changing the Type of its top-most environment. This class is comparable to [Control.Lens.Magnify](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Magnify), but does not use lenses (why would it), and is derived automatically for any transformer implementing `MonadFunctor`. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReaderFunctor (ρ ρ' : outParam (Type u)) (n n' : Type u β†’ Type u) := (map {Ξ± : Type u} : (βˆ€ {m : Type u β†’ Type u} [Monad m], ReaderT ρ m Ξ± β†’ ReaderT ρ' m Ξ±) β†’ n Ξ± β†’ n' Ξ±) ``` -/ class MonadReaderAdapter (ρ ρ' : outParam (Type u)) (m m' : Type u β†’ Type v) := (adaptReader {Ξ± : Type u} : (ρ' β†’ ρ) β†’ m Ξ± β†’ m' Ξ±) export MonadReaderAdapter (adaptReader) section variables {ρ ρ' : Type u} {m m' : Type u β†’ Type v} instance monadReaderAdapterTrans {n n' : Type u β†’ Type v} [MonadReaderAdapter ρ ρ' m m'] [MonadFunctor m m' n n'] : MonadReaderAdapter ρ ρ' n n' := ⟨fun Ξ± f => monadMap (fun Ξ± => (adaptReader f : m Ξ± β†’ m' Ξ±))⟩ instance [Monad m] : MonadReaderAdapter ρ ρ' (ReaderT ρ m) (ReaderT ρ' m) := ⟨fun Ξ± => ReaderT.adapt⟩ end instance (ρ : Type u) (m out) [MonadRun out m] : MonadRun (fun Ξ± => ρ β†’ out Ξ±) (ReaderT ρ m) := ⟨fun Ξ± x => run ∘ x⟩ class MonadReaderRunner (ρ : Type u) (m m' : Type u β†’ Type u) := (runReader {Ξ± : Type u} : m Ξ± β†’ ρ β†’ m' Ξ±) export MonadReaderRunner (runReader) section variables {ρ ρ' : Type u} {m m' : Type u β†’ Type u} instance monadReaderRunnerTrans {n n' : Type u β†’ Type u} [MonadReaderRunner ρ m m'] [MonadFunctor m m' n n'] : MonadReaderRunner ρ n n' := ⟨fun Ξ± x r => monadMap (fun (Ξ±) (y : m Ξ±) => (runReader y r : m' Ξ±)) x⟩ instance ReaderT.MonadStateRunner [Monad m] : MonadReaderRunner ρ (ReaderT ρ m) m := ⟨fun Ξ± x r => x r⟩ end
710d0bdd251bdb1f5875436e0a1ef8e59362fb46
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/convex/specific_functions.lean
a6a8429d91153ac9ed136940811acbeca6123671
[ "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
13,119
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, SΓ©bastien GouΓ«zel -/ import analysis.calculus.mean_value import analysis.special_functions.pow_deriv import analysis.special_functions.sqrt /-! # Collection of convex functions In this file we prove that the following functions are convex: * `strict_convex_on_exp` : The exponential function is strictly convex. * `even.convex_on_pow`, `even.strict_convex_on_pow` : For an even `n : β„•`, `Ξ» x, x ^ n` is convex and strictly convex when `2 ≀ n`. * `convex_on_pow`, `strict_convex_on_pow` : For `n : β„•`, `Ξ» x, x ^ n` is convex on $[0, +∞)$ and strictly convex when `2 ≀ n`. * `convex_on_zpow`, `strict_convex_on_zpow` : For `m : β„€`, `Ξ» x, x ^ m` is convex on $[0, +∞)$ and strictly convex when `m β‰  0, 1`. * `convex_on_rpow`, `strict_convex_on_rpow` : For `p : ℝ`, `Ξ» x, x ^ p` is convex on $[0, +∞)$ when `1 ≀ p` and strictly convex when `1 < p`. * `strict_concave_on_log_Ioi`, `strict_concave_on_log_Iio`: `real.log` is strictly concave on $(0, +∞)$ and $(-∞, 0)$ respectively. ## TODO For `p : ℝ`, prove that `Ξ» x, x ^ p` is concave when `0 ≀ p ≀ 1` and strictly concave when `0 < p < 1`. -/ open real set open_locale big_operators nnreal /-- `exp` is strictly convex on the whole real line. -/ lemma strict_convex_on_exp : strict_convex_on ℝ univ exp := strict_convex_on_univ_of_deriv2_pos continuous_exp (Ξ» x, (iter_deriv_exp 2).symm β–Έ exp_pos x) /-- `exp` is convex on the whole real line. -/ lemma convex_on_exp : convex_on ℝ univ exp := strict_convex_on_exp.convex_on /-- `x^n`, `n : β„•` is convex on the whole real line whenever `n` is even -/ lemma even.convex_on_pow {n : β„•} (hn : even n) : convex_on ℝ set.univ (Ξ» x : ℝ, x^n) := begin apply convex_on_univ_of_deriv2_nonneg (differentiable_pow n), { simp only [deriv_pow', differentiable.mul, differentiable_const, differentiable_pow] }, { intro x, obtain ⟨k, hk⟩ := (hn.tsub $ even_bit0 _).exists_two_nsmul _, rw [iter_deriv_pow, finset.prod_range_cast_nat_sub, hk, nsmul_eq_mul, pow_mul'], exact mul_nonneg (nat.cast_nonneg _) (pow_two_nonneg _) } end /-- `x^n`, `n : β„•` is strictly convex on the whole real line whenever `n β‰  0` is even. -/ lemma even.strict_convex_on_pow {n : β„•} (hn : even n) (h : n β‰  0) : strict_convex_on ℝ set.univ (Ξ» x : ℝ, x^n) := begin apply strict_mono.strict_convex_on_univ_of_deriv (continuous_pow n), rw deriv_pow', replace h := nat.pos_of_ne_zero h, exact strict_mono.const_mul (odd.strict_mono_pow $ nat.even.sub_odd h hn $ nat.odd_iff.2 rfl) (nat.cast_pos.2 h), end /-- `x^n`, `n : β„•` is convex on `[0, +∞)` for all `n` -/ lemma convex_on_pow (n : β„•) : convex_on ℝ (Ici 0) (Ξ» x : ℝ, x^n) := begin apply convex_on_of_deriv2_nonneg (convex_Ici _) (continuous_pow n).continuous_on (differentiable_on_pow n), { simp only [deriv_pow'], exact (@differentiable_on_pow ℝ _ _ _).const_mul (n : ℝ) }, { intros x hx, rw [iter_deriv_pow, finset.prod_range_cast_nat_sub], exact mul_nonneg (nat.cast_nonneg _) (pow_nonneg (interior_subset hx) _) } end /-- `x^n`, `n : β„•` is strictly convex on `[0, +∞)` for all `n` greater than `2`. -/ lemma strict_convex_on_pow {n : β„•} (hn : 2 ≀ n) : strict_convex_on ℝ (Ici 0) (Ξ» x : ℝ, x^n) := begin apply strict_mono_on.strict_convex_on_of_deriv (convex_Ici _) (continuous_on_pow _), rw [deriv_pow', interior_Ici], exact Ξ» x (hx : 0 < x) y hy hxy, mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_left hxy hx.le $ nat.sub_pos_of_lt hn) (nat.cast_pos.2 $ zero_lt_two.trans_le hn), end /-- Specific case of Jensen's inequality for sums of powers -/ lemma real.pow_sum_div_card_le_sum_pow {Ξ± : Type*} {s : finset Ξ±} {f : Ξ± β†’ ℝ} (n : β„•) (hf : βˆ€ a ∈ s, 0 ≀ f a) : (βˆ‘ x in s, f x) ^ (n + 1) / s.card ^ n ≀ βˆ‘ x in s, (f x) ^ (n + 1) := begin rcases s.eq_empty_or_nonempty with rfl | hs, { simp_rw [finset.sum_empty, zero_pow' _ (nat.succ_ne_zero n), zero_div] }, { have hs0 : 0 < (s.card : ℝ) := nat.cast_pos.2 hs.card_pos, suffices : (βˆ‘ x in s, f x / s.card) ^ (n + 1) ≀ βˆ‘ x in s, (f x ^ (n + 1) / s.card), { rwa [← finset.sum_div, ← finset.sum_div, div_pow, pow_succ' (s.card : ℝ), ← div_div, div_le_iff hs0, div_mul, div_self hs0.ne', div_one] at this }, have := @convex_on.map_sum_le ℝ ℝ ℝ Ξ± _ _ _ _ _ _ (set.Ici 0) (Ξ» x, x ^ (n + 1)) s (Ξ» _, 1 / s.card) (coe ∘ f) (convex_on_pow (n + 1)) _ _ (Ξ» i hi, set.mem_Ici.2 (hf i hi)), { simpa only [inv_mul_eq_div, one_div, algebra.id.smul_eq_mul] using this }, { simp only [one_div, inv_nonneg, nat.cast_nonneg, implies_true_iff] }, { simpa only [one_div, finset.sum_const, nsmul_eq_mul] using mul_inv_cancel hs0.ne' } } end lemma nnreal.pow_sum_div_card_le_sum_pow {Ξ± : Type*} (s : finset Ξ±) (f : Ξ± β†’ ℝβ‰₯0) (n : β„•) : (βˆ‘ x in s, f x) ^ (n + 1) / s.card ^ n ≀ βˆ‘ x in s, (f x) ^ (n + 1) := by simpa only [← nnreal.coe_le_coe, nnreal.coe_sum, nonneg.coe_div, nnreal.coe_pow] using @real.pow_sum_div_card_le_sum_pow Ξ± s (coe ∘ f) n (Ξ» _ _, nnreal.coe_nonneg _) lemma finset.prod_nonneg_of_card_nonpos_even {Ξ± Ξ² : Type*} [linear_ordered_comm_ring Ξ²] {f : Ξ± β†’ Ξ²} [decidable_pred (Ξ» x, f x ≀ 0)] {s : finset Ξ±} (h0 : even (s.filter (Ξ» x, f x ≀ 0)).card) : 0 ≀ ∏ x in s, f x := calc 0 ≀ (∏ x in s, ((if f x ≀ 0 then (-1:Ξ²) else 1) * f x)) : finset.prod_nonneg (Ξ» x _, by { split_ifs with hx hx, by simp [hx], simp at hx ⊒, exact le_of_lt hx }) ... = _ : by rw [finset.prod_mul_distrib, finset.prod_ite, finset.prod_const_one, mul_one, finset.prod_const, neg_one_pow_eq_pow_mod_two, nat.even_iff.1 h0, pow_zero, one_mul] lemma int_prod_range_nonneg (m : β„€) (n : β„•) (hn : even n) : 0 ≀ ∏ k in finset.range n, (m - k) := begin rcases hn with ⟨n, rfl⟩, induction n with n ihn, { simp }, rw ← two_mul at ihn, rw [← two_mul, nat.succ_eq_add_one, mul_add, mul_one, bit0, ← add_assoc, finset.prod_range_succ, finset.prod_range_succ, mul_assoc], refine mul_nonneg ihn _, generalize : (1 + 1) * n = k, cases le_or_lt m k with hmk hmk, { have : m ≀ k + 1, from hmk.trans (lt_add_one ↑k).le, convert mul_nonneg_of_nonpos_of_nonpos (sub_nonpos_of_le hmk) _, convert sub_nonpos_of_le this }, { exact mul_nonneg (sub_nonneg_of_le hmk.le) (sub_nonneg_of_le hmk) } end lemma int_prod_range_pos {m : β„€} {n : β„•} (hn : even n) (hm : m βˆ‰ Ico (0 : β„€) n) : 0 < ∏ k in finset.range n, (m - k) := begin refine (int_prod_range_nonneg m n hn).lt_of_ne (Ξ» h, hm _), rw [eq_comm, finset.prod_eq_zero_iff] at h, obtain ⟨a, ha, h⟩ := h, rw sub_eq_zero.1 h, exact ⟨int.coe_zero_le _, int.coe_nat_lt.2 $ finset.mem_range.1 ha⟩, end /-- `x^m`, `m : β„€` is convex on `(0, +∞)` for all `m` -/ lemma convex_on_zpow (m : β„€) : convex_on ℝ (Ioi 0) (Ξ» x : ℝ, x^m) := begin have : βˆ€ n : β„€, differentiable_on ℝ (Ξ» x, x ^ n) (Ioi (0 : ℝ)), from Ξ» n, differentiable_on_zpow _ _ (or.inl $ lt_irrefl _), apply convex_on_of_deriv2_nonneg (convex_Ioi 0); try { simp only [interior_Ioi, deriv_zpow'] }, { exact (this _).continuous_on }, { exact this _ }, { exact (this _).const_mul _ }, { intros x hx, rw iter_deriv_zpow, refine mul_nonneg _ (zpow_nonneg (le_of_lt hx) _), exact_mod_cast int_prod_range_nonneg _ _ (even_bit0 1) } end /-- `x^m`, `m : β„€` is convex on `(0, +∞)` for all `m` except `0` and `1`. -/ lemma strict_convex_on_zpow {m : β„€} (hmβ‚€ : m β‰  0) (hm₁ : m β‰  1) : strict_convex_on ℝ (Ioi 0) (Ξ» x : ℝ, x^m) := begin apply strict_convex_on_of_deriv2_pos' (convex_Ioi 0), { exact (continuous_on_zpowβ‚€ m).mono (Ξ» x hx, ne_of_gt hx) }, intros x hx, rw iter_deriv_zpow, refine mul_pos _ (zpow_pos_of_pos hx _), exact_mod_cast int_prod_range_pos (even_bit0 1) (Ξ» hm, _), norm_cast at hm, rw ← finset.coe_Ico at hm, fin_cases hm; cc, end lemma convex_on_rpow {p : ℝ} (hp : 1 ≀ p) : convex_on ℝ (Ici 0) (Ξ» x : ℝ, x^p) := begin have A : deriv (Ξ» (x : ℝ), x ^ p) = Ξ» x, p * x^(p-1), by { ext x, simp [hp] }, apply convex_on_of_deriv2_nonneg (convex_Ici 0), { exact continuous_on_id.rpow_const (Ξ» x _, or.inr (zero_le_one.trans hp)) }, { exact (differentiable_rpow_const hp).differentiable_on }, { rw A, assume x hx, replace hx : x β‰  0, by { simp at hx, exact ne_of_gt hx }, simp [differentiable_at.differentiable_within_at, hx] }, { assume x hx, replace hx : 0 < x, by simpa using hx, suffices : 0 ≀ p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A], apply mul_nonneg (le_trans zero_le_one hp), exact mul_nonneg (sub_nonneg_of_le hp) (rpow_nonneg_of_nonneg hx.le _) } end lemma strict_convex_on_rpow {p : ℝ} (hp : 1 < p) : strict_convex_on ℝ (Ici 0) (Ξ» x : ℝ, x^p) := begin have A : deriv (Ξ» (x : ℝ), x ^ p) = Ξ» x, p * x^(p-1), by { ext x, simp [hp.le] }, apply strict_convex_on_of_deriv2_pos (convex_Ici 0), { exact continuous_on_id.rpow_const (Ξ» x _, or.inr (zero_le_one.trans hp.le)) }, rw interior_Ici, rintro x (hx : 0 < x), suffices : 0 < p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A], exact mul_pos (zero_lt_one.trans hp) (mul_pos (sub_pos_of_lt hp) (rpow_pos_of_pos hx _)), end lemma strict_concave_on_log_Ioi : strict_concave_on ℝ (Ioi 0) log := begin have h₁ : Ioi 0 βŠ† ({0} : set ℝ)ᢜ, { exact Ξ» x (hx : 0 < x) (hx' : x = 0), hx.ne' hx' }, refine strict_concave_on_of_deriv2_neg' (convex_Ioi 0) (continuous_on_log.mono h₁) (Ξ» x (hx : 0 < x), _), rw [function.iterate_succ, function.iterate_one], change (deriv (deriv log)) x < 0, rw [deriv_log', deriv_inv], exact neg_neg_of_pos (inv_pos.2 $ sq_pos_of_ne_zero _ hx.ne'), end lemma strict_concave_on_log_Iio : strict_concave_on ℝ (Iio 0) log := begin have h₁ : Iio 0 βŠ† ({0} : set ℝ)ᢜ, { exact Ξ» x (hx : x < 0) (hx' : x = 0), hx.ne hx' }, refine strict_concave_on_of_deriv2_neg' (convex_Iio 0) (continuous_on_log.mono h₁) (Ξ» x (hx : x < 0), _), rw [function.iterate_succ, function.iterate_one], change (deriv (deriv log)) x < 0, rw [deriv_log', deriv_inv], exact neg_neg_of_pos (inv_pos.2 $ sq_pos_of_ne_zero _ hx.ne), end section sqrt_mul_log lemma has_deriv_at_sqrt_mul_log {x : ℝ} (hx : x β‰  0) : has_deriv_at (Ξ» x, sqrt x * log x) ((2 + log x) / (2 * sqrt x)) x := begin convert (has_deriv_at_sqrt hx).mul (has_deriv_at_log hx), rw [add_div, div_mul_right (sqrt x) two_ne_zero, ←div_eq_mul_inv, sqrt_div_self', add_comm, div_eq_mul_one_div, mul_comm], end lemma deriv_sqrt_mul_log (x : ℝ) : deriv (Ξ» x, sqrt x * log x) x = (2 + log x) / (2 * sqrt x) := begin cases lt_or_le 0 x with hx hx, { exact (has_deriv_at_sqrt_mul_log hx.ne').deriv }, { rw [sqrt_eq_zero_of_nonpos hx, mul_zero, div_zero], refine has_deriv_within_at.deriv_eq_zero _ (unique_diff_on_Iic 0 x hx), refine (has_deriv_within_at_const x _ 0).congr_of_mem (Ξ» x hx, _) hx, rw [sqrt_eq_zero_of_nonpos hx, zero_mul] }, end lemma deriv_sqrt_mul_log' : deriv (Ξ» x, sqrt x * log x) = Ξ» x, (2 + log x) / (2 * sqrt x) := funext deriv_sqrt_mul_log lemma deriv2_sqrt_mul_log (x : ℝ) : deriv^[2] (Ξ» x, sqrt x * log x) x = -log x / (4 * sqrt x ^ 3) := begin simp only [nat.iterate, deriv_sqrt_mul_log'], cases le_or_lt x 0 with hx hx, { rw [sqrt_eq_zero_of_nonpos hx, zero_pow zero_lt_three, mul_zero, div_zero], refine has_deriv_within_at.deriv_eq_zero _ (unique_diff_on_Iic 0 x hx), refine (has_deriv_within_at_const _ _ 0).congr_of_mem (Ξ» x hx, _) hx, rw [sqrt_eq_zero_of_nonpos hx, mul_zero, div_zero] }, { have hβ‚€ : sqrt x β‰  0, from sqrt_ne_zero'.2 hx, convert (((has_deriv_at_log hx.ne').const_add 2).div ((has_deriv_at_sqrt hx.ne').const_mul 2) $ mul_ne_zero two_ne_zero hβ‚€).deriv using 1, nth_rewrite 2 [← mul_self_sqrt hx.le], field_simp, ring }, end lemma strict_concave_on_sqrt_mul_log_Ioi : strict_concave_on ℝ (set.Ioi 1) (Ξ» x, sqrt x * log x) := begin apply strict_concave_on_of_deriv2_neg' (convex_Ioi 1) _ (Ξ» x hx, _), { exact continuous_sqrt.continuous_on.mul (continuous_on_log.mono (Ξ» x hx, ne_of_gt (zero_lt_one.trans hx))) }, { rw [deriv2_sqrt_mul_log x], exact div_neg_of_neg_of_pos (neg_neg_of_pos (log_pos hx)) (mul_pos four_pos (pow_pos (sqrt_pos.mpr (zero_lt_one.trans hx)) 3)) }, end end sqrt_mul_log open_locale real lemma strict_concave_on_sin_Icc : strict_concave_on ℝ (Icc 0 Ο€) sin := begin apply strict_concave_on_of_deriv2_neg (convex_Icc _ _) continuous_on_sin (Ξ» x hx, _), rw interior_Icc at hx, simp [sin_pos_of_mem_Ioo hx], end lemma strict_concave_on_cos_Icc : strict_concave_on ℝ (Icc (-(Ο€/2)) (Ο€/2)) cos := begin apply strict_concave_on_of_deriv2_neg (convex_Icc _ _) continuous_on_cos (Ξ» x hx, _), rw interior_Icc at hx, simp [cos_pos_of_mem_Ioo hx], end
0d7748258d1dbb64c41cd209987ce5ba1759f0be
7541ac8517945d0f903ff5397e13e2ccd7c10573
/src/category_theory/iso_induction.lean
63fe838861950b4fcebcd44202cac619e32e3ce4
[]
no_license
ramonfmir/lean-category-theory
29b6bad9f62c2cdf7517a3135e5a12b340b4ed90
be516bcbc2dc21b99df2bcb8dde0d1e8de79c9ad
refs/heads/master
1,586,110,684,637
1,541,927,184,000
1,541,927,184,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,503
lean
import category_theory.isomorphism import category_theory.types universes u v def isos (C : Type u) := C open category_theory instance category_isos {C : Type u} [category.{u v} C] : category (isos C) := { hom := Ξ» X Y, @iso C _ X Y, id := iso.refl, comp := Ξ» X Y Z, iso.trans } instance category_isos_type : large_category (isos (Type u)) := by apply_instance @[extensionality] lemma monoid.ext {Ξ± : Type u} (m n : monoid Ξ±) (mul : βˆ€ x y : Ξ±, (by haveI := m; exact x * y) = (by haveI := n; exact x * y)) : m = n := begin tactic.unfreeze_local_instances, induction m, induction n, congr, { ext x y, exact mul x y }, { dsimp at *, rw ← n_one_mul m_one, rw ← mul, erw m_mul_one n_one }, end def monoid_type_constructor : isos (Type u) β₯€ Type u := { obj := monoid, map := Ξ» Ξ± Ξ² f m, { one := f.hom (by resetI; exact 1), mul := Ξ» x y, begin resetI, exact f.hom (f.inv x * f.inv y) end, one_mul := sorry, mul_one := sorry, mul_assoc := sorry }, } def monoid_type_constructor_indirection (Ξ± : Type u) : monoid Ξ± = monoid_type_constructor.obj Ξ± := rfl def monoid_transport {Ξ± Ξ² : Type u} (f : Ξ± β‰… Ξ²) (m : monoid Ξ±) : monoid Ξ² := begin -- iso_induction f, -- -- This tactic doesn't exist yet, but 'just' needs to do: rw monoid_type_constructor_indirection Ξ± at m, replace m := monoid_type_constructor.map f m, rw ← monoid_type_constructor_indirection Ξ² at m, clear f, clear Ξ±, exact m, end
f3b3eda92aad02c8bd871bb552bcfc5b0a7fcd5c
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep1/equiv.lean
b6baf84cdc61a54d67a2cb14607f7f520cfde118
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
293
lean
import linear_algebra.basic import algebra.module variables (M : Type )(R :Type) [ring R] [add_comm_group M] [add_comm_group M] [module R M] variables (f g : M→ₗ[R]M) example : f * g = linear_map.id := sorry #check (by apply_instance : has_mul (M→ₗ[R]M )) linear_map.has_scalar
5f43f5035565fb90803e33fe18ecf93848653f3f
26ac254ecb57ffcb886ff709cf018390161a9225
/src/data/equiv/ring.lean
d19f6b4785407c6bf2ed0d9055227a3c2fff13e3
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
10,235
lean
/- Copyright (c) 2018 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl, Callum Sutton, Yury Kudryashov -/ import data.equiv.mul_add import algebra.field import algebra.opposites import deprecated.ring /-! # (Semi)ring equivs In this file we define extension of `equiv` called `ring_equiv`, which is a datatype representing an isomorphism of `semiring`s, `ring`s, `division_ring`s, or `field`s. We also introduce the corresponding group of automorphisms `ring_aut`. ## Notations The extended equiv have coercions to functions, and the coercion is the canonical notation when treating the isomorphism as maps. ## Implementation notes The fields for `ring_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. Definition of multiplication in the groups of automorphisms agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with `category_theory.comp`. ## Tags equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut -/ variables {R : Type*} {S : Type*} {S' : Type*} set_option old_structure_cmd true /- (semi)ring equivalence. -/ structure ring_equiv (R S : Type*) [has_mul R] [has_add R] [has_mul S] [has_add S] extends R ≃ S, R ≃* S, R ≃+ S infix ` ≃+* `:25 := ring_equiv namespace ring_equiv section basic variables [has_mul R] [has_add R] [has_mul S] [has_add S] [has_mul S'] [has_add S'] instance : has_coe_to_fun (R ≃+* S) := ⟨_, ring_equiv.to_fun⟩ @[simp] lemma to_fun_eq_coe_fun (f : R ≃+* S) : f.to_fun = f := rfl instance has_coe_to_mul_equiv : has_coe (R ≃+* S) (R ≃* S) := ⟨ring_equiv.to_mul_equiv⟩ instance has_coe_to_add_equiv : has_coe (R ≃+* S) (R ≃+ S) := ⟨ring_equiv.to_add_equiv⟩ @[norm_cast] lemma coe_mul_equiv (f : R ≃+* S) (a : R) : (f : R ≃* S) a = f a := rfl @[norm_cast] lemma coe_add_equiv (f : R ≃+* S) (a : R) : (f : R ≃+ S) a = f a := rfl variable (R) /-- The identity map is a ring isomorphism. -/ @[refl] protected def refl : R ≃+* R := { .. mul_equiv.refl R, .. add_equiv.refl R } @[simp] lemma refl_apply (x : R) : ring_equiv.refl R x = x := rfl @[simp] lemma coe_add_equiv_refl : (ring_equiv.refl R : R ≃+ R) = add_equiv.refl R := rfl @[simp] lemma coe_mul_equiv_refl : (ring_equiv.refl R : R ≃* R) = mul_equiv.refl R := rfl variables {R} /-- The inverse of a ring isomorphism is a ring isomorphism. -/ @[symm] protected def symm (e : R ≃+* S) : S ≃+* R := { .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm } /-- Transitivity of `ring_equiv`. -/ @[trans] protected def trans (e₁ : R ≃+* S) (eβ‚‚ : S ≃+* S') : R ≃+* S' := { .. (e₁.to_mul_equiv.trans eβ‚‚.to_mul_equiv), .. (e₁.to_add_equiv.trans eβ‚‚.to_add_equiv) } protected lemma bijective (e : R ≃+* S) : function.bijective e := e.to_equiv.bijective protected lemma injective (e : R ≃+* S) : function.injective e := e.to_equiv.injective protected lemma surjective (e : R ≃+* S) : function.surjective e := e.to_equiv.surjective @[simp] lemma apply_symm_apply (e : R ≃+* S) : βˆ€ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : R ≃+* S) : βˆ€ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply lemma image_eq_preimage (e : R ≃+* S) (s : set R) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end basic section comm_semiring open opposite variables (R) [comm_semiring R] /-- A commutative ring is isomorphic to its opposite. -/ def to_opposite : R ≃+* Rα΅’α΅– := { map_add' := Ξ» x y, rfl, map_mul' := Ξ» x y, mul_comm (op y) (op x), ..equiv_to_opposite } @[simp] lemma to_opposite_apply (r : R) : to_opposite R r = op r := rfl @[simp] lemma to_opposite_symm_apply (r : Rα΅’α΅–) : (to_opposite R).symm r = unop r := rfl end comm_semiring section variables [semiring R] [semiring S] (f : R ≃+* S) (x y : R) /-- A ring isomorphism preserves multiplication. -/ @[simp] lemma map_mul : f (x * y) = f x * f y := f.map_mul' x y /-- A ring isomorphism sends one to one. -/ @[simp] lemma map_one : f 1 = 1 := (f : R ≃* S).map_one /-- A ring isomorphism preserves addition. -/ @[simp] lemma map_add : f (x + y) = f x + f y := f.map_add' x y /-- A ring isomorphism sends zero to zero. -/ @[simp] lemma map_zero : f 0 = 0 := (f : R ≃+ S).map_zero variable {x} @[simp] lemma map_eq_one_iff : f x = 1 ↔ x = 1 := (f : R ≃* S).map_eq_one_iff @[simp] lemma map_eq_zero_iff : f x = 0 ↔ x = 0 := (f : R ≃+ S).map_eq_zero_iff lemma map_ne_one_iff : f x β‰  1 ↔ x β‰  1 := (f : R ≃* S).map_ne_one_iff lemma map_ne_zero_iff : f x β‰  0 ↔ x β‰  0 := (f : R ≃+ S).map_ne_zero_iff end section variables [ring R] [ring S] (f : R ≃+* S) (x y : R) @[simp] lemma map_neg : f (-x) = -f x := (f : R ≃+ S).map_neg x @[simp] lemma map_sub : f (x - y) = f x - f y := (f : R ≃+ S).map_sub x y @[simp] lemma map_neg_one : f (-1) = -1 := f.map_one β–Έ f.map_neg 1 end section semiring_hom variables [semiring R] [semiring S] /-- Reinterpret a ring equivalence as a ring homomorphism. -/ def to_ring_hom (e : R ≃+* S) : R β†’+* S := { .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom } /-- Reinterpret a ring equivalence as a monoid homomorphism. -/ abbreviation to_monoid_hom (e : R ≃+* S) : R β†’* S := e.to_ring_hom.to_monoid_hom /-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/ abbreviation to_add_monoid_hom (e : R ≃+* S) : R β†’+ S := e.to_ring_hom.to_add_monoid_hom /-- Interpret an equivalence `f : R ≃ S` as a ring equivalence `R ≃+* S`. -/ def of (e : R ≃ S) [is_semiring_hom e] : R ≃+* S := { .. e, .. monoid_hom.of e, .. add_monoid_hom.of e } instance (e : R ≃+* S) : is_semiring_hom e := e.to_ring_hom.is_semiring_hom @[simp] lemma to_ring_hom_refl : (ring_equiv.refl R).to_ring_hom = ring_hom.id R := rfl @[simp] lemma to_monoid_hom_refl : (ring_equiv.refl R).to_monoid_hom = monoid_hom.id R := rfl @[simp] lemma to_add_monoid_hom_refl : (ring_equiv.refl R).to_add_monoid_hom = add_monoid_hom.id R := rfl @[simp] lemma to_ring_hom_apply_symm_to_ring_hom_apply {R S} [semiring R] [semiring S] (e : R ≃+* S) : βˆ€ (y : S), e.to_ring_hom (e.symm.to_ring_hom y) = y := e.to_equiv.apply_symm_apply @[simp] lemma symm_to_ring_hom_apply_to_ring_hom_apply {R S} [semiring R] [semiring S] (e : R ≃+* S) : βˆ€ (x : R), e.symm.to_ring_hom (e.to_ring_hom x) = x := equiv.symm_apply_apply (e.to_equiv) end semiring_hom end ring_equiv namespace mul_equiv /-- Gives a `ring_equiv` from a `mul_equiv` preserving addition.-/ def to_ring_equiv {R : Type*} {S : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S] (h : R ≃* S) (H : βˆ€ x y : R, h (x + y) = h x + h y) : R ≃+* S := {..h.to_equiv, ..h, ..add_equiv.mk' h.to_equiv H } end mul_equiv namespace ring_equiv section ring_hom variables [ring R] [ring S] /-- Interpret an equivalence `f : R ≃ S` as a ring equivalence `R ≃+* S`. -/ def of' (e : R ≃ S) [is_ring_hom e] : R ≃+* S := { .. e, .. monoid_hom.of e, .. add_monoid_hom.of e } instance (e : R ≃+* S) : is_ring_hom e := e.to_ring_hom.is_ring_hom end ring_hom /-- Two ring isomorphisms agree if they are defined by the same underlying function. -/ @[ext] lemma ext {R S : Type*} [has_mul R] [has_add R] [has_mul S] [has_add S] {f g : R ≃+* S} (h : βˆ€ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected lemma is_integral_domain {A : Type*} (B : Type*) [ring A] [ring B] (hB : is_integral_domain B) (e : A ≃+* B) : is_integral_domain A := { mul_comm := Ξ» x y, have e.symm (e x * e y) = e.symm (e y * e x), by rw hB.mul_comm, by simpa, eq_zero_or_eq_zero_of_mul_eq_zero := Ξ» x y hxy, have e x * e y = 0, by rw [← e.map_mul, hxy, e.map_zero], (hB.eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).imp (Ξ» hx, by simpa using congr_arg e.symm hx) (Ξ» hy, by simpa using congr_arg e.symm hy), exists_pair_ne := ⟨e.symm 0, e.symm 1, by { haveI : nontrivial B := hB.to_nontrivial, exact e.symm.injective.ne zero_ne_one }⟩ } /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected def integral_domain {A : Type*} (B : Type*) [ring A] [integral_domain B] (e : A ≃+* B) : integral_domain A := { .. (β€Ή_β€Ί : ring A), .. e.is_integral_domain B (integral_domain.to_is_integral_domain B) } end ring_equiv /-- The group of ring automorphisms. -/ @[reducible] def ring_aut (R : Type*) [has_mul R] [has_add R] := ring_equiv R R namespace ring_aut variables (R) [has_mul R] [has_add R] /-- The group operation on automorphisms of a ring is defined by Ξ» g h, ring_equiv.trans h g. This means that multiplication agrees with composition, (g*h)(x) = g (h x) . -/ instance : group (ring_aut R) := by refine_struct { mul := Ξ» g h, ring_equiv.trans h g, one := ring_equiv.refl R, inv := ring_equiv.symm }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (ring_aut R) := ⟨1⟩ /-- Monoid homomorphism from ring automorphisms to additive automorphisms. -/ def to_add_aut : ring_aut R β†’* add_aut R := by refine_struct { to_fun := ring_equiv.to_add_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to multiplicative automorphisms. -/ def to_mul_aut : ring_aut R β†’* mul_aut R := by refine_struct { to_fun := ring_equiv.to_mul_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to permutations. -/ def to_perm : ring_aut R β†’* equiv.perm R := by refine_struct { to_fun := ring_equiv.to_equiv }; intros; refl end ring_aut namespace equiv variables (K : Type*) [division_ring K] def units_equiv_ne_zero : units K ≃ {a : K | a β‰  0} := ⟨λ a, ⟨a.1, a.coe_ne_zero⟩, Ξ» a, units.mk0 _ a.2, Ξ» ⟨_, _, _, _⟩, units.ext rfl, Ξ» ⟨_, _⟩, rfl⟩ variable {K} @[simp] lemma coe_units_equiv_ne_zero (a : units K) : ((units_equiv_ne_zero K a) : K) = a := rfl end equiv
67417b65760f4b7a57fda876f3794b7279862c16
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/ParserCompiler.lean
4a792d78481e6206f2ea366b4ffcd7e021cc83b0
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,073
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ /-! Gadgets for compiling parser declarations into other programs, such as pretty printers. -/ import Lean.Util.ReplaceExpr import Lean.Meta.Basic import Lean.Meta.WHNF import Lean.ParserCompiler.Attribute import Lean.Parser.Extension namespace Lean namespace ParserCompiler structure Context (Ξ± : Type) := (varName : Name) (runtimeAttr : KeyedDeclsAttribute Ξ±) (combinatorAttr : CombinatorAttribute) (interpretParserDescr : ParserDescr β†’ AttrM Ξ±) def Context.tyName {Ξ±} (ctx : Context Ξ±) : Name := ctx.runtimeAttr.defn.valueTypeName -- replace all references of `Parser` with `tyName` as a first approximation def preprocessParserBody {Ξ±} (ctx : Context Ξ±) (e : Expr) : Expr := e.replace fun e => if e.isConstOf `Lean.Parser.Parser then mkConst ctx.tyName else none section open Meta -- translate an expression of type `Parser` into one of type `tyName` partial def compileParserBody {Ξ±} (ctx : Context Ξ±) : Expr β†’ MetaM Expr | e => do e ← whnfCore e; match e with | e@(Expr.lam _ _ _ _) => lambdaLetTelescope e fun xs b => compileParserBody b >>= mkLambdaFVars xs | e@(Expr.fvar _ _) => pure e | _ => do let fn := e.getAppFn; Expr.const c _ _ ← pure fn | throwError $ "call of unknown parser at '" ++ toString e ++ "'"; let args := e.getAppArgs; -- call the translated `p` with (a prefix of) the arguments of `e`, recursing for arguments -- of type `ty` (i.e. formerly `Parser`) let mkCall (p : Name) := do { ty ← inferType (mkConst p); forallTelescope ty fun params _ => params.foldlMβ‚‚ (fun p param arg => do paramTy ← inferType param; resultTy ← forallTelescope paramTy fun _ b => pure b; arg ← if resultTy.isConstOf ctx.tyName then compileParserBody arg else pure arg; pure $ mkApp p arg) (mkConst p) e.getAppArgs }; env ← getEnv; match ctx.combinatorAttr.getDeclFor env c with | some p => mkCall p | none => do let c' := c ++ ctx.varName; cinfo ← getConstInfo c; resultTy ← forallTelescope cinfo.type fun _ b => pure b; if resultTy.isConstOf `Lean.Parser.TrailingParser || resultTy.isConstOf `Lean.Parser.Parser then do -- synthesize a new `[combinatorAttr c]` some value ← pure cinfo.value? | throwError $ "don't know how to generate " ++ ctx.varName ++ " for non-definition '" ++ toString e ++ "'"; value ← compileParserBody $ preprocessParserBody ctx value; ty ← forallTelescope cinfo.type fun params _ => params.foldrM (fun param ty => do paramTy ← inferType param; paramTy ← forallTelescope paramTy fun _ b => pure $ if b.isConstOf `Lean.Parser.Parser then mkConst ctx.tyName else b; pure $ mkForall `_ BinderInfo.default paramTy ty) (mkConst ctx.tyName); let decl := Declaration.defnDecl { name := c', lparams := [], type := ty, value := value, hints := ReducibilityHints.opaque, isUnsafe := false }; env ← getEnv; env ← match env.addAndCompile {} decl with | Except.ok env => pure env | Except.error kex => do { d ← liftIO $ (kex.toMessageData {}).toString; throwError d }; setEnv $ ctx.combinatorAttr.setDeclFor env c c'; mkCall c' else do -- if this is a generic function, e.g. `HasAndthen.andthen`, it's easier to just unfold it until we are -- back to parser combinators some e' ← unfoldDefinition? e | throwError $ "don't know how to generate " ++ ctx.varName ++ " for non-parser combinator '" ++ toString e ++ "'"; compileParserBody e' end open Core /-- Compile the given declaration into a `[(builtin)runtimeAttr declName]` -/ def compileParser {Ξ±} (ctx : Context Ξ±) (declName : Name) (builtin : Bool) : AttrM Unit := do -- This will also tag the declaration as a `[combinatorParenthesizer declName]` in case the parser is used by other parsers. -- Note that simply having `[(builtin)Parenthesizer]` imply `[combinatorParenthesizer]` is not ideal since builtin -- attributes are active only in the next stage, while `[combinatorParenthesizer]` is active immediately (since we never -- call them at compile time but only reference them). (Expr.const c' _ _) ← liftM $ (compileParserBody ctx (mkConst declName)).run' | unreachable!; -- We assume that for tagged parsers, the kind is equal to the declaration name. This is automatically true for parsers -- using `parser!` or `syntax`. let kind := declName; addAttribute c' (if builtin then ctx.runtimeAttr.defn.builtinName else ctx.runtimeAttr.defn.name) (mkNullNode #[mkIdent kind]) -- When called from `interpretParserDescr`, `declName` might not be a tagged parser, so ignore "not a valid syntax kind" failures <|> pure () unsafe def interpretParser {Ξ±} (ctx : Context Ξ±) (constName : Name) : AttrM Ξ± := do info ← getConstInfo constName; env ← getEnv; if info.type.isConstOf `Lean.Parser.TrailingParser || info.type.isConstOf `Lean.Parser.Parser then match ctx.runtimeAttr.getValues env constName with | p::_ => pure p | _ => do compileParser ctx constName /- builtin -/ false; env ← getEnv; ofExcept $ env.evalConst Ξ± (constName ++ ctx.varName) else do d ← ofExcept $ env.evalConst TrailingParserDescr constName; ctx.interpretParserDescr d unsafe def registerParserCompiler {Ξ±} (ctx : Context Ξ±) : IO Unit := do Parser.registerParserAttributeHook { postAdd := fun catName declName builtin => if builtin then compileParser ctx declName builtin else do p ← interpretParser ctx declName; -- Register `p` without exporting it to the .olean file. It will be re-interpreted and registered -- when the parser is imported. env ← getEnv; setEnv $ ctx.runtimeAttr.ext.modifyState env fun st => { st with table := st.table.insert declName p } } end ParserCompiler end Lean
cf8a80ce4b0ec0f8233239fbdc4be6128cea9628
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/polynomial/coeff.lean
099ef2d77a6d9fb9bec8b1e93409df3def9d4ddd
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,899
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.basic import data.finset.nat_antidiagonal import data.nat.choose.sum /-! # Theory of univariate polynomials The theorems include formulas for computing coefficients, such as `coeff_add`, `coeff_sum`, `coeff_mul` -/ noncomputable theory open finsupp finset add_monoid_algebra open_locale big_operators namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b : R} {n m : β„•} variables [semiring R] {p q r : polynomial R} section coeff lemma coeff_one (n : β„•) : coeff (1 : polynomial R) n = if 0 = n then 1 else 0 := coeff_monomial @[simp] lemma coeff_add (p q : polynomial R) (n : β„•) : coeff (p + q) n = coeff p n + coeff q n := by { rcases p, rcases q, simp [coeff, add_to_finsupp] } @[simp] lemma coeff_smul [monoid S] [distrib_mul_action S R] (r : S) (p : polynomial R) (n : β„•) : coeff (r β€’ p) n = r β€’ coeff p n := by { rcases p, simp [coeff, smul_to_finsupp] } lemma support_smul [monoid S] [distrib_mul_action S R] (r : S) (p : polynomial R) : support (r β€’ p) βŠ† support p := begin assume i hi, simp [mem_support_iff] at hi ⊒, contrapose! hi, simp [hi] end /-- `polynomial.sum` as a linear map. -/ @[simps] def lsum {R A M : Type*} [semiring R] [semiring A] [add_comm_monoid M] [module R A] [module R M] (f : β„• β†’ A β†’β‚—[R] M) : polynomial A β†’β‚—[R] M := { to_fun := Ξ» p, p.sum (Ξ» n r, f n r), map_add' := Ξ» p q, sum_add_index p q _ (Ξ» n, (f n).map_zero) (Ξ» n _ _, (f n).map_add _ _), map_smul' := Ξ» c p, begin rw [sum_eq_of_subset _ (Ξ» n r, f n r) (Ξ» n, (f n).map_zero) _ (support_smul c p)], simp only [sum_def, finset.smul_sum, coeff_smul, linear_map.map_smul, ring_hom.id_apply] end } variable (R) /-- The nth coefficient, as a linear map. -/ def lcoeff (n : β„•) : polynomial R β†’β‚—[R] R := { to_fun := Ξ» p, coeff p n, map_add' := Ξ» p q, coeff_add p q n, map_smul' := Ξ» r p, coeff_smul r p n } variable {R} @[simp] lemma lcoeff_apply (n : β„•) (f : polynomial R) : lcoeff R n f = coeff f n := rfl @[simp] lemma finset_sum_coeff {ΞΉ : Type*} (s : finset ΞΉ) (f : ΞΉ β†’ polynomial R) (n : β„•) : coeff (βˆ‘ b in s, f b) n = βˆ‘ b in s, coeff (f b) n := (lcoeff R n).map_sum lemma coeff_sum [semiring S] (n : β„•) (f : β„• β†’ R β†’ polynomial S) : coeff (p.sum f) n = p.sum (Ξ» a b, coeff (f a b) n) := by { rcases p, simp [polynomial.sum, support, coeff] } /-- Decomposes the coefficient of the product `p * q` as a sum over `nat.antidiagonal`. A version which sums over `range (n + 1)` can be obtained by using `finset.nat.sum_antidiagonal_eq_sum_range_succ`. -/ lemma coeff_mul (p q : polynomial R) (n : β„•) : coeff (p * q) n = βˆ‘ x in nat.antidiagonal n, coeff p x.1 * coeff q x.2 := begin rcases p, rcases q, simp only [coeff, mul_to_finsupp], exact add_monoid_algebra.mul_apply_antidiagonal p q n _ (Ξ» x, nat.mem_antidiagonal) end @[simp] lemma mul_coeff_zero (p q : polynomial R) : coeff (p * q) 0 = coeff p 0 * coeff q 0 := by simp [coeff_mul] lemma coeff_mul_X_zero (p : polynomial R) : coeff (p * X) 0 = 0 := by simp lemma coeff_X_mul_zero (p : polynomial R) : coeff (X * p) 0 = 0 := by simp lemma coeff_C_mul_X (x : R) (k n : β„•) : coeff (C x * X^k : polynomial R) n = if n = k then x else 0 := by { rw [← monomial_eq_C_mul_X, coeff_monomial], congr' 1, simp [eq_comm] } @[simp] lemma coeff_C_mul (p : polynomial R) : coeff (C a * p) n = a * coeff p n := by { rcases p, simp only [C, monomial, monomial_fun, mul_to_finsupp, ring_hom.coe_mk, coeff, add_monoid_algebra.single_zero_mul_apply p a n] } lemma C_mul' (a : R) (f : polynomial R) : C a * f = a β€’ f := by { ext, rw [coeff_C_mul, coeff_smul, smul_eq_mul] } @[simp] lemma coeff_mul_C (p : polynomial R) (n : β„•) (a : R) : coeff (p * C a) n = coeff p n * a := by { rcases p, simp only [C, monomial, monomial_fun, mul_to_finsupp, ring_hom.coe_mk, coeff, add_monoid_algebra.mul_single_zero_apply p a n] } lemma coeff_X_pow (k n : β„•) : coeff (X^k : polynomial R) n = if n = k then 1 else 0 := by simp only [one_mul, ring_hom.map_one, ← coeff_C_mul_X] @[simp] lemma coeff_X_pow_self (n : β„•) : coeff (X^n : polynomial R) n = 1 := by simp [coeff_X_pow] theorem coeff_mul_X_pow (p : polynomial R) (n d : β„•) : coeff (p * polynomial.X ^ n) (d + n) = coeff p d := begin rw [coeff_mul, sum_eq_single (d,n), coeff_X_pow, if_pos rfl, mul_one], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, mul_zero], rintro rfl, apply h2, rw [nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 }, { exact Ξ» h1, (h1 (nat.mem_antidiagonal.2 rfl)).elim } end lemma coeff_mul_X_pow' (p : polynomial R) (n d : β„•) : (p * X ^ n).coeff d = ite (n ≀ d) (p.coeff (d - n)) 0 := begin split_ifs, { rw [← tsub_add_cancel_of_le h, coeff_mul_X_pow, add_tsub_cancel_right] }, { refine (coeff_mul _ _ _).trans (finset.sum_eq_zero (Ξ» x hx, _)), rw [coeff_X_pow, if_neg, mul_zero], exact ne_of_lt (lt_of_le_of_lt (nat.le_of_add_le_right (le_of_eq (finset.nat.mem_antidiagonal.mp hx))) (not_le.mp h)) }, end @[simp] theorem coeff_mul_X (p : polynomial R) (n : β„•) : coeff (p * X) (n + 1) = coeff p n := by simpa only [pow_one] using coeff_mul_X_pow p 1 n theorem mul_X_pow_eq_zero {p : polynomial R} {n : β„•} (H : p * X ^ n = 0) : p = 0 := ext $ Ξ» k, (coeff_mul_X_pow p n k).symm.trans $ ext_iff.1 H (k+n) lemma C_mul_X_pow_eq_monomial (c : R) (n : β„•) : C c * X^n = monomial n c := by { ext1, rw [monomial_eq_smul_X, coeff_smul, coeff_C_mul, smul_eq_mul] } lemma support_mul_X_pow (c : R) (n : β„•) (H : c β‰  0) : (C c * X^n).support = singleton n := by rw [C_mul_X_pow_eq_monomial, support_monomial n c H] lemma support_C_mul_X_pow' {c : R} {n : β„•} : (C c * X^n).support βŠ† singleton n := by { rw [C_mul_X_pow_eq_monomial], exact support_monomial' n c } lemma coeff_X_add_one_pow (R : Type*) [semiring R] (n k : β„•) : ((X + 1) ^ n).coeff k = (n.choose k : R) := begin rw [(commute_X (1 : polynomial R)).add_pow, ← lcoeff_apply, linear_map.map_sum], simp only [one_pow, mul_one, lcoeff_apply, ← C_eq_nat_cast, coeff_mul_C, nat.cast_id], rw [finset.sum_eq_single k, coeff_X_pow_self, one_mul], { intros _ _, simp only [coeff_X_pow, boole_mul, ite_eq_right_iff, ne.def] {contextual := tt}, rintro h rfl, contradiction }, { simp only [coeff_X_pow_self, one_mul, not_lt, finset.mem_range], intro h, rw [nat.choose_eq_zero_of_lt h, nat.cast_zero], } end lemma coeff_one_add_X_pow (R : Type*) [semiring R] (n k : β„•) : ((1 + X) ^ n).coeff k = (n.choose k : R) := by rw [add_comm _ X, coeff_X_add_one_pow] lemma C_dvd_iff_dvd_coeff (r : R) (Ο† : polynomial R) : C r ∣ Ο† ↔ βˆ€ i, r ∣ Ο†.coeff i := begin split, { rintros βŸ¨Ο†, rfl⟩ c, rw coeff_C_mul, apply dvd_mul_right }, { intro h, choose c hc using h, classical, let c' : β„• β†’ R := Ξ» i, if i ∈ Ο†.support then c i else 0, let ψ : polynomial R := βˆ‘ i in Ο†.support, monomial i (c' i), use ψ, ext i, simp only [ψ, c', coeff_C_mul, mem_support_iff, coeff_monomial, finset_sum_coeff, finset.sum_ite_eq'], split_ifs with hi hi, { rw hc }, { rw [not_not] at hi, rwa mul_zero } }, end lemma coeff_bit0_mul (P Q : polynomial R) (n : β„•) : coeff (bit0 P * Q) n = 2 * coeff (P * Q) n := by simp [bit0, add_mul] lemma coeff_bit1_mul (P Q : polynomial R) (n : β„•) : coeff (bit1 P * Q) n = 2 * coeff (P * Q) n + coeff Q n := by simp [bit1, add_mul, coeff_bit0_mul] lemma smul_eq_C_mul (a : R) : a β€’ p = C a * p := by simp [ext_iff] lemma update_eq_add_sub_coeff {R : Type*} [ring R] (p : polynomial R) (n : β„•) (a : R) : p.update n a = p + (polynomial.C (a - p.coeff n) * polynomial.X ^ n) := begin ext, rw [coeff_update_apply, coeff_add, coeff_C_mul_X], split_ifs with h; simp [h] end end coeff section cast @[simp] lemma nat_cast_coeff_zero {n : β„•} {R : Type*} [semiring R] : (n : polynomial R).coeff 0 = n := begin induction n with n ih, { simp, }, { simp [ih], }, end @[simp, norm_cast] theorem nat_cast_inj {m n : β„•} {R : Type*} [semiring R] [char_zero R] : (↑m : polynomial R) = ↑n ↔ m = n := begin fsplit, { intro h, apply_fun (Ξ» p, p.coeff 0) at h, simpa using h, }, { rintro rfl, refl, }, end @[simp] lemma int_cast_coeff_zero {i : β„€} {R : Type*} [ring R] : (i : polynomial R).coeff 0 = i := by cases i; simp @[simp, norm_cast] theorem int_cast_inj {m n : β„€} {R : Type*} [ring R] [char_zero R] : (↑m : polynomial R) = ↑n ↔ m = n := begin fsplit, { intro h, apply_fun (Ξ» p, p.coeff 0) at h, simpa using h, }, { rintro rfl, refl, }, end end cast end polynomial
76ae9ebf7440907ef6d11719ad21707e9ef58f35
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/unfold_cases.lean
5ee52a444ef20ac1db053cceb0efba88d4da13ca
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,228
lean
/- Copyright (c) 2020 Dany Fabian. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dany Fabian -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.split_ifs import Mathlib.PostPort namespace Mathlib /-! # Unfold cases tactic In Lean, pattern matching expressions are not atomic parts of the syntax, but rather they are compiled down into simpler terms that are later checked by the kernel. This allows Lean to have a minimalistic kernel but can occasionally lead an explosion of cases that need to be considered. What looks like one case in the `match` expression can in fact be compiled into many different cases that all need to proved by case analysis. This tactic automates the process by allowing us to write down an equation `f x = y` where we know that `f x = y` is provably true, but does not hold definitionally. In that case the `unfold_cases` tactic will continue unfolding `f` and introducing `cases` where necessary until the left hand side becomes definitionally equal to the right hand side. Consider a definition as follows: ```lean def myand : bool β†’ bool β†’ bool | ff _ := ff | _ ff := ff | _ _ := tt ``` The equation compiler generates 4 equation lemmas for us: ```lean myand ff ff = ff myand ff tt = ff myand tt ff = ff myand tt tt = tt ``` This is not in line with what one might expect looking at the definition. Whilst it is provably true, that `βˆ€ x, myand ff x = ff` and `βˆ€ x, myand x ff = ff`, we do not get these stronger lemmas from the compiler for free but must in fact prove them using `cases` or some other local reasoning. In other words, the following does not constitute a proof that lean accepts. ```lean example : βˆ€ x, myand ff x = ff := begin intros, refl end ``` However, you can use `unfold_cases { refl }` to prove `βˆ€ x, myand ff x = ff` and `βˆ€ x, myand x ff = ff`. For definitions with many cases, the savings can be very significant. The term that gets generated for the above definition looks like this: ```lean Ξ» (a a_1 : bool), a.cases_on (a_1.cases_on (id_rhs bool ff) (id_rhs bool ff)) (a_1.cases_on (id_rhs bool ff) (id_rhs bool tt)) ``` When the tactic tries to prove the goal `βˆ€ x, myand ff x = ff`, it starts by `intros`, followed by unfolding the definition: ```lean ⊒ ff.cases_on (x.cases_on (id_rhs bool ff) (id_rhs bool ff)) (x.cases_on (id_rhs bool ff) (id_rhs bool tt)) = ff ``` At this point, it can make progress using `dsimp`. But then it gets stuck: ```lean ⊒ bool.rec (id_rhs bool ff) (id_rhs bool ff) x = ff ``` Next, it can introduce a case split on `x`. At this point, it has to prove two goals: ```lean ⊒ bool.rec (id_rhs bool ff) (id_rhs bool ff) ff = ff ⊒ bool.rec (id_rhs bool ff) (id_rhs bool ff) tt = ff ``` Now, however, both goals can be discharged using `refl`. -/ namespace tactic namespace unfold_cases /-- Given an equation `f x = y`, this tactic tries to infer an expression that can be used to do distinction by cases on to make progress. Pre-condition: assumes that the outer-most application cannot be beta-reduced (e.g. `whnf` or `dsimp`). -/ /-- Tries to finish the current goal using the `inner` tactic. If the tactic fails, it tries to find an expression on which to do a distinction by cases and calls itself recursively. The order of operations is significant. Because the unfolding can potentially be infinite, it is important to apply the `inner` tactic at every step. Notice, that if the `inner` tactic succeeds, the recursive unfolding is stopped. -/ /-- Given a target of the form `⊒ f x₁ ... xβ‚™ = y`, unfolds `f` using a delta reduction. -/ end unfold_cases namespace interactive /-- This tactic unfolds the definition of a function or `match` expression. Then it recursively introduces a distinction by cases. The decision what expression to do the distinction on is driven by the pattern matching expression. A typical use case is using `unfold_cases { refl }` to collapse cases that need to be considered in a pattern matching. ```lean have h : foo x = y, by unfold_cases { refl }, rw h, ``` The tactic expects a goal in the form of an equation, possibly universally quantified. We can prove a theorem, even if the various case do not directly correspond to the function definition. Here is an example application of the tactic: ```lean def foo : β„• β†’ β„• β†’ β„• | 0 0 := 17 | (n+2) 17 := 17 | 1 0 := 23 | 0 (n+18) := 15 | 0 17 := 17 | 1 17 := 17 | _ (n+18) := 27 | _ _ := 15 example : βˆ€ x, foo x 17 = 17 := begin unfold_cases { refl }, end ``` The compiler generates 57 cases for `foo`. However, when we look at the definition, we see that whenever the function is applied to `17` in the second argument, it returns `17`. Proving this property consists of merely considering all the cases, eliminating invalid ones and applying `refl` on the ones which remain. Further examples can be found in `test/unfold_cases.lean`. -/
659600b047e7505696973670d1ea27ba1511ae4a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/monoidal/Mod.lean
0a351deb1f418c09a79b91f2e98179ceb2c1cd1b
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,479
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.monoidal.Mon_ import Mathlib.PostPort universes v₁ u₁ l namespace Mathlib /-! # The category of module objects over a monoid object. -/ /-- A module object for a monoid object, all internal to some monoidal category. -/ structure Mod {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] (A : Mon_ C) where X : C act : Mon_.X A βŠ— X ⟢ X one_act' : autoParam ((Mon_.one A βŠ— πŸ™) ≫ act = category_theory.iso.hom Ξ»_) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) assoc' : autoParam ((Mon_.mul A βŠ— πŸ™) ≫ act = category_theory.iso.hom Ξ±_ ≫ (πŸ™ βŠ— act) ≫ act) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) @[simp] theorem Mod.one_act {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (c : Mod A) : (Mon_.one A βŠ— πŸ™) ≫ Mod.act c = category_theory.iso.hom Ξ»_ := sorry @[simp] theorem Mod.assoc {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (c : Mod A) : (Mon_.mul A βŠ— πŸ™) ≫ Mod.act c = category_theory.iso.hom Ξ±_ ≫ (πŸ™ βŠ— Mod.act c) ≫ Mod.act c := sorry @[simp] theorem Mod.one_act_assoc {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (c : Mod A) {X' : C} (f' : Mod.X c ⟢ X') : (Mon_.one A βŠ— πŸ™) ≫ Mod.act c ≫ f' = category_theory.iso.hom Ξ»_ ≫ f' := sorry namespace Mod theorem assoc_flip {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (M : Mod A) : (πŸ™ βŠ— act M) ≫ act M = category_theory.iso.inv Ξ±_ ≫ (Mon_.mul A βŠ— πŸ™) ≫ act M := sorry /-- A morphism of module objects. -/ structure hom {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (M : Mod A) (N : Mod A) where hom : X M ⟢ X N act_hom' : autoParam (act M ≫ hom = (πŸ™ βŠ— hom) ≫ act N) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) @[simp] theorem hom.act_hom {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} {M : Mod A} {N : Mod A} (c : hom M N) : act M ≫ hom.hom c = (πŸ™ βŠ— hom.hom c) ≫ act N := sorry @[simp] theorem hom.act_hom_assoc {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} {M : Mod A} {N : Mod A} (c : hom M N) {X' : C} (f' : X N ⟢ X') : act M ≫ hom.hom c ≫ f' = (πŸ™ βŠ— hom.hom c) ≫ act N ≫ f' := sorry /-- The identity morphism on a module object. -/ def id {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (M : Mod A) : hom M M := hom.mk πŸ™ protected instance hom_inhabited {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (M : Mod A) : Inhabited (hom M M) := { default := id M } /-- Composition of module object morphisms. -/ def comp {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} {M : Mod A} {N : Mod A} {O : Mod A} (f : hom M N) (g : hom N O) : hom M O := hom.mk (hom.hom f ≫ hom.hom g) protected instance category_theory.category {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} : category_theory.category (Mod A) := category_theory.category.mk @[simp] theorem id_hom' {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} (M : Mod A) : hom.hom πŸ™ = πŸ™ := rfl @[simp] theorem comp_hom' {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} {M : Mod A} {N : Mod A} {K : Mod A} (f : M ⟢ N) (g : N ⟢ K) : hom.hom (f ≫ g) = hom.hom f ≫ hom.hom g := rfl /-- A monoid object as a module over itself. -/ @[simp] theorem regular_X {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] (A : Mon_ C) : X (regular A) = Mon_.X A := Eq.refl (X (regular A)) protected instance inhabited {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] (A : Mon_ C) : Inhabited (Mod A) := { default := regular A } /-- The forgetful functor from module objects to the ambient category. -/ def forget {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] (A : Mon_ C) : Mod A β₯€ C := category_theory.functor.mk (fun (A_1 : Mod A) => X A_1) fun (A_1 B : Mod A) (f : A_1 ⟢ B) => hom.hom f /-- A morphism of monoid objects induces a "restriction" or "comap" functor between the categories of module objects. -/ @[simp] theorem comap_obj_act {C : Type u₁} [category_theory.category C] [category_theory.monoidal_category C] {A : Mon_ C} {B : Mon_ C} (f : A ⟢ B) (M : Mod B) : act (category_theory.functor.obj (comap f) M) = (Mon_.hom.hom f βŠ— πŸ™) ≫ act M := Eq.refl (act (category_theory.functor.obj (comap f) M))
2113f55a2782463a586a9afd9db0fc14600a4711
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/class_group.lean
6ad944e45c7be561384ebce8c5daac118ac65853
[ "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
10,439
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import group_theory.quotient_group import ring_theory.dedekind_domain /-! # The ideal class group This file defines the ideal class group `class_group R K` of fractional ideals of `R` inside `A`'s field of fractions `K`. ## Main definitions - `to_principal_ideal` sends an invertible `x : K` to an invertible fractional ideal - `class_group` is the quotient of invertible fractional ideals modulo `to_principal_ideal.range` - `class_group.mk0` sends a nonzero integral ideal in a Dedekind domain to its class ## Main results - `class_group.mk0_eq_mk0_iff` shows the equivalence with the "classical" definition, where `I ~ J` iff `x I = y J` for `x y β‰  (0 : R)` -/ variables {R K L : Type*} [comm_ring R] variables [field K] [field L] [decidable_eq L] variables [algebra R K] [is_fraction_ring R K] variables [algebra K L] [finite_dimensional K L] variables [algebra R L] [is_scalar_tower R K L] open_locale non_zero_divisors open is_localization is_fraction_ring fractional_ideal units section variables (R K) /-- `to_principal_ideal R K x` sends `x β‰  0 : K` to the fractional `R`-ideal generated by `x` -/ @[irreducible] def to_principal_ideal : KΛ£ β†’* (fractional_ideal R⁰ K)Λ£ := { to_fun := Ξ» x, ⟨span_singleton _ x, span_singleton _ x⁻¹, by simp only [span_singleton_one, units.mul_inv', span_singleton_mul_span_singleton], by simp only [span_singleton_one, units.inv_mul', span_singleton_mul_span_singleton]⟩, map_mul' := Ξ» x y, ext (by simp only [units.coe_mk, units.coe_mul, span_singleton_mul_span_singleton]), map_one' := ext (by simp only [span_singleton_one, units.coe_mk, units.coe_one]) } local attribute [semireducible] to_principal_ideal variables {R K} @[simp] lemma coe_to_principal_ideal (x : KΛ£) : (to_principal_ideal R K x : fractional_ideal R⁰ K) = span_singleton _ x := rfl @[simp] lemma to_principal_ideal_eq_iff {I : (fractional_ideal R⁰ K)Λ£} {x : KΛ£} : to_principal_ideal R K x = I ↔ span_singleton R⁰ (x : K) = I := units.ext_iff end instance principal_ideals.normal : (to_principal_ideal R K).range.normal := subgroup.normal_of_comm _ section variables (R K) /-- The ideal class group of `R` in a field of fractions `K` is the group of invertible fractional ideals modulo the principal ideals. -/ @[derive(comm_group)] def class_group := (fractional_ideal R⁰ K)Λ£ β§Έ (to_principal_ideal R K).range instance : inhabited (class_group R K) := ⟨1⟩ variables {R} [is_domain R] /-- Send a nonzero integral ideal to an invertible fractional ideal. -/ @[simps] noncomputable def fractional_ideal.mk0 [is_dedekind_domain R] : (ideal R)⁰ β†’* (fractional_ideal R⁰ K)Λ£ := { to_fun := Ξ» I, units.mk0 I ((fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl R⁰)).mpr (mem_non_zero_divisors_iff_ne_zero.mp I.2)), map_one' := by simp, map_mul' := Ξ» x y, by simp } /-- Send a nonzero ideal to the corresponding class in the class group. -/ @[simps] noncomputable def class_group.mk0 [is_dedekind_domain R] : (ideal R)⁰ β†’* class_group R K := (quotient_group.mk' _).comp (fractional_ideal.mk0 K) variables {K} lemma quotient_group.mk'_eq_mk' {G : Type*} [group G] {N : subgroup G} [hN : N.normal] {x y : G} : quotient_group.mk' N x = quotient_group.mk' N y ↔ βˆƒ z ∈ N, x * z = y := (@quotient.eq _ (quotient_group.left_rel _) _ _).trans ⟨λ (h : x⁻¹ * y ∈ N), ⟨_, h, by rw [← mul_assoc, mul_right_inv, one_mul]⟩, Ξ» ⟨z, z_mem, eq_y⟩, by { rw ← eq_y, show x⁻¹ * (x * z) ∈ N, rwa [← mul_assoc, mul_left_inv, one_mul] }⟩ lemma class_group.mk0_eq_mk0_iff_exists_fraction_ring [is_dedekind_domain R] {I J : (ideal R)⁰} : class_group.mk0 K I = class_group.mk0 K J ↔ βˆƒ (x β‰  (0 : K)), span_singleton R⁰ x * I = J := begin simp only [class_group.mk0, monoid_hom.comp_apply, quotient_group.mk'_eq_mk'], split, { rintros ⟨_, ⟨x, rfl⟩, hx⟩, refine ⟨x, x.ne_zero, _⟩, simpa only [mul_comm, coe_mk0, monoid_hom.to_fun_eq_coe, coe_to_principal_ideal, units.coe_mul] using congr_arg (coe : _ β†’ fractional_ideal R⁰ K) hx }, { rintros ⟨x, hx, eq_J⟩, refine ⟨_, ⟨units.mk0 x hx, rfl⟩, units.ext _⟩, simpa only [fractional_ideal.mk0_apply, units.coe_mk0, mul_comm, coe_to_principal_ideal, coe_coe, units.coe_mul] using eq_J } end lemma class_group.mk0_eq_mk0_iff [is_dedekind_domain R] {I J : (ideal R)⁰} : class_group.mk0 K I = class_group.mk0 K J ↔ βˆƒ (x y : R) (hx : x β‰  0) (hy : y β‰  0), ideal.span {x} * (I : ideal R) = ideal.span {y} * J := begin refine class_group.mk0_eq_mk0_iff_exists_fraction_ring.trans ⟨_, _⟩, { rintros ⟨z, hz, h⟩, obtain ⟨x, ⟨y, hy⟩, rfl⟩ := is_localization.mk'_surjective R⁰ z, refine ⟨x, y, _, mem_non_zero_divisors_iff_ne_zero.mp hy, _⟩, { rintro hx, apply hz, rw [hx, is_fraction_ring.mk'_eq_div, (algebra_map R K).map_zero, zero_div] }, { exact (fractional_ideal.mk'_mul_coe_ideal_eq_coe_ideal K hy).mp h } }, { rintros ⟨x, y, hx, hy, h⟩, have hy' : y ∈ R⁰ := mem_non_zero_divisors_iff_ne_zero.mpr hy, refine ⟨is_localization.mk' K x ⟨y, hy'⟩, _, _⟩, { contrapose! hx, rwa [is_localization.mk'_eq_iff_eq_mul, zero_mul, ← (algebra_map R K).map_zero, (is_fraction_ring.injective R K).eq_iff] at hx }, { exact (fractional_ideal.mk'_mul_coe_ideal_eq_coe_ideal K hy').mpr h } }, end lemma class_group.mk0_surjective [is_dedekind_domain R] : function.surjective (class_group.mk0 K : (ideal R)⁰ β†’ class_group R K) := begin rintros ⟨I⟩, obtain ⟨a, a_ne_zero', ha⟩ := I.1.2, have a_ne_zero := mem_non_zero_divisors_iff_ne_zero.mp a_ne_zero', have fa_ne_zero : (algebra_map R K) a β‰  0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors a_ne_zero', refine ⟨⟨{ carrier := { x | (algebra_map R K a)⁻¹ * algebra_map R K x ∈ I.1 }, .. }, _⟩, _⟩, { simp only [ring_hom.map_zero, set.mem_set_of_eq, mul_zero, ring_hom.map_mul], exact submodule.zero_mem I }, { simp only [ring_hom.map_add, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add], exact Ξ» _ _ ha hb, submodule.add_mem I ha hb }, { intros c _ hb, simp only [smul_eq_mul, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add, mul_left_comm ((algebra_map R K) a)⁻¹], rw ← algebra.smul_def c, exact submodule.smul_mem I c hb }, { rw [mem_non_zero_divisors_iff_ne_zero, submodule.zero_eq_bot, submodule.ne_bot_iff], obtain ⟨x, x_ne, x_mem⟩ := exists_ne_zero_mem_is_integer I.ne_zero, refine ⟨a * x, _, mul_ne_zero a_ne_zero x_ne⟩, change ((algebra_map R K) a)⁻¹ * (algebra_map R K) (a * x) ∈ I.1, rwa [ring_hom.map_mul, ← mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] }, { symmetry, apply quotient.sound, refine ⟨units.mk0 (algebra_map R K a) fa_ne_zero, _⟩, apply @mul_left_cancel _ _ I, rw [← mul_assoc, mul_right_inv, one_mul, eq_comm, mul_comm I], apply units.ext, simp only [monoid_hom.coe_mk, subtype.coe_mk, ring_hom.map_mul, coe_coe, units.coe_mul, coe_to_principal_ideal, coe_mk0, fractional_ideal.eq_span_singleton_mul], split, { intros zJ' hzJ', obtain ⟨zJ, hzJ : (algebra_map R K a)⁻¹ * algebra_map R K zJ ∈ ↑I, rfl⟩ := (mem_coe_ideal R⁰).mp hzJ', refine ⟨_, hzJ, _⟩, rw [← mul_assoc, mul_inv_cancel fa_ne_zero, one_mul] }, { intros zI' hzI', obtain ⟨y, hy⟩ := ha zI' hzI', rw [← algebra.smul_def, fractional_ideal.mk0_apply, coe_mk0, coe_coe, mem_coe_ideal], refine ⟨y, _, hy⟩, show (algebra_map R K a)⁻¹ * algebra_map R K y ∈ (I : fractional_ideal R⁰ K), rwa [hy, algebra.smul_def, ← mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] } } end end lemma class_group.mk_eq_one_iff {I : (fractional_ideal R⁰ K)Λ£} : quotient_group.mk' (to_principal_ideal R K).range I = 1 ↔ (I : submodule R K).is_principal := begin rw [← (quotient_group.mk' _).map_one, eq_comm, quotient_group.mk'_eq_mk'], simp only [exists_prop, one_mul, exists_eq_right, to_principal_ideal_eq_iff, monoid_hom.mem_range, coe_coe], refine ⟨λ ⟨x, hx⟩, ⟨⟨x, by rw [← hx, coe_span_singleton]⟩⟩, _⟩, unfreezingI { intros hI }, obtain ⟨x, hx⟩ := @submodule.is_principal.principal _ _ _ _ _ _ hI, have hx' : (I : fractional_ideal R⁰ K) = span_singleton R⁰ x, { apply subtype.coe_injective, rw [hx, coe_span_singleton] }, refine ⟨units.mk0 x _, _⟩, { intro x_eq, apply units.ne_zero I, simp [hx', x_eq] }, simp [hx'] end variables [is_domain R] lemma class_group.mk0_eq_one_iff [is_dedekind_domain R] {I : ideal R} (hI : I ∈ (ideal R)⁰) : class_group.mk0 K ⟨I, hI⟩ = 1 ↔ I.is_principal := class_group.mk_eq_one_iff.trans (coe_submodule_is_principal R K) /-- The class group of principal ideal domain is finite (in fact a singleton). TODO: generalize to Dedekind domains -/ instance [is_principal_ideal_ring R] : fintype (class_group R K) := { elems := {1}, complete := begin rintros ⟨I⟩, rw [finset.mem_singleton], exact class_group.mk_eq_one_iff.mpr (I : fractional_ideal R⁰ K).is_principal end } /-- The class number of a principal ideal domain is `1`. -/ lemma card_class_group_eq_one [is_principal_ideal_ring R] : fintype.card (class_group R K) = 1 := begin rw fintype.card_eq_one_iff, use 1, rintros ⟨I⟩, exact class_group.mk_eq_one_iff.mpr (I : fractional_ideal R⁰ K).is_principal end /-- The class number is `1` iff the ring of integers is a principal ideal domain. -/ lemma card_class_group_eq_one_iff [is_dedekind_domain R] [fintype (class_group R K)] : fintype.card (class_group R K) = 1 ↔ is_principal_ideal_ring R := begin split, swap, { introsI, convert card_class_group_eq_one, assumption, assumption, }, rw fintype.card_eq_one_iff, rintros ⟨I, hI⟩, have eq_one : βˆ€ J : class_group R K, J = 1 := Ξ» J, trans (hI J) (hI 1).symm, refine ⟨λ I, _⟩, by_cases hI : I = βŠ₯, { rw hI, exact bot_is_principal }, exact (class_group.mk0_eq_one_iff (mem_non_zero_divisors_iff_ne_zero.mpr hI)).mp (eq_one _), end
28ef71cd535d51a6c2ff7053c422cc44104b5e4c
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/order/conditionally_complete_lattice.lean
918585e263151e36cb74bb60e45073bd6e70b76b
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
49,687
lean
/- Copyright (c) 2018 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 data.nat.enat import data.set.intervals.ord_connected /-! # Theory of conditionally complete lattices. A conditionally complete lattice is a lattice in which every non-empty bounded subset s has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s. Typical examples are real, nat, int with their usual orders. The theory is very comparable to the theory of complete lattices, except that suitable boundedness and nonemptiness assumptions have to be added to most statements. We introduce two predicates bdd_above and bdd_below to express this boundedness, prove their basic properties, and then go on to prove most useful properties of Sup and Inf in conditionally complete lattices. To differentiate the statements between complete lattices and conditionally complete lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance, Inf_le is a statement in complete lattices ensuring Inf s ≀ x, while cInf_le is the same statement in conditionally complete lattices with an additional assumption that s is bounded below. -/ set_option old_structure_cmd true open set variables {Ξ± Ξ² : Type*} {ΞΉ : Sort*} section /-! Extension of Sup and Inf from a preorder `Ξ±` to `with_top Ξ±` and `with_bot Ξ±` -/ open_locale classical noncomputable instance {Ξ± : Type*} [preorder Ξ±] [has_Sup Ξ±] : has_Sup (with_top Ξ±) := ⟨λ S, if ⊀ ∈ S then ⊀ else if bdd_above (coe ⁻¹' S : set Ξ±) then ↑(Sup (coe ⁻¹' S : set Ξ±)) else ⊀⟩ noncomputable instance {Ξ± : Type*} [has_Inf Ξ±] : has_Inf (with_top Ξ±) := ⟨λ S, if S βŠ† {⊀} then ⊀ else ↑(Inf (coe ⁻¹' S : set Ξ±))⟩ noncomputable instance {Ξ± : Type*} [has_Sup Ξ±] : has_Sup (with_bot Ξ±) := ⟨(@with_top.has_Inf (order_dual Ξ±) _).Inf⟩ noncomputable instance {Ξ± : Type*} [preorder Ξ±] [has_Inf Ξ±] : has_Inf (with_bot Ξ±) := ⟨(@with_top.has_Sup (order_dual Ξ±) _ _).Sup⟩ @[simp] theorem with_top.cInf_empty {Ξ± : Type*} [has_Inf Ξ±] : Inf (βˆ… : set (with_top Ξ±)) = ⊀ := if_pos $ set.empty_subset _ @[simp] theorem with_bot.cSup_empty {Ξ± : Type*} [has_Sup Ξ±] : Sup (βˆ… : set (with_bot Ξ±)) = βŠ₯ := if_pos $ set.empty_subset _ end -- section /-- A conditionally complete lattice is a lattice in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of nonemptiness or boundedness.-/ class conditionally_complete_lattice (Ξ± : Type*) extends lattice Ξ±, has_Sup Ξ±, has_Inf Ξ± := (le_cSup : βˆ€s a, bdd_above s β†’ a ∈ s β†’ a ≀ Sup s) (cSup_le : βˆ€ s a, set.nonempty s β†’ a ∈ upper_bounds s β†’ Sup s ≀ a) (cInf_le : βˆ€s a, bdd_below s β†’ a ∈ s β†’ Inf s ≀ a) (le_cInf : βˆ€s a, set.nonempty s β†’ a ∈ lower_bounds s β†’ a ≀ Inf s) /-- A conditionally complete linear order is a linear order in which every nonempty subset which is bounded above has a supremum, and every nonempty subset which is bounded below has an infimum. Typical examples are real numbers or natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete linear orders, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of nonemptiness or boundedness.-/ class conditionally_complete_linear_order (Ξ± : Type*) extends conditionally_complete_lattice Ξ±, linear_order Ξ± /-- A conditionally complete linear order with `bot` is a linear order with least element, in which every nonempty subset which is bounded above has a supremum, and every nonempty subset (necessarily bounded below) has an infimum. A typical example is the natural numbers. To differentiate the statements from the corresponding statements in (unconditional) complete linear orders, we prefix Inf and Sup by a c everywhere. The same statements should hold in both worlds, sometimes with additional assumptions of nonemptiness or boundedness.-/ class conditionally_complete_linear_order_bot (Ξ± : Type*) extends conditionally_complete_linear_order Ξ±, order_bot Ξ± := (cSup_empty : Sup βˆ… = βŠ₯) /- A complete lattice is a conditionally complete lattice, as there are no restrictions on the properties of Inf and Sup in a complete lattice.-/ @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_lattice_of_complete_lattice [complete_lattice Ξ±]: conditionally_complete_lattice Ξ± := { le_cSup := by intros; apply le_Sup; assumption, cSup_le := by intros; apply Sup_le; assumption, cInf_le := by intros; apply Inf_le; assumption, le_cInf := by intros; apply le_Inf; assumption, ..β€Ήcomplete_lattice Ξ±β€Ί } @[priority 100] -- see Note [lower instance priority] instance conditionally_complete_linear_order_of_complete_linear_order [complete_linear_order Ξ±]: conditionally_complete_linear_order Ξ± := { ..conditionally_complete_lattice_of_complete_lattice, .. β€Ήcomplete_linear_order Ξ±β€Ί } section order_dual instance (Ξ± : Type*) [conditionally_complete_lattice Ξ±] : conditionally_complete_lattice (order_dual Ξ±) := { le_cSup := @conditionally_complete_lattice.cInf_le Ξ± _, cSup_le := @conditionally_complete_lattice.le_cInf Ξ± _, le_cInf := @conditionally_complete_lattice.cSup_le Ξ± _, cInf_le := @conditionally_complete_lattice.le_cSup Ξ± _, ..order_dual.has_Inf Ξ±, ..order_dual.has_Sup Ξ±, ..order_dual.lattice Ξ± } instance (Ξ± : Type*) [conditionally_complete_linear_order Ξ±] : conditionally_complete_linear_order (order_dual Ξ±) := { ..order_dual.conditionally_complete_lattice Ξ±, ..order_dual.linear_order Ξ± } end order_dual section conditionally_complete_lattice variables [conditionally_complete_lattice Ξ±] {s t : set Ξ±} {a b : Ξ±} theorem le_cSup (h₁ : bdd_above s) (hβ‚‚ : a ∈ s) : a ≀ Sup s := conditionally_complete_lattice.le_cSup s a h₁ hβ‚‚ theorem cSup_le (h₁ : s.nonempty) (hβ‚‚ : βˆ€b∈s, b ≀ a) : Sup s ≀ a := conditionally_complete_lattice.cSup_le s a h₁ hβ‚‚ theorem cInf_le (h₁ : bdd_below s) (hβ‚‚ : a ∈ s) : Inf s ≀ a := conditionally_complete_lattice.cInf_le s a h₁ hβ‚‚ theorem le_cInf (h₁ : s.nonempty) (hβ‚‚ : βˆ€b∈s, a ≀ b) : a ≀ Inf s := conditionally_complete_lattice.le_cInf s a h₁ hβ‚‚ theorem le_cSup_of_le (_ : bdd_above s) (hb : b ∈ s) (h : a ≀ b) : a ≀ Sup s := le_trans h (le_cSup β€Ήbdd_above sβ€Ί hb) theorem cInf_le_of_le (_ : bdd_below s) (hb : b ∈ s) (h : b ≀ a) : Inf s ≀ a := le_trans (cInf_le β€Ήbdd_below sβ€Ί hb) h theorem cSup_le_cSup (_ : bdd_above t) (_ : s.nonempty) (h : s βŠ† t) : Sup s ≀ Sup t := cSup_le β€Ή_β€Ί (assume (a) (ha : a ∈ s), le_cSup β€Ήbdd_above tβ€Ί (h ha)) theorem cInf_le_cInf (_ : bdd_below t) (_ : s.nonempty) (h : s βŠ† t) : Inf t ≀ Inf s := le_cInf β€Ή_β€Ί (assume (a) (ha : a ∈ s), cInf_le β€Ήbdd_below tβ€Ί (h ha)) lemma is_lub_cSup (ne : s.nonempty) (H : bdd_above s) : is_lub s (Sup s) := ⟨assume x, le_cSup H, assume x, cSup_le ne⟩ lemma is_lub_csupr [nonempty ΞΉ] {f : ΞΉ β†’ Ξ±} (H : bdd_above (range f)) : is_lub (range f) (⨆ i, f i) := is_lub_cSup (range_nonempty f) H lemma is_lub_csupr_set {f : Ξ² β†’ Ξ±} {s : set Ξ²} (H : bdd_above (f '' s)) (Hne : s.nonempty) : is_lub (f '' s) (⨆ i : s, f i) := by { rw ← Sup_image', exact is_lub_cSup (Hne.image _) H } lemma is_glb_cInf (ne : s.nonempty) (H : bdd_below s) : is_glb s (Inf s) := ⟨assume x, cInf_le H, assume x, le_cInf ne⟩ lemma is_glb_cinfi [nonempty ΞΉ] {f : ΞΉ β†’ Ξ±} (H : bdd_below (range f)) : is_glb (range f) (β¨… i, f i) := is_glb_cInf (range_nonempty f) H lemma is_glb_cinfi_set {f : Ξ² β†’ Ξ±} {s : set Ξ²} (H : bdd_below (f '' s)) (Hne : s.nonempty) : is_glb (f '' s) (β¨… i : s, f i) := @is_lub_csupr_set (order_dual Ξ±) _ _ _ _ H Hne lemma is_lub.cSup_eq (H : is_lub s a) (ne : s.nonempty) : Sup s = a := (is_lub_cSup ne ⟨a, H.1⟩).unique H lemma is_lub.csupr_eq [nonempty ΞΉ] {f : ΞΉ β†’ Ξ±} (H : is_lub (range f) a) : (⨆ i, f i) = a := H.cSup_eq (range_nonempty f) lemma is_lub.csupr_set_eq {s : set Ξ²} {f : Ξ² β†’ Ξ±} (H : is_lub (f '' s) a) (Hne : s.nonempty) : (⨆ i : s, f i) = a := is_lub.cSup_eq (image_eq_range f s β–Έ H) (image_eq_range f s β–Έ Hne.image f) /-- A greatest element of a set is the supremum of this set. -/ lemma is_greatest.cSup_eq (H : is_greatest s a) : Sup s = a := H.is_lub.cSup_eq H.nonempty lemma is_greatest.Sup_mem (H : is_greatest s a) : Sup s ∈ s := H.cSup_eq.symm β–Έ H.1 lemma is_glb.cInf_eq (H : is_glb s a) (ne : s.nonempty) : Inf s = a := (is_glb_cInf ne ⟨a, H.1⟩).unique H lemma is_glb.cinfi_eq [nonempty ΞΉ] {f : ΞΉ β†’ Ξ±} (H : is_lub (range f) a) : (⨆ i, f i) = a := H.cSup_eq (range_nonempty f) lemma is_glb.cinfi_set_eq {s : set Ξ²} {f : Ξ² β†’ Ξ±} (H : is_glb (f '' s) a) (Hne : s.nonempty) : (β¨… i : s, f i) = a := is_glb.cInf_eq (image_eq_range f s β–Έ H) (image_eq_range f s β–Έ Hne.image f) /-- A least element of a set is the infimum of this set. -/ lemma is_least.cInf_eq (H : is_least s a) : Inf s = a := H.is_glb.cInf_eq H.nonempty lemma is_least.Inf_mem (H : is_least s a) : Inf s ∈ s := H.cInf_eq.symm β–Έ H.1 lemma subset_Icc_cInf_cSup (hb : bdd_below s) (ha : bdd_above s) : s βŠ† Icc (Inf s) (Sup s) := Ξ» x hx, ⟨cInf_le hb hx, le_cSup ha hx⟩ theorem cSup_le_iff (hb : bdd_above s) (ne : s.nonempty) : Sup s ≀ a ↔ (βˆ€b ∈ s, b ≀ a) := is_lub_le_iff (is_lub_cSup ne hb) theorem le_cInf_iff (hb : bdd_below s) (ne : s.nonempty) : a ≀ Inf s ↔ (βˆ€b ∈ s, a ≀ b) := le_is_glb_iff (is_glb_cInf ne hb) lemma cSup_lower_bounds_eq_cInf {s : set Ξ±} (h : bdd_below s) (hs : s.nonempty) : Sup (lower_bounds s) = Inf s := (is_lub_cSup h $ hs.mono $ Ξ» x hx y hy, hy hx).unique (is_glb_cInf hs h).is_lub lemma cInf_upper_bounds_eq_cSup {s : set Ξ±} (h : bdd_above s) (hs : s.nonempty) : Inf (upper_bounds s) = Sup s := (is_glb_cInf h $ hs.mono $ Ξ» x hx y hy, hy hx).unique (is_lub_cSup hs h).is_glb /--Introduction rule to prove that `b` is the supremum of `s`: it suffices to check that `b` is larger than all elements of `s`, and that this is not the case of any `w<b`. See `Sup_eq_of_forall_le_of_forall_lt_exists_gt` for a version in complete lattices. -/ theorem cSup_eq_of_forall_le_of_forall_lt_exists_gt (_ : s.nonempty) (_ : βˆ€a∈s, a ≀ b) (H : βˆ€w, w < b β†’ (βˆƒa∈s, w < a)) : Sup s = b := have bdd_above s := ⟨b, by assumption⟩, have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (cSup_le β€Ή_β€Ί β€Ήβˆ€a∈s, a ≀ bβ€Ί), have Β¬(Sup s < b) := assume: Sup s < b, let ⟨a, _, _⟩ := (H (Sup s) β€ΉSup s < bβ€Ί) in /- a ∈ s, Sup s < a-/ have Sup s < Sup s := lt_of_lt_of_le β€ΉSup s < aβ€Ί (le_cSup β€Ήbdd_above sβ€Ί β€Ήa ∈ sβ€Ί), show false, by finish [lt_irrefl (Sup s)], show Sup s = b, by finish /--Introduction rule to prove that `b` is the infimum of `s`: it suffices to check that `b` is smaller than all elements of `s`, and that this is not the case of any `w>b`. See `Inf_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in complete lattices. -/ theorem cInf_eq_of_forall_ge_of_forall_gt_exists_lt (_ : s.nonempty) (_ : βˆ€a∈s, b ≀ a) (H : βˆ€w, b < w β†’ (βˆƒa∈s, a < w)) : Inf s = b := @cSup_eq_of_forall_le_of_forall_lt_exists_gt (order_dual Ξ±) _ _ _ β€Ή_β€Ί β€Ή_β€Ί β€Ή_β€Ί /--b < Sup s when there is an element a in s with b < a, when s is bounded above. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness above for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma lt_cSup_of_lt (_ : bdd_above s) (_ : a ∈ s) (_ : b < a) : b < Sup s := lt_of_lt_of_le β€Ήb < aβ€Ί (le_cSup β€Ήbdd_above sβ€Ί β€Ήa ∈ sβ€Ί) /--Inf s < b when there is an element a in s with a < b, when s is bounded below. This is essentially an iff, except that the assumptions for the two implications are slightly different (one needs boundedness below for one direction, nonemptiness and linear order for the other one), so we formulate separately the two implications, contrary to the complete_lattice case.-/ lemma cInf_lt_of_lt (_ : bdd_below s) (_ : a ∈ s) (_ : a < b) : Inf s < b := @lt_cSup_of_lt (order_dual Ξ±) _ _ _ _ β€Ή_β€Ί β€Ή_β€Ί β€Ή_β€Ί /-- If all elements of a nonempty set `s` are less than or equal to all elements of a nonempty set `t`, then there exists an element between these sets. -/ lemma exists_between_of_forall_le (sne : s.nonempty) (tne : t.nonempty) (hst : βˆ€ (x ∈ s) (y ∈ t), x ≀ y) : (upper_bounds s ∩ lower_bounds t).nonempty := ⟨Inf t, Ξ» x hx, le_cInf tne $ hst x hx, Ξ» y hy, cInf_le (sne.mono hst) hy⟩ /--The supremum of a singleton is the element of the singleton-/ @[simp] theorem cSup_singleton (a : Ξ±) : Sup {a} = a := is_greatest_singleton.cSup_eq /--The infimum of a singleton is the element of the singleton-/ @[simp] theorem cInf_singleton (a : Ξ±) : Inf {a} = a := is_least_singleton.cInf_eq /--If a set is bounded below and above, and nonempty, its infimum is less than or equal to its supremum.-/ theorem cInf_le_cSup (hb : bdd_below s) (ha : bdd_above s) (ne : s.nonempty) : Inf s ≀ Sup s := is_glb_le_is_lub (is_glb_cInf ne hb) (is_lub_cSup ne ha) ne /--The sup of a union of two sets is the max of the suprema of each subset, under the assumptions that all sets are bounded above and nonempty.-/ theorem cSup_union (hs : bdd_above s) (sne : s.nonempty) (ht : bdd_above t) (tne : t.nonempty) : Sup (s βˆͺ t) = Sup s βŠ” Sup t := ((is_lub_cSup sne hs).union (is_lub_cSup tne ht)).cSup_eq sne.inl /--The inf of a union of two sets is the min of the infima of each subset, under the assumptions that all sets are bounded below and nonempty.-/ theorem cInf_union (hs : bdd_below s) (sne : s.nonempty) (ht : bdd_below t) (tne : t.nonempty) : Inf (s βˆͺ t) = Inf s βŠ“ Inf t := @cSup_union (order_dual Ξ±) _ _ _ hs sne ht tne /--The supremum of an intersection of two sets is bounded by the minimum of the suprema of each set, if all sets are bounded above and nonempty.-/ theorem cSup_inter_le (_ : bdd_above s) (_ : bdd_above t) (hst : (s ∩ t).nonempty) : Sup (s ∩ t) ≀ Sup s βŠ“ Sup t := begin apply cSup_le hst, simp only [le_inf_iff, and_imp, set.mem_inter_eq], intros b _ _, split, apply le_cSup β€Ήbdd_above sβ€Ί β€Ήb ∈ sβ€Ί, apply le_cSup β€Ήbdd_above tβ€Ί β€Ήb ∈ tβ€Ί end /--The infimum of an intersection of two sets is bounded below by the maximum of the infima of each set, if all sets are bounded below and nonempty.-/ theorem le_cInf_inter (_ : bdd_below s) (_ : bdd_below t) (hst : (s ∩ t).nonempty) : Inf s βŠ” Inf t ≀ Inf (s ∩ t) := @cSup_inter_le (order_dual Ξ±) _ _ _ β€Ή_β€Ί β€Ή_β€Ί hst /-- The supremum of insert a s is the maximum of a and the supremum of s, if s is nonempty and bounded above.-/ theorem cSup_insert (hs : bdd_above s) (sne : s.nonempty) : Sup (insert a s) = a βŠ” Sup s := ((is_lub_cSup sne hs).insert a).cSup_eq (insert_nonempty a s) /-- The infimum of insert a s is the minimum of a and the infimum of s, if s is nonempty and bounded below.-/ theorem cInf_insert (hs : bdd_below s) (sne : s.nonempty) : Inf (insert a s) = a βŠ“ Inf s := @cSup_insert (order_dual Ξ±) _ _ _ hs sne @[simp] lemma cInf_Icc (h : a ≀ b) : Inf (Icc a b) = a := (is_glb_Icc h).cInf_eq (nonempty_Icc.2 h) @[simp] lemma cInf_Ici : Inf (Ici a) = a := is_least_Ici.cInf_eq @[simp] lemma cInf_Ico (h : a < b) : Inf (Ico a b) = a := (is_glb_Ico h).cInf_eq (nonempty_Ico.2 h) @[simp] lemma cInf_Ioc [densely_ordered Ξ±] (h : a < b) : Inf (Ioc a b) = a := (is_glb_Ioc h).cInf_eq (nonempty_Ioc.2 h) @[simp] lemma cInf_Ioi [no_top_order Ξ±] [densely_ordered Ξ±] : Inf (Ioi a) = a := cInf_eq_of_forall_ge_of_forall_gt_exists_lt nonempty_Ioi (Ξ» _, le_of_lt) (Ξ» w hw, by simpa using exists_between hw) @[simp] lemma cInf_Ioo [densely_ordered Ξ±] (h : a < b) : Inf (Ioo a b) = a := (is_glb_Ioo h).cInf_eq (nonempty_Ioo.2 h) @[simp] lemma cSup_Icc (h : a ≀ b) : Sup (Icc a b) = b := (is_lub_Icc h).cSup_eq (nonempty_Icc.2 h) @[simp] lemma cSup_Ico [densely_ordered Ξ±] (h : a < b) : Sup (Ico a b) = b := (is_lub_Ico h).cSup_eq (nonempty_Ico.2 h) @[simp] lemma cSup_Iic : Sup (Iic a) = a := is_greatest_Iic.cSup_eq @[simp] lemma cSup_Iio [no_bot_order Ξ±] [densely_ordered Ξ±] : Sup (Iio a) = a := cSup_eq_of_forall_le_of_forall_lt_exists_gt nonempty_Iio (Ξ» _, le_of_lt) (Ξ» w hw, by simpa [and_comm] using exists_between hw) @[simp] lemma cSup_Ioc (h : a < b) : Sup (Ioc a b) = b := (is_lub_Ioc h).cSup_eq (nonempty_Ioc.2 h) @[simp] lemma cSup_Ioo [densely_ordered Ξ±] (h : a < b) : Sup (Ioo a b) = b := (is_lub_Ioo h).cSup_eq (nonempty_Ioo.2 h) /--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/ lemma csupr_le_csupr {f g : ΞΉ β†’ Ξ±} (B : bdd_above (range g)) (H : βˆ€x, f x ≀ g x) : supr f ≀ supr g := begin classical, by_cases hΞΉ : nonempty ΞΉ, { have Rf : (range f).nonempty, { exactI range_nonempty _ }, apply cSup_le Rf, rintros y ⟨x, rfl⟩, have : g x ∈ range g := ⟨x, rfl⟩, exact le_cSup_of_le B this (H x) }, { have Rf : range f = βˆ…, from range_eq_empty.2 hΞΉ, have Rg : range g = βˆ…, from range_eq_empty.2 hΞΉ, unfold supr, rw [Rf, Rg] } end /--The indexed supremum of a function is bounded above by a uniform bound-/ lemma csupr_le [nonempty ΞΉ] {f : ΞΉ β†’ Ξ±} {c : Ξ±} (H : βˆ€x, f x ≀ c) : supr f ≀ c := cSup_le (range_nonempty f) (by rwa forall_range_iff) /--The indexed supremum of a function is bounded below by the value taken at one point-/ lemma le_csupr {f : ΞΉ β†’ Ξ±} (H : bdd_above (range f)) (c : ΞΉ) : f c ≀ supr f := le_cSup H (mem_range_self _) lemma le_csupr_of_le {f : ΞΉ β†’ Ξ±} (H : bdd_above (range f)) (c : ΞΉ) (h : a ≀ f c) : a ≀ supr f := le_trans h (le_csupr H c) /--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/ lemma cinfi_le_cinfi {f g : ΞΉ β†’ Ξ±} (B : bdd_below (range f)) (H : βˆ€x, f x ≀ g x) : infi f ≀ infi g := @csupr_le_csupr (order_dual Ξ±) _ _ _ _ B H /--The indexed minimum of a function is bounded below by a uniform lower bound-/ lemma le_cinfi [nonempty ΞΉ] {f : ΞΉ β†’ Ξ±} {c : Ξ±} (H : βˆ€x, c ≀ f x) : c ≀ infi f := @csupr_le (order_dual Ξ±) _ _ _ _ _ H /--The indexed infimum of a function is bounded above by the value taken at one point-/ lemma cinfi_le {f : ΞΉ β†’ Ξ±} (H : bdd_below (range f)) (c : ΞΉ) : infi f ≀ f c := @le_csupr (order_dual Ξ±) _ _ _ H c lemma cinfi_le_of_le {f : ΞΉ β†’ Ξ±} (H : bdd_below (range f)) (c : ΞΉ) (h : f c ≀ a) : infi f ≀ a := @le_csupr_of_le (order_dual Ξ±) _ _ _ _ H c h @[simp] theorem csupr_const [hΞΉ : nonempty ΞΉ] {a : Ξ±} : (⨆ b:ΞΉ, a) = a := by rw [supr, range_const, cSup_singleton] @[simp] theorem cinfi_const [hΞΉ : nonempty ΞΉ] {a : Ξ±} : (β¨… b:ΞΉ, a) = a := @csupr_const (order_dual Ξ±) _ _ _ _ theorem supr_unique [unique ΞΉ] {s : ΞΉ β†’ Ξ±} : (⨆ i, s i) = s (default ΞΉ) := have βˆ€ i, s i = s (default ΞΉ) := Ξ» i, congr_arg s (unique.eq_default i), by simp only [this, csupr_const] theorem infi_unique [unique ΞΉ] {s : ΞΉ β†’ Ξ±} : (β¨… i, s i) = s (default ΞΉ) := @supr_unique (order_dual Ξ±) _ _ _ _ @[simp] theorem supr_unit {f : unit β†’ Ξ±} : (⨆ x, f x) = f () := by { convert supr_unique, apply_instance } @[simp] theorem infi_unit {f : unit β†’ Ξ±} : (β¨… x, f x) = f () := @supr_unit (order_dual Ξ±) _ _ @[simp] lemma csupr_pos {p : Prop} {f : p β†’ Ξ±} (hp : p) : (⨆ h : p, f h) = f hp := by haveI := unique_prop hp; exact supr_unique @[simp] lemma cinfi_pos {p : Prop} {f : p β†’ Ξ±} (hp : p) : (β¨… h : p, f h) = f hp := @csupr_pos (order_dual Ξ±) _ _ _ hp /--Introduction rule to prove that `b` is the supremum of `f`: it suffices to check that `b` is larger than `f i` for all `i`, and that this is not the case of any `w<b`. See `supr_eq_of_forall_le_of_forall_lt_exists_gt` for a version in complete lattices. -/ theorem csupr_eq_of_forall_le_of_forall_lt_exists_gt [nonempty ΞΉ] {f : ΞΉ β†’ Ξ±} (h₁ : βˆ€ i, f i ≀ b) (hβ‚‚ : βˆ€ w, w < b β†’ (βˆƒ i, w < f i)) : (⨆ (i : ΞΉ), f i) = b := cSup_eq_of_forall_le_of_forall_lt_exists_gt (range_nonempty f) (forall_range_iff.mpr h₁) (Ξ» w hw, exists_range_iff.mpr $ hβ‚‚ w hw) /--Introduction rule to prove that `b` is the infimum of `f`: it suffices to check that `b` is smaller than `f i` for all `i`, and that this is not the case of any `w>b`. See `infi_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in complete lattices. -/ theorem cinfi_eq_of_forall_ge_of_forall_gt_exists_lt [nonempty ΞΉ] {f : ΞΉ β†’ Ξ±} (h₁ : βˆ€ i, b ≀ f i) (hβ‚‚ : βˆ€ w, b < w β†’ (βˆƒ i, f i < w)) : (β¨… (i : ΞΉ), f i) = b := @csupr_eq_of_forall_le_of_forall_lt_exists_gt (order_dual Ξ±) _ _ _ _ β€Ή_β€Ί β€Ή_β€Ί β€Ή_β€Ί /-- Nested intervals lemma: if `f` is a monotonically increasing sequence, `g` is a monotonically decreasing sequence, and `f n ≀ g n` for all `n`, then `⨆ n, f n` belongs to all the intervals `[f n, g n]`. -/ lemma csupr_mem_Inter_Icc_of_mono_incr_of_mono_decr [nonempty Ξ²] [semilattice_sup Ξ²] {f g : Ξ² β†’ Ξ±} (hf : monotone f) (hg : βˆ€ ⦃m n⦄, m ≀ n β†’ g n ≀ g m) (h : βˆ€ n, f n ≀ g n) : (⨆ n, f n) ∈ β‹‚ n, Icc (f n) (g n) := begin inhabit Ξ², refine mem_Inter.2 (Ξ» n, ⟨le_csupr ⟨g $ default Ξ², forall_range_iff.2 $ Ξ» m, _⟩ _, csupr_le $ Ξ» m, _⟩); exact forall_le_of_monotone_of_mono_decr hf hg h _ _ end /-- Nested intervals lemma: if `[f n, g n]` is a monotonically decreasing sequence of nonempty closed intervals, then `⨆ n, f n` belongs to all the intervals `[f n, g n]`. -/ lemma csupr_mem_Inter_Icc_of_mono_decr_Icc [nonempty Ξ²] [semilattice_sup Ξ²] {f g : Ξ² β†’ Ξ±} (h : βˆ€ ⦃m n⦄, m ≀ n β†’ Icc (f n) (g n) βŠ† Icc (f m) (g m)) (h' : βˆ€ n, f n ≀ g n) : (⨆ n, f n) ∈ β‹‚ n, Icc (f n) (g n) := csupr_mem_Inter_Icc_of_mono_incr_of_mono_decr (Ξ» m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).1) (Ξ» m n hmn, ((Icc_subset_Icc_iff (h' n)).1 (h hmn)).2) h' /-- Nested intervals lemma: if `[f n, g n]` is a monotonically decreasing sequence of nonempty closed intervals, then `⨆ n, f n` belongs to all the intervals `[f n, g n]`. -/ lemma csupr_mem_Inter_Icc_of_mono_decr_Icc_nat {f g : β„• β†’ Ξ±} (h : βˆ€ n, Icc (f (n + 1)) (g (n + 1)) βŠ† Icc (f n) (g n)) (h' : βˆ€ n, f n ≀ g n) : (⨆ n, f n) ∈ β‹‚ n, Icc (f n) (g n) := csupr_mem_Inter_Icc_of_mono_decr_Icc (@monotone_nat_of_le_succ (order_dual $ set Ξ±) _ (Ξ» n, Icc (f n) (g n)) h) h' end conditionally_complete_lattice instance pi.conditionally_complete_lattice {ΞΉ : Type*} {Ξ± : Ξ  i : ΞΉ, Type*} [Ξ  i, conditionally_complete_lattice (Ξ± i)] : conditionally_complete_lattice (Ξ  i, Ξ± i) := { le_cSup := Ξ» s f ⟨g, hg⟩ hf i, le_cSup ⟨g i, set.forall_range_iff.2 $ Ξ» ⟨f', hf'⟩, hg hf' i⟩ ⟨⟨f, hf⟩, rfl⟩, cSup_le := Ξ» s f hs hf i, cSup_le (by haveI := hs.to_subtype; apply range_nonempty) $ Ξ» b ⟨⟨g, hg⟩, hb⟩, hb β–Έ hf hg i, cInf_le := Ξ» s f ⟨g, hg⟩ hf i, cInf_le ⟨g i, set.forall_range_iff.2 $ Ξ» ⟨f', hf'⟩, hg hf' i⟩ ⟨⟨f, hf⟩, rfl⟩, le_cInf := Ξ» s f hs hf i, le_cInf (by haveI := hs.to_subtype; apply range_nonempty) $ Ξ» b ⟨⟨g, hg⟩, hb⟩, hb β–Έ hf hg i, .. pi.lattice, .. pi.has_Sup, .. pi.has_Inf } section conditionally_complete_linear_order variables [conditionally_complete_linear_order Ξ±] {s t : set Ξ±} {a b : Ξ±} lemma set.nonempty.cSup_mem (h : s.nonempty) (hs : finite s) : Sup s ∈ s := begin classical, revert h, apply finite.induction_on hs, { simp }, rintros a t hat t_fin ih -, rcases t.eq_empty_or_nonempty with rfl | ht, { simp }, { rw cSup_insert t_fin.bdd_above ht, by_cases ha : a ≀ Sup t, { simp [sup_eq_right.mpr ha, ih ht] }, { simp only [sup_eq_left, mem_insert_iff, (not_le.mp ha).le, true_or] } } end lemma finset.nonempty.cSup_mem {s : finset Ξ±} (h : s.nonempty) : Sup (s : set Ξ±) ∈ s := set.nonempty.cSup_mem h s.finite_to_set lemma set.nonempty.cInf_mem (h : s.nonempty) (hs : finite s) : Inf s ∈ s := @set.nonempty.cSup_mem (order_dual Ξ±) _ _ h hs lemma finset.nonempty.cInf_mem {s : finset Ξ±} (h : s.nonempty) : Inf (s : set Ξ±) ∈ s := set.nonempty.cInf_mem h s.finite_to_set /-- When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is a linear order. -/ lemma exists_lt_of_lt_cSup (hs : s.nonempty) (hb : b < Sup s) : βˆƒa∈s, b < a := begin classical, contrapose! hb, exact cSup_le hs hb end /-- Indexed version of the above lemma `exists_lt_of_lt_cSup`. When `b < supr f`, there is an element `i` such that `b < f i`. -/ lemma exists_lt_of_lt_csupr [nonempty ΞΉ] {f : ΞΉ β†’ Ξ±} (h : b < supr f) : βˆƒi, b < f i := let ⟨_, ⟨i, rfl⟩, h⟩ := exists_lt_of_lt_cSup (range_nonempty f) h in ⟨i, h⟩ /--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is a linear order.-/ lemma exists_lt_of_cInf_lt (hs : s.nonempty) (hb : Inf s < b) : βˆƒa∈s, a < b := @exists_lt_of_lt_cSup (order_dual Ξ±) _ _ _ hs hb /-- Indexed version of the above lemma `exists_lt_of_cInf_lt` When `infi f < a`, there is an element `i` such that `f i < a`. -/ lemma exists_lt_of_cinfi_lt [nonempty ΞΉ] {f : ΞΉ β†’ Ξ±} (h : infi f < a) : (βˆƒi, f i < a) := @exists_lt_of_lt_csupr (order_dual Ξ±) _ _ _ _ _ h /--Introduction rule to prove that b is the supremum of s: it suffices to check that 1) b is an upper bound 2) every other upper bound b' satisfies b ≀ b'.-/ theorem cSup_eq_of_is_forall_le_of_forall_le_imp_ge (_ : s.nonempty) (h_is_ub : βˆ€ a ∈ s, a ≀ b) (h_b_le_ub : βˆ€ub, (βˆ€ a ∈ s, a ≀ ub) β†’ (b ≀ ub)) : Sup s = b := le_antisymm (show Sup s ≀ b, from cSup_le β€Ήs.nonemptyβ€Ί h_is_ub) (show b ≀ Sup s, from h_b_le_ub _ $ assume a, le_cSup ⟨b, h_is_ub⟩) end conditionally_complete_linear_order section conditionally_complete_linear_order_bot variables [conditionally_complete_linear_order_bot Ξ±] lemma cSup_empty : (Sup βˆ… : Ξ±) = βŠ₯ := conditionally_complete_linear_order_bot.cSup_empty @[simp] lemma csupr_neg {p : Prop} {f : p β†’ Ξ±} (hp : Β¬ p) : (⨆ h : p, f h) = βŠ₯ := begin have : Β¬nonempty p := by simp [hp], rw [supr, range_eq_empty.mpr this, cSup_empty], end end conditionally_complete_linear_order_bot namespace nat open_locale classical noncomputable instance : has_Inf β„• := ⟨λs, if h : βˆƒn, n ∈ s then @nat.find (Ξ»n, n ∈ s) _ h else 0⟩ noncomputable instance : has_Sup β„• := ⟨λs, if h : βˆƒn, βˆ€a∈s, a ≀ n then @nat.find (Ξ»n, βˆ€a∈s, a ≀ n) _ h else 0⟩ lemma Inf_def {s : set β„•} (h : s.nonempty) : Inf s = @nat.find (Ξ»n, n ∈ s) _ h := dif_pos _ lemma Sup_def {s : set β„•} (h : βˆƒn, βˆ€a∈s, a ≀ n) : Sup s = @nat.find (Ξ»n, βˆ€a∈s, a ≀ n) _ h := dif_pos _ @[simp] lemma Inf_eq_zero {s : set β„•} : Inf s = 0 ↔ 0 ∈ s ∨ s = βˆ… := begin cases eq_empty_or_nonempty s, { subst h, simp only [or_true, eq_self_iff_true, iff_true, Inf, has_Inf.Inf, mem_empty_eq, exists_false, dif_neg, not_false_iff] }, { have := ne_empty_iff_nonempty.mpr h, simp only [this, or_false, nat.Inf_def, h, nat.find_eq_zero] } end lemma Inf_mem {s : set β„•} (h : s.nonempty) : Inf s ∈ s := by { rw [nat.Inf_def h], exact nat.find_spec h } lemma not_mem_of_lt_Inf {s : set β„•} {m : β„•} (hm : m < Inf s) : m βˆ‰ s := begin cases eq_empty_or_nonempty s, { subst h, apply not_mem_empty }, { rw [nat.Inf_def h] at hm, exact nat.find_min h hm } end protected lemma Inf_le {s : set β„•} {m : β„•} (hm : m ∈ s) : Inf s ≀ m := by { rw [nat.Inf_def ⟨m, hm⟩], exact nat.find_min' ⟨m, hm⟩ hm } lemma nonempty_of_pos_Inf {s : set β„•} (h : 0 < Inf s) : s.nonempty := begin by_contradiction contra, rw set.not_nonempty_iff_eq_empty at contra, have h' : Inf s β‰  0, { exact ne_of_gt h, }, apply h', rw nat.Inf_eq_zero, right, assumption, end lemma nonempty_of_Inf_eq_succ {s : set β„•} {k : β„•} (h : Inf s = k + 1) : s.nonempty := nonempty_of_pos_Inf (h.symm β–Έ (succ_pos k) : Inf s > 0) lemma eq_Ici_of_nonempty_of_upward_closed {s : set β„•} (hs : s.nonempty) (hs' : βˆ€ (k₁ kβ‚‚ : β„•), k₁ ≀ kβ‚‚ β†’ k₁ ∈ s β†’ kβ‚‚ ∈ s) : s = Ici (Inf s) := ext (Ξ» n, ⟨λ H, nat.Inf_le H, Ξ» H, hs' (Inf s) n H (Inf_mem hs)⟩) lemma Inf_upward_closed_eq_succ_iff {s : set β„•} (hs : βˆ€ (k₁ kβ‚‚ : β„•), k₁ ≀ kβ‚‚ β†’ k₁ ∈ s β†’ kβ‚‚ ∈ s) (k : β„•) : Inf s = k + 1 ↔ k + 1 ∈ s ∧ k βˆ‰ s := begin split, { intro H, rw [eq_Ici_of_nonempty_of_upward_closed (nonempty_of_Inf_eq_succ H) hs, H, mem_Ici, mem_Ici], exact ⟨le_refl _, k.not_succ_le_self⟩, }, { rintro ⟨H, H'⟩, rw [Inf_def (⟨_, H⟩ : s.nonempty), find_eq_iff], exact ⟨H, Ξ» n hnk hns, H' $ hs n k (lt_succ_iff.mp hnk) hns⟩, }, end /-- This instance is necessary, otherwise the lattice operations would be derived via conditionally_complete_linear_order_bot and marked as noncomputable. -/ instance : lattice β„• := lattice_of_linear_order noncomputable instance : conditionally_complete_linear_order_bot β„• := { Sup := Sup, Inf := Inf, le_cSup := assume s a hb ha, by rw [Sup_def hb]; revert a ha; exact @nat.find_spec _ _ hb, cSup_le := assume s a hs ha, by rw [Sup_def ⟨a, ha⟩]; exact nat.find_min' _ ha, le_cInf := assume s a hs hb, by rw [Inf_def hs]; exact hb (@nat.find_spec (Ξ»n, n ∈ s) _ _), cInf_le := assume s a hb ha, by rw [Inf_def ⟨a, ha⟩]; exact nat.find_min' _ ha, cSup_empty := begin simp only [Sup_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff, exists_const], apply bot_unique (nat.find_min' _ _), trivial end, .. (infer_instance : order_bot β„•), .. (lattice_of_linear_order : lattice β„•), .. (infer_instance : linear_order β„•) } end nat namespace with_top open_locale classical variables [conditionally_complete_linear_order_bot Ξ±] /-- The Sup of a non-empty set is its least upper bound for a conditionally complete lattice with a top. -/ lemma is_lub_Sup' {Ξ² : Type*} [conditionally_complete_lattice Ξ²] {s : set (with_top Ξ²)} (hs : s.nonempty) : is_lub s (Sup s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { contradiction }, apply some_le_some.2, exact le_cSup h_1 ha }, { intros _ _, exact le_top } }, { show ite _ _ _ ∈ _, split_ifs, { rintro (⟨⟩|a) ha, { exact _root_.le_refl _ }, { exact false.elim (not_top_le_coe a (ha h)) } }, { rintro (⟨⟩|b) hb, { exact le_top }, refine some_le_some.2 (cSup_le _ _), { rcases hs with ⟨⟨⟩|b, hb⟩, { exact absurd hb h }, { exact ⟨b, hb⟩ } }, { intros a ha, exact some_le_some.1 (hb ha) } }, { rintro (⟨⟩|b) hb, { exact _root_.le_refl _ }, { exfalso, apply h_1, use b, intros a ha, exact some_le_some.1 (hb ha) } } } end lemma is_lub_Sup (s : set (with_top Ξ±)) : is_lub s (Sup s) := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, show is_lub βˆ… (ite _ _ _), split_ifs, { cases h }, { rw [preimage_empty, cSup_empty], exact is_lub_empty }, { exfalso, apply h_1, use βŠ₯, rintro a ⟨⟩ } }, exact is_lub_Sup' hs, end /-- The Inf of a bounded-below set is its greatest lower bound for a conditionally complete lattice with a top. -/ lemma is_glb_Inf' {Ξ² : Type*} [conditionally_complete_lattice Ξ²] {s : set (with_top Ξ²)} (hs : bdd_below s) : is_glb s (Inf s) := begin split, { show ite _ _ _ ∈ _, split_ifs, { intros a ha, exact top_le_iff.2 (set.mem_singleton_iff.1 (h ha)) }, { rintro (⟨⟩|a) ha, { exact le_top }, refine some_le_some.2 (cInf_le _ ha), rcases hs with ⟨⟨⟩|b, hb⟩, { exfalso, apply h, intros c hc, rw [mem_singleton_iff, ←top_le_iff], exact hb hc }, use b, intros c hc, exact some_le_some.1 (hb hc) } }, { show ite _ _ _ ∈ _, split_ifs, { intros _ _, exact le_top }, { rintro (⟨⟩|a) ha, { exfalso, apply h, intros b hb, exact set.mem_singleton_iff.2 (top_le_iff.1 (ha hb)) }, { refine some_le_some.2 (le_cInf _ _), { classical, contrapose! h, rintros (⟨⟩|a) ha, { exact mem_singleton ⊀ }, { exact (h ⟨a, ha⟩).elim }}, { intros b hb, rw ←some_le_some, exact ha hb } } } } end lemma is_glb_Inf (s : set (with_top Ξ±)) : is_glb s (Inf s) := begin by_cases hs : bdd_below s, { exact is_glb_Inf' hs }, { exfalso, apply hs, use βŠ₯, intros _ _, exact bot_le }, end noncomputable instance : complete_linear_order (with_top Ξ±) := { Sup := Sup, le_Sup := assume s, (is_lub_Sup s).1, Sup_le := assume s, (is_lub_Sup s).2, Inf := Inf, le_Inf := assume s, (is_glb_Inf s).2, Inf_le := assume s, (is_glb_Inf s).1, decidable_le := classical.dec_rel _, .. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma coe_Sup {s : set Ξ±} (hb : bdd_above s) : (↑(Sup s) : with_top Ξ±) = (⨆a∈s, ↑a) := begin cases s.eq_empty_or_nonempty with hs hs, { rw [hs, cSup_empty], simp only [set.mem_empty_eq, supr_bot, supr_false], refl }, apply le_antisymm, { refine (coe_le_iff.2 $ assume b hb, cSup_le hs $ assume a has, coe_le_coe.1 $ hb β–Έ _), exact (le_supr_of_le a $ le_supr_of_le has $ _root_.le_refl _) }, { exact (supr_le $ assume a, supr_le $ assume ha, coe_le_coe.2 $ le_cSup hb ha) } end lemma coe_Inf {s : set Ξ±} (hs : s.nonempty) : (↑(Inf s) : with_top Ξ±) = (β¨…a∈s, ↑a) := let ⟨x, hx⟩ := hs in have (β¨…a∈s, ↑a : with_top Ξ±) ≀ x, from infi_le_of_le x $ infi_le_of_le hx $ _root_.le_refl _, let ⟨r, r_eq, hr⟩ := le_coe_iff.1 this in le_antisymm (le_infi $ assume a, le_infi $ assume ha, coe_le_coe.2 $ cInf_le (order_bot.bdd_below s) ha) begin refine (r_eq.symm β–Έ coe_le_coe.2 $ le_cInf hs $ assume a has, coe_le_coe.1 $ _), refine (r_eq β–Έ infi_le_of_le a _), exact (infi_le_of_le has $ _root_.le_refl _), end end with_top namespace enat open_locale classical noncomputable instance : complete_linear_order enat := { Sup := Ξ» s, with_top_equiv.symm $ Sup (with_top_equiv '' s), Inf := Ξ» s, with_top_equiv.symm $ Inf (with_top_equiv '' s), le_Sup := by intros; rw ← with_top_equiv_le; simp; apply le_Sup _; simpa, Inf_le := by intros; rw ← with_top_equiv_le; simp; apply Inf_le _; simpa, Sup_le := begin intros s a h1, rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm], apply Sup_le _, rintros b ⟨x, h2, rfl⟩, rw with_top_equiv_le, apply h1, assumption end, le_Inf := begin intros s a h1, rw [← with_top_equiv_le, with_top_equiv.right_inverse_symm], apply le_Inf _, rintros b ⟨x, h2, rfl⟩, rw with_top_equiv_le, apply h1, assumption end, ..enat.linear_order, ..enat.bounded_lattice } end enat namespace monotone variables [preorder Ξ±] [conditionally_complete_lattice Ξ²] {f : Ξ± β†’ Ξ²} (h_mono : monotone f) /-! A monotone function into a conditionally complete lattice preserves the ordering properties of `Sup` and `Inf`. -/ lemma le_cSup_image {s : set Ξ±} {c : Ξ±} (hcs : c ∈ s) (h_bdd : bdd_above s) : f c ≀ Sup (f '' s) := le_cSup (map_bdd_above h_mono h_bdd) (mem_image_of_mem f hcs) lemma cSup_image_le {s : set Ξ±} (hs : s.nonempty) {B : Ξ±} (hB: B ∈ upper_bounds s) : Sup (f '' s) ≀ f B := cSup_le (nonempty.image f hs) (h_mono.mem_upper_bounds_image hB) lemma cInf_image_le {s : set Ξ±} {c : Ξ±} (hcs : c ∈ s) (h_bdd : bdd_below s) : Inf (f '' s) ≀ f c := @le_cSup_image (order_dual Ξ±) (order_dual Ξ²) _ _ _ (Ξ» x y hxy, h_mono hxy) _ _ hcs h_bdd lemma le_cInf_image {s : set Ξ±} (hs : s.nonempty) {B : Ξ±} (hB: B ∈ lower_bounds s) : f B ≀ Inf (f '' s) := @cSup_image_le (order_dual Ξ±) (order_dual Ξ²) _ _ _ (Ξ» x y hxy, h_mono hxy) _ hs _ hB end monotone namespace galois_connection variables {Ξ³ : Type*} [conditionally_complete_lattice Ξ±] [conditionally_complete_lattice Ξ²] [nonempty ΞΉ] {l : Ξ± β†’ Ξ²} {u : Ξ² β†’ Ξ±} lemma l_cSup (gc : galois_connection l u) {s : set Ξ±} (hne : s.nonempty) (hbdd : bdd_above s) : l (Sup s) = ⨆ x : s, l x := eq.symm $ is_lub.csupr_set_eq (gc.is_lub_l_image $ is_lub_cSup hne hbdd) hne lemma l_csupr (gc : galois_connection l u) {f : ΞΉ β†’ Ξ±} (hf : bdd_above (range f)) : l (⨆ i, f i) = ⨆ i, l (f i) := by rw [supr, gc.l_cSup (range_nonempty _) hf, supr_range'] lemma l_csupr_set (gc : galois_connection l u) {s : set Ξ³} {f : Ξ³ β†’ Ξ±} (hf : bdd_above (f '' s)) (hne : s.nonempty) : l (⨆ i : s, f i) = ⨆ i : s, l (f i) := by { haveI := hne.to_subtype, rw image_eq_range at hf, exact gc.l_csupr hf } lemma u_cInf (gc : galois_connection l u) {s : set Ξ²} (hne : s.nonempty) (hbdd : bdd_below s) : u (Inf s) = β¨… x : s, u x := gc.dual.l_cSup hne hbdd lemma u_cinfi (gc : galois_connection l u) {f : ΞΉ β†’ Ξ²} (hf : bdd_below (range f)) : u (β¨… i, f i) = β¨… i, u (f i) := gc.dual.l_csupr hf lemma u_cinfi_set (gc : galois_connection l u) {s : set Ξ³} {f : Ξ³ β†’ Ξ²} (hf : bdd_below (f '' s)) (hne : s.nonempty) : u (β¨… i : s, f i) = β¨… i : s, u (f i) := gc.dual.l_csupr_set hf hne end galois_connection namespace order_iso variables {Ξ³ : Type*} [conditionally_complete_lattice Ξ±] [conditionally_complete_lattice Ξ²] [nonempty ΞΉ] lemma map_cSup (e : Ξ± ≃o Ξ²) {s : set Ξ±} (hne : s.nonempty) (hbdd : bdd_above s) : e (Sup s) = ⨆ x : s, e x := e.to_galois_connection.l_cSup hne hbdd lemma map_csupr (e : Ξ± ≃o Ξ²) {f : ΞΉ β†’ Ξ±} (hf : bdd_above (range f)) : e (⨆ i, f i) = ⨆ i, e (f i) := e.to_galois_connection.l_csupr hf lemma map_csupr_set (e : Ξ± ≃o Ξ²) {s : set Ξ³} {f : Ξ³ β†’ Ξ±} (hf : bdd_above (f '' s)) (hne : s.nonempty) : e (⨆ i : s, f i) = ⨆ i : s, e (f i) := e.to_galois_connection.l_csupr_set hf hne lemma map_cInf (e : Ξ± ≃o Ξ²) {s : set Ξ±} (hne : s.nonempty) (hbdd : bdd_below s) : e (Inf s) = β¨… x : s, e x := e.dual.map_cSup hne hbdd lemma map_cinfi (e : Ξ± ≃o Ξ²) {f : ΞΉ β†’ Ξ±} (hf : bdd_below (range f)) : e (β¨… i, f i) = β¨… i, e (f i) := e.dual.map_csupr hf lemma map_cinfi_set (e : Ξ± ≃o Ξ²) {s : set Ξ³} {f : Ξ³ β†’ Ξ±} (hf : bdd_below (f '' s)) (hne : s.nonempty) : e (β¨… i : s, f i) = β¨… i : s, e (f i) := e.dual.map_csupr_set hf hne end order_iso /-! ### Relation between `Sup` / `Inf` and `finset.sup'` / `finset.inf'` Like the `Sup` of a `conditionally_complete_lattice`, `finset.sup'` also requires the set to be non-empty. As a result, we can translate between the two. -/ namespace finset lemma sup'_eq_cSup_image [conditionally_complete_lattice Ξ²] (s : finset Ξ±) (H) (f : Ξ± β†’ Ξ²) : s.sup' H f = Sup (f '' s) := begin apply le_antisymm, { refine (finset.sup'_le _ _ $ Ξ» a ha, _), refine le_cSup ⟨s.sup' H f, _⟩ ⟨a, ha, rfl⟩, rintros i ⟨j, hj, rfl⟩, exact finset.le_sup' _ hj }, { apply cSup_le ((coe_nonempty.mpr H).image _), rintros _ ⟨a, ha, rfl⟩, exact finset.le_sup' _ ha, } end lemma inf'_eq_cInf_image [conditionally_complete_lattice Ξ²] (s : finset Ξ±) (H) (f : Ξ± β†’ Ξ²) : s.inf' H f = Inf (f '' s) := @sup'_eq_cSup_image _ (order_dual Ξ²) _ _ _ _ lemma sup'_id_eq_cSup [conditionally_complete_lattice Ξ±] (s : finset Ξ±) (H) : s.sup' H id = Sup s := by rw [sup'_eq_cSup_image s H, set.image_id] lemma inf'_id_eq_cInf [conditionally_complete_lattice Ξ±] (s : finset Ξ±) (H) : s.inf' H id = Inf s := @sup'_id_eq_cSup (order_dual Ξ±) _ _ _ end finset section with_top_bot /-! ### Complete lattice structure on `with_top (with_bot Ξ±)` If `Ξ±` is a `conditionally_complete_lattice`, then we show that `with_top Ξ±` and `with_bot Ξ±` also inherit the structure of conditionally complete lattices. Furthermore, we show that `with_top (with_bot Ξ±)` naturally inherits the structure of a complete lattice. Note that for Ξ± a conditionally complete lattice, `Sup` and `Inf` both return junk values for sets which are empty or unbounded. The extension of `Sup` to `with_top Ξ±` fixes the unboundedness problem and the extension to `with_bot Ξ±` fixes the problem with the empty set. This result can be used to show that the extended reals [-∞, ∞] are a complete lattice. -/ open_locale classical /-- Adding a top element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_top.conditionally_complete_lattice {Ξ± : Type*} [conditionally_complete_lattice Ξ±] : conditionally_complete_lattice (with_top Ξ±) := { le_cSup := Ξ» S a hS haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS, cSup_le := Ξ» S a hS haS, (with_top.is_lub_Sup' hS).2 haS, cInf_le := Ξ» S a hS haS, (with_top.is_glb_Inf' hS).1 haS, le_cInf := Ξ» S a hS haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.lattice, ..with_top.has_Sup, ..with_top.has_Inf } /-- Adding a bottom element to a conditionally complete lattice gives a conditionally complete lattice -/ noncomputable instance with_bot.conditionally_complete_lattice {Ξ± : Type*} [conditionally_complete_lattice Ξ±] : conditionally_complete_lattice (with_bot Ξ±) := { le_cSup := (@with_top.conditionally_complete_lattice (order_dual Ξ±) _).cInf_le, cSup_le := (@with_top.conditionally_complete_lattice (order_dual Ξ±) _).le_cInf, cInf_le := (@with_top.conditionally_complete_lattice (order_dual Ξ±) _).le_cSup, le_cInf := (@with_top.conditionally_complete_lattice (order_dual Ξ±) _).cSup_le, ..with_bot.lattice, ..with_bot.has_Sup, ..with_bot.has_Inf } /-- Adding a bottom and a top to a conditionally complete lattice gives a bounded lattice-/ noncomputable instance with_top.with_bot.bounded_lattice {Ξ± : Type*} [conditionally_complete_lattice Ξ±] : bounded_lattice (with_top (with_bot Ξ±)) := { ..with_top.order_bot, ..with_top.order_top, ..conditionally_complete_lattice.to_lattice _ } noncomputable instance with_top.with_bot.complete_lattice {Ξ± : Type*} [conditionally_complete_lattice Ξ±] : complete_lattice (with_top (with_bot Ξ±)) := { le_Sup := Ξ» S a haS, (with_top.is_lub_Sup' ⟨a, haS⟩).1 haS, Sup_le := Ξ» S a ha, begin cases S.eq_empty_or_nonempty with h, { show ite _ _ _ ≀ a, split_ifs, { rw h at h_1, cases h_1 }, { convert bot_le, convert with_bot.cSup_empty, rw h, refl }, { exfalso, apply h_2, use βŠ₯, rw h, rintro b ⟨⟩ } }, { refine (with_top.is_lub_Sup' h).2 ha } end, Inf_le := Ξ» S a haS, show ite _ _ _ ≀ a, begin split_ifs, { cases a with a, exact _root_.le_refl _, cases (h haS); tauto }, { cases a, { exact le_top }, { apply with_top.some_le_some.2, refine cInf_le _ haS, use βŠ₯, intros b hb, exact bot_le } } end, le_Inf := Ξ» S a haS, (with_top.is_glb_Inf' ⟨a, haS⟩).2 haS, ..with_top.has_Inf, ..with_top.has_Sup, ..with_top.with_bot.bounded_lattice } noncomputable instance with_top.with_bot.complete_linear_order {Ξ± : Type*} [conditionally_complete_linear_order Ξ±] : complete_linear_order (with_top (with_bot Ξ±)) := { .. with_top.with_bot.complete_lattice, .. with_top.linear_order } end with_top_bot section subtype variables (s : set Ξ±) /-! ### Subtypes of conditionally complete linear orders In this section we give conditions on a subset of a conditionally complete linear order, to ensure that the subtype is itself conditionally complete. We check that an `ord_connected` set satisfies these conditions. TODO There are several possible variants; the `conditionally_complete_linear_order` could be changed to `conditionally_complete_linear_order_bot` or `complete_linear_order`. -/ open_locale classical section has_Sup variables [has_Sup Ξ±] /-- `has_Sup` structure on a nonempty subset `s` of an object with `has_Sup`. This definition is non-canonical (it uses `default s`); it should be used only as here, as an auxiliary instance in the construction of the `conditionally_complete_linear_order` structure. -/ noncomputable def subset_has_Sup [inhabited s] : has_Sup s := {Sup := Ξ» t, if ht : Sup (coe '' t : set Ξ±) ∈ s then ⟨Sup (coe '' t : set Ξ±), ht⟩ else default s} local attribute [instance] subset_has_Sup @[simp] lemma subset_Sup_def [inhabited s] : @Sup s _ = Ξ» t, if ht : Sup (coe '' t : set Ξ±) ∈ s then ⟨Sup (coe '' t : set Ξ±), ht⟩ else default s := rfl lemma subset_Sup_of_within [inhabited s] {t : set s} (h : Sup (coe '' t : set Ξ±) ∈ s) : Sup (coe '' t : set Ξ±) = (@Sup s _ t : Ξ±) := by simp [dif_pos h] end has_Sup section has_Inf variables [has_Inf Ξ±] /-- `has_Inf` structure on a nonempty subset `s` of an object with `has_Inf`. This definition is non-canonical (it uses `default s`); it should be used only as here, as an auxiliary instance in the construction of the `conditionally_complete_linear_order` structure. -/ noncomputable def subset_has_Inf [inhabited s] : has_Inf s := {Inf := Ξ» t, if ht : Inf (coe '' t : set Ξ±) ∈ s then ⟨Inf (coe '' t : set Ξ±), ht⟩ else default s} local attribute [instance] subset_has_Inf @[simp] lemma subset_Inf_def [inhabited s] : @Inf s _ = Ξ» t, if ht : Inf (coe '' t : set Ξ±) ∈ s then ⟨Inf (coe '' t : set Ξ±), ht⟩ else default s := rfl lemma subset_Inf_of_within [inhabited s] {t : set s} (h : Inf (coe '' t : set Ξ±) ∈ s) : Inf (coe '' t : set Ξ±) = (@Inf s _ t : Ξ±) := by simp [dif_pos h] end has_Inf variables [conditionally_complete_linear_order Ξ±] local attribute [instance] subset_has_Sup local attribute [instance] subset_has_Inf /-- For a nonempty subset of a conditionally complete linear order to be a conditionally complete linear order, it suffices that it contain the `Sup` of all its nonempty bounded-above subsets, and the `Inf` of all its nonempty bounded-below subsets. -/ noncomputable def subset_conditionally_complete_linear_order [inhabited s] (h_Sup : βˆ€ {t : set s} (ht : t.nonempty) (h_bdd : bdd_above t), Sup (coe '' t : set Ξ±) ∈ s) (h_Inf : βˆ€ {t : set s} (ht : t.nonempty) (h_bdd : bdd_below t), Inf (coe '' t : set Ξ±) ∈ s) : conditionally_complete_linear_order s := { le_cSup := begin rintros t c h_bdd hct, -- The following would be a more natural way to finish, but gives a "deep recursion" error: -- simpa [subset_Sup_of_within (h_Sup t)] using -- (strict_mono_coe s).monotone.le_cSup_image hct h_bdd, have := (subtype.mono_coe s).le_cSup_image hct h_bdd, rwa subset_Sup_of_within s (h_Sup ⟨c, hct⟩ h_bdd) at this, end, cSup_le := begin rintros t B ht hB, have := (subtype.mono_coe s).cSup_image_le ht hB, rwa subset_Sup_of_within s (h_Sup ht ⟨B, hB⟩) at this, end, le_cInf := begin intros t B ht hB, have := (subtype.mono_coe s).le_cInf_image ht hB, rwa subset_Inf_of_within s (h_Inf ht ⟨B, hB⟩) at this, end, cInf_le := begin rintros t c h_bdd hct, have := (subtype.mono_coe s).cInf_image_le hct h_bdd, rwa subset_Inf_of_within s (h_Inf ⟨c, hct⟩ h_bdd) at this, end, ..subset_has_Sup s, ..subset_has_Inf s, ..distrib_lattice.to_lattice s, ..(infer_instance : linear_order s) } section ord_connected /-- The `Sup` function on a nonempty `ord_connected` set `s` in a conditionally complete linear order takes values within `s`, for all nonempty bounded-above subsets of `s`. -/ lemma Sup_within_of_ord_connected {s : set Ξ±} [hs : ord_connected s] ⦃t : set s⦄ (ht : t.nonempty) (h_bdd : bdd_above t) : Sup (coe '' t : set Ξ±) ∈ s := begin obtain ⟨c, hct⟩ : βˆƒ c, c ∈ t := ht, obtain ⟨B, hB⟩ : βˆƒ B, B ∈ upper_bounds t := h_bdd, refine hs.out c.2 B.2 ⟨_, _⟩, { exact (subtype.mono_coe s).le_cSup_image hct ⟨B, hB⟩ }, { exact (subtype.mono_coe s).cSup_image_le ⟨c, hct⟩ hB }, end /-- The `Inf` function on a nonempty `ord_connected` set `s` in a conditionally complete linear order takes values within `s`, for all nonempty bounded-below subsets of `s`. -/ lemma Inf_within_of_ord_connected {s : set Ξ±} [hs : ord_connected s] ⦃t : set s⦄ (ht : t.nonempty) (h_bdd : bdd_below t) : Inf (coe '' t : set Ξ±) ∈ s := begin obtain ⟨c, hct⟩ : βˆƒ c, c ∈ t := ht, obtain ⟨B, hB⟩ : βˆƒ B, B ∈ lower_bounds t := h_bdd, refine hs.out B.2 c.2 ⟨_, _⟩, { exact (subtype.mono_coe s).le_cInf_image ⟨c, hct⟩ hB }, { exact (subtype.mono_coe s).cInf_image_le hct ⟨B, hB⟩ }, end /-- A nonempty `ord_connected` set in a conditionally complete linear order is naturally a conditionally complete linear order. -/ noncomputable instance ord_connected_subset_conditionally_complete_linear_order [inhabited s] [ord_connected s] : conditionally_complete_linear_order s := subset_conditionally_complete_linear_order s Sup_within_of_ord_connected Inf_within_of_ord_connected end ord_connected end subtype
1835f3ede0a49eaa8531bbb7d213ff4904691bf6
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/pnat/factors.lean
176e65dfc1cbd1bdb4340e697bfc8385031428f8
[ "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
13,940
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Neil Strickland -/ import data.pnat.basic import data.multiset import data.int.gcd import algebra.group /-- The type of multisets of prime numbers. Unique factorization gives an equivalence between this set and β„•+, as we will formalize below. -/ def prime_multiset := multiset nat.primes namespace prime_multiset instance : inhabited prime_multiset := by unfold prime_multiset; apply_instance instance : has_repr prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : canonically_ordered_add_monoid prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : distrib_lattice prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : semilattice_sup_bot prime_multiset := by { dsimp [prime_multiset], apply_instance } instance : has_sub prime_multiset := by { dsimp [prime_multiset], apply_instance } theorem add_sub_of_le {u v : prime_multiset} : u ≀ v β†’ u + (v - u) = v := multiset.add_sub_of_le /-- The multiset consisting of a single prime -/ def of_prime (p : nat.primes) : prime_multiset := (p :: 0) theorem card_of_prime (p : nat.primes) : multiset.card (of_prime p) = 1 := rfl /-- We can forget the primality property and regard a multiset of primes as just a multiset of positive integers, or a multiset of natural numbers. In the opposite direction, if we have a multiset of positive integers or natural numbers, together with a proof that all the elements are prime, then we can regard it as a multiset of primes. The next block of results records obvious properties of these coercions. -/ def to_nat_multiset : prime_multiset β†’ multiset β„• := Ξ» v, v.map (Ξ» p, (p : β„•)) instance coe_nat : has_coe prime_multiset (multiset β„•) := ⟨to_nat_multiset⟩ instance coe_nat_hom : is_add_monoid_hom (coe : prime_multiset β†’ multiset β„•) := by { unfold_coes, dsimp [to_nat_multiset], apply_instance } theorem coe_nat_inj : function.injective (coe : prime_multiset β†’ multiset β„•) := multiset.injective_map nat.primes.coe_nat_inj theorem coe_nat_of_prime (p : nat.primes) : ((of_prime p) : multiset β„•) = (p : β„•) :: 0 := rfl theorem coe_nat_prime (v : prime_multiset) (p : β„•) (h : p ∈ (v : multiset β„•)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq β–Έ hp' } def to_pnat_multiset : prime_multiset β†’ multiset β„•+ := Ξ» v, v.map (Ξ» p, (p : β„•+)) instance coe_pnat : has_coe prime_multiset (multiset β„•+) := ⟨to_pnat_multiset⟩ instance coe_pnat_hom : is_add_monoid_hom (coe : prime_multiset β†’ multiset β„•+) := by { unfold_coes, dsimp [to_pnat_multiset], apply_instance } theorem coe_pnat_inj : function.injective (coe : prime_multiset β†’ multiset β„•+) := multiset.injective_map nat.primes.coe_pnat_inj theorem coe_pnat_of_prime (p : nat.primes) : ((of_prime p) : multiset β„•+) = (p : β„•+) :: 0 := rfl theorem coe_pnat_prime (v : prime_multiset) (p : β„•+) (h : p ∈ (v : multiset β„•+)) : p.prime := by { rcases multiset.mem_map.mp h with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq β–Έ hp' } instance coe_multiset_pnat_nat : has_coe (multiset β„•+) (multiset β„•) := ⟨λ v, v.map (Ξ» n, (n : β„•))⟩ theorem coe_pnat_nat (v : prime_multiset) : ((v : (multiset β„•+)) : (multiset β„•)) = (v : multiset β„•) := by { change (v.map (coe : nat.primes β†’ β„•+)).map subtype.val = v.map subtype.val, rw [multiset.map_map], congr } def prod (v : prime_multiset) : β„•+ := (v : multiset pnat).prod theorem coe_prod (v : prime_multiset) : (v.prod : β„•) = (v : multiset β„•).prod := begin let h : (v.prod : β„•) = ((v.map coe).map coe).prod := (v.to_pnat_multiset.prod_hom coe).symm, rw [multiset.map_map] at h, have : (coe : β„•+ β†’ β„•) ∘ (coe : nat.primes β†’ β„•+) = coe := funext (Ξ» p, rfl), rw[this] at h, exact h, end theorem prod_of_prime (p : nat.primes) : (of_prime p).prod = (p : β„•+) := by { change multiset.prod ((p : β„•+) :: 0) = (p : β„•+), rw [multiset.prod_cons, multiset.prod_zero, mul_one] } def of_nat_multiset (v : multiset β„•) (h : βˆ€ (p : β„•), p ∈ v β†’ p.prime) : prime_multiset := @multiset.pmap β„• nat.primes nat.prime (Ξ» p hp, ⟨p, hp⟩) v h theorem to_of_nat_multiset (v : multiset β„•) (h) : ((of_nat_multiset v h) : multiset β„•) = v := begin unfold_coes, dsimp [of_nat_multiset, to_nat_multiset], have : (Ξ» (p : β„•) (h : p.prime), ((⟨p, h⟩ : nat.primes) : β„•)) = (Ξ» p h, id p) := by {funext p h, refl}, rw [multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_nat_multiset (v : multiset β„•) (h) : ((of_nat_multiset v h).prod : β„•) = (v.prod : β„•) := by rw[coe_prod, to_of_nat_multiset] def of_pnat_multiset (v : multiset β„•+) (h : βˆ€ (p : β„•+), p ∈ v β†’ p.prime) : prime_multiset := @multiset.pmap β„•+ nat.primes pnat.prime (Ξ» p hp, ⟨(p : β„•), hp⟩) v h theorem to_of_pnat_multiset (v : multiset β„•+) (h) : ((of_pnat_multiset v h) : multiset β„•+) = v := begin unfold_coes, dsimp[of_pnat_multiset, to_pnat_multiset], have : (Ξ» (p : β„•+) (h : p.prime), ((coe : nat.primes β†’ β„•+) ⟨p, h⟩)) = (Ξ» p h, id p) := by {funext p h, apply subtype.eq, refl}, rw[multiset.map_pmap, this, multiset.pmap_eq_map, multiset.map_id] end theorem prod_of_pnat_multiset (v : multiset β„•+) (h) : ((of_pnat_multiset v h).prod : β„•+) = v.prod := by { dsimp [prod], rw [to_of_pnat_multiset] } /-- Lists can be coerced to multisets; here we have some results about how this interacts with our constructions on multisets. -/ def of_nat_list (l : list β„•) (h : βˆ€ (p : β„•), p ∈ l β†’ p.prime) : prime_multiset := of_nat_multiset (l : multiset β„•) h theorem prod_of_nat_list (l : list β„•) (h) : ((of_nat_list l h).prod : β„•) = l.prod := by { have := prod_of_nat_multiset (l : multiset β„•) h, rw [multiset.coe_prod] at this, exact this } def of_pnat_list (l : list β„•+) (h : βˆ€ (p : β„•+), p ∈ l β†’ p.prime) : prime_multiset := of_pnat_multiset (l : multiset β„•+) h theorem prod_of_pnat_list (l : list β„•+) (h) : (of_pnat_list l h).prod = l.prod := by { have := prod_of_pnat_multiset (l : multiset β„•+) h, rw [multiset.coe_prod] at this, exact this } /-- The product map gives a homomorphism from the additive monoid of multisets to the multiplicative monoid β„•+. -/ theorem prod_zero : (0 : prime_multiset).prod = 1 := by { dsimp [prod], exact multiset.prod_zero } theorem prod_add (u v : prime_multiset) : (u + v).prod = u.prod * v.prod := by { dsimp [prod], rw [is_add_monoid_hom.map_add (coe : prime_multiset β†’ multiset β„•+)], rw [multiset.prod_add] } theorem prod_smul (d : β„•) (u : prime_multiset) : (add_monoid.smul d u).prod = u.prod ^ d := by { induction d with d ih, refl, rw[succ_smul, prod_add, ih, nat.succ_eq_add_one, pow_succ, mul_comm] } end prime_multiset namespace pnat /-- The prime factors of n, regarded as a multiset -/ def factor_multiset (n : β„•+) : prime_multiset := prime_multiset.of_nat_list (nat.factors n) (@nat.mem_factors n) /-- The product of the factors is the original number -/ theorem prod_factor_multiset (n : β„•+) : (factor_multiset n).prod = n := eq $ by { dsimp [factor_multiset], rw [prime_multiset.prod_of_nat_list], exact nat.prod_factors n.pos } theorem coe_nat_factor_multiset (n : β„•+) : ((factor_multiset n) : (multiset β„•)) = ((nat.factors n) : multiset β„•) := prime_multiset.to_of_nat_multiset (nat.factors n) (@nat.mem_factors n) end pnat namespace prime_multiset /-- If we start with a multiset of primes, take the product and then factor it, we get back the original multiset. -/ theorem factor_multiset_prod (v : prime_multiset) : v.prod.factor_multiset = v := begin apply prime_multiset.coe_nat_inj, rw [v.prod.coe_nat_factor_multiset, prime_multiset.coe_prod], rcases v with l, unfold_coes, dsimp [prime_multiset.to_nat_multiset], rw [multiset.coe_prod], let l' := l.map (coe : nat.primes β†’ β„•), have : βˆ€ (p : β„•), p ∈ l' β†’ p.prime := Ξ» p hp, by {rcases list.mem_map.mp hp with ⟨⟨p', hp'⟩, ⟨h_mem, h_eq⟩⟩, exact h_eq β–Έ hp'}, exact multiset.coe_eq_coe.mpr (@nat.factors_unique _ l' rfl this).symm, end end prime_multiset namespace pnat /-- Positive integers biject with multisets of primes. -/ def factor_multiset_equiv : β„•+ ≃ prime_multiset := { to_fun := factor_multiset, inv_fun := prime_multiset.prod, left_inv := prod_factor_multiset, right_inv := prime_multiset.factor_multiset_prod } /-- Factoring gives a homomorphism from the multiplicative monoid β„•+ to the additive monoid of multisets. -/ theorem factor_multiset_one : factor_multiset 1 = 0 := rfl theorem factor_multiset_mul (n m : β„•+) : factor_multiset (n * m) = (factor_multiset n) + (factor_multiset m) := begin let u := factor_multiset n, let v := factor_multiset m, have : n = u.prod := (prod_factor_multiset n).symm, rw[this], have : m = v.prod := (prod_factor_multiset m).symm, rw[this], rw[← prime_multiset.prod_add], repeat {rw[prime_multiset.factor_multiset_prod]}, end theorem factor_multiset_pow (n : β„•+) (m : β„•) : factor_multiset (n ^ m) = add_monoid.smul m (factor_multiset n) := begin let u := factor_multiset n, have : n = u.prod := (prod_factor_multiset n).symm, rw[this, ← prime_multiset.prod_smul], repeat {rw[prime_multiset.factor_multiset_prod]}, end /-- Factoring a prime gives the corresponding one-element multiset. -/ theorem factor_multiset_of_prime (p : nat.primes) : (p : β„•+).factor_multiset = prime_multiset.of_prime p := begin apply factor_multiset_equiv.symm.injective, change (p : β„•+).factor_multiset.prod = (prime_multiset.of_prime p).prod, rw[(p : β„•+).prod_factor_multiset, prime_multiset.prod_of_prime], end /-- We now have four different results that all encode the idea that inequality of multisets corresponds to divisibility of positive integers. -/ theorem factor_multiset_le_iff {m n : β„•+} : factor_multiset m ≀ factor_multiset n ↔ m ∣ n := begin split, { intro h, rw [← prod_factor_multiset m, ← prod_factor_multiset m], apply dvd_intro (n.factor_multiset - m.factor_multiset).prod, rw [← prime_multiset.prod_add, prime_multiset.factor_multiset_prod, prime_multiset.add_sub_of_le h, prod_factor_multiset] }, { intro h, rw [← mul_div_exact h, factor_multiset_mul], exact le_add_right (le_refl _) } end theorem factor_multiset_le_iff' {m : β„•+} {v : prime_multiset}: factor_multiset m ≀ v ↔ m ∣ v.prod := by { let h := @factor_multiset_le_iff m v.prod, rw [v.factor_multiset_prod] at h, exact h } end pnat namespace prime_multiset theorem prod_dvd_iff {u v : prime_multiset} : u.prod ∣ v.prod ↔ u ≀ v := by { let h := @pnat.factor_multiset_le_iff' u.prod v, rw [u.factor_multiset_prod] at h, exact h.symm } theorem prod_dvd_iff' {u : prime_multiset} {n : β„•+} : u.prod ∣ n ↔ u ≀ n.factor_multiset := by { let h := @prod_dvd_iff u n.factor_multiset, rw [n.prod_factor_multiset] at h, exact h } end prime_multiset namespace pnat /-- The gcd and lcm operations on positive integers correspond to the inf and sup operations on multisets. -/ theorem factor_multiset_gcd (m n : β„•+) : factor_multiset (gcd m n) = (factor_multiset m) βŠ“ (factor_multiset n) := begin apply le_antisymm, { apply le_inf_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact gcd_dvd_left m n, exact gcd_dvd_right m n}, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply dvd_gcd; rw[prime_multiset.prod_dvd_iff'], exact inf_le_left, exact inf_le_right} end theorem factor_multiset_lcm (m n : β„•+) : factor_multiset (lcm m n) = (factor_multiset m) βŠ” (factor_multiset n) := begin apply le_antisymm, { rw[← prime_multiset.prod_dvd_iff, prod_factor_multiset], apply lcm_dvd; rw[← factor_multiset_le_iff'], exact le_sup_left, exact le_sup_right}, { apply sup_le_iff.mpr; split; apply factor_multiset_le_iff.mpr, exact dvd_lcm_left m n, exact dvd_lcm_right m n }, end /-- The number of occurrences of p in the factor multiset of m is the same as the p-adic valuation of m. -/ theorem count_factor_multiset (m : β„•+) (p : nat.primes) (k : β„•) : (p : β„•+) ^ k ∣ m ↔ k ≀ m.factor_multiset.count p := begin intros, rw [multiset.le_count_iff_repeat_le], rw [← factor_multiset_le_iff, factor_multiset_pow, factor_multiset_of_prime], congr' 2, apply multiset.eq_repeat.mpr, split, { rw [multiset.card_smul, prime_multiset.card_of_prime, mul_one] }, { have : βˆ€ (m : β„•), add_monoid.smul m (p::0) = multiset.repeat p m := Ξ» m, by {induction m with m ih, { refl }, rw [succ_smul, multiset.repeat_succ, ih], rw[multiset.cons_add, zero_add] }, intros q h, rw [prime_multiset.of_prime, this k] at h, exact multiset.eq_of_mem_repeat h } end end pnat namespace prime_multiset theorem prod_inf (u v : prime_multiset) : (u βŠ“ v).prod = pnat.gcd u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u βŠ“ v).prod = pnat.gcd n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw [← pnat.factor_multiset_gcd n m, pnat.prod_factor_multiset] end theorem prod_sup (u v : prime_multiset) : (u βŠ” v).prod = pnat.lcm u.prod v.prod := begin let n := u.prod, let m := v.prod, change (u βŠ” v).prod = pnat.lcm n m, have : u = n.factor_multiset := u.factor_multiset_prod.symm, rw [this], have : v = m.factor_multiset := v.factor_multiset_prod.symm, rw [this], rw[← pnat.factor_multiset_lcm n m, pnat.prod_factor_multiset] end end prime_multiset
b6bac2142f1bc218e6a6413d68a1c8d567f539b6
8c02fed42525b65813b55c064afe2484758d6d09
/src/proptest.lean
6988de6a29a583123ad92908bfeb803dec29753e
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
microsoft/AliveInLean
3eac351a34154efedd3ffc4fe2fa4ec01b219e0d
4b739dd6e4266b26a045613849df221374119871
refs/heads/master
1,691,419,737,939
1,689,365,567,000
1,689,365,568,000
131,156,103
23
18
NOASSERTION
1,660,342,040,000
1,524,747,538,000
Lean
UTF-8
Lean
false
false
27,402
lean
-- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the MIT license. import system.io import .smtexpr import .smtcompile import .spec.spec import smt2.tactic open tactic open spec namespace proptest @[reducible] meta def var := expr -- name and its type meta def var.ty (v:var) := match v with | (expr.local_const n1 n2 b itsty) := itsty | _ := v end meta def var.setty (v:var) (newty:expr):var := match v with | (expr.local_const n1 n2 b itsty) := (expr.local_const n1 n2 b newty) | _ := v end meta def tys (l:list var):list expr := l.map (Ξ» v, v.ty) meta def print_detail: expr β†’ nat β†’ tactic unit | (expr.local_const n1 n2 b itsty) icnt := do let indent := list.as_string (list.repeat ' ' icnt), trace format!"{indent}(local_const {n1} {n2} _", print_detail itsty (icnt + 2), trace format!"{indent})" | (expr.app a1 a2) icnt := do let indent := list.as_string (list.repeat ' ' icnt), trace format!"{indent}(app", print_detail a1 (icnt + 2), print_detail a2 (icnt + 2), trace format!"{indent})" | (expr.lam n b e e') icnt := do let indent := list.as_string (list.repeat ' ' icnt), trace format!"{indent}(lam {n}", print_detail e (icnt + 2), print_detail e' (icnt + 2), trace format!"{indent})" | (expr.pi n b e e') icnt := do let indent := list.as_string (list.repeat ' ' icnt), trace format!"{indent}(pi {n}", print_detail e (icnt + 2), print_detail e' (icnt + 2), trace format!"{indent})" | (expr.elet n e1 e2 e3) icnt := do let indent := list.as_string (list.repeat ' ' icnt), trace format!"{indent}(elet {n}", print_detail e1 (icnt + 2), print_detail e2 (icnt + 2), print_detail e3 (icnt + 2), trace format!"{indent})" | (expr.macro _ _) _ := fail "Unsupported case" | (expr.var v) icnt := do let indent := list.as_string (list.repeat ' ' icnt), trace format!"{indent}(var {v})" | (expr.sort lvl) icnt := do let indent := list.as_string (list.repeat ' ' icnt), trace format!"{indent}(sort {lvl})" | (expr.const n levels) icnt := do let indent := list.as_string (list.repeat ' ' icnt), trace format!"{indent}(const {n} {levels})" | (expr.mvar n1 n2 _) icnt := do let indent := list.as_string (list.repeat ' ' icnt), trace format!"{indent}(mvar {n1} {n2} _)" meta def is_inequality (tyname:name):bool := tyname = `has_lt.lt ∨ tyname = `has_le.le ∨ tyname = `gt ∨ tyname = `ge ∨ tyname = `lt ∨ tyname = `le -- Utility functions -- Replaces name with val. -- If nested_only is tt, it replaces things only inside -- the expression. meta def replace (name:expr) (val:expr): bool β†’ expr β†’ expr | nested_only x@(expr.local_const n m b itsty) := if x = name ∧ Β¬ nested_only then val else expr.local_const n m b (replace ff itsty) | nested_only (expr.app e1 e2) := expr.app (replace ff e1) (replace ff e2) | nested_only (expr.pi n b nty e) := expr.pi n b (replace ff nty) (replace ff e) | nested_only (expr.lam n b nty e) := expr.lam n b (replace ff nty) (replace ff e) | nested_only x := x -- for all other cases - just give up! :( -- Get all bound variables inside an expression. meta def get_allvars: expr β†’ tactic (list var) | e@(expr.local_const _ n _ itsty) := return [e] | (expr.app f g) := do l1 ← get_allvars f, l2 ← get_allvars g, return (l1.union l2) | (expr.lam n b nty e2) := do l1 ← get_allvars nty, l2 ← get_allvars e2, return (l1.union (l2.filter (Ξ» i, Β¬ (n = i.local_uniq_name ∧ nty = i.local_type)))) | (expr.pi n b nty e2) := do l1 ← get_allvars nty, l2 ← get_allvars e2, return (l1.union (l2.filter (Ξ» i, Β¬ (n = i.local_uniq_name ∧ nty = i.local_type)))) | (expr.elet _ _ _ _) := fail "Unsupported case" | (expr.macro _ _) := fail "Unsupported case" | (expr.var _) := return [] | (expr.sort _) := return [] | (expr.const _ _) := return [] | (expr.mvar _ _ _) := return [] -- Remove parameters and return the type name of e. -- ex) bitvector 8 -> bitvector meta def get_typename (e:expr): tactic name := match (e.get_app_fn) with | expr.const n _ := return n | _ := do trace "??", print_detail e 2, fail "cannot get typename" end -- A list of assignments. @[reducible] meta def assns := list (var Γ— expr) namespace assns meta def assign (a:assns) (v:var) (val:expr) := (v, val)::a meta def get (a:assns) (v:var): option expr := match (list.filter (Ξ» (i:var Γ— expr), i.1 = v) a) with | head::tail := some head.2 | _ := none end meta def erase (a:assns) (v:var):assns := list.filter (Ξ» itm, itm.1 β‰  v) a -- Replaces all occurrences of variables in e -- with corresponding value if there exists an assignment. -- If `nested_only` is tt, it replaces only nested expressions -- inside e. meta def replace_all (a:assns) (e:expr) (nested_only:bool): expr := list.foldl (Ξ» (s:expr) (y:var Γ— expr), -- Replace y.1.1 in s with y.2. replace y.1 y.2 nested_only s) e a end assns -- Random value generator. meta def valgen := (assns Γ— std_gen) β†’ tactic (expr Γ— assns Γ— std_gen) meta structure test_env := (vars:list var) -- Variables (goal:expr) -- goal (a:assns) -- Assignments to the variables (g:std_gen) -- Random value generator -- Lazy evaluator of variables. (f:var β†’ valgen) namespace test_env -- Creates an empty testing context meta def new (vars:list var) (goal:expr) (randgen:std_gen):test_env := test_env.mk vars goal [] randgen (Ξ» (x:var) (y:assns Γ— std_gen), do trace "Uninitialized variable:", print_detail x 2, fail "Uninitialized variable") -- Adds a new uninitializd variable. meta def add_var (tenv:test_env) (v:var):test_env := ⟨tenv.vars ++ [v], -- preserves order tenv.goal, tenv.a, tenv.g, tenv.f⟩ -- Replace v in tenv.vars with v' meta def replace_var_at (tenv:test_env) (idx:nat) (newv:var):tactic test_env := do v ← tenv.vars.nth idx, return ⟨tenv.vars.map (Ξ» x, if x = v then newv else x), tenv.goal, tenv.a.map (Ξ» x, if x.1 = v then (newv, x.2) else x), tenv.g, (Ξ» x, if x = newv then tenv.f v else tenv.f x)⟩ -- Updates random value generator meta def update_gen (tenv:test_env) (newgen:std_gen):test_env := ⟨tenv.vars, tenv.goal, tenv.a, newgen, tenv.f⟩ -- Updates goal. meta def update_goal (tenv:test_env) (newgoal:expr):test_env := ⟨tenv.vars, newgoal, tenv.a, tenv.g, tenv.f⟩ meta def has_value (tenv:test_env) (v:var):bool := tenv.a.get v β‰  none -- Get the assigned value. meta def get (tenv:test_env) (v:var):tactic expr := let err:tactic expr := do trace format!"test_env.get:Unknown variable", trace "finding variable:", print_detail v 0, trace "each vars:", monad.foldl (Ξ» _ (v:var), do print_detail v 0) () tenv.vars, fail format!"test_env.get:Unknown variable {v}" in if tenv.vars.mem v then match tenv.a.get v with | none := err | some n := return n end else err -- Gets the value expression assigned to the variable. -- If there's no such value, create a new value and assign it. meta def get_or_init (tenv:test_env) (v:var):tactic (expr Γ— test_env) := if tenv.vars.mem v then match tenv.a.get v with | none := do (val, a, g) ← tenv.f v (tenv.a, tenv.g), return (val, ⟨tenv.vars, tenv.goal, a.assign v val, g, tenv.f⟩) | some n := return (n, tenv) end else do trace format!"test_env.get_or_init:Unknown variable", trace "finding variable:", print_detail v 0, trace "each vars:", monad.foldl (Ξ» _ (v:var), do print_detail v 0) () tenv.vars, fail format!"test_env.get_or_init:Unknown variable {v}" -- Evaluate the expression which is assigned to the variable. meta def eval (tenv:test_env) (v:var) (retty:Type) [reflected retty] :tactic retty := match (tenv.a.get v) with | some vexpr := do v ← eval_expr retty vexpr, return v | none := fail "Cannot find assignment to the variable" end -- Replace all occurrences of variable v in vars and goal -- into its assigned value. meta def replace_all (tenv:test_env) (v:var): test_env := ⟨tenv.vars.map (Ξ» (i:var), if v β‰  i then -- variable name contains type as well. -- However, (tenv.a.replace_all i tt) else i), tenv.a.replace_all tenv.goal ff, tenv.a, tenv.g, tenv.f⟩ -- Adds a lazy evalutor for the variable. meta def add_evaluator (tenv:test_env) (v:var) (f:valgen) :test_env := ⟨tenv.vars, tenv.goal, tenv.a, tenv.g, (Ξ» v0, if v0 = v then f else tenv.f v0)⟩ end test_env -- Pick a random value of given type and assign to it. -- valgen = (assns Γ— std_gen) β†’ tactic (expr Γ— assns Γ— std_gen) meta def pick :var β†’ valgen | v f := let (a, gen) := f in do tyname ← get_typename v.ty, if tyname = `size then do let (n,gen') := std_next gen, let n := n % 5, let ne := `(n), return (`(size.incr_nat %%ne), a, gen') else if tyname = `bitvector then do -- size of bitvector is already concretized by process_type. `(bitvector %%sze) ← pure v.ty, sz ← eval_expr size sze, let (n,gen') := std_next gen, let n' := n % (2^sz.val), let n'e := `(n'), e ← to_expr ``(bitvector.of_int %%sze %%n'e), return (e, a, gen') else if tyname = `sbitvec then do -- size of sbitvec is already concretized by process_type. -- Assign sbitvec.var! `(sbitvec %%sze) ← pure v.ty, sz ← eval_expr size sze, let vname := to_string v, let vnamee := `(vname), e ← to_expr ``(sbitvec.var %%sze %%vnamee), return (e, a, gen) else if tyname = `bool then do let (n, gen') := std_next gen, let b:bool := n % 2 = 0, let be := `(b), return (be, a, gen') else if tyname = `sbool then do -- Assign sbool.var! let vname := to_string v, let vnamee := `(vname), be' ← to_expr ``(sbool.var %%vnamee), return (be', a, gen) else if tyname = `int then do let (n, gen') := std_next gen, let ne := `(((int.of_nat n) - (int.of_nat n) * 2)), return (ne, a, gen') else if tyname = `nat then do let (n, gen') := std_next gen, let ne := `(n), return (ne, a, gen') else do trace v, fail "Unknown type!" -- Checks whether the type can be encoded into SMT. meta def can_encode_to_smt (tyexpr:expr): tactic bool := if tyexpr.is_arrow then return tt else do n ← get_typename tyexpr, return (n = `eq ∨ n = `or ∨ n = `and ∨ n = `spec.bv_equiv ∨ n = `spec.b_equiv ∨ n = `true ∨ n = `false ∨ n = `bitvector ∨ n = `sbitvec ∨ n = `bool ∨ n = `int) -- no natural number now. -- Replace all occurrences of variables in e with its value, -- as well as all other occurences in test_env. -- If leave_vars is tt, variables are not instantiated unless -- it is used by functions which cannot be encoded to SMT. -- For example, if leave_vars = tt, then term `x op y` does not -- instantiate x and y if it is known that 'op has its corresponding -- SMT operation. meta def concretize: test_env β†’ expr β†’ bool β†’ tactic (test_env Γ— expr) | tenv e leave_vars := do if leave_vars ∧ e.is_local_constant then do -- Don't initialize it if e is just a variable. -- Otherwise it removes opportunity to use 'forall' in SMT. return (tenv, e) else do flag ← can_encode_to_smt e, if flag ∧ leave_vars then do -- ex: "p = q" let args := e.get_app_args, let f := e.get_app_fn, (tenv, args') ← monad.foldl (Ξ» (x:test_env Γ— list expr) (arg:expr), do let tenv := x.1, -- Replace all initialized variables with -- its corresponding value. let arg := tenv.a.replace_all arg ff, (tenv, arg') ← concretize tenv arg leave_vars, return (tenv, x.2 ++ [arg'])) (tenv, []) args, return (tenv, f.app_of_list args') else do vars ← get_allvars e, res ← monad.foldl (Ξ» (x:test_env Γ— expr) v, do --print_detail v 2, let (tenv, e) := x, (val, tenv) ← tenv.get_or_init v, -- Give random value to v -- Replace all occurrences of v with its value let tenv := tenv.replace_all v, let e := replace v val ff e, return (tenv, e)) (tenv, e) vars, return res meta mutual def process_eq, process_ineq, process_implies, process_and, process_or, process_bv_equiv_opt, process_bv_equiv, process_b_equiv_opt, process_b_equiv, process_type -- Processes `P = Q` -- Currently equality does nothing special. with process_eq: test_env β†’ expr β†’ tactic (test_env Γ— option expr) | tenv pty := do (tenv, e) ← concretize tenv pty tt, return (tenv, some e) -- Processes 'P > Q', 'P ≀ Q', ... with process_ineq: test_env β†’ expr β†’ tactic (test_env Γ— option expr) | tenv pty := do (tenv, e) ← concretize tenv pty tt, b ← try_core (do pre_cast ← to_expr ``(to_bool %%e), b ← eval_expr bool pre_cast, return b), match b with | some b := return (tenv, if b then some `(true) else some `(false)) | none := fail "Converting inequality into SMT is not supported ; should be eagerly evaluated" end -- Processes `P β†’ Q` with process_implies: test_env β†’ expr β†’ tactic (test_env Γ— option expr) | tenv pty@(expr.pi n bi pre post) := do (tenv, pre) ← concretize tenv pre tt, -- Let's concretize precondition first. -- Can we evaluate this precondition in Lean? -- (e.g. is all local variables in precondition initialized?) pre_b ← try_core (do pre_cast ← to_expr ``(to_bool %%pre), b ← eval_expr bool pre_cast, return b), match pre_b with | some ff := -- Precondition evaluates to false! -- We can just remove this implies term, if allowed. return (tenv, none) | some tt := -- Precondition is true, equivalent to postcondition only. process_type tenv post | none := -- Let's process postcondition now. do (tenv, post) ← concretize tenv post tt, return (tenv, expr.pi n bi pre post) end | _ _ := fail "Invalid argument" -- Processes `P ∧ Q` with process_and: test_env β†’ expr β†’ tactic (test_env Γ— option expr) | tenv pty := do `(and %%e1 %%e2) ← pure pty, (tenv, oe1) ← process_type tenv e1, (tenv, oe2) ← process_type tenv e2, match oe1, oe2 with | none, none := return (tenv, none) | some e1, none := return (tenv, some e1) | none, some e2 := return (tenv, some e2) | some e1, some e2 := do e ← to_expr ``(and %%e1 %%e2), return (tenv, e) end -- Processes `P ∨ Q` with process_or: test_env β†’ expr β†’ tactic (test_env Γ— option expr) | tenv pty := do `(or %%e1 %%e2) ← pure pty, (tenv, e1) ← concretize tenv e1 tt, (tenv, e2) ← concretize tenv e2 tt, e ← to_expr ``(or %%e1 %%e2), return (tenv, some e) -- Processes `bv_equiv s b`, assign s = (sbitvec.of_bv b) if possible with process_bv_equiv_opt: test_env β†’ expr β†’ tactic (test_env Γ— option expr) | tenv pty := do `(spec.bv_equiv %%s %%b) ← pure pty, if s.is_local_constant then do -- s is just a simple variable. -- Let's replace s with (sbitvec.of_bv b). -- Then, this bv_equiv can be removed. b' ← to_expr ``(sbitvec.of_bv %%b), (tenv, b') ← concretize tenv b' tt, let f:valgen := (Ξ»l, return (b', l.1, l.2)), let tenv := tenv.add_evaluator s f, return (tenv, none) else do -- Eagerly assign all variables in s. (tenv, s) ← concretize tenv s tt, (tenv, b) ← concretize tenv b tt, e ← to_expr ``(spec.bv_equiv %%s %%b), return (tenv, some e) -- Processes `bv_equiv s b` with process_bv_equiv: test_env β†’ expr β†’ tactic (test_env Γ— option expr) | tenv pty := do `(spec.bv_equiv %%s %%b) ← pure pty, (tenv, s) ← concretize tenv s tt, (tenv, b) ← concretize tenv b tt, e ← to_expr ``(spec.bv_equiv %%s %%b), return (tenv, some e) -- Processes `b_equiv s b`, assign s = (sbool.of_bool b) if possible with process_b_equiv_opt: test_env β†’ expr β†’ tactic (test_env Γ— option expr) | tenv pty := do `(b_equiv %%s %%b) ← pure pty, if s.is_local_constant then do -- s is just a simple variable. -- Let's replace s with (sbool.of_bool b). -- Then, this b_equiv can be removed. sty ← infer_type s, b' ← to_expr ``(sbool.of_bool %%b), (tenv, b') ← concretize tenv b' tt, let f:valgen := (Ξ»l, return (b', l.1, l.2)), let tenv := tenv.add_evaluator s f, return (tenv, none) else do -- Eagerly assign all variables in s. (tenv, s) ← concretize tenv s tt, (tenv, b) ← concretize tenv b tt, e ← to_expr ``(b_equiv %%s %%b), return (tenv, some e) -- Processes `bv_equiv s b` with process_b_equiv: test_env β†’ expr β†’ tactic (test_env Γ— option expr) | tenv pty := do `(spec.b_equiv %%s %%b) ← pure pty, (tenv, s) ← concretize tenv s tt, (tenv, b) ← concretize tenv b tt, e ← to_expr ``(spec.b_equiv %%s %%b), return (tenv, some e) -- Returns new test environmen Γ— optimized expression. -- (ex: bitvector sz -> bitvector 8) -- If the expression can be totally removed, it returns none. -- Otherwise, it returns the updated expression. with process_type: test_env β†’ expr β†’ tactic (test_env Γ— option expr) | tenv pty := do is_prop ← is_prop pty, match is_prop with | tt := do -- it is Prop! (tenv, oe) ← ( if pty.is_arrow then process_implies tenv pty else do tyname ← get_typename pty, if tyname = `eq then process_eq tenv pty else if is_inequality tyname then process_ineq tenv pty else if tyname = `or then process_or tenv pty else if tyname = `and then process_and tenv pty else if tyname = `spec.bv_equiv then process_bv_equiv tenv pty else if tyname = `spec.b_equiv then process_b_equiv tenv pty else fail "."), return (tenv, oe) | ff := do -- it is not Prop. -- Eagerly assign parameters of the type. -- eg) bitvector sz -- Here, sz should be initialized immediately. (tenv, pty) ← concretize tenv pty ff, return (tenv, some pty) end -- Evaluates e(ex: `1+1` -> 2), and returns a string that encodes e -- so it can be used in SMT code. meta def eval_and_tosmtstr (e:expr):tactic string := do ty ← infer_type e, tn ← get_typename ty, ostr ← try_core ( if tn = `bitvector then do e ← to_expr ``(to_string (sbitvec.of_bv %%e)), str ← eval_expr string e, return str else if tn = `sbitvec then do e ← to_expr ``(to_string (%%e)), str ← eval_expr string e, return str else if tn = `int then do i ← eval_expr int e, return (to_string i) else if tn = `bool then do if e = `(bool.tt) then return "true" else if e = `(bool.ff) then return "false" else do b ← eval_expr bool e, return (if b then "true" else "false") else fail ""), match ostr with | none := do -- I wish this will work in general.. fmt ← tactic_format_expr e, return (to_string fmt) | some s := return s end -- smt2.term does not have has_to_pexpr, so expr_to_string / prop_to_smt -- is currently returning string instead of smt2.term. meta mutual def expr_to_smt, prop_to_smt with expr_to_smt: test_env β†’ expr β†’ tactic string | tenv e := do is_prop ← is_prop e, match is_prop with | tt := prop_to_smt tenv e | ff := do str ← eval_and_tosmtstr e, return str end with prop_to_smt: test_env β†’ expr β†’ tactic string | tenv ty := do e ← ( if ty.is_arrow then do let p := ty.binding_domain, let q := ty.binding_body, sp ← prop_to_smt tenv p, sq ← prop_to_smt tenv q, --e ← to_expr ``(smt2.builder.implies %%sp %%sq), return $ to_string (format!"(=> {sp} {sq})") else do tyname ← get_typename ty, if tyname = `eq then do `(eq %%p %%q) ← pure ty, sp ← expr_to_smt tenv p, sq ← expr_to_smt tenv q, return $ to_string (format!"(= {sp} {sq})") else if tyname = `or then do `(or %%p %%q) ← pure ty, sp ← prop_to_smt tenv p, sq ← prop_to_smt tenv q, return $ to_string (format!"(or {sp} {sq})") else if tyname = `and then do `(and %%p %%q) ← pure ty, sp ← prop_to_smt tenv p, sq ← prop_to_smt tenv q, return $ to_string (format!"(and {sp} {sq})") else if tyname = `spec.bv_equiv then do `(@spec.bv_equiv %%sz %%s %%b) ← pure ty, se ← to_expr ``(to_string (%%s)), sstr ← eval_expr string se, be ← to_expr ``(to_string (sbitvec.of_bv %%b)), bstr ← eval_expr string be, return $ to_string (format!"(= {sstr} {bstr})") else if tyname = `spec.b_equiv then do `(b_equiv %%s %%b) ← pure ty, se ← to_expr ``(to_string (%%s)), sstr ← eval_expr string se, bse ← to_expr ``(to_string (sbool.of_bool %%b)), bstr ← eval_expr string bse, return $ to_string (format!"(= {sstr} {bstr})") else if tyname = `true then do return "true" else if tyname = `false then do return "false" else do trace ty, fail "Unknown goal type"), return e -- Creates a variable which can be used for forall quantifier. meta def var_to_smtvar (tenv:test_env) (v:var): tactic (option (string Γ— smt2.sort)) := do tyname ← get_typename v.ty, if tyname = `size then -- size should be initialized in Lean. if tenv.has_value v then return none else fail "size should be initialized in Lean." else if tyname = `bitvector then if tenv.has_value v then return none else do -- sz should be already concretized. `(bitvector %%sz) ← pure v.ty, sz ← eval_expr size sz, return (to_string v, smt2.sort.apply "_" ["BitVec", to_string sz]) else if tyname = `sbitvec then -- a BitVec variable creator. let newvar := Ξ» (sze:expr) (vname:string), do -- sz should be already concretized. sz ← eval_expr size sze, return (some (vname, smt2.sort.apply "_" ["BitVec", to_string sz])) in if tenv.has_value v then do val ← tenv.get v, -- If sbitvec.var is assigned, it can be forall quantified. o ← try_core (do `(sbitvec.var %%sze %%varnamee) ← pure val, varname ← eval_expr string varnamee, return (sze, varname) ), match o with | none := return none -- it's not variable. | some (sz, vname) := newvar sz vname end else do `(sbitvec %%sz) ← pure v.ty, newvar sz (to_string v) else if tyname = `bool then if tenv.has_value v then return none else return (to_string v, smt2.sort.id "Bool") else if tyname = `sbool then if tenv.has_value v then do val ← tenv.get v, -- If sbitvec.var is assigned, it can be forall quantified. o ← try_core (do `(sbool.var %%varnamee) ← pure val, varname ← eval_expr string varnamee, return varname ), match o with | none := return none -- it's not variable. | some vname := return (some (vname, smt2.sort.id "Bool")) end else do return (some (to_string v, smt2.sort.id "Bool")) else if tyname = `int then if tenv.has_value v then return none else return (to_string v, smt2.sort.id "Int") else do trace v, fail "Unknown type!" meta def update_smt (tenv:test_env) (orgsmt: string) (v:var): tactic string := do is_prop ← is_prop v.ty, match is_prop with | tt := do t ← prop_to_smt tenv v.ty, return $ to_string (format!"(=> {t} {orgsmt})") | ff := do ovar ← var_to_smtvar tenv v, match ovar with | none := -- Isn't needed to create forall. return orgsmt | some (vname, sort) := -- Make (forall x, P). return $ to_string (format!"(forall (({vname} {sort})) {orgsmt})") end end meta def build_smt (tenv:test_env): tactic string := do -- First, synthesize goal. smt ← prop_to_smt tenv tenv.goal, smt ← monad.foldl (update_smt tenv) smt (tenv.vars.reverse), return $ to_string (format!"(assert {smt})") meta def run_smt (smtcode:string) : io smt2.response := do z3i ← z3_instance.start, smtres ← z3_instance.raw z3i (smtcode ++ " (check-sat)"), pure (parse_smt2_result smtres) meta def visit_each_param :test_env β†’ nat β†’ tactic test_env | tenv n := if tenv.vars.length ≀ n then return tenv else do v ← tenv.vars.nth n, (tenv, oe) ← process_type tenv v.ty, match oe with | none := -- This parameter is optimized out. -- Remove the param from testing environment later. visit_each_param tenv (n+1) | some e' := do let newv := v.setty e', is_prop ← is_prop v.ty, tenv ← tenv.replace_var_at n newv, visit_each_param (if Β¬ is_prop then -- register a random value generator for newv tenv.add_evaluator newv (pick newv) else tenv) (n+1) end meta def test_can_be_omitted (tenv:test_env): bool := tenv.vars.any (Ξ» v, v.ty = `(false)) inductive test_result:Type | success | fail | unknown | error : string β†’ test_result | omitted instance : decidable_eq test_result := by tactic.mk_dec_eq_instance instance : has_to_string test_result := ⟨λ r, match r with | test_result.success := "success" | test_result.fail := "fail" | test_result.unknown := "unknown" | test_result.error s := "error(" ++ s ++ ")" | test_result.omitted := "omitted" end ⟩ -- Main function. meta def test (spec : expr) (gen:std_gen) :tactic (string Γ— test_result Γ— std_gen) := do -- 1. Infer the type of specificaton t ← infer_type spec, -- 2. Segregate arguments from the type, and -- infer types of the input arguments. -- ex) get a, b from Ξ  (a:nat) (b:nat), P a b (params, goal) ← mk_local_pis t, -- 3. Create the test environment. let tenv := test_env.new params goal gen, -- 4. Process each parameter. tenv ← visit_each_param tenv 0, -- 5. Process goal. (tenv, some newgoal) ← process_type tenv tenv.goal, let tenv := tenv.update_goal newgoal, -- 6. If a test can be omitted, stop here. -- ex) if there is a false in its premise, it isn't needed to invoke smt if test_can_be_omitted tenv then return ("", test_result.omitted, tenv.g) else do -- 7. Synthesize SMT code. smtcode ← build_smt tenv, let smtcode_expr := `(smtcode), tgt ← to_expr ``(run_smt %%smtcode_expr), tgt ← eval_expr (io smt2.response) tgt, res ← unsafe_run_io tgt, return (smtcode, match res with | smt2.response.sat := test_result.success | smt2.response.unsat := test_result.fail | smt2.response.unknown := test_result.unknown | smt2.response.other s := test_result.error s end, tenv.g) end proptest