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
95ac2594963550b3c4ee1c4e8ad9b2bd00bf2069
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/game/intro.lean
be06477245657de1cb076fbadd79e9230485ab5b
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,021
lean
/- # The Real Number Game, version 1.0beta ## By Kevin Buzzard, Dan Stanescu and Gavin Thomson # What is this game? Welcome to the real number game -- a game to help undergraduates learn analysis through Lean, a formal proof verification system. Starting from the real numbers with its usual structure, we develop the theory of bounds, least upper bounds and greatest lower bounds (sups and infs), infinite sequences and infinite series. We develop the theory through problem-solving, getting students to formalise proofs in the theory. This game is a sequel to <a href="http://wwwf.imperial.ac.uk/~buzzard/xena/natural_number_game/" target="blank">the natural number game</a>. The levels in the Real Number Game need to be solved using tactics. To learn how to use these tactics, I would recommend that you first play the Natural Number Game up to at least "Advanced Proposition world". I will not go through a careful explanation of the tactics taught by the natural number game here. Blue nodes on the graph are ones that you are ready to enter. Grey nodes you should stay away from -- try blue ones higher up the chain first. Green nodes are completed. # Thanks Many thanks to Mohammad Pedramfar, without whom this game would not exist. Several people contributed ideas and sometimes full proofs, most of which have found their place in the game in one way or another. This aims at being a complete list eventually: Kenny Lau, Patrick Massot, Christopher Sumnicht, Aniruddh Agarwal. # Questions? You can ask questions on the <a href="https://leanprover.zulipchat.com/" target="blank">Lean Zulip chat</a>, where I am often to be found. The Real Number Game is brought to you by the Xena project, a project based at Imperial College London whose aim is to get mathematics undergraduates using computer theorem provers. Lean is a computer theorem prover being developed at Microsoft Research. Prove a theorem. Write a function. <a href="https://twitter.com/XenaProject" target="blank">@XenaProject</a>. -/
a21ab5d2b923e094a10b311dfa02e621b761d7cc
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/algebra/opposites.lean
4db5d0daee227f6e43f3858319ee4bfd41a2eec7
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,984
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.opposite import algebra.field import group_theory.group_action.defs import data.equiv.mul_add /-! # Algebraic operations on `αᵒᵖ` -/ namespace opposite universes u variables (α : Type u) instance [has_add α] : has_add (opposite α) := { add := λ x y, op (unop x + unop y) } instance [has_sub α] : has_sub (opposite α) := { sub := λ x y, op (unop x - unop y) } instance [add_semigroup α] : add_semigroup (opposite α) := { add_assoc := λ x y z, unop_injective $ add_assoc (unop x) (unop y) (unop z), .. opposite.has_add α } instance [add_left_cancel_semigroup α] : add_left_cancel_semigroup (opposite α) := { add_left_cancel := λ x y z H, unop_injective $ add_left_cancel $ op_injective H, .. opposite.add_semigroup α } instance [add_right_cancel_semigroup α] : add_right_cancel_semigroup (opposite α) := { add_right_cancel := λ x y z H, unop_injective $ add_right_cancel $ op_injective H, .. opposite.add_semigroup α } instance [add_comm_semigroup α] : add_comm_semigroup (opposite α) := { add_comm := λ x y, unop_injective $ add_comm (unop x) (unop y), .. opposite.add_semigroup α } instance [has_zero α] : has_zero (opposite α) := { zero := op 0 } instance [nontrivial α] : nontrivial (opposite α) := let ⟨x, y, h⟩ := exists_pair_ne α in nontrivial_of_ne (op x) (op y) (op_injective.ne h) section local attribute [reducible] opposite @[simp] lemma unop_eq_zero_iff [has_zero α] (a : αᵒᵖ) : a.unop = (0 : α) ↔ a = (0 : αᵒᵖ) := iff.refl _ @[simp] lemma op_eq_zero_iff [has_zero α] (a : α) : op a = (0 : αᵒᵖ) ↔ a = (0 : α) := iff.refl _ end instance [add_monoid α] : add_monoid (opposite α) := { zero_add := λ x, unop_injective $ zero_add $ unop x, add_zero := λ x, unop_injective $ add_zero $ unop x, .. opposite.add_semigroup α, .. opposite.has_zero α } instance [add_comm_monoid α] : add_comm_monoid (opposite α) := { .. opposite.add_monoid α, .. opposite.add_comm_semigroup α } instance [has_neg α] : has_neg (opposite α) := { neg := λ x, op $ -(unop x) } instance [add_group α] : add_group (opposite α) := { add_left_neg := λ x, unop_injective $ add_left_neg $ unop x, sub_eq_add_neg := λ x y, unop_injective $ sub_eq_add_neg (unop x) (unop y), .. opposite.add_monoid α, .. opposite.has_neg α, .. opposite.has_sub α } instance [add_comm_group α] : add_comm_group (opposite α) := { .. opposite.add_group α, .. opposite.add_comm_monoid α } instance [has_mul α] : has_mul (opposite α) := { mul := λ x y, op (unop y * unop x) } instance [semigroup α] : semigroup (opposite α) := { mul_assoc := λ x y z, unop_injective $ eq.symm $ mul_assoc (unop z) (unop y) (unop x), .. opposite.has_mul α } instance [right_cancel_semigroup α] : left_cancel_semigroup (opposite α) := { mul_left_cancel := λ x y z H, unop_injective $ mul_right_cancel $ op_injective H, .. opposite.semigroup α } instance [left_cancel_semigroup α] : right_cancel_semigroup (opposite α) := { mul_right_cancel := λ x y z H, unop_injective $ mul_left_cancel $ op_injective H, .. opposite.semigroup α } instance [comm_semigroup α] : comm_semigroup (opposite α) := { mul_comm := λ x y, unop_injective $ mul_comm (unop y) (unop x), .. opposite.semigroup α } instance [has_one α] : has_one (opposite α) := { one := op 1 } section local attribute [reducible] opposite @[simp] lemma unop_eq_one_iff [has_one α] (a : αᵒᵖ) : a.unop = 1 ↔ a = 1 := iff.refl _ @[simp] lemma op_eq_one_iff [has_one α] (a : α) : op a = 1 ↔ a = 1 := iff.refl _ end instance [monoid α] : monoid (opposite α) := { one_mul := λ x, unop_injective $ mul_one $ unop x, mul_one := λ x, unop_injective $ one_mul $ unop x, .. opposite.semigroup α, .. opposite.has_one α } instance [comm_monoid α] : comm_monoid (opposite α) := { .. opposite.monoid α, .. opposite.comm_semigroup α } instance [has_inv α] : has_inv (opposite α) := { inv := λ x, op $ (unop x)⁻¹ } instance [group α] : group (opposite α) := { mul_left_inv := λ x, unop_injective $ mul_inv_self $ unop x, .. opposite.monoid α, .. opposite.has_inv α } instance [comm_group α] : comm_group (opposite α) := { .. opposite.group α, .. opposite.comm_monoid α } instance [distrib α] : distrib (opposite α) := { left_distrib := λ x y z, unop_injective $ add_mul (unop y) (unop z) (unop x), right_distrib := λ x y z, unop_injective $ mul_add (unop z) (unop x) (unop y), .. opposite.has_add α, .. opposite.has_mul α } instance [semiring α] : semiring (opposite α) := { zero_mul := λ x, unop_injective $ mul_zero $ unop x, mul_zero := λ x, unop_injective $ zero_mul $ unop x, .. opposite.add_comm_monoid α, .. opposite.monoid α, .. opposite.distrib α } instance [ring α] : ring (opposite α) := { .. opposite.add_comm_group α, .. opposite.monoid α, .. opposite.semiring α } instance [comm_ring α] : comm_ring (opposite α) := { .. opposite.ring α, .. opposite.comm_semigroup α } instance [has_zero α] [has_mul α] [no_zero_divisors α] : no_zero_divisors (opposite α) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y (H : op (_ * _) = op (0:α)), or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ op_injective H) (λ hy, or.inr $ unop_injective $ hy) (λ hx, or.inl $ unop_injective $ hx), } instance [integral_domain α] : integral_domain (opposite α) := { .. opposite.no_zero_divisors α, .. opposite.comm_ring α, .. opposite.nontrivial α } instance [field α] : field (opposite α) := { mul_inv_cancel := λ x hx, unop_injective $ inv_mul_cancel $ λ hx', hx $ unop_injective hx', inv_zero := unop_injective inv_zero, .. opposite.comm_ring α, .. opposite.has_inv α, .. opposite.nontrivial α } instance (R : Type*) [has_scalar R α] : has_scalar R (opposite α) := { smul := λ c x, op (c • unop x) } instance (R : Type*) [monoid R] [mul_action R α] : mul_action R (opposite α) := { one_smul := λ x, unop_injective $ one_smul R (unop x), mul_smul := λ r₁ r₂ x, unop_injective $ mul_smul r₁ r₂ (unop x), ..opposite.has_scalar α R } instance (R : Type*) [monoid R] [add_monoid α] [distrib_mul_action R α] : distrib_mul_action R (opposite α) := { smul_add := λ r x₁ x₂, unop_injective $ smul_add r (unop x₁) (unop x₂), smul_zero := λ r, unop_injective $ smul_zero r, ..opposite.mul_action α R } @[simp] lemma op_zero [has_zero α] : op (0 : α) = 0 := rfl @[simp] lemma unop_zero [has_zero α] : unop (0 : αᵒᵖ) = 0 := rfl @[simp] lemma op_one [has_one α] : op (1 : α) = 1 := rfl @[simp] lemma unop_one [has_one α] : unop (1 : αᵒᵖ) = 1 := rfl variable {α} @[simp] lemma op_add [has_add α] (x y : α) : op (x + y) = op x + op y := rfl @[simp] lemma unop_add [has_add α] (x y : αᵒᵖ) : unop (x + y) = unop x + unop y := rfl @[simp] lemma op_neg [has_neg α] (x : α) : op (-x) = -op x := rfl @[simp] lemma unop_neg [has_neg α] (x : αᵒᵖ) : unop (-x) = -unop x := rfl @[simp] lemma op_mul [has_mul α] (x y : α) : op (x * y) = op y * op x := rfl @[simp] lemma unop_mul [has_mul α] (x y : αᵒᵖ) : unop (x * y) = unop y * unop x := rfl @[simp] lemma op_inv [has_inv α] (x : α) : op (x⁻¹) = (op x)⁻¹ := rfl @[simp] lemma unop_inv [has_inv α] (x : αᵒᵖ) : unop (x⁻¹) = (unop x)⁻¹ := rfl @[simp] lemma op_sub [add_group α] (x y : α) : op (x - y) = op x - op y := rfl @[simp] lemma unop_sub [add_group α] (x y : αᵒᵖ) : unop (x - y) = unop x - unop y := rfl @[simp] lemma op_smul {R : Type*} [has_scalar R α] (c : R) (a : α) : op (c • a) = c • op a := rfl @[simp] lemma unop_smul {R : Type*} [has_scalar R α] (c : R) (a : αᵒᵖ) : unop (c • a) = c • unop a := rfl /-- The function `op` is an additive equivalence. -/ def op_add_equiv [has_add α] : α ≃+ αᵒᵖ := { map_add' := λ a b, rfl, .. equiv_to_opposite } @[simp] lemma coe_op_add_equiv [has_add α] : (op_add_equiv : α → αᵒᵖ) = op := rfl @[simp] lemma coe_op_add_equiv_symm [has_add α] : (op_add_equiv.symm : αᵒᵖ → α) = unop := rfl @[simp] lemma op_add_equiv_to_equiv [has_add α] : (op_add_equiv : α ≃+ αᵒᵖ).to_equiv = equiv_to_opposite := rfl end opposite open opposite /-- A ring homomorphism `f : R →+* S` such that `f x` commutes with `f y` for all `x, y` defines a ring homomorphism to `Sᵒᵖ`. -/ def ring_hom.to_opposite {R S : Type*} [semiring R] [semiring S] (f : R →+* S) (hf : ∀ x y, commute (f x) (f y)) : R →+* Sᵒᵖ := { map_one' := congr_arg op f.map_one, map_mul' := λ x y, by simp [(hf x y).eq], .. (opposite.op_add_equiv : S ≃+ Sᵒᵖ).to_add_monoid_hom.comp ↑f } @[simp] lemma ring_hom.coe_to_opposite {R S : Type*} [semiring R] [semiring S] (f : R →+* S) (hf : ∀ x y, commute (f x) (f y)) : ⇑(f.to_opposite hf) = op ∘ f := rfl
a5fd606803c4623469e63af859586d153700db5c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/wlog.lean
edb965d87235072c46665a11b84201f8378c7cdd
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,460
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 Without loss of generality tactic. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.perm import Mathlib.PostPort namespace Mathlib namespace tactic namespace interactive /-- Without loss of generality: reduces to one goal under variables permutations. Given a goal of the form `g xs`, a predicate `p` over a set of variables, as well as variable permutations `xs_i`. Then `wlog` produces goals of the form The case goal, i.e. the permutation `xs_i` covers all possible cases: `⊢ p xs_0 ∨ ⋯ ∨ p xs_n` The main goal, i.e. the goal reduced to `xs_0`: `(h : p xs_0) ⊢ g xs_0` The invariant goals, i.e. `g` is invariant under `xs_i`: `(h : p xs_i) (this : g xs_0) ⊢ gs xs_i` Either the permutation is provided, or a proof of the disjunction is provided to compute the permutation. The disjunction need to be in assoc normal form, e.g. `p₀ ∨ (p₁ ∨ p₂)`. In many cases the invariant goals can be solved by AC rewriting using `cc` etc. Example: On a state `(n m : ℕ) ⊢ p n m` the tactic `wlog h : n ≤ m using [n m, m n]` produces the following states: `(n m : ℕ) ⊢ n ≤ m ∨ m ≤ n` `(n m : ℕ) (h : n ≤ m) ⊢ p n m` `(n m : ℕ) (h : m ≤ n) (this : p n m) ⊢ p m n` `wlog` supports different calling conventions. The name `h` is used to give a name to the introduced case hypothesis. If the name is avoided, the default will be `case`. (1) `wlog : p xs0 using [xs0, …, xsn]` Results in the case goal `p xs0 ∨ ⋯ ∨ ps xsn`, the main goal `(case : p xs0) ⊢ g xs0` and the invariance goals `(case : p xsi) (this : g xs0) ⊢ g xsi`. (2) `wlog : p xs0 := r using xs0` The expression `r` is a proof of the shape `p xs0 ∨ ⋯ ∨ p xsi`, it is also used to compute the variable permutations. (3) `wlog := r using xs0` The expression `r` is a proof of the shape `p xs0 ∨ ⋯ ∨ p xsi`, it is also used to compute the variable permutations. This is not as stable as (2), for example `p` cannot be a disjunction. (4) `wlog : R x y using x y` and `wlog : R x y` Produces the case `R x y ∨ R y x`. If `R` is ≤, then the disjunction discharged using linearity. If `using x y` is avoided then `x` and `y` are the last two variables appearing in the expression `R x y`. -/
d7bde6d5fb5b728c5a464d175e346d57f43172dc
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/autobound_and_macroscopes.lean
c679805969a8a8d0acfc5d52bcb494a66168d9df
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
57
lean
local notation "A" => id x theorem test : A = A := sorry
6bae758879f23bdd09f519d50aa8a66063451888
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/matchEqsBug.lean
44884f6f99e6b6d39160c88954f1936535681b93
[ "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
690
lean
import Lean syntax (name := test) "test%" ident : command open Lean.Elab open Lean.Elab.Command @[command_elab test] def elabTest : CommandElab := fun stx => do let id ← resolveGlobalConstNoOverloadWithInfo stx[1] liftTermElabM do IO.println (repr (← Lean.Meta.Match.getEquationsFor id)) return () def f (x : List Nat) : Nat := match x with | [] => 1 | [a] => 2 | _ => 3 def g (x : Unit) (y : Bool) : Unit := match x, y with | _, true => () | x, _ => x set_option trace.Meta.Match.matchEqs true test% f.match_1 #check f.match_1.splitter def g.match_1.splitter := 4 test% g.match_1 #check g.match_1.eq_1 #check g.match_1.eq_2 #check g.match_1.splitter
1756f9ea265c567bd023e86ead61d1e3a0f4ed25
d9ed0fce1c218297bcba93e046cb4e79c83c3af8
/library/tools/super/clausifier.lean
6a73883c122cc961a89e32f8821ff24a3e6649f4
[ "Apache-2.0" ]
permissive
leodemoura/lean_clone
005c63aa892a6492f2d4741ee3c2cb07a6be9d7f
cc077554b584d39bab55c360bc12a6fe7957afe6
refs/heads/master
1,610,506,475,484
1,482,348,354,000
1,482,348,543,000
77,091,586
0
0
null
null
null
null
UTF-8
Lean
false
false
9,885
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .clause_ops import .prover_state .misc_preprocessing open expr list tactic monad decidable universe variable u namespace super meta def try_option {a : Type (u + 1)} (tac : tactic a) : tactic (option a) := lift some tac <|> return none meta def inf_whnf_l (c : clause) : tactic (list clause) := on_first_left c $ λtype, do type' ← whnf_core transparency.reducible type, guard $ type' ≠ type, h ← mk_local_def `h type', return [([h], h)] meta def inf_whnf_r (c : clause) : tactic (list clause) := on_first_right c $ λha, do a' ← whnf_core transparency.reducible ha^.local_type, guard $ a' ≠ ha^.local_type, hna ← mk_local_def `hna (imp a' c^.local_false), return [([hna], app hna ha)] set_option eqn_compiler.max_steps 500 meta def inf_false_l (c : clause) : tactic (list clause) := first $ do i ← list.range c^.num_lits, if c^.get_lit i = clause.literal.left false_ then [return []] else [] meta def inf_false_r (c : clause) : tactic (list clause) := on_first_right c $ λhf, if hf^.local_type = c^.local_false then return [([], hf)] else match hf^.local_type with | const ``false [] := do pr ← mk_app ``false.rec [c^.local_false, hf], return [([], pr)] | _ := failed end meta def inf_true_l (c : clause) : tactic (list clause) := on_first_left c $ λt, match t with | (const ``true []) := return [([], const ``true.intro [])] | _ := failed end meta def inf_true_r (c : clause) : tactic (list clause) := first $ do i ← list.range c^.num_lits, if c^.get_lit i = clause.literal.right (const ``true []) then [return []] else [] meta def inf_not_l (c : clause) : tactic (list clause) := on_first_left c $ λtype, match type with | app (const ``not []) a := do hna ← mk_local_def `h (imp a false_), return [([hna], hna)] | _ := failed end meta def inf_not_r (c : clause) : tactic (list clause) := on_first_right c $ λhna, match hna^.local_type with | app (const ``not []) a := do hnna ← mk_local_def `h (imp (imp a false_) c^.local_false), return [([hnna], app hnna hna)] | _ := failed end meta def inf_and_l (c : clause) : tactic (list clause) := on_first_left c $ λab, match ab with | (app (app (const ``and []) a) b) := do ha ← mk_local_def `l a, hb ← mk_local_def `r b, pab ← mk_mapp ``and.intro [some a, some b, some ha, some hb], return [([ha, hb], pab)] | _ := failed end meta def inf_and_r (c : clause) : tactic (list clause) := on_first_right' c $ λhyp, do pa ← mk_mapp ``and.left [none, none, some hyp], pb ← mk_mapp ``and.right [none, none, some hyp], return [([], pa), ([], pb)] meta def inf_or_r (c : clause) : tactic (list clause) := on_first_right c $ λhab, match hab^.local_type with | (app (app (const ``or []) a) b) := do hna ← mk_local_def `l (imp a c^.local_false), hnb ← mk_local_def `r (imp b c^.local_false), proof ← mk_app ``or.elim [a, b, c^.local_false, hab, hna, hnb], return [([hna, hnb], proof)] | _ := failed end meta def inf_or_l (c : clause) : tactic (list clause) := on_first_left c $ λab, match ab with | (app (app (const ``or []) a) b) := do ha ← mk_local_def `l a, hb ← mk_local_def `l b, pa ← mk_mapp ``or.inl [some a, some b, some ha], pb ← mk_mapp ``or.inr [some a, some b, some hb], return [([ha], pa), ([hb], pb)] | _ := failed end meta def inf_all_r (c : clause) : tactic (list clause) := on_first_right' c $ λhallb, match hallb^.local_type with | (pi n bi a b) := do ha ← mk_local_def `x a, return [([ha], app hallb ha)] | _ := failed end lemma imp_l {F a b} [decidable a] : ((a → b) → F) → ((a → F) → F) := λhabf haf, decidable.by_cases (assume ha : a, haf ha) (assume hna : ¬a, habf (take ha, absurd ha hna)) lemma imp_l' {F a b} [decidable F] : ((a → b) → F) → ((a → F) → F) := λhabf haf, decidable.by_cases (assume hf : F, hf) (assume hnf : ¬F, habf (take ha, absurd (haf ha) hnf)) lemma imp_l_c {F : Prop} {a b} : ((a → b) → F) → ((a → F) → F) := λhabf haf, classical.by_cases (assume hf : F, hf) (assume hnf : ¬F, habf (take ha, absurd (haf ha) hnf)) meta def inf_imp_l (c : clause) : tactic (list clause) := on_first_left_dn c $ λhnab, match hnab^.local_type with | (pi _ _ (pi _ _ a b) _) := if b^.has_var then failed else do hna ← mk_local_def `na (imp a c^.local_false), pf ← first (do r ← [``super.imp_l, ``super.imp_l', ``super.imp_l_c], [mk_app r [hnab, hna]]), hb ← mk_local_def `b b, return [([hna], pf), ([hb], app hnab (lam `a binder_info.default a hb))] | _ := failed end meta def inf_ex_l (c : clause) : tactic (list clause) := on_first_left c $ λexp, match exp with | (app (app (const ``Exists [u]) dom) pred) := do hx ← mk_local_def `x dom, predx ← whnf $ app pred hx, hpx ← mk_local_def `hpx predx, return [([hx,hpx], app_of_list (const ``exists.intro [u]) [dom, pred, hx, hpx])] | _ := failed end lemma demorgan' {F a} {b : a → Prop} : ((∀x, b x) → F) → (((∃x, b x → F) → F) → F) := assume hab hnenb, classical.by_cases (assume h : ∃x, ¬b x, begin cases h with x, apply hnenb, existsi x, intros, contradiction end) (assume h : ¬∃x, ¬b x, hab (take x, classical.by_cases (assume bx : b x, bx) (assume nbx : ¬b x, begin assert hf : false, apply h, existsi x, assumption, contradiction end))) meta def inf_all_l (c : clause) : tactic (list clause) := on_first_left_dn c $ λhnallb, match hnallb^.local_type with | pi _ _ (pi n bi a b) _ := do enb ← mk_mapp ``Exists [none, some $ lam n binder_info.default a (imp b c^.local_false)], hnenb ← mk_local_def `h (imp enb c^.local_false), pr ← mk_app ``super.demorgan' [hnallb, hnenb], return [([hnenb], pr)] | _ := failed end meta def inf_ex_r (c : clause) : tactic (list clause) := do (qf, ctx) ← c^.open_constn c^.num_quants, skolemized ← on_first_right' qf $ λhexp, match hexp^.local_type with | (app (app (const ``Exists [u]) d) p) := do sk_sym_name_pp ← get_unused_name `sk (some 1), inh_lc ← mk_local' `w binder_info.implicit d, sk_sym ← mk_local_def sk_sym_name_pp (pis (ctx ++ [inh_lc]) d), sk_p ← whnf_core transparency.none $ app p (app_of_list sk_sym (ctx ++ [inh_lc])), sk_ax ← mk_mapp ``Exists [some (local_type sk_sym), some (lambdas [sk_sym] (pis (ctx ++ [inh_lc]) (imp hexp^.local_type sk_p)))], sk_ax_name ← get_unused_name `sk_axiom (some 1), assert sk_ax_name sk_ax, nonempt_of_inh ← mk_mapp ``nonempty.intro [some d, some inh_lc], eps ← mk_mapp ``classical.epsilon [some d, some nonempt_of_inh, some p], existsi (lambdas (ctx ++ [inh_lc]) eps), eps_spec ← mk_mapp ``classical.epsilon_spec [some d, some p], exact (lambdas (ctx ++ [inh_lc]) eps_spec), sk_ax_local ← get_local sk_ax_name, cases_using sk_ax_local [sk_sym_name_pp, sk_ax_name], sk_ax' ← get_local sk_ax_name, return [([inh_lc], app_of_list sk_ax' (ctx ++ [inh_lc, hexp]))] | _ := failed end, return $ skolemized^.for (λs, s^.close_constn ctx) meta def first_some {a : Type} : list (tactic (option a)) → tactic (option a) | [] := return none | (x::xs) := do xres ← x, match xres with some y := return (some y) | none := first_some xs end private meta def get_clauses_core' (rules : list (clause → tactic (list clause))) : list clause → tactic (list clause) | cs := lift list.join $ do for cs $ λc, do first $ rules^.for (λr, r c >>= get_clauses_core') ++ [return [c]] meta def get_clauses_core (rules : list (clause → tactic (list clause))) (initial : list clause) : tactic (list clause) := do clauses ← get_clauses_core' rules initial, filter (λc, lift bnot $ is_taut c) $ list.nub_on clause.type clauses meta def clausification_rules_intuit : list (clause → tactic (list clause)) := [ inf_false_l, inf_false_r, inf_true_l, inf_true_r, inf_not_l, inf_not_r, inf_and_l, inf_and_r, inf_or_l, inf_or_r, inf_ex_l, inf_whnf_l, inf_whnf_r ] meta def clausification_rules_classical : list (clause → tactic (list clause)) := [ inf_false_l, inf_false_r, inf_true_l, inf_true_r, inf_not_l, inf_not_r, inf_and_l, inf_and_r, inf_or_l, inf_or_r, inf_imp_l, inf_all_r, inf_ex_l, inf_all_l, inf_ex_r, inf_whnf_l, inf_whnf_r ] meta def get_clauses_classical : list clause → tactic (list clause) := get_clauses_core clausification_rules_classical meta def get_clauses_intuit : list clause → tactic (list clause) := get_clauses_core clausification_rules_intuit meta def as_refutation : tactic unit := do repeat (do intro1, skip), tgt ← target, if tgt^.is_constant || tgt^.is_local_constant then skip else do local_false_name ← get_unused_name `F none, tgt_type ← infer_type tgt, definev local_false_name tgt_type tgt, local_false ← get_local local_false_name, target_name ← get_unused_name `target none, assertv target_name (imp tgt local_false) (lam `hf binder_info.default tgt $ mk_var 0), change local_false meta def clauses_of_context : tactic (list clause) := do local_false ← target, l ← local_context, monad.for l (clause.of_proof local_false) @[super.inf] meta def clausification_inf : inf_decl := inf_decl.mk 0 $ λgiven, list.foldr orelse (return ()) $ do r ← clausification_rules_classical, [do cs ← ♯ r given^.c, cs' ← ♯ get_clauses_classical cs, for' cs' (λc, mk_derived c given^.sc^.sched_now >>= add_inferred), remove_redundant given^.id []] end super
d314987c4bf30f7069cd0ac3edfec42b49969a66
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/lie/weights.lean
949cdf6dd190f1522079dadf3c69e83afcf6af70
[ "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
24,026
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.nilpotent import algebra.lie.tensor_product import algebra.lie.character import algebra.lie.engel import algebra.lie.cartan_subalgebra import linear_algebra.eigenspace import ring_theory.tensor_product /-! # Weights and roots of Lie modules and Lie algebras Just as a key tool when studying the behaviour of a linear operator is to decompose the space on which it acts into a sum of (generalised) eigenspaces, a key tool when studying a representation `M` of Lie algebra `L` is to decompose `M` into a sum of simultaneous eigenspaces of `x` as `x` ranges over `L`. These simultaneous generalised eigenspaces are known as the weight spaces of `M`. When `L` is nilpotent, it follows from the binomial theorem that weight spaces are Lie submodules. Even when `L` is not nilpotent, it may be useful to study its representations by restricting them to a nilpotent subalgebra (e.g., a Cartan subalgebra). In the particular case when we view `L` as a module over itself via the adjoint action, the weight spaces of `L` restricted to a nilpotent subalgebra are known as root spaces. Basic definitions and properties of the above ideas are provided in this file. ## Main definitions * `lie_module.weight_space` * `lie_module.is_weight` * `lie_algebra.root_space` * `lie_algebra.is_root` * `lie_algebra.root_space_weight_space_product` * `lie_algebra.root_space_product` * `lie_algebra.zero_root_subalgebra_eq_iff_is_cartan` ## References * [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 7--9*](bourbaki1975b) ## Tags lie character, eigenvalue, eigenspace, weight, weight vector, root, root vector -/ universes u v w w₁ w₂ w₃ variables {R : Type u} {L : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L] variables (H : lie_subalgebra R L) [lie_algebra.is_nilpotent R H] variables (M : Type w) [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] namespace lie_module open lie_algebra open tensor_product open tensor_product.lie_module open_locale big_operators open_locale tensor_product /-- Given a Lie module `M` over a Lie algebra `L`, the pre-weight space of `M` with respect to a map `χ : L → R` is the simultaneous generalized eigenspace of the action of all `x : L` on `M`, with eigenvalues `χ x`. See also `lie_module.weight_space`. -/ def pre_weight_space (χ : L → R) : submodule R M := ⨅ (x : L), (to_endomorphism R L M x).maximal_generalized_eigenspace (χ x) lemma mem_pre_weight_space (χ : L → R) (m : M) : m ∈ pre_weight_space M χ ↔ ∀ x, ∃ (k : ℕ), ((to_endomorphism R L M x - (χ x) • 1)^k) m = 0 := by simp [pre_weight_space, -linear_map.pow_apply] variables (R) lemma exists_pre_weight_space_zero_le_ker_of_is_noetherian [is_noetherian R M] (x : L) : ∃ (k : ℕ), pre_weight_space M (0 : L → R) ≤ ((to_endomorphism R L M x)^k).ker := begin use (to_endomorphism R L M x).maximal_generalized_eigenspace_index 0, simp only [← module.End.generalized_eigenspace_zero, pre_weight_space, pi.zero_apply, infi_le, ← (to_endomorphism R L M x).maximal_generalized_eigenspace_eq], end variables {R} (L) /-- See also `bourbaki1975b` Chapter VII §1.1, Proposition 2 (ii). -/ protected lemma weight_vector_multiplication (M₁ : Type w₁) (M₂ : Type w₂) (M₃ : Type w₃) [add_comm_group M₁] [module R M₁] [lie_ring_module L M₁] [lie_module R L M₁] [add_comm_group M₂] [module R M₂] [lie_ring_module L M₂] [lie_module R L M₂] [add_comm_group M₃] [module R M₃] [lie_ring_module L M₃] [lie_module R L M₃] (g : M₁ ⊗[R] M₂ →ₗ⁅R,L⁆ M₃) (χ₁ χ₂ : L → R) : ((g : M₁ ⊗[R] M₂ →ₗ[R] M₃).comp (map_incl (pre_weight_space M₁ χ₁) (pre_weight_space M₂ χ₂))).range ≤ pre_weight_space M₃ (χ₁ + χ₂) := begin /- Unpack the statement of the goal. -/ intros m₃, simp only [lie_module_hom.coe_to_linear_map, pi.add_apply, function.comp_app, mem_pre_weight_space, linear_map.coe_comp, tensor_product.map_incl, exists_imp_distrib, linear_map.mem_range], rintros t rfl x, /- Set up some notation. -/ let F : module.End R M₃ := (to_endomorphism R L M₃ x) - (χ₁ x + χ₂ x) • 1, change ∃ k, (F^k) (g _) = 0, /- The goal is linear in `t` so use induction to reduce to the case that `t` is a pure tensor. -/ apply t.induction_on, { use 0, simp only [linear_map.map_zero, lie_module_hom.map_zero], }, swap, { rintros t₁ t₂ ⟨k₁, hk₁⟩ ⟨k₂, hk₂⟩, use max k₁ k₂, simp only [lie_module_hom.map_add, linear_map.map_add, linear_map.pow_map_zero_of_le (le_max_left k₁ k₂) hk₁, linear_map.pow_map_zero_of_le (le_max_right k₁ k₂) hk₂, add_zero], }, /- Now the main argument: pure tensors. -/ rintros ⟨m₁, hm₁⟩ ⟨m₂, hm₂⟩, change ∃ k, (F^k) ((g : M₁ ⊗[R] M₂ →ₗ[R] M₃) (m₁ ⊗ₜ m₂)) = 0, /- Eliminate `g` from the picture. -/ let f₁ : module.End R (M₁ ⊗[R] M₂) := (to_endomorphism R L M₁ x - (χ₁ x) • 1).rtensor M₂, let f₂ : module.End R (M₁ ⊗[R] M₂) := (to_endomorphism R L M₂ x - (χ₂ x) • 1).ltensor M₁, have h_comm_square : F ∘ₗ ↑g = (g : M₁ ⊗[R] M₂ →ₗ[R] M₃).comp (f₁ + f₂), { ext m₁ m₂, simp only [← g.map_lie x (m₁ ⊗ₜ m₂), add_smul, sub_tmul, tmul_sub, smul_tmul, lie_tmul_right, tmul_smul, to_endomorphism_apply_apply, lie_module_hom.map_smul, linear_map.one_apply, lie_module_hom.coe_to_linear_map, linear_map.smul_apply, function.comp_app, linear_map.coe_comp, linear_map.rtensor_tmul, lie_module_hom.map_add, linear_map.add_apply, lie_module_hom.map_sub, linear_map.sub_apply, linear_map.ltensor_tmul, algebra_tensor_module.curry_apply, curry_apply, linear_map.to_fun_eq_coe, linear_map.coe_restrict_scalars_eq_coe], abel, }, suffices : ∃ k, ((f₁ + f₂)^k) (m₁ ⊗ₜ m₂) = 0, { obtain ⟨k, hk⟩ := this, use k, rw [← linear_map.comp_apply, linear_map.commute_pow_left_of_commute h_comm_square, linear_map.comp_apply, hk, linear_map.map_zero], }, /- Unpack the information we have about `m₁`, `m₂`. -/ simp only [mem_pre_weight_space] at hm₁ hm₂, obtain ⟨k₁, hk₁⟩ := hm₁ x, obtain ⟨k₂, hk₂⟩ := hm₂ x, have hf₁ : (f₁^k₁) (m₁ ⊗ₜ m₂) = 0, { simp only [hk₁, zero_tmul, linear_map.rtensor_tmul, linear_map.rtensor_pow], }, have hf₂ : (f₂^k₂) (m₁ ⊗ₜ m₂) = 0, { simp only [hk₂, tmul_zero, linear_map.ltensor_tmul, linear_map.ltensor_pow], }, /- It's now just an application of the binomial theorem. -/ use k₁ + k₂ - 1, have hf_comm : commute f₁ f₂, { ext m₁ m₂, simp only [linear_map.mul_apply, linear_map.rtensor_tmul, linear_map.ltensor_tmul, algebra_tensor_module.curry_apply, linear_map.to_fun_eq_coe, linear_map.ltensor_tmul, curry_apply, linear_map.coe_restrict_scalars_eq_coe], }, rw hf_comm.add_pow', simp only [tensor_product.map_incl, submodule.subtype_apply, finset.sum_apply, submodule.coe_mk, linear_map.coe_fn_sum, tensor_product.map_tmul, linear_map.smul_apply], /- The required sum is zero because each individual term is zero. -/ apply finset.sum_eq_zero, rintros ⟨i, j⟩ hij, /- Eliminate the binomial coefficients from the picture. -/ suffices : (f₁^i * f₂^j) (m₁ ⊗ₜ m₂) = 0, { rw this, apply smul_zero, }, /- Finish off with appropriate case analysis. -/ cases nat.le_or_le_of_add_eq_add_pred (finset.nat.mem_antidiagonal.mp hij) with hi hj, { rw [(hf_comm.pow_pow i j).eq, linear_map.mul_apply, linear_map.pow_map_zero_of_le hi hf₁, linear_map.map_zero], }, { rw [linear_map.mul_apply, linear_map.pow_map_zero_of_le hj hf₂, linear_map.map_zero], }, end variables {L M} lemma lie_mem_pre_weight_space_of_mem_pre_weight_space {χ₁ χ₂ : L → R} {x : L} {m : M} (hx : x ∈ pre_weight_space L χ₁) (hm : m ∈ pre_weight_space M χ₂) : ⁅x, m⁆ ∈ pre_weight_space M (χ₁ + χ₂) := begin apply lie_module.weight_vector_multiplication L L M M (to_module_hom R L M) χ₁ χ₂, simp only [lie_module_hom.coe_to_linear_map, function.comp_app, linear_map.coe_comp, tensor_product.map_incl, linear_map.mem_range], use [⟨x, hx⟩ ⊗ₜ ⟨m, hm⟩], simp only [submodule.subtype_apply, to_module_hom_apply, tensor_product.map_tmul], refl, end variables (M) /-- If a Lie algebra is nilpotent, then pre-weight spaces are Lie submodules. -/ def weight_space [lie_algebra.is_nilpotent R L] (χ : L → R) : lie_submodule R L M := { lie_mem := λ x m hm, begin rw ← zero_add χ, refine lie_mem_pre_weight_space_of_mem_pre_weight_space _ hm, suffices : pre_weight_space L (0 : L → R) = ⊤, { simp only [this, submodule.mem_top], }, exact lie_algebra.infi_max_gen_zero_eigenspace_eq_top_of_nilpotent R L, end, .. pre_weight_space M χ } lemma mem_weight_space [lie_algebra.is_nilpotent R L] (χ : L → R) (m : M) : m ∈ weight_space M χ ↔ m ∈ pre_weight_space M χ := iff.rfl /-- See also the more useful form `lie_module.zero_weight_space_eq_top_of_nilpotent`. -/ @[simp] lemma zero_weight_space_eq_top_of_nilpotent' [lie_algebra.is_nilpotent R L] [is_nilpotent R L M] : weight_space M (0 : L → R) = ⊤ := begin rw [← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.top_coe_submodule], exact infi_max_gen_zero_eigenspace_eq_top_of_nilpotent R L M, end lemma coe_weight_space_of_top [lie_algebra.is_nilpotent R L] (χ : L → R) : (weight_space M (χ ∘ (⊤ : lie_subalgebra R L).incl) : submodule R M) = weight_space M χ := begin ext m, simp only [weight_space, lie_submodule.coe_to_submodule_mk, lie_subalgebra.coe_bracket_of_module, function.comp_app, mem_pre_weight_space], split; intros h x, { obtain ⟨k, hk⟩ := h ⟨x, set.mem_univ x⟩, use k, exact hk, }, { obtain ⟨k, hk⟩ := h x, use k, exact hk, }, end @[simp] lemma zero_weight_space_eq_top_of_nilpotent [lie_algebra.is_nilpotent R L] [is_nilpotent R L M] : weight_space M (0 : (⊤ : lie_subalgebra R L) → R) = ⊤ := begin /- We use `coe_weight_space_of_top` as a trick to circumvent the fact that we don't (yet) know `is_nilpotent R (⊤ : lie_subalgebra R L) M` is equivalent to `is_nilpotent R L M`. -/ have h₀ : (0 : L → R) ∘ (⊤ : lie_subalgebra R L).incl = 0, { ext, refl, }, rw [← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.top_coe_submodule, ← h₀, coe_weight_space_of_top, ← infi_max_gen_zero_eigenspace_eq_top_of_nilpotent R L M], refl, end /-- Given a Lie module `M` of a Lie algebra `L`, a weight of `M` with respect to a nilpotent subalgebra `H ⊆ L` is a Lie character whose corresponding weight space is non-empty. -/ def is_weight (χ : lie_character R H) : Prop := weight_space M χ ≠ ⊥ /-- For a non-trivial nilpotent Lie module over a nilpotent Lie algebra, the zero character is a weight with respect to the `⊤` Lie subalgebra. -/ lemma is_weight_zero_of_nilpotent [nontrivial M] [lie_algebra.is_nilpotent R L] [is_nilpotent R L M] : is_weight (⊤ : lie_subalgebra R L) M 0 := by { rw [is_weight, lie_hom.coe_zero, zero_weight_space_eq_top_of_nilpotent], exact top_ne_bot, } /-- A (nilpotent) Lie algebra acts nilpotently on the zero weight space of a Noetherian Lie module. -/ lemma is_nilpotent_to_endomorphism_weight_space_zero [lie_algebra.is_nilpotent R L] [is_noetherian R M] (x : L) : _root_.is_nilpotent $ to_endomorphism R L (weight_space M (0 : L → R)) x := begin obtain ⟨k, hk⟩ := exists_pre_weight_space_zero_le_ker_of_is_noetherian R M x, use k, ext ⟨m, hm : m ∈ pre_weight_space M 0⟩, rw [linear_map.zero_apply, lie_submodule.coe_zero, submodule.coe_eq_zero, ← lie_submodule.to_endomorphism_restrict_eq_to_endomorphism, linear_map.pow_restrict, ← set_like.coe_eq_coe, linear_map.restrict_apply, submodule.coe_mk, lie_submodule.coe_zero], exact hk hm, end /-- By Engel's theorem, when the Lie algebra is Noetherian, the zero weight space of a Noetherian Lie module is nilpotent. -/ instance [lie_algebra.is_nilpotent R L] [is_noetherian R L] [is_noetherian R M] : is_nilpotent R L (weight_space M (0 : L → R)) := is_nilpotent_iff_forall.mpr $ is_nilpotent_to_endomorphism_weight_space_zero M end lie_module namespace lie_algebra open_locale tensor_product open tensor_product.lie_module open lie_module /-- Given a nilpotent Lie subalgebra `H ⊆ L`, the root space of a map `χ : H → R` is the weight space of `L` regarded as a module of `H` via the adjoint action. -/ abbreviation root_space (χ : H → R) : lie_submodule R H L := weight_space L χ @[simp] lemma zero_root_space_eq_top_of_nilpotent [h : is_nilpotent R L] : root_space (⊤ : lie_subalgebra R L) 0 = ⊤ := zero_weight_space_eq_top_of_nilpotent L /-- A root of a Lie algebra `L` with respect to a nilpotent subalgebra `H ⊆ L` is a weight of `L`, regarded as a module of `H` via the adjoint action. -/ abbreviation is_root := is_weight H L @[simp] lemma root_space_comap_eq_weight_space (χ : H → R) : (root_space H χ).comap H.incl' = weight_space H χ := begin ext x, let f : H → module.End R L := λ y, to_endomorphism R H L y - (χ y) • 1, let g : H → module.End R H := λ y, to_endomorphism R H H y - (χ y) • 1, suffices : (∀ (y : H), ∃ (k : ℕ), ((f y)^k).comp (H.incl : H →ₗ[R] L) x = 0) ↔ ∀ (y : H), ∃ (k : ℕ), (H.incl : H →ₗ[R] L).comp ((g y)^k) x = 0, { simp only [lie_hom.coe_to_linear_map, lie_subalgebra.coe_incl, function.comp_app, linear_map.coe_comp, submodule.coe_eq_zero] at this, simp only [mem_weight_space, mem_pre_weight_space, lie_subalgebra.coe_incl', lie_submodule.mem_comap, this], }, have hfg : ∀ (y : H), (f y).comp (H.incl : H →ₗ[R] L) = (H.incl : H →ₗ[R] L).comp (g y), { rintros ⟨y, hy⟩, ext ⟨z, hz⟩, simp only [submodule.coe_sub, to_endomorphism_apply_apply, lie_hom.coe_to_linear_map, linear_map.one_apply, lie_subalgebra.coe_incl, lie_subalgebra.coe_bracket_of_module, lie_subalgebra.coe_bracket, linear_map.smul_apply, function.comp_app, submodule.coe_smul_of_tower, linear_map.coe_comp, linear_map.sub_apply], }, simp_rw [linear_map.commute_pow_left_of_commute (hfg _)], end variables {H M} lemma lie_mem_weight_space_of_mem_weight_space {χ₁ χ₂ : H → R} {x : L} {m : M} (hx : x ∈ root_space H χ₁) (hm : m ∈ weight_space M χ₂) : ⁅x, m⁆ ∈ weight_space M (χ₁ + χ₂) := begin apply lie_module.weight_vector_multiplication H L M M ((to_module_hom R L M).restrict_lie H) χ₁ χ₂, simp only [lie_module_hom.coe_to_linear_map, function.comp_app, linear_map.coe_comp, tensor_product.map_incl, linear_map.mem_range], use [⟨x, hx⟩ ⊗ₜ ⟨m, hm⟩], simp only [submodule.subtype_apply, to_module_hom_apply, submodule.coe_mk, lie_module_hom.coe_restrict_lie, tensor_product.map_tmul], end variables (R L H M) /-- Auxiliary definition for `root_space_weight_space_product`, which is close to the deterministic timeout limit. -/ def root_space_weight_space_product_aux {χ₁ χ₂ χ₃ : H → R} (hχ : χ₁ + χ₂ = χ₃) : (root_space H χ₁) →ₗ[R] (weight_space M χ₂) →ₗ[R] (weight_space M χ₃) := { to_fun := λ x, { to_fun := λ m, ⟨⁅(x : L), (m : M)⁆, hχ ▸ (lie_mem_weight_space_of_mem_weight_space x.property m.property) ⟩, map_add' := λ m n, by { simp only [lie_submodule.coe_add, lie_add], refl, }, map_smul' := λ t m, by { conv_lhs { congr, rw [lie_submodule.coe_smul, lie_smul], }, refl, }, }, map_add' := λ x y, by ext m; rw [linear_map.add_apply, linear_map.coe_mk, linear_map.coe_mk, linear_map.coe_mk, subtype.coe_mk, lie_submodule.coe_add, lie_submodule.coe_add, add_lie, subtype.coe_mk, subtype.coe_mk], map_smul' := λ t x, begin simp only [ring_hom.id_apply], ext m, rw [linear_map.smul_apply, linear_map.coe_mk, linear_map.coe_mk, subtype.coe_mk, lie_submodule.coe_smul, smul_lie, lie_submodule.coe_smul, subtype.coe_mk], end, } /-- Given a nilpotent Lie subalgebra `H ⊆ L` together with `χ₁ χ₂ : H → R`, there is a natural `R`-bilinear product of root vectors and weight vectors, compatible with the actions of `H`. -/ def root_space_weight_space_product (χ₁ χ₂ χ₃ : H → R) (hχ : χ₁ + χ₂ = χ₃) : (root_space H χ₁) ⊗[R] (weight_space M χ₂) →ₗ⁅R,H⁆ weight_space M χ₃ := lift_lie R H (root_space H χ₁) (weight_space M χ₂) (weight_space M χ₃) { to_linear_map := root_space_weight_space_product_aux R L H M hχ, map_lie' := λ x y, by ext m; rw [root_space_weight_space_product_aux, lie_hom.lie_apply, lie_submodule.coe_sub, linear_map.coe_mk, linear_map.coe_mk, subtype.coe_mk, subtype.coe_mk, lie_submodule.coe_bracket, lie_submodule.coe_bracket, subtype.coe_mk, lie_subalgebra.coe_bracket_of_module, lie_subalgebra.coe_bracket_of_module, lie_submodule.coe_bracket, lie_subalgebra.coe_bracket_of_module, lie_lie], } @[simp] lemma coe_root_space_weight_space_product_tmul (χ₁ χ₂ χ₃ : H → R) (hχ : χ₁ + χ₂ = χ₃) (x : root_space H χ₁) (m : weight_space M χ₂) : (root_space_weight_space_product R L H M χ₁ χ₂ χ₃ hχ (x ⊗ₜ m) : M) = ⁅(x : L), (m : M)⁆ := by simp only [root_space_weight_space_product, root_space_weight_space_product_aux, lift_apply, lie_module_hom.coe_to_linear_map, coe_lift_lie_eq_lift_coe, submodule.coe_mk, linear_map.coe_mk, lie_module_hom.coe_mk] /-- Given a nilpotent Lie subalgebra `H ⊆ L` together with `χ₁ χ₂ : H → R`, there is a natural `R`-bilinear product of root vectors, compatible with the actions of `H`. -/ def root_space_product (χ₁ χ₂ χ₃ : H → R) (hχ : χ₁ + χ₂ = χ₃) : (root_space H χ₁) ⊗[R] (root_space H χ₂) →ₗ⁅R,H⁆ root_space H χ₃ := root_space_weight_space_product R L H L χ₁ χ₂ χ₃ hχ @[simp] lemma root_space_product_def : root_space_product R L H = root_space_weight_space_product R L H L := rfl lemma root_space_product_tmul (χ₁ χ₂ χ₃ : H → R) (hχ : χ₁ + χ₂ = χ₃) (x : root_space H χ₁) (y : root_space H χ₂) : (root_space_product R L H χ₁ χ₂ χ₃ hχ (x ⊗ₜ y) : L) = ⁅(x : L), (y : L)⁆ := by simp only [root_space_product_def, coe_root_space_weight_space_product_tmul] /-- Given a nilpotent Lie subalgebra `H ⊆ L`, the root space of the zero map `0 : H → R` is a Lie subalgebra of `L`. -/ def zero_root_subalgebra : lie_subalgebra R L := { lie_mem' := λ x y hx hy, by { let xy : (root_space H 0) ⊗[R] (root_space H 0) := ⟨x, hx⟩ ⊗ₜ ⟨y, hy⟩, suffices : (root_space_product R L H 0 0 0 (add_zero 0) xy : L) ∈ root_space H 0, { rwa [root_space_product_tmul, subtype.coe_mk, subtype.coe_mk] at this, }, exact (root_space_product R L H 0 0 0 (add_zero 0) xy).property, }, .. (root_space H 0 : submodule R L) } @[simp] lemma coe_zero_root_subalgebra : (zero_root_subalgebra R L H : submodule R L) = root_space H 0 := rfl lemma mem_zero_root_subalgebra (x : L) : x ∈ zero_root_subalgebra R L H ↔ ∀ (y : H), ∃ (k : ℕ), ((to_endomorphism R H L y)^k) x = 0 := by simp only [zero_root_subalgebra, mem_weight_space, mem_pre_weight_space, pi.zero_apply, sub_zero, set_like.mem_coe, zero_smul, lie_submodule.mem_coe_submodule, submodule.mem_carrier, lie_subalgebra.mem_mk_iff] lemma to_lie_submodule_le_root_space_zero : H.to_lie_submodule ≤ root_space H 0 := begin intros x hx, simp only [lie_subalgebra.mem_to_lie_submodule] at hx, simp only [mem_weight_space, mem_pre_weight_space, pi.zero_apply, sub_zero, zero_smul], intros y, unfreezingI { obtain ⟨k, hk⟩ := (infer_instance : is_nilpotent R H) }, use k, let f : module.End R H := to_endomorphism R H H y, let g : module.End R L := to_endomorphism R H L y, have hfg : g.comp (H : submodule R L).subtype = (H : submodule R L).subtype.comp f, { ext z, simp only [to_endomorphism_apply_apply, submodule.subtype_apply, lie_subalgebra.coe_bracket_of_module, lie_subalgebra.coe_bracket, function.comp_app, linear_map.coe_comp], }, change (g^k).comp (H : submodule R L).subtype ⟨x, hx⟩ = 0, rw linear_map.commute_pow_left_of_commute hfg k, have h := iterate_to_endomorphism_mem_lower_central_series R H H y ⟨x, hx⟩ k, rw [hk, lie_submodule.mem_bot] at h, simp only [submodule.subtype_apply, function.comp_app, linear_map.pow_apply, linear_map.coe_comp, submodule.coe_eq_zero], exact h, end lemma le_zero_root_subalgebra : H ≤ zero_root_subalgebra R L H := begin rw [← lie_subalgebra.coe_submodule_le_coe_submodule, ← H.coe_to_lie_submodule, coe_zero_root_subalgebra, lie_submodule.coe_submodule_le_coe_submodule], exact to_lie_submodule_le_root_space_zero R L H, end @[simp] lemma zero_root_subalgebra_normalizer_eq_self : (zero_root_subalgebra R L H).normalizer = zero_root_subalgebra R L H := begin refine le_antisymm _ (lie_subalgebra.le_normalizer _), intros x hx, rw lie_subalgebra.mem_normalizer_iff at hx, rw mem_zero_root_subalgebra, rintros ⟨y, hy⟩, specialize hx y (le_zero_root_subalgebra R L H hy), rw mem_zero_root_subalgebra at hx, obtain ⟨k, hk⟩ := hx ⟨y, hy⟩, rw [← lie_skew, linear_map.map_neg, neg_eq_zero] at hk, use k + 1, rw [linear_map.iterate_succ, linear_map.coe_comp, function.comp_app, to_endomorphism_apply_apply, lie_subalgebra.coe_bracket_of_module, submodule.coe_mk, hk], end /-- If the zero root subalgebra of a nilpotent Lie subalgebra `H` is just `H` then `H` is a Cartan subalgebra. When `L` is Noetherian, it follows from Engel's theorem that the converse holds. See `lie_algebra.zero_root_subalgebra_eq_iff_is_cartan` -/ lemma is_cartan_of_zero_root_subalgebra_eq (h : zero_root_subalgebra R L H = H) : H.is_cartan_subalgebra := { nilpotent := infer_instance, self_normalizing := by { rw ← h, exact zero_root_subalgebra_normalizer_eq_self R L H, } } @[simp] lemma zero_root_subalgebra_eq_of_is_cartan (H : lie_subalgebra R L) [H.is_cartan_subalgebra] [is_noetherian R L] : zero_root_subalgebra R L H = H := begin refine le_antisymm _ (le_zero_root_subalgebra R L H), suffices : root_space H 0 ≤ H.to_lie_submodule, { exact λ x hx, this hx, }, obtain ⟨k, hk⟩ := (root_space H 0).is_nilpotent_iff_exists_self_le_ucs.mp (by apply_instance), exact hk.trans (lie_submodule.ucs_le_of_centralizer_eq_self (by simp) k), end lemma zero_root_subalgebra_eq_iff_is_cartan [is_noetherian R L] : zero_root_subalgebra R L H = H ↔ H.is_cartan_subalgebra := ⟨is_cartan_of_zero_root_subalgebra_eq R L H, by { introsI, simp, }⟩ end lie_algebra namespace lie_module open lie_algebra variables {R L H} /-- A priori, weight spaces are Lie submodules over the Lie subalgebra `H` used to define them. However they are naturally Lie submodules over the (in general larger) Lie subalgebra `zero_root_subalgebra R L H`. Even though it is often the case that `zero_root_subalgebra R L H = H`, it is likely to be useful to have the flexibility not to have to invoke this equality (as well as to work more generally). -/ def weight_space' (χ : H → R) : lie_submodule R (zero_root_subalgebra R L H) M := { lie_mem := λ x m hm, by { have hx : (x : L) ∈ root_space H 0, { rw [← lie_submodule.mem_coe_submodule, ← coe_zero_root_subalgebra], exact x.property, }, rw ← zero_add χ, exact lie_mem_weight_space_of_mem_weight_space hx hm, }, .. (weight_space M χ : submodule R M) } @[simp] lemma coe_weight_space' (χ : H → R) : (weight_space' M χ : submodule R M) = weight_space M χ := rfl end lie_module
f5e74f86eb1e3b252aab2ffe41d675f39ebfb2c4
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/number_theory/pell.lean
d59b87ec9b0ae7f436a7c2fed84328546ec8e0e5
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,690
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.nat.modeq import number_theory.zsqrtd.basic /-! # Pell's equation and Matiyasevic's theorem This file solves Pell's equation, i.e. integer solutions to `x ^ 2 - d * y ^ 2 = 1` in the special case that `d = a ^ 2 - 1`. This is then applied to prove Matiyasevic's theorem that the power function is Diophantine, which is the last key ingredient in the solution to Hilbert's tenth problem. For the definition of Diophantine function, see `dioph.lean`. ## Main definition * `pell` is a function assigning to a natural number `n` the `n`-th solution to Pell's equation constructed recursively from the initial solution `(0, 1)`. ## Main statements * `eq_pell` shows that every solution to Pell's equation is recursively obtained using `pell` * `matiyasevic` shows that a certain system of Diophantine equations has a solution if and only if the first variable is the `x`-component in a solution to Pell's equation - the key step towards Hilbert's tenth problem in Davis' version of Matiyasevic's theorem. * `eq_pow_of_pell` shows that the power function is Diophantine. ## Implementation notes The proof of Matiyasevic's theorem doesn't follow Matiyasevic's original account of using Fibonacci numbers but instead Davis' variant of using solutions to Pell's equation. ## References * [M. Carneiro, _A Lean formalization of Matiyasiv's theorem_][carneiro2018matiysevic] * [M. Davis, _Hilbert's tenth problem is unsolvable_][MR317916] ## Tags Pell's equation, Matiyasevic's theorem, Hilbert's tenth problem ## TODO * Please the unused arguments linter. * Provide solutions to Pell's equation for the case of arbitrary `d` (not just `d = a ^ 2 - 1` like in the current version) and furthermore also for `x ^ 2 - d * y ^ 2 = -1`. * Connect solutions to the continued fraction expansion of `√d`. -/ namespace pell open nat section parameters {a : ℕ} (a1 : 1 < a) include a1 private def d := a*a - 1 @[simp] theorem d_pos : 0 < d := nat.sub_pos_of_lt (mul_lt_mul a1 (le_of_lt a1) dec_trivial dec_trivial : 1*1<a*a) /-- The Pell sequences, i.e. the sequence of integer solutions to `x ^ 2 - d * y ^ 2 = 1`, where `d = a ^ 2 - 1`, defined together in mutual recursion. -/ -- TODO(lint): Fix double namespace issue @[nolint dup_namespace] def pell : ℕ → ℕ × ℕ := λn, nat.rec_on n (1, 0) (λn xy, (xy.1*a + d*xy.2, xy.1 + xy.2*a)) /-- The Pell `x` sequence. -/ def xn (n : ℕ) : ℕ := (pell n).1 /-- The Pell `y` sequence. -/ def yn (n : ℕ) : ℕ := (pell n).2 @[simp] theorem pell_val (n : ℕ) : pell n = (xn n, yn n) := show pell n = ((pell n).1, (pell n).2), from match pell n with (a, b) := rfl end @[simp] theorem xn_zero : xn 0 = 1 := rfl @[simp] theorem yn_zero : yn 0 = 0 := rfl @[simp] theorem xn_succ (n : ℕ) : xn (n+1) = xn n * a + d * yn n := rfl @[simp] theorem yn_succ (n : ℕ) : yn (n+1) = xn n + yn n * a := rfl @[simp] theorem xn_one : xn 1 = a := by simp @[simp] theorem yn_one : yn 1 = 1 := by simp /-- The Pell `x` sequence, considered as an integer sequence.-/ def xz (n : ℕ) : ℤ := xn n /-- The Pell `y` sequence, considered as an integer sequence.-/ def yz (n : ℕ) : ℤ := yn n /-- The element `a` such that `d = a ^ 2 - 1`, considered as an integer.-/ def az : ℤ := a theorem asq_pos : 0 < a*a := le_trans (le_of_lt a1) (by have := @nat.mul_le_mul_left 1 a a (le_of_lt a1); rwa mul_one at this) theorem dz_val : ↑d = az*az - 1 := have 1 ≤ a*a, from asq_pos, show ↑(a*a - 1) = _, by rw int.coe_nat_sub this; refl @[simp] theorem xz_succ (n : ℕ) : xz (n+1) = xz n * az + ↑d * yz n := rfl @[simp] theorem yz_succ (n : ℕ) : yz (n+1) = xz n + yz n * az := rfl /-- The Pell sequence can also be viewed as an element of `ℤ√d` -/ def pell_zd (n : ℕ) : ℤ√d := ⟨xn n, yn n⟩ @[simp] theorem pell_zd_re (n : ℕ) : (pell_zd n).re = xn n := rfl @[simp] theorem pell_zd_im (n : ℕ) : (pell_zd n).im = yn n := rfl /-- The property of being a solution to the Pell equation, expressed as a property of elements of `ℤ√d`. -/ def is_pell : ℤ√d → Prop | ⟨x, y⟩ := x*x - d*y*y = 1 theorem is_pell_nat {x y : ℕ} : is_pell ⟨x, y⟩ ↔ x*x - d*y*y = 1 := ⟨λh, int.coe_nat_inj (by rw int.coe_nat_sub (int.le_of_coe_nat_le_coe_nat $ int.le.intro_sub h); exact h), λh, show ((x*x : ℕ) - (d*y*y:ℕ) : ℤ) = 1, by rw [← int.coe_nat_sub $ le_of_lt $ nat.lt_of_sub_eq_succ h, h]; refl⟩ theorem is_pell_norm : Π {b : ℤ√d}, is_pell b ↔ b * b.conj = 1 | ⟨x, y⟩ := by simp [zsqrtd.ext, is_pell, mul_comm]; ring_nf theorem is_pell_mul {b c : ℤ√d} (hb : is_pell b) (hc : is_pell c) : is_pell (b * c) := is_pell_norm.2 (by simp [mul_comm, mul_left_comm, zsqrtd.conj_mul, pell.is_pell_norm.1 hb, pell.is_pell_norm.1 hc]) theorem is_pell_conj : ∀ {b : ℤ√d}, is_pell b ↔ is_pell b.conj | ⟨x, y⟩ := by simp [is_pell, zsqrtd.conj] @[simp] theorem pell_zd_succ (n : ℕ) : pell_zd (n+1) = pell_zd n * ⟨a, 1⟩ := by simp [zsqrtd.ext] theorem is_pell_one : is_pell ⟨a, 1⟩ := show az*az-d*1*1=1, by simp [dz_val]; ring theorem is_pell_pell_zd : ∀ (n : ℕ), is_pell (pell_zd n) | 0 := rfl | (n+1) := let o := is_pell_one in by simp; exact pell.is_pell_mul (is_pell_pell_zd n) o @[simp] theorem pell_eqz (n : ℕ) : xz n * xz n - d * yz n * yz n = 1 := is_pell_pell_zd n @[simp] theorem pell_eq (n : ℕ) : xn n * xn n - d * yn n * yn n = 1 := let pn := pell_eqz n in have h : (↑(xn n * xn n) : ℤ) - ↑(d * yn n * yn n) = 1, by repeat {rw int.coe_nat_mul}; exact pn, have hl : d * yn n * yn n ≤ xn n * xn n, from int.le_of_coe_nat_le_coe_nat $ int.le.intro $ add_eq_of_eq_sub' $ eq.symm h, int.coe_nat_inj (by rw int.coe_nat_sub hl; exact h) instance dnsq : zsqrtd.nonsquare d := ⟨λn h, have n*n + 1 = a*a, by rw ← h; exact nat.succ_pred_eq_of_pos (asq_pos a1), have na : n < a, from nat.mul_self_lt_mul_self_iff.2 (by rw ← this; exact nat.lt_succ_self _), have (n+1)*(n+1) ≤ n*n + 1, by rw this; exact nat.mul_self_le_mul_self na, have n+n ≤ 0, from @nat.le_of_add_le_add_right (n*n + 1) _ _ (by ring_nf at this ⊢; assumption), ne_of_gt d_pos $ by rwa nat.eq_zero_of_le_zero ((nat.le_add_left _ _).trans this) at h⟩ theorem xn_ge_a_pow : ∀ (n : ℕ), a^n ≤ xn n | 0 := le_refl 1 | (n+1) := by simp [pow_succ']; exact le_trans (nat.mul_le_mul_right _ (xn_ge_a_pow n)) (nat.le_add_right _ _) theorem n_lt_a_pow : ∀ (n : ℕ), n < a^n | 0 := nat.le_refl 1 | (n+1) := begin have IH := n_lt_a_pow n, have : a^n + a^n ≤ a^n * a, { rw ← mul_two, exact nat.mul_le_mul_left _ a1 }, simp [pow_succ'], refine lt_of_lt_of_le _ this, exact add_lt_add_of_lt_of_le IH (lt_of_le_of_lt (nat.zero_le _) IH) end theorem n_lt_xn (n) : n < xn n := lt_of_lt_of_le (n_lt_a_pow n) (xn_ge_a_pow n) theorem x_pos (n) : 0 < xn n := lt_of_le_of_lt (nat.zero_le n) (n_lt_xn n) lemma eq_pell_lem : ∀n (b:ℤ√d), 1 ≤ b → is_pell b → b ≤ pell_zd n → ∃n, b = pell_zd n | 0 b := λh1 hp hl, ⟨0, @zsqrtd.le_antisymm _ dnsq _ _ hl h1⟩ | (n+1) b := λh1 hp h, have a1p : (0:ℤ√d) ≤ ⟨a, 1⟩, from trivial, have am1p : (0:ℤ√d) ≤ ⟨a, -1⟩, from show (_:nat) ≤ _, by simp; exact nat.pred_le _, have a1m : (⟨a, 1⟩ * ⟨a, -1⟩ : ℤ√d) = 1, from is_pell_norm.1 is_pell_one, if ha : (⟨↑a, 1⟩ : ℤ√d) ≤ b then let ⟨m, e⟩ := eq_pell_lem n (b * ⟨a, -1⟩) (by rw ← a1m; exact mul_le_mul_of_nonneg_right ha am1p) (is_pell_mul hp (is_pell_conj.1 is_pell_one)) (by have t := mul_le_mul_of_nonneg_right h am1p; rwa [pell_zd_succ, mul_assoc, a1m, mul_one] at t) in ⟨m+1, by rw [show b = b * ⟨a, -1⟩ * ⟨a, 1⟩, by rw [mul_assoc, eq.trans (mul_comm _ _) a1m]; simp, pell_zd_succ, e]⟩ else suffices ¬1 < b, from ⟨0, show b = 1, from (or.resolve_left (lt_or_eq_of_le h1) this).symm⟩, λ h1l, by cases b with x y; exact have bm : (_*⟨_,_⟩ :ℤ√(d a1)) = 1, from pell.is_pell_norm.1 hp, have y0l : (0:ℤ√(d a1)) < ⟨x - x, y - -y⟩, from sub_lt_sub h1l $ λ(hn : (1:ℤ√(d a1)) ≤ ⟨x, -y⟩), by have t := mul_le_mul_of_nonneg_left hn (le_trans zero_le_one h1); rw [bm, mul_one] at t; exact h1l t, have yl2 : (⟨_, _⟩ : ℤ√_) < ⟨_, _⟩, from show (⟨x, y⟩ - ⟨x, -y⟩ : ℤ√(d a1)) < ⟨a, 1⟩ - ⟨a, -1⟩, from sub_lt_sub (by exact ha) $ λ(hn : (⟨x, -y⟩ : ℤ√(d a1)) ≤ ⟨a, -1⟩), by have t := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hn (le_trans zero_le_one h1)) a1p; rw [bm, one_mul, mul_assoc, eq.trans (mul_comm _ _) a1m, mul_one] at t; exact ha t, by simp at y0l; simp at yl2; exact match y, y0l, (yl2 : (⟨_, _⟩ : ℤ√_) < ⟨_, _⟩) with | 0, y0l, yl2 := y0l (le_refl 0) | (y+1 : ℕ), y0l, yl2 := yl2 (zsqrtd.le_of_le_le (le_refl 0) (let t := int.coe_nat_le_coe_nat_of_le (nat.succ_pos y) in add_le_add t t)) | -[1+y], y0l, yl2 := y0l trivial end theorem eq_pell_zd (b : ℤ√d) (b1 : 1 ≤ b) (hp : is_pell b) : ∃n, b = pell_zd n := let ⟨n, h⟩ := @zsqrtd.le_arch d b in eq_pell_lem n b b1 hp $ zsqrtd.le_trans h $ by rw zsqrtd.coe_nat_val; exact zsqrtd.le_of_le_le (int.coe_nat_le_coe_nat_of_le $ le_of_lt $ n_lt_xn _ _) (int.coe_zero_le _) /-- Every solution to **Pell's equation** is recursively obtained from the initial solution `(1,0)` using the recursion `pell`. -/ theorem eq_pell {x y : ℕ} (hp : x*x - d*y*y = 1) : ∃n, x = xn n ∧ y = yn n := have (1:ℤ√d) ≤ ⟨x, y⟩, from match x, hp with | 0, (hp : 0 - _ = 1) := by rw nat.zero_sub at hp; contradiction | (x+1), hp := zsqrtd.le_of_le_le (int.coe_nat_le_coe_nat_of_le $ nat.succ_pos x) (int.coe_zero_le _) end, let ⟨m, e⟩ := eq_pell_zd ⟨x, y⟩ this (is_pell_nat.2 hp) in ⟨m, match x, y, e with ._, ._, rfl := ⟨rfl, rfl⟩ end⟩ theorem pell_zd_add (m) : ∀ n, pell_zd (m + n) = pell_zd m * pell_zd n | 0 := (mul_one _).symm | (n+1) := by rw[← add_assoc, pell_zd_succ, pell_zd_succ, pell_zd_add n, ← mul_assoc] theorem xn_add (m n) : xn (m + n) = xn m * xn n + d * yn m * yn n := by injection (pell_zd_add _ m n) with h _; repeat {rw ← int.coe_nat_add at h <|> rw ← int.coe_nat_mul at h}; exact int.coe_nat_inj h theorem yn_add (m n) : yn (m + n) = xn m * yn n + yn m * xn n := by injection (pell_zd_add _ m n) with _ h; repeat {rw ← int.coe_nat_add at h <|> rw ← int.coe_nat_mul at h}; exact int.coe_nat_inj h theorem pell_zd_sub {m n} (h : n ≤ m) : pell_zd (m - n) = pell_zd m * (pell_zd n).conj := let t := pell_zd_add n (m - n) in by rw [nat.add_sub_of_le h] at t; rw [t, mul_comm (pell_zd _ n) _, mul_assoc, (is_pell_norm _).1 (is_pell_pell_zd _ _), mul_one] theorem xz_sub {m n} (h : n ≤ m) : xz (m - n) = xz m * xz n - d * yz m * yz n := by injection (pell_zd_sub _ h) with h _; repeat {rw ← neg_mul_eq_mul_neg at h}; exact h theorem yz_sub {m n} (h : n ≤ m) : yz (m - n) = xz n * yz m - xz m * yz n := by injection (pell_zd_sub a1 h) with _ h; repeat {rw ← neg_mul_eq_mul_neg at h}; rw [add_comm, mul_comm] at h; exact h theorem xy_coprime (n) : (xn n).coprime (yn n) := nat.coprime_of_dvd' $ λk kp kx ky, let p := pell_eq n in by rw ← p; exact nat.dvd_sub (le_of_lt $ nat.lt_of_sub_eq_succ p) (kx.mul_left _) (ky.mul_left _) theorem y_increasing {m} : Π {n}, m < n → yn m < yn n | 0 h := absurd h $ nat.not_lt_zero _ | (n+1) h := have yn m ≤ yn n, from or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ h) (λhl, le_of_lt $ y_increasing hl) (λe, by rw e), by simp; refine lt_of_le_of_lt _ (nat.lt_add_of_pos_left $ x_pos a1 n); rw ← mul_one (yn a1 m); exact mul_le_mul this (le_of_lt a1) (nat.zero_le _) (nat.zero_le _) theorem x_increasing {m} : Π {n}, m < n → xn m < xn n | 0 h := absurd h $ nat.not_lt_zero _ | (n+1) h := have xn m ≤ xn n, from or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ h) (λhl, le_of_lt $ x_increasing hl) (λe, by rw e), by simp; refine lt_of_lt_of_le (lt_of_le_of_lt this _) (nat.le_add_right _ _); have t := nat.mul_lt_mul_of_pos_left a1 (x_pos a1 n); rwa mul_one at t theorem yn_ge_n : Π n, n ≤ yn n | 0 := nat.zero_le _ | (n+1) := show n < yn (n+1), from lt_of_le_of_lt (yn_ge_n n) (y_increasing $ nat.lt_succ_self n) theorem y_mul_dvd (n) : ∀k, yn n ∣ yn (n * k) | 0 := dvd_zero _ | (k+1) := by rw [nat.mul_succ, yn_add]; exact dvd_add (dvd_mul_left _ _) ((y_mul_dvd k).mul_right _) theorem y_dvd_iff (m n) : yn m ∣ yn n ↔ m ∣ n := ⟨λh, nat.dvd_of_mod_eq_zero $ (nat.eq_zero_or_pos _).resolve_right $ λhp, have co : nat.coprime (yn m) (xn (m * (n / m))), from nat.coprime.symm $ (xy_coprime _).coprime_dvd_right (y_mul_dvd m (n / m)), have m0 : 0 < m, from m.eq_zero_or_pos.resolve_left $ λe, by rw [e, nat.mod_zero] at hp; rw [e] at h; exact ne_of_lt (y_increasing a1 hp) (eq_zero_of_zero_dvd h).symm, by rw [← nat.mod_add_div n m, yn_add] at h; exact not_le_of_gt (y_increasing _ $ nat.mod_lt n m0) (nat.le_of_dvd (y_increasing _ hp) $ co.dvd_of_dvd_mul_right $ (nat.dvd_add_iff_right $ (y_mul_dvd _ _ _).mul_left _).2 h), λ⟨k, e⟩, by rw e; apply y_mul_dvd⟩ theorem xy_modeq_yn (n) : ∀ k, xn (n * k) ≡ (xn n)^k [MOD (yn n)^2] ∧ yn (n * k) ≡ k * (xn n)^(k-1) * yn n [MOD (yn n)^3] | 0 := by constructor; simp | (k+1) := let ⟨hx, hy⟩ := xy_modeq_yn k in have L : xn (n * k) * xn n + d * yn (n * k) * yn n ≡ xn n^k * xn n + 0 [MOD yn n^2], from (hx.mul_right _ ).add $ modeq_zero_iff_dvd.2 $ by rw pow_succ'; exact mul_dvd_mul_right (dvd_mul_of_dvd_right (modeq_zero_iff_dvd.1 $ (hy.modeq_of_dvd $ by simp [pow_succ']).trans $ modeq_zero_iff_dvd.2 $ by simp [-mul_comm, -mul_assoc]) _) _, have R : xn (n * k) * yn n + yn (n * k) * xn n ≡ xn n^k * yn n + k * xn n^k * yn n [MOD yn n^3], from modeq.add (by { rw pow_succ', exact hx.mul_right' _ }) $ have k * xn n^(k - 1) * yn n * xn n = k * xn n^k * yn n, by clear _let_match; cases k with k; simp [pow_succ', mul_comm, mul_left_comm], by { rw ← this, exact hy.mul_right _ }, by { rw [nat.add_sub_cancel, nat.mul_succ, xn_add, yn_add, pow_succ' (xn _ n), nat.succ_mul, add_comm (k * xn _ n^k) (xn _ n^k), right_distrib], exact ⟨L, R⟩ } theorem ysq_dvd_yy (n) : yn n * yn n ∣ yn (n * yn n) := modeq_zero_iff_dvd.1 $ ((xy_modeq_yn n (yn n)).right.modeq_of_dvd $ by simp [pow_succ]).trans (modeq_zero_iff_dvd.2 $ by simp [mul_dvd_mul_left, mul_assoc]) theorem dvd_of_ysq_dvd {n t} (h : yn n * yn n ∣ yn t) : yn n ∣ t := have nt : n ∣ t, from (y_dvd_iff n t).1 $ dvd_of_mul_left_dvd h, n.eq_zero_or_pos.elim (λ n0, by rwa n0 at ⊢ nt) $ λ (n0l : 0 < n), let ⟨k, ke⟩ := nt in have yn n ∣ k * (xn n)^(k-1), from nat.dvd_of_mul_dvd_mul_right (y_increasing n0l) $ modeq_zero_iff_dvd.1 $ by have xm := (xy_modeq_yn a1 n k).right; rw ← ke at xm; exact (xm.modeq_of_dvd $ by simp [pow_succ]).symm.trans h.modeq_zero_nat, by rw ke; exact dvd_mul_of_dvd_right (((xy_coprime _ _).pow_left _).symm.dvd_of_dvd_mul_right this) _ theorem pell_zd_succ_succ (n) : pell_zd (n + 2) + pell_zd n = (2 * a : ℕ) * pell_zd (n + 1) := have (1:ℤ√d) + ⟨a, 1⟩ * ⟨a, 1⟩ = ⟨a, 1⟩ * (2 * a), by { rw zsqrtd.coe_nat_val, change (⟨_,_⟩:ℤ√(d a1))=⟨_,_⟩, rw dz_val, change az a1 with a, rw zsqrtd.ext, dsimp, split; ring }, by simpa [mul_add, mul_comm, mul_left_comm, add_comm] using congr_arg (* pell_zd a1 n) this theorem xy_succ_succ (n) : xn (n + 2) + xn n = (2 * a) * xn (n + 1) ∧ yn (n + 2) + yn n = (2 * a) * yn (n + 1) := begin have := pell_zd_succ_succ a1 n, unfold pell_zd at this, rw [← int.cast_coe_nat, zsqrtd.smul_val] at this, injection this with h₁ h₂, split; apply int.coe_nat_inj; [simpa using h₁, simpa using h₂] end theorem xn_succ_succ (n) : xn (n + 2) + xn n = (2 * a) * xn (n + 1) := (xy_succ_succ n).1 theorem yn_succ_succ (n) : yn (n + 2) + yn n = (2 * a) * yn (n + 1) := (xy_succ_succ n).2 theorem xz_succ_succ (n) : xz (n + 2) = (2 * a : ℕ) * xz (n + 1) - xz n := eq_sub_of_add_eq $ by delta xz; rw [← int.coe_nat_add, ← int.coe_nat_mul, xn_succ_succ] theorem yz_succ_succ (n) : yz (n + 2) = (2 * a : ℕ) * yz (n + 1) - yz n := eq_sub_of_add_eq $ by delta yz; rw [← int.coe_nat_add, ← int.coe_nat_mul, yn_succ_succ] theorem yn_modeq_a_sub_one : ∀ n, yn n ≡ n [MOD a-1] | 0 := by simp | 1 := by simp | (n+2) := (yn_modeq_a_sub_one n).add_right_cancel $ begin rw [yn_succ_succ, (by ring : n + 2 + n = 2 * (n + 1))], exact ((modeq_sub a1.le).mul_left 2).mul (yn_modeq_a_sub_one (n+1)), end theorem yn_modeq_two : ∀ n, yn n ≡ n [MOD 2] | 0 := by simp | 1 := by simp | (n+2) := (yn_modeq_two n).add_right_cancel $ begin rw [yn_succ_succ, mul_assoc, (by ring : n + 2 + n = 2 * (n + 1))], exact (dvd_mul_right 2 _).modeq_zero_nat.trans (dvd_mul_right 2 _).zero_modeq_nat, end lemma x_sub_y_dvd_pow_lem (y2 y1 y0 yn1 yn0 xn1 xn0 ay a2 : ℤ) : (a2 * yn1 - yn0) * ay + y2 - (a2 * xn1 - xn0) = y2 - a2 * y1 + y0 + a2 * (yn1 * ay + y1 - xn1) - (yn0 * ay + y0 - xn0) := by ring theorem x_sub_y_dvd_pow (y : ℕ) : ∀ n, (2*a*y - y*y - 1 : ℤ) ∣ yz n * (a - y) + ↑(y^n) - xz n | 0 := by simp [xz, yz, int.coe_nat_zero, int.coe_nat_one] | 1 := by simp [xz, yz, int.coe_nat_zero, int.coe_nat_one] | (n+2) := have (2*a*y - y*y - 1 : ℤ) ∣ ↑(y^(n + 2)) - ↑(2 * a) * ↑(y^(n + 1)) + ↑(y^n), from ⟨-↑(y^n), by { simp [pow_succ, mul_add, int.coe_nat_mul, show ((2:ℕ):ℤ) = 2, from rfl, mul_comm, mul_left_comm], ring }⟩, by { rw [xz_succ_succ, yz_succ_succ, x_sub_y_dvd_pow_lem a1 ↑(y^(n+2)) ↑(y^(n+1)) ↑(y^n)], exact dvd_sub (dvd_add this $ (x_sub_y_dvd_pow (n+1)).mul_left _) (x_sub_y_dvd_pow n) } theorem xn_modeq_x2n_add_lem (n j) : xn n ∣ d * yn n * (yn n * xn j) + xn j := have h1 : d * yn n * (yn n * xn j) + xn j = (d * yn n * yn n + 1) * xn j, by simp [add_mul, mul_assoc], have h2 : d * yn n * yn n + 1 = xn n * xn n, by apply int.coe_nat_inj; repeat {rw int.coe_nat_add <|> rw int.coe_nat_mul}; exact add_eq_of_eq_sub' (eq.symm $ pell_eqz _ _), by rw h2 at h1; rw [h1, mul_assoc]; exact dvd_mul_right _ _ theorem xn_modeq_x2n_add (n j) : xn (2 * n + j) + xn j ≡ 0 [MOD xn n] := begin rw [two_mul, add_assoc, xn_add, add_assoc, ←zero_add 0], refine (dvd_mul_right (xn a1 n) (xn a1 (n + j))).modeq_zero_nat.add _, rw [yn_add, left_distrib, add_assoc, ←zero_add 0], exact ((dvd_mul_right _ _).mul_left _).modeq_zero_nat.add (xn_modeq_x2n_add_lem _ _ _).modeq_zero_nat, end lemma xn_modeq_x2n_sub_lem {n j} (h : j ≤ n) : xn (2 * n - j) + xn j ≡ 0 [MOD xn n] := have h1 : xz n ∣ ↑d * yz n * yz (n - j) + xz j, by rw [yz_sub _ h, mul_sub_left_distrib, sub_add_eq_add_sub]; exact dvd_sub (by delta xz; delta yz; repeat {rw ← int.coe_nat_add <|> rw ← int.coe_nat_mul}; rw mul_comm (xn a1 j) (yn a1 n); exact int.coe_nat_dvd.2 (xn_modeq_x2n_add_lem _ _ _)) ((dvd_mul_right _ _).mul_left _), begin rw [two_mul, nat.add_sub_assoc h, xn_add, add_assoc, ←zero_add 0], exact (dvd_mul_right _ _).modeq_zero_nat.add (int.coe_nat_dvd.1 $ by simpa [xz, yz] using h1).modeq_zero_nat, end theorem xn_modeq_x2n_sub {n j} (h : j ≤ 2 * n) : xn (2 * n - j) + xn j ≡ 0 [MOD xn n] := (le_total j n).elim xn_modeq_x2n_sub_lem (λjn, have 2 * n - j + j ≤ n + j, by rw [nat.sub_add_cancel h, two_mul]; exact nat.add_le_add_left jn _, let t := xn_modeq_x2n_sub_lem (nat.le_of_add_le_add_right this) in by rwa [nat.sub_sub_self h, add_comm] at t) theorem xn_modeq_x4n_add (n j) : xn (4 * n + j) ≡ xn j [MOD xn n] := modeq.add_right_cancel' (xn (2 * n + j)) $ by refine @modeq.trans _ _ 0 _ _ (by rw add_comm; exact (xn_modeq_x2n_add _ _ _).symm); rw [show 4*n = 2*n + 2*n, from right_distrib 2 2 n, add_assoc]; apply xn_modeq_x2n_add theorem xn_modeq_x4n_sub {n j} (h : j ≤ 2 * n) : xn (4 * n - j) ≡ xn j [MOD xn n] := have h' : j ≤ 2*n, from le_trans h (by rw nat.succ_mul; apply nat.le_add_left), modeq.add_right_cancel' (xn (2 * n - j)) $ by refine @modeq.trans _ _ 0 _ _ (by rw add_comm; exact (xn_modeq_x2n_sub _ h).symm); rw [show 4*n = 2*n + 2*n, from right_distrib 2 2 n, nat.add_sub_assoc h']; apply xn_modeq_x2n_add theorem eq_of_xn_modeq_lem1 {i n} : Π {j}, i < j → j < n → xn i % xn n < xn j % xn n | 0 ij _ := absurd ij (nat.not_lt_zero _) | (j+1) ij jn := suffices xn j % xn n < xn (j + 1) % xn n, from (lt_or_eq_of_le (nat.le_of_succ_le_succ ij)).elim (λh, lt_trans (eq_of_xn_modeq_lem1 h (le_of_lt jn)) this) (λh, by rw h; exact this), by rw [nat.mod_eq_of_lt (x_increasing _ (nat.lt_of_succ_lt jn)), nat.mod_eq_of_lt (x_increasing _ jn)]; exact x_increasing _ (nat.lt_succ_self _) theorem eq_of_xn_modeq_lem2 {n} (h : 2 * xn n = xn (n + 1)) : a = 2 ∧ n = 0 := by rw [xn_succ, mul_comm] at h; exact have n = 0, from n.eq_zero_or_pos.resolve_right $ λnp, ne_of_lt (lt_of_le_of_lt (nat.mul_le_mul_left _ a1) (nat.lt_add_of_pos_right $ mul_pos (d_pos a1) (y_increasing a1 np))) h, by cases this; simp at h; exact ⟨h.symm, rfl⟩ theorem eq_of_xn_modeq_lem3 {i n} (npos : 0 < n) : Π {j}, i < j → j ≤ 2 * n → j ≠ n → ¬(a = 2 ∧ n = 1 ∧ i = 0 ∧ j = 2) → xn i % xn n < xn j % xn n | 0 ij _ _ _ := absurd ij (nat.not_lt_zero _) | (j+1) ij j2n jnn ntriv := have lem2 : ∀k > n, k ≤ 2*n → (↑(xn k % xn n) : ℤ) = xn n - xn (2 * n - k), from λk kn k2n, let k2nl := lt_of_add_lt_add_right $ show 2*n-k+k < n+k, by {rw nat.sub_add_cancel, rw two_mul; exact (add_lt_add_left kn n), exact k2n } in have xle : xn (2 * n - k) ≤ xn n, from le_of_lt $ x_increasing k2nl, suffices xn k % xn n = xn n - xn (2 * n - k), by rw [this, int.coe_nat_sub xle], by { rw ← nat.mod_eq_of_lt (nat.sub_lt (x_pos a1 n) (x_pos a1 (2 * n - k))), apply modeq.add_right_cancel' (xn a1 (2 * n - k)), rw [nat.sub_add_cancel xle], have t := xn_modeq_x2n_sub_lem a1 k2nl.le, rw nat.sub_sub_self k2n at t, exact t.trans dvd_rfl.zero_modeq_nat }, (lt_trichotomy j n).elim (λ (jn : j < n), eq_of_xn_modeq_lem1 ij (lt_of_le_of_ne jn jnn)) $ λ o, o.elim (λ (jn : j = n), by { cases jn, apply int.lt_of_coe_nat_lt_coe_nat, rw [lem2 (n+1) (nat.lt_succ_self _) j2n, show 2 * n - (n + 1) = n - 1, by rw[two_mul, ← nat.sub_sub, nat.add_sub_cancel]], refine lt_sub_left_of_add_lt (int.coe_nat_lt_coe_nat_of_lt _), cases (lt_or_eq_of_le $ nat.le_of_succ_le_succ ij) with lin ein, { rw nat.mod_eq_of_lt (x_increasing _ lin), have ll : xn a1 (n-1) + xn a1 (n-1) ≤ xn a1 n, { rw [← two_mul, mul_comm, show xn a1 n = xn a1 (n-1+1), by rw [nat.sub_add_cancel npos], xn_succ], exact le_trans (nat.mul_le_mul_left _ a1) (nat.le_add_right _ _) }, have npm : (n-1).succ = n := nat.succ_pred_eq_of_pos npos, have il : i ≤ n - 1, { apply nat.le_of_succ_le_succ, rw npm, exact lin }, cases lt_or_eq_of_le il with ill ile, { exact lt_of_lt_of_le (nat.add_lt_add_left (x_increasing a1 ill) _) ll }, { rw ile, apply lt_of_le_of_ne ll, rw ← two_mul, exact λe, ntriv $ let ⟨a2, s1⟩ := @eq_of_xn_modeq_lem2 _ a1 (n-1) (by rwa [nat.sub_add_cancel npos]) in have n1 : n = 1, from le_antisymm (nat.le_of_sub_eq_zero s1) npos, by rw [ile, a2, n1]; exact ⟨rfl, rfl, rfl, rfl⟩ } }, { rw [ein, nat.mod_self, add_zero], exact x_increasing _ (nat.pred_lt $ ne_of_gt npos) } }) (λ (jn : j > n), have lem1 : j ≠ n → xn j % xn n < xn (j + 1) % xn n → xn i % xn n < xn (j + 1) % xn n, from λjn s, (lt_or_eq_of_le (nat.le_of_succ_le_succ ij)).elim (λh, lt_trans (eq_of_xn_modeq_lem3 h (le_of_lt j2n) jn $ λ⟨a1, n1, i0, j2⟩, by rw [n1, j2] at j2n; exact absurd j2n dec_trivial) s) (λh, by rw h; exact s), lem1 (ne_of_gt jn) $ int.lt_of_coe_nat_lt_coe_nat $ by { rw [lem2 j jn (le_of_lt j2n), lem2 (j+1) (nat.le_succ_of_le jn) j2n], refine sub_lt_sub_left (int.coe_nat_lt_coe_nat_of_lt $ x_increasing _ _) _, rw [nat.sub_succ], exact nat.pred_lt (ne_of_gt $ nat.sub_pos_of_lt j2n) }) theorem eq_of_xn_modeq_le {i j n} (npos : 0 < n) (ij : i ≤ j) (j2n : j ≤ 2 * n) (h : xn i ≡ xn j [MOD xn n]) (ntriv : ¬(a = 2 ∧ n = 1 ∧ i = 0 ∧ j = 2)) : i = j := (lt_or_eq_of_le ij).resolve_left $ λij', if jn : j = n then by { refine ne_of_gt _ h, rw [jn, nat.mod_self], have x0 : 0 < xn a1 0 % xn a1 n := by rw [nat.mod_eq_of_lt (x_increasing a1 npos)]; exact dec_trivial, cases i with i, exact x0, rw jn at ij', exact x0.trans (eq_of_xn_modeq_lem3 _ npos (nat.succ_pos _) (le_trans ij j2n) (ne_of_lt ij') $ λ⟨a1, n1, _, i2⟩, by rw [n1, i2] at ij'; exact absurd ij' dec_trivial) } else ne_of_lt (eq_of_xn_modeq_lem3 npos ij' j2n jn ntriv) h theorem eq_of_xn_modeq {i j n} (npos : 0 < n) (i2n : i ≤ 2 * n) (j2n : j ≤ 2 * n) (h : xn i ≡ xn j [MOD xn n]) (ntriv : a = 2 → n = 1 → (i = 0 → j ≠ 2) ∧ (i = 2 → j ≠ 0)) : i = j := (le_total i j).elim (λij, eq_of_xn_modeq_le npos ij j2n h $ λ⟨a2, n1, i0, j2⟩, (ntriv a2 n1).left i0 j2) (λij, (eq_of_xn_modeq_le npos ij i2n h.symm $ λ⟨a2, n1, j0, i2⟩, (ntriv a2 n1).right i2 j0).symm) theorem eq_of_xn_modeq' {i j n} (ipos : 0 < i) (hin : i ≤ n) (j4n : j ≤ 4 * n) (h : xn j ≡ xn i [MOD xn n]) : j = i ∨ j + i = 4 * n := have i2n : i ≤ 2*n, by apply le_trans hin; rw two_mul; apply nat.le_add_left, have npos : 0 < n, from lt_of_lt_of_le ipos hin, (le_or_gt j (2 * n)).imp (λj2n : j ≤ 2 * n, eq_of_xn_modeq npos j2n i2n h $ λa2 n1, ⟨λj0 i2, by rw [n1, i2] at hin; exact absurd hin dec_trivial, λj2 i0, ne_of_gt ipos i0⟩) (λj2n : 2 * n < j, suffices i = 4*n - j, by rw [this, nat.add_sub_of_le j4n], have j42n : 4*n - j ≤ 2*n, from @nat.le_of_add_le_add_right j _ _ $ by rw [nat.sub_add_cancel j4n, show 4*n = 2*n + 2*n, from right_distrib 2 2 n]; exact nat.add_le_add_left (le_of_lt j2n) _, eq_of_xn_modeq npos i2n j42n (h.symm.trans $ let t := xn_modeq_x4n_sub j42n in by rwa [nat.sub_sub_self j4n] at t) (λa2 n1, ⟨λi0, absurd i0 (ne_of_gt ipos), λi2, by { rw [n1, i2] at hin, exact absurd hin dec_trivial }⟩)) theorem modeq_of_xn_modeq {i j n} (ipos : 0 < i) (hin : i ≤ n) (h : xn j ≡ xn i [MOD xn n]) : j ≡ i [MOD 4 * n] ∨ j + i ≡ 0 [MOD 4 * n] := let j' := j % (4 * n) in have n4 : 0 < 4 * n, from mul_pos dec_trivial (ipos.trans_le hin), have jl : j' < 4 * n, from nat.mod_lt _ n4, have jj : j ≡ j' [MOD 4 * n], by delta modeq; rw nat.mod_eq_of_lt jl, have ∀j q, xn (j + 4 * n * q) ≡ xn j [MOD xn n], begin intros j q, induction q with q IH, { simp }, rw [nat.mul_succ, ← add_assoc, add_comm], exact (xn_modeq_x4n_add _ _ _).trans IH end, or.imp (λ(ji : j' = i), by rwa ← ji) (λ(ji : j' + i = 4 * n), (jj.add_right _).trans $ by { rw ji, exact dvd_rfl.modeq_zero_nat }) (eq_of_xn_modeq' ipos hin jl.le $ (h.symm.trans $ by { rw ← nat.mod_add_div j (4*n), exact this j' _ }).symm) end theorem xy_modeq_of_modeq {a b c} (a1 : 1 < a) (b1 : 1 < b) (h : a ≡ b [MOD c]) : ∀ n, xn a1 n ≡ xn b1 n [MOD c] ∧ yn a1 n ≡ yn b1 n [MOD c] | 0 := by constructor; refl | 1 := by simp; exact ⟨h, modeq.refl 1⟩ | (n+2) := ⟨ (xy_modeq_of_modeq n).left.add_right_cancel $ by { rw [xn_succ_succ a1, xn_succ_succ b1], exact (h.mul_left _ ).mul (xy_modeq_of_modeq (n+1)).left }, (xy_modeq_of_modeq n).right.add_right_cancel $ by { rw [yn_succ_succ a1, yn_succ_succ b1], exact (h.mul_left _ ).mul (xy_modeq_of_modeq (n+1)).right }⟩ theorem matiyasevic {a k x y} : (∃ a1 : 1 < a, xn a1 k = x ∧ yn a1 k = y) ↔ 1 < a ∧ k ≤ y ∧ (x = 1 ∧ y = 0 ∨ ∃ (u v s t b : ℕ), x * x - (a * a - 1) * y * y = 1 ∧ u * u - (a * a - 1) * v * v = 1 ∧ s * s - (b * b - 1) * t * t = 1 ∧ 1 < b ∧ b ≡ 1 [MOD 4 * y] ∧ b ≡ a [MOD u] ∧ 0 < v ∧ y * y ∣ v ∧ s ≡ x [MOD u] ∧ t ≡ k [MOD 4 * y]) := ⟨λ⟨a1, hx, hy⟩, by rw [← hx, ← hy]; refine ⟨a1, (nat.eq_zero_or_pos k).elim (λk0, by rw k0; exact ⟨le_rfl, or.inl ⟨rfl, rfl⟩⟩) (λkpos, _)⟩; exact let x := xn a1 k, y := yn a1 k, m := 2 * (k * y), u := xn a1 m, v := yn a1 m in have ky : k ≤ y, from yn_ge_n a1 k, have yv : y * y ∣ v, from (ysq_dvd_yy a1 k).trans $ (y_dvd_iff _ _ _).2 $ dvd_mul_left _ _, have uco : nat.coprime u (4 * y), from have 2 ∣ v, from modeq_zero_iff_dvd.1 $ (yn_modeq_two _ _).trans (dvd_mul_right _ _).modeq_zero_nat, have nat.coprime u 2, from (xy_coprime a1 m).coprime_dvd_right this, (this.mul_right this).mul_right $ (xy_coprime _ _).coprime_dvd_right (dvd_of_mul_left_dvd yv), let ⟨b, ba, bm1⟩ := chinese_remainder uco a 1 in have m1 : 1 < m, from have 0 < k * y, from mul_pos kpos (y_increasing a1 kpos), nat.mul_le_mul_left 2 this, have vp : 0 < v, from y_increasing a1 (lt_trans zero_lt_one m1), have b1 : 1 < b, from have xn a1 1 < u, from x_increasing a1 m1, have a < u, by simp at this; exact this, lt_of_lt_of_le a1 $ by delta modeq at ba; rw nat.mod_eq_of_lt this at ba; rw ← ba; apply nat.mod_le, let s := xn b1 k, t := yn b1 k in have sx : s ≡ x [MOD u], from (xy_modeq_of_modeq b1 a1 ba k).left, have tk : t ≡ k [MOD 4 * y], from have 4 * y ∣ b - 1, from int.coe_nat_dvd.1 $ by rw int.coe_nat_sub (le_of_lt b1); exact bm1.symm.dvd, (yn_modeq_a_sub_one _ _).modeq_of_dvd this, ⟨ky, or.inr ⟨u, v, s, t, b, pell_eq _ _, pell_eq _ _, pell_eq _ _, b1, bm1, ba, vp, yv, sx, tk⟩⟩, λ⟨a1, ky, o⟩, ⟨a1, match o with | or.inl ⟨x1, y0⟩ := by rw y0 at ky; rw [nat.eq_zero_of_le_zero ky, x1, y0]; exact ⟨rfl, rfl⟩ | or.inr ⟨u, v, s, t, b, xy, uv, st, b1, rem⟩ := match x, y, eq_pell a1 xy, u, v, eq_pell a1 uv, s, t, eq_pell b1 st, rem, ky with | ._, ._, ⟨i, rfl, rfl⟩, ._, ._, ⟨n, rfl, rfl⟩, ._, ._, ⟨j, rfl, rfl⟩, ⟨(bm1 : b ≡ 1 [MOD 4 * yn a1 i]), (ba : b ≡ a [MOD xn a1 n]), (vp : 0 < yn a1 n), (yv : yn a1 i * yn a1 i ∣ yn a1 n), (sx : xn b1 j ≡ xn a1 i [MOD xn a1 n]), (tk : yn b1 j ≡ k [MOD 4 * yn a1 i])⟩, (ky : k ≤ yn a1 i) := (nat.eq_zero_or_pos i).elim (λi0, by simp [i0] at ky; rw [i0, ky]; exact ⟨rfl, rfl⟩) $ λipos, suffices i = k, by rw this; exact ⟨rfl, rfl⟩, by clear _x o rem xy uv st _match _match _fun_match; exact have iln : i ≤ n, from le_of_not_gt $ λhin, not_lt_of_ge (nat.le_of_dvd vp (dvd_of_mul_left_dvd yv)) (y_increasing a1 hin), have yd : 4 * yn a1 i ∣ 4 * n, from mul_dvd_mul_left _ $ dvd_of_ysq_dvd a1 yv, have jk : j ≡ k [MOD 4 * yn a1 i], from have 4 * yn a1 i ∣ b - 1, from int.coe_nat_dvd.1 $ by rw int.coe_nat_sub (le_of_lt b1); exact bm1.symm.dvd, ((yn_modeq_a_sub_one b1 _).modeq_of_dvd this).symm.trans tk, have ki : k + i < 4 * yn a1 i, from lt_of_le_of_lt (add_le_add ky (yn_ge_n a1 i)) $ by rw ← two_mul; exact nat.mul_lt_mul_of_pos_right dec_trivial (y_increasing a1 ipos), have ji : j ≡ i [MOD 4 * n], from have xn a1 j ≡ xn a1 i [MOD xn a1 n], from (xy_modeq_of_modeq b1 a1 ba j).left.symm.trans sx, (modeq_of_xn_modeq a1 ipos iln this).resolve_right $ λ (ji : j + i ≡ 0 [MOD 4 * n]), not_le_of_gt ki $ nat.le_of_dvd (lt_of_lt_of_le ipos $ nat.le_add_left _ _) $ modeq_zero_iff_dvd.1 $ (jk.symm.add_right i).trans $ ji.modeq_of_dvd yd, by have : i % (4 * yn a1 i) = k % (4 * yn a1 i) := (ji.modeq_of_dvd yd).symm.trans jk; rwa [nat.mod_eq_of_lt (lt_of_le_of_lt (nat.le_add_left _ _) ki), nat.mod_eq_of_lt (lt_of_le_of_lt (nat.le_add_right _ _) ki)] at this end end⟩⟩ lemma eq_pow_of_pell_lem {a y k} (a1 : 1 < a) (ypos : 0 < y) : 0 < k → y^k < a → (↑(y^k) : ℤ) < 2*a*y - y*y - 1 := have y < a → a + (y*y + 1) ≤ 2*a*y, begin intro ya, induction y with y IH, exact absurd ypos (lt_irrefl _), cases nat.eq_zero_or_pos y with y0 ypos, { rw y0, simpa [two_mul], }, { rw [nat.mul_succ, nat.mul_succ, nat.succ_mul y], have : y + nat.succ y ≤ 2 * a, { change y + y < 2 * a, rw ← two_mul, exact mul_lt_mul_of_pos_left (nat.lt_of_succ_lt ya) dec_trivial }, have := add_le_add (IH ypos (nat.lt_of_succ_lt ya)) this, convert this using 1, ring } end, λk0 yak, lt_of_lt_of_le (int.coe_nat_lt_coe_nat_of_lt yak) $ by rw sub_sub; apply le_sub_right_of_add_le; apply int.coe_nat_le_coe_nat_of_le; have y1 := nat.pow_le_pow_of_le_right ypos k0; simp at y1; exact this (lt_of_le_of_lt y1 yak) theorem eq_pow_of_pell {m n k} : (n^k = m ↔ k = 0 ∧ m = 1 ∨ 0 < k ∧ (n = 0 ∧ m = 0 ∨ 0 < n ∧ ∃ (w a t z : ℕ) (a1 : 1 < a), xn a1 k ≡ yn a1 k * (a - n) + m [MOD t] ∧ 2 * a * n = t + (n * n + 1) ∧ m < t ∧ n ≤ w ∧ k ≤ w ∧ a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)) := ⟨λe, by rw ← e; refine (nat.eq_zero_or_pos k).elim (λk0, by rw k0; exact or.inl ⟨rfl, rfl⟩) (λkpos, or.inr ⟨kpos, _⟩); refine (nat.eq_zero_or_pos n).elim (λn0, by rw [n0, zero_pow kpos]; exact or.inl ⟨rfl, rfl⟩) (λnpos, or.inr ⟨npos, _⟩); exact let w := _root_.max n k in have nw : n ≤ w, from le_max_left _ _, have kw : k ≤ w, from le_max_right _ _, have wpos : 0 < w, from lt_of_lt_of_le npos nw, have w1 : 1 < w + 1, from nat.succ_lt_succ wpos, let a := xn w1 w in have a1 : 1 < a, from x_increasing w1 wpos, let x := xn a1 k, y := yn a1 k in let ⟨z, ze⟩ := show w ∣ yn w1 w, from modeq_zero_iff_dvd.1 $ (yn_modeq_a_sub_one w1 w).trans dvd_rfl.modeq_zero_nat in have nt : (↑(n^k) : ℤ) < 2 * a * n - n * n - 1, from eq_pow_of_pell_lem a1 npos kpos $ calc n^k ≤ n^w : nat.pow_le_pow_of_le_right npos kw ... < (w + 1)^w : nat.pow_lt_pow_of_lt_left (nat.lt_succ_of_le nw) wpos ... ≤ a : xn_ge_a_pow w1 w, let ⟨t, te⟩ := int.eq_coe_of_zero_le $ le_trans (int.coe_zero_le _) nt.le in have na : n ≤ a, from nw.trans $ le_of_lt $ n_lt_xn w1 w, have tm : x ≡ y * (a - n) + n^k [MOD t], begin apply modeq_of_dvd, rw [int.coe_nat_add, int.coe_nat_mul, int.coe_nat_sub na, ← te], exact x_sub_y_dvd_pow a1 n k end, have ta : 2 * a * n = t + (n * n + 1), from int.coe_nat_inj $ by rw [int.coe_nat_add, ← te, sub_sub]; repeat {rw int.coe_nat_add <|> rw int.coe_nat_mul}; rw [int.coe_nat_one, sub_add_cancel]; refl, have mt : n^k < t, from int.lt_of_coe_nat_lt_coe_nat $ by rw ← te; exact nt, have zp : a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1, by rw ← ze; exact pell_eq w1 w, ⟨w, a, t, z, a1, tm, ta, mt, nw, kw, zp⟩, λo, match o with | or.inl ⟨k0, m1⟩ := by rw [k0, m1]; refl | or.inr ⟨kpos, or.inl ⟨n0, m0⟩⟩ := by rw [n0, m0, zero_pow kpos] | or.inr ⟨kpos, or.inr ⟨npos, w, a, t, z, (a1 : 1 < a), (tm : xn a1 k ≡ yn a1 k * (a - n) + m [MOD t]), (ta : 2 * a * n = t + (n * n + 1)), (mt : m < t), (nw : n ≤ w), (kw : k ≤ w), (zp : a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)⟩⟩ := have wpos : 0 < w, from lt_of_lt_of_le npos nw, have w1 : 1 < w + 1, from nat.succ_lt_succ wpos, let ⟨j, xj, yj⟩ := eq_pell w1 zp in by clear _match o _let_match; exact have jpos : 0 < j, from (nat.eq_zero_or_pos j).resolve_left $ λj0, have a1 : a = 1, by rw j0 at xj; exact xj, have 2 * n = t + (n * n + 1), by rw a1 at ta; exact ta, have n1 : n = 1, from have n * n < n * 2, by rw [mul_comm n 2, this]; apply nat.le_add_left, have n ≤ 1, from nat.le_of_lt_succ $ lt_of_mul_lt_mul_left this (nat.zero_le _), le_antisymm this npos, by rw n1 at this; rw ← @nat.add_right_cancel 0 2 t this at mt; exact nat.not_lt_zero _ mt, have wj : w ≤ j, from nat.le_of_dvd jpos $ modeq_zero_iff_dvd.1 $ (yn_modeq_a_sub_one w1 j).symm.trans $ modeq_zero_iff_dvd.2 ⟨z, yj.symm⟩, have nt : (↑(n^k) : ℤ) < 2 * a * n - n * n - 1, from eq_pow_of_pell_lem a1 npos kpos $ calc n^k ≤ n^j : nat.pow_le_pow_of_le_right npos (le_trans kw wj) ... < (w + 1)^j : nat.pow_lt_pow_of_lt_left (nat.lt_succ_of_le nw) jpos ... ≤ xn w1 j : xn_ge_a_pow w1 j ... = a : xj.symm, have na : n ≤ a, by rw xj; exact le_trans (le_trans nw wj) (le_of_lt $ n_lt_xn _ _), have te : (t : ℤ) = 2 * ↑a * ↑n - ↑n * ↑n - 1, by rw sub_sub; apply eq_sub_of_add_eq; apply (int.coe_nat_eq_coe_nat_iff _ _).2; exact ta.symm, have xn a1 k ≡ yn a1 k * (a - n) + n^k [MOD t], by have := x_sub_y_dvd_pow a1 n k; rw [← te, ← int.coe_nat_sub na] at this; exact modeq_of_dvd this, have n^k % t = m % t, from (this.symm.trans tm).add_left_cancel' _, by rw ← te at nt; rwa [nat.mod_eq_of_lt (int.lt_of_coe_nat_lt_coe_nat nt), nat.mod_eq_of_lt mt] at this end⟩ end pell
5059bd0d3e63d1b2380d6f46b5670c76ddf671a7
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/tests/lean/pp_char_bug.lean
ba1b002f3fccb476de6cd1d70fccfc25b34d71ef
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
418
lean
#check (fin.mk 2 dec_trivial : fin 5) #check (fin.mk 1 dec_trivial : fin 3) #check #"a" #check to_string #"a" #eval to_string #"a" #eval #"a" #eval char.of_nat 1 #eval char.of_nat 1 #eval char.of_nat 20 #check char.of_nat 1 #check char.of_nat 20 #check char.of_nat 15 #check char.of_nat 16 #eval char.of_nat 15 #eval char.of_nat 16 example : char.of_nat 1 = #"\x01" := rfl example : char.of_nat 20 = #"\x14" := rfl
b4f3bc4ab5d7ac2bf5da40d684052da17890595d
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Compiler/LCNF/JoinPoints.lean
604b30602ec6f6d3f08be817601d6138e1519715
[ "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
18,705
lean
/- Copyright (c) 2022 Henrik Böving. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Henrik Böving -/ import Lean.Compiler.LCNF.CompilerM import Lean.Compiler.LCNF.PassManager import Lean.Compiler.LCNF.PullFunDecls namespace Lean.Compiler.LCNF -- TODO: These can be used in a much more general context partial def mapFVarM [Monad m] (f : FVarId → m FVarId) (e : Expr) : m Expr := do match e with | .proj typ idx struct => return .proj typ idx (←mapFVarM f struct) | .app fn arg => return .app (←mapFVarM f fn) (←mapFVarM f arg) | .fvar fvarId => return .fvar (←f fvarId) | .lam arg ty body bi => return .lam arg (←mapFVarM f ty) (←mapFVarM f body) bi | .forallE arg ty body bi => return .forallE arg (←mapFVarM f ty) (←mapFVarM f body) bi | .letE var ty value body nonDep => return .letE var (←mapFVarM f ty) (←mapFVarM f value) (←mapFVarM f body) nonDep | .bvar .. | .sort .. => return e | .mdata .. | .const .. | .lit .. => return e | .mvar .. => unreachable! partial def forFVarM [Monad m] (f : FVarId → m Unit) (e : Expr) : m Unit := do match e with | .proj _ _ struct => forFVarM f struct | .app fn arg => forFVarM f fn forFVarM f arg | .fvar fvarId => f fvarId | .lam _ ty body .. => forFVarM f ty forFVarM f body | .forallE _ ty body .. => forFVarM f ty forFVarM f body | .letE _ ty value body .. => forFVarM f ty forFVarM f value forFVarM f body | .bvar .. | .sort .. => return | .mdata .. | .const .. | .lit .. => return | .mvar .. => unreachable! /-- A general abstraction for the idea of a scope in the compiler. -/ abbrev ScopeM := StateRefT FVarIdSet CompilerM namespace ScopeM def getScope : ScopeM FVarIdSet := get def setScope (newScope : FVarIdSet) : ScopeM Unit := set newScope def clearScope : ScopeM Unit := setScope {} /-- Execute `x` but recover the previous scope after doing so. -/ def withBackTrackingScope [MonadLiftT ScopeM m] [Monad m] [MonadFinally m] (x : m α) : m α := do let scope ← getScope try x finally setScope scope /-- Clear the current scope for the monadic action `x`, afterwards continuing with the old one. -/ def withNewScope [MonadLiftT ScopeM m] [Monad m] [MonadFinally m] (x : m α) : m α := do withBackTrackingScope do clearScope x /-- Check whether `fvarId` is in the current scope, that is, was declared within the current `fun` declaration that is being processed. -/ def isInScope (fvarId : FVarId) : ScopeM Bool := do let scope ← getScope return scope.contains fvarId /-- Add a new `FVarId` to the current scope. -/ def addToScope (fvarId : FVarId) : ScopeM Unit := modify fun scope => scope.insert fvarId end ScopeM namespace JoinPointFinder open ScopeM /-- Info about a join point candidate (a `fun` declaration) during the find phase. -/ structure CandidateInfo where /-- The arity of the candidate -/ arity : Nat /-- The set of candidates that rely on this candidate to be a join point. For a more detailed explanation see the documentation of `find` -/ associated : HashSet FVarId deriving Inhabited /-- The state for the join point candidate finder. -/ structure FindState where /-- All current join point candidates accessible by their `FVarId`. -/ candidates : HashMap FVarId CandidateInfo := .empty /-- The `FVarId`s of all `fun` declarations that were declared within the current `fun`. -/ scope : HashSet FVarId := .empty abbrev ReplaceCtx := HashMap FVarId Name abbrev FindM := ReaderT (Option FVarId) StateRefT FindState ScopeM abbrev ReplaceM := ReaderT ReplaceCtx CompilerM /-- Attempt to find a join point candidate by its `FVarId`. -/ private def findCandidate? (fvarId : FVarId) : FindM (Option CandidateInfo) := do return (← get).candidates.find? fvarId /-- Erase a join point candidate as well as all the ones that depend on it by its `FVarId`, no error is thrown is the candidate does not exist. -/ private partial def eraseCandidate (fvarId : FVarId) : FindM Unit := do if let some info ← findCandidate? fvarId then modify (fun state => { state with candidates := state.candidates.erase fvarId }) info.associated.forM eraseCandidate /-- Combinator for modifying the candidates in `FindM`. -/ private def modifyCandidates (f : HashMap FVarId CandidateInfo → HashMap FVarId CandidateInfo) : FindM Unit := modify (fun state => {state with candidates := f state.candidates }) /-- Remove all join point candidates contained in `e`. -/ private partial def removeCandidatesContainedIn (e : Expr) : FindM Unit := do forFVarM eraseCandidate e /-- Add a new join point candidate to the state. -/ private def addCandidate (fvarId : FVarId) (arity : Nat) : FindM Unit := do let cinfo := { arity, associated := .empty } modifyCandidates (fun cs => cs.insert fvarId cinfo ) /-- Add a new join point dependency from `src` to `dst`. -/ private def addDependency (src : FVarId) (target : FVarId) : FindM Unit := do if let some targetInfo ← findCandidate? target then modifyCandidates (fun cs => cs.insert target { targetInfo with associated := targetInfo.associated.insert src }) else eraseCandidate src /-- Find all `fun` declarations that qualify as a join point, that is: - are always fully applied - are always called in tail position Where a `fun` `f` is in tail position iff it is called as follows: ``` let res := f arg res ``` The majority (if not all) tail calls will be brought into this form by the simplifier pass. Furthermore a `fun` disqualifies as a join point if turning it into a join point would turn a call to it into an out of scope join point. This can happen if we have something like: ``` def test (b : Bool) (x y : Nat) : Nat := fun myjp x => Nat.add x (Nat.add x x) fun f y => let x := Nat.add y y myjp x fun f y => let x := Nat.mul y y myjp x cases b (f x) (g y) ``` `f` and `g` can be detected as a join point right away, however `myjp` can only ever be detected as a join point after we have established this. This is because otherwise the calls to `myjp` in `f` and `g` would produce out of scope join point jumps. -/ partial def find (decl : Decl) : CompilerM FindState := do let (_, candidates) ← go decl.value |>.run none |>.run {} |>.run' {} return candidates where go : Code → FindM Unit | .let decl k => do match k, decl.value, decl.value.getAppFn with | .return valId, .app .., .fvar fvarId => decl.value.getAppArgs.forM removeCandidatesContainedIn if let some candidateInfo ← findCandidate? fvarId then -- Erase candidate that are not fully applied or applied outside of tail position if valId != decl.fvarId || decl.value.getAppNumArgs != candidateInfo.arity then eraseCandidate fvarId -- Out of scope join point candidate handling else if let some upperCandidate ← read then if !(←isInScope fvarId) then addDependency fvarId upperCandidate else eraseCandidate fvarId | _, _, _ => removeCandidatesContainedIn decl.value go k | .fun decl k => do withReader (fun _ => some decl.fvarId) do withNewScope do go decl.value addCandidate decl.fvarId decl.getArity addToScope decl.fvarId go k | .jp decl k => do go decl.value go k | .jmp _ args => args.forM removeCandidatesContainedIn | .return val => eraseCandidate val | .cases c => do eraseCandidate c.discr c.alts.forM (·.forCodeM go) | .unreach .. => return () /-- Replace all join point candidate `fun` declarations with `jp` ones and all calls to them with `jmp`s. -/ partial def replace (decl : Decl) (state : FindState) : CompilerM Decl := do let mapper := fun acc cname _ => do return acc.insert cname (←mkFreshJpName) let replaceCtx : ReplaceCtx ← state.candidates.foldM (init := .empty) mapper let newValue ← go decl.value |>.run replaceCtx return { decl with value := newValue } where go (code : Code) : ReplaceM Code := do match code with | .let decl k => match k, decl.value, decl.value.getAppFn with | .return valId, .app .., (.fvar fvarId) => if valId == decl.fvarId then if (← read).contains fvarId then eraseLetDecl decl return .jmp fvarId decl.value.getAppArgs else return code else return code | _, _, _ => return Code.updateLet! code decl (←go k) | .fun decl k => if let some replacement := (← read).find? decl.fvarId then let newDecl := { decl with binderName := replacement, value := (←go decl.value) } modifyLCtx fun lctx => lctx.addFunDecl newDecl return .jp newDecl (←go k) else let newDecl ← decl.updateValue (←go decl.value) return Code.updateFun! code newDecl (←go k) | .jp decl k => let newDecl ← decl.updateValue (←go decl.value) return Code.updateFun! code newDecl (←go k) | .cases cs => return Code.updateCases! code cs.resultType cs.discr (←cs.alts.mapM (·.mapCodeM go)) | .jmp .. | .return .. | .unreach .. => return code end JoinPointFinder namespace JoinPointContextExtender open ScopeM /-- The context managed by `ExtendM`. -/ structure ExtendContext where /-- The `FVarId` of the current join point if we are currently inside one. -/ currentJp? : Option FVarId := none /-- The list of valid candidates for extending the context. This will be all `let` and `fun` declarations as well as all `jp` parameters up until the last `fun` declaration in the tree. -/ candidates : FVarIdSet := {} /-- The state managed by `ExtendM`. -/ structure ExtendState where /-- A map from join point `FVarId`s to a respective map from free variables to `Param`s. The free variables in this map are the once that the context of said join point will be extended by by passing in the respective parameter. -/ fvarMap : HashMap FVarId (HashMap FVarId Param) := {} /-- The monad for the `extendJoinPointContext` pass. -/ abbrev ExtendM := ReaderT ExtendContext StateRefT ExtendState ScopeM /-- Replace a free variable if necessary, that is: - It is in the list of candidates - We are currently within a join point (if we are within a function there cannot be a need to replace them since we dont extend their context) - Said join point actually has a replacement parameter registered. otherwise just return `fvar`. -/ def replaceFVar (fvar : FVarId) : ExtendM FVarId := do if (←read).candidates.contains fvar then if let some currentJp := (←read).currentJp? then if let some replacement := (←get).fvarMap.find! currentJp |>.find? fvar then return replacement.fvarId return fvar /-- Add a new candidate to the current scope + to the list of candidates if we are currently within a join point. Then execute `x`. -/ def withNewCandidate (fvar : FVarId) (x : ExtendM α) : ExtendM α := do addToScope fvar if (←read).currentJp?.isSome then withReader (fun ctx => { ctx with candidates := ctx.candidates.insert fvar }) do x else x /-- Same as `withNewCandidate` but with multiple `FVarId`s. -/ def withNewCandidates (fvars : Array FVarId) (x : ExtendM α) : ExtendM α := do if (←read).currentJp?.isSome then let candidates := (←read).candidates let folder := (fun acc val => do addToScope val; return acc.insert val) let newCandidates ← fvars.foldlM (init := candidates) folder withReader (fun ctx => { ctx with candidates := newCandidates }) do x else x /-- Extend the context of the current join point (if we are within one) by `fvar` if necessary. This is necessary if: - `fvar` is not in scope (that is, was declared outside of the current jp) - we have not already extended the context by `fvar` - the list of candidates contains `fvar`. This is because if we have something like: ``` let x := .. fun f a => jp j b => let y := x y ``` There is no point in extending the context of `j` by `x` because we cannot lift a join point outside of a local function declaration. -/ def extendByIfNecessary (fvar : FVarId) : ExtendM Unit := do if let some currentJp := (←read).currentJp? then let mut translator := (←get).fvarMap.find! currentJp let candidates := (←read).candidates if !(←isInScope fvar) && !translator.contains fvar && candidates.contains fvar then let typ ← getType fvar let newParam ← mkAuxParam typ translator := translator.insert fvar newParam modify fun s => { s with fvarMap := s.fvarMap.insert currentJp translator } /-- Merge the extended context of two join points if necessary. That is if we have a structure such as: ``` jp j.1 ... => jp j.2 .. => ... ... ``` And we are just done visiting `j.2` we want to extend the context of `j.1` by all free variables that the context of `j.2` was extended by as well because we need to drag these variables through at the call sites of `j.2` in `j.1`. -/ def mergeJpContextIfNecessary (jp : FVarId) : ExtendM Unit := do if (←read).currentJp?.isSome then let additionalArgs := (←get).fvarMap.find! jp |>.toArray for (fvar, _) in additionalArgs do extendByIfNecessary fvar /-- We call this whenever we enter a new local function. It clears both the current join point and the list of candidates since we cant lift join points outside of functions as explained in `mergeJpContextIfNecessary`. -/ def withNewFunScope (decl : FunDecl) (x : ExtendM α): ExtendM α := do withReader (fun ctx => { ctx with currentJp? := none, candidates := {} }) do withNewScope do x /-- We call this whenever we enter a new join point. It will set the current join point and extend the list of candidates by all of the parameters of the join point. This is so in the case of nested join points that refer to parameters of the current one we extend the context of the nested join points by said parameters. -/ def withNewJpScope (decl : FunDecl) (x : ExtendM α): ExtendM α := do withReader (fun ctx => { ctx with currentJp? := some decl.fvarId }) do modify fun s => { s with fvarMap := s.fvarMap.insert decl.fvarId {} } withNewScope do withNewCandidates (decl.params.map (·.fvarId)) do x /-- We call this whenever we visit a new arm of a cases statement. It will back up the current scope (since we are doing a case split and want to continue with other arms afterwards) and add all of the parameters of the match arm to the list of candidates. -/ def withNewAltScope (alt : Alt) (x : ExtendM α) : ExtendM α := do withBackTrackingScope do withNewCandidates (alt.getParams.map (·.fvarId)) do x /-- Use all of the above functions to find free variables declared outside of join points that said join points can be reasonaly extended by. Reasonable meaning that in case the current join point is nested within a function declaration we will not extend it by free variables declared before the function declaration because we cannot lift join points outside of function declarations. All of this is done to eliminate dependencies of join points onto their position within the code so we can pull them out as far as possible, hopefully enabling new inlining possibilities in the next simplifier run. -/ partial def extend (decl : Decl) : CompilerM Decl := do let newValue ← go decl.value |>.run {} |>.run' {} |>.run' {} let decl := { decl with value := newValue } decl.pullFunDecls where goExpr (e : Expr) : ExtendM Expr := let visitor := fun fvar => do extendByIfNecessary fvar replaceFVar fvar mapFVarM visitor e go (code : Code) : ExtendM Code := do match code with | .let decl k => let decl ← decl.updateValue (←goExpr decl.value) withNewCandidate decl.fvarId do return Code.updateLet! code decl (←go k) | .jp decl k => let decl ← withNewJpScope decl do let value ← go decl.value let additionalParams := (←get).fvarMap.find! decl.fvarId |>.toArray |>.map Prod.snd let newType := additionalParams.foldr (init := decl.type) (fun val acc => .forallE val.binderName val.type acc .default) decl.update newType (additionalParams ++ decl.params) value mergeJpContextIfNecessary decl.fvarId withNewCandidate decl.fvarId do return Code.updateFun! code decl (←go k) | .fun decl k => let decl ← withNewFunScope decl do decl.updateValue (←go decl.value) withNewCandidate decl.fvarId do return Code.updateFun! code decl (←go k) | .cases cs => extendByIfNecessary cs.discr let discr ← replaceFVar cs.discr let visitor := fun alt => do withNewAltScope alt do alt.mapCodeM go let alts ← cs.alts.mapM visitor return Code.updateCases! code cs.resultType discr alts | .jmp fn args => let mut newArgs ← args.mapM goExpr let additionalArgs := (←get).fvarMap.find! fn |>.toArray |>.map Prod.fst if let some currentJp := (←read).currentJp? then let translator := (←get).fvarMap.find! currentJp let f := fun arg => if let some translated := translator.find? arg then .fvar translated.fvarId else .fvar arg newArgs := (additionalArgs.map f) ++ newArgs else newArgs := (additionalArgs.map .fvar) ++ newArgs return Code.updateJmp! code fn newArgs | .return var => extendByIfNecessary var return Code.updateReturn! code (←replaceFVar var) | .unreach .. => return code end JoinPointContextExtender /-- Find all `fun` declarations in `decl` that qualify as join points then replace their definitions and call sites with `jp`/`jmp`. -/ def Decl.findJoinPoints (decl : Decl) : CompilerM Decl := do let findResult ← JoinPointFinder.find decl trace[Compiler.findJoinPoints] s!"Found: {findResult.candidates.size} jp candidates" JoinPointFinder.replace decl findResult def findJoinPoints : Pass := .mkPerDeclaration `findJoinPoints Decl.findJoinPoints .base builtin_initialize registerTraceClass `Compiler.findJoinPoints (inherited := true) def Decl.extendJoinPointContext (decl : Decl) : CompilerM Decl := do JoinPointContextExtender.extend decl def extendJoinPointContext : Pass := .mkPerDeclaration `extendJoinPointContext Decl.extendJoinPointContext .base builtin_initialize registerTraceClass `Compiler.extendJoinPointContext (inherited := true) end Lean.Compiler.LCNF
bbd805e90ac7dcf58655fac9db7b01fb971764a8
1437b3495ef9020d5413178aa33c0a625f15f15f
/data/equiv/basic.lean
58c866c1dd2252e9c7d07a853710eb4de472ae8e
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,923
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro In the standard library we cannot assume the univalence axiom. We say two types are equivalent if they are isomorphic. Two equivalent types have the same cardinality. -/ import logic.function data.set.basic data.bool open function universes u v w variables {α : Sort u} {β : Sort v} {γ : Sort w} /-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/ structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) namespace equiv /-- `perm α` is the type of bijections from `α` to itself. -/ @[reducible] def perm (α : Sort*) := equiv α α infix ` ≃ `:50 := equiv instance : has_coe_to_fun (α ≃ β) := ⟨_, to_fun⟩ @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : equiv α β}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h := have f₁ = f₂, from h, have g₁ = g₂, from funext $ assume x, have f₁ (g₁ x) = f₂ (g₂ x), from (r₁ x).trans (r₂ x).symm, have f₁ (g₁ x) = f₁ (g₂ x), by subst f₂; exact this, show g₁ x = g₂ x, from injective_of_left_inverse l₁ this, by simp * @[extensionality] lemma ext (f g : equiv α β) (H : ∀ x, f x = g x) : f = g := eq_of_to_fun_eq (funext H) @[extensionality] lemma perm.ext (σ τ : equiv.perm α) (H : ∀ x, σ x = τ x) : σ = τ := equiv.ext _ _ H @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ e₂.inv_fun, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ protected theorem bijective : ∀ f : α ≃ β, bijective f | ⟨f, g, h₁, h₂⟩ := ⟨injective_of_left_inverse h₁, surjective_of_has_right_inverse ⟨_, h₂⟩⟩ protected theorem subsingleton (e : α ≃ β) : ∀ [subsingleton β], subsingleton α | ⟨H⟩ := ⟨λ a b, e.bijective.1 (H _ _)⟩ protected def decidable_eq (e : α ≃ β) [H : decidable_eq β] : decidable_eq α | a b := decidable_of_iff _ e.bijective.1.eq_iff protected def cast {α β : Sort*} (h : α = β) : α ≃ β := ⟨cast h, cast h.symm, λ x, by cases h; refl, λ x, by cases h; refl⟩ @[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g := rfl @[simp] theorem refl_apply (x : α) : equiv.refl α x = x := rfl @[simp] theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_inverse_apply : ∀ (e : α ≃ β) (x : β), e (e.symm x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw r₁ @[simp] theorem inverse_apply_apply : ∀ (e : α ≃ β) (x : α), e.symm (e x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw l₁ @[simp] lemma inverse_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) : (f.trans g).symm a = f.symm (g.symm a) := rfl @[simp] theorem apply_eq_iff_eq : ∀ (f : α ≃ β) (x y : α), f x = f y ↔ x = y | ⟨f₁, g₁, l₁, r₁⟩ x y := (injective_of_left_inverse l₁).eq_iff @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x := (eq_comm.trans e.symm_apply_eq).trans eq_comm @[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by cases e; refl @[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by cases e; refl @[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by cases e; refl @[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext _ _ (by simp) @[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext _ _ (by simp) lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) : (ab.trans bc).trans cd = ab.trans (bc.trans cd) := equiv.ext _ _ $ assume a, rfl theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) := ⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, ⟩ def perm_congr {α : Type*} {β : Type*} (e : α ≃ β) : perm α ≃ perm β := equiv_congr e e protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ e '' s ↔ e.symm '' t ⊆ s := by rw [set.image_subset_iff, e.image_eq_preimage] lemma symm_image_image {α β} (f : equiv α β) (s : set α) : f.symm '' (f '' s) = s := by rw [← set.image_comp]; simpa using set.image_id s protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' -s = -(f '' s) := set.image_compl_eq f.bijective /- The group of permutations (self-equivalences) of a type `α` -/ namespace perm instance perm_group {α : Type u} : group (perm α) := begin refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..}; intros; apply equiv.ext; try { apply trans_apply }, apply inverse_apply_apply end @[simp] theorem mul_apply {α : Type u} (f g : perm α) (x) : (f * g) x = f (g x) := equiv.trans_apply _ _ _ @[simp] theorem one_apply {α : Type u} (x) : (1 : perm α) x = x := rfl @[simp] lemma inv_apply_self {α : Type u} (f : perm α) (x) : f⁻¹ (f x) = x := equiv.inverse_apply_apply _ _ @[simp] lemma apply_inv_self {α : Type u} (f : perm α) (x) : f (f⁻¹ x) = x := equiv.apply_inverse_apply _ _ lemma one_def {α : Type u} : (1 : perm α) = equiv.refl α := rfl lemma mul_def {α : Type u} (f g : perm α) : f * g = g.trans f := rfl lemma inv_def {α : Type u} (f : perm α) : f⁻¹ = f.symm := rfl end perm def equiv_empty (h : α → false) : α ≃ empty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_empty : false ≃ empty := equiv_empty _root_.id def equiv_pempty (h : α → false) : α ≃ pempty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_pempty : false ≃ pempty := equiv_pempty _root_.id def empty_equiv_pempty : empty ≃ pempty := equiv_pempty $ empty.rec _ def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} := equiv_pempty pempty.elim def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty := equiv_empty $ assume a, h ⟨a⟩ def pempty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ pempty := equiv_pempty $ assume a, h ⟨a⟩ def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit := ⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩ def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial protected def ulift {α : Type u} : ulift α ≃ α := ⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩ protected def plift : plift α ≃ α := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ @[congr] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ → β₁) ≃ (α₂ → β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ (h : α₁ → β₁) (a : α₂), f₂ (h (g₁ a)), λ (h : α₂ → β₂) (a : α₁), g₂ (h (f₁ a)), λ h, by funext a; dsimp; rw [l₁, l₂], λ h, by funext a; dsimp; rw [r₁, r₂]⟩ def punit_equiv_punit : punit.{v} ≃ punit.{w} := ⟨λ _, punit.star, λ _, punit.star, λ u, by cases u; refl, λ u, by cases u; reflexivity⟩ section @[simp] def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} := ⟨λ f, punit.star, λ u f, punit.star, λ f, by funext x; cases f x; refl, λ u, by cases u; reflexivity⟩ @[simp] def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α := ⟨λ f, f punit.star, λ a u, a, λ f, by funext x; cases x; refl, λ u, rfl⟩ @[simp] def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩ @[simp] def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩ @[simp] def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} := calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _) ... ≃ punit : empty_arrow_equiv_punit _ end @[congr] def prod_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ :β₁ ≃ β₂) : (α₁ × β₁) ≃ (α₂ × β₂) := ⟨λp, (e₁ p.1, e₂ p.2), λp, (e₁.symm p.1, e₂.symm p.2), λ ⟨a, b⟩, show (e₁.symm (e₁ a), e₂.symm (e₂ b)) = (a, b), by rw [inverse_apply_apply, inverse_apply_apply], λ ⟨a, b⟩, show (e₁ (e₁.symm a), e₂ (e₂.symm b)) = (a, b), by rw [apply_inverse_apply, apply_inverse_apply]⟩ @[simp] theorem prod_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) (b : β₁) : prod_congr e₁ e₂ (a, b) = (e₁ a, e₂ b) := rfl @[simp] def prod_comm (α β : Sort*) : (α × β) ≃ (β × α) := ⟨λ p, (p.2, p.1), λ p, (p.2, p.1), λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ @[simp] def prod_assoc (α β γ : Sort*) : ((α × β) × γ) ≃ (α × (β × γ)) := ⟨λ p, ⟨p.1.1, ⟨p.1.2, p.2⟩⟩, λp, ⟨⟨p.1, p.2.1⟩, p.2.2⟩, λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩ @[simp] theorem prod_assoc_apply {α β γ : Sort*} (p : (α × β) × γ) : prod_assoc α β γ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl section @[simp] def prod_punit (α : Sort*) : (α × punit.{u+1}) ≃ α := ⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩ @[simp] theorem prod_punit_apply {α : Sort*} (a : α × punit.{u+1}) : prod_punit α a = a.1 := rfl @[simp] def punit_prod (α : Sort*) : (punit.{u+1} × α) ≃ α := calc (punit × α) ≃ (α × punit) : prod_comm _ _ ... ≃ α : prod_punit _ @[simp] theorem punit_prod_apply {α : Sort*} (a : punit.{u+1} × α) : punit_prod α a = a.2 := rfl @[simp] def prod_empty (α : Sort*) : (α × empty) ≃ empty := equiv_empty (λ ⟨_, e⟩, e.rec _) @[simp] def empty_prod (α : Sort*) : (empty × α) ≃ empty := equiv_empty (λ ⟨e, _⟩, e.rec _) @[simp] def prod_pempty (α : Sort*) : (α × pempty) ≃ pempty := equiv_pempty (λ ⟨_, e⟩, e.rec _) @[simp] def pempty_prod (α : Sort*) : (pempty × α) ≃ pempty := equiv_pempty (λ ⟨e, _⟩, e.rec _) end section open sum def psum_equiv_sum (α β : Sort*) : psum α β ≃ (α ⊕ β) := ⟨λ s, psum.cases_on s inl inr, λ s, sum.cases_on s psum.inl psum.inr, λ s, by cases s; refl, λ s, by cases s; refl⟩ def sum_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ ⊕ β₁) ≃ (α₂ ⊕ β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end, λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end, λ s, match s with inl a := congr_arg inl (l₁ a) | inr a := congr_arg inr (l₂ a) end, λ s, match s with inl a := congr_arg inl (r₁ a) | inr a := congr_arg inr (r₂ a) end⟩ @[simp] theorem sum_congr_apply_inl {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) : sum_congr e₁ e₂ (inl a) = inl (e₁ a) := by cases e₁; cases e₂; refl @[simp] theorem sum_congr_apply_inr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (b : β₁) : sum_congr e₁ e₂ (inr b) = inr (e₂ b) := by cases e₁; cases e₂; refl def bool_equiv_punit_sum_punit : bool ≃ (punit.{u+1} ⊕ punit.{v+1}) := ⟨λ b, cond b (inr punit.star) (inl punit.star), λ s, sum.rec_on s (λ_, ff) (λ_, tt), λ b, by cases b; refl, λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), λ b, b, λ p, by simp, λ b, by simp⟩ @[simp] def sum_comm (α β : Sort*) : (α ⊕ β) ≃ (β ⊕ α) := ⟨λ s, match s with inl a := inr a | inr b := inl b end, λ s, match s with inl b := inr b | inr a := inl a end, λ s, by cases s; refl, λ s, by cases s; refl⟩ @[simp] def sum_assoc (α β γ : Sort*) : ((α ⊕ β) ⊕ γ) ≃ (α ⊕ (β ⊕ γ)) := ⟨λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end, λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end, λ s, by rcases s with ⟨_ | _⟩ | _; refl, λ s, by rcases s with _ | _ | _; refl⟩ @[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl @[simp] def sum_empty (α : Sort*) : (α ⊕ empty) ≃ α := ⟨λ s, match s with inl a := a | inr e := empty.rec _ e end, inl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl, λ a, rfl⟩ @[simp] def empty_sum (α : Sort*) : (empty ⊕ α) ≃ α := (sum_comm _ _).trans $ sum_empty _ @[simp] def sum_pempty (α : Sort*) : (α ⊕ pempty) ≃ α := ⟨λ s, match s with inl a := a | inr e := pempty.rec _ e end, inl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl, λ a, rfl⟩ @[simp] def pempty_sum (α : Sort*) : (pempty ⊕ α) ≃ α := (sum_comm _ _).trans $ sum_pempty _ @[simp] def option_equiv_sum_punit (α : Sort*) : option α ≃ (α ⊕ punit.{u+1}) := ⟨λ o, match o with none := inr punit.star | some a := inl a end, λ s, match s with inr _ := none | inl a := some a end, λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ def sum_equiv_sigma_bool (α β : Sort*) : (α ⊕ β) ≃ (Σ b: bool, cond b α β) := ⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end, λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ def equiv_fib {α β : Type*} (f : α → β) : α ≃ Σ y : β, {x // f x = y} := ⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨y, x, rfl⟩, rfl⟩ end section def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) := ⟨λ H a, F a (H a), λ H a, (F a).symm (H a), λ H, funext $ by simp, λ H, funext $ by simp⟩ end section def psigma_equiv_sigma {α} (β : α → Sort*) : psigma β ≃ sigma β := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : sigma β₁ ≃ sigma β₂ := ⟨λ ⟨a, b⟩, ⟨a, F a b⟩, λ ⟨a, b⟩, ⟨a, (F a).symm b⟩, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ inverse_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_inverse_apply (F a) b⟩ def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} : ∀ f : α₁ ≃ α₂, (Σ a:α₁, β (f a)) ≃ (Σ a:α₂, β a) | ⟨f, g, l, r⟩ := ⟨λ ⟨a, b⟩, ⟨f a, b⟩, λ ⟨a, b⟩, ⟨g a, @@eq.rec β b (r a).symm⟩, λ ⟨a, b⟩, match g (f a), l a : ∀ a' (h : a' = a), @sigma.mk _ (β ∘ f) _ (@@eq.rec β b (congr_arg f h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, λ ⟨a, b⟩, match f (g a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ def sigma_equiv_prod (α β : Sort*) : (Σ_:α, β) ≃ (α × β) := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : ∀ a, β₁ a ≃ β) : sigma β₁ ≃ (α × β) := (sigma_congr_right F).trans (sigma_equiv_prod α β) end section def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ ((γ → α) × (γ → β)) := ⟨λ f, (λ c, (f c).1, λ c, (f c).2), λ p c, (p.1 c, p.2 c), λ f, funext $ λ c, prod.mk.eta, λ p, by cases p; refl⟩ def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) := ⟨λ f, λ p, f p.1 p.2, λ f, λ a b, f (a, b), λ f, rfl, λ f, by funext p; cases p; refl⟩ open sum def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ ((α → γ) × (β → γ)) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p s, sum.rec_on s p.1 p.2, λ f, by funext s; cases s; refl, λ p, by cases p; refl⟩ def sum_prod_distrib (α β γ : Sort*) : ((α ⊕ β) × γ) ≃ ((α × γ) ⊕ (β × γ)) := ⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end, λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end, λ p, by rcases p with ⟨_ | _, _⟩; refl, λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩ @[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) : sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) : sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl def prod_sum_distrib (α β γ : Sort*) : (α × (β ⊕ γ)) ≃ ((α × β) ⊕ (α × γ)) := calc (α × (β ⊕ γ)) ≃ ((β ⊕ γ) × α) : prod_comm _ _ ... ≃ ((β × α) ⊕ (γ × α)) : sum_prod_distrib _ _ _ ... ≃ ((α × β) ⊕ (α × γ)) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) : prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) : prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl def bool_prod_equiv_sum (α : Type u) : (bool × α) ≃ (α ⊕ α) := calc (bool × α) ≃ ((unit ⊕ unit) × α) : prod_congr bool_equiv_punit_sum_punit (equiv.refl _) ... ≃ (α × (unit ⊕ unit)) : prod_comm _ _ ... ≃ ((α × unit) ⊕ (α × unit)) : prod_sum_distrib _ _ _ ... ≃ (α ⊕ α) : sum_congr (prod_punit _) (prod_punit _) end section open sum nat def nat_equiv_nat_sum_punit : ℕ ≃ (ℕ ⊕ punit.{u+1}) := ⟨λ n, match n with zero := inr punit.star | succ a := inl a end, λ s, match s with inl n := succ n | inr punit.star := zero end, λ n, begin cases n, repeat { refl } end, λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩ @[simp] def nat_sum_punit_equiv_nat : (ℕ ⊕ punit.{u+1}) ≃ ℕ := nat_equiv_nat_sum_punit.symm def int_equiv_nat_sum_nat : ℤ ≃ (ℕ ⊕ ℕ) := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} end def list_equiv_of_equiv {α β : Type*} : α ≃ β → list α ≃ list β | ⟨f, g, l, r⟩ := by refine ⟨list.map f, list.map g, λ x, _, λ x, _⟩; simp [id_of_left_inverse l, id_of_right_inverse r] def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} := ⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩ def decidable_eq_of_equiv [decidable_eq β] (e : α ≃ β) : decidable_eq α | a₁ a₂ := decidable_of_iff (e a₁ = e a₂) e.bijective.1.eq_iff def inhabited_of_equiv [inhabited β] (e : α ≃ β) : inhabited α := ⟨e.symm (default _)⟩ section open subtype def subtype_equiv_of_subtype {p : α → Prop} : Π (e : α ≃ β), {a : α // p a} ≃ {b : β // p (e.symm b)} | ⟨f, g, l, r⟩ := ⟨subtype.map f $ assume a ha, show p (g (f a)), by rwa [l], subtype.map g $ assume a ha, ha, assume p, by simp [map_comp, l.comp_eq_id]; rw [map_id]; refl, assume p, by simp [map_comp, r.comp_eq_id]; rw [map_id]; refl⟩ def subtype_subtype_equiv_subtype {α : Type u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩, λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by cases ha; exact ha_h⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ /-- aka coimage -/ def equiv_sigma_subtype {α : Type u} {β : Type v} (f : α → β) : α ≃ Σ b, {x : α // f x = b} := ⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨b, x, H⟩, sigma.eq H $ eq.drec_on H $ subtype.eq rfl⟩ def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) : (Πi, π i) ≃ {f : ι → Σi, π i | ∀i, (f i).1 = i } := ⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end, assume f, funext $ assume i, rfl, assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $ eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩ end section local attribute [elab_with_expected_type] quot.lift def quot_equiv_of_quot' {r : α → α → Prop} {s : β → β → Prop} (e : α ≃ β) (h : ∀ a a', r a a' ↔ s (e a) (e a')) : quot r ≃ quot s := ⟨quot.lift (λ a, quot.mk _ (e a)) (λ a a' H, quot.sound ((h a a').mp H)), quot.lift (λ b, quot.mk _ (e.symm b)) (λ b b' H, quot.sound ((h _ _).mpr (by convert H; simp))), quot.ind $ by simp, quot.ind $ by simp⟩ def quot_equiv_of_quot {r : α → α → Prop} (e : α ≃ β) : quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) := quot_equiv_of_quot' e (by simp) end namespace set open set protected def univ (α) : @univ α ≃ α := ⟨subtype.val, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h protected def pempty (α) : (∅ : set α) ≃ pempty := equiv_pempty $ λ ⟨x, h⟩, not_mem_empty x h protected def union' {α} {s t : set α} (p : α → Prop) [decidable_pred p] (hs : ∀ x ∈ s, p x) (ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ (s ⊕ t) := ⟨λ ⟨x, h⟩, if hp : p x then sum.inl ⟨_, h.resolve_right (λ xt, ht _ xt hp)⟩ else sum.inr ⟨_, h.resolve_left (λ xs, hp (hs _ xs))⟩, λ o, match o with | (sum.inl ⟨x, h⟩) := ⟨x, or.inl h⟩ | (sum.inr ⟨x, h⟩) := ⟨x, or.inr h⟩ end, λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, union'._match_2, h]; congr, λ o, by rcases o with ⟨x, h⟩ | ⟨x, h⟩; simp [union'._match_1, union'._match_2, h]; [simp [hs _ h], simp [ht _ h]]⟩ protected def union {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) : (s ∪ t : set α) ≃ (s ⊕ t) := set.union' s (λ _, id) (λ x xt xs, subset_empty_iff.2 H ⟨xs, xt⟩) protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by simp at h; subst x, λ ⟨⟩, rfl⟩ protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ (s ⊕ punit.{u+1}) := by rw ← union_singleton; exact (set.union $ inter_singleton_eq_empty.2 H).trans (sum_congr (equiv.refl _) (set.singleton _)) protected def sum_compl {α} (s : set α) [decidable_pred s] : (s ⊕ (-s : set α)) ≃ α := (set.union (inter_compl_self _)).symm.trans (by rw union_compl_self; exact set.univ _) protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred s] : ((s ∪ t : set α) ⊕ (s ∩ t : set α)) ≃ (s ⊕ t) := calc ((s ∪ t : set α) ⊕ (s ∩ t : set α)) ≃ ((s ∪ t \ s : set α) ⊕ (s ∩ t : set α)) : by rw [union_diff_self] ... ≃ ((s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α)) : sum_congr (set.union (inter_diff_self _ _)) (equiv.refl _) ... ≃ (s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α)) : sum_assoc _ _ _ ... ≃ (s ⊕ (t \ s ∪ s ∩ t : set α)) : sum_congr (equiv.refl _) begin refine (set.union' (∉ s) _ _).symm, exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1] end ... ≃ (s ⊕ t) : by rw (_ : t \ s ∪ s ∩ t = t); rw [union_comm, inter_comm, inter_union_diff] protected def prod {α β} (s : set α) (t : set β) : (s.prod t) ≃ (s × t) := ⟨λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, rfl, λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, rfl⟩ protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := ⟨λ ⟨x, h⟩, ⟨f x, mem_image_of_mem _ h⟩, λ ⟨y, h⟩, ⟨classical.some h, (classical.some_spec h).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ @[simp] theorem image_apply {α β} (f : α → β) (s : set α) (H : injective f) (a h) : set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl protected noncomputable def range {α β} (f : α → β) (H : injective f) : α ≃ range f := (set.univ _).symm.trans $ (set.image f univ H).trans (equiv.cast $ by rw image_univ) @[simp] theorem range_apply {α β} (f : α → β) (H : injective f) (a) : set.range f H a = ⟨f a, set.mem_range_self _⟩ := by dunfold equiv.set.range equiv.set.univ; simp [set_coe_cast, -image_univ, image_univ.symm] end set noncomputable def of_bijective {α β} {f : α → β} (hf : bijective f) : α ≃ β := ⟨f, λ x, classical.some (hf.2 x), λ x, hf.1 (classical.some_spec (hf.2 (f x))), λ x, classical.some_spec (hf.2 x)⟩ @[simp] theorem of_bijective_to_fun {α β} {f : α → β} (hf : bijective f) : (of_bijective hf : α → β) = f := rfl section swap variable [decidable_eq α] open decidable def swap_core (a b r : α) : α := if r = a then b else if r = b then a else r theorem swap_core_self (r a : α) : swap_core a a r = r := by unfold swap_core; split_ifs; cc theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r := by unfold swap_core; split_ifs; cc theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r := by unfold swap_core; split_ifs; cc /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : perm α := ⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩ theorem swap_self (a : α) : swap a a = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := eq_of_to_fun_eq $ funext $ λ r, swap_core_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : α) : swap a b b = a := by by_cases b = a; simp [swap_apply_def, *] theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp [swap_apply_def] {contextual := tt} @[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ x, swap_core_swap_core _ _ _ theorem swap_comp_apply {a b x : α} (π : perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by cases π; refl @[simp] lemma swap_inv {α : Type*} [decidable_eq α] (x y : α) : (swap x y)⁻¹ = swap x y := rfl @[simp] lemma symm_trans_swap_trans [decidable_eq α] [decidable_eq β] (a b : α) (e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext _ _ (λ x, begin have : ∀ a, e.symm x = a ↔ x = e a := λ a, by rw @eq_comm _ (e.symm x); split; intros; simp * at *, simp [swap_apply_def, this], split_ifs; simp end) @[simp] lemma swap_mul_self {α : Type*} [decidable_eq α] (i j : α) : swap i j * swap i j = 1 := equiv.swap_swap i j @[simp] lemma swap_apply_self {α : Type*} [decidable_eq α] (i j a : α) : swap i j (swap i j a) = a := by rw [← perm.mul_apply, swap_mul_self, perm.one_apply] /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b := by dsimp [set_value]; simp [swap_apply_left] end swap end equiv instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq
a4cef51a610c9b11a9f1f98cee779241aba2ec6f
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/compiler/termparsertest1.lean
5a4b29770b780b882f7bcfd0ae760390620ddef1
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
2,598
lean
import Init.Lean.Parser.Term open Lean open Lean.Parser def testParser (input : String) : IO Unit := do env ← mkEmptyEnvironment; stx ← IO.ofExcept $ runParserCategory env `term input "<input>"; IO.println stx def test (is : List String) : IO Unit := is.forM $ fun input => do IO.println input; testParser input def testParserFailure (input : String) : IO Unit := do env ← mkEmptyEnvironment; match runParserCategory env `term input "<input>" with | Except.ok stx => throw (IO.userError ("unexpected success\n" ++ toString stx)) | Except.error msg => IO.println ("failed as expected, error: " ++ msg) def testFailures (is : List String) : IO Unit := is.forM $ fun input => do IO.println input; testParserFailure input def main (xs : List String) : IO Unit := do test [ "Prod.mk", "x.{u, v+1}", "x.{u}", "x", "x.{max u v}", "x.{max u v, 0}", "f 0 1", "f.{u+1} \"foo\" x", "(f x, 0, 1)", "()", "(f x)", "(f x : Type)", "h (f x) (g y)", "if x then f x else g x", "if h : x then f x h else g x h", "have p x y from f x; g this", "suffices h : p x y from f x; g this", "show p x y from f x", "fun x y => f y x", "fun (x y : Nat) => f y x", "fun (x, y) => f y x", "fun z (x, y) => f y x", "fun ⟨x, y⟩ ⟨z, w⟩ => f y x w z", "fun (Prod.mk x y) => f y x", "{ x := 10, y := 20 }", "{ x := 10, y := 20, }", "{ x // p x 10 }", "{ x : Nat // p x 10 }", "{ .. }", "{ Prod . fst := 10, .. }", "a[i]", "f [10, 20]", "g a[x+2]", "g f.a.1.2.bla x.1.a", "x+y*z < 10/3", "id (α := Nat) 10", "(x : a)", "a -> b", "{x : a} -> b", "{a : Type} -> [HasToString a] -> (x : a) -> b", "f ({x : a} -> b)", "f (x : a) -> b", "f ((x : a) -> b)", "(f : (n : Nat) → Vector Nat n) -> Nat", "∀ x y (z : Nat), x > y -> x > y - z", " match x with | some x => true | none => false", " match x with | some y => match y with | some (a, b) => a + b | none => 1 | none => 0 ", "Type u", "Sort v", "Type 1", "f Type 1", "let x := 0; x + 1", "let x : Nat := 0; x + 1", "let f (x : Nat) := x + 1; f 0", "let f {α : Type} (a : α) : α := a; f 10", "let f (x) := x + 1; f 10 + f 20", "let (x, y) := f 10; x + y", "let { fst := x, .. } := f 10; x + x", "let x.y := f 10; x", "let x.1 := f 10; x", "let x[i].y := f 10; x", "let x[i] := f 20; x", "-x + y", "!x", "¬ a ∧ b", " do x ← f a; x : Nat ← f a; g x; let y := g x; (a, b) <- h x y; let (a, b) := (b, a); pure (a + b)", "do { x ← f a; pure $ a + a }", "let f : Nat → Nat → Nat | 0, a => a + 10 | n+1, b => n * b; f 20", "max a b" ]; testFailures [ "f {x : a} -> b", "(x := 20)", "let x 10; x", "let x := y" ]
e78d945ff51d31ba879cfde6dc405f51300f91cf
1437b3495ef9020d5413178aa33c0a625f15f15f
/tactic/basic.lean
b29f201bc4fe3112869942322b47ddd2ce1327ed
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,356
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek -/ import data.dlist.basic category.basic namespace name meta def deinternalize_field : name → name | (name.mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) -- Pops the top `n` prefixes from the given name. meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 -- `name`s can contain numeral pieces, which are not legal names -- when typed/passed directly to the parser. We turn an arbitrary -- name into a legal identifier name. meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p end name namespace name_set meta def filter (s : name_set) (P : name → bool) : name_set := s.fold s (λ a m, if P a then m else m.erase a) meta def mfilter {m} [monad m] (s : name_set) (P : name → m bool) : m name_set := s.fold (pure s) (λ a m, do x ← m, mcond (P a) (pure x) (pure $ x.erase a)) meta def union (s t : name_set) : name_set := s.fold t (λ a t, t.insert a) end name_set namespace expr open tactic attribute [derive has_reflect] binder_info protected meta def to_pos_nat : expr → option ℕ | `(has_one.one _) := some 1 | `(bit0 %%e) := bit0 <$> e.to_pos_nat | `(bit1 %%e) := bit1 <$> e.to_pos_nat | _ := none protected meta def to_nat : expr → option ℕ | `(has_zero.zero _) := some 0 | e := e.to_pos_nat protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] meta def is_meta_var : expr → bool | (mvar _ _ _) := tt | e := ff meta def is_sort : expr → bool | (sort _) := tt | e := ff meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_meta_var then insert e' es else es) meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /- only traverses the direct descendents -/ meta def {u} traverse {m : Type → Type u} [applicative m] {elab elab' : bool} (f : expr elab → m (expr elab')) : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> list.traverse f es meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (e.traverse $ λ e', (get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _) meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff end expr namespace environment meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) meta def is_structure_like (env : environment) (n : name) : option (nat × name) := do guardb (env.is_inductive n), d ← (env.get n).to_option, [intro] ← pure (env.constructors_of n) | none, guard (env.inductive_num_indices n = 0), some (env.inductive_num_params n, intro) meta def is_structure (env : environment) (n : name) : bool := option.is_some $ do (nparams, intro) ← env.is_structure_like n, di ← (env.get intro).to_option, expr.pi x _ _ _ ← nparams.iterate (λ e : option expr, do expr.pi _ _ _ body ← e | none, some body) (some di.type) | none, env.is_projection (n ++ x.deinternalize_field) end environment namespace interaction_monad open result meta def get_result {σ α} (tac : interaction_monad σ α) : interaction_monad σ (interaction_monad.result σ α) | s := match tac s with | r@(success _ s') := success r s' | r@(exception _ _ s') := success r s' end end interaction_monad namespace lean.parser open lean interaction_monad.result meta def of_tactic' {α} (tac : tactic α) : parser α := do r ← of_tactic (interaction_monad.get_result tac), match r with | (success a _) := return a | (exception f pos _) := exception f pos end -- Override the builtin `lean.parser.of_tactic` coe, which is broken. -- (See tests/tactics.lean for a failure case.) @[priority 2000] meta instance has_coe' {α} : has_coe (tactic α) (parser α) := ⟨of_tactic'⟩ meta def emit_command_here (str : string) : lean.parser string := do (_, left) ← with_input command_like str, return left -- Emit a source code string at the location being parsed. meta def emit_code_here : string → lean.parser unit | str := do left ← emit_command_here str, if left.length = 0 then return () else emit_code_here left end lean.parser namespace tactic meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α := mk_app ``id [e] >>= eval_expr α -- `mk_fresh_name` returns identifiers starting with underscores, -- which are not legal when emitted by tactic programs. Turn the -- useful source of random names provided by `mk_fresh_name` into -- names which are usable by tactic programs. -- -- The returned name has four components. meta def mk_user_fresh_name : tactic name := do nm ← mk_fresh_name, return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__ meta def is_simp_lemma : name → tactic bool := succeeds ∘ tactic.has_attribute `simp meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file' e d.to_name then s.insert d.to_name d else s), pure xs meta def simp_lemmas_from_file : tactic name_set := do s ← local_decls, let s := s.map (expr.list_constant ∘ declaration.value), xs ← s.to_list.mmap ((<$>) name_set.of_list ∘ mfilter tactic.is_simp_lemma ∘ name_set.to_list ∘ prod.snd), return $ name_set.filter (xs.foldl name_set.union mk_name_set) (λ x, ¬ s.contains x) meta def file_simp_attribute_decl (attr : name) : tactic unit := do s ← simp_lemmas_from_file, trace format!"run_cmd mk_simp_attr `{attr}", let lmms := format.join $ list.intersperse " " $ s.to_list.map to_fmt, trace format!"local attribute [{attr}] {lmms}" meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) meta def local_def_value (e : expr) : tactic expr := do do (v,_) ← solve_aux `(true) (do (expr.elet n t v _) ← (revert e >> target) | fail format!"{e} is not a local definition", return v), return v meta def check_defn (n : name) (e : pexpr) : tactic unit := do (declaration.defn _ _ _ d _ _) ← get_decl n, e' ← to_expr e, guard (d =ₐ e') <|> trace d >> failed -- meta def compile_eqn (n : name) (univ : list name) (args : list expr) (val : expr) (num : ℕ) : tactic unit := -- do let lhs := (expr.const n $ univ.map level.param).mk_app args, -- stmt ← mk_app `eq [lhs,val], -- let vs := stmt.list_local_const, -- let stmt := stmt.pis vs, -- (_,pr) ← solve_aux stmt (tactic.intros >> reflexivity), -- add_decl $ declaration.thm (n <.> "equations" <.> to_string (format!"_eqn_{num}")) univ stmt (pure pr) meta def to_implicit : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map to_implicit <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least m times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) end instance_cache /-- Reset the instance cache for the main goal. -/ meta def reset_instance_cache : tactic unit := unfreeze_local_instances meta def match_head (e : expr) : expr → tactic unit | e' := unify e e' <|> do `(_ → %%e') ← whnf e', v ← mk_mvar, match_head (e'.instantiate_var v) meta def find_matching_head : expr → list expr → tactic (list expr) | e [] := return [] | e (H :: Hs) := do t ← infer_type H, ((::) H <$ match_head e t <|> pure id) <*> find_matching_head e Hs meta def subst_locals (s : list (expr × expr)) (e : expr) : expr := (e.abstract_locals (s.map (expr.local_uniq_name ∘ prod.fst)).reverse).instantiate_vars (s.map prod.snd) meta def set_binder : expr → list binder_info → expr | e [] := e | (expr.pi v _ d b) (bi :: bs) := expr.pi v bi d (set_binder b bs) | e _ := e meta def last_explicit_arg : expr → tactic expr | (expr.app f e) := do t ← infer_type f >>= whnf, if t.binding_info = binder_info.default then pure e else last_explicit_arg f | e := pure e private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of the given (Pi-)type -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of the given function -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity /-- variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] meta def drop_binders : expr → tactic expr | (expr.pi n bi t b) := b.instantiate_var <$> mk_local' n bi t >>= drop_binders | e := pure e meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, [c] ← pure $ env.constructors_of struct_n | fail "too many constructors", vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do e ← mk_const (n.update_prefix struct_n) >>= infer_type >>= drop_binders, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) open nat meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /--`iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /--`iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /--`apply_list l`: try to apply the tactics in the list `l` on the first goal, and fail if none succeeds -/ meta def apply_list_expr : list expr → tactic unit | [] := fail "no matching rule" | (h::t) := do interactive.concat_tags (apply h) <|> apply_list_expr t /-- constructs a list of expressions given a list of p-expressions, as follows: - if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it - if the p-expression is a user attribute, add all the theorems with this attribute to the list.-/ meta def build_list_expr_for_apply : list pexpr → tactic (list expr) | [] := return [] | (h::t) := do tail ← build_list_expr_for_apply t, a ← i_to_expr_for_apply h, (do l ← attribute.get_instances (expr.const_name a), m ← list.mmap mk_const l, return (m.append tail)) <|> return (a::tail) /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times -/ meta def apply_rules (hs : list pexpr) (n : nat) : tactic unit := do l ← build_list_expr_for_apply hs, iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l) meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' meta def symm_apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := tactic.apply e cfg <|> (symmetry >> tactic.apply e cfg) meta def apply_assumption (asms : tactic (list expr) := local_context) (tac : tactic unit := skip) : tactic unit := do { ctx ← asms, ctx.any_of (λ H, symm_apply H >> tac) } <|> do { exfalso, ctx ← asms, ctx.any_of (λ H, symm_apply H >> tac) } <|> fail "assumption tactic failed" meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted open nat meta def solve_by_elim_aux (discharger : tactic unit) (asms : tactic (list expr)) : ℕ → tactic unit | 0 := done | (succ n) := discharger <|> (apply_assumption asms $ solve_by_elim_aux n) meta structure by_elim_opt := (discharger : tactic unit := done) (assumptions : tactic (list expr) := local_context) (max_rep : ℕ := 3) meta def solve_by_elim (opt : by_elim_opt := { }) : tactic unit := do tactic.fail_if_no_goals, focus1 $ solve_by_elim_aux opt.discharger opt.assumptions opt.max_rep meta def metavariables : tactic (list expr) := do r ← result, pure (r.list_meta_vars) /-- Succeeds only if the current goal is a proposition. -/ meta def propositional_goal : tactic unit := do goals ← get_goals, p ← is_proof goals.head, guard p meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible variable {α : Type} private meta def iterate_aux (t : tactic α) : list α → tactic (list α) | L := (do r ← t, iterate_aux (r :: L)) <|> return L /-- Apply a tactic as many times as possible, collecting the results in a list. -/ meta def iterate' (t : tactic α) : tactic (list α) := list.reverse <$> iterate_aux t [] /-- Like iterate', but fail if the tactic does not succeed at least once. -/ meta def iterate1 (t : tactic α) : tactic (α × list α) := do r ← decorate_ex "iterate1 failed: tactic did not succeed" t, L ← iterate' t, return (r, L) meta def intros1 : tactic (list expr) := iterate1 intro1 >>= λ p, return (p.1 :: p.2) /-- `successes` invokes each tactic in turn, returning the list of successful results. -/ meta def successes (tactics : list (tactic α)) : tactic (list α) := list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t)) /-- Return target after instantiating metavars and whnf -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf /-- Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor. However it does not reorder goals or invoke `auto_param` tactics. -/ -- FIXME check if we can remove `auto_param := ff` meta def fsplit : tactic unit := do [c] ← target' >>= get_constructors_for | tactic.fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip run_cmd add_interactive [`fsplit] /-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection` succeeds, clears the old hypothesis. -/ meta def injections_and_clear : tactic unit := do l ← local_context, results ← successes $ l.map $ λ e, injection e >> clear e, when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis") run_cmd add_interactive [`injections_and_clear] meta def note_anon (e : expr) : tactic unit := do n ← get_unused_name "lh", note n none e, skip /-- `find_local t` returns a local constant with type t, or fails if none exists. -/ meta def find_local (t : pexpr) : tactic expr := do t' ← to_expr t, prod.snd <$> solve_aux t' assumption /-- `dependent_pose_core l`: introduce dependent hypothesis, where the proofs depend on the values of the previous local constants. `l` is a list of local constants and their values. -/ meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do let lc := l.map prod.fst, let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)), t ← target, new_goal ← mk_meta_var (t.pis lc), old::other_goals ← get_goals, set_goals (old :: new_goal :: other_goals), exact ((new_goal.mk_app lc).instantiate_locals lm), return () /-- like `mk_local_pis` but translating into weak head normal form before checking if it is a Π. -/ meta def mk_local_pis_whnf : expr → tactic (list expr × expr) | e := do (expr.pi n bi d b) ← whnf e | return ([], e), p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) /-- Changes `(h : ∀xs, ∃a:α, p a) ⊢ g` to `(d : ∀xs, a) (s : ∀xs, p (d xs) ⊢ g` -/ meta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do t ← infer_type h, (ctxt, t) ← mk_local_pis_whnf t, `(@Exists %%α %%p) ← whnf t transparency.all | fail "expected a term of the shape ∀xs, ∃a, p xs a", α_t ← infer_type α, expr.sort u ← whnf α_t transparency.all, value ← mk_local_def data (α.pis ctxt), t' ← head_beta (p.app (value.mk_app ctxt)), spec ← mk_local_def spec (t'.pis ctxt), dependent_pose_core [ (value, ((((expr.const `classical.some [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt), (spec, ((((expr.const `classical.some_spec [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt)], try (tactic.clear h), intro1, intro1 /-- Changes `(h : ∀xs, ∃as, p as) ⊢ g` to a list of functions `as`, an a final hypothesis on `p as` -/ meta def choose : expr → list name → tactic unit | h [] := fail "expect list of variables" | h [n] := do cnt ← revert h, intro n, intron (cnt - 1), return () | h (n::ns) := do v ← get_unused_name >>= choose1 h n, choose v ns /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end /-- Hole command used to fill in a structure's field when specifying an instance. In the following: ``` instance : monad id := {! !} ``` invoking hole command `Instance Stub` produces: ``` instance : monad id := { map := _, map_const := _, pure := _, seq := _, seq_left := _, seq_right := _, bind := _ } ``` -/ @[hole_command] meta def instance_stub : hole_command := { name := "Instance Stub", descr := "Generate a skeleton for the structure under construction.", action := λ _, do tgt ← target, let cl := tgt.get_app_fn.const_name, env ← get_env, fs ← expanded_field_list cl, let fs := fs.map prod.snd, let fs := list.intersperse (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"), let out := format.to_string format!"{{ {format.join fs} }", return [(out,"")] } meta def classical : tactic unit := do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache open expr meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) meta def mk_comp (v : expr) : expr → tactic expr | (app f e) := if e = v then pure f else do guard (¬ v.occurs f) <|> fail "bad guard", e' ← mk_comp e >>= instantiate_mvars, f ← instantiate_mvars f, mk_mapp ``function.comp [none,none,none,f,e'] | e := do guard (e = v), t ← infer_type e, mk_mapp ``id [t] meta def mk_higher_order_type : expr → tactic expr | (pi n bi d b@(pi _ _ _ _)) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b' | (pi n bi d b) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (l,r) ← match_eq b' <|> fail format!"not an equality {b'}", l' ← mk_comp v l, r' ← mk_comp v r, mk_app ``eq [l',r'] | e := failed open lean.parser interactive.types @[user_attribute] meta def higher_order_attr : user_attribute unit (option name) := { name := `higher_order, parser := optional ident, descr := "From a lemma of the shape `f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.", after_set := some $ λ lmm _ _, do env ← get_env, decl ← env.get lmm, let num := decl.univ_params.length, let lvls := (list.iota num).map (`l).append_after, let l : expr := expr.const lmm $ lvls.map level.param, t ← infer_type l >>= instantiate_mvars, t' ← mk_higher_order_type t, (_,pr) ← solve_aux t' $ do { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption }, pr ← instantiate_mvars pr, lmm' ← higher_order_attr.get_param lmm, lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure (add_prime lmm), add_decl $ declaration.thm lmm' lvls t' (pure pr), copy_attribute `simp lmm tt lmm', copy_attribute `functor_norm lmm tt lmm' } attribute [higher_order map_comp_pure] map_pure private meta def tactic.use_aux (h : pexpr) : tactic unit := (focus1 (refine h >> done)) <|> (fconstructor >> tactic.use_aux) meta def tactic.use (l : list pexpr) : tactic unit := focus1 $ l.mmap' $ λ h, tactic.use_aux h <|> fail format!"failed to instantiate goal with {h}" end tactic
54cc199b43363faf764bbf52605020733fbaa72b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/special_functions/trigonometric/inverse_deriv.lean
152623840582c746cd8c0c8e658b74665a374de4
[ "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
7,703
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import analysis.special_functions.trigonometric.inverse import analysis.special_functions.trigonometric.deriv /-! # derivatives of the inverse trigonometric functions Derivatives of `arcsin` and `arccos`. -/ noncomputable theory open_locale classical topological_space filter open set filter open_locale real namespace real section arcsin lemma deriv_arcsin_aux {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_strict_deriv_at arcsin (1 / sqrt (1 - x ^ 2)) x ∧ cont_diff_at ℝ ⊤ arcsin x := begin cases h₁.lt_or_lt with h₁ h₁, { have : 1 - x ^ 2 < 0, by nlinarith [h₁], rw [sqrt_eq_zero'.2 this.le, div_zero], have : arcsin =ᶠ[𝓝 x] λ _, -(π / 2) := (gt_mem_nhds h₁).mono (λ y hy, arcsin_of_le_neg_one hy.le), exact ⟨(has_strict_deriv_at_const _ _).congr_of_eventually_eq this.symm, cont_diff_at_const.congr_of_eventually_eq this⟩ }, cases h₂.lt_or_lt with h₂ h₂, { have : 0 < sqrt (1 - x ^ 2) := sqrt_pos.2 (by nlinarith [h₁, h₂]), simp only [← cos_arcsin, one_div] at this ⊢, exact ⟨sin_local_homeomorph.has_strict_deriv_at_symm ⟨h₁, h₂⟩ this.ne' (has_strict_deriv_at_sin _), sin_local_homeomorph.cont_diff_at_symm_deriv this.ne' ⟨h₁, h₂⟩ (has_deriv_at_sin _) cont_diff_sin.cont_diff_at⟩ }, { have : 1 - x ^ 2 < 0, by nlinarith [h₂], rw [sqrt_eq_zero'.2 this.le, div_zero], have : arcsin =ᶠ[𝓝 x] λ _, π / 2 := (lt_mem_nhds h₂).mono (λ y hy, arcsin_of_one_le hy.le), exact ⟨(has_strict_deriv_at_const _ _).congr_of_eventually_eq this.symm, cont_diff_at_const.congr_of_eventually_eq this⟩ } end lemma has_strict_deriv_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_strict_deriv_at arcsin (1 / sqrt (1 - x ^ 2)) x := (deriv_arcsin_aux h₁ h₂).1 lemma has_deriv_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_deriv_at arcsin (1 / sqrt (1 - x ^ 2)) x := (has_strict_deriv_at_arcsin h₁ h₂).has_deriv_at lemma cont_diff_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) {n : ℕ∞} : cont_diff_at ℝ n arcsin x := (deriv_arcsin_aux h₁ h₂).2.of_le le_top lemma has_deriv_within_at_arcsin_Ici {x : ℝ} (h : x ≠ -1) : has_deriv_within_at arcsin (1 / sqrt (1 - x ^ 2)) (Ici x) x := begin rcases em (x = 1) with (rfl|h'), { convert (has_deriv_within_at_const _ _ (π / 2)).congr _ _; simp [arcsin_of_one_le] { contextual := tt } }, { exact (has_deriv_at_arcsin h h').has_deriv_within_at } end lemma has_deriv_within_at_arcsin_Iic {x : ℝ} (h : x ≠ 1) : has_deriv_within_at arcsin (1 / sqrt (1 - x ^ 2)) (Iic x) x := begin rcases em (x = -1) with (rfl|h'), { convert (has_deriv_within_at_const _ _ (-(π / 2))).congr _ _; simp [arcsin_of_le_neg_one] { contextual := tt } }, { exact (has_deriv_at_arcsin h' h).has_deriv_within_at } end lemma differentiable_within_at_arcsin_Ici {x : ℝ} : differentiable_within_at ℝ arcsin (Ici x) x ↔ x ≠ -1 := begin refine ⟨_, λ h, (has_deriv_within_at_arcsin_Ici h).differentiable_within_at⟩, rintro h rfl, have : sin ∘ arcsin =ᶠ[𝓝[≥] (-1 : ℝ)] id, { filter_upwards [Icc_mem_nhds_within_Ici ⟨le_rfl, neg_lt_self (zero_lt_one' ℝ)⟩] with x using sin_arcsin', }, have := h.has_deriv_within_at.sin.congr_of_eventually_eq this.symm (by simp), simpa using (unique_diff_on_Ici _ _ left_mem_Ici).eq_deriv _ this (has_deriv_within_at_id _ _) end lemma differentiable_within_at_arcsin_Iic {x : ℝ} : differentiable_within_at ℝ arcsin (Iic x) x ↔ x ≠ 1 := begin refine ⟨λ h, _, λ h, (has_deriv_within_at_arcsin_Iic h).differentiable_within_at⟩, rw [← neg_neg x, ← image_neg_Ici] at h, have := (h.comp (-x) differentiable_within_at_id.neg (maps_to_image _ _)).neg, simpa [(∘), differentiable_within_at_arcsin_Ici] using this end lemma differentiable_at_arcsin {x : ℝ} : differentiable_at ℝ arcsin x ↔ x ≠ -1 ∧ x ≠ 1 := ⟨λ h, ⟨differentiable_within_at_arcsin_Ici.1 h.differentiable_within_at, differentiable_within_at_arcsin_Iic.1 h.differentiable_within_at⟩, λ h, (has_deriv_at_arcsin h.1 h.2).differentiable_at⟩ @[simp] lemma deriv_arcsin : deriv arcsin = λ x, 1 / sqrt (1 - x ^ 2) := begin funext x, by_cases h : x ≠ -1 ∧ x ≠ 1, { exact (has_deriv_at_arcsin h.1 h.2).deriv }, { rw [deriv_zero_of_not_differentiable_at (mt differentiable_at_arcsin.1 h)], simp only [not_and_distrib, ne.def, not_not] at h, rcases h with (rfl|rfl); simp } end lemma differentiable_on_arcsin : differentiable_on ℝ arcsin {-1, 1}ᶜ := λ x hx, (differentiable_at_arcsin.2 ⟨λ h, hx (or.inl h), λ h, hx (or.inr h)⟩).differentiable_within_at lemma cont_diff_on_arcsin {n : ℕ∞} : cont_diff_on ℝ n arcsin {-1, 1}ᶜ := λ x hx, (cont_diff_at_arcsin (mt or.inl hx) (mt or.inr hx)).cont_diff_within_at lemma cont_diff_at_arcsin_iff {x : ℝ} {n : ℕ∞} : cont_diff_at ℝ n arcsin x ↔ n = 0 ∨ (x ≠ -1 ∧ x ≠ 1) := ⟨λ h, or_iff_not_imp_left.2 $ λ hn, differentiable_at_arcsin.1 $ h.differentiable_at $ enat.one_le_iff_ne_zero.2 hn, λ h, h.elim (λ hn, hn.symm ▸ (cont_diff_zero.2 continuous_arcsin).cont_diff_at) $ λ hx, cont_diff_at_arcsin hx.1 hx.2⟩ end arcsin section arccos lemma has_strict_deriv_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_strict_deriv_at arccos (-(1 / sqrt (1 - x ^ 2))) x := (has_strict_deriv_at_arcsin h₁ h₂).const_sub (π / 2) lemma has_deriv_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) : has_deriv_at arccos (-(1 / sqrt (1 - x ^ 2))) x := (has_deriv_at_arcsin h₁ h₂).const_sub (π / 2) lemma cont_diff_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) {n : ℕ∞} : cont_diff_at ℝ n arccos x := cont_diff_at_const.sub (cont_diff_at_arcsin h₁ h₂) lemma has_deriv_within_at_arccos_Ici {x : ℝ} (h : x ≠ -1) : has_deriv_within_at arccos (-(1 / sqrt (1 - x ^ 2))) (Ici x) x := (has_deriv_within_at_arcsin_Ici h).const_sub _ lemma has_deriv_within_at_arccos_Iic {x : ℝ} (h : x ≠ 1) : has_deriv_within_at arccos (-(1 / sqrt (1 - x ^ 2))) (Iic x) x := (has_deriv_within_at_arcsin_Iic h).const_sub _ lemma differentiable_within_at_arccos_Ici {x : ℝ} : differentiable_within_at ℝ arccos (Ici x) x ↔ x ≠ -1 := (differentiable_within_at_const_sub_iff _).trans differentiable_within_at_arcsin_Ici lemma differentiable_within_at_arccos_Iic {x : ℝ} : differentiable_within_at ℝ arccos (Iic x) x ↔ x ≠ 1 := (differentiable_within_at_const_sub_iff _).trans differentiable_within_at_arcsin_Iic lemma differentiable_at_arccos {x : ℝ} : differentiable_at ℝ arccos x ↔ x ≠ -1 ∧ x ≠ 1 := (differentiable_at_const_sub_iff _).trans differentiable_at_arcsin @[simp] lemma deriv_arccos : deriv arccos = λ x, -(1 / sqrt (1 - x ^ 2)) := funext $ λ x, (deriv_const_sub _).trans $ by simp only [deriv_arcsin] lemma differentiable_on_arccos : differentiable_on ℝ arccos {-1, 1}ᶜ := differentiable_on_arcsin.const_sub _ lemma cont_diff_on_arccos {n : ℕ∞} : cont_diff_on ℝ n arccos {-1, 1}ᶜ := cont_diff_on_const.sub cont_diff_on_arcsin lemma cont_diff_at_arccos_iff {x : ℝ} {n : ℕ∞} : cont_diff_at ℝ n arccos x ↔ n = 0 ∨ (x ≠ -1 ∧ x ≠ 1) := by refine iff.trans ⟨λ h, _, λ h, _⟩ cont_diff_at_arcsin_iff; simpa [arccos] using (@cont_diff_at_const _ _ _ _ _ _ _ _ _ _ (π / 2)).sub h end arccos end real
06dbdf46b611840308471c9ebdcf2fd3863fddb8
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/leanpkg/leanpkg/resolve.lean
76d6e66b2bf107d7c60e624e621c4949f2fbd0df
[ "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
3,471
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner -/ import leanpkg.manifest system.io data.hash_map leanpkg.proc variable [io.interface] namespace leanpkg def assignment := hash_map string (λ _, string) -- TODO(gabriel): hash function for strings def assignment.empty : assignment := mk_hash_map list.length @[reducible] def solver := state_t assignment io instance {α : Type} : has_coe (io α) (solver α) := ⟨state_t.lift⟩ def not_yet_assigned (d : string) : solver bool := do assg ← state_t.read, return $ ¬ assg.contains d def resolved_path (d : string) : solver string := do assg ← state_t.read, some path ← return (assg.find d) | io.fail "", return path -- TODO(gabriel): directory existence testing def dir_exists (d : string) : io bool := do ch ← io.proc.spawn { cmd := "test", args := ["-d", d] }, ev ← io.proc.wait ch, return $ ev = 0 -- TODO(gabriel): windows? def resolve_dir (abs_or_rel : string) (base : string) : string := if abs_or_rel.reverse.head = '/' then abs_or_rel -- absolute else base ++ "/" ++ abs_or_rel def materialize (relpath : string) (dep : dependency) : solver unit := match dep.src with | (source.path dir) := do let depdir := resolve_dir dir relpath, io.put_str_ln $ dep.name ++ ": using local path " ++ depdir, state_t.modify $ λ assg, assg.insert dep.name depdir | (source.git url rev) := do let depdir := "_target/deps/" ++ dep.name, already_there ← dir_exists depdir, let checkout_action := exec_cmd "git" ["checkout", "--detach", rev] (some depdir), (do guard already_there, io.put_str_ln $ dep.name ++ ": trying to update " ++ depdir ++ " to revision " ++ rev, checkout_action) <|> (do guard already_there, exec_cmd "git" ["fetch"] (some depdir), checkout_action) <|> (do io.put_str_ln $ dep.name ++ ": cloning " ++ url ++ " to " ++ depdir, exec_cmd "rm" ["-rf", depdir], exec_cmd "mkdir" ["-p", depdir], exec_cmd "git" ["clone", url, depdir], exec_cmd "git" ["checkout", "--detach", rev] (some depdir)), state_t.modify $ λ assg, assg.insert dep.name depdir end def solve_deps_core : ∀ (rel_path : string) (d : manifest) (max_depth : ℕ), solver unit | _ _ 0 := io.fail "maximum dependency resolution depth reached" | relpath d (max_depth + 1) := do deps ← monad.filter (not_yet_assigned ∘ dependency.name) d.dependencies, monad.for' deps (materialize relpath), monad.for' deps $ λ dep, do p ← resolved_path dep.name, d ← manifest.from_file $ p ++ "/" ++ "leanpkg.toml", when (d.name ≠ dep.name) $ io.fail $ d.name ++ " (in " ++ relpath ++ ") depends on " ++ d.name ++ ", but resolved dependency has name " ++ dep.name ++ " (in " ++ p ++ ")", solve_deps_core p d max_depth def solve_deps (d : manifest) : io assignment := do (_, assg) ← solve_deps_core "." d 1024 $ assignment.empty.insert d.name ".", return assg def construct_path_core (depname : string) (dirname : string) : io (list string) := list.map (λ relpath, dirname ++ "/" ++ relpath) <$> manifest.effective_path <$> (manifest.from_file $ dirname ++ "/" ++ leanpkg_toml_fn) def construct_path (assg : assignment) : io (list string) := do let assg := assg.fold [] (λ xs depname dirname, (depname, dirname) :: xs), list.join <$> (list.mfor assg $ λ ⟨depname, dirname⟩, construct_path_core depname dirname) end leanpkg
17405c88fe8e476db796bbfde761991029430434
2385ce0e3b60d8dbea33dd439902a2070cca7a24
/tests/lean/1603.lean
49cf4953b032142e93971cf3a565d3cf65192ceb
[ "Apache-2.0" ]
permissive
TehMillhouse/lean
68d6fdd2fb11a6c65bc28dec308d70f04dad38b4
6bbf2fbd8912617e5a973575bab8c383c9c268a1
refs/heads/master
1,620,830,893,339
1,515,592,479,000
1,515,592,997,000
116,964,828
0
0
null
1,515,592,734,000
1,515,592,734,000
null
UTF-8
Lean
false
false
223
lean
def some_lets : ℕ → ℕ → ℕ | 0 v := v | (nat.succ n) v := let k := some_lets n v + v in k def some_unfolded_lets (n : ℕ) : ∃ v : ℕ , v = some_lets 5 n := begin dunfold some_lets, -- sorry end
75090fabdb8d0bfa6300d653dc7e83dbb3b4dc0d
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/algebra/order.lean
5ed0a49f71d37c7bf43cd68146e1b827498c77c6
[ "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
9,797
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 set_option old_structure_cmd true universe u variables {α : Type u} class weak_order (α : Type u) extends has_le α := (le_refl : ∀ a : α, a ≤ a) (le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c) (le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b) class linear_weak_order (α : Type u) extends weak_order α := (le_total : ∀ a b : α, a ≤ b ∨ b ≤ a) class strict_order (α : Type u) extends has_lt α := (lt_irrefl : ∀ a : α, ¬ a < a) (lt_trans : ∀ a b c : α, a < b → b < c → a < c) /- structures with a weak and a strict order -/ class order_pair (α : Type u) extends weak_order α, has_lt α := (le_of_lt : ∀ a b : α, a < b → a ≤ b) (lt_of_lt_of_le : ∀ a b c : α, a < b → b ≤ c → a < c) (lt_of_le_of_lt : ∀ a b c : α, a ≤ b → b < c → a < c) (lt_irrefl : ∀ a : α, ¬ a < a) class strong_order_pair (α : Type u) extends weak_order α, has_lt α := (le_iff_lt_or_eq : ∀ a b : α, a ≤ b ↔ a < b ∨ a = b) (lt_irrefl : ∀ a : α, ¬ a < a) class linear_order_pair (α : Type u) extends order_pair α, linear_weak_order α class linear_strong_order_pair (α : Type u) extends strong_order_pair α, linear_weak_order α @[refl] lemma le_refl [weak_order α] : ∀ a : α, a ≤ a := weak_order.le_refl @[trans] lemma le_trans [weak_order α] : ∀ {a b c : α}, a ≤ b → b ≤ c → a ≤ c := weak_order.le_trans lemma le_antisymm [weak_order α] : ∀ {a b : α}, a ≤ b → b ≤ a → a = b := weak_order.le_antisymm lemma le_of_eq [weak_order α] {a b : α} : a = b → a ≤ b := λ h, h ▸ le_refl a @[trans] lemma ge_trans [weak_order α] : ∀ {a b c : α}, a ≥ b → b ≥ c → a ≥ c := λ a b c h₁ h₂, le_trans h₂ h₁ lemma le_total [linear_weak_order α] : ∀ a b : α, a ≤ b ∨ b ≤ a := linear_weak_order.le_total lemma le_of_not_ge [linear_weak_order α] {a b : α} : ¬ a ≥ b → a ≤ b := or.resolve_left (le_total b a) lemma le_of_not_le [linear_weak_order α] {a b : α} : ¬ a ≤ b → b ≤ a := or.resolve_left (le_total a b) lemma lt_irrefl [strict_order α] : ∀ a : α, ¬ a < a := strict_order.lt_irrefl lemma gt_irrefl [strict_order α] : ∀ a : α, ¬ a > a := lt_irrefl @[trans] lemma lt_trans [strict_order α] : ∀ {a b c : α}, a < b → b < c → a < c := strict_order.lt_trans def lt.trans := @lt_trans @[trans] lemma gt_trans [strict_order α] : ∀ {a b c : α}, a > b → b > c → a > c := λ a b c h₁ h₂, lt_trans h₂ h₁ def gt.trans := @gt_trans lemma ne_of_lt [strict_order α] {a b : α} (h : a < b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma ne_of_gt [strict_order α] {a b : α} (h : a > b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma lt_asymm [strict_order α] {a b : α} (h : a < b) : ¬ b < a := λ h1 : b < a, lt_irrefl a (lt_trans h h1) lemma not_lt_of_gt [strict_order α] {a b : α} (h : a > b) : ¬ a < b := lt_asymm h lemma le_of_lt [order_pair α] : ∀ {a b : α}, a < b → a ≤ b := order_pair.le_of_lt @[trans] lemma lt_of_lt_of_le [order_pair α] : ∀ {a b c : α}, a < b → b ≤ c → a < c := order_pair.lt_of_lt_of_le @[trans] lemma lt_of_le_of_lt [order_pair α] : ∀ {a b c : α}, a ≤ b → b < c → a < c := order_pair.lt_of_le_of_lt @[trans] lemma gt_of_gt_of_ge [order_pair α] {a b c : α} (h₁ : a > b) (h₂ : b ≥ c) : a > c := lt_of_le_of_lt h₂ h₁ @[trans] lemma gt_of_ge_of_gt [order_pair α] {a b c : α} (h₁ : a ≥ b) (h₂ : b > c) : a > c := lt_of_lt_of_le h₂ h₁ instance order_pair.to_strict_order [s : order_pair α] : strict_order α := { s with lt_irrefl := order_pair.lt_irrefl, lt_trans := λ a b c h₁ h₂, lt_of_lt_of_le h₁ (le_of_lt h₂) } lemma not_le_of_gt [order_pair α] {a b : α} (h : a > b) : ¬ a ≤ b := λ h₁, lt_irrefl b (lt_of_lt_of_le h h₁) lemma not_lt_of_ge [order_pair α] {a b : α} (h : a ≥ b) : ¬ a < b := λ h₁, lt_irrefl b (lt_of_le_of_lt h h₁) lemma le_iff_lt_or_eq [strong_order_pair α] : ∀ {a b : α}, a ≤ b ↔ a < b ∨ a = b := strong_order_pair.le_iff_lt_or_eq lemma lt_or_eq_of_le [strong_order_pair α] : ∀ {a b : α}, a ≤ b → a < b ∨ a = b := λ a b h, iff.mp le_iff_lt_or_eq h lemma le_of_lt_or_eq [strong_order_pair α] : ∀ {a b : α}, (a < b ∨ a = b) → a ≤ b := λ a b h, iff.mpr le_iff_lt_or_eq h lemma lt_of_le_of_ne [strong_order_pair α] {a b : α} : a ≤ b → a ≠ b → a < b := λ h₁ h₂, or.resolve_right (lt_or_eq_of_le h₁) h₂ private lemma lt_irrefl' [strong_order_pair α] : ∀ a : α, ¬ a < a := strong_order_pair.lt_irrefl private lemma le_of_lt' [strong_order_pair α] ⦃a b : α⦄ (h : a < b) : a ≤ b := le_of_lt_or_eq (or.inl h) private lemma lt_of_lt_of_le' [strong_order_pair α] (a b c : α) (h₁ : a < b) (h₂ : b ≤ c) : a < c := have a ≤ c, from le_trans (le_of_lt' h₁) h₂, or.elim (lt_or_eq_of_le this) (λ h : a < c, h) (λ h : a = c, have b ≤ a, from h.symm ▸ h₂, have a = b, from le_antisymm (le_of_lt' h₁) this, absurd h₁ (this ▸ lt_irrefl' a)) private lemma lt_of_le_of_lt' [strong_order_pair α] (a b c : α) (h₁ : a ≤ b) (h₂ : b < c) : a < c := have a ≤ c, from le_trans h₁ (le_of_lt' h₂), or.elim (lt_or_eq_of_le this) (λ h : a < c, h) (λ h : a = c, have c ≤ b, from h ▸ h₁, have c = b, from le_antisymm this (le_of_lt' h₂), absurd h₂ (this ▸ lt_irrefl' c)) instance strong_order_pair.to_order_pair [s : strong_order_pair α] : order_pair α := { s with lt_irrefl := lt_irrefl', le_of_lt := le_of_lt', lt_of_le_of_lt := lt_of_le_of_lt', lt_of_lt_of_le := lt_of_lt_of_le'} instance linear_strong_order_pair.to_linear_order_pair [s : linear_strong_order_pair α] : linear_order_pair α := { s with lt_irrefl := lt_irrefl', le_of_lt := le_of_lt', lt_of_le_of_lt := lt_of_le_of_lt', lt_of_lt_of_le := lt_of_lt_of_le'} lemma lt_trichotomy [linear_strong_order_pair α] (a b : α) : a < b ∨ a = b ∨ b < a := or.elim (le_total a b) (λ h : a ≤ b, or.elim (lt_or_eq_of_le h) (λ h : a < b, or.inl h) (λ h : a = b, or.inr (or.inl h))) (λ h : b ≤ a, or.elim (lt_or_eq_of_le h) (λ h : b < a, or.inr (or.inr h)) (λ h : b = a, or.inr (or.inl h.symm))) lemma le_of_not_gt [linear_strong_order_pair α] {a b : α} (h : ¬ a > b) : a ≤ b := match lt_trichotomy a b with | or.inl hlt := le_of_lt hlt | or.inr (or.inl heq) := heq ▸ le_refl a | or.inr (or.inr hgt) := absurd hgt h end lemma lt_of_not_ge [linear_strong_order_pair α] {a b : α} (h : ¬ a ≥ b) : a < b := match lt_trichotomy a b with | or.inl hlt := hlt | or.inr (or.inl heq) := absurd (heq ▸ le_refl a : a ≥ b) h | or.inr (or.inr hgt) := absurd (le_of_lt hgt) h end lemma lt_or_ge [linear_strong_order_pair α] (a b : α) : a < b ∨ a ≥ b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := or.inr (heq ▸ le_refl a) | or.inr (or.inr hgt) := or.inr (le_of_lt hgt) end lemma le_or_gt [linear_strong_order_pair α] (a b : α) : a ≤ b ∨ a > b := or.swap (lt_or_ge b a) lemma lt_or_gt_of_ne [linear_strong_order_pair α] {a b : α} (h : a ≠ b) : a < b ∨ a > b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := absurd heq h | or.inr (or.inr hgt) := or.inr hgt end lemma lt_iff_not_ge [linear_strong_order_pair α] (x y : α) : x < y ↔ ¬ x ≥ y := ⟨not_le_of_gt, lt_of_not_ge⟩ /- The following lemma can be used when defining a decidable_linear_order instance, and the concrete structure does not have its own definition for decidable le -/ def decidable_le_of_decidable_lt [linear_strong_order_pair α] [∀ a b : α, decidable (a < b)] (a b : α) : decidable (a ≤ b) := if h₁ : a < b then is_true (le_of_lt h₁) else if h₂ : b < a then is_false (not_le_of_gt h₂) else is_true (le_of_not_gt h₂) /- The following lemma can be used when defining a decidable_linear_order instance, and the concrete structure does not have its own definition for decidable le -/ def decidable_eq_of_decidable_lt [linear_strong_order_pair α] [∀ a b : α, decidable (a < b)] (a b : α) : decidable (a = b) := match decidable_le_of_decidable_lt a b with | is_true h₁ := match decidable_le_of_decidable_lt b a with | is_true h₂ := is_true (le_antisymm h₁ h₂) | is_false h₂ := is_false (λ he : a = b, h₂ (he ▸ le_refl a)) end | is_false h₁ := is_false (λ he : a = b, h₁ (he ▸ le_refl a)) end class decidable_linear_order (α : Type u) extends linear_strong_order_pair α := (decidable_lt : decidable_rel lt) (decidable_le : decidable_rel le) -- TODO(Leo): add default value using decidable_le_of_decidable_lt (decidable_eq : decidable_eq α) -- TODO(Leo): add default value using decidable_eq_of_decidable_lt instance [decidable_linear_order α] (a b : α) : decidable (a < b) := decidable_linear_order.decidable_lt α a b instance [decidable_linear_order α] (a b : α) : decidable (a ≤ b) := decidable_linear_order.decidable_le α a b instance [decidable_linear_order α] (a b : α) : decidable (a = b) := decidable_linear_order.decidable_eq α a b lemma eq_or_lt_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ a < b) : a = b ∨ b < a := if h₁ : a = b then or.inl h₁ else or.inr (lt_of_not_ge (λ hge, h (lt_of_le_of_ne hge h₁)))
607fa4a0a6a379417f003ca0d5e8b2c0736a565d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/macroPrio.lean
6ff84b47d811e04a7974e8ab9d1a082c757f9681
[ "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
518
lean
import Lean macro "foo!" x:term:max : term => `($x + 1) #check foo! 0 theorem ex1 : foo! 2 = 3 := rfl macro "foo!" x:term:max : term => `($x * 2) #check foo! 1 -- ambiguous -- macro with higher priority macro (priority := high) "foo!" x:term:max : term => `($x - 2) #check foo! 2 theorem ex2 : foo! 2 = 0 := rfl -- Define elaborator with even higher priority elab (priority := high+1) "foo!" x:term:max : term <= expectedType => Lean.Elab.Term.elabTerm x expectedType theorem ex3 : foo! 3 = 3 := rfl
8e996a61ef10a28450089f82d0ffc46045fe8689
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/Lean/Elab/Tactic/Basic.lean
0e685f43e5e955f9b5b7db93f21abe27234dba58
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
17,505
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Lean.Util.CollectMVars import Init.Lean.Meta.Tactic.Assumption import Init.Lean.Meta.Tactic.Intro import Init.Lean.Meta.Tactic.Clear import Init.Lean.Meta.Tactic.Revert import Init.Lean.Meta.Tactic.Subst import Init.Lean.Elab.Util import Init.Lean.Elab.Term namespace Lean namespace Elab def goalsToMessageData (goals : List MVarId) : MessageData := MessageData.joinSep (goals.map $ MessageData.ofGoal) (Format.line ++ Format.line) def Term.reportUnsolvedGoals (ref : Syntax) (goals : List MVarId) : TermElabM Unit := let tailRef := ref.getTailWithInfo.getD ref; Term.throwError tailRef $ "unsolved goals" ++ Format.line ++ goalsToMessageData goals namespace Tactic structure Context extends toTermCtx : Term.Context := (main : MVarId) (ref : Syntax) structure State extends toTermState : Term.State := (goals : List MVarId) instance State.inhabited : Inhabited State := ⟨{ goals := [], toTermState := arbitrary _ }⟩ structure BacktrackableState := (env : Environment) (mctx : MetavarContext) (goals : List MVarId) abbrev Exception := Elab.Exception abbrev TacticM := ReaderT Context (EStateM Exception State) abbrev Tactic := Syntax → TacticM Unit protected def save (s : State) : BacktrackableState := { .. s } protected def restore (s : State) (bs : BacktrackableState) : State := { env := bs.env, mctx := bs.mctx, goals := bs.goals, .. s } instance : EStateM.Backtrackable BacktrackableState State := { save := Tactic.save, restore := Tactic.restore } def liftTermElabM {α} (x : TermElabM α) : TacticM α := fun ctx s => match x ctx.toTermCtx s.toTermState with | EStateM.Result.ok a newS => EStateM.Result.ok a { toTermState := newS, .. s } | EStateM.Result.error (Term.Exception.ex ex) newS => EStateM.Result.error ex { toTermState := newS, .. s } | EStateM.Result.error Term.Exception.postpone _ => unreachable! def liftMetaM {α} (ref : Syntax) (x : MetaM α) : TacticM α := liftTermElabM $ Term.liftMetaM ref x def getEnv : TacticM Environment := do s ← get; pure s.env def getMCtx : TacticM MetavarContext := do s ← get; pure s.mctx @[inline] def modifyMCtx (f : MetavarContext → MetavarContext) : TacticM Unit := modify $ fun s => { mctx := f s.mctx, .. s } def getLCtx : TacticM LocalContext := do ctx ← read; pure ctx.lctx def getLocalInsts : TacticM LocalInstances := do ctx ← read; pure ctx.localInstances def getOptions : TacticM Options := do ctx ← read; pure ctx.config.opts def getMVarDecl (mvarId : MVarId) : TacticM MetavarDecl := do mctx ← getMCtx; pure $ mctx.getDecl mvarId def instantiateMVars (ref : Syntax) (e : Expr) : TacticM Expr := liftTermElabM $ Term.instantiateMVars ref e def addContext (msg : MessageData) : TacticM MessageData := liftTermElabM $ Term.addContext msg def isExprMVarAssigned (mvarId : MVarId) : TacticM Bool := liftTermElabM $ Term.isExprMVarAssigned mvarId def assignExprMVar (mvarId : MVarId) (val : Expr) : TacticM Unit := liftTermElabM $ Term.assignExprMVar mvarId val def ensureHasType (ref : Syntax) (expectedType? : Option Expr) (e : Expr) : TacticM Expr := liftTermElabM $ Term.ensureHasType ref expectedType? e def reportUnsolvedGoals (ref : Syntax) (goals : List MVarId) : TacticM Unit := liftTermElabM $ Term.reportUnsolvedGoals ref goals def inferType (ref : Syntax) (e : Expr) : TacticM Expr := liftTermElabM $ Term.inferType ref e def whnf (ref : Syntax) (e : Expr) : TacticM Expr := liftTermElabM $ Term.whnf ref e def whnfCore (ref : Syntax) (e : Expr) : TacticM Expr := liftTermElabM $ Term.whnfCore ref e def unfoldDefinition? (ref : Syntax) (e : Expr) : TacticM (Option Expr) := liftTermElabM $ Term.unfoldDefinition? ref e def resolveGlobalName (n : Name) : TacticM (List (Name × List String)) := liftTermElabM $ Term.resolveGlobalName n /-- Collect unassigned metavariables -/ def collectMVars (ref : Syntax) (e : Expr) : TacticM (List MVarId) := do e ← instantiateMVars ref e; let s := Lean.collectMVars {} e; pure s.result.toList instance monadLog : MonadLog TacticM := { getCmdPos := do ctx ← read; pure ctx.cmdPos, getFileMap := do ctx ← read; pure ctx.fileMap, getFileName := do ctx ← read; pure ctx.fileName, addContext := addContext, logMessage := fun msg => modify $ fun s => { messages := s.messages.add msg, .. s } } def throwError {α} (ref : Syntax) (msgData : MessageData) : TacticM α := do ref ← if ref.getPos.isNone then do ctx ← read; pure ctx.ref else pure ref; liftTermElabM $ Term.throwError ref msgData def throwUnsupportedSyntax {α} : TacticM α := liftTermElabM $ Term.throwUnsupportedSyntax @[inline] def withIncRecDepth {α} (ref : Syntax) (x : TacticM α) : TacticM α := do ctx ← read; when (ctx.currRecDepth == ctx.maxRecDepth) $ throwError ref maxRecDepthErrorMessage; adaptReader (fun (ctx : Context) => { currRecDepth := ctx.currRecDepth + 1, .. ctx }) x protected def getCurrMacroScope : TacticM MacroScope := do ctx ← read; pure ctx.currMacroScope protected def getMainModule : TacticM Name := do env ← getEnv; pure env.mainModule @[inline] protected def withFreshMacroScope {α} (x : TacticM α) : TacticM α := do fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })); adaptReader (fun (ctx : Context) => { ctx with currMacroScope := fresh }) x instance monadQuotation : MonadQuotation TacticM := { getCurrMacroScope := Tactic.getCurrMacroScope, getMainModule := Tactic.getMainModule, withFreshMacroScope := @Tactic.withFreshMacroScope } unsafe def mkTacticAttribute : IO (KeyedDeclsAttribute Tactic) := mkElabAttribute Tactic `Lean.Elab.Tactic.tacticElabAttribute `builtinTactic `tactic `Lean.Parser.Tactic `Lean.Elab.Tactic.Tactic "tactic" @[init mkTacticAttribute] constant tacticElabAttribute : KeyedDeclsAttribute Tactic := arbitrary _ def logTrace (cls : Name) (ref : Syntax) (msg : MessageData) : TacticM Unit := liftTermElabM $ Term.logTrace cls ref msg @[inline] def trace (cls : Name) (ref : Syntax) (msg : Unit → MessageData) : TacticM Unit := liftTermElabM $ Term.trace cls ref msg @[inline] def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TacticM Unit := liftTermElabM $ Term.traceAtCmdPos cls msg def dbgTrace {α} [HasToString α] (a : α) : TacticM Unit :=_root_.dbgTrace (toString a) $ fun _ => pure () private def evalTacticUsing (s : State) (stx : Syntax) : List Tactic → TacticM Unit | [] => do let refFmt := stx.prettyPrint; throwError stx ("unexpected syntax" ++ MessageData.nest 2 (Format.line ++ refFmt)) | (evalFn::evalFns) => catch (evalFn stx) (fun ex => match ex with | Exception.error _ => match evalFns with | [] => throw ex | _ => do set s; evalTacticUsing evalFns | Exception.unsupportedSyntax => do set s; evalTacticUsing evalFns) /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : TacticM α) : TacticM α := adaptReader (fun (ctx : Context) => { macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack, .. ctx }) x instance : MonadMacroAdapter TacticM := { getEnv := getEnv, getCurrMacroScope := getCurrMacroScope, getNextMacroScope := do s ← get; pure s.nextMacroScope, setNextMacroScope := fun next => modify $ fun s => { nextMacroScope := next, .. s }, throwError := @throwError, throwUnsupportedSyntax := @throwUnsupportedSyntax } @[specialize] private def expandTacticMacroFns (evalTactic : Syntax → TacticM Unit) (stx : Syntax) : List Macro → TacticM Unit | [] => throwError stx ("tactic '" ++ toString stx.getKind ++ "' has not been implemented") | m::ms => do scp ← getCurrMacroScope; catch (do stx' ← adaptMacro m stx; evalTactic stx') (fun ex => match ms with | [] => throw ex | _ => expandTacticMacroFns ms) @[inline] def expandTacticMacro (evalTactic : Syntax → TacticM Unit) (stx : Syntax) : TacticM Unit := do env ← getEnv; let k := stx.getKind; let table := (macroAttribute.ext.getState env).table; let macroFns := (table.find? k).getD []; expandTacticMacroFns evalTactic stx macroFns partial def evalTactic : Syntax → TacticM Unit | stx => withIncRecDepth stx $ withFreshMacroScope $ match stx with | Syntax.node k args => if k == nullKind then -- list of tactics separated by `;` => evaluate in order -- Syntax quotations can return multiple ones stx.forSepArgsM evalTactic else do trace `Elab.step stx $ fun _ => stx; s ← get; let table := (tacticElabAttribute.ext.getState s.env).table; let k := stx.getKind; match table.find? k with | some evalFns => evalTacticUsing s stx evalFns | none => expandTacticMacro evalTactic stx | _ => throwError stx "unexpected command" /-- Adapt a syntax transformation to a regular tactic evaluator. -/ def adaptExpander (exp : Syntax → TacticM Syntax) : Tactic := fun stx => do stx' ← exp stx; withMacroExpansion stx stx' $ evalTactic stx' @[inline] def withLCtx {α} (lctx : LocalContext) (localInsts : LocalInstances) (x : TacticM α) : TacticM α := adaptReader (fun (ctx : Context) => { lctx := lctx, localInstances := localInsts, .. ctx }) x def resetSynthInstanceCache : TacticM Unit := liftTermElabM Term.resetSynthInstanceCache @[inline] def resettingSynthInstanceCache {α} (x : TacticM α) : TacticM α := do s ← get; let savedSythInstance := s.cache.synthInstance; resetSynthInstanceCache; finally x (modify $ fun s => { cache := { synthInstance := savedSythInstance, .. s.cache }, .. s }) @[inline] def resettingSynthInstanceCacheWhen {α} (b : Bool) (x : TacticM α) : TacticM α := if b then resettingSynthInstanceCache x else x def withMVarContext {α} (mvarId : MVarId) (x : TacticM α) : TacticM α := do mvarDecl ← getMVarDecl mvarId; ctx ← read; let needReset := ctx.localInstances == mvarDecl.localInstances; withLCtx mvarDecl.lctx mvarDecl.localInstances $ resettingSynthInstanceCacheWhen needReset x def getGoals : TacticM (List MVarId) := do s ← get; pure s.goals def setGoals (gs : List MVarId) : TacticM Unit := modify $ fun s => { goals := gs, .. s } def appendGoals (gs : List MVarId) : TacticM Unit := modify $ fun s => { goals := s.goals ++ gs, .. s } def pruneSolvedGoals : TacticM Unit := do gs ← getGoals; gs ← gs.filterM $ fun g => not <$> isExprMVarAssigned g; setGoals gs def getUnsolvedGoals : TacticM (List MVarId) := do pruneSolvedGoals; getGoals def getMainGoal (ref : Syntax) : TacticM (MVarId × List MVarId) := do (g::gs) ← getUnsolvedGoals | throwError ref "no goals to be solved"; pure (g, gs) def ensureHasNoMVars (ref : Syntax) (e : Expr) : TacticM Unit := do e ← instantiateMVars ref e; when e.hasMVar $ throwError ref ("tactic failed, resulting expression contains metavariables" ++ indentExpr e) def withMainMVarContext {α} (ref : Syntax) (x : TacticM α) : TacticM α := do (mvarId, _) ← getMainGoal ref; withMVarContext mvarId x @[inline] def liftMetaMAtMain {α} (ref : Syntax) (x : MVarId → MetaM α) : TacticM α := do (g, _) ← getMainGoal ref; withMVarContext g $ liftMetaM ref $ x g @[inline] def liftMetaTacticAux {α} (ref : Syntax) (tactic : MVarId → MetaM (α × List MVarId)) : TacticM α := do (g, gs) ← getMainGoal ref; withMVarContext g $ do (a, gs') ← liftMetaM ref $ tactic g; setGoals (gs' ++ gs); pure a @[inline] def liftMetaTactic (ref : Syntax) (tactic : MVarId → MetaM (List MVarId)) : TacticM Unit := liftMetaTacticAux ref (fun mvarId => do gs ← tactic mvarId; pure ((), gs)) def done (ref : Syntax) : TacticM Unit := do gs ← getUnsolvedGoals; unless gs.isEmpty $ reportUnsolvedGoals ref gs def focusAux {α} (ref : Syntax) (tactic : TacticM α) : TacticM α := do (g, gs) ← getMainGoal ref; setGoals [g]; a ← tactic; gs' ← getGoals; setGoals (gs' ++ gs); pure a def focus {α} (ref : Syntax) (tactic : TacticM α) : TacticM α := focusAux ref (do a ← tactic; done ref; pure a) /-- Use `parentTag` to tag untagged goals at `newGoals`. If there are multiple new goals, they are named using `<parentTag>.<newSuffix>_<idx>` where `idx > 0`. If there is only one new goal, then we just use `parentTag` -/ def tagUntaggedGoals (parentTag : Name) (newSuffix : Name) (newGoals : List MVarId) : TacticM Unit := do mctx ← getMCtx; match newGoals with | [g] => modifyMCtx $ fun mctx => if mctx.isAnonymousMVar g then mctx.renameMVar g parentTag else mctx | _ => modifyMCtx $ fun mctx => let (mctx, _) := newGoals.foldl (fun (acc : MetavarContext × Nat) (g : MVarId) => let (mctx, idx) := acc; if mctx.isAnonymousMVar g then (mctx.renameMVar g (parentTag ++ newSuffix.appendIndexAfter idx), idx+1) else acc) (mctx, 1); mctx @[builtinTactic seq] def evalSeq : Tactic := fun stx => (stx.getArg 0).forSepArgsM evalTactic partial def evalChoiceAux (tactics : Array Syntax) : Nat → TacticM Unit | i => if h : i < tactics.size then let tactic := tactics.get ⟨i, h⟩; catch (evalTactic tactic) (fun ex => match ex with | Exception.unsupportedSyntax => evalChoiceAux (i+1) | _ => throw ex) else throwUnsupportedSyntax @[builtinTactic choice] def evalChoice : Tactic := fun stx => evalChoiceAux stx.getArgs 0 @[builtinTactic skip] def evalSkip : Tactic := fun stx => pure () @[builtinTactic traceState] def evalTraceState : Tactic := fun stx => do gs ← getUnsolvedGoals; logInfo stx (goalsToMessageData gs) @[builtinTactic «assumption»] def evalAssumption : Tactic := fun stx => liftMetaTactic stx $ fun mvarId => do Meta.assumption mvarId; pure [] @[builtinTactic «intro»] def evalIntro : Tactic := fun stx => match_syntax stx with | `(tactic| intro) => liftMetaTactic stx $ fun mvarId => do (_, mvarId) ← Meta.intro1 mvarId; pure [mvarId] | `(tactic| intro $h) => liftMetaTactic stx $ fun mvarId => do (_, mvarId) ← Meta.intro mvarId h.getId; pure [mvarId] | _ => throwUnsupportedSyntax private def getIntrosSize : Expr → Nat | Expr.forallE _ _ b _ => getIntrosSize b + 1 | Expr.letE _ _ _ b _ => getIntrosSize b + 1 | _ => 0 @[builtinTactic «intros»] def evalIntros : Tactic := fun stx => match_syntax stx with | `(tactic| intros) => liftMetaTactic stx $ fun mvarId => do type ← Meta.getMVarType mvarId; type ← Meta.instantiateMVars type; let n := getIntrosSize type; (_, mvarId) ← Meta.introN mvarId n; pure [mvarId] | `(tactic| intros $ids*) => liftMetaTactic stx $ fun mvarId => do (_, mvarId) ← Meta.introN mvarId ids.size (ids.map Syntax.getId).toList; pure [mvarId] | _ => throwUnsupportedSyntax def getFVarId (id : Syntax) : TacticM FVarId := do fvar? ← liftTermElabM $ Term.isLocalTermId? id true; match fvar? with | some fvar => pure fvar.fvarId! | none => throwError id ("unknown variable '" ++ toString id.getId ++ "'") def getFVarIds (ids : Array Syntax) : TacticM (Array FVarId) := ids.mapM getFVarId @[builtinTactic «revert»] def evalRevert : Tactic := fun stx => match_syntax stx with | `(tactic| revert $hs*) => do (g, gs) ← getMainGoal stx; withMVarContext g $ do fvarIds ← getFVarIds hs; (_, g) ← liftMetaM stx $ Meta.revert g fvarIds; setGoals (g :: gs) | _ => throwUnsupportedSyntax def forEachVar (ref : Syntax) (hs : Array Syntax) (tac : MVarId → FVarId → MetaM MVarId) : TacticM Unit := hs.forM $ fun h => do (g, gs) ← getMainGoal ref; withMVarContext g $ do fvarId ← getFVarId h; g ← liftMetaM ref $ tac g fvarId; setGoals (g :: gs) @[builtinTactic «clear»] def evalClear : Tactic := fun stx => match_syntax stx with | `(tactic| clear $hs*) => forEachVar stx hs Meta.clear | _ => throwUnsupportedSyntax @[builtinTactic «subst»] def evalSubst : Tactic := fun stx => match_syntax stx with | `(tactic| subst $hs*) => forEachVar stx hs Meta.subst | _ => throwUnsupportedSyntax @[builtinTactic paren] def evalParen : Tactic := fun stx => evalTactic (stx.getArg 1) @[builtinTactic nestedTacticBlock] def evalNestedTacticBlock : Tactic := fun stx => focus stx (evalTactic (stx.getArg 1)) @[builtinTactic nestedTacticBlockCurly] def evalNestedTacticBlockCurly : Tactic := evalNestedTacticBlock @[builtinTactic «case»] def evalCase : Tactic := fun stx => match_syntax stx with | `(tactic| case $tag $tac) => do let tag := tag.getId; gs ← getUnsolvedGoals; some g ← gs.findM? (fun g => do mvarDecl ← getMVarDecl g; pure $ tag.isSuffixOf mvarDecl.userName) | throwError stx "tag not found"; let gs := gs.erase g; setGoals [g]; evalTactic tac; done stx; setGoals gs | _ => throwUnsupportedSyntax @[builtinTactic «orelse»] def evalOrelse : Tactic := fun stx => match_syntax stx with | `(tactic| $tac1 <|> $tac2) => evalTactic tac1 <|> evalTactic tac2 | _ => throwUnsupportedSyntax @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.tactic; pure () end Tactic end Elab end Lean
744b60347c28e1978a92521fbb298f8e93bf8852
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/data/rbtree/main.lean
fdffc54f68ed812393b044433217bc70b00cc8aa
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
8,380
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import data.rbtree.find data.rbtree.insert data.rbtree.min_max universes u namespace rbnode variables {α : Type u} {lt : α → α → Prop} lemma is_searchable_of_well_formed {t : rbnode α} [is_strict_weak_order α lt] : t.well_formed lt → is_searchable lt t none none := begin intro h, induction h, { constructor, simp [lift] }, { subst h_n', apply is_searchable_insert, assumption } end open color lemma is_red_black_of_well_formed {t : rbnode α} : t.well_formed lt → ∃ c n, is_red_black t c n := begin intro h, induction h, { existsi black, existsi 0, constructor }, { cases h_ih with c ih, cases ih with n ih, subst h_n', apply insert_is_red_black, assumption } end end rbnode namespace rbtree variables {α : Type u} {lt : α → α → Prop} lemma balanced (t : rbtree α lt) : 2 * t.depth min + 1 ≥ t.depth max := begin cases t with n p, simp only [depth], have := rbnode.is_red_black_of_well_formed p, cases this with _ this, cases this with _ this, apply rbnode.balanced, assumption end lemma not_mem_mk_rbtree : ∀ (a : α), a ∉ mk_rbtree α lt := by simp [has_mem.mem, rbtree.mem, rbnode.mem, mk_rbtree] lemma not_mem_of_empty {t : rbtree α lt} (a : α) : t.empty = tt → a ∉ t := by cases t with n p; cases n; simp [empty, has_mem.mem, rbtree.mem, rbnode.mem, false_implies_iff] lemma mem_of_mem_of_eqv [is_strict_weak_order α lt] {t : rbtree α lt} {a b : α} : a ∈ t → a ≈[lt] b → b ∈ t := begin cases t with n p; simp [has_mem.mem, rbtree.mem]; clear p; induction n; simp [rbnode.mem, strict_weak_order.equiv, false_implies_iff]; intros h₁ h₂; blast_disjs, iterate 2 { { have : rbnode.mem lt b n_lchild := n_ih_lchild h₁ h₂, simp [this] }, { simp [incomp_trans_of lt h₂.swap h₁] }, { have : rbnode.mem lt b n_rchild := n_ih_rchild h₁ h₂, simp [this] } } end variables [decidable_rel lt] lemma insert_ne_mk_rbtree (t : rbtree α lt) (a : α) : t.insert a ≠ mk_rbtree α lt := begin cases t with n p, simp [insert, mk_rbtree], intro h, injection h with h', apply rbnode.insert_ne_leaf lt n a h' end lemma find_correct [is_strict_weak_order α lt] (a : α) (t : rbtree α lt) : a ∈ t ↔ (∃ b, t.find a = some b ∧ a ≈[lt] b) := begin cases t, apply rbnode.find_correct, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_correct_of_total [is_strict_total_order α lt] (a : α) (t : rbtree α lt) : a ∈ t ↔ t.find a = some a := iff.intro (λ h, match iff.mp (find_correct a t) h with | ⟨b, heq, heqv⟩ := by simp [heq, (eq_of_eqv_lt heqv).symm] end) (λ h, iff.mpr (find_correct a t) ⟨a, ⟨h, refl a⟩⟩) lemma find_correct_exact [is_strict_total_order α lt] (a : α) (t : rbtree α lt) : mem_exact a t ↔ t.find a = some a := begin cases t, apply rbnode.find_correct_exact, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_insert_of_eqv [is_strict_weak_order α lt] (t : rbtree α lt) {x y} : x ≈[lt] y → (t.insert x).find y = some x := begin cases t, intro h, apply rbnode.find_insert_of_eqv lt h, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_insert [is_strict_weak_order α lt] (t : rbtree α lt) (x) : (t.insert x).find x = some x := find_insert_of_eqv t (refl x) lemma find_insert_of_disj [is_strict_weak_order α lt] {x y : α} (t : rbtree α lt) : lt x y ∨ lt y x → (t.insert x).find y = t.find y := begin cases t, intro h, apply rbnode.find_insert_of_disj lt h, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_insert_of_not_eqv [is_strict_weak_order α lt] {x y : α} (t : rbtree α lt) : ¬ x ≈[lt] y → (t.insert x).find y = t.find y := begin cases t, intro h, apply rbnode.find_insert_of_not_eqv lt h, apply rbnode.is_searchable_of_well_formed, assumption end lemma find_insert_of_ne [is_strict_total_order α lt] {x y : α} (t : rbtree α lt) : x ≠ y → (t.insert x).find y = t.find y := begin cases t, intro h, have : ¬ x ≈[lt] y := λ h', h (eq_of_eqv_lt h'), apply rbnode.find_insert_of_not_eqv lt this, apply rbnode.is_searchable_of_well_formed, assumption end lemma not_mem_of_find_none [is_strict_weak_order α lt] {a : α} {t : rbtree α lt} : t.find a = none → a ∉ t := λ h, iff.mpr (not_iff_not_of_iff (find_correct a t)) $ begin intro h, cases h with _ h, cases h with h₁ h₂, rw [h] at h₁, contradiction end lemma eqv_of_find_some [is_strict_weak_order α lt] {a b : α} {t : rbtree α lt} : t.find a = some b → a ≈[lt] b := begin cases t, apply rbnode.eqv_of_find_some, apply rbnode.is_searchable_of_well_formed, assumption end lemma eq_of_find_some [is_strict_total_order α lt] {a b : α} {t : rbtree α lt} : t.find a = some b → a = b := λ h, suffices a ≈[lt] b, from eq_of_eqv_lt this, eqv_of_find_some h lemma mem_of_find_some [is_strict_weak_order α lt] {a b : α} {t : rbtree α lt} : t.find a = some b → a ∈ t := λ h, iff.mpr (find_correct a t) ⟨b, ⟨h, eqv_of_find_some h⟩⟩ lemma find_eq_find_of_eqv [is_strict_weak_order α lt] {a b : α} (t : rbtree α lt) : a ≈[lt] b → t.find a = t.find b := begin cases t, apply rbnode.find_eq_find_of_eqv, apply rbnode.is_searchable_of_well_formed, assumption end lemma contains_correct [is_strict_weak_order α lt] (a : α) (t : rbtree α lt) : a ∈ t ↔ (t.contains a = tt) := begin have h := find_correct a t, simp [h, contains], apply iff.intro, { intro h', cases h' with _ h', cases h', simp [*], simp [option.is_some] }, { intro h', cases heq : find t a with v, simp [heq, option.is_some] at h', contradiction, existsi v, simp, apply eqv_of_find_some heq } end lemma mem_insert_of_incomp {a b : α} (t : rbtree α lt) : (¬ lt a b ∧ ¬ lt b a) → a ∈ t.insert b := begin cases t, apply rbnode.mem_insert_of_incomp end lemma mem_insert [is_irrefl α lt] : ∀ (a : α) (t : rbtree α lt), a ∈ t.insert a := begin intros, apply mem_insert_of_incomp, split; apply irrefl_of lt end lemma mem_insert_of_equiv {a b : α} (t : rbtree α lt) : a ≈[lt] b → a ∈ t.insert b := begin cases t, apply rbnode.mem_insert_of_incomp end lemma mem_insert_of_mem [is_strict_weak_order α lt] {a : α} {t : rbtree α lt} (b : α) : a ∈ t → a ∈ t.insert b := begin cases t, apply rbnode.mem_insert_of_mem end lemma equiv_or_mem_of_mem_insert [is_strict_weak_order α lt] {a b : α} {t : rbtree α lt} : a ∈ t.insert b → a ≈[lt] b ∨ a ∈ t := begin cases t, apply rbnode.equiv_or_mem_of_mem_insert end lemma incomp_or_mem_of_mem_ins [is_strict_weak_order α lt] {a b : α} {t : rbtree α lt} : a ∈ t.insert b → (¬ lt a b ∧ ¬ lt b a) ∨ a ∈ t := equiv_or_mem_of_mem_insert lemma eq_or_mem_of_mem_ins [is_strict_total_order α lt] {a b : α} {t : rbtree α lt} : a ∈ t.insert b → a = b ∨ a ∈ t := λ h, suffices a ≈[lt] b ∨ a ∈ t, by simp [eqv_lt_iff_eq] at this; assumption, incomp_or_mem_of_mem_ins h lemma mem_of_min_eq [is_irrefl α lt] {a : α} {t : rbtree α lt} : t.min = some a → a ∈ t := begin cases t, apply rbnode.mem_of_min_eq end lemma mem_of_max_eq [is_irrefl α lt] {a : α} {t : rbtree α lt} : t.max = some a → a ∈ t := begin cases t, apply rbnode.mem_of_max_eq end lemma eq_leaf_of_min_eq_none [is_strict_weak_order α lt] {t : rbtree α lt} : t.min = none → t = mk_rbtree α lt := begin cases t, intro h, congr, apply rbnode.eq_leaf_of_min_eq_none h end lemma eq_leaf_of_max_eq_none [is_strict_weak_order α lt] {t : rbtree α lt} : t.max = none → t = mk_rbtree α lt := begin cases t, intro h, congr, apply rbnode.eq_leaf_of_max_eq_none h end lemma min_is_minimal [is_strict_weak_order α lt] {a : α} {t : rbtree α lt} : t.min = some a → ∀ {b}, b ∈ t → a ≈[lt] b ∨ lt a b := by { cases t, apply rbnode.min_is_minimal, apply rbnode.is_searchable_of_well_formed, assumption } lemma max_is_maximal [is_strict_weak_order α lt] {a : α} {t : rbtree α lt} : t.max = some a → ∀ {b}, b ∈ t → a ≈[lt] b ∨ lt b a := by { cases t, apply rbnode.max_is_maximal, apply rbnode.is_searchable_of_well_formed, assumption } end rbtree
976c7c6783c1f04e6def058aaae6317dad42994e
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/671.lean
cfa840046619dd06da53e7079422433c75e0fc55
[ "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
15
lean
#print nat.add
0a8984df7dfaa28027a8740d1fae78bcde8b0f45
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/test/matrix.lean
01aefc126484e2aaca7b4a991b844a3aa1186a18
[ "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
3,414
lean
import data.matrix.notation import linear_algebra.determinant import group_theory.perm.fin import tactic.norm_swap variables {α β : Type} [semiring α] [ring β] namespace matrix open_locale matrix example {a a' b b' c c' d d' : α} : ![![a, b], ![c, d]] + ![![a', b'], ![c', d']] = ![![a + a', b + b'], ![c + c', d + d']] := by simp example {a a' b b' c c' d d' : β} : ![![a, b], ![c, d]] - ![![a', b'], ![c', d']] = ![![a - a', b - b'], ![c - c', d - d']] := by simp example {a a' b b' c c' d d' : α} : ![![a, b], ![c, d]] ⬝ ![![a', b'], ![c', d']] = ![![a * a' + b * c', a * b' + b * d'], ![c * a' + d * c', c * b' + d * d']] := by simp example {a b c d x y : α} : mul_vec ![![a, b], ![c, d]] ![x, y] = ![a * x + b * y, c * x + d * y] := by simp example {a b c d : α} : minor ![![a, b], ![c, d]] ![1, 0] ![0] = ![![c], ![a]] := by { ext, simp } example {a b c : α} : ![a, b, c] 0 = a := by simp example {a b c : α} : ![a, b, c] 1 = b := by simp example {a b c : α} : ![a, b, c] 2 = c := by simp example {a b c d : α} : ![a, b, c, d] 0 = a := by simp example {a b c d : α} : ![a, b, c, d] 1 = b := by simp example {a b c d : α} : ![a, b, c, d] 2 = c := by simp example {a b c d : α} : ![a, b, c, d] 3 = d := by simp example {a b c d : α} : ![a, b, c, d] 42 = c := by simp example {a b c d e : α} : ![a, b, c, d, e] 0 = a := by simp example {a b c d e : α} : ![a, b, c, d, e] 1 = b := by simp example {a b c d e : α} : ![a, b, c, d, e] 2 = c := by simp example {a b c d e : α} : ![a, b, c, d, e] 3 = d := by simp example {a b c d e : α} : ![a, b, c, d, e] 4 = e := by simp example {a b c d e : α} : ![a, b, c, d, e] 5 = a := by simp example {a b c d e : α} : ![a, b, c, d, e] 6 = b := by simp example {a b c d e : α} : ![a, b, c, d, e] 7 = c := by simp example {a b c d e : α} : ![a, b, c, d, e] 8 = d := by simp example {a b c d e : α} : ![a, b, c, d, e] 9 = e := by simp example {a b c d e : α} : ![a, b, c, d, e] 123 = d := by simp example {a b c d e : α} : ![a, b, c, d, e] 123456789 = e := by simp example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 5 = f := by simp example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 7 = h := by simp example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 37 = f := by simp example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 99 = d := by simp example {α : Type*} [comm_ring α] {a b c d : α} : matrix.det ![![a, b], ![c, d]] = a * d - b * c := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], /- Try this: simp only [matrix.det_succ_row_zero, fin.sum_univ_succ, det_fin_zero, finset.sum_singleton, fin.sum_univ_zero, minor_apply, cons_val_zero, cons_val_succ, fin.succ_above_zero, fin.coe_succ, fin.coe_zero], -/ ring end example {α : Type*} [comm_ring α] (A : matrix (fin 3) (fin 3) α) {a b c d e f g h i : α} : matrix.det ![![a, b, c], ![d, e, f], ![g, h, i]] = a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], /- Try this: simp only [matrix.det_succ_row_zero, fin.sum_univ_succ, det_fin_zero, finset.sum_singleton, fin.sum_univ_zero, minor_apply, cons_val_zero, cons_val_succ, fin.succ_above_zero, fin.succ_succ_above_zero, fin.succ_succ_above_succ, fin.coe_zero, fin.coe_succ, pow_zero, pow_add], -/ ring end end matrix
f369a3b80c22793f172864fe4987ca6ab7175903
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/247.lean
5cf2fff399f4a14d7d38c1fdef2f0a2e3b33a266
[ "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
212
lean
import Lean namespace Lean.Meta def f (e : Expr) : MetaM Bool := do forallTelescope e fun xs b => match (← uinfoldDefinition? b) with | none => pure true | some _ => pure false end Lean.Meta
8e84749dcb3552ad7a09439a9ca7e23dc8091791
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1842.lean
b101bd2d8244bf431810b48f62e636cfe0741527
[ "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
753
lean
variable (R : α → α → Prop) inductive List.Pairwise : List α → Prop | nil : Pairwise [] | cons : ∀ {a : α} {l : List α}, (∀ {a} (_ : a' ∈ l), R a a') → Pairwise l → Pairwise (a :: l) theorem and_assoc : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := ⟨fun ⟨⟨ha, hb⟩, hc⟩ => ⟨ha, hb, hc⟩, fun ⟨ha, hb, hc⟩ => ⟨⟨ha, hb⟩, hc⟩⟩ theorem and_left_comm : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := by rw [← and_assoc, ← and_assoc, @And.comm a b] exact Iff.rfl theorem pairwise_append {l₁ l₂ : List α} : (l₁ ++ l₂).Pairwise R ↔ l₁.Pairwise R ∧ l₂.Pairwise R ∧ ∀ {a} (_ : a ∈ l₁), ∀ {b} (_ : b ∈ l₂), R a b := by induction l₁ <;> simp [*, and_left_comm] repeat sorry
bab47a36e663bfd376c7bb4846572a54eddb90d6
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/field.lean
782fcccd187bcf56042bf24ed0241a1acf49ac34
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
5,145
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 logic.basic algebra.ring algebra.group_with_zero open set universe u variables {α : Type u} @[priority 100] -- see Note [lower instance priority] instance division_ring.to_domain [s : division_ring α] : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, classical.by_contradiction $ λ hn, division_ring.mul_ne_zero (mt or.inl hn) (mt or.inr hn) h ..s, ..(by apply_instance : semiring α) } /-- Every division ring is a `group_with_zero`. -/ @[priority 10] -- see Note [lower instance priority] instance division_ring.to_group_with_zero {K : Type*} [division_ring K] : group_with_zero K := { mul_inv_cancel := λ _, mul_inv_cancel, .. ‹division_ring K›, .. (by apply_instance : semiring K) } /-- Every field is a `comm_group_with_zero`. -/ @[priority 100] -- see Note [lower instance priority] instance field.to_comm_group_with_zero {K : Type*} [field K] : comm_group_with_zero K := { .. (_ : group_with_zero K), .. ‹field K› } @[simp] theorem inv_one [division_ring α] : (1⁻¹ : α) = 1 := by rw [inv_eq_one_div, one_div_one] attribute [simp] inv_inv' section division_ring variables [s : division_ring α] {a b c : α} include s attribute [simp] div_one zero_div div_self lemma neg_inv : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma add_div (a b c : α) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma sub_div (a b c : α) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma division_ring.inv_inj : a⁻¹ = b⁻¹ ↔ a = b := inv_inj'' _ _ lemma division_ring.inv_eq_iff : a⁻¹ = b ↔ b⁻¹ = a := inv_eq_iff lemma div_neg (a : α) : a / -b = -(a / b) := by rw [← div_neg_eq_neg_div] end division_ring @[priority 100] -- see Note [lower instance priority] instance field.to_integral_domain [F : field α] : integral_domain α := { ..F, ..division_ring.to_domain } section variables [field α] {a b c d : α} lemma inv_add_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] lemma add_div' (a b c : α) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc lemma sub_div' (a b c : α) (hc : c ≠ 0) : b - a / c = (b * c - a) / c := by simpa using div_sub_div b a one_ne_zero hc lemma div_add' (a b c : α) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] lemma div_sub' (a b c : α) (hc : c ≠ 0) : a / c - b = (a - c * b) / c := by simpa using div_sub_div a b hc one_ne_zero end namespace ring_hom section variables {β : Type*} [division_ring α] [division_ring β] (f : α →+* β) {x y : α} lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := ⟨mt $ λ h, h.symm ▸ f.map_zero, λ x0 h, one_ne_zero $ by rw [← f.map_one, ← mul_inv_cancel x0, f.map_mul, h, zero_mul]⟩ lemma map_eq_zero : f x = 0 ↔ x = 0 := by haveI := classical.dec; exact not_iff_not.1 f.map_ne_zero lemma map_inv : f x⁻¹ = (f x)⁻¹ := begin classical, by_cases h : x = 0, by simp [h], apply (domain.mul_left_inj (f.map_ne_zero.2 h)).1, rw [mul_inv_cancel (f.map_ne_zero.2 h), ← f.map_mul, mul_inv_cancel h, f.map_one] end lemma map_div : f (x / y) = f x / f y := (f.map_mul _ _).trans $ congr_arg _ $ f.map_inv lemma injective : function.injective f := f.injective_iff.2 (λ a ha, classical.by_contradiction $ λ ha0, by simpa [ha, f.map_mul, f.map_one, zero_ne_one] using congr_arg f (mul_inv_cancel ha0)) end end ring_hom namespace is_ring_hom open ring_hom (of) section variables {β : Type*} [division_ring α] [division_ring β] variables (f : α → β) [is_ring_hom f] {x y : α} lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := (of f).map_ne_zero lemma map_eq_zero : f x = 0 ↔ x = 0 := (of f).map_eq_zero lemma map_inv : f x⁻¹ = (f x)⁻¹ := (of f).map_inv lemma map_div : f (x / y) = f x / f y := (of f).map_div lemma injective : function.injective f := (of f).injective end end is_ring_hom section field_simp mk_simp_attribute field_simps "The simpset `field_simps` is used by the tactic `field_simp` to reduce an expression in a field to an expression of the form `n / d` where `n` and `d` are division-free." lemma mul_div_assoc' {α : Type*} [division_ring α] (a b c : α) : a * (b / c) = (a * b) / c := by simp [mul_div_assoc] lemma neg_div' {α : Type*} [division_ring α] (a b : α) : - (b / a) = (-b) / a := by simp [neg_div] attribute [field_simps] div_add_div_same inv_eq_one_div div_mul_eq_mul_div div_add' add_div' div_div_eq_div_mul mul_div_assoc' div_eq_div_iff div_eq_iff eq_div_iff mul_ne_zero' div_div_eq_mul_div neg_div' two_ne_zero div_sub_div div_sub' sub_div' end field_simp
6ae76b52cb30f68c39401faad9a0e35c3b76fa61
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/1766.lean
16ece880ae4919c7d9dca3aa04b623c44eaab3c1
[ "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
741
lean
inductive is_some (x : option nat) : Prop | mk : ∀ value : nat, x = some value → is_some def value_1 (x : option nat) (H : is_some x) : nat := begin destruct x; intros, {destruct H, -- ERROR: `is_some` can only eliminate into Prop intros, clear _x_2, rw _x at _x_1, contradiction}, {assumption} end def value_2 (x : option nat) (H : is_some x) : x = x := begin destruct x; intros, {destruct H, intros, rw a at ᾰ}, {refl} end inductive is_some' (x : option nat) : Type | mk : ∀ value : nat, x = some value → is_some' def value_3 (x : option nat) (H : is_some' x) : nat := begin destruct x; intros, {destruct H, intros, clear a_1, rw a at ᾰ, contradiction}, {assumption} end
81c227e4cd6cc74ece1d6f424375a479850ab49c
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/inj2.lean
c3cb498e3e76677f2b00159f614b6feb42b13de8
[ "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
1,142
lean
new_frontend universes u v inductive Vec2 (α : Type u) (β : Type v) : Nat → Type (max u v) | nil : Vec2 α β 0 | cons : α → β → forall {n}, Vec2 α β n → Vec2 α β (n+1) inductive Fin2 : Nat → Type | zero (n : Nat) : Fin2 (n+1) | succ {n : Nat} (s : Fin2 n) : Fin2 (n+1) theorem test1 {α β} {n} (a₁ a₂ : α) (b₁ b₂ : β) (v w : Vec2 α β n) (h : Vec2.cons a₁ b₁ v = Vec2.cons a₂ b₂ w) : a₁ = a₂ := by { injection h; assumption } theorem test2 {α β} {n} (a₁ a₂ : α) (b₁ b₂ : β) (v w : Vec2 α β n) (h : Vec2.cons a₁ b₁ v = Vec2.cons a₂ b₂ w) : v = w := by { injection h with h1 h2 h3 h4; assumption } theorem test3 {α β} {n} (a₁ a₂ : α) (b₁ b₂ : β) (v w : Vec2 α β n) (h : Vec2.cons a₁ b₁ v = Vec2.cons a₂ b₂ w) : v = w := by { injection h with _ _ _ h4; exact h4 } theorem test4 {α} (v : Fin2 0) : α := by cases v def test5 {α β} {n} (v : Vec2 α β (n+1)) : α := by cases v with | cons h1 h2 n tail => exact h1 def test6 {α β} {n} (v : Vec2 α β (n+2)) : α := by cases v with | cons h1 h2 n tail => exact h1
ceffeb6d74d172aaff0d2a018ab95c1fb8c71a7a
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/field_theory/separable_degree.lean
62efddcfb545298deb8a3ce0609e8f6948b917b4
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
6,476
lean
/- Copyright (c) 2021 Jakob Scholbach. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob Scholbach -/ import field_theory.separable import algebra.algebra.basic import data.polynomial.degree import algebra.char_p.exp_char /-! # Separable degree This file contains basics about the separable degree of a polynomial. ## Main results - `is_separable_contraction`: is the condition that `g(x^(q^m)) = f(x)` for some `m : ℕ` - `has_separable_contraction`: the condition of having a separable contraction - `has_separable_contraction.degree`: the separable degree, defined as the degree of some separable contraction - `irreducible_has_separable_contraction`: any nonzero irreducible polynomial can be contracted to a separable polynomial - `has_separable_contraction.dvd_degree'`: the degree of a separable contraction divides the degree, in function of the exponential characteristic of the field - `has_separable_contraction.dvd_degree` and `has_separable_contraction.eq_degree` specialize the statement of `separable_degree_dvd_degree` - `is_separable_contraction.degree_eq`: the separable degree is well-defined, implemented as the statement that the degree of any separable contraction equals `has_separable_contraction.degree` ## Tags separable degree, degree, polynomial -/ namespace polynomial noncomputable theory open_locale classical section comm_semiring variables {F : Type} [comm_semiring F] (q : ℕ) /-- A separable contraction of a polynomial `f` is a separable polynomial `g` such that `g(x^(q^m)) = f(x)` for some `m : ℕ`.-/ def is_separable_contraction (f : polynomial F) (g : polynomial F) : Prop := g.separable ∧ ∃ m : ℕ, expand F (q^m) g = f /-- The condition of having a separable contration. -/ def has_separable_contraction (f : polynomial F) : Prop := ∃ g : polynomial F, is_separable_contraction q f g variables {q} {f : polynomial F} (hf : has_separable_contraction q f) /-- A choice of a separable contraction. -/ def has_separable_contraction.contraction : polynomial F := classical.some hf /-- The separable degree of a polynomial is the degree of a given separable contraction. -/ def has_separable_contraction.degree : ℕ := hf.contraction.nat_degree /-- The separable degree divides the degree, in function of the exponential characteristic of F. -/ lemma is_separable_contraction.dvd_degree' {g} (hf : is_separable_contraction q f g) : ∃ m : ℕ, g.nat_degree * (q ^ m) = f.nat_degree := begin obtain ⟨m, rfl⟩ := hf.2, use m, rw nat_degree_expand, end lemma has_separable_contraction.dvd_degree' : ∃ m : ℕ, hf.degree * (q ^ m) = f.nat_degree := (classical.some_spec hf).dvd_degree' /-- The separable degree divides the degree. -/ lemma has_separable_contraction.dvd_degree : hf.degree ∣ f.nat_degree := let ⟨a, ha⟩ := hf.dvd_degree' in dvd.intro (q ^ a) ha /-- In exponential characteristic one, the separable degree equals the degree. -/ lemma has_separable_contraction.eq_degree {f : polynomial F} (hf : has_separable_contraction 1 f) : hf.degree = f.nat_degree := let ⟨a, ha⟩ := hf.dvd_degree' in by rw [←ha, one_pow a, mul_one] end comm_semiring section field variables {F : Type} [field F] variables (q : ℕ) {f : polynomial F} (hf : has_separable_contraction q f) /-- Every irreducible polynomial can be contracted to a separable polynomial. https://stacks.math.columbia.edu/tag/09H0 -/ lemma irreducible_has_separable_contraction (q : ℕ) [hF : exp_char F q] (f : polynomial F) [irred : irreducible f] (fn : f ≠ 0) : has_separable_contraction q f := begin casesI hF, { use f, exact ⟨irreducible.separable irred, ⟨0, by rw [pow_zero, expand_one]⟩⟩ }, { haveI qp : fact (nat.prime q) := ⟨hF_hprime⟩, rcases exists_separable_of_irreducible q irred fn with ⟨n, g, hgs, hge⟩, exact ⟨g, hgs, n, hge⟩, } end /-- A helper lemma: if two expansions (along the positive characteristic) of two polynomials `g` and `g'` agree, and the one with the larger degree is separable, then their degrees are the same. -/ lemma contraction_degree_eq_aux [hq : fact q.prime] [hF : char_p F q] (g g' : polynomial F) (m m' : ℕ) (h_expand : expand F (q^m) g = expand F (q^m') g') (h : m < m') (hg : g.separable): g.nat_degree = g'.nat_degree := begin obtain ⟨s, rfl⟩ := nat.exists_eq_add_of_lt h, rw [add_assoc, pow_add, expand_mul] at h_expand, let aux := expand_injective (pow_pos hq.1.pos m) h_expand, rw aux at hg, have := (is_unit_or_eq_zero_of_separable_expand q (s + 1) hg).resolve_right s.succ_ne_zero, rw [aux, nat_degree_expand, nat_degree_eq_of_degree_eq_some (degree_eq_zero_of_is_unit this), zero_mul] end /-- If two expansions (along the positive characteristic) of two separable polynomials `g` and `g'` agree, then they have the same degree. -/ theorem contraction_degree_eq_or_insep [hq : fact q.prime] [char_p F q] (g g' : polynomial F) (m m' : ℕ) (h_expand : expand F (q^m) g = expand F (q^m') g') (hg : g.separable) (hg' : g'.separable) : g.nat_degree = g'.nat_degree := begin by_cases h : m = m', { -- if `m = m'` then we show `g.nat_degree = g'.nat_degree` by unfolding the definitions rw h at h_expand, have expand_deg : ((expand F (q ^ m')) g).nat_degree = (expand F (q ^ m') g').nat_degree, by rw h_expand, rw [nat_degree_expand (q^m') g, nat_degree_expand (q^m') g'] at expand_deg, apply nat.eq_of_mul_eq_mul_left (pow_pos hq.1.pos m'), rw [mul_comm] at expand_deg, rw expand_deg, rw [mul_comm] }, { cases ne.lt_or_lt h, { exact contraction_degree_eq_aux q g g' m m' h_expand h_1 hg }, { exact (contraction_degree_eq_aux q g' g m' m h_expand.symm h_1 hg').symm, } } end /-- The separable degree equals the degree of any separable contraction, i.e., it is unique. -/ theorem is_separable_contraction.degree_eq [hF : exp_char F q] (g : polynomial F) (hg : is_separable_contraction q f g) : g.nat_degree = hf.degree := begin casesI hF, { rcases hg with ⟨g, m, hm⟩, rw [one_pow, expand_one] at hm, rw hf.eq_degree, rw hm, }, { rcases hg with ⟨hg, m, hm⟩, let g' := classical.some hf, cases (classical.some_spec hf).2 with m' hm', haveI : fact q.prime := fact_iff.2 hF_hprime, apply contraction_degree_eq_or_insep q g g' m m', rw [hm, hm'], exact hg, exact (classical.some_spec hf).1 } end end field end polynomial
75ab4f287922323e3478e55ab76ba5f40e8717a9
43390109ab88557e6090f3245c47479c123ee500
/src/Topology/Problem_Sheets/ps_2_ex4a.lean
8f26ac1c87cdf801d72b5591455e8515a31ea263
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,035
lean
-- Setup for doing the topology problem sheet 2 exercise 4 import analysis.topology.continuity import analysis.topology.topological_space import analysis.topology.infinite_sum import analysis.topology.topological_structures import analysis.topology.uniform_space universe u open set filter lattice classical -- A function that checks if a collection is sets satisfies the axioms of a topology definition is_open_sets {α : Type u} (is_open : set α → Prop) := is_open univ ∧ (∀s t, is_open s → is_open t → is_open (s ∩ t)) ∧ (∀s, (∀t∈s, is_open t) → is_open (⋃₀ s)) -- A function that converts a proof that a collection of sets satisfies the axioms of a topology into an actual topology (see the definition of a topology in mathlib) definition is_to_top {α : Type u} (is_open : set α → Prop) (H : is_open_sets (is_open)) : topological_space α := { is_open := is_open, is_open_univ := H.left, is_open_inter := H.right.left, is_open_sUnion := H.right.right } -- A function that converts a topology into a proof that the given collection of sets satisfies the axioms of a topology. definition top_to_is {α : Type u} (T : topological_space α) : is_open_sets (T.is_open) := ⟨T.is_open_univ,T.is_open_inter,T.is_open_sUnion⟩ -- A proof that given two collections of sets that satisfy the axioms of a topology, their intersection satisfies the axioms of a topology. theorem exercisefoura {α : Type u} {T1_sets T2_sets : set α → Prop} : is_open_sets T1_sets → is_open_sets T2_sets → is_open_sets (λ (a : set α), and (T1_sets a) (T2_sets a) := begin intros H1 H2, unfold is_open_sets, split, exact ⟨H1.left, H2.left⟩, split, intros s t H3 H4, exact ⟨H1.right.left s t H3.left H4.left, H2.right.left s t H3.right H4.right⟩, intros I H3, split, have H4 : ∀ (t : set α), t ∈ I → T1_sets t, intros A H5, exact (H3 A H5).left, exact H1.right.right I H4, have H4 : ∀ (t : set α), t ∈ I → T2_sets t, intros A H5, exact (H3 A H5).right, exact H2.right.right I H4, end
122740bb1e2f8f696c3b361d5b782a726b212242
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Meta/AppBuilder.lean
85d23c70a1bc6761d39f41917dacce3d2af49877
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,884
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Structure import Lean.Util.Recognizers import Lean.Meta.SynthInstance import Lean.Meta.Check namespace Lean.Meta variables {m : Type → Type} [MonadLiftT MetaM m] private def mkIdImp (e : Expr) : MetaM Expr := do let type ← inferType e let u ← getLevel type pure $ mkApp2 (mkConst `id [u]) type e /-- Return `id e` -/ def mkId (e : Expr) : m Expr := liftMetaM $ mkIdImp e def mkIdRhsImp (e : Expr) : MetaM Expr := do let type ← inferType e let u ← getLevel type pure $ mkApp2 (mkConst `idRhs [u]) type e /-- Return `idRhs e` -/ def mkIdRhs (e : Expr) : m Expr := liftMetaM $ mkIdRhsImp e private def mkExpectedTypeHintImp (e : Expr) (expectedType : Expr) : MetaM Expr := do let u ← getLevel expectedType pure $ mkApp2 (mkConst `id [u]) expectedType e /-- Given `e` s.t. `inferType e` is definitionally equal to `expectedType`, return term `@id expectedType e`. -/ def mkExpectedTypeHint (e : Expr) (expectedType : Expr) : m Expr := liftMetaM $ mkExpectedTypeHintImp e expectedType private def mkEqImp (a b : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType pure $ mkApp3 (mkConst `Eq [u]) aType a b def mkEq (a b : Expr) : m Expr := liftMetaM $ mkEqImp a b private def mkHEqImp (a b : Expr) : MetaM Expr := do let aType ← inferType a let bType ← inferType b let u ← getLevel aType pure $ mkApp4 (mkConst `HEq [u]) aType a bType b def mkHEq (a b : Expr) : m Expr := liftMetaM $ mkHEqImp a b private def mkEqReflImp (a : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType pure $ mkApp2 (mkConst `Eq.refl [u]) aType a def mkEqRefl (a : Expr) : m Expr := liftMetaM $ mkEqReflImp a private def mkHEqReflImp (a : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType pure $ mkApp2 (mkConst `HEq.refl [u]) aType a def mkHEqRefl (a : Expr) : m Expr := liftMetaM $ mkHEqReflImp a private def infer (h : Expr) : MetaM Expr := do let hType ← inferType h whnfD hType private def hasTypeMsg (e type : Expr) : MessageData := m!"{indentExpr e}\nhas type{indentExpr type}" private def throwAppBuilderException {α} (op : Name) (msg : MessageData) : MetaM α := throwError! "AppBuilder for '{op}', {msg}" private def mkEqSymmImp (h : Expr) : MetaM Expr := if h.isAppOf `Eq.refl then pure h else do let hType ← infer h match hType.eq? with | some (α, a, b) => do let u ← getLevel α; pure $ mkApp4 (mkConst `Eq.symm [u]) α a b h | none => throwAppBuilderException `Eq.symm ("equality proof expected" ++ hasTypeMsg h hType) def mkEqSymm (h : Expr) : m Expr := liftMetaM $ mkEqSymmImp h private def mkEqTransImp (h₁ h₂ : Expr) : MetaM Expr := if h₁.isAppOf `Eq.refl then pure h₂ else if h₂.isAppOf `Eq.refl then pure h₁ else do let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.eq?, hType₂.eq? with | some (α, a, b), some (_, _, c) => do let u ← getLevel α; pure $ mkApp6 (mkConst `Eq.trans [u]) α a b c h₁ h₂ | none, _ => throwAppBuilderException `Eq.trans ("equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException `Eq.trans ("equality proof expected" ++ hasTypeMsg h₂ hType₂) def mkEqTrans (h₁ h₂ : Expr) : m Expr := liftMetaM $ mkEqTransImp h₁ h₂ private def mkHEqSymmImp (h : Expr) : MetaM Expr := if h.isAppOf `HEq.refl then pure h else do let hType ← infer h match hType.heq? with | some (α, a, β, b) => do let u ← getLevel α; pure $ mkApp5 (mkConst `HEq.symm [u]) α β a b h | none => throwAppBuilderException `HEq.symm ("heterogeneous equality proof expected" ++ hasTypeMsg h hType) def mkHEqSymm (h : Expr) : m Expr := liftMetaM $ mkHEqSymmImp h private def mkHEqTransImp (h₁ h₂ : Expr) : MetaM Expr := do if h₁.isAppOf `HEq.refl then pure h₂ else if h₂.isAppOf `HEq.refl then pure h₁ else do let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.heq?, hType₂.heq? with | some (α, a, β, b), some (_, _, γ, c) => let u ← getLevel α; pure $ mkApp8 (mkConst `HEq.trans [u]) α β γ a b c h₁ h₂ | none, _ => throwAppBuilderException `HEq.trans ("heterogeneous equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException `HEq.trans ("heterogeneous equality proof expected" ++ hasTypeMsg h₂ hType₂) def mkHEqTrans (h₁ h₂ : Expr) : m Expr := liftMetaM $ mkHEqTransImp h₁ h₂ private def mkEqOfHEqImp (h : Expr) : MetaM Expr := do let hType ← infer h match hType.heq? with | some (α, a, β, b) => unless (← isDefEq α β) do throwAppBuilderException `eqOfHEq m!"heterogeneous equality types are not definitionally equal{indentExpr α}\nis not definitionally equal to{indentExpr β}" let u ← getLevel α pure $ mkApp4 (mkConst `eqOfHEq [u]) α a b h | _ => throwAppBuilderException `HEq.trans m!"heterogeneous equality proof expected{indentExpr h}" def mkEqOfHEq (h : Expr) : m Expr := liftMetaM $ mkEqOfHEqImp h private def mkCongrArgImp (f h : Expr) : MetaM Expr := do let hType ← infer h let fType ← infer f match fType.arrow?, hType.eq? with | some (α, β), some (_, a, b) => let u ← getLevel α; let v ← getLevel β; pure $ mkApp6 (mkConst `congrArg [u, v]) α β a b f h | none, _ => throwAppBuilderException `congrArg ("non-dependent function expected" ++ hasTypeMsg f fType) | _, none => throwAppBuilderException `congrArg ("equality proof expected" ++ hasTypeMsg h hType) def mkCongrArg (f h : Expr) : m Expr := liftMetaM $ mkCongrArgImp f h private def mkCongrFunImp (h a : Expr) : MetaM Expr := do let hType ← infer h match hType.eq? with | some (ρ, f, g) => do let ρ ← whnfD ρ match ρ with | Expr.forallE n α β _ => do let β' := Lean.mkLambda n BinderInfo.default α β let u ← getLevel α let v ← getLevel (mkApp β' a) pure $ mkApp6 (mkConst `congrFun [u, v]) α β' f g h a | _ => throwAppBuilderException `congrFun ("equality proof between functions expected" ++ hasTypeMsg h hType) | _ => throwAppBuilderException `congrFun ("equality proof expected" ++ hasTypeMsg h hType) def mkCongrFun (h a : Expr) : m Expr := liftMetaM $ mkCongrFunImp h a private def mkCongrImp (h₁ h₂ : Expr) : MetaM Expr := do let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.eq?, hType₂.eq? with | some (ρ, f, g), some (α, a, b) => do let ρ ← whnfD ρ match ρ.arrow? with | some (_, β) => do let u ← getLevel α let v ← getLevel β pure $ mkApp8 (mkConst `congr [u, v]) α β f g a b h₁ h₂ | _ => throwAppBuilderException `congr ("non-dependent function expected" ++ hasTypeMsg h₁ hType₁) | none, _ => throwAppBuilderException `congr ("equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException `congr ("equality proof expected" ++ hasTypeMsg h₂ hType₂) def mkCongr (h₁ h₂ : Expr) : m Expr := liftMetaM $ mkCongrImp h₁ h₂ private def mkAppMFinal (methodName : Name) (f : Expr) (args : Array Expr) (instMVars : Array MVarId) : MetaM Expr := do instMVars.forM fun mvarId => do let mvarDecl ← getMVarDecl mvarId let mvarVal ← synthInstance mvarDecl.type assignExprMVar mvarId mvarVal let result ← instantiateMVars (mkAppN f args) if (← hasAssignableMVar result) then throwAppBuilderException methodName ("result contains metavariables" ++ indentExpr result) pure result private partial def mkAppMArgs (f : Expr) (fType : Expr) (xs : Array Expr) : MetaM Expr := let rec loop (type : Expr) (i : Nat) (j : Nat) (args : Array Expr) (instMVars : Array MVarId) : MetaM Expr := do if i >= xs.size then mkAppMFinal `mkAppM f args instMVars else match type with | Expr.forallE n d b c => let d := d.instantiateRevRange j args.size args match c.binderInfo with | BinderInfo.implicit => let mvar ← mkFreshExprMVar d MetavarKind.natural n loop b i j (args.push mvar) instMVars | BinderInfo.instImplicit => let mvar ← mkFreshExprMVar d MetavarKind.synthetic n loop b i j (args.push mvar) (instMVars.push mvar.mvarId!) | _ => let x := xs[i] let xType ← inferType x if (← isDefEq d xType) then loop b (i+1) j (args.push x) instMVars else throwAppTypeMismatch (mkAppN f args) x | type => let type := type.instantiateRevRange j args.size args let type ← whnfD type if type.isForall then loop type i args.size args instMVars else throwAppBuilderException `mkAppM m!"too many explicit arguments provided to{indentExpr f}\narguments{indentD xs}" loop fType 0 0 #[] #[] private def mkFun (constName : Name) : MetaM (Expr × Expr) := do let cinfo ← getConstInfo constName let us ← cinfo.lparams.mapM fun _ => mkFreshLevelMVar let f := mkConst constName us let fType := cinfo.instantiateTypeLevelParams us pure (f, fType) /-- Return the application `constName xs`. It tries to fill the implicit arguments before the last element in `xs`. Remark: ``mkAppM `arbitrary #[α]`` returns `@arbitrary.{u} α` without synthesizing the implicit argument occurring after `α`. Given a `x : (([Decidable p] → Bool) × Nat`, ``mkAppM `Prod.fst #[x]`` returns `@Prod.fst ([Decidable p] → Bool) Nat x` -/ def mkAppM (constName : Name) (xs : Array Expr) : m Expr := liftMetaM do traceCtx `Meta.appBuilder $ withNewMCtxDepth do let (f, fType) ← mkFun constName let r ← mkAppMArgs f fType xs trace[Meta.appBuilder]! "constName: {constName}, xs: {xs}, result: {r}" pure r private partial def mkAppOptMAux (f : Expr) (xs : Array (Option Expr)) : Nat → Array Expr → Nat → Array MVarId → Expr → MetaM Expr | i, args, j, instMVars, Expr.forallE n d b c => do let d := d.instantiateRevRange j args.size args if h : i < xs.size then match xs.get ⟨i, h⟩ with | none => match c.binderInfo with | BinderInfo.instImplicit => do let mvar ← mkFreshExprMVar d MetavarKind.synthetic n mkAppOptMAux f xs (i+1) (args.push mvar) j (instMVars.push mvar.mvarId!) b | _ => do let mvar ← mkFreshExprMVar d MetavarKind.natural n mkAppOptMAux f xs (i+1) (args.push mvar) j instMVars b | some x => let xType ← inferType x if (← isDefEq d xType) then mkAppOptMAux f xs (i+1) (args.push x) j instMVars b else throwAppTypeMismatch (mkAppN f args) x else mkAppMFinal `mkAppOptM f args instMVars | i, args, j, instMVars, type => do let type := type.instantiateRevRange j args.size args let type ← whnfD type if type.isForall then mkAppOptMAux f xs i args args.size instMVars type else if i == xs.size then mkAppMFinal `mkAppOptM f args instMVars else do let xs : Array Expr := xs.foldl (fun r x? => match x? with | none => r | some x => r.push x) #[] throwAppBuilderException `mkAppOptM ("too many arguments provided to" ++ indentExpr f ++ Format.line ++ "arguments" ++ xs) /-- Similar to `mkAppM`, but it allows us to specify which arguments are provided explicitly using `Option` type. Example: Given `Pure.pure {m : Type u → Type v} [Pure m] {α : Type u} (a : α) : m α`, ``` mkAppOptM `Pure.pure #[m, none, none, a] ``` returns a `Pure.pure` application if the instance `Pure m` can be synthesized, and the universes match. Note that, ``` mkAppM `Pure.pure #[a] ``` fails because the only explicit argument `(a : α)` is not sufficient for inferring the remaining arguments, we would need the expected type. -/ def mkAppOptM (constName : Name) (xs : Array (Option Expr)) : m Expr := liftMetaM do traceCtx `Meta.appBuilder $ withNewMCtxDepth do let (f, fType) ← mkFun constName mkAppOptMAux f xs 0 #[] 0 #[] fType private def mkEqNDRecImp (motive h1 h2 : Expr) : MetaM Expr := do if h2.isAppOf `Eq.refl then pure h1 else let h2Type ← infer h2 match h2Type.eq? with | none => throwAppBuilderException `Eq.ndrec ("equality proof expected" ++ hasTypeMsg h2 h2Type) | some (α, a, b) => let u2 ← getLevel α let motiveType ← infer motive match motiveType with | Expr.forallE _ _ (Expr.sort u1 _) _ => pure $ mkAppN (mkConst `Eq.ndrec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwAppBuilderException `Eq.ndrec ("invalid motive" ++ indentExpr motive) def mkEqNDRec (motive h1 h2 : Expr) : m Expr := liftMetaM $ mkEqNDRecImp motive h1 h2 private def mkEqRecImp (motive h1 h2 : Expr) : MetaM Expr := do if h2.isAppOf `Eq.refl then pure h1 else let h2Type ← infer h2 match h2Type.eq? with | none => throwAppBuilderException `Eq.rec ("equality proof expected" ++ indentExpr h2) | some (α, a, b) => let u2 ← getLevel α let motiveType ← infer motive match motiveType with | Expr.forallE _ _ (Expr.forallE _ _ (Expr.sort u1 _) _) _ => pure $ mkAppN (mkConst `Eq.rec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwAppBuilderException `Eq.rec ("invalid motive" ++ indentExpr motive) def mkEqRec (motive h1 h2 : Expr) : m Expr := liftMetaM $ mkEqRecImp motive h1 h2 def mkEqMP (eqProof pr : Expr) : m Expr := mkAppM `Eq.mp #[eqProof, pr] def mkEqMPR (eqProof pr : Expr) : m Expr := mkAppM `Eq.mpr #[eqProof, pr] private def mkNoConfusionImp (target : Expr) (h : Expr) : MetaM Expr := do let type ← inferType h let type ← whnf type match type.eq? with | none => throwAppBuilderException `noConfusion ("equality expected" ++ hasTypeMsg h type) | some (α, a, b) => let α ← whnf α matchConstInduct α.getAppFn (fun _ => throwAppBuilderException `noConfusion ("inductive type expected" ++ indentExpr α)) fun v us => do let u ← getLevel target pure $ mkAppN (mkConst (Name.mkStr v.name "noConfusion") (u :: us)) (α.getAppArgs ++ #[target, a, b, h]) def mkNoConfusion (target : Expr) (h : Expr) : m Expr := liftMetaM $ mkNoConfusionImp target h def mkPure (monad : Expr) (e : Expr) : m Expr := mkAppOptM `Pure.pure #[monad, none, none, e] /-- `mkProjection s fieldName` return an expression for accessing field `fieldName` of the structure `s`. Remark: `fieldName` may be a subfield of `s`. -/ private partial def mkProjectionImp : Expr → Name → MetaM Expr | s, fieldName => do let type ← inferType s let type ← whnf type match type.getAppFn with | Expr.const structName us _ => let env ← getEnv unless isStructureLike env structName do throwAppBuilderException `mkProjection ("structure expected" ++ hasTypeMsg s type) match getProjFnForField? env structName fieldName with | some projFn => let params := type.getAppArgs pure $ mkApp (mkAppN (mkConst projFn us) params) s | none => do let fields := getStructureFields env structName let r? ← fields.findSomeM? fun fieldName' => do match isSubobjectField? env structName fieldName' with | none => pure none | some _ => let parent ← mkProjectionImp s fieldName' (do let r ← mkProjectionImp parent fieldName; pure $ some r) <|> pure none match r? with | some r => pure r | none => throwAppBuilderException `mkProjectionn ("invalid field name '" ++ toString fieldName ++ "' for" ++ hasTypeMsg s type) | _ => throwAppBuilderException `mkProjectionn ("structure expected" ++ hasTypeMsg s type) def mkProjection (s : Expr) (fieldName : Name) : m Expr := liftMetaM $ mkProjectionImp s fieldName private def mkListLitAux (nil : Expr) (cons : Expr) : List Expr → Expr | [] => nil | x::xs => mkApp (mkApp cons x) (mkListLitAux nil cons xs) private def mkListLitImp (type : Expr) (xs : List Expr) : MetaM Expr := do let u ← getDecLevel type let nil := mkApp (mkConst `List.nil [u]) type match xs with | [] => pure nil | _ => let cons := mkApp (mkConst `List.cons [u]) type pure $ mkListLitAux nil cons xs def mkListLit (type : Expr) (xs : List Expr) : m Expr := liftMetaM $ mkListLitImp type xs def mkArrayLit (type : Expr) (xs : List Expr) : m Expr := liftMetaM do let u ← getDecLevel type let listLit ← mkListLit type xs pure (mkApp (mkApp (mkConst `List.toArray [u]) type) listLit) def mkSorry (type : Expr) (synthetic : Bool) : m Expr := liftMetaM do let u ← getLevel type pure $ mkApp2 (mkConst `sorryAx [u]) type (toExpr synthetic) /-- Return `Decidable.decide p` -/ def mkDecide (p : Expr) : m Expr := mkAppOptM `Decidable.decide #[p, none] /-- Return a proof for `p : Prop` using `decide p` -/ def mkDecideProof (p : Expr) : m Expr := liftMetaM do let decP ← mkDecide p let decEqTrue ← mkEq decP (mkConst `Bool.true) let h ← mkEqRefl (mkConst `Bool.true) let h ← mkExpectedTypeHint h decEqTrue mkAppM `ofDecideEqTrue #[h] /-- Return `a < b` -/ def mkLt (a b : Expr) : m Expr := mkAppM `HasLess.Less #[a, b] /-- Return `a <= b` -/ def mkLe (a b : Expr) : m Expr := mkAppM `HasLessEq.LessEq #[a, b] /-- Return `arbitrary α` -/ def mkArbitrary (α : Expr) : m Expr := mkAppOptM `arbitrary #[α, none] builtin_initialize registerTraceClass `Meta.appBuilder end Lean.Meta
70593bddc9b21696c6ce3f04c306efa43edfc40d
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/group_theory/perm/sign.lean
ff6c4edfad97850303332bd863cec04f860f74bd
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
32,958
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.fintype universes u v open equiv function fintype finset variables {α : Type u} {β : Type v} namespace equiv.perm def subtype_perm (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) : perm {x // p x} := ⟨λ x, ⟨f x, (h _).1 x.2⟩, λ x, ⟨f⁻¹ x, (h (f⁻¹ x)).2 $ by simpa using x.2⟩, λ _, by simp, λ _, by simp⟩ @[simp] lemma subtype_perm_one (p : α → Prop) (h : ∀ x, p x ↔ p ((1 : perm α) x)) : @subtype_perm α 1 p h = 1 := equiv.ext _ _ $ λ ⟨_, _⟩, rfl def of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : perm α := ⟨λ x, if h : p x then f ⟨x, h⟩ else x, λ x, if h : p x then f⁻¹ ⟨x, h⟩ else x, λ x, have h : ∀ h : p x, p (f ⟨x, h⟩), from λ h, (f ⟨x, h⟩).2, by simp; split_ifs at *; simp * at *, λ x, have h : ∀ h : p x, p (f⁻¹ ⟨x, h⟩), from λ h, (f⁻¹ ⟨x, h⟩).2, by simp; split_ifs at *; simp * at *⟩ instance of_subtype.is_group_hom {p : α → Prop} [decidable_pred p] : is_group_hom (@of_subtype α p _) := ⟨λ f g, equiv.ext _ _ $ λ x, begin rw [of_subtype, of_subtype, of_subtype], by_cases h : p x, { have h₁ : p (f (g ⟨x, h⟩)), from (f (g ⟨x, h⟩)).2, have h₂ : p (g ⟨x, h⟩), from (g ⟨x, h⟩).2, simp [h, h₁, h₂] }, { simp [h] } end⟩ @[simp] lemma of_subtype_one (p : α → Prop) [decidable_pred p] : @of_subtype α p _ 1 = 1 := is_group_hom.map_one of_subtype lemma eq_inv_iff_eq {f : perm α} {x y : α} : x = f⁻¹ y ↔ f x = y := by conv {to_lhs, rw [← injective.eq_iff f.injective, apply_inv_self]} lemma inv_eq_iff_eq {f : perm α} {x y : α} : f⁻¹ x = y ↔ x = f y := by rw [eq_comm, eq_inv_iff_eq, eq_comm] def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x @[symm] lemma disjoint.symm {f g : perm α} : disjoint f g → disjoint g f := by simp [disjoint, or.comm] lemma disjoint_comm {f g : perm α} : disjoint f g ↔ disjoint g f := ⟨disjoint.symm, disjoint.symm⟩ lemma disjoint_mul_comm {f g : perm α} (h : disjoint f g) : f * g = g * f := equiv.ext _ _ $ λ x, (h x).elim (λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg]) (λ hg, by simp [mul_apply, hf, g.injective hg])) (λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg]) (λ hf, by simp [mul_apply, hf, hg])) @[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl @[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl lemma disjoint_mul_left {f g h : perm α} (H1 : disjoint f h) (H2 : disjoint g h) : disjoint (f * g) h := λ x, by cases H1 x; cases H2 x; simp * lemma disjoint_mul_right {f g h : perm α} (H1 : disjoint f g) (H2 : disjoint f h) : disjoint f (g * h) := by rw disjoint_comm; exact disjoint_mul_left H1.symm H2.symm lemma disjoint_prod_right {f : perm α} (l : list (perm α)) (h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod := begin induction l with g l ih, { exact disjoint_one_right _ }, { rw list.prod_cons; exact disjoint_mul_right (h _ (list.mem_cons_self _ _)) (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) } end lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint) (hp : l₁ ~ l₂) : l₁.prod = l₂.prod := begin induction hp, { refl }, { rw [list.prod_cons, list.prod_cons, hp_ih (list.pairwise_cons.1 hl).2] }, { simp [list.prod_cons, disjoint_mul_comm, (mul_assoc _ _ _).symm, *, list.pairwise_cons] at * }, { rw [hp_ih_a hl, hp_ih_a_1 ((list.perm_pairwise (λ x y (h : disjoint x y), disjoint.symm h) hp_a).1 hl)] } end lemma of_subtype_subtype_perm {f : perm α} {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : of_subtype (subtype_perm f h₁) = f := equiv.ext _ _ $ λ x, begin rw [of_subtype, subtype_perm], by_cases hx : p x, { simp [hx] }, { haveI := classical.prop_decidable, simp [hx, not_not.1 (mt (h₂ x) hx)] } end lemma of_subtype_apply_of_not_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : ¬ p x) : of_subtype f x = x := dif_neg hx lemma mem_iff_of_subtype_apply_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : α) : p x ↔ p ((of_subtype f : α → α) x) := if h : p x then by dsimp [of_subtype]; simpa [h] using (f ⟨x, h⟩).2 else by simp [h, of_subtype_apply_of_not_mem f h] @[simp] lemma subtype_perm_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : subtype_perm (of_subtype f) (mem_iff_of_subtype_apply_mem f) = f := equiv.ext _ _ $ λ ⟨x, hx⟩, by dsimp [subtype_perm, of_subtype]; simp [show p x, from hx] lemma pow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℕ, (f ^ n) x = x | 0 := rfl | (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self] lemma gpow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℤ, (f ^ n) x = x | (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n | -[1+ n] := by rw [gpow_neg_succ, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx] lemma pow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x | 0 := or.inl rfl | (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim (λ h, or.inr (by rw [pow_succ, mul_apply, h])) (λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx])) lemma gpow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x | (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n | -[1+ n] := by rw [gpow_neg_succ, inv_eq_iff_eq, ← injective.eq_iff f.injective, ← mul_apply, ← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm]; exact pow_apply_eq_of_apply_apply_eq_self hffx _ variable [decidable_eq α] def support [fintype α] (f : perm α) := univ.filter (λ x, f x ≠ x) @[simp] lemma mem_support [fintype α] {f : perm α} {x : α} : x ∈ f.support ↔ f x ≠ x := by simp [support] def is_swap (f : perm α) := ∃ x y, x ≠ y ∧ f = swap x y lemma swap_mul_eq_mul_swap (f : perm α) (x y : α) : swap x y * f = f * swap (f⁻¹ x) (f⁻¹ y) := equiv.ext _ _ $ λ z, begin simp [mul_apply, swap_apply_def], split_ifs; simp [*, eq_inv_iff_eq] at * <|> cc end lemma mul_swap_eq_swap_mul (f : perm α) (x y : α) : f * swap x y = swap (f x) (f y) * f := by rw [swap_mul_eq_mul_swap, inv_apply_self, inv_apply_self] @[simp] lemma swap_mul_self (i j : α) : equiv.swap i j * equiv.swap i j = 1 := equiv.swap_swap i j @[simp] lemma swap_swap_apply (i j k : α) : equiv.swap i j (equiv.swap i j k) = k := equiv.swap_core_swap_core k i j lemma is_swap_of_subtype {p : α → Prop} [decidable_pred p] {f : perm (subtype p)} (h : is_swap f) : is_swap (of_subtype f) := let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in ⟨x, y, by simp at hxy; tauto, equiv.ext _ _ $ λ z, begin rw [hxy.2, of_subtype], simp [swap_apply_def], split_ifs; cc <|> simp * at * end⟩ lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α} (hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x := begin simp only [swap_apply_def, mul_apply, injective.eq_iff f.injective] at *, by_cases h : f y = x, { split; intro; simp * at * }, { split_ifs at hy; cc } end lemma support_swap_mul_eq [fintype α] {f : perm α} {x : α} (hffx : f (f x) ≠ x) : (swap x (f x) * f).support = f.support.erase x := have hfx : f x ≠ x, from λ hfx, by simpa [hfx] using hffx, finset.ext.2 $ λ y, ⟨λ hy, have hy' : (swap x (f x) * f) y ≠ y, from mem_support.1 hy, mem_erase.2 ⟨λ hyx, by simp [hyx, mul_apply, *] at *, mem_support.2 $ λ hfy, by simp only [mul_apply, swap_apply_def, hfy] at hy'; split_ifs at hy'; simp * at *⟩, λ hy, by simp only [mem_erase, mem_support, swap_apply_def, mul_apply] at *; intro; split_ifs at *; simp * at *⟩ lemma card_support_swap_mul [fintype α] {f : perm α} {x : α} (hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card := finset.card_lt_card ⟨λ z hz, mem_support.2 (ne_and_ne_of_swap_mul_apply_ne_self (mem_support.1 hz)).1, λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩ def swap_factors_aux : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) → {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} | [] := λ f h, ⟨[], equiv.ext _ _ $ λ x, by rw [list.prod_nil]; exact eq.symm (not_not.1 (mt h (list.not_mem_nil _))), by simp⟩ | (x :: l) := λ f h, if hfx : x = f x then swap_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h hy)) else let m := swap_factors_aux l (swap x (f x) * f) (λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h this.1)) in ⟨swap x (f x) :: m.1, by rw [list.prod_cons, m.2.1, ← mul_assoc, mul_def (swap x (f x)), swap_swap, ← one_def, one_mul], λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ h, ⟨x, f x, hfx, h⟩) (m.2.2 _)⟩ /-- `swap_factors` represents a permutation as a product of a list of transpositions. The representation is non unique and depends on the linear order structure. For types without linear order `trunc_swap_factors` can be used -/ def swap_factors [fintype α] [decidable_linear_order α] (f : perm α) : {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := swap_factors_aux ((@univ α _).sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _)) def trunc_swap_factors [fintype α] (f : perm α) : trunc {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := quotient.rec_on_subsingleton (@univ α _).1 (λ l h, trunc.mk (swap_factors_aux l f h)) (show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _) @[elab_as_eliminator] lemma swap_induction_on [fintype α] {P : perm α → Prop} (f : perm α) : P 1 → (∀ f x y, x ≠ y → P f → P (swap x y * f)) → P f := begin cases trunc.out (trunc_swap_factors f) with l hl, induction l with g l ih generalizing f, { simp [hl.1.symm] {contextual := tt} }, { assume h1 hmul_swap, rcases hl.2 g (by simp) with ⟨x, y, hxy⟩, rw [← hl.1, list.prod_cons, hxy.2], exact hmul_swap _ _ _ hxy.1 (ih _ ⟨rfl, λ v hv, hl.2 _ (list.mem_cons_of_mem _ hv)⟩ h1 hmul_swap) } end lemma swap_mul_swap_mul_swap {x y z : α} (hwz: x ≠ y) (hxz : x ≠ z) : swap y z * swap x y * swap y z = swap z x := equiv.ext _ _ $ λ n, by simp only [swap_apply_def, mul_apply]; split_ifs; cc lemma is_conj_swap {w x y z : α} (hwx : w ≠ x) (hyz : y ≠ z) : is_conj (swap w x) (swap y z) := have h : ∀ {y z : α}, y ≠ z → w ≠ z → (swap w y * swap x z) * swap w x * (swap w y * swap x z)⁻¹ = swap y z := λ y z hyz hwz, by rw [mul_inv_rev, swap_inv, swap_inv, mul_assoc (swap w y), mul_assoc (swap w y), ← mul_assoc _ (swap x z), swap_mul_swap_mul_swap hwx hwz, ← mul_assoc, swap_mul_swap_mul_swap hwz.symm hyz.symm], if hwz : w = z then have hwy : w ≠ y, by cc, ⟨swap w z * swap x y, by rw [swap_comm y z, h hyz.symm hwy]⟩ else ⟨swap w y * swap x z, h hyz hwz⟩ /-- set of all pairs (⟨a, b⟩ : Σ a : fin n, fin n) such that b < a -/ def fin_pairs_lt (n : ℕ) : finset (Σ a : fin n, fin n) := (univ : finset (fin n)).sigma (λ a, (range a.1).attach_fin (λ m hm, lt_trans (mem_range.1 hm) a.2)) lemma mem_fin_pairs_lt {n : ℕ} {a : Σ a : fin n, fin n} : a ∈ fin_pairs_lt n ↔ a.2 < a.1 := by simp [fin_pairs_lt, fin.lt_def] def sign_aux {n : ℕ} (a : perm (fin n)) : units ℤ := (fin_pairs_lt n).prod (λ x, if a x.1 ≤ a x.2 then -1 else 1) @[simp] lemma sign_aux_one (n : ℕ) : sign_aux (1 : perm (fin n)) = 1 := begin unfold sign_aux, conv { to_rhs, rw ← @finset.prod_const_one _ (units ℤ) (fin_pairs_lt n) }, exact finset.prod_congr rfl (λ a ha, if_neg (not_le_of_gt (mem_fin_pairs_lt.1 ha))) end def sign_bij_aux {n : ℕ} (f : perm (fin n)) (a : Σ a : fin n, fin n) : Σ a : fin n, fin n := if hxa : f a.2 < f a.1 then ⟨f a.1, f a.2⟩ else ⟨f a.2, f a.1⟩ lemma sign_bij_aux_inj {n : ℕ} {f : perm (fin n)} : ∀ a b : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → b ∈ fin_pairs_lt n → sign_bij_aux f a = sign_bij_aux f b → a = b := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, begin unfold sign_bij_aux at h, rw mem_fin_pairs_lt at *, have : ¬b₁ < b₂ := not_lt_of_ge (le_of_lt hb), split_ifs at h; simp [*, injective.eq_iff f.injective, sigma.mk.inj_eq] at * end lemma sign_bij_aux_surj {n : ℕ} {f : perm (fin n)} : ∀ a ∈ fin_pairs_lt n, ∃ b ∈ fin_pairs_lt n, a = sign_bij_aux f b := λ ⟨a₁, a₂⟩ ha, if hxa : f⁻¹ a₂ < f⁻¹ a₁ then ⟨⟨f⁻¹ a₁, f⁻¹ a₂⟩, mem_fin_pairs_lt.2 hxa, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_pos (mem_fin_pairs_lt.1 ha)]⟩ else ⟨⟨f⁻¹ a₂, f⁻¹ a₁⟩, mem_fin_pairs_lt.2 $ lt_of_le_of_ne (le_of_not_gt hxa) $ λ h, by simpa [mem_fin_pairs_lt, (f⁻¹).injective h, lt_irrefl] using ha, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_neg (not_lt_of_ge (le_of_lt (mem_fin_pairs_lt.1 ha)))]⟩ lemma sign_bij_aux_mem {n : ℕ} {f : perm (fin n)}: ∀ a : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → sign_bij_aux f a ∈ fin_pairs_lt n := λ ⟨a₁, a₂⟩ ha, begin unfold sign_bij_aux, split_ifs with h, { exact mem_fin_pairs_lt.2 h }, { exact mem_fin_pairs_lt.2 (lt_of_le_of_ne (le_of_not_gt h) (λ h, ne_of_lt (mem_fin_pairs_lt.1 ha) (f.injective h.symm))) } end @[simp] lemma sign_aux_inv {n : ℕ} (f : perm (fin n)) : sign_aux f⁻¹ = sign_aux f := prod_bij (λ a ha, sign_bij_aux f⁻¹ a) sign_bij_aux_mem (λ ⟨a, b⟩ hab, if h : f⁻¹ b < f⁻¹ a then by rw [sign_bij_aux, dif_pos h, if_neg (not_le_of_gt h), apply_inv_self, apply_inv_self, if_neg (not_le_of_gt $ mem_fin_pairs_lt.1 hab)] else by rw [sign_bij_aux, if_pos (le_of_not_gt h), dif_neg h, apply_inv_self, apply_inv_self, if_pos (le_of_lt $ mem_fin_pairs_lt.1 hab)]) sign_bij_aux_inj sign_bij_aux_surj lemma sign_aux_mul {n : ℕ} (f g : perm (fin n)) : sign_aux (f * g) = sign_aux f * sign_aux g := begin rw ← sign_aux_inv g, unfold sign_aux, rw ← prod_mul_distrib, refine prod_bij (λ a ha, sign_bij_aux g a) sign_bij_aux_mem _ sign_bij_aux_inj sign_bij_aux_surj, rintros ⟨a, b⟩ hab, rw [sign_bij_aux, mul_apply, mul_apply], rw mem_fin_pairs_lt at hab, by_cases h : g b < g a, { rw dif_pos h, simp [not_le_of_gt hab]; congr }, { rw [dif_neg h, inv_apply_self, inv_apply_self, if_pos (le_of_lt hab)], by_cases h₁ : f (g b) ≤ f (g a), { have : f (g b) ≠ f (g a), { rw [ne.def, injective.eq_iff f.injective, injective.eq_iff g.injective]; exact ne_of_lt hab }, rw [if_pos h₁, if_neg (not_le_of_gt (lt_of_le_of_ne h₁ this))], refl }, { rw [if_neg h₁, if_pos (le_of_lt (lt_of_not_ge h₁))], refl } } end instance sign_aux.is_group_hom {n : ℕ} : is_group_hom (@sign_aux n) := ⟨sign_aux_mul⟩ private lemma sign_aux_swap_zero_one {n : ℕ} (hn : 2 ≤ n) : sign_aux (swap (⟨0, lt_of_lt_of_le dec_trivial hn⟩ : fin n) ⟨1, lt_of_lt_of_le dec_trivial hn⟩) = -1 := let zero : fin n := ⟨0, lt_of_lt_of_le dec_trivial hn⟩ in let one : fin n := ⟨1, lt_of_lt_of_le dec_trivial hn⟩ in have hzo : zero < one := dec_trivial, show _ = (finset.singleton (⟨one, zero⟩ : Σ a : fin n, fin n)).prod (λ x : Σ a : fin n, fin n, if (equiv.swap zero one) x.1 ≤ swap zero one x.2 then (-1 : units ℤ) else 1), begin refine eq.symm (prod_subset (λ ⟨x₁, x₂⟩, by simp [mem_fin_pairs_lt, hzo] {contextual := tt}) (λ a ha₁ ha₂, _)), rcases a with ⟨⟨a₁, ha₁⟩, ⟨a₂, ha₂⟩⟩, replace ha₁ : a₂ < a₁ := mem_fin_pairs_lt.1 ha₁, simp only [swap_apply_def], have : ¬ 1 ≤ a₂ → a₂ = 0, from λ h, nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge h)), have : a₁ ≤ 1 → a₁ = 0 ∨ a₁ = 1, from nat.cases_on a₁ (λ _, or.inl rfl) (λ a₁, nat.cases_on a₁ (λ _, or.inr rfl) (λ _ h, absurd h dec_trivial)), split_ifs; simp [*, lt_irrefl, -not_lt, not_le.symm, -not_le, le_refl, fin.lt_def, fin.le_def, nat.zero_le, zero, one, iff.intro fin.veq_of_eq fin.eq_of_veq, nat.le_zero_iff] at *, end lemma sign_aux_swap : ∀ {n : ℕ} {x y : fin n} (hxy : x ≠ y), sign_aux (swap x y) = -1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ x y hxy, have h2n : 2 ≤ n + 2 := dec_trivial, by rw [← is_conj_iff_eq, ← sign_aux_swap_zero_one h2n]; exact is_group_hom.is_conj _ (is_conj_swap hxy dec_trivial) def sign_aux2 : list α → perm α → units ℤ | [] f := 1 | (x::l) f := if x = f x then sign_aux2 l f else -sign_aux2 l (swap x (f x) * f) lemma sign_aux_eq_sign_aux2 {n : ℕ} : ∀ (l : list α) (f : perm α) (e : α ≃ fin n) (h : ∀ x, f x ≠ x → x ∈ l), sign_aux ((e.symm.trans f).trans e) = sign_aux2 l f | [] f e h := have f = 1, from equiv.ext _ _ $ λ y, not_not.1 (mt (h y) (list.not_mem_nil _)), by rw [this, one_def, equiv.trans_refl, equiv.symm_trans, ← one_def, sign_aux_one, sign_aux2] | (x::l) f e h := begin rw sign_aux2, by_cases hfx : x = f x, { rw if_pos hfx, exact sign_aux_eq_sign_aux2 l f _ (λ y (hy : f y ≠ y), list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h y hy) ) }, { have hy : ∀ y : α, (swap x (f x) * f) y ≠ y → y ∈ l, from λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h _ this.1), have : (e.symm.trans (swap x (f x) * f)).trans e = (swap (e x) (e (f x))) * (e.symm.trans f).trans e, from equiv.ext _ _ (λ z, by rw ← equiv.symm_trans_swap_trans; simp [mul_def]), have hefx : e x ≠ e (f x), from mt (injective.eq_iff e.injective).1 hfx, rw [if_neg hfx, ← sign_aux_eq_sign_aux2 _ _ e hy, this, sign_aux_mul, sign_aux_swap hefx], simp } end def sign_aux3 [fintype α] (f : perm α) {s : multiset α} : (∀ x, x ∈ s) → units ℤ := quotient.hrec_on s (λ l h, sign_aux2 l f) (trunc.induction_on (equiv_fin α) (λ e l₁ l₂ h, function.hfunext (show (∀ x, x ∈ l₁) = ∀ x, x ∈ l₂, by simp [list.mem_of_perm h]) (λ h₁ h₂ _, by rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₂ _)]))) lemma sign_aux3_mul_and_swap [fintype α] (f g : perm α) (s : multiset α) (hs : ∀ x, x ∈ s) : sign_aux3 (f * g) hs = sign_aux3 f hs * sign_aux3 g hs ∧ ∀ x y, x ≠ y → sign_aux3 (swap x y) hs = -1 := let ⟨l, hl⟩ := quotient.exists_rep s in let ⟨e, _⟩ := trunc.exists_rep (equiv_fin α) in begin clear _let_match _let_match, subst hl, show sign_aux2 l (f * g) = sign_aux2 l f * sign_aux2 l g ∧ ∀ x y, x ≠ y → sign_aux2 l (swap x y) = -1, have hfg : (e.symm.trans (f * g)).trans e = (e.symm.trans f).trans e * (e.symm.trans g).trans e, from equiv.ext _ _ (λ h, by simp [mul_apply]), split, { rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), hfg, sign_aux_mul] }, { assume x y hxy, have hexy : e x ≠ e y, from mt (injective.eq_iff e.injective).1 hxy, rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), equiv.symm_trans_swap_trans, sign_aux_swap hexy] } end /-- `sign` of a permutation returns the signature or parity of a permutation, `1` for even permutations, `-1` for odd permutations. It is the unique surjective group homomorphism from `perm α` to the group with two elements.-/ def sign [fintype α] (f : perm α) := sign_aux3 f mem_univ instance sign.is_group_hom [fintype α] : is_group_hom (@sign α _ _) := ⟨λ f g, (sign_aux3_mul_and_swap f g _ mem_univ).1⟩ section sign variable [fintype α] @[simp] lemma sign_mul (f g : perm α) : sign (f * g) = sign f * sign g := is_group_hom.map_mul sign _ _ @[simp] lemma sign_one : (sign (1 : perm α)) = 1 := is_group_hom.map_one sign @[simp] lemma sign_refl : sign (equiv.refl α) = 1 := is_group_hom.map_one sign @[simp] lemma sign_inv (f : perm α) : sign f⁻¹ = sign f := by rw [is_group_hom.map_inv sign, int.units_inv_eq_self]; apply_instance lemma sign_swap {x y : α} (h : x ≠ y) : sign (swap x y) = -1 := (sign_aux3_mul_and_swap 1 1 _ mem_univ).2 x y h @[simp] lemma sign_swap' {x y : α} : (swap x y).sign = if x = y then 1 else -1 := if H : x = y then by simp [H, swap_self] else by simp [sign_swap H, H] lemma sign_eq_of_is_swap {f : perm α} (h : is_swap f) : sign f = -1 := let ⟨x, y, hxy⟩ := h in hxy.2.symm ▸ sign_swap hxy.1 lemma sign_aux3_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) {s : multiset α} {t : multiset β} (hs : ∀ x, x ∈ s) (ht : ∀ x, x ∈ t) : sign_aux3 ((e.symm.trans f).trans e) ht = sign_aux3 f hs := quotient.induction_on₂ t s (λ l₁ l₂ h₁ h₂, show sign_aux2 _ _ = sign_aux2 _ _, from let n := trunc.out (equiv_fin β) in by rw [← sign_aux_eq_sign_aux2 _ _ n (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ (e.trans n) (λ _ _, h₂ _)]; exact congr_arg sign_aux (equiv.ext _ _ (λ x, by simp))) ht hs lemma sign_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) : sign ((e.symm.trans f).trans e) = sign f := sign_aux3_symm_trans_trans f e mem_univ mem_univ lemma sign_prod_list_swap {l : list (perm α)} (hl : ∀ g ∈ l, is_swap g) : sign l.prod = -1 ^ l.length := have h₁ : l.map sign = list.repeat (-1) l.length := list.eq_repeat.2 ⟨by simp, λ u hu, let ⟨g, hg⟩ := list.mem_map.1 hu in hg.2 ▸ sign_eq_of_is_swap (hl _ hg.1)⟩, by rw [← list.prod_repeat, ← h₁, ← is_group_hom.map_prod (@sign α _ _)] lemma sign_surjective (hα : 1 < fintype.card α) : function.surjective (sign : perm α → units ℤ) := λ a, (int.units_eq_one_or a).elim (λ h, ⟨1, by simp [h]⟩) (λ h, let ⟨x⟩ := fintype.card_pos_iff.1 (lt_trans zero_lt_one hα) in let ⟨y, hxy⟩ := fintype.exists_ne_of_card_gt_one hα x in ⟨swap y x, by rw [sign_swap hxy, h]⟩ ) lemma eq_sign_of_surjective_hom {s : perm α → units ℤ} [is_group_hom s] (hs : surjective s) : s = sign := have ∀ {f}, is_swap f → s f = -1 := λ f ⟨x, y, hxy, hxy'⟩, hxy'.symm ▸ by_contradiction (λ h, have ∀ f, is_swap f → s f = 1 := λ f ⟨a, b, hab, hab'⟩, by rw [← is_conj_iff_eq, ← or.resolve_right (int.units_eq_one_or _) h, hab']; exact is_group_hom.is_conj _ (is_conj_swap hab hxy), let ⟨g, hg⟩ := hs (-1) in let ⟨l, hl⟩ := trunc.out (trunc_swap_factors g) in have ∀ a ∈ l.map s, a = (1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this _ (hl.2 _ hg.1), have s l.prod = 1, by rw [is_group_hom.map_prod s, list.eq_repeat'.2 this, list.prod_repeat, one_pow], by rw [hl.1, hg] at this; exact absurd this dec_trivial), funext $ λ f, let ⟨l, hl₁, hl₂⟩ := trunc.out (trunc_swap_factors f) in have hsl : ∀ a ∈ l.map s, a = (-1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this (hl₂ _ hg.1), by rw [← hl₁, is_group_hom.map_prod s, list.eq_repeat'.2 hsl, list.length_map, list.prod_repeat, sign_prod_list_swap hl₂] lemma sign_subtype_perm (f : perm α) {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : sign (subtype_perm f h₁) = sign f := let l := trunc.out (trunc_swap_factors (subtype_perm f h₁)) in have hl' : ∀ g' ∈ l.1.map of_subtype, is_swap g' := λ g' hg', let ⟨g, hg⟩ := list.mem_map.1 hg' in hg.2 ▸ is_swap_of_subtype (l.2.2 _ hg.1), have hl'₂ : (l.1.map of_subtype).prod = f, by rw [← is_group_hom.map_prod of_subtype l.1, l.2.1, of_subtype_subtype_perm _ h₂], by conv {congr, rw ← l.2.1, skip, rw ← hl'₂}; rw [sign_prod_list_swap l.2.2, sign_prod_list_swap hl', list.length_map] @[simp] lemma sign_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : sign (of_subtype f) = sign f := have ∀ x, of_subtype f x ≠ x → p x, from λ x, not_imp_comm.1 (of_subtype_apply_of_not_mem f), by conv {to_rhs, rw [← subtype_perm_of_subtype f, sign_subtype_perm _ _ this]} lemma sign_eq_sign_of_equiv [decidable_eq β] [fintype β] (f : perm α) (g : perm β) (e : α ≃ β) (h : ∀ x, e (f x) = g (e x)) : sign f = sign g := have hg : g = (e.symm.trans f).trans e, from equiv.ext _ _ $ by simp [h], by rw [hg, sign_symm_trans_trans] lemma sign_bij [decidable_eq β] [fintype β] {f : perm α} {g : perm β} (i : Π x : α, f x ≠ x → β) (h : ∀ x hx hx', i (f x) hx' = g (i x hx)) (hi : ∀ x₁ x₂ hx₁ hx₂, i x₁ hx₁ = i x₂ hx₂ → x₁ = x₂) (hg : ∀ y, g y ≠ y → ∃ x hx, i x hx = y) : sign f = sign g := calc sign f = sign (@subtype_perm _ f (λ x, f x ≠ x) (by simp)) : eq.symm (sign_subtype_perm _ _ (λ _, id)) ... = sign (@subtype_perm _ g (λ x, g x ≠ x) (by simp)) : sign_eq_sign_of_equiv _ _ (equiv.of_bijective (show function.bijective (λ x : {x // f x ≠ x}, (⟨i x.1 x.2, have f (f x) ≠ f x, from mt (λ h, f.injective h) x.2, by rw [← h _ x.2 this]; exact mt (hi _ _ this x.2) x.2⟩ : {y // g y ≠ y})), from ⟨λ ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq (hi _ _ _ _ (subtype.mk.inj h)), λ ⟨y, hy⟩, let ⟨x, hfx, hx⟩ := hg y hy in ⟨⟨x, hfx⟩, subtype.eq hx⟩⟩)) (λ ⟨x, _⟩, subtype.eq (h x _ _)) ... = sign g : sign_subtype_perm _ _ (λ _, id) def is_cycle (f : perm β) := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y lemma is_cycle_swap {x y : α} (hxy : x ≠ y) : is_cycle (swap x y) := ⟨y, by rwa swap_apply_right, λ a (ha : ite (a = x) y (ite (a = y) x a) ≠ a), if hya : y = a then ⟨0, hya⟩ else ⟨1, by rw [gpow_one, swap_apply_def]; split_ifs at *; cc⟩⟩ lemma is_cycle_inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := let ⟨x, hx⟩ := hf in ⟨x, by simp [eq_inv_iff_eq, inv_eq_iff_eq, *] at *; cc, λ y hy, let ⟨i, hi⟩ := hx.2 y (by simp [eq_inv_iff_eq, inv_eq_iff_eq, *] at *; cc) in ⟨-i, by rwa [gpow_neg, inv_gpow, inv_inv]⟩⟩ lemma exists_gpow_eq_of_is_cycle {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℤ, (f ^ i) x = y := let ⟨g, hg⟩ := hf in let ⟨a, ha⟩ := hg.2 x hx in let ⟨b, hb⟩ := hg.2 y hy in ⟨b - a, by rw [← ha, ← mul_apply, ← gpow_add, sub_add_cancel, hb]⟩ lemma is_cycle_swap_mul_aux₁ : ∀ (n : ℕ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | 0 := λ b x f hb h, ⟨0, h⟩ | (n+1 : ℕ) := λ b x f hb h, if hfbx : f x = b then ⟨0, hfbx⟩ else have f b ≠ b ∧ b ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hb, have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx), ne.def, ← injective.eq_iff f.injective, apply_inv_self]; exact this.1, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb' (f.injective $ by rw [apply_inv_self]; rwa [pow_succ, mul_apply] at h) in ⟨i + 1, by rw [add_comm, gpow_add, mul_apply, hi, gpow_one, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩ lemma is_cycle_swap_mul_aux₂ : ∀ (n : ℤ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | (n : ℕ) := λ b x f, is_cycle_swap_mul_aux₁ n | -[1+ n] := λ b x f hb h, if hfbx : f⁻¹ x = b then ⟨-1, by rwa [gpow_neg, gpow_one, mul_inv_rev, mul_apply, swap_inv, swap_apply_right]⟩ else if hfbx' : f x = b then ⟨0, hfbx'⟩ else have f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb, have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, swap_apply_def]; split_ifs; simp [inv_eq_iff_eq, eq_inv_iff_eq] at *; cc, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb (show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by rw [← gpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, gpow_neg_succ, ← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, gpow_coe_nat, ← pow_succ', ← pow_succ]) in have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left], ⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, gpow_add, gpow_one, gpow_neg, ← inv_gpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, gpow_add, gpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩ lemma eq_swap_of_is_cycle_of_apply_apply_eq_self {f : perm α} (hf : is_cycle f) {x : α} (hfx : f x ≠ x) (hffx : f (f x) = x) : f = swap x (f x) := equiv.ext _ _ $ λ y, let ⟨z, hz⟩ := hf in let ⟨i, hi⟩ := hz.2 x hfx in if hyx : y = x then by simp [hyx] else if hfyx : y = f x then by simp [hfyx, hffx] else begin rw [swap_apply_of_ne_of_ne hyx hfyx], refine by_contradiction (λ hy, _), cases hz.2 y hy with j hj, rw [← sub_add_cancel j i, gpow_add, mul_apply, hi] at hj, cases gpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji, { rw [← hj, hji] at hyx, cc }, { rw [← hj, hji] at hfyx, cc } end lemma is_cycle_swap_mul {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) (hffx : f (f x) ≠ x) : is_cycle (swap x (f x) * f) := ⟨f x, by simp only [swap_apply_def, mul_apply]; split_ifs; simp [injective.eq_iff f.injective] at *; cc, λ y hy, let ⟨i, hi⟩ := exists_gpow_eq_of_is_cycle hf hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in have hi : (f ^ (i - 1)) (f x) = y, from calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : ℤ)) x : by rw [gpow_one, mul_apply] ... = y : by rwa [← gpow_add, sub_add_cancel], is_cycle_swap_mul_aux₂ (i - 1) hy hi⟩ @[simp] lemma support_swap [fintype α] {x y : α} (hxy : x ≠ y) : (swap x y).support = {x, y} := finset.ext.2 $ λ a, by simp [swap_apply_def]; split_ifs; cc lemma card_support_swap [fintype α] {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 := show (swap x y).support.card = finset.card ⟨x::y::0, by simp [hxy]⟩, from congr_arg card $ by rw [support_swap hxy]; simp [*, finset.ext]; cc lemma sign_cycle [fintype α] : ∀ {f : perm α} (hf : is_cycle f), sign f = -(-1 ^ f.support.card) | f := λ hf, let ⟨x, hx⟩ := hf in calc sign f = sign (swap x (f x) * (swap x (f x) * f)) : by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl] ... = -(-1 ^ f.support.card) : if h1 : f (f x) = x then have h : swap x (f x) * f = 1, by conv in (f) {rw eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1 }; simp [mul_def, one_def], by rw [sign_mul, sign_swap hx.1.symm, h, sign_one, eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1, card_support_swap hx.1.symm]; refl else have h : card (support (swap x (f x) * f)) + 1 = card (support f), by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq h1, card_insert_of_not_mem (not_mem_erase _ _)], have wf : card (support (swap x (f x) * f)) < card (support f), from card_support_swap_mul hx.1, by rw [sign_mul, sign_swap hx.1.symm, sign_cycle (is_cycle_swap_mul hf hx.1 h1), ← h]; simp [pow_add] using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]} end sign end equiv.perm lemma finset.prod_univ_perm [fintype α] [comm_monoid β] {f : α → β} (σ : perm α) : (univ : finset α).prod f = univ.prod (λ z, f (σ z)) := eq.symm $ prod_bij (λ z _, σ z) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ H, σ.injective H) (λ b _, ⟨σ⁻¹ b, mem_univ _, by simp⟩) lemma finset.sum_univ_perm [fintype α] [add_comm_monoid β] {f : α → β} (σ : perm α) : (univ : finset α).sum f = univ.sum (λ z, f (σ z)) := @finset.prod_univ_perm _ (multiplicative β) _ _ f σ attribute [to_additive finset.sum_univ_perm] finset.prod_univ_perm
716b350d74449faff9dd42a1856af4727830bfeb
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/analysis/calculus/fderiv.lean
ca1ee8ad3722e6a477c5eb4701a42339b3f6390f
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
121,898
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.tangent_cone import analysis.normed_space.units import analysis.asymptotics.asymptotic_equivalent import analysis.analytic.basic /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` Finally, `has_strict_fderiv_at f f' x` means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability, i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse function theorem, and is defined here only to avoid proving theorems like `is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for `has_strict_fderiv_at`. ## Main results In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * sum of finitely many functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) * inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are translated to this more elementary point of view on the derivative in the file `deriv.lean`. The derivative of polynomials is handled there, as it is naturally one-dimensional. The simplifier is set up to prove automatically that some functions are differentiable, or differentiable at a point (but not differentiable on a set or within a set at a point, as checking automatically that the good domains are mapped one to the other when using composition is not something the simplifier can easily do). This means that one can write `example (x : ℝ) : differentiable ℝ (λ x, sin (exp (3 + x^2)) - 5 * cos x) := by simp`. If there are divisions, one needs to supply to the simplifier proofs that the denominators do not vanish, as in ```lean example (x : ℝ) (h : 1 + sin x ≠ 0) : differentiable_at ℝ (λ x, exp x / (1 + sin x)) x := by simp [h] ``` Of course, these examples only work once `exp`, `cos` and `sin` have been shown to be differentiable, in `analysis.special_functions.trigonometric`. The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general complicated multidimensional linear maps), but it will compute one-dimensional derivatives, see `deriv.lean`. ## Implementation details The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. To make sure that the simplifier can prove automatically that functions are differentiable, we tag many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable functions is differentiable, as well as their product, their cartesian product, and so on. A notable exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are differentiable, then their composition also is: `simp` would always be able to match this lemma, by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`), we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding some boilerplate lemmas, but these can also be useful in their own right. Tests for this ability of the simplifier (with more examples) are provided in `tests/differentiable.lean`. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set metric open_locale topological_space classical nnreal asymptotics filter ennreal noncomputable theory section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G'] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = 𝓝[s] x` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L /-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/ def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (𝓝[s] x) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) /-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability* if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required, e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/ def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := is_o (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s) (clim : tendsto (λ n, ∥c n∥) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (𝓝[s] x), { conv in (𝓝[s] x) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (𝓝[s] x) := h, have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l := this.comp_tendsto tendsto_arg, have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'], have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l := (is_O_refl c l).smul_is_o this, have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l := this.trans_is_O (is_O_one_of_tendsto ℝ cdlim), have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) := (is_o_one_iff ℝ).1 this, have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) := tendsto.comp f'.cont.continuous_at cdlim, have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) l (𝓝 (0 + f' v)) := L1.add L2, have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) = (λn, c n • (f (x + d n) - f x)), by { ext n, simp [smul_add, smul_sub] }, rwa [this, zero_add] at L3 end /-- If `f'` and `f₁'` are two derivatives of `f` within `s` at `x`, then they are equal on the tangent cone to `s` at `x` -/ theorem has_fderiv_within_at.unique_on (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : eq_on f' f₁' (tangent_cone_at 𝕜 s x) := λ y ⟨c, d, dtop, clim, cdlim⟩, tendsto_nhds_unique (hf.lim at_top dtop clim cdlim) (hg.lim at_top dtop clim cdlim) /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x) (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : f' = f₁' := continuous_linear_map.ext_on H.1 (hf.unique_on hg) theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := (H x hx).eq h h₁ end derivative_uniqueness section fderiv_properties /-! ### Basic properties of the derivative -/ theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) := have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx', by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto_congr (λ _, div_eq_inv_mul), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝[s] x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) := begin rw [has_fderiv_at, has_fderiv_at_filter, ← map_add_left_nhds_zero x, is_o_map], simp [(∘)] end /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. -/ lemma has_fderiv_at.le_of_lip {f : E → F} {f' : E →L[𝕜] F} {x₀ : E} (hf : has_fderiv_at f f' x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥f'∥ ≤ C := begin refine le_of_forall_pos_le_add (λ ε ε0, op_norm_le_of_nhds_zero _ _), exact add_nonneg C.coe_nonneg ε0.le, have hs' := hs, rw [← map_add_left_nhds_zero x₀, mem_map] at hs', filter_upwards [is_o_iff.1 (has_fderiv_at_iff_is_o_nhds_zero.1 hf) ε0, hs'], intros y hy hys, have := hlip.norm_sub_le hys (mem_of_nhds hs), rw add_sub_cancel' at this, calc ∥f' y∥ ≤ ∥f (x₀ + y) - f x₀∥ + ∥f (x₀ + y) - f x₀ - f' y∥ : norm_le_insert _ _ ... ≤ C * ∥y∥ + ε * ∥y∥ : add_le_add this hy ... = (C + ε) * ∥y∥ : (add_mul _ _ _).symm end theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := h.mono hst theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono (nhds_within_mono _ hst) theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) : is_O (λ p : E × E, f p.1 - f p.2) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) := hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _) lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.is_O.congr_of_sub.2 (f'.is_O_sub _ _) protected lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) : has_fderiv_at f f' x := begin rw [has_fderiv_at, has_fderiv_at_filter, is_o_iff], exact (λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (is_o_iff.1 hf hc)) end protected lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) : differentiable_at 𝕜 f x := hf.has_fderiv_at.differentiable_at /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_nhds hU, dsimp only, rw [← mul_smul, mul_inv_cancel hy, one_smul] end theorem has_fderiv_at.unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.join ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) : has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x := begin dunfold fderiv_within, dunfold differentiable_within_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) : has_fderiv_at f (fderiv 𝕜 f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw h.unique h.differentiable_at.has_fderiv_at } /-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. Version using `fderiv`. -/ lemma fderiv_at.le_of_lip {f : E → F} {x₀ : E} (hf : differentiable_at 𝕜 f x₀) {s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥fderiv 𝕜 f x₀∥ ≤ C := hf.has_fderiv_at.le_of_lip hs hlip lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := (hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp only [mem_closure_iff_nhds_within_ne_bot, ne_bot_iff, ne.def, not_not] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_at.differentiable_within_at (h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := (differentiable_within_at_univ.2 h).mono (subset_univ _) lemma differentiable.differentiable_at (h : differentiable 𝕜 f) : differentiable_at 𝕜 f x := h x lemma differentiable_within_at.differentiable_at (h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.imp (λ f' hf', hf'.has_fderiv_at hs) lemma differentiable_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact h.has_fderiv_at.has_fderiv_within_at end lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) : differentiable_on 𝕜 f s := λx hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f := by { simp [differentiable_on, differentiable_within_at_univ], refl } lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s := (differentiable_on_univ.2 h).mono (subset_univ _) lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 (ht x ⟨xs, xt⟩) end lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := ((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht @[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f := begin ext x : 1, by_cases h : differentiable_at 𝕜 f x, { apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ, rw has_fderiv_within_at_univ, apply h.has_fderiv_at }, { have : ¬ differentiable_within_at 𝕜 f univ x, by contrapose! h; rwa ← differentiable_within_at_univ, rw [fderiv_zero_of_not_differentiable_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x, { apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h), apply hs.inter ht }, { have : ¬ differentiable_within_at 𝕜 f s x, by contrapose! h; rw differentiable_within_at_inter; assumption, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_of_mem_nhds (h : s ∈ 𝓝 x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin have : s = univ ∩ s, by simp only [univ_inter], rw [this, ← fderiv_within_univ], exact fderiv_within_inter h (unique_diff_on_univ _ (mem_univ _)) end lemma fderiv_within_of_open (hs : is_open s) (hx : x ∈ s) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := fderiv_within_of_mem_nhds (mem_nhds_sets hs hx) lemma fderiv_within_eq_fderiv (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_at 𝕜 f x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin rw ← fderiv_within_univ, exact fderiv_within_subset (subset_univ _) hs h.differentiable_within_at end lemma fderiv_mem_iff {f : E → F} {s : set (E →L[𝕜] F)} {x : E} : fderiv 𝕜 f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ s) ∨ (0 : E →L[𝕜] F) ∈ s ∧ ¬differentiable_at 𝕜 f x := begin split, { intro hfx, by_cases hx : differentiable_at 𝕜 f x, { exact or.inl ⟨hx, hfx⟩ }, { rw [fderiv_zero_of_not_differentiable_at hx] at hfx, exact or.inr ⟨hfx, hx⟩ } }, { rintro (⟨hf, hf'⟩|⟨h₀, hx⟩), { exact hf' }, { rwa [fderiv_zero_of_not_differentiable_at hx] } } end end fderiv_properties section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto.mono_left _ hL), rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds }, have := tendsto.add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at protected lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) : continuous_at f x := hf.has_fderiv_at.continuous_at lemma has_strict_fderiv_at.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) x) : is_O (λ p : E × E, p.1 - p.2) (λ p : E × E, f p.1 - f p.2) (𝓝 (x, x)) := ((f'.is_O_comp_rev _ _).trans (hf.trans_is_O (f'.is_O_comp_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) lemma has_fderiv_at_filter.is_O_sub_rev {f' : E ≃L[𝕜] F} (hf : has_fderiv_at_filter f (f' : E →L[𝕜] F) x L) : is_O (λ x', x' - x) (λ x', f x' - f x) L := ((f'.is_O_sub_rev _ _).trans (hf.trans_is_O (f'.is_O_sub_rev _ _)).right_is_O_add).congr (λ _, rfl) (λ _, sub_add_cancel _ _) end continuous section congr /-! ### congr properties of the derivative -/ theorem filter.eventually_eq.has_strict_fderiv_at_iff (h : f₀ =ᶠ[𝓝 x] f₁) (h' : ∀ y, f₀' y = f₁' y) : has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x := begin refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall $ λ _, rfl), rintros p ⟨hp₁, hp₂⟩, simp only [*] end theorem has_strict_fderiv_at.congr_of_eventually_eq (h : has_strict_fderiv_at f f' x) (h₁ : f =ᶠ[𝓝 x] f₁) : has_strict_fderiv_at f₁ f' x := (h₁.has_strict_fderiv_at_iff (λ _, rfl)).1 h theorem filter.eventually_eq.has_fderiv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall $ λ _, rfl) lemma has_fderiv_at_filter.congr_of_eventually_eq (h : has_fderiv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := (hL.has_fderiv_at_filter_iff hx $ λ _, rfl).2 h lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr_of_eventually_eq (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr_of_eventually_eq (h : has_fderiv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_fderiv_at.congr_of_eventually_eq (h : has_fderiv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_eventually_eq h h₁ (mem_of_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_eventually_eq (h : differentiable_within_at 𝕜 f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_eventually_eq h₁ hx).differentiable_within_at lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s := λ x hx, (h x hx).congr h' (h' x hx) lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s := ⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm), λ h, differentiable_on.congr h h'⟩ lemma differentiable_at.congr_of_eventually_eq (h : differentiable_at 𝕜 f x) (hL : f₁ =ᶠ[𝓝 x] f) : differentiable_at 𝕜 f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_eventually_eq h.has_fderiv_at hL (mem_of_nhds hL : _)) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma filter.eventually_eq.fderiv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then has_fderiv_within_at.fderiv_within (h.has_fderiv_within_at.congr_of_eventually_eq hL hx) hs else have h' : ¬ differentiable_within_at 𝕜 f₁ s x, from mt (λ h, h.congr_of_eventually_eq (hL.mono $ λ x, eq.symm) hx.symm) h, by rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at h'] lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply filter.eventually_eq.fderiv_within_eq hs _ hx, apply mem_sets_of_superset self_mem_nhds_within, exact hL end lemma filter.eventually_eq.fderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := hL.eq_of_nhds, rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact hL.fderiv_within_eq unique_diff_within_at_univ A end end congr section id /-! ### Derivative of the identity -/ theorem has_strict_fderiv_at_id (x : E) : has_strict_fderiv_at id (id 𝕜 E) x := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id 𝕜 E) x L := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_within_at_id (x : E) (s : set E) : has_fderiv_within_at id (id 𝕜 E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id 𝕜 E) x := has_fderiv_at_filter_id _ _ @[simp] lemma differentiable_at_id : differentiable_at 𝕜 id x := (has_fderiv_at_id x).differentiable_at @[simp] lemma differentiable_at_id' : differentiable_at 𝕜 (λ x, x) x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x := differentiable_at_id.differentiable_within_at @[simp] lemma differentiable_id : differentiable 𝕜 (id : E → E) := λx, differentiable_at_id @[simp] lemma differentiable_id' : differentiable 𝕜 (λ (x : E), x) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on 𝕜 id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv 𝕜 id x = id 𝕜 E := has_fderiv_at.fderiv (has_fderiv_at_id x) @[simp] lemma fderiv_id' : fderiv 𝕜 (λ (x : E), x) x = continuous_linear_map.id 𝕜 E := fderiv_id lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id 𝕜 E := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end lemma fderiv_within_id' (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ (x : E), x) s x = continuous_linear_map.id 𝕜 E := fderiv_within_id hxs end id section const /-! ### derivative of a constant function -/ theorem has_strict_fderiv_at_const (c : F) (x : E) : has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x := has_fderiv_at_filter_const _ _ _ @[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) @[simp] lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 := by { ext m, rw fderiv_const_apply, refl } lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const_apply _ end @[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} : has_strict_fderiv_at e e x := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := (is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self] protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter @[simp] protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at @[simp] protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end @[simp] protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := h.to_continuous_linear_map.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on end continuous_linear_map section analytic variables {p : formal_multilinear_series 𝕜 E F} {r : ℝ≥0∞} lemma has_fpower_series_at.has_strict_fderiv_at (h : has_fpower_series_at f p x) : has_strict_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x := begin refine h.is_O_image_sub_norm_mul_norm_sub.trans_is_o (is_o.of_norm_right _), refine is_o_iff_exists_eq_mul.2 ⟨λ y, ∥y - (x, x)∥, _, eventually_eq.rfl⟩, refine (continuous_id.sub continuous_const).norm.tendsto' _ _ _, rw [_root_.id, sub_self, norm_zero] end lemma has_fpower_series_at.has_fderiv_at (h : has_fpower_series_at f p x) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x := h.has_strict_fderiv_at.has_fderiv_at lemma has_fpower_series_at.differentiable_at (h : has_fpower_series_at f p x) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma analytic_at.differentiable_at : analytic_at 𝕜 f x → differentiable_at 𝕜 f x | ⟨p, hp⟩ := hp.differentiable_at lemma analytic_at.differentiable_within_at (h : analytic_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma has_fpower_series_at.fderiv (h : has_fpower_series_at f p x) : fderiv 𝕜 f x = continuous_multilinear_curry_fin1 𝕜 E F (p 1) := h.has_fderiv_at.fderiv lemma has_fpower_series_on_ball.differentiable_on [complete_space F] (h : has_fpower_series_on_ball f p x r) : differentiable_on 𝕜 f (emetric.ball x r) := λ y hy, (h.analytic_at_of_mem hy).differentiable_within_at end analytic section composition /-! ### Derivative of the composition of two functions For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in let eq₂ := (hg.comp_tendsto tendsto_map).trans_is_O hf.is_O_sub in by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp } /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := begin unfold has_fderiv_at_filter at hg, have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L, from hg.comp_tendsto (le_refl _), have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L, from this.trans_is_O hf.is_O_sub, have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L, from hf, have : is_O (λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L, from g'.is_O_comp _ _, have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L, from this.trans_is_o eq₂, have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L, by { refine this.congr_left _, simp}, exact eq₁.triangle eq₃ end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf, calc map f (𝓝[s] x) ≤ 𝓝[f '' s] (f x) : hf.continuous_within_at.tendsto_nhds_within_image ... ≤ 𝓝[t] (f x) : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := (hg.mono hf.continuous_at).comp x hf theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin rw ← has_fderiv_within_at_univ at hg, exact has_fderiv_within_at.comp x hg hf subset_preimage_univ end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩ end lemma differentiable_within_at.comp' {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma differentiable_at.comp_differentiable_within_at {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) s x := (differentiable_within_at_univ.2 hg).comp x hf (by simp) lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma fderiv.comp_fderiv_within {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at) end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (g ∘ f) s := (differentiable_on_univ.2 hg).comp hf (by simp) /-- The chain rule for derivatives in the sense of strict differentiability. -/ protected lemma has_strict_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_strict_fderiv_at g g' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, g (f x)) (g'.comp f') x := ((hg.comp_tendsto (hf.continuous_at.prod_map' hf.continuous_at)).trans_is_O hf.is_O_sub).triangle $ by simpa only [g'.map_sub, f'.coe_comp'] using (g'.is_O_comp _ _).trans_is_o hf protected lemma differentiable.iterate {f : E → E} (hf : differentiable 𝕜 f) (n : ℕ) : differentiable 𝕜 (f^[n]) := nat.rec_on n differentiable_id (λ n ihn, ihn.comp hf) protected lemma differentiable_on.iterate {f : E → E} (hf : differentiable_on 𝕜 f s) (hs : maps_to f s s) (n : ℕ) : differentiable_on 𝕜 (f^[n]) s := nat.rec_on n differentiable_on_id (λ n ihn, ihn.comp hf hs) variable {x} protected lemma has_fderiv_at_filter.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_fderiv_at_filter (f^[n]) (f'^n) x L := begin induction n with n ihn, { exact has_fderiv_at_filter_id x L }, { change has_fderiv_at_filter (f^[n] ∘ f) (f'^(n+1)) x L, rw [pow_succ'], refine has_fderiv_at_filter.comp x _ hf, rw hx, exact ihn.mono hL } end protected lemma has_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_fderiv_at (f^[n]) (f'^n) x := begin refine hf.iterate _ hx n, convert hf.continuous_at, exact hx.symm end protected lemma has_fderiv_within_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_fderiv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_fderiv_within_at (f^[n]) (f'^n) s x := begin refine hf.iterate _ hx n, convert tendsto_inf.2 ⟨hf.continuous_within_at, _⟩, exacts [hx.symm, (tendsto_principal_principal.2 hs).mono_left inf_le_right] end protected lemma has_strict_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E} (hf : has_strict_fderiv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_fderiv_at (f^[n]) (f'^n) x := begin induction n with n ihn, { exact has_strict_fderiv_at_id x }, { change has_strict_fderiv_at (f^[n] ∘ f) (f'^(n+1)) x, rw [pow_succ'], refine has_strict_fderiv_at.comp x _ hf, rwa hx } end protected lemma differentiable_at.iterate {f : E → E} (hf : differentiable_at 𝕜 f x) (hx : f x = x) (n : ℕ) : differentiable_at 𝕜 (f^[n]) x := exists.elim hf $ λ f' hf, (hf.iterate hx n).differentiable_at protected lemma differentiable_within_at.iterate {f : E → E} (hf : differentiable_within_at 𝕜 f s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : differentiable_within_at 𝕜 (f^[n]) s x := exists.elim hf $ λ f' hf, (hf.iterate hx hs n).differentiable_within_at end composition section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ section prod variables {f₂ : E → G} {f₂' : E →L[𝕜] G} protected lemma has_strict_fderiv_at.prod (hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x := hf₁.prod_left hf₂ lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x L := hf₁.prod_left hf₂ lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod hf₂ lemma differentiable_within_at.prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) @[simp] lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = (fderiv 𝕜 f₁ x).prod (fderiv 𝕜 f₂ x) := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).fderiv lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = (fderiv_within 𝕜 f₁ s x).prod (fderiv_within 𝕜 f₂ s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at end end prod section fst variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_fst : has_strict_fderiv_at prod.fst (fst 𝕜 E F) p := (fst 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.fst (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := has_strict_fderiv_at_fst.comp x h lemma has_fderiv_at_filter_fst {L : filter (E × F)} : has_fderiv_at_filter prod.fst (fst 𝕜 E F) p L := (fst 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.fst (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_fst.comp x h lemma has_fderiv_at_fst : has_fderiv_at prod.fst (fst 𝕜 E F) p := has_fderiv_at_filter_fst protected lemma has_fderiv_at.fst (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x := h.fst lemma has_fderiv_within_at_fst {s : set (E × F)} : has_fderiv_within_at prod.fst (fst 𝕜 E F) s p := has_fderiv_at_filter_fst protected lemma has_fderiv_within_at.fst (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') s x := h.fst lemma differentiable_at_fst : differentiable_at 𝕜 prod.fst p := has_fderiv_at_fst.differentiable_at @[simp] protected lemma differentiable_at.fst (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).1) x := differentiable_at_fst.comp x h lemma differentiable_fst : differentiable 𝕜 (prod.fst : E × F → E) := λ x, differentiable_at_fst @[simp] protected lemma differentiable.fst (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).1) := differentiable_fst.comp h lemma differentiable_within_at_fst {s : set (E × F)} : differentiable_within_at 𝕜 prod.fst s p := differentiable_at_fst.differentiable_within_at protected lemma differentiable_within_at.fst (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).1) s x := differentiable_at_fst.comp_differentiable_within_at x h lemma differentiable_on_fst {s : set (E × F)} : differentiable_on 𝕜 prod.fst s := differentiable_fst.differentiable_on protected lemma differentiable_on.fst (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).1) s := differentiable_fst.comp_differentiable_on h lemma fderiv_fst : fderiv 𝕜 prod.fst p = fst 𝕜 E F := has_fderiv_at_fst.fderiv lemma fderiv.fst (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).1) x = (fst 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.fst.fderiv lemma fderiv_within_fst {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.fst s p = fst 𝕜 E F := has_fderiv_within_at_fst.fderiv_within hs lemma fderiv_within.fst (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).1) s x = (fst 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.fst.fderiv_within hs end fst section snd variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F} lemma has_strict_fderiv_at_snd : has_strict_fderiv_at prod.snd (snd 𝕜 E F) p := (snd 𝕜 E F).has_strict_fderiv_at protected lemma has_strict_fderiv_at.snd (h : has_strict_fderiv_at f₂ f₂' x) : has_strict_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := has_strict_fderiv_at_snd.comp x h lemma has_fderiv_at_filter_snd {L : filter (E × F)} : has_fderiv_at_filter prod.snd (snd 𝕜 E F) p L := (snd 𝕜 E F).has_fderiv_at_filter protected lemma has_fderiv_at_filter.snd (h : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x L := has_fderiv_at_filter_snd.comp x h lemma has_fderiv_at_snd : has_fderiv_at prod.snd (snd 𝕜 E F) p := has_fderiv_at_filter_snd protected lemma has_fderiv_at.snd (h : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x := h.snd lemma has_fderiv_within_at_snd {s : set (E × F)} : has_fderiv_within_at prod.snd (snd 𝕜 E F) s p := has_fderiv_at_filter_snd protected lemma has_fderiv_within_at.snd (h : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') s x := h.snd lemma differentiable_at_snd : differentiable_at 𝕜 prod.snd p := has_fderiv_at_snd.differentiable_at @[simp] protected lemma differentiable_at.snd (h : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λ x, (f₂ x).2) x := differentiable_at_snd.comp x h lemma differentiable_snd : differentiable 𝕜 (prod.snd : E × F → F) := λ x, differentiable_at_snd @[simp] protected lemma differentiable.snd (h : differentiable 𝕜 f₂) : differentiable 𝕜 (λ x, (f₂ x).2) := differentiable_snd.comp h lemma differentiable_within_at_snd {s : set (E × F)} : differentiable_within_at 𝕜 prod.snd s p := differentiable_at_snd.differentiable_within_at protected lemma differentiable_within_at.snd (h : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λ x, (f₂ x).2) s x := differentiable_at_snd.comp_differentiable_within_at x h lemma differentiable_on_snd {s : set (E × F)} : differentiable_on 𝕜 prod.snd s := differentiable_snd.differentiable_on protected lemma differentiable_on.snd (h : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λ x, (f₂ x).2) s := differentiable_snd.comp_differentiable_on h lemma fderiv_snd : fderiv 𝕜 prod.snd p = snd 𝕜 E F := has_fderiv_at_snd.fderiv lemma fderiv.snd (h : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λ x, (f₂ x).2) x = (snd 𝕜 F G).comp (fderiv 𝕜 f₂ x) := h.has_fderiv_at.snd.fderiv lemma fderiv_within_snd {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) : fderiv_within 𝕜 prod.snd s p = snd 𝕜 E F := has_fderiv_within_at_snd.fderiv_within hs lemma fderiv_within.snd (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) : fderiv_within 𝕜 (λ x, (f₂ x).2) s x = (snd 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) := h.has_fderiv_within_at.snd.fderiv_within hs end snd section prod_map variables {f₂ : G → G'} {f₂' : G →L[𝕜] G'} {y : G} (p : E × G) -- TODO (Lean 3.8): use `prod.map f f₂`` protected theorem has_strict_fderiv_at.prod_map (hf : has_strict_fderiv_at f f' p.1) (hf₂ : has_strict_fderiv_at f₂ f₂' p.2) : has_strict_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_strict_fderiv_at_fst).prod (hf₂.comp p has_strict_fderiv_at_snd) protected theorem has_fderiv_at.prod_map (hf : has_fderiv_at f f' p.1) (hf₂ : has_fderiv_at f₂ f₂' p.2) : has_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p := (hf.comp p has_fderiv_at_fst).prod (hf₂.comp p has_fderiv_at_snd) @[simp] protected theorem differentiable_at.prod_map (hf : differentiable_at 𝕜 f p.1) (hf₂ : differentiable_at 𝕜 f₂ p.2) : differentiable_at 𝕜 (λ p : E × G, (f p.1, f₂ p.2)) p := (hf.comp p differentiable_at_fst).prod (hf₂.comp p differentiable_at_snd) end prod_map end cartesian_product section const_smul /-! ### Derivative of a function multiplied by a constant -/ theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : 𝕜) : has_strict_fderiv_at (λ x, c • f x) (c • f') x := (c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ y, f y + g y) (f' + g') x := (hf.add hg).congr_left $ λ y, by simp; abel theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp; abel theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) @[simp] lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, f y + c) f' x := add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _) theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at @[simp] lemma differentiable_within_at_add_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at @[simp] lemma differentiable_at_add_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y + c) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c @[simp] lemma differentiable_on_add_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y + c) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c @[simp] lemma differentiable_add_const_iff (c : F) : differentiable 𝕜 (λ y, f y + c) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩ lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := if hf : differentiable_within_at 𝕜 f s x then (hf.has_fderiv_within_at.add_const c).fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf, fderiv_within_zero_of_not_differentiable_within_at], simpa } lemma fderiv_add_const (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_add_const unique_diff_within_at_univ] theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ y, c + f y) f' x := zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at @[simp] lemma differentiable_within_at_const_add_iff (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at @[simp] lemma differentiable_at_const_add_iff (c : F) : differentiable_at 𝕜 (λ y, c + f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c @[simp] lemma differentiable_on_const_add_iff (c : F) : differentiable_on 𝕜 (λ y, c + f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c @[simp] lemma differentiable_const_add_iff (c : F) : differentiable 𝕜 (λ y, c + f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩ lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := by simpa only [add_comm] using fderiv_within_add_const hxs c lemma fderiv_const_add (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := by simp only [add_comm c, fderiv_add_const] end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (E → F)} {A' : ι → (E →L[𝕜] F)} theorem has_strict_fderiv_at.sum (h : ∀ i ∈ u, has_strict_fderiv_at (A i) (A' i) x) : has_strict_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := begin dsimp [has_strict_fderiv_at] at *, convert is_o.sum h, simp [finset.sum_sub_distrib, continuous_linear_map.sum_apply] end theorem has_fderiv_at_filter.sum (h : ∀ i ∈ u, has_fderiv_at_filter (A i) (A' i) x L) : has_fderiv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := begin dsimp [has_fderiv_at_filter] at *, convert is_o.sum h, simp [continuous_linear_map.sum_apply] end theorem has_fderiv_within_at.sum (h : ∀ i ∈ u, has_fderiv_within_at (A i) (A' i) s x) : has_fderiv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_fderiv_at_filter.sum h theorem has_fderiv_at.sum (h : ∀ i ∈ u, has_fderiv_at (A i) (A' i) x) : has_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_fderiv_at_filter.sum h theorem differentiable_within_at.sum (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : differentiable_within_at 𝕜 (λ y, ∑ i in u, A i y) s x := has_fderiv_within_at.differentiable_within_at $ has_fderiv_within_at.sum $ λ i hi, (h i hi).has_fderiv_within_at @[simp] theorem differentiable_at.sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : differentiable_at 𝕜 (λ y, ∑ i in u, A i y) x := has_fderiv_at.differentiable_at $ has_fderiv_at.sum $ λ i hi, (h i hi).has_fderiv_at theorem differentiable_on.sum (h : ∀ i ∈ u, differentiable_on 𝕜 (A i) s) : differentiable_on 𝕜 (λ y, ∑ i in u, A i y) s := λ x hx, differentiable_within_at.sum $ λ i hi, h i hi x hx @[simp] theorem differentiable.sum (h : ∀ i ∈ u, differentiable 𝕜 (A i)) : differentiable 𝕜 (λ y, ∑ i in u, A i y) := λ x, differentiable_at.sum $ λ i hi, h i hi x theorem fderiv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : fderiv_within 𝕜 (λ y, ∑ i in u, A i y) s x = (∑ i in u, fderiv_within 𝕜 (A i) s x) := (has_fderiv_within_at.sum (λ i hi, (h i hi).has_fderiv_within_at)).fderiv_within hxs theorem fderiv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : fderiv 𝕜 (λ y, ∑ i in u, A i y) x = (∑ i in u, fderiv 𝕜 (A i) x) := (has_fderiv_at.sum (λ i hi, (h i hi).has_fderiv_at)).fderiv end sum section pi /-! ### Derivatives of functions `f : E → Π i, F' i` In this section we formulate `has_*fderiv*_pi` theorems as `iff`s, and provide two versions of each theorem: * the version without `'` deals with `φ : Π i, E → F' i` and `φ' : Π i, E →L[𝕜] F' i` and is designed to deduce differentiability of `λ x i, φ i x` from differentiability of each `φ i`; * the version with `'` deals with `Φ : E → Π i, F' i` and `Φ' : E →L[𝕜] Π i, F' i` and is designed to deduce differentiability of the components `λ x, Φ x i` from differentiability of `Φ`. -/ variables {ι : Type*} [fintype ι] {F' : ι → Type*} [Π i, normed_group (F' i)] [Π i, normed_space 𝕜 (F' i)] {φ : Π i, E → F' i} {φ' : Π i, E →L[𝕜] F' i} {Φ : E → Π i, F' i} {Φ' : E →L[𝕜] Π i, F' i} @[simp] lemma has_strict_fderiv_at_pi' : has_strict_fderiv_at Φ Φ' x ↔ ∀ i, has_strict_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x := begin simp only [has_strict_fderiv_at, continuous_linear_map.coe_pi], exact is_o_pi end @[simp] lemma has_strict_fderiv_at_pi : has_strict_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔ ∀ i, has_strict_fderiv_at (φ i) (φ' i) x := has_strict_fderiv_at_pi' @[simp] lemma has_fderiv_at_filter_pi' : has_fderiv_at_filter Φ Φ' x L ↔ ∀ i, has_fderiv_at_filter (λ x, Φ x i) ((proj i).comp Φ') x L := begin simp only [has_fderiv_at_filter, continuous_linear_map.coe_pi], exact is_o_pi end lemma has_fderiv_at_filter_pi : has_fderiv_at_filter (λ x i, φ i x) (continuous_linear_map.pi φ') x L ↔ ∀ i, has_fderiv_at_filter (φ i) (φ' i) x L := has_fderiv_at_filter_pi' @[simp] lemma has_fderiv_at_pi' : has_fderiv_at Φ Φ' x ↔ ∀ i, has_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x := has_fderiv_at_filter_pi' lemma has_fderiv_at_pi : has_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔ ∀ i, has_fderiv_at (φ i) (φ' i) x := has_fderiv_at_filter_pi @[simp] lemma has_fderiv_within_at_pi' : has_fderiv_within_at Φ Φ' s x ↔ ∀ i, has_fderiv_within_at (λ x, Φ x i) ((proj i).comp Φ') s x := has_fderiv_at_filter_pi' lemma has_fderiv_within_at_pi : has_fderiv_within_at (λ x i, φ i x) (continuous_linear_map.pi φ') s x ↔ ∀ i, has_fderiv_within_at (φ i) (φ' i) s x := has_fderiv_at_filter_pi @[simp] lemma differentiable_within_at_pi : differentiable_within_at 𝕜 Φ s x ↔ ∀ i, differentiable_within_at 𝕜 (λ x, Φ x i) s x := ⟨λ h i, (has_fderiv_within_at_pi'.1 h.has_fderiv_within_at i).differentiable_within_at, λ h, (has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).differentiable_within_at⟩ @[simp] lemma differentiable_at_pi : differentiable_at 𝕜 Φ x ↔ ∀ i, differentiable_at 𝕜 (λ x, Φ x i) x := ⟨λ h i, (has_fderiv_at_pi'.1 h.has_fderiv_at i).differentiable_at, λ h, (has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).differentiable_at⟩ lemma differentiable_on_pi : differentiable_on 𝕜 Φ s ↔ ∀ i, differentiable_on 𝕜 (λ x, Φ x i) s := ⟨λ h i x hx, differentiable_within_at_pi.1 (h x hx) i, λ h x hx, differentiable_within_at_pi.2 (λ i, h i x hx)⟩ lemma differentiable_pi : differentiable 𝕜 Φ ↔ ∀ i, differentiable 𝕜 (λ x, Φ x i) := ⟨λ h i x, differentiable_at_pi.1 (h x) i, λ h x, differentiable_at_pi.2 (λ i, h i x)⟩ -- TODO: find out which version (`φ` or `Φ`) works better with `rw`/`simp` lemma fderiv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (φ i) s x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ x i, φ i x) s x = pi (λ i, fderiv_within 𝕜 (φ i) s x) := (has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).fderiv_within hs lemma fderiv_pi (h : ∀ i, differentiable_at 𝕜 (φ i) x) : fderiv 𝕜 (λ x i, φ i x) x = pi (λ i, fderiv 𝕜 (φ i) x) := (has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).fderiv end pi section neg /-! ### Derivative of the negative of a function -/ theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, -f x) (-f') x := (-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at @[simp] lemma differentiable_within_at_neg_iff : differentiable_within_at 𝕜 (λy, -f y) s x ↔ differentiable_within_at 𝕜 f s x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at @[simp] lemma differentiable_at_neg_iff : differentiable_at 𝕜 (λy, -f y) x ↔ differentiable_at 𝕜 f x := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg @[simp] lemma differentiable_on_neg_iff : differentiable_on 𝕜 (λy, -f y) s ↔ differentiable_on 𝕜 f s := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg @[simp] lemma differentiable_neg_iff : differentiable 𝕜 (λy, -f y) ↔ differentiable 𝕜 f := ⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩ lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := if h : differentiable_within_at 𝕜 f s x then h.has_fderiv_within_at.neg.fderiv_within hxs else by { rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at, neg_zero], simpa } @[simp] lemma fderiv_neg : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_neg unique_diff_within_at_univ] end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_strict_fderiv_at.sub (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) : has_strict_fderiv_at (λ x, f x - g x) (f' - g') x := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) @[simp] lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_strict_fderiv_at.sub_const (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, f x - c) f' x := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at @[simp] lemma differentiable_within_at_sub_const_iff (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x ↔ differentiable_within_at 𝕜 f s x := by simp only [sub_eq_add_neg, differentiable_within_at_add_const_iff] lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at @[simp] lemma differentiable_at_sub_const_iff (c : F) : differentiable_at 𝕜 (λ y, f y - c) x ↔ differentiable_at 𝕜 f x := by simp only [sub_eq_add_neg, differentiable_at_add_const_iff] lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c @[simp] lemma differentiable_on_sub_const_iff (c : F) : differentiable_on 𝕜 (λ y, f y - c) s ↔ differentiable_on 𝕜 f s := by simp only [sub_eq_add_neg, differentiable_on_add_const_iff] lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c @[simp] lemma differentiable_sub_const_iff (c : F) : differentiable 𝕜 (λ y, f y - c) ↔ differentiable 𝕜 f := by simp only [sub_eq_add_neg, differentiable_add_const_iff] lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_add_const hxs] lemma fderiv_sub_const (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := by simp only [sub_eq_add_neg, fderiv_add_const] theorem has_strict_fderiv_at.const_sub (hf : has_strict_fderiv_at f f' x) (c : F) : has_strict_fderiv_at (λ x, c - f x) (-f') x := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at @[simp] lemma differentiable_within_at_const_sub_iff (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x ↔ differentiable_within_at 𝕜 f s x := by simp [sub_eq_add_neg] lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at @[simp] lemma differentiable_at_const_sub_iff (c : F) : differentiable_at 𝕜 (λ y, c - f y) x ↔ differentiable_at 𝕜 f x := by simp [sub_eq_add_neg] lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c @[simp] lemma differentiable_on_const_sub_iff (c : F) : differentiable_on 𝕜 (λ y, c - f y) s ↔ differentiable_on 𝕜 f s := by simp [sub_eq_add_neg] lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c @[simp] lemma differentiable_const_sub_iff (c : F) : differentiable 𝕜 (λ y, c - f y) ↔ differentiable 𝕜 f := by simp [sub_eq_add_neg] lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := by simp only [sub_eq_add_neg, fderiv_within_const_add, fderiv_within_neg, hxs] lemma fderiv_const_sub (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := by simp only [← fderiv_within_univ, fderiv_within_const_sub unique_diff_within_at_univ] end sub section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_strict_fderiv_at b (h.deriv p) p := begin rw has_strict_fderiv_at, set T := (E × F) × (E × F), have : is_o (λ q : T, b (q.1 - q.2)) (λ q : T, ∥q.1 - q.2∥ * 1) (𝓝 (p, p)), { refine (h.is_O'.comp_tendsto le_top).trans_is_o _, simp only [(∘)], refine (is_O_refl (λ q : T, ∥q.1 - q.2∥) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _), rw [← sub_self p], exact continuous_at_fst.sub continuous_at_snd }, simp only [mul_one, is_o_norm_right] at this, refine (is_o.congr_of_sub _).1 this, clear this, convert_to is_o (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) (λ q : T, q.1 - q.2) (𝓝 (p, p)), { ext ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩, simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right], abel }, have : is_o (λ q : T, p - q.2) (λ q, (1:ℝ)) (𝓝 (p, p)), from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd), apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o, refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right, refine is_o.mul_is_O _ (is_O_refl _ _), exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top : _).trans_is_o this).norm_left end lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := (h.has_strict_fderiv_at p).has_fderiv_at lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) : continuous b := h.differentiable.continuous lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} : continuous (λe, b (e, f)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} : continuous (λf, b (e, f)) := h.continuous.comp (continuous_const.prod_mk continuous_id) end bilinear_map namespace continuous_linear_equiv /-! ### The set of continuous linear equivalences between two Banach spaces is open In this section we establish that the set of continuous linear equivalences between two Banach spaces is an open subset of the space of linear maps between them. These facts are placed here because the proof uses `is_bounded_bilinear_map.continuous_left`, proved just above as a consequence of its differentiability. -/ protected lemma is_open [complete_space E] : is_open (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) := begin nontriviality E, rw [is_open_iff_mem_nhds, forall_range_iff], refine λ e, mem_nhds_sets _ (mem_range_self _), let O : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : F →L[𝕜] E).comp f, have h_O : continuous O := is_bounded_bilinear_map_comp.continuous_left, convert units.is_open.preimage h_O using 1, ext f', split, { rintros ⟨e', rfl⟩, exact ⟨(e'.trans e.symm).to_unit, rfl⟩ }, { rintros ⟨w, hw⟩, use (units_equiv 𝕜 E w).trans e, ext x, simp [hw] } end protected lemma nhds [complete_space E] (e : E ≃L[𝕜] F) : (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) ∈ 𝓝 (e : E →L[𝕜] F) := mem_nhds_sets continuous_linear_equiv.is_open (by simp) end continuous_linear_equiv section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function If `c` is a differentiable scalar-valued function and `f` is a differentiable vector-valued function, then `λ x, c x • f x` is differentiable as well. Lemmas in this section works for function `c` taking values in the base field, as well as in a normed algebra over the base field: e.g., they work for `c : E → ℂ` and `f : E → F` provided that `F` is a complex normed vector space. -/ variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] variables {c : E → 𝕜'} {c' : E →L[𝕜] 𝕜'} theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $ hc.prod hf theorem has_fderiv_within_at.smul (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $ hc.prod hf theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := (is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $ hc.prod hf lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) @[simp] lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) : has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x) theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s) theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x) lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two scalar-valued functions -/ variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜} theorem has_strict_fderiv_at.mul (hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) : has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := by { convert hc.smul hd, ext z, apply mul_comm } theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := by { convert hc.smul hd, ext z, apply mul_comm } lemma differentiable_within_at.mul (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at @[simp] lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) @[simp] lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, c y * d) (d • c') x := by simpa only [smul_zero, zero_add] using hc.mul (has_strict_fderiv_at_const d x) theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, c y * d) (d • c') s x := by simpa only [smul_zero, zero_add] using hc.mul (has_fderiv_within_at_const d x s) theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, c y * d) (d • c') x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.mul_const d end lemma differentiable_within_at.mul_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, c y * d) s x := (hc.has_fderiv_within_at.mul_const d).differentiable_within_at lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, c y * d) x := (hc.has_fderiv_at.mul_const d).differentiable_at lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, c y * d) s := λx hx, (hc x hx).mul_const d lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, c y * d) := λx, (hc x).mul_const d lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_strict_fderiv_at.const_mul (hc : has_strict_fderiv_at c c' x) (d : 𝕜) : has_strict_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_within_at.const_mul (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, d * c y) (d • c') s x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end lemma differentiable_within_at.const_mul (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, d * c y) s x := (hc.has_fderiv_within_at.const_mul d).differentiable_within_at lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, d * c y) x := (hc.has_fderiv_at.const_mul d).differentiable_at lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, d * c y) s := λx hx, (hc x hx).const_mul d lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, d * c y) := λx, (hc x).const_mul d lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.const_mul d).fderiv_within hxs lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.const_mul d).fderiv end mul section algebra_inverse variables {R : Type*} [normed_ring R] [normed_algebra 𝕜 R] [complete_space R] open normed_ring continuous_linear_map ring /-- At an invertible element `x` of a normed algebra `R`, the Fréchet derivative of the inversion operation is the linear map `λ t, - x⁻¹ * t * x⁻¹`. -/ lemma has_fderiv_at_ring_inverse (x : units R) : has_fderiv_at ring.inverse (-lmul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹) x := begin have h_is_o : is_o (λ (t : R), inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) (λ (t : R), t) (𝓝 0), { refine (inverse_add_norm_diff_second_order x).trans_is_o ((is_o_norm_norm).mp _), simp only [normed_field.norm_pow, norm_norm], have h12 : 1 < 2 := by norm_num, convert (asymptotics.is_o_pow_pow h12).comp_tendsto tendsto_norm_zero, ext, simp }, have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0), { refine tendsto_zero_iff_norm_tendsto_zero.mpr _, exact tendsto_iff_norm_tendsto_zero.mp tendsto_id }, simp only [has_fderiv_at, has_fderiv_at_filter], convert h_is_o.comp_tendsto h_lim, ext y, simp only [coe_comp', function.comp_app, lmul_left_right_apply, neg_apply, inverse_unit x, units.inv_mul, add_sub_cancel'_right, mul_sub, sub_mul, one_mul, sub_neg_eq_add] end lemma differentiable_at_inverse (x : units R) : differentiable_at 𝕜 (@ring.inverse R _) x := (has_fderiv_at_ring_inverse x).differentiable_at lemma fderiv_inverse (x : units R) : fderiv 𝕜 (@ring.inverse R _) x = - lmul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹ := (has_fderiv_at_ring_inverse x).fderiv end algebra_inverse namespace continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_strict_fderiv_at protected lemma has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := iso.to_continuous_linear_map.has_fderiv_within_at protected lemma has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := iso.to_continuous_linear_map.fderiv_within hxs protected lemma differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := begin refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩, have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x := iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H, rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this, end lemma comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ, iso.comp_differentiable_within_at_iff] lemma comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := begin rw [differentiable_on, differentiable_on], simp only [iso.comp_differentiable_within_at_iff], end lemma comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := begin rw [← differentiable_on_univ, ← differentiable_on_univ], exact iso.comp_differentiable_on_iff end lemma comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := begin refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩, have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl }, have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'), by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.id_comp], rw [A, B], exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H end lemma comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := begin refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩, convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm end lemma comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp] lemma comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := begin by_cases h : differentiable_within_at 𝕜 f s x, { rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] }, { have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x, from mt iso.comp_differentiable_within_at_iff.1 h, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this, continuous_linear_map.comp_zero] } end lemma comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := begin rw [← fderiv_within_univ, ← fderiv_within_univ], exact iso.comp_fderiv_within unique_diff_within_at_univ, end end continuous_linear_equiv namespace linear_isometry_equiv /-! ### Differentiability of linear isometry equivs, and invariance of differentiability -/ variable (iso : E ≃ₗᵢ[𝕜] F) protected lemma has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x := (iso : E ≃L[𝕜] F).has_strict_fderiv_at protected lemma has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := (iso : E ≃L[𝕜] F).has_fderiv_within_at protected lemma has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := (iso : E ≃L[𝕜] F).has_fderiv_at protected lemma differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := (iso : E ≃L[𝕜] F).fderiv_within hxs protected lemma differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := (iso : E ≃L[𝕜] F).comp_differentiable_within_at_iff lemma comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := (iso : E ≃L[𝕜] F).comp_differentiable_at_iff lemma comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := (iso : E ≃L[𝕜] F).comp_differentiable_on_iff lemma comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := (iso : E ≃L[𝕜] F).comp_differentiable_iff lemma comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := (iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff lemma comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x := (iso : E ≃L[𝕜] F).comp_has_strict_fderiv_at_iff lemma comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := (iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff lemma comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := (iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff' lemma comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := (iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff' lemma comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := (iso : E ≃L[𝕜] F).comp_fderiv_within hxs lemma comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := (iso : E ≃L[𝕜] F).comp_fderiv end linear_isometry_equiv /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin replace hg := hg.prod_map' hg, replace hfg := hfg.prod_mk_nhds hfg, have : is_O (λ p : F × F, g p.1 - g p.2 - f'.symm (p.1 - p.2)) (λ p : F × F, f' (g p.1 - g p.2) - (p.1 - p.2)) (𝓝 (a, a)), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p ⟨hp1, hp2⟩, simp [hp1, hp2] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p ⟨hp1, hp2⟩, simp only [(∘), hp1, hp2] } end /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F} (hg : continuous_at g a) (hf : has_fderiv_at f (f' : E →L[𝕜] F) (g a)) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_fderiv_at g (f'.symm : F →L[𝕜] E) a := begin have : is_O (λ x : F, g x - g a - f'.symm (x - a)) (λ x : F, f' (g x - g a) - (x - a)) (𝓝 a), { refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl), simp }, refine this.trans_is_o _, clear this, refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _) (eventually_of_forall $ λ _, rfl)).trans_is_O _, { rintros p hp, simp [hp, hfg.self_of_nhds] }, { refine (hf.is_O_sub_rev.comp_tendsto hg).congr' (eventually_of_forall $ λ _, rfl) (hfg.mono _), rintros p hp, simp only [(∘), hp, hfg.self_of_nhds] } end /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` in the sense of strict differentiability at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_strict_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_strict_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_strict_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an invertible derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (htff' : has_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) : has_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a := htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha) lemma has_fderiv_within_at.eventually_ne (h : has_fderiv_within_at f f' s x) (hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) : ∀ᶠ z in 𝓝[s \ {x}] x, f z ≠ f x := begin rw [nhds_within, diff_eq, ← inf_principal, ← inf_assoc, eventually_inf_principal], have A : is_O (λ z, z - x) (λ z, f' (z - x)) (𝓝[s] x) := (is_O_iff.2 $ hf'.imp $ λ C hC, eventually_of_forall $ λ z, hC _), have : (λ z, f z - f x) ~[𝓝[s] x] (λ z, f' (z - x)) := h.trans_is_O A, simpa [not_imp_not, sub_eq_zero] using (A.trans this.is_O_symm).eq_zero_imp end lemma has_fderiv_at.eventually_ne (h : has_fderiv_at f f' x) (hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) : ∀ᶠ z in 𝓝[{x}ᶜ] x, f z ≠ f x := by simpa only [compl_eq_univ_diff] using (has_fderiv_within_at_univ.2 h).eventually_ne hf' end section /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) : maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) := begin rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : dense_range f') : unique_diff_within_at 𝕜 (f '' s) (f x) := begin refine ⟨h'.dense_of_maps_to f'.continuous hs.1 _, h.continuous_within_at.mem_closure_image hs.2⟩, show submodule.span 𝕜 (tangent_cone_at 𝕜 s x) ≤ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))).comap f', rw [submodule.span_le], exact h.maps_to_tangent_cone.mono (subset.refl _) submodule.subset_span end lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := h.unique_diff_within_at hs e'.surjective.dense_range lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) : unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s := begin split, { assume hs x hx, have A : s = e '' (e.symm '' s) := (equiv.symm_image_image (e.symm.to_linear_equiv.to_equiv) s).symm, have B : e.symm '' s = e⁻¹' s := equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s, rw [A, B, (e.apply_symm_apply x).symm], refine has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e e.has_fderiv_within_at (hs _ _), rwa [mem_preimage, e.apply_symm_apply x] }, { assume hs x hx, have : e ⁻¹' s = e.symm '' s := (equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s).symm, rw [this, (e.symm_apply_apply x).symm], exact has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e.symm e.symm.has_fderiv_within_at (hs _ hx) }, end end tangent_cone section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is differentiable over `ℂ`, then it is differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [normed_space 𝕜' E] variables [is_scalar_tower 𝕜 𝕜' E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [normed_space 𝕜' F] variables [is_scalar_tower 𝕜 𝕜' F] variables {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) : has_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) : differentiable_at 𝕜 f x := (h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) : differentiable_within_at 𝕜 f s x := (h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) : differentiable_on 𝕜 f s := λx hx, (h x hx).restrict_scalars 𝕜 lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) : differentiable 𝕜 f := λx, (h x).restrict_scalars 𝕜 end restrict_scalars
f2640c087dfe76e6ce5034ca1ceaeb77119efc97
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/set_theory/cardinal/finite.lean
537d6afb6d7e9cb32ef75e0077d3ee8a6067e236
[ "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
4,031
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.zmod.defs import set_theory.cardinal.basic /-! # Finite Cardinality Functions ## Main Definitions * `nat.card α` is the cardinality of `α` as a natural number. If `α` is infinite, `nat.card α = 0`. * `part_enat.card α` is the cardinality of `α` as an extended natural number (`part ℕ` implementation). If `α` is infinite, `part_enat.card α = ⊤`. -/ open cardinal noncomputable theory open_locale big_operators variables {α β : Type*} namespace nat /-- `nat.card α` is the cardinality of `α` as a natural number. If `α` is infinite, `nat.card α = 0`. -/ protected def card (α : Type*) : ℕ := (mk α).to_nat @[simp] lemma card_eq_fintype_card [fintype α] : nat.card α = fintype.card α := mk_to_nat_eq_card @[simp] lemma card_eq_zero_of_infinite [infinite α] : nat.card α = 0 := mk_to_nat_of_infinite lemma finite_of_card_ne_zero (h : nat.card α ≠ 0) : finite α := not_infinite_iff_finite.mp $ h ∘ @nat.card_eq_zero_of_infinite α lemma card_congr (f : α ≃ β) : nat.card α = nat.card β := cardinal.to_nat_congr f lemma card_eq_of_bijective (f : α → β) (hf : function.bijective f) : nat.card α = nat.card β := card_congr (equiv.of_bijective f hf) lemma card_eq_of_equiv_fin {α : Type*} {n : ℕ} (f : α ≃ fin n) : nat.card α = n := by simpa using card_congr f /-- If the cardinality is positive, that means it is a finite type, so there is an equivalence between `α` and `fin (nat.card α)`. See also `finite.equiv_fin`. -/ def equiv_fin_of_card_pos {α : Type*} (h : nat.card α ≠ 0) : α ≃ fin (nat.card α) := begin casesI fintype_or_infinite α, { simpa using fintype.equiv_fin α }, { simpa using h }, end lemma card_of_subsingleton (a : α) [subsingleton α] : nat.card α = 1 := begin letI := fintype.of_subsingleton a, rw [card_eq_fintype_card, fintype.card_of_subsingleton a] end @[simp] lemma card_unique [unique α] : nat.card α = 1 := card_of_subsingleton default lemma card_eq_one_iff_unique : nat.card α = 1 ↔ subsingleton α ∧ nonempty α := cardinal.to_nat_eq_one_iff_unique lemma card_eq_two_iff : nat.card α = 2 ↔ ∃ x y : α, x ≠ y ∧ {x, y} = @set.univ α := (to_nat_eq_iff two_ne_zero).trans $ iff.trans (by rw [nat.cast_two]) mk_eq_two_iff lemma card_eq_two_iff' (x : α) : nat.card α = 2 ↔ ∃! y, y ≠ x := (to_nat_eq_iff two_ne_zero).trans $ iff.trans (by rw [nat.cast_two]) (mk_eq_two_iff' x) theorem card_of_is_empty [is_empty α] : nat.card α = 0 := by simp @[simp] lemma card_prod (α β : Type*) : nat.card (α × β) = nat.card α * nat.card β := by simp only [nat.card, mk_prod, to_nat_mul, to_nat_lift] @[simp] lemma card_ulift (α : Type*) : nat.card (ulift α) = nat.card α := card_congr equiv.ulift @[simp] lemma card_plift (α : Type*) : nat.card (plift α) = nat.card α := card_congr equiv.plift lemma card_pi {β : α → Type*} [fintype α] : nat.card (Π a, β a) = ∏ a, nat.card (β a) := by simp_rw [nat.card, mk_pi, prod_eq_of_fintype, to_nat_lift, to_nat_finset_prod] lemma card_fun [finite α] : nat.card (α → β) = nat.card β ^ nat.card α := begin haveI := fintype.of_finite α, rw [nat.card_pi, finset.prod_const, finset.card_univ, ←nat.card_eq_fintype_card], end @[simp] lemma card_zmod (n : ℕ) : nat.card (zmod n) = n := begin cases n, { exact nat.card_eq_zero_of_infinite }, { rw [nat.card_eq_fintype_card, zmod.card] }, end end nat namespace part_enat /-- `part_enat.card α` is the cardinality of `α` as an extended natural number. If `α` is infinite, `part_enat.card α = ⊤`. -/ def card (α : Type*) : part_enat := (mk α).to_part_enat @[simp] lemma card_eq_coe_fintype_card [fintype α] : card α = fintype.card α := mk_to_part_enat_eq_coe_card @[simp] lemma card_eq_top_of_infinite [infinite α] : card α = ⊤ := mk_to_part_enat_of_infinite end part_enat
c87883f8218e12b2b2b519393bd558f97754a555
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/nat/choose/basic.lean
e1d811e9e8794b0b1630b2fc666da527983641f0
[ "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
8,148
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Bhavik Mehta -/ import data.nat.factorial /-! # Binomial coefficients This file contains a definition of binomial coefficients and simple lemmas (i.e. those not requiring more imports). ## Main definition and results - `nat.choose`: binomial coefficients, defined inductively - `nat.choose_eq_factorial_div_factorial`: a proof that `choose n k = n! / (k! * (n - k)!)` - `nat.choose_symm`: symmetry of binomial coefficients - `nat.choose_le_succ_of_lt_half_left`: `choose n k` is increasing for small values of `k` - `nat.choose_le_middle`: `choose n r` is maximised when `r` is `n/2` -/ open_locale nat namespace nat /-- `choose n k` is the number of `k`-element subsets in an `n`-element set. Also known as binomial coefficients. -/ def choose : ℕ → ℕ → ℕ | _ 0 := 1 | 0 (k + 1) := 0 | (n + 1) (k + 1) := choose n k + choose n (k + 1) @[simp] lemma choose_zero_right (n : ℕ) : choose n 0 = 1 := by cases n; refl @[simp] lemma choose_zero_succ (k : ℕ) : choose 0 (succ k) = 0 := rfl lemma choose_succ_succ (n k : ℕ) : choose (succ n) (succ k) = choose n k + choose n (succ k) := rfl lemma choose_eq_zero_of_lt : ∀ {n k}, n < k → choose n k = 0 | _ 0 hk := absurd hk dec_trivial | 0 (k + 1) hk := choose_zero_succ _ | (n + 1) (k + 1) hk := have hnk : n < k, from lt_of_succ_lt_succ hk, have hnk1 : n < k + 1, from lt_of_succ_lt hk, by rw [choose_succ_succ, choose_eq_zero_of_lt hnk, choose_eq_zero_of_lt hnk1] @[simp] lemma choose_self (n : ℕ) : choose n n = 1 := by induction n; simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)] @[simp] lemma choose_succ_self (n : ℕ) : choose n (succ n) = 0 := choose_eq_zero_of_lt (lt_succ_self _) @[simp] lemma choose_one_right (n : ℕ) : choose n 1 = n := by induction n; simp [*, choose, add_comm] /- The `n+1`-st triangle number is `n` more than the `n`-th triangle number -/ lemma triangle_succ (n : ℕ) : (n + 1) * ((n + 1) - 1) / 2 = n * (n - 1) / 2 + n := begin rw [← add_mul_div_left, mul_comm 2 n, ← mul_add, nat.add_sub_cancel, mul_comm], cases n; refl, apply zero_lt_succ end /-- `choose n 2` is the `n`-th triangle number. -/ lemma choose_two_right (n : ℕ) : choose n 2 = n * (n - 1) / 2 := begin induction n with n ih, simp, {rw triangle_succ n, simp [choose, ih], rw add_comm}, end lemma choose_pos : ∀ {n k}, k ≤ n → 0 < choose n k | 0 _ hk := by rw [eq_zero_of_le_zero hk]; exact dec_trivial | (n + 1) 0 hk := by simp; exact dec_trivial | (n + 1) (k + 1) hk := by rw choose_succ_succ; exact add_pos_of_pos_of_nonneg (choose_pos (le_of_succ_le_succ hk)) (nat.zero_le _) lemma succ_mul_choose_eq : ∀ n k, succ n * choose n k = choose (succ n) (succ k) * succ k | 0 0 := dec_trivial | 0 (k + 1) := by simp [choose] | (n + 1) 0 := by simp | (n + 1) (k + 1) := by rw [choose_succ_succ (succ n) (succ k), add_mul, ←succ_mul_choose_eq, mul_succ, ←succ_mul_choose_eq, add_right_comm, ←mul_add, ←choose_succ_succ, ←succ_mul] lemma choose_mul_factorial_mul_factorial : ∀ {n k}, k ≤ n → choose n k * k! * (n - k)! = n! | 0 _ hk := by simp [eq_zero_of_le_zero hk] | (n + 1) 0 hk := by simp | (n + 1) (succ k) hk := begin cases lt_or_eq_of_le hk with hk₁ hk₁, { have h : choose n k * k.succ! * (n-k)! = k.succ * n! := by rw ← choose_mul_factorial_mul_factorial (le_of_succ_le_succ hk); simp [factorial_succ, mul_comm, mul_left_comm], have h₁ : (n - k)! = (n - k) * (n - k.succ)! := by rw [← succ_sub_succ, succ_sub (le_of_lt_succ hk₁), factorial_succ], have h₂ : choose n (succ k) * k.succ! * ((n - k) * (n - k.succ)!) = (n - k) * n! := by rw ← choose_mul_factorial_mul_factorial (le_of_lt_succ hk₁); simp [factorial_succ, mul_comm, mul_left_comm, mul_assoc], have h₃ : k * n! ≤ n * n! := mul_le_mul_right _ (le_of_succ_le_succ hk), rw [choose_succ_succ, add_mul, add_mul, succ_sub_succ, h, h₁, h₂, ← add_one, add_mul, nat.mul_sub_right_distrib, factorial_succ, ← nat.add_sub_assoc h₃, add_assoc, ← add_mul, nat.add_sub_cancel_left, add_comm] }, { simp [hk₁, mul_comm, choose, nat.sub_self] } end theorem choose_eq_factorial_div_factorial {n k : ℕ} (hk : k ≤ n) : choose n k = n! / (k! * (n - k)!) := begin have : n! = choose n k * (k! * (n - k)!) := by rw ← mul_assoc; exact (choose_mul_factorial_mul_factorial hk).symm, exact (nat.div_eq_of_eq_mul_left (mul_pos (factorial_pos _) (factorial_pos _)) this).symm end theorem factorial_mul_factorial_dvd_factorial {n k : ℕ} (hk : k ≤ n) : k! * (n - k)! ∣ n! := by rw [←choose_mul_factorial_mul_factorial hk, mul_assoc]; exact dvd_mul_left _ _ @[simp] lemma choose_symm {n k : ℕ} (hk : k ≤ n) : choose n (n-k) = choose n k := by rw [choose_eq_factorial_div_factorial hk, choose_eq_factorial_div_factorial (sub_le _ _), nat.sub_sub_self hk, mul_comm] lemma choose_symm_of_eq_add {n a b : ℕ} (h : n = a + b) : nat.choose n a = nat.choose n b := by { convert nat.choose_symm (nat.le_add_left _ _), rw nat.add_sub_cancel} lemma choose_symm_add {a b : ℕ} : choose (a+b) a = choose (a+b) b := choose_symm_of_eq_add rfl lemma choose_symm_half (m : ℕ) : choose (2 * m + 1) (m + 1) = choose (2 * m + 1) m := by { apply choose_symm_of_eq_add, rw [add_comm m 1, add_assoc 1 m m, add_comm (2 * m) 1, two_mul m] } lemma choose_succ_right_eq (n k : ℕ) : choose n (k + 1) * (k + 1) = choose n k * (n - k) := begin have e : (n+1) * choose n k = choose n k * (k+1) + choose n (k+1) * (k+1), rw [← right_distrib, ← choose_succ_succ, succ_mul_choose_eq], rw [← nat.sub_eq_of_eq_add e, mul_comm, ← nat.mul_sub_left_distrib, nat.add_sub_add_right] end @[simp] lemma choose_succ_self_right : ∀ (n:ℕ), (n+1).choose n = n+1 | 0 := rfl | (n+1) := by rw [choose_succ_succ, choose_succ_self_right, choose_self] lemma choose_mul_succ_eq (n k : ℕ) : (n.choose k) * (n + 1) = ((n+1).choose k) * (n + 1 - k) := begin induction k with k ih, { simp }, by_cases hk : n < k + 1, { rw [choose_eq_zero_of_lt hk, sub_eq_zero_of_le hk, zero_mul, mul_zero] }, push_neg at hk, replace hk : k + 1 ≤ n + 1 := _root_.le_add_right hk, rw [choose_succ_succ], rw [add_mul, succ_sub_succ], rw [← choose_succ_right_eq], rw [← succ_sub_succ, nat.mul_sub_left_distrib], symmetry, apply nat.add_sub_cancel', exact mul_le_mul_left _ hk, end /-! ### Inequalities -/ /-- Show that `nat.choose` is increasing for small values of the right argument. -/ lemma choose_le_succ_of_lt_half_left {r n : ℕ} (h : r < n/2) : choose n r ≤ choose n (r+1) := begin refine le_of_mul_le_mul_right _ (nat.lt_sub_left_of_add_lt (lt_of_lt_of_le h (n.div_le_self 2))), rw ← choose_succ_right_eq, apply nat.mul_le_mul_left, rw [← nat.lt_iff_add_one_le, nat.lt_sub_left_iff_add_lt, ← mul_two], exact lt_of_lt_of_le (mul_lt_mul_of_pos_right h zero_lt_two) (n.div_mul_le_self 2), end /-- Show that for small values of the right argument, the middle value is largest. -/ private lemma choose_le_middle_of_le_half_left {n r : ℕ} (hr : r ≤ n/2) : choose n r ≤ choose n (n/2) := decreasing_induction (λ _ k a, (eq_or_lt_of_le a).elim (λ t, t.symm ▸ le_refl _) (λ h, trans (choose_le_succ_of_lt_half_left h) (k h))) hr (λ _, le_refl _) hr /-- `choose n r` is maximised when `r` is `n/2`. -/ lemma choose_le_middle (r n : ℕ) : choose n r ≤ choose n (n/2) := begin cases le_or_gt r n with b b, { cases le_or_lt r (n/2) with a h, { apply choose_le_middle_of_le_half_left a }, { rw ← choose_symm b, apply choose_le_middle_of_le_half_left, rw [div_lt_iff_lt_mul' zero_lt_two] at h, rw [le_div_iff_mul_le' zero_lt_two, nat.mul_sub_right_distrib, nat.sub_le_iff, mul_two, nat.add_sub_cancel], exact le_of_lt h } }, { rw choose_eq_zero_of_lt b, apply zero_le } end end nat
c186d1c5e9ad5bc999aea09ba6cf3bd10d1d41d1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/ElimDead.lean
28bdae95bf5886b2d6b441557582cc9dc088d678
[ "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,116
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.LCNF.CompilerM namespace Lean.Compiler.LCNF abbrev UsedLocalDecls := FVarIdHashSet /-- Collect set of (let) free variables in a LCNF value. This code exploits the LCNF property that local declarations do not occur in types. -/ def collectLocalDeclsType (s : UsedLocalDecls) (type : Expr) : UsedLocalDecls := go s type where go (s : UsedLocalDecls) (e : Expr) : UsedLocalDecls := match e with | .forallE .. => s | .lam _ _ b _ => go s b | .app f a => go (go s a) f | .fvar fvarId => s.insert fvarId | .letE .. | .proj .. | .mdata .. => unreachable! -- Valid LCNF type does not contain this kind of expr | _ => s def collectLocalDeclsArg (s : UsedLocalDecls) (arg : Arg) : UsedLocalDecls := match arg with | .erased => s | .type e => collectLocalDeclsType s e | .fvar fvarId => s.insert fvarId def collectLocalDeclsArgs (s : UsedLocalDecls) (args : Array Arg) : UsedLocalDecls := args.foldl (init := s) collectLocalDeclsArg def collectLocalDeclsLetValue (s : UsedLocalDecls) (e : LetValue) : UsedLocalDecls := match e with | .erased | .value .. => s | .proj _ _ fvarId => s.insert fvarId | .const _ _ args => collectLocalDeclsArgs s args | .fvar fvarId args => collectLocalDeclsArgs (s.insert fvarId) args namespace ElimDead abbrev M := StateRefT UsedLocalDecls CompilerM private abbrev collectArgM (arg : Arg) : M Unit := modify (collectLocalDeclsArg · arg) private abbrev collectLetValueM (e : LetValue) : M Unit := modify (collectLocalDeclsLetValue · e) private abbrev collectFVarM (fvarId : FVarId) : M Unit := modify (·.insert fvarId) mutual partial def visitFunDecl (funDecl : FunDecl) : M FunDecl := do let value ← elimDead funDecl.value funDecl.updateValue value partial def elimDead (code : Code) : M Code := do match code with | .let decl k => let k ← elimDead k if (← get).contains decl.fvarId then /- Remark: we don't need to collect `decl.type` because LCNF local declarations do not occur in types. -/ collectLetValueM decl.value return code.updateCont! k else eraseLetDecl decl return k | .fun decl k | .jp decl k => let k ← elimDead k if (← get).contains decl.fvarId then let decl ← visitFunDecl decl return code.updateFun! decl k else eraseFunDecl decl return k | .cases c => let alts ← c.alts.mapMonoM fun alt => return alt.updateCode (← elimDead alt.getCode) collectFVarM c.discr return code.updateAlts! alts | .return fvarId => collectFVarM fvarId; return code | .jmp fvarId args => collectFVarM fvarId; args.forM collectArgM; return code | .unreach .. => return code end end ElimDead def Code.elimDead (code : Code) : CompilerM Code := ElimDead.elimDead code |>.run' {} def Decl.elimDead (decl : Decl) : CompilerM Decl := do return { decl with value := (← decl.value.elimDead) } end Lean.Compiler.LCNF
9a91794b880aba705022fb9ba95200f8f92cf553
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/interactive/t12.lean
c6213977172dca9a50ed8b644e793ce2db342f93
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
1,120
lean
(* import("tactic.lua") -- Define a simple tactic using Lua auto = Repeat(OrElse(assumption_tac(), conj_tac(), conj_hyp_tac())) *) theorem T1 (A B : Bool) : A /\ B -> B /\ A := fun assumption : A /\ B, let lemma1 : A := (by auto), lemma2 : B := (by auto) in (show B /\ A, by auto) print environment 1. -- print proof for the previous theorem theorem T2 (A B : Bool) : A /\ B -> B /\ A := fun assumption : A /\ B, let lemma1 : A := _, lemma2 : B := _ in _. auto. done. auto. done. auto. done. theorem T3 (A B : Bool) : A /\ B -> B /\ A := fun assumption : A /\ B, let lemma1 : A := _, lemma2 : B := _ in _. conj_hyp. exact. done. conj_hyp. exact. done. apply and_intro. exact. done. theorem T4 (A B : Bool) : A /\ B -> B /\ A := fun assumption : A /\ B, let lemma1 : A := _, lemma2 : B := _ in (show B /\ A, by auto). conj_hyp. exact. done. conj_hyp. exact. done.
61ea9e50a39d41e12e14d5ae95544cdd362e7d1d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/split_ifs.lean
59905ced6a81c1fe2581e7dd83f215ada12eb32f
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,304
lean
/- Copyright (c) 2018 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner Tactic to split if-then-else-expressions. -/ import tactic.hint open expr tactic namespace tactic open interactive meta def find_if_cond : expr → option expr | e := e.fold none $ λ e _ acc, acc <|> do c ← match e with | `(@ite _ %%c %%_ _ _) := some c | `(@dite _ %%c %%_ _ _) := some c | _ := none end, guard ¬c.has_var, find_if_cond c <|> return c meta def find_if_cond_at (at_ : loc) : tactic (option expr) := do lctx ← at_.get_locals, lctx ← lctx.mmap infer_type, tgt ← target, let es := if at_.include_goal then tgt::lctx else lctx, return $ find_if_cond $ es.foldr app (default expr) run_cmd mk_simp_attr `split_if_reduction run_cmd add_doc_string `simp_attr.split_if_reduction "Simp set for if-then-else statements" attribute [split_if_reduction] if_pos if_neg dif_pos dif_neg meta def reduce_ifs_at (at_ : loc) : tactic unit := do sls ← get_user_simp_lemmas `split_if_reduction, let cfg : simp_config := { fail_if_unchanged := ff }, let discharger := assumption <|> (applyc `not_not_intro >> assumption), hs ← at_.get_locals, hs.mmap' (λ h, simp_hyp sls [] h cfg discharger >> skip), when at_.include_goal (simp_target sls [] cfg discharger >> skip) meta def split_if1 (c : expr) (n : name) (at_ : loc) : tactic unit := by_cases c n; reduce_ifs_at at_ private meta def get_next_name (names : ref (list name)) : tactic name := do ns ← read_ref names, match ns with | [] := get_unused_name `h | n::ns := do write_ref names ns, return n end private meta def value_known (c : expr) : tactic bool := do lctx ← local_context, lctx ← lctx.mmap infer_type, return $ c ∈ lctx ∨ `(¬%%c) ∈ lctx private meta def split_ifs_core (at_ : loc) (names : ref (list name)) : list expr → tactic unit | done := do some cond ← find_if_cond_at at_ | fail "no if-then-else expressions to split", let cond := match cond with `(¬%%p) := p | p := p end, if cond ∈ done then skip else do no_split ← value_known cond, if no_split then reduce_ifs_at at_; try (split_ifs_core (cond :: done)) else do n ← get_next_name names, split_if1 cond n at_; try (split_ifs_core (cond :: done)) meta def split_ifs (names : list name) (at_ : loc := loc.ns [none]) := using_new_ref names $ λ names, split_ifs_core at_ names [] namespace interactive open interactive interactive.types expr lean.parser /-- Splits all if-then-else-expressions into multiple goals. Given a goal of the form `g (if p then x else y)`, `split_ifs` will produce two goals: `p ⊢ g x` and `¬p ⊢ g y`. If there are multiple ite-expressions, then `split_ifs` will split them all, starting with a top-most one whose condition does not contain another ite-expression. `split_ifs at *` splits all ite-expressions in all hypotheses as well as the goal. `split_ifs with h₁ h₂ h₃` overrides the default names for the hypotheses. -/ meta def split_ifs (at_ : parse location) (names : parse with_ident_list) : tactic unit := tactic.split_ifs names at_ add_hint_tactic "split_ifs" add_tactic_doc { name := "split_ifs", category := doc_category.tactic, decl_names := [``split_ifs], tags := ["case bashing"] } end interactive end tactic
e73d48f8606f3692b70ffdaa5fc965d6fcdc303a
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Server/InfoUtils.lean
68d6fd0db164ae9cb89beeff36ea7ebc82cae70a
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
14,087
lean
/- Copyright (c) 2021 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.PrettyPrinter protected structure String.Range where start : String.Pos stop : String.Pos deriving Inhabited, Repr, BEq, Hashable def String.Range.contains (r : String.Range) (pos : String.Pos) (includeStop := false) : Bool := r.start <= pos && (if includeStop then pos <= r.stop else pos < r.stop) def Lean.Syntax.getRange? (stx : Syntax) (originalOnly := false) : Option String.Range := match stx.getPos? originalOnly, stx.getTailPos? originalOnly with | some start, some stop => some { start, stop } | _, _ => none namespace Lean.Elab /-- Visit nodes, passing in a surrounding context (the innermost one) and accumulating results on the way back up. -/ partial def InfoTree.visitM [Monad m] (preNode : ContextInfo → Info → (children : Std.PersistentArray InfoTree) → m Unit := fun _ _ _ => pure ()) (postNode : ContextInfo → Info → (children : Std.PersistentArray InfoTree) → List (Option α) → m α) : InfoTree → m (Option α) := go none where go | _, context ctx t => go ctx t | some ctx, node i cs => do preNode ctx i cs let as ← cs.toList.mapM (go <| i.updateContext? ctx) postNode ctx i cs as | none, node .. => panic! "unexpected context-free info tree node" | _, hole .. => pure none /-- `InfoTree.visitM` specialized to `Unit` return type -/ def InfoTree.visitM' [Monad m] (preNode : ContextInfo → Info → (children : Std.PersistentArray InfoTree) → m Unit := fun _ _ _ => pure ()) (postNode : ContextInfo → Info → (children : Std.PersistentArray InfoTree) → m Unit := fun _ _ _ => pure ()) (t : InfoTree) : m Unit := t.visitM preNode (fun ci i cs _ => postNode ci i cs) |> discard /-- Visit nodes bottom-up, passing in a surrounding context (the innermost one) and the union of nested results (empty at leaves). -/ def InfoTree.collectNodesBottomUp (p : ContextInfo → Info → Std.PersistentArray InfoTree → List α → List α) (i : InfoTree) : List α := i.visitM (m := Id) (postNode := fun ci i cs as => p ci i cs (as.filterMap id).join) |>.getD [] /-- For every branch of the `InfoTree`, find the deepest node in that branch for which `p` returns `some _` and return the union of all such nodes. The visitor `p` is given a node together with its innermost surrounding `ContextInfo`. -/ partial def InfoTree.deepestNodes (p : ContextInfo → Info → Std.PersistentArray InfoTree → Option α) (infoTree : InfoTree) : List α := infoTree.collectNodesBottomUp fun ctx i cs rs => if rs.isEmpty then match p ctx i cs with | some r => [r] | none => [] else rs partial def InfoTree.foldInfo (f : ContextInfo → Info → α → α) (init : α) : InfoTree → α := go none init where go ctx? a | context ctx t => go ctx a t | node i ts => let a := match ctx? with | none => a | some ctx => f ctx i a ts.foldl (init := a) (go <| i.updateContext? ctx?) | _ => a def Info.isTerm : Info → Bool | ofTermInfo _ => true | _ => false def Info.isCompletion : Info → Bool | ofCompletionInfo .. => true | _ => false def InfoTree.getCompletionInfos (infoTree : InfoTree) : Array (ContextInfo × CompletionInfo) := infoTree.foldInfo (init := #[]) fun ctx info result => match info with | Info.ofCompletionInfo info => result.push (ctx, info) | _ => result def Info.stx : Info → Syntax | ofTacticInfo i => i.stx | ofTermInfo i => i.stx | ofCommandInfo i => i.stx | ofMacroExpansionInfo i => i.stx | ofFieldInfo i => i.stx | ofCompletionInfo i => i.stx | ofCustomInfo i => i.stx | ofUserWidgetInfo i => i.stx | ofFVarAliasInfo _ => .missing | ofFieldRedeclInfo i => i.stx def Info.lctx : Info → LocalContext | Info.ofTermInfo i => i.lctx | Info.ofFieldInfo i => i.lctx | _ => LocalContext.empty def Info.pos? (i : Info) : Option String.Pos := i.stx.getPos? (originalOnly := true) def Info.tailPos? (i : Info) : Option String.Pos := i.stx.getTailPos? (originalOnly := true) def Info.range? (i : Info) : Option String.Range := i.stx.getRange? (originalOnly := true) def Info.contains (i : Info) (pos : String.Pos) (includeStop := false) : Bool := i.range?.any (·.contains pos includeStop) def Info.size? (i : Info) : Option String.Pos := do let pos ← i.pos? let tailPos ← i.tailPos? return tailPos - pos -- `Info` without position information are considered to have "infinite" size def Info.isSmaller (i₁ i₂ : Info) : Bool := match i₁.size?, i₂.pos? with | some sz₁, some sz₂ => sz₁ < sz₂ | some _, none => true | _, _ => false def Info.occursBefore? (i : Info) (hoverPos : String.Pos) : Option String.Pos := do let tailPos ← i.tailPos? guard (tailPos ≤ hoverPos) return hoverPos - tailPos def Info.occursInside? (i : Info) (hoverPos : String.Pos) : Option String.Pos := do let headPos ← i.pos? let tailPos ← i.tailPos? guard (headPos ≤ hoverPos && hoverPos < tailPos) return hoverPos - headPos def InfoTree.smallestInfo? (p : Info → Bool) (t : InfoTree) : Option (ContextInfo × Info) := let ts := t.deepestNodes fun ctx i _ => if p i then some (ctx, i) else none let infos := ts.map fun (ci, i) => let diff := i.tailPos?.get! - i.pos?.get! (diff, ci, i) infos.toArray.getMax? (fun a b => a.1 > b.1) |>.map fun (_, ci, i) => (ci, i) /-- Find an info node, if any, which should be shown on hover/cursor at position `hoverPos`. -/ partial def InfoTree.hoverableInfoAt? (t : InfoTree) (hoverPos : String.Pos) (includeStop := false) (omitAppFns := false) : Option (ContextInfo × Info) := Id.run do let results := t.visitM (m := Id) (postNode := fun ctx info _ results => do let mut results := results.bind (·.getD []) if omitAppFns && info.stx.isOfKind ``Parser.Term.app && info.stx[0].isIdent then results := results.filter (·.2.2.stx != info.stx[0]) unless results.isEmpty do return results -- prefer innermost results /- Remark: we skip `info` nodes associated with the `nullKind` and `withAnnotateState` because they are used by tactics (e.g., `rewrite`) to control which goal is displayed in the info views. See issue #1403 -/ if info.stx.isOfKind nullKind || info.toElabInfo?.any (·.elaborator == `Lean.Elab.Tactic.evalWithAnnotateState) then return results unless (info matches Info.ofFieldInfo _ || info.toElabInfo?.isSome) && info.contains hoverPos includeStop do return results let r := info.range?.get! let priority := if r.stop == hoverPos then 0 -- prefer results directly *after* the hover position (only matters for `includeStop = true`; see #767) else if info matches .ofTermInfo { expr := .fvar .., .. } then 0 -- prefer results for constants over variables (which overlap at declaration names) else 1 [(priority, ctx, info)]) |>.getD [] let maxPrio? := results.map (·.1) |>.maximum? let res? := results.find? (·.1 == maxPrio?) |>.map (·.2) if let some (_, i) := res? then if let .ofTermInfo ti := i then if ti.expr.isSyntheticSorry then return none return res? def Info.type? (i : Info) : MetaM (Option Expr) := match i with | Info.ofTermInfo ti => Meta.inferType ti.expr | Info.ofFieldInfo fi => Meta.inferType fi.val | _ => return none def Info.docString? (i : Info) : MetaM (Option String) := do let env ← getEnv if let Info.ofTermInfo ti := i then if let some n := ti.expr.constName? then return ← findDocString? env n if let Info.ofFieldInfo fi := i then return ← findDocString? env fi.projName if let some ei := i.toElabInfo? then return ← findDocString? env ei.stx.getKind <||> findDocString? env ei.elaborator return none /-- Construct a hover popup, if any, from an info node in a context.-/ def Info.fmtHover? (ci : ContextInfo) (i : Info) : IO (Option Format) := do ci.runMetaM i.lctx do let mut fmts := #[] try if let some f ← fmtTerm? then fmts := fmts.push f catch _ => pure () if let some m ← i.docString? then fmts := fmts.push m if fmts.isEmpty then return none else return f!"\n***\n".joinSep fmts.toList where fmtTerm? : MetaM (Option Format) := do match i with | Info.ofTermInfo ti => let e ← instantiateMVars ti.expr if e.isSort then -- Types of sorts are funny to look at in widgets, but ultimately not very helpful return none let tp ← instantiateMVars (← Meta.inferType e) let tpFmt ← Meta.ppExpr tp if e.isConst then -- Recall that `ppExpr` adds a `@` if the constant has implicit arguments, and it is quite distracting let eFmt ← withOptions (pp.fullNames.set · true |> (pp.universes.set · true)) <| PrettyPrinter.ppConst e return some f!"```lean {eFmt} : {tpFmt} ```" else let eFmt ← Meta.ppExpr e -- Try not to show too scary internals let showTerm := if let .fvar _ := e then if let some ldecl := (← getLCtx).findFVar? e then !ldecl.userName.hasMacroScopes else false else isAtomicFormat eFmt let fmt := if showTerm then f!"{eFmt} : {tpFmt}" else tpFmt return some f!"```lean {fmt} ```" | Info.ofFieldInfo fi => let tp ← Meta.inferType fi.val let tpFmt ← Meta.ppExpr tp return some f!"```lean {fi.fieldName} : {tpFmt} ```" | _ => return none isAtomicFormat : Format → Bool | Std.Format.text _ => true | Std.Format.group f _ => isAtomicFormat f | Std.Format.nest _ f => isAtomicFormat f | Std.Format.tag _ f => isAtomicFormat f | _ => false structure GoalsAtResult where ctxInfo : ContextInfo tacticInfo : TacticInfo useAfter : Bool /-- Whether the tactic info is further indented than the hover position. -/ indented : Bool -- for overlapping goals, only keep those of the highest reported priority priority : Nat /-- Try to retrieve `TacticInfo` for `hoverPos`. We retrieve all `TacticInfo` nodes s.t. `hoverPos` is inside the node's range plus trailing whitespace. We usually prefer the innermost such nodes so that for composite tactics such as `induction`, we show the nested proofs' states. However, if `hoverPos` is after the tactic, we prefer nodes that are not indented relative to it, meaning that e.g. at `|` in ```lean have := by exact foo | ``` we show the (final, see below) state of `have`, not `exact`. Moreover, we instruct the LSP server to use the state after tactic execution if - the hover position is after the info's start position *and* - there is no nested tactic info after the hover position (tactic combinators should decide for themselves where to show intermediate states by calling `withTacticInfoContext`) -/ partial def InfoTree.goalsAt? (text : FileMap) (t : InfoTree) (hoverPos : String.Pos) : List GoalsAtResult := let gs := t.collectNodesBottomUp fun ctx i cs gs => Id.run do if let Info.ofTacticInfo ti := i then if let (some pos, some tailPos) := (i.pos?, i.tailPos?) then let trailSize := i.stx.getTrailingSize -- show info at EOF even if strictly outside token + trail let atEOF := tailPos.byteIdx + trailSize == text.source.endPos.byteIdx -- include at least one trailing character (see also `priority` below) if pos ≤ hoverPos ∧ (hoverPos.byteIdx < tailPos.byteIdx + max 1 trailSize || atEOF) then -- overwrite bottom-up results according to "innermost" heuristics documented above if gs.isEmpty || hoverPos ≥ tailPos && gs.all (·.indented) then return [{ ctxInfo := ctx tacticInfo := ti useAfter := hoverPos > pos && !cs.any (hasNestedTactic pos tailPos) indented := (text.toPosition pos).column > (text.toPosition hoverPos).column -- use goals just before cursor as fall-back only -- thus for `(by foo)`, placing the cursor after `foo` shows its state as long -- as there is no state on `)` priority := if hoverPos.byteIdx == tailPos.byteIdx + trailSize then 0 else 1 }] return gs let maxPrio? := gs.map (·.priority) |>.maximum? gs.filter (some ·.priority == maxPrio?) where hasNestedTactic (pos tailPos) : InfoTree → Bool | InfoTree.node i@(Info.ofTacticInfo _) cs => Id.run do if let `(by $_) := i.stx then return false -- ignore term-nested proofs such as in `simp [show p by ...]` if let (some pos', some tailPos') := (i.pos?, i.tailPos?) then -- ignore preceding nested infos -- ignore nested infos of the same tactic, e.g. from expansion if tailPos' > hoverPos && (pos', tailPos') != (pos, tailPos) then return true cs.any (hasNestedTactic pos tailPos) | InfoTree.node (Info.ofMacroExpansionInfo _) cs => cs.any (hasNestedTactic pos tailPos) | _ => false partial def InfoTree.termGoalAt? (t : InfoTree) (hoverPos : String.Pos) : Option (ContextInfo × Info) := -- In the case `f a b`, where `f` is an identifier, the term goal at `f` should be the goal for the full application `f a b`. hoverableInfoAt? t hoverPos (includeStop := true) (omitAppFns := true) partial def InfoTree.hasSorry : InfoTree → IO Bool := go none where go ci? | .context ci t => go ci t | .node i cs => if let (some ci, .ofTermInfo ti) := (ci?, i) then do let expr ← ti.runMetaM ci (instantiateMVars ti.expr) return expr.hasSorry -- we assume that `cs` are subterms of `ti.expr` and -- thus do not have to be checked as well else cs.anyM (go ci?) | _ => return false end Lean.Elab
15ef09174c330989539877dd6fc66472f5be1dac
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/category_theory/limits/preserves.lean
4e5d0266087abae0bd80e137ced7f172bc710c07
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
10,243
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison, Reid Barton -- Preservation and reflection of (co)limits. import category_theory.whiskering import category_theory.limits.limits open category_theory namespace category_theory.limits universes v u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Sort u₁} [𝒞 : category.{v+1} C] variables {D : Sort u₂} [𝒟 : category.{v+1} D] include 𝒞 𝒟 variables {J : Type v} [small_category J] {K : J ⥤ C} /- Note on "preservation of (co)limits" There are various distinct notions of "preserving limits". The one we aim to capture here is: A functor F : C → D "preserves limits" if it sends every limit cone in C to a limit cone in D. Informally, F preserves all the limits which exist in C. Note that: * Of course, we do not want to require F to *strictly* take chosen limit cones of C to chosen limit cones of D. Indeed, the above definition makes no reference to a choice of limit cones so it makes sense without any conditions on C or D. * Some diagrams in C may have no limit. In this case, there is no condition on the behavior of F on such diagrams. There are other notions (such as "flat functor") which impose conditions also on diagrams in C with no limits, but these are not considered here. In order to be able to express the property of preserving limits of a certain form, we say that a functor F preserves the limit of a diagram K if F sends every limit cone on K to a limit cone. This is vacuously satisfied when K does not admit a limit, which is consistent with the above definition of "preserves limits". -/ class preserves_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves : Π {c : cone K}, is_limit c → is_limit (F.map_cone c)) class preserves_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (preserves : Π {c : cocone K}, is_colimit c → is_colimit (F.map_cocone c)) @[class] def preserves_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := Π {K : J ⥤ C}, preserves_limit K F @[class] def preserves_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := Π {K : J ⥤ C}, preserves_colimit K F @[class] def preserves_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := Π {J : Type v} {𝒥 : small_category J}, by exactI preserves_limits_of_shape J F @[class] def preserves_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := Π {J : Type v} {𝒥 : small_category J}, by exactI preserves_colimits_of_shape J F instance preserves_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_limit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance preserves_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (preserves_colimit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance preserves_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (preserves_limits_of_shape J F) := by split; intros; funext; apply subsingleton.elim instance preserves_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (preserves_colimits_of_shape J F) := by split; intros; funext; apply subsingleton.elim instance preserves_limits_subsingleton (F : C ⥤ D) : subsingleton (preserves_limits F) := by split; intros; funext; resetI; apply subsingleton.elim instance preserves_colimits_subsingleton (F : C ⥤ D) : subsingleton (preserves_colimits F) := by split; intros; funext; resetI; apply subsingleton.elim instance preserves_limit_of_preserves_limits_of_shape (F : C ⥤ D) [H : preserves_limits_of_shape J F] : preserves_limit K F := H instance preserves_colimit_of_preserves_colimits_of_shape (F : C ⥤ D) [H : preserves_colimits_of_shape J F] : preserves_colimit K F := H instance preserves_limits_of_shape_of_preserves_limits (F : C ⥤ D) [H : preserves_limits F] : preserves_limits_of_shape J F := @H J _ instance preserves_colimits_of_shape_of_preserves_colimits (F : C ⥤ D) [H : preserves_colimits F] : preserves_colimits_of_shape J F := @H J _ instance id_preserves_limits : preserves_limits (functor.id C) := λ J 𝒥 K, by exactI ⟨λ c h, ⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ instance id_preserves_colimits : preserves_colimits (functor.id C) := λ J 𝒥 K, by exactI ⟨λ c h, ⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ section variables {E : Sort u₃} [ℰ : category.{v+1} E] variables (F : C ⥤ D) (G : D ⥤ E) local attribute [elab_simple] preserves_limit.preserves preserves_colimit.preserves instance comp_preserves_limit [preserves_limit K F] [preserves_limit (K ⋙ F) G] : preserves_limit K (F ⋙ G) := ⟨λ c h, preserves_limit.preserves G (preserves_limit.preserves F h)⟩ instance comp_preserves_colimit [preserves_colimit K F] [preserves_colimit (K ⋙ F) G] : preserves_colimit K (F ⋙ G) := ⟨λ c h, preserves_colimit.preserves G (preserves_colimit.preserves F h)⟩ end /-- If F preserves one limit cone for the diagram K, then it preserves any limit cone for K. -/ def preserves_limit_of_preserves_limit_cone {F : C ⥤ D} {t : cone K} (h : is_limit t) (hF : is_limit (F.map_cone t)) : preserves_limit K F := ⟨λ t' h', is_limit.of_iso_limit hF (functor.on_iso _ (is_limit.unique h h'))⟩ /-- If F preserves one colimit cocone for the diagram K, then it preserves any colimit cocone for K. -/ def preserves_colimit_of_preserves_colimit_cocone {F : C ⥤ D} {t : cocone K} (h : is_colimit t) (hF : is_colimit (F.map_cocone t)) : preserves_colimit K F := ⟨λ t' h', is_colimit.of_iso_colimit hF (functor.on_iso _ (is_colimit.unique h h'))⟩ /- A functor F : C → D reflects limits if whenever the image of a cone under F is a limit cone in D, the cone was already a limit cone in C. Note that again we do not assume a priori that D actually has any limits. -/ class reflects_limit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects : Π {c : cone K}, is_limit (F.map_cone c) → is_limit c) class reflects_colimit (K : J ⥤ C) (F : C ⥤ D) : Type (max u₁ u₂ v) := (reflects : Π {c : cocone K}, is_colimit (F.map_cocone c) → is_colimit c) @[class] def reflects_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := Π {K : J ⥤ C}, reflects_limit K F @[class] def reflects_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) : Type (max u₁ u₂ v) := Π {K : J ⥤ C}, reflects_colimit K F @[class] def reflects_limits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_limits_of_shape J F @[class] def reflects_colimits (F : C ⥤ D) : Type (max u₁ u₂ (v+1)) := Π {J : Type v} {𝒥 : small_category J}, by exactI reflects_colimits_of_shape J F instance reflects_limit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_limit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance reflects_colimit_subsingleton (K : J ⥤ C) (F : C ⥤ D) : subsingleton (reflects_colimit K F) := by split; rintros ⟨a⟩ ⟨b⟩; congr instance reflects_limits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (reflects_limits_of_shape J F) := by split; intros; funext; apply subsingleton.elim instance reflects_colimits_of_shape_subsingleton (J : Type v) [small_category J] (F : C ⥤ D) : subsingleton (reflects_colimits_of_shape J F) := by split; intros; funext; apply subsingleton.elim instance reflects_limits_subsingleton (F : C ⥤ D) : subsingleton (reflects_limits F) := by split; intros; funext; resetI; apply subsingleton.elim instance reflects_colimits_subsingleton (F : C ⥤ D) : subsingleton (reflects_colimits F) := by split; intros; funext; resetI; apply subsingleton.elim instance reflects_limit_of_reflects_limits_of_shape (K : J ⥤ C) (F : C ⥤ D) [H : reflects_limits_of_shape J F] : reflects_limit K F := H instance reflects_colimit_of_reflects_colimits_of_shape (K : J ⥤ C) (F : C ⥤ D) [H : reflects_colimits_of_shape J F] : reflects_colimit K F := H instance reflects_limits_of_shape_of_reflects_limits (F : C ⥤ D) [H : reflects_limits F] : reflects_limits_of_shape J F := @H J _ instance reflects_colimits_of_shape_of_reflects_colimits (F : C ⥤ D) [H : reflects_colimits F] : reflects_colimits_of_shape J F := @H J _ instance id_reflects_limits : reflects_limits (functor.id C) := λ J 𝒥 K, by exactI ⟨λ c h, ⟨λ s, h.lift ⟨s.X, λ j, s.π.app j, λ j j' f, s.π.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ instance id_reflects_colimits : reflects_colimits (functor.id C) := λ J 𝒥 K, by exactI ⟨λ c h, ⟨λ s, h.desc ⟨s.X, λ j, s.ι.app j, λ j j' f, s.ι.naturality f⟩, by cases K; rcases c with ⟨_, _, _⟩; intros s j; cases s; exact h.fac _ j, by cases K; rcases c with ⟨_, _, _⟩; intros s m w; rcases s with ⟨_, _, _⟩; exact h.uniq _ m w⟩⟩ section variables {E : Sort u₃} [ℰ : category.{v+1} E] variables (F : C ⥤ D) (G : D ⥤ E) instance comp_reflects_limit [reflects_limit K F] [reflects_limit (K ⋙ F) G] : reflects_limit K (F ⋙ G) := ⟨λ c h, reflects_limit.reflects (reflects_limit.reflects h)⟩ instance comp_reflects_colimit [reflects_colimit K F] [reflects_colimit (K ⋙ F) G] : reflects_colimit K (F ⋙ G) := ⟨λ c h, reflects_colimit.reflects (reflects_colimit.reflects h)⟩ end end category_theory.limits
e42cf5113e1d7d8f4965c9128c753377f05f3ff3
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport/Util/String.lean
3448642c16fd3ac4b1566c34ac8c12a64ea337fe
[ "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
1,366
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ namespace String def snake2pascalCamel (snake : String) (lc : Bool) : String := Id.run do let mut pascal := join (snake.splitOn "_" |>.map capitalize) if lc then pascal := decapitalize pascal if snake.startsWith "_" then pascal := "_" ++ pascal if snake.endsWith "_" then pascal := pascal ++ "_" pascal def snake2pascal (snake : String) : String := snake2pascalCamel snake (lc := false) def snake2camel (snake : String) : String := snake2pascalCamel snake (lc := true) inductive CapsKind | snake | camel | pascal def getCapsKind (snake : String) : CapsKind := Id.run do let s := snake let startPos := if s.startsWith "_" then ⟨1⟩ else 0 let stopPos := if s.endsWith "_" then s.endPos - ⟨1⟩ else s.endPos let s := Substring.mk s startPos stopPos if s.contains '_' then CapsKind.snake else if s.front == s.front.toLower then CapsKind.camel else CapsKind.pascal def convertSnake (snake : String) : CapsKind → String | CapsKind.snake => snake | CapsKind.camel => snake.snake2camel | CapsKind.pascal => snake.snake2pascal def cmp (x y : String) : Ordering := if x < y then Ordering.lt else if x > y then Ordering.gt else Ordering.eq end String
049b7a57d329e187b3b0b5fef4f219d1f0e961c2
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/category_theory/limits/creates.lean
a90b09d246fc3c0cc78afcddb1bcef0cf67bbdda
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
16,844
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.preserves.basic open category_theory category_theory.limits noncomputable theory namespace category_theory universes v u₁ u₂ u₃ variables {C : Type u₁} [category.{v} C] section creates variables {D : Type u₂} [category.{v} D] variables {J : Type v} [small_category J] {K : J ⥤ C} /-- Define the lift of a cone: For a cone `c` for `K ⋙ F`, give a cone for `K` which is a lift of `c`, i.e. the image of it under `F` is (iso) to `c`. We will then use this as part of the definition of creation of limits: every limit cone has a lift. Note this definition is really only useful when `c` is a limit already. -/ structure liftable_cone (K : J ⥤ C) (F : C ⥤ D) (c : cone (K ⋙ F)) := (lifted_cone : cone K) (valid_lift : F.map_cone lifted_cone ≅ c) /-- Define the lift of a cocone: For a cocone `c` for `K ⋙ F`, give a cocone for `K` which is a lift of `c`, i.e. the image of it under `F` is (iso) to `c`. We will then use this as part of the definition of creation of colimits: every limit cocone has a lift. Note this definition is really only useful when `c` is a colimit already. -/ structure liftable_cocone (K : J ⥤ C) (F : C ⥤ D) (c : cocone (K ⋙ F)) := (lifted_cocone : cocone K) (valid_lift : F.map_cocone lifted_cocone ≅ c) /-- Definition 3.3.1 of [Riehl]. We say that `F` creates limits of `K` if, given any limit cone `c` for `K ⋙ F` (i.e. below) we can lift it to a cone "above", and further that `F` reflects limits for `K`. If `F` reflects isomorphisms, it suffices to show only that the lifted cone is a limit - see `creates_limit_of_reflects_iso`. -/ class creates_limit (K : J ⥤ C) (F : C ⥤ D) extends reflects_limit K F := (lifts : Π c, is_limit c → liftable_cone K F c) /-- `F` creates limits of shape `J` if `F` creates the limit of any diagram `K : J ⥤ C`. -/ class creates_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) := (creates_limit : Π {K : J ⥤ C}, creates_limit K F) /-- `F` creates limits if it creates limits of shape `J` for any small `J`. -/ class creates_limits (F : C ⥤ D) := (creates_limits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI creates_limits_of_shape J F) /-- Dual of definition 3.3.1 of [Riehl]. We say that `F` creates colimits of `K` if, given any limit cocone `c` for `K ⋙ F` (i.e. below) we can lift it to a cocone "above", and further that `F` reflects limits for `K`. If `F` reflects isomorphisms, it suffices to show only that the lifted cocone is a limit - see `creates_limit_of_reflects_iso`. -/ class creates_colimit (K : J ⥤ C) (F : C ⥤ D) extends reflects_colimit K F := (lifts : Π c, is_colimit c → liftable_cocone K F c) /-- `F` creates colimits of shape `J` if `F` creates the colimit of any diagram `K : J ⥤ C`. -/ class creates_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) := (creates_colimit : Π {K : J ⥤ C}, creates_colimit K F) /-- `F` creates colimits if it creates colimits of shape `J` for any small `J`. -/ class creates_colimits (F : C ⥤ D) := (creates_colimits_of_shape : Π {J : Type v} {𝒥 : small_category J}, by exactI creates_colimits_of_shape J F) attribute [instance, priority 100] -- see Note [lower instance priority] creates_limits_of_shape.creates_limit creates_limits.creates_limits_of_shape creates_colimits_of_shape.creates_colimit creates_colimits.creates_colimits_of_shape /- Interface to the `creates_limit` class. -/ /-- `lift_limit t` is the cone for `K` given by lifting the limit `t` for `K ⋙ F`. -/ def lift_limit {K : J ⥤ C} {F : C ⥤ D} [creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) : cone K := (creates_limit.lifts c t).lifted_cone /-- The lifted cone has an image isomorphic to the original cone. -/ def lifted_limit_maps_to_original {K : J ⥤ C} {F : C ⥤ D} [creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) : F.map_cone (lift_limit t) ≅ c := (creates_limit.lifts c t).valid_lift /-- The lifted cone is a limit. -/ def lifted_limit_is_limit {K : J ⥤ C} {F : C ⥤ D} [creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) : is_limit (lift_limit t) := reflects_limit.reflects (is_limit.of_iso_limit t (lifted_limit_maps_to_original t).symm) /-- If `F` creates the limit of `K` and `K ⋙ F` has a limit, then `K` has a limit. -/ lemma has_limit_of_created (K : J ⥤ C) (F : C ⥤ D) [has_limit (K ⋙ F)] [creates_limit K F] : has_limit K := has_limit.mk { cone := lift_limit (limit.is_limit (K ⋙ F)), is_limit := lifted_limit_is_limit _ } /- Interface to the `creates_colimit` class. -/ /-- `lift_colimit t` is the cocone for `K` given by lifting the colimit `t` for `K ⋙ F`. -/ def lift_colimit {K : J ⥤ C} {F : C ⥤ D} [creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) : cocone K := (creates_colimit.lifts c t).lifted_cocone /-- The lifted cocone has an image isomorphic to the original cocone. -/ def lifted_colimit_maps_to_original {K : J ⥤ C} {F : C ⥤ D} [creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) : F.map_cocone (lift_colimit t) ≅ c := (creates_colimit.lifts c t).valid_lift /-- The lifted cocone is a colimit. -/ def lifted_colimit_is_colimit {K : J ⥤ C} {F : C ⥤ D} [creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) : is_colimit (lift_colimit t) := reflects_colimit.reflects (is_colimit.of_iso_colimit t (lifted_colimit_maps_to_original t).symm) /-- If `F` creates the limit of `K` and `K ⋙ F` has a limit, then `K` has a limit. -/ lemma has_colimit_of_created (K : J ⥤ C) (F : C ⥤ D) [has_colimit (K ⋙ F)] [creates_colimit K F] : has_colimit K := has_colimit.mk { cocone := lift_colimit (colimit.is_colimit (K ⋙ F)), is_colimit := lifted_colimit_is_colimit _ } /-- A helper to show a functor creates limits. In particular, if we can show that for any limit cone `c` for `K ⋙ F`, there is a lift of it which is a limit and `F` reflects isomorphisms, then `F` creates limits. Usually, `F` creating limits says that _any_ lift of `c` is a limit, but here we only need to show that our particular lift of `c` is a limit. -/ structure lifts_to_limit (K : J ⥤ C) (F : C ⥤ D) (c : cone (K ⋙ F)) (t : is_limit c) extends liftable_cone K F c := (makes_limit : is_limit lifted_cone) /-- A helper to show a functor creates colimits. In particular, if we can show that for any limit cocone `c` for `K ⋙ F`, there is a lift of it which is a limit and `F` reflects isomorphisms, then `F` creates colimits. Usually, `F` creating colimits says that _any_ lift of `c` is a colimit, but here we only need to show that our particular lift of `c` is a colimit. -/ structure lifts_to_colimit (K : J ⥤ C) (F : C ⥤ D) (c : cocone (K ⋙ F)) (t : is_colimit c) extends liftable_cocone K F c := (makes_colimit : is_colimit lifted_cocone) /-- If `F` reflects isomorphisms and we can lift any limit cone to a limit cone, then `F` creates limits. In particular here we don't need to assume that F reflects limits. -/ def creates_limit_of_reflects_iso {K : J ⥤ C} {F : C ⥤ D} [reflects_isomorphisms F] (h : Π c t, lifts_to_limit K F c t) : creates_limit K F := { lifts := λ c t, (h c t).to_liftable_cone, to_reflects_limit := { reflects := λ (d : cone K) (hd : is_limit (F.map_cone d)), begin let d' : cone K := (h (F.map_cone d) hd).to_liftable_cone.lifted_cone, let i : F.map_cone d' ≅ F.map_cone d := (h (F.map_cone d) hd).to_liftable_cone.valid_lift, let hd' : is_limit d' := (h (F.map_cone d) hd).makes_limit, let f : d ⟶ d' := hd'.lift_cone_morphism d, have : (cones.functoriality K F).map f = i.inv := (hd.of_iso_limit i.symm).uniq_cone_morphism, haveI : is_iso ((cones.functoriality K F).map f) := (by { rw this, apply_instance }), haveI : is_iso f := is_iso_of_reflects_iso f (cones.functoriality K F), exact is_limit.of_iso_limit hd' (as_iso f).symm, end } } /-- When `F` is fully faithful, and `has_limit (K ⋙ F)`, to show that `F` creates the limit for `K` it suffices to exhibit a lift of the chosen limit cone for `K ⋙ F`. -/ -- Notice however that even if the isomorphism is `iso.refl _`, -- this construction will insert additional identity morphisms in the cone maps, -- so the constructed limits may not be ideal, definitionally. def creates_limit_of_fully_faithful_of_lift {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] [has_limit (K ⋙ F)] (c : cone K) (i : F.map_cone c ≅ limit.cone (K ⋙ F)) : creates_limit K F := creates_limit_of_reflects_iso (λ c' t, { lifted_cone := c, valid_lift := i.trans (is_limit.unique_up_to_iso (limit.is_limit _) t), makes_limit := is_limit.of_faithful F (is_limit.of_iso_limit (limit.is_limit _) i.symm) (λ s, F.preimage _) (λ s, F.image_preimage _) }) /-- When `F` is fully faithful, and `has_limit (K ⋙ F)`, to show that `F` creates the limit for `K` it suffices to show that the chosen limit point is in the essential image of `F`. -/ -- Notice however that even if the isomorphism is `iso.refl _`, -- this construction will insert additional identity morphisms in the cone maps, -- so the constructed limits may not be ideal, definitionally. def creates_limit_of_fully_faithful_of_iso {K : J ⥤ C} {F : C ⥤ D} [full F] [faithful F] [has_limit (K ⋙ F)] (X : C) (i : F.obj X ≅ limit (K ⋙ F)) : creates_limit K F := creates_limit_of_fully_faithful_of_lift ({ X := X, π := { app := λ j, F.preimage (i.hom ≫ limit.π (K ⋙ F) j), naturality' := λ Y Z f, F.map_injective (by { dsimp, simp, erw limit.w (K ⋙ F), }) }} : cone K) (by { fapply cones.ext, exact i, tidy, }) /-- `F` preserves the limit of `K` if it creates the limit and `K ⋙ F` has the limit. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_limit_of_creates_limit_and_has_limit (K : J ⥤ C) (F : C ⥤ D) [creates_limit K F] [has_limit (K ⋙ F)] : preserves_limit K F := { preserves := λ c t, is_limit.of_iso_limit (limit.is_limit _) ((lifted_limit_maps_to_original (limit.is_limit _)).symm ≪≫ ((cones.functoriality K F).map_iso ((lifted_limit_is_limit (limit.is_limit _)).unique_up_to_iso t))) } /-- `F` preserves the limit of shape `J` if it creates these limits and `D` has them. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_limit_of_shape_of_creates_limits_of_shape_and_has_limits_of_shape (F : C ⥤ D) [creates_limits_of_shape J F] [has_limits_of_shape J D] : preserves_limits_of_shape J F := { preserves_limit := λ K, category_theory.preserves_limit_of_creates_limit_and_has_limit K F } /-- `F` preserves limits if it creates limits and `D` has limits. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_limits_of_creates_limits_and_has_limits (F : C ⥤ D) [creates_limits F] [has_limits D] : preserves_limits F := { preserves_limits_of_shape := λ J 𝒥, by exactI category_theory.preserves_limit_of_shape_of_creates_limits_of_shape_and_has_limits_of_shape F } /-- If `F` reflects isomorphisms and we can lift any limit cocone to a limit cocone, then `F` creates colimits. In particular here we don't need to assume that F reflects colimits. -/ def creates_colimit_of_reflects_iso {K : J ⥤ C} {F : C ⥤ D} [reflects_isomorphisms F] (h : Π c t, lifts_to_colimit K F c t) : creates_colimit K F := { lifts := λ c t, (h c t).to_liftable_cocone, to_reflects_colimit := { reflects := λ (d : cocone K) (hd : is_colimit (F.map_cocone d)), begin let d' : cocone K := (h (F.map_cocone d) hd).to_liftable_cocone.lifted_cocone, let i : F.map_cocone d' ≅ F.map_cocone d := (h (F.map_cocone d) hd).to_liftable_cocone.valid_lift, let hd' : is_colimit d' := (h (F.map_cocone d) hd).makes_colimit, let f : d' ⟶ d := hd'.desc_cocone_morphism d, have : (cocones.functoriality K F).map f = i.hom := (hd.of_iso_colimit i.symm).uniq_cocone_morphism, haveI : is_iso ((cocones.functoriality K F).map f) := (by { rw this, apply_instance }), haveI := is_iso_of_reflects_iso f (cocones.functoriality K F), exact is_colimit.of_iso_colimit hd' (as_iso f), end } } /-- `F` preserves the colimit of `K` if it creates the colimit and `K ⋙ F` has the colimit. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_colimit_of_creates_colimit_and_has_colimit (K : J ⥤ C) (F : C ⥤ D) [creates_colimit K F] [has_colimit (K ⋙ F)] : preserves_colimit K F := { preserves := λ c t, is_colimit.of_iso_colimit (colimit.is_colimit _) ((lifted_colimit_maps_to_original (colimit.is_colimit _)).symm ≪≫ ((cocones.functoriality K F).map_iso ((lifted_colimit_is_colimit (colimit.is_colimit _)).unique_up_to_iso t))) } /-- `F` preserves the colimit of shape `J` if it creates these colimits and `D` has them. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_colimit_of_shape_of_creates_colimits_of_shape_and_has_colimits_of_shape (F : C ⥤ D) [creates_colimits_of_shape J F] [has_colimits_of_shape J D] : preserves_colimits_of_shape J F := { preserves_colimit := λ K, category_theory.preserves_colimit_of_creates_colimit_and_has_colimit K F } /-- `F` preserves limits if it creates limits and `D` has limits. -/ @[priority 100] -- see Note [lower instance priority] instance preserves_colimits_of_creates_colimits_and_has_colimits (F : C ⥤ D) [creates_colimits F] [has_colimits D] : preserves_colimits F := { preserves_colimits_of_shape := λ J 𝒥, by exactI category_theory.preserves_colimit_of_shape_of_creates_colimits_of_shape_and_has_colimits_of_shape F } -- For the inhabited linter later. /-- If F creates the limit of K, any cone lifts to a limit. -/ def lifts_to_limit_of_creates (K : J ⥤ C) (F : C ⥤ D) [creates_limit K F] (c : cone (K ⋙ F)) (t : is_limit c) : lifts_to_limit K F c t := { lifted_cone := lift_limit t, valid_lift := lifted_limit_maps_to_original t, makes_limit := lifted_limit_is_limit t } -- For the inhabited linter later. /-- If F creates the colimit of K, any cocone lifts to a colimit. -/ def lifts_to_colimit_of_creates (K : J ⥤ C) (F : C ⥤ D) [creates_colimit K F] (c : cocone (K ⋙ F)) (t : is_colimit c) : lifts_to_colimit K F c t := { lifted_cocone := lift_colimit t, valid_lift := lifted_colimit_maps_to_original t, makes_colimit := lifted_colimit_is_colimit t } /-- Any cone lifts through the identity functor. -/ def id_lifts_cone (c : cone (K ⋙ 𝟭 C)) : liftable_cone K (𝟭 C) c := { lifted_cone := { X := c.X, π := c.π ≫ K.right_unitor.hom }, valid_lift := cones.ext (iso.refl _) (by tidy) } /-- The identity functor creates all limits. -/ instance id_creates_limits : creates_limits (𝟭 C) := { creates_limits_of_shape := λ J 𝒥, by exactI { creates_limit := λ F, { lifts := λ c t, id_lifts_cone c } } } /-- Any cocone lifts through the identity functor. -/ def id_lifts_cocone (c : cocone (K ⋙ 𝟭 C)) : liftable_cocone K (𝟭 C) c := { lifted_cocone := { X := c.X, ι := K.right_unitor.inv ≫ c.ι }, valid_lift := cocones.ext (iso.refl _) (by tidy) } /-- The identity functor creates all colimits. -/ instance id_creates_colimits : creates_colimits (𝟭 C) := { creates_colimits_of_shape := λ J 𝒥, by exactI { creates_colimit := λ F, { lifts := λ c t, id_lifts_cocone c } } } /-- Satisfy the inhabited linter -/ instance inhabited_liftable_cone (c : cone (K ⋙ 𝟭 C)) : inhabited (liftable_cone K (𝟭 C) c) := ⟨id_lifts_cone c⟩ instance inhabited_liftable_cocone (c : cocone (K ⋙ 𝟭 C)) : inhabited (liftable_cocone K (𝟭 C) c) := ⟨id_lifts_cocone c⟩ /-- Satisfy the inhabited linter -/ instance inhabited_lifts_to_limit (K : J ⥤ C) (F : C ⥤ D) [creates_limit K F] (c : cone (K ⋙ F)) (t : is_limit c) : inhabited (lifts_to_limit _ _ _ t) := ⟨lifts_to_limit_of_creates K F c t⟩ instance inhabited_lifts_to_colimit (K : J ⥤ C) (F : C ⥤ D) [creates_colimit K F] (c : cocone (K ⋙ F)) (t : is_colimit c) : inhabited (lifts_to_colimit _ _ _ t) := ⟨lifts_to_colimit_of_creates K F c t⟩ section comp variables {E : Type u₃} [ℰ : category.{v} E] variables (F : C ⥤ D) (G : D ⥤ E) instance comp_creates_limit [i₁ : creates_limit K F] [i₂ : creates_limit (K ⋙ F) G] : creates_limit K (F ⋙ G) := { lifts := λ c t, { lifted_cone := lift_limit (lifted_limit_is_limit t), valid_lift := (cones.functoriality (K ⋙ F) G).map_iso (lifted_limit_maps_to_original (lifted_limit_is_limit t)) ≪≫ (lifted_limit_maps_to_original t), } } end comp end creates end category_theory
2475517410d354cc8b48dbe7c047145da9438cff
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/real/complete.lean
e56255bb60d74124779e208c77171bf10558c258
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
32,202
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The real numbers, constructed as equivalence classes of Cauchy sequences of rationals. This construction follows Bishop and Bridges (1985). At this point, we no longer proceed constructively: this file makes heavy use of decidability, excluded middle, and Hilbert choice. Two sets of definitions of Cauchy sequences, convergence, etc are available in the libray, one with rates and one without. The definitions here, with rates, are amenable to be used constructively if and when that development takes place. The second set of definitions available in /library/theories/analysis/metric_space.lean are the usual classical ones. Here, we show that ℝ is complete. The proofs of Cauchy completeness and the supremum property are independent of each other. -/ import data.real.basic data.real.order data.real.division data.rat data.nat data.pnat open rat local postfix ⁻¹ := pnat.inv open eq.ops pnat classical namespace rat_seq theorem rat_approx {s : seq} (H : regular s) : ∀ n : ℕ+, ∃ q : ℚ, ∃ N : ℕ+, ∀ m : ℕ+, m ≥ N → abs (s m - q) ≤ n⁻¹ := begin intro n, existsi (s (2 * n)), existsi 2 * n, intro m Hm, apply le.trans, apply H, rewrite -(pnat.add_halves n), apply add_le_add_right, apply inv_ge_of_le Hm end theorem rat_approx_seq {s : seq} (H : regular s) : ∀ n : ℕ+, ∃ q : ℚ, s_le (s_abs (sadd s (sneg (const q)))) (const n⁻¹) := begin intro m, rewrite ↑s_le, cases rat_approx H m with [q, Hq], cases Hq with [N, HN], existsi q, apply nonneg_of_bdd_within, repeat (apply reg_add_reg | apply reg_neg_reg | apply abs_reg_of_reg | apply const_reg | assumption), intro n, existsi N, intro p Hp, rewrite ↑[sadd, sneg, s_abs, const], apply le.trans, rotate 1, rewrite -sub_eq_add_neg, apply sub_le_sub_left, apply HN, apply pnat.le_trans, apply Hp, rewrite -*pnat.mul_assoc, apply pnat.mul_le_mul_left, rewrite [sub_self, -neg_zero], apply neg_le_neg, apply rat.le_of_lt, apply pnat.inv_pos end theorem r_rat_approx (s : reg_seq) : ∀ n : ℕ+, ∃ q : ℚ, r_le (r_abs (radd s (rneg (r_const q)))) (r_const n⁻¹) := rat_approx_seq (reg_seq.is_reg s) theorem const_bound {s : seq} (Hs : regular s) (n : ℕ+) : s_le (s_abs (sadd s (sneg (const (s n))))) (const n⁻¹) := begin rewrite ↑[s_le, nonneg, s_abs, sadd, sneg, const], intro m, rewrite -sub_eq_add_neg, apply iff.mp !le_add_iff_neg_le_sub_left, apply le.trans, apply Hs, apply add_le_add_right, rewrite -*pnat.mul_assoc, apply inv_ge_of_le, apply pnat.mul_le_mul_left end theorem abs_const (a : ℚ) : const (abs a) ≡ s_abs (const a) := by apply equiv.refl theorem r_abs_const (a : ℚ) : requiv (r_const (abs a) ) (r_abs (r_const a)) := abs_const a theorem equiv_abs_of_ge_zero {s : seq} (Hs : regular s) (Hz : s_le zero s) : s_abs s ≡ s := begin apply eq_of_bdd, apply abs_reg_of_reg Hs, apply Hs, intro j, rewrite ↑s_abs, let Hz' := s_nonneg_of_ge_zero Hs Hz, existsi 2 * j, intro n Hn, cases em (s n ≥ 0) with [Hpos, Hneg], rewrite [abs_of_nonneg Hpos, sub_self, abs_zero], apply rat.le_of_lt, apply pnat.inv_pos, let Hneg' := lt_of_not_ge Hneg, have Hsn : -s n - s n > 0, from add_pos (neg_pos_of_neg Hneg') (neg_pos_of_neg Hneg'), rewrite [abs_of_neg Hneg', abs_of_pos Hsn], apply le.trans, apply add_le_add, repeat (apply neg_le_neg; apply Hz'), rewrite neg_neg, apply le.trans, apply add_le_add, repeat (apply inv_ge_of_le; apply Hn), krewrite pnat.add_halves, end theorem equiv_neg_abs_of_le_zero {s : seq} (Hs : regular s) (Hz : s_le s zero) : s_abs s ≡ sneg s := begin apply eq_of_bdd, apply abs_reg_of_reg Hs, apply reg_neg_reg Hs, intro j, rewrite [↑s_abs, ↑s_le at Hz], have Hz' : nonneg (sneg s), begin apply nonneg_of_nonneg_equiv, rotate 3, apply Hz, rotate 2, apply s_zero_add, repeat (apply Hs | apply zero_is_reg | apply reg_neg_reg | apply reg_add_reg) end, existsi 2 * j, intro n Hn, cases em (s n ≥ 0) with [Hpos, Hneg], have Hsn : s n + s n ≥ 0, from add_nonneg Hpos Hpos, rewrite [abs_of_nonneg Hpos, ↑sneg, sub_neg_eq_add, abs_of_nonneg Hsn], rewrite [↑nonneg at Hz', ↑sneg at Hz'], apply le.trans, apply add_le_add, repeat apply (le_of_neg_le_neg !Hz'), apply le.trans, apply add_le_add, repeat (apply inv_ge_of_le; apply Hn), krewrite pnat.add_halves, let Hneg' := lt_of_not_ge Hneg, rewrite [abs_of_neg Hneg', ↑sneg, sub_neg_eq_add, neg_add_eq_sub, sub_self, abs_zero], apply rat.le_of_lt, apply pnat.inv_pos end theorem r_equiv_abs_of_ge_zero {s : reg_seq} (Hz : r_le r_zero s) : requiv (r_abs s) s := equiv_abs_of_ge_zero (reg_seq.is_reg s) Hz theorem r_equiv_neg_abs_of_le_zero {s : reg_seq} (Hz : r_le s r_zero) : requiv (r_abs s) (-s) := equiv_neg_abs_of_le_zero (reg_seq.is_reg s) Hz end rat_seq namespace real open [class] rat_seq private theorem rewrite_helper9 (a b c : ℝ) : b - c = (b - a) - (c - a) := by rewrite [-sub_add_eq_sub_sub_swap, sub_add_cancel] private theorem rewrite_helper10 (a b c d : ℝ) : c - d = (c - a) + (a - b) + (b - d) := by rewrite [*add_sub, *sub_add_cancel] noncomputable definition rep (x : ℝ) : rat_seq.reg_seq := some (quot.exists_rep x) definition re_abs (x : ℝ) : ℝ := quot.lift_on x (λ a, quot.mk (rat_seq.r_abs a)) (take a b Hab, quot.sound (rat_seq.r_abs_well_defined Hab)) theorem r_abs_nonneg {x : ℝ} : zero ≤ x → re_abs x = x := quot.induction_on x (λ a Ha, quot.sound (rat_seq.r_equiv_abs_of_ge_zero Ha)) theorem r_abs_nonpos {x : ℝ} : x ≤ zero → re_abs x = -x := quot.induction_on x (λ a Ha, quot.sound (rat_seq.r_equiv_neg_abs_of_le_zero Ha)) private theorem abs_const' (a : ℚ) : of_rat (abs a) = re_abs (of_rat a) := quot.sound (rat_seq.r_abs_const a) private theorem re_abs_is_abs : re_abs = abs := funext (begin intro x, apply eq.symm, cases em (zero ≤ x) with [Hor1, Hor2], rewrite [abs_of_nonneg Hor1, r_abs_nonneg Hor1], have Hor2' : x ≤ zero, from le_of_lt (lt_of_not_ge Hor2), rewrite [abs_of_neg (lt_of_not_ge Hor2), r_abs_nonpos Hor2'] end) theorem abs_const (a : ℚ) : of_rat (abs a) = abs (of_rat a) := by rewrite -re_abs_is_abs private theorem rat_approx' (x : ℝ) : ∀ n : ℕ+, ∃ q : ℚ, re_abs (x - of_rat q) ≤ of_rat n⁻¹ := quot.induction_on x (λ s n, rat_seq.r_rat_approx s n) theorem rat_approx (x : ℝ) : ∀ n : ℕ+, ∃ q : ℚ, abs (x - of_rat q) ≤ of_rat n⁻¹ := by rewrite -re_abs_is_abs; apply rat_approx' noncomputable definition approx (x : ℝ) (n : ℕ+) := some (rat_approx x n) theorem approx_spec (x : ℝ) (n : ℕ+) : abs (x - (of_rat (approx x n))) ≤ of_rat n⁻¹ := some_spec (rat_approx x n) theorem approx_spec' (x : ℝ) (n : ℕ+) : abs ((of_rat (approx x n)) - x) ≤ of_rat n⁻¹ := by rewrite abs_sub; apply approx_spec theorem ex_rat_pos_lower_bound_of_pos {x : ℝ} (H : x > 0) : ∃ q : ℚ, q > 0 ∧ of_rat q ≤ x := if Hgeo : x ≥ 1 then exists.intro 1 (and.intro zero_lt_one Hgeo) else have Hdp : 1 / x > 0, from one_div_pos_of_pos H, begin cases rat_approx (1 / x) 2 with q Hq, have Hqp : q > 0, begin apply lt_of_not_ge, intro Hq2, note Hx' := one_div_lt_one_div_of_lt H (lt_of_not_ge Hgeo), rewrite div_one at Hx', have Horqn : of_rat q ≤ 0, begin krewrite -of_rat_zero, apply of_rat_le_of_rat_of_le Hq2 end, have Hgt1 : 1 / x - of_rat q > 1, from calc 1 / x - of_rat q = 1 / x + -of_rat q : sub_eq_add_neg ... ≥ 1 / x : le_add_of_nonneg_right (neg_nonneg_of_nonpos Horqn) ... > 1 : Hx', have Hpos : 1 / x - of_rat q > 0, from gt.trans Hgt1 zero_lt_one, rewrite [abs_of_pos Hpos at Hq], apply not_le_of_gt Hgt1, apply le.trans, apply Hq, krewrite -of_rat_one, apply of_rat_le_of_rat_of_le, apply inv_le_one end, existsi 1 / (2⁻¹ + q), split, apply div_pos_of_pos_of_pos, exact zero_lt_one, apply add_pos, apply pnat.inv_pos, exact Hqp, note Hle2 := sub_le_of_abs_sub_le_right Hq, note Hle3 := le_add_of_sub_left_le Hle2, note Hle4 := one_div_le_of_one_div_le_of_pos H Hle3, rewrite [of_rat_divide, of_rat_add], exact Hle4 end theorem ex_rat_neg_upper_bound_of_neg {x : ℝ} (H : x < 0) : ∃ q : ℚ, q < 0 ∧ x ≤ of_rat q := have H' : -x > 0, from neg_pos_of_neg H, obtain q [Hq1 Hq2], from ex_rat_pos_lower_bound_of_pos H', exists.intro (-q) (and.intro (neg_neg_of_pos Hq1) (le_neg_of_le_neg Hq2)) notation `r_seq` := ℕ+ → ℝ noncomputable definition converges_to_with_rate (X : r_seq) (a : ℝ) (N : ℕ+ → ℕ+) := ∀ k : ℕ+, ∀ n : ℕ+, n ≥ N k → abs (X n - a) ≤ of_rat k⁻¹ noncomputable definition cauchy_with_rate (X : r_seq) (M : ℕ+ → ℕ+) := ∀ k : ℕ+, ∀ m n : ℕ+, m ≥ M k → n ≥ M k → abs (X m - X n) ≤ of_rat k⁻¹ theorem cauchy_with_rate_of_converges_to_with_rate {X : r_seq} {a : ℝ} {N : ℕ+ → ℕ+} (Hc : converges_to_with_rate X a N) : cauchy_with_rate X (λ k, N (2 * k)) := begin intro k m n Hm Hn, rewrite (rewrite_helper9 a), apply le.trans, apply abs_add_le_abs_add_abs, apply le.trans, apply add_le_add, apply Hc, apply Hm, krewrite abs_neg, apply Hc, apply Hn, xrewrite -of_rat_add, apply of_rat_le_of_rat_of_le, krewrite pnat.add_halves, end private definition Nb (M : ℕ+ → ℕ+) := λ k, pnat.max (3 * k) (M (2 * k)) private theorem Nb_spec_right (M : ℕ+ → ℕ+) (k : ℕ+) : M (2 * k) ≤ Nb M k := !pnat.max_right private theorem Nb_spec_left (M : ℕ+ → ℕ+) (k : ℕ+) : 3 * k ≤ Nb M k := !pnat.max_left section lim_seq parameter {X : r_seq} parameter {M : ℕ+ → ℕ+} hypothesis Hc : cauchy_with_rate X M include Hc noncomputable definition lim_seq : ℕ+ → ℚ := λ k, approx (X (Nb M k)) (2 * k) private theorem lim_seq_reg_helper {m n : ℕ+} (Hmn : M (2 * n) ≤M (2 * m)) : abs (of_rat (lim_seq m) - X (Nb M m)) + abs (X (Nb M m) - X (Nb M n)) + abs (X (Nb M n) - of_rat (lim_seq n)) ≤ of_rat (m⁻¹ + n⁻¹) := begin apply le.trans, apply add_le_add_three, apply approx_spec', rotate 1, apply approx_spec, rotate 1, apply Hc, rotate 1, apply Nb_spec_right, rotate 1, apply pnat.le_trans, apply Hmn, apply Nb_spec_right, krewrite [-+of_rat_add], change of_rat ((2 * m)⁻¹ + (2 * n)⁻¹ + (2 * n)⁻¹) ≤ of_rat (m⁻¹ + n⁻¹), rewrite [add.assoc], krewrite pnat.add_halves, apply of_rat_le_of_rat_of_le, apply add_le_add_right, apply inv_ge_of_le, apply pnat.mul_le_mul_left end theorem lim_seq_reg : rat_seq.regular lim_seq := begin rewrite ↑rat_seq.regular, intro m n, apply le_of_of_rat_le_of_rat, rewrite [abs_const, of_rat_sub, (rewrite_helper10 (X (Nb M m)) (X (Nb M n)))], apply le.trans, apply abs_add_three, cases em (M (2 * m) ≥ M (2 * n)) with [Hor1, Hor2], apply lim_seq_reg_helper Hor1, let Hor2' := pnat.le_of_lt (pnat.lt_of_not_le Hor2), krewrite [abs_sub (X (Nb M n)), abs_sub (X (Nb M m)), abs_sub, rat.add_comm, add_comm_three], apply lim_seq_reg_helper Hor2' end theorem lim_seq_spec (k : ℕ+) : rat_seq.s_le (rat_seq.s_abs (rat_seq.sadd lim_seq (rat_seq.sneg (rat_seq.const (lim_seq k))))) (rat_seq.const k⁻¹) := by apply rat_seq.const_bound; apply lim_seq_reg private noncomputable definition r_lim_seq : rat_seq.reg_seq := rat_seq.reg_seq.mk lim_seq lim_seq_reg private theorem r_lim_seq_spec (k : ℕ+) : rat_seq.r_le (rat_seq.r_abs ((rat_seq.radd r_lim_seq (rat_seq.rneg (rat_seq.r_const ((rat_seq.reg_seq.sq r_lim_seq) k)))))) (rat_seq.r_const k⁻¹) := lim_seq_spec k noncomputable definition lim : ℝ := quot.mk r_lim_seq theorem re_lim_spec (k : ℕ+) : re_abs (lim - (of_rat (lim_seq k))) ≤ of_rat k⁻¹ := r_lim_seq_spec k theorem lim_spec' (k : ℕ+) : abs (lim - (of_rat (lim_seq k))) ≤ of_rat k⁻¹ := by rewrite -re_abs_is_abs; apply re_lim_spec theorem lim_spec (k : ℕ+) : abs ((of_rat (lim_seq k)) - lim) ≤ of_rat k⁻¹ := by rewrite abs_sub; apply lim_spec' theorem converges_to_with_rate_of_cauchy_with_rate : converges_to_with_rate X lim (Nb M) := begin intro k n Hn, rewrite (rewrite_helper10 (X (Nb M n)) (of_rat (lim_seq n))), apply le.trans, apply abs_add_three, apply le.trans, apply add_le_add_three, apply Hc, apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply Nb_spec_right, have HMk : M (2 * k) ≤ Nb M n, begin apply pnat.le_trans, apply Nb_spec_right, apply pnat.le_trans, apply Hn, apply pnat.le_trans, apply pnat.mul_le_mul_left 3, apply Nb_spec_left end, apply HMk, rewrite ↑lim_seq, apply approx_spec, apply lim_spec, krewrite [-+of_rat_add], change of_rat ((2 * k)⁻¹ + (2 * n)⁻¹ + n⁻¹) ≤ of_rat k⁻¹, apply of_rat_le_of_rat_of_le, apply le.trans, apply add_le_add_three, apply rat.le_refl, apply inv_ge_of_le, apply pnat_mul_le_mul_left', apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply Nb_spec_left, apply inv_ge_of_le, apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply Nb_spec_left, rewrite -*pnat.mul_assoc, krewrite pnat.p_add_fractions, end end lim_seq ------------------------------------------- -- int embedding theorems -- archimedean properties, integer floor and ceiling section ints open int theorem archimedean_upper (x : ℝ) : ∃ z : ℤ, x ≤ of_int z := begin apply quot.induction_on x, intro s, cases rat_seq.bdd_of_regular (rat_seq.reg_seq.is_reg s) with [b, Hb], existsi ubound b, have H : rat_seq.s_le (rat_seq.reg_seq.sq s) (rat_seq.const (rat.of_nat (ubound b))), begin apply rat_seq.s_le_of_le_pointwise (rat_seq.reg_seq.is_reg s), apply rat_seq.const_reg, intro n, apply rat.le_trans, apply Hb, apply ubound_ge end, apply H end theorem archimedean_upper_strict (x : ℝ) : ∃ z : ℤ, x < of_int z := begin cases archimedean_upper x with [z, Hz], existsi z + 1, apply lt_of_le_of_lt, apply Hz, apply of_int_lt_of_int_of_lt, apply lt_add_of_pos_right, apply dec_trivial end theorem archimedean_lower (x : ℝ) : ∃ z : ℤ, x ≥ of_int z := begin cases archimedean_upper (-x) with [z, Hz], existsi -z, rewrite [of_int_neg], apply iff.mp !neg_le_iff_neg_le Hz end theorem archimedean_lower_strict (x : ℝ) : ∃ z : ℤ, x > of_int z := begin cases archimedean_upper_strict (-x) with [z, Hz], existsi -z, rewrite [of_int_neg], apply iff.mp !neg_lt_iff_neg_lt Hz end private definition ex_floor (x : ℝ) := (@exists_greatest_of_bdd (λ z, x ≥ of_int z) _ (begin existsi some (archimedean_upper_strict x), let Har := some_spec (archimedean_upper_strict x), intros z Hz, apply not_le_of_gt, apply lt_of_lt_of_le, apply Har, have H : of_int (some (archimedean_upper_strict x)) ≤ of_int z, begin apply of_int_le_of_int_of_le, apply Hz end, exact H end) (by existsi some (archimedean_lower x); apply some_spec (archimedean_lower x))) noncomputable definition floor (x : ℝ) : ℤ := some (ex_floor x) noncomputable definition ceil (x : ℝ) : ℤ := - floor (-x) theorem floor_le (x : ℝ) : floor x ≤ x := and.left (some_spec (ex_floor x)) theorem lt_of_floor_lt {x : ℝ} {z : ℤ} (Hz : floor x < z) : x < z := begin apply lt_of_not_ge, cases some_spec (ex_floor x), apply a_1 _ Hz end theorem le_ceil (x : ℝ) : x ≤ ceil x := begin rewrite [↑ceil, of_int_neg], apply iff.mp !le_neg_iff_le_neg, apply floor_le end theorem lt_of_lt_ceil {x : ℝ} {z : ℤ} (Hz : z < ceil x) : z < x := begin rewrite ↑ceil at Hz, note Hz' := lt_of_floor_lt (iff.mp !lt_neg_iff_lt_neg Hz), rewrite [of_int_neg at Hz'], apply lt_of_neg_lt_neg Hz' end theorem floor_succ (x : ℝ) : floor (x + 1) = floor x + 1 := begin apply by_contradiction, intro H, cases lt_or_gt_of_ne H with [Hgt, Hlt], note Hl := lt_of_floor_lt Hgt, rewrite [of_int_add at Hl], apply not_le_of_gt (lt_of_add_lt_add_right Hl) !floor_le, note Hl := lt_of_floor_lt (iff.mp !add_lt_iff_lt_sub_right Hlt), rewrite [of_int_sub at Hl], apply not_le_of_gt (iff.mpr !add_lt_iff_lt_sub_right Hl) !floor_le end theorem floor_sub_one_lt_floor (x : ℝ) : floor (x - 1) < floor x := begin apply @lt_of_add_lt_add_right ℤ _ _ 1, rewrite [-floor_succ (x - 1), sub_add_cancel], apply lt_add_of_pos_right dec_trivial end theorem ceil_lt_ceil_succ (x : ℝ) : ceil x < ceil (x + 1) := begin rewrite [↑ceil, neg_add], apply neg_lt_neg, apply floor_sub_one_lt_floor end open nat theorem archimedean_small {ε : ℝ} (H : ε > 0) : ∃ (n : ℕ), 1 / succ n < ε := let n := int.nat_abs (ceil (2 / ε)) in have int.of_nat n ≥ ceil (2 / ε), by rewrite of_nat_nat_abs; apply le_abs_self, have int.of_nat (succ n) ≥ ceil (2 / ε), begin apply le.trans, exact this, apply int.of_nat_le_of_nat_of_le, apply le_succ end, have H₁ : int.succ n ≥ ceil (2 / ε), from of_int_le_of_int_of_le this, have H₂ : succ n ≥ 2 / ε, from !le.trans !le_ceil H₁, have H₃ : 2 / ε > 0, from div_pos_of_pos_of_pos two_pos H, have 1 / succ n < ε, from calc 1 / succ n ≤ 1 / (2 / ε) : one_div_le_one_div_of_le H₃ H₂ ... = ε / 2 : one_div_div ... < ε : div_two_lt_of_pos H, exists.intro n this end ints -------------------------------------------------- -- supremum property -- this development roughly follows the proof of completeness done in Isabelle. -- It does not depend on the previous proof of Cauchy completeness. Much of the same -- machinery can be used to show that Cauchy completeness implies the supremum property. section supremum open prod nat local postfix `~` := nat_of_pnat -- The top part of this section could be refactored. What is the appropriate place to define -- bounds, supremum, etc? In algebra/ordered_field? They potentially apply to more than just ℝ. parameter X : ℝ → Prop definition ub (x : ℝ) := ∀ y : ℝ, X y → y ≤ x definition is_sup (x : ℝ) := ub x ∧ ∀ y : ℝ, ub y → x ≤ y definition lb (x : ℝ) := ∀ y : ℝ, X y → x ≤ y definition is_inf (x : ℝ) := lb x ∧ ∀ y : ℝ, lb y → y ≤ x parameter elt : ℝ hypothesis inh : X elt parameter bound : ℝ hypothesis bdd : ub bound include inh bdd private definition avg (a b : ℚ) := a / 2 + b / 2 private noncomputable definition bisect (ab : ℚ × ℚ) := if ub (avg (pr1 ab) (pr2 ab)) then (pr1 ab, (avg (pr1 ab) (pr2 ab))) else (avg (pr1 ab) (pr2 ab), pr2 ab) private noncomputable definition under : ℚ := rat.of_int (floor (elt - 1)) private theorem under_spec1 : of_rat under < elt := have H : of_rat under < of_int (floor elt), begin apply of_int_lt_of_int_of_lt, apply floor_sub_one_lt_floor end, lt_of_lt_of_le H !floor_le private theorem under_spec : ¬ ub under := begin rewrite ↑ub, apply not_forall_of_exists_not, existsi elt, apply iff.mpr !not_implies_iff_and_not, apply and.intro, apply inh, apply not_le_of_gt under_spec1 end private noncomputable definition over : ℚ := rat.of_int (ceil (bound + 1)) -- b private theorem over_spec1 : bound < of_rat over := have H : of_int (ceil bound) < of_rat over, begin apply of_int_lt_of_int_of_lt, apply ceil_lt_ceil_succ end, lt_of_le_of_lt !le_ceil H private theorem over_spec : ub over := begin rewrite ↑ub, intro y Hy, apply le_of_lt, apply lt_of_le_of_lt, apply bdd, apply Hy, apply over_spec1 end private noncomputable definition under_seq := λ n : ℕ, pr1 (iterate bisect n (under, over)) -- A private noncomputable definition over_seq := λ n : ℕ, pr2 (iterate bisect n (under, over)) -- B private noncomputable definition avg_seq := λ n : ℕ, avg (over_seq n) (under_seq n) -- C private theorem avg_symm (n : ℕ) : avg_seq n = avg (under_seq n) (over_seq n) := by rewrite [↑avg_seq, ↑avg, add.comm] private theorem over_0 : over_seq 0 = over := rfl private theorem under_0 : under_seq 0 = under := rfl private theorem succ_helper (n : ℕ) : avg (pr1 (iterate bisect n (under, over))) (pr2 (iterate bisect n (under, over))) = avg_seq n := by rewrite avg_symm private theorem under_succ (n : ℕ) : under_seq (succ n) = (if ub (avg_seq n) then under_seq n else avg_seq n) := begin cases em (ub (avg_seq n)) with [Hub, Hub], rewrite [if_pos Hub], have H : pr1 (bisect (iterate bisect n (under, over))) = under_seq n, by rewrite [↑under_seq, ↑bisect at {2}, -succ_helper at Hub, if_pos Hub], apply H, rewrite [if_neg Hub], have H : pr1 (bisect (iterate bisect n (under, over))) = avg_seq n, by rewrite [↑bisect at {2}, -succ_helper at Hub, if_neg Hub, avg_symm], apply H end private theorem over_succ (n : ℕ) : over_seq (succ n) = (if ub (avg_seq n) then avg_seq n else over_seq n) := begin cases em (ub (avg_seq n)) with [Hub, Hub], rewrite [if_pos Hub], have H : pr2 (bisect (iterate bisect n (under, over))) = avg_seq n, by rewrite [↑bisect at {2}, -succ_helper at Hub, if_pos Hub, avg_symm], apply H, rewrite [if_neg Hub], have H : pr2 (bisect (iterate bisect n (under, over))) = over_seq n, by rewrite [↑over_seq, ↑bisect at {2}, -succ_helper at Hub, if_neg Hub], apply H end private theorem nat.zero_eq_0 : (zero : ℕ) = 0 := rfl private theorem width (n : ℕ) : over_seq n - under_seq n = (over - under) / ((2^n) : ℚ) := nat.induction_on n (by xrewrite [nat.zero_eq_0, over_0, under_0, pow_zero, div_one]) (begin intro a Ha, rewrite [over_succ, under_succ], let Hou := calc (over_seq a) / 2 - (under_seq a) / 2 = ((over - under) / 2^a) / 2 : by rewrite [div_sub_div_same, Ha] ... = (over - under) / ((2^a) * 2) : by rewrite div_div_eq_div_mul ... = (over - under) / 2^(a + 1) : by rewrite pow_add, cases em (ub (avg_seq a)), rewrite [*if_pos a_1, -add_one, -Hou, ↑avg_seq, ↑avg, sub_eq_add_neg, add.assoc, -sub_eq_add_neg, div_two_sub_self], rewrite [*if_neg a_1, -add_one, -Hou, ↑avg_seq, ↑avg, sub_add_eq_sub_sub, sub_self_div_two] end) private theorem width_narrows : ∃ n : ℕ, over_seq n - under_seq n ≤ 1 := begin cases binary_bound (over - under) with [a, Ha], existsi a, rewrite (width a), apply div_le_of_le_mul, apply pow_pos dec_trivial, rewrite rat.mul_one, apply Ha end private noncomputable definition over' := over_seq (some width_narrows) private noncomputable definition under' := under_seq (some width_narrows) private noncomputable definition over_seq' := λ n, over_seq (n + some width_narrows) private noncomputable definition under_seq' := λ n, under_seq (n + some width_narrows) private theorem over_seq'0 : over_seq' 0 = over' := by rewrite [↑over_seq', nat.zero_add] private theorem under_seq'0 : under_seq' 0 = under' := by rewrite [↑under_seq', nat.zero_add] private theorem under_over' : over' - under' ≤ 1 := some_spec width_narrows private theorem width' (n : ℕ) : over_seq' n - under_seq' n ≤ 1 / 2^n := nat.induction_on n (begin xrewrite [nat.zero_eq_0, over_seq'0, under_seq'0, pow_zero, div_one], apply under_over' end) (begin intros a Ha, rewrite [↑over_seq' at *, ↑under_seq' at *, *succ_add at *, width at *, -add_one, -(add_one a), pow_add, pow_add _ a 1, *pow_one], apply div_mul_le_div_mul_of_div_le_div_pos' Ha dec_trivial end) private theorem PA (n : ℕ) : ¬ ub (under_seq n) := nat.induction_on n (by rewrite under_0; apply under_spec) (begin intro a Ha, rewrite under_succ, cases em (ub (avg_seq a)), rewrite (if_pos a_1), assumption, rewrite (if_neg a_1), assumption end) private theorem PB (n : ℕ) : ub (over_seq n) := nat.induction_on n (by rewrite over_0; apply over_spec) (begin intro a Ha, rewrite over_succ, cases em (ub (avg_seq a)), rewrite (if_pos a_1), assumption, rewrite (if_neg a_1), assumption end) private theorem under_lt_over : under < over := begin cases exists_not_of_not_forall under_spec with [x, Hx], cases and_not_of_not_implies Hx with [HXx, Hxu], apply lt_of_of_rat_lt_of_rat, apply lt_of_lt_of_le, apply lt_of_not_ge Hxu, apply over_spec _ HXx end private theorem under_seq_lt_over_seq : ∀ m n : ℕ, under_seq m < over_seq n := begin intros, cases exists_not_of_not_forall (PA m) with [x, Hx], cases iff.mp !not_implies_iff_and_not Hx with [HXx, Hxu], apply lt_of_of_rat_lt_of_rat, apply lt_of_lt_of_le, apply lt_of_not_ge Hxu, apply PB, apply HXx end private theorem under_seq_lt_over_seq_single : ∀ n : ℕ, under_seq n < over_seq n := by intros; apply under_seq_lt_over_seq private theorem under_seq'_lt_over_seq' : ∀ m n : ℕ, under_seq' m < over_seq' n := by intros; apply under_seq_lt_over_seq private theorem under_seq'_lt_over_seq'_single : ∀ n : ℕ, under_seq' n < over_seq' n := by intros; apply under_seq_lt_over_seq private theorem under_seq_mono_helper (i k : ℕ) : under_seq i ≤ under_seq (i + k) := (nat.induction_on k (by rewrite nat.add_zero; apply rat.le_refl) (begin intros a Ha, rewrite [add_succ, under_succ], cases em (ub (avg_seq (i + a))) with [Havg, Havg], rewrite (if_pos Havg), apply Ha, rewrite [if_neg Havg, ↑avg_seq, ↑avg], apply rat.le_trans, apply Ha, rewrite -add_halves at {1}, apply add_le_add_right, apply div_le_div_of_le_of_pos, apply rat.le_of_lt, apply under_seq_lt_over_seq, apply dec_trivial end)) private theorem under_seq_mono (i j : ℕ) (H : i ≤ j) : under_seq i ≤ under_seq j := begin cases le.elim H with [k, Hk'], rewrite -Hk', apply under_seq_mono_helper end private theorem over_seq_mono_helper (i k : ℕ) : over_seq (i + k) ≤ over_seq i := nat.induction_on k (by rewrite nat.add_zero; apply rat.le_refl) (begin intros a Ha, rewrite [add_succ, over_succ], cases em (ub (avg_seq (i + a))) with [Havg, Havg], rewrite [if_pos Havg, ↑avg_seq, ↑avg], apply rat.le_trans, rotate 1, apply Ha, rotate 1, apply add_le_of_le_sub_left, rewrite sub_self_div_two, apply div_le_div_of_le_of_pos, apply rat.le_of_lt, apply under_seq_lt_over_seq, apply dec_trivial, rewrite [if_neg Havg], apply Ha end) private theorem over_seq_mono (i j : ℕ) (H : i ≤ j) : over_seq j ≤ over_seq i := begin cases le.elim H with [k, Hk'], rewrite -Hk', apply over_seq_mono_helper end private theorem rat_power_two_inv_ge (k : ℕ+) : 1 / 2^k~ ≤ k⁻¹ := one_div_le_one_div_of_le !rat_of_pnat_is_pos !rat_power_two_le open rat_seq private theorem regular_lemma_helper {s : seq} {m n : ℕ+} (Hm : m ≤ n) (H : ∀ n i : ℕ+, i ≥ n → under_seq' n~ ≤ s i ∧ s i ≤ over_seq' n~) : abs (s m - s n) ≤ m⁻¹ + n⁻¹ := begin cases H m n Hm with [T1under, T1over], cases H m m (!pnat.le_refl) with [T2under, T2over], apply rat.le_trans, apply dist_bdd_within_interval, apply under_seq'_lt_over_seq'_single, rotate 1, repeat assumption, apply rat.le_trans, apply width', apply rat.le_trans, apply rat_power_two_inv_ge, apply le_add_of_nonneg_right, apply rat.le_of_lt (!pnat.inv_pos) end private theorem regular_lemma (s : seq) (H : ∀ n i : ℕ+, i ≥ n → under_seq' n~ ≤ s i ∧ s i ≤ over_seq' n~) : regular s := begin rewrite ↑regular, intros, cases em (m ≤ n) with [Hm, Hn], apply regular_lemma_helper Hm H, note T := regular_lemma_helper (pnat.le_of_lt (pnat.lt_of_not_le Hn)) H, rewrite [abs_sub at T, {n⁻¹ + _}add.comm at T], exact T end private noncomputable definition p_under_seq : seq := λ n : ℕ+, under_seq' n~ private noncomputable definition p_over_seq : seq := λ n : ℕ+, over_seq' n~ private theorem under_seq_regular : regular p_under_seq := begin apply regular_lemma, intros n i Hni, apply and.intro, apply under_seq_mono, apply add_le_add_right, apply Hni, apply rat.le_of_lt, apply under_seq_lt_over_seq end private theorem over_seq_regular : regular p_over_seq := begin apply regular_lemma, intros n i Hni, apply and.intro, apply rat.le_of_lt, apply under_seq_lt_over_seq, apply over_seq_mono, apply add_le_add_right, apply Hni end private noncomputable definition sup_over : ℝ := quot.mk (reg_seq.mk p_over_seq over_seq_regular) private noncomputable definition sup_under : ℝ := quot.mk (reg_seq.mk p_under_seq under_seq_regular) private theorem over_bound : ub sup_over := begin rewrite ↑ub, intros y Hy, apply le_of_le_reprs, intro n, apply PB, apply Hy end private theorem under_lowest_bound : ∀ y : ℝ, ub y → sup_under ≤ y := begin intros y Hy, apply le_of_reprs_le, intro n, cases exists_not_of_not_forall (PA _) with [x, Hx], cases and_not_of_not_implies Hx with [HXx, Hxn], apply le.trans, apply le_of_lt, apply lt_of_not_ge Hxn, apply Hy, apply HXx end private theorem under_over_equiv : p_under_seq ≡ p_over_seq := begin intros, apply rat.le_trans, have H : p_under_seq n < p_over_seq n, from !under_seq_lt_over_seq, rewrite [abs_of_neg (iff.mpr !sub_neg_iff_lt H), neg_sub], apply width', apply rat.le_trans, apply rat_power_two_inv_ge, apply le_add_of_nonneg_left, apply rat.le_of_lt !pnat.inv_pos end private theorem under_over_eq : sup_under = sup_over := quot.sound under_over_equiv theorem exists_is_sup_of_inh_of_bdd : ∃ x : ℝ, is_sup x := exists.intro sup_over (and.intro over_bound (under_over_eq ▸ under_lowest_bound)) end supremum definition bounding_set (X : ℝ → Prop) (x : ℝ) : Prop := ∀ y : ℝ, X y → x ≤ y theorem exists_is_inf_of_inh_of_bdd (X : ℝ → Prop) (elt : ℝ) (inh : X elt) (bound : ℝ) (bdd : lb X bound) : ∃ x : ℝ, is_inf X x := begin have Hinh : bounding_set X bound, begin intros y Hy, apply bdd, apply Hy end, have Hub : ub (bounding_set X) elt, begin intros y Hy, apply Hy, apply inh end, cases exists_is_sup_of_inh_of_bdd _ _ Hinh _ Hub with [supr, Hsupr], existsi supr, cases Hsupr with [Hubs1, Hubs2], apply and.intro, intros, apply Hubs2, intros z Hz, apply Hz, apply a, intros y Hlby, apply Hubs1, intros z Hz, apply Hlby, apply Hz end end real
ac6884f2bfdaa3b261dea0815df6c7a0b650911b
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/measure_theory/l1_space.lean
11d0cb2251ab33c7836c45013c92581709021ded
[ "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
28,178
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import measure_theory.ae_eq_fun /-! # Integrable functions and `L¹` space In the first part of this file, the predicate `integrable` is defined and basic properties of integrable functions are proved. In the second part, the space `L¹` of equivalence classes of integrable functions under the relation of being almost everywhere equal is defined as a subspace of the space `L⁰`. See the file `src/measure_theory/ae_eq_fun.lean` for information on `L⁰` space. ## Notation * `α →₁ β` is the type of `L¹` space, where `α` is a `measure_space` and `β` is a `normed_group` with a `second_countable_topology`. `f : α →ₘ β` is a "function" in `L¹`. In comments, `[f]` is also used to denote an `L¹` function. `₁` can be typed as `\1`. ## Main definitions * Let `f : α → β` be a function, where `α` is a `measure_space` and `β` a `normed_group`. Then `f` is called `integrable` if `(∫⁻ a, nnnorm (f a)) < ⊤` holds. * The space `L¹` is defined as a subspace of `L⁰` : An `ae_eq_fun` `[f] : α →ₘ β` is in the space `L¹` if `edist [f] 0 < ⊤`, which means `(∫⁻ a, edist (f a) 0) < ⊤` if we expand the definition of `edist` in `L⁰`. ## Main statements `L¹`, as a subspace, inherits most of the structures of `L⁰`. ## Implementation notes Maybe `integrable f` should be mean `(∫⁻ a, edist (f a) 0) < ⊤`, so that `integrable` and `ae_eq_fun.integrable` are more aligned. But in the end one can use the lemma `lintegral_nnnorm_eq_lintegral_edist : (∫⁻ a, nnnorm (f a)) = (∫⁻ a, edist (f a) 0)` to switch the two forms. ## Tags integrable, function space, l1 -/ noncomputable theory open_locale classical topological_space set_option class.instance_max_depth 100 namespace measure_theory open set filter topological_space ennreal emetric universes u v w variables {α : Type u} [measure_space α] variables {β : Type v} [normed_group β] {γ : Type w} [normed_group γ] /-- A function is `integrable` if the integral of its pointwise norm is less than infinity. -/ def integrable (f : α → β) : Prop := (∫⁻ a, nnnorm (f a)) < ⊤ lemma integrable_iff_norm (f : α → β) : integrable f ↔ (∫⁻ a, ennreal.of_real ∥f a∥) < ⊤ := have eq : (λa, ennreal.of_real ∥f a∥) = (λa, (nnnorm(f a) : ennreal)), by { funext, rw of_real_norm_eq_coe_nnnorm }, iff.intro (by { rw eq, exact λh, h }) $ by { rw eq, exact λh, h } lemma integrable_iff_edist (f : α → β) : integrable f ↔ (∫⁻ a, edist (f a) 0) < ⊤ := have eq : (λa, edist (f a) 0) = (λa, (nnnorm(f a) : ennreal)), by { funext, rw edist_eq_coe_nnnorm }, iff.intro (by { rw eq, exact λh, h }) $ by { rw eq, exact λh, h } lemma integrable_iff_of_real {f : α → ℝ} (h : ∀ₘ a, 0 ≤ f a) : integrable f ↔ (∫⁻ a, ennreal.of_real (f a)) < ⊤ := have lintegral_eq : (∫⁻ a, ennreal.of_real ∥f a∥) = (∫⁻ a, ennreal.of_real (f a)) := begin apply lintegral_congr_ae, filter_upwards [h], simp only [mem_set_of_eq], assume a h, rw [real.norm_eq_abs, abs_of_nonneg], exact h end, by rw [integrable_iff_norm, lintegral_eq] lemma integrable_of_ae_eq {f g : α → β} (hf : integrable f) (h : ∀ₘ a, f a = g a) : integrable g := begin simp only [integrable] at *, have : (∫⁻ (a : α), ↑(nnnorm (f a))) = (∫⁻ (a : α), ↑(nnnorm (g a))), { apply lintegral_congr_ae, filter_upwards [h], assume a, simp only [mem_set_of_eq], assume h, rw h }, rwa ← this end lemma integrable_congr_ae {f g : α → β} (h : ∀ₘ a, f a = g a) : integrable f ↔ integrable g := iff.intro (λhf, integrable_of_ae_eq hf h) (λhg, integrable_of_ae_eq hg (all_ae_eq_symm h)) lemma integrable_of_le_ae {f : α → β} {g : α → γ} (h : ∀ₘ a, ∥f a∥ ≤ ∥g a∥) (hg : integrable g) : integrable f := begin simp only [integrable_iff_norm] at *, calc (∫⁻ a, ennreal.of_real ∥f a∥) ≤ (∫⁻ (a : α), ennreal.of_real ∥g a∥) : lintegral_le_lintegral_ae (by { filter_upwards [h], assume a h, exact of_real_le_of_real h }) ... < ⊤ : hg end lemma integrable_of_le {f : α → β} {g : α → γ} (h : ∀a, ∥f a∥ ≤ ∥g a∥) (hg : integrable g) : integrable f := integrable_of_le_ae (univ_mem_sets' h) hg lemma lintegral_nnnorm_eq_lintegral_edist (f : α → β) : (∫⁻ a, nnnorm (f a)) = ∫⁻ a, edist (f a) 0 := by { congr, funext, rw edist_eq_coe_nnnorm } lemma lintegral_norm_eq_lintegral_edist (f : α → β) : (∫⁻ a, ennreal.of_real ∥f a∥) = ∫⁻ a, edist (f a) 0 := by { congr, funext, rw [of_real_norm_eq_coe_nnnorm, edist_eq_coe_nnnorm] } lemma lintegral_edist_triangle [second_countable_topology β] {f g h : α → β} (hf : measurable f) (hg : measurable g) (hh : measurable h) : (∫⁻ a, edist (f a) (g a)) ≤ (∫⁻ a, edist (f a) (h a)) + ∫⁻ a, edist (g a) (h a) := begin rw ← lintegral_add (measurable.edist hf hh) (measurable.edist hg hh), apply lintegral_le_lintegral, assume a, have := edist_triangle (f a) (h a) (g a), convert this, rw edist_comm (h a) (g a), end lemma lintegral_edist_lt_top [second_countable_topology β] {f g : α → β} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : (∫⁻ a, edist (f a) (g a)) < ⊤ := lt_of_le_of_lt (lintegral_edist_triangle hfm hgm (measurable_const : measurable (λa, (0 : β)))) (ennreal.add_lt_top.2 $ by { split; rw ← integrable_iff_edist; assumption }) lemma lintegral_nnnorm_zero : (∫⁻ a : α, nnnorm (0 : β)) = 0 := by simp variables (α β) @[simp] lemma integrable_zero : integrable (λa:α, (0:β)) := by { have := coe_lt_top, simpa [integrable] } variables {α β} lemma lintegral_nnnorm_add {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : (∫⁻ a, nnnorm (f a) + nnnorm (g a)) = (∫⁻ a, nnnorm (f a)) + ∫⁻ a, nnnorm (g a) := lintegral_add (measurable.coe_nnnorm hf) (measurable.coe_nnnorm hg) lemma integrable.add {f g : α → β} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g): integrable (λa, f a + g a) := calc (∫⁻ (a : α), ↑(nnnorm ((f + g) a))) ≤ ∫⁻ (a : α), ↑(nnnorm (f a)) + ↑(nnnorm (g a)) : lintegral_le_lintegral _ _ (assume a, by { simp only [coe_add.symm, coe_le_coe], exact nnnorm_add_le _ _ }) ... = _ : lintegral_nnnorm_add hfm hgm ... < ⊤ : add_lt_top.2 ⟨hfi, hgi⟩ lemma integrable_finset_sum {ι} [second_countable_topology β] (s : finset ι) {f : ι → α → β} (hfm : ∀ i, measurable (f i)) (hfi : ∀ i, integrable (f i)) : integrable (λ a, s.sum (λ i, f i a)) := begin refine finset.induction_on s _ _, { simp only [finset.sum_empty, integrable_zero] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], refine (hfi _).add (hfm _) (measurable_finset_sum s hfm) ih } end lemma lintegral_nnnorm_neg {f : α → β} : (∫⁻ (a : α), ↑(nnnorm ((-f) a))) = ∫⁻ (a : α), ↑(nnnorm ((f) a)) := lintegral_congr_ae $ by { filter_upwards [], simp } lemma integrable.neg {f : α → β} : integrable f → integrable (λa, -f a) := assume hfi, calc _ = _ : lintegral_nnnorm_neg ... < ⊤ : hfi @[simp] lemma integrable_neg_iff (f : α → β) : integrable (λa, -f a) ↔ integrable f := begin split, { assume h, simpa only [_root_.neg_neg] using h.neg }, exact integrable.neg end lemma integrable.sub {f g : α → β} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : integrable (λa, f a - g a) := by { simp only [sub_eq_add_neg], exact hfi.add hfm (measurable.neg hgm) (integrable.neg hgi) } lemma integrable.norm {f : α → β} (hfi : integrable f) : integrable (λa, ∥f a∥) := have eq : (λa, (nnnorm ∥f a∥ : ennreal)) = λa, (nnnorm (f a) : ennreal), by { funext, rw nnnorm_norm }, by { rwa [integrable, eq] } lemma integrable_norm_iff (f : α → β) : integrable (λa, ∥f a∥) ↔ integrable f := have eq : (λa, (nnnorm ∥f a∥ : ennreal)) = λa, (nnnorm (f a) : ennreal), by { funext, rw nnnorm_norm }, by { rw [integrable, integrable, eq] } lemma integrable_of_integrable_bound {f : α → β} {bound : α → ℝ} (h : integrable bound) (h_bound : ∀ₘ a, ∥f a∥ ≤ bound a) : integrable f := have h₁ : ∀ₘ a, (nnnorm (f a) : ennreal) ≤ ennreal.of_real (bound a), begin filter_upwards [h_bound], simp only [mem_set_of_eq], assume a h, calc (nnnorm (f a) : ennreal) = ennreal.of_real (∥f a∥) : by rw of_real_norm_eq_coe_nnnorm ... ≤ ennreal.of_real (bound a) : ennreal.of_real_le_of_real h end, calc (∫⁻ a, nnnorm (f a)) ≤ (∫⁻ a, ennreal.of_real (bound a)) : by { apply lintegral_le_lintegral_ae, exact h₁ } ... ≤ (∫⁻ a, ennreal.of_real ∥bound a∥) : lintegral_le_lintegral _ _ $ by { assume a, apply ennreal.of_real_le_of_real, exact le_max_left (bound a) (-bound a) } ... < ⊤ : by { rwa [integrable_iff_norm] at h } section dominated_convergence variables {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} lemma all_ae_of_real_F_le_bound (h : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) : ∀ n, ∀ₘ a, ennreal.of_real ∥F n a∥ ≤ ennreal.of_real (bound a) := λn, by filter_upwards [h n] λ a h, ennreal.of_real_le_of_real h lemma all_ae_tendsto_of_real_norm (h : ∀ₘ a, tendsto (λ n, F n a) at_top $ 𝓝 $ f a) : ∀ₘ a, tendsto (λn, ennreal.of_real ∥F n a∥) at_top $ 𝓝 $ ennreal.of_real ∥f a∥ := by filter_upwards [h] λ a h, tendsto_of_real $ tendsto.comp (continuous.tendsto continuous_norm _) h lemma all_ae_of_real_f_le_bound (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : ∀ₘ a, ennreal.of_real ∥f a∥ ≤ ennreal.of_real (bound a) := begin have F_le_bound := all_ae_of_real_F_le_bound h_bound, rw ← all_ae_all_iff at F_le_bound, filter_upwards [all_ae_tendsto_of_real_norm h_lim, F_le_bound], assume a tendsto_norm F_le_bound, exact le_of_tendsto at_top_ne_bot tendsto_norm (univ_mem_sets' F_le_bound) end lemma integrable_of_dominated_convergence {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (bound_integrable : integrable bound) (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : integrable f := /- `∥F n a∥ ≤ bound a` and `∥F n a∥ --> ∥f a∥` implies `∥f a∥ ≤ bound a`, and so `∫ ∥f∥ ≤ ∫ bound < ⊤` since `bound` is integrable -/ begin rw integrable_iff_norm, calc (∫⁻ a, (ennreal.of_real ∥f a∥)) ≤ ∫⁻ a, ennreal.of_real (bound a) : lintegral_le_lintegral_ae $ all_ae_of_real_f_le_bound h_bound h_lim ... < ⊤ : begin rw ← integrable_iff_of_real, { exact bound_integrable }, filter_upwards [h_bound 0] λ a h, le_trans (norm_nonneg _) h, end end lemma tendsto_lintegral_norm_of_dominated_convergence [second_countable_topology β] {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (F_measurable : ∀ n, measurable (F n)) (f_measurable : measurable f) (bound_integrable : integrable bound) (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0) := let b := λa, 2 * ennreal.of_real (bound a) in /- `∥F n a∥ ≤ bound a` and `F n a --> f a` implies `∥f a∥ ≤ bound a`, and thus by the triangle inequality, have `∥F n a - f a∥ ≤ 2 * (bound a). -/ have hb : ∀ n, ∀ₘ a, ennreal.of_real ∥F n a - f a∥ ≤ b a, begin assume n, filter_upwards [all_ae_of_real_F_le_bound h_bound n, all_ae_of_real_f_le_bound h_bound h_lim], assume a h₁ h₂, calc ennreal.of_real ∥F n a - f a∥ ≤ (ennreal.of_real ∥F n a∥) + (ennreal.of_real ∥f a∥) : begin rw [← ennreal.of_real_add], apply of_real_le_of_real, { apply norm_sub_le }, { exact norm_nonneg _ }, { exact norm_nonneg _ } end ... ≤ (ennreal.of_real (bound a)) + (ennreal.of_real (bound a)) : add_le_add' h₁ h₂ ... = b a : by rw ← two_mul end, /- On the other hand, `F n a --> f a` implies that `∥F n a - f a∥ --> 0` -/ have h : ∀ₘ a, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0), begin suffices h : ∀ₘ a, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 $ ennreal.of_real 0), { rwa ennreal.of_real_zero at h }, filter_upwards [h_lim], assume a h, refine tendsto.comp (continuous.tendsto continuous_of_real _) _, rw ← tendsto_iff_norm_tendsto_zero, exact h end, /- Therefore, by the dominated convergence theorem for nonnegative integration, have ` ∫ ∥f a - F n a∥ --> 0 ` -/ begin suffices h : tendsto (λn, ∫⁻ a, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 (∫⁻ (a:α), 0)), { rwa lintegral_zero at h }, -- Using the dominated convergence theorem. refine tendsto_lintegral_of_dominated_convergence _ _ hb _ _, -- Show `λa, ∥f a - F n a∥` is measurable for all `n` { exact λn, measurable.comp measurable_of_real (measurable.norm (measurable.sub (F_measurable n) f_measurable)) }, -- Show `2 * bound` is integrable { rw integrable_iff_of_real at bound_integrable, { calc (∫⁻ a, b a) = 2 * (∫⁻ a, ennreal.of_real (bound a)) : by { rw lintegral_const_mul', exact coe_ne_top } ... < ⊤ : mul_lt_top (coe_lt_top) bound_integrable }, filter_upwards [h_bound 0] λ a h, le_trans (norm_nonneg _) h }, -- Show `∥f a - F n a∥ --> 0` { exact h } end end dominated_convergence section pos_part /-! Lemmas used for defining the positive part of a `L¹` function -/ lemma integrable.max_zero {f : α → ℝ} (hf : integrable f) : integrable (λa, max (f a) 0) := begin simp only [integrable_iff_norm] at *, calc (∫⁻ a, ennreal.of_real ∥max (f a) 0∥) ≤ (∫⁻ (a : α), ennreal.of_real ∥f a∥) : lintegral_le_lintegral _ _ begin assume a, apply of_real_le_of_real, simp only [real.norm_eq_abs], calc abs (max (f a) 0) = max (f a) 0 : by { rw abs_of_nonneg, apply le_max_right } ... ≤ abs (f a) : max_le (le_abs_self _) (abs_nonneg _) end ... < ⊤ : hf end lemma integrable.min_zero {f : α → ℝ} (hf : integrable f) : integrable (λa, min (f a) 0) := begin have : (λa, min (f a) 0) = (λa, - max (-f a) 0), { funext, rw [min_eq_neg_max_neg_neg, neg_zero] }, rw this, exact (integrable.max_zero hf.neg).neg, end end pos_part section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul (c : 𝕜) {f : α → β} : integrable f → integrable (λa, c • f a) := begin simp only [integrable], assume hfi, calc (∫⁻ (a : α), nnnorm ((c • f) a)) = (∫⁻ (a : α), (nnnorm c) * nnnorm (f a)) : begin apply lintegral_congr_ae, filter_upwards [], assume a, simp only [nnnorm_smul, set.mem_set_of_eq, pi.smul_apply, ennreal.coe_mul] end ... < ⊤ : begin rw lintegral_const_mul', apply mul_lt_top, { exact coe_lt_top }, { exact hfi }, { simp only [ennreal.coe_ne_top, ne.def, not_false_iff] } end end lemma integrable_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) : integrable (λa, c • f a) ↔ integrable f := begin split, { assume h, simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.smul c⁻¹ }, exact integrable.smul _ end end normed_space variables [second_countable_topology β] namespace ae_eq_fun /-- An almost everywhere equal function is `integrable` if it has a finite distance to the origin. Should mean the same thing as the predicate `integrable` over functions. -/ def integrable (f : α →ₘ β) : Prop := f ∈ ball (0 : α →ₘ β) ⊤ lemma integrable_mk (f : α → β) (hf : measurable f) : (integrable (mk f hf)) ↔ measure_theory.integrable f := by simp [integrable, zero_def, edist_mk_mk', measure_theory.integrable, nndist_eq_nnnorm] lemma integrable_to_fun (f : α →ₘ β) : integrable f ↔ (measure_theory.integrable f.to_fun) := by conv_lhs { rw [self_eq_mk f, integrable_mk] } local attribute [simp] integrable_mk lemma integrable_zero : integrable (0 : α →ₘ β) := mem_ball_self coe_lt_top lemma integrable.add : ∀ {f g : α →ₘ β}, integrable f → integrable g → integrable (f + g) := begin rintros ⟨f, hf⟩ ⟨g, hg⟩, simp only [mem_ball, zero_def, mk_add_mk, integrable_mk, quot_mk_eq_mk], assume hfi hgi, exact hfi.add hf hg hgi end lemma integrable.neg : ∀ {f : α →ₘ β}, integrable f → integrable (-f) := by { rintros ⟨f, hf⟩, have := measure_theory.integrable.neg, simpa } lemma integrable.sub : ∀ {f g : α →ₘ β}, integrable f → integrable g → integrable (f - g) := begin rintros ⟨f, hfm⟩ ⟨g, hgm⟩, simp only [mem_ball, zero_def, mk_sub_mk, integrable_mk, quot_mk_eq_mk], assume hfi hgi, exact hfi.sub hfm hgm hgi end protected lemma is_add_subgroup : is_add_subgroup (ball (0 : α →ₘ β) ⊤) := { zero_mem := integrable_zero, add_mem := λ _ _, integrable.add, neg_mem := λ _, integrable.neg } section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul : ∀ {c : 𝕜} {f : α →ₘ β}, integrable f → integrable (c • f) := by { assume c, rintros ⟨f, hf⟩, simpa using integrable.smul _ } end normed_space end ae_eq_fun section variables (α β) /-- The space of equivalence classes of integrable (and measurable) functions, where two integrable functions are equivalent if they agree almost everywhere, i.e., they differ on a set of measure `0`. -/ def l1 : Type (max u v) := subtype (@ae_eq_fun.integrable α _ β _ _) infixr ` →₁ `:25 := l1 end namespace l1 open ae_eq_fun local attribute [instance] ae_eq_fun.is_add_subgroup instance : has_coe (α →₁ β) (α →ₘ β) := ⟨subtype.val⟩ protected lemma eq {f g : α →₁ β} : (f : α →ₘ β) = (g : α →ₘ β) → f = g := subtype.eq @[elim_cast] protected lemma eq_iff {f g : α →₁ β} : (f : α →ₘ β) = (g : α →ₘ β) ↔ f = g := iff.intro (l1.eq) (congr_arg coe) /- TODO : order structure of l1-/ /-- `L¹` space forms a `emetric_space`, with the emetric being inherited from almost everywhere functions, i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`. -/ instance : emetric_space (α →₁ β) := subtype.emetric_space /-- `L¹` space forms a `metric_space`, with the metric being inherited from almost everywhere functions, i.e., `edist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a))`. -/ instance : metric_space (α →₁ β) := metric_space_emetric_ball 0 ⊤ instance : add_comm_group (α →₁ β) := subtype.add_comm_group instance : inhabited (α →₁ β) := ⟨0⟩ @[simp, elim_cast] lemma coe_zero : ((0 : α →₁ β) : α →ₘ β) = 0 := rfl @[simp, move_cast] lemma coe_add (f g : α →₁ β) : ((f + g : α →₁ β) : α →ₘ β) = f + g := rfl @[simp, move_cast] lemma coe_neg (f : α →₁ β) : ((-f : α →₁ β) : α →ₘ β) = -f := rfl @[simp, move_cast] lemma coe_sub (f g : α →₁ β) : ((f - g : α →₁ β) : α →ₘ β) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁ β) : edist f g = edist (f : α →ₘ β) (g : α →ₘ β) := rfl lemma dist_eq (f g : α →₁ β) : dist f g = ennreal.to_real (edist (f : α →ₘ β) (g : α →ₘ β)) := rfl /-- The norm on `L¹` space is defined to be `∥f∥ = ∫⁻ a, edist (f a) 0`. -/ instance : has_norm (α →₁ β) := ⟨λ f, dist f 0⟩ lemma norm_eq (f : α →₁ β) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ β) 0) := rfl instance : normed_group (α →₁ β) := normed_group.of_add_dist (λ x, rfl) $ by { intros, simp only [dist_eq, coe_add], rw edist_eq_add_add } section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] instance : has_scalar 𝕜 (α →₁ β) := ⟨λ x f, ⟨x • (f : α →ₘ β), ae_eq_fun.integrable.smul f.2⟩⟩ @[simp, move_cast] lemma coe_smul (c : 𝕜) (f : α →₁ β) : ((c • f : α →₁ β) : α →ₘ β) = c • (f : α →ₘ β) := rfl instance : semimodule 𝕜 (α →₁ β) := { one_smul := λf, l1.eq (by { simp only [coe_smul], exact one_smul _ _ }), mul_smul := λx y f, l1.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }), smul_add := λx f g, l1.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }), smul_zero := λx, l1.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }), add_smul := λx y f, l1.eq (by { simp only [coe_smul], exact add_smul _ _ _ }), zero_smul := λf, l1.eq (by { simp only [coe_smul], exact zero_smul _ _ }) } instance : module 𝕜 (α →₁ β) := { .. l1.semimodule } instance : vector_space 𝕜 (α →₁ β) := { .. l1.semimodule } instance : normed_space 𝕜 (α →₁ β) := ⟨ begin rintros x ⟨f, hf⟩, show ennreal.to_real (edist (x • f) 0) = ∥x∥ * ennreal.to_real (edist f 0), rw [edist_smul, to_real_of_real_mul], exact norm_nonneg _ end ⟩ end normed_space section of_fun /-- Construct the equivalence class `[f]` of a measurable and integrable function `f`. -/ def of_fun (f : α → β) (hfm : measurable f) (hfi : integrable f) : (α →₁ β) := ⟨mk f hfm, by { rw integrable_mk, exact hfi }⟩ lemma of_fun_eq_mk (f : α → β) (hfm hfi) : (of_fun f hfm hfi : α →ₘ β) = mk f hfm := rfl lemma of_fun_eq_of_fun (f g : α → β) (hfm hfi hgm hgi) : of_fun f hfm hfi = of_fun g hgm hgi ↔ ∀ₘ a, f a = g a := by { rw ← l1.eq_iff, simp only [of_fun_eq_mk, mk_eq_mk] } lemma of_fun_zero : of_fun (λa:α, (0:β)) (@measurable_const _ _ _ _ (0:β)) (integrable_zero α β) = 0 := rfl lemma of_fun_add (f g : α → β) (hfm hfi hgm hgi) : of_fun (λa, f a + g a) (measurable.add hfm hgm) (integrable.add hfm hfi hgm hgi) = of_fun f hfm hfi + of_fun g hgm hgi := rfl lemma of_fun_neg (f : α → β) (hfm hfi) : of_fun (λa, - f a) (measurable.neg hfm) (integrable.neg hfi) = - of_fun f hfm hfi := rfl lemma of_fun_sub (f g : α → β) (hfm hfi hgm hgi) : of_fun (λa, f a - g a) (measurable.sub hfm hgm) (integrable.sub hfm hfi hgm hgi) = of_fun f hfm hfi - of_fun g hgm hgi := rfl lemma norm_of_fun (f : α → β) (hfm hfi) : ∥of_fun f hfm hfi∥ = ennreal.to_real (∫⁻ a, edist (f a) 0) := rfl lemma norm_of_fun_eq_lintegral_norm (f : α → β) (hfm hfi) : ∥of_fun f hfm hfi∥ = ennreal.to_real (∫⁻ a, ennreal.of_real ∥f a∥) := by { rw [norm_of_fun, lintegral_norm_eq_lintegral_edist] } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma of_fun_smul (f : α → β) (hfm hfi) (k : 𝕜) : of_fun (λa, k • f a) (measurable.smul _ hfm) (integrable.smul _ hfi) = k • of_fun f hfm hfi := rfl end of_fun section to_fun /-- Find a representative of a `L¹` function [f] -/ @[reducible] protected def to_fun (f : α →₁ β) : α → β := (f : α →ₘ β).to_fun protected lemma measurable (f : α →₁ β) : measurable f.to_fun := f.1.measurable protected lemma integrable (f : α →₁ β) : integrable f.to_fun := by { rw [l1.to_fun, ← integrable_to_fun], exact f.2 } lemma of_fun_to_fun (f : α →₁ β) : of_fun (f.to_fun) f.measurable f.integrable = f := begin rcases f with ⟨f, hfi⟩, rw [of_fun, subtype.mk_eq_mk], exact (self_eq_mk f).symm end lemma mk_to_fun (f : α →₁ β) : mk (f.to_fun) f.measurable = f := by { rw ← of_fun_eq_mk, rw l1.eq_iff, exact of_fun_to_fun f } lemma to_fun_of_fun (f : α → β) (hfm hfi) : ∀ₘ a, (of_fun f hfm hfi).to_fun a = f a := begin filter_upwards [all_ae_mk_to_fun f hfm], assume a, simp only [mem_set_of_eq], assume h, rw ← h, refl end variables (α β) lemma zero_to_fun : ∀ₘ a, (0 : α →₁ β).to_fun a = 0 := ae_eq_fun.zero_to_fun variables {α β} lemma add_to_fun (f g : α →₁ β) : ∀ₘ a, (f + g).to_fun a = f.to_fun a + g.to_fun a := ae_eq_fun.add_to_fun _ _ lemma neg_to_fun (f : α →₁ β) : ∀ₘ a, (-f).to_fun a = -f.to_fun a := ae_eq_fun.neg_to_fun _ lemma sub_to_fun (f g : α →₁ β) : ∀ₘ a, (f - g).to_fun a = f.to_fun a - g.to_fun a := ae_eq_fun.sub_to_fun _ _ lemma dist_to_fun (f g : α →₁ β) : dist f g = ennreal.to_real (∫⁻ x, edist (f.to_fun x) (g.to_fun x)) := by { simp only [dist_eq, edist_to_fun] } lemma norm_eq_nnnorm_to_fun (f : α →₁ β) : ∥f∥ = ennreal.to_real (∫⁻ a, nnnorm (f.to_fun a)) := by { rw [lintegral_nnnorm_eq_lintegral_edist, ← edist_zero_to_fun], refl } lemma norm_eq_norm_to_fun (f : α →₁ β) : ∥f∥ = ennreal.to_real (∫⁻ a, ennreal.of_real ∥f.to_fun a∥) := by { rw norm_eq_nnnorm_to_fun, congr, funext, rw of_real_norm_eq_coe_nnnorm } lemma lintegral_edist_to_fun_lt_top (f g : α →₁ β) : (∫⁻ a, edist (f.to_fun a) (g.to_fun a)) < ⊤ := begin apply lintegral_edist_lt_top, exact f.measurable, exact f.integrable, exact g.measurable, exact g.integrable end variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma smul_to_fun (c : 𝕜) (f : α →₁ β) : ∀ₘ a, (c • f).to_fun a = c • f.to_fun a := ae_eq_fun.smul_to_fun _ _ end to_fun section pos_part /-- Positive part of a function in `L¹` space. -/ def pos_part (f : α →₁ ℝ) : α →₁ ℝ := ⟨ ae_eq_fun.pos_part f, begin rw [ae_eq_fun.integrable_to_fun, integrable_congr_ae (pos_part_to_fun _)], exact integrable.max_zero f.integrable end ⟩ /-- Negative part of a function in `L¹` space. -/ def neg_part (f : α →₁ ℝ) : α →₁ ℝ := pos_part (-f) @[move_cast] lemma coe_pos_part (f : α →₁ ℝ) : (f.pos_part : α →ₘ ℝ) = (f : α →ₘ ℝ).pos_part := rfl lemma pos_part_to_fun (f : α →₁ ℝ) : ∀ₘ a, (pos_part f).to_fun a = max (f.to_fun a) 0 := ae_eq_fun.pos_part_to_fun _ lemma neg_part_to_fun_eq_max (f : α →₁ ℝ) : ∀ₘ a, (neg_part f).to_fun a = max (- f.to_fun a) 0 := begin rw neg_part, filter_upwards [pos_part_to_fun (-f), neg_to_fun f], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂] end lemma neg_part_to_fun_eq_min (f : α →₁ ℝ) : ∀ₘ a, (neg_part f).to_fun a = - min (f.to_fun a) 0 := begin filter_upwards [neg_part_to_fun_eq_max f], simp only [mem_set_of_eq], assume a h, rw [h, min_eq_neg_max_neg_neg, _root_.neg_neg, neg_zero], end lemma norm_le_norm_of_ae_le {f g : α →₁ β} (h : ∀ₘ a, ∥f.to_fun a∥ ≤ ∥g.to_fun a∥) : ∥f∥ ≤ ∥g∥ := begin simp only [l1.norm_eq_norm_to_fun], rw to_real_le_to_real, { apply lintegral_le_lintegral_ae, filter_upwards [h], simp only [mem_set_of_eq], assume a h, exact of_real_le_of_real h }, { rw [← lt_top_iff_ne_top, ← integrable_iff_norm], exact f.integrable }, { rw [← lt_top_iff_ne_top, ← integrable_iff_norm], exact g.integrable } end lemma continuous_pos_part : continuous $ λf : α →₁ ℝ, pos_part f := begin simp only [metric.continuous_iff], assume g ε hε, use ε, use hε, simp only [dist_eq_norm], assume f hfg, refine lt_of_le_of_lt (norm_le_norm_of_ae_le _) hfg, filter_upwards [l1.sub_to_fun f g, l1.sub_to_fun (pos_part f) (pos_part g), pos_part_to_fun f, pos_part_to_fun g], simp only [mem_set_of_eq], assume a h₁ h₂ h₃ h₄, simp only [real.norm_eq_abs, h₁, h₂, h₃, h₄], exact abs_max_sub_max_le_abs _ _ _ end lemma continuous_neg_part : continuous $ λf : α →₁ ℝ, neg_part f := have eq : (λf : α →₁ ℝ, neg_part f) = (λf : α →₁ ℝ, pos_part (-f)) := rfl, by { rw eq, exact continuous_pos_part.comp continuous_neg } end pos_part /- TODO: l1 is a complete space -/ end l1 end measure_theory
f6936173dbffd2d29c8ac3283e2bdec1f6cdb8b7
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/undergraduate/MAS114/scratch.lean
a37539e4bb737e618eb88c570293813aa88d38ba
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,443
lean
def half_Q : ℚ := 1 / 2 def neg_half_Q : ℚ := - half_Q noncomputable def half_R : ℝ := half_Q noncomputable def neg_half_R : ℝ := neg_half_Q /- Even basic identities like 1/2 - 1 = -1/2 cannot easily be proved directly in ℝ, because there are no general algorithms for exact calculation in ℝ. We need to work in ℚ and then apply the cast map. -/ /- Here is a small identity that could in principle be proved by a long string of applications of the commutative ring axioms. The "ring" tactic automates the process of finding this string. For reasons that I do not fully understand, the ring tactic seems to work more reliably if we do it in a separate lemma so that the terms are just free variables. We can then substitute values for this variables as an extra step. In particular, we will substitute h = 1/2, and then give a separate argument that the final term 2 * h - 1 is zero. -/ lemma misc_identity (m n h : ℝ) : (m + h) - (2 * m + 1 - n) = - ((m + h) - n) + (2 * h - 1) := by ring /- We now prove that there is no closest integer to m + 1/2. The obvious approach would be to focus attention on the candidates n = m and n = m + 1, but it turns out that that creates more work than necessary. It is more efficient to prove that for all n, the integer k = 2 m + 1 - n is different from n and lies at the same distance from m + 1/2, so n does not have the required property. -/ lemma no_closest_integer (n m : ℤ) : ¬ (is_closest_integer n ((m : ℝ) + half_R)) := begin intro h0, let x_Q : ℚ := (m : ℚ) + half_Q, let x_R : ℝ := (m : ℝ) + half_R, let k := 2 * m + 1 - n, by_cases e0 : k = n, {-- In this block we consider the possibility that k = n, and -- show that it is impossible. exfalso, dsimp[k] at e0, let e1 := calc (1 : ℤ) = (2 * m + 1 + -n) + n - 2 * m : by ring ... = n + n - 2 * m : by rw[e0] ... = 2 * (n - m) : by ring, have e2 := calc (1 : ℤ) = int.mod 1 2 : rfl ... = int.mod (2 * (n - m)) 2 : congr_arg (λ x, int.mod x 2) e1 ... = 0 : int.mul_mod_right 2 (n - m), exact (dec_trivial : (1 : ℤ) ≠ 0) e2, },{ let h1 := ne_of_gt (h0 k e0), let u_R := x_R - n, let v_R := x_R - k, have h2 : v_R = - u_R + (2 * half_R - 1) := begin dsimp[u_R,v_R,x_R,k], rw[int.cast_add,int.cast_add,int.cast_mul,int.cast_bit0], rw[int.cast_one,int.cast_neg], exact misc_identity (↑ m) (↑ n) half_R, end, have h3 : 2 * half_Q - 1 = 0 := dec_trivial, have h4 : 2 * half_R - 1 = (((2 * half_Q - 1) : ℚ) : ℝ) := begin dsimp[half_R], rw[rat.cast_add,rat.cast_mul,rat.cast_bit0,rat.cast_neg,rat.cast_one], end, have h5 : 2 * half_R - 1 = 0 := by rw[h4,h3,rat.cast_zero], rw[h5,add_zero] at h2, have h6 : abs v_R = abs u_R := by rw[h2,abs_neg], exact h1 h6, } end def fibonacci_step_mod (p : ℕ+) : ℕ × ℕ → ℕ × ℕ := λ ⟨a,b⟩, ⟨b,(a + b) % p⟩ #eval fibonacci_pair_mod 89 44 def fibonacci_mod (p : ℕ+): ℕ → ℕ | 0 := 0 % p | 1 := 1 % p | (n + 2) := ((fibonacci_mod n) + (fibonacci_mod (n + 1))) % p lemma fibonacci_mod_mod (p : ℕ+) (n : ℕ) : fibonacci_mod p n = (fibonacci_mod p n) % p := begin rcases n with _ | _ | n; rw[fibonacci_mod,nat.mod_mod], end lemma fibonacci_mod_spec (p : ℕ+) : ∀ n, fibonacci_mod p n = (fibonacci n) % p | 0 := rfl | 1 := rfl | (n + 2) := begin rw[fibonacci_mod_mod], change fibonacci_mod p (n + 2) ≡ fibonacci (n + 2) [MOD p], rw[fibonacci,fibonacci_mod], let h0 := calc fibonacci n ≡ (fibonacci n) % p [MOD p] : (nat.modeq.mod_modeq (fibonacci n) p).symm ... ≡ fibonacci_mod p n [MOD p] : by rw[fibonacci_mod_spec n], let h1 := calc fibonacci n.succ ≡ (fibonacci n.succ) % p [MOD p] : (nat.modeq.mod_modeq (fibonacci n.succ) p).symm ... ≡ fibonacci_mod p n.succ [MOD p] : by rw[fibonacci_mod_spec n.succ], let h2 := nat.modeq.modeq_add h0 h1, rw[nat.modeq,nat.mod_mod,← nat.modeq], exact h2.symm end lemma fibonacci_period (p : ℕ+) (m : ℕ) (h0 : (fibonacci m) ≡ 0 [MOD p]) (h1 : (fibonacci (m + 1)) ≡ 1 [MOD p]) : ∀ n, fibonacci (m + n) ≡ (fibonacci n) [MOD p] | 0 := by {simp[zero_add,h0,fibonacci],} | 1 := by {simp[zero_add,h1,fibonacci],} | (n + 2) := begin rw[← add_assoc,fibonacci,fibonacci], apply nat.modeq.modeq_add, apply fibonacci_period n, apply fibonacci_period n.succ, end
0a3be761b173c831b21ec49fe306f99b9f9029d4
43d840497673d50aaf1058dc851b1edc51d1ab11
/src/solutions/tuesday/morning.lean
6cc67790308f0b6a5334d6e93c6866b37c875633
[]
permissive
dhruva-divate/lftcm2020
6606bc857204fbfd8ab92812060c0e5114f67e0d
d2e1a31a4ad280eadef1d0ae6a89920b7345c823
refs/heads/master
1,668,432,237,346
1,594,377,206,000
1,594,377,206,000
278,630,020
0
0
MIT
1,594,384,713,000
1,594,384,712,000
null
UTF-8
Lean
false
false
79
lean
import tactic example : true := begin -- sorry trivial, -- sorry end
8528834d33461c863cb43ab521050cda91876213
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/pfunctor/univariate/M.lean
e59d13b8212e221c0e5b300be0af2c6fb9960e46
[]
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
16,750
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.pfunctor.univariate.basic import Mathlib.PostPort universes u l w u_1 namespace Mathlib /-! # M-types M types are potentially infinite tree-like structures. They are defined as the greatest fixpoint of a polynomial functor. -/ namespace pfunctor namespace approx /-- `cofix_a F n` is an `n` level approximation of a M-type -/ inductive cofix_a (F : pfunctor) : ℕ → Type u where | continue : cofix_a F 0 | intro : {n : ℕ} → (a : A F) → (B F a → cofix_a F n) → cofix_a F (Nat.succ n) /-- default inhabitant of `cofix_a` -/ protected def cofix_a.default (F : pfunctor) [Inhabited (A F)] (n : ℕ) : cofix_a F n := sorry protected instance cofix_a.inhabited (F : pfunctor) [Inhabited (A F)] {n : ℕ} : Inhabited (cofix_a F n) := { default := cofix_a.default F n } theorem cofix_a_eq_zero (F : pfunctor) (x : cofix_a F 0) (y : cofix_a F 0) : x = y := sorry /-- The label of the root of the tree for a non-trivial approximation of the cofix of a pfunctor. -/ def head' {F : pfunctor} {n : ℕ} : cofix_a F (Nat.succ n) → A F := sorry /-- for a non-trivial approximation, return all the subtrees of the root -/ def children' {F : pfunctor} {n : ℕ} (x : cofix_a F (Nat.succ n)) : B F (head' x) → cofix_a F n := sorry theorem approx_eta {F : pfunctor} {n : ℕ} (x : cofix_a F (n + 1)) : x = cofix_a.intro (head' x) (children' x) := sorry /-- Relation between two approximations of the cofix of a pfunctor that state they both contain the same data until one of them is truncated -/ inductive agree {F : pfunctor} : {n : ℕ} → cofix_a F n → cofix_a F (n + 1) → Prop where | continue : ∀ (x : cofix_a F 0) (y : cofix_a F 1), agree x y | intro : ∀ {n : ℕ} {a : A F} (x : B F a → cofix_a F n) (x' : B F a → cofix_a F (n + 1)), (∀ (i : B F a), agree (x i) (x' i)) → agree (cofix_a.intro a x) (cofix_a.intro a x') /-- Given an infinite series of approximations `approx`, `all_agree approx` states that they are all consistent with each other. -/ def all_agree {F : pfunctor} (x : (n : ℕ) → cofix_a F n) := ∀ (n : ℕ), agree (x n) (x (Nat.succ n)) @[simp] theorem agree_trival {F : pfunctor} {x : cofix_a F 0} {y : cofix_a F 1} : agree x y := agree.continue x y theorem agree_children {F : pfunctor} {n : ℕ} (x : cofix_a F (Nat.succ n)) (y : cofix_a F (Nat.succ n + 1)) {i : B F (head' x)} {j : B F (head' y)} (h₀ : i == j) (h₁ : agree x y) : agree (children' x i) (children' y j) := sorry /-- `truncate a` turns `a` into a more limited approximation -/ def truncate {F : pfunctor} {n : ℕ} : cofix_a F (n + 1) → cofix_a F n := sorry theorem truncate_eq_of_agree {F : pfunctor} {n : ℕ} (x : cofix_a F n) (y : cofix_a F (Nat.succ n)) (h : agree x y) : truncate y = x := sorry /-- `s_corec f i n` creates an approximation of height `n` of the final coalgebra of `f` -/ def s_corec {F : pfunctor} {X : Type w} (f : X → obj F X) (i : X) (n : ℕ) : cofix_a F n := sorry theorem P_corec {F : pfunctor} {X : Type w} (f : X → obj F X) (i : X) (n : ℕ) : agree (s_corec f i n) (s_corec f i (Nat.succ n)) := sorry /-- `path F` provides indices to access internal nodes in `corec F` -/ def path (F : pfunctor) := List (Idx F) protected instance path.inhabited {F : pfunctor} : Inhabited (path F) := { default := [] } protected instance cofix_a.subsingleton {F : pfunctor} : subsingleton (cofix_a F 0) := subsingleton.intro fun (a b : cofix_a F 0) => cofix_a.cases_on a (fun (a_1 : 0 = 0) (H_2 : a == cofix_a.continue) => Eq._oldrec (cofix_a.cases_on b (fun (a : 0 = 0) (H_2 : b == cofix_a.continue) => Eq._oldrec (Eq.refl cofix_a.continue) (Eq.symm (eq_of_heq H_2))) (fun {b_n : ℕ} (b_a : A F) (b_ᾰ : B F b_a → cofix_a F b_n) (a : 0 = Nat.succ b_n) => nat.no_confusion a) (Eq.refl 0) (HEq.refl b)) (Eq.symm (eq_of_heq H_2))) (fun {a_n : ℕ} (a_a : A F) (a_ᾰ : B F a_a → cofix_a F a_n) (a_1 : 0 = Nat.succ a_n) => nat.no_confusion a_1) (Eq.refl 0) (HEq.refl a) theorem head_succ' {F : pfunctor} (n : ℕ) (m : ℕ) (x : (n : ℕ) → cofix_a F n) (Hconsistent : all_agree x) : head' (x (Nat.succ n)) = head' (x (Nat.succ m)) := sorry end approx /-- Internal definition for `M`. It is needed to avoid name clashes between `M.mk` and `M.cases_on` and the declarations generated for the structure -/ structure M_intl (F : pfunctor) where approx : (n : ℕ) → approx.cofix_a F n consistent : approx.all_agree approx /-- For polynomial functor `F`, `M F` is its final coalgebra -/ def M (F : pfunctor) := M_intl F theorem M.default_consistent (F : pfunctor) [Inhabited (A F)] (n : ℕ) : approx.agree Inhabited.default Inhabited.default := sorry protected instance M.inhabited (F : pfunctor) [Inhabited (A F)] : Inhabited (M F) := { default := M_intl.mk (fun (n : ℕ) => Inhabited.default) (M.default_consistent F) } protected instance M_intl.inhabited (F : pfunctor) [Inhabited (A F)] : Inhabited (M_intl F) := (fun (this : Inhabited (M F)) => this) (M.inhabited F) namespace M theorem ext' (F : pfunctor) (x : M F) (y : M F) (H : ∀ (i : ℕ), M_intl.approx x i = M_intl.approx y i) : x = y := sorry /-- Corecursor for the M-type defined by `F`. -/ protected def corec {F : pfunctor} {X : Type u_1} (f : X → obj F X) (i : X) : M F := M_intl.mk (approx.s_corec f i) (approx.P_corec f i) /-- given a tree generated by `F`, `head` gives us the first piece of data it contains -/ def head {F : pfunctor} (x : M F) : A F := approx.head' (M_intl.approx x 1) /-- return all the subtrees of the root of a tree `x : M F` -/ def children {F : pfunctor} (x : M F) (i : B F (head x)) : M F := M_intl.mk (fun (n : ℕ) => approx.children' (M_intl.approx x (Nat.succ n)) (cast sorry i)) sorry /-- select a subtree using a `i : F.Idx` or return an arbitrary tree if `i` designates no subtree of `x` -/ def ichildren {F : pfunctor} [Inhabited (M F)] [DecidableEq (A F)] (i : Idx F) (x : M F) : M F := dite (sigma.fst i = head x) (fun (H' : sigma.fst i = head x) => children x (cast sorry (sigma.snd i))) fun (H' : ¬sigma.fst i = head x) => Inhabited.default theorem head_succ {F : pfunctor} (n : ℕ) (m : ℕ) (x : M F) : approx.head' (M_intl.approx x (Nat.succ n)) = approx.head' (M_intl.approx x (Nat.succ m)) := approx.head_succ' n m (M_intl.approx x) (M_intl.consistent x) theorem head_eq_head' {F : pfunctor} (x : M F) (n : ℕ) : head x = approx.head' (M_intl.approx x (n + 1)) := sorry theorem head'_eq_head {F : pfunctor} (x : M F) (n : ℕ) : approx.head' (M_intl.approx x (n + 1)) = head x := sorry theorem truncate_approx {F : pfunctor} (x : M F) (n : ℕ) : approx.truncate (M_intl.approx x (n + 1)) = M_intl.approx x n := approx.truncate_eq_of_agree (M_intl.approx x n) (M_intl.approx x (n + 1)) (M_intl.consistent x n) /-- unfold an M-type -/ def dest {F : pfunctor} : M F → obj F (M F) := sorry namespace approx /-- generates the approximations needed for `M.mk` -/ protected def s_mk {F : pfunctor} (x : obj F (M F)) (n : ℕ) : approx.cofix_a F n := sorry protected theorem P_mk {F : pfunctor} (x : obj F (M F)) : approx.all_agree (approx.s_mk x) := sorry end approx /-- constructor for M-types -/ protected def mk {F : pfunctor} (x : obj F (M F)) : M F := M_intl.mk (approx.s_mk x) (approx.P_mk x) /-- `agree' n` relates two trees of type `M F` that are the same up to dept `n` -/ inductive agree' {F : pfunctor} : ℕ → M F → M F → Prop where | trivial : ∀ (x y : M F), agree' 0 x y | step : ∀ {n : ℕ} {a : A F} (x y : B F a → M F) {x' y' : M F}, x' = M.mk (sigma.mk a x) → y' = M.mk (sigma.mk a y) → (∀ (i : B F a), agree' n (x i) (y i)) → agree' (Nat.succ n) x' y' @[simp] theorem dest_mk {F : pfunctor} (x : obj F (M F)) : dest (M.mk x) = x := sorry @[simp] theorem mk_dest {F : pfunctor} (x : M F) : M.mk (dest x) = x := sorry theorem mk_inj {F : pfunctor} {x : obj F (M F)} {y : obj F (M F)} (h : M.mk x = M.mk y) : x = y := eq.mpr (id (Eq._oldrec (Eq.refl (x = y)) (Eq.symm (dest_mk x)))) (eq.mpr (id (Eq._oldrec (Eq.refl (dest (M.mk x) = y)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (dest (M.mk y) = y)) (dest_mk y))) (Eq.refl y))) /-- destructor for M-types -/ protected def cases {F : pfunctor} {r : M F → Sort w} (f : (x : obj F (M F)) → r (M.mk x)) (x : M F) : r x := (fun (this : r (M.mk (dest x))) => eq.mpr sorry this) (f (dest x)) /-- destructor for M-types -/ protected def cases_on {F : pfunctor} {r : M F → Sort w} (x : M F) (f : (x : obj F (M F)) → r (M.mk x)) : r x := M.cases f x /-- destructor for M-types, similar to `cases_on` but also gives access directly to the root and subtrees on an M-type -/ protected def cases_on' {F : pfunctor} {r : M F → Sort w} (x : M F) (f : (a : A F) → (f : B F a → M F) → r (M.mk (sigma.mk a f))) : r x := M.cases_on x fun (_x : obj F (M F)) => sorry theorem approx_mk {F : pfunctor} (a : A F) (f : B F a → M F) (i : ℕ) : M_intl.approx (M.mk (sigma.mk a f)) (Nat.succ i) = approx.cofix_a.intro a fun (j : B F a) => M_intl.approx (f j) i := rfl @[simp] theorem agree'_refl {F : pfunctor} {n : ℕ} (x : M F) : agree' n x x := sorry theorem agree_iff_agree' {F : pfunctor} {n : ℕ} (x : M F) (y : M F) : approx.agree (M_intl.approx x n) (M_intl.approx y (n + 1)) ↔ agree' n x y := sorry @[simp] theorem cases_mk {F : pfunctor} {r : M F → Sort u_1} (x : obj F (M F)) (f : (x : obj F (M F)) → r (M.mk x)) : M.cases f (M.mk x) = f x := sorry @[simp] theorem cases_on_mk {F : pfunctor} {r : M F → Sort u_1} (x : obj F (M F)) (f : (x : obj F (M F)) → r (M.mk x)) : M.cases_on (M.mk x) f = f x := cases_mk x f @[simp] theorem cases_on_mk' {F : pfunctor} {r : M F → Sort u_1} {a : A F} (x : B F a → M F) (f : (a : A F) → (f : B F a → M F) → r (M.mk (sigma.mk a f))) : M.cases_on' (M.mk (sigma.mk a x)) f = f a x := cases_mk (sigma.mk a x) fun (_x : obj F (M F)) => cases_on'._match_1 f _x /-- `is_path p x` tells us if `p` is a valid path through `x` -/ inductive is_path {F : pfunctor} : approx.path F → M F → Prop where | nil : ∀ (x : M F), is_path [] x | cons : ∀ (xs : approx.path F) {a : A F} (x : M F) (f : B F a → M F) (i : B F a), x = M.mk (sigma.mk a f) → is_path xs (f i) → is_path (sigma.mk a i :: xs) x theorem is_path_cons {F : pfunctor} {xs : approx.path F} {a : A F} {a' : A F} {f : B F a → M F} {i : B F a'} (h : is_path (sigma.mk a' i :: xs) (M.mk (sigma.mk a f))) : a = a' := sorry theorem is_path_cons' {F : pfunctor} {xs : approx.path F} {a : A F} {f : B F a → M F} {i : B F a} (h : is_path (sigma.mk a i :: xs) (M.mk (sigma.mk a f))) : is_path xs (f i) := sorry /-- follow a path through a value of `M F` and return the subtree found at the end of the path if it is a valid path for that value and return a default tree -/ def isubtree {F : pfunctor} [DecidableEq (A F)] [Inhabited (M F)] : approx.path F → M F → M F := sorry /-- similar to `isubtree` but returns the data at the end of the path instead of the whole subtree -/ def iselect {F : pfunctor} [DecidableEq (A F)] [Inhabited (M F)] (ps : approx.path F) : M F → A F := fun (x : M F) => head (isubtree ps x) theorem iselect_eq_default {F : pfunctor} [DecidableEq (A F)] [Inhabited (M F)] (ps : approx.path F) (x : M F) (h : ¬is_path ps x) : iselect ps x = head Inhabited.default := sorry @[simp] theorem head_mk {F : pfunctor} (x : obj F (M F)) : head (M.mk x) = sigma.fst x := sorry theorem children_mk {F : pfunctor} {a : A F} (x : B F a → M F) (i : B F (head (M.mk (sigma.mk a x)))) : children (M.mk (sigma.mk a x)) i = x (cast (eq.mpr (id (Eq._oldrec (Eq.refl (B F (head (M.mk (sigma.mk a x))) = B F a)) (head_mk (sigma.mk a x)))) (Eq.refl (B F (sigma.fst (sigma.mk a x))))) i) := sorry @[simp] theorem ichildren_mk {F : pfunctor} [DecidableEq (A F)] [Inhabited (M F)] (x : obj F (M F)) (i : Idx F) : ichildren i (M.mk x) = obj.iget x i := sorry @[simp] theorem isubtree_cons {F : pfunctor} [DecidableEq (A F)] [Inhabited (M F)] (ps : approx.path F) {a : A F} (f : B F a → M F) {i : B F a} : isubtree (sigma.mk a i :: ps) (M.mk (sigma.mk a f)) = isubtree ps (f i) := sorry @[simp] theorem iselect_nil {F : pfunctor} [DecidableEq (A F)] [Inhabited (M F)] {a : A F} (f : B F a → M F) : iselect [] (M.mk (sigma.mk a f)) = a := Eq.refl (iselect [] (M.mk (sigma.mk a f))) @[simp] theorem iselect_cons {F : pfunctor} [DecidableEq (A F)] [Inhabited (M F)] (ps : approx.path F) {a : A F} (f : B F a → M F) {i : B F a} : iselect (sigma.mk a i :: ps) (M.mk (sigma.mk a f)) = iselect ps (f i) := sorry theorem corec_def {F : pfunctor} {X : Type u} (f : X → obj F X) (x₀ : X) : M.corec f x₀ = M.mk (M.corec f <$> f x₀) := sorry theorem ext_aux {F : pfunctor} [Inhabited (M F)] [DecidableEq (A F)] {n : ℕ} (x : M F) (y : M F) (z : M F) (hx : agree' n z x) (hy : agree' n z y) (hrec : ∀ (ps : approx.path F), n = list.length ps → iselect ps x = iselect ps y) : M_intl.approx x (n + 1) = M_intl.approx y (n + 1) := sorry theorem ext {F : pfunctor} [Inhabited (M F)] (x : M F) (y : M F) (H : ∀ (ps : approx.path F), iselect ps x = iselect ps y) : x = y := sorry /-- Bisimulation is the standard proof technique for equality between infinite tree-like structures -/ structure is_bisimulation {F : pfunctor} (R : M F → M F → Prop) where head : ∀ {a a' : A F} {f : B F a → M F} {f' : B F a' → M F}, R (M.mk (sigma.mk a f)) (M.mk (sigma.mk a' f')) → a = a' tail : ∀ {a : A F} {f f' : B F a → M F}, R (M.mk (sigma.mk a f)) (M.mk (sigma.mk a f')) → ∀ (i : B F a), R (f i) (f' i) theorem nth_of_bisim {F : pfunctor} (R : M F → M F → Prop) [Inhabited (M F)] (bisim : is_bisimulation R) (s₁ : M F) (s₂ : M F) (ps : approx.path F) : R s₁ s₂ → is_path ps s₁ ∨ is_path ps s₂ → iselect ps s₁ = iselect ps s₂ ∧ ∃ (a : A F), ∃ (f : B F a → M F), ∃ (f' : B F a → M F), isubtree ps s₁ = M.mk (sigma.mk a f) ∧ isubtree ps s₂ = M.mk (sigma.mk a f') ∧ ∀ (i : B F a), R (f i) (f' i) := sorry theorem eq_of_bisim {F : pfunctor} (R : M F → M F → Prop) [Nonempty (M F)] (bisim : is_bisimulation R) (s₁ : M F) (s₂ : M F) : R s₁ s₂ → s₁ = s₂ := sorry /-- corecursor for `M F` with swapped arguments -/ def corec_on {F : pfunctor} {X : Type u_1} (x₀ : X) (f : X → obj F X) : M F := M.corec f x₀ theorem dest_corec {P : pfunctor} {α : Type u} (g : α → obj P α) (x : α) : dest (M.corec g x) = M.corec g <$> g x := sorry theorem bisim {P : pfunctor} (R : M P → M P → Prop) (h : ∀ (x y : M P), R x y → ∃ (a : A P), ∃ (f : B P a → M P), ∃ (f' : B P a → M P), dest x = sigma.mk a f ∧ dest y = sigma.mk a f' ∧ ∀ (i : B P a), R (f i) (f' i)) (x : M P) (y : M P) : R x y → x = y := sorry theorem bisim' {P : pfunctor} {α : Type u_1} (Q : α → Prop) (u : α → M P) (v : α → M P) (h : ∀ (x : α), Q x → ∃ (a : A P), ∃ (f : B P a → M P), ∃ (f' : B P a → M P), dest (u x) = sigma.mk a f ∧ dest (v x) = sigma.mk a f' ∧ ∀ (i : B P a), ∃ (x' : α), Q x' ∧ f i = u x' ∧ f' i = v x') (x : α) : Q x → u x = v x := sorry -- for the record, show M_bisim follows from _bisim' theorem bisim_equiv {P : pfunctor} (R : M P → M P → Prop) (h : ∀ (x y : M P), R x y → ∃ (a : A P), ∃ (f : B P a → M P), ∃ (f' : B P a → M P), dest x = sigma.mk a f ∧ dest y = sigma.mk a f' ∧ ∀ (i : B P a), R (f i) (f' i)) (x : M P) (y : M P) : R x y → x = y := sorry theorem corec_unique {P : pfunctor} {α : Type u} (g : α → obj P α) (f : α → M P) (hyp : ∀ (x : α), dest (f x) = f <$> g x) : f = M.corec g := sorry /-- corecursor where the state of the computation can be sent downstream in the form of a recursive call -/ def corec₁ {P : pfunctor} {α : Type u} (F : (X : Type u) → (α → X) → α → obj P X) : α → M P := M.corec (F α id) /-- corecursor where it is possible to return a fully formed value at any point of the computation -/ def corec' {P : pfunctor} {α : Type u} (F : {X : Type u} → (α → X) → α → M P ⊕ obj P X) (x : α) : M P := corec₁ (fun (X : Type u) (rec : M P ⊕ α → X) (a : M P ⊕ α) => let y : M P ⊕ obj P X := a >>= F (rec ∘ sum.inr); sorry) (sum.inr x)
088c5cd1ff90027dda7aeed7a26bec5f9575c3a0
359199d7253811b032ab92108191da7336eba86e
/src/mywork/mid-term_review/pre_exam_oh_notes.lean
7b395e54641608b174a9ab182b5c5a8bc7438a92
[]
no_license
arte-et-marte/my_cs2120f21
0bc6215cb5018a3b7c90d9d399a173233f587064
91609c3609ad81fda895bee8b97cc76813241e17
refs/heads/main
1,693,298,928,348
1,634,931,202,000
1,634,931,202,000
399,946,705
0
0
null
null
null
null
UTF-8
Lean
false
false
643
lean
-- Is the exam open-note? -- What does lemma mean? /- exists intro takes in two things _ _ - a witness, 3 - proof that 3 satisfies predicate ∃ (n : ℕ), ev n exists.intro 3 ways to get to a goal of false: 1. some var of type false, can exact it (or contradiction?) 2. apply false elimination rule on a proof of false. 3. have 2 variables that provide a direct contradiction in context 4. have a proof of something's that's obviously false, 1 = 0, can apply cases to that, 0 cases -/ example : ∃ (n : ℕ), n = 1 := begin -- how do we prove an exists statement - need the exists Intro rule! exact exists.intro 1 (eq.refl 1), end
980146866fd4d36f06a5957d6db2bf58c3a49ef9
94e33a31faa76775069b071adea97e86e218a8ee
/src/order/compactly_generated.lean
c6cd469de8db929398b5307ca53ea478b1a2333c
[ "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
22,030
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import tactic.tfae import order.atoms import order.order_iso_nat import order.sup_indep import order.zorn import data.finset.order import data.finite.default /-! # Compactness properties for complete lattices For complete lattices, there are numerous equivalent ways to express the fact that the relation `>` is well-founded. In this file we define three especially-useful characterisations and provide proofs that they are indeed equivalent to well-foundedness. ## Main definitions * `complete_lattice.is_sup_closed_compact` * `complete_lattice.is_Sup_finite_compact` * `complete_lattice.is_compact_element` * `complete_lattice.is_compactly_generated` ## Main results The main result is that the following four conditions are equivalent for a complete lattice: * `well_founded (>)` * `complete_lattice.is_sup_closed_compact` * `complete_lattice.is_Sup_finite_compact` * `∀ k, complete_lattice.is_compact_element k` This is demonstrated by means of the following four lemmas: * `complete_lattice.well_founded.is_Sup_finite_compact` * `complete_lattice.is_Sup_finite_compact.is_sup_closed_compact` * `complete_lattice.is_sup_closed_compact.well_founded` * `complete_lattice.is_Sup_finite_compact_iff_all_elements_compact` We also show well-founded lattices are compactly generated (`complete_lattice.compactly_generated_of_well_founded`). ## References - [G. Călugăreanu, *Lattice Concepts of Module Theory*][calugareanu] ## Tags complete lattice, well-founded, compact -/ variables {α : Type*} [complete_lattice α] namespace complete_lattice variables (α) /-- A compactness property for a complete lattice is that any `sup`-closed non-empty subset contains its `Sup`. -/ def is_sup_closed_compact : Prop := ∀ (s : set α) (h : s.nonempty), (∀ a b ∈ s, a ⊔ b ∈ s) → (Sup s) ∈ s /-- A compactness property for a complete lattice is that any subset has a finite subset with the same `Sup`. -/ def is_Sup_finite_compact : Prop := ∀ (s : set α), ∃ (t : finset α), ↑t ⊆ s ∧ Sup s = t.sup id /-- An element `k` of a complete lattice is said to be compact if any set with `Sup` above `k` has a finite subset with `Sup` above `k`. Such an element is also called "finite" or "S-compact". -/ def is_compact_element {α : Type*} [complete_lattice α] (k : α) := ∀ s : set α, k ≤ Sup s → ∃ t : finset α, ↑t ⊆ s ∧ k ≤ t.sup id lemma {u} is_compact_element_iff {α : Type u} [complete_lattice α] (k : α) : complete_lattice.is_compact_element k ↔ ∀ (ι : Type u) (s : ι → α), k ≤ supr s → ∃ t : finset ι, k ≤ t.sup s := begin classical, split, { intros H ι s hs, obtain ⟨t, ht, ht'⟩ := H (set.range s) hs, have : ∀ x : t, ∃ i, s i = x := λ x, ht x.prop, choose f hf using this, refine ⟨finset.univ.image f, ht'.trans _⟩, { rw finset.sup_le_iff, intros b hb, rw ← (show s (f ⟨b, hb⟩) = id b, from hf _), exact finset.le_sup (finset.mem_image_of_mem f $ finset.mem_univ ⟨b, hb⟩) } }, { intros H s hs, obtain ⟨t, ht⟩ := H s coe (by { delta supr, rwa subtype.range_coe }), refine ⟨t.image coe, by simp, ht.trans _⟩, rw finset.sup_le_iff, exact λ x hx, @finset.le_sup _ _ _ _ _ id _ (finset.mem_image_of_mem coe hx) } end /-- An element `k` is compact if and only if any directed set with `Sup` above `k` already got above `k` at some point in the set. -/ theorem is_compact_element_iff_le_of_directed_Sup_le (k : α) : is_compact_element k ↔ ∀ s : set α, s.nonempty → directed_on (≤) s → k ≤ Sup s → ∃ x : α, x ∈ s ∧ k ≤ x := begin classical, split, { intros hk s hne hdir hsup, obtain ⟨t, ht⟩ := hk s hsup, -- certainly every element of t is below something in s, since ↑t ⊆ s. have t_below_s : ∀ x ∈ t, ∃ y ∈ s, x ≤ y, from λ x hxt, ⟨x, ht.left hxt, le_rfl⟩, obtain ⟨x, ⟨hxs, hsupx⟩⟩ := finset.sup_le_of_le_directed s hne hdir t t_below_s, exact ⟨x, ⟨hxs, le_trans ht.right hsupx⟩⟩, }, { intros hk s hsup, -- Consider the set of finite joins of elements of the (plain) set s. let S : set α := { x | ∃ t : finset α, ↑t ⊆ s ∧ x = t.sup id }, -- S is directed, nonempty, and still has sup above k. have dir_US : directed_on (≤) S, { rintros x ⟨c, hc⟩ y ⟨d, hd⟩, use x ⊔ y, split, { use c ∪ d, split, { simp only [hc.left, hd.left, set.union_subset_iff, finset.coe_union, and_self], }, { simp only [hc.right, hd.right, finset.sup_union], }, }, simp only [and_self, le_sup_left, le_sup_right], }, have sup_S : Sup s ≤ Sup S, { apply Sup_le_Sup, intros x hx, use {x}, simpa only [and_true, id.def, finset.coe_singleton, eq_self_iff_true, finset.sup_singleton, set.singleton_subset_iff], }, have Sne : S.nonempty, { suffices : ⊥ ∈ S, from set.nonempty_of_mem this, use ∅, simp only [set.empty_subset, finset.coe_empty, finset.sup_empty, eq_self_iff_true, and_self], }, -- Now apply the defn of compact and finish. obtain ⟨j, ⟨hjS, hjk⟩⟩ := hk S Sne dir_US (le_trans hsup sup_S), obtain ⟨t, ⟨htS, htsup⟩⟩ := hjS, use t, exact ⟨htS, by rwa ←htsup⟩, }, end /-- A compact element `k` has the property that any directed set lying strictly below `k` has its Sup strictly below `k`. -/ lemma is_compact_element.directed_Sup_lt_of_lt {α : Type*} [complete_lattice α] {k : α} (hk : is_compact_element k) {s : set α} (hemp : s.nonempty) (hdir : directed_on (≤) s) (hbelow : ∀ x ∈ s, x < k) : Sup s < k := begin rw is_compact_element_iff_le_of_directed_Sup_le at hk, by_contradiction, have sSup : Sup s ≤ k, from Sup_le (λ s hs, (hbelow s hs).le), replace sSup : Sup s = k := eq_iff_le_not_lt.mpr ⟨sSup, h⟩, obtain ⟨x, hxs, hkx⟩ := hk s hemp hdir sSup.symm.le, obtain hxk := hbelow x hxs, exact hxk.ne (hxk.le.antisymm hkx), end lemma finset_sup_compact_of_compact {α β : Type*} [complete_lattice α] {f : β → α} (s : finset β) (h : ∀ x ∈ s, is_compact_element (f x)) : is_compact_element (s.sup f) := begin classical, rw is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, change f with id ∘ f, rw ←finset.sup_finset_image, apply finset.sup_le_of_le_directed d hemp hdir, rintros x hx, obtain ⟨p, ⟨hps, rfl⟩⟩ := finset.mem_image.mp hx, specialize h p hps, rw is_compact_element_iff_le_of_directed_Sup_le at h, specialize h d hemp hdir (le_trans (finset.le_sup hps) hsup), simpa only [exists_prop], end lemma well_founded.is_Sup_finite_compact (h : well_founded ((>) : α → α → Prop)) : is_Sup_finite_compact α := begin intros s, let p : set α := { x | ∃ (t : finset α), ↑t ⊆ s ∧ t.sup id = x }, have hp : p.nonempty, { use [⊥, ∅], simp, }, obtain ⟨m, ⟨t, ⟨ht₁, ht₂⟩⟩, hm⟩ := well_founded.well_founded_iff_has_max'.mp h p hp, use t, simp only [ht₁, ht₂, true_and], apply le_antisymm, { apply Sup_le, intros y hy, classical, have hy' : (insert y t).sup id ∈ p, { use insert y t, simp, rw set.insert_subset, exact ⟨hy, ht₁⟩, }, have hm' : m ≤ (insert y t).sup id, { rw ← ht₂, exact finset.sup_mono (t.subset_insert y), }, rw ← hm _ hy' hm', simp, }, { rw [← ht₂, finset.sup_id_eq_Sup], exact Sup_le_Sup ht₁, }, end lemma is_Sup_finite_compact.is_sup_closed_compact (h : is_Sup_finite_compact α) : is_sup_closed_compact α := begin intros s hne hsc, obtain ⟨t, ht₁, ht₂⟩ := h s, clear h, cases t.eq_empty_or_nonempty with h h, { subst h, rw finset.sup_empty at ht₂, rw ht₂, simp [eq_singleton_bot_of_Sup_eq_bot_of_nonempty ht₂ hne], }, { rw ht₂, exact t.sup_closed_of_sup_closed h ht₁ hsc, }, end lemma is_sup_closed_compact.well_founded (h : is_sup_closed_compact α) : well_founded ((>) : α → α → Prop) := begin refine rel_embedding.well_founded_iff_no_descending_seq.mpr ⟨λ a, _⟩, suffices : Sup (set.range a) ∈ set.range a, { obtain ⟨n, hn⟩ := set.mem_range.mp this, have h' : Sup (set.range a) < a (n+1), { change _ > _, simp [← hn, a.map_rel_iff], }, apply lt_irrefl (a (n+1)), apply lt_of_le_of_lt _ h', apply le_Sup, apply set.mem_range_self, }, apply h (set.range a), { use a 37, apply set.mem_range_self, }, { rintros x ⟨m, hm⟩ y ⟨n, hn⟩, use m ⊔ n, rw [← hm, ← hn], apply rel_hom_class.map_sup a, }, end lemma is_Sup_finite_compact_iff_all_elements_compact : is_Sup_finite_compact α ↔ (∀ k : α, is_compact_element k) := begin refine ⟨λ h k s hs, _, λ h s, _⟩, { obtain ⟨t, ⟨hts, htsup⟩⟩ := h s, use [t, hts], rwa ←htsup, }, { obtain ⟨t, ⟨hts, htsup⟩⟩ := h (Sup s) s (by refl), have : Sup s = t.sup id, { suffices : t.sup id ≤ Sup s, by { apply le_antisymm; assumption }, simp only [id.def, finset.sup_le_iff], intros x hx, exact le_Sup (hts hx) }, use [t, hts, this] }, end lemma well_founded_characterisations : tfae [well_founded ((>) : α → α → Prop), is_Sup_finite_compact α, is_sup_closed_compact α, ∀ k : α, is_compact_element k] := begin tfae_have : 1 → 2, by { exact well_founded.is_Sup_finite_compact α, }, tfae_have : 2 → 3, by { exact is_Sup_finite_compact.is_sup_closed_compact α, }, tfae_have : 3 → 1, by { exact is_sup_closed_compact.well_founded α, }, tfae_have : 2 ↔ 4, by { exact is_Sup_finite_compact_iff_all_elements_compact α }, tfae_finish, end lemma well_founded_iff_is_Sup_finite_compact : well_founded ((>) : α → α → Prop) ↔ is_Sup_finite_compact α := (well_founded_characterisations α).out 0 1 lemma is_Sup_finite_compact_iff_is_sup_closed_compact : is_Sup_finite_compact α ↔ is_sup_closed_compact α := (well_founded_characterisations α).out 1 2 lemma is_sup_closed_compact_iff_well_founded : is_sup_closed_compact α ↔ well_founded ((>) : α → α → Prop) := (well_founded_characterisations α).out 2 0 alias well_founded_iff_is_Sup_finite_compact ↔ _ is_Sup_finite_compact.well_founded alias is_Sup_finite_compact_iff_is_sup_closed_compact ↔ _ is_sup_closed_compact.is_Sup_finite_compact alias is_sup_closed_compact_iff_well_founded ↔ _ _root_.well_founded.is_sup_closed_compact variables {α} lemma well_founded.finite_of_set_independent (h : well_founded ((>) : α → α → Prop)) {s : set α} (hs : set_independent s) : s.finite := begin classical, refine set.not_infinite.mp (λ contra, _), obtain ⟨t, ht₁, ht₂⟩ := well_founded.is_Sup_finite_compact α h s, replace contra : ∃ (x : α), x ∈ s ∧ x ≠ ⊥ ∧ x ∉ t, { have : (s \ (insert ⊥ t : finset α)).infinite := contra.diff (finset.finite_to_set _), obtain ⟨x, hx₁, hx₂⟩ := this.nonempty, exact ⟨x, hx₁, by simpa [not_or_distrib] using hx₂⟩, }, obtain ⟨x, hx₀, hx₁, hx₂⟩ := contra, replace hs : x ⊓ Sup s = ⊥, { have := hs.mono (by simp [ht₁, hx₀, -set.union_singleton] : ↑t ∪ {x} ≤ s) (by simp : x ∈ _), simpa [disjoint, hx₂, ← t.sup_id_eq_Sup, ← ht₂] using this, }, apply hx₁, rw [← hs, eq_comm, inf_eq_left], exact le_Sup hx₀, end lemma well_founded.finite_of_independent (hwf : well_founded ((>) : α → α → Prop)) {ι : Type*} {t : ι → α} (ht : independent t) (h_ne_bot : ∀ i, t i ≠ ⊥) : finite ι := begin haveI := (well_founded.finite_of_set_independent hwf ht.set_independent_range).to_subtype, exact finite.of_injective_finite_range (ht.injective h_ne_bot), end end complete_lattice /-- A complete lattice is said to be compactly generated if any element is the `Sup` of compact elements. -/ class is_compactly_generated (α : Type*) [complete_lattice α] : Prop := (exists_Sup_eq : ∀ (x : α), ∃ (s : set α), (∀ x ∈ s, complete_lattice.is_compact_element x) ∧ Sup s = x) section variables {α} [is_compactly_generated α] {a b : α} {s : set α} @[simp] lemma Sup_compact_le_eq (b) : Sup {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} = b := begin rcases is_compactly_generated.exists_Sup_eq b with ⟨s, hs, rfl⟩, exact le_antisymm (Sup_le (λ c hc, hc.2)) (Sup_le_Sup (λ c cs, ⟨hs c cs, le_Sup cs⟩)), end @[simp] theorem Sup_compact_eq_top : Sup {a : α | complete_lattice.is_compact_element a} = ⊤ := begin refine eq.trans (congr rfl (set.ext (λ x, _))) (Sup_compact_le_eq ⊤), exact (and_iff_left le_top).symm, end theorem le_iff_compact_le_imp {a b : α} : a ≤ b ↔ ∀ c : α, complete_lattice.is_compact_element c → c ≤ a → c ≤ b := ⟨λ ab c hc ca, le_trans ca ab, λ h, begin rw [← Sup_compact_le_eq a, ← Sup_compact_le_eq b], exact Sup_le_Sup (λ c hc, ⟨hc.1, h c hc.1 hc.2⟩), end⟩ /-- This property is sometimes referred to as `α` being upper continuous. -/ theorem inf_Sup_eq_of_directed_on (h : directed_on (≤) s): a ⊓ Sup s = ⨆ b ∈ s, a ⊓ b := le_antisymm (begin rw le_iff_compact_le_imp, by_cases hs : s.nonempty, { intros c hc hcinf, rw le_inf_iff at hcinf, rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le at hc, rcases hc s hs h hcinf.2 with ⟨d, ds, cd⟩, exact (le_inf hcinf.1 cd).trans (le_supr₂ d ds) }, { rw set.not_nonempty_iff_eq_empty at hs, simp [hs] } end) supr_inf_le_inf_Sup /-- This property is equivalent to `α` being upper continuous. -/ theorem inf_Sup_eq_supr_inf_sup_finset : a ⊓ Sup s = ⨆ (t : finset α) (H : ↑t ⊆ s), a ⊓ (t.sup id) := le_antisymm (begin rw le_iff_compact_le_imp, intros c hc hcinf, rw le_inf_iff at hcinf, rcases hc s hcinf.2 with ⟨t, ht1, ht2⟩, exact (le_inf hcinf.1 ht2).trans (le_supr₂ t ht1), end) (supr_le $ λ t, supr_le $ λ h, inf_le_inf_left _ ((finset.sup_id_eq_Sup t).symm ▸ (Sup_le_Sup h))) theorem complete_lattice.set_independent_iff_finite {s : set α} : complete_lattice.set_independent s ↔ ∀ t : finset α, ↑t ⊆ s → complete_lattice.set_independent (↑t : set α) := ⟨λ hs t ht, hs.mono ht, λ h a ha, begin rw [disjoint_iff, inf_Sup_eq_supr_inf_sup_finset, supr_eq_bot], intro t, rw [supr_eq_bot, finset.sup_id_eq_Sup], intro ht, classical, have h' := (h (insert a t) _ (t.mem_insert_self a)).eq_bot, { rwa [finset.coe_insert, set.insert_diff_self_of_not_mem] at h', exact λ con, ((set.mem_diff a).1 (ht con)).2 (set.mem_singleton a) }, { rw [finset.coe_insert, set.insert_subset], exact ⟨ha, set.subset.trans ht (set.diff_subset _ _)⟩ } end⟩ lemma complete_lattice.set_independent_Union_of_directed {η : Type*} {s : η → set α} (hs : directed (⊆) s) (h : ∀ i, complete_lattice.set_independent (s i)) : complete_lattice.set_independent (⋃ i, s i) := begin by_cases hη : nonempty η, { resetI, rw complete_lattice.set_independent_iff_finite, intros t ht, obtain ⟨I, fi, hI⟩ := set.finite_subset_Union t.finite_to_set ht, obtain ⟨i, hi⟩ := hs.finset_le fi.to_finset, exact (h i).mono (set.subset.trans hI $ set.Union₂_subset $ λ j hj, hi j (fi.mem_to_finset.2 hj)) }, { rintros a ⟨_, ⟨i, _⟩, _⟩, exfalso, exact hη ⟨i⟩, }, end lemma complete_lattice.independent_sUnion_of_directed {s : set (set α)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, complete_lattice.set_independent a) : complete_lattice.set_independent (⋃₀ s) := by rw set.sUnion_eq_Union; exact complete_lattice.set_independent_Union_of_directed hs.directed_coe (by simpa using h) end namespace complete_lattice lemma compactly_generated_of_well_founded (h : well_founded ((>) : α → α → Prop)) : is_compactly_generated α := begin rw [well_founded_iff_is_Sup_finite_compact, is_Sup_finite_compact_iff_all_elements_compact] at h, -- x is the join of the set of compact elements {x} exact ⟨λ x, ⟨{x}, ⟨λ x _, h x, Sup_singleton⟩⟩⟩, end /-- A compact element `k` has the property that any `b < k` lies below a "maximal element below `k`", which is to say `[⊥, k]` is coatomic. -/ theorem Iic_coatomic_of_compact_element {k : α} (h : is_compact_element k) : is_coatomic (set.Iic k) := ⟨λ ⟨b, hbk⟩, begin by_cases htriv : b = k, { left, ext, simp only [htriv, set.Iic.coe_top, subtype.coe_mk], }, right, obtain ⟨a, a₀, ba, h⟩ := zorn_nonempty_partial_order₀ (set.Iio k) _ b (lt_of_le_of_ne hbk htriv), { refine ⟨⟨a, le_of_lt a₀⟩, ⟨ne_of_lt a₀, λ c hck, by_contradiction $ λ c₀, _⟩, ba⟩, cases h c.1 (lt_of_le_of_ne c.2 (λ con, c₀ (subtype.ext con))) hck.le, exact lt_irrefl _ hck, }, { intros S SC cC I IS, by_cases hS : S.nonempty, { exact ⟨Sup S, h.directed_Sup_lt_of_lt hS cC.directed_on SC, λ _, le_Sup⟩, }, exact ⟨b, lt_of_le_of_ne hbk htriv, by simp only [set.not_nonempty_iff_eq_empty.mp hS, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff]⟩, }, end⟩ lemma coatomic_of_top_compact (h : is_compact_element (⊤ : α)) : is_coatomic α := (@order_iso.Iic_top α _ _).is_coatomic_iff.mp (Iic_coatomic_of_compact_element h) end complete_lattice section variables [is_modular_lattice α] [is_compactly_generated α] @[priority 100] instance is_atomic_of_is_complemented [is_complemented α] : is_atomic α := ⟨λ b, begin by_cases h : {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} ⊆ {⊥}, { left, rw [← Sup_compact_le_eq b, Sup_eq_bot], exact h }, { rcases set.not_subset.1 h with ⟨c, ⟨hc, hcb⟩, hcbot⟩, right, have hc' := complete_lattice.Iic_coatomic_of_compact_element hc, rw ← is_atomic_iff_is_coatomic at hc', haveI := hc', obtain con | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le (⟨c, le_refl c⟩ : set.Iic c), { exfalso, apply hcbot, simp only [subtype.ext_iff, set.Iic.coe_bot, subtype.coe_mk] at con, exact con }, rw [← subtype.coe_le_coe, subtype.coe_mk] at hac, exact ⟨a, ha.of_is_atom_coe_Iic, hac.trans hcb⟩ }, end⟩ /-- See Lemma 5.1, Călugăreanu -/ @[priority 100] instance is_atomistic_of_is_complemented [is_complemented α] : is_atomistic α := ⟨λ b, ⟨{a | is_atom a ∧ a ≤ b}, begin symmetry, have hle : Sup {a : α | is_atom a ∧ a ≤ b} ≤ b := (Sup_le $ λ _, and.right), apply (lt_or_eq_of_le hle).resolve_left (λ con, _), obtain ⟨c, hc⟩ := exists_is_compl (⟨Sup {a : α | is_atom a ∧ a ≤ b}, hle⟩ : set.Iic b), obtain rfl | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le c, { exact ne_of_lt con (subtype.ext_iff.1 (eq_top_of_is_compl_bot hc)) }, { apply ha.1, rw eq_bot_iff, apply le_trans (le_inf _ hac) hc.1, rw [← subtype.coe_le_coe, subtype.coe_mk], exact le_Sup ⟨ha.of_is_atom_coe_Iic, a.2⟩ } end, λ _, and.left⟩⟩ /-- See Theorem 6.6, Călugăreanu -/ theorem is_complemented_of_Sup_atoms_eq_top (h : Sup {a : α | is_atom a} = ⊤) : is_complemented α := ⟨λ b, begin obtain ⟨s, ⟨s_ind, b_inf_Sup_s, s_atoms⟩, s_max⟩ := zorn_subset {s : set α | complete_lattice.set_independent s ∧ b ⊓ Sup s = ⊥ ∧ ∀ a ∈ s, is_atom a} _, { refine ⟨Sup s, le_of_eq b_inf_Sup_s, h.symm.trans_le $ Sup_le_iff.2 $ λ a ha, _⟩, rw ← inf_eq_left, refine (ha.le_iff.mp inf_le_left).resolve_left (λ con, ha.1 _), rw [eq_bot_iff, ← con], refine le_inf (le_refl a) ((le_Sup _).trans le_sup_right), rw ← disjoint_iff at *, have a_dis_Sup_s : disjoint a (Sup s) := con.mono_right le_sup_right, rw ← s_max (s ∪ {a}) ⟨λ x hx, _, ⟨_, λ x hx, _⟩⟩ (set.subset_union_left _ _), { exact set.mem_union_right _ (set.mem_singleton _) }, { rw [set.mem_union, set.mem_singleton_iff] at hx, by_cases xa : x = a, { simp only [xa, set.mem_singleton, set.insert_diff_of_mem, set.union_singleton], exact con.mono_right (le_trans (Sup_le_Sup (set.diff_subset s {a})) le_sup_right) }, { have h : (s ∪ {a}) \ {x} = (s \ {x}) ∪ {a}, { simp only [set.union_singleton], rw set.insert_diff_of_not_mem, rw set.mem_singleton_iff, exact ne.symm xa }, rw [h, Sup_union, Sup_singleton], apply (s_ind (hx.resolve_right xa)).disjoint_sup_right_of_disjoint_sup_left (a_dis_Sup_s.mono_right _).symm, rw [← Sup_insert, set.insert_diff_singleton, set.insert_eq_of_mem (hx.resolve_right xa)] } }, { rw [Sup_union, Sup_singleton, ← disjoint_iff], exact b_inf_Sup_s.disjoint_sup_right_of_disjoint_sup_left con.symm }, { rw [set.mem_union, set.mem_singleton_iff] at hx, cases hx, { exact s_atoms x hx }, { rw hx, exact ha } } }, { intros c hc1 hc2, refine ⟨⋃₀ c, ⟨complete_lattice.independent_sUnion_of_directed hc2.directed_on (λ s hs, (hc1 hs).1), _, λ a ha, _⟩, λ _, set.subset_sUnion_of_mem⟩, { rw [Sup_sUnion, ← Sup_image, inf_Sup_eq_of_directed_on, supr_eq_bot], { intro i, rw supr_eq_bot, intro hi, obtain ⟨x, xc, rfl⟩ := (set.mem_image _ _ _).1 hi, exact (hc1 xc).2.1 }, { rw directed_on_image, refine hc2.directed_on.mono (λ s t, Sup_le_Sup) } }, { rcases set.mem_sUnion.1 ha with ⟨s, sc, as⟩, exact (hc1 sc).2.2 a as } } end⟩ /-- See Theorem 6.6, Călugăreanu -/ theorem is_complemented_of_is_atomistic [is_atomistic α] : is_complemented α := is_complemented_of_Sup_atoms_eq_top Sup_atoms_eq_top theorem is_complemented_iff_is_atomistic : is_complemented α ↔ is_atomistic α := begin split; introsI, { exact is_atomistic_of_is_complemented }, { exact is_complemented_of_is_atomistic } end end
c37477d5952f1c4c7def153d963ee05a46867cc9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/action.lean
935da218803452d1a3b18198cadd5e5547ef364d
[ "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,730
lean
/- Copyright (c) 2020 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import category_theory.elements import category_theory.is_connected import category_theory.single_obj import group_theory.group_action.quotient import group_theory.semidirect_product /-! # Actions as functors and as categories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. From a multiplicative action M ↻ X, we can construct a functor from M to the category of types, mapping the single object of M to X and an element `m : M` to map `X → X` given by multiplication by `m`. This functor induces a category structure on X -- a special case of the category of elements. A morphism `x ⟶ y` in this category is simply a scalar `m : M` such that `m • x = y`. In the case where M is a group, this category is a groupoid -- the `action groupoid'. -/ open mul_action semidirect_product namespace category_theory universes u variables (M : Type*) [monoid M] (X : Type u) [mul_action M X] /-- A multiplicative action M ↻ X viewed as a functor mapping the single object of M to X and an element `m : M` to the map `X → X` given by multiplication by `m`. -/ @[simps] def action_as_functor : single_obj M ⥤ Type u := { obj := λ _, X, map := λ _ _, (•), map_id' := λ _, funext $ mul_action.one_smul, map_comp' := λ _ _ _ f g, funext $ λ x, (smul_smul g f x).symm } /-- A multiplicative action M ↻ X induces a category strucure on X, where a morphism from x to y is a scalar taking x to y. Due to implementation details, the object type of this category is not equal to X, but is in bijection with X. -/ @[derive category] def action_category := (action_as_functor M X).elements namespace action_category /-- The projection from the action category to the monoid, mapping a morphism to its label. -/ def π : action_category M X ⥤ single_obj M := category_of_elements.π _ @[simp] lemma π_map (p q : action_category M X) (f : p ⟶ q) : (π M X).map f = f.val := rfl @[simp] lemma π_obj (p : action_category M X) : (π M X).obj p = single_obj.star M := unit.ext variables {M X} /-- The canonical map `action_category M X → X`. It is given by `λ x, x.snd`, but has a more explicit type. -/ protected def back : action_category M X → X := λ x, x.snd instance : has_coe_t X (action_category M X) := ⟨λ x, ⟨(), x⟩⟩ @[simp] lemma coe_back (x : X) : (↑x : action_category M X).back = x := rfl @[simp] lemma back_coe (x : action_category M X) : ↑(x.back) = x := by ext; refl variables (M X) /-- An object of the action category given by M ↻ X corresponds to an element of X. -/ def obj_equiv : X ≃ action_category M X := { to_fun := coe, inv_fun := λ x, x.back, left_inv := coe_back, right_inv := back_coe } lemma hom_as_subtype (p q : action_category M X) : (p ⟶ q) = { m : M // m • p.back = q.back } := rfl instance [inhabited X] : inhabited (action_category M X) := ⟨show X, from default⟩ instance [nonempty X] : nonempty (action_category M X) := nonempty.map (obj_equiv M X) infer_instance variables {X} (x : X) /-- The stabilizer of a point is isomorphic to the endomorphism monoid at the corresponding point. In fact they are definitionally equivalent. -/ def stabilizer_iso_End : stabilizer.submonoid M x ≃* End (↑x : action_category M X) := mul_equiv.refl _ @[simp] lemma stabilizer_iso_End_apply (f : stabilizer.submonoid M x) : (stabilizer_iso_End M x).to_fun f = f := rfl @[simp] lemma stabilizer_iso_End_symm_apply (f : End _) : (stabilizer_iso_End M x).inv_fun f = f := rfl variables {M X} @[simp] protected lemma id_val (x : action_category M X) : subtype.val (𝟙 x) = 1 := rfl @[simp] protected lemma comp_val {x y z : action_category M X} (f : x ⟶ y) (g : y ⟶ z) : (f ≫ g).val = g.val * f.val := rfl instance [is_pretransitive M X] [nonempty X] : is_connected (action_category M X) := zigzag_is_connected $ λ x y, relation.refl_trans_gen.single $ or.inl $ nonempty_subtype.mpr (show _, from exists_smul_eq M x.back y.back) section group variables {G : Type*} [group G] [mul_action G X] noncomputable instance : groupoid (action_category G X) := category_theory.groupoid_of_elements _ /-- Any subgroup of `G` is a vertex group in its action groupoid. -/ def End_mul_equiv_subgroup (H : subgroup G) : End (obj_equiv G (G ⧸ H) ↑(1 : G)) ≃* H := mul_equiv.trans (stabilizer_iso_End G ((1 : G) : G ⧸ H)).symm (mul_equiv.subgroup_congr $ stabilizer_quotient H) /-- A target vertex `t` and a scalar `g` determine a morphism in the action groupoid. -/ def hom_of_pair (t : X) (g : G) : ↑(g⁻¹ • t) ⟶ (t : action_category G X) := subtype.mk g (smul_inv_smul g t) @[simp] lemma hom_of_pair.val (t : X) (g : G) : (hom_of_pair t g).val = g := rfl /-- Any morphism in the action groupoid is given by some pair. -/ protected def cases {P : Π ⦃a b : action_category G X⦄, (a ⟶ b) → Sort*} (hyp : ∀ t g, P (hom_of_pair t g)) ⦃a b⦄ (f : a ⟶ b) : P f := begin refine cast _ (hyp b.back f.val), rcases a with ⟨⟨⟩, a : X⟩, rcases b with ⟨⟨⟩, b : X⟩, rcases f with ⟨g : G, h : g • a = b⟩, cases (inv_smul_eq_iff.mpr h.symm), refl end variables {H : Type*} [group H] /-- Given `G` acting on `X`, a functor from the corresponding action groupoid to a group `H` can be curried to a group homomorphism `G →* (X → H) ⋊ G`. -/ @[simps] def curry (F : action_category G X ⥤ single_obj H) : G →* (X → H) ⋊[mul_aut_arrow] G := have F_map_eq : ∀ {a b} {f : a ⟶ b}, F.map f = (F.map (hom_of_pair b.back f.val) : H) := action_category.cases (λ _ _, rfl), { to_fun := λ g, ⟨λ b, F.map (hom_of_pair b g), g⟩, map_one' := by { congr, funext, exact F_map_eq.symm.trans (F.map_id b) }, map_mul' := begin intros g h, congr, funext, exact F_map_eq.symm.trans (F.map_comp (hom_of_pair (g⁻¹ • b) h) (hom_of_pair b g)), end } /-- Given `G` acting on `X`, a group homomorphism `φ : G →* (X → H) ⋊ G` can be uncurried to a functor from the action groupoid to `H`, provided that `φ g = (_, g)` for all `g`. -/ @[simps] def uncurry (F : G →* (X → H) ⋊[mul_aut_arrow] G) (sane : ∀ g, (F g).right = g) : action_category G X ⥤ single_obj H := { obj := λ _, (), map := λ a b f, ((F f.val).left b.back), map_id' := by { intro x, rw [action_category.id_val, F.map_one], refl }, map_comp' := begin intros x y z f g, revert y z g, refine action_category.cases _, simp [single_obj.comp_as_mul, sane], end } end group end action_category end category_theory
e5689ecceeeee64001691dcc00ccb2f98dc4a5ca
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/order/bounded_lattice.lean
550af2082d68f407761c890fc885b00e0c8e7bce
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
42,607
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 Defines bounded lattice type class hierarchy. Includes the Prop and fun instances. -/ import order.lattice import data.option.basic import tactic.pi_instances import logic.nontrivial set_option old_structure_cmd true universes u v variables {α : Type u} {β : Type v} /-- Typeclass for the `⊤` (`\top`) notation -/ class has_top (α : Type u) := (top : α) /-- Typeclass for the `⊥` (`\bot`) notation -/ class has_bot (α : Type u) := (bot : α) notation `⊤` := has_top.top notation `⊥` := has_bot.bot attribute [pattern] has_bot.bot has_top.top /-- An `order_top` is a partial order with a maximal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_top (α : Type u) extends has_top α, partial_order α := (le_top : ∀ a : α, a ≤ ⊤) section order_top variables [order_top α] {a b : α} @[simp] theorem le_top : a ≤ ⊤ := order_top.le_top a theorem top_unique (h : ⊤ ≤ a) : a = ⊤ := le_antisymm le_top h -- TODO: delete in favor of the next? theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := ⟨assume eq, eq.symm ▸ le_refl ⊤, top_unique⟩ @[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ := ⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩ @[simp] theorem not_top_lt : ¬ ⊤ < a := assume h, lt_irrefl a (lt_of_le_of_lt le_top h) theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ := top_le_iff.1 $ h₂ ▸ h lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := begin haveI := classical.dec_eq α, haveI : decidable (⊤ ≤ a) := decidable_of_iff' _ top_le_iff, by simp [-top_le_iff, lt_iff_le_not_le, not_iff_not.2 (@top_le_iff _ _ a)] end lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ := lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ := assume ha, hb $ top_unique $ ha ▸ hab end order_top lemma strict_mono.top_preimage_top' [linear_order α] [order_top β] {f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) : x ≤ a := H.top_preimage_top (λ p, by { rw h_top, exact le_top }) x theorem order_top.ext_top {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊤ : α) = ⊤ := top_unique $ by rw ← H; apply le_top theorem order_top.ext {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_top.ext_top H, casesI A, casesI B, injection this; congr' end /-- An `order_bot` is a partial order with a minimal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_bot (α : Type u) extends has_bot α, partial_order α := (bot_le : ∀ a : α, ⊥ ≤ a) section order_bot variables [order_bot α] {a b : α} @[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a theorem bot_unique (h : a ≤ ⊥) : a = ⊥ := le_antisymm h bot_le -- TODO: delete? theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := ⟨assume eq, eq.symm ▸ le_refl ⊥, bot_unique⟩ @[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := ⟨bot_unique, assume h, h.symm ▸ le_refl ⊥⟩ @[simp] theorem not_lt_bot : ¬ a < ⊥ := assume h, lt_irrefl a (lt_of_lt_of_le h bot_le) theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := assume ha, hb $ bot_unique $ ha ▸ hab theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ := le_bot_iff.1 $ h₂ ▸ h lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ := begin haveI := classical.dec_eq α, haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff, simp [-le_bot_iff, lt_iff_le_not_le, not_iff_not.2 (@le_bot_iff _ _ a)] end lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ := bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h end order_bot lemma strict_mono.bot_preimage_bot' [linear_order α] [order_bot β] {f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) : a ≤ x := H.bot_preimage_bot (λ p, by { rw h_bot, exact bot_le }) x theorem order_bot.ext_bot {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊥ : α) = ⊥ := bot_unique $ by rw ← H; apply bot_le theorem order_bot.ext {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection this; congr' end /-- A `semilattice_sup_top` is a semilattice with top and join. -/ class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α section semilattice_sup_top variables [semilattice_sup_top α] {a : α} @[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top /-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/ class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α section semilattice_sup_bot variables [semilattice_sup_bot α] {a b : α} @[simp] theorem bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] theorem sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by rw [eq_bot_iff, sup_le_iff]; simp end semilattice_sup_bot instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ := { bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice } /-- A `semilattice_inf_top` is a semilattice with top and meet. -/ class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α section semilattice_inf_top variables [semilattice_inf_top α] {a b : α} @[simp] theorem top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] theorem inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := by rw [eq_top_iff, le_inf_iff]; simp end semilattice_inf_top /-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/ class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α section semilattice_inf_bot variables [semilattice_inf_bot α] {a : α} @[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /- Bounded lattices -/ /-- A bounded lattice is a lattice with a top and bottom element, denoted `⊤` and `⊥` respectively. This allows for the interpretation of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/ class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } theorem bounded_lattice.ext {α} {A B : bounded_lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have H1 : @bounded_lattice.to_lattice α A = @bounded_lattice.to_lattice α B := lattice.ext H, have H2 := order_bot.ext H, have H3 : @bounded_lattice.to_order_top α A = @bounded_lattice.to_order_top α B := order_top.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection H1; injection H2; injection H3; congr' end /-- A bounded distributive lattice is exactly what it sounds like. -/ class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α} (h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c := ⟨assume : a ⊓ b = ⊥, calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁] ... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left] ... ≤ c : by simp [this, inf_le_right], assume : a ≤ c, bot_unique $ calc a ⊓ b ≤ b ⊓ c : by { rw [inf_comm], exact inf_le_inf_left _ this } ... = ⊥ : h₂⟩ /- Prop instance -/ instance bounded_distrib_lattice_Prop : bounded_distrib_lattice Prop := { le := λa b, a → b, le_refl := assume _, id, le_trans := assume a b c f g, g ∘ f, le_antisymm := assume a b Hab Hba, propext ⟨Hab, Hba⟩, sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := assume a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := assume a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), le_sup_inf := assume a b c H, or_iff_not_imp_left.2 $ λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩, top := true, le_top := assume a Ha, true.intro, bot := false, bot_le := @false.elim } noncomputable instance Prop.linear_order : linear_order Prop := { le_total := by intros p q; change (p → q) ∨ (q → p); tauto!, decidable_le := classical.dec_rel _, .. (_ : partial_order Prop) } @[simp] lemma le_iff_imp {p q : Prop} : p ≤ q ↔ (p → q) := iff.rfl section logic variable [preorder α] theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∧ q x) := assume a b h, and.imp (m_p h) (m_q h) -- Note: by finish [monotone] doesn't work theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∨ q x) := assume a b h, or.imp (m_p h) (m_q h) end logic instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, order_bot $ β a] : order_bot (Π a, β a) := { bot := λ _, ⊥, bot_le := λ x a, bot_le, .. pi.partial_order } /- Function lattices -/ instance pi.has_sup {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] : has_sup (Π i, α i) := ⟨λ f g i, f i ⊔ g i⟩ @[simp] lemma sup_apply {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] (f g : Π i, α i) (i : ι) : (f ⊔ g) i = f i ⊔ g i := rfl instance pi.has_inf {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] : has_inf (Π i, α i) := ⟨λ f g i, f i ⊓ g i⟩ @[simp] lemma inf_apply {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] (f g : Π i, α i) (i : ι) : (f ⊓ g) i = f i ⊓ g i := rfl instance pi.has_bot {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] : has_bot (Π i, α i) := ⟨λ i, ⊥⟩ @[simp] lemma bot_apply {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] (i : ι) : (⊥ : Π i, α i) i = ⊥ := rfl instance pi.has_top {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] : has_top (Π i, α i) := ⟨λ i, ⊤⟩ @[simp] lemma top_apply {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] (i : ι) : (⊤ : Π i, α i) i = ⊤ := rfl instance pi.semilattice_sup {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup (α i)] : semilattice_sup (Π i, α i) := by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf (α i)] : semilattice_inf (Π i, α i) := by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_bot (α i)] : semilattice_inf_bot (Π i, α i) := by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_top (α i)] : semilattice_inf_top (Π i, α i) := by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_sup_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_bot (α i)] : semilattice_sup_bot (Π i, α i) := by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_sup_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_top (α i)] : semilattice_sup_top (Π i, α i) := by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.lattice {ι : Type*} {α : ι → Type*} [Π i, lattice (α i)] : lattice (Π i, α i) := { .. pi.semilattice_sup, .. pi.semilattice_inf } instance pi.bounded_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_lattice (α i)] : bounded_lattice (Π i, α i) := { .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot } lemma eq_bot_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊥ : α) := eq_bot_mono le_top (eq.symm hα) lemma eq_top_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊤ : α) := eq_top_mono bot_le hα lemma subsingleton_of_top_le_bot {α : Type*} [bounded_lattice α] (h : (⊤ : α) ≤ (⊥ : α)) : subsingleton α := ⟨λ a b, le_antisymm (le_trans le_top $ le_trans h bot_le) (le_trans le_top $ le_trans h bot_le)⟩ lemma subsingleton_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = (⊤ : α)) : subsingleton α := subsingleton_of_top_le_bot (ge_of_eq hα) /-- Attach `⊥` to a type. -/ def with_bot (α : Type*) := option α namespace with_bot meta instance {α} [has_to_format α] : has_to_format (with_bot α) := { to_format := λ x, match x with | none := "⊥" | (some x) := to_fmt x end } instance : has_coe_t α (with_bot α) := ⟨some⟩ instance has_bot : has_bot (with_bot α) := ⟨none⟩ instance : inhabited (with_bot α) := ⟨⊥⟩ lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl /-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/ @[elab_as_eliminator] def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) : Π (n : with_bot α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[priority 10] instance has_lt [has_lt α] : has_lt (with_bot α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b := by simp [(<)] lemma bot_lt_some [has_lt α] (a : α) : (⊥ : with_bot α) < some a := ⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩ lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a instance [preorder α] : preorder (with_bot α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b, lt := (<), lt_iff_le_not_le := by intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<)]; split; refl, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha, let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in ⟨c, hc, le_trans ab bc⟩ } instance partial_order [partial_order α] : partial_order (with_bot α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₁ with a, { cases o₂ with b, {refl}, rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩, rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_bot.preorder } instance order_bot [partial_order α] : order_bot (with_bot α) := { bot_le := λ a a' h, option.no_confusion h, ..with_bot.partial_order, ..with_bot.has_bot } @[simp, norm_cast] theorem coe_le_coe [preorder α] {a b : α} : (a : with_bot α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩ @[simp] theorem some_le_some [preorder α] {a b : α} : @has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe theorem coe_le [partial_order α] {a b : α} : ∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b) | _ rfl := coe_le_coe @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b | (some a) b := le_refl a | none b := λ _ h, option.no_confusion h @[simp] lemma get_or_else_bot (a : α) : option.get_or_else (⊥ : with_bot α) a = a := rfl lemma get_or_else_bot_le_iff [order_bot α] {a : with_bot α} {b : α} : a.get_or_else ⊥ ≤ b ↔ a ≤ b := by cases a; simp [none_eq_bot, some_eq_coe] instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_bot α) (≤) | none x := is_true $ λ a h, option.no_confusion h | (some x) (some y) := if h : x ≤ y then is_true (some_le_some.2 h) else is_false $ by simp * | (some x) none := is_false $ λ h, by rcases h x rfl with ⟨y, ⟨_⟩, _⟩ instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<) | none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩ | (some x) (some y) := if h : x < y then is_true $ by simp * else is_false $ by simp * | x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩ instance linear_order [linear_order α] : linear_order (with_bot α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inl bot_le}, cases o₂ with b, {exact or.inr bot_le}, simp [le_total] end, decidable_le := with_bot.decidable_le, decidable_lt := with_bot.decidable_lt, ..with_bot.partial_order } instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) := { sup := option.lift_or_get (⊔), le_sup_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], le_sup_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₁ with b; cases o₂ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, sup_le h₁' h₂⟩ } end, ..with_bot.order_bot } instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) := { inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)), inf_le_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_left⟩ end, inf_le_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_right⟩ end, le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, le_inf ab ac⟩ end, ..with_bot.order_bot } instance lattice [lattice α] : lattice (with_bot α) := { ..with_bot.semilattice_sup, ..with_bot.semilattice_inf } theorem lattice_eq_DLO [linear_order α] : lattice_of_linear_order = @with_bot.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [linear_order α] (x y : with_bot α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [linear_order α] (x y : with_bot α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_top [order_top α] : order_top (with_bot α) := { top := some ⊤, le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩, ..with_bot.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) := { ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot } lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_bot α → with_bot α → Prop) := have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ := acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim), ⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot) (λ b, well_founded.induction h b (show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) b, from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot) (λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] : densely_ordered (with_bot α) := ⟨ assume a b, match a, b with | a, none := assume h : a < ⊥, (not_lt_bot h).elim | none, some b := assume h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ end with_bot --TODO(Mario): Construct using order dual on with_bot /-- Attach `⊤` to a type. -/ def with_top (α : Type*) := option α namespace with_top meta instance {α} [has_to_format α] : has_to_format (with_top α) := { to_format := λ x, match x with | none := "⊤" | (some x) := to_fmt x end } instance : has_coe_t α (with_top α) := ⟨some⟩ instance has_top : has_top (with_top α) := ⟨none⟩ instance : inhabited (with_top α) := ⟨⊤⟩ lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl /-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/ @[elab_as_eliminator] def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) : Π (n : with_top α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) . @[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ . @[priority 10] instance has_lt [has_lt α] : has_lt (with_top α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a } @[priority 10] instance has_le [has_le α] : has_le (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b := by simp [(<)] @[simp] theorem some_le_some [has_le α] {a b : α} : @has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b := by simp [(≤)] @[simp] theorem le_none [has_le α] {a : with_top α} : @has_le.le (with_top α) _ a none := by simp [(≤)] @[simp] theorem some_lt_none [has_lt α] {a : α} : @has_lt.lt (with_top α) _ (some a) none := by simp [(<)]; existsi a; refl instance : can_lift (with_top α) α := { coe := coe, cond := λ r, r ≠ ⊤, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } instance [preorder α] : preorder (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a, lt := (<), lt_iff_le_not_le := by { intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<),(≤)] }, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc, let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in ⟨a, ha, le_trans ab bc⟩, } instance partial_order [partial_order α] : partial_order (with_top α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₂ with b, { cases o₁ with a, {refl}, rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩, rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_top.preorder } instance order_top [partial_order α] : order_top (with_top α) := { le_top := λ a a' h, option.no_confusion h, ..with_top.partial_order, .. with_top.has_top } @[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_top α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩ theorem le_coe [partial_order α] {a b : α} : ∀ {o : option α}, a ∈ o → (@has_le.le (with_top α) _ o b ↔ a ≤ b) | _ rfl := coe_le_coe theorem le_coe_iff [partial_order α] {b : α} : ∀{x : with_top α}, x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b) | (some a) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem coe_le_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b) | (some b) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem lt_iff_exists_coe [partial_order α] : ∀{a b : with_top α}, a < b ↔ (∃p:α, a = p ∧ ↑p < b) | (some a) b := by simp [some_eq_coe, coe_eq_coe] | none b := by simp [none_eq_top] @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ := some_lt_none theorem coe_lt_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a < x ↔ (∀b:α, x = ↑b → a < b) | (some b) := by simp [some_eq_coe, coe_eq_coe, coe_lt_coe] | none := by simp [none_eq_top, coe_lt_top] lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a := assume h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_top α) (≤) := λ x y, @with_bot.decidable_le (order_dual α) _ _ y x instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_top α) (<) := λ x y, @with_bot.decidable_lt (order_dual α) _ _ y x instance linear_order [linear_order α] : linear_order (with_top α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inr le_top}, cases o₂ with b, {exact or.inl le_top}, simp [le_total] end, decidable_le := with_top.decidable_le, decidable_lt := with_top.decidable_lt, ..with_top.partial_order } instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) := { inf := option.lift_or_get (⊓), inf_le_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], inf_le_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₂ with b; cases o₃ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, le_inf h₁' h₂⟩ } end, ..with_top.order_top } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) := { sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)), le_sup_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_left⟩ end, le_sup_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_right⟩ end, sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, sup_le ab ac⟩ end, ..with_top.order_top } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl instance lattice [lattice α] : lattice (with_top α) := { ..with_top.semilattice_sup, ..with_top.semilattice_inf } theorem lattice_eq_DLO [linear_order α] : lattice_of_linear_order = @with_top.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [linear_order α] (x y : with_top α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [linear_order α] (x y : with_top α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_bot [order_bot α] : order_bot (with_top α) := { bot := some ⊥, bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩, ..with_top.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) := { ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_top α → with_top α → Prop) := have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) := λ a, acc.intro _ (well_founded.induction h a (show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) → ∀ y : with_top α, y < some b → acc (<) y, from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim) (λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))), ⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim) (λ _ _, acc_some _))) acc_some⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] : densely_ordered (with_top α) := ⟨ assume a b, match a, b with | none, a := assume h : ⊤ < a, (not_top_lt h).elim | some a, none := assume h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α] {a b : with_top α} : (a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) := ⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 in ⟨x, hx.1 ▸ hy⟩, λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩ end with_top namespace subtype /-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. -/ protected def semilattice_sup [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} := { sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩, le_sup_left := λ x y, @le_sup_left _ _ (x : α) y, le_sup_right := λ x y, @le_sup_right _ _ (x : α) y, sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. -/ protected def semilattice_inf [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} := { inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩, inf_le_left := λ x y, @inf_le_left _ _ (x : α) y, inf_le_right := λ x y, @inf_le_right _ _ (x : α) y, le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. -/ protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop} (Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_sup Psup } /-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. -/ protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop} (Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property. -/ protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop} (Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} := { top := ⟨⊤, Ptop⟩, le_top := λ x, @le_top α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. -/ protected def lattice [lattice α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : lattice {x : α // P x} := { ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup } end subtype namespace order_dual variable (α) instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩ instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩ instance [order_bot α] : order_top (order_dual α) := { le_top := @bot_le α _, .. order_dual.partial_order α, .. order_dual.has_top α } instance [order_top α] : order_bot (order_dual α) := { bot_le := @le_top α _, .. order_dual.partial_order α, .. order_dual.has_bot α } instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_top α } instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_bot α } instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_top α } instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_bot α } instance [bounded_lattice α] : bounded_lattice (order_dual α) := { .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α } instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) := { .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α } end order_dual namespace prod variables (α β) instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩ instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩ instance [order_top α] [order_top β] : order_top (α × β) := { le_top := assume a, ⟨le_top, le_top⟩, .. prod.partial_order α β, .. prod.has_top α β } instance [order_bot α] [order_bot β] : order_bot (α × β) := { bot_le := assume a, ⟨bot_le, bot_le⟩, .. prod.partial_order α β, .. prod.has_bot α β } instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) := { .. prod.semilattice_sup α β, .. prod.order_top α β } instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) := { .. prod.semilattice_inf α β, .. prod.order_top α β } instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) := { .. prod.semilattice_sup α β, .. prod.order_bot α β } instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) := { .. prod.semilattice_inf α β, .. prod.order_bot α β } instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) := { .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β } instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] : bounded_distrib_lattice (α × β) := { .. prod.bounded_lattice α β, .. prod.distrib_lattice α β } end prod section disjoint section semilattice_inf_bot variable [semilattice_inf_bot α] /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥ theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ := eq_bot_iff.2 h theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ := eq_bot_iff.symm theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a := by rw [disjoint, disjoint, inf_comm] @[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a := disjoint.comm.1 @[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := inf_le_left @[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := inf_le_right theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂) theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c := disjoint.mono h (le_refl _) theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b := disjoint.mono (le_refl _) h @[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ := by simp [disjoint] lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b := by { intro h, rw [←h, disjoint_self] at hab, exact ha hab } end semilattice_inf_bot section bounded_lattice variables [bounded_lattice α] {a : α} @[simp] theorem disjoint_top : disjoint a ⊤ ↔ a = ⊥ := by simp [disjoint_iff] @[simp] theorem top_disjoint : disjoint ⊤ a ↔ a = ⊥ := by simp [disjoint_iff] end bounded_lattice section bounded_distrib_lattice variables [bounded_distrib_lattice α] {a b c : α} @[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c := by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff] @[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c := by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff] lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c := disjoint_sup_left.2 ⟨ha, hb⟩ lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) := disjoint_sup_right.2 ⟨hb, hc⟩ lemma disjoint.left_le_of_le_sup_right {a b c : α} (h : a ≤ b ⊔ c) (hd : disjoint a c) : a ≤ b := (λ x, le_of_inf_le_sup_le x (sup_le h le_sup_right)) ((disjoint_iff.mp hd).symm ▸ bot_le) lemma disjoint.left_le_of_le_sup_left {a b c : α} (h : a ≤ c ⊔ b) (hd : disjoint a c) : a ≤ b := @le_of_inf_le_sup_le _ _ a b c ((disjoint_iff.mp hd).symm ▸ bot_le) ((@sup_comm _ _ c b) ▸ (sup_le h le_sup_left)) end bounded_distrib_lattice end disjoint section is_compl /-! ### `is_compl` predicate -/ /-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/ structure is_compl [bounded_lattice α] (x y : α) : Prop := (inf_le_bot : x ⊓ y ≤ ⊥) (top_le_sup : ⊤ ≤ x ⊔ y) namespace is_compl section bounded_lattice variables [bounded_lattice α] {x y z : α} protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1 @[symm] protected lemma symm (h : is_compl x y) : is_compl y x := ⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩ lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y := ⟨le_of_eq h₁, le_of_eq h₂.symm⟩ lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩ end bounded_lattice variables [bounded_distrib_lattice α] {x y z : α} lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y := ⟨λ hz, h.disjoint.mono_left hz, λ hz, le_of_inf_le_sup_le (le_trans hz bot_le) (le_trans le_top h.top_le_sup)⟩ lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x := h.symm.le_left_iff lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y := h.to_order_dual.le_left_iff lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x := h.symm.left_le_iff lemma antimono {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') : y' ≤ y := h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _) lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) : y = z := le_antisymm (hxz.antimono hxy $ le_refl x) (hxy.antimono hxz $ le_refl x) lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) : x = y := hxz.symm.right_unique hyz.symm lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊔ x') (y ⊓ y') := of_eq (by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm, h'.inf_eq_bot, inf_bot_eq]) (by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq, sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq]) lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊓ x') (y ⊔ y') := (h.symm.sup_inf h'.symm).symm lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z := inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y := h.symm.inf_left_eq_bot_iff lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z := disjoint_iff.trans h.inf_left_eq_bot_iff lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y := h.symm.disjoint_left_iff end is_compl lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ := is_compl.of_eq bot_inf_eq sup_top_eq lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ := is_compl.of_eq inf_bot_eq top_sup_eq end is_compl section nontrivial variables [bounded_lattice α] [nontrivial α] lemma bot_ne_top : (⊥ : α) ≠ ⊤ := λ H, not_nontrivial_iff_subsingleton.mpr (subsingleton_of_bot_eq_top H) ‹_› lemma top_ne_bot : (⊤ : α) ≠ ⊥ := ne.symm bot_ne_top end nontrivial
fc6278abdb1614f280eb9cd10192b479723edd2b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/set_theory/game/winner.lean
5dbd1cd012b5e86bb384da49e91aff92b281380a
[]
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
3,445
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.set_theory.pgame import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Basic definitions about who has a winning stratergy We define `G.first_loses`, `G.first_wins`, `G.left_wins` and `G.right_wins` for a pgame `G`, which means the second, first, left and right players have a winning strategy respectively. These are defined by inequalities which can be unfolded with `pgame.lt_def` and `pgame.le_def`. -/ namespace pgame /-- The player who goes first loses -/ def first_loses (G : pgame) := G ≤ 0 ∧ 0 ≤ G /-- The player who goes first wins -/ def first_wins (G : pgame) := 0 < G ∧ G < 0 /-- The left player can always win -/ def left_wins (G : pgame) := 0 < G ∧ 0 ≤ G /-- The right player can always win -/ def right_wins (G : pgame) := G ≤ 0 ∧ G < 0 theorem zero_first_loses : first_loses 0 := { left := le_refl 0, right := le_refl 0 } theorem one_left_wins : left_wins 1 := sorry theorem star_first_wins : first_wins star := { left := zero_lt_star, right := star_lt_zero } theorem omega_left_wins : left_wins omega := sorry theorem winner_cases (G : pgame) : left_wins G ∨ right_wins G ∨ first_loses G ∨ first_wins G := sorry theorem first_loses_is_zero {G : pgame} : first_loses G ↔ equiv G 0 := iff.refl (first_loses G) theorem first_loses_of_equiv {G : pgame} {H : pgame} (h : equiv G H) : first_loses G → first_loses H := fun (hGp : first_loses G) => { left := le_of_equiv_of_le (and.symm h) (and.left hGp), right := le_of_le_of_equiv (and.right hGp) h } theorem first_wins_of_equiv {G : pgame} {H : pgame} (h : equiv G H) : first_wins G → first_wins H := fun (hGn : first_wins G) => { left := lt_of_lt_of_equiv (and.left hGn) h, right := lt_of_equiv_of_lt (and.symm h) (and.right hGn) } theorem left_wins_of_equiv {G : pgame} {H : pgame} (h : equiv G H) : left_wins G → left_wins H := fun (hGl : left_wins G) => { left := lt_of_lt_of_equiv (and.left hGl) h, right := le_of_le_of_equiv (and.right hGl) h } theorem right_wins_of_equiv {G : pgame} {H : pgame} (h : equiv G H) : right_wins G → right_wins H := fun (hGr : right_wins G) => { left := le_of_equiv_of_le (and.symm h) (and.left hGr), right := lt_of_equiv_of_lt (and.symm h) (and.right hGr) } theorem first_loses_of_equiv_iff {G : pgame} {H : pgame} (h : equiv G H) : first_loses G ↔ first_loses H := { mp := first_loses_of_equiv h, mpr := first_loses_of_equiv (and.symm h) } theorem first_wins_of_equiv_iff {G : pgame} {H : pgame} (h : equiv G H) : first_wins G ↔ first_wins H := { mp := first_wins_of_equiv h, mpr := first_wins_of_equiv (and.symm h) } theorem left_wins_of_equiv_iff {G : pgame} {H : pgame} (h : equiv G H) : left_wins G ↔ left_wins H := { mp := left_wins_of_equiv h, mpr := left_wins_of_equiv (and.symm h) } theorem right_wins_of_equiv_iff {G : pgame} {H : pgame} (h : equiv G H) : right_wins G ↔ right_wins H := { mp := right_wins_of_equiv h, mpr := right_wins_of_equiv (and.symm h) } theorem not_first_wins_of_first_loses {G : pgame} : first_loses G → ¬first_wins G := sorry theorem not_first_loses_of_first_wins {G : pgame} : first_wins G → ¬first_loses G := iff.mp imp_not_comm not_first_wins_of_first_loses
d0b008be36949968b52ae13e92b685718ea37be0
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/filter/cofinite.lean
d126c43dd9446250a5593808219929173e414ec1
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
6,727
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov -/ import order.filter.at_top_bot import order.filter.pi /-! # The cofinite filter In this file we define `cofinite`: the filter of sets with finite complement and prove its basic properties. In particular, we prove that for `ℕ` it is equal to `at_top`. ## TODO Define filters for other cardinalities of the complement. -/ open set open_locale classical variables {α : Type*} namespace filter /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite : filter α := { sets := {s | finite sᶜ}, univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq], sets_of_superset := assume s t (hs : finite sᶜ) (st: s ⊆ t), hs.subset $ compl_subset_compl.2 st, inter_sets := assume s t (hs : finite sᶜ) (ht : finite (tᶜ)), by simp only [compl_inter, finite.union, ht, hs, mem_set_of_eq] } @[simp] lemma mem_cofinite {s : set α} : s ∈ (@cofinite α) ↔ finite sᶜ := iff.rfl @[simp] lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in cofinite, p x) ↔ finite {x | ¬p x} := iff.rfl lemma has_basis_cofinite : has_basis cofinite (λ s : set α, s.finite) compl := ⟨λ s, ⟨λ h, ⟨sᶜ, h, (compl_compl s).subset⟩, λ ⟨t, htf, hts⟩, htf.subset $ compl_subset_comm.2 hts⟩⟩ instance cofinite_ne_bot [infinite α] : ne_bot (@cofinite α) := has_basis_cofinite.ne_bot_iff.2 $ λ s hs, hs.infinite_compl.nonempty lemma frequently_cofinite_iff_infinite {p : α → Prop} : (∃ᶠ x in cofinite, p x) ↔ set.infinite {x | p x} := by simp only [filter.frequently, filter.eventually, mem_cofinite, compl_set_of, not_not, set.infinite] /-- The coproduct of the cofinite filters on two types is the cofinite filter on their product. -/ lemma coprod_cofinite {β : Type*} : (cofinite : filter α).coprod (cofinite : filter β) = cofinite := begin ext S, simp only [mem_coprod_iff, exists_prop, mem_comap, mem_cofinite], split, { rintro ⟨⟨A, hAf, hAS⟩, B, hBf, hBS⟩, rw [← compl_subset_compl, ← preimage_compl] at hAS hBS, exact (hAf.prod hBf).subset (subset_inter hAS hBS) }, { intro hS, refine ⟨⟨(prod.fst '' Sᶜ)ᶜ, _, _⟩, ⟨(prod.snd '' Sᶜ)ᶜ, _, _⟩⟩, { simpa using hS.image prod.fst }, { simpa [compl_subset_comm] using subset_preimage_image prod.fst Sᶜ }, { simpa using hS.image prod.snd }, { simpa [compl_subset_comm] using subset_preimage_image prod.snd Sᶜ } }, end /-- Finite product of finite sets is finite -/ lemma Coprod_cofinite {δ : Type*} {κ : δ → Type*} [fintype δ] : filter.Coprod (λ d, (cofinite : filter (κ d))) = cofinite := begin ext S, rcases compl_surjective S with ⟨S, rfl⟩, simp_rw [compl_mem_Coprod_iff, mem_cofinite, compl_compl], split, { rintro ⟨t, htf, hsub⟩, exact (finite.pi htf).subset hsub }, { exact λ hS, ⟨λ i, function.eval i '' S, λ i, hS.image _, subset_pi_eval_image _ _⟩ } end end filter open filter lemma set.finite.compl_mem_cofinite {s : set α} (hs : s.finite) : sᶜ ∈ (@cofinite α) := mem_cofinite.2 $ (compl_compl s).symm ▸ hs lemma set.finite.eventually_cofinite_nmem {s : set α} (hs : s.finite) : ∀ᶠ x in cofinite, x ∉ s := hs.compl_mem_cofinite lemma finset.eventually_cofinite_nmem (s : finset α) : ∀ᶠ x in cofinite, x ∉ s := s.finite_to_set.eventually_cofinite_nmem lemma set.infinite_iff_frequently_cofinite {s : set α} : set.infinite s ↔ (∃ᶠ x in cofinite, x ∈ s) := frequently_cofinite_iff_infinite.symm lemma filter.eventually_cofinite_ne (x : α) : ∀ᶠ a in cofinite, a ≠ x := (set.finite_singleton x).eventually_cofinite_nmem /-- For natural numbers the filters `cofinite` and `at_top` coincide. -/ lemma nat.cofinite_eq_at_top : @cofinite ℕ = at_top := begin ext s, simp only [mem_cofinite, mem_at_top_sets], split, { assume hs, use (hs.to_finset.sup id) + 1, assume b hb, by_contradiction hbs, have := hs.to_finset.subset_range_sup_succ (hs.mem_to_finset.2 hbs), exact not_lt_of_le hb (finset.mem_range.1 this) }, { rintros ⟨N, hN⟩, apply (finite_lt_nat N).subset, assume n hn, change n < N, exact lt_of_not_ge (λ hn', hn $ hN n hn') } end lemma nat.frequently_at_top_iff_infinite {p : ℕ → Prop} : (∃ᶠ n in at_top, p n) ↔ set.infinite {n | p n} := by simp only [← nat.cofinite_eq_at_top, frequently_cofinite_iff_infinite] lemma filter.tendsto.exists_within_forall_le {α β : Type*} [linear_order β] {s : set α} (hs : s.nonempty) {f : α → β} (hf : filter.tendsto f filter.cofinite filter.at_top) : ∃ a₀ ∈ s, ∀ a ∈ s, f a₀ ≤ f a := begin rcases em (∃ y ∈ s, ∃ x, f y < x) with ⟨y, hys, x, hx⟩|not_all_top, { -- the set of points `{y | f y < x}` is nonempty and finite, so we take `min` over this set have : finite {y | ¬x ≤ f y} := (filter.eventually_cofinite.mp (tendsto_at_top.1 hf x)), simp only [not_le] at this, obtain ⟨a₀, ⟨ha₀ : f a₀ < x, ha₀s⟩, others_bigger⟩ := exists_min_image _ f (this.inter_of_left s) ⟨y, hx, hys⟩, refine ⟨a₀, ha₀s, λ a has, (lt_or_le (f a) x).elim _ (le_trans ha₀.le)⟩, exact λ h, others_bigger a ⟨h, has⟩ }, { -- in this case, f is constant because all values are at top push_neg at not_all_top, obtain ⟨a₀, ha₀s⟩ := hs, exact ⟨a₀, ha₀s, λ a ha, not_all_top a ha (f a₀)⟩ } end lemma filter.tendsto.exists_forall_le {α β : Type*} [nonempty α] [linear_order β] {f : α → β} (hf : tendsto f cofinite at_top) : ∃ a₀, ∀ a, f a₀ ≤ f a := let ⟨a₀, _, ha₀⟩ := hf.exists_within_forall_le univ_nonempty in ⟨a₀, λ a, ha₀ a (mem_univ _)⟩ lemma filter.tendsto.exists_within_forall_ge {α β : Type*} [linear_order β] {s : set α} (hs : s.nonempty) {f : α → β} (hf : filter.tendsto f filter.cofinite filter.at_bot) : ∃ a₀ ∈ s, ∀ a ∈ s, f a ≤ f a₀ := @filter.tendsto.exists_within_forall_le _ (order_dual β) _ _ hs _ hf lemma filter.tendsto.exists_forall_ge {α β : Type*} [nonempty α] [linear_order β] {f : α → β} (hf : tendsto f cofinite at_bot) : ∃ a₀, ∀ a, f a ≤ f a₀ := @filter.tendsto.exists_forall_le _ (order_dual β) _ _ _ hf /-- For an injective function `f`, inverse images of finite sets are finite. -/ lemma function.injective.tendsto_cofinite {α β : Type*} {f : α → β} (hf : function.injective f) : tendsto f cofinite cofinite := λ s h, h.preimage (hf.inj_on _)
8cb3fce69befa7dbff79171587b2e54926a3e8bb
0e175f34f8dca5ea099671777e8d7446d7d74227
/library/init/meta/type_context.lean
4598f38ad649003452806c84272796426620fa79
[ "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,605
lean
prelude import init.control init.meta.local_context init.meta.tactic init.meta.fun_info namespace tactic.unsafe /-- A monad that exposes the functionality of the C++ class `type_context_old`. The idea is that the methods to `type_context` are more powerful but _unsafe_ in the sense that you can create terms that do not typecheck or that are infinitely descending. Under the hood, `type_context` is implemented as a reader monad, with a mutable `type_context` object. -/ meta constant type_context : Type → Type namespace type_context variables {α β : Type} protected meta constant bind : type_context α → (α → type_context β) → type_context β protected meta constant pure : α → type_context α protected meta constant fail : format → type_context α protected meta def failure : type_context α := type_context.fail "" meta instance : monad type_context := {bind := @type_context.bind, pure := @type_context.pure} meta instance : monad_fail type_context := {fail := λ α, type_context.fail ∘ to_fmt} meta constant get_env : type_context environment meta constant whnf : expr → type_context expr meta constant is_def_eq (e₁ e₂ : expr) (approx := ff) : type_context bool meta constant unify (e₁ e₂ : expr) (approx := ff) : type_context bool /-- Infer the type of the given expr. Inferring the type does not mean that it typechecks. Will fail if type can't be inferred. -/ meta constant infer : expr → type_context expr /-- A stuck expression `e` is an expression that _would_ reduce, except that a metavariable is present that prevents the reduction. Returns the metavariable which is causing the stuckage. For example, `@has_add.add nat ?m a b` can't project because `?m` is not given. -/ meta constant is_stuck : expr → type_context (option expr) /-- Add a local to the tc local context. -/ meta constant push_local (pp_name : name) (type : expr) (bi := binder_info.default) : type_context expr meta constant pop_local : type_context unit /-- Get the local context of the type_context. -/ meta constant get_local_context : type_context local_context /-- Create and declare a new metavariable. If the local context is not given then it will use the current local context. -/ meta constant mk_mvar (pp_name : name) (type : expr) (context : option local_context := none) : type_context expr /-- Iterate over all mvars in the mvar context. -/ meta constant fold_mvars {α : Type} (f : α → expr → type_context α) : α → type_context α meta def list_mvars : type_context (list expr) := fold_mvars (λ l x, pure $ x :: l) [] /-- Set the mvar to the following assignments. Works for temporary metas too. [WARNING] `assign` does not perform certain checks: - No typecheck is done before assignment. - If the metavariable is already assigned this will clobber the assignment. - It will not stop you from assigning an metavariable to itself or creating cycles of metavariable assignments. These will manifest as 'deep recursion' exceptions when `instantiate_mvars` is used. - It is not checked whether the assignment uses local constants outside the declaration's context. You can avoid the unsafety by using `unify` instead. -/ meta constant assign (mvar : expr) (assignment : expr) : type_context unit /-- Assigns a given level metavariable. -/ meta constant level.assign (mvar : level) (assignment : level) : type_context unit /-- Returns true if the given expression is a declared local constant or a declared metavariable. -/ meta constant is_declared (e : expr) : type_context bool meta constant is_assigned (mvar : expr) : type_context bool /-- Given a metavariable, returns the local context that the metavariable was declared with. -/ meta constant get_context (mvar : expr) : type_context local_context /-- Get the expression that is assigned to the given mvar expression. Fails if given a -/ meta constant get_assignment (mvar : expr) : type_context expr meta constant instantiate_mvars : expr → type_context expr meta constant level.instantiate_mvars : level → type_context level meta constant is_tmp_mvar (mvar : expr) : type_context bool meta constant is_regular_mvar (mvar : expr) : type_context bool /-- Run the given `type_context` monad in a temporary mvar scope. Doing this twice will push the old tmp_mvar assignments to a stack. So it is safe to do this whether or not you are already in tmp mode. -/ meta constant tmp_mode (n_uvars n_mvars : nat) : type_context α → type_context α /-- Returns true when in temp mode. -/ meta constant in_tmp_mode : type_context bool meta constant tmp_is_assigned : nat → type_context bool meta constant tmp_get_assignment : nat → type_context expr meta constant level.tmp_is_assigned : nat → type_context bool meta constant level.tmp_get_assignment : nat → type_context level /-- Replace each metavariable in the given expression with a temporary metavariable. -/ meta constant to_tmp_mvars : expr → type_context (expr × list level × list expr) meta constant mk_tmp_mvar (index : nat) (type : expr): expr meta constant level.mk_tmp_mvar (index : nat) : level /-- Run the provided type_context within a backtracking scope. This means that any changes to the metavariable context will not be committed if the inner monad fails. [warning]: the local context modified by `push_local` and `pop_local` is not affected by `try`. Any unpopped locals will be present after the `try` even if the inner `type_context` failed. -/ meta constant try {α : Type} : type_context α → type_context (option α) meta def orelse {α : Type} : type_context α → type_context α → type_context α | x y := try x >>= λ x, option.rec y pure x meta instance type_context_alternative : alternative type_context := { failure := λ α, type_context.fail "failed", orelse := λ α x y, type_context.orelse x y } /-- Runs the given type_context monad using the type context of the current tactic state. You can use this to perform unsafe operations such as direct metavariable assignment and the use of temporary metavariables. -/ meta constant run (inner : type_context α) (tr := tactic.transparency.semireducible) : tactic α meta def trace {α} [has_to_format α] : α → type_context unit | a := pure $ _root_.trace_fmt (to_fmt a) (λ u, ()) meta def print_mvars : type_context unit := do mvs ← list_mvars, mvs ← pure $ mvs.map (λ x, match x with (expr.mvar _ pp _) := to_fmt pp | _ := "" end), trace mvs /-- Same as tactic.get_fun_info -/ meta constant get_fun_info (f : expr) (nargs : option nat := none) : type_context fun_info end type_context end tactic.unsafe
af929dc5682f4bd81f5d55b1923894440794aae5
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Compiler/NeverExtractAttr.lean
9a185da07451e7e6971315270bf898508179372c
[ "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
806
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Environment import Lean.Attributes namespace Lean builtin_initialize neverExtractAttr : TagAttribute ← registerTagAttribute `neverExtract "instruct the compiler that function applications using the tagged declaration should not be extracted when they are closed terms, nor common subexpression should be performed. This is useful for declarations that have implicit effects." @[export lean_has_never_extract_attribute] partial def hasNeverExtractAttribute (env : Environment) (n : Name) : Bool := let rec visit (n : Name) : Bool := neverExtractAttr.hasTag env n || (n.isInternal && visit n.getPrefix) visit n end Lean
8cd5554963e89bc039900222517f5af272b1806b
2d34dfb0a1cc250584282618dc10ea03d3fa858e
/src/by_exactI_hack.lean
6bc7306d4c839abfae616b58b80ddacda2350be6
[]
no_license
zeta1999/lean-liquid
61e294ec5adae959d8ee1b65d015775484ff58c2
96bb0fa3afc3b451bcd1fb7d974348de2f290541
refs/heads/master
1,676,579,150,248
1,610,771,445,000
1,610,771,445,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
556
lean
-- brilliant hack by Gabriel Ebner -- thanks!! open tactic expr open lean open lean.parser open interactive open tactic reserve prefix `​ `:100 -- zero-width space Unicode char @[user_notation] meta def exact_notation (_ : parse $ tk "​") (e : parse (lean.parser.pexpr 0)) : parser pexpr := do expr.macro d [_] ← pure ``(by skip), pure $ expr.macro d [const `tactic.interactive.exactI [] (cast undefined e.reflect)] -- files that import this file can use the zero-width space char -- to reset the TC instance cache, and avoid `by exactI` kludges
22b364394bf29261d6362e422cdf51251de87bd0
7a76361040c55ae1eba5856c1a637593117a6556
/src/exercises/love04_functional_programming_exercise_solution.lean
b3579dd991652972f0bcb98424b2a3b94f17efa3
[]
no_license
rgreenblatt/fpv2021
c2cbe7b664b648cef7d240a654d6bdf97a559272
c65d72e48c8fa827d2040ed6ea86c2be62db36fa
refs/heads/main
1,692,245,693,819
1,633,364,621,000
1,633,364,621,000
407,231,487
0
0
null
1,631,808,608,000
1,631,808,608,000
null
UTF-8
Lean
false
false
7,192
lean
import ..lectures.love03_forward_proofs_demo /-! # LoVe Exercise 4: Functional Programming -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /-! ## Question 1: Reverse of a List We define a new accumulator-based version of `reverse`. The first argument, `as`, serves as the accumulator. This definition is __tail-recursive__, meaning that compilers and interpreters can easily optimize the recursion away, resulting in more efficient code. -/ def accurev {α : Type} : list α → list α → list α | as [] := as | as (x :: xs) := accurev (x :: as) xs /-! 1.1. Our intention is that `accurev [] xs` should be equal to `reverse xs`. But if we start an induction, we quickly see that the induction hypothesis is not strong enough. Start by proving the following generalization (using the `induction'` tactic or pattern matching): -/ lemma accurev_eq_reverse_append {α : Type} : ∀as xs : list α, accurev as xs = reverse xs ++ as | as [] := by refl | as (x :: xs) := by simp [reverse, accurev, accurev_eq_reverse_append _ xs] /-! 1.2. Derive the desired equation. -/ lemma accurev_eq_reverse {α : Type} (xs : list α) : accurev [] xs = reverse xs := by simp [accurev_eq_reverse_append] /-! 1.3. Prove the following property. Hint: A one-line inductionless proof is possible. -/ lemma accurev_accurev {α : Type} (xs : list α) : accurev [] (accurev [] xs) = xs := by simp [accurev_eq_reverse, reverse_reverse] /-! 1.4. Prove the following lemma by structural induction, as a "paper" proof. This is a good exercise to develop a deeper understanding of how structural induction works (and is good practice for the final exam). lemma accurev_eq_reverse_append {α : Type} : ∀as xs : list α, accurev as xs = reverse xs ++ as Guidelines for paper proofs: We expect detailed, rigorous, mathematical proofs. You are welcome to use standard mathematical notation or Lean structured commands (e.g., `assume`, `have`, `show`, `calc`). You can also use tactical proofs (e.g., `intro`, `apply`), but then please indicate some of the intermediate goals, so that we can follow the chain of reasoning. Major proof steps, including applications of induction and invocation of the induction hypothesis, must be stated explicitly. For each case of a proof by induction, you must list the inductive hypotheses assumed (if any) and the goal to be proved. Minor proof steps corresponding to `refl`, `simp`, or `cc` need not be justified if you think they are obvious (to humans), but you should say which key lemmas they depend on. You should be explicit whenever you use a function definition or an introduction rule for an inductive predicate. -/ /-! We perform the proof by structural induction on `xs` (generalizing `as`). Case `[]`: The goal is `accurev as [] = reverse [] ++ as`. The left-hand side is `as` by definition of `accurev`. The right-hand side is `as` by definition of `reverse` and `++`. Case `x :: xs`: The goal is `accurev as (x :: xs) = reverse (x :: xs) ++ as`. The induction hypothesis is `∀as, accurev as xs = reverse xs ++ as`. Let us simplify the goal's left-hand side: accurev as (x :: xs) = accurev (x :: as) xs -- by definition of `accurev` = reverse xs ++ (x :: as) -- by the induction hypothesis Now let us massage the right-hand side so that it matches the simplified left-hand side: reverse (x :: xs) ++ as = (reverse xs ++ [x]) ++ as -- by definition of `reverse` = reverse xs ++ ([x] ++ as) -- by associativity of `++` = reverse xs ++ (x :: as) -- by definition of `++` The two sides are equal. QED -/ /-! ## Question 2: Drop and Take The `drop` function removes the first `n` elements from the front of a list. -/ def drop {α : Type} : ℕ → list α → list α | 0 xs := xs | (_ + 1) [] := [] | (m + 1) (x :: xs) := drop m xs /-! 2.1. Define the `take` function, which returns a list consisting of the the first `n` elements at the front of a list. To avoid unpleasant surprises in the proofs, we recommend that you follow the same recursion pattern as for `drop` above. -/ def take {α : Type} : ℕ → list α → list α | 0 _ := [] | (_ + 1) [] := [] | (m + 1) (x :: xs) := x :: take m xs #eval take 0 [3, 7, 11] -- expected: [] #eval take 1 [3, 7, 11] -- expected: [3] #eval take 2 [3, 7, 11] -- expected: [3, 7] #eval take 3 [3, 7, 11] -- expected: [3, 7, 11] #eval take 4 [3, 7, 11] -- expected: [3, 7, 11] #eval take 2 ["a", "b", "c"] -- expected: ["a", "b"] /-! 2.2. Prove the following lemmas, using `induction'` or pattern matching. Notice that they are registered as simplification rules thanks to the `@[simp]` attribute. -/ @[simp] lemma drop_nil {α : Type} : ∀n : ℕ, drop n ([] : list α) = [] | 0 := by refl | (_ + 1) := by refl @[simp] lemma take_nil {α : Type} : ∀n : ℕ, take n ([] : list α) = [] | 0 := by refl | (_ + 1) := by refl /-! 2.3. Follow the recursion pattern of `drop` and `take` to prove the following lemmas. In other words, for each lemma, there should be three cases, and the third case will need to invoke the induction hypothesis. Hint: Note that there are three variables in the `drop_drop` lemma (but only two arguments to `drop`). For the third case, `←add_assoc` might be useful. -/ lemma drop_drop {α : Type} : ∀(m n : ℕ) (xs : list α), drop n (drop m xs) = drop (n + m) xs | 0 n xs := by refl | (_ + 1) _ [] := by simp [drop] | (m + 1) n (x :: xs) := by simp [drop, drop_drop m n xs, ←add_assoc] lemma take_take {α : Type} : ∀(m : ℕ) (xs : list α), take m (take m xs) = take m xs | 0 _ := by refl | (_ + 1) [] := by refl | (m + 1) (x :: xs) := by simp [take, take_take m xs] lemma take_drop {α : Type} : ∀(n : ℕ) (xs : list α), take n xs ++ drop n xs = xs | 0 _ := by refl | (_ + 1) [] := by refl | (m + 1) (x :: xs) := by simp [take, drop, take_drop m] /-! ## Question 3: A Type of λ-Terms 3.1. Define an inductive type corresponding to the untyped λ-terms, as given by the following context-free grammar: term ::= 'var' string -- variable (e.g., `x`) | 'lam' string term -- λ-expression (e.g., `λx, t`) | 'app' term term -- application (e.g., `t u`) -/ inductive term : Type | var : string → term | lam : string → term → term | app : term → term → term /-! 3.2. Register a textual representation of the type `term` as an instance of the `has_repr` type class. Make sure to supply enough parentheses to guarantee that the output is unambiguous. -/ def term.repr : term → string | (term.var s) := s | (term.lam s t) := "(λ" ++ s ++ ", " ++ term.repr t ++ ")" | (term.app t u) := "(" ++ term.repr t ++ " " ++ term.repr u ++ ")" @[instance] def term.has_repr : has_repr term := { repr := term.repr } /-! 3.3. Test your textual representation. The following command should print something like `(λx, ((y x) x))`. -/ #eval (term.lam "x" (term.app (term.app (term.var "y") (term.var "x")) (term.var "x"))) end LoVe
cec9972cda7bea695a8b376361515f974794bc67
80746c6dba6a866de5431094bf9f8f841b043d77
/src/analysis/exponential.lean
8af0e806ed7713e1446fac39bb2fe110b93dd744
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
51,360
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import topology.instances.complex tactic.linarith data.complex.exponential open finset filter metric namespace complex lemma tendsto_exp_zero_one : tendsto exp (nhds 0) (nhds 1) := tendsto_nhds_nhds.2 $ λ ε ε0, ⟨min (ε / 2) 1, lt_min (div_pos ε0 (by norm_num)) (by norm_num), λ x h, have h : abs x < min (ε / 2) 1, by simpa [dist_eq] using h, calc abs (exp x - 1) ≤ 2 * abs x : abs_exp_sub_one_le (le_trans (le_of_lt h) (min_le_right _ _)) ... = abs x + abs x : two_mul (abs x) ... < ε / 2 + ε / 2 : add_lt_add (lt_of_lt_of_le h (min_le_left _ _)) (lt_of_lt_of_le h (min_le_left _ _)) ... = ε : by rw add_halves⟩ lemma continuous_exp : continuous exp := continuous_iff_tendsto.2 (λ x, have H1 : tendsto (λ h, exp (x + h)) (nhds 0) (nhds (exp x)), by simpa [exp_add] using tendsto_mul tendsto_const_nhds tendsto_exp_zero_one, have H2 : tendsto (λ y, y - x) (nhds x) (nhds (x - x)) := tendsto_sub tendsto_id (@tendsto_const_nhds _ _ _ x _), suffices tendsto ((λ h, exp (x + h)) ∘ (λ y, id y - (λ z, x) y)) (nhds x) (nhds (exp x)), by simp only [function.comp, add_sub_cancel'_right, id.def] at this; exact this, tendsto.comp (by rw [sub_self] at H2; exact H2) H1) lemma continuous_sin : continuous sin := continuous_mul (continuous_mul (continuous_sub ((continuous_mul continuous_neg' continuous_const).comp continuous_exp) ((continuous_mul continuous_id continuous_const).comp continuous_exp)) continuous_const) continuous_const lemma continuous_cos : continuous cos := continuous_mul (continuous_add ((continuous_mul continuous_id continuous_const).comp continuous_exp) ((continuous_mul continuous_neg' continuous_const).comp continuous_exp)) continuous_const lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := continuous_mul (continuous_subtype_val.comp continuous_sin) (continuous_inv subtype.property (continuous_subtype_val.comp continuous_cos)) lemma continuous_sinh : continuous sinh := continuous_mul (continuous_sub continuous_exp (continuous_neg'.comp continuous_exp)) continuous_const lemma continuous_cosh : continuous cosh := continuous_mul (continuous_add continuous_exp (continuous_neg'.comp continuous_exp)) continuous_const end complex namespace real lemma continuous_exp : continuous exp := (complex.continuous_of_real.comp complex.continuous_exp).comp complex.continuous_re lemma continuous_sin : continuous sin := (complex.continuous_of_real.comp complex.continuous_sin).comp complex.continuous_re lemma continuous_cos : continuous cos := (complex.continuous_of_real.comp complex.continuous_cos).comp complex.continuous_re lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := by simp only [tan_eq_sin_div_cos]; exact continuous_mul (continuous_subtype_val.comp continuous_sin) (continuous_inv subtype.property (continuous_subtype_val.comp continuous_cos)) lemma continuous_sinh : continuous sinh := (complex.continuous_of_real.comp complex.continuous_sinh).comp complex.continuous_re lemma continuous_cosh : continuous cosh := (complex.continuous_of_real.comp complex.continuous_cosh).comp complex.continuous_re private lemma exists_exp_eq_of_one_le {x : ℝ} (hx : 1 ≤ x) : ∃ y, exp y = x := let ⟨y, hy⟩ := @intermediate_value real.exp 0 (x - 1) x (λ _ _ _, continuous_iff_tendsto.1 continuous_exp _) (by simpa) (by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hx)) (sub_nonneg.2 hx) in ⟨y, hy.2.2⟩ lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x := match le_total x 1 with | (or.inl hx1) := let ⟨y, hy⟩ := exists_exp_eq_of_one_le (one_le_inv hx hx1) in ⟨-y, by rw [exp_neg, hy, inv_inv']⟩ | (or.inr hx1) := exists_exp_eq_of_one_le hx1 end noncomputable def log (x : ℝ) : ℝ := if hx : 0 < x then classical.some (exists_exp_eq_of_pos hx) else 0 lemma exp_log {x : ℝ} (hx : 0 < x) : exp (log x) = x := by rw [log, dif_pos hx]; exact classical.some_spec (exists_exp_eq_of_pos hx) @[simp] lemma log_exp (x : ℝ) : log (exp x) = x := exp_injective $ exp_log (exp_pos x) @[simp] lemma log_zero : log 0 = 0 := by simp [log, lt_irrefl] @[simp] lemma log_one : log 1 = 0 := exp_injective $ by rw [exp_log zero_lt_one, exp_zero] lemma log_mul {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : log (x * y) = log x + log y := exp_injective $ by rw [exp_log (mul_pos hx hy), exp_add, exp_log hx, exp_log hy] lemma exists_cos_eq_zero : ∃ x, 1 ≤ x ∧ x ≤ 2 ∧ cos x = 0 := real.intermediate_value' (λ x _ _, continuous_iff_tendsto.1 continuous_cos _) (le_of_lt cos_one_pos) (le_of_lt cos_two_neg) (by norm_num) noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero local notation `π` := pi @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2.2 lemma one_le_pi_div_two : (1 : ℝ) ≤ π / 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1 lemma pi_div_two_le_two : π / 2 ≤ 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2.1 lemma two_le_pi : (2 : ℝ) ≤ π := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (by rw div_self (@two_ne_zero' ℝ _ _ _); exact one_le_pi_div_two) lemma pi_le_four : π ≤ 4 := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (calc π / 2 ≤ 2 : pi_div_two_le_two ... = 4 / 2 : by norm_num) lemma pi_pos : 0 < π := lt_of_lt_of_le (by norm_num) two_le_pi lemma pi_div_two_pos : 0 < π / 2 := half_pos pi_pos lemma two_pi_pos : 0 < 2 * π := by linarith using [pi_pos] @[simp] lemma sin_pi : sin π = 0 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), two_mul, add_div, sin_add, cos_pi_div_two]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), mul_div_assoc, cos_two_mul, cos_pi_div_two]; simp [bit0, pow_add] @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [cos_add] lemma sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < π) : 0 < sin x := if hx2 : x ≤ 2 then sin_pos_of_pos_of_le_two h0x hx2 else have (2 : ℝ) + 2 = 4, from rfl, have π - x ≤ 2, from sub_le_iff_le_add.2 (le_trans pi_le_four (this ▸ add_le_add_left (le_of_not_ge hx2) _)), sin_pi_sub x ▸ sin_pos_of_pos_of_le_two (sub_pos.2 hxp) this lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x := match lt_or_eq_of_le h0x with | or.inl h0x := (lt_or_eq_of_le hxp).elim (le_of_lt ∘ sin_pos_of_pos_of_lt_pi h0x) (λ hpx, by simp [hpx]) | or.inr h0x := by simp [h0x.symm] end lemma sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -π < x) : sin x < 0 := neg_pos.1 $ sin_neg x ▸ sin_pos_of_pos_of_lt_pi (neg_pos.2 hx0) (neg_lt.1 hpx) lemma sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -π ≤ x) : sin x ≤ 0 := neg_nonneg.1 $ sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (neg_nonneg.2 hx0) (neg_le.1 hpx) @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := have sin (π / 2) = 1 ∨ sin (π / 2) = -1 := by simpa [pow_two, mul_self_eq_one_iff] using sin_pow_two_add_cos_pow_two (π / 2), this.resolve_right (λ h, (show ¬(0 : ℝ) < -1, by norm_num) $ h ▸ sin_pos_of_pos_of_lt_pi pi_div_two_pos (half_lt_self pi_pos)) lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : 0 < cos x := sin_add_pi_div_two x ▸ sin_pos_of_pos_of_lt_pi (by linarith) (by linarith) lemma cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : 0 ≤ cos x := match lt_or_eq_of_le hx₁, lt_or_eq_of_le hx₂ with | or.inl hx₁, or.inl hx₂ := le_of_lt (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two hx₁ hx₂) | or.inl hx₁, or.inr hx₂ := by simp [hx₂] | or.inr hx₁, _ := by simp [hx₁.symm] end lemma cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : π / 2 < x) (hx₂ : x < π + π / 2) : cos x < 0 := neg_pos.1 $ cos_pi_sub x ▸ cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) (by linarith) lemma cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : π / 2 ≤ x) (hx₂ : x ≤ π + π / 2) : cos x ≤ 0 := neg_nonneg.1 $ cos_pi_sub x ▸ cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (by linarith) (by linarith) lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] lemma sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -π < x) (hx₂ : x < π) : sin x = 0 ↔ x = 0 := ⟨λ h, le_antisymm (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 < sin x : sin_pos_of_pos_of_lt_pi h0 hx₂ ... = 0 : h)) (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 = sin x : h.symm ... < 0 : sin_neg_of_neg_of_neg_pi_lt h0 hx₁)), λ h, by simp [h]⟩ lemma sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ n : ℤ, (n : ℝ) * π = x := ⟨λ h, ⟨⌊x / π⌋, le_antisymm (sub_nonneg.1 (sub_floor_div_mul_nonneg _ pi_pos)) (sub_nonpos.1 $ le_of_not_gt $ λ h₃, ne_of_lt (sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos)) (by simp [sin_add, h, sin_int_mul_pi]))⟩, λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩ lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 := by rw [← mul_self_eq_one_iff (cos x), ← sin_pow_two_add_cos_pow_two x, pow_two, pow_two, ← sub_eq_iff_eq_add, sub_self]; exact ⟨λ h, by rw [h, mul_zero], eq_zero_of_mul_self_eq_zero ∘ eq.symm⟩ lemma cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ n : ℤ, (n : ℝ) * (2 * π) = x := ⟨λ h, let ⟨n, hn⟩ := sin_eq_zero_iff.1 (sin_eq_zero_iff_cos_eq.2 (or.inl h)) in ⟨n / 2, (int.mod_two_eq_zero_or_one n).elim (λ hn0, by rwa [← mul_assoc, ← @int.cast_two ℝ, ← int.cast_mul, int.div_mul_cancel ((int.dvd_iff_mod_eq_zero _ _).2 hn0)]) (λ hn1, by rw [← int.mod_add_div n 2, hn1, int.cast_add, int.cast_one, add_mul, one_mul, add_comm, mul_comm (2 : ℤ), int.cast_mul, mul_assoc, int.cast_two] at hn; rw [← hn, cos_int_mul_two_pi_add_pi] at h; exact absurd h (by norm_num))⟩, λ ⟨n, hn⟩, hn ▸ cos_int_mul_two_pi _⟩ lemma cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(2 * π) < x) (hx₂ : x < 2 * π) : cos x = 1 ↔ x = 0 := ⟨λ h, let ⟨n, hn⟩ := (cos_eq_one_iff x).1 h in begin clear _let_match, subst hn, rw [mul_lt_iff_lt_one_left two_pi_pos, ← int.cast_one, int.cast_lt, ← int.le_sub_one_iff, sub_self] at hx₂, rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos, neg_lt, ← int.cast_one, ← int.cast_neg, int.cast_lt, ← int.add_one_le_iff, neg_add_self] at hx₁, exact mul_eq_zero.2 (or.inl (int.cast_eq_zero.2 (le_antisymm hx₂ hx₁))), end, λ h, by simp [h]⟩ lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : cos y < cos x := calc cos y = cos x * cos (y - x) - sin x * sin (y - x) : by rw [← cos_add, add_sub_cancel'_right] ... < (cos x * 1) - sin x * sin (y - x) : sub_lt_sub_right ((mul_lt_mul_left (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (lt_of_lt_of_le (neg_neg_of_pos pi_div_two_pos) hx₁) (lt_of_lt_of_le hxy hy₂))).2 (lt_of_le_of_ne (cos_le_one _) (mt (cos_eq_one_iff_of_lt_of_lt (show -(2 * π) < y - x, by linarith) (show y - x < 2 * π, by linarith)).1 (sub_ne_zero.2 (ne_of_lt hxy).symm)))) _ ... ≤ _ : by rw mul_one; exact sub_le_self _ (mul_nonneg (sin_nonneg_of_nonneg_of_le_pi hx₁ (by linarith)) (sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith))) lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x < y) : cos y < cos x := match (le_total x (π / 2) : x ≤ π / 2 ∨ π / 2 ≤ x), le_total y (π / 2) with | or.inl hx, or.inl hy := cos_lt_cos_of_nonneg_of_le_pi_div_two hx₁ hx hy₁ hy hxy | or.inl hx, or.inr hy := (lt_or_eq_of_le hx).elim (λ hx, calc cos y ≤ 0 : cos_nonpos_of_pi_div_two_le_of_le hy (by linarith using [pi_pos]) ... < cos x : cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hx) (λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith using [pi_pos]) ... = cos x : by rw [hx, cos_pi_div_two]) | or.inr hx, or.inl hy := by linarith | or.inr hx, or.inr hy := neg_lt_neg_iff.1 (by rw [← cos_pi_sub, ← cos_pi_sub]; apply cos_lt_cos_of_nonneg_of_le_pi_div_two; linarith) end lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x ≤ y) : cos y ≤ cos x := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ cos_lt_cos_of_nonneg_of_le_pi hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : sin x < sin y := by rw [← cos_sub_pi_div_two, ← cos_sub_pi_div_two, ← cos_neg (x - _), ← cos_neg (y - _)]; apply cos_lt_cos_of_nonneg_of_le_pi; linarith lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_inj_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : sin x = sin y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (sin_lt_sin_of_le_of_le_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end lemma cos_inj_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : cos x = cos y) : x = y := begin rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub] at hxy, refine (sub_left_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy); linarith end lemma exists_sin_eq {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : ∃ y, -(π / 2) ≤ y ∧ y ≤ π / 2 ∧ sin y = x := @real.intermediate_value sin (-(π / 2)) (π / 2) x (λ _ _ _, continuous_iff_tendsto.1 continuous_sin _) (by rwa [sin_neg, sin_pi_div_two]) (by rwa sin_pi_div_two) (le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos)) /-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x` and `arcsin x ≤ π / 2`. If the argument is not between `-1` and `1` it defaults to `0` -/ noncomputable def arcsin (x : ℝ) : ℝ := if hx : -1 ≤ x ∧ x ≤ 1 then classical.some (exists_sin_eq hx.1 hx.2) else 0 lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx.1 hx.2)).2.1 else by rw [arcsin, dif_neg hx]; exact le_of_lt pi_div_two_pos lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx.1 hx.2)).1 else by rw [arcsin, dif_neg hx]; exact neg_nonpos.2 (le_of_lt pi_div_two_pos) lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x := by rw [arcsin, dif_pos (and.intro hx₁ hx₂)]; exact (classical.some_spec (exists_sin_eq hx₁ hx₂)).2.2 lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) hx₁ hx₂ (by rw sin_arcsin (neg_one_le_sin _) (sin_le_one _)) lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arcsin x = arcsin y) : x = y := by rw [← sin_arcsin hx₁ hx₂, ← sin_arcsin hy₁ hy₂, hxy] @[simp] lemma arcsin_zero : arcsin 0 = 0 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) (by rw [sin_arcsin, sin_zero]; norm_num) @[simp] lemma arcsin_one : arcsin 1 = π / 2 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (by linarith using [pi_pos]) (le_refl _) (by rw [sin_arcsin, sin_pi_div_two]; norm_num) @[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x := if h : -1 ≤ x ∧ x ≤ 1 then have -1 ≤ -x ∧ -x ≤ 1, by rwa [neg_le_neg_iff, neg_le, and.comm], sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_le_neg (arcsin_le_pi_div_two _)) (neg_le.1 (neg_pi_div_two_le_arcsin _)) (by rw [sin_arcsin this.1 this.2, sin_neg, sin_arcsin h.1 h.2]) else have ¬(-1 ≤ -x ∧ -x ≤ 1) := by rwa [neg_le_neg_iff, neg_le, and.comm], by rw [arcsin, arcsin, dif_neg h, dif_neg this, neg_zero] @[simp] lemma arcsin_neg_one : arcsin (-1) = -(π / 2) := by simp lemma arcsin_nonneg {x : ℝ} (hx : 0 ≤ x) : 0 ≤ arcsin x := if hx₁ : x ≤ 1 then not_lt.1 (λ h, not_lt.2 hx begin have := sin_lt_sin_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) h, rw [real.sin_arcsin, sin_zero] at this; linarith end) else by rw [arcsin, dif_neg]; simp [hx₁] lemma arcsin_eq_zero_iff {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : arcsin x = 0 ↔ x = 0 := ⟨λ h, have sin (arcsin x) = 0, by simp [h], by rwa [sin_arcsin hx₁ hx₂] at this, λ h, by simp [h]⟩ lemma arcsin_pos {x : ℝ} (hx₁ : 0 < x) (hx₂ : x ≤ 1) : 0 < arcsin x := lt_of_le_of_ne (arcsin_nonneg (le_of_lt hx₁)) (ne.symm (mt (arcsin_eq_zero_iff (by linarith) hx₂).1 (ne_of_lt hx₁).symm)) lemma arcsin_nonpos {x : ℝ} (hx : x ≤ 0) : arcsin x ≤ 0 := neg_nonneg.1 (arcsin_neg x ▸ arcsin_nonneg (neg_nonneg.2 hx)) /-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`. If the argument is not between `-1` and `1` it defaults to `π / 2` -/ noncomputable def arccos (x : ℝ) : ℝ := π / 2 - arcsin x lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x := by simp [arccos] lemma arccos_le_pi (x : ℝ) : arccos x ≤ π := by unfold arccos; linarith using [neg_pi_div_two_le_arcsin x] lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x := by unfold arccos; linarith using [arcsin_le_pi_div_two x] lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x := by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂] lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x := by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp; linarith lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arccos x = arccos y) : x = y := arcsin_inj hx₁ hx₂ hy₁ hy₂ $ by simp [arccos, *] at * @[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos] @[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos] @[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves] lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x := by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self]; simp lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) := cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) := have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_pow_two_add_cos_pow_two (arcsin x), begin rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_pow_two_le_one (arcsin x))), pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this, rw [this, sin_arcsin hx₁ hx₂], end lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) := by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂] lemma abs_div_sqrt_one_add_lt (x : ℝ) : abs (x / sqrt (1 + x ^ 2)) < 1 := have h₁ : 0 < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : 0 < sqrt (1 + x ^ 2), from sqrt_pos.2 h₁, by rw [abs_div, div_lt_iff (abs_pos_of_pos h₂), one_mul, mul_self_lt_mul_self_iff (abs_nonneg x) (abs_nonneg _), ← abs_mul, ← abs_mul, mul_self_sqrt (add_nonneg zero_le_one (pow_two_nonneg _)), abs_of_nonneg (mul_self_nonneg x), abs_of_nonneg (le_of_lt h₁), pow_two, add_comm]; exact lt_add_one _ lemma div_sqrt_one_add_lt_one (x : ℝ) : x / sqrt (1 + x ^ 2) < 1 := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).2 lemma neg_one_lt_div_sqrt_one_add (x : ℝ) : -1 < x / sqrt (1 + x ^ 2) := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).1 lemma tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < π / 2) : 0 < tan x := by rw tan_eq_sin_div_cos; exact div_pos (sin_pos_of_pos_of_lt_pi h0x (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hxp) lemma tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π / 2) : 0 ≤ tan x := match lt_or_eq_of_le h0x, lt_or_eq_of_le hxp with | or.inl hx0, or.inl hxp := le_of_lt (tan_pos_of_pos_of_lt_pi_div_two hx0 hxp) | or.inl hx0, or.inr hxp := by simp [hxp, tan_eq_sin_div_cos] | or.inr hx0, _ := by simp [hx0.symm] end lemma tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(π / 2) < x) : tan x < 0 := neg_pos.1 (tan_neg x ▸ tan_pos_of_pos_of_lt_pi_div_two (by linarith) (by linarith using [pi_pos])) lemma tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(π / 2) ≤ x) : tan x ≤ 0 := neg_nonneg.1 (tan_neg x ▸ tan_nonneg_of_nonneg_of_le_pi_div_two (by linarith) (by linarith using [pi_pos])) lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x < π / 2) (hy₁ : 0 ≤ y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := begin rw [tan_eq_sin_div_cos, tan_eq_sin_div_cos], exact div_lt_div (sin_lt_sin_of_le_of_le_pi_div_two (by linarith) (le_of_lt hx₂) (by linarith) (le_of_lt hy₂) hxy) (cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) hy₁ (by linarith) (le_of_lt hxy)) (sin_nonneg_of_nonneg_of_le_pi hy₁ (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hy₂) end lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := match le_total x 0, le_total y 0 with | or.inl hx0, or.inl hy0 := neg_lt_neg_iff.1 $ by rw [← tan_neg, ← tan_neg]; exact tan_lt_tan_of_nonneg_of_lt_pi_div_two (neg_nonneg.2 hy0) (neg_lt.2 hy₁) (neg_nonneg.2 hx0) (neg_lt.2 hx₁) (neg_lt_neg hxy) | or.inl hx0, or.inr hy0 := (lt_or_eq_of_le hy0).elim (λ hy0, calc tan x ≤ 0 : tan_nonpos_of_nonpos_of_neg_pi_div_two_le hx0 (le_of_lt hx₁) ... < tan y : tan_pos_of_pos_of_lt_pi_div_two hy0 hy₂) (λ hy0, by rw [← hy0, tan_zero]; exact tan_neg_of_neg_of_pi_div_two_lt (hy0.symm ▸ hxy) hx₁) | or.inr hx0, or.inl hy0 := by linarith | or.inr hx0, or.inr hy0 := tan_lt_tan_of_nonneg_of_lt_pi_div_two hx0 hx₂ hy0 hy₂ hxy end lemma tan_inj_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : tan x = tan y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end /-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/ noncomputable def arctan (x : ℝ) : ℝ := arcsin (x / sqrt (1 + x ^ 2)) lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) := sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)) lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) := have h₁ : (0 : ℝ) < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : (x / sqrt (1 + x ^ 2)) ^ 2 < 1, by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_lt_one_of_nonneg_of_lt_one_left (abs_nonneg _) (abs_div_sqrt_one_add_lt _) (le_of_lt (abs_div_sqrt_one_add_lt _)), by rw [arctan, cos_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), one_div_eq_inv, ← sqrt_inv, sqrt_inj (sub_nonneg.2 (le_of_lt h₂)) (inv_nonneg.2 (le_of_lt h₁)), div_pow _ (mt sqrt_eq_zero'.1 (not_le.2 h₁)), pow_two (sqrt _), mul_self_sqrt (le_of_lt h₁), ← domain.mul_left_inj (ne.symm (ne_of_lt h₁)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt h₁)), mul_inv_cancel (ne.symm (ne_of_lt h₁))]; simp lemma tan_arctan (x : ℝ) : tan (arctan x) = x := by rw [tan_eq_sin_div_cos, sin_arctan, cos_arctan, div_div_div_div_eq, mul_one, mul_div_assoc, div_self (mt sqrt_eq_zero'.1 (not_le_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg x)))), mul_one] lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 := lt_of_le_of_ne (arcsin_le_pi_div_two _) (λ h, ne_of_lt (div_sqrt_one_add_lt_one x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, h, sin_pi_div_two]) lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x := lt_of_le_of_ne (neg_pi_div_two_le_arcsin _) (λ h, ne_of_lt (neg_one_lt_div_sqrt_one_add x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, ← h, sin_neg, sin_pi_div_two]) lemma tan_surjective : function.surjective tan := function.surjective_of_has_right_inverse ⟨_, tan_arctan⟩ lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x := tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan _) (arctan_lt_pi_div_two _) hx₁ hx₂ (by rw tan_arctan) @[simp] lemma arctan_zero : arctan 0 = 0 := by simp [arctan] @[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x := by simp [arctan, neg_div] end real namespace complex local notation `π` := real.pi /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x,abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma arg_le_pi (x : ℂ) : arg x ≤ π := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact le_trans (real.arcsin_le_pi_div_two _) (le_of_lt (half_lt_self real.pi_pos)) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact le_sub_iff_add_le.1 (by rw sub_self; exact real.arcsin_nonpos (by rw [neg_im, neg_div, neg_nonpos]; exact div_nonneg hx₂ (abs_pos.2 hx))) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact sub_le_iff_le_add.2 (le_trans (real.arcsin_le_pi_div_two _) (by linarith using [real.pi_pos])) lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact lt_of_lt_of_le (neg_lt_neg (half_lt_self real.pi_pos)) (real.neg_pi_div_two_le_arcsin _) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact sub_lt_iff_lt_add.1 (lt_of_lt_of_le (by linarith using [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _)) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact lt_sub_iff_add_lt.2 (by rw neg_add_self; exact real.arcsin_pos (by rw [neg_im]; exact div_pos (neg_pos.2 (lt_of_not_ge hx₂)) (abs_pos.2 hx)) (by rw [← abs_neg x]; exact (abs_le.1 (abs_im_div_abs_le_one _)).2)) lemma arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : 0 ≤ x.im) : arg x = arg (-x) + π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_pos this, if_pos hxi, abs_neg] lemma arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : x.im < 0) : arg x = arg (-x) - π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_neg (not_le.2 hxi), if_pos this, abs_neg] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] private lemma cos_arg_of_re_nonneg {x : ℂ} (hx : x ≠ 0) (hxr : 0 ≤ x.re) : real.cos (arg x) = x.re / x.abs := have 0 ≤ 1 - (x.im / abs x) ^ 2, from sub_nonneg.2 $ by rw [pow_two, ← _root_.abs_mul_self, _root_.abs_mul, ← pow_two]; exact pow_le_one _ (_root_.abs_nonneg _) (abs_im_div_abs_le_one _), by rw [eq_div_iff_mul_eq _ _ (mt abs_eq_zero.1 hx), ← real.mul_self_sqrt (abs_nonneg x), arg, if_pos hxr, real.cos_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, ← real.sqrt_mul (abs_nonneg _), ← real.sqrt_mul this, sub_mul, div_pow _ (mt abs_eq_zero.1 hx), ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)), one_mul, pow_two, mul_self_abs, norm_sq, pow_two, add_sub_cancel, real.sqrt_mul_self hxr] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := if hxr : 0 ≤ x.re then cos_arg_of_re_nonneg hx hxr else have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, if hxi : 0 ≤ x.im then have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg (not_le.1 hxr) hxi, real.cos_add_pi, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this]; simp [neg_div] else by rw [arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg (not_le.1 hxr) (not_le.1 hxi)]; simp [real.cos_add, neg_div, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this] lemma tan_arg {x : ℂ} : real.tan (arg x) = x.im / x.re := if hx : x = 0 then by simp [hx] else by rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg hx, div_div_div_cancel_right _ _ (mt abs_eq_zero.1 hx)] lemma arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -π < x) (hx₂ : x ≤ π) : arg (cos x + sin x * I) = x := if hx₃ : -(π / 2) ≤ x ∧ x ≤ π / 2 then have hx₄ : 0 ≤ (cos x + sin x * I).re, by simp; exact real.cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two hx₃.1 hx₃.2, by rw [arg, if_pos hx₄]; simp [abs_cos_add_sin_mul_I, sin_of_real_re, real.arcsin_sin hx₃.1 hx₃.2] else if hx₄ : x < -(π / 2) then have hx₅ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬ 0 ≤ real.cos x, by simpa, not_le.2 $ by rw ← real.cos_neg; apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₆ : ¬0 ≤ (cos ↑x + sin ↑x * I).im := suffices real.sin x < 0, by simpa, by apply real.sin_neg_of_neg_of_neg_pi_lt; linarith, suffices -π + -real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₅, if_neg hx₆]; simpa [abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; simp; linarith else have hx₅ : π / 2 < x, by cases not_and_distrib.1 hx₃; linarith, have hx₆ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬0 ≤ real.cos x, by simpa, not_le.2 $ by apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₇ : 0 ≤ (cos x + sin x * I).im := suffices 0 ≤ real.sin x, by simpa, by apply real.sin_nonneg_of_nonneg_of_le_pi; linarith, suffices π - real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₆, if_pos hx₇]; simpa [abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.sin_pi_sub, real.arcsin_sin]; simp; linarith lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := have hax : abs x ≠ 0, from (mt abs_eq_zero.1 hx), have hay : abs y ≠ 0, from (mt abs_eq_zero.1 hy), ⟨λ h, begin have hcos := congr_arg real.cos h, rw [cos_arg hx, cos_arg hy, div_eq_div_iff hax hay] at hcos, have hsin := congr_arg real.sin h, rw [sin_arg, sin_arg, div_eq_div_iff hax hay] at hsin, apply complex.ext, { rw [mul_re, ← of_real_div, of_real_re, of_real_im, zero_mul, sub_zero, mul_comm, ← mul_div_assoc, hcos, mul_div_cancel _ hax] }, { rw [mul_im, ← of_real_div, of_real_re, of_real_im, zero_mul, add_zero, mul_comm, ← mul_div_assoc, hsin, mul_div_cancel _ hax] } end, λ h, have hre : abs (y / x) * x.re = y.re, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg re h, have hre' : abs (x / y) * y.re = x.re, by rw [← hre, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have him : abs (y / x) * x.im = y.im, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg im h, have him' : abs (x / y) * y.im = x.im, by rw [← him, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have hxya : x.im / abs x = y.im / abs y, by rw [← him, abs_div, mul_comm, ← mul_div_comm, mul_div_cancel_left _ hay], have hnxya : (-x).im / abs x = (-y).im / abs y, by rw [neg_im, neg_im, neg_div, neg_div, hxya], if hxr : 0 ≤ x.re then have hyr : 0 ≤ y.re, from hre ▸ mul_nonneg (abs_nonneg _) hxr, by simp [arg, *] at * else have hyr : ¬ 0 ≤ y.re, from λ hyr, hxr $ hre' ▸ mul_nonneg (abs_nonneg _) hyr, if hxi : 0 ≤ x.im then have hyi : 0 ≤ y.im, from him ▸ mul_nonneg (abs_nonneg _) hxi, by simp [arg, *] at * else have hyi : ¬ 0 ≤ y.im, from λ hyi, hxi $ him' ▸ mul_nonneg (abs_nonneg _) hyi, by simp [arg, *] at *⟩ lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := if hx : x = 0 then by simp [hx] else (arg_eq_arg_iff (mul_ne_zero (of_real_ne_zero.2 (ne_of_lt hr).symm) hx) hx).2 $ by rw [abs_mul, abs_of_nonneg (le_of_lt hr), ← mul_assoc, of_real_mul, mul_comm (r : ℂ), ← div_div_eq_div_mul, div_mul_cancel _ (of_real_ne_zero.2 (ne_of_lt hr).symm), div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), one_mul] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := if hy : y = 0 then by simp * at * else have hx : x ≠ 0, from λ hx, by simp [*, eq_comm] at *, by rwa [arg_eq_arg_iff hx hy, h₁, div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hy)), one_mul] at h₂ lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg, ← of_real_neg, arg_of_real_of_nonneg]; simp [*, le_iff_eq_or_lt, lt_neg] /-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`. `log 0 = 0`-/ noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log] lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log] lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x := by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx, ← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im] lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π) (hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y] at hxy; exact complex.ext (real.exp_injective $ by simpa [abs_mul, abs_cos_add_sin_mul_I] using congr_arg complex.abs hxy) (by simpa [(of_real_exp _).symm, - of_real_exp, arg_real_mul _ (real.exp_pos _), arg_cos_add_sin_mul_I hx₁ hx₂, arg_cos_add_sin_mul_I hy₁ hy₂] using congr_arg arg hxy) lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x := exp_inj_of_neg_pi_lt_of_le_pi (by rw log_im; exact neg_pi_lt_arg _) (by rw log_im; exact arg_le_pi _) hx₁ hx₂ (by rw [exp_log (exp_ne_zero _)]) lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x := complex.ext (by rw [log_re, of_real_re, abs_of_nonneg hx]) (by rw [of_real_im, log_im, arg_of_real_of_nonneg hx]) @[simp] lemma log_zero : log 0 = 0 := by simp [log] @[simp] lemma log_one : log 1 = 0 := by simp [log] lemma log_neg_one : log (-1) = π * I := by simp [log] lemma log_I : log I = π / 2 * I := by simp [log] lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log] lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) := have real.exp (x.re) * real.cos (x.im) = 1 → real.cos x.im ≠ -1, from λ h₁ h₂, begin rw [h₂, mul_neg_eq_neg_mul_symm, mul_one, neg_eq_iff_neg_eq] at h₁, have := real.exp_pos x.re, rw ← h₁ at this, exact absurd this (by norm_num) end, calc exp x = 1 ↔ (exp x).re = 1 ∧ (exp x).im = 0 : by simp [complex.ext_iff] ... ↔ real.cos x.im = 1 ∧ real.sin x.im = 0 ∧ x.re = 0 : begin rw exp_eq_exp_re_mul_sin_add_cos, simp [complex.ext_iff, cos_of_real_re, sin_of_real_re, exp_of_real_re, real.exp_ne_zero], split; finish [real.sin_eq_zero_iff_cos_eq] end ... ↔ (∃ n : ℤ, ↑n * (2 * π) = x.im) ∧ (∃ n : ℤ, ↑n * π = x.im) ∧ x.re = 0 : by rw [real.sin_eq_zero_iff, real.cos_eq_one_iff] ... ↔ ∃ n : ℤ, x = n * ((2 * π) * I) : ⟨λ ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩, ⟨n, by simp [complex.ext_iff, hn.symm, h]⟩, λ ⟨n, hn⟩, ⟨⟨n, by simp [hn]⟩, ⟨2 * n, by simp [hn, mul_comm, mul_assoc, mul_left_comm]⟩, by simp [hn]⟩⟩ lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 := by rw [exp_sub, div_eq_one_iff_eq _ (exp_ne_zero _)] lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) := by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add'] @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := calc cos (π / 2) = real.cos (π / 2) : by rw [of_real_cos]; simp ... = 0 : by simp @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := calc sin (π / 2) = real.sin (π / 2) : by rw [of_real_sin]; simp ... = 1 : by simp @[simp] lemma sin_pi : sin π = 0 := by rw [← of_real_sin, real.sin_pi]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← of_real_cos, real.cos_pi]; simp @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [cos_add] lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] section pow noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (@one_ne_zero ℂ _), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_def, hx, mul_add, exp_add, pow_succ, (cpow_nat_cast n).symm, exp_log hx] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw fpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := have (log x * (↑n)⁻¹).im = (log x).im / n, by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im, of_real_re, of_real_im]; simp, have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π, from (le_total (log x).im 0).elim (λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg] ... ≤ ((log x).im * 1) / n : le_div_of_mul_le (nat.cast_pos.2 hn) (mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h) ... = (log x * (↑n)⁻¹).im : by simp [this], this.symm ▸ le_trans (div_nonpos_of_nonpos_of_pos h (nat.cast_pos.2 hn)) (le_of_lt real.pi_pos)⟩) (λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos) (div_nonneg h (nat.cast_pos.2 hn)), calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this] ... ≤ (log x).im : (div_le_of_le_mul (nat.cast_pos.2 hn) (mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)) ... ≤ _ : by simp [log, arg_le_pi]⟩), by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2, inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), cpow_one] end pow end complex namespace real noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul] at * end end complex namespace real @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma rpow_add {x : ℝ} (y z : ℝ) (hx : 0 < x) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_lt hx).symm, mul_add, exp_add] lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] end real
680ef37014652c1fa4f7b4bc50a9cd074675b7fb
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/category_theory/isomorphism.lean
b8849f1b315b882fb494c6b192a7cfaf543647e3
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,227
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor /-! # Isomorphisms This file defines isomorphisms between objects of a category. ## Main definitions - `structure iso` : a bundled isomorphism between two objects of a category; - `class is_iso` : an unbundled version of `iso`; note that `is_iso f` is usually *not* a `Prop`, because it holds the inverse morphism; - `as_iso` : convert from `is_iso` to `iso`; - `of_iso` : convert from `iso` to `is_iso`; - standard operations on isomorphisms (composition, inverse etc) ## Notations - `X ≅ Y` : same as `iso X Y`; - `α ≪≫ β` : composition of two isomorphisms; it is called `iso.trans` ## Tags category, category theory, isomorphism -/ universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open category /-- An isomorphism (a.k.a. an invertible morphism) between two objects of a category. The inverse morphism is bundled. See also `category_theory.core` for the category with the same objects and isomorphisms playing the role of morphisms. See https://stacks.math.columbia.edu/tag/0017. -/ structure iso {C : Type u} [category.{v} C] (X Y : C) := (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id' : hom ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ hom = 𝟙 Y . obviously) restate_axiom iso.hom_inv_id' restate_axiom iso.inv_hom_id' attribute [simp, reassoc] iso.hom_inv_id iso.inv_hom_id infixr ` ≅ `:10 := iso -- type as \cong or \iso variables {C : Type u} [category.{v} C] variables {X Y Z : C} namespace iso @[ext] lemma ext ⦃α β : X ≅ Y⦄ (w : α.hom = β.hom) : α = β := suffices α.inv = β.inv, by cases α; cases β; cc, calc α.inv = α.inv ≫ (β.hom ≫ β.inv) : by rw [iso.hom_inv_id, category.comp_id] ... = (α.inv ≫ α.hom) ≫ β.inv : by rw [category.assoc, ←w] ... = β.inv : by rw [iso.inv_hom_id, category.id_comp] /-- Inverse isomorphism. -/ @[symm] def symm (I : X ≅ Y) : Y ≅ X := { hom := I.inv, inv := I.hom, hom_inv_id' := I.inv_hom_id', inv_hom_id' := I.hom_inv_id' } @[simp] lemma symm_hom (α : X ≅ Y) : α.symm.hom = α.inv := rfl @[simp] lemma symm_inv (α : X ≅ Y) : α.symm.inv = α.hom := rfl @[simp] lemma symm_mk {X Y : C} (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id) : iso.symm {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} = {hom := inv, inv := hom, hom_inv_id' := inv_hom_id, inv_hom_id' := hom_inv_id} := rfl @[simp] lemma symm_symm_eq {X Y : C} (α : X ≅ Y) : α.symm.symm = α := by cases α; refl @[simp] lemma symm_eq_iff {X Y : C} {α β : X ≅ Y} : α.symm = β.symm ↔ α = β := ⟨λ h, symm_symm_eq α ▸ symm_symm_eq β ▸ congr_arg symm h, congr_arg symm⟩ /-- Identity isomorphism. -/ @[refl, simps] def refl (X : C) : X ≅ X := { hom := 𝟙 X, inv := 𝟙 X } instance : inhabited (X ≅ X) := ⟨iso.refl X⟩ @[simp] lemma refl_symm (X : C) : (iso.refl X).symm = iso.refl X := rfl /-- Composition of two isomorphisms -/ @[trans, simps] def trans (α : X ≅ Y) (β : Y ≅ Z) : X ≅ Z := { hom := α.hom ≫ β.hom, inv := β.inv ≫ α.inv } infixr ` ≪≫ `:80 := iso.trans -- type as `\ll \gg`. @[simp] lemma trans_mk {X Y Z : C} (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id) (hom' : Y ⟶ Z) (inv' : Z ⟶ Y) (hom_inv_id') (inv_hom_id') (hom_inv_id'') (inv_hom_id'') : iso.trans {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} {hom := hom', inv := inv', hom_inv_id' := hom_inv_id', inv_hom_id' := inv_hom_id'} = {hom := hom ≫ hom', inv := inv' ≫ inv, hom_inv_id' := hom_inv_id'', inv_hom_id' := inv_hom_id''} := rfl @[simp] lemma trans_symm (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).symm = β.symm ≪≫ α.symm := rfl @[simp] lemma trans_assoc {Z' : C} (α : X ≅ Y) (β : Y ≅ Z) (γ : Z ≅ Z') : (α ≪≫ β) ≪≫ γ = α ≪≫ β ≪≫ γ := by ext; simp only [trans_hom, category.assoc] @[simp] lemma refl_trans (α : X ≅ Y) : (iso.refl X) ≪≫ α = α := by ext; apply category.id_comp @[simp] lemma trans_refl (α : X ≅ Y) : α ≪≫ (iso.refl Y) = α := by ext; apply category.comp_id @[simp] lemma symm_self_id (α : X ≅ Y) : α.symm ≪≫ α = iso.refl Y := ext α.inv_hom_id @[simp] lemma self_symm_id (α : X ≅ Y) : α ≪≫ α.symm = iso.refl X := ext α.hom_inv_id @[simp] lemma symm_self_id_assoc (α : X ≅ Y) (β : Y ≅ Z) : α.symm ≪≫ α ≪≫ β = β := by rw [← trans_assoc, symm_self_id, refl_trans] @[simp] lemma self_symm_id_assoc (α : X ≅ Y) (β : X ≅ Z) : α ≪≫ α.symm ≪≫ β = β := by rw [← trans_assoc, self_symm_id, refl_trans] lemma inv_comp_eq (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : α.inv ≫ f = g ↔ f = α.hom ≫ g := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_inv_comp (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : g = α.inv ≫ f ↔ α.hom ≫ g = f := (inv_comp_eq α.symm).symm lemma comp_inv_eq (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : f ≫ α.inv = g ↔ f = g ≫ α.hom := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_comp_inv (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : g = f ≫ α.inv ↔ g ≫ α.hom = f := (comp_inv_eq α.symm).symm lemma inv_eq_inv (f g : X ≅ Y) : f.inv = g.inv ↔ f.hom = g.hom := have ∀{X Y : C} (f g : X ≅ Y), f.hom = g.hom → f.inv = g.inv, from λ X Y f g h, by rw [ext h], ⟨this f.symm g.symm, this f g⟩ lemma hom_comp_eq_id (α : X ≅ Y) {f : Y ⟶ X} : α.hom ≫ f = 𝟙 X ↔ f = α.inv := by rw [←eq_inv_comp, comp_id] lemma comp_hom_eq_id (α : X ≅ Y) {f : Y ⟶ X} : f ≫ α.hom = 𝟙 Y ↔ f = α.inv := by rw [←eq_comp_inv, id_comp] lemma hom_eq_inv (α : X ≅ Y) (β : Y ≅ X) : α.hom = β.inv ↔ β.hom = α.inv := by { erw [inv_eq_inv α.symm β, eq_comm], refl } end iso /-- `is_iso` typeclass expressing that a morphism is invertible. This contains the data of the inverse, but is a subsingleton type. -/ class is_iso (f : X ⟶ Y) := (inv : Y ⟶ X) (hom_inv_id' : f ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ f = 𝟙 Y . obviously) export is_iso (inv) /-- Reinterpret a morphism `f` with an `is_iso f` instance as an `iso`. -/ def as_iso (f : X ⟶ Y) [h : is_iso f] : X ≅ Y := { hom := f, ..h } @[simp] lemma as_iso_hom (f : X ⟶ Y) [is_iso f] : (as_iso f).hom = f := rfl @[simp] lemma as_iso_inv (f : X ⟶ Y) [is_iso f] : (as_iso f).inv = inv f := rfl namespace is_iso @[simp] lemma hom_inv_id (f : X ⟶ Y) [is_iso f] : f ≫ inv f = 𝟙 X := is_iso.hom_inv_id' @[simp] lemma inv_hom_id (f : X ⟶ Y) [is_iso f] : inv f ≫ f = 𝟙 Y := is_iso.inv_hom_id' @[simp] lemma hom_inv_id_assoc {Z} (f : X ⟶ Y) [is_iso f] (g : X ⟶ Z) : f ≫ inv f ≫ g = g := (as_iso f).hom_inv_id_assoc g @[simp] lemma inv_hom_id_assoc {Z} (f : X ⟶ Y) [is_iso f] (g : Y ⟶ Z) : inv f ≫ f ≫ g = g := (as_iso f).inv_hom_id_assoc g instance id (X : C) : is_iso (𝟙 X) := { inv := 𝟙 X } instance of_iso (f : X ≅ Y) : is_iso f.hom := { .. f } instance of_iso_inv (f : X ≅ Y) : is_iso f.inv := is_iso.of_iso f.symm variables {f g : X ⟶ Y} {h : Y ⟶ Z} instance inv_is_iso [is_iso f] : is_iso (inv f) := is_iso.of_iso_inv (as_iso f) instance comp_is_iso [is_iso f] [is_iso h] : is_iso (f ≫ h) := is_iso.of_iso $ (as_iso f) ≪≫ (as_iso h) @[simp] lemma inv_id : inv (𝟙 X) = 𝟙 X := rfl @[simp] lemma inv_comp [is_iso f] [is_iso h] : inv (f ≫ h) = inv h ≫ inv f := rfl @[simp] lemma inv_inv [is_iso f] : inv (inv f) = f := rfl @[simp] lemma iso.inv_inv (f : X ≅ Y) : inv (f.inv) = f.hom := rfl @[simp] lemma iso.inv_hom (f : X ≅ Y) : inv (f.hom) = f.inv := rfl @[simp] lemma inv_comp_eq (α : X ⟶ Y) [is_iso α] {f : X ⟶ Z} {g : Y ⟶ Z} : inv α ≫ f = g ↔ f = α ≫ g := (as_iso α).inv_comp_eq @[simp] lemma eq_inv_comp (α : X ⟶ Y) [is_iso α] {f : X ⟶ Z} {g : Y ⟶ Z} : g = inv α ≫ f ↔ α ≫ g = f := (as_iso α).eq_inv_comp @[simp] lemma comp_inv_eq (α : X ⟶ Y) [is_iso α] {f : Z ⟶ Y} {g : Z ⟶ X} : f ≫ inv α = g ↔ f = g ≫ α := (as_iso α).comp_inv_eq @[simp] lemma eq_comp_inv (α : X ⟶ Y) [is_iso α] {f : Z ⟶ Y} {g : Z ⟶ X} : g = f ≫ inv α ↔ g ≫ α = f := (as_iso α).eq_comp_inv @[priority 100] -- see Note [lower instance priority] instance epi_of_iso (f : X ⟶ Y) [is_iso f] : epi f := { left_cancellation := λ Z g h w, -- This is an interesting test case for better rewrite automation. by rw [← is_iso.inv_hom_id_assoc f g, w, is_iso.inv_hom_id_assoc f h] } @[priority 100] -- see Note [lower instance priority] instance mono_of_iso (f : X ⟶ Y) [is_iso f] : mono f := { right_cancellation := λ Z g h w, by rw [←category.comp_id g, ←category.comp_id h, ←is_iso.hom_inv_id f, ←category.assoc, w, ←category.assoc] } end is_iso open is_iso lemma eq_of_inv_eq_inv {f g : X ⟶ Y} [is_iso f] [is_iso g] (p : inv f = inv g) : f = g := begin apply (cancel_epi (inv f)).1, erw [inv_hom_id, p, inv_hom_id], end instance (f : X ⟶ Y) : subsingleton (is_iso f) := ⟨λ a b, suffices a.inv = b.inv, by cases a; cases b; congr; exact this, show (@as_iso C _ _ _ f a).inv = (@as_iso C _ _ _ f b).inv, by congr' 1; ext; refl⟩ lemma is_iso.inv_eq_inv {f g : X ⟶ Y} [is_iso f] [is_iso g] : inv f = inv g ↔ f = g := iso.inv_eq_inv (as_iso f) (as_iso g) namespace iso /-! All these cancellation lemmas can be solved by `simp [cancel_mono]` (or `simp [cancel_epi]`), but with the current design `cancel_mono` is not a good `simp` lemma, because it generates a typeclass search. When we can see syntactically that a morphism is a `mono` or an `epi` because it came from an isomorphism, it's fine to do the cancellation via `simp`. In the longer term, it might be worth exploring making `mono` and `epi` structures, rather than typeclasses, with coercions back to `X ⟶ Y`. Presumably we could write `X ↪ Y` and `X ↠ Y`. -/ @[simp] lemma cancel_iso_hom_left {X Y Z : C} (f : X ≅ Y) (g g' : Y ⟶ Z) : f.hom ≫ g = f.hom ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_iso_inv_left {X Y Z : C} (f : Y ≅ X) (g g' : Y ⟶ Z) : f.inv ≫ g = f.inv ≫ g' ↔ g = g' := by simp only [cancel_epi] @[simp] lemma cancel_iso_hom_right {X Y Z : C} (f f' : X ⟶ Y) (g : Y ≅ Z) : f ≫ g.hom = f' ≫ g.hom ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_iso_inv_right {X Y Z : C} (f f' : X ⟶ Y) (g : Z ≅ Y) : f ≫ g.inv = f' ≫ g.inv ↔ f = f' := by simp only [cancel_mono] /- Unfortunately cancelling an isomorphism from the right of a chain of compositions is awkward. We would need separate lemmas for each chain length (worse: for each pair of chain lengths). We provide two more lemmas, for case of three morphisms, because this actually comes up in practice, but then stop. -/ @[simp] lemma cancel_iso_hom_right_assoc {W X X' Y Z : C} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) (h : Y ≅ Z) : f ≫ g ≫ h.hom = f' ≫ g' ≫ h.hom ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_iso_inv_right_assoc {W X X' Y Z : C} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) (h : Z ≅ Y) : f ≫ g ≫ h.inv = f' ≫ g' ≫ h.inv ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] end iso namespace functor universes u₁ v₁ u₂ v₂ variables {D : Type u₂} variables [category.{v₂} D] /-- A functor `F : C ⥤ D` sends isomorphisms `i : X ≅ Y` to isomorphisms `F.obj X ≅ F.obj Y` -/ def map_iso (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.obj X ≅ F.obj Y := { hom := F.map i.hom, inv := F.map i.inv, hom_inv_id' := by rw [←map_comp, iso.hom_inv_id, ←map_id], inv_hom_id' := by rw [←map_comp, iso.inv_hom_id, ←map_id] } @[simp] lemma map_iso_hom (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.map_iso i).hom = F.map i.hom := rfl @[simp] lemma map_iso_inv (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.map_iso i).inv = F.map i.inv := rfl @[simp] lemma map_iso_symm (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.map_iso i.symm = (F.map_iso i).symm := rfl @[simp] lemma map_iso_trans (F : C ⥤ D) {X Y Z : C} (i : X ≅ Y) (j : Y ≅ Z) : F.map_iso (i ≪≫ j) = (F.map_iso i) ≪≫ (F.map_iso j) := by ext; apply functor.map_comp @[simp] lemma map_iso_refl (F : C ⥤ D) (X : C) : F.map_iso (iso.refl X) = iso.refl (F.obj X) := iso.ext $ F.map_id X instance map_is_iso (F : C ⥤ D) (f : X ⟶ Y) [is_iso f] : is_iso (F.map f) := is_iso.of_iso $ F.map_iso (as_iso f) @[simp] lemma map_inv (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map (inv f) = inv (F.map f) := rfl lemma map_hom_inv (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map f ≫ F.map (inv f) = 𝟙 (F.obj X) := by simp lemma map_inv_hom (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map (inv f) ≫ F.map f = 𝟙 (F.obj Y) := by simp end functor end category_theory
745ed547d4adf847b353863264720ccb6da324d8
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/readerThe.lean
c09115970989289ad4dddc102b74fdf5513be6d7
[ "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
331
lean
abbrev M := ReaderT String $ StateT Nat $ ReaderT Bool $ IO def f : M Nat := do let s ← read IO.println s let b ← readThe Bool IO.println b let s ← get pure s #eval (f "hello").run' 10 true def g : M Nat := let a : M Nat := withTheReader Bool not f withReader (fun s => s ++ " world") a #eval (g "hello").run' 10 true
7ec9a938b8b1b71caf27034c04675b5902d33e40
359199d7253811b032ab92108191da7336eba86e
/src/mywork/my_lect_14.lean
dabc089b60d9573238eb3ff1164a1cc21627586d
[]
no_license
arte-et-marte/my_cs2120f21
0bc6215cb5018a3b7c90d9d399a173233f587064
91609c3609ad81fda895bee8b97cc76813241e17
refs/heads/main
1,693,298,928,348
1,634,931,202,000
1,634,931,202,000
399,946,705
0
0
null
null
null
null
UTF-8
Lean
false
false
966
lean
axioms (Person : Type) (Likes : Person → Person → Prop) -- Likes is a binary relation (using a 2-place predicate) example: ¬(∀ (p : Person), Likes p p) ↔ ∃ (p : Person), ¬ Likes p p := -- uninhabitated type = no values/proofs/instances of that type begin apply iff.intro _ _, -- forwards assume h, -- elim rule for all is simply to apply the all proof to something (of the correct type) have f := classical.em (∃ (p : Person), ¬Likes p p), -- how??? cases f with f nf, -- case 1 assumption, -- case 2 (how to unearth the contradiction???) have to_contra : ∀ (p : Person), Likes p p := _, -- come back to prove this after proving original goal contradiction, assume p, have lpp_nlpp := classical.em (Likes p p), cases lpp_nlpp with lpp nlpp, assumption, -- have a witness value and a proof that it can go into have a : ∃ (p : Person), ¬Likes p p := exists.intro p nlpp, contradiction, -- backwards end
955bb60bbcb4796e961b85b6e4d5d22e8b134e83
97c8e5d8aca4afeebb5b335f26a492c53680efc8
/ground_zero/HITs/int.lean
539a59efc1514f0ff7b978360ecbb98e051d7bf9
[]
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
7,302
lean
import ground_zero.types.heq /- Integers ℤ as a quotient of ℕ × ℕ. * HoTT 6.10, remark 6.10.7 -/ abbreviation builtin.int := int namespace ground_zero.HITs def int.rel : ℕ × ℕ → ℕ × ℕ → Prop | ⟨a, b⟩ ⟨c, d⟩ := a + d = b + c def int := quot int.rel local notation ℤ := int namespace nat.product def add (x y : ℕ × ℕ) : ℕ × ℕ := begin cases x with a b, cases y with c d, split, apply a + c, apply b + d end instance : has_add (ℕ × ℕ) := ⟨add⟩ def mul (x y : ℕ × ℕ) : ℕ × ℕ := begin cases x with a b, cases y with c d, split, apply a * c + b * d, apply a * d + b * c end instance : has_mul (ℕ × ℕ) := ⟨mul⟩ lemma add_comm (x y : ℕ × ℕ) : x + y = y + x := begin cases x with a b, cases y with c d, simp [has_add.add], simp [add] end lemma mul_comm (x y : ℕ × ℕ) : x * y = y * x := begin cases x with a b, cases y with c d, simp [has_mul.mul], simp [mul], split, { rw [nat.mul_comm c a], rw [nat.mul_comm d b] }, { rw [nat.mul_comm c b], rw [nat.mul_comm d a], rw [nat.add_comm (b * c) (a * d)] } end lemma rw.add (a b : ℕ × ℕ) : nat.product.add a b = a + b := by trivial lemma rw.mul (a b : ℕ × ℕ) : nat.product.mul a b = a * b := by trivial end nat.product namespace int universes u v def mk : ℕ × ℕ → ℤ := quot.mk rel def elem (a b : ℕ) : ℤ := quot.mk rel ⟨a, b⟩ def pos (n : ℕ) := mk ⟨n, 0⟩ instance : has_coe ℕ ℤ := ⟨pos⟩ def neg (n : ℕ) := mk ⟨0, n⟩ instance : has_zero int := ⟨mk ⟨0, 0⟩⟩ instance : has_one int := ⟨mk ⟨1, 0⟩⟩ def knife {a b c d : ℕ} (H : a + d = b + c :> ℕ) : mk ⟨a, b⟩ = mk ⟨c, d⟩ :> ℤ := ground_zero.support.inclusion $ @quot.sound _ int.rel ⟨a, b⟩ ⟨c, d⟩ (ground_zero.support.truncation H) def ind {π : ℤ → Sort u} (mk₁ : Π (x : ℕ × ℕ), π (mk x)) (knife₁ : Π {a b c d : ℕ} (H : a + d = b + c :> ℕ), mk₁ ⟨a, b⟩ =[knife H] mk₁ ⟨c, d⟩) (x : ℤ) : π x := begin refine quot.hrec_on x _ _, exact mk₁, intros x y p, cases x with a b, cases y with c d, refine ground_zero.types.eq.rec _ (ground_zero.types.equiv.subst_from_pathover (knife₁ (ground_zero.support.inclusion p))), apply ground_zero.types.heq.eq_subst_heq end def injs {β : Sort u} (pos₁ : ℕ → β) (zero₁ : β) (neg₁ : ℕ → β) : ℕ × ℕ → β | ⟨0, 0⟩ := zero₁ | ⟨n, 0⟩ := pos₁ n | ⟨0, n⟩ := neg₁ n | ⟨n + 1, m + 1⟩ := if n > m then injs ⟨n + 1, m⟩ else injs ⟨n, m + 1⟩ def simplify : ℕ × ℕ → ℕ × ℕ | ⟨0, 0⟩ := ⟨0, 0⟩ | ⟨n + 1, 0⟩ := ⟨n + 1, 0⟩ | ⟨0, n + 1⟩ := ⟨0, n + 1⟩ | ⟨n + 1, m + 1⟩ := if n > m then ⟨n - m, 0⟩ else ⟨0, m - n⟩ lemma ite.left {c : Prop} [decidable c] {α : Sort u} {x y : α} (h : not c) : ite c x y = y := begin unfold ite, tactic.unfreeze_local_instances, cases _inst_1 with u v, trivial, contradiction end lemma ite.right {c : Prop} [decidable c] {α : Sort u} {x y : α} (h : c) : ite c x y = x := begin unfold ite, tactic.unfreeze_local_instances, cases _inst_1 with u v, contradiction, trivial end /- theorem simplify_correct (x : ℕ × ℕ) : mk x = mk (simplify x) := begin apply quot.sound, cases x with u v, induction u with u ih₁, { induction v with v ih, repeat { simp [simplify, rel] } }, { induction v with v ih₂, { simp [simplify, rel] }, { simp [simplify], have H := nat.decidable_le (v + 1) u, induction H; unfold gt; unfold has_lt.lt; unfold nat.lt; unfold has_le.le at H, { rw [ite.left H], unfold rel, admit }, { rw [ite.right H], unfold rel, admit } } } end def blade {π : ℤ → Sort u} (pos₁ : Π (n : ℕ), π (elem n 0)) (zero₁ : π 0) (neg₁ : Π (n : ℕ), π (elem 0 n)) : Π x, π x := begin fapply ind, { intro x, cases x with u v, rw [simplify_correct], admit }, admit end -/ instance : has_neg int := ⟨quot.lift (λ (x : ℕ × ℕ), mk ⟨x.pr₂, x.pr₁⟩) (begin intros x y H, simp, cases x with a b, cases y with c d, simp, apply quot.sound, simp [rel], simp [rel] at H, symmetry, assumption end)⟩ lemma nat_rw (a b : ℕ) : nat.add a b = a + b := by trivial def lift₂ (f : ℕ × ℕ → ℕ × ℕ → ℕ × ℕ) (h₁ : Π (a b x : ℕ × ℕ) (H : rel a b), mk (f x a) = mk (f x b)) (h₂ : Π (a b : ℕ × ℕ), mk (f a b) = mk (f b a)) (x y : int) : int := quot.lift (λ x, quot.lift (λ y, mk (f x y)) (begin intros a b H, simp, apply h₁, assumption end) y) (begin intros a b H, simp, induction y, simp, rw [h₂ a y], rw [h₂ b y], apply h₁, assumption, trivial end) x lemma add_saves_int {a b c d : ℕ} (H : a + d = b + c) (y : ℕ × ℕ) : mk (⟨a, b⟩ + y) = mk (⟨c, d⟩ + y) := begin cases y with u v, simp [has_add.add], apply quot.sound, simp [nat.product.add], simp [rel], rw [←nat.add_assoc], rw [H], rw [nat.add_assoc] end def eq_map {α : Sort u} {β : Sort v} {a b : α} (f : α → β) (p : a = b) : f a = f b := begin induction p, reflexivity end def add : int → int → int := begin apply lift₂ nat.product.add, { intros x y u H, cases x with a b, cases y with c d, repeat { rw [nat.product.rw.add] }, rw [nat.product.add_comm u ⟨a, b⟩], rw [nat.product.add_comm u ⟨c, d⟩], apply add_saves_int, assumption }, { intros x y, apply eq_map mk, apply nat.product.add_comm } end instance : has_add int := ⟨add⟩ instance : has_sub int := ⟨λ a b, a + (-b)⟩ theorem inv_append (a : ℤ) : a + (-a) = 0 := begin induction a, cases a with u v, simp [has_neg.neg], apply quot.sound, simp [nat.product.add], simp [rel], end theorem send_to_right {a b c : ℤ} : (a + b = c) → (a = c - b) := begin intro h, induction a, induction b, induction c, cases a with x y, cases b with u v, cases c with p q, simp [has_sub.sub, has_neg.neg], rw [←h], simp [mk], simp [has_add.add] at *, apply quot.sound, simp [nat.product.add], simp [rel], repeat { trivial } end def mul : ℤ → ℤ → ℤ := begin apply lift₂ nat.product.mul, { intros x y z H, cases x with a b, cases y with c d, cases z with u v, simp [nat.product.mul], apply quot.sound, simp [rel], rw [←nat.add_assoc (u * a)], rw [←nat.add_assoc (u * b)], rw [←nat.left_distrib u a d], rw [←nat.left_distrib v b c], rw [←nat.left_distrib u b c], rw [←nat.left_distrib v a d], simp [rel] at H, rw [H] }, { intros x y, apply eq_map mk, apply nat.product.mul_comm } end instance : has_mul int := ⟨mul⟩ theorem k_equiv (a b k : ℕ) : mk ⟨a, b⟩ = mk ⟨a + k, b + k⟩ := begin apply quot.sound, simp [rel] end end int end ground_zero.HITs
9547a3beb78711b485fc8afff0d8d1289715267f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_cc13.lean
d8673733a01aab406e770a24a85b8f043041ea24
[ "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
565
lean
set_option blast.strategy "cc" example (p : nat → nat → Prop) (f : nat → nat) (a b c d : nat) : p (f a) (f b) → a = c → b = d → b = c → p (f c) (f c) := by blast example (p : nat → nat → Prop) (a b c d : nat) : p a b → a = c → b = d → p c d := by blast example (p : nat → nat → Prop) (f : nat → nat) (a b c d : nat) : p (f (f (f (f (f (f a)))))) (f (f (f (f (f (f b)))))) → a = c → b = d → b = c → p (f (f (f (f (f (f c)))))) (f (f (f (f (f (f c)))))) := by blast
87ea776937f8742ad56f8ab1940688bf86a1ff08
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/Mathlib/Mathport/SpecialNames.lean
4794ab14ff48a3c6bca64592d8cbd5f70f0fd8b6
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
1,804
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import Mathlib.Mathport.Rename namespace Mathlib.Prelude -- Note: we do not currently auto-align constants. #align quot Quot #align quot.mk Quot.mk #align quot.lift Quot.lift #align quot.ind Quot.ind -- Otherwise would be`OutParam` and `OptParam`! -- Note: we want `auto_param` to *not* align. #align out_param outParam #align opt_param optParam #align heq HEq #align punit PUnit #align pprod PProd #align has_coe Coe #align has_coe.coe Coe.coe #align has_coe_t CoeT #align has_coe_t.coe CoeT.coe #align has_coe_to_fun CoeFun #align has_coe_to_fun.coe CoeFun.coe #align has_coe_to_sort CoeSort #align has_coe_to_sort.coe CoeSort.coe #align has_le LE #align has_le.le LE.le #align has_lt LT #align has_lt.lt LT.lt #align has_beq BEq #align has_sizeof SizeOf -- This otherwise causes filenames to clash #align category_theory.Kleisli CategoryTheory.KleisliCat -- TODO: backport? #align int.neg_succ_of_nat Int.negSucc -- Generic 'has'-stripping -- Note: we don't currently strip automatically for various reasons. #align has_add Add #align has_sub Sub #align has_mul Mul #align has_div Div #align has_neg Neg #align has_mod Mod #align has_pow Pow #align has_append Append #align has_pure Pure #align has_bind Bind #align has_seq Seq #align has_seq_left SeqLeft #align has_seq_right SeqRight -- Implementation detail #align _sorry_placeholder_ _sorry_placeholder_ end Mathlib.Prelude
ffe9412bf8e89c3db03d0abba34afc85c21edbea
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/cases_unsupported_equality.lean
d69e75de9e7eccfe35922adfa77340bac4ef904a
[ "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
131
lean
inductive foo : ℕ → Type | a : foo 0 | b : ∀ n, foo (n+1) example (n) (f : ℕ → ℕ) (h : foo (f n)) : true := by cases h
f1e3fcc156979d3ab1901fd0aee6805b99c41b5d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/group_theory/coset.lean
a2d4c3d13bb296a22cd4f9d2b7d56023e22892c0
[ "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
15,025
lean
/- Copyright (c) 2018 Mitchell Rowett. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Rowett, Scott Morrison -/ import group_theory.subgroup /-! # Cosets This file develops the basic theory of left and right cosets. ## Main definitions * `left_coset a s`: the left coset `a * s` for an element `a : α` and a subset `s ⊆ α`, for an `add_group` this is `left_add_coset a s`. * `right_coset s a`: the right coset `s * a` for an element `a : α` and a subset `s ⊆ α`, for an `add_group` this is `right_add_coset s a`. * `quotient_group.quotient s`: the quotient type representing the left cosets with respect to a subgroup `s`, for an `add_group` this is `quotient_add_group.quotient s`. * `quotient_group.mk`: the canonical map from `α` to `α/s` for a subgroup `s` of `α`, for an `add_group` this is `quotient_add_group.mk`. * `subgroup.left_coset_equiv_subgroup`: the natural bijection between a left coset and the subgroup, for an `add_group` this is `add_subgroup.left_coset_equiv_add_subgroup`. ## Notation * `a *l s`: for `left_coset a s`. * `a +l s`: for `left_add_coset a s`. * `s *r a`: for `right_coset s a`. * `s +r a`: for `right_add_coset s a`. ## TODO Add `to_additive` to `preimage_mk_equiv_subgroup_times_set`. -/ open set function variable {α : Type*} /-- The left coset `a * s` for an element `a : α` and a subset `s : set α` -/ @[to_additive left_add_coset "The left coset `a+s` for an element `a : α` and a subset `s : set α`"] def left_coset [has_mul α] (a : α) (s : set α) : set α := (λ x, a * x) '' s /-- The right coset `s * a` for an element `a : α` and a subset `s : set α` -/ @[to_additive right_add_coset "The right coset `s+a` for an element `a : α` and a subset `s : set α`"] def right_coset [has_mul α] (s : set α) (a : α) : set α := (λ x, x * a) '' s localized "infix ` *l `:70 := left_coset" in coset localized "infix ` +l `:70 := left_add_coset" in coset localized "infix ` *r `:70 := right_coset" in coset localized "infix ` +r `:70 := right_add_coset" in coset section coset_mul variable [has_mul α] @[to_additive mem_left_add_coset] lemma mem_left_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ a *l s := mem_image_of_mem (λ b : α, a * b) hxS @[to_additive mem_right_add_coset] lemma mem_right_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ s *r a := mem_image_of_mem (λ b : α, b * a) hxS /-- Equality of two left cosets `a * s` and `b * s`. -/ @[to_additive left_add_coset_equivalence "Equality of two left cosets `a + s` and `b + s`."] def left_coset_equivalence (s : set α) (a b : α) := a *l s = b *l s @[to_additive left_add_coset_equivalence_rel] lemma left_coset_equivalence_rel (s : set α) : equivalence (left_coset_equivalence s) := mk_equivalence (left_coset_equivalence s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) /-- Equality of two right cosets `s * a` and `s * b`. -/ @[to_additive right_add_coset_equivalence "Equality of two right cosets `s + a` and `s + b`."] def right_coset_equivalence (s : set α) (a b : α) := s *r a = s *r b @[to_additive right_add_coset_equivalence_rel] lemma right_coset_equivalence_rel (s : set α) : equivalence (right_coset_equivalence s) := mk_equivalence (right_coset_equivalence s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) end coset_mul section coset_semigroup variable [semigroup α] @[simp] lemma left_coset_assoc (s : set α) (a b : α) : a *l (b *l s) = (a * b) *l s := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] attribute [to_additive left_add_coset_assoc] left_coset_assoc @[simp] lemma right_coset_assoc (s : set α) (a b : α) : s *r a *r b = s *r (a * b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] attribute [to_additive right_add_coset_assoc] right_coset_assoc @[to_additive left_add_coset_right_add_coset] lemma left_coset_right_coset (s : set α) (a b : α) : a *l s *r b = a *l (s *r b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] end coset_semigroup section coset_monoid variables [monoid α] (s : set α) @[simp] lemma one_left_coset : 1 *l s = s := set.ext $ by simp [left_coset] attribute [to_additive zero_left_add_coset] one_left_coset @[simp] lemma right_coset_one : s *r 1 = s := set.ext $ by simp [right_coset] attribute [to_additive right_add_coset_zero] right_coset_one end coset_monoid section coset_submonoid open submonoid variables [monoid α] (s : submonoid α) @[to_additive mem_own_left_add_coset] lemma mem_own_left_coset (a : α) : a ∈ a *l s := suffices a * 1 ∈ a *l s, by simpa, mem_left_coset a (one_mem s) @[to_additive mem_own_right_add_coset] lemma mem_own_right_coset (a : α) : a ∈ (s : set α) *r a := suffices 1 * a ∈ (s : set α) *r a, by simpa, mem_right_coset a (one_mem s) @[to_additive mem_left_add_coset_left_add_coset] lemma mem_left_coset_left_coset {a : α} (ha : a *l s = s) : a ∈ s := by rw [←set_like.mem_coe, ←ha]; exact mem_own_left_coset s a @[to_additive mem_right_add_coset_right_add_coset] lemma mem_right_coset_right_coset {a : α} (ha : (s : set α) *r a = s) : a ∈ s := by rw [←set_like.mem_coe, ←ha]; exact mem_own_right_coset s a end coset_submonoid section coset_group variables [group α] {s : set α} {x : α} @[to_additive mem_left_add_coset_iff] lemma mem_left_coset_iff (a : α) : x ∈ a *l s ↔ a⁻¹ * x ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨a⁻¹ * x, h, by simp⟩) @[to_additive mem_right_add_coset_iff] lemma mem_right_coset_iff (a : α) : x ∈ s *r a ↔ x * a⁻¹ ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨x * a⁻¹, h, by simp⟩) end coset_group section coset_subgroup open subgroup variables [group α] (s : subgroup α) @[to_additive left_add_coset_mem_left_add_coset] lemma left_coset_mem_left_coset {a : α} (ha : a ∈ s) : a *l s = s := set.ext $ by simp [mem_left_coset_iff, mul_mem_cancel_left s (s.inv_mem ha)] @[to_additive right_add_coset_mem_right_add_coset] lemma right_coset_mem_right_coset {a : α} (ha : a ∈ s) : (s : set α) *r a = s := set.ext $ assume b, by simp [mem_right_coset_iff, mul_mem_cancel_right s (s.inv_mem ha)] @[to_additive eq_add_cosets_of_normal] theorem eq_cosets_of_normal (N : s.normal) (g : α) : g *l s = s *r g := set.ext $ assume a, by simp [mem_left_coset_iff, mem_right_coset_iff]; rw [N.mem_comm_iff] @[to_additive normal_of_eq_add_cosets] theorem normal_of_eq_cosets (h : ∀ g : α, g *l s = s *r g) : s.normal := ⟨assume a ha g, show g * a * g⁻¹ ∈ (s : set α), by rw [← mem_right_coset_iff, ← h]; exact mem_left_coset g ha⟩ @[to_additive normal_iff_eq_add_cosets] theorem normal_iff_eq_cosets : s.normal ↔ ∀ g : α, g *l s = s *r g := ⟨@eq_cosets_of_normal _ _ s, normal_of_eq_cosets s⟩ end coset_subgroup run_cmd to_additive.map_namespace `quotient_group `quotient_add_group namespace quotient_group /-- The equivalence relation corresponding to the partition of a group by left cosets of a subgroup.-/ @[to_additive "The equivalence relation corresponding to the partition of a group by left cosets of a subgroup."] def left_rel [group α] (s : subgroup α) : setoid α := ⟨λ x y, x⁻¹ * y ∈ s, assume x, by simp [s.one_mem], assume x y hxy, have (x⁻¹ * y)⁻¹ ∈ s, from s.inv_mem hxy, by simpa using this, assume x y z hxy hyz, have x⁻¹ * y * (y⁻¹ * z) ∈ s, from s.mul_mem hxy hyz, by simpa [mul_assoc] using this⟩ @[to_additive] instance left_rel_decidable [group α] (s : subgroup α) [d : decidable_pred (λ a, a ∈ s)] : decidable_rel (left_rel s).r := λ _ _, d _ /-- `quotient s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `quotient s` is a group -/ def quotient [group α] (s : subgroup α) : Type* := quotient (left_rel s) /-- The equivalence relation corresponding to the partition of a group by right cosets of a subgroup. -/ @[to_additive "The equivalence relation corresponding to the partition of a group by right cosets of a subgroup."] def right_rel [group α] (s : subgroup α) : setoid α := ⟨λ x y, y * x⁻¹ ∈ s, assume x, by simp [s.one_mem], assume x y hxy, have (y * x⁻¹)⁻¹ ∈ s, from s.inv_mem hxy, by simpa using this, assume x y z hxy hyz, have (z * y⁻¹) * (y * x⁻¹) ∈ s, from s.mul_mem hyz hxy, by simpa [mul_assoc] using this⟩ @[to_additive] instance right_rel_decidable [group α] (s : subgroup α) [d : decidable_pred (λ a, a ∈ s)] : decidable_rel (left_rel s).r := λ _ _, d _ end quotient_group namespace quotient_add_group /-- `quotient s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `quotient s` is a group -/ def quotient [add_group α] (s : add_subgroup α) : Type* := quotient (left_rel s) end quotient_add_group attribute [to_additive quotient_add_group.quotient] quotient_group.quotient namespace quotient_group variables [group α] {s : subgroup α} @[to_additive] instance fintype [fintype α] (s : subgroup α) [decidable_rel (left_rel s).r] : fintype (quotient_group.quotient s) := quotient.fintype (left_rel s) /-- The canonical map from a group `α` to the quotient `α/s`. -/ @[to_additive "The canonical map from an `add_group` `α` to the quotient `α/s`."] abbreviation mk (a : α) : quotient s := quotient.mk' a @[elab_as_eliminator, to_additive] lemma induction_on {C : quotient s → Prop} (x : quotient s) (H : ∀ z, C (quotient_group.mk z)) : C x := quotient.induction_on' x H @[to_additive] instance : has_coe_t α (quotient s) := ⟨mk⟩ -- note [use has_coe_t] @[elab_as_eliminator, to_additive] lemma induction_on' {C : quotient s → Prop} (x : quotient s) (H : ∀ z : α, C z) : C x := quotient.induction_on' x H @[to_additive] instance (s : subgroup α) : inhabited (quotient s) := ⟨((1 : α) : quotient s)⟩ @[to_additive quotient_add_group.eq] protected lemma eq {a b : α} : (a : quotient s) = b ↔ a⁻¹ * b ∈ s := quotient.eq' @[to_additive] lemma eq_class_eq_left_coset (s : subgroup α) (g : α) : {x : α | (x : quotient s) = g} = left_coset g s := set.ext $ λ z, by { rw [mem_left_coset_iff, set.mem_set_of_eq, eq_comm, quotient_group.eq], simp } @[to_additive] lemma preimage_image_coe (N : subgroup α) (s : set α) : coe ⁻¹' ((coe : α → quotient N) '' s) = ⋃ x : N, (λ y : α, y * x) ⁻¹' s := begin ext x, simp only [quotient_group.eq, set_like.exists, exists_prop, set.mem_preimage, set.mem_Union, set.mem_image, subgroup.coe_mk, ← eq_inv_mul_iff_mul_eq], exact ⟨λ ⟨y, hs, hN⟩, ⟨_, N.inv_mem hN, by simpa using hs⟩, λ ⟨z, hz, hxz⟩, ⟨x*z, hxz, by simpa using hz⟩⟩, end end quotient_group namespace subgroup open quotient_group variables [group α] {s : subgroup α} /-- The natural bijection between a left coset `g * s` and `s`. -/ @[to_additive "The natural bijection between the cosets `g + s` and `s`."] def left_coset_equiv_subgroup (g : α) : left_coset g s ≃ s := ⟨λ x, ⟨g⁻¹ * x.1, (mem_left_coset_iff _).1 x.2⟩, λ x, ⟨g * x.1, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ /-- The natural bijection between a right coset `s * g` and `s`. -/ @[to_additive "The natural bijection between the cosets `s + g` and `s`."] def right_coset_equiv_subgroup (g : α) : right_coset ↑s g ≃ s := ⟨λ x, ⟨x.1 * g⁻¹, (mem_right_coset_iff _).1 x.2⟩, λ x, ⟨x.1 * g, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ /-- A (non-canonical) bijection between a group `α` and the product `(α/s) × s` -/ @[to_additive "A (non-canonical) bijection between an add_group `α` and the product `(α/s) × s`"] noncomputable def group_equiv_quotient_times_subgroup : α ≃ quotient s × s := calc α ≃ Σ L : quotient s, {x : α // (x : quotient s) = L} : (equiv.sigma_preimage_equiv quotient_group.mk).symm ... ≃ Σ L : quotient s, left_coset (quotient.out' L) s : equiv.sigma_congr_right (λ L, begin rw ← eq_class_eq_left_coset, show _root_.subtype (λ x : α, quotient.mk' x = L) ≃ _root_.subtype (λ x : α, quotient.mk' x = quotient.mk' _), simp [-quotient.eq'], end) ... ≃ Σ L : quotient s, s : equiv.sigma_congr_right (λ L, left_coset_equiv_subgroup _) ... ≃ quotient s × s : equiv.sigma_equiv_prod _ _ lemma card_eq_card_quotient_mul_card_subgroup [fintype α] (s : subgroup α) [fintype s] [decidable_pred (λ a, a ∈ s)] : fintype.card α = fintype.card (quotient s) * fintype.card s := by rw ← fintype.card_prod; exact fintype.card_congr (subgroup.group_equiv_quotient_times_subgroup) lemma card_subgroup_dvd_card [fintype α] (s : subgroup α) [fintype s] : fintype.card s ∣ fintype.card α := by haveI := classical.prop_decidable; simp [card_eq_card_quotient_mul_card_subgroup s] lemma card_quotient_dvd_card [fintype α] (s : subgroup α) [decidable_pred (λ a, a ∈ s)] [fintype s] : fintype.card (quotient s) ∣ fintype.card α := by simp [card_eq_card_quotient_mul_card_subgroup s] end subgroup namespace quotient_group variables [group α] -- FIXME -- why is there no `to_additive`? /-- If `s` is a subgroup of the group `α`, and `t` is a subset of `α/s`, then there is a (typically non-canonical) bijection between the preimage of `t` in `α` and the product `s × t`. -/ noncomputable def preimage_mk_equiv_subgroup_times_set (s : subgroup α) (t : set (quotient s)) : quotient_group.mk ⁻¹' t ≃ s × t := have h : ∀ {x : quotient s} {a : α}, x ∈ t → a ∈ s → (quotient.mk' (quotient.out' x * a) : quotient s) = quotient.mk' (quotient.out' x) := λ x a hx ha, quotient.sound' (show (quotient.out' x * a)⁻¹ * quotient.out' x ∈ s, from (s.inv_mem_iff).1 $ by rwa [mul_inv_rev, inv_inv, ← mul_assoc, inv_mul_self, one_mul]), { to_fun := λ ⟨a, ha⟩, ⟨⟨(quotient.out' (quotient.mk' a))⁻¹ * a, @quotient.exact' _ (left_rel s) _ _ $ (quotient.out_eq' _)⟩, ⟨quotient.mk' a, ha⟩⟩, inv_fun := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, ⟨quotient.out' x * a, show quotient.mk' _ ∈ t, by simp [h hx ha, hx]⟩, left_inv := λ ⟨a, ha⟩, subtype.eq $ show _ * _ = a, by simp, right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, show (_, _) = _, by simp [h hx ha] } end quotient_group /-- We use the class `has_coe_t` instead of `has_coe` if the first argument is a variable, or if the second argument is a variable not occurring in the first. Using `has_coe` would cause looping of type-class inference. See <https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/remove.20all.20instances.20with.20variable.20domain> -/ library_note "use has_coe_t"
bb1ed1a2afb53d1330690c4de82f6f3026467ab3
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/isomorphisms.lean
ee1181632dcacba663cfda6ffff9b2f82d63cb1a
[ "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
5,891
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov -/ import linear_algebra.quotient /-! # Isomorphism theorems for modules. * The Noether's first, second, and third isomorphism theorems for modules are proved as `linear_map.quot_ker_equiv_range`, `linear_map.quotient_inf_equiv_sup_quotient` and `submodule.quotient_quotient_equiv_quotient`. -/ universes u v variables {R M M₂ M₃ : Type*} variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-! The first and second isomorphism theorems for modules. -/ namespace linear_map open submodule section isomorphism_laws /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range := (linear_equiv.of_injective (f.ker.liftq f $ le_refl _) $ ker_eq_bot.mp $ submodule.ker_liftq_eq_bot _ _ _ (le_refl f.ker)).trans (linear_equiv.of_eq _ _ $ submodule.range_liftq _ _ _) /-- The first isomorphism theorem for surjective linear maps. -/ noncomputable def quot_ker_equiv_of_surjective (f : M →ₗ[R] M₂) (hf : function.surjective f) : f.ker.quotient ≃ₗ[R] M₂ := f.quot_ker_equiv_range.trans (linear_equiv.of_top f.range (linear_map.range_eq_top.2 hf)) @[simp] lemma quot_ker_equiv_range_apply_mk (x : M) : (f.quot_ker_equiv_range (submodule.quotient.mk x) : M₂) = f x := rfl @[simp] lemma quot_ker_equiv_range_symm_apply_image (x : M) (h : f x ∈ f.range) : f.quot_ker_equiv_range.symm ⟨f x, h⟩ = f.ker.mkq x := f.quot_ker_equiv_range.symm_apply_apply (f.ker.mkq x) /-- Canonical linear map from the quotient `p/(p ∩ p')` to `(p+p')/p'`, mapping `x + (p ∩ p')` to `x + p'`, where `p` and `p'` are submodules of an ambient module. -/ def quotient_inf_to_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient := (comap p.subtype (p ⊓ p')).liftq ((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype], exact comap_mono (inf_le_inf_right _ le_sup_left) end /-- Second Isomorphism Law : the canonical map from `p/(p ∩ p')` to `(p+p')/p'` as a linear isomorphism. -/ noncomputable def quotient_inf_equiv_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient := linear_equiv.of_bijective (quotient_inf_to_sup_quotient p p') begin rw [← ker_eq_bot, quotient_inf_to_sup_quotient, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], exact λ ⟨x, hx1⟩ hx2, ⟨hx1, hx2⟩ end begin rw [← range_eq_top, quotient_inf_to_sup_quotient, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end @[simp] lemma coe_quotient_inf_to_sup_quotient (p p' : submodule R M) : ⇑(quotient_inf_to_sup_quotient p p') = quotient_inf_equiv_sup_quotient p p' := rfl @[simp] lemma quotient_inf_equiv_sup_quotient_apply_mk (p p' : submodule R M) (x : p) : quotient_inf_equiv_sup_quotient p p' (submodule.quotient.mk x) = submodule.quotient.mk (of_le (le_sup_left : p ≤ p ⊔ p') x) := rfl lemma quotient_inf_equiv_sup_quotient_symm_apply_left (p p' : submodule R M) (x : p ⊔ p') (hx : (x:M) ∈ p) : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = submodule.quotient.mk ⟨x, hx⟩ := (linear_equiv.symm_apply_eq _).2 $ by simp [of_le_apply] @[simp] lemma quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff {p p' : submodule R M} {x : p ⊔ p'} : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 ↔ (x:M) ∈ p' := (linear_equiv.symm_apply_eq _).trans $ by simp [of_le_apply] lemma quotient_inf_equiv_sup_quotient_symm_apply_right (p p' : submodule R M) {x : p ⊔ p'} (hx : (x:M) ∈ p') : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 := quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff.2 hx end isomorphism_laws end linear_map /-! The third isomorphism theorem for modules. -/ namespace submodule variables (S T : submodule R M) (h : S ≤ T) /-- The map from the third isomorphism theorem for modules: `(M / S) / (T / S) → M / T`. -/ def quotient_quotient_equiv_quotient_aux : quotient (T.map S.mkq) →ₗ[R] quotient T := liftq _ (mapq S T linear_map.id h) (by { rintro _ ⟨x, hx, rfl⟩, rw [linear_map.mem_ker, mkq_apply, mapq_apply], exact (quotient.mk_eq_zero _).mpr hx }) @[simp] lemma quotient_quotient_equiv_quotient_aux_mk (x : S.quotient) : quotient_quotient_equiv_quotient_aux S T h (quotient.mk x) = mapq S T linear_map.id h x := liftq_apply _ _ _ @[simp] lemma quotient_quotient_equiv_quotient_aux_mk_mk (x : M) : quotient_quotient_equiv_quotient_aux S T h (quotient.mk (quotient.mk x)) = quotient.mk x := by rw [quotient_quotient_equiv_quotient_aux_mk, mapq_apply, linear_map.id_apply] /-- **Noether's third isomorphism theorem** for modules: `(M / S) / (T / S) ≃ M / T`. -/ def quotient_quotient_equiv_quotient : quotient (T.map S.mkq) ≃ₗ[R] quotient T := { to_fun := quotient_quotient_equiv_quotient_aux S T h, inv_fun := mapq _ _ (mkq S) (le_comap_map _ _), left_inv := λ x, quotient.induction_on' x $ λ x, quotient.induction_on' x $ λ x, by simp, right_inv := λ x, quotient.induction_on' x $ λ x, by simp, .. quotient_quotient_equiv_quotient_aux S T h } end submodule
bf4d148bfd6d3a3b6bf9de05d5f2d6b5d1c1afac
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/projective_space/subspace.lean
d15d8c751ec4a0f1d00b29eca0ebe0dcee42a786
[ "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
8,298
lean
/- Copyright (c) 2022 Michael Blyth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Blyth -/ import linear_algebra.projective_space.basic /-! # Subspaces of Projective Space In this file we define subspaces of a projective space, and show that the subspaces of a projective space form a complete lattice under inclusion. ## Implementation Details A subspace of a projective space ℙ K V is defined to be a structure consisting of a subset of ℙ K V such that if two nonzero vectors in V determine points in ℙ K V which are in the subset, and the sum of the two vectors is nonzero, then the point determined by the sum of the two vectors is also in the subset. ## Results - There is a Galois insertion between the subsets of points of a projective space and the subspaces of the projective space, which is given by taking the span of the set of points. - The subspaces of a projective space form a complete lattice under inclusion. # Future Work - Show that there is a one-to-one order-preserving correspondence between subspaces of a projective space and the submodules of the underlying vector space. -/ variables (K V : Type*) [field K] [add_comm_group V] [module K V] namespace projectivization /-- A subspace of a projective space is a structure consisting of a set of points such that: If two nonzero vectors determine points which are in the set, and the sum of the two vectors is nonzero, then the point determined by the sum is also in the set. -/ @[ext] structure subspace := (carrier : set (ℙ K V)) (mem_add' (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) (hvw : v + w ≠ 0) : mk K v hv ∈ carrier → mk K w hw ∈ carrier → mk K (v + w) (hvw) ∈ carrier) namespace subspace variables {K V} instance : set_like (subspace K V) (ℙ K V) := { coe := carrier, coe_injective' := λ A B, by { cases A, cases B, simp } } @[simp] lemma mem_carrier_iff (A : subspace K V) (x : ℙ K V) : x ∈ A.carrier ↔ x ∈ A := iff.refl _ lemma mem_add (T : subspace K V) (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) (hvw : v + w ≠ 0) : projectivization.mk K v hv ∈ T → projectivization.mk K w hw ∈ T → projectivization.mk K (v + w) (hvw) ∈ T := T.mem_add' v w hv hw hvw /-- The span of a set of points in a projective space is defined inductively to be the set of points which contains the original set, and contains all points determined by the (nonzero) sum of two nonzero vectors, each of which determine points in the span. -/ inductive span_carrier (S : set (ℙ K V)) : set (ℙ K V) | of (x : ℙ K V) (hx : x ∈ S) : span_carrier x | mem_add (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) (hvw : v + w ≠ 0) : span_carrier (projectivization.mk K v hv) → span_carrier (projectivization.mk K w hw) → span_carrier (projectivization.mk K (v + w) (hvw)) /-- The span of a set of points in projective space is a subspace. -/ def span (S : set (ℙ K V)) : subspace K V := { carrier := span_carrier S, mem_add' := λ v w hv hw hvw, span_carrier.mem_add v w hv hw hvw } /-- The span of a set of points contains the set of points. -/ lemma subset_span (S : set (ℙ K V)) : S ⊆ span S := λ x hx, span_carrier.of _ hx /-- The span of a set of points is a Galois insertion between sets of points of a projective space and subspaces of the projective space. -/ def gi : galois_insertion (span : set (ℙ K V) → subspace K V) coe := { choice := λ S hS, span S, gc := λ A B, ⟨λ h, le_trans (subset_span _) h, begin intros h x hx, induction hx, { apply h, assumption }, { apply B.mem_add, assumption' } end⟩, le_l_u := λ S, subset_span _, choice_eq := λ _ _, rfl } /-- The span of a subspace is the subspace. -/ @[simp] lemma span_coe (W : subspace K V) : span ↑W = W := galois_insertion.l_u_eq gi W /-- The infimum of two subspaces exists. -/ instance has_inf : has_inf (subspace K V) := ⟨λ A B, ⟨A ⊓ B, λ v w hv hw hvw h1 h2, ⟨A.mem_add _ _ hv hw _ h1.1 h2.1, B.mem_add _ _ hv hw _ h1.2 h2.2⟩⟩⟩ /-- Infimums of arbitrary collections of subspaces exist. -/ instance has_Inf : has_Inf (subspace K V) := ⟨λ A, ⟨Inf (coe '' A), λ v w hv hw hvw h1 h2 t, begin rintro ⟨s, hs, rfl⟩, exact s.mem_add v w hv hw _ (h1 s ⟨s, hs, rfl⟩) (h2 s ⟨s, hs, rfl⟩), end⟩⟩ /-- The subspaces of a projective space form a complete lattice. -/ instance : complete_lattice (subspace K V) := { inf_le_left := λ A B x hx, by exact hx.1, inf_le_right := λ A B x hx, by exact hx.2, le_inf := λ A B C h1 h2 x hx, ⟨h1 hx, h2 hx⟩, ..(infer_instance : has_inf _), ..complete_lattice_of_Inf (subspace K V) begin refine λ s, ⟨λ a ha x hx, (hx _ ⟨a, ha, rfl⟩), λ a ha x hx E, _⟩, rintros ⟨E, hE, rfl⟩, exact (ha hE hx) end } instance subspace_inhabited : inhabited (subspace K V) := { default := ⊤ } /-- The span of the empty set is the bottom of the lattice of subspaces. -/ @[simp] lemma span_empty : span (∅ : set (ℙ K V)) = ⊥ := gi.gc.l_bot /-- The span of the entire projective space is the top of the lattice of subspaces. -/ @[simp] lemma span_univ : span (set.univ : set (ℙ K V)) = ⊤ := by { rw [eq_top_iff, set_like.le_def], intros x hx, exact subset_span _ (set.mem_univ x) } /-- The span of a set of points is contained in a subspace if and only if the set of points is contained in the subspace. -/ lemma span_le_subspace_iff {S : set (ℙ K V)} {W : subspace K V} : span S ≤ W ↔ S ⊆ W := gi.gc S W /-- If a set of points is a subset of another set of points, then its span will be contained in the span of that set. -/ @[mono] lemma monotone_span : monotone (span : set (ℙ K V) → subspace K V) := gi.gc.monotone_l lemma subset_span_trans {S T U : set (ℙ K V)} (hST : S ⊆ span T) (hTU : T ⊆ span U) : S ⊆ span U := gi.gc.le_u_l_trans hST hTU /-- The supremum of two subspaces is equal to the span of their union. -/ lemma span_union (S T : set (ℙ K V)) : span (S ∪ T) = span S ⊔ span T := (@gi K V _ _ _).gc.l_sup /-- The supremum of a collection of subspaces is equal to the span of the union of the collection. -/ lemma span_Union {ι} (s : ι → set (ℙ K V)) : span (⋃ i, s i) = ⨆ i, span (s i) := (@gi K V _ _ _).gc.l_supr /-- The supremum of a subspace and the span of a set of points is equal to the span of the union of the subspace and the set of points. -/ lemma sup_span {S : set (ℙ K V)} {W : subspace K V} : W ⊔ span S = span (W ∪ S) := by rw [span_union, span_coe] lemma span_sup {S : set (ℙ K V)} {W : subspace K V}: span S ⊔ W = span (S ∪ W) := by rw [span_union, span_coe] /-- A point in a projective space is contained in the span of a set of points if and only if the point is contained in all subspaces of the projective space which contain the set of points. -/ lemma mem_span {S : set (ℙ K V)} (u : ℙ K V) : u ∈ span S ↔ ∀ (W : subspace K V), S ⊆ W → u ∈ W := by { simp_rw ← span_le_subspace_iff, exact ⟨λ hu W hW, hW hu, λ W, W (span S) (le_refl _)⟩ } /-- The span of a set of points in a projective space is equal to the infimum of the collection of subspaces which contain the set. -/ lemma span_eq_Inf {S : set (ℙ K V)} : span S = Inf {W | S ⊆ W} := begin ext, simp_rw [mem_carrier_iff, mem_span x], refine ⟨λ hx, _, λ hx W hW, _⟩, { rintros W ⟨T, ⟨hT, rfl⟩⟩, exact (hx T hT) }, { exact (@Inf_le _ _ {W : subspace K V | S ⊆ ↑W} W hW) x hx }, end /-- If a set of points in projective space is contained in a subspace, and that subspace is contained in the span of the set of points, then the span of the set of points is equal to the subspace. -/ lemma span_eq_of_le {S : set (ℙ K V)} {W : subspace K V} (hS : S ⊆ W) (hW : W ≤ span S) : span S = W := le_antisymm (span_le_subspace_iff.mpr hS) hW /-- The spans of two sets of points in a projective space are equal if and only if each set of points is contained in the span of the other set. -/ lemma span_eq_span_iff {S T : set (ℙ K V)} : span S = span T ↔ S ⊆ span T ∧ T ⊆ span S := ⟨λ h, ⟨h ▸ subset_span S, h.symm ▸ subset_span T⟩, λ h, le_antisymm (span_le_subspace_iff.2 h.1) (span_le_subspace_iff.2 h.2)⟩ end subspace end projectivization
4f453c8e31b740c4f7a615656d0694b5a389cbb3
e6b8240a90527fd55d42d0ec6649253d5d0bd414
/src/topology/metric_space/closeds.lean
656f3b42721c3e3e3af9a21b0aeee7f99c51f92c
[ "Apache-2.0" ]
permissive
mattearnshaw/mathlib
ac90f9fb8168aa642223bea3ffd0286b0cfde44f
d8dc1445cf8a8c74f8df60b9f7a1f5cf10946666
refs/heads/master
1,606,308,351,137
1,576,594,130,000
1,576,594,130,000
228,666,195
0
0
Apache-2.0
1,576,603,094,000
1,576,603,093,000
null
UTF-8
Lean
false
false
22,489
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import topology.metric_space.hausdorff_distance topology.opens /-! # Closed subsets This file defines the metric and emetric space structure on the types of closed subsets and nonempty compact subsets of a metric or emetric space. The Hausdorff distance induces an emetric space structure on the type of closed subsets of an emetric space, called `closeds`. Its completeness, resp. compactness, resp. second-countability, follow from the corresponding properties of the original space. In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is always finite in this context. -/ noncomputable theory open_locale classical open_locale topological_space universe u open classical lattice set function topological_space filter namespace emetric section variables {α : Type u} [emetric_space α] {s : set α} /-- In emetric spaces, the Hausdorff edistance defines an emetric space structure on the type of closed subsets -/ instance closeds.emetric_space : emetric_space (closeds α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq ((Hausdorff_edist_zero_iff_eq_of_closed s.property t.property).1 h) } /-- The edistance to a closed set depends continuously on the point and the set -/ lemma continuous_inf_edist_Hausdorff_edist : continuous (λp : α × (closeds α), inf_edist p.1 (p.2).val) := begin refine continuous_of_le_add_edist 2 (by simp) _, rintros ⟨x, s⟩ ⟨y, t⟩, calc inf_edist x (s.val) ≤ inf_edist x (t.val) + Hausdorff_edist (t.val) (s.val) : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ (inf_edist y (t.val) + edist x y) + Hausdorff_edist (t.val) (s.val) : add_le_add_right' inf_edist_le_inf_edist_add_edist ... = inf_edist y (t.val) + (edist x y + Hausdorff_edist (s.val) (t.val)) : by simp [add_comm, Hausdorff_edist_comm] ... ≤ inf_edist y (t.val) + (edist (x, s) (y, t) + edist (x, s) (y, t)) : add_le_add_left' (add_le_add' (by simp [edist, le_refl]) (by simp [edist, le_refl])) ... = inf_edist y (t.val) + 2 * edist (x, s) (y, t) : by rw [← mul_two, mul_comm] end /-- Subsets of a given closed subset form a closed set -/ lemma is_closed_subsets_of_is_closed (hs : is_closed s) : is_closed {t : closeds α | t.val ⊆ s} := begin refine is_closed_of_closure_subset (λt ht x hx, _), -- t : closeds α, ht : t ∈ closure {t : closeds α | t.val ⊆ s}, -- x : α, hx : x ∈ t.val -- goal : x ∈ s have : x ∈ closure s, { refine mem_closure_iff'.2 (λε εpos, _), rcases mem_closure_iff'.1 ht ε εpos with ⟨u, hu, Dtu⟩, -- u : closeds α, hu : u ∈ {t : closeds α | t.val ⊆ s}, hu' : edist t u < ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dtu with ⟨y, hy, Dxy⟩, -- y : α, hy : y ∈ u.val, Dxy : edist x y < ε exact ⟨y, hu hy, Dxy⟩ }, rwa closure_eq_of_is_closed hs at this, end /-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/ lemma closeds.edist_eq {s t : closeds α} : edist s t = Hausdorff_edist s.val t.val := rfl /-- In a complete space, the type of closed subsets is complete for the Hausdorff edistance. -/ instance closeds.complete_space [complete_space α] : complete_space (closeds α) := begin /- We will show that, if a sequence of sets `s n` satisfies `edist (s n) (s (n+1)) < 2^{-n}`, then it converges. This is enough to guarantee completeness, by a standard completeness criterion. We use the shorthand `B n = 2^{-n}` in ennreal. -/ let B : ℕ → ennreal := λ n, (2⁻¹)^n, have B_pos : ∀ n, (0:ennreal) < B n, by simp [B, ennreal.pow_pos], have B_ne_top : ∀ n, B n ≠ ⊤, by simp [B, ennreal.div_def, ennreal.pow_ne_top], /- Consider a sequence of closed sets `s n` with `edist (s n) (s (n+1)) < B n`. We will show that it converges. The limit set is t0 = ⋂n, closure (⋃m≥n, s m). We will have to show that a point in `s n` is close to a point in `t0`, and a point in `t0` is close to a point in `s n`. The completeness then follows from a standard criterion. -/ refine complete_of_convergent_controlled_sequences B B_pos (λs hs, _), let t0 := ⋂n, closure (⋃m≥n, (s m).val), let t : closeds α := ⟨t0, is_closed_Inter (λ_, is_closed_closure)⟩, use t, -- The inequality is written this way to agree with `edist_le_of_edist_le_geometric_of_tendsto₀` have I1 : ∀n:ℕ, ∀x ∈ (s n).val, ∃y ∈ t0, edist x y ≤ 2 * B n, { /- This is the main difficulty of the proof. Starting from `x ∈ s n`, we want to find a point in `t0` which is close to `x`. Define inductively a sequence of points `z m` with `z n = x` and `z m ∈ s m` and `edist (z m) (z (m+1)) ≤ B m`. This is possible since the Hausdorff distance between `s m` and `s (m+1)` is at most `B m`. This sequence is a Cauchy sequence, therefore converging as the space is complete, to a limit which satisfies the required properties. -/ assume n x hx, obtain ⟨z, hz₀, hz⟩ : ∃ z : Π l, (s (n+l)).val, (z 0:α) = x ∧ ∀ k, edist (z k:α) (z (k+1):α) ≤ B n / 2^k, { -- We prove existence of the sequence by induction. have : ∀ (l : ℕ) (z : (s (n+l)).val), ∃ z' : (s (n+l+1)).val, edist (z:α) z' ≤ B n / 2^l, { assume l z, obtain ⟨z', z'_mem, hz'⟩ : ∃ z' ∈ (s (n+l+1)).val, edist (z:α) z' < B n / 2^l, { apply exists_edist_lt_of_Hausdorff_edist_lt z.2, simp only [B, ennreal.div_def, ennreal.inv_pow'], rw [← pow_add], apply hs; simp }, exact ⟨⟨z', z'_mem⟩, le_of_lt hz'⟩ }, use [λ k, nat.rec_on k ⟨x, hx⟩ (λl z, some (this l z)), rfl], exact λ k, some_spec (this k _) }, -- it follows from the previous bound that `z` is a Cauchy sequence have : cauchy_seq (λ k, ((z k):α)), from cauchy_seq_of_edist_le_geometric_two (B n) (B_ne_top n) hz, -- therefore, it converges rcases cauchy_seq_tendsto_of_complete this with ⟨y, y_lim⟩, use y, -- the limit point `y` will be the desired point, in `t0` and close to our initial point `x`. -- First, we check it belongs to `t0`. have : y ∈ t0 := mem_Inter.2 (λk, mem_closure_of_tendsto (by simp) y_lim begin simp only [exists_prop, set.mem_Union, filter.mem_at_top_sets, set.mem_preimage, set.preimage_Union], exact ⟨k, λ m hm, ⟨n+m, zero_add k ▸ add_le_add (zero_le n) hm, (z m).2⟩⟩ end), use this, -- Then, we check that `y` is close to `x = z n`. This follows from the fact that `y` -- is the limit of `z k`, and the distance between `z n` and `z k` has already been estimated. rw [← hz₀], exact edist_le_of_edist_le_geometric_two_of_tendsto₀ (B n) hz y_lim }, have I2 : ∀n:ℕ, ∀x ∈ t0, ∃y ∈ (s n).val, edist x y ≤ 2 * B n, { /- For the (much easier) reverse inequality, we start from a point `x ∈ t0` and we want to find a point `y ∈ s n` which is close to `x`. `x` belongs to `t0`, the intersection of the closures. In particular, it is well approximated by a point `z` in `⋃m≥n, s m`, say in `s m`. Since `s m` and `s n` are close, this point is itself well approximated by a point `y` in `s n`, as required. -/ assume n x xt0, have : x ∈ closure (⋃m≥n, (s m).val), by apply mem_Inter.1 xt0 n, rcases mem_closure_iff'.1 this (B n) (B_pos n) with ⟨z, hz, Dxz⟩, -- z : α, Dxz : edist x z < B n, simp only [exists_prop, set.mem_Union] at hz, rcases hz with ⟨m, ⟨m_ge_n, hm⟩⟩, -- m : ℕ, m_ge_n : m ≥ n, hm : z ∈ (s m).val have : Hausdorff_edist (s m).val (s n).val < B n := hs n m n m_ge_n (le_refl n), rcases exists_edist_lt_of_Hausdorff_edist_lt hm this with ⟨y, hy, Dzy⟩, -- y : α, hy : y ∈ (s n).val, Dzy : edist z y < B n exact ⟨y, hy, calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... ≤ B n + B n : add_le_add' (le_of_lt Dxz) (le_of_lt Dzy) ... = 2 * B n : (two_mul _).symm ⟩ }, -- Deduce from the above inequalities that the distance between `s n` and `t0` is at most `2 B n`. have main : ∀n:ℕ, edist (s n) t ≤ 2 * B n := λn, Hausdorff_edist_le_of_mem_edist (I1 n) (I2 n), -- from this, the convergence of `s n` to `t0` follows. refine (tendsto_at_top _).2 (λε εpos, _), have : tendsto (λn, 2 * B n) at_top (𝓝 (2 * 0)), from ennreal.tendsto.mul_right (ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 $ by simp [ennreal.one_lt_two]) (or.inr $ by simp), rw mul_zero at this, have Z := (tendsto_orderable.1 this).2 ε εpos, simp only [filter.mem_at_top_sets, set.mem_set_of_eq] at Z, rcases Z with ⟨N, hN⟩, -- ∀ (b : ℕ), b ≥ N → ε > 2 * B b exact ⟨N, λn hn, lt_of_le_of_lt (main n) (hN n hn)⟩ end /-- In a compact space, the type of closed subsets is compact. -/ instance closeds.compact_space [compact_space α] : compact_space (closeds α) := ⟨begin /- by completeness, it suffices to show that it is totally bounded, i.e., for all ε>0, there is a finite set which is ε-dense. start from a set `s` which is ε-dense in α. Then the subsets of `s` are finitely many, and ε-dense for the Hausdorff distance. -/ refine compact_of_totally_bounded_is_closed (emetric.totally_bounded_iff.2 (λε εpos, _)) is_closed_univ, rcases dense εpos with ⟨δ, δpos, δlt⟩, rcases emetric.totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 (@compact_univ α _ _)).1 δ δpos with ⟨s, fs, hs⟩, -- s : set α, fs : finite s, hs : univ ⊆ ⋃ (y : α) (H : y ∈ s), eball y δ -- we first show that any set is well approximated by a subset of `s`. have main : ∀ u : set α, ∃v ⊆ s, Hausdorff_edist u v ≤ δ, { assume u, let v := {x : α | x ∈ s ∧ ∃y∈u, edist x y < δ}, existsi [v, ((λx hx, hx.1) : v ⊆ s)], refine Hausdorff_edist_le_of_mem_edist _ _, { assume x hx, have : x ∈ ⋃y ∈ s, ball y δ := hs (by simp), rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, dy⟩⟩, have : edist y x < δ := by simp at dy; rwa [edist_comm] at dy, exact ⟨y, ⟨ys, ⟨x, hx, this⟩⟩, le_of_lt dy⟩ }, { rintros x ⟨hx1, ⟨y, yu, hy⟩⟩, exact ⟨y, yu, le_of_lt hy⟩ }}, -- introduce the set F of all subsets of `s` (seen as members of `closeds α`). let F := {f : closeds α | f.val ⊆ s}, use F, split, -- `F` is finite { apply @finite_of_finite_image _ _ F (λf, f.val), { apply set.inj_on_of_injective, simp [subtype.val_injective] }, { refine finite_subset (finite_subsets_of_finite fs) (λb, _), simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib], assume x hx hx', rwa hx' at hx }}, -- `F` is ε-dense { assume u _, rcases main u.val with ⟨t0, t0s, Dut0⟩, have : finite t0 := finite_subset fs t0s, have : is_closed t0 := closed_of_compact _ (compact_of_finite this), let t : closeds α := ⟨t0, this⟩, have : t ∈ F := t0s, have : edist u t < ε := lt_of_le_of_lt Dut0 δlt, apply mem_bUnion_iff.2, exact ⟨t, ‹t ∈ F›, this⟩ } end⟩ /-- In an emetric space, the type of non-empty compact subsets is an emetric space, where the edistance is the Hausdorff edistance -/ instance nonempty_compacts.emetric_space : emetric_space (nonempty_compacts α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq $ begin have : closure (s.val) = closure (t.val) := Hausdorff_edist_zero_iff_closure_eq_closure.1 h, rwa [closure_eq_iff_is_closed.2 (closed_of_compact _ s.property.2), closure_eq_iff_is_closed.2 (closed_of_compact _ t.property.2)] at this, end } /-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/ lemma nonempty_compacts.to_closeds.uniform_embedding : uniform_embedding (@nonempty_compacts.to_closeds α _ _) := isometry.uniform_embedding $ λx y, rfl /-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/ lemma nonempty_compacts.is_closed_in_closeds [complete_space α] : is_closed (nonempty_compacts.to_closeds '' (univ : set (nonempty_compacts α))) := begin have : nonempty_compacts.to_closeds '' univ = {s : closeds α | s.val ≠ ∅ ∧ compact s.val}, { ext, simp only [set.image_univ, set.mem_range, ne.def, set.mem_set_of_eq], split, { rintros ⟨y, hy⟩, have : x.val = y.val := by rcases hy; simp, rw this, exact y.property }, { rintros ⟨hx1, hx2⟩, existsi (⟨x.val, ⟨hx1, hx2⟩⟩ : nonempty_compacts α), apply subtype.eq, refl }}, rw this, refine is_closed_of_closure_subset (λs hs, _), split, { -- take a set set t which is nonempty and at distance at most 1 of s rcases mem_closure_iff'.1 hs 1 ennreal.zero_lt_one with ⟨t, ht, Dst⟩, rw edist_comm at Dst, -- this set t contains a point x rcases ne_empty_iff_exists_mem.1 ht.1 with ⟨x, hx⟩, -- by the Hausdorff distance control, this point x is at distance at most 1 -- of a point y in s rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨y, hy, _⟩, -- this shows that s is not empty exact ne_empty_of_mem hy }, { refine compact_iff_totally_bounded_complete.2 ⟨_, is_complete_of_is_closed s.property⟩, refine totally_bounded_iff.2 (λε εpos, _), -- we have to show that s is covered by finitely many eballs of radius ε -- pick a nonempty compact set t at distance at most ε/2 of s rcases mem_closure_iff'.1 hs (ε/2) (ennreal.half_pos εpos) with ⟨t, ht, Dst⟩, -- cover this space with finitely many balls of radius ε/2 rcases totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 ht.2).1 (ε/2) (ennreal.half_pos εpos) with ⟨u, fu, ut⟩, refine ⟨u, ⟨fu, λx hx, _⟩⟩, -- u : set α, fu : finite u, ut : t.val ⊆ ⋃ (y : α) (H : y ∈ u), eball y (ε / 2) -- then s is covered by the union of the balls centered at u of radius ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨z, hz, Dxz⟩, rcases mem_bUnion_iff.1 (ut hz) with ⟨y, hy, Dzy⟩, have : edist x y < ε := calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add Dxz Dzy ... = ε : ennreal.add_halves _, exact mem_bUnion hy this }, end /-- In a complete space, the type of nonempty compact subsets is complete. This follows from the same statement for closed subsets -/ instance nonempty_compacts.complete_space [complete_space α] : complete_space (nonempty_compacts α) := begin apply complete_space_of_is_complete_univ, apply (is_complete_image_iff nonempty_compacts.to_closeds.uniform_embedding).1, apply is_complete_of_is_closed, exact nonempty_compacts.is_closed_in_closeds end /-- In a compact space, the type of nonempty compact subsets is compact. This follows from the same statement for closed subsets -/ instance nonempty_compacts.compact_space [compact_space α] : compact_space (nonempty_compacts α) := ⟨begin rw compact_iff_compact_image_of_embedding nonempty_compacts.to_closeds.uniform_embedding.embedding, exact compact_of_closed nonempty_compacts.is_closed_in_closeds end⟩ /-- In a second countable space, the type of nonempty compact subsets is second countable -/ instance nonempty_compacts.second_countable_topology [second_countable_topology α] : second_countable_topology (nonempty_compacts α) := begin haveI : separable_space (nonempty_compacts α) := begin /- To obtain a countable dense subset of `nonempty_compacts α`, start from a countable dense subset `s` of α, and then consider all its finite nonempty subsets. This set is countable and made of nonempty compact sets. It turns out to be dense: by total boundedness, any compact set `t` can be covered by finitely many small balls, and approximations in `s` of the centers of these balls give the required finite approximation of `t`. -/ have : separable_space α := by apply_instance, rcases this.exists_countable_closure_eq_univ with ⟨s, cs, s_dense⟩, let v0 := {t : set α | finite t ∧ t ⊆ s}, let v : set (nonempty_compacts α) := {t : nonempty_compacts α | t.val ∈ v0}, refine ⟨⟨v, ⟨_, _⟩⟩⟩, { have : countable (subtype.val '' v), { refine countable_subset (λx hx, _) (countable_set_of_finite_subset cs), rcases (mem_image _ _ _).1 hx with ⟨y, ⟨hy, yx⟩⟩, rw ← yx, exact hy }, apply countable_of_injective_of_countable_image _ this, apply inj_on_of_inj_on_of_subset (injective_iff_inj_on_univ.1 subtype.val_injective) (subset_univ _) }, { refine subset.antisymm (subset_univ _) (λt ht, mem_closure_iff'.2 (λε εpos, _)), -- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`. rcases dense εpos with ⟨δ, δpos, δlt⟩, -- construct a map F associating to a point in α an approximating point in s, up to δ/2. have Exy : ∀x, ∃y, y ∈ s ∧ edist x y < δ/2, { assume x, have : x ∈ closure s := by rw s_dense; exact mem_univ _, rcases mem_closure_iff'.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, hy⟩, exact ⟨y, ⟨ys, hy⟩⟩ }, let F := λx, some (Exy x), have Fspec : ∀x, F x ∈ s ∧ edist x (F x) < δ/2 := λx, some_spec (Exy x), -- cover `t` with finitely many balls. Their centers form a set `a` have : totally_bounded t.val := (compact_iff_totally_bounded_complete.1 t.property.2).1, rcases totally_bounded_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨a, af, ta⟩, -- a : set α, af : finite a, ta : t.val ⊆ ⋃ (y : α) (H : y ∈ a), eball y (δ / 2) -- replace each center by a nearby approximation in `s`, giving a new set `b` let b := F '' a, have : finite b := finite_image _ af, have tb : ∀x ∈ t.val, ∃y ∈ b, edist x y < δ, { assume x hx, rcases mem_bUnion_iff.1 (ta hx) with ⟨z, za, Dxz⟩, existsi [F z, mem_image_of_mem _ za], calc edist x (F z) ≤ edist x z + edist z (F z) : edist_triangle _ _ _ ... < δ/2 + δ/2 : ennreal.add_lt_add Dxz (Fspec z).2 ... = δ : ennreal.add_halves _ }, -- keep only the points in `b` that are close to point in `t`, yielding a new set `c` let c := {y ∈ b | ∃x∈t.val, edist x y < δ}, have : finite c := finite_subset ‹finite b› (λx hx, hx.1), -- points in `t` are well approximated by points in `c` have tc : ∀x ∈ t.val, ∃y ∈ c, edist x y ≤ δ, { assume x hx, rcases tb x hx with ⟨y, yv, Dxy⟩, have : y ∈ c := by simp [c, -mem_image]; exact ⟨yv, ⟨x, hx, Dxy⟩⟩, exact ⟨y, this, le_of_lt Dxy⟩ }, -- points in `c` are well approximated by points in `t` have ct : ∀y ∈ c, ∃x ∈ t.val, edist y x ≤ δ, { rintros y ⟨hy1, ⟨x, xt, Dyx⟩⟩, have : edist y x ≤ δ := calc edist y x = edist x y : edist_comm _ _ ... ≤ δ : le_of_lt Dyx, exact ⟨x, xt, this⟩ }, -- it follows that their Hausdorff distance is small have : Hausdorff_edist t.val c ≤ δ := Hausdorff_edist_le_of_mem_edist tc ct, have Dtc : Hausdorff_edist t.val c < ε := lt_of_le_of_lt this δlt, -- the set `c` is not empty, as it is well approximated by a nonempty set have : c ≠ ∅, { by_contradiction h, simp only [not_not, ne.def] at h, rw [h, Hausdorff_edist_empty t.property.1] at Dtc, exact not_top_lt Dtc }, -- let `d` be the version of `c` in the type `nonempty_compacts α` let d : nonempty_compacts α := ⟨c, ⟨‹c ≠ ∅›, compact_of_finite ‹finite c›⟩⟩, have : c ⊆ s, { assume x hx, rcases (mem_image _ _ _).1 hx.1 with ⟨y, ⟨ya, yx⟩⟩, rw ← yx, exact (Fspec y).1 }, have : d ∈ v := ⟨‹finite c›, this⟩, -- we have proved that `d` is a good approximation of `t` as requested exact ⟨d, ‹d ∈ v›, Dtc⟩ }, end, apply second_countable_of_separable, end end --section end emetric --namespace namespace metric section variables {α : Type u} [metric_space α] /-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff edistance between two such sets is finite. -/ instance nonempty_compacts.metric_space : metric_space (nonempty_compacts α) := emetric_space.to_metric_space $ λx y, Hausdorff_edist_ne_top_of_ne_empty_of_bounded x.2.1 y.2.1 (bounded_of_compact x.2.2) (bounded_of_compact y.2.2) /-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/ lemma nonempty_compacts.dist_eq {x y : nonempty_compacts α} : dist x y = Hausdorff_dist x.val y.val := rfl lemma lipschitz_inf_dist_set (x : α) : lipschitz_with 1 (λ s : nonempty_compacts α, inf_dist x s.val) := lipschitz_with.one_of_le_add $ assume s t, by { rw dist_comm, exact inf_dist_le_inf_dist_add_Hausdorff_dist (edist_ne_top t s) } lemma lipschitz_inf_dist : lipschitz_with 2 (λ p : α × (nonempty_compacts α), inf_dist p.1 p.2.val) := @lipschitz_with.uncurry' _ _ _ _ _ _ (λ (x : α) (s : nonempty_compacts α), inf_dist x s.val) 1 1 (λ s, lipschitz_inf_dist_pt s.val) lipschitz_inf_dist_set lemma uniform_continuous_inf_dist_Hausdorff_dist : uniform_continuous (λp : α × (nonempty_compacts α), inf_dist p.1 (p.2).val) := lipschitz_inf_dist.to_uniform_continuous end --section end metric --namespace
90218b43b41d420178856f4031b5ddc9a1061f32
2cf781335f4a6706b7452ab07ce323201e2e101f
/lean/elf.lean
357bc87909e60e168c88a46ccba97de8c1de7db9
[ "Apache-2.0" ]
permissive
simonjwinwood/reopt-vcg
697cdd5e68366b5aa3298845eebc34fc97ccfbe2
6aca24e759bff4f2230bb58270bac6746c13665e
refs/heads/master
1,586,353,878,347
1,549,667,148,000
1,549,667,148,000
159,409,828
0
0
null
1,543,358,444,000
1,543,358,444,000
null
UTF-8
Lean
false
false
17,193
lean
/- This file contains the start of an Elf parser for Lean. It currently has facilities for parsing Elf -/ import system.io import init.category.reader import init.category.state import decodex86 import .imap import .file_input def repeat {α : Type} {m : Type → Type} [applicative m] : ℕ → m α → m (list α) | 0 m := pure [] | (nat.succ n) m := list.cons <$> m <*> repeat n m def forM' {m : Type → Type} [monad m] {α : Type} {β:Type} (l:list α) (f:α → m β) : m unit := list.mmap' f l def bracket {α β:Type} (c:io α) (d:α → io unit) (f:α → io β) := do x ← c, io.finally (f x) (d x) @[reducible] def uint8 := fin (nat.succ 0xff) @[reducible] def uint16 := fin (nat.succ 0xffff) @[reducible] def uint32 := fin (nat.succ 0xffffffff) @[reducible] def uint64 := fin (nat.succ 0xffffffffffffffff) namespace buffer @[reducible] def reader := except_t string (state char_buffer) namespace reader protected def read_chars (n:ℕ) : reader (list char) := do s ← get, when (s.size < n) (throw "read_chars eof"), put $ s.drop n, return ((s.take n).to_list) def skip (n:ℕ) : reader unit := do s ← get, when (s.size < n) (throw "skip eof"), put $ s.drop n def read_uint8 : reader uint8 := do l ← reader.read_chars 1, match l with | [h] := do return $ fin.of_nat h.val | _ := throw "internal: read_uint8" end def from_handle {α} (h:io.handle) (n:ℕ) (r:reader α) : io α := do b ← io.fs.read h n, match r.run.run b with | ⟨except.ok r,b'⟩ := do pure r | ⟨except.error e, b'⟩ := do io.fail e end end reader end buffer namespace elf def magic : list char := ['\x7f', 'E', 'L', 'F' ] inductive elf_class | ELF32 : elf_class | ELF64 : elf_class namespace elf_class protected def repr : elf_class → string | ELF32 := "ELF32" | ELF64 := "ELF64" protected def bytes : elf_class → ℕ | ELF32 := 4 | ELF64 := 8 protected def bits : elf_class → ℕ | ELF32 := 32 | ELF64 := 64 end elf_class inductive elf_data | ELFDATA2LSB : elf_data | ELFDATA2MSB : elf_data namespace elf_data protected def repr : elf_data → string | ELFDATA2LSB := "ELFDATA2LSB" | ELFDATA2MSB := "ELFDATA2MSB" end elf_data open elf_class open elf_data structure osabi := (val : uint8) namespace osabi protected def repr (o:osabi) : string := match o.val.val with | 0 := "UNIX - System V" | v := v.repr end end osabi -- Information from first 16-bytes of Elf file (allows reading rest of file). structure info := (elf_class : elf_class) (elf_data : elf_data) (osabi : osabi) (abi_version : uint8) namespace info protected def pp (e:info) : string := "Class: " ++ e.elf_class.repr ++ "\n" ++ "Data: " ++ e.elf_data.repr ++ "\n" ++ "OS/ABI: " ++ e.osabi.repr ++ "\n" ++ "ABI Version: " ++ e.abi_version.val.repr ++ "\n" open buffer def read : reader info := do b ← reader.read_chars 4, when (b ≠ magic) (throw "Not an elf file."), cl_val ← reader.read_uint8, cl ← match cl_val.val with | 1 := pure ELF32 | 2 := pure ELF64 | _ := throw "Invalid elf data." end, dt_val ← reader.read_uint8, dt ← match dt_val.val with | 1 := pure ELFDATA2LSB | 2 := pure ELFDATA2MSB | _ := throw "Invalid elf data." end, elf_version ← reader.read_uint8, when (elf_version ≠ 1) (throw "Mismatched elf version."), osabi ← reader.read_uint8, osabi_ver ← reader.read_uint8, pure { elf_class := cl , elf_data := dt , osabi := ⟨osabi⟩ , abi_version := osabi_ver } end info -- A reader for elf files @[reducible] def file_reader := reader_t info buffer.reader namespace file_reader protected def from_handle {α:Type} (i:info) (h:io.handle) (n:ℕ) (r:file_reader α) : io α := do b ← io.fs.read h n, match (r.run i).run.run b with | ⟨except.ok r, b'⟩ := do pure r | ⟨except.error e, b'⟩ := do io.fail e end def read_u8 : file_reader uint8 := reader_t.lift $ buffer.reader.read_uint8 protected def read_chars_lsb (w:ℕ) : file_reader (list char) := do i ← read, let f (l:list char) : list char := match i.elf_data with | ELFDATA2LSB := l | ELFDATA2MSB := l.reverse end in do reader_t.lift $ f <$> buffer.reader.read_chars w def read_u16 : file_reader uint16 := do l ← file_reader.read_chars_lsb 2, match l with | [x0,x1] := return $ fin.of_nat $ nat.shiftl x1.val 8 + x0.val | _ := throw "internal: read_uint16" end def read_u32 : file_reader uint32 := do l ← file_reader.read_chars_lsb 4, match l with | [x0,x1,x2,x3] := return $ fin.of_nat $ nat.shiftl x3.val 24 + nat.shiftl x2.val 16 + nat.shiftl x1.val 8 + x0.val | _ := throw "internal: read_uint32" end def read_u64 : file_reader uint64 := do l ← file_reader.read_chars_lsb 8, match l with | [x0,x1,x2,x3, x4, x5, x6, x7] := return $ fin.of_nat $ nat.shiftl x7.val 56 + nat.shiftl x6.val 48 + nat.shiftl x5.val 40 + nat.shiftl x4.val 32 + nat.shiftl x3.val 24 + nat.shiftl x2.val 16 + nat.shiftl x1.val 8 + x0.val | _ := throw "internal: read_uint64" end end file_reader class elf_file_data (α:Type) := (read {} : file_reader α) instance uint16_si_elf_file_data : elf_file_data uint16 := { read := file_reader.read_u16 } /- Elf defines a set of types depending on the class, e.g. Elf32_Word, Elf32_Addr, etc. Some of these are independent of the class, e.g. Elf32_Word = Elf64_Word = uint32. -/ -- A 32 or 64-bit word dependent on the class. def word (c:elf_class) := fin (nat.succ (2^c.bits-1)) namespace word protected def to_hex_with_leading_zeros : list char → ℕ → ℕ → string | prev 0 _ := prev.as_string | prev (nat.succ w) x := let c := (nat.land x 0xf).digit_char in to_hex_with_leading_zeros (c::prev) w (nat.shiftr x 4) protected def to_hex' : list char → ℕ → ℕ → string | prev 0 _ := prev.as_string | prev w 0 := prev.as_string | prev (nat.succ w) x := let c := (nat.land x 0xf).digit_char in to_hex' (c::prev) w (nat.shiftr x 4) -- Print word as decinal protected def pp_dec : Π{c:elf_class}, word c → string | ELF32 v := v.val.repr | ELF64 v := v.val.repr --- Print word as hex protected def pp_hex : Π{c:elf_class}, word c → string | ELF32 v := "0x" ++ word.to_hex' [] 8 v.val | ELF64 v := "0x" ++ word.to_hex' [] 16 v.val protected def size : elf_class → ℕ := elf_class.bytes theorem dbl_is_bit0 (x y:ℕ) : bit0 x*y = bit0 (x*y) := begin simp [bit0, nat.right_distrib], end --- `bit1_dec d x` is a utility function that denotes `(d+1)*x-1` -- It is primarily used def bit1_dec : ℕ → ℕ → ℕ | d x := (d+1)*x-1 theorem bit0_sub_1_congr (x:ℕ) : bit0 x - 1 = bit1_dec 1 x := begin simp [bit1_dec, bit1, bit0, nat.add_succ, nat.succ_mul], end theorem bit1_dec_bit0 (d x:ℕ) : bit1_dec d (bit0 x) = bit1_dec (bit1 d) x := begin simp [bit1_dec, bit1, bit0, nat.add_succ, nat.succ_mul, nat.left_distrib, nat.right_distrib], end theorem bit1_dec_one (d:ℕ) : bit1_dec d 1 = d := begin simp [bit1_dec], end theorem word32_is_uint32 : uint32 = word ELF32 := begin simp [uint32, word, elf_class.bits, has_pow.pow, nat.pow, dbl_is_bit0, bit0_sub_1_congr , bit1_dec_bit0, bit1_dec_one], end theorem word64_is_uint64 : uint64 = word ELF64 := begin simp [uint32, word, elf_class.bits, has_pow.pow, nat.pow, dbl_is_bit0, bit0_sub_1_congr , bit1_dec_bit0, bit1_dec_one], end instance (c:elf_class) : elf_file_data (word c) := { read := do match c with | ELF32 := eq.mp word32_is_uint32 <$> file_reader.read_u32 | ELF64 := eq.mp word64_is_uint64 <$> file_reader.read_u64 end } end word ------------------------------------------------------------------------ -- phdr structure phdr_type := (val : uint32) namespace phdr_type instance : elf_file_data phdr_type := { read := mk <$> file_reader.read_u32 } def repr (pht : phdr_type) : string := match pht.val.val with | 0 := "PT_NULL" | 1 := "PT_LOAD" | 2 := "PT_DYNAMIC" | 3 := "PT_INTERP" | 4 := "PT_NOTE" | 5 := "PT_SHLIB" | 6 := "PT_PHDR" | _ := "PT_PROC " ++ pht.val.val.repr end instance : has_repr phdr_type := ⟨repr⟩ instance : decidable_eq phdr_type := by tactic.mk_dec_eq_instance def PT_LOAD : phdr_type := mk 0 end phdr_type /-- Flags for a program header. -/ structure phdr_flags := (val : uint32) namespace phdr_flags instance : elf_file_data phdr_flags := { read := mk <$> file_reader.read_u32 } def repr (phfs : phdr_flags) : string := phfs.val.val.repr instance : has_repr phdr_flags := ⟨repr⟩ end phdr_flags structure phdr (c : elf_class) := (phdr_type : phdr_type) (flags : phdr_flags) (offset : word c) (vaddr : word c) (paddr : word c) (filesz : word c) (memsz : word c) (align : word c) namespace phdr def size (c:elf_class) : ℕ := 8 + 6 * word.size c protected def pp {c:elf_class} (x:phdr c) := "Type: " ++ x.phdr_type.repr ++ "\n" ++ "Flags: " ++ x.flags.repr ++ "\n" ++ "File Offset: " ++ x.offset.pp_dec ++ "\n" ++ "Virtual Address: " ++ x.vaddr.pp_hex ++ "\n" ++ "Physical Address: " ++ x.paddr.pp_hex ++ "\n" ++ "File Size: " ++ x.filesz.pp_dec ++ "\n" ++ "Memory Size: " ++ x.memsz.pp_dec ++ "\n" ++ "Alignment: " ++ x.memsz.pp_hex ++ "\n" end phdr def read_phdr : Π(c:elf_class), file_reader (phdr c) | ELF32 := do tp ← elf_file_data.read, offset ← elf_file_data.read, vaddr ← elf_file_data.read, paddr ← elf_file_data.read, filesz ← elf_file_data.read, memsz ← elf_file_data.read, flags ← elf_file_data.read, align ← elf_file_data.read, pure { phdr_type := tp , flags := flags , offset := offset , vaddr := vaddr , paddr := paddr , filesz := filesz , memsz := memsz , align := align } | ELF64 := do tp ← elf_file_data.read, flags ← elf_file_data.read, offset ← elf_file_data.read, vaddr ← elf_file_data.read, paddr ← elf_file_data.read, filesz ← elf_file_data.read, memsz ← elf_file_data.read, align ← elf_file_data.read, pure { phdr_type := tp , flags := flags , offset := offset , vaddr := vaddr , paddr := paddr , filesz := filesz , memsz := memsz , align := align } ------------------------------------------------------------------------ -- ehdr /-- Elf file type -/ structure elf_type := (val : uint16) namespace elf_type instance : elf_file_data elf_type := { read := elf_type.mk <$> file_reader.read_u16 } end elf_type /-- Elf header machine type. -/ structure machine := (val : uint16) namespace machine instance : elf_file_data machine := { read := machine.mk <$> file_reader.read_u16 } end machine /-- Flags for a elf header. -/ structure ehdr_flags := (val : uint32) namespace ehdr_flags instance : elf_file_data ehdr_flags := { read := ehdr_flags.mk <$> file_reader.read_u32 } end ehdr_flags /-- The elf header information -/ structure ehdr := (info : info) (elf_type : elf_type) (machine : machine) (entry : word info.elf_class) (phoff : word info.elf_class) (shoff : word info.elf_class) (flags : ehdr_flags) (phnum : uint16) (shnum : uint16) (shstrndx : uint16) namespace ehdr -- Number of bytes in the ehdr after the 16 byte info. protected def size (c:elf_class) : ℕ := 16 + 24 + 3 * c.bytes protected def elf_class (e:ehdr) := e.info.elf_class protected def pp (e:ehdr) := e.info.pp ++ "Type: " ++ e.elf_type.val.val.repr ++ "\n" ++ "Machine: " ++ e.machine.val.val.repr ++ "\n" ++ "Entry point address: " ++ e.entry.pp_hex ++ "\n" ++ "Start of program headers: " ++ e.phoff.val.repr ++ " (bytes into file)\n" ++ "Start of section headers: " ++ e.shoff.val.repr ++ " (bytes into file)\n" ++ "Flags: " ++ e.flags.val.val.repr ++ "\n" ++ "Number of program headers: " ++ e.phnum.val.repr ++ "\n" ++ "Number of section headers: " ++ e.shnum.val.repr ++ "\n" ++ "Section header string table index: " ++ e.shstrndx.val.repr ++ "\n" end ehdr -- Read the remainder of the elf header after the first 16 bytes for the info. def read_ehdr_remainder : file_reader ehdr := do i ← read, tp ← elf_file_data.read, mach ← elf_file_data.read, ver ← file_reader.read_u32, when (ver ≠ 1) (throw $ "Unexpected version: " ++ ver.val.repr), entry ← elf_file_data.read, phoff ← elf_file_data.read, shoff ← elf_file_data.read, flags ← elf_file_data.read, _ehsize ← file_reader.read_u16, _phentsize ← file_reader.read_u16, phnum ← elf_file_data.read, _shentsize ← file_reader.read_u16, shnum ← elf_file_data.read, shstrndx ← elf_file_data.read, pure { info := i , elf_type := tp , machine := mach , entry := entry , phoff := phoff , shoff := shoff , flags := flags , phnum := phnum , shnum := shnum , shstrndx := shstrndx } -- The the elf header from the handle (which should be at the -- beginning of the file. def read_ehdr_from_handle (h:io.handle) : io ehdr := do i ← buffer.reader.from_handle h 16 info.read, let ehdr_size := ehdr.size i.elf_class in do file_reader.from_handle i h (ehdr_size - 16) read_ehdr_remainder -- Return size of phdr table def phdr_table_size (e:ehdr) : ℕ := phdr.size e.elf_class * e.phnum.val def read_phdrs_from_handle (e:ehdr) (h:io.handle) : io (list (phdr e.elf_class)) := file_reader.from_handle (e.info) h (phdr_table_size e) ( repeat (e.phnum.val) $ read_phdr e.elf_class) -- Move from current offset to target offset. def move_to_target (h:io.handle) (cur_off:ℕ) (target_off:ℕ) : io unit := if target_off < cur_off then do io.fail "Unexpected phdr offset" else do _ ← io.fs.read h (target_off - cur_off), pure () def pp_phdrs {c:elf_class} (phdrs:list (phdr c)) : io unit := do forM' (list.zip (list.range phdrs.length) phdrs) (λphdr, do let idx := phdr.fst in do io.put_str_ln $ "Index: " ++ idx.repr, io.put_str_ln phdr.snd.pp) -- A region is the contents of memory as it appears at load time. @[reducible] def region := char_buffer -- An elfmem represeents the load-time address space represented by -- the elf file. It is indexed by virtual address def elfmem : Type := data.imap ℕ region (<) -- Helper for read_elfmem: add the region corresponding to the phdr in ph def read_one_elfmem {c : elf_class} (m : elfmem) (ph : phdr c) : file_input elfmem := if ph.phdr_type = phdr_type.PT_LOAD then do file_input.seek ph.offset.val, fbs <- file_input.read (min ph.filesz.val ph.memsz.val), monad_lift (io.put_str_ln ("read_one_elfmem: read " ++ fbs.size.repr ++ " bytes")), let val := buffer.append_list fbs (list.repeat (char.of_nat 0) (ph.memsz.val - ph.filesz.val)) in pure $ data.imap.insert ph.vaddr.val ph.memsz.val val m else pure m def read_elfmem {c : elf_class} (path : string) (phdrs : list (phdr c)) : io elfmem := do r <- file_input.run_file_input path $ list.mfoldl read_one_elfmem [] phdrs, match r with | except.error s := io.fail s | except.ok r := return r end /--- Read the elf file from the given path, and print out ehdr and program headers. -/ def read_info_from_file (path:string) : io elfmem := do bracket (io.mk_file_handle path io.mode.read tt) io.fs.close $ λh, do e ← read_ehdr_from_handle h, let i := e.info in do let ehdr_size := ehdr.size i.elf_class in do move_to_target h ehdr_size e.phoff.val, phdrs ← read_phdrs_from_handle e h, read_elfmem path phdrs -- pp_phdrs phdrs end elf def get_filename_arg : io (string × string × ℕ × ℕ) := do args ← io.cmdline_args, match args with | [name, decoder, first, last_plus_1 ] := do return ( name, decoder, string.to_nat first, string.to_nat last_plus_1 ) | _ := do io.fail "Usage: CMD elf_file decoder first_byte last_byte_plus_1" end def main : io unit := do (file, decoder, first, last_plus_1) ← get_filename_arg, mem <- elf.read_info_from_file file, match data.imap.lookup first mem with | none := io.fail ("Could not find start address: " ++ repr first) | (some (buf_start, buf)) := if last_plus_1 - buf_start > buffer.size buf then io.fail ("Last byte outside buffer: " ++ repr last_plus_1) else do buf' <- return (buffer.take (buffer.drop buf (first - buf_start)) (last_plus_1 - first)), res <- decodex86.decode decoder buf', match res with | (sum.inl e) := io.fail ("Decode error: " ++ e) | (sum.inr r) := io.put_str_ln (repr r) end end
2cd8369d2eefce30e2b0bcbb714bf8fe827c98ec
a721fe7446524f18ba361625fc01033d9c8b7a78
/elaborate/strong_induction.stripped.lean
4e6a8271b4d798f3f1eac588b7c9e6a3a0512247
[]
no_license
Sterrs/leaning
8fd80d1f0a6117a220bb2e57ece639b9a63deadc
3901cc953694b33adda86cb88ca30ba99594db31
refs/heads/master
1,627,023,822,744
1,616,515,221,000
1,616,515,221,000
245,512,190
2
0
null
1,616,429,050,000
1,583,527,118,000
Lean
UTF-8
Lean
false
false
11,368
lean
λ (statement : mynat → Prop) (base_case : statement zero) (inductive_step : ∀ (n : mynat), (∀ (m : mynat), (∃ (k : mynat), n = add m k) → statement m) → statement (succ n)) (k : mynat), mynat.rec (λ (M : mynat) (hMl0 : ∃ (k : mynat), zero = add M k), eq.rec base_case (eq.rec (eq.refl (statement M)) (eq.rec (eq.refl (statement M)) (Exists.rec (λ (w : mynat) (h : zero = add M w) («_» : ∃ (k : mynat), zero = add M k), mynat.rec (eq.rec true.intro (eq.rec (eq.refl (add zero w = zero → zero = zero)) (eq.rec (propext {mp := λ (hab : add zero w = zero → zero = zero) (hc : w = zero), (eq.rec {mp := λ (h : zero = zero), h, mpr := λ (h : zero = zero), h} (eq.rec (eq.refl (zero = zero)) (propext {mp := λ (hl : zero = zero), true.intro, mpr := λ (hr : true), eq.refl zero}))).mp (hab ((eq.rec {mp := λ (h : add zero w = zero), h, mpr := λ (h : add zero w = zero), h} (eq.rec (eq.refl (add zero w = zero)) (eq.rec (eq.refl (eq (add zero w))) (eq.rec (eq.refl (add zero w)) (mynat.rec (eq.rec true.intro (eq.rec (eq.refl (zero = zero)) (eq.rec (eq.refl (zero = zero)) (propext {mp := λ (hl : zero = zero), true.intro, mpr := λ (hr : true), eq.refl zero})))) (λ (n_n : mynat) (n_ih : add zero n_n = n_n), eq.rec n_ih (eq.rec (eq.refl (succ (add zero n_n) = succ n_n)) (eq.rec (eq.refl (succ (add zero n_n) = succ n_n)) (propext {mp := λ (h : succ (add zero n_n) = succ n_n), eq.rec (λ (h11 : succ (add zero n_n) = succ (add zero n_n)) (a : add zero n_n = add zero n_n → add zero n_n = n_n), a (eq.refl (add zero n_n))) h h (λ (n_eq : add zero n_n = n_n), n_eq), mpr := λ (a : add zero n_n = n_n), eq.rec (eq.refl (succ (add zero n_n))) a})))) w))))).mpr hc)), mpr := λ (hcd : w = zero → true) (ha : add zero w = zero), (eq.rec {mp := λ (h : zero = zero), h, mpr := λ (h : zero = zero), h} (eq.rec (eq.refl (zero = zero)) (propext {mp := λ (hl : zero = zero), true.intro, mpr := λ (hr : true), eq.refl zero}))).mpr (hcd ((eq.rec {mp := λ (h : add zero w = zero), h, mpr := λ (h : add zero w = zero), h} (eq.rec (eq.refl (add zero w = zero)) (eq.rec (eq.refl (eq (add zero w))) (eq.rec (eq.refl (add zero w)) (mynat.rec (eq.rec true.intro (eq.rec (eq.refl (zero = zero)) (eq.rec (eq.refl (zero = zero)) (propext {mp := λ (hl : zero = zero), true.intro, mpr := λ (hr : true), eq.refl zero})))) (λ (n_n : mynat) (n_ih : add zero n_n = n_n), eq.rec n_ih (eq.rec (eq.refl (succ (add zero n_n) = succ n_n)) (eq.rec (eq.refl (succ (add zero n_n) = succ n_n)) (propext {mp := λ (h : succ (add zero n_n) = succ n_n), eq.rec (λ (h11 : succ (add zero n_n) = succ (add zero n_n)) (a : add zero n_n = add zero n_n → add zero n_n = n_n), a (eq.refl (add zero n_n))) h h (λ (n_eq : add zero n_n = n_n), n_eq), mpr := λ (a : add zero n_n = n_n), eq.rec (eq.refl (succ (add zero n_n))) a})))) w))))).mp ha))}) (propext {mp := λ (h : w = zero → true), true.intro, mpr := λ (ha : true) (h : w = zero), true.intro})))) (λ (n : mynat) (ih : add n w = zero → n = zero), eq.rec (λ (hsmnz : succ (add w n) = zero), false.rec (succ n = zero) (eq.rec (λ («_» : succ (add w n) = succ (add w n)) (a : zero = succ (add w n)), eq.rec (λ (h11 : zero = zero) (a : hsmnz == eq.refl (succ (add w n)) → false), a) a a) hsmnz hsmnz (eq.refl zero) (heq.refl hsmnz))) (eq.rec (eq.refl (add (succ n) w = zero → succ n = zero)) (propext {mp := λ (hab : add (succ n) w = zero → succ n = zero) (hc : succ (add w n) = zero), hab ((eq.rec {mp := λ (h : add (succ n) w = zero), h, mpr := λ (h : add (succ n) w = zero), h} (eq.rec (eq.refl (add (succ n) w = zero)) (eq.rec (eq.refl (eq (add (succ n) w))) (mynat.rec (eq.rec true.intro (eq.rec (eq.refl (succ n = succ (add zero n))) (eq.rec (eq.rec (eq.refl (succ n = succ (add zero n))) (eq.rec (eq.refl (succ (add zero n))) (eq.rec (mynat.rec (eq.refl zero) (λ (m_n : mynat) (m_ih : add zero m_n = m_n), eq.rec m_ih (eq.rec (eq.refl (succ (add zero m_n) = succ m_n)) (eq.rec (eq.refl (succ (add zero m_n) = succ m_n)) (propext {mp := λ (h : succ (add zero m_n) = succ m_n), eq.rec (λ (h11 : succ (add zero m_n) = succ (add zero m_n)) (a : add zero m_n = add zero m_n → add zero m_n = m_n), a (eq.refl (add zero m_n))) h h (λ (n_eq : add zero m_n = m_n), n_eq), mpr := λ (a : add zero m_n = m_n), eq.rec (eq.refl (succ (add zero m_n))) a})))) n) (eq.rec (eq.refl (succ (add zero n) = succ n)) (eq.rec (eq.refl (succ (add zero n) = succ n)) (propext {mp := λ (h : succ (add zero n) = succ n), eq.rec (λ (h11 : succ (add zero n) = succ (add zero n)) (a : add zero n = add zero n → add zero n = n), a (eq.refl (add zero n))) h h (λ (n_eq : add zero n = n), n_eq), mpr := λ (a : add zero n = n), eq.rec (eq.refl (succ (add zero n))) a})))))) (propext {mp := λ (hl : succ n = succ n), true.intro, mpr := λ (hr : true), eq.refl (succ n)})))) (λ (n_n : mynat) (n_ih : add (succ n) n_n = succ (add n_n n)), eq.rec n_ih (eq.rec (eq.refl (succ (add (succ n) n_n) = succ (add (succ n_n) n))) (eq.rec (eq.rec (eq.refl (succ (add (succ n) n_n) = succ (add (succ n_n) n))) (eq.rec (mynat.rec (eq.refl (succ n_n)) (λ (n_n_1 : mynat) (n_ih : add (succ n_n) n_n_1 = succ (add n_n n_n_1)), eq.rec n_ih (eq.rec (eq.refl (succ (add (succ n_n) n_n_1) = succ (succ (add n_n n_n_1)))) (eq.rec (eq.refl (succ (add (succ n_n) n_n_1) = succ (succ (add n_n n_n_1)))) (propext {mp := λ (h : succ (add (succ n_n) n_n_1) = succ (succ (add n_n n_n_1))), eq.rec (λ (h11 : succ (add (succ n_n) n_n_1) = succ (add (succ n_n) n_n_1)) (a : add (succ n_n) n_n_1 = add (succ n_n) n_n_1 → add (succ n_n) n_n_1 = succ (add n_n n_n_1)), a (eq.refl (add (succ n_n) n_n_1))) h h (λ (n_eq : add (succ n_n) n_n_1 = succ (add n_n n_n_1)), n_eq), mpr := λ (a : add (succ n_n) n_n_1 = succ (add n_n n_n_1)), eq.rec (eq.refl (succ (add (succ n_n) n_n_1))) a})))) n) (eq.rec (eq.refl (succ (add (succ n_n) n) = succ (succ (add n_n n)))) (eq.rec (eq.refl (succ (add (succ n_n) n) = succ (succ (add n_n n)))) (propext {mp := λ (h : succ (add (succ n_n) n) = succ (succ (add n_n n))), eq.rec (λ (h11 : succ (add (succ n_n) n) = succ (add (succ n_n) n)) (a : add (succ n_n) n = add (succ n_n) n → add (succ n_n) n = succ (add n_n n)), a (eq.refl (add (succ n_n) n))) h h (λ (n_eq : add (succ n_n) n = succ (add n_n n)), n_eq), mpr := λ (a : add (succ n_n) n = succ (add n_n n)), eq.rec (eq.refl (succ (add (succ n_n) n))) a}))))) (propext {mp := λ (h : succ (add (succ n) n_n) = succ (succ (add n_n n))), eq.rec (λ (h11 : succ (add (succ n) n_n) = succ (add (succ n) n_n)) (a : add (succ n) n_n = add (succ n) n_n → add (succ n) n_n = succ (add n_n n)), a (eq.refl (add (succ n) n_n))) h h (λ (n_eq : add (succ n) n_n = succ (add n_n n)), n_eq), mpr := λ (a : add (succ n) n_n = succ (add n_n n)), eq.rec (eq.refl (succ (add (succ n) n_n))) a})))) w)))).mpr hc), mpr := λ (hcd : succ (add w n) = zero → succ n = zero) (ha : add (succ n) w = zero), hcd ((eq.rec {mp := λ (h : add (succ n) w = zero), h, mpr := λ (h : add (succ n) w = zero), h} (eq.rec (eq.refl (add (succ n) w = zero)) (eq.rec (eq.refl (eq (add (succ n) w))) (mynat.rec (eq.rec true.intro (eq.rec (eq.refl (succ n = succ (add zero n))) (eq.rec (eq.rec (eq.refl (succ n = succ (add zero n))) (eq.rec (eq.refl (succ (add zero n))) (eq.rec (mynat.rec (eq.refl zero) (λ (m_n : mynat) (m_ih : add zero m_n = m_n), eq.rec m_ih (eq.rec (eq.refl (succ (add zero m_n) = succ m_n)) (eq.rec (eq.refl (succ (add zero m_n) = succ m_n)) (propext {mp := λ (h : succ (add zero m_n) = succ m_n), eq.rec (λ (h11 : succ (add zero m_n) = succ (add zero m_n)) (a : add zero m_n = add zero m_n → add zero m_n = m_n), a (eq.refl (add zero m_n))) h h (λ (n_eq : add zero m_n = m_n), n_eq), mpr := λ (a : add zero m_n = m_n), eq.rec (eq.refl (succ (add zero m_n))) a})))) n) (eq.rec (eq.refl (succ (add zero n) = succ n)) (eq.rec (eq.refl (succ (add zero n) = succ n)) (propext {mp := λ (h : succ (add zero n) = succ n), eq.rec (λ (h11 : succ (add zero n) = succ (add zero n)) (a : add zero n = add zero n → add zero n = n), a (eq.refl (add zero n))) h h (λ (n_eq : add zero n = n), n_eq), mpr := λ (a : add zero n = n), eq.rec (eq.refl (succ (add zero n))) a})))))) (propext {mp := λ (hl : succ n = succ n), true.intro, mpr := λ (hr : true), eq.refl (succ n)})))) (λ (n_n : mynat) (n_ih : add (succ n) n_n = succ (add n_n n)), eq.rec n_ih (eq.rec (eq.refl (succ (add (succ n) n_n) = succ (add (succ n_n) n))) (eq.rec (eq.rec (eq.refl (succ (add (succ n) n_n) = succ (add (succ n_n) n))) (eq.rec (mynat.rec (eq.refl (succ n_n)) (λ (n_n_1 : mynat) (n_ih : add (succ n_n) n_n_1 = succ (add n_n n_n_1)), eq.rec n_ih (eq.rec (eq.refl (succ (add (succ n_n) n_n_1) = succ (succ (add n_n n_n_1)))) (eq.rec (eq.refl (succ (add (succ n_n) n_n_1) = succ (succ (add n_n n_n_1)))) (propext {mp := λ (h : succ (add (succ n_n) n_n_1) = succ (succ (add n_n n_n_1))), eq.rec (λ (h11 : succ (add (succ n_n) n_n_1) = succ (add (succ n_n) n_n_1)) (a : add (succ n_n) n_n_1 = add (succ n_n) n_n_1 → add (succ n_n) n_n_1 = succ (add n_n n_n_1)), a (eq.refl (add (succ n_n) n_n_1))) h h (λ (n_eq : add (succ n_n) n_n_1 = succ (add n_n n_n_1)), n_eq), mpr := λ (a : add (succ n_n) n_n_1 = succ (add n_n n_n_1)), eq.rec (eq.refl (succ (add (succ n_n) n_n_1))) a})))) n) (eq.rec (eq.refl (succ (add (succ n_n) n) = succ (succ (add n_n n)))) (eq.rec (eq.refl (succ (add (succ n_n) n) = succ (succ (add n_n n)))) (propext {mp := λ (h : succ (add (succ n_n) n) = succ (succ (add n_n n))), eq.rec (λ (h11 : succ (add (succ n_n) n) = succ (add (succ n_n) n)) (a : add (succ n_n) n = add (succ n_n) n → add (succ n_n) n = succ (add n_n n)), a (eq.refl (add (succ n_n) n))) h h (λ (n_eq : add (succ n_n) n = succ (add n_n n)), n_eq), mpr := λ (a : add (succ n_n) n = succ (add n_n n)), eq.rec (eq.refl (succ (add (succ n_n) n))) a}))))) (propext {mp := λ (h : succ (add (succ n) n_n) = succ (succ (add n_n n))), eq.rec (λ (h11 : succ (add (succ n) n_n) = succ (add (succ n) n_n)) (a : add (succ n) n_n = add (succ n) n_n → add (succ n) n_n = succ (add n_n n)), a (eq.refl (add (succ n) n_n))) h h (λ (n_eq : add (succ n) n_n = succ (add n_n n)), n_eq), mpr := λ (a : add (succ n) n_n = succ (add n_n n)), eq.rec (eq.refl (succ (add (succ n) n_n))) a})))) w)))).mp ha)}))) M (eq.rec (eq.refl zero) h)) hMl0 hMl0)))) (λ (N_n : mynat) (N_ih : ∀ (M : mynat), (∃ (k : mynat), N_n = add M k) → statement M) (M : mynat) (hMlesN : ∃ (k : mynat), succ N_n = add M k), Exists.rec (λ (w : mynat) (h : succ N_n = add M w) («_» : ∃ (k : mynat), succ N_n = add M k), mynat.rec (λ (hd : succ N_n = M), eq.rec (inductive_step N_n N_ih) (eq.rec (eq.refl (statement M)) (eq.rec (eq.refl (statement M)) (eq.rec (eq.refl (succ N_n)) hd)))) (λ (n : mynat) (ih : succ N_n = add M n → statement M) (hd : succ N_n = succ (add M n)), N_ih M (Exists.intro n (eq.rec hd (eq.rec (eq.refl (succ N_n = succ (add M n))) (propext {mp := λ (h : succ N_n = succ (add M n)), eq.rec (λ (h11 : succ N_n = succ N_n) (a : N_n = N_n → N_n = add M n), a (eq.refl N_n)) h h (λ (n_eq : N_n = add M n), n_eq), mpr := λ (a : N_n = add M n), eq.rec (eq.refl (succ N_n)) a}))))) w h) hMlesN hMlesN) k k (Exists.intro zero (eq.rec (eq.refl (succ k)) (eq.rec (eq.refl (succ k = succ k)) (propext {mp := λ (h : succ k = succ k), eq.refl k, mpr := λ (a : k = k), eq.refl (succ k)}))))
137a3184acbf70a6d71225b0a4ac5a3e03e5bd50
4727251e0cd73359b15b664c3170e5d754078599
/src/data/multiset/range.lean
a074ad5a805e01275c5bb300ddec41c2f87ad1a5
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
1,658
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.basic import data.list.range /-! # `multiset.range n` gives `{0, 1, ..., n-1}` as a multiset. -/ open list nat namespace multiset /- range -/ /-- `range n` is the multiset lifted from the list `range n`, that is, the set `{0, 1, ..., n-1}`. -/ def range (n : ℕ) : multiset ℕ := range n @[simp] theorem range_zero : range 0 = 0 := rfl @[simp] theorem range_succ (n : ℕ) : range (succ n) = n ::ₘ range n := by rw [range, range_succ, ← coe_add, add_comm]; refl @[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _ theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := list.self_mem_range_succ n lemma range_add (a b : ℕ) : range (a + b) = range a + (range b).map (λ x, a + x) := congr_arg coe (list.range_add _ _) lemma range_disjoint_map_add (a : ℕ) (m : multiset ℕ) : (range a).disjoint (m.map (λ x, a + x)) := begin intros x hxa hxb, rw [range, mem_coe, list.mem_range] at hxa, obtain ⟨c, _, rfl⟩ := mem_map.1 hxb, exact (self_le_add_right _ _).not_lt hxa, end lemma range_add_eq_union (a b : ℕ) : range (a + b) = range a ∪ (range b).map (λ x, a + x) := by { rw [range_add, add_eq_union_iff_disjoint], apply range_disjoint_map_add } end multiset
674c04d42feadb359a85d2d0929f1e9242945b4f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/CompilerFloatLetIn.lean
5af1e09f9744ab4689ed98d4a972b9c42a569c86
[ "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
773
lean
import Lean.Compiler.Main import Lean.Compiler.LCNF.Testing import Lean.Elab.Do open Lean open Lean.Compiler.LCNF -- Run compilation twice to avoid the output caused by the inliner #eval Compiler.compile #[``Lean.Meta.synthInstance, ``Lean.Elab.Term.Do.elabDo] -- #eval fails if we uncomment this pass after I added a `floatLetIn` pass at the mono phase -- @[cpass] -- def floatLetInFixTest : PassInstaller := Testing.assertIsAtFixPoint |>.install `floatLetIn `floatLetInFix @[cpass] def floatLetInSizeTest : PassInstaller := Testing.assertReducesOrPreservesSize "FloatLetIn increased size of declaration" |>.install `floatLetIn `floatLetInSizeEq set_option trace.Compiler.test true in #eval Compiler.compile #[``Lean.Meta.synthInstance, ``Lean.Elab.Term.Do.elabDo]
f1a3e90706b3cdb3d71b6bc1b26420090a7b2462
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/newfrontend1.lean
1ee4593519d29353869866af1d249f82c3dfbfa9
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
6,165
lean
def x := 1 new_frontend #check x variables {α : Type} def f (a : α) : α := a def tst (xs : List Nat) : Nat := xs.foldl (init := 10) (· + ·) #check tst [1, 2, 3] #check tst #check (fun stx => if True then let e := stx; HasPure.pure e else HasPure.pure stx : Nat → Id Nat) #check let x : Nat := 1; x def foo (a : Nat) (b : Nat := 10) (c : Bool := Bool.true) : Nat := a + b set_option pp.all true #check foo 1 #check foo 3 (c := false) def Nat.boo (a : Nat) := succ a -- succ here is resolved as `Nat.succ`. #check Nat.boo #check true -- apply is still a valid identifier name def apply := "hello" #check apply theorem simple1 (x y : Nat) (h : x = y) : x = y := begin assumption end theorem simple2 (x y : Nat) : x = y → x = y := begin intro h; assumption end syntax "intro2" : tactic macro_rules | `(tactic| intro2) => `(tactic| intro; intro ) theorem simple3 (x y : Nat) : x = x → x = y → x = y := begin intro2; assumption end macro intro3 : tactic => `(intro; intro; intro) macro check2 x:term : command => `(#check $x #check $x) macro foo x:term "," y:term : term => `($x + $y + $x) set_option pp.all false check2 0+1 check2 foo 0,1 theorem simple4 (x y : Nat) : y = y → x = x → x = y → x = y := begin intro3; assumption end theorem simple5 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intro h1; intro _; intro h3; exact Eq.trans h3 h1 end theorem simple6 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intro h1; intro _; intro h3; refine Eq.trans _ h1; assumption end theorem simple7 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intro h1; intro _; intro h3; refine Eq.trans ?pre ?post; exact y; { exact h3 }; { exact h1 } end theorem simple8 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intro h1; intro _; intro h3; refine Eq.trans ?pre ?post; case post { exact h1 }; case pre { exact h3 }; end theorem simple9 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intros h1 _ h3; traceState; { refine Eq.trans ?pre ?post; (exact h1) <|> (exact y; exact h3; assumption) } end namespace Foo def Prod.mk := 1 #check (⟨2, 3⟩ : Prod _ _) end Foo theorem simple10 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intro h1; intro h2; intro h3; skip; apply Eq.trans; exact h3; assumption end theorem simple11 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intro h1; intro h2; intro h3; apply @Eq.trans; traceState; exact h3; assumption end macro try t:tactic : tactic => `($t <|> skip) syntax "repeat" tactic : tactic macro_rules | `(tactic| repeat $t) => `(tactic| try ($t; repeat $t)) theorem simple12 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intro h1; intro h2; intro h3; apply @Eq.trans; try exact h1; -- `exact h1` fails traceState; try exact h3; traceState; try exact h1; end theorem simple13 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intros h1 h2 h3; traceState; apply @Eq.trans; case main.b exact y; traceState; repeat assumption end theorem simple14 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intros; apply @Eq.trans; case main.b exact y; repeat assumption end theorem simple15 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intros h1 h2 h3; revert y; intros y h1 h3; apply Eq.trans; exact h3; exact h1 end theorem simple16 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intros h1 h2 h3; try (clear x); -- should fail clear h2; traceState; apply Eq.trans; exact h3; exact h1 end macro "blabla" : tactic => `(assumption) -- Tactic head symbols do not become reserved words def blabla := 100 #check blabla theorem simple17 (x : Nat) (h : x = 0) : x = 0 := begin blabla end theorem simple18 (x : Nat) (h : x = 0) : x = 0 := by blabla theorem simple19 (x y : Nat) (h₁ : x = 0) (h₂ : x = y) : y = 0 := by subst x; subst y; exact rfl theorem tstprec1 (x y z : Nat) : x + y * z = x + (y * z) := rfl theorem tstprec2 (x y z : Nat) : y * z + x = (y * z) + x := rfl set_option pp.all true #check fun {α} (a : α) => a #check @(fun {α} (a : α) => a) -- In the following example, we need `@` otherwise we will try to insert mvars for α and [HasAdd α], -- and will fail to generate instance for [HasAdd α] #check @(fun {α} [HasAdd α] (a : α) => a + a) def g1 {α} (a₁ a₂ : α) {β} (b : β) : α × α × β := (a₁, a₂, b) def id1 : {α : Type} → α → α := fun x => x def listId : List ({α : Type} → α → α) := (fun x => x) :: [] def id2 : {α : Type} → α → α := fun {α : Type} (x : α) => id1 x def id3 : {α : Type} → α → α := @(fun {α} x => id1 x) def id4 : {α : Type} → α → α := fun x => id1 x def id5 : {α : Type} → α → α := @(fun α x => id1 x) def id6 : {α : Type} → α → α := fun {α} x => id1 x def id7 : {α : Type} → α → α := fun {α} x => @id α x def id8 : {α : Type} → α → α := fun {α} x => id (@id α x) def altTst1 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨StateT.failure, StateT.orelse⟩ def altTst2 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨@(fun α => StateT.failure), @(fun α => StateT.orelse)⟩ def altTst3 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨@(fun {α} => StateT.failure), @(fun {α} => StateT.orelse)⟩ def altTst4 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨@StateT.failure _ _ _ _, @StateT.orelse _ _ _ _⟩ def altTst5 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨fun {α} => StateT.failure, fun {α} => StateT.orelse⟩ #check_failure 1 + true /- universes u v /- MonadFunctorT.{u ?M_1 v} (λ (β : Type u), m α) (λ (β : Type u), m' α) n n' -/ set_option syntaxMaxDepth 100 set_option trace.Elab true def adapt {m m' σ σ'} {n n' : Type → Type} [MonadFunctor m m' n n'] [MonadStateAdapter σ σ' m m'] : MonadStateAdapter σ σ' n n' := ⟨fun split join => monadMap (adaptState split join : m α → m' α)⟩ -/
6809213ad5ce5c06cffb68211ee71aed12572e3d
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/locally_convex/basic.lean
e85a878843e3b32bb490047aabd532cbec164f94
[ "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
12,094
lean
/- Copyright (c) 2019 Jean Lo. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jean Lo, Bhavik Mehta, Yaël Dillies -/ import analysis.normed_space.basic /-! # Local convexity This file defines absorbent and balanced sets. An absorbent set is one that "surrounds" the origin. The idea is made precise by requiring that any point belongs to all large enough scalings of the set. This is the vector world analog of a topological neighborhood of the origin. A balanced set is one that is everywhere around the origin. This means that `a • s ⊆ s` for all `a` of norm less than `1`. ## Main declarations For a module over a normed ring: * `absorbs`: A set `s` absorbs a set `t` if all large scalings of `s` contain `t`. * `absorbent`: A set `s` is absorbent if every point eventually belongs to all large scalings of `s`. * `balanced`: A set `s` is balanced if `a • s ⊆ s` for all `a` of norm less than `1`. ## References * [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966] ## Tags absorbent, balanced, locally convex, LCTVS -/ open set open_locale pointwise topological_space variables {𝕜 𝕝 E ι : Type*} section semi_normed_ring variables [semi_normed_ring 𝕜] section has_scalar variables (𝕜) [has_scalar 𝕜 E] /-- A set `A` absorbs another set `B` if `B` is contained in all scalings of `A` by elements of sufficiently large norm. -/ def absorbs (A B : set E) := ∃ r, 0 < r ∧ ∀ a : 𝕜, r ≤ ∥a∥ → B ⊆ a • A variables {𝕜} {s t u v A B : set E} @[simp] lemma absorbs_empty {s : set E}: absorbs 𝕜 s (∅ : set E) := ⟨1, one_pos, λ a ha, set.empty_subset _⟩ lemma absorbs.mono (hs : absorbs 𝕜 s u) (hst : s ⊆ t) (hvu : v ⊆ u) : absorbs 𝕜 t v := let ⟨r, hr, h⟩ := hs in ⟨r, hr, λ a ha, hvu.trans $ (h _ ha).trans $ smul_set_mono hst⟩ lemma absorbs.mono_left (hs : absorbs 𝕜 s u) (h : s ⊆ t) : absorbs 𝕜 t u := hs.mono h subset.rfl lemma absorbs.mono_right (hs : absorbs 𝕜 s u) (h : v ⊆ u) : absorbs 𝕜 s v := hs.mono subset.rfl h lemma absorbs.union (hu : absorbs 𝕜 s u) (hv : absorbs 𝕜 s v) : absorbs 𝕜 s (u ∪ v) := begin obtain ⟨a, ha, hu⟩ := hu, obtain ⟨b, hb, hv⟩ := hv, exact ⟨max a b, lt_max_of_lt_left ha, λ c hc, union_subset (hu _ $ le_of_max_le_left hc) (hv _ $ le_of_max_le_right hc)⟩, end @[simp] lemma absorbs_union : absorbs 𝕜 s (u ∪ v) ↔ absorbs 𝕜 s u ∧ absorbs 𝕜 s v := ⟨λ h, ⟨h.mono_right $ subset_union_left _ _, h.mono_right $ subset_union_right _ _⟩, λ h, h.1.union h.2⟩ lemma absorbs_Union_finset {s : set E} {t : finset ι} {f : ι → set E} : absorbs 𝕜 s (⋃ (i ∈ t), f i) ↔ ∀ i ∈ t, absorbs 𝕜 s (f i) := begin classical, induction t using finset.induction_on with i t ht hi, { simp only [finset.not_mem_empty, set.Union_false, set.Union_empty, absorbs_empty, forall_false_left, implies_true_iff] }, rw [finset.set_bUnion_insert, absorbs_union, hi], split; intro h, { refine λ _ hi', (finset.mem_insert.mp hi').elim _ (h.2 _), exact (λ hi'', by { rw hi'', exact h.1 }) }, exact ⟨h i (finset.mem_insert_self i t), λ i' hi', h i' (finset.mem_insert_of_mem hi')⟩, end lemma set.finite.absorbs_Union {s : set E} {t : set ι} {f : ι → set E} (hi : t.finite) : absorbs 𝕜 s (⋃ (i : ι) (hy : i ∈ t), f i) ↔ ∀ i ∈ t, absorbs 𝕜 s (f i) := begin lift t to finset ι using hi, simp only [finset.mem_coe], exact absorbs_Union_finset, end variables (𝕜) /-- A set is absorbent if it absorbs every singleton. -/ def absorbent (A : set E) := ∀ x, ∃ r, 0 < r ∧ ∀ a : 𝕜, r ≤ ∥a∥ → x ∈ a • A variables {𝕜} lemma absorbent.subset (hA : absorbent 𝕜 A) (hAB : A ⊆ B) : absorbent 𝕜 B := begin refine forall_imp (λ x, _) hA, exact Exists.imp (λ r, and.imp_right $ forall₂_imp $ λ a ha hx, set.smul_set_mono hAB hx), end lemma absorbent_iff_forall_absorbs_singleton : absorbent 𝕜 A ↔ ∀ x, absorbs 𝕜 A {x} := by simp_rw [absorbs, absorbent, singleton_subset_iff] lemma absorbent.absorbs (hs : absorbent 𝕜 s) {x : E} : absorbs 𝕜 s {x} := absorbent_iff_forall_absorbs_singleton.1 hs _ lemma absorbent_iff_nonneg_lt : absorbent 𝕜 A ↔ ∀ x, ∃ r, 0 ≤ r ∧ ∀ ⦃a : 𝕜⦄, r < ∥a∥ → x ∈ a • A := forall_congr $ λ x, ⟨λ ⟨r, hr, hx⟩, ⟨r, hr.le, λ a ha, hx a ha.le⟩, λ ⟨r, hr, hx⟩, ⟨r + 1, add_pos_of_nonneg_of_pos hr zero_lt_one, λ a ha, hx ((lt_add_of_pos_right r zero_lt_one).trans_le ha)⟩⟩ lemma absorbent.absorbs_finite {s : set E} (hs : absorbent 𝕜 s) {v : set E} (hv : v.finite) : absorbs 𝕜 s v := begin rw ←set.bUnion_of_singleton v, exact hv.absorbs_Union.mpr (λ _ _, hs.absorbs), end variables (𝕜) /-- A set `A` is balanced if `a • A` is contained in `A` whenever `a` has norm at most `1`. -/ def balanced (A : set E) := ∀ a : 𝕜, ∥a∥ ≤ 1 → a • A ⊆ A variables {𝕜} lemma balanced_mem {s : set E} (hs : balanced 𝕜 s) {x : E} (hx : x ∈ s) {a : 𝕜} (ha : ∥a∥ ≤ 1) : a • x ∈ s := mem_of_subset_of_mem (hs a ha) (smul_mem_smul_set hx) lemma balanced_univ : balanced 𝕜 (univ : set E) := λ a ha, subset_univ _ lemma balanced.union (hA : balanced 𝕜 A) (hB : balanced 𝕜 B) : balanced 𝕜 (A ∪ B) := begin intros a ha t ht, rw smul_set_union at ht, exact ht.imp (λ x, hA _ ha x) (λ x, hB _ ha x), end lemma balanced.inter (hA : balanced 𝕜 A) (hB : balanced 𝕜 B) : balanced 𝕜 (A ∩ B) := begin rintro a ha _ ⟨x, ⟨hx₁, hx₂⟩, rfl⟩, exact ⟨hA _ ha ⟨_, hx₁, rfl⟩, hB _ ha ⟨_, hx₂, rfl⟩⟩, end end has_scalar section add_comm_monoid variables [add_comm_monoid E] [module 𝕜 E] {s s' t t' u v A B : set E} lemma absorbs.add (h : absorbs 𝕜 s t) (h' : absorbs 𝕜 s' t') : absorbs 𝕜 (s + s') (t + t') := begin rcases h with ⟨r, hr, h⟩, rcases h' with ⟨r', hr', h'⟩, refine ⟨max r r', lt_max_of_lt_left hr, λ a ha, _⟩, rw smul_add, exact set.add_subset_add (h a (le_of_max_le_left ha)) (h' a (le_of_max_le_right ha)), end lemma balanced.add (hA₁ : balanced 𝕜 A) (hA₂ : balanced 𝕜 B) : balanced 𝕜 (A + B) := begin rintro a ha _ ⟨_, ⟨x, y, hx, hy, rfl⟩, rfl⟩, rw smul_add, exact add_mem_add (hA₁ _ ha ⟨_, hx, rfl⟩) (hA₂ _ ha ⟨_, hy, rfl⟩), end lemma zero_singleton_balanced : balanced 𝕜 ({0} : set E) := λ a ha, by simp only [smul_set_singleton, smul_zero] end add_comm_monoid end semi_normed_ring section normed_comm_ring variables [normed_comm_ring 𝕜] [add_comm_monoid E] [module 𝕜 E] {A B : set E} (a : 𝕜) lemma balanced.smul (hA : balanced 𝕜 A) : balanced 𝕜 (a • A) := begin rintro b hb _ ⟨_, ⟨x, hx, rfl⟩, rfl⟩, exact ⟨b • x, hA _ hb ⟨_, hx, rfl⟩, smul_comm _ _ _⟩, end end normed_comm_ring section normed_field variables [normed_field 𝕜] [normed_ring 𝕝] [normed_space 𝕜 𝕝] [add_comm_group E] [module 𝕜 E] [smul_with_zero 𝕝 E] [is_scalar_tower 𝕜 𝕝 E] {s t u v A B : set E} {a b : 𝕜} /-- Scalar multiplication (by possibly different types) of a balanced set is monotone. -/ lemma balanced.smul_mono (hs : balanced 𝕝 s) {a : 𝕝} {b : 𝕜} (h : ∥a∥ ≤ ∥b∥) : a • s ⊆ b • s := begin obtain rfl | hb := eq_or_ne b 0, { rw norm_zero at h, rw norm_eq_zero.1 (h.antisymm $ norm_nonneg _), obtain rfl | h := s.eq_empty_or_nonempty, { simp_rw [smul_set_empty] }, { simp_rw [zero_smul_set h] } }, rintro _ ⟨x, hx, rfl⟩, refine ⟨b⁻¹ • a • x, _, smul_inv_smul₀ hb _⟩, rw ←smul_assoc, refine hs _ _ (smul_mem_smul_set hx), rw [norm_smul, norm_inv, ←div_eq_inv_mul], exact div_le_one_of_le h (norm_nonneg _), end /-- A balanced set absorbs itself. -/ lemma balanced.absorbs_self (hA : balanced 𝕜 A) : absorbs 𝕜 A A := begin refine ⟨1, zero_lt_one, λ a ha x hx, _⟩, rw mem_smul_set_iff_inv_smul_mem₀ (norm_pos_iff.1 $ zero_lt_one.trans_le ha), refine hA a⁻¹ _ (smul_mem_smul_set hx), rw norm_inv, exact inv_le_one ha, end lemma balanced.subset_smul (hA : balanced 𝕜 A) (ha : 1 ≤ ∥a∥) : A ⊆ a • A := begin refine (subset_set_smul_iff₀ _).2 (hA (a⁻¹) _), { rintro rfl, rw norm_zero at ha, exact zero_lt_one.not_le ha }, { rw norm_inv, exact inv_le_one ha } end lemma balanced.smul_eq (hA : balanced 𝕜 A) (ha : ∥a∥ = 1) : a • A = A := (hA _ ha.le).antisymm $ hA.subset_smul ha.ge lemma absorbs.inter (hs : absorbs 𝕜 s u) (ht : absorbs 𝕜 t u) : absorbs 𝕜 (s ∩ t) u := begin obtain ⟨a, ha, hs⟩ := hs, obtain ⟨b, hb, ht⟩ := ht, have h : 0 < max a b := lt_max_of_lt_left ha, refine ⟨max a b, lt_max_of_lt_left ha, λ c hc, _⟩, rw smul_set_inter₀ (norm_pos_iff.1 $ h.trans_le hc), exact subset_inter (hs _ $ le_of_max_le_left hc) (ht _ $ le_of_max_le_right hc), end @[simp] lemma absorbs_inter : absorbs 𝕜 (s ∩ t) u ↔ absorbs 𝕜 s u ∧ absorbs 𝕜 t u := ⟨λ h, ⟨h.mono_left $ inter_subset_left _ _, h.mono_left $ inter_subset_right _ _⟩, λ h, h.1.inter h.2⟩ lemma absorbent_univ : absorbent 𝕜 (univ : set E) := begin refine λ x, ⟨1, zero_lt_one, λ a ha, _⟩, rw smul_set_univ₀ (norm_pos_iff.1 $ zero_lt_one.trans_le ha), exact trivial, end variables [topological_space E] [has_continuous_smul 𝕜 E] /-- Every neighbourhood of the origin is absorbent. -/ lemma absorbent_nhds_zero (hA : A ∈ 𝓝 (0 : E)) : absorbent 𝕜 A := begin intro x, obtain ⟨w, hw₁, hw₂, hw₃⟩ := mem_nhds_iff.mp hA, have hc : continuous (λ t : 𝕜, t • x) := continuous_id.smul continuous_const, obtain ⟨r, hr₁, hr₂⟩ := metric.is_open_iff.mp (hw₂.preimage hc) 0 (by rwa [mem_preimage, zero_smul]), have hr₃ := inv_pos.mpr (half_pos hr₁), refine ⟨(r / 2)⁻¹, hr₃, λ a ha₁, _⟩, have ha₂ : 0 < ∥a∥ := hr₃.trans_le ha₁, refine (mem_smul_set_iff_inv_smul_mem₀ (norm_pos_iff.mp ha₂) _ _).2 (hw₁ $ hr₂ _), rw [metric.mem_ball, dist_zero_right, norm_inv], calc ∥a∥⁻¹ ≤ r/2 : (inv_le (half_pos hr₁) ha₂).mp ha₁ ... < r : half_lt_self hr₁, end /-- The union of `{0}` with the interior of a balanced set is balanced. -/ lemma balanced_zero_union_interior (hA : balanced 𝕜 A) : balanced 𝕜 ((0 : set E) ∪ interior A) := begin intros a ha, obtain rfl | h := eq_or_ne a 0, { rw zero_smul_set, exacts [subset_union_left _ _, ⟨0, or.inl rfl⟩] }, { rw [←image_smul, image_union], apply union_subset_union, { rw [image_zero, smul_zero], refl }, { calc a • interior A ⊆ interior (a • A) : (is_open_map_smul₀ h).image_interior_subset A ... ⊆ interior A : interior_mono (hA _ ha) } } end /-- The interior of a balanced set is balanced if it contains the origin. -/ lemma balanced.interior (hA : balanced 𝕜 A) (h : (0 : E) ∈ interior A) : balanced 𝕜 (interior A) := begin rw ←union_eq_self_of_subset_left (singleton_subset_iff.2 h), exact balanced_zero_union_interior hA, end lemma balanced.closure (hA : balanced 𝕜 A) : balanced 𝕜 (closure A) := λ a ha, (image_closure_subset_closure_image $ continuous_id.const_smul _).trans $ closure_mono $ hA _ ha end normed_field section nondiscrete_normed_field variables [nondiscrete_normed_field 𝕜] [add_comm_group E] [module 𝕜 E] {s : set E} lemma absorbs_zero_iff : absorbs 𝕜 s 0 ↔ (0 : E) ∈ s := begin refine ⟨_, λ h, ⟨1, zero_lt_one, λ a _, zero_subset.2 $ zero_mem_smul_set h⟩⟩, rintro ⟨r, hr, h⟩, obtain ⟨a, ha⟩ := normed_space.exists_lt_norm 𝕜 𝕜 r, have := h _ ha.le, rwa [zero_subset, zero_mem_smul_set_iff] at this, exact norm_ne_zero_iff.1 (hr.trans ha).ne', end lemma absorbent.zero_mem (hs : absorbent 𝕜 s) : (0 : E) ∈ s := absorbs_zero_iff.1 $ absorbent_iff_forall_absorbs_singleton.1 hs _ end nondiscrete_normed_field
5bbe7190282e9face41d318d44223d6b668977b7
df561f413cfe0a88b1056655515399c546ff32a5
/3-multiplication-world/l4.lean
b24d5811910b6824f5be44375211ea00c93583ae
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
210
lean
lemma mul_add (t a b : mynat) : t * (a + b) = t * a + t * b := begin induction b with k Pk, rw mul_zero, repeat { rw add_zero }, rw mul_succ, rw ← add_assoc, rw ← Pk, rw ← mul_succ, rw add_succ, refl, end
9f61ea116f139516afa600e097c46e462298ce93
38193807b9085b93599c814229d2b0dacb64ba22
/benchmarks/optimize/Optimize.lean
8698062592f113ee2afa943d9d195658ec0d29d9
[]
no_license
zgrannan/rest-old
d650363e403a9d5322fb44ee892b743aec558e1b
6a6974641b25259cb8701af4302169db22b33b6b
refs/heads/master
1,670,816,037,466
1,599,571,928,000
1,599,571,928,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
327
lean
open nat def sumSeries : ℕ → ℕ | zero := zero | (succ n) := succ n + sumSeries n def sumSeries' : ℕ → ℕ | n := (n * (succ n)) / 2 theorem isOpt : ∀ (n : ℕ) , sumSeries n = sumSeries' n := sorry theorem proof (n : ℕ) (f : ℕ -> ℕ → ℕ) : f (sumSeries n) = f (sumSeries' n) := by simp [isOpt]
e85d4813b1d6fa7672844a7441860c7d83edf440
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Server/InfoUtils.lean
101a835b7d506566f1c1c2b24455ea5c4e2e45dd
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,807
lean
/- Copyright (c) 2021 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.DocString import Lean.Elab.InfoTree import Lean.Util.Sorry namespace Lean.Elab /-- Find the deepest node matching `p` in the first subtree which contains a matching node. The result is wrapped in all outer `ContextInfo`s. -/ partial def InfoTree.smallestNode? (p : Info → Bool) : InfoTree → Option InfoTree | context i t => context i <$> t.smallestNode? p | n@(node i cs) => let cs := cs.map (·.smallestNode? p) let cs := cs.filter (·.isSome) if !cs.isEmpty then cs.get! 0 else if p i then some n else none | _ => none /-- For every branch, find the deepest node in that branch matching `p` and return all of them. Each result is wrapped in all outer `ContextInfo`s. -/ partial def InfoTree.smallestNodes (p : Info → Bool) : InfoTree → List InfoTree | context i t => t.smallestNodes p |>.map (context i) | n@(node i cs) => let cs := cs.toList let ccs := cs.map (smallestNodes p) let cs := ccs.join if !cs.isEmpty then cs else if p i then [n] else [] | _ => [] def Info.stx : Info → Syntax | ofTacticInfo i => i.stx | ofTermInfo i => i.stx | ofMacroExpansionInfo i => i.before | ofFieldInfo i => i.stx def Info.pos? (i : Info) : Option String.Pos := i.stx.getPos? (originalOnly := true) def Info.tailPos? (i : Info) : Option String.Pos := i.stx.getTailPos? (originalOnly := true) def InfoTree.smallestInfo? (p : Info → Bool) (t : InfoTree) : Option (ContextInfo × Info) := let ts := t.smallestNodes p let infos : List (Nat × ContextInfo × Info) := ts.filterMap fun | context ci (node i _) => let diff := i.tailPos?.get! - i.pos?.get! some (diff, ci, i) | _ => none infos.toArray.getMax? (fun a b => a.1 > b.1) |>.map fun (_, ci, i) => (ci, i) /-- Find an info node, if any, which should be shown on hover/cursor at position `hoverPos`. -/ partial def InfoTree.hoverableInfoAt? (t : InfoTree) (hoverPos : String.Pos) : Option (ContextInfo × Info) := t.smallestInfo? fun i => if let (some pos, some tailPos) := (i.pos?, i.tailPos?) then if pos ≤ hoverPos ∧ hoverPos < tailPos then match i with | Info.ofTermInfo ti => !ti.expr.isSyntheticSorry && -- TODO: see if we can get rid of this #[identKind, strLitKind, charLitKind, numLitKind, scientificLitKind, nameLitKind, fieldIdxKind, interpolatedStrLitKind, interpolatedStrKind ].contains i.stx.getKind | Info.ofFieldInfo _ => true | _ => false else false else false /-- Construct a hover popup, if any, from an info node in a context.-/ def Info.fmtHover? (ci : ContextInfo) (i : Info) : IO (Option Format) := do let lctx ← match i with | Info.ofTermInfo i => i.lctx | Info.ofFieldInfo i => i.lctx | _ => return none ci.runMetaM lctx do match i with | Info.ofTermInfo ti => let tp ← Meta.inferType ti.expr let eFmt ← Meta.ppExpr ti.expr let tpFmt ← Meta.ppExpr tp let hoverFmt := f!"```lean {eFmt} : {tpFmt} ```" if let some n := ti.expr.constName? then if let some doc ← findDocString? n then return f!"{hoverFmt}\n***\n{doc}" return hoverFmt | Info.ofFieldInfo fi => let tp ← Meta.inferType fi.val let tpFmt ← Meta.ppExpr tp return f!"```lean {fi.name} : {tpFmt} ```" | _ => return none /-- Return a flattened list of smallest-in-span tactic info nodes, sorted by position. -/ partial def InfoTree.smallestTacticStates (t : InfoTree) : Array (Nat × ContextInfo × TacticInfo) := let ts := tacticLeaves t let ts := ts.filterMap fun | context ci (node i@(Info.ofTacticInfo ti) _) => some (i.pos?.get!, ci, ti) | _ => none ts.toArray.qsort fun a b => a.1 < b.1 where tacticLeaves (t : InfoTree) : List InfoTree := t.smallestNodes fun | i@(Info.ofTacticInfo _) => i.pos?.isSome ∧ i.tailPos?.isSome | _ => false partial def InfoTree.goalsAt? (t : InfoTree) (hoverPos : String.Pos) : Option (ContextInfo × TacticInfo) := let ts := t.smallestTacticStates -- The extent of a tactic state is (pos, pos of next tactic) let extents := ts.mapIdx fun i (p, _, ti) => (p, if h : (i.val+1) < ts.size then ts.get ⟨i.val+1, h⟩ |>.1 else ti.stx.getTailPos?.get!) let idx? := extents.findIdx? fun (p, tp) => p ≤ hoverPos ∧ hoverPos < tp idx?.map fun idx => ts.get! idx |> fun (_, ci, ti) => (ci, ti) end Lean.Elab
cf6146f18be9da36f119acb684b86220a7398484
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/nat/bitwise.lean
159359c85cfa2bb75ffceee14f938b6dc6d824e3
[ "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
9,661
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import data.nat.bits import tactic.linarith /-! # Bitwise operations on natural numbers In the first half of this file, we provide theorems for reasoning about natural numbers from their bitwise properties. In the second half of this file, we show properties of the bitwise operations `lor`, `land` and `lxor`, which are defined in core. ## Main results * `eq_of_test_bit_eq`: two natural numbers are equal if they have equal bits at every position. * `exists_most_significant_bit`: if `n ≠ 0`, then there is some position `i` that contains the most significant `1`-bit of `n`. * `lt_of_test_bit`: if `n` and `m` are numbers and `i` is a position such that the `i`-th bit of of `n` is zero, the `i`-th bit of `m` is one, and all more significant bits are equal, then `n < m`. ## Future work There is another way to express bitwise properties of natural number: `digits 2`. The two ways should be connected. ## Keywords bitwise, and, or, xor -/ open function namespace nat @[simp] lemma bit_ff : bit ff = bit0 := rfl @[simp] lemma bit_tt : bit tt = bit1 := rfl @[simp] lemma bit_eq_zero {n : ℕ} {b : bool} : n.bit b = 0 ↔ n = 0 ∧ b = ff := by { cases b; norm_num [bit0_eq_zero, nat.bit1_ne_zero] } lemma zero_of_test_bit_eq_ff {n : ℕ} (h : ∀ i, test_bit n i = ff) : n = 0 := begin induction n using nat.binary_rec with b n hn, { refl }, { have : b = ff := by simpa using h 0, rw [this, bit_ff, bit0_val, hn (λ i, by rw [←h (i + 1), test_bit_succ]), mul_zero] } end @[simp] lemma zero_test_bit (i : ℕ) : test_bit 0 i = ff := by simp [test_bit] /-- The ith bit is the ith element of `n.bits`. -/ lemma test_bit_eq_inth (n i : ℕ) : n.test_bit i = n.bits.inth i := begin induction i with i ih generalizing n, { simp [test_bit, shiftr, bodd_eq_bits_head, list.inth_zero_eq_head], }, conv_lhs { rw ← bit_decomp n, }, rw [test_bit_succ, ih n.div2, div2_bits_eq_tail], cases n.bits; simp, end /-- Bitwise extensionality: Two numbers agree if they agree at every bit position. -/ lemma eq_of_test_bit_eq {n m : ℕ} (h : ∀ i, test_bit n i = test_bit m i) : n = m := begin induction n using nat.binary_rec with b n hn generalizing m, { simp only [zero_test_bit] at h, exact (zero_of_test_bit_eq_ff (λ i, (h i).symm)).symm }, induction m using nat.binary_rec with b' m hm, { simp only [zero_test_bit] at h, exact zero_of_test_bit_eq_ff h }, suffices h' : n = m, { rw [h', show b = b', by simpa using h 0] }, exact hn (λ i, by convert h (i + 1) using 1; rw test_bit_succ) end lemma exists_most_significant_bit {n : ℕ} (h : n ≠ 0) : ∃ i, test_bit n i = tt ∧ ∀ j, i < j → test_bit n j = ff := begin induction n using nat.binary_rec with b n hn, { exact false.elim (h rfl) }, by_cases h' : n = 0, { subst h', rw (show b = tt, by { revert h, cases b; simp }), refine ⟨0, ⟨by rw [test_bit_zero], λ j hj, _⟩⟩, obtain ⟨j', rfl⟩ := exists_eq_succ_of_ne_zero (ne_of_gt hj), rw [test_bit_succ, zero_test_bit] }, { obtain ⟨k, ⟨hk, hk'⟩⟩ := hn h', refine ⟨k + 1, ⟨by rw [test_bit_succ, hk], λ j hj, _⟩⟩, obtain ⟨j', rfl⟩ := exists_eq_succ_of_ne_zero (show j ≠ 0, by linarith), exact (test_bit_succ _ _ _).trans (hk' _ (lt_of_succ_lt_succ hj)) } end lemma lt_of_test_bit {n m : ℕ} (i : ℕ) (hn : test_bit n i = ff) (hm : test_bit m i = tt) (hnm : ∀ j, i < j → test_bit n j = test_bit m j) : n < m := begin induction n using nat.binary_rec with b n hn' generalizing i m, { contrapose! hm, rw le_zero_iff at hm, simp [hm] }, induction m using nat.binary_rec with b' m hm' generalizing i, { exact false.elim (bool.ff_ne_tt ((zero_test_bit i).symm.trans hm)) }, by_cases hi : i = 0, { subst hi, simp only [test_bit_zero] at hn hm, have : n = m, { exact eq_of_test_bit_eq (λ i, by convert hnm (i + 1) dec_trivial using 1; rw test_bit_succ) }, rw [hn, hm, this, bit_ff, bit_tt, bit0_val, bit1_val], exact lt_add_one _ }, { obtain ⟨i', rfl⟩ := exists_eq_succ_of_ne_zero hi, simp only [test_bit_succ] at hn hm, have := hn' _ hn hm (λ j hj, by convert hnm j.succ (succ_lt_succ hj) using 1; rw test_bit_succ), cases b; cases b'; simp only [bit_ff, bit_tt, bit0_val n, bit1_val n, bit0_val m, bit1_val m]; linarith } end @[simp] lemma test_bit_two_pow_self (n : ℕ) : test_bit (2 ^ n) n = tt := by rw [test_bit, shiftr_eq_div_pow, nat.div_self (pow_pos zero_lt_two n), bodd_one] lemma test_bit_two_pow_of_ne {n m : ℕ} (hm : n ≠ m) : test_bit (2 ^ n) m = ff := begin rw [test_bit, shiftr_eq_div_pow], cases hm.lt_or_lt with hm hm, { rw [nat.div_eq_zero, bodd_zero], exact nat.pow_lt_pow_of_lt_right one_lt_two hm }, { rw [pow_div hm.le zero_lt_two, ← tsub_add_cancel_of_le (succ_le_of_lt $ tsub_pos_of_lt hm)], simp [pow_succ] } end lemma test_bit_two_pow (n m : ℕ) : test_bit (2 ^ n) m = (n = m) := begin by_cases n = m, { cases h, simp }, { rw test_bit_two_pow_of_ne h, simp [h] } end /-- If `f` is a commutative operation on bools such that `f ff ff = ff`, then `bitwise f` is also commutative. -/ lemma bitwise_comm {f : bool → bool → bool} (hf : ∀ b b', f b b' = f b' b) (hf' : f ff ff = ff) (n m : ℕ) : bitwise f n m = bitwise f m n := suffices bitwise f = swap (bitwise f), by conv_lhs { rw this }, calc bitwise f = bitwise (swap f) : congr_arg _ $ funext $ λ _, funext $ hf _ ... = swap (bitwise f) : bitwise_swap hf' lemma lor_comm (n m : ℕ) : lor n m = lor m n := bitwise_comm bool.bor_comm rfl n m lemma land_comm (n m : ℕ) : land n m = land m n := bitwise_comm bool.band_comm rfl n m lemma lxor_comm (n m : ℕ) : lxor n m = lxor m n := bitwise_comm bool.bxor_comm rfl n m @[simp] lemma zero_lxor (n : ℕ) : lxor 0 n = n := by simp [lxor] @[simp] lemma lxor_zero (n : ℕ) : lxor n 0 = n := by simp [lxor] @[simp] lemma zero_land (n : ℕ) : land 0 n = 0 := by simp [land] @[simp] lemma land_zero (n : ℕ) : land n 0 = 0 := by simp [land] @[simp] lemma zero_lor (n : ℕ) : lor 0 n = n := by simp [lor] @[simp] lemma lor_zero (n : ℕ) : lor n 0 = n := by simp [lor] /-- Proving associativity of bitwise operations in general essentially boils down to a huge case distinction, so it is shorter to use this tactic instead of proving it in the general case. -/ meta def bitwise_assoc_tac : tactic unit := `[induction n using nat.binary_rec with b n hn generalizing m k, { simp }, induction m using nat.binary_rec with b' m hm, { simp }, induction k using nat.binary_rec with b'' k hk; simp [hn]] lemma lxor_assoc (n m k : ℕ) : lxor (lxor n m) k = lxor n (lxor m k) := by bitwise_assoc_tac lemma land_assoc (n m k : ℕ) : land (land n m) k = land n (land m k) := by bitwise_assoc_tac lemma lor_assoc (n m k : ℕ) : lor (lor n m) k = lor n (lor m k) := by bitwise_assoc_tac @[simp] lemma lxor_self (n : ℕ) : lxor n n = 0 := zero_of_test_bit_eq_ff $ λ i, by simp -- These lemmas match `mul_inv_cancel_right` and `mul_inv_cancel_left`. lemma lxor_cancel_right (n m : ℕ) : lxor (lxor m n) n = m := by rw [lxor_assoc, lxor_self, lxor_zero] lemma lxor_cancel_left (n m : ℕ) : lxor n (lxor n m) = m := by rw [←lxor_assoc, lxor_self, zero_lxor] lemma lxor_right_injective {n : ℕ} : function.injective (lxor n) := λ m m' h, by rw [←lxor_cancel_left n m, ←lxor_cancel_left n m', h] lemma lxor_left_injective {n : ℕ} : function.injective (λ m, lxor m n) := λ m m' (h : lxor m n = lxor m' n), by rw [←lxor_cancel_right n m, ←lxor_cancel_right n m', h] @[simp] lemma lxor_right_inj {n m m' : ℕ} : lxor n m = lxor n m' ↔ m = m' := lxor_right_injective.eq_iff @[simp] lemma lxor_left_inj {n m m' : ℕ} : lxor m n = lxor m' n ↔ m = m' := lxor_left_injective.eq_iff @[simp] lemma lxor_eq_zero {n m : ℕ} : lxor n m = 0 ↔ n = m := by rw [←lxor_self n, lxor_right_inj, eq_comm] lemma lxor_ne_zero {n m : ℕ} : lxor n m ≠ 0 ↔ n ≠ m := lxor_eq_zero.not lemma lxor_trichotomy {a b c : ℕ} (h : a ≠ lxor b c) : lxor b c < a ∨ lxor a c < b ∨ lxor a b < c := begin set v := lxor a (lxor b c) with hv, -- The xor of any two of `a`, `b`, `c` is the xor of `v` and the third. have hab : lxor a b = lxor c v, { rw hv, conv_rhs { rw lxor_comm, simp [lxor_assoc] } }, have hac : lxor a c = lxor b v, { rw hv, conv_rhs { congr, skip, rw lxor_comm }, rw [←lxor_assoc, ←lxor_assoc, lxor_self, zero_lxor, lxor_comm] }, have hbc : lxor b c = lxor a v, { simp [hv, ←lxor_assoc] }, -- If `i` is the position of the most significant bit of `v`, then at least one of `a`, `b`, `c` -- has a one bit at position `i`. obtain ⟨i, ⟨hi, hi'⟩⟩ := exists_most_significant_bit (lxor_ne_zero.2 h), have : test_bit a i = tt ∨ test_bit b i = tt ∨ test_bit c i = tt, { contrapose! hi, simp only [eq_ff_eq_not_eq_tt, ne, test_bit_lxor] at ⊢ hi, rw [hi.1, hi.2.1, hi.2.2, bxor_ff, bxor_ff] }, -- If, say, `a` has a one bit at position `i`, then `a xor v` has a zero bit at position `i`, but -- the same bits as `a` in positions greater than `j`, so `a xor v < a`. rcases this with h|h|h; [{ left, rw hbc }, { right, left, rw hac }, { right, right, rw hab }]; exact lt_of_test_bit i (by simp [h, hi]) h (λ j hj, by simp [hi' _ hj]) end lemma lt_lxor_cases {a b c : ℕ} (h : a < lxor b c) : lxor a c < b ∨ lxor a b < c := (or_iff_right $ λ h', (h.asymm h').elim).1 $ lxor_trichotomy h.ne end nat
9ce56b2d1d66af5f5e43974be26814b2582b2633
05b503addd423dd68145d68b8cde5cd595d74365
/src/topology/separation.lean
ef241a065f60f8e1b8ebb108c50928c7b6d53762
[ "Apache-2.0" ]
permissive
aestriplex/mathlib
77513ff2b176d74a3bec114f33b519069788811d
e2fa8b2b1b732d7c25119229e3cdfba8370cb00f
refs/heads/master
1,621,969,960,692
1,586,279,279,000
1,586,279,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,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, Mario Carneiro Separation properties of topological spaces. -/ import topology.subset_properties open set filter open_locale topological_space local attribute [instance] classical.prop_decidable -- TODO: use "open_locale classical" universes u v variables {α : Type u} {β : Type v} [topological_space α] section separation /-- A T₀ space, also known as a Kolmogorov space, is a topological space where for every pair `x ≠ y`, there is an open set containing one but not the other. -/ class t0_space (α : Type u) [topological_space α] : Prop := (t0 : ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U))) theorem exists_open_singleton_of_fintype [t0_space α] [f : fintype α] [decidable_eq α] [ha : nonempty α] : ∃ x:α, is_open ({x}:set α) := have H : ∀ (T : finset α), T ≠ ∅ → ∃ x ∈ T, ∃ u, is_open u ∧ {x} = {y | y ∈ T} ∩ u := begin intro T, apply finset.case_strong_induction_on T, { intro h, exact (h rfl).elim }, { intros x S hxS ih h, by_cases hs : S = ∅, { existsi [x, finset.mem_insert_self x S, univ, is_open_univ], rw [hs, inter_univ], refl }, { rcases ih S (finset.subset.refl S) hs with ⟨y, hy, V, hv1, hv2⟩, by_cases hxV : x ∈ V, { cases t0_space.t0 x y (λ hxy, hxS $ by rwa hxy) with U hu, rcases hu with ⟨hu1, ⟨hu2, hu3⟩ | ⟨hu2, hu3⟩⟩, { existsi [x, finset.mem_insert_self x S, U ∩ V, is_open_inter hu1 hv1], apply set.ext, intro z, split, { intro hzx, rw set.mem_singleton_iff at hzx, rw hzx, exact ⟨finset.mem_insert_self x S, ⟨hu2, hxV⟩⟩ }, { intro hz, rw set.mem_singleton_iff, rcases hz with ⟨hz1, hz2, hz3⟩, cases finset.mem_insert.1 hz1 with hz4 hz4, { exact hz4 }, { have h1 : z ∈ {y : α | y ∈ S} ∩ V, { exact ⟨hz4, hz3⟩ }, rw ← hv2 at h1, rw set.mem_singleton_iff at h1, rw h1 at hz2, exact (hu3 hz2).elim } } }, { existsi [y, finset.mem_insert_of_mem hy, U ∩ V, is_open_inter hu1 hv1], apply set.ext, intro z, split, { intro hz, rw set.mem_singleton_iff at hz, rw hz, refine ⟨finset.mem_insert_of_mem hy, hu2, _⟩, have h1 : y ∈ {y} := set.mem_singleton y, rw hv2 at h1, exact h1.2 }, { intro hz, rw set.mem_singleton_iff, cases hz with hz1 hz2, cases finset.mem_insert.1 hz1 with hz3 hz3, { rw hz3 at hz2, exact (hu3 hz2.1).elim }, { have h1 : z ∈ {y : α | y ∈ S} ∩ V := ⟨hz3, hz2.2⟩, rw ← hv2 at h1, rw set.mem_singleton_iff at h1, exact h1 } } } }, { existsi [y, finset.mem_insert_of_mem hy, V, hv1], apply set.ext, intro z, split, { intro hz, rw set.mem_singleton_iff at hz, rw hz, split, { exact finset.mem_insert_of_mem hy }, { have h1 : y ∈ {y} := set.mem_singleton y, rw hv2 at h1, exact h1.2 } }, { intro hz, rw hv2, cases hz with hz1 hz2, cases finset.mem_insert.1 hz1 with hz3 hz3, { rw hz3 at hz2, exact (hxV hz2).elim }, { exact ⟨hz3, hz2⟩ } } } } } end, begin apply nonempty.elim ha, intro x, specialize H finset.univ (finset.ne_empty_of_mem $ finset.mem_univ x), rcases H with ⟨y, hyf, U, hu1, hu2⟩, existsi y, have h1 : {y : α | y ∈ finset.univ} = (univ : set α), { exact set.eq_univ_of_forall (λ x : α, by rw mem_set_of_eq; exact finset.mem_univ x) }, rw h1 at hu2, rw set.univ_inter at hu2, rw hu2, exact hu1 end /-- A T₁ space, also known as a Fréchet space, is a topological space where every singleton set is closed. Equivalently, for every pair `x ≠ y`, there is an open set containing `x` and not `y`. -/ class t1_space (α : Type u) [topological_space α] : Prop := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x @[priority 100] -- see Note [lower instance priority] instance t1_space.t0_space [t1_space α] : t0_space α := ⟨λ x y h, ⟨-{x}, is_open_compl_iff.2 is_closed_singleton, or.inr ⟨λ hyx, or.cases_on hyx h.symm id, λ hx, hx $ or.inl rfl⟩⟩⟩ lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : - {x} ∈ 𝓝 y := mem_nhds_sets is_closed_singleton $ by rwa [mem_compl_eq, mem_singleton_iff] @[simp] lemma closure_singleton [t1_space α] {a : α} : closure ({a} : set α) = {a} := closure_eq_of_is_closed is_closed_singleton /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ class t2_space (α : Type u) [topological_space α] : Prop := (t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅) lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := t2_space.t2 x y h @[priority 100] -- see Note [lower instance priority] instance t2_space.t1_space [t2_space α] : t1_space α := ⟨λ x, is_open_iff_forall_mem_open.2 $ λ y hxy, let ⟨u, v, hu, hv, hyu, hxv, huv⟩ := t2_separation (mt mem_singleton_of_eq hxy) in ⟨u, λ z hz1 hz2, ((ext_iff _ _).1 huv x).1 ⟨mem_singleton_iff.1 hz2 ▸ hz1, hxv⟩, hu, hyu⟩⟩ lemma eq_of_nhds_ne_bot [ht : t2_space α] {x y : α} (h : 𝓝 x ⊓ 𝓝 y ≠ ⊥) : x = y := classical.by_contradiction $ assume : x ≠ y, let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in have u ∩ v ∈ 𝓝 x ⊓ 𝓝 y, from inter_mem_inf_sets (mem_nhds_sets hu hx) (mem_nhds_sets hv hy), h $ empty_in_sets_eq_bot.mp $ huv ▸ this lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, 𝓝 x ⊓ 𝓝 y ≠ ⊥ → x = y := ⟨assume h, by exactI λ x y, eq_of_nhds_ne_bot, assume h, ⟨assume x y xy, have 𝓝 x ⊓ 𝓝 y = ⊥ := classical.by_contradiction (mt h xy), let ⟨u', hu', v', hv', u'v'⟩ := empty_in_sets_eq_bot.mpr this, ⟨u, uu', uo, hu⟩ := mem_nhds_sets_iff.mp hu', ⟨v, vv', vo, hv⟩ := mem_nhds_sets_iff.mp hv' in ⟨u, v, uo, vo, hu, hv, disjoint.eq_bot $ disjoint.mono uu' vv' u'v'⟩⟩⟩ lemma t2_iff_ultrafilter : t2_space α ↔ ∀ f {x y : α}, is_ultrafilter f → f ≤ 𝓝 x → f ≤ 𝓝 y → x = y := t2_iff_nhds.trans ⟨assume h f x y u fx fy, h $ ne_bot_of_le_ne_bot u.1 (le_inf fx fy), assume h x y xy, let ⟨f, hf, uf⟩ := exists_ultrafilter xy in h f uf (le_trans hf inf_le_left) (le_trans hf inf_le_right)⟩ @[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : 𝓝 a = 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [h, inf_idem]; exact nhds_ne_bot, assume h, h ▸ rfl⟩ @[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : 𝓝 a ≤ 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [inf_of_le_left h]; exact nhds_ne_bot, assume h, h ▸ le_refl _⟩ lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : l ≠ ⊥) (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le_ne_bot (map_ne_bot hl) $ le_inf ha hb section lim variables [nonempty α] [t2_space α] {f : filter α} lemma lim_eq {a : α} (hf : f ≠ ⊥) (h : f ≤ 𝓝 a) : lim f = a := eq_of_nhds_ne_bot $ ne_bot_of_le_ne_bot hf $ le_inf (lim_spec ⟨_, h⟩) h @[simp] lemma lim_nhds_eq {a : α} : lim (𝓝 a) = a := lim_eq nhds_ne_bot (le_refl _) @[simp] lemma lim_nhds_eq_of_closure {a : α} {s : set α} (h : a ∈ closure s) : lim (𝓝 a ⊓ principal s) = a := lim_eq begin rw [closure_eq_nhds] at h, exact h end inf_le_left end lim @[priority 100] -- see Note [lower instance priority] instance t2_space_discrete {α : Type*} [topological_space α] [discrete_topology α] : t2_space α := { t2 := assume x y hxy, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, mem_insert _ _, mem_insert _ _, eq_empty_iff_forall_not_mem.2 $ by intros z hz; cases eq_of_mem_singleton hz.1; cases eq_of_mem_singleton hz.2; cc⟩ } private lemma separated_by_f {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] [t2_space β] (f : α → β) (hf : tα ≤ tβ.induced f) {x y : α} (h : f x ≠ f y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f ⁻¹' u, f ⁻¹' v, hf _ ⟨u, uo, rfl⟩, hf _ ⟨v, vo, rfl⟩, xu, yv, by rw [←preimage_inter, uv, preimage_empty]⟩ instance {α : Type*} {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) := ⟨assume x y h, separated_by_f subtype.val (le_refl _) (mt subtype.eq h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α × β) := ⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h, or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h)) (λ h₁, separated_by_f prod.fst inf_le_left h₁) (λ h₂, separated_by_f prod.snd inf_le_right h₂)⟩ instance Pi.t2_space {α : Type*} {β : α → Type v} [t₂ : Πa, topological_space (β a)] [Πa, t2_space (β a)] : t2_space (Πa, β a) := ⟨assume x y h, let ⟨i, hi⟩ := not_forall.mp (mt funext h) in separated_by_f (λz, z i) (infi_le _ i) hi⟩ lemma is_closed_diagonal [t2_space α] : is_closed {p:α×α | p.1 = p.2} := is_closed_iff_nhds.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_ne_bot $ assume : 𝓝 a₁ ⊓ 𝓝 a₂ = ⊥, h $ let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ := by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in begin change t₁ ∈ 𝓝 a₁ at ht₁, change t₂ ∈ 𝓝 a₂ at ht₂, rw [nhds_prod_eq, ←empty_in_sets_eq_bot], apply filter.sets_of_superset, apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)), exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩, show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩ end variables [topological_space β] lemma is_closed_eq [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal lemma diagonal_eq_range_diagonal_map {α : Type*} : {p:α×α | p.1 = p.2} = range (λx, (x,x)) := ext $ assume p, iff.intro (assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩) (assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx) lemma prod_subset_compl_diagonal_iff_disjoint {α : Type*} {s t : set α} : set.prod s t ⊆ - {p:α×α | p.1 = p.2} ↔ s ∩ t = ∅ := by rw [eq_empty_iff_forall_not_mem, subset_compl_comm, diagonal_eq_range_diagonal_map, range_subset_iff]; simp lemma compact_compact_separated [t2_space α] {s t : set α} (hs : compact s) (ht : compact t) (hst : s ∩ t = ∅) : ∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ := by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal hst lemma closed_of_compact [t2_space α] (s : set α) (hs : compact s) : is_closed s := is_open_compl_iff.mpr $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := compact_compact_separated hs (compact_singleton : compact {x}) (by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in have v ⊆ -s, from subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)), ⟨v, this, vo, by simpa using xv⟩ lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ 𝓝 x ∧ compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := compact_compact_separated compact_singleton (compact_diff kc uo) (by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in have wn : -w ∈ 𝓝 x, from mem_nhds_sets_iff.mpr ⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩, ⟨k - w, filter.inter_mem_sets kx wn, subset.trans (diff_subset_comm.mp kuw) un, compact_diff kc wo⟩⟩ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, compact_univ⟩) end separation section regularity section prio set_option default_priority 100 -- see Note [default priority] /-- A T₃ space, also known as a regular space (although this condition sometimes omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist disjoint open sets containing `x` and `C` respectively. -/ class regular_space (α : Type u) [topological_space α] extends t1_space α : Prop := (regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ 𝓝 a ⊓ principal t = ⊥) end prio lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ 𝓝 a) : ∃t∈(𝓝 a), t ⊆ s ∧ is_closed t := let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in have ∃t, is_open t ∧ -s' ⊆ t ∧ 𝓝 a ⊓ principal t = ⊥, from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃), let ⟨t, ht₁, ht₂, ht₃⟩ := this in ⟨-t, mem_sets_of_eq_bot $ by rwa [compl_compl], subset.trans (compl_subset_comm.1 ht₂) h₁, is_closed_compl_iff.mpr ht₁⟩ variable (α) @[priority 100] -- see Note [lower instance priority] instance regular_space.t2_space [regular_space α] : t2_space α := ⟨λ x y hxy, let ⟨s, hs, hys, hxs⟩ := regular_space.regular is_closed_singleton (mt mem_singleton_iff.1 hxy), ⟨t, hxt, u, hsu, htu⟩ := empty_in_sets_eq_bot.2 hxs, ⟨v, hvt, hv, hxv⟩ := mem_nhds_sets_iff.1 hxt in ⟨v, s, hv, hs, hxv, singleton_subset_iff.1 hys, eq_empty_of_subset_empty $ λ z ⟨hzv, hzs⟩, htu ⟨hvt hzv, hsu hzs⟩⟩⟩ end regularity section normality section prio set_option default_priority 100 -- see Note [default priority] /-- A T₄ space, also known as a normal space (although this condition sometimes omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`, there exist disjoint open sets containing `C` and `D` respectively. -/ class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop := (normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t → ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v) end prio theorem normal_separation [normal_space α] (s t : set α) (H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) : ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v := normal_space.normal s t H1 H2 H3 @[priority 100] -- see Note [lower instance priority] instance normal_space.regular_space [normal_space α] : regular_space α := { regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation s {x} hs is_closed_singleton (λ _ ⟨hx, hy⟩, hxs $ set.mem_of_eq_of_mem (set.eq_of_mem_singleton hy).symm hx) in ⟨u, hu, hsu, filter.empty_in_sets_eq_bot.1 $ filter.mem_inf_sets.2 ⟨v, mem_nhds_sets hv (set.singleton_subset_iff.1 hxv), u, filter.mem_principal_self u, set.inter_comm u v ▸ huv⟩⟩ } -- We can't make this an instance because it could cause an instance loop. lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α := begin refine ⟨assume s t hs ht st, _⟩, simp only [disjoint_iff], exact compact_compact_separated hs.compact ht.compact st.eq_bot end end normality
a5068f60f4e01d9fa607b9625013980f6ba09d97
a7dd8b83f933e72c40845fd168dde330f050b1c9
/docs/tutorial/category_theory/calculating_colimits_in_Top.lean
2b86ab64ad1d4301c058068cf9099b2ee9821c72
[ "Apache-2.0" ]
permissive
NeilStrickland/mathlib
10420e92ee5cb7aba1163c9a01dea2f04652ed67
3efbd6f6dff0fb9b0946849b43b39948560a1ffe
refs/heads/master
1,589,043,046,346
1,558,938,706,000
1,558,938,706,000
181,285,984
0
0
Apache-2.0
1,568,941,848,000
1,555,233,833,000
Lean
UTF-8
Lean
false
false
2,934
lean
import category_theory.instances.Top.limits import category_theory.limits.shapes import topology.instances.real /- This file contains some demos of using the (co)limits API to do topology. -/ noncomputable theory open category_theory open category_theory.instances open category_theory.limits def R : Top := Top.of ℝ def I : Top := Top.of (set.Icc 0 1 : set ℝ) def pt : Top := Top.of unit section MappingCylinder -- Let's construct the mapping cylinder. def to_pt (X : Top) : X ⟶ pt := { val := λ _, unit.star, property := continuous_const } def I_0 : pt ⟶ I := { val := λ _, ⟨(0 : ℝ), begin rw [set.left_mem_Icc], norm_num, end⟩, property := continuous_const } def I_1 : pt ⟶ I := { val := λ _, ⟨(1 : ℝ), begin rw [set.right_mem_Icc], norm_num, end⟩, property := continuous_const } def cylinder (X : Top) : Top := limit (pair X I) -- To define a map to the cylinder, we give a map to each factor. -- `binary_fan.mk` is a helper method for constructing a `cone` over `pair X Y`. def cylinder_0 (X : Top) : X ⟶ cylinder X := limit.lift (pair X I) (binary_fan.mk (𝟙 X) (to_pt X ≫ I_0)) def cylinder_1 (X : Top) : X ⟶ cylinder X := limit.lift (pair X I) (binary_fan.mk (𝟙 X) (to_pt X ≫ I_1)) -- The mapping cylinder is the colimit of the diagram -- X -- ↙ ↘ -- Y (X x I) def mapping_cylinder {X Y : Top} (f : X ⟶ Y) : Top := colimit (span f (cylinder_1 X)) -- The mapping cone is the colimit of the diagram -- X X -- ↙ ↘ ↙ ↘ -- Y (X x I) pt -- Here we'll calculate it as an iterated colimit, as the colimit of -- X -- ↙ ↘ -- (Cyl f) pt def mapping_cylinder_0 {X Y : Top} (f : X ⟶ Y) : X ⟶ mapping_cylinder f := cylinder_0 X ≫ colimit.ι (span f (cylinder_1 X)) walking_span.right def mapping_cone {X Y : Top} (f : X ⟶ Y) : Top := colimit (span (mapping_cylinder_0 f) (to_pt X)) -- TODO Hopefully someone will write a nice tactic for generating diagrams quickly, -- and we'll be able to verify that this iterated construction is the same as the colimit -- over a single diagram. end MappingCylinder section Gluing -- Here's two copies of the real line glued together at a point. def f : pt ⟶ R := { val := λ _, (0 : ℝ), property := continuous_const } def X : Top := colimit (span f f) -- To define a map out of it, we define maps out of each copy of the line, -- and check the maps agree at 0. -- `pushout_cocone.mk` is a helper method for constructing cocones over a span. def g : X ⟶ R := colimit.desc (span f f) (pushout_cocone.mk (𝟙 _) (𝟙 _) rfl). end Gluing universes v u w section Products def d : discrete ℕ ⥤ Top := functor.of_function (λ n : ℕ, R) def Y : Top := limit d def w : cone d := fan.mk (λ (n : ℕ), ⟨λ (_ : pt), (n : ℝ), continuous_const⟩) def q : pt ⟶ Y := limit.lift d w example : (q.val ()).val (57 : ℕ) = ((57 : ℕ) : ℝ) := rfl end Products
8c5fa588af04c4bd6ff2a1d49f223112440daf1a
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/class7.lean
8e4f710439edea8ce84a7772e1e2d7150564aefb
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
472
lean
import logic open tactic inductive inh [class] (A : Type) : Type := intro : A -> inh A theorem inh_bool [instance] : inh Prop := inh.intro true set_option elaborator.trace_instances true theorem inh_fun [instance] {A B : Type} (H : inh B) : inh (A → B) := inh.rec (λ b, inh.intro (λ a : A, b)) H theorem tst {A B : Type} (H : inh B) : inh (A → B → B) theorem T1 {A : Type} (a : A) : inh A := by repeat [apply @inh.intro | eassumption] theorem T2 : inh Prop
161a19614a0eba27d46905f9ab94f9cc210a7556
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/matchArrayLit.lean
d0430ea3ec0cf4e474428fad64bd61615bba4d19
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
2,475
lean
universe u v theorem eqLitOfSize0 {α : Type u} (a : Array α) (hsz : a.size = 0) : a = #[] := a.toArrayLitEq 0 hsz theorem eqLitOfSize1 {α : Type u} (a : Array α) (hsz : a.size = 1) : a = #[a.getLit 0 hsz (ofDecideEqTrue rfl)] := a.toArrayLitEq 1 hsz theorem eqLitOfSize2 {α : Type u} (a : Array α) (hsz : a.size = 2) : a = #[a.getLit 0 hsz (ofDecideEqTrue rfl), a.getLit 1 hsz (ofDecideEqTrue rfl)] := a.toArrayLitEq 2 hsz theorem eqLitOfSize3 {α : Type u} (a : Array α) (hsz : a.size = 3) : a = #[a.getLit 0 hsz (ofDecideEqTrue rfl), a.getLit 1 hsz (ofDecideEqTrue rfl), a.getLit 2 hsz (ofDecideEqTrue rfl)] := a.toArrayLitEq 3 hsz /- Matcher for the following patterns ``` | #[] => _ | #[a₁] => _ | #[a₁, a₂, a₃] => _ | a => _ ``` -/ def matchArrayLit {α : Type u} (C : Array α → Sort v) (a : Array α) (h₁ : Unit → C #[]) (h₂ : ∀ a₁, C #[a₁]) (h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃]) (h₄ : ∀ a, C a) : C a := if h : a.size = 0 then @Eq.rec _ _ (fun x _ => C x) (h₁ ()) _ (a.toArrayLitEq 0 h).symm else if h : a.size = 1 then @Eq.rec _ _ (fun x _ => C x) (h₂ (a.getLit 0 h (ofDecideEqTrue rfl))) _ (a.toArrayLitEq 1 h).symm else if h : a.size = 3 then @Eq.rec _ _ (fun x _ => C x) (h₃ (a.getLit 0 h (ofDecideEqTrue rfl)) (a.getLit 1 h (ofDecideEqTrue rfl)) (a.getLit 2 h (ofDecideEqTrue rfl))) _ (a.toArrayLitEq 3 h).symm else h₄ a /- Equational lemmas that should be generated automatically. -/ theorem matchArrayLit.eq1 {α : Type u} (C : Array α → Sort v) (h₁ : Unit → C #[]) (h₂ : ∀ a₁, C #[a₁]) (h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃]) (h₄ : ∀ a, C a) : matchArrayLit C #[] h₁ h₂ h₃ h₄ = h₁ () := rfl theorem matchArrayLit.eq2 {α : Type u} (C : Array α → Sort v) (h₁ : Unit → C #[]) (h₂ : ∀ a₁, C #[a₁]) (h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃]) (h₄ : ∀ a, C a) (a₁ : α) : matchArrayLit C #[a₁] h₁ h₂ h₃ h₄ = h₂ a₁ := rfl theorem matchArrayLit.eq3 {α : Type u} (C : Array α → Sort v) (h₁ : Unit → C #[]) (h₂ : ∀ a₁, C #[a₁]) (h₃ : ∀ a₁ a₂ a₃, C #[a₁, a₂, a₃]) (h₄ : ∀ a, C a) (a₁ a₂ a₃ : α) : matchArrayLit C #[a₁, a₂, a₃] h₁ h₂ h₃ h₄ = h₃ a₁ a₂ a₃ := rfl
ca60603475882a0d8d0965b67f98717985012bba
7c2dd01406c42053207061adb11703dc7ce0b5e5
/src/exercises/06_sub_sequences.lean
986acc2f343f332777097d5efbb15c7857d45552
[ "Apache-2.0" ]
permissive
leanprover-community/tutorials
50ec79564cbf2ad1afd1ac43d8ee3c592c2883a8
79a6872a755c4ae0c2aca57e1adfdac38b1d8bb1
refs/heads/master
1,687,466,144,386
1,672,061,276,000
1,672,061,276,000
189,169,918
186
81
Apache-2.0
1,686,350,300,000
1,559,113,678,000
Lean
UTF-8
Lean
false
false
3,271
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 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 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 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 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 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 end
903999f5533cb53df5601bd4e2aa104b0aa666d0
e898bfefd5cb60a60220830c5eba68cab8d02c79
/uexp/src/uexp/rules/pullConstantThroughUnion3.lean
bfc2e6f6c4f98d57f1663e98919bcd8da81eb657
[ "BSD-2-Clause" ]
permissive
kkpapa/Cosette
9ed09e2dc4c1ecdef815c30b5501f64a7383a2ce
fda8fdbbf0de6c1be9b4104b87bbb06cede46329
refs/heads/master
1,584,573,128,049
1,526,370,422,000
1,526,370,422,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,017
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..UDP set_option profiler true open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int constant integer_2: const int constant integer_3: const int theorem Rule: forall (Γ scm_t scm_account scm_bonus scm_dept scm_emp: Schema) (rel_t: relation scm_t) (rel_account: relation scm_account) (rel_bonus: relation scm_bonus) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (t_k0 : Column int scm_t) (t_c1 : Column int scm_t) (t_f1_a0 : Column int scm_t) (t_f2_a0 : Column int scm_t) (t_f0_c0 : Column int scm_t) (t_f1_c0 : Column int scm_t) (t_f0_c1 : Column int scm_t) (t_f1_c2 : Column int scm_t) (t_f2_c3 : Column int scm_t) (account_acctno : Column int scm_account) (account_type : Column int scm_account) (account_balance : Column int scm_account) (bonus_ename : Column int scm_bonus) (bonus_job : Column int scm_bonus) (bonus_sal : Column int scm_bonus) (bonus_comm : Column int scm_bonus) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL (((SELECT1 (combine (e2p (constantExpr integer_2)) (e2p (constantExpr integer_3))) FROM1 (table rel_emp) )) UNION ALL ((SELECT1 (combine (e2p (constantExpr integer_2)) (e2p (constantExpr integer_3))) FROM1 (table rel_emp) )) :SQL Γ _) = denoteSQL ((SELECT1 (combine (e2p (constantExpr integer_2)) (e2p (constantExpr integer_3))) FROM1 (((SELECT1 (e2p (constantExpr integer_2)) FROM1 (table rel_emp) )) UNION ALL ((SELECT1 (e2p (constantExpr integer_2)) FROM1 (table rel_emp) ))) ) : SQL Γ _):= begin intros, unfold_all_denotations, funext, print_size, simp, print_size, UDP, end
c47d4242d2470d0fb5517d71204727a46e7b5ff7
fe84e287c662151bb313504482b218a503b972f3
/src/combinatorics/domino.lean
231474360beb1ed43de159db3f798a5d4f62b19b
[]
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
11,763
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland (This is part of an attempt to formalise some material from a basic undergraduate combinatorics course.) A "domino" means a subset of ℕ × ℕ of the form {i} × {j,j+1} or {i,i+1} × {j}. Given a finite subset B ⊆ ℕ × ℕ, we ask whether B can be written as a disjoint union of dominos. One basic tool that we can use is the chessboard colouring map c : ℕ × ℕ → {black,white}. (Probably it is more convenient to use bool = {ff,tt} instead of {black,white}.) If B can be covered by a disjoint set of dominos, then it is clear that the number of black squares in B must be equal to the number of white squares. Examples should be given to show that the converse fails. -/ import data.fintype.basic algebra.group algebra.big_operators.basic tactic.ring namespace combinatorics lemma finset.mem_pair {α : Type} [decidable_eq α] {u v w : α} : u ∈ [v,w].to_finset ↔ u = v ∨ u = w := by { intros, simp } lemma finset.pair_eq {α : Type} [decidable_eq α] {u v w x : α} : [u,v].to_finset = [w,x].to_finset ↔ (u = w ∧ v = x) ∨ (u = x ∧ v = w) := begin split, { intro h, have hu : u ∈ [u,v].to_finset := by simp, have hv : v ∈ [u,v].to_finset := by simp, have hw : w ∈ [w,x].to_finset := by simp, have hx : x ∈ [w,x].to_finset := by simp, rw [ h, finset.mem_pair] at hu hv, rw [← h, finset.mem_pair] at hw hx, cases hu with hu hu; cases hu; cases hv with hv hv; cases hv; cases hw with hw hw; cases hw; cases hx with hx hx; cases hx; try { left , exact ⟨rfl,rfl⟩ } ; try { right, exact ⟨rfl,rfl⟩ } }, { intro h, cases h with h h; rcases h with ⟨⟨h₀⟩,⟨h₁⟩⟩, { refl }, { ext z, rw[finset.mem_pair, finset.mem_pair], split; exact or.symm } } end lemma finset.pair_disjoint {α : Type} [decidable_eq α] {u v w x : α} : disjoint [u,v].to_finset [w,x].to_finset ↔ (u ≠ w ∧ u ≠ x ∧ v ≠ w ∧ v ≠ x) := begin rw [disjoint_iff], change _ ∩ _ = ∅ ↔ _, rw [finset.eq_empty_iff_forall_not_mem], split, { intro h, have hu := h u, have hv := h v, have hw := h w, have hx := h x, rw [finset.mem_inter, finset.mem_pair, finset.mem_pair, decidable.not_and_iff_or_not, decidable.not_or_iff_and_not,decidable.not_or_iff_and_not] at hu hv hw hx, tauto }, { rintro ⟨h₀,h₁,h₂,h₃⟩ a ha, rw [ finset.mem_inter, finset.mem_pair, finset.mem_pair ] at ha, cases ha with ha₀ ha₁, cases ha₀ with ha₀ ha₀; cases ha₀; cases ha₁ with ha₁ ha₁; cases ha₁; contradiction } end lemma prod.ne {α β : Type*} [decidable_eq α] [decidable_eq β] (a a' : α) (b b' : β) : prod.mk a b ≠ prod.mk a' b' ↔ (a ≠ a' ∨ b ≠ b') := begin rw [ne,prod.eq_iff_fst_eq_snd_eq, decidable.not_and_iff_or_not] end lemma mem_list_union {α : Type*} [decidable_eq α] {a : α} {l : list (finset α)} : a ∈ l.foldr has_union.union ∅ ↔ ∃ s, s ∈ l ∧ a ∈ s := begin induction l with s l ih, { rw [list.foldr], split; intro h, { exfalso, exact finset.not_mem_empty a h }, { rcases h with ⟨s,hs⟩, exfalso, exact list.not_mem_nil s hs.left } }, { rw [list.foldr, finset.mem_union], split; intro h, { cases h, { use s, exact ⟨list.mem_cons_self s l,h⟩ }, { rcases (ih.mp h) with ⟨t,ht⟩, use t, exact ⟨list.mem_cons_of_mem s ht.left, ht.right⟩ } }, { rcases h with ⟨t,ht⟩, rcases (list.mem_cons_iff t s l).mp ht.left with ⟨⟨_⟩|ht⟩ , { left, exact ht.right }, { right, exact ih.mpr ⟨t,⟨h,ht.right⟩⟩ } } } end namespace chess def square := ℕ × ℕ namespace square lemma eq_iff {u v : square} : u = v ↔ u.1 = v.1 ∧ u.2 = v.2 := prod.eq_iff_fst_eq_snd_eq def rank : square → ℕ := λ u, u.1 + u.2 def color : square → bool := λ u, u.rank.bodd def hstep : square → square := λ u, ⟨u.1 + 1,u.2⟩ def vstep : square → square := λ u, ⟨u.1,u.2 + 1⟩ lemma hstep_eq (u v : square) : u.hstep = v.hstep ↔ u = v := begin cases u with i j, cases v with k l, rw [eq_iff, eq_iff], change i + 1 = k + 1 ∧ j = l ↔ i = k ∧ j = l, rw [nat.succ_inj'] end lemma vstep_eq (u v : square) : u.vstep = v.vstep ↔ u = v := begin cases u with i j, cases v with k l, rw [eq_iff, eq_iff], change i = k ∧ j + 1 = l + 1 ↔ i = k ∧ j = l, rw [nat.succ_inj'] end lemma hstep_ne_self (u : square) : u.hstep ≠ u := λ h, by { rw[eq_iff] at h, exact nat.succ_ne_self _ h.1 } lemma vstep_ne_self (u : square) : u.vstep ≠ u := λ h, by { rw[eq_iff] at h, exact nat.succ_ne_self _ h.2 } lemma rank_vstep (u : square) : u.vstep.rank = u.rank + 1 := rfl lemma rank_hstep (u : square) : u.hstep.rank = u.rank + 1 := nat.succ_add _ _ lemma color_vstep (u : square) : u.vstep.color = bnot u.color := by { simp only [color], rw [rank_vstep, nat.bodd_succ] } lemma color_hstep (u : square) : u.hstep.color = bnot u.color := by { simp only [color], rw [rank_hstep, nat.bodd_succ] } end square def count_pair := bool → ℕ namespace count_pair instance : add_comm_monoid count_pair := by {unfold count_pair, pi_instance, } def both : count_pair | _ := 1 def delta : bool → count_pair | ff ff := 1 | ff tt := 0 | tt ff := 0 | tt tt := 1 def delta' (n : ℕ) : count_pair := delta n.bodd def tot : count_pair →+ ℕ := { to_fun := λ x, (x ff) + (x tt), map_zero' := rfl, map_add' := λ u v, begin change ((u ff) + (v ff)) + ((u tt) + (v tt)) = ((u ff) + (u tt)) + ((v ff) + (v tt)), rw[add_assoc,← add_assoc (v ff)], rw[add_comm (v ff) (u tt),add_assoc,add_assoc], end } lemma tot_both : tot both = 2 := rfl lemma tot_delta : ∀ b : bool, tot (delta b) = 1 | ff := rfl | tt := rfl lemma delta_succ (b : bool) : (delta b) + (delta (bnot b)) = both := by { ext x, cases b; cases x; refl } lemma delta'_succ (n : ℕ) : (delta' n) + (delta' n.succ) = both := by { dsimp [delta'], rw [nat.bodd_succ], exact delta_succ n.bodd } lemma tot_delta' (n : ℕ) : tot (delta' n) = 1 := tot_delta n.bodd def diff : count_pair →+ ℤ := { to_fun := λ x, (x tt) - (x ff), map_zero' := rfl, map_add' := λ u v, begin have : (u + v) tt = (u tt) + (v tt) := rfl, rw[this,int.coe_nat_add], have : (u + v) ff = (u ff) + (v ff) := rfl, rw[this,int.coe_nat_add], ring, end } lemma diff_both : diff both = 0 := rfl end count_pair open chess def color_count (s : finset square) : count_pair := s.sum (λ x, (count_pair.delta x.color)) def black_count (s : finset square) : ℕ := color_count s ff def white_count (s : finset square) : ℕ := color_count s tt def color_diff (s : finset (ℕ × ℕ)) : ℤ := (color_count s).diff lemma count_eq (s : finset (ℕ × ℕ)) : (color_count s).tot = s.card := begin rw[color_count,count_pair.tot.map_sum], have : (λ x : square, (count_pair.delta x.color).tot) = (λ x, 1) := by {funext, apply count_pair.tot_delta}, rw[this,finset.sum_const,smul_eq_mul,mul_one] end namespace color_count lemma empty : color_count ∅ = 0 := by {rw[color_count,finset.sum_empty]} lemma sum (s t : finset square) : (color_count (s ∪ t)) + (color_count (s ∩ t)) = (color_count s) + (color_count t) := finset.sum_union_inter lemma disjoint_sum (s t : finset (ℕ × ℕ)) (h : disjoint s t) : (color_count (s ∪ t)) = (color_count s) + (color_count t) := finset.sum_union h lemma disjoint_sum' (ss : list (finset (ℕ × ℕ))) (h : ss.pairwise disjoint) : color_count (ss.foldr has_union.union ∅) = (ss.map color_count).sum := begin induction ss with s ss ih, { refl }, { let t := ss.foldr has_union.union ∅, rw [list.pairwise_cons] at h, rw [list.foldr, list.map, list.sum_cons, ← ih h.right], apply disjoint_sum s t, rw [disjoint_iff], change s ∩ t = ∅, apply finset.eq_empty_of_forall_not_mem, intros x hx, replace hx := finset.mem_inter.mp hx, rcases mem_list_union.mp hx.right with ⟨u,hu⟩, have hx' := finset.mem_inter.mpr ⟨hx.1,hu.2⟩, have hsu : s ∩ u = ∅ := disjoint_iff.mp (h.left u hu.left), rw [hsu] at hx', exact finset.not_mem_empty x hx' } end end color_count end chess open chess inductive domino : Type | horizontal : square → domino | vertical : square → domino namespace domino def to_list : domino → list square | (horizontal u) := [u, u.hstep] | (vertical u) := [u, u.vstep] lemma to_list_length (d : domino) : d.to_list.length = 2 := by { cases d; refl } lemma to_list_nodup (d : domino) : d.to_list.nodup := begin cases d with u u; simp [to_list, list.nodup_cons], exact u.hstep_ne_self.symm, exact u.vstep_ne_self.symm end def to_finset (d : domino) : finset square := ⟨d.to_list,d.to_list_nodup⟩ lemma to_list_coe (d : domino) : d.to_finset = d.to_list.to_finset := list.to_finset_eq d.to_list_nodup lemma color_count (d : domino) : color_count d.to_finset = count_pair.both := begin rw [chess.color_count], rw [finset.sum_eq_multiset_sum d.to_finset (count_pair.delta ∘ square.color)], have : d.to_finset.val = d.to_list := rfl, rw [this, multiset.coe_map, multiset.coe_sum], cases d with u u; rw [to_list, list.map_cons, list.map_singleton, list.sum_cons, list.sum_cons, list.sum_nil, add_zero]; rw [function.comp_app, function.comp_app], rw [square.color_hstep, count_pair.delta_succ], rw [square.color_vstep, count_pair.delta_succ] end lemma color_diff (d : domino) : (chess.color_count d.to_finset).diff = 0 := by { rw[color_count],refl } def overlap : domino → domino → Prop | (horizontal u) (horizontal v) := u = v ∨ u = v.hstep ∨ u.hstep = v | (horizontal u) (vertical v) := u = v ∨ u = v.vstep ∨ u.hstep = v ∨ u.hstep = v.vstep | (vertical u) (horizontal v) := u = v ∨ u = v.hstep ∨ u.vstep = v ∨ u.vstep = v.hstep | (vertical u) (vertical v) := u = v ∨ u = v.vstep ∨ u.vstep = v instance overlap_dec : decidable_rel overlap := λ a b, by {cases a with u u; cases b with v v; rw[overlap]; apply_instance} def disjoint : domino → domino → Prop := λ a b , ¬ (overlap a b) instance disjoint_dec : decidable_rel disjoint := λ a b, by {dsimp[disjoint],apply_instance} lemma disjoint_iff {a b : domino} : disjoint a b ↔ _root_.disjoint a.to_finset b.to_finset := begin cases a with u u; cases b with v v; simp only [disjoint, to_list_coe, to_list, finset.pair_disjoint, ne]; rw [overlap]; try { rw[square.hstep_eq] at * }; try { rw[square.vstep_eq] at * }; tauto end def track (l : list domino) := (l.map to_finset).foldr has_union.union ∅ def is_cover (s : finset (ℕ × ℕ)) (l : list domino) := l.pairwise disjoint ∧ (track l) = s def has_cover (s : finset (ℕ × ℕ)) := ∃ l, is_cover s l lemma diff_eq_zero_aux (l : list domino) : (((l.map to_finset).map chess.color_count).map count_pair.diff).sum = 0 := begin induction l with d l0 ih, {refl}, { rw[list.map_cons,list.map_cons,list.map_cons,color_diff,list.sum_cons,ih,add_zero] } end lemma diff_eq_zero {l : list domino} (hl : l.pairwise disjoint) : (chess.color_count (track l)).diff = 0 := begin let h₀ := list.pairwise.imp (λ a b,(@disjoint_iff a b).mp) hl, let h₁ := (list.pairwise_map to_finset).mpr h₀, let h₂ : (chess.color_count (track l)) = _ := chess.color_count.disjoint_sum' (l.map to_finset) h₁, rw[h₂,count_pair.diff.map_list_sum,diff_eq_zero_aux], end end domino end combinatorics
230e6af9434ea70f038a58d73e2daad1c67c3ec7
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/number_theory/zsqrtd/basic.lean
89d07fd537d81a6618215812ef0a02052a368128
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
33,343
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 ring_theory.int.basic import tactic.ring /-! # ℤ[√d] The ring of integers adjoined with a square root of `d : ℤ`. After defining the norm, we show that it is a linearly ordered commutative ring, as well as an integral domain. We provide the universal property, that ring homomorphisms `ℤ√d →+* R` correspond to choices of square roots of `d` in `R`. -/ /-- 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. -/ 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 -/ instance : has_zero ℤ√d := ⟨of_int 0⟩ @[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 -/ instance : has_one ℤ√d := ⟨of_int 1⟩ @[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` -/ instance : has_add ℤ√d := ⟨λ z w, ⟨z.1 + w.1, z.2 + w.2⟩⟩ @[simp] lemma add_def (x y x' y' : ℤ) : (⟨x, y⟩ + ⟨x', y'⟩ : ℤ√d) = ⟨x + x', y + y'⟩ := rfl @[simp] lemma add_re (z w : ℤ√d) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℤ√d) : (z + w).im = z.im + w.im := rfl @[simp] lemma bit0_re (z) : (bit0 z : ℤ√d).re = bit0 z.re := rfl @[simp] lemma bit0_im (z) : (bit0 z : ℤ√d).im = bit0 z.im := rfl @[simp] theorem bit1_re (z) : (bit1 z : ℤ√d).re = bit1 z.re := rfl @[simp] theorem bit1_im (z) : (bit1 z : ℤ√d).im = bit0 z.im := by simp [bit1] /-- Negation in `ℤ√d` -/ instance : has_neg ℤ√d := ⟨λ z, ⟨-z.1, -z.2⟩⟩ @[simp] lemma neg_re (z : ℤ√d) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℤ√d) : (-z).im = -z.im := rfl /-- Multiplication in `ℤ√d` -/ instance : has_mul ℤ√d := ⟨λ z w, ⟨z.1 * w.1 + d * z.2 * w.2, z.1 * w.2 + z.2 * w.1⟩⟩ @[simp] lemma mul_re (z w : ℤ√d) : (z * w).re = z.re * w.re + d * z.im * w.im := rfl @[simp] lemma mul_im (z w : ℤ√d) : (z * w).im = z.re * w.im + z.im * w.re := rfl instance : add_comm_group ℤ√d := by refine_struct { add := (+), zero := (0 : ℤ√d), sub := λ a b, a + -b, neg := has_neg.neg, zsmul := @zsmul_rec (ℤ√d) ⟨0⟩ ⟨(+)⟩ ⟨has_neg.neg⟩, nsmul := @nsmul_rec (ℤ√d) ⟨0⟩ ⟨(+)⟩ }; intros; try { refl }; simp [ext, add_comm, add_left_comm] instance : add_group_with_one ℤ√d := { nat_cast := λ n, of_int n, int_cast := of_int, one := 1, .. zsqrtd.add_comm_group } instance : comm_ring ℤ√d := by refine_struct { add := (+), zero := (0 : ℤ√d), mul := (*), one := 1, npow := @npow_rec (ℤ√d) ⟨1⟩ ⟨(*)⟩, .. zsqrtd.add_group_with_one }; intros; try { refl }; simp [ext, add_mul, mul_add, add_comm, add_left_comm, mul_comm, mul_left_comm] 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 /-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/ def conj (z : ℤ√d) : ℤ√d := ⟨z.1, -z.2⟩ @[simp] lemma conj_re (z : ℤ√d) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℤ√d) : (conj z).im = -z.im := rfl /-- `conj` as an `add_monoid_hom`. -/ def conj_hom : ℤ√d →+ ℤ√d := { to_fun := conj, map_add' := λ ⟨a, ai⟩ ⟨b, bi⟩, ext.mpr ⟨rfl, neg_add _ _⟩, map_zero' := ext.mpr ⟨rfl, neg_zero⟩ } @[simp] lemma conj_zero : conj (0 : ℤ√d) = 0 := conj_hom.map_zero @[simp] lemma conj_one : conj (1 : ℤ√d) = 1 := by simp only [zsqrtd.ext, zsqrtd.conj_re, zsqrtd.conj_im, zsqrtd.one_im, neg_zero, eq_self_iff_true, and_self] @[simp] lemma conj_neg (x : ℤ√d) : (-x).conj = -x.conj := rfl @[simp] lemma conj_add (x y : ℤ√d) : (x + y).conj = x.conj + y.conj := conj_hom.map_add x y @[simp] lemma conj_sub (x y : ℤ√d) : (x - y).conj = x.conj - y.conj := conj_hom.map_sub x y @[simp] lemma conj_conj {d : ℤ} (x : ℤ√d) : x.conj.conj = x := by simp only [ext, true_and, conj_re, eq_self_iff_true, neg_neg, conj_im] instance : nontrivial ℤ√d := ⟨⟨0, 1, dec_trivial⟩⟩ @[simp] theorem coe_nat_re (n : ℕ) : (n : ℤ√d).re = n := rfl @[simp] theorem coe_nat_im (n : ℕ) : (n : ℤ√d).im = 0 := rfl theorem coe_nat_val (n : ℕ) : (n : ℤ√d) = ⟨n, 0⟩ := rfl @[simp] theorem coe_int_re (n : ℤ) : (n : ℤ√d).re = n := by cases n; refl @[simp] theorem coe_int_im (n : ℤ) : (n : ℤ√d).im = 0 := by cases n; refl 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] theorem smul_re (a : ℤ) (b : ℤ√d) : (↑a * b).re = a * b.re := by simp theorem smul_im (a : ℤ) (b : ℤ√d) : (↑a * b).im = a * b.im := by simp @[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 lemma coe_int_dvd_iff (z : ℤ) (a : ℤ√d) : ↑z ∣ a ↔ z ∣ a.re ∧ z ∣ a.im := begin split, { rintro ⟨x, rfl⟩, simp only [add_zero, coe_int_re, zero_mul, mul_im, dvd_mul_right, and_self, mul_re, mul_zero, coe_int_im] }, { rintro ⟨⟨r, hr⟩, ⟨i, hi⟩⟩, use ⟨r, i⟩, rw [smul_val, ext], exact ⟨hr, hi⟩ }, end @[simp, norm_cast] lemma coe_int_dvd_coe_int (a b : ℤ) : (a : ℤ√d) ∣ b ↔ a ∣ b := begin rw coe_int_dvd_iff, split, { rintro ⟨hre, -⟩, rwa [coe_int_re] at hre }, { rw [coe_int_re, coe_int_im], exact λ hc, ⟨hc, dvd_zero a⟩ }, end protected lemma eq_of_smul_eq_smul_left {a : ℤ} {b c : ℤ√d} (ha : a ≠ 0) (h : ↑a * b = a * c) : b = c := begin rw ext at h ⊢, apply and.imp _ _ h; { simp only [smul_re, smul_im], exact int.eq_of_mul_eq_mul_left ha }, end section gcd lemma gcd_eq_zero_iff (a : ℤ√d) : int.gcd a.re a.im = 0 ↔ a = 0 := by simp only [int.gcd_eq_zero_iff, ext, eq_self_iff_true, zero_im, zero_re] lemma gcd_pos_iff (a : ℤ√d) : 0 < int.gcd a.re a.im ↔ a ≠ 0 := pos_iff_ne_zero.trans $ not_congr a.gcd_eq_zero_iff lemma coprime_of_dvd_coprime {a b : ℤ√d} (hcoprime : is_coprime a.re a.im) (hdvd : b ∣ a) : is_coprime b.re b.im := begin apply is_coprime_of_dvd, { rintro ⟨hre, him⟩, obtain rfl : b = 0, { simp only [ext, hre, eq_self_iff_true, zero_im, him, and_self, zero_re] }, rw zero_dvd_iff at hdvd, simpa only [hdvd, zero_im, zero_re, not_coprime_zero_zero] using hcoprime }, { intros z hz hznezero hzdvdu hzdvdv, apply hz, obtain ⟨ha, hb⟩ : z ∣ a.re ∧ z ∣ a.im, { rw ←coe_int_dvd_iff, apply dvd_trans _ hdvd, rw coe_int_dvd_iff, exact ⟨hzdvdu, hzdvdv⟩ }, exact hcoprime.is_unit_of_dvd' ha hb }, end lemma exists_coprime_of_gcd_pos {a : ℤ√d} (hgcd : 0 < int.gcd a.re a.im) : ∃ b : ℤ√d, a = ((int.gcd a.re a.im : ℤ) : ℤ√d) * b ∧ is_coprime b.re b.im := begin obtain ⟨re, im, H1, Hre, Him⟩ := int.exists_gcd_one hgcd, rw [mul_comm] at Hre Him, refine ⟨⟨re, im⟩, _, _⟩, { rw [smul_val, ext, ←Hre, ←Him], split; refl }, { rw [←int.gcd_eq_one_iff_coprime, H1] } end end gcd /-- 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 /-- The norm of an element of `ℤ[√d]`. -/ def norm (n : ℤ√d) : ℤ := n.re * n.re - d * n.im * n.im lemma norm_def (n : ℤ√d) : n.norm = n.re * n.re - d * n.im * n.im := rfl @[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 } /-- `norm` as a `monoid_hom`. -/ def norm_monoid_hom : ℤ√d →* ℤ := { to_fun := norm, map_mul' := norm_mul, map_one' := norm_one } 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] @[simp] lemma norm_neg (x : ℤ√d) : (-x).norm = x.norm := coe_int_inj $ by simp only [norm_eq_mul_conj, conj_neg, neg_mul, mul_neg, neg_neg] @[simp] lemma norm_conj (x : ℤ√d) : x.conj.norm = x.norm := coe_int_inj $ by simp only [norm_eq_mul_conj, conj_conj, mul_comm] 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⟩ lemma is_unit_iff_norm_is_unit {d : ℤ} (z : ℤ√d) : is_unit z ↔ is_unit z.norm := by rw [int.is_unit_iff_nat_abs_eq, norm_eq_one_iff] lemma norm_eq_one_iff' {d : ℤ} (hd : d ≤ 0) (z : ℤ√d) : z.norm = 1 ↔ is_unit z := by rw [←norm_eq_one_iff, ←int.coe_nat_inj', int.nat_abs_of_nonneg (norm_nonneg hd z), int.coe_nat_one] lemma norm_eq_zero_iff {d : ℤ} (hd : d < 0) (z : ℤ√d) : z.norm = 0 ↔ z = 0 := begin split, { intro h, rw [ext, zero_re, zero_im], rw [norm_def, sub_eq_add_neg, mul_assoc] at h, have left := mul_self_nonneg z.re, have right := neg_nonneg.mpr (mul_nonpos_of_nonpos_of_nonneg hd.le (mul_self_nonneg z.im)), obtain ⟨ha, hb⟩ := (add_eq_zero_iff' left right).mp h, split; apply eq_zero_of_mul_self_eq_zero, { exact ha }, { rw [neg_eq_zero, mul_eq_zero] at hb, exact hb.resolve_left hd.ne } }, { rintro rfl, exact norm_zero } end lemma norm_eq_of_associated {d : ℤ} (hd : d ≤ 0) {x y : ℤ√d} (h : associated x y) : x.norm = y.norm := begin obtain ⟨u, rfl⟩ := h, rw [norm_mul, (norm_eq_one_iff' hd _).mpr u.is_unit, mul_one], end end norm end section parameter {d : ℕ} /-- Nonnegativity of an element of `ℤ√d`. -/ def nonneg : ℤ√d → Prop | ⟨a, b⟩ := nonnegg d 1 a b instance : has_le ℤ√d := ⟨λ a b, nonneg (b - a)⟩ instance : has_lt ℤ√d := ⟨λ a b, ¬ b ≤ a⟩ 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 : @decidable_rel (ℤ√d) (≤) := λ _ _, 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_rfl 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 lemma 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⟩, { 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 h)) }, { apply nat.le_add_right } }, { dsimp, 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 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 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 := begin have t := (b - a).nonneg_total, rwa neg_sub at t, end instance : preorder ℤ√d := { le := (≤), le_refl := λ a, show nonneg (a - a), by simp only [sub_self], le_trans := λ a b c hab hbc, by simpa [sub_add_sub_cancel'] using hab.add hbc, lt := (<), lt_iff_le_not_le := λ a b, (and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm } 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, h.trans _⟩, 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 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 simp only [← int.cast_coe_nat] {single_pass := tt}; 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_smul ha).add (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_sq (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_sq _ _) | ⟨-[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_sq _ _) 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_left h1, have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero_left 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 : is_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_ring ℤ√d := by apply_instance instance : ordered_ring ℤ√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} @[ext] lemma hom_ext [ring R] {d : ℤ} (f g : ℤ√d →+* R) (h : f sqrtd = g sqrtd) : f = g := begin ext ⟨x_re, x_im⟩, simp [decompose, h], end variables [comm_ring R] /-- 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, 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) := (injective_iff_map_eq_zero (lift r)).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
0b2b3bbf4724b4a064c5133cfc7095a6d8ece5e0
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/number_theory/fermat4.lean
9e1d004c2ff4942ce93c70d3ed92833af262f997
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,333
lean
/- Copyright (c) 2020 Paul van Wamelen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Paul van Wamelen -/ import number_theory.pythagorean_triples import ring_theory.coprime.lemmas /-! # Fermat's Last Theorem for the case n = 4 There are no non-zero integers `a`, `b` and `c` such that `a ^ 4 + b ^ 4 = c ^ 4`. -/ noncomputable theory open_locale classical /-- Shorthand for three non-zero integers `a`, `b`, and `c` satisfying `a ^ 4 + b ^ 4 = c ^ 2`. We will show that no integers satisfy this equation. Clearly Fermat's Last theorem for n = 4 follows. -/ def fermat_42 (a b c : ℤ) : Prop := a ≠ 0 ∧ b ≠ 0 ∧ a ^ 4 + b ^ 4 = c ^ 2 namespace fermat_42 lemma comm {a b c : ℤ} : (fermat_42 a b c) ↔ (fermat_42 b a c) := by { delta fermat_42, rw add_comm, tauto } lemma mul {a b c k : ℤ} (hk0 : k ≠ 0) : fermat_42 a b c ↔ fermat_42 (k * a) (k * b) (k ^ 2 * c) := begin delta fermat_42, split, { intro f42, split, { exact mul_ne_zero hk0 f42.1 }, split, { exact mul_ne_zero hk0 f42.2.1 }, { calc (k * a) ^ 4 + (k * b) ^ 4 = k ^ 4 * (a ^ 4 + b ^ 4) : by ring ... = k ^ 4 * c ^ 2 : by rw f42.2.2 ... = (k ^ 2 * c) ^ 2 : by ring }}, { intro f42, split, { exact right_ne_zero_of_mul f42.1 }, split, { exact right_ne_zero_of_mul f42.2.1 }, apply (mul_right_inj' (pow_ne_zero 4 hk0)).mp, { calc k ^ 4 * (a ^ 4 + b ^ 4) = (k * a) ^ 4 + (k * b) ^ 4 : by ring ... = (k ^ 2 * c) ^ 2 : by rw f42.2.2 ... = k ^ 4 * c ^ 2 : by ring }} end lemma ne_zero {a b c : ℤ} (h : fermat_42 a b c) : c ≠ 0 := begin apply ne_zero_pow (dec_trivial : 2 ≠ 0), apply ne_of_gt, rw [← h.2.2, (by ring : a ^ 4 + b ^ 4 = (a ^ 2) ^ 2 + (b ^ 2) ^ 2)], exact add_pos (sq_pos_of_ne_zero _ (pow_ne_zero 2 h.1)) (sq_pos_of_ne_zero _ (pow_ne_zero 2 h.2.1)) end /-- We say a solution to `a ^ 4 + b ^ 4 = c ^ 2` is minimal if there is no other solution with a smaller `c` (in absolute value). -/ def minimal (a b c : ℤ) : Prop := (fermat_42 a b c) ∧ ∀ (a1 b1 c1 : ℤ), (fermat_42 a1 b1 c1) → int.nat_abs c ≤ int.nat_abs c1 /-- if we have a solution to `a ^ 4 + b ^ 4 = c ^ 2` then there must be a minimal one. -/ lemma exists_minimal {a b c : ℤ} (h : fermat_42 a b c) : ∃ (a0 b0 c0), (minimal a0 b0 c0) := begin let S : set ℕ := { n | ∃ (s : ℤ × ℤ × ℤ), fermat_42 s.1 s.2.1 s.2.2 ∧ n = int.nat_abs s.2.2}, have S_nonempty : S.nonempty, { use int.nat_abs c, rw set.mem_set_of_eq, use ⟨a, ⟨b, c⟩⟩, tauto }, let m : ℕ := nat.find S_nonempty, have m_mem : m ∈ S := nat.find_spec S_nonempty, rcases m_mem with ⟨s0, hs0, hs1⟩, use [s0.1, s0.2.1, s0.2.2, hs0], intros a1 b1 c1 h1, rw ← hs1, apply nat.find_min', use ⟨a1, ⟨b1, c1⟩⟩, tauto end /-- a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` must have `a` and `b` coprime. -/ lemma coprime_of_minimal {a b c : ℤ} (h : minimal a b c) : is_coprime a b := begin apply int.gcd_eq_one_iff_coprime.mp, by_contradiction hab, obtain ⟨p, hp, hpa, hpb⟩ := nat.prime.not_coprime_iff_dvd.mp hab, obtain ⟨a1, rfl⟩ := (int.coe_nat_dvd_left.mpr hpa), obtain ⟨b1, rfl⟩ := (int.coe_nat_dvd_left.mpr hpb), have hpc : (p : ℤ) ^ 2 ∣ c, { apply (int.pow_dvd_pow_iff (dec_trivial : 0 < 2)).mp, rw ← h.1.2.2, apply dvd.intro (a1 ^ 4 + b1 ^ 4), ring }, obtain ⟨c1, rfl⟩ := hpc, have hf : fermat_42 a1 b1 c1, exact (fermat_42.mul (int.coe_nat_ne_zero.mpr (nat.prime.ne_zero hp))).mpr h.1, apply nat.le_lt_antisymm (h.2 _ _ _ hf), rw [int.nat_abs_mul, lt_mul_iff_one_lt_left, int.nat_abs_pow, int.nat_abs_of_nat], { exact nat.one_lt_pow _ _ (show 0 < 2, from dec_trivial) (nat.prime.one_lt hp) }, { exact (nat.pos_of_ne_zero (int.nat_abs_ne_zero_of_ne_zero (ne_zero hf))) }, end /-- We can swap `a` and `b` in a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2`. -/ lemma minimal_comm {a b c : ℤ} : (minimal a b c) → (minimal b a c) := λ ⟨h1, h2⟩, ⟨fermat_42.comm.mp h1, h2⟩ /-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has positive `c`. -/ lemma neg_of_minimal {a b c : ℤ} : (minimal a b c) → (minimal a b (-c)) := begin rintros ⟨⟨ha, hb, heq⟩, h2⟩, split, { apply and.intro ha (and.intro hb _), rw heq, exact (neg_sq c).symm }, rwa (int.nat_abs_neg c), end /-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has `a` odd. -/ lemma exists_odd_minimal {a b c : ℤ} (h : fermat_42 a b c) : ∃ (a0 b0 c0), (minimal a0 b0 c0) ∧ a0 % 2 = 1 := begin obtain ⟨a0, b0, c0, hf⟩ := exists_minimal h, cases int.mod_two_eq_zero_or_one a0 with hap hap, { cases int.mod_two_eq_zero_or_one b0 with hbp hbp, { exfalso, have h1 : 2 ∣ (int.gcd a0 b0 : ℤ), { exact int.dvd_gcd (int.dvd_of_mod_eq_zero hap) (int.dvd_of_mod_eq_zero hbp) }, rw int.gcd_eq_one_iff_coprime.mpr (coprime_of_minimal hf) at h1, revert h1, norm_num }, { exact ⟨b0, ⟨a0, ⟨c0, minimal_comm hf, hbp⟩⟩⟩ }}, exact ⟨a0, ⟨b0, ⟨c0 , hf, hap⟩⟩⟩, end /-- We can assume that a minimal solution to `a ^ 4 + b ^ 4 = c ^ 2` has `a` odd and `c` positive. -/ lemma exists_pos_odd_minimal {a b c : ℤ} (h : fermat_42 a b c) : ∃ (a0 b0 c0), (minimal a0 b0 c0) ∧ a0 % 2 = 1 ∧ 0 < c0 := begin obtain ⟨a0, b0, c0, hf, hc⟩ := exists_odd_minimal h, rcases lt_trichotomy 0 c0 with (h1 | rfl | h1), { use [a0, b0, c0], tauto }, { exfalso, exact ne_zero hf.1 rfl}, { use [a0, b0, -c0, neg_of_minimal hf, hc], exact neg_pos.mpr h1 }, end end fermat_42 lemma int.coprime_of_sq_sum {r s : ℤ} (h2 : is_coprime s r) : is_coprime (r ^ 2 + s ^ 2) r := begin rw [sq, sq], exact (is_coprime.mul_left h2 h2).mul_add_left_left r end lemma int.coprime_of_sq_sum' {r s : ℤ} (h : is_coprime r s) : is_coprime (r ^ 2 + s ^ 2) (r * s) := begin apply is_coprime.mul_right (int.coprime_of_sq_sum (is_coprime_comm.mp h)), rw add_comm, apply int.coprime_of_sq_sum h end namespace fermat_42 -- If we have a solution to a ^ 4 + b ^ 4 = c ^ 2, we can construct a smaller one. This -- implies there can't be a smallest solution. lemma not_minimal {a b c : ℤ} (h : minimal a b c) (ha2 : a % 2 = 1) (hc : 0 < c) : false := begin -- Use the fact that a ^ 2, b ^ 2, c form a pythagorean triple to obtain m and n such that -- a ^ 2 = m ^ 2 - n ^ 2, b ^ 2 = 2 * m * n and c = m ^ 2 + n ^ 2 -- first the formula: have ht : pythagorean_triple (a ^ 2) (b ^ 2) c, { calc ((a ^ 2) * (a ^ 2)) + ((b ^ 2) * (b ^ 2)) = a ^ 4 + b ^ 4 : by ring ... = c ^ 2 : by rw h.1.2.2 ... = c * c : by rw sq }, -- coprime requirement: have h2 : int.gcd (a ^ 2) (b ^ 2) = 1 := int.gcd_eq_one_iff_coprime.mpr (coprime_of_minimal h).pow, -- in order to reduce the possibilities we get from the classification of pythagorean triples -- it helps if we know the parity of a ^ 2 (and the sign of c): have ha22 : a ^ 2 % 2 = 1, { rw [sq, int.mul_mod, ha2], norm_num }, obtain ⟨m, n, ht1, ht2, ht3, ht4, ht5, ht6⟩ := pythagorean_triple.coprime_classification' ht h2 ha22 hc, -- Now a, n, m form a pythagorean triple and so we can obtain r and s such that -- a = r ^ 2 - s ^ 2, n = 2 * r * s and m = r ^ 2 + s ^ 2 -- formula: have htt : pythagorean_triple a n m, { delta pythagorean_triple, rw [← sq, ← sq, ← sq], exact (add_eq_of_eq_sub ht1) }, -- a and n are coprime, because a ^ 2 = m ^ 2 - n ^ 2 and m and n are coprime. have h3 : int.gcd a n = 1, { apply int.gcd_eq_one_iff_coprime.mpr, apply @is_coprime.of_mul_left_left _ _ _ a, rw [← sq, ht1, (by ring : m ^ 2 - n ^ 2 = m ^ 2 + (-n) * n)], exact (int.gcd_eq_one_iff_coprime.mp ht4).pow_left.add_mul_right_left (-n) }, -- m is positive because b is non-zero and b ^ 2 = 2 * m * n and we already have 0 ≤ m. have hb20 : b ^ 2 ≠ 0 := mt pow_eq_zero h.1.2.1, have h4 : 0 < m, { apply lt_of_le_of_ne ht6, rintro rfl, revert hb20, rw ht2, simp }, obtain ⟨r, s, htt1, htt2, htt3, htt4, htt5, htt6⟩ := pythagorean_triple.coprime_classification' htt h3 ha2 h4, -- Now use the fact that (b / 2) ^ 2 = m * r * s, and m, r and s are pairwise coprime to obtain -- i, j and k such that m = i ^ 2, r = j ^ 2 and s = k ^ 2. -- m and r * s are coprime because m = r ^ 2 + s ^ 2 and r and s are coprime. have hcp : int.gcd m (r * s) = 1, { rw htt3, exact int.gcd_eq_one_iff_coprime.mpr (int.coprime_of_sq_sum' (int.gcd_eq_one_iff_coprime.mp htt4)) }, -- b is even because b ^ 2 = 2 * m * n. have hb2 : 2 ∣ b, { apply @int.prime.dvd_pow' _ 2 _ (by norm_num : nat.prime 2), rw [ht2, mul_assoc], exact dvd_mul_right 2 (m * n) }, cases hb2 with b' hb2', have hs : b' ^ 2 = m * (r * s), { apply (mul_right_inj' (by norm_num : (4 : ℤ) ≠ 0)).mp, calc 4 * b' ^ 2 = (2 * b') * (2 * b') : by ring ... = 2 * m * (2 * r * s) : by rw [← hb2', ← sq, ht2, htt2] ... = 4 * (m * (r * s)) : by ring }, have hrsz : r * s ≠ 0, -- because b ^ 2 is not zero and (b / 2) ^ 2 = m * (r * s) { by_contradiction hrsz, revert hb20, rw [ht2, htt2, mul_assoc, @mul_assoc _ _ _ r s, hrsz], simp }, have h2b0 : b' ≠ 0, { apply ne_zero_pow (dec_trivial : 2 ≠ 0), rw hs, apply mul_ne_zero, { exact ne_of_gt h4}, { exact hrsz } }, obtain ⟨i, hi⟩ := int.sq_of_gcd_eq_one hcp hs.symm, -- use m is positive to exclude m = - i ^ 2 have hi' : ¬ m = - i ^ 2, { by_contradiction h1, have hit : - i ^ 2 ≤ 0, apply neg_nonpos.mpr (sq_nonneg i), rw ← h1 at hit, apply absurd h4 (not_lt.mpr hit) }, replace hi : m = i ^ 2, { apply or.resolve_right hi hi' }, rw mul_comm at hs, rw [int.gcd_comm] at hcp, -- obtain d such that r * s = d ^ 2 obtain ⟨d, hd⟩ := int.sq_of_gcd_eq_one hcp hs.symm, -- (b / 2) ^ 2 and m are positive so r * s is positive have hd' : ¬ r * s = - d ^ 2, { by_contradiction h1, rw h1 at hs, have h2 : b' ^ 2 ≤ 0, { rw [hs, (by ring : - d ^ 2 * m = - (d ^ 2 * m))], exact neg_nonpos.mpr ((zero_le_mul_right h4).mpr (sq_nonneg d)) }, have h2' : 0 ≤ b' ^ 2, { apply sq_nonneg b' }, exact absurd (lt_of_le_of_ne h2' (ne.symm (pow_ne_zero _ h2b0))) (not_lt.mpr h2) }, replace hd : r * s = d ^ 2, { apply or.resolve_right hd hd' }, -- r = +/- j ^ 2 obtain ⟨j, hj⟩ := int.sq_of_gcd_eq_one htt4 hd, have hj0 : j ≠ 0, { intro h0, rw [h0, zero_pow (dec_trivial : 0 < 2), neg_zero, or_self] at hj, apply left_ne_zero_of_mul hrsz hj }, rw mul_comm at hd, rw [int.gcd_comm] at htt4, -- s = +/- k ^ 2 obtain ⟨k, hk⟩ := int.sq_of_gcd_eq_one htt4 hd, have hk0 : k ≠ 0, { intro h0, rw [h0, zero_pow (dec_trivial : 0 < 2), neg_zero, or_self] at hk, apply right_ne_zero_of_mul hrsz hk }, have hj2 : r ^ 2 = j ^ 4, { cases hj with hjp hjp; { rw hjp, ring } }, have hk2 : s ^ 2 = k ^ 4, { cases hk with hkp hkp; { rw hkp, ring } }, -- from m = r ^ 2 + s ^ 2 we now get a new solution to a ^ 4 + b ^ 4 = c ^ 2: have hh : i ^ 2 = j ^ 4 + k ^ 4, { rw [← hi, htt3, hj2, hk2] }, have hn : n ≠ 0, { rw ht2 at hb20, apply right_ne_zero_of_mul hb20 }, -- and it has a smaller c: from c = m ^ 2 + n ^ 2 we see that m is smaller than c, and i ^ 2 = m. have hic : int.nat_abs i < int.nat_abs c, { apply int.coe_nat_lt.mp, rw ← (int.eq_nat_abs_of_zero_le (le_of_lt hc)), apply gt_of_gt_of_ge _ (int.abs_le_self_sq i), rw [← hi, ht3], apply gt_of_gt_of_ge _ (int.le_self_sq m), exact lt_add_of_pos_right (m ^ 2) (sq_pos_of_ne_zero n hn) }, have hic' : int.nat_abs c ≤ int.nat_abs i, { apply (h.2 j k i), exact ⟨hj0, hk0, hh.symm⟩ }, apply absurd (not_le_of_lt hic) (not_not.mpr hic') end end fermat_42 lemma not_fermat_42 {a b c : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) : a ^ 4 + b ^ 4 ≠ c ^ 2 := begin intro h, obtain ⟨a0, b0, c0, ⟨hf, h2, hp⟩⟩ := fermat_42.exists_pos_odd_minimal (and.intro ha (and.intro hb h)), apply fermat_42.not_minimal hf h2 hp end theorem not_fermat_4 {a b c : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) : a ^ 4 + b ^ 4 ≠ c ^ 4 := begin intro heq, apply @not_fermat_42 _ _ (c ^ 2) ha hb, rw heq, ring end
17cda8e706517b14bcbbb60f27996a9b19c24ba5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/ordered_pi_auto.lean
0ef9dd0b2e23ee8d31d154ff7621378b25cab95e
[]
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,233
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group.pi import Mathlib.algebra.ordered_group import Mathlib.tactic.pi_instances import Mathlib.PostPort universes u v namespace Mathlib /-! # Pi instances for ordered groups and monoids This file defines instances for ordered group, monoid, and related structures on Pi types. -/ namespace pi protected instance ordered_cancel_comm_monoid {I : Type u} {f : I → Type v} [(i : I) → ordered_cancel_comm_monoid (f i)] : ordered_cancel_comm_monoid ((i : I) → f i) := ordered_cancel_comm_monoid.mk Mul.mul sorry sorry 1 sorry sorry sorry sorry LessEq Less sorry sorry sorry sorry sorry protected instance ordered_add_comm_group {I : Type u} {f : I → Type v} [(i : I) → ordered_add_comm_group (f i)] : ordered_add_comm_group ((i : I) → f i) := ordered_add_comm_group.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry partial_order.le partial_order.lt sorry sorry sorry sorry end Mathlib
8f630587b59dd60f20084360493679aef3bfdfc4
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/eqncompiler/matchpattern.lean
8f815b8fed0fdd1cfd9eb8b735565600418a3cbf
[ "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
702
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.lean.attributes namespace Lean namespace EqnCompiler def mkMatchPatternAttr : IO TagAttribute := registerTagAttribute `matchPattern "mark that a definition can be used in a pattern (remark: the dependent pattern matching compiler will unfold the definition)" @[init mkMatchPatternAttr] constant matchPatternAttr : TagAttribute := default _ @[export lean.has_match_pattern_attribute_core] def hasMatchPatternAttribute (env : Environment) (n : Name) : Bool := matchPatternAttr.hasTag env n end EqnCompiler end Lean
a323b3eaee14bc9cbcce37b774e836516d872736
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/bounds.lean
b9835fab1511e352299bb58a11eeb456da9f8db0
[ "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
38,149
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import data.set.intervals.basic /-! # Upper / lower bounds In this file we define: * `upper_bounds`, `lower_bounds` : the set of upper bounds (resp., lower bounds) of a set; * `bdd_above s`, `bdd_below s` : the set `s` is bounded above (resp., below), i.e., the set of upper (resp., lower) bounds of `s` is nonempty; * `is_least s a`, `is_greatest s a` : `a` is a least (resp., greatest) element of `s`; for a partial order, it is unique if exists; * `is_lub s a`, `is_glb s a` : `a` is a least upper bound (resp., a greatest lower bound) of `s`; for a partial order, it is unique if exists. We also prove various lemmas about monotonicity, behaviour under `∪`, `∩`, `insert`, and provide formulas for `∅`, `univ`, and intervals. -/ open set order_dual (to_dual of_dual) universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section variables [preorder α] [preorder β] {s t : set α} {a b : α} /-! ### Definitions -/ /-- The set of upper bounds of a set. -/ def upper_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → a ≤ x } /-- The set of lower bounds of a set. -/ def lower_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → x ≤ a } /-- A set is bounded above if there exists an upper bound. -/ def bdd_above (s : set α) := (upper_bounds s).nonempty /-- A set is bounded below if there exists a lower bound. -/ def bdd_below (s : set α) := (lower_bounds s).nonempty /-- `a` is a least element of a set `s`; for a partial order, it is unique if exists. -/ def is_least (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ lower_bounds s /-- `a` is a greatest element of a set `s`; for a partial order, it is unique if exists -/ def is_greatest (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ upper_bounds s /-- `a` is a least upper bound of a set `s`; for a partial order, it is unique if exists. -/ def is_lub (s : set α) : α → Prop := is_least (upper_bounds s) /-- `a` is a greatest lower bound of a set `s`; for a partial order, it is unique if exists. -/ def is_glb (s : set α) : α → Prop := is_greatest (lower_bounds s) lemma mem_upper_bounds : a ∈ upper_bounds s ↔ ∀ x ∈ s, x ≤ a := iff.rfl lemma mem_lower_bounds : a ∈ lower_bounds s ↔ ∀ x ∈ s, a ≤ x := iff.rfl /-- A set `s` is not bounded above if and only if for each `x` there exists `y ∈ s` such that `x` is not greater than or equal to `y`. This version only assumes `preorder` structure and uses `¬(y ≤ x)`. A version for linear orders is called `not_bdd_above_iff`. -/ lemma not_bdd_above_iff' : ¬bdd_above s ↔ ∀ x, ∃ y ∈ s, ¬(y ≤ x) := by simp [bdd_above, upper_bounds, set.nonempty] /-- A set `s` is not bounded below if and only if for each `x` there exists `y ∈ s` such that `x` is not less than or equal to `y`. This version only assumes `preorder` structure and uses `¬(x ≤ y)`. A version for linear orders is called `not_bdd_below_iff`. -/ lemma not_bdd_below_iff' : ¬bdd_below s ↔ ∀ x, ∃ y ∈ s, ¬(x ≤ y) := @not_bdd_above_iff' (order_dual α) _ _ /-- A set `s` is not bounded above if and only if for each `x` there exists `y ∈ s` that is greater than `x`. A version for preorders is called `not_bdd_above_iff'`. -/ lemma not_bdd_above_iff {α : Type*} [linear_order α] {s : set α} : ¬bdd_above s ↔ ∀ x, ∃ y ∈ s, x < y := by simp only [not_bdd_above_iff', not_le] /-- A set `s` is not bounded below if and only if for each `x` there exists `y ∈ s` that is less than `x`. A version for preorders is called `not_bdd_below_iff'`. -/ lemma not_bdd_below_iff {α : Type*} [linear_order α] {s : set α} : ¬bdd_below s ↔ ∀ x, ∃ y ∈ s, y < x := @not_bdd_above_iff (order_dual α) _ _ lemma bdd_above.dual (h : bdd_above s) : bdd_below (of_dual ⁻¹' s) := h lemma bdd_below.dual (h : bdd_below s) : bdd_above (of_dual ⁻¹' s) := h lemma is_least.dual (h : is_least s a) : is_greatest (of_dual ⁻¹' s) (to_dual a) := h lemma is_greatest.dual (h : is_greatest s a) : is_least (of_dual ⁻¹' s) (to_dual a) := h lemma is_lub.dual (h : is_lub s a) : is_glb (of_dual ⁻¹' s) (to_dual a) := h lemma is_glb.dual (h : is_glb s a) : is_lub (of_dual ⁻¹' s) (to_dual a) := h /-! ### Monotonicity -/ lemma upper_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) : upper_bounds t ⊆ upper_bounds s := λ b hb x h, hb $ hst h lemma lower_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) : lower_bounds t ⊆ lower_bounds s := λ b hb x h, hb $ hst h lemma upper_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : a ∈ upper_bounds s → b ∈ upper_bounds s := λ ha x h, le_trans (ha h) hab lemma lower_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : b ∈ lower_bounds s → a ∈ lower_bounds s := λ hb x h, le_trans hab (hb h) lemma upper_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) : a ∈ upper_bounds t → b ∈ upper_bounds s := λ ha, upper_bounds_mono_set hst $ upper_bounds_mono_mem hab ha lemma lower_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) : b ∈ lower_bounds t → a ∈ lower_bounds s := λ hb, lower_bounds_mono_set hst $ lower_bounds_mono_mem hab hb /-- If `s ⊆ t` and `t` is bounded above, then so is `s`. -/ lemma bdd_above.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_above t → bdd_above s := nonempty.mono $ upper_bounds_mono_set h /-- If `s ⊆ t` and `t` is bounded below, then so is `s`. -/ lemma bdd_below.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_below t → bdd_below s := nonempty.mono $ lower_bounds_mono_set h /-- If `a` is a least upper bound for sets `s` and `p`, then it is a least upper bound for any set `t`, `s ⊆ t ⊆ p`. -/ lemma is_lub.of_subset_of_superset {s t p : set α} (hs : is_lub s a) (hp : is_lub p a) (hst : s ⊆ t) (htp : t ⊆ p) : is_lub t a := ⟨upper_bounds_mono_set htp hp.1, lower_bounds_mono_set (upper_bounds_mono_set hst) hs.2⟩ /-- If `a` is a greatest lower bound for sets `s` and `p`, then it is a greater lower bound for any set `t`, `s ⊆ t ⊆ p`. -/ lemma is_glb.of_subset_of_superset {s t p : set α} (hs : is_glb s a) (hp : is_glb p a) (hst : s ⊆ t) (htp : t ⊆ p) : is_glb t a := hs.dual.of_subset_of_superset hp hst htp lemma is_least.mono (ha : is_least s a) (hb : is_least t b) (hst : s ⊆ t) : b ≤ a := hb.2 (hst ha.1) lemma is_greatest.mono (ha : is_greatest s a) (hb : is_greatest t b) (hst : s ⊆ t) : a ≤ b := hb.2 (hst ha.1) lemma is_lub.mono (ha : is_lub s a) (hb : is_lub t b) (hst : s ⊆ t) : a ≤ b := hb.mono ha $ upper_bounds_mono_set hst lemma is_glb.mono (ha : is_glb s a) (hb : is_glb t b) (hst : s ⊆ t) : b ≤ a := hb.mono ha $ lower_bounds_mono_set hst lemma subset_lower_bounds_upper_bounds (s : set α) : s ⊆ lower_bounds (upper_bounds s) := λ x hx y hy, hy hx lemma subset_upper_bounds_lower_bounds (s : set α) : s ⊆ upper_bounds (lower_bounds s) := λ x hx y hy, hy hx lemma set.nonempty.bdd_above_lower_bounds (hs : s.nonempty) : bdd_above (lower_bounds s) := hs.mono (subset_upper_bounds_lower_bounds s) lemma set.nonempty.bdd_below_upper_bounds (hs : s.nonempty) : bdd_below (upper_bounds s) := hs.mono (subset_lower_bounds_upper_bounds s) /-! ### Conversions -/ lemma is_least.is_glb (h : is_least s a) : is_glb s a := ⟨h.2, λ b hb, hb h.1⟩ lemma is_greatest.is_lub (h : is_greatest s a) : is_lub s a := ⟨h.2, λ b hb, hb h.1⟩ lemma is_lub.upper_bounds_eq (h : is_lub s a) : upper_bounds s = Ici a := set.ext $ λ b, ⟨λ hb, h.2 hb, λ hb, upper_bounds_mono_mem hb h.1⟩ lemma is_glb.lower_bounds_eq (h : is_glb s a) : lower_bounds s = Iic a := h.dual.upper_bounds_eq lemma is_least.lower_bounds_eq (h : is_least s a) : lower_bounds s = Iic a := h.is_glb.lower_bounds_eq lemma is_greatest.upper_bounds_eq (h : is_greatest s a) : upper_bounds s = Ici a := h.is_lub.upper_bounds_eq lemma is_lub_le_iff (h : is_lub s a) : a ≤ b ↔ b ∈ upper_bounds s := by { rw h.upper_bounds_eq, refl } lemma le_is_glb_iff (h : is_glb s a) : b ≤ a ↔ b ∈ lower_bounds s := by { rw h.lower_bounds_eq, refl } lemma is_lub_iff_le_iff : is_lub s a ↔ ∀ b, a ≤ b ↔ b ∈ upper_bounds s := ⟨λ h b, is_lub_le_iff h, λ H, ⟨(H _).1 le_rfl, λ b hb, (H b).2 hb⟩⟩ lemma is_glb_iff_le_iff : is_glb s a ↔ ∀ b, b ≤ a ↔ b ∈ lower_bounds s := @is_lub_iff_le_iff (order_dual α) _ _ _ /-- If `s` has a least upper bound, then it is bounded above. -/ lemma is_lub.bdd_above (h : is_lub s a) : bdd_above s := ⟨a, h.1⟩ /-- If `s` has a greatest lower bound, then it is bounded below. -/ lemma is_glb.bdd_below (h : is_glb s a) : bdd_below s := ⟨a, h.1⟩ /-- If `s` has a greatest element, then it is bounded above. -/ lemma is_greatest.bdd_above (h : is_greatest s a) : bdd_above s := ⟨a, h.2⟩ /-- If `s` has a least element, then it is bounded below. -/ lemma is_least.bdd_below (h : is_least s a) : bdd_below s := ⟨a, h.2⟩ lemma is_least.nonempty (h : is_least s a) : s.nonempty := ⟨a, h.1⟩ lemma is_greatest.nonempty (h : is_greatest s a) : s.nonempty := ⟨a, h.1⟩ /-! ### Union and intersection -/ @[simp] lemma upper_bounds_union : upper_bounds (s ∪ t) = upper_bounds s ∩ upper_bounds t := subset.antisymm (λ b hb, ⟨λ x hx, hb (or.inl hx), λ x hx, hb (or.inr hx)⟩) (λ b hb x hx, hx.elim (λ hs, hb.1 hs) (λ ht, hb.2 ht)) @[simp] lemma lower_bounds_union : lower_bounds (s ∪ t) = lower_bounds s ∩ lower_bounds t := @upper_bounds_union (order_dual α) _ s t lemma union_upper_bounds_subset_upper_bounds_inter : upper_bounds s ∪ upper_bounds t ⊆ upper_bounds (s ∩ t) := union_subset (upper_bounds_mono_set $ inter_subset_left _ _) (upper_bounds_mono_set $ inter_subset_right _ _) lemma union_lower_bounds_subset_lower_bounds_inter : lower_bounds s ∪ lower_bounds t ⊆ lower_bounds (s ∩ t) := @union_upper_bounds_subset_upper_bounds_inter (order_dual α) _ s t lemma is_least_union_iff {a : α} {s t : set α} : is_least (s ∪ t) a ↔ (is_least s a ∧ a ∈ lower_bounds t ∨ a ∈ lower_bounds s ∧ is_least t a) := by simp [is_least, lower_bounds_union, or_and_distrib_right, and_comm (a ∈ t), and_assoc] lemma is_greatest_union_iff : is_greatest (s ∪ t) a ↔ (is_greatest s a ∧ a ∈ upper_bounds t ∨ a ∈ upper_bounds s ∧ is_greatest t a) := @is_least_union_iff (order_dual α) _ a s t /-- If `s` is bounded, then so is `s ∩ t` -/ lemma bdd_above.inter_of_left (h : bdd_above s) : bdd_above (s ∩ t) := h.mono $ inter_subset_left s t /-- If `t` is bounded, then so is `s ∩ t` -/ lemma bdd_above.inter_of_right (h : bdd_above t) : bdd_above (s ∩ t) := h.mono $ inter_subset_right s t /-- If `s` is bounded, then so is `s ∩ t` -/ lemma bdd_below.inter_of_left (h : bdd_below s) : bdd_below (s ∩ t) := h.mono $ inter_subset_left s t /-- If `t` is bounded, then so is `s ∩ t` -/ lemma bdd_below.inter_of_right (h : bdd_below t) : bdd_below (s ∩ t) := h.mono $ inter_subset_right s t /-- If `s` and `t` are bounded above sets in a `semilattice_sup`, then so is `s ∪ t`. -/ lemma bdd_above.union [semilattice_sup γ] {s t : set γ} : bdd_above s → bdd_above t → bdd_above (s ∪ t) := begin rintros ⟨bs, hs⟩ ⟨bt, ht⟩, use bs ⊔ bt, rw upper_bounds_union, exact ⟨upper_bounds_mono_mem le_sup_left hs, upper_bounds_mono_mem le_sup_right ht⟩ end /-- The union of two sets is bounded above if and only if each of the sets is. -/ lemma bdd_above_union [semilattice_sup γ] {s t : set γ} : bdd_above (s ∪ t) ↔ bdd_above s ∧ bdd_above t := ⟨λ h, ⟨h.mono $ subset_union_left s t, h.mono $ subset_union_right s t⟩, λ h, h.1.union h.2⟩ lemma bdd_below.union [semilattice_inf γ] {s t : set γ} : bdd_below s → bdd_below t → bdd_below (s ∪ t) := @bdd_above.union (order_dual γ) _ s t /--The union of two sets is bounded above if and only if each of the sets is.-/ lemma bdd_below_union [semilattice_inf γ] {s t : set γ} : bdd_below (s ∪ t) ↔ bdd_below s ∧ bdd_below t := @bdd_above_union (order_dual γ) _ s t /-- If `a` is the least upper bound of `s` and `b` is the least upper bound of `t`, then `a ⊔ b` is the least upper bound of `s ∪ t`. -/ lemma is_lub.union [semilattice_sup γ] {a b : γ} {s t : set γ} (hs : is_lub s a) (ht : is_lub t b) : is_lub (s ∪ t) (a ⊔ b) := ⟨λ c h, h.cases_on (λ h, le_sup_of_le_left $ hs.left h) (λ h, le_sup_of_le_right $ ht.left h), assume c hc, sup_le (hs.right $ assume d hd, hc $ or.inl hd) (ht.right $ assume d hd, hc $ or.inr hd)⟩ /-- If `a` is the greatest lower bound of `s` and `b` is the greatest lower bound of `t`, then `a ⊓ b` is the greatest lower bound of `s ∪ t`. -/ lemma is_glb.union [semilattice_inf γ] {a₁ a₂ : γ} {s t : set γ} (hs : is_glb s a₁) (ht : is_glb t a₂) : is_glb (s ∪ t) (a₁ ⊓ a₂) := hs.dual.union ht /-- If `a` is the least element of `s` and `b` is the least element of `t`, then `min a b` is the least element of `s ∪ t`. -/ lemma is_least.union [linear_order γ] {a b : γ} {s t : set γ} (ha : is_least s a) (hb : is_least t b) : is_least (s ∪ t) (min a b) := ⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1], (ha.is_glb.union hb.is_glb).1⟩ /-- If `a` is the greatest element of `s` and `b` is the greatest element of `t`, then `max a b` is the greatest element of `s ∪ t`. -/ lemma is_greatest.union [linear_order γ] {a b : γ} {s t : set γ} (ha : is_greatest s a) (hb : is_greatest t b) : is_greatest (s ∪ t) (max a b) := ⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1], (ha.is_lub.union hb.is_lub).1⟩ lemma is_lub.inter_Ici_of_mem [linear_order γ] {s : set γ} {a b : γ} (ha : is_lub s a) (hb : b ∈ s) : is_lub (s ∩ Ici b) a := ⟨λ x hx, ha.1 hx.1, λ c hc, have hbc : b ≤ c, from hc ⟨hb, le_rfl⟩, ha.2 $ λ x hx, (le_total x b).elim (λ hxb, hxb.trans hbc) $ λ hbx, hc ⟨hx, hbx⟩⟩ lemma is_glb.inter_Iic_of_mem [linear_order γ] {s : set γ} {a b : γ} (ha : is_glb s a) (hb : b ∈ s) : is_glb (s ∩ Iic b) a := ha.dual.inter_Ici_of_mem hb /-! ### Specific sets #### Unbounded intervals -/ lemma is_least_Ici : is_least (Ici a) a := ⟨left_mem_Ici, λ x, id⟩ lemma is_greatest_Iic : is_greatest (Iic a) a := ⟨right_mem_Iic, λ x, id⟩ lemma is_lub_Iic : is_lub (Iic a) a := is_greatest_Iic.is_lub lemma is_glb_Ici : is_glb (Ici a) a := is_least_Ici.is_glb lemma upper_bounds_Iic : upper_bounds (Iic a) = Ici a := is_lub_Iic.upper_bounds_eq lemma lower_bounds_Ici : lower_bounds (Ici a) = Iic a := is_glb_Ici.lower_bounds_eq lemma bdd_above_Iic : bdd_above (Iic a) := is_lub_Iic.bdd_above lemma bdd_below_Ici : bdd_below (Ici a) := is_glb_Ici.bdd_below lemma bdd_above_Iio : bdd_above (Iio a) := ⟨a, λ x hx, le_of_lt hx⟩ lemma bdd_below_Ioi : bdd_below (Ioi a) := ⟨a, λ x hx, le_of_lt hx⟩ section variables [linear_order γ] [densely_ordered γ] lemma is_lub_Iio {a : γ} : is_lub (Iio a) a := ⟨λ x hx, le_of_lt hx, λ y hy, le_of_forall_ge_of_dense hy⟩ lemma is_glb_Ioi {a : γ} : is_glb (Ioi a) a := @is_lub_Iio (order_dual γ) _ _ a lemma upper_bounds_Iio {a : γ} : upper_bounds (Iio a) = Ici a := is_lub_Iio.upper_bounds_eq lemma lower_bounds_Ioi {a : γ} : lower_bounds (Ioi a) = Iic a := is_glb_Ioi.lower_bounds_eq end /-! #### Singleton -/ lemma is_greatest_singleton : is_greatest {a} a := ⟨mem_singleton a, λ x hx, le_of_eq $ eq_of_mem_singleton hx⟩ lemma is_least_singleton : is_least {a} a := @is_greatest_singleton (order_dual α) _ a lemma is_lub_singleton : is_lub {a} a := is_greatest_singleton.is_lub lemma is_glb_singleton : is_glb {a} a := is_least_singleton.is_glb lemma bdd_above_singleton : bdd_above ({a} : set α) := is_lub_singleton.bdd_above lemma bdd_below_singleton : bdd_below ({a} : set α) := is_glb_singleton.bdd_below @[simp] lemma upper_bounds_singleton : upper_bounds {a} = Ici a := is_lub_singleton.upper_bounds_eq @[simp] lemma lower_bounds_singleton : lower_bounds {a} = Iic a := is_glb_singleton.lower_bounds_eq /-! #### Bounded intervals -/ lemma bdd_above_Icc : bdd_above (Icc a b) := ⟨b, λ _, and.right⟩ lemma bdd_below_Icc : bdd_below (Icc a b) := ⟨a, λ _, and.left⟩ lemma bdd_above_Ico : bdd_above (Ico a b) := bdd_above_Icc.mono Ico_subset_Icc_self lemma bdd_below_Ico : bdd_below (Ico a b) := bdd_below_Icc.mono Ico_subset_Icc_self lemma bdd_above_Ioc : bdd_above (Ioc a b) := bdd_above_Icc.mono Ioc_subset_Icc_self lemma bdd_below_Ioc : bdd_below (Ioc a b) := bdd_below_Icc.mono Ioc_subset_Icc_self lemma bdd_above_Ioo : bdd_above (Ioo a b) := bdd_above_Icc.mono Ioo_subset_Icc_self lemma bdd_below_Ioo : bdd_below (Ioo a b) := bdd_below_Icc.mono Ioo_subset_Icc_self lemma is_greatest_Icc (h : a ≤ b) : is_greatest (Icc a b) b := ⟨right_mem_Icc.2 h, λ x, and.right⟩ lemma is_lub_Icc (h : a ≤ b) : is_lub (Icc a b) b := (is_greatest_Icc h).is_lub lemma upper_bounds_Icc (h : a ≤ b) : upper_bounds (Icc a b) = Ici b := (is_lub_Icc h).upper_bounds_eq lemma is_least_Icc (h : a ≤ b) : is_least (Icc a b) a := ⟨left_mem_Icc.2 h, λ x, and.left⟩ lemma is_glb_Icc (h : a ≤ b) : is_glb (Icc a b) a := (is_least_Icc h).is_glb lemma lower_bounds_Icc (h : a ≤ b) : lower_bounds (Icc a b) = Iic a := (is_glb_Icc h).lower_bounds_eq lemma is_greatest_Ioc (h : a < b) : is_greatest (Ioc a b) b := ⟨right_mem_Ioc.2 h, λ x, and.right⟩ lemma is_lub_Ioc (h : a < b) : is_lub (Ioc a b) b := (is_greatest_Ioc h).is_lub lemma upper_bounds_Ioc (h : a < b) : upper_bounds (Ioc a b) = Ici b := (is_lub_Ioc h).upper_bounds_eq lemma is_least_Ico (h : a < b) : is_least (Ico a b) a := ⟨left_mem_Ico.2 h, λ x, and.left⟩ lemma is_glb_Ico (h : a < b) : is_glb (Ico a b) a := (is_least_Ico h).is_glb lemma lower_bounds_Ico (h : a < b) : lower_bounds (Ico a b) = Iic a := (is_glb_Ico h).lower_bounds_eq section variables [semilattice_sup γ] [densely_ordered γ] lemma is_glb_Ioo {a b : γ} (h : a < b) : is_glb (Ioo a b) a := ⟨λ x hx, hx.1.le, λ x hx, begin cases eq_or_lt_of_le (le_sup_right : a ≤ x ⊔ a) with h₁ h₂, { exact h₁.symm ▸ le_sup_left }, obtain ⟨y, lty, ylt⟩ := exists_between h₂, apply (not_lt_of_le (sup_le (hx ⟨lty, ylt.trans_le (sup_le _ h.le)⟩) lty.le) ylt).elim, obtain ⟨u, au, ub⟩ := exists_between h, apply (hx ⟨au, ub⟩).trans ub.le, end⟩ lemma lower_bounds_Ioo {a b : γ} (hab : a < b) : lower_bounds (Ioo a b) = Iic a := (is_glb_Ioo hab).lower_bounds_eq lemma is_glb_Ioc {a b : γ} (hab : a < b) : is_glb (Ioc a b) a := (is_glb_Ioo hab).of_subset_of_superset (is_glb_Icc hab.le) Ioo_subset_Ioc_self Ioc_subset_Icc_self lemma lower_bound_Ioc {a b : γ} (hab : a < b) : lower_bounds (Ioc a b) = Iic a := (is_glb_Ioc hab).lower_bounds_eq end section variables [semilattice_inf γ] [densely_ordered γ] lemma is_lub_Ioo {a b : γ} (hab : a < b) : is_lub (Ioo a b) b := by simpa only [dual_Ioo] using is_glb_Ioo hab.dual lemma upper_bounds_Ioo {a b : γ} (hab : a < b) : upper_bounds (Ioo a b) = Ici b := (is_lub_Ioo hab).upper_bounds_eq lemma is_lub_Ico {a b : γ} (hab : a < b) : is_lub (Ico a b) b := by simpa only [dual_Ioc] using is_glb_Ioc hab.dual lemma upper_bounds_Ico {a b : γ} (hab : a < b) : upper_bounds (Ico a b) = Ici b := (is_lub_Ico hab).upper_bounds_eq end lemma bdd_below_iff_subset_Ici : bdd_below s ↔ ∃ a, s ⊆ Ici a := iff.rfl lemma bdd_above_iff_subset_Iic : bdd_above s ↔ ∃ a, s ⊆ Iic a := iff.rfl lemma bdd_below_bdd_above_iff_subset_Icc : bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ Icc a b := by simp only [Ici_inter_Iic.symm, subset_inter_iff, bdd_below_iff_subset_Ici, bdd_above_iff_subset_Iic, exists_and_distrib_left, exists_and_distrib_right] /-! #### Univ -/ lemma is_greatest_univ [preorder γ] [order_top γ] : is_greatest (univ : set γ) ⊤ := ⟨mem_univ _, λ x hx, le_top⟩ @[simp] lemma order_top.upper_bounds_univ [partial_order γ] [order_top γ] : upper_bounds (univ : set γ) = {⊤} := by rw [is_greatest_univ.upper_bounds_eq, Ici_top] lemma is_lub_univ [preorder γ] [order_top γ] : is_lub (univ : set γ) ⊤ := is_greatest_univ.is_lub @[simp] lemma order_bot.lower_bounds_univ [partial_order γ] [order_bot γ] : lower_bounds (univ : set γ) = {⊥} := @order_top.upper_bounds_univ (order_dual γ) _ _ lemma is_least_univ [preorder γ] [order_bot γ] : is_least (univ : set γ) ⊥ := @is_greatest_univ (order_dual γ) _ _ lemma is_glb_univ [preorder γ] [order_bot γ] : is_glb (univ : set γ) ⊥ := is_least_univ.is_glb @[simp] lemma no_top_order.upper_bounds_univ [no_top_order α] : upper_bounds (univ : set α) = ∅ := eq_empty_of_subset_empty $ λ b hb, let ⟨x, hx⟩ := no_top b in not_le_of_lt hx (hb trivial) @[simp] lemma no_bot_order.lower_bounds_univ [no_bot_order α] : lower_bounds (univ : set α) = ∅ := @no_top_order.upper_bounds_univ (order_dual α) _ _ @[simp] lemma not_bdd_above_univ [no_top_order α] : ¬bdd_above (univ : set α) := by simp [bdd_above] @[simp] lemma not_bdd_below_univ [no_bot_order α] : ¬bdd_below (univ : set α) := @not_bdd_above_univ (order_dual α) _ _ /-! #### Empty set -/ @[simp] lemma upper_bounds_empty : upper_bounds (∅ : set α) = univ := by simp only [upper_bounds, eq_univ_iff_forall, mem_set_of_eq, ball_empty_iff, forall_true_iff] @[simp] lemma lower_bounds_empty : lower_bounds (∅ : set α) = univ := @upper_bounds_empty (order_dual α) _ @[simp] lemma bdd_above_empty [nonempty α] : bdd_above (∅ : set α) := by simp only [bdd_above, upper_bounds_empty, univ_nonempty] @[simp] lemma bdd_below_empty [nonempty α] : bdd_below (∅ : set α) := by simp only [bdd_below, lower_bounds_empty, univ_nonempty] lemma is_glb_empty [preorder γ] [order_top γ] : is_glb ∅ (⊤:γ) := by simp only [is_glb, lower_bounds_empty, is_greatest_univ] lemma is_lub_empty [preorder γ] [order_bot γ] : is_lub ∅ (⊥:γ) := @is_glb_empty (order_dual γ) _ _ lemma is_lub.nonempty [no_bot_order α] (hs : is_lub s a) : s.nonempty := let ⟨a', ha'⟩ := no_bot a in ne_empty_iff_nonempty.1 $ assume h, have a ≤ a', from hs.right $ by simp only [h, upper_bounds_empty], not_le_of_lt ha' this lemma is_glb.nonempty [no_top_order α] (hs : is_glb s a) : s.nonempty := hs.dual.nonempty lemma nonempty_of_not_bdd_above [ha : nonempty α] (h : ¬bdd_above s) : s.nonempty := nonempty.elim ha $ λ x, (not_bdd_above_iff'.1 h x).imp $ λ a ha, ha.fst lemma nonempty_of_not_bdd_below [ha : nonempty α] (h : ¬bdd_below s) : s.nonempty := @nonempty_of_not_bdd_above (order_dual α) _ _ _ h /-! #### insert -/ /-- Adding a point to a set preserves its boundedness above. -/ @[simp] lemma bdd_above_insert [semilattice_sup γ] (a : γ) {s : set γ} : bdd_above (insert a s) ↔ bdd_above s := by simp only [insert_eq, bdd_above_union, bdd_above_singleton, true_and] lemma bdd_above.insert [semilattice_sup γ] (a : γ) {s : set γ} (hs : bdd_above s) : bdd_above (insert a s) := (bdd_above_insert a).2 hs /--Adding a point to a set preserves its boundedness below.-/ @[simp] lemma bdd_below_insert [semilattice_inf γ] (a : γ) {s : set γ} : bdd_below (insert a s) ↔ bdd_below s := by simp only [insert_eq, bdd_below_union, bdd_below_singleton, true_and] lemma bdd_below.insert [semilattice_inf γ] (a : γ) {s : set γ} (hs : bdd_below s) : bdd_below (insert a s) := (bdd_below_insert a).2 hs lemma is_lub.insert [semilattice_sup γ] (a) {b} {s : set γ} (hs : is_lub s b) : is_lub (insert a s) (a ⊔ b) := by { rw insert_eq, exact is_lub_singleton.union hs } lemma is_glb.insert [semilattice_inf γ] (a) {b} {s : set γ} (hs : is_glb s b) : is_glb (insert a s) (a ⊓ b) := by { rw insert_eq, exact is_glb_singleton.union hs } lemma is_greatest.insert [linear_order γ] (a) {b} {s : set γ} (hs : is_greatest s b) : is_greatest (insert a s) (max a b) := by { rw insert_eq, exact is_greatest_singleton.union hs } lemma is_least.insert [linear_order γ] (a) {b} {s : set γ} (hs : is_least s b) : is_least (insert a s) (min a b) := by { rw insert_eq, exact is_least_singleton.union hs } @[simp] lemma upper_bounds_insert (a : α) (s : set α) : upper_bounds (insert a s) = Ici a ∩ upper_bounds s := by rw [insert_eq, upper_bounds_union, upper_bounds_singleton] @[simp] lemma lower_bounds_insert (a : α) (s : set α) : lower_bounds (insert a s) = Iic a ∩ lower_bounds s := by rw [insert_eq, lower_bounds_union, lower_bounds_singleton] /-- When there is a global maximum, every set is bounded above. -/ @[simp] protected lemma order_top.bdd_above [preorder γ] [order_top γ] (s : set γ) : bdd_above s := ⟨⊤, assume a ha, order_top.le_top a⟩ /-- When there is a global minimum, every set is bounded below. -/ @[simp] protected lemma order_bot.bdd_below [preorder γ] [order_bot γ] (s : set γ) : bdd_below s := ⟨⊥, assume a ha, order_bot.bot_le a⟩ /-! #### Pair -/ lemma is_lub_pair [semilattice_sup γ] {a b : γ} : is_lub {a, b} (a ⊔ b) := is_lub_singleton.insert _ lemma is_glb_pair [semilattice_inf γ] {a b : γ} : is_glb {a, b} (a ⊓ b) := is_glb_singleton.insert _ lemma is_least_pair [linear_order γ] {a b : γ} : is_least {a, b} (min a b) := is_least_singleton.insert _ lemma is_greatest_pair [linear_order γ] {a b : γ} : is_greatest {a, b} (max a b) := is_greatest_singleton.insert _ /-! #### Lower/upper bounds -/ @[simp] lemma is_lub_lower_bounds : is_lub (lower_bounds s) a ↔ is_glb s a := ⟨λ H, ⟨λ x hx, H.2 $ subset_upper_bounds_lower_bounds s hx, H.1⟩, is_greatest.is_lub⟩ @[simp] lemma is_glb_upper_bounds : is_glb (upper_bounds s) a ↔ is_lub s a := @is_lub_lower_bounds (order_dual α) _ _ _ end /-! ### (In)equalities with the least upper bound and the greatest lower bound -/ section preorder variables [preorder α] {s : set α} {a b : α} lemma lower_bounds_le_upper_bounds (ha : a ∈ lower_bounds s) (hb : b ∈ upper_bounds s) : s.nonempty → a ≤ b | ⟨c, hc⟩ := le_trans (ha hc) (hb hc) lemma is_glb_le_is_lub (ha : is_glb s a) (hb : is_lub s b) (hs : s.nonempty) : a ≤ b := lower_bounds_le_upper_bounds ha.1 hb.1 hs lemma is_lub_lt_iff (ha : is_lub s a) : a < b ↔ ∃ c ∈ upper_bounds s, c < b := ⟨λ hb, ⟨a, ha.1, hb⟩, λ ⟨c, hcs, hcb⟩, lt_of_le_of_lt (ha.2 hcs) hcb⟩ lemma lt_is_glb_iff (ha : is_glb s a) : b < a ↔ ∃ c ∈ lower_bounds s, b < c := is_lub_lt_iff ha.dual lemma le_of_is_lub_le_is_glb {x y} (ha : is_glb s a) (hb : is_lub s b) (hab : b ≤ a) (hx : x ∈ s) (hy : y ∈ s) : x ≤ y := calc x ≤ b : hb.1 hx ... ≤ a : hab ... ≤ y : ha.1 hy end preorder section partial_order variables [partial_order α] {s : set α} {a b : α} lemma is_least.unique (Ha : is_least s a) (Hb : is_least s b) : a = b := le_antisymm (Ha.right Hb.left) (Hb.right Ha.left) lemma is_least.is_least_iff_eq (Ha : is_least s a) : is_least s b ↔ a = b := iff.intro Ha.unique (assume h, h ▸ Ha) lemma is_greatest.unique (Ha : is_greatest s a) (Hb : is_greatest s b) : a = b := le_antisymm (Hb.right Ha.left) (Ha.right Hb.left) lemma is_greatest.is_greatest_iff_eq (Ha : is_greatest s a) : is_greatest s b ↔ a = b := iff.intro Ha.unique (assume h, h ▸ Ha) lemma is_lub.unique (Ha : is_lub s a) (Hb : is_lub s b) : a = b := Ha.unique Hb lemma is_glb.unique (Ha : is_glb s a) (Hb : is_glb s b) : a = b := Ha.unique Hb lemma set.subsingleton_of_is_lub_le_is_glb (Ha : is_glb s a) (Hb : is_lub s b) (hab : b ≤ a) : s.subsingleton := λ x hx y hy, le_antisymm (le_of_is_lub_le_is_glb Ha Hb hab hx hy) (le_of_is_lub_le_is_glb Ha Hb hab hy hx) lemma is_glb_lt_is_lub_of_ne (Ha : is_glb s a) (Hb : is_lub s b) {x y} (Hx : x ∈ s) (Hy : y ∈ s) (Hxy : x ≠ y) : a < b := lt_iff_le_not_le.2 ⟨lower_bounds_le_upper_bounds Ha.1 Hb.1 ⟨x, Hx⟩, λ hab, Hxy $ set.subsingleton_of_is_lub_le_is_glb Ha Hb hab Hx Hy⟩ end partial_order section linear_order variables [linear_order α] {s : set α} {a b : α} lemma lt_is_lub_iff (h : is_lub s a) : b < a ↔ ∃ c ∈ s, b < c := by simp only [← not_le, is_lub_le_iff h, mem_upper_bounds, not_forall] lemma is_glb_lt_iff (h : is_glb s a) : a < b ↔ ∃ c ∈ s, c < b := lt_is_lub_iff h.dual lemma is_lub.exists_between (h : is_lub s a) (hb : b < a) : ∃ c ∈ s, b < c ∧ c ≤ a := let ⟨c, hcs, hbc⟩ := (lt_is_lub_iff h).1 hb in ⟨c, hcs, hbc, h.1 hcs⟩ lemma is_lub.exists_between' (h : is_lub s a) (h' : a ∉ s) (hb : b < a) : ∃ c ∈ s, b < c ∧ c < a := let ⟨c, hcs, hbc, hca⟩ := h.exists_between hb in ⟨c, hcs, hbc, hca.lt_of_ne $ λ hac, h' $ hac ▸ hcs⟩ lemma is_glb.exists_between (h : is_glb s a) (hb : a < b) : ∃ c ∈ s, a ≤ c ∧ c < b := let ⟨c, hcs, hbc⟩ := (is_glb_lt_iff h).1 hb in ⟨c, hcs, h.1 hcs, hbc⟩ lemma is_glb.exists_between' (h : is_glb s a) (h' : a ∉ s) (hb : a < b) : ∃ c ∈ s, a < c ∧ c < b := let ⟨c, hcs, hac, hcb⟩ := h.exists_between hb in ⟨c, hcs, hac.lt_of_ne $ λ hac, h' $ hac.symm ▸ hcs, hcb⟩ end linear_order /-! ### Least upper bound and the greatest lower bound in linear ordered additive commutative groups -/ section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] {s : set α} {a ε : α} lemma is_glb.exists_between_self_add (h : is_glb s a) (hε : 0 < ε) : ∃ b ∈ s, a ≤ b ∧ b < a + ε := h.exists_between $ lt_add_of_pos_right _ hε lemma is_glb.exists_between_self_add' (h : is_glb s a) (h₂ : a ∉ s) (hε : 0 < ε) : ∃ b ∈ s, a < b ∧ b < a + ε := h.exists_between' h₂ $ lt_add_of_pos_right _ hε lemma is_lub.exists_between_sub_self (h : is_lub s a) (hε : 0 < ε) : ∃ b ∈ s, a - ε < b ∧ b ≤ a := h.exists_between $ sub_lt_self _ hε lemma is_lub.exists_between_sub_self' (h : is_lub s a) (h₂ : a ∉ s) (hε : 0 < ε) : ∃ b ∈ s, a - ε < b ∧ b < a := h.exists_between' h₂ $ sub_lt_self _ hε end linear_ordered_add_comm_group /-! ### Images of upper/lower bounds under monotone functions -/ namespace monotone variables [preorder α] [preorder β] {f : α → β} (Hf : monotone f) {a : α} {s : set α} lemma mem_upper_bounds_image (Ha : a ∈ upper_bounds s) : f a ∈ upper_bounds (f '' s) := ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›)) lemma mem_lower_bounds_image (Ha : a ∈ lower_bounds s) : f a ∈ lower_bounds (f '' s) := ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›)) lemma image_upper_bounds_subset_upper_bounds_image (hf : monotone f) : f '' upper_bounds s ⊆ upper_bounds (f '' s) := begin rintro _ ⟨a, ha, rfl⟩, exact hf.mem_upper_bounds_image ha, end lemma image_lower_bounds_subset_lower_bounds_image (hf : monotone f) : f '' lower_bounds s ⊆ lower_bounds (f '' s) := hf.dual.image_upper_bounds_subset_upper_bounds_image /-- The image under a monotone function of a set which is bounded above is bounded above. -/ lemma map_bdd_above (hf : monotone f) : bdd_above s → bdd_above (f '' s) | ⟨C, hC⟩ := ⟨f C, hf.mem_upper_bounds_image hC⟩ /-- The image under a monotone function of a set which is bounded below is bounded below. -/ lemma map_bdd_below (hf : monotone f) : bdd_below s → bdd_below (f '' s) | ⟨C, hC⟩ := ⟨f C, hf.mem_lower_bounds_image hC⟩ /-- A monotone map sends a least element of a set to a least element of its image. -/ lemma map_is_least (Ha : is_least s a) : is_least (f '' s) (f a) := ⟨mem_image_of_mem _ Ha.1, Hf.mem_lower_bounds_image Ha.2⟩ /-- A monotone map sends a greatest element of a set to a greatest element of its image. -/ lemma map_is_greatest (Ha : is_greatest s a) : is_greatest (f '' s) (f a) := ⟨mem_image_of_mem _ Ha.1, Hf.mem_upper_bounds_image Ha.2⟩ lemma is_lub_image_le (Ha : is_lub s a) {b : β} (Hb : is_lub (f '' s) b) : b ≤ f a := Hb.2 (Hf.mem_upper_bounds_image Ha.1) lemma le_is_glb_image (Ha : is_glb s a) {b : β} (Hb : is_glb (f '' s) b) : f a ≤ b := Hb.2 (Hf.mem_lower_bounds_image Ha.1) end monotone namespace antitone variables [preorder α] [preorder β] {f : α → β} (hf : antitone f) {a : α} {s : set α} lemma mem_upper_bounds_image (ha : a ∈ lower_bounds s) : f a ∈ upper_bounds (f '' s) := hf.dual_right.mem_lower_bounds_image ha lemma mem_lower_bounds_image (ha : a ∈ upper_bounds s) : f a ∈ lower_bounds (f '' s) := hf.dual_right.mem_upper_bounds_image ha lemma image_lower_bounds_subset_upper_bounds_image (hf : antitone f) : f '' lower_bounds s ⊆ upper_bounds (f '' s) := hf.dual_right.image_lower_bounds_subset_lower_bounds_image lemma image_upper_bounds_subset_lower_bounds_image (hf : antitone f) : f '' upper_bounds s ⊆ lower_bounds (f '' s) := hf.dual_right.image_upper_bounds_subset_upper_bounds_image /-- The image under an antitone function of a set which is bounded above is bounded below. -/ lemma map_bdd_above (hf : antitone f) : bdd_above s → bdd_below (f '' s) := hf.dual_right.map_bdd_above /-- The image under an antitone function of a set which is bounded below is bounded above. -/ lemma map_bdd_below (hf : antitone f) : bdd_below s → bdd_above (f '' s) := hf.dual_right.map_bdd_below /-- An antitone map sends a greatest element of a set to a least element of its image. -/ lemma map_is_greatest (ha : is_greatest s a) : is_least (f '' s) (f a) := hf.dual_right.map_is_greatest ha /-- An antitone map sends a least element of a set to a greatest element of its image. -/ lemma map_is_least (ha : is_least s a) : is_greatest (f '' s) (f a) := hf.dual_right.map_is_least ha lemma is_lub_image_le (ha : is_glb s a) {b : β} (hb : is_lub (f '' s) b) : b ≤ f a := hf.dual_left.is_lub_image_le ha hb lemma le_is_glb_image (ha : is_lub s a) {b : β} (hb : is_glb (f '' s) b) : f a ≤ b := hf.dual_left.le_is_glb_image ha hb end antitone lemma is_glb.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y) {s : set α} {x : α} (hx : is_glb (f '' s) (f x)) : is_glb s x := ⟨λ y hy, hf.1 $ hx.1 $ mem_image_of_mem _ hy, λ y hy, hf.1 $ hx.2 $ monotone.mem_lower_bounds_image (λ x y, hf.2) hy⟩ lemma is_lub.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y) {s : set α} {x : α} (hx : is_lub (f '' s) (f x)) : is_lub s x := @is_glb.of_image (order_dual α) (order_dual β) _ _ f (λ x y, hf) _ _ hx lemma is_lub_pi {π : α → Type*} [Π a, preorder (π a)] {s : set (Π a, π a)} {f : Π a, π a} : is_lub s f ↔ ∀ a, is_lub (function.eval a '' s) (f a) := begin classical, refine ⟨λ H a, ⟨(function.monotone_eval a).mem_upper_bounds_image H.1, λ b hb, _⟩, λ H, ⟨_, _⟩⟩, { suffices : function.update f a b ∈ upper_bounds s, from function.update_same a b f ▸ H.2 this a, refine λ g hg, le_update_iff.2 ⟨hb $ mem_image_of_mem _ hg, λ i hi, H.1 hg i⟩ }, { exact λ g hg a, (H a).1 (mem_image_of_mem _ hg) }, { exact λ g hg a, (H a).2 ((function.monotone_eval a).mem_upper_bounds_image hg) } end lemma is_glb_pi {π : α → Type*} [Π a, preorder (π a)] {s : set (Π a, π a)} {f : Π a, π a} : is_glb s f ↔ ∀ a, is_glb (function.eval a '' s) (f a) := @is_lub_pi α (λ a, order_dual (π a)) _ s f lemma is_lub_prod [preorder α] [preorder β] {s : set (α × β)} (p : α × β) : is_lub s p ↔ is_lub (prod.fst '' s) p.1 ∧ is_lub (prod.snd '' s) p.2 := begin refine ⟨λ H, ⟨⟨monotone_fst.mem_upper_bounds_image H.1, λ a ha, _⟩, ⟨monotone_snd.mem_upper_bounds_image H.1, λ a ha, _⟩⟩, λ H, ⟨_, _⟩⟩, { suffices : (a, p.2) ∈ upper_bounds s, from (H.2 this).1, exact λ q hq, ⟨ha $ mem_image_of_mem _ hq, (H.1 hq).2⟩ }, { suffices : (p.1, a) ∈ upper_bounds s, from (H.2 this).2, exact λ q hq, ⟨(H.1 hq).1, ha $ mem_image_of_mem _ hq⟩ }, { exact λ q hq, ⟨H.1.1 $ mem_image_of_mem _ hq, H.2.1 $ mem_image_of_mem _ hq⟩ }, { exact λ q hq, ⟨H.1.2 $ monotone_fst.mem_upper_bounds_image hq, H.2.2 $ monotone_snd.mem_upper_bounds_image hq⟩ } end lemma is_glb_prod [preorder α] [preorder β] {s : set (α × β)} (p : α × β) : is_glb s p ↔ is_glb (prod.fst '' s) p.1 ∧ is_glb (prod.snd '' s) p.2 := @is_lub_prod (order_dual α) (order_dual β) _ _ _ _ namespace order_iso variables [preorder α] [preorder β] (f : α ≃o β) lemma upper_bounds_image {s : set α} : upper_bounds (f '' s) = f '' upper_bounds s := subset.antisymm (λ x hx, ⟨f.symm x, λ y hy, f.le_symm_apply.2 (hx $ mem_image_of_mem _ hy), f.apply_symm_apply x⟩) f.monotone.image_upper_bounds_subset_upper_bounds_image lemma lower_bounds_image {s : set α} : lower_bounds (f '' s) = f '' lower_bounds s := @upper_bounds_image (order_dual α) (order_dual β) _ _ f.dual _ @[simp] lemma is_lub_image {s : set α} {x : β} : is_lub (f '' s) x ↔ is_lub s (f.symm x) := ⟨λ h, is_lub.of_image (λ _ _, f.le_iff_le) ((f.apply_symm_apply x).symm ▸ h), λ h, is_lub.of_image (λ _ _, f.symm.le_iff_le) $ (f.symm_image_image s).symm ▸ h⟩ lemma is_lub_image' {s : set α} {x : α} : is_lub (f '' s) (f x) ↔ is_lub s x := by rw [is_lub_image, f.symm_apply_apply] @[simp] lemma is_glb_image {s : set α} {x : β} : is_glb (f '' s) x ↔ is_glb s (f.symm x) := f.dual.is_lub_image lemma is_glb_image' {s : set α} {x : α} : is_glb (f '' s) (f x) ↔ is_glb s x := f.dual.is_lub_image' @[simp] lemma is_lub_preimage {s : set β} {x : α} : is_lub (f ⁻¹' s) x ↔ is_lub s (f x) := by rw [← f.symm_symm, ← image_eq_preimage, is_lub_image] lemma is_lub_preimage' {s : set β} {x : β} : is_lub (f ⁻¹' s) (f.symm x) ↔ is_lub s x := by rw [is_lub_preimage, f.apply_symm_apply] @[simp] lemma is_glb_preimage {s : set β} {x : α} : is_glb (f ⁻¹' s) x ↔ is_glb s (f x) := f.dual.is_lub_preimage lemma is_glb_preimage' {s : set β} {x : β} : is_glb (f ⁻¹' s) (f.symm x) ↔ is_glb s x := f.dual.is_lub_preimage' end order_iso
5334a2524d9aa1e6680cf6b20f2e3a72ac416836
76ce87faa6bc3c2aa9af5962009e01e04f2a074a
/03_Conjunction/00_and.lean
4b7f62322cc036e5d0119a52c21c1cffb120c7e5
[]
no_license
Mnormansell/Discrete-Notes
db423dd9206bbe7080aecb84b4c2d275b758af97
61f13b98be590269fc4822be7b47924a6ddc1261
refs/heads/master
1,585,412,435,424
1,540,919,483,000
1,540,919,483,000
148,684,638
0
0
null
null
null
null
UTF-8
Lean
false
false
19,182
lean
/- Intuitively, if a proposition P is true and a second proposition Q is true, then the more complex proposition, "P and Q" is also true. This proposition is written symbolically as P ∧ Q. In mathematical logic, we say that the proposition, P ∧ Q, is the conjunction of the individual propositions, P and Q. There's an inference rule for that. It says that if P and Q are propositions (types of type Prop), and if you have a proof of P and you have a proof of Q then you can derive a proof of P ∧ Q. Moreover, the form of that proof is basically the pair of proofs, (p, q). {P Q : Prop }, p : P, q : Q --------------------------- (∧-intro) (p, q): P ∧ Q To give us some propositions and proofs to use in examples, let's define P and Q to be simple equality propositions, and let's then define p and q to be proofs of P and Q. -/ def P : Prop := 0 = 0 def Q := 1 = 1 -- type inference works here theorem pfP : P := eq.refl 0 theorem pfQ : Q := eq.refl 1 /- We note that rfl doesn't work here. It's the right idea, but the proposition, P, to be proved isn't written as an equality, so rfl doesn't know what to do with it. We just just eq.refl directly instead. -/ /- * SYNTAX OF CONJUNCTIONS * -/ /--/ Now the syntax of proposition logic allows us to form a new proposition, P ∧ Q. -/ def P_and_Q : Prop := P ∧ Q #check P_and_Q -- it's a proposition #check P ∧ Q -- same thing /- * SEMANTICS OF CONJUNCTIONS * -/ /- * AND INTRODUCTION RULE * -/ /- Now intuitively, P ∧ Q should be true if and only if P is true and Q is true, which in the logic of Lean is to say if we have a proof of P and a proof of Q. The and.intro inference rule formalizes this idea. It says if you give me propositions, P and Q, and proofs, p and q of P and Q respectively, then I will give you back a proof of P ∧ Q. { P, Q : Prop } (p: P) (q: Q) ----------------------------- and.intro pf_PQ : P ∧ Q The and.intro takes two explicit arguments: a proof of P and a proof of Q. It infers P and Q from pf_P and pf_Q. It then derives a proof of P ∧ Q. Here is an example of its use in Lean -/ theorem pf_PQ: P ∧ Q := and.intro pfP pfQ -- study this carefully! /- Ok, let's decode that. We're proposing a theorem. The proposition we aim to prove is P ∧ Q, which is really just 0 = 0 ∧ 1 = 1. To produce a proof of this proposition, we need a proof of 0 = 0. That is p. We also need a proof of 1 = 1. That is q. If we then apply the rule to p and q we can expect to get back a proof of P ∧ Q,=. The Lean checker confirms that we do. You might be getting the sense that these inference rules are sort of like functions: They take propositions, proofs, and other values as arguments and they compute and return proofs as results. This is exactly what is happening here. What you're seeing is how programs like Lean turns propositions and proofs into objects that can be handled and transformed by programs! It's like your ordinary discrete math class on steroids. -/ /- * PROOF TREES * -/ /- A key point is that what we just did is to build a larger proof, pf, from two smaller ones, p and q. Those proofs in turn we built using the eq.refl inference rule applied to the values 0 and 1, respectively. We can now visualize the whole construction as what we call a proof tree, or derivation (with more than one level of rules being applied). eq.refl 0 eq.refl 1 --------- --------- 0 = 0 1 = 1 ---------------------- 0 = 0 ∧ 1 = 1 We can read such a proof tree either from the top to the bottom or from the bottom to the top. We can also translate such a tree into English. Most mathematicians would just provide the English language proof, leaving it to human and social processes to check that it's good. We now have the benefit of automated proof checking. Reading it from the top we might say the following. By the reflexive property of equality, we derive that 0 = 0 and that 1 = 1. These lemmas both now been proved separately, a proof of their conjunction follows immediately. QED Now as one seeking to prove P ∧ Q (the conclusion), one would work from bottom to top. The reasoning would go like this: To prove the conclusion, we need proofs of ach conjunct. We obtain a proof of the first, 0 = 0, by noting that this follows from the reflexive property of equality. So does a proof of 1 = 1. Now having proved the individual conjuncts, the truth of the conjunction follows immediately. QED. You can see that the everyday working mathematician elides many details, such as the precise principle used to derive the truth of the conjunction. The lack of detail in informal proofs makes them at best nearly impossible for machines to check. Reading and checking them really relies on human mathematical understanding. Nevertheless, whether you are asked to write an informal proof or a formal one, the process of deriving a proof often involves this kind of "backwards chaining." When asked to prove a proposition, X, we generally try to find other propositions, such as S and T, such that if we had proofs of S and T, we could then apply a valid reasoning step (inference rule) to derive a proof of X. One thus reduces the problem of proving X to the sub-problems of proving S and T. One then backward-chains this way until one finally reaches ... axioms, i.e., rules with no proofs required above the line. Axioms are the "base cases" in the recursive decomposition of the overall problem: there is no need to recurse any further once you've reach the bottom! To be really precise about it, there is one more layer in the proof tree: it's where the Lean type checker gives us proofs that 0 and 1 are of type nat; and that's what eq.refl needs as its input. The type checker in turn gives us proofs of these type judgments by means of yet further, but not hidden, logic reasoning. 0: nat 1 : nat --------- --------- eq.refl 0 eq.refl 1 --------- --------- 0 = 0 1 = 1 ---------------------- 0 = 0 ∧ 1 = 1 QED! Now you're looking at a depiction of a mathematically precise proof. The English just presents such an object in a more natural language, but at the cost of a massive loss of precision and checkability. The downside of the formal proof object is that it's not in the form of a story; and as you can imagine, in cases where proofs get massive, understanding why they are the way they are can be near impossible. But that's why we have machines. In practice, you should really know how to produce both formal and informal proofs. Better yet, you might someday try some tools that produce formal proofs for you. (Such a tool is Dafny. We will perhaps see it later.) -/ /- EXERCISE: What "smaller" propositions might you want to prove to prove that 5 = 1 + 4 ∧ "Strike" = "S" ++ "trike". Prove those smaller propositions giving them whatever names you choose. Then write the theorem in Lean that proves the final result using and.intro. -/ /- * Proving conjunctions with tactics * -/ /- One can always prove a proposition by giving an exact proof term, but these terms are like programs, and they can get large and complicated. Sometimes, indeed often, it's easier to develop them step by step. A key idea is that we start with the goal at the bottom of a proof tree, the goal (proposition) to be proved, and by working backwards through the tree, we can identify the smaller propositions for which we need proofs so as to be able to apply a final rule to construct the desired proof. Consider again the goal of proving the conjunctive proposition P ∧ Q. If we have a proof of P and a proof of Q then we can apply the and.intro rule to build the proof we need. Well, that breaks the overall goal into two subgoals, and we can then solve them recursively (i.e., as sub-problems to solve nested within the solution to the overall problem). In particular, we can *split* the goal of proving a conjunction into sub-goals, one for each conjunct. We then solve the sub-problems and finally combine the partial solutions into a final result using and.intro. Whether you are using a tool like Lean or are just writing informal mathematical proofs, the use of decomposition of a large problem into pieces, recursively solving of the parts, and ultimately the combination of the partial results into a final result, is essential and ubiquitous. Indeed, it's a general way to solve complex problems in almost any domain. The key is being able to break a problem into parts that can be solved independently. -/ /- In Lean, we can build proofs this way using tactic scripts. First we apply the and.intro rule. Used in a script in this way, it works backwards! Rather than combining proofs for P and Q into a proof of P ∧ Q, it decomposes the top-level goal of proving P ∧ Q into two sub-goals: to prove P and to prove Q. The problem of proving P ∧ Q is thus decomposed into the problem of proving premises needed to make the and.intro rule succeed. We then use additional tactics too solve each of the sub-problems, one by one. Open the Messages view, then put your cursor at the beginning of each line in the following script and study how the tactic state changes as you go. -/ theorem pf_PQ': P ∧ Q := begin apply and.intro, exact pfP, exact pfQ, end /- An English-language rendition of this proof-constructing procedure would go like this: "We split the problem of proving P ∧ Q into the sub-problems, of proving P and proving Q. This is a valid step because the and.intro rule tells us that having such proofs will suffice to prove the main goal. A proof of P follows from the reflexive property of equality, and a proof of Q also then follows similarly. QED." Constructing proofs in this way is very much like writing programs by first writing the Main routine, having it call subroutines, and then writing the subroutines. Here instead we start with the main goal, P ∧ Q. We apply an inference rule to break down the problem of proving the goal into one or more problems of proving sub-goals, and once we're done with that, a proof of the top-level goals follows by the application of the mai inference rule. We call this approach to development of programs, and of proofs, top-down decomposition. Sometimes a software will say that she's using "top-down structured programming" to design her code. Learning to think this way is a major step forward for a computer scientist. -/ /- There's another way, of course, to build a proof, or a program, and that iss to write the sub-routines first and then to integrate them into a larger program by writing code that uses them. We call such an approach "bottom-up." You can similarly develop proofs using a bottom-up approach. You first obtain the proofs of sub-goals that you'll need and then you "integrate" (combine) them by applying some inference rule. We now introduce a style of Lean proof scripts that supports such a bottom-up approach to constructing proofs. Here's an example where we prove the same proposition but in a bottom-up manner. -/ theorem pf_PQ'': P ∧ Q := begin have X := pfP, have Y := pfQ, apply and.intro X Y end /- Study very carefully how the tactic state changes as you advance through the script. The first tactic we use is "have." It gives a name to a proof for a sub-goal that you will then use later on. Here, the name X is given to a proof of 0 = 0. Once this tactic has run, you will see the proof state update to a new state in which you have a proof X of 0 = 0 (before the ⊢), with P ∧ Q as desired proposition to be proved. Next we give a name to, and then subsequently also have a proof of Q. And finally, we apply the and.intro rule to these two proofs, which are now available in the "context" of the proof state (before the ⊢) to build a proof of the overall goal. Lean checks and accepts that proof thereby solving the overall problem. QED, as they say. This style of proof scripts starts to look like proofs that a mathematician might write. This one could be read like this: "We have a proof of P, (eq.refl 0). Let's call it X. We also have a proof of Q, (eq.refl 1). Let's call it Y. Given proofs X and Y we now apply the and.intro rule to X and Y to derive the proof we need. QED." -/ /- Whether you write exact proof objects, or use top-down or bottom-up scripting methods, the key point to bear in mind is that everything ultimately relies on the inference rules. They are what is most fundamental. Moving from the conclusion to the premises of and.intro is how we decompose the top-level goal, P ∧ Q, into sub-goals. Moving from the premises X and Y down through the and.intro rule to a proof of P ∧ Q is how we merge bottom-up partial results into an overall solution. And of course if we're going to write a proof object exactly, the expression we need is one in which eq.refl is used. It's thus very important that you familiarize yourself deeply with the introduction (and also the elimination) inference rules for predicate logic. Now we move on to the elimination rules for and (∧). -/ /- * AND ELIMINATION * -/ /- Given a proof of P ∧ Q, it's clear that P should be true individually, and Q too. The and elimination rules provide us with these reasoning principles, allowing us to derive P from P ∧ Q, and Q from P ∧ Q. We call them and.elim_left and and.elim_right. { P Q: Prop } (paq : P ∧ Q) --------------------------- and.elim_left pfP : P { P Q: Prop } (paq : P ∧ Q) --------------------------- and.elim_right pfQ : Q -/ -- recall that t is a proof of P ∧ Q #check and.elim_left pf_PQ #check and.elim_right pf_PQ /- EXERCISE: Fill in the "sorry" words in the following incomplete theorems with explicit proof objects obtained by applying the and elimination rules to our proof, pf_PQ, of P ∧ Q. Note: Sorry says, "please just accept the theorem as proved: an axiom. It's dangerous to use sorry except as a temporary placeholder for a proof that you plan fill in later." -/ theorem pfP' : P := and.elim_left pf_PQ theorem pfQ' : Q := sorry /- Here are two script-based proofs. -/ theorem pfP'' : P := begin exact and.elim_left pf_PQ end theorem pfP''' : P := begin have pfP := and.elim_left pf_PQ, exact pfP end /- * COMMUTATIVITY OF CONJUNCTION *-/ /- Now we've really got some power tools. We can prove equalities. From constituent proofs we can prove conjunctions, and from proofs of conjunctions we can obtain proofs of the individual conjuncts. With these tools in hand we can now start to state and prove essential mathematical properties of logical operators, here of conjunction (and, ∧) . -/ /- *** Commutativity of ∧ ***-/ /- Let's first state a claim informally. If P ∧ Q is true then Q ∧ P must be true as well. For example, from a proof of (0 = 0 ∧ 1 = 1) we should be able to derive a proof of (1 = 1 ∧ 0 = 0). We already have the propositions, P := 0 = 0, Q := 1 = 1, and a proof, pf_PQ, of P ∧ Q (i.e., of 0 = 0 ∧ 1 =1 ). Now let's give a name to the proposition that (1 = 1 ∧ 0 = 0). -/ def Q_and_P : Prop := Q ∧ P -- reverse! /- How can we generate a proof of Q_and_P? Let's think in a top-down manner. Start with the goal, Q ∧ P, and ask how it can be proved. The only way we can prove it at present is by applying and.intro to a proof of Q and a proof of P (in this new and reversed order!). So the form of a proof simply has to be (and.intro _ _), where the first _ is a proof of Q and the second _ is a proof of P. If all we start with is a proof, pf_PQ, of P ∧ Q, how can get the proofs, pfP of P and pfQ of Q, that we need? Easy! Apply the and.elimination rules to get first a proof of Q then a proof of P; then use those proofs as arguments to and.intro, the first being the proof of Q and the second, the proof of P. -/ theorem pfQaP : Q ∧ P := and.intro (and.elim_right pf_PQ) (and.elim_left pf_PQ) /- EXERCISE: Write a top-down proof script to prove the same proposition, calling the result pfQaP'. EXERCISE: Write a bottom-up proof script to prove the same proposition, calling the result pfQaP''. -/ theorem pfQaP' : Q ∧ P := begin apply and.intro, exact (and.elim_right pf_PQ), exact (and.elim_left pf_PQ), end theorem pfQaP'' : Q ∧ P := begin have pfQ := (and.elim_right pf_PQ), have pfP := (and.elim_left pf_PQ), apply and.intro pfQ pfP end /- The general inference rule, which we will call and.commutes, says that if P and Q are *any* propositions, and we have a proof, paq, of P ∧ Q, then we can obtain a proof, qap, of Q ∧ P. We could write the rule like this (the arguments P and Q are implicit and are inferred from paq). { P Q: Prop }, paq : P ∧ Q -------------------------- and_commutes qap: Q ∧ P We can now even see how we might implement this rule ourselves -- literally as a program! We'll call it "and_commutes". -/ def and_commutes { P Q: Prop } (paq: P ∧ Q) : Q ∧ P := <<<<<<< Updated upstream and.intro (and.elim_right paq) (and.elim_left paq) ======= and.intro (and.elim_right paq) (and.elim_left paq) >>>>>>> Stashed changes #check and_commutes /- In this program we use the same curly brace notation as introduced informally above to indicate parameters that are to be inferred from context. That is, we can apply this function to a proof of P ∧ Q, without explicitly giving P and Q as parameters, to obtain a proof of Q ∧ P. Does it work? -/ theorem qap : Q ∧ P := (and_commutes pf_PQ) /- Holy cow, it works! We applied our new *proof converter* to convert a proof of 0 = 0 ∧ 1 = 1 into a proof of 1 = 1 ∧ 0 = 0. But we've written our converter program in a way that will work for any P and Q are. We have in effect proven that conjunction is commutative: that for any propositions, P and Q, if P ∧ Q is true, then we can derive that Q ∧ P is, too. Now things are getting interesting. -/ /- EXERCISE: From a proof of 1 = 1 ∧ tt = tt, use and_commutes to prove tt = tt ∧ 1 = 1. -/ /- test solution theorem proofz : 1 = 1 ∧ tt = tt := begin have pfa := eq.refl 1, have pft := tt, apply and.intro (pfa) (pft) exact eq.rfl -/ /- Having now proved that "and commutes," as mathematicians would say, we can now use this principle in all future reasoning. Indeed in the work of everyday mathematics, if one had proved P ∧ Q and needed a proof of Q ∧ P, it'd be a simple matter of saying "Q ∧ P follows from the commutativity of conjunction." Many mathematicians would just say, "Q ∧ P follows immediately," leaving it to the reader to know that the commutativity property of ∧ is the real justification for the conclusion. -/ def and_assoc_r { P Q R : Prop } (pfP_QR: (P ∧ Q) ∧ R) : (P ∧ (Q ∧ R)) := begin have pfPQ := and.elim_left pfP_QR, have pfR := and.elim_right pfP_QR, have pfP := and.elim_left pfPQ, have pfQ := and.elim_right pfPQ, have pfQR := and.intro (pfQ) (pfR), have pfP_QR :=and.intro pfP pfQR, exact pfP_QR end
405dab56f2a8c7700c2c46825d50cf0957eb4a64
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/letrecInProofs.lean
853b9f821a0ed7f0ad0093aa2d97c50b96085c2c
[ "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
2,702
lean
import Lean inductive Tree | leaf : Tree | node : Tree → Tree → Tree abbrev notSubtree (x : Tree) (t : Tree) : Prop := Tree.ibelow (motive := fun z => x ≠ z) t infix:50 "≮" => notSubtree theorem Tree.acyclic (x t : Tree) : x = t → x ≮ t := by let rec right (x s : Tree) (b : Tree) (h : x ≮ b) : node s x ≠ b ∧ node s x ≮ b := by match b, h with | leaf, h => apply And.intro _ trivial intro h; injection h | node l r, h => have ihl : x ≮ l → node s x ≠ l ∧ node s x ≮ l := right x s l have ihr : x ≮ r → node s x ≠ r ∧ node s x ≮ r := right x s r have hl : x ≠ l ∧ x ≮ l := h.1 have hr : x ≠ r ∧ x ≮ r := h.2.1 have ihl : node s x ≠ l ∧ node s x ≮ l := ihl hl.2 have ihr : node s x ≠ r ∧ node s x ≮ r := ihr hr.2 apply And.intro focus intro h injection h with _ h exact absurd h hr.1 done focus apply And.intro apply ihl apply And.intro _ trivial apply ihr let rec left (x t : Tree) (b : Tree) (h : x ≮ b) : node x t ≠ b ∧ node x t ≮ b := by match b, h with | leaf, h => apply And.intro _ trivial intro h; injection h | node l r, h => have ihl : x ≮ l → node x t ≠ l ∧ node x t ≮ l := left x t l have ihr : x ≮ r → node x t ≠ r ∧ node x t ≮ r := left x t r have hl : x ≠ l ∧ x ≮ l := h.1 have hr : x ≠ r ∧ x ≮ r := h.2.1 have ihl : node x t ≠ l ∧ node x t ≮ l := ihl hl.2 have ihr : node x t ≠ r ∧ node x t ≮ r := ihr hr.2 apply And.intro focus intro h injection h with h _ exact absurd h hl.1 done focus apply And.intro apply ihl apply And.intro _ trivial apply ihr let rec aux : (x : Tree) → x ≮ x | leaf => trivial | node l r => by have ih₁ : l ≮ l := aux l have ih₂ : r ≮ r := aux r show (node l r ≠ l ∧ node l r ≮ l) ∧ (node l r ≠ r ∧ node l r ≮ r) ∧ True apply And.intro focus apply left assumption apply And.intro _ trivial focus apply right assumption intro h subst h apply aux open Tree theorem ex1 (x : Tree) : x ≠ node leaf (node x leaf) := by intro h exact absurd rfl $ Tree.acyclic _ _ h |>.2.1.2.1.1 theorem ex2 (x : Tree) : x ≠ node x leaf := by intro h exact absurd rfl $ Tree.acyclic _ _ h |>.1.1 theorem ex3 (x y : Tree) : x ≠ node y x := by intro h exact absurd rfl $ Tree.acyclic _ _ h |>.2.1.1
94ef9b080465735cce674ae907add63c9a3bb30e
3bdd27ffdff3ffa22d4bb010eba695afcc96bc4a
/src/combinatorics/simplicial_complex/polytope.lean
7667aa442e21d6f4c0820cc041c14fd56af87955
[]
no_license
mmasdeu/brouwerfixedpoint
684d712c982c6a8b258b4e2c6b2eab923f2f1289
548270f79ecf12d7e20a256806ccb9fcf57b87e2
refs/heads/main
1,690,539,793,996
1,631,801,831,000
1,631,801,831,000
368,139,809
4
3
null
1,624,453,250,000
1,621,246,034,000
Lean
UTF-8
Lean
false
false
6,037
lean
/- Copyright (c) 2021 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 combinatorics.simplicial_complex.convex_independence import combinatorics.simplicial_complex.glued open set affine namespace poly variables {m n : ℕ} {E : Type*} [normed_group E] [normed_space ℝ E] {S : simplicial_complex E} {x : E} {X Y : finset E} {C : set E} {A : set (finset E)} /-- A polytope of dimension `n` in `R^m` is a subset for which there exists a simplicial complex which is pure of dimension `n` and has the same underlying space. -/ @[ext] structure polytope (E : Type*) [normed_group E] [normed_space ℝ E] := (space : set E) (realisable : ∃ {S : simplicial_complex E}, S.pure ∧ space = S.space) variables {p : polytope E} /-- A constructor for polytopes from an underlying simplicial complex -/ def simplicial_complex.to_polytope (hS : S.pure) : polytope E := { space := S.space, realisable := ⟨S, hS, rfl⟩} noncomputable def polytope.to_simplicial_complex (p : polytope E) : simplicial_complex E := classical.some p.realisable lemma pure_polytope_realisation : p.to_simplicial_complex.pure := (classical.some_spec p.realisable).1 lemma polytope_space_eq_realisation_space : p.space = p.to_simplicial_complex.space := (classical.some_spec p.realisable).2 def polytope.vertices (p : polytope E) : set E := ⋂ (S : simplicial_complex E) (H : p.space = S.space), S.vertices lemma vertices_subset_space : p.vertices ⊆ p.space := begin rintro x hx, have hx' : x ∈ p.to_simplicial_complex.vertices, { --apply bInter_subset_of_mem (polytope_space_eq_realisation_space : -- p.to_simplicial_complex ∈ set_of (λ q : simplicial_complex E, p.space = q.space)), sorry }, rw polytope_space_eq_realisation_space, exact mem_space_iff.2 ⟨{x}, hx', by simp⟩, end def polytope.edges (p : polytope E) : set (finset E) := ⋂ (S : simplicial_complex E) (H : p.space = S.space), {X | X ∈ S.faces ∧ X.card = 2} --def polytope.faces {n : ℕ} (P : polytope E) : set (finset E) := -- P.realisation.boundary.faces noncomputable def polytope.triangulation (p : polytope E) : simplicial_complex E := begin classical, exact if p.space.nonempty ∧ convex p.space then begin have hpnonempty : p.space.nonempty := sorry, let x := classical.some hpnonempty, have hx := classical.some_spec hpnonempty, sorry end else p.to_simplicial_complex, end /- Every convex polytope can be realised by a simplicial complex with the same vertices-/ lemma polytope.triangulable_of_convex (hp : convex p.space) : p.triangulation.vertices = p.vertices := begin cases p.space.eq_empty_or_nonempty with hpempty hpnonempty, { /-rw empty_space_of_empty_simplicial_complex, use hpempty, rintro X (hX : {X} ∈ {∅}), simp at hX, exfalso, exact hX,-/ sorry }, obtain ⟨x, hx⟩ := hpnonempty, --consider the boundary of some realisation of P and remove it x, --have := P.realisation.boundary.erasure {x}, --then add it back by taking the pyramid of this monster with x sorry end /-lemma convex_polytope_iff_intersection_of_half_spaces {space : set E} {n : ℕ} : ∃ {S : simplicial_complex E}, S.pure ∧ space = S.space ↔ ∃ half spaces and stuff-/ @[ext] structure polytopial_complex (E : Type*) [normed_group E] [normed_space ℝ E] := (faces : set (finset E)) (indep : ∀ {X}, X ∈ faces → convex_independent (λ p, p : (X : set E) → E)) (down_closed : ∀ {X Y}, X ∈ faces → Y ⊆ X → (Y : set E) = (X : set E) ∩ affine_span ℝ (Y : set E) → Y ∈ faces) (disjoint : ∀ {X Y}, X ∈ faces → Y ∈ faces → convex_hull ↑X ∩ convex_hull ↑Y ⊆ convex_hull (X ∩ Y : set E)) variables {P : polytopial_complex E} def polytopial_complex.polytopes (P : polytopial_complex E) : set (polytope E) := sorry def polytopial_complex.space (P : polytopial_complex E) : set E := ⋃ (p ∈ P.polytopes), (p : polytope E).space lemma mem_space_iff : x ∈ P.space ↔ ∃ (p : polytope E), p ∈ P.polytopes ∧ x ∈ p.space := begin unfold polytopial_complex.space, simp, end def simplicial_complex.to_polytopial_complex (S : simplicial_complex E) : polytopial_complex E := { faces := S.faces, indep := λ X hX, (S.indep hX).convex_independent, down_closed := λ X Y hX hYX hY, S.down_closed hX hYX, disjoint := S.disjoint } noncomputable def polytope.to_polytopial_complex (p : polytope E) : polytopial_complex E := simplicial_complex.to_polytopial_complex p.to_simplicial_complex --@Bhavik I can't use dot notation here because of namespace problems. Do you have a fix? def polytopial_complex.coplanarless (P : polytopial_complex E) : Prop := ∀ X Y ∈ P.faces, adjacent X Y → (X : set E) ⊆ affine_span ℝ (Y : set E) → X.card = finite_dimensional.finrank ℝ E + 1 def polytopial_complex.to_simplicial_complex (P : polytopial_complex E) : simplicial_complex E := { faces := ⋃ (p ∈ P.polytopes), (p : polytope E).to_simplicial_complex.faces, indep := begin rintro X hX, rw mem_bUnion_iff at hX, obtain ⟨p, hp, hX⟩ := hX, exact p.to_simplicial_complex.indep hX, end, down_closed := begin rintro X Y hX hYX, rw mem_bUnion_iff at ⊢ hX, obtain ⟨p, hp, hX⟩ := hX, exact ⟨p, hp, p.to_simplicial_complex.down_closed hX hYX⟩, end, disjoint := begin rintro X Y hX hY, rw mem_bUnion_iff at hX hY, obtain ⟨p, hp, hX⟩ := hX, obtain ⟨q, hq, hY⟩ := hY, sorry --this is wrong because faces of adjacent polytopes aren't required to glue nicely -- causes problem as soon as their shared faces aren't simplices end } lemma polytopial_space_iff_simplicial_space [finite_dimensional ℝ E] : (∃ (S : simplicial_complex E), S.space = C) ↔ ∃ (P : polytopial_complex E), P.space = C := begin split, { rintro ⟨S, hS⟩, sorry }, sorry end end poly
1dd54f00a3ebe52cd7dbebfb3451eb2f4309b7f4
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/list/sigma.lean
3e99184fe09f32ff0e69dfbd0fae0bc0c6ee481d
[ "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
24,689
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Sean Leather Functions on lists of sigma types. -/ import data.list.perm import data.list.range import data.sigma universes u v namespace list variables {α : Type u} {β : α → Type v} /- keys -/ /-- List of keys from a list of key-value pairs -/ def keys : list (sigma β) → list α := map sigma.fst @[simp] theorem keys_nil : @keys α β [] = [] := rfl @[simp] theorem keys_cons {s} {l : list (sigma β)} : (s :: l).keys = s.1 :: l.keys := rfl theorem mem_keys_of_mem {s : sigma β} {l : list (sigma β)} : s ∈ l → s.1 ∈ l.keys := mem_map_of_mem sigma.fst theorem exists_of_mem_keys {a} {l : list (sigma β)} (h : a ∈ l.keys) : ∃ (b : β a), sigma.mk a b ∈ l := let ⟨⟨a', b'⟩, m, e⟩ := exists_of_mem_map h in eq.rec_on e (exists.intro b' m) theorem mem_keys {a} {l : list (sigma β)} : a ∈ l.keys ↔ ∃ (b : β a), sigma.mk a b ∈ l := ⟨exists_of_mem_keys, λ ⟨b, h⟩, mem_keys_of_mem h⟩ theorem not_mem_keys {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ b : β a, sigma.mk a b ∉ l := (not_iff_not_of_iff mem_keys).trans not_exists theorem not_eq_key {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ s : sigma β, s ∈ l → a ≠ s.1 := iff.intro (λ h₁ s h₂ e, absurd (mem_keys_of_mem h₂) (by rwa e at h₁)) (λ f h₁, let ⟨b, h₂⟩ := exists_of_mem_keys h₁ in f _ h₂ rfl) /- nodupkeys -/ def nodupkeys (l : list (sigma β)) : Prop := l.keys.nodup theorem nodupkeys_iff_pairwise {l} : nodupkeys l ↔ pairwise (λ s s' : sigma β, s.1 ≠ s'.1) l := pairwise_map _ theorem nodupkeys.pairwise_ne {l} (h : nodupkeys l) : pairwise (λ s s' : sigma β, s.1 ≠ s'.1) l := nodupkeys_iff_pairwise.1 h @[simp] theorem nodupkeys_nil : @nodupkeys α β [] := pairwise.nil @[simp] theorem nodupkeys_cons {s : sigma β} {l : list (sigma β)} : nodupkeys (s::l) ↔ s.1 ∉ l.keys ∧ nodupkeys l := by simp [keys, nodupkeys] theorem nodupkeys.eq_of_fst_eq {l : list (sigma β)} (nd : nodupkeys l) {s s' : sigma β} (h : s ∈ l) (h' : s' ∈ l) : s.1 = s'.1 → s = s' := @forall_of_forall_of_pairwise _ (λ s s' : sigma β, s.1 = s'.1 → s = s') (λ s s' H h, (H h.symm).symm) _ (λ x h _, rfl) ((nodupkeys_iff_pairwise.1 nd).imp (λ s s' h h', (h h').elim)) _ h _ h' theorem nodupkeys.eq_of_mk_mem {a : α} {b b' : β a} {l : list (sigma β)} (nd : nodupkeys l) (h : sigma.mk a b ∈ l) (h' : sigma.mk a b' ∈ l) : b = b' := by cases nd.eq_of_fst_eq h h' rfl; refl theorem nodupkeys_singleton (s : sigma β) : nodupkeys [s] := nodup_singleton _ theorem nodupkeys_of_sublist {l₁ l₂ : list (sigma β)} (h : l₁ <+ l₂) : nodupkeys l₂ → nodupkeys l₁ := nodup_of_sublist (h.map _) theorem nodup_of_nodupkeys {l : list (sigma β)} : nodupkeys l → nodup l := nodup_of_nodup_map _ theorem perm_nodupkeys {l₁ l₂ : list (sigma β)} (h : l₁ ~ l₂) : nodupkeys l₁ ↔ nodupkeys l₂ := (h.map _).nodup_iff theorem nodupkeys_join {L : list (list (sigma β))} : nodupkeys (join L) ↔ (∀ l ∈ L, nodupkeys l) ∧ pairwise disjoint (L.map keys) := begin rw [nodupkeys_iff_pairwise, pairwise_join, pairwise_map], refine and_congr (ball_congr $ λ l h, by simp [nodupkeys_iff_pairwise]) _, apply iff_of_eq, congr' with l₁ l₂, simp [keys, disjoint_iff_ne] end theorem nodup_enum_map_fst (l : list α) : (l.enum.map prod.fst).nodup := by simp [list.nodup_range] lemma mem_ext {l₀ l₁ : list (sigma β)} (nd₀ : l₀.nodup) (nd₁ : l₁.nodup) (h : ∀ x, x ∈ l₀ ↔ x ∈ l₁) : l₀ ~ l₁ := begin induction l₀ with x xs generalizing l₁; cases l₁ with y ys, { constructor }, iterate 2 { specialize h x <|> specialize h y, simp at h, cases h }, simp at nd₀ nd₁, classical, cases nd₀, cases nd₁, by_cases h' : x = y, { subst y, constructor, apply l₀_ih ‹ _ › ‹ nodup ys ›, intro a, specialize h a, simp at h, by_cases h' : a = x, { subst a, rw ← not_iff_not, split; intro; assumption }, { simp [h'] at h, exact h } }, { transitivity x :: y :: ys.erase x, { constructor, apply l₀_ih ‹ _ ›, { simp, split, { intro, apply nd₁_left, apply mem_of_mem_erase a }, apply nodup_erase_of_nodup; assumption }, { intro a, specialize h a, simp at h, by_cases h' : a = x, { subst a, rw ← not_iff_not, split; intro, simp [mem_erase_of_nodup,*], assumption }, { simp [h'] at h, simp [h], apply or_congr, refl, simp [mem_erase_of_ne,*] } } }, transitivity y :: x :: ys.erase x, { constructor }, { constructor, symmetry, apply perm_cons_erase, specialize h x, simp [h'] at h, exact h } } end variables [decidable_eq α] /- lookup -/ /-- `lookup a l` is the first value in `l` corresponding to the key `a`, or `none` if no such element exists. -/ def lookup (a : α) : list (sigma β) → option (β a) | [] := none | (⟨a', b⟩ :: l) := if h : a' = a then some (eq.rec_on h b) else lookup l @[simp] theorem lookup_nil (a : α) : lookup a [] = @none (β a) := rfl @[simp] theorem lookup_cons_eq (l) (a : α) (b : β a) : lookup a (⟨a, b⟩::l) = some b := dif_pos rfl @[simp] theorem lookup_cons_ne (l) {a} : ∀ s : sigma β, a ≠ s.1 → lookup a (s::l) = lookup a l | ⟨a', b⟩ h := dif_neg h.symm theorem lookup_is_some {a : α} : ∀ {l : list (sigma β)}, (lookup a l).is_some ↔ a ∈ l.keys | [] := by simp | (⟨a', b⟩ :: l) := begin by_cases h : a = a', { subst a', simp }, { simp [h, lookup_is_some] }, end theorem lookup_eq_none {a : α} {l : list (sigma β)} : lookup a l = none ↔ a ∉ l.keys := by simp [← lookup_is_some, option.is_none_iff_eq_none] theorem of_mem_lookup {a : α} {b : β a} : ∀ {l : list (sigma β)}, b ∈ lookup a l → sigma.mk a b ∈ l | (⟨a', b'⟩ :: l) H := begin by_cases h : a = a', { subst a', simp at H, simp [H] }, { simp [h] at H, exact or.inr (of_mem_lookup H) } end theorem mem_lookup {a} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys) (h : sigma.mk a b ∈ l) : b ∈ lookup a l := begin cases option.is_some_iff_exists.mp (lookup_is_some.mpr (mem_keys_of_mem h)) with b' h', cases nd.eq_of_mk_mem h (of_mem_lookup h'), exact h' end theorem map_lookup_eq_find (a : α) : ∀ l : list (sigma β), (lookup a l).map (sigma.mk a) = find (λ s, a = s.1) l | [] := rfl | (⟨a', b'⟩ :: l) := begin by_cases h : a = a', { subst a', simp }, { simp [h, map_lookup_eq_find] } end theorem mem_lookup_iff {a : α} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys) : b ∈ lookup a l ↔ sigma.mk a b ∈ l := ⟨of_mem_lookup, mem_lookup nd⟩ theorem perm_lookup (a : α) {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup a l₁ = lookup a l₂ := by ext b; simp [mem_lookup_iff, nd₁, nd₂]; exact p.mem_iff lemma lookup_ext {l₀ l₁ : list (sigma β)} (nd₀ : l₀.nodupkeys) (nd₁ : l₁.nodupkeys) (h : ∀ x y, y ∈ l₀.lookup x ↔ y ∈ l₁.lookup x) : l₀ ~ l₁ := mem_ext (nodup_of_nodupkeys nd₀) (nodup_of_nodupkeys nd₁) (λ ⟨a,b⟩, by rw [← mem_lookup_iff, ← mem_lookup_iff, h]; assumption) /- lookup_all -/ /-- `lookup_all a l` is the list of all values in `l` corresponding to the key `a`. -/ def lookup_all (a : α) : list (sigma β) → list (β a) | [] := [] | (⟨a', b⟩ :: l) := if h : a' = a then eq.rec_on h b :: lookup_all l else lookup_all l @[simp] theorem lookup_all_nil (a : α) : lookup_all a [] = @nil (β a) := rfl @[simp] theorem lookup_all_cons_eq (l) (a : α) (b : β a) : lookup_all a (⟨a, b⟩::l) = b :: lookup_all a l := dif_pos rfl @[simp] theorem lookup_all_cons_ne (l) {a} : ∀ s : sigma β, a ≠ s.1 → lookup_all a (s::l) = lookup_all a l | ⟨a', b⟩ h := dif_neg h.symm theorem lookup_all_eq_nil {a : α} : ∀ {l : list (sigma β)}, lookup_all a l = [] ↔ ∀ b : β a, sigma.mk a b ∉ l | [] := by simp | (⟨a', b⟩ :: l) := begin by_cases h : a = a', { subst a', simp, exact ⟨_, or.inl rfl⟩ }, { simp [h, lookup_all_eq_nil] }, end theorem head_lookup_all (a : α) : ∀ l : list (sigma β), head' (lookup_all a l) = lookup a l | [] := by simp | (⟨a', b⟩ :: l) := by by_cases h : a = a'; [{subst h, simp}, simp *] theorem mem_lookup_all {a : α} {b : β a} : ∀ {l : list (sigma β)}, b ∈ lookup_all a l ↔ sigma.mk a b ∈ l | [] := by simp | (⟨a', b'⟩ :: l) := by by_cases h : a = a'; [{subst h, simp *}, simp *] theorem lookup_all_sublist (a : α) : ∀ l : list (sigma β), (lookup_all a l).map (sigma.mk a) <+ l | [] := by simp | (⟨a', b'⟩ :: l) := begin by_cases h : a = a', { subst h, simp, exact (lookup_all_sublist l).cons2 _ _ _ }, { simp [h], exact (lookup_all_sublist l).cons _ _ _ } end theorem lookup_all_length_le_one (a : α) {l : list (sigma β)} (h : l.nodupkeys) : length (lookup_all a l) ≤ 1 := by have := nodup_of_sublist ((lookup_all_sublist a l).map _) h; rw map_map at this; rwa [← nodup_repeat, ← map_const _ a] theorem lookup_all_eq_lookup (a : α) {l : list (sigma β)} (h : l.nodupkeys) : lookup_all a l = (lookup a l).to_list := begin rw ← head_lookup_all, have := lookup_all_length_le_one a h, revert this, rcases lookup_all a l with _|⟨b, _|⟨c, l⟩⟩; intro; try {refl}, exact absurd this dec_trivial end theorem lookup_all_nodup (a : α) {l : list (sigma β)} (h : l.nodupkeys) : (lookup_all a l).nodup := by rw lookup_all_eq_lookup a h; apply option.to_list_nodup theorem perm_lookup_all (a : α) {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup_all a l₁ = lookup_all a l₂ := by simp [lookup_all_eq_lookup, nd₁, nd₂, perm_lookup a nd₁ nd₂ p] /- kreplace -/ def kreplace (a : α) (b : β a) : list (sigma β) → list (sigma β) := lookmap $ λ s, if h : a = s.1 then some ⟨a, b⟩ else none theorem kreplace_of_forall_not (a : α) (b : β a) {l : list (sigma β)} (H : ∀ b : β a, sigma.mk a b ∉ l) : kreplace a b l = l := lookmap_of_forall_not _ $ begin rintro ⟨a', b'⟩ h, dsimp, split_ifs, { subst a', exact H _ h }, {refl} end theorem kreplace_self {a : α} {b : β a} {l : list (sigma β)} (nd : nodupkeys l) (h : sigma.mk a b ∈ l) : kreplace a b l = l := begin refine (lookmap_congr _).trans (lookmap_id' (option.guard (λ s, a = s.1)) _ _), { rintro ⟨a', b'⟩ h', dsimp [option.guard], split_ifs, { subst a', exact ⟨rfl, heq_of_eq $ nd.eq_of_mk_mem h h'⟩ }, { refl } }, { rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, dsimp [option.guard], split_ifs, { subst a₁, rintro ⟨⟩, simp }, { rintro ⟨⟩ } }, end theorem keys_kreplace (a : α) (b : β a) : ∀ l : list (sigma β), (kreplace a b l).keys = l.keys := lookmap_map_eq _ _ $ by rintro ⟨a₁, b₂⟩ ⟨a₂, b₂⟩; dsimp; split_ifs; simp [h] {contextual := tt} theorem kreplace_nodupkeys (a : α) (b : β a) {l : list (sigma β)} : (kreplace a b l).nodupkeys ↔ l.nodupkeys := by simp [nodupkeys, keys_kreplace] theorem perm.kreplace {a : α} {b : β a} {l₁ l₂ : list (sigma β)} (nd : l₁.nodupkeys) : l₁ ~ l₂ → kreplace a b l₁ ~ kreplace a b l₂ := perm_lookmap _ $ begin refine nd.pairwise_ne.imp _, intros x y h z h₁ w h₂, split_ifs at h₁ h₂; cases h₁; cases h₂, exact (h (h_2.symm.trans h_1)).elim end /- kerase -/ /-- Remove the first pair with the key `a`. -/ def kerase (a : α) : list (sigma β) → list (sigma β) := erasep $ λ s, a = s.1 @[simp] theorem kerase_nil {a} : @kerase _ β _ a [] = [] := rfl @[simp, priority 990] theorem kerase_cons_eq {a} {s : sigma β} {l : list (sigma β)} (h : a = s.1) : kerase a (s :: l) = l := by simp [kerase, h] @[simp, priority 990] theorem kerase_cons_ne {a} {s : sigma β} {l : list (sigma β)} (h : a ≠ s.1) : kerase a (s :: l) = s :: kerase a l := by simp [kerase, h] @[simp, priority 980] theorem kerase_of_not_mem_keys {a} {l : list (sigma β)} (h : a ∉ l.keys) : kerase a l = l := by induction l with _ _ ih; [refl, { simp [not_or_distrib] at h, simp [h.1, ih h.2] }] theorem kerase_sublist (a : α) (l : list (sigma β)) : kerase a l <+ l := erasep_sublist _ theorem kerase_keys_subset (a) (l : list (sigma β)) : (kerase a l).keys ⊆ l.keys := ((kerase_sublist a l).map _).subset theorem mem_keys_of_mem_keys_kerase {a₁ a₂} {l : list (sigma β)} : a₁ ∈ (kerase a₂ l).keys → a₁ ∈ l.keys := @kerase_keys_subset _ _ _ _ _ _ theorem exists_of_kerase {a : α} {l : list (sigma β)} (h : a ∈ l.keys) : ∃ (b : β a) (l₁ l₂ : list (sigma β)), a ∉ l₁.keys ∧ l = l₁ ++ ⟨a, b⟩ :: l₂ ∧ kerase a l = l₁ ++ l₂ := begin induction l, case list.nil { cases h }, case list.cons : hd tl ih { by_cases e : a = hd.1, { subst e, exact ⟨hd.2, [], tl, by simp, by cases hd; refl, by simp⟩ }, { simp at h, cases h, case or.inl : h { exact absurd h e }, case or.inr : h { rcases ih h with ⟨b, tl₁, tl₂, h₁, h₂, h₃⟩, exact ⟨b, hd :: tl₁, tl₂, not_mem_cons_of_ne_of_not_mem e h₁, by rw h₂; refl, by simp [e, h₃]⟩ } } } end @[simp, priority 990] theorem mem_keys_kerase_of_ne {a₁ a₂} {l : list (sigma β)} (h : a₁ ≠ a₂) : a₁ ∈ (kerase a₂ l).keys ↔ a₁ ∈ l.keys := iff.intro mem_keys_of_mem_keys_kerase $ λ p, if q : a₂ ∈ l.keys then match l, kerase a₂ l, exists_of_kerase q, p with | _, _, ⟨_, _, _, _, rfl, rfl⟩, p := by simpa [keys, h] using p end else by simp [q, p] theorem keys_kerase {a} {l : list (sigma β)} : (kerase a l).keys = l.keys.erase a := by rw [keys, kerase, ←erasep_map sigma.fst l, erase_eq_erasep] theorem kerase_kerase {a a'} {l : list (sigma β)} : (kerase a' l).kerase a = (kerase a l).kerase a' := begin by_cases a = a', { subst a' }, induction l with x xs, { refl }, { by_cases a' = x.1, { subst a', simp [kerase_cons_ne h,kerase_cons_eq rfl] }, by_cases h' : a = x.1, { subst a, simp [kerase_cons_eq rfl,kerase_cons_ne (ne.symm h)] }, { simp [kerase_cons_ne,*] } } end theorem kerase_nodupkeys (a : α) {l : list (sigma β)} : nodupkeys l → (kerase a l).nodupkeys := nodupkeys_of_sublist $ kerase_sublist _ _ theorem perm.kerase {a : α} {l₁ l₂ : list (sigma β)} (nd : l₁.nodupkeys) : l₁ ~ l₂ → kerase a l₁ ~ kerase a l₂ := perm.erasep _ $ (nodupkeys_iff_pairwise.1 nd).imp $ by rintro x y h rfl; exact h @[simp] theorem not_mem_keys_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) : a ∉ (kerase a l).keys := begin induction l, case list.nil { simp }, case list.cons : hd tl ih { simp at nd, by_cases h : a = hd.1, { subst h, simp [nd.1] }, { simp [h, ih nd.2] } } end @[simp] theorem lookup_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) : lookup a (kerase a l) = none := lookup_eq_none.mpr (not_mem_keys_kerase a nd) @[simp] theorem lookup_kerase_ne {a a'} {l : list (sigma β)} (h : a ≠ a') : lookup a (kerase a' l) = lookup a l := begin induction l, case list.nil { refl }, case list.cons : hd tl ih { cases hd with ah bh, by_cases h₁ : a = ah; by_cases h₂ : a' = ah, { substs h₁ h₂, cases ne.irrefl h }, { subst h₁, simp [h₂] }, { subst h₂, simp [h] }, { simp [h₁, h₂, ih] } } end theorem kerase_append_left {a} : ∀ {l₁ l₂ : list (sigma β)}, a ∈ l₁.keys → kerase a (l₁ ++ l₂) = kerase a l₁ ++ l₂ | [] _ h := by cases h | (s :: l₁) l₂ h₁ := if h₂ : a = s.1 then by simp [h₂] else by simp at h₁; cases h₁; [exact absurd h₁ h₂, simp [h₂, kerase_append_left h₁]] theorem kerase_append_right {a} : ∀ {l₁ l₂ : list (sigma β)}, a ∉ l₁.keys → kerase a (l₁ ++ l₂) = l₁ ++ kerase a l₂ | [] _ h := rfl | (_ :: l₁) l₂ h := by simp [not_or_distrib] at h; simp [h.1, kerase_append_right h.2] theorem kerase_comm (a₁ a₂) (l : list (sigma β)) : kerase a₂ (kerase a₁ l) = kerase a₁ (kerase a₂ l) := if h : a₁ = a₂ then by simp [h] else if ha₁ : a₁ ∈ l.keys then if ha₂ : a₂ ∈ l.keys then match l, kerase a₁ l, exists_of_kerase ha₁, ha₂ with | _, _, ⟨b₁, l₁, l₂, a₁_nin_l₁, rfl, rfl⟩, a₂_in_l₁_app_l₂ := if h' : a₂ ∈ l₁.keys then by simp [kerase_append_left h', kerase_append_right (mt (mem_keys_kerase_of_ne h).mp a₁_nin_l₁)] else by simp [kerase_append_right h', kerase_append_right a₁_nin_l₁, @kerase_cons_ne _ _ _ a₂ ⟨a₁, b₁⟩ _ (ne.symm h)] end else by simp [ha₂, mt mem_keys_of_mem_keys_kerase ha₂] else by simp [ha₁, mt mem_keys_of_mem_keys_kerase ha₁] lemma sizeof_kerase {α} {β : α → Type*} [decidable_eq α] [has_sizeof (sigma β)] (x : α) (xs : list (sigma β)) : sizeof (list.kerase x xs) ≤ sizeof xs := begin unfold_wf, induction xs with y ys, { simp }, { by_cases x = y.1; simp [*, list.sizeof] }, end /- kinsert -/ /-- Insert the pair `⟨a, b⟩` and erase the first pair with the key `a`. -/ def kinsert (a : α) (b : β a) (l : list (sigma β)) : list (sigma β) := ⟨a, b⟩ :: kerase a l @[simp] theorem kinsert_def {a} {b : β a} {l : list (sigma β)} : kinsert a b l = ⟨a, b⟩ :: kerase a l := rfl theorem mem_keys_kinsert {a a'} {b' : β a'} {l : list (sigma β)} : a ∈ (kinsert a' b' l).keys ↔ a = a' ∨ a ∈ l.keys := by by_cases h : a = a'; simp [h] theorem kinsert_nodupkeys (a) (b : β a) {l : list (sigma β)} (nd : l.nodupkeys) : (kinsert a b l).nodupkeys := nodupkeys_cons.mpr ⟨not_mem_keys_kerase a nd, kerase_nodupkeys a nd⟩ theorem perm.kinsert {a} {b : β a} {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (p : l₁ ~ l₂) : kinsert a b l₁ ~ kinsert a b l₂ := (p.kerase nd₁).cons _ theorem lookup_kinsert {a} {b : β a} (l : list (sigma β)) : lookup a (kinsert a b l) = some b := by simp only [kinsert, lookup_cons_eq] theorem lookup_kinsert_ne {a a'} {b' : β a'} {l : list (sigma β)} (h : a ≠ a') : lookup a (kinsert a' b' l) = lookup a l := by simp [h] /- kextract -/ def kextract (a : α) : list (sigma β) → option (β a) × list (sigma β) | [] := (none, []) | (s::l) := if h : s.1 = a then (some (eq.rec_on h s.2), l) else let (b', l') := kextract l in (b', s :: l') @[simp] theorem kextract_eq_lookup_kerase (a : α) : ∀ l : list (sigma β), kextract a l = (lookup a l, kerase a l) | [] := rfl | (⟨a', b⟩::l) := begin simp [kextract], dsimp, split_ifs, { subst a', simp [kerase] }, { simp [kextract, ne.symm h, kextract_eq_lookup_kerase l, kerase] } end /- erase_dupkeys -/ /-- Remove entries with duplicate keys from `l : list (sigma β)`. -/ def erase_dupkeys : list (sigma β) → list (sigma β) := list.foldr (λ x, kinsert x.1 x.2) [] lemma erase_dupkeys_cons {x : sigma β} (l : list (sigma β)) : erase_dupkeys (x :: l) = kinsert x.1 x.2 (erase_dupkeys l) := rfl lemma nodupkeys_erase_dupkeys (l : list (sigma β)) : nodupkeys (erase_dupkeys l) := begin dsimp [erase_dupkeys], generalize hl : nil = l', have : nodupkeys l', { rw ← hl, apply nodup_nil }, clear hl, induction l with x xs, { apply this }, { cases x, simp [erase_dupkeys], split, { simp [keys_kerase], apply mem_erase_of_nodup l_ih }, apply kerase_nodupkeys _ l_ih, } end lemma lookup_erase_dupkeys (a : α) (l : list (sigma β)) : lookup a (erase_dupkeys l) = lookup a l := begin induction l, refl, cases l_hd with a' b, by_cases a = a', { subst a', rw [erase_dupkeys_cons,lookup_kinsert,lookup_cons_eq] }, { rw [erase_dupkeys_cons,lookup_kinsert_ne h,l_ih,lookup_cons_ne], exact h }, end lemma sizeof_erase_dupkeys {α} {β : α → Type*} [decidable_eq α] [has_sizeof (sigma β)] (xs : list (sigma β)) : sizeof (list.erase_dupkeys xs) ≤ sizeof xs := begin unfold_wf, induction xs with x xs, { simp [list.erase_dupkeys] }, { simp only [erase_dupkeys_cons, list.sizeof, kinsert_def, add_le_add_iff_left, sigma.eta], transitivity, apply sizeof_kerase, assumption } end /- kunion -/ /-- `kunion l₁ l₂` is the append to l₁ of l₂ after, for each key in l₁, the first matching pair in l₂ is erased. -/ def kunion : list (sigma β) → list (sigma β) → list (sigma β) | [] l₂ := l₂ | (s :: l₁) l₂ := s :: kunion l₁ (kerase s.1 l₂) @[simp] theorem nil_kunion {l : list (sigma β)} : kunion [] l = l := rfl @[simp] theorem kunion_nil : ∀ {l : list (sigma β)}, kunion l [] = l | [] := rfl | (_ :: l) := by rw [kunion, kerase_nil, kunion_nil] @[simp] theorem kunion_cons {s} {l₁ l₂ : list (sigma β)} : kunion (s :: l₁) l₂ = s :: kunion l₁ (kerase s.1 l₂) := rfl @[simp] theorem mem_keys_kunion {a} {l₁ l₂ : list (sigma β)} : a ∈ (kunion l₁ l₂).keys ↔ a ∈ l₁.keys ∨ a ∈ l₂.keys := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : s l₁ ih { by_cases h : a = s.1; [simp [h], simp [h, ih]] } end @[simp] theorem kunion_kerase {a} : ∀ {l₁ l₂ : list (sigma β)}, kunion (kerase a l₁) (kerase a l₂) = kerase a (kunion l₁ l₂) | [] _ := rfl | (s :: _) l := by by_cases h : a = s.1; simp [h, kerase_comm a s.1 l, kunion_kerase] theorem kunion_nodupkeys {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) : (kunion l₁ l₂).nodupkeys := begin induction l₁ generalizing l₂, case list.nil { simp only [nil_kunion, nd₂] }, case list.cons : s l₁ ih { simp at nd₁, simp [not_or_distrib, nd₁.1, nd₂, ih nd₁.2 (kerase_nodupkeys s.1 nd₂)] } end theorem perm.kunion_right {l₁ l₂ : list (sigma β)} (p : l₁ ~ l₂) (l) : kunion l₁ l ~ kunion l₂ l := begin induction p generalizing l, case list.perm.nil { refl }, case list.perm.cons : hd tl₁ tl₂ p ih { simp [ih (kerase hd.1 l), perm.cons] }, case list.perm.swap : s₁ s₂ l { simp [kerase_comm, perm.swap] }, case list.perm.trans : l₁ l₂ l₃ p₁₂ p₂₃ ih₁₂ ih₂₃ { exact perm.trans (ih₁₂ l) (ih₂₃ l) } end theorem perm.kunion_left : ∀ l {l₁ l₂ : list (sigma β)}, l₁.nodupkeys → l₁ ~ l₂ → kunion l l₁ ~ kunion l l₂ | [] _ _ _ p := p | (s :: l) l₁ l₂ nd₁ p := by simp [((p.kerase nd₁).kunion_left l (kerase_nodupkeys s.1 nd₁)).cons s] theorem perm.kunion {l₁ l₂ l₃ l₄ : list (sigma β)} (nd₃ : l₃.nodupkeys) (p₁₂ : l₁ ~ l₂) (p₃₄ : l₃ ~ l₄) : kunion l₁ l₃ ~ kunion l₂ l₄ := (p₁₂.kunion_right l₃).trans (p₃₄.kunion_left l₂ nd₃) @[simp] theorem lookup_kunion_left {a} {l₁ l₂ : list (sigma β)} (h : a ∈ l₁.keys) : lookup a (kunion l₁ l₂) = lookup a l₁ := begin induction l₁ with s _ ih generalizing l₂; simp at h; cases h; cases s with a', { subst h, simp }, { rw kunion_cons, by_cases h' : a = a', { subst h', simp }, { simp [h', ih h] } } end @[simp] theorem lookup_kunion_right {a} {l₁ l₂ : list (sigma β)} (h : a ∉ l₁.keys) : lookup a (kunion l₁ l₂) = lookup a l₂ := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : _ _ ih { simp [not_or_distrib] at h, simp [h.1, ih h.2] } end @[simp] theorem mem_lookup_kunion {a} {b : β a} {l₁ l₂ : list (sigma β)} : b ∈ lookup a (kunion l₁ l₂) ↔ b ∈ lookup a l₁ ∨ a ∉ l₁.keys ∧ b ∈ lookup a l₂ := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : s _ ih { cases s with a', by_cases h₁ : a = a', { subst h₁, simp }, { let h₂ := @ih (kerase a' l₂), simp [h₁] at h₂, simp [h₁, h₂] } } end theorem mem_lookup_kunion_middle {a} {b : β a} {l₁ l₂ l₃ : list (sigma β)} (h₁ : b ∈ lookup a (kunion l₁ l₃)) (h₂ : a ∉ keys l₂) : b ∈ lookup a (kunion (kunion l₁ l₂) l₃) := match mem_lookup_kunion.mp h₁ with | or.inl h := mem_lookup_kunion.mpr (or.inl (mem_lookup_kunion.mpr (or.inl h))) | or.inr h := mem_lookup_kunion.mpr $ or.inr ⟨mt mem_keys_kunion.mp (not_or_distrib.mpr ⟨h.1, h₂⟩), h.2⟩ end end list
cba23b49c19d766e459f14ec07aa8b517f120052
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/limits/punit.lean
a9e045c56e8c10ca66f19cc6fa659fca3e844187
[ "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
974
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 category_theory.punit import category_theory.limits.limits /-! # `discrete punit` has limits and colimits Mostly for the sake of constructing trivial examples, we show all (co)cones into `discrete punit` are (co)limit (co)cones, and `discrete punit` has all (co)limits. -/ universe v open category_theory namespace category_theory.limits variables {J : Type v} [small_category J] {F : J ⥤ discrete punit.{v+1}} /-- Any cone over a functor into `punit` is a limit cone. -/ def punit_cone_is_limit {c : cone F} : is_limit c := by tidy /-- Any cocone over a functor into `punit` is a colimit cocone. -/ def punit_cocone_is_colimit {c : cocone F} : is_colimit c := by tidy instance : has_limits (discrete punit) := by tidy instance : has_colimits (discrete punit) := by tidy end category_theory.limits
c54357bb4b93e15e57d709c04153cfe94c5b83c2
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/rat/cast.lean
bf44984c62b12a5b2b366700ebcdf0307eecb819
[ "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
11,488
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.rat.order /-! # Casts for Rational Numbers ## Summary We define the canonical injection from ℚ into an arbitrary division ring and prove various casting lemmas showing the well-behavedness of this injection. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting -/ namespace rat variable {α : Type*} open_locale rat section with_div_ring variable [division_ring α] /-- Construct the canonical injection from `ℚ` into an arbitrary division ring. If the field has positive characteristic `p`, we define `1 / p = 1 / 0 = 0` for consistency with our division by zero convention. -/ @[priority 10] instance cast_coe : has_coe ℚ α := ⟨λ r, r.1 / r.2⟩ @[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n := show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one] @[simp, squash_cast] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n := by rw [coe_int_eq_of_int, cast_of_int] @[simp, squash_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n @[simp, squash_cast] theorem cast_zero : ((0 : ℚ) : α) = 0 := (cast_of_int _).trans int.cast_zero @[simp, squash_cast] theorem cast_one : ((1 : ℚ) : α) = 1 := (cast_of_int _).trans int.cast_one theorem mul_cast_comm (a : α) : ∀ (n : ℚ), (n.denom : α) ≠ 0 → a * n = n * a | ⟨n, d, h, c⟩ h₂ := show a * (n * d⁻¹) = n * d⁻¹ * a, by rw [← mul_assoc, int.mul_cast_comm, mul_assoc, mul_assoc, ← show (d:α)⁻¹ * a = a * d⁻¹, from division_ring.inv_comm_of_comm h₂ (int.mul_cast_comm a d).symm] @[move_cast] theorem cast_mk_of_ne_zero (a b : ℤ) (b0 : (b:α) ≠ 0) : (a /. b : α) = a / b := begin have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} }, cases e : a /. b with n d h c, have d0 : (d:α) ≠ 0, { intro d0, have dd := denom_dvd a b, cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke, have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl}, rw [d0, zero_mul] at this, contradiction }, rw [num_denom'] at e, have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e), rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this, symmetry, change (a * b⁻¹ : α) = n / d, rw [eq_div_iff_mul_eq _ _ d0, mul_assoc, nat.mul_cast_comm, ← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one] end @[move_cast] theorem cast_add_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', add_def d₁0' d₂0'], suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) + n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹, { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, left_distrib, right_distrib, mul_inv', d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} }, rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul, ← nat.mul_cast_comm], simp [d₁0, mul_assoc] end @[simp, move_cast] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n | ⟨n, d, h, c⟩ := show (↑-n * d⁻¹ : α) = -(n * d⁻¹), by rw [int.cast_neg, neg_mul_eq_neg_mul] @[move_cast] theorem cast_sub_of_ne_zero {m n : ℚ} (m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n := have ((-n).denom : α) ≠ 0, by cases n; exact n0, by simp [sub_eq_add_neg, (cast_add_of_ne_zero m0 this)] @[move_cast] theorem cast_mul_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', mul_def d₁0' d₂0'], suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)), { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, mul_inv', d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} }, rw [division_ring.inv_comm_of_comm d₁0 (nat.mul_cast_comm _ _).symm] end @[move_cast] theorem cast_inv_of_ne_zero : ∀ {n : ℚ}, (n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹ | ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl, have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl), rw [num_denom', inv_def], rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div]; simp [n0, d0] end @[move_cast] theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0) (nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n := have (n⁻¹.denom : ℤ) ∣ n.num, by conv in n⁻¹.denom { rw [←(@num_denom n), inv_def] }; apply denom_dvd, have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from λ h, let ⟨k, e⟩ := this in by have := congr_arg (coe : ℤ → α) e; rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this, by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def] @[simp, elim_cast] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin refine ⟨λ h, _, congr_arg _⟩, have d₁0 : d₁ ≠ 0 := ne_of_gt h₁, have d₂0 : d₂ ≠ 0 := ne_of_gt h₂, have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0, have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0, rw [num_denom', num_denom'] at h ⊢, rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢, rwa [eq_div_iff_mul_eq _ _ d₂a, division_def, mul_assoc, division_ring.inv_comm_of_comm d₁a (nat.mul_cast_comm _ _), ← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq _ _ d₁a, eq_comm, ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul, int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h end theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α) | m n := cast_inj.1 @[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero theorem eq_cast_of_ne_zero (f : ℚ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (Hmul : ∀ x y, f (x * y) = f x * f y) : ∀ n : ℚ, (n.denom : α) ≠ 0 → f n = n | ⟨n, d, h, c⟩ := λ (h₂ : ((d:ℤ):α) ≠ 0), show _ = (n / (d:ℤ) : α), begin rw [num_denom', mk_eq_div, eq_div_iff_mul_eq _ _ h₂], have : ∀ n : ℤ, f n = n, { apply int.eq_cast; simp [H1, Hadd] }, rw [← this, ← this, ← Hmul, div_mul_cancel], exact int.cast_ne_zero.2 (int.coe_nat_ne_zero.2 $ ne_of_gt h), end theorem eq_cast [char_zero α] (f : ℚ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (Hmul : ∀ x y, f (x * y) = f x * f y) (n : ℚ) : f n = n := eq_cast_of_ne_zero _ H1 Hadd Hmul _ $ nat.cast_ne_zero.2 $ ne_of_gt n.pos @[simp, move_cast] theorem cast_add [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n := cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, move_cast] theorem cast_sub [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n := cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, move_cast] theorem cast_mul [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n := cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, squash_cast, move_cast] theorem cast_bit0 [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _ @[simp, squash_cast, move_cast] theorem cast_bit1 [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl variable (α) /-- Coercion `ℚ → α` as a `ring_hom`. -/ def cast_hom [char_zero α] : ℚ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ variable {α} @[simp] lemma coe_cast_hom [char_zero α] : ⇑(cast_hom α) = coe := rfl @[simp, move_cast] theorem cast_inv [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ := (cast_hom α).map_inv @[simp, move_cast] theorem cast_div [char_zero α] (m n) : ((m / n : ℚ) : α) = m / n := (cast_hom α).map_div @[move_cast] theorem cast_mk [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b := by simp only [mk_eq_div, cast_div, cast_coe_int] @[simp, move_cast] theorem cast_pow [char_zero α] (q) (k : ℕ) : ((q ^ k : ℚ) : α) = q ^ k := (cast_hom α).map_pow q k end with_div_ring @[simp, elim_cast] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n | ⟨n, d, h, c⟩ := show 0 ≤ (n * d⁻¹ : α) ↔ 0 ≤ (⟨n, d, h, c⟩ : ℚ), by rw [num_denom', ← nonneg_iff_zero_le, mk_nonneg _ (int.coe_nat_pos.2 h), mul_nonneg_iff_right_nonneg_of_pos ((@inv_pos α _ _).2 (nat.cast_pos.2 h)), int.cast_nonneg] @[simp, elim_cast] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp, elim_cast] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, squash_cast] theorem cast_id : ∀ n : ℚ, ↑n = n | ⟨n, d, h, c⟩ := show (n / (d : ℤ) : ℚ) = _, by rw [num_denom', mk_eq_div] @[simp, move_cast] theorem cast_min [discrete_linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, move_cast] theorem cast_max [discrete_linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, move_cast] theorem cast_abs [discrete_linear_ordered_field α] {q : ℚ} : ((abs q : ℚ) : α) = abs q := by simp [abs] end rat
1f1fc951aa049f15638658104453e229780cc22d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/monad/basic.lean
69302b5bd815bf0fd1f45b9c8a7a43480c486aae
[ "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
11,452
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta, Adam Topaz -/ import category_theory.functor.category import category_theory.functor.fully_faithful import category_theory.functor.reflects_isomorphisms /-! # Monads > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We construct the categories of monads and comonads, and their forgetful functors to endofunctors. (Note that these are the category theorist's monads, not the programmers monads. For the translation, see the file `category_theory.monad.types`.) For the fact that monads are "just" monoids in the category of endofunctors, see the file `category_theory.monad.equiv_mon`. -/ namespace category_theory open category universes v₁ u₁ -- morphism levels before object levels. See note [category_theory universes]. variables (C : Type u₁) [category.{v₁} C] /-- The data of a monad on C consists of an endofunctor T together with natural transformations η : 𝟭 C ⟶ T and μ : T ⋙ T ⟶ T satisfying three equations: - T μ_X ≫ μ_X = μ_(TX) ≫ μ_X (associativity) - η_(TX) ≫ μ_X = 1_X (left unit) - Tη_X ≫ μ_X = 1_X (right unit) -/ structure monad extends C ⥤ C := (η' [] : 𝟭 _ ⟶ to_functor) (μ' [] : to_functor ⋙ to_functor ⟶ to_functor) (assoc' : ∀ X, to_functor.map (nat_trans.app μ' X) ≫ μ'.app _ = μ'.app _ ≫ μ'.app _ . obviously) (left_unit' : ∀ X : C, η'.app (to_functor.obj X) ≫ μ'.app _ = 𝟙 _ . obviously) (right_unit' : ∀ X : C, to_functor.map (η'.app X) ≫ μ'.app _ = 𝟙 _ . obviously) /-- The data of a comonad on C consists of an endofunctor G together with natural transformations ε : G ⟶ 𝟭 C and δ : G ⟶ G ⋙ G satisfying three equations: - δ_X ≫ G δ_X = δ_X ≫ δ_(GX) (coassociativity) - δ_X ≫ ε_(GX) = 1_X (left counit) - δ_X ≫ G ε_X = 1_X (right counit) -/ structure comonad extends C ⥤ C := (ε' [] : to_functor ⟶ 𝟭 _) (δ' [] : to_functor ⟶ to_functor ⋙ to_functor) (coassoc' : ∀ X, nat_trans.app δ' _ ≫ to_functor.map (δ'.app X) = δ'.app _ ≫ δ'.app _ . obviously) (left_counit' : ∀ X : C, δ'.app X ≫ ε'.app (to_functor.obj X) = 𝟙 _ . obviously) (right_counit' : ∀ X : C, δ'.app X ≫ to_functor.map (ε'.app X) = 𝟙 _ . obviously) variables {C} (T : monad C) (G : comonad C) instance coe_monad : has_coe (monad C) (C ⥤ C) := ⟨λ T, T.to_functor⟩ instance coe_comonad : has_coe (comonad C) (C ⥤ C) := ⟨λ G, G.to_functor⟩ @[simp] lemma monad_to_functor_eq_coe : T.to_functor = T := rfl @[simp] lemma comonad_to_functor_eq_coe : G.to_functor = G := rfl /-- The unit for the monad `T`. -/ def monad.η : 𝟭 _ ⟶ (T : C ⥤ C) := T.η' /-- The multiplication for the monad `T`. -/ def monad.μ : (T : C ⥤ C) ⋙ (T : C ⥤ C) ⟶ T := T.μ' /-- The counit for the comonad `G`. -/ def comonad.ε : (G : C ⥤ C) ⟶ 𝟭 _ := G.ε' /-- The comultiplication for the comonad `G`. -/ def comonad.δ : (G : C ⥤ C) ⟶ (G : C ⥤ C) ⋙ G := G.δ' /-- A custom simps projection for the functor part of a monad, as a coercion. -/ def monad.simps.coe := (T : C ⥤ C) /-- A custom simps projection for the unit of a monad, in simp normal form. -/ def monad.simps.η : 𝟭 _ ⟶ (T : C ⥤ C) := T.η /-- A custom simps projection for the multiplication of a monad, in simp normal form. -/ def monad.simps.μ : (T : C ⥤ C) ⋙ (T : C ⥤ C) ⟶ (T : C ⥤ C) := T.μ /-- A custom simps projection for the functor part of a comonad, as a coercion. -/ def comonad.simps.coe := (G : C ⥤ C) /-- A custom simps projection for the counit of a comonad, in simp normal form. -/ def comonad.simps.ε : (G : C ⥤ C) ⟶ 𝟭 _ := G.ε /-- A custom simps projection for the comultiplication of a comonad, in simp normal form. -/ def comonad.simps.δ : (G : C ⥤ C) ⟶ (G : C ⥤ C) ⋙ (G : C ⥤ C) := G.δ initialize_simps_projections category_theory.monad (to_functor → coe, η' → η, μ' → μ) initialize_simps_projections category_theory.comonad (to_functor → coe, ε' → ε, δ' → δ) @[reassoc] lemma monad.assoc (T : monad C) (X : C) : (T : C ⥤ C).map (T.μ.app X) ≫ T.μ.app _ = T.μ.app _ ≫ T.μ.app _ := T.assoc' X @[simp, reassoc] lemma monad.left_unit (T : monad C) (X : C) : T.η.app ((T : C ⥤ C).obj X) ≫ T.μ.app X = 𝟙 ((T : C ⥤ C).obj X) := T.left_unit' X @[simp, reassoc] lemma monad.right_unit (T : monad C) (X : C) : (T : C ⥤ C).map (T.η.app X) ≫ T.μ.app X = 𝟙 ((T : C ⥤ C).obj X) := T.right_unit' X @[reassoc] lemma comonad.coassoc (G : comonad C) (X : C) : G.δ.app _ ≫ (G : C ⥤ C).map (G.δ.app X) = G.δ.app _ ≫ G.δ.app _ := G.coassoc' X @[simp, reassoc] lemma comonad.left_counit (G : comonad C) (X : C) : G.δ.app X ≫ G.ε.app ((G : C ⥤ C).obj X) = 𝟙 ((G : C ⥤ C).obj X) := G.left_counit' X @[simp, reassoc] lemma comonad.right_counit (G : comonad C) (X : C) : G.δ.app X ≫ (G : C ⥤ C).map (G.ε.app X) = 𝟙 ((G : C ⥤ C).obj X) := G.right_counit' X /-- A morphism of monads is a natural transformation compatible with η and μ. -/ @[ext] structure monad_hom (T₁ T₂ : monad C) extends nat_trans (T₁ : C ⥤ C) T₂ := (app_η' : ∀ X, T₁.η.app X ≫ app X = T₂.η.app X . obviously) (app_μ' : ∀ X, T₁.μ.app X ≫ app X = ((T₁ : C ⥤ C).map (app X) ≫ app _) ≫ T₂.μ.app X . obviously) /-- A morphism of comonads is a natural transformation compatible with ε and δ. -/ @[ext] structure comonad_hom (M N : comonad C) extends nat_trans (M : C ⥤ C) N := (app_ε' : ∀ X, app X ≫ N.ε.app X = M.ε.app X . obviously) (app_δ' : ∀ X, app X ≫ N.δ.app X = M.δ.app X ≫ app _ ≫ (N : C ⥤ C).map (app X) . obviously) restate_axiom monad_hom.app_η' restate_axiom monad_hom.app_μ' attribute [simp, reassoc] monad_hom.app_η monad_hom.app_μ restate_axiom comonad_hom.app_ε' restate_axiom comonad_hom.app_δ' attribute [simp, reassoc] comonad_hom.app_ε comonad_hom.app_δ instance : category (monad C) := { hom := monad_hom, id := λ M, { to_nat_trans := 𝟙 (M : C ⥤ C) }, comp := λ _ _ _ f g, { to_nat_trans := { app := λ X, f.app X ≫ g.app X, naturality' := λ X Y h, by rw [assoc, f.1.naturality_assoc, g.1.naturality] } }, id_comp' := λ _ _ _, by {ext, apply id_comp}, comp_id' := λ _ _ _, by {ext, apply comp_id}, assoc' := λ _ _ _ _ _ _ _, by {ext, apply assoc} } instance : category (comonad C) := { hom := comonad_hom, id := λ M, { to_nat_trans := 𝟙 (M : C ⥤ C) }, comp := λ _ _ _ f g, { to_nat_trans := { app := λ X, f.app X ≫ g.app X, naturality' := λ X Y h, by rw [assoc, f.1.naturality_assoc, g.1.naturality] } }, id_comp' := λ _ _ _, by {ext, apply id_comp}, comp_id' := λ _ _ _, by {ext, apply comp_id}, assoc' := λ _ _ _ _ _ _ _, by {ext, apply assoc} } instance {T : monad C} : inhabited (monad_hom T T) := ⟨𝟙 T⟩ @[simp] lemma monad_hom.id_to_nat_trans (T : monad C) : (𝟙 T : T ⟶ T).to_nat_trans = 𝟙 (T : C ⥤ C) := rfl @[simp] lemma monad_hom.comp_to_nat_trans {T₁ T₂ T₃ : monad C} (f : T₁ ⟶ T₂) (g : T₂ ⟶ T₃) : (f ≫ g).to_nat_trans = ((f.to_nat_trans : _ ⟶ (T₂ : C ⥤ C)) ≫ g.to_nat_trans : (T₁ : C ⥤ C) ⟶ T₃) := rfl instance {G : comonad C} : inhabited (comonad_hom G G) := ⟨𝟙 G⟩ @[simp] lemma comonad_hom.id_to_nat_trans (T : comonad C) : (𝟙 T : T ⟶ T).to_nat_trans = 𝟙 (T : C ⥤ C) := rfl @[simp] lemma comp_to_nat_trans {T₁ T₂ T₃ : comonad C} (f : T₁ ⟶ T₂) (g : T₂ ⟶ T₃) : (f ≫ g).to_nat_trans = ((f.to_nat_trans : _ ⟶ (T₂ : C ⥤ C)) ≫ g.to_nat_trans : (T₁ : C ⥤ C) ⟶ T₃) := rfl /-- Construct a monad isomorphism from a natural isomorphism of functors where the forward direction is a monad morphism. -/ @[simps] def monad_iso.mk {M N : monad C} (f : (M : C ⥤ C) ≅ N) (f_η f_μ) : M ≅ N := { hom := { to_nat_trans := f.hom, app_η' := f_η, app_μ' := f_μ }, inv := { to_nat_trans := f.inv, app_η' := λ X, by simp [←f_η], app_μ' := λ X, begin rw ←nat_iso.cancel_nat_iso_hom_right f, simp only [nat_trans.naturality, iso.inv_hom_id_app, assoc, comp_id, f_μ, nat_trans.naturality_assoc, iso.inv_hom_id_app_assoc, ←functor.map_comp_assoc], simp, end } } /-- Construct a comonad isomorphism from a natural isomorphism of functors where the forward direction is a comonad morphism. -/ @[simps] def comonad_iso.mk {M N : comonad C} (f : (M : C ⥤ C) ≅ N) (f_ε f_δ) : M ≅ N := { hom := { to_nat_trans := f.hom, app_ε' := f_ε, app_δ' := f_δ }, inv := { to_nat_trans := f.inv, app_ε' := λ X, by simp [←f_ε], app_δ' := λ X, begin rw ←nat_iso.cancel_nat_iso_hom_left f, simp only [reassoc_of (f_δ X), iso.hom_inv_id_app_assoc, nat_trans.naturality_assoc], rw [←functor.map_comp, iso.hom_inv_id_app, functor.map_id], apply (comp_id _).symm end } } variable (C) /-- The forgetful functor from the category of monads to the category of endofunctors. -/ @[simps] def monad_to_functor : monad C ⥤ (C ⥤ C) := { obj := λ T, T, map := λ M N f, f.to_nat_trans } instance : faithful (monad_to_functor C) := {}. lemma monad_to_functor_map_iso_monad_iso_mk {M N : monad C} (f : (M : C ⥤ C) ≅ N) (f_η f_μ) : (monad_to_functor _).map_iso (monad_iso.mk f f_η f_μ) = f := by { ext, refl } instance : reflects_isomorphisms (monad_to_functor C) := { reflects := λ M N f i, begin resetI, convert is_iso.of_iso (monad_iso.mk (as_iso ((monad_to_functor C).map f)) f.app_η f.app_μ), ext; refl, end } /-- The forgetful functor from the category of comonads to the category of endofunctors. -/ @[simps] def comonad_to_functor : comonad C ⥤ (C ⥤ C) := { obj := λ G, G, map := λ M N f, f.to_nat_trans } instance : faithful (comonad_to_functor C) := {}. lemma comonad_to_functor_map_iso_comonad_iso_mk {M N : comonad C} (f : (M : C ⥤ C) ≅ N) (f_ε f_δ) : (comonad_to_functor _).map_iso (comonad_iso.mk f f_ε f_δ) = f := by { ext, refl } instance : reflects_isomorphisms (comonad_to_functor C) := { reflects := λ M N f i, begin resetI, convert is_iso.of_iso (comonad_iso.mk (as_iso ((comonad_to_functor C).map f)) f.app_ε f.app_δ), ext; refl, end } variable {C} /-- An isomorphism of monads gives a natural isomorphism of the underlying functors. -/ @[simps {rhs_md := semireducible}] def monad_iso.to_nat_iso {M N : monad C} (h : M ≅ N) : (M : C ⥤ C) ≅ N := (monad_to_functor C).map_iso h /-- An isomorphism of comonads gives a natural isomorphism of the underlying functors. -/ @[simps {rhs_md := semireducible}] def comonad_iso.to_nat_iso {M N : comonad C} (h : M ≅ N) : (M : C ⥤ C) ≅ N := (comonad_to_functor C).map_iso h variable (C) namespace monad /-- The identity monad. -/ @[simps] def id : monad C := { to_functor := 𝟭 C, η' := 𝟙 (𝟭 C), μ' := 𝟙 (𝟭 C) } instance : inhabited (monad C) := ⟨monad.id C⟩ end monad namespace comonad /-- The identity comonad. -/ @[simps] def id : comonad C := { to_functor := 𝟭 _, ε' := 𝟙 (𝟭 C), δ' := 𝟙 (𝟭 C) } instance : inhabited (comonad C) := ⟨comonad.id C⟩ end comonad end category_theory
c9d305bad4e56279b3f1220be06d8b994a8b30a1
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/tst4.lean
93104e72c8c90ad883343b9db10904457d78b2b0
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
503
lean
variable f {A : Type} (a b : A) : A variable N : Type variable n1 : N variable n2 : N set_option lean::pp::implicit true print f n1 n2 print f (fun x : N -> N, x) (fun y : _, y) variable EqNice {A : Type} (lhs rhs : A) : Bool infix 50 === : EqNice print n1 === n2 check f n1 n2 check @congr print f n1 n2 variable a : N variable b : N variable c : N variable g : N -> N axiom H1 : a = b && b = c theorem Pr : (g a) = (g c) := congr (refl g) (trans (and_eliml H1) (and_elimr H1)) print environment 2
11a69c0c5f94f1d38588fedb9d48842f830866ef
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/special_functions/arsinh.lean
545a87e21093281789922179cc32607e5cfc6632
[ "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
8,741
lean
/- Copyright (c) 2020 James Arthur. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: James Arthur, Chris Hughes, Shing Tak Lam -/ import analysis.special_functions.trigonometric.deriv import analysis.special_functions.log.basic /-! # Inverse of the sinh function In this file we prove that sinh is bijective and hence has an inverse, arsinh. ## Main definitions - `real.arsinh`: The inverse function of `real.sinh`. - `real.sinh_equiv`, `real.sinh_order_iso`, `real.sinh_homeomorph`: `real.sinh` as an `equiv`, `order_iso`, and `homeomorph`, respectively. ## Main Results - `real.sinh_surjective`, `real.sinh_bijective`: `real.sinh` is surjective and bijective; - `real.arsinh_injective`, `real.arsinh_surjective`, `real.arsinh_bijective`: `real.arsinh` is injective, surjective, and bijective; - `real.continuous_arsinh`, `real.differentiable_arsinh`, `real.cont_diff_arsinh`: `real.arsinh` is continuous, differentiable, and continuously differentiable; we also provide dot notation convenience lemmas like `filter.tendsto.arsinh` and `cont_diff_at.arsinh`. ## Tags arsinh, arcsinh, argsinh, asinh, sinh injective, sinh bijective, sinh surjective -/ noncomputable theory open function filter set open_locale topological_space namespace real variables {x y : ℝ} /-- `arsinh` is defined using a logarithm, `arsinh x = log (x + sqrt(1 + x^2))`. -/ @[pp_nodot] def arsinh (x : ℝ) := log (x + sqrt (1 + x^2)) lemma exp_arsinh (x : ℝ) : exp (arsinh x) = x + sqrt (1 + x^2) := begin apply exp_log, rw [← neg_lt_iff_pos_add'], calc -x ≤ sqrt (x ^ 2) : le_sqrt_of_sq_le (neg_pow_bit0 _ _).le ... < sqrt (1 + x ^ 2) : sqrt_lt_sqrt (sq_nonneg _) (lt_one_add _) end @[simp] lemma arsinh_zero : arsinh 0 = 0 := by simp [arsinh] @[simp] lemma arsinh_neg (x : ℝ) : arsinh (-x) = -arsinh x := begin rw [← exp_eq_exp, exp_arsinh, exp_neg, exp_arsinh], apply eq_inv_of_mul_eq_one_left, rw [neg_sq, neg_add_eq_sub, add_comm x, mul_comm, ← sq_sub_sq, sq_sqrt, add_sub_cancel], exact add_nonneg zero_le_one (sq_nonneg _) end /-- `arsinh` is the right inverse of `sinh`. -/ @[simp] lemma sinh_arsinh (x : ℝ) : sinh (arsinh x) = x := by { rw [sinh_eq, ← arsinh_neg, exp_arsinh, exp_arsinh, neg_sq], field_simp } @[simp] lemma cosh_arsinh (x : ℝ) : cosh (arsinh x) = sqrt (1 + x^2) := by rw [← sqrt_sq (cosh_pos _).le, cosh_sq', sinh_arsinh] /-- `sinh` is surjective, `∀ b, ∃ a, sinh a = b`. In this case, we use `a = arsinh b`. -/ lemma sinh_surjective : surjective sinh := left_inverse.surjective sinh_arsinh /-- `sinh` is bijective, both injective and surjective. -/ lemma sinh_bijective : bijective sinh := ⟨sinh_injective, sinh_surjective⟩ /-- `arsinh` is the left inverse of `sinh`. -/ @[simp] lemma arsinh_sinh (x : ℝ) : arsinh (sinh x) = x := right_inverse_of_injective_of_left_inverse sinh_injective sinh_arsinh x /-- `real.sinh` as an `equiv`. -/ @[simps] def sinh_equiv : ℝ ≃ ℝ := { to_fun := sinh, inv_fun := arsinh, left_inv := arsinh_sinh, right_inv := sinh_arsinh } /-- `real.sinh` as an `order_iso`. -/ @[simps { fully_applied := ff }] def sinh_order_iso : ℝ ≃o ℝ := { to_equiv := sinh_equiv, map_rel_iff' := @sinh_le_sinh } /-- `real.sinh` as a `homeomorph`. -/ @[simps { fully_applied := ff }] def sinh_homeomorph : ℝ ≃ₜ ℝ := sinh_order_iso.to_homeomorph lemma arsinh_bijective : bijective arsinh := sinh_equiv.symm.bijective lemma arsinh_injective : injective arsinh := sinh_equiv.symm.injective lemma arsinh_surjective : surjective arsinh := sinh_equiv.symm.surjective lemma arsinh_strict_mono : strict_mono arsinh := sinh_order_iso.symm.strict_mono @[simp] lemma arsinh_inj : arsinh x = arsinh y ↔ x = y := arsinh_injective.eq_iff @[simp] lemma arsinh_le_arsinh : arsinh x ≤ arsinh y ↔ x ≤ y := sinh_order_iso.symm.le_iff_le @[simp] lemma arsinh_lt_arsinh : arsinh x < arsinh y ↔ x < y := sinh_order_iso.symm.lt_iff_lt @[simp] lemma arsinh_eq_zero_iff : arsinh x = 0 ↔ x = 0 := arsinh_injective.eq_iff' arsinh_zero @[simp] lemma arsinh_nonneg_iff : 0 ≤ arsinh x ↔ 0 ≤ x := by rw [← sinh_le_sinh, sinh_zero, sinh_arsinh] @[simp] lemma arsinh_nonpos_iff : arsinh x ≤ 0 ↔ x ≤ 0 := by rw [← sinh_le_sinh, sinh_zero, sinh_arsinh] @[simp] lemma arsinh_pos_iff : 0 < arsinh x ↔ 0 < x := lt_iff_lt_of_le_iff_le arsinh_nonpos_iff @[simp] lemma arsinh_neg_iff : arsinh x < 0 ↔ x < 0 := lt_iff_lt_of_le_iff_le arsinh_nonneg_iff lemma has_strict_deriv_at_arsinh (x : ℝ) : has_strict_deriv_at arsinh (sqrt (1 + x ^ 2))⁻¹ x := begin convert sinh_homeomorph.to_local_homeomorph.has_strict_deriv_at_symm (mem_univ x) (cosh_pos _).ne' (has_strict_deriv_at_sinh _), exact (cosh_arsinh _).symm end lemma has_deriv_at_arsinh (x : ℝ) : has_deriv_at arsinh (sqrt (1 + x ^ 2))⁻¹ x := (has_strict_deriv_at_arsinh x).has_deriv_at lemma differentiable_arsinh : differentiable ℝ arsinh := λ x, (has_deriv_at_arsinh x).differentiable_at lemma cont_diff_arsinh {n : ℕ∞} : cont_diff ℝ n arsinh := sinh_homeomorph.cont_diff_symm_deriv (λ x, (cosh_pos x).ne') has_deriv_at_sinh cont_diff_sinh @[continuity] lemma continuous_arsinh : continuous arsinh := sinh_homeomorph.symm.continuous end real open real lemma filter.tendsto.arsinh {α : Type*} {l : filter α} {f : α → ℝ} {a : ℝ} (h : tendsto f l (𝓝 a)) : tendsto (λ x, arsinh (f x)) l (𝓝 (arsinh a)) := (continuous_arsinh.tendsto _).comp h section continuous variables {X : Type*} [topological_space X] {f : X → ℝ} {s : set X} {a : X} lemma continuous_at.arsinh (h : continuous_at f a) : continuous_at (λ x, arsinh (f x)) a := h.arsinh lemma continuous_within_at.arsinh (h : continuous_within_at f s a) : continuous_within_at (λ x, arsinh (f x)) s a := h.arsinh lemma continuous_on.arsinh (h : continuous_on f s) : continuous_on (λ x, arsinh (f x)) s := λ x hx, (h x hx).arsinh lemma continuous.arsinh (h : continuous f) : continuous (λ x, arsinh (f x)) := continuous_arsinh.comp h end continuous section fderiv variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {f : E → ℝ} {s : set E} {a : E} {f' : E →L[ℝ] ℝ} {n : ℕ∞} lemma has_strict_fderiv_at.arsinh (hf : has_strict_fderiv_at f f' a) : has_strict_fderiv_at (λ x, arsinh (f x)) ((sqrt (1 + (f a) ^ 2))⁻¹ • f') a := (has_strict_deriv_at_arsinh _).comp_has_strict_fderiv_at a hf lemma has_fderiv_at.arsinh (hf : has_fderiv_at f f' a) : has_fderiv_at (λ x, arsinh (f x)) ((sqrt (1 + (f a) ^ 2))⁻¹ • f') a := (has_deriv_at_arsinh _).comp_has_fderiv_at a hf lemma has_fderiv_within_at.arsinh (hf : has_fderiv_within_at f f' s a) : has_fderiv_within_at (λ x, arsinh (f x)) ((sqrt (1 + (f a) ^ 2))⁻¹ • f') s a := (has_deriv_at_arsinh _).comp_has_fderiv_within_at a hf lemma differentiable_at.arsinh (h : differentiable_at ℝ f a) : differentiable_at ℝ (λ x, arsinh (f x)) a := (differentiable_arsinh _).comp a h lemma differentiable_within_at.arsinh (h : differentiable_within_at ℝ f s a) : differentiable_within_at ℝ (λ x, arsinh (f x)) s a := (differentiable_arsinh _).comp_differentiable_within_at a h lemma differentiable_on.arsinh (h : differentiable_on ℝ f s) : differentiable_on ℝ (λ x, arsinh (f x)) s := λ x hx, (h x hx).arsinh lemma differentiable.arsinh (h : differentiable ℝ f) : differentiable ℝ (λ x, arsinh (f x)) := differentiable_arsinh.comp h lemma cont_diff_at.arsinh (h : cont_diff_at ℝ n f a) : cont_diff_at ℝ n (λ x, arsinh (f x)) a := cont_diff_arsinh.cont_diff_at.comp a h lemma cont_diff_within_at.arsinh (h : cont_diff_within_at ℝ n f s a) : cont_diff_within_at ℝ n (λ x, arsinh (f x)) s a := cont_diff_arsinh.cont_diff_at.comp_cont_diff_within_at a h lemma cont_diff.arsinh (h : cont_diff ℝ n f) : cont_diff ℝ n (λ x, arsinh (f x)) := cont_diff_arsinh.comp h lemma cont_diff_on.arsinh (h : cont_diff_on ℝ n f s) : cont_diff_on ℝ n (λ x, arsinh (f x)) s := λ x hx, (h x hx).arsinh end fderiv section deriv variables {f : ℝ → ℝ} {s : set ℝ} {a f' : ℝ} lemma has_strict_deriv_at.arsinh (hf : has_strict_deriv_at f f' a) : has_strict_deriv_at (λ x, arsinh (f x)) ((sqrt (1 + (f a) ^ 2))⁻¹ • f') a := (has_strict_deriv_at_arsinh _).comp a hf lemma has_deriv_at.arsinh (hf : has_deriv_at f f' a) : has_deriv_at (λ x, arsinh (f x)) ((sqrt (1 + (f a) ^ 2))⁻¹ • f') a := (has_deriv_at_arsinh _).comp a hf lemma has_deriv_within_at.arsinh (hf : has_deriv_within_at f f' s a) : has_deriv_within_at (λ x, arsinh (f x)) ((sqrt (1 + (f a) ^ 2))⁻¹ • f') s a := (has_deriv_at_arsinh _).comp_has_deriv_within_at a hf end deriv
b975539358cfc556aa30d851e1180c578b14b29f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/polynomial/erase_lead.lean
c17b0e7673ad41414cf80ed82c87d6122927ba4e
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
6,975
lean
/- Copyright (c) 2020 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.polynomial.degree import data.polynomial.degree.trailing_degree /-! # Erase the leading term of a univariate polynomial ## Definition * `erase_lead f`: the polynomial `f - leading term of f` `erase_lead` serves as reduction step in an induction, shaving off one monomial from a polynomial. The definition is set up so that it does not mention subtraction in the definition, and thus works for polynomials over semirings as well as rings. -/ noncomputable theory open_locale classical open polynomial finset namespace polynomial variables {R : Type*} [semiring R] {f : polynomial R} /-- `erase_lead f` for a polynomial `f` is the polynomial obtained by subtracting from `f` the leading term of `f`. -/ def erase_lead (f : polynomial R) : polynomial R := polynomial.erase f.nat_degree f section erase_lead lemma erase_lead_support (f : polynomial R) : f.erase_lead.support = f.support.erase f.nat_degree := by simp only [erase_lead, support_erase] lemma erase_lead_coeff (i : ℕ) : f.erase_lead.coeff i = if i = f.nat_degree then 0 else f.coeff i := by simp only [erase_lead, coeff_erase] @[simp] lemma erase_lead_coeff_nat_degree : f.erase_lead.coeff f.nat_degree = 0 := by simp [erase_lead_coeff] lemma erase_lead_coeff_of_ne (i : ℕ) (hi : i ≠ f.nat_degree) : f.erase_lead.coeff i = f.coeff i := by simp [erase_lead_coeff, hi] @[simp] lemma erase_lead_zero : erase_lead (0 : polynomial R) = 0 := by simp only [erase_lead, erase_zero] @[simp] lemma erase_lead_add_monomial_nat_degree_leading_coeff (f : polynomial R) : f.erase_lead + monomial f.nat_degree f.leading_coeff = f := begin ext i, simp only [erase_lead_coeff, coeff_monomial, coeff_add, @eq_comm _ _ i], split_ifs with h, { subst i, simp only [leading_coeff, zero_add] }, { exact add_zero _ } end @[simp] lemma erase_lead_add_C_mul_X_pow (f : polynomial R) : f.erase_lead + (C f.leading_coeff) * X ^ f.nat_degree = f := by rw [C_mul_X_pow_eq_monomial, erase_lead_add_monomial_nat_degree_leading_coeff] @[simp] lemma self_sub_monomial_nat_degree_leading_coeff {R : Type*} [ring R] (f : polynomial R) : f - monomial f.nat_degree f.leading_coeff = f.erase_lead := (eq_sub_iff_add_eq.mpr (erase_lead_add_monomial_nat_degree_leading_coeff f)).symm @[simp] lemma self_sub_C_mul_X_pow {R : Type*} [ring R] (f : polynomial R) : f - (C f.leading_coeff) * X ^ f.nat_degree = f.erase_lead := by rw [C_mul_X_pow_eq_monomial, self_sub_monomial_nat_degree_leading_coeff] lemma erase_lead_ne_zero (f0 : 2 ≤ f.support.card) : erase_lead f ≠ 0 := begin rw [ne.def, ← card_support_eq_zero, erase_lead_support], exact (zero_lt_one.trans_le $ (nat.sub_le_sub_right f0 1).trans finset.pred_card_le_card_erase).ne.symm end @[simp] lemma nat_degree_not_mem_erase_lead_support : f.nat_degree ∉ (erase_lead f).support := by simp [not_mem_support_iff] lemma ne_nat_degree_of_mem_erase_lead_support {a : ℕ} (h : a ∈ (erase_lead f).support) : a ≠ f.nat_degree := by { rintro rfl, exact nat_degree_not_mem_erase_lead_support h } lemma erase_lead_support_card_lt (h : f ≠ 0) : (erase_lead f).support.card < f.support.card := begin rw erase_lead_support, exact card_lt_card (erase_ssubset $ nat_degree_mem_support_of_nonzero h) end lemma erase_lead_card_support {c : ℕ} (fc : f.support.card = c) : f.erase_lead.support.card = c - 1 := begin by_cases f0 : f = 0, { rw [← fc, f0, erase_lead_zero, support_zero, card_empty] }, { rw [erase_lead_support, card_erase_of_mem (nat_degree_mem_support_of_nonzero f0), fc], exact c.pred_eq_sub_one }, end lemma erase_lead_card_support' {c : ℕ} (fc : f.support.card = c + 1) : f.erase_lead.support.card = c := erase_lead_card_support fc @[simp] lemma erase_lead_monomial (i : ℕ) (r : R) : erase_lead (monomial i r) = 0 := begin by_cases hr : r = 0, { subst r, simp only [monomial_zero_right, erase_lead_zero] }, { rw [erase_lead, nat_degree_monomial _ _ hr, erase_monomial] } end @[simp] lemma erase_lead_C (r : R) : erase_lead (C r) = 0 := erase_lead_monomial _ _ @[simp] lemma erase_lead_X : erase_lead (X : polynomial R) = 0 := erase_lead_monomial _ _ @[simp] lemma erase_lead_X_pow (n : ℕ) : erase_lead (X ^ n : polynomial R) = 0 := by rw [X_pow_eq_monomial, erase_lead_monomial] @[simp] lemma erase_lead_C_mul_X_pow (r : R) (n : ℕ) : erase_lead (C r * X ^ n) = 0 := by rw [C_mul_X_pow_eq_monomial, erase_lead_monomial] lemma erase_lead_degree_le : (erase_lead f).degree ≤ f.degree := begin rw degree_le_iff_coeff_zero, intros i hi, rw erase_lead_coeff, split_ifs with h, { refl }, apply coeff_eq_zero_of_degree_lt hi end lemma erase_lead_nat_degree_le : (erase_lead f).nat_degree ≤ f.nat_degree := nat_degree_le_nat_degree erase_lead_degree_le lemma erase_lead_nat_degree_lt (f0 : 2 ≤ f.support.card) : (erase_lead f).nat_degree < f.nat_degree := lt_of_le_of_ne erase_lead_nat_degree_le $ ne_nat_degree_of_mem_erase_lead_support $ nat_degree_mem_support_of_nonzero $ erase_lead_ne_zero f0 lemma erase_lead_nat_degree_lt_or_erase_lead_eq_zero (f : polynomial R) : (erase_lead f).nat_degree < f.nat_degree ∨ f.erase_lead = 0 := begin by_cases h : f.support.card ≤ 1, { right, rw ← C_mul_X_pow_eq_self h, simp }, { left, apply erase_lead_nat_degree_lt (lt_of_not_ge h) } end end erase_lead /-- An induction lemma for polynomials. It takes a natural number `N` as a parameter, that is required to be at least as big as the `nat_degree` of the polynomial. This is useful to prove results where you want to change each term in a polynomial to something else depending on the `nat_degree` of the polynomial itself and not on the specific `nat_degree` of each term. -/ lemma induction_with_nat_degree_le {R : Type*} [semiring R] {P : polynomial R → Prop} (N : ℕ) (P_0 : P 0) (P_C_mul_pow : ∀ n : ℕ, ∀ r : R, r ≠ 0 → n ≤ N → P (C r * X ^ n)) (P_C_add : ∀ f g : polynomial R, f.nat_degree ≤ N → g.nat_degree ≤ N → P f → P g → P (f + g)) : ∀ f : polynomial R, f.nat_degree ≤ N → P f := begin intros f df, generalize' hd : card f.support = c, revert f, induction c with c hc, { assume f df f0, convert P_0, simpa only [support_eq_empty, card_eq_zero] using f0}, -- exact λ f df f0, by rwa (finsupp.support_eq_empty.mp (card_eq_zero.mp f0)) }, { intros f df f0, rw ← erase_lead_add_C_mul_X_pow f, refine P_C_add f.erase_lead _ (erase_lead_nat_degree_le.trans df) _ _ _, { exact (nat_degree_C_mul_X_pow_le f.leading_coeff f.nat_degree).trans df }, { exact hc _ (erase_lead_nat_degree_le.trans df) (erase_lead_card_support f0) }, { refine P_C_mul_pow _ _ _ df, rw [ne.def, leading_coeff_eq_zero], rintro rfl, exact not_le.mpr c.succ_pos f0.ge } } end end polynomial