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
4d30b980649fd68bd1cd8975cd1633c0f56efa49
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/omega/int/main.lean
8c1e5412e8376fe83ecaa0291e9cb0c80ea7ad1f
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,289
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ /- Main procedure for linear integer arithmetic. -/ import tactic.omega.prove_unsats import tactic.omega.int.dnf open tactic namespace omega namespace int open_locale omega.int run_cmd mk_simp_attr `sugar attribute [sugar] ne not_le not_lt int.lt_iff_add_one_le or_false false_or and_true true_and ge gt mul_add add_mul one_mul mul_one mul_comm sub_eq_add_neg imp_iff_not_or iff_iff_not_or_and_or_not meta def desugar := `[try {simp only with sugar}] lemma univ_close_of_unsat_clausify (m : nat) (p : preform) : clauses.unsat (dnf (Β¬* p)) β†’ univ_close p (Ξ» x, 0) m | h1 := begin apply univ_close_of_valid, apply valid_of_unsat_not, apply unsat_of_clauses_unsat, exact h1 end /-- Given a (p : preform), return the expr of a (t : univ_close m p) -/ meta def prove_univ_close (m : nat) (p : preform) : tactic expr := do x ← prove_unsats (dnf (Β¬*p)), return `(univ_close_of_unsat_clausify %%`(m) %%`(p) %%x) /-- Reification to imtermediate shadow syntax that retains exprs -/ meta def to_exprterm : expr β†’ tactic exprterm | `(- %%x) := --return (exprterm.exp (-1 : int) x) ( do z ← eval_expr' int x, return (exprterm.cst (-z : int)) ) <|> ( return $ exprterm.exp (-1 : int) x ) | `(%%mx * %%zx) := do z ← eval_expr' int zx, return (exprterm.exp z mx) | `(%%t1x + %%t2x) := do t1 ← to_exprterm t1x, t2 ← to_exprterm t2x, return (exprterm.add t1 t2) | x := ( do z ← eval_expr' int x, return (exprterm.cst z) ) <|> ( return $ exprterm.exp 1 x ) /-- Reification to imtermediate shadow syntax that retains exprs -/ meta def to_exprform : expr β†’ tactic exprform | `(%%tx1 = %%tx2) := do t1 ← to_exprterm tx1, t2 ← to_exprterm tx2, return (exprform.eq t1 t2) | `(%%tx1 ≀ %%tx2) := do t1 ← to_exprterm tx1, t2 ← to_exprterm tx2, return (exprform.le t1 t2) | `(Β¬ %%px) := do p ← to_exprform px, return (exprform.not p) | `(%%px ∨ %%qx) := do p ← to_exprform px, q ← to_exprform qx, return (exprform.or p q) | `(%%px ∧ %%qx) := do p ← to_exprform px, q ← to_exprform qx, return (exprform.and p q) | `(_ β†’ %%px) := to_exprform px | x := trace "Cannot reify expr : " >> trace x >> failed /-- List of all unreified exprs -/ meta def exprterm.exprs : exprterm β†’ list expr | (exprterm.cst _) := [] | (exprterm.exp _ x) := [x] | (exprterm.add t s) := list.union t.exprs s.exprs /-- List of all unreified exprs -/ meta def exprform.exprs : exprform β†’ list expr | (exprform.eq t s) := list.union t.exprs s.exprs | (exprform.le t s) := list.union t.exprs s.exprs | (exprform.not p) := p.exprs | (exprform.or p q) := list.union p.exprs q.exprs | (exprform.and p q) := list.union p.exprs q.exprs /-- Reification to an intermediate shadow syntax which eliminates exprs, but still includes non-canonical terms -/ meta def exprterm.to_preterm (xs : list expr) : exprterm β†’ tactic preterm | (exprterm.cst k) := return & k | (exprterm.exp k x) := let m := xs.index_of x in if m < xs.length then return (k ** m) else failed | (exprterm.add xa xb) := do a ← xa.to_preterm, b ← xb.to_preterm, return (a +* b) /-- Reification to an intermediate shadow syntax which eliminates exprs, but still includes non-canonical terms -/ meta def exprform.to_preform (xs : list expr) : exprform β†’ tactic preform | (exprform.eq xa xb) := do a ← xa.to_preterm xs, b ← xb.to_preterm xs, return (a =* b) | (exprform.le xa xb) := do a ← xa.to_preterm xs, b ← xb.to_preterm xs, return (a ≀* b) | (exprform.not xp) := do p ← xp.to_preform, return Β¬* p | (exprform.or xp xq) := do p ← xp.to_preform, q ← xq.to_preform, return (p ∨* q) | (exprform.and xp xq) := do p ← xp.to_preform, q ← xq.to_preform, return (p ∧* q) /-- Reification to an intermediate shadow syntax which eliminates exprs, but still includes non-canonical terms. -/ meta def to_preform (x : expr) : tactic (preform Γ— nat) := do xf ← to_exprform x, let xs := xf.exprs, f ← xf.to_preform xs, return (f, xs.length) /-- Return expr of proof of current LIA goal -/ meta def prove : tactic expr := do (p,m) ← target >>= to_preform, trace_if_enabled `omega p, prove_univ_close m p /-- Succeed iff argument is the expr of β„€ -/ meta def eq_int (x : expr) : tactic unit := if x = `(int) then skip else failed /-- Check whether argument is expr of a well-formed formula of LIA-/ meta def wff : expr β†’ tactic unit | `(Β¬ %%px) := wff px | `(%%px ∨ %%qx) := wff px >> wff qx | `(%%px ∧ %%qx) := wff px >> wff qx | `(%%px ↔ %%qx) := wff px >> wff qx | `(%%(expr.pi _ _ px qx)) := monad.cond (if expr.has_var px then return tt else is_prop px) (wff px >> wff qx) (eq_int px >> wff qx) | `(@has_lt.lt %%dx %%h _ _) := eq_int dx | `(@has_le.le %%dx %%h _ _) := eq_int dx | `(@eq %%dx _ _) := eq_int dx | `(@ge %%dx %%h _ _) := eq_int dx | `(@gt %%dx %%h _ _) := eq_int dx | `(@ne %%dx _ _) := eq_int dx | `(true) := skip | `(false) := skip | _ := failed /-- Succeed iff argument is expr of term whose type is wff -/ meta def wfx (x : expr) : tactic unit := infer_type x >>= wff /-- Intro all universal quantifiers over β„€ -/ meta def intro_ints_core : tactic unit := do x ← target, match x with | (expr.pi _ _ `(int) _) := intro_fresh >> intro_ints_core | _ := skip end meta def intro_ints : tactic unit := do (expr.pi _ _ `(int) _) ← target, intro_ints_core /-- If the goal has universal quantifiers over integers, introduce all of them. Otherwise, revert all hypotheses that are formulas of linear integer arithmetic. -/ meta def preprocess : tactic unit := intro_ints <|> (revert_cond_all wfx >> desugar) end int end omega open omega.int /-- The core omega tactic for integers. -/ meta def omega_int (is_manual : bool) : tactic unit := desugar ; (if is_manual then skip else preprocess) ; prove >>= apply >> skip
31dc8778aa490d03ca79120eeec2568a890e5b4f
859855170b866e395d328ebb28c4e060aa5559e8
/src/solutions/06_sub_sequences.lean
3931d8aed1666e63d3980efc8764b79ae973e4ac
[ "Apache-2.0" ]
permissive
bradheintz/tutorials
1be40c9e97a484441f268ea8504c3d74534162cf
02f15b400478de7278f4baa08935befd0f3986ef
refs/heads/master
1,688,028,802,367
1,627,863,284,000
1,627,863,284,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,803
lean
import tuto_lib /- This file continues the elementary study of limits of sequences. It can be skipped if the previous file was too easy, it won't introduce any new tactic or trick. Remember useful lemmas: abs_le (x y : ℝ) : |x| ≀ y ↔ -y ≀ x ∧ x ≀ y abs_add (x y : ℝ) : |x + y| ≀ |x| + |y| abs_sub_comm (x y : ℝ) : |x - y| = |y - x| 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 and the definition: def seq_limit (u : β„• β†’ ℝ) (l : ℝ) : Prop := βˆ€ Ξ΅ > 0, βˆƒ N, βˆ€ n β‰₯ N, |u n - l| ≀ Ξ΅ You can also use a property proved in the previous file: unique_limit : seq_limit u l β†’ seq_limit u l' β†’ l = l' def extraction (Ο† : β„• β†’ β„•) := βˆ€ n m, n < m β†’ Ο† n < Ο† m -/ variable { Ο† : β„• β†’ β„•} /- The next lemma is proved by an easy induction, but we haven't seen induction in this tutorial. If you did the natural number game then you can delete the proof below and try to reconstruct it. -/ /-- An extraction is greater than id -/ lemma id_le_extraction' : extraction Ο† β†’ βˆ€ n, n ≀ Ο† n := begin intros hyp n, induction n with n hn, { exact nat.zero_le _ }, { exact nat.succ_le_of_lt (by linarith [hyp n (n+1) (by linarith)]) }, end /-- Extractions take arbitrarily large values for arbitrarily large inputs. -/ -- 0039 lemma extraction_ge : extraction Ο† β†’ βˆ€ N N', βˆƒ n β‰₯ N', Ο† n β‰₯ N := begin -- sorry intros h N N', use max N N', split, apply le_max_right, calc N ≀ max N N' : by apply le_max_left ... ≀ Ο† (max N N') : by apply id_le_extraction' h -- sorry end /-- A real number `a` is a cluster point of a sequence `u` if `u` has a subsequence converging to `a`. def cluster_point (u : β„• β†’ ℝ) (a : ℝ) := βˆƒ Ο†, extraction Ο† ∧ seq_limit (u ∘ Ο†) a -/ variables {u : β„• β†’ ℝ} {a l : ℝ} /- In the exercise, we use `βˆƒ n β‰₯ N, ...` which is the abbreviation of `βˆƒ n, n β‰₯ N ∧ ...`. Lean can read this abbreviation, but displays it as the confusing: `βˆƒ (n : β„•) (H : n β‰₯ N)` One gets used to it. Alternatively, one can get rid of it using the lemma exists_prop {p q : Prop} : (βˆƒ (h : p), q) ↔ p ∧ q -/ /-- If `a` is a cluster point of `u` then there are values of `u` arbitrarily close to `a` for arbitrarily large input. -/ -- 0040 lemma near_cluster : cluster_point u a β†’ βˆ€ Ξ΅ > 0, βˆ€ N, βˆƒ n β‰₯ N, |u n - a| ≀ Ξ΅ := begin -- sorry intros hyp Ξ΅ Ξ΅_pos N, rcases hyp with βŸ¨Ο†, Ο†_extr, hΟ†βŸ©, cases hΟ† Ξ΅ Ξ΅_pos with N' hN', rcases extraction_ge Ο†_extr N N' with ⟨q, hq, hq'⟩, exact βŸ¨Ο† q, hq', hN' _ hq⟩, -- sorry end /- The above exercice can be done in five lines. Hint: you can use the anonymous constructor syntax when proving existential statements. -/ /-- If `u` tends to `l` then its subsequences tend to `l`. -/ -- 0041 lemma subseq_tendsto_of_tendsto' (h : seq_limit u l) (hΟ† : extraction Ο†) : seq_limit (u ∘ Ο†) l := begin -- sorry intros Ξ΅ Ξ΅_pos, cases h Ξ΅ Ξ΅_pos with N hN, use N, intros n hn, apply hN, calc N ≀ n : hn ... ≀ Ο† n : id_le_extraction' hΟ† n, -- sorry end /-- If `u` tends to `l` all its cluster points are equal to `l`. -/ -- 0042 lemma cluster_limit (hl : seq_limit u l) (ha : cluster_point u a) : a = l := begin -- sorry rcases ha with βŸ¨Ο†, Ο†_extr, lim_u_Ο†βŸ©, have lim_u_Ο†' : seq_limit (u ∘ Ο†) l, from subseq_tendsto_of_tendsto' hl Ο†_extr, exact unique_limit lim_u_Ο† lim_u_Ο†', -- sorry end /-- Cauchy_sequence sequence -/ def cauchy_sequence (u : β„• β†’ ℝ) := βˆ€ Ξ΅ > 0, βˆƒ N, βˆ€ p q, p β‰₯ N β†’ q β‰₯ N β†’ |u p - u q| ≀ Ξ΅ -- 0043 example : (βˆƒ l, seq_limit u l) β†’ cauchy_sequence u := begin -- sorry intro hyp, cases hyp with l hl, intros Ξ΅ Ξ΅_pos, cases hl (Ξ΅/2) (by linarith) with N hN, use N, intros p q hp hq, calc |u p - u q| = |(u p - l) + (l - u q)| : by ring_nf ... ≀ |u p - l| + |l - u q| : by apply abs_add ... = |u p - l| + |u q - l| : by rw abs_sub_comm (u q) l ... ≀ Ξ΅ : by linarith [hN p hp, hN q hq], -- sorry end /- In the next exercise, you can reuse near_cluster : cluster_point u a β†’ βˆ€ Ξ΅ > 0, βˆ€ N, βˆƒ n β‰₯ N, |u n - a| ≀ Ξ΅ -/ -- 0044 example (hu : cauchy_sequence u) (hl : cluster_point u l) : seq_limit u l := begin -- sorry intros Ξ΅ Ξ΅_pos, cases hu (Ξ΅/2) (by linarith) with N hN, use N, have clef : βˆƒ N' β‰₯ N, |u N' - l| ≀ Ξ΅/2, apply near_cluster hl (Ξ΅/2) (by linarith), cases clef with N' h, cases h with hNN' hN', intros n hn, calc |u n - l| = |(u n - u N') + (u N' - l)| : by ring ... ≀ |u n - u N'| + |u N' - l| : by apply abs_add ... ≀ Ξ΅ : by linarith [hN n N' (by linarith) hNN'], -- sorry end
418d600b991a54af361680ecf3556322b71ecc99
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/nth_rewrite/congr.lean
81b48cc3508fe8d7c32821566d30ffb7790cacb2
[]
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
651
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.nth_rewrite.basic import Mathlib.tactic.core import Mathlib.data.mllist import Mathlib.PostPort namespace Mathlib namespace tactic namespace nth_rewrite.congr /-- Helper function which just tries to rewrite `e` using the equality `r` without assigning any metavariables in the tactic state, and without creating any metavariables which cannot be discharged by `cfg.discharger` in the process. -/
02be97905b6f45a78c6f5ff841bcf48b376a9531
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/set_theory/game/pgame.lean
b6a9580b9cbb2ea047de298450d579c576ca1849
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
59,543
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison -/ import data.fin.basic import data.list.basic import logic.relation import logic.small.basic import order.game_add /-! # Combinatorial (pre-)games. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The basic theory of combinatorial games, following Conway's book `On Numbers and Games`. We construct "pregames", define an ordering and arithmetic operations on them, then show that the operations descend to "games", defined via the equivalence relation `p β‰ˆ q ↔ p ≀ q ∧ q ≀ p`. The surreal numbers will be built as a quotient of a subtype of pregames. A pregame (`pgame` below) is axiomatised via an inductive type, whose sole constructor takes two types (thought of as indexing the possible moves for the players Left and Right), and a pair of functions out of these types to `pgame` (thought of as describing the resulting game after making a move). Combinatorial games themselves, as a quotient of pregames, are constructed in `game.lean`. ## Conway induction By construction, the induction principle for pregames is exactly "Conway induction". That is, to prove some predicate `pgame β†’ Prop` holds for all pregames, it suffices to prove that for every pregame `g`, if the predicate holds for every game resulting from making a move, then it also holds for `g`. While it is often convenient to work "by induction" on pregames, in some situations this becomes awkward, so we also define accessor functions `pgame.left_moves`, `pgame.right_moves`, `pgame.move_left` and `pgame.move_right`. There is a relation `pgame.subsequent p q`, saying that `p` can be reached by playing some non-empty sequence of moves starting from `q`, an instance `well_founded subsequent`, and a local tactic `pgame_wf_tac` which is helpful for discharging proof obligations in inductive proofs relying on this relation. ## Order properties Pregames have both a `≀` and a `<` relation, satisfying the usual properties of a `preorder`. The relation `0 < x` means that `x` can always be won by Left, while `0 ≀ x` means that `x` can be won by Left as the second player. It turns out to be quite convenient to define various relations on top of these. We define the "less or fuzzy" relation `x ⧏ y` as `Β¬ y ≀ x`, the equivalence relation `x β‰ˆ y` as `x ≀ y ∧ y ≀ x`, and the fuzzy relation `x β€– y` as `x ⧏ y ∧ y ⧏ x`. If `0 ⧏ x`, then `x` can be won by Left as the first player. If `x β‰ˆ 0`, then `x` can be won by the second player. If `x β€– 0`, then `x` can be won by the first player. Statements like `zero_le_lf`, `zero_lf_le`, etc. unfold these definitions. The theorems `le_def` and `lf_def` give a recursive characterisation of each relation in terms of themselves two moves later. The theorems `zero_le`, `zero_lf`, etc. also take into account that `0` has no moves. Later, games will be defined as the quotient by the `β‰ˆ` relation; that is to say, the `antisymmetrization` of `pgame`. ## Algebraic structures We next turn to defining the operations necessary to make games into a commutative additive group. Addition is defined for $x = \{xL | xR\}$ and $y = \{yL | yR\}$ by $x + y = \{xL + y, x + yL | xR + y, x + yR\}$. Negation is defined by $\{xL | xR\} = \{-xR | -xL\}$. The order structures interact in the expected way with addition, so we have ``` theorem le_iff_sub_nonneg {x y : pgame} : x ≀ y ↔ 0 ≀ y - x := sorry theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x := sorry ``` We show that these operations respect the equivalence relation, and hence descend to games. At the level of games, these operations satisfy all the laws of a commutative group. To prove the necessary equivalence relations at the level of pregames, we introduce the notion of a `relabelling` of a game, and show, for example, that there is a relabelling between `x + (y + z)` and `(x + y) + z`. ## Future work * The theory of dominated and reversible positions, and unique normal form for short games. * Analysis of basic domineering positions. * Hex. * Temperature. * The development of surreal numbers, based on this development of combinatorial games, is still quite incomplete. ## References The material here is all drawn from * [Conway, *On numbers and games*][conway2001] An interested reader may like to formalise some of the material from * [Andreas Blass, *A game semantics for linear logic*][MR1167694] * [AndrΓ© Joyal, *Remarques sur la thΓ©orie des jeux Γ  deux personnes*][joyal1997] -/ open function relation universes u /-! ### Pre-game moves -/ /-- The type of pre-games, before we have quotiented by equivalence (`pgame.setoid`). In ZFC, a combinatorial game is constructed from two sets of combinatorial games that have been constructed at an earlier stage. To do this in type theory, we say that a pre-game is built inductively from two families of pre-games indexed over any type in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`, reflecting that it is a proper class in ZFC. -/ inductive pgame : Type (u+1) | mk : βˆ€ Ξ± Ξ² : Type u, (Ξ± β†’ pgame) β†’ (Ξ² β†’ pgame) β†’ pgame namespace pgame /-- The indexing type for allowable moves by Left. -/ def left_moves : pgame β†’ Type u | (mk l _ _ _) := l /-- The indexing type for allowable moves by Right. -/ def right_moves : pgame β†’ Type u | (mk _ r _ _) := r /-- The new game after Left makes an allowed move. -/ def move_left : Ξ  (g : pgame), left_moves g β†’ pgame | (mk l _ L _) := L /-- The new game after Right makes an allowed move. -/ def move_right : Ξ  (g : pgame), right_moves g β†’ pgame | (mk _ r _ R) := R @[simp] lemma left_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).left_moves = xl := rfl @[simp] lemma move_left_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).move_left = xL := rfl @[simp] lemma right_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).right_moves = xr := rfl @[simp] lemma move_right_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).move_right = xR := rfl /-- Construct a pre-game from list of pre-games describing the available moves for Left and Right. -/ -- TODO define this at the level of games, as well, and perhaps also for finsets of games. def of_lists (L R : list pgame.{u}) : pgame.{u} := mk (ulift (fin L.length)) (ulift (fin R.length)) (Ξ» i, L.nth_le i.down i.down.is_lt) (Ξ» j, R.nth_le j.down j.down.prop) lemma left_moves_of_lists (L R : list pgame) : (of_lists L R).left_moves = ulift (fin L.length) := rfl lemma right_moves_of_lists (L R : list pgame) : (of_lists L R).right_moves = ulift (fin R.length) := rfl /-- Converts a number into a left move for `of_lists`. -/ def to_of_lists_left_moves {L R : list pgame} : fin L.length ≃ (of_lists L R).left_moves := ((equiv.cast (left_moves_of_lists L R).symm).trans equiv.ulift).symm /-- Converts a number into a right move for `of_lists`. -/ def to_of_lists_right_moves {L R : list pgame} : fin R.length ≃ (of_lists L R).right_moves := ((equiv.cast (right_moves_of_lists L R).symm).trans equiv.ulift).symm theorem of_lists_move_left {L R : list pgame} (i : fin L.length) : (of_lists L R).move_left (to_of_lists_left_moves i) = L.nth_le i i.is_lt := rfl @[simp] theorem of_lists_move_left' {L R : list pgame} (i : (of_lists L R).left_moves) : (of_lists L R).move_left i = L.nth_le (to_of_lists_left_moves.symm i) (to_of_lists_left_moves.symm i).is_lt := rfl theorem of_lists_move_right {L R : list pgame} (i : fin R.length) : (of_lists L R).move_right (to_of_lists_right_moves i) = R.nth_le i i.is_lt := rfl @[simp] theorem of_lists_move_right' {L R : list pgame} (i : (of_lists L R).right_moves) : (of_lists L R).move_right i = R.nth_le (to_of_lists_right_moves.symm i) (to_of_lists_right_moves.symm i).is_lt := rfl /-- A variant of `pgame.rec_on` expressed in terms of `pgame.move_left` and `pgame.move_right`. Both this and `pgame.rec_on` describe Conway induction on games. -/ @[elab_as_eliminator] def move_rec_on {C : pgame β†’ Sort*} (x : pgame) (IH : βˆ€ (y : pgame), (βˆ€ i, C (y.move_left i)) β†’ (βˆ€ j, C (y.move_right j)) β†’ C y) : C x := x.rec_on $ Ξ» yl yr yL yR, IH (mk yl yr yL yR) /-- `is_option x y` means that `x` is either a left or right option for `y`. -/ @[mk_iff] inductive is_option : pgame β†’ pgame β†’ Prop | move_left {x : pgame} (i : x.left_moves) : is_option (x.move_left i) x | move_right {x : pgame} (i : x.right_moves) : is_option (x.move_right i) x theorem is_option.mk_left {xl xr : Type u} (xL : xl β†’ pgame) (xR : xr β†’ pgame) (i : xl) : (xL i).is_option (mk xl xr xL xR) := @is_option.move_left (mk _ _ _ _) i theorem is_option.mk_right {xl xr : Type u} (xL : xl β†’ pgame) (xR : xr β†’ pgame) (i : xr) : (xR i).is_option (mk xl xr xL xR) := @is_option.move_right (mk _ _ _ _) i theorem wf_is_option : well_founded is_option := ⟨λ x, move_rec_on x $ Ξ» x IHl IHr, acc.intro x $ Ξ» y h, begin induction h with _ i _ j, { exact IHl i }, { exact IHr j } end⟩ /-- `subsequent x y` says that `x` can be obtained by playing some nonempty sequence of moves from `y`. It is the transitive closure of `is_option`. -/ def subsequent : pgame β†’ pgame β†’ Prop := trans_gen is_option instance : is_trans _ subsequent := trans_gen.is_trans @[trans] theorem subsequent.trans {x y z} : subsequent x y β†’ subsequent y z β†’ subsequent x z := trans_gen.trans theorem wf_subsequent : well_founded subsequent := wf_is_option.trans_gen instance : has_well_founded pgame := ⟨_, wf_subsequent⟩ lemma subsequent.move_left {x : pgame} (i : x.left_moves) : subsequent (x.move_left i) x := trans_gen.single (is_option.move_left i) lemma subsequent.move_right {x : pgame} (j : x.right_moves) : subsequent (x.move_right j) x := trans_gen.single (is_option.move_right j) lemma subsequent.mk_left {xl xr} (xL : xl β†’ pgame) (xR : xr β†’ pgame) (i : xl) : subsequent (xL i) (mk xl xr xL xR) := @subsequent.move_left (mk _ _ _ _) i lemma subsequent.mk_right {xl xr} (xL : xl β†’ pgame) (xR : xr β†’ pgame) (j : xr) : subsequent (xR j) (mk xl xr xL xR) := @subsequent.move_right (mk _ _ _ _) j /-- A local tactic for proving well-foundedness of recursive definitions involving pregames. -/ meta def pgame_wf_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right, subsequent.move_left, subsequent.move_right, subsequent.mk_left, subsequent.mk_right, subsequent.trans] { max_depth := 6 }] /-! ### Basic pre-games -/ /-- The pre-game `zero` is defined by `0 = { | }`. -/ instance : has_zero pgame := ⟨⟨pempty, pempty, pempty.elim, pempty.elim⟩⟩ @[simp] lemma zero_left_moves : left_moves 0 = pempty := rfl @[simp] lemma zero_right_moves : right_moves 0 = pempty := rfl instance is_empty_zero_left_moves : is_empty (left_moves 0) := pempty.is_empty instance is_empty_zero_right_moves : is_empty (right_moves 0) := pempty.is_empty instance : inhabited pgame := ⟨0⟩ /-- The pre-game `one` is defined by `1 = { 0 | }`. -/ instance : has_one pgame := ⟨⟨punit, pempty, Ξ» _, 0, pempty.elim⟩⟩ @[simp] lemma one_left_moves : left_moves 1 = punit := rfl @[simp] lemma one_move_left (x) : move_left 1 x = 0 := rfl @[simp] lemma one_right_moves : right_moves 1 = pempty := rfl instance unique_one_left_moves : unique (left_moves 1) := punit.unique instance is_empty_one_right_moves : is_empty (right_moves 1) := pempty.is_empty /-! ### Pre-game order relations -/ /-- The less or equal relation on pre-games. If `0 ≀ x`, then Left can win `x` as the second player. -/ instance : has_le pgame := ⟨sym2.game_add.fix wf_is_option $ Ξ» x y le, (βˆ€ i, Β¬ le y (x.move_left i) (sym2.game_add.snd_fst $ is_option.move_left i)) ∧ (βˆ€ j, Β¬ le (y.move_right j) x (sym2.game_add.fst_snd $ is_option.move_right j))⟩ /-- The less or fuzzy relation on pre-games. If `0 ⧏ x`, then Left can win `x` as the first player. -/ def lf (x y : pgame) : Prop := Β¬ y ≀ x localized "infix (name := pgame.lf) ` ⧏ `:50 := pgame.lf" in pgame @[simp] protected theorem not_le {x y : pgame} : Β¬ x ≀ y ↔ y ⧏ x := iff.rfl @[simp] theorem not_lf {x y : pgame} : Β¬ x ⧏ y ↔ y ≀ x := not_not theorem _root_.has_le.le.not_gf {x y : pgame} : x ≀ y β†’ Β¬ y ⧏ x := not_lf.2 theorem lf.not_ge {x y : pgame} : x ⧏ y β†’ Β¬ y ≀ x := id /-- Definition of `x ≀ y` on pre-games, in terms of `⧏`. The ordering here is chosen so that `and.left` refer to moves by Left, and `and.right` refer to moves by Right. -/ theorem le_iff_forall_lf {x y : pgame} : x ≀ y ↔ (βˆ€ i, x.move_left i ⧏ y) ∧ βˆ€ j, x ⧏ y.move_right j := by { unfold has_le.le, rw sym2.game_add.fix_eq, refl } /-- Definition of `x ≀ y` on pre-games built using the constructor. -/ @[simp] theorem mk_le_mk {xl xr xL xR yl yr yL yR} : mk xl xr xL xR ≀ mk yl yr yL yR ↔ (βˆ€ i, xL i ⧏ mk yl yr yL yR) ∧ βˆ€ j, mk xl xr xL xR ⧏ yR j := le_iff_forall_lf theorem le_of_forall_lf {x y : pgame} (h₁ : βˆ€ i, x.move_left i ⧏ y) (hβ‚‚ : βˆ€ j, x ⧏ y.move_right j) : x ≀ y := le_iff_forall_lf.2 ⟨h₁, hβ‚‚βŸ© /-- Definition of `x ⧏ y` on pre-games, in terms of `≀`. The ordering here is chosen so that `or.inl` refer to moves by Left, and `or.inr` refer to moves by Right. -/ theorem lf_iff_exists_le {x y : pgame} : x ⧏ y ↔ (βˆƒ i, x ≀ y.move_left i) ∨ βˆƒ j, x.move_right j ≀ y := by { rw [lf, le_iff_forall_lf, not_and_distrib], simp } /-- Definition of `x ⧏ y` on pre-games built using the constructor. -/ @[simp] theorem mk_lf_mk {xl xr xL xR yl yr yL yR} : mk xl xr xL xR ⧏ mk yl yr yL yR ↔ (βˆƒ i, mk xl xr xL xR ≀ yL i) ∨ βˆƒ j, xR j ≀ mk yl yr yL yR := lf_iff_exists_le theorem le_or_gf (x y : pgame) : x ≀ y ∨ y ⧏ x := by { rw ←pgame.not_le, apply em } theorem move_left_lf_of_le {x y : pgame} (h : x ≀ y) (i) : x.move_left i ⧏ y := (le_iff_forall_lf.1 h).1 i alias move_left_lf_of_le ← _root_.has_le.le.move_left_lf theorem lf_move_right_of_le {x y : pgame} (h : x ≀ y) (j) : x ⧏ y.move_right j := (le_iff_forall_lf.1 h).2 j alias lf_move_right_of_le ← _root_.has_le.le.lf_move_right theorem lf_of_move_right_le {x y : pgame} {j} (h : x.move_right j ≀ y) : x ⧏ y := lf_iff_exists_le.2 $ or.inr ⟨j, h⟩ theorem lf_of_le_move_left {x y : pgame} {i} (h : x ≀ y.move_left i) : x ⧏ y := lf_iff_exists_le.2 $ or.inl ⟨i, h⟩ theorem lf_of_le_mk {xl xr xL xR y} : mk xl xr xL xR ≀ y β†’ βˆ€ i, xL i ⧏ y := move_left_lf_of_le theorem lf_of_mk_le {x yl yr yL yR} : x ≀ mk yl yr yL yR β†’ βˆ€ j, x ⧏ yR j := lf_move_right_of_le theorem mk_lf_of_le {xl xr y j} (xL) {xR : xr β†’ pgame} : xR j ≀ y β†’ mk xl xr xL xR ⧏ y := @lf_of_move_right_le (mk _ _ _ _) y j theorem lf_mk_of_le {x yl yr} {yL : yl β†’ pgame} (yR) {i} : x ≀ yL i β†’ x ⧏ mk yl yr yL yR := @lf_of_le_move_left x (mk _ _ _ _) i /- We prove that `x ≀ y β†’ y ≀ z ← x ≀ z` inductively, by also simultaneously proving its cyclic reorderings. This auxiliary lemma is used during said induction. -/ private theorem le_trans_aux {x y z : pgame} (h₁ : βˆ€ {i}, y ≀ z β†’ z ≀ x.move_left i β†’ y ≀ x.move_left i) (hβ‚‚ : βˆ€ {j}, z.move_right j ≀ x β†’ x ≀ y β†’ z.move_right j ≀ y) (hxy : x ≀ y) (hyz : y ≀ z) : x ≀ z := le_of_forall_lf (Ξ» i, pgame.not_le.1 $ Ξ» h, (h₁ hyz h).not_gf $ hxy.move_left_lf i) (Ξ» j, pgame.not_le.1 $ Ξ» h, (hβ‚‚ h hxy).not_gf $ hyz.lf_move_right j) instance : preorder pgame := { le_refl := Ξ» x, begin induction x with _ _ _ _ IHl IHr, exact le_of_forall_lf (Ξ» i, lf_of_le_move_left (IHl i)) (Ξ» i, lf_of_move_right_le (IHr i)) end, le_trans := begin suffices : βˆ€ {x y z : pgame}, (x ≀ y β†’ y ≀ z β†’ x ≀ z) ∧ (y ≀ z β†’ z ≀ x β†’ y ≀ x) ∧ (z ≀ x β†’ x ≀ y β†’ z ≀ y), from Ξ» x y z, this.1, intros x y z, induction x with xl xr xL xR IHxl IHxr generalizing y z, induction y with yl yr yL yR IHyl IHyr generalizing z, induction z with zl zr zL zR IHzl IHzr, exact ⟨le_trans_aux (Ξ» i, (IHxl i).2.1) (Ξ» j, (IHzr j).2.2), le_trans_aux (Ξ» i, (IHyl i).2.2) (Ξ» j, (IHxr j).1), le_trans_aux (Ξ» i, (IHzl i).1) (Ξ» j, (IHyr j).2.1)⟩ end, lt := Ξ» x y, x ≀ y ∧ x ⧏ y, ..pgame.has_le, } theorem lt_iff_le_and_lf {x y : pgame} : x < y ↔ x ≀ y ∧ x ⧏ y := iff.rfl theorem lt_of_le_of_lf {x y : pgame} (h₁ : x ≀ y) (hβ‚‚ : x ⧏ y) : x < y := ⟨h₁, hβ‚‚βŸ© theorem lf_of_lt {x y : pgame} (h : x < y) : x ⧏ y := h.2 alias lf_of_lt ← _root_.has_lt.lt.lf theorem lf_irrefl (x : pgame) : Β¬ x ⧏ x := le_rfl.not_gf instance : is_irrefl _ (⧏) := ⟨lf_irrefl⟩ @[trans] theorem lf_of_le_of_lf {x y z : pgame} (h₁ : x ≀ y) (hβ‚‚ : y ⧏ z) : x ⧏ z := by { rw ←pgame.not_le at hβ‚‚ ⊒, exact Ξ» h₃, hβ‚‚ (h₃.trans h₁) } @[trans] theorem lf_of_lf_of_le {x y z : pgame} (h₁ : x ⧏ y) (hβ‚‚ : y ≀ z) : x ⧏ z := by { rw ←pgame.not_le at h₁ ⊒, exact Ξ» h₃, h₁ (hβ‚‚.trans h₃) } alias lf_of_le_of_lf ← _root_.has_le.le.trans_lf alias lf_of_lf_of_le ← lf.trans_le @[trans] theorem lf_of_lt_of_lf {x y z : pgame} (h₁ : x < y) (hβ‚‚ : y ⧏ z) : x ⧏ z := h₁.le.trans_lf hβ‚‚ @[trans] theorem lf_of_lf_of_lt {x y z : pgame} (h₁ : x ⧏ y) (hβ‚‚ : y < z) : x ⧏ z := h₁.trans_le hβ‚‚.le alias lf_of_lt_of_lf ← _root_.has_lt.lt.trans_lf alias lf_of_lf_of_lt ← lf.trans_lt theorem move_left_lf {x : pgame} : βˆ€ i, x.move_left i ⧏ x := le_rfl.move_left_lf theorem lf_move_right {x : pgame} : βˆ€ j, x ⧏ x.move_right j := le_rfl.lf_move_right theorem lf_mk {xl xr} (xL : xl β†’ pgame) (xR : xr β†’ pgame) (i) : xL i ⧏ mk xl xr xL xR := @move_left_lf (mk _ _ _ _) i theorem mk_lf {xl xr} (xL : xl β†’ pgame) (xR : xr β†’ pgame) (j) : mk xl xr xL xR ⧏ xR j := @lf_move_right (mk _ _ _ _) j /-- This special case of `pgame.le_of_forall_lf` is useful when dealing with surreals, where `<` is preferred over `⧏`. -/ theorem le_of_forall_lt {x y : pgame} (h₁ : βˆ€ i, x.move_left i < y) (hβ‚‚ : βˆ€ j, x < y.move_right j) : x ≀ y := le_of_forall_lf (Ξ» i, (h₁ i).lf) (Ξ» i, (hβ‚‚ i).lf) /-- The definition of `x ≀ y` on pre-games, in terms of `≀` two moves later. -/ theorem le_def {x y : pgame} : x ≀ y ↔ (βˆ€ i, (βˆƒ i', x.move_left i ≀ y.move_left i') ∨ βˆƒ j, (x.move_left i).move_right j ≀ y) ∧ βˆ€ j, (βˆƒ i, x ≀ (y.move_right j).move_left i) ∨ βˆƒ j', x.move_right j' ≀ y.move_right j := by { rw le_iff_forall_lf, conv { to_lhs, simp only [lf_iff_exists_le] } } /-- The definition of `x ⧏ y` on pre-games, in terms of `⧏` two moves later. -/ theorem lf_def {x y : pgame} : x ⧏ y ↔ (βˆƒ i, (βˆ€ i', x.move_left i' ⧏ y.move_left i) ∧ βˆ€ j, x ⧏ (y.move_left i).move_right j) ∨ βˆƒ j, (βˆ€ i, (x.move_right j).move_left i ⧏ y) ∧ βˆ€ j', x.move_right j ⧏ y.move_right j' := by { rw lf_iff_exists_le, conv { to_lhs, simp only [le_iff_forall_lf] } } /-- The definition of `0 ≀ x` on pre-games, in terms of `0 ⧏`. -/ theorem zero_le_lf {x : pgame} : 0 ≀ x ↔ βˆ€ j, 0 ⧏ x.move_right j := by { rw le_iff_forall_lf, simp } /-- The definition of `x ≀ 0` on pre-games, in terms of `⧏ 0`. -/ theorem le_zero_lf {x : pgame} : x ≀ 0 ↔ βˆ€ i, x.move_left i ⧏ 0 := by { rw le_iff_forall_lf, simp } /-- The definition of `0 ⧏ x` on pre-games, in terms of `0 ≀`. -/ theorem zero_lf_le {x : pgame} : 0 ⧏ x ↔ βˆƒ i, 0 ≀ x.move_left i := by { rw lf_iff_exists_le, simp } /-- The definition of `x ⧏ 0` on pre-games, in terms of `≀ 0`. -/ theorem lf_zero_le {x : pgame} : x ⧏ 0 ↔ βˆƒ j, x.move_right j ≀ 0 := by { rw lf_iff_exists_le, simp } /-- The definition of `0 ≀ x` on pre-games, in terms of `0 ≀` two moves later. -/ theorem zero_le {x : pgame} : 0 ≀ x ↔ βˆ€ j, βˆƒ i, 0 ≀ (x.move_right j).move_left i := by { rw le_def, simp } /-- The definition of `x ≀ 0` on pre-games, in terms of `≀ 0` two moves later. -/ theorem le_zero {x : pgame} : x ≀ 0 ↔ βˆ€ i, βˆƒ j, (x.move_left i).move_right j ≀ 0 := by { rw le_def, simp } /-- The definition of `0 ⧏ x` on pre-games, in terms of `0 ⧏` two moves later. -/ theorem zero_lf {x : pgame} : 0 ⧏ x ↔ βˆƒ i, βˆ€ j, 0 ⧏ (x.move_left i).move_right j := by { rw lf_def, simp } /-- The definition of `x ⧏ 0` on pre-games, in terms of `⧏ 0` two moves later. -/ theorem lf_zero {x : pgame} : x ⧏ 0 ↔ βˆƒ j, βˆ€ i, (x.move_right j).move_left i ⧏ 0 := by { rw lf_def, simp } @[simp] theorem zero_le_of_is_empty_right_moves (x : pgame) [is_empty x.right_moves] : 0 ≀ x := zero_le.2 is_empty_elim @[simp] theorem le_zero_of_is_empty_left_moves (x : pgame) [is_empty x.left_moves] : x ≀ 0 := le_zero.2 is_empty_elim /-- Given a game won by the right player when they play second, provide a response to any move by left. -/ noncomputable def right_response {x : pgame} (h : x ≀ 0) (i : x.left_moves) : (x.move_left i).right_moves := classical.some $ (le_zero.1 h) i /-- Show that the response for right provided by `right_response` preserves the right-player-wins condition. -/ lemma right_response_spec {x : pgame} (h : x ≀ 0) (i : x.left_moves) : (x.move_left i).move_right (right_response h i) ≀ 0 := classical.some_spec $ (le_zero.1 h) i /-- Given a game won by the left player when they play second, provide a response to any move by right. -/ noncomputable def left_response {x : pgame} (h : 0 ≀ x) (j : x.right_moves) : (x.move_right j).left_moves := classical.some $ (zero_le.1 h) j /-- Show that the response for left provided by `left_response` preserves the left-player-wins condition. -/ lemma left_response_spec {x : pgame} (h : 0 ≀ x) (j : x.right_moves) : 0 ≀ (x.move_right j).move_left (left_response h j) := classical.some_spec $ (zero_le.1 h) j /-- An explicit upper bound for a family of pre-games, whose left moves are the union of the left moves of all the pre-games in the family. -/ def upper_bound {ΞΉ : Type u} (f : ΞΉ β†’ pgame.{u}) : pgame := ⟨Σ i, (f i).left_moves, pempty, Ξ» x, move_left _ x.2, pempty.elim⟩ instance upper_bound_right_moves_empty {ΞΉ : Type u} (f : ΞΉ β†’ pgame.{u}) : is_empty (upper_bound f).right_moves := pempty.is_empty theorem le_upper_bound {ΞΉ : Type u} (f : ΞΉ β†’ pgame.{u}) (i : ΞΉ) : f i ≀ upper_bound f := begin rw [upper_bound, le_iff_forall_lf], dsimp, simp only [and_true, is_empty.forall_iff], exact Ξ» j, @move_left_lf (upper_bound f) ⟨i, j⟩ end lemma upper_bound_mem_upper_bounds (s : set pgame.{u}) [small.{u} s] : upper_bound (subtype.val ∘ (equiv_shrink s).symm) ∈ upper_bounds s := Ξ» i hi, by simpa using le_upper_bound (subtype.val ∘ (equiv_shrink s).symm) (equiv_shrink s ⟨i, hi⟩) /-- A small set `s` of pre-games is bounded above. -/ lemma bdd_above_of_small (s : set pgame.{u}) [small.{u} s] : bdd_above s := ⟨_, upper_bound_mem_upper_bounds s⟩ /-- An explicit lower bound for a family of pre-games, whose right moves are the union of the right moves of all the pre-games in the family. -/ def lower_bound {ΞΉ : Type u} (f : ΞΉ β†’ pgame.{u}) : pgame := ⟨pempty, Ξ£ i, (f i).right_moves, pempty.elim, Ξ» x, move_right _ x.2⟩ instance lower_bound_left_moves_empty {ΞΉ : Type u} (f : ΞΉ β†’ pgame.{u}) : is_empty (lower_bound f).left_moves := pempty.is_empty theorem lower_bound_le {ΞΉ : Type u} (f : ΞΉ β†’ pgame.{u}) (i : ΞΉ) : lower_bound f ≀ f i := begin rw [lower_bound, le_iff_forall_lf], dsimp, simp only [is_empty.forall_iff, true_and], exact Ξ» j, @lf_move_right (lower_bound f) ⟨i, j⟩ end lemma lower_bound_mem_lower_bounds (s : set pgame.{u}) [small.{u} s] : lower_bound (subtype.val ∘ (equiv_shrink s).symm) ∈ lower_bounds s := Ξ» i hi, by simpa using lower_bound_le (subtype.val ∘ (equiv_shrink s).symm) (equiv_shrink s ⟨i, hi⟩) /-- A small set `s` of pre-games is bounded below. -/ lemma bdd_below_of_small (s : set pgame.{u}) [small.{u} s] : bdd_below s := ⟨_, lower_bound_mem_lower_bounds s⟩ /-- The equivalence relation on pre-games. Two pre-games `x`, `y` are equivalent if `x ≀ y` and `y ≀ x`. If `x β‰ˆ 0`, then the second player can always win `x`. -/ def equiv (x y : pgame) : Prop := x ≀ y ∧ y ≀ x localized "infix (name := pgame.equiv) ` β‰ˆ ` := pgame.equiv" in pgame instance : is_equiv _ (β‰ˆ) := { refl := Ξ» x, ⟨le_rfl, le_rfl⟩, trans := Ξ» x y z ⟨xy, yx⟩ ⟨yz, zy⟩, ⟨xy.trans yz, zy.trans yx⟩, symm := Ξ» x y, and.symm } theorem equiv.le {x y : pgame} (h : x β‰ˆ y) : x ≀ y := h.1 theorem equiv.ge {x y : pgame} (h : x β‰ˆ y) : y ≀ x := h.2 @[refl, simp] theorem equiv_rfl {x} : x β‰ˆ x := refl x theorem equiv_refl (x) : x β‰ˆ x := refl x @[symm] protected theorem equiv.symm {x y} : x β‰ˆ y β†’ y β‰ˆ x := symm @[trans] protected theorem equiv.trans {x y z} : x β‰ˆ y β†’ y β‰ˆ z β†’ x β‰ˆ z := trans protected theorem equiv_comm {x y} : x β‰ˆ y ↔ y β‰ˆ x := comm theorem equiv_of_eq {x y} (h : x = y) : x β‰ˆ y := by subst h @[trans] theorem le_of_le_of_equiv {x y z} (h₁ : x ≀ y) (hβ‚‚ : y β‰ˆ z) : x ≀ z := h₁.trans hβ‚‚.1 @[trans] theorem le_of_equiv_of_le {x y z} (h₁ : x β‰ˆ y) : y ≀ z β†’ x ≀ z := h₁.1.trans theorem lf.not_equiv {x y} (h : x ⧏ y) : Β¬ x β‰ˆ y := Ξ» h', h.not_ge h'.2 theorem lf.not_equiv' {x y} (h : x ⧏ y) : Β¬ y β‰ˆ x := Ξ» h', h.not_ge h'.1 theorem lf.not_gt {x y} (h : x ⧏ y) : Β¬ y < x := Ξ» h', h.not_ge h'.le theorem le_congr_imp {x₁ y₁ xβ‚‚ yβ‚‚} (hx : x₁ β‰ˆ xβ‚‚) (hy : y₁ β‰ˆ yβ‚‚) (h : x₁ ≀ y₁) : xβ‚‚ ≀ yβ‚‚ := hx.2.trans (h.trans hy.1) theorem le_congr {x₁ y₁ xβ‚‚ yβ‚‚} (hx : x₁ β‰ˆ xβ‚‚) (hy : y₁ β‰ˆ yβ‚‚) : x₁ ≀ y₁ ↔ xβ‚‚ ≀ yβ‚‚ := ⟨le_congr_imp hx hy, le_congr_imp hx.symm hy.symm⟩ theorem le_congr_left {x₁ xβ‚‚ y} (hx : x₁ β‰ˆ xβ‚‚) : x₁ ≀ y ↔ xβ‚‚ ≀ y := le_congr hx equiv_rfl theorem le_congr_right {x y₁ yβ‚‚} (hy : y₁ β‰ˆ yβ‚‚) : x ≀ y₁ ↔ x ≀ yβ‚‚ := le_congr equiv_rfl hy theorem lf_congr {x₁ y₁ xβ‚‚ yβ‚‚} (hx : x₁ β‰ˆ xβ‚‚) (hy : y₁ β‰ˆ yβ‚‚) : x₁ ⧏ y₁ ↔ xβ‚‚ ⧏ yβ‚‚ := pgame.not_le.symm.trans $ (not_congr (le_congr hy hx)).trans pgame.not_le theorem lf_congr_imp {x₁ y₁ xβ‚‚ yβ‚‚} (hx : x₁ β‰ˆ xβ‚‚) (hy : y₁ β‰ˆ yβ‚‚) : x₁ ⧏ y₁ β†’ xβ‚‚ ⧏ yβ‚‚ := (lf_congr hx hy).1 theorem lf_congr_left {x₁ xβ‚‚ y} (hx : x₁ β‰ˆ xβ‚‚) : x₁ ⧏ y ↔ xβ‚‚ ⧏ y := lf_congr hx equiv_rfl theorem lf_congr_right {x y₁ yβ‚‚} (hy : y₁ β‰ˆ yβ‚‚) : x ⧏ y₁ ↔ x ⧏ yβ‚‚ := lf_congr equiv_rfl hy @[trans] theorem lf_of_lf_of_equiv {x y z} (h₁ : x ⧏ y) (hβ‚‚ : y β‰ˆ z) : x ⧏ z := lf_congr_imp equiv_rfl hβ‚‚ h₁ @[trans] theorem lf_of_equiv_of_lf {x y z} (h₁ : x β‰ˆ y) : y ⧏ z β†’ x ⧏ z := lf_congr_imp h₁.symm equiv_rfl @[trans] theorem lt_of_lt_of_equiv {x y z} (h₁ : x < y) (hβ‚‚ : y β‰ˆ z) : x < z := h₁.trans_le hβ‚‚.1 @[trans] theorem lt_of_equiv_of_lt {x y z} (h₁ : x β‰ˆ y) : y < z β†’ x < z := h₁.1.trans_lt theorem lt_congr_imp {x₁ y₁ xβ‚‚ yβ‚‚} (hx : x₁ β‰ˆ xβ‚‚) (hy : y₁ β‰ˆ yβ‚‚) (h : x₁ < y₁) : xβ‚‚ < yβ‚‚ := hx.2.trans_lt (h.trans_le hy.1) theorem lt_congr {x₁ y₁ xβ‚‚ yβ‚‚} (hx : x₁ β‰ˆ xβ‚‚) (hy : y₁ β‰ˆ yβ‚‚) : x₁ < y₁ ↔ xβ‚‚ < yβ‚‚ := ⟨lt_congr_imp hx hy, lt_congr_imp hx.symm hy.symm⟩ theorem lt_congr_left {x₁ xβ‚‚ y} (hx : x₁ β‰ˆ xβ‚‚) : x₁ < y ↔ xβ‚‚ < y := lt_congr hx equiv_rfl theorem lt_congr_right {x y₁ yβ‚‚} (hy : y₁ β‰ˆ yβ‚‚) : x < y₁ ↔ x < yβ‚‚ := lt_congr equiv_rfl hy theorem lt_or_equiv_of_le {x y : pgame} (h : x ≀ y) : x < y ∨ x β‰ˆ y := and_or_distrib_left.mp ⟨h, (em $ y ≀ x).swap.imp_left pgame.not_le.1⟩ theorem lf_or_equiv_or_gf (x y : pgame) : x ⧏ y ∨ x β‰ˆ y ∨ y ⧏ x := begin by_cases h : x ⧏ y, { exact or.inl h }, { right, cases (lt_or_equiv_of_le (pgame.not_lf.1 h)) with h' h', { exact or.inr h'.lf }, { exact or.inl h'.symm } } end theorem equiv_congr_left {y₁ yβ‚‚} : y₁ β‰ˆ yβ‚‚ ↔ βˆ€ x₁, x₁ β‰ˆ y₁ ↔ x₁ β‰ˆ yβ‚‚ := ⟨λ h x₁, ⟨λ h', h'.trans h, Ξ» h', h'.trans h.symm⟩, Ξ» h, (h y₁).1 $ equiv_rfl⟩ theorem equiv_congr_right {x₁ xβ‚‚} : x₁ β‰ˆ xβ‚‚ ↔ βˆ€ y₁, x₁ β‰ˆ y₁ ↔ xβ‚‚ β‰ˆ y₁ := ⟨λ h y₁, ⟨λ h', h.symm.trans h', Ξ» h', h.trans h'⟩, Ξ» h, (h xβ‚‚).2 $ equiv_rfl⟩ theorem equiv_of_mk_equiv {x y : pgame} (L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves) (hl : βˆ€ i, x.move_left i β‰ˆ y.move_left (L i)) (hr : βˆ€ j, x.move_right j β‰ˆ y.move_right (R j)) : x β‰ˆ y := begin fsplit; rw le_def, { exact ⟨λ i, or.inl ⟨_, (hl i).1⟩, Ξ» j, or.inr ⟨_, by simpa using (hr (R.symm j)).1⟩⟩ }, { exact ⟨λ i, or.inl ⟨_, by simpa using (hl (L.symm i)).2⟩, Ξ» j, or.inr ⟨_, (hr j).2⟩⟩ } end /-- The fuzzy, confused, or incomparable relation on pre-games. If `x β€– 0`, then the first player can always win `x`. -/ def fuzzy (x y : pgame) : Prop := x ⧏ y ∧ y ⧏ x localized "infix (name := pgame.fuzzy) ` β€– `:50 := pgame.fuzzy" in pgame @[symm] theorem fuzzy.swap {x y : pgame} : x β€– y β†’ y β€– x := and.swap instance : is_symm _ (β€–) := ⟨λ x y, fuzzy.swap⟩ theorem fuzzy.swap_iff {x y : pgame} : x β€– y ↔ y β€– x := ⟨fuzzy.swap, fuzzy.swap⟩ theorem fuzzy_irrefl (x : pgame) : Β¬ x β€– x := Ξ» h, lf_irrefl x h.1 instance : is_irrefl _ (β€–) := ⟨fuzzy_irrefl⟩ theorem lf_iff_lt_or_fuzzy {x y : pgame} : x ⧏ y ↔ x < y ∨ x β€– y := by { simp only [lt_iff_le_and_lf, fuzzy, ←pgame.not_le], tauto! } theorem lf_of_fuzzy {x y : pgame} (h : x β€– y) : x ⧏ y := lf_iff_lt_or_fuzzy.2 (or.inr h) alias lf_of_fuzzy ← fuzzy.lf theorem lt_or_fuzzy_of_lf {x y : pgame} : x ⧏ y β†’ x < y ∨ x β€– y := lf_iff_lt_or_fuzzy.1 theorem fuzzy.not_equiv {x y : pgame} (h : x β€– y) : Β¬ x β‰ˆ y := Ξ» h', h'.1.not_gf h.2 theorem fuzzy.not_equiv' {x y : pgame} (h : x β€– y) : Β¬ y β‰ˆ x := Ξ» h', h'.2.not_gf h.2 theorem not_fuzzy_of_le {x y : pgame} (h : x ≀ y) : Β¬ x β€– y := Ξ» h', h'.2.not_ge h theorem not_fuzzy_of_ge {x y : pgame} (h : y ≀ x) : Β¬ x β€– y := Ξ» h', h'.1.not_ge h theorem equiv.not_fuzzy {x y : pgame} (h : x β‰ˆ y) : Β¬ x β€– y := not_fuzzy_of_le h.1 theorem equiv.not_fuzzy' {x y : pgame} (h : x β‰ˆ y) : Β¬ y β€– x := not_fuzzy_of_le h.2 theorem fuzzy_congr {x₁ y₁ xβ‚‚ yβ‚‚ : pgame} (hx : x₁ β‰ˆ xβ‚‚) (hy : y₁ β‰ˆ yβ‚‚) : x₁ β€– y₁ ↔ xβ‚‚ β€– yβ‚‚ := show _ ∧ _ ↔ _ ∧ _, by rw [lf_congr hx hy, lf_congr hy hx] theorem fuzzy_congr_imp {x₁ y₁ xβ‚‚ yβ‚‚ : pgame} (hx : x₁ β‰ˆ xβ‚‚) (hy : y₁ β‰ˆ yβ‚‚) : x₁ β€– y₁ β†’ xβ‚‚ β€– yβ‚‚ := (fuzzy_congr hx hy).1 theorem fuzzy_congr_left {x₁ xβ‚‚ y} (hx : x₁ β‰ˆ xβ‚‚) : x₁ β€– y ↔ xβ‚‚ β€– y := fuzzy_congr hx equiv_rfl theorem fuzzy_congr_right {x y₁ yβ‚‚} (hy : y₁ β‰ˆ yβ‚‚) : x β€– y₁ ↔ x β€– yβ‚‚ := fuzzy_congr equiv_rfl hy @[trans] theorem fuzzy_of_fuzzy_of_equiv {x y z} (h₁ : x β€– y) (hβ‚‚ : y β‰ˆ z) : x β€– z := (fuzzy_congr_right hβ‚‚).1 h₁ @[trans] theorem fuzzy_of_equiv_of_fuzzy {x y z} (h₁ : x β‰ˆ y) (hβ‚‚ : y β€– z) : x β€– z := (fuzzy_congr_left h₁).2 hβ‚‚ /-- Exactly one of the following is true (although we don't prove this here). -/ theorem lt_or_equiv_or_gt_or_fuzzy (x y : pgame) : x < y ∨ x β‰ˆ y ∨ y < x ∨ x β€– y := begin cases le_or_gf x y with h₁ h₁; cases le_or_gf y x with hβ‚‚ hβ‚‚, { right, left, exact ⟨h₁, hβ‚‚βŸ© }, { left, exact ⟨h₁, hβ‚‚βŸ© }, { right, right, left, exact ⟨hβ‚‚, hβ‚βŸ© }, { right, right, right, exact ⟨hβ‚‚, hβ‚βŸ© } end theorem lt_or_equiv_or_gf (x y : pgame) : x < y ∨ x β‰ˆ y ∨ y ⧏ x := begin rw [lf_iff_lt_or_fuzzy, fuzzy.swap_iff], exact lt_or_equiv_or_gt_or_fuzzy x y end /-! ### Relabellings -/ /-- `relabelling x y` says that `x` and `y` are really the same game, just dressed up differently. Specifically, there is a bijection between the moves for Left in `x` and in `y`, and similarly for Right, and under these bijections we inductively have `relabelling`s for the consequent games. -/ inductive relabelling : pgame.{u} β†’ pgame.{u} β†’ Type (u+1) | mk : Ξ  {x y : pgame} (L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves), (βˆ€ i, relabelling (x.move_left i) (y.move_left (L i))) β†’ (βˆ€ j, relabelling (x.move_right j) (y.move_right (R j))) β†’ relabelling x y localized "infix (name := pgame.relabelling) ` ≑r `:50 := pgame.relabelling" in pgame namespace relabelling variables {x y : pgame.{u}} /-- A constructor for relabellings swapping the equivalences. -/ def mk' (L : y.left_moves ≃ x.left_moves) (R : y.right_moves ≃ x.right_moves) (hL : βˆ€ i, x.move_left (L i) ≑r y.move_left i) (hR : βˆ€ j, x.move_right (R j) ≑r y.move_right j) : x ≑r y := ⟨L.symm, R.symm, Ξ» i, by simpa using hL (L.symm i), Ξ» j, by simpa using hR (R.symm j)⟩ /-- The equivalence between left moves of `x` and `y` given by the relabelling. -/ def left_moves_equiv : Ξ  (r : x ≑r y), x.left_moves ≃ y.left_moves | ⟨L, R, hL, hR⟩ := L @[simp] theorem mk_left_moves_equiv {x y L R hL hR} : (@relabelling.mk x y L R hL hR).left_moves_equiv = L := rfl @[simp] theorem mk'_left_moves_equiv {x y L R hL hR} : (@relabelling.mk' x y L R hL hR).left_moves_equiv = L.symm := rfl /-- The equivalence between right moves of `x` and `y` given by the relabelling. -/ def right_moves_equiv : Ξ  (r : x ≑r y), x.right_moves ≃ y.right_moves | ⟨L, R, hL, hR⟩ := R @[simp] theorem mk_right_moves_equiv {x y L R hL hR} : (@relabelling.mk x y L R hL hR).right_moves_equiv = R := rfl @[simp] theorem mk'_right_moves_equiv {x y L R hL hR} : (@relabelling.mk' x y L R hL hR).right_moves_equiv = R.symm := rfl /-- A left move of `x` is a relabelling of a left move of `y`. -/ def move_left : βˆ€ (r : x ≑r y) (i : x.left_moves), x.move_left i ≑r y.move_left (r.left_moves_equiv i) | ⟨L, R, hL, hR⟩ := hL /-- A left move of `y` is a relabelling of a left move of `x`. -/ def move_left_symm : βˆ€ (r : x ≑r y) (i : y.left_moves), x.move_left (r.left_moves_equiv.symm i) ≑r y.move_left i | ⟨L, R, hL, hR⟩ i := by simpa using hL (L.symm i) /-- A right move of `x` is a relabelling of a right move of `y`. -/ def move_right : βˆ€ (r : x ≑r y) (i : x.right_moves), x.move_right i ≑r y.move_right (r.right_moves_equiv i) | ⟨L, R, hL, hR⟩ := hR /-- A right move of `y` is a relabelling of a right move of `x`. -/ def move_right_symm : βˆ€ (r : x ≑r y) (i : y.right_moves), x.move_right (r.right_moves_equiv.symm i) ≑r y.move_right i | ⟨L, R, hL, hR⟩ i := by simpa using hR (R.symm i) /-- The identity relabelling. -/ @[refl] def refl : Ξ  (x : pgame), x ≑r x | x := ⟨equiv.refl _, equiv.refl _, Ξ» i, refl _, Ξ» j, refl _⟩ using_well_founded { dec_tac := pgame_wf_tac } instance (x : pgame) : inhabited (x ≑r x) := ⟨refl _⟩ /-- Flip a relabelling. -/ @[symm] def symm : Ξ  {x y : pgame}, x ≑r y β†’ y ≑r x | x y ⟨L, R, hL, hR⟩ := mk' L R (Ξ» i, (hL i).symm) (Ξ» j, (hR j).symm) theorem le : βˆ€ {x y : pgame} (r : x ≑r y), x ≀ y | x y r := le_def.2 ⟨λ i, or.inl ⟨_, (r.move_left i).le⟩, Ξ» j, or.inr ⟨_, (r.move_right_symm j).le⟩⟩ using_well_founded { dec_tac := pgame_wf_tac } theorem ge {x y : pgame} (r : x ≑r y) : y ≀ x := r.symm.le /-- A relabelling lets us prove equivalence of games. -/ theorem equiv (r : x ≑r y) : x β‰ˆ y := ⟨r.le, r.ge⟩ /-- Transitivity of relabelling. -/ @[trans] def trans : Ξ  {x y z : pgame}, x ≑r y β†’ y ≑r z β†’ x ≑r z | x y z ⟨L₁, R₁, hL₁, hRβ‚βŸ© ⟨Lβ‚‚, Rβ‚‚, hLβ‚‚, hRβ‚‚βŸ© := ⟨L₁.trans Lβ‚‚, R₁.trans Rβ‚‚, Ξ» i, (hL₁ i).trans (hLβ‚‚ _), Ξ» j, (hR₁ j).trans (hRβ‚‚ _)⟩ /-- Any game without left or right moves is a relabelling of 0. -/ def is_empty (x : pgame) [is_empty x.left_moves] [is_empty x.right_moves] : x ≑r 0 := ⟨equiv.equiv_pempty _, equiv.equiv_of_is_empty _ _, is_empty_elim, is_empty_elim⟩ end relabelling theorem equiv.is_empty (x : pgame) [is_empty x.left_moves] [is_empty x.right_moves] : x β‰ˆ 0 := (relabelling.is_empty x).equiv instance {x y : pgame} : has_coe (x ≑r y) (x β‰ˆ y) := ⟨relabelling.equiv⟩ /-- Replace the types indexing the next moves for Left and Right by equivalent types. -/ def relabel {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) : pgame := ⟨xl', xr', x.move_left ∘ el, x.move_right ∘ er⟩ @[simp] lemma relabel_move_left' {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) (i : xl') : move_left (relabel el er) i = x.move_left (el i) := rfl @[simp] lemma relabel_move_left {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) (i : x.left_moves) : move_left (relabel el er) (el.symm i) = x.move_left i := by simp @[simp] lemma relabel_move_right' {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) (j : xr') : move_right (relabel el er) j = x.move_right (er j) := rfl @[simp] lemma relabel_move_right {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) (j : x.right_moves) : move_right (relabel el er) (er.symm j) = x.move_right j := by simp /-- The game obtained by relabelling the next moves is a relabelling of the original game. -/ def relabel_relabelling {x : pgame} {xl' xr'} (el : xl' ≃ x.left_moves) (er : xr' ≃ x.right_moves) : x ≑r relabel el er := relabelling.mk' el er (Ξ» i, by simp) (Ξ» j, by simp) /-! ### Negation -/ /-- The negation of `{L | R}` is `{-R | -L}`. -/ def neg : pgame β†’ pgame | ⟨l, r, L, R⟩ := ⟨r, l, Ξ» i, neg (R i), Ξ» i, neg (L i)⟩ instance : has_neg pgame := ⟨neg⟩ @[simp] lemma neg_def {xl xr xL xR} : -(mk xl xr xL xR) = mk xr xl (Ξ» j, -(xR j)) (Ξ» i, -(xL i)) := rfl instance : has_involutive_neg pgame := { neg_neg := Ξ» x, begin induction x with xl xr xL xR ihL ihR, simp_rw [neg_def, ihL, ihR], exact ⟨rfl, rfl, heq.rfl, heq.rfl⟩, end, ..pgame.has_neg } instance : neg_zero_class pgame := { neg_zero := begin dsimp [has_zero.zero, has_neg.neg, neg], congr; funext i; cases i end, ..pgame.has_zero, ..pgame.has_neg } @[simp] lemma neg_of_lists (L R : list pgame) : -of_lists L R = of_lists (R.map (Ξ» x, -x)) (L.map (Ξ» x, -x)) := begin simp only [of_lists, neg_def, list.length_map, list.nth_le_map', eq_self_iff_true, true_and], split, all_goals { apply hfunext, { simp }, { intros a a' ha, congr' 2, have : βˆ€ {m n} (h₁ : m = n) {b : ulift (fin m)} {c : ulift (fin n)} (hβ‚‚ : b == c), (b.down : β„•) = ↑c.down, { rintros m n rfl b c rfl, refl }, exact this (list.length_map _ _).symm ha } } end theorem is_option_neg {x y : pgame} : is_option x (-y) ↔ is_option (-x) y := begin rw [is_option_iff, is_option_iff, or_comm], cases y, apply or_congr; { apply exists_congr, intro, rw neg_eq_iff_eq_neg, refl }, end @[simp] theorem is_option_neg_neg {x y : pgame} : is_option (-x) (-y) ↔ is_option x y := by rw [is_option_neg, neg_neg] theorem left_moves_neg : βˆ€ x : pgame, (-x).left_moves = x.right_moves | ⟨_, _, _, _⟩ := rfl theorem right_moves_neg : βˆ€ x : pgame, (-x).right_moves = x.left_moves | ⟨_, _, _, _⟩ := rfl /-- Turns a right move for `x` into a left move for `-x` and vice versa. Even though these types are the same (not definitionally so), this is the preferred way to convert between them. -/ def to_left_moves_neg {x : pgame} : x.right_moves ≃ (-x).left_moves := equiv.cast (left_moves_neg x).symm /-- Turns a left move for `x` into a right move for `-x` and vice versa. Even though these types are the same (not definitionally so), this is the preferred way to convert between them. -/ def to_right_moves_neg {x : pgame} : x.left_moves ≃ (-x).right_moves := equiv.cast (right_moves_neg x).symm lemma move_left_neg {x : pgame} (i) : (-x).move_left (to_left_moves_neg i) = -x.move_right i := by { cases x, refl } @[simp] lemma move_left_neg' {x : pgame} (i) : (-x).move_left i = -x.move_right (to_left_moves_neg.symm i) := by { cases x, refl } lemma move_right_neg {x : pgame} (i) : (-x).move_right (to_right_moves_neg i) = -(x.move_left i) := by { cases x, refl } @[simp] lemma move_right_neg' {x : pgame} (i) : (-x).move_right i = -x.move_left (to_right_moves_neg.symm i) := by { cases x, refl } lemma move_left_neg_symm {x : pgame} (i) : x.move_left (to_right_moves_neg.symm i) = -(-x).move_right i := by simp lemma move_left_neg_symm' {x : pgame} (i) : x.move_left i = -(-x).move_right (to_right_moves_neg i) := by simp lemma move_right_neg_symm {x : pgame} (i) : x.move_right (to_left_moves_neg.symm i) = -(-x).move_left i := by simp lemma move_right_neg_symm' {x : pgame} (i) : x.move_right i = -(-x).move_left (to_left_moves_neg i) := by simp /-- If `x` has the same moves as `y`, then `-x` has the sames moves as `-y`. -/ def relabelling.neg_congr : βˆ€ {x y : pgame}, x ≑r y β†’ -x ≑r -y | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ⟨L, R, hL, hR⟩ := ⟨R, L, Ξ» j, (hR j).neg_congr, Ξ» i, (hL i).neg_congr⟩ private theorem neg_le_lf_neg_iff : Ξ  {x y : pgame.{u}}, (-y ≀ -x ↔ x ≀ y) ∧ (-y ⧏ -x ↔ x ⧏ y) | (mk xl xr xL xR) (mk yl yr yL yR) := begin simp_rw [neg_def, mk_le_mk, mk_lf_mk, ← neg_def], split, { rw and_comm, apply and_congr; exact forall_congr (Ξ» _, neg_le_lf_neg_iff.2) }, { rw or_comm, apply or_congr; exact exists_congr (Ξ» _, neg_le_lf_neg_iff.1) }, end using_well_founded { dec_tac := pgame_wf_tac } @[simp] theorem neg_le_neg_iff {x y : pgame} : -y ≀ -x ↔ x ≀ y := neg_le_lf_neg_iff.1 @[simp] theorem neg_lf_neg_iff {x y : pgame} : -y ⧏ -x ↔ x ⧏ y := neg_le_lf_neg_iff.2 @[simp] theorem neg_lt_neg_iff {x y : pgame} : -y < -x ↔ x < y := by rw [lt_iff_le_and_lf, lt_iff_le_and_lf, neg_le_neg_iff, neg_lf_neg_iff] @[simp] theorem neg_equiv_neg_iff {x y : pgame} : -x β‰ˆ -y ↔ x β‰ˆ y := by rw [equiv, equiv, neg_le_neg_iff, neg_le_neg_iff, and.comm] @[simp] theorem neg_fuzzy_neg_iff {x y : pgame} : -x β€– -y ↔ x β€– y := by rw [fuzzy, fuzzy, neg_lf_neg_iff, neg_lf_neg_iff, and.comm] theorem neg_le_iff {x y : pgame} : -y ≀ x ↔ -x ≀ y := by rw [←neg_neg x, neg_le_neg_iff, neg_neg] theorem neg_lf_iff {x y : pgame} : -y ⧏ x ↔ -x ⧏ y := by rw [←neg_neg x, neg_lf_neg_iff, neg_neg] theorem neg_lt_iff {x y : pgame} : -y < x ↔ -x < y := by rw [←neg_neg x, neg_lt_neg_iff, neg_neg] theorem neg_equiv_iff {x y : pgame} : -x β‰ˆ y ↔ x β‰ˆ -y := by rw [←neg_neg y, neg_equiv_neg_iff, neg_neg] theorem neg_fuzzy_iff {x y : pgame} : -x β€– y ↔ x β€– -y := by rw [←neg_neg y, neg_fuzzy_neg_iff, neg_neg] theorem le_neg_iff {x y : pgame} : y ≀ -x ↔ x ≀ -y := by rw [←neg_neg x, neg_le_neg_iff, neg_neg] theorem lf_neg_iff {x y : pgame} : y ⧏ -x ↔ x ⧏ -y := by rw [←neg_neg x, neg_lf_neg_iff, neg_neg] theorem lt_neg_iff {x y : pgame} : y < -x ↔ x < -y := by rw [←neg_neg x, neg_lt_neg_iff, neg_neg] @[simp] theorem neg_le_zero_iff {x : pgame} : -x ≀ 0 ↔ 0 ≀ x := by rw [neg_le_iff, neg_zero] @[simp] theorem zero_le_neg_iff {x : pgame} : 0 ≀ -x ↔ x ≀ 0 := by rw [le_neg_iff, neg_zero] @[simp] theorem neg_lf_zero_iff {x : pgame} : -x ⧏ 0 ↔ 0 ⧏ x := by rw [neg_lf_iff, neg_zero] @[simp] theorem zero_lf_neg_iff {x : pgame} : 0 ⧏ -x ↔ x ⧏ 0 := by rw [lf_neg_iff, neg_zero] @[simp] theorem neg_lt_zero_iff {x : pgame} : -x < 0 ↔ 0 < x := by rw [neg_lt_iff, neg_zero] @[simp] theorem zero_lt_neg_iff {x : pgame} : 0 < -x ↔ x < 0 := by rw [lt_neg_iff, neg_zero] @[simp] theorem neg_equiv_zero_iff {x : pgame} : -x β‰ˆ 0 ↔ x β‰ˆ 0 := by rw [neg_equiv_iff, neg_zero] @[simp] theorem neg_fuzzy_zero_iff {x : pgame} : -x β€– 0 ↔ x β€– 0 := by rw [neg_fuzzy_iff, neg_zero] @[simp] theorem zero_equiv_neg_iff {x : pgame} : 0 β‰ˆ -x ↔ 0 β‰ˆ x := by rw [←neg_equiv_iff, neg_zero] @[simp] theorem zero_fuzzy_neg_iff {x : pgame} : 0 β€– -x ↔ 0 β€– x := by rw [←neg_fuzzy_iff, neg_zero] /-! ### Addition and subtraction -/ /-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/ instance : has_add pgame.{u} := ⟨λ x y, begin induction x with xl xr xL xR IHxl IHxr generalizing y, induction y with yl yr yL yR IHyl IHyr, have y := mk yl yr yL yR, refine ⟨xl βŠ• yl, xr βŠ• yr, sum.rec _ _, sum.rec _ _⟩, { exact Ξ» i, IHxl i y }, { exact IHyl }, { exact Ξ» i, IHxr i y }, { exact IHyr } end⟩ /-- The pre-game `((0+1)+β‹―)+1`. -/ instance : has_nat_cast pgame := ⟨nat.unary_cast⟩ @[simp] protected theorem nat_succ (n : β„•) : ((n + 1 : β„•) : pgame) = n + 1 := rfl instance is_empty_left_moves_add (x y : pgame.{u}) [is_empty x.left_moves] [is_empty y.left_moves] : is_empty (x + y).left_moves := begin unfreezingI { cases x, cases y }, apply is_empty_sum.2 ⟨_, _⟩, assumption' end instance is_empty_right_moves_add (x y : pgame.{u}) [is_empty x.right_moves] [is_empty y.right_moves] : is_empty (x + y).right_moves := begin unfreezingI { cases x, cases y }, apply is_empty_sum.2 ⟨_, _⟩, assumption' end /-- `x + 0` has exactly the same moves as `x`. -/ def add_zero_relabelling : Ξ  (x : pgame.{u}), x + 0 ≑r x | ⟨xl, xr, xL, xR⟩ := begin refine ⟨equiv.sum_empty xl pempty, equiv.sum_empty xr pempty, _, _⟩; rintro (⟨i⟩|⟨⟨⟩⟩); apply add_zero_relabelling end /-- `x + 0` is equivalent to `x`. -/ lemma add_zero_equiv (x : pgame.{u}) : x + 0 β‰ˆ x := (add_zero_relabelling x).equiv /-- `0 + x` has exactly the same moves as `x`. -/ def zero_add_relabelling : Ξ  (x : pgame.{u}), 0 + x ≑r x | ⟨xl, xr, xL, xR⟩ := begin refine ⟨equiv.empty_sum pempty xl, equiv.empty_sum pempty xr, _, _⟩; rintro (⟨⟨⟩⟩|⟨i⟩); apply zero_add_relabelling end /-- `0 + x` is equivalent to `x`. -/ lemma zero_add_equiv (x : pgame.{u}) : 0 + x β‰ˆ x := (zero_add_relabelling x).equiv theorem left_moves_add : βˆ€ (x y : pgame.{u}), (x + y).left_moves = (x.left_moves βŠ• y.left_moves) | ⟨_, _, _, _⟩ ⟨_, _, _, _⟩ := rfl theorem right_moves_add : βˆ€ (x y : pgame.{u}), (x + y).right_moves = (x.right_moves βŠ• y.right_moves) | ⟨_, _, _, _⟩ ⟨_, _, _, _⟩ := rfl /-- Converts a left move for `x` or `y` into a left move for `x + y` and vice versa. Even though these types are the same (not definitionally so), this is the preferred way to convert between them. -/ def to_left_moves_add {x y : pgame} : x.left_moves βŠ• y.left_moves ≃ (x + y).left_moves := equiv.cast (left_moves_add x y).symm /-- Converts a right move for `x` or `y` into a right move for `x + y` and vice versa. Even though these types are the same (not definitionally so), this is the preferred way to convert between them. -/ def to_right_moves_add {x y : pgame} : x.right_moves βŠ• y.right_moves ≃ (x + y).right_moves := equiv.cast (right_moves_add x y).symm @[simp] lemma mk_add_move_left_inl {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inl i) = (mk xl xr xL xR).move_left i + (mk yl yr yL yR) := rfl @[simp] lemma add_move_left_inl {x : pgame} (y : pgame) (i) : (x + y).move_left (to_left_moves_add (sum.inl i)) = x.move_left i + y := by { cases x, cases y, refl } @[simp] lemma mk_add_move_right_inl {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inl i) = (mk xl xr xL xR).move_right i + (mk yl yr yL yR) := rfl @[simp] lemma add_move_right_inl {x : pgame} (y : pgame) (i) : (x + y).move_right (to_right_moves_add (sum.inl i)) = x.move_right i + y := by { cases x, cases y, refl } @[simp] lemma mk_add_move_left_inr {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inr i) = (mk xl xr xL xR) + (mk yl yr yL yR).move_left i := rfl @[simp] lemma add_move_left_inr (x : pgame) {y : pgame} (i) : (x + y).move_left (to_left_moves_add (sum.inr i)) = x + y.move_left i := by { cases x, cases y, refl } @[simp] lemma mk_add_move_right_inr {xl xr yl yr} {xL xR yL yR} {i} : (mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inr i) = (mk xl xr xL xR) + (mk yl yr yL yR).move_right i := rfl @[simp] lemma add_move_right_inr (x : pgame) {y : pgame} (i) : (x + y).move_right (to_right_moves_add (sum.inr i)) = x + y.move_right i := by { cases x, cases y, refl } lemma left_moves_add_cases {x y : pgame} (k) {P : (x + y).left_moves β†’ Prop} (hl : βˆ€ i, P $ to_left_moves_add (sum.inl i)) (hr : βˆ€ i, P $ to_left_moves_add (sum.inr i)) : P k := begin rw ←to_left_moves_add.apply_symm_apply k, cases to_left_moves_add.symm k with i i, { exact hl i }, { exact hr i } end lemma right_moves_add_cases {x y : pgame} (k) {P : (x + y).right_moves β†’ Prop} (hl : βˆ€ j, P $ to_right_moves_add (sum.inl j)) (hr : βˆ€ j, P $ to_right_moves_add (sum.inr j)) : P k := begin rw ←to_right_moves_add.apply_symm_apply k, cases to_right_moves_add.symm k with i i, { exact hl i }, { exact hr i } end instance is_empty_nat_right_moves : βˆ€ n : β„•, is_empty (right_moves n) | 0 := pempty.is_empty | (n + 1) := begin haveI := is_empty_nat_right_moves n, rw [pgame.nat_succ, right_moves_add], apply_instance end /-- If `w` has the same moves as `x` and `y` has the same moves as `z`, then `w + y` has the same moves as `x + z`. -/ def relabelling.add_congr : βˆ€ {w x y z : pgame.{u}}, w ≑r x β†’ y ≑r z β†’ w + y ≑r x + z | ⟨wl, wr, wL, wR⟩ ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ⟨zl, zr, zL, zR⟩ ⟨L₁, R₁, hL₁, hRβ‚βŸ© ⟨Lβ‚‚, Rβ‚‚, hLβ‚‚, hRβ‚‚βŸ© := begin let Hwx : ⟨wl, wr, wL, wR⟩ ≑r ⟨xl, xr, xL, xR⟩ := ⟨L₁, R₁, hL₁, hRβ‚βŸ©, let Hyz : ⟨yl, yr, yL, yR⟩ ≑r ⟨zl, zr, zL, zR⟩ := ⟨Lβ‚‚, Rβ‚‚, hLβ‚‚, hRβ‚‚βŸ©, refine ⟨equiv.sum_congr L₁ Lβ‚‚, equiv.sum_congr R₁ Rβ‚‚, _, _⟩; rintro (i|j), { exact (hL₁ i).add_congr Hyz }, { exact Hwx.add_congr (hLβ‚‚ j) }, { exact (hR₁ i).add_congr Hyz }, { exact Hwx.add_congr (hRβ‚‚ j) } end using_well_founded { dec_tac := pgame_wf_tac } instance : has_sub pgame := ⟨λ x y, x + -y⟩ @[simp] theorem sub_zero (x : pgame) : x - 0 = x + 0 := show x + -0 = x + 0, by rw neg_zero /-- If `w` has the same moves as `x` and `y` has the same moves as `z`, then `w - y` has the same moves as `x - z`. -/ def relabelling.sub_congr {w x y z : pgame} (h₁ : w ≑r x) (hβ‚‚ : y ≑r z) : w - y ≑r x - z := h₁.add_congr hβ‚‚.neg_congr /-- `-(x + y)` has exactly the same moves as `-x + -y`. -/ def neg_add_relabelling : Ξ  (x y : pgame), -(x + y) ≑r -x + -y | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ := begin refine ⟨equiv.refl _, equiv.refl _, _, _⟩, all_goals { exact Ξ» j, sum.cases_on j (Ξ» j, neg_add_relabelling _ _) (Ξ» j, neg_add_relabelling ⟨xl, xr, xL, xR⟩ _) } end using_well_founded { dec_tac := pgame_wf_tac } theorem neg_add_le {x y : pgame} : -(x + y) ≀ -x + -y := (neg_add_relabelling x y).le /-- `x + y` has exactly the same moves as `y + x`. -/ def add_comm_relabelling : Ξ  (x y : pgame.{u}), x + y ≑r y + x | (mk xl xr xL xR) (mk yl yr yL yR) := begin refine ⟨equiv.sum_comm _ _, equiv.sum_comm _ _, _, _⟩; rintros (_|_); { dsimp [left_moves_add, right_moves_add], apply add_comm_relabelling } end using_well_founded { dec_tac := pgame_wf_tac } theorem add_comm_le {x y : pgame} : x + y ≀ y + x := (add_comm_relabelling x y).le theorem add_comm_equiv {x y : pgame} : x + y β‰ˆ y + x := (add_comm_relabelling x y).equiv /-- `(x + y) + z` has exactly the same moves as `x + (y + z)`. -/ def add_assoc_relabelling : Ξ  (x y z : pgame.{u}), x + y + z ≑r x + (y + z) | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ⟨zl, zr, zL, zR⟩ := begin refine ⟨equiv.sum_assoc _ _ _, equiv.sum_assoc _ _ _, _, _⟩, all_goals { rintro (⟨i|i⟩|i) <|> rintro (j|⟨j|j⟩), { apply add_assoc_relabelling }, { apply add_assoc_relabelling ⟨xl, xr, xL, xR⟩ }, { apply add_assoc_relabelling ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ } } end using_well_founded { dec_tac := pgame_wf_tac } theorem add_assoc_equiv {x y z : pgame} : (x + y) + z β‰ˆ x + (y + z) := (add_assoc_relabelling x y z).equiv theorem add_left_neg_le_zero : βˆ€ (x : pgame), -x + x ≀ 0 | ⟨xl, xr, xL, xR⟩ := le_zero.2 $ Ξ» i, begin cases i, { -- If Left played in -x, Right responds with the same move in x. refine ⟨@to_right_moves_add _ ⟨_, _, _, _⟩ (sum.inr i), _⟩, convert @add_left_neg_le_zero (xR i), apply add_move_right_inr }, { -- If Left in x, Right responds with the same move in -x. dsimp, refine ⟨@to_right_moves_add ⟨_, _, _, _⟩ _ (sum.inl i), _⟩, convert @add_left_neg_le_zero (xL i), apply add_move_right_inl } end theorem zero_le_add_left_neg (x : pgame) : 0 ≀ -x + x := begin rw [←neg_le_neg_iff, neg_zero], exact neg_add_le.trans (add_left_neg_le_zero _) end theorem add_left_neg_equiv (x : pgame) : -x + x β‰ˆ 0 := ⟨add_left_neg_le_zero x, zero_le_add_left_neg x⟩ theorem add_right_neg_le_zero (x : pgame) : x + -x ≀ 0 := add_comm_le.trans (add_left_neg_le_zero x) theorem zero_le_add_right_neg (x : pgame) : 0 ≀ x + -x := (zero_le_add_left_neg x).trans add_comm_le theorem add_right_neg_equiv (x : pgame) : x + -x β‰ˆ 0 := ⟨add_right_neg_le_zero x, zero_le_add_right_neg x⟩ theorem sub_self_equiv : βˆ€ x, x - x β‰ˆ 0 := add_right_neg_equiv private lemma add_le_add_right' : βˆ€ {x y z : pgame} (h : x ≀ y), x + z ≀ y + z | (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) := Ξ» h, begin refine le_def.2 ⟨λ i, _, Ξ» i, _⟩; cases i, { rw le_def at h, cases h, rcases h_left i with ⟨i', ih⟩ | ⟨j, jh⟩, { exact or.inl ⟨to_left_moves_add (sum.inl i'), add_le_add_right' ih⟩ }, { refine or.inr ⟨to_right_moves_add (sum.inl j), _⟩, convert add_le_add_right' jh, apply add_move_right_inl } }, { exact or.inl ⟨@to_left_moves_add _ ⟨_, _, _, _⟩ (sum.inr i), add_le_add_right' h⟩ }, { rw le_def at h, cases h, rcases h_right i with ⟨i, ih⟩ | ⟨j', jh⟩, { refine or.inl ⟨to_left_moves_add (sum.inl i), _⟩, convert add_le_add_right' ih, apply add_move_left_inl }, { exact or.inr ⟨to_right_moves_add (sum.inl j'), add_le_add_right' jh⟩ } }, { exact or.inr ⟨@to_right_moves_add _ ⟨_, _, _, _⟩ (sum.inr i), add_le_add_right' h⟩ } end using_well_founded { dec_tac := pgame_wf_tac } instance covariant_class_swap_add_le : covariant_class pgame pgame (swap (+)) (≀) := ⟨λ x y z, add_le_add_right'⟩ instance covariant_class_add_le : covariant_class pgame pgame (+) (≀) := ⟨λ x y z h, (add_comm_le.trans (add_le_add_right h x)).trans add_comm_le⟩ theorem add_lf_add_right {y z : pgame} (h : y ⧏ z) (x) : y + x ⧏ z + x := suffices z + x ≀ y + x β†’ z ≀ y, by { rw ←pgame.not_le at ⊒ h, exact mt this h }, Ξ» w, calc z ≀ z + 0 : (add_zero_relabelling _).symm.le ... ≀ z + (x + -x) : add_le_add_left (zero_le_add_right_neg x) _ ... ≀ z + x + -x : (add_assoc_relabelling _ _ _).symm.le ... ≀ y + x + -x : add_le_add_right w _ ... ≀ y + (x + -x) : (add_assoc_relabelling _ _ _).le ... ≀ y + 0 : add_le_add_left (add_right_neg_le_zero x) _ ... ≀ y : (add_zero_relabelling _).le theorem add_lf_add_left {y z : pgame} (h : y ⧏ z) (x) : x + y ⧏ x + z := by { rw lf_congr add_comm_equiv add_comm_equiv, apply add_lf_add_right h } instance covariant_class_swap_add_lt : covariant_class pgame pgame (swap (+)) (<) := ⟨λ x y z h, ⟨add_le_add_right h.1 x, add_lf_add_right h.2 x⟩⟩ instance covariant_class_add_lt : covariant_class pgame pgame (+) (<) := ⟨λ x y z h, ⟨add_le_add_left h.1 x, add_lf_add_left h.2 x⟩⟩ theorem add_lf_add_of_lf_of_le {w x y z : pgame} (hwx : w ⧏ x) (hyz : y ≀ z) : w + y ⧏ x + z := lf_of_lf_of_le (add_lf_add_right hwx y) (add_le_add_left hyz x) theorem add_lf_add_of_le_of_lf {w x y z : pgame} (hwx : w ≀ x) (hyz : y ⧏ z) : w + y ⧏ x + z := lf_of_le_of_lf (add_le_add_right hwx y) (add_lf_add_left hyz x) theorem add_congr {w x y z : pgame} (h₁ : w β‰ˆ x) (hβ‚‚ : y β‰ˆ z) : w + y β‰ˆ x + z := ⟨(add_le_add_left hβ‚‚.1 w).trans (add_le_add_right h₁.1 z), (add_le_add_left hβ‚‚.2 x).trans (add_le_add_right h₁.2 y)⟩ theorem add_congr_left {x y z : pgame} (h : x β‰ˆ y) : x + z β‰ˆ y + z := add_congr h equiv_rfl theorem add_congr_right {x y z : pgame} : y β‰ˆ z β†’ x + y β‰ˆ x + z := add_congr equiv_rfl theorem sub_congr {w x y z : pgame} (h₁ : w β‰ˆ x) (hβ‚‚ : y β‰ˆ z) : w - y β‰ˆ x - z := add_congr h₁ (neg_equiv_neg_iff.2 hβ‚‚) theorem sub_congr_left {x y z : pgame} (h : x β‰ˆ y) : x - z β‰ˆ y - z := sub_congr h equiv_rfl theorem sub_congr_right {x y z : pgame} : y β‰ˆ z β†’ x - y β‰ˆ x - z := sub_congr equiv_rfl theorem le_iff_sub_nonneg {x y : pgame} : x ≀ y ↔ 0 ≀ y - x := ⟨λ h, (zero_le_add_right_neg x).trans (add_le_add_right h _), Ξ» h, calc x ≀ 0 + x : (zero_add_relabelling x).symm.le ... ≀ y - x + x : add_le_add_right h _ ... ≀ y + (-x + x) : (add_assoc_relabelling _ _ _).le ... ≀ y + 0 : add_le_add_left (add_left_neg_le_zero x) _ ... ≀ y : (add_zero_relabelling y).le⟩ theorem lf_iff_sub_zero_lf {x y : pgame} : x ⧏ y ↔ 0 ⧏ y - x := ⟨λ h, (zero_le_add_right_neg x).trans_lf (add_lf_add_right h _), Ξ» h, calc x ≀ 0 + x : (zero_add_relabelling x).symm.le ... ⧏ y - x + x : add_lf_add_right h _ ... ≀ y + (-x + x) : (add_assoc_relabelling _ _ _).le ... ≀ y + 0 : add_le_add_left (add_left_neg_le_zero x) _ ... ≀ y : (add_zero_relabelling y).le⟩ theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x := ⟨λ h, lt_of_le_of_lt (zero_le_add_right_neg x) (add_lt_add_right h _), Ξ» h, calc x ≀ 0 + x : (zero_add_relabelling x).symm.le ... < y - x + x : add_lt_add_right h _ ... ≀ y + (-x + x) : (add_assoc_relabelling _ _ _).le ... ≀ y + 0 : add_le_add_left (add_left_neg_le_zero x) _ ... ≀ y : (add_zero_relabelling y).le⟩ /-! ### Special pre-games -/ /-- The pre-game `star`, which is fuzzy with zero. -/ def star : pgame.{u} := ⟨punit, punit, Ξ» _, 0, Ξ» _, 0⟩ @[simp] theorem star_left_moves : star.left_moves = punit := rfl @[simp] theorem star_right_moves : star.right_moves = punit := rfl @[simp] theorem star_move_left (x) : star.move_left x = 0 := rfl @[simp] theorem star_move_right (x) : star.move_right x = 0 := rfl instance unique_star_left_moves : unique star.left_moves := punit.unique instance unique_star_right_moves : unique star.right_moves := punit.unique theorem star_fuzzy_zero : star β€– 0 := ⟨by { rw lf_zero, use default, rintros ⟨⟩ }, by { rw zero_lf, use default, rintros ⟨⟩ }⟩ @[simp] theorem neg_star : -star = star := by simp [star] @[simp] protected theorem zero_lt_one : (0 : pgame) < 1 := lt_of_le_of_lf (zero_le_of_is_empty_right_moves 1) (zero_lf_le.2 ⟨default, le_rfl⟩) instance : zero_le_one_class pgame := ⟨pgame.zero_lt_one.le⟩ @[simp] theorem zero_lf_one : (0 : pgame) ⧏ 1 := pgame.zero_lt_one.lf end pgame
c4b941e5e947991c4b0da0ce3a92e5d4f06da9fe
5b273b8c05e2f73fb74340ce100ce261900a98cd
/disjoint_finset.lean
f969ffb0c640767458ee86b442670dde0cdc5663
[]
no_license
ChrisHughes24/leanstuff1
2eba44bc48da6e544e07495b41e1703f81dc1c24
cbcd788b8b1d07b20b2fff4482c870077a13d1c0
refs/heads/master
1,631,670,333,297
1,527,093,981,000
1,527,093,981,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,793
lean
import data.finset namespace finset variable {Ξ± : Type*} def disjoint (s t : finset Ξ±) : Prop := βˆ€ ⦃a⦄, a ∈ s β†’ a ∈ t β†’ false theorem disjoint.symm {s t : finset Ξ±} (d : disjoint s t) : disjoint t s | a iβ‚‚ i₁ := d i₁ iβ‚‚ @[simp] theorem disjoint_comm {s t : finset Ξ±} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : finset Ξ±} : disjoint s t ↔ βˆ€ {a}, a ∈ s β†’ a βˆ‰ t := iff.rfl theorem disjoint_right {s t : finset Ξ±} : disjoint s t ↔ βˆ€ {a}, a ∈ t β†’ a βˆ‰ s := disjoint_comm theorem disjoint_iff_ne {s t : finset Ξ±} : disjoint s t ↔ βˆ€ a ∈ s, βˆ€ b ∈ t, a β‰  b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : finset Ξ±} (h : s βŠ† u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : finset Ξ±} (h : t βŠ† u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) @[simp] theorem empty_disjoint (l : finset Ξ±) : disjoint βˆ… l | a := (not_mem_empty a).elim @[simp] theorem singleton_disjoint [decidable_eq Ξ±] {l : finset Ξ±} {a : Ξ±} : disjoint (singleton a) l ↔ a βˆ‰ l := by simp [disjoint]; refl @[simp] theorem disjoint_singleton [decidable_eq Ξ±] {l : finset Ξ±} {a : Ξ±} : disjoint l (singleton a) ↔ a βˆ‰ l := by rw disjoint_comm; simp @[simp] theorem disjoint_insert_left [decidable_eq Ξ±] {a : Ξ±} {s t : finset Ξ±} : disjoint (insert a s) t ↔ a βˆ‰ t ∧ disjoint s t := by simp [disjoint, or_imp_distrib, forall_and_distrib]; refl @[simp] theorem disjoint_insert_right [decidable_eq Ξ±] {a : Ξ±} {s t : finset Ξ±} : disjoint s (insert a t) ↔ a βˆ‰ s ∧ disjoint s t := disjoint_comm.trans $ by simp [disjoint_insert_left] theorem inter_eq_empty_iff_disjoint [decidable_eq Ξ±] {s t : finset Ξ±} : s ∩ t = βˆ… ↔ disjoint s t := by simp [ext, mem_inter]; refl theorem inter_eq_zero_iff_disjoint [decidable_eq Ξ±] {s t : finset Ξ±} : s ∩ t = βˆ… ↔ disjoint s t := by rw ← subset_empty; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq Ξ±] {s t u : finset Ξ±} : disjoint (s βˆͺ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq Ξ±] {s t u : finset Ξ±} : disjoint s (t βˆͺ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_val {s t : finset Ξ±} : multiset.disjoint s.1 t.1 ↔ disjoint s t := by simp [disjoint, multiset.disjoint, mem_def] @[simp] theorem card_disjoint_union [decidable_eq Ξ±] {s t : finset Ξ±} : disjoint s t β†’ card (s βˆͺ t) = card s + card t := finset.induction_on s (by simp) $ begin simp {contextual := tt} end end finset
2b0203d93d224709956b728868cb7e44a08ef01c
6329dd15b8fd567a4737f2dacd02bd0e8c4b3ae4
/src/game/world1/level1.lean
489c394c84218cd5fbce620ff85698c8caf82495
[ "Apache-2.0" ]
permissive
agusakov/mathematics_in_lean_game
76e455a688a8826b05160c16c0490b9e3d39f071
ad45fd42148f2203b973537adec7e8a48677ba2a
refs/heads/master
1,666,147,402,274
1,592,119,137,000
1,592,119,137,000
272,111,226
0
0
null
null
null
null
UTF-8
Lean
false
false
1,845
lean
import data.real.basic --imports the real numbers import tactic.maths_in_lean_game -- hide namespace calculating -- hide /- Axiom : mul_comm (a b : ℝ) : a * b = b * a -/ /- Axiom : mul_assoc (a b c : ℝ) : (a * b) * c = a * (b * c) -/ /- #Calculating ## Level 1: The `rw` tactic. We generally learn to carry out mathematical calculations without thinking of them as proofs. But when we justify each step in a calculation, as Lean requires us to do, the net result is a proof that the left-hand side of the calculation is equal to the right-hand side. In Lean, stating a theorem is tantamount to stating a goal, namely, the goal of proving the theorem. Lean provides the `rewrite` tactic, abbreviated `rw`, to replace the left-hand side of an identity by the right-hand side in the goal. If `a`, `b`, and `c` are real numbers, `mul_assoc a b c` is the identity `a * b * c = a * (b * c)` and `mul_comm a b` is the identity `a * b = b * a`. In Lean, multiplication associates to the left, so the left-hand side of `mul_assoc` could also be written `(a * b) * c`. However, it is generally good style to be mindful of Lean's notational conventions and leave out parentheses when Lean does as well. Let's try out `rw`. First we use `rw mul_comm a b,` to swap $a$ with $b$, and then `rw mul_assoc b a c` to do associativity stuff. -/ /- Lemma : no-side-bar -/ lemma example1 (a b c : ℝ) : (a * b) * c = b * (a * c) := begin [maths_in_lean_game] rw mul_comm a b, rw mul_assoc b a c end /- As you move your cursor past each step of the proof, you can see the goal of the proof change. The `import` line at the beginning of the example imports the theory of the real numbers from `mathlib`. For the sake of brevity, we generally suppress information like this when it is repeated from example to example. -/ end calculating -- hide
902962e14589540053f0644bd8d675e87daa4b71
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/geometry/euclidean/triangle.lean
dbfad34a93f32df2e9eb832b945169b0c8a276ef
[ "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
19,223
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 geometry.euclidean.basic import tactic.interval_cases /-! # Triangles This file proves basic geometrical results about distances and angles in (possibly degenerate) triangles in real inner product spaces and Euclidean affine spaces. More specialized results, and results developed for simplices in general rather than just for triangles, are in separate files. Definitions and results that make sense in more general affine spaces rather than just in the Euclidean case go under `linear_algebra.affine_space`. ## Implementation notes Results in this file are generally given in a form with only those non-degeneracy conditions needed for the particular result, rather than requiring affine independence of the points of a triangle unnecessarily. ## References * https://en.wikipedia.org/wiki/Pythagorean_theorem * https://en.wikipedia.org/wiki/Law_of_cosines * https://en.wikipedia.org/wiki/Pons_asinorum * https://en.wikipedia.org/wiki/Sum_of_angles_of_a_triangle -/ noncomputable theory open_locale big_operators open_locale classical open_locale real open_locale real_inner_product_space namespace inner_product_geometry /-! ### Geometrical results on triangles in real inner product spaces This section develops some results on (possibly degenerate) triangles in real inner product spaces, where those definitions and results can most conveniently be developed in terms of vectors and then used to deduce corresponding results for Euclidean affine spaces. -/ variables {V : Type*} [inner_product_space ℝ V] /-- Pythagorean theorem, if-and-only-if vector angle form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two (x y : V) : βˆ₯x + yβˆ₯ * βˆ₯x + yβˆ₯ = βˆ₯xβˆ₯ * βˆ₯xβˆ₯ + βˆ₯yβˆ₯ * βˆ₯yβˆ₯ ↔ angle x y = Ο€ / 2 := begin rw norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, exact inner_eq_zero_iff_angle_eq_pi_div_two x y end /-- Pythagorean theorem, vector angle form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq' (x y : V) (h : angle x y = Ο€ / 2) : βˆ₯x + yβˆ₯ * βˆ₯x + yβˆ₯ = βˆ₯xβˆ₯ * βˆ₯xβˆ₯ + βˆ₯yβˆ₯ * βˆ₯yβˆ₯ := (norm_add_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector angle form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two (x y : V) : βˆ₯x - yβˆ₯ * βˆ₯x - yβˆ₯ = βˆ₯xβˆ₯ * βˆ₯xβˆ₯ + βˆ₯yβˆ₯ * βˆ₯yβˆ₯ ↔ angle x y = Ο€ / 2 := begin rw norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero, exact inner_eq_zero_iff_angle_eq_pi_div_two x y end /-- Pythagorean theorem, subtracting vectors, vector angle form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq' (x y : V) (h : angle x y = Ο€ / 2) : βˆ₯x - yβˆ₯ * βˆ₯x - yβˆ₯ = βˆ₯xβˆ₯ * βˆ₯xβˆ₯ + βˆ₯yβˆ₯ * βˆ₯yβˆ₯ := (norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two x y).2 h /-- Law of cosines (cosine rule), vector angle form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_sub_two_mul_norm_mul_norm_mul_cos_angle (x y : V) : βˆ₯x - yβˆ₯ * βˆ₯x - yβˆ₯ = βˆ₯xβˆ₯ * βˆ₯xβˆ₯ + βˆ₯yβˆ₯ * βˆ₯yβˆ₯ - 2 * βˆ₯xβˆ₯ * βˆ₯yβˆ₯ * real.cos (angle x y) := by rw [(show 2 * βˆ₯xβˆ₯ * βˆ₯yβˆ₯ * real.cos (angle x y) = 2 * (real.cos (angle x y) * (βˆ₯xβˆ₯ * βˆ₯yβˆ₯)), by ring), cos_angle_mul_norm_mul_norm, ←real_inner_self_eq_norm_sq, ←real_inner_self_eq_norm_sq, ←real_inner_self_eq_norm_sq, real_inner_sub_sub_self, sub_add_eq_add_sub] /-- Pons asinorum, vector angle form. -/ lemma angle_sub_eq_angle_sub_rev_of_norm_eq {x y : V} (h : βˆ₯xβˆ₯ = βˆ₯yβˆ₯) : angle x (x - y) = angle y (y - x) := begin refine real.inj_on_cos ⟨angle_nonneg _ _, angle_le_pi _ _⟩ ⟨angle_nonneg _ _, angle_le_pi _ _⟩ _, rw [cos_angle, cos_angle, h, ←neg_sub, norm_neg, neg_sub, inner_sub_right, inner_sub_right, real_inner_self_eq_norm_sq, real_inner_self_eq_norm_sq, h, real_inner_comm x y] end /-- Converse of pons asinorum, vector angle form. -/ lemma norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi {x y : V} (h : angle x (x - y) = angle y (y - x)) (hpi : angle x y β‰  Ο€) : βˆ₯xβˆ₯ = βˆ₯yβˆ₯ := begin replace h := real.arccos_inj_on (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x (x - y))) (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one y (y - x))) h, by_cases hxy : x = y, { rw hxy }, { rw [←norm_neg (y - x), neg_sub, mul_comm, mul_comm βˆ₯yβˆ₯, div_eq_mul_inv, div_eq_mul_inv, mul_inv_rev', mul_inv_rev', ←mul_assoc, ←mul_assoc] at h, replace h := mul_right_cancel' (inv_ne_zero (Ξ» hz, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 hz)))) h, rw [inner_sub_right, inner_sub_right, real_inner_comm x y, real_inner_self_eq_norm_sq, real_inner_self_eq_norm_sq, mul_sub_right_distrib, mul_sub_right_distrib, mul_self_mul_inv, mul_self_mul_inv, sub_eq_sub_iff_sub_eq_sub, ←mul_sub_left_distrib] at h, by_cases hx0 : x = 0, { rw [hx0, norm_zero, inner_zero_left, zero_mul, zero_sub, neg_eq_zero] at h, rw [hx0, norm_zero, h] }, { by_cases hy0 : y = 0, { rw [hy0, norm_zero, inner_zero_right, zero_mul, sub_zero] at h, rw [hy0, norm_zero, h] }, { rw [inv_sub_inv (Ξ» hz, hx0 (norm_eq_zero.1 hz)) (Ξ» hz, hy0 (norm_eq_zero.1 hz)), ←neg_sub, ←mul_div_assoc, mul_comm, mul_div_assoc, ←mul_neg_one] at h, symmetry, by_contradiction hyx, replace h := (mul_left_cancel' (sub_ne_zero_of_ne hyx) h).symm, rw [real_inner_div_norm_mul_norm_eq_neg_one_iff, ←angle_eq_pi_iff] at h, exact hpi h } } } end /-- The cosine of the sum of two angles in a possibly degenerate triangle (where two given sides are nonzero), vector angle form. -/ lemma cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle {x y : V} (hx : x β‰  0) (hy : y β‰  0) : real.cos (angle x (x - y) + angle y (y - x)) = -real.cos (angle x y) := begin by_cases hxy : x = y, { rw [hxy, angle_self hy], simp }, { rw [real.cos_add, cos_angle, cos_angle, cos_angle], have hxn : βˆ₯xβˆ₯ β‰  0 := (Ξ» h, hx (norm_eq_zero.1 h)), have hyn : βˆ₯yβˆ₯ β‰  0 := (Ξ» h, hy (norm_eq_zero.1 h)), have hxyn : βˆ₯x - yβˆ₯ β‰  0 := (Ξ» h, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 h))), apply mul_right_cancel' hxn, apply mul_right_cancel' hyn, apply mul_right_cancel' hxyn, apply mul_right_cancel' hxyn, have H1 : real.sin (angle x (x - y)) * real.sin (angle y (y - x)) * βˆ₯xβˆ₯ * βˆ₯yβˆ₯ * βˆ₯x - yβˆ₯ * βˆ₯x - yβˆ₯ = (real.sin (angle x (x - y)) * (βˆ₯xβˆ₯ * βˆ₯x - yβˆ₯)) * (real.sin (angle y (y - x)) * (βˆ₯yβˆ₯ * βˆ₯x - yβˆ₯)), { ring }, have H2 : βŸͺx, x⟫ * (inner x x - inner x y - (inner x y - inner y y)) - (inner x x - inner x y) * (inner x x - inner x y) = inner x x * inner y y - inner x y * inner x y, { ring }, have H3 : βŸͺy, y⟫ * (inner y y - inner x y - (inner x y - inner x x)) - (inner y y - inner x y) * (inner y y - inner x y) = inner x x * inner y y - inner x y * inner x y, { ring }, rw [mul_sub_right_distrib, mul_sub_right_distrib, mul_sub_right_distrib, mul_sub_right_distrib, H1, sin_angle_mul_norm_mul_norm, norm_sub_rev x y, sin_angle_mul_norm_mul_norm, norm_sub_rev y x, inner_sub_left, inner_sub_left, inner_sub_right, inner_sub_right, inner_sub_right, inner_sub_right, real_inner_comm x y, H2, H3, real.mul_self_sqrt (sub_nonneg_of_le (real_inner_mul_inner_self_le x y)), real_inner_self_eq_norm_sq, real_inner_self_eq_norm_sq, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two], field_simp [hxn, hyn, hxyn], ring } end /-- The sine of the sum of two angles in a possibly degenerate triangle (where two given sides are nonzero), vector angle form. -/ lemma sin_angle_sub_add_angle_sub_rev_eq_sin_angle {x y : V} (hx : x β‰  0) (hy : y β‰  0) : real.sin (angle x (x - y) + angle y (y - x)) = real.sin (angle x y) := begin by_cases hxy : x = y, { rw [hxy, angle_self hy], simp }, { rw [real.sin_add, cos_angle, cos_angle], have hxn : βˆ₯xβˆ₯ β‰  0 := (Ξ» h, hx (norm_eq_zero.1 h)), have hyn : βˆ₯yβˆ₯ β‰  0 := (Ξ» h, hy (norm_eq_zero.1 h)), have hxyn : βˆ₯x - yβˆ₯ β‰  0 := (Ξ» h, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 h))), apply mul_right_cancel' hxn, apply mul_right_cancel' hyn, apply mul_right_cancel' hxyn, apply mul_right_cancel' hxyn, have H1 : real.sin (angle x (x - y)) * (βŸͺy, y - x⟫ / (βˆ₯yβˆ₯ * βˆ₯y - xβˆ₯)) * βˆ₯xβˆ₯ * βˆ₯yβˆ₯ * βˆ₯x - yβˆ₯ = real.sin (angle x (x - y)) * (βˆ₯xβˆ₯ * βˆ₯x - yβˆ₯) * (βŸͺy, y - x⟫ / (βˆ₯yβˆ₯ * βˆ₯y - xβˆ₯)) * βˆ₯yβˆ₯, { ring }, have H2 : βŸͺx, x - y⟫ / (βˆ₯xβˆ₯ * βˆ₯y - xβˆ₯) * real.sin (angle y (y - x)) * βˆ₯xβˆ₯ * βˆ₯yβˆ₯ * βˆ₯y - xβˆ₯ = βŸͺx, x - y⟫ / (βˆ₯xβˆ₯ * βˆ₯y - xβˆ₯) * (real.sin (angle y (y - x)) * (βˆ₯yβˆ₯ * βˆ₯y - xβˆ₯)) * βˆ₯xβˆ₯, { ring }, have H3 : βŸͺx, x⟫ * (βŸͺx, x⟫ - βŸͺx, y⟫ - (βŸͺx, y⟫ - βŸͺy, y⟫)) - (βŸͺx, x⟫ - βŸͺx, y⟫) * (βŸͺx, x⟫ - βŸͺx, y⟫) = βŸͺx, x⟫ * βŸͺy, y⟫ - βŸͺx, y⟫ * βŸͺx, y⟫, { ring }, have H4 : βŸͺy, y⟫ * (βŸͺy, y⟫ - βŸͺx, y⟫ - (βŸͺx, y⟫ - βŸͺx, x⟫)) - (βŸͺy, y⟫ - βŸͺx, y⟫) * (βŸͺy, y⟫ - βŸͺx, y⟫) = βŸͺx, x⟫ * βŸͺy, y⟫ - βŸͺx, y⟫ * βŸͺx, y⟫, { ring }, rw [right_distrib, right_distrib, right_distrib, right_distrib, H1, sin_angle_mul_norm_mul_norm, norm_sub_rev x y, H2, sin_angle_mul_norm_mul_norm, norm_sub_rev y x, mul_assoc (real.sin (angle x y)), sin_angle_mul_norm_mul_norm, inner_sub_left, inner_sub_left, inner_sub_right, inner_sub_right, inner_sub_right, inner_sub_right, real_inner_comm x y, H3, H4, real_inner_self_eq_norm_sq, real_inner_self_eq_norm_sq, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two], field_simp [hxn, hyn, hxyn], ring } end /-- The cosine of the sum of the angles of a possibly degenerate triangle (where two given sides are nonzero), vector angle form. -/ lemma cos_angle_add_angle_sub_add_angle_sub_eq_neg_one {x y : V} (hx : x β‰  0) (hy : y β‰  0) : real.cos (angle x y + angle x (x - y) + angle y (y - x)) = -1 := by rw [add_assoc, real.cos_add, cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle hx hy, sin_angle_sub_add_angle_sub_rev_eq_sin_angle hx hy, ←neg_mul_eq_mul_neg, ←neg_add', add_comm, ←sq, ←sq, real.sin_sq_add_cos_sq] /-- The sine of the sum of the angles of a possibly degenerate triangle (where two given sides are nonzero), vector angle form. -/ lemma sin_angle_add_angle_sub_add_angle_sub_eq_zero {x y : V} (hx : x β‰  0) (hy : y β‰  0) : real.sin (angle x y + angle x (x - y) + angle y (y - x)) = 0 := begin rw [add_assoc, real.sin_add, cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle hx hy, sin_angle_sub_add_angle_sub_rev_eq_sin_angle hx hy], ring end /-- The sum of the angles of a possibly degenerate triangle (where the two given sides are nonzero), vector angle form. -/ lemma angle_add_angle_sub_add_angle_sub_eq_pi {x y : V} (hx : x β‰  0) (hy : y β‰  0) : angle x y + angle x (x - y) + angle y (y - x) = Ο€ := begin have hcos := cos_angle_add_angle_sub_add_angle_sub_eq_neg_one hx hy, have hsin := sin_angle_add_angle_sub_add_angle_sub_eq_zero hx hy, rw real.sin_eq_zero_iff at hsin, cases hsin with n hn, symmetry' at hn, have h0 : 0 ≀ angle x y + angle x (x - y) + angle y (y - x) := add_nonneg (add_nonneg (angle_nonneg _ _) (angle_nonneg _ _)) (angle_nonneg _ _), have h3 : angle x y + angle x (x - y) + angle y (y - x) ≀ Ο€ + Ο€ + Ο€ := add_le_add (add_le_add (angle_le_pi _ _) (angle_le_pi _ _)) (angle_le_pi _ _), have h3lt : angle x y + angle x (x - y) + angle y (y - x) < Ο€ + Ο€ + Ο€, { by_contradiction hnlt, have hxy : angle x y = Ο€, { by_contradiction hxy, exact hnlt (add_lt_add_of_lt_of_le (add_lt_add_of_lt_of_le (lt_of_le_of_ne (angle_le_pi _ _) hxy) (angle_le_pi _ _)) (angle_le_pi _ _)) }, rw hxy at hnlt, rw angle_eq_pi_iff at hxy, rcases hxy with ⟨hx, ⟨r, ⟨hr, hxr⟩⟩⟩, rw [hxr, ←one_smul ℝ x, ←mul_smul, mul_one, ←sub_smul, one_smul, sub_eq_add_neg, angle_smul_right_of_pos _ _ (add_pos zero_lt_one (neg_pos_of_neg hr)), angle_self hx, add_zero] at hnlt, apply hnlt, rw add_assoc, exact add_lt_add_left (lt_of_le_of_lt (angle_le_pi _ _) (lt_add_of_pos_right Ο€ real.pi_pos)) _ }, have hn0 : 0 ≀ n, { rw [hn, mul_nonneg_iff_right_nonneg_of_pos real.pi_pos] at h0, norm_cast at h0, exact h0 }, have hn3 : n < 3, { rw [hn, (show Ο€ + Ο€ + Ο€ = 3 * Ο€, by ring)] at h3lt, replace h3lt := lt_of_mul_lt_mul_right h3lt (le_of_lt real.pi_pos), norm_cast at h3lt, exact h3lt }, interval_cases n, { rw hn at hcos, simp at hcos, norm_num at hcos }, { rw hn, norm_num }, { rw hn at hcos, simp at hcos, norm_num at hcos }, end end inner_product_geometry namespace euclidean_geometry /-! ### Geometrical results on triangles in Euclidean affine spaces This section develops some geometrical definitions and results on (possible degenerate) triangles in Euclidean affine spaces. -/ open inner_product_geometry open_locale euclidean_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- Pythagorean theorem, if-and-only-if angle-at-point form. -/ lemma dist_sq_eq_dist_sq_add_dist_sq_iff_angle_eq_pi_div_two (p1 p2 p3 : P) : dist p1 p3 * dist p1 p3 = dist p1 p2 * dist p1 p2 + dist p3 p2 * dist p3 p2 ↔ ∠ p1 p2 p3 = Ο€ / 2 := by erw [pseudo_metric_space.dist_comm p3 p2, dist_eq_norm_vsub V p1 p3, dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p2 p3, ←norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two, vsub_sub_vsub_cancel_right p1, ←neg_vsub_eq_vsub_rev p2 p3, norm_neg] /-- Law of cosines (cosine rule), angle-at-point form. -/ lemma dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle (p1 p2 p3 : P) : dist p1 p3 * dist p1 p3 = dist p1 p2 * dist p1 p2 + dist p3 p2 * dist p3 p2 - 2 * dist p1 p2 * dist p3 p2 * real.cos (∠ p1 p2 p3) := begin rw [dist_eq_norm_vsub V p1 p3, dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p3 p2], unfold angle, convert norm_sub_sq_eq_norm_sq_add_norm_sq_sub_two_mul_norm_mul_norm_mul_cos_angle (p1 -α΅₯ p2 : V) (p3 -α΅₯ p2 : V), { exact (vsub_sub_vsub_cancel_right p1 p3 p2).symm }, { exact (vsub_sub_vsub_cancel_right p1 p3 p2).symm } end alias dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle ← law_cos /-- Pons asinorum, angle-at-point form. -/ lemma angle_eq_angle_of_dist_eq {p1 p2 p3 : P} (h : dist p1 p2 = dist p1 p3) : ∠ p1 p2 p3 = ∠ p1 p3 p2 := begin rw [dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p1 p3] at h, unfold angle, convert angle_sub_eq_angle_sub_rev_of_norm_eq h, { exact (vsub_sub_vsub_cancel_left p3 p2 p1).symm }, { exact (vsub_sub_vsub_cancel_left p2 p3 p1).symm } end /-- Converse of pons asinorum, angle-at-point form. -/ lemma dist_eq_of_angle_eq_angle_of_angle_ne_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = ∠ p1 p3 p2) (hpi : ∠ p2 p1 p3 β‰  Ο€) : dist p1 p2 = dist p1 p3 := begin unfold angle at h hpi, rw [dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p1 p3], rw [←angle_neg_neg, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] at hpi, rw [←vsub_sub_vsub_cancel_left p3 p2 p1, ←vsub_sub_vsub_cancel_left p2 p3 p1] at h, exact norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi h hpi end /-- The sum of the angles of a possibly degenerate triangle (where the given vertex is distinct from the others), angle-at-point. -/ lemma angle_add_angle_add_angle_eq_pi {p1 p2 p3 : P} (h2 : p2 β‰  p1) (h3 : p3 β‰  p1) : ∠ p1 p2 p3 + ∠ p2 p3 p1 + ∠ p3 p1 p2 = Ο€ := begin rw [add_assoc, add_comm, add_comm (∠ p2 p3 p1), angle_comm p2 p3 p1], unfold angle, rw [←angle_neg_neg (p1 -α΅₯ p3), ←angle_neg_neg (p1 -α΅₯ p2), neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev, ←vsub_sub_vsub_cancel_right p3 p2 p1, ←vsub_sub_vsub_cancel_right p2 p3 p1], exact angle_add_angle_sub_add_angle_sub_eq_pi (Ξ» he, h3 (vsub_eq_zero_iff_eq.1 he)) (Ξ» he, h2 (vsub_eq_zero_iff_eq.1 he)) end /-- Stewart's Theorem. -/ theorem dist_sq_mul_dist_add_dist_sq_mul_dist (a b c p : P) (h : ∠ b p c = Ο€) : dist a b ^ 2 * dist c p + dist a c ^ 2 * dist b p = dist b c * (dist a p ^ 2 + dist b p * dist c p) := begin rw [pow_two, pow_two, law_cos a p b, law_cos a p c, eq_sub_of_add_eq (angle_add_angle_eq_pi_of_angle_eq_pi a h), real.cos_pi_sub, dist_eq_add_dist_of_angle_eq_pi h], ring, end /-- Apollonius's Theorem. -/ theorem dist_sq_add_dist_sq_eq_two_mul_dist_midpoint_sq_add_half_dist_sq (a b c : P) : dist a b ^ 2 + dist a c ^ 2 = 2 * (dist a (midpoint ℝ b c) ^ 2 + (dist b c / 2) ^ 2) := begin by_cases hbc : b = c, { simp [hbc, midpoint_self, dist_self, two_mul] }, { let m := midpoint ℝ b c, have : dist b c β‰  0 := (dist_pos.mpr hbc).ne', have hm := dist_sq_mul_dist_add_dist_sq_mul_dist a b c m (angle_midpoint_eq_pi b c hbc), simp only [dist_left_midpoint, dist_right_midpoint, real.norm_two] at hm, calc dist a b ^ 2 + dist a c ^ 2 = 2 / dist b c * (dist a b ^ 2 * (2⁻¹ * dist b c) + dist a c ^ 2 * (2⁻¹ * dist b c)) : by { field_simp, ring } ... = 2 * (dist a (midpoint ℝ b c) ^ 2 + (dist b c / 2) ^ 2) : by { rw hm, field_simp, ring } }, end lemma dist_mul_of_eq_angle_of_dist_mul (a b c a' b' c' : P) (r : ℝ) (h : ∠ a' b' c' = ∠ a b c) (hab : dist a' b' = r * dist a b) (hcb : dist c' b' = r * dist c b) : dist a' c' = r * dist a c := begin have h' : dist a' c' ^ 2 = (r * dist a c) ^ 2, calc dist a' c' ^ 2 = dist a' b' ^ 2 + dist c' b' ^ 2 - 2 * dist a' b' * dist c' b' * real.cos (∠ a' b' c') : by { simp [pow_two, law_cos a' b' c'] } ... = r ^ 2 * (dist a b ^ 2 + dist c b ^ 2 - 2 * dist a b * dist c b * real.cos (∠ a b c)) : by { rw [h, hab, hcb], ring } ... = (r * dist a c) ^ 2 : by simp [pow_two, ← law_cos a b c, mul_pow], by_cases hab₁ : a = b, { have hab'₁ : a' = b', { rw [← dist_eq_zero, hab, dist_eq_zero.mpr hab₁, mul_zero r] }, rw [hab₁, hab'₁, dist_comm b' c', dist_comm b c, hcb] }, { have h1 : 0 ≀ r * dist a b, { rw ← hab, exact dist_nonneg }, have h2 : 0 ≀ r := nonneg_of_mul_nonneg_right h1 (dist_pos.mpr hab₁), exact (eq_of_sq_eq_sq dist_nonneg (mul_nonneg h2 dist_nonneg)).mp h' }, end end euclidean_geometry
cf766947312df35a31d104d2e58b8fee325f1274
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/hints/thursday/afternoon/category_theory/exercise1/hint2.lean
787902bde4159453a2f7ceea4222cdd89f56a7a7
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
851
lean
import category_theory.isomorphism import category_theory.yoneda open category_theory open opposite variables {C : Type*} [category C] def iso_of_hom_iso_attempt (X Y : C) (h : yoneda.obj X β‰… yoneda.obj Y) : X β‰… Y := { hom := begin -- We need to construct a morphism `X ⟢ Y`. -- Recall that the components `h.app Z` of our hypothesis are isomorphisms. -- We can check exactly what they are (if we've forgotten how `yoneda` works), like this: have := h.app, dsimp at this, -- This says that for any `Z : Cα΅’α΅–`, we get an isomorphism from -- the morphism space `unop Z ⟢ Z` to the morphism space `unop Z ⟢ Y`. -- This suggests we want to use `h.app (op X)`, and apply the forward direction of that -- to some element of `unop (op X) ⟢ X` that we have available. sorry end, inv := sorry, }
8753de0c113598183dc0941f9e76d0c48ae320e5
367134ba5a65885e863bdc4507601606690974c1
/src/data/zsqrtd/basic.lean
ed665d670673418d7495294dfb9269191300bffb
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
28,608
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.associated import tactic.ring /-- The ring of integers adjoined with a square root of `d`. These have the form `a + b √d` where `a b : β„€`. The components are called `re` and `im` by analogy to the negative `d` case, but of course both parts are real here since `d` is nonnegative. -/ structure zsqrtd (d : β„€) := (re : β„€) (im : β„€) prefix `β„€βˆš`:100 := zsqrtd namespace zsqrtd section parameters {d : β„€} instance : decidable_eq β„€βˆšd := by tactic.mk_dec_eq_instance theorem ext : βˆ€ {z w : β„€βˆšd}, z = w ↔ z.re = w.re ∧ z.im = w.im | ⟨x, y⟩ ⟨x', y'⟩ := ⟨λ h, by injection h; split; assumption, Ξ» ⟨h₁, hβ‚‚βŸ©, by congr; assumption⟩ /-- Convert an integer to a `β„€βˆšd` -/ def of_int (n : β„€) : β„€βˆšd := ⟨n, 0⟩ theorem of_int_re (n : β„€) : (of_int n).re = n := rfl theorem of_int_im (n : β„€) : (of_int n).im = 0 := rfl /-- The zero of the ring -/ def zero : β„€βˆšd := of_int 0 instance : has_zero β„€βˆšd := ⟨zsqrtd.zero⟩ @[simp] theorem zero_re : (0 : β„€βˆšd).re = 0 := rfl @[simp] theorem zero_im : (0 : β„€βˆšd).im = 0 := rfl instance : inhabited β„€βˆšd := ⟨0⟩ /-- The one of the ring -/ def one : β„€βˆšd := of_int 1 instance : has_one β„€βˆšd := ⟨zsqrtd.one⟩ @[simp] theorem one_re : (1 : β„€βˆšd).re = 1 := rfl @[simp] theorem one_im : (1 : β„€βˆšd).im = 0 := rfl /-- The representative of `√d` in the ring -/ def sqrtd : β„€βˆšd := ⟨0, 1⟩ @[simp] theorem sqrtd_re : (sqrtd : β„€βˆšd).re = 0 := rfl @[simp] theorem sqrtd_im : (sqrtd : β„€βˆšd).im = 1 := rfl /-- Addition of elements of `β„€βˆšd` -/ def add : β„€βˆšd β†’ β„€βˆšd β†’ β„€βˆšd | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x + x', y + y'⟩ instance : has_add β„€βˆšd := ⟨zsqrtd.add⟩ @[simp] theorem add_def (x y x' y' : β„€) : (⟨x, y⟩ + ⟨x', y'⟩ : β„€βˆšd) = ⟨x + x', y + y'⟩ := rfl @[simp] theorem add_re : βˆ€ z w : β„€βˆšd, (z + w).re = z.re + w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem add_im : βˆ€ z w : β„€βˆšd, (z + w).im = z.im + w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem bit0_re (z) : (bit0 z : β„€βˆšd).re = bit0 z.re := add_re _ _ @[simp] theorem bit0_im (z) : (bit0 z : β„€βˆšd).im = bit0 z.im := add_im _ _ @[simp] theorem bit1_re (z) : (bit1 z : β„€βˆšd).re = bit1 z.re := by simp [bit1] @[simp] theorem bit1_im (z) : (bit1 z : β„€βˆšd).im = bit0 z.im := by simp [bit1] /-- Negation in `β„€βˆšd` -/ def neg : β„€βˆšd β†’ β„€βˆšd | ⟨x, y⟩ := ⟨-x, -y⟩ instance : has_neg β„€βˆšd := ⟨zsqrtd.neg⟩ @[simp] theorem neg_re : βˆ€ z : β„€βˆšd, (-z).re = -z.re | ⟨x, y⟩ := rfl @[simp] theorem neg_im : βˆ€ z : β„€βˆšd, (-z).im = -z.im | ⟨x, y⟩ := rfl /-- Conjugation in `β„€βˆšd`. The conjugate of `a + b √d` is `a - b √d`. -/ def conj : β„€βˆšd β†’ β„€βˆšd | ⟨x, y⟩ := ⟨x, -y⟩ @[simp] theorem conj_re : βˆ€ z : β„€βˆšd, (conj z).re = z.re | ⟨x, y⟩ := rfl @[simp] theorem conj_im : βˆ€ z : β„€βˆšd, (conj z).im = -z.im | ⟨x, y⟩ := rfl /-- Multiplication in `β„€βˆšd` -/ def mul : β„€βˆšd β†’ β„€βˆšd β†’ β„€βˆšd | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x * x' + d * y * y', x * y' + y * x'⟩ instance : has_mul β„€βˆšd := ⟨zsqrtd.mul⟩ @[simp] theorem mul_re : βˆ€ z w : β„€βˆšd, (z * w).re = z.re * w.re + d * z.im * w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem mul_im : βˆ€ z w : β„€βˆšd, (z * w).im = z.re * w.im + z.im * w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl instance : comm_ring β„€βˆšd := by refine { add := (+), zero := 0, neg := has_neg.neg, mul := (*), sub := Ξ» a b, a + -b, one := 1, ..}; { intros, simp [ext, add_mul, mul_add, add_comm, add_left_comm, mul_comm, mul_left_comm] } instance : add_comm_monoid β„€βˆšd := by apply_instance instance : add_monoid β„€βˆšd := by apply_instance instance : monoid β„€βˆšd := by apply_instance instance : comm_monoid β„€βˆšd := by apply_instance instance : comm_semigroup β„€βˆšd := by apply_instance instance : semigroup β„€βˆšd := by apply_instance instance : add_comm_semigroup β„€βˆšd := by apply_instance instance : add_semigroup β„€βˆšd := by apply_instance instance : comm_semiring β„€βˆšd := by apply_instance instance : semiring β„€βˆšd := by apply_instance instance : ring β„€βˆšd := by apply_instance instance : distrib β„€βˆšd := by apply_instance instance : nontrivial β„€βˆšd := ⟨⟨0, 1, dec_trivial⟩⟩ @[simp] theorem coe_nat_re (n : β„•) : (n : β„€βˆšd).re = n := by induction n; simp * @[simp] theorem coe_nat_im (n : β„•) : (n : β„€βˆšd).im = 0 := by induction n; simp * theorem coe_nat_val (n : β„•) : (n : β„€βˆšd) = ⟨n, 0⟩ := by simp [ext] @[simp] theorem coe_int_re (n : β„€) : (n : β„€βˆšd).re = n := by cases n; simp [*, int.of_nat_eq_coe, int.neg_succ_of_nat_eq] @[simp] theorem coe_int_im (n : β„€) : (n : β„€βˆšd).im = 0 := by cases n; simp * theorem coe_int_val (n : β„€) : (n : β„€βˆšd) = ⟨n, 0⟩ := by simp [ext] instance : char_zero β„€βˆšd := { cast_injective := Ξ» m n, by simp [ext] } @[simp] theorem of_int_eq_coe (n : β„€) : (of_int n : β„€βˆšd) = n := by simp [ext, of_int_re, of_int_im] @[simp] theorem smul_val (n x y : β„€) : (n : β„€βˆšd) * ⟨x, y⟩ = ⟨n * x, n * y⟩ := by simp [ext] @[simp] theorem muld_val (x y : β„€) : sqrtd * ⟨x, y⟩ = ⟨d * y, x⟩ := by simp [ext] @[simp] theorem dmuld : sqrtd * sqrtd = d := by simp [ext] @[simp] theorem smuld_val (n x y : β„€) : sqrtd * (n : β„€βˆšd) * ⟨x, y⟩ = ⟨d * n * y, n * x⟩ := by simp [ext] theorem decompose {x y : β„€} : (⟨x, y⟩ : β„€βˆšd) = x + sqrtd * y := by simp [ext] theorem mul_conj {x y : β„€} : (⟨x, y⟩ * conj ⟨x, y⟩ : β„€βˆšd) = x * x - d * y * y := by simp [ext, sub_eq_add_neg, mul_comm] theorem conj_mul {a b : β„€βˆšd} : conj (a * b) = conj a * conj b := by { simp [ext], ring } protected lemma coe_int_add (m n : β„€) : (↑(m + n) : β„€βˆšd) = ↑m + ↑n := (int.cast_ring_hom _).map_add _ _ protected lemma coe_int_sub (m n : β„€) : (↑(m - n) : β„€βˆšd) = ↑m - ↑n := (int.cast_ring_hom _).map_sub _ _ protected lemma coe_int_mul (m n : β„€) : (↑(m * n) : β„€βˆšd) = ↑m * ↑n := (int.cast_ring_hom _).map_mul _ _ protected lemma coe_int_inj {m n : β„€} (h : (↑m : β„€βˆšd) = ↑n) : m = n := by simpa using congr_arg re h /-- Read `sq_le a c b d` as `a √c ≀ b √d` -/ def sq_le (a c b d : β„•) : Prop := c*a*a ≀ d*b*b theorem sq_le_of_le {c d x y z w : β„•} (xz : z ≀ x) (yw : y ≀ w) (xy : sq_le x c y d) : sq_le z c w d := le_trans (mul_le_mul (nat.mul_le_mul_left _ xz) xz (nat.zero_le _) (nat.zero_le _)) $ le_trans xy (mul_le_mul (nat.mul_le_mul_left _ yw) yw (nat.zero_le _) (nat.zero_le _)) theorem sq_le_add_mixed {c d x y z w : β„•} (xy : sq_le x c y d) (zw : sq_le z c w d) : c * (x * z) ≀ d * (y * w) := nat.mul_self_le_mul_self_iff.2 $ by simpa [mul_comm, mul_left_comm] using mul_le_mul xy zw (nat.zero_le _) (nat.zero_le _) theorem sq_le_add {c d x y z w : β„•} (xy : sq_le x c y d) (zw : sq_le z c w d) : sq_le (x + z) c (y + w) d := begin have xz := sq_le_add_mixed xy zw, simp [sq_le, mul_assoc] at xy zw, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_le_add, *] end theorem sq_le_cancel {c d x y z w : β„•} (zw : sq_le y d x c) (h : sq_le (x + z) c (y + w) d) : sq_le z c w d := begin apply le_of_not_gt, intro l, refine not_le_of_gt _ h, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_assoc], have hm := sq_le_add_mixed zw (le_of_lt l), simp [sq_le, mul_assoc] at l zw, exact lt_of_le_of_lt (add_le_add_right zw _) (add_lt_add_left (add_lt_add_of_le_of_lt hm (add_lt_add_of_le_of_lt hm l)) _) end theorem sq_le_smul {c d x y : β„•} (n : β„•) (xy : sq_le x c y d) : sq_le (n * x) c (n * y) d := by simpa [sq_le, mul_left_comm, mul_assoc] using nat.mul_le_mul_left (n * n) xy theorem sq_le_mul {d x y z w : β„•} : (sq_le x 1 y d β†’ sq_le z 1 w d β†’ sq_le (x * w + y * z) d (x * z + d * y * w) 1) ∧ (sq_le x 1 y d β†’ sq_le w d z 1 β†’ sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 β†’ sq_le z 1 w d β†’ sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 β†’ sq_le w d z 1 β†’ sq_le (x * w + y * z) d (x * z + d * y * w) 1) := by refine ⟨_, _, _, _⟩; { intros xy zw, have := int.mul_nonneg (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le xy)) (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le zw)), refine int.le_of_coe_nat_le_coe_nat (le_of_sub_nonneg _), convert this, simp only [one_mul, int.coe_nat_add, int.coe_nat_mul], ring } /-- "Generalized" `nonneg`. `nonnegg c d x y` means `a √c + b √d β‰₯ 0`; we are interested in the case `c = 1` but this is more symmetric -/ def nonnegg (c d : β„•) : β„€ β†’ β„€ β†’ Prop | (a : β„•) (b : β„•) := true | (a : β„•) -[1+ b] := sq_le (b+1) c a d | -[1+ a] (b : β„•) := sq_le (a+1) d b c | -[1+ a] -[1+ b] := false theorem nonnegg_comm {c d : β„•} {x y : β„€} : nonnegg c d x y = nonnegg d c y x := by induction x; induction y; refl theorem nonnegg_neg_pos {c d} : Ξ  {a b : β„•}, nonnegg c d (-a) b ↔ sq_le a d b c | 0 b := ⟨by simp [sq_le, nat.zero_le], Ξ»a, trivial⟩ | (a+1) b := by rw ← int.neg_succ_of_nat_coe; refl theorem nonnegg_pos_neg {c d} {a b : β„•} : nonnegg c d a (-b) ↔ sq_le b c a d := by rw nonnegg_comm; exact nonnegg_neg_pos theorem nonnegg_cases_right {c d} {a : β„•} : Ξ  {b : β„€}, (Ξ  x : β„•, b = -x β†’ sq_le x c a d) β†’ nonnegg c d a b | (b:nat) h := trivial | -[1+ b] h := h (b+1) rfl theorem nonnegg_cases_left {c d} {b : β„•} {a : β„€} (h : Ξ  x : β„•, a = -x β†’ sq_le x d b c) : nonnegg c d a b := cast nonnegg_comm (nonnegg_cases_right h) section norm def norm (n : β„€βˆšd) : β„€ := n.re * n.re - d * n.im * n.im @[simp] lemma norm_zero : norm 0 = 0 := by simp [norm] @[simp] lemma norm_one : norm 1 = 1 := by simp [norm] @[simp] lemma norm_int_cast (n : β„€) : norm n = n * n := by simp [norm] @[simp] lemma norm_nat_cast (n : β„•) : norm n = n * n := norm_int_cast n @[simp] lemma norm_mul (n m : β„€βˆšd) : norm (n * m) = norm n * norm m := by { simp only [norm, mul_im, mul_re], ring } lemma norm_eq_mul_conj (n : β„€βˆšd) : (norm n : β„€βˆšd) = n * n.conj := by cases n; simp [norm, conj, zsqrtd.ext, mul_comm, sub_eq_add_neg] instance : is_monoid_hom norm := { map_one := norm_one, map_mul := norm_mul } lemma norm_nonneg (hd : d ≀ 0) (n : β„€βˆšd) : 0 ≀ n.norm := add_nonneg (mul_self_nonneg _) (by rw [mul_assoc, neg_mul_eq_neg_mul]; exact (mul_nonneg (neg_nonneg.2 hd) (mul_self_nonneg _))) lemma norm_eq_one_iff {x : β„€βˆšd} : x.norm.nat_abs = 1 ↔ is_unit x := ⟨λ h, is_unit_iff_dvd_one.2 $ (le_total 0 (norm x)).cases_on (Ξ» hx, show x ∣ 1, from ⟨x.conj, by rwa [← int.coe_nat_inj', int.nat_abs_of_nonneg hx, ← @int.cast_inj (β„€βˆšd) _ _, norm_eq_mul_conj, eq_comm] at h⟩) (Ξ» hx, show x ∣ 1, from ⟨- x.conj, by rwa [← int.coe_nat_inj', int.of_nat_nat_abs_of_nonpos hx, ← @int.cast_inj (β„€βˆšd) _ _, int.cast_neg, norm_eq_mul_conj, neg_mul_eq_mul_neg, eq_comm] at h⟩), Ξ» h, let ⟨y, hy⟩ := is_unit_iff_dvd_one.1 h in begin have := congr_arg (int.nat_abs ∘ norm) hy, rw [function.comp_app, function.comp_app, norm_mul, int.nat_abs_mul, norm_one, int.nat_abs_one, eq_comm, nat.mul_eq_one_iff] at this, exact this.1 end⟩ end norm end section parameter {d : β„•} /-- Nonnegativity of an element of `β„€βˆšd`. -/ def nonneg : β„€βˆšd β†’ Prop | ⟨a, b⟩ := nonnegg d 1 a b protected def le (a b : β„€βˆšd) : Prop := nonneg (b - a) instance : has_le β„€βˆšd := ⟨zsqrtd.le⟩ protected def lt (a b : β„€βˆšd) : Prop := Β¬(b ≀ a) instance : has_lt β„€βˆšd := ⟨zsqrtd.lt⟩ instance decidable_nonnegg (c d a b) : decidable (nonnegg c d a b) := by cases a; cases b; repeat {rw int.of_nat_eq_coe}; unfold nonnegg sq_le; apply_instance instance decidable_nonneg : Ξ  (a : β„€βˆšd), decidable (nonneg a) | ⟨a, b⟩ := zsqrtd.decidable_nonnegg _ _ _ _ instance decidable_le (a b : β„€βˆšd) : decidable (a ≀ b) := decidable_nonneg _ theorem nonneg_cases : Ξ  {a : β„€βˆšd}, nonneg a β†’ βˆƒ x y : β„•, a = ⟨x, y⟩ ∨ a = ⟨x, -y⟩ ∨ a = ⟨-x, y⟩ | ⟨(x : β„•), (y : β„•)⟩ h := ⟨x, y, or.inl rfl⟩ | ⟨(x : β„•), -[1+ y]⟩ h := ⟨x, y+1, or.inr $ or.inl rfl⟩ | ⟨-[1+ x], (y : β„•)⟩ h := ⟨x+1, y, or.inr $ or.inr rfl⟩ | ⟨-[1+ x], -[1+ y]⟩ h := false.elim h lemma nonneg_add_lem {x y z w : β„•} (xy : nonneg ⟨x, -y⟩) (zw : nonneg ⟨-z, w⟩) : nonneg (⟨x, -y⟩ + ⟨-z, w⟩) := have nonneg ⟨int.sub_nat_nat x z, int.sub_nat_nat w y⟩, from int.sub_nat_nat_elim x z (Ξ»m n i, sq_le y d m 1 β†’ sq_le n 1 w d β†’ nonneg ⟨i, int.sub_nat_nat w y⟩) (Ξ»j k, int.sub_nat_nat_elim w y (Ξ»m n i, sq_le n d (k + j) 1 β†’ sq_le k 1 m d β†’ nonneg ⟨int.of_nat j, i⟩) (Ξ»m n xy zw, trivial) (Ξ»m n xy zw, sq_le_cancel zw xy)) (Ξ»j k, int.sub_nat_nat_elim w y (Ξ»m n i, sq_le n d k 1 β†’ sq_le (k + j + 1) 1 m d β†’ nonneg ⟨-[1+ j], i⟩) (Ξ»m n xy zw, sq_le_cancel xy zw) (Ξ»m n xy zw, let t := nat.le_trans zw (sq_le_of_le (nat.le_add_right n (m+1)) (le_refl _) xy) in have k + j + 1 ≀ k, from nat.mul_self_le_mul_self_iff.2 (by repeat{rw one_mul at t}; exact t), absurd this (not_le_of_gt $ nat.succ_le_succ $ nat.le_add_right _ _))) (nonnegg_pos_neg.1 xy) (nonnegg_neg_pos.1 zw), show nonneg ⟨_, _⟩, by rw [neg_add_eq_sub]; rwa [int.sub_nat_nat_eq_coe,int.sub_nat_nat_eq_coe] at this theorem nonneg_add {a b : β„€βˆšd} (ha : nonneg a) (hb : nonneg b) : nonneg (a + b) := begin rcases nonneg_cases ha with ⟨x, y, rfl|rfl|rfl⟩; rcases nonneg_cases hb with ⟨z, w, rfl|rfl|rfl⟩; dsimp [add, nonneg] at ha hb ⊒, { trivial }, { refine nonnegg_cases_right (Ξ»i h, sq_le_of_le _ _ (nonnegg_pos_neg.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ y (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_left (Ξ»i h, sq_le_of_le _ _ (nonnegg_neg_pos.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ x (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_right (Ξ»i h, sq_le_of_le _ _ (nonnegg_pos_neg.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ w (by simp *))) }, { apply nat.le_add_right } }, { simpa [add_comm] using nonnegg_pos_neg.2 (sq_le_add (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) }, { exact nonneg_add_lem ha hb }, { refine nonnegg_cases_left (Ξ»i h, sq_le_of_le _ _ (nonnegg_neg_pos.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ z (by simp *))) }, { apply nat.le_add_right } }, { rw [add_comm, add_comm ↑y], exact nonneg_add_lem hb ha }, { simpa [add_comm] using nonnegg_neg_pos.2 (sq_le_add (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) }, end theorem le_refl (a : β„€βˆšd) : a ≀ a := show nonneg (a - a), by simp protected theorem le_trans {a b c : β„€βˆšd} (ab : a ≀ b) (bc : b ≀ c) : a ≀ c := have nonneg (b - a + (c - b)), from nonneg_add ab bc, by simpa [sub_add_sub_cancel'] theorem nonneg_iff_zero_le {a : β„€βˆšd} : nonneg a ↔ 0 ≀ a := show _ ↔ nonneg _, by simp theorem le_of_le_le {x y z w : β„€} (xz : x ≀ z) (yw : y ≀ w) : (⟨x, y⟩ : β„€βˆšd) ≀ ⟨z, w⟩ := show nonneg ⟨z - x, w - y⟩, from match z - x, w - y, int.le.dest_sub xz, int.le.dest_sub yw with ._, ._, ⟨a, rfl⟩, ⟨b, rfl⟩ := trivial end theorem le_arch (a : β„€βˆšd) : βˆƒn : β„•, a ≀ n := let ⟨x, y, (h : a ≀ ⟨x, y⟩)⟩ := show βˆƒx y : β„•, nonneg (⟨x, y⟩ + -a), from match -a with | ⟨int.of_nat x, int.of_nat y⟩ := ⟨0, 0, trivial⟩ | ⟨int.of_nat x, -[1+ y]⟩ := ⟨0, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], int.of_nat y⟩ := ⟨x+1, 0, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], -[1+ y]⟩ := ⟨x+1, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ end in begin refine ⟨x + d*y, zsqrtd.le_trans h _⟩, rw [← int.cast_coe_nat, ← of_int_eq_coe], change nonneg ⟨(↑x + d*y) - ↑x, 0-↑y⟩, cases y with y, { simp }, have h : βˆ€y, sq_le y d (d * y) 1 := Ξ» y, by simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_right (y * y) (nat.le_mul_self d), rw [show (x:β„€) + d * nat.succ y - x = d * nat.succ y, by simp], exact h (y+1) end protected theorem nonneg_total : Ξ  (a : β„€βˆšd), nonneg a ∨ nonneg (-a) | ⟨(x : β„•), (y : β„•)⟩ := or.inl trivial | ⟨-[1+ x], -[1+ y]⟩ := or.inr trivial | ⟨0, -[1+ y]⟩ := or.inr trivial | ⟨-[1+ x], 0⟩ := or.inr trivial | ⟨(x+1:β„•), -[1+ y]⟩ := nat.le_total | ⟨-[1+ x], (y+1:β„•)⟩ := nat.le_total protected theorem le_total (a b : β„€βˆšd) : a ≀ b ∨ b ≀ a := let t := nonneg_total (b - a) in by rw [show -(b-a) = a-b, from neg_sub b a] at t; exact t instance : preorder β„€βˆšd := { le := zsqrtd.le, le_refl := zsqrtd.le_refl, le_trans := @zsqrtd.le_trans, lt := zsqrtd.lt, lt_iff_le_not_le := Ξ» a b, (and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm } protected theorem add_le_add_left (a b : β„€βˆšd) (ab : a ≀ b) (c : β„€βˆšd) : c + a ≀ c + b := show nonneg _, by rw add_sub_add_left_eq_sub; exact ab protected theorem le_of_add_le_add_left (a b c : β„€βˆšd) (h : c + a ≀ c + b) : a ≀ b := by simpa using zsqrtd.add_le_add_left _ _ h (-c) protected theorem add_lt_add_left (a b : β„€βˆšd) (h : a < b) (c) : c + a < c + b := Ξ» h', h (zsqrtd.le_of_add_le_add_left _ _ _ h') theorem nonneg_smul {a : β„€βˆšd} {n : β„•} (ha : nonneg a) : nonneg (n * a) := by rw ← int.cast_coe_nat; exact match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := by rw smul_val; trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by rw smul_val; simpa using nonnegg_pos_neg.2 (sq_le_smul n $ nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by rw smul_val; simpa using nonnegg_neg_pos.2 (sq_le_smul n $ nonnegg_neg_pos.1 ha) end theorem nonneg_muld {a : β„€βˆšd} (ha : nonneg a) : nonneg (sqrtd * a) := by refine match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by simp; apply nonnegg_neg_pos.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by simp; apply nonnegg_pos_neg.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_neg_pos.1 ha) end theorem nonneg_mul_lem {x y : β„•} {a : β„€βˆšd} (ha : nonneg a) : nonneg (⟨x, y⟩ * a) := have (⟨x, y⟩ * a : β„€βˆšd) = x * a + sqrtd * (y * a), by rw [decompose, right_distrib, mul_assoc]; refl, by rw this; exact nonneg_add (nonneg_smul ha) (nonneg_muld $ nonneg_smul ha) theorem nonneg_mul {a b : β„€βˆšd} (ha : nonneg a) (hb : nonneg b) : nonneg (a * b) := match a, b, nonneg_cases ha, nonneg_cases hb, ha, hb with | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := trivial | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨-z, w⟩ : β„€βˆšd) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.left (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨z, -w⟩ : β„€βˆšd) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.left (nonnegg_neg_pos.1 ha) (nonnegg_pos_neg.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨-z, w⟩ : β„€βˆšd) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.right.left (nonnegg_pos_neg.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨z, -w⟩ : β„€βˆšd) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.right.right.right (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) end protected theorem mul_nonneg (a b : β„€βˆšd) : 0 ≀ a β†’ 0 ≀ b β†’ 0 ≀ a * b := by repeat {rw ← nonneg_iff_zero_le}; exact nonneg_mul theorem not_sq_le_succ (c d y) (h : 0 < c) : Β¬sq_le (y + 1) c 0 d := not_le_of_gt $ mul_pos (mul_pos h $ nat.succ_pos _) $ nat.succ_pos _ /-- A nonsquare is a natural number that is not equal to the square of an integer. This is implemented as a typeclass because it's a necessary condition for much of the Pell equation theory. -/ class nonsquare (x : β„•) : Prop := (ns [] : βˆ€n : β„•, x β‰  n*n) parameter [dnsq : nonsquare d] include dnsq theorem d_pos : 0 < d := lt_of_le_of_ne (nat.zero_le _) $ ne.symm $ (nonsquare.ns d 0) theorem divides_sq_eq_zero {x y} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := let g := x.gcd y in or.elim g.eq_zero_or_pos (Ξ»H, ⟨nat.eq_zero_of_gcd_eq_zero_left H, nat.eq_zero_of_gcd_eq_zero_right H⟩) (Ξ»gpos, false.elim $ let ⟨m, n, co, (hx : x = m * g), (hy : y = n * g)⟩ := nat.exists_coprime gpos in begin rw [hx, hy] at h, have : m * m = d * (n * n) := nat.eq_of_mul_eq_mul_left (mul_pos gpos gpos) (by simpa [mul_comm, mul_left_comm] using h), have co2 := let co1 := co.mul_right co in co1.mul co1, exact nonsquare.ns d m (nat.dvd_antisymm (by rw this; apply dvd_mul_right) $ co2.dvd_of_dvd_mul_right $ by simp [this]) end) theorem divides_sq_eq_zero_z {x y : β„€} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := by rw [mul_assoc, ← int.nat_abs_mul_self, ← int.nat_abs_mul_self, ← int.coe_nat_mul, ← mul_assoc] at h; exact let ⟨h1, h2⟩ := divides_sq_eq_zero (int.coe_nat_inj h) in ⟨int.eq_zero_of_nat_abs_eq_zero h1, int.eq_zero_of_nat_abs_eq_zero h2⟩ theorem not_divides_square (x y) : (x + 1) * (x + 1) β‰  d * (y + 1) * (y + 1) := Ξ»e, by have t := (divides_sq_eq_zero e).left; contradiction theorem nonneg_antisymm : Ξ  {a : β„€βˆšd}, nonneg a β†’ nonneg (-a) β†’ a = 0 | ⟨0, 0⟩ xy yx := rfl | ⟨-[1+ x], -[1+ y]⟩ xy yx := false.elim xy | ⟨(x+1:nat), (y+1:nat)⟩ xy yx := false.elim yx | ⟨-[1+ x], 0⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ dec_trivial) | ⟨(x+1:nat), 0⟩ xy yx := absurd yx (not_sq_le_succ _ _ _ dec_trivial) | ⟨0, -[1+ y]⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ d_pos) | ⟨0, (y+1:nat)⟩ _ yx := absurd yx (not_sq_le_succ _ _ _ d_pos) | ⟨(x+1:nat), -[1+ y]⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm yx xy in by rw[one_mul] at t; exact absurd t (not_divides_square _ _) | ⟨-[1+ x], (y+1:nat)⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm xy yx in by rw[one_mul] at t; exact absurd t (not_divides_square _ _) theorem le_antisymm {a b : β„€βˆšd} (ab : a ≀ b) (ba : b ≀ a) : a = b := eq_of_sub_eq_zero $ nonneg_antisymm ba (by rw neg_sub; exact ab) instance : linear_order β„€βˆšd := { le_antisymm := @zsqrtd.le_antisymm, le_total := zsqrtd.le_total, decidable_le := zsqrtd.decidable_le, ..zsqrtd.preorder } protected theorem eq_zero_or_eq_zero_of_mul_eq_zero : Ξ  {a b : β„€βˆšd}, a * b = 0 β†’ a = 0 ∨ b = 0 | ⟨x, y⟩ ⟨z, w⟩ h := by injection h with h1 h2; exact have h1 : x*z = -(d*y*w), from eq_neg_of_add_eq_zero h1, have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero h2, have fin : x*x = d*y*y β†’ (⟨x, y⟩:β„€βˆšd) = 0, from Ξ»e, match x, y, divides_sq_eq_zero_z e with ._, ._, ⟨rfl, rfl⟩ := rfl end, if z0 : z = 0 then if w0 : w = 0 then or.inr (match z, w, z0, w0 with ._, ._, rfl, rfl := rfl end) else or.inl $ fin $ mul_right_cancel' w0 $ calc x * x * w = -y * (x * z) : by simp [h2, mul_assoc, mul_left_comm] ... = d * y * y * w : by simp [h1, mul_assoc, mul_left_comm] else or.inl $ fin $ mul_right_cancel' z0 $ calc x * x * z = d * -y * (x * w) : by simp [h1, mul_assoc, mul_left_comm] ... = d * y * y * z : by simp [h2, mul_assoc, mul_left_comm] instance : integral_domain β„€βˆšd := { eq_zero_or_eq_zero_of_mul_eq_zero := @zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero, .. zsqrtd.comm_ring, .. zsqrtd.nontrivial } protected theorem mul_pos (a b : β„€βˆšd) (a0 : 0 < a) (b0 : 0 < b) : 0 < a * b := Ξ»ab, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero (le_antisymm ab (mul_nonneg _ _ (le_of_lt a0) (le_of_lt b0)))) (Ξ»e, ne_of_gt a0 e) (Ξ»e, ne_of_gt b0 e) instance : linear_ordered_comm_ring β„€βˆšd := { add_le_add_left := @zsqrtd.add_le_add_left, mul_pos := @zsqrtd.mul_pos, zero_le_one := dec_trivial, .. zsqrtd.comm_ring, .. zsqrtd.linear_order, .. zsqrtd.nontrivial } instance : linear_ordered_semiring β„€βˆšd := by apply_instance instance : ordered_semiring β„€βˆšd := by apply_instance end lemma norm_eq_zero {d : β„€} (h_nonsquare : βˆ€ n : β„€, d β‰  n*n) (a : β„€βˆšd) : norm a = 0 ↔ a = 0 := begin refine ⟨λ ha, ext.mpr _, Ξ» h, by rw [h, norm_zero]⟩, delta norm at ha, rw sub_eq_zero at ha, by_cases h : 0 ≀ d, { obtain ⟨d', rfl⟩ := int.eq_coe_of_zero_le h, haveI : nonsquare d' := ⟨λ n h, h_nonsquare n $ by exact_mod_cast h⟩, exact divides_sq_eq_zero_z ha, }, { push_neg at h, suffices : a.re * a.re = 0, { rw eq_zero_of_mul_self_eq_zero this at ha ⊒, simpa only [true_and, or_self_right, zero_re, zero_im, eq_self_iff_true, zero_eq_mul, mul_zero, mul_eq_zero, h.ne, false_or, or_self] using ha }, apply _root_.le_antisymm _ (mul_self_nonneg _), rw [ha, mul_assoc], exact mul_nonpos_of_nonpos_of_nonneg h.le (mul_self_nonneg _) } end variables {R : Type} [comm_ring R] @[ext] lemma hom_ext {d : β„€} (f g : β„€βˆšd β†’+* R) (h : f sqrtd = g sqrtd) : f = g := begin ext ⟨x_re, x_im⟩, simp [decompose, h], end /-- The unique `ring_hom` from `β„€βˆšd` to a ring `R`, constructed by replacing `√d` with the provided root. Conversely, this associates to every mapping `β„€βˆšd β†’+* R` a value of `√d` in `R`. -/ @[simps] def lift {d : β„€} : {r : R // r * r = ↑d} ≃ (β„€βˆšd β†’+* R) := { to_fun := Ξ» r, { to_fun := Ξ» a, a.1 + a.2*(r : R), map_zero' := by simp, map_add' := Ξ» a b, by { simp, ring, }, map_one' := by simp, map_mul' := Ξ» a b, by { have : (a.re + a.im * r : R) * (b.re + b.im * r) = a.re * b.re + (a.re * b.im + a.im * b.re) * r + a.im * b.im * (r * r) := by ring, simp [this, r.prop], ring, } }, inv_fun := Ξ» f, ⟨f sqrtd, by rw [←f.map_mul, dmuld, ring_hom.map_int_cast]⟩, left_inv := Ξ» r, by { ext, simp }, right_inv := Ξ» f, by { ext, simp } } /-- `lift r` is injective if `d` is non-square, and R has characteristic zero (that is, the map from `β„€` into `R` is injective). -/ lemma lift_injective [char_zero R] {d : β„€} (r : {r : R // r * r = ↑d}) (hd : βˆ€ n : β„€, d β‰  n*n) : function.injective (lift r) := (lift r).injective_iff.mpr $ Ξ» a ha, begin have h_inj : function.injective (coe : β„€ β†’ R) := int.cast_injective, suffices : lift r a.norm = 0, { simp only [coe_int_re, add_zero, lift_apply_apply, coe_int_im, int.cast_zero, zero_mul] at this, rwa [← int.cast_zero, h_inj.eq_iff, norm_eq_zero hd] at this }, rw [norm_eq_mul_conj, ring_hom.map_mul, ha, zero_mul] end end zsqrtd
99333fbae78c79ed048d8b57275fa767d1712730
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Data/Option/Basic.lean
21359e6dfaaf16d9f6c1ec81bcb6c1fecb79598d
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
3,274
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Core import Init.Control.Basic import Init.Coe namespace Option def toMonad [Monad m] [Alternative m] : Option Ξ± β†’ m Ξ± | none => failure | some a => pure a @[inline] def toBool : Option Ξ± β†’ Bool | some _ => true | none => false @[inline] def isSome : Option Ξ± β†’ Bool | some _ => true | none => false @[inline] def isNone : Option Ξ± β†’ Bool | some _ => false | none => true @[inline] def isEqSome [BEq Ξ±] : Option Ξ± β†’ Ξ± β†’ Bool | some a, b => a == b | none, _ => false @[inline] protected def bind : Option Ξ± β†’ (Ξ± β†’ Option Ξ²) β†’ Option Ξ² | none, _ => none | some a, b => b a @[inline] protected def mapM [Monad m] (f : Ξ± β†’ m Ξ²) (o : Option Ξ±) : m (Option Ξ²) := do if let some a := o then return some (← f a) else return none theorem map_id : (Option.map id : Option Ξ± β†’ Option Ξ±) = id := funext (fun o => match o with | none => rfl | some _ => rfl) @[always_inline, inline] protected def filter (p : Ξ± β†’ Bool) : Option Ξ± β†’ Option Ξ± | some a => if p a then some a else none | none => none @[always_inline, inline] protected def all (p : Ξ± β†’ Bool) : Option Ξ± β†’ Bool | some a => p a | none => true @[always_inline, inline] protected def any (p : Ξ± β†’ Bool) : Option Ξ± β†’ Bool | some a => p a | none => false @[always_inline, macro_inline] protected def orElse : Option Ξ± β†’ (Unit β†’ Option Ξ±) β†’ Option Ξ± | some a, _ => some a | none, b => b () instance : OrElse (Option Ξ±) where orElse := Option.orElse @[inline] protected def lt (r : Ξ± β†’ Ξ± β†’ Prop) : Option Ξ± β†’ Option Ξ± β†’ Prop | none, some _ => True | some x, some y => r x y | _, _ => False instance (r : Ξ± β†’ Ξ± β†’ Prop) [s : DecidableRel r] : DecidableRel (Option.lt r) | none, some _ => isTrue trivial | some x, some y => s x y | some _, none => isFalse not_false | none, none => isFalse not_false /-- Take a pair of options and if they are both `some`, apply the given fn to produce an output. Otherwise act like `orElse`. -/ def merge (fn : Ξ± β†’ Ξ± β†’ Ξ±) : Option Ξ± β†’ Option Ξ± β†’ Option Ξ± | none , none => none | some x, none => some x | none , some y => some y | some x, some y => some <| fn x y end Option deriving instance DecidableEq for Option deriving instance BEq for Option instance [LT Ξ±] : LT (Option Ξ±) where lt := Option.lt (Β· < Β·) @[always_inline] instance : Functor Option where map := Option.map @[always_inline] instance : Monad Option where pure := Option.some bind := Option.bind @[always_inline] instance : Alternative Option where failure := Option.none orElse := Option.orElse def liftOption [Alternative m] : Option Ξ± β†’ m Ξ± | some a => pure a | none => failure @[always_inline, inline] protected def Option.tryCatch (x : Option Ξ±) (handle : Unit β†’ Option Ξ±) : Option Ξ± := match x with | some _ => x | none => handle () instance : MonadExceptOf Unit Option where throw := fun _ => Option.none tryCatch := Option.tryCatch
3bca43aa7886ed055d2f9a302de2b79db2e45cfb
94e33a31faa76775069b071adea97e86e218a8ee
/src/ring_theory/nullstellensatz.lean
2384031ea8136b64ade84ab7a40bc938c3bab0a8
[ "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
8,179
lean
/- Copyright (c) 2021 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Devon Tuma -/ import ring_theory.jacobson import field_theory.is_alg_closed.basic import field_theory.mv_polynomial import algebraic_geometry.prime_spectrum.basic /-! # Nullstellensatz This file establishes a version of Hilbert's classical Nullstellensatz for `mv_polynomial`s. The main statement of the theorem is `vanishing_ideal_zero_locus_eq_radical`. The statement is in terms of new definitions `vanishing_ideal` and `zero_locus`. Mathlib already has versions of these in terms of the prime spectrum of a ring, but those are not well-suited for expressing this result. Suggestions for better ways to state this theorem or organize things are welcome. The machinery around `vanishing_ideal` and `zero_locus` is also minimal, I only added lemmas directly needed in this proof, since I'm not sure if they are the right approach. -/ open ideal noncomputable theory namespace mv_polynomial open mv_polynomial variables {k : Type*} [field k] variables {Οƒ : Type*} /-- Set of points that are zeroes of all polynomials in an ideal -/ def zero_locus (I : ideal (mv_polynomial Οƒ k)) : set (Οƒ β†’ k) := {x : Οƒ β†’ k | βˆ€ p ∈ I, eval x p = 0} @[simp] lemma mem_zero_locus_iff {I : ideal (mv_polynomial Οƒ k)} {x : Οƒ β†’ k} : x ∈ zero_locus I ↔ βˆ€ p ∈ I, eval x p = 0 := iff.rfl lemma zero_locus_anti_mono {I J : ideal (mv_polynomial Οƒ k)} (h : I ≀ J) : zero_locus J ≀ zero_locus I := Ξ» x hx p hp, hx p $ h hp lemma zero_locus_bot : zero_locus (βŠ₯ : ideal (mv_polynomial Οƒ k)) = ⊀ := eq_top_iff.2 (Ξ» x hx p hp, trans (congr_arg (eval x) (mem_bot.1 hp)) (eval x).map_zero) lemma zero_locus_top : zero_locus (⊀ : ideal (mv_polynomial Οƒ k)) = βŠ₯ := eq_bot_iff.2 $ Ξ» x hx, one_ne_zero ((eval x).map_one β–Έ (hx 1 submodule.mem_top) : (1 : k) = 0) /-- Ideal of polynomials with common zeroes at all elements of a set -/ def vanishing_ideal (V : set (Οƒ β†’ k)) : ideal (mv_polynomial Οƒ k) := { carrier := {p | βˆ€ x ∈ V, eval x p = 0}, zero_mem' := Ξ» x hx, ring_hom.map_zero _, add_mem' := Ξ» p q hp hq x hx, by simp only [hq x hx, hp x hx, add_zero, ring_hom.map_add], smul_mem' := Ξ» p q hq x hx, by simp only [hq x hx, algebra.id.smul_eq_mul, mul_zero, ring_hom.map_mul] } @[simp] lemma mem_vanishing_ideal_iff {V : set (Οƒ β†’ k)} {p : mv_polynomial Οƒ k} : p ∈ vanishing_ideal V ↔ βˆ€ x ∈ V, eval x p = 0 := iff.rfl lemma vanishing_ideal_anti_mono {A B : set (Οƒ β†’ k)} (h : A ≀ B) : vanishing_ideal B ≀ vanishing_ideal A := Ξ» p hp x hx, hp x $ h hx lemma vanishing_ideal_empty : vanishing_ideal (βˆ… : set (Οƒ β†’ k)) = ⊀ := le_antisymm le_top (Ξ» p hp x hx, absurd hx (set.not_mem_empty x)) lemma le_vanishing_ideal_zero_locus (I : ideal (mv_polynomial Οƒ k)) : I ≀ vanishing_ideal (zero_locus I) := Ξ» p hp x hx, hx p hp lemma zero_locus_vanishing_ideal_le (V : set (Οƒ β†’ k)) : V ≀ zero_locus (vanishing_ideal V) := Ξ» V hV p hp, hp V hV theorem zero_locus_vanishing_ideal_galois_connection : @galois_connection (ideal (mv_polynomial Οƒ k)) (set (Οƒ β†’ k))α΅’α΅ˆ _ _ zero_locus vanishing_ideal := Ξ» I V, ⟨λ h, le_trans (le_vanishing_ideal_zero_locus I) (vanishing_ideal_anti_mono h), Ξ» h, le_trans (zero_locus_anti_mono h) (zero_locus_vanishing_ideal_le V)⟩ lemma mem_vanishing_ideal_singleton_iff (x : Οƒ β†’ k) (p : mv_polynomial Οƒ k) : p ∈ (vanishing_ideal {x} : ideal (mv_polynomial Οƒ k)) ↔ (eval x p = 0) := ⟨λ h, h x rfl, Ξ» hpx y hy, hy.symm β–Έ hpx⟩ instance vanishing_ideal_singleton_is_maximal {x : Οƒ β†’ k} : (vanishing_ideal {x} : ideal (mv_polynomial Οƒ k)).is_maximal := begin have : mv_polynomial Οƒ k β§Έ vanishing_ideal {x} ≃+* k := ring_equiv.of_bijective (ideal.quotient.lift _ (eval x) (Ξ» p h, (mem_vanishing_ideal_singleton_iff x p).mp h)) begin refine ⟨(injective_iff_map_eq_zero _).mpr (Ξ» p hp, _), Ξ» z, ⟨(ideal.quotient.mk (vanishing_ideal {x} : ideal (mv_polynomial Οƒ k))) (C z), by simp⟩⟩, obtain ⟨q, rfl⟩ := quotient.mk_surjective p, rwa [ideal.quotient.lift_mk, ← mem_vanishing_ideal_singleton_iff, ← quotient.eq_zero_iff_mem] at hp, end, rw [← bot_quotient_is_maximal_iff, ring_equiv.bot_maximal_iff this], exact bot_is_maximal, end lemma radical_le_vanishing_ideal_zero_locus (I : ideal (mv_polynomial Οƒ k)) : I.radical ≀ vanishing_ideal (zero_locus I) := begin intros p hp x hx, rw ← mem_vanishing_ideal_singleton_iff, rw radical_eq_Inf at hp, refine (mem_Inf.mp hp) ⟨le_trans (le_vanishing_ideal_zero_locus I) (vanishing_ideal_anti_mono (Ξ» y hy, hy.symm β–Έ hx)), is_maximal.is_prime' _⟩, end /-- The point in the prime spectrum assosiated to a given point -/ def point_to_point (x : Οƒ β†’ k) : prime_spectrum (mv_polynomial Οƒ k) := ⟨(vanishing_ideal {x} : ideal (mv_polynomial Οƒ k)), by apply_instance⟩ @[simp] lemma vanishing_ideal_point_to_point (V : set (Οƒ β†’ k)) : prime_spectrum.vanishing_ideal (point_to_point '' V) = mv_polynomial.vanishing_ideal V := le_antisymm (Ξ» p hp x hx, (((prime_spectrum.mem_vanishing_ideal _ _).1 hp) ⟨vanishing_ideal {x}, by apply_instance⟩ ⟨x, ⟨hx, rfl⟩⟩) x rfl) (Ξ» p hp, (prime_spectrum.mem_vanishing_ideal _ _).2 (Ξ» I hI, let ⟨x, hx⟩ := hI in hx.2 β–Έ Ξ» x' hx', (set.mem_singleton_iff.1 hx').symm β–Έ hp x hx.1)) lemma point_to_point_zero_locus_le (I : ideal (mv_polynomial Οƒ k)) : point_to_point '' (mv_polynomial.zero_locus I) ≀ prime_spectrum.zero_locus ↑I := Ξ» J hJ, let ⟨x, hx⟩ := hJ in (le_trans (le_vanishing_ideal_zero_locus I) (hx.2 β–Έ vanishing_ideal_anti_mono (set.singleton_subset_iff.2 hx.1)) : I ≀ J.as_ideal) variables [is_alg_closed k] [fintype Οƒ] lemma is_maximal_iff_eq_vanishing_ideal_singleton (I : ideal (mv_polynomial Οƒ k)) : I.is_maximal ↔ βˆƒ (x : Οƒ β†’ k), I = vanishing_ideal {x} := begin refine ⟨λ hI, _, Ξ» h, let ⟨x, hx⟩ := h in hx.symm β–Έ (mv_polynomial.vanishing_ideal_singleton_is_maximal)⟩, letI : I.is_maximal := hI, letI : field (mv_polynomial Οƒ k β§Έ I) := quotient.field I, let Ο• : k β†’+* mv_polynomial Οƒ k β§Έ I := (ideal.quotient.mk I).comp C, have hΟ• : function.bijective Ο• := ⟨quotient_mk_comp_C_injective _ _ I hI.ne_top, is_alg_closed.algebra_map_surjective_of_is_integral' Ο• (mv_polynomial.comp_C_integral_of_surjective_of_jacobson _ quotient.mk_surjective)⟩, obtain βŸ¨Ο†, hΟ†βŸ© := function.surjective.has_right_inverse hΟ•.2, let x : Οƒ β†’ k := Ξ» s, Ο† ((ideal.quotient.mk I) (X s)), have hx : βˆ€ s : Οƒ, Ο• (x s) = (ideal.quotient.mk I) (X s) := Ξ» s, hΟ† ((ideal.quotient.mk I) (X s)), refine ⟨x, (is_maximal.eq_of_le (by apply_instance) hI.ne_top _).symm⟩, intros p hp, rw [← quotient.eq_zero_iff_mem, map_mv_polynomial_eq_evalβ‚‚ (ideal.quotient.mk I) p, evalβ‚‚_eq'], rw [mem_vanishing_ideal_singleton_iff, eval_eq'] at hp, simpa only [Ο•.map_sum, Ο•.map_mul, Ο•.map_prod, Ο•.map_pow, Ο•.map_zero, hx] using congr_arg Ο• hp, end /-- Main statement of the Nullstellensatz -/ @[simp] theorem vanishing_ideal_zero_locus_eq_radical (I : ideal (mv_polynomial Οƒ k)) : vanishing_ideal (zero_locus I) = I.radical := begin rw I.radical_eq_jacobson, refine le_antisymm (le_Inf _) (Ξ» p hp x hx, _), { rintros J ⟨hJI, hJ⟩, obtain ⟨x, hx⟩ := (is_maximal_iff_eq_vanishing_ideal_singleton J).1 hJ, refine hx.symm β–Έ vanishing_ideal_anti_mono (Ξ» y hy p hp, _), rw [← mem_vanishing_ideal_singleton_iff, set.mem_singleton_iff.1 hy, ← hx], refine hJI hp }, { rw ← mem_vanishing_ideal_singleton_iff x p, refine (mem_Inf.mp hp) ⟨le_trans (le_vanishing_ideal_zero_locus I) (vanishing_ideal_anti_mono (Ξ» y hy, hy.symm β–Έ hx)), mv_polynomial.vanishing_ideal_singleton_is_maximal⟩ }, end @[simp] lemma is_prime.vanishing_ideal_zero_locus (P : ideal (mv_polynomial Οƒ k)) [h : P.is_prime] : vanishing_ideal (zero_locus P) = P := trans (vanishing_ideal_zero_locus_eq_radical P) h.radical end mv_polynomial
87258492f999bf41f27ae557fc27948c2867d736
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/calculus/local_extr.lean
203a1ac4ccf605bd6635a6ca98dd038b72e1dfd8
[ "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
18,183
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.deriv import topology.algebra.ordered.extend_from import topology.algebra.polynomial import topology.local_extr /-! # Local extrema of smooth functions ## Main definitions In a real normed space `E` we define `pos_tangent_cone_at (s : set E) (x : E)`. This would be the same as `tangent_cone_at ℝβ‰₯0 s x` if we had a theory of normed semifields. This set is used in the proof of Fermat's Theorem (see below), and can be used to formalize [Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) and/or [Karush–Kuhn–Tucker conditions](https://en.wikipedia.org/wiki/Karush–Kuhn–Tucker_conditions). ## Main statements For each theorem name listed below, we also prove similar theorems for `min`, `extr` (if applicable)`, and `(f)deriv` instead of `has_fderiv`. * `is_local_max_on.has_fderiv_within_at_nonpos` : `f' y ≀ 0` whenever `a` is a local maximum of `f` on `s`, `f` has derivative `f'` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`. * `is_local_max_on.has_fderiv_within_at_eq_zero` : In the settings of the previous theorem, if both `y` and `-y` belong to the positive tangent cone, then `f' y = 0`. * `is_local_max.has_fderiv_at_eq_zero` : [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)), the derivative of a differentiable function at a local extremum point equals zero. * `exists_has_deriv_at_eq_zero` : [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem): given a function `f` continuous on `[a, b]` and differentiable on `(a, b)`, there exists `c ∈ (a, b)` such that `f' c = 0`. ## Implementation notes For each mathematical fact we prove several versions of its formalization: * for maxima and minima; * using `has_fderiv*`/`has_deriv*` or `fderiv*`/`deriv*`. For the `fderiv*`/`deriv*` versions we omit the differentiability condition whenever it is possible due to the fact that `fderiv` and `deriv` are defined to be zero for non-differentiable functions. ## References * [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)); * [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem); * [Tangent cone](https://en.wikipedia.org/wiki/Tangent_cone); ## Tags local extremum, Fermat's Theorem, Rolle's Theorem -/ universes u v open filter set open_locale topological_space classical section module variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : E β†’ ℝ} {a : E} {f' : E β†’L[ℝ] ℝ} /-- "Positive" tangent cone to `s` at `x`; the only difference from `tangent_cone_at` is that we require `c n β†’ ∞` instead of `βˆ₯c nβˆ₯ β†’ ∞`. One can think about `pos_tangent_cone_at` as `tangent_cone_at nnreal` but we have no theory of normed semifields yet. -/ def pos_tangent_cone_at (s : set E) (x : E) : set E := {y : E | βˆƒ(c : β„• β†’ ℝ) (d : β„• β†’ E), (βˆ€αΆ  n in at_top, x + d n ∈ s) ∧ (tendsto c at_top at_top) ∧ (tendsto (Ξ»n, c n β€’ d n) at_top (𝓝 y))} lemma pos_tangent_cone_at_mono : monotone (Ξ» s, pos_tangent_cone_at s a) := begin rintros s t hst y ⟨c, d, hd, hc, hcd⟩, exact ⟨c, d, mem_sets_of_superset hd $ Ξ» h hn, hst hn, hc, hcd⟩ end lemma mem_pos_tangent_cone_at_of_segment_subset {s : set E} {x y : E} (h : segment x y βŠ† s) : y - x ∈ pos_tangent_cone_at s x := begin let c := Ξ»n:β„•, (2:ℝ)^n, let d := Ξ»n:β„•, (c n)⁻¹ β€’ (y-x), refine ⟨c, d, filter.univ_mem_sets' (Ξ»n, h _), tendsto_pow_at_top_at_top_of_one_lt one_lt_two, _⟩, show x + d n ∈ segment x y, { rw segment_eq_image', refine ⟨(c n)⁻¹, ⟨_, _⟩, rfl⟩, exacts [inv_nonneg.2 (pow_nonneg zero_le_two _), inv_le_one (one_le_pow_of_one_le one_le_two _)] }, show tendsto (Ξ» n, c n β€’ d n) at_top (𝓝 (y - x)), { convert tendsto_const_nhds, ext n, simp only [d, smul_smul], rw [mul_inv_cancel, one_smul], exact pow_ne_zero _ two_ne_zero } end lemma mem_pos_tangent_cone_at_of_segment_subset' {s : set E} {x y : E} (h : segment x (x + y) βŠ† s) : y ∈ pos_tangent_cone_at s x := by simpa only [add_sub_cancel'] using mem_pos_tangent_cone_at_of_segment_subset h lemma pos_tangent_cone_at_univ : pos_tangent_cone_at univ a = univ := eq_univ_of_forall $ Ξ» x, mem_pos_tangent_cone_at_of_segment_subset' (subset_univ _) /-- If `f` has a local max on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≀ 0`. -/ lemma is_local_max_on.has_fderiv_within_at_nonpos {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : f' y ≀ 0 := begin rcases hy with ⟨c, d, hd, hc, hcd⟩, have hc' : tendsto (Ξ» n, βˆ₯c nβˆ₯) at_top at_top, from tendsto_at_top_mono (Ξ» n, le_abs_self _) hc, refine le_of_tendsto (hf.lim at_top hd hc' hcd) _, replace hd : tendsto (Ξ» n, a + d n) at_top (𝓝[s] (a + 0)), from tendsto_inf.2 ⟨tendsto_const_nhds.add (tangent_cone_at.lim_zero _ hc' hcd), by rwa tendsto_principal⟩, rw [add_zero] at hd, replace h : βˆ€αΆ  n in at_top, f (a + d n) ≀ f a, from mem_map.1 (hd h), replace hc : βˆ€αΆ  n in at_top, 0 ≀ c n, from mem_map.1 (hc (mem_at_top (0:ℝ))), filter_upwards [h, hc], simp only [smul_eq_mul, mem_preimage, subset_def], assume n hnf hn, exact mul_nonpos_of_nonneg_of_nonpos hn (sub_nonpos.2 hnf) end /-- If `f` has a local max on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `f' y ≀ 0`. -/ lemma is_local_max_on.fderiv_within_nonpos {s : set E} (h : is_local_max_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E β†’ ℝ) y ≀ 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_nonpos hf.has_fderiv_within_at hy else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≀ 0`. -/ lemma is_local_max_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : f' y = 0 := le_antisymm (h.has_fderiv_within_at_nonpos hf hy) $ by simpa using h.has_fderiv_within_at_nonpos hf hy' /-- If `f` has a local max on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ lemma is_local_max_on.fderiv_within_eq_zero {s : set E} (h : is_local_max_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E β†’ ℝ) y = 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy' else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- If `f` has a local min on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≀ f' y`. -/ lemma is_local_min_on.has_fderiv_within_at_nonneg {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : 0 ≀ f' y := by simpa using h.neg.has_fderiv_within_at_nonpos hf.neg hy /-- If `f` has a local min on `s` at `a` and `y` belongs to the positive tangent cone of `s` at `a`, then `0 ≀ f' y`. -/ lemma is_local_min_on.fderiv_within_nonneg {s : set E} (h : is_local_min_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : (0:ℝ) ≀ (fderiv_within ℝ f s a : E β†’ ℝ) y := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_nonneg hf.has_fderiv_within_at hy else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf], refl } /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y ≀ 0`. -/ lemma is_local_min_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : f' y = 0 := by simpa using h.neg.has_fderiv_within_at_eq_zero hf.neg hy hy' /-- If `f` has a local min on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y = 0`. -/ lemma is_local_min_on.fderiv_within_eq_zero {s : set E} (h : is_local_min_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E β†’ ℝ) y = 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy' else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.has_fderiv_at_eq_zero (h : is_local_min f a) (hf : has_fderiv_at f f' a) : f' = 0 := begin ext y, apply (h.on univ).has_fderiv_within_at_eq_zero hf.has_fderiv_within_at; rw pos_tangent_cone_at_univ; apply mem_univ end /-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.fderiv_eq_zero (h : is_local_min f a) : fderiv ℝ f a = 0 := if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at else fderiv_zero_of_not_differentiable_at hf /-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.has_fderiv_at_eq_zero (h : is_local_max f a) (hf : has_fderiv_at f f' a) : f' = 0 := neg_eq_zero.1 $ h.neg.has_fderiv_at_eq_zero hf.neg /-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.fderiv_eq_zero (h : is_local_max f a) : fderiv ℝ f a = 0 := if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at else fderiv_zero_of_not_differentiable_at hf /-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.has_fderiv_at_eq_zero (h : is_local_extr f a) : has_fderiv_at f f' a β†’ f' = 0 := h.elim is_local_min.has_fderiv_at_eq_zero is_local_max.has_fderiv_at_eq_zero /-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.fderiv_eq_zero (h : is_local_extr f a) : fderiv ℝ f a = 0 := h.elim is_local_min.fderiv_eq_zero is_local_max.fderiv_eq_zero end module section real variables {f : ℝ β†’ ℝ} {f' : ℝ} {a b : ℝ} /-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.has_deriv_at_eq_zero (h : is_local_min f a) (hf : has_deriv_at f f' a) : f' = 0 := by simpa using continuous_linear_map.ext_iff.1 (h.has_fderiv_at_eq_zero (has_deriv_at_iff_has_fderiv_at.1 hf)) 1 /-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.deriv_eq_zero (h : is_local_min f a) : deriv f a = 0 := if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at else deriv_zero_of_not_differentiable_at hf /-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.has_deriv_at_eq_zero (h : is_local_max f a) (hf : has_deriv_at f f' a) : f' = 0 := neg_eq_zero.1 $ h.neg.has_deriv_at_eq_zero hf.neg /-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.deriv_eq_zero (h : is_local_max f a) : deriv f a = 0 := if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at else deriv_zero_of_not_differentiable_at hf /-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.has_deriv_at_eq_zero (h : is_local_extr f a) : has_deriv_at f f' a β†’ f' = 0 := h.elim is_local_min.has_deriv_at_eq_zero is_local_max.has_deriv_at_eq_zero /-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.deriv_eq_zero (h : is_local_extr f a) : deriv f a = 0 := h.elim is_local_min.deriv_eq_zero is_local_max.deriv_eq_zero end real section Rolle variables (f f' : ℝ β†’ ℝ) {a b : ℝ} /-- A continuous function on a closed interval with `f a = f b` takes either its maximum or its minimum value at a point in the interior of the interval. -/ lemma exists_Ioo_extr_on_Icc (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : βˆƒ c ∈ Ioo a b, is_extr_on f (Icc a b) c := begin have ne : (Icc a b).nonempty, from nonempty_Icc.2 (le_of_lt hab), -- Consider absolute min and max points obtain ⟨c, cmem, cle⟩ : βˆƒ c ∈ Icc a b, βˆ€ x ∈ Icc a b, f c ≀ f x, from is_compact_Icc.exists_forall_le ne hfc, obtain ⟨C, Cmem, Cge⟩ : βˆƒ C ∈ Icc a b, βˆ€ x ∈ Icc a b, f x ≀ f C, from is_compact_Icc.exists_forall_ge ne hfc, by_cases hc : f c = f a, { by_cases hC : f C = f a, { have : βˆ€ x ∈ Icc a b, f x = f a, from Ξ» x hx, le_antisymm (hC β–Έ Cge x hx) (hc β–Έ cle x hx), -- `f` is a constant, so we can take any point in `Ioo a b` rcases exists_between hab with ⟨c', hc'⟩, refine ⟨c', hc', or.inl _⟩, assume x hx, rw [mem_set_of_eq, this x hx, ← hC], exact Cge c' ⟨le_of_lt hc'.1, le_of_lt hc'.2⟩ }, { refine ⟨C, ⟨lt_of_le_of_ne Cmem.1 $ mt _ hC, lt_of_le_of_ne Cmem.2 $ mt _ hC⟩, or.inr Cge⟩, exacts [Ξ» h, by rw h, Ξ» h, by rw [h, hfI]] } }, { refine ⟨c, ⟨lt_of_le_of_ne cmem.1 $ mt _ hc, lt_of_le_of_ne cmem.2 $ mt _ hc⟩, or.inl cle⟩, exacts [Ξ» h, by rw h, Ξ» h, by rw [h, hfI]] } end /-- A continuous function on a closed interval with `f a = f b` has a local extremum at some point of the corresponding open interval. -/ lemma exists_local_extr_Ioo (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : βˆƒ c ∈ Ioo a b, is_local_extr f c := let ⟨c, cmem, hc⟩ := exists_Ioo_extr_on_Icc f hab hfc hfI in ⟨c, cmem, hc.is_local_extr $ Icc_mem_nhds cmem.1 cmem.2⟩ /-- **Rolle's Theorem** `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) (hff' : βˆ€ x ∈ Ioo a b, has_deriv_at f (f' x) x) : βˆƒ c ∈ Ioo a b, f' c = 0 := let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in ⟨c, cmem, hc.has_deriv_at_eq_zero $ hff' c cmem⟩ /-- **Rolle's Theorem** `deriv` version -/ lemma exists_deriv_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) : βˆƒ c ∈ Ioo a b, deriv f c = 0 := let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in ⟨c, cmem, hc.deriv_eq_zero⟩ variables {f f'} {l : ℝ} /-- **Rolle's Theorem**, a version for a function on an open interval: if `f` has derivative `f'` on `(a, b)` and has the same limit `l` at `𝓝[Ioi a] a` and `𝓝[Iio b] b`, then `f' c = 0` for some `c ∈ (a, b)`. -/ lemma exists_has_deriv_at_eq_zero' (hab : a < b) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 l)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 l)) (hff' : βˆ€ x ∈ Ioo a b, has_deriv_at f (f' x) x) : βˆƒ c ∈ Ioo a b, f' c = 0 := begin have : continuous_on f (Ioo a b) := Ξ» x hx, (hff' x hx).continuous_at.continuous_within_at, have hcont := continuous_on_Icc_extend_from_Ioo hab this hfa hfb, obtain ⟨c, hc, hcextr⟩ : βˆƒ c ∈ Ioo a b, is_local_extr (extend_from (Ioo a b) f) c, { apply exists_local_extr_Ioo _ hab hcont, rw eq_lim_at_right_extend_from_Ioo hab hfb, exact eq_lim_at_left_extend_from_Ioo hab hfa }, use [c, hc], apply (hcextr.congr _).has_deriv_at_eq_zero (hff' c hc), rw eventually_eq_iff_exists_mem, exact ⟨Ioo a b, Ioo_mem_nhds hc.1 hc.2, extend_from_extends this⟩ end /-- **Rolle's Theorem**, a version for a function on an open interval: if `f` has the same limit `l` at `𝓝[Ioi a] a` and `𝓝[Iio b] b`, then `deriv f c = 0` for some `c ∈ (a, b)`. This version does not require differentiability of `f` because we define `deriv f c = 0` whenever `f` is not differentiable at `c`. -/ lemma exists_deriv_eq_zero' (hab : a < b) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 l)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 l)) : βˆƒ c ∈ Ioo a b, deriv f c = 0 := classical.by_cases (assume h : βˆ€ x ∈ Ioo a b, differentiable_at ℝ f x, show βˆƒ c ∈ Ioo a b, deriv f c = 0, from exists_has_deriv_at_eq_zero' hab hfa hfb (Ξ» x hx, (h x hx).has_deriv_at)) (assume h : Β¬βˆ€ x ∈ Ioo a b, differentiable_at ℝ f x, have h : βˆƒ x, x ∈ Ioo a b ∧ Β¬differentiable_at ℝ f x, by { push_neg at h, exact h }, let ⟨c, hc, hcdiff⟩ := h in ⟨c, hc, deriv_zero_of_not_differentiable_at hcdiff⟩) end Rolle namespace polynomial lemma card_root_set_le_derivative {F : Type*} [field F] [algebra F ℝ] (p : polynomial F) : fintype.card (p.root_set ℝ) ≀ fintype.card (p.derivative.root_set ℝ) + 1 := begin haveI : char_zero F := (ring_hom.char_zero_iff (algebra_map F ℝ).injective).mpr (by apply_instance), by_cases hp : p = 0, { simp_rw [hp, derivative_zero, root_set_zero, set.empty_card', zero_le_one] }, by_cases hp' : p.derivative = 0, { rw eq_C_of_nat_degree_eq_zero (nat_degree_eq_zero_of_derivative_eq_zero hp'), simp_rw [root_set_C, set.empty_card', zero_le] }, simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe], refine finset.card_le_of_interleaved (Ξ» x y hx hy hxy, _), rw [←finset.mem_coe, ←root_set_def, mem_root_set hp] at hx hy, obtain ⟨z, hz1, hz2⟩ := exists_deriv_eq_zero (Ξ» x : ℝ, aeval x p) hxy p.continuous_aeval.continuous_on (hx.trans hy.symm), refine ⟨z, _, hz1⟩, rw [←finset.mem_coe, ←root_set_def, mem_root_set hp', ←hz2], simp_rw [aeval_def, ←eval_map, polynomial.deriv, derivative_map], end end polynomial
83d970fd3e5759df2bc63a389fc02d4f8f443677
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/unique_factorization_domain.lean
a14c36192d98af5f31e5eb23c3782f27d3a27ea2
[ "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
67,990
lean
/- Copyright (c) 2018 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl, Jens Wagemaker, Aaron Anderson -/ import algebra.big_operators.associated import algebra.gcd_monoid.basic import data.finsupp.multiset import ring_theory.noetherian import ring_theory.multiplicity /-! # Unique factorization ## Main Definitions * `wf_dvd_monoid` holds for `monoid`s for which a strict divisibility relation is well-founded. * `unique_factorization_monoid` holds for `wf_dvd_monoid`s where `irreducible` is equivalent to `prime` ## To do * set up the complete lattice structure on `factor_set`. -/ variables {Ξ± : Type*} local infix ` ~α΅€ ` : 50 := associated /-- Well-foundedness of the strict version of |, which is equivalent to the descending chain condition on divisibility and to the ascending chain condition on principal ideals in an integral domain. -/ class wf_dvd_monoid (Ξ± : Type*) [comm_monoid_with_zero Ξ±] : Prop := (well_founded_dvd_not_unit : well_founded (@dvd_not_unit Ξ± _)) export wf_dvd_monoid (well_founded_dvd_not_unit) @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring.wf_dvd_monoid [comm_ring Ξ±] [is_domain Ξ±] [is_noetherian_ring Ξ±] : wf_dvd_monoid Ξ± := ⟨by { convert inv_image.wf (Ξ» a, ideal.span ({a} : set Ξ±)) (well_founded_submodule_gt _ _), ext, exact ideal.span_singleton_lt_span_singleton.symm }⟩ namespace wf_dvd_monoid variables [comm_monoid_with_zero Ξ±] open associates nat theorem of_wf_dvd_monoid_associates (h : wf_dvd_monoid (associates Ξ±)): wf_dvd_monoid Ξ± := ⟨begin haveI := h, refine (surjective.well_founded_iff mk_surjective _).2 well_founded_dvd_not_unit, intros, rw mk_dvd_not_unit_mk_iff end⟩ variables [wf_dvd_monoid Ξ±] instance wf_dvd_monoid_associates : wf_dvd_monoid (associates Ξ±) := ⟨begin refine (surjective.well_founded_iff mk_surjective _).1 well_founded_dvd_not_unit, intros, rw mk_dvd_not_unit_mk_iff end⟩ theorem well_founded_associates : well_founded ((<) : associates Ξ± β†’ associates Ξ± β†’ Prop) := subrelation.wf (Ξ» x y, dvd_not_unit_of_lt) well_founded_dvd_not_unit local attribute [elab_as_eliminator] well_founded.fix lemma exists_irreducible_factor {a : Ξ±} (ha : Β¬ is_unit a) (ha0 : a β‰  0) : βˆƒ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (Ξ» hai, ⟨a, hai, dvd_rfl⟩) (well_founded.fix well_founded_dvd_not_unit (Ξ» a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x β‰  0, from Ξ» hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (Ξ» hxi, ⟨x, hxi, hxy β–Έ by simp⟩) (Ξ» hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, hi.2.trans (hxy β–Έ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma induction_on_irreducible {P : Ξ± β†’ Prop} (a : Ξ±) (h0 : P 0) (hu : βˆ€ u : Ξ±, is_unit u β†’ P u) (hi : βˆ€ a i : Ξ±, a β‰  0 β†’ irreducible i β†’ P a β†’ P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix well_founded_dvd_not_unit (Ξ» a ih, if ha0 : a = 0 then ha0.symm β–Έ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b β‰  0, from Ξ» hb0, by simp * at *, hb.symm β–Έ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : Ξ±) : a β‰  0 β†’ βˆƒ f : multiset Ξ±, (βˆ€ b ∈ f, irreducible b) ∧ associated f.prod a := induction_on_irreducible a (Ξ» h, (h rfl).elim) (Ξ» u hu _, ⟨0, ⟨by simp [hu], associated.symm (by simp [hu, associated_one_iff_is_unit])⟩⟩) (Ξ» a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i ::β‚˜ s, ⟨by clear _let_match; { intros b H, cases (multiset.mem_cons.mp H), { convert hii }, { exact hs.1 b h } }, by { rw multiset.prod_cons, exact hs.2.mul_left _ }⟩⟩) lemma not_unit_iff_exists_factors_eq (a : Ξ±) (hn0 : a β‰  0) : Β¬ is_unit a ↔ βˆƒ f : multiset Ξ±, (βˆ€ b ∈ f, irreducible b) ∧ f.prod = a ∧ f β‰  βˆ… := ⟨λ hnu, begin obtain ⟨f, hi, u, rfl⟩ := exists_factors a hn0, obtain ⟨b, h⟩ := multiset.exists_mem_of_ne_zero (Ξ» h : f = 0, hnu $ by simp [h]), classical, refine ⟨(f.erase b).cons (b * u), Ξ» a ha, _, _, multiset.cons_ne_zero⟩, { obtain (rfl|ha) := multiset.mem_cons.1 ha, exacts [associated.irreducible ⟨u,rfl⟩ (hi b h), hi a (multiset.mem_of_mem_erase ha)] }, { rw [multiset.prod_cons, mul_comm b, mul_assoc, multiset.prod_erase h, mul_comm] }, end, Ξ» ⟨f,hi,he,hne⟩, let ⟨b, h⟩ := multiset.exists_mem_of_ne_zero hne in not_is_unit_of_not_is_unit_dvd (hi b h).not_unit (he.subst $ multiset.dvd_prod h)⟩ end wf_dvd_monoid theorem wf_dvd_monoid.of_well_founded_associates [cancel_comm_monoid_with_zero Ξ±] (h : well_founded ((<) : associates Ξ± β†’ associates Ξ± β†’ Prop)) : wf_dvd_monoid Ξ± := wf_dvd_monoid.of_wf_dvd_monoid_associates ⟨by { convert h, ext, exact associates.dvd_not_unit_iff_lt }⟩ theorem wf_dvd_monoid.iff_well_founded_associates [cancel_comm_monoid_with_zero Ξ±] : wf_dvd_monoid Ξ± ↔ well_founded ((<) : associates Ξ± β†’ associates Ξ± β†’ Prop) := ⟨by apply wf_dvd_monoid.well_founded_associates, wf_dvd_monoid.of_well_founded_associates⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- unique factorization monoids. These are defined as `cancel_comm_monoid_with_zero`s with well-founded strict divisibility relations, but this is equivalent to more familiar definitions: Each element (except zero) is uniquely represented as a multiset of irreducible factors. Uniqueness is only up to associated elements. Each element (except zero) is non-uniquely represented as a multiset of prime factors. To define a UFD using the definition in terms of multisets of irreducible factors, use the definition `of_exists_unique_irreducible_factors` To define a UFD using the definition in terms of multisets of prime factors, use the definition `of_exists_prime_factors` -/ class unique_factorization_monoid (Ξ± : Type*) [cancel_comm_monoid_with_zero Ξ±] extends wf_dvd_monoid Ξ± : Prop := (irreducible_iff_prime : βˆ€ {a : Ξ±}, irreducible a ↔ prime a) /-- Can't be an instance because it would cause a loop `ufm β†’ wf_dvd_monoid β†’ ufm β†’ ...`. -/ @[reducible] lemma ufm_of_gcd_of_wf_dvd_monoid [cancel_comm_monoid_with_zero Ξ±] [wf_dvd_monoid Ξ±] [gcd_monoid Ξ±] : unique_factorization_monoid Ξ± := { irreducible_iff_prime := Ξ» _, gcd_monoid.irreducible_iff_prime .. β€Ήwf_dvd_monoid Ξ±β€Ί } instance associates.ufm [cancel_comm_monoid_with_zero Ξ±] [unique_factorization_monoid Ξ±] : unique_factorization_monoid (associates Ξ±) := { irreducible_iff_prime := by { rw ← associates.irreducible_iff_prime_iff, apply unique_factorization_monoid.irreducible_iff_prime, } .. (wf_dvd_monoid.wf_dvd_monoid_associates : wf_dvd_monoid (associates Ξ±)) } end prio namespace unique_factorization_monoid variables [cancel_comm_monoid_with_zero Ξ±] [unique_factorization_monoid Ξ±] theorem exists_prime_factors (a : Ξ±) : a β‰  0 β†’ βˆƒ f : multiset Ξ±, (βˆ€b ∈ f, prime b) ∧ f.prod ~α΅€ a := by { simp_rw ← unique_factorization_monoid.irreducible_iff_prime, apply wf_dvd_monoid.exists_factors a } @[elab_as_eliminator] lemma induction_on_prime {P : Ξ± β†’ Prop} (a : Ξ±) (h₁ : P 0) (hβ‚‚ : βˆ€ x : Ξ±, is_unit x β†’ P x) (h₃ : βˆ€ a p : Ξ±, a β‰  0 β†’ prime p β†’ P a β†’ P (p * a)) : P a := begin simp_rw ← unique_factorization_monoid.irreducible_iff_prime at h₃, exact wf_dvd_monoid.induction_on_irreducible a h₁ hβ‚‚ h₃, end lemma factors_unique : βˆ€{f g : multiset Ξ±}, (βˆ€x∈f, irreducible x) β†’ (βˆ€x∈g, irreducible x) β†’ f.prod ~α΅€ g.prod β†’ multiset.rel associated f g := by haveI := classical.dec_eq Ξ±; exact Ξ» f, multiset.induction_on f (Ξ» g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem (Ξ» x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).not_unit (is_unit_iff_dvd_one.2 ((multiset.dvd_prod hx).trans (is_unit_iff_dvd_one.1 this))))) (Ξ» p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (irreducible_iff_prime.1 (hf p (by simp))) (Ξ» q hq, irreducible_iff_prime.1 (hg _ hq)) $ hfg.dvd_iff_dvd_right.1 (show p ∣ (p ::β‚˜ f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (Ξ» q hq, hf _ (by simp [hq])) (Ξ» q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated.of_mul_left (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)) end) end unique_factorization_monoid lemma prime_factors_unique [cancel_comm_monoid_with_zero Ξ±] : βˆ€ {f g : multiset Ξ±}, (βˆ€ x ∈ f, prime x) β†’ (βˆ€ x ∈ g, prime x) β†’ f.prod ~α΅€ g.prod β†’ multiset.rel associated f g := by haveI := classical.dec_eq Ξ±; exact Ξ» f, multiset.induction_on f (Ξ» g _ hg h, multiset.rel_zero_left.2 $ multiset.eq_zero_of_forall_not_mem $ Ξ» x hx, have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm, (hg x hx).not_unit $ is_unit_iff_dvd_one.2 $ (multiset.dvd_prod hx).trans (is_unit_iff_dvd_one.1 this)) (Ξ» p f ih g hf hg hfg, let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod (hf p (by simp)) (Ξ» q hq, hg _ hq) $ hfg.dvd_iff_dvd_right.1 (show p ∣ (p ::β‚˜ f).prod, by simp) in begin rw ← multiset.cons_erase hbg, exact multiset.rel.cons hb (ih (Ξ» q hq, hf _ (by simp [hq])) (Ξ» q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq)) (associated.of_mul_left (by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb (hf p (by simp)).ne_zero)), end) /-- If an irreducible has a prime factorization, then it is an associate of one of its prime factors. -/ lemma prime_factors_irreducible [cancel_comm_monoid_with_zero Ξ±] {a : Ξ±} {f : multiset Ξ±} (ha : irreducible a) (pfa : (βˆ€ b ∈ f, prime b) ∧ f.prod ~α΅€ a) : βˆƒ p, a ~α΅€ p ∧ f = {p} := begin haveI := classical.dec_eq Ξ±, refine multiset.induction_on f (Ξ» h, (ha.not_unit (associated_one_iff_is_unit.1 (associated.symm h))).elim) _ pfa.2 pfa.1, rintros p s _ ⟨u, hu⟩ hs, use p, have hs0 : s = 0, { by_contra hs0, obtain ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0, apply (hs q (by simp [hq])).2.1, refine (ha.is_unit_or_is_unit (_ : _ = ((p * ↑u) * (s.erase q).prod) * _)).resolve_left _, { rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq, ← hu, mul_comm, mul_comm p _, mul_assoc], simp, }, apply mt is_unit_of_mul_is_unit_left (mt is_unit_of_mul_is_unit_left _), apply (hs p (multiset.mem_cons_self _ _)).2.1 }, simp only [mul_one, multiset.prod_cons, multiset.prod_zero, hs0] at *, exact ⟨associated.symm ⟨u, hu⟩, rfl⟩, end section exists_prime_factors variables [cancel_comm_monoid_with_zero Ξ±] variables (pf : βˆ€ (a : Ξ±), a β‰  0 β†’ βˆƒ f : multiset Ξ±, (βˆ€b ∈ f, prime b) ∧ f.prod ~α΅€ a) include pf lemma wf_dvd_monoid.of_exists_prime_factors : wf_dvd_monoid Ξ± := ⟨begin classical, refine rel_hom_class.well_founded (rel_hom.mk _ _ : (dvd_not_unit : Ξ± β†’ Ξ± β†’ Prop) β†’r ((<) : with_top β„• β†’ with_top β„• β†’ Prop)) (with_top.well_founded_lt nat.lt_wf), { intro a, by_cases h : a = 0, { exact ⊀ }, exact (classical.some (pf a h)).card }, rintros a b ⟨ane0, ⟨c, hc, b_eq⟩⟩, rw dif_neg ane0, by_cases h : b = 0, { simp [h, lt_top_iff_ne_top] }, rw [dif_neg h, with_top.coe_lt_coe], have cne0 : c β‰  0, { refine mt (Ξ» con, _) h, rw [b_eq, con, mul_zero] }, calc multiset.card (classical.some (pf a ane0)) < _ + multiset.card (classical.some (pf c cne0)) : lt_add_of_pos_right _ (multiset.card_pos.mpr (Ξ» con, hc (associated_one_iff_is_unit.mp _))) ... = multiset.card (classical.some (pf a ane0) + classical.some (pf c cne0)) : (multiset.card_add _ _).symm ... = multiset.card (classical.some (pf b h)) : multiset.card_eq_card_of_rel (prime_factors_unique _ (classical.some_spec (pf _ h)).1 _), { convert (classical.some_spec (pf c cne0)).2.symm, rw [con, multiset.prod_zero] }, { intros x hadd, rw multiset.mem_add at hadd, cases hadd; apply (classical.some_spec (pf _ _)).1 _ hadd }, { rw multiset.prod_add, transitivity a * c, { apply associated.mul_mul; apply (classical.some_spec (pf _ _)).2 }, { rw ← b_eq, apply (classical.some_spec (pf _ _)).2.symm, } } end⟩ lemma irreducible_iff_prime_of_exists_prime_factors {p : Ξ±} : irreducible p ↔ prime p := begin by_cases hp0 : p = 0, { simp [hp0] }, refine ⟨λ h, _, prime.irreducible⟩, obtain ⟨f, hf⟩ := pf p hp0, obtain ⟨q, hq, rfl⟩ := prime_factors_irreducible h hf, rw hq.prime_iff, exact hf.1 q (multiset.mem_singleton_self _) end theorem unique_factorization_monoid.of_exists_prime_factors : unique_factorization_monoid Ξ± := { irreducible_iff_prime := Ξ» _, irreducible_iff_prime_of_exists_prime_factors pf, .. wf_dvd_monoid.of_exists_prime_factors pf } end exists_prime_factors theorem unique_factorization_monoid.iff_exists_prime_factors [cancel_comm_monoid_with_zero Ξ±] : unique_factorization_monoid Ξ± ↔ (βˆ€ (a : Ξ±), a β‰  0 β†’ βˆƒ f : multiset Ξ±, (βˆ€b ∈ f, prime b) ∧ f.prod ~α΅€ a) := ⟨λ h, @unique_factorization_monoid.exists_prime_factors _ _ h, unique_factorization_monoid.of_exists_prime_factors⟩ section variables {Ξ² : Type*} [cancel_comm_monoid_with_zero Ξ±] [cancel_comm_monoid_with_zero Ξ²] lemma mul_equiv.unique_factorization_monoid (e : Ξ± ≃* Ξ²) (hΞ± : unique_factorization_monoid Ξ±) : unique_factorization_monoid Ξ² := begin rw unique_factorization_monoid.iff_exists_prime_factors at hΞ± ⊒, intros a ha, obtain ⟨w,hp,u,h⟩ := hΞ± (e.symm a) (Ξ» h, ha $ by { convert ← map_zero e, simp [← h] }), exact ⟨ w.map e, Ξ» b hb, let ⟨c,hc,he⟩ := multiset.mem_map.1 hb in he β–Έ e.prime_iff.1 (hp c hc), units.map e.to_monoid_hom u, by { erw [multiset.prod_hom, ← e.map_mul, h], simp } ⟩, end lemma mul_equiv.unique_factorization_monoid_iff (e : Ξ± ≃* Ξ²) : unique_factorization_monoid Ξ± ↔ unique_factorization_monoid Ξ² := ⟨ e.unique_factorization_monoid, e.symm.unique_factorization_monoid ⟩ end theorem irreducible_iff_prime_of_exists_unique_irreducible_factors [cancel_comm_monoid_with_zero Ξ±] (eif : βˆ€ (a : Ξ±), a β‰  0 β†’ βˆƒ f : multiset Ξ±, (βˆ€b ∈ f, irreducible b) ∧ f.prod ~α΅€ a) (uif : βˆ€ (f g : multiset Ξ±), (βˆ€ x ∈ f, irreducible x) β†’ (βˆ€ x ∈ g, irreducible x) β†’ f.prod ~α΅€ g.prod β†’ multiset.rel associated f g) (p : Ξ±) : irreducible p ↔ prime p := ⟨by letI := classical.dec_eq Ξ±; exact Ξ» hpi, ⟨hpi.ne_zero, hpi.1, Ξ» a b ⟨x, hx⟩, if hab0 : a * b = 0 then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim (Ξ» ha0, by simp [ha0]) (Ξ» hb0, by simp [hb0]) else have hx0 : x β‰  0, from Ξ» hx0, by simp * at *, have ha0 : a β‰  0, from left_ne_zero_of_mul hab0, have hb0 : b β‰  0, from right_ne_zero_of_mul hab0, begin cases eif x hx0 with fx hfx, cases eif a ha0 with fa hfa, cases eif b hb0 with fb hfb, have h : multiset.rel associated (p ::β‚˜ fx) (fa + fb), { apply uif, { exact Ξ» i hi, (multiset.mem_cons.1 hi).elim (Ξ» hip, hip.symm β–Έ hpi) (hfx.1 _), }, { exact Ξ» i hi, (multiset.mem_add.1 hi).elim (hfa.1 _) (hfb.1 _), }, calc multiset.prod (p ::β‚˜ fx) ~α΅€ a * b : by rw [hx, multiset.prod_cons]; exact hfx.2.mul_left _ ... ~α΅€ (fa).prod * (fb).prod : hfa.2.symm.mul_mul hfb.2.symm ... = _ : by rw multiset.prod_add, }, exact let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem h (multiset.mem_cons_self p _) in (multiset.mem_add.1 hqf).elim (Ξ» hqa, or.inl $ hq.dvd_iff_dvd_left.2 $ hfa.2.dvd_iff_dvd_right.1 (multiset.dvd_prod hqa)) (Ξ» hqb, or.inr $ hq.dvd_iff_dvd_left.2 $ hfb.2.dvd_iff_dvd_right.1 (multiset.dvd_prod hqb)) end⟩, prime.irreducible⟩ theorem unique_factorization_monoid.of_exists_unique_irreducible_factors [cancel_comm_monoid_with_zero Ξ±] (eif : βˆ€ (a : Ξ±), a β‰  0 β†’ βˆƒ f : multiset Ξ±, (βˆ€b ∈ f, irreducible b) ∧ f.prod ~α΅€ a) (uif : βˆ€ (f g : multiset Ξ±), (βˆ€ x ∈ f, irreducible x) β†’ (βˆ€ x ∈ g, irreducible x) β†’ f.prod ~α΅€ g.prod β†’ multiset.rel associated f g) : unique_factorization_monoid Ξ± := unique_factorization_monoid.of_exists_prime_factors (by { convert eif, simp_rw irreducible_iff_prime_of_exists_unique_irreducible_factors eif uif }) namespace unique_factorization_monoid variables [cancel_comm_monoid_with_zero Ξ±] [decidable_eq Ξ±] variables [unique_factorization_monoid Ξ±] /-- Noncomputably determines the multiset of prime factors. -/ noncomputable def factors (a : Ξ±) : multiset Ξ± := if h : a = 0 then 0 else classical.some (unique_factorization_monoid.exists_prime_factors a h) theorem factors_prod {a : Ξ±} (ane0 : a β‰  0) : associated (factors a).prod a := begin rw [factors, dif_neg ane0], exact (classical.some_spec (exists_prime_factors a ane0)).2 end theorem prime_of_factor {a : Ξ±} : βˆ€ (x : Ξ±), x ∈ factors a β†’ prime x := begin rw [factors], split_ifs with ane0, { simp only [multiset.not_mem_zero, forall_false_left, forall_const] }, intros x hx, exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 x hx, end theorem irreducible_of_factor {a : Ξ±} : βˆ€ (x : Ξ±), x ∈ factors a β†’ irreducible x := Ξ» x h, (prime_of_factor x h).irreducible lemma exists_mem_factors_of_dvd {a p : Ξ±} (ha0 : a β‰  0) (hp : irreducible p) : p ∣ a β†’ βˆƒ q ∈ factors a, p ~α΅€ q := Ξ» ⟨b, hb⟩, have hb0 : b β‰  0, from Ξ» hb0, by simp * at *, have multiset.rel associated (p ::β‚˜ factors b) (factors a), from factors_unique (Ξ» x hx, (multiset.mem_cons.1 hx).elim (Ξ» h, h.symm β–Έ hp) (irreducible_of_factor _)) irreducible_of_factor (associated.symm $ calc multiset.prod (factors a) ~α΅€ a : factors_prod ha0 ... = p * b : hb ... ~α΅€ multiset.prod (p ::β‚˜ factors b) : by rw multiset.prod_cons; exact (factors_prod hb0).symm.mul_left _), multiset.exists_mem_of_rel_of_mem this (by simp) end unique_factorization_monoid namespace unique_factorization_monoid variables [cancel_comm_monoid_with_zero Ξ±] [decidable_eq Ξ±] [normalization_monoid Ξ±] variables [unique_factorization_monoid Ξ±] /-- Noncomputably determines the multiset of prime factors. -/ noncomputable def normalized_factors (a : Ξ±) : multiset Ξ± := multiset.map normalize $ factors a /-- An arbitrary choice of factors of `x : M` is exactly the (unique) normalized set of factors, if `M` has a trivial group of units. -/ @[simp] lemma factors_eq_normalized_factors {M : Type*} [cancel_comm_monoid_with_zero M] [decidable_eq M] [unique_factorization_monoid M] [unique (MΛ£)] (x : M) : factors x = normalized_factors x := begin unfold normalized_factors, convert (multiset.map_id (factors x)).symm, ext p, exact normalize_eq p end theorem normalized_factors_prod {a : Ξ±} (ane0 : a β‰  0) : associated (normalized_factors a).prod a := begin rw [normalized_factors, factors, dif_neg ane0], refine associated.trans _ (classical.some_spec (exists_prime_factors a ane0)).2, rw [← associates.mk_eq_mk_iff_associated, ← associates.prod_mk, ← associates.prod_mk, multiset.map_map], congr' 2, ext, rw [function.comp_apply, associates.mk_normalize], end theorem prime_of_normalized_factor {a : Ξ±} : βˆ€ (x : Ξ±), x ∈ normalized_factors a β†’ prime x := begin rw [normalized_factors, factors], split_ifs with ane0, { simp }, intros x hx, rcases multiset.mem_map.1 hx with ⟨y, ⟨hy, rfl⟩⟩, rw (normalize_associated _).prime_iff, exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 y hy, end theorem irreducible_of_normalized_factor {a : Ξ±} : βˆ€ (x : Ξ±), x ∈ normalized_factors a β†’ irreducible x := Ξ» x h, (prime_of_normalized_factor x h).irreducible theorem normalize_normalized_factor {a : Ξ±} : βˆ€ (x : Ξ±), x ∈ normalized_factors a β†’ normalize x = x := begin rw [normalized_factors, factors], split_ifs with h, { simp }, intros x hx, obtain ⟨y, hy, rfl⟩ := multiset.mem_map.1 hx, apply normalize_idem end lemma normalized_factors_irreducible {a : Ξ±} (ha : irreducible a) : normalized_factors a = {normalize a} := begin obtain ⟨p, a_assoc, hp⟩ := prime_factors_irreducible ha ⟨prime_of_normalized_factor, normalized_factors_prod ha.ne_zero⟩, have p_mem : p ∈ normalized_factors a, { rw hp, exact multiset.mem_singleton_self _ }, convert hp, rwa [← normalize_normalized_factor p p_mem, normalize_eq_normalize_iff, dvd_dvd_iff_associated] end lemma exists_mem_normalized_factors_of_dvd {a p : Ξ±} (ha0 : a β‰  0) (hp : irreducible p) : p ∣ a β†’ βˆƒ q ∈ normalized_factors a, p ~α΅€ q := Ξ» ⟨b, hb⟩, have hb0 : b β‰  0, from Ξ» hb0, by simp * at *, have multiset.rel associated (p ::β‚˜ normalized_factors b) (normalized_factors a), from factors_unique (Ξ» x hx, (multiset.mem_cons.1 hx).elim (Ξ» h, h.symm β–Έ hp) (irreducible_of_normalized_factor _)) irreducible_of_normalized_factor (associated.symm $ calc multiset.prod (normalized_factors a) ~α΅€ a : normalized_factors_prod ha0 ... = p * b : hb ... ~α΅€ multiset.prod (p ::β‚˜ normalized_factors b) : by rw multiset.prod_cons; exact (normalized_factors_prod hb0).symm.mul_left _), multiset.exists_mem_of_rel_of_mem this (by simp) @[simp] lemma normalized_factors_zero : normalized_factors (0 : Ξ±) = 0 := by simp [normalized_factors, factors] @[simp] lemma normalized_factors_one : normalized_factors (1 : Ξ±) = 0 := begin nontriviality Ξ± using [normalized_factors, factors], rw ← multiset.rel_zero_right, apply factors_unique irreducible_of_normalized_factor, { intros x hx, exfalso, apply multiset.not_mem_zero x hx }, { simp [normalized_factors_prod (@one_ne_zero Ξ± _ _)] }, apply_instance end @[simp] lemma normalized_factors_mul {x y : Ξ±} (hx : x β‰  0) (hy : y β‰  0) : normalized_factors (x * y) = normalized_factors x + normalized_factors y := begin have h : (normalize : Ξ± β†’ Ξ±) = associates.out ∘ associates.mk, { ext, rw [function.comp_apply, associates.out_mk], }, rw [← multiset.map_id' (normalized_factors (x * y)), ← multiset.map_id' (normalized_factors x), ← multiset.map_id' (normalized_factors y), ← multiset.map_congr rfl normalize_normalized_factor, ← multiset.map_congr rfl normalize_normalized_factor, ← multiset.map_congr rfl normalize_normalized_factor, ← multiset.map_add, h, ← multiset.map_map associates.out, eq_comm, ← multiset.map_map associates.out], refine congr rfl _, apply multiset.map_mk_eq_map_mk_of_rel, apply factors_unique, { intros x hx, rcases multiset.mem_add.1 hx with hx | hx; exact irreducible_of_normalized_factor x hx }, { exact irreducible_of_normalized_factor }, { rw multiset.prod_add, exact ((normalized_factors_prod hx).mul_mul (normalized_factors_prod hy)).trans (normalized_factors_prod (mul_ne_zero hx hy)).symm } end @[simp] lemma normalized_factors_pow {x : Ξ±} (n : β„•) : normalized_factors (x ^ n) = n β€’ normalized_factors x := begin induction n with n ih, { simp }, by_cases h0 : x = 0, { simp [h0, zero_pow n.succ_pos, smul_zero] }, rw [pow_succ, succ_nsmul, normalized_factors_mul h0 (pow_ne_zero _ h0), ih], end theorem _root_.irreducible.normalized_factors_pow {p : Ξ±} (hp : irreducible p) (k : β„•) : normalized_factors (p ^ k) = multiset.repeat (normalize p) k := by rw [normalized_factors_pow, normalized_factors_irreducible hp, multiset.nsmul_singleton] lemma dvd_iff_normalized_factors_le_normalized_factors {x y : Ξ±} (hx : x β‰  0) (hy : y β‰  0) : x ∣ y ↔ normalized_factors x ≀ normalized_factors y := begin split, { rintro ⟨c, rfl⟩, simp [hx, right_ne_zero_of_mul hy] }, { rw [← (normalized_factors_prod hx).dvd_iff_dvd_left, ← (normalized_factors_prod hy).dvd_iff_dvd_right], apply multiset.prod_dvd_prod_of_le } end theorem normalized_factors_of_irreducible_pow {p : Ξ±} (hp : irreducible p) (k : β„•) : normalized_factors (p ^ k) = multiset.repeat (normalize p) k := by rw [normalized_factors_pow, normalized_factors_irreducible hp, multiset.nsmul_singleton] lemma zero_not_mem_normalized_factors (x : Ξ±) : (0 : Ξ±) βˆ‰ normalized_factors x := Ξ» h, prime.ne_zero (prime_of_normalized_factor _ h) rfl lemma dvd_of_mem_normalized_factors {a p : Ξ±} (H : p ∈ normalized_factors a) : p ∣ a := begin by_cases hcases : a = 0, { rw hcases, exact dvd_zero p }, { exact dvd_trans (multiset.dvd_prod H) (associated.dvd (normalized_factors_prod hcases)) }, end lemma exists_associated_prime_pow_of_unique_normalized_factor {p r : Ξ±} (h : βˆ€ {m}, m ∈ normalized_factors r β†’ m = p) (hr : r β‰  0) : βˆƒ (i : β„•), associated (p ^ i) r := begin use (normalized_factors r).card, have := unique_factorization_monoid.normalized_factors_prod hr, rwa [multiset.eq_repeat_of_mem (Ξ» b, h), multiset.prod_repeat] at this end end unique_factorization_monoid namespace unique_factorization_monoid open_locale classical open multiset associates noncomputable theory variables [cancel_comm_monoid_with_zero Ξ±] [nontrivial Ξ±] [unique_factorization_monoid Ξ±] /-- Noncomputably defines a `normalization_monoid` structure on a `unique_factorization_monoid`. -/ protected def normalization_monoid : normalization_monoid Ξ± := normalization_monoid_of_monoid_hom_right_inverse { to_fun := Ξ» a : associates Ξ±, if a = 0 then 0 else ((normalized_factors a).map (classical.some mk_surjective.has_right_inverse : associates Ξ± β†’ Ξ±)).prod, map_one' := by simp, map_mul' := Ξ» x y, by { by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, simp [hx, hy] } } begin intro x, dsimp, by_cases hx : x = 0, { simp [hx] }, have h : associates.mk_monoid_hom ∘ (classical.some mk_surjective.has_right_inverse) = (id : associates Ξ± β†’ associates Ξ±), { ext x, rw [function.comp_apply, mk_monoid_hom_apply, classical.some_spec mk_surjective.has_right_inverse x], refl }, rw [if_neg hx, ← mk_monoid_hom_apply, monoid_hom.map_multiset_prod, map_map, h, map_id, ← associated_iff_eq], apply normalized_factors_prod hx end instance : inhabited (normalization_monoid Ξ±) := ⟨unique_factorization_monoid.normalization_monoid⟩ end unique_factorization_monoid namespace unique_factorization_monoid variables {R : Type*} [cancel_comm_monoid_with_zero R] [unique_factorization_monoid R] lemma no_factors_of_no_prime_factors {a b : R} (ha : a β‰  0) (h : (βˆ€ {d}, d ∣ a β†’ d ∣ b β†’ Β¬ prime d)) : βˆ€ {d}, d ∣ a β†’ d ∣ b β†’ is_unit d := Ξ» d, induction_on_prime d (by { simp only [zero_dvd_iff], intros, contradiction }) (Ξ» x hx _ _, hx) (Ξ» d q hp hq ih dvd_a dvd_b, absurd hq (h (dvd_of_mul_right_dvd dvd_a) (dvd_of_mul_right_dvd dvd_b))) /-- Euclid's lemma: if `a ∣ b * c` and `a` and `c` have no common prime factors, `a ∣ b`. Compare `is_coprime.dvd_of_dvd_mul_left`. -/ lemma dvd_of_dvd_mul_left_of_no_prime_factors {a b c : R} (ha : a β‰  0) : (βˆ€ {d}, d ∣ a β†’ d ∣ c β†’ Β¬ prime d) β†’ a ∣ b * c β†’ a ∣ b := begin refine induction_on_prime c _ _ _, { intro no_factors, simp only [dvd_zero, mul_zero, forall_prop_of_true], haveI := classical.prop_decidable, exact is_unit_iff_forall_dvd.mp (no_factors_of_no_prime_factors ha @no_factors (dvd_refl a) (dvd_zero a)) _ }, { rintros _ ⟨x, rfl⟩ _ a_dvd_bx, apply units.dvd_mul_right.mp a_dvd_bx }, { intros c p hc hp ih no_factors a_dvd_bpc, apply ih (Ξ» q dvd_a dvd_c hq, no_factors dvd_a (dvd_c.mul_left _) hq), rw mul_left_comm at a_dvd_bpc, refine or.resolve_left (hp.left_dvd_or_dvd_right_of_dvd_mul a_dvd_bpc) (Ξ» h, _), exact no_factors h (dvd_mul_right p c) hp } end /-- Euclid's lemma: if `a ∣ b * c` and `a` and `b` have no common prime factors, `a ∣ c`. Compare `is_coprime.dvd_of_dvd_mul_right`. -/ lemma dvd_of_dvd_mul_right_of_no_prime_factors {a b c : R} (ha : a β‰  0) (no_factors : βˆ€ {d}, d ∣ a β†’ d ∣ b β†’ Β¬ prime d) : a ∣ b * c β†’ a ∣ c := by simpa [mul_comm b c] using dvd_of_dvd_mul_left_of_no_prime_factors ha @no_factors /-- If `a β‰  0, b` are elements of a unique factorization domain, then dividing out their common factor `c'` gives `a'` and `b'` with no factors in common. -/ lemma exists_reduced_factors : βˆ€ (a β‰  (0 : R)) b, βˆƒ a' b' c', (βˆ€ {d}, d ∣ a' β†’ d ∣ b' β†’ is_unit d) ∧ c' * a' = a ∧ c' * b' = b := begin haveI := classical.prop_decidable, intros a, refine induction_on_prime a _ _ _, { intros, contradiction }, { intros a a_unit a_ne_zero b, use [a, b, 1], split, { intros p p_dvd_a _, exact is_unit_of_dvd_unit p_dvd_a a_unit }, { simp } }, { intros a p a_ne_zero p_prime ih_a pa_ne_zero b, by_cases p ∣ b, { rcases h with ⟨b, rfl⟩, obtain ⟨a', b', c', no_factor, ha', hb'⟩ := ih_a a_ne_zero b, refine ⟨a', b', p * c', @no_factor, _, _⟩, { rw [mul_assoc, ha'] }, { rw [mul_assoc, hb'] } }, { obtain ⟨a', b', c', coprime, rfl, rfl⟩ := ih_a a_ne_zero b, refine ⟨p * a', b', c', _, mul_left_comm _ _ _, rfl⟩, intros q q_dvd_pa' q_dvd_b', cases p_prime.left_dvd_or_dvd_right_of_dvd_mul q_dvd_pa' with p_dvd_q q_dvd_a', { have : p ∣ c' * b' := dvd_mul_of_dvd_right (p_dvd_q.trans q_dvd_b') _, contradiction }, exact coprime q_dvd_a' q_dvd_b' } } end lemma exists_reduced_factors' (a b : R) (hb : b β‰  0) : βˆƒ a' b' c', (βˆ€ {d}, d ∣ a' β†’ d ∣ b' β†’ is_unit d) ∧ c' * a' = a ∧ c' * b' = b := let ⟨b', a', c', no_factor, hb, ha⟩ := exists_reduced_factors b hb a in ⟨a', b', c', Ξ» _ hpb hpa, no_factor hpa hpb, ha, hb⟩ section multiplicity variables [nontrivial R] [normalization_monoid R] [decidable_eq R] variables [dec_dvd : decidable_rel (has_dvd.dvd : R β†’ R β†’ Prop)] open multiplicity multiset include dec_dvd lemma le_multiplicity_iff_repeat_le_normalized_factors {a b : R} {n : β„•} (ha : irreducible a) (hb : b β‰  0) : ↑n ≀ multiplicity a b ↔ repeat (normalize a) n ≀ normalized_factors b := begin rw ← pow_dvd_iff_le_multiplicity, revert b, induction n with n ih, { simp }, intros b hb, split, { rintro ⟨c, rfl⟩, rw [ne.def, pow_succ, mul_assoc, mul_eq_zero, decidable.not_or_iff_and_not] at hb, rw [pow_succ, mul_assoc, normalized_factors_mul hb.1 hb.2, repeat_succ, normalized_factors_irreducible ha, singleton_add, cons_le_cons_iff, ← ih hb.2], apply dvd.intro _ rfl }, { rw [multiset.le_iff_exists_add], rintro ⟨u, hu⟩, rw [← (normalized_factors_prod hb).dvd_iff_dvd_right, hu, prod_add, prod_repeat], exact (associated.pow_pow $ associated_normalize a).dvd.trans (dvd.intro u.prod rfl) } end /-- The multiplicity of an irreducible factor of a nonzero element is exactly the number of times the normalized factor occurs in the `normalized_factors`. See also `count_normalized_factors_eq` which expands the definition of `multiplicity` to produce a specification for `count (normalized_factors _) _`.. -/ lemma multiplicity_eq_count_normalized_factors {a b : R} (ha : irreducible a) (hb : b β‰  0) : multiplicity a b = (normalized_factors b).count (normalize a) := begin apply le_antisymm, { apply enat.le_of_lt_add_one, rw [← nat.cast_one, ← nat.cast_add, lt_iff_not_ge, ge_iff_le, le_multiplicity_iff_repeat_le_normalized_factors ha hb, ← le_count_iff_repeat_le], simp }, rw [le_multiplicity_iff_repeat_le_normalized_factors ha hb, ← le_count_iff_repeat_le], end omit dec_dvd /-- The number of times an irreducible factor `p` appears in `normalized_factors x` is defined by the number of times it divides `x`. See also `multiplicity_eq_count_normalized_factors` if `n` is given by `multiplicity p x`. -/ lemma count_normalized_factors_eq {p x : R} (hp : irreducible p) (hnorm : normalize p = p) {n : β„•} (hle : p^n ∣ x) (hlt : Β¬ (p^(n+1) ∣ x)) : (normalized_factors x).count p = n := begin letI : decidable_rel ((∣) : R β†’ R β†’ Prop) := Ξ» _ _, classical.prop_decidable _, by_cases hx0 : x = 0, { simp [hx0] at hlt, contradiction }, rw [← enat.coe_inj], convert (multiplicity_eq_count_normalized_factors hp hx0).symm, { exact hnorm.symm }, exact (multiplicity.eq_coe_iff.mpr ⟨hle, hlt⟩).symm end end multiplicity end unique_factorization_monoid namespace associates open unique_factorization_monoid associated multiset variables [cancel_comm_monoid_with_zero Ξ±] /-- `factor_set Ξ±` representation elements of unique factorization domain as multisets. `multiset Ξ±` produced by `normalized_factors` are only unique up to associated elements, while the multisets in `factor_set Ξ±` are unique by equality and restricted to irreducible elements. This gives us a representation of each element as a unique multisets (or the added ⊀ for 0), which has a complete lattice struture. Infimum is the greatest common divisor and supremum is the least common multiple. -/ @[reducible] def {u} factor_set (Ξ± : Type u) [cancel_comm_monoid_with_zero Ξ±] : Type u := with_top (multiset { a : associates Ξ± // irreducible a }) local attribute [instance] associated.setoid theorem factor_set.coe_add {a b : multiset { a : associates Ξ± // irreducible a }} : (↑(a + b) : factor_set Ξ±) = a + b := by norm_cast lemma factor_set.sup_add_inf_eq_add [decidable_eq (associates Ξ±)] : βˆ€(a b : factor_set Ξ±), a βŠ” b + a βŠ“ b = a + b | none b := show ⊀ βŠ” b + ⊀ βŠ“ b = ⊀ + b, by simp | a none := show a βŠ” ⊀ + a βŠ“ ⊀ = a + ⊀, by simp | (some a) (some b) := show (a : factor_set Ξ±) βŠ” b + a βŠ“ b = a + b, from begin rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add, with_top.coe_eq_coe], exact multiset.union_add_inter _ _ end /-- Evaluates the product of a `factor_set` to be the product of the corresponding multiset, or `0` if there is none. -/ def factor_set.prod : factor_set Ξ± β†’ associates Ξ± | none := 0 | (some s) := (s.map coe).prod @[simp] theorem prod_top : (⊀ : factor_set Ξ±).prod = 0 := rfl @[simp] theorem prod_coe {s : multiset { a : associates Ξ± // irreducible a }} : (s : factor_set Ξ±).prod = (s.map coe).prod := rfl @[simp] theorem prod_add : βˆ€(a b : factor_set Ξ±), (a + b).prod = a.prod * b.prod | none b := show (⊀ + b).prod = (⊀:factor_set Ξ±).prod * b.prod, by simp | a none := show (a + ⊀).prod = a.prod * (⊀:factor_set Ξ±).prod, by simp | (some a) (some b) := show (↑a + ↑b:factor_set Ξ±).prod = (↑a:factor_set Ξ±).prod * (↑b:factor_set Ξ±).prod, by rw [← factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add] theorem prod_mono : βˆ€{a b : factor_set Ξ±}, a ≀ b β†’ a.prod ≀ b.prod | none b h := have b = ⊀, from top_unique h, by rw [this, prod_top]; exact le_rfl | a none h := show a.prod ≀ (⊀ : factor_set Ξ±).prod, by simp; exact le_top | (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h theorem factor_set.prod_eq_zero_iff [nontrivial Ξ±] (p : factor_set Ξ±) : p.prod = 0 ↔ p = ⊀ := begin induction p using with_top.rec_top_coe, { simp only [iff_self, eq_self_iff_true, associates.prod_top] }, simp only [prod_coe, with_top.coe_ne_top, iff_false, prod_eq_zero_iff, multiset.mem_map], rintro ⟨⟨a, ha⟩, -, eq⟩, rw [subtype.coe_mk] at eq, exact ha.ne_zero eq, end /-- `bcount p s` is the multiplicity of `p` in the factor_set `s` (with bundled `p`)-/ def bcount [decidable_eq (associates Ξ±)] (p : {a : associates Ξ± // irreducible a}) : factor_set Ξ± β†’ β„• | none := 0 | (some s) := s.count p variables [dec_irr : Ξ  (p : associates Ξ±), decidable (irreducible p)] include dec_irr /-- `count p s` is the multiplicity of the irreducible `p` in the factor_set `s`. If `p` is not irreducible, `count p s` is defined to be `0`. -/ def count [decidable_eq (associates Ξ±)] (p : associates Ξ±) : factor_set Ξ± β†’ β„• := if hp : irreducible p then bcount ⟨p, hp⟩ else 0 @[simp] lemma count_some [decidable_eq (associates Ξ±)] {p : associates Ξ±} (hp : irreducible p) (s : multiset _) : count p (some s) = s.count ⟨p, hp⟩:= by { dunfold count, split_ifs, refl } @[simp] lemma count_zero [decidable_eq (associates Ξ±)] {p : associates Ξ±} (hp : irreducible p) : count p (0 : factor_set Ξ±) = 0 := by { dunfold count, split_ifs, refl } lemma count_reducible [decidable_eq (associates Ξ±)] {p : associates Ξ±} (hp : Β¬ irreducible p) : count p = 0 := dif_neg hp omit dec_irr /-- membership in a factor_set (bundled version) -/ def bfactor_set_mem : {a : associates Ξ± // irreducible a} β†’ (factor_set Ξ±) β†’ Prop | _ ⊀ := true | p (some l) := p ∈ l include dec_irr /-- `factor_set_mem p s` is the predicate that the irreducible `p` is a member of `s : factor_set Ξ±`. If `p` is not irreducible, `p` is not a member of any `factor_set`. -/ def factor_set_mem (p : associates Ξ±) (s : factor_set Ξ±) : Prop := if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false instance : has_mem (associates Ξ±) (factor_set Ξ±) := ⟨factor_set_mem⟩ @[simp] lemma factor_set_mem_eq_mem (p : associates Ξ±) (s : factor_set Ξ±) : factor_set_mem p s = (p ∈ s) := rfl lemma mem_factor_set_top {p : associates Ξ±} {hp : irreducible p} : p ∈ (⊀ : factor_set Ξ±) := begin dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, exact trivial end lemma mem_factor_set_some {p : associates Ξ±} {hp : irreducible p} {l : multiset {a : associates Ξ± // irreducible a }} : p ∈ (l : factor_set Ξ±) ↔ subtype.mk p hp ∈ l := begin dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, refl end lemma reducible_not_mem_factor_set {p : associates Ξ±} (hp : Β¬ irreducible p) (s : factor_set Ξ±) : Β¬ p ∈ s := Ξ» (h : if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false), by rwa [dif_neg hp] at h omit dec_irr variable [unique_factorization_monoid Ξ±] theorem unique' {p q : multiset (associates Ξ±)} : (βˆ€a∈p, irreducible a) β†’ (βˆ€a∈q, irreducible a) β†’ p.prod = q.prod β†’ p = q := begin apply multiset.induction_on_multiset_quot p, apply multiset.induction_on_multiset_quot q, assume s t hs ht eq, refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_monoid.factors_unique _ _ _), { exact assume a ha, ((irreducible_mk _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) }, { exact assume a ha, ((irreducible_mk _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) }, simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq end theorem factor_set.unique [nontrivial Ξ±] {p q : factor_set Ξ±} (h : p.prod = q.prod) : p = q := begin induction p using with_top.rec_top_coe; induction q using with_top.rec_top_coe, { refl }, { rw [eq_comm, ←factor_set.prod_eq_zero_iff, ←h, associates.prod_top] }, { rw [←factor_set.prod_eq_zero_iff, h, associates.prod_top] }, { congr' 1, rw ←multiset.map_eq_map subtype.coe_injective, apply unique' _ _ h; { intros a ha, obtain ⟨⟨a', irred⟩, -, rfl⟩ := multiset.mem_map.mp ha, rwa [subtype.coe_mk] } }, end theorem prod_le_prod_iff_le [nontrivial Ξ±] {p q : multiset (associates Ξ±)} (hp : βˆ€a∈p, irreducible a) (hq : βˆ€a∈q, irreducible a) : p.prod ≀ q.prod ↔ p ≀ q := iff.intro begin classical, rintros ⟨c, eqc⟩, refine multiset.le_iff_exists_add.2 ⟨factors c, unique' hq (Ξ» x hx, _) _⟩, { obtain h|h := multiset.mem_add.1 hx, { exact hp x h }, { exact irreducible_of_factor _ h } }, { rw [eqc, multiset.prod_add], congr, refine associated_iff_eq.mp (factors_prod (Ξ» hc, _)).symm, refine not_irreducible_zero (hq _ _), rw [←prod_eq_zero_iff, eqc, hc, mul_zero] } end prod_le_prod variables [dec : decidable_eq Ξ±] [dec' : decidable_eq (associates Ξ±)] include dec /-- This returns the multiset of irreducible factors as a `factor_set`, a multiset of irreducible associates `with_top`. -/ noncomputable def factors' (a : Ξ±) : multiset { a : associates Ξ± // irreducible a } := (factors a).pmap (Ξ»a ha, ⟨associates.mk a, (irreducible_mk _).2 ha⟩) (irreducible_of_factor) @[simp] theorem map_subtype_coe_factors' {a : Ξ±} : (factors' a).map coe = (factors a).map associates.mk := by simp [factors', multiset.map_pmap, multiset.pmap_eq_map] theorem factors'_cong {a b : Ξ±} (h : a ~α΅€ b) : factors' a = factors' b := begin obtain rfl|hb := eq_or_ne b 0, { rw associated_zero_iff_eq_zero at h, rw h }, have ha : a β‰  0, { contrapose! hb with ha, rw [←associated_zero_iff_eq_zero, ←ha], exact h.symm }, rw [←multiset.map_eq_map subtype.coe_injective, map_subtype_coe_factors', map_subtype_coe_factors', ←rel_associated_iff_map_eq_map], exact factors_unique irreducible_of_factor irreducible_of_factor ((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm), end include dec' /-- This returns the multiset of irreducible factors of an associate as a `factor_set`, a multiset of irreducible associates `with_top`. -/ noncomputable def factors (a : associates Ξ±) : factor_set Ξ± := begin refine (if h : a = 0 then ⊀ else quotient.hrec_on a (Ξ»x h, some $ factors' x) _ h), assume a b hab, apply function.hfunext, { have : a ~α΅€ 0 ↔ b ~α΅€ 0, from iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0), simp only [associated_zero_iff_eq_zero] at this, simp only [quotient_mk_eq_mk, this, mk_eq_zero] }, exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong hab) end @[simp] theorem factors_0 : (0 : associates Ξ±).factors = ⊀ := dif_pos rfl @[simp] theorem factors_mk (a : Ξ±) (h : a β‰  0) : (associates.mk a).factors = factors' a := by { classical, apply dif_neg, apply (mt mk_eq_zero.1 h) } @[simp] theorem factors_prod (a : associates Ξ±) : a.factors.prod = a := quotient.induction_on a $ assume a, decidable.by_cases (assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this]) (assume : associates.mk a β‰  0, have a β‰  0, by simp * at *, by simp [this, quotient_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated.2 (factors_prod this)]) theorem prod_factors [nontrivial Ξ±] (s : factor_set Ξ±) : s.prod.factors = s := factor_set.unique $ factors_prod _ @[nontriviality] lemma factors_subsingleton [subsingleton Ξ±] {a : associates Ξ±} : a.factors = option.none := by { convert factors_0; apply_instance } lemma factors_eq_none_iff_zero {a : associates Ξ±} : a.factors = option.none ↔ a = 0 := begin nontriviality Ξ±, exact ⟨λ h, by rwa [← factors_prod a, factor_set.prod_eq_zero_iff], Ξ» h, h.symm β–Έ factors_0⟩ end lemma factors_eq_some_iff_ne_zero {a : associates Ξ±} : (βˆƒ (s : multiset {p : associates Ξ± // irreducible p}), a.factors = some s) ↔ a β‰  0 := by rw [← option.is_some_iff_exists, ← option.ne_none_iff_is_some, ne.def, ne.def, factors_eq_none_iff_zero] theorem eq_of_factors_eq_factors {a b : associates Ξ±} (h : a.factors = b.factors) : a = b := have a.factors.prod = b.factors.prod, by rw h, by rwa [factors_prod, factors_prod] at this omit dec dec' theorem eq_of_prod_eq_prod [nontrivial Ξ±] {a b : factor_set Ξ±} (h : a.prod = b.prod) : a = b := begin classical, have : a.prod.factors = b.prod.factors, by rw h, rwa [prod_factors, prod_factors] at this end include dec dec' dec_irr theorem eq_factors_of_eq_counts {a b : associates Ξ±} (ha : a β‰  0) (hb : b β‰  0) (h : βˆ€ (p : associates Ξ±) (hp : irreducible p), p.count a.factors = p.count b.factors) : a.factors = b.factors := begin obtain ⟨sa, h_sa⟩ := factors_eq_some_iff_ne_zero.mpr ha, obtain ⟨sb, h_sb⟩ := factors_eq_some_iff_ne_zero.mpr hb, rw [h_sa, h_sb] at h ⊒, rw option.some_inj, have h_count : βˆ€ (p : associates Ξ±) (hp : irreducible p), sa.count ⟨p, hp⟩ = sb.count ⟨p, hp⟩, { intros p hp, rw [← count_some, ← count_some, h p hp] }, apply multiset.to_finsupp.injective, ext ⟨p, hp⟩, rw [multiset.to_finsupp_apply, multiset.to_finsupp_apply, h_count p hp] end theorem eq_of_eq_counts {a b : associates Ξ±} (ha : a β‰  0) (hb : b β‰  0) (h : βˆ€ (p : associates Ξ±), irreducible p β†’ p.count a.factors = p.count b.factors) : a = b := eq_of_factors_eq_factors (eq_factors_of_eq_counts ha hb h) lemma count_le_count_of_factors_le {a b p : associates Ξ±} (hb : b β‰  0) (hp : irreducible p) (h : a.factors ≀ b.factors) : p.count a.factors ≀ p.count b.factors := begin by_cases ha : a = 0, { simp [*] at *, }, obtain ⟨sa, h_sa⟩ := factors_eq_some_iff_ne_zero.mpr ha, obtain ⟨sb, h_sb⟩ := factors_eq_some_iff_ne_zero.mpr hb, rw [h_sa, h_sb] at h ⊒, rw [count_some hp, count_some hp], rw with_top.some_le_some at h, exact multiset.count_le_of_le _ h end omit dec_irr @[simp] theorem factors_mul (a b : associates Ξ±) : (a * b).factors = a.factors + b.factors := begin casesI subsingleton_or_nontrivial Ξ±, { simp [subsingleton.elim a 0], }, refine (eq_of_prod_eq_prod (eq_of_factors_eq_factors _)), rw [prod_add, factors_prod, factors_prod, factors_prod], end theorem factors_mono : βˆ€{a b : associates Ξ±}, a ≀ b β†’ a.factors ≀ b.factors | s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right bot_le theorem factors_le {a b : associates Ξ±} : a.factors ≀ b.factors ↔ a ≀ b := iff.intro (assume h, have a.factors.prod ≀ b.factors.prod, from prod_mono h, by rwa [factors_prod, factors_prod] at this) factors_mono include dec_irr lemma count_le_count_of_le {a b p : associates Ξ±} (hb : b β‰  0) (hp : irreducible p) (h : a ≀ b) : p.count a.factors ≀ p.count b.factors := count_le_count_of_factors_le hb hp $ factors_mono h omit dec dec' dec_irr theorem prod_le [nontrivial Ξ±] {a b : factor_set Ξ±} : a.prod ≀ b.prod ↔ a ≀ b := begin classical, exact iff.intro (assume h, have a.prod.factors ≀ b.prod.factors, from factors_mono h, by rwa [prod_factors, prod_factors] at this) prod_mono end include dec dec' noncomputable instance : has_sup (associates Ξ±) := ⟨λa b, (a.factors βŠ” b.factors).prod⟩ noncomputable instance : has_inf (associates Ξ±) := ⟨λa b, (a.factors βŠ“ b.factors).prod⟩ noncomputable instance : lattice (associates Ξ±) := { sup := (βŠ”), inf := (βŠ“), sup_le := assume a b c hac hbc, factors_prod c β–Έ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)), le_sup_left := assume a b, le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left, le_sup_right := assume a b, le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right, le_inf := assume a b c hac hbc, factors_prod a β–Έ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)), inf_le_left := assume a b, le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)), inf_le_right := assume a b, le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)), .. associates.partial_order } lemma sup_mul_inf (a b : associates Ξ±) : (a βŠ” b) * (a βŠ“ b) = a * b := show (a.factors βŠ” b.factors).prod * (a.factors βŠ“ b.factors).prod = a * b, begin nontriviality Ξ±, refine eq_of_factors_eq_factors _, rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add] end include dec_irr lemma dvd_of_mem_factors {a p : associates Ξ±} {hp : irreducible p} (hm : p ∈ factors a) : p ∣ a := begin by_cases ha0 : a = 0, { rw ha0, exact dvd_zero p }, obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha0, rw [← associates.factors_prod a], rw [← ha', factors_mk a0 nza] at hm ⊒, erw prod_coe, apply multiset.dvd_prod, apply multiset.mem_map.mpr, exact ⟨⟨p, hp⟩, mem_factor_set_some.mp hm, rfl⟩ end omit dec' lemma dvd_of_mem_factors' {a : Ξ±} {p : associates Ξ±} {hp : irreducible p} {hz : a β‰  0} (h_mem : subtype.mk p hp ∈ factors' a) : p ∣ associates.mk a := by { haveI := classical.dec_eq (associates Ξ±), apply @dvd_of_mem_factors _ _ _ _ _ _ _ _ hp, rw factors_mk _ hz, apply mem_factor_set_some.2 h_mem } omit dec_irr lemma mem_factors'_of_dvd {a p : Ξ±} (ha0 : a β‰  0) (hp : irreducible p) (hd : p ∣ a) : subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a := begin obtain ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd ha0 hp hd, apply multiset.mem_pmap.mpr, use q, use hq, exact subtype.eq (eq.symm (mk_eq_mk_iff_associated.mpr hpq)) end include dec_irr lemma mem_factors'_iff_dvd {a p : Ξ±} (ha0 : a β‰  0) (hp : irreducible p) : subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a ↔ p ∣ a := begin split, { rw ← mk_dvd_mk, apply dvd_of_mem_factors', apply ha0 }, { apply mem_factors'_of_dvd ha0 } end include dec' lemma mem_factors_of_dvd {a p : Ξ±} (ha0 : a β‰  0) (hp : irreducible p) (hd : p ∣ a) : (associates.mk p) ∈ factors (associates.mk a) := begin rw factors_mk _ ha0, exact mem_factor_set_some.mpr (mem_factors'_of_dvd ha0 hp hd) end lemma mem_factors_iff_dvd {a p : Ξ±} (ha0 : a β‰  0) (hp : irreducible p) : (associates.mk p) ∈ factors (associates.mk a) ↔ p ∣ a := begin split, { rw ← mk_dvd_mk, apply dvd_of_mem_factors, exact (irreducible_mk p).mpr hp }, { apply mem_factors_of_dvd ha0 hp } end lemma exists_prime_dvd_of_not_inf_one {a b : Ξ±} (ha : a β‰  0) (hb : b β‰  0) (h : (associates.mk a) βŠ“ (associates.mk b) β‰  1) : βˆƒ (p : Ξ±), prime p ∧ p ∣ a ∧ p ∣ b := begin have hz : (factors (associates.mk a)) βŠ“ (factors (associates.mk b)) β‰  0, { contrapose! h with hf, change ((factors (associates.mk a)) βŠ“ (factors (associates.mk b))).prod = 1, rw hf, exact multiset.prod_zero }, rw [factors_mk a ha, factors_mk b hb, ← with_top.coe_inf] at hz, obtain ⟨⟨p0, p0_irr⟩, p0_mem⟩ := multiset.exists_mem_of_ne_zero ((mt with_top.coe_eq_coe.mpr) hz), rw multiset.inf_eq_inter at p0_mem, obtain ⟨p, rfl⟩ : βˆƒ p, associates.mk p = p0 := quot.exists_rep p0, refine ⟨p, _, _, _⟩, { rw [← irreducible_iff_prime, ← irreducible_mk], exact p0_irr }, { apply dvd_of_mk_le_mk, apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).left, apply ha, }, { apply dvd_of_mk_le_mk, apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).right, apply hb } end theorem coprime_iff_inf_one {a b : Ξ±} (ha0 : a β‰  0) (hb0 : b β‰  0) : (associates.mk a) βŠ“ (associates.mk b) = 1 ↔ βˆ€ {d : Ξ±}, d ∣ a β†’ d ∣ b β†’ Β¬ prime d := begin split, { intros hg p ha hb hp, refine ((associates.prime_mk _).mpr hp).not_unit (is_unit_of_dvd_one _ _), rw ← hg, exact le_inf (mk_le_mk_of_dvd ha) (mk_le_mk_of_dvd hb) }, { contrapose, intros hg hc, obtain ⟨p, hp, hpa, hpb⟩ := exists_prime_dvd_of_not_inf_one ha0 hb0 hg, exact hc hpa hpb hp } end omit dec_irr theorem factors_self [nontrivial Ξ±] {p : associates Ξ±} (hp : irreducible p) : p.factors = some ({⟨p, hp⟩}) := eq_of_prod_eq_prod (by rw [factors_prod, factor_set.prod, map_singleton, prod_singleton, subtype.coe_mk]) theorem factors_prime_pow [nontrivial Ξ±] {p : associates Ξ±} (hp : irreducible p) (k : β„•) : factors (p ^ k) = some (multiset.repeat ⟨p, hp⟩ k) := eq_of_prod_eq_prod (by rw [associates.factors_prod, factor_set.prod, multiset.map_repeat, multiset.prod_repeat, subtype.coe_mk]) include dec_irr theorem prime_pow_dvd_iff_le [nontrivial Ξ±] {m p : associates Ξ±} (h₁ : m β‰  0) (hβ‚‚ : irreducible p) {k : β„•} : p ^ k ≀ m ↔ k ≀ count p m.factors := begin obtain ⟨a, nz, rfl⟩ := associates.exists_non_zero_rep h₁, rw [factors_mk _ nz, ← with_top.some_eq_coe, count_some, multiset.le_count_iff_repeat_le, ← factors_le, factors_prime_pow hβ‚‚, factors_mk _ nz], exact with_top.coe_le_coe end theorem le_of_count_ne_zero {m p : associates Ξ±} (h0 : m β‰  0) (hp : irreducible p) : count p m.factors β‰  0 β†’ p ≀ m := begin nontriviality Ξ±, rw [← pos_iff_ne_zero], intro h, rw [← pow_one p], apply (prime_pow_dvd_iff_le h0 hp).2, simpa only end theorem count_ne_zero_iff_dvd {a p : Ξ±} (ha0 : a β‰  0) (hp : irreducible p) : (associates.mk p).count (associates.mk a).factors β‰  0 ↔ p ∣ a := begin nontriviality Ξ±, rw ← associates.mk_le_mk_iff_dvd_iff, refine ⟨λ h, associates.le_of_count_ne_zero (associates.mk_ne_zero.mpr ha0) ((associates.irreducible_mk p).mpr hp) h, Ξ» h, _⟩, { rw [← pow_one (associates.mk p), associates.prime_pow_dvd_iff_le (associates.mk_ne_zero.mpr ha0) ((associates.irreducible_mk p).mpr hp)] at h, exact (zero_lt_one.trans_le h).ne' } end theorem count_self [nontrivial Ξ±] {p : associates Ξ±} (hp : irreducible p) : p.count p.factors = 1 := by simp [factors_self hp, associates.count_some hp] lemma count_eq_zero_of_ne {p q : associates Ξ±} (hp : irreducible p) (hq : irreducible q) (h : p β‰  q) : p.count q.factors = 0 := not_ne_iff.mp $ Ξ» h', h $ associated_iff_eq.mp $ hp.associated_of_dvd hq $ by { nontriviality Ξ±, exact le_of_count_ne_zero hq.ne_zero hp h' } theorem count_mul {a : associates Ξ±} (ha : a β‰  0) {b : associates Ξ±} (hb : b β‰  0) {p : associates Ξ±} (hp : irreducible p) : count p (factors (a * b)) = count p a.factors + count p b.factors := begin obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha, obtain ⟨b0, nzb, hb'⟩ := exists_non_zero_rep hb, rw [factors_mul, ← ha', ← hb', factors_mk a0 nza, factors_mk b0 nzb, ← factor_set.coe_add, ← with_top.some_eq_coe, ← with_top.some_eq_coe, ← with_top.some_eq_coe, count_some hp, multiset.count_add, count_some hp, count_some hp] end theorem count_of_coprime {a : associates Ξ±} (ha : a β‰  0) {b : associates Ξ±} (hb : b β‰  0) (hab : βˆ€ d, d ∣ a β†’ d ∣ b β†’ Β¬ prime d) {p : associates Ξ±} (hp : irreducible p) : count p a.factors = 0 ∨ count p b.factors = 0 := begin rw [or_iff_not_imp_left, ← ne.def], intro hca, contrapose! hab with hcb, exact ⟨p, le_of_count_ne_zero ha hp hca, le_of_count_ne_zero hb hp hcb, (irreducible_iff_prime.mp hp)⟩, end theorem count_mul_of_coprime {a : associates Ξ±} {b : associates Ξ±} (hb : b β‰  0) {p : associates Ξ±} (hp : irreducible p) (hab : βˆ€ d, d ∣ a β†’ d ∣ b β†’ Β¬ prime d) : count p a.factors = 0 ∨ count p a.factors = count p (a * b).factors := begin by_cases ha : a = 0, { simp [ha], }, cases count_of_coprime ha hb hab hp with hz hb0, { tauto }, apply or.intro_right, rw [count_mul ha hb hp, hb0, add_zero] end theorem count_mul_of_coprime' {a b : associates Ξ±} {p : associates Ξ±} (hp : irreducible p) (hab : βˆ€ d, d ∣ a β†’ d ∣ b β†’ Β¬ prime d) : count p (a * b).factors = count p a.factors ∨ count p (a * b).factors = count p b.factors := begin by_cases ha : a = 0, { simp [ha], }, by_cases hb : b = 0, { simp [hb], }, rw [count_mul ha hb hp], cases count_of_coprime ha hb hab hp with ha0 hb0, { apply or.intro_right, rw [ha0, zero_add] }, { apply or.intro_left, rw [hb0, add_zero] } end theorem dvd_count_of_dvd_count_mul {a b : associates Ξ±} (hb : b β‰  0) {p : associates Ξ±} (hp : irreducible p) (hab : βˆ€ d, d ∣ a β†’ d ∣ b β†’ Β¬ prime d) {k : β„•} (habk : k ∣ count p (a * b).factors) : k ∣ count p a.factors := begin by_cases ha : a = 0, { simpa [*] using habk, }, cases count_of_coprime ha hb hab hp with hz h, { rw hz, exact dvd_zero k }, { rw [count_mul ha hb hp, h] at habk, exact habk } end omit dec_irr @[simp] lemma factors_one [nontrivial Ξ±] : factors (1 : associates Ξ±) = 0 := begin apply eq_of_prod_eq_prod, rw associates.factors_prod, exact multiset.prod_zero, end @[simp] theorem pow_factors [nontrivial Ξ±] {a : associates Ξ±} {k : β„•} : (a ^ k).factors = k β€’ a.factors := begin induction k with n h, { rw [zero_nsmul, pow_zero], exact factors_one }, { rw [pow_succ, succ_nsmul, factors_mul, h] } end include dec_irr lemma count_pow [nontrivial Ξ±] {a : associates Ξ±} (ha : a β‰  0) {p : associates Ξ±} (hp : irreducible p) (k : β„•) : count p (a ^ k).factors = k * count p a.factors := begin induction k with n h, { rw [pow_zero, factors_one, zero_mul, count_zero hp] }, { rw [pow_succ, count_mul ha (pow_ne_zero _ ha) hp, h, nat.succ_eq_add_one], ring } end theorem dvd_count_pow [nontrivial Ξ±] {a : associates Ξ±} (ha : a β‰  0) {p : associates Ξ±} (hp : irreducible p) (k : β„•) : k ∣ count p (a ^ k).factors := by { rw count_pow ha hp, apply dvd_mul_right } theorem is_pow_of_dvd_count [nontrivial Ξ±] {a : associates Ξ±} (ha : a β‰  0) {k : β„•} (hk : βˆ€ (p : associates Ξ±) (hp : irreducible p), k ∣ count p a.factors) : βˆƒ (b : associates Ξ±), a = b ^ k := begin obtain ⟨a0, hz, rfl⟩ := exists_non_zero_rep ha, rw [factors_mk a0 hz] at hk, have hk' : βˆ€ p, p ∈ (factors' a0) β†’ k ∣ (factors' a0).count p, { rintros p -, have pp : p = ⟨p.val, p.2⟩, { simp only [subtype.coe_eta, subtype.val_eq_coe] }, rw [pp, ← count_some p.2], exact hk p.val p.2 }, obtain ⟨u, hu⟩ := multiset.exists_smul_of_dvd_count _ hk', use (u : factor_set Ξ±).prod, apply eq_of_factors_eq_factors, rw [pow_factors, prod_factors, factors_mk a0 hz, ← with_top.some_eq_coe, hu], exact with_bot.coe_nsmul u k end /-- The only divisors of prime powers are prime powers. See `eq_pow_find_of_dvd_irreducible_pow` for an explicit expression as a p-power (without using `count`). -/ theorem eq_pow_count_factors_of_dvd_pow {p a : associates Ξ±} (hp : irreducible p) {n : β„•} (h : a ∣ p ^ n) : a = p ^ p.count a.factors := begin nontriviality Ξ±, have hph := pow_ne_zero n hp.ne_zero, have ha := ne_zero_of_dvd_ne_zero hph h, apply eq_of_eq_counts ha (pow_ne_zero _ hp.ne_zero), have eq_zero_of_ne : βˆ€ (q : associates Ξ±), irreducible q β†’ q β‰  p β†’ _ = 0 := Ξ» q hq h', nat.eq_zero_of_le_zero $ by { convert count_le_count_of_le hph hq h, symmetry, rw [count_pow hp.ne_zero hq, count_eq_zero_of_ne hq hp h', mul_zero] }, intros q hq, rw count_pow hp.ne_zero hq, by_cases h : q = p, { rw [h, count_self hp, mul_one] }, { rw [count_eq_zero_of_ne hq hp h, mul_zero, eq_zero_of_ne q hq h] } end lemma count_factors_eq_find_of_dvd_pow {a p : associates Ξ±} (hp : irreducible p) [βˆ€ n : β„•, decidable (a ∣ p ^ n)] {n : β„•} (h : a ∣ p ^ n) : nat.find ⟨n, h⟩ = p.count a.factors := begin apply le_antisymm, { refine nat.find_le ⟨1, _⟩, rw mul_one, symmetry, exact eq_pow_count_factors_of_dvd_pow hp h }, { have hph := pow_ne_zero (nat.find ⟨n, h⟩) hp.ne_zero, casesI (subsingleton_or_nontrivial Ξ±) with hΞ± hΞ±, { simpa using hph, }, convert count_le_count_of_le hph hp (nat.find_spec ⟨n, h⟩), rw [count_pow hp.ne_zero hp, count_self hp, mul_one] } end omit dec omit dec_irr omit dec' theorem eq_pow_of_mul_eq_pow [nontrivial Ξ±] {a b c : associates Ξ±} (ha : a β‰  0) (hb : b β‰  0) (hab : βˆ€ d, d ∣ a β†’ d ∣ b β†’ Β¬ prime d) {k : β„•} (h : a * b = c ^ k) : βˆƒ (d : associates Ξ±), a = d ^ k := begin classical, by_cases hk0 : k = 0, { use 1, rw [hk0, pow_zero] at h ⊒, apply (mul_eq_one_iff.1 h).1 }, { refine is_pow_of_dvd_count ha _, intros p hp, apply dvd_count_of_dvd_count_mul hb hp hab, rw h, apply dvd_count_pow _ hp, rintros rfl, rw zero_pow' _ hk0 at h, cases mul_eq_zero.mp h; contradiction } end /-- The only divisors of prime powers are prime powers. -/ theorem eq_pow_find_of_dvd_irreducible_pow {a p : associates Ξ±} (hp : irreducible p) [βˆ€ n : β„•, decidable (a ∣ p ^ n)] {n : β„•} (h : a ∣ p ^ n) : a = p ^ nat.find ⟨n, h⟩ := by { classical, rw [count_factors_eq_find_of_dvd_pow hp, ← eq_pow_count_factors_of_dvd_pow hp h] } end associates section open associates unique_factorization_monoid lemma associates.quot_out {Ξ± : Type*} [comm_monoid Ξ±] (a : associates Ξ±): associates.mk (quot.out (a)) = a := by rw [←quot_mk_eq_mk, quot.out_eq] /-- `to_gcd_monoid` constructs a GCD monoid out of a unique factorization domain. -/ noncomputable def unique_factorization_monoid.to_gcd_monoid (Ξ± : Type*) [cancel_comm_monoid_with_zero Ξ±] [unique_factorization_monoid Ξ±] [decidable_eq (associates Ξ±)] [decidable_eq Ξ±] : gcd_monoid Ξ± := { gcd := Ξ»a b, quot.out (associates.mk a βŠ“ associates.mk b : associates Ξ±), lcm := Ξ»a b, quot.out (associates.mk a βŠ” associates.mk b : associates Ξ±), gcd_dvd_left := Ξ» a b, by { rw [←mk_dvd_mk, (associates.mk a βŠ“ associates.mk b).quot_out, dvd_eq_le], exact inf_le_left }, gcd_dvd_right := Ξ» a b, by { rw [←mk_dvd_mk, (associates.mk a βŠ“ associates.mk b).quot_out, dvd_eq_le], exact inf_le_right }, dvd_gcd := Ξ» a b c hac hab, by { rw [←mk_dvd_mk, (associates.mk c βŠ“ associates.mk b).quot_out, dvd_eq_le, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff], exact ⟨hac, hab⟩ }, lcm_zero_left := Ξ» a, by { have : associates.mk (0 : Ξ±) = ⊀ := rfl, rw [this, top_sup_eq, ←this, ←associated_zero_iff_eq_zero, ←mk_eq_mk_iff_associated, ←associated_iff_eq, associates.quot_out] }, lcm_zero_right := Ξ» a, by { have : associates.mk (0 : Ξ±) = ⊀ := rfl, rw [this, sup_top_eq, ←this, ←associated_zero_iff_eq_zero, ←mk_eq_mk_iff_associated, ←associated_iff_eq, associates.quot_out] }, gcd_mul_lcm := Ξ» a b, by { rw [←mk_eq_mk_iff_associated, ←associates.mk_mul_mk, ←associated_iff_eq, associates.quot_out, associates.quot_out, mul_comm, sup_mul_inf, associates.mk_mul_mk] } } /-- `to_normalized_gcd_monoid` constructs a GCD monoid out of a normalization on a unique factorization domain. -/ noncomputable def unique_factorization_monoid.to_normalized_gcd_monoid (Ξ± : Type*) [cancel_comm_monoid_with_zero Ξ±] [unique_factorization_monoid Ξ±] [normalization_monoid Ξ±] [decidable_eq (associates Ξ±)] [decidable_eq Ξ±] : normalized_gcd_monoid Ξ± := { gcd := Ξ»a b, (associates.mk a βŠ“ associates.mk b).out, lcm := Ξ»a b, (associates.mk a βŠ” associates.mk b).out, gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a βŠ“ associates.mk b)).2 $ inf_le_left, gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a βŠ“ associates.mk b)).2 $ inf_le_right, dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c βŠ“ associates.mk b).out, by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩, lcm_zero_left := assume a, show (⊀ βŠ” associates.mk a).out = 0, by simp, lcm_zero_right := assume a, show (associates.mk a βŠ” ⊀).out = 0, by simp, gcd_mul_lcm := assume a b, by { rw [← out_mul, mul_comm, sup_mul_inf, mk_mul_mk, out_mk], exact normalize_associated (a * b) }, normalize_gcd := assume a b, by convert normalize_out _, normalize_lcm := assume a b, by convert normalize_out _, .. β€Ήnormalization_monoid Ξ±β€Ί } end namespace unique_factorization_monoid /-- If `y` is a nonzero element of a unique factorization monoid with finitely many units (e.g. `β„€`, `ideal (ring_of_integers K)`), it has finitely many divisors. -/ noncomputable def fintype_subtype_dvd {M : Type*} [cancel_comm_monoid_with_zero M] [unique_factorization_monoid M] [fintype MΛ£] (y : M) (hy : y β‰  0) : fintype {x // x ∣ y} := begin haveI : nontrivial M := ⟨⟨y, 0, hy⟩⟩, haveI : normalization_monoid M := unique_factorization_monoid.normalization_monoid, haveI := classical.dec_eq M, haveI := classical.dec_eq (associates M), -- We'll show `Ξ» (u : MΛ£) (f βŠ† factors y) β†’ u * Ξ  f` is injective -- and has image exactly the divisors of `y`. refine fintype.of_finset (((normalized_factors y).powerset.to_finset.product (finset.univ : finset MΛ£)).image (Ξ» s, (s.snd : M) * s.fst.prod)) (Ξ» x, _), simp only [exists_prop, finset.mem_image, finset.mem_product, finset.mem_univ, and_true, multiset.mem_to_finset, multiset.mem_powerset, exists_eq_right, multiset.mem_map], split, { rintros ⟨s, hs, rfl⟩, have prod_s_ne : s.fst.prod β‰  0, { intro hz, apply hy (eq_zero_of_zero_dvd _), have hz := (@multiset.prod_eq_zero_iff M _ _ _ s.fst).mp hz, rw ← (normalized_factors_prod hy).dvd_iff_dvd_right, exact multiset.dvd_prod (multiset.mem_of_le hs hz) }, show (s.snd : M) * s.fst.prod ∣ y, rw [(unit_associated_one.mul_right s.fst.prod).dvd_iff_dvd_left, one_mul, ← (normalized_factors_prod hy).dvd_iff_dvd_right], exact multiset.prod_dvd_prod_of_le hs }, { rintro (h : x ∣ y), have hx : x β‰  0, { refine mt (Ξ» hx, _) hy, rwa [hx, zero_dvd_iff] at h }, obtain ⟨u, hu⟩ := normalized_factors_prod hx, refine ⟨⟨normalized_factors x, u⟩, _, (mul_comm _ _).trans hu⟩, exact (dvd_iff_normalized_factors_le_normalized_factors hx hy).mp h } end end unique_factorization_monoid section finsupp variables [cancel_comm_monoid_with_zero Ξ±] [unique_factorization_monoid Ξ±] variables [normalization_monoid Ξ±] [decidable_eq Ξ±] open unique_factorization_monoid /-- This returns the multiset of irreducible factors as a `finsupp` -/ noncomputable def factorization (n : Ξ±) : Ξ± β†’β‚€ β„• := (normalized_factors n).to_finsupp lemma factorization_eq_count {n p : Ξ±} : factorization n p = multiset.count p (normalized_factors n) := by simp [factorization] @[simp] lemma factorization_zero : factorization (0 : Ξ±) = 0 := by simp [factorization] @[simp] lemma factorization_one : factorization (1 : Ξ±) = 0 := by simp [factorization] /-- The support of `factorization n` is exactly the finset of normalized factors -/ @[simp] lemma support_factorization {n : Ξ±} : (factorization n).support = (normalized_factors n).to_finset := by simp [factorization, multiset.to_finsupp_support] /-- For nonzero `a` and `b`, the power of `p` in `a * b` is the sum of the powers in `a` and `b` -/ @[simp] lemma factorization_mul {a b : Ξ±} (ha : a β‰  0) (hb : b β‰  0) : factorization (a * b) = factorization a + factorization b := by simp [factorization, normalized_factors_mul ha hb] /-- For any `p`, the power of `p` in `x^n` is `n` times the power in `x` -/ lemma factorization_pow {x : Ξ±} {n : β„•} : factorization (x^n) = n β€’ factorization x := by { ext, simp [factorization] } lemma associated_of_factorization_eq (a b: Ξ±) (ha: a β‰  0) (hb: b β‰  0) (h: factorization a = factorization b) : associated a b := begin simp only [factorization, add_equiv.apply_eq_iff_eq] at h, have ha' := normalized_factors_prod ha, rw h at ha', exact associated.trans ha'.symm (normalized_factors_prod hb), end end finsupp
359028f59688248c614c709e487093b7ebc27faa
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/topology/uniform_space/UniformSpace.lean
01b60488d27bce502679337efeb69a23704178eb
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
6,266
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Patrick Massot, Scott Morrison -/ import category_theory.concrete_category import category_theory.full_subcategory import category_theory.monad.limits import topology.uniform_space.completion import topology.Top.basic /-! # The category of uniform spaces We construct the category of uniform spaces, show that the complete separated uniform spaces form a reflective subcategory, and hence possess all limits that uniform spaces do. TODO: show that uniform spaces actually have all limits! -/ universes u open category_theory /-- A (bundled) uniform spaces. -/ @[reducible] def UniformSpace : Type (u+1) := bundled uniform_space namespace UniformSpace instance (x : UniformSpace) : uniform_space x := x.str /-- The category instance on `UniformSpace`. -/ instance concrete_category_uniform_continuous : concrete_category @uniform_continuous := ⟨@uniform_continuous_id, by { introsI, apply uniform_continuous.comp; assumption }⟩ def of (Ξ± : Type u) [uniform_space Ξ±] : UniformSpace := ⟨α⟩ abbreviation forget : UniformSpace.{u} β₯€ Type u := forget instance forget.faithful : faithful (forget) := {} /-- The forgetful functor from uniform spaces to topological spaces. -/ def forget_to_Top : UniformSpace.{u} β₯€ Top.{u} := { obj := Ξ» X, { Ξ± := X.1 }, map := Ξ» X Y f, ⟨ f, uniform_continuous.continuous f.property ⟩ } /-- The natural isomorphism between forgetting from `UniformSpace` to `Type` via `Top`, and forgetting directly. -/ def forget_to_Type_via_Top : forget_to_Top β‹™ Top.forget β‰… forget := iso.refl _ end UniformSpace /-- A (bundled) complete separated uniform space. -/ structure CpltSepUniformSpace := (Ξ± : Type u) [is_uniform_space : uniform_space Ξ±] [is_complete_space : complete_space Ξ±] [is_separated : separated Ξ±] namespace CpltSepUniformSpace instance : has_coe_to_sort CpltSepUniformSpace := { S := Type u, coe := CpltSepUniformSpace.Ξ± } attribute [instance] is_uniform_space is_complete_space is_separated def to_UniformSpace (X : CpltSepUniformSpace) : UniformSpace := ⟨X⟩ instance (X : CpltSepUniformSpace) : complete_space ((to_UniformSpace X).Ξ±) := CpltSepUniformSpace.is_complete_space X instance (X : CpltSepUniformSpace) : separated ((to_UniformSpace X).Ξ±) := CpltSepUniformSpace.is_separated X /-- The category instance on `CpltSepUniformSpace`. -/ instance CpltSepUniformSpace_category : category CpltSepUniformSpace := induced_category.category to_UniformSpace def of (X : Type u) [uniform_space X] [complete_space X] [separated X] : CpltSepUniformSpace := ⟨X⟩ def forget_to_UniformSpace : CpltSepUniformSpace β₯€ UniformSpace := induced_functor to_UniformSpace /-- The forgetful functor from complete separated uniform spaces to `Type`. -/ def forget : CpltSepUniformSpace β₯€ Type u := { obj := Ξ» R, R, map := Ξ» R S f, f.1 } instance forget_faithful : faithful forget := {} instance forget_to_UniformSpace_full : full forget_to_UniformSpace := induced_category.full _ instance forget_to_UniformSpace_faithful : faithful forget_to_UniformSpace := induced_category.faithful _ /-- The natural isomorphism between forgetting from `CpltSepUniformSpace` to `Type` via `UniformSpace`, and forgetting directly. -/ def forget_to_Type_via_UniformSpace : forget_to_UniformSpace β‹™ UniformSpace.forget β‰… forget := iso.refl _ end CpltSepUniformSpace namespace UniformSpace open uniform_space open CpltSepUniformSpace /-- The functor turning uniform spaces into complete separated uniform spaces. -/ noncomputable def completion_functor : UniformSpace β₯€ CpltSepUniformSpace := { obj := Ξ» X, CpltSepUniformSpace.of (completion X), map := Ξ» X Y f, ⟨completion.map f.1, completion.uniform_continuous_map⟩, map_comp' := Ξ» X Y Z f g, begin cases f, cases g, apply subtype.ext.2, dsimp, rw ←completion.map_comp; assumption end }. /-- The inclusion of any uniform spaces into its completion. -/ def completion_hom (X : UniformSpace) : X ⟢ forget_to_UniformSpace.obj (completion_functor.obj X) := { val := (coe : X β†’ completion X), property := completion.uniform_continuous_coe X } @[simp] lemma completion_hom_val (X : UniformSpace) (x) : (completion_hom X) x = (x : completion X) := rfl /-- The mate of a morphism from a `UniformSpace` to a `CpltSepUniformSpace`. -/ noncomputable def extension_hom {X : UniformSpace} {Y : CpltSepUniformSpace} (f : X ⟢ forget_to_UniformSpace.obj Y) : completion_functor.obj X ⟢ Y := { val := completion.extension f, property := completion.uniform_continuous_extension } @[simp] lemma extension_hom_val {X : UniformSpace} {Y : CpltSepUniformSpace} (f : X ⟢ forget_to_UniformSpace.obj Y) (x) : (extension_hom f) x = completion.extension f x := rfl. @[simp] lemma extension_comp_coe {X : UniformSpace} {Y : CpltSepUniformSpace} (f : to_UniformSpace (CpltSepUniformSpace.of (completion X)) ⟢ to_UniformSpace Y) : extension_hom (completion_hom X ≫ f) = f := by { ext x, exact congr_fun (completion.extension_comp_coe f.property) x } /-- The completion functor is left adjoint to the forgetful functor. -/ noncomputable def adj : completion_functor ⊣ forget_to_UniformSpace := adjunction.mk_of_hom_equiv { hom_equiv := Ξ» X Y, { to_fun := Ξ» f, completion_hom X ≫ f, inv_fun := Ξ» f, extension_hom f, left_inv := Ξ» f, by { dsimp, erw extension_comp_coe }, right_inv := Ξ» f, begin ext1, cases f, change completion.extension f_val _ = f_val x, erw completion.extension_coe, assumption end }, hom_equiv_naturality_left_symm' := Ξ» X X' Y f g, begin ext1, dsimp, erw ←completion.extension_map, refl, exact g.property, exact f.property, end } noncomputable instance : is_right_adjoint forget_to_UniformSpace := ⟨completion_functor, adj⟩ noncomputable instance : reflective forget_to_UniformSpace := {} open category_theory.limits -- TODO Once someone defines `has_limits UniformSpace`, turn this into an instance. noncomputable example [has_limits.{u} UniformSpace.{u}] : has_limits.{u} CpltSepUniformSpace.{u} := has_limits_of_reflective forget_to_UniformSpace end UniformSpace
09ba396ca15bde1196cd7782f7b76f70a4cd68d8
c777c32c8e484e195053731103c5e52af26a25d1
/src/combinatorics/simple_graph/regularity/bound.lean
0142d46464d4b8fc3f5663548aa36db2547add1b
[ "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,115
lean
/- Copyright (c) 2022 YaΓ«l Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies, Bhavik Mehta -/ import algebra.order.chebyshev import analysis.special_functions.pow import order.partition.equipartition /-! # Numerical bounds for SzemerΓ©di Regularity Lemma This file gathers the numerical facts required by the proof of SzemerΓ©di's regularity lemma. This entire file is internal to the proof of SzemerΓ©di Regularity Lemma. ## Main declarations * `szemeredi_regularity.step_bound`: During the inductive step, a partition of size `n` is blown to size at most `step_bound n`. * `szemeredi_regularity.initial_bound`: The size of the partition we start the induction with. * `szemeredi_regularity.bound`: The upper bound on the size of the partition produced by our version of SzemerΓ©di's regularity lemma. -/ open finset fintype function real open_locale big_operators namespace szemeredi_regularity /-- Auxiliary function for SzemerΓ©di's regularity lemma. Blowing up a partition of size `n` during the induction results in a partition of size at most `step_bound n`. -/ def step_bound (n : β„•) : β„• := n * 4 ^ n lemma le_step_bound : id ≀ step_bound := Ξ» n, nat.le_mul_of_pos_right $ pow_pos (by norm_num) n lemma step_bound_mono : monotone step_bound := Ξ» a b h, nat.mul_le_mul h $ nat.pow_le_pow_of_le_right (by norm_num) h lemma step_bound_pos_iff {n : β„•} : 0 < step_bound n ↔ 0 < n := zero_lt_mul_right $ by positivity alias step_bound_pos_iff ↔ _ step_bound_pos end szemeredi_regularity open szemeredi_regularity variables {Ξ± : Type*} [decidable_eq Ξ±] [fintype Ξ±] {P : finpartition (univ : finset Ξ±)} {u : finset Ξ±} {Ξ΅ : ℝ} local notation `m` := (card Ξ±/step_bound P.parts.card : β„•) local notation `a` := (card Ξ±/P.parts.card - m * 4^P.parts.card : β„•) namespace tactic open positivity private lemma eps_pos {Ξ΅ : ℝ} {n : β„•} (h : 100 ≀ 4 ^ n * Ξ΅^5) : 0 < Ξ΅ := pow_bit1_pos_iff.1 $ pos_of_mul_pos_right (h.trans_lt' $ by norm_num) $ by positivity private lemma m_pos [nonempty Ξ±] (hPΞ± : P.parts.card * 16^P.parts.card ≀ card Ξ±) : 0 < m := nat.div_pos ((nat.mul_le_mul_left _ $ nat.pow_le_pow_of_le_left (by norm_num) _).trans hPΞ±) $ step_bound_pos (P.parts_nonempty $ univ_nonempty.ne_empty).card_pos /-- Local extension for the `positivity` tactic: A few facts that are needed many times for the proof of SzemerΓ©di's regularity lemma. -/ meta def positivity_szemeredi_regularity : expr β†’ tactic strictness | `(%%n / step_bound (finpartition.parts %%P).card) := do p ← to_expr ``((finpartition.parts %%P).card * 16^(finpartition.parts %%P).card ≀ %%n) >>= find_assumption, positive <$> mk_app ``m_pos [p] | Ξ΅ := do typ ← infer_type Ξ΅, unify typ `(ℝ), p ← to_expr ``(100 ≀ 4 ^ _ * %%Ξ΅ ^ 5) >>= find_assumption, positive <$> mk_app ``eps_pos [p] end tactic local attribute [positivity] tactic.positivity_szemeredi_regularity namespace szemeredi_regularity lemma m_pos [nonempty Ξ±] (hPΞ± : P.parts.card * 16^P.parts.card ≀ card Ξ±) : 0 < m := by positivity lemma coe_m_add_one_pos : 0 < (m : ℝ) + 1 := by positivity lemma one_le_m_coe [nonempty Ξ±] (hPΞ± : P.parts.card * 16^P.parts.card ≀ card Ξ±) : (1 : ℝ) ≀ m := nat.one_le_cast.2 $ m_pos hPΞ± lemma eps_pow_five_pos (hPΞ΅ : 100 ≀ 4^P.parts.card * Ξ΅^5) : 0 < Ξ΅^5 := pos_of_mul_pos_right ((by norm_num : (0 : ℝ) < 100).trans_le hPΞ΅) $ pow_nonneg (by norm_num) _ lemma eps_pos (hPΞ΅ : 100 ≀ 4^P.parts.card * Ξ΅^5) : 0 < Ξ΅ := pow_bit1_pos_iff.1 $ eps_pow_five_pos hPΞ΅ lemma hundred_div_Ξ΅_pow_five_le_m [nonempty Ξ±] (hPΞ± : P.parts.card * 16^P.parts.card ≀ card Ξ±) (hPΞ΅ : 100 ≀ 4^P.parts.card * Ξ΅^5) : 100 / Ξ΅^5 ≀ m := (div_le_of_nonneg_of_le_mul (eps_pow_five_pos hPΞ΅).le (by positivity) hPΞ΅).trans begin norm_cast, rwa [nat.le_div_iff_mul_le'(step_bound_pos (P.parts_nonempty $ univ_nonempty.ne_empty).card_pos), step_bound, mul_left_comm, ←mul_pow], end lemma hundred_le_m [nonempty Ξ±] (hPΞ± : P.parts.card * 16^P.parts.card ≀ card Ξ±) (hPΞ΅ : 100 ≀ 4^P.parts.card * Ξ΅^5) (hΞ΅ : Ξ΅ ≀ 1) : 100 ≀ m := by exact_mod_cast (hundred_div_Ξ΅_pow_five_le_m hPΞ± hPΞ΅).trans' (le_div_self (by norm_num) (by positivity) $ pow_le_one _ (by positivity) hΞ΅) lemma a_add_one_le_four_pow_parts_card : a + 1 ≀ 4^P.parts.card := begin have h : 1 ≀ 4^P.parts.card := one_le_pow_of_one_le (by norm_num) _, rw [step_bound, ←nat.div_div_eq_div_mul, ←nat.le_sub_iff_right h, tsub_le_iff_left, ←nat.add_sub_assoc h], exact nat.le_pred_of_lt (nat.lt_div_mul_add h), end lemma card_aux₁ (hucard : u.card = m * 4^P.parts.card + a) : (4^P.parts.card - a) * m + a * (m + 1) = u.card := by rw [hucard, mul_add, mul_one, ←add_assoc, ←add_mul, nat.sub_add_cancel ((nat.le_succ _).trans a_add_one_le_four_pow_parts_card), mul_comm] lemma card_auxβ‚‚ (hP : P.is_equipartition) (hu : u ∈ P.parts) (hucard : Β¬u.card = m * 4^P.parts.card + a) : (4^P.parts.card - (a + 1)) * m + (a + 1) * (m + 1) = u.card := begin have : m * 4 ^ P.parts.card ≀ card Ξ± / P.parts.card, { rw [step_bound, ←nat.div_div_eq_div_mul], exact nat.div_mul_le_self _ _ }, rw nat.add_sub_of_le this at hucard, rw [(hP.card_parts_eq_average hu).resolve_left hucard, mul_add, mul_one, ←add_assoc, ←add_mul, nat.sub_add_cancel a_add_one_le_four_pow_parts_card, ←add_assoc, mul_comm, nat.add_sub_of_le this, card_univ], end lemma pow_mul_m_le_card_part (hP : P.is_equipartition) (hu : u ∈ P.parts) : (4 : ℝ) ^ P.parts.card * m ≀ u.card := begin norm_cast, rw [step_bound, ←nat.div_div_eq_div_mul], exact (nat.mul_div_le _ _).trans (hP.average_le_card_part hu), end variables (P Ξ΅) (l : β„•) /-- Auxiliary function for SzemerΓ©di's regularity lemma. The size of the partition by which we start blowing. -/ noncomputable def initial_bound : β„• := max 7 $ max l $ ⌊log (100 / Ξ΅^5) / log 4βŒ‹β‚Š + 1 lemma le_initial_bound : l ≀ initial_bound Ξ΅ l := (le_max_left _ _).trans $ le_max_right _ _ lemma seven_le_initial_bound : 7 ≀ initial_bound Ξ΅ l := le_max_left _ _ lemma initial_bound_pos : 0 < initial_bound Ξ΅ l := nat.succ_pos'.trans_le $ seven_le_initial_bound _ _ lemma hundred_lt_pow_initial_bound_mul {Ξ΅ : ℝ} (hΞ΅ : 0 < Ξ΅) (l : β„•) : 100 < 4^initial_bound Ξ΅ l * Ξ΅^5 := begin rw [←rpow_nat_cast 4, ←div_lt_iff (pow_pos hΞ΅ 5), lt_rpow_iff_log_lt _ zero_lt_four, ←div_lt_iff, initial_bound, nat.cast_max, nat.cast_max], { push_cast, exact lt_max_of_lt_right (lt_max_of_lt_right $ nat.lt_floor_add_one _) }, { exact log_pos (by norm_num) }, { exact div_pos (by norm_num) (pow_pos hΞ΅ 5) } end /-- An explicit bound on the size of the equipartition whose existence is given by SzemerΓ©di's regularity lemma. -/ noncomputable def bound : β„• := (step_bound^[⌊4 / Ξ΅^5βŒ‹β‚Š] $ initial_bound Ξ΅ l) * 16 ^ (step_bound^[⌊4 / Ξ΅^5βŒ‹β‚Š] $ initial_bound Ξ΅ l) lemma initial_bound_le_bound : initial_bound Ξ΅ l ≀ bound Ξ΅ l := (id_le_iterate_of_id_le le_step_bound _ _).trans $ nat.le_mul_of_pos_right $ by positivity lemma le_bound : l ≀ bound Ξ΅ l := (le_initial_bound Ξ΅ l).trans $ initial_bound_le_bound Ξ΅ l lemma bound_pos : 0 < bound Ξ΅ l := (initial_bound_pos Ξ΅ l).trans_le $ initial_bound_le_bound Ξ΅ l variables {ΞΉ π•œ : Type*} [linear_ordered_field π•œ] (r : ΞΉ β†’ ΞΉ β†’ Prop) [decidable_rel r] {s t : finset ΞΉ} {x : π•œ} lemma mul_sq_le_sum_sq (hst : s βŠ† t) (f : ΞΉ β†’ π•œ) (hs : x^2 ≀ ((βˆ‘ i in s, f i) / s.card) ^ 2) (hs' : (s.card : π•œ) β‰  0) : (s.card : π•œ) * x ^ 2 ≀ βˆ‘ i in t, f i ^ 2 := (mul_le_mul_of_nonneg_left (hs.trans sum_div_card_sq_le_sum_sq_div_card) $ nat.cast_nonneg _).trans $ (mul_div_cancel' _ hs').le.trans $ sum_le_sum_of_subset_of_nonneg hst $ Ξ» i _ _, sq_nonneg _ lemma add_div_le_sum_sq_div_card (hst : s βŠ† t) (f : ΞΉ β†’ π•œ) (d : π•œ) (hx : 0 ≀ x) (hs : x ≀ |(βˆ‘ i in s, f i)/s.card - (βˆ‘ i in t, f i)/t.card|) (ht : d ≀ ((βˆ‘ i in t, f i)/t.card)^2) : d + s.card/t.card * x^2 ≀ (βˆ‘ i in t, f i^2)/t.card := begin obtain hscard | hscard := (s.card.cast_nonneg : (0 : π•œ) ≀ s.card).eq_or_lt, { simpa [←hscard] using ht.trans sum_div_card_sq_le_sum_sq_div_card }, have htcard : (0:π•œ) < t.card := hscard.trans_le (nat.cast_le.2 (card_le_of_subset hst)), have h₁ : x^2 ≀ ((βˆ‘ i in s, f i)/s.card - (βˆ‘ i in t, f i)/t.card)^2 := sq_le_sq.2 (by rwa [abs_of_nonneg hx]), have hβ‚‚ : x^2 ≀ ((βˆ‘ i in s, (f i - (βˆ‘ j in t, f j)/t.card))/s.card)^2, { apply h₁.trans, rw [sum_sub_distrib, sum_const, nsmul_eq_mul, sub_div, mul_div_cancel_left _ hscard.ne'] }, apply (add_le_add_right ht _).trans, rw [←mul_div_right_comm, le_div_iff htcard, add_mul, div_mul_cancel _ htcard.ne'], have h₃ := mul_sq_le_sum_sq hst (Ξ» i, f i - (βˆ‘ j in t, f j) / t.card) hβ‚‚ hscard.ne', apply (add_le_add_left h₃ _).trans, simp [←mul_div_right_comm _ (t.card : π•œ), sub_div' _ _ _ htcard.ne', ←sum_div, ←add_div, mul_pow, div_le_iff (sq_pos_of_ne_zero _ htcard.ne'), sub_sq, sum_add_distrib, ←sum_mul, ←mul_sum], ring_nf, end end szemeredi_regularity namespace tactic open positivity szemeredi_regularity /-- Extension for the `positivity` tactic: `szemeredi_regularity.initial_bound` and `szemeredi_regularity.bound` are always positive. -/ @[positivity] meta def positivity_szemeredi_regularity_bound : expr β†’ tactic strictness | `(szemeredi_regularity.initial_bound %%Ξ΅ %%l) := positive <$> mk_app ``initial_bound_pos [Ξ΅, l] | `(szemeredi_regularity.bound %%Ξ΅ %%l) := positive <$> mk_app ``bound_pos [Ξ΅, l] | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `szemeredi_regularity.initial_bound Ξ΅ l` nor `szemeredi_regularity.bound Ξ΅ l`" example (Ξ΅ : ℝ) (l : β„•) : 0 < szemeredi_regularity.initial_bound Ξ΅ l := by positivity example (Ξ΅ : ℝ) (l : β„•) : 0 < szemeredi_regularity.bound Ξ΅ l := by positivity end tactic
351daed1fd5eeb617d636a695a104699d16a2c6d
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Server/Snapshots.lean
1f8310f7c3c13e3b23e297511a30f06930a4ba5a
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,397
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Init.System.IO import Lean.Elab.Import import Lean.Elab.Command /-! One can think of this module as being a partial reimplementation of Lean.Elab.Frontend which also stores a snapshot of the world after each command. Importantly, we allow (re)starting compilation from any snapshot/position in the file for interactive editing purposes. -/ namespace Lean namespace Server namespace Snapshots open Elab /-- The data associated with a snapshot is different depending on whether it was produced from the header or from a command. -/ inductive SnapshotData | headerData : Environment β†’ MessageLog β†’ Options β†’ SnapshotData | cmdData : Command.State β†’ SnapshotData /-- What Lean knows about the world after the header and each command. -/ structure Snapshot := /- Where the command which produced this snapshot begins. Note that neighbouring snapshots are *not* necessarily attached beginning-to-end, since inputs outside the grammar advance the parser but do not produce snapshots. -/ (beginPos : String.Pos) (mpState : Parser.ModuleParserState) (data : SnapshotData) namespace Snapshot def endPos (s : Snapshot) : String.Pos := s.mpState.pos def env : Snapshot β†’ Environment | ⟨_, _, SnapshotData.headerData env_ _ _⟩ => env_ | ⟨_, _, SnapshotData.cmdData cmdState⟩ => cmdState.env def msgLog : Snapshot β†’ MessageLog | ⟨_, _, SnapshotData.headerData _ msgLog_ _⟩ => msgLog_ | ⟨_, _, SnapshotData.cmdData cmdState⟩ => cmdState.messages def toCmdState : Snapshot β†’ Command.State | ⟨_, _, SnapshotData.headerData env msgLog opts⟩ => Command.mkState env msgLog opts | ⟨_, _, SnapshotData.cmdData cmdState⟩ => cmdState end Snapshot -- TODO(WN): fns here should probably take inputCtx and live -- in some SnapshotsM := ReaderT Context (EIO Empty) def compileHeader (contents : String) (opts : Options := {}) : IO Snapshot := do let inputCtx := Parser.mkInputContext contents "<input>" let (headerStx, headerParserState, msgLog) ← Parser.parseHeader inputCtx let (headerEnv, msgLog) ← Elab.processHeader headerStx opts msgLog inputCtx pure { beginPos := 0, mpState := headerParserState, data := SnapshotData.headerData headerEnv msgLog opts } private def ioErrorFromEmpty (ex : Empty) : IO.Error := nomatch ex /-- Compiles the next command occurring after the given snapshot. If there is no next command (file ended), returns messages produced through the file. -/ -- NOTE: This code is really very similar to Elab.Frontend. But generalizing it -- over "store snapshots"/"don't store snapshots" would likely result in confusing -- isServer? conditionals and not be worth it due to how short it is. def compileNextCmd (contents : String) (snap : Snapshot) : IO (Sum Snapshot MessageLog) := do let inputCtx := Parser.mkInputContext contents "<input>"; let (cmdStx, cmdParserState, msgLog) := Parser.parseCommand snap.env inputCtx snap.mpState snap.msgLog; let cmdPos := cmdStx.getHeadInfo.get!.pos.get!; -- TODO(WN): always `some`? if Parser.isEOI cmdStx || Parser.isExitCommand cmdStx then pure $ Sum.inr msgLog else let cmdStateRef ← IO.mkRef { snap.toCmdState with messages := msgLog } let cmdCtx : Elab.Command.Context := { cmdPos := snap.endPos, fileName := inputCtx.fileName, fileMap := inputCtx.fileMap } EIO.toIO ioErrorFromEmpty $ Elab.Command.catchExceptions (Elab.Command.elabCommand cmdStx) cmdCtx cmdStateRef let postCmdState ← cmdStateRef.get let postCmdSnap : Snapshot := { beginPos := cmdPos, mpState := cmdParserState, data := SnapshotData.cmdData postCmdState } pure $ Sum.inl postCmdSnap /-- Compiles all commands after the given snapshot. Returns them as a list, together with the final message log. -/ partial def compileCmdsAfter (contents : String) (snap : Snapshot) : IO (List Snapshot Γ— MessageLog) := do let cmdOut ← compileNextCmd contents snap match cmdOut with | Sum.inl snap => do let (snaps, msgLog) ← compileCmdsAfter contents snap pure $ (snap :: snaps, msgLog) | Sum.inr msgLog => pure ([], msgLog) end Snapshots end Server end Lean
53510d9cceb69a2fd6c0179c823a68f47c070d37
a9fe717b93ccfa4b2e64faeb24f96dfefb390240
/nat/reify.lean
fabb86352a3e8301699434363472f789d4d3f75f
[]
no_license
skbaek/omega
ab1f4a6daadfc8c855f14c39d9459ab841527141
715e384ed14e8eb177a326700066e7c98269e078
refs/heads/master
1,588,000,876,352
1,552,645,917,000
1,552,645,917,000
174,442,914
1
0
null
null
null
null
UTF-8
Lean
false
false
1,254
lean
import .form ..tactic open expr tactic namespace nat meta def to_preterm : expr β†’ tactic preterm | (expr.var k) := return (preterm.var 1 k) | `(%%(expr.var k) * %%mx) := do m ← eval_expr nat mx, return (preterm.var m k) | `(%%t1x + %%t2x) := do t1 ← to_preterm t1x, t2 ← to_preterm t2x, return (preterm.add t1 t2) | `(%%t1x - %%t2x) := do t1 ← to_preterm t1x, t2 ← to_preterm t2x, return (preterm.sub t1 t2) | mx := do m ← eval_expr nat mx, return (preterm.cst m) meta def to_form_core : expr β†’ tactic form | `(%%tx1 = %%tx2) := do t1 ← to_preterm tx1, t2 ← to_preterm tx2, return (t1 =* t2) | `(%%tx1 ≀ %%tx2) := do t1 ← to_preterm tx1, t2 ← to_preterm tx2, return (t1 ≀* t2) | `(Β¬ %%px) := do p ← to_form_core px, return (Β¬* p) | `(%%px ∨ %%qx) := do p ← to_form_core px, q ← to_form_core qx, return (p ∨* q) | `(%%px ∧ %%qx) := do p ← to_form_core px, q ← to_form_core qx, return (p ∧* q) | `(_ β†’ %%px) := to_form_core px | _ := failed meta def to_form : nat β†’ expr β†’ tactic (form Γ— nat) | m `(_ β†’ %%px) := to_form (m+1) px | m x := do p ← to_form_core x, return (p,m) end nat
5378c3a6ed485d5eb4a16fb1556379d6826f55d9
fe2016bd13274f6bcbed6792696f5f4520ac9c4b
/src/training2.lean
30ae168a8223be1511530b99fea704361720ebdd
[]
no_license
inkytonik/lean-training
178d6d8d42eca8b6065e85a784bb2997c1bdf6d9
7005c0ba8c8a87bd7ea8322926693dec26ec53ec
refs/heads/main
1,672,144,760,431
1,602,561,261,000
1,602,561,261,000
301,878,072
0
1
null
1,602,561,263,000
1,602,026,587,000
Lean
UTF-8
Lean
false
false
1,954
lean
import tactic set_option pp.generalized_field_notation false open nat namespace training def powerOf2 : β„• β†’ β„• | 0 := 1 | (n+1) := 2 * powerOf2 n lemma lowerBoundPowerOf2 (n : β„•) : 1 ≀ powerOf2 n := begin induction n; simp [powerOf2], linarith, end lemma sumSamePowerOf2 (n : β„•) : powerOf2 n + powerOf2 n == 2 * powerOf2 n := by ring lemma monotonicPowerOf2 : βˆ€ {n m}, n ≀ m β†’ powerOf2 n ≀ powerOf2 m | 0 m le := lowerBoundPowerOf2 m | (n+1) 0 le := by cases le | (n+1) (m+1) le := begin simp [powerOf2], apply monotonicPowerOf2, linarith, end lemma addPowerOf2 (n m : β„•) : powerOf2 n * powerOf2 m = powerOf2 (n + m) := begin induction n; simp [powerOf2], rw [mul_assoc, n_ih, succ_add], simp [powerOf2], end inductive tree : Type | leaf : tree | node : tree β†’ tree β†’ tree namespace tree def height : tree β†’ β„• | leaf := 1 | (node l r) := max (height l) (height r) + 1 def nodeCount : tree β†’ β„• | leaf := 1 | (node l r) := nodeCount l + nodeCount r + 1 def leafCount : tree β†’ β„• | leaf := 1 | (node l r) := leafCount l + leafCount r -- Move - 1 to LHS to avoid nat subtraction lemma upperboundForNodeCount (root : tree) : nodeCount root + 1 ≀ powerOf2 (height root) := begin induction root with l r ih_l ih_r; simp [height, nodeCount, powerOf2], set hl := height l, set hr := height r, calc nodeCount (node l r) + 1 = nodeCount l + nodeCount r + 1 + 1 : rfl ... ≀ powerOf2 hl + powerOf2 hr : by linarith ... ≀ powerOf2 (max hl hr) + powerOf2 (max hl hr) : by linarith [ monotonicPowerOf2 (le_max_left hl hr) , monotonicPowerOf2 (le_max_right hl hr) ] ... = 2 * powerOf2 (max hl hr) : by ring ... = powerOf2 (max hl hr + 1) : rfl ... = powerOf2 (height (node l r)) : rfl end end tree end training
44a16dc5065e9fd62d41967a9c9eafbce79cacb1
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/MonadEnv.lean
e0ae9545cb70b541d4f5c19a9d932648fe82559f
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,324
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.Environment import Lean.Exception namespace Lean def setEnv [MonadEnv m] (env : Environment) : m Unit := modifyEnv fun _ => env def isInductive [Monad m] [MonadEnv m] (declName : Name) : m Bool := do match (← getEnv).find? declName with | some (ConstantInfo.inductInfo ..) => return true | _ => return false def isRec [Monad m] [MonadEnv m] (declName : Name) : m Bool := do match (← getEnv).find? declName with | some (ConstantInfo.recInfo ..) => return true | _ => return false @[inline] def withoutModifyingEnv [Monad m] [MonadEnv m] [MonadFinally m] {Ξ± : Type} (x : m Ξ±) : m Ξ± := do let env ← getEnv try x finally setEnv env @[inline] def matchConst [Monad m] [MonadEnv m] (e : Expr) (failK : Unit β†’ m Ξ±) (k : ConstantInfo β†’ List Level β†’ m Ξ±) : m Ξ± := do match e with | Expr.const constName us _ => do match (← getEnv).find? constName with | some cinfo => k cinfo us | none => failK () | _ => failK () @[inline] def matchConstInduct [Monad m] [MonadEnv m] (e : Expr) (failK : Unit β†’ m Ξ±) (k : InductiveVal β†’ List Level β†’ m Ξ±) : m Ξ± := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.inductInfo val => k val us | _ => failK () @[inline] def matchConstCtor [Monad m] [MonadEnv m] (e : Expr) (failK : Unit β†’ m Ξ±) (k : ConstructorVal β†’ List Level β†’ m Ξ±) : m Ξ± := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.ctorInfo val => k val us | _ => failK () @[inline] def matchConstRec [Monad m] [MonadEnv m] (e : Expr) (failK : Unit β†’ m Ξ±) (k : RecursorVal β†’ List Level β†’ m Ξ±) : m Ξ± := matchConst e failK fun cinfo us => match cinfo with | ConstantInfo.recInfo val => k val us | _ => failK () def hasConst [Monad m] [MonadEnv m] (constName : Name) : m Bool := do return (← getEnv).contains constName private partial def mkAuxNameAux (env : Environment) (base : Name) (i : Nat) : Name := let candidate := base.appendIndexAfter i if env.contains candidate then mkAuxNameAux env base (i+1) else candidate def mkAuxName [Monad m] [MonadEnv m] (baseName : Name) (idx : Nat) : m Name := do return mkAuxNameAux (← getEnv) baseName idx def getConstInfo [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m ConstantInfo := do match (← getEnv).find? constName with | some info => pure info | none => throwError! "unknown constant '{mkConst constName}'" def getConstInfoInduct [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m InductiveVal := do match (← getConstInfo constName) with | ConstantInfo.inductInfo v => pure v | _ => throwError! "'{mkConst constName}' is not a inductive type" def getConstInfoCtor [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m ConstructorVal := do match (← getConstInfo constName) with | ConstantInfo.ctorInfo v => pure v | _ => throwError! "'{mkConst constName}' is not a constructor" def getConstInfoRec [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m RecursorVal := do match (← getConstInfo constName) with | ConstantInfo.recInfo v => pure v | _ => throwError! "'{mkConst constName}' is not a recursor" @[inline] def matchConstStruct [Monad m] [MonadEnv m] [MonadError m] (e : Expr) (failK : Unit β†’ m Ξ±) (k : InductiveVal β†’ List Level β†’ ConstructorVal β†’ m Ξ±) : m Ξ± := matchConstInduct e failK fun ival us => do if ival.isRec then failK () else match ival.ctors with | [ctor] => match (← getConstInfo ctor) with | ConstantInfo.ctorInfo cval => k ival us cval | _ => failK () | _ => failK () def addDecl [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (decl : Declaration) : m Unit := do match (← getEnv).addDecl decl with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex def compileDecl [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (decl : Declaration) : m Unit := do match (← getEnv).compileDecl (← getOptions) decl with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex def addAndCompile [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (decl : Declaration) : m Unit := do addDecl decl; compileDecl decl unsafe def evalConst [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (Ξ±) (constName : Name) : m Ξ± := do ofExcept <| (← getEnv).evalConst Ξ± (← getOptions) constName unsafe def evalConstCheck [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (Ξ±) (typeName : Name) (constName : Name) : m Ξ± := do ofExcept <| (← getEnv).evalConstCheck Ξ± (← getOptions) typeName constName def findModuleOf? [Monad m] [MonadEnv m] [MonadError m] (declName : Name) : m (Option Name) := do discard <| getConstInfo declName -- ensure declaration exists match (← getEnv).getModuleIdxFor? declName with | none => return none | some modIdx => return some ((← getEnv).allImportedModuleNames[modIdx]) end Lean
ab14573865c628712f79e926a59487271ccdccca
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/tactic/linarith.lean
af94c07bab10956d695bfba6e0c68ed6eb4191df
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
32,509
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis A tactic for discharging linear arithmetic goals using Fourier-Motzkin elimination. `linarith` is (in principle) complete for β„š and ℝ. It is not complete for non-dense orders, i.e. β„€. @TODO: investigate storing comparisons in a list instead of a set, for possible efficiency gains @TODO: delay proofs of denominator normalization and nat casting until after contradiction is found -/ import tactic.ring data.nat.gcd data.list.basic meta.rb_map meta def nat.to_pexpr : β„• β†’ pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) open native namespace linarith section lemmas lemma int.coe_nat_bit0 (n : β„•) : (↑(bit0 n : β„•) : β„€) = bit0 (↑n : β„€) := by simp [bit0] lemma int.coe_nat_bit1 (n : β„•) : (↑(bit1 n : β„•) : β„€) = bit1 (↑n : β„€) := by simp [bit1, bit0] lemma int.coe_nat_bit0_mul (n : β„•) (x : β„•) : (↑(bit0 n * x) : β„€) = (↑(bit0 n) : β„€) * (↑x : β„€) := by simp lemma int.coe_nat_bit1_mul (n : β„•) (x : β„•) : (↑(bit1 n * x) : β„€) = (↑(bit1 n) : β„€) * (↑x : β„€) := by simp lemma int.coe_nat_one_mul (x : β„•) : (↑(1 * x) : β„€) = 1 * (↑x : β„€) := by simp lemma int.coe_nat_zero_mul (x : β„•) : (↑(0 * x) : β„€) = 0 * (↑x : β„€) := by simp lemma int.coe_nat_mul_bit0 (n : β„•) (x : β„•) : (↑(x * bit0 n) : β„€) = (↑x : β„€) * (↑(bit0 n) : β„€) := by simp lemma int.coe_nat_mul_bit1 (n : β„•) (x : β„•) : (↑(x * bit1 n) : β„€) = (↑x : β„€) * (↑(bit1 n) : β„€) := by simp lemma int.coe_nat_mul_one (x : β„•) : (↑(x * 1) : β„€) = (↑x : β„€) * 1 := by simp lemma int.coe_nat_mul_zero (x : β„•) : (↑(x * 0) : β„€) = (↑x : β„€) * 0 := by simp lemma nat_eq_subst {n1 n2 : β„•} {z1 z2 : β„€} (hn : n1 = n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 = z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_eq_coe_nat_iff] lemma nat_le_subst {n1 n2 : β„•} {z1 z2 : β„€} (hn : n1 ≀ n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 ≀ z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_le] lemma nat_lt_subst {n1 n2 : β„•} {z1 z2 : β„€} (hn : n1 < n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 < z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_lt] lemma eq_of_eq_of_eq {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (ha : a = 0) (hb : b = 0) : a + b = 0 := by simp * lemma le_of_eq_of_le {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (ha : a = 0) (hb : b ≀ 0) : a + b ≀ 0 := by simp * lemma lt_of_eq_of_lt {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (ha : a = 0) (hb : b < 0) : a + b < 0 := by simp * lemma le_of_le_of_eq {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (ha : a ≀ 0) (hb : b = 0) : a + b ≀ 0 := by simp * lemma lt_of_lt_of_eq {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (ha : a < 0) (hb : b = 0) : a + b < 0 := by simp * lemma mul_neg {Ξ±} [ordered_ring Ξ±] {a b : Ξ±} (ha : a < 0) (hb : b > 0) : b * a < 0 := have (-b)*a > 0, from mul_pos_of_neg_of_neg (neg_neg_of_pos hb) ha, neg_of_neg_pos (by simpa) lemma mul_nonpos {Ξ±} [ordered_ring Ξ±] {a b : Ξ±} (ha : a ≀ 0) (hb : b > 0) : b * a ≀ 0 := have (-b)*a β‰₯ 0, from mul_nonneg_of_nonpos_of_nonpos (le_of_lt (neg_neg_of_pos hb)) ha, nonpos_of_neg_nonneg (by simp at this; exact this) lemma mul_eq {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (ha : a = 0) (hb : b > 0) : b * a = 0 := by simp * lemma eq_of_not_lt_of_not_gt {Ξ±} [linear_order Ξ±] (a b : Ξ±) (h1 : Β¬ a < b) (h2 : Β¬ b < a) : a = b := le_antisymm (le_of_not_gt h2) (le_of_not_gt h1) lemma add_subst {Ξ±} [ring Ξ±] {n e1 e2 t1 t2 : Ξ±} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 + e2) = t1 + t2 := by simp [left_distrib, *] lemma sub_subst {Ξ±} [ring Ξ±] {n e1 e2 t1 t2 : Ξ±} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 - e2) = t1 - t2 := by simp [left_distrib, *] lemma neg_subst {Ξ±} [ring Ξ±] {n e t : Ξ±} (h1 : n * e = t) : n * (-e) = -t := by simp * private meta def apnn : tactic unit := `[norm_num] lemma mul_subst {Ξ±} [comm_ring Ξ±] {n1 n2 k e1 e2 t1 t2 : Ξ±} (h1 : n1 * e1 = t1) (h2 : n2 * e2 = t2) (h3 : n1*n2 = k . apnn) : k * (e1 * e2) = t1 * t2 := have h3 : n1 * n2 = k, from h3, by rw [←h3, mul_comm n1, mul_assoc n2, ←mul_assoc n1, h1, ←mul_assoc n2, mul_comm n2, mul_assoc, h2] -- OUCH lemma div_subst {Ξ±} [field Ξ±] {n1 n2 k e1 e2 t1 : Ξ±} (h1 : n1 * e1 = t1) (h2 : n2 / e2 = 1) (h3 : n1*n2 = k) : k * (e1 / e2) = t1 := by rw [←h3, mul_assoc, mul_div_comm, h2, ←mul_assoc, h1, mul_comm, one_mul] end lemmas section datatypes @[derive decidable_eq] inductive ineq | eq | le | lt open ineq def ineq.max : ineq β†’ ineq β†’ ineq | eq a := a | le a := a | lt a := lt def ineq.is_lt : ineq β†’ ineq β†’ bool | eq le := tt | eq lt := tt | le lt := tt | _ _ := ff def ineq.to_string : ineq β†’ string | eq := "=" | le := "≀" | lt := "<" instance : has_to_string ineq := ⟨ineq.to_string⟩ /-- The main datatype for FM elimination. Variables are represented by natural numbers, each of which has an integer coefficient. Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1. The represented term is coeffs.keys.sum (Ξ» i, coeffs.find i * Var[i]). str determines the direction of the comparison -- is it < 0, ≀ 0, or = 0? -/ meta structure comp := (str : ineq) (coeffs : rb_map β„• int) meta instance : inhabited comp := ⟨⟨ineq.eq, mk_rb_map⟩⟩ meta inductive comp_source | assump : β„• β†’ comp_source | add : comp_source β†’ comp_source β†’ comp_source | scale : β„• β†’ comp_source β†’ comp_source meta def comp_source.flatten : comp_source β†’ rb_map β„• β„• | (comp_source.assump n) := mk_rb_map.insert n 1 | (comp_source.add c1 c2) := (comp_source.flatten c1).add (comp_source.flatten c2) | (comp_source.scale n c) := (comp_source.flatten c).map (Ξ» v, v * n) meta def comp_source.to_string : comp_source β†’ string | (comp_source.assump e) := to_string e | (comp_source.add c1 c2) := comp_source.to_string c1 ++ " + " ++ comp_source.to_string c2 | (comp_source.scale n c) := to_string n ++ " * " ++ comp_source.to_string c meta instance comp_source.has_to_format : has_to_format comp_source := ⟨λ a, comp_source.to_string a⟩ meta structure pcomp := (c : comp) (src : comp_source) meta def map_lt (m1 m2 : rb_map β„• int) : bool := list.lex (prod.lex (<) (<)) m1.to_list m2.to_list -- make more efficient meta def comp.lt (c1 c2 : comp) : bool := (c1.str.is_lt c2.str) || (c1.str = c2.str) && map_lt c1.coeffs c2.coeffs meta instance comp.has_lt : has_lt comp := ⟨λ a b, comp.lt a b⟩ meta instance pcomp.has_lt : has_lt pcomp := ⟨λ p1 p2, p1.c < p2.c⟩ meta instance pcomp.has_lt_dec : decidable_rel ((<) : pcomp β†’ pcomp β†’ Prop) := by apply_instance meta def comp.coeff_of (c : comp) (a : β„•) : β„€ := c.coeffs.zfind a meta def comp.scale (c : comp) (n : β„•) : comp := { c with coeffs := c.coeffs.map ((*) (n : β„€)) } meta def comp.add (c1 c2 : comp) : comp := ⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩ meta def pcomp.scale (c : pcomp) (n : β„•) : pcomp := ⟨c.c.scale n, comp_source.scale n c.src⟩ meta def pcomp.add (c1 c2 : pcomp) : pcomp := ⟨c1.c.add c2.c, comp_source.add c1.src c2.src⟩ meta instance pcomp.to_format : has_to_format pcomp := ⟨λ p, to_fmt p.c.coeffs ++ to_string p.c.str ++ "0"⟩ meta instance comp.to_format : has_to_format comp := ⟨λ p, to_fmt p.coeffs⟩ end datatypes section fm_elim /-- If c1 and c2 both contain variable a with opposite coefficients, produces v1, v2, and c such that a has been cancelled in c := v1*c1 + v2*c2 -/ meta def elim_var (c1 c2 : comp) (a : β„•) : option (β„• Γ— β„• Γ— comp) := let v1 := c1.coeff_of a, v2 := c2.coeff_of a in if v1 * v2 < 0 then let vlcm := nat.lcm v1.nat_abs v2.nat_abs, v1' := vlcm / v1.nat_abs, v2' := vlcm / v2.nat_abs in some ⟨v1', v2', comp.add (c1.scale v1') (c2.scale v2')⟩ else none meta def pelim_var (p1 p2 : pcomp) (a : β„•) : option pcomp := do (n1, n2, c) ← elim_var p1.c p2.c a, return ⟨c, comp_source.add (p1.src.scale n1) (p2.src.scale n2)⟩ meta def comp.is_contr (c : comp) : bool := c.coeffs.empty ∧ c.str = ineq.lt meta def pcomp.is_contr (p : pcomp) : bool := p.c.is_contr meta def elim_with_set (a : β„•) (p : pcomp) (comps : rb_set pcomp) : rb_set pcomp := if Β¬ p.c.coeffs.contains a then mk_rb_set.insert p else comps.fold mk_rb_set $ Ξ» pc s, match pelim_var p pc a with | some pc := s.insert pc | none := s end /-- The state for the elimination monad. vars: the set of variables present in comps comps: a set of comparisons inputs: a set of pairs of exprs (t, pf), where t is a term and pf is a proof that t {<, ≀, =} 0, indexed by β„•. has_false: stores a pcomp of 0 < 0 if one has been found TODO: is it more efficient to store comps as a list, to avoid comparisons? -/ meta structure linarith_structure := (vars : rb_set β„•) (comps : rb_set pcomp) @[reducible] meta def linarith_monad := state_t linarith_structure (except_t pcomp id) meta instance : monad linarith_monad := state_t.monad meta instance : monad_except pcomp linarith_monad := state_t.monad_except pcomp meta def get_vars : linarith_monad (rb_set β„•) := linarith_structure.vars <$> get meta def get_var_list : linarith_monad (list β„•) := rb_set.to_list <$> get_vars meta def get_comps : linarith_monad (rb_set pcomp) := linarith_structure.comps <$> get meta def validate : linarith_monad unit := do ⟨_, comps⟩ ← get, match comps.to_list.find (Ξ» p : pcomp, p.is_contr) with | none := return () | some c := throw c end meta def update (vars : rb_set β„•) (comps : rb_set pcomp) : linarith_monad unit := state_t.put ⟨vars, comps⟩ >> validate meta def monad.elim_var (a : β„•) : linarith_monad unit := do vs ← get_vars, when (vs.contains a) $ do comps ← get_comps, let cs' := comps.fold mk_rb_set (Ξ» p s, s.union (elim_with_set a p comps)), update (vs.erase a) cs' meta def elim_all_vars : linarith_monad unit := get_var_list >>= list.mmap' monad.elim_var end fm_elim section parse open ineq tactic meta def map_of_expr_mul_aux (c1 c2 : rb_map β„• β„€) : option (rb_map β„• β„€) := match c1.keys, c2.keys with | [0], _ := some $ c2.scale (c1.zfind 0) | _, [0] := some $ c1.scale (c2.zfind 0) | _, _ := none end /-- Turns an expression into a map from β„• to β„€, for use in a comp object. The expr_map β„• argument identifies which expressions have already been assigned numbers. Returns a new map. -/ meta def map_of_expr : expr_map β„• β†’ expr β†’ option (expr_map β„• Γ— rb_map β„• β„€) | m e@`(%%e1 * %%e2) := (do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, mp ← map_of_expr_mul_aux comp1 comp2, return (m', mp)) <|> (match m.find e with | some k := return (m, mk_rb_map.insert k 1) | none := let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1) end) | m `(%%e1 + %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add comp2) | m `(%%e1 - %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add (comp2.scale (-1))) | m `(-%%e) := do (m', comp) ← map_of_expr m e, return (m', comp.scale (-1)) | m e := match e.to_int, m.find e with | some 0, _ := return ⟨m, mk_rb_map⟩ | some z, _ := return ⟨m, mk_rb_map.insert 0 z⟩ | none, some k := return (m, mk_rb_map.insert k 1) | none, none := let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1) end meta def parse_into_comp_and_expr : expr β†’ option (ineq Γ— expr) | `(%%e < 0) := (ineq.lt, e) | `(%%e ≀ 0) := (ineq.le, e) | `(%%e = 0) := (ineq.eq, e) | _ := none meta def to_comp (e : expr) (m : expr_map β„•) : option (comp Γ— expr_map β„•) := do (iq, e) ← parse_into_comp_and_expr e, (m', comp') ← map_of_expr m e, return ⟨⟨iq, comp'⟩, m'⟩ meta def to_comp_fold : expr_map β„• β†’ list expr β†’ (list (option comp) Γ— expr_map β„•) | m [] := ([], m) | m (h::t) := match to_comp h m with | some (c, m') := let (l, mp) := to_comp_fold m' t in (c::l, mp) | none := let (l, mp) := to_comp_fold m t in (none::l, mp) end /-- Takes a list of proofs of props of the form t {<, ≀, =} 0, and creates a linarith_structure. -/ meta def mk_linarith_structure (l : list expr) : tactic (linarith_structure Γ— rb_map β„• (expr Γ— expr)) := do pftps ← l.mmap infer_type, let (l', map) := to_comp_fold mk_rb_map pftps, let lz := list.enum $ ((l.zip pftps).zip l').filter_map (Ξ» ⟨a, b⟩, prod.mk a <$> b), let prmap := rb_map.of_list $ lz.map (Ξ» ⟨n, x⟩, (n, x.1)), let vars : rb_set β„• := rb_map.set_of_list $ list.range map.size.succ, let pc : rb_set pcomp := rb_map.set_of_list $ lz.map (Ξ» ⟨n, x⟩, ⟨x.2, comp_source.assump n⟩), return (⟨vars, pc⟩, prmap) meta def linarith_monad.run {Ξ±} (tac : linarith_monad Ξ±) (l : list expr) : tactic ((pcomp βŠ• Ξ±) Γ— rb_map β„• (expr Γ— expr)) := do (struct, inputs) ← mk_linarith_structure l, match (state_t.run (validate >> tac) struct).run with | (except.ok (a, _)) := return (sum.inr a, inputs) | (except.error contr) := return (sum.inl contr, inputs) end end parse section prove open ineq tactic meta def get_rel_sides : expr β†’ tactic (expr Γ— expr) | `(%%a < %%b) := return (a, b) | `(%%a ≀ %%b) := return (a, b) | `(%%a = %%b) := return (a, b) | `(%%a β‰₯ %%b) := return (a, b) | `(%%a > %%b) := return (a, b) | _ := failed meta def mul_expr (n : β„•) (e : expr) : pexpr := if n = 1 then ``(%%e) else ``(%%(nat.to_pexpr n) * %%e) meta def add_exprs_aux : pexpr β†’ list pexpr β†’ pexpr | p [] := p | p [a] := ``(%%p + %%a) | p (h::t) := add_exprs_aux ``(%%p + %%h) t meta def add_exprs : list pexpr β†’ pexpr | [] := ``(0) | (h::t) := add_exprs_aux h t meta def find_contr (m : rb_set pcomp) : option pcomp := m.keys.find (Ξ» p, p.c.is_contr) meta def ineq_const_mul_nm : ineq β†’ name | lt := ``mul_neg | le := ``mul_nonpos | eq := ``mul_eq meta def ineq_const_nm : ineq β†’ ineq β†’ (name Γ— ineq) | eq eq := (``eq_of_eq_of_eq, eq) | eq le := (``le_of_eq_of_le, le) | eq lt := (``lt_of_eq_of_lt, lt) | le eq := (``le_of_le_of_eq, le) | le le := (`add_nonpos, le) | le lt := (`add_neg_of_nonpos_of_neg, lt) | lt eq := (``lt_of_lt_of_eq, lt) | lt le := (`add_neg_of_neg_of_nonpos, lt) | lt lt := (`add_neg, lt) meta def mk_single_comp_zero_pf (c : β„•) (h : expr) : tactic (ineq Γ— expr) := do tp ← infer_type h, some (iq, e) ← return $ parse_into_comp_and_expr tp, if c = 0 then do e' ← mk_app ``zero_mul [e], return (eq, e') else if c = 1 then return (iq, h) else do nm ← resolve_name (ineq_const_mul_nm iq), tp ← (prod.snd <$> (infer_type h >>= get_rel_sides)) >>= infer_type, cpos ← to_expr ``((%%c.to_pexpr : %%tp) > 0), (_, ex) ← solve_aux cpos `[norm_num, done], -- e' ← mk_app (ineq_const_mul_nm iq) [h, ex], -- this takes many seconds longer in some examples! why? e' ← to_expr ``(%%nm %%h %%ex) ff, return (iq, e') meta def mk_lt_zero_pf_aux (c : ineq) (pf npf : expr) (coeff : β„•) : tactic (ineq Γ— expr) := do (iq, h') ← mk_single_comp_zero_pf coeff npf, let (nm, niq) := ineq_const_nm c iq, n ← resolve_name nm, e' ← to_expr ``(%%n %%pf %%h'), return (niq, e') /-- Takes a list of coefficients [c] and list of expressions, of equal length. Each expression is a proof of a prop of the form t {<, ≀, =} 0. Produces a proof that the sum of (c*t) {<, ≀, =} 0, where the comp is as strong as possible. -/ meta def mk_lt_zero_pf : list β„• β†’ list expr β†’ tactic expr | _ [] := fail "no linear hypotheses found" | [c] [h] := prod.snd <$> mk_single_comp_zero_pf c h | (c::ct) (h::t) := do (iq, h') ← mk_single_comp_zero_pf c h, prod.snd <$> (ct.zip t).mfoldl (Ξ» pr ce, mk_lt_zero_pf_aux pr.1 pr.2 ce.2 ce.1) (iq, h') | _ _ := fail "not enough args to mk_lt_zero_pf" meta def term_of_ineq_prf (prf : expr) : tactic expr := do (lhs, _) ← infer_type prf >>= get_rel_sides, return lhs meta structure linarith_config := (discharger : tactic unit := `[ring]) (restrict_type : option Type := none) (restrict_type_reflect : reflected restrict_type . apply_instance) (exfalso : bool := tt) meta def ineq_pf_tp (pf : expr) : tactic expr := do (_, z) ← infer_type pf >>= get_rel_sides, infer_type z meta def mk_neg_one_lt_zero_pf (tp : expr) : tactic expr := to_expr ``((neg_neg_of_pos zero_lt_one : -1 < (0 : %%tp))) /-- Assumes e is a proof that t = 0. Creates a proof that -t = 0. -/ meta def mk_neg_eq_zero_pf (e : expr) : tactic expr := to_expr ``(neg_eq_zero.mpr %%e) meta def add_neg_eq_pfs : list expr β†’ tactic (list expr) | [] := return [] | (h::t) := do some (iq, tp) ← parse_into_comp_and_expr <$> infer_type h, match iq with | ineq.eq := do nep ← mk_neg_eq_zero_pf h, tl ← add_neg_eq_pfs t, return $ h::nep::tl | _ := list.cons h <$> add_neg_eq_pfs t end /-- Takes a list of proofs of propositions of the form t {<, ≀, =} 0, and tries to prove the goal `false`. -/ meta def prove_false_by_linarith1 (cfg : linarith_config) : list expr β†’ tactic unit | [] := fail "no args to linarith" | l@(h::t) := do l' ← add_neg_eq_pfs l, hz ← ineq_pf_tp h >>= mk_neg_one_lt_zero_pf, (sum.inl contr, inputs) ← elim_all_vars.run (hz::l') | fail "linarith failed to find a contradiction", let coeffs := inputs.keys.map (Ξ» k, (contr.src.flatten.ifind k)), let pfs : list expr := inputs.keys.map (Ξ» k, (inputs.ifind k).1), let zip := (coeffs.zip pfs).filter (Ξ» pr, pr.1 β‰  0), let (coeffs, pfs) := zip.unzip, mls ← zip.mmap (Ξ» pr, do e ← term_of_ineq_prf pr.2, return (mul_expr pr.1 e)), sm ← to_expr $ add_exprs mls, tgt ← to_expr ``(%%sm = 0), (a, b) ← solve_aux tgt (cfg.discharger >> done), pf ← mk_lt_zero_pf coeffs pfs, pftp ← infer_type pf, (_, nep, _) ← rewrite_core b pftp, pf' ← mk_eq_mp nep pf, mk_app `lt_irrefl [pf'] >>= exact end prove section normalize open tactic set_option eqn_compiler.max_steps 50000 meta def rem_neg (prf : expr) : expr β†’ tactic expr | `(_ ≀ _) := to_expr ``(lt_of_not_ge %%prf) | `(_ < _) := to_expr ``(le_of_not_gt %%prf) | `(_ > _) := to_expr ``(le_of_not_gt %%prf) | `(_ β‰₯ _) := to_expr ``(lt_of_not_ge %%prf) | e := failed meta def rearr_comp : expr β†’ expr β†’ tactic expr | prf `(%%a ≀ 0) := return prf | prf `(%%a < 0) := return prf | prf `(%%a = 0) := return prf | prf `(%%a β‰₯ 0) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(%%a > 0) := to_expr ``(neg_neg_of_pos %%prf) | prf `(0 β‰₯ %%a) := to_expr ``(show %%a ≀ 0, from %%prf) | prf `(0 > %%a) := to_expr ``(show %%a < 0, from %%prf) | prf `(0 = %%a) := to_expr ``(eq.symm %%prf) | prf `(0 ≀ %%a) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(0 < %%a) := to_expr ``(neg_neg_of_pos %%prf) | prf `(%%a ≀ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(%%a < %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a = %%b) := to_expr ``(sub_eq_zero.mpr %%prf) | prf `(%%a > %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a β‰₯ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(Β¬ %%t) := do nprf ← rem_neg prf t, tp ← infer_type nprf, rearr_comp nprf tp | prf _ := fail "couldn't rearrange comp" meta def is_numeric : expr β†’ option β„š | `(%%e1 + %%e2) := (+) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 - %%e2) := has_sub.sub <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 * %%e2) := (*) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 / %%e2) := (/) <$> is_numeric e1 <*> is_numeric e2 | `(-%%e) := rat.neg <$> is_numeric e | e := e.to_rat inductive {u} tree (Ξ± : Type u) : Type u | nil {} : tree | node : Ξ± β†’ tree β†’ tree β†’ tree def tree.repr {Ξ±} [has_repr Ξ±] : tree Ξ± β†’ string | tree.nil := "nil" | (tree.node a t1 t2) := "tree.node " ++ repr a ++ " (" ++ tree.repr t1 ++ ") (" ++ tree.repr t2 ++ ")" instance {Ξ±} [has_repr Ξ±] : has_repr (tree Ξ±) := ⟨tree.repr⟩ meta def find_cancel_factor : expr β†’ β„• Γ— tree β„• | `(%%e1 + %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 - %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 * %%e2) := match is_numeric e1, is_numeric e2 with | none, none := (1, tree.node 1 tree.nil tree.nil) | _, _ := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, pd := v1*v2 in (pd, tree.node pd t1 t2) end | `(%%e1 / %%e2) := match is_numeric e2 with | some q := let (v1, t1) := find_cancel_factor e1, n := v1.lcm q.num.nat_abs in (n, tree.node n t1 (tree.node q.num.nat_abs tree.nil tree.nil)) | none := (1, tree.node 1 tree.nil tree.nil) end | `(-%%e) := find_cancel_factor e | _ := (1, tree.node 1 tree.nil tree.nil) open tree meta def mk_prod_prf : β„• β†’ tree β„• β†’ expr β†’ tactic expr | v (node _ lhs rhs) `(%%e1 + %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``add_subst [v1, v2] | v (node _ lhs rhs) `(%%e1 - %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``sub_subst [v1, v2] | v (node n lhs@(node ln _ _) rhs) `(%%e1 * %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf ln lhs e1, v2 ← mk_prod_prf (v/ln) rhs e2, ln' ← tp.of_nat ln, vln' ← tp.of_nat (v/ln), v' ← tp.of_nat v, ntp ← to_expr ``(%%ln' * %%vln' = %%v'), (_, npf) ← solve_aux ntp `[norm_num, done], mk_app ``mul_subst [v1, v2, npf] | v (node n lhs rhs@(node rn _ _)) `(%%e1 / %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf (v/rn) lhs e1, rn' ← tp.of_nat rn, vrn' ← tp.of_nat (v/rn), n' ← tp.of_nat n, v' ← tp.of_nat v, ntp ← to_expr ``(%%rn' / %%e2 = 1), (_, npf) ← solve_aux ntp `[norm_num, done], ntp2 ← to_expr ``(%%vrn' * %%n' = %%v'), (_, npf2) ← solve_aux ntp2 `[norm_num, done], mk_app ``div_subst [v1, npf, npf2] | v t `(-%%e) := do v' ← mk_prod_prf v t e, mk_app ``neg_subst [v'] | v _ e := do tp ← infer_type e, v' ← tp.of_nat v, e' ← to_expr ``(%%v' * %%e), mk_app `eq.refl [e'] /-- e is a term with rational division. produces a natural number n and a proof that n*e = e', where e' has no division. -/ meta def kill_factors (e : expr) : tactic (β„• Γ— expr) := let (n, t) := find_cancel_factor e in do e' ← mk_prod_prf n t e, return (n, e') open expr meta def expr_contains (n : name) : expr β†’ bool | (const nm _) := nm = n | (lam _ _ _ bd) := expr_contains bd | (pi _ _ _ bd) := expr_contains bd | (app e1 e2) := expr_contains e1 || expr_contains e2 | _ := ff lemma sub_into_lt {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (he : a = b) (hl : a ≀ 0) : b ≀ 0 := by rwa he at hl meta def norm_hyp_aux (h' lhs : expr) : tactic expr := do (v, lhs') ← kill_factors 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'' meta def norm_hyp (h : expr) : tactic expr := do htp ← infer_type h, h' ← rearr_comp h htp, some (c, lhs) ← parse_into_comp_and_expr <$> infer_type h', if expr_contains `has_div.div lhs then norm_hyp_aux h' lhs else return h' meta def get_contr_lemma_name : expr β†’ option name | `(%%a < %%b) := return `lt_of_not_ge | `(%%a ≀ %%b) := return `le_of_not_gt | `(%%a = %%b) := return ``eq_of_not_lt_of_not_gt | `(%%a β‰₯ %%b) := return `le_of_not_gt | `(%%a > %%b) := return `lt_of_not_ge | `(Β¬ %%a < %%b) := return `not.intro | `(Β¬ %%a ≀ %%b) := return `not.intro | `(Β¬ %%a = %%b) := return `not.intro | `(Β¬ %%a β‰₯ %%b) := return `not.intro | `(Β¬ %%a > %%b) := return `not.intro | _ := none -- assumes the input t is of type β„•. Produces t' of type β„€ such that ↑t = t' and a proof of equality meta def cast_expr (e : expr) : tactic (expr Γ— expr) := do s ← [`int.coe_nat_add, `int.coe_nat_zero, `int.coe_nat_one, ``int.coe_nat_bit0_mul, ``int.coe_nat_bit1_mul, ``int.coe_nat_zero_mul, ``int.coe_nat_one_mul, ``int.coe_nat_mul_bit0, ``int.coe_nat_mul_bit1, ``int.coe_nat_mul_zero, ``int.coe_nat_mul_one, ``int.coe_nat_bit0, ``int.coe_nat_bit1].mfoldl simp_lemmas.add_simp simp_lemmas.mk, ce ← to_expr ``(↑%%e : β„€), simplify s [] ce {fail_if_unchanged := ff} meta def is_nat_int_coe : expr β†’ option expr | `((↑(%%n : β„•) : β„€)) := some n | _ := none meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr := mk_app `int.coe_nat_nonneg [e] 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 meta def mk_coe_nat_nonneg_prfs (e : expr) : tactic (list expr) := (get_nat_comps e).mmap mk_coe_nat_nonneg_prf meta def mk_cast_eq_and_nonneg_prfs (pf a b : expr) (ln : name) : tactic (list expr) := do (a', prfa) ← cast_expr a, (b', prfb) ← cast_expr b, la ← mk_coe_nat_nonneg_prfs a', lb ← mk_coe_nat_nonneg_prfs b', pf' ← mk_app ln [pf, prfa, prfb], return $ pf'::(la.append lb) meta def mk_int_pfs_of_nat_pf (pf : expr) : tactic (list expr) := do tp ← infer_type pf, match tp with | `(%%a = %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_eq_subst | `(%%a ≀ %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_le_subst | `(%%a < %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_lt_subst | `(%%a β‰₯ %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_le_subst | `(%%a > %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_lt_subst | `(Β¬ %%a ≀ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_lt_subst | `(Β¬ %%a < %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_le_subst | `(Β¬ %%a β‰₯ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_lt_subst | `(Β¬ %%a > %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_le_subst | _ := fail "mk_int_pfs_of_nat_pf failed: proof is not an inequality" end 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 ``(@cast (%%a < %%b) (%%a + 1 ≀ %%b) (by refl) %%pf) | `(%%a > %%b) := to_expr ``(@cast (%%a > %%b) (%%a β‰₯ %%b + 1) (by refl) %%pf) | `(Β¬ %%a ≀ %%b) := to_expr ``(@cast (%%a > %%b) (%%a β‰₯ %%b + 1) (by refl) (lt_of_not_ge %%pf)) | `(Β¬ %%a β‰₯ %%b) := to_expr ``(@cast (%%a < %%b) (%%a + 1 ≀ %%b) (by refl) (lt_of_not_ge %%pf)) | _ := fail "mk_non_strict_int_pf_of_strict_int_pf failed: proof is not an inequality" end meta def guard_is_nat_prop : expr β†’ tactic unit | `(%%a = _) := infer_type a >>= unify `(β„•) | `(%%a ≀ _) := infer_type a >>= unify `(β„•) | `(%%a < _) := infer_type a >>= unify `(β„•) | `(%%a β‰₯ _) := infer_type a >>= unify `(β„•) | `(%%a > _) := infer_type a >>= unify `(β„•) | `(Β¬ %%p) := guard_is_nat_prop p | _ := failed meta def guard_is_strict_int_prop : expr β†’ tactic unit | `(%%a < _) := infer_type a >>= unify `(β„€) | `(%%a > _) := infer_type a >>= unify `(β„€) | `(Β¬ %%a ≀ _) := infer_type a >>= unify `(β„€) | `(Β¬ %%a β‰₯ _) := infer_type a >>= unify `(β„€) | _ := failed meta def replace_nat_pfs : list expr β†’ tactic (list expr) | [] := return [] | (h::t) := (do infer_type h >>= guard_is_nat_prop, ls ← mk_int_pfs_of_nat_pf h, list.append ls <$> replace_nat_pfs t) <|> list.cons h <$> replace_nat_pfs t meta def replace_strict_int_pfs : list expr β†’ tactic (list expr) | [] := return [] | (h::t) := (do infer_type h >>= guard_is_strict_int_prop, l ← mk_non_strict_int_pf_of_strict_int_pf h, list.cons l <$> replace_strict_int_pfs t) <|> list.cons h <$> replace_strict_int_pfs t meta def partition_by_type_aux : rb_lmap expr expr β†’ list expr β†’ tactic (rb_lmap expr expr) | m [] := return m | m (h::t) := do tp ← ineq_pf_tp h, partition_by_type_aux (m.insert tp h) t meta def partition_by_type (l : list expr) : tactic (rb_lmap expr expr) := partition_by_type_aux mk_rb_map l private meta def try_linarith_on_lists (cfg : linarith_config) (ls : list (list expr)) : tactic unit := (first $ ls.map $ prove_false_by_linarith1 cfg) <|> fail "linarith failed" /-- Takes a list of proofs of propositions. Filters out the proofs of linear (in)equalities, and tries to use them to prove `false`. If pref_type is given, starts by working over this type -/ meta def prove_false_by_linarith (cfg : linarith_config) (pref_type : option expr) (l : list expr) : tactic unit := do l' ← replace_nat_pfs l, l'' ← replace_strict_int_pfs l', ls ← list.reduce_option <$> l''.mmap (Ξ» h, (do s ← norm_hyp h, return (some s)) <|> return none) >>= partition_by_type, pref_type ← (unify pref_type.iget `(β„•) >> return (some `(β„€) : option expr)) <|> return pref_type, match cfg.restrict_type, ls.values, pref_type with | some rtp, _, _ := do m ← mk_mvar, unify `(some %%m : option Type) cfg.restrict_type_reflect, m ← instantiate_mvars m, prove_false_by_linarith1 cfg (ls.ifind m) | none, [ls'], _ := prove_false_by_linarith1 cfg ls' | none, ls', none := try_linarith_on_lists cfg ls' | none, _, (some t) := prove_false_by_linarith1 cfg (ls.ifind t) <|> try_linarith_on_lists cfg (ls.erase t).values end end normalize end linarith section open tactic linarith open lean lean.parser interactive tactic interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many meta def linarith.interactive_aux (cfg : linarith_config) : option expr β†’ parse ident* β†’ (parse (tk "using" *> pexpr_list)?) β†’ tactic unit | pt l (some pe) := pe.mmap (Ξ» p, i_to_expr p >>= note_anon) >> linarith.interactive_aux pt l none | pt [] none := do t ← target, if t = `(false) then local_context >>= prove_false_by_linarith cfg pt else match get_contr_lemma_name t with | some nm := seq (applyc nm) (do t ← intro1 >>= ineq_pf_tp, linarith.interactive_aux (some t) [] none) | none := if cfg.exfalso then exfalso >> linarith.interactive_aux pt [] none else fail "linarith failed: target type is not an inequality." end | pt ls none := (ls.mmap get_local) >>= prove_false_by_linarith cfg pt /-- Tries to prove a goal of `false` by linear arithmetic on hypotheses. If the goal is a linear (in)equality, tries to prove it by contradiction. If the goal is not `false` or an inequality, applies `exfalso` and tries linarith on the hypotheses. `linarith` will use all relevant hypotheses in the local context. `linarith h1 h2 h3` will only use hypotheses h1, h2, h3. `linarith using [t1, t2, t3]` will add proof terms t1, t2, t3 to the local context. Config options: `linarith {exfalso := ff}` will fail on a goal that is neither an inequality nor `false` `linarith {restrict_type := T}` will run only on hypotheses that are inequalities over `T` `linarith {discharger := tac}` will use `tac` instead of `ring` for normalization. Options: `ring2`, `ring SOP`, `simp` -/ meta def tactic.interactive.linarith (ids : parse (many ident)) (using_hyps : parse (tk "using" *> pexpr_list)?) (cfg : linarith_config := {}) : tactic unit := linarith.interactive_aux cfg none ids using_hyps end
32ecb83aaeb8148b3822a76ac9d3872dcac3fc71
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch6/ex0403.lean
1c3d87b9af4d91e3168eaaa5bde97a7ba667dbe0
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
252
lean
variable {Ξ± : Type*} def is_prefix (l₁ : list Ξ±) (lβ‚‚ : list Ξ±) : Prop := βˆƒ t, l₁ ++ t = lβ‚‚ infix ` <+: `:50 := is_prefix theorem list.is_prefix_refl (l : list Ξ±) : l <+: l := ⟨[], by simp⟩ attribute [simp] list.is_prefix_refl
3373478b6469e15078778b0858df4aa377b70358
dd4e652c749fea9ac77e404005cb3470e5f75469
/src/array.lean
1b533a856b4fc782eace1fc9ac6bbc8984587816
[]
no_license
skbaek/cvx
e32822ad5943541539966a37dee162b0a5495f55
c50c790c9116f9fac8dfe742903a62bdd7292c15
refs/heads/master
1,623,803,010,339
1,618,058,958,000
1,618,058,958,000
176,293,135
3
2
null
null
null
null
UTF-8
Lean
false
false
1,016
lean
import .vector variables {Ξ± Ξ² : Type} variables {k m n : nat} open nat namespace array def cell_size [has_repr Ξ±] (as : array m Ξ±) : nat := as.foldl 0 (Ξ» a n, max n (repr a).length) def sum [has_zero Ξ±] [has_add Ξ±] (v : array n Ξ±) : Ξ± := foldl v 0 (+) def dot_prod [has_zero Ξ±] [has_add Ξ±] [has_mul Ξ±] (v w : array n Ξ±) : Ξ± := array.sum (mapβ‚‚ (*) v w) #check tactic.simplify --#exit --lemma ext'_succ (a b : array (k+1) Ξ±) : -- βˆ€ (m : nat) (h : m < k), read a ⟨m, _⟩ = read b ⟨m, _⟩ β†’ -- read a ⟨k, lt_succ_self k⟩ = read b ⟨k, lt_succ_self k⟩ β†’ -- a = b := --sorry end array #exit def vector.to_array : βˆ€ {k : nat}, vector Ξ± k β†’ array k Ξ± | 0 _ := array.nil | (k+1) v := (mk_array (k+1) (v.nth ⟨0, nat.zero_lt_succ _⟩)).foreach (Ξ» i _, v.nth i) #exit run_cmd tactic.norm_num `(array.dot_prod (vector.to_array (⟨([0,1,2] : list nat), rfl⟩ : vector nat 3)) (vector.to_array (⟨([0,1,2] : list nat), rfl⟩ : vector nat 3)))
dd94af7bed7a883ef327d054a5fbc3882c01e094
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/dynamics/fixed_points/topology_auto.lean
a5e301268b04acf8e5ef7ba05e758504de69aa21
[]
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,356
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Johannes HΓΆlzl -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.dynamics.fixed_points.basic import Mathlib.topology.separation import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Topological properties of fixed points Currently this file contains two lemmas: - `is_fixed_pt_of_tendsto_iterate`: if `f^n(x) β†’ y` and `f` is continuous at `y`, then `f y = y`; - `is_closed_fixed_points`: the set of fixed points of a continuous map is a closed set. ## TODO fixed points, iterates -/ /-- If the iterates `f^[n] x` converge to `y` and `f` is continuous at `y`, then `y` is a fixed point for `f`. -/ theorem is_fixed_pt_of_tendsto_iterate {Ξ± : Type u_1} [topological_space Ξ±] [t2_space Ξ±] {f : Ξ± β†’ Ξ±} {x : Ξ±} {y : Ξ±} (hy : filter.tendsto (fun (n : β„•) => nat.iterate f n x) filter.at_top (nhds y)) (hf : continuous_at f y) : function.is_fixed_pt f y := sorry /-- The set of fixed points of a continuous map is a closed set. -/ theorem is_closed_fixed_points {Ξ± : Type u_1} [topological_space Ξ±] [t2_space Ξ±] {f : Ξ± β†’ Ξ±} (hf : continuous f) : is_closed (function.fixed_points f) := is_closed_eq hf continuous_id end Mathlib
5ca5bf371c8ecd2436b7cfb2a23d712c6de63993
97c8e5d8aca4afeebb5b335f26a492c53680efc8
/ground_zero/HITs/simplicial.lean
771840e7d7c0ae3d1a0515c693a6c65120713c49
[]
no_license
jfrancese/lean
cf32f0d8d5520b6f0e9d3987deb95841c553c53c
06e7efaecce4093d97fb5ecc75479df2ef1dbbdb
refs/heads/master
1,587,915,151,351
1,551,012,140,000
1,551,012,140,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,540
lean
import ground_zero.HITs.truncation open ground_zero.types open ground_zero.types.eq (renaming rfl -> idp) /- * Filled simplex. * Simplex. -/ hott theory namespace ground_zero.HITs universes u v w def iterated_unit : β„• β†’ Type | 0 := empty | (n + 1) := coproduct ground_zero.types.unit.{1} (iterated_unit n) def filled_simplex (n : β„•) := βˆ₯iterated_unit nβˆ₯ inductive simplex.core : β„• β†’ Type | base {n : β„•} : simplex.core (n + 1) | lift {n : β„•} : simplex.core n β†’ simplex.core (n + 1) inductive simplex.rel : Ξ  n, simplex.core n β†’ simplex.core n β†’ Prop | mk {n : β„•} (x : simplex.core n) : simplex.rel (n + 1) simplex.core.base (simplex.core.lift x) def simplex (n : β„•) := quot (simplex.rel n) inductive graph.rel {Ξ± : Sort u} (edges : Ξ± β†’ Ξ± β†’ Sort v) : Ξ± β†’ Ξ± β†’ Prop | line (n m : Ξ±) : edges n m β†’ graph.rel n m def graph {Ξ± : Sort u} (edges : Ξ± β†’ Ξ± β†’ Sort v) := quot (graph.rel edges) namespace graph def elem {Ξ± : Sort u} {edges : Ξ± β†’ Ξ± β†’ Sort w} : Ξ± β†’ graph edges := quot.mk (rel edges) def line {Ξ± : Sort u} {edges : Ξ± β†’ Ξ± β†’ Sort w} {x y : Ξ±} (h : edges x y) : @elem Ξ± edges x = @elem Ξ± edges y := ground_zero.support.inclusion (quot.sound (rel.line x y h)) def rec {Ξ± : Sort u} {Ξ² : Sort v} {edges : Ξ± β†’ Ξ± β†’ Sort w} (f : Ξ± β†’ Ξ²) (h : Ξ  x y, edges x y β†’ f x = f y) : graph edges β†’ Ξ² := begin fapply quot.lift, exact f, { intros a b, intro H, cases H, apply ground_zero.support.truncation, fapply h, assumption } end def ind {Ξ± : Sort u} {edges : Ξ± β†’ Ξ± β†’ Sort w} {Ξ² : graph edges β†’ Sort v} (f : Ξ  x, Ξ² (elem x)) (h : Ξ  x y (H : edges x y), f x =[line H] f y) : Ξ  x, Ξ² x := begin intro x, fapply quot.hrec_on x, exact f, intros a b H, cases H, apply ground_zero.types.heq.from_pathover (line H_a), fapply h end end graph def is_connected (Ξ± : Sort u) := Ξ£' (x : Ξ±), Ξ  y, βˆ₯x = yβˆ₯ def is_loop {Ξ± : Sort u} {a : Ξ±} (p : a = a) := Β¬(p = idp) def is_acyclic {Ξ± : Sort u} (edges : Ξ± β†’ Ξ± β†’ Sort u) := ground_zero.structures.K (graph edges) def is_tree {Ξ± : Sort u} (edges : Ξ± β†’ Ξ± β†’ Sort u) := is_connected (graph edges) Γ— is_acyclic edges def is_complete {Ξ± : Sort u} (edges : Ξ± β†’ Ξ± β†’ Sort u) := ground_zero.structures.prop (graph edges) namespace iso_example inductive ABC | A | B open ABC def G₁ : ABC β†’ ABC β†’ Type | A B := 𝟐 | _ _ := 𝟎 def Gβ‚‚ : ABC β†’ ABC β†’ Type | A B := 𝟏 | B A := 𝟏 | _ _ := 𝟎 def G₁Gβ‚‚ : graph G₁ β†’ graph Gβ‚‚ := graph.rec (graph.elem ∘ id) (begin intros x y, cases x; cases y; intro H, { cases H }, { cases H, { apply graph.line, exact β˜… }, { symmetry, apply graph.line, exact β˜… } }, { cases H }, { cases H } end) def Gβ‚‚G₁ : graph Gβ‚‚ β†’ graph G₁ := graph.rec (graph.elem ∘ id) (begin intros x y, cases x; cases y; intro H, { cases H }, { apply graph.line, exact ff }, { symmetry, apply graph.line, exact tt }, { cases H } end) end iso_example inductive Koenigsberg | Altstadt | Kneiphof | Lomse | Vorstadt namespace Koenigsberg def edges : Koenigsberg β†’ Koenigsberg β†’ Type | Kneiphof Lomse := ground_zero.types.unit | Altstadt Lomse := ground_zero.types.unit | Lomse Vorstadt := ground_zero.types.unit | Altstadt Kneiphof := bool | Altstadt Vorstadt := bool | _ _ := empty end Koenigsberg end ground_zero.HITs
ced53e101eab3b6b96933b35ba775b3d7fe56448
f313d4982feee650661f61ed73f0cb6635326350
/Mathlib/Algebra/Group/Defs.lean
f12ce731973a1a42c6bec7024d1fe6faf25b85c2
[ "Apache-2.0" ]
permissive
shingtaklam1324/mathlib4
38c6e172eec1385944db5a70a3b5545c924980ee
50610c343b7065e8eec056d641f859ceed608e69
refs/heads/master
1,683,032,333,313
1,621,942,699,000
1,621,942,699,000
371,130,608
0
0
Apache-2.0
1,622,053,166,000
1,622,053,166,000
null
UTF-8
Lean
false
false
11,093
lean
import Mathlib.Data.Nat.Basic -- *only* for notation β„• which should be in a "prelude" /-! # Typeclasses for monoids and groups etc -/ /- ## Stuff which was in core Lean 3 -- this should also be in a "prelude" -- it is not in mathlib3's algebra.group.defs -/ class Zero (Ξ± : Type u) where zero : Ξ± instance [Zero Ξ±] : OfNat Ξ± (nat_lit 0) where ofNat := Zero.zero class One (Ξ± : Type u) where one : Ξ± instance [One Ξ±] : OfNat Ξ± (nat_lit 1) where ofNat := One.one class Inv (Ξ± : Type u) where inv : Ξ± β†’ Ξ± postfix:max "⁻¹" => Inv.inv /- ## The trick for adding a natural action onto monoids -/ section nat_action variable {M : Type u} -- see npow_rec comment for explanation about why not nsmul_rec n a + a /-- The fundamental scalar multiplication in an additive monoid. `nsmul_rec n a = a+a+...+a` n times. Use instead `n β€’ a`, which has better definitional behavior. -/ def nsmul_rec [Zero M] [Add M] : β„• β†’ M β†’ M | 0 , a => 0 | n+1, a => a + nsmul_rec n a -- use `x * npow_rec n x` and not `npow_rec n x * x` in the definition to make sure that -- definitional unfolding of `npow_rec` is blocked, to avoid deep recursion issues. /-- The fundamental power operation in a monoid. `npow_rec n a = a*a*...*a` n times. Use instead `a ^ n`, which has better definitional behavior. -/ def npow_rec [One M] [Mul M] : β„• β†’ M β†’ M | 0 , a => 1 | n+1, a => a * npow_rec n a end nat_action section int_action -- TODO -- this should be in a prelude notation "β„€" => Int /-- The fundamental scalar multiplication in an additive group. `gsmul_rec n a = a+a+...+a` n times, for integer `n`. Use instead `n β€’ a`, which has better definitional behavior. -/ def gsmul_rec {G : Type u} [Zero G] [Add G] [Neg G]: β„€ β†’ G β†’ G | (Int.ofNat n) , a => nsmul_rec n a | (Int.negSucc n), a => - (nsmul_rec n.succ a) /-- The fundamental power operation in a group. `gpow_rec n a = a*a*...*a` n times, for integer `n`. Use instead `a ^ n`, which has better definitional behavior. -/ def gpow_rec {G : Type u} [One G] [Mul G] [Inv G] : β„€ β†’ G β†’ G | (Int.ofNat n) , a => npow_rec n a | (Int.negSucc n), a => (npow_rec n.succ a) ⁻¹ end int_action /- ## Additive semigroups, monoids and groups -/ /- ### Semigroups -/ class AddSemigroup (A : Type u) extends Add A where add_assoc (a b c : A) : (a + b) + c = a + (b + c) theorem add_assoc {G : Type u} [AddSemigroup G] : βˆ€ a b c : G, (a + b) + c = a + (b + c) := AddSemigroup.add_assoc class AddCommSemigroup (A : Type u) extends AddSemigroup A where add_comm (a b : A) : a + b = b + a theorem add_comm {A : Type u} [AddCommSemigroup A] (a b : A) : a + b = b + a := AddCommSemigroup.add_comm a b /- ### Cancellative semigroups -/ class IsAddLeftCancel (A : Type u) [Add A] where add_left_cancel (a b c : A) : a + b = a + c β†’ b = c class IsAddRightCancel (A : Type u) [Add A] where add_right_cancel (a b c : A) : b + a = c + a β†’ b = c section AddLeftCancel_lemmas variable {A : Type u} [AddSemigroup A] [IsAddLeftCancel A] {a b c : A} theorem add_left_cancel : a + b = a + c β†’ b = c := IsAddLeftCancel.add_left_cancel a b c theorem add_left_cancel_iff : a + b = a + c ↔ b = c := ⟨add_left_cancel, congrArg _⟩ -- no `function.injective`? --theorem add_right_injective (a : G) : function.injective (c * .) := --Ξ» a b => add_left_cancel @[simp] theorem add_right_inj (a : A) {b c : A} : a + b = a + c ↔ b = c := ⟨add_left_cancel, congrArg _⟩ --theorem add_ne_add_right (a : A) {b c : A} : a + b β‰  a + c ↔ b β‰  c := --(add_right_injective a).ne_iff end AddLeftCancel_lemmas section AddRightCancel_lemmas variable {A : Type u} [AddSemigroup A] [IsAddRightCancel A] {a b c : A} theorem add_right_cancel : b + a = c + a β†’ b = c := IsAddRightCancel.add_right_cancel a b c theorem add_right_cancel_iff : b + a = c + a ↔ b = c := ⟨add_right_cancel, Ξ» h => h β–Έ rfl⟩ @[simp] theorem add_left_inj (a : A) {b c : A} : b + a = c + a ↔ b = c := ⟨add_right_cancel, Ξ» h => h β–Έ rfl⟩ end AddRightCancel_lemmas /- ### Additive monoids -/ class AddMonoid (A : Type u) extends AddSemigroup A, Zero A where add_zero (a : A) : a + 0 = a zero_add (a : A) : 0 + a = a nsmul : β„• β†’ A β†’ A := nsmul_rec nsmul_zero' : βˆ€ x, nsmul 0 x = 0 -- fill in with tactic once we can do this nsmul_succ' : βˆ€ (n : β„•) x, nsmul n.succ x = x + nsmul n x -- fill in with tactic section AddMonoid_lemmas variable {A : Type u} [AddMonoid A] {a b c : A} @[simp] theorem add_zero (a : A) : a + 0 = a := AddMonoid.add_zero a @[simp] theorem zero_add (a : A) : 0 + a = a := AddMonoid.zero_add a theorem left_neg_eq_right_neg (hba : b + a = 0) (hac : a + c = 0) : b = c := by rw [←zero_add c, ←hba, add_assoc, hac, add_zero b] end AddMonoid_lemmas /- ### Commutative additive monoids -/ class AddCommMonoid (A : Type u) extends AddMonoid A where add_comm (a b : A) : a + b = b + a instance (A : Type u) [h : AddCommMonoid A] : AddCommSemigroup A := {h with} /- ### Additive groups -/ class AddGroup (A : Type u) extends AddMonoid A, Neg A, Sub A where add_left_neg (a : A) : -a + a = 0 sub_eq_add_neg (a b : A) : a - b = a + -b gsmul : β„€ β†’ A β†’ A := gsmul_rec gpow_zero' (a : A) : gsmul 0 a = 0 -- try rfl gpow_succ' (n : β„•) (a : A) : gsmul (Int.ofNat n.succ) a = a + gsmul (Int.ofNat n) a gpow_neg' (n : β„•) (a : A) : gsmul (Int.negSucc n) a = -(gsmul ↑(n.succ) a) section AddGroup_lemmas variable {A : Type u} [AddGroup A] {a b c : A} @[simp] theorem add_left_neg : βˆ€ a : A, -a + a = 0 := AddGroup.add_left_neg theorem neg_add_self (a : A) : -a + a = 0 := add_left_neg a @[simp] theorem neg_add_cancel_left (a b : A) : -a + (a + b) = b := by rw [← add_assoc, add_left_neg, zero_add] @[simp] theorem neg_eq_of_add_eq_zero (h : a + b = 0) : -a = b := left_neg_eq_right_neg (neg_add_self a) h @[simp] theorem neg_neg (a : A) : -(-a) = a := neg_eq_of_add_eq_zero (add_left_neg a) @[simp] theorem add_right_neg (a : A) : a + -a = 0 := by rw [←add_left_neg (-a), neg_neg] -- synonym theorem add_neg_self (a : A) : a + -a = 0 := add_right_neg a @[simp] theorem add_neg_cancel_right (a b : A) : a + b + -b = a := by rw [add_assoc, add_right_neg, add_zero] instance (A : Type u) [AddGroup A] : IsAddRightCancel A where add_right_cancel a b c h := by rw [← add_neg_cancel_right b a, h, add_neg_cancel_right] instance (A : Type u) [AddGroup A] : IsAddLeftCancel A where add_left_cancel a b c h := by rw [← neg_add_cancel_left a b, h, neg_add_cancel_left] end AddGroup_lemmas class AddCommGroup (A : Type u) extends AddGroup A where add_comm (a b : A) : a + b = b + a -- the automatically generated name is something like instAddCommMonoid -- I need to explicitly refer to this later when making Ring.toSemiring instance AddCommGroup.toAddCommMonoid (A : Type u) [h : AddCommGroup A] : AddCommMonoid A := { h with } /- ## Multiplicative semigroups, monoids and groups -/ /- ## Semigroups -/ class Semigroup (G : Type u) extends Mul G where mul_assoc (a b c : G) : (a * b) * c = a * (b * c) theorem mul_assoc {G : Type u} [Semigroup G] : βˆ€ a b c : G, a * b * c = a * (b * c) := Semigroup.mul_assoc class CommSemigroup (G : Type u) extends Semigroup G where mul_comm (a b : G) : a * b = b * a theorem mul_comm {M : Type u} [CommSemigroup M] : βˆ€ a b : M, a * b = b * a := CommSemigroup.mul_comm /- ### Cancellative semigroups -/ class IsMulLeftCancel (G : Type u) [Mul G] where mul_left_cancel (a b c : G) : a * b = a * c β†’ b = c class IsMulRightCancel (G : Type u) [Mul G] where mul_right_cancel (a b c : G) : b * a = c * a β†’ b = c section MulLeftCancel variable {G : Type u} [Semigroup G] [IsMulLeftCancel G] {a b c : G} theorem mul_left_cancel : a * b = a * c β†’ b = c := IsMulLeftCancel.mul_left_cancel a b c theorem mul_left_cancel_iff : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congrArg _⟩ -- no `function.injective`? --theorem mul_right_injective (a : G) : function.injective (c * .) := --Ξ» a b => mul_left_cancel @[simp] theorem mul_right_inj (a : G) {b c : G} : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congrArg _⟩ --theorem mul_ne_mul_right (a : G) {b c : G} : a * b β‰  a * c ↔ b β‰  c := --(mul_right_injective a).ne_iff end MulLeftCancel section MulRightCancel variable {G : Type u} [Semigroup G] [IsMulRightCancel G] {a b c : G} theorem mul_right_cancel : b * a = c * a β†’ b = c := IsMulRightCancel.mul_right_cancel a b c theorem mul_right_cancel_iff : b * a = c * a ↔ b = c := ⟨mul_right_cancel, Ξ» h => h β–Έ rfl⟩ @[simp] theorem mul_left_inj (a : G) {b c : G} : b * a = c * a ↔ b = c := ⟨mul_right_cancel, Ξ» h => h β–Έ rfl⟩ end MulRightCancel /- ### Monoids -/ class Monoid (M : Type u) extends Semigroup M, One M where mul_one (m : M) : m * 1 = m one_mul (m : M) : 1 * m = m npow : β„• β†’ M β†’ M := npow_rec npow_zero' : βˆ€ x, npow 0 x = 1 -- fill in with tactic once we can do this npow_succ' : βˆ€ (n : β„•) x, npow n.succ x = x * npow n x -- fill in with tactic @[simp] theorem mul_one {M : Type u} [Monoid M] : βˆ€ (m : M), m * 1 = m := Monoid.mul_one @[simp] theorem one_mul {M : Type u} [Monoid M] : βˆ€ (m : M), 1 * m = m := Monoid.one_mul theorem left_inv_eq_right_inv {M : Type u} [Monoid M] {a b c : M} (hba : b * a = 1) (hac : a * c = 1) : b = c := by rw [←one_mul c, ←hba, mul_assoc, hac, mul_one b] /- ### Commutative monoids -/ class CommMonoid (M : Type u) extends Monoid M where mul_comm (a b : M) : a * b = b * a instance (M : Type u) [h : CommMonoid M] : CommSemigroup M := { h with } /- ### Groups -/ class Group (G : Type u) extends Monoid G, Inv G, Div G where mul_left_inv (a : G) : a⁻¹ * a = 1 div_eq_mul_inv (a b : G) : a / b = a * b⁻¹ gpow : β„€ β†’ G β†’ G := gpow_rec gpow_zero' (a : G) : gpow 0 a = 1 -- try rfl gpow_succ' (n : β„•) (a : G) : gpow (Int.ofNat n.succ) a = a * gpow (Int.ofNat n) a gpow_neg' (n : β„•) (a : G) : gpow (Int.negSucc n) a = (gpow ↑(n.succ) a)⁻¹ section Group_lemmas variable {G : Type u} [Group G] {a b c : G} @[simp] theorem mul_left_inv : βˆ€ a : G, a⁻¹ * a = 1 := Group.mul_left_inv theorem inv_mul_self (a : G) : a⁻¹ * a = 1 := mul_left_inv a @[simp] theorem inv_mul_cancel_left (a b : G) : a⁻¹ * (a * b) = b := by rw [← mul_assoc, mul_left_inv, one_mul] @[simp] theorem inv_eq_of_mul_eq_one (h : a * b = 1) : a⁻¹ = b := left_inv_eq_right_inv (inv_mul_self a) h @[simp] theorem inv_inv (a : G) : (a⁻¹)⁻¹ = a := inv_eq_of_mul_eq_one (mul_left_inv a) @[simp] theorem mul_right_inv (a : G) : a * a⁻¹ = 1 := by rw [←mul_left_inv (a⁻¹), inv_inv] -- synonym theorem mul_inv_self (a : G) : a * a⁻¹ = 1 := mul_right_inv a @[simp] theorem mul_inv_cancel_right (a b : G) : a * b * b⁻¹ = a := by rw [mul_assoc, mul_right_inv, mul_one] end Group_lemmas class CommGroup (G : Type u) extends Group G where mul_comm (a b : G) : a * b = b * a instance (G : Type u) [h : CommGroup G] : CommMonoid G := { h with }
74b0fd7406c0da666e41a7327031c99f59807219
39c5aa4cf3be4a2dfd294cd2becd0848ff4cad97
/src/TypeCheck.lean
49b56fb7c35bafb4370150b206eeffb773317ce2
[]
no_license
anfelor/coc-lean
70d489ae1d34932d33bcf211b4ef8d1fe557e1d3
fdd967d2b7bc349202a1deabbbce155eed4db73a
refs/heads/master
1,617,867,588,097
1,587,224,804,000
1,587,224,804,000
248,754,643
5
0
null
null
null
null
UTF-8
Lean
false
false
11,455
lean
import Terms import CoC open PTSSort open BetaOpt /-! The type checker. -/ /- Since Judgements are in Prop, we have to jump through some hoops to write nearly trivial functions. But Judgements belong to Prop not least because the type checker would be noncomputable if they were in type due to some hard to prove statements. -/ inductive TypeError : Type | TypeMismatch : Exp β†’ Exp β†’ TypeError | UnboundIndex : nat β†’ TypeError | UnboundVar : string β†’ TypeError | BoxInTerm : TypeError | WhileChecking : Exp β†’ TypeError β†’ TypeError | ExpectedFunctionButGot : Exp β†’ TypeError | ExpectedSortButGot : Exp β†’ TypeError open TypeError def type_error_repr : TypeError -> string | (TypeMismatch e1 e2) := "Type mismatch between: " ++ repr e1 ++ " and " ++ repr e2 | (UnboundIndex n) := "Unbound index: " ++ repr n | (UnboundVar s) := "Unbound var: " ++ repr s | (BoxInTerm) := "Box in term." | (WhileChecking e t) := "While checking " ++ repr e ++ " encountered\n" ++ type_error_repr t | (ExpectedFunctionButGot e) := "Expected function but got: " ++ repr e | (ExpectedSortButGot e) := "Expected sort but got: " ++ repr e instance type_error_has_repr : has_repr TypeError := { repr := type_error_repr } /-- The type checker monad -/ def TC := except TypeError open except instance tc_has_bind : has_bind TC := { bind := Ξ» _ _, except.bind } instance tc_has_repr {a} {h : has_repr a} : has_repr (TC a) := { repr := Ξ» t, match t with | error t := repr t | ok a := repr a end } instance type_psigma_has_repr {g e} : has_repr (Ξ£' t : Exp, Judgement g e t) := { repr := Ξ» s, repr s.fst } /- This instance is necessary for #eval -/ instance type_tc_has_repr {g e} : has_repr (TC (Ξ£' t : Exp, Judgement g e t)) := { repr := (@tc_has_repr _ type_psigma_has_repr).repr } /-- Lookup a variable in a well-formed context. -/ def lookup (x : string) : Ξ  (g : Context) (h : ContextWF g), TC (Ξ£' t, Judgement g (Exp.free x) t) | (Context.empty) h := error (UnboundVar x) | (Context.cons y e g') h := match string.has_decidable_eq x y with | (is_true p) := ok ⟨e, begin simp [p], cases h, exact Judgement.start y h_noShadowing h_a, end⟩ | (is_false p) := lookup g' (by { cases h, assumption }) >>= (begin intro a, apply ok, cases a, apply psigma.mk, cases h, exact Judgement.weaken y h_noShadowing a_snd h_a, end) end def find_rule : Ξ  (s t : PTSSort), Rule s t | star star := Rule.vdv | star box := Rule.tdv | box star := Rule.vdt | box box := Rule.tdt inductive Classification (g : Context) (t : Exp) : Type | kind : t = Exp.sort box β†’ Classification | term : Judgement g t (Exp.sort star) β†’ Classification | constructor : Judgement g t (Exp.sort box) β†’ Classification -- | See Theorem 3.2 and 3.3 in [snforcc]. -- The classification lemma will be challenging since Classification is in -- type and not in Prop. See typing_pi_find_sort below. axiom preservation {g e t} : Judgement g e t β†’ Judgement g (head_reduce e) t axiom classification : Ξ  {g e t}, Judgement g e t β†’ Classification g t axiom beta_preserves_type : Ξ  {g e t z}, Beta Red t z β†’ Judgement g e t β†’ Judgement g e z def beta_reduce_terminates_type {g e t} : Judgement g e t β†’ (beta_reduce t).dom := begin intro j, cases classification j, simp [a, beta_reduce], refine acc.intro t _, intro y, rw [a], intro b, cases b, repeat { exact beta_reduce_terminates a }, end inductive ContextLT : Context -> Context -> Prop | empty {g} : ContextLT (Context.empty) g | cons1 {x a g h} : ContextLT g h -> ContextLT g (Context.cons x a h) | cons2 {x a g h} : ContextLT g h -> ContextLT (Context.cons x a g) (Context.cons x a h) def context_lt_refl : Ξ  g, ContextLT g g | Context.empty := ContextLT.empty | (Context.cons x a g) := ContextLT.cons2 (context_lt_refl g) def context_lt_cons {x a} : Ξ  g, ContextLT g (Context.cons x a g) := Ξ» g, ContextLT.cons1 (context_lt_refl g) def preserves_type {g e t} : Judgement g e t β†’ Judgement g e (head_reduce t) := begin intro j, cases classification j, rw [a, head_reduce], rw [a] at j, exact j, exact Judgement.conv (Beta.head_reduce Eq t) (preservation a) j, exact Judgement.conv (Beta.head_reduce Eq t) (preservation a) j, end -- The grammar for expressions of type box is -- t := A | * | x -> t for A a variable and x an arbitrary expression. lemma typing_pi_find_sort : Ξ  a (g : Context) (h : ContextWF g), Ξ£' s, βˆ€ p, βˆ€ h_g, ContextLT h_g g -> Judgement h_g a (Exp.sort p) -> p = s := sorry lemma typing_pi : Ξ  {g x a b t}, Judgement g (Exp.pi x a b) t β†’ Ξ£' s, Judgement g a (Exp.sort s) := begin intros g x a b t, generalize e : Exp.pi x a b = y, intro h, let z := typing_pi_find_sort a g (judgement_context_wf h), apply psigma.mk z.fst, induction h generalizing e; cases e, { apply Judgement.weaken, exact h_noShadowing, have z2 := h_ih_a (eq.refl _), exact eq.mp (by rw [z.snd _ h_g (context_lt_cons _) z2]) z2, exact h_a_1, }, { exact eq.mp (by rw [z.snd h_s1 h_g (context_lt_refl h_g) h_a]) h_a }, { from h_ih_a_1 (eq.refl _) }, end lemma beta_reduce_terminates_head_reduce_pi {g e t x a b} : Judgement g e t β†’ head_reduce t = Exp.pi x a b β†’ (beta_reduce a).dom := begin intros j h, cases classification j, simp [a_1, head_reduce] at h, from false.elim h, iterate 2 { have h2 := preservation a_1, rw [h] at h2, cases typing_pi h2, from beta_reduce_terminates snd, } end inductive typecheck_rel : (Ξ£' (e : Exp) (g : Context), ContextWF g) β†’ (Ξ£' (e : Exp) (g : Context), ContextWF g) β†’ Prop | app_1 {g h a b} : typecheck_rel ⟨a, g, h⟩ ⟨Exp.app a b, g, h⟩ | app_2 {g h a b} : typecheck_rel ⟨b, g, h⟩ ⟨Exp.app a b, g, h⟩ | lam_1 {g h x a b} : typecheck_rel ⟨a, g, h⟩ ⟨Exp.lam x a b, g, h⟩ | lam_2 {g h x a t s hns} {h1 : Judgement g a (Exp.sort s)} : typecheck_rel ⟨instantiate (Exp.free (fresh (context_domain g βˆͺ free_vars t) x)) t , Context.cons (fresh (context_domain g βˆͺ free_vars t) x) a g, ContextWF.cons h hns h1⟩ ⟨Exp.lam x a t, g, h⟩ | check_pi {g h x a t b} (h1 : Judgement (Context.cons (fresh (context_domain g βˆͺ free_vars t) x) a g) (instantiate (Exp.free (fresh (context_domain g βˆͺ free_vars t) x)) t) b) : typecheck_rel ⟨Exp.pi (fresh (context_domain g βˆͺ free_vars t) x) a (abstract (fresh (context_domain g βˆͺ free_vars t) x) b), g, h⟩ ⟨Exp.lam x a t, g, h⟩ | pi_1 {g h x a b} : typecheck_rel ⟨a, g, h⟩ ⟨Exp.pi x a b, g, h⟩ | pi_2 {g h x a t s hns} {h1 : Judgement g a (Exp.sort s)} : typecheck_rel ⟨instantiate (Exp.free (fresh (context_domain g βˆͺ free_vars t) x)) t , Context.cons (fresh (context_domain g βˆͺ free_vars t) x) a g, ContextWF.cons h hns h1⟩ ⟨Exp.pi x a t, g, h⟩ set_option eqn_compiler.zeta true def typecheck_recur : Ξ  (e : Exp) (g : Context) (h : ContextWF g), (Ξ  y, typecheck_rel y ⟨e, g, h⟩ β†’ TC (Ξ£' t, Judgement y.2.1 y.1 t)) β†’ TC (Ξ£' t, Judgement g e t) | (Exp.free x) g h IH := lookup x g h | (Exp.bound x) g h IH := error (UnboundIndex x) | (Exp.sort s) g h IH := match s with | star := ok ⟨Exp.sort box, ContextWF.rec_on h (Judgement.starInBox) (Ξ» x _ _ _ _ hns a h, Judgement.weaken x hns h a)⟩ | box := error BoxInTerm end | (Exp.app f a) g h IH := IH ⟨f, g, h⟩ (typecheck_rel.app_1) >>= Ξ» ⟨e, je⟩, IH ⟨a, g, h⟩ (typecheck_rel.app_2) >>= Ξ» ⟨A, jA⟩, let ⟨z1, beta1⟩ := (beta_reduce A).get (beta_reduce_terminates_type jA) in begin cases h : (head_reduce e), case Exp.pi : x A' B begin rename h_1 h, let zb := (beta_reduce A').get (beta_reduce_terminates_head_reduce_pi je h), cases exp_decidable_eq z1 zb.1, exact error (ExpectedFunctionButGot e), let h2 : Ξ£' s, Judgement g (Exp.pi x A' B) (Exp.sort s) := begin cases classification (preserves_type je), simp [a_1, head_reduce] at h, from false.elim h, repeat { rw [h] at a_1 }, exact ⟨star, a_1⟩, exact ⟨box, a_1⟩, end, let h4 : Ξ£' s, Judgement g A' (Exp.sort s) := begin cases classification (preserves_type je), simp [a_1, head_reduce] at h, from false.elim h, repeat { rw [h] at a_1, from typing_pi a_1, }, end, apply ok, fapply psigma.mk, exact (instantiate a B), apply Judgement.app, apply Judgement.conv, apply eq.mp (by simp [h]) (Beta.head_reduce Eq e), from h2.snd, from je, apply Judgement.conv, from (Beta.trans Red Eq Eq (eq.refl _) beta1 (eq.mp (by simp[h_1]) (Beta.symm zb.2))), from h4.2, from jA, end, repeat { exact error (ExpectedFunctionButGot (head_reduce e)) } end | (Exp.lam x a t) g h IH := IH ⟨a, g, h⟩ (typecheck_rel.lam_1) >>= λ⟨s, ja⟩, match (beta_reduce s).get (beta_reduce_terminates_type ja), ja with | ⟨Exp.sort s, bs⟩, ja := let x' := fresh (context_domain g βˆͺ free_vars t) x in IH ⟨(instantiate (Exp.free x') t), (Context.cons x' a g), (ContextWF.cons h (iff.elim_left finset.not_mem_union (fresh_not_mem)).1 (beta_preserves_type bs ja))⟩ (typecheck_rel.lam_2) >>= λ⟨b, jb⟩, IH ⟨(Exp.pi x' a (abstract x' b)), g, h⟩ (typecheck_rel.check_pi jb) >>= λ⟨p, jp⟩, match (beta_reduce p).get (beta_reduce_terminates_type jp), jp with | ⟨Exp.sort _, bp⟩, jp := let h : Judgement g (Exp.lam x a t) (Exp.pi x a (abstract x' b)) := eq.mp (by simp [fresh_avoids_capture (finset.subset_union_right _ _)]) (Judgement.abs x jb (beta_preserves_type bp jp)) in ok ⟨Exp.pi x a (abstract x' b), h⟩ | _, _ := error (ExpectedSortButGot p) end | ⟨e, _⟩, _ := error (ExpectedSortButGot e) end | (Exp.pi x a b) g h IH := IH ⟨a, g, h⟩ (typecheck_rel.pi_1) >>= λ⟨s, js⟩, match (beta_reduce s).get (beta_reduce_terminates_type js), js with | ⟨Exp.sort s, bs⟩, js := let x' := fresh (context_domain g βˆͺ free_vars b) x in IH ⟨(instantiate (Exp.free x') b), (Context.cons x' a g), (ContextWF.cons h (iff.elim_left finset.not_mem_union (fresh_not_mem)).1 (beta_preserves_type bs js))⟩ (typecheck_rel.pi_2) >>= λ⟨t, jt⟩, match (beta_reduce t).get (beta_reduce_terminates_type jt), jt with | ⟨Exp.sort t, bt⟩, jt := let h : Judgement g (Exp.pi x a b) (Exp.sort t) := eq.mp (by simp [fresh_avoids_capture (finset.subset_union_right _ _)]) (Judgement.product x (find_rule s t) (beta_preserves_type bs js) (beta_preserves_type bt jt)) in ok ⟨Exp.sort t, h⟩ | ⟨e, _⟩, _ := error (ExpectedSortButGot e) end | ⟨e, _⟩, _ := error (ExpectedSortButGot e) end set_option eqn_compiler.zeta false def typecheck_roption (e : Exp) (g : Context) (h : ContextWF g) : roption (TC (Ξ£' t, Judgement g e t)) := begin refine ⟨acc typecheck_rel ⟨e,g,h⟩, Ξ» h2, @acc.rec_on (Ξ£' (e : Exp) (g : Context), ContextWF g) _ (Ξ» y, TC (Ξ£' t, Judgement y.2.1 y.1 t)) _ h2 (Ξ» ⟨e1,g1,h1⟩ ih IH, typecheck_recur e1 g1 h1 IH)⟩, end def typecheck_terminates (e : Exp) (g : Context) (h : ContextWF g) : (typecheck_roption e g h).dom := sorry def typecheck (e : Exp) (g : Context) (h : ContextWF g) : TC (Ξ£' t, Judgement g e t) := (typecheck_roption e g h).get (typecheck_terminates e g h)
6aca3a9921b510a7ba369ad4f80f56fb82708c30
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/locally_convex/polar.lean
6c2d73ba3e9bee61d7914bf2cf5337f30601a04d
[ "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
4,695
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll, Kalle KytΓΆlΓ€ -/ import analysis.normed.normed_field import analysis.convex.basic import linear_algebra.sesquilinear_form import topology.algebra.module.weak_dual /-! # Polar set In this file we define the polar set. There are different notions of the polar, we will define the *absolute polar*. The advantage over the real polar is that we can define the absolute polar for any bilinear form `B : E β†’β‚—[π•œ] F β†’β‚—[π•œ] π•œ`, where `π•œ` is a normed commutative ring and `E` and `F` are modules over `π•œ`. ## Main definitions * `linear_map.polar`: The polar of a bilinear form `B : E β†’β‚—[π•œ] F β†’β‚—[π•œ] π•œ`. ## Main statements * `linear_map.polar_eq_Inter`: The polar as an intersection. * `linear_map.subset_bipolar`: The polar is a subset of the bipolar. * `linear_map.polar_weak_closed`: The polar is closed in the weak topology induced by `B.flip`. ## References * [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966] ## Tags polar -/ variables {π•œ E F : Type*} namespace linear_map section normed_ring variables [normed_comm_ring π•œ] [add_comm_monoid E] [add_comm_monoid F] variables [module π•œ E] [module π•œ F] variables (B : E β†’β‚—[π•œ] F β†’β‚—[π•œ] π•œ) /-- The (absolute) polar of `s : set E` is given by the set of all `y : F` such that `βˆ₯B x yβˆ₯ ≀ 1` for all `x ∈ s`.-/ def polar (s : set E) : set F := {y : F | βˆ€ x ∈ s, βˆ₯B x yβˆ₯ ≀ 1 } lemma polar_mem_iff (s : set E) (y : F) : y ∈ B.polar s ↔ βˆ€ x ∈ s, βˆ₯B x yβˆ₯ ≀ 1 := iff.rfl lemma polar_mem (s : set E) (y : F) (hy : y ∈ B.polar s) : βˆ€ x ∈ s, βˆ₯B x yβˆ₯ ≀ 1 := hy @[simp] lemma zero_mem_polar (s : set E) : (0 : F) ∈ B.polar s := Ξ» _ _, by simp only [map_zero, norm_zero, zero_le_one] lemma polar_eq_Inter {s : set E} : B.polar s = β‹‚ x ∈ s, {y : F | βˆ₯B x yβˆ₯ ≀ 1} := by { ext, simp only [polar_mem_iff, set.mem_Inter, set.mem_set_of_eq] } /-- The map `B.polar : set E β†’ set F` forms an order-reversing Galois connection with `B.flip.polar : set F β†’ set E`. We use `order_dual.to_dual` and `order_dual.of_dual` to express that `polar` is order-reversing. -/ lemma polar_gc : galois_connection (order_dual.to_dual ∘ B.polar) (B.flip.polar ∘ order_dual.of_dual) := Ξ» s t, ⟨λ h _ hx _ hy, h hy _ hx, Ξ» h _ hx _ hy, h hy _ hx⟩ @[simp] lemma polar_Union {ΞΉ} {s : ΞΉ β†’ set E} : B.polar (⋃ i, s i) = β‹‚ i, B.polar (s i) := B.polar_gc.l_supr @[simp] lemma polar_union {s t : set E} : B.polar (s βˆͺ t) = B.polar s ∩ B.polar t := B.polar_gc.l_sup lemma polar_antitone : antitone (B.polar : set E β†’ set F) := B.polar_gc.monotone_l @[simp] lemma polar_empty : B.polar βˆ… = set.univ := B.polar_gc.l_bot @[simp] lemma polar_zero : B.polar ({0} : set E) = set.univ := begin refine set.eq_univ_iff_forall.mpr (Ξ» y x hx, _), rw [set.mem_singleton_iff.mp hx, map_zero, linear_map.zero_apply, norm_zero], exact zero_le_one, end lemma subset_bipolar (s : set E) : s βŠ† B.flip.polar (B.polar s) := Ξ» x hx y hy, by { rw B.flip_apply, exact hy x hx } @[simp] lemma tripolar_eq_polar (s : set E) : B.polar (B.flip.polar (B.polar s)) = B.polar s := begin refine (B.polar_antitone (B.subset_bipolar s)).antisymm _, convert subset_bipolar B.flip (B.polar s), exact B.flip_flip.symm, end /-- The polar set is closed in the weak topology induced by `B.flip`. -/ lemma polar_weak_closed (s : set E) : @is_closed _ (weak_bilin.topological_space B.flip) (B.polar s) := begin rw polar_eq_Inter, refine is_closed_Inter (Ξ» x, is_closed_Inter (Ξ» _, _)), exact is_closed_le (weak_bilin.eval_continuous B.flip x).norm continuous_const, end end normed_ring section nondiscrete_normed_field variables [nondiscrete_normed_field π•œ] [add_comm_monoid E] [add_comm_monoid F] variables [module π•œ E] [module π•œ F] variables (B : E β†’β‚—[π•œ] F β†’β‚—[π•œ] π•œ) lemma polar_univ (h : separating_right B) : B.polar set.univ = {(0 : F)} := begin rw set.eq_singleton_iff_unique_mem, refine ⟨by simp only [zero_mem_polar], Ξ» y hy, h _ (Ξ» x, _)⟩, refine norm_le_zero_iff.mp (le_of_forall_le_of_dense $ Ξ» Ξ΅ hΞ΅, _), rcases normed_field.exists_norm_lt π•œ hΞ΅ with ⟨c, hc, hcΡ⟩, calc βˆ₯B x yβˆ₯ = βˆ₯cβˆ₯ * βˆ₯B (c⁻¹ β€’ x) yβˆ₯ : by rw [B.map_smul, linear_map.smul_apply, algebra.id.smul_eq_mul, norm_mul, norm_inv, mul_inv_cancel_leftβ‚€ hc.ne'] ... ≀ Ξ΅ * 1 : mul_le_mul hcΞ΅.le (hy _ trivial) (norm_nonneg _) hΞ΅.le ... = Ξ΅ : mul_one _ end end nondiscrete_normed_field end linear_map
bada3eec3971aee9440353432c6fbb6ec43b4e4f
f2fbd9ce3f46053c664b74a5294d7d2f584e72d3
/src/adic_space.lean
5b0b4a98ecd845868cf8e23249bd4649e5cd4827
[ "Apache-2.0" ]
permissive
jcommelin/lean-perfectoid-spaces
c656ae26a2338ee7a0072dab63baf577f079ca12
d5ed816bcc116fd4cde5ce9aaf03905d00ee391c
refs/heads/master
1,584,610,432,107
1,538,491,594,000
1,538,491,594,000
136,299,168
0
0
null
1,528,274,452,000
1,528,274,452,000
null
UTF-8
Lean
false
false
2,298
lean
import for_mathlib.prime import for_mathlib.is_cover import analysis.topology.topological_structures import data.nat.prime import algebra.group_power import for_mathlib.presheaves import for_mathlib.topology import for_mathlib.topological_structures import continuous_valuations import Spa import Huber_pair universe u open nat function --definition π“ž_X (A : Huber_pair) : presheaf_of_rings (Spa A) := sorry -- it's a presheaf of complete topological rings on all opens (defined on rational opens -- first and then extended to all via proj limits) -- Wedhorn p75 -- most of that would not be in the adic_space file. --structure π“₯pre := --(X : sorry) --(π“žX : sorry) --(v : sorry) /- We denote by π“₯pre the category of tuples X = (X, O X , (v x ) x∈X ), where (a) X is a topological space, (b) π“ž_X is a presheaf of complete topological rings on X such that the stalk π“ž_X,x of π“ž_X (considered as a presheaf of rings) is a local ring, (c) v_x is an equivalence class of valuations on the stalk π“ž_X,x such that supp(v_x) is the maximal ideal of π“ž_X,x . Wedhorn p76 shows how Spa(A) gives an object of this for A a Huber pair -/ --definition affinoid_adic_space (A : Huber_pair) : π“₯pre := sorry -- unwritten -- it's a full subcat of π“₯pre class preadic_space (X : Type) extends topological_space X -- not logically necessary but should be easy instance (A : Huber_pair) : preadic_space (Spa A) := sorry -- attribute [class] _root_.is_open instance preadic_space_restriction {X : Type} [preadic_space X] {U : opens X} : preadic_space U := sorry -- unwritten class adic_space (X : Type) extends preadic_space X -- a preadic_space_equiv is just an isom in π“₯pre, or an isomorphism of preadic spaces. -- is homeo in Lean yet? -- unwritten structure preadic_space_equiv (X Y : Type) [AX : preadic_space X] [AY : preadic_space Y] extends equiv X Y definition is_preadic_space_equiv (X Y : Type) [AX : preadic_space X] [AY : preadic_space Y] := nonempty (preadic_space_equiv X Y) definition preadic_space_pullback {X : Type} [preadic_space X] (U : set X) := {x : X // x ∈ U} instance pullback_is_preadic_space {X : Type} [preadic_space X] (U : set X) : preadic_space (preadic_space_pullback U) := sorry -- notation `is_open` := _root_.is_open
77dc9bce8268cfbf871f2e9ff42ce210d5737991
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/polynomial/pochhammer.lean
81f5de17ff7a734b62afaa0c354e6ee5deb8634e
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
6,774
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 tactic.abel import data.polynomial.eval /-! # The Pochhammer polynomials We define and prove some basic relations about `pochhammer S n : S[X] := X * (X + 1) * ... * (X + n - 1)` which is also known as the rising factorial. A version of this definition that is focused on `nat` can be found in `data.nat.factorial` as `nat.asc_factorial`. ## Implementation As with many other families of polynomials, even though the coefficients are always in `β„•`, we define the polynomial with coefficients in any `[semiring S]`. ## TODO There is lots more in this direction: * q-factorials, q-binomials, q-Pochhammer. -/ universes u v open polynomial open_locale polynomial section semiring variables (S : Type u) [semiring S] /-- `pochhammer S n` is the polynomial `X * (X+1) * ... * (X + n - 1)`, with coefficients in the semiring `S`. -/ noncomputable def pochhammer : β„• β†’ S[X] | 0 := 1 | (n+1) := X * (pochhammer n).comp (X + 1) @[simp] lemma pochhammer_zero : pochhammer S 0 = 1 := rfl @[simp] lemma pochhammer_one : pochhammer S 1 = X := by simp [pochhammer] lemma pochhammer_succ_left (n : β„•) : pochhammer S (n+1) = X * (pochhammer S n).comp (X+1) := by rw pochhammer section variables {S} {T : Type v} [semiring T] @[simp] lemma pochhammer_map (f : S β†’+* T) (n : β„•) : (pochhammer S n).map f = pochhammer T n := begin induction n with n ih, { simp, }, { simp [ih, pochhammer_succ_left, map_comp], }, end end @[simp, norm_cast] lemma pochhammer_eval_cast (n k : β„•) : ((pochhammer β„• n).eval k : S) = (pochhammer S n).eval k := begin rw [←pochhammer_map (algebra_map β„• S), eval_map, ←eq_nat_cast (algebra_map β„• S), evalβ‚‚_at_nat_cast, nat.cast_id, eq_nat_cast], end lemma pochhammer_eval_zero {n : β„•} : (pochhammer S n).eval 0 = if n = 0 then 1 else 0 := begin cases n, { simp, }, { simp [X_mul, nat.succ_ne_zero, pochhammer_succ_left], } end lemma pochhammer_zero_eval_zero : (pochhammer S 0).eval 0 = 1 := by simp @[simp] lemma pochhammer_ne_zero_eval_zero {n : β„•} (h : n β‰  0) : (pochhammer S n).eval 0 = 0 := by simp [pochhammer_eval_zero, h] lemma pochhammer_succ_right (n : β„•) : pochhammer S (n+1) = pochhammer S n * (X + n) := begin suffices h : pochhammer β„• (n+1) = pochhammer β„• n * (X + n), { apply_fun polynomial.map (algebra_map β„• S) at h, simpa only [pochhammer_map, polynomial.map_mul, polynomial.map_add, map_X, polynomial.map_nat_cast] using h }, induction n with n ih, { simp, }, { conv_lhs { rw [pochhammer_succ_left, ih, mul_comp, ←mul_assoc, ←pochhammer_succ_left, add_comp, X_comp, nat_cast_comp, add_assoc, add_comm (1 : β„•[X])], }, refl, }, end lemma pochhammer_succ_eval {S : Type*} [semiring S] (n : β„•) (k : S) : (pochhammer S (n + 1)).eval k = (pochhammer S n).eval k * (k + n) := by rw [pochhammer_succ_right, mul_add, eval_add, eval_mul_X, ← nat.cast_comm, ← C_eq_nat_cast, eval_C_mul, nat.cast_comm, ← mul_add] lemma pochhammer_succ_comp_X_add_one (n : β„•) : (pochhammer S (n + 1)).comp (X + 1) = pochhammer S (n + 1) + (n + 1) β€’ (pochhammer S n).comp (X + 1) := begin suffices : (pochhammer β„• (n + 1)).comp (X + 1) = pochhammer β„• (n + 1) + (n + 1) * (pochhammer β„• n).comp (X + 1), { simpa [map_comp] using congr_arg (polynomial.map (nat.cast_ring_hom S)) this }, nth_rewrite 1 pochhammer_succ_left, rw [← add_mul, pochhammer_succ_right β„• n, mul_comp, mul_comm, add_comp, X_comp, nat_cast_comp, add_comm ↑n, ← add_assoc] end lemma polynomial.mul_X_add_nat_cast_comp {p q : S[X]} {n : β„•} : (p * (X + n)).comp q = (p.comp q) * (q + n) := by rw [mul_add, add_comp, mul_X_comp, ←nat.cast_comm, nat_cast_mul_comp, nat.cast_comm, mul_add] lemma pochhammer_mul (n m : β„•) : pochhammer S n * (pochhammer S m).comp (X + n) = pochhammer S (n + m) := begin induction m with m ih, { simp, }, { rw [pochhammer_succ_right, polynomial.mul_X_add_nat_cast_comp, ←mul_assoc, ih, nat.succ_eq_add_one, ←add_assoc, pochhammer_succ_right, nat.cast_add, add_assoc], } end lemma pochhammer_nat_eq_asc_factorial (n : β„•) : βˆ€ k, (pochhammer β„• k).eval (n + 1) = n.asc_factorial k | 0 := by erw [eval_one]; refl | (t + 1) := begin rw [pochhammer_succ_right, eval_mul, pochhammer_nat_eq_asc_factorial t], suffices : n.asc_factorial t * (n + 1 + t) = n.asc_factorial (t + 1), by simpa, rw [nat.asc_factorial_succ, add_right_comm, mul_comm] end lemma pochhammer_nat_eq_desc_factorial (a b : β„•) : (pochhammer β„• b).eval a = (a + b - 1).desc_factorial b := begin cases b, { rw [nat.desc_factorial_zero, pochhammer_zero, polynomial.eval_one] }, rw [nat.add_succ, nat.succ_sub_succ, tsub_zero], cases a, { rw [pochhammer_ne_zero_eval_zero _ b.succ_ne_zero, zero_add, nat.desc_factorial_of_lt b.lt_succ_self] }, { rw [nat.succ_add, ←nat.add_succ, nat.add_desc_factorial_eq_asc_factorial, pochhammer_nat_eq_asc_factorial] } end end semiring section ordered_semiring variables {S : Type*} [ordered_semiring S] [nontrivial S] lemma pochhammer_pos (n : β„•) (s : S) (h : 0 < s) : 0 < (pochhammer S n).eval s := begin induction n with n ih, { simp only [nat.nat_zero_eq_zero, pochhammer_zero, eval_one], exact zero_lt_one, }, { rw [pochhammer_succ_right, mul_add, eval_add, ←nat.cast_comm, eval_nat_cast_mul, eval_mul_X, nat.cast_comm, ←mul_add], exact mul_pos ih (lt_of_lt_of_le h ((le_add_iff_nonneg_right _).mpr (nat.cast_nonneg n))), } end end ordered_semiring section factorial open_locale nat variables (S : Type*) [semiring S] (r n : β„•) @[simp] lemma pochhammer_eval_one (S : Type*) [semiring S] (n : β„•) : (pochhammer S n).eval (1 : S) = (n! : S) := by rw_mod_cast [pochhammer_nat_eq_asc_factorial, nat.zero_asc_factorial] lemma factorial_mul_pochhammer (S : Type*) [semiring S] (r n : β„•) : (r! : S) * (pochhammer S n).eval (r + 1) = (r + n)! := by rw_mod_cast [pochhammer_nat_eq_asc_factorial, nat.factorial_mul_asc_factorial] lemma pochhammer_nat_eval_succ (r : β„•) : βˆ€ n : β„•, n * (pochhammer β„• r).eval (n + 1) = (n + r) * (pochhammer β„• r).eval n | 0 := begin by_cases h : r = 0, { simp only [h, zero_mul, zero_add], }, { simp only [pochhammer_eval_zero, zero_mul, if_neg h, mul_zero], } end | (k + 1) := by simp only [pochhammer_nat_eq_asc_factorial, nat.succ_asc_factorial, add_right_comm] lemma pochhammer_eval_succ (r n : β„•) : (n : S) * (pochhammer S r).eval (n + 1 : S) = (n + r) * (pochhammer S r).eval n := by exact_mod_cast congr_arg nat.cast (pochhammer_nat_eval_succ r n) end factorial
f154d8efa6f52eac328b7b0bd85e8ad3104ed698
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/parser/level.lean
b7a888a114c35d978cf13d122ee796b1affbc7f6
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
1,273
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, Sebastian Ullrich -/ prelude import init.lean.parser.parser namespace Lean namespace Parser @[init mkBuiltinParsingTablesRef] constant builtinLevelParsingTable : IO.Ref ParsingTables := default _ @[init] def regBuiltinLevelParserAttr : IO Unit := registerBuiltinParserAttribute `builtinLevelParser `Lean.Parser.builtinLevelParsingTable def levelParserFn {k : ParserKind} (rbp : Nat) : ParserFn k := fun _ => runBuiltinParser "universe level" builtinLevelParsingTable rbp @[inline] def levelParser {k : ParserKind} (rbp : Nat := 0) : Parser k := { fn := levelParserFn rbp } namespace Level @[builtinLevelParser] def paren := parser! symbol "(" appPrec >> levelParser >> ")" @[builtinLevelParser] def max := parser! "max" >> many1 (levelParser appPrec) @[builtinLevelParser] def imax := parser! "imax" >> many1 (levelParser appPrec) @[builtinLevelParser] def hole := parser! "_" @[builtinLevelParser] def num : Parser := numLit @[builtinLevelParser] def ident : Parser := ident @[builtinLevelParser] def addLit := tparser! pushLeading >> symbol "+" (65:Nat) >> numLit end Level end Parser end Lean
1c8b1bf3c79ec4736a3b91409c6c346de483b783
bdb33f8b7ea65f7705fc342a178508e2722eb851
/algebra/euclidean_domain.lean
ed8b93a2a547742d2149e85876100ff72852ca54
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
7,197
lean
/- Copyright (c) 2018 Louis Carlin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Louis Carlin Euclidean domains and Euclidean algorithm (extended to come) A lot is based on pre-existing code in mathlib for natural number gcds -/ import tactic.ring universe u class euclidean_domain (Ξ± : Type u) [decidable_eq Ξ±] extends integral_domain Ξ± := (quotient : Ξ± β†’ Ξ± β†’ Ξ±) (remainder : Ξ± β†’ Ξ± β†’ Ξ±) (quotient_mul_add_remainder_eq : βˆ€ a b, (quotient a b) * b + (remainder a b) = a) -- This could be changed to the same order as int.mod_add_div. We normally write qb+r rather than r + qb though. (valuation : Ξ± β†’ β„•) (valuation_remainder_lt : βˆ€ a b, b β‰  0 β†’ valuation (remainder a b) < valuation b) (le_valuation_mul : βˆ€ a b, b β‰  0 β†’ valuation a ≀ valuation (a*b)) /- le_valuation_mul is often not a required in definitions of a euclidean domain since given the other properties we can show there is a (noncomputable) euclidean domain Ξ± with the property le_valuation_mul. So potentially this definition could be split into two different ones (euclidean_domain_weak and euclidean_domain_strong) with a noncomputable function from weak to strong. I've currently divided the lemmas into strong and weak depending on whether they require le_valuation_mul or not. -/ namespace euclidean_domain variable {Ξ± : Type u} variables [decidable_eq Ξ±] [euclidean_domain Ξ±] instance : has_div Ξ± := ⟨quotient⟩ instance : has_mod Ξ± := ⟨remainder⟩ instance : has_sizeof Ξ± := ⟨valuation⟩ lemma gcd_decreasing (a b : Ξ±) (w : a β‰  0) : has_well_founded.r (b % a) a := valuation_remainder_lt b a w def gcd : Ξ± β†’ Ξ± β†’ Ξ± | a b := if a_zero : a = 0 then b else have h : has_well_founded.r (b % a) a := gcd_decreasing a b a_zero, gcd (b%a) a /- weak lemmas -/ @[simp] lemma mod_zero (a : Ξ±) : a % 0 = a := by simpa using quotient_mul_add_remainder_eq a 0 lemma dvd_mod_self (a : Ξ±) : a ∣ a % a := begin let d := (a/a)*a, -- ring tactic can't solve things without this have : a%a = a - (a/a)*a, from calc a%a = d + a%a - d : by ring ... = (a/a)*a + a%a - (a/a)*a : by dsimp [d]; refl ... = a - (a/a)*a : by simp [(%), (/), quotient_mul_add_remainder_eq a a], rw this, exact dvd_sub (dvd_refl a) (dvd_mul_left a (a/a)), end lemma mod_lt : βˆ€ (a : Ξ±) {b : Ξ±}, valuation b > valuation (0:Ξ±) β†’ valuation (a%b) < valuation b := begin intros a b h, by_cases b_zero : (b=0), { rw b_zero at h, have := lt_irrefl (valuation (0:Ξ±)), contradiction }, { exact valuation_remainder_lt a b b_zero } end lemma neq_zero_lt_mod_lt (a b : Ξ±) : b β‰  0 β†’ valuation (a%b) < valuation b | hnb := valuation_remainder_lt a b hnb lemma dvd_mod {a b c : Ξ±} : c ∣ a β†’ c ∣ b β†’ c ∣ a % b := begin intros dvd_a dvd_b, have : remainder a b = a - quotient a b * b, from calc a%b = quotient a b * b + a%b - quotient a b * b : by ring ... = a - quotient a b * b : by {dsimp[(%)]; rw (quotient_mul_add_remainder_eq a b)}, dsimp [(%)], rw this, exact dvd_sub dvd_a (dvd_mul_of_dvd_right dvd_b (a/b)), end /- strong lemmas -/ lemma val_lt_one (a : Ξ±) : valuation a < valuation (1:Ξ±) β†’ a = 0 := begin intro a_lt, by_cases a = 0, { exact h }, { have := le_valuation_mul (1:Ξ±) a h, simp at this, have := not_le_of_lt a_lt, contradiction } end lemma val_dvd_le : βˆ€ a b : Ξ±, b ∣ a β†’ a β‰  0 β†’ valuation b ≀ valuation a | _ b ⟨d, rfl⟩ ha := begin by_cases d = 0, { simp[h] at ha, contradiction }, { exact le_valuation_mul b d h } end @[simp] lemma mod_one (a : Ξ±) : a % 1 = 0 := val_lt_one _ (valuation_remainder_lt a 1 one_ne_zero) @[simp] lemma zero_mod (b : Ξ±) : 0 % b = 0 := begin have h : remainder 0 b = b * (-quotient 0 b ), from calc remainder 0 b = quotient 0 b * b + remainder 0 b + b * (-quotient 0 b ) : by ring ... = b * (-quotient 0 b ) : by rw [quotient_mul_add_remainder_eq 0 b, zero_add], by_cases quotient_zero : (-quotient 0 b) = 0, { simp[quotient_zero] at h, exact h }, { by_cases h'' : b = 0, { rw h'', simp }, { have := not_le_of_lt (valuation_remainder_lt 0 b h''), rw h at this, have := le_valuation_mul b (-quotient 0 b) quotient_zero, contradiction }} end @[simp] lemma zero_div (b : Ξ±) (hnb : b β‰  0) : 0 / b = 0 := begin have h1 : remainder 0 b = 0, from zero_mod b, have h2 := quotient_mul_add_remainder_eq 0 b, simp[h1] at h2, cases eq_zero_or_eq_zero_of_mul_eq_zero h2, { exact h }, { contradiction } end @[simp] lemma mod_self (a : Ξ±) : a % a = 0 := let ⟨m, a_mul⟩ := dvd_mod_self a in begin by_cases m = 0, { rw [h, mul_zero] at a_mul, exact a_mul }, { by_cases a_zero : a = 0, { rw a_zero, simp }, { have := le_valuation_mul a m h, rw ←a_mul at this, have := not_le_of_lt (valuation_remainder_lt a a a_zero), contradiction}} end lemma div_self (a : Ξ±) : a β‰  0 β†’ a / a = (1:Ξ±) := begin intro hna, have wit_aa := quotient_mul_add_remainder_eq a a, have a_mod_a := mod_self a, dsimp [(%)] at a_mod_a, simp [a_mod_a] at wit_aa, have h1 : 1 * a = a, from one_mul a, conv at wit_aa {for a [4] {rw ←h1}}, exact eq_of_mul_eq_mul_right hna wit_aa end /- weak gcd lemmas -/ @[simp] theorem gcd_zero_left (a : Ξ±) : gcd 0 a = a := begin rw gcd, simp, end @[elab_as_eliminator] theorem gcd.induction {P : Ξ± β†’ Ξ± β†’ Prop} (a b : Ξ±) (H0 : βˆ€ x, P 0 x) (H1 : βˆ€ a b, a β‰  0 β†’ P (b%a) a β†’ P a b) : P a b := @well_founded.induction _ _ (has_well_founded.wf Ξ±) (Ξ»a, βˆ€b, P a b) a begin intros c IH, by_cases c = 0, { rw h, exact H0 }, { intro b, exact H1 c b (h) (IH (b%c) (neq_zero_lt_mod_lt b c h) c) } end b theorem gcd_dvd (a b : Ξ±) : (gcd a b ∣ a) ∧ (gcd a b ∣ b) := gcd.induction a b (Ξ» b, by simp) begin intros a b aneq h_dvd, rw gcd, simp [aneq], induction h_dvd, split, { exact h_dvd_right }, { conv {for b [2] {rw ←(quotient_mul_add_remainder_eq b a)}}, have h_dvd_right_a:= dvd_mul_of_dvd_right h_dvd_right (b/a), exact dvd_add h_dvd_right_a h_dvd_left } end theorem gcd_dvd_left (a b : Ξ±) : gcd a b ∣ a := (gcd_dvd a b).left theorem gcd_dvd_right (a b : Ξ±) : gcd a b ∣ b := (gcd_dvd a b).right theorem dvd_gcd {a b c : Ξ±} : c ∣ a β†’ c ∣ b β†’ c ∣ gcd a b := gcd.induction a b begin intros b dvd_0 dvd_b, simp, exact dvd_b end begin intros a b hna d dvd_a dvd_b, rw gcd, simp [hna], exact d (dvd_mod dvd_b dvd_a) dvd_a, end /- strong gcd lemmas -/ @[simp] theorem gcd_zero_right (a : Ξ±) : gcd a 0 = a := begin by_cases (a=0), { simp[h] }, { rw gcd, simp [h] } end @[simp] theorem gcd_one_left (a : Ξ±) : gcd 1 a = 1 := begin rw [gcd], simp, end theorem gcd_next (a b : Ξ±) : gcd a b = gcd (b % a) a := begin by_cases (a=0), { simp [h] }, { rw gcd, simp [h] } end @[simp] theorem gcd_self (a : Ξ±) : gcd a a = a := by rw [gcd_next a a, mod_self a, gcd_zero_left] end euclidean_domain
7e83e84ea188a916ad56712681cc8eae45c6a82e
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/analytic/inverse.lean
7b8f71305b137ce23f59511056312b596cf24891
[ "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
27,251
lean
/- Copyright (c) 2021 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: SΓ©bastien GouΓ«zel -/ import analysis.analytic.composition import tactic.congrm /-! # Inverse of analytic functions We construct the left and right inverse of a formal multilinear series with invertible linear term, we prove that they coincide and study their properties (notably convergence). ## Main statements * `p.left_inv i`: the formal left inverse of the formal multilinear series `p`, for `i : E ≃L[π•œ] F` which coincides with `p₁`. * `p.right_inv i`: the formal right inverse of the formal multilinear series `p`, for `i : E ≃L[π•œ] F` which coincides with `p₁`. * `p.left_inv_comp` says that `p.left_inv i` is indeed a left inverse to `p` when `p₁ = i`. * `p.right_inv_comp` says that `p.right_inv i` is indeed a right inverse to `p` when `p₁ = i`. * `p.left_inv_eq_right_inv`: the two inverses coincide. * `p.radius_right_inv_pos_of_radius_pos`: if a power series has a positive radius of convergence, then so does its inverse. -/ open_locale big_operators classical topological_space open finset filter namespace formal_multilinear_series variables {π•œ : Type*} [nondiscrete_normed_field π•œ] {E : Type*} [normed_group E] [normed_space π•œ E] {F : Type*} [normed_group F] [normed_space π•œ F] /-! ### The left inverse of a formal multilinear series -/ /-- The left inverse of a formal multilinear series, where the `n`-th term is defined inductively in terms of the previous ones to make sure that `(left_inv p i) ∘ p = id`. For this, the linear term `p₁` in `p` should be invertible. In the definition, `i` is a linear isomorphism that should coincide with `p₁`, so that one can use its inverse in the construction. The definition does not use that `i = p₁`, but proofs that the definition is well-behaved do. The `n`-th term in `q ∘ p` is `βˆ‘ qβ‚– (p_{j₁}, ..., p_{jβ‚–})` over `j₁ + ... + jβ‚– = n`. In this expression, `qβ‚™` appears only once, in `qβ‚™ (p₁, ..., p₁)`. We adjust the definition so that this term compensates the rest of the sum, using `i⁻¹` as an inverse to `p₁`. These formulas only make sense when the constant term `pβ‚€` vanishes. The definition we give is general, but it ignores the value of `pβ‚€`. -/ noncomputable def left_inv (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) : formal_multilinear_series π•œ F E | 0 := 0 | 1 := (continuous_multilinear_curry_fin1 π•œ F E).symm i.symm | (n+2) := - βˆ‘ c : {c : composition (n+2) // c.length < n + 2}, have (c : composition (n+2)).length < n+2 := c.2, (left_inv (c : composition (n+2)).length).comp_along_composition (p.comp_continuous_linear_map i.symm) c @[simp] lemma left_inv_coeff_zero (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) : p.left_inv i 0 = 0 := by rw left_inv @[simp] lemma left_inv_coeff_one (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) : p.left_inv i 1 = (continuous_multilinear_curry_fin1 π•œ F E).symm i.symm := by rw left_inv /-- The left inverse does not depend on the zeroth coefficient of a formal multilinear series. -/ lemma left_inv_remove_zero (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) : p.remove_zero.left_inv i = p.left_inv i := begin ext1 n, induction n using nat.strong_rec' with n IH, cases n, { simp }, -- if one replaces `simp` with `refl`, the proof times out in the kernel. cases n, { simp }, -- TODO: why? simp only [left_inv, neg_inj], refine finset.sum_congr rfl (Ξ» c cuniv, _), rcases c with ⟨c, hc⟩, ext v, dsimp, simp [IH _ hc], end /-- The left inverse to a formal multilinear series is indeed a left inverse, provided its linear term is invertible. -/ lemma left_inv_comp (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) (h : p 1 = (continuous_multilinear_curry_fin1 π•œ E F).symm i) : (left_inv p i).comp p = id π•œ E := begin ext n v, cases n, { simp only [left_inv, continuous_multilinear_map.zero_apply, id_apply_ne_one, ne.def, not_false_iff, zero_ne_one, comp_coeff_zero']}, cases n, { simp only [left_inv, comp_coeff_one, h, id_apply_one, continuous_linear_equiv.coe_apply, continuous_linear_equiv.symm_apply_apply, continuous_multilinear_curry_fin1_symm_apply] }, have A : (finset.univ : finset (composition (n+2))) = {c | composition.length c < n + 2}.to_finset βˆͺ {composition.ones (n+2)}, { refine subset.antisymm (Ξ» c hc, _) (subset_univ _), by_cases h : c.length < n + 2, { simp [h] }, { simp [composition.eq_ones_iff_le_length.2 (not_lt.1 h)] } }, have B : disjoint ({c | composition.length c < n + 2} : set (composition (n + 2))).to_finset {composition.ones (n+2)}, by simp, have C : (p.left_inv i (composition.ones (n + 2)).length) (Ξ» (j : fin (composition.ones n.succ.succ).length), p 1 (Ξ» k, v ((fin.cast_le (composition.length_le _)) j))) = p.left_inv i (n+2) (Ξ» (j : fin (n+2)), p 1 (Ξ» k, v j)), { apply formal_multilinear_series.congr _ (composition.ones_length _) (Ξ» j hj1 hj2, _), exact formal_multilinear_series.congr _ rfl (Ξ» k hk1 hk2, by congr) }, have D : p.left_inv i (n+2) (Ξ» (j : fin (n+2)), p 1 (Ξ» k, v j)) = - βˆ‘ (c : composition (n + 2)) in {c : composition (n + 2) | c.length < n + 2}.to_finset, (p.left_inv i c.length) (p.apply_composition c v), { simp only [left_inv, continuous_multilinear_map.neg_apply, neg_inj, continuous_multilinear_map.sum_apply], convert (sum_to_finset_eq_subtype (Ξ» (c : composition (n+2)), c.length < n+2) (Ξ» (c : composition (n+2)), (continuous_multilinear_map.comp_along_composition (p.comp_continuous_linear_map ↑(i.symm)) c (p.left_inv i c.length)) (Ξ» (j : fin (n + 2)), p 1 (Ξ» (k : fin 1), v j)))).symm.trans _, simp only [comp_continuous_linear_map_apply_composition, continuous_multilinear_map.comp_along_composition_apply], congr, ext c, congr, ext k, simp [h] }, simp [formal_multilinear_series.comp, show n + 2 β‰  1, by dec_trivial, A, finset.sum_union B, apply_composition_ones, C, D], end /-! ### The right inverse of a formal multilinear series -/ /-- The right inverse of a formal multilinear series, where the `n`-th term is defined inductively in terms of the previous ones to make sure that `p ∘ (right_inv p i) = id`. For this, the linear term `p₁` in `p` should be invertible. In the definition, `i` is a linear isomorphism that should coincide with `p₁`, so that one can use its inverse in the construction. The definition does not use that `i = p₁`, but proofs that the definition is well-behaved do. The `n`-th term in `p ∘ q` is `βˆ‘ pβ‚– (q_{j₁}, ..., q_{jβ‚–})` over `j₁ + ... + jβ‚– = n`. In this expression, `qβ‚™` appears only once, in `p₁ (qβ‚™)`. We adjust the definition of `qβ‚™` so that this term compensates the rest of the sum, using `i⁻¹` as an inverse to `p₁`. These formulas only make sense when the constant term `pβ‚€` vanishes. The definition we give is general, but it ignores the value of `pβ‚€`. -/ noncomputable def right_inv (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) : formal_multilinear_series π•œ F E | 0 := 0 | 1 := (continuous_multilinear_curry_fin1 π•œ F E).symm i.symm | (n+2) := let q : formal_multilinear_series π•œ F E := Ξ» k, if h : k < n + 2 then right_inv k else 0 in - (i.symm : F β†’L[π•œ] E).comp_continuous_multilinear_map ((p.comp q) (n+2)) @[simp] lemma right_inv_coeff_zero (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) : p.right_inv i 0 = 0 := by rw right_inv @[simp] lemma right_inv_coeff_one (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) : p.right_inv i 1 = (continuous_multilinear_curry_fin1 π•œ F E).symm i.symm := by rw right_inv /-- The right inverse does not depend on the zeroth coefficient of a formal multilinear series. -/ lemma right_inv_remove_zero (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) : p.remove_zero.right_inv i = p.right_inv i := begin ext1 n, induction n using nat.strong_rec' with n IH, rcases n with _|_|n, { simp only [right_inv_coeff_zero] }, { simp only [right_inv_coeff_one] }, simp only [right_inv, neg_inj], rw remove_zero_comp_of_pos _ _ (add_pos_of_nonneg_of_pos (n.zero_le) zero_lt_two), congrm i.symm.to_continuous_linear_map.comp_continuous_multilinear_map (p.comp (Ξ» k, _) _), by_cases hk : k < n+2; simp [hk, IH] end lemma comp_right_inv_aux1 {n : β„•} (hn : 0 < n) (p : formal_multilinear_series π•œ E F) (q : formal_multilinear_series π•œ F E) (v : fin n β†’ F) : p.comp q n v = (βˆ‘ (c : composition n) in {c : composition n | 1 < c.length}.to_finset, p c.length (q.apply_composition c v)) + p 1 (Ξ» i, q n v) := begin have A : (finset.univ : finset (composition n)) = {c | 1 < composition.length c}.to_finset βˆͺ {composition.single n hn}, { refine subset.antisymm (Ξ» c hc, _) (subset_univ _), by_cases h : 1 < c.length, { simp [h] }, { have : c.length = 1, by { refine (eq_iff_le_not_lt.2 ⟨ _, h⟩).symm, exact c.length_pos_of_pos hn }, rw ← composition.eq_single_iff_length hn at this, simp [this] } }, have B : disjoint ({c | 1 < composition.length c} : set (composition n)).to_finset {composition.single n hn}, by simp, have C : p (composition.single n hn).length (q.apply_composition (composition.single n hn) v) = p 1 (Ξ» (i : fin 1), q n v), { apply p.congr (composition.single_length hn) (Ξ» j hj1 hj2, _), simp [apply_composition_single] }, simp [formal_multilinear_series.comp, A, finset.sum_union B, C], end lemma comp_right_inv_aux2 (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) (n : β„•) (v : fin (n + 2) β†’ F) : βˆ‘ (c : composition (n + 2)) in {c : composition (n + 2) | 1 < c.length}.to_finset, p c.length (apply_composition (Ξ» (k : β„•), ite (k < n + 2) (p.right_inv i k) 0) c v) = βˆ‘ (c : composition (n + 2)) in {c : composition (n + 2) | 1 < c.length}.to_finset, p c.length ((p.right_inv i).apply_composition c v) := begin have N : 0 < n + 2, by dec_trivial, refine sum_congr rfl (Ξ» c hc, p.congr rfl (Ξ» j hj1 hj2, _)), have : βˆ€ k, c.blocks_fun k < n + 2, { simp only [set.mem_to_finset, set.mem_set_of_eq] at hc, simp [← composition.ne_single_iff N, composition.eq_single_iff_length, ne_of_gt hc] }, simp [apply_composition, this], end /-- The right inverse to a formal multilinear series is indeed a right inverse, provided its linear term is invertible and its constant term vanishes. -/ lemma comp_right_inv (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) (h : p 1 = (continuous_multilinear_curry_fin1 π•œ E F).symm i) (h0 : p 0 = 0) : p.comp (right_inv p i) = id π•œ F := begin ext n v, cases n, { simp only [h0, continuous_multilinear_map.zero_apply, id_apply_ne_one, ne.def, not_false_iff, zero_ne_one, comp_coeff_zero']}, cases n, { simp only [comp_coeff_one, h, right_inv, continuous_linear_equiv.apply_symm_apply, id_apply_one, continuous_linear_equiv.coe_apply, continuous_multilinear_curry_fin1_symm_apply] }, have N : 0 < n+2, by dec_trivial, simp [comp_right_inv_aux1 N, h, right_inv, lt_irrefl n, show n + 2 β‰  1, by dec_trivial, ← sub_eq_add_neg, sub_eq_zero, comp_right_inv_aux2], end lemma right_inv_coeff (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) (n : β„•) (hn : 2 ≀ n) : p.right_inv i n = - (i.symm : F β†’L[π•œ] E).comp_continuous_multilinear_map (βˆ‘ c in ({c | 1 < composition.length c}.to_finset : finset (composition n)), p.comp_along_composition (p.right_inv i) c) := begin cases n, { exact false.elim (zero_lt_two.not_le hn) }, cases n, { exact false.elim (one_lt_two.not_le hn) }, simp only [right_inv, neg_inj], congr' 1, ext v, have N : 0 < n + 2, by dec_trivial, have : (p 1) (Ξ» (i : fin 1), 0) = 0 := continuous_multilinear_map.map_zero _, simp [comp_right_inv_aux1 N, lt_irrefl n, this, comp_right_inv_aux2] end /-! ### Coincidence of the left and the right inverse -/ private lemma left_inv_eq_right_inv_aux (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) (h : p 1 = (continuous_multilinear_curry_fin1 π•œ E F).symm i) (h0 : p 0 = 0) : left_inv p i = right_inv p i := calc left_inv p i = (left_inv p i).comp (id π•œ F) : by simp ... = (left_inv p i).comp (p.comp (right_inv p i)) : by rw comp_right_inv p i h h0 ... = ((left_inv p i).comp p).comp (right_inv p i) : by rw comp_assoc ... = (id π•œ E).comp (right_inv p i) : by rw left_inv_comp p i h ... = right_inv p i : by simp /-- The left inverse and the right inverse of a formal multilinear series coincide. This is not at all obvious from their definition, but it follows from uniqueness of inverses (which comes from the fact that composition is associative on formal multilinear series). -/ theorem left_inv_eq_right_inv (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) (h : p 1 = (continuous_multilinear_curry_fin1 π•œ E F).symm i) : left_inv p i = right_inv p i := calc left_inv p i = left_inv p.remove_zero i : by rw left_inv_remove_zero ... = right_inv p.remove_zero i : by { apply left_inv_eq_right_inv_aux; simp [h] } ... = right_inv p i : by rw right_inv_remove_zero /-! ### Convergence of the inverse of a power series Assume that `p` is a convergent multilinear series, and let `q` be its (left or right) inverse. Using the left-inverse formula gives $$ q_n = - (p_1)^{-n} \sum_{k=0}^{n-1} \sum_{i_1 + \dotsc + i_k = n} q_k (p_{i_1}, \dotsc, p_{i_k}). $$ Assume for simplicity that we are in dimension `1` and `p₁ = 1`. In the formula for `qβ‚™`, the term `q_{n-1}` appears with a multiplicity of `n-1` (choosing the index `i_j` for which `i_j = 2` while all the other indices are equal to `1`), which indicates that `qβ‚™` might grow like `n!`. This is bad for summability properties. It turns out that the right-inverse formula is better behaved, and should instead be used for this kind of estimate. It reads $$ q_n = - (p_1)^{-1} \sum_{k=2}^n \sum_{i_1 + \dotsc + i_k = n} p_k (q_{i_1}, \dotsc, q_{i_k}). $$ Here, `q_{n-1}` can only appear in the term with `k = 2`, and it only appears twice, so there is hope this formula can lead to an at most geometric behavior. Let `Qβ‚™ = βˆ₯qβ‚™βˆ₯`. Bounding `βˆ₯pβ‚–βˆ₯` with `C r^k` gives an inequality $$ Q_n ≀ C' \sum_{k=2}^n r^k \sum_{i_1 + \dotsc + i_k = n} Q_{i_1} \dotsm Q_{i_k}. $$ This formula is not enough to prove by naive induction on `n` a bound of the form `Qβ‚™ ≀ D R^n`. However, assuming that the inequality above were an equality, one could get a formula for the generating series of the `Qβ‚™`: $$ \begin{align} Q(z) & := \sum Q_n z^n = Q_1 z + C' \sum_{2 \leq k \leq n} \sum_{i_1 + \dotsc + i_k = n} (r z^{i_1} Q_{i_1}) \dotsm (r z^{i_k} Q_{i_k}) \\ & = Q_1 z + C' \sum_{k = 2}^\infty (\sum_{i_1 \geq 1} r z^{i_1} Q_{i_1}) \dotsm (\sum_{i_k \geq 1} r z^{i_k} Q_{i_k}) \\ & = Q_1 z + C' \sum_{k = 2}^\infty (r Q(z))^k = Q_1 z + C' (r Q(z))^2 / (1 - r Q(z)). \end{align} $$ One can solve this formula explicitly. The solution is analytic in a neighborhood of `0` in `β„‚`, hence its coefficients grow at most geometrically (by a contour integral argument), and therefore the original `Qβ‚™`, which are bounded by these ones, are also at most geometric. This classical argument is not really satisfactory, as it requires an a priori bound on a complex analytic function. Another option would be to compute explicitly its terms (with binomial coefficients) to obtain an explicit geometric bound, but this would be very painful. Instead, we will use the above intuition, but in a slightly different form, with finite sums and an induction. I learnt this trick in [pΓΆschel2017siegelsternberg]. Let $S_n = \sum_{k=1}^n Q_k a^k$ (where `a` is a positive real parameter to be chosen suitably small). The above computation but with finite sums shows that $$ S_n \leq Q_1 a + C' \sum_{k=2}^n (r S_{n-1})^k. $$ In particular, $S_n \leq Q_1 a + C' (r S_{n-1})^2 / (1- r S_{n-1})$. Assume that $S_{n-1} \leq K a$, where `K > Q₁` is fixed and `a` is small enough so that `r K a ≀ 1/2` (to control the denominator). Then this equation gives a bound $S_n \leq Q_1 a + 2 C' r^2 K^2 a^2$. If `a` is small enough, this is bounded by `K a` as the second term is quadratic in `a`, and therefore negligible. By induction, we deduce `Sβ‚™ ≀ K a` for all `n`, which gives in particular the fact that `aⁿ Qβ‚™` remains bounded. -/ /-- First technical lemma to control the growth of coefficients of the inverse. Bound the explicit expression for `βˆ‘_{k<n+1} aᡏ Qβ‚–` in terms of a sum of powers of the same sum one step before, in a general abstract setup. -/ lemma radius_right_inv_pos_of_radius_pos_aux1 (n : β„•) (p : β„• β†’ ℝ) (hp : βˆ€ k, 0 ≀ p k) {r a : ℝ} (hr : 0 ≀ r) (ha : 0 ≀ a) : βˆ‘ k in Ico 2 (n + 1), a ^ k * (βˆ‘ c in ({c | 1 < composition.length c}.to_finset : finset (composition k)), r ^ c.length * ∏ j, p (c.blocks_fun j)) ≀ βˆ‘ j in Ico 2 (n + 1), r ^ j * (βˆ‘ k in Ico 1 n, a ^ k * p k) ^ j := calc βˆ‘ k in Ico 2 (n + 1), a ^ k * (βˆ‘ c in ({c | 1 < composition.length c}.to_finset : finset (composition k)), r ^ c.length * ∏ j, p (c.blocks_fun j)) = βˆ‘ k in Ico 2 (n + 1), (βˆ‘ c in ({c | 1 < composition.length c}.to_finset : finset (composition k)), ∏ j, r * (a ^ (c.blocks_fun j) * p (c.blocks_fun j))) : begin simp_rw [mul_sum], apply sum_congr rfl (Ξ» k hk, _), apply sum_congr rfl (Ξ» c hc, _), rw [prod_mul_distrib, prod_mul_distrib, prod_pow_eq_pow_sum, composition.sum_blocks_fun, prod_const, card_fin], ring, end ... ≀ βˆ‘ d in comp_partial_sum_target 2 (n + 1) n, ∏ (j : fin d.2.length), r * (a ^ d.2.blocks_fun j * p (d.2.blocks_fun j)) : begin rw sum_sigma', refine sum_le_sum_of_subset_of_nonneg _ (Ξ» x hx1 hx2, prod_nonneg (Ξ» j hj, mul_nonneg hr (mul_nonneg (pow_nonneg ha _) (hp _)))), rintros ⟨k, c⟩ hd, simp only [set.mem_to_finset, mem_Ico, mem_sigma, set.mem_set_of_eq] at hd, simp only [mem_comp_partial_sum_target_iff], refine ⟨hd.2, c.length_le.trans_lt hd.1.2, Ξ» j, _⟩, have : c β‰  composition.single k (zero_lt_two.trans_le hd.1.1), by simp [composition.eq_single_iff_length, ne_of_gt hd.2], rw composition.ne_single_iff at this, exact (this j).trans_le (nat.lt_succ_iff.mp hd.1.2) end ... = βˆ‘ e in comp_partial_sum_source 2 (n+1) n, ∏ (j : fin e.1), r * (a ^ e.2 j * p (e.2 j)) : begin symmetry, apply comp_change_of_variables_sum, rintros ⟨k, blocks_fun⟩ H, have K : (comp_change_of_variables 2 (n + 1) n ⟨k, blocks_fun⟩ H).snd.length = k, by simp, congr' 2; try { rw K }, rw fin.heq_fun_iff K.symm, assume j, rw comp_change_of_variables_blocks_fun, end ... = βˆ‘ j in Ico 2 (n+1), r ^ j * (βˆ‘ k in Ico 1 n, a ^ k * p k) ^ j : begin rw [comp_partial_sum_source, ← sum_sigma' (Ico 2 (n + 1)) (Ξ» (k : β„•), (fintype.pi_finset (Ξ» (i : fin k), Ico 1 n) : finset (fin k β†’ β„•))) (Ξ» n e, ∏ (j : fin n), r * (a ^ e j * p (e j)))], apply sum_congr rfl (Ξ» j hj, _), simp only [← @multilinear_map.mk_pi_algebra_apply ℝ (fin j) _ _ ℝ], simp only [← multilinear_map.map_sum_finset (multilinear_map.mk_pi_algebra ℝ (fin j) ℝ) (Ξ» k (m : β„•), r * (a ^ m * p m))], simp only [multilinear_map.mk_pi_algebra_apply], dsimp, simp [prod_const, ← mul_sum, mul_pow], end /-- Second technical lemma to control the growth of coefficients of the inverse. Bound the explicit expression for `βˆ‘_{k<n+1} aᡏ Qβ‚–` in terms of a sum of powers of the same sum one step before, in the specific setup we are interesting in, by reducing to the general bound in `radius_right_inv_pos_of_radius_pos_aux1`. -/ lemma radius_right_inv_pos_of_radius_pos_aux2 {n : β„•} (hn : 2 ≀ n + 1) (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) {r a C : ℝ} (hr : 0 ≀ r) (ha : 0 ≀ a) (hC : 0 ≀ C) (hp : βˆ€ n, βˆ₯p nβˆ₯ ≀ C * r ^ n) : (βˆ‘ k in Ico 1 (n + 1), a ^ k * βˆ₯p.right_inv i kβˆ₯) ≀ βˆ₯(i.symm : F β†’L[π•œ] E)βˆ₯ * a + βˆ₯(i.symm : F β†’L[π•œ] E)βˆ₯ * C * βˆ‘ k in Ico 2 (n + 1), (r * ((βˆ‘ j in Ico 1 n, a ^ j * βˆ₯p.right_inv i jβˆ₯))) ^ k := let I := βˆ₯(i.symm : F β†’L[π•œ] E)βˆ₯ in calc βˆ‘ k in Ico 1 (n + 1), a ^ k * βˆ₯p.right_inv i kβˆ₯ = a * I + βˆ‘ k in Ico 2 (n + 1), a ^ k * βˆ₯p.right_inv i kβˆ₯ : by simp only [linear_isometry_equiv.norm_map, pow_one, right_inv_coeff_one, nat.Ico_succ_singleton, sum_singleton, ← sum_Ico_consecutive _ one_le_two hn] ... = a * I + βˆ‘ k in Ico 2 (n + 1), a ^ k * βˆ₯(i.symm : F β†’L[π•œ] E).comp_continuous_multilinear_map (βˆ‘ c in ({c | 1 < composition.length c}.to_finset : finset (composition k)), p.comp_along_composition (p.right_inv i) c)βˆ₯ : begin congr' 1, apply sum_congr rfl (Ξ» j hj, _), rw [right_inv_coeff _ _ _ (mem_Ico.1 hj).1, norm_neg], end ... ≀ a * βˆ₯(i.symm : F β†’L[π•œ] E)βˆ₯ + βˆ‘ k in Ico 2 (n + 1), a ^ k * (I * (βˆ‘ c in ({c | 1 < composition.length c}.to_finset : finset (composition k)), C * r ^ c.length * ∏ j, βˆ₯p.right_inv i (c.blocks_fun j)βˆ₯)) : begin apply_rules [add_le_add, le_refl, sum_le_sum (Ξ» j hj, _), mul_le_mul_of_nonneg_left, pow_nonneg, ha], apply (continuous_linear_map.norm_comp_continuous_multilinear_map_le _ _).trans, apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), apply (norm_sum_le _ _).trans, apply sum_le_sum (Ξ» c hc, _), apply (comp_along_composition_norm _ _ _).trans, apply mul_le_mul_of_nonneg_right (hp _), exact prod_nonneg (Ξ» j hj, norm_nonneg _), end ... = I * a + I * C * βˆ‘ k in Ico 2 (n + 1), a ^ k * (βˆ‘ c in ({c | 1 < composition.length c}.to_finset : finset (composition k)), r ^ c.length * ∏ j, βˆ₯p.right_inv i (c.blocks_fun j)βˆ₯) : begin simp_rw [mul_assoc C, ← mul_sum, ← mul_assoc, mul_comm _ (βˆ₯↑i.symmβˆ₯), mul_assoc, ← mul_sum, ← mul_assoc, mul_comm _ C, mul_assoc, ← mul_sum], ring, end ... ≀ I * a + I * C * βˆ‘ k in Ico 2 (n+1), (r * ((βˆ‘ j in Ico 1 n, a ^ j * βˆ₯p.right_inv i jβˆ₯))) ^ k : begin apply_rules [add_le_add, le_refl, mul_le_mul_of_nonneg_left, norm_nonneg, hC, mul_nonneg], simp_rw [mul_pow], apply radius_right_inv_pos_of_radius_pos_aux1 n (Ξ» k, βˆ₯p.right_inv i kβˆ₯) (Ξ» k, norm_nonneg _) hr ha, end /-- If a a formal multilinear series has a positive radius of convergence, then its right inverse also has a positive radius of convergence. -/ theorem radius_right_inv_pos_of_radius_pos (p : formal_multilinear_series π•œ E F) (i : E ≃L[π•œ] F) (hp : 0 < p.radius) : 0 < (p.right_inv i).radius := begin obtain ⟨C, r, Cpos, rpos, ple⟩ : βˆƒ C r (hC : 0 < C) (hr : 0 < r), βˆ€ (n : β„•), βˆ₯p nβˆ₯ ≀ C * r ^ n := le_mul_pow_of_radius_pos p hp, let I := βˆ₯(i.symm : F β†’L[π•œ] E)βˆ₯, -- choose `a` small enough to make sure that `βˆ‘_{k ≀ n} aᡏ Qβ‚–` will be controllable by -- induction obtain ⟨a, apos, ha1, ha2⟩ : βˆƒ a (apos : 0 < a), (2 * I * C * r^2 * (I + 1) ^ 2 * a ≀ 1) ∧ (r * (I + 1) * a ≀ 1/2), { have : tendsto (Ξ» a, 2 * I * C * r^2 * (I + 1) ^ 2 * a) (𝓝 0) (𝓝 (2 * I * C * r^2 * (I + 1) ^ 2 * 0)) := tendsto_const_nhds.mul tendsto_id, have A : βˆ€αΆ  a in 𝓝 0, 2 * I * C * r^2 * (I + 1) ^ 2 * a < 1, by { apply (tendsto_order.1 this).2, simp [zero_lt_one] }, have : tendsto (Ξ» a, r * (I + 1) * a) (𝓝 0) (𝓝 (r * (I + 1) * 0)) := tendsto_const_nhds.mul tendsto_id, have B : βˆ€αΆ  a in 𝓝 0, r * (I + 1) * a < 1/2, by { apply (tendsto_order.1 this).2, simp [zero_lt_one] }, have C : βˆ€αΆ  a in 𝓝[>] (0 : ℝ), (0 : ℝ) < a, by { filter_upwards [self_mem_nhds_within] with _ ha using ha }, rcases (C.and ((A.and B).filter_mono inf_le_left)).exists with ⟨a, ha⟩, exact ⟨a, ha.1, ha.2.1.le, ha.2.2.le⟩ }, -- check by induction that the partial sums are suitably bounded, using the choice of `a` and the -- inductive control from Lemma `radius_right_inv_pos_of_radius_pos_aux2`. let S := Ξ» n, βˆ‘ k in Ico 1 n, a ^ k * βˆ₯p.right_inv i kβˆ₯, have IRec : βˆ€ n, 1 ≀ n β†’ S n ≀ (I + 1) * a, { apply nat.le_induction, { simp only [S], rw [Ico_eq_empty_of_le (le_refl 1), sum_empty], exact mul_nonneg (add_nonneg (norm_nonneg _) zero_le_one) apos.le }, { assume n one_le_n hn, have In : 2 ≀ n + 1, by linarith, have Snonneg : 0 ≀ S n := sum_nonneg (Ξ» x hx, mul_nonneg (pow_nonneg apos.le _) (norm_nonneg _)), have rSn : r * S n ≀ 1/2 := calc r * S n ≀ r * ((I+1) * a) : mul_le_mul_of_nonneg_left hn rpos.le ... ≀ 1/2 : by rwa [← mul_assoc], calc S (n + 1) ≀ I * a + I * C * βˆ‘ k in Ico 2 (n + 1), (r * S n)^k : radius_right_inv_pos_of_radius_pos_aux2 In p i rpos.le apos.le Cpos.le ple ... = I * a + I * C * (((r * S n) ^ 2 - (r * S n) ^ (n + 1)) / (1 - r * S n)) : by { rw geom_sum_Ico' _ In, exact ne_of_lt (rSn.trans_lt (by norm_num)) } ... ≀ I * a + I * C * ((r * S n) ^ 2 / (1/2)) : begin apply_rules [add_le_add, le_refl, mul_le_mul_of_nonneg_left, mul_nonneg, norm_nonneg, Cpos.le], refine div_le_div (sq_nonneg _) _ (by norm_num) (by linarith), simp only [sub_le_self_iff], apply pow_nonneg (mul_nonneg rpos.le Snonneg), end ... = I * a + 2 * I * C * (r * S n) ^ 2 : by ring ... ≀ I * a + 2 * I * C * (r * ((I + 1) * a)) ^ 2 : by apply_rules [add_le_add, le_refl, mul_le_mul_of_nonneg_left, mul_nonneg, norm_nonneg, Cpos.le, zero_le_two, pow_le_pow_of_le_left, rpos.le] ... = (I + 2 * I * C * r^2 * (I + 1) ^ 2 * a) * a : by ring ... ≀ (I + 1) * a : by apply_rules [mul_le_mul_of_nonneg_right, apos.le, add_le_add, le_refl] } }, -- conclude that all coefficients satisfy `aⁿ Qβ‚™ ≀ (I + 1) a`. let a' : nnreal := ⟨a, apos.le⟩, suffices H : (a' : ennreal) ≀ (p.right_inv i).radius, by { apply lt_of_lt_of_le _ H, exact_mod_cast apos }, apply le_radius_of_bound _ ((I + 1) * a) (Ξ» n, _), by_cases hn : n = 0, { have : βˆ₯p.right_inv i nβˆ₯ = βˆ₯p.right_inv i 0βˆ₯, by congr; try { rw hn }, simp only [this, norm_zero, zero_mul, right_inv_coeff_zero], apply_rules [mul_nonneg, add_nonneg, norm_nonneg, zero_le_one, apos.le] }, { have one_le_n : 1 ≀ n := bot_lt_iff_ne_bot.2 hn, calc βˆ₯p.right_inv i nβˆ₯ * ↑a' ^ n = a ^ n * βˆ₯p.right_inv i nβˆ₯ : mul_comm _ _ ... ≀ βˆ‘ k in Ico 1 (n + 1), a ^ k * βˆ₯p.right_inv i kβˆ₯ : begin have : βˆ€ k ∈ Ico 1 (n + 1), 0 ≀ a ^ k * βˆ₯p.right_inv i kβˆ₯ := Ξ» k hk, mul_nonneg (pow_nonneg apos.le _) (norm_nonneg _), exact single_le_sum this (by simp [one_le_n]), end ... ≀ (I + 1) * a : IRec (n + 1) (by dec_trivial) } end end formal_multilinear_series
1fc2667a93ae4080683d7a953b9677cce3dd4986
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/assert_tac2.lean
9ca6c3257eea35bc5610874564d3f11a01339139
[ "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,307
lean
import data.nat open nat eq.ops algebra theorem lcm_dvd {m n k : nat} (H1 : m ∣ k) (H2 : (n ∣ k)) : (lcm m n ∣ k) := match eq_zero_or_pos k with | @or.inl _ _ kzero := begin rewrite kzero, apply dvd_zero end | @or.inr _ _ kpos := obtain (p : nat) (km : k = m * p), from exists_eq_mul_right_of_dvd H1, obtain (q : nat) (kn : k = n * q), from exists_eq_mul_right_of_dvd H2, begin have mpos : m > 0, from pos_of_dvd_of_pos H1 kpos, have npos : n > 0, from pos_of_dvd_of_pos H2 kpos, have gcd_pos : gcd m n > 0, from gcd_pos_of_pos_left n mpos, have ppos : p > 0, begin apply pos_of_mul_pos_left, apply (eq.rec_on km), exact kpos end, have qpos : q > 0, from pos_of_mul_pos_left (kn β–Έ kpos), have H3 : p * q * (m * n * gcd p q) = p * q * (gcd m n * k), begin apply sorry end, have H4 : m * n * gcd p q = gcd m n * k, from !eq_of_mul_eq_mul_left (mul_pos ppos qpos) H3, have H5 : gcd m n * (lcm m n * gcd p q) = gcd m n * k, begin rewrite [-mul.assoc, gcd_mul_lcm], exact H4 end, have H6 : lcm m n * gcd p q = k, from !eq_of_mul_eq_mul_left gcd_pos H5, exact (dvd.intro H6) end end
011937e4cf9103b4df106b3fdcd6ac0552e74e70
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/shapes/wide_pullbacks_auto.lean
e64a2c411b2ea3c3260fbdf84c07a6b6dbaa6733
[]
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
6,999
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.limits import Mathlib.category_theory.thin import Mathlib.PostPort universes v l u namespace Mathlib /-! # Wide pullbacks We define the category `wide_pullback_shape`, (resp. `wide_pushout_shape`) which is the category obtained from a discrete category of type `J` by adjoining a terminal (resp. initial) element. Limits of this shape are wide pullbacks (pushouts). The convenience method `wide_cospan` (`wide_span`) constructs a functor from this category, hitting the given morphisms. We use `wide_pullback_shape` to define ordinary pullbacks (pushouts) by using `J := walking_pair`, which allows easy proofs of some related lemmas. Furthermore, wide pullbacks are used to show the existence of limits in the slice category. Namely, if `C` has wide pullbacks then `C/B` has limits for any object `B` in `C`. Typeclasses `has_wide_pullbacks` and `has_finite_wide_pullbacks` assert the existence of wide pullbacks and finite wide pullbacks. -/ namespace category_theory.limits /-- A wide pullback shape for any type `J` can be written simply as `option J`. -/ def wide_pullback_shape (J : Type v) := Option J /-- A wide pushout shape for any type `J` can be written simply as `option J`. -/ def wide_pushout_shape (J : Type v) := Option J namespace wide_pullback_shape /-- The type of arrows for the shape indexing a wide pullback. -/ inductive hom {J : Type v} : wide_pullback_shape J β†’ wide_pullback_shape J β†’ Type v where | id : (X : wide_pullback_shape J) β†’ hom X X | term : (j : J) β†’ hom (some j) none protected instance struct {J : Type v} : category_struct (wide_pullback_shape J) := sorry protected instance hom.inhabited {J : Type v} : Inhabited (hom none none) := { default := hom.id none } protected instance subsingleton_hom {J : Type v} (j : wide_pullback_shape J) (j' : wide_pullback_shape J) : subsingleton (j ⟢ j') := sorry protected instance category {J : Type v} : small_category (wide_pullback_shape J) := thin_category @[simp] theorem hom_id {J : Type v} (X : wide_pullback_shape J) : hom.id X = πŸ™ := rfl /-- Construct a functor out of the wide pullback shape given a J-indexed collection of arrows to a fixed object. -/ @[simp] theorem wide_cospan_map {J : Type v} {C : Type u} [category C] (B : C) (objs : J β†’ C) (arrows : (j : J) β†’ objs j ⟢ B) (X : wide_pullback_shape J) (Y : wide_pullback_shape J) (f : X ⟢ Y) : functor.map (wide_cospan B objs arrows) f = hom.cases_on f (fun (f_1 : wide_pullback_shape J) (H_1 : X = f_1) => Eq._oldrec (fun (H_2 : Y = X) => Eq._oldrec (fun (f : X ⟢ X) (H_3 : f == hom.id X) => Eq._oldrec πŸ™ (wide_cospan._proof_1 X f H_3)) (wide_cospan._proof_2 X Y H_2) f) H_1) (fun (j : J) (H_1 : X = some j) => Eq._oldrec (fun (f : some j ⟢ Y) (H_2 : Y = none) => Eq._oldrec (fun (f : some j ⟢ none) (H_3 : f == hom.term j) => Eq._oldrec (arrows j) (wide_cospan._proof_3 j f H_3)) (wide_cospan._proof_4 Y H_2) f) (wide_cospan._proof_5 X j H_1) f) (wide_cospan._proof_6 X) (wide_cospan._proof_7 Y) (wide_cospan._proof_8 X Y f) := Eq.refl (functor.map (wide_cospan B objs arrows) f) /-- Every diagram is naturally isomorphic (actually, equal) to a `wide_cospan` -/ def diagram_iso_wide_cospan {J : Type v} {C : Type u} [category C] (F : wide_pullback_shape J β₯€ C) : F β‰… wide_cospan (functor.obj F none) (fun (j : J) => functor.obj F (some j)) fun (j : J) => functor.map F (hom.term j) := nat_iso.of_components (fun (j : wide_pullback_shape J) => eq_to_iso sorry) sorry end wide_pullback_shape namespace wide_pushout_shape /-- The type of arrows for the shape indexing a wide psuhout. -/ inductive hom {J : Type v} : wide_pushout_shape J β†’ wide_pushout_shape J β†’ Type v where | id : (X : wide_pushout_shape J) β†’ hom X X | init : (j : J) β†’ hom none (some j) protected instance struct {J : Type v} : category_struct (wide_pushout_shape J) := sorry protected instance hom.inhabited {J : Type v} : Inhabited (hom none none) := { default := hom.id none } protected instance subsingleton_hom {J : Type v} (j : wide_pushout_shape J) (j' : wide_pushout_shape J) : subsingleton (j ⟢ j') := sorry protected instance category {J : Type v} : small_category (wide_pushout_shape J) := thin_category @[simp] theorem hom_id {J : Type v} (X : wide_pushout_shape J) : hom.id X = πŸ™ := rfl /-- Construct a functor out of the wide pushout shape given a J-indexed collection of arrows from a fixed object. -/ @[simp] theorem wide_span_map {J : Type v} {C : Type u} [category C] (B : C) (objs : J β†’ C) (arrows : (j : J) β†’ B ⟢ objs j) (X : wide_pushout_shape J) (Y : wide_pushout_shape J) (f : X ⟢ Y) : functor.map (wide_span B objs arrows) f = hom.cases_on f (fun (f_1 : wide_pushout_shape J) (H_1 : X = f_1) => Eq._oldrec (fun (H_2 : Y = X) => Eq._oldrec (fun (f : X ⟢ X) (H_3 : f == hom.id X) => Eq._oldrec πŸ™ (wide_span._proof_1 X f H_3)) (wide_span._proof_2 X Y H_2) f) H_1) (fun (j : J) (H_1 : X = none) => Eq._oldrec (fun (f : none ⟢ Y) (H_2 : Y = some j) => Eq._oldrec (fun (f : none ⟢ some j) (H_3 : f == hom.init j) => Eq._oldrec (arrows j) (wide_span._proof_3 j f H_3)) (wide_span._proof_4 Y j H_2) f) (wide_span._proof_5 X H_1) f) (wide_span._proof_6 X) (wide_span._proof_7 Y) (wide_span._proof_8 X Y f) := Eq.refl (functor.map (wide_span B objs arrows) f) /-- Every diagram is naturally isomorphic (actually, equal) to a `wide_span` -/ def diagram_iso_wide_span {J : Type v} {C : Type u} [category C] (F : wide_pushout_shape J β₯€ C) : F β‰… wide_span (functor.obj F none) (fun (j : J) => functor.obj F (some j)) fun (j : J) => functor.map F (hom.init j) := nat_iso.of_components (fun (j : wide_pushout_shape J) => eq_to_iso sorry) sorry end wide_pushout_shape /-- `has_wide_pullbacks` represents a choice of wide pullback for every collection of morphisms -/ def has_wide_pullbacks (C : Type u) [category C] := βˆ€ (J : Type v), has_limits_of_shape (wide_pullback_shape J) C /-- `has_wide_pushouts` represents a choice of wide pushout for every collection of morphisms -/ def has_wide_pushouts (C : Type u) [category C] := βˆ€ (J : Type v), has_colimits_of_shape (wide_pushout_shape J) C end Mathlib
4460033b20965805092532025f0b5b6928177dd6
63abd62053d479eae5abf4951554e1064a4c45b4
/src/analysis/convex/basic.lean
9a99772b0b0d4af0908d6728f5398611c21156c4
[ "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
58,022
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov -/ import data.set.intervals.ord_connected import data.set.intervals.image_preimage import data.complex.module import linear_algebra.affine_space.affine_map import algebra.module.ordered /-! # Convex sets and functions on real vector spaces In a real vector space, we define the following objects and properties. * `segment x y` is the closed segment joining `x` and `y`. * A set `s` is `convex` if for any two points `x y ∈ s` it includes `segment x y`; * A function `f : E β†’ Ξ²` is `convex_on` a set `s` if `s` is itself a convex set, and for any two points `x y ∈ s` the segment joining `(x, f x)` to `(y, f y)` is (non-strictly) above the graph of `f`; equivalently, `convex_on f s` means that the epigraph `{p : E Γ— Ξ² | p.1 ∈ s ∧ f p.1 ≀ p.2}` is a convex set; * Center mass of a finite set of points with prescribed weights. * Convex hull of a set `s` is the minimal convex set that includes `s`. * Standard simplex `std_simplex ΞΉ [fintype ΞΉ]` is the intersection of the positive quadrant with the hyperplane `s.sum = 1` in the space `ΞΉ β†’ ℝ`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex, and prove Jensen's inequality. Note: To define convexity for functions `f : E β†’ Ξ²`, we need `Ξ²` to be an ordered vector space, defined using the instance `ordered_semimodule ℝ Ξ²`. ## Notations We use the following local notations: * `I = Icc (0:ℝ) 1`; * `[x, y] = segment x y`. They are defined using `local notation`, so they are not available outside of this file. -/ universes u' u v v' w x variables {E : Type u} {F : Type v} {ΞΉ : Type w} {ΞΉ' : Type x} {Ξ± : Type v'} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] [linear_ordered_field Ξ±] {s : set E} open set linear_map open_locale classical big_operators local notation `I` := (Icc 0 1 : set ℝ) section sets /-! ### Segment -/ /-- Segments in a vector space -/ def segment (x y : E) : set E := {z : E | βˆƒ (a b : ℝ) (ha : 0 ≀ a) (hb : 0 ≀ b) (hab : a + b = 1), a β€’ x + b β€’ y = z} local notation `[`x `, ` y `]` := segment x y lemma segment_symm (x y : E) : [x, y] = [y, x] := set.ext $ Ξ» z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, Ξ» ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma left_mem_segment (x y : E) : x ∈ [x, y] := ⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩ lemma right_mem_segment (x y : E) : y ∈ [x, y] := segment_symm y x β–Έ left_mem_segment y x lemma segment_same (x : E) : [x, x] = {x} := set.ext $ Ξ» z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz, Ξ» h, mem_singleton_iff.1 h β–Έ left_mem_segment z z⟩ lemma segment_eq_image (x y : E) : segment x y = (Ξ» (ΞΈ : ℝ), (1 - ΞΈ) β€’ x + ΞΈ β€’ y) '' I := set.ext $ Ξ» z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab β–Έ le_add_of_nonneg_left ha⟩, hab β–Έ hz β–Έ by simp only [add_sub_cancel]⟩, Ξ» ⟨θ, ⟨hΞΈβ‚€, hΞΈβ‚βŸ©, hz⟩, ⟨1-ΞΈ, ΞΈ, sub_nonneg.2 hθ₁, hΞΈβ‚€, sub_add_cancel _ _, hz⟩⟩ lemma segment_eq_image' (x y : E) : segment x y = (Ξ» (ΞΈ : ℝ), x + ΞΈ β€’ (y - x)) '' I := by { convert segment_eq_image x y, ext ΞΈ, simp only [smul_sub, sub_smul, one_smul], abel } lemma segment_eq_imageβ‚‚ (x y : E) : segment x y = (Ξ» p:ℝ×ℝ, p.1 β€’ x + p.2 β€’ y) '' {p | 0 ≀ p.1 ∧ 0 ≀ p.2 ∧ p.1 + p.2 = 1} := by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma segment_eq_Icc {a b : ℝ} (h : a ≀ b) : [a, b] = Icc a b := begin rw [segment_eq_image'], show (((+) a) ∘ (Ξ» t, t * (b - a))) '' Icc 0 1 = Icc a b, rw [image_comp, image_mul_right_Icc (@zero_le_one ℝ _) (sub_nonneg.2 h), image_const_add_Icc], simp end lemma segment_eq_Icc' (a b : ℝ) : [a, b] = Icc (min a b) (max a b) := by cases le_total a b; [skip, rw segment_symm]; simp [segment_eq_Icc, *] lemma segment_eq_interval (a b : ℝ) : segment a b = interval a b := segment_eq_Icc' _ _ lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b, a + c] ↔ x ∈ [b, c] := begin rw [segment_eq_image', segment_eq_image'], refine exists_congr (Ξ» ΞΈ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj] end lemma segment_translate_preimage (a b c : E) : (Ξ» x, a + x) ⁻¹' [a + b, a + c] = [b, c] := set.ext $ Ξ» x, mem_segment_translate a lemma segment_translate_image (a b c: E) : (Ξ»x, a + x) '' [b, c] = [a + b, a + c] := segment_translate_preimage a b c β–Έ image_preimage_eq $ add_left_surjective a /-! ### Convexity of sets -/ /-- Convexity of sets -/ def convex (s : set E) := βˆ€ ⦃x y : E⦄, x ∈ s β†’ y ∈ s β†’ βˆ€ ⦃a b : ℝ⦄, 0 ≀ a β†’ 0 ≀ b β†’ a + b = 1 β†’ a β€’ x + b β€’ y ∈ s lemma convex_iff_forall_pos : convex s ↔ βˆ€ ⦃x y⦄, x ∈ s β†’ y ∈ s β†’ βˆ€ ⦃a b : ℝ⦄, 0 < a β†’ 0 < b β†’ a + b = 1 β†’ a β€’ x + b β€’ y ∈ s := begin refine ⟨λ h x y hx hy a b ha hb hab, h hx hy (le_of_lt ha) (le_of_lt hb) hab, _⟩, intros h x y hx hy a b ha hb hab, cases eq_or_lt_of_le ha with ha ha, { subst a, rw [zero_add] at hab, simp [hab, hy] }, cases eq_or_lt_of_le hb with hb hb, { subst b, rw [add_zero] at hab, simp [hab, hx] }, exact h hx hy ha hb hab end lemma convex_iff_segment_subset : convex s ↔ βˆ€ ⦃x y⦄, x ∈ s β†’ y ∈ s β†’ [x, y] βŠ† s := by simp only [convex, segment_eq_imageβ‚‚, subset_def, ball_image_iff, prod.forall, mem_set_of_eq, and_imp] lemma convex.segment_subset (h : convex s) {x y:E} (hx : x ∈ s) (hy : y ∈ s) : [x, y] βŠ† s := convex_iff_segment_subset.1 h hx hy /-- Alternative definition of set convexity, in terms of pointwise set operations. -/ lemma convex_iff_pointwise_add_subset: convex s ↔ βˆ€ ⦃a b : ℝ⦄, 0 ≀ a β†’ 0 ≀ b β†’ a + b = 1 β†’ a β€’ s + b β€’ s βŠ† s := iff.intro begin rintros hA a b ha hb hab w ⟨au, bv, ⟨u, hu, rfl⟩, ⟨v, hv, rfl⟩, rfl⟩, exact hA hu hv ha hb hab end (Ξ» h x y hx hy a b ha hb hab, (h ha hb hab) (set.add_mem_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩)) /-- Alternative definition of set convexity, using division -/ lemma convex_iff_div: convex s ↔ βˆ€ ⦃x y : E⦄, x ∈ s β†’ y ∈ s β†’ βˆ€ ⦃a b : ℝ⦄, 0 ≀ a β†’ 0 ≀ b β†’ 0 < a + b β†’ (a/(a+b)) β€’ x + (b/(a+b)) β€’ y ∈ s := ⟨begin assume h x y hx hy a b ha hb hab, apply h hx hy, have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at ha', have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at hb', rw [←add_div], exact div_self (ne_of_lt hab).symm end, begin assume h x y hx hy a b ha hb hab, have h', from h hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ /-! ### Examples of convex sets -/ lemma convex_empty : convex (βˆ… : set E) := by finish lemma convex_singleton (c : E) : convex ({c} : set E) := begin intros x y hx hy a b ha hb hab, rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, ←add_smul, hab, one_smul], exact mem_singleton c end lemma convex_univ : convex (set.univ : set E) := Ξ» _ _ _ _ _ _ _ _ _, trivial lemma convex.inter {t : set E} (hs: convex s) (ht: convex t) : convex (s ∩ t) := Ξ» x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≀ a) (hb : 0 ≀ b) (hab : a + b = 1), ⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩ lemma convex_sInter {S : set (set E)} (h : βˆ€ s ∈ S, convex s) : convex (β‹‚β‚€ S) := assume x y hx hy a b ha hb hab s hs, h s hs (hx s hs) (hy s hs) ha hb hab lemma convex_Inter {ΞΉ : Sort*} {s: ΞΉ β†’ set E} (h: βˆ€ i : ΞΉ, convex (s i)) : convex (β‹‚ i, s i) := (sInter_range s) β–Έ convex_sInter $ forall_range_iff.2 h lemma convex.prod {s : set E} {t : set F} (hs : convex s) (ht : convex t) : convex (s.prod t) := begin intros x y hx hy a b ha hb hab, apply mem_prod.2, exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab, ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩ end lemma convex.combo_to_vadd {a b : ℝ} {x y : E} (h : a + b = 1) : a β€’ x + b β€’ y = b β€’ (y - x) + x := eq.symm (calc b β€’ (y - x) + x = b β€’ (y - x) + (1 : ℝ) β€’ x : by rw [one_smul] ... = b β€’ (y - x) + (a + b) β€’ x : by rw [h] ... = (b β€’ y - b β€’ x) + (a β€’ x + b β€’ x) : by rw [add_smul, smul_sub] ... = a β€’ x + b β€’ y : by abel ) /-- Applying an affine map to an affine combination of two points yields an affine combination of the images. -/ lemma convex.combo_affine_apply {a b : ℝ} {x y : E} {f : E →ᡃ[ℝ] F} (h : a + b = 1) : f (a β€’ x + b β€’ y) = a β€’ f x + b β€’ f y := begin simp only [convex.combo_to_vadd h, ← vsub_eq_sub], exact f.apply_line_map _ _ _, end /-- The preimage of a convex set under an affine map is convex. -/ lemma convex.affine_preimage (f : E →ᡃ[ℝ] F) {s : set F} (hs : convex s) : convex (f ⁻¹' s) := begin intros x y xs ys a b ha hb hab, rw [mem_preimage, convex.combo_affine_apply hab], exact hs xs ys ha hb hab, end /-- The image of a convex set under an affine map is convex. -/ lemma convex.affine_image (f : E →ᡃ[ℝ] F) {s : set E} (hs : convex s) : convex (f '' s) := begin rintros x y ⟨x', ⟨hx', hx'f⟩⟩ ⟨y', ⟨hy', hy'f⟩⟩ a b ha hb hab, refine ⟨a β€’ x' + b β€’ y', ⟨hs hx' hy' ha hb hab, _⟩⟩, rw [convex.combo_affine_apply hab, hx'f, hy'f] end lemma convex.linear_image (hs : convex s) (f : E β†’β‚—[ℝ] F) : convex (image f s) := hs.affine_image f.to_affine_map lemma convex.is_linear_image (hs : convex s) {f : E β†’ F} (hf : is_linear_map ℝ f) : convex (f '' s) := hs.linear_image $ hf.mk' f lemma convex.linear_preimage {s : set F} (hs : convex s) (f : E β†’β‚—[ℝ] F) : convex (preimage f s) := hs.affine_preimage f.to_affine_map lemma convex.is_linear_preimage {s : set F} (hs : convex s) {f : E β†’ F} (hf : is_linear_map ℝ f) : convex (preimage f s) := hs.linear_preimage $ hf.mk' f lemma convex.neg (hs : convex s) : convex ((Ξ» z, -z) '' s) := hs.is_linear_image is_linear_map.is_linear_map_neg lemma convex.neg_preimage (hs : convex s) : convex ((Ξ» z, -z) ⁻¹' s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg lemma convex.smul (c : ℝ) (hs : convex s) : convex (c β€’ s) := hs.linear_image (linear_map.lsmul _ _ c) lemma convex.smul_preimage (c : ℝ) (hs : convex s) : convex ((Ξ» z, c β€’ z) ⁻¹' s) := hs.linear_preimage (linear_map.lsmul _ _ c) lemma convex.add {t : set E} (hs : convex s) (ht : convex t) : convex (s + t) := by { rw ← add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add } lemma convex.sub {t : set E} (hs : convex s) (ht : convex t) : convex ((Ξ»x : E Γ— E, x.1 - x.2) '' (s.prod t)) := (hs.prod ht).is_linear_image is_linear_map.is_linear_map_sub lemma convex.translate (hs : convex s) (z : E) : convex ((Ξ»x, z + x) '' s) := hs.affine_image $ affine_map.const ℝ E z +α΅₯ affine_map.id ℝ E /-- The translation of a convex set is also convex -/ lemma convex.translate_preimage_right (hs : convex s) (a : E) : convex ((Ξ» z, a + z) ⁻¹' s) := hs.affine_preimage $ affine_map.const ℝ E a +α΅₯ affine_map.id ℝ E /-- The translation of a convex set is also convex -/ lemma convex.translate_preimage_left (hs : convex s) (a : E) : convex ((Ξ» z, z + a) ⁻¹' s) := by simpa only [add_comm] using hs.translate_preimage_right a lemma convex.affinity (hs : convex s) (z : E) (c : ℝ) : convex ((Ξ»x, z + c β€’ x) '' s) := hs.affine_image $ affine_map.const ℝ E z +α΅₯ c β€’ affine_map.id ℝ E lemma real.convex_iff_ord_connected {s : set ℝ} : convex s ↔ ord_connected s := begin simp only [convex_iff_segment_subset, segment_eq_interval, ord_connected_iff_interval_subset], exact forall_congr (Ξ» x, forall_swap) end alias real.convex_iff_ord_connected ↔ convex.ord_connected set.ord_connected.convex lemma convex_Iio (r : ℝ) : convex (Iio r) := ord_connected_Iio.convex lemma convex_Ioi (r : ℝ) : convex (Ioi r) := ord_connected_Ioi.convex lemma convex_Iic (r : ℝ) : convex (Iic r) := ord_connected_Iic.convex lemma convex_Ici (r : ℝ) : convex (Ici r) := ord_connected_Ici.convex lemma convex_Ioo (r s : ℝ) : convex (Ioo r s) := ord_connected_Ioo.convex lemma convex_Ico (r s : ℝ) : convex (Ico r s) := ord_connected_Ico.convex lemma convex_Ioc (r : ℝ) (s : ℝ) : convex (Ioc r s) := ord_connected_Ioc.convex lemma convex_Icc (r : ℝ) (s : ℝ) : convex (Icc r s) := ord_connected_Icc.convex lemma convex_interval (r : ℝ) (s : ℝ) : convex (interval r s) := ord_connected_interval.convex lemma convex_segment (a b : E) : convex [a, b] := begin have : (Ξ» (t : ℝ), a + t β€’ (b - a)) = (Ξ»z : E, a + z) ∘ (Ξ»t:ℝ, t β€’ (b - a)) := rfl, rw [segment_eq_image', this, image_comp], refine ((convex_Icc _ _).is_linear_image _).translate _, exact is_linear_map.is_linear_map_smul' _ end lemma convex_halfspace_lt {f : E β†’ ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w < r} := (convex_Iio r).is_linear_preimage h lemma convex_halfspace_le {f : E β†’ ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w ≀ r} := (convex_Iic r).is_linear_preimage h lemma convex_halfspace_gt {f : E β†’ ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r < f w} := (convex_Ioi r).is_linear_preimage h lemma convex_halfspace_ge {f : E β†’ ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r ≀ f w} := (convex_Ici r).is_linear_preimage h lemma convex_hyperplane {f : E β†’ ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w = r} := begin show convex (f ⁻¹' {p | p = r}), rw set_of_eq_eq_singleton, exact (convex_singleton r).is_linear_preimage h end lemma convex_halfspace_re_lt (r : ℝ) : convex {c : β„‚ | c.re < r} := convex_halfspace_lt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_le (r : ℝ) : convex {c : β„‚ | c.re ≀ r} := convex_halfspace_le (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_gt (r : ℝ) : convex {c : β„‚ | r < c.re } := convex_halfspace_gt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_lge (r : ℝ) : convex {c : β„‚ | r ≀ c.re} := convex_halfspace_ge (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_im_lt (r : ℝ) : convex {c : β„‚ | c.im < r} := convex_halfspace_lt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_le (r : ℝ) : convex {c : β„‚ | c.im ≀ r} := convex_halfspace_le (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_gt (r : ℝ) : convex {c : β„‚ | r < c.im } := convex_halfspace_gt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_lge (r : ℝ) : convex {c : β„‚ | r ≀ c.im} := convex_halfspace_ge (is_linear_map.mk complex.add_im complex.smul_im) _ /- Convex combinations in intervals -/ lemma convex.combo_self (a : Ξ±) {x y : Ξ±} (h : x + y = 1) : a = x * a + y * a := calc a = 1 * a : by rw [one_mul] ... = (x + y) * a : by rw [h] ... = x * a + y * a : by rw [add_mul] /-- If x is in an Ioo, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ioo {a b x : Ξ±} (h : a < b) : x ∈ Ioo a b ↔ βˆƒ (x_a x_b : Ξ±), 0 < x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases hab : Β¬a < b, { exfalso; exact hab h }, { refine ⟨(b-x) / (b-a), (x-a) / (b-a), _⟩, refine ⟨div_pos (by linarith) (by linarith), div_pos (by linarith) (by linarith),_,_⟩; { field_simp [show b - a β‰  0, by linarith], ring } } }, { rw [mem_Ioo], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, hβ‚‚βŸ©βŸ©, rw [←hβ‚‚], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If x is in an Ioc, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ioc {a b x : Ξ±} (h : a < b) : x ∈ Ioc a b ↔ βˆƒ (x_a x_b : Ξ±), 0 ≀ x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases h_x : x = b, { exact ⟨0, 1, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioo h).mp ⟨h_ax, lt_of_le_of_ne h_bx h_x⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, by linarith, Ioo_case.2⟩ } }, { rw [mem_Ioc], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, hβ‚‚βŸ©βŸ©, rw [←hβ‚‚], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If x is in an Ico, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ico {a b x : Ξ±} (h : a < b) : x ∈ Ico a b ↔ βˆƒ (x_a x_b : Ξ±), 0 < x_a ∧ 0 ≀ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases h_x : x = a, { exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioo h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } }, { rw [mem_Ico], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, hβ‚‚βŸ©βŸ©, rw [←hβ‚‚], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If x is in an Icc, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Icc {a b x : Ξ±} (h : a ≀ b): x ∈ Icc a b ↔ βˆƒ (x_a x_b : Ξ±), 0 ≀ x_a ∧ 0 ≀ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { intro x_in_I, rw [Icc, mem_set_of_eq] at x_in_I, rcases x_in_I with ⟨h_ax, h_bx⟩, by_cases hab' : a = b, { exact ⟨0, 1, le_refl 0, by linarith, by ring, by linarith⟩ }, change a β‰  b at hab', replace h : a < b, exact lt_of_le_of_ne h hab', by_cases h_x : x = a, { exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioc h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } }, { rw [mem_Icc], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, hβ‚‚βŸ©βŸ©, rw [←hβ‚‚], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end section submodule open submodule lemma submodule.convex (K : submodule ℝ E) : convex (↑K : set E) := by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption } lemma subspace.convex (K : subspace ℝ E) : convex (↑K : set E) := K.convex end submodule end sets section functions variables {Ξ² : Type*} [ordered_add_comm_monoid Ξ²] [semimodule ℝ Ξ²] local notation `[`x `, ` y `]` := segment x y /-! ### Convex functions -/ /-- Convexity of functions -/ def convex_on (s : set E) (f : E β†’ Ξ²) : Prop := convex s ∧ βˆ€ ⦃x y : E⦄, x ∈ s β†’ y ∈ s β†’ βˆ€ ⦃a b : ℝ⦄, 0 ≀ a β†’ 0 ≀ b β†’ a + b = 1 β†’ f (a β€’ x + b β€’ y) ≀ a β€’ f x + b β€’ f y /-- Concavity of functions -/ def concave_on (s : set E) (f : E β†’ Ξ²) : Prop := convex s ∧ βˆ€ ⦃x y : E⦄, x ∈ s β†’ y ∈ s β†’ βˆ€ ⦃a b : ℝ⦄, 0 ≀ a β†’ 0 ≀ b β†’ a + b = 1 β†’ a β€’ f x + b β€’ f y ≀ f (a β€’ x + b β€’ y) /-- A function f is concave iff -f is convex -/ @[simp] lemma neg_convex_on_iff {Ξ³ : Type*} [ordered_add_comm_group Ξ³] [semimodule ℝ Ξ³] (s : set E) (f : E β†’ Ξ³) : convex_on s (-f) ↔ concave_on s f := begin split, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm] at h, exact h }, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm, h] } end /-- A function f is concave iff -f is convex -/ @[simp] lemma neg_concave_on_iff {Ξ³ : Type*} [ordered_add_comm_group Ξ³] [semimodule ℝ Ξ³] (s : set E) (f : E β†’ Ξ³) : concave_on s (-f) ↔ convex_on s f:= by rw [← neg_convex_on_iff s (-f), neg_neg f] lemma convex_on_id {s : set ℝ} (hs : convex s) : convex_on s id := ⟨hs, by { intros, refl }⟩ lemma concave_on_id {s : set ℝ} (hs : convex s) : concave_on s id := ⟨hs, by { intros, refl }⟩ lemma convex_on_const (c : Ξ²) (hs : convex s) : convex_on s (Ξ» x:E, c) := ⟨hs, by { intros, simp only [← add_smul, *, one_smul] }⟩ lemma concave_on_const (c : Ξ²) (hs : convex s) : concave_on s (Ξ» x:E, c) := @convex_on_const _ _ _ _ (order_dual Ξ²) _ _ c hs variables {t : set E} lemma convex_on_iff_div {f : E β†’ Ξ²} : convex_on s f ↔ convex s ∧ βˆ€ ⦃x y : E⦄, x ∈ s β†’ y ∈ s β†’ βˆ€ ⦃a b : ℝ⦄, 0 ≀ a β†’ 0 ≀ b β†’ 0 < a + b β†’ f ((a/(a+b)) β€’ x + (b/(a+b)) β€’ y) ≀ (a/(a+b)) β€’ f x + (b/(a+b)) β€’ f y := and_congr iff.rfl ⟨begin intros h x y hx hy a b ha hb hab, apply h hx hy (div_nonneg ha $ le_of_lt hab) (div_nonneg hb $ le_of_lt hab), rw [←add_div], exact div_self (ne_of_gt hab) end, begin intros h x y hx hy a b ha hb hab, simpa [hab, zero_lt_one] using h hx hy ha hb, end⟩ lemma concave_on_iff_div {f : E β†’ Ξ²} : concave_on s f ↔ convex s ∧ βˆ€ ⦃x y : E⦄, x ∈ s β†’ y ∈ s β†’ βˆ€ ⦃a b : ℝ⦄, 0 ≀ a β†’ 0 ≀ b β†’ 0 < a + b β†’ (a/(a+b)) β€’ f x + (b/(a+b)) β€’ f y ≀ f ((a/(a+b)) β€’ x + (b/(a+b)) β€’ y) := @convex_on_iff_div _ _ _ _ (order_dual Ξ²) _ _ _ /-- For a function on a convex set in a linear ordered space, in order to prove that it is convex it suffices to verify the inequality `f (a β€’ x + b β€’ y) ≀ a β€’ f x + b β€’ f y` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.convex_on_of_lt {f : E β†’ Ξ²} [linear_order E] (hs : convex s) (hf : βˆ€ ⦃x y : E⦄, x ∈ s β†’ y ∈ s β†’ x < y β†’ βˆ€ ⦃a b : ℝ⦄, 0 < a β†’ 0 < b β†’ a + b = 1 β†’ f (a β€’ x + b β€’ y) ≀ a β€’ f x + b β€’ f y) : convex_on s f := begin use hs, intros x y hx hy a b ha hb hab, wlog hxy : x<=y using [x y a b, y x b a], { exact le_total _ _ }, { cases eq_or_lt_of_le hxy with hxy hxy, by { subst y, rw [← add_smul, ← add_smul, hab, one_smul, one_smul] }, cases eq_or_lt_of_le ha with ha ha, by { subst a, rw [zero_add] at hab, subst b, simp }, cases eq_or_lt_of_le hb with hb hb, by { subst b, rw [add_zero] at hab, subst a, simp }, exact hf hx hy hxy ha hb hab } end /-- For a function on a convex set in a linear ordered space, in order to prove that it is concave it suffices to verify the inequality `a β€’ f x + b β€’ f y ≀ f (a β€’ x + b β€’ y)` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.concave_on_of_lt {f : E β†’ Ξ²} [linear_order E] (hs : convex s) (hf : βˆ€ ⦃x y : E⦄, x ∈ s β†’ y ∈ s β†’ x < y β†’ βˆ€ ⦃a b : ℝ⦄, 0 < a β†’ 0 < b β†’ a + b = 1 β†’ a β€’ f x + b β€’ f y ≀ f (a β€’ x + b β€’ y)) : concave_on s f := @linear_order.convex_on_of_lt _ _ _ _ (order_dual Ξ²) _ _ f _ hs hf /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is convex on `D`. This way of proving convexity of a function is used in the proof of convexity of a function with a monotone derivative. -/ lemma convex_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ β†’ ℝ} (hf : βˆ€ {x y z : ℝ}, x ∈ s β†’ z ∈ s β†’ x < y β†’ y < z β†’ (f y - f x) / (y - x) ≀ (f z - f y) / (z - y)) : convex_on s f := linear_order.convex_on_of_lt hs begin assume x z hx hz hxz a b ha hb hab, let y := a * x + b * z, have hxy : x < y, { rw [← one_mul x, ← hab, add_mul], exact add_lt_add_left ((mul_lt_mul_left hb).2 hxz) _ }, have hyz : y < z, { rw [← one_mul z, ← hab, add_mul], exact add_lt_add_right ((mul_lt_mul_left ha).2 hxz) _ }, have : (f y - f x) * (z - y) ≀ (f z - f y) * (y - x), from (div_le_div_iff (sub_pos.2 hxy) (sub_pos.2 hyz)).1 (hf hx hz hxy hyz), have A : z - y + (y - x) = z - x, by abel, have B : 0 < z - x, from sub_pos.2 (lt_trans hxy hyz), rw [sub_mul, sub_mul, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le, ← mul_add, A, ← le_div_iff B, add_div, mul_div_assoc, mul_div_assoc, mul_comm (f x), mul_comm (f z)] at this, rw [eq_comm, ← sub_eq_iff_eq_add] at hab; subst a, convert this; symmetry; simp only [div_eq_iff (ne_of_gt B), y]; ring end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is convex on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on.slope_mono_adjacent {s : set ℝ} {f : ℝ β†’ ℝ} (hf : convex_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f y - f x) / (y - x) ≀ (f z - f y) / (z - y) := begin have h₁ : 0 < y - x := by linarith, have hβ‚‚ : 0 < z - y := by linarith, have h₃ : 0 < z - x := by linarith, suffices : f y / (y - x) + f y / (z - y) ≀ f x / (y - x) + f z / (z - y), by { ring at this ⊒, linarith }, set a := (z - y) / (z - x), set b := (y - x) / (z - x), have heqz : a β€’ x + b β€’ z = y, by { field_simp, rw div_eq_iff; [ring, linarith], }, have key, from hf.2 hx hz (show 0 ≀ a, by apply div_nonneg; linarith) (show 0 ≀ b, by apply div_nonneg; linarith) (show a + b = 1, by { field_simp, rw div_eq_iff; [ring, linarith], }), rw heqz at key, replace key := mul_le_mul_of_nonneg_left key (le_of_lt h₃), field_simp [ne_of_gt h₁, ne_of_gt hβ‚‚, ne_of_gt h₃, mul_comm (z - x) _] at key ⊒, rw div_le_div_right, { linarith, }, { nlinarith, }, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is convex on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ β†’ ℝ} : convex_on s f ↔ (βˆ€ {x y z : ℝ}, x ∈ s β†’ z ∈ s β†’ x < y β†’ y < z β†’ (f y - f x) / (y - x) ≀ (f z - f y) / (z - y)) := ⟨convex_on.slope_mono_adjacent, convex_on_real_of_slope_mono_adjacent hs⟩ /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is concave on `D`. -/ lemma concave_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ β†’ ℝ} (hf : βˆ€ {x y z : ℝ}, x ∈ s β†’ z ∈ s β†’ x < y β†’ y < z β†’ (f z - f y) / (z - y) ≀ (f y - f x) / (y - x)) : concave_on s f := begin rw [←neg_convex_on_iff], apply convex_on_real_of_slope_mono_adjacent hs, intros x y z xs zs xy yz, rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], simp only [hf xs zs xy yz, neg_sub_neg, pi.neg_apply], end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is concave on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on.slope_mono_adjacent {s : set ℝ} {f : ℝ β†’ ℝ} (hf : concave_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f z - f y) / (z - y) ≀ (f y - f x) / (y - x) := begin rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], rw [←neg_sub_neg (f y), ←neg_sub_neg (f z)], simp_rw [←pi.neg_apply], rw [←neg_convex_on_iff] at hf, apply convex_on.slope_mono_adjacent hf; assumption, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is concave on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ β†’ ℝ} : concave_on s f ↔ (βˆ€ {x y z : ℝ}, x ∈ s β†’ z ∈ s β†’ x < y β†’ y < z β†’ (f z - f y) / (z - y) ≀ (f y - f x) / (y - x)) := ⟨concave_on.slope_mono_adjacent, concave_on_real_of_slope_mono_adjacent hs⟩ lemma convex_on.subset {f : E β†’ Ξ²} (h_convex_on : convex_on t f) (h_subset : s βŠ† t) (h_convex : convex s) : convex_on s f := begin apply and.intro h_convex, intros x y hx hy, exact h_convex_on.2 (h_subset hx) (h_subset hy), end lemma concave_on.subset {f : E β†’ Ξ²} (h_concave_on : concave_on t f) (h_subset : s βŠ† t) (h_convex : convex s) : concave_on s f := @convex_on.subset _ _ _ _ (order_dual Ξ²) _ _ t f h_concave_on h_subset h_convex lemma convex_on.add {f g : E β†’ Ξ²} (hf : convex_on s f) (hg : convex_on s g) : convex_on s (Ξ»x, f x + g x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc f (a β€’ x + b β€’ y) + g (a β€’ x + b β€’ y) ≀ (a β€’ f x + b β€’ f y) + (a β€’ g x + b β€’ g y) : add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab) ... = a β€’ f x + a β€’ g x + b β€’ f y + b β€’ g y : by abel ... = a β€’ (f x + g x) + b β€’ (f y + g y) : by simp [smul_add, add_assoc] end lemma concave_on.add {f g : E β†’ Ξ²} (hf : concave_on s f) (hg : concave_on s g) : concave_on s (Ξ»x, f x + g x) := @convex_on.add _ _ _ _ (order_dual Ξ²) _ _ f g hf hg lemma convex_on.smul [ordered_semimodule ℝ Ξ²] {f : E β†’ Ξ²} {c : ℝ} (hc : 0 ≀ c) (hf : convex_on s f) : convex_on s (Ξ»x, c β€’ f x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc c β€’ f (a β€’ x + b β€’ y) ≀ c β€’ (a β€’ f x + b β€’ f y) : smul_le_smul_of_nonneg (hf.2 hx hy ha hb hab) hc ... = a β€’ (c β€’ f x) + b β€’ (c β€’ f y) : by simp only [smul_add, smul_comm] end lemma concave_on.smul [ordered_semimodule ℝ Ξ²] {f : E β†’ Ξ²} {c : ℝ} (hc : 0 ≀ c) (hf : concave_on s f) : concave_on s (Ξ»x, c β€’ f x) := @convex_on.smul _ _ _ _ (order_dual Ξ²) _ _ _ f c hc hf /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment' {Ξ³ : Type*} [linear_ordered_add_comm_group Ξ³] [semimodule ℝ Ξ³] [ordered_semimodule ℝ Ξ³] {f : E β†’ Ξ³} {x y : E} {a b : ℝ} (hf : convex_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≀ a) (hb : 0 ≀ b) (hab : a + b = 1) : f (a β€’ x + b β€’ y) ≀ max (f x) (f y) := calc f (a β€’ x + b β€’ y) ≀ a β€’ f x + b β€’ f y : hf.2 hx hy ha hb hab ... ≀ a β€’ max (f x) (f y) + b β€’ max (f x) (f y) : add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha) (smul_le_smul_of_nonneg (le_max_right _ _) hb) ... ≀ max (f x) (f y) : by rw [←add_smul, hab, one_smul] /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment' {Ξ³ : Type*} [linear_ordered_add_comm_group Ξ³] [semimodule ℝ Ξ³] [ordered_semimodule ℝ Ξ³] {f : E β†’ Ξ³} {x y : E} {a b : ℝ} (hf : concave_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≀ a) (hb : 0 ≀ b) (hab : a + b = 1) : min (f x) (f y) ≀ f (a β€’ x + b β€’ y) := @convex_on.le_on_segment' _ _ _ _ (order_dual Ξ³) _ _ _ f x y a b hf hx hy ha hb hab /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment {Ξ³ : Type*} [linear_ordered_add_comm_group Ξ³] [semimodule ℝ Ξ³] [ordered_semimodule ℝ Ξ³] {f : E β†’ Ξ³} (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : f z ≀ max (f x) (f y) := let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz β–Έ hf.le_on_segment' hx hy ha hb hab /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment {Ξ³ : Type*} [linear_ordered_add_comm_group Ξ³] [semimodule ℝ Ξ³] [ordered_semimodule ℝ Ξ³] {f : E β†’ Ξ³} (hf : concave_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : min (f x) (f y) ≀ f z := @convex_on.le_on_segment _ _ _ _ (order_dual Ξ³) _ _ _ f hf x y z hx hy hz lemma convex_on.convex_le [ordered_semimodule ℝ Ξ²] {f : E β†’ Ξ²} (hf : convex_on s f) (r : Ξ²) : convex {x ∈ s | f x ≀ r} := convex_iff_segment_subset.2 $ Ξ» x y hx hy z hz, begin refine ⟨hf.1.segment_subset hx.1 hy.1 hz,_⟩, rcases hz with ⟨za,zb,hza,hzb,hzazb,H⟩, rw ←H, calc f (za β€’ x + zb β€’ y) ≀ za β€’ (f x) + zb β€’ (f y) : hf.2 hx.1 hy.1 hza hzb hzazb ... ≀ za β€’ r + zb β€’ r : add_le_add (smul_le_smul_of_nonneg hx.2 hza) (smul_le_smul_of_nonneg hy.2 hzb) ... ≀ r : by simp [←add_smul, hzazb] end lemma concave_on.concave_le [ordered_semimodule ℝ Ξ²] {f : E β†’ Ξ²} (hf : concave_on s f) (r : Ξ²) : convex {x ∈ s | r ≀ f x} := @convex_on.convex_le _ _ _ _ (order_dual Ξ²) _ _ _ f hf r lemma convex_on.convex_lt {Ξ³ : Type*} [ordered_cancel_add_comm_monoid Ξ³] [semimodule ℝ Ξ³] [ordered_semimodule ℝ Ξ³] {f : E β†’ Ξ³} (hf : convex_on s f) (r : Ξ³) : convex {x ∈ s | f x < r} := begin intros a b as bs xa xb hxa hxb hxaxb, refine ⟨hf.1 as.1 bs.1 hxa hxb hxaxb,_⟩, dsimp, by_cases H : xa = 0, { have H' : xb = 1 := by rwa [H, zero_add] at hxaxb, rw [H, H', zero_smul, one_smul, zero_add], exact bs.2 }, { calc f (xa β€’ a + xb β€’ b) ≀ xa β€’ (f a) + xb β€’ (f b) : hf.2 as.1 bs.1 hxa hxb hxaxb ... < xa β€’ r + xb β€’ (f b) : (add_lt_add_iff_right (xb β€’ (f b))).mpr (smul_lt_smul_of_pos as.2 (lt_of_le_of_ne hxa (ne.symm H))) ... ≀ xa β€’ r + xb β€’ r : (add_le_add_iff_left (xa β€’ r)).mpr (smul_le_smul_of_nonneg (le_of_lt bs.2) hxb) ... = r : by simp only [←add_smul, hxaxb, one_smul] } end lemma concave_on.convex_lt {Ξ³ : Type*} [ordered_cancel_add_comm_monoid Ξ³] [semimodule ℝ Ξ³] [ordered_semimodule ℝ Ξ³] {f : E β†’ Ξ³} (hf : concave_on s f) (r : Ξ³) : convex {x ∈ s | r < f x} := @convex_on.convex_lt _ _ _ _ (order_dual Ξ³) _ _ _ f hf r lemma convex_on.convex_epigraph {Ξ³ : Type*} [ordered_add_comm_group Ξ³] [semimodule ℝ Ξ³] [ordered_semimodule ℝ Ξ³] {f : E β†’ Ξ³} (hf : convex_on s f) : convex {p : E Γ— Ξ³ | p.1 ∈ s ∧ f p.1 ≀ p.2} := begin rintros ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab, refine ⟨hf.1 hx hy ha hb hab, _⟩, calc f (a β€’ x + b β€’ y) ≀ a β€’ f x + b β€’ f y : hf.2 hx hy ha hb hab ... ≀ a β€’ r + b β€’ t : add_le_add (smul_le_smul_of_nonneg hr ha) (smul_le_smul_of_nonneg ht hb) end lemma concave_on.convex_hypograph {Ξ³ : Type*} [ordered_add_comm_group Ξ³] [semimodule ℝ Ξ³] [ordered_semimodule ℝ Ξ³] {f : E β†’ Ξ³} (hf : concave_on s f) : convex {p : E Γ— Ξ³ | p.1 ∈ s ∧ p.2 ≀ f p.1} := @convex_on.convex_epigraph _ _ _ _ (order_dual Ξ³) _ _ _ f hf lemma convex_on_iff_convex_epigraph {Ξ³ : Type*} [ordered_add_comm_group Ξ³] [semimodule ℝ Ξ³] [ordered_semimodule ℝ Ξ³] {f : E β†’ Ξ³} : convex_on s f ↔ convex {p : E Γ— Ξ³ | p.1 ∈ s ∧ f p.1 ≀ p.2} := begin refine ⟨convex_on.convex_epigraph, Ξ» h, ⟨_, _⟩⟩, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).1 }, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).2 } end lemma concave_on_iff_convex_hypograph {Ξ³ : Type*} [ordered_add_comm_group Ξ³] [semimodule ℝ Ξ³] [ordered_semimodule ℝ Ξ³] {f : E β†’ Ξ³} : concave_on s f ↔ convex {p : E Γ— Ξ³ | p.1 ∈ s ∧ p.2 ≀ f p.1} := @convex_on_iff_convex_epigraph _ _ _ _ (order_dual Ξ³) _ _ _ f /-- If a function is convex on s, it remains convex when precomposed by an affine map -/ lemma convex_on.comp_affine_map {f : F β†’ Ξ²} (g : E →ᡃ[ℝ] F) {s : set F} (hf : convex_on s f) : convex_on (g ⁻¹' s) (f ∘ g) := begin refine ⟨hf.1.affine_preimage _,_⟩, intros x y xs ys a b ha hb hab, calc (f ∘ g) (a β€’ x + b β€’ y) = f (g (a β€’ x + b β€’ y)) : rfl ... = f (a β€’ (g x) + b β€’ (g y)) : by rw [convex.combo_affine_apply hab] ... ≀ a β€’ f (g x) + b β€’ f (g y) : hf.2 xs ys ha hb hab ... = a β€’ (f ∘ g) x + b β€’ (f ∘ g) y : rfl end /-- If a function is concave on s, it remains concave when precomposed by an affine map -/ lemma concave_on.comp_affine_map {f : F β†’ Ξ²} (g : E →ᡃ[ℝ] F) {s : set F} (hf : concave_on s f) : concave_on (g ⁻¹' s) (f ∘ g) := @convex_on.comp_affine_map _ _ _ _ _ _ (order_dual Ξ²) _ _ f g s hf /-- If g is convex on s, so is (g ∘ f) on f ⁻¹' s for a linear f. -/ lemma convex_on.comp_linear_map {g : F β†’ Ξ²} {s : set F} (hg : convex_on s g) (f : E β†’β‚—[ℝ] F) : convex_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If g is concave on s, so is (g ∘ f) on f ⁻¹' s for a linear f. -/ lemma concave_on.comp_linear_map {g : F β†’ Ξ²} {s : set F} (hg : concave_on s g) (f : E β†’β‚—[ℝ] F) : concave_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If a function is convex on s, it remains convex after a translation. -/ lemma convex_on.translate_right {f : E β†’ Ξ²} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((Ξ» z, a + z) ⁻¹' s) (f ∘ (Ξ» z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +α΅₯ affine_map.id ℝ E /-- If a function is concave on s, it remains concave after a translation. -/ lemma concave_on.translate_right {f : E β†’ Ξ²} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((Ξ» z, a + z) ⁻¹' s) (f ∘ (Ξ» z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +α΅₯ affine_map.id ℝ E /-- If a function is convex on s, it remains convex after a translation. -/ lemma convex_on.translate_left {f : E β†’ Ξ²} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((Ξ» z, a + z) ⁻¹' s) (f ∘ (Ξ» z, z + a)) := by simpa only [add_comm] using hf.translate_right /-- If a function is concave on s, it remains concave after a translation. -/ lemma concave_on.translate_left {f : E β†’ Ξ²} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((Ξ» z, a + z) ⁻¹' s) (f ∘ (Ξ» z, z + a)) := by simpa only [add_comm] using hf.translate_right end functions section center_mass /-- Center mass of a finite collection of points with prescribed weights. Note that we require neither `0 ≀ w i` nor `βˆ‘ w = 1`. -/ noncomputable def finset.center_mass (t : finset ΞΉ) (w : ΞΉ β†’ ℝ) (z : ΞΉ β†’ E) : E := (βˆ‘ i in t, w i)⁻¹ β€’ (βˆ‘ i in t, w i β€’ z i) variables (i j : ΞΉ) (c : ℝ) (t : finset ΞΉ) (w : ΞΉ β†’ ℝ) (z : ΞΉ β†’ E) open finset lemma finset.center_mass_empty : (βˆ… : finset ΞΉ).center_mass w z = 0 := by simp only [center_mass, sum_empty, smul_zero] lemma finset.center_mass_pair (hne : i β‰  j) : ({i, j} : finset ΞΉ).center_mass w z = (w i / (w i + w j)) β€’ z i + (w j / (w i + w j)) β€’ z j := by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul] variable {w} lemma finset.center_mass_insert (ha : i βˆ‰ t) (hw : βˆ‘ j in t, w j β‰  0) : (insert i t).center_mass w z = (w i / (w i + βˆ‘ j in t, w j)) β€’ z i + ((βˆ‘ j in t, w j) / (w i + βˆ‘ j in t, w j)) β€’ t.center_mass w z := begin simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm], congr' 2, { apply mul_comm }, { rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div] } end lemma finset.center_mass_singleton (hw : w i β‰  0) : ({i} : finset ΞΉ).center_mass w z = z i := by rw [center_mass, sum_singleton, sum_singleton, ← mul_smul, inv_mul_cancel hw, one_smul] lemma finset.center_mass_eq_of_sum_1 (hw : βˆ‘ i in t, w i = 1) : t.center_mass w z = βˆ‘ i in t, w i β€’ z i := by simp only [finset.center_mass, hw, inv_one, one_smul] lemma finset.center_mass_smul : t.center_mass w (Ξ» i, c β€’ z i) = c β€’ t.center_mass w z := by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc] /-- A convex combination of two centers of mass is a center of mass as well. This version deals with two different index types. -/ lemma finset.center_mass_segment' (s : finset ΞΉ) (t : finset ΞΉ') (ws : ΞΉ β†’ ℝ) (zs : ΞΉ β†’ E) (wt : ΞΉ' β†’ ℝ) (zt : ΞΉ' β†’ E) (hws : βˆ‘ i in s, ws i = 1) (hwt : βˆ‘ i in t, wt i = 1) (a b : ℝ) (hab : a + b = 1): a β€’ s.center_mass ws zs + b β€’ t.center_mass wt zt = (s.image sum.inl βˆͺ t.image sum.inr).center_mass (sum.elim (Ξ» i, a * ws i) (Ξ» j, b * wt j)) (sum.elim zs zt) := begin rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt, smul_sum, smul_sum, ← finset.sum_sum_elim, finset.center_mass_eq_of_sum_1], { congr' with ⟨⟩; simp only [sum.elim_inl, sum.elim_inr, mul_smul] }, { rw [sum_sum_elim, ← mul_sum, ← mul_sum, hws, hwt, mul_one, mul_one, hab] } end /-- A convex combination of two centers of mass is a center of mass as well. This version works if two centers of mass share the set of original points. -/ lemma finset.center_mass_segment (s : finset ΞΉ) (w₁ wβ‚‚ : ΞΉ β†’ ℝ) (z : ΞΉ β†’ E) (hw₁ : βˆ‘ i in s, w₁ i = 1) (hwβ‚‚ : βˆ‘ i in s, wβ‚‚ i = 1) (a b : ℝ) (hab : a + b = 1): a β€’ s.center_mass w₁ z + b β€’ s.center_mass wβ‚‚ z = s.center_mass (Ξ» i, a * w₁ i + b * wβ‚‚ i) z := have hw : βˆ‘ i in s, (a * w₁ i + b * wβ‚‚ i) = 1, by simp only [mul_sum.symm, sum_add_distrib, mul_one, *], by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *] lemma finset.center_mass_ite_eq (hi : i ∈ t) : t.center_mass (Ξ» j, if (i = j) then 1 else 0) z = z i := begin rw [finset.center_mass_eq_of_sum_1], transitivity βˆ‘ j in t, if (i = j) then z i else 0, { congr' with i, split_ifs, exacts [h β–Έ one_smul _ _, zero_smul _ _] }, { rw [sum_ite_eq, if_pos hi] }, { rw [sum_ite_eq, if_pos hi] } end variables {t w} lemma finset.center_mass_subset {t' : finset ΞΉ} (ht : t βŠ† t') (h : βˆ€ i ∈ t', i βˆ‰ t β†’ w i = 0) : t.center_mass w z = t'.center_mass w z := begin rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum], apply sum_subset ht, assume i hit' hit, rw [h i hit' hit, zero_smul, smul_zero] end lemma finset.center_mass_filter_ne_zero : (t.filter (Ξ» i, w i β‰  0)).center_mass w z = t.center_mass w z := finset.center_mass_subset z (filter_subset _) $ Ξ» i hit hit', by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit' variable {z} /-- Center mass of a finite subset of a convex set belongs to the set provided that all weights are non-negative, and the total weight is positive. -/ lemma convex.center_mass_mem (hs : convex s) : (βˆ€ i ∈ t, 0 ≀ w i) β†’ (0 < βˆ‘ i in t, w i) β†’ (βˆ€ i ∈ t, z i ∈ s) β†’ t.center_mass w z ∈ s := begin induction t using finset.induction with i t hi ht, { simp [lt_irrefl] }, intros hβ‚€ hpos hmem, have zi : z i ∈ s, from hmem _ (mem_insert_self _ _), have hsβ‚€ : βˆ€ j ∈ t, 0 ≀ w j, from Ξ» j hj, hβ‚€ j $ mem_insert_of_mem hj, rw [sum_insert hi] at hpos, by_cases hsum_t : βˆ‘ j in t, w j = 0, { have ws : βˆ€ j ∈ t, w j = 0, from (sum_eq_zero_iff_of_nonneg hsβ‚€).1 hsum_t, have wz : βˆ‘ j in t, w j β€’ z j = 0, from sum_eq_zero (Ξ» i hi, by simp [ws i hi]), simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero], simp only [hsum_t, add_zero] at hpos, rw [← mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul], exact zi }, { rw [finset.center_mass_insert _ _ _ hi hsum_t], refine convex_iff_div.1 hs zi (ht hsβ‚€ _ _) _ (sum_nonneg hsβ‚€) hpos, { exact lt_of_le_of_ne (sum_nonneg hsβ‚€) (ne.symm hsum_t) }, { intros j hj, exact hmem j (mem_insert_of_mem hj) }, { exact hβ‚€ _ (mem_insert_self _ _) } } end lemma convex.sum_mem (hs : convex s) (hβ‚€ : βˆ€ i ∈ t, 0 ≀ w i) (h₁ : βˆ‘ i in t, w i = 1) (hz : βˆ€ i ∈ t, z i ∈ s) : βˆ‘ i in t, w i β€’ z i ∈ s := by simpa only [h₁, center_mass, inv_one, one_smul] using hs.center_mass_mem hβ‚€ (h₁.symm β–Έ zero_lt_one) hz lemma convex_iff_sum_mem : convex s ↔ (βˆ€ (t : finset E) (w : E β†’ ℝ), (βˆ€ i ∈ t, 0 ≀ w i) β†’ βˆ‘ i in t, w i = 1 β†’ (βˆ€ x ∈ t, x ∈ s) β†’ βˆ‘ x in t, w x β€’ x ∈ s ) := begin refine ⟨λ hs t w hwβ‚€ hw₁ hts, hs.sum_mem hwβ‚€ hw₁ hts, _⟩, intros h x y hx hy a b ha hb hab, by_cases h_cases: x = y, { rw [h_cases, ←add_smul, hab, one_smul], exact hy }, { convert h {x, y} (Ξ» z, if z = y then b else a) _ _ _, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] }, { simp_intros i hi, cases hi; subst i; simp [ha, hb, if_neg h_cases] }, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] }, { simp_intros i hi, cases hi; subst i; simp [hx, hy, if_neg h_cases] } } end /-- Jensen's inequality, `finset.center_mass` version. -/ lemma convex_on.map_center_mass_le {f : E β†’ ℝ} (hf : convex_on s f) (hβ‚€ : βˆ€ i ∈ t, 0 ≀ w i) (hpos : 0 < βˆ‘ i in t, w i) (hmem : βˆ€ i ∈ t, z i ∈ s) : f (t.center_mass w z) ≀ t.center_mass w (f ∘ z) := begin have hmem' : βˆ€ i ∈ t, (z i, (f ∘ z) i) ∈ {p : E Γ— ℝ | p.1 ∈ s ∧ f p.1 ≀ p.2}, from Ξ» i hi, ⟨hmem i hi, le_refl _⟩, convert (hf.convex_epigraph.center_mass_mem hβ‚€ hpos hmem').2; simp only [center_mass, function.comp, prod.smul_fst, prod.fst_sum, prod.smul_snd, prod.snd_sum] end /-- Jensen's inequality, `finset.sum` version. -/ lemma convex_on.map_sum_le {f : E β†’ ℝ} (hf : convex_on s f) (hβ‚€ : βˆ€ i ∈ t, 0 ≀ w i) (h₁ : βˆ‘ i in t, w i = 1) (hmem : βˆ€ i ∈ t, z i ∈ s) : f (βˆ‘ i in t, w i β€’ z i) ≀ βˆ‘ i in t, w i * (f (z i)) := by simpa only [center_mass, h₁, inv_one, one_smul] using hf.map_center_mass_le hβ‚€ (h₁.symm β–Έ zero_lt_one) hmem /-- If a function `f` is convex on `s` takes value `y` at the center mass of some points `z i ∈ s`, then for some `i` we have `y ≀ f (z i)`. -/ lemma convex_on.exists_ge_of_center_mass {f : E β†’ ℝ} (h : convex_on s f) (hwβ‚€ : βˆ€ i ∈ t, 0 ≀ w i) (hws : 0 < βˆ‘ i in t, w i) (hz : βˆ€ i ∈ t, z i ∈ s) : βˆƒ i ∈ t, f (t.center_mass w z) ≀ f (z i) := begin set y := t.center_mass w z, have : f y ≀ t.center_mass w (f ∘ z) := h.map_center_mass_le hwβ‚€ hws hz, rw ← sum_filter_ne_zero at hws, rw [← finset.center_mass_filter_ne_zero (f ∘ z), center_mass, smul_eq_mul, ← div_eq_inv_mul, le_div_iff hws, mul_sum] at this, replace : βˆƒ i ∈ t.filter (Ξ» i, w i β‰  0), f y * w i ≀ w i β€’ (f ∘ z) i := exists_le_of_sum_le (nonempty_of_sum_ne_zero (ne_of_gt hws)) this, rcases this with ⟨i, hi, H⟩, rw [mem_filter] at hi, use [i, hi.1], simp only [smul_eq_mul, mul_comm (w i)] at H, refine (mul_le_mul_right _).1 H, exact lt_of_le_of_ne (hwβ‚€ i hi.1) hi.2.symm end end center_mass section convex_hull variable {t : set E} /-- Convex hull of a set `s` is the minimal convex set that includes `s` -/ def convex_hull (s : set E) : set E := β‹‚ (t : set E) (hst : s βŠ† t) (ht : convex t), t variable (s) lemma subset_convex_hull : s βŠ† convex_hull s := set.subset_Inter $ Ξ» t, set.subset_Inter $ Ξ» hst, set.subset_Inter $ Ξ» ht, hst lemma convex_convex_hull : convex (convex_hull s) := convex_Inter $ Ξ» t, convex_Inter $ Ξ» ht, convex_Inter id variable {s} lemma convex_hull_min (hst : s βŠ† t) (ht : convex t) : convex_hull s βŠ† t := set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht lemma convex_hull_mono (hst : s βŠ† t) : convex_hull s βŠ† convex_hull t := convex_hull_min (set.subset.trans hst $ subset_convex_hull t) (convex_convex_hull t) lemma convex.convex_hull_eq {s : set E} (hs : convex s) : convex_hull s = s := set.subset.antisymm (convex_hull_min (set.subset.refl _) hs) (subset_convex_hull s) @[simp] lemma convex_hull_singleton {x : E} : convex_hull ({x} : set E) = {x} := (convex_singleton x).convex_hull_eq lemma is_linear_map.image_convex_hull {f : E β†’ F} (hf : is_linear_map ℝ f) : f '' (convex_hull s) = convex_hull (f '' s) := begin refine set.subset.antisymm _ _, { rw [set.image_subset_iff], exact convex_hull_min (set.image_subset_iff.1 $ subset_convex_hull $ f '' s) ((convex_convex_hull (f '' s)).is_linear_preimage hf) }, { exact convex_hull_min (set.image_subset _ $ subset_convex_hull s) ((convex_convex_hull s).is_linear_image hf) } end lemma linear_map.image_convex_hull (f : E β†’β‚—[ℝ] F) : f '' (convex_hull s) = convex_hull (f '' s) := f.is_linear.image_convex_hull lemma finset.center_mass_mem_convex_hull (t : finset ΞΉ) {w : ΞΉ β†’ ℝ} (hwβ‚€ : βˆ€ i ∈ t, 0 ≀ w i) (hws : 0 < βˆ‘ i in t, w i) {z : ΞΉ β†’ E} (hz : βˆ€ i ∈ t, z i ∈ s) : t.center_mass w z ∈ convex_hull s := (convex_convex_hull s).center_mass_mem hwβ‚€ hws (Ξ» i hi, subset_convex_hull s $ hz i hi) -- TODO : Do we need other versions of the next lemma? /-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t βŠ† s`. This version allows finsets in any type in any universe. -/ lemma convex_hull_eq (s : set E) : convex_hull s = {x : E | βˆƒ (ΞΉ : Type u') (t : finset ΞΉ) (w : ΞΉ β†’ ℝ) (z : ΞΉ β†’ E) (hwβ‚€ : βˆ€ i ∈ t, 0 ≀ w i) (hw₁ : βˆ‘ i in t, w i = 1) (hz : βˆ€ i ∈ t, z i ∈ s) , t.center_mass w z = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, use [punit, {punit.star}, Ξ» _, 1, Ξ» _, x, Ξ» _ _, zero_le_one, finset.sum_singleton, Ξ» _ _, hx], simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] }, { rintros x y ⟨ι, sx, wx, zx, hwxβ‚€, hwx₁, hzx, rfl⟩ ⟨ι', sy, wy, zy, hwyβ‚€, hwy₁, hzy, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment' _ _ _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, _, _, _, _, rfl⟩, { rintros i hi, rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [mul_nonneg, hwxβ‚€, hwyβ‚€] }, { simp [finset.sum_sum_elim, finset.mul_sum.symm, *] }, { intros i hi, rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [hzx, hzy] } }, { rintros _ ⟨ι, t, w, z, hwβ‚€, hw₁, hz, rfl⟩, exact t.center_mass_mem_convex_hull hwβ‚€ (hw₁.symm β–Έ zero_lt_one) hz } end /-- Maximum principle for convex functions. If a function `f` is convex on the convex hull of `s`, then `f` can't have a maximum on `convex_hull s` outside of `s`. -/ lemma convex_on.exists_ge_of_mem_convex_hull {f : E β†’ ℝ} (hf : convex_on (convex_hull s) f) {x} (hx : x ∈ convex_hull s) : βˆƒ y ∈ s, f x ≀ f y := begin rw convex_hull_eq at hx, rcases hx with ⟨α, t, w, z, hwβ‚€, hw₁, hz, rfl⟩, rcases hf.exists_ge_of_center_mass hwβ‚€ (hw₁.symm β–Έ zero_lt_one) (Ξ» i hi, subset_convex_hull s (hz i hi)) with ⟨i, hit, Hi⟩, exact ⟨z i, hz i hit, Hi⟩ end lemma finset.convex_hull_eq (s : finset E) : convex_hull ↑s = {x : E | βˆƒ (w : E β†’ ℝ) (hwβ‚€ : βˆ€ y ∈ s, 0 ≀ w y) (hw₁ : βˆ‘ y in s, w y = 1), s.center_mass w id = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, rw [finset.mem_coe] at hx, refine ⟨_, _, _, finset.center_mass_ite_eq _ _ _ hx⟩, { intros, split_ifs, exacts [zero_le_one, le_refl 0] }, { rw [finset.sum_ite_eq, if_pos hx] } }, { rintros x y ⟨wx, hwxβ‚€, hwx₁, rfl⟩ ⟨wy, hwyβ‚€, hwy₁, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, rfl⟩, { rintros i hi, apply_rules [add_nonneg, mul_nonneg, hwxβ‚€, hwyβ‚€], }, { simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } }, { rintros _ ⟨w, hwβ‚€, hw₁, rfl⟩, exact s.center_mass_mem_convex_hull (Ξ» x hx, hwβ‚€ _ hx) (hw₁.symm β–Έ zero_lt_one) (Ξ» x hx, hx) } end lemma set.finite.convex_hull_eq {s : set E} (hs : finite s) : convex_hull s = {x : E | βˆƒ (w : E β†’ ℝ) (hwβ‚€ : βˆ€ y ∈ s, 0 ≀ w y) (hw₁ : βˆ‘ y in hs.to_finset, w y = 1), hs.to_finset.center_mass w id = x} := by simpa only [set.finite.coe_to_finset, set.finite.mem_to_finset, exists_prop] using hs.to_finset.convex_hull_eq lemma convex_hull_eq_union_convex_hull_finite_subsets (s : set E) : convex_hull s = ⋃ (t : finset E) (w : ↑t βŠ† s), convex_hull ↑t := begin refine subset.antisymm _ _, { rw [convex_hull_eq.{u}], rintros x ⟨ι, t, w, z, hwβ‚€, hw₁, hz, rfl⟩, simp only [mem_Union], refine ⟨t.image z, _, _⟩, { rw [finset.coe_image, image_subset_iff], exact hz }, { apply t.center_mass_mem_convex_hull hwβ‚€, { simp only [hw₁, zero_lt_one] }, { exact Ξ» i hi, finset.mem_coe.2 (finset.mem_image_of_mem _ hi) } } }, { exact Union_subset (Ξ» i, Union_subset convex_hull_mono), }, end lemma is_linear_map.convex_hull_image {f : E β†’ F} (hf : is_linear_map ℝ f) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull s)) $ (convex_convex_hull s).is_linear_image hf) (image_subset_iff.2 $ convex_hull_min (image_subset_iff.1 $ subset_convex_hull _) ((convex_convex_hull _).is_linear_preimage hf)) lemma linear_map.convex_hull_image (f : E β†’β‚—[ℝ] F) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := f.is_linear.convex_hull_image s end convex_hull /-! ### Simplex -/ section simplex variables (ΞΉ) [fintype ΞΉ] {f : ΞΉ β†’ ℝ} /-- Standard simplex in the space of functions `ΞΉ β†’ ℝ` is the set of vectors with non-negative coordinates with total sum `1`. -/ def std_simplex (ΞΉ : Type*) [fintype ΞΉ] : set (ΞΉ β†’ ℝ) := { f | (βˆ€ x, 0 ≀ f x) ∧ βˆ‘ x, f x = 1 } lemma std_simplex_eq_inter : std_simplex ΞΉ = (β‹‚ x, {f | 0 ≀ f x}) ∩ {f | βˆ‘ x, f x = 1} := by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] } lemma convex_std_simplex : convex (std_simplex ΞΉ) := begin refine Ξ» f g hf hg a b ha hb hab, ⟨λ x, _, _⟩, { apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] }, { erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2, smul_eq_mul, smul_eq_mul, mul_one, mul_one], exact hab } end variable {ΞΉ} lemma ite_eq_mem_std_simplex (i : ΞΉ) : (Ξ» j, ite (i = j) (1:ℝ) 0) ∈ std_simplex ΞΉ := ⟨λ j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)] ⟩ /-- `std_simplex ΞΉ` is the convex hull of the canonical basis in `ΞΉ β†’ ℝ`. -/ lemma convex_hull_basis_eq_std_simplex : convex_hull (range $ Ξ»(i j:ΞΉ), if i = j then (1:ℝ) else 0) = std_simplex ΞΉ := begin refine subset.antisymm (convex_hull_min _ (convex_std_simplex ΞΉ)) _, { rintros _ ⟨i, rfl⟩, exact ite_eq_mem_std_simplex i }, { rintros w ⟨hwβ‚€, hwβ‚βŸ©, rw [pi_eq_sum_univ w, ← finset.univ.center_mass_eq_of_sum_1 _ hw₁], exact finset.univ.center_mass_mem_convex_hull (Ξ» i hi, hwβ‚€ i) (hw₁.symm β–Έ zero_lt_one) (Ξ» i hi, mem_range_self i) } end variable {ΞΉ} /-- Convex hull of a finite set is the image of the standard simplex in `s β†’ ℝ` under the linear map sending each function `w` to `βˆ‘ x in s, w x β€’ x`. Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`. The map is defined in terms of operations on `(s β†’ ℝ) β†’β‚—[ℝ] ℝ` so that later we will not need to prove that this map is linear. -/ lemma set.finite.convex_hull_eq_image {s : set E} (hs : finite s) : convex_hull s = by haveI := hs.fintype; exact (⇑(βˆ‘ x : s, (@linear_map.proj ℝ s _ (Ξ» i, ℝ) _ _ x).smul_right x.1)) '' (std_simplex s) := begin rw [← convex_hull_basis_eq_std_simplex, ← linear_map.convex_hull_image, ← set.range_comp, (∘)], apply congr_arg, convert subtype.range_coe.symm, ext x, simp [linear_map.sum_apply, ite_smul, finset.filter_eq] end /-- All values of a function `f ∈ std_simplex ΞΉ` belong to `[0, 1]`. -/ lemma mem_Icc_of_mem_std_simplex (hf : f ∈ std_simplex ΞΉ) (x) : f x ∈ I := ⟨hf.1 x, hf.2 β–Έ finset.single_le_sum (Ξ» y hy, hf.1 y) (finset.mem_univ x)⟩ end simplex
9287040de8c43470ef4d65f46de09843cf1acca7
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/today.lean
f505580f2bf848a826f2cd9c23d222dc2ece8f7d
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
99
lean
/- - polynorphic functions and implicit arguments - Lean's "structure" syntax for "record" types -/
fe24aae1ebc85a8f4520e53c5f2dfcc8b964fce0
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/bicategory/coherence.lean
c0b364e1e9122b65a157b5204f50db5e20665318
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
8,725
lean
/- Copyright (c) 2022 Yuma Mizuno. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yuma Mizuno, Junyan Xu -/ import category_theory.path_category import category_theory.functor.fully_faithful import category_theory.bicategory.free import category_theory.bicategory.locally_discrete /-! # The coherence theorem for bicategories In this file, we prove the coherence theorem for bicategories, stated in the following form: the free bicategory over any quiver is locally thin. The proof is almost the same as the proof of the coherence theorem for monoidal categories that has been previously formalized in mathlib, which is based on the proof described by Ilya Beylin and Peter Dybjer. The idea is to view a path on a quiver as a normal form of a 1-morphism in the free bicategory on the same quiver. A normalization procedure is then described by `normalize : pseudofunctor (free_bicategory B) (locally_discrete (paths B))`, which is a pseudofunctor from the free bicategory to the locally discrete bicategory on the path category. It turns out that this pseudofunctor is locally an equivalence of categories, and the coherence theorem follows immediately from this fact. ## Main statements * `locally_thin` : the free bicategory is locally thin, that is, there is at most one 2-morphism between two fixed 1-morphisms. ## References * [Ilya Beylin and Peter Dybjer, Extracting a proof of coherence for monoidal categories from a proof of normalization for monoids][beylin1996] -/ open quiver (path) quiver.path namespace category_theory open bicategory category open_locale bicategory universes v u namespace free_bicategory variables {B : Type u} [quiver.{v+1} B] /-- Auxiliary definition for `inclusion_path`. -/ @[simp] def inclusion_path_aux {a : B} : βˆ€ {b : B}, path a b β†’ hom a b | _ nil := hom.id a | _ (cons p f) := (inclusion_path_aux p).comp (hom.of f) /-- The discrete category on the paths includes into the category of 1-morphisms in the free bicategory. -/ def inclusion_path (a b : B) : discrete (path.{v+1} a b) β₯€ hom a b := { obj := inclusion_path_aux, map := Ξ» f g Ξ·, eq_to_hom (congr_arg inclusion_path_aux (discrete.eq_of_hom Ξ·)) } /-- The inclusion from the locally discrete bicategory on the path category into the free bicategory as a prelax functor. This will be promoted to a pseudofunctor after proving the coherence theorem. See `inclusion`. -/ def preinclusion (B : Type u) [quiver.{v+1} B] : prelax_functor (locally_discrete (paths B)) (free_bicategory B) := { obj := id, map := Ξ» a b, (inclusion_path a b).obj, mapβ‚‚ := Ξ» a b, (inclusion_path a b).map } @[simp] lemma preinclusion_obj (a : B) : (preinclusion B).obj a = a := rfl /-- The normalization of the composition of `p : path a b` and `f : hom b c`. `p` will eventually be taken to be `nil` and we then get the normalization of `f` alone, but the auxiliary `p` is necessary for Lean to accept the definition of `normalize_iso` and the `whisker_left` case of `normalize_aux_congr` and `normalize_naturality`. -/ @[simp] def normalize_aux {a : B} : βˆ€ {b c : B}, path a b β†’ hom b c β†’ path a c | _ _ p (hom.of f) := p.cons f | _ _ p (hom.id b) := p | _ _ p (hom.comp f g) := normalize_aux (normalize_aux p f) g /- We may define ``` def normalize_aux' : βˆ€ {a b : B}, hom a b β†’ path a b | _ _ (hom.of f) := f.to_path | _ _ (hom.id b) := nil | _ _ (hom.comp f g) := (normalize_aux' f).comp (normalize_aux' g) ``` and define `normalize_aux p f` to be `p.comp (normalize_aux' f)` and this will be equal to the above definition, but the equality proof requires `comp_assoc`, and it thus lacks the correct definitional property to make the definition of `normalize_iso` typecheck. ``` example {a b c : B} (p : path a b) (f : hom b c) : normalize_aux p f = p.comp (normalize_aux' f) := by { induction f, refl, refl, case comp : _ _ _ _ _ ihf ihg { rw [normalize_aux, ihf, ihg], apply comp_assoc } } ``` -/ /-- A 2-isomorphism between a partially-normalized 1-morphism in the free bicategory to the fully-normalized 1-morphism. -/ @[simp] def normalize_iso {a : B} : βˆ€ {b c : B} (p : path a b) (f : hom b c), (preinclusion B).map p ≫ f β‰… (preinclusion B).map (normalize_aux p f) | _ _ p (hom.of f) := iso.refl _ | _ _ p (hom.id b) := ρ_ _ | _ _ p (hom.comp f g) := (Ξ±_ _ _ _).symm β‰ͺ≫ whisker_right_iso (normalize_iso p f) g β‰ͺ≫ normalize_iso (normalize_aux p f) g /-- Given a 2-morphism between `f` and `g` in the free bicategory, we have the equality `normalize_aux p f = normalize_aux p g`. -/ lemma normalize_aux_congr {a b c : B} (p : path a b) {f g : hom b c} (Ξ· : f ⟢ g) : normalize_aux p f = normalize_aux p g := begin rcases Ξ·, apply @congr_fun _ _ (Ξ» p, normalize_aux p f), clear p, induction Ξ·, case vcomp { apply eq.trans; assumption }, /- p β‰  nil required! See the docstring of `normalize_aux`. -/ case whisker_left : _ _ _ _ _ _ _ ih { funext, apply congr_fun ih }, case whisker_right : _ _ _ _ _ _ _ ih { funext, apply congr_arg2 _ (congr_fun ih p) rfl }, all_goals { funext, refl } end /-- The 2-isomorphism `normalize_iso p f` is natural in `f`. -/ lemma normalize_naturality {a b c : B} (p : path a b) {f g : hom b c} (Ξ· : f ⟢ g) : (preinclusion B).map p ◁ Ξ· ≫ (normalize_iso p g).hom = (normalize_iso p f).hom ≫ eq_to_hom (congr_arg _ (normalize_aux_congr p Ξ·)) := begin rcases Ξ·, induction Ξ·, case id : { simp }, case vcomp : _ _ _ _ _ _ _ ihf ihg { rw [mk_vcomp, bicategory.whisker_left_comp], slice_lhs 2 3 { rw ihg }, slice_lhs 1 2 { rw ihf }, simp }, case whisker_left : _ _ _ _ _ _ _ ih /- p β‰  nil required! See the docstring of `normalize_aux`. -/ { dsimp, simp_rw [associator_inv_naturality_right_assoc, whisker_exchange_assoc, ih, assoc] }, case whisker_right : _ _ _ _ _ h Ξ· ih { dsimp, rw [associator_inv_naturality_middle_assoc, ←comp_whisker_right_assoc, ih, comp_whisker_right], have := dcongr_arg (Ξ» x, (normalize_iso x h).hom) (normalize_aux_congr p (quot.mk _ Ξ·)), dsimp at this, simp [this] }, all_goals { dsimp, dsimp [id_def, comp_def], simp } end @[simp] lemma normalize_aux_nil_comp {a b c : B} (f : hom a b) (g : hom b c) : normalize_aux nil (f.comp g) = (normalize_aux nil f).comp (normalize_aux nil g) := begin induction g generalizing a, case id { refl }, case of { refl }, case comp : _ _ _ g _ ihf ihg { erw [ihg (f.comp g), ihf f, ihg g, comp_assoc] } end /-- The normalization pseudofunctor for the free bicategory on a quiver `B`. -/ def normalize (B : Type u) [quiver.{v+1} B] : pseudofunctor (free_bicategory B) (locally_discrete (paths B)) := { obj := id, map := Ξ» a b, normalize_aux nil, mapβ‚‚ := Ξ» a b f g Ξ·, eq_to_hom (normalize_aux_congr nil Ξ·), map_id := Ξ» a, iso.refl nil, map_comp := Ξ» a b c f g, eq_to_iso (normalize_aux_nil_comp f g) } /-- Auxiliary definition for `normalize_equiv`. -/ def normalize_unit_iso (a b : free_bicategory B) : 𝟭 (a ⟢ b) β‰… (normalize B).map_functor a b β‹™ inclusion_path a b := nat_iso.of_components (Ξ» f, (Ξ»_ f).symm β‰ͺ≫ normalize_iso nil f) begin intros f g Ξ·, erw [left_unitor_inv_naturality_assoc, assoc], congr' 1, exact normalize_naturality nil Ξ· end /-- Normalization as an equivalence of categories. -/ def normalize_equiv (a b : B) : hom a b β‰Œ discrete (path.{v+1} a b) := equivalence.mk ((normalize _).map_functor a b) (inclusion_path a b) (normalize_unit_iso a b) (discrete.nat_iso (Ξ» f, eq_to_iso (by { induction f; tidy }))) /-- The coherence theorem for bicategories. -/ instance locally_thin {a b : free_bicategory B} (f g : a ⟢ b) : subsingleton (f ⟢ g) := ⟨λ Ξ· ΞΈ, (normalize_equiv a b).functor.map_injective (subsingleton.elim _ _)⟩ /-- Auxiliary definition for `inclusion`. -/ def inclusion_map_comp_aux {a b : B} : βˆ€ {c : B} (f : path a b) (g : path b c), (preinclusion _).map (f ≫ g) β‰… (preinclusion _).map f ≫ (preinclusion _).map g | _ f nil := (ρ_ ((preinclusion _).map f)).symm | _ f (cons g₁ gβ‚‚) := whisker_right_iso (inclusion_map_comp_aux f g₁) (hom.of gβ‚‚) β‰ͺ≫ Ξ±_ _ _ _ /-- The inclusion pseudofunctor from the locally discrete bicategory on the path category into the free bicategory. -/ def inclusion (B : Type u) [quiver.{v+1} B] : pseudofunctor (locally_discrete (paths B)) (free_bicategory B) := { map_id := Ξ» a, iso.refl (πŸ™ a), map_comp := Ξ» a b c f g, inclusion_map_comp_aux f g, -- All the conditions for 2-morphisms are trivial thanks to the coherence theorem! .. preinclusion B } end free_bicategory end category_theory
862ac4ad8a23d7197b17a65a3072e82c6efea3c9
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/tactic/lint/frontend.lean
6aac5f3cf669a55c7b0027b52ba57e9e9db29185
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,927
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner -/ import tactic.lint.basic /-! # Linter frontend and commands This file defines the linter commands which spot common mistakes in the code. * `#lint`: check all declarations in the current file * `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects, and also excluding the current file) * `#lint_all`: check all declarations in the environment (the current file and all imported files) For a list of default / non-default linters, see the "Linting Commands" user command doc entry. The command `#list_linters` prints a list of the names of all available linters. You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4). You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint that suppresses the output if all checks pass. A silent lint will fail if any test fails. You can append a `+` to any command (e.g. `#lint_mathlib+`) to run a verbose lint that reports the result of each linter, including the successes. You can append a sequence of linter names to any command to run extra tests, in addition to the default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`. You can append `only name1 name2 ...` to any command to run a subset of linters, e.g. `#lint only unused_arguments` You can add custom linters by defining a term of type `linter` in the `linter` namespace. A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check` or `lint only my_new_check`. If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default. Adding the attribute `@[nolint doc_blame unused_arguments]` to a declaration omits it from only the specified linter checks. ## Tags sanity check, lint, cleanup, command, tactic -/ open tactic expr native setup_tactic_parser /-- Verbosity for the linter output. * `low`: only print failing checks, print nothing on success. * `medium`: only print failing checks, print confirmation on success. * `high`: print output of every check. -/ @[derive [decidable_eq, inhabited]] inductive lint_verbosity | low | medium | high /-- `get_checks slow extra use_only` produces a list of linters. `extras` is a list of names that should resolve to declarations with type `linter`. If `use_only` is true, it only uses the linters in `extra`. Otherwise, it uses all linters in the environment tagged with `@[linter]`. If `slow` is false, it only uses the fast default tests. -/ meta def get_checks (slow : bool) (extra : list name) (use_only : bool) : tactic (list (name Γ— linter)) := do default ← if use_only then return [] else attribute.get_instances `linter >>= get_linters, let default := if slow then default else default.filter (Ξ» l, l.2.is_fast), list.append default <$> get_linters extra /-- `lint_core all_decls non_auto_decls checks` applies the linters `checks` to the list of declarations. If `auto_decls` is false for a linter (default) the linter is applied to `non_auto_decls`. If `auto_decls` is true, then it is applied to `all_decls`. The resulting list has one element for each linter, containing the linter as well as a map from declaration name to warning. -/ meta def lint_core (all_decls non_auto_decls : list declaration) (checks : list (name Γ— linter)) : tactic (list (name Γ— linter Γ— rb_map name string)) := do checks.mmap $ Ξ» ⟨linter_name, linter⟩, do let test_decls := if linter.auto_decls then all_decls else non_auto_decls, test_decls ← test_decls.mfilter (Ξ» decl, should_be_linted linter_name decl.to_name), s ← read, let results := test_decls.map_async_chunked $ Ξ» decl, prod.mk decl.to_name $ match linter.test decl s with | result.success w _ := w | result.exception msg _ _ := some $ "LINTER FAILED:\n" ++ msg.elim "(no message)" (Ξ» msg, to_string $ msg ()) end, let results := results.foldl (Ξ» (results : rb_map name string) warning, match warning with | (decl_name, some w) := results.insert decl_name w | (_, none) := results end) mk_rb_map, pure (linter_name, linter, results) /-- Sorts a map with declaration keys as names by line number. -/ meta def sort_results {Ξ±} (e : environment) (results : rb_map name Ξ±) : list (name Γ— Ξ±) := list.reverse $ rb_lmap.values $ rb_lmap.of_list $ results.fold [] $ Ξ» decl linter_warning results, (((e.decl_pos decl).get_or_else ⟨0,0⟩).line, (decl, linter_warning)) :: results /-- Formats a linter warning as `#print` command with comment. -/ meta def print_warning (decl_name : name) (warning : string) : format := "#check @" ++ to_fmt decl_name ++ " /- " ++ warning ++ " -/" /-- Formats a map of linter warnings using `print_warning`, sorted by line number. -/ meta def print_warnings (env : environment) (results : rb_map name string) : format := format.intercalate format.line $ (sort_results env results).map $ Ξ» ⟨decl_name, warning⟩, print_warning decl_name warning /-- Formats a map of linter warnings grouped by filename with `-- filename` comments. The first `drop_fn_chars` characters are stripped from the filename. -/ meta def grouped_by_filename (e : environment) (results : rb_map name string) (drop_fn_chars := 0) (formatter: rb_map name string β†’ format) : format := let results := results.fold (rb_map.mk string (rb_map name string)) $ Ξ» decl_name linter_warning results, let fn := (e.decl_olean decl_name).get_or_else "" in results.insert fn (((results.find fn).get_or_else mk_rb_map).insert decl_name linter_warning) in let l := results.to_list.reverse.map (Ξ» ⟨fn, results⟩, ("-- " ++ fn.popn drop_fn_chars ++ "\n" ++ formatter results : format)) in format.intercalate "\n\n" l ++ "\n" /-- Formats the linter results as Lean code with comments and `#print` commands. -/ meta def format_linter_results (env : environment) (results : list (name Γ— linter Γ— rb_map name string)) (decls non_auto_decls : list declaration) (group_by_filename : option β„•) (where_desc : string) (slow : bool) (verbose : lint_verbosity) (num_linters : β„•) : format := do let formatted_results := results.map $ Ξ» ⟨linter_name, linter, results⟩, let report_str : format := to_fmt "/- The `" ++ to_fmt linter_name ++ "` linter reports: -/\n" in if Β¬ results.empty then let warnings := match group_by_filename with | none := print_warnings env results | some dropped := grouped_by_filename env results dropped (print_warnings env) end in report_str ++ "/- " ++ linter.errors_found ++ " -/\n" ++ warnings ++ "\n" else if verbose = lint_verbosity.high then "/- OK: " ++ linter.no_errors_found ++ " -/" else format.nil, let s := format.intercalate "\n" (formatted_results.filter (Ξ» f, Β¬ f.is_nil)), let s := if verbose = lint_verbosity.low then s else format!("/- Checking {non_auto_decls.length} declarations (plus " ++ "{decls.length - non_auto_decls.length} automatically generated ones) {where_desc} " ++ "with {num_linters} linters -/\n\n") ++ s, let s := if slow then s else s ++ "/- (slow tests skipped) -/\n", s /-- The common denominator of `#lint[|mathlib|all]`. The different commands have different configurations for `l`, `group_by_filename` and `where_desc`. If `slow` is false, doesn't do the checks that take a lot of time. If `verbose` is false, it will suppress messages from passing checks. By setting `checks` you can customize which checks are performed. Returns a `name_set` containing the names of all declarations that fail any check in `check`, and a `format` object describing the failures. -/ meta def lint_aux (decls : list declaration) (group_by_filename : option β„•) (where_desc : string) (slow : bool) (verbose : lint_verbosity) (checks : list (name Γ— linter)) : tactic (name_set Γ— format) := do e ← get_env, let non_auto_decls := decls.filter (Ξ» d, Β¬ d.is_auto_or_internal e), results ← lint_core decls non_auto_decls checks, let s := format_linter_results e results decls non_auto_decls group_by_filename where_desc slow verbose checks.length, let ns := name_set.of_list (do (_,_,rs) ← results, rs.keys), pure (ns, s) /-- Return the message printed by `#lint` and a `name_set` containing all declarations that fail. -/ meta def lint (slow : bool := tt) (verbose : lint_verbosity := lint_verbosity.medium) (extra : list name := []) (use_only : bool := ff) : tactic (name_set Γ— format) := do checks ← get_checks slow extra use_only, e ← get_env, let l := e.filter (Ξ» d, e.in_current_file d.to_name), lint_aux l none "in the current file" slow verbose checks /-- Returns the declarations considered by the mathlib linter. -/ meta def lint_mathlib_decls : tactic (list declaration) := do e ← get_env, ml ← get_mathlib_dir, pure $ e.filter $ Ξ» d, e.is_prefix_of_file ml d.to_name /-- Return the message printed by `#lint_mathlib` and a `name_set` containing all declarations that fail. -/ meta def lint_mathlib (slow : bool := tt) (verbose : lint_verbosity := lint_verbosity.medium) (extra : list name := []) (use_only : bool := ff) : tactic (name_set Γ— format) := do checks ← get_checks slow extra use_only, decls ← lint_mathlib_decls, mathlib_path_len ← string.length <$> get_mathlib_dir, lint_aux decls mathlib_path_len "in mathlib (only in imported files)" slow verbose checks /-- Return the message printed by `#lint_all` and a `name_set` containing all declarations that fail. -/ meta def lint_all (slow : bool := tt) (verbose : lint_verbosity := lint_verbosity.medium) (extra : list name := []) (use_only : bool := ff) : tactic (name_set Γ— format) := do checks ← get_checks slow extra use_only, e ← get_env, let l := e.get_decls, lint_aux l (some 0) "in all imported files (including this one)" slow verbose checks /-- Parses an optional `only`, followed by a sequence of zero or more identifiers. Prepends `linter.` to each of these identifiers. -/ private meta def parse_lint_additions : parser (bool Γ— list name) := prod.mk <$> only_flag <*> (list.map (name.append `linter) <$> ident*) /-- Parses a "-" or "+", returning `lint_verbosity.low` or `lint_verbosity.high` respectively, or returns `none`. -/ private meta def parse_verbosity : parser (option lint_verbosity) := tk "-" >> return lint_verbosity.low <|> tk "+" >> return lint_verbosity.high <|> return none /-- The common denominator of `lint_cmd`, `lint_mathlib_cmd`, `lint_all_cmd` -/ private meta def lint_cmd_aux (scope : bool β†’ lint_verbosity β†’ list name β†’ bool β†’ tactic (name_set Γ— format)) : parser unit := do verbosity ← parse_verbosity, fast_only ← optional (tk "*"), -- allow either order of *- verbosity ← if verbosity.is_some then return verbosity else parse_verbosity, let verbosity := verbosity.get_or_else lint_verbosity.medium, (use_only, extra) ← parse_lint_additions, (failed, s) ← scope fast_only.is_none verbosity extra use_only, when (Β¬ s.is_nil) $ trace s, when (verbosity = lint_verbosity.low ∧ Β¬ failed.empty) $ fail "Linting did not succeed", when (verbosity = lint_verbosity.medium ∧ failed.empty) $ trace "/- All linting checks passed! -/" /-- The command `#lint` at the bottom of a file will warn you about some common mistakes in that file. Usage: `#lint`, `#lint linter_1 linter_2`, `#lint only linter_1 linter_2`. `#lint-` will suppress the output if all checks pass. `#lint+` will enable verbose output. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_cmd (_ : parse $ tk "#lint") : parser unit := lint_cmd_aux @lint /-- The command `#lint_mathlib` checks all of mathlib for certain mistakes. Usage: `#lint_mathlib`, `#lint_mathlib linter_1 linter_2`, `#lint_mathlib only linter_1 linter_2`. `#lint_mathlib-` will suppress the output if all checks pass. `lint_mathlib+` will enable verbose output. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_mathlib_cmd (_ : parse $ tk "#lint_mathlib") : parser unit := lint_cmd_aux @lint_mathlib /-- The command `#lint_all` checks all imported files for certain mistakes. Usage: `#lint_all`, `#lint_all linter_1 linter_2`, `#lint_all only linter_1 linter_2`. `#lint_all-` will suppress the output if all checks pass. `lint_all+` will enable verbose output. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_all_cmd (_ : parse $ tk "#lint_all") : parser unit := lint_cmd_aux @lint_all /-- The command `#list_linters` prints a list of all available linters. -/ @[user_command] meta def list_linters (_ : parse $ tk "#list_linters") : parser unit := do env ← get_env, let ns := env.decl_filter_map $ Ξ» dcl, if (dcl.to_name.get_prefix = `linter) && (dcl.type = `(linter)) then some dcl.to_name else none, trace "Available linters:\n linters marked with (*) are in the default lint set\n", ns.mmap' $ Ξ» n, do b ← has_attribute' `linter n, trace $ n.pop_prefix.to_string ++ if b then " (*)" else "" /-- Invoking the hole command `lint` ("Find common mistakes in current file") will print text that indicates mistakes made in the file above the command. It is equivalent to copying and pasting the output of `#lint`. On large files, it may take some time before the output appears. -/ @[hole_command] meta def lint_hole_cmd : hole_command := { name := "Lint", descr := "Lint: Find common mistakes in current file.", action := Ξ» es, do (_, s) ← lint, return [(s.to_string,"")] } add_tactic_doc { name := "Lint", category := doc_category.hole_cmd, decl_names := [`lint_hole_cmd], tags := ["linting"] }
8afcdd18b320a29166cb2072a317f058afd93fdf
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/geometry/manifold/metrizable.lean
432c3b5b1dae06a39fc279a2b84f647b6964852a
[ "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
1,205
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import geometry.manifold.smooth_manifold_with_corners import topology.paracompact import topology.metric_space.metrizable /-! # Metrizability of a Οƒ-compact manifold In this file we show that a Οƒ-compact Hausdorff topological manifold over a finite dimensional real vector space is metrizable. -/ open topological_space /-- A Οƒ-compact Hausdorff topological manifold over a finite dimensional real vector space is metrizable. -/ lemma manifold_with_corners.metrizable_space {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {H : Type*} [topological_space H] (I : model_with_corners ℝ E H) (M : Type*) [topological_space M] [charted_space H M] [sigma_compact_space M] [t2_space M] : metrizable_space M := begin haveI := I.locally_compact, haveI := charted_space.locally_compact H M, haveI : normal_space M := normal_of_paracompact_t2, haveI := I.second_countable_topology, haveI := charted_space.second_countable_of_sigma_compact H M, exact metrizable_space_of_t3_second_countable M end
749fc7e1c33786750c5294f528a92e6f6d165096
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/idempotents/simplicial_object.lean
0432a50a0e2ab86b1d80f50e83610b9da3125ffc
[ "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
867
lean
/- Copyright (c) 2022 JoΓ«l Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: JoΓ«l Riou -/ import algebraic_topology.simplicial_object import category_theory.idempotents.functor_categories /-! # Idempotent completeness of categories of simplicial objects In this file, we provide an instance expressing that `simplicial_object C` and `cosimplicial_object C` are idempotent complete categories when the category `C` is. -/ namespace category_theory namespace idempotents variables {C : Type*} [category C] [is_idempotent_complete C] instance : is_idempotent_complete (simplicial_object C) := idempotents.functor_category_is_idempotent_complete _ _ instance : is_idempotent_complete (cosimplicial_object C) := idempotents.functor_category_is_idempotent_complete _ _ end idempotents end category_theory
542657b6659b84e7bac23515c1159dc5ba1e6671
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Init/System.lean
0585f2c7ffb051bf7c2e26d9333de3c7cc3c6ae0
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
222
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.System.IO import Init.System.Platform
2fbf931912081958a39713ea5eee0df376abd023
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/fin.lean
90a30445b839e6d63517149080ba190b249ad44a
[]
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
47,420
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Keeley Hoek -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.nat.cast import Mathlib.tactic.localized import Mathlib.order.rel_iso import Mathlib.PostPort universes u u_1 u_2 v namespace Mathlib /-! # The finite type with `n` elements `fin n` is the type whose elements are natural numbers smaller than `n`. This file expands on the development in the core library. ## Main definitions ### Induction principles * `fin_zero_elim` : Elimination principle for the empty set `fin 0`, generalizes `fin.elim0`. * `fin.succ_rec` : Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. * `fin.succ_rec_on` : same as `fin.succ_rec` but `i : fin n` is the first argument; * `fin.induction` : Define `C i` by induction on `i : fin (n + 1)`, separating into the `nat`-like base cases of `C 0` and `C (i.succ)`. * `fin.induction_on` : same as `fin.induction` but with `i : fin (n + 1)` as the first argument. ### Casts * `cast_lt i h` : embed `i` into a `fin` where `h` proves it belongs into; * `cast_le h` : embed `fin n` into `fin m`, `h : n ≀ m`; * `cast eq` : embed `fin n` into `fin m`, `eq : n = m`; * `cast_add m` : embed `fin n` into `fin (n+m)`; * `cast_succ` : embed `fin n` into `fin (n+1)`; * `succ_above p` : embed `fin n` into `fin (n + 1)` with a hole around `p`; * `pred_above p i h` : embed `i : fin (n+1)` into `fin n` by ignoring `p`; * `sub_nat i h` : subtract `m` from `i β‰₯ m`, generalizes `fin.pred`; * `add_nat i h` : add `m` on `i` on the right, generalizes `fin.succ`; * `nat_add i h` adds `n` on `i` on the left; * `clamp n m` : `min n m` as an element of `fin (m + 1)`; ### Operation on tuples We interpret maps `Ξ  i : fin n, Ξ± i` as tuples `(Ξ± 0, …, Ξ± (n-1))`. If `Ξ± i` is a constant map, then tuples are isomorphic (but not definitionally equal) to `vector`s. We define the following operations: * `tail` : the tail of an `n+1` tuple, i.e., its last `n` entries; * `cons` : adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple; * `init` : the beginning of an `n+1` tuple, i.e., its first `n` entries; * `snoc` : adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. * `insert_nth` : insert an element to a tuple at a given position. * `find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. ### Misc definitions * `fin.last n` : The greatest value of `fin (n+1)`. -/ /-- Elimination principle for the empty set `fin 0`, dependent version. -/ def fin_zero_elim {Ξ± : fin 0 β†’ Sort u} (x : fin 0) : Ξ± x := fin.elim0 x theorem fact.succ.pos {n : β„•} : fact (0 < Nat.succ n) := nat.zero_lt_succ n theorem fact.bit0.pos {n : β„•} [h : fact (0 < n)] : fact (0 < bit0 n) := nat.zero_lt_bit0 (ne_of_gt h) theorem fact.bit1.pos {n : β„•} : fact (0 < bit1 n) := nat.zero_lt_bit1 n theorem fact.pow.pos {p : β„•} {n : β„•} [h : fact (0 < p)] : fact (0 < p ^ n) := pow_pos h n namespace fin protected instance fin_to_nat (n : β„•) : has_coe (fin n) β„• := has_coe.mk subtype.val theorem is_lt {n : β„•} (i : fin n) : ↑i < n := subtype.property i /-- convert a `β„•` to `fin n`, provided `n` is positive -/ def of_nat' {n : β„•} [h : fact (0 < n)] (i : β„•) : fin n := { val := i % n, property := nat.mod_lt i h } @[simp] protected theorem eta {n : β„•} (a : fin n) (h : ↑a < n) : { val := ↑a, property := h } = a := sorry theorem ext {n : β„•} {a : fin n} {b : fin n} (h : ↑a = ↑b) : a = b := eq_of_veq h theorem ext_iff {n : β„•} (a : fin n) (b : fin n) : a = b ↔ ↑a = ↑b := { mp := congr_arg fun (a : fin n) => ↑a, mpr := eq_of_veq } theorem coe_injective {n : β„•} : function.injective coe := subtype.coe_injective theorem eq_iff_veq {n : β„•} (a : fin n) (b : fin n) : a = b ↔ subtype.val a = subtype.val b := { mp := veq_of_eq, mpr := eq_of_veq } theorem ne_iff_vne {n : β„•} (a : fin n) (b : fin n) : a β‰  b ↔ subtype.val a β‰  subtype.val b := { mp := vne_of_ne, mpr := ne_of_vne } @[simp] theorem mk_eq_subtype_mk {n : β„•} (a : β„•) (h : a < n) : mk a h = { val := a, property := h } := rfl protected theorem mk.inj_iff {n : β„•} {a : β„•} {b : β„•} {ha : a < n} {hb : b < n} : { val := a, property := ha } = { val := b, property := hb } ↔ a = b := subtype.mk_eq_mk theorem mk_val {m : β„•} {n : β„•} (h : m < n) : subtype.val { val := m, property := h } = m := rfl theorem eq_mk_iff_coe_eq {n : β„•} {a : fin n} {k : β„•} {hk : k < n} : a = { val := k, property := hk } ↔ ↑a = k := eq_iff_veq a { val := k, property := hk } @[simp] theorem coe_mk {m : β„•} {n : β„•} (h : m < n) : ↑{ val := m, property := h } = m := rfl theorem mk_coe {n : β„•} (i : fin n) : { val := ↑i, property := is_lt i } = i := fin.eta i (is_lt i) theorem coe_eq_val {n : β„•} (a : fin n) : ↑a = subtype.val a := rfl @[simp] theorem val_eq_coe {n : β„•} (a : fin n) : subtype.val a = ↑a := rfl @[simp] theorem val_one {n : β„•} : subtype.val 1 = 1 := rfl @[simp] theorem val_two {n : β„•} : subtype.val (bit0 1) = bit0 1 := rfl @[simp] theorem coe_zero {n : β„•} : ↑0 = 0 := rfl @[simp] theorem coe_one {n : β„•} : ↑1 = 1 := rfl @[simp] theorem coe_two {n : β„•} : ↑(bit0 1) = bit0 1 := rfl /-- `a < b` as natural numbers if and only if `a < b` in `fin n`. -/ @[simp] theorem coe_fin_lt {n : β„•} {a : fin n} {b : fin n} : ↑a < ↑b ↔ a < b := iff.rfl /-- `a ≀ b` as natural numbers if and only if `a ≀ b` in `fin n`. -/ @[simp] theorem coe_fin_le {n : β„•} {a : fin n} {b : fin n} : ↑a ≀ ↑b ↔ a ≀ b := iff.rfl theorem val_add {n : β„•} (a : fin n) (b : fin n) : subtype.val (a + b) = (subtype.val a + subtype.val b) % n := sorry theorem coe_add {n : β„•} (a : fin n) (b : fin n) : ↑(a + b) = (↑a + ↑b) % n := sorry theorem val_mul {n : β„•} (a : fin n) (b : fin n) : subtype.val (a * b) = subtype.val a * subtype.val b % n := sorry theorem coe_mul {n : β„•} (a : fin n) (b : fin n) : ↑(a * b) = ↑a * ↑b % n := sorry theorem one_val {n : β„•} : subtype.val 1 = 1 % (n + 1) := rfl theorem coe_one' {n : β„•} : ↑1 = 1 % (n + 1) := rfl @[simp] theorem val_zero' (n : β„•) : subtype.val 0 = 0 := rfl @[simp] theorem mk_zero {n : β„•} : { val := 0, property := nat.succ_pos' } = 0 := rfl @[simp] theorem mk_one {n : β„•} : { val := 1, property := nat.succ_lt_succ (nat.succ_pos n) } = 1 := rfl @[simp] theorem mk_bit0 {m : β„•} {n : β„•} (h : bit0 m < n) : { val := bit0 m, property := h } = bit0 { val := m, property := has_le.le.trans_lt (nat.le_add_right m m) h } := eq_of_veq (Eq.symm (nat.mod_eq_of_lt h)) @[simp] theorem mk_bit1 {m : β„•} {n : β„•} (h : bit1 m < n + 1) : { val := bit1 m, property := h } = bit1 { val := m, property := has_le.le.trans_lt (nat.le_add_right m m) (has_lt.lt.trans (nat.lt_succ_self (m + m)) h) } := sorry @[simp] theorem of_nat_eq_coe (n : β„•) (a : β„•) : of_nat a = ↑a := sorry /-- Converting an in-range number to `fin (n + 1)` produces a result whose value is the original number. -/ theorem coe_val_of_lt {n : β„•} {a : β„•} (h : a < n + 1) : subtype.val ↑a = a := eq.mpr (id (Eq._oldrec (Eq.refl (subtype.val ↑a = a)) (Eq.symm (of_nat_eq_coe n a)))) (nat.mod_eq_of_lt h) /-- Converting the value of a `fin (n + 1)` to `fin (n + 1)` results in the same value. -/ theorem coe_val_eq_self {n : β„•} (a : fin (n + 1)) : ↑(subtype.val a) = a := eq.mpr (id (Eq._oldrec (Eq.refl (↑(subtype.val a) = a)) (propext (eq_iff_veq (↑(subtype.val a)) a)))) (coe_val_of_lt (subtype.property a)) /-- Coercing an in-range number to `fin (n + 1)`, and converting back to `β„•`, results in that number. -/ theorem coe_coe_of_lt {n : β„•} {a : β„•} (h : a < n + 1) : ↑↑a = a := coe_val_of_lt h /-- Converting a `fin (n + 1)` to `β„•` and back results in the same value. -/ @[simp] theorem coe_coe_eq_self {n : β„•} (a : fin (n + 1)) : ↑↑a = a := coe_val_eq_self a /-- Assume `k = l`. If two functions defined on `fin k` and `fin l` are equal on each element, then they coincide (in the heq sense). -/ protected theorem heq_fun_iff {Ξ± : Type u_1} {k : β„•} {l : β„•} (h : k = l) {f : fin k β†’ Ξ±} {g : fin l β†’ Ξ±} : f == g ↔ βˆ€ (i : fin k), f i = g { val := ↑i, property := h β–Έ subtype.property i } := sorry protected theorem heq_ext_iff {k : β„•} {l : β„•} (h : k = l) {i : fin k} {j : fin l} : i == j ↔ ↑i = ↑j := sorry protected instance nontrivial {n : β„•} : nontrivial (fin (n + bit0 1)) := nontrivial.mk (Exists.intro 0 (Exists.intro 1 (of_as_true trivial))) protected instance linear_order {n : β„•} : linear_order (fin n) := linear_order.mk LessEq Less sorry sorry sorry sorry fin.decidable_le (fin.decidable_eq n) fin.decidable_lt theorem exists_iff {n : β„•} {p : fin n β†’ Prop} : (βˆƒ (i : fin n), p i) ↔ βˆƒ (i : β„•), βˆƒ (h : i < n), p { val := i, property := h } := sorry theorem forall_iff {n : β„•} {p : fin n β†’ Prop} : (βˆ€ (i : fin n), p i) ↔ βˆ€ (i : β„•) (h : i < n), p { val := i, property := h } := sorry theorem lt_iff_coe_lt_coe {n : β„•} {a : fin n} {b : fin n} : a < b ↔ ↑a < ↑b := iff.rfl theorem le_iff_coe_le_coe {n : β„•} {a : fin n} {b : fin n} : a ≀ b ↔ ↑a ≀ ↑b := iff.rfl theorem mk_lt_of_lt_coe {n : β„•} {b : fin n} {a : β„•} (h : a < ↑b) : { val := a, property := has_lt.lt.trans h (is_lt b) } < b := h theorem mk_le_of_le_coe {n : β„•} {b : fin n} {a : β„•} (h : a ≀ ↑b) : { val := a, property := has_le.le.trans_lt h (is_lt b) } ≀ b := h theorem zero_le {n : β„•} (a : fin (n + 1)) : 0 ≀ a := nat.zero_le (subtype.val a) @[simp] theorem coe_succ {n : β„•} (j : fin n) : ↑(fin.succ j) = ↑j + 1 := sorry theorem succ_pos {n : β„•} (a : fin n) : 0 < fin.succ a := sorry /-- The greatest value of `fin (n+1)` -/ def last (n : β„•) : fin (n + 1) := { val := n, property := nat.lt_succ_self n } @[simp] theorem coe_last (n : β„•) : ↑(last n) = n := rfl theorem last_val (n : β„•) : subtype.val (last n) = n := rfl theorem le_last {n : β„•} (i : fin (n + 1)) : i ≀ last n := nat.le_of_lt_succ (is_lt i) protected instance bounded_lattice {n : β„•} : bounded_lattice (fin (n + 1)) := bounded_lattice.mk lattice.sup linear_order.le linear_order.lt sorry sorry sorry sorry sorry sorry lattice.inf sorry sorry sorry (last n) le_last 0 zero_le /-- `fin.succ` as an `order_embedding` -/ def succ_embedding (n : β„•) : fin n β†ͺo fin (n + 1) := order_embedding.of_strict_mono fin.succ sorry @[simp] theorem coe_succ_embedding {n : β„•} : ⇑(succ_embedding n) = fin.succ := rfl @[simp] theorem succ_le_succ_iff {n : β„•} {a : fin n} {b : fin n} : fin.succ a ≀ fin.succ b ↔ a ≀ b := order_embedding.le_iff_le (succ_embedding n) @[simp] theorem succ_lt_succ_iff {n : β„•} {a : fin n} {b : fin n} : fin.succ a < fin.succ b ↔ a < b := order_embedding.lt_iff_lt (succ_embedding n) theorem succ_injective (n : β„•) : function.injective fin.succ := rel_embedding.injective (succ_embedding n) @[simp] theorem succ_inj {n : β„•} {a : fin n} {b : fin n} : fin.succ a = fin.succ b ↔ a = b := function.injective.eq_iff (succ_injective n) theorem succ_ne_zero {n : β„•} (k : fin n) : fin.succ k β‰  0 := sorry @[simp] theorem succ_zero_eq_one {n : β„•} : fin.succ 0 = 1 := rfl theorem mk_succ_pos {n : β„•} (i : β„•) (h : i < n) : 0 < { val := Nat.succ i, property := add_lt_add_right h 1 } := sorry theorem one_lt_succ_succ {n : β„•} (a : fin n) : 1 < fin.succ (fin.succ a) := sorry theorem succ_succ_ne_one {n : β„•} (a : fin n) : fin.succ (fin.succ a) β‰  1 := ne_of_gt (one_lt_succ_succ a) @[simp] theorem coe_pred {n : β„•} (j : fin (n + 1)) (h : j β‰  0) : ↑(pred j h) = ↑j - 1 := sorry @[simp] theorem succ_pred {n : β„•} (i : fin (n + 1)) (h : i β‰  0) : fin.succ (pred i h) = i := sorry @[simp] theorem pred_succ {n : β„•} (i : fin n) {h : fin.succ i β‰  0} : pred (fin.succ i) h = i := sorry @[simp] theorem pred_mk_succ {n : β„•} (i : β„•) (h : i < n + 1) : pred { val := i + 1, property := add_lt_add_right h 1 } (ne_of_vne (ne_of_gt (mk_succ_pos i h))) = { val := i, property := h } := sorry @[simp] theorem pred_le_pred_iff {n : β„•} {a : fin (Nat.succ n)} {b : fin (Nat.succ n)} {ha : a β‰  0} {hb : b β‰  0} : pred a ha ≀ pred b hb ↔ a ≀ b := eq.mpr (id (Eq._oldrec (Eq.refl (pred a ha ≀ pred b hb ↔ a ≀ b)) (Eq.symm (propext succ_le_succ_iff)))) (eq.mpr (id (Eq._oldrec (Eq.refl (fin.succ (pred a ha) ≀ fin.succ (pred b hb) ↔ a ≀ b)) (succ_pred a ha))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ≀ fin.succ (pred b hb) ↔ a ≀ b)) (succ_pred b hb))) (iff.refl (a ≀ b)))) @[simp] theorem pred_lt_pred_iff {n : β„•} {a : fin (Nat.succ n)} {b : fin (Nat.succ n)} {ha : a β‰  0} {hb : b β‰  0} : pred a ha < pred b hb ↔ a < b := eq.mpr (id (Eq._oldrec (Eq.refl (pred a ha < pred b hb ↔ a < b)) (Eq.symm (propext succ_lt_succ_iff)))) (eq.mpr (id (Eq._oldrec (Eq.refl (fin.succ (pred a ha) < fin.succ (pred b hb) ↔ a < b)) (succ_pred a ha))) (eq.mpr (id (Eq._oldrec (Eq.refl (a < fin.succ (pred b hb) ↔ a < b)) (succ_pred b hb))) (iff.refl (a < b)))) @[simp] theorem pred_inj {n : β„•} {a : fin (n + 1)} {b : fin (n + 1)} {ha : a β‰  0} {hb : b β‰  0} : pred a ha = pred b hb ↔ a = b := sorry /-- The inclusion map `fin n β†’ β„•` is a relation embedding. -/ def coe_embedding (n : β„•) : fin n β†ͺo β„• := rel_embedding.mk (function.embedding.mk coe eq_of_veq) sorry /-- The ordering on `fin n` is a well order. -/ protected instance fin.lt.is_well_order (n : β„•) : is_well_order (fin n) Less := order_embedding.is_well_order (coe_embedding n) /-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/ def cast_lt {n : β„•} {m : β„•} (i : fin m) (h : subtype.val i < n) : fin n := { val := subtype.val i, property := h } @[simp] theorem coe_cast_lt {n : β„•} {m : β„•} (i : fin m) (h : subtype.val i < n) : ↑(cast_lt i h) = ↑i := rfl /-- `cast_le h i` embeds `i` into a larger `fin` type. -/ def cast_le {n : β„•} {m : β„•} (h : n ≀ m) : fin n β†ͺo fin m := order_embedding.of_strict_mono (fun (a : fin n) => cast_lt a sorry) sorry @[simp] theorem coe_cast_le {n : β„•} {m : β„•} (h : n ≀ m) (i : fin n) : ↑(coe_fn (cast_le h) i) = ↑i := rfl /-- `cast eq i` embeds `i` into a equal `fin` type. -/ def cast {n : β„•} {m : β„•} (eq : n = m) : fin n ≃o fin m := rel_iso.mk (equiv.mk ⇑(cast_le sorry) ⇑(cast_le sorry) sorry sorry) sorry @[simp] theorem symm_cast {n : β„•} {m : β„•} (h : n = m) : order_iso.symm (cast h) = cast (Eq.symm h) := rfl theorem coe_cast {n : β„•} {m : β„•} (h : n = m) (i : fin n) : ↑(coe_fn (cast h) i) = ↑i := rfl @[simp] theorem cast_trans {n : β„•} {m : β„•} {k : β„•} (h : n = m) (h' : m = k) {i : fin n} : coe_fn (cast h') (coe_fn (cast h) i) = coe_fn (cast (Eq.trans h h')) i := rfl @[simp] theorem cast_refl {n : β„•} {i : fin n} : coe_fn (cast rfl) i = i := ext (Eq.refl ↑(coe_fn (cast rfl) i)) /-- `cast_add m i` embeds `i : fin n` in `fin (n+m)`. -/ def cast_add {n : β„•} (m : β„•) : fin n β†ͺo fin (n + m) := cast_le (nat.le_add_right n m) @[simp] theorem coe_cast_add {n : β„•} (m : β„•) (i : fin n) : ↑(coe_fn (cast_add m) i) = ↑i := rfl /-- `cast_succ i` embeds `i : fin n` in `fin (n+1)`. -/ def cast_succ {n : β„•} : fin n β†ͺo fin (n + 1) := cast_add 1 @[simp] theorem coe_cast_succ {n : β„•} (i : fin n) : ↑(coe_fn cast_succ i) = ↑i := rfl theorem cast_succ_lt_succ {n : β„•} (i : fin n) : coe_fn cast_succ i < fin.succ i := sorry theorem succ_above_aux {n : β„•} (p : fin (n + 1)) : strict_mono fun (i : fin n) => ite (coe_fn cast_succ i < p) (coe_fn cast_succ i) (fin.succ i) := sorry /-- `succ_above p i` embeds `fin n` into `fin (n + 1)` with a hole around `p`. -/ def succ_above {n : β„•} (p : fin (n + 1)) : fin n β†ͺo fin (n + 1) := order_embedding.of_strict_mono (fun (a : fin n) => (fun (i : fin n) => ite (coe_fn cast_succ i < p) (coe_fn cast_succ i) (fin.succ i)) a) (succ_above_aux p) /-- `pred_above p i h` embeds `i : fin (n+1)` into `fin n` by ignoring `p`. -/ def pred_above {n : β„•} (p : fin (n + 1)) (i : fin (n + 1)) (hi : i β‰  p) : fin n := dite (i < p) (fun (h : i < p) => cast_lt i sorry) fun (h : Β¬i < p) => pred i sorry /-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/ def sub_nat {n : β„•} (m : β„•) (i : fin (n + m)) (h : m ≀ ↑i) : fin n := { val := ↑i - m, property := sorry } @[simp] theorem coe_sub_nat {n : β„•} {m : β„•} (i : fin (n + m)) (h : m ≀ ↑i) : ↑(sub_nat m i h) = ↑i - m := rfl /-- `add_nat i h` adds `m` to `i`, generalizes `fin.succ`. -/ def add_nat {n : β„•} (m : β„•) : fin n β†ͺo fin (n + m) := order_embedding.of_strict_mono (fun (i : fin n) => { val := ↑i + m, property := sorry }) sorry @[simp] theorem coe_add_nat {n : β„•} (m : β„•) (i : fin n) : ↑(coe_fn (add_nat m) i) = ↑i + m := rfl /-- `nat_add i h` adds `n` to `i` "on the left". -/ def nat_add (n : β„•) {m : β„•} : fin m β†ͺo fin (n + m) := order_embedding.of_strict_mono (fun (i : fin m) => { val := n + ↑i, property := sorry }) sorry @[simp] theorem coe_nat_add (n : β„•) {m : β„•} (i : fin m) : ↑(coe_fn (nat_add n) i) = n + ↑i := rfl /-- If `e` is an `order_iso` between `fin n` and `fin m`, then `n = m` and `e` is the identity map. In this lemma we state that for each `i : fin n` we have `(e i : β„•) = (i : β„•)`. -/ @[simp] theorem coe_order_iso_apply {n : β„•} {m : β„•} (e : fin n ≃o fin m) (i : fin n) : ↑(coe_fn e i) = ↑i := sorry protected instance order_iso_subsingleton {n : β„•} {Ξ± : Type u_1} [preorder Ξ±] : subsingleton (fin n ≃o Ξ±) := sorry protected instance order_iso_subsingleton' {n : β„•} {Ξ± : Type u_1} [preorder Ξ±] : subsingleton (Ξ± ≃o fin n) := function.injective.subsingleton order_iso.symm_injective protected instance order_iso_unique {n : β„•} : unique (fin n ≃o fin n) := unique.mk' (fin n ≃o fin n) /-- Two strictly monotone functions from `fin n` are equal provided that their ranges are equal. -/ theorem strict_mono_unique {n : β„•} {Ξ± : Type u_1} [preorder Ξ±] {f : fin n β†’ Ξ±} {g : fin n β†’ Ξ±} (hf : strict_mono f) (hg : strict_mono g) (h : set.range f = set.range g) : f = g := sorry /-- Two order embeddings of `fin n` are equal provided that their ranges are equal. -/ theorem order_embedding_eq {n : β„•} {Ξ± : Type u_1} [preorder Ξ±] {f : fin n β†ͺo Ξ±} {g : fin n β†ͺo Ξ±} (h : set.range ⇑f = set.range ⇑g) : f = g := rel_embedding.ext (iff.mp function.funext_iff (strict_mono_unique (order_embedding.strict_mono f) (order_embedding.strict_mono g) h)) @[simp] theorem succ_last (n : β„•) : fin.succ (last n) = last (Nat.succ n) := rfl @[simp] theorem cast_succ_cast_lt {n : β„•} (i : fin (n + 1)) (h : ↑i < n) : coe_fn cast_succ (cast_lt i h) = i := eq_of_veq rfl @[simp] theorem cast_lt_cast_succ {n : β„•} (a : fin n) (h : ↑a < n) : cast_lt (coe_fn cast_succ a) h = a := sorry theorem cast_succ_injective (n : β„•) : function.injective ⇑cast_succ := rel_embedding.injective cast_succ theorem cast_succ_inj {n : β„•} {a : fin n} {b : fin n} : coe_fn cast_succ a = coe_fn cast_succ b ↔ a = b := function.injective.eq_iff (cast_succ_injective n) theorem cast_succ_lt_last {n : β„•} (a : fin n) : coe_fn cast_succ a < last n := iff.mpr lt_iff_coe_lt_coe (is_lt a) @[simp] theorem cast_succ_zero {n : β„•} : coe_fn cast_succ 0 = 0 := rfl /-- `cast_succ i` is positive when `i` is positive -/ theorem cast_succ_pos {n : β„•} (i : fin (n + 1)) (h : 0 < i) : 0 < coe_fn cast_succ i := sorry theorem last_pos {n : β„•} : 0 < last (n + 1) := sorry theorem coe_nat_eq_last (n : β„•) : ↑n = last n := sorry theorem le_coe_last {n : β„•} (i : fin (n + 1)) : i ≀ ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (i ≀ ↑n)) (coe_nat_eq_last n))) (le_last i) theorem eq_last_of_not_lt {n : β„•} {i : fin (n + 1)} (h : ¬↑i < n) : i = last n := le_antisymm (le_last i) (iff.mp not_lt h) theorem add_one_pos {n : β„•} (i : fin (n + 1)) (h : i < last n) : 0 < i + 1 := sorry theorem one_pos {n : β„•} : 0 < 1 := succ_pos 0 theorem zero_ne_one {n : β„•} : 0 β‰  1 := ne_of_lt one_pos @[simp] theorem zero_eq_one_iff {n : β„•} : 0 = 1 ↔ n = 0 := { mp := nat.cases_on n (fun (h : 0 = 1) => Eq.refl 0) fun (n : β„•) (h : 0 = 1) => absurd h zero_ne_one, mpr := fun (αΎ° : n = 0) => Eq._oldrec (Eq.refl 0) (Eq.symm αΎ°) } @[simp] theorem one_eq_zero_iff {n : β„•} : 1 = 0 ↔ n = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (1 = 0 ↔ n = 0)) (propext eq_comm))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 = 1 ↔ n = 0)) (propext zero_eq_one_iff))) (iff.refl (n = 0))) theorem cast_succ_fin_succ (n : β„•) (j : fin n) : coe_fn cast_succ (fin.succ j) = fin.succ (coe_fn cast_succ j) := sorry @[simp] theorem coe_eq_cast_succ {n : β„•} {a : fin n} : ↑a = coe_fn cast_succ a := ext (coe_val_of_lt (nat.lt.step (is_lt a))) @[simp] theorem coe_succ_eq_succ {n : β„•} {a : fin n} : coe_fn cast_succ a + 1 = fin.succ a := sorry theorem lt_succ {n : β„•} {a : fin n} : coe_fn cast_succ a < fin.succ a := sorry @[simp] theorem pred_one {n : β„•} : pred 1 (ne.symm (ne_of_lt one_pos)) = 0 := rfl theorem pred_add_one {n : β„•} (i : fin (n + bit0 1)) (h : ↑i < n + 1) : pred (i + 1) (ne_of_gt (add_one_pos i (iff.mpr lt_iff_coe_lt_coe h))) = cast_lt i h := sorry theorem nat_add_zero {n : β„•} : nat_add 0 = rel_iso.to_rel_embedding (cast (Eq.symm (zero_add n))) := rel_embedding.ext fun (x : fin n) => ext (zero_add ↑x) /-- `min n m` as an element of `fin (m + 1)` -/ def clamp (n : β„•) (m : β„•) : fin (m + 1) := of_nat (min n m) @[simp] theorem coe_clamp (n : β„•) (m : β„•) : ↑(clamp n m) = min n m := nat.mod_eq_of_lt (iff.mpr nat.lt_succ_iff (min_le_right n m)) /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `cast_succ` when the resulting `i.cast_succ < p`. -/ theorem succ_above_below {n : β„•} (p : fin (n + 1)) (i : fin n) (h : coe_fn cast_succ i < p) : coe_fn (succ_above p) i = coe_fn cast_succ i := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (succ_above p) i = coe_fn cast_succ i)) (succ_above.equations._eqn_1 p))) (if_pos h) /-- Embedding `fin n` into `fin (n + 1)` with a hole around zero embeds by `succ`. -/ @[simp] theorem succ_above_zero {n : β„•} : ⇑(succ_above 0) = fin.succ := rfl /-- Embedding `fin n` into `fin (n + 1)` with a hole around `last n` embeds by `cast_succ`. -/ @[simp] theorem succ_above_last {n : β„•} : succ_above (last n) = cast_succ := sorry theorem succ_above_last_apply {n : β„•} (i : fin n) : coe_fn (succ_above (last n)) i = coe_fn cast_succ i := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (succ_above (last n)) i = coe_fn cast_succ i)) succ_above_last)) (Eq.refl (coe_fn cast_succ i)) /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `succ` when the resulting `p < i.succ`. -/ theorem succ_above_above {n : β„•} (p : fin (n + 1)) (i : fin n) (h : p ≀ coe_fn cast_succ i) : coe_fn (succ_above p) i = fin.succ i := sorry /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/ theorem succ_above_lt_ge {n : β„•} (p : fin (n + 1)) (i : fin n) : coe_fn cast_succ i < p ∨ p ≀ coe_fn cast_succ i := lt_or_ge (coe_fn cast_succ i) p /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/ theorem succ_above_lt_gt {n : β„•} (p : fin (n + 1)) (i : fin n) : coe_fn cast_succ i < p ∨ p < fin.succ i := or.cases_on (succ_above_lt_ge p i) (fun (h : coe_fn cast_succ i < p) => Or.inl h) fun (h : p ≀ coe_fn cast_succ i) => Or.inr (lt_of_le_of_lt h (cast_succ_lt_succ i)) /-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is greater results in a value that is less than `p`. -/ @[simp] theorem succ_above_lt_iff {n : β„•} (p : fin (n + 1)) (i : fin n) : coe_fn (succ_above p) i < p ↔ coe_fn cast_succ i < p := sorry /-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is lesser results in a value that is greater than `p`. -/ theorem lt_succ_above_iff {n : β„•} (p : fin (n + 1)) (i : fin n) : p < coe_fn (succ_above p) i ↔ p ≀ coe_fn cast_succ i := sorry /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` never results in `p` itself -/ theorem succ_above_ne {n : β„•} (p : fin (n + 1)) (i : fin n) : coe_fn (succ_above p) i β‰  p := sorry /-- Embedding a positive `fin n` results in a positive fin (n + 1)` -/ theorem succ_above_pos {n : β„•} (p : fin (n + bit0 1)) (i : fin (n + 1)) (h : 0 < i) : 0 < coe_fn (succ_above p) i := sorry /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ theorem succ_above_right_injective {n : β„•} {x : fin (n + 1)} : function.injective ⇑(succ_above x) := rel_embedding.injective (succ_above x) /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ theorem succ_above_right_inj {n : β„•} {a : fin n} {b : fin n} {x : fin (n + 1)} : coe_fn (succ_above x) a = coe_fn (succ_above x) b ↔ a = b := function.injective.eq_iff succ_above_right_injective /-- Embedding a `fin (n + 1)` into `fin n` and embedding it back around the same hole gives the starting `fin (n + 1)` -/ @[simp] theorem succ_above_pred_above {n : β„•} (p : fin (n + 1)) (i : fin (n + 1)) (h : i β‰  p) : coe_fn (succ_above p) (pred_above p i h) = i := sorry /-- Embedding a `fin n` into `fin (n + 1)` and embedding it back around the same hole gives the starting `fin n` -/ @[simp] theorem pred_above_succ_above {n : β„•} (p : fin (n + 1)) (i : fin n) : pred_above p (coe_fn (succ_above p) i) (succ_above_ne p i) = i := sorry @[simp] theorem pred_above_zero {n : β„•} {i : fin (n + 1)} (hi : i β‰  0) : pred_above 0 i hi = pred i hi := rfl theorem forall_iff_succ_above {n : β„•} {p : fin (n + 1) β†’ Prop} (i : fin (n + 1)) : (βˆ€ (j : fin (n + 1)), p j) ↔ p i ∧ βˆ€ (j : fin n), p (coe_fn (succ_above i) j) := sorry /-- `succ_above` is injective at the pivot -/ theorem succ_above_left_injective {n : β„•} : function.injective succ_above := sorry /-- `succ_above` is injective at the pivot -/ theorem succ_above_left_inj {n : β„•} {x : fin (n + 1)} {y : fin (n + 1)} : succ_above x = succ_above y ↔ x = y := function.injective.eq_iff succ_above_left_injective /-- A function `f` on `fin n` is strictly monotone if and only if `f i < f (i+1)` for all `i`. -/ theorem strict_mono_iff_lt_succ {n : β„•} {Ξ± : Type u_1} [preorder Ξ±] {f : fin n β†’ Ξ±} : strict_mono f ↔ βˆ€ (i : β„•) (h : i + 1 < n), f { val := i, property := lt_of_le_of_lt (nat.le_succ i) h } < f { val := i + 1, property := h } := sorry /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. -/ def succ_rec {C : (n : β„•) β†’ fin n β†’ Sort u_1} (H0 : (n : β„•) β†’ C (Nat.succ n) 0) (Hs : (n : β„•) β†’ (i : fin n) β†’ C n i β†’ C (Nat.succ n) (fin.succ i)) {n : β„•} (i : fin n) : C n i := sorry /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. A version of `fin.succ_rec` taking `i : fin n` as the first argument. -/ def succ_rec_on {n : β„•} (i : fin n) {C : (n : β„•) β†’ fin n β†’ Sort u_1} (H0 : (n : β„•) β†’ C (Nat.succ n) 0) (Hs : (n : β„•) β†’ (i : fin n) β†’ C n i β†’ C (Nat.succ n) (fin.succ i)) : C n i := succ_rec H0 Hs i @[simp] theorem succ_rec_on_zero {C : (n : β„•) β†’ fin n β†’ Sort u_1} {H0 : (n : β„•) β†’ C (Nat.succ n) 0} {Hs : (n : β„•) β†’ (i : fin n) β†’ C n i β†’ C (Nat.succ n) (fin.succ i)} (n : β„•) : succ_rec_on 0 H0 Hs = H0 n := rfl @[simp] theorem succ_rec_on_succ {C : (n : β„•) β†’ fin n β†’ Sort u_1} {H0 : (n : β„•) β†’ C (Nat.succ n) 0} {Hs : (n : β„•) β†’ (i : fin n) β†’ C n i β†’ C (Nat.succ n) (fin.succ i)} {n : β„•} (i : fin n) : succ_rec_on (fin.succ i) H0 Hs = Hs n i (succ_rec_on i H0 Hs) := subtype.cases_on i fun (i_val : β„•) (i_property : i_val < n) => Eq.refl (succ_rec_on (fin.succ { val := i_val, property := i_property }) H0 Hs) /-- Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `h0` handles the base case on `C 0`, and `hs` defines the inductive step using `C i.cast_succ`. -/ def induction {n : β„•} {C : fin (n + 1) β†’ Sort u_1} (h0 : C 0) (hs : (i : fin n) β†’ C (coe_fn cast_succ i) β†’ C (fin.succ i)) (i : fin (n + 1)) : C i := subtype.cases_on i fun (i : β„•) (hi : i < n + 1) => Nat.rec (fun (hi : 0 < n + 1) => eq.mpr sorry h0) (fun (i : β„•) (IH : (hi : i < n + 1) β†’ C { val := i, property := hi }) (hi : Nat.succ i < n + 1) => hs { val := i, property := nat.lt_of_succ_lt_succ hi } (IH sorry)) i hi /-- Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `h0` handles the base case on `C 0`, and `hs` defines the inductive step using `C i.cast_succ`. A version of `fin.induction` taking `i : fin (n + 1)` as the first argument. -/ def induction_on {n : β„•} (i : fin (n + 1)) {C : fin (n + 1) β†’ Sort u_1} (h0 : C 0) (hs : (i : fin n) β†’ C (coe_fn cast_succ i) β†’ C (fin.succ i)) : C i := induction h0 hs i /-- Define `f : Ξ  i : fin n.succ, C i` by separately handling the cases `i = 0` and `i = j.succ`, `j : fin n`. -/ def cases {n : β„•} {C : fin (Nat.succ n) β†’ Sort u_1} (H0 : C 0) (Hs : (i : fin n) β†’ C (fin.succ i)) (i : fin (Nat.succ n)) : C i := induction H0 fun (i : fin n) (_x : C (coe_fn cast_succ i)) => Hs i @[simp] theorem cases_zero {n : β„•} {C : fin (Nat.succ n) β†’ Sort u_1} {H0 : C 0} {Hs : (i : fin n) β†’ C (fin.succ i)} : cases H0 Hs 0 = H0 := rfl @[simp] theorem cases_succ {n : β„•} {C : fin (Nat.succ n) β†’ Sort u_1} {H0 : C 0} {Hs : (i : fin n) β†’ C (fin.succ i)} (i : fin n) : cases H0 Hs (fin.succ i) = Hs i := subtype.cases_on i fun (i_val : β„•) (i_property : i_val < n) => Eq.refl (cases H0 Hs (fin.succ { val := i_val, property := i_property })) @[simp] theorem cases_succ' {n : β„•} {C : fin (Nat.succ n) β†’ Sort u_1} {H0 : C 0} {Hs : (i : fin n) β†’ C (fin.succ i)} {i : β„•} (h : i + 1 < n + 1) : cases H0 Hs { val := Nat.succ i, property := h } = Hs { val := i, property := nat.lt_of_succ_lt_succ h } := nat.cases_on i (fun (h : 0 + 1 < n + 1) => Eq.refl (cases H0 Hs { val := 1, property := h })) (fun (i : β„•) (h : Nat.succ i + 1 < n + 1) => Eq.refl (cases H0 Hs { val := Nat.succ (Nat.succ i), property := h })) h theorem forall_fin_succ {n : β„•} {P : fin (n + 1) β†’ Prop} : (βˆ€ (i : fin (n + 1)), P i) ↔ P 0 ∧ βˆ€ (i : fin n), P (fin.succ i) := sorry theorem exists_fin_succ {n : β„•} {P : fin (n + 1) β†’ Prop} : (βˆƒ (i : fin (n + 1)), P i) ↔ P 0 ∨ βˆƒ (i : fin n), P (fin.succ i) := sorry /-! ### Tuples We can think of the type `Ξ (i : fin n), Ξ± i` as `n`-tuples of elements of possibly varying type `Ξ± i`. A particular case is `fin n β†’ Ξ±` of elements with all the same type. Here are some relevant operations, first about adding or removing elements at the beginning of a tuple. -/ /-- There is exactly one tuple of size zero. -/ protected instance tuple0_unique (Ξ± : fin 0 β†’ Type u) : unique ((i : fin 0) β†’ Ξ± i) := unique.mk { default := fin_zero_elim } sorry @[simp] theorem tuple0_le {Ξ± : fin 0 β†’ Type u_1} [(i : fin 0) β†’ preorder (Ξ± i)] (f : (i : fin 0) β†’ Ξ± i) (g : (i : fin 0) β†’ Ξ± i) : f ≀ g := fin_zero_elim /-- The tail of an `n+1` tuple, i.e., its last `n` entries. -/ def tail {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (q : (i : fin (n + 1)) β†’ Ξ± i) (i : fin n) : Ξ± (fin.succ i) := q (fin.succ i) /-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple. -/ def cons {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (x : Ξ± 0) (p : (i : fin n) β†’ Ξ± (fin.succ i)) (i : fin (n + 1)) : Ξ± i := cases x p j @[simp] theorem tail_cons {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (x : Ξ± 0) (p : (i : fin n) β†’ Ξ± (fin.succ i)) : tail (cons x p) = p := sorry @[simp] theorem cons_succ {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (x : Ξ± 0) (p : (i : fin n) β†’ Ξ± (fin.succ i)) (i : fin n) : cons x p (fin.succ i) = p i := sorry @[simp] theorem cons_zero {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (x : Ξ± 0) (p : (i : fin n) β†’ Ξ± (fin.succ i)) : cons x p 0 = x := sorry /-- Updating a tuple and adding an element at the beginning commute. -/ @[simp] theorem cons_update {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (x : Ξ± 0) (p : (i : fin n) β†’ Ξ± (fin.succ i)) (i : fin n) (y : Ξ± (fin.succ i)) : cons x (function.update p i y) = function.update (cons x p) (fin.succ i) y := sorry /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ theorem update_cons_zero {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (x : Ξ± 0) (p : (i : fin n) β†’ Ξ± (fin.succ i)) (z : Ξ± 0) : function.update (cons x p) 0 z = cons z p := sorry /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] theorem cons_self_tail {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (q : (i : fin (n + 1)) β†’ Ξ± i) : cons (q 0) (tail q) = q := sorry /-- Updating the first element of a tuple does not change the tail. -/ @[simp] theorem tail_update_zero {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (q : (i : fin (n + 1)) β†’ Ξ± i) (z : Ξ± 0) : tail (function.update q 0 z) = tail q := sorry /-- Updating a nonzero element and taking the tail commute. -/ @[simp] theorem tail_update_succ {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (q : (i : fin (n + 1)) β†’ Ξ± i) (i : fin n) (y : Ξ± (fin.succ i)) : tail (function.update q (fin.succ i) y) = function.update (tail q) i y := sorry theorem comp_cons {n : β„•} {Ξ± : Type u_1} {Ξ² : Type u_2} (g : Ξ± β†’ Ξ²) (y : Ξ±) (q : fin n β†’ Ξ±) : g ∘ cons y q = cons (g y) (g ∘ q) := sorry theorem comp_tail {n : β„•} {Ξ± : Type u_1} {Ξ² : Type u_2} (g : Ξ± β†’ Ξ²) (q : fin (Nat.succ n) β†’ Ξ±) : g ∘ tail q = tail (g ∘ q) := sorry theorem le_cons {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} [(i : fin (n + 1)) β†’ preorder (Ξ± i)] {x : Ξ± 0} {q : (i : fin (n + 1)) β†’ Ξ± i} {p : (i : fin n) β†’ Ξ± (fin.succ i)} : q ≀ cons x p ↔ q 0 ≀ x ∧ tail q ≀ p := sorry theorem cons_le {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} [(i : fin (n + 1)) β†’ preorder (Ξ± i)] {x : Ξ± 0} {q : (i : fin (n + 1)) β†’ Ξ± i} {p : (i : fin n) β†’ Ξ± (fin.succ i)} : cons x p ≀ q ↔ x ≀ q 0 ∧ p ≀ tail q := le_cons /-- `fin.append ho u v` appends two vectors of lengths `m` and `n` to produce one of length `o = m + n`. `ho` provides control of definitional equality for the vector length. -/ def append {n : β„•} {m : β„•} {Ξ± : Type u_1} {o : β„•} (ho : o = m + n) (u : fin m β†’ Ξ±) (v : fin n β†’ Ξ±) : fin o β†’ Ξ± := fun (i : fin o) => dite (↑i < m) (fun (h : ↑i < m) => u { val := ↑i, property := h }) fun (h : ¬↑i < m) => v { val := ↑i - m, property := sorry } @[simp] theorem fin_append_apply_zero {n : β„•} {m : β„•} {Ξ± : Type u_1} {o : β„•} (ho : o + 1 = m + 1 + n) (u : fin (m + 1) β†’ Ξ±) (v : fin n β†’ Ξ±) : append ho u v 0 = u 0 := rfl /-! In the previous section, we have discussed inserting or removing elements on the left of a tuple. In this section, we do the same on the right. A difference is that `fin (n+1)` is constructed inductively from `fin n` starting from the left, not from the right. This implies that Lean needs more help to realize that elements belong to the right types, i.e., we need to insert casts at several places. -/ /-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/ def init {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (q : (i : fin (n + 1)) β†’ Ξ± i) (i : fin n) : Ξ± (coe_fn cast_succ i) := q (coe_fn cast_succ i) /-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/ def snoc {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (p : (i : fin n) β†’ Ξ± (coe_fn cast_succ i)) (x : Ξ± (last n)) (i : fin (n + 1)) : Ξ± i := dite (subtype.val i < n) (fun (h : subtype.val i < n) => cast sorry (p (cast_lt i h))) fun (h : Β¬subtype.val i < n) => cast sorry x @[simp] theorem init_snoc {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (x : Ξ± (last n)) (p : (i : fin n) β†’ Ξ± (coe_fn cast_succ i)) : init (snoc p x) = p := sorry @[simp] theorem snoc_cast_succ {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (x : Ξ± (last n)) (p : (i : fin n) β†’ Ξ± (coe_fn cast_succ i)) (i : fin n) : snoc p x (coe_fn cast_succ i) = p i := sorry @[simp] theorem snoc_last {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (x : Ξ± (last n)) (p : (i : fin n) β†’ Ξ± (coe_fn cast_succ i)) : snoc p x (last n) = x := sorry /-- Updating a tuple and adding an element at the end commute. -/ @[simp] theorem snoc_update {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (x : Ξ± (last n)) (p : (i : fin n) β†’ Ξ± (coe_fn cast_succ i)) (i : fin n) (y : Ξ± (coe_fn cast_succ i)) : snoc (function.update p i y) x = function.update (snoc p x) (coe_fn cast_succ i) y := sorry /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ theorem update_snoc_last {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (x : Ξ± (last n)) (p : (i : fin n) β†’ Ξ± (coe_fn cast_succ i)) (z : Ξ± (last n)) : function.update (snoc p x) (last n) z = snoc p z := sorry /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] theorem snoc_init_self {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (q : (i : fin (n + 1)) β†’ Ξ± i) : snoc (init q) (q (last n)) = q := sorry /-- Updating the last element of a tuple does not change the beginning. -/ @[simp] theorem init_update_last {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (q : (i : fin (n + 1)) β†’ Ξ± i) (z : Ξ± (last n)) : init (function.update q (last n) z) = init q := sorry /-- Updating an element and taking the beginning commute. -/ @[simp] theorem init_update_cast_succ {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (q : (i : fin (n + 1)) β†’ Ξ± i) (i : fin n) (y : Ξ± (coe_fn cast_succ i)) : init (function.update q (coe_fn cast_succ i) y) = function.update (init q) i y := sorry /-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ theorem tail_init_eq_init_tail {n : β„•} {Ξ² : Type u_1} (q : fin (n + bit0 1) β†’ Ξ²) : tail (init q) = init (tail q) := sorry /-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ theorem cons_snoc_eq_snoc_cons {n : β„•} {Ξ² : Type u_1} (a : Ξ²) (q : fin n β†’ Ξ²) (b : Ξ²) : cons a (snoc q b) = snoc (cons a q) b := sorry theorem comp_snoc {n : β„•} {Ξ± : Type u_1} {Ξ² : Type u_2} (g : Ξ± β†’ Ξ²) (q : fin n β†’ Ξ±) (y : Ξ±) : g ∘ snoc q y = snoc (g ∘ q) (g y) := sorry theorem comp_init {n : β„•} {Ξ± : Type u_1} {Ξ² : Type u_2} (g : Ξ± β†’ Ξ²) (q : fin (Nat.succ n) β†’ Ξ±) : g ∘ init q = init (g ∘ q) := sorry /-- Insert an element into a tuple at a given position. For `i = 0` see `fin.cons`, for `i = fin.last n` see `fin.snoc`. -/ def insert_nth {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (i : fin (n + 1)) (x : Ξ± i) (p : (j : fin n) β†’ Ξ± (coe_fn (succ_above i) j)) (j : fin (n + 1)) : Ξ± j := dite (j = i) (fun (h : j = i) => cast sorry x) fun (h : Β¬j = i) => cast sorry (p (pred_above i j h)) @[simp] theorem insert_nth_apply_same {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (i : fin (n + 1)) (x : Ξ± i) (p : (j : fin n) β†’ Ξ± (coe_fn (succ_above i) j)) : insert_nth i x p i = x := sorry @[simp] theorem insert_nth_apply_succ_above {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (i : fin (n + 1)) (x : Ξ± i) (p : (j : fin n) β†’ Ξ± (coe_fn (succ_above i) j)) (j : fin n) : insert_nth i x p (coe_fn (succ_above i) j) = p j := sorry @[simp] theorem insert_nth_comp_succ_above {n : β„•} {Ξ² : Type v} (i : fin (n + 1)) (x : Ξ²) (p : fin n β†’ Ξ²) : insert_nth i x p ∘ ⇑(succ_above i) = p := funext (insert_nth_apply_succ_above i x p) theorem insert_nth_eq_iff {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} {i : fin (n + 1)} {x : Ξ± i} {p : (j : fin n) β†’ Ξ± (coe_fn (succ_above i) j)} {q : (j : fin (n + 1)) β†’ Ξ± j} : insert_nth i x p = q ↔ q i = x ∧ p = fun (j : fin n) => q (coe_fn (succ_above i) j) := sorry theorem eq_insert_nth_iff {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} {i : fin (n + 1)} {x : Ξ± i} {p : (j : fin n) β†’ Ξ± (coe_fn (succ_above i) j)} {q : (j : fin (n + 1)) β†’ Ξ± j} : q = insert_nth i x p ↔ q i = x ∧ p = fun (j : fin n) => q (coe_fn (succ_above i) j) := iff.trans eq_comm insert_nth_eq_iff theorem insert_nth_zero {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (x : Ξ± 0) (p : (j : fin n) β†’ Ξ± (coe_fn (succ_above 0) j)) : insert_nth 0 x p = cons x fun (j : fin n) => cast (congr_arg Ξ± (congr_fun succ_above_zero j)) (p j) := sorry @[simp] theorem insert_nth_zero' {n : β„•} {Ξ² : Type v} (x : Ξ²) (p : fin n β†’ Ξ²) : insert_nth 0 x p = cons x p := sorry theorem insert_nth_last {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} (x : Ξ± (last n)) (p : (j : fin n) β†’ Ξ± (coe_fn (succ_above (last n)) j)) : insert_nth (last n) x p = snoc (fun (j : fin n) => cast (congr_arg Ξ± (succ_above_last_apply j)) (p j)) x := sorry @[simp] theorem insert_nth_last' {n : β„•} {Ξ² : Type v} (x : Ξ²) (p : fin n β†’ Ξ²) : insert_nth (last n) x p = snoc p x := sorry theorem insert_nth_le_iff {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} [(i : fin (n + 1)) β†’ preorder (Ξ± i)] {i : fin (n + 1)} {x : Ξ± i} {p : (j : fin n) β†’ Ξ± (coe_fn (succ_above i) j)} {q : (j : fin (n + 1)) β†’ Ξ± j} : insert_nth i x p ≀ q ↔ x ≀ q i ∧ p ≀ fun (j : fin n) => q (coe_fn (succ_above i) j) := sorry theorem le_insert_nth_iff {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} [(i : fin (n + 1)) β†’ preorder (Ξ± i)] {i : fin (n + 1)} {x : Ξ± i} {p : (j : fin n) β†’ Ξ± (coe_fn (succ_above i) j)} {q : (j : fin (n + 1)) β†’ Ξ± j} : q ≀ insert_nth i x p ↔ q i ≀ x ∧ (fun (j : fin n) => q (coe_fn (succ_above i) j)) ≀ p := sorry theorem insert_nth_mem_Icc {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} [(i : fin (n + 1)) β†’ preorder (Ξ± i)] {i : fin (n + 1)} {x : Ξ± i} {p : (j : fin n) β†’ Ξ± (coe_fn (succ_above i) j)} {q₁ : (j : fin (n + 1)) β†’ Ξ± j} {qβ‚‚ : (j : fin (n + 1)) β†’ Ξ± j} : insert_nth i x p ∈ set.Icc q₁ qβ‚‚ ↔ x ∈ set.Icc (q₁ i) (qβ‚‚ i) ∧ p ∈ set.Icc (fun (j : fin n) => q₁ (coe_fn (succ_above i) j)) fun (j : fin n) => qβ‚‚ (coe_fn (succ_above i) j) := sorry theorem preimage_insert_nth_Icc_of_mem {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} [(i : fin (n + 1)) β†’ preorder (Ξ± i)] {i : fin (n + 1)} {x : Ξ± i} {q₁ : (j : fin (n + 1)) β†’ Ξ± j} {qβ‚‚ : (j : fin (n + 1)) β†’ Ξ± j} (hx : x ∈ set.Icc (q₁ i) (qβ‚‚ i)) : insert_nth i x ⁻¹' set.Icc q₁ qβ‚‚ = set.Icc (fun (j : fin n) => q₁ (coe_fn (succ_above i) j)) fun (j : fin n) => qβ‚‚ (coe_fn (succ_above i) j) := sorry theorem preimage_insert_nth_Icc_of_not_mem {n : β„•} {Ξ± : fin (n + 1) β†’ Type u} [(i : fin (n + 1)) β†’ preorder (Ξ± i)] {i : fin (n + 1)} {x : Ξ± i} {q₁ : (j : fin (n + 1)) β†’ Ξ± j} {qβ‚‚ : (j : fin (n + 1)) β†’ Ξ± j} (hx : Β¬x ∈ set.Icc (q₁ i) (qβ‚‚ i)) : insert_nth i x ⁻¹' set.Icc q₁ qβ‚‚ = βˆ… := sorry /-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. -/ def find {n : β„•} (p : fin n β†’ Prop) [decidable_pred p] : Option (fin n) := sorry /-- If `find p = some i`, then `p i` holds -/ theorem find_spec {n : β„•} (p : fin n β†’ Prop) [decidable_pred p] {i : fin n} (hi : i ∈ find p) : p i := sorry /-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/ theorem is_some_find_iff {n : β„•} {p : fin n β†’ Prop} [decidable_pred p] : β†₯(option.is_some (find p)) ↔ βˆƒ (i : fin n), p i := sorry /-- `find p` returns `none` if and only if `p i` never holds. -/ theorem find_eq_none_iff {n : β„•} {p : fin n β†’ Prop} [decidable_pred p] : find p = none ↔ βˆ€ (i : fin n), Β¬p i := sorry /-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among the indices where `p` holds. -/ theorem find_min {n : β„•} {p : fin n β†’ Prop} [decidable_pred p] {i : fin n} (hi : i ∈ find p) {j : fin n} (hj : j < i) : Β¬p j := sorry theorem find_min' {n : β„•} {p : fin n β†’ Prop} [decidable_pred p] {i : fin n} (h : i ∈ find p) {j : fin n} (hj : p j) : i ≀ j := le_of_not_gt fun (hij : i > j) => find_min h hij hj theorem nat_find_mem_find {n : β„•} {p : fin n β†’ Prop} [decidable_pred p] (h : βˆƒ (i : β„•), βˆƒ (hin : i < n), p { val := i, property := hin }) : { val := nat.find h, property := Exists.fst (nat.find_spec h) } ∈ find p := sorry theorem mem_find_iff {n : β„•} {p : fin n β†’ Prop} [decidable_pred p] {i : fin n} : i ∈ find p ↔ p i ∧ βˆ€ (j : fin n), p j β†’ i ≀ j := sorry theorem find_eq_some_iff {n : β„•} {p : fin n β†’ Prop} [decidable_pred p] {i : fin n} : find p = some i ↔ p i ∧ βˆ€ (j : fin n), p j β†’ i ≀ j := mem_find_iff theorem mem_find_of_unique {n : β„•} {p : fin n β†’ Prop} [decidable_pred p] (h : βˆ€ (i j : fin n), p i β†’ p j β†’ i = j) {i : fin n} (hi : p i) : i ∈ find p := iff.mpr mem_find_iff { left := hi, right := fun (j : fin n) (hj : p j) => le_of_eq (h i j hi hj) } @[simp] theorem coe_of_nat_eq_mod (m : β„•) (n : β„•) : ↑↑n = n % Nat.succ m := eq.mpr (id (Eq._oldrec (Eq.refl (↑↑n = n % Nat.succ m)) (Eq.symm (of_nat_eq_coe m n)))) (Eq.refl ↑(of_nat n)) @[simp] theorem coe_of_nat_eq_mod' (m : β„•) (n : β„•) [I : fact (0 < m)] : ↑(of_nat' n) = n % m := rfl @[simp] protected theorem add_zero {n : β„•} (k : fin (n + 1)) : k + 0 = k := sorry @[simp] protected theorem zero_add {n : β„•} (k : fin (n + 1)) : 0 + k = k := sorry @[simp] protected theorem mul_one {n : β„•} (k : fin (n + 1)) : k * 1 = k := sorry @[simp] protected theorem one_mul {n : β„•} (k : fin (n + 1)) : 1 * k = k := sorry @[simp] protected theorem mul_zero {n : β„•} (k : fin (n + 1)) : k * 0 = 0 := sorry @[simp] protected theorem zero_mul {n : β„•} (k : fin (n + 1)) : 0 * k = 0 := sorry protected instance add_comm_monoid (n : β„•) : add_comm_monoid (fin (n + 1)) := add_comm_monoid.mk Add.add sorry 0 fin.zero_add fin.add_zero sorry
22f3112e66c0f2f4a829859a10b2621baca14049
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/tactic_error_pos.lean
ffbd369c65678bea8204fa300cf121b6e77f1980
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,145
lean
example (p q : Prop) (h1 : p) (h2 : q) : p ∧ q := begin exact (or.inl _) --^ type mismatch here (OK) end example (p q : Prop) (h1 : p) (h2 : q) : p ∧ q := begin exact (and.intro _ h2) --^ don't know how to synthesize placeholder here (OK) end example (p q : Prop) (h1 : p) (h2 : q) : p ∧ q := begin abstract {exact (and.intro _ h2)} --^ don't know how to synthesize placeholder here (OK) end example (p q : Prop) (h1 : p) (h2 : q) : p ∧ q := begin {exact (and.intro _ h2) } <|> apply and.intro --^ should not show error here (BUG) end example (p q : Prop) (h1 : p) (h2 : q) : p ∧ q := begin try {exact (and.intro _ h2) } --^ should not show error here (BUG) end example (p q : Prop) (h1 : p) (h2 : q) : p ∧ q := begin repeat {exact (and.intro _ h2) } --^ should not show error here (BUG) end open tactic meta def mytac : tactic unit := `[apply (or.inl _)] example (p q : Prop) (h1 : p) (h2 : q) : p ∧ q := begin mytac --^ failed to unify error here, it shoult *not* be at mytac or.inl (OK) end
493361e105b7401cb61729979a9b1329c9331f8f
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/algebra/category/Group/limits.lean
23d70ed325335d61871db608f5e7ca1eaaf2c4dc
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,772
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Mon.limits import algebra.category.Group.preadditive import category_theory.over import category_theory.limits.concrete_category import category_theory.limits.shapes.concrete_category import group_theory.subgroup /-! # The category of (commutative) (additive) groups has all limits Further, these limits are preserved by the forgetful functor --- that is, the underlying types are just the limits in the category of types. -/ open category_theory open category_theory.limits universe u noncomputable theory variables {J : Type u} [small_category J] namespace Group @[to_additive] instance group_obj (F : J β₯€ Group) (j) : group ((F β‹™ forget Group).obj j) := by { change group (F.obj j), apply_instance } /-- The flat sections of a functor into `Group` form a subgroup of all sections. -/ @[to_additive "The flat sections of a functor into `AddGroup` form an additive subgroup of all sections."] def sections_subgroup (F : J β₯€ Group) : subgroup (Ξ  j, F.obj j) := { carrier := (F β‹™ forget Group).sections, inv_mem' := Ξ» a ah j j' f, begin simp only [forget_map_eq_coe, functor.comp_map, pi.inv_apply, monoid_hom.map_inv, inv_inj], dsimp [functor.sections] at ah, rw ah f, end, ..(Mon.sections_submonoid (F β‹™ forgetβ‚‚ Group Mon)) } @[to_additive] instance limit_group (F : J β₯€ Group) : group (types.limit_cone (F β‹™ forget Group.{u})).X := begin change group (sections_subgroup F), apply_instance, end /-- We show that the forgetful functor `Group β₯€ Mon` creates limits. All we need to do is notice that the limit point has a `group` instance available, and then reuse the existing limit. -/ @[to_additive] instance (F : J β₯€ Group) : creates_limit F (forgetβ‚‚ Group Mon.{u}) := creates_limit_of_reflects_iso (Ξ» c' t, { lifted_cone := { X := Group.of (types.limit_cone (F β‹™ forget Group)).X, Ο€ := { app := Mon.limit_Ο€_monoid_hom (F β‹™ forgetβ‚‚ Group Mon.{u}), naturality' := (Mon.has_limits.limit_cone (F β‹™ forgetβ‚‚ _ _)).Ο€.naturality, } }, valid_lift := is_limit.unique_up_to_iso (Mon.has_limits.limit_cone_is_limit _) t, makes_limit := is_limit.of_faithful (forgetβ‚‚ Group Mon.{u}) (Mon.has_limits.limit_cone_is_limit _) (Ξ» s, _) (Ξ» s, rfl) }) /-- A choice of limit cone for a functor into `Group`. (Generally, you'll just want to use `limit F`.) -/ @[to_additive "A choice of limit cone for a functor into `Group`. (Generally, you'll just want to use `limit F`.)"] def limit_cone (F : J β₯€ Group) : cone F := lift_limit (limit.is_limit (F β‹™ (forgetβ‚‚ Group Mon.{u}))) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ @[to_additive "The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.)"] def limit_cone_is_limit (F : J β₯€ Group) : is_limit (limit_cone F) := lifted_limit_is_limit _ /-- The category of groups has all limits. -/ @[to_additive] instance has_limits : has_limits Group := { has_limits_of_shape := Ξ» J π’₯, by exactI { has_limit := Ξ» F, has_limit_of_created F (forgetβ‚‚ Group Mon) } } -- TODO use the above instead? /-- The forgetful functor from groups to monoids preserves all limits. (That is, the underlying monoid could have been computed instead as limits in the category of monoids.) -/ @[to_additive AddGroup.forgetβ‚‚_AddMon_preserves_limits] instance forgetβ‚‚_Mon_preserves_limits : preserves_limits (forgetβ‚‚ Group Mon) := { preserves_limits_of_shape := Ξ» J π’₯, { preserves_limit := Ξ» F, by apply_instance } } /-- The forgetful functor from groups to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ @[to_additive] instance forget_preserves_limits : preserves_limits (forget Group) := { preserves_limits_of_shape := Ξ» J π’₯, by exactI { preserves_limit := Ξ» F, limits.comp_preserves_limit (forgetβ‚‚ Group Mon) (forget Mon) } } end Group namespace CommGroup @[to_additive] instance comm_group_obj (F : J β₯€ CommGroup) (j) : comm_group ((F β‹™ forget CommGroup).obj j) := by { change comm_group (F.obj j), apply_instance } @[to_additive] instance limit_comm_group (F : J β₯€ CommGroup) : comm_group (types.limit_cone (F β‹™ forget CommGroup.{u})).X := @subgroup.to_comm_group (Ξ  j, F.obj j) _ (Group.sections_subgroup (F β‹™ forgetβ‚‚ CommGroup Group.{u})) /-- We show that the forgetful functor `CommGroup β₯€ Group` creates limits. All we need to do is notice that the limit point has a `comm_group` instance available, and then reuse the existing limit. -/ @[to_additive] instance (F : J β₯€ CommGroup) : creates_limit F (forgetβ‚‚ CommGroup Group.{u}) := creates_limit_of_reflects_iso (Ξ» c' t, { lifted_cone := { X := CommGroup.of (types.limit_cone (F β‹™ forget CommGroup)).X, Ο€ := { app := Mon.limit_Ο€_monoid_hom (F β‹™ forgetβ‚‚ CommGroup Group.{u} β‹™ forgetβ‚‚ Group Mon), naturality' := (Mon.has_limits.limit_cone _).Ο€.naturality, } }, valid_lift := is_limit.unique_up_to_iso (Group.limit_cone_is_limit _) t, makes_limit := is_limit.of_faithful (forgetβ‚‚ _ Group.{u} β‹™ forgetβ‚‚ _ Mon.{u}) (Mon.has_limits.limit_cone_is_limit _) (Ξ» s, _) (Ξ» s, rfl) }) /-- A choice of limit cone for a functor into `CommGroup`. (Generally, you'll just want to use `limit F`.) -/ @[to_additive "A choice of limit cone for a functor into `CommGroup`. (Generally, you'll just want to use `limit F`.)"] def limit_cone (F : J β₯€ CommGroup) : cone F := lift_limit (limit.is_limit (F β‹™ (forgetβ‚‚ CommGroup Group.{u}))) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ @[to_additive "The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.)"] def limit_cone_is_limit (F : J β₯€ CommGroup) : is_limit (limit_cone F) := lifted_limit_is_limit _ /-- The category of commutative groups has all limits. -/ @[to_additive] instance has_limits : has_limits CommGroup := { has_limits_of_shape := Ξ» J π’₯, by exactI { has_limit := Ξ» F, has_limit_of_created F (forgetβ‚‚ CommGroup Group) } } /-- The forgetful functor from commutative groups to groups preserves all limits. (That is, the underlying group could have been computed instead as limits in the category of groups.) -/ @[to_additive AddCommGroup.forgetβ‚‚_AddGroup_preserves_limits] instance forgetβ‚‚_Group_preserves_limits : preserves_limits (forgetβ‚‚ CommGroup Group) := { preserves_limits_of_shape := Ξ» J π’₯, { preserves_limit := Ξ» F, by apply_instance } } /-- An auxiliary declaration to speed up typechecking. -/ @[to_additive AddCommGroup.forgetβ‚‚_AddCommMon_preserves_limits_aux "An auxiliary declaration to speed up typechecking."] def forgetβ‚‚_CommMon_preserves_limits_aux (F : J β₯€ CommGroup) : is_limit ((forgetβ‚‚ CommGroup CommMon).map_cone (limit_cone F)) := CommMon.limit_cone_is_limit (F β‹™ forgetβ‚‚ CommGroup CommMon) /-- The forgetful functor from commutative groups to commutative monoids preserves all limits. (That is, the underlying commutative monoids could have been computed instead as limits in the category of commutative monoids.) -/ @[to_additive AddCommGroup.forgetβ‚‚_AddCommMon_preserves_limits] instance forgetβ‚‚_CommMon_preserves_limits : preserves_limits (forgetβ‚‚ CommGroup CommMon) := { preserves_limits_of_shape := Ξ» J π’₯, by exactI { preserves_limit := Ξ» F, preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forgetβ‚‚_CommMon_preserves_limits_aux F) } } /-- The forgetful functor from commutative groups to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ @[to_additive AddCommGroup.forget_preserves_limits] instance forget_preserves_limits : preserves_limits (forget CommGroup) := { preserves_limits_of_shape := Ξ» J π’₯, by exactI { preserves_limit := Ξ» F, limits.comp_preserves_limit (forgetβ‚‚ CommGroup Group) (forget Group) } } end CommGroup namespace AddCommGroup /-- The categorical kernel of a morphism in `AddCommGroup` agrees with the usual group-theoretical kernel. -/ def kernel_iso_ker {G H : AddCommGroup} (f : G ⟢ H) : kernel f β‰… AddCommGroup.of f.ker := { hom := { to_fun := Ξ» g, ⟨kernel.ΞΉ f g, begin -- TODO where is this `has_coe_t_aux.coe` coming from? can we prevent it appearing? change (kernel.ΞΉ f) g ∈ f.ker, simp [add_monoid_hom.mem_ker], end⟩, map_zero' := by { ext, simp, }, map_add' := Ξ» g g', by { ext, simp, }, }, inv := kernel.lift f (add_subgroup.subtype f.ker) (by tidy), hom_inv_id' := by { apply equalizer.hom_ext _, ext, simp, }, inv_hom_id' := begin apply AddCommGroup.ext, simp only [add_monoid_hom.coe_mk, coe_id, coe_comp], rintro ⟨x, mem⟩, simp, end, }. @[simp] lemma kernel_iso_ker_hom_comp_subtype {G H : AddCommGroup} (f : G ⟢ H) : (kernel_iso_ker f).hom ≫ add_subgroup.subtype f.ker = kernel.ΞΉ f := begin ext, simp [kernel_iso_ker], end @[simp] lemma kernel_iso_ker_inv_comp_ΞΉ {G H : AddCommGroup} (f : G ⟢ H) : (kernel_iso_ker f).inv ≫ kernel.ΞΉ f = add_subgroup.subtype f.ker := begin ext, simp [kernel_iso_ker], end /-- The categorical kernel inclusion for `f : G ⟢ H`, as an object over `G`, agrees with the `subtype` map. -/ @[simps {rhs_md:=semireducible}] def kernel_iso_ker_over {G H : AddCommGroup.{u}} (f : G ⟢ H) : over.mk (kernel.ΞΉ f) β‰… @over.mk _ _ G (AddCommGroup.of f.ker) (add_subgroup.subtype f.ker) := over.iso_mk (kernel_iso_ker f) (by simp) end AddCommGroup
7b400899f3b37eb9ffab1ab33917c2f014ca5365
29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f
/31_lecture.lean
1c864b391f9367de98c527305ed23f78b1df3b1a
[]
no_license
KjellZijlemaker/Logical_Verification_VU
ced0ba95316a30e3c94ba8eebd58ea004fa6f53b
4578b93bf1615466996157bb333c84122b201d99
refs/heads/master
1,585,966,086,108
1,549,187,704,000
1,549,187,704,000
155,690,284
0
0
null
null
null
null
UTF-8
Lean
false
false
9,540
lean
/- Lecture 3.1: Program Semantics β€” Operational Semantics -/ import .x31_library attribute [pattern] or.intro_left or.intro_right /- A WHILE programming language -/ section syntax inductive program (Οƒ : Type) : Type | skip {} : program | assign : (Οƒ β†’ Οƒ) β†’ program | seq : program β†’ program β†’ program | ite : (Οƒ β†’ Prop) β†’ program β†’ program β†’ program | while : (Οƒ β†’ Prop) β†’ program β†’ program end syntax /- Big-step semantics -/ open program section semantics variables {Οƒ : Type} {c : Οƒ β†’ Prop} {f : Οƒ β†’ Οƒ} {p pβ‚€ p₁ pβ‚‚ : program Οƒ} {s sβ‚€ s₁ sβ‚‚ t u : Οƒ} /- `big_step p s s'`: when started in `s`, program `p` terminates in `s'`. -/ inductive big_step : (program Οƒ Γ— Οƒ) β†’ Οƒ β†’ Prop | skip {s} : big_step (skip, s) s | assign {f s} : big_step (assign f, s) (f s) | seq {p₁ pβ‚‚ s u} (t) (h₁ : big_step (p₁, s) t) (hβ‚‚ : big_step (pβ‚‚, t) u) : big_step (seq p₁ pβ‚‚, s) u | ite_true {c : Οƒ β†’ Prop} {p₁ pβ‚€ s t} (hs : c s) (h : big_step (p₁, s) t) : big_step (ite c p₁ pβ‚€, s) t | ite_false {c : Οƒ β†’ Prop} {p₁ pβ‚€ s t} (hs : Β¬ c s) (h : big_step (pβ‚€, s) t) : big_step (ite c p₁ pβ‚€, s) t | while_true {c : Οƒ β†’ Prop} {p s u} (t) (hs : c s) (hp : big_step (p, s) t) (hw : big_step (while c p, t) u) : big_step (while c p, s) u | while_false {c : Οƒ β†’ Prop} {p s} (hs : Β¬ c s) : big_step (while c p, s) s /- Mixfix notation for `big_step`: (p, s) ⟹ s' := big_step (p, s) s'. `⟹` is entered as `\==>`. -/ infix ` ⟹ `:110 := big_step section tactics open tactic /- Finds two local hypotheses `hnp : Β¬ p` and `hp : p` and solves the goal by contradiction -/ meta def find_absurd : tactic unit := do hs ← local_context, hs.mfirst $ Ξ»hn, do `(Β¬ %%p) ← infer_type hn, (hs.mfirst $ Ξ»h, do p' ← infer_type h, is_def_eq p p', to_expr ``(false.elim (%%hn %%h)) >>= exact) /- For a `ih : βˆ€x, p x β†’ q x`, finds all matching `h : p t` and resolves `ih` with each `h` -/ meta def resolve_all : tactic unit := do hs ← local_context, hs.mfirst $ Ξ»ih, do ([x, h'], g) ← infer_type ih >>= mk_local_pis, p ← mk_pattern [] [x] h' [] [x], l ← hs.reverse.mmap $ Ξ»h, (do ([], [x']) ← match_pattern p h, tactic.note ih.local_pp_name none (ih x' h), pure tt) <|> pure ff, if l.bor then clear ih else skip /- Resolves all `ih : βˆ€x, p x β†’ q x` with all `h : p t` and substitutes all occurrences of `x = t` or `t = x` -/ meta def tactic.interactive.resolve_subst : tactic unit := repeat (resolve_all >> subst_vars) end tactics /- The `big_step` semantics is deterministic: two terminating program executions result in the same output -/ lemma big_step_unique (ht : (p, s) ⟹ t) (hu : (p, s) ⟹ u) : u = t := begin induction ht generalizing u hu; cases hu; resolve_subst; try { refl <|> find_absurd } end lemma not_cond_of_big_step_while : (while c p, s) ⟹ t β†’ Β¬ c t := begin generalize eq_ps : (while c p, s) = ps, intro h, induction h generalizing s eq_ps; cases eq_ps, { apply h_ih_hw, refl }, { assumption } end /- Inversion rules for `⟹` -/ @[simp] lemma big_step_skip_iff : (skip, s) ⟹ t ↔ t = s := iff.intro (assume h, match t, h with _, big_step.skip := by refl end) (assume h, match t, h with _, rfl := big_step.skip end) @[simp] lemma big_step_assign_iff : (assign f, s) ⟹ t ↔ t = f s := iff.intro (assume h, match t, h with _, big_step.assign := rfl end) (assume h, match t, h with _, rfl := big_step.assign end) @[simp] lemma big_step_seq_iff : (seq p₁ pβ‚‚, s) ⟹ t ↔ (βˆƒu, (p₁, s) ⟹ u ∧ (pβ‚‚, u) ⟹ t) := iff.intro (assume h, match h with big_step.seq u h₁ hβ‚‚ := ⟨u, h₁, hβ‚‚βŸ© end) (assume h, match h with ⟨u, h₁, hβ‚‚βŸ© := big_step.seq u h₁ hβ‚‚ end) @[simp] lemma big_step_ite_iff : (ite c p₁ pβ‚€, s) ⟹ t ↔ ((c s ∧ (p₁, s) ⟹ t) ∨ (Β¬ c s ∧ (pβ‚€, s) ⟹ t)) := iff.intro (assume h, match h with | big_step.ite_true hs h := or.intro_left _ ⟨hs, h⟩ | big_step.ite_false hs h := or.intro_right _ ⟨hs, h⟩ end) (assume h, match h with | or.intro_left _ ⟨hs, h⟩ := big_step.ite_true hs h | or.intro_right _ ⟨hs, h⟩ := big_step.ite_false hs h end) lemma big_step_while_iff : (while c p, s) ⟹ t ↔ (βˆƒu, c s ∧ (p, s) ⟹ u ∧ (while c p, u) ⟹ t) ∨ (Β¬ c s ∧ t = s) := iff.intro (assume h, match t, h with | t, big_step.while_true u hs h₁ hβ‚‚ := or.intro_left _ ⟨u, hs, h₁, hβ‚‚βŸ© | s, big_step.while_false hs := or.intro_right _ ⟨hs, rfl⟩ end) (assume h, match t, h with | _, or.intro_left _ ⟨u, hs, h₁, hβ‚‚βŸ© := big_step.while_true u hs h₁ hβ‚‚ | _, or.intro_right _ ⟨hs, rfl⟩ := big_step.while_false hs end) @[simp] lemma big_step_while_true_iff (hs : c s) : (while c p, s) ⟹ t ↔ (βˆƒu, (p, s) ⟹ u ∧ (while c p, u) ⟹ t) := by rw [big_step_while_iff]; simp [hs] @[simp] lemma big_step_while_false_iff (hs : Β¬ c s) : (while c p, s) ⟹ t ↔ t = s := by rw [big_step_while_iff]; simp [hs] /- Small-step semantics -/ inductive small_step : program Οƒ Γ— Οƒ β†’ program Οƒ Γ— Οƒ β†’ Prop | assign {f s} : small_step (assign f, s) (skip, f s) | seq_step {p₁ pβ‚‚ s s'} (p) : small_step (p₁, s) (p, s') β†’ small_step (seq p₁ pβ‚‚, s) (seq p pβ‚‚, s') | seq_skip {p s} : small_step (seq skip p, s) (p, s) | ite_true {c : Οƒ β†’ Prop} {p₁ pβ‚€ s} : c s β†’ small_step (ite c p₁ pβ‚€, s) (p₁, s) | ite_false {c : Οƒ β†’ Prop} {p₁ pβ‚€ s} : Β¬ c s β†’ small_step (ite c p₁ pβ‚€, s) (pβ‚€, s) | while {c : Οƒ β†’ Prop} {p s} : small_step (while c p, s) (ite c (seq p (while c p)) skip, s) /- Mixfix notations for `small_step`: ps β‡’ qt := small_step ps qt ps β‡’* qt := refl_trans small_step ps qt -/ infixr ` β‡’ ` := small_step infixr ` β‡’* ` : 100 := refl_trans small_step /- Inversion rules for `β‡’` -/ @[simp] lemma small_step_skip : Β¬ ((skip, s) β‡’ (p, t)) := assume h, match h with end lemma small_step_seq_iff {v : program Οƒ Γ— Οƒ} : (seq p₁ pβ‚‚, s) β‡’ v ↔ (βˆƒp t, (p₁, s) β‡’ (p, t) ∧ v = (seq p pβ‚‚, t)) ∨ (p₁ = skip ∧ v = (pβ‚‚, s)) := iff.intro (assume h, match p₁, v, h with | _, (_, t), small_step.seq_step p h := or.intro_left _ ⟨p, t, h, rfl⟩ | _, _, small_step.seq_skip := or.intro_right _ ⟨rfl, rfl⟩ end) (assume h, match p₁, v, h with | _, _, or.intro_left _ ⟨p, t, h, rfl⟩ := small_step.seq_step p h | _, _, or.intro_right _ ⟨rfl, rfl⟩ := small_step.seq_skip end) @[simp] lemma small_step_ite_iff {v : program Οƒ Γ— Οƒ} : (ite c p₁ pβ‚‚, s) β‡’ v ↔ (c s ∧ v = (p₁, s)) ∨ (Β¬ c s ∧ v = (pβ‚‚, s)) := iff.intro (assume h, match v, h with | _, small_step.ite_true h := or.intro_left _ ⟨h, rfl⟩ | _, small_step.ite_false h := or.intro_right _ ⟨h, rfl⟩ end) (assume h, match v, h with | _, or.intro_left _ ⟨h, rfl⟩ := small_step.ite_true h | _, or.intro_right _ ⟨h, rfl⟩ := small_step.ite_false h end) /- Connection between `_ β‡’* _` and `⟹` -/ lemma refl_trans_small_step_seq (h : (p₁, s) β‡’* (skip, u)) : (seq p₁ pβ‚‚, s) β‡’* (seq skip pβ‚‚, u) := h.lift (Ξ»p:program Οƒ Γ— Οƒ, (seq p.1 pβ‚‚, p.2)) $ assume ⟨p₁, s⟩ ⟨pβ‚‚, t⟩, small_step.seq_step _ lemma big_step_imp_refl_trans_small_step (h : (p, s) ⟹ t) : (p, s) β‡’* (skip, t) := begin induction h, case big_step.skip { refl }, case big_step.assign { exact refl_trans.single small_step.assign }, case big_step.seq : p₁ pβ‚‚ s t u h₁ hβ‚‚ ih₁ ihβ‚‚ { transitivity, exact refl_trans_small_step_seq ih₁, exact ihβ‚‚.head small_step.seq_skip }, case big_step.ite_true : c p₁ pβ‚‚ s t hs hst ih { exact ih.head (small_step.ite_true hs) }, case big_step.ite_false : c p₁ pβ‚‚ s t hs hst ih { exact ih.head (small_step.ite_false hs) }, case big_step.while_true : c p s t u hs h₁ hβ‚‚ ih₁ ihβ‚‚ { exact (refl_trans.head (small_step.while) $ refl_trans.head (small_step.ite_true hs) $ (refl_trans_small_step_seq ih₁).trans $ refl_trans.head small_step.seq_skip $ ihβ‚‚) }, case big_step.while_false : c p s hs { exact (refl_trans.single small_step.while).tail (small_step.ite_false hs) } end lemma big_step_of_small_step_of_big_step : (pβ‚€, sβ‚€) β‡’ (p₁, s₁) β†’ (p₁, s₁) ⟹ sβ‚‚ β†’ (pβ‚€, sβ‚€) ⟹ sβ‚‚ := begin generalize hvβ‚€ : (pβ‚€, sβ‚€) = vβ‚€, generalize hv₁ : (p₁, s₁) = vβ‚€, intro h, induction h generalizing pβ‚€ sβ‚€ p₁ s₁ sβ‚‚; cases hv₁; clear hv₁; cases hvβ‚€; clear hvβ‚€; simp [*, big_step_while_true_iff] {contextual := tt}, { intros u h₁ hβ‚‚, exact ⟨u, h_ih rfl rfl h₁, hβ‚‚βŸ© }, { intro h, exact ⟨_, rfl, h⟩ } end lemma refl_trans_small_step_imp_big_step : (p, s) β‡’* (skip, t) β†’ (p, s) ⟹ t := begin generalize hvβ‚€ : (p, s) = vβ‚€, intro h, induction h using refl_trans.head_induction_on with vβ‚€ v₁ h h' ih generalizing p s; cases hvβ‚€; clear hvβ‚€, { exact big_step.skip }, { cases v₁ with p' s', specialize ih rfl, exact big_step_of_small_step_of_big_step h ih } end lemma big_step_iff_refl_trans_small_step : (p, s) ⟹ t ↔ (p, s) β‡’* (skip, t) := iff.intro big_step_imp_refl_trans_small_step refl_trans_small_step_imp_big_step end semantics
0097296e4f1cca57f9481ac9dcca0234419cb931
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/algebra/ordered_ring.lean
edcd160a712d5c4ec4562e3c23775514f06a1c08
[ "Apache-2.0" ]
permissive
LibertasSpZ/mathlib
b9fcd46625eb940611adb5e719a4b554138dade6
33f7870a49d7cc06d2f3036e22543e6ec5046e68
refs/heads/master
1,672,066,539,347
1,602,429,158,000
1,602,429,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
43,042
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro -/ import algebra.ordered_group set_option old_structure_cmd true universe u variable {Ξ± : Type u} /-- An `ordered_semiring Ξ±` is a semiring `Ξ±` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_semiring (Ξ± : Type u) extends semiring Ξ±, ordered_cancel_add_comm_monoid Ξ± := (zero_lt_one : 0 < (1 : Ξ±)) (mul_lt_mul_of_pos_left : βˆ€ a b c : Ξ±, a < b β†’ 0 < c β†’ c * a < c * b) (mul_lt_mul_of_pos_right : βˆ€ a b c : Ξ±, a < b β†’ 0 < c β†’ a * c < b * c) section ordered_semiring variables [ordered_semiring Ξ±] {a b c d : Ξ±} lemma zero_lt_one : 0 < (1:Ξ±) := ordered_semiring.zero_lt_one lemma zero_le_one : 0 ≀ (1:Ξ±) := zero_lt_one.le lemma zero_lt_two : 0 < (2:Ξ±) := add_pos zero_lt_one zero_lt_one @[field_simps] lemma two_ne_zero : (2:Ξ±) β‰  0 := ne.symm (ne_of_lt zero_lt_two) lemma one_lt_two : 1 < (2:Ξ±) := calc (2:Ξ±) = 1+1 : one_add_one_eq_two ... > 1+0 : add_lt_add_left zero_lt_one _ ... = 1 : add_zero 1 lemma one_le_two : 1 ≀ (2:Ξ±) := one_lt_two.le lemma zero_lt_four : 0 < (4:Ξ±) := add_pos zero_lt_two zero_lt_two lemma mul_lt_mul_of_pos_left (h₁ : a < b) (hβ‚‚ : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left a b c h₁ hβ‚‚ lemma mul_lt_mul_of_pos_right (h₁ : a < b) (hβ‚‚ : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right a b c h₁ hβ‚‚ lemma mul_le_mul_of_nonneg_left (h₁ : a ≀ b) (hβ‚‚ : 0 ≀ c) : c * a ≀ c * b := begin cases classical.em (b ≀ a), { simp [h.antisymm h₁] }, cases classical.em (c ≀ 0), { simp [h_1.antisymm hβ‚‚] }, exact (mul_lt_mul_of_pos_left (h₁.lt_of_not_le h) (hβ‚‚.lt_of_not_le h_1)).le, end lemma mul_le_mul_of_nonneg_right (h₁ : a ≀ b) (hβ‚‚ : 0 ≀ c) : a * c ≀ b * c := begin cases classical.em (b ≀ a), { simp [h.antisymm h₁] }, cases classical.em (c ≀ 0), { simp [h_1.antisymm hβ‚‚] }, exact (mul_lt_mul_of_pos_right (h₁.lt_of_not_le h) (hβ‚‚.lt_of_not_le h_1)).le, end -- TODO: there are four variations, depending on which variables we assume to be nonneg lemma mul_le_mul (hac : a ≀ c) (hbd : b ≀ d) (nn_b : 0 ≀ b) (nn_c : 0 ≀ c) : a * b ≀ c * d := calc a * b ≀ c * b : mul_le_mul_of_nonneg_right hac nn_b ... ≀ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_nonneg (ha : 0 ≀ a) (hb : 0 ≀ b) : 0 ≀ a * b := have h : 0 * b ≀ a * b, from mul_le_mul_of_nonneg_right ha hb, by rwa [zero_mul] at h lemma mul_nonpos_of_nonneg_of_nonpos (ha : 0 ≀ a) (hb : b ≀ 0) : a * b ≀ 0 := have h : a * b ≀ a * 0, from mul_le_mul_of_nonneg_left hb ha, by rwa mul_zero at h lemma mul_nonpos_of_nonpos_of_nonneg (ha : a ≀ 0) (hb : 0 ≀ b) : a * b ≀ 0 := have h : a * b ≀ 0 * b, from mul_le_mul_of_nonneg_right ha hb, by rwa zero_mul at h lemma mul_lt_mul (hac : a < c) (hbd : b ≀ d) (pos_b : 0 < b) (nn_c : 0 ≀ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right hac pos_b ... ≀ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_lt_mul' (h1 : a ≀ c) (h2 : b < d) (h3 : 0 ≀ b) (h4 : 0 < c) : a * b < c * d := calc a * b ≀ c * b : mul_le_mul_of_nonneg_right h1 h3 ... < c * d : mul_lt_mul_of_pos_left h2 h4 lemma mul_pos (ha : 0 < a) (hb : 0 < b) : 0 < a * b := have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a * b < 0 := have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha, by rwa mul_zero at h lemma mul_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a * b < 0 := have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_self_le_mul_self (h1 : 0 ≀ a) (h2 : a ≀ b) : a * a ≀ b * b := mul_le_mul h2 h2 h1 $ h1.trans h2 lemma mul_self_lt_mul_self (h1 : 0 ≀ a) (h2 : a < b) : a * a < b * b := mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2 lemma mul_lt_mul'' (h1 : a < c) (h2 : b < d) (h3 : 0 ≀ a) (h4 : 0 ≀ b) : a * b < c * d := (lt_or_eq_of_le h4).elim (Ξ» b0, mul_lt_mul h1 h2.le b0 $ h3.trans h1.le) (Ξ» b0, by rw [← b0, mul_zero]; exact mul_pos (h3.trans_lt h1) (h4.trans_lt h2)) lemma le_mul_of_one_le_right (hb : 0 ≀ b) (h : 1 ≀ a) : b ≀ b * a := suffices b * 1 ≀ b * a, by rwa mul_one at this, mul_le_mul_of_nonneg_left h hb lemma le_mul_of_one_le_left (hb : 0 ≀ b) (h : 1 ≀ a) : b ≀ a * b := suffices 1 * b ≀ a * b, by rwa one_mul at this, mul_le_mul_of_nonneg_right h hb lemma bit1_pos (h : 0 ≀ a) : 0 < bit1 a := lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one lemma bit1_pos' (h : 0 < a) : 0 < bit1 a := bit1_pos h.le lemma lt_add_one (a : Ξ±) : a < a + 1 := lt_add_of_le_of_pos le_rfl zero_lt_one lemma lt_one_add (a : Ξ±) : a < 1 + a := by { rw [add_comm], apply lt_add_one } lemma one_lt_mul (ha : 1 ≀ a) (hb : 1 < b) : 1 < a * b := (one_mul (1 : Ξ±)) β–Έ mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) lemma mul_le_one (ha : a ≀ 1) (hb' : 0 ≀ b) (hb : b ≀ 1) : a * b ≀ 1 := begin rw ← one_mul (1 : Ξ±), apply mul_le_mul; {assumption <|> apply zero_le_one} end lemma one_lt_mul_of_le_of_lt (ha : 1 ≀ a) (hb : 1 < b) : 1 < a * b := calc 1 = 1 * 1 : by rw one_mul ... < a * b : mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha) lemma one_lt_mul_of_lt_of_le (ha : 1 < a) (hb : 1 ≀ b) : 1 < a * b := calc 1 = 1 * 1 : by rw one_mul ... < a * b : mul_lt_mul ha hb zero_lt_one $ zero_le_one.trans ha.le lemma mul_le_of_le_one_right (ha : 0 ≀ a) (hb1 : b ≀ 1) : a * b ≀ a := calc a * b ≀ a * 1 : mul_le_mul_of_nonneg_left hb1 ha ... = a : mul_one a lemma mul_le_of_le_one_left (hb : 0 ≀ b) (ha1 : a ≀ 1) : a * b ≀ b := calc a * b ≀ 1 * b : mul_le_mul ha1 le_rfl hb zero_le_one ... = b : one_mul b lemma mul_lt_one_of_nonneg_of_lt_one_left (ha0 : 0 ≀ a) (ha : a < 1) (hb : b ≀ 1) : a * b < 1 := calc a * b ≀ a : mul_le_of_le_one_right ha0 hb ... < 1 : ha lemma mul_lt_one_of_nonneg_of_lt_one_right (ha : a ≀ 1) (hb0 : 0 ≀ b) (hb : b < 1) : a * b < 1 := calc a * b ≀ b : mul_le_of_le_one_left hb0 ha ... < 1 : hb end ordered_semiring /-- A `linear_ordered_semiring Ξ±` is a semiring `Ξ±` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_semiring (Ξ± : Type u) extends ordered_semiring Ξ±, linear_order Ξ± section linear_ordered_semiring variables [linear_ordered_semiring Ξ±] {a b c d : Ξ±} lemma lt_of_mul_lt_mul_left (h : c * a < c * b) (hc : 0 ≀ c) : a < b := lt_of_not_ge (assume h1 : b ≀ a, have h2 : c * b ≀ c * a, from mul_le_mul_of_nonneg_left h1 hc, h2.not_lt h) lemma lt_of_mul_lt_mul_right (h : a * c < b * c) (hc : 0 ≀ c) : a < b := lt_of_not_ge (assume h1 : b ≀ a, have h2 : b * c ≀ a * c, from mul_le_mul_of_nonneg_right h1 hc, h2.not_lt h) lemma le_of_mul_le_mul_left (h : c * a ≀ c * b) (hc : 0 < c) : a ≀ b := le_of_not_gt (assume h1 : b < a, have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc, h2.not_le h) lemma le_of_mul_le_mul_right (h : a * c ≀ b * c) (hc : 0 < c) : a ≀ b := le_of_not_gt (assume h1 : b < a, have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc, h2.not_le h) lemma pos_and_pos_or_neg_and_neg_of_mul_pos (hab : 0 < a * b) : (0 < a ∧ 0 < b) ∨ (a < 0 ∧ b < 0) := begin rcases lt_trichotomy 0 a with (ha|rfl|ha), { refine or.inl ⟨ha, _⟩, contrapose! hab, exact mul_nonpos_of_nonneg_of_nonpos ha.le hab }, { rw [zero_mul] at hab, exact hab.false.elim }, { refine or.inr ⟨ha, _⟩, contrapose! hab, exact mul_nonpos_of_nonpos_of_nonneg ha.le hab } end lemma nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg (hab : 0 ≀ a * b) : (0 ≀ a ∧ 0 ≀ b) ∨ (a ≀ 0 ∧ b ≀ 0) := begin contrapose! hab, rcases lt_trichotomy 0 a with (ha|rfl|ha), exacts [mul_neg_of_pos_of_neg ha (hab.1 ha.le), ((hab.1 le_rfl).asymm (hab.2 le_rfl)).elim, mul_neg_of_neg_of_pos ha (hab.2 ha.le)] end lemma pos_of_mul_pos_left (h : 0 < a * b) (ha : 0 ≀ a) : 0 < b := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ Ξ» h, h.1.not_le ha).2 lemma pos_of_mul_pos_right (h : 0 < a * b) (hb : 0 ≀ b) : 0 < a := ((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ Ξ» h, h.2.not_le hb).1 lemma nonneg_of_mul_nonneg_left (h : 0 ≀ a * b) (h1 : 0 < a) : 0 ≀ b := le_of_not_gt (assume h2 : b < 0, (mul_neg_of_pos_of_neg h1 h2).not_le h) lemma nonneg_of_mul_nonneg_right (h : 0 ≀ a * b) (h1 : 0 < b) : 0 ≀ a := le_of_not_gt (assume h2 : a < 0, (mul_neg_of_neg_of_pos h2 h1).not_le h) lemma neg_of_mul_neg_left (h : a * b < 0) (h1 : 0 ≀ a) : b < 0 := lt_of_not_ge (assume h2 : b β‰₯ 0, (mul_nonneg h1 h2).not_lt h) lemma neg_of_mul_neg_right (h : a * b < 0) (h1 : 0 ≀ b) : a < 0 := lt_of_not_ge (assume h2 : a β‰₯ 0, (mul_nonneg h2 h1).not_lt h) lemma nonpos_of_mul_nonpos_left (h : a * b ≀ 0) (h1 : 0 < a) : b ≀ 0 := le_of_not_gt (assume h2 : b > 0, (mul_pos h1 h2).not_le h) lemma nonpos_of_mul_nonpos_right (h : a * b ≀ 0) (h1 : 0 < b) : a ≀ 0 := le_of_not_gt (assume h2 : a > 0, (mul_pos h2 h1).not_le h) @[simp] lemma mul_le_mul_left (h : 0 < c) : c * a ≀ c * b ↔ a ≀ b := ⟨λ h', le_of_mul_le_mul_left h' h, Ξ» h', mul_le_mul_of_nonneg_left h' h.le⟩ @[simp] lemma mul_le_mul_right (h : 0 < c) : a * c ≀ b * c ↔ a ≀ b := ⟨λ h', le_of_mul_le_mul_right h' h, Ξ» h', mul_le_mul_of_nonneg_right h' h.le⟩ @[simp] lemma mul_lt_mul_left (h : 0 < c) : c * a < c * b ↔ a < b := ⟨lt_imp_lt_of_le_imp_le $ Ξ» h', mul_le_mul_of_nonneg_left h' h.le, Ξ» h', mul_lt_mul_of_pos_left h' h⟩ @[simp] lemma mul_lt_mul_right (h : 0 < c) : a * c < b * c ↔ a < b := ⟨lt_imp_lt_of_le_imp_le $ Ξ» h', mul_le_mul_of_nonneg_right h' h.le, Ξ» h', mul_lt_mul_of_pos_right h' h⟩ @[simp] lemma zero_le_mul_left (h : 0 < c) : 0 ≀ c * b ↔ 0 ≀ b := by { convert mul_le_mul_left h, simp } @[simp] lemma zero_le_mul_right (h : 0 < c) : 0 ≀ b * c ↔ 0 ≀ b := by { convert mul_le_mul_right h, simp } @[simp] lemma zero_lt_mul_left (h : 0 < c) : 0 < c * b ↔ 0 < b := by { convert mul_lt_mul_left h, simp } @[simp] lemma zero_lt_mul_right (h : 0 < c) : 0 < b * c ↔ 0 < b := by { convert mul_lt_mul_right h, simp } @[simp] lemma bit0_le_bit0 : bit0 a ≀ bit0 b ↔ a ≀ b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_le_mul_left zero_lt_two] @[simp] lemma bit0_lt_bit0 : bit0 a < bit0 b ↔ a < b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_lt_mul_left zero_lt_two] @[simp] lemma bit1_le_bit1 : bit1 a ≀ bit1 b ↔ a ≀ b := (add_le_add_iff_right 1).trans bit0_le_bit0 @[simp] lemma bit1_lt_bit1 : bit1 a < bit1 b ↔ a < b := (add_lt_add_iff_right 1).trans bit0_lt_bit0 @[simp] lemma one_le_bit1 : (1 : Ξ±) ≀ bit1 a ↔ 0 ≀ a := by rw [bit1, le_add_iff_nonneg_left, bit0, ← two_mul, zero_le_mul_left zero_lt_two] @[simp] lemma one_lt_bit1 : (1 : Ξ±) < bit1 a ↔ 0 < a := by rw [bit1, lt_add_iff_pos_left, bit0, ← two_mul, zero_lt_mul_left zero_lt_two] @[simp] lemma zero_le_bit0 : (0 : Ξ±) ≀ bit0 a ↔ 0 ≀ a := by rw [bit0, ← two_mul, zero_le_mul_left zero_lt_two] @[simp] lemma zero_lt_bit0 : (0 : Ξ±) < bit0 a ↔ 0 < a := by rw [bit0, ← two_mul, zero_lt_mul_left zero_lt_two] lemma le_mul_iff_one_le_left (hb : 0 < b) : b ≀ a * b ↔ 1 ≀ a := suffices 1 * b ≀ a * b ↔ 1 ≀ a, by rwa one_mul at this, mul_le_mul_right hb lemma lt_mul_iff_one_lt_left (hb : 0 < b) : b < a * b ↔ 1 < a := suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this, mul_lt_mul_right hb lemma le_mul_iff_one_le_right (hb : 0 < b) : b ≀ b * a ↔ 1 ≀ a := suffices b * 1 ≀ b * a ↔ 1 ≀ a, by rwa mul_one at this, mul_le_mul_left hb lemma lt_mul_iff_one_lt_right (hb : 0 < b) : b < b * a ↔ 1 < a := suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this, mul_lt_mul_left hb lemma lt_mul_of_one_lt_right (hb : 0 < b) : 1 < a β†’ b < b * a := (lt_mul_iff_one_lt_right hb).2 theorem mul_nonneg_iff_right_nonneg_of_pos (h : 0 < a) : 0 ≀ b * a ↔ 0 ≀ b := ⟨assume : 0 ≀ b * a, nonneg_of_mul_nonneg_right this h, assume : 0 ≀ b, mul_nonneg this h.le⟩ lemma mul_le_iff_le_one_left (hb : 0 < b) : a * b ≀ b ↔ a ≀ 1 := ⟨ Ξ» h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 h.not_lt), Ξ» h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_left (hb : 0 < b) : a * b < b ↔ a < 1 := ⟨ Ξ» h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 h.not_le), Ξ» h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 h.not_le) ⟩ lemma mul_le_iff_le_one_right (hb : 0 < b) : b * a ≀ b ↔ a ≀ 1 := ⟨ Ξ» h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 h.not_lt), Ξ» h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 h.not_lt) ⟩ lemma mul_lt_iff_lt_one_right (hb : 0 < b) : b * a < b ↔ a < 1 := ⟨ Ξ» h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 h.not_le), Ξ» h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 h.not_le) ⟩ lemma nonpos_of_mul_nonneg_left (h : 0 ≀ a * b) (hb : b < 0) : a ≀ 0 := le_of_not_gt (Ξ» ha, absurd h (mul_neg_of_pos_of_neg ha hb).not_le) lemma nonpos_of_mul_nonneg_right (h : 0 ≀ a * b) (ha : a < 0) : b ≀ 0 := le_of_not_gt (Ξ» hb, absurd h (mul_neg_of_neg_of_pos ha hb).not_le) lemma neg_of_mul_pos_left (h : 0 < a * b) (hb : b ≀ 0) : a < 0 := lt_of_not_ge (Ξ» ha, absurd h (mul_nonpos_of_nonneg_of_nonpos ha hb).not_lt) lemma neg_of_mul_pos_right (h : 0 < a * b) (ha : a ≀ 0) : b < 0 := lt_of_not_ge (Ξ» hb, absurd h (mul_nonpos_of_nonpos_of_nonneg ha hb).not_lt) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_nontrivial {Ξ± : Type*} [linear_ordered_semiring Ξ±] : nontrivial Ξ± := { exists_pair_ne := ⟨0, 1, ne_of_lt zero_lt_one⟩ } /- TODO This theorem ought to be written in the context of `nontrivial` linearly ordered (additive) commutative monoids rather than linearly ordered rings; however, the former concept does not currently exist in mathlib. -/ @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_no_top_order {Ξ± : Type*} [linear_ordered_semiring Ξ±] : no_top_order Ξ± := ⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩ end linear_ordered_semiring section mono variables {Ξ² : Type*} [linear_ordered_semiring Ξ±] [preorder Ξ²] {f g : Ξ² β†’ Ξ±} {a : Ξ±} lemma monotone_mul_left_of_nonneg (ha : 0 ≀ a) : monotone (Ξ» x, a*x) := assume b c b_le_c, mul_le_mul_of_nonneg_left b_le_c ha lemma monotone_mul_right_of_nonneg (ha : 0 ≀ a) : monotone (Ξ» x, x*a) := assume b c b_le_c, mul_le_mul_of_nonneg_right b_le_c ha lemma monotone.mul_const (hf : monotone f) (ha : 0 ≀ a) : monotone (Ξ» x, (f x) * a) := (monotone_mul_right_of_nonneg ha).comp hf lemma monotone.const_mul (hf : monotone f) (ha : 0 ≀ a) : monotone (Ξ» x, a * (f x)) := (monotone_mul_left_of_nonneg ha).comp hf lemma monotone.mul (hf : monotone f) (hg : monotone g) (hf0 : βˆ€ x, 0 ≀ f x) (hg0 : βˆ€ x, 0 ≀ g x) : monotone (Ξ» x, f x * g x) := Ξ» x y h, mul_le_mul (hf h) (hg h) (hg0 x) (hf0 y) lemma strict_mono_mul_left_of_pos (ha : 0 < a) : strict_mono (Ξ» x, a * x) := assume b c b_lt_c, (mul_lt_mul_left ha).2 b_lt_c lemma strict_mono_mul_right_of_pos (ha : 0 < a) : strict_mono (Ξ» x, x * a) := assume b c b_lt_c, (mul_lt_mul_right ha).2 b_lt_c lemma strict_mono.mul_const (hf : strict_mono f) (ha : 0 < a) : strict_mono (Ξ» x, (f x) * a) := (strict_mono_mul_right_of_pos ha).comp hf lemma strict_mono.const_mul (hf : strict_mono f) (ha : 0 < a) : strict_mono (Ξ» x, a * (f x)) := (strict_mono_mul_left_of_pos ha).comp hf lemma strict_mono.mul_monotone (hf : strict_mono f) (hg : monotone g) (hf0 : βˆ€ x, 0 ≀ f x) (hg0 : βˆ€ x, 0 < g x) : strict_mono (Ξ» x, f x * g x) := Ξ» x y h, mul_lt_mul (hf h) (hg h.le) (hg0 x) (hf0 y) lemma monotone.mul_strict_mono (hf : monotone f) (hg : strict_mono g) (hf0 : βˆ€ x, 0 < f x) (hg0 : βˆ€ x, 0 ≀ g x) : strict_mono (Ξ» x, f x * g x) := Ξ» x y h, mul_lt_mul' (hf h.le) (hg h) (hg0 x) (hf0 y) lemma strict_mono.mul (hf : strict_mono f) (hg : strict_mono g) (hf0 : βˆ€ x, 0 ≀ f x) (hg0 : βˆ€ x, 0 ≀ g x) : strict_mono (Ξ» x, f x * g x) := Ξ» x y h, mul_lt_mul'' (hf h) (hg h) (hf0 x) (hg0 x) end mono /-- A `decidable_linear_ordered_semiring Ξ±` is a semiring `Ξ±` with a decidable linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class decidable_linear_ordered_semiring (Ξ± : Type u) extends linear_ordered_semiring Ξ±, decidable_linear_order Ξ± section decidable_linear_ordered_semiring variables [decidable_linear_ordered_semiring Ξ±] {a b c : Ξ±} @[simp] lemma decidable.mul_le_mul_left (h : 0 < c) : c * a ≀ c * b ↔ a ≀ b := decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_left h @[simp] lemma decidable.mul_le_mul_right (h : 0 < c) : a * c ≀ b * c ↔ a ≀ b := decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_right h end decidable_linear_ordered_semiring /-- An `ordered_ring Ξ±` is a ring `Ξ±` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_ring (Ξ± : Type u) extends ring Ξ±, ordered_add_comm_group Ξ±, nontrivial Ξ± := (zero_lt_one : zero < one) (mul_pos : βˆ€ a b : Ξ±, 0 < a β†’ 0 < b β†’ 0 < a * b) section ordered_ring variables [ordered_ring Ξ±] {a b c : Ξ±} lemma ordered_ring.mul_nonneg (a b : Ξ±) (h₁ : 0 ≀ a) (hβ‚‚ : 0 ≀ b) : 0 ≀ a * b := begin cases classical.em (a ≀ 0), { simp [le_antisymm h h₁] }, cases classical.em (b ≀ 0), { simp [le_antisymm h_1 hβ‚‚] }, exact (le_not_le_of_lt (ordered_ring.mul_pos a b (h₁.lt_of_not_le h) (hβ‚‚.lt_of_not_le h_1))).left, end lemma ordered_ring.mul_le_mul_of_nonneg_left (h₁ : a ≀ b) (hβ‚‚ : 0 ≀ c) : c * a ≀ c * b := have 0 ≀ b - a, from sub_nonneg_of_le h₁, have 0 ≀ c * (b - a), from ordered_ring.mul_nonneg c (b - a) hβ‚‚ this, begin rw mul_sub_left_distrib at this, apply le_of_sub_nonneg this end lemma ordered_ring.mul_le_mul_of_nonneg_right (h₁ : a ≀ b) (hβ‚‚ : 0 ≀ c) : a * c ≀ b * c := have 0 ≀ b - a, from sub_nonneg_of_le h₁, have 0 ≀ (b - a) * c, from ordered_ring.mul_nonneg (b - a) c this hβ‚‚, begin rw mul_sub_right_distrib at this, apply le_of_sub_nonneg this end lemma ordered_ring.mul_lt_mul_of_pos_left (h₁ : a < b) (hβ‚‚ : 0 < c) : c * a < c * b := have 0 < b - a, from sub_pos_of_lt h₁, have 0 < c * (b - a), from ordered_ring.mul_pos c (b - a) hβ‚‚ this, begin rw mul_sub_left_distrib at this, apply lt_of_sub_pos this end lemma ordered_ring.mul_lt_mul_of_pos_right (h₁ : a < b) (hβ‚‚ : 0 < c) : a * c < b * c := have 0 < b - a, from sub_pos_of_lt h₁, have 0 < (b - a) * c, from ordered_ring.mul_pos (b - a) c this hβ‚‚, begin rw mul_sub_right_distrib at this, apply lt_of_sub_pos this end @[priority 100] -- see Note [lower instance priority] instance ordered_ring.to_ordered_semiring : ordered_semiring Ξ± := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel Ξ± _, add_right_cancel := @add_right_cancel Ξ± _, le_of_add_le_add_left := @le_of_add_le_add_left Ξ± _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left Ξ± _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right Ξ± _, ..β€Ήordered_ring Ξ±β€Ί } lemma mul_le_mul_of_nonpos_left {a b c : Ξ±} (h : b ≀ a) (hc : c ≀ 0) : c * a ≀ c * b := have -c β‰₯ 0, from neg_nonneg_of_nonpos hc, have -c * b ≀ -c * a, from mul_le_mul_of_nonneg_left h this, have -(c * b) ≀ -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_right {a b c : Ξ±} (h : b ≀ a) (hc : c ≀ 0) : a * c ≀ b * c := have -c β‰₯ 0, from neg_nonneg_of_nonpos hc, have b * -c ≀ a * -c, from mul_le_mul_of_nonneg_right h this, have -(b * c) ≀ -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, le_of_neg_le_neg this lemma mul_nonneg_of_nonpos_of_nonpos {a b : Ξ±} (ha : a ≀ 0) (hb : b ≀ 0) : 0 ≀ a * b := have 0 * b ≀ a * b, from mul_le_mul_of_nonpos_right ha hb, by rwa zero_mul at this lemma mul_lt_mul_of_neg_left {a b c : Ξ±} (h : b < a) (hc : c < 0) : c * a < c * b := have -c > 0, from neg_pos_of_neg hc, have -c * b < -c * a, from mul_lt_mul_of_pos_left h this, have -(c * b) < -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, lt_of_neg_lt_neg this lemma mul_lt_mul_of_neg_right {a b c : Ξ±} (h : b < a) (hc : c < 0) : a * c < b * c := have -c > 0, from neg_pos_of_neg hc, have b * -c < a * -c, from mul_lt_mul_of_pos_right h this, have -(b * c) < -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, lt_of_neg_lt_neg this lemma mul_pos_of_neg_of_neg {a b : Ξ±} (ha : a < 0) (hb : b < 0) : 0 < a * b := have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb, by rwa zero_mul at this end ordered_ring /-- A `linear_ordered_ring Ξ±` is a ring `Ξ±` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_ring (Ξ± : Type u) extends ordered_ring Ξ±, linear_order Ξ± section linear_ordered_ring variables [linear_ordered_ring Ξ±] {a b c : Ξ±} @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_linear_ordered_semiring : linear_ordered_semiring Ξ± := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel Ξ± _, add_right_cancel := @add_right_cancel Ξ± _, le_of_add_le_add_left := @le_of_add_le_add_left Ξ± _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left Ξ± _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right Ξ± _, le_total := linear_ordered_ring.le_total, ..β€Ήlinear_ordered_ring Ξ±β€Ί } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_domain : domain Ξ± := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros a b hab, contrapose! hab, cases (lt_or_gt_of_ne hab.1) with ha ha; cases (lt_or_gt_of_ne hab.2) with hb hb, exacts [(mul_pos_of_neg_of_neg ha hb).ne.symm, (mul_neg_of_neg_of_pos ha hb).ne, (mul_neg_of_pos_of_neg ha hb).ne, (mul_pos ha hb).ne.symm] end, .. β€Ήlinear_ordered_ring Ξ±β€Ί } lemma mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := ⟨pos_and_pos_or_neg_and_neg_of_mul_pos, Ξ» h, h.elim (and_imp.2 mul_pos) (and_imp.2 mul_pos_of_neg_of_neg)⟩ lemma mul_neg_iff : a * b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by rw [← neg_pos, neg_mul_eq_mul_neg, mul_pos_iff, neg_pos, neg_lt_zero] lemma mul_nonneg_iff : 0 ≀ a * b ↔ 0 ≀ a ∧ 0 ≀ b ∨ a ≀ 0 ∧ b ≀ 0 := ⟨nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg, Ξ» h, h.elim (and_imp.2 mul_nonneg) (and_imp.2 mul_nonneg_of_nonpos_of_nonpos)⟩ lemma mul_nonpos_iff : a * b ≀ 0 ↔ 0 ≀ a ∧ b ≀ 0 ∨ a ≀ 0 ∧ 0 ≀ b := by rw [← neg_nonneg, neg_mul_eq_mul_neg, mul_nonneg_iff, neg_nonneg, neg_nonpos] lemma mul_self_nonneg (a : Ξ±) : 0 ≀ a * a := or.elim (le_total 0 a) (assume h : a β‰₯ 0, mul_nonneg h h) (assume h : a ≀ 0, mul_nonneg_of_nonpos_of_nonpos h h) lemma gt_of_mul_lt_mul_neg_left (h : c * a < c * b) (hc : c ≀ 0) : b < a := have nhc : 0 ≀ -c, from neg_nonneg_of_nonpos hc, have h2 : -(c * b) < -(c * a), from neg_lt_neg h, have h3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul ... < -(c * a) : h2 ... = (-c) * a : by rewrite neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left h3 nhc lemma neg_one_lt_zero : -1 < (0:Ξ±) := begin have this := neg_lt_neg (@zero_lt_one Ξ± _), rwa neg_zero at this end lemma le_of_mul_le_of_one_le {a b c : Ξ±} (h : a * c ≀ b) (hb : 0 ≀ b) (hc : 1 ≀ c) : a ≀ b := have h' : a * c ≀ b * c, from calc a * c ≀ b : h ... = b * 1 : by rewrite mul_one ... ≀ b * c : mul_le_mul_of_nonneg_left hc hb, le_of_mul_le_mul_right h' (zero_lt_one.trans_le hc) lemma nonneg_le_nonneg_of_squares_le {a b : Ξ±} (hb : 0 ≀ b) (h : a * a ≀ b * b) : a ≀ b := le_of_not_gt (Ξ»hab, (mul_self_lt_mul_self hb hab).not_le h) lemma mul_self_le_mul_self_iff {a b : Ξ±} (h1 : 0 ≀ a) (h2 : 0 ≀ b) : a ≀ b ↔ a * a ≀ b * b := ⟨mul_self_le_mul_self h1, nonneg_le_nonneg_of_squares_le h2⟩ lemma mul_self_lt_mul_self_iff {a b : Ξ±} (h1 : 0 ≀ a) (h2 : 0 ≀ b) : a < b ↔ a * a < b * b := iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff $ mul_self_le_mul_self_iff h2 h1) $ iff.symm (lt_iff_not_ge _ _) /- TODO This theorem ought to be written in the context of `nontrivial` linearly ordered (additive) commutative groups rather than linearly ordered rings; however, the former concept does not currently exist in mathlib. -/ @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_no_bot_order : no_bot_order Ξ± := ⟨assume a, ⟨a - 1, sub_lt_iff_lt_add.mpr $ lt_add_of_pos_right _ zero_lt_one⟩⟩ @[simp] lemma mul_le_mul_left_of_neg {a b c : Ξ±} (h : c < 0) : c * a ≀ c * b ↔ b ≀ a := ⟨le_imp_le_of_lt_imp_lt $ Ξ» h', mul_lt_mul_of_neg_left h' h, Ξ» h', mul_le_mul_of_nonpos_left h' h.le⟩ @[simp] lemma mul_le_mul_right_of_neg {a b c : Ξ±} (h : c < 0) : a * c ≀ b * c ↔ b ≀ a := ⟨le_imp_le_of_lt_imp_lt $ Ξ» h', mul_lt_mul_of_neg_right h' h, Ξ» h', mul_le_mul_of_nonpos_right h' h.le⟩ @[simp] lemma mul_lt_mul_left_of_neg {a b c : Ξ±} (h : c < 0) : c * a < c * b ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h) @[simp] lemma mul_lt_mul_right_of_neg {a b c : Ξ±} (h : c < 0) : a * c < b * c ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h) lemma sub_one_lt (a : Ξ±) : a - 1 < a := sub_lt_iff_lt_add.2 (lt_add_one a) lemma mul_self_pos {a : Ξ±} (ha : a β‰  0) : 0 < a * a := by rcases lt_trichotomy a 0 with h|h|h; [exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h] lemma mul_self_le_mul_self_of_le_of_neg_le {x y : Ξ±} (h₁ : x ≀ y) (hβ‚‚ : -x ≀ y) : x * x ≀ y * y := begin cases le_total 0 x, { exact mul_self_le_mul_self h h₁ }, { rw ← neg_mul_neg, exact mul_self_le_mul_self (neg_nonneg_of_nonpos h) hβ‚‚ } end lemma nonneg_of_mul_nonpos_left {a b : Ξ±} (h : a * b ≀ 0) (hb : b < 0) : 0 ≀ a := le_of_not_gt (Ξ» ha, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma nonneg_of_mul_nonpos_right {a b : Ξ±} (h : a * b ≀ 0) (ha : a < 0) : 0 ≀ b := le_of_not_gt (Ξ» hb, absurd h (mul_pos_of_neg_of_neg ha hb).not_le) lemma pos_of_mul_neg_left {a b : Ξ±} (h : a * b < 0) (hb : b ≀ 0) : 0 < a := lt_of_not_ge (Ξ» ha, absurd h (mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) lemma pos_of_mul_neg_right {a b : Ξ±} (h : a * b < 0) (ha : a ≀ 0) : 0 < b := lt_of_not_ge (Ξ» hb, absurd h (mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt) /- The sum of two squares is zero iff both elements are zero. -/ lemma mul_self_add_mul_self_eq_zero {x y : Ξ±} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := begin split; intro h, swap, { rcases h with ⟨rfl, rfl⟩, simp }, have : y * y ≀ 0, { rw [← h], apply le_add_of_nonneg_left (mul_self_nonneg x) }, have : y * y = 0 := le_antisymm this (mul_self_nonneg y), have hx : x = 0, { rwa [this, add_zero, mul_self_eq_zero] at h }, rw mul_self_eq_zero at this, split; assumption end end linear_ordered_ring /-- A `linear_ordered_comm_ring Ξ±` is a commutative ring `Ξ±` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_comm_ring (Ξ± : Type u) extends linear_ordered_ring Ξ±, comm_monoid Ξ± @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_ring.to_integral_domain [s: linear_ordered_comm_ring Ξ±] : integral_domain Ξ± := { ..s, .. linear_ordered_ring.to_domain } /-- A `decidable_linear_ordered_comm_ring Ξ±` is a commutative ring `Ξ±` with a decidable linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class decidable_linear_ordered_comm_ring (Ξ± : Type u) extends linear_ordered_comm_ring Ξ±, decidable_linear_ordered_add_comm_group Ξ± @[priority 100] -- see Note [lower instance priority] instance decidable_linear_ordered_comm_ring.to_decidable_linear_ordered_semiring [d : decidable_linear_ordered_comm_ring Ξ±] : decidable_linear_ordered_semiring Ξ± := let s : linear_ordered_semiring Ξ± := @linear_ordered_ring.to_linear_ordered_semiring Ξ± _ in { zero_mul := @linear_ordered_semiring.zero_mul Ξ± s, mul_zero := @linear_ordered_semiring.mul_zero Ξ± s, add_left_cancel := @linear_ordered_semiring.add_left_cancel Ξ± s, add_right_cancel := @linear_ordered_semiring.add_right_cancel Ξ± s, le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left Ξ± s, mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left Ξ± s, mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right Ξ± s, ..d } section decidable_linear_ordered_comm_ring variables [decidable_linear_ordered_comm_ring Ξ±] {a b c : Ξ±} lemma abs_mul (a b : Ξ±) : abs (a * b) = abs a * abs b := or.elim (le_total 0 a) (assume h1 : 0 ≀ a, or.elim (le_total 0 b) (assume h2 : 0 ≀ b, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg h1 h2) ... = abs a * b : by rw (abs_of_nonneg h1) ... = abs a * abs b : by rw (abs_of_nonneg h2)) (assume h2 : b ≀ 0, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos h1 h2) ... = a * -b : by rw neg_mul_eq_mul_neg ... = abs a * -b : by rw (abs_of_nonneg h1) ... = abs a * abs b : by rw (abs_of_nonpos h2))) (assume h1 : a ≀ 0, or.elim (le_total 0 b) (assume h2 : 0 ≀ b, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg h1 h2) ... = -a * b : by rw neg_mul_eq_neg_mul ... = abs a * b : by rw (abs_of_nonpos h1) ... = abs a * abs b : by rw (abs_of_nonneg h2)) (assume h2 : b ≀ 0, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos h1 h2) ... = -a * -b : by rw neg_mul_neg ... = abs a * -b : by rw (abs_of_nonpos h1) ... = abs a * abs b : by rw (abs_of_nonpos h2))) lemma abs_mul_abs_self (a : Ξ±) : abs a * abs a = a * a := abs_by_cases (Ξ» x, x * x = a * a) rfl (neg_mul_neg a a) lemma abs_mul_self (a : Ξ±) : abs (a * a) = a * a := by rw [abs_mul, abs_mul_abs_self] lemma sub_le_of_abs_sub_le_left (h : abs (a - b) ≀ c) : b - c ≀ a := if hz : 0 ≀ a - b then (calc a β‰₯ b : le_of_sub_nonneg hz ... β‰₯ b - c : sub_le_self _ $ (abs_nonneg _).trans h) else have habs : b - a ≀ c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h, have habs' : b ≀ c + a, from le_add_of_sub_right_le habs, sub_left_le_of_le_add habs' lemma sub_le_of_abs_sub_le_right (h : abs (a - b) ≀ c) : a - c ≀ b := sub_le_of_abs_sub_le_left (abs_sub a b β–Έ h) lemma sub_lt_of_abs_sub_lt_left (h : abs (a - b) < c) : b - c < a := if hz : 0 ≀ a - b then (calc a β‰₯ b : le_of_sub_nonneg hz ... > b - c : sub_lt_self _ ((abs_nonneg _).trans_lt h)) else have habs : b - a < c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h, have habs' : b < c + a, from lt_add_of_sub_right_lt habs, sub_left_lt_of_lt_add habs' lemma sub_lt_of_abs_sub_lt_right (h : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub a b β–Έ h) lemma abs_sub_square (a b : Ξ±) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := begin rw abs_mul_abs_self, simp [left_distrib, right_distrib, add_assoc, add_comm, add_left_comm, mul_comm, sub_eq_add_neg] end lemma eq_zero_of_mul_self_add_mul_self_eq_zero (h : a * a + b * b = 0) : a = 0 := have a * a ≀ (0 : Ξ±), from calc a * a ≀ a * a + b * b : le_add_of_nonneg_right (mul_self_nonneg b) ... = 0 : h, eq_zero_of_mul_self_eq_zero (le_antisymm this (mul_self_nonneg a)) lemma abs_abs_sub_abs_le_abs_sub (a b : Ξ±) : abs (abs a - abs b) ≀ abs (a - b) := begin apply nonneg_le_nonneg_of_squares_le, apply abs_nonneg, iterate {rw abs_sub_square}, iterate {rw abs_mul_abs_self}, apply sub_le_sub_left, iterate {rw mul_assoc}, apply mul_le_mul_of_nonneg_left, { rw [← abs_mul], apply le_abs_self }, { exact (add_pos (@zero_lt_one Ξ± _) zero_lt_one).le } end -- The proof doesn't need commutativity but we have no `decidable_linear_ordered_ring` @[simp] lemma abs_two : abs (2:Ξ±) = 2 := abs_of_pos zero_lt_two end decidable_linear_ordered_comm_ring /-- Extend `nonneg_add_comm_group` to support ordered rings specified by their nonnegative elements -/ class nonneg_ring (Ξ± : Type*) extends ring Ξ±, nonneg_add_comm_group Ξ±, nontrivial Ξ± := (one_pos : pos 1) (mul_nonneg : βˆ€ {a b}, nonneg a β†’ nonneg b β†’ nonneg (a * b)) (mul_pos : βˆ€ {a b}, pos a β†’ pos b β†’ pos (a * b)) /-- Extend `nonneg_add_comm_group` to support linearly ordered rings specified by their nonnegative elements -/ class linear_nonneg_ring (Ξ± : Type*) extends domain Ξ±, nonneg_add_comm_group Ξ± := (one_pos : pos 1) (mul_nonneg : βˆ€ {a b}, nonneg a β†’ nonneg b β†’ nonneg (a * b)) (nonneg_total : βˆ€ a, nonneg a ∨ nonneg (-a)) namespace nonneg_ring open nonneg_add_comm_group variable [nonneg_ring Ξ±] @[priority 100] -- see Note [lower instance priority] instance to_ordered_ring : ordered_ring Ξ± := { zero_lt_one := begin dsimp [(<), preorder.lt, partial_order.lt], convert one_pos, exact sub_zero _, end, mul_pos := Ξ» a b, by simp [pos_def.symm]; exact mul_pos, ..β€Ήnonneg_ring Ξ±β€Ί, ..(infer_instance : ordered_add_comm_group Ξ±) } /-- `to_linear_nonneg_ring` shows that a `nonneg_ring` with a total order is a `domain`, hence a `linear_nonneg_ring`. -/ def to_linear_nonneg_ring (nonneg_total : βˆ€ a : Ξ±, nonneg a ∨ nonneg (-a)) : linear_nonneg_ring Ξ± := { nonneg_total := nonneg_total, eq_zero_or_eq_zero_of_mul_eq_zero := suffices βˆ€ {a} b : Ξ±, nonneg a β†’ a * b = 0 β†’ a = 0 ∨ b = 0, from Ξ» a b, (nonneg_total a).elim (this b) (Ξ» na, by simpa using this b na), suffices βˆ€ {a b : Ξ±}, nonneg a β†’ nonneg b β†’ a * b = 0 β†’ a = 0 ∨ b = 0, from Ξ» a b na, (nonneg_total b).elim (this na) (Ξ» nb, by simpa using this na nb), Ξ» a b na nb z, classical.by_cases (Ξ» nna : nonneg (-a), or.inl (nonneg_antisymm na nna)) (Ξ» pa, classical.by_cases (Ξ» nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb)) (Ξ» pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos ((pos_iff _).2 ⟨na, pa⟩) ((pos_iff _).2 ⟨nb, pb⟩))), ..β€Ήnonneg_ring Ξ±β€Ί } end nonneg_ring namespace linear_nonneg_ring open nonneg_add_comm_group variable [linear_nonneg_ring Ξ±] @[priority 100] -- see Note [lower instance priority] instance to_nonneg_ring : nonneg_ring Ξ± := { mul_pos := Ξ» a b pa pb, let ⟨a1, a2⟩ := (pos_iff a).1 pa, ⟨b1, b2⟩ := (pos_iff b).1 pb in have ab : nonneg (a * b), from mul_nonneg a1 b1, (pos_iff _).2 ⟨ab, Ξ» hn, have a * b = 0, from nonneg_antisymm ab hn, (eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim (ne_of_gt (pos_def.1 pa)) (ne_of_gt (pos_def.1 pb))⟩, ..β€Ήlinear_nonneg_ring Ξ±β€Ί } @[priority 100] -- see Note [lower instance priority] instance to_linear_order : linear_order Ξ± := { le_total := nonneg_total_iff.1 nonneg_total, ..β€Ήlinear_nonneg_ring Ξ±β€Ί, ..(infer_instance : ordered_add_comm_group Ξ±) } @[priority 100] -- see Note [lower instance priority] instance to_linear_ordered_ring : linear_ordered_ring Ξ± := { mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _, zero_lt_one := lt_of_not_ge $ Ξ» (h : nonneg (0 - 1)), begin rw [zero_sub] at h, have := mul_nonneg h h, simp at this, exact zero_ne_one (nonneg_antisymm this h).symm end, ..β€Ήlinear_nonneg_ring Ξ±β€Ί, ..(infer_instance : ordered_add_comm_group Ξ±), ..(infer_instance : linear_order Ξ±) } /-- Convert a `linear_nonneg_ring` with a commutative multiplication and decidable non-negativity into a `decidable_linear_ordered_comm_ring` -/ def to_decidable_linear_ordered_comm_ring [decidable_pred (@nonneg Ξ± _)] [comm : @is_commutative Ξ± (*)] : decidable_linear_ordered_comm_ring Ξ± := { decidable_le := by apply_instance, decidable_lt := by apply_instance, mul_comm := is_commutative.comm, ..@linear_nonneg_ring.to_linear_ordered_ring _ _ } end linear_nonneg_ring /-- A canonically ordered commutative semiring is an ordered, commutative semiring in which `a ≀ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ class canonically_ordered_comm_semiring (Ξ± : Type*) extends canonically_ordered_add_monoid Ξ±, comm_semiring Ξ±, nontrivial Ξ± := (eq_zero_or_eq_zero_of_mul_eq_zero : βˆ€ a b : Ξ±, a * b = 0 β†’ a = 0 ∨ b = 0) namespace canonically_ordered_semiring variables [canonically_ordered_comm_semiring Ξ±] {a b : Ξ±} open canonically_ordered_add_monoid (le_iff_exists_add) @[priority 100] -- see Note [lower instance priority] instance canonically_ordered_comm_semiring.to_no_zero_divisors : no_zero_divisors Ξ± := ⟨canonically_ordered_comm_semiring.eq_zero_or_eq_zero_of_mul_eq_zero⟩ lemma mul_le_mul {a b c d : Ξ±} (hab : a ≀ b) (hcd : c ≀ d) : a * c ≀ b * d := begin rcases (le_iff_exists_add _ _).1 hab with ⟨b, rfl⟩, rcases (le_iff_exists_add _ _).1 hcd with ⟨d, rfl⟩, suffices : a * c ≀ a * c + (a * d + b * c + b * d), by simpa [mul_add, add_mul, _root_.add_assoc], exact (le_iff_exists_add _ _).2 ⟨_, rfl⟩ end lemma mul_le_mul_left' {b c : Ξ±} (h : b ≀ c) (a : Ξ±) : a * b ≀ a * c := mul_le_mul (le_refl a) h lemma mul_le_mul_right' {b c : Ξ±} (h : b ≀ c) (a : Ξ±) : b * a ≀ c * a := mul_le_mul h (le_refl a) /-- A version of `zero_lt_one : 0 < 1` for a `canonically_ordered_comm_semiring`. -/ lemma zero_lt_one : (0:Ξ±) < 1 := (zero_le 1).lt_of_ne zero_ne_one lemma mul_pos : 0 < a * b ↔ (0 < a) ∧ (0 < b) := by simp only [zero_lt_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] end canonically_ordered_semiring namespace with_top instance [nonempty Ξ±] : nontrivial (with_top Ξ±) := option.nontrivial variable [decidable_eq Ξ±] section has_mul variables [has_zero Ξ±] [has_mul Ξ±] instance : mul_zero_class (with_top Ξ±) := { zero := 0, mul := Ξ»m n, if m = 0 ∨ n = 0 then 0 else m.bind (Ξ»a, n.bind $ Ξ»b, ↑(a * b)), zero_mul := assume a, if_pos $ or.inl rfl, mul_zero := assume a, if_pos $ or.inr rfl } lemma mul_def {a b : with_top Ξ±} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (Ξ»a, b.bind $ Ξ»b, ↑(a * b)) := rfl @[simp] lemma mul_top {a : with_top Ξ±} (h : a β‰  0) : a * ⊀ = ⊀ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul {a : with_top Ξ±} (h : a β‰  0) : ⊀ * a = ⊀ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul_top : (⊀ * ⊀ : with_top Ξ±) = ⊀ := top_mul top_ne_zero end has_mul section mul_zero_class variables [mul_zero_class Ξ±] @[norm_cast] lemma coe_mul {a b : Ξ±} : (↑(a * b) : with_top Ξ±) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by { simp [*, mul_def], refl } lemma mul_coe {b : Ξ±} (hb : b β‰  0) : βˆ€{a : with_top Ξ±}, a * b = a.bind (Ξ»a:Ξ±, ↑(a * b)) | none := show (if (⊀:with_top Ξ±) = 0 ∨ (b:with_top Ξ±) = 0 then 0 else ⊀ : with_top Ξ±) = ⊀, by simp [hb] | (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm @[simp] lemma mul_eq_top_iff {a b : with_top Ξ±} : a * b = ⊀ ↔ (a β‰  0 ∧ b = ⊀) ∨ (a = ⊀ ∧ b β‰  0) := begin cases a; cases b; simp only [none_eq_top, some_eq_coe], { simp [← coe_mul] }, { suffices : ⊀ * (b : with_top Ξ±) = ⊀ ↔ b β‰  0, by simpa, by_cases hb : b = 0; simp [hb] }, { suffices : (a : with_top Ξ±) * ⊀ = ⊀ ↔ a β‰  0, by simpa, by_cases ha : a = 0; simp [ha] }, { simp [← coe_mul] } end end mul_zero_class section no_zero_divisors variables [mul_zero_class Ξ±] [no_zero_divisors Ξ±] instance : no_zero_divisors (with_top Ξ±) := ⟨λ a b, by cases a; cases b; dsimp [mul_def]; split_ifs; simp [*, none_eq_top, some_eq_coe, mul_eq_zero] at *⟩ end no_zero_divisors variables [canonically_ordered_comm_semiring Ξ±] private lemma comm (a b : with_top Ξ±) : a * b = b * a := begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, simp [ha, hb, mul_def, option.bind_comm a b, mul_comm] end private lemma distrib' (a b c : with_top Ξ±) : (a + b) * c = a * c + b * c := begin cases c, { show (a + b) * ⊀ = a * ⊀ + b * ⊀, by_cases ha : a = 0; simp [ha] }, { show (a + b) * c = a * c + b * c, by_cases hc : c = 0, { simp [hc] }, simp [mul_coe hc], cases a; cases b, repeat { refl <|> exact congr_arg some (add_mul _ _ _) } } end private lemma assoc (a b c : with_top Ξ±) : (a * b) * c = a * (b * c) := begin cases a, { by_cases hb : b = 0; by_cases hc : c = 0; simp [*, none_eq_top] }, cases b, { by_cases ha : a = 0; by_cases hc : c = 0; simp [*, none_eq_top, some_eq_coe] }, cases c, { by_cases ha : a = 0; by_cases hb : b = 0; simp [*, none_eq_top, some_eq_coe] }, simp [some_eq_coe, coe_mul.symm, mul_assoc] end private lemma one_mul' : βˆ€a : with_top Ξ±, 1 * a = a | none := show ((1:Ξ±) : with_top Ξ±) * ⊀ = ⊀, by simp [-with_top.coe_one] | (some a) := show ((1:Ξ±) : with_top Ξ±) * a = a, by simp [coe_mul.symm, -with_top.coe_one] instance : canonically_ordered_comm_semiring (with_top Ξ±) := { one := (1 : Ξ±), right_distrib := distrib', left_distrib := assume a b c, by rw [comm, distrib', comm b, comm c]; refl, mul_assoc := assoc, mul_comm := comm, one_mul := one_mul', mul_one := assume a, by rw [comm, one_mul'], .. with_top.add_comm_monoid, .. with_top.mul_zero_class, .. with_top.canonically_ordered_add_monoid, .. with_top.no_zero_divisors, .. with_top.nontrivial } end with_top
d089d8fc7c3cf1c498a2de7bc344560c71765445
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/calc_heq_symm.lean
00483999fd4e8051057a1a31d03e49bc4a284046
[ "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
303
lean
import logic theorem tst {A B C D : Type} {a₁ aβ‚‚ : A} {b : B} {c : C} {d : D} (Hβ‚€ : a₁ = aβ‚‚) (H₁ : aβ‚‚ == b) (Hβ‚‚ : b == c) (H₃ : c == d) : d == a₁ := calc d == c : H₃ ... == b : Hβ‚‚ ... == aβ‚‚ : H₁ ... = a₁ : Hβ‚€ reveal tst print definition tst
828b3cd9f608cc9ec2fb95aea30dda12b7926b7c
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/limits/shapes/images.lean
b295301cc6ec70780125915fc164a7767ecff732
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
19,728
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.strong_epi /-! # Categorical images We define the categorical image of `f` as a factorisation `f = e ≫ m` through a monomorphism `m`, so that `m` factors through the `m'` in any other such factorisation. ## Main definitions * A `mono_factorisation` is a factorisation `f = e ≫ m`, where `m` is a monomorphism * `is_image F` means that a given mono factorisation `F` has the universal property of the image. * `has_image f` means that we have chosen an image for the morphism `f : X ⟢ Y`. * In this case, `image f` is the image object, `image.ΞΉ f : image f ⟢ Y` is the monomorphism `m` of the factorisation and `factor_thru_image f : X ⟢ image f` is the morphism `e`. * `has_images C` means that every morphism in `C` has an image. * Let `f : X ⟢ Y` and `g : P ⟢ Q` be morphisms in `C`, which we will represent as objects of the arrow category `arrow C`. Then `sq : f ⟢ g` is a commutative square in `C`. If `f` and `g` have images, then `has_image_map sq` represents the fact that there is a morphism `i : image f ⟢ image g` making the diagram X ----β†’ image f ----β†’ Y | | | | | | ↓ ↓ ↓ P ----β†’ image g ----β†’ Q commute, where the top row is the image factorisation of `f`, the bottom row is the image factorisation of `g`, and the outer rectangle is the commutative square `sq`. * If a category `has_images`, then `has_image_maps` means that every commutative square admits an image map. * If a category `has_images`, then `has_strong_epi_images` means that the morphism to the image is always a strong epimorphism. ## Main statements * When `C` has equalizers, the morphism `e` appearing in an image factorisation is an epimorphism. * When `C` has strong epi images, then these images admit image maps. ## Future work * TODO: coimages, and abelian categories. * TODO: connect this with existing working in the group theory and ring theory libraries. -/ universes v u open category_theory open category_theory.limits.walking_parallel_pair namespace category_theory.limits variables {C : Type u} [category.{v} C] variables {X Y : C} (f : X ⟢ Y) /-- A factorisation of a morphism `f = e ≫ m`, with `m` monic. -/ structure mono_factorisation (f : X ⟢ Y) := (I : C) (m : I ⟢ Y) [m_mono : mono m] (e : X ⟢ I) (fac' : e ≫ m = f . obviously) restate_axiom mono_factorisation.fac' attribute [simp, reassoc] mono_factorisation.fac attribute [instance] mono_factorisation.m_mono attribute [instance] mono_factorisation.m_mono namespace mono_factorisation /-- The obvious factorisation of a monomorphism through itself. -/ def self [mono f] : mono_factorisation f := { I := X, m := f, e := πŸ™ X } -- I'm not sure we really need this, but the linter says that an inhabited instance ought to exist... instance [mono f] : inhabited (mono_factorisation f) := ⟨self f⟩ /-- The morphism `m` in a factorisation `f = e ≫ m` through a monomorphism is uniquely determined. -/ @[ext] lemma ext {F F' : mono_factorisation f} (hI : F.I = F'.I) (hm : F.m = (eq_to_hom hI) ≫ F'.m) : F = F' := begin cases F, cases F', cases hI, simp at hm, dsimp at F_fac' F'_fac', congr, { assumption }, { resetI, apply (cancel_mono F_m).1, rw [F_fac', hm, F'_fac'], } end end mono_factorisation variable {f} /-- Data exhibiting that a given factorisation through a mono is initial. -/ structure is_image (F : mono_factorisation f) := (lift : Ξ  (F' : mono_factorisation f), F.I ⟢ F'.I) (lift_fac' : Ξ  (F' : mono_factorisation f), lift F' ≫ F'.m = F.m . obviously) restate_axiom is_image.lift_fac' attribute [simp, reassoc] is_image.lift_fac @[simp, reassoc] lemma is_image.fac_lift {F : mono_factorisation f} (hF : is_image F) (F' : mono_factorisation f) : F.e ≫ hF.lift F' = F'.e := (cancel_mono F'.m).1 $ by simp variable (f) namespace is_image /-- The trivial factorisation of a monomorphism satisfies the universal property. -/ @[simps] def self [mono f] : is_image (mono_factorisation.self f) := { lift := Ξ» F', F'.e } instance [mono f] : inhabited (is_image (mono_factorisation.self f)) := ⟨self f⟩ variable {f} /-- Two factorisations through monomorphisms satisfying the universal property must factor through isomorphic objects. -/ -- TODO this is another good candidate for a future `unique_up_to_canonical_iso`. @[simps] def iso_ext {F F' : mono_factorisation f} (hF : is_image F) (hF' : is_image F') : F.I β‰… F'.I := { hom := hF.lift F', inv := hF'.lift F, hom_inv_id' := (cancel_mono F.m).1 (by simp), inv_hom_id' := (cancel_mono F'.m).1 (by simp) } end is_image /-- Data exhibiting that a morphism `f` has an image. -/ class has_image (f : X ⟢ Y) := (F : mono_factorisation f) (is_image : is_image F) section variable [has_image f] /-- The chosen factorisation of `f` through a monomorphism. -/ def image.mono_factorisation : mono_factorisation f := has_image.F /-- The witness of the universal property for the chosen factorisation of `f` through a monomorphism. -/ def image.is_image : is_image (image.mono_factorisation f) := has_image.is_image /-- The categorical image of a morphism. -/ def image : C := (image.mono_factorisation f).I /-- The inclusion of the image of a morphism into the target. -/ def image.ΞΉ : image f ⟢ Y := (image.mono_factorisation f).m @[simp] lemma image.as_ΞΉ : (image.mono_factorisation f).m = image.ΞΉ f := rfl instance : mono (image.ΞΉ f) := (image.mono_factorisation f).m_mono /-- The map from the source to the image of a morphism. -/ def factor_thru_image : X ⟢ image f := (image.mono_factorisation f).e /-- Rewrite in terms of the `factor_thru_image` interface. -/ @[simp] lemma as_factor_thru_image : (image.mono_factorisation f).e = factor_thru_image f := rfl @[simp, reassoc] lemma image.fac : factor_thru_image f ≫ image.ΞΉ f = f := (image.mono_factorisation f).fac' variable {f} /-- Any other factorisation of the morphism `f` through a monomorphism receives a map from the image. -/ def image.lift (F' : mono_factorisation f) : image f ⟢ F'.I := (image.is_image f).lift F' @[simp, reassoc] lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ΞΉ f := (image.is_image f).lift_fac' F' @[simp, reassoc] lemma image.fac_lift (F' : mono_factorisation f) : factor_thru_image f ≫ image.lift F' = F'.e := (image.is_image f).fac_lift F' -- TODO we could put a category structure on `mono_factorisation f`, -- with the morphisms being `g : I ⟢ I'` commuting with the `m`s -- (they then automatically commute with the `e`s) -- and show that an `image_of f` gives an initial object there -- (uniqueness of the lift comes for free). instance lift_mono (F' : mono_factorisation f) : mono (image.lift F') := begin split, intros Z a b w, have w' : a ≫ image.ΞΉ f = b ≫ image.ΞΉ f := calc a ≫ image.ΞΉ f = a ≫ (image.lift F' ≫ F'.m) : by simp ... = (a ≫ image.lift F') ≫ F'.m : by rw [category.assoc] ... = (b ≫ image.lift F') ≫ F'.m : by rw w ... = b ≫ (image.lift F' ≫ F'.m) : by rw [←category.assoc] ... = b ≫ image.ΞΉ f : by simp, exact (cancel_mono (image.ΞΉ f)).1 w', end lemma has_image.uniq (F' : mono_factorisation f) (l : image f ⟢ F'.I) (w : l ≫ F'.m = image.ΞΉ f) : l = image.lift F' := (cancel_mono F'.m).1 (by simp [w]) end section variables (C) /-- `has_images` represents a choice of image for every morphism -/ class has_images := (has_image : Ξ  {X Y : C} (f : X ⟢ Y), has_image f) attribute [instance, priority 100] has_images.has_image end section variables (f) [has_image f] /-- The image of a monomorphism is isomorphic to the source. -/ def image_mono_iso_source [mono f] : image f β‰… X := is_image.iso_ext (image.is_image f) (is_image.self f) @[simp, reassoc] lemma image_mono_iso_source_inv_ΞΉ [mono f] : (image_mono_iso_source f).inv ≫ image.ΞΉ f = f := by simp [image_mono_iso_source] @[simp, reassoc] lemma image_mono_iso_source_hom_self [mono f] : (image_mono_iso_source f).hom ≫ f = image.ΞΉ f := begin conv { to_lhs, congr, skip, rw ←image_mono_iso_source_inv_ΞΉ f, }, rw [←category.assoc, iso.hom_inv_id, category.id_comp], end -- This is the proof that `factor_thru_image f` is an epimorphism -- from https://en.wikipedia.org/wiki/Image_(category_theory), which is in turn taken from: -- Mitchell, Barry (1965), Theory of categories, MR 0202787, p.12, Proposition 10.1 @[ext] lemma image.ext {W : C} {g h : image f ⟢ W} [has_limit (parallel_pair g h)] (w : factor_thru_image f ≫ g = factor_thru_image f ≫ h) : g = h := begin let q := equalizer.ΞΉ g h, let e' := equalizer.lift _ w, let F' : mono_factorisation f := { I := equalizer g h, m := q ≫ image.ΞΉ f, m_mono := by apply mono_comp, e := e' }, let v := image.lift F', have tβ‚€ : v ≫ q ≫ image.ΞΉ f = image.ΞΉ f := image.lift_fac F', have t : v ≫ q = πŸ™ (image f) := (cancel_mono_id (image.ΞΉ f)).1 (by { convert tβ‚€ using 1, rw category.assoc }), -- The proof from wikipedia next proves `q ≫ v = πŸ™ _`, -- and concludes that `equalizer g h β‰… image f`, -- but this isn't necessary. calc g = πŸ™ (image f) ≫ g : by rw [category.id_comp] ... = v ≫ q ≫ g : by rw [←t, category.assoc] ... = v ≫ q ≫ h : by rw [equalizer.condition g h] ... = πŸ™ (image f) ≫ h : by rw [←category.assoc, t] ... = h : by rw [category.id_comp] end instance [Ξ  {Z : C} (g h : image f ⟢ Z), has_limit (parallel_pair g h)] : epi (factor_thru_image f) := ⟨λ Z g h w, image.ext f w⟩ lemma epi_image_of_epi {X Y : C} (f : X ⟢ Y) [has_image f] [E : epi f] : epi (image.ΞΉ f) := begin rw ←image.fac f at E, resetI, exact epi_of_epi (factor_thru_image f) (image.ΞΉ f), end lemma epi_of_epi_image {X Y : C} (f : X ⟢ Y) [has_image f] [epi (image.ΞΉ f)] [epi (factor_thru_image f)] : epi f := by { rw [←image.fac f], apply epi_comp, } end section variables {f} {f' : X ⟢ Y} [has_image f] [has_image f'] /-- An equation between morphisms gives a comparison map between the images (which momentarily we prove is an iso). -/ def image.eq_to_hom (h : f = f') : image f ⟢ image f' := image.lift { I := image f', m := image.ΞΉ f', e := factor_thru_image f', }. instance (h : f = f') : is_iso (image.eq_to_hom h) := { inv := image.eq_to_hom h.symm, hom_inv_id' := (cancel_mono (image.ΞΉ f)).1 (by simp [image.eq_to_hom]), inv_hom_id' := (cancel_mono (image.ΞΉ f')).1 (by simp [image.eq_to_hom]), } /-- An equation between morphisms gives an isomorphism between the images. -/ def image.eq_to_iso (h : f = f') : image f β‰… image f' := as_iso (image.eq_to_hom h) /-- As long as the category has equalizers, the image inclusion maps commute with `image.eq_to_iso`. -/ lemma image.eq_fac [has_equalizers C] (h : f = f') : image.ΞΉ f = (image.eq_to_iso h).hom ≫ image.ΞΉ f' := by { ext, simp [image.eq_to_iso, image.eq_to_hom], } end section variables {Z : C} (g : Y ⟢ Z) /-- The comparison map `image (f ≫ g) ⟢ image g`. -/ def image.pre_comp [has_image g] [has_image (f ≫ g)] : image (f ≫ g) ⟢ image g := image.lift { I := image g, m := image.ΞΉ g, e := f ≫ factor_thru_image g } /-- The two step comparison map `image (f ≫ (g ≫ h)) ⟢ image (g ≫ h) ⟢ image h` agrees with the one step comparison map `image (f ≫ (g ≫ h)) β‰… image ((f ≫ g) ≫ h) ⟢ image h`. -/ lemma image.pre_comp_comp {W : C} (h : Z ⟢ W) [has_image (g ≫ h)] [has_image (f ≫ g ≫ h)] [has_image h] [has_image ((f ≫ g) ≫ h)] : image.pre_comp f (g ≫ h) ≫ image.pre_comp g h = image.eq_to_hom (category.assoc f g h).symm ≫ (image.pre_comp (f ≫ g) h) := begin apply (cancel_mono (image.ΞΉ h)).1, simp [image.pre_comp, image.eq_to_hom], end -- Note that in general we don't have the other comparison map you might expect -- `image f ⟢ image (f ≫ g)`. end end category_theory.limits namespace category_theory.limits variables {C : Type u} [category.{v} C] section instance {X Y : C} (f : X ⟢ Y) [has_image f] : has_image (arrow.mk f).hom := show has_image f, by apply_instance end section has_image_map /-- An image map is a morphism `image f β†’ image g` fitting into a commutative square and satisfying the obvious commutativity conditions. -/ class has_image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟢ g) := (map : image f.hom ⟢ image g.hom) (map_ΞΉ' : map ≫ image.ΞΉ g.hom = image.ΞΉ f.hom ≫ sq.right . obviously) restate_axiom has_image_map.map_ΞΉ' attribute [simp, reassoc] has_image_map.map_ΞΉ @[simp, reassoc] lemma has_image_map.factor_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟢ g) [has_image_map sq] : factor_thru_image f.hom ≫ has_image_map.map sq = sq.left ≫ factor_thru_image g.hom := (cancel_mono (image.ΞΉ g.hom)).1 $ by simp [arrow.w] variables {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟢ g) section local attribute [ext] has_image_map instance : subsingleton (has_image_map sq) := subsingleton.intro $ Ξ» a b, has_image_map.ext a b $ (cancel_mono (image.ΞΉ g.hom)).1 $ by simp only [has_image_map.map_ΞΉ] end variable [has_image_map sq] /-- The map on images induced by a commutative square. -/ abbreviation image.map : image f.hom ⟢ image g.hom := has_image_map.map sq lemma image.factor_map : factor_thru_image f.hom ≫ image.map sq = sq.left ≫ factor_thru_image g.hom := by simp lemma image.map_ΞΉ : image.map sq ≫ image.ΞΉ g.hom = image.ΞΉ f.hom ≫ sq.right := by simp lemma image.map_hom_mk'_ΞΉ {X Y P Q : C} {k : X ⟢ Y} [has_image k] {l : P ⟢ Q} [has_image l] {m : X ⟢ P} {n : Y ⟢ Q} (w : m ≫ l = k ≫ n) [has_image_map (arrow.hom_mk' w)] : image.map (arrow.hom_mk' w) ≫ image.ΞΉ l = image.ΞΉ k ≫ n := image.map_ΞΉ _ section variables {h : arrow C} [has_image h.hom] (sq' : g ⟢ h) variables [has_image_map sq'] /-- Image maps for composable commutative squares induce an image map in the composite square. -/ def has_image_map_comp : has_image_map (sq ≫ sq') := { map := image.map sq ≫ image.map sq' } @[simp] lemma image.map_comp [has_image_map (sq ≫ sq')] : image.map (sq ≫ sq') = image.map sq ≫ image.map sq' := show (has_image_map.map (sq ≫ sq')) = (has_image_map_comp sq sq').map, by congr end section variables (f) /-- The identity `image f ⟢ image f` fits into the commutative square represented by the identity morphism `πŸ™ f` in the arrow category. -/ def has_image_map_id : has_image_map (πŸ™ f) := { map := πŸ™ (image f.hom) } @[simp] lemma image.map_id [has_image_map (πŸ™ f)] : image.map (πŸ™ f) = πŸ™ (image f.hom) := show (image.map (πŸ™ f)) = (has_image_map_id f).map, by congr end end has_image_map section variables (C) [has_images C] /-- If a category `has_image_maps`, then all commutative squares induce morphisms on images. -/ class has_image_maps := (has_image_map : Ξ  {f g : arrow C} (st : f ⟢ g), has_image_map st) attribute [instance, priority 100] has_image_maps.has_image_map end section has_image_maps variables [has_images C] [has_image_maps C] /-- The functor from the arrow category of `C` to `C` itself that maps a morphism to its image and a commutative square to the induced morphism on images. -/ @[simps] def im : arrow C β₯€ C := { obj := Ξ» f, image f.hom, map := Ξ» _ _ st, image.map st } end has_image_maps section strong_epi_mono_factorisation /-- A strong epi-mono factorisation is a decomposition `f = e ≫ m` with `e` a strong epimorphism and `m` a monomorphism. -/ structure strong_epi_mono_factorisation {X Y : C} (f : X ⟢ Y) extends mono_factorisation f := [e_strong_epi : strong_epi e] attribute [instance] strong_epi_mono_factorisation.e_strong_epi /-- Satisfying the inhabited linter -/ instance strong_epi_mono_factorisation_inhabited {X Y : C} (f : X ⟢ Y) [strong_epi f] : inhabited (strong_epi_mono_factorisation f) := ⟨⟨⟨Y, πŸ™ Y, f, by simp⟩⟩⟩ /-- A mono factorisation coming from a strong epi-mono factorisation always has the universal property of the image. -/ def strong_epi_mono_factorisation.to_mono_is_image {X Y : C} {f : X ⟢ Y} (F : strong_epi_mono_factorisation f) : is_image F.to_mono_factorisation := { lift := Ξ» G, arrow.lift $ arrow.hom_mk' $ show G.e ≫ G.m = F.e ≫ F.m, by rw [F.to_mono_factorisation.fac, G.fac] } variable (C) /-- A category has strong epi-mono factorisations if every morphism admits a strong epi-mono factorisation. -/ class has_strong_epi_mono_factorisations := (has_fac : Ξ  {X Y : C} (f : X ⟢ Y), strong_epi_mono_factorisation f) @[priority 100] instance has_images_of_has_strong_epi_mono_factorisations [has_strong_epi_mono_factorisations C] : has_images C := { has_image := Ξ» X Y f, let F' := has_strong_epi_mono_factorisations.has_fac f in { F := F'.to_mono_factorisation, is_image := F'.to_mono_is_image } } end strong_epi_mono_factorisation section has_strong_epi_images variables (C) [has_images C] /-- A category has strong epi images if it has all images and `factor_thru_image f` is a strong epimorphism for all `f`. -/ class has_strong_epi_images := (strong_factor_thru_image : Ξ  {X Y : C} (f : X ⟢ Y), strong_epi (factor_thru_image f)) attribute [instance] has_strong_epi_images.strong_factor_thru_image end has_strong_epi_images section has_strong_epi_images /-- If we constructed our images from strong epi-mono factorisations, then these images are strong epi images. -/ @[priority 100] instance has_strong_epi_images_of_has_strong_epi_mono_factorisations [has_strong_epi_mono_factorisations C] : has_strong_epi_images C := { strong_factor_thru_image := Ξ» X Y f, (has_strong_epi_mono_factorisations.has_fac f).e_strong_epi } end has_strong_epi_images section has_strong_epi_images variables [has_images C] /-- A category with strong epi images has image maps. The construction is taken from Borceux, Handbook of Categorical Algebra 1, Proposition 4.4.5. -/ @[priority 100] instance has_image_maps_of_has_strong_epi_images [has_strong_epi_images C] : has_image_maps C := { has_image_map := Ξ» f g st, let I := image (image.ΞΉ f.hom ≫ st.right) in let I' := image (st.left ≫ factor_thru_image g.hom) in let upper : strong_epi_mono_factorisation (f.hom ≫ st.right) := { I := I, e := factor_thru_image f.hom ≫ factor_thru_image (image.ΞΉ f.hom ≫ st.right), m := image.ΞΉ (image.ΞΉ f.hom ≫ st.right), e_strong_epi := strong_epi_comp _ _, m_mono := by apply_instance } in let lower : strong_epi_mono_factorisation (f.hom ≫ st.right) := { I := I', e := factor_thru_image (st.left ≫ factor_thru_image g.hom), m := image.ΞΉ (st.left ≫ factor_thru_image g.hom) ≫ image.ΞΉ g.hom, fac' := by simp [arrow.w], e_strong_epi := by apply_instance, m_mono := mono_comp _ _ } in let s : I ⟢ I' := is_image.lift upper.to_mono_is_image lower.to_mono_factorisation in { map := factor_thru_image (image.ΞΉ f.hom ≫ st.right) ≫ s ≫ image.ΞΉ (st.left ≫ factor_thru_image g.hom), map_ΞΉ' := by rw [category.assoc, category.assoc, is_image.lift_fac upper.to_mono_is_image lower.to_mono_factorisation, image.fac] } } end has_strong_epi_images end category_theory.limits
157f69e438f1d8c890edfcbde07e8bd125aeac3e
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/category_theory/limits/shapes/zero.lean
0cc7edcdc1c256cbad41c0a15d0e5734dc717913
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,129
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.terminal import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.products import category_theory.limits.shapes.images import category_theory.isomorphism_classes /-! # Zero morphisms and zero objects A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space, and compositions of zero morphisms with anything give the zero morphism. (Notice this is extra structure, not merely a property.) A category "has a zero object" if it has an object which is both initial and terminal. Having a zero object provides zero morphisms, as the unique morphisms factoring through the zero object. ## References * https://en.wikipedia.org/wiki/Zero_morphism * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ noncomputable theory universes v u open category_theory open category_theory.category namespace category_theory.limits variables (C : Type u) [category.{v} C] /-- A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space, and compositions of zero morphisms with anything give the zero morphism. -/ class has_zero_morphisms := [has_zero : Ξ  X Y : C, has_zero (X ⟢ Y)] (comp_zero' : βˆ€ {X Y : C} (f : X ⟢ Y) (Z : C), f ≫ (0 : Y ⟢ Z) = (0 : X ⟢ Z) . obviously) (zero_comp' : βˆ€ (X : C) {Y Z : C} (f : Y ⟢ Z), (0 : X ⟢ Y) ≫ f = (0 : X ⟢ Z) . obviously) attribute [instance] has_zero_morphisms.has_zero restate_axiom has_zero_morphisms.comp_zero' restate_axiom has_zero_morphisms.zero_comp' variables {C} @[simp] lemma comp_zero [has_zero_morphisms C] {X Y : C} {f : X ⟢ Y} {Z : C} : f ≫ (0 : Y ⟢ Z) = (0 : X ⟢ Z) := has_zero_morphisms.comp_zero f Z @[simp] lemma zero_comp [has_zero_morphisms C] {X : C} {Y Z : C} {f : Y ⟢ Z} : (0 : X ⟢ Y) ≫ f = (0 : X ⟢ Z) := has_zero_morphisms.zero_comp X f instance has_zero_morphisms_pempty : has_zero_morphisms (discrete pempty) := { has_zero := by tidy } instance has_zero_morphisms_punit : has_zero_morphisms (discrete punit) := { has_zero := by tidy } namespace has_zero_morphisms variables {C} /-- This lemma will be immediately superseded by `ext`, below. -/ private lemma ext_aux (I J : has_zero_morphisms C) (w : βˆ€ X Y : C, (@has_zero_morphisms.has_zero _ _ I X Y).zero = (@has_zero_morphisms.has_zero _ _ J X Y).zero) : I = J := begin casesI I, casesI J, congr, { ext X Y, exact w X Y }, { apply proof_irrel_heq, }, { apply proof_irrel_heq, } end /-- If you're tempted to use this lemma "in the wild", you should probably carefully consider whether you've made a mistake in allowing two instances of `has_zero_morphisms` to exist at all. See, particularly, the note on `zero_morphisms_of_zero_object` below. -/ lemma ext (I J : has_zero_morphisms C) : I = J := begin apply ext_aux, intros X Y, rw ←@has_zero_morphisms.comp_zero _ _ I X X (@has_zero_morphisms.has_zero _ _ J X X).zero, rw @has_zero_morphisms.zero_comp _ _ J, end instance : subsingleton (has_zero_morphisms C) := ⟨ext⟩ end has_zero_morphisms open has_zero_morphisms section variables {C} [has_zero_morphisms C] lemma zero_of_comp_mono {X Y Z : C} {f : X ⟢ Y} (g : Y ⟢ Z) [mono g] (h : f ≫ g = 0) : f = 0 := by { rw [←zero_comp, cancel_mono] at h, exact h } lemma zero_of_epi_comp {X Y Z : C} (f : X ⟢ Y) {g : Y ⟢ Z} [epi f] (h : f ≫ g = 0) : g = 0 := by { rw [←comp_zero, cancel_epi] at h, exact h } lemma eq_zero_of_image_eq_zero {X Y : C} {f : X ⟢ Y} [has_image f] (w : image.ΞΉ f = 0) : f = 0 := by rw [←image.fac f, w, has_zero_morphisms.comp_zero] lemma nonzero_image_of_nonzero {X Y : C} {f : X ⟢ Y} [has_image f] (w : f β‰  0) : image.ΞΉ f β‰  0 := Ξ» h, w (eq_zero_of_image_eq_zero h) end section universes v' u' variables (D : Type u') [category.{v'} D] variables [has_zero_morphisms D] instance : has_zero_morphisms (C β₯€ D) := { has_zero := Ξ» F G, ⟨{ app := Ξ» X, 0, }⟩ } @[simp] lemma zero_app (F G : C β₯€ D) (j : C) : (0 : F ⟢ G).app j = 0 := rfl variables [has_zero_morphisms C] lemma equivalence_preserves_zero_morphisms (F : C β‰Œ D) (X Y : C) : F.functor.map (0 : X ⟢ Y) = (0 : F.functor.obj X ⟢ F.functor.obj Y) := begin have t : F.functor.map (0 : X ⟢ Y) = F.functor.map (0 : X ⟢ Y) ≫ (0 : F.functor.obj Y ⟢ F.functor.obj Y), { apply faithful.map_injective (F.inverse), rw [functor.map_comp, equivalence.inv_fun_map], dsimp, rw [zero_comp, comp_zero, zero_comp], }, exact t.trans (by simp) end @[simp] lemma is_equivalence_preserves_zero_morphisms (F : C β₯€ D) [is_equivalence F] (X Y : C) : F.map (0 : X ⟢ Y) = 0 := by rw [←functor.as_equivalence_functor F, equivalence_preserves_zero_morphisms] end variables (C) /-- A category "has a zero object" if it has an object which is both initial and terminal. -/ class has_zero_object := (zero : C) (unique_to : Ξ  X : C, unique (zero ⟢ X)) (unique_from : Ξ  X : C, unique (X ⟢ zero)) instance has_zero_object_punit : has_zero_object (discrete punit) := { zero := punit.star, unique_to := by tidy, unique_from := by tidy, } variables {C} namespace has_zero_object variables [has_zero_object C] /-- Construct a `has_zero C` for a category with a zero object. This can not be a global instance as it will trigger for every `has_zero C` typeclass search. -/ protected def has_zero : has_zero C := { zero := has_zero_object.zero } local attribute [instance] has_zero_object.has_zero local attribute [instance] has_zero_object.unique_to has_zero_object.unique_from @[ext] lemma to_zero_ext {X : C} (f g : X ⟢ 0) : f = g := by rw [(has_zero_object.unique_from X).uniq f, (has_zero_object.unique_from X).uniq g] @[ext] lemma from_zero_ext {X : C} (f g : 0 ⟢ X) : f = g := by rw [(has_zero_object.unique_to X).uniq f, (has_zero_object.unique_to X).uniq g] instance (X : C) : subsingleton (X β‰… 0) := by tidy instance {X : C} (f : 0 ⟢ X) : mono f := { right_cancellation := Ξ» Z g h w, by ext, } instance {X : C} (f : X ⟢ 0) : epi f := { left_cancellation := Ξ» Z g h w, by ext, } /-- A category with a zero object has zero morphisms. It is rarely a good idea to use this. Many categories that have a zero object have zero morphisms for some other reason, for example from additivity. Library code that uses `zero_morphisms_of_zero_object` will then be incompatible with these categories because the `has_zero_morphisms` instances will not be definitionally equal. For this reason library code should generally ask for an instance of `has_zero_morphisms` separately, even if it already asks for an instance of `has_zero_objects`. -/ def zero_morphisms_of_zero_object : has_zero_morphisms C := { has_zero := Ξ» X Y, { zero := inhabited.default (X ⟢ 0) ≫ inhabited.default (0 ⟢ Y) }, zero_comp' := Ξ» X Y Z f, by { dunfold has_zero.zero, rw category.assoc, congr, }, comp_zero' := Ξ» X Y Z f, by { dunfold has_zero.zero, rw ←category.assoc, congr, }} /-- A zero object is in particular initial. -/ lemma has_initial : has_initial C := has_initial_of_unique 0 /-- A zero object is in particular terminal. -/ lemma has_terminal : has_terminal C := has_terminal_of_unique 0 end has_zero_object section variables [has_zero_object C] [has_zero_morphisms C] local attribute [instance] has_zero_object.has_zero @[simp] lemma id_zero : πŸ™ (0 : C) = (0 : 0 ⟢ 0) := by ext /-- An arrow ending in the zero object is zero -/ -- This can't be a `simp` lemma because the left hand side would be a metavariable. lemma zero_of_to_zero {X : C} (f : X ⟢ 0) : f = 0 := by ext lemma zero_of_target_iso_zero {X Y : C} (f : X ⟢ Y) (i : Y β‰… 0) : f = 0 := begin have h : f = f ≫ i.hom ≫ πŸ™ 0 ≫ i.inv := by simp only [iso.hom_inv_id, id_comp, comp_id], simpa using h, end /-- An arrow starting at the zero object is zero -/ lemma zero_of_from_zero {X : C} (f : 0 ⟢ X) : f = 0 := by ext lemma zero_of_source_iso_zero {X Y : C} (f : X ⟢ Y) (i : X β‰… 0) : f = 0 := begin have h : f = i.hom ≫ πŸ™ 0 ≫ i.inv ≫ f := by simp only [iso.hom_inv_id_assoc, id_comp, comp_id], simpa using h, end lemma zero_of_source_iso_zero' {X Y : C} (f : X ⟢ Y) (i : is_isomorphic X 0) : f = 0 := zero_of_source_iso_zero f (nonempty.some i) lemma zero_of_target_iso_zero' {X Y : C} (f : X ⟢ Y) (i : is_isomorphic Y 0) : f = 0 := zero_of_target_iso_zero f (nonempty.some i) lemma mono_of_source_iso_zero {X Y : C} (f : X ⟢ Y) (i : X β‰… 0) : mono f := ⟨λ Z g h w, by rw [zero_of_target_iso_zero g i, zero_of_target_iso_zero h i]⟩ lemma epi_of_target_iso_zero {X Y : C} (f : X ⟢ Y) (i : Y β‰… 0) : epi f := ⟨λ Z g h w, by rw [zero_of_source_iso_zero g i, zero_of_source_iso_zero h i]⟩ /-- An object `X` has `πŸ™ X = 0` if and only if it is isomorphic to the zero object. Because `X β‰… 0` contains data (even if a subsingleton), we express this `↔` as an `≃`. -/ def id_zero_equiv_iso_zero (X : C) : (πŸ™ X = 0) ≃ (X β‰… 0) := { to_fun := Ξ» h, { hom := 0, inv := 0, }, inv_fun := Ξ» i, zero_of_target_iso_zero (πŸ™ X) i, left_inv := by tidy, right_inv := by tidy, } @[simp] lemma id_zero_equiv_iso_zero_apply_hom (X : C) (h : πŸ™ X = 0) : ((id_zero_equiv_iso_zero X) h).hom = 0 := rfl @[simp] lemma id_zero_equiv_iso_zero_apply_inv (X : C) (h : πŸ™ X = 0) : ((id_zero_equiv_iso_zero X) h).inv = 0 := rfl /-- If an object `X` is isomorphic to 0, there's no need to use choice to construct an explicit isomorphism: the zero morphism suffices. -/ def iso_of_is_isomorphic_zero {X : C} (P : is_isomorphic X 0) : X β‰… 0 := { hom := 0, inv := 0, hom_inv_id' := begin casesI P, rw ←P.hom_inv_id, rw ←category.id_comp P.inv, simp, end, inv_hom_id' := by simp, } end section is_iso variables [has_zero_morphisms C] /-- A zero morphism `0 : X ⟢ Y` is an isomorphism if and only if the identities on both `X` and `Y` are zero. -/ @[simps] def is_iso_zero_equiv (X Y : C) : is_iso (0 : X ⟢ Y) ≃ (πŸ™ X = 0 ∧ πŸ™ Y = 0) := { to_fun := by { introsI i, rw ←is_iso.hom_inv_id (0 : X ⟢ Y), rw ←is_iso.inv_hom_id (0 : X ⟢ Y), simp }, inv_fun := Ξ» h, ⟨⟨(0 : Y ⟢ X), by tidy⟩⟩, left_inv := by tidy, right_inv := by tidy, } /-- A zero morphism `0 : X ⟢ X` is an isomorphism if and only if the identity on `X` is zero. -/ def is_iso_zero_self_equiv (X : C) : is_iso (0 : X ⟢ X) ≃ (πŸ™ X = 0) := by simpa using is_iso_zero_equiv X X variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- A zero morphism `0 : X ⟢ Y` is an isomorphism if and only if `X` and `Y` are isomorphic to the zero object. -/ def is_iso_zero_equiv_iso_zero (X Y : C) : is_iso (0 : X ⟢ Y) ≃ (X β‰… 0) Γ— (Y β‰… 0) := begin -- This is lame, because `prod` can't cope with `Prop`, so we can't use `equiv.prod_congr`. refine (is_iso_zero_equiv X Y).trans _, symmetry, fsplit, { rintros ⟨eX, eY⟩, fsplit, exact (id_zero_equiv_iso_zero X).symm eX, exact (id_zero_equiv_iso_zero Y).symm eY, }, { rintros ⟨hX, hY⟩, fsplit, exact (id_zero_equiv_iso_zero X) hX, exact (id_zero_equiv_iso_zero Y) hY, }, { tidy, }, { tidy, }, end /-- A zero morphism `0 : X ⟢ X` is an isomorphism if and only if `X` is isomorphic to the zero object. -/ def is_iso_zero_self_equiv_iso_zero (X : C) : is_iso (0 : X ⟢ X) ≃ (X β‰… 0) := (is_iso_zero_equiv_iso_zero X X).trans subsingleton_prod_self_equiv end is_iso /-- If there are zero morphisms, any initial object is a zero object. -/ @[priority 50] instance has_zero_object_of_has_initial_object [has_zero_morphisms C] [has_initial C] : has_zero_object C := { zero := βŠ₯_ C, unique_to := Ξ» X, ⟨⟨0⟩, by tidy⟩, unique_from := Ξ» X, ⟨⟨0⟩, Ξ» f, calc f = f ≫ πŸ™ _ : (category.comp_id _).symm ... = f ≫ 0 : by congr ... = 0 : has_zero_morphisms.comp_zero _ _ ⟩ } /-- If there are zero morphisms, any terminal object is a zero object. -/ @[priority 50] instance has_zero_object_of_has_terminal_object [has_zero_morphisms C] [has_terminal C] : has_zero_object C := { zero := ⊀_ C, unique_from := Ξ» X, ⟨⟨0⟩, by tidy⟩, unique_to := Ξ» X, ⟨⟨0⟩, Ξ» f, calc f = πŸ™ _ ≫ f : (category.id_comp _).symm ... = 0 ≫ f : by congr ... = 0 : zero_comp ⟩ } section image variable [has_zero_morphisms C] lemma image_ΞΉ_comp_eq_zero {X Y Z : C} {f : X ⟢ Y} {g : Y ⟢ Z} [has_image f] [epi (factor_thru_image f)] (h : f ≫ g = 0) : image.ΞΉ f ≫ g = 0 := zero_of_epi_comp (factor_thru_image f) $ by simp [h] variables [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- The zero morphism has a `mono_factorisation` through the zero object. -/ @[simps] def mono_factorisation_zero (X Y : C) : mono_factorisation (0 : X ⟢ Y) := { I := 0, m := 0, e := 0, } /-- The factorisation through the zero object is an image factorisation. -/ def image_factorisation_zero (X Y : C) : image_factorisation (0 : X ⟢ Y) := { F := mono_factorisation_zero X Y, is_image := { lift := Ξ» F', 0 } } instance has_image_zero {X Y : C} : has_image (0 : X ⟢ Y) := has_image.mk $ image_factorisation_zero _ _ /-- The image of a zero morphism is the zero object. -/ def image_zero {X Y : C} : image (0 : X ⟢ Y) β‰… 0 := is_image.iso_ext (image.is_image (0 : X ⟢ Y)) (image_factorisation_zero X Y).is_image /-- The image of a morphism which is equal to zero is the zero object. -/ def image_zero' {X Y : C} {f : X ⟢ Y} (h : f = 0) [has_image f] : image f β‰… 0 := image.eq_to_iso h β‰ͺ≫ image_zero @[simp] lemma image.ΞΉ_zero {X Y : C} [has_image (0 : X ⟢ Y)] : image.ΞΉ (0 : X ⟢ Y) = 0 := begin rw ←image.lift_fac (mono_factorisation_zero X Y), simp, end /-- If we know `f = 0`, it requires a little work to conclude `image.ΞΉ f = 0`, because `f = g` only implies `image f β‰… image g`. -/ @[simp] lemma image.ΞΉ_zero' [has_equalizers C] {X Y : C} {f : X ⟢ Y} (h : f = 0) [has_image f] : image.ΞΉ f = 0 := by { rw image.eq_fac h, simp } end image /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_sigma_ΞΉ {Ξ² : Type v} [decidable_eq Ξ²] [has_zero_morphisms C] (f : Ξ² β†’ C) [has_colimit (discrete.functor f)] (b : Ξ²) : split_mono (sigma.ΞΉ f b) := { retraction := sigma.desc (Ξ» b', if h : b' = b then eq_to_hom (congr_arg f h) else 0), } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_pi_Ο€ {Ξ² : Type v} [decidable_eq Ξ²] [has_zero_morphisms C] (f : Ξ² β†’ C) [has_limit (discrete.functor f)] (b : Ξ²) : split_epi (pi.Ο€ f b) := { section_ := pi.lift (Ξ» b', if h : b = b' then eq_to_hom (congr_arg f h) else 0), } /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_coprod_inl [has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] : split_mono (coprod.inl : X ⟢ X β¨Ώ Y) := { retraction := coprod.desc (πŸ™ X) 0, } /-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/ instance split_mono_coprod_inr [has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] : split_mono (coprod.inr : Y ⟢ X β¨Ώ Y) := { retraction := coprod.desc 0 (πŸ™ Y), } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_prod_fst [has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] : split_epi (prod.fst : X β¨― Y ⟢ X) := { section_ := prod.lift (πŸ™ X) 0, } /-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/ instance split_epi_prod_snd [has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] : split_epi (prod.snd : X β¨― Y ⟢ Y) := { section_ := prod.lift 0 (πŸ™ Y), } end category_theory.limits
841b89dd4d4428e6cf6d37da2cc0d3cb59fbedfd
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/format_thunk1.lean
a3d083f3e57f922af278c3c031a793d66bcb0237
[ "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
132
lean
open tactic example : true := by do str ← to_expr ``(string), one ← to_expr ``(1), definev `H str one, constructor
63d71a1ce8d76eb1183a9d0b749de6b6af640cc5
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/finsupp/pointwise.lean
bdc93a49df5d17c93e32091159252d6345aea71f
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,220
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 data.finsupp.basic /-! # The pointwise product on `finsupp`. TODO per issue #1864: We intend to remove the convolution product on finsupp, and define it only on a type synonym `add_monoid_algebra`. After we've done this, it would be good to make this the default product on `finsupp`. -/ noncomputable theory open_locale classical open finset universes u₁ uβ‚‚ u₃ uβ‚„ uβ‚… variables {Ξ± : Type u₁} {Ξ² : Type uβ‚‚} {Ξ³ : Type u₃} {Ξ΄ : Type uβ‚„} {ΞΉ : Type uβ‚…} namespace finsupp /-! ### Declarations about the pointwise product on `finsupp`s -/ section variables [mul_zero_class Ξ²] /-- The product of `f g : Ξ± β†’β‚€ Ξ²` is the finitely supported function whose value at `a` is `f a * g a`. -/ instance : has_mul (Ξ± β†’β‚€ Ξ²) := ⟨zip_with (*) (mul_zero 0)⟩ @[simp] lemma mul_apply {g₁ gβ‚‚ : Ξ± β†’β‚€ Ξ²} {a : Ξ±} : (g₁ * gβ‚‚) a = g₁ a * gβ‚‚ a := rfl lemma support_mul {g₁ gβ‚‚ : Ξ± β†’β‚€ Ξ²} : (g₁ * gβ‚‚).support βŠ† g₁.support ∩ gβ‚‚.support := begin intros a h, simp only [mul_apply, mem_support_iff] at h, simp only [mem_support_iff, mem_inter, ne.def], rw ←not_or_distrib, intro w, apply h, cases w; { rw w, simp }, end instance : mul_zero_class (Ξ± β†’β‚€ Ξ²) := { zero := 0, mul := (*), mul_zero := Ξ» f, by { ext, simp only [mul_apply, zero_apply, mul_zero], }, zero_mul := Ξ» f, by { ext, simp only [mul_apply, zero_apply, zero_mul], }, } end instance [semiring Ξ²] : semigroup (Ξ± β†’β‚€ Ξ²) := { mul := (*), mul_assoc := Ξ» f g h, by { ext, simp only [mul_apply, mul_assoc], }, } instance [semiring Ξ²] : distrib (Ξ± β†’β‚€ Ξ²) := { left_distrib := Ξ» f g h, by { ext, simp only [mul_apply, add_apply, left_distrib] {proj := ff} }, right_distrib := Ξ» f g h, by { ext, simp only [mul_apply, add_apply, right_distrib] {proj := ff} }, ..(infer_instance : semigroup (Ξ± β†’β‚€ Ξ²)), ..(infer_instance : add_comm_monoid (Ξ± β†’β‚€ Ξ²)) } -- If `non_unital_semiring` existed in the algebraic hierarchy, we could produce one here. end finsupp
eb50ec8cf5a31ec47c507dca966e64696107a95f
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/data/complex/is_R_or_C.lean
a759eb58f331979a66f0c93cebb5022f12fb00d3
[ "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
25,812
lean
/- Copyright (c) 2020 FrΓ©dΓ©ric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: FrΓ©dΓ©ric Dupuis -/ import analysis.normed_space.basic import analysis.complex.basic /-! # `is_R_or_C`: a typeclass for ℝ or β„‚ This file defines the typeclass `is_R_or_C` intended to have only two instances: ℝ and β„‚. It is meant for definitions and theorems which hold for both the real and the complex case, and in particular when the real case follows directly from the complex case by setting `re` to `id`, `im` to zero and so on. Its API follows closely that of β„‚. Possible applications include defining inner products and Hilbert spaces for both the real and complex case. One would produce the definitions and proof for an arbitrary field of this typeclass, which basically amounts to doing the complex case, and the two cases then fall out immediately from the two instances of the class. -/ /-- This typeclass captures properties shared by ℝ and β„‚, with an API that closely matches that of β„‚. -/ class is_R_or_C (K : Type*) extends nondiscrete_normed_field K, normed_algebra ℝ K, complete_space K := (re : K β†’+ ℝ) (im : K β†’+ ℝ) (conj : K β†’+* K) (I : K) -- Meant to be set to 0 for K=ℝ (of_real : ℝ β†’ K) -- Meant to be id for K=ℝ and the coercion from ℝ for K=β„‚ (I_re_ax : re I = 0) (I_mul_I_ax : I = 0 ∨ I * I = -1) (re_add_im_ax : βˆ€ (z : K), of_real (re z) + of_real (im z) * I = z) (smul_coe_mul_ax : βˆ€ (z : K) (r : ℝ), r β€’ z = of_real r * z) (of_real_re_ax : βˆ€ r : ℝ, re (of_real r) = r) (of_real_im_ax : βˆ€ r : ℝ, im (of_real r) = 0) (mul_re_ax : βˆ€ z w : K, re (z * w) = re z * re w - im z * im w) (mul_im_ax : βˆ€ z w : K, im (z * w) = re z * im w + im z * re w) (conj_re_ax : βˆ€ z : K, re (conj z) = re z) (conj_im_ax : βˆ€ z : K, im (conj z) = -(im z)) (conj_I_ax : conj I = -I) (norm_sq_eq_def_ax : βˆ€ (z : K), βˆ₯zβˆ₯^2 = (re z) * (re z) + (im z) * (im z)) (mul_im_I_ax : βˆ€ (z : K), (im z) * im I = im z) (inv_def_ax : βˆ€ (z : K), z⁻¹ = conj z * of_real ((βˆ₯zβˆ₯^2)⁻¹)) (div_I_ax : βˆ€ (z : K), z / I = -(z * I)) namespace is_R_or_C variables {K : Type*} [is_R_or_C K] local notation `π“š` := @is_R_or_C.of_real K _ local postfix `†`:100 := @is_R_or_C.conj K _ lemma of_real_alg : βˆ€ x : ℝ, π“š x = x β€’ (1 : K) := Ξ» x, by rw [←mul_one (π“š x), smul_coe_mul_ax] @[simp] lemma re_add_im (z : K) : π“š (re z) + π“š (im z) * I = z := is_R_or_C.re_add_im_ax z @[simp] lemma of_real_re : βˆ€ r : ℝ, re (π“š r) = r := is_R_or_C.of_real_re_ax @[simp] lemma of_real_im : βˆ€ r : ℝ, im (π“š r) = 0 := is_R_or_C.of_real_im_ax @[simp] lemma mul_re : βˆ€ z w : K, re (z * w) = re z * re w - im z * im w := is_R_or_C.mul_re_ax @[simp] lemma mul_im : βˆ€ z w : K, im (z * w) = re z * im w + im z * re w := is_R_or_C.mul_im_ax lemma inv_def {z : K} : z⁻¹ = conj z * of_real ((βˆ₯zβˆ₯^2)⁻¹) := is_R_or_C.inv_def_ax z theorem ext_iff : βˆ€ {z w : K}, z = w ↔ re z = re w ∧ im z = im w := Ξ» z w, { mp := by { rintro rfl, cc }, mpr := by { rintro ⟨h₁,hβ‚‚βŸ©, rw [←re_add_im z, ←re_add_im w, h₁, hβ‚‚] } } theorem ext : βˆ€ {z w : K}, re z = re w β†’ im z = im w β†’ z = w := by { simp_rw ext_iff, cc } @[simp] lemma zero_re : re (π“š 0) = (0 : ℝ) := by simp only [of_real_re] @[simp] lemma zero_im : im (π“š 0) = 0 := by rw [of_real_im] lemma of_real_zero : π“š 0 = 0 := by rw [of_real_alg, zero_smul] @[simp] lemma zero_re' : re (0 : K) = (0 : ℝ) := by simp only [add_monoid_hom.map_zero] @[simp] lemma of_real_one : π“š 1 = 1 := by rw [of_real_alg, one_smul] @[simp] lemma one_re : re (1 : K) = 1 := by rw [←of_real_one, of_real_re] @[simp] lemma one_im : im (1 : K) = 0 := by rw [←of_real_one, of_real_im] @[simp] theorem of_real_inj {z w : ℝ} : π“š z = π“š w ↔ z = w := { mp := Ξ» h, by { convert congr_arg re h; simp only [of_real_re] }, mpr := Ξ» h, by rw h } @[simp] lemma bit0_re (z : K) : re (bit0 z) = bit0 (re z) := by simp [bit0] @[simp] lemma bit1_re (z : K) : re (bit1 z) = bit1 (re z) := by simp only [bit1, add_monoid_hom.map_add, bit0_re, add_right_inj, one_re] @[simp] lemma bit0_im (z : K) : im (bit0 z) = bit0 (im z) := by simp [bit0] @[simp] lemma bit1_im (z : K) : im (bit1 z) = bit0 (im z) := by simp only [bit1, add_right_eq_self, add_monoid_hom.map_add, bit0_im, one_im] @[simp] theorem of_real_eq_zero {z : ℝ} : π“š z = 0 ↔ z = 0 := by rw [←of_real_zero]; exact of_real_inj @[simp] lemma of_real_add ⦃r s : ℝ⦄ : π“š (r + s) = π“š r + π“š s := by apply (@is_R_or_C.ext_iff K _ (π“š (r + s)) (π“š r + π“š s)).mpr; simp @[simp] lemma of_real_bit0 (r : ℝ) : π“š (bit0 r : ℝ) = bit0 (π“š r) := ext_iff.2 $ by simp [bit0] @[simp] lemma of_real_bit1 (r : ℝ) : π“š (bit1 r : ℝ) = bit1 (π“š r) := ext_iff.2 $ by simp [bit1] /- Note: This can be proven by `norm_num` once K is proven to be of characteristic zero below. -/ lemma two_ne_zero : (2 : K) β‰  0 := begin intro h, rw [(show (2 : K) = π“š 2, by norm_num), ←of_real_zero, of_real_inj] at h, linarith, end @[simp] lemma of_real_neg (r : ℝ) : π“š (-r) = -(π“š r) := ext_iff.2 $ by simp @[simp] lemma of_real_mul (r s : ℝ) : π“š (r * s) = (π“š r) * (π“š s) := ext_iff.2 $ by simp lemma of_real_mul_re (r : ℝ) (z : K) : re ((π“š r) * z) = r * re z := by simp only [mul_re, of_real_im, zero_mul, of_real_re, sub_zero] lemma smul_re (r : ℝ) (z : K) : re ((π“š r) * z) = r * (re z) := by simp only [of_real_im, zero_mul, of_real_re, sub_zero, mul_re] lemma smul_im (r : ℝ) (z : K) : im ((π“š r) * z) = r * (im z) := by simp only [add_zero, of_real_im, zero_mul, of_real_re, mul_im] lemma smul_re' : βˆ€ (r : ℝ) (z : K), re (r β€’ z) = r * (re z) := Ξ» r z, by { rw [smul_coe_mul_ax], apply smul_re } lemma smul_im' : βˆ€ (r : ℝ) (z : K), im (r β€’ z) = r * (im z) := Ξ» r z, by { rw [smul_coe_mul_ax], apply smul_im } /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ @[simp] lemma I_re : re (I : K) = 0 := I_re_ax @[simp] lemma I_im (z : K) : im z * im (I : K) = im z := mul_im_I_ax z @[simp] lemma I_im' (z : K) : im (I : K) * im z = im z := by rw [mul_comm, I_im _] lemma I_mul_I : (I : K) = 0 ∨ (I : K) * I = -1 := I_mul_I_ax @[simp] lemma conj_re (z : K) : re (conj z) = re z := is_R_or_C.conj_re_ax z @[simp] lemma conj_im (z : K) : im (conj z) = -(im z) := is_R_or_C.conj_im_ax z @[simp] lemma conj_of_real (r : ℝ) : conj (π“š r) = (π“š r) := by { rw ext_iff, simp only [of_real_im, conj_im, eq_self_iff_true, conj_re, and_self, neg_zero] } @[simp] lemma conj_bit0 (z : K) : conj (bit0 z) = bit0 (conj z) := by simp [bit0, ext_iff] @[simp] lemma conj_bit1 (z : K) : conj (bit1 z) = bit1 (conj z) := by simp [bit0, ext_iff] @[simp] lemma conj_neg_I : conj (-I) = (I : K) := by simp [ext_iff] @[simp] lemma conj_conj (z : K) : conj (conj z) = z := by simp [ext_iff] lemma conj_involutive : @function.involutive K is_R_or_C.conj := conj_conj lemma conj_bijective : @function.bijective K K is_R_or_C.conj := conj_involutive.bijective lemma conj_inj (z w : K) : conj z = conj w ↔ z = w := conj_bijective.1.eq_iff @[simp] lemma conj_eq_zero {z : K} : conj z = 0 ↔ z = 0 := by simpa using @conj_inj K _ z 0 lemma eq_conj_iff_real {z : K} : conj z = z ↔ βˆƒ r : ℝ, z = (π“š r) := begin split, { intro h, suffices : im z = 0, { use (re z), rw ← add_zero (of_real _), convert (re_add_im z).symm, simp [this] }, contrapose! h, rw ← re_add_im z, simp only [conj_of_real, ring_hom.map_add, ring_hom.map_mul, conj_I_ax], rw [add_left_cancel_iff, ext_iff], simpa [neg_eq_iff_add_eq_zero, add_self_eq_zero] }, { rintros ⟨r, rfl⟩, apply conj_of_real } end /-- Conjugation as a ring equivalence. This is used to convert the inner product into a sesquilinear product. -/ def conj_to_ring_equiv : K ≃+* Kα΅’α΅– := { to_fun := opposite.op ∘ conj, inv_fun := conj ∘ opposite.unop, left_inv := Ξ» x, by simp only [conj_conj, function.comp_app, opposite.unop_op], right_inv := Ξ» x, by simp only [conj_conj, opposite.op_unop, function.comp_app], map_mul' := Ξ» x y, by simp [mul_comm], map_add' := Ξ» x y, by simp } lemma eq_conj_iff_re {z : K} : conj z = z ↔ π“š (re z) = z := eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, Ξ» h, ⟨_, h.symm⟩⟩ /-- The norm squared function. -/ def norm_sq (z : K) : ℝ := re z * re z + im z * im z lemma norm_sq_eq_def {z : K} : βˆ₯zβˆ₯^2 = (re z) * (re z) + (im z) * (im z) := norm_sq_eq_def_ax z lemma norm_sq_eq_def' (z : K) : norm_sq z = βˆ₯zβˆ₯^2 := by rw [norm_sq_eq_def, norm_sq] @[simp] lemma norm_sq_of_real (r : ℝ) : βˆ₯π“š rβˆ₯^2 = r * r := by simp [norm_sq_eq_def] @[simp] lemma norm_sq_zero : norm_sq (0 : K) = 0 := by simp [norm_sq, pow_two] @[simp] lemma norm_sq_one : norm_sq (1 : K) = 1 := by simp [norm_sq] lemma norm_sq_nonneg (z : K) : 0 ≀ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma norm_sq_eq_zero {z : K} : norm_sq z = 0 ↔ z = 0 := by { rw [norm_sq, ←norm_sq_eq_def], simp [pow_two] } @[simp] lemma norm_sq_pos {z : K} : 0 < norm_sq z ↔ z β‰  0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg] @[simp] lemma norm_sq_neg (z : K) : norm_sq (-z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_conj (z : K) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_mul (z w : K) : norm_sq (z * w) = norm_sq z * norm_sq w := by simp [norm_sq, pow_two]; ring lemma norm_sq_add (z w : K) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (re (z * conj w)) := by simp [norm_sq, pow_two]; ring lemma re_sq_le_norm_sq (z : K) : re z * re z ≀ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : K) : im z * im z ≀ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : K) : z * conj z = π“š (norm_sq z) := by simp [ext_iff, norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : K) : z + conj z = π“š (2 * re z) := by simp [ext_iff, two_mul] /-- The pseudo-coercion `of_real` as a `ring_hom`. -/ def of_real_hom : ℝ β†’+* K := ⟨of_real, of_real_one, of_real_mul, of_real_zero, of_real_add⟩ @[simp] lemma of_real_sub (r s : ℝ) : π“š (r - s : ℝ) = π“š r - π“š s := ext_iff.2 $ by simp @[simp] lemma of_real_pow (r : ℝ) (n : β„•) : π“š (r ^ n : ℝ) = (π“š r) ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : K) : z - conj z = π“š (2 * im z) * I := by simp [ext_iff, two_mul, sub_eq_add_neg, add_mul, mul_im_I_ax] lemma norm_sq_sub (z w : K) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * re (z * conj w) := by simp [-mul_re, norm_sq_add, add_comm, add_left_comm, sub_eq_add_neg] lemma sqrt_norm_sq_eq_norm {z : K} : real.sqrt (norm_sq z) = βˆ₯zβˆ₯ := begin have h₁ : (norm_sq z) = βˆ₯zβˆ₯^2 := by rw [norm_sq_eq_def, norm_sq], have hβ‚‚ : βˆ₯zβˆ₯ = real.sqrt (βˆ₯zβˆ₯^2) := eq_comm.mp (real.sqrt_sqr (norm_nonneg z)), rw [hβ‚‚], exact congr_arg real.sqrt h₁ end /-! ### Inversion -/ @[simp] lemma inv_re (z : K) : re (z⁻¹) = re z / norm_sq z := by simp [inv_def, norm_sq_eq_def, norm_sq, division_def] @[simp] lemma inv_im (z : K) : im (z⁻¹) = im (-z) / norm_sq z := by simp [inv_def, norm_sq_eq_def, norm_sq, division_def] @[simp] lemma of_real_inv (r : ℝ) : π“š (r⁻¹) = (π“š r)⁻¹ := begin rw ext_iff, by_cases r = 0, { simp [h] }, { simp; field_simp [h, norm_sq] }, end protected lemma inv_zero : (0⁻¹ : K) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : K} (h : z β‰  0) : z * z⁻¹ = 1 := by rw [inv_def, ←mul_assoc, mul_conj, ←of_real_mul, ←norm_sq_eq_def', mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] lemma div_re (z w : K) : re (z / w) = re z * re w / norm_sq w + im z * im w / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : K) : im (z / w) = im z * re w / norm_sq w - re z * im w / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] @[simp] lemma of_real_div (r s : ℝ) : π“š (r / s : ℝ) = π“š r / π“š s := (@is_R_or_C.of_real_hom K _).map_div r s lemma div_re_of_real {z : K} {r : ℝ} : re (z / (π“š r)) = re z / r := begin by_cases h : r = 0, { simp [h, of_real_zero] }, { change r β‰  0 at h, rw [div_eq_mul_inv, ←of_real_inv, div_eq_mul_inv], simp [norm_sq, norm_sq_of_real, div_mul_eq_div_mul_one_div, div_self h] } end @[simp] lemma of_real_fpow (r : ℝ) (n : β„€) : π“š (r ^ n) = (π“š r) ^ n := (@is_R_or_C.of_real_hom K _).map_fpow r n lemma I_mul_I_of_nonzero : (I : K) β‰  0 β†’ (I : K) * I = -1 := by { have := I_mul_I_ax, tauto } @[simp] lemma div_I (z : K) : z / I = -(z * I) := begin by_cases h : (I : K) = 0, { simp [h] }, { field_simp [h], simp [mul_assoc, I_mul_I_of_nonzero h] } end @[simp] lemma inv_I : (I : K)⁻¹ = -I := by { by_cases h : (I : K) = 0; field_simp [h] } @[simp] lemma norm_sq_inv (z : K) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := begin by_cases z = 0, { simp [h] }, { refine mul_right_cancel' (mt norm_sq_eq_zero.1 h) _, simp [h, ←norm_sq_mul], } end @[simp] lemma norm_sq_div (z w : K) : norm_sq (z / w) = norm_sq z / norm_sq w := by { rw [division_def, norm_sq_mul, norm_sq_inv], refl } lemma norm_conj {z : K} : βˆ₯conj zβˆ₯ = βˆ₯zβˆ₯ := by simp only [←sqrt_norm_sq_eq_norm, norm_sq_conj] lemma conj_inv {z : K} : conj (z⁻¹) = (conj z)⁻¹ := by simp only [inv_def, norm_conj, ring_hom.map_mul, conj_of_real] lemma conj_div {z w : K} : conj (z / w) = (conj z) / (conj w) := by rw [div_eq_inv_mul, div_eq_inv_mul, ring_hom.map_mul]; simp only [conj_inv] /-! ### Cast lemmas -/ @[simp] theorem of_real_nat_cast (n : β„•) : π“š (n : ℝ) = n := of_real_hom.map_nat_cast n @[simp] lemma nat_cast_re (n : β„•) : re (n : K) = n := by rw [← of_real_nat_cast, of_real_re] @[simp] lemma nat_cast_im (n : β„•) : im (n : K) = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp] theorem of_real_int_cast (n : β„€) : π“š (n : ℝ) = n := of_real_hom.map_int_cast n @[simp] lemma int_cast_re (n : β„€) : re (n : K) = n := by rw [← of_real_int_cast, of_real_re] @[simp] lemma int_cast_im (n : β„€) : im (n : K) = 0 := by rw [← of_real_int_cast, of_real_im] @[simp] theorem of_real_rat_cast (n : β„š) : π“š (n : ℝ) = n := (@is_R_or_C.of_real_hom K _).map_rat_cast n @[simp] lemma rat_cast_re (q : β„š) : re (q : K) = q := by rw [← of_real_rat_cast, of_real_re] @[simp] lemma rat_cast_im (q : β„š) : im (q : K) = 0 := by rw [← of_real_rat_cast, of_real_im] /-! ### Characteristic zero -/ /-- ℝ and β„‚ are both of characteristic zero. Note: This is not registered as an instance to avoid having multiple instances on ℝ and β„‚. -/ lemma char_zero_R_or_C : char_zero K := add_group.char_zero_of_inj_zero $ Ξ» n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h theorem re_eq_add_conj (z : K) : π“š (re z) = (z + conj z) / 2 := by rw [add_conj]; simp; rw [mul_div_cancel_left (π“š (re z)) two_ne_zero] /-! ### Absolute value -/ /-- The complex absolute value function, defined as the square root of the norm squared. -/ @[pp_nodot] noncomputable def abs (z : K) : ℝ := (norm_sq z).sqrt local notation `abs'` := _root_.abs local notation `absK` := @abs K _ @[simp] lemma abs_of_real (r : ℝ) : absK (π“š r) = abs' r := by simp [abs, norm_sq, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma abs_of_nonneg {r : ℝ} (h : 0 ≀ r) : absK (π“š r) = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : β„•) : absK n = n := by { rw [← of_real_nat_cast], exact abs_of_nonneg (nat.cast_nonneg n) } lemma mul_self_abs (z : K) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : absK 0 = 0 := by simp [abs] @[simp] lemma abs_one : absK 1 = 1 := by simp [abs] @[simp] lemma abs_two : absK 2 = 2 := calc absK 2 = absK (π“š 2) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : K) : 0 ≀ absK z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : K} : absK z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero lemma abs_ne_zero {z : K} : abs z β‰  0 ↔ z β‰  0 := not_congr abs_eq_zero @[simp] lemma abs_conj (z : K) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : K) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl lemma abs_re_le_abs (z : K) : abs' (re z) ≀ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (re z)) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : K) : abs' (im z) ≀ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (im z)) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : K) : re z ≀ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : K) : im z ≀ abs z := (abs_le.1 (abs_im_le_abs _)).2 lemma abs_add (z w : K) : abs (z + w) ≀ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@zero_lt_two ℝ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : is_absolute_value absK := { abv_nonneg := abs_nonneg, abv_eq_zero := Ξ» _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[simp] lemma abs_abs (z : K) : abs' (abs z) = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : K} : 0 < abs z ↔ z β‰  0 := abv_pos abs @[simp] lemma abs_neg : βˆ€ z : K, abs (-z) = abs z := abv_neg abs lemma abs_sub : βˆ€ z w : K, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : βˆ€ a b c : K, abs (a - c) ≀ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : βˆ€ z : K, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : βˆ€ z w : K, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : βˆ€ z w : K, abs' (abs z - abs w) ≀ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_re_div_abs_le_one (z : K) : abs' (re z / abs z) ≀ 1 := begin by_cases hz : z = 0, { simp [hz, zero_le_one] }, { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] } end lemma abs_im_div_abs_le_one (z : K) : abs' (im z / abs z) ≀ 1 := begin by_cases hz : z = 0, { simp [hz, zero_le_one] }, { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] } end @[simp] lemma abs_cast_nat (n : β„•) : abs (n : K) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] lemma norm_sq_eq_abs (x : K) : norm_sq x = abs x ^ 2 := by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)] lemma re_eq_abs_of_mul_conj (x : K) : re (x * (conj x)) = abs (x * (conj x)) := by rw [mul_conj, of_real_re, abs_of_real, norm_sq_eq_abs, pow_two, _root_.abs_mul, abs_abs] lemma abs_sqr_re_add_conj (x : K) : (abs (x + x†))^2 = (re (x + x†))^2 := by simp [pow_two, ←norm_sq_eq_abs, norm_sq] lemma abs_sqr_re_add_conj' (x : K) : (abs (x† + x))^2 = (re (x† + x))^2 := by simp [pow_two, ←norm_sq_eq_abs, norm_sq] lemma conj_mul_eq_norm_sq_left (x : K) : x† * x = π“š (norm_sq x) := begin rw ext_iff, refine ⟨by simp [of_real_re, mul_re, conj_re, conj_im, norm_sq],_⟩, simp [of_real_im, mul_im, conj_im, conj_re, mul_comm], end /-! ### Cauchy sequences -/ theorem is_cau_seq_re (f : cau_seq K abs) : is_cau_seq abs' (Ξ» n, re (f n)) := Ξ» Ξ΅ Ξ΅0, (f.cauchy Ξ΅0).imp $ Ξ» i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq K abs) : is_cau_seq abs' (Ξ» n, im (f n)) := Ξ» Ξ΅ Ξ΅0, (f.cauchy Ξ΅0).imp $ Ξ» i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) /-- The real part of a K Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_re (f : cau_seq K abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ /-- The imaginary part of a K Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_im (f : cau_seq K abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : β„• β†’ K} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := Ξ» Ξ΅ Ξ΅0, let ⟨i, hi⟩ := hf Ξ΅ Ξ΅0 in ⟨i, Ξ» j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ end is_R_or_C section instances noncomputable instance real.is_R_or_C : is_R_or_C ℝ := { re := add_monoid_hom.id ℝ, im := 0, conj := ring_hom.id ℝ, I := 0, of_real := id, I_re_ax := by simp only [add_monoid_hom.map_zero], I_mul_I_ax := or.intro_left _ rfl, re_add_im_ax := Ξ» z, by unfold_coes; simp [add_zero, id.def, mul_zero], smul_coe_mul_ax := Ξ» z r, by simp only [algebra.id.smul_eq_mul, id.def], of_real_re_ax := Ξ» r, by simp only [id.def, add_monoid_hom.id_apply], of_real_im_ax := Ξ» r, by simp only [add_monoid_hom.zero_apply], mul_re_ax := Ξ» z w, by simp only [sub_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply], mul_im_ax := Ξ» z w, by simp only [add_zero, zero_mul, mul_zero, add_monoid_hom.zero_apply], conj_re_ax := Ξ» z, by simp only [ring_hom.id_apply], conj_im_ax := Ξ» z, by simp only [neg_zero, add_monoid_hom.zero_apply], conj_I_ax := by simp only [ring_hom.map_zero, neg_zero], norm_sq_eq_def_ax := Ξ» z, by simp only [pow_two, norm, ←abs_mul, abs_mul_self z, add_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply], mul_im_I_ax := Ξ» z, by simp only [mul_zero, add_monoid_hom.zero_apply], inv_def_ax := begin intro z, unfold_coes, have H : z β‰  0 β†’ 1 / z = z / (z * z) := Ξ» h, calc 1 / z = 1 * (1 / z) : (one_mul (1 / z)).symm ... = (z / z) * (1 / z) : congr_arg (Ξ» x, x * (1 / z)) (div_self h).symm ... = z / (z * z) : by field_simp, rcases lt_trichotomy z 0 with hlt|heq|hgt, { field_simp [norm, abs, max_eq_right_of_lt (show z < -z, by linarith), pow_two, mul_inv', ←H (ne_of_lt hlt)] }, { simp [heq] }, { field_simp [norm, abs, max_eq_left_of_lt (show -z < z, by linarith), pow_two, mul_inv', ←H (ne_of_gt hgt)] }, end, div_I_ax := Ξ» z, by simp only [div_zero, mul_zero, neg_zero]} noncomputable instance complex.is_R_or_C : is_R_or_C β„‚ := { re := ⟨complex.re, complex.zero_re, complex.add_re⟩, im := ⟨complex.im, complex.zero_im, complex.add_im⟩, conj := complex.conj, I := complex.I, of_real := coe, I_re_ax := by simp only [add_monoid_hom.coe_mk, complex.I_re], I_mul_I_ax := by simp only [complex.I_mul_I, eq_self_iff_true, or_true], re_add_im_ax := by simp only [forall_const, add_monoid_hom.coe_mk, complex.re_add_im, eq_self_iff_true], smul_coe_mul_ax := Ξ» z r, rfl, of_real_re_ax := Ξ» r, by simp only [add_monoid_hom.coe_mk, complex.of_real_re], of_real_im_ax := Ξ» r, by simp only [add_monoid_hom.coe_mk, complex.of_real_im], mul_re_ax := Ξ» z w, by simp only [complex.mul_re, add_monoid_hom.coe_mk], mul_im_ax := Ξ» z w, by simp only [add_monoid_hom.coe_mk, complex.mul_im], conj_re_ax := Ξ» z, by simp only [ring_hom.coe_mk, add_monoid_hom.coe_mk, complex.conj_re], conj_im_ax := Ξ» z, by simp only [ring_hom.coe_mk, complex.conj_im, add_monoid_hom.coe_mk], conj_I_ax := by simp only [complex.conj_I, ring_hom.coe_mk], norm_sq_eq_def_ax := Ξ» z, by simp only [←complex.norm_sq_eq_abs, ←complex.norm_sq, add_monoid_hom.coe_mk, complex.norm_eq_abs], mul_im_I_ax := Ξ» z, by simp only [mul_one, add_monoid_hom.coe_mk, complex.I_im], inv_def_ax := Ξ» z, by convert complex.inv_def z; exact (complex.norm_sq_eq_abs z).symm, div_I_ax := complex.div_I } end instances namespace is_R_or_C section cleanup_lemmas local notation `reR` := @is_R_or_C.re ℝ _ local notation `imR` := @is_R_or_C.im ℝ _ local notation `conjR` := @is_R_or_C.conj ℝ _ local notation `IR` := @is_R_or_C.I ℝ _ local notation `of_realR` := @is_R_or_C.of_real ℝ _ local notation `absR` := @is_R_or_C.abs ℝ _ local notation `norm_sqR` := @is_R_or_C.norm_sq ℝ _ local notation `reC` := @is_R_or_C.re β„‚ _ local notation `imC` := @is_R_or_C.im β„‚ _ local notation `conjC` := @is_R_or_C.conj β„‚ _ local notation `IC` := @is_R_or_C.I β„‚ _ local notation `of_realC` := @is_R_or_C.of_real β„‚ _ local notation `absC` := @is_R_or_C.abs β„‚ _ local notation `norm_sqC` := @is_R_or_C.norm_sq β„‚ _ @[simp] lemma re_to_real {x : ℝ} : reR x = x := rfl @[simp] lemma im_to_real {x : ℝ} : imR x = 0 := rfl @[simp] lemma conj_to_real {x : ℝ} : conjR x = x := rfl @[simp] lemma I_to_real : IR = 0 := rfl @[simp] lemma of_real_to_real {x : ℝ} : of_realR x = x := rfl @[simp] lemma norm_sq_to_real {x : ℝ} : norm_sqR x = x*x := by simp [is_R_or_C.norm_sq] @[simp] lemma abs_to_real {x : ℝ} : absR x = _root_.abs x := by simp [is_R_or_C.abs, abs, real.sqrt_mul_self_eq_abs] @[simp] lemma re_to_complex {x : β„‚} : reC x = x.re := rfl @[simp] lemma im_to_complex {x : β„‚} : imC x = x.im := rfl @[simp] lemma conj_to_complex {x : β„‚} : conjC x = x.conj := rfl @[simp] lemma I_to_complex : IC = complex.I := rfl @[simp] lemma of_real_to_complex {x : ℝ} : of_realC x = x := rfl @[simp] lemma norm_sq_to_complex {x : β„‚} : norm_sqC x = complex.norm_sq x := by simp [is_R_or_C.norm_sq, complex.norm_sq] @[simp] lemma abs_to_complex {x : β„‚} : absC x = complex.abs x := by simp [is_R_or_C.abs, complex.abs] end cleanup_lemmas end is_R_or_C
61b8b9601cdbc6e69612d73595f20c850b1d845f
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport/Syntax/AST3.lean
ebe66b4bdb9fb26c02975f79196aa724e8bcc950
[ "Apache-2.0" ]
permissive
leanprover-community/mathport
2c9bdc8292168febf59799efdc5451dbf0450d4a
13051f68064f7638970d39a8fecaede68ffbf9e1
refs/heads/master
1,693,841,364,079
1,693,813,111,000
1,693,813,111,000
379,357,010
27
10
Apache-2.0
1,691,309,132,000
1,624,384,521,000
Lean
UTF-8
Lean
false
false
46,724
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Daniel Selsam -/ import Mathport.Util.Misc def Lean.BinderInfo.bracket (paren : Bool) : BinderInfo β†’ Format β†’ Format | BinderInfo.default, f => if paren then f.paren else f.group | BinderInfo.implicit, f => f.bracket "{" "}" | BinderInfo.strictImplicit, f => f.bracket "{{" "}}" | BinderInfo.instImplicit, f => f.sbracket namespace Mathport open Lean (Position Name BinderInfo) open Std (Format) namespace Lean3 inductive Proj | nat : Nat β†’ Proj | ident : Name β†’ Proj deriving Inhabited instance : Repr Proj where reprPrec | Proj.nat n, _ => repr n | Proj.ident n, _ => n.toString open Lean (Level) inductive Annotation | no_univ | do_failure_eq | infix_fn | begin_hole | end_hole | anonymous_constructor | Β«calcΒ» | no_info | frozen_name | Β«haveΒ» | Β«showΒ» | Β«sufficesΒ» | checkpoint | Β«@Β» | Β«@@Β» | as_atomic | as_is | antiquote | expr_quote_pre | comp_irrel | inaccessible | Β«byΒ» | pattern_hint | th_proof deriving Repr structure EquationsHeader := (num_fns : Nat) (fn_names fn_actual_names : Array Name) (is_private is_noncomputable is_meta is_lemma gen_code aux_lemmas : Bool) deriving Repr instance : Repr Level.Data := ⟨fun _ _ => "Β·"⟩ deriving instance Repr for Level mutual inductive Expr where | var : Nat β†’ Expr | sort : Level β†’ Expr | const : Name β†’ Array Level β†’ Expr | mvar (name pp : Name) (type : Expr) | Β«localΒ» (name pp : Name) (bi : BinderInfo) (type : Expr) | app : Expr β†’ Expr β†’ Expr | lam (name : Name) (bi : BinderInfo) (dom body : Expr) | Pi (name : Name) (bi : BinderInfo) (dom body : Expr) | Β«letΒ» (name : Name) (type value body : Expr) | annotation : Annotation β†’ Expr β†’ Expr | field : Expr β†’ Proj β†’ Expr | typed_expr (ty val : Expr) | structinst (struct : Name) (catchall : Bool) (fields : Array (Name Γ— Expr)) (sources : Array Expr) | prenum (value : Nat) | nat (value : Nat) | quote (value : Expr) (expr : Bool) | choice (args : Array Expr) | string (value : String) | no_equation | equation (lhs rhs : Expr) (ignore_if_unused : Bool) | equations (h : EquationsHeader) (eqns : Array LambdaEquation) (wf : Option Expr) | equations_result (args : Array Expr) | as_pattern (lhs rhs : Expr) | delayed_abstraction : Expr β†’ Array (Name Γ— Expr) β†’ Expr | Β«sorryΒ» (synthetic : Bool) (ty : Expr) | rec_fn (name : Name) (ty : Expr) | proj (I constr proj : Name) (idx : Nat) (params : Array Name) (ty val arg : Expr) | ac_app (args : Array Expr) (op : Expr) | perm_ac (assoc comm e1 e2 : Expr) | cc_proof (e1 e2 : Expr) deriving Inhabited, Repr inductive LambdaEquation where | no_equation | equation (lhs rhs : Expr) (ignore_if_unused : Bool) | lam (name : Name) (bi : BinderInfo) (dom : Expr) : LambdaEquation β†’ LambdaEquation deriving Inhabited, Repr end partial def Expr.toLambdaEqn : Expr β†’ Option LambdaEquation | Expr.no_equation => LambdaEquation.no_equation | Expr.equation lhs rhs iu => LambdaEquation.equation lhs rhs iu | Expr.lam n pp bi e => LambdaEquation.lam n pp bi <$> e.toLambdaEqn | _ => none end Lean3 structure Meta where id : Nat start : Position end_ : Position deriving Inhabited structure Spanned (Ξ± : Type u) where meta : Option Meta kind : Ξ± deriving Inhabited instance [Repr Ξ±] : Repr (Spanned Ξ±) := ⟨fun n p => reprPrec n.kind p⟩ def Spanned.map (f : Ξ± β†’ Ξ²) : Spanned Ξ± β†’ Spanned Ξ² | ⟨m, a⟩ => ⟨m, f a⟩ def Spanned.dummy (a : Ξ±) : Spanned Ξ± := ⟨none, a⟩ local prefix:max "#" => Spanned namespace AST3 open Lean3 (Proj) inductive BinderName | ident : Name β†’ BinderName | Β«_Β» : BinderName instance : Repr BinderName where reprPrec | BinderName.ident n, _ => n.toString | BinderName.Β«_Β», _ => "_" inductive VariableKind | Β«variableΒ» | Β«parameterΒ» deriving Inhabited instance : Repr VariableKind where reprPrec | VariableKind.Β«variableΒ», _ => "variable" | VariableKind.Β«parameterΒ», _ => "parameter" inductive AxiomKind | Β«axiomΒ» | Β«constantΒ» deriving Inhabited instance : Repr AxiomKind where reprPrec | AxiomKind.Β«axiomΒ», _ => "axiom" | AxiomKind.Β«constantΒ», _ => "constant" inductive DeclKind | Β«defΒ» | Β«theoremΒ» | Β«abbrevΒ» | Β«exampleΒ» | Β«instanceΒ» deriving Inhabited instance : Repr DeclKind where reprPrec | DeclKind.def, _ => "def" | DeclKind.theorem, _ => "theorem" | DeclKind.abbrev, _ => "abbreviation" | DeclKind.example, _ => "example" | DeclKind.instance, _ => "instance" def LocalReserve := Bool Γ— Bool instance : Repr LocalReserve := ⟨fun ⟨loc, res⟩ _ => ((if loc then "local " else "") ++ (if res then "reserve " else "") : String)⟩ inductive MixfixKind | Β«infixΒ» | Β«infixlΒ» | Β«infixrΒ» | Β«postfixΒ» | Β«prefixΒ» deriving Inhabited, BEq, Hashable instance : Repr MixfixKind where reprPrec | MixfixKind.infix, _ => "infix" | MixfixKind.infixl, _ => "infixl" | MixfixKind.infixr, _ => "infixr" | MixfixKind.postfix, _ => "postfix" | MixfixKind.prefix, _ => "prefix" instance : ToString MixfixKind where toString m := toString (repr m) inductive InferKind | implicit | relaxedImplicit | none instance : Inhabited InferKind := ⟨InferKind.relaxedImplicit⟩ instance : ToString InferKind where toString | InferKind.implicit => "[]" | InferKind.relaxedImplicit => "{}" | InferKind.none => "( )" instance : Repr InferKind where reprPrec ik _ := toString ik def InferKind.optRepr : Option InferKind β†’ Format | Option.none => "" | some ik => " " ++ repr ik inductive Symbol | quoted : String β†’ Symbol | ident : String β†’ Symbol deriving Inhabited instance : Repr Symbol where reprPrec | Symbol.quoted s, _ => ("`" ++ s ++ "`" : String) | Symbol.ident n, _ => n def Symbol.trim : Symbol β†’ String | Symbol.ident s => s | Symbol.quoted s => s.trim def Symbol.toString : Symbol β†’ String | Symbol.ident s => s | Symbol.quoted s => s inductive Choice | one : Name β†’ Choice | many : Array Name β†’ Choice deriving Inhabited def Choice.name : Choice β†’ Name | Choice.one n => n | Choice.many #[n] => n | _ => default instance : Repr Choice where reprPrec | Choice.one n, _ => n.toString | Choice.many ns, _ => (Format.joinSep (ns.toList.map (Β·.toString)) "/").sbracket inductive OptionVal | bool : Bool β†’ OptionVal | str : String β†’ OptionVal | nat : Nat β†’ OptionVal | decimal : Nat β†’ Nat β†’ OptionVal instance : Repr OptionVal where reprPrec | OptionVal.bool n, _ => repr n | OptionVal.nat n, _ => repr n | OptionVal.str n, _ => repr n | OptionVal.decimal n d, _ => repr n ++ "/" ++ repr d inductive Level | Β«_Β» : Level | nat : Nat β†’ Level | add : #Level β†’ #Nat β†’ Level | max : Array #Level β†’ Level | imax : Array #Level β†’ Level | param : Name β†’ Level | paren : #Level β†’ Level deriving Inhabited def Levels := Option (Array #Level) def LevelDecl := Option (Array #Name) instance : Inhabited Levels := ⟨none⟩ instance : Inhabited LevelDecl := ⟨none⟩ -- These are used to break up the huge mutual recursion below abbrev NotationId := Nat abbrev CommandId := Nat section set_option hygiene false local notation "Binders" => Array #Binder mutual inductive Default | Β«:=Β» : #Expr β†’ Default | Β«.Β» : #Name β†’ Default inductive Binder | Β«notationΒ» : NotationId β†’ Binder | binder : BinderInfo β†’ Option (Array #BinderName) β†’ Binders β†’ Option #Expr β†’ Option Default β†’ Binder | collection : BinderInfo β†’ Array #BinderName β†’ (nota : Name) β†’ (rhs : #Expr) β†’ Binder deriving Inhabited inductive LambdaBinder | reg : Binder β†’ LambdaBinder | «⟨⟩» : Array #Expr β†’ LambdaBinder deriving Inhabited inductive LetDecl | Β«notationΒ» : NotationId β†’ LetDecl | var : #BinderName β†’ Binders β†’ Option #Expr β†’ #Expr β†’ LetDecl | pat : #Expr β†’ #Expr β†’ LetDecl deriving Inhabited inductive Arg | expr : Expr β†’ Arg | exprs : Array #Expr β†’ Arg | binder : Binder β†’ Arg | binders : Binders β†’ Arg deriving Inhabited inductive Expr | Β«...Β» : Expr | Β«sorryΒ» : Expr | Β«_Β» : Expr | Β«()Β» : Expr | Β«{}Β» : Expr | ident : Name β†’ Expr | const : #Name β†’ Levels β†’ Array Name β†’ Expr | nat : Nat β†’ Expr | decimal : Nat β†’ Nat β†’ Expr | string : String β†’ Expr | char : Char β†’ Expr | paren : #Expr β†’ Expr | sort (isType isStar : Bool) : Option #Level β†’ Expr | app : #Expr β†’ #Expr β†’ Expr | Β«funΒ» (isAssume : Bool) : Array #LambdaBinder β†’ #Expr β†’ Expr | Β«β†’Β» : #Expr β†’ #Expr β†’ Expr | Pi : Binders β†’ #Expr β†’ Expr | Β«showΒ» : #Expr β†’ #Proof β†’ Expr | Β«haveΒ» (suff : Bool) : Option #Name β†’ #Expr β†’ #Proof β†’ #Expr β†’ Expr | Β«.Β» (compact : Bool) : #Expr β†’ #Proj β†’ Expr | Β«ifΒ» : Option #Name β†’ #Expr β†’ #Expr β†’ #Expr β†’ Expr | Β«calcΒ» : Array (#Expr Γ— #Expr) β†’ Expr | Β«@Β» (Β«partialΒ» : Bool) : #Expr β†’ Expr | pattern : #Expr β†’ Expr | Β«`()Β» (lazy expr : Bool) : #Expr β†’ Expr | Β«%%Β» : #Expr β†’ Expr | Β«`[]Β» : Array #Tactic β†’ Expr | Β«`Β» (resolve : Bool) : Name β†’ Expr | «⟨⟩» : Array #Expr β†’ Expr | infix_fn : Choice β†’ Option #Expr β†’ Expr | Β«(,)Β» : Array #Expr β†’ Expr | Β«:Β» : #Expr β†’ #Expr β†’ Expr | hole : Array #Expr β†’ Expr | Β«#[]Β» : Array #Expr β†’ Expr | Β«byΒ» : #Tactic β†’ Expr | begin : Block β†’ Expr | Β«letΒ» : Array #LetDecl β†’ #Expr β†’ Expr | Β«matchΒ» : Array #Expr β†’ Option #Expr β†’ Array Arm β†’ Expr | Β«doΒ» (braces : Bool) : Array #DoElem β†’ Expr | Β«{,}Β» : Array #Expr β†’ Expr | subtype (setOf : Bool) : #Name β†’ Option #Expr β†’ #Expr β†’ Expr | sep : #Name β†’ #Expr β†’ #Expr β†’ Expr | setReplacement : #Expr β†’ Binders β†’ Expr | structInst (ty : Option #Name) (src : Option #Expr) (fields : Array (#Name Γ— #Expr)) (srcs : Array #Expr) (catchall : Bool) : Expr | atPat : #Name β†’ #Expr β†’ Expr | Β«.()Β» : #Expr β†’ Expr | Β«notationΒ» (n : Choice) : Array #Arg β†’ Expr | userNotation (n : Name) : Array #Param β†’ Expr deriving Inhabited inductive Arm | mk (lhs : Array #Expr) (rhs : #Expr) : Arm deriving Inhabited inductive DoElem | Β«letΒ» : #LetDecl β†’ DoElem | «←» : #Expr β†’ Option #Expr β†’ #Expr β†’ Option #Expr β†’ DoElem | eval : #Expr β†’ DoElem deriving Inhabited inductive Proof | Β«fromΒ» (Β«:=Β» : Bool) : #Expr β†’ Proof | block : Block β†’ Proof | Β«byΒ» : #Tactic β†’ Proof deriving Inhabited inductive Tactic | Β«;Β» : Array #Tactic β†’ Tactic | Β«<|>Β» : Array #Tactic β†’ Tactic | Β«[]Β» : Array #Tactic β†’ Tactic | block : Block β†’ Tactic | Β«byΒ» : #Tactic β†’ Tactic | exact_shortcut : #Expr β†’ Tactic | expr : #Expr β†’ Tactic | interactive (n : Name) : Array #Param β†’ Tactic deriving Inhabited inductive Block | mk (curly : Bool) (tacClass : Option #Name) (cfg : Option #Expr) (tacs : Array #Tactic) : Block deriving Inhabited inductive Param | parse : Lean3.Expr β†’ Array #VMCall β†’ Param | expr : #Expr β†’ Param | block : Block β†’ Param deriving Inhabited inductive VMCall | ident : Name β†’ VMCall | nat : Nat β†’ VMCall | token : String β†’ VMCall | pat : Expr β†’ VMCall | expr : Expr β†’ VMCall | binders : Binders β†’ VMCall | block : Block β†’ VMCall | Β«inductiveΒ» : CommandId β†’ VMCall | command : Option CommandId β†’ VMCall | withInput : Array #VMCall β†’ (bytesParsed : Nat) β†’ VMCall deriving Inhabited end end def Binders := Array #Binder instance : Inhabited Binders := ⟨#[]⟩ partial def Expr.unparen : Expr β†’ Expr | Expr.paren e => e.kind.unparen | e => e inductive AttrArg | eager : AttrArg | indices : Array #Nat β†’ AttrArg | keyValue : #String β†’ #String β†’ AttrArg | vmOverride : #Name β†’ Option #Name β†’ AttrArg | user : Lean3.Expr β†’ Array #VMCall β†’ AttrArg deriving Inhabited inductive Attribute | priority : #Expr β†’ Attribute | del (name : Name) : Attribute | add (name : Name) (arg : Option #AttrArg) : Attribute deriving Inhabited def Attributes := Array #Attribute instance : Inhabited Attributes := ⟨#[]⟩ inductive Precedence | nat : Nat β†’ Precedence | expr : #Expr β†’ Precedence deriving Inhabited def PrecSymbol := #Symbol Γ— Option #Precedence instance : Inhabited PrecSymbol := inferInstanceAs (Inhabited (_Γ—_)) inductive Action | prec : Precedence β†’ Action | prev : Action | Β«scopedΒ» : Option #Precedence β†’ Option (#Name Γ— #Expr) β†’ Action | fold (right : Bool) (prec : Option #Precedence) (sep : PrecSymbol) (Β«recΒ» : #Name Γ— #Name Γ— #Expr) (ini : Option #Expr) (term : Option PrecSymbol) : Action deriving Inhabited inductive Literal | nat : Nat β†’ Literal | var : #Name β†’ Option #Action β†’ Literal | sym : PrecSymbol β†’ Literal | binder : Option #Precedence β†’ Literal | binders : Option #Precedence β†’ Literal deriving Inhabited inductive Notation | Β«notationΒ» : Option #Name β†’ Array #Literal β†’ Option #Expr β†’ Notation | mixfix : MixfixKind β†’ Option #Name β†’ PrecSymbol β†’ Option #Expr β†’ Notation deriving Inhabited inductive Modifier | Β«privateΒ» : Modifier | Β«protectedΒ» : Modifier | Β«noncomputableΒ» : Modifier | meta : Modifier | Β«mutualΒ» : Modifier | doc : String β†’ Modifier | attr (Β«localΒ» compact : Bool) : Attributes β†’ Modifier deriving Inhabited def Modifiers := Array #Modifier instance : Inhabited Modifiers := ⟨#[]⟩ inductive DeclVal | expr : Expr β†’ DeclVal | eqns : Array Arm β†’ DeclVal deriving Inhabited structure Mutual (Ξ± : Type) := (attrs : Attributes) (name : #Name) (ty : #Expr) (vals : Array Ξ±) deriving Inhabited structure MutualHeader (Ξ± : Type) where (mods : Modifiers) (lvls : LevelDecl) (bis : Binders) (vals : Array (Mutual Ξ±)) deriving Inhabited structure Intro where (doc : Option String) (name : #Name) (ik : Option InferKind) (bis : Binders) (ty : Option #Expr) structure Rename := (Β«fromΒ» to : #Name) structure Parent where (Β«privateΒ» : Bool) (name : Option #Name) (expr : #Expr) (renames : Array Rename) structure Mk := (name : #Name) (ik : Option InferKind) inductive Field | binder : BinderInfo β†’ Array #Name β†’ Option InferKind β†’ Binders β†’ Option #Expr β†’ Option Default β†’ Field | Β«notationΒ» : Notation β†’ Field inductive OpenClause | explicit : Array #Name β†’ OpenClause | Β«renamingΒ» : Array Rename β†’ OpenClause | Β«hidingΒ» : Array #Name β†’ OpenClause structure Open := (tgt : #Name) (as : Option #Name) (clauses : Array #OpenClause) inductive HelpCmd | options : HelpCmd | commands : HelpCmd inductive PrintAttrCmd | recursor : PrintAttrCmd | unify : PrintAttrCmd | simp : PrintAttrCmd | congr : PrintAttrCmd | attr : Name β†’ PrintAttrCmd def PrintAttrCmd.toName : PrintAttrCmd β†’ Name | recursor => `recursor | unify => `unify | simp => `simp | congr => `congr | attr n => n inductive PrintCmd | str : String β†’ PrintCmd | raw : #Expr β†’ PrintCmd | options : PrintCmd | trust : PrintCmd | keyEquivalences : PrintCmd | Β«defΒ» : #Name β†’ PrintCmd | instances : #Name β†’ PrintCmd | classes : PrintCmd | attributes : PrintCmd | Β«prefixΒ» : #Name β†’ PrintCmd | aliases : PrintCmd | Β«axiomsΒ» : Option #Name β†’ PrintCmd | fields : #Name β†’ PrintCmd | Β«notationΒ» : Array #Name β†’ PrintCmd | Β«inductiveΒ» : #Name β†’ PrintCmd | attr : #PrintAttrCmd β†’ PrintCmd | token : #Name β†’ PrintCmd | ident : #Name β†’ PrintCmd inductive InductiveCmd | reg (Β«classΒ» : Bool) : Modifiers β†’ #Name β†’ LevelDecl β†’ Binders β†’ (ty : Option #Expr) β†’ Option Notation β†’ Array #Intro β†’ InductiveCmd | Β«mutualΒ» (Β«classΒ» : Bool) : Modifiers β†’ LevelDecl β†’ Binders β†’ Option Notation β†’ Array (Mutual #Intro) β†’ InductiveCmd inductive Command | initQuotient : Command | mdoc : String β†’ Command | Β«universeΒ» (var plural : Bool) : Array #Name β†’ Command | Β«namespaceΒ» : #Name β†’ Command | Β«sectionΒ» : Option #Name β†’ Command | Β«endΒ» : Option #Name β†’ Command | Β«variableΒ» : VariableKind β†’ (plural : Bool) β†’ Modifiers β†’ Binders β†’ Command | Β«axiomΒ» : AxiomKind β†’ Modifiers β†’ #Name β†’ LevelDecl β†’ Binders β†’ #Expr β†’ Command | Β«axiomsΒ» : AxiomKind β†’ Modifiers β†’ Binders β†’ Command | decl : DeclKind β†’ Modifiers β†’ Option #Name β†’ LevelDecl β†’ Binders β†’ (ty : Option #Expr) β†’ #DeclVal β†’ (uwf : Option #Expr) β†’ Command | mutualDecl : DeclKind β†’ Modifiers β†’ LevelDecl β†’ Binders β†’ Array (Mutual Arm) β†’ (uwf : Option #Expr) β†’ Command | Β«inductiveΒ» : InductiveCmd β†’ Command | Β«structureΒ» (Β«classΒ» : Bool) : Modifiers β†’ #Name β†’ LevelDecl β†’ Binders β†’ Array #Parent β†’ (ty : Option #Expr) β†’ Option #Mk β†’ Array #Field β†’ Command | Β«attributeΒ» (Β«localΒ» : Bool) : Modifiers β†’ Attributes β†’ Array #Name β†’ Command | Β«precedenceΒ» : #Symbol β†’ #Precedence β†’ Command | Β«notationΒ» : LocalReserve β†’ Attributes β†’ Notation β†’ Command | Β«openΒ» (Β«exportΒ» : Bool) : Array Open β†’ Command | Β«includeΒ» (pos : Bool) : Array #Name β†’ Command | Β«hideΒ» : Array #Name β†’ Command | Β«theoryΒ» : Modifiers β†’ Command | setOption : #Name β†’ #OptionVal β†’ Command | declareTrace : #Name β†’ Command | addKeyEquivalence : #Name β†’ #Name β†’ Command | runCmd : #Expr β†’ Command | check : #Expr β†’ Command | reduce (whnf : Bool) : #Expr β†’ Command | eval : #Expr β†’ Command | unify : #Expr β†’ #Expr β†’ Command | compile : #Name β†’ Command | help : HelpCmd β†’ Command | print : PrintCmd β†’ Command | userCommand (n : Name) : Modifiers β†’ Array #Param β†’ Command deriving Inhabited def spaced (f : Ξ± β†’ Format) (mods : Array Ξ±) : Format := (Format.joinSep (mods.toList.map f) Format.line).fill def spacedBefore (f : Ξ± β†’ Format) (mods : Array Ξ±) : Format := (Format.join (mods.toList.map fun m => Format.line ++ f m)).fill def spacedAfter (f : Ξ± β†’ Format) (mods : Array Ξ±) : Format := (Format.join (mods.toList.map fun m => f m ++ Format.line)).fill def suffix (pl : Bool) := if pl then "s " else " " partial def Level_repr : Level β†’ (prec : _ := 0) β†’ Format | Level.Β«_Β», _ => "_" | Level.nat n, _ => repr n | Level.add l n, p => Format.parenPrec 10 p $ Level_repr l.kind 10 ++ "+" ++ repr n | Level.imax ls, p => Format.parenPrec max_prec p $ "imax" ++ Format.join (ls.toList.map fun l => " " ++ Level_repr l.kind max_prec) | Level.max ls, p => Format.parenPrec max_prec p $ "max" ++ Format.join (ls.toList.map fun l => " " ++ Level_repr l.kind max_prec) | Level.param u, _ => u.toString | Level.paren l, _ => Level_repr l.kind instance : Repr Level := ⟨@Level_repr⟩ instance : Repr Levels where reprPrec | none, _ => "" | some us, _ => (Format.joinSep (us.toList.map repr) ", ").bracket ".{" "}" instance : Repr LevelDecl where reprPrec | none, _ => "" | some us, _ => (Format.joinSep (us.toList.map fun u => u.kind.toString) ", ").bracket ".{" "}" mutual partial def Precedence_repr : Precedence β†’ Format | Precedence.nat n => repr n | Precedence.expr e => Expr_repr e.kind max_prec partial def optTy : Option #Expr β†’ Format | none => "" | some e => " :" ++ Format.line ++ Expr_repr e.kind partial def Default_repr : Option Default β†’ Format | none => "" | some (Default.Β«:=Β» e) => " :=" ++ Format.line ++ Expr_repr e.kind | some (Default.Β«.Β» n) => " ." ++ Format.line ++ (n.kind.toString : Format) partial def Binder_repr : Binder β†’ (paren :_:= true) β†’ Format | Binder.binder bi none _ e dflt, paren => bi.bracket paren $ (match e with | none => "⬝" | some e => Expr_repr e.kind) ++ Default_repr dflt | Binder.binder bi (some vars) bis ty dflt, paren => bi.bracket paren $ spaced repr vars ++ Binders_repr bis ++ optTy ty ++ Default_repr dflt | Binder.collection bi vars n rhs, paren => bi.bracket paren $ spaced repr vars ++ " " ++ n.toString ++ " " ++ Expr_repr rhs.kind | Binder.notation n, _ => Format.paren s!"notation <{show Nat from n}>" partial def Binders_repr (bis : Binders) (paren := true) : Format := let paren := paren || bis.size β‰  1 spacedBefore (fun m => Binder_repr m.kind paren) bis partial def LambdaBinder_repr : LambdaBinder β†’ (paren :_:= true) β†’ Format | LambdaBinder.reg bi, paren => Binder_repr bi paren | LambdaBinder.«⟨⟩» args, _ => (Format.joinSep (args.toList.map fun e => Expr_repr e.kind) ", ").bracket "⟨" "⟩" partial def LambdaBinders_repr (bis : Array #LambdaBinder) (paren := true) : Format := let paren := paren || bis.size β‰  1 spacedBefore (fun m => LambdaBinder_repr m.kind paren) bis partial def LetDecl_repr : LetDecl β†’ Format | LetDecl.var v bis ty val => repr v ++ Binders_repr bis ++ optTy ty ++ " := " ++ Expr_repr val.kind | LetDecl.pat pat val => Expr_repr pat.kind ++ " := " ++ Expr_repr val.kind | LetDecl.notation n => s!"notation <{show Nat from n}>" partial def Expr_repr : Expr β†’ (prec : _ := 0) β†’ Format | Expr.Β«...Β», _ => "..." | Expr.sorry, _ => "sorry" | Expr.Β«_Β», _ => "_" | Expr.Β«()Β», _ => "()" | Expr.Β«{}Β», _ => "{}" | Expr.ident n, _ => n.toString | Expr.const n l cs, _ => n.kind.toString ++ cs.toList.toString ++ repr l | Expr.nat n, _ => repr n | Expr.decimal n d, _ => repr n ++ "/" ++ repr d | Expr.string s, _ => repr s | Expr.char c, _ => repr c | Expr.paren e, p => Expr_repr e.kind p | Expr.sort ty st u, p => Format.parenPrec max_prec p $ (if ty then "Type" else "Sort") ++ if st then ("*" : Format) else match u with | none => "" | some u => " " ++ Level_repr u.kind max_prec | Expr.Β«β†’Β» lhs rhs, p => Format.parenPrec 25 p $ Expr_repr lhs.kind 25 ++ " β†’ " ++ Expr_repr rhs.kind 24 | Expr.fun as bis e, p => Format.parenPrec max_prec p $ ((if as then "assume" else "Ξ»" : Format) ++ (match as, bis with | true, #[⟨_, .reg (.binder _ none _ (some ty) _)⟩] => ": " ++ Expr_repr ty.kind | _, _ => LambdaBinders_repr bis false) ++ ",").group ++ Format.line ++ Expr_repr e.kind | Expr.Pi bis e, p => Format.parenPrec max_prec p $ ("βˆ€" ++ Binders_repr bis false ++ ",").group ++ Format.line ++ Expr_repr e.kind | Expr.app f x, p => Format.parenPrec max_prec p $ (Expr_repr f.kind 1023 ++ Format.line ++ Expr_repr x.kind max_prec).fill | Expr.show t pr, p => Format.parenPrec 1000 p $ "show " ++ Expr_repr t.kind ++ Proof_repr' pr.kind | Expr.have suff h t pr e, p => Format.parenPrec 1000 p $ (if suff then "suffices " else "have ") ++ (match h with | none => "" | some h => h.kind.toString ++ " : ") ++ Expr_repr t.kind ++ Proof_repr' pr.kind ++ "," ++ Format.line ++ Expr_repr e.kind | Expr.Β«.Β» compact e pr, _ => Expr_repr e.kind max_prec ++ (if compact then "." else "^.") ++ repr pr.kind | Expr.if h c t e, p => Format.parenPrec 1000 p $ "if " ++ (match h with | none => "" | some h => h.kind.toString ++ " : ") ++ Expr_repr c.kind ++ " then " ++ Expr_repr t.kind ++ " else " ++ Expr_repr e.kind | Expr.calc args, p => Format.parenPrec 1000 p $ "calc" ++ (Format.join $ args.toList.map fun (lhs, rhs) => Format.line ++ Expr_repr lhs.kind ++ " : " ++ Expr_repr rhs.kind).nest 2 | Expr.Β«@Β» part e, _ => (if part then "@@" else "@") ++ Expr_repr e.kind max_prec | Expr.pattern e, p => Format.parenPrec 1000 p $ "(: " ++ Expr_repr e.kind ++ " :)" | Expr.Β«`()Β» lazy expr e, p => Format.parenPrec 1000 p $ (if expr then "`(" else if lazy then "```(" else "``(") ++ (match e.kind with | Expr.Β«:Β» e ty => Expr_repr e.kind ++ " : " ++ Expr_repr ty.kind | _ => Expr_repr e.kind : Format) ++ ")" | Expr.Β«%%Β» e, p => Format.parenPrec 1000 p $ "%%" ++ Expr_repr e.kind | Expr.Β«`[]Β» tacs, p => Format.parenPrec 1000 p $ (Format.joinSep (tacs.toList.map fun t => Tactic_repr t.kind) ", ").bracket "`[" "]" | Expr.Β«`Β» res n, p => Format.parenPrec 1000 p $ (if res then "``" else "`" : Format) ++ n.toString | Expr.«⟨⟩» es, _ => (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) ", ").bracket "⟨" "⟩" | Expr.infix_fn c e, p => Format.parenPrec 1000 p $ "(" ++ repr c ++ (match e with | none => "" | some e => " " ++ Expr_repr e.kind) ++ ")" | Expr.Β«(,)Β» es, _ => (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) ", ").paren | Expr.Β«.()Β» e, _ => "." ++ Expr_repr e.kind max_prec | Expr.Β«:Β» e ty, _ => "(" ++ Expr_repr e.kind ++ " : " ++ Expr_repr ty.kind ++ ")" | Expr.hole es, p => Format.parenPrec 1000 p $ (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) ", ").bracket "{! " " !}" | Expr.Β«#[]Β» es, p => Format.parenPrec 1000 p $ (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) ", ").bracket "#[" "]" | Expr.by tac, p => Format.parenPrec 1000 p $ "by " ++ Tactic_repr tac.kind | Expr.begin tacs, p => Format.parenPrec 1000 p $ Block_repr tacs | Expr.let bis e, p => Format.parenPrec 1000 p $ ("let " ++ (("," ++ Format.line).joinSep (bis.toList.map fun bi => LetDecl_repr bi.kind)).nest 4 ++ " in").group ++ Format.line ++ Expr_repr e.kind | Expr.match xs ty eqns, _ => "match " ++ Format.joinSep (xs.toList.map fun x => Expr_repr x.kind) ", " ++ optTy ty ++ " with" ++ (if eqns.isEmpty then " end" else Arms_repr eqns ++ Format.line ++ "end" : Format) | Expr.do braces els, p => Format.parenPrec 1000 p $ let s := Format.line ++ (("," ++ Format.line).joinSep (els.toList.map fun el => DoElem_repr el.kind)).nest 2 if braces then "do" ++ s else "do {" ++ s ++ " }" | Expr.Β«{,}Β» es, _ => (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) ", ").bracket "{" "}" | Expr.subtype setOf x ty p, _ => "{" ++ x.kind.toString ++ optTy ty ++ (if setOf then " | " else " // ") ++ Expr_repr p.kind ++ "}" | Expr.sep x ty p, _ => "{" ++ x.kind.toString ++ " ∈ " ++ Expr_repr ty.kind ++ " | " ++ Expr_repr p.kind ++ "}" | Expr.setReplacement e bis, _ => "{(" ++ Expr_repr e.kind ++ ") |" ++ Binders_repr bis false ++ "}" | Expr.structInst S src flds srcs catchall, _ => Format.nest 2 $ Format.group $ "{ " ++ (match S with | none => "" | some S => S.kind.toString ++ " ." ++ Format.line : Format) ++ (match src with | none => "" | some s => Expr_repr s.kind ++ " with" ++ Format.line : Format) ++ (("," ++ Format.line).joinSep $ flds.toList.map (fun (i, s) => i.kind.toString ++ " := " ++ Expr_repr s.kind) ++ srcs.toList.map (fun s => ".." ++ Expr_repr s.kind) ++ if catchall then [(".." : Format)] else []) ++ " }" | Expr.atPat lhs rhs, p => Format.parenPrec 1000 p $ lhs.kind.toString ++ "@" ++ Expr_repr rhs.kind max_prec | Expr.notation n args, _ => repr n ++ (Format.joinSep (args.toList.map fun e => Arg_repr e.kind) ("," ++ Format.line)).paren | Expr.userNotation n args, p => Format.parenPrec 1000 p $ n.toString ++ Format.join (args.toList.map fun a => " " ++ Param_repr a.kind) partial def Arg_repr : Arg β†’ Format | Arg.expr e => Expr_repr e | Arg.exprs es => (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) ", ").sbracket | Arg.binder bi => Binder_repr bi | Arg.binders bis => spaced (fun m => Binder_repr m.kind) bis partial def Arm_repr : Arm β†’ Format | ⟨lhs, rhs⟩ => "\n| " ++ Format.joinSep (lhs.toList.map fun e => Expr_repr e.kind) ", " ++ " := " ++ Expr_repr rhs.kind partial def DoElem_repr : DoElem β†’ Format | DoElem.let bi => "let " ++ LetDecl_repr bi.kind | DoElem.«←» lhs ty rhs els => Expr_repr lhs.kind ++ optTy ty ++ " ← " ++ Expr_repr rhs.kind ++ match els with | none => "" | some e => " | " ++ Expr_repr e.kind | DoElem.eval e => Expr_repr e.kind partial def Arms_repr (arms : Array Arm) : Format := if arms.isEmpty then "." else Format.join $ arms.toList.map Arm_repr partial def Proof_repr' : Proof β†’ Format | Proof.from true e => " := " ++ Expr_repr e.kind | p => ", " ++ Proof_repr p partial def Proof_repr : Proof β†’ Format | Proof.from _ e => "from " ++ Expr_repr e.kind | Proof.block tacs => Block_repr tacs | Proof.by tac => "by " ++ Tactic_repr tac.kind partial def Tactic_repr : Tactic β†’ Format | Tactic.Β«;Β» tacs => Format.joinSep (tacs.toList.map fun t => Tactic_repr t.kind) "; " | Tactic.Β«<|>Β» tacs => Format.joinSep (tacs.toList.map fun t => Tactic_repr t.kind) " <|> " | Tactic.Β«[]Β» tacs => (Format.joinSep (tacs.toList.map fun t => Tactic_repr t.kind) ", ").sbracket | Tactic.block tacs => Block_repr tacs | Tactic.by tac => "by " ++ Tactic_repr tac.kind | Tactic.exact_shortcut e => Expr_repr e.kind | Tactic.expr tac => Expr_repr tac.kind | Tactic.interactive n args => n.toString ++ Format.join (args.toList.map fun a => " " ++ Param_repr a.kind) partial def Block_repr : Block β†’ Format | ⟨curly, cl, cfg, tacs⟩ => let s₁ := match cl with | none => "" | some cl => " [" ++ cl.kind.toString ++ "]" let sβ‚‚ : Format := match cfg with | none => "" | some e => " with " ++ Expr_repr e.kind ++ "," let s₃ := ("," ++ Format.line).joinSep (tacs.toList.map fun t => Tactic_repr t.kind) if curly then ("{" ++ s₁ ++ sβ‚‚ ++ (if cl.isSome || cfg.isSome then Format.line else " ") ++ s₃ ++ " }").nest 2 else ("begin" ++ s₁ ++ sβ‚‚ ++ Format.line ++ s₃).nest 2 ++ Format.line ++ "end" partial def Param_repr : Param β†’ Format | Param.parse _ calls => Format.sbracket $ (", ":Format).joinSep $ calls.toList.map fun c => VMCall_repr c.kind | Param.expr e => Expr_repr e.kind | Param.block e => Block_repr e partial def VMCall_repr : VMCall β†’ Format | VMCall.ident n => "ident " ++ (n.toString:Format) | VMCall.nat n => repr n | VMCall.token tk => repr tk | VMCall.pat e => "pat " ++ Expr_repr e | VMCall.expr e => "expr " ++ Expr_repr e | VMCall.binders bis => "binders" ++ Binders_repr bis | VMCall.block bl => Block_repr bl | VMCall.inductive c => s!"inductive <{show Nat from c}>" | VMCall.command c => s!"command <{repr $ show Option Nat from c}>" | VMCall.withInput calls _ => Format.sbracket $ (", ":Format).joinSep $ calls.toList.map fun c => VMCall_repr c.kind partial def optPrec_repr : Option #Precedence β†’ Format | none => "" | some p => ":" ++ Precedence_repr p.kind partial def PrecSymbol_repr : PrecSymbol β†’ Format | (sym, prec) => repr sym ++ optPrec_repr prec partial def Action_repr : Action β†’ Format | Action.prec p => Precedence_repr p | Action.prev => "prev" | Action.scoped p none => "scoped" ++ optPrec_repr p | Action.scoped p (some (x, e)) => "(scoped" ++ optPrec_repr p ++ " " ++ x.kind.toString ++ ", " ++ Expr_repr e.kind ++ ")" | Action.fold r p sep (x, y, Β«recΒ») ini term => "(fold" ++ (if r then "r" else "l") ++ optPrec_repr p ++ " " ++ PrecSymbol_repr sep ++ " (" ++ x.kind.toString ++ " " ++ y.kind.toString ++ ", " ++ Expr_repr rec.kind ++ ")" ++ (match ini with | none => "" | some ini => " " ++ Expr_repr ini.kind) ++ (match term with | none => "" | some term => " " ++ PrecSymbol_repr term) ++ ")" partial def Literal_repr : Literal β†’ Format | Literal.nat n => repr n | Literal.sym sym => PrecSymbol_repr sym | Literal.binder prec => "binder" ++ optPrec_repr prec | Literal.binders prec => "binders" ++ optPrec_repr prec | Literal.var v a => (v.kind.toString : Format) ++ match a with | none => "" | some a => ":" ++ Action_repr a.kind end instance : Repr Precedence := ⟨fun n _ => Precedence_repr n⟩ instance : Repr Binder := ⟨fun n _ => Binder_repr n⟩ instance : Repr Binders := ⟨fun n _ => Binders_repr n⟩ instance : Repr Expr := ⟨fun n _ => Expr_repr n⟩ instance : Repr Arg := ⟨fun n _ => Arg_repr n⟩ instance : Repr Arm := ⟨fun n _ => Arm_repr n⟩ instance : Repr DoElem := ⟨fun n _ => DoElem_repr n⟩ instance : Repr Proof := ⟨fun n _ => Proof_repr n⟩ instance : Repr Tactic := ⟨fun n _ => Tactic_repr n⟩ instance : Repr Block := ⟨fun n _ => Block_repr n⟩ instance : Repr Param := ⟨fun n _ => Param_repr n⟩ instance : Repr VMCall := ⟨fun n _ => VMCall_repr n⟩ instance : Repr PrecSymbol := ⟨fun n _ => PrecSymbol_repr n⟩ instance : Repr Action := ⟨fun n _ => Action_repr n⟩ instance : Repr Literal := ⟨fun n _ => Literal_repr n⟩ instance : Repr AttrArg where reprPrec | AttrArg.eager, _ => "!" | AttrArg.indices ns, _ => spacedBefore repr ns | AttrArg.keyValue a b, _ => " " ++ repr a ++ " " ++ repr b | AttrArg.vmOverride a b, _ => " " ++ repr a ++ (match b with | none => "" | some b => " " ++ repr b : Format) | AttrArg.user _ e, _ => repr e instance : Repr Attribute where reprPrec | Attribute.priority e, _ => "priority " ++ Expr_repr e.kind | Attribute.del n, _ => ("-":Format) ++ n.toString | Attribute.add n arg, _ => n.toString ++ (match arg with | none => "" | some arg => " " ++ repr arg : Format) instance : Repr Attributes := ⟨fun attrs _ => (Format.joinSep (attrs.toList.map repr) ", ").sbracket⟩ def Notation_repr : Notation β†’ (attrs : Attributes := #[]) β†’ Format | Notation.mixfix mk name sym val, attrs => repr mk ++ (if attrs.isEmpty then "" else " " ++ repr attrs : Format) ++ (match name with | none => "" | some n => f!" (name := {repr n})") ++ " " ++ PrecSymbol_repr sym ++ (match val with | none => "" | some e => " := " ++ Expr_repr e.kind) | Notation.notation name lits val, attrs => "notation" ++ (if attrs.isEmpty then "" else " " ++ repr attrs : Format) ++ (match name with | none => "" | some n => f!" (name := {repr n})") ++ spacedBefore (fun n => Literal_repr n.kind) lits ++ (match val with | none => "" | some e => " := " ++ Expr_repr e.kind) instance : Repr Notation := ⟨fun n _ => Notation_repr n⟩ instance : Repr DeclVal where reprPrec | DeclVal.expr n, _ => " :=" ++ Format.line ++ repr n | DeclVal.eqns arms, _ => Format.join (arms.toList.map repr) instance : Repr Modifier where reprPrec | Modifier.private, _ => "private" | Modifier.protected, _ => "protected" | Modifier.noncomputable, _ => "noncomputable" | Modifier.meta, _ => "meta" | Modifier.mutual, _ => "mutual" | Modifier.doc s, _ => ("/--" ++ s ++ "-/" : String) | Modifier.attr l c attrs, _ => (if l then "local " else "") ++ (if c then "@" else "attribute ") ++ repr attrs def Modifiers_repr : Modifiers β†’ Format := spacedAfter repr instance : Repr Modifiers := ⟨fun n _ => Modifiers_repr n⟩ instance : Repr Intro where reprPrec | ⟨doc, name, ik, bis, ty⟩, _ => (match doc with | none => "" | some doc => "\n/--" ++ doc ++ "-/") ++ "\n| " ++ name.kind.toString ++ InferKind.optRepr ik ++ repr bis ++ optTy ty def Intros_repr (arms : Array #Intro) : Format := Format.join $ arms.toList.map repr def Mutual_repr (f : Array Ξ± β†’ Format) : Mutual Ξ± β†’ Format | ⟨attr, n, ty, vals⟩ => "with " ++ repr attr ++ " " ++ n.kind.toString ++ " : " ++ Expr_repr ty.kind ++ f vals instance : Repr Mk where reprPrec | ⟨mk, ik⟩, _ => mk.kind.toString ++ InferKind.optRepr ik instance : Repr Rename where reprPrec | ⟨«fromΒ», to⟩, _ => (Β«fromΒ».kind.toString ++ "β†’" ++ to.kind.toString : String) instance : Repr Parent where reprPrec | ⟨priv, n, ty, rens⟩, _ => (if priv then "private " else "") ++ (match n with | none => "" | some n => n.kind.toString ++ " : ") ++ repr ty ++ if rens.isEmpty then ("":Format) else "renaming" ++ spacedBefore repr rens instance : Repr Field where reprPrec | Field.binder bi vars ik bis ty dflt, _ => bi.bracket true $ spaced (fun v => v.kind.toString) vars ++ InferKind.optRepr ik ++ Binders_repr bis ++ optTy ty ++ Default_repr dflt | Field.notation n, _ => (repr n).paren instance : Repr OpenClause where reprPrec | OpenClause.explicit ns, _ => spaced (fun n => n.kind.toString) ns | OpenClause.renaming rens, _ => "renaming" ++ spacedBefore repr rens | OpenClause.hiding ns, _ => "hiding" ++ spacedBefore (fun n => n.kind.toString) ns instance : Repr Open where reprPrec | ⟨tgt, as, cls⟩, _ => tgt.kind.toString ++ (match as with | none => "" | some as => " as " ++ as.kind.toString) ++ spacedBefore (fun i => (repr i).paren) cls instance : Repr HelpCmd where reprPrec | HelpCmd.options, _ => "options" | HelpCmd.commands, _ => "commands" instance : Repr PrintCmd where reprPrec c _ := match c with | PrintCmd.str n => repr n | PrintCmd.raw e => "raw " ++ (repr e).nest 2 | PrintCmd.options => "options" | PrintCmd.trust => "trust" | PrintCmd.keyEquivalences => "key_equivalences" | PrintCmd.def n => "def " ++ repr n | PrintCmd.instances n => ("instances " : Format) ++ n.kind.toString | PrintCmd.classes => "classes" | PrintCmd.attributes => "attributes" | PrintCmd.prefix n => ("prefix " : Format) ++ n.kind.toString | PrintCmd.aliases => "aliases" | PrintCmd.axioms n => ("axioms" : Format) ++ (match n with | none => "" | some n => " " ++ n.kind.toString : String) | PrintCmd.fields n => ("fields " : Format) ++ n.kind.toString | PrintCmd.notation ns => ("notation" : Format) ++ spacedBefore (fun n => n.kind.toString) ns | PrintCmd.inductive n => ("inductive " : Format) ++ n.kind.toString | PrintCmd.attr n => (n.kind.toName.toString : Format).sbracket | PrintCmd.token n => n.kind.toString | PrintCmd.ident n => n.kind.toString instance : Repr InductiveCmd where reprPrec c _ := match c with | InductiveCmd.reg cl mods n us bis ty nota intros => repr mods ++ (if cl then "class " else "") ++ "inductive " ++ n.kind.toString ++ repr us ++ repr bis ++ optTy ty ++ (match nota with | none => "" | some n => "\n" ++ repr n) ++ Intros_repr intros | InductiveCmd.mutual cl mods us bis nota inds => repr mods ++ (if cl then "class " else "") ++ "inductive " ++ repr us ++ Format.joinSep (inds.toList.map fun m => m.name.kind.toString) ", " ++ repr bis ++ (match nota with | none => "" | some n => "\n" ++ repr n) ++ Format.join (inds.toList.map (Mutual_repr Intros_repr)) instance : Repr Command where reprPrec c _ := match c with | Command.initQuotient => "init_quotient" | Command.mdoc s => ("/-!" ++ s ++ "-/" : String) | Command.Β«universeΒ» var pl ns => "universe" ++ (if var then " variable" else "") ++ suffix pl ++ Format.joinSep (ns.toList.map fun a => a.kind.toString) " " | Command.Β«namespaceΒ» n => ("namespace ":Format) ++ n.kind.toString | Command.Β«sectionΒ» (some n) => ("section ":Format) ++ n.kind.toString | Command.Β«sectionΒ» none => "section" | Command.Β«endΒ» (some n) => ("end ":Format) ++ n.kind.toString | Command.Β«endΒ» none => "end" | Command.Β«variableΒ» vk plural mods bis => repr mods ++ repr vk ++ (if plural then "s" else "") ++ Binders_repr bis plural | Command.axiom ak mods n us bis ty => repr mods ++ repr ak ++ " " ++ n.kind.toString ++ repr us ++ repr bis ++ optTy ty | Command.axioms ak mods bis => repr mods ++ repr ak ++ "s" ++ repr bis | Command.decl dk mods n us bis ty val uwf => repr mods ++ (repr dk ++ (match n with | none => "" | some n => " " ++ n.kind.toString : String) ++ repr us ++ repr bis ++ optTy ty).group.nest 2 ++ repr val.kind ++ (match uwf with | none => "" | some e => "\nusing_well_founded " ++ (repr e).nest 2) | Command.mutualDecl dk mods us bis arms uwf => repr mods ++ repr dk ++ " " ++ repr us ++ Format.joinSep (arms.toList.map fun m => m.name.kind.toString) ", " ++ repr bis ++ Format.join (arms.toList.map (Mutual_repr Arms_repr)) ++ (match uwf with | none => "" | some e => "\nusing_well_founded " ++ (repr e).nest 2) | Command.inductive ind => repr ind | Command.structure cl mods n us bis exts ty mk flds => repr mods ++ (if cl then "class " else "structure ") ++ n.kind.toString ++ repr us ++ repr bis ++ (if exts.isEmpty then ("":Format) else "extends " ++ ((", ":Format).joinSep $ exts.toList.map repr)) ++ optTy ty ++ if mk.isNone && flds.isEmpty then ("":Format) else " :=" ++ (match mk with | none => "" | some mk => " " ++ repr mk ++ if flds.isEmpty then "" else " ::" : Format) ++ ((Format.join $ flds.toList.map fun f => Format.line ++ repr f).group).nest 2 | Command.attribute loc mods attrs ns => repr mods ++ (if loc then "local " else "") ++ "attribute" ++ (if attrs.isEmpty then "" else " " ++ repr attrs : Format) ++ spacedBefore (fun n => n.kind.toString) ns | Command.precedence sym prec => "precedence " ++ repr sym ++ ":" ++ repr prec | Command.notation loc attrs n => repr loc ++ Notation_repr n attrs | Command.open exp ops => (if exp then "export" else "open") ++ spacedBefore repr ops | Command.include pos ops => (if pos then "include" else "omit") ++ spacedBefore (fun n => n.kind.toString) ops | Command.hide ops => "hide" ++ spacedBefore (fun n => n.kind.toString) ops | Command.theory mods => repr mods ++ "theory" | Command.setOption n val => "set_option " ++ n.kind.toString ++ " " ++ repr val | Command.declareTrace n => ("declare_trace " : Format) ++ n.kind.toString | Command.addKeyEquivalence a b => ("add_key_equivalence " : Format) ++ a.kind.toString ++ " " ++ b.kind.toString | Command.runCmd e => "run_cmd " ++ (repr e).nest 2 | Command.check e => "#check " ++ (repr e).nest 2 | Command.reduce whnf e => "#reduce " ++ (if whnf then "[whnf] " else "") ++ (repr e).nest 2 | Command.eval e => "#eval " ++ (repr e).nest 2 | Command.unify e₁ eβ‚‚ => "#unify " ++ (repr e₁ ++ ", " ++ repr eβ‚‚).nest 2 | Command.compile n => ("#compile ":Format) ++ n.kind.toString | Command.help n => "#help " ++ repr n | Command.print n => "#print " ++ repr n | Command.userCommand n mods args => repr mods ++ n.toString ++ Format.join (args.toList.map fun a => " " ++ Param_repr a.kind) def Notation.name (sp : Char) (f : PrecSymbol β†’ String) (withTerm : Bool) (start : String) : Notation β†’ Name | Notation.notation (some name) .. | Notation.mixfix _ (some name) .. => name.kind | Notation.notation none lits _ => Id.run do let mut s := start for ⟨_, lit⟩ in lits do match lit with | Literal.nat n => s := s ++ toString n | Literal.sym tk => s := s ++ f tk | Literal.var _ none => s := s.push sp | Literal.var _ (some ⟨_, Action.prec _⟩) => s := s.push sp | Literal.var _ (some ⟨_, Action.prev⟩) => s := s.push sp | Literal.var _ (some ⟨_, Action.scoped _ _⟩) => s := s.push sp | Literal.var _ (some ⟨_, Action.fold _ _ sep _ _ term⟩) => s := s.push sp ++ f sep if withTerm then if let some term := term then s := s ++ f term | Literal.binder _ => s := s.push sp | Literal.binders _ => s := s.push sp Name.mkSimple s | Notation.mixfix mk none tk _ => Name.mkSimple <| match mk with | MixfixKind.infix => start.push sp ++ (f tk).push sp | MixfixKind.infixl => start.push sp ++ (f tk).push sp | MixfixKind.infixr => start.push sp ++ (f tk).push sp | MixfixKind.postfix => start.push sp ++ f tk | MixfixKind.prefix => start ++ (f tk).push sp def Notation.name3 := Notation.name ' ' (Β·.1.kind.trim) true "expr" def Notation.name4 := Notation.name '_' (Β·.1.kind.trim) false "term" def Attributes.hasToAdditive (attrs : Attributes) : Bool := attrs.any (Β· matches ⟨_, .add `to_additive _⟩) def Modifiers.hasToAdditive (mods : Modifiers) : Bool := mods.any fun | ⟨_, .attr _ _ attrs⟩ => attrs.hasToAdditive | _ => false structure Hyp where name : Name pp : Name type : Lean3.Expr value : Option Lean3.Expr instance : Repr Hyp where reprPrec | ⟨_, pp, t, v⟩, _ => pp.toString ++ " : " ++ repr t ++ match v with | none => ("":Format) | some v => repr v structure Goal where hyps : Array Hyp target : Lean3.Expr instance : Repr Goal where reprPrec | ⟨hyps, target⟩, _ => Format.join (hyps.toList.map fun hyp => repr hyp ++ "\n") ++ "⊒ " ++ repr target def Goals_repr (gs : Array Goal) : Format := Format.join (gs.toList.map fun g => repr g ++ "\n") structure TacticInvocation where declName : Name ast : Option #Tactic start : Array Goal Β«endΒ» : Array Goal success : Bool instance : Repr TacticInvocation where reprPrec | ⟨declName, tac, start, end_, success⟩, _ => "in declaration " ++ toString declName ++ " " ++ "invoking " ++ repr tac ++ ":\n" ++ "before:\n" ++ Goals_repr start ++ (if success then "success" else "failed") ++ ", after:\n" ++ Goals_repr end_ structure Comment where start : Position Β«endΒ» : Position text : String deriving Repr, Inhabited end AST3 structure AST3 where Β«preludeΒ» : Option #Unit Β«importΒ» : Array (Array #Name) commands : Array (Spanned AST3.Command) indexed_nota : Array AST3.Notation indexed_cmds : Array AST3.Command comments : Array AST3.Comment instance : Repr AST3 where reprPrec | ⟨prel, imps, cmds, _, _, _⟩, _ => (match prel with | none => "" | some _ => "prelude\n") ++ Format.join (imps.toList.map fun ns => "import " ++ Format.joinSep (ns.toList.map fun a => a.kind.toString) " " ++ "\n") ++ "\n" ++ Format.join (cmds.toList.map fun c => repr c ++ "\n\n") partial def Spanned.unparen : #AST3.Expr β†’ #AST3.Expr | ⟨_, AST3.Expr.paren e⟩ => e.unparen | e => e end Mathport
44359d8e377b8cdf4dd3cda75579c5c82ff4c79d
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/tactic/ring.lean
74ef9adf71e7d98914b1654f30ecd9c07cfbba0e
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
21,846
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.group_power tactic.norm_num import tactic.converter.interactive /-! # `ring` Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ namespace tactic namespace ring def horner {Ξ±} [comm_semiring Ξ±] (a x : Ξ±) (n : β„•) (b : Ξ±) := a * x ^ n + b meta structure cache := (Ξ± : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) meta def ring_m (Ξ± : Type) : Type := reader_t cache (state_t (buffer expr) tactic) Ξ± meta instance : monad ring_m := by dunfold ring_m; apply_instance meta instance : alternative ring_m := by dunfold ring_m; apply_instance meta def get_cache : ring_m cache := reader_t.read meta def get_atom (n : β„•) : ring_m expr := reader_t.lift $ (Ξ» es : buffer expr, es.read' n) <$> state_t.get meta def get_transparency : ring_m transparency := cache.red <$> get_cache meta def add_atom (e : expr) : ring_m β„• := do red ← get_transparency, reader_t.lift ⟨λ es, (do n ← es.iterate failed (Ξ» n e' t, t <|> (is_def_eq e e' red $> n)), return (n, es)) <|> return (es.size, es.push_back e)⟩ meta def lift {Ξ±} (m : tactic Ξ±) : ring_m Ξ± := reader_t.lift (state_t.lift m) meta def ring_m.run (red : transparency) (e : expr) {Ξ±} (m : ring_m Ξ±) : tactic Ξ± := do Ξ± ← infer_type e, c ← mk_app ``comm_semiring [Ξ±] >>= mk_instance, u ← mk_meta_univ, infer_type Ξ± >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, prod.fst <$> state_t.run (reader_t.run m ⟨α, u, c, red⟩) mk_buffer meta def cache.cs_app (c : cache) (n : name) : list expr β†’ expr := (@expr.const tt n [c.univ] c.Ξ± c.comm_semiring_inst).mk_app meta def ring_m.mk_app (n inst : name) (l : list expr) : ring_m expr := do c ← get_cache, m ← lift $ mk_instance ((expr.const inst [c.univ] : expr) c.Ξ±), return $ (@expr.const tt n [c.univ] c.Ξ± m).mk_app l meta inductive horner_expr : Type | const (e : expr) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr Γ— β„•) (n : expr Γ— β„•) (b : horner_expr) : horner_expr meta def horner_expr.e : horner_expr β†’ expr | (horner_expr.const e) := e | (horner_expr.xadd e _ _ _ _) := e meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr Γ— β„•) (n : expr Γ— β„•) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr meta def horner_expr.to_string : horner_expr β†’ string | (const e) := to_string e | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^" ++ to_string n ++ " + " ++ b.to_string meta def horner_expr.pp : horner_expr β†’ tactic format | (const e) := pp e | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x.1, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr Γ— expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {Ξ±} [comm_semiring Ξ±] (x n b) : @horner Ξ± _ 0 x n b = b := by simp [horner] theorem horner_horner {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ nβ‚‚ b n') (h : n₁ + nβ‚‚ = n') : @horner Ξ± _ (horner a₁ x n₁ 0) x nβ‚‚ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] meta def eval_horner : horner_expr β†’ expr Γ— β„• β†’ expr Γ— β„• β†’ horner_expr β†’ ring_m (horner_expr Γ— expr) | ha@(const a) x n b := do c ← get_cache, if a.to_nat = some 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← lift $ mk_app ``has_add.add [n₁.1, n.1] >>= norm_num, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {Ξ±} [comm_semiring Ξ±] (k a x n b b') (h : k + b = b') : k + @horner Ξ± _ a x n b = horner a x n b' := by simp [h.symm, horner]; cc theorem horner_add_const {Ξ±} [comm_semiring Ξ±] (a x n b k b') (h : b + k = b') : @horner Ξ± _ a x n b + k = horner a x n b' := by simp [h.symm, horner] theorem horner_add_horner_lt {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ bβ‚‚ k a' b') (h₁ : n₁ + k = nβ‚‚) (hβ‚‚ : (a₁ + horner aβ‚‚ x k 0 : Ξ±) = a') (h₃ : b₁ + bβ‚‚ = b') : @horner Ξ± _ a₁ x n₁ b₁ + horner aβ‚‚ x nβ‚‚ bβ‚‚ = horner a' x n₁ b' := by simp [hβ‚‚.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_gt {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ bβ‚‚ k a' b') (h₁ : nβ‚‚ + k = n₁) (hβ‚‚ : (horner a₁ x k 0 + aβ‚‚ : Ξ±) = a') (h₃ : b₁ + bβ‚‚ = b') : @horner Ξ± _ a₁ x n₁ b₁ + horner aβ‚‚ x nβ‚‚ bβ‚‚ = horner a' x nβ‚‚ b' := by simp [hβ‚‚.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc -- set_option trace.class_instances true -- set_option class.instance_max_depth 128 theorem horner_add_horner_eq {Ξ±} [comm_semiring Ξ±] (a₁ x n b₁ aβ‚‚ bβ‚‚ a' b' t) (h₁ : a₁ + aβ‚‚ = a') (hβ‚‚ : b₁ + bβ‚‚ = b') (h₃ : horner a' x n b' = t) : @horner Ξ± _ a₁ x n b₁ + horner aβ‚‚ x n bβ‚‚ = t := by simp [h₃.symm, hβ‚‚.symm, h₁.symm, horner, add_mul, mul_comm]; cc meta def eval_add : horner_expr β†’ horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e₁) (const eβ‚‚) := do (e, p) ← lift $ mk_app ``has_add.add [e₁, eβ‚‚] >>= norm_num, return (const e, p) | he₁@(const e₁) heβ‚‚@(xadd eβ‚‚ a x n b) := do c ← get_cache, if e₁.to_nat = some 0 then do p ← lift $ mk_app ``zero_add [eβ‚‚], return (heβ‚‚, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) heβ‚‚@(const eβ‚‚) := do c ← get_cache, if eβ‚‚.to_nat = some 0 then do p ← lift $ mk_app ``add_zero [e₁], return (he₁, p) else do (b', h) ← eval_add b heβ‚‚, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, eβ‚‚, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) heβ‚‚@(xadd eβ‚‚ aβ‚‚ xβ‚‚ nβ‚‚ bβ‚‚) := do c ← get_cache, if x₁.2 < xβ‚‚.2 then do (b', h) ← eval_add b₁ heβ‚‚, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, eβ‚‚, b', h]) else if x₁.2 β‰  xβ‚‚.2 then do (b', h) ← eval_add he₁ bβ‚‚, return (xadd' c aβ‚‚ xβ‚‚ nβ‚‚ b', c.cs_app ``const_add_horner [e₁, aβ‚‚, xβ‚‚.1, nβ‚‚.1, bβ‚‚, b', h]) else if n₁.2 < nβ‚‚.2 then do let k := nβ‚‚.2 - n₁.2, ek ← lift $ expr.of_nat (expr.const `nat []) k, (_, h₁) ← lift $ mk_app ``has_add.add [n₁.1, ek] >>= norm_num, Ξ±0 ← lift $ expr.of_nat c.Ξ± 0, (a', hβ‚‚) ← eval_add a₁ (xadd' c aβ‚‚ x₁ (ek, k) (const Ξ±0)), (b', h₃) ← eval_add b₁ bβ‚‚, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, bβ‚‚, ek, a', b', h₁, hβ‚‚, h₃]) else if n₁.2 β‰  nβ‚‚.2 then do let k := n₁.2 - nβ‚‚.2, ek ← lift $ expr.of_nat (expr.const `nat []) k, (_, h₁) ← lift $ mk_app ``has_add.add [nβ‚‚.1, ek] >>= norm_num, Ξ±0 ← lift $ expr.of_nat c.Ξ± 0, (a', hβ‚‚) ← eval_add (xadd' c a₁ x₁ (ek, k) (const Ξ±0)) aβ‚‚, (b', h₃) ← eval_add b₁ bβ‚‚, return (xadd' c a' x₁ nβ‚‚ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, bβ‚‚, ek, a', b', h₁, hβ‚‚, h₃]) else do (a', h₁) ← eval_add a₁ aβ‚‚, (b', hβ‚‚) ← eval_add b₁ bβ‚‚, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, aβ‚‚, bβ‚‚, a', b', t, h₁, hβ‚‚, h₃]) theorem horner_neg {Ξ±} [comm_ring Ξ±] (a x n b a' b') (h₁ : -a = a') (hβ‚‚ : -b = b') : -@horner Ξ± _ a x n b = horner a' x n b' := by simp [hβ‚‚.symm, h₁.symm, horner]; cc meta def eval_neg : horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e) := do (e', p) ← lift $ mk_app ``has_neg.neg [e] >>= norm_num, return (const e', p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', hβ‚‚) ← eval_neg b, p ← ring_m.mk_app ``horner_neg ``comm_ring [a, x.1, n.1, b, a', b', h₁, hβ‚‚], return (xadd' c a' x n b', p) theorem horner_const_mul {Ξ±} [comm_semiring Ξ±] (c a x n b a' b') (h₁ : c * a = a') (hβ‚‚ : c * b = b') : c * @horner Ξ± _ a x n b = horner a' x n b' := by simp [hβ‚‚.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {Ξ±} [comm_semiring Ξ±] (a x n b c a' b') (h₁ : a * c = a') (hβ‚‚ : b * c = b') : @horner Ξ± _ a x n b * c = horner a' x n b' := by simp [hβ‚‚.symm, h₁.symm, horner, add_mul, mul_right_comm] meta def eval_const_mul (k : expr) : horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e) := do (e', p) ← lift $ mk_app ``has_mul.mul [k, e] >>= norm_num, return (const e', p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', hβ‚‚) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k, a, x.1, n.1, b, a', b', h₁, hβ‚‚]) theorem horner_mul_horner_zero {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ aa t) (h₁ : @horner Ξ± _ a₁ x n₁ b₁ * aβ‚‚ = aa) (hβ‚‚ : horner aa x nβ‚‚ 0 = t) : horner a₁ x n₁ b₁ * horner aβ‚‚ x nβ‚‚ 0 = t := by rw [← hβ‚‚, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {Ξ±} [comm_semiring Ξ±] (a₁ x n₁ b₁ aβ‚‚ nβ‚‚ bβ‚‚ aa haa ab bb t) (h₁ : @horner Ξ± _ a₁ x n₁ b₁ * aβ‚‚ = aa) (hβ‚‚ : horner aa x nβ‚‚ 0 = haa) (h₃ : a₁ * bβ‚‚ = ab) (hβ‚„ : b₁ * bβ‚‚ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner aβ‚‚ x nβ‚‚ bβ‚‚ = t := by rw [← H, ← hβ‚‚, ← h₁, ← h₃, ← hβ‚„]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] meta def eval_mul : horner_expr β†’ horner_expr β†’ ring_m (horner_expr Γ— expr) | (const e₁) (const eβ‚‚) := do (e', p) ← lift $ mk_app ``has_mul.mul [e₁, eβ‚‚] >>= norm_num, return (const e', p) | (const e₁) eβ‚‚ := match e₁.to_nat with | (some 0) := do c ← get_cache, Ξ±0 ← lift $ expr.of_nat c.Ξ± 0, p ← lift $ mk_app ``zero_mul [eβ‚‚], return (const Ξ±0, p) | (some 1) := do p ← lift $ mk_app ``one_mul [eβ‚‚], return (eβ‚‚, p) | _ := eval_const_mul e₁ eβ‚‚ end | e₁ heβ‚‚@(const eβ‚‚) := do p₁ ← lift $ mk_app ``mul_comm [e₁, eβ‚‚], (e', pβ‚‚) ← eval_mul heβ‚‚ e₁, p ← lift $ mk_eq_trans p₁ pβ‚‚, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) heβ‚‚@(xadd eβ‚‚ aβ‚‚ xβ‚‚ nβ‚‚ bβ‚‚) := do c ← get_cache, if x₁.2 < xβ‚‚.2 then do (a', h₁) ← eval_mul a₁ heβ‚‚, (b', hβ‚‚) ← eval_mul b₁ heβ‚‚, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, eβ‚‚, a', b', h₁, hβ‚‚]) else if x₁.2 β‰  xβ‚‚.2 then do (a', h₁) ← eval_mul he₁ aβ‚‚, (b', hβ‚‚) ← eval_mul he₁ bβ‚‚, return (xadd' c a' xβ‚‚ nβ‚‚ b', c.cs_app ``horner_const_mul [e₁, aβ‚‚, xβ‚‚.1, nβ‚‚.1, bβ‚‚, a', b', h₁, hβ‚‚]) else do (aa, h₁) ← eval_mul he₁ aβ‚‚, Ξ±0 ← lift $ expr.of_nat c.Ξ± 0, (haa, hβ‚‚) ← eval_horner aa x₁ nβ‚‚ (const Ξ±0), if bβ‚‚.e.to_nat = some 0 then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, aa, haa, h₁, hβ‚‚]) else do (ab, h₃) ← eval_mul a₁ bβ‚‚, (bb, hβ‚„) ← eval_mul b₁ bβ‚‚, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, aβ‚‚, nβ‚‚.1, bβ‚‚, aa, haa, ab, bb, t, h₁, hβ‚‚, h₃, hβ‚„, H]) theorem horner_pow {Ξ±} [comm_semiring Ξ±] (a x n m n' a') (h₁ : n * m = n') (hβ‚‚ : a ^ m = a') : @horner Ξ± _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, hβ‚‚.symm, horner, mul_pow, pow_mul] meta def eval_pow : horner_expr β†’ expr Γ— β„• β†’ ring_m (horner_expr Γ— expr) | e (_, 0) := do c ← get_cache, Ξ±1 ← lift $ expr.of_nat c.Ξ± 1, p ← lift $ mk_app ``pow_zero [e], return (const Ξ±1, p) | e (_, 1) := do p ← lift $ mk_app ``pow_one [e], return (e, p) | (const e) (eβ‚‚, m) := do (e', p) ← lift $ mk_app ``monoid.pow [e, eβ‚‚] >>= norm_num.derive', return (const e', p) | he@(xadd e a x n b) m := do c ← get_cache, let N : expr := expr.const `nat [], match b.e.to_nat with | some 0 := do (n', h₁) ← lift $ mk_app ``has_mul.mul [n.1, m.1] >>= norm_num.derive', (a', hβ‚‚) ← eval_pow a m, Ξ±0 ← lift $ expr.of_nat c.Ξ± 0, return (xadd' c a' x (n', n.2 * m.2) (const Ξ±0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, hβ‚‚]) | _ := do eβ‚‚ ← lift $ expr.of_nat N (m.2-1), l ← lift $ mk_app ``monoid.pow [e, eβ‚‚], (tl, hl) ← eval_pow he (eβ‚‚, m.2-1), (t, pβ‚‚) ← eval_mul tl he, hr ← lift $ mk_eq_refl e, pβ‚‚ ← ring_m.mk_app ``norm_num.subst_into_prod ``has_mul [l, e, tl, e, t, hl, hr, pβ‚‚], p₁ ← lift $ mk_app ``pow_succ' [e, eβ‚‚], p ← lift $ mk_eq_trans p₁ pβ‚‚, return (t, p) end theorem horner_atom {Ξ±} [comm_semiring Ξ±] (x : Ξ±) : x = horner 1 x 1 0 := by simp [horner] meta def eval_atom (e : expr) : ring_m (horner_expr Γ— expr) := do c ← get_cache, i ← add_atom e, Ξ±0 ← lift $ expr.of_nat c.Ξ± 0, Ξ±1 ← lift $ expr.of_nat c.Ξ± 1, n1 ← lift $ expr.of_nat (expr.const `nat []) 1, return (xadd' c (const Ξ±1) (e, i) (n1, 1) (const Ξ±0), c.cs_app ``horner_atom [e]) lemma subst_into_pow {Ξ±} [monoid Ξ±] (l r tl tr t) (prl : (l : Ξ±) = tl) (prr : (r : β„•) = tr) (prt : tl ^ tr = t) : l ^ r = t := by simp [prl, prr, prt] lemma unfold_sub {Ξ±} [add_group Ξ±] (a b c : Ξ±) (h : a + -b = c) : a - b = c := h lemma unfold_div {Ξ±} [division_ring Ξ±] (a b c : Ξ±) (h : a * b⁻¹ = c) : a / b = c := h meta def eval : expr β†’ ring_m (horner_expr Γ— expr) | `(%%e₁ + %%eβ‚‚) := do (e₁', p₁) ← eval e₁, (eβ‚‚', pβ‚‚) ← eval eβ‚‚, (e', p') ← eval_add e₁' eβ‚‚', p ← ring_m.mk_app ``norm_num.subst_into_sum ``has_add [e₁, eβ‚‚, e₁', eβ‚‚', e', p₁, pβ‚‚, p'], return (e', p) | e@`(@has_sub.sub %%Ξ± %%P %%e₁ %%eβ‚‚) := mcond (succeeds (lift $ mk_app ``comm_ring [Ξ±] >>= mk_instance)) (do eβ‚‚' ← lift $ mk_app ``has_neg.neg [eβ‚‚], e ← lift $ mk_app ``has_add.add [e₁, eβ‚‚'], (e', p) ← eval e, p' ← ring_m.mk_app ``unfold_sub ``add_group [e₁, eβ‚‚, e', p], return (e', p')) (eval_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (eβ‚‚, pβ‚‚) ← eval_neg e₁, p ← ring_m.mk_app ``norm_num.subst_into_neg ``has_neg [e, e₁, eβ‚‚, p₁, pβ‚‚], return (eβ‚‚, p) | `(%%e₁ * %%eβ‚‚) := do (e₁', p₁) ← eval e₁, (eβ‚‚', pβ‚‚) ← eval eβ‚‚, (e', p') ← eval_mul e₁' eβ‚‚', p ← ring_m.mk_app ``norm_num.subst_into_prod ``has_mul [e₁, eβ‚‚, e₁', eβ‚‚', e', p₁, pβ‚‚, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e <|> refl_conv e, lift $ e'.to_rat, return (const e', p)) <|> eval_atom e | e@`(@has_div.div _ %%inst %%e₁ %%eβ‚‚) := mcond (succeeds (do inst' ← ring_m.mk_app ``division_ring_has_div ``division_ring [], lift $ is_def_eq inst inst')) (do eβ‚‚' ← lift $ mk_app ``has_inv.inv [eβ‚‚], e ← lift $ mk_app ``has_mul.mul [e₁, eβ‚‚'], (e', p) ← eval e, p' ← ring_m.mk_app ``unfold_div ``division_ring [e₁, eβ‚‚, e', p], return (e', p')) (eval_atom e) | e@`(@has_pow.pow _ _ %%P %%e₁ %%eβ‚‚) := do (eβ‚‚', pβ‚‚) ← lift $ norm_num.derive eβ‚‚ <|> refl_conv eβ‚‚, match eβ‚‚'.to_nat, P with | some k, `(monoid.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (eβ‚‚, k), p ← ring_m.mk_app ``subst_into_pow ``monoid [e₁, eβ‚‚, e₁', eβ‚‚', e', p₁, pβ‚‚, p'], return (e', p) | some k, `(nat.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (eβ‚‚, k), p₃ ← ring_m.mk_app ``subst_into_pow ``monoid [e₁, eβ‚‚, e₁', eβ‚‚', e', p₁, pβ‚‚, p'], pβ‚„ ← lift $ mk_app ``nat.pow_eq_pow [e₁, eβ‚‚] >>= mk_eq_symm, p ← lift $ mk_eq_trans pβ‚„ p₃, return (e', p) | _, _ := eval_atom e end | e := match e.to_nat with | some n := (const e).refl_conv | none := eval_atom e end meta def eval' (red : transparency) (e : expr) : tactic (expr Γ— expr) := ring_m.run red e $ do (e', p) ← eval e, return (e', p) theorem horner_def' {Ξ±} [comm_semiring Ξ±] (a x n b) : @horner Ξ± _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {Ξ±} [semigroup Ξ±] (a b c : Ξ±) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {Ξ±} [monoid Ξ±] (a : Ξ±) (m n : β„•) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {Ξ±} [monoid Ξ±] (a b : Ξ±) (m n : β„•) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {Ξ±} [add_group Ξ±] (a b : Ξ±) : a + -b = a - b := rfl @[derive has_reflect] inductive normalize_mode | raw | SOP | horner instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩ meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr Γ— expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (Ξ» _, failed) (Ξ» _ _ _ _ e, do (new_e, pr) ← match mode with | normalize_mode.raw := eval' red | normalize_mode.horner := trans_conv (eval' red) (simplify lemmas []) | normalize_mode.SOP := trans_conv (eval' red) $ trans_conv (simplify lemmas []) $ simp_bottom_up' (Ξ» e, norm_num e <|> pow_lemma.rewrite e) end e, guard (Β¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (Ξ» _ _ _ _ _, failed) `eq e, return (e', pr) end ring namespace interactive open interactive interactive.types lean.parser open tactic.ring local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%eβ‚‚) ← target, ((e₁', p₁), (eβ‚‚', pβ‚‚)) ← ring_m.run transp e₁ $ prod.mk <$> eval e₁ <*> eval eβ‚‚, is_def_eq e₁' eβ‚‚', p ← mk_eq_symm pβ‚‚ >>= mk_eq_trans p₁, tactic.exact p meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := return ring.normalize_mode.horner | some `horner := return ring.normalize_mode.horner | some `SOP := return ring.normalize_mode.SOP | some `raw := return ring.normalize_mode.raw | _ := failed end /-- Tactic for solving equations in the language of *commutative* (semi)rings. Attempts to prove the goal outright if there is no `at` specifier and the target is an equality, but if this fails it falls back to rewriting all ring expressions into a normal form. When writing a normal form, `ring SOP` will use sum-of-products form instead of horner form. `ring!` will use a more aggressive reducibility setting to identify atoms. Based on [Proving Equalities in a Commutative Ring Done Right in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin GrΓ©goire and Assia Mahboubi. -/ meta def ring (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := instantiate_mvars_in_target >> ring1 red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp SOP) ns loc.include_goal | fail "ring failed to simplify", when loc.include_goal $ try tactic.reflexivity add_hint_tactic "ring" add_tactic_doc { name := "ring", category := doc_category.tactic, decl_names := [`tactic.interactive.ring], tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize) local postfix `?`:9001 := optional meta def ring (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> replace_lhs (normalize transp SOP) <|> fail "ring failed to simplify" end conv.interactive
4b0afabfd4fc6007808d3ea022cfb45ef4097b79
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/function/conditional_expectation/real.lean
ffdda9fc88a671d74d3a548fa1d4759b492da054
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
19,807
lean
/- Copyright (c) 2022 RΓ©my Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: RΓ©my Degenne, Kexing Ying -/ import measure_theory.function.conditional_expectation.indicator import measure_theory.function.uniform_integrable import measure_theory.decomposition.radon_nikodym /-! # Conditional expectation of real-valued functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves some results regarding the conditional expectation of real-valued functions. ## Main results * `measure_theory.rn_deriv_ae_eq_condexp`: the conditional expectation `ΞΌ[f | m]` is equal to the Radon-Nikodym derivative of `fΞΌ` restricted on `m` with respect to `ΞΌ` restricted on `m`. * `measure_theory.integrable.uniform_integrable_condexp`: the conditional expectation of a function form a uniformly integrable class. * `measure_theory.condexp_strongly_measurable_mul`: the pull-out property of the conditional expectation. -/ noncomputable theory open topological_space measure_theory.Lp filter continuous_linear_map open_locale nnreal ennreal topology big_operators measure_theory namespace measure_theory variables {Ξ± : Type*} {m m0 : measurable_space Ξ±} {ΞΌ : measure Ξ±} lemma rn_deriv_ae_eq_condexp {hm : m ≀ m0} [hΞΌm : sigma_finite (ΞΌ.trim hm)] {f : Ξ± β†’ ℝ} (hf : integrable f ΞΌ) : signed_measure.rn_deriv ((ΞΌ.with_densityα΅₯ f).trim hm) (ΞΌ.trim hm) =ᡐ[ΞΌ] ΞΌ[f | m] := begin refine ae_eq_condexp_of_forall_set_integral_eq hm hf _ _ _, { exact Ξ» _ _ _, (integrable_of_integrable_trim hm (signed_measure.integrable_rn_deriv ((ΞΌ.with_densityα΅₯ f).trim hm) (ΞΌ.trim hm))).integrable_on }, { intros s hs hlt, conv_rhs { rw [← hf.with_densityα΅₯_trim_eq_integral hm hs, ← signed_measure.with_densityα΅₯_rn_deriv_eq ((ΞΌ.with_densityα΅₯ f).trim hm) (ΞΌ.trim hm) (hf.with_densityα΅₯_trim_absolutely_continuous hm)], }, rw [with_densityα΅₯_apply (signed_measure.integrable_rn_deriv ((ΞΌ.with_densityα΅₯ f).trim hm) (ΞΌ.trim hm)) hs, ← set_integral_trim hm _ hs], exact (signed_measure.measurable_rn_deriv _ _).strongly_measurable }, { exact strongly_measurable.ae_strongly_measurable' (signed_measure.measurable_rn_deriv _ _).strongly_measurable }, end -- TODO: the following couple of lemmas should be generalized and proved using Jensen's inequality -- for the conditional expectation (not in mathlib yet) . lemma snorm_one_condexp_le_snorm (f : Ξ± β†’ ℝ) : snorm (ΞΌ[f | m]) 1 ΞΌ ≀ snorm f 1 ΞΌ := begin by_cases hf : integrable f ΞΌ, swap, { rw [condexp_undef hf, snorm_zero], exact zero_le _ }, by_cases hm : m ≀ m0, swap, { rw [condexp_of_not_le hm, snorm_zero], exact zero_le _ }, by_cases hsig : sigma_finite (ΞΌ.trim hm), swap, { rw [condexp_of_not_sigma_finite hm hsig, snorm_zero], exact zero_le _ }, calc snorm (ΞΌ[f | m]) 1 ΞΌ ≀ snorm (ΞΌ[|f| | m]) 1 ΞΌ : begin refine snorm_mono_ae _, filter_upwards [@condexp_mono _ m m0 _ _ _ _ _ _ _ _ hf hf.abs (@ae_of_all _ m0 _ ΞΌ (Ξ» x, le_abs_self (f x) : βˆ€ x, f x ≀ |f x|)), eventually_le.trans (condexp_neg f).symm.le (@condexp_mono _ m m0 _ _ _ _ _ _ _ _ hf.neg hf.abs (@ae_of_all _ m0 _ ΞΌ (Ξ» x, neg_le_abs_self (f x) : βˆ€ x, -f x ≀ |f x|)))] with x hx₁ hxβ‚‚, exact abs_le_abs hx₁ hxβ‚‚, end ... = snorm f 1 ΞΌ : begin rw [snorm_one_eq_lintegral_nnnorm, snorm_one_eq_lintegral_nnnorm, ← ennreal.to_real_eq_to_real (ne_of_lt integrable_condexp.2) (ne_of_lt hf.2), ← integral_norm_eq_lintegral_nnnorm (strongly_measurable_condexp.mono hm).ae_strongly_measurable, ← integral_norm_eq_lintegral_nnnorm hf.1], simp_rw [real.norm_eq_abs], rw ← @integral_condexp _ _ _ _ _ m m0 ΞΌ _ hm hsig hf.abs, refine integral_congr_ae _, have : 0 ≀ᡐ[ΞΌ] ΞΌ[|f| | m], { rw ← @condexp_zero Ξ± ℝ _ _ _ m m0 ΞΌ, exact condexp_mono (integrable_zero _ _ _) hf.abs (@ae_of_all _ m0 _ ΞΌ (Ξ» x, abs_nonneg (f x) : βˆ€ x, 0 ≀ |f x|)) }, filter_upwards [this] with x hx, exact abs_eq_self.2 hx end end lemma integral_abs_condexp_le (f : Ξ± β†’ ℝ) : ∫ x, |ΞΌ[f | m] x| βˆ‚ΞΌ ≀ ∫ x, |f x| βˆ‚ΞΌ := begin by_cases hm : m ≀ m0, swap, { simp_rw [condexp_of_not_le hm, pi.zero_apply, abs_zero, integral_zero], exact integral_nonneg (Ξ» x, abs_nonneg _) }, by_cases hfint : integrable f ΞΌ, swap, { simp only [condexp_undef hfint, pi.zero_apply, abs_zero, integral_const, algebra.id.smul_eq_mul, mul_zero], exact integral_nonneg (Ξ» x, abs_nonneg _) }, rw [integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae], { rw ennreal.to_real_le_to_real; simp_rw [← real.norm_eq_abs, of_real_norm_eq_coe_nnnorm], { rw [← snorm_one_eq_lintegral_nnnorm, ← snorm_one_eq_lintegral_nnnorm], exact snorm_one_condexp_le_snorm _ }, { exact ne_of_lt integrable_condexp.2 }, { exact ne_of_lt hfint.2 } }, { exact eventually_of_forall (Ξ» x, abs_nonneg _) }, { simp_rw ← real.norm_eq_abs, exact hfint.1.norm }, { exact eventually_of_forall (Ξ» x, abs_nonneg _) }, { simp_rw ← real.norm_eq_abs, exact (strongly_measurable_condexp.mono hm).ae_strongly_measurable.norm } end lemma set_integral_abs_condexp_le {s : set Ξ±} (hs : measurable_set[m] s) (f : Ξ± β†’ ℝ) : ∫ x in s, |ΞΌ[f | m] x| βˆ‚ΞΌ ≀ ∫ x in s, |f x| βˆ‚ΞΌ := begin by_cases hnm : m ≀ m0, swap, { simp_rw [condexp_of_not_le hnm, pi.zero_apply, abs_zero, integral_zero], exact integral_nonneg (Ξ» x, abs_nonneg _) }, by_cases hfint : integrable f ΞΌ, swap, { simp only [condexp_undef hfint, pi.zero_apply, abs_zero, integral_const, algebra.id.smul_eq_mul, mul_zero], exact integral_nonneg (Ξ» x, abs_nonneg _) }, have : ∫ x in s, |ΞΌ[f | m] x| βˆ‚ΞΌ = ∫ x, |ΞΌ[s.indicator f | m] x| βˆ‚ΞΌ, { rw ← integral_indicator, swap, { exact hnm _ hs }, refine integral_congr_ae _, have : (Ξ» x, |ΞΌ[s.indicator f | m] x|) =ᡐ[ΞΌ] Ξ» x, |s.indicator (ΞΌ[f | m]) x| := eventually_eq.fun_comp (condexp_indicator hfint hs) _, refine eventually_eq.trans (eventually_of_forall $ Ξ» x, _) this.symm, rw [← real.norm_eq_abs, norm_indicator_eq_indicator_norm], refl }, rw [this, ← integral_indicator], swap, { exact hnm _ hs }, refine (integral_abs_condexp_le _).trans (le_of_eq $ integral_congr_ae $ eventually_of_forall $ Ξ» x, _), rw [← real.norm_eq_abs, norm_indicator_eq_indicator_norm], refl, end /-- If the real valued function `f` is bounded almost everywhere by `R`, then so is its conditional expectation. -/ lemma ae_bdd_condexp_of_ae_bdd {R : ℝβ‰₯0} {f : Ξ± β†’ ℝ} (hbdd : βˆ€α΅ x βˆ‚ΞΌ, |f x| ≀ R) : βˆ€α΅ x βˆ‚ΞΌ, |ΞΌ[f | m] x| ≀ R := begin by_cases hnm : m ≀ m0, swap, { simp_rw [condexp_of_not_le hnm, pi.zero_apply, abs_zero], refine eventually_of_forall (Ξ» x, R.coe_nonneg) }, by_cases hfint : integrable f ΞΌ, swap, { simp_rw [condexp_undef hfint], filter_upwards [hbdd] with x hx, rw [pi.zero_apply, abs_zero], exact (abs_nonneg _).trans hx }, by_contra h, change ΞΌ _ β‰  0 at h, simp only [← zero_lt_iff, set.compl_def, set.mem_set_of_eq, not_le] at h, suffices : (ΞΌ {x | ↑R < |ΞΌ[f | m] x|}).to_real * ↑R < (ΞΌ {x | ↑R < |ΞΌ[f | m] x|}).to_real * ↑R, { exact this.ne rfl }, refine lt_of_lt_of_le (set_integral_gt_gt R.coe_nonneg _ _ h.ne.symm) _, { simp_rw [← real.norm_eq_abs], exact (strongly_measurable_condexp.mono hnm).measurable.norm }, { exact integrable_condexp.abs.integrable_on }, refine (set_integral_abs_condexp_le _ _).trans _, { simp_rw [← real.norm_eq_abs], exact @measurable_set_lt _ _ _ _ _ m _ _ _ _ _ measurable_const strongly_measurable_condexp.norm.measurable }, simp only [← smul_eq_mul, ← set_integral_const, nnreal.val_eq_coe, is_R_or_C.coe_real_eq_id, id.def], refine set_integral_mono_ae hfint.abs.integrable_on _ _, { refine ⟨ae_strongly_measurable_const, lt_of_le_of_lt _ (integrable_condexp.integrable_on : integrable_on (ΞΌ[f | m]) {x | ↑R < |ΞΌ[f | m] x|} ΞΌ).2⟩, refine set_lintegral_mono (measurable.nnnorm _).coe_nnreal_ennreal (strongly_measurable_condexp.mono hnm).measurable.nnnorm.coe_nnreal_ennreal (Ξ» x hx, _), { exact measurable_const }, { rw [ennreal.coe_le_coe, real.nnnorm_of_nonneg R.coe_nonneg], exact subtype.mk_le_mk.2 (le_of_lt hx) } }, { exact hbdd }, end /-- Given a integrable function `g`, the conditional expectations of `g` with respect to a sequence of sub-Οƒ-algebras is uniformly integrable. -/ lemma integrable.uniform_integrable_condexp {ΞΉ : Type*} [is_finite_measure ΞΌ] {g : Ξ± β†’ ℝ} (hint : integrable g ΞΌ) {β„± : ΞΉ β†’ measurable_space Ξ±} (hβ„± : βˆ€ i, β„± i ≀ m0) : uniform_integrable (Ξ» i, ΞΌ[g | β„± i]) 1 ΞΌ := begin have hmeas : βˆ€ n, βˆ€ C, measurable_set {x | C ≀ β€–ΞΌ[g | β„± n] xβ€–β‚Š} := Ξ» n C, measurable_set_le measurable_const (strongly_measurable_condexp.mono (hβ„± n)).measurable.nnnorm, have hg : mem_β„’p g 1 ΞΌ := mem_β„’p_one_iff_integrable.2 hint, refine uniform_integrable_of le_rfl ennreal.one_ne_top (Ξ» n, (strongly_measurable_condexp.mono (hβ„± n)).ae_strongly_measurable) (Ξ» Ξ΅ hΞ΅, _), by_cases hne : snorm g 1 ΞΌ = 0, { rw snorm_eq_zero_iff hg.1 one_ne_zero at hne, refine ⟨0, Ξ» n, (le_of_eq $ (snorm_eq_zero_iff ((strongly_measurable_condexp.mono (hβ„± n)).ae_strongly_measurable.indicator (hmeas n 0)) one_ne_zero).2 _).trans (zero_le _)⟩, filter_upwards [@condexp_congr_ae _ _ _ _ _ (β„± n) m0 ΞΌ _ _ hne] with x hx, simp only [zero_le', set.set_of_true, set.indicator_univ, pi.zero_apply, hx, condexp_zero] }, obtain ⟨δ, hΞ΄, h⟩ := hg.snorm_indicator_le ΞΌ le_rfl ennreal.one_ne_top hΞ΅, set C : ℝβ‰₯0 := ⟨δ, hΞ΄.le⟩⁻¹ * (snorm g 1 ΞΌ).to_nnreal with hC, have hCpos : 0 < C := mul_pos (inv_pos.2 hΞ΄) (ennreal.to_nnreal_pos hne hg.snorm_lt_top.ne), have : βˆ€ n, ΞΌ {x : Ξ± | C ≀ β€–ΞΌ[g | β„± n] xβ€–β‚Š} ≀ ennreal.of_real Ξ΄, { intro n, have := mul_meas_ge_le_pow_snorm' ΞΌ one_ne_zero ennreal.one_ne_top ((@strongly_measurable_condexp _ _ _ _ _ (β„± n) _ ΞΌ g).mono (hβ„± n)).ae_strongly_measurable C, rw [ennreal.one_to_real, ennreal.rpow_one, ennreal.rpow_one, mul_comm, ← ennreal.le_div_iff_mul_le (or.inl (ennreal.coe_ne_zero.2 hCpos.ne.symm)) (or.inl ennreal.coe_lt_top.ne)] at this, simp_rw [ennreal.coe_le_coe] at this, refine this.trans _, rw [ennreal.div_le_iff_le_mul (or.inl (ennreal.coe_ne_zero.2 hCpos.ne.symm)) (or.inl ennreal.coe_lt_top.ne), hC, nonneg.inv_mk, ennreal.coe_mul, ennreal.coe_to_nnreal hg.snorm_lt_top.ne, ← mul_assoc, ← ennreal.of_real_eq_coe_nnreal, ← ennreal.of_real_mul hΞ΄.le, mul_inv_cancel hΞ΄.ne.symm, ennreal.of_real_one, one_mul], exact snorm_one_condexp_le_snorm _ }, refine ⟨C, Ξ» n, le_trans _ (h {x : Ξ± | C ≀ β€–ΞΌ[g | β„± n] xβ€–β‚Š} (hmeas n C) (this n))⟩, have hmeasβ„± : measurable_set[β„± n] {x : Ξ± | C ≀ β€–ΞΌ[g | β„± n] xβ€–β‚Š} := @measurable_set_le _ _ _ _ _ (β„± n) _ _ _ _ _ measurable_const (@measurable.nnnorm _ _ _ _ _ (β„± n) _ strongly_measurable_condexp.measurable), rw ← snorm_congr_ae (condexp_indicator hint hmeasβ„±), exact snorm_one_condexp_le_snorm _, end section pull_out -- TODO: this section could be generalized beyond multiplication, to any bounded bilinear map. /-- Auxiliary lemma for `condexp_measurable_mul`. -/ lemma condexp_strongly_measurable_simple_func_mul (hm : m ≀ m0) (f : @simple_func Ξ± m ℝ) {g : Ξ± β†’ ℝ} (hg : integrable g ΞΌ) : ΞΌ[f * g | m] =ᡐ[ΞΌ] f * ΞΌ[g | m] := begin have : βˆ€ s c (f : Ξ± β†’ ℝ), set.indicator s (function.const Ξ± c) * f = s.indicator (c β€’ f), { intros s c f, ext1 x, by_cases hx : x ∈ s, { simp only [hx, pi.mul_apply, set.indicator_of_mem, pi.smul_apply, algebra.id.smul_eq_mul] }, { simp only [hx, pi.mul_apply, set.indicator_of_not_mem, not_false_iff, zero_mul], }, }, refine @simple_func.induction _ _ m _ _ (Ξ» c s hs, _) (Ξ» g₁ gβ‚‚ h_disj h_eq₁ h_eqβ‚‚, _) f, { simp only [simple_func.const_zero, simple_func.coe_piecewise, simple_func.coe_const, simple_func.coe_zero, set.piecewise_eq_indicator], rw [this, this], refine (condexp_indicator (hg.smul c) hs).trans _, filter_upwards [@condexp_smul Ξ± ℝ ℝ _ _ _ _ _ m m0 ΞΌ c g] with x hx, classical, simp_rw [set.indicator_apply, hx], }, { have h_add := @simple_func.coe_add _ _ m _ g₁ gβ‚‚, calc ΞΌ[⇑(g₁ + gβ‚‚) * g|m] =ᡐ[ΞΌ] ΞΌ[(⇑g₁ + ⇑gβ‚‚) * g|m] : by { refine condexp_congr_ae (eventually_eq.mul _ eventually_eq.rfl), rw h_add, } ... =ᡐ[ΞΌ] ΞΌ[⇑g₁ * g|m] + ΞΌ[⇑gβ‚‚ * g|m] : by { rw add_mul, exact condexp_add (hg.simple_func_mul' hm _) (hg.simple_func_mul' hm _), } ... =ᡐ[ΞΌ] ⇑g₁ * ΞΌ[g|m] + ⇑gβ‚‚ * ΞΌ[g|m] : eventually_eq.add h_eq₁ h_eqβ‚‚ ... =ᡐ[ΞΌ] ⇑(g₁ + gβ‚‚) * ΞΌ[g|m] : by rw [h_add, add_mul], }, end lemma condexp_strongly_measurable_mul_of_bound (hm : m ≀ m0) [is_finite_measure ΞΌ] {f g : Ξ± β†’ ℝ} (hf : strongly_measurable[m] f) (hg : integrable g ΞΌ) (c : ℝ) (hf_bound : βˆ€α΅ x βˆ‚ΞΌ, β€–f xβ€– ≀ c) : ΞΌ[f * g | m] =ᡐ[ΞΌ] f * ΞΌ[g | m] := begin let fs := hf.approx_bounded c, have hfs_tendsto : βˆ€α΅ x βˆ‚ΞΌ, tendsto (Ξ» n, fs n x) at_top (𝓝 (f x)), from hf.tendsto_approx_bounded_ae hf_bound, by_cases hΞΌ : ΞΌ = 0, { simp only [hΞΌ, ae_zero], }, haveI : ΞΌ.ae.ne_bot, by simp only [hΞΌ, ae_ne_bot, ne.def, not_false_iff], have hc : 0 ≀ c, { have h_exists : βˆƒ x, β€–f xβ€– ≀ c := eventually.exists hf_bound, exact (norm_nonneg _).trans h_exists.some_spec, }, have hfs_bound : βˆ€ n x, β€–fs n xβ€– ≀ c := hf.norm_approx_bounded_le hc, have hn_eq : βˆ€ n, ΞΌ[fs n * g | m] =ᡐ[ΞΌ] fs n * ΞΌ[g | m], from Ξ» n, condexp_strongly_measurable_simple_func_mul hm _ hg, have : ΞΌ[f * ΞΌ[g|m]|m] = f * ΞΌ[g|m], { refine condexp_of_strongly_measurable hm (hf.mul strongly_measurable_condexp) _, exact integrable_condexp.bdd_mul' ((hf.mono hm).ae_strongly_measurable) hf_bound, }, rw ← this, refine tendsto_condexp_unique (Ξ» n x, fs n x * g x) (Ξ» n x, fs n x * ΞΌ[g|m] x) (f * g) (f * ΞΌ[g|m]) _ _ _ _ (Ξ» x, c * β€–g xβ€–) _ (Ξ» x, c * β€–ΞΌ[g|m] xβ€–) _ _ _ _, { exact Ξ» n, hg.bdd_mul' ((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable (eventually_of_forall (hfs_bound n)), }, { exact Ξ» n, integrable_condexp.bdd_mul' ((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable (eventually_of_forall (hfs_bound n)), }, { filter_upwards [hfs_tendsto] with x hx, rw pi.mul_apply, exact tendsto.mul hx tendsto_const_nhds, }, { filter_upwards [hfs_tendsto] with x hx, rw pi.mul_apply, exact tendsto.mul hx tendsto_const_nhds, }, { exact hg.norm.const_mul c, }, { exact integrable_condexp.norm.const_mul c, }, { refine Ξ» n, eventually_of_forall (Ξ» x, _), exact (norm_mul_le _ _).trans (mul_le_mul_of_nonneg_right (hfs_bound n x) (norm_nonneg _)), }, { refine Ξ» n, eventually_of_forall (Ξ» x, _), exact (norm_mul_le _ _).trans (mul_le_mul_of_nonneg_right (hfs_bound n x) (norm_nonneg _)), }, { intros n, simp_rw ← pi.mul_apply, refine (condexp_strongly_measurable_simple_func_mul hm _ hg).trans _, rw condexp_of_strongly_measurable hm ((simple_func.strongly_measurable _).mul strongly_measurable_condexp) _, { apply_instance, }, { apply_instance, }, exact integrable_condexp.bdd_mul' ((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable (eventually_of_forall (hfs_bound n)), }, end lemma condexp_strongly_measurable_mul_of_boundβ‚€ (hm : m ≀ m0) [is_finite_measure ΞΌ] {f g : Ξ± β†’ ℝ} (hf : ae_strongly_measurable' m f ΞΌ) (hg : integrable g ΞΌ) (c : ℝ) (hf_bound : βˆ€α΅ x βˆ‚ΞΌ, β€–f xβ€– ≀ c) : ΞΌ[f * g | m] =ᡐ[ΞΌ] f * ΞΌ[g | m] := begin have : ΞΌ[f * g | m] =ᡐ[ΞΌ] ΞΌ[hf.mk f * g | m], from condexp_congr_ae (eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl), refine this.trans _, have : f * ΞΌ[g | m] =ᡐ[ΞΌ] hf.mk f * ΞΌ[g | m] := eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl, refine eventually_eq.trans _ this.symm, refine condexp_strongly_measurable_mul_of_bound hm hf.strongly_measurable_mk hg c _, filter_upwards [hf_bound, hf.ae_eq_mk] with x hxc hx_eq, rw ← hx_eq, exact hxc, end /-- Pull-out property of the conditional expectation. -/ lemma condexp_strongly_measurable_mul {f g : Ξ± β†’ ℝ} (hf : strongly_measurable[m] f) (hfg : integrable (f * g) ΞΌ) (hg : integrable g ΞΌ) : ΞΌ[f * g | m] =ᡐ[ΞΌ] f * ΞΌ[g | m] := begin by_cases hm : m ≀ m0, swap, { simp_rw condexp_of_not_le hm, rw mul_zero, }, by_cases hΞΌm : sigma_finite (ΞΌ.trim hm), swap, { simp_rw condexp_of_not_sigma_finite hm hΞΌm, rw mul_zero, }, haveI : sigma_finite (ΞΌ.trim hm) := hΞΌm, obtain ⟨sets, sets_prop, h_univ⟩ := hf.exists_spanning_measurable_set_norm_le hm ΞΌ, simp_rw forall_and_distrib at sets_prop, obtain ⟨h_meas, h_finite, h_norm⟩ := sets_prop, suffices : βˆ€ n, βˆ€α΅ x βˆ‚ΞΌ, x ∈ sets n β†’ ΞΌ[f * g|m] x = f x * ΞΌ[g|m] x, { rw ← ae_all_iff at this, filter_upwards [this] with x hx, rw pi.mul_apply, obtain ⟨i, hi⟩ : βˆƒ i, x ∈ sets i, { have h_mem : x ∈ ⋃ i, sets i, { rw h_univ, exact set.mem_univ _, }, simpa using h_mem, }, exact hx i hi, }, refine Ξ» n, ae_imp_of_ae_restrict _, suffices : (ΞΌ.restrict (sets n))[f * g | m] =ᡐ[ΞΌ.restrict (sets n)] f * (ΞΌ.restrict (sets n))[g | m], { simp_rw ← pi.mul_apply, refine (condexp_restrict_ae_eq_restrict hm (h_meas n) hfg).symm.trans _, exact this.trans (eventually_eq.rfl.mul (condexp_restrict_ae_eq_restrict hm (h_meas n) hg)), }, suffices : (ΞΌ.restrict (sets n))[((sets n).indicator f) * g | m] =ᡐ[ΞΌ.restrict (sets n)] ((sets n).indicator f) * (ΞΌ.restrict (sets n))[g | m], { refine eventually_eq.trans _ (this.trans _), { exact condexp_congr_ae ((indicator_ae_eq_restrict (hm _ (h_meas n))).symm.mul eventually_eq.rfl), }, { exact (indicator_ae_eq_restrict (hm _ (h_meas n))).mul eventually_eq.rfl, }, }, haveI : is_finite_measure (ΞΌ.restrict (sets n)), { constructor, rw measure.restrict_apply_univ, exact h_finite n, }, refine condexp_strongly_measurable_mul_of_bound hm (hf.indicator (h_meas n)) hg.integrable_on n _, refine eventually_of_forall (Ξ» x, _), by_cases hxs : x ∈ sets n, { simp only [hxs, set.indicator_of_mem], exact h_norm n x hxs, }, { simp only [hxs, set.indicator_of_not_mem, not_false_iff, _root_.norm_zero, nat.cast_nonneg], }, end /-- Pull-out property of the conditional expectation. -/ lemma condexp_strongly_measurable_mulβ‚€ {f g : Ξ± β†’ ℝ} (hf : ae_strongly_measurable' m f ΞΌ) (hfg : integrable (f * g) ΞΌ) (hg : integrable g ΞΌ) : ΞΌ[f * g | m] =ᡐ[ΞΌ] f * ΞΌ[g | m] := begin have : ΞΌ[f * g | m] =ᡐ[ΞΌ] ΞΌ[hf.mk f * g | m], from condexp_congr_ae (eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl), refine this.trans _, have : f * ΞΌ[g | m] =ᡐ[ΞΌ] hf.mk f * ΞΌ[g | m] := eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl, refine eventually_eq.trans _ this.symm, refine condexp_strongly_measurable_mul hf.strongly_measurable_mk _ hg, refine (integrable_congr _).mp hfg, exact eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl, end end pull_out end measure_theory
a867007d3d7f0047863418c852e072ba43c889e5
263b858cfdc89a2f9d3a4b5f400694bf81ab855d
/mm0-lean/x86/lemmas.lean
1d2544af83639c857ea92d72b42ae39207814177
[ "CC0-1.0" ]
permissive
jcommelin/mm0
97d89e6935cdf21523a6f29904bd0a2a042335cc
7482b84b3518cae5c730ba07d91e23ae978dafd9
refs/heads/master
1,617,826,105,860
1,583,734,867,000
1,583,735,028,000
248,705,227
0
0
CC0-1.0
1,584,693,150,000
1,584,693,150,000
null
UTF-8
Lean
false
false
62,601
lean
import x86.x86 data.list.basic data.zmod.basic theorem bool.coe_bool_iff : βˆ€ {a b : bool}, (a ↔ b) ↔ a = b := dec_trivial namespace bitvec theorem of_nat_zero (n) : bitvec.of_nat n 0 = 0 := by induction n; [refl, exact congr_arg (vector.cons ff) n_ih] theorem of_nat_one (n) : bitvec.of_nat n 1 = 1 := by cases n; [refl, exact congr_arg (vector.cons tt) (of_nat_zero _)] theorem from_bits_fill_eq : βˆ€ {n b l} (e : list.length l = n), from_bits_fill b l = ⟨l, e⟩ | 0 b [] e := rfl | (n+1) b (a :: l) e := by rw [from_bits_fill, from_bits_fill_eq (nat.succ_inj e)]; refl theorem bits_to_nat_zero (n) : bits_to_nat (list.repeat ff n) = 0 := by simp [bits_to_nat]; induction n; simp * @[simp] theorem bits_to_nat_cons (a l) : bits_to_nat (a :: l) = nat.bit a (bits_to_nat l) := rfl @[simp] theorem to_nat_nil : to_nat vector.nil = 0 := rfl @[simp] theorem to_nat_zero (n) : to_nat (0 : bitvec n) = 0 := bits_to_nat_zero _ @[simp] theorem to_nat_cons (b) {n} (v : bitvec n) : to_nat (b :: v) = nat.bit b (to_nat v) := by cases v; refl @[simp] theorem of_nat_succ (n i : β„•) : bitvec.of_nat n.succ i = i.bodd :: bitvec.of_nat n i.div2 := by rw [bitvec.of_nat, nat.bodd_div2_eq, bitvec.of_nat] @[simp] theorem of_nat_bit (n : β„•) (b i) : bitvec.of_nat n.succ (nat.bit b i) = b :: bitvec.of_nat n i := by rw [of_nat_succ, nat.div2_bit, nat.bodd_bit] theorem of_nat_bits_to_nat {n} (l : list bool) : bitvec.of_nat n (bits_to_nat l) = from_bits_fill ff l := begin rw bits_to_nat, induction l generalizing n, exact of_nat_zero _, cases n, refl, simp [*, bits_to_nat, from_bits_fill, bitvec.of_nat, nat.bodd_bit, nat.div2_bit] end theorem of_nat_bits_to_nat_eq {n} (l : list bool) (e : l.length = n) : bitvec.of_nat n (bits_to_nat l) = ⟨l, e⟩ := begin induction n generalizing l; cases l; injection e, refl, simp [bits_to_nat, nat.div2_bit, nat.bodd_bit], exact congr_arg (vector.cons l_hd) (n_ih _ h_1) end @[simp] theorem of_nat_to_nat : βˆ€ {n} (v : bitvec n), bitvec.of_nat n (to_nat v) = v | n ⟨l, e⟩ := of_nat_bits_to_nat_eq l e theorem to_nat_of_nat_aux (m n b) : nat.bit b (n % 2 ^ m) = nat.bit b n % 2 ^ nat.succ m := begin have := nat.mod_add_div (n.bit b) (2^m * 2), conv at this { to_rhs, rw [nat.bit_val, ← nat.mod_add_div n (2^m), mul_add, add_right_comm, ← nat.bit_val, mul_left_comm, ← mul_assoc] }, rw [nat.pow_succ], refine add_right_cancel (this.symm.trans _), congr' 2, rw [mul_comm, ← nat.div_div_eq_div_mul, ← nat.div2_val, nat.div2_bit] end theorem to_nat_of_nat (m n) : to_nat (bitvec.of_nat m n) = n % 2 ^ m := begin induction m generalizing n, { simp [bitvec.of_nat, to_nat], refl }, simp [bitvec.of_nat, m_ih], conv { to_rhs, rw ← nat.bit_decomp n }, apply to_nat_of_nat_aux end theorem to_nat_lt_pow2 {n} (v : bitvec n) : to_nat v < 2 ^ n := begin rw [← of_nat_to_nat v, to_nat_of_nat], exact nat.mod_lt _ (nat.pow_pos dec_trivial _), end def pow2 (n : β„•) : β„•+ := ⟨2^n, nat.pow_pos dec_trivial _⟩ def to_zmod {n} (v : bitvec n) : zmod (pow2 n) := bitvec.to_nat v def of_zmod {n} (i : zmod (pow2 n)) : bitvec n := bitvec.of_nat _ i.1 theorem to_zmod_of_zmod {n} (i : zmod (pow2 n)) : to_zmod (of_zmod i) = i := ((zmod.eq_iff_modeq_nat' _).2 (by convert nat.modeq.mod_modeq _ _; apply to_nat_of_nat)).trans (zmod.cast_val _) theorem of_zmod_to_zmod {n} (v : bitvec n) : of_zmod (to_zmod v) = v := by unfold of_zmod to_zmod; convert of_nat_to_nat v; exact zmod.val_cast_of_lt (to_nat_lt_pow2 _) theorem of_nat_eq_iff_modeq {m n₁ nβ‚‚} : bitvec.of_nat m n₁ = bitvec.of_nat m nβ‚‚ ↔ n₁ ≑ nβ‚‚ [MOD 2 ^ m] := begin dunfold nat.modeq, split; intro h, { rw [← to_nat_of_nat, h, to_nat_of_nat] }, { rw [← of_nat_to_nat (bitvec.of_nat m n₁), to_nat_of_nat, h, ← to_nat_of_nat, of_nat_to_nat] }, end theorem of_nat_eq_of_zmod (m n) : bitvec.of_nat m n = bitvec.of_zmod n := eq.symm $ of_nat_eq_iff_modeq.2 $ by convert nat.modeq.mod_modeq _ _; apply zmod.val_cast_nat theorem to_zmod_zero (n) : to_zmod (0 : bitvec n) = 0 := by rw [to_zmod, to_nat_zero]; refl theorem of_zmod_zero (n) : (of_zmod 0 : bitvec n) = 0 := by rw [← to_zmod_zero, of_zmod_to_zmod] theorem of_zmod_one (n) : (of_zmod 1 : bitvec n) = 1 := begin cases n, {refl}, change bitvec.of_nat _ (1 % 2 ^ _) = _, rw [nat.mod_eq_of_lt, of_nat_one], exact @nat.pow_lt_pow_of_lt_right _ dec_trivial 0 _ (nat.succ_pos _) end theorem to_zmod_one (n) : to_zmod (1 : bitvec n) = 1 := by rw [← of_zmod_one, to_zmod_of_zmod] theorem to_zmod_add {n} (a b : bitvec n) : to_zmod (a + b) = to_zmod a + to_zmod b := show to_zmod (bitvec.of_nat _ _) = _, by rw [of_nat_eq_of_zmod, to_zmod_of_zmod, to_zmod, to_zmod, nat.cast_add] theorem to_zmod_mul {n} (a b : bitvec n) : to_zmod (a * b) = to_zmod a * to_zmod b := show to_zmod (bitvec.of_nat _ _) = _, by rw [of_nat_eq_of_zmod, to_zmod_of_zmod, to_zmod, to_zmod, nat.cast_mul] theorem to_zmod_neg {n} (a : bitvec n) : to_zmod (-a) = -to_zmod a := show to_zmod (bitvec.of_nat _ _) = _, begin rw [of_nat_eq_of_zmod, to_zmod_of_zmod, eq_neg_iff_add_eq_zero, to_zmod, ← nat.cast_add, nat.sub_add_cancel (le_of_lt (to_nat_lt_pow2 _))], exact zmod.cast_self_eq_zero, end theorem of_zmod_add {n} (a b : zmod (pow2 n)) : of_zmod (a + b) = of_zmod a + of_zmod b := by conv_lhs {rw [← to_zmod_of_zmod a, ← to_zmod_of_zmod b]}; rw [← to_zmod_add, of_zmod_to_zmod] theorem of_zmod_mul {n} (a b : zmod (pow2 n)) : of_zmod (a * b) = of_zmod a * of_zmod b := by conv_lhs {rw [← to_zmod_of_zmod a, ← to_zmod_of_zmod b]}; rw [← to_zmod_mul, of_zmod_to_zmod] theorem of_zmod_neg {n} (a : zmod (pow2 n)) : of_zmod (-a) = -of_zmod a := by conv_lhs {rw [← to_zmod_of_zmod a]}; rw [← to_zmod_neg, of_zmod_to_zmod] instance (n : β„•) : add_comm_semigroup (bitvec n) := { add_assoc := Ξ» a b c, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_to_zmod c, ← of_zmod_add, ← of_zmod_add, add_assoc, of_zmod_add, of_zmod_add], add_comm := Ξ» a b, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_add, add_comm, of_zmod_add], ..bitvec.has_add } instance (n : β„•) : comm_semigroup (bitvec n) := { mul_assoc := Ξ» a b c, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_to_zmod c, ← of_zmod_mul, ← of_zmod_mul, mul_assoc, of_zmod_mul, of_zmod_mul], mul_comm := Ξ» a b, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_mul, mul_comm, of_zmod_mul], ..bitvec.has_mul } instance (n : β„•) : comm_ring (bitvec n) := { zero_add := Ξ» a, by rw [← of_zmod_to_zmod a, ← of_zmod_zero, ← of_zmod_add, zero_add], add_zero := Ξ» a, by rw [← of_zmod_to_zmod a, ← of_zmod_zero, ← of_zmod_add, add_zero], add_left_neg := Ξ» a, by rw [← of_zmod_to_zmod a, ← of_zmod_neg, ← of_zmod_add, add_left_neg, ← of_zmod_zero], one_mul := Ξ» a, by rw [← of_zmod_to_zmod a, ← of_zmod_one, ← of_zmod_mul, one_mul], mul_one := Ξ» a, by rw [← of_zmod_to_zmod a, ← of_zmod_one, ← of_zmod_mul, mul_one], left_distrib := Ξ» a b c, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_to_zmod c, ← of_zmod_add, ← of_zmod_mul, left_distrib, of_zmod_add, of_zmod_mul, of_zmod_mul]; refl, right_distrib := Ξ» a b c, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_to_zmod c, ← of_zmod_add, ← of_zmod_mul, right_distrib, of_zmod_add, of_zmod_mul, of_zmod_mul]; refl, ..bitvec.has_zero, ..bitvec.has_one, ..bitvec.has_neg, ..bitvec.add_comm_semigroup n, ..bitvec.comm_semigroup n } theorem to_nat_nth {n} (i j) : (bitvec.of_nat n i).nth j = i.test_bit j.1 := begin generalize e : bitvec.of_nat n i = v, cases v with l e', cases j with j h, rw [vector.nth], dsimp only, induction n generalizing i l j, cases h, cases l; injection e', simp [bitvec.of_nat] at e, generalize_hyp eβ‚‚ : bitvec.of_nat n_n i.div2 = v at e, cases v with l eβ‚‚', injection e, cases h_2, cases j; simp, refl, rw [← nat.bit_decomp i, nat.test_bit_succ], exact n_ih _ _ _ _ eβ‚‚ (nat.lt_of_succ_lt_succ h) end theorem of_nat_from_bits_fill (n m i) (h : n ≀ m) : bitvec.of_nat n i = from_bits_fill ff (bitvec.of_nat m i).1 := begin generalize e : bitvec.of_nat m i = v, cases v with l h, simp, induction n generalizing m i l e, exact (vector.eq_nil _).trans (vector.eq_nil _).symm, rw [of_nat_succ], cases m, cases h, rw [of_nat_succ] at e, generalize e' : bitvec.of_nat m i.div2 = v, cases v with l' h', rw e' at e, injection e, subst l, rw [n_ih _ _ (nat.le_of_succ_le_succ h) _ _ e', from_bits_fill], end theorem of_nat_bit0_aux {n} (j : bitvec (nat.succ n)) : bit0 j = ff :: from_bits_fill ff (j.val) := begin change bitvec.of_nat n.succ (bit0 (to_nat j)) = _, rw [of_nat_succ, nat.bodd_bit0, nat.div2_bit0, to_nat, of_nat_bits_to_nat] end theorem of_nat_bit0 (n i) : bitvec.of_nat n (bit0 i) = bit0 (bitvec.of_nat n i) := begin induction n generalizing i, refl, rw [of_nat_succ, nat.bodd_bit0, nat.div2_bit0], rw [of_nat_from_bits_fill _ _ _ (nat.le_succ _)], generalize : bitvec.of_nat n_n.succ i = j, rw of_nat_bit0_aux, end theorem of_nat_bit1 (n i) : bitvec.of_nat n (bit1 i) = bit1 (bitvec.of_nat n i) := begin induction n generalizing i, refl, rw [of_nat_succ, nat.bodd_bit1, nat.div2_bit1], rw [of_nat_from_bits_fill _ _ _ (nat.le_succ _)], generalize : bitvec.of_nat n_n.succ i = j, change _ = bitvec.of_nat _ (to_nat (bit0 j) + bit0 (@to_nat n_n 0) + 1), rw [to_nat_zero], change _ = bitvec.of_nat _ (to_nat (bit0 j) + 1), rw [of_nat_bit0_aux, to_nat_cons], change _ = bitvec.of_nat _ (nat.bit tt _), rw [of_nat_bit, of_nat_to_nat], end theorem add_nat_assoc {n} (v : bitvec n) (a b : β„•) : v + a + b = v + (a + b : β„•) := by rw [nat.cast_add, add_assoc] theorem of_nat_add {n} (a b : β„•) : bitvec.of_nat n (a + b) = bitvec.of_nat n a + bitvec.of_nat n b := by simp [of_nat_eq_of_zmod, of_zmod_add] theorem of_nat_succ' {n} (a : β„•) : bitvec.of_nat n a.succ = bitvec.of_nat n a + 1 := (of_nat_add a 1).trans $ by simp [of_nat_one] theorem of_nat_mul {n} (a b : β„•) : bitvec.of_nat n (a * b) = bitvec.of_nat n a * bitvec.of_nat n b := by simp [of_nat_eq_of_zmod, of_zmod_mul] theorem coe_eq_of_nat {n} (a : β„•) : (a : bitvec n) = bitvec.of_nat n a := begin induction a, exact (bitvec.of_nat_zero _).symm, rw [of_nat_succ', ← a_ih], refl, end theorem coe_to_nat {n} (v : bitvec n) : (to_nat v : bitvec n) = v := by rw [coe_eq_of_nat, of_nat_to_nat] theorem bits_to_nat_inj : βˆ€ {l₁ lβ‚‚}, bits_to_nat l₁ = bits_to_nat lβ‚‚ β†’ l₁.length = lβ‚‚.length β†’ l₁ = lβ‚‚ | [] [] _ _ := rfl | (a :: l₁) (b :: lβ‚‚) e e' := begin rw [bits_to_nat_cons, bits_to_nat_cons] at e, rw [← nat.bodd_bit a (bits_to_nat l₁), e, nat.bodd_bit, @bits_to_nat_inj l₁ lβ‚‚ _ (nat.succ_inj e')], rw [← nat.div2_bit a (bits_to_nat l₁), e, nat.div2_bit] end theorem to_nat_inj {n v₁ vβ‚‚} (h : @bitvec.to_nat n v₁ = bitvec.to_nat vβ‚‚) : v₁ = vβ‚‚ := subtype.eq $ bits_to_nat_inj h (v₁.2.trans vβ‚‚.2.symm) theorem coe_shl {n} (a b) : (nat.shiftl a b : bitvec n) = bitvec.shl a b := begin rw [shl, coe_eq_of_nat, nat.shiftl_eq_mul_pow, nat.shiftl_eq_mul_pow], refine of_nat_eq_iff_modeq.2 (nat.modeq.modeq_mul_right _ _), rw [← of_nat_eq_iff_modeq, of_nat_to_nat, coe_eq_of_nat], end theorem sign_iff_neg {n v} : @bitvec.sign n v ↔ bitvec.to_int v < 0 := begin unfold bitvec.to_int, cases sign v; simp, apply sub_lt_zero.2, norm_cast, exact to_nat_lt_pow2 _ end theorem to_int_inj {n v₁ vβ‚‚} (h : @bitvec.to_int n v₁ = bitvec.to_int vβ‚‚) : v₁ = vβ‚‚ := begin have : sign v₁ = sign vβ‚‚, { apply bool.coe_bool_iff.1, rw [sign_iff_neg, sign_iff_neg, h] }, revert h, unfold bitvec.to_int, rw this, cases sign vβ‚‚; simp; exact to_nat_inj end theorem pow2_eq_zero {n} : (2 ^ n : bitvec n) = 0 := begin suffices : ((2 ^ n : β„•) : bitvec n) = 0, {exact_mod_cast this}, have := to_nat_of_nat n (2^n), apply to_nat_inj, rw [coe_eq_of_nat, to_nat_of_nat, nat.mod_self, to_nat_zero], end theorem coe_to_int {n} (v : bitvec n) : (to_int v : bitvec n) = v := by unfold to_int; cases sign v; simp [coe_to_nat, pow2_eq_zero] @[class] def reify {n} (v : bitvec n) (l : out_param (list bool)) : Prop := from_bits_fill ff l = v theorem reify.mk {n} (v) {l} [h : @reify n v l] : from_bits_fill ff l = v := h theorem reify_eq {n v l l'} [@reify n v l] (h : l' = v.1) : l' = (@from_bits_fill ff l n).1 := by rwa reify.mk v theorem reify_eq' {n v l l'} [@reify n v l] (h : l' = v) : l' = @from_bits_fill ff l n := by rwa reify.mk v theorem reify_eqβ‚‚ {n v₁ l₁ vβ‚‚ lβ‚‚} [@reify n v₁ l₁] [@reify n vβ‚‚ lβ‚‚] (h : v₁ = vβ‚‚) : @from_bits_fill ff l₁ n = from_bits_fill ff lβ‚‚ := by rwa [reify.mk v₁, reify.mk vβ‚‚] theorem reify_iff {n v l} : @reify n v l ↔ bitvec.of_nat n (bits_to_nat l) = v := iff_of_eq $ congr_arg (= v) (of_nat_bits_to_nat _).symm instance reify_0 {n} : @reify n 0 [] := rfl instance reify_1 {n} : @reify n 1 [tt] := by cases n; exact rfl instance reify_bit0 {n} (v l) [h : @reify n v l] : reify (bit0 v) (ff :: l) := reify_iff.2 $ by have := of_nat_bit0 n (bits_to_nat l); rwa [reify_iff.1 h] at this instance reify_bit1 {n} (v l) [h : @reify n v l] : reify (bit1 v) (tt :: l) := reify_iff.2 $ by have := of_nat_bit1 n (bits_to_nat l); rwa [reify_iff.1 h] at this end bitvec namespace x86 def split_bits_spec : list (Ξ£ n, bitvec n) β†’ list bool β†’ Prop | [] l := list.all l bnot | (⟨n, v⟩ :: s) l := let ⟨l₁, lβ‚‚βŸ© := l.split_at n in (@bitvec.from_bits_fill ff l₁ n).1 = v.1 ∧ split_bits_spec s lβ‚‚ theorem split_bits_ok {l s} : split_bits (bitvec.bits_to_nat l) s β†’ split_bits_spec s l := begin generalize e₁ : bitvec.bits_to_nat l = n, induction s generalizing l n, rintro ⟨⟩, { induction l, constructor, cases l_hd, { exact bool.band_intro rfl (l_ih (not_imp_not.1 (nat.bit_ne_zero _) e₁)) }, { cases nat.bit1_ne_zero _ e₁ } }, { rcases s_hd with ⟨i, l', eβ‚‚βŸ©, unfold split_bits_spec, generalize e₃ : l.split_at i = p, cases p with l₁ lβ‚‚, dsimp [split_bits_spec], induction i with i generalizing l' l₁ lβ‚‚ eβ‚‚ l n; cases l'; injection eβ‚‚, { cases h_2, cases e₃, exact ⟨rfl, s_ih _ e₁ h_2_a⟩ }, { generalize_hyp eβ‚„ : (⟨l'_hd :: l'_tl, eβ‚‚βŸ© : bitvec _) = f at h_2, cases h_2, cases h_2_bs with _ pr, injection eβ‚„, cases h_3, generalize eβ‚… : l.tail.split_at i = p, cases p with l₁' lβ‚‚', have : bitvec.bits_to_nat l.tail = nat.div2 n, { subst e₁, cases l, refl, exact (nat.div2_bit _ _).symm }, rcases i_ih _ _ _ h_1 _ this eβ‚… h_2_a with ⟨e₆, h'⟩, replace e₆ : bitvec.from_bits_fill ff l₁' = ⟨l'_tl, pr⟩ := subtype.eq e₆, cases l, { cases e₃, have : (l₁', lβ‚‚') = ([], []), {cases i; cases eβ‚…; refl}, cases this, simp [bitvec.from_bits_fill, h', vector.repeat] at e₆ ⊒, cases e₁, exact ⟨rfl, eβ‚†βŸ© }, { rw [list.split_at, show l_tl.split_at i = (l₁', lβ‚‚'), from eβ‚…] at e₃, cases e₃, rw [bitvec.from_bits_fill, ← e₁, e₆], refine ⟨_, h'⟩, simp [vector.cons], exact (nat.bodd_bit _ _).symm } } } end theorem split_bits.determ_l {n₁ nβ‚‚ l} (h₁ : split_bits n₁ l) (hβ‚‚ : split_bits nβ‚‚ l) : n₁ = nβ‚‚ := begin induction l generalizing n₁ nβ‚‚, {cases h₁, cases hβ‚‚, refl}, rcases l_hd with ⟨_, l', rfl⟩, induction l' generalizing n₁ nβ‚‚, { cases h₁, cases hβ‚‚, exact l_ih h₁_a hβ‚‚_a }, { have : βˆ€ {n l'}, split_bits n l' β†’ l' = ⟨_, l'_hd :: l'_tl, rfl⟩ :: l_tl β†’ l'_hd = nat.bodd n ∧ split_bits (nat.div2 n) (⟨_, l'_tl, rfl⟩ :: l_tl), { intros, cases a; try {cases a_1}, rcases a_bs with ⟨lβ‚‚, rfl⟩, injection a_1, cases h_2, cases congr_arg (Ξ» v : Ξ£ n, bitvec n, v.2.1) h_1, exact ⟨rfl, a_a⟩ }, rcases this h₁ rfl with ⟨rfl, h₁'⟩, rcases this hβ‚‚ rfl with ⟨e, hβ‚‚'⟩, rw [← nat.bit_decomp n₁, e, l'_ih h₁' hβ‚‚', nat.bit_decomp] } end theorem split_bits.determ {n l₁ lβ‚‚} (h₁ : split_bits n l₁) (hβ‚‚ : split_bits n lβ‚‚) (h : l₁.map sigma.fst = lβ‚‚.map sigma.fst) : l₁ = lβ‚‚ := begin induction l₁ generalizing n lβ‚‚; cases lβ‚‚; injection h, refl, cases l₁_hd with i v₁, cases lβ‚‚_hd with _ vβ‚‚, cases h_1, clear h h_1, induction i with i generalizing v₁ vβ‚‚ n, { cases h₁, cases hβ‚‚, rw l₁_ih h₁_a hβ‚‚_a h_2 }, { cases h₁, cases hβ‚‚, cases i_ih _ _ h₁_a hβ‚‚_a, refl } end theorem bits_to_byte.determ_l {n m w1 w2 l} : @bits_to_byte n m w1 l β†’ @bits_to_byte n m w2 l β†’ w1 = w2 | ⟨e₁, hβ‚βŸ© ⟨_, hβ‚‚βŸ© := bitvec.to_nat_inj $ split_bits.determ_l h₁ hβ‚‚ theorem bits_to_byte.determ_l_aux {n m w1 w2 l l'} : @bits_to_byte n m w1 l β†’ @bits_to_byte n m w2 (l ++ l') β†’ (w1, l') = (w2, []) | ⟨e₁, hβ‚βŸ© ⟨eβ‚‚, hβ‚‚βŸ© := begin simp, suffices, refine ⟨_, this⟩, swap, { apply list.length_eq_zero.1, apply @eq_of_add_eq_add_left _ _ l.length, rw [add_zero, ← list.length_append, e₁, eβ‚‚] }, clear bits_to_byte.determ_l_aux, subst this, rw list.append_nil at hβ‚‚, exact bitvec.to_nat_inj (split_bits.determ_l h₁ hβ‚‚) end theorem bits_to_byte.determ {n m w l1 l2} : @bits_to_byte n m w l1 β†’ @bits_to_byte n m w l2 β†’ l1 = l2 | ⟨e₁, hβ‚βŸ© ⟨eβ‚‚, hβ‚‚βŸ© := list.injective_map_iff.2 (by rintro x y ⟨⟩; refl) (split_bits.determ h₁ hβ‚‚ (by rw [list.map_map, list.map_map, (_ : _∘_ = _), list.map_const _ 8, e₁, list.map_const, eβ‚‚]; refl)) theorem read_prefixes.determ {r₁ rβ‚‚ l} : read_prefixes r₁ l β†’ read_prefixes rβ‚‚ l β†’ r₁ = rβ‚‚ := begin intros h₁ hβ‚‚, cases h₁; cases hβ‚‚; congr, cases split_bits.determ h₁_a hβ‚‚_a rfl, refl, end @[elab_as_eliminator] theorem byte_split {C : byte β†’ Sort*} : βˆ€ b : byte, (βˆ€ b0 b1 b2 b3 b4 b5 b6 b7, C ⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩) β†’ C b | ⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ H := H _ _ _ _ _ _ _ _ def binop.from_bits : βˆ€ (b0 b1 b2 b3 : bool), binop | ff ff ff ff := binop.add | tt ff ff ff := binop.or | ff tt ff ff := binop.adc | tt tt ff ff := binop.sbb | ff ff tt ff := binop.and | tt ff tt ff := binop.sub | ff tt tt ff := binop.xor | tt tt tt ff := binop.cmp | ff ff ff tt := binop.rol | tt ff ff tt := binop.ror | ff tt ff tt := binop.rcl | tt tt ff tt := binop.rcr | ff ff tt tt := binop.shl | tt ff tt tt := binop.shr | ff tt tt tt := binop.tst | tt tt tt tt := binop.sar theorem binop.bits_eq {b0 b1 b2 b3 e op} : binop.bits op ⟨[b0, b1, b2, b3], e⟩ β†’ op = binop.from_bits b0 b1 b2 b3 := begin generalize e' : (⟨[b0, b1, b2, b3], e⟩ : bitvec 4) = v, intro h, induction h; { cases bitvec.reify_eq (congr_arg subtype.val e'), refl } end theorem binop.bits.determ : βˆ€ {op1 op2 v}, binop.bits op1 v β†’ binop.bits op2 v β†’ op1 = op2 | op1 op2 ⟨[b0, b1, b2, b3], _⟩ h1 h2 := (binop.bits_eq h1).trans (binop.bits_eq h2).symm def basic_cond.from_bits : βˆ€ (b0 b1 b2 : bool), option basic_cond | ff ff ff := some basic_cond.o | tt ff ff := some basic_cond.b | ff tt ff := some basic_cond.e | tt tt ff := some basic_cond.na | ff ff tt := some basic_cond.s | tt ff tt := none | ff tt tt := some basic_cond.l | tt tt tt := some basic_cond.ng theorem basic_cond.bits_eq {b0 b1 b2 e c} : basic_cond.bits c ⟨[b0, b1, b2], e⟩ β†’ basic_cond.from_bits b0 b1 b2 = some c := begin generalize e' : (⟨[b0, b1, b2], e⟩ : bitvec 3) = v, intro h, induction h; { cases bitvec.reify_eq (congr_arg subtype.val e'), refl } end def cond_code.from_bits (b0 b1 b2 b3 : bool) : option cond_code := option.map (cond_code.mk b0) (basic_cond.from_bits b1 b2 b3) theorem cond_code.bits_eq {b0 b1 b2 b3 e c} : cond_code.bits c ⟨[b0, b1, b2, b3], e⟩ β†’ cond_code.from_bits b0 b1 b2 b3 = some c := begin rintro ⟨⟩, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases subtype.eq h₁, rw [cond_code.from_bits, basic_cond.bits_eq a_a_1], refl end theorem cond_code.bits.determ : βˆ€ {c1 c2 v}, cond_code.bits c1 v β†’ cond_code.bits c2 v β†’ c1 = c2 | c1 c2 ⟨[b0, b1, b2, b3], _⟩ h1 h2 := option.some_inj.1 $ (cond_code.bits_eq h1).symm.trans (cond_code.bits_eq h2) theorem read_displacement_ne_3 {mod disp l} : read_displacement mod disp l β†’ mod β‰  3 := by rintro ⟨⟩ ⟨⟩ theorem read_displacement.determ_aux {mod disp1 disp2 l l'} (h₁ : read_displacement mod disp1 l) (hβ‚‚ : read_displacement mod disp2 (l ++ l')) : (disp1, l') = (disp2, []) := begin cases h₁; cases hβ‚‚; try {refl}, cases bits_to_byte.determ_l_aux h₁_a hβ‚‚_a, refl end theorem read_displacement.determ {mod disp1 disp2 l} (h₁ : read_displacement mod disp1 l) (hβ‚‚ : read_displacement mod disp2 l) : disp1 = disp2 := by cases read_displacement.determ_aux h₁ (by rw list.append_nil; exact hβ‚‚); refl theorem read_sib_displacement_ne_3 {mod bbase w Base l} : read_sib_displacement mod bbase w Base l β†’ mod β‰  3 := by rw [read_sib_displacement]; split_ifs; [ {rcases h with ⟨_, rfl⟩; rintro _ ⟨⟩}, exact Ξ» h, read_displacement_ne_3 h.1] theorem read_sib_displacement.determ_aux {mod bbase w1 w2 Base1 Base2 l l'} (h₁ : read_sib_displacement mod bbase w1 Base1 l) (hβ‚‚ : read_sib_displacement mod bbase w2 Base2 (l ++ l')) : (w1, Base1, l') = (w2, Base2, []) := begin rw read_sib_displacement at h₁ hβ‚‚, split_ifs at h₁ hβ‚‚, { rcases h₁ with ⟨b, rfl, rfl, rfl⟩, rcases hβ‚‚ with ⟨_, rfl, rfl, ⟨⟩⟩, refl }, { rcases h₁ with ⟨h1, rfl⟩, rcases hβ‚‚ with ⟨h2, rfl⟩, cases read_displacement.determ_aux h1 h2, refl }, end theorem read_sib_displacement.determ {mod bbase w1 w2 Base1 Base2 l} (h₁ : read_sib_displacement mod bbase w1 Base1 l) (hβ‚‚ : read_sib_displacement mod bbase w2 Base2 l) : (w1, Base1) = (w2, Base2) := by cases read_sib_displacement.determ_aux h₁ (by rw list.append_nil; exact hβ‚‚); refl theorem read_SIB_ne_3 {rex mod rm l} : read_SIB rex mod rm l β†’ mod β‰  3 := by rintro ⟨⟩; exact read_sib_displacement_ne_3 a_a_1 theorem read_SIB.determ_aux {rex mod rm1 rm2 l l'} (h₁ : read_SIB rex mod rm1 l) (hβ‚‚ : read_SIB rex mod rm2 (l ++ l')) : (rm1, l') = (rm2, []) := begin cases h₁, cases hβ‚‚, cases split_bits.determ h₁_a hβ‚‚_a rfl, cases read_sib_displacement.determ_aux h₁_a_1 hβ‚‚_a_1, refl end theorem read_SIB.determ {rex mod rm1 rm2 l} (h₁ : read_SIB rex mod rm1 l) (hβ‚‚ : read_SIB rex mod rm2 l) : rm1 = rm2 := by cases read_SIB.determ_aux h₁ (by rw list.append_nil; exact hβ‚‚); refl theorem read_ModRM_nil {rex reg r} : Β¬ read_ModRM rex reg r [] := by rintro ⟨⟩ def read_ModRM' (rex : REX) (r : RM) (rm : bitvec 3) (mod : bitvec 2) (l : list byte) : Prop := if mod = 3 then r = RM.reg (rex_reg rex.B rm) ∧ l = [] else if rm = 4 then read_SIB rex mod r l else if rm = 5 ∧ mod = 0 then βˆƒ i : word, i.to_list_byte l ∧ r = RM.mem none base.rip (EXTS i) else βˆƒ disp, read_displacement mod disp l ∧ r = RM.mem none (base.reg (rex_reg rex.B rm)) disp theorem read_ModRM_ModRM' {rex : REX} {reg : regnum} {r : RM} {rm reg_opc : bitvec 3} {mod : bitvec 2} {b : byte} {l : list byte} (h₁ : split_bits b.to_nat [⟨3, rm⟩, ⟨3, reg_opc⟩, ⟨2, mod⟩]) (hβ‚‚ : read_ModRM rex reg r (b :: l)) : reg = rex_reg rex.R reg_opc ∧ read_ModRM' rex r rm mod l := begin generalize_hyp e : list.cons b l = l' at hβ‚‚, induction hβ‚‚; cases e; cases split_bits.determ h₁ hβ‚‚_a rfl; refine ⟨rfl, _⟩, { rw [read_ModRM', if_neg, if_neg, if_pos], exact ⟨_, hβ‚‚_a_1, rfl⟩, all_goals {exact dec_trivial} }, { rw [read_ModRM', if_pos], exact ⟨rfl, rfl⟩, exact dec_trivial }, { rw [read_ModRM', if_neg (read_SIB_ne_3 hβ‚‚_a_1), if_pos], exact hβ‚‚_a_1, refl }, { rw [read_ModRM', if_neg (read_displacement_ne_3 hβ‚‚_a_3), if_neg hβ‚‚_a_1, if_neg hβ‚‚_a_2], exact ⟨_, hβ‚‚_a_3, rfl⟩ }, end theorem read_ModRM_split {rex reg r b l} (h : read_ModRM rex reg r (b :: l)) : βˆƒ rm reg_opc mod, split_bits b.to_nat [⟨3, rm⟩, ⟨3, reg_opc⟩, ⟨2, mod⟩] := by cases h; exact ⟨_, _, _, by assumption⟩ theorem read_ModRM.determ_aux {rex reg1 r1 reg2 r2 l l'} (h₁ : read_ModRM rex reg1 r1 l) (hβ‚‚ : read_ModRM rex reg2 r2 (l ++ l')) : (reg1, r1, l') = (reg2, r2, []) := begin simp, cases l with b l, {cases read_ModRM_nil h₁}, rcases read_ModRM_split h₁ with ⟨rm, reg_opc, r, s⟩, rcases read_ModRM_ModRM' s h₁ with ⟨rfl, h₁'⟩, rcases read_ModRM_ModRM' s hβ‚‚ with ⟨rfl, hβ‚‚'⟩, refine ⟨rfl, _⟩, clear h₁ hβ‚‚ s, unfold read_ModRM' at h₁' hβ‚‚', split_ifs at h₁' hβ‚‚', { rw h₁'.2 at hβ‚‚', exact ⟨h₁'.1.trans hβ‚‚'.1.symm, hβ‚‚'.2⟩ }, { cases read_SIB.determ_aux h₁' hβ‚‚', exact ⟨rfl, rfl⟩ }, { rcases h₁' with ⟨i1, h11, h12⟩, rcases hβ‚‚' with ⟨i2, h21, h22⟩, cases bits_to_byte.determ_l_aux h11 h21, exact ⟨h12.trans h22.symm, rfl⟩ }, { rcases h₁' with ⟨i1, h11, h12⟩, rcases hβ‚‚' with ⟨i2, h21, h22⟩, cases read_displacement.determ_aux h11 h21, exact ⟨h12.trans h22.symm, rfl⟩ }, end theorem read_ModRM.determ {rex reg1 r1 reg2 r2 l} (h₁ : read_ModRM rex reg1 r1 l) (hβ‚‚ : read_ModRM rex reg2 r2 l) : (reg1, r1) = (reg2, r2) := by cases read_ModRM.determ_aux h₁ (by rw list.append_nil; exact hβ‚‚); refl theorem read_ModRM.determβ‚‚ {rex reg1 r1 reg2 r2 l1 l2 l1' l2'} (h₁ : read_ModRM rex reg1 r1 l1) (hβ‚‚ : read_ModRM rex reg2 r2 l2) (e : l1 ++ l1' = l2 ++ l2') : (reg1, r1, l1, l1') = (reg2, r2, l2, l2') := begin have : βˆ€ {reg1 r1 reg2 r2 l1 l2 l1' l2'} (h₁ : read_ModRM rex reg1 r1 l1) (hβ‚‚ : read_ModRM rex reg2 r2 l2) (e : βˆƒ a', l2 = l1 ++ a' ∧ l1' = a' ++ l2'), (l1, l1') = (l2, l2'), { intros, rcases e_1 with ⟨l3, rfl, rfl⟩, cases read_ModRM.determ_aux h₁_1 hβ‚‚_1, simp }, cases (list.append_eq_append_iff.1 e).elim (Ξ» h, this h₁ hβ‚‚ h) (Ξ» h, (this hβ‚‚ h₁ h).symm), cases read_ModRM.determ h₁ hβ‚‚, refl, end theorem read_opcode_ModRM.determ_aux {rex v1 r1 v2 r2 l l'} (h₁ : read_opcode_ModRM rex v1 r1 l) (hβ‚‚ : read_opcode_ModRM rex v2 r2 (l ++ l')) : (v1, r1, l') = (v2, r2, []) := begin cases h₁, cases hβ‚‚, cases read_ModRM.determ_aux h₁_a hβ‚‚_a, cases split_bits.determ h₁_a_1 hβ‚‚_a_1 rfl, refl, end theorem read_opcode_ModRM.determ {rex v1 r1 v2 r2 l} (h₁ : read_opcode_ModRM rex v1 r1 l) (hβ‚‚ : read_opcode_ModRM rex v2 r2 l) : (v1, r1) = (v2, r2) := by cases read_opcode_ModRM.determ_aux h₁ (by rw list.append_nil; exact hβ‚‚); refl theorem read_opcode_ModRM.determβ‚‚_aux {rex v1 r1 v2 r2 l1 l2 l1' l2' l'} (h₁ : read_opcode_ModRM rex v1 r1 l1) (hβ‚‚ : read_opcode_ModRM rex v2 r2 l2) (e : l1 ++ l1' ++ l' = l2 ++ l2') : (v1, r1, l1, l1' ++ l') = (v2, r2, l2, l2') := begin cases h₁, cases hβ‚‚, rw [list.append_assoc, list.append_eq_append_iff] at e, rcases e with ⟨x, rfl, e⟩ | ⟨x, rfl, rfl⟩, { cases read_ModRM.determ_aux h₁_a hβ‚‚_a, cases e, cases split_bits.determ h₁_a_1 hβ‚‚_a_1 rfl, rw list.append_nil, refl }, { cases read_ModRM.determ_aux hβ‚‚_a h₁_a, cases split_bits.determ h₁_a_1 hβ‚‚_a_1 rfl, rw list.append_nil, refl }, end theorem read_opcode_ModRM.determβ‚‚ {rex v1 r1 v2 r2 l1 l2 l1' l2'} (h₁ : read_opcode_ModRM rex v1 r1 l1) (hβ‚‚ : read_opcode_ModRM rex v2 r2 l2) : l1 ++ l1' = l2 ++ l2' β†’ (v1, r1, l1, l1') = (v2, r2, l2, l2') := by simpa using @read_opcode_ModRM.determβ‚‚_aux _ _ _ _ _ _ _ l1' l2' [] h₁ hβ‚‚ theorem read_imm8.determ_aux {w1 w2 l l'} (h₁ : read_imm8 w1 l) (hβ‚‚ : read_imm8 w2 (l ++ l')) : (w1, l') = (w2, []) := by cases h₁; cases hβ‚‚; refl theorem read_imm16.determ_aux {w1 w2 l l'} (h₁ : read_imm16 w1 l) (hβ‚‚ : read_imm16 w2 (l ++ l')) : (w1, l') = (w2, []) := by cases h₁; cases hβ‚‚; cases bits_to_byte.determ_l_aux h₁_a hβ‚‚_a; refl theorem read_imm32.determ_aux {w1 w2 l l'} (h₁ : read_imm32 w1 l) (hβ‚‚ : read_imm32 w2 (l ++ l')) : (w1, l') = (w2, []) := by cases h₁; cases hβ‚‚; cases bits_to_byte.determ_l_aux h₁_a hβ‚‚_a; refl theorem read_imm8.determ {w1 w2 l} (h₁ : read_imm8 w1 l) (hβ‚‚ : read_imm8 w2 l) : w1 = w2 := by cases h₁; cases hβ‚‚; refl theorem read_imm16.determ {w1 w2 l} (h₁ : read_imm16 w1 l) (hβ‚‚ : read_imm16 w2 l) : w1 = w2 := by cases h₁; cases hβ‚‚; cases bits_to_byte.determ_l h₁_a hβ‚‚_a; refl theorem read_imm32.determ {w1 w2 l} (h₁ : read_imm32 w1 l) (hβ‚‚ : read_imm32 w2 l) : w1 = w2 := by cases h₁; cases hβ‚‚; cases bits_to_byte.determ_l h₁_a hβ‚‚_a; refl theorem read_imm.determ_aux : βˆ€ {sz w1 w2 l l'}, read_imm sz w1 l β†’ read_imm sz w2 (l ++ l') β†’ (w1, l') = (w2, []) | (wsize.Sz8 _) _ _ _ _ := read_imm8.determ_aux | wsize.Sz16 _ _ _ _ := read_imm16.determ_aux | wsize.Sz32 _ _ _ _ := read_imm32.determ_aux | wsize.Sz64 _ _ _ _ := false.elim theorem read_full_imm.determ_aux : βˆ€ {sz w1 w2 l l'}, read_full_imm sz w1 l β†’ read_full_imm sz w2 (l ++ l') β†’ (w1, l') = (w2, []) | (wsize.Sz8 _) _ _ _ _ := read_imm8.determ_aux | wsize.Sz16 _ _ _ _ := read_imm16.determ_aux | wsize.Sz32 _ _ _ _ := read_imm32.determ_aux | wsize.Sz64 _ _ _ _ := bits_to_byte.determ_l_aux theorem read_imm.determ {sz w1 w2 l} (h₁ : read_imm sz w1 l) (hβ‚‚ : read_imm sz w2 l) : w1 = w2 := by cases read_imm.determ_aux h₁ (by rw list.append_nil; exact hβ‚‚); refl theorem read_full_imm.determ {sz w1 w2 l} (h₁ : read_full_imm sz w1 l) (hβ‚‚ : read_full_imm sz w2 l) : w1 = w2 := by cases read_full_imm.determ_aux h₁ (by rw list.append_nil; exact hβ‚‚); refl def decode_two' (rex : REX) (a : ast) (b0 b1 b2 b3 b4 b5 b6 b7 : bool) (l : list byte) : Prop := cond b7 (cond b6 ( -- xadd [b1, b2, b3, b4, b5] = [ff, ff, ff, ff, ff] ∧ let v := b0, sz := op_size_W rex v in βˆƒ reg r, read_ModRM rex reg r l ∧ a = ast.xadd sz r reg) (cond b5 (cond b2 ( -- movsx [b1, b4] = [tt, tt] ∧ let sz2 := op_size_W rex tt, sz := if b0 then wsize.Sz16 else wsize.Sz8 rex.is_some in βˆƒ reg r, read_ModRM rex reg r l ∧ a = (if b3 then ast.movsx else ast.movzx) sz (dest_src.R_rm reg r) sz2) ( -- cmpxchg [b1, b4] = [ff, tt] ∧ let v := b0, sz := op_size_W rex v in βˆƒ reg r, read_ModRM rex reg r l ∧ a = ast.cmpxchg sz r reg)) (cond b4 ( -- setcc βˆƒ reg r code, read_ModRM rex reg r l ∧ cond_code.from_bits b0 b1 b2 b3 = some code ∧ a = ast.setcc code rex.is_some r) ( -- jcc βˆƒ imm code, read_imm32 imm l ∧ cond_code.from_bits b0 b1 b2 b3 = some code ∧ a = ast.jcc code imm)))) (cond b6 ( -- cmov [b4, b5] = [ff, ff] ∧ let sz := op_size tt rex.W tt in βˆƒ reg r code, read_ModRM rex reg r l ∧ cond_code.from_bits b0 b1 b2 b3 = some code ∧ a = ast.cmov code sz (dest_src.R_rm reg r)) ( -- syscall [b0, b1, b2, b3, b4, b5] = [tt, ff, tt, ff, ff, ff] ∧ a = ast.syscall ∧ l = [])) theorem decode_two_two' {rex a b0 b1 b2 b3 b4 b5 b6 b7 l} : decode_two rex a (⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ :: l) β†’ decode_two' rex a b0 b1 b2 b3 b4 b5 b6 b7 l := begin generalize e : (⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ :: l : list byte) = l', intro a, cases a, { cases e, rcases split_bits_ok a_a with ⟨h₁, hβ‚‚, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq hβ‚‚, exact ⟨rfl, _, _, _, a_a_1, cond_code.bits_eq a_a_2, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, hβ‚‚, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq hβ‚‚, exact ⟨_, _, a_a_1, cond_code.bits_eq a_a_2, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, hβ‚‚, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq hβ‚‚, exact ⟨_, _, _, a_a_1, cond_code.bits_eq a_a_2, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, ⟨⟩, hβ‚‚, _⟩, cases bitvec.reify_eq h₁, cases bitvec.reify_eq hβ‚‚, exact ⟨rfl, _, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, _, a_a_1, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, rfl, rfl⟩ }, end theorem decode_two_nil {rex a} : Β¬ decode_two rex a []. theorem decode_two.determ_aux {rex a₁ aβ‚‚ l l'} : decode_two rex a₁ l β†’ decode_two rex aβ‚‚ (l ++ l') β†’ (a₁, l') = (aβ‚‚, []) := begin cases l with b l, {exact decode_two_nil.elim}, apply byte_split b, introv h1 h2, replace h1 := decode_two_two' h1, replace h2 := decode_two_two' h2, unfold decode_two' at h1 h2, repeat { do `(cond %%e _ _) ← tactic.get_local `h1 >>= tactic.infer_type, tactic.cases e $> (); `[dsimp only [cond] at h1 h2] }, { rcases h1.2 with ⟨rfl, rfl⟩, rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl }, { rcases h1.2 with ⟨reg1, r1, h11, h12, h13, rfl⟩, rcases h2.2 with ⟨reg2, r2, h21, h22, h23, rfl⟩, cases read_ModRM.determ_aux h12 h22, cases h13.symm.trans h23, refl }, { rcases h1 with ⟨imm1, code1, h11, h12, rfl⟩, rcases h2 with ⟨imm2, code2, h21, h22, rfl⟩, cases read_imm32.determ_aux h11 h21, cases h12.symm.trans h22, refl }, { rcases h1 with ⟨reg1, r1, code1, h11, h12, rfl⟩, rcases h2 with ⟨reg2, r2, code2, h21, h22, rfl⟩, cases read_ModRM.determ_aux h11 h21, cases h12.symm.trans h22, refl }, { rcases h1 with ⟨reg1, r1, code1, h11, h12, rfl⟩, rcases h2 with ⟨reg2, r2, code2, h21, h22, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨reg1, r1, h11, rfl⟩, rcases h2.2 with ⟨reg2, r2, h21, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨reg1, r1, h11, rfl⟩, rcases h2.2 with ⟨reg2, r2, h21, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, end theorem decode_two.determ {rex a₁ aβ‚‚ l} (h₁ : decode_two rex a₁ l) (hβ‚‚ : decode_two rex aβ‚‚ l) : a₁ = aβ‚‚ := by cases decode_two.determ_aux h₁ (by rw list.append_nil; exact hβ‚‚); refl def decode_hi' (v : bool) (sz : wsize) (r : RM) : βˆ€ (b0 b1 b2 x : bool), ast β†’ list byte β†’ Prop | ff ff ff ff a l := βˆƒ imm, read_imm sz imm l ∧ a = ast.binop binop.tst sz (dest_src.Rm_i r imm) | ff tt ff ff a l := a = ast.unop unop.not sz r ∧ l = [] | tt tt ff ff a l := a = ast.unop unop.neg sz r ∧ l = [] | ff ff tt ff a l := a = ast.mul sz r ∧ l = [] | ff tt tt ff a l := a = ast.div sz r ∧ l = [] | ff ff ff tt a l := a = ast.unop unop.inc sz r ∧ l = [] | tt ff ff tt a l := a = ast.unop unop.dec sz r ∧ l = [] | ff tt ff tt a l := a = ast.call (imm_rm.rm r) ∧ l = [] | ff ff tt tt a l := a = ast.jump r ∧ l = [] | ff tt tt tt a l := a = ast.push (imm_rm.rm r) ∧ l = [] | _ _ _ _ a l := false theorem decode_hi_hi' {v sz r x b0 b1 b2 a l} (h : decode_hi v sz r x ⟨[b0, b1, b2], rfl⟩ a l) : decode_hi' v sz r b0 b1 b2 x a l := begin generalize_hyp e : (⟨[b0, b1, b2], rfl⟩ : bitvec 3) = opc at h, induction h; cases congr_arg subtype.val (bitvec.reify_eq' e), exact ⟨_, h_a, rfl⟩, all_goals { exact ⟨rfl, rfl⟩ } end theorem decode_hi.determ_aux {v sz r x a₁ aβ‚‚ l l'} : βˆ€ {opc}, decode_hi v sz r x opc a₁ l β†’ decode_hi v sz r x opc aβ‚‚ (l ++ l') β†’ (a₁, l') = (aβ‚‚, []) | ⟨[b0, b1, b2], _⟩ h1 h2 := begin replace h1 := decode_hi_hi' h1, replace h2 := decode_hi_hi' h2, clear decode_hi.determ_aux, cases b0; cases b1; cases b2; cases x; cases h1; cases h2, { cases read_imm.determ_aux h1_h.1 h2_h.1, cases h1_h.2.trans h2_h.2.symm, refl }, all_goals { rw [h1_left, ← h2_left], cases h1_right, cases h2_right, refl } end theorem decode_hi.determ {v sz r x opc a₁ aβ‚‚ l} (h₁ : decode_hi v sz r x opc a₁ l) (hβ‚‚ : decode_hi v sz r x opc aβ‚‚ l) : a₁ = aβ‚‚ := by cases decode_hi.determ_aux h₁ (by rw list.append_nil; exact hβ‚‚); refl def decode_aux' (rex : REX) (a : ast) (b0 b1 b2 b3 b4 b5 b6 b7 : bool) (l : list byte) : Prop := cond b7 (cond b6 (cond b5 (cond b4 (cond b2 (cond b1 ( -- hi let v := b0, sz := op_size_W rex v in βˆƒ opc r l1 l2, read_opcode_ModRM rex opc r l1 ∧ decode_hi v sz r b3 opc a l2 ∧ l = l1 ++ l2) ( -- cmc b0 = tt ∧ a = ast.cmc ∧ l = [])) ( -- clc, stc [b1, b3] = [ff, tt] ∧ a = cond b0 ast.stc ast.clc ∧ l = [])) (cond b0 ( -- jump [b2, b3] = [ff, tt] ∧ βˆƒ imm, (if b1 then read_imm8 imm l else read_imm32 imm l) ∧ a = ast.jcc cond_code.always imm) ( -- call [b2, b3] = [ff, tt] ∧ βˆƒ imm, read_imm32 imm l ∧ a = ast.call (imm_rm.imm imm)))) ( let v := b0, sz := op_size_W rex v in cond b4 ( -- binop_hi_reg [b2, b3] = [ff, ff] ∧ βˆƒ opc r op, read_opcode_ModRM rex opc r l ∧ opc β‰  6 ∧ binop.bits op (rex_reg tt opc) ∧ let src_dst := if b1 then dest_src.Rm_r r RCX else dest_src.Rm_i r 1 in a = ast.binop op sz src_dst) (cond b3 ( -- leave [b0, b1, b2] = [tt, ff, ff] ∧ a = ast.leave ∧ l = []) (cond b2 ( -- mov_imm b1 = tt ∧ βˆƒ opc r imm l1 l2, read_opcode_ModRM rex opc r l1 ∧ read_imm sz imm l2 ∧ a = ast.mov sz (dest_src.Rm_i r imm) ∧ l = l1 ++ l2) (cond b1 ( -- ret βˆƒ imm, (if v then imm = 0 ∧ l = [] else read_imm16 imm l) ∧ a = ast.ret imm) ( -- binop_hi βˆƒ opc r imm op l1 l2, read_opcode_ModRM rex opc r l1 ∧ opc β‰  6 ∧ binop.bits op (rex_reg tt opc) ∧ read_imm8 imm l2 ∧ a = ast.binop op sz (dest_src.Rm_i r imm) ∧ l = l1 ++ l2)))))) (cond b5 (cond b4 ( -- mov64 let v := b3, sz := op_size_W rex v in βˆƒ imm, read_full_imm sz imm l ∧ a = ast.mov sz (dest_src.Rm_i (RM.reg ⟨[b0, b1, b2, rex.B], rfl⟩) imm)) ( -- test_rax [b1, b2, b3] = [ff, ff, tt] ∧ let v := b0, sz := op_size tt rex.W v in βˆƒ imm, read_imm sz imm l ∧ a = ast.binop binop.tst sz (dest_src.Rm_i (RM.reg RAX) imm))) (cond b4 ( -- xchg_rax b3 = ff ∧ let sz := op_size tt rex.W tt in a = ast.xchg sz (RM.reg RAX) ⟨[b0, b1, b2, rex.B], rfl⟩ ∧ l = []) (cond b3 (cond b2 (cond b1 ( -- pop_rm b0 = tt ∧ βˆƒ r, read_opcode_ModRM rex 0 r l ∧ a = ast.pop r) ( -- lea b0 = tt ∧ βˆƒ reg r, let sz := op_size tt rex.W tt in read_ModRM rex reg r l ∧ RM.is_mem r ∧ a = ast.lea sz (dest_src.R_rm reg r))) ( -- mov let v := b0, sz := op_size_W rex v in βˆƒ reg r, read_ModRM rex reg r l ∧ let src_dst := if b1 then dest_src.R_rm reg r else dest_src.Rm_r r reg in a = ast.mov sz src_dst)) (cond b2 ( let v := b0, sz := op_size_W rex v in -- xchg, test βˆƒ reg r, read_ModRM rex reg r l ∧ a = cond b1 (ast.xchg sz r reg) (ast.binop binop.tst sz (dest_src.Rm_r r reg))) ( -- binop_imm, binop_imm8 let sz := op_size_W rex (cond b1 tt b0) in βˆƒ opc r l1 imm l2 op, read_opcode_ModRM rex opc r l1 ∧ binop.bits op (EXTZ opc) ∧ cond b1 (read_imm8 imm l2) (read_imm sz imm l2) ∧ a = ast.binop op sz (dest_src.Rm_i r imm) ∧ l = l1 ++ l2)))))) (cond b6 (cond b5 (cond b4 ( -- jcc8 βˆƒ code imm, cond_code.from_bits b0 b1 b2 b3 = some code ∧ read_imm8 imm l ∧ a = ast.jcc code imm) (cond b3 ( -- push_imm [b0, b2] = [ff, ff] ∧ βˆƒ imm, read_imm (if b1 then wsize.Sz8 ff else wsize.Sz32) imm l ∧ a = ast.push (imm_rm.imm imm)) ( -- movsx [b0, b1, b2] = [tt, tt, ff] ∧ βˆƒ reg r, read_ModRM rex reg r l ∧ a = ast.movsx wsize.Sz32 (dest_src.R_rm reg r) wsize.Sz64))) (cond b4 ( -- pop, push_rm let reg := RM.reg ⟨[b0, b1, b2, rex.B], rfl⟩ in a = cond b3 (ast.pop reg) (ast.push (imm_rm.rm reg)) ∧ l = []) ( -- prefix byte false))) (cond b2 (cond b1 ( -- decode_two [b0, b3, b4, b5] = [tt, tt, ff, ff] ∧ decode_two rex a l) ( -- binop_imm_rax let v := b0, sz := op_size_W rex v, op := binop.from_bits b3 b4 b5 ff in βˆƒ imm, read_imm sz imm l ∧ a = ast.binop op sz (dest_src.Rm_i (RM.reg RAX) imm))) ( -- binop1 let v := b0, d := b1, sz := op_size_W rex v, op := binop.from_bits b3 b4 b5 ff in βˆƒ reg r, read_ModRM rex reg r l ∧ let src_dst := if d then dest_src.R_rm reg r else dest_src.Rm_r r reg in a = ast.binop op sz src_dst))) theorem decode_aux_aux' {rex a b0 b1 b2 b3 b4 b5 b6 b7 l} : decode_aux rex a (⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ :: l) β†’ decode_aux' rex a b0 b1 b2 b3 b4 b5 b6 b7 l := begin generalize e : (⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ :: l : list byte) = l', intro a, cases a, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, ⟨⟩, h₁, hβ‚‚, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq hβ‚‚, cases binop.bits_eq a_a_2, exact ⟨_, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, hβ‚‚, h₃, _⟩, cases bitvec.reify_eq h₁, cases subtype.eq hβ‚‚, cases bitvec.reify_eq h₃, cases binop.bits_eq a_a_1, exact ⟨_, a_a_2, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨_, _, _, _, _, _, a_a_1, a_a_3, a_a_2, rfl, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), exact ⟨_, _, _, _, _, _, a_a, a_a_1, a_a_2, rfl, h_2⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨_, _, _, _, _, _, a_a_1, a_a_2, a_a_3, a_a_4, rfl, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, _, _, a_a_1, a_a_2, a_a_3, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, a_a_1⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, _, _, a_a, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨_, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, ⟨⟩, hβ‚‚, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq hβ‚‚, exact ⟨_, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, _, _, _, _, a_a_1, a_a_2, rfl, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨_, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, hβ‚‚, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq hβ‚‚, exact ⟨rfl, rfl, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, hβ‚‚, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq hβ‚‚, exact ⟨rfl, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, hβ‚‚, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq hβ‚‚, exact ⟨rfl, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, _, a_a, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, hβ‚‚, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq hβ‚‚, exact ⟨_, _, cond_code.bits_eq a_a_1, a_a_2, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, _, a_a, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨_, a_a_1, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, rfl, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, _, _, a_a, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨_, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, a_a_1, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, rfl, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, rfl, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, rfl, rfl⟩ }, { cases e, rcases split_bits_ok a_a_1 with ⟨⟨⟩, h₁, ⟨⟩, hβ‚‚, _⟩, cases bitvec.reify_eq h₁, cases bitvec.reify_eq hβ‚‚, exact ⟨_, _, _, _, a_a_2, a_a_3, rfl⟩ }, end theorem decode_aux_nil {rex a} : Β¬ decode_aux rex a []. theorem decode_aux.determ_aux {rex a₁ aβ‚‚ l l'} : decode_aux rex a₁ l β†’ decode_aux rex aβ‚‚ (l ++ l') β†’ (a₁, l') = (aβ‚‚, []) := begin cases l with b l, {exact decode_aux_nil.elim}, apply byte_split b, introv h1 h2, replace h1 := decode_aux_aux' h1, replace h2 := decode_aux_aux' h2, unfold decode_aux' at h1 h2, repeat { do `(cond %%e _ _) ← tactic.get_local `h1 >>= tactic.infer_type, tactic.cases e $> (); `[dsimp only [cond] at h1 h2] }, { rcases h1 with ⟨reg1, r1, h11, rfl⟩, rcases h2 with ⟨reg2, r2, h21, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1 with ⟨imm1, h11, rfl⟩, rcases h2 with ⟨imm2, h21, rfl⟩, cases read_imm.determ_aux h11 h21, refl }, { exact decode_two.determ_aux h1.2 h2.2 }, { cases h2 }, { rcases h1 with ⟨rfl, rfl⟩, rcases h2 with ⟨rfl, ⟨⟩⟩, refl }, { rcases h1.2 with ⟨reg1, r1, h11, rfl⟩, rcases h2.2 with ⟨reg2, r2, h21, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨imm1, h11, rfl⟩, rcases h2.2 with ⟨imm2, h21, rfl⟩, cases read_imm.determ_aux h11 h21, refl }, { rcases h1 with ⟨code1, imm1, h11, h12, rfl⟩, rcases h2 with ⟨code2, imm2, h21, h22, rfl⟩, cases h11.symm.trans h21, cases read_imm8.determ_aux h12 h22, refl }, { rcases h1 with ⟨opc1, r1, l11, imm1, l12, op1, h11, h12, h13, rfl, rfl⟩, rcases h2 with ⟨opc2, r2, l21, imm2, l22, op2, h21, h22, h23, rfl, e⟩, cases read_opcode_ModRM.determβ‚‚_aux h11 h21 e, cases binop.bits.determ h12 h22, cases b1, { cases read_imm.determ_aux h13 h23, refl }, { cases read_imm8.determ_aux h13 h23, refl } }, { rcases h1 with ⟨reg1, r1, h11, rfl⟩, rcases h2 with ⟨reg2, r2, h21, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1 with ⟨reg1, r1, h11, rfl⟩, rcases h2 with ⟨reg2, r2, h21, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨reg1, r1, h11, h12, rfl⟩, rcases h2.2 with ⟨reg2, r2, h21, h22, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨r1, h11, h12, rfl⟩, rcases h2.2 with ⟨r2, h21, h22, rfl⟩, cases read_opcode_ModRM.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨rfl, rfl⟩, rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl }, { rcases h1.2 with ⟨imm1, h11, rfl⟩, rcases h2.2 with ⟨imm2, h21, rfl⟩, cases read_imm.determ_aux h11 h21, refl }, { rcases h1 with ⟨imm1, h11, rfl⟩, rcases h2 with ⟨imm2, h21, rfl⟩, cases read_full_imm.determ_aux h11 h21, refl }, { rcases h1 with ⟨opc1, r1, imm1, op1, l11, l12, h11, _, h12, h13, rfl, rfl⟩, rcases h2 with ⟨opc2, r2, imm2, op2, l21, l22, h21, _, h22, h23, rfl, e⟩, cases read_opcode_ModRM.determβ‚‚_aux h11 h21 e, cases binop.bits.determ h12 h22, cases read_imm8.determ_aux h13 h23, refl }, { rcases h1 with ⟨imm1, h11, rfl⟩, rcases h2 with ⟨imm2, h21, rfl⟩, split_ifs at h11 h21, { rcases h11 with ⟨rfl, rfl⟩, rcases h21 with ⟨rfl, ⟨⟩⟩, refl }, { cases read_imm16.determ_aux h11 h21, refl } }, { rcases h1 with ⟨opc1, r1, imm1, op1, l11, l12, h11, h12, rfl, rfl⟩, rcases h2 with ⟨opc2, r2, imm2, op2, l21, l22, h21, h22, rfl, e⟩, cases read_opcode_ModRM.determβ‚‚_aux h11 h21 e, cases read_imm.determ_aux h12 h22, refl }, { rcases h1.2 with ⟨rfl, rfl⟩, rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl }, { rcases h1.2 with ⟨opc1, r1, op1, h11, _, h12, rfl⟩, rcases h2.2 with ⟨opc2, r2, op2, h21, _, h22, rfl⟩, cases read_opcode_ModRM.determ_aux h11 h21, cases binop.bits.determ h12 h22, refl }, { rcases h1.2 with ⟨imm1, h11, rfl⟩, rcases h2.2 with ⟨imm2, h21, rfl⟩, cases read_imm32.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨imm1, h11, rfl⟩, rcases h2.2 with ⟨imm2, h21, rfl⟩, split_ifs at h11 h21, { cases read_imm8.determ_aux h11 h21, refl }, { cases read_imm32.determ_aux h11 h21, refl } }, { rcases h1.2 with ⟨rfl, rfl⟩, rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl }, { rcases h1.2 with ⟨rfl, rfl⟩, rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl }, { rcases h1 with ⟨opc1, r1, l11, l12, h11, h12, rfl⟩, rcases h2 with ⟨opc2, r2, l21, l22, h21, h22, e⟩, cases read_opcode_ModRM.determβ‚‚_aux h11 h21 e, exact decode_hi.determ_aux h12 h22 }, end theorem decode_aux.determ {rex a₁ aβ‚‚ l} (h₁ : decode_aux rex a₁ l) (hβ‚‚ : decode_aux rex aβ‚‚ l) : a₁ = aβ‚‚ := by cases decode_aux.determ_aux h₁ (by rw list.append_nil; exact hβ‚‚); refl theorem decode.no_prefix {rex rex' a l b l'} : read_prefixes rex l β†’ b ∈ l β†’ Β¬ decode_aux rex' a (b :: l') := begin rintro ⟨⟩ (rfl|⟨⟨⟩⟩), -- generalize e : b :: l' = lβ‚‚, revert a_1_a, apply byte_split b, intros, rcases split_bits_ok a_1_a with ⟨_, ⟨⟩, _⟩, exact decode_aux_aux' end theorem decode_nil {a} : Β¬ decode a [] := begin generalize e : [] = l, rintro ⟨⟩, cases a_1_l1; cases e, exact decode_aux_nil a_1_a_2 end theorem decode.determ_aux {a₁ aβ‚‚ l l'} (h₁ : decode a₁ l) (hβ‚‚ : decode aβ‚‚ (l ++ l')) : (a₁, l') = (aβ‚‚, []) := begin generalize_hyp e : l ++ l' = x at hβ‚‚, induction h₁, induction hβ‚‚, rw [list.append_assoc, list.append_eq_append_iff] at e, rcases e with ⟨_|⟨b, x⟩, rfl, e⟩ | ⟨_|⟨b, x⟩, rfl, rfl⟩, { rw list.append_nil at hβ‚‚_a_1, cases e, cases read_prefixes.determ h₁_a_1 hβ‚‚_a_1, exact decode_aux.determ_aux h₁_a_2 hβ‚‚_a_2 }, { cases h₁_l2 with b' l2, cases decode_aux_nil h₁_a_2, injection e, subst b', cases decode.no_prefix hβ‚‚_a_1 (list.mem_append_right _ (or.inl rfl)) h₁_a_2 }, { rw list.append_nil at h₁_a_1, cases read_prefixes.determ h₁_a_1 hβ‚‚_a_1, exact decode_aux.determ_aux h₁_a_2 hβ‚‚_a_2 }, { cases decode.no_prefix h₁_a_1 (list.mem_append_right _ (or.inl rfl)) hβ‚‚_a_2 }, end theorem decode.determ {a₁ aβ‚‚ l} (h₁ : decode a₁ l) (hβ‚‚ : decode aβ‚‚ l) : a₁ = aβ‚‚ := by cases decode.determ_aux h₁ (by rw list.append_nil; exact hβ‚‚); refl instance : add_comm_monoid perm := { zero := ⟨ff, ff, ff⟩, add_assoc := Ξ» a b c, show perm.mk (_||_||_) (_||_||_) (_||_||_) = _, by repeat {rw bool.bor_assoc}; refl, zero_add := Ξ» ⟨r, w, x⟩, show perm.mk (ff||_) (ff||_) (ff||_) = _, by repeat {rw ff_bor}, add_zero := Ξ» ⟨r, w, x⟩, show perm.mk (_||ff) (_||ff) (_||ff) = _, by repeat {rw bor_ff}, add_comm := Ξ» a b, show perm.mk (_||_) (_||_) (_||_) = _, by rw [bool.bor_comm, bool.bor_comm a.isW, bool.bor_comm a.isX]; refl, ..perm.has_add } theorem perm.add_self : βˆ€ p : perm, p + p = p | ⟨r, w, x⟩ := show perm.mk (r||r) (w||w) (x||x) = _, by repeat {rw bor_self} instance : partial_order perm := { le_refl := perm.add_self, le_trans := Ξ» a b c (h₁ : a + b = b) (hβ‚‚ : b + c = c), show a + c = c, by rw [← hβ‚‚, ← add_assoc, h₁], le_antisymm := Ξ» a b (h₁ : a + b = b) (hβ‚‚ : b + a = a), by rw [← hβ‚‚, add_comm, h₁], ..perm.has_le } theorem perm.le_add_left {p₁ pβ‚‚ : perm} : p₁ ≀ p₁ + pβ‚‚ := show _=_, by rw [← add_assoc, perm.add_self] theorem mem.read1.determ {p1 p2 m a b1 b2} : mem.read1 p1 m a b1 β†’ mem.read1 p2 m a b2 β†’ b1 = b2 := by rintro ⟨_, rfl, _⟩ ⟨_, rfl, _⟩; refl theorem mem.read'.determ_aux {p1 p2 m a l1 l2} (h₁ : mem.read' p1 m a l1) (hβ‚‚ : mem.read' p2 m a l2) : l1 <+: l2 ∨ l2 <+: l1 := begin induction h₁ generalizing l2, { exact or.inl (list.nil_prefix _) }, cases hβ‚‚, { exact or.inr (list.nil_prefix _) }, cases h₁_a.determ hβ‚‚_a, rw [list.prefix_cons_inj, list.prefix_cons_inj], exact h₁_ih hβ‚‚_a_1, end theorem mem.read'.determ_len {p1 p2 m a l1 l2} (h₁ : mem.read' p1 m a l1) (hβ‚‚ : mem.read' p2 m a l2) (h : l1.length = l2.length) : l1 = l2 := (mem.read'.determ_aux h₁ hβ‚‚).elim (Ξ» h', list.eq_of_prefix_of_length_eq h' h) (Ξ» h', (list.eq_of_prefix_of_length_eq h' h.symm).symm) theorem mem_decode.determ {p1 p2 m a l1 l2 ast1 ast2} (m₁ : mem.read' p1 m a l1) (h₁ : decode ast1 l1) (mβ‚‚ : mem.read' p2 m a l2) (hβ‚‚ : decode ast2 l2) : (ast1, l1) = (ast2, l2) := begin rcases mem.read'.determ_aux m₁ mβ‚‚ with ⟨x, rfl⟩ | ⟨x, rfl⟩, { cases decode.determ_aux h₁ hβ‚‚, simp }, { cases decode.determ_aux hβ‚‚ h₁, simp }, end theorem config.step_noIO {k k₁ kβ‚‚} : config.step k k₁ β†’ Β¬ config.isIO k kβ‚‚ := Ξ» h₁ hβ‚‚, begin cases h₁, cases hβ‚‚, cases mem_decode.determ h₁_a_1 h₁_a_2 hβ‚‚_a hβ‚‚_a_1, rcases h₁_a_3 with ⟨_, s₁, _, ⟨⟩, _⟩ end theorem mem.write1.determ {m a b m₁ mβ‚‚} (h₁ : mem.write1 m a b m₁) (hβ‚‚ : mem.write1 m a b mβ‚‚) : m₁ = mβ‚‚ := by cases h₁; cases hβ‚‚; refl theorem mem.write.determ {m a l m₁ mβ‚‚} (h₁ : mem.write m a l m₁) (hβ‚‚ : mem.write m a l mβ‚‚) : m₁ = mβ‚‚ := begin induction h₁ generalizing mβ‚‚; cases hβ‚‚, refl, cases mem.write1.determ h₁_a hβ‚‚_a, cases h₁_ih hβ‚‚_a_1, refl end theorem config.write_mem.determ {k a l k₁ kβ‚‚} (h₁ : config.write_mem k a l k₁) (hβ‚‚ : config.write_mem k a l kβ‚‚) : k₁ = kβ‚‚ := by cases h₁; cases hβ‚‚; cases mem.write.determ h₁_a_1 hβ‚‚_a_1; refl theorem EA.write.determ {k ea sz v k₁ kβ‚‚} (h₁ : EA.write k ea sz v k₁) (hβ‚‚ : EA.write k ea sz v kβ‚‚) : k₁ = kβ‚‚ := begin cases h₁; cases hβ‚‚, refl, cases bits_to_byte.determ h₁_a_1 hβ‚‚_a_1, exact config.write_mem.determ h₁_a_2 hβ‚‚_a_2 end theorem config.isIO.determ {k k₁ kβ‚‚} : config.isIO k k₁ β†’ config.isIO k kβ‚‚ β†’ βˆƒ k' v₁ vβ‚‚, k₁ = config.set_reg k' 11 v₁ ∧ kβ‚‚ = config.set_reg k' 11 vβ‚‚ := begin rintro ⟨l₁, _, m₁, d₁, _, _, ⟨⟩, ⟨⟩, k', a₁, q₁, _, ⟨⟨⟩, rfl⟩, hβ‚βŸ© ⟨lβ‚‚, _, mβ‚‚, dβ‚‚, _, _, ⟨⟩, ⟨⟩, k'', aβ‚‚, qβ‚‚, _, ⟨⟨⟩, rfl⟩, hβ‚‚βŸ©, cases mem_decode.determ m₁ d₁ mβ‚‚ dβ‚‚, cases EA.write.determ a₁ aβ‚‚, cases h₁, cases hβ‚‚, exact ⟨_, _, _, rfl, rfl⟩ end theorem config.step.no_exit {k k₁ r} : config.step k k₁ β†’ Β¬ config.exit k r := Ξ» h ⟨k', h', _⟩, config.step_noIO h h' theorem set_reg_ne {k r r' q} (h : r' β‰  r) : (config.set_reg k r q).regs r' = k.regs r' := if_neg h theorem config.set_reg_11_exec_exit {k v r} : exec_exit (config.set_reg k 11 v) r ↔ exec_exit k r := begin split; rintro ⟨e⟩; split, { rwa set_reg_ne at e, rintro ⟨⟩ }, { rwa set_reg_ne, rintro ⟨⟩ }, end theorem config.isIO.determ_exec {k k₁ kβ‚‚ r} (h₁ : config.isIO k k₁) (hβ‚‚ : config.isIO k kβ‚‚) : exec_exit k₁ r ↔ exec_exit kβ‚‚ r := begin rcases h₁.determ hβ‚‚ with ⟨k', v₁, vβ‚‚, rfl, rfl⟩, simp [config.set_reg_11_exec_exit], end theorem exec_io.no_exit {i o k i' o' k' ret r} : exec_io i o k (k.regs RAX) i' o' k' ret β†’ Β¬ exec_exit k r := begin rintro h ⟨e⟩, rw e at h, rcases h with ⟨_, _, _, _, e⟩ | ⟨_, _, _, _, _, _, _, e⟩; cases bitvec.reify_eqβ‚‚ e, end theorem read_from_fd.io_part {fd i H_dat i'} (H : read_from_fd fd i H_dat i') : i' <:+ i := begin cases H, apply list.suffix_refl, exact ⟨_, rfl⟩ end theorem exec_read.io_part {i k fd count i' k' ret} (H : exec_read i k fd count i' k' ret) : i' <:+ i := begin cases H, apply list.suffix_refl, exact read_from_fd.io_part H_a_2 end theorem exec_io.io_part {k₁ i₁ o₁ kβ‚‚ iβ‚‚ oβ‚‚ call ret} (H : exec_io i₁ o₁ k₁ call iβ‚‚ oβ‚‚ kβ‚‚ ret) : iβ‚‚ <:+ i₁ ∧ o₁ <+: oβ‚‚ := begin induction H, exact ⟨list.suffix_refl _, list.prefix_refl _⟩, exact ⟨exec_read.io_part H_a_2, list.prefix_refl _⟩, end theorem kcfg.step.no_exit {k k' r} : kcfg.step k k' β†’ Β¬ config.exit k.k r := begin rintro (⟨_, _, _, _, h⟩ | ⟨_, _, k₁, kβ‚‚, _, _, _, _, h₁, h⟩), { exact h.no_exit }, { rintro ⟨k₃, hβ‚‚, e⟩, exact h.no_exit ((h₁.determ_exec hβ‚‚).2 e) }, end theorem kcfg.step.io_part {k₁ i₁ o₁ kβ‚‚ iβ‚‚ oβ‚‚} (H : kcfg.step ⟨i₁, o₁, kβ‚βŸ© ⟨iβ‚‚, oβ‚‚, kβ‚‚βŸ©) : iβ‚‚ <:+ i₁ ∧ o₁ <+: oβ‚‚ := begin cases H, exact ⟨list.suffix_refl _, list.prefix_refl _⟩, exact exec_io.io_part H_a_1 end @[simp] theorem EXTZ_id {n} (w : bitvec n) : EXTZ w = w := begin suffices : βˆ€ l n, list.length l = n β†’ (@EXTZ_aux l n).to_list = l, { exact subtype.eq (this w.1 _ w.2) }, intro l, induction l; intros n e; cases e, {refl}, unfold EXTZ_aux, rw [vector.to_list_cons, l_ih _ rfl], end @[simp] theorem EXTS_id {n} (w : bitvec n) : EXTS w = w := begin suffices : βˆ€ l a n, list.length l = n β†’ (@EXTS_aux l a n).to_list = l, { exact subtype.eq (this w.1 _ _ w.2) }, intro l, induction l; intros n a e; cases e, {refl}, unfold EXTS_aux, rw [vector.to_list_cons, l_ih _ _ rfl], end theorem EA.read_reg_64 {r k q} : (EA.r r).read k wsize.Sz64 q ↔ q = k.regs r := by simp [EA.read] theorem EA.readq_reg_64 {r k q} : (EA.r r).readq k wsize.Sz64 q ↔ q = k.regs r := by simp [EA.readq, EA.read_reg_64] theorem EA.write_reg_64 {r k q k'} : (EA.r r).write k wsize.Sz64 q k' ↔ k' = k.set_reg r q := by split; [{rintro ⟨⟩, refl}, {rintro rfl, constructor}] theorem EA.writeq_reg_64 {r k q k'} : (EA.r r).writeq k wsize.Sz64 q k' ↔ k' = k.set_reg r q := by simp [EA.writeq, EA.write_reg_64] theorem mem.set.read'_exists {p m q w b v} (h1 : mem.read' p m q v) : βˆƒ v', mem.read' p (m.set w b) q v' := begin induction h1, {exact ⟨_, mem.read'.nil _ _ _⟩}, cases h1_ih with v1 ih, rcases h1_a with ⟨_, rfl, h1⟩, exact ⟨_, mem.read'.cons ⟨_, rfl, h1⟩ ih⟩, end theorem mem.write.read'_exists {p m q a v v2 m'} (h1 : mem.read' p m q v) (h2 : mem.write m a v2 m') : βˆƒ v', mem.read' p m' q v' := begin induction h2 generalizing v, {exact ⟨_, h1⟩}, cases h2_a with h3 h4, cases mem.set.read'_exists h1 with v1 h1, exact h2_ih h1, end theorem EA.read.determ {k ea sz w1 w2} (h1 : EA.read k ea sz w1) (h2 : EA.read k ea sz w2) : w1 = w2 := begin cases ea, { exact h1.trans h2.symm }, { cases sz, cases sz, all_goals {exact h1.trans h2.symm} }, { rcases h1 with ⟨_, a1, b1⟩, rcases h2 with ⟨_, a2, b2⟩, cases a1.determ_len a2 (b1.1.trans b2.1.symm), exact bits_to_byte.determ_l b1 b2 }, end theorem EA.readq.determ {k ea sz q1 q2} : EA.readq k ea sz q1 β†’ EA.readq k ea sz q2 β†’ q1 = q2 | ⟨a1, b1, e1⟩ ⟨a2, b2, e2⟩ := by cases b1.determ b2; exact e1.trans e2.symm theorem hoare_p.bind {P P' : kcfg β†’ Prop} (H : βˆ€ {{k}}, P k β†’ hoare_p P' k) {k} : hoare_p P k β†’ hoare_p P' k := begin intro h, induction h, exact H h_a, exact hoare_p.step h_a (Ξ» k', h_ih _), by_cases h_ret = 0, { cases H (h_a_1 h), { exact hoare_p.zero a }, { cases a with k' h, cases h.no_exit h_a }, { exact hoare_p.exit _ _ a a_1 } }, { exact hoare_p.exit _ _ h_a h.elim }, end theorem hoare_p.mono {P P' : kcfg β†’ Prop} (H : βˆ€ {{k}}, P k β†’ P' k) {k} : hoare_p P k β†’ hoare_p P' k := hoare_p.bind (Ξ» k h, hoare_p.zero (H h)) end x86
34d13a414b027c5b765f99142c53cb69f31db959
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/run/1562.lean
db95359906bc656fe994629b0aedf7f0f570186b
[ "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
494
lean
meta constant term : Type meta constant smt2.builder.int_const : int -> term meta constant smt2_state : Type @[reducible] meta def smt2_m (Ξ± : Type) := state_t smt2_state tactic Ξ± meta instance tactic_to_smt2_m (Ξ± : Type) : has_coe (tactic Ξ±) (smt2_m Ξ±) := ⟨ fun tc, fun s, do res ← tc, return (res, s) ⟩ meta def reflect_arith_formula : expr β†’ smt2_m term | ```(has_zero.zero) := smt2.builder.int_const <$> tactic.eval_expr int ```(has_zero.zero int) | a := tactic.fail "foo"
ee5c4afacade4f49b96a2f8a48e2dc517de794b9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/float_auto.lean
8688c8426ff850c9dfe00fe607dbbd13baa99008
[]
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
158
lean
/- Authors: E.W.Ayers -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.default namespace Mathlib namespace native namespace float end Mathlib
80f8c40302ab981c93ce29bd38246aabe9e4d2f9
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/algebra/Mon/basic.lean
4bbd2e16de0d6a9d0150e820a8b09d6ce535bdcc
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
1,823
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison Introduce Mon -- the category of monoids. Currently only the basic setup. -/ import category_theory.concrete_category algebra.group universes u v open category_theory /-- The category of monoids and monoid morphisms. -/ @[reducible] def Mon : Type (u+1) := bundled monoid /-- The category of commutative monoids and monoid morphisms. -/ @[reducible] def CommMon : Type (u+1) := bundled comm_monoid namespace Mon instance (x : Mon) : monoid x := x.str instance concrete_is_monoid_hom : concrete_category @is_monoid_hom := ⟨by introsI Ξ± ia; apply_instance, by introsI Ξ± Ξ² Ξ³ ia ib ic f g hf hg; apply_instance⟩ def of (X : Type u) [monoid X] : Mon := ⟨X⟩ abbreviation forget : Mon.{u} β₯€ Type u := forget instance hom_is_monoid_hom {R S : Mon} (f : R ⟢ S) : is_monoid_hom (f : R β†’ S) := f.2 end Mon namespace CommMon instance (x : CommMon) : comm_monoid x := x.str @[reducible] def is_comm_monoid_hom {Ξ± Ξ²} [comm_monoid Ξ±] [comm_monoid Ξ²] (f : Ξ± β†’ Ξ²) : Prop := is_monoid_hom f instance concrete_is_comm_monoid_hom : concrete_category @is_comm_monoid_hom := ⟨by introsI Ξ± ia; apply_instance, by introsI Ξ± Ξ² Ξ³ ia ib ic f g hf hg; apply_instance⟩ def of (X : Type u) [comm_monoid X] : CommMon := ⟨X⟩ abbreviation forget : CommMon.{u} β₯€ Type u := forget instance hom_is_comm_monoid_hom {R S : CommMon} (f : R ⟢ S) : is_comm_monoid_hom (f : R β†’ S) := f.2 /-- The forgetful functor from commutative monoids to monoids. -/ def forget_to_Mon : CommMon β₯€ Mon := concrete_functor (by intros _ c; exact { ..c }) (by introsI _ _ _ _ f i; exact { ..i }) instance : faithful (forget_to_Mon) := {} end CommMon
ec072efc529512e8d85c616271d6a798b85a1385
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/data/to_string.lean
7f4766e87329b62d5b255f25afcf62c30b25f8a8
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,587
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.string.basic init.data.bool.basic init.data.subtype.basic import init.data.unsigned.basic init.data.prod init.data.sum.basic init.data.nat.div open sum subtype nat universes u v class has_to_string (Ξ± : Type u) := (to_string : Ξ± β†’ string) def to_string {Ξ± : Type u} [has_to_string Ξ±] : Ξ± β†’ string := has_to_string.to_string instance : has_to_string bool := ⟨λ b, cond b "tt" "ff"⟩ instance {p : Prop} : has_to_string (decidable p) := -- Remark: type class inference will not consider local instance `b` in the new elaborator ⟨λ b : decidable p, @ite p b _ "tt" "ff"⟩ protected def list.to_string_aux {Ξ± : Type u} [has_to_string Ξ±] : bool β†’ list Ξ± β†’ string | b [] := "" | tt (x::xs) := to_string x ++ list.to_string_aux ff xs | ff (x::xs) := ", " ++ to_string x ++ list.to_string_aux ff xs protected def list.to_string {Ξ± : Type u} [has_to_string Ξ±] : list Ξ± β†’ string | [] := "[]" | (x::xs) := "[" ++ list.to_string_aux tt (x::xs) ++ "]" instance {Ξ± : Type u} [has_to_string Ξ±] : has_to_string (list Ξ±) := ⟨list.to_string⟩ instance : has_to_string unit := ⟨λ u, "star"⟩ instance {Ξ± : Type u} [has_to_string Ξ±] : has_to_string (option Ξ±) := ⟨λ o, match o with | none := "none" | (some a) := "(some " ++ to_string a ++ ")" end⟩ instance {Ξ± : Type u} {Ξ² : Type v} [has_to_string Ξ±] [has_to_string Ξ²] : has_to_string (Ξ± βŠ• Ξ²) := ⟨λ s, match s with | (inl a) := "(inl " ++ to_string a ++ ")" | (inr b) := "(inr " ++ to_string b ++ ")" end⟩ instance {Ξ± : Type u} {Ξ² : Type v} [has_to_string Ξ±] [has_to_string Ξ²] : has_to_string (Ξ± Γ— Ξ²) := ⟨λ ⟨a, b⟩, "(" ++ to_string a ++ ", " ++ to_string b ++ ")"⟩ instance {Ξ± : Type u} {Ξ² : Ξ± β†’ Type v} [has_to_string Ξ±] [s : βˆ€ x, has_to_string (Ξ² x)] : has_to_string (sigma Ξ²) := ⟨λ ⟨a, b⟩, "⟨" ++ to_string a ++ ", " ++ to_string b ++ "⟩"⟩ instance {Ξ± : Type u} {p : Ξ± β†’ Prop} [has_to_string Ξ±] : has_to_string (subtype p) := ⟨λ s, to_string (val s)⟩ /- Remark: the code generator replaces this definition with one that display natural numbers in decimal notation -/ protected def nat.to_string : nat β†’ string | 0 := "zero" | (succ a) := "(succ " ++ nat.to_string a ++ ")" instance : has_to_string nat := ⟨nat.to_string⟩ def hex_digit_to_string (n : nat) : string := if n ≀ 9 then to_string n else if n = 10 then "a" else if n = 11 then "b" else if n = 12 then "c" else if n = 13 then "d" else if n = 14 then "e" else "f" def char_to_hex (c : char) : string := let n := char.to_nat c, d2 := n / 16, d1 := n % 16 in hex_digit_to_string d2 ++ hex_digit_to_string d1 def char.quote_core (c : char) : string := if c = '\n' then "\\n" else if c = '\t' then "\\t" else if c = '\\' then "\\\\" else if c = '\"' then "\\\"" else if char.to_nat c <= 31 then "\\x" ++ char_to_hex c else [c] instance : has_to_string char := ⟨λ c, "'" ++ char.quote_core c ++ "'"⟩ def string.quote_aux : string β†’ string | [] := "" | (x::xs) := string.quote_aux xs ++ char.quote_core x def string.quote : string β†’ string | [] := "\"\"" | (x::xs) := "\"" ++ string.quote_aux (x::xs) ++ "\"" instance : has_to_string string := ⟨string.quote⟩ instance (n : nat) : has_to_string (fin n) := ⟨λ f, to_string (fin.val f)⟩ instance : has_to_string unsigned := ⟨λ n, to_string (fin.val n)⟩
e91945045ec7c4f26a611daca9e0a6e95d75a9d2
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Data/Position.lean
a35dc0a8f3d82bc4a7359c12a73524af00d83aca
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,239
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, Sebastian Ullrich -/ import Lean.Data.Format namespace Lean structure Position where line : Nat column : Nat deriving Inhabited, DecidableEq, Repr namespace Position protected def lt : Position β†’ Position β†’ Bool | ⟨l₁, cβ‚βŸ©, ⟨lβ‚‚, cβ‚‚βŸ© => (l₁, c₁) < (lβ‚‚, cβ‚‚) instance : ToFormat Position := ⟨fun ⟨l, c⟩ => "⟨" ++ fmt l ++ ", " ++ fmt c ++ "⟩"⟩ instance : ToString Position := ⟨fun ⟨l, c⟩ => "⟨" ++ toString l ++ ", " ++ toString c ++ "⟩"⟩ end Position structure FileMap where source : String positions : Array String.Pos lines : Array Nat deriving Inhabited namespace FileMap partial def ofString (s : String) : FileMap := let rec loop (i : String.Pos) (line : Nat) (ps : Array String.Pos) (lines : Array Nat) : FileMap := if s.atEnd i then { source := s, positions := ps.push i, lines := lines.push line } else let c := s.get i; let i := s.next i; if c == '\n' then loop i (line+1) (ps.push i) (lines.push (line+1)) else loop i line ps lines loop 0 1 (#[0]) (#[1]) partial def toPosition (fmap : FileMap) (pos : String.Pos) : Position := match fmap with | { source := str, positions := ps, lines := lines } => if ps.size >= 2 && pos <= ps.back then let rec toColumn (i : String.Pos) (c : Nat) : Nat := if i == pos || str.atEnd i then c else toColumn (str.next i) (c+1) let rec loop (b e : Nat) := let posB := ps[b] if e == b + 1 then { line := lines.get! b, column := toColumn posB 0 } else let m := (b + e) / 2; let posM := ps.get! m; if pos == posM then { line := lines.get! m, column := 0 } else if pos > posM then loop m e else loop b m loop 0 (ps.size -1) else -- Some systems like the delaborator use synthetic positions without an input file, -- which would violate `toPositionAux`'s invariant ⟨1, pos⟩ end FileMap end Lean def String.toFileMap (s : String) : Lean.FileMap := Lean.FileMap.ofString s
a9332e39dc51dba196f88e3b503aee6e293623c7
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/simpStar.lean
7ef9d42a1e183dcce534176e18781caa5e5f888e
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
490
lean
opaque f (x y : Nat) : Nat opaque g (x : Nat) : Nat theorem ex1 (x : Nat) (h₁ : f x x = g x) (hβ‚‚ : g x = x) : f x (f x x) = x := by simp simp [*] theorem ex2 (x : Nat) (h₁ : f x x = g x) (hβ‚‚ : g x = x) : f x (f x x) = x := by simp [*] axiom g_ax (x : Nat) : g x = 0 theorem ex3 (x y : Nat) (h₁ : f x x = g x) (hβ‚‚ : f x x < 5) : f x x + f x x = 0 := by simp [*] at * trace_state have aux₁ : f x x = g x := h₁ have auxβ‚‚ : g x < 5 := hβ‚‚ simp [g_ax]
75f92982d4a649923e413a73bebe40847a6a1fa6
ea80d7bb31b9673a3a06d5148363b44b66c53796
/thys/move.lean
1086ae568afb335e671602da0160b9204780e8ea
[]
no_license
gitter-badger/electrolysis
2a59d6e0fe1b6629a14a1202e31b1a8ff1c93ced
4f63846e817cb52bdac4ae65ef3d17634e6ffc36
refs/heads/master
1,608,825,996,259
1,467,154,609,000
1,467,154,609,000
62,184,345
0
0
null
null
null
null
UTF-8
Lean
false
false
14,209
lean
/- things that may or may not belong in the stdlib -/ import data.list import data.list.sorted open eq.ops open list open nat open option lemma generalize_with_eq {A : Type} {P : A β†’ Prop} (x : A) (H : βˆ€y, x = y β†’ P y) : P x := H x rfl namespace nat open int definition of_int : β„€ β†’ β„• | (int.of_nat n) := n | _ := 0 lemma of_int_one : of_int 1 = 1 := rfl end nat namespace option variables {A B : Type} protected definition any [unfold 3] (P : A β†’ Prop) : option A β†’ Prop | (some x) := P x | none := false protected theorem any.elim {x : option A} {P : A β†’ Prop} (H : option.any P x) : βˆƒy, x = some y ∧ P y := begin cases x with y, { contradiction }, { apply exists.intro y (and.intro rfl H) } end theorem ex_some_of_neq_none {x : option A} (H : x β‰  none) : βˆƒy, x = some y := begin cases x with y, { exfalso, apply H rfl }, { existsi y, apply rfl } end protected definition bind [unfold 4] {A B : Type} (f : A β†’ option B) : option A β†’ option B | (some x) := f x | none := none theorem bind_some_eq_id {x : option A} : option.bind some x = x := by cases x; esimp; esimp theorem bind_neq_none {f : A β†’ option B} {x} (Hx : x β‰  none) (Hf : βˆ€x', f x' β‰  none) : option.bind f x β‰  none := obtain x' H₁, from ex_some_of_neq_none Hx, obtain x'' Hβ‚‚, from ex_some_of_neq_none (Hf x'), by rewrite [H₁, β–Έ*, Hβ‚‚]; contradiction end option namespace list section parameter {A : Type} variable xs : list A -- first without [inhabited], last without predicate definition first' [unfold 2] : option A := nth xs 0 definition last' : list A β†’ option A | [] := none | [x] := some x | (x::xs) := last' xs theorem last'_cons_eq_last' : Ξ {x : A} {xs : list A}, xs β‰  nil β†’ last' (x::xs) = last' xs | x [] H := false.elim (H rfl) | x (x'::xs) H := by esimp theorem firstn_sub : Ξ (n : β„•) (xs : list A), firstn n xs βŠ† xs | 0 xs := nil_sub _ | (succ n) [] := sub.refl _ | (succ n) (x::xs) := cons_sub_cons x (firstn_sub n xs) theorem dropn_nil (n : β„•) : dropn n (nil : list A) = nil := nat.cases_on n rfl (Ξ»n, rfl) theorem mem_of_mem_dropn (x : A) : Ξ (n : β„•) (xs : list A), x ∈ dropn n xs β†’ x ∈ xs | 0 xs H := H | (n+1) [] H := by contradiction | (succ n) (y::xs) H := by esimp at H; apply mem_cons_of_mem y (mem_of_mem_dropn n xs H) theorem dropn_sub_dropn_cons : Ξ (n : β„•) (x : A) (xs : list A), dropn n xs βŠ† dropn n (x::xs) | 0 x xs := sub_cons x xs | (succ n) x [] := nil_sub _ | (succ n) x (x'::xs) := by esimp; apply dropn_sub_dropn_cons n x' xs theorem dropn_sub : Ξ (n : β„•) (xs : list A), dropn n xs βŠ† xs | 0 xs := sub.refl _ | (succ n) [] := sub.refl _ | (succ n) (x::xs) := by esimp; apply sub.trans (dropn_sub_dropn_cons n x xs) (dropn_sub n (x::xs)) theorem dropn_dropn (n : β„•) : Ξ  (m : β„•) (xs : list A), dropn n (dropn m xs) = dropn (n+m) xs | 0 xs := by esimp | (succ m) [] := by rewrite +dropn_nil | (succ m) (x::xs) := by rewrite [nat.add_succ, ↑dropn at {1,3}]; apply dropn_dropn m xs theorem last'_dropn_of_last' : Ξ (n : β„•) (xs : list A) (H : n < length xs), last' (dropn n xs) = last' xs | 0 xs H := rfl | (succ n) [] H := by rewrite length_nil at H | (succ n) (x::xs) H := begin have H' : n < length xs, from lt_of_succ_lt_succ (!length_cons β–Έ H), have xs β‰  nil, begin intro Hcontr, rewrite [Hcontr at H', length_nil at H'], apply not_succ_le_zero n H', end, rewrite [↑dropn, last'_cons_eq_last' this], apply last'_dropn_of_last' n xs H' end theorem nth_eq_first'_dropn : Ξ (n : β„•) (xs : list A), nth xs n = first' (dropn n xs) | 0 xs := rfl | (succ n) [] := by esimp | (succ n) (x::xs) := by rewrite [↑dropn, ↑nth]; apply nth_eq_first'_dropn n xs theorem firstn_app_dropn_eq_self : Ξ (n : β„•) (xs : list A), firstn n xs ++ dropn n xs = xs | 0 xs := rfl | (succ n) [] := rfl | (succ n) (x::xs) := by rewrite [↑firstn, ↑dropn, β–Έ*, append_cons, firstn_app_dropn_eq_self] theorem mem_of_nth : Ξ {i : β„•} {xs : list A} {y : A}, nth xs i = some y β†’ y ∈ xs | _ [] _ H := by contradiction | 0 (x::xs) y H := by injection H with Hxy; apply Hxy β–Έ !mem_cons | (succ i) (x::xs) y H := by rewrite [↑nth at H]; apply mem_cons_of_mem x (mem_of_nth H) theorem nth_of_mem : Ξ {xs : list A} {y : A}, y ∈ xs β†’ βˆƒi, nth xs i = some y | [] y H := by contradiction | (x::xs) y H := or.rec_on (eq_or_mem_of_mem_cons H) (suppose y = x, exists.intro 0 (this β–Έ rfl)) (suppose y ∈ xs, obtain i Hnth, from nth_of_mem this, exists.intro (i+1) (!nth_succ ⬝ Hnth)) theorem lt_length_of_mem : Ξ {xs : list A} {i : β„•} {y : A}, nth xs i = some y β†’ i < length xs | [] i y H := by contradiction | (x::xs) 0 y H := !zero_lt_succ | (x::xs) (succ i) y H := by unfold nth at H; apply succ_lt_succ (lt_length_of_mem H) definition insert_at : list A β†’ β„• β†’ A β†’ list A | [] n y := [y] | xs 0 y := y::xs | (x::xs) (succ n) y := x::insert_at xs n y end inductive prefixeq {A : Type} : list A β†’ list A β†’ Prop := infix ` βŠ‘β‚š `:50 := prefixeq | nil : Ξ ys, [] βŠ‘β‚š ys | cons : Ξ x {xs ys}, xs βŠ‘β‚š ys β†’ x::xs βŠ‘β‚š x::ys namespace prefixeq section parameter {A : Type} infix ` βŠ‘β‚š `:50 := prefixeq protected theorem refl [refl] : Ξ (xs : list A), xs βŠ‘β‚š xs | [] := !nil | (x::xs) := cons x (refl xs) protected theorem trans [trans] : Ξ {xs ys zs : list A}, xs βŠ‘β‚š ys β†’ ys βŠ‘β‚š zs β†’ xs βŠ‘β‚š zs | [] ys zs _ _ := !nil | (x::xs) (x::ys) (x::zs) (cons x H₁) (cons x Hβ‚‚) := cons x (trans H₁ Hβ‚‚) protected theorem antisymm : Ξ {xs ys : list A}, xs βŠ‘β‚š ys β†’ ys βŠ‘β‚š xs β†’ xs = ys | [] [] _ _ := rfl | (x::xs) (x::ys) (cons x H₁) (cons x Hβ‚‚) := antisymm H₁ Hβ‚‚ β–Έ rfl definition weak_order [instance] : weak_order (list A) := ⦃weak_order, le := prefixeq, le_refl := refl, le_trans := @trans, le_antisymm := @antisymm ⦄ theorem nth_of_nth_prefixeq {i : β„•} {xs ys : list A} {z : A} (Hxs : nth xs i = some z) (Hprefix : xs βŠ‘β‚š ys) : nth ys i = some z := begin revert i Hxs, induction Hprefix with x z' xs ys Hprefix ih, all_goals intro i Hxs, { contradiction }, { cases i with i, { apply Hxs }, { apply ih i Hxs } } end theorem firstn_prefixeq : Ξ (n : β„•) (xs : list A), firstn n xs βŠ‘β‚š xs | 0 xs := !nil | (succ n) [] := !nil | (succ n) (x::xs) := cons x (firstn_prefixeq n xs) theorem dropn_prefixeq_dropn_of_prefixeq : Ξ (n : β„•) {xs ys : list A} (H : xs βŠ‘β‚š ys), dropn n xs βŠ‘β‚š dropn n ys | 0 xs ys H := H | n [] ys H := by rewrite dropn_nil; apply !prefixeq.nil | (succ n) (x::xs) (x::ys) (cons x H) := by unfold dropn; apply dropn_prefixeq_dropn_of_prefixeq n H end end prefixeq namespace sorted section parameter {A : Type} parameter [decidable_linear_order A] definition insert_pos : list A β†’ A β†’ β„• | [] y := 0 | (x::xs) y := if y ≀ x then 0 else succ (insert_pos xs y) theorem insert_pos_le_length : Ξ (xs : list A) (y : A), insert_pos xs y ≀ length xs | [] y := zero_le _ | (x::xs) y := begin unfold insert_pos, cases (_ : decidable (y ≀ x)), { apply zero_le }, { apply succ_le_succ (insert_pos_le_length xs y) } end section variable {xs : list A} variable (Hsorted : sorted le xs) theorem first_le {x x' : A} (Hsorted : sorted le (x::xs)) (Hx'_mem : x' ∈ x::xs) : x ≀ x' := or.rec_on (eq_or_mem_of_mem_cons Hx'_mem) (assume H : x' = x, H β–Έ le.refl x') (assume H : x' ∈ xs, of_mem_of_all H (sorted_extends (@le.trans _ _) Hsorted)) include Hsorted theorem le_of_nth_le_nth {x₁ xβ‚‚ : A} : Ξ {i j : β„•}, nth xs i = some x₁ β†’ nth xs j = some xβ‚‚ β†’ i ≀ j β†’ x₁ ≀ xβ‚‚ := begin induction Hsorted using sorted.rec with y ys Hhd_rel Hsorted ih, { contradiction }, { intro i j Hi Hj Hle, cases i with i', { injection Hi with H, subst H, apply first_le (sorted.step Hhd_rel Hsorted) (mem_of_nth Hj) }, { cases j with j', { exfalso, apply !not_succ_le_zero Hle }, { unfold nth at Hi, unfold nth at Hj, apply ih Hi Hj (le_of_succ_le_succ Hle) } } } end theorem insert_pos_gt {y xi : A} {i : β„•} (Hyxi : y > xi) (Hnth : nth xs i = some xi) : insert_pos xs y > i := begin revert i Hnth, induction Hsorted using sorted.rec with x xs Hhd_rel Hsorted ih, { contradiction }, { unfold insert_pos, cases (_ : decidable (y ≀ x)) with Hyx Hyx, { intro i Hnth, exfalso, exact lt.irrefl _ ( calc x ≀ xi : first_le (sorted.step Hhd_rel Hsorted) (mem_of_nth Hnth) ... < y : Hyxi ... ≀ x : Hyx) }, { intro i Hnth, cases i with i, { apply zero_lt_succ }, { apply succ_lt_succ (ih i Hnth) } } } end theorem insert_pos_le {y xi : A} {i : β„•} (Hyxi : y < xi) (Hnth : nth xs i = some xi) : insert_pos xs y ≀ i := begin revert i Hnth, induction Hsorted using sorted.rec with x xs Hhd_rel Hsorted ih, { contradiction }, { unfold insert_pos, cases (_ : decidable (y ≀ x)) with Hyx Hyx, { intros, apply zero_le }, { intro i Hnth, cases i with i, { injection Hnth with Hx_eq_xi, exfalso, apply Hyx (le_of_lt (Hx_eq_xi⁻¹ β–Έ Hyxi)) }, { apply succ_le_succ (ih i Hnth) } } } end theorem sorted_insert_at_insert_pos (y : A) : sorted le (insert_at xs (insert_pos xs y) y) := begin note Hlsorted := locally_sorted_of_sorted Hsorted, clear Hsorted, apply sorted_of_locally_sorted, induction xs with x xs ih, { apply locally_sorted.base }, { unfold insert_pos, exact decidable.rec_on _ (suppose y ≀ x, locally_sorted.step this Hlsorted) (suppose Hyx : Β¬y ≀ x, begin cases xs with x' xs, { exact locally_sorted.step (le_of_not_ge Hyx) !locally_sorted.base }, { cases Hlsorted with _ _ _ _ Hxx' Hlsorted', rewrite [↑ite, ↑insert_at], revert ih, rewrite [↑insert_pos], exact decidable.rec_on _ (suppose y ≀ x', assume ih, locally_sorted.step (le_of_not_ge Hyx) (locally_sorted.step this Hlsorted')) (suppose Β¬y ≀ x', assume ih, locally_sorted.step Hxx' (ih Hlsorted')) } end) } end theorem sorted_dropn_of_sorted : Ξ (n : β„•), sorted le (dropn n xs) := begin induction Hsorted using sorted.rec with x xs Hhd_rel Hsorted ih, { intro n, rewrite dropn_nil, apply sorted.base }, { intro n, cases n, { apply sorted.step Hhd_rel Hsorted }, { unfold dropn, apply ih } } end omit Hsorted theorem hd_rel_of_prefix_of_hd_rel {x : A} {ys : list A} (Hprefix : prefixeq xs ys) (Hhd_rel : hd_rel le x ys) : hd_rel le x xs := begin cases Hhd_rel with y ys' Hxy, { cases Hprefix, apply hd_rel.base }, { cases Hprefix, { apply hd_rel.base }, { exact hd_rel.step _ Hxy } } end theorem sorted_of_prefix_of_sorted {ys : list A} (Hprefix : prefixeq xs ys) (Hsorted : sorted le ys) : sorted le xs := begin revert xs Hprefix, induction Hsorted using sorted.rec with y ys Hhd_rel Hsorted ih, all_goals intro xs Hprefix, { cases Hprefix, apply sorted.base }, { cases Hprefix with _ _ xs' _ Hprefix', { apply sorted.base }, { apply sorted.step (!hd_rel_of_prefix_of_hd_rel Hprefix' Hhd_rel) (ih xs' Hprefix') } } end end end end sorted end list namespace partial infixr ` ⇀ `:25 := Ξ»A B, A β†’ option B section parameters {A B : Type} {R : B β†’ B β†’ Prop} parameters (f : A ⇀ B) definition R' [unfold 3] : option B β†’ option B β†’ Prop | (some y) (some x) := R y x | _ _ := false private definition R'.wf (H : well_founded R) : well_founded R' := begin apply well_founded.intro, intro x, cases x with x', { apply acc.intro, intro y, cases y; repeat contradiction }, { induction (well_founded.apply H x') with x' _ ih, apply acc.intro, intro y HR', cases y with y', { contradiction }, { apply ih _ HR' } } end parameter (R) definition inv_image (f : A ⇀ B) : A β†’ A β†’ Prop := inv_image R' f parameter {R} lemma inv_image.wf (H : well_founded R) : well_founded (inv_image f) := inv_image.wf f (R'.wf H) end end partial namespace sum definition inl_opt [unfold 3] {A B : Type} : A + B β†’ option A | (inl a) := some a | (inr _) := none definition inr_opt [unfold 3] {A B : Type} : A + B β†’ option B | (inl _) := none | (inr b) := some b end sum -- generalized nat.le_lt_antisymm theorem le_lt_antisymm {T : Type} [order_pair T] {n m : T} (H1 : n ≀ m) (H2 : m < n) : false := !lt.irrefl (lt_of_le_of_lt H1 H2) namespace classical theorem dite_else_false {c : Prop} {t : c β†’ Prop} (Hdite : if H : c then t H else false) : c := if H : c then H else false.elim (dif_neg H β–Έ Hdite) end classical attribute dite [unfold 2] attribute ite [unfold 2] -- H as implicit instead of instance implicit for rewriting theorem if_pos' {c : Prop} {H : decidable c} (Hc : c) {A : Type} {t e : A} : (ite c t e) = t := decidable.rec (Ξ» Hc : c, eq.refl (@ite c (decidable.inl Hc) A t e)) (Ξ» Hnc : Β¬c, absurd Hc Hnc) H theorem if_neg' {c : Prop} {H : decidable c} (Hnc : Β¬c) {A : Type} {t e : A} : (ite c t e) = e := decidable.rec (Ξ» Hc : c, absurd Hc Hnc) (Ξ» Hnc : Β¬c, eq.refl (@ite c (decidable.inr Hnc) A t e)) H
d76dd5dff1401702443ca8a3fc1ee5c92fc06ce6
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/finset/sort.lean
0e3d62639b3d41c6a263dc9a111d7373c052004f
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
10,475
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.finset.lattice import data.multiset.sort /-! # Construct a sorted list from a finset. -/ namespace finset open multiset nat variables {Ξ± Ξ² : Type*} /-! ### sort -/ section sort variables (r : Ξ± β†’ Ξ± β†’ Prop) [decidable_rel r] [is_trans Ξ± r] [is_antisymm Ξ± r] [is_total Ξ± r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset Ξ±) : list Ξ± := sort r s.1 @[simp] theorem sort_sorted (s : finset Ξ±) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset Ξ±) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset Ξ±) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup Ξ± (sort r s)) @[simp] theorem sort_to_finset [decidable_eq Ξ±] (s : finset Ξ±) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) β–Έ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset Ξ±} {a : Ξ±} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ @[simp] theorem length_sort {s : finset Ξ±} : (sort r s).length = s.card := multiset.length_sort _ end sort section sort_linear_order variables [decidable_linear_order Ξ±] theorem sort_sorted_lt (s : finset Ξ±) : list.sorted (<) (sort (≀) s) := (sort_sorted _ _).impβ‚‚ (@lt_of_le_of_ne _ _) (sort_nodup _ _) lemma sorted_zero_eq_min'_aux (s : finset Ξ±) (h : 0 < (s.sort (≀)).length) (H : s.nonempty) : (s.sort (≀)).nth_le 0 h = s.min' H := begin let l := s.sort (≀), apply le_antisymm, { have : s.min' H ∈ l := (finset.mem_sort (≀)).mpr (s.min'_mem H), obtain ⟨i, i_lt, hi⟩ : βˆƒ i (hi : i < l.length), l.nth_le i hi = s.min' H := list.mem_iff_nth_le.1 this, rw ← hi, exact list.nth_le_of_sorted_of_le (s.sort_sorted (≀)) (nat.zero_le i) }, { have : l.nth_le 0 h ∈ s := (finset.mem_sort (≀)).1 (list.nth_le_mem l 0 h), exact s.min'_le _ this } end lemma sorted_zero_eq_min' {s : finset Ξ±} {h : 0 < (s.sort (≀)).length} : (s.sort (≀)).nth_le 0 h = s.min' (card_pos.1 $ by rwa length_sort at h) := sorted_zero_eq_min'_aux _ _ _ lemma min'_eq_sorted_zero {s : finset Ξ±} {h : s.nonempty} : s.min' h = (s.sort (≀)).nth_le 0 (by { rw length_sort, exact card_pos.2 h }) := (sorted_zero_eq_min'_aux _ _ _).symm lemma sorted_last_eq_max'_aux (s : finset Ξ±) (h : (s.sort (≀)).length - 1 < (s.sort (≀)).length) (H : s.nonempty) : (s.sort (≀)).nth_le ((s.sort (≀)).length - 1) h = s.max' H := begin let l := s.sort (≀), apply le_antisymm, { have : l.nth_le ((s.sort (≀)).length - 1) h ∈ s := (finset.mem_sort (≀)).1 (list.nth_le_mem l _ h), exact s.le_max' _ this }, { have : s.max' H ∈ l := (finset.mem_sort (≀)).mpr (s.max'_mem H), obtain ⟨i, i_lt, hi⟩ : βˆƒ i (hi : i < l.length), l.nth_le i hi = s.max' H := list.mem_iff_nth_le.1 this, rw ← hi, have : i ≀ l.length - 1 := nat.le_pred_of_lt i_lt, exact list.nth_le_of_sorted_of_le (s.sort_sorted (≀)) (nat.le_pred_of_lt i_lt) }, end lemma sorted_last_eq_max' {s : finset Ξ±} {h : (s.sort (≀)).length - 1 < (s.sort (≀)).length} : (s.sort (≀)).nth_le ((s.sort (≀)).length - 1) h = s.max' (by { rw length_sort at h, exact card_pos.1 (lt_of_le_of_lt bot_le h) }) := sorted_last_eq_max'_aux _ _ _ lemma max'_eq_sorted_last {s : finset Ξ±} {h : s.nonempty} : s.max' h = (s.sort (≀)).nth_le ((s.sort (≀)).length - 1) (by simpa using sub_lt (card_pos.mpr h) zero_lt_one) := (sorted_last_eq_max'_aux _ _ _).symm /-- Given a finset `s` of cardinal `k` in a linear order `Ξ±`, the map `mono_of_fin s h` is the increasing bijection between `fin k` and `s` as an `Ξ±`-valued map. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of a map `fin s.card β†’ Ξ±` to avoid casting issues in further uses of this function. -/ def mono_of_fin (s : finset Ξ±) {k : β„•} (h : s.card = k) (i : fin k) : Ξ± := have A : (i : β„•) < (s.sort (≀)).length, by simpa [h] using i.2, (s.sort (≀)).nth_le i A lemma mono_of_fin_strict_mono (s : finset Ξ±) {k : β„•} (h : s.card = k) : strict_mono (s.mono_of_fin h) := begin assume i j hij, exact list.pairwise_iff_nth_le.1 s.sort_sorted_lt _ _ _ hij end lemma mono_of_fin_bij_on (s : finset Ξ±) {k : β„•} (h : s.card = k) : set.bij_on (s.mono_of_fin h) set.univ ↑s := begin have A : βˆ€ j, j ∈ s ↔ j ∈ (s.sort (≀)) := Ξ» j, by simp, apply set.bij_on.mk, { assume i hi, simp only [mono_of_fin, set.mem_preimage, mem_coe, list.nth_le, A], exact list.nth_le_mem _ _ _ }, { exact ((mono_of_fin_strict_mono s h).injective).inj_on _ }, { assume x hx, simp only [mem_coe, A] at hx, obtain ⟨i, il, hi⟩ : βˆƒ (i : β„•) (h : i < (s.sort (≀)).length), (s.sort (≀)).nth_le i h = x := list.nth_le_of_mem hx, simp [h] at il, exact ⟨⟨i, il⟩, set.mem_univ _, hi⟩ } end lemma mono_of_fin_injective (s : finset Ξ±) {k : β„•} (h : s.card = k) : function.injective (s.mono_of_fin h) := set.injective_iff_inj_on_univ.mpr (s.mono_of_fin_bij_on h).inj_on /-- The bijection `mono_of_fin s h` sends `0` to the minimum of `s`. -/ lemma mono_of_fin_zero {s : finset Ξ±} {k : β„•} (h : s.card = k) (hz : 0 < k) : mono_of_fin s h ⟨0, hz⟩ = s.min' (card_pos.mp (h.symm β–Έ hz)) := begin apply le_antisymm, { have : min' s _ ∈ s := min'_mem s _, rcases (mono_of_fin_bij_on s h).surj_on this with ⟨a, _, ha⟩, rw ← ha, apply (mono_of_fin_strict_mono s h).monotone, exact zero_le a.val }, { have : mono_of_fin s h ⟨0, hz⟩ ∈ s := (mono_of_fin_bij_on s h).maps_to (set.mem_univ _), exact min'_le s _ this } end /-- The bijection `mono_of_fin s h` sends `k-1` to the maximum of `s`. -/ lemma mono_of_fin_last {s : finset Ξ±} {k : β„•} (h : s.card = k) (hz : 0 < k) : mono_of_fin s h ⟨k-1, buffer.lt_aux_2 hz⟩ = s.max' (card_pos.mp (h.symm β–Έ hz)) := begin have h'' : k - 1 < k := buffer.lt_aux_2 hz, apply le_antisymm, { have : mono_of_fin s h ⟨k-1, h''⟩ ∈ s := (mono_of_fin_bij_on s h).maps_to (set.mem_univ _), exact le_max' s _ this }, { have : max' s _ ∈ s := max'_mem s _, rcases (mono_of_fin_bij_on s h).surj_on this with ⟨a, _, ha⟩, rw ← ha, apply (mono_of_fin_strict_mono s h).monotone, exact le_pred_of_lt a.2}, end /-- `mono_of_fin {a} h` sends any argument to `a`. -/ @[simp] lemma mono_of_fin_singleton (a : Ξ±) (i : fin 1) {h} : mono_of_fin {a} h i = a := by rw [subsingleton.elim i ⟨0, zero_lt_one⟩, mono_of_fin_zero h zero_lt_one, min'_singleton] /-- The range of `mono_of_fin`. -/ @[simp] lemma range_mono_of_fin {s : finset Ξ±} {k : β„•} (h : s.card = k) : set.range (s.mono_of_fin h) = ↑s := begin rw ←set.image_univ, exact (mono_of_fin_bij_on s h).image_eq end /-- Any increasing bijection between `fin k` and a finset of cardinality `k` has to coincide with the increasing bijection `mono_of_fin s h`. For a statement assuming only that `f` maps `univ` to `s`, see `mono_of_fin_unique'`.-/ lemma mono_of_fin_unique {s : finset Ξ±} {k : β„•} (h : s.card = k) {f : fin k β†’ Ξ±} (hbij : set.bij_on f set.univ ↑s) (hmono : strict_mono f) : f = s.mono_of_fin h := begin ext ⟨i, hi⟩, induction i using nat.strong_induction_on with i IH, rcases lt_trichotomy (f ⟨i, hi⟩) (mono_of_fin s h ⟨i, hi⟩) with H|H|H, { have A : f ⟨i, hi⟩ ∈ ↑s := hbij.maps_to (set.mem_univ _), rcases (mono_of_fin_bij_on s h).surj_on A with ⟨j, _, hj⟩, rw ← hj at H, have ji : j < ⟨i, hi⟩ := (mono_of_fin_strict_mono s h).lt_iff_lt.1 H, have : f j = mono_of_fin s h j, by { convert IH j ji (lt_trans ji hi), rw [fin.ext_iff, fin.coe_mk] }, rw ← this at hj, exact (ne_of_lt (hmono ji) hj).elim }, { exact H }, { have A : mono_of_fin s h ⟨i, hi⟩ ∈ ↑s := (mono_of_fin_bij_on s h).maps_to (set.mem_univ _), rcases hbij.surj_on A with ⟨j, _, hj⟩, rw ← hj at H, have ji : j < ⟨i, hi⟩ := hmono.lt_iff_lt.1 H, have : f j = mono_of_fin s h j, by { convert IH j ji (lt_trans ji hi), rw [fin.ext_iff, fin.coe_mk] }, rw this at hj, exact (ne_of_lt (mono_of_fin_strict_mono s h ji) hj).elim } end /-- Any increasing map between `fin k` and a finset of cardinality `k` has to coincide with the increasing bijection `mono_of_fin s h`. -/ lemma mono_of_fin_unique' {s : finset Ξ±} {k : β„•} (h : s.card = k) {f : fin k β†’ Ξ±} (fmap : set.maps_to f set.univ ↑s) (hmono : strict_mono f) : f = s.mono_of_fin h := begin have finj : set.inj_on f set.univ := hmono.injective.inj_on _, apply mono_of_fin_unique h (set.bij_on.mk fmap finj (Ξ» y hy, _)) hmono, simp only [set.image_univ, set.mem_range], rcases surj_on_of_inj_on_of_card_le (Ξ» i (hi : i ∈ finset.fin_range k), f i) (Ξ» i hi, fmap (set.mem_univ i)) (Ξ» i j hi hj hij, finj (set.mem_univ i) (set.mem_univ j) hij) (by simp [h]) y hy with ⟨x, _, hx⟩, exact ⟨x, hx.symm⟩ end /-- Two parametrizations `mono_of_fin` of the same set take the same value on `i` and `j` if and only if `i = j`. Since they can be defined on a priori not defeq types `fin k` and `fin l` (although necessarily `k = l`), the conclusion is rather written `(i : β„•) = (j : β„•)`. -/ @[simp] lemma mono_of_fin_eq_mono_of_fin_iff {k l : β„•} {s : finset Ξ±} {i : fin k} {j : fin l} {h : s.card = k} {h' : s.card = l} : s.mono_of_fin h i = s.mono_of_fin h' j ↔ (i : β„•) = (j : β„•) := begin have A : k = l, by rw [← h', ← h], have : s.mono_of_fin h = (s.mono_of_fin h') ∘ (Ξ» j : (fin k), ⟨j, A β–Έ j.is_lt⟩) := rfl, rw [this, function.comp_app, (s.mono_of_fin_injective h').eq_iff, fin.ext_iff, fin.coe_mk] end /-- Given a finset `s` of cardinal `k` in a linear order `Ξ±`, the equiv `mono_equiv_of_fin s h` is the increasing bijection between `fin k` and `s` as an `s`-valued map. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of a map `fin s.card β†’ Ξ±` to avoid casting issues in further uses of this function. -/ noncomputable def mono_equiv_of_fin (s : finset Ξ±) {k : β„•} (h : s.card = k) : fin k ≃ {x // x ∈ s} := (s.mono_of_fin_bij_on h).equiv _ end sort_linear_order instance [has_repr Ξ±] : has_repr (finset Ξ±) := ⟨λ s, repr s.1⟩ end finset
143d356141f12480a96dbbc1f3d1fb5e25cd18d6
ac1c2a2f522b0fdf854095ba00f882ca849669e7
/library/init/data/to_string.lean
4e8ae12c6303e68389ac765b34bb59a37c5b949a
[ "Apache-2.0" ]
permissive
abliss/lean
b8b336abc8d50dbb0726dcff9dd16793c23bfbe1
fb24cc99573c153f97a1951ee94bbbdda300b6be
refs/heads/master
1,611,536,584,520
1,497,811,981,000
1,497,811,981,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,670
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.string.basic init.data.bool.basic init.data.subtype.basic import init.data.unsigned.basic init.data.prod init.data.sum.basic init.data.nat.div open sum subtype nat universes u v class has_to_string (Ξ± : Type u) := (to_string : Ξ± β†’ string) def to_string {Ξ± : Type u} [has_to_string Ξ±] : Ξ± β†’ string := has_to_string.to_string instance : has_to_string bool := ⟨λ b, cond b "tt" "ff"⟩ instance {p : Prop} : has_to_string (decidable p) := -- Remark: type class inference will not consider local instance `b` in the new elaborator ⟨λ b : decidable p, @ite p b _ "tt" "ff"⟩ protected def list.to_string_aux {Ξ± : Type u} [has_to_string Ξ±] : bool β†’ list Ξ± β†’ string | b [] := "" | tt (x::xs) := to_string x ++ list.to_string_aux ff xs | ff (x::xs) := ", " ++ to_string x ++ list.to_string_aux ff xs protected def list.to_string {Ξ± : Type u} [has_to_string Ξ±] : list Ξ± β†’ string | [] := "[]" | (x::xs) := "[" ++ list.to_string_aux tt (x::xs) ++ "]" instance {Ξ± : Type u} [has_to_string Ξ±] : has_to_string (list Ξ±) := ⟨list.to_string⟩ instance : has_to_string unit := ⟨λ u, "star"⟩ instance {Ξ± : Type u} [has_to_string Ξ±] : has_to_string (option Ξ±) := ⟨λ o, match o with | none := "none" | (some a) := "(some " ++ to_string a ++ ")" end⟩ instance {Ξ± : Type u} {Ξ² : Type v} [has_to_string Ξ±] [has_to_string Ξ²] : has_to_string (Ξ± βŠ• Ξ²) := ⟨λ s, match s with | (inl a) := "(inl " ++ to_string a ++ ")" | (inr b) := "(inr " ++ to_string b ++ ")" end⟩ instance {Ξ± : Type u} {Ξ² : Type v} [has_to_string Ξ±] [has_to_string Ξ²] : has_to_string (Ξ± Γ— Ξ²) := ⟨λ ⟨a, b⟩, "(" ++ to_string a ++ ", " ++ to_string b ++ ")"⟩ instance {Ξ± : Type u} {Ξ² : Ξ± β†’ Type v} [has_to_string Ξ±] [s : βˆ€ x, has_to_string (Ξ² x)] : has_to_string (sigma Ξ²) := ⟨λ ⟨a, b⟩, "⟨" ++ to_string a ++ ", " ++ to_string b ++ "⟩"⟩ instance {Ξ± : Type u} {p : Ξ± β†’ Prop} [has_to_string Ξ±] : has_to_string (subtype p) := ⟨λ s, to_string (val s)⟩ /- Remark: the code generator replaces this definition with one that display natural numbers in decimal notation -/ protected def nat.to_string : nat β†’ string | 0 := "zero" | (succ a) := "(succ " ++ nat.to_string a ++ ")" instance : has_to_string nat := ⟨nat.to_string⟩ def hex_digit_to_string (n : nat) : string := if n ≀ 9 then to_string n else if n = 10 then "a" else if n = 11 then "b" else if n = 12 then "c" else if n = 13 then "d" else if n = 14 then "e" else "f" def char_to_hex (c : char) : string := let n := char.to_nat c, d2 := n / 16, d1 := n % 16 in hex_digit_to_string d2 ++ hex_digit_to_string d1 def char.quote_core (c : char) : string := if c = '\n' then "\\n" else if c = '\t' then "\\t" else if c = '\\' then "\\\\" else if c = '\"' then "\\\"" else if char.to_nat c <= 31 then "\\x" ++ char_to_hex c else string.singleton c instance : has_to_string char := ⟨λ c, "'" ++ char.quote_core c ++ "'"⟩ def string.quote_aux : list char β†’ string | [] := "" | (x::xs) := char.quote_core x ++ string.quote_aux xs def string.quote (s : string) : string := if s.is_empty = tt then "\"\"" else "\"" ++ string.quote_aux s.to_list ++ "\"" instance : has_to_string string := ⟨string.quote⟩ instance (n : nat) : has_to_string (fin n) := ⟨λ f, to_string (fin.val f)⟩ instance : has_to_string unsigned := ⟨λ n, to_string (fin.val n)⟩ def char.to_string (c : char) : string := to_string c
58e63007a6d0fc0316ae0602350ee252685ea2b2
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/algebra/monoid.lean
ee3b1845b415330c461261e9fd6c02007a0bca18
[]
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
12,071
lean
/- Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.continuous_on import Mathlib.group_theory.submonoid.basic import Mathlib.algebra.group.prod import Mathlib.algebra.pointwise import Mathlib.PostPort universes u_5 l u_3 u_1 u_4 u_2 namespace Mathlib /-! # Theory of topological monoids In this file we define mixin classes `has_continuous_mul` and `has_continuous_add`. While in many applications the underlying type is a monoid (multiplicative or additive), we do not require this in the definitions. -/ /-- Basic hypothesis to talk about a topological additive monoid or a topological additive semigroup. A topological additive monoid over `Ξ±`, for example, is obtained by requiring both the instances `add_monoid Ξ±` and `has_continuous_add Ξ±`. -/ class has_continuous_add (M : Type u_5) [topological_space M] [Add M] where continuous_add : continuous fun (p : M Γ— M) => prod.fst p + prod.snd p /-- Basic hypothesis to talk about a topological monoid or a topological semigroup. A topological monoid over `Ξ±`, for example, is obtained by requiring both the instances `monoid Ξ±` and `has_continuous_mul Ξ±`. -/ class has_continuous_mul (M : Type u_5) [topological_space M] [Mul M] where continuous_mul : continuous fun (p : M Γ— M) => prod.fst p * prod.snd p theorem continuous_add {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] : continuous fun (p : M Γ— M) => prod.fst p + prod.snd p := has_continuous_add.continuous_add theorem continuous.mul {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Mul M] [has_continuous_mul M] [topological_space Ξ±] {f : Ξ± β†’ M} {g : Ξ± β†’ M} (hf : continuous f) (hg : continuous g) : continuous fun (x : Ξ±) => f x * g x := continuous.comp continuous_mul (continuous.prod_mk hf hg) -- should `to_additive` be doing this? theorem continuous_add_left {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] (a : M) : continuous fun (b : M) => a + b := continuous.add continuous_const continuous_id theorem continuous_add_right {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] (a : M) : continuous fun (b : M) => b + a := continuous.add continuous_id continuous_const theorem continuous_on.add {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] [topological_space Ξ±] {f : Ξ± β†’ M} {g : Ξ± β†’ M} {s : set Ξ±} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (fun (x : Ξ±) => f x + g x) s := continuous.comp_continuous_on continuous_add (continuous_on.prod hf hg) theorem tendsto_add {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] {a : M} {b : M} : filter.tendsto (fun (p : M Γ— M) => prod.fst p + prod.snd p) (nhds (a, b)) (nhds (a + b)) := iff.mp continuous_iff_continuous_at has_continuous_add.continuous_add (a, b) theorem filter.tendsto.add {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] {f : Ξ± β†’ M} {g : Ξ± β†’ M} {x : filter Ξ±} {a : M} {b : M} (hf : filter.tendsto f x (nhds a)) (hg : filter.tendsto g x (nhds b)) : filter.tendsto (fun (x : Ξ±) => f x + g x) x (nhds (a + b)) := filter.tendsto.comp tendsto_add (filter.tendsto.prod_mk_nhds hf hg) theorem tendsto.const_mul {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Mul M] [has_continuous_mul M] (b : M) {c : M} {f : Ξ± β†’ M} {l : filter Ξ±} (h : filter.tendsto (fun (k : Ξ±) => f k) l (nhds c)) : filter.tendsto (fun (k : Ξ±) => b * f k) l (nhds (b * c)) := filter.tendsto.mul tendsto_const_nhds h theorem tendsto.add_const {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] (b : M) {c : M} {f : Ξ± β†’ M} {l : filter Ξ±} (h : filter.tendsto (fun (k : Ξ±) => f k) l (nhds c)) : filter.tendsto (fun (k : Ξ±) => f k + b) l (nhds (c + b)) := filter.tendsto.add h tendsto_const_nhds theorem continuous_at.add {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] [topological_space Ξ±] {f : Ξ± β†’ M} {g : Ξ± β†’ M} {x : Ξ±} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (fun (x : Ξ±) => f x + g x) x := filter.tendsto.add hf hg theorem continuous_within_at.add {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] [topological_space Ξ±] {f : Ξ± β†’ M} {g : Ξ± β†’ M} {s : set Ξ±} {x : Ξ±} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (fun (x : Ξ±) => f x + g x) s x := filter.tendsto.add hf hg protected instance prod.has_continuous_mul {M : Type u_3} {N : Type u_4} [topological_space M] [Mul M] [has_continuous_mul M] [topological_space N] [Mul N] [has_continuous_mul N] : has_continuous_mul (M Γ— N) := has_continuous_mul.mk (continuous.prod_mk (continuous.mul (continuous.comp continuous_fst continuous_fst) (continuous.comp continuous_fst continuous_snd)) (continuous.mul (continuous.comp continuous_snd continuous_fst) (continuous.comp continuous_snd continuous_snd))) protected instance has_continuous_mul_of_discrete_topology {N : Type u_4} [topological_space N] [Mul N] [discrete_topology N] : has_continuous_mul N := has_continuous_mul.mk continuous_of_discrete_topology theorem has_continuous_mul.of_nhds_one {M : Type (max u_1 u_2)} [monoid M] [topological_space M] (hmul : filter.tendsto (function.uncurry Mul.mul) (filter.prod (nhds 1) (nhds 1)) (nhds 1)) (hleft : βˆ€ (xβ‚€ : M), nhds xβ‚€ = filter.map (fun (x : M) => xβ‚€ * x) (nhds 1)) (hright : βˆ€ (xβ‚€ : M), nhds xβ‚€ = filter.map (fun (x : M) => x * xβ‚€) (nhds 1)) : has_continuous_mul M := sorry theorem has_continuous_mul_of_comm_of_nhds_one (M : Type (max u_1 u_2)) [comm_monoid M] [topological_space M] (hmul : filter.tendsto (function.uncurry Mul.mul) (filter.prod (nhds 1) (nhds 1)) (nhds 1)) (hleft : βˆ€ (xβ‚€ : M), nhds xβ‚€ = filter.map (fun (x : M) => xβ‚€ * x) (nhds 1)) : has_continuous_mul M := sorry theorem add_submonoid.top_closure_add_self_subset {M : Type u_3} [topological_space M] [add_monoid M] [has_continuous_add M] (s : add_submonoid M) : closure ↑s + closure ↑s βŠ† closure ↑s := sorry theorem submonoid.top_closure_mul_self_eq {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] (s : submonoid M) : closure ↑s * closure ↑s = closure ↑s := sorry /-- The (topological-space) closure of a submonoid of a space `M` with `has_continuous_mul` is itself a submonoid. -/ def add_submonoid.topological_closure {M : Type u_3} [topological_space M] [add_monoid M] [has_continuous_add M] (s : add_submonoid M) : add_submonoid M := add_submonoid.mk (closure ↑s) sorry sorry theorem submonoid.submonoid_topological_closure {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] (s : submonoid M) : s ≀ submonoid.topological_closure s := subset_closure theorem submonoid.is_closed_topological_closure {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] (s : submonoid M) : is_closed ↑(submonoid.topological_closure s) := sorry theorem submonoid.topological_closure_minimal {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] (s : submonoid M) {t : submonoid M} (h : s ≀ t) (ht : is_closed ↑t) : submonoid.topological_closure s ≀ t := closure_minimal h ht theorem exists_open_nhds_zero_half {M : Type u_3} [topological_space M] [add_monoid M] [has_continuous_add M] {s : set M} (hs : s ∈ nhds 0) : βˆƒ (V : set M), is_open V ∧ 0 ∈ V ∧ βˆ€ (v : M), v ∈ V β†’ βˆ€ (w : M), w ∈ V β†’ v + w ∈ s := sorry theorem exists_nhds_zero_half {M : Type u_3} [topological_space M] [add_monoid M] [has_continuous_add M] {s : set M} (hs : s ∈ nhds 0) : βˆƒ (V : set M), βˆƒ (H : V ∈ nhds 0), βˆ€ (v : M), v ∈ V β†’ βˆ€ (w : M), w ∈ V β†’ v + w ∈ s := sorry theorem exists_nhds_one_split4 {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] {u : set M} (hu : u ∈ nhds 1) : βˆƒ (V : set M), βˆƒ (H : V ∈ nhds 1), βˆ€ {v w s t : M}, v ∈ V β†’ w ∈ V β†’ s ∈ V β†’ t ∈ V β†’ v * w * s * t ∈ u := sorry /-- Given a neighborhood `U` of `1` there is an open neighborhood `V` of `1` such that `VV βŠ† U`. -/ theorem exists_open_nhds_one_mul_subset {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] {U : set M} (hU : U ∈ nhds 1) : βˆƒ (V : set M), is_open V ∧ 1 ∈ V ∧ V * V βŠ† U := sorry theorem tendsto_list_sum {Ξ± : Type u_1} {Ξ² : Type u_2} {M : Type u_3} [topological_space M] [add_monoid M] [has_continuous_add M] {f : Ξ² β†’ Ξ± β†’ M} {x : filter Ξ±} {a : Ξ² β†’ M} (l : List Ξ²) : (βˆ€ (c : Ξ²), c ∈ l β†’ filter.tendsto (f c) x (nhds (a c))) β†’ filter.tendsto (fun (b : Ξ±) => list.sum (list.map (fun (c : Ξ²) => f c b) l)) x (nhds (list.sum (list.map a l))) := sorry theorem continuous_list_sum {Ξ± : Type u_1} {Ξ² : Type u_2} {M : Type u_3} [topological_space M] [add_monoid M] [has_continuous_add M] [topological_space Ξ±] {f : Ξ² β†’ Ξ± β†’ M} (l : List Ξ²) (h : βˆ€ (c : Ξ²), c ∈ l β†’ continuous (f c)) : continuous fun (a : Ξ±) => list.sum (list.map (fun (c : Ξ²) => f c a) l) := iff.mpr continuous_iff_continuous_at fun (x : Ξ±) => tendsto_list_sum l fun (c : Ξ²) (hc : c ∈ l) => iff.mp continuous_iff_continuous_at (h c hc) x -- @[to_additive continuous_smul] theorem continuous_pow {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] (n : β„•) : continuous fun (a : M) => a ^ n := sorry theorem continuous.pow {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] {f : Ξ± β†’ M} [topological_space Ξ±] (h : continuous f) (n : β„•) : continuous fun (b : Ξ±) => f b ^ n := continuous.comp (continuous_pow n) h theorem submonoid.mem_nhds_one {M : Type u_3} [topological_space M] [comm_monoid M] (S : submonoid M) (oS : is_open ↑S) : ↑S ∈ nhds 1 := mem_nhds_sets oS (submonoid.one_mem S) theorem tendsto_multiset_prod {Ξ± : Type u_1} {Ξ² : Type u_2} {M : Type u_3} [topological_space M] [comm_monoid M] [has_continuous_mul M] {f : Ξ² β†’ Ξ± β†’ M} {x : filter Ξ±} {a : Ξ² β†’ M} (s : multiset Ξ²) : (βˆ€ (c : Ξ²), c ∈ s β†’ filter.tendsto (f c) x (nhds (a c))) β†’ filter.tendsto (fun (b : Ξ±) => multiset.prod (multiset.map (fun (c : Ξ²) => f c b) s)) x (nhds (multiset.prod (multiset.map a s))) := sorry theorem tendsto_finset_sum {Ξ± : Type u_1} {Ξ² : Type u_2} {M : Type u_3} [topological_space M] [add_comm_monoid M] [has_continuous_add M] {f : Ξ² β†’ Ξ± β†’ M} {x : filter Ξ±} {a : Ξ² β†’ M} (s : finset Ξ²) : (βˆ€ (c : Ξ²), c ∈ s β†’ filter.tendsto (f c) x (nhds (a c))) β†’ filter.tendsto (fun (b : Ξ±) => finset.sum s fun (c : Ξ²) => f c b) x (nhds (finset.sum s fun (c : Ξ²) => a c)) := tendsto_multiset_sum (finset.val s) theorem continuous_multiset_prod {Ξ± : Type u_1} {Ξ² : Type u_2} {M : Type u_3} [topological_space M] [comm_monoid M] [has_continuous_mul M] [topological_space Ξ±] {f : Ξ² β†’ Ξ± β†’ M} (s : multiset Ξ²) : (βˆ€ (c : Ξ²), c ∈ s β†’ continuous (f c)) β†’ continuous fun (a : Ξ±) => multiset.prod (multiset.map (fun (c : Ξ²) => f c a) s) := sorry theorem continuous_finset_prod {Ξ± : Type u_1} {Ξ² : Type u_2} {M : Type u_3} [topological_space M] [comm_monoid M] [has_continuous_mul M] [topological_space Ξ±] {f : Ξ² β†’ Ξ± β†’ M} (s : finset Ξ²) : (βˆ€ (c : Ξ²), c ∈ s β†’ continuous (f c)) β†’ continuous fun (a : Ξ±) => finset.prod s fun (c : Ξ²) => f c a := continuous_multiset_prod (finset.val s) -- should `to_additive` be doing this? protected instance additive.has_continuous_add {M : Type u_1} [h : topological_space M] [Mul M] [has_continuous_mul M] : has_continuous_add (additive M) := has_continuous_add.mk continuous_mul protected instance multiplicative.has_continuous_mul {M : Type u_1} [h : topological_space M] [Add M] [has_continuous_add M] : has_continuous_mul (multiplicative M) := has_continuous_mul.mk continuous_add
0c7a995643d8ec49001f49794af1af54ee484c06
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/measure_theory/lebesgue_measure.lean
fb7863c2d6bdeeef31c93f92123a6ac949118ce0
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
13,724
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 measure_theory.measure_space import measure_theory.borel_space /-! # Lebesgue measure on the real line -/ noncomputable theory open classical set filter open ennreal (of_real) open_locale big_operators namespace measure_theory /-- Length of an interval. This is the largest monotonic function which correctly measures all intervals. -/ def lebesgue_length (s : set ℝ) : ennreal := β¨…a b (h : s βŠ† Ico a b), of_real (b - a) @[simp] lemma lebesgue_length_empty : lebesgue_length βˆ… = 0 := le_zero_iff_eq.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp @[simp] lemma lebesgue_length_Ico (a b : ℝ) : lebesgue_length (Ico a b) = of_real (b - a) := begin refine le_antisymm (infi_le_of_le a $ binfi_le b (subset.refl _)) (le_infi $ Ξ» a', le_infi $ Ξ» b', le_infi $ Ξ» h, ennreal.coe_le_coe.2 _), cases le_or_lt b a with ab ab, { rw nnreal.of_real_of_nonpos (sub_nonpos.2 ab), apply zero_le }, cases (Ico_subset_Ico_iff ab).1 h with h₁ hβ‚‚, exact nnreal.of_real_le_of_real (sub_le_sub hβ‚‚ h₁) end lemma lebesgue_length_mono {s₁ sβ‚‚ : set ℝ} (h : s₁ βŠ† sβ‚‚) : lebesgue_length s₁ ≀ lebesgue_length sβ‚‚ := infi_le_infi $ Ξ» a, infi_le_infi $ Ξ» b, infi_le_infi2 $ Ξ» h', ⟨subset.trans h h', le_refl _⟩ lemma lebesgue_length_eq_infi_Ioo (s) : lebesgue_length s = β¨…a b (h : s βŠ† Ioo a b), of_real (b - a) := begin refine le_antisymm (infi_le_infi $ Ξ» a, infi_le_infi $ Ξ» b, infi_le_infi2 $ Ξ» h, ⟨subset.trans h Ioo_subset_Ico_self, le_refl _⟩) _, refine le_infi (Ξ» a, le_infi $ Ξ» b, le_infi $ Ξ» h, _), refine ennreal.le_of_forall_epsilon_le (Ξ» Ξ΅ Ξ΅0 _, _), refine infi_le_of_le (a - Ξ΅) (infi_le_of_le b $ infi_le_of_le (subset.trans h $ Ico_subset_Ioo_left $ (sub_lt_self_iff _).2 Ξ΅0) _), rw ← sub_add, refine le_trans ennreal.of_real_add_le (add_le_add_left _ _), simp only [ennreal.of_real_coe_nnreal, le_refl] end @[simp] lemma lebesgue_length_Ioo (a b : ℝ) : lebesgue_length (Ioo a b) = of_real (b - a) := begin rw ← lebesgue_length_Ico, refine le_antisymm (lebesgue_length_mono Ioo_subset_Ico_self) _, rw lebesgue_length_eq_infi_Ioo (Ioo a b), refine (le_infi $ Ξ» a', le_infi $ Ξ» b', le_infi $ Ξ» h, _), cases le_or_lt b a with ab ab, {simp [ab]}, cases (Ioo_subset_Ioo_iff ab).1 h with h₁ hβ‚‚, rw [lebesgue_length_Ico], exact ennreal.of_real_le_of_real (sub_le_sub hβ‚‚ h₁) end lemma lebesgue_length_eq_infi_Icc (s) : lebesgue_length s = β¨…a b (h : s βŠ† Icc a b), of_real (b - a) := begin refine le_antisymm _ (infi_le_infi $ Ξ» a, infi_le_infi $ Ξ» b, infi_le_infi2 $ Ξ» h, ⟨subset.trans h Ico_subset_Icc_self, le_refl _⟩), refine le_infi (Ξ» a, le_infi $ Ξ» b, le_infi $ Ξ» h, _), refine ennreal.le_of_forall_epsilon_le (Ξ» Ξ΅ Ξ΅0 _, _), refine infi_le_of_le a (infi_le_of_le (b + Ξ΅) $ infi_le_of_le (subset.trans h $ Icc_subset_Ico_right $ (lt_add_iff_pos_right _).2 Ξ΅0) _), rw [← sub_add_eq_add_sub], refine le_trans ennreal.of_real_add_le (add_le_add_left _ _), simp only [ennreal.of_real_coe_nnreal, le_refl] end @[simp] lemma lebesgue_length_Icc (a b : ℝ) : lebesgue_length (Icc a b) = of_real (b - a) := begin rw ← lebesgue_length_Ico, refine le_antisymm _ (lebesgue_length_mono Ico_subset_Icc_self), rw lebesgue_length_eq_infi_Icc (Icc a b), exact infi_le_of_le a (infi_le_of_le b $ infi_le_of_le (by refl) (by simp [le_refl])) end /-- The Lebesgue outer measure, as an outer measure of ℝ. -/ def lebesgue_outer : outer_measure ℝ := outer_measure.of_function lebesgue_length lebesgue_length_empty lemma lebesgue_outer_le_length (s : set ℝ) : lebesgue_outer s ≀ lebesgue_length s := outer_measure.of_function_le _ lemma lebesgue_length_subadditive {a b : ℝ} {c d : β„• β†’ ℝ} (ss : Icc a b βŠ† ⋃i, Ioo (c i) (d i)) : (of_real (b - a) : ennreal) ≀ βˆ‘' i, of_real (d i - c i) := begin suffices : βˆ€ (s:finset β„•) b (cv : Icc a b βŠ† ⋃ i ∈ (↑s:set β„•), Ioo (c i) (d i)), (of_real (b - a) : ennreal) ≀ βˆ‘ i in s, of_real (d i - c i), { rcases compact_Icc.elim_finite_subcover_image (Ξ» (i : β„•) (_ : i ∈ univ), @is_open_Ioo _ _ _ _ (c i) (d i)) (by simpa using ss) with ⟨s, su, hf, hs⟩, have e : (⋃ i ∈ (↑hf.to_finset:set β„•), Ioo (c i) (d i)) = (⋃ i ∈ s, Ioo (c i) (d i)), {simp [set.ext_iff]}, rw ennreal.tsum_eq_supr_sum, refine le_trans _ (le_supr _ hf.to_finset), exact this hf.to_finset _ (by simpa [e]) }, clear ss b, refine Ξ» s, finset.strong_induction_on s (Ξ» s IH b cv, _), cases le_total b a with ab ab, { rw ennreal.of_real_eq_zero.2 (sub_nonpos.2 ab), exact zero_le _ }, have := cv ⟨ab, le_refl _⟩, simp at this, rcases this with ⟨i, is, cb, bd⟩, rw [← finset.insert_erase is] at cv ⊒, rw [finset.coe_insert, bUnion_insert] at cv, rw [finset.sum_insert (finset.not_mem_erase _ _)], refine le_trans _ (add_le_add_left (IH _ (finset.erase_ssubset is) (c i) _) _), { refine le_trans (ennreal.of_real_le_of_real _) ennreal.of_real_add_le, rw sub_add_sub_cancel, exact sub_le_sub_right (le_of_lt bd) _ }, { rintro x ⟨h₁, hβ‚‚βŸ©, refine (cv ⟨h₁, le_trans hβ‚‚ (le_of_lt cb)⟩).resolve_left (mt and.left (not_lt_of_le hβ‚‚)) } end @[simp] lemma lebesgue_outer_Icc (a b : ℝ) : lebesgue_outer (Icc a b) = of_real (b - a) := begin refine le_antisymm (by rw ← lebesgue_length_Icc; apply lebesgue_outer_le_length) (le_binfi $ Ξ» f hf, ennreal.le_of_forall_epsilon_le $ Ξ» Ξ΅ Ξ΅0 h, _), rcases ennreal.exists_pos_sum_of_encodable (ennreal.zero_lt_coe_iff.2 Ξ΅0) β„• with ⟨Ρ', Ξ΅'0, hΡ⟩, refine le_trans _ (add_le_add_left (le_of_lt hΞ΅) _), rw ← ennreal.tsum_add, choose g hg using show βˆ€ i, βˆƒ p:ℝ×ℝ, f i βŠ† Ioo p.1 p.2 ∧ (of_real (p.2 - p.1) : ennreal) < lebesgue_length (f i) + Ξ΅' i, { intro i, have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h) (ennreal.zero_lt_coe_iff.2 (Ξ΅'0 i))), conv at this {to_lhs, rw lebesgue_length_eq_infi_Ioo}, simpa [infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ Ξ» i, le_of_lt (hg i).2), exact lebesgue_length_subadditive (subset.trans hf $ Union_subset_Union $ Ξ» i, (hg i).1) end @[simp] lemma lebesgue_outer_singleton (a : ℝ) : lebesgue_outer {a} = 0 := by simpa using lebesgue_outer_Icc a a @[simp] lemma lebesgue_outer_Ico (a b : ℝ) : lebesgue_outer (Ico a b) = of_real (b - a) := by rw [← Icc_diff_right, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _), lebesgue_outer_Icc] @[simp] lemma lebesgue_outer_Ioo (a b : ℝ) : lebesgue_outer (Ioo a b) = of_real (b - a) := by rw [← Ico_diff_left, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _), lebesgue_outer_Ico] @[simp] lemma lebesgue_outer_Ioc (a b : ℝ) : lebesgue_outer (Ioc a b) = of_real (b - a) := by rw [← Icc_diff_left, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _), lebesgue_outer_Icc] lemma is_lebesgue_measurable_Iio {c : ℝ} : lebesgue_outer.caratheodory.is_measurable' (Iio c) := outer_measure.of_function_caratheodory $ Ξ» t, le_infi $ Ξ» a, le_infi $ Ξ» b, le_infi $ Ξ» h, begin refine le_trans (add_le_add (lebesgue_length_mono $ inter_subset_inter_left _ h) (lebesgue_length_mono $ diff_subset_diff_left h)) _, cases le_total a c with hac hca; cases le_total b c with hbc hcb; simp [*, -sub_eq_add_neg, sub_add_sub_cancel', le_refl], { simp [*, ← ennreal.of_real_add, -sub_eq_add_neg, sub_add_sub_cancel', le_refl] }, { simp only [ennreal.of_real_eq_zero.2 (sub_nonpos.2 (le_trans hbc hca)), zero_add, le_refl] } end theorem lebesgue_outer_trim : lebesgue_outer.trim = lebesgue_outer := begin refine le_antisymm (Ξ» s, _) (outer_measure.le_trim _), rw outer_measure.trim_eq_infi, refine le_infi (Ξ» f, le_infi $ Ξ» hf, ennreal.le_of_forall_epsilon_le $ Ξ» Ξ΅ Ξ΅0 h, _), rcases ennreal.exists_pos_sum_of_encodable (ennreal.zero_lt_coe_iff.2 Ξ΅0) β„• with ⟨Ρ', Ξ΅'0, hΡ⟩, refine le_trans _ (add_le_add_left (le_of_lt hΞ΅) _), rw ← ennreal.tsum_add, choose g hg using show βˆ€ i, βˆƒ s, f i βŠ† s ∧ is_measurable s ∧ lebesgue_outer s ≀ lebesgue_length (f i) + of_real (Ξ΅' i), { intro i, have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h) (ennreal.zero_lt_coe_iff.2 (Ξ΅'0 i))), conv at this {to_lhs, rw lebesgue_length}, simp only [infi_lt_iff] at this, rcases this with ⟨a, b, h₁, hβ‚‚βŸ©, rw ← lebesgue_outer_Ico at hβ‚‚, exact ⟨_, h₁, is_measurable_Ico, le_of_lt $ by simpa using hβ‚‚βŸ© }, simp at hg, apply infi_le_of_le (Union g) _, apply infi_le_of_le (subset.trans hf $ Union_subset_Union (Ξ» i, (hg i).1)) _, apply infi_le_of_le (is_measurable.Union (Ξ» i, (hg i).2.1)) _, exact le_trans (lebesgue_outer.Union _) (ennreal.tsum_le_tsum $ Ξ» i, (hg i).2.2) end lemma borel_le_lebesgue_measurable : borel ℝ ≀ lebesgue_outer.caratheodory := begin rw real.borel_eq_generate_from_Iio_rat, refine measurable_space.generate_from_le _, simp [is_lebesgue_measurable_Iio] { contextual := tt } end /-- Lebesgue measure on the Borel sets The outer Lebesgue measure is the completion of this measure. (TODO: proof this) -/ instance real.measure_space : measure_space ℝ := ⟨{to_outer_measure := lebesgue_outer, m_Union := Ξ» f hf, lebesgue_outer.Union_eq_of_caratheodory $ Ξ» i, borel_le_lebesgue_measurable _ (hf i), trimmed := lebesgue_outer_trim }⟩ @[simp] theorem lebesgue_to_outer_measure : (volume : measure ℝ).to_outer_measure = lebesgue_outer := rfl end measure_theory open measure_theory namespace real open_locale topological_space theorem volume_val (s) : volume s = lebesgue_outer s := rfl instance has_no_atoms_volume : has_no_atoms (volume : measure ℝ) := ⟨lebesgue_outer_singleton⟩ @[simp] lemma volume_Ico {a b : ℝ} : volume (Ico a b) = of_real (b - a) := lebesgue_outer_Ico a b @[simp] lemma volume_Icc {a b : ℝ} : volume (Icc a b) = of_real (b - a) := lebesgue_outer_Icc a b @[simp] lemma volume_Ioo {a b : ℝ} : volume (Ioo a b) = of_real (b - a) := lebesgue_outer_Ioo a b @[simp] lemma volume_Ioc {a b : ℝ} : volume (Ioc a b) = of_real (b - a) := lebesgue_outer_Ioc a b @[simp] lemma volume_singleton {a : ℝ} : volume ({a} : set ℝ) = 0 := lebesgue_outer_singleton a @[simp] lemma volume_interval {a b : ℝ} : volume (interval a b) = of_real (abs (b - a)) := by rw [interval, volume_Icc, max_sub_min_eq_abs] instance locally_finite_volume : locally_finite_measure (volume : measure ℝ) := ⟨λ x, ⟨Ioo (x - 1) (x + 1), mem_nhds_sets is_open_Ioo ⟨sub_lt_self _ zero_lt_one, lt_add_of_pos_right _ zero_lt_one⟩, by simp only [real.volume_Ioo, ennreal.of_real_lt_top]⟩⟩ lemma map_volume_add_left (a : ℝ) : measure.map ((+) a) volume = volume := eq.symm $ real.measure_ext_Ioo_rat $ Ξ» p q, by simp [measure.map_apply (measurable_add_left a) is_measurable_Ioo, sub_sub_sub_cancel_right] lemma map_volume_add_right (a : ℝ) : measure.map (+ a) volume = volume := by simpa only [add_comm] using real.map_volume_add_left a lemma smul_map_volume_mul_left {a : ℝ} (h : a β‰  0) : ennreal.of_real (abs a) β€’ measure.map ((*) a) volume = volume := begin refine (real.measure_ext_Ioo_rat $ Ξ» p q, _).symm, cases lt_or_gt_of_ne h with h h, { simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt $ neg_pos.2 h), measure.map_apply (measurable_mul_left a) is_measurable_Ioo, neg_sub_neg, ← neg_mul_eq_neg_mul, preimage_const_mul_Ioo_of_neg _ _ h, abs_of_neg h, mul_sub, mul_div_cancel' _ (ne_of_lt h)] }, { simp only [real.volume_Ioo, measure.smul_apply, ← ennreal.of_real_mul (le_of_lt h), measure.map_apply (measurable_mul_left a) is_measurable_Ioo, preimage_const_mul_Ioo _ _ h, abs_of_pos h, mul_sub, mul_div_cancel' _ (ne_of_gt h)] } end lemma map_volume_mul_left {a : ℝ} (h : a β‰  0) : measure.map ((*) a) volume = ennreal.of_real (abs a⁻¹) β€’ volume := by conv_rhs { rw [← real.smul_map_volume_mul_left h, smul_smul, ← ennreal.of_real_mul (abs_nonneg _), ← abs_mul, inv_mul_cancel h, abs_one, ennreal.of_real_one, one_smul] } lemma smul_map_volume_mul_right {a : ℝ} (h : a β‰  0) : ennreal.of_real (abs a) β€’ measure.map (* a) volume = volume := by simpa only [mul_comm] using real.smul_map_volume_mul_left h lemma map_volume_mul_right {a : ℝ} (h : a β‰  0) : measure.map (* a) volume = ennreal.of_real (abs a⁻¹) β€’ volume := by simpa only [mul_comm] using real.map_volume_mul_left h @[simp] lemma map_volume_neg : measure.map has_neg.neg (volume : measure ℝ) = volume := eq.symm $ real.measure_ext_Ioo_rat $ Ξ» p q, by simp [measure.map_apply measurable_neg is_measurable_Ioo] end real /- section vitali def vitali_aux_h (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : βˆƒ y ∈ Icc (0:ℝ) 1, βˆƒ q:β„š, ↑q = x - y := ⟨x, h, 0, by simp⟩ def vitali_aux (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : ℝ := classical.some (vitali_aux_h x h) theorem vitali_aux_mem (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : vitali_aux x h ∈ Icc (0:ℝ) 1 := Exists.fst (classical.some_spec (vitali_aux_h x h):_) theorem vitali_aux_rel (x : ℝ) (h : x ∈ Icc (0:ℝ) 1) : βˆƒ q:β„š, ↑q = x - vitali_aux x h := Exists.snd (classical.some_spec (vitali_aux_h x h):_) def vitali : set ℝ := {x | βˆƒ h, x = vitali_aux x h} theorem vitali_nonmeasurable : Β¬ is_null_measurable measure_space.ΞΌ vitali := sorry end vitali -/
e689daedf503cbe0f7c3c463474b67e5d8c0998c
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/types/sum.hlean
b163158b9c9c430d16ef2aed5f0421108fb37aef
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
15,428
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about sums/coproducts/disjoint unions -/ import .pi .equiv logic open lift eq is_equiv equiv equiv.ops prod prod.ops is_trunc sigma bool namespace sum universe variables u v u' v' variables {A : Type.{u}} {B : Type.{v}} (z z' : A + B) {P : A β†’ Type.{u'}} {Q : A β†’ Type.{v'}} protected definition eta : sum.rec inl inr z = z := by induction z; all_goals reflexivity protected definition code [unfold 3 4] : A + B β†’ A + B β†’ Type.{max u v} | code (inl a) (inl a') := lift (a = a') | code (inr b) (inr b') := lift (b = b') | code _ _ := lift empty protected definition decode [unfold 3 4] : Ξ (z z' : A + B), sum.code z z' β†’ z = z' | decode (inl a) (inl a') := Ξ»c, ap inl (down c) | decode (inl a) (inr b') := Ξ»c, empty.elim (down c) _ | decode (inr b) (inl a') := Ξ»c, empty.elim (down c) _ | decode (inr b) (inr b') := Ξ»c, ap inr (down c) protected definition mem_cases : (Ξ£ a, z = inl a) + (Ξ£ b, z = inr b) := by cases z with a b; exact inl ⟨a, idp⟩; exact inr ⟨b, idp⟩ protected definition eqrec {A B : Type} {C : A + B β†’ Type} (x : A + B) (cl : Ξ  a, x = inl a β†’ C (inl a)) (cr : Ξ  b, x = inr b β†’ C (inr b)) : C x := by cases x with a b; exact cl a idp; exact cr b idp variables {z z'} protected definition encode [unfold 3 4 5] (p : z = z') : sum.code z z' := by induction p; induction z; all_goals exact up idp variables (z z') definition sum_eq_equiv [constructor] : (z = z') ≃ sum.code z z' := equiv.MK sum.encode !sum.decode abstract begin intro c, induction z with a b, all_goals induction z' with a' b', all_goals (esimp at *; induction c with c), all_goals induction c, -- c either has type empty or a path all_goals reflexivity end end abstract begin intro p, induction p, induction z, all_goals reflexivity end end section variables {a a' : A} {b b' : B} definition eq_of_inl_eq_inl [unfold 5] (p : inl a = inl a' :> A + B) : a = a' := down (sum.encode p) definition eq_of_inr_eq_inr [unfold 5] (p : inr b = inr b' :> A + B) : b = b' := down (sum.encode p) definition empty_of_inl_eq_inr (p : inl a = inr b) : empty := down (sum.encode p) definition empty_of_inr_eq_inl (p : inr b = inl a) : empty := down (sum.encode p) /- Transport -/ definition sum_transport (p : a = a') (z : P a + Q a) : p β–Έ z = sum.rec (Ξ»a, inl (p β–Έ a)) (Ξ»b, inr (p β–Έ b)) z := by induction p; induction z; all_goals reflexivity /- Pathovers -/ definition etao (p : a = a') (z : P a + Q a) : z =[p] sum.rec (Ξ»a, inl (p β–Έ a)) (Ξ»b, inr (p β–Έ b)) z := by induction p; induction z; all_goals constructor protected definition codeo (p : a = a') : P a + Q a β†’ P a' + Q a' β†’ Type.{max u' v'} | codeo (inl x) (inl x') := lift.{u' v'} (x =[p] x') | codeo (inr y) (inr y') := lift.{v' u'} (y =[p] y') | codeo _ _ := lift empty protected definition decodeo (p : a = a') : Ξ (z : P a + Q a) (z' : P a' + Q a'), sum.codeo p z z' β†’ z =[p] z' | decodeo (inl x) (inl x') := Ξ»c, apo (Ξ»a, inl) (down c) | decodeo (inl x) (inr y') := Ξ»c, empty.elim (down c) _ | decodeo (inr y) (inl x') := Ξ»c, empty.elim (down c) _ | decodeo (inr y) (inr y') := Ξ»c, apo (Ξ»a, inr) (down c) variables {z z'} protected definition encodeo {p : a = a'} {z : P a + Q a} {z' : P a' + Q a'} (q : z =[p] z') : sum.codeo p z z' := by induction q; induction z; all_goals exact up idpo variables (z z') definition sum_pathover_equiv [constructor] (p : a = a') (z : P a + Q a) (z' : P a' + Q a') : (z =[p] z') ≃ sum.codeo p z z' := equiv.MK sum.encodeo !sum.decodeo abstract begin intro c, induction z with a b, all_goals induction z' with a' b', all_goals (esimp at *; induction c with c), all_goals induction c, -- c either has type empty or a pathover all_goals reflexivity end end abstract begin intro q, induction q, induction z, all_goals reflexivity end end end /- Functorial action -/ variables {A' B' : Type} (f : A β†’ A') (g : B β†’ B') definition sum_functor [unfold 7] : A + B β†’ A' + B' | sum_functor (inl a) := inl (f a) | sum_functor (inr b) := inr (g b) /- Equivalences -/ definition is_equiv_sum_functor [constructor] [Hf : is_equiv f] [Hg : is_equiv g] : is_equiv (sum_functor f g) := adjointify (sum_functor f g) (sum_functor f⁻¹ g⁻¹) abstract begin intro z, induction z, all_goals (esimp; (apply ap inl | apply ap inr); apply right_inv) end end abstract begin intro z, induction z, all_goals (esimp; (apply ap inl | apply ap inr); apply right_inv) end end definition sum_equiv_sum_of_is_equiv [constructor] [Hf : is_equiv f] [Hg : is_equiv g] : A + B ≃ A' + B' := equiv.mk _ (is_equiv_sum_functor f g) definition sum_equiv_sum [constructor] (f : A ≃ A') (g : B ≃ B') : A + B ≃ A' + B' := equiv.mk _ (is_equiv_sum_functor f g) definition sum_equiv_sum_left [constructor] (g : B ≃ B') : A + B ≃ A + B' := sum_equiv_sum equiv.refl g definition sum_equiv_sum_right [constructor] (f : A ≃ A') : A + B ≃ A' + B := sum_equiv_sum f equiv.refl definition flip [unfold 3] : A + B β†’ B + A | flip (inl a) := inr a | flip (inr b) := inl b definition sum_comm_equiv [constructor] (A B : Type) : A + B ≃ B + A := begin fapply equiv.MK, exact flip, exact flip, all_goals (intro z; induction z; all_goals reflexivity) end definition sum_assoc_equiv [constructor] (A B C : Type) : A + (B + C) ≃ (A + B) + C := begin fapply equiv.MK, all_goals try (intro z; induction z with u v; all_goals try induction u; all_goals try induction v), all_goals try (repeat append (append (apply inl) (apply inr)) assumption; now), all_goals reflexivity end definition sum_empty_equiv [constructor] (A : Type) : A + empty ≃ A := begin fapply equiv.MK, { intro z, induction z, assumption, contradiction}, { exact inl}, { intro a, reflexivity}, { intro z, induction z, reflexivity, contradiction} end definition empty_sum_equiv (A : Type) : empty + A ≃ A := !sum_comm_equiv ⬝e !sum_empty_equiv definition bool_equiv_unit_sum_unit : bool ≃ unit + unit := begin fapply equiv.MK, { intro b, cases b, exact inl unit.star, exact inr unit.star }, { intro s, cases s, exact bool.ff, exact bool.tt }, { intro s, cases s, do 2 (cases a; reflexivity) }, { intro b, cases b, do 2 reflexivity }, end definition sum_prod_right_distrib [constructor] (A B C : Type) : (A + B) Γ— C ≃ (A Γ— C) + (B Γ— C) := begin fapply equiv.MK, { intro x, cases x with ab c, cases ab with a b, exact inl (a, c), exact inr (b, c) }, { intro x, cases x with ac bc, cases ac with a c, exact (inl a, c), cases bc with b c, exact (inr b, c) }, { intro x, cases x with ac bc, cases ac with a c, reflexivity, cases bc, reflexivity }, { intro x, cases x with ab c, cases ab with a b, do 2 reflexivity } end definition sum_prod_left_distrib [constructor] (A B C : Type) : A Γ— (B + C) ≃ (A Γ— B) + (A Γ— C) := calc A Γ— (B + C) ≃ (B + C) Γ— A : prod_comm_equiv ... ≃ (B Γ— A) + (C Γ— A) : sum_prod_right_distrib ... ≃ (A Γ— B) + (C Γ— A) : prod_comm_equiv ... ≃ (A Γ— B) + (A Γ— C) : prod_comm_equiv section variables (H : unit + A ≃ unit + B) include H open unit decidable sigma.ops definition unit_sum_equiv_cancel_map : A β†’ B := begin intro a, cases sum.mem_cases (H (inr a)) with u b, rotate 1, exact b.1, cases u with u Hu, cases sum.mem_cases (H (inl ⋆)) with u' b, rotate 1, exact b.1, cases u' with u' Hu', exfalso, apply empty_of_inl_eq_inr, calc inl ⋆ = H⁻¹ (H (inl ⋆)) : (to_left_inv H (inl ⋆))⁻¹ ... = H⁻¹ (inl u') : {Hu'} ... = H⁻¹ (inl u) : is_hprop.elim ... = H⁻¹ (H (inr a)) : {Hu⁻¹} ... = inr a : to_left_inv H (inr a) end definition unit_sum_equiv_cancel_inv (b : B) : unit_sum_equiv_cancel_map H (unit_sum_equiv_cancel_map H⁻¹ b) = b := begin assert HH : to_fun H⁻¹ = (to_fun H)⁻¹, cases H, reflexivity, esimp[unit_sum_equiv_cancel_map], apply sum.rec, { intro x, cases x with u Hu, esimp, apply sum.rec, { intro x, exfalso, cases x with u' Hu', apply empty_of_inl_eq_inr, calc inl ⋆ = H⁻¹ (H (inl ⋆)) : (to_left_inv H (inl ⋆))⁻¹ ... = H⁻¹ (inl u') : ap H⁻¹ Hu' ... = H⁻¹ (inl u) : {!is_hprop.elim} ... = H⁻¹ (H (inr _)) : {Hu⁻¹} ... = inr _ : to_left_inv H }, { intro x, cases x with b' Hb', esimp, cases sum.mem_cases (H⁻¹ (inr b)) with x x, { cases x with u' Hu', cases u', apply eq_of_inr_eq_inr, rewrite -HH at Hu', calc inr b' = H (inl ⋆) : Hb'⁻¹ ... = H (H⁻¹ (inr b)) : {(ap (to_fun H) Hu')⁻¹} ... = inr b : to_right_inv H (inr b) }, { exfalso, cases x with a Ha, rewrite -HH at Ha, apply empty_of_inl_eq_inr, cases u, apply concat, apply Hu⁻¹, apply concat, rotate 1, apply !(to_right_inv H), apply ap (to_fun H), krewrite -HH, apply concat, rotate 1, apply Ha⁻¹, apply ap inr, esimp, apply sum.rec, intro x, exfalso, apply empty_of_inl_eq_inr, apply concat, exact x.2⁻¹, apply Ha, intro x, cases x with a' Ha', esimp, apply eq_of_inr_eq_inr, apply Ha'⁻¹ ⬝ Ha } } }, { intro x, cases x with b' Hb', esimp, apply eq_of_inr_eq_inr, refine Hb'⁻¹ ⬝ _, cases sum.mem_cases (to_fun H⁻¹ (inr b)) with x x, { cases x with u Hu, esimp, cases sum.mem_cases (to_fun H⁻¹ (inl ⋆)) with x x, { cases x with u' Hu', exfalso, apply empty_of_inl_eq_inr, calc inl ⋆ = H (H⁻¹ (inl ⋆)) : (to_right_inv H (inl ⋆))⁻¹ ... = H (inl u') : {ap H Hu'} ... = H (inl u) : {!is_hprop.elim} ... = H (H⁻¹ (inr b)) : {ap H Hu⁻¹} ... = inr b : to_right_inv H (inr b) }, { cases x with a Ha, exfalso, apply empty_of_inl_eq_inr, apply concat, rotate 1, exact Hb', krewrite HH at Ha, assert Ha' : inl ⋆ = H (inr a), apply !(to_right_inv H)⁻¹ ⬝ ap H Ha, apply concat Ha', apply ap H, apply ap inr, apply sum.rec, intro x, cases x with u' Hu', esimp, apply sum.rec, intro x, cases x with u'' Hu'', esimp, apply empty.rec, intro x, cases x with a'' Ha'', esimp, krewrite Ha' at Ha'', apply eq_of_inr_eq_inr, apply !(to_left_inv H)⁻¹ ⬝ Ha'', intro x, exfalso, cases x with a'' Ha'', apply empty_of_inl_eq_inr, apply Hu⁻¹ ⬝ Ha'', } }, { cases x with a' Ha', esimp, refine _ ⬝ !(to_right_inv H), apply ap H, rewrite -HH, apply Ha'⁻¹ } } end definition unit_sum_equiv_cancel : A ≃ B := begin fapply equiv.MK, apply unit_sum_equiv_cancel_map H, apply unit_sum_equiv_cancel_map H⁻¹, intro b, apply unit_sum_equiv_cancel_inv, { intro a, have H = (H⁻¹)⁻¹, from !equiv.symm_symm⁻¹, rewrite this at {2}, apply unit_sum_equiv_cancel_inv } end end /- universal property -/ definition sum_rec_unc [unfold 5] {P : A + B β†’ Type} (fg : (Ξ a, P (inl a)) Γ— (Ξ b, P (inr b))) : Ξ z, P z := sum.rec fg.1 fg.2 definition is_equiv_sum_rec [constructor] (P : A + B β†’ Type) : is_equiv (sum_rec_unc : (Ξ a, P (inl a)) Γ— (Ξ b, P (inr b)) β†’ Ξ z, P z) := begin apply adjointify sum_rec_unc (Ξ»f, (Ξ»a, f (inl a), Ξ»b, f (inr b))), intro f, apply eq_of_homotopy, intro z, focus (induction z; all_goals reflexivity), intro h, induction h with f g, reflexivity end definition equiv_sum_rec [constructor] (P : A + B β†’ Type) : (Ξ a, P (inl a)) Γ— (Ξ b, P (inr b)) ≃ Ξ z, P z := equiv.mk _ !is_equiv_sum_rec definition imp_prod_imp_equiv_sum_imp [constructor] (A B C : Type) : (A β†’ C) Γ— (B β†’ C) ≃ (A + B β†’ C) := !equiv_sum_rec /- truncatedness -/ variables (A B) theorem is_trunc_sum (n : trunc_index) [HA : is_trunc (n.+2) A] [HB : is_trunc (n.+2) B] : is_trunc (n.+2) (A + B) := begin apply is_trunc_succ_intro, intro z z', apply is_trunc_equiv_closed_rev, apply sum_eq_equiv, induction z with a b, all_goals induction z' with a' b', all_goals esimp, all_goals exact _, end theorem is_trunc_sum_excluded (n : trunc_index) [HA : is_trunc n A] [HB : is_trunc n B] (H : A β†’ B β†’ empty) : is_trunc n (A + B) := begin induction n with n IH, { exfalso, exact H !center !center}, { clear IH, induction n with n IH, { apply is_hprop.mk, intros x y, induction x, all_goals induction y, all_goals esimp, all_goals try (exfalso;apply H;assumption;assumption), all_goals apply ap _ !is_hprop.elim}, { apply is_trunc_sum}} end variable {B} definition is_contr_sum_left [HA : is_contr A] (H : Β¬B) : is_contr (A + B) := is_contr.mk (inl !center) (Ξ»x, sum.rec_on x (Ξ»a, ap inl !center_eq) (Ξ»b, empty.elim (H b))) /- Sums are equivalent to dependent sigmas where the first component is a bool. The current construction only works for A and B in the same universe. If we need it for A and B in different universes, we need to insert some lifts. -/ definition sum_of_sigma_bool {A B : Type.{u}} (v : Ξ£(b : bool), bool.rec A B b) : A + B := by induction v with b x; induction b; exact inl x; exact inr x definition sigma_bool_of_sum {A B : Type.{u}} (z : A + B) : Ξ£(b : bool), bool.rec A B b := by induction z with a b; exact ⟨ff, a⟩; exact ⟨tt, b⟩ definition sum_equiv_sigma_bool [constructor] (A B : Type.{u}) : A + B ≃ Ξ£(b : bool), bool.rec A B b := equiv.MK sigma_bool_of_sum sum_of_sigma_bool begin intro v, induction v with b x, induction b, all_goals reflexivity end begin intro z, induction z with a b, all_goals reflexivity end end sum open sum pi namespace decidable definition decidable_equiv [constructor] (A : Type) : decidable A ≃ A + Β¬A := begin fapply equiv.MK:intro a;induction a:try (constructor;assumption;now), all_goals reflexivity end definition is_trunc_decidable [constructor] (A : Type) (n : trunc_index) [H : is_trunc n A] : is_trunc n (decidable A) := begin apply is_trunc_equiv_closed_rev, apply decidable_equiv, induction n with n IH, { apply is_contr_sum_left, exact Ξ»na, na !center}, { apply is_trunc_sum_excluded, exact Ξ»a na, na a} end end decidable attribute sum.is_trunc_sum [instance] [priority 1480] definition tsum [constructor] {n : trunc_index} (A B : (n.+2)-Type) : (n.+2)-Type := trunctype.mk (A + B) _ infixr `+t`:25 := tsum
b755ecfdff105a5e5ab2ee6c9d2af1581d81c42b
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/apply.lean
6d62b92d1b10a74c591fc93dcb8ac943004e4d59
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
7,911
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import tactic.core /-! This file provides an alternative implementation for `apply` to fix the so-called "apply bug". The issue arises when the goals is a Ξ -type -- whether it is visible or hidden behind a definition. For instance, consider the following proof: ``` example {Ξ± Ξ²} (x y z : Ξ± β†’ Ξ²) (hβ‚€ : x ≀ y) (h₁ : y ≀ z) : x ≀ z := begin apply le_trans, end ``` Because `x ≀ z` is definitionally equal to `βˆ€ i, x i ≀ z i`, `apply` will fail. The alternative definition, `apply'` fixes this. When `apply` would work, `apply` is used and otherwise, a different strategy is deployed -/ namespace tactic /-- With `gs` a list of proof goals, `reorder_goals gs new_g` will use the `new_goals` policy `new_g` to rearrange the dependent goals to either drop them, push them to the end of the list or leave them in place. The `bool` values in `gs` indicates whether the goal is dependent or not. -/ def reorder_goals {Ξ±} (gs : list (bool Γ— Ξ±)) : new_goals β†’ list Ξ± | new_goals.non_dep_first := let ⟨dep,non_dep⟩ := gs.partition (coe ∘ prod.fst) in non_dep.map prod.snd ++ dep.map prod.snd | new_goals.non_dep_only := (gs.filter (coe ∘ bnot ∘ prod.fst)).map prod.snd | new_goals.all := gs.map prod.snd private meta def has_opt_auto_param_inst_for_apply (ms : list (name Γ— expr)) : tactic bool := ms.mfoldl (Ξ» r m, do type ← infer_type m.2, b ← is_class type, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2 || b) ff private meta def try_apply_opt_auto_param_instance_for_apply (cfg : apply_cfg) (ms : list (name Γ— expr)) : tactic unit := mwhen (has_opt_auto_param_inst_for_apply ms) $ do gs ← get_goals, ms.mmap' (Ξ» m, mwhen (bnot <$> (is_assigned m.2)) $ set_goals [m.2] >> try apply_instance >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs private meta def retry_apply_aux : Ξ  (e : expr) (cfg : apply_cfg), list (bool Γ— name Γ— expr) β†’ tactic (list (name Γ— expr)) | e cfg gs := focus1 (do { tgt : expr ← target, t ← infer_type e, unify t tgt, exact e, gs' ← get_goals, let r := reorder_goals gs.reverse cfg.new_goals, set_goals (gs' ++ r.map prod.snd), return r }) <|> do (expr.pi n bi d b) ← infer_type e >>= whnf | apply_core e cfg, v ← mk_meta_var d, let b := b.has_var, e ← head_beta $ e v, retry_apply_aux e cfg ((b, n, v) :: gs) private meta def retry_apply (e : expr) (cfg : apply_cfg) : tactic (list (name Γ— expr)) := apply_core e cfg <|> retry_apply_aux e cfg [] /-- `apply'` mimics the behavior of `apply_core`. When `apply_core` fails, it is retried by providing the term with meta variables as additional arguments. The meta variables can then become new goals depending on the `cfg.new_goals` policy. `apply'` also finds instances and applies opt_params and auto_params. -/ meta def apply' (e : expr) (cfg : apply_cfg := {}) : tactic (list (name Γ— expr)) := do r ← retry_apply e cfg, try_apply_opt_auto_param_instance_for_apply cfg r, return r /-- Same as `apply'` but __all__ arguments that weren't inferred are added to goal list. -/ meta def fapply' (e : expr) : tactic (list (name Γ— expr)) := apply' e {new_goals := new_goals.all} /-- Same as `apply'` but only goals that don't depend on other goals are added to goal list. -/ meta def eapply' (e : expr) : tactic (list (name Γ— expr)) := apply' e {new_goals := new_goals.non_dep_only} /-- `relation_tactic` finds a proof rule for the relation found in the goal and uses `apply'` to make one proof step. -/ private meta def relation_tactic (md : transparency) (op_for : environment β†’ name β†’ option name) (tac_name : string) : tactic unit := do tgt ← target >>= instantiate_mvars, env ← get_env, let r := expr.get_app_fn tgt, match op_for env (expr.const_name r) with | (some refl) := do r ← mk_const refl, retry_apply r {md := md, new_goals := new_goals.non_dep_only }, return () | none := fail $ tac_name ++ " tactic failed, target is not a relation application with the expected property." end /-- Similar to `reflexivity` with the difference that `apply'` is used instead of `apply` -/ meta def reflexivity' (md := semireducible) : tactic unit := relation_tactic md environment.refl_for "reflexivity" /-- Similar to `symmetry` with the difference that `apply'` is used instead of `apply` -/ meta def symmetry' (md := semireducible) : tactic unit := relation_tactic md environment.symm_for "symmetry" /-- Similar to `transitivity` with the difference that `apply'` is used instead of `apply` -/ meta def transitivity' (md := semireducible) : tactic unit := relation_tactic md environment.trans_for "transitivity" namespace interactive setup_tactic_parser /-- Similarly to `apply`, the `apply'` tactic tries to match the current goal against the conclusion of the type of term. It differs from `apply` in that it does not unfold definition in order to find out what the assumptions of the provided term is. It is especially useful when defining relations on function spaces (e.g. `≀`) so that rules like transitivity on `le : (Ξ± β†’ Ξ²) β†’ (Ξ± β†’ Ξ²) β†’ (Ξ± β†’ Ξ²)` will be considered to have three parameters and two assumptions (i.e. `f g h : Ξ± β†’ Ξ²`, `Hβ‚€ : f ≀ g`, `H₁ : g ≀ h`) instead of three parameters, two assumptions and then one more parameter (i.e. `f g h : Ξ± β†’ Ξ²`, `Hβ‚€ : f ≀ g`, `H₁ : g ≀ h`, `x : Ξ±`). Whereas `apply` would expect the goal `f x ≀ h x`, `apply'` will work with the goal `f ≀ h`. -/ meta def apply' (q : parse texpr) : tactic unit := concat_tags (do h ← i_to_expr_for_apply q, tactic.apply' h) /-- Similar to the `apply'` tactic, but does not reorder goals. -/ meta def fapply' (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.fapply') /-- Similar to the `apply'` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution. -/ meta def eapply' (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.eapply') /-- Similar to the `apply'` tactic, but allows the user to provide a `apply_cfg` configuration object. -/ meta def apply_with' (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply' e cfg) /-- Similar to the `apply'` tactic, but uses matching instead of unification. `mapply' t` is equivalent to `apply_with' t {unify := ff}` -/ meta def mapply' (q : parse texpr) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply' e {unify := ff}) /-- Similar to `reflexivity` with the difference that `apply'` is used instead of `apply`. -/ meta def reflexivity' : tactic unit := tactic.reflexivity' /-- Shorter name for the tactic `reflexivity'`. -/ meta def refl' : tactic unit := tactic.reflexivity' /-- `symmetry'` behaves like `symmetry` but also offers the option `symmetry' at h` to apply symmetry to assumption `h` -/ meta def symmetry' : parse location β†’ tactic unit | l@loc.wildcard := l.try_apply symmetry_hyp tactic.symmetry' | (loc.ns hs) := (loc.ns hs.reverse).apply symmetry_hyp tactic.symmetry' /-- Similar to `transitivity` with the difference that `apply'` is used instead of `apply`. -/ meta def transitivity' (q : parse texpr?) : tactic unit := tactic.transitivity' >> match q with | none := skip | some q := do (r, lhs, rhs) ← target_lhs_rhs, t ← infer_type lhs, i_to_expr ``(%%q : %%t) >>= unify rhs end end interactive end tactic
27d60a527afde5417c6a4b7e08790094fbfeffd3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/tfae.lean
43c494df03ad1d3aabe686c9156b0c63882cbbed
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,923
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Simon Hudon -/ import data.list.tfae import tactic.scc /-! # The Following Are Equivalent (TFAE) This file provides the tactics `tfae_have` and `tfae_finish` for proving the pairwise equivalence of propositions in a set using various implications between them. -/ namespace tactic export list (tfae) namespace tfae @[derive has_reflect, derive inhabited] inductive arrow : Type | right : arrow | left_right : arrow | left : arrow meta def mk_implication : Ξ  (re : arrow) (e₁ eβ‚‚ : expr), pexpr | arrow.right e₁ eβ‚‚ := ``(%%e₁ β†’ %%eβ‚‚) | arrow.left_right e₁ eβ‚‚ := ``(%%e₁ ↔ %%eβ‚‚) | arrow.left e₁ eβ‚‚ := ``(%%eβ‚‚ β†’ %%e₁) meta def mk_name : Ξ  (re : arrow) (i₁ iβ‚‚ : nat), name | arrow.right i₁ iβ‚‚ := ("tfae_" ++ to_string i₁ ++ "_to_" ++ to_string iβ‚‚ : string) | arrow.left_right i₁ iβ‚‚ := ("tfae_" ++ to_string i₁ ++ "_iff_" ++ to_string iβ‚‚ : string) | arrow.left i₁ iβ‚‚ := ("tfae_" ++ to_string iβ‚‚ ++ "_to_" ++ to_string i₁ : string) end tfae namespace interactive setup_tactic_parser open tactic.tfae list meta def parse_list : expr β†’ option (list expr) | `([]) := pure [] | `(%%e :: %%es) := (::) e <$> parse_list es | _ := none /-- In a goal of the form `tfae [aβ‚€, a₁, aβ‚‚]`, `tfae_have : i β†’ j` creates the assertion `aα΅’ β†’ aβ±Ό`. The other possible notations are `tfae_have : i ← j` and `tfae_have : i ↔ j`. The user can also provide a label for the assertion, as with `have`: `tfae_have h : i ↔ j`. -/ meta def tfae_have (h : parse $ optional ident <* tk ":") (i₁ : parse (with_desc "i" small_nat)) (re : parse (((tk "β†’" <|> tk "->") *> return arrow.right) <|> ((tk "↔" <|> tk "<->") *> return arrow.left_right) <|> ((tk "←" <|> tk "<-") *> return arrow.left))) (iβ‚‚ : parse (with_desc "j" small_nat)) : tactic unit := do `(tfae %%l) <- target, l ← parse_list l, e₁ ← list.nth l (i₁ - 1) <|> fail format!"index {i₁} is not between 1 and {l.length}", eβ‚‚ ← list.nth l (iβ‚‚ - 1) <|> fail format!"index {iβ‚‚} is not between 1 and {l.length}", type ← to_expr (tfae.mk_implication re e₁ eβ‚‚), let h := h.get_or_else (mk_name re i₁ iβ‚‚), tactic.assert h type, return () /-- Finds all implications and equivalences in the context to prove a goal of the form `tfae [...]`. -/ meta def tfae_finish : tactic unit := applyc ``tfae_nil <|> closure.with_new_closure (Ξ» cl, do impl_graph.mk_scc cl, `(tfae %%l) ← target, l ← parse_list l, (_,r,_) ← cl.root l.head, refine ``(tfae_of_forall %%r _ _), thm ← mk_const ``forall_mem_cons, l.mmap' (Ξ» e, do rewrite_target thm, split, (_,r',p) ← cl.root e, tactic.exact p ), applyc ``forall_mem_nil, pure ()) end interactive end tactic /-- The `tfae` tactic suite is a set of tactics that help with proving that certain propositions are equivalent. In `data/list/basic.lean` there is a section devoted to propositions of the form ```lean tfae [p1, p2, ..., pn] ``` where `p1`, `p2`, through, `pn` are terms of type `Prop`. This proposition asserts that all the `pi` are pairwise equivalent. There are results that allow to extract the equivalence of two propositions `pi` and `pj`. To prove a goal of the form `tfae [p1, p2, ..., pn]`, there are two tactics. The first tactic is `tfae_have`. As an argument it takes an expression of the form `i arrow j`, where `i` and `j` are two positive natural numbers, and `arrow` is an arrow such as `β†’`, `->`, `←`, `<-`, `↔`, or `<->`. The tactic `tfae_have : i arrow j` sets up a subgoal in which the user has to prove the equivalence (or implication) of `pi` and `pj`. The remaining tactic, `tfae_finish`, is a finishing tactic. It collects all implications and equivalences from the local context and computes their transitive closure to close the main goal. `tfae_have` and `tfae_finish` can be used together in a proof as follows: ```lean example (a b c d : Prop) : tfae [a,b,c,d] := begin tfae_have : 3 β†’ 1, { /- prove c β†’ a -/ }, tfae_have : 2 β†’ 3, { /- prove b β†’ c -/ }, tfae_have : 2 ← 1, { /- prove a β†’ b -/ }, tfae_have : 4 ↔ 2, { /- prove d ↔ b -/ }, -- a b c d : Prop, -- tfae_3_to_1 : c β†’ a, -- tfae_2_to_3 : b β†’ c, -- tfae_1_to_2 : a β†’ b, -- tfae_4_iff_2 : d ↔ b -- ⊒ tfae [a, b, c, d] tfae_finish, end ``` -/ add_tactic_doc { name := "tfae", category := doc_category.tactic, decl_names := [`tactic.interactive.tfae_have, `tactic.interactive.tfae_finish], tags := ["logic"], inherit_description_from := `tactic.interactive.tfae_finish }
4edef9e7012e6ff583d15cff48bbeaaf78d834e0
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/quaternion.lean
3e3000dc5c7fa96f6f52126cd722c7560252120e
[ "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,451
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import algebra.quaternion import analysis.inner_product_space.basic /-! # Quaternions as a normed algebra In this file we define the following structures on the space `ℍ := ℍ[ℝ]` of quaternions: * inner product space; * normed ring; * normed space over `ℝ`. ## Notation The following notation is available with `open_locale quaternion`: * `ℍ` : quaternions ## Tags quaternion, normed ring, normed space, normed algebra -/ localized "notation (name := quaternion.real) `ℍ` := quaternion ℝ" in quaternion open_locale real_inner_product_space noncomputable theory namespace quaternion instance : has_inner ℝ ℍ := ⟨λ a b, (a * b.conj).re⟩ lemma inner_self (a : ℍ) : βŸͺa, a⟫ = norm_sq a := rfl lemma inner_def (a b : ℍ) : βŸͺa, b⟫ = (a * b.conj).re := rfl instance : inner_product_space ℝ ℍ := inner_product_space.of_core { inner := has_inner.inner, conj_sym := Ξ» x y, by simp [inner_def, mul_comm], nonneg_re := Ξ» x, norm_sq_nonneg, definite := Ξ» x, norm_sq_eq_zero.1, add_left := Ξ» x y z, by simp only [inner_def, add_mul, add_re], smul_left := Ξ» x y r, by simp [inner_def] } lemma norm_sq_eq_norm_sq (a : ℍ) : norm_sq a = β€–aβ€– * β€–aβ€– := by rw [← inner_self, real_inner_self_eq_norm_mul_norm] instance : norm_one_class ℍ := ⟨by rw [norm_eq_sqrt_real_inner, inner_self, norm_sq.map_one, real.sqrt_one]⟩ @[simp, norm_cast] lemma norm_coe (a : ℝ) : β€–(a : ℍ)β€– = β€–aβ€– := by rw [norm_eq_sqrt_real_inner, inner_self, norm_sq_coe, real.sqrt_sq_eq_abs, real.norm_eq_abs] @[simp, norm_cast] lemma nnnorm_coe (a : ℝ) : β€–(a : ℍ)β€–β‚Š = β€–aβ€–β‚Š := subtype.ext $ norm_coe a noncomputable instance : normed_division_ring ℍ := { dist_eq := Ξ» _ _, rfl, norm_mul' := Ξ» a b, by { simp only [norm_eq_sqrt_real_inner, inner_self, norm_sq.map_mul], exact real.sqrt_mul norm_sq_nonneg _ } } noncomputable instance : normed_algebra ℝ ℍ := { norm_smul_le := Ξ» a x, (norm_smul a x).le, to_algebra := quaternion.algebra } instance : has_coe β„‚ ℍ := ⟨λ z, ⟨z.re, z.im, 0, 0⟩⟩ @[simp, norm_cast] lemma coe_complex_re (z : β„‚) : (z : ℍ).re = z.re := rfl @[simp, norm_cast] lemma coe_complex_im_i (z : β„‚) : (z : ℍ).im_i = z.im := rfl @[simp, norm_cast] lemma coe_complex_im_j (z : β„‚) : (z : ℍ).im_j = 0 := rfl @[simp, norm_cast] lemma coe_complex_im_k (z : β„‚) : (z : ℍ).im_k = 0 := rfl @[simp, norm_cast] lemma coe_complex_add (z w : β„‚) : ↑(z + w) = (z + w : ℍ) := by ext; simp @[simp, norm_cast] lemma coe_complex_mul (z w : β„‚) : ↑(z * w) = (z * w : ℍ) := by ext; simp @[simp, norm_cast] lemma coe_complex_zero : ((0 : β„‚) : ℍ) = 0 := rfl @[simp, norm_cast] lemma coe_complex_one : ((1 : β„‚) : ℍ) = 1 := rfl @[simp, norm_cast] lemma coe_real_complex_mul (r : ℝ) (z : β„‚) : (r β€’ z : ℍ) = ↑r * ↑z := by ext; simp @[simp, norm_cast] lemma coe_complex_coe (r : ℝ) : ((r : β„‚) : ℍ) = r := rfl /-- Coercion `β„‚ →ₐ[ℝ] ℍ` as an algebra homomorphism. -/ def of_complex : β„‚ →ₐ[ℝ] ℍ := { to_fun := coe, map_one' := rfl, map_zero' := rfl, map_add' := coe_complex_add, map_mul' := coe_complex_mul, commutes' := Ξ» x, rfl } @[simp] lemma coe_of_complex : ⇑of_complex = coe := rfl end quaternion
5cda4ecec26ba3542e6c3b9e8332e15124c6d3fd
abd677583c7e4d55daf9487b82da11b7c5498d8d
/src/print.lean
e8d404ec8dfd87ee3a90431610a930f0bb5f0caa
[ "Apache-2.0" ]
permissive
jesse-michael-han/embed
e9c346918ad58e03933bdaa057a571c0cc4a7641
c2fc188328e871e18e0dcb8258c6d0462c70a8c9
refs/heads/master
1,584,677,705,005
1,528,451,877,000
1,528,451,877,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
183
lean
import .exp variable {Ξ± : Type} open expr tactic def sqt2str (exp2str : exp Ξ± β†’ string) (Ξ“ Ξ” : list (exp Ξ±)) : string := lst2str exp2str Ξ“ ++ " ⊒ " ++ lst2str exp2str Ξ”
dd38ddb7e83b2d9d4378543884f909e4b861f9dd
c777c32c8e484e195053731103c5e52af26a25d1
/src/logic/equiv/array.lean
5e1f98c7d71cfd6aa1dbbac6825ea519b4770e0a
[ "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
1,766
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.vector.basic import logic.equiv.list import control.traversable.equiv /-! # Equivalences involving `array` We keep this separate from the file containing `list`-like equivalences as those have no future in mathlib4. -/ namespace equiv /-- The natural equivalence between length-`n` heterogeneous arrays and dependent functions from `fin n`. -/ def d_array_equiv_fin {n : β„•} (Ξ± : fin n β†’ Type*) : d_array n Ξ± ≃ (Ξ  i, Ξ± i) := ⟨d_array.read, d_array.mk, Ξ» ⟨f⟩, rfl, Ξ» f, rfl⟩ /-- The natural equivalence between length-`n` arrays and functions from `fin n`. -/ def array_equiv_fin (n : β„•) (Ξ± : Type*) : array n Ξ± ≃ (fin n β†’ Ξ±) := d_array_equiv_fin _ /-- The natural equivalence between length-`n` vectors and length-`n` arrays. -/ def vector_equiv_array (Ξ± : Type*) (n : β„•) : vector Ξ± n ≃ array n Ξ± := (vector_equiv_fin _ _).trans (array_equiv_fin _ _).symm end equiv namespace array open function variable {n : β„•} instance : traversable (array n) := @equiv.traversable (flip vector n) _ (Ξ» Ξ±, equiv.vector_equiv_array Ξ± n) _ instance : is_lawful_traversable (array n) := @equiv.is_lawful_traversable (flip vector n) _ (Ξ» Ξ±, equiv.vector_equiv_array Ξ± n) _ _ end array /-- If `Ξ±` is encodable, then so is `array n Ξ±`. -/ instance _root_.array.encodable {Ξ±} [encodable Ξ±] {n} : encodable (array n Ξ±) := encodable.of_equiv _ (equiv.array_equiv_fin _ _) /-- If `Ξ±` is countable, then so is `array n Ξ±`. -/ instance _root_.array.countable {Ξ±} [countable Ξ±] {n} : countable (array n Ξ±) := countable.of_equiv _ (equiv.vector_equiv_array _ _)
7f5e8db2f79af29913708e2f186b7bb59ab15ba5
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/set_theory/cardinal.lean
b7479b4ef8e0f0f33ead869675e7cf51cac67d2f
[ "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
46,208
lean
/- Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes HΓΆlzl, Mario Carneiro -/ import data.set.countable import set_theory.schroeder_bernstein import data.fintype.card /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. We define the order on cardinal numbers, define omega, and do basic cardinal arithmetic: addition, multiplication, power, cardinal successor, minimum, supremum, infinitary sums and products The fact that the cardinality of `Ξ± Γ— Ξ±` coincides with that of `Ξ±` when `Ξ±` is infinite is not proved in this file, as it relies on facts on well-orders. Instead, it is in `cardinal_ordinal.lean` (together with many other facts on cardinals, for instance the cardinality of `list Ξ±`). ## Implementation notes * There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`. There is a lift operation lifting cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `ΞΊ * ΞΊ = ΞΊ`) is in the file `set_theory/ordinal.lean`, because concepts from that file are used in the proof. ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, omega -/ open function set open_locale classical universes u v w x variables {Ξ± Ξ² : Type u} /-- The equivalence relation on types given by equivalence (bijective correspondence) of types. Quotienting by this equivalence relation gives the cardinal numbers. -/ instance cardinal.is_equivalent : setoid (Type u) := { r := λα Ξ², nonempty (Ξ± ≃ Ξ²), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα Ξ² ⟨e⟩, ⟨e.symm⟩, λα Ξ² Ξ³ ⟨eβ‚βŸ© ⟨eβ‚‚βŸ©, ⟨e₁.trans eβ‚‚βŸ©βŸ© } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal number of a type -/ def mk : Type u β†’ cardinal := quotient.mk localized "notation `#` := cardinal.mk" in cardinal protected lemma eq : mk Ξ± = mk Ξ² ↔ nonempty (Ξ± ≃ Ξ²) := quotient.eq @[simp] theorem mk_def (Ξ± : Type u) : @eq cardinal ⟦α⟧ (mk Ξ±) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ /-- We define the order on cardinal numbers by `mk Ξ± ≀ mk Ξ²` if and only if there exists an embedding (injective function) from Ξ± to Ξ². -/ instance : has_le cardinal.{u} := ⟨λq₁ qβ‚‚, quotient.lift_onβ‚‚ q₁ qβ‚‚ (λα Ξ², nonempty $ Ξ± β†ͺ Ξ²) $ assume Ξ± Ξ² Ξ³ Ξ΄ ⟨eβ‚βŸ© ⟨eβ‚‚βŸ©, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ eβ‚‚βŸ©, assume ⟨e⟩, ⟨e.congr e₁.symm eβ‚‚.symm⟩⟩⟩ theorem mk_le_of_injective {Ξ± Ξ² : Type u} {f : Ξ± β†’ Ξ²} (hf : injective f) : mk Ξ± ≀ mk Ξ² := ⟨⟨f, hf⟩⟩ theorem mk_le_of_surjective {Ξ± Ξ² : Type u} {f : Ξ± β†’ Ξ²} (hf : surjective f) : mk Ξ² ≀ mk Ξ± := ⟨embedding.of_surjective f hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {Ξ± : Type u} : c ≀ mk Ξ± ↔ βˆƒ p : set Ξ±, mk p = c := ⟨quotient.induction_on c $ Ξ» Ξ² ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, Ξ» ⟨p, e⟩, e β–Έ ⟨⟨subtype.val, Ξ» a b, subtype.eq⟩⟩⟩ theorem out_embedding {c c' : cardinal} : c ≀ c' ↔ nonempty (c.out β†ͺ c'.out) := by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl } instance : linear_order cardinal.{u} := { le := (≀), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨eβ‚βŸ© ⟨eβ‚‚βŸ©; exact ⟨e₁.trans eβ‚‚βŸ©, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨eβ‚βŸ© ⟨eβ‚‚βŸ©; exact quotient.sound (e₁.antisymm eβ‚‚), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total } noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _ noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance -- short-circuit type class inference instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {Ξ± : Type u} : mk Ξ± β‰  0 ↔ nonempty Ξ± := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩, Ξ» e, let ⟨h⟩ := quotient.exact e in Ξ» ⟨a⟩, (h a).elim⟩ instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : nontrivial cardinal.{u} := ⟨⟨1, 0, ne_zero_iff_nonempty.2 ⟨punit.star⟩⟩⟩ theorem le_one_iff_subsingleton {Ξ± : Type u} : mk Ξ± ≀ 1 ↔ subsingleton Ξ± := ⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩, Ξ» ⟨h⟩, ⟨⟨λ a, punit.star, Ξ» a b _, h _ _⟩⟩⟩ theorem one_lt_iff_nontrivial {Ξ± : Type u} : 1 < mk Ξ± ↔ nontrivial Ξ± := by { rw [← not_iff_not, not_nontrivial_iff_subsingleton, ← le_one_iff_subsingleton], simp } instance : has_add cardinal.{u} := ⟨λq₁ qβ‚‚, quotient.lift_onβ‚‚ q₁ qβ‚‚ (λα Ξ², mk (Ξ± βŠ• Ξ²)) $ assume Ξ± Ξ² Ξ³ Ξ΄ ⟨eβ‚βŸ© ⟨eβ‚‚βŸ©, quotient.sound ⟨equiv.sum_congr e₁ eβ‚‚βŸ©βŸ© @[simp] theorem add_def (Ξ± Ξ²) : mk Ξ± + mk Ξ² = mk (Ξ± βŠ• Ξ²) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ qβ‚‚, quotient.lift_onβ‚‚ q₁ qβ‚‚ (λα Ξ², mk (Ξ± Γ— Ξ²)) $ assume Ξ± Ξ² Ξ³ Ξ΄ ⟨eβ‚βŸ© ⟨eβ‚‚βŸ©, quotient.sound ⟨equiv.prod_congr e₁ eβ‚‚βŸ©βŸ© @[simp] theorem mul_def (Ξ± Ξ² : Type u) : mk Ξ± * mk Ξ² = mk (Ξ± Γ— Ξ²) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_onβ‚‚ a b $ assume Ξ± Ξ², quotient.sound ⟨equiv.sum_comm Ξ± β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_onβ‚‚ a b $ assume Ξ± Ξ², quotient.sound ⟨equiv.prod_comm Ξ± β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume Ξ±, quotient.sound ⟨equiv.pempty_sum α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume Ξ±, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume Ξ±, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume Ξ± Ξ² Ξ³, quotient.sound ⟨equiv.prod_sum_distrib Ξ± Ξ² γ⟩ instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := Ξ»a b c, quotient.induction_on₃ a b c $ assume Ξ± Ξ² Ξ³, quotient.sound ⟨equiv.sum_assoc Ξ± Ξ² γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := Ξ»a b c, quotient.induction_on₃ a b c $ assume Ξ± Ξ² Ξ³, quotient.sound ⟨equiv.prod_assoc Ξ± Ξ² γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk Ξ± ^ mk Ξ²` is the cardinal of `Ξ² β†’ Ξ±`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_onβ‚‚ a b (λα Ξ², mk (Ξ² β†’ Ξ±)) $ assume α₁ Ξ±β‚‚ β₁ Ξ²β‚‚ ⟨eβ‚βŸ© ⟨eβ‚‚βŸ©, quotient.sound ⟨equiv.arrow_congr eβ‚‚ eβ‚βŸ© instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (Ξ± Ξ²) : mk Ξ± ^ mk Ξ² = mk (Ξ² β†’ Ξ±) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume Ξ±, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume Ξ±, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume Ξ±, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a β‰  0 β†’ 0 ^ a = 0 := quotient.induction_on a $ assume Ξ± heq, nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a, quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (Ξ» _, false) (f a)⟩ theorem power_ne_zero {a : cardinal} (b) : a β‰  0 β†’ a ^ b β‰  0 := quotient.induction_onβ‚‚ a b $ Ξ» Ξ± Ξ² h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume Ξ± Ξ² Ξ³, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow Ξ± Ξ² γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume Ξ± Ξ² Ξ³, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow Ξ² Ξ³ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume Ξ± Ξ² Ξ³, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow Ξ³ Ξ² α⟩) @[simp] lemma pow_cast_right (ΞΊ : cardinal.{u}) : βˆ€ n : β„•, (ΞΊ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow ΞΊ n | 0 := by simp | (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right] section order_properties open sum theorem zero_le : βˆ€(a : cardinal), 0 ≀ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ Ξ» ⟨a⟩, a.elim⟩ theorem le_zero (a : cardinal) : a ≀ 0 ↔ a = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o β‰  0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] @[simp] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≀ 1 := by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le } theorem add_le_add : βˆ€{a b c d : cardinal}, a ≀ b β†’ c ≀ d β†’ a + c ≀ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨eβ‚βŸ© ⟨eβ‚‚βŸ©; exact ⟨e₁.sum_map eβ‚‚βŸ© theorem add_le_add_left (a) {b c : cardinal} : b ≀ c β†’ a + b ≀ a + c := add_le_add (le_refl _) theorem add_le_add_right {a b : cardinal} (c) (h : a ≀ b) : a + c ≀ b + c := add_le_add h (le_refl _) theorem le_add_right (a b : cardinal) : a ≀ a + b := by simpa using add_le_add_left a (zero_le b) theorem le_add_left (a b : cardinal) : a ≀ b + a := by simpa using add_le_add_right a (zero_le b) theorem mul_le_mul : βˆ€{a b c d : cardinal}, a ≀ b β†’ c ≀ d β†’ a * c ≀ b * d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨eβ‚βŸ© ⟨eβ‚‚βŸ©; exact ⟨e₁.prod_map eβ‚‚βŸ© theorem mul_le_mul_left (a) {b c : cardinal} : b ≀ c β†’ a * b ≀ a * c := mul_le_mul (le_refl _) theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≀ b) : a * c ≀ b * c := mul_le_mul h (le_refl _) theorem power_le_power_left : βˆ€{a b c : cardinal}, a β‰  0 β†’ b ≀ c β†’ a ^ b ≀ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hΞ± ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hΞ± in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_max_power_one {a b c : cardinal} (h : b ≀ c) : a ^ b ≀ max (a ^ c) 1 := begin by_cases ha : a = 0, simp [ha, zero_power_le], exact le_trans (power_le_power_left ha h) (le_max_left _ _) end theorem power_le_power_right {a b c : cardinal} : a ≀ b β†’ a ^ c ≀ b ^ c := quotient.induction_on₃ a b c $ assume Ξ± Ξ² Ξ³ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ theorem le_iff_exists_add {a b : cardinal} : a ≀ b ↔ βˆƒ c, b = a + c := ⟨quotient.induction_onβ‚‚ a b $ Ξ» Ξ± Ξ² ⟨⟨f, hf⟩⟩, have (Ξ± βŠ• ((range f)ᢜ : set Ξ²)) ≃ Ξ², from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦β†₯(range f)ᢜ⟧, quotient.sound ⟨this.symm⟩⟩, Ξ» ⟨c, e⟩, add_zero a β–Έ e.symm β–Έ add_le_add_left _ (zero_le _)⟩ end order_properties instance : order_bot cardinal.{u} := { bot := 0, bot_le := zero_le, ..cardinal.linear_order } instance : canonically_ordered_add_monoid cardinal.{u} := { add_le_add_left := Ξ» a b h c, add_le_add_left _ h, lt_of_add_lt_add_left := Ξ» a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _), le_iff_exists_add := @le_iff_exists_add, ..cardinal.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } theorem cantor : βˆ€(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, Ξ» a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, Ξ» ⟨⟨f, hf⟩⟩, cantor_injective (Ξ» s, f (Ξ» a, ⟨s a⟩)) $ Ξ» s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := Ξ» a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ΞΉ} (I : nonempty ΞΉ) (f : ΞΉ β†’ cardinal) : cardinal := f $ classical.some $ @embedding.min_injective _ (Ξ» i, (f i).out) I theorem min_eq {ΞΉ} (I) (f : ΞΉ β†’ cardinal) : βˆƒ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ΞΉ I} (f : ΞΉ β†’ cardinal) (i) : min I f ≀ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.min_injective _ (Ξ» i, (f i).out) I) in ⟨g i⟩ theorem le_min {ΞΉ I} {f : ΞΉ β†’ cardinal} {a} : a ≀ min I f ↔ βˆ€ i, a ≀ f i := ⟨λ h i, le_trans h (min_le _ _), Ξ» h, let ⟨i, e⟩ := min_eq I f in e.symm β–Έ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ Ξ» h, let ΞΉ := {c :cardinal // Β¬ acc (<) c}, f : ΞΉ β†’ cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ΞΉ ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (Ξ» j ⟨_, h'⟩, classical.by_contradiction $ Ξ» hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≀ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), Ξ» h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≀ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≀ succ c := begin refine quot.induction_on c (Ξ» Ξ±, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r Ξ±)) (Ξ» Ξ² h, _), cases h.left with f, have : Β¬ surjective f := Ξ» hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective f ⟨f.injective, hn⟩⟩), cases not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact Ξ» _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.injective h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end lemma succ_ne_zero (c : cardinal) : succ c β‰  0 := by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le } /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ΞΉ} (f : ΞΉ β†’ cardinal) : cardinal := mk Ξ£ i, (f i).out theorem le_sum {ΞΉ} (f : ΞΉ β†’ cardinal) (i) : f i ≀ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, Ξ» a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ΞΉ} (f : ΞΉ β†’ Type*) : sum (Ξ» i, mk (f i)) = mk (Ξ£ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ Ξ» i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ΞΉ : Type u) (a : cardinal.{u}) : sum (Ξ» _:ΞΉ, a) = mk ΞΉ * a := quotient.induction_on a $ Ξ» Ξ±, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ΞΉ} (f g : ΞΉ β†’ cardinal) (H : βˆ€ i, f i ≀ g i) : sum f ≀ sum g := ⟨(embedding.refl _).sigma_map $ Ξ» i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ΞΉ} (f : ΞΉ β†’ cardinal) : cardinal := @min {c // βˆ€ i, f i ≀ c} ⟨⟨sum f, le_sum f⟩⟩ (Ξ» a, a.1) theorem le_sup {ΞΉ} (f : ΞΉ β†’ cardinal) (i) : f i ≀ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ΞΉ} {f : ΞΉ β†’ cardinal} {a} : sup f ≀ a ↔ βˆ€ i, f i ≀ a := ⟨λ h i, le_trans (le_sup _ _) h, Ξ» h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ΞΉ} (f g : ΞΉ β†’ cardinal) (H : βˆ€ i, f i ≀ g i) : sup f ≀ sup g := sup_le.2 $ Ξ» i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ΞΉ} (f : ΞΉ β†’ cardinal) : sup f ≀ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ΞΉ : Type u} (f : ΞΉ β†’ cardinal.{u}) : sum f ≀ mk ΞΉ * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) theorem sup_eq_zero {ΞΉ} {f : ΞΉ β†’ cardinal} (h : ΞΉ β†’ false) : sup f = 0 := by { rw [←le_zero, sup_le], intro x, exfalso, exact h x } /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ΞΉ : Type u} (f : ΞΉ β†’ cardinal) : cardinal := mk (Ξ  i, (f i).out) @[simp] theorem prod_mk {ΞΉ} (f : ΞΉ β†’ Type*) : prod (Ξ» i, mk (f i)) = mk (Ξ  i, f i) := quot.sound ⟨equiv.Pi_congr_right $ Ξ» i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ΞΉ : Type u) (a : cardinal.{u}) : prod (Ξ» _:ΞΉ, a) = a ^ mk ΞΉ := quotient.induction_on a $ by simp theorem prod_le_prod {ΞΉ} (f g : ΞΉ β†’ cardinal) (H : βˆ€ i, f i ≀ g i) : prod f ≀ prod g := ⟨embedding.Pi_congr_right $ Ξ» i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ΞΉ} (f : ΞΉ β†’ cardinal) : prod f β‰  0 ↔ βˆ€ i, f i β‰  0 := begin conv in (f _) {rw ← mk_out (f i)}, simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def], exact ⟨λ ⟨F⟩ i, ⟨F i⟩, Ξ» h, ⟨λ i, classical.choice (h i)⟩⟩, end theorem prod_eq_zero {ΞΉ} (f : ΞΉ β†’ cardinal) : prod f = 0 ↔ βˆƒ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{u} β†’ cardinal.{max u v}` -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (Ξ» Ξ±, ⟦ulift α⟧) $ Ξ» Ξ± Ξ² ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (Ξ±) : lift.{u v} (mk Ξ±) = mk (ulift.{v u} Ξ±) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ Ξ» a, quot.induction_on a $ Ξ» Ξ±, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ Ξ» Ξ±, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : βˆ€ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ Ξ» Ξ±, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {Ξ± : Type u} {Ξ² : Type v} : lift.{u (max v w)} (mk Ξ±) ≀ lift.{v (max u w)} (mk Ξ²) ↔ nonempty (Ξ± β†ͺ Ξ²) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, Ξ» ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {Ξ± : Type u} {Ξ² : Type v} : lift.{u (max v w)} (mk Ξ±) = lift.{v (max u w)} (mk Ξ²) ↔ nonempty (Ξ± ≃ Ξ²) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, Ξ» ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≀ lift b ↔ a ≀ b := quotient.induction_onβ‚‚ a b $ Ξ» Ξ± Ξ², by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_onβ‚‚ a b $ Ξ» Ξ± Ξ², quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_onβ‚‚ a b $ Ξ» Ξ± Ξ², quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_onβ‚‚ a b $ Ξ» Ξ± Ξ², quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ΞΉ I} (f : ΞΉ β†’ cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ Ξ» a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ Ξ» j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≀ lift a β†’ βˆƒ a', lift a' = b := quotient.induction_onβ‚‚ a b $ Ξ» Ξ± Ξ², by dsimp; rw [← lift_id (mk Ξ²), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact Ξ» ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ Ξ» ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≀ lift a ↔ βˆƒ a', lift a' = b ∧ a' ≀ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm β–Έ h⟩, Ξ» ⟨a', e, h⟩, e β–Έ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ βˆƒ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm β–Έ h⟩, Ξ» ⟨a', e, h⟩, e β–Έ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ Ξ» h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) @[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} : lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b := calc lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{(max u v) w} (lift.{u v} a) = lift.{(max u v) w} (lift.{v u} b) : by simp ... ↔ lift.{u v} a = lift.{v u} b : lift_inj theorem mk_prod {Ξ± : Type u} {Ξ² : Type v} : mk (Ξ± Γ— Ξ²) = lift.{u v} (mk Ξ±) * lift.{v u} (mk Ξ²) := quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩ theorem sum_const_eq_lift_mul (ΞΉ : Type u) (a : cardinal.{v}) : sum (Ξ» _:ΞΉ, a) = lift.{u v} (mk ΞΉ) * lift.{v u} a := begin apply quotient.induction_on a, intro Ξ±, simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id], convert mk_prod using 1, exact quotient.sound ⟨equiv.sigma_equiv_prod ΞΉ α⟩, end /-- `Ο‰` is the smallest infinite cardinal, also known as β„΅β‚€. -/ def omega : cardinal.{u} := lift (mk β„•) lemma mk_nat : mk nat = omega := (lift_id _).symm theorem omega_ne_zero : omega β‰  0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /- properties about the cast from nat -/ @[simp] theorem mk_fin : βˆ€ (n : β„•), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ Ξ» ⟨h⟩, h.elim0)⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : β„•) : lift n = n := by induction n; simp * lemma lift_eq_nat_iff {a : cardinal.{u}} {n : β„•} : lift.{u v} a = n ↔ a = n := by rw [← lift_nat_cast.{u v} n, lift_inj] lemma nat_eq_lift_eq_iff {n : β„•} {a : cardinal.{u}} : (n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a := by rw [← lift_nat_cast.{u v} n, lift_inj] theorem lift_mk_fin (n : β„•) : lift (mk (fin n)) = n := by simp theorem fintype_card (Ξ± : Type u) [fintype Ξ±] : mk Ξ± = fintype.card Ξ± := by rw [← lift_mk_fin.{u}, ← lift_id (mk Ξ±), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {Ξ±} (s : finset Ξ±) : (s.card : cardinal) ≀ cardinal.mk Ξ± := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set Ξ±)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp, norm_cast] theorem nat_cast_pow {m n : β„•} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *] @[simp, norm_cast] theorem nat_cast_le {m n : β„•} : (m : cardinal) ≀ n ↔ m ≀ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, Ξ» h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, Ξ» a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp, norm_cast] theorem nat_cast_lt {m n : β„•} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp, norm_cast] theorem nat_cast_inj {m n : β„•} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp, norm_cast, priority 900] theorem nat_succ (n : β„•) : (n.succ : cardinal) = succ n := le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) @[simp] theorem succ_zero : succ 0 = 1 := by norm_cast theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≀ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≀ c ↔ c β‰  0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : β„•) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨coe, Ξ» a b, fin.ext⟩⟩ @[simp] theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ βˆƒ n : β„•, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : βˆ€ (n : β„•) (IH : βˆ€ i<n, S), βˆƒ a : S, Β¬ βˆƒ y h, IH y h = a := Ξ» n IH, let g : {i | i < n} β†’ S := Ξ» ⟨i, h⟩, IH i h in not_forall.1 (Ξ» h, nf ⟨fintype.of_surjective g (Ξ» a, subtype.exists.2 (h a))⟩), let F : β„• β†’ S := nat.lt_wf.fix (Ξ» n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : βˆ€ (n : β„•) (m < n), F m β‰  F n, { refine Ξ» m n, not_imp_not.1 (Ξ» ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (Ξ» y _, F y)), rw [← show F n = classical.some (P n (Ξ» y _, F y)), from nat.lt_wf.fix_eq (Ξ» n IH, classical.some (P n IH)) n] at this, exact Ξ» e, this ⟨m, h, e⟩, end, Ξ» ⟨n, e⟩, e.symm β–Έ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≀ c ↔ βˆ€ n : β„•, (n:cardinal) ≀ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, Ξ» h, le_of_not_lt $ Ξ» hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {Ξ± : Type u} : mk Ξ± < omega ↔ nonempty (fintype Ξ±) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, Ξ» ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {Ξ±} {S : set Ξ±} : mk S < omega ↔ finite S := lt_omega_iff_fintype instance can_lift_cardinal_nat : can_lift cardinal β„• := ⟨ coe, Ξ» x, x < omega, Ξ» x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩ theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega := ⟨λ h, ⟨lt_of_le_of_lt (le_add_right _ _) h, lt_of_le_of_lt (le_add_left _ _) h⟩, λ⟨h1, h2⟩, add_lt_omega h1 h2⟩ theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega := begin split, { intro h, by_cases ha : a = 0, { left, exact ha }, right, by_cases hb : b = 0, { left, exact hb }, right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split, { rw [← mul_one a], refine lt_of_le_of_lt (mul_le_mul (le_refl a) hb) h }, { rw [← _root_.one_mul b], refine lt_of_le_of_lt (mul_le_mul ha (le_refl b)) h }}, rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero] end lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a β‰  0) (hb : b β‰  0) : a * b < omega ↔ a < omega ∧ b < omega := by simp [mul_lt_omega_iff, ha, hb] theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end lemma eq_one_iff_subsingleton_and_nonempty {Ξ± : Type*} : mk Ξ± = 1 ↔ (subsingleton Ξ± ∧ nonempty Ξ±) := calc mk Ξ± = 1 ↔ mk Ξ± ≀ 1 ∧ Β¬mk Ξ± < 1 : eq_iff_le_not_lt ... ↔ subsingleton Ξ± ∧ nonempty Ξ± : begin apply and_congr le_one_iff_subsingleton, push_neg, rw [one_le_iff_ne_zero, ne_zero_iff_nonempty] end theorem infinite_iff {Ξ± : Type u} : infinite Ξ± ↔ omega ≀ mk Ξ± := by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype] lemma countable_iff (s : set Ξ±) : countable s ↔ mk s ≀ omega := begin rw [countable_iff_exists_injective], split, rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩, rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩ end lemma denumerable_iff {Ξ± : Type u} : nonempty (denumerable Ξ±) ↔ mk Ξ± = omega := ⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv Ξ±).trans equiv.ulift.symm ⟩, Ξ» h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ lemma mk_int : mk β„€ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma mk_pnat : mk β„•+ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma two_le_iff : (2 : cardinal) ≀ mk Ξ± ↔ βˆƒx y : Ξ±, x β‰  y := begin split, { rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h }, { rintro ⟨x, y, h⟩, by_contra h', rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : Ξ±) : (2 : cardinal) ≀ mk Ξ± ↔ βˆƒy : Ξ±, x β‰  y := begin rw [two_le_iff], split, { rintro ⟨y, z, h⟩, refine classical.by_cases (Ξ»(h' : x = y), _) (Ξ» h', ⟨y, h'⟩), rw [←h'] at h, exact ⟨z, h⟩ }, { rintro ⟨y, h⟩, exact ⟨x, y, h⟩ } end /-- KΓΆnig's theorem -/ theorem sum_lt_prod {ΞΉ} (f g : ΞΉ β†’ cardinal) (H : βˆ€ i, f i < g i) : sum f < prod g := lt_of_not_ge $ Ξ» ⟨F⟩, begin have : inhabited (Ξ  (i : ΞΉ), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show βˆ€ i, βˆƒ b, βˆ€ a, G ⟨i, a⟩ i β‰  b, { assume i, simp only [- not_exists, not_exists.symm, not_forall.symm], refine Ξ» h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective _ h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_plift_of_false {p : Prop} (h : Β¬ p) : mk (plift p) = 0 := quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩ theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {Ξ± : Type u} (x : Ξ±) : mk ({x} : set Ξ±) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 := quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_option {Ξ± : Type u} : mk (option Ξ±) = mk Ξ± + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_list_eq_sum_pow (Ξ± : Type u) : mk (list Ξ±) = sum (Ξ» n : β„•, (mk Ξ±)^(n:cardinal.{u})) := calc mk (list Ξ±) = mk (Ξ£ n, vector Ξ± n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩ ... = mk (Ξ£ n, fin n β†’ Ξ±) : quotient.sound ⟨equiv.sigma_congr_right $ Ξ» n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, Ξ» f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Ξ£ n : β„•, ulift.{u} (fin n) β†’ Ξ±) : quotient.sound ⟨equiv.sigma_congr_right $ Ξ» n, equiv.arrow_congr equiv.ulift.symm (equiv.refl Ξ±)⟩ ... = sum (Ξ» n : β„•, (mk Ξ±)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_quot_le {Ξ± : Type u} {r : Ξ± β†’ Ξ± β†’ Prop} : mk (quot r) ≀ mk Ξ± := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {Ξ± : Type u} {s : setoid Ξ±} : mk (quotient s) ≀ mk Ξ± := mk_quot_le theorem mk_subtype_le {Ξ± : Type u} (p : Ξ± β†’ Prop) : mk (subtype p) ≀ mk Ξ± := ⟨embedding.subtype p⟩ theorem mk_subtype_le_of_subset {Ξ± : Type u} {p q : Ξ± β†’ Prop} (h : βˆ€ ⦃x⦄, p x β†’ q x) : mk (subtype p) ≀ mk (subtype q) := ⟨embedding.subtype_map (embedding.refl Ξ±) h⟩ @[simp] theorem mk_emptyc (Ξ± : Type u) : mk (βˆ… : set Ξ±) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ lemma mk_emptyc_iff {Ξ± : Type u} {s : set Ξ±} : mk s = 0 ↔ s = βˆ… := begin split, { intro h, have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h], refine set.eq_empty_iff_forall_not_mem.mpr (Ξ» _ hx, _), rcases cardinal.eq.mp h2 with ⟨f, _⟩, cases f ⟨_, hx⟩ }, { intro, convert mk_emptyc _ } end theorem mk_univ {Ξ± : Type u} : mk (@univ Ξ±) = mk Ξ± := quotient.sound ⟨equiv.set.univ α⟩ theorem mk_image_le {Ξ± Ξ² : Type u} {f : Ξ± β†’ Ξ²} {s : set Ξ±} : mk (f '' s) ≀ mk s := mk_le_of_surjective surjective_onto_image theorem mk_image_le_lift {Ξ± : Type u} {Ξ² : Type v} {f : Ξ± β†’ Ξ²} {s : set Ξ±} : lift.{v u} (mk (f '' s)) ≀ lift.{u v} (mk s) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩ theorem mk_range_le {Ξ± Ξ² : Type u} {f : Ξ± β†’ Ξ²} : mk (range f) ≀ mk Ξ± := mk_le_of_surjective surjective_onto_range lemma mk_range_eq (f : Ξ± β†’ Ξ²) (h : injective f) : mk (range f) = mk Ξ± := quotient.sound ⟨(equiv.set.range f h).symm⟩ lemma mk_range_eq_of_injective {Ξ± : Type u} {Ξ² : Type v} {f : Ξ± β†’ Ξ²} (hf : injective f) : lift.{v u} (mk (range f)) = lift.{u v} (mk Ξ±) := begin have := (@lift_mk_eq.{v u max u v} (range f) Ξ±).2 ⟨(equiv.set.range f hf).symm⟩, simp only [lift_umax.{u v}, lift_umax.{v u}] at this, exact this end lemma mk_range_eq_lift {Ξ± : Type u} {Ξ² : Type v} {f : Ξ± β†’ Ξ²} (hf : injective f) : lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# Ξ±) := lift_mk_eq.mpr ⟨(equiv.set.range f hf).symm⟩ theorem mk_image_eq {Ξ± Ξ² : Type u} {f : Ξ± β†’ Ξ²} {s : set Ξ±} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_Union_le_sum_mk {Ξ± ΞΉ : Type u} {f : ΞΉ β†’ set Ξ±} : mk (⋃ i, f i) ≀ sum (Ξ» i, mk (f i)) := calc mk (⋃ i, f i) ≀ mk (Ξ£ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f) ... = sum (Ξ» i, mk (f i)) : (sum_mk _).symm theorem mk_Union_eq_sum_mk {Ξ± ΞΉ : Type u} {f : ΞΉ β†’ set Ξ±} (h : βˆ€i j, i β‰  j β†’ disjoint (f i) (f j)) : mk (⋃ i, f i) = sum (Ξ» i, mk (f i)) := calc mk (⋃ i, f i) = mk (Ξ£i, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩ ... = sum (Ξ»i, mk (f i)) : (sum_mk _).symm lemma mk_Union_le {Ξ± ΞΉ : Type u} (f : ΞΉ β†’ set Ξ±) : mk (⋃ i, f i) ≀ mk ΞΉ * cardinal.sup.{u u} (Ξ» i, mk (f i)) := le_trans mk_Union_le_sum_mk (sum_le_sup _) lemma mk_sUnion_le {Ξ± : Type u} (A : set (set Ξ±)) : mk (⋃₀ A) ≀ mk A * cardinal.sup.{u u} (Ξ» s : A, mk s) := by { rw [sUnion_eq_Union], apply mk_Union_le } lemma mk_bUnion_le {ΞΉ Ξ± : Type u} (A : ΞΉ β†’ set Ξ±) (s : set ΞΉ) : mk (⋃(x ∈ s), A x) ≀ mk s * cardinal.sup.{u u} (Ξ» x : s, mk (A x.1)) := by { rw [bUnion_eq_Union], apply mk_Union_le } @[simp] lemma finset_card {Ξ± : Type u} {s : finset Ξ±} : ↑(finset.card s) = mk (↑s : set Ξ±) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] lemma finset_card_lt_omega (s : finset Ξ±) : mk (↑s : set Ξ±) < omega := by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ } theorem mk_union_add_mk_inter {Ξ± : Type u} {S T : set Ξ±} : mk (S βˆͺ T : set Ξ±) + mk (S ∩ T : set Ξ±) = mk S + mk T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ /-- The cardinality of a union is at most the sum of the cardinalities of the two sets. -/ lemma mk_union_le {Ξ± : Type u} (S T : set Ξ±) : mk (S βˆͺ T : set Ξ±) ≀ mk S + mk T := @mk_union_add_mk_inter Ξ± S T β–Έ le_add_right (mk (S βˆͺ T : set Ξ±)) (mk (S ∩ T : set Ξ±)) theorem mk_union_of_disjoint {Ξ± : Type u} {S T : set Ξ±} (H : disjoint S T) : mk (S βˆͺ T : set Ξ±) = mk S + mk T := quot.sound ⟨equiv.set.union H⟩ lemma mk_sum_compl {Ξ±} (s : set Ξ±) : #s + #(sᢜ : set Ξ±) = #Ξ± := quotient.sound ⟨equiv.set.sum_compl s⟩ lemma mk_le_mk_of_subset {Ξ±} {s t : set Ξ±} (h : s βŠ† t) : mk s ≀ mk t := ⟨set.embedding_of_subset s t h⟩ lemma mk_subtype_mono {p q : Ξ± β†’ Prop} (h : βˆ€x, p x β†’ q x) : mk {x // p x} ≀ mk {x // q x} := ⟨embedding_of_subset _ _ h⟩ lemma mk_set_le (s : set Ξ±) : mk s ≀ mk Ξ± := mk_subtype_le s lemma mk_image_eq_lift {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β†’ Ξ²) (s : set Ξ±) (h : injective f) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩ lemma mk_image_eq_of_inj_on_lift {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β†’ Ξ²) (s : set Ξ±) (h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_image_eq_of_inj_on {Ξ± Ξ² : Type u} (f : Ξ± β†’ Ξ²) (s : set Ξ±) (h : inj_on f s) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_subtype_of_equiv {Ξ± Ξ² : Type u} (p : Ξ² β†’ Prop) (e : Ξ± ≃ Ξ²) : mk {a : Ξ± // p (e a)} = mk {b : Ξ² // p b} := quotient.sound ⟨equiv.subtype_equiv_of_subtype e⟩ lemma mk_sep (s : set Ξ±) (t : Ξ± β†’ Prop) : mk ({ x ∈ s | t x } : set Ξ±) = mk { x : s | t x.1 } := quotient.sound ⟨equiv.set.sep s t⟩ lemma mk_preimage_of_injective_lift {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β†’ Ξ²) (s : set Ξ²) (h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≀ lift.{v u} (mk s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (Ξ» x, f x.1) (Ξ» x, x.2), apply subtype.coind_injective, exact h.comp subtype.val_injective end lemma mk_preimage_of_subset_range_lift {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β†’ Ξ²) (s : set Ξ²) (h : s βŠ† range f) : lift.{v u} (mk s) ≀ lift.{u v} (mk (f ⁻¹' s)) := begin rw lift_mk_le.{v u 0}, refine ⟨⟨_, _⟩⟩, { rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ }, rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩, simp, intro hxx', rw hxx' end lemma mk_preimage_of_injective_of_subset_range_lift {Ξ² : Type v} (f : Ξ± β†’ Ξ²) (s : set Ξ²) (h : injective f) (h2 : s βŠ† range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) lemma mk_preimage_of_injective (f : Ξ± β†’ Ξ²) (s : set Ξ²) (h : injective f) : mk (f ⁻¹' s) ≀ mk s := by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_subset_range (f : Ξ± β†’ Ξ²) (s : set Ξ²) (h : s βŠ† range f) : mk s ≀ mk (f ⁻¹' s) := by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_injective_of_subset_range (f : Ξ± β†’ Ξ²) (s : set Ξ²) (h : injective f) (h2 : s βŠ† range f) : mk (f ⁻¹' s) = mk s := by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] } lemma mk_subset_ge_of_subset_image_lift {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β†’ Ξ²) {s : set Ξ±} {t : set Ξ²} (h : t βŠ† f '' s) : lift.{v u} (mk t) ≀ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set Ξ±)) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl } lemma mk_subset_ge_of_subset_image (f : Ξ± β†’ Ξ²) {s : set Ξ±} {t : set Ξ²} (h : t βŠ† f '' s) : mk t ≀ mk ({ x ∈ s | f x ∈ t } : set Ξ±) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl } theorem le_mk_iff_exists_subset {c : cardinal} {Ξ± : Type u} {s : set Ξ±} : c ≀ mk s ↔ βˆƒ p : set Ξ±, p βŠ† s ∧ mk p = c := begin rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype], apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective end /-- The function Ξ±^{<Ξ²}, defined to be sup_{Ξ³ < Ξ²} Ξ±^Ξ³. We index over {s : set Ξ².out // mk s < Ξ² } instead of {Ξ³ // Ξ³ < Ξ²}, because the latter lives in a higher universe -/ noncomputable def powerlt (Ξ± Ξ² : cardinal.{u}) : cardinal.{u} := sup.{u u} (Ξ»(s : {s : set Ξ².out // mk s < Ξ²}), Ξ± ^ mk.{u} s) infix ` ^< `:80 := powerlt theorem powerlt_aux {c c' : cardinal} (h : c < c') : βˆƒ(s : {s : set c'.out // mk s < c'}), mk s = c := begin cases out_embedding.mp (le_of_lt h) with f, have : mk β†₯(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 }, exact ⟨⟨range f, by convert h⟩, this⟩ end lemma le_powerlt {c₁ cβ‚‚ c₃ : cardinal} (h : cβ‚‚ < c₃) : c₁ ^ cβ‚‚ ≀ c₁ ^< c₃ := by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s } lemma powerlt_le {c₁ cβ‚‚ c₃ : cardinal} : c₁ ^< cβ‚‚ ≀ c₃ ↔ βˆ€(cβ‚„ < cβ‚‚), c₁ ^ cβ‚„ ≀ c₃ := begin rw [powerlt, sup_le], split, { intros h cβ‚„ hcβ‚„, rcases powerlt_aux hcβ‚„ with ⟨s, rfl⟩, exact h s }, intros h s, exact h _ s.2 end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≀ c) : a ^< b ≀ a ^< c := by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h } lemma powerlt_succ {c₁ cβ‚‚ : cardinal} (h : c₁ β‰  0) : c₁ ^< cβ‚‚.succ = c₁ ^ cβ‚‚ := begin apply le_antisymm, { rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] }, { apply le_powerlt, apply lt_succ_self } end lemma powerlt_max {c₁ cβ‚‚ c₃ : cardinal} : c₁ ^< max cβ‚‚ c₃ = max (c₁ ^< cβ‚‚) (c₁ ^< c₃) := by { cases le_total cβ‚‚ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] } lemma zero_powerlt {a : cardinal} (h : a β‰  0) : 0 ^< a = 1 := begin apply le_antisymm, { rw [powerlt_le], intros c hc, apply zero_power_le }, convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero] end lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le } end cardinal
102e8c73e36dc4a0a96d03b37c25611c7e42a1b5
e94d3f31e48d06d252ee7307fe71efe1d500f274
/hott/init/equiv.hlean
cd5174045d46b75a6792d5d4a72b5ee132309b9e
[ "Apache-2.0" ]
permissive
GallagherCommaJack/lean
e4471240a069d82f97cb361d2bf1a029de3f4256
226f8bafeb9baaa5a2ac58000c83d6beb29991e2
refs/heads/master
1,610,725,100,482
1,459,194,829,000
1,459,195,377,000
55,377,224
0
0
null
1,459,731,701,000
1,459,731,700,000
null
UTF-8
Lean
false
false
17,140
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .path .function open eq function lift /- Equivalences -/ -- This is our definition of equivalence. In the HoTT-book it's called -- ihae (half-adjoint equivalence). structure is_equiv [class] {A B : Type} (f : A β†’ B) := mk' :: (inv : B β†’ A) (right_inv : Ξ b, f (inv b) = b) (left_inv : Ξ a, inv (f a) = a) (adj : Ξ x, right_inv (f x) = ap f (left_inv x)) attribute is_equiv.inv [reducible] -- A more bundled version of equivalence structure equiv (A B : Type) := (to_fun : A β†’ B) (to_is_equiv : is_equiv to_fun) namespace is_equiv /- Some instances and closure properties of equivalences -/ postfix ⁻¹ := inv /- a second notation for the inverse, which is not overloaded -/ postfix [parsing_only] `⁻¹ᢠ`:std.prec.max_plus := inv section variables {A B C : Type} (f : A β†’ B) (g : B β†’ C) {f' : A β†’ B} -- The variant of mk' where f is explicit. protected abbreviation mk [constructor] := @is_equiv.mk' A B f -- The identity function is an equivalence. definition is_equiv_id [instance] [constructor] (A : Type) : (is_equiv (id : A β†’ A)) := is_equiv.mk id id (Ξ»a, idp) (Ξ»a, idp) (Ξ»a, idp) -- The composition of two equivalences is, again, an equivalence. definition is_equiv_compose [constructor] [Hf : is_equiv f] [Hg : is_equiv g] : is_equiv (g ∘ f) := is_equiv.mk (g ∘ f) (f⁻¹ ∘ g⁻¹) abstract (Ξ»c, ap g (right_inv f (g⁻¹ c)) ⬝ right_inv g c) end abstract (Ξ»a, ap (inv f) (left_inv g (f a)) ⬝ left_inv f a) end abstract (Ξ»a, (whisker_left _ (adj g (f a))) ⬝ (ap_con g _ _)⁻¹ ⬝ ap02 g ((ap_con_eq_con (right_inv f) (left_inv g (f a)))⁻¹ ⬝ (ap_compose f (inv f) _ β—Ύ adj f a) ⬝ (ap_con f _ _)⁻¹ ) ⬝ (ap_compose g f _)⁻¹) end -- Any function equal to an equivalence is an equivlance as well. variable {f} definition is_equiv_eq_closed [Hf : is_equiv f] (Heq : f = f') : is_equiv f' := eq.rec_on Heq Hf end section parameters {A B : Type} (f : A β†’ B) (g : B β†’ A) (ret : Ξ b, f (g b) = b) (sec : Ξ a, g (f a) = a) private definition adjointify_left_inv' (a : A) : g (f a) = a := ap g (ap f (inverse (sec a))) ⬝ ap g (ret (f a)) ⬝ sec a private theorem adjointify_adj' (a : A) : ret (f a) = ap f (adjointify_left_inv' a) := let fgretrfa := ap f (ap g (ret (f a))) in let fgfinvsect := ap f (ap g (ap f (sec a)⁻¹)) in let fgfa := f (g (f a)) in let retrfa := ret (f a) in have eq1 : ap f (sec a) = _, from calc ap f (sec a) = idp ⬝ ap f (sec a) : by rewrite idp_con ... = (ret (f a) ⬝ (ret (f a))⁻¹) ⬝ ap f (sec a) : by rewrite con.right_inv ... = ((ret fgfa)⁻¹ ⬝ ap (f ∘ g) (ret (f a))) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((ret fgfa)⁻¹ ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc, have eq2 : ap f (sec a) ⬝ idp = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)), from !con_idp ⬝ eq1, have eq3 : idp = _, from calc idp = (ap f (sec a))⁻¹ ⬝ ((ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a))) : eq_inv_con_of_con_eq eq2 ... = ((ap f (sec a))⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc' ... = (ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite ap_inv ... = ((ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con.assoc' ... = ((retrfa⁻¹ ⬝ ap (f ∘ g) (ap f (sec a)⁻¹)) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((retrfa⁻¹ ⬝ fgfinvsect) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (retrfa⁻¹ ⬝ (fgfinvsect ⬝ fgretrfa)) ⬝ ap f (sec a) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a) : by rewrite ap_con ... = retrfa⁻¹ ⬝ (ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a)) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a) : by rewrite -ap_con, show ret (f a) = ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a), from eq_of_idp_eq_inv_con eq3 definition adjointify [constructor] : is_equiv f := is_equiv.mk f g ret adjointify_left_inv' adjointify_adj' end -- Any function pointwise equal to an equivalence is an equivalence as well. definition homotopy_closed [constructor] {A B : Type} (f : A β†’ B) {f' : A β†’ B} [Hf : is_equiv f] (Hty : f ~ f') : is_equiv f' := adjointify f' (inv f) (Ξ» b, (Hty (inv f b))⁻¹ ⬝ right_inv f b) (Ξ» a, (ap (inv f) (Hty a))⁻¹ ⬝ left_inv f a) definition inv_homotopy_closed [constructor] {A B : Type} {f : A β†’ B} {f' : B β†’ A} [Hf : is_equiv f] (Hty : f⁻¹ ~ f') : is_equiv f := adjointify f f' (Ξ» b, ap f !Hty⁻¹ ⬝ right_inv f b) (Ξ» a, !Hty⁻¹ ⬝ left_inv f a) definition is_equiv_up [instance] [constructor] (A : Type) : is_equiv (up : A β†’ lift A) := adjointify up down (Ξ»a, by induction a;reflexivity) (Ξ»a, idp) section variables {A B C : Type} (f : A β†’ B) {f' : A β†’ B} [Hf : is_equiv f] (g : B β†’ C) include Hf --The inverse of an equivalence is, again, an equivalence. definition is_equiv_inv [instance] [constructor] : is_equiv f⁻¹ := adjointify f⁻¹ f (left_inv f) (right_inv f) definition cancel_right (g : B β†’ C) [Hgf : is_equiv (g ∘ f)] : (is_equiv g) := have Hfinv : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose f⁻¹ (g ∘ f)) (Ξ»b, ap g (@right_inv _ _ f _ b)) definition cancel_left (g : C β†’ A) [Hgf : is_equiv (f ∘ g)] : (is_equiv g) := have Hfinv : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose (f ∘ g) f⁻¹) (Ξ»a, left_inv f (g a)) definition eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y theorem ap_eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : ap f (eq_of_fn_eq_fn' f q) = q := begin rewrite [↑eq_of_fn_eq_fn',+ap_con,ap_inv,-+adj,-ap_compose,con.assoc, ap_con_eq_con_ap (right_inv f) q,inv_con_cancel_left,ap_id], end definition is_equiv_ap [instance] (x y : A) : is_equiv (ap f : x = y β†’ f x = f y) := adjointify (ap f) (eq_of_fn_eq_fn' f) abstract (Ξ»q, !ap_con ⬝ whisker_right !ap_con _ ⬝ ((!ap_inv ⬝ inverse2 (adj f _)⁻¹) β—Ύ (inverse (ap_compose f f⁻¹ _)) β—Ύ (adj f _)⁻¹) ⬝ con_ap_con_eq_con_con (right_inv f) _ _ ⬝ whisker_right !con.left_inv _ ⬝ !idp_con) end abstract (Ξ»p, whisker_right (whisker_left _ (ap_compose f⁻¹ f _)⁻¹) _ ⬝ con_ap_con_eq_con_con (left_inv f) _ _ ⬝ whisker_right !con.left_inv _ ⬝ !idp_con) end -- The function equiv_rect says that given an equivalence f : A β†’ B, -- and a hypothesis from B, one may always assume that the hypothesis -- is in the image of e. -- In fibrational terms, if we have a fibration over B which has a section -- once pulled back along an equivalence f : A β†’ B, then it has a section -- over all of B. definition is_equiv_rect (P : B β†’ Type) (g : Ξ a, P (f a)) (b : B) : P b := right_inv f b β–Έ g (f⁻¹ b) definition is_equiv_rect' (P : A β†’ B β†’ Type) (g : Ξ b, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a β–Έ g (f a) definition is_equiv_rect_comp (P : B β†’ Type) (df : Ξ  (x : A), P (f x)) (x : A) : is_equiv_rect f P df (f x) = df x := calc is_equiv_rect f P df (f x) = right_inv f (f x) β–Έ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) β–Έ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x β–Έ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apd df (left_inv f x)) theorem adj_inv (b : B) : left_inv f (f⁻¹ b) = ap f⁻¹ (right_inv f b) := is_equiv_rect f _ (Ξ»a, eq.cancel_right (left_inv f (id a)) (whisker_left _ !ap_id⁻¹ ⬝ (ap_con_eq_con_ap (left_inv f) (left_inv f a))⁻¹) ⬝ !ap_compose ⬝ ap02 f⁻¹ (adj f a)⁻¹) b end section variables {A B C : Type} {f : A β†’ B} [Hf : is_equiv f] include Hf section rewrite_rules variables {a : A} {b : B} definition eq_of_eq_inv (p : a = f⁻¹ b) : f a = b := ap f p ⬝ right_inv f b definition eq_of_inv_eq (p : f⁻¹ b = a) : b = f a := (eq_of_eq_inv p⁻¹)⁻¹ definition inv_eq_of_eq (p : b = f a) : f⁻¹ b = a := ap f⁻¹ p ⬝ left_inv f a definition eq_inv_of_eq (p : f a = b) : a = f⁻¹ b := (inv_eq_of_eq p⁻¹)⁻¹ end rewrite_rules variable (f) section pre_compose variables (Ξ± : A β†’ C) (Ξ² : B β†’ C) definition homotopy_of_homotopy_inv_pre (p : Ξ² ~ Ξ± ∘ f⁻¹) : Ξ² ∘ f ~ Ξ± := Ξ» a, p (f a) ⬝ ap Ξ± (left_inv f a) definition homotopy_of_inv_homotopy_pre (p : Ξ± ∘ f⁻¹ ~ Ξ²) : Ξ± ~ Ξ² ∘ f := Ξ» a, (ap Ξ± (left_inv f a))⁻¹ ⬝ p (f a) definition inv_homotopy_of_homotopy_pre (p : Ξ± ~ Ξ² ∘ f) : Ξ± ∘ f⁻¹ ~ Ξ² := Ξ» b, p (f⁻¹ b) ⬝ ap Ξ² (right_inv f b) definition homotopy_inv_of_homotopy_pre (p : Ξ² ∘ f ~ Ξ±) : Ξ² ~ Ξ± ∘ f⁻¹ := Ξ» b, (ap Ξ² (right_inv f b))⁻¹ ⬝ p (f⁻¹ b) end pre_compose section post_compose variables (Ξ± : C β†’ A) (Ξ² : C β†’ B) definition homotopy_of_homotopy_inv_post (p : Ξ± ~ f⁻¹ ∘ Ξ²) : f ∘ Ξ± ~ Ξ² := Ξ» c, ap f (p c) ⬝ (right_inv f (Ξ² c)) definition homotopy_of_inv_homotopy_post (p : f⁻¹ ∘ Ξ² ~ Ξ±) : Ξ² ~ f ∘ Ξ± := Ξ» c, (right_inv f (Ξ² c))⁻¹ ⬝ ap f (p c) definition inv_homotopy_of_homotopy_post (p : Ξ² ~ f ∘ Ξ±) : f⁻¹ ∘ Ξ² ~ Ξ± := Ξ» c, ap f⁻¹ (p c) ⬝ (left_inv f (Ξ± c)) definition homotopy_inv_of_homotopy_post (p : f ∘ Ξ± ~ Ξ²) : Ξ± ~ f⁻¹ ∘ Ξ² := Ξ» c, (left_inv f (Ξ± c))⁻¹ ⬝ ap f⁻¹ (p c) end post_compose end --Transporting is an equivalence definition is_equiv_tr [constructor] {A : Type} (P : A β†’ Type) {x y : A} (p : x = y) : (is_equiv (transport P p)) := is_equiv.mk _ (transport P p⁻¹) (tr_inv_tr p) (inv_tr_tr p) (tr_inv_tr_lemma p) section variables {A : Type} {B C : A β†’ Type} (f : Ξ {a}, B a β†’ C a) [H : Ξ a, is_equiv (@f a)] {g : A β†’ A} {g' : A β†’ A} (h : Ξ {a}, B (g' a) β†’ B (g a)) (h' : Ξ {a}, C (g' a) β†’ C (g a)) include H definition inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) := eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹) definition fun_commute_of_inv_commute' (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c)) {a : A} (b : B (g' a)) : f (h b) = h' (f b) := eq_of_fn_eq_fn' f⁻¹ (left_inv f (h b) ⬝ ap h (left_inv f b)⁻¹ ⬝ (p (f b))⁻¹) definition ap_inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : ap f (inv_commute' @f @h @h' p c) = right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹ := !ap_eq_of_fn_eq_fn' end end is_equiv open is_equiv namespace eq local attribute is_equiv_tr [instance] definition tr_inv_fn {A : Type} {B : A β†’ Type} {a a' : A} (p : a = a') : transport B p⁻¹ = (transport B p)⁻¹ := idp definition tr_inv {A : Type} {B : A β†’ Type} {a a' : A} (p : a = a') (b : B a') : p⁻¹ β–Έ b = (transport B p)⁻¹ b := idp definition cast_inv_fn {A B : Type} (p : A = B) : cast p⁻¹ = (cast p)⁻¹ := idp definition cast_inv {A B : Type} (p : A = B) (b : B) : cast p⁻¹ b = (cast p)⁻¹ b := idp end eq infix ` ≃ `:25 := equiv attribute equiv.to_is_equiv [instance] namespace equiv attribute to_fun [coercion] section variables {A B C : Type} protected definition MK [reducible] [constructor] (f : A β†’ B) (g : B β†’ A) (right_inv : Ξ b, f (g b) = b) (left_inv : Ξ a, g (f a) = a) : A ≃ B := equiv.mk f (adjointify f g right_inv left_inv) definition to_inv [reducible] [unfold 3] (f : A ≃ B) : B β†’ A := f⁻¹ definition to_right_inv [reducible] [unfold 3] (f : A ≃ B) (b : B) : f (f⁻¹ b) = b := right_inv f b definition to_left_inv [reducible] [unfold 3] (f : A ≃ B) (a : A) : f⁻¹ (f a) = a := left_inv f a protected definition refl [refl] [constructor] : A ≃ A := equiv.mk id !is_equiv_id protected definition symm [symm] (f : A ≃ B) : B ≃ A := equiv.mk f⁻¹ !is_equiv_inv protected definition trans [trans] (f : A ≃ B) (g : B ≃ C) : A ≃ C := equiv.mk (g ∘ f) !is_equiv_compose infixl ` ⬝e `:75 := equiv.trans postfix `⁻¹ᡉ`:(max + 1) := equiv.symm -- notation for inverse which is not overloaded abbreviation erfl [constructor] := @equiv.refl definition to_inv_trans [reducible] [unfold_full] (f : A ≃ B) (g : B ≃ C) : to_inv (f ⬝e g) = to_fun (g⁻¹ᡉ ⬝e f⁻¹ᡉ) := idp definition equiv_change_fun [constructor] (f : A ≃ B) {f' : A β†’ B} (Heq : f ~ f') : A ≃ B := equiv.mk f' (is_equiv.homotopy_closed f Heq) definition equiv_change_inv [constructor] (f : A ≃ B) {f' : B β†’ A} (Heq : f⁻¹ ~ f') : A ≃ B := equiv.mk f (inv_homotopy_closed Heq) --rename: eq_equiv_fn_eq_of_is_equiv definition eq_equiv_fn_eq [constructor] (f : A β†’ B) [H : is_equiv f] (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap --rename: eq_equiv_fn_eq definition eq_equiv_fn_eq_of_equiv [constructor] (f : A ≃ B) (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap definition equiv_ap [constructor] (P : A β†’ Type) {a b : A} (p : a = b) : P a ≃ P b := equiv.mk (transport P p) !is_equiv_tr definition equiv_of_eq [constructor] {A B : Type} (p : A = B) : A ≃ B := equiv.mk (cast p) !is_equiv_tr definition eq_of_fn_eq_fn (f : A ≃ B) {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y definition eq_of_fn_eq_fn_inv (f : A ≃ B) {x y : B} (q : f⁻¹ x = f⁻¹ y) : x = y := (right_inv f x)⁻¹ ⬝ ap f q ⬝ right_inv f y --we need this theorem for the funext_of_ua proof theorem inv_eq {A B : Type} (eqf eqg : A ≃ B) (p : eqf = eqg) : (to_fun eqf)⁻¹ = (to_fun eqg)⁻¹ := eq.rec_on p idp definition equiv_of_equiv_of_eq [trans] {A B C : Type} (p : A = B) (q : B ≃ C) : A ≃ C := equiv_of_eq p ⬝e q definition equiv_of_eq_of_equiv [trans] {A B C : Type} (p : A ≃ B) (q : B = C) : A ≃ C := p ⬝e equiv_of_eq q definition equiv_lift [constructor] (A : Type) : A ≃ lift A := equiv.mk up _ definition equiv_rect (f : A ≃ B) (P : B β†’ Type) (g : Ξ a, P (f a)) (b : B) : P b := right_inv f b β–Έ g (f⁻¹ b) definition equiv_rect' (f : A ≃ B) (P : A β†’ B β†’ Type) (g : Ξ b, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a β–Έ g (f a) definition equiv_rect_comp (f : A ≃ B) (P : B β†’ Type) (df : Ξ  (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) = df x := calc equiv_rect f P df (f x) = right_inv f (f x) β–Έ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) β–Έ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x β–Έ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apd df (left_inv f x)) end section variables {A : Type} {B C : A β†’ Type} (f : Ξ {a}, B a ≃ C a) {g : A β†’ A} {g' : A β†’ A} (h : Ξ {a}, B (g' a) β†’ B (g a)) (h' : Ξ {a}, C (g' a) β†’ C (g a)) definition inv_commute (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) := inv_commute' @f @h @h' p c definition fun_commute_of_inv_commute (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c)) {a : A} (b : B (g' a)) : f (h b) = h' (f b) := fun_commute_of_inv_commute' @f @h @h' p b end infixl ` ⬝pe `:75 := equiv_of_equiv_of_eq infixl ` ⬝ep `:75 := equiv_of_eq_of_equiv end equiv open equiv namespace is_equiv definition is_equiv_of_equiv_of_homotopy [constructor] {A B : Type} (f : A ≃ B) {f' : A β†’ B} (Hty : f ~ f') : is_equiv f' := homotopy_closed f Hty end is_equiv export [unfold] equiv export [unfold] is_equiv
ccd6564ccaf41deb756f544879a1b40ba4dfe3d2
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/set/intervals/image_preimage.lean
b81dd58a02b6061dbd9a3a405127551a5662e8aa
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,068
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, Patrick Massot -/ import data.set.intervals.basic import data.equiv.mul_add import algebra.pointwise /-! # (Pre)images of intervals In this file we prove a bunch of trivial lemmas like β€œif we add `a` to all points of `[b, c]`, then we get `[a + b, a + c]`”. For the functions `x ↦ x Β± a`, `x ↦ a Β± x`, and `x ↦ -x` we prove lemmas about preimages and images of all intervals. We also prove a few lemmas about images under `x ↦ a * x`, `x ↦ x * a` and `x ↦ x⁻¹`. -/ universe u namespace set section has_exists_add_of_le /-! The lemmas in this section state that addition maps intervals bijectively. The typeclass `has_exists_add_of_le` is defined specifically to make them work when combined with `ordered_cancel_add_comm_monoid`; the lemmas below therefore apply to all `ordered_add_comm_group`, but also to `β„•` and `ℝβ‰₯0`, which are not groups. TODO : move as much as possible in this file to the setting of this weaker typeclass. -/ variables {Ξ± : Type u} [ordered_cancel_add_comm_monoid Ξ±] [has_exists_add_of_le Ξ±] (a b d : Ξ±) lemma Icc_add_bij : bij_on (+d) (Icc a b) (Icc (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_le_add_right h.1 _, add_le_add_right h.2 _⟩, Ξ» _ _ _ _ h, add_right_cancel h, Ξ» _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1, rw [mem_Icc, add_right_comm, add_le_add_iff_right, add_le_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ioo_add_bij : bij_on (+d) (Ioo a b) (Ioo (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_lt_add_right h.1 _, add_lt_add_right h.2 _⟩, Ξ» _ _ _ _ h, add_right_cancel h, Ξ» _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1.le, rw [mem_Ioo, add_right_comm, add_lt_add_iff_right, add_lt_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ioc_add_bij : bij_on (+d) (Ioc a b) (Ioc (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_lt_add_right h.1 _, add_le_add_right h.2 _⟩, Ξ» _ _ _ _ h, add_right_cancel h, Ξ» _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1.le, rw [mem_Ioc, add_right_comm, add_lt_add_iff_right, add_le_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ico_add_bij : bij_on (+d) (Ico a b) (Ico (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_le_add_right h.1 _, add_lt_add_right h.2 _⟩, Ξ» _ _ _ _ h, add_right_cancel h, Ξ» _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1, rw [mem_Ico, add_right_comm, add_le_add_iff_right, add_lt_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ici_add_bij : bij_on (+d) (Ici a) (Ici (a + d)) := begin refine ⟨λ x h, add_le_add_right (mem_Ici.mp h) _, Ξ» _ _ _ _ h, add_right_cancel h, Ξ» _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le (mem_Ici.mp h), rw [mem_Ici, add_right_comm, add_le_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ioi_add_bij : bij_on (+d) (Ioi a) (Ioi (a + d)) := begin refine ⟨λ x h, add_lt_add_right (mem_Ioi.mp h) _, Ξ» _ _ _ _ h, add_right_cancel h, Ξ» _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le (mem_Ioi.mp h).le, rw [mem_Ioi, add_right_comm, add_lt_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end end has_exists_add_of_le section ordered_add_comm_group variables {G : Type u} [ordered_add_comm_group G] (a b c : G) /-! ### Preimages under `x ↦ a + x` -/ @[simp] lemma preimage_const_add_Ici : (Ξ» x, a + x) ⁻¹' (Ici b) = Ici (b - a) := ext $ Ξ» x, sub_le_iff_le_add'.symm @[simp] lemma preimage_const_add_Ioi : (Ξ» x, a + x) ⁻¹' (Ioi b) = Ioi (b - a) := ext $ Ξ» x, sub_lt_iff_lt_add'.symm @[simp] lemma preimage_const_add_Iic : (Ξ» x, a + x) ⁻¹' (Iic b) = Iic (b - a) := ext $ Ξ» x, le_sub_iff_add_le'.symm @[simp] lemma preimage_const_add_Iio : (Ξ» x, a + x) ⁻¹' (Iio b) = Iio (b - a) := ext $ Ξ» x, lt_sub_iff_add_lt'.symm @[simp] lemma preimage_const_add_Icc : (Ξ» x, a + x) ⁻¹' (Icc b c) = Icc (b - a) (c - a) := by simp [← Ici_inter_Iic] @[simp] lemma preimage_const_add_Ico : (Ξ» x, a + x) ⁻¹' (Ico b c) = Ico (b - a) (c - a) := by simp [← Ici_inter_Iio] @[simp] lemma preimage_const_add_Ioc : (Ξ» x, a + x) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_const_add_Ioo : (Ξ» x, a + x) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) := by simp [← Ioi_inter_Iio] /-! ### Preimages under `x ↦ x + a` -/ @[simp] lemma preimage_add_const_Ici : (Ξ» x, x + a) ⁻¹' (Ici b) = Ici (b - a) := ext $ Ξ» x, sub_le_iff_le_add.symm @[simp] lemma preimage_add_const_Ioi : (Ξ» x, x + a) ⁻¹' (Ioi b) = Ioi (b - a) := ext $ Ξ» x, sub_lt_iff_lt_add.symm @[simp] lemma preimage_add_const_Iic : (Ξ» x, x + a) ⁻¹' (Iic b) = Iic (b - a) := ext $ Ξ» x, le_sub_iff_add_le.symm @[simp] lemma preimage_add_const_Iio : (Ξ» x, x + a) ⁻¹' (Iio b) = Iio (b - a) := ext $ Ξ» x, lt_sub_iff_add_lt.symm @[simp] lemma preimage_add_const_Icc : (Ξ» x, x + a) ⁻¹' (Icc b c) = Icc (b - a) (c - a) := by simp [← Ici_inter_Iic] @[simp] lemma preimage_add_const_Ico : (Ξ» x, x + a) ⁻¹' (Ico b c) = Ico (b - a) (c - a) := by simp [← Ici_inter_Iio] @[simp] lemma preimage_add_const_Ioc : (Ξ» x, x + a) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_add_const_Ioo : (Ξ» x, x + a) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) := by simp [← Ioi_inter_Iio] /-! ### Preimages under `x ↦ -x` -/ @[simp] lemma preimage_neg_Ici : - Ici a = Iic (-a) := ext $ Ξ» x, le_neg @[simp] lemma preimage_neg_Iic : - Iic a = Ici (-a) := ext $ Ξ» x, neg_le @[simp] lemma preimage_neg_Ioi : - Ioi a = Iio (-a) := ext $ Ξ» x, lt_neg @[simp] lemma preimage_neg_Iio : - Iio a = Ioi (-a) := ext $ Ξ» x, neg_lt @[simp] lemma preimage_neg_Icc : - Icc a b = Icc (-b) (-a) := by simp [← Ici_inter_Iic, inter_comm] @[simp] lemma preimage_neg_Ico : - Ico a b = Ioc (-b) (-a) := by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, inter_comm] @[simp] lemma preimage_neg_Ioc : - Ioc a b = Ico (-b) (-a) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_neg_Ioo : - Ioo a b = Ioo (-b) (-a) := by simp [← Ioi_inter_Iio, inter_comm] /-! ### Preimages under `x ↦ x - a` -/ @[simp] lemma preimage_sub_const_Ici : (Ξ» x, x - a) ⁻¹' (Ici b) = Ici (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioi : (Ξ» x, x - a) ⁻¹' (Ioi b) = Ioi (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Iic : (Ξ» x, x - a) ⁻¹' (Iic b) = Iic (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Iio : (Ξ» x, x - a) ⁻¹' (Iio b) = Iio (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Icc : (Ξ» x, x - a) ⁻¹' (Icc b c) = Icc (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ico : (Ξ» x, x - a) ⁻¹' (Ico b c) = Ico (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioc : (Ξ» x, x - a) ⁻¹' (Ioc b c) = Ioc (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioo : (Ξ» x, x - a) ⁻¹' (Ioo b c) = Ioo (b + a) (c + a) := by simp [sub_eq_add_neg] /-! ### Preimages under `x ↦ a - x` -/ @[simp] lemma preimage_const_sub_Ici : (Ξ» x, a - x) ⁻¹' (Ici b) = Iic (a - b) := ext $ Ξ» x, le_sub @[simp] lemma preimage_const_sub_Iic : (Ξ» x, a - x) ⁻¹' (Iic b) = Ici (a - b) := ext $ Ξ» x, sub_le @[simp] lemma preimage_const_sub_Ioi : (Ξ» x, a - x) ⁻¹' (Ioi b) = Iio (a - b) := ext $ Ξ» x, lt_sub @[simp] lemma preimage_const_sub_Iio : (Ξ» x, a - x) ⁻¹' (Iio b) = Ioi (a - b) := ext $ Ξ» x, sub_lt @[simp] lemma preimage_const_sub_Icc : (Ξ» x, a - x) ⁻¹' (Icc b c) = Icc (a - c) (a - b) := by simp [← Ici_inter_Iic, inter_comm] @[simp] lemma preimage_const_sub_Ico : (Ξ» x, a - x) ⁻¹' (Ico b c) = Ioc (a - c) (a - b) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_const_sub_Ioc : (Ξ» x, a - x) ⁻¹' (Ioc b c) = Ico (a - c) (a - b) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_const_sub_Ioo : (Ξ» x, a - x) ⁻¹' (Ioo b c) = Ioo (a - c) (a - b) := by simp [← Ioi_inter_Iio, inter_comm] /-! ### Images under `x ↦ a + x` -/ @[simp] lemma image_const_add_Ici : (Ξ» x, a + x) '' Ici b = Ici (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Iic : (Ξ» x, a + x) '' Iic b = Iic (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Iio : (Ξ» x, a + x) '' Iio b = Iio (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Ioi : (Ξ» x, a + x) '' Ioi b = Ioi (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Icc : (Ξ» x, a + x) '' Icc b c = Icc (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_const_add_Ico : (Ξ» x, a + x) '' Ico b c = Ico (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_const_add_Ioc : (Ξ» x, a + x) '' Ioc b c = Ioc (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_const_add_Ioo : (Ξ» x, a + x) '' Ioo b c = Ioo (a + b) (a + c) := by simp [add_comm] /-! ### Images under `x ↦ x + a` -/ @[simp] lemma image_add_const_Ici : (Ξ» x, x + a) '' Ici b = Ici (a + b) := by simp [add_comm] @[simp] lemma image_add_const_Iic : (Ξ» x, x + a) '' Iic b = Iic (a + b) := by simp [add_comm] @[simp] lemma image_add_const_Iio : (Ξ» x, x + a) '' Iio b = Iio (a + b) := by simp [add_comm] @[simp] lemma image_add_const_Ioi : (Ξ» x, x + a) '' Ioi b = Ioi (a + b) := by simp [add_comm] @[simp] lemma image_add_const_Icc : (Ξ» x, x + a) '' Icc b c = Icc (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_add_const_Ico : (Ξ» x, x + a) '' Ico b c = Ico (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_add_const_Ioc : (Ξ» x, x + a) '' Ioc b c = Ioc (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_add_const_Ioo : (Ξ» x, x + a) '' Ioo b c = Ioo (a + b) (a + c) := by simp [add_comm] /-! ### Images under `x ↦ -x` -/ lemma image_neg_Ici : has_neg.neg '' (Ici a) = Iic (-a) := by simp lemma image_neg_Iic : has_neg.neg '' (Iic a) = Ici (-a) := by simp lemma image_neg_Ioi : has_neg.neg '' (Ioi a) = Iio (-a) := by simp lemma image_neg_Iio : has_neg.neg '' (Iio a) = Ioi (-a) := by simp lemma image_neg_Icc : has_neg.neg '' (Icc a b) = Icc (-b) (-a) := by simp lemma image_neg_Ico : has_neg.neg '' (Ico a b) = Ioc (-b) (-a) := by simp lemma image_neg_Ioc : has_neg.neg '' (Ioc a b) = Ico (-b) (-a) := by simp lemma image_neg_Ioo : has_neg.neg '' (Ioo a b) = Ioo (-b) (-a) := by simp /-! ### Images under `x ↦ a - x` -/ @[simp] lemma image_const_sub_Ici : (Ξ» x, a - x) '' Ici b = Iic (a - b) := by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)] @[simp] lemma image_const_sub_Iic : (Ξ» x, a - x) '' Iic b = Ici (a - b) := by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)] @[simp] lemma image_const_sub_Ioi : (Ξ» x, a - x) '' Ioi b = Iio (a - b) := by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)] @[simp] lemma image_const_sub_Iio : (Ξ» x, a - x) '' Iio b = Ioi (a - b) := by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)] @[simp] lemma image_const_sub_Icc : (Ξ» x, a - x) '' Icc b c = Icc (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)] @[simp] lemma image_const_sub_Ico : (Ξ» x, a - x) '' Ico b c = Ioc (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)] @[simp] lemma image_const_sub_Ioc : (Ξ» x, a - x) '' Ioc b c = Ico (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)] @[simp] lemma image_const_sub_Ioo : (Ξ» x, a - x) '' Ioo b c = Ioo (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)] /-! ### Images under `x ↦ x - a` -/ @[simp] lemma image_sub_const_Ici : (Ξ» x, x - a) '' Ici b = Ici (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Iic : (Ξ» x, x - a) '' Iic b = Iic (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioi : (Ξ» x, x - a) '' Ioi b = Ioi (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Iio : (Ξ» x, x - a) '' Iio b = Iio (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Icc : (Ξ» x, x - a) '' Icc b c = Icc (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ico : (Ξ» x, x - a) '' Ico b c = Ico (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioc : (Ξ» x, x - a) '' Ioc b c = Ioc (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioo : (Ξ» x, x - a) '' Ioo b c = Ioo (b - a) (c - a) := by simp [sub_eq_neg_add] /-! ### Bijections -/ lemma Iic_add_bij : bij_on (+a) (Iic b) (Iic (b + a)) := begin refine ⟨λ x h, add_le_add_right (mem_Iic.mp h) _, Ξ» _ _ _ _ h, add_right_cancel h, Ξ» _ h, _⟩, simpa [add_comm a] using h, end lemma Iio_add_bij : bij_on (+a) (Iio b) (Iio (b + a)) := begin refine ⟨λ x h, add_lt_add_right (mem_Iio.mp h) _, Ξ» _ _ _ _ h, add_right_cancel h, Ξ» _ h, _⟩, simpa [add_comm a] using h, end end ordered_add_comm_group /-! ### Multiplication and inverse in a field -/ section linear_ordered_field variables {k : Type u} [linear_ordered_field k] @[simp] lemma preimage_mul_const_Iio (a : k) {c : k} (h : 0 < c) : (Ξ» x, x * c) ⁻¹' (Iio a) = Iio (a / c) := ext $ Ξ» x, (lt_div_iff h).symm @[simp] lemma preimage_mul_const_Ioi (a : k) {c : k} (h : 0 < c) : (Ξ» x, x * c) ⁻¹' (Ioi a) = Ioi (a / c) := ext $ Ξ» x, (div_lt_iff h).symm @[simp] lemma preimage_mul_const_Iic (a : k) {c : k} (h : 0 < c) : (Ξ» x, x * c) ⁻¹' (Iic a) = Iic (a / c) := ext $ Ξ» x, (le_div_iff h).symm @[simp] lemma preimage_mul_const_Ici (a : k) {c : k} (h : 0 < c) : (Ξ» x, x * c) ⁻¹' (Ici a) = Ici (a / c) := ext $ Ξ» x, (div_le_iff h).symm @[simp] lemma preimage_mul_const_Ioo (a b : k) {c : k} (h : 0 < c) : (Ξ» x, x * c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) := by simp [← Ioi_inter_Iio, h] @[simp] lemma preimage_mul_const_Ioc (a b : k) {c : k} (h : 0 < c) : (Ξ» x, x * c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) := by simp [← Ioi_inter_Iic, h] @[simp] lemma preimage_mul_const_Ico (a b : k) {c : k} (h : 0 < c) : (Ξ» x, x * c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) := by simp [← Ici_inter_Iio, h] @[simp] lemma preimage_mul_const_Icc (a b : k) {c : k} (h : 0 < c) : (Ξ» x, x * c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) := by simp [← Ici_inter_Iic, h] @[simp] lemma preimage_mul_const_Iio_of_neg (a : k) {c : k} (h : c < 0) : (Ξ» x, x * c) ⁻¹' (Iio a) = Ioi (a / c) := ext $ Ξ» x, (div_lt_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ioi_of_neg (a : k) {c : k} (h : c < 0) : (Ξ» x, x * c) ⁻¹' (Ioi a) = Iio (a / c) := ext $ Ξ» x, (lt_div_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Iic_of_neg (a : k) {c : k} (h : c < 0) : (Ξ» x, x * c) ⁻¹' (Iic a) = Ici (a / c) := ext $ Ξ» x, (div_le_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ici_of_neg (a : k) {c : k} (h : c < 0) : (Ξ» x, x * c) ⁻¹' (Ici a) = Iic (a / c) := ext $ Ξ» x, (le_div_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ioo_of_neg (a b : k) {c : k} (h : c < 0) : (Ξ» x, x * c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) := by simp [← Ioi_inter_Iio, h, inter_comm] @[simp] lemma preimage_mul_const_Ioc_of_neg (a b : k) {c : k} (h : c < 0) : (Ξ» x, x * c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, h, inter_comm] @[simp] lemma preimage_mul_const_Ico_of_neg (a b : k) {c : k} (h : c < 0) : (Ξ» x, x * c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) := by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, h, inter_comm] @[simp] lemma preimage_mul_const_Icc_of_neg (a b : k) {c : k} (h : c < 0) : (Ξ» x, x * c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) := by simp [← Ici_inter_Iic, h, inter_comm] @[simp] lemma preimage_const_mul_Iio (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Iio a) = Iio (a / c) := ext $ Ξ» x, (lt_div_iff' h).symm @[simp] lemma preimage_const_mul_Ioi (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ioi a) = Ioi (a / c) := ext $ Ξ» x, (div_lt_iff' h).symm @[simp] lemma preimage_const_mul_Iic (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Iic a) = Iic (a / c) := ext $ Ξ» x, (le_div_iff' h).symm @[simp] lemma preimage_const_mul_Ici (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ici a) = Ici (a / c) := ext $ Ξ» x, (div_le_iff' h).symm @[simp] lemma preimage_const_mul_Ioo (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) := by simp [← Ioi_inter_Iio, h] @[simp] lemma preimage_const_mul_Ioc (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) := by simp [← Ioi_inter_Iic, h] @[simp] lemma preimage_const_mul_Ico (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) := by simp [← Ici_inter_Iio, h] @[simp] lemma preimage_const_mul_Icc (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) := by simp [← Ici_inter_Iic, h] @[simp] lemma preimage_const_mul_Iio_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Iio a) = Ioi (a / c) := by simpa only [mul_comm] using preimage_mul_const_Iio_of_neg a h @[simp] lemma preimage_const_mul_Ioi_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ioi a) = Iio (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioi_of_neg a h @[simp] lemma preimage_const_mul_Iic_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Iic a) = Ici (a / c) := by simpa only [mul_comm] using preimage_mul_const_Iic_of_neg a h @[simp] lemma preimage_const_mul_Ici_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ici a) = Iic (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ici_of_neg a h @[simp] lemma preimage_const_mul_Ioo_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioo_of_neg a b h @[simp] lemma preimage_const_mul_Ioc_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioc_of_neg a b h @[simp] lemma preimage_const_mul_Ico_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ico_of_neg a b h @[simp] lemma preimage_const_mul_Icc_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Icc_of_neg a b h lemma image_mul_right_Icc' (a b : k) {c : k} (h : 0 < c) : (Ξ» x, x * c) '' Icc a b = Icc (a * c) (b * c) := begin refine ((units.mk0 c (ne_of_gt h)).mul_right.image_eq_preimage _).trans _, simp [h, division_def] end lemma image_mul_right_Icc {a b c : k} (hab : a ≀ b) (hc : 0 ≀ c) : (Ξ» x, x * c) '' Icc a b = Icc (a * c) (b * c) := begin cases eq_or_lt_of_le hc, { subst c, simp [(nonempty_Icc.2 hab).image_const] }, exact image_mul_right_Icc' a b β€Ή0 < cβ€Ί end lemma image_mul_left_Icc' {a : k} (h : 0 < a) (b c : k) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc' b c h using 1; simp only [mul_comm _ a] } lemma image_mul_left_Icc {a b c : k} (ha : 0 ≀ a) (hbc : b ≀ c) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc hbc ha using 1; simp only [mul_comm _ a] } /-- The image under `inv` of `Ioo 0 a` is `Ioi a⁻¹`. -/ lemma image_inv_Ioo_0_left {a : k} (ha : 0 < a) : has_inv.inv '' Ioo 0 a = Ioi a⁻¹ := begin ext x, split, { rintros ⟨y, ⟨hy0, hya⟩, hyx⟩, exact hyx β–Έ (inv_lt_inv ha hy0).2 hya }, { exact Ξ» h, ⟨x⁻¹, ⟨inv_pos.2 (lt_trans (inv_pos.2 ha) h), (inv_lt ha (lt_trans (inv_pos.2 ha) h)).1 h⟩, inv_inv' x⟩ } end end linear_ordered_field end set
1c659ffdee1bccfd1ec088b83054de288dfdec29
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/09_Type_Classes.org.9.lean
319e5770e79f5e938c921dd0bf2bbdd5d2abf201
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
809
lean
import standard import data.prod namespace hide inductive inhabited [class] (A : Type) : Type := mk : A β†’ inhabited A definition Prop.is_inhabited [instance] : inhabited Prop := inhabited.mk true definition bool.is_inhabited [instance] : inhabited bool := inhabited.mk bool.tt definition nat.is_inhabited [instance] : inhabited nat := inhabited.mk nat.zero definition unit.is_inhabited [instance] : inhabited unit := inhabited.mk unit.star definition default (A : Type) [H : inhabited A] : A := inhabited.rec (Ξ» a, a) H definition arbitrary [irreducible] (A : Type) [H : inhabited A] : A := inhabited.rec (Ξ» a, a) H -- BEGIN definition prod.is_inhabited [instance] {A B : Type} [H1 : inhabited A] [H2 : inhabited B] : inhabited (prod A B) := inhabited.mk ((default A, default B)) -- END end hide
a34b6743abf37f6a4c9cfc4b7d8f45a4fda3253a
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/obtain.lean
4f5565439dedacc93cacdc553edf21b4f5b1cb93
[ "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
680
lean
new_frontend macro "obtain " p:term " from " d:term "; " body:term : term => `(match $d:term with | $p:term => $body:term) theorem tst1 {p q r} (h : p ∧ q ∧ r) : q ∧ p ∧ r := match h with | ⟨h₁, ⟨hβ‚‚, hβ‚ƒβŸ©βŸ© => ⟨hβ‚‚, ⟨h₁, hβ‚ƒβŸ©βŸ© theorem tst2 {p q r} (h : p ∧ q ∧ r) : q ∧ p ∧ r := obtain ⟨h₁, ⟨hβ‚‚, hβ‚ƒβŸ©βŸ© from h; ⟨hβ‚‚, ⟨h₁, hβ‚ƒβŸ©βŸ© macro "obtain " p:term " from " d:term : tactic => `(tactic| match $d:term with | $p:term => ?hole) theorem tst3 {p q r} (h : p ∧ q ∧ r) : q ∧ p ∧ r := by obtain ⟨h₁, ⟨hβ‚‚, hβ‚ƒβŸ©βŸ© from h apply And.intro assumption apply And.intro assumption assumption
743f09abddd8db037cae7c564dc8883fe322c0f1
49bd2218ae088932d847f9030c8dbff1c5607bb7
/src/topology/basic.lean
be5a4e66154505c69838d954f39aac8494d2d6ce
[ "Apache-2.0" ]
permissive
FredericLeRoux/mathlib
e8f696421dd3e4edc8c7edb3369421c8463d7bac
3645bf8fb426757e0a20af110d1fdded281d286e
refs/heads/master
1,607,062,870,732
1,578,513,186,000
1,578,513,186,000
231,653,181
0
0
Apache-2.0
1,578,080,327,000
1,578,080,326,000
null
UTF-8
Lean
false
false
35,497
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, Jeremy Avigad -/ import order.filter /-! # Basic theory of topological spaces. The main definition is the type class `topological space Ξ±` which endows a type `Ξ±` with a topology. Then `set Ξ±` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and `frontier`. Each point `x` of `Ξ±` gets a neighborhood filter `𝓝 x`. This file also defines locally finite families of subsets of `Ξ±`. For topological spaces `Ξ±` and `Ξ²`, a function `f : Ξ± β†’ Ξ²` and a point `a : Ξ±`, `continuous_at f a` means `f` is continuous at `a`, and global continuity is `continuous f`. There is also a version of continuity `pcontinuous` for partially defined functions. ## Implementation notes Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in `docs/theories/topology.md`. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] ## Tags topological space, interior, closure, frontier, neighborhood, continuity, continuous function -/ open set filter lattice classical open_locale classical universes u v w /-- A topology on `Ξ±`. -/ structure topological_space (Ξ± : Type u) := (is_open : set Ξ± β†’ Prop) (is_open_univ : is_open univ) (is_open_inter : βˆ€s t, is_open s β†’ is_open t β†’ is_open (s ∩ t)) (is_open_sUnion : βˆ€s, (βˆ€t∈s, is_open t) β†’ is_open (⋃₀ s)) attribute [class] topological_space section topological_space variables {Ξ± : Type u} {Ξ² : Type v} {ΞΉ : Sort w} {a : Ξ±} {s s₁ sβ‚‚ : set Ξ±} {p p₁ pβ‚‚ : Ξ± β†’ Prop} @[ext] lemma topological_space_eq : βˆ€ {f g : topological_space Ξ±}, f.is_open = g.is_open β†’ f = g | ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl section variables [t : topological_space Ξ±] include t /-- `is_open s` means that `s` is open in the ambient topological space on `Ξ±` -/ def is_open (s : set Ξ±) : Prop := topological_space.is_open t s @[simp] lemma is_open_univ : is_open (univ : set Ξ±) := topological_space.is_open_univ t lemma is_open_inter (h₁ : is_open s₁) (hβ‚‚ : is_open sβ‚‚) : is_open (s₁ ∩ sβ‚‚) := topological_space.is_open_inter t s₁ sβ‚‚ h₁ hβ‚‚ lemma is_open_sUnion {s : set (set Ξ±)} (h : βˆ€t ∈ s, is_open t) : is_open (⋃₀ s) := topological_space.is_open_sUnion t s h end lemma is_open_fold {s : set Ξ±} {t : topological_space Ξ±} : t.is_open s = @is_open Ξ± t s := rfl variables [topological_space Ξ±] lemma is_open_Union {f : ΞΉ β†’ set Ξ±} (h : βˆ€i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i lemma is_open_bUnion {s : set Ξ²} {f : Ξ² β†’ set Ξ±} (h : βˆ€i∈s, is_open (f i)) : is_open (⋃i∈s, f i) := is_open_Union $ assume i, is_open_Union $ assume hi, h i hi lemma is_open_union (h₁ : is_open s₁) (hβ‚‚ : is_open sβ‚‚) : is_open (s₁ βˆͺ sβ‚‚) := by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨hβ‚‚, hβ‚βŸ©) @[simp] lemma is_open_empty : is_open (βˆ… : set Ξ±) := by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim) lemma is_open_sInter {s : set (set Ξ±)} (hs : finite s) : (βˆ€t ∈ s, is_open t) β†’ is_open (β‹‚β‚€ s) := finite.induction_on hs (Ξ» _, by rw sInter_empty; exact is_open_univ) $ Ξ» a s has hs ih h, by rw sInter_insert; exact is_open_inter (h _ $ mem_insert _ _) (ih $ Ξ» t, h t ∘ mem_insert_of_mem _) lemma is_open_bInter {s : set Ξ²} {f : Ξ² β†’ set Ξ±} (hs : finite s) : (βˆ€i∈s, is_open (f i)) β†’ is_open (β‹‚i∈s, f i) := finite.induction_on hs (Ξ» _, by rw bInter_empty; exact is_open_univ) (Ξ» a s has hs ih h, by rw bInter_insert; exact is_open_inter (h a (mem_insert _ _)) (ih (Ξ» i hi, h i (mem_insert_of_mem _ hi)))) lemma is_open_Inter [fintype Ξ²] {s : Ξ² β†’ set Ξ±} (h : βˆ€ i, is_open (s i)) : is_open (β‹‚ i, s i) := suffices is_open (β‹‚ (i : Ξ²) (hi : i ∈ @univ Ξ²), s i), by simpa, is_open_bInter finite_univ (Ξ» i _, h i) lemma is_open_Inter_prop {p : Prop} {s : p β†’ set Ξ±} (h : βˆ€ h : p, is_open (s h)) : is_open (Inter s) := by by_cases p; simp * lemma is_open_const {p : Prop} : is_open {a : Ξ± | p} := by_cases (assume : p, begin simp only [this]; exact is_open_univ end) (assume : Β¬ p, begin simp only [this]; exact is_open_empty end) lemma is_open_and : is_open {a | p₁ a} β†’ is_open {a | pβ‚‚ a} β†’ is_open {a | p₁ a ∧ pβ‚‚ a} := is_open_inter /-- A set is closed if its complement is open -/ def is_closed (s : set Ξ±) : Prop := is_open (-s) @[simp] lemma is_closed_empty : is_closed (βˆ… : set Ξ±) := by unfold is_closed; rw compl_empty; exact is_open_univ @[simp] lemma is_closed_univ : is_closed (univ : set Ξ±) := by unfold is_closed; rw compl_univ; exact is_open_empty lemma is_closed_union : is_closed s₁ β†’ is_closed sβ‚‚ β†’ is_closed (s₁ βˆͺ sβ‚‚) := Ξ» h₁ hβ‚‚, by unfold is_closed; rw compl_union; exact is_open_inter h₁ hβ‚‚ lemma is_closed_sInter {s : set (set Ξ±)} : (βˆ€t ∈ s, is_closed t) β†’ is_closed (β‹‚β‚€ s) := by simp only [is_closed, compl_sInter, sUnion_image]; exact assume h, is_open_Union $ assume t, is_open_Union $ assume ht, h t ht lemma is_closed_Inter {f : ΞΉ β†’ set Ξ±} (h : βˆ€i, is_closed (f i)) : is_closed (β‹‚i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq β–Έ h i @[simp] lemma is_open_compl_iff {s : set Ξ±} : is_open (-s) ↔ is_closed s := iff.rfl @[simp] lemma is_closed_compl_iff {s : set Ξ±} : is_closed (-s) ↔ is_open s := by rw [←is_open_compl_iff, compl_compl] lemma is_open_diff {s t : set Ξ±} (h₁ : is_open s) (hβ‚‚ : is_closed t) : is_open (s \ t) := is_open_inter h₁ $ is_open_compl_iff.mpr hβ‚‚ lemma is_closed_inter (h₁ : is_closed s₁) (hβ‚‚ : is_closed sβ‚‚) : is_closed (s₁ ∩ sβ‚‚) := by rw [is_closed, compl_inter]; exact is_open_union h₁ hβ‚‚ lemma is_closed_bUnion {s : set Ξ²} {f : Ξ² β†’ set Ξ±} (hs : finite s) : (βˆ€i∈s, is_closed (f i)) β†’ is_closed (⋃i∈s, f i) := finite.induction_on hs (Ξ» _, by rw bUnion_empty; exact is_closed_empty) (Ξ» a s has hs ih h, by rw bUnion_insert; exact is_closed_union (h a (mem_insert _ _)) (ih (Ξ» i hi, h i (mem_insert_of_mem _ hi)))) lemma is_closed_Union [fintype Ξ²] {s : Ξ² β†’ set Ξ±} (h : βˆ€ i, is_closed (s i)) : is_closed (Union s) := suffices is_closed (⋃ (i : Ξ²) (hi : i ∈ @univ Ξ²), s i), by convert this; simp [set.ext_iff], is_closed_bUnion finite_univ (Ξ» i _, h i) lemma is_closed_Union_prop {p : Prop} {s : p β†’ set Ξ±} (h : βˆ€ h : p, is_closed (s h)) : is_closed (Union s) := by by_cases p; simp * lemma is_closed_imp {p q : Ξ± β†’ Prop} (hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x β†’ q x} := have {x | p x β†’ q x} = (- {x | p x}) βˆͺ {x | q x}, from set.ext $ Ξ» x, imp_iff_not_or, by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq lemma is_open_neg : is_closed {a | p a} β†’ is_open {a | Β¬ p a} := is_open_compl_iff.mpr /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : set Ξ±) : set Ξ± := ⋃₀ {t | is_open t ∧ t βŠ† s} lemma mem_interior {s : set Ξ±} {x : Ξ±} : x ∈ interior s ↔ βˆƒ t βŠ† s, is_open t ∧ x ∈ t := by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm] @[simp] lemma is_open_interior {s : set Ξ±} : is_open (interior s) := is_open_sUnion $ assume t ⟨h₁, hβ‚‚βŸ©, h₁ lemma interior_subset {s : set Ξ±} : interior s βŠ† s := sUnion_subset $ assume t ⟨h₁, hβ‚‚βŸ©, hβ‚‚ lemma interior_maximal {s t : set Ξ±} (h₁ : t βŠ† s) (hβ‚‚ : is_open t) : t βŠ† interior s := subset_sUnion_of_mem ⟨hβ‚‚, hβ‚βŸ© lemma interior_eq_of_open {s : set Ξ±} (h : is_open s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_open {s : set Ξ±} : interior s = s ↔ is_open s := ⟨assume h, h β–Έ is_open_interior, interior_eq_of_open⟩ lemma subset_interior_iff_open {s : set Ξ±} : s βŠ† interior s ↔ is_open s := by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and] lemma subset_interior_iff_subset_of_open {s t : set Ξ±} (h₁ : is_open s) : s βŠ† interior t ↔ s βŠ† t := ⟨assume h, subset.trans h interior_subset, assume hβ‚‚, interior_maximal hβ‚‚ hβ‚βŸ© lemma interior_mono {s t : set Ξ±} (h : s βŠ† t) : interior s βŠ† interior t := interior_maximal (subset.trans interior_subset h) is_open_interior @[simp] lemma interior_empty : interior (βˆ… : set Ξ±) = βˆ… := interior_eq_of_open is_open_empty @[simp] lemma interior_univ : interior (univ : set Ξ±) = univ := interior_eq_of_open is_open_univ @[simp] lemma interior_interior {s : set Ξ±} : interior (interior s) = interior s := interior_eq_of_open is_open_interior @[simp] lemma interior_inter {s t : set Ξ±} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open_inter is_open_interior is_open_interior) lemma interior_union_is_closed_of_interior_empty {s t : set Ξ±} (h₁ : is_closed s) (hβ‚‚ : interior t = βˆ…) : interior (s βˆͺ t) = interior s := have interior (s βˆͺ t) βŠ† s, from assume x ⟨u, ⟨(hu₁ : is_open u), (huβ‚‚ : u βŠ† s βˆͺ t)⟩, (hx₁ : x ∈ u)⟩, classical.by_contradiction $ assume hxβ‚‚ : x βˆ‰ s, have u \ s βŠ† t, from assume x ⟨h₁, hβ‚‚βŸ©, or.resolve_left (huβ‚‚ h₁) hβ‚‚, have u \ s βŠ† interior t, by rwa subset_interior_iff_subset_of_open (is_open_diff hu₁ h₁), have u \ s βŠ† βˆ…, by rwa hβ‚‚ at this, this ⟨hx₁, hxβ‚‚βŸ©, subset.antisymm (interior_maximal this is_open_interior) (interior_mono $ subset_union_left _ _) lemma is_open_iff_forall_mem_open : is_open s ↔ βˆ€ x ∈ s, βˆƒ t βŠ† s, is_open t ∧ x ∈ t := by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior] /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : set Ξ±) : set Ξ± := β‹‚β‚€ {t | is_closed t ∧ s βŠ† t} @[simp] lemma is_closed_closure {s : set Ξ±} : is_closed (closure s) := is_closed_sInter $ assume t ⟨h₁, hβ‚‚βŸ©, h₁ lemma subset_closure {s : set Ξ±} : s βŠ† closure s := subset_sInter $ assume t ⟨h₁, hβ‚‚βŸ©, hβ‚‚ lemma closure_minimal {s t : set Ξ±} (h₁ : s βŠ† t) (hβ‚‚ : is_closed t) : closure s βŠ† t := sInter_subset_of_mem ⟨hβ‚‚, hβ‚βŸ© lemma closure_eq_of_is_closed {s : set Ξ±} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma closure_eq_iff_is_closed {s : set Ξ±} : closure s = s ↔ is_closed s := ⟨assume h, h β–Έ is_closed_closure, closure_eq_of_is_closed⟩ lemma closure_subset_iff_subset_of_is_closed {s t : set Ξ±} (h₁ : is_closed t) : closure s βŠ† t ↔ s βŠ† t := ⟨subset.trans subset_closure, assume h, closure_minimal h hβ‚βŸ© lemma closure_mono {s t : set Ξ±} (h : s βŠ† t) : closure s βŠ† closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure lemma monotone_closure (Ξ± : Type*) [topological_space Ξ±] : monotone (@closure Ξ± _) := Ξ» _ _, closure_mono lemma closure_inter_subset_inter_closure (s t : set Ξ±) : closure (s ∩ t) βŠ† closure s ∩ closure t := (monotone_closure Ξ±).map_inf_le s t lemma is_closed_of_closure_subset {s : set Ξ±} (h : closure s βŠ† s) : is_closed s := by rw subset.antisymm subset_closure h; exact is_closed_closure @[simp] lemma closure_empty : closure (βˆ… : set Ξ±) = βˆ… := closure_eq_of_is_closed is_closed_empty lemma closure_empty_iff (s : set Ξ±) : closure s = βˆ… ↔ s = βˆ… := begin split; intro h, { rw set.eq_empty_iff_forall_not_mem, intros x H, simpa only [h] using subset_closure H }, { exact (eq.symm h) β–Έ closure_empty }, end @[simp] lemma closure_univ : closure (univ : set Ξ±) = univ := closure_eq_of_is_closed is_closed_univ @[simp] lemma closure_closure {s : set Ξ±} : closure (closure s) = closure s := closure_eq_of_is_closed is_closed_closure @[simp] lemma closure_union {s t : set Ξ±} : closure (s βˆͺ t) = closure s βˆͺ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed_union is_closed_closure is_closed_closure) ((monotone_closure Ξ±).le_map_sup s t) lemma interior_subset_closure {s : set Ξ±} : interior s βŠ† closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set Ξ±} : closure s = - interior (- s) := begin unfold interior closure is_closed, rw [compl_sUnion, compl_image_set_of], simp only [compl_subset_compl] end @[simp] lemma interior_compl {s : set Ξ±} : interior (- s) = - closure s := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl {s : set Ξ±} : closure (- s) = - interior s := by simp [closure_eq_compl_interior_compl] theorem mem_closure_iff {s : set Ξ±} {a : Ξ±} : a ∈ closure s ↔ βˆ€ o, is_open o β†’ a ∈ o β†’ o ∩ s β‰  βˆ… := ⟨λ h o oo ao os, have s βŠ† -o, from Ξ» x xs xo, @ne_empty_of_mem Ξ± (o∩s) x ⟨xo, xs⟩ os, closure_minimal this (is_closed_compl_iff.2 oo) h ao, Ξ» H c ⟨h₁, hβ‚‚βŸ©, classical.by_contradiction $ Ξ» nc, let ⟨x, hc, hs⟩ := exists_mem_of_ne_empty (H _ h₁ nc) in hc (hβ‚‚ hs)⟩ lemma dense_iff_inter_open {s : set Ξ±} : closure s = univ ↔ βˆ€ U, is_open U β†’ U β‰  βˆ… β†’ U ∩ s β‰  βˆ… := begin split ; intro h, { intros U U_op U_ne, cases exists_mem_of_ne_empty U_ne with x x_in, exact mem_closure_iff.1 (by simp only [h]) U U_op x_in }, { apply eq_univ_of_forall, intro x, rw mem_closure_iff, intros U U_op x_in, exact h U U_op (ne_empty_of_mem x_in) }, end lemma dense_of_subset_dense {s₁ sβ‚‚ : set Ξ±} (h : s₁ βŠ† sβ‚‚) (hd : closure s₁ = univ) : closure sβ‚‚ = univ := by { rw [← univ_subset_iff, ← hd], exact closure_mono h } /-- The frontier of a set is the set of points between the closure and interior. -/ def frontier (s : set Ξ±) : set Ξ± := closure s \ interior s lemma frontier_eq_closure_inter_closure {s : set Ξ±} : frontier s = closure s ∩ closure (- s) := by rw [closure_compl, frontier, diff_eq] /-- The complement of a set has the same frontier as the original set. -/ @[simp] lemma frontier_compl (s : set Ξ±) : frontier (-s) = frontier s := by simp only [frontier_eq_closure_inter_closure, lattice.neg_neg, inter_comm] lemma frontier_inter_subset (s t : set Ξ±) : frontier (s ∩ t) βŠ† (frontier s ∩ closure t) βˆͺ (closure s ∩ frontier t) := begin simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union], convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t), simp only [inter_distrib_left, inter_distrib_right, inter_assoc], congr' 2, apply inter_comm end lemma frontier_union_subset (s t : set Ξ±) : frontier (s βˆͺ t) βŠ† (frontier s ∩ closure (-t)) βˆͺ (closure (-s) ∩ frontier t) := by simpa only [frontier_compl, (compl_union _ _).symm] using frontier_inter_subset (-s) (-t) lemma is_closed.frontier_eq {s : set Ξ±} (hs : is_closed s) : frontier s = s \ interior s := by rw [frontier, closure_eq_of_is_closed hs] lemma is_open.frontier_eq {s : set Ξ±} (hs : is_open s) : frontier s = closure s \ s := by rw [frontier, interior_eq_of_open hs] /-- The frontier of a set is closed. -/ lemma is_closed_frontier {s : set Ξ±} : is_closed (frontier s) := by rw frontier_eq_closure_inter_closure; exact is_closed_inter is_closed_closure is_closed_closure /-- The frontier of a set has no interior point. -/ lemma interior_frontier {s : set Ξ±} (h : is_closed s) : interior (frontier s) = βˆ… := begin have A : frontier s = s \ interior s, from h.frontier_eq, have B : interior (frontier s) βŠ† interior s, by rw A; exact interior_mono (diff_subset _ _), have C : interior (frontier s) βŠ† frontier s := interior_subset, have : interior (frontier s) βŠ† (interior s) ∩ (s \ interior s) := subset_inter B (by simpa [A] using C), rwa [inter_diff_self, subset_empty_iff] at this, end /-- neighbourhood filter -/ def nhds (a : Ξ±) : filter Ξ± := (β¨… s ∈ {s : set Ξ± | a ∈ s ∧ is_open s}, principal s) localized "notation `𝓝` := nhds" in topological_space lemma nhds_def (a : Ξ±) : 𝓝 a = (β¨… s ∈ {s : set Ξ± | a ∈ s ∧ is_open s}, principal s) := rfl lemma le_nhds_iff {f a} : f ≀ 𝓝 a ↔ βˆ€ s : set Ξ±, a ∈ s β†’ is_open s β†’ s ∈ f := by simp [nhds_def] lemma nhds_le_of_le {f a} {s : set Ξ±} (h : a ∈ s) (o : is_open s) (sf : principal s ≀ f) : 𝓝 a ≀ f := by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf) lemma nhds_sets {a : Ξ±} : (𝓝 a).sets = {s | βˆƒtβŠ†s, is_open t ∧ a ∈ t} := calc (𝓝 a).sets = (⋃s∈{s : set Ξ±| a ∈ s ∧ is_open s}, (principal s).sets) : binfi_sets_eq (assume x ⟨hx₁, hxβ‚‚βŸ© y ⟨hy₁, hyβ‚‚βŸ©, ⟨x ∩ y, ⟨⟨hx₁, hyβ‚βŸ©, is_open_inter hxβ‚‚ hyβ‚‚βŸ©, le_principal_iff.2 (inter_subset_left _ _), le_principal_iff.2 (inter_subset_right _ _)⟩) ⟨univ, mem_univ _, is_open_univ⟩ ... = {s | βˆƒtβŠ†s, is_open t ∧ a ∈ t} : le_antisymm (supr_le $ assume i, supr_le $ assume ⟨hi₁, hiβ‚‚βŸ© t ht, ⟨i, ht, hiβ‚‚, hiβ‚βŸ©) (assume t ⟨i, hi₁, hiβ‚‚, hiβ‚ƒβŸ©, mem_Union.2 ⟨i, mem_Union.2 ⟨⟨hi₃, hiβ‚‚βŸ©, hiβ‚βŸ©βŸ©) lemma map_nhds {a : Ξ±} {f : Ξ± β†’ Ξ²} : map f (𝓝 a) = (β¨… s ∈ {s : set Ξ± | a ∈ s ∧ is_open s}, principal (image f s)) := calc map f (𝓝 a) = (β¨… s ∈ {s : set Ξ± | a ∈ s ∧ is_open s}, map f (principal s)) : map_binfi_eq (assume x ⟨hx₁, hxβ‚‚βŸ© y ⟨hy₁, hyβ‚‚βŸ©, ⟨x ∩ y, ⟨⟨hx₁, hyβ‚βŸ©, is_open_inter hxβ‚‚ hyβ‚‚βŸ©, le_principal_iff.2 (inter_subset_left _ _), le_principal_iff.2 (inter_subset_right _ _)⟩) ⟨univ, mem_univ _, is_open_univ⟩ ... = _ : by simp only [map_principal] attribute [irreducible] nhds lemma mem_nhds_sets_iff {a : Ξ±} {s : set Ξ±} : s ∈ 𝓝 a ↔ βˆƒtβŠ†s, is_open t ∧ a ∈ t := by simp only [nhds_sets, mem_set_of_eq, exists_prop] lemma mem_of_nhds {a : Ξ±} {s : set Ξ±} : s ∈ 𝓝 a β†’ a ∈ s := Ξ» H, let ⟨t, ht, _, hs⟩ := mem_nhds_sets_iff.1 H in ht hs lemma mem_nhds_sets {a : Ξ±} {s : set Ξ±} (hs : is_open s) (ha : a ∈ s) : s ∈ 𝓝 a := mem_nhds_sets_iff.2 ⟨s, subset.refl _, hs, ha⟩ theorem all_mem_nhds (x : Ξ±) (P : set Ξ± β†’ Prop) (hP : βˆ€ s t, s βŠ† t β†’ P s β†’ P t) : (βˆ€ s ∈ 𝓝 x, P s) ↔ (βˆ€ s, is_open s β†’ x ∈ s β†’ P s) := iff.intro (Ξ» h s os xs, h s (mem_nhds_sets os xs)) (Ξ» h t, begin change t ∈ (𝓝 x).sets β†’ P t, rw nhds_sets, rintros ⟨s, hs, opens, xs⟩, exact hP _ _ hs (h s opens xs), end) theorem all_mem_nhds_filter (x : Ξ±) (f : set Ξ± β†’ set Ξ²) (hf : βˆ€ s t, s βŠ† t β†’ f s βŠ† f t) (l : filter Ξ²) : (βˆ€ s ∈ 𝓝 x, f s ∈ l) ↔ (βˆ€ s, is_open s β†’ x ∈ s β†’ f s ∈ l) := all_mem_nhds _ _ (Ξ» s t ssubt h, mem_sets_of_superset h (hf s t ssubt)) theorem rtendsto_nhds {r : rel Ξ² Ξ±} {l : filter Ξ²} {a : Ξ±} : rtendsto r l (𝓝 a) ↔ (βˆ€ s, is_open s β†’ a ∈ s β†’ r.core s ∈ l) := all_mem_nhds_filter _ _ (Ξ» s t, id) _ theorem rtendsto'_nhds {r : rel Ξ² Ξ±} {l : filter Ξ²} {a : Ξ±} : rtendsto' r l (𝓝 a) ↔ (βˆ€ s, is_open s β†’ a ∈ s β†’ r.preimage s ∈ l) := by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono } theorem ptendsto_nhds {f : Ξ² β†’. Ξ±} {l : filter Ξ²} {a : Ξ±} : ptendsto f l (𝓝 a) ↔ (βˆ€ s, is_open s β†’ a ∈ s β†’ f.core s ∈ l) := rtendsto_nhds theorem ptendsto'_nhds {f : Ξ² β†’. Ξ±} {l : filter Ξ²} {a : Ξ±} : ptendsto' f l (𝓝 a) ↔ (βˆ€ s, is_open s β†’ a ∈ s β†’ f.preimage s ∈ l) := rtendsto'_nhds theorem tendsto_nhds {f : Ξ² β†’ Ξ±} {l : filter Ξ²} {a : Ξ±} : tendsto f l (𝓝 a) ↔ (βˆ€ s, is_open s β†’ a ∈ s β†’ f ⁻¹' s ∈ l) := all_mem_nhds_filter _ _ (Ξ» s t h, preimage_mono h) _ lemma tendsto_const_nhds {a : Ξ±} {f : filter Ξ²} : tendsto (Ξ»b:Ξ², a) f (𝓝 a) := tendsto_nhds.mpr $ assume s hs ha, univ_mem_sets' $ assume _, ha lemma pure_le_nhds : pure ≀ (𝓝 : Ξ± β†’ filter Ξ±) := assume a, by rw nhds_def; exact le_infi (assume s, le_infi $ assume ⟨h₁, _⟩, principal_mono.mpr $ singleton_subset_iff.2 h₁) lemma tendsto_pure_nhds {Ξ± : Type*} [topological_space Ξ²] (f : Ξ± β†’ Ξ²) (a : Ξ±) : tendsto f (pure a) (𝓝 (f a)) := begin rw [tendsto, filter.map_pure], exact pure_le_nhds (f a) end @[simp] lemma nhds_neq_bot {a : Ξ±} : 𝓝 a β‰  βŠ₯ := assume : 𝓝 a = βŠ₯, have pure a = (βŠ₯ : filter Ξ±), from lattice.bot_unique $ this β–Έ pure_le_nhds a, pure_neq_bot this lemma interior_eq_nhds {s : set Ξ±} : interior s = {a | 𝓝 a ≀ principal s} := set.ext $ Ξ» x, by simp only [mem_interior, le_principal_iff, mem_nhds_sets_iff]; refl lemma mem_interior_iff_mem_nhds {s : set Ξ±} {a : Ξ±} : a ∈ interior s ↔ s ∈ 𝓝 a := by simp only [interior_eq_nhds, le_principal_iff]; refl lemma is_open_iff_nhds {s : set Ξ±} : is_open s ↔ βˆ€a∈s, 𝓝 a ≀ principal s := calc is_open s ↔ s βŠ† interior s : subset_interior_iff_open.symm ... ↔ (βˆ€a∈s, 𝓝 a ≀ principal s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set Ξ±} : is_open s ↔ βˆ€a∈s, s ∈ 𝓝 a := is_open_iff_nhds.trans $ forall_congr $ Ξ» _, imp_congr_right $ Ξ» _, le_principal_iff lemma closure_eq_nhds {s : set Ξ±} : closure s = {a | 𝓝 a βŠ“ principal s β‰  βŠ₯} := calc closure s = - interior (- s) : closure_eq_compl_interior_compl ... = {a | Β¬ 𝓝 a ≀ principal (-s)} : by rw [interior_eq_nhds]; refl ... = {a | 𝓝 a βŠ“ principal s β‰  βŠ₯} : set.ext $ assume a, not_congr (inf_eq_bot_iff_le_compl (show principal s βŠ” principal (-s) = ⊀, by simp only [sup_principal, union_compl_self, principal_univ]) (by simp only [inf_principal, inter_compl_self, principal_empty])).symm theorem mem_closure_iff_nhds {s : set Ξ±} {a : Ξ±} : a ∈ closure s ↔ βˆ€ t ∈ 𝓝 a, t ∩ s β‰  βˆ… := mem_closure_iff.trans ⟨λ H t ht, subset_ne_empty (inter_subset_inter_left _ interior_subset) (H _ is_open_interior (mem_interior_iff_mem_nhds.2 ht)), Ξ» H o oo ao, H _ (mem_nhds_sets oo ao)⟩ /-- `x` belongs to the closure of `s` if and only if some ultrafilter supported on `s` converges to `x`. -/ lemma mem_closure_iff_ultrafilter {s : set Ξ±} {x : Ξ±} : x ∈ closure s ↔ βˆƒ (u : ultrafilter Ξ±), s ∈ u.val ∧ u.val ≀ 𝓝 x := begin rw closure_eq_nhds, change 𝓝 x βŠ“ principal s β‰  βŠ₯ ↔ _, symmetry, convert exists_ultrafilter_iff _, ext u, rw [←le_principal_iff, inf_comm, le_inf_iff] end lemma is_closed_iff_nhds {s : set Ξ±} : is_closed s ↔ βˆ€a, 𝓝 a βŠ“ principal s β‰  βŠ₯ β†’ a ∈ s := calc is_closed s ↔ closure s = s : by rw [closure_eq_iff_is_closed] ... ↔ closure s βŠ† s : ⟨assume h, by rw h, assume h, subset.antisymm h subset_closure⟩ ... ↔ (βˆ€a, 𝓝 a βŠ“ principal s β‰  βŠ₯ β†’ a ∈ s) : by rw [closure_eq_nhds]; refl lemma closure_inter_open {s t : set Ξ±} (h : is_open s) : s ∩ closure t βŠ† closure (s ∩ t) := assume a ⟨hs, ht⟩, have s ∈ 𝓝 a, from mem_nhds_sets h hs, have 𝓝 a βŠ“ principal s = 𝓝 a, from inf_of_le_left $ by rwa le_principal_iff, have 𝓝 a βŠ“ principal (s ∩ t) β‰  βŠ₯, from calc 𝓝 a βŠ“ principal (s ∩ t) = 𝓝 a βŠ“ (principal s βŠ“ principal t) : by rw inf_principal ... = 𝓝 a βŠ“ principal t : by rw [←inf_assoc, this] ... β‰  βŠ₯ : by rw [closure_eq_nhds] at ht; assumption, by rw [closure_eq_nhds]; assumption lemma closure_diff {s t : set Ξ±} : closure s - closure t βŠ† closure (s - t) := calc closure s \ closure t = (- closure t) ∩ closure s : by simp only [diff_eq, inter_comm] ... βŠ† closure (- closure t ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure ... = closure (s \ closure t) : by simp only [diff_eq, inter_comm] ... βŠ† closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure lemma mem_of_closed_of_tendsto {f : Ξ² β†’ Ξ±} {b : filter Ξ²} {a : Ξ±} {s : set Ξ±} (hb : b β‰  βŠ₯) (hf : tendsto f b (𝓝 a)) (hs : is_closed s) (h : f ⁻¹' s ∈ b) : a ∈ s := have b.map f ≀ 𝓝 a βŠ“ principal s, from le_trans (le_inf (le_refl _) (le_principal_iff.mpr h)) (inf_le_inf hf (le_refl _)), is_closed_iff_nhds.mp hs a $ neq_bot_of_le_neq_bot (map_ne_bot hb) this lemma mem_of_closed_of_tendsto' {f : Ξ² β†’ Ξ±} {x : filter Ξ²} {a : Ξ±} {s : set Ξ±} (hf : tendsto f x (𝓝 a)) (hs : is_closed s) (h : x βŠ“ principal (f ⁻¹' s) β‰  βŠ₯) : a ∈ s := is_closed_iff_nhds.mp hs _ $ neq_bot_of_le_neq_bot (@map_ne_bot _ _ _ f h) $ le_inf (le_trans (map_mono $ inf_le_left) hf) $ le_trans (map_mono $ inf_le_right_of_le $ by simp only [comap_principal, le_principal_iff]; exact subset.refl _) (@map_comap_le _ _ _ f) lemma mem_closure_of_tendsto {f : Ξ² β†’ Ξ±} {b : filter Ξ²} {a : Ξ±} {s : set Ξ±} (hb : b β‰  βŠ₯) (hf : tendsto f b (𝓝 a)) (h : f ⁻¹' s ∈ b) : a ∈ closure s := mem_of_closed_of_tendsto hb hf (is_closed_closure) $ filter.mem_sets_of_superset h (preimage_mono subset_closure) /-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter. Then `f` tends to `a` along `l` restricted to `s` if and only it tends to `a` along `l`. -/ lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : Ξ² β†’ Ξ±} {l : filter Ξ²} {s : set Ξ²} {a : Ξ±} (h : βˆ€ x βˆ‰ s, f x = a) : tendsto f (l βŠ“ principal s) (𝓝 a) ↔ tendsto f l (𝓝 a) := begin rw [tendsto_iff_comap, tendsto_iff_comap], replace h : principal (-s) ≀ comap f (𝓝 a), { rintros U ⟨t, ht, htU⟩ x hx, have : f x ∈ t, from (h x hx).symm β–Έ mem_of_nhds ht, exact htU this }, refine ⟨λ h', _, le_trans inf_le_left⟩, have := sup_le h' h, rw [sup_inf_right, sup_principal, union_compl_self, principal_univ, inf_top_eq, sup_le_iff] at this, exact this.1 end section lim variables [inhabited Ξ±] /-- If `f` is a filter, then `lim f` is a limit of the filter, if it exists. -/ noncomputable def lim (f : filter Ξ±) : Ξ± := epsilon $ Ξ»a, f ≀ 𝓝 a lemma lim_spec {f : filter Ξ±} (h : βˆƒa, f ≀ 𝓝 a) : f ≀ 𝓝 (lim f) := epsilon_spec h end lim /- locally finite family [General Topology (Bourbaki, 1995)] -/ section locally_finite /-- A family of sets in `set Ξ±` is locally finite if at every point `x:Ξ±`, there is a neighborhood of `x` which meets only finitely many sets in the family -/ def locally_finite (f : Ξ² β†’ set Ξ±) := βˆ€x:Ξ±, βˆƒt ∈ 𝓝 x, finite {i | f i ∩ t β‰  βˆ… } lemma locally_finite_of_finite {f : Ξ² β†’ set Ξ±} (h : finite (univ : set Ξ²)) : locally_finite f := assume x, ⟨univ, univ_mem_sets, finite_subset h $ subset_univ _⟩ lemma locally_finite_subset {f₁ fβ‚‚ : Ξ² β†’ set Ξ±} (hfβ‚‚ : locally_finite fβ‚‚) (hf : βˆ€b, f₁ b βŠ† fβ‚‚ b) : locally_finite f₁ := assume a, let ⟨t, ht₁, htβ‚‚βŸ© := hfβ‚‚ a in ⟨t, ht₁, finite_subset htβ‚‚ $ assume i hi, neq_bot_of_le_neq_bot hi $ inter_subset_inter (hf i) $ subset.refl _⟩ lemma is_closed_Union_of_locally_finite {f : Ξ² β†’ set Ξ±} (h₁ : locally_finite f) (hβ‚‚ : βˆ€i, is_closed (f i)) : is_closed (⋃i, f i) := is_open_iff_nhds.mpr $ assume a, assume h : a βˆ‰ (⋃i, f i), have βˆ€i, a ∈ -f i, from assume i hi, h $ mem_Union.2 ⟨i, hi⟩, have βˆ€i, - f i ∈ (𝓝 a).sets, by rw [nhds_sets]; exact assume i, ⟨- f i, subset.refl _, hβ‚‚ i, this i⟩, let ⟨t, h_sets, (h_fin : finite {i | f i ∩ t β‰  βˆ… })⟩ := h₁ a in calc 𝓝 a ≀ principal (t ∩ (β‹‚ i∈{i | f i ∩ t β‰  βˆ… }, - f i)) : begin rw [le_principal_iff], apply @filter.inter_mem_sets _ (𝓝 a) _ _ h_sets, apply @filter.Inter_mem_sets _ (𝓝 a) _ _ _ h_fin, exact assume i h, this i end ... ≀ principal (- ⋃i, f i) : begin simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq, mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists, not_eq_empty_iff_exists, exists_imp_distrib, (β‰ )], exact assume x xt ht i xfi, ht i x xfi xt xfi end end locally_finite end topological_space section continuous variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ξ΄ : Type*} variables [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³] open_locale topological_space /-- A function between topological spaces is continuous if the preimage of every open set is open. -/ def continuous (f : Ξ± β†’ Ξ²) := βˆ€s, is_open s β†’ is_open (f ⁻¹' s) /-- A function between topological spaces is continuous at a point `xβ‚€` if `f x` tends to `f xβ‚€` when `x` tends to `xβ‚€`. -/ def continuous_at (f : Ξ± β†’ Ξ²) (x : Ξ±) := tendsto f (𝓝 x) (𝓝 (f x)) lemma continuous_at.preimage_mem_nhds {f : Ξ± β†’ Ξ²} {x : Ξ±} {t : set Ξ²} (h : continuous_at f x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x := h ht lemma continuous_id : continuous (id : Ξ± β†’ Ξ±) := assume s h, h lemma continuous.comp {g : Ξ² β†’ Ξ³} {f : Ξ± β†’ Ξ²} (hg : continuous g) (hf : continuous f) : continuous (g ∘ f) := assume s h, hf _ (hg s h) lemma continuous_at.comp {g : Ξ² β†’ Ξ³} {f : Ξ± β†’ Ξ²} {x : Ξ±} (hg : continuous_at g (f x)) (hf : continuous_at f x) : continuous_at (g ∘ f) x := hg.comp hf lemma continuous.tendsto {f : Ξ± β†’ Ξ²} (hf : continuous f) (x) : tendsto f (𝓝 x) (𝓝 (f x)) | s := show s ∈ 𝓝 (f x) β†’ s ∈ map f (𝓝 x), by simp [nhds_sets]; exact assume t t_subset t_open fx_in_t, ⟨f ⁻¹' t, preimage_mono t_subset, hf t t_open, fx_in_t⟩ lemma continuous.continuous_at {f : Ξ± β†’ Ξ²} {x : Ξ±} (h : continuous f) : continuous_at f x := h.tendsto x lemma continuous_iff_continuous_at {f : Ξ± β†’ Ξ²} : continuous f ↔ βˆ€ x, continuous_at f x := ⟨continuous.tendsto, assume hf : βˆ€x, tendsto f (𝓝 x) (𝓝 (f x)), assume s, assume hs : is_open s, have βˆ€a, f a ∈ s β†’ s ∈ 𝓝 (f a), by simp [nhds_sets]; exact assume a ha, ⟨s, subset.refl s, hs, ha⟩, show is_open (f ⁻¹' s), by simp [is_open_iff_nhds]; exact assume a ha, hf a (this a ha)⟩ lemma continuous_const {b : Ξ²} : continuous (Ξ»a:Ξ±, b) := continuous_iff_continuous_at.mpr $ assume a, tendsto_const_nhds lemma continuous_at_const {x : Ξ±} {b : Ξ²} : continuous_at (Ξ» a:Ξ±, b) x := continuous_const.continuous_at lemma continuous_at_id {x : Ξ±} : continuous_at id x := continuous_id.continuous_at lemma continuous_iff_is_closed {f : Ξ± β†’ Ξ²} : continuous f ↔ (βˆ€s, is_closed s β†’ is_closed (f ⁻¹' s)) := ⟨assume hf s hs, hf (-s) hs, assume hf s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩ lemma continuous_at_iff_ultrafilter {f : Ξ± β†’ Ξ²} (x) : continuous_at f x ↔ βˆ€ g, is_ultrafilter g β†’ g ≀ 𝓝 x β†’ g.map f ≀ 𝓝 (f x) := tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x)) lemma continuous_iff_ultrafilter {f : Ξ± β†’ Ξ²} : continuous f ↔ βˆ€ x g, is_ultrafilter g β†’ g ≀ 𝓝 x β†’ g.map f ≀ 𝓝 (f x) := by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter] /-- A piecewise defined function `if p then f else g` is continuous, if both `f` and `g` are continuous, and they coincide on the frontier (boundary) of the set `{a | p a}`. -/ lemma continuous_if {p : Ξ± β†’ Prop} {f g : Ξ± β†’ Ξ²} {h : βˆ€a, decidable (p a)} (hp : βˆ€a∈frontier {a | p a}, f a = g a) (hf : continuous f) (hg : continuous g) : continuous (Ξ»a, @ite (p a) (h a) Ξ² (f a) (g a)) := continuous_iff_is_closed.mpr $ assume s hs, have (Ξ»a, ite (p a) (f a) (g a)) ⁻¹' s = (closure {a | p a} ∩ f ⁻¹' s) βˆͺ (closure {a | Β¬ p a} ∩ g ⁻¹' s), from set.ext $ assume a, classical.by_cases (assume : a ∈ frontier {a | p a}, have hac : a ∈ closure {a | p a}, from this.left, have hai : a ∈ closure {a | Β¬ p a}, from have a ∈ - interior {a | p a}, from this.right, by rwa [←closure_compl] at this, by by_cases p a; simp [h, hp a this, hac, hai, iff_def] {contextual := tt}) (assume hf : a ∈ - frontier {a | p a}, classical.by_cases (assume : p a, have hc : a ∈ closure {a | p a}, from subset_closure this, have hnc : a βˆ‰ closure {a | Β¬ p a}, by show a βˆ‰ closure (- {a | p a}); rw [closure_compl]; simpa [frontier, hc] using hf, by simp [this, hc, hnc]) (assume : Β¬ p a, have hc : a ∈ closure {a | Β¬ p a}, from subset_closure this, have hnc : a βˆ‰ closure {a | p a}, begin have hc : a ∈ closure (- {a | p a}), from hc, simp [closure_compl] at hc, simpa [frontier, hc] using hf end, by simp [this, hc, hnc])), by rw [this]; exact is_closed_union (is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hf s hs) (is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hg s hs) /- Continuity and partial functions -/ /-- Continuity of a partial function -/ def pcontinuous (f : Ξ± β†’. Ξ²) := βˆ€ s, is_open s β†’ is_open (f.preimage s) lemma open_dom_of_pcontinuous {f : Ξ± β†’. Ξ²} (h : pcontinuous f) : is_open f.dom := by rw [←pfun.preimage_univ]; exact h _ is_open_univ lemma pcontinuous_iff' {f : Ξ± β†’. Ξ²} : pcontinuous f ↔ βˆ€ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) := begin split, { intros h x y h', rw [ptendsto'_def], change βˆ€ (s : set Ξ²), s ∈ (𝓝 y).sets β†’ pfun.preimage f s ∈ (𝓝 x).sets, rw [nhds_sets, nhds_sets], rintros s ⟨t, tsubs, opent, yt⟩, exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ }, intros hf s os, rw is_open_iff_nhds, rintros x ⟨y, ys, fxy⟩ t, rw [mem_principal_sets], assume h : f.preimage s βŠ† t, change t ∈ 𝓝 x, apply mem_sets_of_superset _ h, have h' : βˆ€ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x, { intros s hs, have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy, rw ptendsto'_def at this, exact this s hs }, show f.preimage s ∈ 𝓝 x, apply h', rw mem_nhds_sets_iff, exact ⟨s, set.subset.refl _, os, ys⟩ end lemma image_closure_subset_closure_image {f : Ξ± β†’ Ξ²} {s : set Ξ±} (h : continuous f) : f '' closure s βŠ† closure (f '' s) := have βˆ€ (a : Ξ±), 𝓝 a βŠ“ principal s β‰  βŠ₯ β†’ 𝓝 (f a) βŠ“ principal (f '' s) β‰  βŠ₯, from assume a ha, have h₁ : Β¬ map f (𝓝 a βŠ“ principal s) = βŠ₯, by rwa[map_eq_bot_iff], have hβ‚‚ : map f (𝓝 a βŠ“ principal s) ≀ 𝓝 (f a) βŠ“ principal (f '' s), from le_inf (le_trans (map_mono inf_le_left) $ by rw [continuous_iff_continuous_at] at h; exact h a) (le_trans (map_mono inf_le_right) $ by simp; exact subset.refl _), neq_bot_of_le_neq_bot h₁ hβ‚‚, by simp [image_subset_iff, closure_eq_nhds]; assumption lemma mem_closure {s : set Ξ±} {t : set Ξ²} {f : Ξ± β†’ Ξ²} {a : Ξ±} (hf : continuous f) (ha : a ∈ closure s) (ht : βˆ€a∈s, f a ∈ t) : f a ∈ closure t := subset.trans (image_closure_subset_closure_image hf) (closure_mono $ image_subset_iff.2 ht) $ (mem_image_of_mem f ha) end continuous
d86cc4b4914b854231943b6ffd652eeff50d23c6
0e175f34f8dca5ea099671777e8d7446d7d74227
/library/data/bitvec.lean
a5c5d1d8f536b97527f04cca46c9b838db1effc3
[ "Apache-2.0" ]
permissive
utensil-contrib/lean
b31266738071c654d96dac8b35d9ccffc8172fda
a28b9c8f78d982a4e82b1e4f7ce7988d87183ae8
refs/heads/master
1,670,045,564,075
1,597,397,599,000
1,597,397,599,000
287,528,503
0
0
Apache-2.0
1,597,408,338,000
1,597,408,337,000
null
UTF-8
Lean
false
false
6,797
lean
/- Copyright (c) 2015 Joe Hendrix. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joe Hendrix, Sebastian Ullrich Basic operations on bitvectors. This is a work-in-progress, and contains additions to other theories. -/ import data.vector @[reducible] def bitvec (n : β„•) := vector bool n namespace bitvec open nat open vector local infix `++β‚œ`:65 := vector.append -- Create a zero bitvector @[reducible] protected def zero (n : β„•) : bitvec n := repeat ff n -- Create a bitvector with the constant one. @[reducible] protected def one : Ξ  (n : β„•), bitvec n | 0 := nil | (succ n) := repeat ff n ++β‚œ tt::nil protected def cong {a b : β„•} (h : a = b) : bitvec a β†’ bitvec b | ⟨x, p⟩ := ⟨x, h β–Έ p⟩ -- bitvec specific version of vector.append def append {m n} : bitvec m β†’ bitvec n β†’ bitvec (m + n) := vector.append section shift variable {n : β„•} def shl (x : bitvec n) (i : β„•) : bitvec n := bitvec.cong (by simp) $ drop i x ++β‚œ repeat ff (min n i) def fill_shr (x : bitvec n) (i : β„•) (fill : bool) : bitvec n := bitvec.cong begin by_cases (i ≀ n), { have h₁ := sub_le n i, rw [min_eq_right h], rw [min_eq_left h₁, ← nat.add_sub_assoc h, nat.add_comm, nat.add_sub_cancel] }, { have h₁ := le_of_not_ge h, rw [min_eq_left h₁, sub_eq_zero_of_le h₁, zero_min, nat.add_zero] } end $ repeat fill (min n i) ++β‚œ take (n-i) x -- unsigned shift right def ushr (x : bitvec n) (i : β„•) : bitvec n := fill_shr x i ff -- signed shift right def sshr : Ξ  {m : β„•}, bitvec m β†’ β„• β†’ bitvec m | 0 _ _ := nil | (succ m) x i := head x :: fill_shr (tail x) i (head x) end shift section bitwise variable {n : β„•} def not : bitvec n β†’ bitvec n := map bnot def and : bitvec n β†’ bitvec n β†’ bitvec n := mapβ‚‚ band def or : bitvec n β†’ bitvec n β†’ bitvec n := mapβ‚‚ bor def xor : bitvec n β†’ bitvec n β†’ bitvec n := mapβ‚‚ bxor end bitwise section arith variable {n : β„•} protected def xor3 (x y c : bool) := bxor (bxor x y) c protected def carry (x y c : bool) := x && y || x && c || y && c protected def neg (x : bitvec n) : bitvec n := let f := Ξ» y c, (y || c, bxor y c) in prod.snd (map_accumr f x ff) -- Add with carry (no overflow) def adc (x y : bitvec n) (c : bool) : bitvec (n+1) := let f := Ξ» x y c, (bitvec.carry x y c, bitvec.xor3 x y c) in let ⟨c, z⟩ := vector.map_accumrβ‚‚ f x y c in c :: z protected def add (x y : bitvec n) : bitvec n := tail (adc x y ff) -- Subtract with borrow def sbb (x y : bitvec n) (b : bool) : bool Γ— bitvec n := let f := Ξ» x y c, (bitvec.carry (bnot x) y c, bitvec.xor3 x y c) in vector.map_accumrβ‚‚ f x y b protected def sub (x y : bitvec n) : bitvec n := prod.snd (sbb x y ff) instance : has_zero (bitvec n) := ⟨bitvec.zero n⟩ instance : has_one (bitvec n) := ⟨bitvec.one n⟩ instance : has_add (bitvec n) := ⟨bitvec.add⟩ instance : has_sub (bitvec n) := ⟨bitvec.sub⟩ instance : has_neg (bitvec n) := ⟨bitvec.neg⟩ protected def mul (x y : bitvec n) : bitvec n := let f := Ξ» r b, cond b (r + r + y) (r + r) in (to_list x).foldl f 0 instance : has_mul (bitvec n) := ⟨bitvec.mul⟩ end arith section comparison variable {n : β„•} def uborrow (x y : bitvec n) : bool := prod.fst (sbb x y ff) def ult (x y : bitvec n) : Prop := uborrow x y def ugt (x y : bitvec n) : Prop := ult y x def ule (x y : bitvec n) : Prop := Β¬ (ult y x) def uge (x y : bitvec n) : Prop := ule y x def sborrow : Ξ  {n : β„•}, bitvec n β†’ bitvec n β†’ bool | 0 _ _ := ff | (succ n) x y := match (head x, head y) with | (tt, ff) := tt | (ff, tt) := ff | _ := uborrow (tail x) (tail y) end def slt (x y : bitvec n) : Prop := sborrow x y def sgt (x y : bitvec n) : Prop := slt y x def sle (x y : bitvec n) : Prop := Β¬ (slt y x) def sge (x y : bitvec n) : Prop := sle y x end comparison section conversion variable {Ξ± : Type} protected def of_nat : Ξ  (n : β„•), nat β†’ bitvec n | 0 x := nil | (succ n) x := of_nat n (x / 2) ++β‚œ to_bool (x % 2 = 1) :: nil protected def of_int : Ξ  (n : β„•), int β†’ bitvec (succ n) | n (int.of_nat m) := ff :: bitvec.of_nat n m | n (int.neg_succ_of_nat m) := tt :: not (bitvec.of_nat n m) def add_lsb (r : β„•) (b : bool) := r + r + cond b 1 0 def bits_to_nat (v : list bool) : nat := v.foldl add_lsb 0 protected def to_nat {n : nat} (v : bitvec n) : nat := bits_to_nat (to_list v) theorem bits_to_nat_to_list {n : β„•} (x : bitvec n) : bitvec.to_nat x = bits_to_nat (vector.to_list x) := rfl local attribute [simp] nat.add_comm nat.add_assoc nat.add_left_comm nat.mul_comm nat.mul_assoc local attribute [simp] nat.zero_add nat.add_zero nat.one_mul nat.mul_one nat.zero_mul nat.mul_zero -- mul_left_comm theorem to_nat_append {m : β„•} (xs : bitvec m) (b : bool) : bitvec.to_nat (xs ++β‚œ b::nil) = bitvec.to_nat xs * 2 + bitvec.to_nat (b::nil) := begin cases xs with xs P, simp [bits_to_nat_to_list], clear P, unfold bits_to_nat list.foldl, -- generalize the accumulator of foldl generalize h : 0 = x, conv in (add_lsb x b) { rw ←h }, clear h, simp, induction xs with x xs generalizing x, { simp, unfold list.foldl add_lsb, simp [nat.mul_succ] }, { simp, apply xs_ih } end theorem bits_to_nat_to_bool (n : β„•) : bitvec.to_nat (to_bool (n % 2 = 1) :: nil) = n % 2 := begin simp [bits_to_nat_to_list], unfold bits_to_nat add_lsb list.foldl cond, simp [cond_to_bool_mod_two], end theorem of_nat_succ {k n : β„•} : bitvec.of_nat (succ k) n = bitvec.of_nat k (n / 2) ++β‚œ to_bool (n % 2 = 1) :: nil := rfl theorem to_nat_of_nat {k n : β„•} : bitvec.to_nat (bitvec.of_nat k n) = n % 2^k := begin induction k with k ih generalizing n, { unfold pow nat.pow, simp [nat.mod_one], refl }, { have h : 0 < 2, { apply le_succ }, rw [of_nat_succ, to_nat_append, ih, bits_to_nat_to_bool, mod_pow_succ h, nat.mul_comm] } end protected def to_int : Ξ  {n : nat}, bitvec n β†’ int | 0 _ := 0 | (succ n) v := cond (head v) (int.neg_succ_of_nat $ bitvec.to_nat $ not $ tail v) (int.of_nat $ bitvec.to_nat $ tail v) end conversion private def repr {n : nat} : bitvec n β†’ string | ⟨bs, p⟩ := "0b" ++ (bs.map (Ξ» b : bool, if b then '1' else '0')).as_string instance (n : nat) : has_repr (bitvec n) := ⟨repr⟩ end bitvec instance {n} {x y : bitvec n} : decidable (bitvec.ult x y) := bool.decidable_eq _ _ instance {n} {x y : bitvec n} : decidable (bitvec.ugt x y) := bool.decidable_eq _ _
bec17396df68325c067994b4312b58878ebbe819
bdc51328652176125c43c2c9f2d3e4398f127ccb
/src/regular_languages.lean
549f39c1a153f0b17a653b24548aece6e5e5ec7b
[]
no_license
atarnoam/lean-automata
d6ca17387b8e0ac6d7c21f12e78d26c237a57cd2
46c69ddaa142913b1f43ef57f700f2481cdfba76
refs/heads/main
1,678,898,675,345
1,614,977,921,000
1,614,977,921,000
344,927,186
6
1
null
null
null
null
UTF-8
Lean
false
false
5,774
lean
import DFA import data.fintype.basic import order.boolean_algebra import data.quot universes u v def is_regular {Ξ± : Type u} [fintype Ξ±] (l : language Ξ±) : Prop := βˆƒ (Οƒ : Type v) [fintype Οƒ] (A : DFA Ξ± Οƒ), A.accepts = l lemma is_regular_def {Ξ± : Type u} [fintype Ξ±] {l : language Ξ±} : (is_regular.{u v}) l ↔ (βˆƒ (Οƒ : Type v) [fintype Οƒ] (A : DFA Ξ± Οƒ), A.accepts = l) := iff.refl _ namespace regular_language open DFA section basic /-- Here we prove basic things on regular languages, such as the they form a boolean algebra -/ variables {Ξ± : Type u} [fintype Ξ±] variables {l l' : language Ξ±} lemma inf_regular : (is_regular.{u v} l) β†’ (is_regular.{u v} l') β†’ is_regular.{u v} (l βŠ“ l') := begin rintros βŸ¨Οƒ, hΟƒ, A, hA⟩, rintros βŸ¨Ο„, hΟ„, B, hB⟩, resetI, refine βŸ¨Οƒ Γ— Ο„, infer_instance, inter A B, _⟩, rw [inter_accepts, hA, hB], end lemma compl_regular : (is_regular.{u v} l) β†’ (is_regular.{u v} lᢜ) := begin rintros ⟨Q, hQ, A, hA⟩, refine ⟨Q, hQ, A.compl, _⟩, rw [compl_accepts, hA] end lemma compl_regular_iff : (is_regular.{u v} lᢜ) ↔ (is_regular.{u v} l) := begin split, { intro h, rw ← compl_compl l, exact compl_regular h }, { exact compl_regular }, end lemma sup_regular : (is_regular.{u v} l) β†’ (is_regular.{u v} l') β†’ is_regular.{u v} (l βŠ” l') := begin intros hl hl', rw [←compl_compl (l βŠ” l'), compl_sup, compl_regular_iff], exact inf_regular (compl_regular hl) (compl_regular hl'), end end basic section relation /-! ### Myhill-Nerode theorem Given `l`, we define an equivalence relation on `list Ξ±`. The main theorem is that `l` is regular iff the number of equivalence classes of this relation is finite. -/ parameters {Ξ± : Type u} [fintype Ξ±] section basic parameters (l : language Ξ±) /-- A relation on `list Ξ±`, identifying `x, y` if for all `z : list Ξ±`, `(x ++ z ∈ l) ↔ (y ++ z ∈ l)`. -/ def rel : list Ξ± β†’ list Ξ± β†’ Prop := Ξ» x y, βˆ€ (z : list Ξ±), (x ++ z ∈ l) ↔ (y ++ z ∈ l) parameter {l} lemma iff_mem_language_of_equiv {x y : list Ξ±} (Rxy : rel x y) : x ∈ l ↔ y ∈ l := begin specialize Rxy [], repeat {rwa list.append_nil at Rxy}, end parameter (l) lemma rel_refl : reflexive (rel) := Ξ» _ _, by refl lemma rel_symm : symmetric (rel) := Ξ» _ _ hxy z, iff.symm (hxy z) lemma rel_trans : transitive (rel) := Ξ» _ _ _ hxy hyz z, iff.trans (hxy z) (hyz z) lemma rel_equiv : equivalence (rel) := ⟨rel_refl, rel_symm, rel_trans⟩ instance space.setoid : setoid (list Ξ±) := setoid.mk rel rel_equiv definition space := quotient space.setoid parameter {l} definition mk (x : list Ξ±) : space := @quotient.mk _ space.setoid x @[simp] lemma mk_def (x : list Ξ±) : mk x = @quotient.mk _ space.setoid x := rfl end basic section finite_class_space /-! ### Myhill-Nerode, first direction We build an automaton accepting `l` whose states are `space l`. As a consequence, if `space l` is finite, then `l` is regular. -/ parameters (l : language Ξ±) def to_DFA : DFA Ξ± (space l) := { step := begin apply quot.lift (Ξ» (z : list Ξ±) (Οƒ : Ξ±), (mk (z ++ [Οƒ]) : space l)), intros x y r, ext Οƒ, simp only [regular_language.mk_def, quotient.eq], intro z, simp [r (Οƒ :: z)], end, start := mk [], accept := begin apply quot.lift (∈ l), intros x y r, simp [iff_mem_language_of_equiv r], end } @[simp] lemma to_DFA_step (w : list Ξ±) (Οƒ : Ξ±) : to_DFA.step (mk w) Οƒ = mk (w ++ [Οƒ]) := rfl @[simp] lemma to_DFA_start : to_DFA.start = mk [] := rfl @[simp] lemma to_DFA_accept (w : list Ξ±) : (mk w) ∈ to_DFA.accept ↔ w ∈ l := by refl @[simp] lemma to_DFA_eval_from (x y : list Ξ±) : eval_from to_DFA (mk x) y = mk (x ++ y) := begin induction y with Οƒ y generalizing x, { simp, exact rel_refl l _, }, { specialize y_ih (x ++ [Οƒ]), simp at *, exact y_ih, } end lemma to_DFA_accepts : accepts to_DFA = l := begin ext, rw [mem_accepts, to_DFA_start, to_DFA_eval_from, list.nil_append, to_DFA_accept], end theorem regular_of_fintype_language_space [fintype (space l)] : is_regular.{u u} l := ⟨space l, infer_instance, to_DFA, to_DFA_accepts⟩ end finite_class_space section regular /-! ### Myhill-Nerode, the other direction. Now we wish to prove that if `l` is regular then `space l` is finite. We prove this using the canonical functions `Q ↩ DFA_space β†  space l`, the first of which we constructed in DFA.relation. -/ parameters {Q : Type u} (A : DFA Ξ± Q) private def l := A.accepts @[simp] private lemma l_def : l = A.accepts := rfl lemma language_rel_of_DFA_rel (x y : list Ξ±) : A.rel x y β†’ rel l x y := begin intros r z, rw rel_def at r, rw [l_def, mem_accepts, mem_accepts, eval_from_of_append, eval_from_of_append, ← eval_def, ← eval_def, r], end definition language_space_of_DFA_space : A.space β†’ space l := by exact quot.map id (language_rel_of_DFA_rel _) @[simp] lemma language_space_of_DFA_space_def (w : list Ξ±) : language_space_of_DFA_space (DFA.space.mk w) = mk w := rfl lemma language_space_of_DFA_space_surjective : function.surjective language_space_of_DFA_space := begin apply quotient.ind, intro w, use DFA.space.mk w, rw language_space_of_DFA_space_def, refl end open classical local attribute [instance] prop_decidable noncomputable instance fintype_language_space_of_regular (l : language Ξ±) (r : is_regular l) : fintype (space l) := begin choose Q fQ A hA using r, rw ← hA, resetI, haveI : fintype A.space := DFA.fintype_space_of_fintype_states _, exact fintype.of_surjective _ (language_space_of_DFA_space_surjective _), end end regular end relation end regular_language variable (Ξ± : Type u)
e1cd29cb3ea82f29412c6c5544888f5e91eee133
4da0c8e61fcd6ec3f3be47ee14a038850c03d0c3
/src/context.lean
f7286bd3d955ad63efeb2649edecd6ae0ece899e
[ "Apache-2.0" ]
permissive
bbentzen/mpl
fcbea60204bc8fd64667e0f76a5cebf4b67fb6ca
bb5066ec51fa11a4b66f440c4f6c9a3d8fb2e0de
refs/heads/master
1,625,175,849,308
1,624,207,634,000
1,624,207,634,000
142,774,375
9
0
null
null
null
null
UTF-8
Lean
false
false
303
lean
/- Copyright (c) 2018 Bruno Bentzen. All rights reserved. Released under the Apache License 2.0 (see "License"); Author: Bruno Bentzen -/ import .language /- context -/ @[reducible] def ctx (Οƒ : nat) : Type := set (form Οƒ) notation `Β·` := {} notation Ξ“ ` βΈ΄ ` p := set.insert p Ξ“
92dbf4f66bad71711507d16a5498f8752bedb7ac
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/number_theory/liouville/residual.lean
2b987bd5167d4fa03714010dffb72d85acfb429f
[ "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
2,916
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import number_theory.liouville.basic import topology.metric_space.baire import topology.instances.irrational /-! # Density of Liouville numbers In this file we prove that the set of Liouville numbers form a dense `GΞ΄` set. We also prove a similar statement about irrational numbers. -/ open_locale filter open filter set metric lemma set_of_liouville_eq_Inter_Union : {x | liouville x} = β‹‚ n : β„•, ⋃ (a b : β„€) (hb : 1 < b), ball (a / b) (1 / b ^ n) \ {a / b} := begin ext x, simp only [mem_Inter, mem_Union, liouville, mem_set_of_eq, exists_prop, mem_diff, mem_singleton_iff, mem_ball, real.dist_eq, and_comm] end lemma is_GΞ΄_set_of_liouville : is_GΞ΄ {x | liouville x} := begin rw set_of_liouville_eq_Inter_Union, refine is_GΞ΄_Inter (Ξ» n, is_open.is_GΞ΄ _), refine is_open_Union (Ξ» a, is_open_Union $ Ξ» b, is_open_Union $ Ξ» hb, _), exact is_open_ball.inter is_closed_singleton.is_open_compl end lemma set_of_liouville_eq_irrational_inter_Inter_Union : {x | liouville x} = {x | irrational x} ∩ β‹‚ n : β„•, ⋃ (a b : β„€) (hb : 1 < b), ball (a / b) (1 / b ^ n) := begin refine subset.antisymm _ _, { refine subset_inter (Ξ» x hx, hx.irrational) _, rw set_of_liouville_eq_Inter_Union, exact Inter_subset_Inter (Ξ» n, Union_subset_Union $ Ξ» a, Union_subset_Union $ Ξ» b, Union_subset_Union $ Ξ» hb, diff_subset _ _) }, { simp only [inter_Inter, inter_Union, set_of_liouville_eq_Inter_Union], refine Inter_subset_Inter (Ξ» n, Union_subset_Union $ Ξ» a, Union_subset_Union $ Ξ» b, Union_subset_Union $ Ξ» hb, _), rw [inter_comm], refine diff_subset_diff subset.rfl (singleton_subset_iff.2 ⟨a / b, _⟩), norm_cast } end /-- The set of Liouville numbers is a residual set. -/ lemma eventually_residual_liouville : βˆ€αΆ  x in residual ℝ, liouville x := begin rw [filter.eventually, set_of_liouville_eq_irrational_inter_Inter_Union], refine eventually_residual_irrational.and _, refine eventually_residual.2 ⟨_, _, rat.dense_embedding_coe_real.dense.mono _, subset.rfl⟩, { exact is_GΞ΄_Inter (Ξ» n, is_open.is_GΞ΄ $ is_open_Union $ Ξ» a, is_open_Union $ Ξ» b, is_open_Union $ Ξ» hb, is_open_ball) }, { rintro _ ⟨r, rfl⟩, simp only [mem_Inter, mem_Union], refine Ξ» n, ⟨r.num * 2, r.denom * 2, _, _⟩, { have := int.coe_nat_le.2 r.pos, rw int.coe_nat_one at this, linarith }, { convert mem_ball_self _ using 2, { norm_cast, field_simp }, { refine one_div_pos.2 (pow_pos (int.cast_pos.2 _) _), exact mul_pos (int.coe_nat_pos.2 r.pos) zero_lt_two } } } end /-- The set of Liouville numbers in dense. -/ lemma dense_liouville : dense {x | liouville x} := dense_of_mem_residual eventually_residual_liouville
039951c7f23112e427e7c89ec22211b9439181e7
4727251e0cd73359b15b664c3170e5d754078599
/src/data/qpf/multivariate/basic.lean
6b47237bf5943eb05f409592168177a7e92e39cd
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
8,756
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import data.pfunctor.multivariate.basic /-! # Multivariate quotients of polynomial functors. Basic definition of multivariate QPF. QPFs form a compositional framework for defining inductive and coinductive types, their quotients and nesting. The idea is based on building ever larger functors. For instance, we can define a list using a shape functor: ```lean inductive list_shape (a b : Type) | nil : list_shape | cons : a -> b -> list_shape ``` This shape can itself be decomposed as a sum of product which are themselves QPFs. It follows that the shape is a QPF and we can take its fixed point and create the list itself: ```lean def list (a : Type) := fix list_shape a -- not the actual notation ``` We can continue and define the quotient on permutation of lists and create the multiset type: ```lean def multiset (a : Type) := qpf.quot list.perm list a -- not the actual notion ``` And `multiset` is also a QPF. We can then create a novel data type (for Lean): ```lean inductive tree (a : Type) | node : a -> multiset tree -> tree ``` An unordered tree. This is currently not supported by Lean because it nests an inductive type inside of a quotient. We can go further and define unordered, possibly infinite trees: ```lean coinductive tree' (a : Type) | node : a -> multiset tree' -> tree' ``` by using the `cofix` construct. Those options can all be mixed and matched because they preserve the properties of QPF. The latter example, `tree'`, combines fixed point, co-fixed point and quotients. ## Related modules * constructions * fix * cofix * quot * comp * sigma / pi * prj * const each proves that some operations on functors preserves the QPF structure ## Reference * [Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universe u open_locale mvfunctor /-- Multivariate quotients of polynomial functors. -/ class mvqpf {n : β„•} (F : typevec.{u} n β†’ Type*) [mvfunctor F] := (P : mvpfunctor.{u} n) (abs : Ξ  {Ξ±}, P.obj Ξ± β†’ F Ξ±) (repr : Ξ  {Ξ±}, F Ξ± β†’ P.obj Ξ±) (abs_repr : βˆ€ {Ξ±} (x : F Ξ±), abs (repr x) = x) (abs_map : βˆ€ {Ξ± Ξ²} (f : Ξ± ⟹ Ξ²) (p : P.obj Ξ±), abs (f <$$> p) = f <$$> abs p) namespace mvqpf variables {n : β„•} {F : typevec.{u} n β†’ Type*} [mvfunctor F] [q : mvqpf F] include q open mvfunctor (liftp liftr) /-! ### Show that every mvqpf is a lawful mvfunctor. -/ protected theorem id_map {Ξ± : typevec n} (x : F Ξ±) : typevec.id <$$> x = x := by { rw ←abs_repr x, cases repr x with a f, rw [←abs_map], reflexivity } @[simp] theorem comp_map {Ξ± Ξ² Ξ³ : typevec n} (f : Ξ± ⟹ Ξ²) (g : Ξ² ⟹ Ξ³) (x : F Ξ±) : (g ⊚ f) <$$> x = g <$$> f <$$> x := by { rw ←abs_repr x, cases repr x with a f, rw [←abs_map, ←abs_map, ←abs_map], reflexivity } @[priority 100] instance is_lawful_mvfunctor : is_lawful_mvfunctor F := { id_map := @mvqpf.id_map n F _ _, comp_map := @comp_map n F _ _ } /- Lifting predicates and relations -/ theorem liftp_iff {Ξ± : typevec n} (p : Ξ  ⦃i⦄, Ξ± i β†’ Prop) (x : F Ξ±) : liftp p x ↔ βˆƒ a f, x = abs ⟨a, f⟩ ∧ βˆ€ i j, p (f i j) := begin split, { rintros ⟨y, hy⟩, cases h : repr y with a f, use [a, Ξ» i j, (f i j).val], split, { rw [←hy, ←abs_repr y, h, ←abs_map], reflexivity }, intros i j, apply (f i j).property }, rintros ⟨a, f, hβ‚€, hβ‚βŸ©, dsimp at *, use abs (⟨a, Ξ» i j, ⟨f i j, h₁ i j⟩⟩), rw [←abs_map, hβ‚€], reflexivity end theorem liftr_iff {Ξ± : typevec n} (r : Ξ  ⦃i⦄, Ξ± i β†’ Ξ± i β†’ Prop) (x y : F Ξ±) : liftr r x y ↔ βˆƒ a fβ‚€ f₁, x = abs ⟨a, fβ‚€βŸ© ∧ y = abs ⟨a, fβ‚βŸ© ∧ βˆ€ i j, r (fβ‚€ i j) (f₁ i j) := begin split, { rintros ⟨u, xeq, yeq⟩, cases h : repr u with a f, use [a, Ξ» i j, (f i j).val.fst, Ξ» i j, (f i j).val.snd], split, { rw [←xeq, ←abs_repr u, h, ←abs_map], refl }, split, { rw [←yeq, ←abs_repr u, h, ←abs_map], refl }, intros i j, exact (f i j).property }, rintros ⟨a, fβ‚€, f₁, xeq, yeq, h⟩, use abs ⟨a, Ξ» i j, ⟨(fβ‚€ i j, f₁ i j), h i j⟩⟩, dsimp, split, { rw [xeq, ←abs_map], refl }, rw [yeq, ←abs_map], refl end open set open mvfunctor theorem mem_supp {Ξ± : typevec n} (x : F Ξ±) (i) (u : Ξ± i) : u ∈ supp x i ↔ βˆ€ a f, abs ⟨a, f⟩ = x β†’ u ∈ f i '' univ := begin rw [supp], dsimp, split, { intros h a f haf, have : liftp (Ξ» i u, u ∈ f i '' univ) x, { rw liftp_iff, refine ⟨a, f, haf.symm, _⟩, intros i u, exact mem_image_of_mem _ (mem_univ _) }, exact h this }, intros h p, rw liftp_iff, rintros ⟨a, f, xeq, h'⟩, rcases h a f xeq.symm with ⟨i, _, hi⟩, rw ←hi, apply h' end theorem supp_eq {Ξ± : typevec n} {i} (x : F Ξ±) : supp x i = { u | βˆ€ a f, abs ⟨a, f⟩ = x β†’ u ∈ f i '' univ } := by ext; apply mem_supp theorem has_good_supp_iff {Ξ± : typevec n} (x : F Ξ±) : (βˆ€ p, liftp p x ↔ βˆ€ i (u ∈ supp x i), p i u) ↔ βˆƒ a f, abs ⟨a, f⟩ = x ∧ βˆ€ i a' f', abs ⟨a', f'⟩ = x β†’ f i '' univ βŠ† f' i '' univ := begin split, { intros h, have : liftp (supp x) x, by { rw h, introv, exact id, }, rw liftp_iff at this, rcases this with ⟨a, f, xeq, h'⟩, refine ⟨a, f, xeq.symm, _⟩, intros a' f' h'', rintros hu u ⟨j, hβ‚‚, hfi⟩, have hh : u ∈ supp x a', by rw ←hfi; apply h', refine (mem_supp x _ u).mp hh _ _ hu, }, rintros ⟨a, f, xeq, h⟩ p, rw liftp_iff, split, { rintros ⟨a', f', xeq', h'⟩ i u usuppx, rcases (mem_supp x _ u).mp @usuppx a' f' xeq'.symm with ⟨i, _, f'ieq⟩, rw ←f'ieq, apply h' }, intro h', refine ⟨a, f, xeq.symm, _⟩, intros j y, apply h', rw mem_supp, intros a' f' xeq', apply h _ a' f' xeq', apply mem_image_of_mem _ (mem_univ _) end variable (q) /-- A qpf is said to be uniform if every polynomial functor representing a single value all have the same range. -/ def is_uniform : Prop := βˆ€ ⦃α : typevec n⦄ (a a' : q.P.A) (f : q.P.B a ⟹ Ξ±) (f' : q.P.B a' ⟹ Ξ±), abs ⟨a, f⟩ = abs ⟨a', f'⟩ β†’ βˆ€ i, f i '' univ = f' i '' univ /-- does `abs` preserve `liftp`? -/ def liftp_preservation : Prop := βˆ€ ⦃α : typevec n⦄ (p : Ξ  ⦃i⦄, Ξ± i β†’ Prop) (x : q.P.obj Ξ±), liftp p (abs x) ↔ liftp p x /-- does `abs` preserve `supp`? -/ def supp_preservation : Prop := βˆ€ ⦃α⦄ (x : q.P.obj Ξ±), supp (abs x) = supp x variable [q] theorem supp_eq_of_is_uniform (h : q.is_uniform) {Ξ± : typevec n} (a : q.P.A) (f : q.P.B a ⟹ Ξ±) : βˆ€ i, supp (abs ⟨a, f⟩) i = f i '' univ := begin intro, ext u, rw [mem_supp], split, { intro h', apply h' _ _ rfl }, intros h' a' f' e, rw [←h _ _ _ _ e.symm], apply h' end theorem liftp_iff_of_is_uniform (h : q.is_uniform) {Ξ± : typevec n} (x : F Ξ±) (p : Ξ  i, Ξ± i β†’ Prop) : liftp p x ↔ βˆ€ i (u ∈ supp x i), p i u := begin rw [liftp_iff, ←abs_repr x], cases repr x with a f, split, { rintros ⟨a', f', abseq, hf⟩ u, rw [supp_eq_of_is_uniform h, h _ _ _ _ abseq], rintros b ⟨i, _, hi⟩, rw ←hi, apply hf }, intro h', refine ⟨a, f, rfl, Ξ» _ i, h' _ _ _⟩, rw supp_eq_of_is_uniform h, exact ⟨i, mem_univ i, rfl⟩ end theorem supp_map (h : q.is_uniform) {Ξ± Ξ² : typevec n} (g : Ξ± ⟹ Ξ²) (x : F Ξ±) (i) : supp (g <$$> x) i = g i '' supp x i := begin rw ←abs_repr x, cases repr x with a f, rw [←abs_map, mvpfunctor.map_eq], rw [supp_eq_of_is_uniform h, supp_eq_of_is_uniform h, ← image_comp], refl, end theorem supp_preservation_iff_uniform : q.supp_preservation ↔ q.is_uniform := begin split, { intros h Ξ± a a' f f' h' i, rw [← mvpfunctor.supp_eq,← mvpfunctor.supp_eq,← h,h',h] }, { rintros h Ξ± ⟨a,f⟩, ext, rwa [supp_eq_of_is_uniform,mvpfunctor.supp_eq], } end theorem supp_preservation_iff_liftp_preservation : q.supp_preservation ↔ q.liftp_preservation := begin split; intro h, { rintros Ξ± p ⟨a,f⟩, have h' := h, rw supp_preservation_iff_uniform at h', dsimp only [supp_preservation,supp] at h, simp only [liftp_iff_of_is_uniform, supp_eq_of_is_uniform, mvpfunctor.liftp_iff', h', image_univ, mem_range, exists_imp_distrib], split; intros; subst_vars; solve_by_elim }, { rintros Ξ± ⟨a,f⟩, simp only [liftp_preservation] at h, ext, simp [supp,h] } end theorem liftp_preservation_iff_uniform : q.liftp_preservation ↔ q.is_uniform := by rw [← supp_preservation_iff_liftp_preservation, supp_preservation_iff_uniform] end mvqpf
d1a724d3ecb80c41d25b71a6c866e94707c24b06
e9dbaaae490bc072444e3021634bf73664003760
/src/Problems/2013/IMO_2013_P4.lean
f6818bc96952b37a599288111b31f0915f431041
[ "Apache-2.0" ]
permissive
liaofei1128/geometry
566d8bfe095ce0c0113d36df90635306c60e975b
3dd128e4eec8008764bb94e18b932f9ffd66e6b3
refs/heads/master
1,678,996,510,399
1,581,454,543,000
1,583,337,839,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
474
lean
import Geo.Geo.Core namespace Geo open Circle Seg Triangle def IMO_2013_P4 : Prop := βˆ€ (A B C W : Point), acute ⟨A, B, C⟩ β†’ let H := orthocenter ⟨A, B, C⟩; strictlyBtw W B C β†’ let M := foot B (Line.mk A C); let N := foot C (Line.mk A B); βˆ€ (X Y : Point), let ω₁ := Triangle.circumcircle ⟨B, W, N⟩; on X ω₁ β†’ isDiameter W X ω₁ β†’ let Ο‰β‚‚ := Triangle.circumcircle ⟨C, W, M⟩; on Y Ο‰β‚‚ β†’ isDiameter W Y Ο‰β‚‚ β†’ coll X Y H end Geo
130a9d43fbb93c4b56807e09ff01591240c57987
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/algebra/module.lean
cb27c1f3cb3e50295e374028e57f41e9e2b3ed14
[]
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
95,148
lean
/- Copyright (c) 2019 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, SΓ©bastien GouΓ«zel, Jean Lo, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.algebra.ring import Mathlib.topology.uniform_space.uniform_embedding import Mathlib.algebra.algebra.basic import Mathlib.linear_algebra.projection import Mathlib.PostPort universes u v l u_1 u_2 u_3 u_4 u_5 namespace Mathlib /-! # Theory of topological modules and continuous linear maps. We define classes `topological_semimodule`, `topological_module` and `topological_vector_spaces`, as extensions of the corresponding algebraic classes where the algebraic operations are continuous. We also define continuous linear maps, as linear maps between topological modules which are continuous. The set of continuous linear maps between the topological `R`-modules `M` and `Mβ‚‚` is denoted by `M β†’L[R] Mβ‚‚`. Continuous linear equivalences are denoted by `M ≃L[R] Mβ‚‚`. ## Implementation notes Topological vector spaces are defined as an `abbreviation` for topological modules, if the base ring is a field. This has as advantage that topological vector spaces are completely transparent for type class inference, which means that all instances for topological modules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend topological vector spaces. The solution is to extend `topological_module` instead. -/ /-- A topological semimodule, over a semiring which is also a topological space, is a semimodule in which scalar multiplication is continuous. In applications, R will be a topological semiring and M a topological additive semigroup, but this is not needed for the definition -/ class topological_semimodule (R : Type u) (M : Type v) [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] where continuous_smul : continuous fun (p : R Γ— M) => prod.fst p β€’ prod.snd p theorem continuous_smul {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] : continuous fun (p : R Γ— M) => prod.fst p β€’ prod.snd p := topological_semimodule.continuous_smul theorem continuous.smul {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] {Ξ± : Type u_1} [topological_space Ξ±] {f : Ξ± β†’ R} {g : Ξ± β†’ M} (hf : continuous f) (hg : continuous g) : continuous fun (p : Ξ±) => f p β€’ g p := continuous.comp continuous_smul (continuous.prod_mk hf hg) theorem tendsto_smul {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] {c : R} {x : M} : filter.tendsto (fun (p : R Γ— M) => prod.fst p β€’ prod.snd p) (nhds (c, x)) (nhds (c β€’ x)) := continuous.tendsto continuous_smul (c, x) theorem filter.tendsto.smul {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] {Ξ± : Type u_1} {l : filter Ξ±} {f : Ξ± β†’ R} {g : Ξ± β†’ M} {c : R} {x : M} (hf : filter.tendsto f l (nhds c)) (hg : filter.tendsto g l (nhds x)) : filter.tendsto (fun (a : Ξ±) => f a β€’ g a) l (nhds (c β€’ x)) := filter.tendsto.comp tendsto_smul (filter.tendsto.prod_mk_nhds hf hg) protected instance topological_semiring.to_semimodule {R : Type u_1} [topological_space R] [semiring R] [topological_semiring R] : topological_semimodule R R := topological_semimodule.mk continuous_mul /-- A topological module, over a ring which is also a topological space, is a module in which scalar multiplication is continuous. In applications, `R` will be a topological ring and `M` a topological additive group, but this is not needed for the definition -/ def topological_module (R : Type u) (M : Type v) [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] := topological_semimodule R M /-- A topological vector space is a topological module over a field. -/ def topological_vector_space (R : Type u) (M : Type v) [field R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] := topological_module R M /-- Scalar multiplication by a unit is a homeomorphism from a topological module onto itself. -/ protected def homeomorph.smul_of_unit {R : Type u_1} {M : Type u_2} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] (a : units R) : M β‰ƒβ‚œ M := homeomorph.mk (equiv.mk (fun (x : M) => ↑a β€’ x) (fun (x : M) => ↑(a⁻¹) β€’ x) sorry sorry) theorem is_open_map_smul_of_unit {R : Type u_1} {M : Type u_2} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] (a : units R) : is_open_map fun (x : M) => ↑a β€’ x := homeomorph.is_open_map (homeomorph.smul_of_unit a) theorem is_closed_map_smul_of_unit {R : Type u_1} {M : Type u_2} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] (a : units R) : is_closed_map fun (x : M) => ↑a β€’ x := homeomorph.is_closed_map (homeomorph.smul_of_unit a) /-- If `M` is a topological module over `R` and `0` is a limit of invertible elements of `R`, then `⊀` is the only submodule of `M` with a nonempty interior. This is the case, e.g., if `R` is a nondiscrete normed field. -/ theorem submodule.eq_top_of_nonempty_interior' {R : Type u_1} {M : Type u_2} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] [has_continuous_add M] [filter.ne_bot (nhds_within 0 (set_of fun (x : R) => is_unit x))] (s : submodule R M) (hs : set.nonempty (interior ↑s)) : s = ⊀ := sorry theorem submodule.closure_smul_self_subset {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] (s : submodule R M) : (fun (p : R Γ— M) => prod.fst p β€’ prod.snd p) '' set.prod set.univ (closure ↑s) βŠ† closure ↑s := sorry theorem submodule.closure_smul_self_eq {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] (s : submodule R M) : (fun (p : R Γ— M) => prod.fst p β€’ prod.snd p) '' set.prod set.univ (closure ↑s) = closure ↑s := sorry /-- The (topological-space) closure of a submodle of a topological `R`-semimodule `M` is itself a submodule. -/ def submodule.topological_closure {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] [has_continuous_add M] (s : submodule R M) : submodule R M := submodule.mk (closure ↑s) sorry sorry sorry theorem submodule.submodule_topological_closure {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] [has_continuous_add M] (s : submodule R M) : s ≀ submodule.topological_closure s := subset_closure theorem submodule.is_closed_topological_closure {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] [has_continuous_add M] (s : submodule R M) : is_closed ↑(submodule.topological_closure s) := sorry theorem submodule.topological_closure_minimal {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] [has_continuous_add M] (s : submodule R M) {t : submodule R M} (h : s ≀ t) (ht : is_closed ↑t) : submodule.topological_closure s ≀ t := closure_minimal h ht /-- Scalar multiplication by a non-zero field element is a homeomorphism from a topological vector space onto itself. -/ protected def homeomorph.smul_of_ne_zero {R : Type u_1} {M : Type u_2} {a : R} [field R] [topological_space R] [topological_space M] [add_comm_group M] [vector_space R M] [topological_vector_space R M] (ha : a β‰  0) : M β‰ƒβ‚œ M := homeomorph.mk (homeomorph.to_equiv (homeomorph.smul_of_unit (units.mk0 a ha))) theorem is_open_map_smul_of_ne_zero {R : Type u_1} {M : Type u_2} {a : R} [field R] [topological_space R] [topological_space M] [add_comm_group M] [vector_space R M] [topological_vector_space R M] (ha : a β‰  0) : is_open_map fun (x : M) => a β€’ x := homeomorph.is_open_map (homeomorph.smul_of_ne_zero ha) /-- `smul` is a closed map in the second argument. The lemma that `smul` is a closed map in the first argument (for a normed space over a complete normed field) is `is_closed_map_smul_left` in `analysis.normed_space.finite_dimension`. -/ theorem is_closed_map_smul_of_ne_zero {R : Type u_1} {M : Type u_2} {a : R} [field R] [topological_space R] [topological_space M] [add_comm_group M] [vector_space R M] [topological_vector_space R M] (ha : a β‰  0) : is_closed_map fun (x : M) => a β€’ x := homeomorph.is_closed_map (homeomorph.smul_of_ne_zero ha) /-- Continuous linear maps between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `Mβ‚‚` will be topological modules over the topological ring `R`. -/ structure continuous_linear_map (R : Type u_1) [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] (Mβ‚‚ : Type u_3) [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] extends linear_map R M Mβ‚‚ where cont : autoParam (continuous (linear_map.to_fun _to_linear_map)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.continuity'") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive") "continuity'") []) /-- Continuous linear equivalences between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `Mβ‚‚` will be topological modules over the topological ring `R`. -/ structure continuous_linear_equiv (R : Type u_1) [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] (Mβ‚‚ : Type u_3) [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] extends linear_equiv R M Mβ‚‚ where continuous_to_fun : autoParam (continuous (linear_equiv.to_fun _to_linear_equiv)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.continuity'") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive") "continuity'") []) continuous_inv_fun : autoParam (continuous (linear_equiv.inv_fun _to_linear_equiv)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.continuity'") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive") "continuity'") []) namespace continuous_linear_map /-! ### Properties that hold for non-necessarily commutative semirings. -/ /-- Coerce continuous linear maps to linear maps. -/ protected instance linear_map.has_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : has_coe (continuous_linear_map R M Mβ‚‚) (linear_map R M Mβ‚‚) := has_coe.mk to_linear_map /-- Coerce continuous linear maps to functions. -/ -- see Note [function coercion] protected instance to_fun {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : has_coe_to_fun (continuous_linear_map R M Mβ‚‚) := has_coe_to_fun.mk (fun (_x : continuous_linear_map R M Mβ‚‚) => M β†’ Mβ‚‚) fun (f : continuous_linear_map R M Mβ‚‚) => ⇑f @[simp] theorem coe_mk {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : linear_map R M Mβ‚‚) (h : autoParam (continuous (linear_map.to_fun f)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.continuity'") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive") "continuity'") [])) : ↑(mk f) = f := rfl @[simp] theorem coe_mk' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : linear_map R M Mβ‚‚) (h : autoParam (continuous (linear_map.to_fun f)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.continuity'") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive") "continuity'") [])) : ⇑(mk f) = ⇑f := rfl protected theorem continuous {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) : continuous ⇑f := cont f theorem coe_injective {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : function.injective coe := sorry theorem injective_coe_fn {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : function.injective fun (f : continuous_linear_map R M Mβ‚‚) => (fun (this : M β†’ Mβ‚‚) => this) ⇑f := function.injective.comp linear_map.coe_injective coe_injective theorem ext {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] {f : continuous_linear_map R M Mβ‚‚} {g : continuous_linear_map R M Mβ‚‚} (h : βˆ€ (x : M), coe_fn f x = coe_fn g x) : f = g := injective_coe_fn (funext h) theorem ext_iff {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] {f : continuous_linear_map R M Mβ‚‚} {g : continuous_linear_map R M Mβ‚‚} : f = g ↔ βˆ€ (x : M), coe_fn f x = coe_fn g x := { mp := fun (h : f = g) (x : M) => eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn f x = coe_fn g x)) h)) (Eq.refl (coe_fn g x)), mpr := ext } -- make some straightforward lemmas available to `simp`. @[simp] theorem map_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) : coe_fn f 0 = 0 := linear_map.map_zero (to_linear_map f) @[simp] theorem map_add {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (x : M) (y : M) : coe_fn f (x + y) = coe_fn f x + coe_fn f y := linear_map.map_add (to_linear_map f) x y @[simp] theorem map_smul {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (c : R) (f : continuous_linear_map R M Mβ‚‚) (x : M) : coe_fn f (c β€’ x) = c β€’ coe_fn f x := linear_map.map_smul (to_linear_map f) c x theorem map_sum {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) {ΞΉ : Type u_4} (s : finset ΞΉ) (g : ΞΉ β†’ M) : coe_fn f (finset.sum s fun (i : ΞΉ) => g i) = finset.sum s fun (i : ΞΉ) => coe_fn f (g i) := linear_map.map_sum (to_linear_map f) @[simp] theorem coe_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) : ⇑↑f = ⇑f := rfl /-- If two continuous linear maps are equal on a set `s`, then they are equal on the closure of the `submodule.span` of this set. -/ theorem eq_on_closure_span {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [t2_space Mβ‚‚] {s : set M} {f : continuous_linear_map R M Mβ‚‚} {g : continuous_linear_map R M Mβ‚‚} (h : set.eq_on (⇑f) (⇑g) s) : set.eq_on (⇑f) (⇑g) (closure ↑(submodule.span R s)) := set.eq_on.closure (linear_map.eq_on_span' h) (continuous_linear_map.continuous f) (continuous_linear_map.continuous g) /-- If the submodule generated by a set `s` is dense in the ambient semimodule, then two continuous linear maps equal on `s` are equal. -/ theorem ext_on {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [t2_space Mβ‚‚] {s : set M} (hs : dense ↑(submodule.span R s)) {f : continuous_linear_map R M Mβ‚‚} {g : continuous_linear_map R M Mβ‚‚} (h : set.eq_on (⇑f) (⇑g) s) : f = g := ext fun (x : M) => eq_on_closure_span h (hs x) /-- The continuous map that is constantly zero. -/ protected instance has_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : HasZero (continuous_linear_map R M Mβ‚‚) := { zero := mk 0 } protected instance inhabited {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : Inhabited (continuous_linear_map R M Mβ‚‚) := { default := 0 } @[simp] theorem default_def {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : Inhabited.default = 0 := rfl @[simp] theorem zero_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (x : M) : coe_fn 0 x = 0 := rfl /- no simp attribute on the next line as simp does not always simplify `0 x` to `0` @[simp] theorem coe_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : ↑0 = 0 := rfl when `0` is the zero function, while it does for the zero continuous linear map, and this is the most important property we care about. -/ theorem coe_zero' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : ⇑0 = 0 := rfl protected instance unique_of_left {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [subsingleton M] : unique (continuous_linear_map R M Mβ‚‚) := function.injective.unique coe_injective protected instance unique_of_right {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [subsingleton Mβ‚‚] : unique (continuous_linear_map R M Mβ‚‚) := function.injective.unique coe_injective /-- the identity map as a continuous linear map. -/ def id (R : Type u_1) [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] [semimodule R M] : continuous_linear_map R M M := mk linear_map.id protected instance has_one {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : HasOne (continuous_linear_map R M M) := { one := id R M } theorem one_def {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : 1 = id R M := rfl theorem id_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (x : M) : coe_fn (id R M) x = x := rfl @[simp] theorem coe_id {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : ↑(id R M) = linear_map.id := rfl @[simp] theorem coe_id' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : ⇑(id R M) = id := rfl @[simp] theorem one_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (x : M) : coe_fn 1 x = x := rfl protected instance has_add {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [has_continuous_add Mβ‚‚] : Add (continuous_linear_map R M Mβ‚‚) := { add := fun (f g : continuous_linear_map R M Mβ‚‚) => mk (↑f + ↑g) } @[simp] theorem add_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (g : continuous_linear_map R M Mβ‚‚) (x : M) [has_continuous_add Mβ‚‚] : coe_fn (f + g) x = coe_fn f x + coe_fn g x := rfl @[simp] theorem coe_add {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (g : continuous_linear_map R M Mβ‚‚) [has_continuous_add Mβ‚‚] : ↑(f + g) = ↑f + ↑g := rfl theorem coe_add' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (g : continuous_linear_map R M Mβ‚‚) [has_continuous_add Mβ‚‚] : ⇑(f + g) = ⇑f + ⇑g := rfl protected instance add_comm_monoid {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [has_continuous_add Mβ‚‚] : add_comm_monoid (continuous_linear_map R M Mβ‚‚) := add_comm_monoid.mk Add.add sorry 0 sorry sorry sorry theorem sum_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [has_continuous_add Mβ‚‚] {ΞΉ : Type u_4} (t : finset ΞΉ) (f : ΞΉ β†’ continuous_linear_map R M Mβ‚‚) (b : M) : coe_fn (finset.sum t fun (d : ΞΉ) => f d) b = finset.sum t fun (d : ΞΉ) => coe_fn (f d) b := Eq.symm (finset.sum_hom t fun (g : continuous_linear_map R M Mβ‚‚) => coe_fn g b) /-- Composition of bounded linear maps. -/ def comp {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (g : continuous_linear_map R Mβ‚‚ M₃) (f : continuous_linear_map R M Mβ‚‚) : continuous_linear_map R M M₃ := mk (linear_map.comp (to_linear_map g) (to_linear_map f)) @[simp] theorem coe_comp {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (f : continuous_linear_map R M Mβ‚‚) (h : continuous_linear_map R Mβ‚‚ M₃) : ↑(comp h f) = linear_map.comp ↑h ↑f := rfl @[simp] theorem coe_comp' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (f : continuous_linear_map R M Mβ‚‚) (h : continuous_linear_map R Mβ‚‚ M₃) : ⇑(comp h f) = ⇑h ∘ ⇑f := rfl @[simp] theorem comp_id {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) : comp f (id R M) = f := ext fun (x : M) => rfl @[simp] theorem id_comp {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) : comp (id R Mβ‚‚) f = f := ext fun (x : M) => rfl @[simp] theorem comp_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (f : continuous_linear_map R M Mβ‚‚) : comp f 0 = 0 := sorry @[simp] theorem zero_comp {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (f : continuous_linear_map R M Mβ‚‚) : comp 0 f = 0 := sorry @[simp] theorem comp_add {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [has_continuous_add Mβ‚‚] [has_continuous_add M₃] (g : continuous_linear_map R Mβ‚‚ M₃) (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R M Mβ‚‚) : comp g (f₁ + fβ‚‚) = comp g f₁ + comp g fβ‚‚ := sorry @[simp] theorem add_comp {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [has_continuous_add M₃] (g₁ : continuous_linear_map R Mβ‚‚ M₃) (gβ‚‚ : continuous_linear_map R Mβ‚‚ M₃) (f : continuous_linear_map R M Mβ‚‚) : comp (g₁ + gβ‚‚) f = comp g₁ f + comp gβ‚‚ f := sorry theorem comp_assoc {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] {Mβ‚„ : Type u_5} [topological_space Mβ‚„] [add_comm_monoid Mβ‚„] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [semimodule R Mβ‚„] (h : continuous_linear_map R M₃ Mβ‚„) (g : continuous_linear_map R Mβ‚‚ M₃) (f : continuous_linear_map R M Mβ‚‚) : comp (comp h g) f = comp h (comp g f) := rfl protected instance has_mul {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : Mul (continuous_linear_map R M M) := { mul := comp } theorem mul_def {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (f : continuous_linear_map R M M) (g : continuous_linear_map R M M) : f * g = comp f g := rfl @[simp] theorem coe_mul {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (f : continuous_linear_map R M M) (g : continuous_linear_map R M M) : ⇑(f * g) = ⇑f ∘ ⇑g := rfl theorem mul_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (f : continuous_linear_map R M M) (g : continuous_linear_map R M M) (x : M) : coe_fn (f * g) x = coe_fn f (coe_fn g x) := rfl /-- The cartesian product of two bounded linear maps, as a bounded linear map. -/ protected def prod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R M M₃) : continuous_linear_map R M (Mβ‚‚ Γ— M₃) := mk (linear_map.mk (linear_map.to_fun (linear_map.prod (to_linear_map f₁) (to_linear_map fβ‚‚))) sorry sorry) @[simp] theorem coe_prod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R M M₃) : ↑(continuous_linear_map.prod f₁ fβ‚‚) = linear_map.prod ↑f₁ ↑fβ‚‚ := rfl @[simp] theorem prod_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R M M₃) (x : M) : coe_fn (continuous_linear_map.prod f₁ fβ‚‚) x = (coe_fn f₁ x, coe_fn fβ‚‚ x) := rfl /-- Kernel of a continuous linear map. -/ def ker {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) : submodule R M := linear_map.ker ↑f theorem ker_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) : linear_map.ker ↑f = ker f := rfl @[simp] theorem mem_ker {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] {f : continuous_linear_map R M Mβ‚‚} {x : M} : x ∈ ker f ↔ coe_fn f x = 0 := linear_map.mem_ker theorem is_closed_ker {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) [t1_space Mβ‚‚] : is_closed ↑(ker f) := iff.mp continuous_iff_is_closed (cont f) (↑βŠ₯) is_closed_singleton @[simp] theorem apply_ker {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (x : β†₯(ker f)) : coe_fn f ↑x = 0 := iff.mp mem_ker (subtype.property x) theorem is_complete_ker {R : Type u_1} [semiring R] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R Mβ‚‚] {M' : Type u_2} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [semimodule R M'] [t1_space Mβ‚‚] (f : continuous_linear_map R M' Mβ‚‚) : is_complete ↑(ker f) := is_closed.is_complete (is_closed_ker f) protected instance complete_space_ker {R : Type u_1} [semiring R] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R Mβ‚‚] {M' : Type u_2} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [semimodule R M'] [t1_space Mβ‚‚] (f : continuous_linear_map R M' Mβ‚‚) : complete_space β†₯(ker f) := is_closed.complete_space_coe (is_closed_ker f) @[simp] theorem ker_prod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (f : continuous_linear_map R M Mβ‚‚) (g : continuous_linear_map R M M₃) : ker (continuous_linear_map.prod f g) = ker f βŠ“ ker g := linear_map.ker_prod ↑f ↑g /-- Range of a continuous linear map. -/ def range {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) : submodule R Mβ‚‚ := linear_map.range ↑f theorem range_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) : ↑(range f) = set.range ⇑f := linear_map.range_coe ↑f theorem mem_range {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] {f : continuous_linear_map R M Mβ‚‚} {y : Mβ‚‚} : y ∈ range f ↔ βˆƒ (x : M), coe_fn f x = y := linear_map.mem_range theorem range_prod_le {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (f : continuous_linear_map R M Mβ‚‚) (g : continuous_linear_map R M M₃) : range (continuous_linear_map.prod f g) ≀ submodule.prod (range f) (range g) := linear_map.range_prod_le ↑f ↑g /-- Restrict codomain of a continuous linear map. -/ def cod_restrict {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (p : submodule R Mβ‚‚) (h : βˆ€ (x : M), coe_fn f x ∈ p) : continuous_linear_map R M β†₯p := mk (linear_map.cod_restrict p (↑f) h) theorem coe_cod_restrict {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (p : submodule R Mβ‚‚) (h : βˆ€ (x : M), coe_fn f x ∈ p) : ↑(cod_restrict f p h) = linear_map.cod_restrict p (↑f) h := rfl @[simp] theorem coe_cod_restrict_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (p : submodule R Mβ‚‚) (h : βˆ€ (x : M), coe_fn f x ∈ p) (x : M) : ↑(coe_fn (cod_restrict f p h) x) = coe_fn f x := rfl @[simp] theorem ker_cod_restrict {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (p : submodule R Mβ‚‚) (h : βˆ€ (x : M), coe_fn f x ∈ p) : ker (cod_restrict f p h) = ker f := linear_map.ker_cod_restrict p (↑f) h /-- Embedding of a submodule into the ambient space as a continuous linear map. -/ def subtype_val {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (p : submodule R M) : continuous_linear_map R (β†₯p) M := mk (submodule.subtype p) @[simp] theorem coe_subtype_val {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (p : submodule R M) : ↑(subtype_val p) = submodule.subtype p := rfl @[simp] theorem subtype_val_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (p : submodule R M) (x : β†₯p) : coe_fn (subtype_val p) x = ↑x := rfl /-- `prod.fst` as a `continuous_linear_map`. -/ def fst (R : Type u_1) [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] (Mβ‚‚ : Type u_3) [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : continuous_linear_map R (M Γ— Mβ‚‚) M := mk (linear_map.fst R M Mβ‚‚) /-- `prod.snd` as a `continuous_linear_map`. -/ def snd (R : Type u_1) [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] (Mβ‚‚ : Type u_3) [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : continuous_linear_map R (M Γ— Mβ‚‚) Mβ‚‚ := mk (linear_map.snd R M Mβ‚‚) @[simp] theorem coe_fst {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : ↑(fst R M Mβ‚‚) = linear_map.fst R M Mβ‚‚ := rfl @[simp] theorem coe_fst' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : ⇑(fst R M Mβ‚‚) = prod.fst := rfl @[simp] theorem coe_snd {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : ↑(snd R M Mβ‚‚) = linear_map.snd R M Mβ‚‚ := rfl @[simp] theorem coe_snd' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : ⇑(snd R M Mβ‚‚) = prod.snd := rfl @[simp] theorem fst_prod_snd {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : continuous_linear_map.prod (fst R M Mβ‚‚) (snd R M Mβ‚‚) = id R (M Γ— Mβ‚‚) := sorry /-- `prod.map` of two continuous linear maps. -/ def prod_map {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] {Mβ‚„ : Type u_5} [topological_space Mβ‚„] [add_comm_monoid Mβ‚„] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [semimodule R Mβ‚„] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R M₃ Mβ‚„) : continuous_linear_map R (M Γ— M₃) (Mβ‚‚ Γ— Mβ‚„) := continuous_linear_map.prod (comp f₁ (fst R M M₃)) (comp fβ‚‚ (snd R M M₃)) @[simp] theorem coe_prod_map {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] {Mβ‚„ : Type u_5} [topological_space Mβ‚„] [add_comm_monoid Mβ‚„] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [semimodule R Mβ‚„] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R M₃ Mβ‚„) : ↑(prod_map f₁ fβ‚‚) = linear_map.prod_map ↑f₁ ↑fβ‚‚ := rfl @[simp] theorem coe_prod_map' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] {Mβ‚„ : Type u_5} [topological_space Mβ‚„] [add_comm_monoid Mβ‚„] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [semimodule R Mβ‚„] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R M₃ Mβ‚„) : ⇑(prod_map f₁ fβ‚‚) = prod.map ⇑f₁ ⇑fβ‚‚ := rfl /-- The continuous linear map given by `(x, y) ↦ f₁ x + fβ‚‚ y`. -/ def coprod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [has_continuous_add M₃] (f₁ : continuous_linear_map R M M₃) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M₃) : continuous_linear_map R (M Γ— Mβ‚‚) M₃ := mk (linear_map.coprod ↑f₁ ↑fβ‚‚) @[simp] theorem coe_coprod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [has_continuous_add M₃] (f₁ : continuous_linear_map R M M₃) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M₃) : ↑(coprod f₁ fβ‚‚) = linear_map.coprod ↑f₁ ↑fβ‚‚ := rfl @[simp] theorem coprod_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [has_continuous_add M₃] (f₁ : continuous_linear_map R M M₃) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M₃) (x : M Γ— Mβ‚‚) : coe_fn (coprod f₁ fβ‚‚) x = coe_fn f₁ (prod.fst x) + coe_fn fβ‚‚ (prod.snd x) := rfl /-- The linear map `Ξ» x, c x β€’ f`. Associates to a scalar-valued linear map and an element of `Mβ‚‚` the `Mβ‚‚`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `Mβ‚‚`). See also `continuous_linear_map.smul_rightβ‚—` and `continuous_linear_map.smul_rightL`. -/ def smul_right {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [topological_space R] [topological_semimodule R Mβ‚‚] (c : continuous_linear_map R M R) (f : Mβ‚‚) : continuous_linear_map R M Mβ‚‚ := mk (linear_map.mk (linear_map.to_fun (linear_map.smul_right (to_linear_map c) f)) sorry sorry) @[simp] theorem smul_right_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [topological_space R] [topological_semimodule R Mβ‚‚] {c : continuous_linear_map R M R} {f : Mβ‚‚} {x : M} : coe_fn (smul_right c f) x = coe_fn c x β€’ f := rfl @[simp] theorem smul_right_one_one {R : Type u_1} [semiring R] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R Mβ‚‚] [topological_space R] [topological_semimodule R Mβ‚‚] (c : continuous_linear_map R R Mβ‚‚) : smul_right 1 (coe_fn c 1) = c := sorry @[simp] theorem smul_right_one_eq_iff {R : Type u_1} [semiring R] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R Mβ‚‚] [topological_space R] [topological_semimodule R Mβ‚‚] {f : Mβ‚‚} {f' : Mβ‚‚} : smul_right 1 f = smul_right 1 f' ↔ f = f' := sorry theorem smul_right_comp {R : Type u_1} [semiring R] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R Mβ‚‚] [topological_space R] [topological_semimodule R Mβ‚‚] [topological_semimodule R R] {x : Mβ‚‚} {c : R} : comp (smul_right 1 x) (smul_right 1 c) = smul_right 1 (c β€’ x) := sorry /-- `pi` construction for continuous linear functions. From a family of continuous linear functions it produces a continuous linear function into a family of topological modules. -/ def pi {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] {ΞΉ : Type u_4} {Ο† : ΞΉ β†’ Type u_5} [(i : ΞΉ) β†’ topological_space (Ο† i)] [(i : ΞΉ) β†’ add_comm_monoid (Ο† i)] [(i : ΞΉ) β†’ semimodule R (Ο† i)] (f : (i : ΞΉ) β†’ continuous_linear_map R M (Ο† i)) : continuous_linear_map R M ((i : ΞΉ) β†’ Ο† i) := mk (linear_map.pi fun (i : ΞΉ) => ↑(f i)) @[simp] theorem pi_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] {ΞΉ : Type u_4} {Ο† : ΞΉ β†’ Type u_5} [(i : ΞΉ) β†’ topological_space (Ο† i)] [(i : ΞΉ) β†’ add_comm_monoid (Ο† i)] [(i : ΞΉ) β†’ semimodule R (Ο† i)] (f : (i : ΞΉ) β†’ continuous_linear_map R M (Ο† i)) (c : M) (i : ΞΉ) : coe_fn (pi f) c i = coe_fn (f i) c := rfl theorem pi_eq_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] {ΞΉ : Type u_4} {Ο† : ΞΉ β†’ Type u_5} [(i : ΞΉ) β†’ topological_space (Ο† i)] [(i : ΞΉ) β†’ add_comm_monoid (Ο† i)] [(i : ΞΉ) β†’ semimodule R (Ο† i)] (f : (i : ΞΉ) β†’ continuous_linear_map R M (Ο† i)) : pi f = 0 ↔ βˆ€ (i : ΞΉ), f i = 0 := sorry theorem pi_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] {ΞΉ : Type u_4} {Ο† : ΞΉ β†’ Type u_5} [(i : ΞΉ) β†’ topological_space (Ο† i)] [(i : ΞΉ) β†’ add_comm_monoid (Ο† i)] [(i : ΞΉ) β†’ semimodule R (Ο† i)] : (pi fun (i : ΞΉ) => 0) = 0 := ext fun (x : M) => funext fun (x_1 : ΞΉ) => Eq.refl (coe_fn (pi fun (i : ΞΉ) => 0) x x_1) theorem pi_comp {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R Mβ‚‚] {ΞΉ : Type u_4} {Ο† : ΞΉ β†’ Type u_5} [(i : ΞΉ) β†’ topological_space (Ο† i)] [(i : ΞΉ) β†’ add_comm_monoid (Ο† i)] [(i : ΞΉ) β†’ semimodule R (Ο† i)] (f : (i : ΞΉ) β†’ continuous_linear_map R M (Ο† i)) (g : continuous_linear_map R Mβ‚‚ M) : comp (pi f) g = pi fun (i : ΞΉ) => comp (f i) g := rfl /-- The projections from a family of topological modules are continuous linear maps. -/ def proj {R : Type u_1} [semiring R] {ΞΉ : Type u_4} {Ο† : ΞΉ β†’ Type u_5} [(i : ΞΉ) β†’ topological_space (Ο† i)] [(i : ΞΉ) β†’ add_comm_monoid (Ο† i)] [(i : ΞΉ) β†’ semimodule R (Ο† i)] (i : ΞΉ) : continuous_linear_map R ((i : ΞΉ) β†’ Ο† i) (Ο† i) := mk (linear_map.proj i) @[simp] theorem proj_apply {R : Type u_1} [semiring R] {ΞΉ : Type u_4} {Ο† : ΞΉ β†’ Type u_5} [(i : ΞΉ) β†’ topological_space (Ο† i)] [(i : ΞΉ) β†’ add_comm_monoid (Ο† i)] [(i : ΞΉ) β†’ semimodule R (Ο† i)] (i : ΞΉ) (b : (i : ΞΉ) β†’ Ο† i) : coe_fn (proj i) b = b i := rfl theorem proj_pi {R : Type u_1} [semiring R] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R Mβ‚‚] {ΞΉ : Type u_4} {Ο† : ΞΉ β†’ Type u_5} [(i : ΞΉ) β†’ topological_space (Ο† i)] [(i : ΞΉ) β†’ add_comm_monoid (Ο† i)] [(i : ΞΉ) β†’ semimodule R (Ο† i)] (f : (i : ΞΉ) β†’ continuous_linear_map R Mβ‚‚ (Ο† i)) (i : ΞΉ) : comp (proj i) (pi f) = f i := ext fun (c : Mβ‚‚) => rfl theorem infi_ker_proj {R : Type u_1} [semiring R] {ΞΉ : Type u_4} {Ο† : ΞΉ β†’ Type u_5} [(i : ΞΉ) β†’ topological_space (Ο† i)] [(i : ΞΉ) β†’ add_comm_monoid (Ο† i)] [(i : ΞΉ) β†’ semimodule R (Ο† i)] : (infi fun (i : ΞΉ) => ker (proj i)) = βŠ₯ := linear_map.infi_ker_proj /-- If `I` and `J` are complementary index sets, the product of the kernels of the `J`th projections of `Ο†` is linearly equivalent to the product over `I`. -/ def infi_ker_proj_equiv (R : Type u_1) [semiring R] {ΞΉ : Type u_4} (Ο† : ΞΉ β†’ Type u_5) [(i : ΞΉ) β†’ topological_space (Ο† i)] [(i : ΞΉ) β†’ add_comm_monoid (Ο† i)] [(i : ΞΉ) β†’ semimodule R (Ο† i)] {I : set ΞΉ} {J : set ΞΉ} [decidable_pred fun (i : ΞΉ) => i ∈ I] (hd : disjoint I J) (hu : set.univ βŠ† I βˆͺ J) : continuous_linear_equiv R (β†₯(infi fun (i : ΞΉ) => infi fun (H : i ∈ J) => ker (proj i))) ((i : β†₯I) β†’ Ο† ↑i) := continuous_linear_equiv.mk (linear_map.infi_ker_proj_equiv R Ο† hd hu) @[simp] theorem map_neg {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (x : M) : coe_fn f (-x) = -coe_fn f x := linear_map.map_neg (to_linear_map f) x @[simp] theorem map_sub {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (x : M) (y : M) : coe_fn f (x - y) = coe_fn f x - coe_fn f y := linear_map.map_sub (to_linear_map f) x y @[simp] theorem sub_apply' {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (g : continuous_linear_map R M Mβ‚‚) (x : M) : coe_fn (↑f - ↑g) x = coe_fn f x - coe_fn g x := rfl theorem range_prod_eq {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_group M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] {f : continuous_linear_map R M Mβ‚‚} {g : continuous_linear_map R M M₃} (h : ker f βŠ” ker g = ⊀) : range (continuous_linear_map.prod f g) = submodule.prod (range f) (range g) := linear_map.range_prod_eq h protected instance has_neg {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [topological_add_group Mβ‚‚] : Neg (continuous_linear_map R M Mβ‚‚) := { neg := fun (f : continuous_linear_map R M Mβ‚‚) => mk (-↑f) } @[simp] theorem neg_apply {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (x : M) [topological_add_group Mβ‚‚] : coe_fn (-f) x = -coe_fn f x := rfl @[simp] theorem coe_neg {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) [topological_add_group Mβ‚‚] : ↑(-f) = -↑f := rfl theorem coe_neg' {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) [topological_add_group Mβ‚‚] : ⇑(-f) = -⇑f := rfl protected instance has_sub {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [topological_add_group Mβ‚‚] : Sub (continuous_linear_map R M Mβ‚‚) := { sub := fun (f g : continuous_linear_map R M Mβ‚‚) => mk (↑f - ↑g) } protected instance add_comm_group {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [topological_add_group Mβ‚‚] : add_comm_group (continuous_linear_map R M Mβ‚‚) := add_comm_group.mk Add.add sorry 0 sorry sorry Neg.neg Sub.sub sorry sorry theorem sub_apply {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (g : continuous_linear_map R M Mβ‚‚) [topological_add_group Mβ‚‚] (x : M) : coe_fn (f - g) x = coe_fn f x - coe_fn g x := rfl @[simp] theorem coe_sub {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (g : continuous_linear_map R M Mβ‚‚) [topological_add_group Mβ‚‚] : ↑(f - g) = ↑f - ↑g := rfl @[simp] theorem coe_sub' {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_map R M Mβ‚‚) (g : continuous_linear_map R M Mβ‚‚) [topological_add_group Mβ‚‚] : ⇑(f - g) = ⇑f - ⇑g := rfl protected instance ring {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] [topological_add_group M] : ring (continuous_linear_map R M M) := ring.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry Mul.mul sorry 1 sorry sorry sorry sorry theorem smul_right_one_pow {R : Type u_1} [ring R] [topological_space R] [topological_add_group R] [topological_semimodule R R] (c : R) (n : β„•) : smul_right 1 c ^ n = smul_right 1 (c ^ n) := sorry /-- Given a right inverse `fβ‚‚ : Mβ‚‚ β†’L[R] M` to `f₁ : M β†’L[R] Mβ‚‚`, `proj_ker_of_right_inverse f₁ fβ‚‚ h` is the projection `M β†’L[R] f₁.ker` along `fβ‚‚.range`. -/ def proj_ker_of_right_inverse {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [topological_add_group M] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M) (h : function.right_inverse ⇑fβ‚‚ ⇑f₁) : continuous_linear_map R M β†₯(ker f₁) := cod_restrict (id R M - comp fβ‚‚ f₁) (ker f₁) sorry @[simp] theorem coe_proj_ker_of_right_inverse_apply {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [topological_add_group M] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M) (h : function.right_inverse ⇑fβ‚‚ ⇑f₁) (x : M) : ↑(coe_fn (proj_ker_of_right_inverse f₁ fβ‚‚ h) x) = x - coe_fn fβ‚‚ (coe_fn f₁ x) := rfl @[simp] theorem proj_ker_of_right_inverse_apply_idem {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [topological_add_group M] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M) (h : function.right_inverse ⇑fβ‚‚ ⇑f₁) (x : β†₯(ker f₁)) : coe_fn (proj_ker_of_right_inverse f₁ fβ‚‚ h) ↑x = x := sorry @[simp] theorem proj_ker_of_right_inverse_comp_inv {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] [topological_add_group M] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M) (h : function.right_inverse ⇑fβ‚‚ ⇑f₁) (y : Mβ‚‚) : coe_fn (proj_ker_of_right_inverse f₁ fβ‚‚ h) (coe_fn fβ‚‚ y) = 0 := sorry protected instance has_scalar {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {M₃ : Type u_4} [topological_space M₃] [add_comm_group M₃] [module R M] [module R M₃] [topological_module R M₃] : has_scalar R (continuous_linear_map R M M₃) := has_scalar.mk fun (c : R) (f : continuous_linear_map R M M₃) => mk (c β€’ ↑f) @[simp] theorem smul_comp {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_group M₃] [module R M] [module R Mβ‚‚] [module R M₃] [topological_module R M₃] (c : R) (h : continuous_linear_map R Mβ‚‚ M₃) (f : continuous_linear_map R M Mβ‚‚) : comp (c β€’ h) f = c β€’ comp h f := rfl @[simp] theorem smul_apply {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [module R M] [module R Mβ‚‚] (c : R) (f : continuous_linear_map R M Mβ‚‚) (x : M) [topological_module R Mβ‚‚] : coe_fn (c β€’ f) x = c β€’ coe_fn f x := rfl @[simp] theorem coe_apply {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [module R M] [module R Mβ‚‚] (c : R) (f : continuous_linear_map R M Mβ‚‚) [topological_module R Mβ‚‚] : ↑(c β€’ f) = c β€’ ↑f := rfl theorem coe_apply' {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [module R M] [module R Mβ‚‚] (c : R) (f : continuous_linear_map R M Mβ‚‚) [topological_module R Mβ‚‚] : ⇑(c β€’ f) = c β€’ ⇑f := rfl @[simp] theorem comp_smul {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_group M₃] [module R M] [module R Mβ‚‚] [module R M₃] [topological_module R M₃] (c : R) (h : continuous_linear_map R Mβ‚‚ M₃) (f : continuous_linear_map R M Mβ‚‚) [topological_module R Mβ‚‚] : comp h (c β€’ f) = c β€’ comp h f := sorry protected instance module {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [module R M] [module R Mβ‚‚] [topological_module R Mβ‚‚] [topological_add_group Mβ‚‚] : module R (continuous_linear_map R M Mβ‚‚) := semimodule.mk sorry sorry protected instance algebra {R : Type u_1} [comm_ring R] [topological_space R] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [module R Mβ‚‚] [topological_module R Mβ‚‚] [topological_add_group Mβ‚‚] : algebra R (continuous_linear_map R Mβ‚‚ Mβ‚‚) := algebra.of_semimodule' sorry sorry /-- Given `c : E β†’L[π•œ] π•œ`, `c.smul_rightβ‚—` is the linear map from `F` to `E β†’L[π•œ] F` sending `f` to `Ξ» e, c e β€’ f`. See also `continuous_linear_map.smul_rightL`. -/ def smul_rightβ‚— {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [module R M] [module R Mβ‚‚] [topological_module R Mβ‚‚] [topological_add_group Mβ‚‚] (c : continuous_linear_map R M R) : linear_map R Mβ‚‚ (continuous_linear_map R M Mβ‚‚) := linear_map.mk (smul_right c) sorry sorry end continuous_linear_map namespace continuous_linear_equiv /-- A continuous linear equivalence induces a continuous linear map. -/ def to_continuous_linear_map {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : continuous_linear_map R M Mβ‚‚ := continuous_linear_map.mk (linear_map.mk (linear_map.to_fun (linear_equiv.to_linear_map (to_linear_equiv e))) sorry sorry) /-- Coerce continuous linear equivs to continuous linear maps. -/ protected instance continuous_linear_map.has_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : has_coe (continuous_linear_equiv R M Mβ‚‚) (continuous_linear_map R M Mβ‚‚) := has_coe.mk to_continuous_linear_map /-- Coerce continuous linear equivs to maps. -/ -- see Note [function coercion] protected instance has_coe_to_fun {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] : has_coe_to_fun (continuous_linear_equiv R M Mβ‚‚) := has_coe_to_fun.mk (fun (_x : continuous_linear_equiv R M Mβ‚‚) => M β†’ Mβ‚‚) fun (f : continuous_linear_equiv R M Mβ‚‚) => ⇑f @[simp] theorem coe_def_rev {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : to_continuous_linear_map e = ↑e := rfl @[simp] theorem coe_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) (b : M) : coe_fn (↑e) b = coe_fn e b := rfl @[simp] theorem coe_to_linear_equiv {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f : continuous_linear_equiv R M Mβ‚‚) : ⇑(to_linear_equiv f) = ⇑f := rfl theorem coe_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : ⇑↑e = ⇑e := rfl theorem ext {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] {f : continuous_linear_equiv R M Mβ‚‚} {g : continuous_linear_equiv R M Mβ‚‚} (h : ⇑f = ⇑g) : f = g := sorry /-- A continuous linear equivalence induces a homeomorphism. -/ def to_homeomorph {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : M β‰ƒβ‚œ Mβ‚‚ := homeomorph.mk (equiv.mk (linear_equiv.to_fun (to_linear_equiv e)) (linear_equiv.inv_fun (to_linear_equiv e)) sorry sorry) -- Make some straightforward lemmas available to `simp`. @[simp] theorem map_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : coe_fn e 0 = 0 := continuous_linear_map.map_zero ↑e @[simp] theorem map_add {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) (x : M) (y : M) : coe_fn e (x + y) = coe_fn e x + coe_fn e y := continuous_linear_map.map_add (↑e) x y @[simp] theorem map_smul {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) (c : R) (x : M) : coe_fn e (c β€’ x) = c β€’ coe_fn e x := continuous_linear_map.map_smul c (↑e) x @[simp] theorem map_eq_zero_iff {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) {x : M} : coe_fn e x = 0 ↔ x = 0 := linear_equiv.map_eq_zero_iff (to_linear_equiv e) protected theorem continuous {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : continuous ⇑e := continuous_to_fun e protected theorem continuous_on {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) {s : set M} : continuous_on (⇑e) s := continuous.continuous_on (continuous_linear_equiv.continuous e) protected theorem continuous_at {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) {x : M} : continuous_at (⇑e) x := continuous.continuous_at (continuous_linear_equiv.continuous e) protected theorem continuous_within_at {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) {s : set M} {x : M} : continuous_within_at (⇑e) s x := continuous.continuous_within_at (continuous_linear_equiv.continuous e) theorem comp_continuous_on_iff {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] {Ξ± : Type u_4} [topological_space Ξ±] (e : continuous_linear_equiv R M Mβ‚‚) {f : Ξ± β†’ M} {s : set Ξ±} : continuous_on (⇑e ∘ f) s ↔ continuous_on f s := homeomorph.comp_continuous_on_iff (to_homeomorph e) f s theorem comp_continuous_iff {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] {Ξ± : Type u_4} [topological_space Ξ±] (e : continuous_linear_equiv R M Mβ‚‚) {f : Ξ± β†’ M} : continuous (⇑e ∘ f) ↔ continuous f := homeomorph.comp_continuous_iff (to_homeomorph e) /-- An extensionality lemma for `R ≃L[R] M`. -/ theorem ext₁ {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_space R] {f : continuous_linear_equiv R R M} {g : continuous_linear_equiv R R M} (h : coe_fn f 1 = coe_fn g 1) : f = g := sorry /-- The identity map as a continuous linear equivalence. -/ protected def refl (R : Type u_1) [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] [semimodule R M] : continuous_linear_equiv R M M := mk (linear_equiv.mk (linear_equiv.to_fun (linear_equiv.refl R M)) sorry sorry (linear_equiv.inv_fun (linear_equiv.refl R M)) sorry sorry) @[simp] theorem coe_refl {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : ↑(continuous_linear_equiv.refl R M) = continuous_linear_map.id R M := rfl @[simp] theorem coe_refl' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : ⇑(continuous_linear_equiv.refl R M) = id := rfl /-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/ protected def symm {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : continuous_linear_equiv R Mβ‚‚ M := mk (linear_equiv.mk (linear_equiv.to_fun (linear_equiv.symm (to_linear_equiv e))) sorry sorry (linear_equiv.inv_fun (linear_equiv.symm (to_linear_equiv e))) sorry sorry) @[simp] theorem symm_to_linear_equiv {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : to_linear_equiv (continuous_linear_equiv.symm e) = linear_equiv.symm (to_linear_equiv e) := linear_equiv.ext fun (x : Mβ‚‚) => Eq.refl (coe_fn (to_linear_equiv (continuous_linear_equiv.symm e)) x) /-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/ protected def trans {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (e₁ : continuous_linear_equiv R M Mβ‚‚) (eβ‚‚ : continuous_linear_equiv R Mβ‚‚ M₃) : continuous_linear_equiv R M M₃ := mk (linear_equiv.mk (linear_equiv.to_fun (linear_equiv.trans (to_linear_equiv e₁) (to_linear_equiv eβ‚‚))) sorry sorry (linear_equiv.inv_fun (linear_equiv.trans (to_linear_equiv e₁) (to_linear_equiv eβ‚‚))) sorry sorry) @[simp] theorem trans_to_linear_equiv {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (e₁ : continuous_linear_equiv R M Mβ‚‚) (eβ‚‚ : continuous_linear_equiv R Mβ‚‚ M₃) : to_linear_equiv (continuous_linear_equiv.trans e₁ eβ‚‚) = linear_equiv.trans (to_linear_equiv e₁) (to_linear_equiv eβ‚‚) := linear_equiv.ext fun (x : M) => Eq.refl (coe_fn (to_linear_equiv (continuous_linear_equiv.trans e₁ eβ‚‚)) x) /-- Product of two continuous linear equivalences. The map comes from `equiv.prod_congr`. -/ def prod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] {Mβ‚„ : Type u_5} [topological_space Mβ‚„] [add_comm_monoid Mβ‚„] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [semimodule R Mβ‚„] (e : continuous_linear_equiv R M Mβ‚‚) (e' : continuous_linear_equiv R M₃ Mβ‚„) : continuous_linear_equiv R (M Γ— M₃) (Mβ‚‚ Γ— Mβ‚„) := mk (linear_equiv.mk (linear_equiv.to_fun (linear_equiv.prod (to_linear_equiv e) (to_linear_equiv e'))) sorry sorry (linear_equiv.inv_fun (linear_equiv.prod (to_linear_equiv e) (to_linear_equiv e'))) sorry sorry) @[simp] theorem prod_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] {Mβ‚„ : Type u_5} [topological_space Mβ‚„] [add_comm_monoid Mβ‚„] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [semimodule R Mβ‚„] (e : continuous_linear_equiv R M Mβ‚‚) (e' : continuous_linear_equiv R M₃ Mβ‚„) (x : M Γ— M₃) : coe_fn (prod e e') x = (coe_fn e (prod.fst x), coe_fn e' (prod.snd x)) := rfl @[simp] theorem coe_prod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] {Mβ‚„ : Type u_5} [topological_space Mβ‚„] [add_comm_monoid Mβ‚„] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [semimodule R Mβ‚„] (e : continuous_linear_equiv R M Mβ‚‚) (e' : continuous_linear_equiv R M₃ Mβ‚„) : ↑(prod e e') = continuous_linear_map.prod_map ↑e ↑e' := rfl theorem bijective {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : function.bijective ⇑e := equiv.bijective (linear_equiv.to_equiv (to_linear_equiv e)) theorem injective {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : function.injective ⇑e := equiv.injective (linear_equiv.to_equiv (to_linear_equiv e)) theorem surjective {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : function.surjective ⇑e := equiv.surjective (linear_equiv.to_equiv (to_linear_equiv e)) @[simp] theorem trans_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (e₁ : continuous_linear_equiv R M Mβ‚‚) (eβ‚‚ : continuous_linear_equiv R Mβ‚‚ M₃) (c : M) : coe_fn (continuous_linear_equiv.trans e₁ eβ‚‚) c = coe_fn eβ‚‚ (coe_fn e₁ c) := rfl @[simp] theorem apply_symm_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) (c : Mβ‚‚) : coe_fn e (coe_fn (continuous_linear_equiv.symm e) c) = c := linear_equiv.right_inv (to_linear_equiv e) c @[simp] theorem symm_apply_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) (b : M) : coe_fn (continuous_linear_equiv.symm e) (coe_fn e b) = b := linear_equiv.left_inv (to_linear_equiv e) b @[simp] theorem symm_trans_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (e₁ : continuous_linear_equiv R Mβ‚‚ M) (eβ‚‚ : continuous_linear_equiv R M₃ Mβ‚‚) (c : M) : coe_fn (continuous_linear_equiv.symm (continuous_linear_equiv.trans eβ‚‚ e₁)) c = coe_fn (continuous_linear_equiv.symm eβ‚‚) (coe_fn (continuous_linear_equiv.symm e₁) c) := rfl @[simp] theorem comp_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_monoid M₃] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] (f : continuous_linear_equiv R M Mβ‚‚) (f' : continuous_linear_equiv R Mβ‚‚ M₃) : continuous_linear_map.comp ↑f' ↑f = ↑(continuous_linear_equiv.trans f f') := rfl @[simp] theorem coe_comp_coe_symm {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : continuous_linear_map.comp ↑e ↑(continuous_linear_equiv.symm e) = continuous_linear_map.id R Mβ‚‚ := continuous_linear_map.ext (apply_symm_apply e) @[simp] theorem coe_symm_comp_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : continuous_linear_map.comp ↑(continuous_linear_equiv.symm e) ↑e = continuous_linear_map.id R M := continuous_linear_map.ext (symm_apply_apply e) theorem symm_comp_self {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : ⇑(continuous_linear_equiv.symm e) ∘ ⇑e = id := funext fun (x : M) => symm_apply_apply e x theorem self_comp_symm {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : ⇑e ∘ ⇑(continuous_linear_equiv.symm e) = id := funext fun (x : Mβ‚‚) => apply_symm_apply e x @[simp] theorem symm_comp_self' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : ⇑↑(continuous_linear_equiv.symm e) ∘ ⇑↑e = id := symm_comp_self e @[simp] theorem self_comp_symm' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : ⇑↑e ∘ ⇑↑(continuous_linear_equiv.symm e) = id := self_comp_symm e @[simp] theorem symm_symm {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) : continuous_linear_equiv.symm (continuous_linear_equiv.symm e) = e := ext (funext fun (x : M) => Eq.refl (coe_fn (continuous_linear_equiv.symm (continuous_linear_equiv.symm e)) x)) @[simp] theorem refl_symm {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : continuous_linear_equiv.symm (continuous_linear_equiv.refl R M) = continuous_linear_equiv.refl R M := rfl theorem symm_symm_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) (x : M) : coe_fn (continuous_linear_equiv.symm (continuous_linear_equiv.symm e)) x = coe_fn e x := rfl theorem symm_apply_eq {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) {x : Mβ‚‚} {y : M} : coe_fn (continuous_linear_equiv.symm e) x = y ↔ x = coe_fn e y := linear_equiv.symm_apply_eq (to_linear_equiv e) theorem eq_symm_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) {x : Mβ‚‚} {y : M} : y = coe_fn (continuous_linear_equiv.symm e) x ↔ coe_fn e y = x := linear_equiv.eq_symm_apply (to_linear_equiv e) /-- Create a `continuous_linear_equiv` from two `continuous_linear_map`s that are inverse of each other. -/ def equiv_of_inverse {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M) (h₁ : function.left_inverse ⇑fβ‚‚ ⇑f₁) (hβ‚‚ : function.right_inverse ⇑fβ‚‚ ⇑f₁) : continuous_linear_equiv R M Mβ‚‚ := mk (linear_equiv.mk ⇑f₁ sorry sorry (⇑fβ‚‚) h₁ hβ‚‚) @[simp] theorem equiv_of_inverse_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M) (h₁ : function.left_inverse ⇑fβ‚‚ ⇑f₁) (hβ‚‚ : function.right_inverse ⇑fβ‚‚ ⇑f₁) (x : M) : coe_fn (equiv_of_inverse f₁ fβ‚‚ h₁ hβ‚‚) x = coe_fn f₁ x := rfl @[simp] theorem symm_equiv_of_inverse {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_monoid Mβ‚‚] [semimodule R M] [semimodule R Mβ‚‚] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M) (h₁ : function.left_inverse ⇑fβ‚‚ ⇑f₁) (hβ‚‚ : function.right_inverse ⇑fβ‚‚ ⇑f₁) : continuous_linear_equiv.symm (equiv_of_inverse f₁ fβ‚‚ h₁ hβ‚‚) = equiv_of_inverse fβ‚‚ f₁ hβ‚‚ h₁ := rfl /-- The continuous linear equivalences from `M` to itself form a group under composition. -/ protected instance automorphism_group {R : Type u_1} [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] [semimodule R M] : group (continuous_linear_equiv R M M) := group.mk (fun (f g : continuous_linear_equiv R M M) => continuous_linear_equiv.trans g f) sorry (continuous_linear_equiv.refl R M) sorry sorry (fun (f : continuous_linear_equiv R M M) => continuous_linear_equiv.symm f) (div_inv_monoid.div._default (fun (f g : continuous_linear_equiv R M M) => continuous_linear_equiv.trans g f) sorry (continuous_linear_equiv.refl R M) sorry sorry fun (f : continuous_linear_equiv R M M) => continuous_linear_equiv.symm f) sorry /-- Equivalence given by a block lower diagonal matrix. `e` and `e'` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ def skew_prod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_group M₃] {Mβ‚„ : Type u_5} [topological_space Mβ‚„] [add_comm_group Mβ‚„] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [semimodule R Mβ‚„] [topological_add_group Mβ‚„] (e : continuous_linear_equiv R M Mβ‚‚) (e' : continuous_linear_equiv R M₃ Mβ‚„) (f : continuous_linear_map R M Mβ‚„) : continuous_linear_equiv R (M Γ— M₃) (Mβ‚‚ Γ— Mβ‚„) := mk (linear_equiv.mk (linear_equiv.to_fun (linear_equiv.skew_prod (to_linear_equiv e) (to_linear_equiv e') ↑f)) sorry sorry (linear_equiv.inv_fun (linear_equiv.skew_prod (to_linear_equiv e) (to_linear_equiv e') ↑f)) sorry sorry) @[simp] theorem skew_prod_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_group M₃] {Mβ‚„ : Type u_5} [topological_space Mβ‚„] [add_comm_group Mβ‚„] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [semimodule R Mβ‚„] [topological_add_group Mβ‚„] (e : continuous_linear_equiv R M Mβ‚‚) (e' : continuous_linear_equiv R M₃ Mβ‚„) (f : continuous_linear_map R M Mβ‚„) (x : M Γ— M₃) : coe_fn (skew_prod e e' f) x = (coe_fn e (prod.fst x), coe_fn e' (prod.snd x) + coe_fn f (prod.fst x)) := rfl @[simp] theorem skew_prod_symm_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] {M₃ : Type u_4} [topological_space M₃] [add_comm_group M₃] {Mβ‚„ : Type u_5} [topological_space Mβ‚„] [add_comm_group Mβ‚„] [semimodule R M] [semimodule R Mβ‚‚] [semimodule R M₃] [semimodule R Mβ‚„] [topological_add_group Mβ‚„] (e : continuous_linear_equiv R M Mβ‚‚) (e' : continuous_linear_equiv R M₃ Mβ‚„) (f : continuous_linear_map R M Mβ‚„) (x : Mβ‚‚ Γ— Mβ‚„) : coe_fn (continuous_linear_equiv.symm (skew_prod e e' f)) x = (coe_fn (continuous_linear_equiv.symm e) (prod.fst x), coe_fn (continuous_linear_equiv.symm e') (prod.snd x - coe_fn f (coe_fn (continuous_linear_equiv.symm e) (prod.fst x)))) := rfl @[simp] theorem map_sub {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) (x : M) (y : M) : coe_fn e (x - y) = coe_fn e x - coe_fn e y := continuous_linear_map.map_sub (↑e) x y @[simp] theorem map_neg {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) (x : M) : coe_fn e (-x) = -coe_fn e x := continuous_linear_map.map_neg (↑e) x /-! The next theorems cover the identification between `M ≃L[π•œ] M`and the group of units of the ring `M β†’L[R] M`. -/ /-- An invertible continuous linear map `f` determines a continuous equivalence from `M` to itself. -/ def of_unit {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] [topological_add_group M] (f : units (continuous_linear_map R M M)) : continuous_linear_equiv R M M := mk (linear_equiv.mk ⇑(units.val f) sorry sorry ⇑(units.inv f) sorry sorry) /-- A continuous equivalence from `M` to itself determines an invertible continuous linear map. -/ def to_unit {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] [topological_add_group M] (f : continuous_linear_equiv R M M) : units (continuous_linear_map R M M) := units.mk ↑f ↑(continuous_linear_equiv.symm f) sorry sorry /-- The units of the algebra of continuous `R`-linear endomorphisms of `M` is multiplicatively equivalent to the type of continuous linear equivalences between `M` and itself. -/ def units_equiv (R : Type u_1) [ring R] (M : Type u_2) [topological_space M] [add_comm_group M] [semimodule R M] [topological_add_group M] : units (continuous_linear_map R M M) ≃* continuous_linear_equiv R M M := mul_equiv.mk of_unit to_unit sorry sorry sorry @[simp] theorem units_equiv_apply (R : Type u_1) [ring R] (M : Type u_2) [topological_space M] [add_comm_group M] [semimodule R M] [topological_add_group M] (f : units (continuous_linear_map R M M)) (x : M) : coe_fn (coe_fn (units_equiv R M) f) x = coe_fn f x := rfl /-- Continuous linear equivalences `R ≃L[R] R` are enumerated by `units R`. -/ def units_equiv_aut (R : Type u_1) [ring R] [topological_space R] [topological_module R R] : units R ≃ continuous_linear_equiv R R R := equiv.mk (fun (u : units R) => equiv_of_inverse (continuous_linear_map.smul_right 1 ↑u) (continuous_linear_map.smul_right 1 ↑(u⁻¹)) sorry sorry) (fun (e : continuous_linear_equiv R R R) => units.mk (coe_fn e 1) (coe_fn (continuous_linear_equiv.symm e) 1) sorry sorry) sorry sorry @[simp] theorem units_equiv_aut_apply {R : Type u_1} [ring R] [topological_space R] [topological_module R R] (u : units R) (x : R) : coe_fn (coe_fn (units_equiv_aut R) u) x = x * ↑u := rfl @[simp] theorem units_equiv_aut_apply_symm {R : Type u_1} [ring R] [topological_space R] [topological_module R R] (u : units R) (x : R) : coe_fn (continuous_linear_equiv.symm (coe_fn (units_equiv_aut R) u)) x = x * ↑(u⁻¹) := rfl @[simp] theorem units_equiv_aut_symm_apply {R : Type u_1} [ring R] [topological_space R] [topological_module R R] (e : continuous_linear_equiv R R R) : ↑(coe_fn (equiv.symm (units_equiv_aut R)) e) = coe_fn e 1 := rfl /-- A pair of continuous linear maps such that `f₁ ∘ fβ‚‚ = id` generates a continuous linear equivalence `e` between `M` and `Mβ‚‚ Γ— f₁.ker` such that `(e x).2 = x` for `x ∈ f₁.ker`, `(e x).1 = f₁ x`, and `(e (fβ‚‚ y)).2 = 0`. The map is given by `e x = (f₁ x, x - fβ‚‚ (f₁ x))`. -/ def equiv_of_right_inverse {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R Mβ‚‚] [topological_add_group M] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M) (h : function.right_inverse ⇑fβ‚‚ ⇑f₁) : continuous_linear_equiv R M (Mβ‚‚ Γ— β†₯(continuous_linear_map.ker f₁)) := equiv_of_inverse (continuous_linear_map.prod f₁ (continuous_linear_map.proj_ker_of_right_inverse f₁ fβ‚‚ h)) (continuous_linear_map.coprod fβ‚‚ (continuous_linear_map.subtype_val (continuous_linear_map.ker f₁))) sorry sorry @[simp] theorem fst_equiv_of_right_inverse {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R Mβ‚‚] [topological_add_group M] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M) (h : function.right_inverse ⇑fβ‚‚ ⇑f₁) (x : M) : prod.fst (coe_fn (equiv_of_right_inverse f₁ fβ‚‚ h) x) = coe_fn f₁ x := rfl @[simp] theorem snd_equiv_of_right_inverse {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R Mβ‚‚] [topological_add_group M] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M) (h : function.right_inverse ⇑fβ‚‚ ⇑f₁) (x : M) : ↑(prod.snd (coe_fn (equiv_of_right_inverse f₁ fβ‚‚ h) x)) = x - coe_fn fβ‚‚ (coe_fn f₁ x) := rfl @[simp] theorem equiv_of_right_inverse_symm_apply {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [semimodule R Mβ‚‚] [topological_add_group M] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M) (h : function.right_inverse ⇑fβ‚‚ ⇑f₁) (y : Mβ‚‚ Γ— β†₯(continuous_linear_map.ker f₁)) : coe_fn (continuous_linear_equiv.symm (equiv_of_right_inverse f₁ fβ‚‚ h)) y = coe_fn fβ‚‚ (prod.fst y) + ↑(prod.snd y) := rfl end continuous_linear_equiv namespace continuous_linear_map /-- Introduce a function `inverse` from `M β†’L[R] Mβ‚‚` to `Mβ‚‚ β†’L[R] M`, which sends `f` to `f.symm` if `f` is a continuous linear equivalence and to `0` otherwise. This definition is somewhat ad hoc, but one needs a fully (rather than partially) defined inverse function for some purposes, including for calculus. -/ def inverse {R : Type u_1} {M : Type u_2} {Mβ‚‚ : Type u_3} [topological_space M] [topological_space Mβ‚‚] [semiring R] [add_comm_monoid Mβ‚‚] [semimodule R Mβ‚‚] [add_comm_monoid M] [semimodule R M] : continuous_linear_map R M Mβ‚‚ β†’ continuous_linear_map R Mβ‚‚ M := fun (f : continuous_linear_map R M Mβ‚‚) => dite (βˆƒ (e : continuous_linear_equiv R M Mβ‚‚), ↑e = f) (fun (h : βˆƒ (e : continuous_linear_equiv R M Mβ‚‚), ↑e = f) => ↑(continuous_linear_equiv.symm (classical.some h))) fun (h : Β¬βˆƒ (e : continuous_linear_equiv R M Mβ‚‚), ↑e = f) => 0 /-- By definition, if `f` is invertible then `inverse f = f.symm`. -/ @[simp] theorem inverse_equiv {R : Type u_1} {M : Type u_2} {Mβ‚‚ : Type u_3} [topological_space M] [topological_space Mβ‚‚] [semiring R] [add_comm_monoid Mβ‚‚] [semimodule R Mβ‚‚] [add_comm_monoid M] [semimodule R M] (e : continuous_linear_equiv R M Mβ‚‚) : inverse ↑e = ↑(continuous_linear_equiv.symm e) := sorry /-- By definition, if `f` is not invertible then `inverse f = 0`. -/ @[simp] theorem inverse_non_equiv {R : Type u_1} {M : Type u_2} {Mβ‚‚ : Type u_3} [topological_space M] [topological_space Mβ‚‚] [semiring R] [add_comm_monoid Mβ‚‚] [semimodule R Mβ‚‚] [add_comm_monoid M] [semimodule R M] (f : continuous_linear_map R M Mβ‚‚) (h : Β¬βˆƒ (e' : continuous_linear_equiv R M Mβ‚‚), ↑e' = f) : inverse f = 0 := dif_neg h @[simp] theorem ring_inverse_equiv {R : Type u_1} {M : Type u_2} [topological_space M] [ring R] [add_comm_group M] [topological_add_group M] [module R M] (e : continuous_linear_equiv R M M) : ring.inverse ↑e = inverse ↑e := sorry /-- The function `continuous_linear_equiv.inverse` can be written in terms of `ring.inverse` for the ring of self-maps of the domain. -/ theorem to_ring_inverse {R : Type u_1} {M : Type u_2} {Mβ‚‚ : Type u_3} [topological_space M] [topological_space Mβ‚‚] [ring R] [add_comm_group M] [topological_add_group M] [module R M] [add_comm_group Mβ‚‚] [module R Mβ‚‚] (e : continuous_linear_equiv R M Mβ‚‚) (f : continuous_linear_map R M Mβ‚‚) : inverse f = comp (ring.inverse (comp (↑(continuous_linear_equiv.symm e)) f)) ↑(continuous_linear_equiv.symm e) := sorry theorem ring_inverse_eq_map_inverse {R : Type u_1} {M : Type u_2} [topological_space M] [ring R] [add_comm_group M] [topological_add_group M] [module R M] : ring.inverse = inverse := sorry end continuous_linear_map namespace submodule /-- A submodule `p` is called *complemented* if there exists a continuous projection `M β†’β‚—[R] p`. -/ def closed_complemented {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [module R M] (p : submodule R M) := βˆƒ (f : continuous_linear_map R M β†₯p), βˆ€ (x : β†₯p), coe_fn f ↑x = x theorem closed_complemented.has_closed_complement {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [module R M] {p : submodule R M} [t1_space β†₯p] (h : closed_complemented p) : βˆƒ (q : submodule R M), βˆƒ (hq : is_closed ↑q), is_compl p q := sorry protected theorem closed_complemented.is_closed {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [module R M] [topological_add_group M] [t1_space M] {p : submodule R M} (h : closed_complemented p) : is_closed ↑p := sorry @[simp] theorem closed_complemented_bot {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [module R M] : closed_complemented βŠ₯ := sorry @[simp] theorem closed_complemented_top {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [module R M] : closed_complemented ⊀ := sorry end submodule theorem continuous_linear_map.closed_complemented_ker_of_right_inverse {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ‚‚ : Type u_3} [topological_space Mβ‚‚] [add_comm_group Mβ‚‚] [module R M] [module R Mβ‚‚] [topological_add_group M] (f₁ : continuous_linear_map R M Mβ‚‚) (fβ‚‚ : continuous_linear_map R Mβ‚‚ M) (h : function.right_inverse ⇑fβ‚‚ ⇑f₁) : submodule.closed_complemented (continuous_linear_map.ker f₁) := Exists.intro (continuous_linear_map.proj_ker_of_right_inverse f₁ fβ‚‚ h) (continuous_linear_map.proj_ker_of_right_inverse_apply_idem f₁ fβ‚‚ h)
5f13aa1372284f10a49a6d711ce89ef4f15624a3
4727251e0cd73359b15b664c3170e5d754078599
/src/data/ordmap/ordset.lean
b0aacf4dd1846b0a629fdd0d38169db044018260
[ "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
69,248
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.ordmap.ordnode import algebra.order.ring import data.nat.dist import tactic.linarith /-! # Verification of the `ordnode Ξ±` datatype This file proves the correctness of the operations in `data.ordmap.ordnode`. The public facing version is the type `ordset Ξ±`, which is a wrapper around `ordnode Ξ±` which includes the correctness invariant of the type, and it exposes parallel operations like `insert` as functions on `ordset` that do the same thing but bundle the correctness proofs. The advantage is that it is possible to, for example, prove that the result of `find` on `insert` will actually find the element, while `ordnode` cannot guarantee this if the input tree did not satisfy the type invariants. ## Main definitions * `ordset Ξ±`: A well formed set of values of type `Ξ±` ## Implementation notes The majority of this file is actually in the `ordnode` namespace, because we first have to prove the correctness of all the operations (and defining what correctness means here is actually somewhat subtle). So all the actual `ordset` operations are at the very end, once we have all the theorems. An `ordnode Ξ±` is an inductive type which describes a tree which stores the `size` at internal nodes. The correctness invariant of an `ordnode Ξ±` is: * `ordnode.sized t`: All internal `size` fields must match the actual measured size of the tree. (This is not hard to satisfy.) * `ordnode.balanced t`: Unless the tree has the form `()` or `((a) b)` or `(a (b))` (that is, nil or a single singleton subtree), the two subtrees must satisfy `size l ≀ Ξ΄ * size r` and `size r ≀ Ξ΄ * size l`, where `Ξ΄ := 3` is a global parameter of the data structure (and this property must hold recursively at subtrees). This is why we say this is a "size balanced tree" data structure. * `ordnode.bounded lo hi t`: The members of the tree must be in strictly increasing order, meaning that if `a` is in the left subtree and `b` is the root, then `a ≀ b` and `Β¬ (b ≀ a)`. We enforce this using `ordnode.bounded` which includes also a global upper and lower bound. Because the `ordnode` file was ported from Haskell, the correctness invariants of some of the functions have not been spelled out, and some theorems like `ordnode.valid'.balance_l_aux` show very intricate assumptions on the sizes, which may need to be revised if it turns out some operations violate these assumptions, because there is a decent amount of slop in the actual data structure invariants, so the theorem will go through with multiple choices of assumption. **Note:** This file is incomplete, in the sense that the intent is to have verified versions and lemmas about all the definitions in `ordnode.lean`, but at the moment only a few operations are verified (the hard part should be out of the way, but still). Contributors are encouraged to pick this up and finish the job, if it appeals to you. ## Tags ordered map, ordered set, data structure, verified programming -/ variable {Ξ± : Type*} namespace ordnode /-! ### delta and ratio -/ theorem not_le_delta {s} (H : 1 ≀ s) : Β¬ s ≀ delta * 0 := not_le_of_gt H theorem delta_lt_false {a b : β„•} (h₁ : delta * a < b) (hβ‚‚ : delta * b < a) : false := not_le_of_lt (lt_trans ((mul_lt_mul_left dec_trivial).2 h₁) hβ‚‚) $ by simpa [mul_assoc] using nat.mul_le_mul_right a (dec_trivial : 1 ≀ delta * delta) /-! ### `singleton` -/ /-! ### `size` and `empty` -/ /-- O(n). Computes the actual number of elements in the set, ignoring the cached `size` field. -/ def real_size : ordnode Ξ± β†’ β„• | nil := 0 | (node _ l _ r) := real_size l + real_size r + 1 /-! ### `sized` -/ /-- The `sized` property asserts that all the `size` fields in nodes match the actual size of the respective subtrees. -/ def sized : ordnode Ξ± β†’ Prop | nil := true | (node s l _ r) := s = size l + size r + 1 ∧ sized l ∧ sized r theorem sized.node' {l x r} (hl : @sized Ξ± l) (hr : sized r) : sized (node' l x r) := ⟨rfl, hl, hr⟩ theorem sized.eq_node' {s l x r} (h : @sized Ξ± (node s l x r)) : node s l x r = node' l x r := by rw h.1; refl theorem sized.size_eq {s l x r} (H : sized (@node Ξ± s l x r)) : size (@node Ξ± s l x r) = size l + size r + 1 := H.1 @[elab_as_eliminator] theorem sized.induction {t} (hl : @sized Ξ± t) {C : ordnode Ξ± β†’ Prop} (H0 : C nil) (H1 : βˆ€ l x r, C l β†’ C r β†’ C (node' l x r)) : C t := begin induction t, {exact H0}, rw hl.eq_node', exact H1 _ _ _ (t_ih_l hl.2.1) (t_ih_r hl.2.2) end theorem size_eq_real_size : βˆ€ {t : ordnode Ξ±}, sized t β†’ size t = real_size t | nil _ := rfl | (node s l x r) ⟨h₁, hβ‚‚, hβ‚ƒβŸ© := by rw [size, h₁, size_eq_real_size hβ‚‚, size_eq_real_size h₃]; refl @[simp] theorem sized.size_eq_zero {t : ordnode Ξ±} (ht : sized t) : size t = 0 ↔ t = nil := by cases t; [simp, simp [ht.1]] theorem sized.pos {s l x r} (h : sized (@node Ξ± s l x r)) : 0 < s := by rw h.1; apply nat.le_add_left /-! `dual` -/ theorem dual_dual : βˆ€ (t : ordnode Ξ±), dual (dual t) = t | nil := rfl | (node s l x r) := by rw [dual, dual, dual_dual, dual_dual] @[simp] theorem size_dual (t : ordnode Ξ±) : size (dual t) = size t := by cases t; refl /-! `balanced` -/ /-- The `balanced_sz l r` asserts that a hypothetical tree with children of sizes `l` and `r` is balanced: either `l ≀ Ξ΄ * r` and `r ≀ Ξ΄ * r`, or the tree is trivial with a singleton on one side and nothing on the other. -/ def balanced_sz (l r : β„•) : Prop := l + r ≀ 1 ∨ (l ≀ delta * r ∧ r ≀ delta * l) instance balanced_sz.dec : decidable_rel balanced_sz := Ξ» l r, or.decidable /-- The `balanced t` asserts that the tree `t` satisfies the balance invariants (at every level). -/ def balanced : ordnode Ξ± β†’ Prop | nil := true | (node _ l _ r) := balanced_sz (size l) (size r) ∧ balanced l ∧ balanced r instance balanced.dec : decidable_pred (@balanced Ξ±) | t := by induction t; unfold balanced; resetI; apply_instance theorem balanced_sz.symm {l r : β„•} : balanced_sz l r β†’ balanced_sz r l := or.imp (by rw add_comm; exact id) and.symm theorem balanced_sz_zero {l : β„•} : balanced_sz l 0 ↔ l ≀ 1 := by simp [balanced_sz] { contextual := tt } theorem balanced_sz_up {l r₁ rβ‚‚ : β„•} (h₁ : r₁ ≀ rβ‚‚) (hβ‚‚ : l + rβ‚‚ ≀ 1 ∨ rβ‚‚ ≀ delta * l) (H : balanced_sz l r₁) : balanced_sz l rβ‚‚ := begin refine or_iff_not_imp_left.2 (Ξ» h, _), refine ⟨_, hβ‚‚.resolve_left h⟩, cases H, { cases rβ‚‚, { cases h (le_trans (nat.add_le_add_left (nat.zero_le _) _) H) }, { exact le_trans (le_trans (nat.le_add_right _ _) H) (nat.le_add_left 1 _) } }, { exact le_trans H.1 (nat.mul_le_mul_left _ h₁) } end theorem balanced_sz_down {l r₁ rβ‚‚ : β„•} (h₁ : r₁ ≀ rβ‚‚) (hβ‚‚ : l + rβ‚‚ ≀ 1 ∨ l ≀ delta * r₁) (H : balanced_sz l rβ‚‚) : balanced_sz l r₁ := have l + rβ‚‚ ≀ 1 β†’ balanced_sz l r₁, from Ξ» H, or.inl (le_trans (nat.add_le_add_left h₁ _) H), or.cases_on H this (Ξ» H, or.cases_on hβ‚‚ this (Ξ» hβ‚‚, or.inr ⟨hβ‚‚, le_trans h₁ H.2⟩)) theorem balanced.dual : βˆ€ {t : ordnode Ξ±}, balanced t β†’ balanced (dual t) | nil h := ⟨⟩ | (node s l x r) ⟨b, bl, br⟩ := ⟨by rw [size_dual, size_dual]; exact b.symm, br.dual, bl.dual⟩ /-! ### `rotate` and `balance` -/ /-- Build a tree from three nodes, left associated (ignores the invariants). -/ def node3_l (l : ordnode Ξ±) (x : Ξ±) (m : ordnode Ξ±) (y : Ξ±) (r : ordnode Ξ±) : ordnode Ξ± := node' (node' l x m) y r /-- Build a tree from three nodes, right associated (ignores the invariants). -/ def node3_r (l : ordnode Ξ±) (x : Ξ±) (m : ordnode Ξ±) (y : Ξ±) (r : ordnode Ξ±) : ordnode Ξ± := node' l x (node' m y r) /-- Build a tree from three nodes, with `a () b -> (a ()) b` and `a (b c) d -> ((a b) (c d))`. -/ def node4_l : ordnode Ξ± β†’ Ξ± β†’ ordnode Ξ± β†’ Ξ± β†’ ordnode Ξ± β†’ ordnode Ξ± | l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r) | l x nil z r := node3_l l x nil z r -- should not happen /-- Build a tree from three nodes, with `a () b -> a (() b)` and `a (b c) d -> ((a b) (c d))`. -/ def node4_r : ordnode Ξ± β†’ Ξ± β†’ ordnode Ξ± β†’ Ξ± β†’ ordnode Ξ± β†’ ordnode Ξ± | l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r) | l x nil z r := node3_r l x nil z r -- should not happen /-- Concatenate two nodes, performing a left rotation `x (y z) -> ((x y) z)` if balance is upset. -/ def rotate_l : ordnode Ξ± β†’ Ξ± β†’ ordnode Ξ± β†’ ordnode Ξ± | l x (node _ m y r) := if size m < ratio * size r then node3_l l x m y r else node4_l l x m y r | l x nil := node' l x nil -- should not happen /-- Concatenate two nodes, performing a right rotation `(x y) z -> (x (y z))` if balance is upset. -/ def rotate_r : ordnode Ξ± β†’ Ξ± β†’ ordnode Ξ± β†’ ordnode Ξ± | (node _ l x m) y r := if size m < ratio * size l then node3_r l x m y r else node4_r l x m y r | nil y r := node' nil y r -- should not happen /-- A left balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_l' (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) : ordnode Ξ± := if size l + size r ≀ 1 then node' l x r else if size l > delta * size r then rotate_r l x r else node' l x r /-- A right balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_r' (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) : ordnode Ξ± := if size l + size r ≀ 1 then node' l x r else if size r > delta * size l then rotate_l l x r else node' l x r /-- The full balance operation. This is the same as `balance`, but with less manual inlining. It is somewhat easier to work with this version in proofs. -/ def balance' (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) : ordnode Ξ± := if size l + size r ≀ 1 then node' l x r else if size r > delta * size l then rotate_l l x r else if size l > delta * size r then rotate_r l x r else node' l x r theorem dual_node' (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) : dual (node' l x r) = node' (dual r) x (dual l) := by simp [node', add_comm] theorem dual_node3_l (l : ordnode Ξ±) (x : Ξ±) (m : ordnode Ξ±) (y : Ξ±) (r : ordnode Ξ±) : dual (node3_l l x m y r) = node3_r (dual r) y (dual m) x (dual l) := by simp [node3_l, node3_r, dual_node'] theorem dual_node3_r (l : ordnode Ξ±) (x : Ξ±) (m : ordnode Ξ±) (y : Ξ±) (r : ordnode Ξ±) : dual (node3_r l x m y r) = node3_l (dual r) y (dual m) x (dual l) := by simp [node3_l, node3_r, dual_node'] theorem dual_node4_l (l : ordnode Ξ±) (x : Ξ±) (m : ordnode Ξ±) (y : Ξ±) (r : ordnode Ξ±) : dual (node4_l l x m y r) = node4_r (dual r) y (dual m) x (dual l) := by cases m; simp [node4_l, node4_r, dual_node3_l, dual_node'] theorem dual_node4_r (l : ordnode Ξ±) (x : Ξ±) (m : ordnode Ξ±) (y : Ξ±) (r : ordnode Ξ±) : dual (node4_r l x m y r) = node4_l (dual r) y (dual m) x (dual l) := by cases m; simp [node4_l, node4_r, dual_node3_r, dual_node'] theorem dual_rotate_l (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) : dual (rotate_l l x r) = rotate_r (dual r) x (dual l) := by cases r; simp [rotate_l, rotate_r, dual_node']; split_ifs; simp [dual_node3_l, dual_node4_l] theorem dual_rotate_r (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) : dual (rotate_r l x r) = rotate_l (dual r) x (dual l) := by rw [← dual_dual (rotate_l _ _ _), dual_rotate_l, dual_dual, dual_dual] theorem dual_balance' (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) : dual (balance' l x r) = balance' (dual r) x (dual l) := begin simp [balance', add_comm], split_ifs; simp [dual_node', dual_rotate_l, dual_rotate_r], cases delta_lt_false h_1 h_2 end theorem dual_balance_l (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) : dual (balance_l l x r) = balance_r (dual r) x (dual l) := begin unfold balance_l balance_r, cases r with rs rl rx rr, { cases l with ls ll lx lr, {refl}, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; dsimp only [dual]; try {refl}, split_ifs; repeat {simp [h, add_comm]} }, { cases l with ls ll lx lr, {refl}, dsimp only [dual], split_ifs, swap, {simp [add_comm]}, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; try {refl}, dsimp only [dual], split_ifs; simp [h, add_comm] }, end theorem dual_balance_r (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) : dual (balance_r l x r) = balance_l (dual r) x (dual l) := by rw [← dual_dual (balance_l _ _ _), dual_balance_l, dual_dual, dual_dual] theorem sized.node3_l {l x m y r} (hl : @sized Ξ± l) (hm : sized m) (hr : sized r) : sized (node3_l l x m y r) := (hl.node' hm).node' hr theorem sized.node3_r {l x m y r} (hl : @sized Ξ± l) (hm : sized m) (hr : sized r) : sized (node3_r l x m y r) := hl.node' (hm.node' hr) theorem sized.node4_l {l x m y r} (hl : @sized Ξ± l) (hm : sized m) (hr : sized r) : sized (node4_l l x m y r) := by cases m; [exact (hl.node' hm).node' hr, exact (hl.node' hm.2.1).node' (hm.2.2.node' hr)] theorem node3_l_size {l x m y r} : size (@node3_l Ξ± l x m y r) = size l + size m + size r + 2 := by dsimp [node3_l, node', size]; rw add_right_comm _ 1 theorem node3_r_size {l x m y r} : size (@node3_r Ξ± l x m y r) = size l + size m + size r + 2 := by dsimp [node3_r, node', size]; rw [← add_assoc, ← add_assoc] theorem node4_l_size {l x m y r} (hm : sized m) : size (@node4_l Ξ± l x m y r) = size l + size m + size r + 2 := by cases m; simp [node4_l, node3_l, node', add_comm, add_left_comm]; [skip, simp [size, hm.1]]; rw [← add_assoc, ← bit0]; simp [add_comm, add_left_comm] theorem sized.dual : βˆ€ {t : ordnode Ξ±} (h : sized t), sized (dual t) | nil h := ⟨⟩ | (node s l x r) ⟨rfl, sl, sr⟩ := ⟨by simp [size_dual, add_comm], sized.dual sr, sized.dual sl⟩ theorem sized.dual_iff {t : ordnode Ξ±} : sized (dual t) ↔ sized t := ⟨λ h, by rw ← dual_dual t; exact h.dual, sized.dual⟩ theorem sized.rotate_l {l x r} (hl : @sized Ξ± l) (hr : sized r) : sized (rotate_l l x r) := begin cases r, {exact hl.node' hr}, rw rotate_l, split_ifs, { exact hl.node3_l hr.2.1 hr.2.2 }, { exact hl.node4_l hr.2.1 hr.2.2 } end theorem sized.rotate_r {l x r} (hl : @sized Ξ± l) (hr : sized r) : sized (rotate_r l x r) := sized.dual_iff.1 $ by rw dual_rotate_r; exact hr.dual.rotate_l hl.dual theorem sized.rotate_l_size {l x r} (hm : sized r) : size (@rotate_l Ξ± l x r) = size l + size r + 1 := begin cases r; simp [rotate_l], simp [size, hm.1, add_comm, add_left_comm], rw [← add_assoc, ← bit0], simp, split_ifs; simp [node3_l_size, node4_l_size hm.2.1, add_comm, add_left_comm] end theorem sized.rotate_r_size {l x r} (hl : sized l) : size (@rotate_r Ξ± l x r) = size l + size r + 1 := by rw [← size_dual, dual_rotate_r, hl.dual.rotate_l_size, size_dual, size_dual, add_comm (size l)] theorem sized.balance' {l x r} (hl : @sized Ξ± l) (hr : sized r) : sized (balance' l x r) := begin unfold balance', split_ifs, { exact hl.node' hr }, { exact hl.rotate_l hr }, { exact hl.rotate_r hr }, { exact hl.node' hr } end theorem size_balance' {l x r} (hl : @sized Ξ± l) (hr : sized r) : size (@balance' Ξ± l x r) = size l + size r + 1 := begin unfold balance', split_ifs, { refl }, { exact hr.rotate_l_size }, { exact hl.rotate_r_size }, { refl } end /-! ## `all`, `any`, `emem`, `amem` -/ theorem all.imp {P Q : Ξ± β†’ Prop} (H : βˆ€ a, P a β†’ Q a) : βˆ€ {t}, all P t β†’ all Q t | nil h := ⟨⟩ | (node _ l x r) ⟨h₁, hβ‚‚, hβ‚ƒβŸ© := ⟨h₁.imp, H _ hβ‚‚, h₃.imp⟩ theorem any.imp {P Q : Ξ± β†’ Prop} (H : βˆ€ a, P a β†’ Q a) : βˆ€ {t}, any P t β†’ any Q t | nil := id | (node _ l x r) := or.imp any.imp $ or.imp (H _) any.imp theorem all_singleton {P : Ξ± β†’ Prop} {x : Ξ±} : all P (singleton x) ↔ P x := ⟨λ h, h.2.1, Ξ» h, ⟨⟨⟩, h, ⟨⟩⟩⟩ theorem any_singleton {P : Ξ± β†’ Prop} {x : Ξ±} : any P (singleton x) ↔ P x := ⟨by rintro (⟨⟨⟩⟩ | h | ⟨⟨⟩⟩); exact h, Ξ» h, or.inr (or.inl h)⟩ theorem all_dual {P : Ξ± β†’ Prop} : βˆ€ {t : ordnode Ξ±}, all P (dual t) ↔ all P t | nil := iff.rfl | (node s l x r) := ⟨λ ⟨hr, hx, hl⟩, ⟨all_dual.1 hl, hx, all_dual.1 hr⟩, Ξ» ⟨hl, hx, hr⟩, ⟨all_dual.2 hr, hx, all_dual.2 hl⟩⟩ theorem all_iff_forall {P : Ξ± β†’ Prop} : βˆ€ {t}, all P t ↔ βˆ€ x, emem x t β†’ P x | nil := (iff_true_intro $ by rintro _ ⟨⟩).symm | (node _ l x r) := by simp [all, emem, all_iff_forall, any, or_imp_distrib, forall_and_distrib] theorem any_iff_exists {P : Ξ± β†’ Prop} : βˆ€ {t}, any P t ↔ βˆƒ x, emem x t ∧ P x | nil := ⟨by rintro ⟨⟩, by rintro ⟨_, ⟨⟩, _⟩⟩ | (node _ l x r) := by simp [any, emem, any_iff_exists, or_and_distrib_right, exists_or_distrib] theorem emem_iff_all {x : Ξ±} {t} : emem x t ↔ βˆ€ P, all P t β†’ P x := ⟨λ h P al, all_iff_forall.1 al _ h, Ξ» H, H _ $ all_iff_forall.2 $ Ξ» _, id⟩ theorem all_node' {P l x r} : @all Ξ± P (node' l x r) ↔ all P l ∧ P x ∧ all P r := iff.rfl theorem all_node3_l {P l x m y r} : @all Ξ± P (node3_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by simp [node3_l, all_node', and_assoc] theorem all_node3_r {P l x m y r} : @all Ξ± P (node3_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := iff.rfl theorem all_node4_l {P l x m y r} : @all Ξ± P (node4_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by cases m; simp [node4_l, all_node', all, all_node3_l, and_assoc] theorem all_node4_r {P l x m y r} : @all Ξ± P (node4_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by cases m; simp [node4_r, all_node', all, all_node3_r, and_assoc] theorem all_rotate_l {P l x r} : @all Ξ± P (rotate_l l x r) ↔ all P l ∧ P x ∧ all P r := by cases r; simp [rotate_l, all_node']; split_ifs; simp [all_node3_l, all_node4_l, all] theorem all_rotate_r {P l x r} : @all Ξ± P (rotate_r l x r) ↔ all P l ∧ P x ∧ all P r := by rw [← all_dual, dual_rotate_r, all_rotate_l]; simp [all_dual, and_comm, and.left_comm] theorem all_balance' {P l x r} : @all Ξ± P (balance' l x r) ↔ all P l ∧ P x ∧ all P r := by rw balance'; split_ifs; simp [all_node', all_rotate_l, all_rotate_r] /-! ### `to_list` -/ theorem foldr_cons_eq_to_list : βˆ€ (t : ordnode Ξ±) (r : list Ξ±), t.foldr list.cons r = to_list t ++ r | nil r := rfl | (node _ l x r) r' := by rw [foldr, foldr_cons_eq_to_list, foldr_cons_eq_to_list, ← list.cons_append, ← list.append_assoc, ← foldr_cons_eq_to_list]; refl @[simp] theorem to_list_nil : to_list (@nil Ξ±) = [] := rfl @[simp] theorem to_list_node (s l x r) : to_list (@node Ξ± s l x r) = to_list l ++ x :: to_list r := by rw [to_list, foldr, foldr_cons_eq_to_list]; refl theorem emem_iff_mem_to_list {x : Ξ±} {t} : emem x t ↔ x ∈ to_list t := by unfold emem; induction t; simp [any, *, or_assoc] theorem length_to_list' : βˆ€ t : ordnode Ξ±, (to_list t).length = t.real_size | nil := rfl | (node _ l _ r) := by rw [to_list_node, list.length_append, list.length_cons, length_to_list', length_to_list']; refl theorem length_to_list {t : ordnode Ξ±} (h : sized t) : (to_list t).length = t.size := by rw [length_to_list', size_eq_real_size h] theorem equiv_iff {t₁ tβ‚‚ : ordnode Ξ±} (h₁ : sized t₁) (hβ‚‚ : sized tβ‚‚) : equiv t₁ tβ‚‚ ↔ to_list t₁ = to_list tβ‚‚ := and_iff_right_of_imp $ Ξ» h, by rw [← length_to_list h₁, h, length_to_list hβ‚‚] /-! ### `mem` -/ theorem pos_size_of_mem [has_le Ξ±] [@decidable_rel Ξ± (≀)] {x : Ξ±} {t : ordnode Ξ±} (h : sized t) (h_mem : x ∈ t) : 0 < size t := by { cases t, { contradiction }, { simp [h.1] } } /-! ### `(find/erase/split)_(min/max)` -/ theorem find_min'_dual : βˆ€ t (x : Ξ±), find_min' (dual t) x = find_max' x t | nil x := rfl | (node _ l x r) _ := find_min'_dual r x theorem find_max'_dual (t) (x : Ξ±) : find_max' x (dual t) = find_min' t x := by rw [← find_min'_dual, dual_dual] theorem find_min_dual : βˆ€ t : ordnode Ξ±, find_min (dual t) = find_max t | nil := rfl | (node _ l x r) := congr_arg some $ find_min'_dual _ _ theorem find_max_dual (t : ordnode Ξ±) : find_max (dual t) = find_min t := by rw [← find_min_dual, dual_dual] theorem dual_erase_min : βˆ€ t : ordnode Ξ±, dual (erase_min t) = erase_max (dual t) | nil := rfl | (node _ nil x r) := rfl | (node _ l@(node _ _ _ _) x r) := by rw [erase_min, dual_balance_r, dual_erase_min, dual, dual, dual, erase_max] theorem dual_erase_max (t : ordnode Ξ±) : dual (erase_max t) = erase_min (dual t) := by rw [← dual_dual (erase_min _), dual_erase_min, dual_dual] theorem split_min_eq : βˆ€ s l (x : Ξ±) r, split_min' l x r = (find_min' l x, erase_min (node s l x r)) | _ nil x r := rfl | _ (node ls ll lx lr) x r := by rw [split_min', split_min_eq, split_min', find_min', erase_min] theorem split_max_eq : βˆ€ s l (x : Ξ±) r, split_max' l x r = (erase_max (node s l x r), find_max' x r) | _ l x nil := rfl | _ l x (node ls ll lx lr) := by rw [split_max', split_max_eq, split_max', find_max', erase_max] @[elab_as_eliminator] theorem find_min'_all {P : Ξ± β†’ Prop} : βˆ€ t (x : Ξ±), all P t β†’ P x β†’ P (find_min' t x) | nil x h hx := hx | (node _ ll lx lr) x ⟨h₁, hβ‚‚, hβ‚ƒβŸ© hx := find_min'_all _ _ h₁ hβ‚‚ @[elab_as_eliminator] theorem find_max'_all {P : Ξ± β†’ Prop} : βˆ€ (x : Ξ±) t, P x β†’ all P t β†’ P (find_max' x t) | x nil hx h := hx | x (node _ ll lx lr) hx ⟨h₁, hβ‚‚, hβ‚ƒβŸ© := find_max'_all _ _ hβ‚‚ h₃ /-! ### `glue` -/ /-! ### `merge` -/ @[simp] theorem merge_nil_left (t : ordnode Ξ±) : merge t nil = t := by cases t; refl @[simp] theorem merge_nil_right (t : ordnode Ξ±) : merge nil t = t := rfl @[simp] theorem merge_node {ls ll lx lr rs rl rx rr} : merge (@node Ξ± ls ll lx lr) (node rs rl rx rr) = if delta * ls < rs then balance_l (merge (node ls ll lx lr) rl) rx rr else if delta * rs < ls then balance_r ll lx (merge lr (node rs rl rx rr)) else glue (node ls ll lx lr) (node rs rl rx rr) := rfl /-! ### `insert` -/ theorem dual_insert [preorder Ξ±] [is_total Ξ± (≀)] [@decidable_rel Ξ± (≀)] (x : Ξ±) : βˆ€ t : ordnode Ξ±, dual (ordnode.insert x t) = @ordnode.insert Ξ±α΅’α΅ˆ _ _ x (dual t) | nil := rfl | (node _ l y r) := begin rw [ordnode.insert, dual, ordnode.insert, order_dual.cmp_le_flip, ← cmp_le_swap x y], cases cmp_le x y; simp [ordering.swap, ordnode.insert, dual_balance_l, dual_balance_r, dual_insert] end /-! ### `balance` properties -/ theorem balance_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) : @balance Ξ± l x r = balance' l x r := begin cases l with ls ll lx lr, { cases r with rs rl rx rr, { refl }, { rw sr.eq_node' at hr ⊒, cases rl with rls rll rlx rlr; cases rr with rrs rrl rrx rrr; dsimp [balance, balance'], { refl }, { have : size rrl = 0 ∧ size rrr = 0, { have := balanced_sz_zero.1 hr.1.symm, rwa [size, sr.2.2.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.2.2.1.size_eq_zero.1 this.1, cases sr.2.2.2.2.size_eq_zero.1 this.2, obtain rfl : rrs = 1 := sr.2.2.1, rw [if_neg, if_pos, rotate_l, if_pos], {refl}, all_goals {exact dec_trivial} }, { have : size rll = 0 ∧ size rlr = 0, { have := balanced_sz_zero.1 hr.1, rwa [size, sr.2.1.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.1.2.1.size_eq_zero.1 this.1, cases sr.2.1.2.2.size_eq_zero.1 this.2, obtain rfl : rls = 1 := sr.2.1.1, rw [if_neg, if_pos, rotate_l, if_neg], {refl}, all_goals {exact dec_trivial} }, { symmetry, rw [zero_add, if_neg, if_pos, rotate_l], { split_ifs, { simp [node3_l, node', add_comm, add_left_comm] }, { simp [node4_l, node', sr.2.1.1, add_comm, add_left_comm] } }, { exact dec_trivial }, { exact not_le_of_gt (nat.succ_lt_succ (add_pos sr.2.1.pos sr.2.2.pos)) } } } }, { cases r with rs rl rx rr, { rw sl.eq_node' at hl ⊒, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; dsimp [balance, balance'], { refl }, { have : size lrl = 0 ∧ size lrr = 0, { have := balanced_sz_zero.1 hl.1.symm, rwa [size, sl.2.2.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sl.2.2.2.1.size_eq_zero.1 this.1, cases sl.2.2.2.2.size_eq_zero.1 this.2, obtain rfl : lrs = 1 := sl.2.2.1, rw [if_neg, if_neg, if_pos, rotate_r, if_neg], {refl}, all_goals {exact dec_trivial} }, { have : size lll = 0 ∧ size llr = 0, { have := balanced_sz_zero.1 hl.1, rwa [size, sl.2.1.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sl.2.1.2.1.size_eq_zero.1 this.1, cases sl.2.1.2.2.size_eq_zero.1 this.2, obtain rfl : lls = 1 := sl.2.1.1, rw [if_neg, if_neg, if_pos, rotate_r, if_pos], {refl}, all_goals {exact dec_trivial} }, { symmetry, rw [if_neg, if_neg, if_pos, rotate_r], { split_ifs, { simp [node3_r, node', add_comm, add_left_comm] }, { simp [node4_r, node', sl.2.2.1, add_comm, add_left_comm] } }, { exact dec_trivial }, { exact dec_trivial }, { exact not_le_of_gt (nat.succ_lt_succ (add_pos sl.2.1.pos sl.2.2.pos)) } } }, { simp [balance, balance'], symmetry, rw [if_neg], { split_ifs, { have rd : delta ≀ size rl + size rr, { have := lt_of_le_of_lt (nat.mul_le_mul_left _ sl.pos) h, rwa [sr.1, nat.lt_succ_iff] at this }, cases rl with rls rll rlx rlr, { rw [size, zero_add] at rd, exact absurd (le_trans rd (balanced_sz_zero.1 hr.1.symm)) dec_trivial }, cases rr with rrs rrl rrx rrr, { exact absurd (le_trans rd (balanced_sz_zero.1 hr.1)) dec_trivial }, dsimp [rotate_l], split_ifs, { simp [node3_l, node', sr.1, add_comm, add_left_comm] }, { simp [node4_l, node', sr.1, sr.2.1.1, add_comm, add_left_comm] } }, { have ld : delta ≀ size ll + size lr, { have := lt_of_le_of_lt (nat.mul_le_mul_left _ sr.pos) h_1, rwa [sl.1, nat.lt_succ_iff] at this }, cases ll with lls lll llx llr, { rw [size, zero_add] at ld, exact absurd (le_trans ld (balanced_sz_zero.1 hl.1.symm)) dec_trivial }, cases lr with lrs lrl lrx lrr, { exact absurd (le_trans ld (balanced_sz_zero.1 hl.1)) dec_trivial }, dsimp [rotate_r], split_ifs, { simp [node3_r, node', sl.1, add_comm, add_left_comm] }, { simp [node4_r, node', sl.1, sl.2.2.1, add_comm, add_left_comm] } }, { simp [node'] } }, { exact not_le_of_gt (add_le_add sl.pos sr.pos : 2 ≀ ls + rs) } } } end theorem balance_l_eq_balance {l x r} (sl : sized l) (sr : sized r) (H1 : size l = 0 β†’ size r ≀ 1) (H2 : 1 ≀ size l β†’ 1 ≀ size r β†’ size r ≀ delta * size l) : @balance_l Ξ± l x r = balance l x r := begin cases r with rs rl rx rr, { refl }, { cases l with ls ll lx lr, { have : size rl = 0 ∧ size rr = 0, { have := H1 rfl, rwa [size, sr.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.1.size_eq_zero.1 this.1, cases sr.2.2.size_eq_zero.1 this.2, rw sr.eq_node', refl }, { replace H2 : Β¬ rs > delta * ls := not_lt_of_le (H2 sl.pos sr.pos), simp [balance_l, balance, H2]; split_ifs; simp [add_comm] } } end /-- `raised n m` means `m` is either equal or one up from `n`. -/ def raised (n m : β„•) : Prop := m = n ∨ m = n + 1 theorem raised_iff {n m} : raised n m ↔ n ≀ m ∧ m ≀ n + 1 := begin split, rintro (rfl | rfl), { exact ⟨le_rfl, nat.le_succ _⟩ }, { exact ⟨nat.le_succ _, le_rfl⟩ }, { rintro ⟨h₁, hβ‚‚βŸ©, rcases eq_or_lt_of_le h₁ with rfl | h₁, { exact or.inl rfl }, { exact or.inr (le_antisymm hβ‚‚ h₁) } } end theorem raised.dist_le {n m} (H : raised n m) : nat.dist n m ≀ 1 := by cases raised_iff.1 H with H1 H2; rwa [nat.dist_eq_sub_of_le H1, tsub_le_iff_left] theorem raised.dist_le' {n m} (H : raised n m) : nat.dist m n ≀ 1 := by rw nat.dist_comm; exact H.dist_le theorem raised.add_left (k) {n m} (H : raised n m) : raised (k + n) (k + m) := begin rcases H with rfl | rfl, { exact or.inl rfl }, { exact or.inr rfl } end theorem raised.add_right (k) {n m} (H : raised n m) : raised (n + k) (m + k) := by rw [add_comm, add_comm m]; exact H.add_left _ theorem raised.right {l x₁ xβ‚‚ r₁ rβ‚‚} (H : raised (size r₁) (size rβ‚‚)) : raised (size (@node' Ξ± l x₁ r₁)) (size (@node' Ξ± l xβ‚‚ rβ‚‚)) := begin dsimp [node', size], generalize_hyp : size rβ‚‚ = m at H ⊒, rcases H with rfl | rfl, { exact or.inl rfl }, { exact or.inr rfl } end theorem balance_l_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (βˆƒ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (βˆƒ r', raised (size r) r' ∧ balanced_sz (size l) r')) : @balance_l Ξ± l x r = balance' l x r := begin rw [← balance_eq_balance' hl hr sl sr, balance_l_eq_balance sl sr], { intro l0, rw l0 at H, rcases H with ⟨_, ⟨⟨⟩⟩|⟨⟨⟩⟩, H⟩ | ⟨r', e, H⟩, { exact balanced_sz_zero.1 H.symm }, exact le_trans (raised_iff.1 e).1 (balanced_sz_zero.1 H.symm) }, { intros l1 r1, rcases H with ⟨l', e, H | ⟨H₁, Hβ‚‚βŸ©βŸ© | ⟨r', e, H | ⟨H₁, Hβ‚‚βŸ©βŸ©, { exact le_trans (le_trans (nat.le_add_left _ _) H) (mul_pos dec_trivial l1 : (0:β„•)<_) }, { exact le_trans Hβ‚‚ (nat.mul_le_mul_left _ (raised_iff.1 e).1) }, { cases raised_iff.1 e, unfold delta, linarith }, { exact le_trans (raised_iff.1 e).1 Hβ‚‚ } } end theorem balance_sz_dual {l r} (H : (βˆƒ l', raised (@size Ξ± l) l' ∧ balanced_sz l' (@size Ξ± r)) ∨ βˆƒ r', raised r' (size r) ∧ balanced_sz (size l) r') : (βˆƒ l', raised l' (size (dual r)) ∧ balanced_sz l' (size (dual l))) ∨ βˆƒ r', raised (size (dual l)) r' ∧ balanced_sz (size (dual r)) r' := begin rw [size_dual, size_dual], exact H.symm.imp (Exists.imp $ Ξ» _, and.imp_right balanced_sz.symm) (Exists.imp $ Ξ» _, and.imp_right balanced_sz.symm) end theorem size_balance_l {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (βˆƒ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (βˆƒ r', raised (size r) r' ∧ balanced_sz (size l) r')) : size (@balance_l Ξ± l x r) = size l + size r + 1 := by rw [balance_l_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balance_l {P l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (βˆƒ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (βˆƒ r', raised (size r) r' ∧ balanced_sz (size l) r')) : all P (@balance_l Ξ± l x r) ↔ all P l ∧ P x ∧ all P r := by rw [balance_l_eq_balance' hl hr sl sr H, all_balance'] theorem balance_r_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (βˆƒ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (βˆƒ r', raised r' (size r) ∧ balanced_sz (size l) r')) : @balance_r Ξ± l x r = balance' l x r := by rw [← dual_dual (balance_r l x r), dual_balance_r, balance_l_eq_balance' hr.dual hl.dual sr.dual sl.dual (balance_sz_dual H), ← dual_balance', dual_dual] theorem size_balance_r {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (βˆƒ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (βˆƒ r', raised r' (size r) ∧ balanced_sz (size l) r')) : size (@balance_r Ξ± l x r) = size l + size r + 1 := by rw [balance_r_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balance_r {P l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (βˆƒ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (βˆƒ r', raised r' (size r) ∧ balanced_sz (size l) r')) : all P (@balance_r Ξ± l x r) ↔ all P l ∧ P x ∧ all P r := by rw [balance_r_eq_balance' hl hr sl sr H, all_balance'] /-! ### `bounded` -/ section variable [preorder Ξ±] /-- `bounded t lo hi` says that every element `x ∈ t` is in the range `lo < x < hi`, and also this property holds recursively in subtrees, making the full tree a BST. The bounds can be set to `lo = βŠ₯` and `hi = ⊀` if we care only about the internal ordering constraints. -/ def bounded : ordnode Ξ± β†’ with_bot Ξ± β†’ with_top Ξ± β†’ Prop | nil (some a) (some b) := a < b | nil _ _ := true | (node _ l x r) o₁ oβ‚‚ := bounded l o₁ ↑x ∧ bounded r ↑x oβ‚‚ theorem bounded.dual : βˆ€ {t : ordnode Ξ±} {o₁ oβ‚‚} (h : bounded t o₁ oβ‚‚), @bounded Ξ±α΅’α΅ˆ _ (dual t) oβ‚‚ o₁ | nil o₁ oβ‚‚ h := by cases o₁; cases oβ‚‚; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨or.dual, ol.dual⟩ theorem bounded.dual_iff {t : ordnode Ξ±} {o₁ oβ‚‚} : bounded t o₁ oβ‚‚ ↔ @bounded Ξ±α΅’α΅ˆ _ (dual t) oβ‚‚ o₁ := ⟨bounded.dual, Ξ» h, by have := bounded.dual h; rwa [dual_dual, order_dual.preorder.dual_dual] at this⟩ theorem bounded.weak_left : βˆ€ {t : ordnode Ξ±} {o₁ oβ‚‚}, bounded t o₁ oβ‚‚ β†’ bounded t βŠ₯ oβ‚‚ | nil o₁ oβ‚‚ h := by cases oβ‚‚; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨ol.weak_left, or⟩ theorem bounded.weak_right : βˆ€ {t : ordnode Ξ±} {o₁ oβ‚‚}, bounded t o₁ oβ‚‚ β†’ bounded t o₁ ⊀ | nil o₁ oβ‚‚ h := by cases o₁; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨ol, or.weak_right⟩ theorem bounded.weak {t : ordnode Ξ±} {o₁ oβ‚‚} (h : bounded t o₁ oβ‚‚) : bounded t βŠ₯ ⊀ := h.weak_left.weak_right theorem bounded.mono_left {x y : Ξ±} (xy : x ≀ y) : βˆ€ {t : ordnode Ξ±} {o}, bounded t ↑y o β†’ bounded t ↑x o | nil none h := ⟨⟩ | nil (some z) h := lt_of_le_of_lt xy h | (node s l z r) o ⟨ol, or⟩ := ⟨ol.mono_left, or⟩ theorem bounded.mono_right {x y : Ξ±} (xy : x ≀ y) : βˆ€ {t : ordnode Ξ±} {o}, bounded t o ↑x β†’ bounded t o ↑y | nil none h := ⟨⟩ | nil (some z) h := lt_of_lt_of_le h xy | (node s l z r) o ⟨ol, or⟩ := ⟨ol, or.mono_right⟩ theorem bounded.to_lt : βˆ€ {t : ordnode Ξ±} {x y : Ξ±}, bounded t x y β†’ x < y | nil x y h := h | (node _ l y r) x z ⟨h₁, hβ‚‚βŸ© := lt_trans h₁.to_lt hβ‚‚.to_lt theorem bounded.to_nil {t : ordnode Ξ±} : βˆ€ {o₁ oβ‚‚}, bounded t o₁ oβ‚‚ β†’ bounded nil o₁ oβ‚‚ | none _ h := ⟨⟩ | (some _) none h := ⟨⟩ | (some x) (some y) h := h.to_lt theorem bounded.trans_left {t₁ tβ‚‚ : ordnode Ξ±} {x : Ξ±} : βˆ€ {o₁ oβ‚‚}, bounded t₁ o₁ ↑x β†’ bounded tβ‚‚ ↑x oβ‚‚ β†’ bounded tβ‚‚ o₁ oβ‚‚ | none oβ‚‚ h₁ hβ‚‚ := hβ‚‚.weak_left | (some y) oβ‚‚ h₁ hβ‚‚ := hβ‚‚.mono_left (le_of_lt h₁.to_lt) theorem bounded.trans_right {t₁ tβ‚‚ : ordnode Ξ±} {x : Ξ±} : βˆ€ {o₁ oβ‚‚}, bounded t₁ o₁ ↑x β†’ bounded tβ‚‚ ↑x oβ‚‚ β†’ bounded t₁ o₁ oβ‚‚ | o₁ none h₁ hβ‚‚ := h₁.weak_right | o₁ (some y) h₁ hβ‚‚ := h₁.mono_right (le_of_lt hβ‚‚.to_lt) theorem bounded.mem_lt : βˆ€ {t o} {x : Ξ±}, bounded t o ↑x β†’ all (< x) t | nil o x _ := ⟨⟩ | (node _ l y r) o x ⟨h₁, hβ‚‚βŸ© := ⟨h₁.mem_lt.imp (Ξ» z h, lt_trans h hβ‚‚.to_lt), hβ‚‚.to_lt, hβ‚‚.mem_lt⟩ theorem bounded.mem_gt : βˆ€ {t o} {x : Ξ±}, bounded t ↑x o β†’ all (> x) t | nil o x _ := ⟨⟩ | (node _ l y r) o x ⟨h₁, hβ‚‚βŸ© := ⟨h₁.mem_gt, h₁.to_lt, hβ‚‚.mem_gt.imp (Ξ» z, lt_trans h₁.to_lt)⟩ theorem bounded.of_lt : βˆ€ {t o₁ oβ‚‚} {x : Ξ±}, bounded t o₁ oβ‚‚ β†’ bounded nil o₁ ↑x β†’ all (< x) t β†’ bounded t o₁ ↑x | nil o₁ oβ‚‚ x _ hn _ := hn | (node _ l y r) o₁ oβ‚‚ x ⟨h₁, hβ‚‚βŸ© hn ⟨al₁, alβ‚‚, alβ‚ƒβŸ© := ⟨h₁, hβ‚‚.of_lt alβ‚‚ alβ‚ƒβŸ© theorem bounded.of_gt : βˆ€ {t o₁ oβ‚‚} {x : Ξ±}, bounded t o₁ oβ‚‚ β†’ bounded nil ↑x oβ‚‚ β†’ all (> x) t β†’ bounded t ↑x oβ‚‚ | nil o₁ oβ‚‚ x _ hn _ := hn | (node _ l y r) o₁ oβ‚‚ x ⟨h₁, hβ‚‚βŸ© hn ⟨al₁, alβ‚‚, alβ‚ƒβŸ© := ⟨h₁.of_gt alβ‚‚ al₁, hβ‚‚βŸ© theorem bounded.to_sep {t₁ tβ‚‚ o₁ oβ‚‚} {x : Ξ±} (h₁ : bounded t₁ o₁ ↑x) (hβ‚‚ : bounded tβ‚‚ ↑x oβ‚‚) : t₁.all (Ξ» y, tβ‚‚.all (Ξ» z : Ξ±, y < z)) := h₁.mem_lt.imp $ Ξ» y yx, hβ‚‚.mem_gt.imp $ Ξ» z xz, lt_trans yx xz end /-! ### `valid` -/ section variable [preorder Ξ±] /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. This version of `valid` also puts all elements in the tree in the interval `(lo, hi)`. -/ structure valid' (lo : with_bot Ξ±) (t : ordnode Ξ±) (hi : with_top Ξ±) : Prop := (ord : t.bounded lo hi) (sz : t.sized) (bal : t.balanced) /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. -/ def valid (t : ordnode Ξ±) : Prop := valid' βŠ₯ t ⊀ theorem valid'.mono_left {x y : Ξ±} (xy : x ≀ y) {t : ordnode Ξ±} {o} (h : valid' ↑y t o) : valid' ↑x t o := ⟨h.1.mono_left xy, h.2, h.3⟩ theorem valid'.mono_right {x y : Ξ±} (xy : x ≀ y) {t : ordnode Ξ±} {o} (h : valid' o t ↑x) : valid' o t ↑y := ⟨h.1.mono_right xy, h.2, h.3⟩ theorem valid'.trans_left {t₁ tβ‚‚ : ordnode Ξ±} {x : Ξ±} {o₁ oβ‚‚} (h : bounded t₁ o₁ ↑x) (H : valid' ↑x tβ‚‚ oβ‚‚) : valid' o₁ tβ‚‚ oβ‚‚ := ⟨h.trans_left H.1, H.2, H.3⟩ theorem valid'.trans_right {t₁ tβ‚‚ : ordnode Ξ±} {x : Ξ±} {o₁ oβ‚‚} (H : valid' o₁ t₁ ↑x) (h : bounded tβ‚‚ ↑x oβ‚‚) : valid' o₁ t₁ oβ‚‚ := ⟨H.1.trans_right h, H.2, H.3⟩ theorem valid'.of_lt {t : ordnode Ξ±} {x : Ξ±} {o₁ oβ‚‚} (H : valid' o₁ t oβ‚‚) (h₁ : bounded nil o₁ ↑x) (hβ‚‚ : all (< x) t) : valid' o₁ t ↑x := ⟨H.1.of_lt h₁ hβ‚‚, H.2, H.3⟩ theorem valid'.of_gt {t : ordnode Ξ±} {x : Ξ±} {o₁ oβ‚‚} (H : valid' o₁ t oβ‚‚) (h₁ : bounded nil ↑x oβ‚‚) (hβ‚‚ : all (> x) t) : valid' ↑x t oβ‚‚ := ⟨H.1.of_gt h₁ hβ‚‚, H.2, H.3⟩ theorem valid'.valid {t o₁ oβ‚‚} (h : @valid' Ξ± _ o₁ t oβ‚‚) : valid t := ⟨h.1.weak, h.2, h.3⟩ theorem valid'_nil {o₁ oβ‚‚} (h : bounded nil o₁ oβ‚‚) : valid' o₁ (@nil Ξ±) oβ‚‚ := ⟨h, ⟨⟩, ⟨⟩⟩ theorem valid_nil : valid (@nil Ξ±) := valid'_nil ⟨⟩ theorem valid'.node {s l x r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r oβ‚‚) (H : balanced_sz (size l) (size r)) (hs : s = size l + size r + 1) : valid' o₁ (@node Ξ± s l x r) oβ‚‚ := ⟨⟨hl.1, hr.1⟩, ⟨hs, hl.2, hr.2⟩, ⟨H, hl.3, hr.3⟩⟩ theorem valid'.dual : βˆ€ {t : ordnode Ξ±} {o₁ oβ‚‚} (h : valid' o₁ t oβ‚‚), @valid' Ξ±α΅’α΅ˆ _ oβ‚‚ (dual t) o₁ | nil o₁ oβ‚‚ h := valid'_nil h.1.dual | (node s l x r) o₁ oβ‚‚ ⟨⟨ol, or⟩, ⟨rfl, sl, sr⟩, ⟨b, bl, br⟩⟩ := let ⟨ol', sl', bl'⟩ := valid'.dual ⟨ol, sl, bl⟩, ⟨or', sr', br'⟩ := valid'.dual ⟨or, sr, br⟩ in ⟨⟨or', ol'⟩, ⟨by simp [size_dual, add_comm], sr', sl'⟩, ⟨by rw [size_dual, size_dual]; exact b.symm, br', bl'⟩⟩ theorem valid'.dual_iff {t : ordnode Ξ±} {o₁ oβ‚‚} : valid' o₁ t oβ‚‚ ↔ @valid' Ξ±α΅’α΅ˆ _ oβ‚‚ (dual t) o₁ := ⟨valid'.dual, Ξ» h, by have := valid'.dual h; rwa [dual_dual, order_dual.preorder.dual_dual] at this⟩ theorem valid.dual {t : ordnode Ξ±} : valid t β†’ @valid Ξ±α΅’α΅ˆ _ (dual t) := valid'.dual theorem valid.dual_iff {t : ordnode Ξ±} : valid t ↔ @valid Ξ±α΅’α΅ˆ _ (dual t) := valid'.dual_iff theorem valid'.left {s l x r o₁ oβ‚‚} (H : valid' o₁ (@node Ξ± s l x r) oβ‚‚) : valid' o₁ l x := ⟨H.1.1, H.2.2.1, H.3.2.1⟩ theorem valid'.right {s l x r o₁ oβ‚‚} (H : valid' o₁ (@node Ξ± s l x r) oβ‚‚) : valid' ↑x r oβ‚‚ := ⟨H.1.2, H.2.2.2, H.3.2.2⟩ theorem valid.left {s l x r} (H : valid (@node Ξ± s l x r)) : valid l := H.left.valid theorem valid.right {s l x r} (H : valid (@node Ξ± s l x r)) : valid r := H.right.valid theorem valid.size_eq {s l x r} (H : valid (@node Ξ± s l x r)) : size (@node Ξ± s l x r) = size l + size r + 1 := H.2.1 theorem valid'.node' {l x r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r oβ‚‚) (H : balanced_sz (size l) (size r)) : valid' o₁ (@node' Ξ± l x r) oβ‚‚ := hl.node hr H rfl theorem valid'_singleton {x : Ξ±} {o₁ oβ‚‚} (h₁ : bounded nil o₁ ↑x) (hβ‚‚ : bounded nil ↑x oβ‚‚) : valid' o₁ (singleton x : ordnode Ξ±) oβ‚‚ := (valid'_nil h₁).node (valid'_nil hβ‚‚) (or.inl zero_le_one) rfl theorem valid_singleton {x : Ξ±} : valid (singleton x : ordnode Ξ±) := valid'_singleton ⟨⟩ ⟨⟩ theorem valid'.node3_l {l x m y r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r oβ‚‚) (H1 : balanced_sz (size l) (size m)) (H2 : balanced_sz (size l + size m + 1) (size r)) : valid' o₁ (@node3_l Ξ± l x m y r) oβ‚‚ := (hl.node' hm H1).node' hr H2 theorem valid'.node3_r {l x m y r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r oβ‚‚) (H1 : balanced_sz (size l) (size m + size r + 1)) (H2 : balanced_sz (size m) (size r)) : valid' o₁ (@node3_r Ξ± l x m y r) oβ‚‚ := hl.node' (hm.node' hr H2) H1 theorem valid'.node4_l_lemma₁ {a b c d : β„•} (lrβ‚‚ : 3 * (b + c + 1 + d) ≀ 16 * a + 9) (mrβ‚‚ : b + c + 1 ≀ 3 * d) (mm₁ : b ≀ 3 * c) : b < 3 * a + 1 := by linarith theorem valid'.node4_l_lemmaβ‚‚ {b c d : β„•} (mrβ‚‚ : b + c + 1 ≀ 3 * d) : c ≀ 3 * d := by linarith theorem valid'.node4_l_lemma₃ {b c d : β„•} (mr₁ : 2 * d ≀ b + c + 1) (mm₁ : b ≀ 3 * c) : d ≀ 3 * c := by linarith theorem valid'.node4_l_lemmaβ‚„ {a b c d : β„•} (lr₁ : 3 * a ≀ b + c + 1 + d) (mrβ‚‚ : b + c + 1 ≀ 3 * d) (mm₁ : b ≀ 3 * c) : a + b + 1 ≀ 3 * (c + d + 1) := by linarith theorem valid'.node4_l_lemmaβ‚… {a b c d : β„•} (lrβ‚‚ : 3 * (b + c + 1 + d) ≀ 16 * a + 9) (mr₁ : 2 * d ≀ b + c + 1) (mmβ‚‚ : c ≀ 3 * b) : c + d + 1 ≀ 3 * (a + b + 1) := by linarith theorem valid'.node4_l {l x m y r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r oβ‚‚) (Hm : 0 < size m) (H : (size l = 0 ∧ size m = 1 ∧ size r ≀ 1) ∨ (0 < size l ∧ ratio * size r ≀ size m ∧ delta * size l ≀ size m + size r ∧ 3 * (size m + size r) ≀ 16 * size l + 9 ∧ size m ≀ delta * size r)) : valid' o₁ (@node4_l Ξ± l x m y r) oβ‚‚ := begin cases m with s ml z mr, {cases Hm}, suffices : balanced_sz (size l) (size ml) ∧ balanced_sz (size mr) (size r) ∧ balanced_sz (size l + size ml + 1) (size mr + size r + 1), from (valid'.node' (hl.node' hm.left this.1) (hm.right.node' hr this.2.1) this.2.2), rcases H with ⟨l0, m1, r0⟩ | ⟨l0, mr₁, lr₁, lrβ‚‚, mrβ‚‚βŸ©, { rw [hm.2.size_eq, nat.succ_inj', add_eq_zero_iff] at m1, rw [l0, m1.1, m1.2], rcases size r with _|_|_; exact dec_trivial }, { cases nat.eq_zero_or_pos (size r) with r0 r0, { rw r0 at mrβ‚‚, cases not_le_of_lt Hm mrβ‚‚ }, rw [hm.2.size_eq] at lr₁ lrβ‚‚ mr₁ mrβ‚‚, by_cases mm : size ml + size mr ≀ 1, { have r1 := le_antisymm ((mul_le_mul_left dec_trivial).1 (le_trans mr₁ (nat.succ_le_succ mm) : _ ≀ ratio * 1)) r0, rw [r1, add_assoc] at lr₁, have l1 := le_antisymm ((mul_le_mul_left dec_trivial).1 (le_trans lr₁ (add_le_add_right mm 2) : _ ≀ delta * 1)) l0, rw [l1, r1], cases size ml; cases size mr, { exact dec_trivial }, { rw zero_add at mm, rcases mm with _|⟨_,⟨⟩⟩, exact dec_trivial }, { rcases mm with _|⟨_,⟨⟩⟩, exact dec_trivial }, { rw nat.succ_add at mm, rcases mm with _|⟨_,⟨⟩⟩ } }, rcases hm.3.1.resolve_left mm with ⟨mm₁, mmβ‚‚βŸ©, cases nat.eq_zero_or_pos (size ml) with ml0 ml0, { rw [ml0, mul_zero, nat.le_zero_iff] at mmβ‚‚, rw [ml0, mmβ‚‚] at mm, cases mm dec_trivial }, have : 2 * size l ≀ size ml + size mr + 1, { have := nat.mul_le_mul_left _ lr₁, rw [mul_left_comm, mul_add] at this, have := le_trans this (add_le_add_left mr₁ _), rw [← nat.succ_mul] at this, exact (mul_le_mul_left dec_trivial).1 this }, refine ⟨or.inr ⟨_, _⟩, or.inr ⟨_, _⟩, or.inr ⟨_, _⟩⟩, { refine (mul_le_mul_left dec_trivial).1 (le_trans this _), rw [two_mul, nat.succ_le_iff], refine add_lt_add_of_lt_of_le _ mmβ‚‚, simpa using (mul_lt_mul_right ml0).2 (dec_trivial:1<3) }, { exact nat.le_of_lt_succ (valid'.node4_l_lemma₁ lrβ‚‚ mrβ‚‚ mm₁) }, { exact valid'.node4_l_lemmaβ‚‚ mrβ‚‚ }, { exact valid'.node4_l_lemma₃ mr₁ mm₁ }, { exact valid'.node4_l_lemmaβ‚„ lr₁ mrβ‚‚ mm₁ }, { exact valid'.node4_l_lemmaβ‚… lrβ‚‚ mr₁ mmβ‚‚ } } end theorem valid'.rotate_l_lemma₁ {a b c : β„•} (H2 : 3 * a ≀ b + c) (hbβ‚‚ : c ≀ 3 * b) : a ≀ 3 * b := by linarith theorem valid'.rotate_l_lemmaβ‚‚ {a b c : β„•} (H3 : 2 * (b + c) ≀ 9 * a + 3) (h : b < 2 * c) : b < 3 * a + 1 := by linarith theorem valid'.rotate_l_lemma₃ {a b c : β„•} (H2 : 3 * a ≀ b + c) (h : b < 2 * c) : a + b < 3 * c := by linarith theorem valid'.rotate_l_lemmaβ‚„ {a b : β„•} (H3 : 2 * b ≀ 9 * a + 3) : 3 * b ≀ 16 * a + 9 := by linarith theorem valid'.rotate_l {l x r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r oβ‚‚) (H1 : Β¬ size l + size r ≀ 1) (H2 : delta * size l < size r) (H3 : 2 * size r ≀ 9 * size l + 5 ∨ size r ≀ 3) : valid' o₁ (@rotate_l Ξ± l x r) oβ‚‚ := begin cases r with rs rl rx rr, {cases H2}, rw [hr.2.size_eq, nat.lt_succ_iff] at H2, rw [hr.2.size_eq] at H3, replace H3 : 2 * (size rl + size rr) ≀ 9 * size l + 3 ∨ size rl + size rr ≀ 2 := H3.imp (@nat.le_of_add_le_add_right 2 _ _) nat.le_of_succ_le_succ, have H3_0 : size l = 0 β†’ size rl + size rr ≀ 2, { intro l0, rw l0 at H3, exact (or_iff_right_of_imp $ by exact Ξ» h, (mul_le_mul_left dec_trivial).1 (le_trans h dec_trivial)).1 H3 }, have H3p : size l > 0 β†’ 2 * (size rl + size rr) ≀ 9 * size l + 3 := Ξ» l0 : 1 ≀ size l, (or_iff_left_of_imp $ by intro; linarith).1 H3, have ablem : βˆ€ {a b : β„•}, 1 ≀ a β†’ a + b ≀ 2 β†’ b ≀ 1, {intros, linarith}, have hlp : size l > 0 β†’ Β¬ size rl + size rr ≀ 1 := Ξ» l0 hb, absurd (le_trans (le_trans (nat.mul_le_mul_left _ l0) H2) hb) dec_trivial, rw rotate_l, split_ifs, { have rr0 : size rr > 0 := (mul_lt_mul_left dec_trivial).1 (lt_of_le_of_lt (nat.zero_le _) h : ratio * 0 < _), suffices : balanced_sz (size l) (size rl) ∧ balanced_sz (size l + size rl + 1) (size rr), { exact hl.node3_l hr.left hr.right this.1 this.2 }, cases nat.eq_zero_or_pos (size l) with l0 l0, { rw l0, replace H3 := H3_0 l0, have := hr.3.1, cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw rl0 at this ⊒, rw le_antisymm (balanced_sz_zero.1 this.symm) rr0, exact dec_trivial }, have rr1 : size rr = 1 := le_antisymm (ablem rl0 H3) rr0, rw add_comm at H3, rw [rr1, show size rl = 1, from le_antisymm (ablem rr0 H3) rl0], exact dec_trivial }, replace H3 := H3p l0, rcases hr.3.1.resolve_left (hlp l0) with ⟨hb₁, hbβ‚‚βŸ©, refine ⟨or.inr ⟨_, _⟩, or.inr ⟨_, _⟩⟩, { exact valid'.rotate_l_lemma₁ H2 hbβ‚‚ }, { exact nat.le_of_lt_succ (valid'.rotate_l_lemmaβ‚‚ H3 h) }, { exact valid'.rotate_l_lemma₃ H2 h }, { exact le_trans hbβ‚‚ (nat.mul_le_mul_left _ $ le_trans (nat.le_add_left _ _) (nat.le_add_right _ _)) } }, { cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw [rl0, not_lt, nat.le_zero_iff, nat.mul_eq_zero] at h, replace h := h.resolve_left dec_trivial, rw [rl0, h, nat.le_zero_iff, nat.mul_eq_zero] at H2, rw [hr.2.size_eq, rl0, h, H2.resolve_left dec_trivial] at H1, cases H1 dec_trivial }, refine hl.node4_l hr.left hr.right rl0 _, cases nat.eq_zero_or_pos (size l) with l0 l0, { replace H3 := H3_0 l0, cases nat.eq_zero_or_pos (size rr) with rr0 rr0, { have := hr.3.1, rw rr0 at this, exact or.inl ⟨l0, le_antisymm (balanced_sz_zero.1 this) rl0, rr0.symm β–Έ zero_le_one⟩ }, exact or.inl ⟨l0, le_antisymm (ablem rr0 $ by rwa add_comm) rl0, ablem rl0 H3⟩ }, exact or.inr ⟨l0, not_lt.1 h, H2, valid'.rotate_l_lemmaβ‚„ (H3p l0), (hr.3.1.resolve_left (hlp l0)).1⟩ } end theorem valid'.rotate_r {l x r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r oβ‚‚) (H1 : Β¬ size l + size r ≀ 1) (H2 : delta * size r < size l) (H3 : 2 * size l ≀ 9 * size r + 5 ∨ size l ≀ 3) : valid' o₁ (@rotate_r Ξ± l x r) oβ‚‚ := begin refine valid'.dual_iff.2 _, rw dual_rotate_r, refine hr.dual.rotate_l hl.dual _ _ _, { rwa [size_dual, size_dual, add_comm] }, { rwa [size_dual, size_dual] }, { rwa [size_dual, size_dual] } end theorem valid'.balance'_aux {l x r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r oβ‚‚) (H₁ : 2 * @size Ξ± r ≀ 9 * size l + 5 ∨ size r ≀ 3) (Hβ‚‚ : 2 * @size Ξ± l ≀ 9 * size r + 5 ∨ size l ≀ 3) : valid' o₁ (@balance' Ξ± l x r) oβ‚‚ := begin rw balance', split_ifs, { exact hl.node' hr (or.inl h) }, { exact hl.rotate_l hr h h_1 H₁ }, { exact hl.rotate_r hr h h_2 Hβ‚‚ }, { exact hl.node' hr (or.inr ⟨not_lt.1 h_2, not_lt.1 h_1⟩) } end theorem valid'.balance'_lemma {Ξ± l l' r r'} (H1 : balanced_sz l' r') (H2 : nat.dist (@size Ξ± l) l' ≀ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≀ 1 ∧ size l = l') : 2 * @size Ξ± r ≀ 9 * size l + 5 ∨ size r ≀ 3 := begin suffices : @size Ξ± r ≀ 3 * (size l + 1), { cases nat.eq_zero_or_pos (size l) with l0 l0, { apply or.inr, rwa l0 at this }, change 1 ≀ _ at l0, apply or.inl, linarith }, rcases H2 with ⟨hl, rfl⟩ | ⟨hr, rfl⟩; rcases H1 with h | ⟨h₁, hβ‚‚βŸ©, { exact le_trans (nat.le_add_left _ _) (le_trans h (nat.le_add_left _ _)) }, { exact le_trans hβ‚‚ (nat.mul_le_mul_left _ $ le_trans (nat.dist_tri_right _ _) (nat.add_le_add_left hl _)) }, { exact le_trans (nat.dist_tri_left' _ _) (le_trans (add_le_add hr (le_trans (nat.le_add_left _ _) h)) dec_trivial) }, { rw nat.mul_succ, exact le_trans (nat.dist_tri_right' _ _) (add_le_add hβ‚‚ (le_trans hr dec_trivial)) }, end theorem valid'.balance' {l x r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r oβ‚‚) (H : βˆƒ l' r', balanced_sz l' r' ∧ (nat.dist (size l) l' ≀ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≀ 1 ∧ size l = l')) : valid' o₁ (@balance' Ξ± l x r) oβ‚‚ := let ⟨l', r', H1, H2⟩ := H in valid'.balance'_aux hl hr (valid'.balance'_lemma H1 H2) (valid'.balance'_lemma H1.symm H2.symm) theorem valid'.balance {l x r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r oβ‚‚) (H : βˆƒ l' r', balanced_sz l' r' ∧ (nat.dist (size l) l' ≀ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≀ 1 ∧ size l = l')) : valid' o₁ (@balance Ξ± l x r) oβ‚‚ := by rw balance_eq_balance' hl.3 hr.3 hl.2 hr.2; exact hl.balance' hr H theorem valid'.balance_l_aux {l x r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r oβ‚‚) (H₁ : size l = 0 β†’ size r ≀ 1) (Hβ‚‚ : 1 ≀ size l β†’ 1 ≀ size r β†’ size r ≀ delta * size l) (H₃ : 2 * @size Ξ± l ≀ 9 * size r + 5 ∨ size l ≀ 3) : valid' o₁ (@balance_l Ξ± l x r) oβ‚‚ := begin rw [balance_l_eq_balance hl.2 hr.2 H₁ Hβ‚‚, balance_eq_balance' hl.3 hr.3 hl.2 hr.2], refine hl.balance'_aux hr (or.inl _) H₃, cases nat.eq_zero_or_pos (size r) with r0 r0, { rw r0, exact nat.zero_le _ }, cases nat.eq_zero_or_pos (size l) with l0 l0, { rw l0, exact le_trans (nat.mul_le_mul_left _ (H₁ l0)) dec_trivial }, replace Hβ‚‚ : _ ≀ 3 * _ := Hβ‚‚ l0 r0, linarith end theorem valid'.balance_l {l x r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r oβ‚‚) (H : (βˆƒ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (βˆƒ r', raised (size r) r' ∧ balanced_sz (size l) r')) : valid' o₁ (@balance_l Ξ± l x r) oβ‚‚ := begin rw balance_l_eq_balance' hl.3 hr.3 hl.2 hr.2 H, refine hl.balance' hr _, rcases H with ⟨l', e, H⟩ | ⟨r', e, H⟩, { exact ⟨_, _, H, or.inl ⟨e.dist_le', rfl⟩⟩ }, { exact ⟨_, _, H, or.inr ⟨e.dist_le, rfl⟩⟩ }, end theorem valid'.balance_r_aux {l x r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r oβ‚‚) (H₁ : size r = 0 β†’ size l ≀ 1) (Hβ‚‚ : 1 ≀ size r β†’ 1 ≀ size l β†’ size l ≀ delta * size r) (H₃ : 2 * @size Ξ± r ≀ 9 * size l + 5 ∨ size r ≀ 3) : valid' o₁ (@balance_r Ξ± l x r) oβ‚‚ := begin rw [valid'.dual_iff, dual_balance_r], have := hr.dual.balance_l_aux hl.dual, rw [size_dual, size_dual] at this, exact this H₁ Hβ‚‚ H₃ end theorem valid'.balance_r {l x r o₁ oβ‚‚} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r oβ‚‚) (H : (βˆƒ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (βˆƒ r', raised r' (size r) ∧ balanced_sz (size l) r')) : valid' o₁ (@balance_r Ξ± l x r) oβ‚‚ := by rw [valid'.dual_iff, dual_balance_r]; exact hr.dual.balance_l hl.dual (balance_sz_dual H) theorem valid'.erase_max_aux {s l x r o₁ oβ‚‚} (H : valid' o₁ (node s l x r) oβ‚‚) : valid' o₁ (@erase_max Ξ± (node' l x r)) ↑(find_max' x r) ∧ size (node' l x r) = size (erase_max (node' l x r)) + 1 := begin have := H.2.eq_node', rw this at H, clear this, induction r with rs rl rx rr IHrl IHrr generalizing l x o₁, { exact ⟨H.left, rfl⟩ }, have := H.2.2.2.eq_node', rw this at H ⊒, rcases IHrr H.right with ⟨h, e⟩, refine ⟨valid'.balance_l H.left h (or.inr ⟨_, or.inr e, H.3.1⟩), _⟩, rw [erase_max, size_balance_l H.3.2.1 h.3 H.2.2.1 h.2 (or.inr ⟨_, or.inr e, H.3.1⟩)], rw [size, e], refl end theorem valid'.erase_min_aux {s l x r o₁ oβ‚‚} (H : valid' o₁ (node s l x r) oβ‚‚) : valid' ↑(find_min' l x) (@erase_min Ξ± (node' l x r)) oβ‚‚ ∧ size (node' l x r) = size (erase_min (node' l x r)) + 1 := by have := H.dual.erase_max_aux; rwa [← dual_node', size_dual, ← dual_erase_min, size_dual, ← valid'.dual_iff, find_max'_dual] at this theorem erase_min.valid : βˆ€ {t} (h : @valid Ξ± _ t), valid (erase_min t) | nil _ := valid_nil | (node _ l x r) h := by rw h.2.eq_node'; exact h.erase_min_aux.1.valid theorem erase_max.valid {t} (h : @valid Ξ± _ t) : valid (erase_max t) := by rw [valid.dual_iff, dual_erase_max]; exact erase_min.valid h.dual theorem valid'.glue_aux {l r o₁ oβ‚‚} (hl : valid' o₁ l oβ‚‚) (hr : valid' o₁ r oβ‚‚) (sep : l.all (Ξ» x, r.all (Ξ» y, x < y))) (bal : balanced_sz (size l) (size r)) : valid' o₁ (@glue Ξ± l r) oβ‚‚ ∧ size (glue l r) = size l + size r := begin cases l with ls ll lx lr, {exact ⟨hr, (zero_add _).symm⟩ }, cases r with rs rl rx rr, {exact ⟨hl, rfl⟩ }, dsimp [glue], split_ifs, { rw [split_max_eq, glue], cases valid'.erase_max_aux hl with v e, suffices H, refine ⟨valid'.balance_r v (hr.of_gt _ _) H, _⟩, { refine find_max'_all lx lr hl.1.2.to_nil (sep.2.2.imp _), exact Ξ» x h, hr.1.2.to_nil.mono_left (le_of_lt h.2.1) }, { exact @find_max'_all _ (Ξ» a, all (> a) (node rs rl rx rr)) lx lr sep.2.1 sep.2.2 }, { rw [size_balance_r v.3 hr.3 v.2 hr.2 H, add_right_comm, ← e, hl.2.1], refl }, { refine or.inl ⟨_, or.inr e, _⟩, rwa hl.2.eq_node' at bal } }, { rw [split_min_eq, glue], cases valid'.erase_min_aux hr with v e, suffices H, refine ⟨valid'.balance_l (hl.of_lt _ _) v H, _⟩, { refine @find_min'_all _ (Ξ» a, bounded nil o₁ ↑a) rl rx (sep.2.1.1.imp _) hr.1.1.to_nil, exact Ξ» y h, hl.1.1.to_nil.mono_right (le_of_lt h) }, { exact @find_min'_all _ (Ξ» a, all (< a) (node ls ll lx lr)) rl rx (all_iff_forall.2 $ Ξ» x hx, sep.imp $ Ξ» y hy, all_iff_forall.1 hy.1 _ hx) (sep.imp $ Ξ» y hy, hy.2.1) }, { rw [size_balance_l hl.3 v.3 hl.2 v.2 H, add_assoc, ← e, hr.2.1], refl }, { refine or.inr ⟨_, or.inr e, _⟩, rwa hr.2.eq_node' at bal } }, end theorem valid'.glue {l x r o₁ oβ‚‚} (hl : valid' o₁ l ↑(x:Ξ±)) (hr : valid' ↑x r oβ‚‚) : balanced_sz (size l) (size r) β†’ valid' o₁ (@glue Ξ± l r) oβ‚‚ ∧ size (@glue Ξ± l r) = size l + size r := valid'.glue_aux (hl.trans_right hr.1) (hr.trans_left hl.1) (hl.1.to_sep hr.1) theorem valid'.merge_lemma {a b c : β„•} (h₁ : 3 * a < b + c + 1) (hβ‚‚ : b ≀ 3 * c) : 2 * (a + b) ≀ 9 * c + 5 := by linarith theorem valid'.merge_aux₁ {o₁ oβ‚‚ ls ll lx lr rs rl rx rr t} (hl : valid' o₁ (@node Ξ± ls ll lx lr) oβ‚‚) (hr : valid' o₁ (node rs rl rx rr) oβ‚‚) (h : delta * ls < rs) (v : valid' o₁ t ↑rx) (e : size t = ls + size rl) : valid' o₁ (balance_l t rx rr) oβ‚‚ ∧ size (balance_l t rx rr) = ls + rs := begin rw hl.2.1 at e, rw [hl.2.1, hr.2.1, delta] at h, rcases hr.3.1 with H|⟨hr₁, hrβ‚‚βŸ©, {linarith}, suffices Hβ‚‚, suffices H₁, refine ⟨valid'.balance_l_aux v hr.right H₁ Hβ‚‚ _, _⟩, { rw e, exact or.inl (valid'.merge_lemma h hr₁) }, { rw [balance_l_eq_balance v.2 hr.2.2.2 H₁ Hβ‚‚, balance_eq_balance' v.3 hr.3.2.2 v.2 hr.2.2.2, size_balance' v.2 hr.2.2.2, e, hl.2.1, hr.2.1], simp [add_comm, add_left_comm] }, { rw [e, add_right_comm], rintro ⟨⟩ }, { intros _ h₁, rw e, unfold delta at hrβ‚‚ ⊒, linarith } end theorem valid'.merge_aux {l r o₁ oβ‚‚} (hl : valid' o₁ l oβ‚‚) (hr : valid' o₁ r oβ‚‚) (sep : l.all (Ξ» x, r.all (Ξ» y, x < y))) : valid' o₁ (@merge Ξ± l r) oβ‚‚ ∧ size (merge l r) = size l + size r := begin induction l with ls ll lx lr IHll IHlr generalizing o₁ oβ‚‚ r, { exact ⟨hr, (zero_add _).symm⟩ }, induction r with rs rl rx rr IHrl IHrr generalizing o₁ oβ‚‚, { exact ⟨hl, rfl⟩ }, rw [merge_node], split_ifs, { cases IHrl (sep.imp $ Ξ» x h, h.1) (hl.of_lt hr.1.1.to_nil $ sep.imp $ Ξ» x h, h.2.1) hr.left with v e, exact valid'.merge_aux₁ hl hr h v e }, { cases IHlr hl.right (hr.of_gt hl.1.2.to_nil sep.2.1) sep.2.2 with v e, have := valid'.merge_aux₁ hr.dual hl.dual h_1 v.dual, rw [size_dual, add_comm, size_dual, ← dual_balance_r, ← valid'.dual_iff, size_dual, add_comm rs] at this, exact this e }, { refine valid'.glue_aux hl hr sep (or.inr ⟨not_lt.1 h_1, not_lt.1 h⟩) } end theorem valid.merge {l r} (hl : valid l) (hr : valid r) (sep : l.all (Ξ» x, r.all (Ξ» y, x < y))) : valid (@merge Ξ± l r) := (valid'.merge_aux hl hr sep).1 theorem insert_with.valid_aux [is_total Ξ± (≀)] [@decidable_rel Ξ± (≀)] (f : Ξ± β†’ Ξ±) (x : Ξ±) (hf : βˆ€ y, x ≀ y ∧ y ≀ x β†’ x ≀ f y ∧ f y ≀ x) : βˆ€ {t o₁ oβ‚‚}, valid' o₁ t oβ‚‚ β†’ bounded nil o₁ ↑x β†’ bounded nil ↑x oβ‚‚ β†’ valid' o₁ (insert_with f x t) oβ‚‚ ∧ raised (size t) (size (insert_with f x t)) | nil o₁ oβ‚‚ _ bl br := ⟨valid'_singleton bl br, or.inr rfl⟩ | (node sz l y r) o₁ oβ‚‚ h bl br := begin rw [insert_with, cmp_le], split_ifs; rw [insert_with], { rcases h with ⟨⟨lx, xr⟩, hs, hb⟩, rcases hf _ ⟨h_1, h_2⟩ with ⟨xf, fx⟩, refine ⟨⟨⟨lx.mono_right (le_trans h_2 xf), xr.mono_left (le_trans fx h_1)⟩, hs, hb⟩, or.inl rfl⟩ }, { rcases insert_with.valid_aux h.left bl (lt_of_le_not_le h_1 h_2) with ⟨vl, e⟩, suffices H, { refine ⟨vl.balance_l h.right H, _⟩, rw [size_balance_l vl.3 h.3.2.2 vl.2 h.2.2.2 H, h.2.size_eq], refine (e.add_right _).add_right _ }, { exact or.inl ⟨_, e, h.3.1⟩ } }, { have : y < x := lt_of_le_not_le ((total_of (≀) _ _).resolve_left h_1) h_1, rcases insert_with.valid_aux h.right this br with ⟨vr, e⟩, suffices H, { refine ⟨h.left.balance_r vr H, _⟩, rw [size_balance_r h.3.2.1 vr.3 h.2.2.1 vr.2 H, h.2.size_eq], refine (e.add_left _).add_right _ }, { exact or.inr ⟨_, e, h.3.1⟩ } }, end theorem insert_with.valid [is_total Ξ± (≀)] [@decidable_rel Ξ± (≀)] (f : Ξ± β†’ Ξ±) (x : Ξ±) (hf : βˆ€ y, x ≀ y ∧ y ≀ x β†’ x ≀ f y ∧ f y ≀ x) {t} (h : valid t) : valid (insert_with f x t) := (insert_with.valid_aux _ _ hf h ⟨⟩ ⟨⟩).1 theorem insert_eq_insert_with [@decidable_rel Ξ± (≀)] (x : Ξ±) : βˆ€ t, ordnode.insert x t = insert_with (Ξ» _, x) x t | nil := rfl | (node _ l y r) := by unfold ordnode.insert insert_with; cases cmp_le x y; unfold ordnode.insert insert_with; simp [insert_eq_insert_with] theorem insert.valid [is_total Ξ± (≀)] [@decidable_rel Ξ± (≀)] (x : Ξ±) {t} (h : valid t) : valid (ordnode.insert x t) := by rw insert_eq_insert_with; exact insert_with.valid _ _ (Ξ» _ _, ⟨le_rfl, le_rfl⟩) h theorem insert'_eq_insert_with [@decidable_rel Ξ± (≀)] (x : Ξ±) : βˆ€ t, insert' x t = insert_with id x t | nil := rfl | (node _ l y r) := by unfold insert' insert_with; cases cmp_le x y; unfold insert' insert_with; simp [insert'_eq_insert_with] theorem insert'.valid [is_total Ξ± (≀)] [@decidable_rel Ξ± (≀)] (x : Ξ±) {t} (h : valid t) : valid (insert' x t) := by rw insert'_eq_insert_with; exact insert_with.valid _ _ (Ξ» _, id) h theorem valid'.map_aux {Ξ²} [preorder Ξ²] {f : Ξ± β†’ Ξ²} (f_strict_mono : strict_mono f) {t a₁ aβ‚‚} (h : valid' a₁ t aβ‚‚) : valid' (option.map f a₁) (map f t) (option.map f aβ‚‚) ∧ (map f t).size = t.size := begin induction t generalizing a₁ aβ‚‚, { simp [map], apply valid'_nil, cases a₁, { trivial }, cases aβ‚‚, { trivial }, simp [bounded], exact f_strict_mono h.ord }, { have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, cases t_ih_l' with t_l_valid t_l_size, cases t_ih_r' with t_r_valid t_r_size, simp [map], split, { exact and.intro t_l_valid.ord t_r_valid.ord }, { repeat { split }, { rw [t_l_size, t_r_size], exact h.sz.1 }, { exact t_l_valid.sz }, { exact t_r_valid.sz } }, { repeat { split }, { rw [t_l_size, t_r_size], exact h.bal.1 }, { exact t_l_valid.bal }, { exact t_r_valid.bal } } }, end theorem map.valid {Ξ²} [preorder Ξ²] {f : Ξ± β†’ Ξ²} (f_strict_mono : strict_mono f) {t} (h : valid t) : valid (map f t) := (valid'.map_aux f_strict_mono h).1 theorem valid'.erase_aux [@decidable_rel Ξ± (≀)] (x : Ξ±) {t a₁ aβ‚‚} (h : valid' a₁ t aβ‚‚) : valid' a₁ (erase x t) aβ‚‚ ∧ raised (erase x t).size t.size := begin induction t generalizing a₁ aβ‚‚, { simp [erase, raised], exact h }, { simp [erase], have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, cases t_ih_l' with t_l_valid t_l_size, cases t_ih_r' with t_r_valid t_r_size, cases (cmp_le x t_x); simp [erase._match_1]; rw h.sz.1, { suffices h_balanceable, split, { exact valid'.balance_r t_l_valid h.right h_balanceable }, { rw size_balance_r t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz h_balanceable, repeat { apply raised.add_right }, exact t_l_size }, { left, existsi t_l.size, exact (and.intro t_l_size h.bal.1) } }, { have h_glue := valid'.glue h.left h.right h.bal.1, cases h_glue with h_glue_valid h_glue_sized, split, { exact h_glue_valid }, { right, rw h_glue_sized } }, { suffices h_balanceable, split, { exact valid'.balance_l h.left t_r_valid h_balanceable }, { rw size_balance_l h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz h_balanceable, apply raised.add_right, apply raised.add_left, exact t_r_size }, { right, existsi t_r.size, exact (and.intro t_r_size h.bal.1) } } }, end theorem erase.valid [@decidable_rel Ξ± (≀)] (x : Ξ±) {t} (h : valid t) : valid (erase x t) := (valid'.erase_aux x h).1 theorem size_erase_of_mem [@decidable_rel Ξ± (≀)] {x : Ξ±} {t a₁ aβ‚‚} (h : valid' a₁ t aβ‚‚) (h_mem : x ∈ t) : size (erase x t) = size t - 1 := begin induction t generalizing a₁ aβ‚‚ h h_mem, { contradiction }, { have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, unfold has_mem.mem mem at h_mem, unfold erase, cases (cmp_le x t_x); simp [mem._match_1] at h_mem; simp [erase._match_1], { have t_ih_l := t_ih_l' h_mem, clear t_ih_l' t_ih_r', have t_l_h := valid'.erase_aux x h.left, cases t_l_h with t_l_valid t_l_size, rw size_balance_r t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz (or.inl (exists.intro t_l.size (and.intro t_l_size h.bal.1))), rw [t_ih_l, h.sz.1], have h_pos_t_l_size := pos_size_of_mem h.left.sz h_mem, cases t_l.size with t_l_size, { cases h_pos_t_l_size }, simp [nat.succ_add] }, { rw [(valid'.glue h.left h.right h.bal.1).2, h.sz.1], refl }, { have t_ih_r := t_ih_r' h_mem, clear t_ih_l' t_ih_r', have t_r_h := valid'.erase_aux x h.right, cases t_r_h with t_r_valid t_r_size, rw size_balance_l h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz (or.inr (exists.intro t_r.size (and.intro t_r_size h.bal.1))), rw [t_ih_r, h.sz.1], have h_pos_t_r_size := pos_size_of_mem h.right.sz h_mem, cases t_r.size with t_r_size, { cases h_pos_t_r_size }, simp [nat.succ_add, nat.add_succ] } }, end end end ordnode /-- An `ordset Ξ±` is a finite set of values, represented as a tree. The operations on this type maintain that the tree is balanced and correctly stores subtree sizes at each level. The correctness property of the tree is baked into the type, so all operations on this type are correct by construction. -/ def ordset (Ξ± : Type*) [preorder Ξ±] := {t : ordnode Ξ± // t.valid} namespace ordset open ordnode variable [preorder Ξ±] /-- O(1). The empty set. -/ def nil : ordset Ξ± := ⟨nil, ⟨⟩, ⟨⟩, ⟨⟩⟩ /-- O(1). Get the size of the set. -/ def size (s : ordset Ξ±) : β„• := s.1.size /-- O(1). Construct a singleton set containing value `a`. -/ protected def singleton (a : Ξ±) : ordset Ξ± := ⟨singleton a, valid_singleton⟩ instance : has_emptyc (ordset Ξ±) := ⟨nil⟩ instance : inhabited (ordset Ξ±) := ⟨nil⟩ instance : has_singleton Ξ± (ordset Ξ±) := ⟨ordset.singleton⟩ /-- O(1). Is the set empty? -/ def empty (s : ordset Ξ±) : Prop := s = βˆ… theorem empty_iff {s : ordset Ξ±} : s = βˆ… ↔ s.1.empty := ⟨λ h, by cases h; exact rfl, Ξ» h, by cases s; cases s_val; [exact rfl, cases h]⟩ instance : decidable_pred (@empty Ξ± _) := Ξ» s, decidable_of_iff' _ empty_iff /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, this replaces it. -/ protected def insert [is_total Ξ± (≀)] [@decidable_rel Ξ± (≀)] (x : Ξ±) (s : ordset Ξ±) : ordset Ξ± := ⟨ordnode.insert x s.1, insert.valid _ s.2⟩ instance [is_total Ξ± (≀)] [@decidable_rel Ξ± (≀)] : has_insert Ξ± (ordset Ξ±) := ⟨ordset.insert⟩ /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the set is returned as is. -/ def insert' [is_total Ξ± (≀)] [@decidable_rel Ξ± (≀)] (x : Ξ±) (s : ordset Ξ±) : ordset Ξ± := ⟨insert' x s.1, insert'.valid _ s.2⟩ section variables [@decidable_rel Ξ± (≀)] /-- O(log n). Does the set contain the element `x`? That is, is there an element that is equivalent to `x` in the order? -/ def mem (x : Ξ±) (s : ordset Ξ±) : bool := x ∈ s.val /-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order, if it exists. -/ def find (x : Ξ±) (s : ordset Ξ±) : option Ξ± := ordnode.find x s.val instance : has_mem Ξ± (ordset Ξ±) := ⟨λ x s, mem x s⟩ instance mem.decidable (x : Ξ±) (s : ordset Ξ±) : decidable (x ∈ s) := bool.decidable_eq _ _ theorem pos_size_of_mem {x : Ξ±} {t : ordset Ξ±} (h_mem : x ∈ t) : 0 < size t := begin simp [has_mem.mem, mem] at h_mem, apply ordnode.pos_size_of_mem t.property.sz h_mem, end end /-- O(log n). Remove an element from the set equivalent to `x`. Does nothing if there is no such element. -/ def erase [@decidable_rel Ξ± (≀)] (x : Ξ±) (s : ordset Ξ±) : ordset Ξ± := ⟨ordnode.erase x s.val, ordnode.erase.valid x s.property⟩ /-- O(n). Map a function across a tree, without changing the structure. -/ def map {Ξ²} [preorder Ξ²] (f : Ξ± β†’ Ξ²) (f_strict_mono : strict_mono f) (s : ordset Ξ±) : ordset Ξ² := ⟨ordnode.map f s.val, ordnode.map.valid f_strict_mono s.property⟩ end ordset
21cf330d4cac412ba31d72a2b888c1e845d8df57
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/module/strong_topology.lean
78e2334d9215026448b6b378aab9f0f1e5f79d17
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
16,888
lean
/- Copyright (c) 2022 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import topology.algebra.uniform_convergence /-! # Strong topologies on the space of continuous linear maps > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we define the strong topologies on `E β†’L[π•œ] F` associated with a family `𝔖 : set (set E)` to be the topology of uniform convergence on the elements of `𝔖` (also called the topology of `𝔖`-convergence). The lemma `uniform_on_fun.has_continuous_smul_of_image_bounded` tells us that this is a vector space topology if the continuous linear image of any element of `𝔖` is bounded (in the sense of `bornology.is_vonN_bounded`). We then declare an instance for the case where `𝔖` is exactly the set of all bounded subsets of `E`, giving us the so-called "topology of uniform convergence on bounded sets" (or "topology of bounded convergence"), which coincides with the operator norm topology in the case of `normed_space`s. Other useful examples include the weak-* topology (when `𝔖` is the set of finite sets or the set of singletons) and the topology of compact convergence (when `𝔖` is the set of relatively compact sets). ## Main definitions * `continuous_linear_map.strong_topology` is the topology mentioned above for an arbitrary `𝔖`. * `continuous_linear_map.topological_space` is the topology of bounded convergence. This is declared as an instance. ## Main statements * `continuous_linear_map.strong_topology.topological_add_group` and `continuous_linear_map.strong_topology.has_continuous_smul` show that the strong topology makes `E β†’L[π•œ] F` a topological vector space, with the assumptions on `𝔖` mentioned above. * `continuous_linear_map.topological_add_group` and `continuous_linear_map.has_continuous_smul` register these facts as instances for the special case of bounded convergence. ## References * [N. Bourbaki, *Topological Vector Spaces*][bourbaki1987] ## TODO * add a type alias for continuous linear maps with the topology of `𝔖`-convergence? ## Tags uniform convergence, bounded convergence -/ open_locale topology uniform_convergence namespace continuous_linear_map section general variables {π•œβ‚ π•œβ‚‚ : Type*} [normed_field π•œβ‚] [normed_field π•œβ‚‚] (Οƒ : π•œβ‚ β†’+* π•œβ‚‚) {E E' F F' : Type*} [add_comm_group E] [module π•œβ‚ E] [add_comm_group E'] [module ℝ E'] [add_comm_group F] [module π•œβ‚‚ F] [add_comm_group F'] [module ℝ F'] [topological_space E] [topological_space E'] (F) /-- Given `E` and `F` two topological vector spaces and `𝔖 : set (set E)`, then `strong_topology Οƒ F 𝔖` is the "topology of uniform convergence on the elements of `𝔖`" on `E β†’L[π•œ] F`. If the continuous linear image of any element of `𝔖` is bounded, this makes `E β†’L[π•œ] F` a topological vector space. -/ def strong_topology [topological_space F] [topological_add_group F] (𝔖 : set (set E)) : topological_space (E β†’SL[Οƒ] F) := (@uniform_on_fun.topological_space E F (topological_add_group.to_uniform_space F) 𝔖).induced coe_fn /-- The uniform structure associated with `continuous_linear_map.strong_topology`. We make sure that this has nice definitional properties. -/ def strong_uniformity [uniform_space F] [uniform_add_group F] (𝔖 : set (set E)) : uniform_space (E β†’SL[Οƒ] F) := @uniform_space.replace_topology _ (strong_topology Οƒ F 𝔖) ((uniform_on_fun.uniform_space E F 𝔖).comap coe_fn) (by rw [strong_topology, uniform_add_group.to_uniform_space_eq]; refl) @[simp] lemma strong_uniformity_topology_eq [uniform_space F] [uniform_add_group F] (𝔖 : set (set E)) : (strong_uniformity Οƒ F 𝔖).to_topological_space = strong_topology Οƒ F 𝔖 := rfl lemma strong_uniformity.uniform_embedding_coe_fn [uniform_space F] [uniform_add_group F] (𝔖 : set (set E)) : @uniform_embedding (E β†’SL[Οƒ] F) (E β†’α΅€[𝔖] F) (strong_uniformity Οƒ F 𝔖) (uniform_on_fun.uniform_space E F 𝔖) coe_fn := begin letI : uniform_space (E β†’SL[Οƒ] F) := strong_uniformity Οƒ F 𝔖, exact ⟨⟨rfl⟩, fun_like.coe_injective⟩ end lemma strong_topology.embedding_coe_fn [uniform_space F] [uniform_add_group F] (𝔖 : set (set E)) : @embedding (E β†’SL[Οƒ] F) (E β†’α΅€[𝔖] F) (strong_topology Οƒ F 𝔖) (uniform_on_fun.topological_space E F 𝔖) (uniform_on_fun.of_fun 𝔖 ∘ coe_fn) := @uniform_embedding.embedding _ _ (_root_.id _) _ _ (strong_uniformity.uniform_embedding_coe_fn _ _ _) lemma strong_uniformity.uniform_add_group [uniform_space F] [uniform_add_group F] (𝔖 : set (set E)) : @uniform_add_group (E β†’SL[Οƒ] F) (strong_uniformity Οƒ F 𝔖) _ := begin letI : uniform_space (E β†’SL[Οƒ] F) := strong_uniformity Οƒ F 𝔖, rw [strong_uniformity, uniform_space.replace_topology_eq], let Ο† : (E β†’SL[Οƒ] F) β†’+ E β†’α΅€[𝔖] F := ⟨(coe_fn : (E β†’SL[Οƒ] F) β†’ E β†’α΅€ F), rfl, Ξ» _ _, rfl⟩, exact uniform_add_group_comap Ο† end lemma strong_topology.topological_add_group [topological_space F] [topological_add_group F] (𝔖 : set (set E)) : @topological_add_group (E β†’SL[Οƒ] F) (strong_topology Οƒ F 𝔖) _ := begin letI : uniform_space F := topological_add_group.to_uniform_space F, haveI : uniform_add_group F := topological_add_comm_group_is_uniform, letI : uniform_space (E β†’SL[Οƒ] F) := strong_uniformity Οƒ F 𝔖, haveI : uniform_add_group (E β†’SL[Οƒ] F) := strong_uniformity.uniform_add_group Οƒ F 𝔖, apply_instance end lemma strong_topology.t2_space [topological_space F] [topological_add_group F] [t2_space F] (𝔖 : set (set E)) (h𝔖 : ⋃₀ 𝔖 = set.univ) : @t2_space (E β†’SL[Οƒ] F) (strong_topology Οƒ F 𝔖) := begin letI : uniform_space F := topological_add_group.to_uniform_space F, haveI : uniform_add_group F := topological_add_comm_group_is_uniform, letI : topological_space (E β†’SL[Οƒ] F) := strong_topology Οƒ F 𝔖, haveI : t2_space (E β†’α΅€[𝔖] F) := uniform_on_fun.t2_space_of_covering h𝔖, exact (strong_topology.embedding_coe_fn Οƒ F 𝔖).t2_space end lemma strong_topology.has_continuous_smul [ring_hom_surjective Οƒ] [ring_hom_isometric Οƒ] [topological_space F] [topological_add_group F] [has_continuous_smul π•œβ‚‚ F] (𝔖 : set (set E)) (h𝔖₁ : 𝔖.nonempty) (h𝔖₂ : directed_on (βŠ†) 𝔖) (h𝔖₃ : βˆ€ S ∈ 𝔖, bornology.is_vonN_bounded π•œβ‚ S) : @has_continuous_smul π•œβ‚‚ (E β†’SL[Οƒ] F) _ _ (strong_topology Οƒ F 𝔖) := begin letI : uniform_space F := topological_add_group.to_uniform_space F, haveI : uniform_add_group F := topological_add_comm_group_is_uniform, letI : topological_space (E β†’SL[Οƒ] F) := strong_topology Οƒ F 𝔖, let Ο† : (E β†’SL[Οƒ] F) β†’β‚—[π•œβ‚‚] E β†’α΅€[𝔖] F := ⟨(coe_fn : (E β†’SL[Οƒ] F) β†’ E β†’ F), Ξ» _ _, rfl, Ξ» _ _, rfl⟩, exact uniform_on_fun.has_continuous_smul_induced_of_image_bounded π•œβ‚‚ E F (E β†’SL[Οƒ] F) h𝔖₁ h𝔖₂ Ο† ⟨rfl⟩ (Ξ» u s hs, (h𝔖₃ s hs).image u) end lemma strong_topology.has_basis_nhds_zero_of_basis [topological_space F] [topological_add_group F] {ΞΉ : Type*} (𝔖 : set (set E)) (h𝔖₁ : 𝔖.nonempty) (h𝔖₂ : directed_on (βŠ†) 𝔖) {p : ΞΉ β†’ Prop} {b : ΞΉ β†’ set F} (h : (𝓝 0 : filter F).has_basis p b) : (@nhds (E β†’SL[Οƒ] F) (strong_topology Οƒ F 𝔖) 0).has_basis (Ξ» Si : set E Γ— ΞΉ, Si.1 ∈ 𝔖 ∧ p Si.2) (Ξ» Si, {f : E β†’SL[Οƒ] F | βˆ€ x ∈ Si.1, f x ∈ b Si.2}) := begin letI : uniform_space F := topological_add_group.to_uniform_space F, haveI : uniform_add_group F := topological_add_comm_group_is_uniform, rw nhds_induced, exact (uniform_on_fun.has_basis_nhds_zero_of_basis 𝔖 h𝔖₁ h𝔖₂ h).comap coe_fn end lemma strong_topology.has_basis_nhds_zero [topological_space F] [topological_add_group F] (𝔖 : set (set E)) (h𝔖₁ : 𝔖.nonempty) (h𝔖₂ : directed_on (βŠ†) 𝔖) : (@nhds (E β†’SL[Οƒ] F) (strong_topology Οƒ F 𝔖) 0).has_basis (Ξ» SV : set E Γ— set F, SV.1 ∈ 𝔖 ∧ SV.2 ∈ (𝓝 0 : filter F)) (Ξ» SV, {f : E β†’SL[Οƒ] F | βˆ€ x ∈ SV.1, f x ∈ SV.2}) := strong_topology.has_basis_nhds_zero_of_basis Οƒ F 𝔖 h𝔖₁ h𝔖₂ (𝓝 0).basis_sets end general section bounded_sets variables {π•œβ‚ π•œβ‚‚ π•œβ‚ƒ : Type*} [normed_field π•œβ‚] [normed_field π•œβ‚‚] [normed_field π•œβ‚ƒ] {Οƒ : π•œβ‚ β†’+* π•œβ‚‚} {Ο„ : π•œβ‚‚ β†’+* π•œβ‚ƒ} {ρ : π•œβ‚ β†’+* π•œβ‚ƒ} [ring_hom_comp_triple Οƒ Ο„ ρ] {E E' F F' G : Type*} [add_comm_group E] [module π•œβ‚ E] [add_comm_group E'] [module ℝ E'] [add_comm_group F] [module π•œβ‚‚ F] [add_comm_group F'] [module ℝ F'] [add_comm_group G] [module π•œβ‚ƒ G] [topological_space E] /-- The topology of bounded convergence on `E β†’L[π•œ] F`. This coincides with the topology induced by the operator norm when `E` and `F` are normed spaces. -/ instance [topological_space F] [topological_add_group F] : topological_space (E β†’SL[Οƒ] F) := strong_topology Οƒ F {S | bornology.is_vonN_bounded π•œβ‚ S} instance [topological_space F] [topological_add_group F] : topological_add_group (E β†’SL[Οƒ] F) := strong_topology.topological_add_group Οƒ F _ instance [ring_hom_surjective Οƒ] [ring_hom_isometric Οƒ] [topological_space F] [topological_add_group F] [has_continuous_smul π•œβ‚‚ F] : has_continuous_smul π•œβ‚‚ (E β†’SL[Οƒ] F) := strong_topology.has_continuous_smul Οƒ F {S | bornology.is_vonN_bounded π•œβ‚ S} βŸ¨βˆ…, bornology.is_vonN_bounded_empty π•œβ‚ E⟩ (directed_on_of_sup_mem $ Ξ» _ _, bornology.is_vonN_bounded.union) (Ξ» s hs, hs) instance [uniform_space F] [uniform_add_group F] : uniform_space (E β†’SL[Οƒ] F) := strong_uniformity Οƒ F {S | bornology.is_vonN_bounded π•œβ‚ S} instance [uniform_space F] [uniform_add_group F] : uniform_add_group (E β†’SL[Οƒ] F) := strong_uniformity.uniform_add_group Οƒ F _ instance [topological_space F] [topological_add_group F] [has_continuous_smul π•œβ‚ E] [t2_space F] : t2_space (E β†’SL[Οƒ] F) := strong_topology.t2_space Οƒ F _ (set.eq_univ_of_forall $ Ξ» x, set.mem_sUnion_of_mem (set.mem_singleton x) (bornology.is_vonN_bounded_singleton x)) protected lemma has_basis_nhds_zero_of_basis [topological_space F] [topological_add_group F] {ΞΉ : Type*} {p : ΞΉ β†’ Prop} {b : ΞΉ β†’ set F} (h : (𝓝 0 : filter F).has_basis p b) : (𝓝 (0 : E β†’SL[Οƒ] F)).has_basis (Ξ» Si : set E Γ— ΞΉ, bornology.is_vonN_bounded π•œβ‚ Si.1 ∧ p Si.2) (Ξ» Si, {f : E β†’SL[Οƒ] F | βˆ€ x ∈ Si.1, f x ∈ b Si.2}) := strong_topology.has_basis_nhds_zero_of_basis Οƒ F {S | bornology.is_vonN_bounded π•œβ‚ S} βŸ¨βˆ…, bornology.is_vonN_bounded_empty π•œβ‚ E⟩ (directed_on_of_sup_mem $ Ξ» _ _, bornology.is_vonN_bounded.union) h protected lemma has_basis_nhds_zero [topological_space F] [topological_add_group F] : (𝓝 (0 : E β†’SL[Οƒ] F)).has_basis (Ξ» SV : set E Γ— set F, bornology.is_vonN_bounded π•œβ‚ SV.1 ∧ SV.2 ∈ (𝓝 0 : filter F)) (Ξ» SV, {f : E β†’SL[Οƒ] F | βˆ€ x ∈ SV.1, f x ∈ SV.2}) := continuous_linear_map.has_basis_nhds_zero_of_basis (𝓝 0).basis_sets variables (G) [topological_space F] [topological_space G] /-- Pre-composition by a *fixed* continuous linear map as a continuous linear map. Note that in non-normed space it is not always true that composition is continuous in both variables, so we have to fix one of them. -/ @[simps] def precomp [topological_add_group G] [has_continuous_const_smul π•œβ‚ƒ G] [ring_hom_surjective Οƒ] [ring_hom_isometric Οƒ] (L : E β†’SL[Οƒ] F) : (F β†’SL[Ο„] G) β†’L[π•œβ‚ƒ] (E β†’SL[ρ] G) := { to_fun := Ξ» f, f.comp L, map_add' := Ξ» f g, add_comp f g L, map_smul' := Ξ» a f, smul_comp a f L, cont := begin letI : uniform_space G := topological_add_group.to_uniform_space G, haveI : uniform_add_group G := topological_add_comm_group_is_uniform, rw (strong_topology.embedding_coe_fn _ _ _).continuous_iff, refine (uniform_on_fun.precomp_uniform_continuous _).continuous.comp (strong_topology.embedding_coe_fn _ _ _).continuous, exact Ξ» S hS, hS.image L, end } variables (E) {G} /-- Post-composition by a *fixed* continuous linear map as a continuous linear map. Note that in non-normed space it is not always true that composition is continuous in both variables, so we have to fix one of them. -/ @[simps] def postcomp [topological_add_group F] [topological_add_group G] [has_continuous_const_smul π•œβ‚ƒ G] [has_continuous_const_smul π•œβ‚‚ F] (L : F β†’SL[Ο„] G) : (E β†’SL[Οƒ] F) β†’SL[Ο„] (E β†’SL[ρ] G) := { to_fun := Ξ» f, L.comp f, map_add' := comp_add L, map_smul' := comp_smulβ‚›β‚— L, cont := begin letI : uniform_space G := topological_add_group.to_uniform_space G, haveI : uniform_add_group G := topological_add_comm_group_is_uniform, letI : uniform_space F := topological_add_group.to_uniform_space F, haveI : uniform_add_group F := topological_add_comm_group_is_uniform, rw (strong_topology.embedding_coe_fn _ _ _).continuous_iff, exact (uniform_on_fun.postcomp_uniform_continuous L.uniform_continuous).continuous.comp (strong_topology.embedding_coe_fn _ _ _).continuous end } end bounded_sets end continuous_linear_map open continuous_linear_map namespace continuous_linear_equiv section semilinear variables {π•œ : Type*} {π•œβ‚‚ : Type*} {π•œβ‚ƒ : Type*} {π•œβ‚„ : Type*} {E : Type*} {F : Type*} {G : Type*} {H : Type*} [add_comm_group E] [add_comm_group F] [add_comm_group G] [add_comm_group H] [nontrivially_normed_field π•œ] [nontrivially_normed_field π•œβ‚‚] [nontrivially_normed_field π•œβ‚ƒ] [nontrivially_normed_field π•œβ‚„] [module π•œ E] [module π•œβ‚‚ F] [module π•œβ‚ƒ G] [module π•œβ‚„ H] [topological_space E] [topological_space F] [topological_space G] [topological_space H] [topological_add_group G] [topological_add_group H] [has_continuous_const_smul π•œβ‚ƒ G] [has_continuous_const_smul π•œβ‚„ H] {σ₁₂ : π•œ β†’+* π•œβ‚‚} {σ₂₁ : π•œβ‚‚ β†’+* π•œ} {σ₂₃ : π•œβ‚‚ β†’+* π•œβ‚ƒ} {σ₁₃ : π•œ β†’+* π•œβ‚ƒ} {σ₃₄ : π•œβ‚ƒ β†’+* π•œβ‚„} {σ₄₃ : π•œβ‚„ β†’+* π•œβ‚ƒ} {Οƒβ‚‚β‚„ : π•œβ‚‚ β†’+* π•œβ‚„} {σ₁₄ : π•œ β†’+* π•œβ‚„} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] [ring_hom_inv_pair σ₃₄ σ₄₃] [ring_hom_inv_pair σ₄₃ σ₃₄] [ring_hom_comp_triple σ₂₁ σ₁₄ Οƒβ‚‚β‚„] [ring_hom_comp_triple Οƒβ‚‚β‚„ σ₄₃ σ₂₃] [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄] [ring_hom_comp_triple σ₂₃ σ₃₄ Οƒβ‚‚β‚„] [ring_hom_comp_triple σ₁₂ Οƒβ‚‚β‚„ σ₁₄] [ring_hom_isometric σ₁₂] [ring_hom_isometric σ₂₁] include σ₁₄ Οƒβ‚‚β‚„ σ₁₃ σ₃₄ σ₂₁ σ₂₃ /-- A pair of continuous (semi)linear equivalences generates a (semi)linear equivalence between the spaces of continuous (semi)linear maps. -/ @[simps] def arrow_congrSL (e₁₂ : E ≃SL[σ₁₂] F) (e₄₃ : H ≃SL[σ₄₃] G) : (E β†’SL[σ₁₄] H) ≃SL[σ₄₃] (F β†’SL[σ₂₃] G) := { -- given explicitly to help `simps` to_fun := Ξ» L, (e₄₃ : H β†’SL[σ₄₃] G).comp (L.comp (e₁₂.symm : F β†’SL[σ₂₁] E)), -- given explicitly to help `simps` inv_fun := Ξ» L, (e₄₃.symm : G β†’SL[σ₃₄] H).comp (L.comp (e₁₂ : E β†’SL[σ₁₂] F)), map_add' := Ξ» f g, by rw [add_comp, comp_add], map_smul' := Ξ» t f, by rw [smul_comp, comp_smulβ‚›β‚—], continuous_to_fun := ((postcomp F e₄₃.to_continuous_linear_map).comp (precomp H e₁₂.symm.to_continuous_linear_map)).continuous, continuous_inv_fun := ((precomp H e₁₂.to_continuous_linear_map).comp (postcomp F e₄₃.symm.to_continuous_linear_map)).continuous, .. e₁₂.arrow_congr_equiv e₄₃, } end semilinear section linear variables {π•œ : Type*} {E : Type*} {F : Type*} {G : Type*} {H : Type*} [add_comm_group E] [add_comm_group F] [add_comm_group G] [add_comm_group H] [nontrivially_normed_field π•œ] [module π•œ E] [module π•œ F] [module π•œ G] [module π•œ H] [topological_space E] [topological_space F] [topological_space G] [topological_space H] [topological_add_group G] [topological_add_group H] [has_continuous_const_smul π•œ G] [has_continuous_const_smul π•œ H] /-- A pair of continuous linear equivalences generates an continuous linear equivalence between the spaces of continuous linear maps. -/ def arrow_congr (e₁ : E ≃L[π•œ] F) (eβ‚‚ : H ≃L[π•œ] G) : (E β†’L[π•œ] H) ≃L[π•œ] (F β†’L[π•œ] G) := e₁.arrow_congrSL eβ‚‚ end linear end continuous_linear_equiv
1a0990d2f78523f3cc864979671fb2fa9c37c74d
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/preadditive/endo_functor.lean
8b4951081b04b74057a05efe69a114bd46651843
[ "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
4,560
lean
/- Copyright (c) 2022 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer -/ import category_theory.preadditive.default import category_theory.endofunctor.algebra import category_theory.preadditive.additive_functor /-! # Preadditive structure on algebras over a monad If `C` is a preadditive categories and `F` is an additive endofunctor on `C` then `algebra F` is also preadditive. Dually, the category `coalgebra F` is also preadditive. -/ universes v₁ u₁ -- morphism levels before object levels. See note [category_theory universes]. namespace category_theory variables (C : Type u₁) [category.{v₁} C] [preadditive C] (F : C β₯€ C) [functor.additive (F : C β₯€ C)] open category_theory.limits preadditive /-- The category of algebras over an additive endofunctor on a preadditive category is preadditive. -/ @[simps] instance endofunctor.algebra_preadditive : preadditive (endofunctor.algebra F) := { hom_group := Ξ» A₁ Aβ‚‚, { add := Ξ» Ξ± Ξ², { f := Ξ±.f + Ξ².f, h' := by simp only [functor.map_add, add_comp, endofunctor.algebra.hom.h, comp_add] }, zero := { f := 0, h' := by simp only [functor.map_zero, zero_comp, comp_zero] }, nsmul := Ξ» n Ξ±, { f := n β€’ Ξ±.f, h' := by rw [comp_nsmul, functor.map_nsmul, nsmul_comp, endofunctor.algebra.hom.h] }, neg := Ξ» Ξ±, { f := -Ξ±.f, h' := by simp only [functor.map_neg, neg_comp, endofunctor.algebra.hom.h, comp_neg] }, sub := Ξ» Ξ± Ξ², { f := Ξ±.f - Ξ².f, h' := by simp only [functor.map_sub, sub_comp, endofunctor.algebra.hom.h, comp_sub] }, zsmul := Ξ» r Ξ±, { f := r β€’ Ξ±.f, h' := by rw [comp_zsmul, functor.map_zsmul, zsmul_comp, endofunctor.algebra.hom.h] }, add_assoc := by { intros, ext, apply add_assoc }, zero_add := by { intros, ext, apply zero_add }, add_zero := by { intros, ext, apply add_zero }, nsmul_zero' := by { intros, ext, apply zero_smul }, nsmul_succ' := by { intros, ext, apply succ_nsmul }, sub_eq_add_neg := by { intros, ext, apply sub_eq_add_neg }, zsmul_zero' := by { intros, ext, apply zero_smul }, zsmul_succ' := by { intros, ext, dsimp, simp only [coe_nat_zsmul, succ_nsmul], refl, }, zsmul_neg' := by { intros, ext, simp only [zsmul_neg_succ_of_nat, neg_inj, nsmul_eq_smul_cast β„€] }, add_left_neg := by { intros, ext, apply add_left_neg }, add_comm := by { intros, ext, apply add_comm } }, add_comp' := by { intros, ext, apply add_comp }, comp_add' := by { intros, ext, apply comp_add } } instance algebra.forget_additive : (endofunctor.algebra.forget F).additive := {} @[simps] instance endofunctor.coalgebra_preadditive : preadditive (endofunctor.coalgebra F) := { hom_group := Ξ» A₁ Aβ‚‚, { add := Ξ» Ξ± Ξ², { f := Ξ±.f + Ξ².f, h' := by simp only [functor.map_add, comp_add, endofunctor.coalgebra.hom.h, add_comp] }, zero := { f := 0, h' := by simp only [functor.map_zero, zero_comp, comp_zero] }, nsmul := Ξ» n Ξ±, { f := n β€’ Ξ±.f, h' := by rw [functor.map_nsmul, comp_nsmul, endofunctor.coalgebra.hom.h, nsmul_comp] }, neg := Ξ» Ξ±, { f := -Ξ±.f, h' := by simp only [functor.map_neg, comp_neg, endofunctor.coalgebra.hom.h, neg_comp] }, sub := Ξ» Ξ± Ξ², { f := Ξ±.f - Ξ².f, h' := by simp only [functor.map_sub, comp_sub, endofunctor.coalgebra.hom.h, sub_comp] }, zsmul := Ξ» r Ξ±, { f := r β€’ Ξ±.f, h' := by rw [functor.map_zsmul, comp_zsmul, endofunctor.coalgebra.hom.h, zsmul_comp] }, add_assoc := by { intros, ext, apply add_assoc }, zero_add := by { intros, ext, apply zero_add }, add_zero := by { intros, ext, apply add_zero }, nsmul_zero' := by { intros, ext, apply zero_smul }, nsmul_succ' := by { intros, ext, apply succ_nsmul }, sub_eq_add_neg := by { intros, ext, apply sub_eq_add_neg }, zsmul_zero' := by { intros, ext, apply zero_smul }, zsmul_succ' := by { intros, ext, dsimp, simp only [coe_nat_zsmul, succ_nsmul], refl, }, zsmul_neg' := by { intros, ext, simp only [zsmul_neg_succ_of_nat, neg_inj, nsmul_eq_smul_cast β„€] }, add_left_neg := by { intros, ext, apply add_left_neg }, add_comm := by { intros, ext, apply add_comm } }, add_comp' := by { intros, ext, apply add_comp }, comp_add' := by { intros, ext, apply comp_add } } instance coalgebra.forget_additive : (endofunctor.coalgebra.forget F).additive := {} end category_theory
74faefaeb3edad44da6181a01ef6cc50e6d7b8af
7282d49021d38dacd06c4ce45a48d09627687fe0
/tests/lean/arith7.lean
9a36066150ce2b57c16f76b55d73e1141fda819b
[ "Apache-2.0" ]
permissive
steveluc/lean
5a0b4431acefaf77f15b25bbb49294c2449923ad
92ba4e8b2d040a799eda7deb8d2a7cdd3e69c496
refs/heads/master
1,611,332,256,930
1,391,013,244,000
1,391,013,244,000
16,361,079
1
0
null
null
null
null
UTF-8
Lean
false
false
409
lean
import Int. eval | -2 | -- Unfortunately, we can't write |-2|, because |- is considered a single token. -- It is not wise to change that since the symbol |- can be used as the notation for -- entailment relation in Lean. eval |3| definition x : Int := -3 eval |x + 1| eval |x + 1| > 0 variable y : Int eval |x + y| print |x + y| > x set_option pp::notation false print |x + y| > x print |x + y| + |y + x| > x
3400f9637a462a43d97c1c8da31074e0308d86b0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/test/lock/Loop.lean
ab3d0aa8287a9d3774b7e90d51dca2b0edaed959
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
29
lean
#eval do repeat IO.sleep 300
647b01ab2962b8bde20935658b96f4549c0dfc78
ea4aee6b11f86433e69bb5e50d0259e056d0ae61
/src/tidy/tests/looping_and_profiling.lean
314b105a79dfa20c6064aef6002e199aa947b128
[]
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
657
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import ..loop_detection import ..profiling open tactic lemma looping_and_profiling_at_the_same_time_test_1 : true := begin profiling $ (detect_looping $ triv), end lemma looping_and_profiling_at_the_same_time_test_2 : true := begin success_if_fail { profiling $ detect_looping $ skip >> skip }, triv end lemma looping_and_profiling_at_the_same_time_test_3 : 1 = 1 := begin success_if_fail { profiling $ detect_looping $ interactive_simp >> skip >> skip }, -- failed, with 2 invocations simp end
38266b1b78be434f62b411e40b44795ba5efa530
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Elab/Deriving/Inhabited.lean
99f0edc1d5dc6140691e3a97c92f71fb2b5b790e
[ "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
5,445
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.Deriving.Basic namespace Lean.Elab open Command open Meta private abbrev IndexSet := Std.RBTree Nat compare private abbrev LocalInst2Index := FVarIdMap Nat private def implicitBinderF := Parser.Term.implicitBinder private def instBinderF := Parser.Term.instBinder private def mkInhabitedInstanceUsing (inductiveTypeName : Name) (ctorName : Name) (addHypotheses : Bool) : CommandElabM Bool := do match (← liftTermElabM none mkInstanceCmd?) with | some cmd => elabCommand cmd return true | none => return false where addLocalInstancesForParamsAux {Ξ±} (k : LocalInst2Index β†’ TermElabM Ξ±) : List Expr β†’ Nat β†’ LocalInst2Index β†’ TermElabM Ξ± | [], i, map => k map | x::xs, i, map => try let instType ← mkAppM `Inhabited #[x] if (← isTypeCorrect instType) then withLocalDeclD (← mkFreshUserName `inst) instType fun inst => do trace[Elab.Deriving.inhabited] "adding local instance {instType}" addLocalInstancesForParamsAux k xs (i+1) (map.insert inst.fvarId! i) else addLocalInstancesForParamsAux k xs (i+1) map catch _ => addLocalInstancesForParamsAux k xs (i+1) map addLocalInstancesForParams {Ξ±} (xs : Array Expr) (k : LocalInst2Index β†’ TermElabM Ξ±) : TermElabM Ξ± := do if addHypotheses then addLocalInstancesForParamsAux k xs.toList 0 {} else k {} collectUsedLocalsInsts (usedInstIdxs : IndexSet) (localInst2Index : LocalInst2Index) (e : Expr) : IndexSet := if localInst2Index.isEmpty then usedInstIdxs else let visit {Ο‰} : StateRefT IndexSet (ST Ο‰) Unit := e.forEach fun | Expr.fvar fvarId _ => match localInst2Index.find? fvarId with | some idx => modify (Β·.insert idx) | none => pure () | _ => pure () runST (fun _ => visit |>.run usedInstIdxs) |>.2 /- Create an `instance` command using the constructor `ctorName` with a hypothesis `Inhabited Ξ±` when `Ξ±` is one of the inductive type parameters at position `i` and `i ∈ assumingParamIdxs`. -/ mkInstanceCmdWith (assumingParamIdxs : IndexSet) : TermElabM Syntax := do let indVal ← getConstInfoInduct inductiveTypeName let ctorVal ← getConstInfoCtor ctorName let mut indArgs := #[] let mut binders := #[] for i in [:indVal.numParams + indVal.numIndices] do let arg := mkIdent (← mkFreshUserName `a) indArgs := indArgs.push arg let binder ← `(implicitBinderF| { $arg:ident }) binders := binders.push binder if assumingParamIdxs.contains i then let binder ← `(instBinderF| [ Inhabited $arg:ident ]) binders := binders.push binder let type ← `(Inhabited (@$(mkIdent inductiveTypeName):ident $indArgs:ident*)) let mut ctorArgs := #[] for i in [:ctorVal.numParams] do ctorArgs := ctorArgs.push (← `(_)) for i in [:ctorVal.numFields] do ctorArgs := ctorArgs.push (← `(arbitrary)) let val ← `(⟨@$(mkIdent ctorName):ident $ctorArgs:ident*⟩) `(instance $binders:explicitBinder* : $type := $val) mkInstanceCmd? : TermElabM (Option Syntax) := do let ctorVal ← getConstInfoCtor ctorName forallTelescopeReducing ctorVal.type fun xs _ => addLocalInstancesForParams xs[:ctorVal.numParams] fun localInst2Index => do let mut usedInstIdxs := {} let mut ok := true for i in [ctorVal.numParams:xs.size] do let x := xs[i] let instType ← mkAppM `Inhabited #[(← inferType x)] trace[Elab.Deriving.inhabited] "checking {instType} for '{ctorName}'" match (← trySynthInstance instType) with | LOption.some e => usedInstIdxs ← collectUsedLocalsInsts usedInstIdxs localInst2Index e | _ => trace[Elab.Deriving.inhabited] "failed to generate instance using '{ctorName}' {if addHypotheses then "(assuming parameters are inhabited)" else ""} because of field with type{indentExpr (← inferType x)}" ok := false break if !ok then return none else trace[Elab.Deriving.inhabited] "inhabited instance using '{ctorName}' {if addHypotheses then "(assuming parameters are inhabited)" else ""} {usedInstIdxs.toList}" let cmd ← mkInstanceCmdWith usedInstIdxs trace[Elab.Deriving.inhabited] "\n{cmd}" return some cmd private def mkInhabitedInstance (declName : Name) : CommandElabM Unit := do let indVal ← getConstInfoInduct declName let doIt (addHypotheses : Bool) : CommandElabM Bool := do for ctorName in indVal.ctors do if (← mkInhabitedInstanceUsing declName ctorName addHypotheses) then return true return false unless (← doIt false <||> doIt true) do throwError "failed to generate 'Inhabited' instance for '{declName}'" def mkInhabitedInstanceHandler (declNames : Array Name) : CommandElabM Bool := do if (← declNames.allM isInductive) then declNames.forM mkInhabitedInstance return true else return false builtin_initialize registerBuiltinDerivingHandler `Inhabited mkInhabitedInstanceHandler registerTraceClass `Elab.Deriving.inhabited end Lean.Elab
c91d8192206d9fc37dd5c2e67346dae59196c165
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/specific_limits/floor_pow.lean
22a9af21cf370ffc0c26fcada04d39d72365c7b7
[ "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
17,666
lean
/- Copyright (c) 2022 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: SΓ©bastien GouΓ«zel -/ import analysis.specific_limits.basic import analysis.special_functions.pow /-! # Results on discretized exponentials We state several auxiliary results pertaining to sequences of the form `⌊c^nβŒ‹β‚Š`. * `tendsto_div_of_monotone_of_tendsto_div_floor_pow`: If a monotone sequence `u` is such that `u ⌊c^nβŒ‹β‚Š / ⌊c^nβŒ‹β‚Š` converges to a limit `l` for all `c > 1`, then `u n / n` tends to `l`. * `sum_div_nat_floor_pow_sq_le_div_sq`: The sum of `1/⌊c^iβŒ‹β‚Š^2` above a threshold `j` is comparable to `1/j^2`, up to a multiplicative constant. -/ open filter finset open_locale topological_space big_operators /-- If a monotone sequence `u` is such that `u n / n` tends to a limit `l` along subsequences with exponential growth rate arbitrarily close to `1`, then `u n / n` tends to `l`. -/ lemma tendsto_div_of_monotone_of_exists_subseq_tendsto_div (u : β„• β†’ ℝ) (l : ℝ) (hmono : monotone u) (hlim : βˆ€ (a : ℝ), 1 < a β†’ βˆƒ c : β„• β†’ β„•, (βˆ€αΆ  n in at_top, (c (n+1) : ℝ) ≀ a * c n) ∧ tendsto c at_top at_top ∧ tendsto (Ξ» n, u (c n) / (c n)) at_top (𝓝 l)) : tendsto (Ξ» n, u n / n) at_top (𝓝 l) := begin /- To check the result up to some `Ξ΅ > 0`, we use a sequence `c` for which the ratio `c (N+1) / c N` is bounded by `1 + Ξ΅`. Sandwiching a given `n` between two consecutive values of `c`, say `c N` and `c (N+1)`, one can then bound `u n / n` from above by `u (c N) / c (N - 1)` and from below by `u (c (N - 1)) / c N` (using that `u` is monotone), which are both comparable to the limit `l` up to `1 + Ξ΅`. We give a version of this proof by clearing out denominators first, to avoid discussing the sign of different quantities. -/ have lnonneg : 0 ≀ l, { rcases hlim 2 one_lt_two with ⟨c, cgrowth, ctop, clim⟩, have : tendsto (Ξ» n, u 0 / (c n)) at_top (𝓝 0) := tendsto_const_nhds.div_at_top (tendsto_coe_nat_at_top_iff.2 ctop), apply le_of_tendsto_of_tendsto' this clim (Ξ» n, _), simp_rw [div_eq_inv_mul], exact mul_le_mul_of_nonneg_left (hmono (zero_le _)) (inv_nonneg.2 (nat.cast_nonneg _)) }, have A : βˆ€ (Ξ΅ : ℝ), 0 < Ξ΅ β†’ βˆ€αΆ  n in at_top, u n - n * l ≀ (Ξ΅ * (1 + Ξ΅ + l)) * n, { assume Ξ΅ Ξ΅pos, rcases hlim (1 + Ξ΅) ((lt_add_iff_pos_right _).2 Ξ΅pos) with ⟨c, cgrowth, ctop, clim⟩, have L : βˆ€αΆ  n in at_top, u (c n) - c n * l ≀ Ξ΅ * c n, { rw [← tendsto_sub_nhds_zero_iff, ← asymptotics.is_o_one_iff ℝ, asymptotics.is_o_iff] at clim, filter_upwards [clim Ξ΅pos, ctop (Ioi_mem_at_top 0)] with n hn cnpos', have cnpos : 0 < c n := cnpos', calc u (c n) - c n * l = (u (c n) / c n - l) * c n: by simp only [cnpos.ne', ne.def, nat.cast_eq_zero, not_false_iff] with field_simps ... ≀ Ξ΅ * c n : begin refine mul_le_mul_of_nonneg_right _ (nat.cast_nonneg _), simp only [mul_one, real.norm_eq_abs, abs_one] at hn, exact le_trans (le_abs_self _) hn, end }, obtain ⟨a, ha⟩ : βˆƒ (a : β„•), βˆ€ (b : β„•), a ≀ b β†’ (c (b + 1) : ℝ) ≀ (1 + Ξ΅) * c b ∧ u (c b) - c b * l ≀ Ξ΅ * c b := eventually_at_top.1 (cgrowth.and L), let M := ((finset.range (a+1)).image (Ξ» i, c i)).max' (by simp), filter_upwards [Ici_mem_at_top M] with n hn, have exN : βˆƒ N, n < c N, { rcases (tendsto_at_top.1 ctop (n+1)).exists with ⟨N, hN⟩, exact ⟨N, by linarith only [hN]⟩ }, let N := nat.find exN, have ncN : n < c N := nat.find_spec exN, have aN : a + 1 ≀ N, { by_contra' h, have cNM : c N ≀ M, { apply le_max', apply mem_image_of_mem, exact mem_range.2 h }, exact lt_irrefl _ ((cNM.trans hn).trans_lt ncN) }, have Npos : 0 < N := lt_of_lt_of_le (nat.succ_pos') aN, have cNn : c (N - 1) ≀ n, { have : N - 1 < N := nat.pred_lt Npos.ne', simpa only [not_lt] using nat.find_min exN this }, have IcN : (c N : ℝ) ≀ (1 + Ξ΅) * (c (N - 1)), { have A : a ≀ N - 1, by linarith only [aN, Npos], have B : N - 1 + 1 = N := nat.succ_pred_eq_of_pos Npos, have := (ha _ A).1, rwa B at this }, calc u n - n * l ≀ u (c N) - c (N - 1) * l : begin apply sub_le_sub (hmono ncN.le), apply mul_le_mul_of_nonneg_right (nat.cast_le.2 cNn) lnonneg, end ... = (u (c N) - c N * l) + (c N - c (N - 1)) * l : by ring ... ≀ Ξ΅ * c N + (Ξ΅ * c (N - 1)) * l : begin apply add_le_add, { apply (ha _ _).2, exact le_trans (by simp only [le_add_iff_nonneg_right, zero_le']) aN }, { apply mul_le_mul_of_nonneg_right _ lnonneg, linarith only [IcN] }, end ... ≀ Ξ΅ * ((1 + Ξ΅) * c (N-1)) + (Ξ΅ * c (N - 1)) * l : add_le_add (mul_le_mul_of_nonneg_left IcN Ξ΅pos.le) le_rfl ... = (Ξ΅ * (1 + Ξ΅ + l)) * c (N - 1) : by ring ... ≀ (Ξ΅ * (1 + Ξ΅ + l)) * n : begin refine mul_le_mul_of_nonneg_left (nat.cast_le.2 cNn) _, apply mul_nonneg Ξ΅pos.le, linarith only [Ξ΅pos, lnonneg] end }, have B : βˆ€ (Ξ΅ : ℝ), 0 < Ξ΅ β†’ βˆ€αΆ  (n : β„•) in at_top, (n : ℝ) * l - u n ≀ (Ξ΅ * (1 + l)) * n, { assume Ξ΅ Ξ΅pos, rcases hlim (1 + Ξ΅) ((lt_add_iff_pos_right _).2 Ξ΅pos) with ⟨c, cgrowth, ctop, clim⟩, have L : βˆ€αΆ  (n : β„•) in at_top, (c n : ℝ) * l - u (c n) ≀ Ξ΅ * c n, { rw [← tendsto_sub_nhds_zero_iff, ← asymptotics.is_o_one_iff ℝ, asymptotics.is_o_iff] at clim, filter_upwards [clim Ξ΅pos, ctop (Ioi_mem_at_top 0)] with n hn cnpos', have cnpos : 0 < c n := cnpos', calc (c n : ℝ) * l - u (c n) = -(u (c n) / c n - l) * c n: by simp only [cnpos.ne', ne.def, nat.cast_eq_zero, not_false_iff, neg_sub] with field_simps ... ≀ Ξ΅ * c n : begin refine mul_le_mul_of_nonneg_right _ (nat.cast_nonneg _), simp only [mul_one, real.norm_eq_abs, abs_one] at hn, exact le_trans (neg_le_abs_self _) hn, end }, obtain ⟨a, ha⟩ : βˆƒ (a : β„•), βˆ€ (b : β„•), a ≀ b β†’ (c (b + 1) : ℝ) ≀ (1 + Ξ΅) * c b ∧ (c b : ℝ) * l - u (c b) ≀ Ξ΅ * c b := eventually_at_top.1 (cgrowth.and L), let M := ((finset.range (a+1)).image (Ξ» i, c i)).max' (by simp), filter_upwards [Ici_mem_at_top M] with n hn, have exN : βˆƒ N, n < c N, { rcases (tendsto_at_top.1 ctop (n+1)).exists with ⟨N, hN⟩, exact ⟨N, by linarith only [hN]⟩ }, let N := nat.find exN, have ncN : n < c N := nat.find_spec exN, have aN : a + 1 ≀ N, { by_contra' h, have cNM : c N ≀ M, { apply le_max', apply mem_image_of_mem, exact mem_range.2 h }, exact lt_irrefl _ ((cNM.trans hn).trans_lt ncN) }, have Npos : 0 < N := lt_of_lt_of_le (nat.succ_pos') aN, have aN' : a ≀ N - 1 := by linarith only [aN, Npos], have cNn : c (N - 1) ≀ n, { have : N - 1 < N := nat.pred_lt Npos.ne', simpa only [not_lt] using nat.find_min exN this }, calc (n : ℝ) * l - u n ≀ c N * l - u (c (N - 1)) : begin refine add_le_add (mul_le_mul_of_nonneg_right (nat.cast_le.2 ncN.le) lnonneg) _, exact neg_le_neg (hmono cNn), end ... ≀ ((1 + Ξ΅) * c (N - 1)) * l - u (c (N - 1)) : begin refine add_le_add (mul_le_mul_of_nonneg_right _ lnonneg) le_rfl, have B : N - 1 + 1 = N := nat.succ_pred_eq_of_pos Npos, have := (ha _ aN').1, rwa B at this, end ... = (c (N - 1) * l - u (c (N - 1))) + Ξ΅ * c (N - 1) * l : by ring ... ≀ Ξ΅ * c (N - 1) + Ξ΅ * c (N - 1) * l : add_le_add (ha _ aN').2 le_rfl ... = (Ξ΅ * (1 + l)) * c (N - 1) : by ring ... ≀ (Ξ΅ * (1 + l)) * n : begin refine mul_le_mul_of_nonneg_left (nat.cast_le.2 cNn) _, exact mul_nonneg (Ξ΅pos.le) (add_nonneg zero_le_one lnonneg), end }, refine tendsto_order.2 ⟨λ d hd, _, Ξ» d hd, _⟩, { obtain ⟨Ρ, hΞ΅, Ξ΅pos⟩ : βˆƒ (Ξ΅ : ℝ), d + Ξ΅ * (1 + l) < l ∧ 0 < Ξ΅, { have L : tendsto (Ξ» Ξ΅, d + (Ξ΅ * (1 + l))) (𝓝[>] 0) (𝓝 (d + 0 * (1 + l))), { apply tendsto.mono_left _ nhds_within_le_nhds, exact tendsto_const_nhds.add (tendsto_id.mul tendsto_const_nhds) }, simp only [zero_mul, add_zero] at L, exact (((tendsto_order.1 L).2 l hd).and (self_mem_nhds_within)).exists }, filter_upwards [B Ξ΅ Ξ΅pos, Ioi_mem_at_top 0] with n hn npos, simp_rw [div_eq_inv_mul], calc d < (n⁻¹ * n) * (l - Ξ΅ * (1 + l)) : begin rw [inv_mul_cancel, one_mul], { linarith only [hΞ΅] }, { exact nat.cast_ne_zero.2 (ne_of_gt npos) } end ... = n⁻¹ * (n * l - Ξ΅ * (1 + l) * n) : by ring ... ≀ n⁻¹ * u n : begin refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 (nat.cast_nonneg _)), linarith only [hn], end }, { obtain ⟨Ρ, hΞ΅, Ξ΅pos⟩ : βˆƒ (Ξ΅ : ℝ), l + Ξ΅ * (1 + Ξ΅ + l) < d ∧ 0 < Ξ΅, { have L : tendsto (Ξ» Ξ΅, l + (Ξ΅ * (1 + Ξ΅ + l))) (𝓝[>] 0) (𝓝 (l + 0 * (1 + 0 + l))), { apply tendsto.mono_left _ nhds_within_le_nhds, exact tendsto_const_nhds.add (tendsto_id.mul ((tendsto_const_nhds.add tendsto_id).add tendsto_const_nhds)) }, simp only [zero_mul, add_zero] at L, exact (((tendsto_order.1 L).2 d hd).and (self_mem_nhds_within)).exists }, filter_upwards [A Ξ΅ Ξ΅pos, Ioi_mem_at_top 0] with n hn npos, simp_rw [div_eq_inv_mul], calc (n : ℝ)⁻¹ * u n ≀ (n : ℝ)⁻¹ * (n * l + Ξ΅ * (1 + Ξ΅ + l) * n) : begin refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 (nat.cast_nonneg _)), linarith only [hn], end ... = ((n : ℝ) ⁻¹ * n) * (l + Ξ΅ * (1 + Ξ΅ + l)) : by ring ... < d : begin rwa [inv_mul_cancel, one_mul], exact nat.cast_ne_zero.2 (ne_of_gt npos), end } end /-- If a monotone sequence `u` is such that `u ⌊c^nβŒ‹β‚Š / ⌊c^nβŒ‹β‚Š` converges to a limit `l` for all `c > 1`, then `u n / n` tends to `l`. It is even enough to have the assumption for a sequence of `c`s converging to `1`. -/ lemma tendsto_div_of_monotone_of_tendsto_div_floor_pow (u : β„• β†’ ℝ) (l : ℝ) (hmono : monotone u) (c : β„• β†’ ℝ) (cone : βˆ€ k, 1 < c k) (clim : tendsto c at_top (𝓝 1)) (hc : βˆ€ k, tendsto (Ξ» (n : β„•), u (⌊(c k) ^ nβŒ‹β‚Š) / ⌊(c k)^nβŒ‹β‚Š) at_top (𝓝 l)) : tendsto (Ξ» n, u n / n) at_top (𝓝 l) := begin apply tendsto_div_of_monotone_of_exists_subseq_tendsto_div u l hmono, assume a ha, obtain ⟨k, hk⟩ : βˆƒ k, c k < a := ((tendsto_order.1 clim).2 a ha).exists, refine ⟨λ n, ⌊(c k)^nβŒ‹β‚Š, _, tendsto_nat_floor_at_top.comp (tendsto_pow_at_top_at_top_of_one_lt (cone k)), hc k⟩, have H : βˆ€ (n : β„•), (0 : ℝ) < ⌊c k ^ nβŒ‹β‚Š, { assume n, refine zero_lt_one.trans_le _, simp only [nat.one_le_cast, nat.one_le_floor_iff, one_le_pow_of_one_le (cone k).le n] }, have A : tendsto (Ξ» (n : β„•), ((⌊c k ^ (n+1)βŒ‹β‚Š : ℝ) / c k ^ (n+1)) * c k / (⌊c k ^ nβŒ‹β‚Š / c k ^ n)) at_top (𝓝 (1 * c k / 1)), { refine tendsto.div (tendsto.mul _ tendsto_const_nhds) _ one_ne_zero, { refine tendsto_nat_floor_div_at_top.comp _, exact (tendsto_pow_at_top_at_top_of_one_lt (cone k)).comp (tendsto_add_at_top_nat 1) }, { refine tendsto_nat_floor_div_at_top.comp _, exact tendsto_pow_at_top_at_top_of_one_lt (cone k) } }, have B : tendsto (Ξ» (n : β„•), (⌊c k ^ (n+1)βŒ‹β‚Š : ℝ) / ⌊c k ^ nβŒ‹β‚Š) at_top (𝓝 (c k)), { simp only [one_mul, div_one] at A, convert A, ext1 n, simp only [(zero_lt_one.trans (cone k)).ne', ne.def, not_false_iff, (H n).ne'] with field_simps {discharger := tactic.field_simp.ne_zero}, ring_exp }, filter_upwards [(tendsto_order.1 B).2 a hk] with n hn, exact (div_le_iff (H n)).1 hn.le end /-- The sum of `1/(c^i)^2` above a threshold `j` is comparable to `1/j^2`, up to a multiplicative constant. -/ lemma sum_div_pow_sq_le_div_sq (N : β„•) {j : ℝ} (hj : 0 < j) {c : ℝ} (hc : 1 < c) : βˆ‘ i in (range N).filter (Ξ» i, j < c ^ i), 1 / (c ^ i) ^ 2 ≀ (c^3 * (c - 1) ⁻¹) / j ^ 2 := begin have cpos : 0 < c := zero_lt_one.trans hc, have A : 0 < (c⁻¹) ^ 2 := sq_pos_of_pos (inv_pos.2 cpos), have B : c^2 * (1 - c⁻¹ ^ 2) ⁻¹ ≀ c^3 * (c - 1) ⁻¹, { rw [← div_eq_mul_inv, ← div_eq_mul_inv, div_le_div_iff _ (sub_pos.2 hc)], swap, { exact sub_pos.2 (pow_lt_one (inv_nonneg.2 cpos.le) (inv_lt_one hc) two_ne_zero) }, have : c ^ 3 = c^2 * c, by ring_exp, simp only [mul_sub, this, mul_one, inv_pow, sub_le_sub_iff_left], rw [mul_assoc, mul_comm c, ← mul_assoc, mul_inv_cancel (sq_pos_of_pos cpos).ne', one_mul], simpa using pow_le_pow hc.le one_le_two }, calc βˆ‘ i in (range N).filter (Ξ» i, j < c ^ i), 1/ (c ^ i) ^ 2 ≀ βˆ‘ i in Ico (⌊real.log j / real.log cβŒ‹β‚Š) N, 1 / (c ^ i) ^ 2 : begin refine sum_le_sum_of_subset_of_nonneg _ (Ξ» i hi hident, div_nonneg zero_le_one (sq_nonneg _)), assume i hi, simp only [mem_filter, mem_range] at hi, simp only [hi.1, mem_Ico, and_true], apply nat.floor_le_of_le, apply le_of_lt, rw [div_lt_iff (real.log_pos hc), ← real.log_pow], exact real.log_lt_log hj hi.2 end ... = βˆ‘ i in Ico (⌊real.log j / real.log cβŒ‹β‚Š) N, ((c⁻¹) ^ 2) ^ i : begin congr' 1 with i, simp [← pow_mul, mul_comm], end ... ≀ ((c⁻¹) ^ 2) ^ (⌊real.log j / real.log cβŒ‹β‚Š) / (1 - (c⁻¹) ^ 2) : begin apply geom_sum_Ico_le_of_lt_one (sq_nonneg _), rw sq_lt_one_iff (inv_nonneg.2 (zero_le_one.trans hc.le)), exact inv_lt_one hc end ... ≀ ((c⁻¹) ^ 2) ^ (real.log j / real.log c - 1) / (1 - (c⁻¹) ^ 2) : begin apply div_le_div _ _ _ le_rfl, { apply real.rpow_nonneg_of_nonneg (sq_nonneg _) }, { rw ← real.rpow_nat_cast, apply real.rpow_le_rpow_of_exponent_ge A, { exact pow_le_one _ (inv_nonneg.2 (zero_le_one.trans hc.le)) (inv_le_one hc.le) }, { exact (nat.sub_one_lt_floor _).le } }, { simpa only [inv_pow, sub_pos] using inv_lt_one (one_lt_pow hc two_ne_zero) } end ... = (c^2 * (1 - c⁻¹ ^ 2) ⁻¹) / j ^ 2 : begin have I : (c ⁻¹ ^ 2) ^ (real.log j / real.log c) = 1 / j ^ 2, { apply real.log_inj_on_pos (real.rpow_pos_of_pos A _), { rw [one_div], exact inv_pos.2 (sq_pos_of_pos hj) }, rw real.log_rpow A, simp only [one_div, real.log_inv, real.log_pow, nat.cast_bit0, nat.cast_one, mul_neg, neg_inj], field_simp [(real.log_pos hc).ne'], ring }, rw [real.rpow_sub A, I], have : c^2 - 1 β‰  0 := (sub_pos.2 (one_lt_pow hc two_ne_zero)).ne', field_simp [hj.ne', (zero_lt_one.trans hc).ne'], ring, end ... ≀ (c^3 * (c - 1) ⁻¹) / j ^ 2 : begin apply div_le_div _ B (sq_pos_of_pos hj) le_rfl, exact mul_nonneg (pow_nonneg cpos.le _) (inv_nonneg.2 (sub_pos.2 hc).le), end end lemma mul_pow_le_nat_floor_pow {c : ℝ} (hc : 1 < c) (i : β„•) : (1 - c⁻¹) * c ^ i ≀ ⌊c ^ iβŒ‹β‚Š := begin have cpos : 0 < c := zero_lt_one.trans hc, rcases nat.eq_zero_or_pos i with rfl|hi, { simp only [pow_zero, nat.floor_one, nat.cast_one, mul_one, sub_le_self_iff, inv_nonneg, cpos.le] }, have hident : 1 ≀ i := hi, calc (1 - c⁻¹) * c ^ i = c ^ i - c ^ i * c ⁻¹ : by ring ... ≀ c ^ i - 1 : by simpa only [←div_eq_mul_inv, sub_le_sub_iff_left, one_le_div cpos, pow_one] using pow_le_pow hc.le hident ... ≀ ⌊c ^ iβŒ‹β‚Š : (nat.sub_one_lt_floor _).le end /-- The sum of `1/⌊c^iβŒ‹β‚Š^2` above a threshold `j` is comparable to `1/j^2`, up to a multiplicative constant. -/ lemma sum_div_nat_floor_pow_sq_le_div_sq (N : β„•) {j : ℝ} (hj : 0 < j) {c : ℝ} (hc : 1 < c) : βˆ‘ i in (range N).filter (Ξ» i, j < ⌊c ^ iβŒ‹β‚Š), (1 : ℝ) / ⌊c ^ iβŒ‹β‚Š ^ 2 ≀ (c ^ 5 * (c - 1) ⁻¹ ^ 3) / j ^ 2 := begin have cpos : 0 < c := zero_lt_one.trans hc, have A : 0 < 1 - c⁻¹ := sub_pos.2 (inv_lt_one hc), calc βˆ‘ i in (range N).filter (Ξ» i, j < ⌊c ^ iβŒ‹β‚Š), (1 : ℝ) / ⌊c ^ iβŒ‹β‚Š ^ 2 ≀ βˆ‘ i in (range N).filter (Ξ» i, j < c ^ i), (1 : ℝ) / ⌊c ^ iβŒ‹β‚Š ^ 2 : begin apply sum_le_sum_of_subset_of_nonneg, { assume i hi, simp only [mem_filter, mem_range] at hi, simpa only [hi.1, mem_filter, mem_range, true_and] using hi.2.trans_le (nat.floor_le (pow_nonneg cpos.le _)) }, { assume i hi hident, exact div_nonneg zero_le_one (sq_nonneg _), } end ... ≀ βˆ‘ i in (range N).filter (Ξ» i, j < c ^ i), ((1 - c⁻¹) ⁻¹) ^ 2 * (1 / (c ^ i) ^ 2) : begin apply sum_le_sum (Ξ» i hi, _), rw [mul_div_assoc', mul_one, div_le_div_iff], rotate, { apply sq_pos_of_pos, refine zero_lt_one.trans_le _, simp only [nat.le_floor, one_le_pow_of_one_le, hc.le, nat.one_le_cast, nat.cast_one] }, { exact sq_pos_of_pos (pow_pos cpos _) }, rw [one_mul, ← mul_pow], apply pow_le_pow_of_le_left (pow_nonneg cpos.le _), rw [← div_eq_inv_mul, le_div_iff A, mul_comm], exact mul_pow_le_nat_floor_pow hc i, end ... ≀ ((1 - c⁻¹) ⁻¹) ^ 2 * (c^3 * (c - 1) ⁻¹) / j ^ 2 : begin rw [← mul_sum, ← mul_div_assoc'], refine mul_le_mul_of_nonneg_left _ (sq_nonneg _), exact sum_div_pow_sq_le_div_sq N hj hc, end ... = (c ^ 5 * (c - 1) ⁻¹ ^ 3) / j ^ 2 : begin congr' 1, field_simp [cpos.ne', (sub_pos.2 hc).ne'], ring, end end
07910707512590bd1405a19ac58f5325d1e4fc62
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Message.lean
94e53a4c9ab4a2f4055dc89acfe2b1c5a1c29cce
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
15,284
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich, Leonardo de Moura Message Type used by the Lean frontend -/ import Lean.Data.Position import Lean.Data.OpenDecl import Lean.Syntax import Lean.MetavarContext import Lean.Environment import Lean.Util.PPExt namespace Lean def mkErrorStringWithPos (fileName : String) (pos : Position) (msg : String) (endPos : Option Position := none) : String := let endPos := match endPos with | some endPos => s!"-{endPos.line}:{endPos.column}" | none => "" s!"{fileName}:{pos.line}:{pos.column}{endPos}: {msg}" inductive MessageSeverity where | information | warning | error deriving Inhabited, BEq structure MessageDataContext where env : Environment mctx : MetavarContext lctx : LocalContext opts : Options structure NamingContext where currNamespace : Name openDecls : List OpenDecl /- Structure message data. We use it for reporting errors, trace messages, etc. -/ inductive MessageData where | ofFormat : Format β†’ MessageData | ofSyntax : Syntax β†’ MessageData | ofExpr : Expr β†’ MessageData | ofLevel : Level β†’ MessageData | ofName : Name β†’ MessageData | ofGoal : MVarId β†’ MessageData /- `withContext ctx d` specifies the pretty printing context `(env, mctx, lctx, opts)` for the nested expressions in `d`. -/ | withContext : MessageDataContext β†’ MessageData β†’ MessageData | withNamingContext : NamingContext β†’ MessageData β†’ MessageData /- Lifted `Format.nest` -/ | nest : Nat β†’ MessageData β†’ MessageData /- Lifted `Format.group` -/ | group : MessageData β†’ MessageData /- Lifted `Format.compose` -/ | compose : MessageData β†’ MessageData β†’ MessageData /- Tagged sections. `Name` should be viewed as a "kind", and is used by `MessageData` inspector functions. Example: an inspector that tries to find "definitional equality failures" may look for the tag "DefEqFailure". -/ | tagged : Name β†’ MessageData β†’ MessageData | trace (cls : Name) (msg : MessageData) (children : Array MessageData) (collapsed : Bool := false) deriving Inhabited namespace MessageData partial def isEmpty : MessageData β†’ Bool | ofFormat f => f.isEmpty | withContext _ m => m.isEmpty | withNamingContext _ m => m.isEmpty | nest _ m => m.isEmpty | group m => m.isEmpty | compose m₁ mβ‚‚ => m₁.isEmpty && mβ‚‚.isEmpty | tagged _ m => m.isEmpty | _ => false /- Instantiate metavariables occurring in nexted `ofExpr` constructors. It uses the surrounding `MetavarContext` at `withContext` constructors. -/ partial def instantiateMVars (msg : MessageData) : MessageData := visit msg {} where visit (msg : MessageData) (mctx : MetavarContext) : MessageData := match msg with | ofExpr e => ofExpr <| instantiateMVarsCore mctx e |>.1 | withContext ctx msg => withContext ctx <| visit msg ctx.mctx | withNamingContext ctx msg => withNamingContext ctx <| visit msg mctx | nest n msg => nest n <| visit msg mctx | group msg => group <| visit msg mctx | compose msg₁ msgβ‚‚ => compose (visit msg₁ mctx) <| visit msgβ‚‚ mctx | tagged n msg => tagged n <| visit msg mctx | trace cls msg msgs c => trace cls (visit msg mctx) (msgs.map (visit Β· mctx)) c | _ => msg variable (p : Name β†’ Bool) in partial def hasTag : MessageData β†’ Bool | withContext _ msg => hasTag msg | withNamingContext _ msg => hasTag msg | nest _ msg => hasTag msg | group msg => hasTag msg | compose msg₁ msgβ‚‚ => hasTag msg₁ || hasTag msgβ‚‚ | tagged n msg => p n || hasTag msg | trace cls msg msgs _ => p cls || hasTag msg || msgs.any hasTag | _ => false def nil : MessageData := ofFormat Format.nil def isNil : MessageData β†’ Bool | ofFormat Format.nil => true | _ => false def isNest : MessageData β†’ Bool | nest _ _ => true | _ => false def mkPPContext (nCtx : NamingContext) (ctx : MessageDataContext) : PPContext := { env := ctx.env, mctx := ctx.mctx, lctx := ctx.lctx, opts := ctx.opts, currNamespace := nCtx.currNamespace, openDecls := nCtx.openDecls } partial def formatAux : NamingContext β†’ Option MessageDataContext β†’ MessageData β†’ IO Format | _, _, ofFormat fmt => return fmt | _, _, ofLevel u => return format u | _, _, ofName n => return format n | nCtx, some ctx, ofSyntax s => ppTerm (mkPPContext nCtx ctx) ⟨s⟩ -- HACK: might not be a term | _, none, ofSyntax s => return s.formatStx | _, none, ofExpr e => return format (toString e) | nCtx, some ctx, ofExpr e => ppExpr (mkPPContext nCtx ctx) e | _, none, ofGoal mvarId => return "goal " ++ format (mkMVar mvarId) | nCtx, some ctx, ofGoal mvarId => ppGoal (mkPPContext nCtx ctx) mvarId | nCtx, _, withContext ctx d => formatAux nCtx ctx d | _, ctx, withNamingContext nCtx d => formatAux nCtx ctx d | nCtx, ctx, tagged _ d => formatAux nCtx ctx d | nCtx, ctx, nest n d => Format.nest n <$> formatAux nCtx ctx d | nCtx, ctx, compose d₁ dβ‚‚ => return (← formatAux nCtx ctx d₁) ++ (← formatAux nCtx ctx dβ‚‚) | nCtx, ctx, group d => Format.group <$> formatAux nCtx ctx d | nCtx, ctx, trace cls header children _ => do let msg := f!"[{cls}] {(← formatAux nCtx ctx header).nest 2}" let children ← children.mapM (formatAux nCtx ctx) return .nest 2 (.joinSep (msg::children.toList) "\n") protected def format (msgData : MessageData) : IO Format := formatAux { currNamespace := Name.anonymous, openDecls := [] } none msgData protected def toString (msgData : MessageData) : IO String := do return toString (← msgData.format) instance : Append MessageData := ⟨compose⟩ instance : Coe String MessageData := ⟨ofFormat ∘ format⟩ instance : Coe Format MessageData := ⟨ofFormat⟩ instance : Coe Level MessageData := ⟨ofLevel⟩ instance : Coe Expr MessageData := ⟨ofExpr⟩ instance : Coe Name MessageData := ⟨ofName⟩ instance : Coe Syntax MessageData := ⟨ofSyntax⟩ instance : Coe MVarId MessageData := ⟨ofGoal⟩ instance : Coe (Option Expr) MessageData := ⟨fun o => match o with | none => "none" | some e => ofExpr e⟩ partial def arrayExpr.toMessageData (es : Array Expr) (i : Nat) (acc : MessageData) : MessageData := if h : i < es.size then let e := es.get ⟨i, h⟩; let acc := if i == 0 then acc ++ ofExpr e else acc ++ ", " ++ ofExpr e; toMessageData es (i+1) acc else acc ++ "]" instance : Coe (Array Expr) MessageData := ⟨fun es => arrayExpr.toMessageData es 0 "#["⟩ def bracket (l : String) (f : MessageData) (r : String) : MessageData := group (nest l.length <| l ++ f ++ r) def paren (f : MessageData) : MessageData := bracket "(" f ")" def sbracket (f : MessageData) : MessageData := bracket "[" f "]" def joinSep : List MessageData β†’ MessageData β†’ MessageData | [], _ => Format.nil | [a], _ => a | a::as, sep => a ++ sep ++ joinSep as sep def ofList: List MessageData β†’ MessageData | [] => "[]" | xs => sbracket <| joinSep xs (ofFormat "," ++ Format.line) def ofArray (msgs : Array MessageData) : MessageData := ofList msgs.toList instance : Coe (List MessageData) MessageData := ⟨ofList⟩ instance : Coe (List Expr) MessageData := ⟨fun es => ofList <| es.map ofExpr⟩ end MessageData structure Message where fileName : String pos : Position endPos : Option Position := none severity : MessageSeverity := MessageSeverity.error caption : String := "" data : MessageData deriving Inhabited namespace Message protected def toString (msg : Message) (includeEndPos := false) : IO String := do let mut str ← msg.data.toString let endPos := if includeEndPos then msg.endPos else none unless msg.caption == "" do str := msg.caption ++ ":\n" ++ str match msg.severity with | MessageSeverity.information => pure () | MessageSeverity.warning => str := mkErrorStringWithPos msg.fileName msg.pos (endPos := endPos) "warning: " ++ str | MessageSeverity.error => str := mkErrorStringWithPos msg.fileName msg.pos (endPos := endPos) "error: " ++ str if str.isEmpty || str.back != '\n' then str := str ++ "\n" return str end Message structure MessageLog where msgs : Std.PersistentArray Message := {} deriving Inhabited namespace MessageLog def empty : MessageLog := ⟨{}⟩ def isEmpty (log : MessageLog) : Bool := log.msgs.isEmpty def add (msg : Message) (log : MessageLog) : MessageLog := ⟨log.msgs.push msg⟩ protected def append (l₁ lβ‚‚ : MessageLog) : MessageLog := ⟨l₁.msgs ++ lβ‚‚.msgs⟩ instance : Append MessageLog := ⟨MessageLog.append⟩ def hasErrors (log : MessageLog) : Bool := log.msgs.any fun m => match m.severity with | MessageSeverity.error => true | _ => false def errorsToWarnings (log : MessageLog) : MessageLog := { msgs := log.msgs.map (fun m => match m.severity with | MessageSeverity.error => { m with severity := MessageSeverity.warning } | _ => m) } def getInfoMessages (log : MessageLog) : MessageLog := { msgs := log.msgs.filter fun m => match m.severity with | MessageSeverity.information => true | _ => false } def forM {m : Type β†’ Type} [Monad m] (log : MessageLog) (f : Message β†’ m Unit) : m Unit := log.msgs.forM f def toList (log : MessageLog) : List Message := (log.msgs.foldl (fun acc msg => msg :: acc) []).reverse end MessageLog def MessageData.nestD (msg : MessageData) : MessageData := MessageData.nest 2 msg def indentD (msg : MessageData) : MessageData := MessageData.nestD (Format.line ++ msg) def indentExpr (e : Expr) : MessageData := indentD e class AddMessageContext (m : Type β†’ Type) where addMessageContext : MessageData β†’ m MessageData export AddMessageContext (addMessageContext) instance (m n) [MonadLift m n] [AddMessageContext m] : AddMessageContext n where addMessageContext := fun msg => liftM (addMessageContext msg : m _) def addMessageContextPartial {m} [Monad m] [MonadEnv m] [MonadOptions m] (msgData : MessageData) : m MessageData := do let env ← getEnv let opts ← getOptions return MessageData.withContext { env := env, mctx := {}, lctx := {}, opts := opts } msgData def addMessageContextFull {m} [Monad m] [MonadEnv m] [MonadMCtx m] [MonadLCtx m] [MonadOptions m] (msgData : MessageData) : m MessageData := do let env ← getEnv let mctx ← getMCtx let lctx ← getLCtx let opts ← getOptions return MessageData.withContext { env := env, mctx := mctx, lctx := lctx, opts := opts } msgData class ToMessageData (Ξ± : Type) where toMessageData : Ξ± β†’ MessageData export ToMessageData (toMessageData) def stringToMessageData (str : String) : MessageData := let lines := str.split (Β· == '\n') let lines := lines.map (MessageData.ofFormat ∘ format) MessageData.joinSep lines (MessageData.ofFormat Format.line) instance [ToFormat Ξ±] : ToMessageData Ξ± := ⟨MessageData.ofFormat ∘ format⟩ instance : ToMessageData Expr := ⟨MessageData.ofExpr⟩ instance : ToMessageData Level := ⟨MessageData.ofLevel⟩ instance : ToMessageData Name := ⟨MessageData.ofName⟩ instance : ToMessageData String := ⟨stringToMessageData⟩ instance : ToMessageData Syntax := ⟨MessageData.ofSyntax⟩ instance : ToMessageData (TSyntax k) := ⟨(MessageData.ofSyntax Β·)⟩ instance : ToMessageData Format := ⟨MessageData.ofFormat⟩ instance : ToMessageData MVarId := ⟨MessageData.ofGoal⟩ instance : ToMessageData MessageData := ⟨id⟩ instance [ToMessageData Ξ±] : ToMessageData (List Ξ±) := ⟨fun as => MessageData.ofList <| as.map toMessageData⟩ instance [ToMessageData Ξ±] : ToMessageData (Array Ξ±) := ⟨fun as => toMessageData as.toList⟩ instance [ToMessageData Ξ±] : ToMessageData (Subarray Ξ±) := ⟨fun as => toMessageData as.toArray.toList⟩ instance [ToMessageData Ξ±] : ToMessageData (Option Ξ±) := ⟨fun | none => "none" | some e => "some (" ++ toMessageData e ++ ")"⟩ instance : ToMessageData (Option Expr) := ⟨fun | none => "<not-available>" | some e => toMessageData e⟩ syntax:max "m!" interpolatedStr(term) : term macro_rules | `(m! $interpStr) => do interpStr.expandInterpolatedStr (← `(MessageData)) (← `(toMessageData)) def toMessageList (msgs : Array MessageData) : MessageData := indentD (MessageData.joinSep msgs.toList m!"\n\n") namespace KernelException private def mkCtx (env : Environment) (lctx : LocalContext) (opts : Options) (msg : MessageData) : MessageData := MessageData.withContext { env := env, mctx := {}, lctx := lctx, opts := opts } msg def toMessageData (e : KernelException) (opts : Options) : MessageData := match e with | unknownConstant env constName => mkCtx env {} opts m!"(kernel) unknown constant '{constName}'" | alreadyDeclared env constName => mkCtx env {} opts m!"(kernel) constant has already been declared '{constName}'" | declTypeMismatch env decl givenType => mkCtx env {} opts <| let process (n : Name) (expectedType : Expr) : MessageData := m!"(kernel) declaration type mismatch, '{n}' has type{indentExpr givenType}\nbut it is expected to have type{indentExpr expectedType}"; match decl with | Declaration.defnDecl { name := n, type := type, .. } => process n type | Declaration.thmDecl { name := n, type := type, .. } => process n type | _ => "(kernel) declaration type mismatch" -- TODO fix type checker, type mismatch for mutual decls does not have enough information | declHasMVars env constName _ => mkCtx env {} opts m!"(kernel) declaration has metavariables '{constName}'" | declHasFVars env constName _ => mkCtx env {} opts m!"(kernel) declaration has free variables '{constName}'" | funExpected env lctx e => mkCtx env lctx opts m!"(kernel) function expected{indentExpr e}" | typeExpected env lctx e => mkCtx env lctx opts m!"(kernel) type expected{indentExpr e}" | letTypeMismatch env lctx n _ _ => mkCtx env lctx opts m!"(kernel) let-declaration type mismatch '{n}'" | exprTypeMismatch env lctx e _ => mkCtx env lctx opts m!"(kernel) type mismatch at{indentExpr e}" | appTypeMismatch env lctx e fnType argType => mkCtx env lctx opts m!"application type mismatch{indentExpr e}\nargument has type{indentExpr argType}\nbut function has type{indentExpr fnType}" | invalidProj env lctx e => mkCtx env lctx opts m!"(kernel) invalid projection{indentExpr e}" | other msg => m!"(kernel) {msg}" end KernelException end Lean
aacde6d70d47cc8bbd1df7c8fa8093f97e941ce6
fe84e287c662151bb313504482b218a503b972f3
/src/exercises/mathcomp_book/chapter_2.lean
78a4be1079ff767d06272e3c6a8e2e097e0e415e
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
10,092
lean
import data.nat.gcd data.nat.prime import tactic.tauto tactic.squeeze tactic.find /- --------------------------------------------------------------- -/ -- Section 2.1.1 #check 3 = 3 #check (ff && tt = ff) #check (false ∧ true = false) #print notation `=` #print eq -- #check (3 = [3]) -- ERROR #check 3 = 4 lemma my_first_lemma : 3 = 3 := rfl #check my_first_lemma /- --------------------------------------------------------------- -/ -- Section 2.1.2 lemma my_add_assoc (n m k : β„•) : m + (n + k) = (m + n) + k := (nat.add_assoc _ _ _).symm lemma my_bor_tt (b : bool) : b || tt = tt := by { cases b; refl } lemma my_bor_assoc (b1 b2 b3) : b1 || (b2 || b3) = (b1 || b2) || b3 := by { cases b1; cases b2; cases b3; refl, } -- Next example skipped because bool implication is not predefined in Lean lemma my_bnot_and (a b : bool) : bnot (a && b) = (bnot a) || (bnot b) := by { cases a; cases b; refl } /- --------------------------------------------------------------- -/ -- Section 2.1.3 lemma my_zero_le (n : β„•) : 0 ≀ n := begin induction n with n ih, exact nat.less_than_or_equal.refl, exact nat.less_than_or_equal.step ih, end def odd' (n : β„•) : Prop := (n % 2 = 1) lemma eq_leq (m n : β„•) : m = n ↔ ((m ≀ n) ∧ (n ≀ m)) := sorry lemma ne_lt (m n : β„•) : m β‰  n ↔ ((m < n) ∨ (n < m)) := sorry lemma le_zero (n : β„•) : n ≀ 0 ↔ n = 0 := sorry lemma dvd_one (d : β„•) : (d ∣ 1) ↔ (d = 1) := sorry lemma odd_mul (m n : β„•) : odd' (m * n) ↔ (odd' n) ∧ (odd' m) := sorry /- --------------------------------------------------------------- -/ -- Section 2.1.4 lemma leq_pmull (m n : β„•) : (n > 0) β†’ m ≀ n * m := sorry lemma odd_gt_zero (n : β„•) : odd' n β†’ n > 0 := sorry lemma dvd_mul (d1 d2 m1 m2 : β„•) : (d1 ∣ m1) β†’ (d2 ∣ m2) β†’ d1 * d2 ∣ m1 * m2 := sorry /- --------------------------------------------------------------- -/ -- Section 2.2.1 lemma my_first_lemma' : 3 = 3 := by refl lemma my_second_lemma : 2 + 1 = 3 := rfl lemma add_succ (m n : β„•) : m + (nat.succ n) = nat.succ (m + n) := rfl lemma my_bnot_bnot (b : bool) : bnot (bnot b) = b := by {cases b; refl,} lemma le_zero' (n : β„•) : n ≀ 0 ↔ n = 0 := by { cases n with k; simp, } lemma my_mul_eq_zero (m n : β„•) : (m * n = 0) ↔ (m = 0) ∨ (n = 0) := begin cases n; cases m; try {simp [-nat.mul_eq_zero]} end /- --------------------------------------------------------------- -/ -- Section 2.3.1 def is_zero : β„• β†’ bool | 0 := tt | _ := ff def my_le (n m : β„•) : bool := is_zero (n - m) lemma le_zero'' (n m : β„•) : (my_le n 0) = is_zero n := begin cases n; dsimp[my_le]; refl, end lemma list_ext (s₁ sβ‚‚ : list β„•) : s₁.length = sβ‚‚.length β†’ βˆ€ i, s₁.nth i = sβ‚‚.nth i β†’ s₁ = sβ‚‚ := sorry lemma map_length {Ξ± Ξ² : Type} (f : Ξ± β†’ Ξ²) (s : list Ξ±) : list.length (list.map f s) = list.length s := sorry def my_commutative {Ξ± Ξ² : Type} (op : Ξ± β†’ Ξ± β†’ Ξ²) := βˆ€ a₁ aβ‚‚ : Ξ±, op a₁ aβ‚‚ = op aβ‚‚ a₁ lemma my_add_comm : my_commutative nat.add := nat.add_comm #print associative #print right_distrib #print left_distrib #print left_identity #print function.injective #print function.left_inverse /- --------------------------------------------------------------- -/ -- Section 2.3.2 section chinese variables m₁ mβ‚‚ : β„• variable co_n12 : nat.coprime m₁ mβ‚‚ lemma chinese_remainder (x y : β„•) : x % (m₁ * mβ‚‚) = y % (m₁ * mβ‚‚) ↔ x % m₁ = y % m₁ ∧ x % mβ‚‚ = y % mβ‚‚ := sorry end chinese /- --------------------------------------------------------------- -/ -- Section 2.3.3 lemma my_le_refl (n : β„•) : n ≀ n := le_refl n example (a b : β„•) : a + b ≀ a + b := my_le_refl (a + b) example (a b : β„•) : a + (nat.succ b) ≀ nat.succ (a + b) := begin apply my_le_refl, end attribute [simp] my_le_refl example (a b : β„•) : a + (nat.succ b) ≀ nat.succ (a + b) := sorry lemma contra (c b : Prop) : (Β¬ c β†’ Β¬ b) β†’ (b β†’ c) := begin intros h hb, cases classical.em c with hc hnc, {exact hc}, {exact false.elim (h hnc hb)} end example (m p : β„•) : nat.prime p β†’ p ∣ ((nat.factorial m) + 1) β†’ m < p := begin intro prime_p, apply contra, intro h0, have leq_p_m : p ≀ m := le_of_not_gt h0, rw[← (@nat.dvd_add_iff_right p (nat.factorial m) 1)], {exact nat.prime.not_dvd_one prime_p}, {exact nat.dvd_factorial (nat.prime.pos prime_p) leq_p_m} end example (m p : β„•) : nat.prime p β†’ p ∣ ((nat.factorial m) + 1) β†’ m < p := begin intros prime_p d1, cases lt_or_ge m p, assumption, exfalso, rw[← (@nat.dvd_add_iff_right p (nat.factorial m) 1)] at d1, exact nat.prime.not_dvd_one prime_p d1, exact nat.dvd_factorial (nat.prime.pos prime_p) h, end /- --------------------------------------------------------------- -/ -- Section 2.3.4 #check @nat.rec #check @list.rec lemma my_add_zero (m : β„•) : m + 0 = m := rfl lemma my_zero_add (m : β„•) : 0 + m = m := begin induction m with m ih,refl,exact congr_arg nat.succ ih, end lemma last_ind (Ξ± : Type) (P : list Ξ± β†’ Prop) : (P list.nil) β†’ (βˆ€ s x, P s β†’ P (s.concat x)) β†’ βˆ€ s, P s := begin intros P_nil P_step, let C : (list Ξ±) β†’ Prop := Ξ» s, (βˆ€ (Q : list Ξ± β†’ Prop) (Q_nil : Q list.nil) (Q_step : βˆ€ t x, Q t β†’ Q (t.concat x)), Q s), have h : βˆ€ s : list Ξ±, C s, {intro s, induction s with w s ih, {intros Q Q_nil Q_step,exact Q_nil}, {intros Q Q_nil Q_step, let R := Ξ» t, Q (w :: t), let R_nil : R list.nil := Q_step list.nil w Q_nil, let R_step : βˆ€ t x, R t β†’ R (t.concat x) := Ξ» t x R_t, Q_step (w :: t) x R_t, exact ih R R_nil R_step, } }, intro s, exact h s P P_nil P_step, end lemma foldl_rev (Ξ± Ξ² : Type) (f : Ξ± β†’ Ξ² β†’ Ξ±) (z : Ξ±) (s : list Ξ²) : list.foldl f z s.reverse = list.foldr (Ξ» x z, f z x) z s := begin revert z, refine last_ind Ξ² _ _ _ s, {intro z,simp,}, {intros t x h0 z, have h1 : list.reverse (list.concat t x) = x :: (list.reverse t) := by simp, have h2 : t.concat x = t ++ [x] := by simp, rw[h1,h2,list.foldl,h0 (f z x),list.foldr_append,list.foldr,list.foldr], } end /- --------------------------------------------------------------- -/ -- Section 2.4 example (m p : β„•) : nat.prime p β†’ p ∣ ((nat.factorial m) + 1) β†’ m < p := begin intros prime_p,apply contra,intros h0 d1, exact nat.prime.not_dvd_one prime_p ((@nat.dvd_add_iff_right p (nat.factorial m) 1 (nat.dvd_factorial (nat.prime.pos prime_p) (le_of_not_gt h0))).mpr d1), end /- --------------------------------------------------------------- -/ -- Section 2.5 -- #find nat.bodd -- #find (_ ∣ nat.fact _) -- #find nat.coprime -- #find (_ * _ = _ * _) /- --------------------------------------------------------------- -/ -- Exercises for Chapter 2 example (b1 b2 b3 : bool) : b1 || (b2 || b3) = (b1 || b2) || b3 := by {cases b1; cases b2; cases b3; refl,} -- Next example skipped as boolean implication is not predefined in Lean example (a b : bool) : bnot (a && b) = (bnot a) || (bnot b) := by {cases a; cases b; refl,} lemma nat.sub_add : βˆ€ (n m k : β„•), n - (m + k) = (n - m) - k | n m 0 := by {rw[add_zero,nat.sub_zero],} | n m (nat.succ k) := by {rw[nat.add_succ,nat.sub_succ,nat.sub_add,nat.sub_succ]} lemma nat.mul_pred (n m : β„•) : n * (nat.pred m) = n * m - n := begin cases m, {rw[nat.pred_zero,mul_zero,nat.zero_sub],}, {rw[nat.pred_succ,nat.mul_succ,nat.add_sub_cancel],} end lemma nat.pred_mul (n m : β„•) : (nat.pred n) * m = n * m - m := by { rw[nat.mul_comm,nat.mul_pred,nat.mul_comm], } lemma nat.mul_sub : βˆ€ (n m k : β„•), n * (m - k) = n * m - n * k | n m 0 := by { rw[mul_zero,nat.sub_zero,nat.sub_zero],} | n m (k + 1) := by {rw[nat.sub_succ,nat.mul_pred,nat.mul_sub,nat.mul_succ,nat.sub_add],} lemma nat.sub_mul (n m k : β„•) : (n - m) * k = n * k - m * k := by {rw[nat.mul_comm,nat.mul_sub],congr' 1;apply nat.mul_comm} example (n m : β„•) : m ^ 2 - n ^ 2 = (m - n) * (m + n) := begin rw[pow_two,pow_two,nat.sub_mul,mul_add,mul_add,nat.mul_comm m n], rw[nat.sub_add,nat.add_sub_cancel], end lemma bodd_exp (m n : β„•) : nat.bodd (m ^ n) = (n = 0) || nat.bodd m := begin induction n with n ih, {refl,}, {rw[to_bool_ff (nat.succ_ne_zero n),ff_bor,pow_succ,nat.bodd_mul,ih], cases (nat.bodd m); cases (to_bool (n = 0)); refl } end def flatten {Ξ± : Type} (l : list (list Ξ±)) : list Ξ± := list.foldr list.append list.nil l lemma flatten_length {Ξ± : Type} : βˆ€ (l : list (list Ξ±)), (flatten l).length = list.sum (l.map list.length) | list.nil := rfl | (list.cons u l) := by { erw[list.length_append,flatten_length l,list.map_cons,list.sum_cons], } def all_words {Ξ± : Type} : βˆ€ (n : β„•) (alphabet : list Ξ±), list (list Ξ±) | 0 _ := [list.nil] | (nat.succ n) alphabet := flatten (list.map (Ξ» a,list.map (list.cons a) (all_words n alphabet)) alphabet) lemma all_words_length {Ξ± : Type} (n : β„•) (alphabet : list Ξ±) : (all_words n alphabet).length = alphabet.length ^ n := begin induction n with n ih, {refl,}, {erw[all_words,flatten_length], rw[pow_succ,mul_comm], let f : Ξ± β†’ list (list Ξ±) := Ξ» a, list.map (list.cons a) (all_words n alphabet), let g : Ξ± β†’ β„• := Ξ» a, (f a).length, let l := alphabet.map f, let m := l.map list.length, have h0 : βˆ€ a : Ξ±, g a = alphabet.length ^ n := Ξ» a, (list.length_map _ _).trans ih, have h1 : m.length = alphabet.length := (list.length_map list.length l).trans (list.length_map f alphabet), have h2 : βˆ€ i : β„•, i ∈ m β†’ i = alphabet.length ^ n := begin intros i i_in_m, rcases list.mem_map.mp i_in_m with ⟨l0,⟨l0_in_l,l0_length⟩⟩, rcases list.mem_map.mp l0_in_l with ⟨a,⟨a_in_alphabet,fa_eq_l0⟩⟩, exact ((h0 a).symm.trans ((congr_arg list.length fa_eq_l0).trans l0_length)).symm, end, let h3 := (@list.eq_repeat β„• (alphabet.length ^ n) alphabet.length (l.map list.length)).mpr ⟨h1,h2⟩, exact ((congr_arg list.sum h3).trans (list.sum_const_nat (alphabet.length ^ n) alphabet.length)), } end
152db41d0b03ced1d44de52fb32b206de2bd4351
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Init/Notation.lean
a167f0f66b7c94079b5953e0f10b67da2f6ee8aa
[ "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
21,218
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro Notation for operators defined at Prelude.lean -/ prelude import Init.Prelude import Init.Coe set_option linter.missingDocs true -- keep it documented namespace Lean /-- Auxiliary type used to represent syntax categories. We mainly use auxiliary definitions with this type to attach doc strings to syntax categories. -/ structure Parser.Category namespace Parser.Category /-- `command` is the syntax category for things that appear at the top level of a lean file. For example, `def foo := 1` is a `command`, as is `namespace Foo` and `end Foo`. Commands generally have an effect on the state of adding something to the environment (like a new definition), as well as commands like `variable` which modify future commands within a scope. -/ def command : Category := {} /-- `term` is the builtin syntax category for terms. A term denotes an expression in lean's type theory, for example `2 + 2` is a term. The difference between `Term` and `Expr` is that the former is a kind of syntax, while the latter is the result of elaboration. For example `by simp` is also a `Term`, but it elaborates to different `Expr`s depending on the context. -/ def term : Category := {} /-- `tactic` is the builtin syntax category for tactics. These appear after `by` in proofs, and they are programs that take in the proof context (the hypotheses in scope plus the type of the term to synthesize) and construct a term of the expected type. For example, `simp` is a tactic, used in: ``` example : 2 + 2 = 4 := by simp ``` -/ def tactic : Category := {} /-- `doElem` is a builtin syntax category for elements that can appear in the `do` notation. For example, `let x ← e` is a `doElem`, and a `do` block consists of a list of `doElem`s. -/ def doElem : Category := {} /-- `level` is a builtin syntax category for universe levels. This is the `u` in `Sort u`: it can contain `max` and `imax`, addition with constants, and variables. -/ def level : Category := {} /-- `attr` is a builtin syntax category for attributes. Declarations can be annotated with attributes using the `@[...]` notation. -/ def attr : Category := {} /-- `stx` is a builtin syntax category for syntax. This is the abbreviated parser notation used inside `syntax` and `macro` declarations. -/ def stx : Category := {} /-- `prio` is a builtin syntax category for priorities. Priorities are used in many different attributes. Higher numbers denote higher priority, and for example typeclass search will try high priority instances before low priority. In addition to literals like `37`, you can also use `low`, `mid`, `high`, as well as add and subtract priorities. -/ def prio : Category := {} /-- `prec` is a builtin syntax category for precedences. A precedence is a value that expresses how tightly a piece of syntax binds: for example `1 + 2 * 3` is parsed as `1 + (2 * 3)` because `*` has a higher pr0ecedence than `+`. Higher numbers denote higher precedence. In addition to literals like `37`, there are some special named priorities: * `arg` for the precedence of function arguments * `max` for the highest precedence used in term parsers (not actually the maximum possible value) * `lead` for the precedence of terms not supposed to be used as arguments and you can also add and subtract precedences. -/ def prec : Category := {} end Parser.Category namespace Parser.Syntax /-! DSL for specifying parser precedences and priorities -/ /-- Addition of precedences. This is normally used only for offseting, e.g. `max + 1`. -/ syntax:65 (name := addPrec) prec " + " prec:66 : prec /-- Subtraction of precedences. This is normally used only for offseting, e.g. `max - 1`. -/ syntax:65 (name := subPrec) prec " - " prec:66 : prec /-- Addition of priorities. This is normally used only for offseting, e.g. `default + 1`. -/ syntax:65 (name := addPrio) prio " + " prio:66 : prio /-- Subtraction of priorities. This is normally used only for offseting, e.g. `default - 1`. -/ syntax:65 (name := subPrio) prio " - " prio:66 : prio end Parser.Syntax instance : CoeHead (TSyntax ks) Syntax where coe stx := stx.raw instance : Coe SyntaxNodeKind SyntaxNodeKinds where coe k := List.cons k List.nil end Lean /-- Maximum precedence used in term parsers, in particular for terms in function position (`ident`, `paren`, ...) -/ macro "max" : prec => `(1024) /-- Precedence used for application arguments (`do`, `by`, ...). -/ macro "arg" : prec => `(1023) /-- Precedence used for terms not supposed to be used as arguments (`let`, `have`, ...). -/ macro "lead" : prec => `(1022) /-- Parentheses are used for grouping precedence expressions. -/ macro "(" p:prec ")" : prec => return p /-- Minimum precedence used in term parsers. -/ macro "min" : prec => `(10) /-- `(min+1)` (we can only write `min+1` after `Meta.lean`) -/ macro "min1" : prec => `(11) /-- `max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`. We use `max_prec` to workaround bootstrapping issues. -/ macro "max_prec" : term => `(1024) /-- The default priority `default = 1000`, which is used when no priority is set. -/ macro "default" : prio => `(1000) /-- The standardized "low" priority `low = 100`, for things that should be lower than default priority. -/ macro "low" : prio => `(100) /-- The standardized "medium" priority `med = 1000`. This is the same as `default`. -/ macro "mid" : prio => `(1000) /-- The standardized "high" priority `high = 10000`, for things that should be higher than default priority. -/ macro "high" : prio => `(10000) /-- Parentheses are used for grouping priority expressions. -/ macro "(" p:prio ")" : prio => return p -- Basic notation for defining parsers -- NOTE: precedence must be at least `arg` to be used in `macro` without parentheses /-- `p+` is shorthand for `many1(p)`. It uses parser `p` 1 or more times, and produces a `nullNode` containing the array of parsed results. This parser has arity 1. If `p` has arity more than 1, it is auto-grouped in the items generated by the parser. -/ syntax:arg stx:max "+" : stx /-- `p*` is shorthand for `many(p)`. It uses parser `p` 0 or more times, and produces a `nullNode` containing the array of parsed results. This parser has arity 1. If `p` has arity more than 1, it is auto-grouped in the items generated by the parser. -/ syntax:arg stx:max "*" : stx /-- `(p)?` is shorthand for `optional(p)`. It uses parser `p` 0 or 1 times, and produces a `nullNode` containing the array of parsed results. This parser has arity 1. `p` is allowed to have arity n > 1 (in which case the node will have either 0 or n children), but if it has arity 0 then the result will be ambiguous. Because `?` is an identifier character, `ident?` will not work as intended. You have to write either `ident ?` or `(ident)?` for it to parse as the `?` combinator applied to the `ident` parser. -/ syntax:arg stx:max "?" : stx /-- `p1 <|> p2` is shorthand for `orelse(p1, p2)`, and parses either `p1` or `p2`. It does not backtrack, meaning that if `p1` consumes at least one token then `p2` will not be tried. Therefore, the parsers should all differ in their first token. The `atomic(p)` parser combinator can be used to locally backtrack a parser. (For full backtracking, consider using extensible syntax classes instead.) On success, if the inner parser does not generate exactly one node, it will be automatically wrapped in a `group` node, so the result will always be arity 1. The `<|>` combinator does not generate a node of its own, and in particular does not tag the inner parsers to distinguish them, which can present a problem when reconstructing the parse. A well formed `<|>` parser should use disjoint node kinds for `p1` and `p2`. -/ syntax:2 stx:2 " <|> " stx:1 : stx macro_rules | `(stx| $p +) => `(stx| many1($p)) | `(stx| $p *) => `(stx| many($p)) | `(stx| $p ?) => `(stx| optional($p)) | `(stx| $p₁ <|> $pβ‚‚) => `(stx| orelse($p₁, $pβ‚‚)) /-- `p,*` is shorthand for `sepBy(p, ",")`. It parses 0 or more occurrences of `p` separated by `,`, that is: `empty | p | p,p | p,p,p | ...`. It produces a `nullNode` containing a `SepArray` with the interleaved parser results. It has arity 1, and auto-groups its component parser if needed. -/ macro:arg x:stx:max ",*" : stx => `(stx| sepBy($x, ",", ", ")) /-- `p,+` is shorthand for `sepBy(p, ",")`. It parses 1 or more occurrences of `p` separated by `,`, that is: `p | p,p | p,p,p | ...`. It produces a `nullNode` containing a `SepArray` with the interleaved parser results. It has arity 1, and auto-groups its component parser if needed. -/ macro:arg x:stx:max ",+" : stx => `(stx| sepBy1($x, ",", ", ")) /-- `p,*,?` is shorthand for `sepBy(p, ",", allowTrailingSep)`. It parses 0 or more occurrences of `p` separated by `,`, possibly including a trailing `,`, that is: `empty | p | p, | p,p | p,p, | p,p,p | ...`. It produces a `nullNode` containing a `SepArray` with the interleaved parser results. It has arity 1, and auto-groups its component parser if needed. -/ macro:arg x:stx:max ",*,?" : stx => `(stx| sepBy($x, ",", ", ", allowTrailingSep)) /-- `p,+,?` is shorthand for `sepBy1(p, ",", allowTrailingSep)`. It parses 1 or more occurrences of `p` separated by `,`, possibly including a trailing `,`, that is: `p | p, | p,p | p,p, | p,p,p | ...`. It produces a `nullNode` containing a `SepArray` with the interleaved parser results. It has arity 1, and auto-groups its component parser if needed. -/ macro:arg x:stx:max ",+,?" : stx => `(stx| sepBy1($x, ",", ", ", allowTrailingSep)) /-- `!p` parses the negation of `p`. That is, it fails if `p` succeeds, and otherwise parses nothing. It has arity 0. -/ macro:arg "!" x:stx:max : stx => `(stx| notFollowedBy($x)) /-- The `nat_lit n` macro constructs "raw numeric literals". This corresponds to the `Expr.lit (.natVal n)` constructor in the `Expr` data type. Normally, when you write a numeral like `#check 37`, the parser turns this into an application of `OfNat.ofNat` to the raw literal `37` to cast it into the target type, even if this type is `Nat` (so the cast is the identity function). But sometimes it is necessary to talk about the raw numeral directly, especially when proving properties about the `ofNat` function itself. -/ syntax (name := rawNatLit) "nat_lit " num : term @[inheritDoc] infixr:90 " ∘ " => Function.comp @[inheritDoc] infixr:35 " Γ— " => Prod @[inheritDoc] infixl:55 " ||| " => HOr.hOr @[inheritDoc] infixl:58 " ^^^ " => HXor.hXor @[inheritDoc] infixl:60 " &&& " => HAnd.hAnd @[inheritDoc] infixl:65 " + " => HAdd.hAdd @[inheritDoc] infixl:65 " - " => HSub.hSub @[inheritDoc] infixl:70 " * " => HMul.hMul @[inheritDoc] infixl:70 " / " => HDiv.hDiv @[inheritDoc] infixl:70 " % " => HMod.hMod @[inheritDoc] infixl:75 " <<< " => HShiftLeft.hShiftLeft @[inheritDoc] infixl:75 " >>> " => HShiftRight.hShiftRight @[inheritDoc] infixr:80 " ^ " => HPow.hPow @[inheritDoc] infixl:65 " ++ " => HAppend.hAppend @[inheritDoc] prefix:100 "-" => Neg.neg @[inheritDoc] prefix:100 "~~~" => Complement.complement /-! Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binop%` elaboration helper for binary operators. It addresses issue #382. -/ macro_rules | `($x ||| $y) => `(binop% HOr.hOr $x $y) macro_rules | `($x ^^^ $y) => `(binop% HXor.hXor $x $y) macro_rules | `($x &&& $y) => `(binop% HAnd.hAnd $x $y) macro_rules | `($x + $y) => `(binop% HAdd.hAdd $x $y) macro_rules | `($x - $y) => `(binop% HSub.hSub $x $y) macro_rules | `($x * $y) => `(binop% HMul.hMul $x $y) macro_rules | `($x / $y) => `(binop% HDiv.hDiv $x $y) macro_rules | `($x % $y) => `(binop% HMod.hMod $x $y) macro_rules | `($x ^ $y) => `(binop% HPow.hPow $x $y) macro_rules | `($x ++ $y) => `(binop% HAppend.hAppend $x $y) -- declare ASCII alternatives first so that the latter Unicode unexpander wins @[inheritDoc] infix:50 " <= " => LE.le @[inheritDoc] infix:50 " ≀ " => LE.le @[inheritDoc] infix:50 " < " => LT.lt @[inheritDoc] infix:50 " >= " => GE.ge @[inheritDoc] infix:50 " β‰₯ " => GE.ge @[inheritDoc] infix:50 " > " => GT.gt @[inheritDoc] infix:50 " = " => Eq @[inheritDoc] infix:50 " == " => BEq.beq /-! Remark: the infix commands above ensure a delaborator is generated for each relations. We redefine the macros below to be able to use the auxiliary `binrel%` elaboration helper for binary relations. It has better support for applying coercions. For example, suppose we have `binrel% Eq n i` where `n : Nat` and `i : Int`. The default elaborator fails because we don't have a coercion from `Int` to `Nat`, but `binrel%` succeeds because it also tries a coercion from `Nat` to `Int` even when the nat occurs before the int. -/ macro_rules | `($x <= $y) => `(binrel% LE.le $x $y) macro_rules | `($x ≀ $y) => `(binrel% LE.le $x $y) macro_rules | `($x < $y) => `(binrel% LT.lt $x $y) macro_rules | `($x > $y) => `(binrel% GT.gt $x $y) macro_rules | `($x >= $y) => `(binrel% GE.ge $x $y) macro_rules | `($x β‰₯ $y) => `(binrel% GE.ge $x $y) macro_rules | `($x = $y) => `(binrel% Eq $x $y) macro_rules | `($x == $y) => `(binrel_no_prop% BEq.beq $x $y) @[inheritDoc] infixr:35 " /\\ " => And @[inheritDoc] infixr:35 " ∧ " => And @[inheritDoc] infixr:30 " \\/ " => Or @[inheritDoc] infixr:30 " ∨ " => Or @[inheritDoc] notation:max "Β¬" p:40 => Not p @[inheritDoc] infixl:35 " && " => and @[inheritDoc] infixl:30 " || " => or @[inheritDoc] notation:max "!" b:40 => not b @[inheritDoc] infix:50 " ∈ " => Membership.mem /-- `a βˆ‰ b` is negated elementhood. It is notation for `Β¬ (a ∈ b)`. -/ notation:50 a:50 " βˆ‰ " b:50 => Β¬ (a ∈ b) @[inheritDoc] infixr:67 " :: " => List.cons @[inheritDoc HOrElse.hOrElse] syntax:20 term:21 " <|> " term:20 : term @[inheritDoc HAndThen.hAndThen] syntax:60 term:61 " >> " term:60 : term @[inheritDoc] infixl:55 " >>= " => Bind.bind @[inheritDoc] notation:60 a:60 " <*> " b:61 => Seq.seq a fun _ : Unit => b @[inheritDoc] notation:60 a:60 " <* " b:61 => SeqLeft.seqLeft a fun _ : Unit => b @[inheritDoc] notation:60 a:60 " *> " b:61 => SeqRight.seqRight a fun _ : Unit => b @[inheritDoc] infixr:100 " <$> " => Functor.map macro_rules | `($x <|> $y) => `(binop_lazy% HOrElse.hOrElse $x $y) macro_rules | `($x >> $y) => `(binop_lazy% HAndThen.hAndThen $x $y) namespace Lean /-- `binderIdent` matches an `ident` or a `_`. It is used for identifiers in binding position, where `_` means that the value should be left unnamed and inaccessible. -/ syntax binderIdent := ident <|> hole namespace Parser.Tactic /-- A case tag argument has the form `tag x₁ ... xβ‚™`; it refers to tag `tag` and renames the last `n` hypotheses to `x₁ ... xβ‚™`. -/ syntax caseArg := binderIdent binderIdent* end Parser.Tactic end Lean @[inheritDoc dite] syntax (name := termDepIfThenElse) ppRealGroup(ppRealFill(ppIndent("if " Lean.binderIdent " : " term " then") ppSpace term) ppDedent(ppSpace) ppRealFill("else " term)) : term macro_rules | `(if $h:ident : $c then $t else $e) => do let mvar ← Lean.withRef c `(?m) `(let_mvar% ?m := $c; wait_if_type_mvar% ?m; dite $mvar (fun $h:ident => $t) (fun $h:ident => $e)) | `(if _%$h : $c then $t else $e) => do let mvar ← Lean.withRef c `(?m) `(let_mvar% ?m := $c; wait_if_type_mvar% ?m; dite $mvar (fun _%$h => $t) (fun _%$h => $e)) @[inheritDoc ite] syntax (name := termIfThenElse) ppRealGroup(ppRealFill(ppIndent("if " term " then") ppSpace term) ppDedent(ppSpace) ppRealFill("else " term)) : term macro_rules | `(if $c then $t else $e) => do let mvar ← Lean.withRef c `(?m) `(let_mvar% ?m := $c; wait_if_type_mvar% ?m; ite $mvar $t $e) /-- `if let pat := d then t else e` is a shorthand syntax for: ``` match d with | pat => t | _ => e ``` It matches `d` against the pattern `pat` and the bindings are available in `t`. If the pattern does not match, it returns `e` instead. -/ macro "if " "let " pat:term " := " d:term " then " t:term " else " e:term : term => `(match $d:term with | $pat => $t | _ => $e) @[inheritDoc cond] syntax (name := boolIfThenElse) ppRealGroup(ppRealFill(ppIndent("bif " term " then") ppSpace term) ppDedent(ppSpace) ppRealFill("else " term)) : term macro_rules | `(bif $c then $t else $e) => `(cond $c $t $e) /-- Haskell-like pipe operator `<|`. `f <| x` means the same as the same as `f x`, except that it parses `x` with lower precedence, which means that `f <| g <| x` is interpreted as `f (g x)` rather than `(f g) x`. -/ syntax:min term " <| " term:min : term macro_rules | `($f $args* <| $a) => `($f $args* $a) | `($f <| $a) => `($f $a) /-- Haskell-like pipe operator `|>`. `x |> f` means the same as the same as `f x`, and it chains such that `x |> f |> g` is interpreted as `g (f x)`. -/ syntax:min term " |> " term:min1 : term macro_rules | `($a |> $f $args*) => `($f $args* $a) | `($a |> $f) => `($f $a) /-- Alternative syntax for `<|`. `f $ x` means the same as the same as `f x`, except that it parses `x` with lower precedence, which means that `f $ g $ x` is interpreted as `f (g x)` rather than `(f g) x`. -/ -- Note that we have a whitespace after `$` to avoid an ambiguity with antiquotations. syntax:min term atomic(" $" ws) term:min : term macro_rules | `($f $args* $ $a) => `($f $args* $a) | `($f $ $a) => `($f $a) @[inheritDoc Subtype] syntax "{ " ident (" : " term)? " // " term " }" : term macro_rules | `({ $x : $type // $p }) => ``(Subtype (fun ($x:ident : $type) => $p)) | `({ $x // $p }) => ``(Subtype (fun ($x:ident : _) => $p)) /-- `without_expected_type t` instructs Lean to elaborate `t` without an expected type. Recall that terms such as `match ... with ...` and `⟨...⟩` will postpone elaboration until expected type is known. So, `without_expected_type` is not effective in this case. -/ macro "without_expected_type " x:term : term => `(let aux := $x; aux) /-- The syntax `[a, b, c]` is shorthand for `a :: b :: c :: []`, or `List.cons a (List.cons b (List.cons c List.nil))`. It allows conveniently constructing list literals. For lists of length at least 64, an alternative desugaring strategy is used which uses let bindings as intermediates as in `let left := [d, e, f]; a :: b :: c :: left` to avoid creating very deep expressions. Note that this changes the order of evaluation, although it should not be observable unless you use side effecting operations like `dbg_trace`. -/ syntax "[" term,* "]" : term /-- Auxiliary syntax for implementing `[$elem,*]` list literal syntax. The syntax `%[a,b,c|tail]` constructs a value equivalent to `a::b::c::tail`. It uses binary partitioning to construct a tree of intermediate let bindings as in `let left := [d, e, f]; a :: b :: c :: left` to avoid creating very deep expressions. -/ syntax "%[" term,* "|" term "]" : term namespace Lean macro_rules | `([ $elems,* ]) => do -- NOTE: we do not have `TSepArray.getElems` yet at this point let rec expandListLit (i : Nat) (skip : Bool) (result : TSyntax `term) : MacroM Syntax := do match i, skip with | 0, _ => pure result | i+1, true => expandListLit i false result | i+1, false => expandListLit i true (← ``(List.cons $(⟨elems.elemsAndSeps.get! i⟩) $result)) if elems.elemsAndSeps.size < 64 then expandListLit elems.elemsAndSeps.size false (← ``(List.nil)) else `(%[ $elems,* | List.nil ]) -- Declare `this` as a keyword that unhygienically binds to a scope-less `this` assumption (or other binding). -- The keyword prevents declaring a `this` binding except through metaprogramming, as is done by `have`/`show`. /-- Special identifier introduced by "anonymous" `have : ...`, `suffices p ...` etc. -/ macro tk:"this" : term => return Syntax.ident tk.getHeadInfo "this".toSubstring `this [] /-- Category for carrying raw syntax trees between macros; any content is printed as is by the pretty printer. The only accepted parser for this category is an antiquotation. -/ declare_syntax_cat rawStx instance : Coe Syntax (TSyntax `rawStx) where coe stx := ⟨stx⟩ /-- `with_annotate_term stx e` annotates the lexical range of `stx : Syntax` with term info for `e`. -/ scoped syntax (name := withAnnotateTerm) "with_annotate_term " rawStx ppSpace term : term /-- The attribute `@[deprecated]` on a declaration indicates that the declaration is discouraged for use in new code, and/or should be migrated away from in existing code. It may be removed in a future version of the library. `@[deprecated myBetterDef]` means that `myBetterDef` is the suggested replacement. -/ syntax (name := deprecated) "deprecated " (ident)? : attr /-- When `parent_dir` contains the current Lean file, `include_str "path" / "to" / "file"` becomes a string literal with the contents of the file at `"parent_dir" / "path" / "to" / "file"`. If this file cannot be read, elaboration fails. -/ syntax (name := includeStr) "include_str" term : term
d425f8acb8352d3d6849ffd23d1b6cb653d85bba
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/exists.lean
43a544e93fc404c8c7737c1cd7526c96707cd314
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
223
lean
example : βˆƒ x : Nat, x = x := by exists 0 example : βˆƒ x : Nat, βˆƒ y : Nat, x > y := by exists 1, 0 example : (x : Nat) Γ—' (y : Nat) Γ—' x > y := by exists 1, 0 example : { x : Nat // x > 2 } := by exists 3
30809fc948ebe4e7eff8bc0d4c37583e3e4e3184
ba4ad8a778c69640c9cca8e5dcaeb40d4a10fa10
/lean4/hello/Main.lean
fc5f68dd47573bebf0a4607c71b0d0e58ffe6afe
[]
no_license
tangentstorm/tangentlabs
390ac60618bd913b567d20933dab70b84aac7151
137adbba6e7c35f8bb54b0786ada6c8c2ff6bc72
refs/heads/master
1,693,514,213,127
1,692,322,210,000
1,692,322,210,000
7,815,356
33
22
null
1,433,592,935,000
1,359,097,381,000
Visual Basic
UTF-8
Lean
false
false
213
lean
-- basic io demo def chomp (s : String) := s.trimRight def main : IO Unit := do (← IO.getStdout).putStr "name> " let input := chomp (← (← IO.getStdin).getLine) IO.println s!"Hello, {input}!"
371fcf33782f90c721838c40a08891f762f783d6
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep_2/basic_definitions/sub_module.lean
8e568de932353c952832f7a8809d2a2aca6a0ecc
[]
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
3,764
lean
import .group_representation import .morphism universe variables u v w variables {G : Type u} {R : Type v} {M : Type w} [group G] [ring R] [add_comm_group M] [module R M] namespace stability variables {p : submodule R M} /-- Technical lemma to deal with `submodule p` of `M`. -/ lemma submodule_ext (x y : p) : (x : M) = (y : M) β†’ x = y := begin intros,rcases x,rcases y,congr, try {assumption}, end /-- Let `ρ : G β†’* M ≃ₗ[R] M` a representation. A submodule `p` of `M` is `ρ-stable` when : `βˆ€ g ∈ G, βˆ€ x ∈ p, ρ g x ∈ p`. It induce a `sub-representation` : ` Res ρ p : G β†’* p ≃ₗ[R] p ` -/ class stable_submodule (ρ : group_representation G R M)(p : submodule R M) := (stability : βˆ€ g : G, βˆ€ x : M, x ∈ p β†’ ρ g x ∈ p) /-- `Trivial submodule` : `βŠ₯` and `⊀` -/ def is_trivial (p : submodule R M) := (p = ⊀ ∨ p = βŠ₯) /-- `Irreducible ρ` : only `βŠ₯` and `⊀` for ` ρ-stable submodule` -/ class Irreductible ( ρ : group_representation G R M) := (certif: βˆ€ (p : submodule R M)[stable_submodule ρ p], is_trivial p) def Trivial (ρ : group_representation G R M)(p : submodule R M) [Irreductible ρ] [stable_submodule ρ p]:= Irreductible.certif ρ p variables (ρ : group_representation G R M) lemma stab [stable_submodule ρ p](g : G) {x : M} : (x ∈ p ) β†’ (ρ g x ∈ p) := stable_submodule.stability g x lemma map' (g : G) [stable_submodule ρ p] : submodule.map (ρ g) p ≀ p := begin rw submodule.le_def', intros x hyp, rw submodule.mem_map at hyp, rcases hyp with ⟨y,hyp_y ⟩, rw ← hyp_y.2, apply (stab ρ g), exact hyp_y.1, assumption, end lemma map (g : G) [stable_submodule ρ p] : submodule.map (ρ g) p = p := begin apply le_antisymm, apply map', rw submodule.le_def', intros x hyp_x, rw submodule.mem_map, use (ρ g⁻¹ ) x, split, apply stab ρ g⁻¹, exact hyp_x, assumption, change (ρ g ⊚ ρ g⁻¹ ) x = _, rw ← map_comp, rw mul_inv_self, rw ρ.map_one, exact rfl, end /-- Restriction map : `res ρ : G β†’ (p β†’ p)`. -/ def res [stable_submodule ρ p] : G β†’ p β†’ p := Ξ» g x, { val := ρ g x, property := stab ρ g x.property } variables [stable_submodule ρ p] lemma res_add (g : G) (x y : p) : res ρ g (x+y) = res ρ g x + res ρ g y := begin apply submodule_ext, change ρ _ _ = _, erw (ρ g).map_add, exact rfl, end lemma res_smul (g : G) (r : R) ( x : p) : res ρ g ( r β€’ x) = r β€’ res ρ g x := begin apply submodule_ext, change ρ _ _ = _, erw (ρ g).map_smul, exact rfl, end /-- `res` is linear map. -/ def res_linear [stable_submodule ρ p] (g : G) : p β†’β‚—[R]p := { to_fun := res ρ g, add := res_add ρ g, smul := res_smul ρ g } /-- ` βˆ€ g :G, res ρ g` has an inverse given by ` res ρ g⁻¹`. -/ lemma res_mul (g1 g2 : G) : (res ρ (g1 * g2) : p β†’ p) = res ρ g1 ∘ (res ρ g2) := begin ext, apply submodule_ext, change ρ (g1 * g2) x = _, erw ρ.map_mul, exact rfl, end lemma res_one : (res ρ 1 : p β†’ p) = id := begin ext,apply submodule_ext, change ρ 1 x = _, erw ρ.map_one, exact rfl, end /-- the restriction representation `G β†’* p ≃ₗ[R]p` -/ def Res : group_representation G R p := { to_fun := res_linear ρ , map_one' := begin ext,apply submodule_ext, change (ρ 1) x = _, rw ρ.map_one, exact rfl, end, map_mul' := begin intros g1 g2, ext, apply submodule_ext, change (ρ (g1 * g2)) x = _ , rw ρ.map_mul, exact rfl, end } def res.subtype : Res ρ ⟢ᡣ ρ := { β„“ := submodule.subtype p, commute := by {intros g, exact rfl} } end stability