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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8c7cd34f8e6a55f98f1c8d10e1cac6fad0ac77ee
|
048b0801f6dafb6486ca4f22bd0957671c3002ff
|
/src/repl.lean
|
18577458b24355ff3733dfd9f7f21fea0d0069b1
|
[
"Apache-2.0"
] |
permissive
|
Scikud/lean-gym
|
e0782e36389ecfa1605a0c12dc95f67014a0fa05
|
a1ca851b7c09eca1f72be2d059e3ed5536348b0b
|
refs/heads/main
| 1,693,940,033,482
| 1,633,522,864,000
| 1,633,522,864,000
| 419,793,692
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 10,776
|
lean
|
/-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author(s): Stanislas Polu, Jesse Michael Han
REPL implementation to interact with Lean through stdio at a specific
declaration.
-/
import tactic
import data.string.basic
import all
import util.io
import util.tactic
import tactic.gptf.utils.util
import basic.table
import tactic.gptf.basic
section main
setup_tactic_parser
meta structure LeanREPLRequest : Type :=
(cmd : string)
(sid: string)
(tsid: string)
(tac: string)
(name: string)
(open_ns: string)
meta structure LeanREPLResponse : Type :=
(sid : option string)
(tsid : option string)
(tactic_state : option string)
(error: option string)
meta structure LeanREPLState : Type :=
(state : dict string (dict string tactic_state))
(next_sid : ℕ)
namespace LeanREPLState
meta def insert_ts (σ : LeanREPLState) (sid) (tsid) (ts) : LeanREPLState :=
⟨dict.insert sid (dict.insert tsid ts (σ.1.get_default (dict.empty) sid)) σ.1, σ.2⟩
meta def get_ts (σ : LeanREPLState) (sid) (tsid) : option tactic_state := (σ.1.get_default (dict.empty) sid).get tsid
meta def get_next_tsid (σ : LeanREPLState) (sid) : string := (format! "{(σ.1.get_default (dict.empty) sid).size}").to_string
meta def erase_search (σ : LeanREPLState) (sid) : LeanREPLState := ⟨σ.1.erase sid, σ.2⟩
meta def get_next_sid (σ : LeanREPLState) : string := (format! "{σ.2}").to_string
meta def incr_next_sid (σ : LeanREPLState) : LeanREPLState := ⟨σ.1, σ.2+1⟩
end LeanREPLState
meta instance : has_from_json LeanREPLRequest := ⟨λ msg, match msg with
| (json.array [json.of_string cmd, json.array args]) := match cmd with
| "run_tac" := match json.array args with
| (json.array [json.of_string sid, json.of_string tsid, json.of_string tac]) := pure ⟨cmd, sid, tsid, tac, "", ""⟩
| exc := tactic.fail format!"request_parsing_error: cmd={cmd} data={exc}"
end
| "init_search" := match json.array args with
| (json.array [json.of_string name, json.of_string open_ns]) := pure ⟨cmd, "", "", "", name, open_ns⟩
| exc := tactic.fail format!"request_parsing_error: cmd={cmd} data={exc}"
end
| "clear_search" := match json.array args with
| (json.array [json.of_string sid]) := pure ⟨cmd, sid, "" , "", "", ""⟩
| exc := tactic.fail format!"request_parsing_error: cmd={cmd} data={exc}"
end
| exc := tactic.fail format!"request_parsing_error: data={exc}"
end
| exc := tactic.fail format!"request_parsing_error: data={exc}"
end
⟩
@[reducible]
meta def LeanREPL := state_t LeanREPLState io
meta def LeanREPL.forever (x : LeanREPL unit) : LeanREPL unit := do
σ₀ ← get,
state_t.lift $ io.iterate σ₀ $ λ σ, do {
(_, σ') ← x.run σ,
return (some σ')
},
state_t.lift $ io.fail' $ format! "[LeanREPL.forever] unreachable code"
meta def record_ts {m} [monad m] (sid: string) (ts : tactic_state) : (state_t LeanREPLState m) string := do {
σ ← get,
let tsid := σ.get_next_tsid sid,
modify $ λ σ, σ.insert_ts sid tsid ts,
pure tsid
}
meta def LeanREPLResponse.to_json: LeanREPLResponse → json
| ⟨sid, tsid, ts, err⟩ :=
json.object [
⟨"search_id", match sid with
| none := json.null
| some sid := json.of_string sid
end⟩,
⟨"tactic_state_id", match tsid with
| none := json.null
| some tsid := json.of_string tsid
end⟩,
⟨"tactic_state", match ts with
| none := json.null
| some ts := json.of_string ts
end⟩,
⟨"error", match err with
| none := json.null
| some err := json.of_string err
end⟩
]
meta instance : has_to_format LeanREPLResponse :=
⟨has_to_format.to_format ∘ LeanREPLResponse.to_json⟩
meta def parse_theorem_name (nm: string) : tactic name :=
do lean.parser.run_with_input ident nm
meta def parse_open_namespace (open_ns: string) : tactic (list name) :=
do lean.parser.run_with_input (many ident) open_ns
meta def handle_init_search
(req : LeanREPLRequest)
: LeanREPL LeanREPLResponse := do {
σ ← get,
-- Parse declaration name.
decl_name ← state_t.lift $ io.run_tactic'' $ do {
parse_theorem_name req.name
},
-- Parse open namespaces.
decl_open_ns ← state_t.lift $ io.run_tactic'' $ do {
parse_open_namespace req.open_ns
},
-- Check that the declaration is a theorem.
is_theorem ← state_t.lift $ io.run_tactic'' $ do {
tactic.is_theorem decl_name
} <|> pure ff,
match is_theorem with
-- The declaration is not a theorem, return an error.
| ff := do {
let err := format! "not_a_theorem: name={req.name} open_ns={req.open_ns}",
pure ⟨none, none, none, some err.to_string⟩
}
-- The declaration is a theorem, set the env with open namespaces to it and
-- generate a new tactic state.
| tt := do {
ts ← state_t.lift $ io.run_tactic'' $ do {
env ← tactic.get_env,
decl ← env.get decl_name,
let g := decl.type,
tactic.set_goal_to g,
lean_file ← env.decl_olean decl_name,
tactic.set_env_core $ environment.for_decl_of_imported_module lean_file decl_name,
add_open_namespaces decl_open_ns,
tactic.read
},
let sid := σ.get_next_sid,
modify $ λ σ, σ.incr_next_sid,
tsid ← record_ts sid ts,
ts_str ← (state_t.lift ∘ io.run_tactic'') $ ts.fully_qualified >>= postprocess_tactic_state,
pure $ ⟨sid, tsid, ts_str, none⟩
}
end
}
meta def handle_clear_search
(req : LeanREPLRequest)
: LeanREPL LeanREPLResponse := do {
-- Simply remove the table associated with the provided search id from the state.
modify $ λ σ, σ.erase_search req.sid,
pure $ ⟨req.sid, none, none, none⟩
}
meta def finalize_proof
(req : LeanREPLRequest)
(ts': tactic_state) : LeanREPL LeanREPLResponse := do {
σ ← get,
-- Retrieve the tactic state at index 0 to extract the top-level goal metavariable.
match σ.get_ts req.sid "0" with
| none := do {
let err := format! "unexpected_unknown_tsid_0: search_id={req.sid}",
pure ⟨none, none, none, some err.to_string⟩
}
| (some ts₀) := do {
result ← (state_t.lift ∘ io.run_tactic'') $ do {
-- Set to tactic state index 0 to retrieve the meta-variable for the top goal.
tactic.write ts₀,
[g] ← tactic.get_goals,
tgt ← tactic.infer_type g,
tactic.write ts',
pf ← tactic.get_assignment g >>= tactic.instantiate_mvars,
tactic.capture' (validate_proof tgt pf)
},
match result with
| (interaction_monad.result.success r s') := do {
tsid ← record_ts req.sid ts',
ts_str ← (state_t.lift ∘ io.run_tactic'') $ ts'.fully_qualified >>= postprocess_tactic_state,
pure $ ⟨req.sid, tsid, ts_str, none⟩
}
| (interaction_monad.result.exception f p s') := do {
let msg := (f.get_or_else (λ _, format.of_string "n/a")) (),
let err := format! "proof_validation_failed: msg={msg}",
pure ⟨none, none, none, some err.to_string⟩
}
end
}
end
}
meta def handle_run_tac
(req : LeanREPLRequest)
: LeanREPL LeanREPLResponse := do {
σ ← get,
match (σ.get_ts req.sid req.tsid) with
-- Received an unknown search id, return an error.
| none := do {
let err := format! "unknown_id: search_id={req.sid} tactic_state_id={req.tsid}",
pure ⟨none, none, none, some err.to_string⟩
}
-- The tactic state was retrieved from the state.
| (some ts) := do {
-- Set the tactic state and try to apply the tactic.
result_with_string ← state_t.lift $ io.run_tactic'' $ do {
tactic.write ts,
get_tac_and_capture_result req.tac 5000 <|> do {
let msg : format := format!"parse_itactic failed on `{req.tac}`",
interaction_monad.mk_exception msg none <$> tactic.read
}
},
match result_with_string with
-- The tactic application was successful.
| interaction_monad.result.success _ ts' := do {
n ← (state_t.lift ∘ io.run_tactic'') $ do {
tactic.write ts',
tactic.num_goals
},
-- monad_lift $ io.run_tactic'' $ tactic.trace format! "REMAINING SUBGOALS: {n}",
match n with
-- There is no more subgoals, check that the produced proof is valid.
| 0 := do {
finalize_proof req ts'
}
-- There are remaining subgoals, return the updated tactic state.
| n := do {
tsid ← record_ts req.sid ts',
ts_str ← (state_t.lift ∘ io.run_tactic'') $ ts'.fully_qualified >>= postprocess_tactic_state,
pure $ ⟨req.sid, tsid, ts_str, none⟩
}
end
}
-- The tactic application failed, potentially return an error with the failure message.
| interaction_monad.result.exception fn pos ts' := do {
-- Some tactics such as linarith fail but result in a tactic state with no goals. Check if
-- that's the case and finalize the proof, otherwise error.
n ← (state_t.lift ∘ io.run_tactic'') $ do {
tactic.write ts',
tactic.num_goals
},
-- monad_lift $ io.run_tactic'' $ tactic.trace format! "REMAINING SUBGOALS: {n}",
match n with
-- There is no more subgoals, check that the produced proof is valid.
| 0 := do {
finalize_proof req ts'
}
-- There are remaining subgoals, return the error.
| _ := do {
state_t.lift $ do {
let msg := (fn.get_or_else (λ _, format.of_string "n/a")) (),
let err := format! "gen_tac_and_capture_res_failed: pos={pos} msg={msg}",
pure ⟨none, none, none, some err.to_string⟩
}
}
end
}
end
}
end
}
meta def handle_request (req : LeanREPLRequest) : LeanREPL LeanREPLResponse :=
match req.cmd with
| "run_tac" := handle_run_tac req
| "init_search" := handle_init_search req
| "clear_search" := handle_clear_search req
| exc := state_t.lift $ io.fail' format! "[fatal] unknown_command: cmd={exc}"
end
meta def parse_request (msg : string) : io LeanREPLRequest := do {
match json.parse msg with
| (some json_msg) := io.run_tactic'' $ has_from_json.from_json json_msg
| none := io.fail' format! "[fatal] parse_failed: data={msg}"
end
}
meta def loop : LeanREPL unit := do {
req ← (state_t.lift $ io.get_line >>= parse_request),
res ← handle_request req,
state_t.lift $ io.put_str_ln' $ format! "{(json.unparse ∘ LeanREPLResponse.to_json) res}"
}
meta def main : io unit := do {
state_t.run loop.forever ⟨dict.empty, 0⟩ $> ()
}
end main
|
2dff509f083d8218b1bf035d772e75f6bcb55dad
|
843cffbd2a25fd01677509247a92e9e8b33bec48
|
/5. Tactics.lean
|
2a92898fcb1c8f88f19f0a0aa66713085afe0b65
|
[] |
no_license
|
AlexandruBosinta/MyLeanPlayground
|
9a78eba4a5c7a2b82edf84e1794a966f53f06c4f
|
5dc50a590d784bfc27e7fb37b6361a6dcc1b2790
|
refs/heads/master
| 1,586,230,010,351
| 1,542,487,422,000
| 1,542,487,422,000
| 158,016,626
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 11,245
|
lean
|
--import tactic.finish
namespace Three
open classical
variables p q r s : Prop
-- commutativity of ∧ and ∨
example : p ∧ q ↔ q ∧ p := begin
split,
intro hpq,
split,
exact hpq.right,
exact hpq.left,
intro hqp,
split,
exact hqp.right,
exact hqp.left,
end
example : p ∨ q ↔ q ∨ p := begin
split,
intro hpq,
cases hpq with hp hq,
right, exact hp,
left, exact hq,
intro hqp,
cases hqp with hq hp,
right, exact hq,
left, exact hp
end
example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := begin
split,
intro h,
split,
exact h.left.left,
split,
exact h.left.right,
exact h.right,
intro h,
split,
split,
exact h.left,
exact h.right.left,
exact h.right.right
end
example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := begin
split,
intro h,
cases h with hpq hr,
cases hpq with hp hq,
left, exact hp,
right, left, exact hq,
right, right, exact hr,
intro h,
cases h with hp hqr,
left, left, exact hp,
cases hqr with hq hr,
left, right, exact hq,
right, exact hr
end
-- distributivity
example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := begin
split,
intro h,
cases h with hp hqr,
cases hqr with hq hr,
left,
split,
exact hp,
exact hq,
right,
split,
exact hp,
exact hr,
intro h,
cases h with hpq hpr,
cases hpq with hp hq,
split,
exact hp,
left, exact hq,
cases hpr with hp hr,
split,
exact hp,
right, exact hr
end
example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := begin
split,
intro h,
cases h with hp hqr,
split; {left, exact hp},
cases hqr with hq hr,
split; right, exact hq, exact hr,
intro h,
cases h with hpq hpr,
cases hpq with hp hq,
left, exact hp,
cases hpr with hp hr,
left, exact hp,
right, split, exact hq, exact hr
end
-- other properties
example : (p → (q → r)) ↔ (p ∧ q → r) := begin
split,
intros,
apply a,
exact a_1.left,
exact a_1.right,
intros,
apply a,
split,
exact a_1,
exact a_2
end
example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := begin
split,
intros,
split,
intros,
apply a,
exact or.intro_left q a_1,
intros,
apply a,
exact or.intro_right p a_1,
intros,
cases a, cases a_1,
exact a_left a_1,
exact a_right a_1
end
example : ¬(p ∨ q) ↔ ¬p ∧ ¬q := begin
split,
intros,
split,
intro hp,
exact a (or.intro_left q hp),
intro hq,
exact a (or.intro_right p hq),
intros,
intro hpq,
cases hpq,
exact a.left hpq,
exact a.right hpq
end
example : ¬p ∨ ¬q → ¬(p ∧ q) := begin
intros,
intro h,
cases a,
exact a h.left,
exact a h.right,
end
example : ¬(p ∧ ¬p) := begin
intro h,
exact h.right h.left
end
example : p ∧ ¬q → ¬(p → q) := begin
intros a h,
exact a.right (h a.left)
end
example : ¬p → (p → q) := begin
intros,
exact absurd a_1 a
end
example : (¬p ∨ q) → (p → q) := begin
intros,
cases a,
exact absurd a_1 a,
exact a
end
example : p ∨ false ↔ p := begin
split,
intros,
cases a,
exact a,
exact false.elim a,
intros,
left, exact a
end
example : p ∧ false ↔ false := begin
split,
intros,
exact a.right,
intros,
exact false.elim a
end
example : ¬(p ↔ ¬p) := begin
intro h,
cases h,
have hnp : ¬p, from begin
intro hp,
exact (h_mp hp) hp,
end,
exact hnp (h_mpr hnp)
end
example : (p → q) → (¬q → ¬p) := begin
intros, intro hp,
exact a_1 (a hp)
end
-- these require classical reasoning
example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := begin
intros,
cases (em p),
cases a h,
left, intro h, exact h_1,
right, intro h, exact h_1,
left,
intros,
exact absurd a_1 h
end
example : ¬(p ∧ q) → ¬p ∨ ¬q := begin
intros,
cases (em p); cases (em q),
exact absurd (and.intro h h_1) a,
right, exact h_1,
left, exact h,
left, exact h
end
example : ¬(p → q) → p ∧ ¬q := begin
intros,
cases (em p); cases (em q),
have hpq : p → q, from begin intros, exact h_1 end,
exact absurd hpq a,
split, exact h, exact h_1,
have hpq : p → q, from begin intros, exact h_1 end,
exact absurd hpq a,
have hpq : p → q, from begin intros, exact absurd a_1 h end,
exact absurd hpq a
end
example : (p → q) → (¬p ∨ q) := begin
intros,
cases (em p),
right, exact a h,
left, exact h,
end
example : (¬q → ¬p) → (p → q) := begin
intros,
cases (em q),
exact h,
exact absurd a_1 (a h)
end
example : p ∨ ¬p := begin
cases (em p), left, assumption,
right, assumption
end
example : (((p → q) → p) → p) := begin
intros,
apply classical.by_contradiction,
intros,
apply a_1, apply a,
intros,
exact absurd a_2 a_1
end
end Three
namespace Four
variables (α : Type) (p q : α → Prop)
example : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := begin
split,
intros,
split,
intros,
exact (a x).left,
intros,
exact (a x).right,
intros,
split,
exact a.left x,
exact a.right x
end
example : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) := begin
intros,
exact (a x) (a_1 x)
end
example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := begin
intros,
cases a,
left, exact a x,
right, exact a x
end
variable r : Prop
example : α → ((∀ x : α, r) ↔ r) := begin
intros,
split,
intros,
exact a_1 a,
intros,
exact a_1
end
open classical
example : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := begin
split,
intros,
cases (em r),
right, exact h,
left, intros,
cases a x,
exact h_1,
exact absurd h_1 h,
intros,
cases a,
left, exact a x,
right,
exact a
end
example : (∀ x, r → p x) ↔ (r → ∀ x, p x) := begin
split,
intros,
exact (a x) a_1,
intros,
exact (a a_1) x
end
variables (men : Type) (barber : men)
variable (shaves : men → men → Prop)
example (h : ∀ x : men, shaves barber x ↔ ¬ shaves x x) : false := begin
have h0 : ∀ (p : Prop), ¬(p ↔ ¬p), from begin
intros p h,
cases h,
have hnp : ¬p, from begin
intro hp,
exact (h_mp hp) hp,
end,
exact hnp (h_mpr hnp)
end,
exact (h0 (shaves barber barber)) (h barber)
end
namespace hidden
def divides (m n : ℕ) : Prop := ∃ k, m * k = n
instance : has_dvd nat := ⟨divides⟩
def even (n : ℕ) : Prop := 2 ∣ n
def prime (n : ℕ) : Prop := ∀ (a b : ℕ), a * b = n → (a = 1 ∨ b = 1)
def infinitely_many_primes : Prop := ∀ (n : ℕ), ∃ (p : ℕ), (n < p) ∧ (prime p)
def Fermat_prime (n : ℕ) : Prop := (prime n) ∧ (∃ (k : ℕ), n = 2 ^ k + 1)
def infinitely_many_Fermat_primes : Prop :=
∀ (n : ℕ), ∃ (p : ℕ), (n < p) ∧ (Fermat_prime p)
def goldbach_conjecture : Prop :=
∀ (n : ℕ), (even n) → (n > 2) → (∃ (p q : ℕ), (prime p) → (prime q) → n = p + q)
def Goldbach's_weak_conjecture : Prop :=
∀ (n : ℕ), (¬ (even n)) → (n > 5) → (∃ (p q r : ℕ),
(prime p) → (prime q) → (prime r) → n = p + q + r)
def Fermat's_last_theorem : Prop :=
∀ (n : ℕ), (n > 2) → (¬ (∃ (a b c : ℕ), a ^ n + b ^ n = c ^ n))
end hidden
end Four
open classical
variables (α : Type) (p q : α → Prop)
variable a : α
variable r : Prop
include a
example : (∃ x : α, r) → r := begin
intro h,
cases h,
exact h_h
end
example : r → (∃ x : α, r) := begin
intros,
apply exists.intro,
exact a, exact a_1
end
example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := begin
split,
intros,
split,
cases a_1,
apply exists.intro,
exact a_1_h.left,
cases a_1,
exact a_1_h.right,
intros,
cases a_1.left,
apply exists.intro,
split,
exact h,
exact a_1.right
end
example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := begin
split,
intros,
cases a_1,
cases a_1_h,
left,
apply exists.intro,
exact a_1_h,
right,
apply exists.intro,
exact a_1_h,
intros,
cases a_1,
cases a_1,
apply exists.intro,
left, exact a_1_h,
cases a_1,
apply exists.intro,
right,
exact a_1_h
end
example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := begin
split,
intros h1 h2,
cases h2 with a h,
exact h (h1 a),
intros h x,
apply by_contradiction,
intros,
have h0 : ∃ (x : α), ¬p x,
apply exists.intro,
exact a_1,
exact h h0
end
example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := begin
split,
intros h h1,
cases h with x h,
exact (h1 x) h,
intros,
apply by_contradiction,
intros,
have h2 : ∀ (x : α), ¬p x,
intros x hpx,
exact a_2 (begin apply exists.intro, exact hpx end),
exact a_1 h2
end
example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := begin
split,
intros h x hpx,
exact h (begin apply exists.intro, exact hpx end),
intros h h0,
cases h0,
exact (h h0_w) h0_h
end
example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := begin
split,
intros h,
apply by_contradiction,
intros h1,
have h2 : ∀ x, p x,
intro x,
apply by_contradiction,
intro hnp,
exact h1 (begin apply exists.intro, exact hnp end),
exact h h2,
intros h h0,
cases h,
exact h_h (h0 h_w)
end
example : (∀ x, p x → r) ↔ (∃ x, p x) → r := begin
split,
intros,
cases a_2,
exact (a_1 a_2_w) a_2_h,
intros,
apply a_1,
apply exists.intro,
exact a_2
end
example : (∃ x, p x → r) ↔ (∀ x, p x) → r := begin
split,
intros,
cases a_1,
exact a_1_h (a_2 a_1_w),
intros,
cases (em (∀ (x : α), p x)),
apply exists.intro,
intro hp,
exact a_1 h,
exact a,
apply by_contradiction,
intro h1,
have h2 : ∀ (x : α), p x,
intro x,
apply by_contradiction,
intro npx,
exact h1 (begin fapply exists.intro,
exact x,
intro hpx,
exact absurd hpx npx end),
exact h h2
end
example : (∃ x, r → p x) ↔ (r → ∃ x, p x) := begin
split,
intros,
cases a_1,
apply exists.intro,
exact a_1_h a_2,
intros,
cases (em r),
cases a_1 h,
apply exists.intro,
intro h,
exact h_1,
apply exists.intro,
intro hr,
exact absurd hr h,
exact a,
end
example (p q r : Prop) (hp : p) :
(p ∨ q ∨ r) ∧ (q ∨ p ∨ r) ∧ (q ∨ r ∨ p) :=
by {split, all_goals { try {split} },
repeat {{left, assumption} <|> right <|> assumption}}
|
b476d636f84edb4b6f5840a9e48722e409df7cd6
|
74addaa0e41490cbaf2abd313a764c96df57b05d
|
/Mathlib/category_theory/monoidal/types_auto.lean
|
247464a768a030187183e243235d685b0dce8ee7
|
[] |
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,123
|
lean
|
/-
Copyright (c) 2018 Michael Jendrusch. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Michael Jendrusch, Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.monoidal.of_chosen_finite_products
import Mathlib.category_theory.limits.shapes.finite_products
import Mathlib.category_theory.limits.shapes.types
import Mathlib.PostPort
universes u
namespace Mathlib
/-!
# The category of types is a symmetric monoidal category
-/
namespace category_theory.monoidal
protected instance types_monoidal : monoidal_category (Type u) :=
monoidal_of_chosen_finite_products limits.types.terminal_limit_cone
limits.types.binary_product_limit_cone
protected instance types_symmetric : symmetric_category (Type u) :=
symmetric_of_chosen_finite_products limits.types.terminal_limit_cone
limits.types.binary_product_limit_cone
@[simp] theorem tensor_apply {W : Type u} {X : Type u} {Y : Type u} {Z : Type u} (f : W ⟶ X)
(g : Y ⟶ Z) (p : W ⊗ Y) :
monoidal_category.tensor_hom f g p = (f (prod.fst p), g (prod.snd p)) :=
rfl
@[simp] theorem left_unitor_hom_apply {X : Type u} {x : X} {p : PUnit} : iso.hom λ_ (p, x) = x :=
rfl
@[simp] theorem left_unitor_inv_apply {X : Type u} {x : X} : iso.inv λ_ x = (PUnit.unit, x) := rfl
@[simp] theorem right_unitor_hom_apply {X : Type u} {x : X} {p : PUnit} : iso.hom ρ_ (x, p) = x :=
rfl
@[simp] theorem right_unitor_inv_apply {X : Type u} {x : X} : iso.inv ρ_ x = (x, PUnit.unit) := rfl
@[simp] theorem associator_hom_apply {X : Type u} {Y : Type u} {Z : Type u} {x : X} {y : Y}
{z : Z} : iso.hom α_ ((x, y), z) = (x, y, z) :=
rfl
@[simp] theorem associator_inv_apply {X : Type u} {Y : Type u} {Z : Type u} {x : X} {y : Y}
{z : Z} : iso.inv α_ (x, y, z) = ((x, y), z) :=
rfl
@[simp] theorem braiding_hom_apply {X : Type u} {Y : Type u} {x : X} {y : Y} :
iso.hom β_ (x, y) = (y, x) :=
rfl
@[simp] theorem braiding_inv_apply {X : Type u} {Y : Type u} {x : X} {y : Y} :
iso.inv β_ (y, x) = (x, y) :=
rfl
end Mathlib
|
b7a1e24bff3a256f5a74175a3179a55ca0e64cc1
|
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
|
/tests/lean/run/def5.lean
|
b4698d6a2d05eb0b40940df7b3047908fc972e7b
|
[
"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
| 178
|
lean
|
--
def fib : Nat → Nat
| 0 | 1 => 1
| n+2 => fib n + fib (n+1)
example : fib 0 = 1 := rfl
example : fib 1 = 1 := rfl
example (n : Nat) : fib (n+2) = fib n + fib (n+1) := rfl
|
11122a1f0d335b07cafe5ec2e6271825acf0ba17
|
8e381650eb2c1c5361be64ff97e47d956bf2ab9f
|
/src/spectrum_of_a_ring/strucutre_sheaf_stalks.lean
|
d200b02bfe5761842e0e6f9e08719ca1ee9bc1ee
|
[] |
no_license
|
alreadydone/lean-scheme
|
04c51ab08eca7ccf6c21344d45d202780fa667af
|
52d7624f57415eea27ed4dfa916cd94189221a1c
|
refs/heads/master
| 1,599,418,221,423
| 1,562,248,559,000
| 1,562,248,559,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 1,757
|
lean
|
/-
Stalks of the structure sheaf are local rings.
-/
import ring_theory.ideals
import to_mathlib.localization.local_rings
import to_mathlib.localization.localization_of_iso
import to_mathlib.localization.localization_alt
import spectrum_of_a_ring.structure_presheaf_stalks
import spectrum_of_a_ring.structure_sheaf
import spectrum_of_a_ring.structure_presheaf_stalks
import sheaves.stalk_of_rings
import sheaves.sheaf_of_rings_on_standard_basis
universe u
open localization_alt
noncomputable theory
variables {R : Type u} [comm_ring R]
variables (P : Spec R)
def ℱ := structure_sheaf R
def ℱP := stalk_of_rings ℱ.F P
--
instance ℱP.is_comm_ring : comm_ring (ℱP P) :=
by simp [ℱP]; by apply_instance
--
lemma structure_sheaf.stalk_local : is_local_ring (ℱP P) :=
begin
have Hbij := to_stalk_extension.bijective
(D_fs_standard_basis R)
(structure_presheaf_on_basis R)
(λ U BU OC, structure_presheaf_on_basis_is_sheaf_on_basis BU OC)
P,
haveI Hhom := to_stalk_extension.is_ring_hom
(D_fs_standard_basis R)
(structure_presheaf_on_basis R)
(λ U BU OC, structure_presheaf_on_basis_is_sheaf_on_basis BU OC)
P,
haveI Hhom2 := strucutre_presheaf_stalks.φP.is_ring_hom P,
have Hloc := strucutre_presheaf_stalks.stalk_local.localization P,
have Hloc' := is_localization_data.of_iso
(-P.1 : set R)
(strucutre_presheaf_stalks.φ P)
Hloc
(to_stalk_extension _ _ _ P)
Hbij
Hhom,
have : is_ring_hom (to_stalk_extension Bstd strucutre_presheaf_stalks.F _ P ∘ strucutre_presheaf_stalks.φ P),
apply is_ring_hom.comp (strucutre_presheaf_stalks.φ P) (to_stalk_extension _ _ _ P),
exact Hhom,
use is_local_ring.of_is_localization_data_at_prime P.2 Hloc',
end
|
e3385d59d0cd4f94573a254ba60fbcbf6073ee22
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/order/category/BoundedDistribLattice.lean
|
ecac2f1ba4af5d27cd0ac86b6bc03cf6666fcfa2
|
[
"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
| 3,721
|
lean
|
/-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import order.category.BoundedLattice
import order.category.DistribLattice
/-!
# The category of bounded distributive lattices
This defines `BoundedDistribLattice`, the category of bounded distributive lattices.
Note that this category is sometimes called [`DistLat`](https://ncatlab.org/nlab/show/DistLat) when
being a lattice is understood to entail having a bottom and a top element.
-/
universes u
open category_theory
/-- The category of bounded distributive lattices with bounded lattice morphisms. -/
structure BoundedDistribLattice :=
(to_DistribLattice : DistribLattice)
[is_bounded_order : bounded_order to_DistribLattice]
namespace BoundedDistribLattice
instance : has_coe_to_sort BoundedDistribLattice Type* := ⟨λ X, X.to_DistribLattice⟩
instance (X : BoundedDistribLattice) : distrib_lattice X := X.to_DistribLattice.str
attribute [instance] BoundedDistribLattice.is_bounded_order
/-- Construct a bundled `BoundedDistribLattice` from a `bounded_order` `distrib_lattice`. -/
def of (α : Type*) [distrib_lattice α] [bounded_order α] : BoundedDistribLattice := ⟨⟨α⟩⟩
@[simp] lemma coe_of (α : Type*) [distrib_lattice α] [bounded_order α] : ↥(of α) = α := rfl
instance : inhabited BoundedDistribLattice := ⟨of punit⟩
/-- Turn a `BoundedDistribLattice` into a `BoundedLattice` by forgetting it is distributive. -/
def to_BoundedLattice (X : BoundedDistribLattice) : BoundedLattice := BoundedLattice.of X
@[simp] lemma coe_to_BoundedLattice (X : BoundedDistribLattice) : ↥X.to_BoundedLattice = ↥X := rfl
instance : large_category.{u} BoundedDistribLattice := induced_category.category to_BoundedLattice
instance : concrete_category BoundedDistribLattice :=
induced_category.concrete_category to_BoundedLattice
instance has_forget_to_DistribLattice : has_forget₂ BoundedDistribLattice DistribLattice :=
{ forget₂ := { obj := λ X, ⟨X⟩, map := λ X Y, bounded_lattice_hom.to_lattice_hom } }
instance has_forget_to_BoundedLattice : has_forget₂ BoundedDistribLattice BoundedLattice :=
induced_category.has_forget₂ to_BoundedLattice
lemma forget_BoundedLattice_Lattice_eq_forget_DistribLattice_Lattice :
forget₂ BoundedDistribLattice BoundedLattice ⋙ forget₂ BoundedLattice Lattice =
forget₂ BoundedDistribLattice DistribLattice ⋙ forget₂ DistribLattice Lattice := rfl
/-- Constructs an equivalence between bounded distributive lattices from an order isomorphism
between them. -/
@[simps] def iso.mk {α β : BoundedDistribLattice.{u}} (e : α ≃o β) : α ≅ β :=
{ hom := (e : bounded_lattice_hom α β),
inv := (e.symm : bounded_lattice_hom β α),
hom_inv_id' := by { ext, exact e.symm_apply_apply _ },
inv_hom_id' := by { ext, exact e.apply_symm_apply _ } }
/-- `order_dual` as a functor. -/
@[simps] def dual : BoundedDistribLattice ⥤ BoundedDistribLattice :=
{ obj := λ X, of Xᵒᵈ, map := λ X Y, bounded_lattice_hom.dual }
/-- The equivalence between `BoundedDistribLattice` and itself induced by `order_dual` both ways. -/
@[simps functor inverse] def dual_equiv : BoundedDistribLattice ≌ BoundedDistribLattice :=
equivalence.mk dual dual
(nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl)
(nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl)
end BoundedDistribLattice
lemma BoundedDistribLattice_dual_comp_forget_to_DistribLattice :
BoundedDistribLattice.dual ⋙ forget₂ BoundedDistribLattice DistribLattice =
forget₂ BoundedDistribLattice DistribLattice ⋙ DistribLattice.dual := rfl
|
bfd160596ba049e02a9e9436f3d61db188933506
|
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
|
/stage0/src/Init/System/IO.lean
|
9553e435090df66028cf27f9130279763d87806d
|
[
"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
| 19,517
|
lean
|
/-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Luke Nelson, Jared Roesch, Leonardo de Moura, Sebastian Ullrich
-/
prelude
import Init.Control.EState
import Init.Control.Reader
import Init.Data.String
import Init.Data.ByteArray
import Init.System.IOError
import Init.System.FilePath
import Init.System.ST
import Init.Data.ToString.Macro
/-- Like https://hackage.haskell.org/package/ghc-Prim-0.5.2.0/docs/GHC-Prim.html#t:RealWorld.
Makes sure we never reorder `IO` operations.
TODO: mark opaque -/
def IO.RealWorld : Type := Unit
/- TODO(Leo): mark it as an opaque definition. Reason: prevent
functions defined in other modules from accessing `IO.RealWorld`.
We don't want action such as
```
def getWorld : IO (IO.RealWorld) := get
```
-/
def EIO (ε : Type) : Type → Type := EStateM ε IO.RealWorld
@[inline] def EIO.catchExceptions (x : EIO ε α) (h : ε → EIO Empty α) : EIO Empty α :=
fun s => match x s with
| EStateM.Result.ok a s => EStateM.Result.ok a s
| EStateM.Result.error ex s => h ex s
instance : Monad (EIO ε) := inferInstanceAs (Monad (EStateM ε IO.RealWorld))
instance : MonadFinally (EIO ε) := inferInstanceAs (MonadFinally (EStateM ε IO.RealWorld))
instance : MonadExceptOf ε (EIO ε) := inferInstanceAs (MonadExceptOf ε (EStateM ε IO.RealWorld))
instance : OrElse (EIO ε α) := ⟨MonadExcept.orelse⟩
instance [Inhabited ε] : Inhabited (EIO ε α) := inferInstanceAs (Inhabited (EStateM ε IO.RealWorld α))
open IO (Error) in
abbrev IO : Type → Type := EIO Error
@[inline] def EIO.toIO (f : ε → IO.Error) (x : EIO ε α) : IO α :=
x.adaptExcept f
@[inline] def EIO.toIO' (x : EIO ε α) : IO (Except ε α) :=
EIO.toIO (fun _ => unreachable!) (observing x)
@[inline] def IO.toEIO (f : IO.Error → ε) (x : IO α) : EIO ε α :=
x.adaptExcept f
/- After we inline `EState.run'`, the closed term `((), ())` is generated, where the second `()`
represents the "initial world". We don't want to cache this closed term. So, we disable
the "extract closed terms" optimization. -/
set_option compiler.extract_closed false in
@[inline] unsafe def unsafeEIO (fn : EIO ε α) : Except ε α :=
match fn.run () with
| EStateM.Result.ok a _ => Except.ok a
| EStateM.Result.error e _ => Except.error e
@[inline] unsafe def unsafeIO (fn : IO α) : Except IO.Error α :=
unsafeEIO fn
@[extern "lean_io_timeit"] constant timeit (msg : @& String) (fn : IO α) : IO α
@[extern "lean_io_allocprof"] constant allocprof (msg : @& String) (fn : IO α) : IO α
/- Programs can execute IO actions during initialization that occurs before
the `main` function is executed. The attribute `[init <action>]` specifies
which IO action is executed to set the value of an opaque constant.
The action `initializing` returns `true` iff it is invoked during initialization. -/
@[extern "lean_io_initializing"] constant IO.initializing : IO Bool
namespace IO
def ofExcept [ToString ε] (e : Except ε α) : IO α :=
match e with
| Except.ok a => pure a
| Except.error e => throw (IO.userError (toString e))
def lazyPure (fn : Unit → α) : IO α :=
pure (fn ())
/-- Monotonically increasing time since an unspecified past point in milliseconds. No relation to wall clock time. -/
@[extern "lean_io_mono_ms_now"] constant monoMsNow : IO Nat
def sleep (ms : UInt32) : IO Unit :=
-- TODO: add a proper primitive for IO.sleep
fun s => dbgSleep ms fun _ => EStateM.Result.ok () s
/--
Run `act` in a separate `Task`. This is similar to Haskell's [`unsafeInterleaveIO`](http://hackage.haskell.org/package/base-4.14.0.0/docs/System-IO-Unsafe.html#v:unsafeInterleaveIO),
except that the `Task` is started eagerly as usual. Thus pure accesses to the `Task` do not influence the impure `act`
computation.
Unlike with pure tasks created by `Task.mk`, tasks created by this function will be run even if the last reference
to the task is dropped. `act` should manually check for cancellation via `IO.checkCanceled` if it wants to react
to that. -/
@[extern "lean_io_as_task"]
constant asTask (act : IO α) (prio := Task.Priority.default) : IO (Task (Except IO.Error α))
/-- See `IO.asTask`. -/
@[extern "lean_io_map_task"]
constant mapTask (f : α → IO β) (t : Task α) (prio := Task.Priority.default) : IO (Task (Except IO.Error β))
/-- See `IO.asTask`. -/
@[extern "lean_io_bind_task"]
constant bindTask (t : Task α) (f : α → IO (Task (Except IO.Error β))) (prio := Task.Priority.default) : IO (Task (Except IO.Error β))
/-- Check if the task's cancellation flag has been set by calling `IO.cancel` or dropping the last reference to the task. -/
@[extern "lean_io_check_canceled"] constant checkCanceled : IO Bool
/-- Request cooperative cancellation of the task. The task must explicitly call `IO.checkCanceled` to react to the cancellation. -/
@[extern "lean_io_cancel"] constant cancel : @& Task α → IO Unit
/-- Check if the task has finished execution, at which point calling `Task.get` will return immediately. -/
@[extern "lean_io_has_finished"] constant hasFinished : @& Task α → IO Bool
/-- Wait for the task to finish, then return its result. -/
@[extern "lean_io_wait"] constant wait : Task α → IO α
/-- Wait until any of the tasks in the given list has finished, then return its result. -/
@[extern "lean_io_wait_any"] constant waitAny : @& List (Task α) → IO α
/-- Helper method for implementing "deterministic" timeouts. It is the numbe of "small" memory allocations performed by the current execution thread. -/
@[extern "lean_io_get_num_heartbeats"] constant getNumHeartbeats : EIO ε Nat
inductive FS.Mode where
| read | write | readWrite | append
constant FS.Handle : Type := Unit
/--
A pure-Lean abstraction of POSIX streams. We use `Stream`s for the standard streams stdin/stdout/stderr so we can
capture output of `#eval` commands into memory. -/
structure FS.Stream where
isEof : IO Bool
flush : IO Unit
read : USize → IO ByteArray
write : ByteArray → IO Unit
getLine : IO String
putStr : String → IO Unit
namespace Prim
open FS
@[extern "lean_get_stdin"] constant getStdin : IO FS.Stream
@[extern "lean_get_stdout"] constant getStdout : IO FS.Stream
@[extern "lean_get_stderr"] constant getStderr : IO FS.Stream
@[extern "lean_get_set_stdin"] constant setStdin : FS.Stream → IO FS.Stream
@[extern "lean_get_set_stdout"] constant setStdout : FS.Stream → IO FS.Stream
@[extern "lean_get_set_stderr"] constant setStderr : FS.Stream → IO FS.Stream
@[specialize] partial def iterate (a : α) (f : α → IO (Sum α β)) : IO β := do
let v ← f a
match v with
| Sum.inl a => iterate a f
| Sum.inr b => pure b
-- @[export lean_fopen_flags]
def fopenFlags (m : FS.Mode) (b : Bool) : String :=
let mode :=
match m with
| FS.Mode.read => "r"
| FS.Mode.write => "w"
| FS.Mode.readWrite => "r+"
| FS.Mode.append => "a" ;
let bin := if b then "b" else "t"
mode ++ bin
@[extern "lean_io_prim_handle_mk"] constant Handle.mk (s : @& String) (mode : @& String) : IO Handle
@[extern "lean_io_prim_handle_is_eof"] constant Handle.isEof (h : @& Handle) : IO Bool
@[extern "lean_io_prim_handle_flush"] constant Handle.flush (h : @& Handle) : IO Unit
@[extern "lean_io_prim_handle_read"] constant Handle.read (h : @& Handle) (bytes : USize) : IO ByteArray
@[extern "lean_io_prim_handle_write"] constant Handle.write (h : @& Handle) (buffer : @& ByteArray) : IO Unit
@[extern "lean_io_prim_handle_get_line"] constant Handle.getLine (h : @& Handle) : IO String
@[extern "lean_io_prim_handle_put_str"] constant Handle.putStr (h : @& Handle) (s : @& String) : IO Unit
@[extern "lean_io_getenv"] constant getEnv (var : @& String) : IO (Option String)
@[extern "lean_io_realpath"] constant realPath (fname : String) : IO String
@[extern "lean_io_is_dir"] constant isDir (fname : @& String) : IO Bool
@[extern "lean_io_file_exists"] constant fileExists (fname : @& String) : IO Bool
@[extern "lean_io_remove_file"] constant removeFile (fname : @& String) : IO Unit
@[extern "lean_io_app_dir"] constant appPath : IO String
@[extern "lean_io_current_dir"] constant currentDir : IO String
end Prim
namespace FS
variable [Monad m] [MonadLiftT IO m]
def Handle.mk (s : String) (Mode : Mode) (bin : Bool := true) : m Handle :=
liftM (Prim.Handle.mk s (Prim.fopenFlags Mode bin))
@[inline]
def withFile (fn : String) (mode : Mode) (f : Handle → m α) : m α :=
Handle.mk fn mode >>= f
/-- returns whether the end of the file has been reached while reading a file.
`h.isEof` returns true /after/ the first attempt at reading past the end of `h`.
Once `h.isEof` is true, the reading `h` raises `IO.Error.eof`.
-/
def Handle.isEof : Handle → m Bool := liftM ∘ Prim.Handle.isEof
def Handle.flush : Handle → m Unit := liftM ∘ Prim.Handle.flush
def Handle.read (h : Handle) (bytes : Nat) : m ByteArray := liftM (Prim.Handle.read h (USize.ofNat bytes))
def Handle.write (h : Handle) (s : ByteArray) : m Unit := liftM (Prim.Handle.write h s)
def Handle.getLine : Handle → m String := liftM ∘ Prim.Handle.getLine
def Handle.putStr (h : Handle) (s : String) : m Unit :=
liftM <| Prim.Handle.putStr h s
def Handle.putStrLn (h : Handle) (s : String) : m Unit :=
h.putStr (s.push '\n')
partial def Handle.readBinToEnd (h : Handle) : m ByteArray := do
let rec loop (acc : ByteArray) : m ByteArray := do
if ← h.isEof then
return acc
else
let buf ← h.read 1024
loop (acc ++ buf)
loop ByteArray.empty
partial def Handle.readToEnd (h : Handle) : m String := do
let rec read (s : String) := do
let line ← h.getLine
if line.length == 0 then pure s else read (s ++ line)
read ""
def readBinFile (fname : String) : m ByteArray := do
let h ← Handle.mk fname Mode.read true
h.readBinToEnd
def readFile (fname : String) : m String := do
let h ← Handle.mk fname Mode.read false
h.readToEnd
partial def lines (fname : String) : m (Array String) := do
let h ← Handle.mk fname Mode.read false
let rec read (lines : Array String) := do
let line ← h.getLine
if line.length == 0 then
pure lines
else if line.back == '\n' then
let line := line.dropRight 1
let line := if System.Platform.isWindows && line.back == '\x0d' then line.dropRight 1 else line
read <| lines.push line
else
pure <| lines.push line
read #[]
def writeBinFile (fname : String) (content : ByteArray) : m Unit := do
let h ← Handle.mk fname Mode.write true
h.write content
def writeFile (fname : String) (content : String) : m Unit := do
let h ← Handle.mk fname Mode.write false
h.putStr content
namespace Stream
def putStrLn (strm : FS.Stream) (s : String) : m Unit :=
liftM (strm.putStr (s.push '\n'))
end Stream
end FS
section
variable [Monad m] [MonadLiftT IO m]
def getStdin : m FS.Stream := liftM Prim.getStdin
def getStdout : m FS.Stream := liftM Prim.getStdout
def getStderr : m FS.Stream := liftM Prim.getStderr
/-- Replaces the stdin stream of the current thread and returns its previous value. -/
def setStdin : FS.Stream → m FS.Stream := liftM ∘ Prim.setStdin
/-- Replaces the stdout stream of the current thread and returns its previous value. -/
def setStdout : FS.Stream → m FS.Stream := liftM ∘ Prim.setStdout
/-- Replaces the stderr stream of the current thread and returns its previous value. -/
def setStderr : FS.Stream → m FS.Stream := liftM ∘ Prim.setStderr
def withStdin [MonadFinally m] (h : FS.Stream) (x : m α) : m α := do
let prev ← setStdin h
try x finally discard <| setStdin prev
def withStdout [MonadFinally m] (h : FS.Stream) (x : m α) : m α := do
let prev ← setStdout h
try
x
finally
discard <| setStdout prev
def withStderr [MonadFinally m] (h : FS.Stream) (x : m α) : m α := do
let prev ← setStderr h
try x finally discard <| setStderr prev
def print [ToString α] (s : α) : IO Unit := do
let out ← getStdout
out.putStr <| toString s
def println [ToString α] (s : α) : IO Unit :=
print ((toString s).push '\n')
def eprint [ToString α] (s : α) : IO Unit := do
let out ← getStderr
liftM <| out.putStr <| toString s
def eprintln [ToString α] (s : α) : IO Unit :=
eprint <| toString s |>.push '\n'
@[export lean_io_eprintln]
private def eprintlnAux (s : String) : IO Unit :=
eprintln s
def getEnv : String → m (Option String) := liftM ∘ Prim.getEnv
def realPath : String → m String := liftM ∘ Prim.realPath
def isDir : String → m Bool := liftM ∘ Prim.isDir
def fileExists : String → m Bool := liftM ∘ Prim.fileExists
def removeFile : String → m Unit := liftM ∘ Prim.removeFile
def appPath : m String := liftM Prim.appPath
def appDir : m String := do
let p ← appPath
realPath (System.FilePath.dirName p)
def currentDir : m String := liftM Prim.currentDir
end
namespace Process
inductive Stdio where
| piped
| inherit
| null
def Stdio.toHandleType : Stdio → Type
| Stdio.piped => FS.Handle
| Stdio.inherit => Unit
| Stdio.null => Unit
structure StdioConfig where
/- Configuration for the process' stdin handle. -/
stdin := Stdio.inherit
/- Configuration for the process' stdout handle. -/
stdout := Stdio.inherit
/- Configuration for the process' stderr handle. -/
stderr := Stdio.inherit
structure SpawnArgs extends StdioConfig where
/- Command name. -/
cmd : String
/- Arguments for the process -/
args : Array String := #[]
/- Working directory for the process. Inherit from current process if `none`. -/
cwd : Option String := none
/- Add or remove environment variables for the process. -/
env : Array (String × Option String) := #[]
-- TODO(Sebastian): constructor must be private
structure Child (cfg : StdioConfig) where
stdin : cfg.stdin.toHandleType
stdout : cfg.stdout.toHandleType
stderr : cfg.stderr.toHandleType
@[extern "lean_io_process_spawn"] constant spawn (args : SpawnArgs) : IO (Child args.toStdioConfig)
@[extern "lean_io_process_child_wait"] constant Child.wait {cfg : @& StdioConfig} : @& Child cfg → IO UInt32
structure Output where
exitCode : UInt32
stdout : String
stderr : String
/-- Run process to completion and capture output. -/
def output (args : SpawnArgs) : IO Output := do
let child ← spawn { args with stdout := Stdio.piped, stderr := Stdio.piped }
let stdout ← IO.asTask child.stdout.readToEnd Task.Priority.dedicated
let stderr ← child.stderr.readToEnd
let exitCode ← child.wait
let stdout ← IO.ofExcept stdout.get
pure { exitCode := exitCode, stdout := stdout, stderr := stderr }
/-- Run process to completion and return stdout on success. -/
def run (args : SpawnArgs) : IO String := do
let out ← output args
if out.exitCode != 0 then
throw <| IO.userError <| "process '" ++ args.cmd ++ "' exited with code " ++ toString out.exitCode;
pure out.stdout
end Process
structure AccessRight where
read : Bool := false
write : Bool := false
execution : Bool := false
def AccessRight.flags (acc : AccessRight) : UInt32 :=
let r : UInt32 := if acc.read then 0x4 else 0
let w : UInt32 := if acc.write then 0x2 else 0
let x : UInt32 := if acc.execution then 0x1 else 0
r.lor <| w.lor x
structure FileRight where
user : AccessRight := {}
group : AccessRight := {}
other : AccessRight := {}
def FileRight.flags (acc : FileRight) : UInt32 :=
let u : UInt32 := acc.user.flags.shiftLeft 6
let g : UInt32 := acc.group.flags.shiftLeft 3
let o : UInt32 := acc.other.flags
u.lor <| g.lor o
@[extern "lean_chmod"] constant Prim.setAccessRights (filename : @& String) (mode : UInt32) : IO Unit
def setAccessRights (filename : String) (mode : FileRight) : IO Unit :=
Prim.setAccessRights filename mode.flags
/- References -/
abbrev Ref (α : Type) := ST.Ref IO.RealWorld α
instance : MonadLift (ST IO.RealWorld) (EIO ε) := ⟨fun x s =>
match x s with
| EStateM.Result.ok a s => EStateM.Result.ok a s
| EStateM.Result.error ex _ => nomatch ex⟩
def mkRef [Monad m] [MonadLiftT (ST IO.RealWorld) m] (a : α) : m (IO.Ref α) :=
ST.mkRef a
namespace FS
namespace Stream
@[export lean_stream_of_handle]
def ofHandle (h : Handle) : Stream := {
isEof := Prim.Handle.isEof h,
flush := Prim.Handle.flush h,
read := Prim.Handle.read h,
write := Prim.Handle.write h,
getLine := Prim.Handle.getLine h,
putStr := Prim.Handle.putStr h,
}
structure Buffer where
data : ByteArray := ByteArray.empty
pos : Nat := 0
def ofBuffer (r : Ref Buffer) : Stream := {
isEof := do let b ← r.get; pure <| b.pos >= b.data.size,
flush := pure (),
read := fun n => r.modifyGet fun b =>
let data := b.data.extract b.pos (b.pos + n.toNat)
(data, { b with pos := b.pos + data.size }),
write := fun data => r.modify fun b =>
-- set `exact` to `false` so that repeatedly writing to the stream does not impose quadratic run time
{ b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size },
getLine := r.modifyGet fun b =>
let pos := match b.data.findIdx? (start := b.pos) fun u => u == 0 || u = '\n'.toNat.toUInt8 with
-- include '\n', but not '\0'
| some pos => if b.data.get! pos == 0 then pos else pos + 1
| none => b.data.size
(String.fromUTF8Unchecked <| b.data.extract b.pos pos, { b with pos := pos }),
putStr := fun s => r.modify fun b =>
let data := s.toUTF8
{ b with data := data.copySlice 0 b.data b.pos data.size false, pos := b.pos + data.size },
}
end Stream
/-- Run action with `stdin` emptied and `stdout+stderr` captured into a `String`. -/
def withIsolatedStreams (x : IO α) : IO (String × Except IO.Error α) := do
let bIn ← mkRef { : Stream.Buffer }
let bOut ← mkRef { : Stream.Buffer }
let r ← withStdin (Stream.ofBuffer bIn) <|
withStdout (Stream.ofBuffer bOut) <|
withStderr (Stream.ofBuffer bOut) <|
observing x
let bOut ← bOut.get
let out := String.fromUTF8Unchecked bOut.data
pure (out, r)
end FS
end IO
universe u
namespace Lean
/-- Typeclass used for presenting the output of an `#eval` command. -/
class Eval (α : Type u) where
-- We default `hideUnit` to `true`, but set it to `false` in the direct call from `#eval`
-- so that `()` output is hidden in chained instances such as for some `m Unit`.
-- We take `Unit → α` instead of `α` because ‵α` may contain effectful debugging primitives (e.g., `dbgTrace!`)
eval : (Unit → α) → forall (hideUnit : optParam Bool true), IO Unit
instance [ToString α] : Eval α :=
⟨fun a _ => IO.println (toString (a ()))⟩
instance [Repr α] : Eval α :=
⟨fun a _ => IO.println (repr (a ()))⟩
instance : Eval Unit :=
⟨fun u hideUnit => if hideUnit then pure () else IO.println (repr (u ()))⟩
instance [Eval α] : Eval (IO α) :=
⟨fun x _ => do let a ← x (); Eval.eval (fun _ => a)⟩
@[noinline, nospecialize] def runEval [Eval α] (a : Unit → α) : IO (String × Except IO.Error Unit) :=
IO.FS.withIsolatedStreams (Eval.eval a false)
end Lean
syntax "println! " (interpolatedStr(term) <|> term) : term
macro_rules
| `(println! $msg) =>
if msg.getKind == Lean.interpolatedStrKind then
`((IO.println (s! $msg) : IO Unit))
else
`((IO.println $msg : IO Unit))
|
c60cd027b683cb5fe3d4551edb0b9d2c338ad2e3
|
35677d2df3f081738fa6b08138e03ee36bc33cad
|
/src/algebra/category/CommRing/limits.lean
|
0b672ed685a123e46012db15080e7429d58dcaf4
|
[
"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,081
|
lean
|
/-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.category.CommRing.basic
import category_theory.limits.types
import category_theory.limits.preserves
import ring_theory.subring
import algebra.pi_instances
/-!
# The category of commutative rings has all limits
Further, these limits are preserved by the forgetful functor --- that is,
the underlying types are just the limits in the category of types.
## Further work
A lot of this should be generalised / automated, as it's quite common for concrete
categories that the forgetful functor preserves limits.
-/
open category_theory
open category_theory.limits
universe u
namespace CommRing
variables {J : Type u} [small_category J]
instance comm_ring_obj (F : J ⥤ CommRing.{u}) (j) :
comm_ring ((F ⋙ forget CommRing).obj j) :=
by { change comm_ring (F.obj j), apply_instance }
instance sections_submonoid (F : J ⥤ CommRing.{u}) :
is_submonoid (F ⋙ forget CommRing).sections :=
{ one_mem := λ j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_one],
refl
end,
mul_mem := λ a b ah bh j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_mul],
dsimp [functor.sections] at ah,
rw ah f,
dsimp [functor.sections] at bh,
rw bh f,
refl,
end }
instance sections_add_submonoid (F : J ⥤ CommRing.{u}) :
is_add_submonoid (F ⋙ forget CommRing).sections :=
{ zero_mem := λ j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_zero],
refl,
end,
add_mem := λ a b ah bh j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_add],
dsimp [functor.sections] at ah,
rw ah f,
dsimp [functor.sections] at bh,
rw bh f,
refl,
end }
instance sections_add_subgroup (F : J ⥤ CommRing.{u}) :
is_add_subgroup (F ⋙ forget CommRing).sections :=
{ neg_mem := λ a ah j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_neg],
dsimp [functor.sections] at ah,
rw ah f,
refl,
end,
..(CommRing.sections_add_submonoid F) }
instance sections_subring (F : J ⥤ CommRing.{u}) :
is_subring (F ⋙ forget CommRing).sections :=
{ ..(CommRing.sections_submonoid F),
..(CommRing.sections_add_subgroup F) }
instance limit_comm_ring (F : J ⥤ CommRing.{u}) :
comm_ring (limit (F ⋙ forget CommRing)) :=
@subtype.comm_ring ((Π (j : J), (F ⋙ forget _).obj j)) (by apply_instance) _
(by convert (CommRing.sections_subring F))
/-- `limit.π (F ⋙ forget CommRing) j` as a `ring_hom`. -/
def limit_π_ring_hom (F : J ⥤ CommRing.{u}) (j) :
limit (F ⋙ forget CommRing) →+* (F ⋙ forget CommRing).obj j :=
{ to_fun := limit.π (F ⋙ forget CommRing) j,
map_one' := by { simp only [types.types_limit_π], refl },
map_zero' := by { simp only [types.types_limit_π], refl },
map_mul' := λ x y, by { simp only [types.types_limit_π], refl },
map_add' := λ x y, by { simp only [types.types_limit_π], refl } }
namespace CommRing_has_limits
-- The next two definitions are used in the construction of `has_limits CommRing`.
-- After that, the limits should be constructed using the generic limits API,
-- e.g. `limit F`, `limit.cone F`, and `limit.is_limit F`.
/--
Construction of a limit cone in `CommRing`.
(Internal use only; use the limits API.)
-/
def limit (F : J ⥤ CommRing.{u}) : cone F :=
{ X := ⟨limit (F ⋙ forget _), by apply_instance⟩,
π :=
{ app := limit_π_ring_hom F,
naturality' := λ j j' f,
ring_hom.coe_inj ((limit.cone (F ⋙ forget _)).π.naturality f) } }
/--
Witness that the limit cone in `CommRing` is a limit cone.
(Internal use only; use the limits API.)
-/
def limit_is_limit (F : J ⥤ CommRing.{u}) : is_limit (limit F) :=
begin
refine is_limit.of_faithful
(forget CommRing) (limit.is_limit _)
(λ s, ⟨_, _, _, _, _⟩) (λ s, rfl); dsimp,
{ apply subtype.eq, funext, dsimp,
erw (s.π.app j).map_one, refl },
{ intros x y, apply subtype.eq, funext, dsimp,
erw (s.π.app j).map_mul, refl },
{ apply subtype.eq, funext, dsimp,
erw (s.π.app j).map_zero, refl },
{ intros x y, apply subtype.eq, funext, dsimp,
erw (s.π.app j).map_add, refl }
end
end CommRing_has_limits
open CommRing_has_limits
/-- The category of commutative rings has all limits. -/
instance CommRing_has_limits : has_limits.{u} CommRing.{u} :=
{ has_limits_of_shape := λ J 𝒥,
{ has_limit := λ F, by exactI
{ cone := limit F,
is_limit := limit_is_limit F } } }
/--
The forgetful functor from commutative rings to types preserves all limits. (That is, the underlying
types could have been computed instead as limits in the category of types.)
-/
instance forget_preserves_limits : preserves_limits (forget CommRing.{u}) :=
{ preserves_limits_of_shape := λ J 𝒥,
{ preserves_limit := λ F,
by exactI preserves_limit_of_preserves_limit_cone
(limit.is_limit F) (limit.is_limit (F ⋙ forget _)) } }
end CommRing
|
a122fbce745189bf121504d61a685d706c5f1f33
|
74addaa0e41490cbaf2abd313a764c96df57b05d
|
/Mathlib/category_theory/monad/products.lean
|
3892166c71a90586a1d38fc2ee7f2aa2ed82b5a7
|
[] |
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
| 4,746
|
lean
|
/-
Copyright (c) 2021 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.over
import Mathlib.category_theory.limits.preserves.basic
import Mathlib.category_theory.limits.creates
import Mathlib.category_theory.limits.shapes.binary_products
import Mathlib.category_theory.monad.algebra
import Mathlib.PostPort
universes u v
namespace Mathlib
/-!
# Algebras for the coproduct monad
The functor `Y ↦ X ⨿ Y` forms a monad, whose category of monads is equivalent to the under category
of `X`. Similarly, `Y ↦ X ⨯ Y` forms a comonad, whose category of comonads is equivalent to the
over category of `X`.
## TODO
Show that `over.forget X : over X ⥤ C` is a comonadic left adjoint and `under.forget : under X ⥤ C`
is a monadic right adjoint.
-/
namespace category_theory
/-- `X ⨯ -` has a comonad structure. This is sometimes called the writer comonad. -/
protected instance obj.comonad {C : Type u} [category C] (X : C) [limits.has_binary_products C] : comonad (functor.obj limits.prod.functor X) :=
comonad.mk (nat_trans.mk fun (Y : C) => limits.prod.snd)
(nat_trans.mk fun (Y : C) => limits.prod.lift limits.prod.fst 𝟙)
/--
The forward direction of the equivalence from coalgebras for the product comonad to the over
category.
-/
def coalgebra_to_over {C : Type u} [category C] (X : C) [limits.has_binary_products C] : comonad.coalgebra (functor.obj limits.prod.functor X) ⥤ over X :=
functor.mk
(fun (A : comonad.coalgebra (functor.obj limits.prod.functor X)) => over.mk (comonad.coalgebra.a A ≫ limits.prod.fst))
fun (A₁ A₂ : comonad.coalgebra (functor.obj limits.prod.functor X)) (f : A₁ ⟶ A₂) =>
over.hom_mk (comonad.coalgebra.hom.f f)
/--
The backward direction of the equivalence from coalgebras for the product comonad to the over
category.
-/
@[simp] theorem over_to_coalgebra_map_f {C : Type u} [category C] (X : C) [limits.has_binary_products C] (f₁ : over X) (f₂ : over X) (g : f₁ ⟶ f₂) : comonad.coalgebra.hom.f (functor.map (over_to_coalgebra X) g) = comma_morphism.left g :=
Eq.refl (comonad.coalgebra.hom.f (functor.map (over_to_coalgebra X) g))
/-- The equivalence from coalgebras for the product comonad to the over category. -/
def coalgebra_equiv_over {C : Type u} [category C] (X : C) [limits.has_binary_products C] : comonad.coalgebra (functor.obj limits.prod.functor X) ≌ over X :=
equivalence.mk' (coalgebra_to_over X) (over_to_coalgebra X)
(nat_iso.of_components
(fun (A : comonad.coalgebra (functor.obj limits.prod.functor X)) =>
comonad.coalgebra.iso_mk (iso.refl (comonad.coalgebra.A (functor.obj 𝟭 A))) sorry)
sorry)
(nat_iso.of_components
(fun (f : over X) =>
over.iso_mk (iso.refl (comma.left (functor.obj (over_to_coalgebra X ⋙ coalgebra_to_over X) f))))
sorry)
/-- `X ⨿ -` has a monad structure. This is sometimes called the either monad. -/
@[simp] theorem obj.monad_μ_app {C : Type u} [category C] (X : C) [limits.has_binary_coproducts C] (Y : C) : nat_trans.app μ_ Y = limits.coprod.desc limits.coprod.inl 𝟙 :=
Eq.refl (nat_trans.app μ_ Y)
/--
The forward direction of the equivalence from algebras for the coproduct monad to the under
category.
-/
def algebra_to_under {C : Type u} [category C] (X : C) [limits.has_binary_coproducts C] : monad.algebra (functor.obj limits.coprod.functor X) ⥤ under X :=
functor.mk
(fun (A : monad.algebra (functor.obj limits.coprod.functor X)) => under.mk (limits.coprod.inl ≫ monad.algebra.a A))
fun (A₁ A₂ : monad.algebra (functor.obj limits.coprod.functor X)) (f : A₁ ⟶ A₂) =>
under.hom_mk (monad.algebra.hom.f f)
/--
The backward direction of the equivalence from algebras for the coproduct monad to the under
category.
-/
@[simp] theorem under_to_algebra_obj_A {C : Type u} [category C] (X : C) [limits.has_binary_coproducts C] (f : under X) : monad.algebra.A (functor.obj (under_to_algebra X) f) = comma.right f :=
Eq.refl (monad.algebra.A (functor.obj (under_to_algebra X) f))
/--
The equivalence from algebras for the coproduct monad to the under category.
-/
@[simp] theorem algebra_equiv_under_unit_iso {C : Type u} [category C] (X : C) [limits.has_binary_coproducts C] : equivalence.unit_iso (algebra_equiv_under X) =
nat_iso.of_components
(fun (A : monad.algebra (functor.obj limits.coprod.functor X)) =>
monad.algebra.iso_mk (iso.refl (monad.algebra.A (functor.obj 𝟭 A))) (algebra_equiv_under._proof_1 X A))
(algebra_equiv_under._proof_2 X) :=
Eq.refl (equivalence.unit_iso (algebra_equiv_under X))
|
ea3b76defe460e7226629c700ddc35a4fe50b986
|
63abd62053d479eae5abf4951554e1064a4c45b4
|
/src/data/real/irrational.lean
|
cf7e6951bb56f9107b5caef39ac64dc16407694e
|
[
"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
| 9,185
|
lean
|
/-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Yury Kudryashov.
-/
import data.real.basic
import data.rat.sqrt
import ring_theory.int.basic
import data.polynomial.eval
import data.polynomial.degree
import tactic.interval_cases
/-!
# Irrational real numbers
In this file we define a predicate `irrational` on `ℝ`, prove that the `n`-th root of an integer
number is irrational if it is not integer, and that `sqrt q` is irrational if and only if
`rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q`.
We also provide dot-style constructors like `irrational.add_rat`, `irrational.rat_sub` etc.
-/
open rat real multiplicity
/-- A real number is irrational if it is not equal to any rational number. -/
def irrational (x : ℝ) := x ∉ set.range (coe : ℚ → ℝ)
lemma irrational_iff_ne_rational (x : ℝ) : irrational x ↔ ∀ a b : ℤ, x ≠ a / b :=
by simp only [irrational, rat.forall, cast_mk, not_exists, set.mem_range, cast_coe_int, cast_div,
eq_comm]
/-!
### Irrationality of roots of integer and rational numbers
-/
/-- If `x^n`, `n > 0`, is integer and is not the `n`-th power of an integer, then
`x` is irrational. -/
theorem irrational_nrt_of_notint_nrt {x : ℝ} (n : ℕ) (m : ℤ)
(hxr : x ^ n = m) (hv : ¬ ∃ y : ℤ, x = y) (hnpos : 0 < n) :
irrational x :=
begin
rintros ⟨⟨N, D, P, C⟩, rfl⟩,
rw [← cast_pow] at hxr,
have c1 : ((D : ℤ) : ℝ) ≠ 0,
{ rw [int.cast_ne_zero, int.coe_nat_ne_zero], exact ne_of_gt P },
have c2 : ((D : ℤ) : ℝ) ^ n ≠ 0 := pow_ne_zero _ c1,
rw [num_denom', cast_pow, cast_mk, div_pow, div_eq_iff_mul_eq c2,
← int.cast_pow, ← int.cast_pow, ← int.cast_mul, int.cast_inj] at hxr,
have hdivn : ↑D ^ n ∣ N ^ n := dvd.intro_left m hxr,
rw [← int.dvd_nat_abs, ← int.coe_nat_pow, int.coe_nat_dvd, int.nat_abs_pow,
nat.pow_dvd_pow_iff hnpos] at hdivn,
have hD : D = 1 := by rw [← nat.gcd_eq_right hdivn, C.gcd_eq_one],
subst D,
refine hv ⟨N, _⟩,
rw [num_denom', int.coe_nat_one, mk_eq_div, int.cast_one, div_one, cast_coe_int]
end
/-- If `x^n = m` is an integer and `n` does not divide the `multiplicity p m`, then `x`
is irrational. -/
theorem irrational_nrt_of_n_not_dvd_multiplicity {x : ℝ} (n : ℕ) {m : ℤ} (hm : m ≠ 0) (p : ℕ)
[hp : fact p.prime] (hxr : x ^ n = m)
(hv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.ne_one, hm⟩) % n ≠ 0) :
irrational x :=
begin
rcases nat.eq_zero_or_pos n with rfl | hnpos,
{ rw [eq_comm, pow_zero, ← int.cast_one, int.cast_inj] at hxr,
simpa [hxr, multiplicity.one_right (mt is_unit_iff_dvd_one.1
(mt int.coe_nat_dvd.1 hp.not_dvd_one)), nat.zero_mod] using hv },
refine irrational_nrt_of_notint_nrt _ _ hxr _ hnpos,
rintro ⟨y, rfl⟩,
rw [← int.cast_pow, int.cast_inj] at hxr, subst m,
have : y ≠ 0, { rintro rfl, rw zero_pow hnpos at hm, exact hm rfl },
erw [multiplicity.pow' (nat.prime_iff_prime_int.1 hp)
(finite_int_iff.2 ⟨hp.ne_one, this⟩), nat.mul_mod_right] at hv,
exact hv rfl
end
theorem irrational_sqrt_of_multiplicity_odd (m : ℤ) (hm : 0 < m)
(p : ℕ) [hp : fact p.prime]
(Hpv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.ne_one, (ne_of_lt hm).symm⟩) % 2 = 1) :
irrational (sqrt m) :=
@irrational_nrt_of_n_not_dvd_multiplicity _ 2 _ (ne.symm (ne_of_lt hm)) p hp
(sqr_sqrt (int.cast_nonneg.2 $ le_of_lt hm))
(by rw Hpv; exact one_ne_zero)
theorem nat.prime.irrational_sqrt {p : ℕ} (hp : nat.prime p) : irrational (sqrt p) :=
@irrational_sqrt_of_multiplicity_odd p (int.coe_nat_pos.2 hp.pos) p hp $
by simp [multiplicity_self (mt is_unit_iff_dvd_one.1 (mt int.coe_nat_dvd.1 hp.not_dvd_one) : _)];
refl
theorem irrational_sqrt_two : irrational (sqrt 2) :=
by simpa using nat.prime_two.irrational_sqrt
theorem irrational_sqrt_rat_iff (q : ℚ) : irrational (sqrt q) ↔
rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q :=
if H1 : rat.sqrt q * rat.sqrt q = q
then iff_of_false (not_not_intro ⟨rat.sqrt q,
by rw [← H1, cast_mul, sqrt_mul_self (cast_nonneg.2 $ rat.sqrt_nonneg q),
sqrt_eq, abs_of_nonneg (rat.sqrt_nonneg q)]⟩) (λ h, h.1 H1)
else if H2 : 0 ≤ q
then iff_of_true (λ ⟨r, hr⟩, H1 $ (exists_mul_self _).1 ⟨r,
by rwa [eq_comm, sqrt_eq_iff_mul_self_eq (cast_nonneg.2 H2), ← cast_mul, cast_inj] at hr;
rw [← hr]; exact real.sqrt_nonneg _⟩) ⟨H1, H2⟩
else iff_of_false (not_not_intro ⟨0,
by rw cast_zero; exact (sqrt_eq_zero_of_nonpos (rat.cast_nonpos.2 $ le_of_not_le H2)).symm⟩)
(λ h, H2 h.2)
instance (q : ℚ) : decidable (irrational (sqrt q)) :=
decidable_of_iff' _ (irrational_sqrt_rat_iff q)
/-!
### Adding/subtracting/multiplying by rational numbers
-/
lemma rat.not_irrational (q : ℚ) : ¬irrational q := λ h, h ⟨q, rfl⟩
namespace irrational
variables (q : ℚ) {x y : ℝ}
open_locale classical
theorem add_cases : irrational (x + y) → irrational x ∨ irrational y :=
begin
delta irrational,
contrapose!,
rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩,
exact ⟨rx + ry, cast_add rx ry⟩
end
theorem of_rat_add (h : irrational (q + x)) : irrational x :=
h.add_cases.elim (λ h, absurd h q.not_irrational) id
theorem rat_add (h : irrational x) : irrational (q + x) :=
of_rat_add (-q) $ by rwa [cast_neg, neg_add_cancel_left]
theorem of_add_rat : irrational (x + q) → irrational x :=
add_comm ↑q x ▸ of_rat_add q
theorem add_rat (h : irrational x) : irrational (x + q) :=
add_comm ↑q x ▸ h.rat_add q
theorem of_neg (h : irrational (-x)) : irrational x :=
λ ⟨q, hx⟩, h ⟨-q, by rw [cast_neg, hx]⟩
protected theorem neg (h : irrational x) : irrational (-x) :=
of_neg $ by rwa neg_neg
theorem sub_rat (h : irrational x) : irrational (x - q) :=
by simpa only [cast_neg] using h.add_rat (-q)
theorem rat_sub (h : irrational x) : irrational (q - x) :=
h.neg.rat_add q
theorem of_sub_rat (h : irrational (x - q)) : irrational x :=
of_add_rat (-q) $ by simpa only [cast_neg]
theorem of_rat_sub (h : irrational (q - x)) : irrational x :=
(h.of_rat_add _).of_neg
theorem mul_cases : irrational (x * y) → irrational x ∨ irrational y :=
begin
delta irrational,
contrapose!,
rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩,
exact ⟨rx * ry, cast_mul rx ry⟩
end
theorem of_mul_rat (h : irrational (x * q)) : irrational x :=
h.mul_cases.elim id (λ h, absurd h q.not_irrational)
theorem mul_rat (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (x * q) :=
of_mul_rat q⁻¹ $ by rwa [mul_assoc, ← cast_mul, mul_inv_cancel hq, cast_one, mul_one]
theorem of_rat_mul : irrational (q * x) → irrational x :=
mul_comm x q ▸ of_mul_rat q
theorem rat_mul (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (q * x) :=
mul_comm x q ▸ h.mul_rat hq
theorem of_mul_self (h : irrational (x * x)) : irrational x :=
h.mul_cases.elim id id
theorem of_inv (h : irrational x⁻¹) : irrational x :=
λ ⟨q, hq⟩, h $ hq ▸ ⟨q⁻¹, q.cast_inv⟩
protected theorem inv (h : irrational x) : irrational x⁻¹ :=
of_inv $ by rwa inv_inv'
theorem div_cases (h : irrational (x / y)) : irrational x ∨ irrational y :=
h.mul_cases.imp id of_inv
theorem of_rat_div (h : irrational (q / x)) : irrational x :=
(h.of_rat_mul q).of_inv
theorem of_one_div (h : irrational (1 / x)) : irrational x :=
of_rat_div 1 $ by rwa [cast_one]
theorem of_pow : ∀ n : ℕ, irrational (x^n) → irrational x
| 0 := λ h, (h ⟨1, cast_one⟩).elim
| (n+1) := λ h, h.mul_cases.elim id (of_pow n)
theorem of_fpow : ∀ m : ℤ, irrational (x^m) → irrational x
| (n:ℕ) := of_pow n
| -[1+n] := λ h, by { rw fpow_neg_succ_of_nat at h, exact h.of_inv.of_pow _ }
end irrational
section polynomial
open polynomial
variables (x : ℝ) (p : polynomial ℤ)
lemma one_lt_nat_degree_of_irrational_root (hx : irrational x) (p_nonzero : p ≠ 0)
(x_is_root : aeval x p = 0) : 1 < p.nat_degree :=
begin
by_contra rid,
rcases exists_eq_X_add_C_of_nat_degree_le_one (not_lt.1 rid) with ⟨a, b, rfl⟩, clear rid,
have : (a : ℝ) * x = -b, by simpa [eq_neg_iff_add_eq_zero] using x_is_root,
rcases em (a = 0) with (rfl|ha),
{ obtain rfl : b = 0, by simpa,
simpa using p_nonzero },
{ rw [mul_comm, ← eq_div_iff_mul_eq, eq_comm] at this,
refine hx ⟨-b / a, _⟩,
assumption_mod_cast, assumption_mod_cast }
end
end polynomial
section
variables {q : ℚ} {x : ℝ}
open irrational
@[simp] theorem irrational_rat_add_iff : irrational (q + x) ↔ irrational x :=
⟨of_rat_add q, rat_add q⟩
@[simp] theorem irrational_add_rat_iff : irrational (x + q) ↔ irrational x :=
⟨of_add_rat q, add_rat q⟩
@[simp] theorem irrational_rat_sub_iff : irrational (q - x) ↔ irrational x :=
⟨of_rat_sub q, rat_sub q⟩
@[simp] theorem irrational_sub_rat_iff : irrational (x - q) ↔ irrational x :=
⟨of_sub_rat q, sub_rat q⟩
@[simp] theorem irrational_neg_iff : irrational (-x) ↔ irrational x :=
⟨of_neg, irrational.neg⟩
@[simp] theorem irrational_inv_iff : irrational x⁻¹ ↔ irrational x :=
⟨of_inv, irrational.inv⟩
end
|
6fb191aaca49843c1a0196d3d3e3f666d6cdaeb7
|
bb31430994044506fa42fd667e2d556327e18dfe
|
/src/topology/algebra/order/field.lean
|
2b9eeecfab668f1f30511a6ea834e3a78ed897ea
|
[
"Apache-2.0"
] |
permissive
|
sgouezel/mathlib
|
0cb4e5335a2ba189fa7af96d83a377f83270e503
|
00638177efd1b2534fc5269363ebf42a7871df9a
|
refs/heads/master
| 1,674,527,483,042
| 1,673,665,568,000
| 1,673,665,568,000
| 119,598,202
| 0
| 0
| null | 1,517,348,647,000
| 1,517,348,646,000
| null |
UTF-8
|
Lean
| false
| false
| 16,435
|
lean
|
/-
Copyright (c) 2022 Benjamin Davidson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Benjamin Davidson, Devon Tuma, Eric Rodriguez, Oliver Nash
-/
import tactic.positivity
import topology.order.basic
import topology.algebra.field
/-!
# Topologies on linear ordered fields
-/
open set filter topological_space
open function
open order_dual (to_dual of_dual)
open_locale topological_space classical filter
variables {α β : Type*}
variables [linear_ordered_field α] [topological_space α] [order_topology α]
variables {l : filter β} {f g : β → α}
section continuous_mul
lemma mul_tendsto_nhds_zero_right (x : α) :
tendsto (uncurry ((*) : α → α → α)) (𝓝 0 ×ᶠ 𝓝 x) $ 𝓝 0 :=
begin
have hx : 0 < 2 * (1 + |x|) := by positivity,
rw ((nhds_basis_zero_abs_sub_lt α).prod $ nhds_basis_abs_sub_lt x).tendsto_iff
(nhds_basis_zero_abs_sub_lt α),
refine λ ε ε_pos, ⟨(ε/(2 * (1 + |x|)), 1), ⟨div_pos ε_pos hx, zero_lt_one⟩, _⟩,
suffices : ∀ (a b : α), |a| < ε / (2 * (1 + |x|)) → |b - x| < 1 → |a| * |b| < ε,
by simpa only [and_imp, prod.forall, mem_prod, ← abs_mul],
intros a b h h',
refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left _ (abs_nonneg a)) ((lt_div_iff hx).1 h),
calc |b| = |(b - x) + x| : by rw sub_add_cancel b x
... ≤ |b - x| + |x| : abs_add (b - x) x
... ≤ 2 * (1 + |x|) : by linarith,
end
lemma mul_tendsto_nhds_zero_left (x : α) :
tendsto (uncurry ((*) : α → α → α)) (𝓝 x ×ᶠ 𝓝 0) $ 𝓝 0 :=
begin
intros s hs,
have := mul_tendsto_nhds_zero_right x hs,
rw [filter.mem_map, mem_prod_iff] at this ⊢,
obtain ⟨U, hU, V, hV, h⟩ := this,
exact ⟨V, hV, U, hU, λ y hy, ((mul_comm y.2 y.1) ▸
h (⟨hy.2, hy.1⟩ : (prod.mk y.2 y.1) ∈ U ×ˢ V) : y.1 * y.2 ∈ s)⟩,
end
lemma nhds_eq_map_mul_left_nhds_one {x₀ : α} (hx₀ : x₀ ≠ 0) :
𝓝 x₀ = map (λ x, x₀*x) (𝓝 1) :=
begin
have hx₀' : 0 < |x₀| := abs_pos.2 hx₀,
refine filter.ext (λ t, _),
simp only [exists_prop, set_of_subset_set_of, (nhds_basis_abs_sub_lt x₀).mem_iff,
(nhds_basis_abs_sub_lt (1 : α)).mem_iff, filter.mem_map'],
refine ⟨λ h, _, λ h, _⟩,
{ obtain ⟨i, hi, hit⟩ := h,
refine ⟨i / (|x₀|), div_pos hi (abs_pos.2 hx₀), λ x hx, hit _⟩,
calc |x₀ * x - x₀| = |x₀ * (x - 1)| : congr_arg abs (by ring_nf)
... = |x₀| * |x - 1| : abs_mul x₀ (x - 1)
... < |x₀| * (i / |x₀|) : mul_lt_mul' le_rfl hx (by positivity) (abs_pos.2 hx₀)
... = |x₀| * i / |x₀| : by ring
... = i : mul_div_cancel_left i (λ h, hx₀ (abs_eq_zero.1 h)) },
{ obtain ⟨i, hi, hit⟩ := h,
refine ⟨i * |x₀|, mul_pos hi (abs_pos.2 hx₀), λ x hx, _⟩,
have : |x / x₀ - 1| < i,
calc |x / x₀ - 1| = |x / x₀ - x₀ / x₀| : (by rw div_self hx₀)
... = |(x - x₀) / x₀| : congr_arg abs (sub_div x x₀ x₀).symm
... = |x - x₀| / |x₀| : abs_div (x - x₀) x₀
... < i * |x₀| / |x₀| : div_lt_div_of_lt (abs_pos.2 hx₀) hx
... = i : by rw [← mul_div_assoc', div_self (ne_of_lt $ abs_pos.2 hx₀).symm, mul_one],
specialize hit (x / x₀) this,
rwa [mul_div_assoc', mul_div_cancel_left x hx₀] at hit }
end
lemma nhds_eq_map_mul_right_nhds_one {x₀ : α} (hx₀ : x₀ ≠ 0) :
𝓝 x₀ = map (λ x, x*x₀) (𝓝 1) :=
by simp_rw [mul_comm _ x₀, nhds_eq_map_mul_left_nhds_one hx₀]
lemma mul_tendsto_nhds_one_nhds_one :
tendsto (uncurry ((*) : α → α → α)) (𝓝 1 ×ᶠ 𝓝 1) $ 𝓝 1 :=
begin
rw ((nhds_basis_Ioo_pos (1 : α)).prod $ nhds_basis_Ioo_pos (1 : α)).tendsto_iff
(nhds_basis_Ioo_pos_of_pos (zero_lt_one : (0 : α) < 1)),
intros ε hε,
have hε' : 0 ≤ 1 - ε / 4 := by linarith,
have ε_pos : 0 < ε / 4 := by linarith,
have ε_pos' : 0 < ε / 2 := by linarith,
simp only [and_imp, prod.forall, mem_Ioo, function.uncurry_apply_pair, mem_prod, prod.exists],
refine ⟨ε/4, ε/4, ⟨ε_pos, ε_pos⟩, λ a b ha ha' hb hb', _⟩,
have ha0 : 0 ≤ a := le_trans hε' (le_of_lt ha),
have hb0 : 0 ≤ b := le_trans hε' (le_of_lt hb),
refine ⟨lt_of_le_of_lt _ (mul_lt_mul'' ha hb hε' hε'),
lt_of_lt_of_le (mul_lt_mul'' ha' hb' ha0 hb0) _⟩,
{ calc 1 - ε = 1 - ε / 2 - ε/2 : by ring_nf
... ≤ 1 - ε/2 - ε/2 + (ε/2)*(ε/2) : le_add_of_nonneg_right (by positivity)
... = (1 - ε/2) * (1 - ε/2) : by ring_nf
... ≤ (1 - ε/4) * (1 - ε/4) : mul_le_mul (by linarith) (by linarith) (by linarith) hε' },
{ calc (1 + ε/4) * (1 + ε/4) = 1 + ε/2 + (ε/4)*(ε/4) : by ring_nf
... = 1 + ε/2 + (ε * ε) / 16 : by ring_nf
... ≤ 1 + ε/2 + ε/2 : add_le_add_left (div_le_div (le_of_lt hε.1) (le_trans
((mul_le_mul_left hε.1).2 hε.2) (le_of_eq $ mul_one ε)) zero_lt_two (by linarith)) (1 + ε/2)
... ≤ 1 + ε : by ring_nf }
end
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_field.has_continuous_mul : has_continuous_mul α :=
⟨begin
rw continuous_iff_continuous_at,
rintro ⟨x₀, y₀⟩,
by_cases hx₀ : x₀ = 0,
{ rw [hx₀, continuous_at, zero_mul, nhds_prod_eq],
exact mul_tendsto_nhds_zero_right y₀ },
by_cases hy₀ : y₀ = 0,
{ rw [hy₀, continuous_at, mul_zero, nhds_prod_eq],
exact mul_tendsto_nhds_zero_left x₀ },
have hxy : x₀ * y₀ ≠ 0 := mul_ne_zero hx₀ hy₀,
have key : (λ p : α × α, x₀ * p.1 * (p.2 * y₀)) = ((λ x, x₀*x) ∘ (λ x, x*y₀)) ∘ (uncurry (*)),
{ ext p, simp [uncurry, mul_assoc] },
have key₂ : (λ x, x₀*x) ∘ (λ x, y₀*x) = λ x, (x₀ *y₀)*x,
{ ext x, simp },
calc map (uncurry (*)) (𝓝 (x₀, y₀))
= map (uncurry (*)) (𝓝 x₀ ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq
... = map (λ (p : α × α), x₀ * p.1 * (p.2 * y₀)) ((𝓝 1) ×ᶠ (𝓝 1))
: by rw [uncurry, nhds_eq_map_mul_left_nhds_one hx₀, nhds_eq_map_mul_right_nhds_one hy₀,
prod_map_map_eq, filter.map_map]
... = map ((λ x, x₀ * x) ∘ λ x, x * y₀) (map (uncurry (*)) (𝓝 1 ×ᶠ 𝓝 1))
: by rw [key, ← filter.map_map]
... ≤ map ((λ (x : α), x₀ * x) ∘ λ x, x * y₀) (𝓝 1) : map_mono (mul_tendsto_nhds_one_nhds_one)
... = 𝓝 (x₀*y₀) : by rw [← filter.map_map, ← nhds_eq_map_mul_right_nhds_one hy₀,
nhds_eq_map_mul_left_nhds_one hy₀, filter.map_map, key₂, ← nhds_eq_map_mul_left_nhds_one hxy],
end⟩
end continuous_mul
/-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to
a positive constant `C` then `f * g` tends to `at_top`. -/
lemma filter.tendsto.at_top_mul {C : α} (hC : 0 < C) (hf : tendsto f l at_top)
(hg : tendsto g l (𝓝 C)) :
tendsto (λ x, (f x * g x)) l at_top :=
begin
refine tendsto_at_top_mono' _ _ (hf.at_top_mul_const (half_pos hC)),
filter_upwards [hg.eventually (lt_mem_nhds (half_lt_self hC)),
hf.eventually (eventually_ge_at_top 0)] with x hg hf using mul_le_mul_of_nonneg_left hg.le hf,
end
/-- In a linearly ordered field with the order topology, if `f` tends to a positive constant `C` and
`g` tends to `at_top` then `f * g` tends to `at_top`. -/
lemma filter.tendsto.mul_at_top {C : α} (hC : 0 < C) (hf : tendsto f l (𝓝 C))
(hg : tendsto g l at_top) :
tendsto (λ x, (f x * g x)) l at_top :=
by simpa only [mul_comm] using hg.at_top_mul hC hf
/-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to
a negative constant `C` then `f * g` tends to `at_bot`. -/
lemma filter.tendsto.at_top_mul_neg {C : α} (hC : C < 0) (hf : tendsto f l at_top)
(hg : tendsto g l (𝓝 C)) :
tendsto (λ x, (f x * g x)) l at_bot :=
by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg]
using tendsto_neg_at_top_at_bot.comp (hf.at_top_mul (neg_pos.2 hC) hg.neg)
/-- In a linearly ordered field with the order topology, if `f` tends to a negative constant `C` and
`g` tends to `at_top` then `f * g` tends to `at_bot`. -/
lemma filter.tendsto.neg_mul_at_top {C : α} (hC : C < 0) (hf : tendsto f l (𝓝 C))
(hg : tendsto g l at_top) :
tendsto (λ x, (f x * g x)) l at_bot :=
by simpa only [mul_comm] using hg.at_top_mul_neg hC hf
/-- In a linearly ordered field with the order topology, if `f` tends to `at_bot` and `g` tends to
a positive constant `C` then `f * g` tends to `at_bot`. -/
lemma filter.tendsto.at_bot_mul {C : α} (hC : 0 < C) (hf : tendsto f l at_bot)
(hg : tendsto g l (𝓝 C)) :
tendsto (λ x, (f x * g x)) l at_bot :=
by simpa [(∘)]
using tendsto_neg_at_top_at_bot.comp ((tendsto_neg_at_bot_at_top.comp hf).at_top_mul hC hg)
/-- In a linearly ordered field with the order topology, if `f` tends to `at_bot` and `g` tends to
a negative constant `C` then `f * g` tends to `at_top`. -/
lemma filter.tendsto.at_bot_mul_neg {C : α} (hC : C < 0) (hf : tendsto f l at_bot)
(hg : tendsto g l (𝓝 C)) :
tendsto (λ x, (f x * g x)) l at_top :=
by simpa [(∘)]
using tendsto_neg_at_bot_at_top.comp ((tendsto_neg_at_bot_at_top.comp hf).at_top_mul_neg hC hg)
/-- In a linearly ordered field with the order topology, if `f` tends to a positive constant `C` and
`g` tends to `at_bot` then `f * g` tends to `at_bot`. -/
lemma filter.tendsto.mul_at_bot {C : α} (hC : 0 < C) (hf : tendsto f l (𝓝 C))
(hg : tendsto g l at_bot) :
tendsto (λ x, (f x * g x)) l at_bot :=
by simpa only [mul_comm] using hg.at_bot_mul hC hf
/-- In a linearly ordered field with the order topology, if `f` tends to a negative constant `C` and
`g` tends to `at_bot` then `f * g` tends to `at_top`. -/
lemma filter.tendsto.neg_mul_at_bot {C : α} (hC : C < 0) (hf : tendsto f l (𝓝 C))
(hg : tendsto g l at_bot) :
tendsto (λ x, (f x * g x)) l at_top :=
by simpa only [mul_comm] using hg.at_bot_mul_neg hC hf
/-- The function `x ↦ x⁻¹` tends to `+∞` on the right of `0`. -/
lemma tendsto_inv_zero_at_top : tendsto (λx:α, x⁻¹) (𝓝[>] (0:α)) at_top :=
begin
refine (at_top_basis' 1).tendsto_right_iff.2 (λ b hb, _),
have hb' : 0 < b := by positivity,
filter_upwards [Ioc_mem_nhds_within_Ioi ⟨le_rfl, inv_pos.2 hb'⟩]
with x hx using (le_inv hx.1 hb').1 hx.2,
end
/-- The function `r ↦ r⁻¹` tends to `0` on the right as `r → +∞`. -/
lemma tendsto_inv_at_top_zero' : tendsto (λr:α, r⁻¹) at_top (𝓝[>] (0:α)) :=
begin
refine (has_basis.tendsto_iff at_top_basis ⟨λ s, mem_nhds_within_Ioi_iff_exists_Ioc_subset⟩).2 _,
refine λ b hb, ⟨b⁻¹, trivial, λ x hx, _⟩,
have : 0 < x := lt_of_lt_of_le (inv_pos.2 hb) hx,
exact ⟨inv_pos.2 this, (inv_le this hb).2 hx⟩
end
lemma tendsto_inv_at_top_zero : tendsto (λr:α, r⁻¹) at_top (𝓝 0) :=
tendsto_inv_at_top_zero'.mono_right inf_le_left
lemma filter.tendsto.div_at_top [has_continuous_mul α] {f g : β → α} {l : filter β} {a : α}
(h : tendsto f l (𝓝 a)) (hg : tendsto g l at_top) : tendsto (λ x, f x / g x) l (𝓝 0) :=
by { simp only [div_eq_mul_inv], exact mul_zero a ▸ h.mul (tendsto_inv_at_top_zero.comp hg) }
lemma filter.tendsto.inv_tendsto_at_top (h : tendsto f l at_top) : tendsto (f⁻¹) l (𝓝 0) :=
tendsto_inv_at_top_zero.comp h
lemma filter.tendsto.inv_tendsto_zero (h : tendsto f l (𝓝[>] 0)) :
tendsto (f⁻¹) l at_top :=
tendsto_inv_zero_at_top.comp h
/-- The function `x^(-n)` tends to `0` at `+∞` for any positive natural `n`.
A version for positive real powers exists as `tendsto_rpow_neg_at_top`. -/
lemma tendsto_pow_neg_at_top {n : ℕ} (hn : n ≠ 0) : tendsto (λ x : α, x ^ (-(n:ℤ))) at_top (𝓝 0) :=
by simpa only [zpow_neg, zpow_coe_nat] using (@tendsto_pow_at_top α _ _ hn).inv_tendsto_at_top
lemma tendsto_zpow_at_top_zero {n : ℤ} (hn : n < 0) :
tendsto (λ x : α, x^n) at_top (𝓝 0) :=
begin
lift -n to ℕ using le_of_lt (neg_pos.mpr hn) with N,
rw [← neg_pos, ← h, nat.cast_pos] at hn,
simpa only [h, neg_neg] using tendsto_pow_neg_at_top hn.ne'
end
lemma tendsto_const_mul_zpow_at_top_zero {n : ℤ} {c : α} (hn : n < 0) :
tendsto (λ x, c * x ^ n) at_top (𝓝 0) :=
(mul_zero c) ▸ (filter.tendsto.const_mul c (tendsto_zpow_at_top_zero hn))
lemma tendsto_const_mul_pow_nhds_iff' {n : ℕ} {c d : α} :
tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔ (c = 0 ∨ n = 0) ∧ c = d :=
begin
rcases eq_or_ne n 0 with (rfl|hn),
{ simp [tendsto_const_nhds_iff] },
rcases lt_trichotomy c 0 with hc|rfl|hc,
{ have := tendsto_const_mul_pow_at_bot_iff.2 ⟨hn, hc⟩,
simp [not_tendsto_nhds_of_tendsto_at_bot this, hc.ne, hn] },
{ simp [tendsto_const_nhds_iff] },
{ have := tendsto_const_mul_pow_at_top_iff.2 ⟨hn, hc⟩,
simp [not_tendsto_nhds_of_tendsto_at_top this, hc.ne', hn] }
end
lemma tendsto_const_mul_pow_nhds_iff {n : ℕ} {c d : α} (hc : c ≠ 0) :
tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔ n = 0 ∧ c = d :=
by simp [tendsto_const_mul_pow_nhds_iff', hc]
lemma tendsto_const_mul_zpow_at_top_nhds_iff {n : ℤ} {c d : α} (hc : c ≠ 0) :
tendsto (λ x : α, c * x ^ n) at_top (𝓝 d) ↔ (n = 0 ∧ c = d) ∨ (n < 0 ∧ d = 0) :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ by_cases hn : 0 ≤ n,
{ lift n to ℕ using hn,
simp only [zpow_coe_nat] at h,
rw [tendsto_const_mul_pow_nhds_iff hc, ← int.coe_nat_eq_zero] at h,
exact or.inl h },
{ rw not_le at hn,
refine or.inr ⟨hn, tendsto_nhds_unique h (tendsto_const_mul_zpow_at_top_zero hn)⟩ } },
{ cases h,
{ simp only [h.left, h.right, zpow_zero, mul_one],
exact tendsto_const_nhds },
{ exact h.2.symm ▸ tendsto_const_mul_zpow_at_top_zero h.1} }
end
-- TODO: With a different proof, this could be possibly generalised to only require a
-- `linear_ordered_semifield` instance, which would also remove the need for the
-- `nnreal` instance of `has_continuous_inv₀`.
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_field.to_topological_division_ring : topological_division_ring α :=
{ continuous_at_inv₀ :=
begin
suffices : ∀ {x : α}, 0 < x → continuous_at has_inv.inv x,
{ intros x hx,
cases hx.symm.lt_or_lt,
{ exact this h },
convert (this $ neg_pos.mpr h).neg.comp continuous_neg.continuous_at,
ext,
simp [neg_inv] },
intros t ht,
rw [continuous_at,
(nhds_basis_Ioo_pos t).tendsto_iff $ nhds_basis_Ioo_pos_of_pos $ inv_pos.2 ht],
rintros ε ⟨hε : ε > 0, hεt : ε ≤ t⁻¹⟩,
refine ⟨min (t ^ 2 * ε / 2) (t / 2), by positivity, λ x h, _⟩,
have hx : t / 2 < x,
{ rw [set.mem_Ioo, sub_lt_comm, lt_min_iff] at h,
nlinarith },
have hx' : 0 < x := (half_pos ht).trans hx,
have aux : 0 < 2 / t ^ 2 := by positivity,
rw [set.mem_Ioo, ←sub_lt_iff_lt_add', sub_lt_comm, ←abs_sub_lt_iff] at h ⊢,
rw [inv_sub_inv ht.ne' hx'.ne', abs_div, div_eq_mul_inv],
suffices : |t * x|⁻¹ < 2 / t ^ 2,
{ rw [←abs_neg, neg_sub],
refine (mul_lt_mul'' h this (by positivity) (by positivity)).trans_le _,
rw [mul_comm, mul_min_of_nonneg _ _ aux.le],
apply min_le_of_left_le,
rw [←mul_div, ←mul_assoc, div_mul_cancel _ (sq_pos_of_pos ht).ne',
mul_div_cancel' ε two_ne_zero] },
refine inv_lt_of_inv_lt aux _,
rw [inv_div, abs_of_pos $ mul_pos ht hx', sq, ←mul_div_assoc'],
exact mul_lt_mul_of_pos_left hx ht
end }
lemma nhds_within_pos_comap_mul_left {x : α} (hx : 0 < x) :
comap (λ ε, x * ε) (𝓝[>] 0) = 𝓝[>] 0 :=
begin
suffices : ∀ {x : α} (hx : 0 < x), 𝓝[>] 0 ≤ comap (λ ε, x * ε) (𝓝[>] 0),
{ refine le_antisymm _ (this hx),
have hr : 𝓝[>] (0 : α) = ((𝓝[>] (0 : α)).comap (λ ε, x⁻¹ * ε)).comap (λ ε, x * ε),
{ simp [comap_comap, inv_mul_cancel hx.ne.symm, comap_id, one_mul_eq_id], },
conv_rhs { rw hr, },
rw comap_le_comap_iff (by convert univ_mem; exact (mul_left_surjective₀ hx.ne.symm).range_eq),
exact this (inv_pos.mpr hx), },
intros x hx,
convert nhds_within_le_comap (continuous_mul_left x).continuous_within_at,
{ exact (mul_zero _).symm, },
{ rw image_const_mul_Ioi_zero hx, },
end
lemma eventually_nhds_within_pos_mul_left {x : α} (hx : 0 < x)
{p : α → Prop} (h : ∀ᶠ ε in 𝓝[>] 0, p ε) : ∀ᶠ ε in 𝓝[>] 0, p (x * ε) :=
begin
convert h.comap (λ ε, x * ε),
exact (nhds_within_pos_comap_mul_left hx).symm,
end
|
bcfc07031c3d4604e8aeed096214f6976415c1ed
|
94e33a31faa76775069b071adea97e86e218a8ee
|
/src/number_theory/arithmetic_function.lean
|
b3eb74b4ab2311324beb2fea322b4ff4a17bb403
|
[
"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
| 37,260
|
lean
|
/-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import algebra.big_operators.ring
import number_theory.divisors
import data.nat.squarefree
import algebra.invertible
import data.nat.factorization.basic
/-!
# Arithmetic Functions and Dirichlet Convolution
This file defines arithmetic functions, which are functions from `ℕ` to a specified type that map 0
to 0. In the literature, they are often instead defined as functions from `ℕ+`. These arithmetic
functions are endowed with a multiplication, given by Dirichlet convolution, and pointwise addition,
to form the Dirichlet ring.
## Main Definitions
* `arithmetic_function R` consists of functions `f : ℕ → R` such that `f 0 = 0`.
* An arithmetic function `f` `is_multiplicative` when `x.coprime y → f (x * y) = f x * f y`.
* The pointwise operations `pmul` and `ppow` differ from the multiplication
and power instances on `arithmetic_function R`, which use Dirichlet multiplication.
* `ζ` is the arithmetic function such that `ζ x = 1` for `0 < x`.
* `σ k` is the arithmetic function such that `σ k x = ∑ y in divisors x, y ^ k` for `0 < x`.
* `pow k` is the arithmetic function such that `pow k x = x ^ k` for `0 < x`.
* `id` is the identity arithmetic function on `ℕ`.
* `ω n` is the number of distinct prime factors of `n`.
* `Ω n` is the number of prime factors of `n` counted with multiplicity.
* `μ` is the Möbius function (spelled `moebius` in code).
## Main Results
* Several forms of Möbius inversion:
* `sum_eq_iff_sum_mul_moebius_eq` for functions to a `comm_ring`
* `sum_eq_iff_sum_smul_moebius_eq` for functions to an `add_comm_group`
* `prod_eq_iff_prod_pow_moebius_eq` for functions to a `comm_group`
* `prod_eq_iff_prod_pow_moebius_eq_of_nonzero` for functions to a `comm_group_with_zero`
## Notation
The arithmetic functions `ζ` and `σ` have Greek letter names, which are localized notation in
the namespace `arithmetic_function`.
## Tags
arithmetic functions, dirichlet convolution, divisors
-/
open finset
open_locale big_operators
namespace nat
variable (R : Type*)
/-- An arithmetic function is a function from `ℕ` that maps 0 to 0. In the literature, they are
often instead defined as functions from `ℕ+`. Multiplication on `arithmetic_functions` is by
Dirichlet convolution. -/
@[derive [has_zero, inhabited]]
def arithmetic_function [has_zero R] := zero_hom ℕ R
variable {R}
namespace arithmetic_function
section has_zero
variable [has_zero R]
instance : has_coe_to_fun (arithmetic_function R) (λ _, ℕ → R) := zero_hom.has_coe_to_fun
@[simp] lemma to_fun_eq (f : arithmetic_function R) : f.to_fun = f := rfl
@[simp]
lemma map_zero {f : arithmetic_function R} : f 0 = 0 :=
zero_hom.map_zero' f
theorem coe_inj {f g : arithmetic_function R} : (f : ℕ → R) = g ↔ f = g :=
⟨λ h, zero_hom.coe_inj h, λ h, h ▸ rfl⟩
@[simp]
lemma zero_apply {x : ℕ} : (0 : arithmetic_function R) x = 0 :=
zero_hom.zero_apply x
@[ext] theorem ext ⦃f g : arithmetic_function R⦄ (h : ∀ x, f x = g x) : f = g :=
zero_hom.ext h
theorem ext_iff {f g : arithmetic_function R} : f = g ↔ ∀ x, f x = g x :=
zero_hom.ext_iff
section has_one
variable [has_one R]
instance : has_one (arithmetic_function R) := ⟨⟨λ x, ite (x = 1) 1 0, rfl⟩⟩
lemma one_apply {x : ℕ} : (1 : arithmetic_function R) x = ite (x = 1) 1 0 := rfl
@[simp] lemma one_one : (1 : arithmetic_function R) 1 = 1 := rfl
@[simp] lemma one_apply_ne {x : ℕ} (h : x ≠ 1) : (1 : arithmetic_function R) x = 0 := if_neg h
end has_one
end has_zero
instance nat_coe [add_monoid_with_one R] :
has_coe (arithmetic_function ℕ) (arithmetic_function R) :=
⟨λ f, ⟨↑(f : ℕ → ℕ), by { transitivity ↑(f 0), refl, simp }⟩⟩
@[simp]
lemma nat_coe_nat (f : arithmetic_function ℕ) :
(↑f : arithmetic_function ℕ) = f :=
ext $ λ _, cast_id _
@[simp]
lemma nat_coe_apply [add_monoid_with_one R] {f : arithmetic_function ℕ} {x : ℕ} :
(f : arithmetic_function R) x = f x := rfl
instance int_coe [add_group_with_one R] :
has_coe (arithmetic_function ℤ) (arithmetic_function R) :=
⟨λ f, ⟨↑(f : ℕ → ℤ), by { transitivity ↑(f 0), refl, simp }⟩⟩
@[simp]
lemma int_coe_int (f : arithmetic_function ℤ) :
(↑f : arithmetic_function ℤ) = f :=
ext $ λ _, int.cast_id _
@[simp]
lemma int_coe_apply [add_group_with_one R]
{f : arithmetic_function ℤ} {x : ℕ} :
(f : arithmetic_function R) x = f x := rfl
@[simp]
lemma coe_coe [add_group_with_one R] {f : arithmetic_function ℕ} :
((f : arithmetic_function ℤ) : arithmetic_function R) = f :=
by { ext, simp, }
@[simp] lemma nat_coe_one [add_monoid_with_one R] :
((1 : arithmetic_function ℕ) : arithmetic_function R) = 1 :=
by { ext n, simp [one_apply] }
@[simp] lemma int_coe_one [add_group_with_one R] :
((1 : arithmetic_function ℤ) : arithmetic_function R) = 1 :=
by { ext n, simp [one_apply] }
section add_monoid
variable [add_monoid R]
instance : has_add (arithmetic_function R) := ⟨λ f g, ⟨λ n, f n + g n, by simp⟩⟩
@[simp]
lemma add_apply {f g : arithmetic_function R} {n : ℕ} : (f + g) n = f n + g n := rfl
instance : add_monoid (arithmetic_function R) :=
{ add_assoc := λ _ _ _, ext (λ _, add_assoc _ _ _),
zero_add := λ _, ext (λ _, zero_add _),
add_zero := λ _, ext (λ _, add_zero _),
.. arithmetic_function.has_zero R,
.. arithmetic_function.has_add }
end add_monoid
instance [add_monoid_with_one R] : add_monoid_with_one (arithmetic_function R) :=
{ nat_cast := λ n, ⟨λ x, if x = 1 then (n : R) else 0, by simp⟩,
nat_cast_zero := by ext; simp [nat.cast],
nat_cast_succ := λ _, by ext; by_cases x = 1; simp [nat.cast, *],
.. arithmetic_function.add_monoid, .. arithmetic_function.has_one }
instance [add_comm_monoid R] : add_comm_monoid (arithmetic_function R) :=
{ add_comm := λ _ _, ext (λ _, add_comm _ _),
.. arithmetic_function.add_monoid }
instance [add_group R] : add_group (arithmetic_function R) :=
{ neg := λ f, ⟨λ n, - f n, by simp⟩,
add_left_neg := λ _, ext (λ _, add_left_neg _),
.. arithmetic_function.add_monoid }
instance [add_comm_group R] : add_comm_group (arithmetic_function R) :=
{ .. arithmetic_function.add_comm_monoid,
.. arithmetic_function.add_group }
section has_smul
variables {M : Type*} [has_zero R] [add_comm_monoid M] [has_smul R M]
/-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function
such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/
instance : has_smul (arithmetic_function R) (arithmetic_function M) :=
⟨λ f g, ⟨λ n, ∑ x in divisors_antidiagonal n, f x.fst • g x.snd, by simp⟩⟩
@[simp]
lemma smul_apply {f : arithmetic_function R} {g : arithmetic_function M} {n : ℕ} :
(f • g) n = ∑ x in divisors_antidiagonal n, f x.fst • g x.snd := rfl
end has_smul
/-- The Dirichlet convolution of two arithmetic functions `f` and `g` is another arithmetic function
such that `(f * g) n` is the sum of `f x * g y` over all `(x,y)` such that `x * y = n`. -/
instance [semiring R] : has_mul (arithmetic_function R) := ⟨(•)⟩
@[simp]
lemma mul_apply [semiring R] {f g : arithmetic_function R} {n : ℕ} :
(f * g) n = ∑ x in divisors_antidiagonal n, f x.fst * g x.snd := rfl
lemma mul_apply_one [semiring R] {f g : arithmetic_function R} :
(f * g) 1 = f 1 * g 1 :=
by simp
@[simp, norm_cast] lemma nat_coe_mul [semiring R] {f g : arithmetic_function ℕ} :
(↑(f * g) : arithmetic_function R) = f * g :=
by { ext n, simp }
@[simp, norm_cast] lemma int_coe_mul [ring R] {f g : arithmetic_function ℤ} :
(↑(f * g) : arithmetic_function R) = f * g :=
by { ext n, simp }
section module
variables {M : Type*} [semiring R] [add_comm_monoid M] [module R M]
lemma mul_smul' (f g : arithmetic_function R) (h : arithmetic_function M) :
(f * g) • h = f • g • h :=
begin
ext n,
simp only [mul_apply, smul_apply, sum_smul, mul_smul, smul_sum, finset.sum_sigma'],
apply finset.sum_bij,
swap 5,
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l*j), (l, j)⟩ },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H,
simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢,
rcases H with ⟨⟨rfl, n0⟩, rfl, i0⟩,
refine ⟨⟨(mul_assoc _ _ _).symm, n0⟩, rfl, _⟩,
rw mul_ne_zero_iff at *,
exact ⟨i0.2, n0.2⟩, },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [mul_assoc] },
{ rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂,
simp only [finset.mem_sigma, mem_divisors_antidiagonal,
and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢,
rintros rfl h2 rfl rfl,
exact ⟨⟨eq.trans H₁.2.1.symm H₂.2.1, rfl⟩, rfl, rfl⟩ },
{ rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i*k, l), (i, k)⟩, _, _⟩,
{ simp only [finset.mem_sigma, mem_divisors_antidiagonal] at H ⊢,
rcases H with ⟨⟨rfl, n0⟩, rfl, j0⟩,
refine ⟨⟨mul_assoc _ _ _, n0⟩, rfl, _⟩,
rw mul_ne_zero_iff at *,
exact ⟨n0.1, j0.1⟩ },
{ simp only [true_and, mem_divisors_antidiagonal, and_true, prod.mk.inj_iff, eq_self_iff_true,
ne.def, mem_sigma, heq_iff_eq] at H ⊢,
rw H.2.1 } }
end
lemma one_smul' (b : arithmetic_function M) :
(1 : arithmetic_function R) • b = b :=
begin
ext,
rw smul_apply,
by_cases x0 : x = 0, {simp [x0]},
have h : {(1,x)} ⊆ divisors_antidiagonal x := by simp [x0],
rw ← sum_subset h, {simp},
intros y ymem ynmem,
have y1ne : y.fst ≠ 1,
{ intro con,
simp only [con, mem_divisors_antidiagonal, one_mul, ne.def] at ymem,
simp only [mem_singleton, prod.ext_iff] at ynmem,
tauto },
simp [y1ne],
end
end module
section semiring
variable [semiring R]
instance : monoid (arithmetic_function R) :=
{ one_mul := one_smul',
mul_one := λ f,
begin
ext,
rw mul_apply,
by_cases x0 : x = 0, {simp [x0]},
have h : {(x,1)} ⊆ divisors_antidiagonal x := by simp [x0],
rw ← sum_subset h, {simp},
intros y ymem ynmem,
have y2ne : y.snd ≠ 1,
{ intro con,
simp only [con, mem_divisors_antidiagonal, mul_one, ne.def] at ymem,
simp only [mem_singleton, prod.ext_iff] at ynmem,
tauto },
simp [y2ne],
end,
mul_assoc := mul_smul',
.. arithmetic_function.has_one,
.. arithmetic_function.has_mul }
instance : semiring (arithmetic_function R) :=
{ zero_mul := λ f, by { ext, simp only [mul_apply, zero_mul, sum_const_zero, zero_apply] },
mul_zero := λ f, by { ext, simp only [mul_apply, sum_const_zero, mul_zero, zero_apply] },
left_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, mul_add, mul_apply, add_apply] },
right_distrib := λ a b c, by { ext, simp only [←sum_add_distrib, add_mul, mul_apply, add_apply] },
.. arithmetic_function.has_zero R,
.. arithmetic_function.has_mul,
.. arithmetic_function.has_add,
.. arithmetic_function.add_comm_monoid,
.. arithmetic_function.add_monoid_with_one,
.. arithmetic_function.monoid }
end semiring
instance [comm_semiring R] : comm_semiring (arithmetic_function R) :=
{ mul_comm := λ f g, by { ext,
rw [mul_apply, ← map_swap_divisors_antidiagonal, sum_map],
simp [mul_comm] },
.. arithmetic_function.semiring }
instance [comm_ring R] : comm_ring (arithmetic_function R) :=
{ .. arithmetic_function.add_comm_group,
.. arithmetic_function.comm_semiring }
instance {M : Type*} [semiring R] [add_comm_monoid M] [module R M] :
module (arithmetic_function R) (arithmetic_function M) :=
{ one_smul := one_smul',
mul_smul := mul_smul',
smul_add := λ r x y, by { ext, simp only [sum_add_distrib, smul_add, smul_apply, add_apply] },
smul_zero := λ r, by { ext, simp only [smul_apply, sum_const_zero, smul_zero, zero_apply] },
add_smul := λ r s x, by { ext, simp only [add_smul, sum_add_distrib, smul_apply, add_apply] },
zero_smul := λ r, by { ext, simp only [smul_apply, sum_const_zero, zero_smul, zero_apply] }, }
section zeta
/-- `ζ 0 = 0`, otherwise `ζ x = 1`. The Dirichlet Series is the Riemann ζ. -/
def zeta : arithmetic_function ℕ :=
⟨λ x, ite (x = 0) 0 1, rfl⟩
localized "notation `ζ` := nat.arithmetic_function.zeta" in arithmetic_function
@[simp]
lemma zeta_apply {x : ℕ} : ζ x = if (x = 0) then 0 else 1 := rfl
lemma zeta_apply_ne {x : ℕ} (h : x ≠ 0) : ζ x = 1 := if_neg h
@[simp]
theorem coe_zeta_mul_apply [semiring R] {f : arithmetic_function R} {x : ℕ} :
(↑ζ * f) x = ∑ i in divisors x, f i :=
begin
rw mul_apply,
transitivity ∑ i in divisors_antidiagonal x, f i.snd,
{ apply sum_congr rfl,
intros i hi,
rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩,
rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_mul] },
{ apply sum_bij (λ i h, prod.snd i),
{ rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] },
{ rintros ⟨a, b⟩ h, refl },
{ rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h,
dsimp at h,
rw h at *,
rw mem_divisors_antidiagonal at *,
ext, swap, {refl},
simp only [prod.fst, prod.snd] at *,
apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm),
rcases h1 with ⟨rfl, h⟩,
apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) },
{ intros a ha,
rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩,
use (b, a),
simp [ne0, mul_comm] } }
end
theorem coe_zeta_smul_apply {M : Type*} [comm_ring R] [add_comm_group M] [module R M]
{f : arithmetic_function M} {x : ℕ} :
((↑ζ : arithmetic_function R) • f) x = ∑ i in divisors x, f i :=
begin
rw smul_apply,
transitivity ∑ i in divisors_antidiagonal x, f i.snd,
{ apply sum_congr rfl,
intros i hi,
rcases mem_divisors_antidiagonal.1 hi with ⟨rfl, h⟩,
rw [nat_coe_apply, zeta_apply_ne (left_ne_zero_of_mul h), cast_one, one_smul] },
{ apply sum_bij (λ i h, prod.snd i),
{ rintros ⟨a, b⟩ h, simp [snd_mem_divisors_of_mem_antidiagonal h] },
{ rintros ⟨a, b⟩ h, refl },
{ rintros ⟨a1, b1⟩ ⟨a2, b2⟩ h1 h2 h,
dsimp at h,
rw h at *,
rw mem_divisors_antidiagonal at *,
ext, swap, {refl},
simp only [prod.fst, prod.snd] at *,
apply nat.eq_of_mul_eq_mul_right _ (eq.trans h1.1 h2.1.symm),
rcases h1 with ⟨rfl, h⟩,
apply nat.pos_of_ne_zero (right_ne_zero_of_mul h) },
{ intros a ha,
rcases mem_divisors.1 ha with ⟨⟨b, rfl⟩, ne0⟩,
use (b, a),
simp [ne0, mul_comm] } }
end
@[simp]
theorem coe_mul_zeta_apply [semiring R] {f : arithmetic_function R} {x : ℕ} :
(f * ζ) x = ∑ i in divisors x, f i :=
begin
apply mul_opposite.op_injective,
rw [op_sum],
convert @coe_zeta_mul_apply Rᵐᵒᵖ _ { to_fun := mul_opposite.op ∘ f, map_zero' := by simp} x,
rw [mul_apply, mul_apply, op_sum],
conv_lhs { rw ← map_swap_divisors_antidiagonal, },
rw sum_map,
apply sum_congr rfl,
intros y hy,
by_cases h1 : y.fst = 0,
{ simp [function.comp_apply, h1] },
{ simp only [h1, mul_one, one_mul, prod.fst_swap, function.embedding.coe_fn_mk, prod.snd_swap,
if_false, zeta_apply, zero_hom.coe_mk, nat_coe_apply, cast_one] }
end
theorem zeta_mul_apply {f : arithmetic_function ℕ} {x : ℕ} :
(ζ * f) x = ∑ i in divisors x, f i :=
by rw [← nat_coe_nat ζ, coe_zeta_mul_apply]
theorem mul_zeta_apply {f : arithmetic_function ℕ} {x : ℕ} :
(f * ζ) x = ∑ i in divisors x, f i :=
by rw [← nat_coe_nat ζ, coe_mul_zeta_apply]
end zeta
open_locale arithmetic_function
section pmul
/-- This is the pointwise product of `arithmetic_function`s. -/
def pmul [mul_zero_class R] (f g : arithmetic_function R) :
arithmetic_function R :=
⟨λ x, f x * g x, by simp⟩
@[simp]
lemma pmul_apply [mul_zero_class R] {f g : arithmetic_function R} {x : ℕ} :
f.pmul g x = f x * g x := rfl
lemma pmul_comm [comm_monoid_with_zero R] (f g : arithmetic_function R) :
f.pmul g = g.pmul f :=
by { ext, simp [mul_comm] }
section non_assoc_semiring
variable [non_assoc_semiring R]
@[simp]
lemma pmul_zeta (f : arithmetic_function R) : f.pmul ↑ζ = f :=
begin
ext x,
cases x;
simp [nat.succ_ne_zero],
end
@[simp]
lemma zeta_pmul (f : arithmetic_function R) : (ζ : arithmetic_function R).pmul f = f :=
begin
ext x,
cases x;
simp [nat.succ_ne_zero],
end
end non_assoc_semiring
variables [semiring R]
/-- This is the pointwise power of `arithmetic_function`s. -/
def ppow (f : arithmetic_function R) (k : ℕ) :
arithmetic_function R :=
if h0 : k = 0 then ζ else ⟨λ x, (f x) ^ k,
by { rw [map_zero], exact zero_pow (nat.pos_of_ne_zero h0) }⟩
@[simp]
lemma ppow_zero {f : arithmetic_function R} : f.ppow 0 = ζ :=
by rw [ppow, dif_pos rfl]
@[simp]
lemma ppow_apply {f : arithmetic_function R} {k x : ℕ} (kpos : 0 < k) :
f.ppow k x = (f x) ^ k :=
by { rw [ppow, dif_neg (ne_of_gt kpos)], refl }
lemma ppow_succ {f : arithmetic_function R} {k : ℕ} :
f.ppow (k + 1) = f.pmul (f.ppow k) :=
begin
ext x,
rw [ppow_apply (nat.succ_pos k), pow_succ],
induction k; simp,
end
lemma ppow_succ' {f : arithmetic_function R} {k : ℕ} {kpos : 0 < k} :
f.ppow (k + 1) = (f.ppow k).pmul f :=
begin
ext x,
rw [ppow_apply (nat.succ_pos k), pow_succ'],
induction k; simp,
end
end pmul
/-- Multiplicative functions -/
def is_multiplicative [monoid_with_zero R] (f : arithmetic_function R) : Prop :=
f 1 = 1 ∧ (∀ {m n : ℕ}, m.coprime n → f (m * n) = f m * f n)
namespace is_multiplicative
section monoid_with_zero
variable [monoid_with_zero R]
@[simp]
lemma map_one {f : arithmetic_function R} (h : f.is_multiplicative) : f 1 = 1 :=
h.1
@[simp]
lemma map_mul_of_coprime {f : arithmetic_function R} (hf : f.is_multiplicative)
{m n : ℕ} (h : m.coprime n) : f (m * n) = f m * f n :=
hf.2 h
end monoid_with_zero
lemma map_prod {ι : Type*} [comm_monoid_with_zero R] (g : ι → ℕ) {f : nat.arithmetic_function R}
(hf : f.is_multiplicative) (s : finset ι) (hs : (s : set ι).pairwise (coprime on g)):
f (∏ i in s, g i) = ∏ i in s, f (g i) :=
begin
classical,
induction s using finset.induction_on with a s has ih hs,
{ simp [hf] },
rw [coe_insert, set.pairwise_insert_of_symmetric (coprime.symmetric.comap g)] at hs,
rw [prod_insert has, prod_insert has, hf.map_mul_of_coprime, ih hs.1],
exact nat.coprime_prod_right (λ i hi, hs.2 _ hi (hi.ne_of_not_mem has).symm),
end
lemma nat_cast {f : arithmetic_function ℕ} [semiring R] (h : f.is_multiplicative) :
is_multiplicative (f : arithmetic_function R) :=
⟨by simp [h], λ m n cop, by simp [cop, h]⟩
lemma int_cast {f : arithmetic_function ℤ} [ring R] (h : f.is_multiplicative) :
is_multiplicative (f : arithmetic_function R) :=
⟨by simp [h], λ m n cop, by simp [cop, h]⟩
lemma mul [comm_semiring R] {f g : arithmetic_function R}
(hf : f.is_multiplicative) (hg : g.is_multiplicative) :
is_multiplicative (f * g) :=
⟨by { simp [hf, hg], }, begin
simp only [mul_apply],
intros m n cop,
rw sum_mul_sum,
symmetry,
apply sum_bij (λ (x : (ℕ × ℕ) × ℕ × ℕ) h, (x.1.1 * x.2.1, x.1.2 * x.2.2)),
{ rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h,
rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩,
simp only [mem_divisors_antidiagonal, nat.mul_eq_zero, ne.def],
split, {ring},
rw nat.mul_eq_zero at *,
apply not_or ha hb },
{ rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ h,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h,
rcases h with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩,
dsimp only,
rw [hf.map_mul_of_coprime cop.coprime_mul_right.coprime_mul_right_right,
hg.map_mul_of_coprime cop.coprime_mul_left.coprime_mul_left_right],
ring, },
{ rintros ⟨⟨a1, a2⟩, ⟨b1, b2⟩⟩ ⟨⟨c1, c2⟩, ⟨d1, d2⟩⟩ hab hcd h,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hab,
rcases hab with ⟨⟨rfl, ha⟩, ⟨rfl, hb⟩⟩,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at hcd,
simp only [prod.mk.inj_iff] at h,
ext; dsimp only,
{ transitivity nat.gcd (a1 * a2) (a1 * b1),
{ rw [nat.gcd_mul_left, cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] },
{ rw [← hcd.1.1, ← hcd.2.1] at cop,
rw [← hcd.1.1, h.1, nat.gcd_mul_left,
cop.coprime_mul_left.coprime_mul_right_right.gcd_eq_one, mul_one] } },
{ transitivity nat.gcd (a1 * a2) (a2 * b2),
{ rw [mul_comm, nat.gcd_mul_left, cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one,
mul_one] },
{ rw [← hcd.1.1, ← hcd.2.1] at cop,
rw [← hcd.1.1, h.2, mul_comm, nat.gcd_mul_left,
cop.coprime_mul_right.coprime_mul_left_right.gcd_eq_one, mul_one] } },
{ transitivity nat.gcd (b1 * b2) (a1 * b1),
{ rw [mul_comm, nat.gcd_mul_right,
cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, one_mul] },
{ rw [← hcd.1.1, ← hcd.2.1] at cop,
rw [← hcd.2.1, h.1, mul_comm c1 d1, nat.gcd_mul_left,
cop.coprime_mul_right.coprime_mul_left_right.symm.gcd_eq_one, mul_one] } },
{ transitivity nat.gcd (b1 * b2) (a2 * b2),
{ rw [nat.gcd_mul_right,
cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] },
{ rw [← hcd.1.1, ← hcd.2.1] at cop,
rw [← hcd.2.1, h.2, nat.gcd_mul_right,
cop.coprime_mul_left.coprime_mul_right_right.symm.gcd_eq_one, one_mul] } } },
{ rintros ⟨b1, b2⟩ h,
simp only [mem_divisors_antidiagonal, ne.def, mem_product] at h,
use ((b1.gcd m, b2.gcd m), (b1.gcd n, b2.gcd n)),
simp only [exists_prop, prod.mk.inj_iff, ne.def, mem_product, mem_divisors_antidiagonal],
rw [← cop.gcd_mul _, ← cop.gcd_mul _, ← h.1, nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop h.1,
nat.gcd_mul_gcd_of_coprime_of_mul_eq_mul cop.symm _],
{ rw [nat.mul_eq_zero, decidable.not_or_iff_and_not] at h, simp [h.2.1, h.2.2] },
rw [mul_comm n m, h.1] }
end⟩
lemma pmul [comm_semiring R] {f g : arithmetic_function R}
(hf : f.is_multiplicative) (hg : g.is_multiplicative) :
is_multiplicative (f.pmul g) :=
⟨by { simp [hf, hg], }, λ m n cop, begin
simp only [pmul_apply, hf.map_mul_of_coprime cop, hg.map_mul_of_coprime cop],
ring,
end⟩
/-- For any multiplicative function `f` and any `n > 0`,
we can evaluate `f n` by evaluating `f` at `p ^ k` over the factorization of `n` -/
lemma multiplicative_factorization [comm_monoid_with_zero R] (f : arithmetic_function R)
(hf : f.is_multiplicative) :
∀ {n : ℕ}, n ≠ 0 → f n = n.factorization.prod (λ p k, f (p ^ k)) :=
λ n hn, multiplicative_factorization f hf.2 hf.1 hn
/-- A recapitulation of the definition of multiplicative that is simpler for proofs -/
lemma iff_ne_zero [monoid_with_zero R] {f : arithmetic_function R} :
is_multiplicative f ↔
f 1 = 1 ∧ (∀ {m n : ℕ}, m ≠ 0 → n ≠ 0 → m.coprime n → f (m * n) = f m * f n) :=
begin
refine and_congr_right' (forall₂_congr (λ m n, ⟨λ h _ _, h, λ h hmn, _⟩)),
rcases eq_or_ne m 0 with rfl | hm,
{ simp },
rcases eq_or_ne n 0 with rfl | hn,
{ simp },
exact h hm hn hmn,
end
/-- Two multiplicative functions `f` and `g` are equal if and only if
they agree on prime powers -/
lemma eq_iff_eq_on_prime_powers [comm_monoid_with_zero R]
(f : arithmetic_function R) (hf : f.is_multiplicative)
(g : arithmetic_function R) (hg : g.is_multiplicative) :
f = g ↔ ∀ (p i : ℕ), nat.prime p → f (p ^ i) = g (p ^ i) :=
begin
split,
{ intros h p i _, rw [h] },
intros h,
ext n,
by_cases hn : n = 0,
{ rw [hn, arithmetic_function.map_zero, arithmetic_function.map_zero] },
rw [multiplicative_factorization f hf hn, multiplicative_factorization g hg hn],
refine finset.prod_congr rfl _,
simp only [support_factorization, list.mem_to_finset],
intros p hp,
exact h p _ (nat.prime_of_mem_factors hp),
end
end is_multiplicative
section special_functions
/-- The identity on `ℕ` as an `arithmetic_function`. -/
def id : arithmetic_function ℕ := ⟨id, rfl⟩
@[simp]
lemma id_apply {x : ℕ} : id x = x := rfl
/-- `pow k n = n ^ k`, except `pow 0 0 = 0`. -/
def pow (k : ℕ) : arithmetic_function ℕ := id.ppow k
@[simp]
lemma pow_apply {k n : ℕ} : pow k n = if (k = 0 ∧ n = 0) then 0 else n ^ k :=
begin
cases k,
{ simp [pow] },
simp [pow, (ne_of_lt (nat.succ_pos k)).symm],
end
lemma pow_zero_eq_zeta : pow 0 = ζ := by { ext n, simp }
/-- `σ k n` is the sum of the `k`th powers of the divisors of `n` -/
def sigma (k : ℕ) : arithmetic_function ℕ :=
⟨λ n, ∑ d in divisors n, d ^ k, by simp⟩
localized "notation `σ` := nat.arithmetic_function.sigma" in arithmetic_function
lemma sigma_apply {k n : ℕ} : σ k n = ∑ d in divisors n, d ^ k := rfl
lemma sigma_one_apply (n : ℕ) : σ 1 n = ∑ d in divisors n, d := by simp [sigma_apply]
lemma sigma_zero_apply (n : ℕ) : σ 0 n = (divisors n).card := by simp [sigma_apply]
lemma sigma_zero_apply_prime_pow {p i : ℕ} (hp : p.prime) :
σ 0 (p ^ i) = i + 1 :=
by rw [sigma_zero_apply, divisors_prime_pow hp, card_map, card_range]
lemma zeta_mul_pow_eq_sigma {k : ℕ} : ζ * pow k = σ k :=
begin
ext,
rw [sigma, zeta_mul_apply],
apply sum_congr rfl,
intros x hx,
rw [pow_apply, if_neg (not_and_of_not_right _ _)],
contrapose! hx,
simp [hx],
end
lemma is_multiplicative_one [monoid_with_zero R] : is_multiplicative (1 : arithmetic_function R) :=
is_multiplicative.iff_ne_zero.2 ⟨by simp,
begin
intros m n hm hn hmn,
rcases eq_or_ne m 1 with rfl | hm',
{ simp },
rw [one_apply_ne, one_apply_ne hm', zero_mul],
rw [ne.def, nat.mul_eq_one_iff, not_and_distrib],
exact or.inl hm'
end⟩
lemma is_multiplicative_zeta : is_multiplicative ζ :=
is_multiplicative.iff_ne_zero.2 ⟨by simp, by simp {contextual := tt}⟩
lemma is_multiplicative_id : is_multiplicative arithmetic_function.id :=
⟨rfl, λ _ _ _, rfl⟩
lemma is_multiplicative.ppow [comm_semiring R] {f : arithmetic_function R}
(hf : f.is_multiplicative) {k : ℕ} :
is_multiplicative (f.ppow k) :=
begin
induction k with k hi,
{ exact is_multiplicative_zeta.nat_cast },
{ rw ppow_succ,
apply hf.pmul hi },
end
lemma is_multiplicative_pow {k : ℕ} : is_multiplicative (pow k) :=
is_multiplicative_id.ppow
lemma is_multiplicative_sigma {k : ℕ} :
is_multiplicative (σ k) :=
begin
rw [← zeta_mul_pow_eq_sigma],
apply ((is_multiplicative_zeta).mul is_multiplicative_pow)
end
/-- `Ω n` is the number of prime factors of `n`. -/
def card_factors : arithmetic_function ℕ :=
⟨λ n, n.factors.length, by simp⟩
localized "notation `Ω` := nat.arithmetic_function.card_factors" in arithmetic_function
lemma card_factors_apply {n : ℕ} :
Ω n = n.factors.length := rfl
@[simp]
lemma card_factors_one : Ω 1 = 0 := by simp [card_factors]
lemma card_factors_eq_one_iff_prime {n : ℕ} :
Ω n = 1 ↔ n.prime :=
begin
refine ⟨λ h, _, λ h, list.length_eq_one.2 ⟨n, factors_prime h⟩⟩,
cases n,
{ contrapose! h,
simp },
rcases list.length_eq_one.1 h with ⟨x, hx⟩,
rw [← prod_factors n.succ_ne_zero, hx, list.prod_singleton],
apply prime_of_mem_factors,
rw [hx, list.mem_singleton]
end
lemma card_factors_mul {m n : ℕ} (m0 : m ≠ 0) (n0 : n ≠ 0) :
Ω (m * n) = Ω m + Ω n :=
by rw [card_factors_apply, card_factors_apply, card_factors_apply, ← multiset.coe_card,
← factors_eq, unique_factorization_monoid.normalized_factors_mul m0 n0, factors_eq, factors_eq,
multiset.card_add, multiset.coe_card, multiset.coe_card]
lemma card_factors_multiset_prod {s : multiset ℕ} (h0 : s.prod ≠ 0) :
Ω s.prod = (multiset.map Ω s).sum :=
begin
revert h0,
apply s.induction_on, by simp,
intros a t h h0,
rw [multiset.prod_cons, mul_ne_zero_iff] at h0,
simp [h0, card_factors_mul, h],
end
@[simp] lemma card_factors_apply_prime {p : ℕ} (hp : p.prime) : Ω p = 1 :=
card_factors_eq_one_iff_prime.2 hp
@[simp] lemma card_factors_apply_prime_pow {p k : ℕ} (hp : p.prime) : Ω (p ^ k) = k :=
by rw [card_factors_apply, hp.factors_pow, list.length_repeat]
/-- `ω n` is the number of distinct prime factors of `n`. -/
def card_distinct_factors : arithmetic_function ℕ :=
⟨λ n, n.factors.dedup.length, by simp⟩
localized "notation `ω` := nat.arithmetic_function.card_distinct_factors" in arithmetic_function
lemma card_distinct_factors_zero : ω 0 = 0 := by simp
@[simp] lemma card_distinct_factors_one : ω 1 = 0 := by simp [card_distinct_factors]
lemma card_distinct_factors_apply {n : ℕ} :
ω n = n.factors.dedup.length := rfl
lemma card_distinct_factors_eq_card_factors_iff_squarefree {n : ℕ} (h0 : n ≠ 0) :
ω n = Ω n ↔ squarefree n :=
begin
rw [squarefree_iff_nodup_factors h0, card_distinct_factors_apply],
split; intro h,
{ rw ← list.eq_of_sublist_of_length_eq n.factors.dedup_sublist h,
apply list.nodup_dedup },
{ rw h.dedup,
refl }
end
@[simp] lemma card_distinct_factors_apply_prime_pow {p k : ℕ} (hp : p.prime) (hk : k ≠ 0) :
ω (p ^ k) = 1 :=
by rw [card_distinct_factors_apply, hp.factors_pow, list.repeat_dedup hk, list.length_singleton]
@[simp] lemma card_distinct_factors_apply_prime {p : ℕ} (hp : p.prime) : ω p = 1 :=
by rw [←pow_one p, card_distinct_factors_apply_prime_pow hp one_ne_zero]
/-- `μ` is the Möbius function. If `n` is squarefree with an even number of distinct prime factors,
`μ n = 1`. If `n` is squarefree with an odd number of distinct prime factors, `μ n = -1`.
If `n` is not squarefree, `μ n = 0`. -/
def moebius : arithmetic_function ℤ :=
⟨λ n, if squarefree n then (-1) ^ (card_factors n) else 0, by simp⟩
localized "notation `μ` := nat.arithmetic_function.moebius" in arithmetic_function
@[simp]
lemma moebius_apply_of_squarefree {n : ℕ} (h : squarefree n) : μ n = (-1) ^ card_factors n :=
if_pos h
@[simp] lemma moebius_eq_zero_of_not_squarefree {n : ℕ} (h : ¬ squarefree n) : μ n = 0 := if_neg h
lemma moebius_apply_one : μ 1 = 1 := by simp
lemma moebius_ne_zero_iff_squarefree {n : ℕ} : μ n ≠ 0 ↔ squarefree n :=
begin
split; intro h,
{ contrapose! h,
simp [h] },
{ simp [h, pow_ne_zero] }
end
lemma moebius_ne_zero_iff_eq_or {n : ℕ} : μ n ≠ 0 ↔ μ n = 1 ∨ μ n = -1 :=
begin
split; intro h,
{ rw moebius_ne_zero_iff_squarefree at h,
rw moebius_apply_of_squarefree h,
apply neg_one_pow_eq_or },
{ rcases h with h | h; simp [h] }
end
lemma moebius_apply_prime {p : ℕ} (hp : p.prime) : μ p = -1 :=
by rw [moebius_apply_of_squarefree hp.squarefree, card_factors_apply_prime hp, pow_one]
lemma moebius_apply_prime_pow {p k : ℕ} (hp : p.prime) (hk : k ≠ 0) :
μ (p ^ k) = if k = 1 then -1 else 0 :=
begin
split_ifs,
{ rw [h, pow_one, moebius_apply_prime hp] },
rw [moebius_eq_zero_of_not_squarefree],
rw [squarefree_pow_iff hp.ne_one hk, not_and_distrib],
exact or.inr h,
end
lemma moebius_apply_is_prime_pow_not_prime {n : ℕ} (hn : is_prime_pow n) (hn' : ¬ n.prime) :
μ n = 0 :=
begin
obtain ⟨p, k, hp, hk, rfl⟩ := (is_prime_pow_nat_iff _).1 hn,
rw [moebius_apply_prime_pow hp hk.ne', if_neg],
rintro rfl,
exact hn' (by simpa),
end
lemma is_multiplicative_moebius : is_multiplicative μ :=
begin
rw is_multiplicative.iff_ne_zero,
refine ⟨by simp, λ n m hn hm hnm, _⟩,
simp only [moebius, zero_hom.coe_mk, squarefree_mul hnm, ite_and, card_factors_mul hn hm],
rw [pow_add, mul_comm, ite_mul_zero_left, ite_mul_zero_right, mul_comm],
end
open unique_factorization_monoid
@[simp] lemma moebius_mul_coe_zeta : (μ * ζ : arithmetic_function ℤ) = 1 :=
begin
ext n,
refine rec_on_pos_prime_pos_coprime _ _ _ _ n,
{ intros p n hp hn,
rw [coe_mul_zeta_apply, sum_divisors_prime_pow hp, sum_range_succ'],
simp_rw [function.embedding.coe_fn_mk, pow_zero, moebius_apply_one,
moebius_apply_prime_pow hp (nat.succ_ne_zero _), nat.succ_inj', sum_ite_eq', mem_range,
if_pos hn, add_left_neg],
rw one_apply_ne,
rw [ne.def, pow_eq_one_iff],
{ exact hp.ne_one },
{ exact hn.ne' } },
{ rw [zero_hom.map_zero, zero_hom.map_zero] },
{ simp },
{ intros a b ha hb hab ha' hb',
rw [is_multiplicative.map_mul_of_coprime _ hab, ha', hb',
is_multiplicative.map_mul_of_coprime is_multiplicative_one hab],
exact is_multiplicative_moebius.mul is_multiplicative_zeta.nat_cast }
end
@[simp] lemma coe_zeta_mul_moebius : (ζ * μ : arithmetic_function ℤ) = 1 :=
by rw [mul_comm, moebius_mul_coe_zeta]
@[simp] lemma coe_moebius_mul_coe_zeta [ring R] : (μ * ζ : arithmetic_function R) = 1 :=
by rw [←coe_coe, ←int_coe_mul, moebius_mul_coe_zeta, int_coe_one]
@[simp] lemma coe_zeta_mul_coe_moebius [ring R] : (ζ * μ : arithmetic_function R) = 1 :=
by rw [←coe_coe, ←int_coe_mul, coe_zeta_mul_moebius, int_coe_one]
section comm_ring
variable [comm_ring R]
instance : invertible (ζ : arithmetic_function R) :=
{ inv_of := μ,
inv_of_mul_self := coe_moebius_mul_coe_zeta,
mul_inv_of_self := coe_zeta_mul_coe_moebius}
/-- A unit in `arithmetic_function R` that evaluates to `ζ`, with inverse `μ`. -/
def zeta_unit : (arithmetic_function R)ˣ :=
⟨ζ, μ, coe_zeta_mul_coe_moebius, coe_moebius_mul_coe_zeta⟩
@[simp]
lemma coe_zeta_unit :
((zeta_unit : (arithmetic_function R)ˣ) : arithmetic_function R) = ζ := rfl
@[simp]
lemma inv_zeta_unit :
((zeta_unit⁻¹ : (arithmetic_function R)ˣ) : arithmetic_function R) = μ := rfl
end comm_ring
/-- Möbius inversion for functions to an `add_comm_group`. -/
theorem sum_eq_iff_sum_smul_moebius_eq
[add_comm_group R] {f g : ℕ → R} :
(∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔
∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, μ x.fst • g x.snd = f n :=
begin
let f' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else f x, if_pos rfl⟩,
let g' : arithmetic_function R := ⟨λ x, if x = 0 then 0 else g x, if_pos rfl⟩,
transitivity (ζ : arithmetic_function ℤ) • f' = g',
{ rw ext_iff,
apply forall_congr,
intro n,
cases n, { simp },
rw coe_zeta_smul_apply,
simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', if_false, zero_hom.coe_mk],
rw sum_congr rfl (λ x hx, _),
rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors hx))) },
transitivity μ • g' = f',
{ split; intro h,
{ rw [← h, ← mul_smul, moebius_mul_coe_zeta, one_smul] },
{ rw [← h, ← mul_smul, coe_zeta_mul_moebius, one_smul] } },
{ rw ext_iff,
apply forall_congr,
intro n,
cases n, { simp },
simp only [n.succ_ne_zero, forall_prop_of_true, succ_pos', smul_apply,
if_false, zero_hom.coe_mk],
rw sum_congr rfl (λ x hx, _),
rw (if_neg (ne_of_gt (nat.pos_of_mem_divisors (snd_mem_divisors_of_mem_antidiagonal hx)))) },
end
/-- Möbius inversion for functions to a `ring`. -/
theorem sum_eq_iff_sum_mul_moebius_eq [ring R] {f g : ℕ → R} :
(∀ (n : ℕ), 0 < n → ∑ i in (n.divisors), f i = g n) ↔
∀ (n : ℕ), 0 < n → ∑ (x : ℕ × ℕ) in n.divisors_antidiagonal, (μ x.fst : R) * g x.snd = f n :=
begin
rw sum_eq_iff_sum_smul_moebius_eq,
apply forall_congr,
refine λ a, imp_congr_right (λ _, (sum_congr rfl $ λ x hx, _).congr_left),
rw [zsmul_eq_mul],
end
/-- Möbius inversion for functions to a `comm_group`. -/
theorem prod_eq_iff_prod_pow_moebius_eq [comm_group R] {f g : ℕ → R} :
(∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔
∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n :=
@sum_eq_iff_sum_smul_moebius_eq (additive R) _ _ _
/-- Möbius inversion for functions to a `comm_group_with_zero`. -/
theorem prod_eq_iff_prod_pow_moebius_eq_of_nonzero [comm_group_with_zero R] {f g : ℕ → R}
(hf : ∀ (n : ℕ), 0 < n → f n ≠ 0) (hg : ∀ (n : ℕ), 0 < n → g n ≠ 0) :
(∀ (n : ℕ), 0 < n → ∏ i in (n.divisors), f i = g n) ↔
∀ (n : ℕ), 0 < n → ∏ (x : ℕ × ℕ) in n.divisors_antidiagonal, g x.snd ^ (μ x.fst) = f n :=
begin
refine iff.trans (iff.trans (forall_congr (λ n, _)) (@prod_eq_iff_prod_pow_moebius_eq Rˣ _
(λ n, if h : 0 < n then units.mk0 (f n) (hf n h) else 1)
(λ n, if h : 0 < n then units.mk0 (g n) (hg n h) else 1))) (forall_congr (λ n, _));
refine imp_congr_right (λ hn, _),
{ dsimp,
rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0,
prod_congr rfl _],
intros x hx,
rw [dif_pos (nat.pos_of_mem_divisors hx), units.coe_hom_apply, units.coe_mk0] },
{ dsimp,
rw [dif_pos hn, ← units.eq_iff, ← units.coe_hom_apply, monoid_hom.map_prod, units.coe_mk0,
prod_congr rfl _],
intros x hx,
rw [dif_pos (nat.pos_of_mem_divisors (nat.snd_mem_divisors_of_mem_antidiagonal hx)),
units.coe_hom_apply, units.coe_zpow, units.coe_mk0] }
end
end special_functions
end arithmetic_function
end nat
|
4b2fcc0d53541bd2aeb249553254377499afcb81
|
7bf54883c04ff2856c37f76a79599ceb380c1996
|
/non-mathlib/numbers.lean
|
e319ec83f1f5083c577c4b95f6abae436d68e539
|
[] |
no_license
|
anonymousLeanDocsHosting/lean-polynomials
|
4094466bf19acc0d1a47b4cabb60d8c21ddb2b00
|
361ef4cb7b68ef47d43b85cfa2d13f2ea0a47613
|
refs/heads/main
| 1,691,112,899,935
| 1,631,819,522,000
| 1,631,819,522,000
| 405,448,439
| 0
| 2
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 3,865
|
lean
|
import field_definition
import field_results
def two (f : Type) [myfld f] : f := (myfld.one .+ myfld.one)
def four (f : Type) [myfld f] : f := ((two f) .+ (two f))
/- We have to add an additional stipulation that our fields are not of characteristic 2.-/
/- The quadratic formula is not defined for fields where 1 + 1 = 0.-/
class fld_not_char_two (f : Type _) [myfld f] :=
(not_char_two : myfld.one .+ myfld.one ≠ (myfld.zero : f))
lemma two_ne_zero (f : Type) [myfld f] [fld_not_char_two f] : (two f) ≠ myfld.zero :=
begin
unfold two, exact fld_not_char_two.not_char_two,
end
lemma two_plus_two (f : Type) [myfld f] : (two f) .+ (two f) = (two f) .* (two f) :=
begin
unfold two, rw distrib_simp f _ _ _, rw myfld.mul_comm myfld.one _, rw <- myfld.mul_one (myfld.one .+ myfld.one),
end
lemma four_ne_zero (f : Type) [myfld f] [fld_not_char_two f] : (four f) ≠ myfld.zero :=
begin
unfold four, rw two_plus_two, exact mul_nonzero f (two f) (two f) (two_ne_zero f) (two_ne_zero f),
end
lemma add_two_halves (f : Type) [myfld f] [fld_not_char_two f] :
(myfld.reciprocal (two f) (two_ne_zero f)) .+ (myfld.reciprocal (two f) (two_ne_zero f)) = myfld.one :=
begin
unfold two,
have h1 : (two f) .* (myfld.reciprocal (two f) (two_ne_zero f)) = myfld.one,
exact myfld.mul_reciprocal (two f) (two_ne_zero f),
unfold two at h1, rw distrib_simp f _ _ _ at h1,
rw myfld.mul_comm (myfld.one) _ at h1,
rw <- myfld.mul_one (myfld.reciprocal (myfld.one .+ myfld.one) (fld_not_char_two.not_char_two)) at h1,
exact h1,
end
/- Now we can move on to the preliminary work for the cubic formula.-/
/- We have to add an additional stipulation that our fields are not of characteristic 3.-/
/- The cubic formula is not defined for fields where 1 + 1 + 1 = 0.-/
def three (f : Type) [myfld f] : f := myfld.one .+ (myfld.one .+ myfld.one)
class fld_not_char_three (f : Type _) [myfld f] :=
(not_char_three : (three f) ≠ (myfld.zero : f))
def six (f : Type) [myfld f] : f := (two f) .* (three f)
lemma six_ne_zero (f : Type) [myfld f] [fld_not_char_two f] [fld_not_char_three f] : (six f) ≠ myfld.zero :=
begin
unfold six, unfold two, exact mul_nonzero f (myfld.one .+ myfld.one) (three f)
fld_not_char_two.not_char_two fld_not_char_three.not_char_three,
end
def nine (f : Type) [myfld f] : f := ((three f) .* (three f))
lemma nine_ne_zero (f : Type) [myfld f] [fld_not_char_three f] : (nine f) ≠ myfld.zero :=
begin
unfold nine, exact mul_nonzero f (three f) (three f) fld_not_char_three.not_char_three fld_not_char_three.not_char_three,
end
def twenty_seven (f : Type) [myfld f] : f := (three f) .* (nine f)
lemma twenty_seven_ne_zero (f : Type) [myfld f] [fld_not_char_three f] : (twenty_seven f) ≠ myfld.zero :=
begin
unfold twenty_seven, exact mul_nonzero f (three f) (nine f) fld_not_char_three.not_char_three (nine_ne_zero f),
end
lemma three_cubed (f : Type) [myfld f] : (cubed f (three f)) = (twenty_seven f) :=
begin
unfold cubed, unfold twenty_seven, unfold nine,
end
def nine_minus_one (f : Type) [myfld f] : (((three f) .* (three f)) .+ (.- myfld.one)) =
(cubed f (two f)) :=
begin
unfold three, unfold two, unfold cubed, simp,
end
def one_plus_three (f : Type) [myfld f] : myfld.one .+ (three f) = (two f) .* (two f) :=
begin
unfold two, unfold three, simp,
end
lemma two_x_div_two (f : Type) [myfld f] [fld_not_char_two f] (a : f) :
(myfld.reciprocal (two f) fld_not_char_two.not_char_two) .* (a .+ a) = a :=
begin
unfold two,
rw [myfld.mul_one a] {occs := occurrences.pos [1, 2]},
rw <- distrib_simp_alt f a, rw myfld.mul_comm a, rw myfld.mul_assoc, rw myfld.mul_comm (myfld.reciprocal _ _) _,
rw myfld.mul_reciprocal, rw one_mul_simp,
end
|
c2b1cf2e6a3a919b27a674bcfc4e1e31b28930a3
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/data/polynomial/cardinal.lean
|
6bd5486e7f972e2d6c7e8882931980d53a5a53af
|
[
"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
| 957
|
lean
|
/-
Copyright (c) 2021 Chris Hughes, Junyan Xu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Junyan Xu
-/
import data.polynomial.basic
import set_theory.cardinal.ordinal
/-!
# Cardinality of Polynomial Ring
The reuslt in this file is that the cardinality of `R[X]` is at most the maximum
of `#R` and `ℵ₀`.
-/
universe u
open_locale cardinal polynomial
open cardinal
namespace polynomial
@[simp] lemma cardinal_mk_eq_max {R : Type u} [semiring R] [nontrivial R] : #R[X] = max (#R) ℵ₀ :=
(to_finsupp_iso R).to_equiv.cardinal_eq.trans $
by { rw [add_monoid_algebra, mk_finsupp_lift_of_infinite, lift_uzero, max_comm], refl }
lemma cardinal_mk_le_max {R : Type u} [semiring R] : #R[X] ≤ max (#R) ℵ₀ :=
begin
casesI subsingleton_or_nontrivial R,
{ exact (mk_eq_one _).trans_le (le_max_of_le_right one_le_aleph_0) },
{ exact cardinal_mk_eq_max.le },
end
end polynomial
|
7e43069183eed420203434cd52af406524fbfaa8
|
b7f22e51856f4989b970961f794f1c435f9b8f78
|
/tests/lean/run/eq13.lean
|
099d288158896923e66a72de81aac6ba83fee6aa
|
[
"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
| 325
|
lean
|
open nat
definition f : nat → nat → nat
| f _ 0 := 0
| f 0 _ := 1
| f _ _ := arbitrary nat
theorem f_zero_right : ∀ a, f a 0 = 0
| f_zero_right 0 := rfl
| f_zero_right (succ a) := rfl
theorem f_zero_succ (a : nat) : f 0 (a+1) = 1 :=
rfl
theorem f_succ_succ (a b : nat) : f (a+1) (b+1) = arbitrary nat :=
rfl
|
9647b7d9c87551adbdca9601b2b4565600af3f1b
|
5719a16e23dfc08cdea7a5bf035b81690f307965
|
/src/Init/Lean/Elab/App.lean
|
c22483744930097e445169eff137afefb7131b12
|
[
"Apache-2.0"
] |
permissive
|
postmasters/lean4
|
488b03969a371e1507e1e8a4df9ebf63c7cbe7ac
|
f3976fc53a883ac7606fc59357d43f4b51016ca7
|
refs/heads/master
| 1,655,582,707,480
| 1,588,682,595,000
| 1,588,682,595,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 29,215
|
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.Util.FindMVar
import Init.Lean.Elab.Term
import Init.Lean.Elab.Binders
namespace Lean
namespace Elab
namespace Term
/--
Auxiliary inductive datatype for combining unelaborated syntax
and already elaborated expressions. It is used to elaborate applications. -/
inductive Arg
| stx (val : Syntax)
| expr (val : Expr)
instance Arg.inhabited : Inhabited Arg := ⟨Arg.stx (arbitrary _)⟩
instance Arg.hasToString : HasToString Arg :=
⟨fun arg => match arg with
| Arg.stx val => toString val
| Arg.expr val => toString val⟩
/-- Named arguments created using the notation `(x := val)` -/
structure NamedArg :=
(name : Name) (val : Arg)
instance NamedArg.hasToString : HasToString NamedArg :=
⟨fun s => "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")"⟩
instance NamedArg.inhabited : Inhabited NamedArg := ⟨{ name := arbitrary _, val := arbitrary _ }⟩
/--
Add a new named argument to `namedArgs`, and throw an error if it already contains a named argument
with the same name. -/
def addNamedArg (ref : Syntax) (namedArgs : Array NamedArg) (namedArg : NamedArg) : TermElabM (Array NamedArg) := do
when (namedArgs.any $ fun namedArg' => namedArg.name == namedArg'.name) $
throwError ref ("argument '" ++ toString namedArg.name ++ "' was already set");
pure $ namedArgs.push namedArg
def synthesizeAppInstMVars (ref : Syntax) (instMVars : Array MVarId) : TermElabM Unit :=
instMVars.forM $ fun mvarId =>
unlessM (synthesizeInstMVarCore ref mvarId) $
registerSyntheticMVar ref mvarId SyntheticMVarKind.typeClass
private def ensureArgType (ref : Syntax) (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do
argType ← inferType ref arg;
ensureHasTypeAux ref expectedType argType arg f
private def elabArg (ref : Syntax) (f : Expr) (arg : Arg) (expectedType : Expr) : TermElabM Expr :=
match arg with
| Arg.expr val => ensureArgType ref f val expectedType
| Arg.stx val => do
val ← elabTerm val expectedType;
ensureArgType ref f val expectedType
private def mkArrow (d b : Expr) : TermElabM Expr := do
n ← mkFreshAnonymousName;
pure $ Lean.mkForall n BinderInfo.default d b
/-
Relevant definitions:
```
class CoeFun (α : Sort u) (γ : α → outParam (Sort v))
abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a
``` -/
private def tryCoeFun (ref : Syntax) (α : Expr) (a : Expr) : TermElabM Expr := do
v ← mkFreshLevelMVar ref;
type ← mkArrow α (mkSort v);
γ ← mkFreshExprMVar ref type;
u ← getLevel ref α;
let coeFunInstType := mkAppN (Lean.mkConst `CoeFun [u, v]) #[α, γ];
mvar ← mkFreshExprMVar ref coeFunInstType MetavarKind.synthetic;
let mvarId := mvar.mvarId!;
synthesized ←
catch (withoutMacroStackAtErr $ synthesizeInstMVarCore ref mvarId)
(fun ex =>
match ex with
| Exception.ex (Elab.Exception.error errMsg) => throwError ref ("function expected" ++ Format.line ++ errMsg.data)
| _ => throwError ref "function expected");
if synthesized then
pure $ mkAppN (Lean.mkConst `coeFun [u, v]) #[α, γ, a, mvar]
else
throwError ref "function expected"
/-- Auxiliary structure used to elaborate function application arguments. -/
structure ElabAppArgsCtx :=
(ref : Syntax)
(args : Array Arg)
(expectedType? : Option Expr)
(explicit : Bool) -- if true, all arguments are treated as explicit
(argIdx : Nat := 0) -- position of next explicit argument to be processed
(namedArgs : Array NamedArg) -- remaining named arguments to be processed
(instMVars : Array MVarId := #[]) -- metavariables for the instance implicit arguments that have already been processed
(typeMVars : Array MVarId := #[]) -- metavariables for implicit arguments of the form `{α : Sort u}` that have already been processed
(foundExplicit : Bool := false) -- true if an explicit argument has already been processed
/- Auxiliary function for retrieving the resulting type of a function application.
See `propagateExpectedType`. -/
private partial def getForallBody : Nat → Array NamedArg → Expr → Option Expr
| i, namedArgs, type@(Expr.forallE n d b c) =>
match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with
| some idx => getForallBody i (namedArgs.eraseIdx idx) b
| none =>
if !c.binderInfo.isExplicit then
getForallBody i namedArgs b
else if i > 0 then
getForallBody (i-1) namedArgs b
else if d.isAutoParam || d.isOptParam then
getForallBody i namedArgs b
else
some type
| i, namedArgs, type => if i == 0 && namedArgs.isEmpty then some type else none
private def hasTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool :=
(type.findMVar? (fun mvarId => ctx.typeMVars.contains mvarId)).isSome
private def hasOnlyTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool :=
(type.findMVar? (fun mvarId => !ctx.typeMVars.contains mvarId)).isNone
/-
Auxiliary method for propagating the expected type. We call it as soon as we find the first explict
argument. The goal is to propagate the expected type in applications of functions such as
```lean
HasAdd.add {α : Type u} : α → α → α
List.cons {α : Type u} : α → List α → List α
```
This is particularly useful when there applicable coercions. For example,
assume we have a coercion from `Nat` to `Int`, and we have
`(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function,
the elaborator will fail to elaborate
```
List.cons x []
```
First, the elaborator creates a new metavariable `?α` for the implicit argument `{α : Type u}`.
Then, when it processes `x`, it assigns `?α := Nat`, and then obtain the
resultant type `List Nat` which is **not** definitionally equal to `List Int`.
We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example).
This method infers that the resultant type is `List ?α` and unifies it with `List Int`.
Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the
term
```
@List.cons Int (coe x) (@List.nil Int)
```
is produced.
The method will do nothing if
1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`)
2- The resultant type does not contain any type metavariable.
3- The resultant type contains a nontype metavariable.
We added conditions 2&3 to be able to restrict this method to simple functions that are "morally" in
the Hindley&Milner fragment.
For example, consider the following definitions
```
def foo {n m : Nat} (a : bv n) (b : bv m) : bv (n - m)
```
Now, consider
```
def test (x1 : bv 32) (x2 : bv 31) (y1 : bv 64) (y2 : bv 63) : bv 1 :=
foo x1 x2 = foo y1 y2
```
When the elaborator reaches the term `foo y1 y2`, the expected type is `bv (32-31)`.
If we apply this method, we would solve the unification problem `bv (?n - ?m) =?= bv (32 - 31)`,
by assigning `?n := 32` and `?m := 31`. Then, the elaborator fails elaborating `y1` since
`bv 64` is **not** definitionally equal to `bv 32`.
-/
private def propagateExpectedType (ctx : ElabAppArgsCtx) (eType : Expr) : TermElabM Unit :=
unless (ctx.explicit || ctx.foundExplicit || ctx.typeMVars.isEmpty) $ do
match ctx.expectedType? with
| none => pure ()
| some expectedType =>
let numRemainingArgs := ctx.args.size - ctx.argIdx;
match getForallBody numRemainingArgs ctx.namedArgs eType with
| none => pure ()
| some eTypeBody =>
unless eTypeBody.hasLooseBVars $
when (hasTypeMVar ctx eTypeBody && hasOnlyTypeMVar ctx eTypeBody) $ do
_ ← isDefEq ctx.ref expectedType eTypeBody;
pure ()
private def nextArgIsHole (ctx : ElabAppArgsCtx) : Bool :=
if h : ctx.argIdx < ctx.args.size then
match ctx.args.get ⟨ctx.argIdx, h⟩ with
| Arg.stx (Syntax.node `Lean.Parser.Term.hole _) => true
| _ => false
else
false
/- Elaborate function application arguments. -/
private partial def elabAppArgsAux : ElabAppArgsCtx → Expr → Expr → TermElabM Expr
| ctx, e, eType => do
let finalize : Unit → TermElabM Expr := fun _ => do {
-- all user explicit arguments have been consumed
trace `Elab.app.finalize ctx.ref $ fun _ => e;
match ctx.expectedType? with
| none => pure ()
| some expectedType => do {
-- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it.
_ ← isDefEq ctx.ref expectedType eType;
pure ()
};
synthesizeAppInstMVars ctx.ref ctx.instMVars;
pure e
};
eType ← whnfForall ctx.ref eType;
match eType with
| Expr.forallE n d b c =>
match ctx.namedArgs.findIdx? (fun namedArg => namedArg.name == n) with
| some idx => do
let arg := ctx.namedArgs.get! idx;
let namedArgs := ctx.namedArgs.eraseIdx idx;
argElab ← elabArg ctx.ref e arg.val d;
propagateExpectedType ctx eType;
elabAppArgsAux { foundExplicit := true, namedArgs := namedArgs, .. ctx } (mkApp e argElab) (b.instantiate1 argElab)
| none =>
let processExplictArg : Unit → TermElabM Expr := fun _ => do {
propagateExpectedType ctx eType;
let ctx := { foundExplicit := true, .. ctx };
if h : ctx.argIdx < ctx.args.size then do
argElab ← elabArg ctx.ref e (ctx.args.get ⟨ctx.argIdx, h⟩) d;
elabAppArgsAux { argIdx := ctx.argIdx + 1, .. ctx } (mkApp e argElab) (b.instantiate1 argElab)
else match ctx.explicit, d.getOptParamDefault?, d.getAutoParamTactic? with
| false, some defVal, _ => elabAppArgsAux ctx (mkApp e defVal) (b.instantiate1 defVal)
| false, _, some (Expr.const tacticDecl _ _) => do
env ← getEnv;
match evalSyntaxConstant env tacticDecl with
| Except.error err => throwError ctx.ref err
| Except.ok tacticSyntax => do
tacticBlock ← `(begin $(tacticSyntax.getArgs)* end);
-- tacticBlock does not have any position information
-- use ctx.ref.getHeadInfo if available
let tacticBlock := match ctx.ref.getHeadInfo with
| some info => tacticBlock.replaceInfo info
| _ => tacticBlock;
let d := d.getArg! 0; -- `autoParam type := by tactic` ==> `type`
argElab ← elabArg ctx.ref e (Arg.stx tacticBlock) d;
elabAppArgsAux ctx (mkApp e argElab) (b.instantiate1 argElab)
| false, _, some _ =>
throwError ctx.ref "invalid autoParam, argument must be a constant"
| _, _, _ =>
if ctx.namedArgs.isEmpty then
finalize ()
else
throwError ctx.ref ("explicit parameter '" ++ n ++ "' is missing, unused named arguments " ++ toString (ctx.namedArgs.map $ fun narg => narg.name))
};
match c.binderInfo with
| BinderInfo.implicit =>
if ctx.explicit then
processExplictArg ()
else do
a ← mkFreshExprMVar ctx.ref d;
typeMVars ← condM (isTypeFormer ctx.ref a) (pure $ ctx.typeMVars.push a.mvarId!) (pure ctx.typeMVars);
elabAppArgsAux { typeMVars := typeMVars, .. ctx } (mkApp e a) (b.instantiate1 a)
| BinderInfo.instImplicit =>
if ctx.explicit && nextArgIsHole ctx then do
/- Recall that if '@' has been used, and the argument is '_', then we still use
type class resolution -/
a ← mkFreshExprMVar ctx.ref d MetavarKind.synthetic;
elabAppArgsAux { argIdx := ctx.argIdx + 1, instMVars := ctx.instMVars.push a.mvarId!, .. ctx } (mkApp e a) (b.instantiate1 a)
else if ctx.explicit then
processExplictArg ()
else do
a ← mkFreshExprMVar ctx.ref d MetavarKind.synthetic;
elabAppArgsAux { instMVars := ctx.instMVars.push a.mvarId!, .. ctx } (mkApp e a) (b.instantiate1 a)
| _ =>
processExplictArg ()
| _ =>
if ctx.namedArgs.isEmpty && ctx.argIdx == ctx.args.size then
finalize ()
else do
e ← tryCoeFun ctx.ref eType e;
eType ← inferType ctx.ref e;
elabAppArgsAux ctx e eType
private def elabAppArgs (ref : Syntax) (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg)
(expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do
fType ← inferType ref f;
fType ← instantiateMVars ref fType;
trace `Elab.app.args ref $ fun _ => "explicit: " ++ toString explicit ++ ", " ++ f ++ " : " ++ fType;
unless (namedArgs.isEmpty && args.isEmpty) $
tryPostponeIfMVar fType;
elabAppArgsAux {ref := ref, args := args, expectedType? := expectedType?, explicit := explicit, namedArgs := namedArgs } f fType
/-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/
inductive LValResolution
| projFn (baseStructName : Name) (structName : Name) (fieldName : Name)
| projIdx (structName : Name) (idx : Nat)
| const (baseName : Name) (constName : Name)
| localRec (baseName : Name) (fullName : Name) (fvar : Expr)
| getOp (fullName : Name) (idx : Syntax)
private def throwLValError {α} (ref : Syntax) (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM α :=
throwError ref $ msg ++ indentExpr e ++ Format.line ++ "has type" ++ indentExpr eType
private def resolveLValAux (ref : Syntax) (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution :=
match eType.getAppFn, lval with
| Expr.const structName _ _, LVal.fieldIdx idx => do
when (idx == 0) $
throwError ref "invalid projection, index must be greater than 0";
env ← getEnv;
unless (isStructureLike env structName) $
throwLValError ref e eType "invalid projection, structure expected";
let fieldNames := getStructureFields env structName;
if h : idx - 1 < fieldNames.size then
if isStructure env structName then
pure $ LValResolution.projFn structName structName (fieldNames.get ⟨idx - 1, h⟩)
else
/- `structName` was declared using `inductive` command.
So, we don't projection functions for it. Thus, we use `Expr.proj` -/
pure $ LValResolution.projIdx structName (idx - 1)
else
throwLValError ref e eType ("invalid projection, structure has only " ++ toString fieldNames.size ++ " field(s)")
| Expr.const structName _ _, LVal.fieldName fieldName => do
env ← getEnv;
let searchEnv (fullName : Name) : TermElabM LValResolution := do {
match env.find? fullName with
| some _ => pure $ LValResolution.const structName fullName
| none =>
let fullNamePrv := mkPrivateName env fullName;
match env.find? fullNamePrv with
| some _ => pure $ LValResolution.const structName fullNamePrv
| none =>
throwLValError ref e eType $
"invalid field notation, '" ++ fieldName ++ "' is not a valid \"field\" because environment does not contain '" ++ fullName ++ "'"
};
-- search local context first, then environment
let searchCtx : Unit → TermElabM LValResolution := fun _ => do {
let fullName := structName ++ fieldName;
currNamespace ← getCurrNamespace;
let localName := fullName.replacePrefix currNamespace Name.anonymous;
lctx ← getLCtx;
match lctx.findFromUserName? localName with
| some localDecl =>
if localDecl.binderInfo == BinderInfo.auxDecl then
/- LVal notation is being used to make a "local" recursive call. -/
pure $ LValResolution.localRec structName fullName localDecl.toExpr
else
searchEnv fullName
| none => searchEnv fullName
};
if isStructure env structName then
match findField? env structName fieldName with
| some baseStructName => pure $ LValResolution.projFn baseStructName structName fieldName
| none => searchCtx ()
else
searchCtx ()
| Expr.const structName _ _, LVal.getOp idx => do
env ← getEnv;
let fullName := mkNameStr structName "getOp";
match env.find? fullName with
| some _ => pure $ LValResolution.getOp fullName idx
| none => throwLValError ref e eType $ "invalid [..] notation because environment does not contain '" ++ fullName ++ "'"
| _, LVal.getOp idx =>
throwLValError ref e eType "invalid [..] notation, type is not of the form (C ...) where C is a constant"
| _, _ =>
throwLValError ref e eType "invalid field notation, type is not of the form (C ...) where C is a constant"
private partial def resolveLValLoop (ref : Syntax) (e : Expr) (lval : LVal) : Expr → Array Message → TermElabM LValResolution
| eType, previousExceptions => do
eType ← whnfCore ref eType;
tryPostponeIfMVar eType;
catch (resolveLValAux ref e eType lval)
(fun ex =>
match ex with
| Exception.postpone => throw ex
| Exception.ex Elab.Exception.unsupportedSyntax => throw ex
| Exception.ex (Elab.Exception.error errMsg) => do
eType? ← unfoldDefinition? ref eType;
match eType? with
| some eType => resolveLValLoop eType (previousExceptions.push errMsg)
| none => do
previousExceptions.forM $ fun ex =>
logMessage errMsg;
throw (Exception.ex (Elab.Exception.error errMsg)))
private def resolveLVal (ref : Syntax) (e : Expr) (lval : LVal) : TermElabM LValResolution := do
eType ← inferType ref e;
resolveLValLoop ref e lval eType #[]
private partial def mkBaseProjections (ref : Syntax) (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do
env ← getEnv;
match getPathToBaseStructure? env baseStructName structName with
| none => throwError ref "failed to access field in parent structure"
| some path =>
path.foldlM
(fun e projFunName => do
projFn ← mkConst ref projFunName;
elabAppArgs ref projFn #[{ name := `self, val := Arg.expr e }] #[] none false)
e
/- Auxiliary method for field notation. It tries to add `e` to `args` as the first explicit parameter
which takes an element of type `(C ...)` where `C` is `baseName`.
`fullName` is the name of the resolved "field" access function. It is used for reporting errors -/
private def addLValArg (ref : Syntax) (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) : Nat → Array NamedArg → Expr → TermElabM (Array Arg)
| i, namedArgs, Expr.forallE n d b c =>
if !c.binderInfo.isExplicit then
addLValArg i namedArgs b
else
/- If there is named argument with name `n`, then we should skip. -/
match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with
| some idx => do
let namedArgs := namedArgs.eraseIdx idx;
addLValArg i namedArgs b
| none => do
if d.consumeMData.isAppOf baseName then
pure $ args.insertAt i (Arg.expr e)
else if i < args.size then
addLValArg (i+1) namedArgs b
else
throwError ref $ "invalid field notation, insufficient number of arguments for '" ++ fullName ++ "'"
| _, _, fType =>
throwError ref $
"invalid field notation, function '" ++ fullName ++ "' does not have explicit argument with type (" ++ baseName ++ " ...)"
private def elabAppLValsAux (ref : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool)
: Expr → List LVal → TermElabM Expr
| f, [] => elabAppArgs ref f namedArgs args expectedType? explicit
| f, lval::lvals => do
lvalRes ← resolveLVal ref f lval;
match lvalRes with
| LValResolution.projIdx structName idx =>
let f := mkProj structName idx f;
elabAppLValsAux f lvals
| LValResolution.projFn baseStructName structName fieldName => do
f ← mkBaseProjections ref baseStructName structName f;
projFn ← mkConst ref (baseStructName ++ fieldName);
if lvals.isEmpty then do
namedArgs ← addNamedArg ref namedArgs { name := `self, val := Arg.expr f };
elabAppArgs ref projFn namedArgs args expectedType? explicit
else do
f ← elabAppArgs ref projFn #[{ name := `self, val := Arg.expr f }] #[] none false;
elabAppLValsAux f lvals
| LValResolution.const baseName constName => do
projFn ← mkConst ref constName;
if lvals.isEmpty then do
projFnType ← inferType ref projFn;
args ← addLValArg ref baseName constName f args 0 namedArgs projFnType;
elabAppArgs ref projFn namedArgs args expectedType? explicit
else do
f ← elabAppArgs ref projFn #[] #[Arg.expr f] none false;
elabAppLValsAux f lvals
| LValResolution.localRec baseName fullName fvar =>
if lvals.isEmpty then do
fvarType ← inferType ref fvar;
args ← addLValArg ref baseName fullName f args 0 namedArgs fvarType;
elabAppArgs ref fvar namedArgs args expectedType? explicit
else do
f ← elabAppArgs ref fvar #[] #[Arg.expr f] none false;
elabAppLValsAux f lvals
| LValResolution.getOp fullName idx => do
getOpFn ← mkConst ref fullName;
if lvals.isEmpty then do
namedArgs ← addNamedArg ref namedArgs { name := `self, val := Arg.expr f };
namedArgs ← addNamedArg ref namedArgs { name := `idx, val := Arg.stx idx };
elabAppArgs ref getOpFn namedArgs args expectedType? explicit
else do
f ← elabAppArgs ref getOpFn #[{ name := `self, val := Arg.expr f }, { name := `idx, val := Arg.stx idx }] #[] none false;
elabAppLValsAux f lvals
private def elabAppLVals (ref : Syntax) (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg)
(expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do
when (!lvals.isEmpty && explicit) $ throwError ref "invalid use of field notation with `@` modifier";
elabAppLValsAux ref namedArgs args expectedType? explicit f lvals
def elabExplicitUniv (stx : Syntax) : TermElabM (List Level) := do
let lvls := stx.getArg 1;
lvls.foldSepRevArgsM
(fun stx lvls => do
lvl ← elabLevel stx;
pure (lvl::lvls))
[]
private partial def elabAppFnId (ref : Syntax) (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal)
(namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) (acc : Array TermElabResult)
: TermElabM (Array TermElabResult) :=
match fIdent with
| Syntax.ident _ _ n preresolved => do
funLVals ← resolveName fIdent n preresolved fExplicitUnivs;
funLVals.foldlM
(fun acc ⟨f, fields⟩ => do
let lvals' := fields.map LVal.fieldName;
s ← observing $ elabAppLVals ref f (lvals' ++ lvals) namedArgs args expectedType? explicit;
pure $ acc.push s)
acc
| _ => throwUnsupportedSyntax
private partial def elabAppFn (ref : Syntax) : Syntax → List LVal → Array NamedArg → Array Arg → Option Expr → Bool → Array TermElabResult → TermElabM (Array TermElabResult)
| f, lvals, namedArgs, args, expectedType?, explicit, acc =>
if f.isIdent then
-- A raw identifier is not a valid Term. Recall that `Term.id` is defined as `parser! ident >> optional (explicitUniv <|> namedPattern)`
-- We handle it here to make macro development more comfortable.
elabAppFnId ref f [] lvals namedArgs args expectedType? explicit acc
else if f.getKind == choiceKind then
f.getArgs.foldlM (fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit acc) acc
else match_syntax f with
| `($(e).$idx:fieldIdx) =>
let idx := idx.isFieldIdx?.get!;
elabAppFn e (LVal.fieldIdx idx :: lvals) namedArgs args expectedType? explicit acc
| `($(e).$field:ident) =>
let newLVals := field.getId.eraseMacroScopes.components.map (fun n => LVal.fieldName (toString n));
elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit acc
| `($e[$idx]) =>
elabAppFn e (LVal.getOp idx :: lvals) namedArgs args expectedType? explicit acc
| `($id:ident$us:explicitUniv*) => do
-- Remark: `id.<namedPattern>` should already have been expanded
us ← if us.isEmpty then pure [] else elabExplicitUniv (us.get! 0);
elabAppFnId ref id us lvals namedArgs args expectedType? explicit acc
| `(@$id:id) =>
elabAppFn id lvals namedArgs args expectedType? true acc
| `(@$t) => throwUnsupportedSyntax -- invalid occurrence of `@`
| _ => do
s ← observing $ do {
f ← elabTerm f none;
elabAppLVals ref f lvals namedArgs args expectedType? explicit
};
pure $ acc.push s
private def getSuccess (candidates : Array TermElabResult) : Array TermElabResult :=
candidates.filter $ fun c => match c with
| EStateM.Result.ok _ _ => true
| _ => false
private def toMessageData (msg : Message) (stx : Syntax) : TermElabM MessageData := do
strPos ← getPos stx;
pos ← getPosition strPos;
if pos == msg.pos then
pure msg.data
else
pure $ toString msg.pos.line ++ ":" ++ toString msg.pos.column ++ " " ++ msg.data
private def mergeFailures {α} (failures : Array TermElabResult) (stx : Syntax) : TermElabM α := do
msgs ← failures.mapM $ fun failure =>
match failure with
| EStateM.Result.ok _ _ => unreachable!
| EStateM.Result.error errMsg s => toMessageData errMsg stx;
throwError stx ("overloaded, errors " ++ MessageData.ofArray msgs)
private def elabAppAux (ref : Syntax) (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) : TermElabM Expr := do
/- TODO: if `f` contains `choice` or overloaded symbols, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned,
then we should postpone until `?m` is assigned.
Another (more expensive) option is: execute, and if successes > 1, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned,
then we postpone `elabAppAux`. It is more expensive because we would have to re-elaborate the whole thing after we assign `?m`.
We **can't** continue from `TermElabResult` since they contain a snapshot of the state, and state has changed. -/
candidates ← elabAppFn ref f [] namedArgs args expectedType? false #[];
if candidates.size == 1 then
applyResult $ candidates.get! 0
else
let successes := getSuccess candidates;
if successes.size == 1 then
applyResult $ successes.get! 0
else if successes.size > 1 then do
lctx ← getLCtx;
opts ← getOptions;
let msgs : Array MessageData := successes.map $ fun success => match success with
| EStateM.Result.ok e s => MessageData.withContext { env := s.env, mctx := s.mctx, lctx := lctx, opts := opts } e
| _ => unreachable!;
throwError f ("ambiguous, possible interpretations " ++ MessageData.ofArray msgs)
else
mergeFailures candidates f
private partial def expandApp (stx : Syntax) : TermElabM (Syntax × Array NamedArg × Array Arg) := do
let f := stx.getArg 0;
(namedArgs, args) ← (stx.getArg 1).getArgs.foldlM
(fun (acc : Array NamedArg × Array Arg) (stx : Syntax) => do
let (namedArgs, args) := acc;
if stx.getKind == `Lean.Parser.Term.namedArgument then do
-- tparser! try ("(" >> ident >> " := ") >> termParser >> ")"
let name := (stx.getArg 1).getId.eraseMacroScopes;
let val := stx.getArg 3;
namedArgs ← addNamedArg stx namedArgs { name := name, val := Arg.stx val };
pure (namedArgs, args)
else
pure (namedArgs, args.push $ Arg.stx stx))
(#[], #[]);
pure (f, namedArgs, args)
@[builtinTermElab app] def elabApp : TermElab :=
fun stx expectedType? => do
(f, namedArgs, args) ← expandApp stx;
elabAppAux stx f namedArgs args expectedType?
def elabAtom : TermElab :=
fun stx expectedType? => elabAppAux stx stx #[] #[] expectedType?
@[builtinTermElab «id»] def elabId : TermElab := elabAtom
@[builtinTermElab explicit] def elabExplicit : TermElab :=
fun stx expectedType? => match_syntax stx with
| `(@$id:id) => elabAtom stx expectedType? -- Recall that `elabApp` also has support for `@`
| `(@($t)) => elabTermWithoutImplicitLambdas t expectedType? -- `@` is being used just to disable implicit lambdas
| `(@$t) => elabTermWithoutImplicitLambdas t expectedType? -- `@` is being used just to disable implicit lambdas
| _ => throwUnsupportedSyntax
@[builtinTermElab choice] def elabChoice : TermElab := elabAtom
@[builtinTermElab proj] def elabProj : TermElab := elabAtom
@[builtinTermElab arrayRef] def elabArrayRef : TermElab := elabAtom
/- A raw identiier is not a valid term,
but it is nice to have a handler for them because it allows `macros` to insert them into terms. -/
@[builtinTermElab ident] def elabRawIdent : TermElab := elabAtom
@[builtinTermElab sortApp] def elabSortApp : TermElab :=
fun stx _ => do
u ← elabLevel (stx.getArg 1);
if (stx.getArg 0).getKind == `Lean.Parser.Term.sort then do
pure $ mkSort u
else
pure $ mkSort (mkLevelSucc u)
@[init] private def regTraceClasses : IO Unit := do
registerTraceClass `Elab.app;
pure ()
end Term
end Elab
end Lean
|
98785f76041861b3ddcbe613506e121d5b787c59
|
432d948a4d3d242fdfb44b81c9e1b1baacd58617
|
/src/set_theory/pgame.lean
|
5351826fa3501060e310c721ffaf93f7e97a95ad
|
[
"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
| 41,403
|
lean
|
/-
Copyright (c) 2019 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison
-/
import logic.embedding
import data.nat.cast
import data.fin
/-!
# Combinatorial (pre-)games.
The basic theory of combinatorial games, following Conway's book `On Numbers and Games`. We
construct "pregames", define an ordering and arithmetic operations on them, then show that the
operations descend to "games", defined via the equivalence relation `p ≈ q ↔ p ≤ q ∧ q ≤ p`.
The surreal numbers will be built as a quotient of a subtype of pregames.
A pregame (`pgame` below) is axiomatised via an inductive type, whose sole constructor takes two
types (thought of as indexing the the possible moves for the players Left and Right), and a pair of
functions out of these types to `pgame` (thought of as describing the resulting game after making a
move).
Combinatorial games themselves, as a quotient of pregames, are constructed in `game.lean`.
## Conway induction
By construction, the induction principle for pregames is exactly "Conway induction". That is, to
prove some predicate `pgame → Prop` holds for all pregames, it suffices to prove that for every
pregame `g`, if the predicate holds for every game resulting from making a move, then it also holds
for `g`.
While it is often convenient to work "by induction" on pregames, in some situations this becomes
awkward, so we also define accessor functions `left_moves`, `right_moves`, `move_left` and
`move_right`. There is a relation `subsequent p q`, saying that `p` can be reached by playing some
non-empty sequence of moves starting from `q`, an instance `well_founded subsequent`, and a local
tactic `pgame_wf_tac` which is helpful for discharging proof obligations in inductive proofs relying
on this relation.
## Order properties
Pregames have both a `≤` and a `<` relation, which are related in quite a subtle way. In particular,
it is worth noting that in Lean's (perhaps unfortunate?) definition of a `preorder`, we have
`lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a)`, but this is _not_ satisfied by the usual
`≤` and `<` relations on pregames. (It is satisfied once we restrict to the surreal numbers.) In
particular, `<` is not transitive; there is an example below showing `0 < star ∧ star < 0`.
We do have
```
theorem not_le {x y : pgame} : ¬ x ≤ y ↔ y < x := ...
theorem not_lt {x y : pgame} : ¬ x < y ↔ y ≤ x := ...
```
The statement `0 ≤ x` means that Left has a good response to any move by Right; in particular, the
theorem `zero_le` below states
```
0 ≤ x ↔ ∀ j : x.right_moves, ∃ i : (x.move_right j).left_moves, 0 ≤ (x.move_right j).move_left i
```
On the other hand the statement `0 < x` means that Left has a good move right now; in particular the
theorem `zero_lt` below states
```
0 < x ↔ ∃ i : left_moves x, ∀ j : right_moves (x.move_left i), 0 < (x.move_left i).move_right j
```
The theorems `le_def`, `lt_def`, give a recursive characterisation of each relation, in terms of
themselves two moves later. The theorems `le_def_lt` and `lt_def_lt` give recursive
characterisations of each relation in terms of the other relation one move later.
We define an equivalence relation `equiv p q ↔ p ≤ q ∧ q ≤ p`. Later, games will be defined as the
quotient by this relation.
## Algebraic structures
We next turn to defining the operations necessary to make games into a commutative additive group.
Addition is defined for $x = \{xL | xR\}$ and $y = \{yL | yR\}$ by $x + y = \{xL + y, x + yL | xR +
y, x + yR\}$. Negation is defined by $\{xL | xR\} = \{-xR | -xL\}$.
The order structures interact in the expected way with addition, so we have
```
theorem le_iff_sub_nonneg {x y : pgame} : x ≤ y ↔ 0 ≤ y - x := sorry
theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x := sorry
```
We show that these operations respect the equivalence relation, and hence descend to games. At the
level of games, these operations satisfy all the laws of a commutative group. To prove the necessary
equivalence relations at the level of pregames, we introduce the notion of a `relabelling` of a
game, and show, for example, that there is a relabelling between `x + (y + z)` and `(x + y) + z`.
## Future work
* The theory of dominated and reversible positions, and unique normal form for short games.
* Analysis of basic domineering positions.
* Hex.
* Temperature.
* The development of surreal numbers, based on this development of combinatorial games, is still
quite incomplete.
## References
The material here is all drawn from
* [Conway, *On numbers and games*][conway2001]
An interested reader may like to formalise some of the material from
* [Andreas Blass, *A game semantics for linear logic*][MR1167694]
* [André Joyal, *Remarques sur la théorie des jeux à deux personnes*][joyal1997]
-/
universes u
/-- The type of pre-games, before we have quotiented
by extensionality. In ZFC, a combinatorial game is constructed from
two sets of combinatorial games that have been constructed at an earlier
stage. To do this in type theory, we say that a pre-game is built
inductively from two families of pre-games indexed over any type
in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`,
reflecting that it is a proper class in ZFC. -/
inductive pgame : Type (u+1)
| mk : ∀ α β : Type u, (α → pgame) → (β → pgame) → pgame
namespace pgame
/--
Construct a pre-game from list of pre-games describing the available moves for Left and Right.
-/
-- TODO provide some API describing the interaction with
-- `left_moves`, `right_moves`, `move_left` and `move_right` below.
-- TODO define this at the level of games, as well, and perhaps also for finsets of games.
def of_lists (L R : list pgame.{0}) : pgame.{0} :=
pgame.mk (fin L.length) (fin R.length) (λ i, L.nth_le i i.is_lt) (λ j, R.nth_le j.val j.is_lt)
/-- The indexing type for allowable moves by Left. -/
def left_moves : pgame → Type u
| (mk l _ _ _) := l
/-- The indexing type for allowable moves by Right. -/
def right_moves : pgame → Type u
| (mk _ r _ _) := r
/-- The new game after Left makes an allowed move. -/
def move_left : Π (g : pgame), left_moves g → pgame
| (mk l _ L _) i := L i
/-- The new game after Right makes an allowed move. -/
def move_right : Π (g : pgame), right_moves g → pgame
| (mk _ r _ R) j := R j
@[simp] lemma left_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).left_moves = xl := rfl
@[simp] lemma move_left_mk {xl xr xL xR i} : (⟨xl, xr, xL, xR⟩ : pgame).move_left i = xL i := rfl
@[simp] lemma right_moves_mk {xl xr xL xR} : (⟨xl, xr, xL, xR⟩ : pgame).right_moves = xr := rfl
@[simp] lemma move_right_mk {xl xr xL xR j} : (⟨xl, xr, xL, xR⟩ : pgame).move_right j = xR j := rfl
/-- `subsequent p q` says that `p` can be obtained by playing
some nonempty sequence of moves from `q`. -/
inductive subsequent : pgame → pgame → Prop
| left : Π (x : pgame) (i : x.left_moves), subsequent (x.move_left i) x
| right : Π (x : pgame) (j : x.right_moves), subsequent (x.move_right j) x
| trans : Π (x y z : pgame), subsequent x y → subsequent y z → subsequent x z
theorem wf_subsequent : well_founded subsequent :=
⟨λ x, begin
induction x with l r L R IHl IHr,
refine ⟨_, λ y h, _⟩,
generalize_hyp e : mk l r L R = x at h,
induction h with _ i _ j a b _ h1 h2 IH1 IH2; subst e,
{ apply IHl },
{ apply IHr },
{ exact acc.inv (IH2 rfl) h1 }
end⟩
instance : has_well_founded pgame :=
{ r := subsequent,
wf := wf_subsequent }
/-- A move by Left produces a subsequent game. (For use in pgame_wf_tac.) -/
lemma subsequent.left_move {xl xr} {xL : xl → pgame} {xR : xr → pgame} {i : xl} :
subsequent (xL i) (mk xl xr xL xR) :=
subsequent.left (mk xl xr xL xR) i
/-- A move by Right produces a subsequent game. (For use in pgame_wf_tac.) -/
lemma subsequent.right_move {xl xr} {xL : xl → pgame} {xR : xr → pgame} {j : xr} :
subsequent (xR j) (mk xl xr xL xR) :=
subsequent.right (mk xl xr xL xR) j
/-- A local tactic for proving well-foundedness of recursive definitions involving pregames. -/
meta def pgame_wf_tac :=
`[solve_by_elim
[psigma.lex.left, psigma.lex.right,
subsequent.left_move, subsequent.right_move,
subsequent.left, subsequent.right, subsequent.trans]
{ max_depth := 6 }]
/-- The pre-game `zero` is defined by `0 = { | }`. -/
instance : has_zero pgame := ⟨⟨pempty, pempty, pempty.elim, pempty.elim⟩⟩
@[simp] lemma zero_left_moves : (0 : pgame).left_moves = pempty := rfl
@[simp] lemma zero_right_moves : (0 : pgame).right_moves = pempty := rfl
instance : inhabited pgame := ⟨0⟩
/-- The pre-game `one` is defined by `1 = { 0 | }`. -/
instance : has_one pgame := ⟨⟨punit, pempty, λ _, 0, pempty.elim⟩⟩
@[simp] lemma one_left_moves : (1 : pgame).left_moves = punit := rfl
@[simp] lemma one_move_left : (1 : pgame).move_left punit.star = 0 := rfl
@[simp] lemma one_right_moves : (1 : pgame).right_moves = pempty := rfl
/-- Define simultaneously by mutual induction the `<=` and `<`
relation on pre-games. The ZFC definition says that `x = {xL | xR}`
is less or equal to `y = {yL | yR}` if `∀ x₁ ∈ xL, x₁ < y`
and `∀ y₂ ∈ yR, x < y₂`, where `x < y` is the same as `¬ y <= x`.
This is a tricky induction because it only decreases one side at
a time, and it also swaps the arguments in the definition of `<`.
The solution is to define `x < y` and `x <= y` simultaneously. -/
def le_lt : Π (x y : pgame), Prop × Prop
| (mk xl xr xL xR) (mk yl yr yL yR) :=
-- the orderings of the clauses here are carefully chosen so that
-- and.left/or.inl refer to moves by Left, and
-- and.right/or.inr refer to moves by Right.
((∀ i : xl, (le_lt (xL i) ⟨yl, yr, yL, yR⟩).2) ∧ (∀ j : yr, (le_lt ⟨xl, xr, xL, xR⟩ (yR j)).2),
(∃ i : yl, (le_lt ⟨xl, xr, xL, xR⟩ (yL i)).1) ∨ (∃ j : xr, (le_lt (xR j) ⟨yl, yr, yL, yR⟩).1))
using_well_founded { dec_tac := pgame_wf_tac }
instance : has_le pgame := ⟨λ x y, (le_lt x y).1⟩
instance : has_lt pgame := ⟨λ x y, (le_lt x y).2⟩
/-- Definition of `x ≤ y` on pre-games built using the constructor. -/
@[simp] theorem mk_le_mk {xl xr xL xR yl yr yL yR} :
(⟨xl, xr, xL, xR⟩ : pgame) ≤ ⟨yl, yr, yL, yR⟩ ↔
(∀ i, xL i < ⟨yl, yr, yL, yR⟩) ∧
(∀ j, (⟨xl, xr, xL, xR⟩ : pgame) < yR j) :=
show (le_lt _ _).1 ↔ _, by { rw le_lt, refl }
/-- Definition of `x ≤ y` on pre-games, in terms of `<` -/
theorem le_def_lt {x y : pgame} : x ≤ y ↔
(∀ i : x.left_moves, x.move_left i < y) ∧
(∀ j : y.right_moves, x < y.move_right j) :=
by { cases x, cases y, rw mk_le_mk, refl }
/-- Definition of `x < y` on pre-games built using the constructor. -/
@[simp] theorem mk_lt_mk {xl xr xL xR yl yr yL yR} :
(⟨xl, xr, xL, xR⟩ : pgame) < ⟨yl, yr, yL, yR⟩ ↔
(∃ i, (⟨xl, xr, xL, xR⟩ : pgame) ≤ yL i) ∨
(∃ j, xR j ≤ ⟨yl, yr, yL, yR⟩) :=
show (le_lt _ _).2 ↔ _, by { rw le_lt, refl }
/-- Definition of `x < y` on pre-games, in terms of `≤` -/
theorem lt_def_le {x y : pgame} : x < y ↔
(∃ i : y.left_moves, x ≤ y.move_left i) ∨
(∃ j : x.right_moves, x.move_right j ≤ y) :=
by { cases x, cases y, rw mk_lt_mk, refl }
/-- The definition of `x ≤ y` on pre-games, in terms of `≤` two moves later. -/
theorem le_def {x y : pgame} : x ≤ y ↔
(∀ i : x.left_moves,
(∃ i' : y.left_moves, x.move_left i ≤ y.move_left i') ∨
(∃ j : (x.move_left i).right_moves, (x.move_left i).move_right j ≤ y)) ∧
(∀ j : y.right_moves,
(∃ i : (y.move_right j).left_moves, x ≤ (y.move_right j).move_left i) ∨
(∃ j' : x.right_moves, x.move_right j' ≤ y.move_right j)) :=
begin
rw [le_def_lt],
conv { to_lhs, simp only [lt_def_le] },
end
/-- The definition of `x < y` on pre-games, in terms of `<` two moves later. -/
theorem lt_def {x y : pgame} : x < y ↔
(∃ i : y.left_moves,
(∀ i' : x.left_moves, x.move_left i' < y.move_left i) ∧
(∀ j : (y.move_left i).right_moves, x < (y.move_left i).move_right j)) ∨
(∃ j : x.right_moves,
(∀ i : (x.move_right j).left_moves, (x.move_right j).move_left i < y) ∧
(∀ j' : y.right_moves, x.move_right j < y.move_right j')) :=
begin
rw [lt_def_le],
conv { to_lhs, simp only [le_def_lt] },
end
/-- The definition of `x ≤ 0` on pre-games, in terms of `≤ 0` two moves later. -/
theorem le_zero {x : pgame} : x ≤ 0 ↔
∀ i : x.left_moves, ∃ j : (x.move_left i).right_moves, (x.move_left i).move_right j ≤ 0 :=
begin
rw le_def,
dsimp,
simp [forall_pempty, exists_pempty]
end
/-- The definition of `0 ≤ x` on pre-games, in terms of `0 ≤` two moves later. -/
theorem zero_le {x : pgame} : 0 ≤ x ↔
∀ j : x.right_moves, ∃ i : (x.move_right j).left_moves, 0 ≤ (x.move_right j).move_left i :=
begin
rw le_def,
dsimp,
simp [forall_pempty, exists_pempty]
end
/-- The definition of `x < 0` on pre-games, in terms of `< 0` two moves later. -/
theorem lt_zero {x : pgame} : x < 0 ↔
∃ j : x.right_moves, ∀ i : (x.move_right j).left_moves, (x.move_right j).move_left i < 0 :=
begin
rw lt_def,
dsimp,
simp [forall_pempty, exists_pempty]
end
/-- The definition of `0 < x` on pre-games, in terms of `< x` two moves later. -/
theorem zero_lt {x : pgame} : 0 < x ↔
∃ i : x.left_moves, ∀ j : (x.move_left i).right_moves, 0 < (x.move_left i).move_right j :=
begin
rw lt_def,
dsimp,
simp [forall_pempty, exists_pempty]
end
/-- Given a right-player-wins game, provide a response to any move by left. -/
noncomputable def right_response {x : pgame} (h : x ≤ 0) (i : x.left_moves) :
(x.move_left i).right_moves :=
classical.some $ (le_zero.1 h) i
/-- Show that the response for right provided by `right_response`
preserves the right-player-wins condition. -/
lemma right_response_spec {x : pgame} (h : x ≤ 0) (i : x.left_moves) :
(x.move_left i).move_right (right_response h i) ≤ 0 :=
classical.some_spec $ (le_zero.1 h) i
/-- Given a left-player-wins game, provide a response to any move by right. -/
noncomputable def left_response {x : pgame} (h : 0 ≤ x) (j : x.right_moves) :
(x.move_right j).left_moves :=
classical.some $ (zero_le.1 h) j
/-- Show that the response for left provided by `left_response`
preserves the left-player-wins condition. -/
lemma left_response_spec {x : pgame} (h : 0 ≤ x) (j : x.right_moves) :
0 ≤ (x.move_right j).move_left (left_response h j) :=
classical.some_spec $ (zero_le.1 h) j
theorem lt_of_le_mk {xl xr xL xR y i} :
(⟨xl, xr, xL, xR⟩ : pgame) ≤ y → xL i < y :=
by { cases y, rw mk_le_mk, tauto }
theorem lt_of_mk_le {x : pgame} {yl yr yL yR i} :
x ≤ ⟨yl, yr, yL, yR⟩ → x < yR i :=
by { cases x, rw mk_le_mk, tauto }
theorem mk_lt_of_le {xl xr xL xR y i} :
(by exact xR i ≤ y) → (⟨xl, xr, xL, xR⟩ : pgame) < y :=
by { cases y, rw mk_lt_mk, tauto }
theorem lt_mk_of_le {x : pgame} {yl yr yL yR i} :
(by exact x ≤ yL i) → x < ⟨yl, yr, yL, yR⟩ :=
by { cases x, rw mk_lt_mk, exact λ h, or.inl ⟨_, h⟩ }
theorem not_le_lt {x y : pgame} :
(¬ x ≤ y ↔ y < x) ∧ (¬ x < y ↔ y ≤ x) :=
begin
induction x with xl xr xL xR IHxl IHxr generalizing y,
induction y with yl yr yL yR IHyl IHyr,
classical,
simp only [mk_le_mk, mk_lt_mk,
not_and_distrib, not_or_distrib, not_forall, not_exists,
and_comm, or_comm, IHxl, IHxr, IHyl, IHyr, iff_self, and_self]
end
theorem not_le {x y : pgame} : ¬ x ≤ y ↔ y < x := not_le_lt.1
theorem not_lt {x y : pgame} : ¬ x < y ↔ y ≤ x := not_le_lt.2
@[refl] theorem le_refl : ∀ x : pgame, x ≤ x
| ⟨l, r, L, R⟩ := by rw mk_le_mk; exact
⟨λ i, lt_mk_of_le (le_refl _), λ i, mk_lt_of_le (le_refl _)⟩
theorem lt_irrefl (x : pgame) : ¬ x < x :=
not_lt.2 (le_refl _)
theorem ne_of_lt : ∀ {x y : pgame}, x < y → x ≠ y
| x _ h rfl := lt_irrefl x h
theorem le_trans_aux
{xl xr} {xL : xl → pgame} {xR : xr → pgame}
{yl yr} {yL : yl → pgame} {yR : yr → pgame}
{zl zr} {zL : zl → pgame} {zR : zr → pgame}
(h₁ : ∀ i, mk yl yr yL yR ≤ mk zl zr zL zR → mk zl zr zL zR ≤ xL i → mk yl yr yL yR ≤ xL i)
(h₂ : ∀ i, zR i ≤ mk xl xr xL xR → mk xl xr xL xR ≤ mk yl yr yL yR → zR i ≤ mk yl yr yL yR) :
mk xl xr xL xR ≤ mk yl yr yL yR →
mk yl yr yL yR ≤ mk zl zr zL zR →
mk xl xr xL xR ≤ mk zl zr zL zR :=
by simp only [mk_le_mk] at *; exact
λ ⟨xLy, xyR⟩ ⟨yLz, yzR⟩, ⟨
λ i, not_le.1 (λ h, not_lt.2 (h₁ _ ⟨yLz, yzR⟩ h) (xLy _)),
λ i, not_le.1 (λ h, not_lt.2 (h₂ _ h ⟨xLy, xyR⟩) (yzR _))⟩
@[trans] theorem le_trans {x y z : pgame} : x ≤ y → y ≤ z → x ≤ z :=
suffices ∀ {x y z : pgame},
(x ≤ y → y ≤ z → x ≤ z) ∧ (y ≤ z → z ≤ x → y ≤ x) ∧ (z ≤ x → x ≤ y → z ≤ y),
from this.1, begin
clear x y z, intros,
induction x with xl xr xL xR IHxl IHxr generalizing y z,
induction y with yl yr yL yR IHyl IHyr generalizing z,
induction z with zl zr zL zR IHzl IHzr,
exact ⟨
le_trans_aux (λ i, (IHxl _).2.1) (λ i, (IHzr _).2.2),
le_trans_aux (λ i, (IHyl _).2.2) (λ i, (IHxr _).1),
le_trans_aux (λ i, (IHzl _).1) (λ i, (IHyr _).2.1)⟩,
end
@[trans] theorem lt_of_le_of_lt {x y z : pgame} (hxy : x ≤ y) (hyz : y < z) : x < z :=
begin
rw ←not_le at ⊢ hyz,
exact mt (λ H, le_trans H hxy) hyz
end
@[trans] theorem lt_of_lt_of_le {x y z : pgame} (hxy : x < y) (hyz : y ≤ z) : x < z :=
begin
rw ←not_le at ⊢ hxy,
exact mt (λ H, le_trans hyz H) hxy
end
/-- Define the equivalence relation on pre-games. Two pre-games
`x`, `y` are equivalent if `x ≤ y` and `y ≤ x`. -/
def equiv (x y : pgame) : Prop := x ≤ y ∧ y ≤ x
local infix ` ≈ ` := pgame.equiv
@[refl, simp] theorem equiv_refl (x) : x ≈ x := ⟨le_refl _, le_refl _⟩
@[symm] theorem equiv_symm {x y} : x ≈ y → y ≈ x | ⟨xy, yx⟩ := ⟨yx, xy⟩
@[trans] theorem equiv_trans {x y z} : x ≈ y → y ≈ z → x ≈ z
| ⟨xy, yx⟩ ⟨yz, zy⟩ := ⟨le_trans xy yz, le_trans zy yx⟩
theorem lt_of_lt_of_equiv {x y z} (h₁ : x < y) (h₂ : y ≈ z) : x < z := lt_of_lt_of_le h₁ h₂.1
theorem le_of_le_of_equiv {x y z} (h₁ : x ≤ y) (h₂ : y ≈ z) : x ≤ z := le_trans h₁ h₂.1
theorem lt_of_equiv_of_lt {x y z} (h₁ : x ≈ y) (h₂ : y < z) : x < z := lt_of_le_of_lt h₁.1 h₂
theorem le_of_equiv_of_le {x y z} (h₁ : x ≈ y) (h₂ : y ≤ z) : x ≤ z := le_trans h₁.1 h₂
theorem le_congr {x₁ y₁ x₂ y₂} : x₁ ≈ x₂ → y₁ ≈ y₂ → (x₁ ≤ y₁ ↔ x₂ ≤ y₂)
| ⟨x12, x21⟩ ⟨y12, y21⟩ := ⟨λ h, le_trans x21 (le_trans h y12), λ h, le_trans x12 (le_trans h y21)⟩
theorem lt_congr {x₁ y₁ x₂ y₂} (hx : x₁ ≈ x₂) (hy : y₁ ≈ y₂) : x₁ < y₁ ↔ x₂ < y₂ :=
not_le.symm.trans $ (not_congr (le_congr hy hx)).trans not_le
theorem equiv_congr_left {y₁ y₂} : y₁ ≈ y₂ ↔ ∀ x₁, x₁ ≈ y₁ ↔ x₁ ≈ y₂ :=
⟨λ h x₁, ⟨λ h', equiv_trans h' h, λ h', equiv_trans h' (equiv_symm h)⟩,
λ h, (h y₁).1 $ equiv_refl _⟩
theorem equiv_congr_right {x₁ x₂} : x₁ ≈ x₂ ↔ ∀ y₁, x₁ ≈ y₁ ↔ x₂ ≈ y₁ :=
⟨λ h y₁, ⟨λ h', equiv_trans (equiv_symm h) h', λ h', equiv_trans h h'⟩,
λ h, (h x₂).2 $ equiv_refl _⟩
/-- `restricted x y` says that Left always has no more moves in `x` than in `y`,
and Right always has no more moves in `y` than in `x` -/
inductive restricted : pgame.{u} → pgame.{u} → Type (u+1)
| mk : Π {x y : pgame} (L : x.left_moves → y.left_moves) (R : y.right_moves → x.right_moves),
(∀ (i : x.left_moves), restricted (x.move_left i) (y.move_left (L i))) →
(∀ (j : y.right_moves), restricted (x.move_right (R j)) (y.move_right j)) → restricted x y
/-- The identity restriction. -/
@[refl] def restricted.refl : Π (x : pgame), restricted x x
| (mk xl xr xL xR) :=
restricted.mk
id id
(λ i, restricted.refl _) (λ j, restricted.refl _)
using_well_founded { dec_tac := pgame_wf_tac }
-- TODO trans for restricted
theorem restricted.le : Π {x y : pgame} (r : restricted x y), x ≤ y
| (mk xl xr xL xR) (mk yl yr yL yR)
(restricted.mk L_embedding R_embedding L_restriction R_restriction) :=
begin
rw le_def,
exact
⟨λ i, or.inl ⟨L_embedding i, (L_restriction i).le⟩,
λ i, or.inr ⟨R_embedding i, (R_restriction i).le⟩⟩
end
/--
`relabelling x y` says that `x` and `y` are really the same game, just dressed up differently.
Specifically, there is a bijection between the moves for Left in `x` and in `y`, and similarly
for Right, and under these bijections we inductively have `relabelling`s for the consequent games.
-/
inductive relabelling : pgame.{u} → pgame.{u} → Type (u+1)
| mk : Π {x y : pgame} (L : x.left_moves ≃ y.left_moves) (R : x.right_moves ≃ y.right_moves),
(∀ (i : x.left_moves), relabelling (x.move_left i) (y.move_left (L i))) →
(∀ (j : y.right_moves), relabelling (x.move_right (R.symm j)) (y.move_right j)) →
relabelling x y
/-- If `x` is a relabelling of `y`, then Left and Right have the same moves in either game,
so `x` is a restriction of `y`. -/
def relabelling.restricted: Π {x y : pgame} (r : relabelling x y), restricted x y
| (mk xl xr xL xR) (mk yl yr yL yR) (relabelling.mk L_equiv R_equiv L_relabelling R_relabelling) :=
restricted.mk L_equiv.to_embedding R_equiv.symm.to_embedding
(λ i, (L_relabelling i).restricted)
(λ j, (R_relabelling j).restricted)
-- It's not the case that `restricted x y → restricted y x → relabelling x y`,
-- but if we insisted that the maps in a restriction were injective, then one
-- could use Schröder-Bernstein for do this.
/-- The identity relabelling. -/
@[refl] def relabelling.refl : Π (x : pgame), relabelling x x
| (mk xl xr xL xR) :=
relabelling.mk (equiv.refl _) (equiv.refl _)
(λ i, relabelling.refl _) (λ j, relabelling.refl _)
using_well_founded { dec_tac := pgame_wf_tac }
/-- Reverse a relabelling. -/
@[symm] def relabelling.symm : Π {x y : pgame}, relabelling x y → relabelling y x
| (mk xl xr xL xR) (mk yl yr yL yR) (relabelling.mk L_equiv R_equiv L_relabelling R_relabelling) :=
begin
refine relabelling.mk L_equiv.symm R_equiv.symm _ _,
{ intro i, simpa using (L_relabelling (L_equiv.symm i)).symm },
{ intro j, simpa using (R_relabelling (R_equiv j)).symm }
end
/-- Transitivity of relabelling -/
@[trans] def relabelling.trans :
Π {x y z : pgame}, relabelling x y → relabelling y z → relabelling x z
| (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR)
(relabelling.mk L_equiv₁ R_equiv₁ L_relabelling₁ R_relabelling₁)
(relabelling.mk L_equiv₂ R_equiv₂ L_relabelling₂ R_relabelling₂) :=
begin
refine relabelling.mk (L_equiv₁.trans L_equiv₂) (R_equiv₁.trans R_equiv₂) _ _,
{ intro i, simpa using (L_relabelling₁ _).trans (L_relabelling₂ _) },
{ intro j, simpa using (R_relabelling₁ _).trans (R_relabelling₂ _) },
end
theorem relabelling.le {x y : pgame} (r : relabelling x y) : x ≤ y :=
r.restricted.le
/-- A relabelling lets us prove equivalence of games. -/
theorem relabelling.equiv {x y : pgame} (r : relabelling x y) : x ≈ y :=
⟨r.le, r.symm.le⟩
instance {x y : pgame} : has_coe (relabelling x y) (x ≈ y) := ⟨relabelling.equiv⟩
/-- Replace the types indexing the next moves for Left and Right by equivalent types. -/
def relabel {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') :=
pgame.mk xl' xr' (λ i, x.move_left (el.symm i)) (λ j, x.move_right (er.symm j))
@[simp] lemma relabel_move_left' {x : pgame} {xl' xr'}
(el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (i : xl') :
move_left (relabel el er) i = x.move_left (el.symm i) :=
rfl
@[simp] lemma relabel_move_left {x : pgame} {xl' xr'}
(el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (i : x.left_moves) :
move_left (relabel el er) (el i) = x.move_left i :=
by simp
@[simp] lemma relabel_move_right' {x : pgame} {xl' xr'}
(el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (j : xr') :
move_right (relabel el er) j = x.move_right (er.symm j) :=
rfl
@[simp] lemma relabel_move_right {x : pgame} {xl' xr'}
(el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') (j : x.right_moves) :
move_right (relabel el er) (er j) = x.move_right j :=
by simp
/-- The game obtained by relabelling the next moves is a relabelling of the original game. -/
def relabel_relabelling {x : pgame} {xl' xr'} (el : x.left_moves ≃ xl') (er : x.right_moves ≃ xr') :
relabelling x (relabel el er) :=
relabelling.mk el er (λ i, by simp) (λ j, by simp)
/-- The negation of `{L | R}` is `{-R | -L}`. -/
def neg : pgame → pgame
| ⟨l, r, L, R⟩ := ⟨r, l, λ i, neg (R i), λ i, neg (L i)⟩
instance : has_neg pgame := ⟨neg⟩
@[simp] lemma neg_def {xl xr xL xR} : -(mk xl xr xL xR) = mk xr xl (λ j, -(xR j)) (λ i, -(xL i)) :=
rfl
@[simp] theorem neg_neg : Π {x : pgame}, -(-x) = x
| (mk xl xr xL xR) :=
begin
dsimp [has_neg.neg, neg],
congr; funext i; apply neg_neg
end
@[simp] theorem neg_zero : -(0 : pgame) = 0 :=
begin
dsimp [has_zero.zero, has_neg.neg, neg],
congr; funext i; cases i
end
/-- An explicit equivalence between the moves for Left in `-x` and the moves for Right in `x`. -/
-- This equivalence is useful to avoid having to use `cases` unnecessarily.
def left_moves_neg (x : pgame) : (-x).left_moves ≃ x.right_moves :=
by { cases x, refl }
/-- An explicit equivalence between the moves for Right in `-x` and the moves for Left in `x`. -/
def right_moves_neg (x : pgame) : (-x).right_moves ≃ x.left_moves :=
by { cases x, refl }
@[simp] lemma move_right_left_moves_neg {x : pgame} (i : left_moves (-x)) :
move_right x ((left_moves_neg x) i) = -(move_left (-x) i) :=
begin
induction x,
exact neg_neg.symm
end
@[simp] lemma move_left_left_moves_neg_symm {x : pgame} (i : right_moves x) :
move_left (-x) ((left_moves_neg x).symm i) = -(move_right x i) :=
by { cases x, refl }
@[simp] lemma move_left_right_moves_neg {x : pgame} (i : right_moves (-x)) :
move_left x ((right_moves_neg x) i) = -(move_right (-x) i) :=
begin
induction x,
exact neg_neg.symm
end
@[simp] lemma move_right_right_moves_neg_symm {x : pgame} (i : left_moves x) :
move_right (-x) ((right_moves_neg x).symm i) = -(move_left x i) :=
by { cases x, refl }
/-- If `x` has the same moves as `y`, then `-x` has the sames moves as `-y`. -/
def relabelling.neg_congr : ∀ {x y : pgame}, x.relabelling y → (-x).relabelling (-y)
| (mk xl xr xL xR) (mk yl yr yL yR) ⟨L_equiv, R_equiv, L_relabelling, R_relabelling⟩ :=
⟨R_equiv, L_equiv,
λ i, relabelling.neg_congr (by simpa using R_relabelling (R_equiv i)),
λ i, relabelling.neg_congr (by simpa using L_relabelling (L_equiv.symm i))⟩
theorem le_iff_neg_ge : Π {x y : pgame}, x ≤ y ↔ -y ≤ -x
| (mk xl xr xL xR) (mk yl yr yL yR) :=
begin
rw [le_def],
rw [le_def],
dsimp [neg],
split,
{ intro h,
split,
{ intro i, have t := h.right i, cases t,
{ right, cases t,
use (@right_moves_neg (yR i)).symm t_w, convert le_iff_neg_ge.1 t_h, simp },
{ left, cases t,
use t_w, exact le_iff_neg_ge.1 t_h, } },
{ intro j, have t := h.left j, cases t,
{ right, cases t,
use t_w, exact le_iff_neg_ge.1 t_h, },
{ left, cases t,
use (@left_moves_neg (xL j)).symm t_w, convert le_iff_neg_ge.1 t_h, simp, } } },
{ intro h,
split,
{ intro i, have t := h.right i, cases t,
{ right, cases t,
use (@left_moves_neg (xL i)) t_w, convert le_iff_neg_ge.2 _, convert t_h, simp, },
{ left, cases t,
use t_w, exact le_iff_neg_ge.2 t_h, } },
{ intro j, have t := h.left j, cases t,
{ right, cases t,
use t_w, exact le_iff_neg_ge.2 t_h, },
{ left, cases t,
use (@right_moves_neg (yR j)) t_w, convert le_iff_neg_ge.2 _, convert t_h, simp } } },
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem neg_congr {x y : pgame} (h : x ≈ y) : -x ≈ -y :=
⟨le_iff_neg_ge.1 h.2, le_iff_neg_ge.1 h.1⟩
theorem lt_iff_neg_gt : Π {x y : pgame}, x < y ↔ -y < -x :=
begin
classical,
intros,
rw [←not_le, ←not_le, not_iff_not],
apply le_iff_neg_ge
end
theorem zero_le_iff_neg_le_zero {x : pgame} : 0 ≤ x ↔ -x ≤ 0 :=
begin
convert le_iff_neg_ge,
rw neg_zero
end
theorem le_zero_iff_zero_le_neg {x : pgame} : x ≤ 0 ↔ 0 ≤ -x :=
begin
convert le_iff_neg_ge,
rw neg_zero
end
/-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/
def add (x y : pgame) : pgame :=
begin
induction x with xl xr xL xR IHxl IHxr generalizing y,
induction y with yl yr yL yR IHyl IHyr,
have y := mk yl yr yL yR,
refine ⟨xl ⊕ yl, xr ⊕ yr, sum.rec _ _, sum.rec _ _⟩,
{ exact λ i, IHxl i y },
{ exact λ i, IHyl i },
{ exact λ i, IHxr i y },
{ exact λ i, IHyr i }
end
instance : has_add pgame := ⟨add⟩
/-- `x + 0` has exactly the same moves as `x`. -/
def add_zero_relabelling : Π (x : pgame.{u}), relabelling (x + 0) x
| (mk xl xr xL xR) :=
begin
refine ⟨equiv.sum_pempty xl, equiv.sum_pempty xr, _, _⟩,
{ rintro (⟨i⟩|⟨⟨⟩⟩),
apply add_zero_relabelling, },
{ rintro j,
apply add_zero_relabelling, }
end
/-- `x + 0` is equivalent to `x`. -/
lemma add_zero_equiv (x : pgame.{u}) : x + 0 ≈ x :=
(add_zero_relabelling x).equiv
/-- `0 + x` has exactly the same moves as `x`. -/
def zero_add_relabelling : Π (x : pgame.{u}), relabelling (0 + x) x
| (mk xl xr xL xR) :=
begin
refine ⟨equiv.pempty_sum xl, equiv.pempty_sum xr, _, _⟩,
{ rintro (⟨⟨⟩⟩|⟨i⟩),
apply zero_add_relabelling, },
{ rintro j,
apply zero_add_relabelling, }
end
/-- `0 + x` is equivalent to `x`. -/
lemma zero_add_equiv (x : pgame.{u}) : 0 + x ≈ x :=
(zero_add_relabelling x).equiv
/-- An explicit equivalence between the moves for Left in `x + y` and the type-theory sum
of the moves for Left in `x` and in `y`. -/
def left_moves_add (x y : pgame) : (x + y).left_moves ≃ x.left_moves ⊕ y.left_moves :=
by { cases x, cases y, refl, }
/-- An explicit equivalence between the moves for Right in `x + y` and the type-theory sum
of the moves for Right in `x` and in `y`. -/
def right_moves_add (x y : pgame) : (x + y).right_moves ≃ x.right_moves ⊕ y.right_moves :=
by { cases x, cases y, refl, }
@[simp] lemma mk_add_move_left_inl {xl xr yl yr} {xL xR yL yR} {i} :
(mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inl i) =
(mk xl xr xL xR).move_left i + (mk yl yr yL yR) :=
rfl
@[simp] lemma add_move_left_inl {x y : pgame} {i} :
(x + y).move_left ((@left_moves_add x y).symm (sum.inl i)) = x.move_left i + y :=
by { cases x, cases y, refl, }
@[simp] lemma mk_add_move_right_inl {xl xr yl yr} {xL xR yL yR} {i} :
(mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inl i) =
(mk xl xr xL xR).move_right i + (mk yl yr yL yR) :=
rfl
@[simp] lemma add_move_right_inl {x y : pgame} {i} :
(x + y).move_right ((@right_moves_add x y).symm (sum.inl i)) = x.move_right i + y :=
by { cases x, cases y, refl, }
@[simp] lemma mk_add_move_left_inr {xl xr yl yr} {xL xR yL yR} {i} :
(mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inr i) =
(mk xl xr xL xR) + (mk yl yr yL yR).move_left i :=
rfl
@[simp] lemma add_move_left_inr {x y : pgame} {i : y.left_moves} :
(x + y).move_left ((@left_moves_add x y).symm (sum.inr i)) = x + y.move_left i :=
by { cases x, cases y, refl, }
@[simp] lemma mk_add_move_right_inr {xl xr yl yr} {xL xR yL yR} {i} :
(mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inr i) =
(mk xl xr xL xR) + (mk yl yr yL yR).move_right i :=
rfl
@[simp] lemma add_move_right_inr {x y : pgame} {i} :
(x + y).move_right ((@right_moves_add x y).symm (sum.inr i)) = x + y.move_right i :=
by { cases x, cases y, refl, }
/-- If `w` has the same moves as `x` and `y` has the same moves as `z`,
then `w + y` has the same moves as `x + z`. -/
def relabelling.add_congr : ∀ {w x y z : pgame.{u}},
w.relabelling x → y.relabelling z → (w + y).relabelling (x + z)
| (mk wl wr wL wR) (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR)
⟨L_equiv₁, R_equiv₁, L_relabelling₁, R_relabelling₁⟩
⟨L_equiv₂, R_equiv₂, L_relabelling₂, R_relabelling₂⟩ :=
begin
refine ⟨equiv.sum_congr L_equiv₁ L_equiv₂, equiv.sum_congr R_equiv₁ R_equiv₂, _, _⟩,
{ rintro (i|j),
{ exact relabelling.add_congr
(L_relabelling₁ i)
(⟨L_equiv₂, R_equiv₂, L_relabelling₂, R_relabelling₂⟩) },
{ exact relabelling.add_congr
(⟨L_equiv₁, R_equiv₁, L_relabelling₁, R_relabelling₁⟩)
(L_relabelling₂ j) }},
{ rintro (i|j),
{ exact relabelling.add_congr
(R_relabelling₁ i)
(⟨L_equiv₂, R_equiv₂, L_relabelling₂, R_relabelling₂⟩) },
{ exact relabelling.add_congr
(⟨L_equiv₁, R_equiv₁, L_relabelling₁, R_relabelling₁⟩)
(R_relabelling₂ j) }}
end
using_well_founded { dec_tac := pgame_wf_tac }
instance : has_sub pgame := ⟨λ x y, x + -y⟩
/-- If `w` has the same moves as `x` and `y` has the same moves as `z`,
then `w - y` has the same moves as `x - z`. -/
def relabelling.sub_congr {w x y z : pgame}
(h₁ : w.relabelling x) (h₂ : y.relabelling z) : (w - y).relabelling (x - z) :=
h₁.add_congr h₂.neg_congr
/-- `-(x+y)` has exactly the same moves as `-x + -y`. -/
def neg_add_relabelling : Π (x y : pgame), relabelling (-(x + y)) (-x + -y)
| (mk xl xr xL xR) (mk yl yr yL yR) :=
⟨equiv.refl _, equiv.refl _,
λ j, sum.cases_on j
(λ j, neg_add_relabelling (xR j) (mk yl yr yL yR))
(λ j, neg_add_relabelling (mk xl xr xL xR) (yR j)),
λ i, sum.cases_on i
(λ i, neg_add_relabelling (xL i) (mk yl yr yL yR))
(λ i, neg_add_relabelling (mk xl xr xL xR) (yL i))⟩
using_well_founded { dec_tac := pgame_wf_tac }
theorem neg_add_le {x y : pgame} : -(x + y) ≤ -x + -y :=
(neg_add_relabelling x y).le
/-- `x+y` has exactly the same moves as `y+x`. -/
def add_comm_relabelling : Π (x y : pgame.{u}), relabelling (x + y) (y + x)
| (mk xl xr xL xR) (mk yl yr yL yR) :=
begin
refine ⟨equiv.sum_comm _ _, equiv.sum_comm _ _, _, _⟩;
rintros (_|_);
{ simp [left_moves_add, right_moves_add], apply add_comm_relabelling }
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem add_comm_le {x y : pgame} : x + y ≤ y + x :=
(add_comm_relabelling x y).le
theorem add_comm_equiv {x y : pgame} : x + y ≈ y + x :=
(add_comm_relabelling x y).equiv
/-- `(x + y) + z` has exactly the same moves as `x + (y + z)`. -/
def add_assoc_relabelling : Π (x y z : pgame.{u}), relabelling ((x + y) + z) (x + (y + z))
| (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) :=
begin
refine ⟨equiv.sum_assoc _ _ _, equiv.sum_assoc _ _ _, _, _⟩,
{ rintro (⟨i|i⟩|i),
{ apply add_assoc_relabelling, },
{ change relabelling
(mk xl xr xL xR + yL i + mk zl zr zL zR) (mk xl xr xL xR + (yL i + mk zl zr zL zR)),
apply add_assoc_relabelling, },
{ change relabelling
(mk xl xr xL xR + mk yl yr yL yR + zL i) (mk xl xr xL xR + (mk yl yr yL yR + zL i)),
apply add_assoc_relabelling, } },
{ rintro (j|⟨j|j⟩),
{ apply add_assoc_relabelling, },
{ change relabelling
(mk xl xr xL xR + yR j + mk zl zr zL zR) (mk xl xr xL xR + (yR j + mk zl zr zL zR)),
apply add_assoc_relabelling, },
{ change relabelling
(mk xl xr xL xR + mk yl yr yL yR + zR j) (mk xl xr xL xR + (mk yl yr yL yR + zR j)),
apply add_assoc_relabelling, } },
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem add_assoc_equiv {x y z : pgame} : (x + y) + z ≈ x + (y + z) :=
(add_assoc_relabelling x y z).equiv
theorem add_le_add_right : Π {x y z : pgame} (h : x ≤ y), x + z ≤ y + z
| (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) :=
begin
intros h,
rw le_def,
split,
{ -- if Left plays first
intros i,
change xl ⊕ zl at i,
cases i,
{ -- either they play in x
rw le_def at h,
cases h,
have t := h_left i,
rcases t with ⟨i', ih⟩ | ⟨j, jh⟩,
{ left,
refine ⟨(left_moves_add _ _).inv_fun (sum.inl i'), _⟩,
exact add_le_add_right ih, },
{ right,
refine ⟨(right_moves_add _ _).inv_fun (sum.inl j), _⟩,
convert add_le_add_right jh,
apply add_move_right_inl },
},
{ -- or play in z
left,
refine ⟨(left_moves_add _ _).inv_fun (sum.inr i), _⟩,
exact add_le_add_right h, }, },
{ -- if Right plays first
intros j,
change yr ⊕ zr at j,
cases j,
{ -- either they play in y
rw le_def at h,
cases h,
have t := h_right j,
rcases t with ⟨i, ih⟩ | ⟨j', jh⟩,
{ left,
refine ⟨(left_moves_add _ _).inv_fun (sum.inl i), _⟩,
convert add_le_add_right ih,
apply add_move_left_inl },
{ right,
refine ⟨(right_moves_add _ _).inv_fun (sum.inl j'), _⟩,
exact add_le_add_right jh } },
{ -- or play in z
right,
refine ⟨(right_moves_add _ _).inv_fun (sum.inr j), _⟩,
exact add_le_add_right h } }
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem add_le_add_left {x y z : pgame} (h : y ≤ z) : x + y ≤ x + z :=
calc x + y ≤ y + x : add_comm_le
... ≤ z + x : add_le_add_right h
... ≤ x + z : add_comm_le
theorem add_congr {w x y z : pgame} (h₁ : w ≈ x) (h₂ : y ≈ z) : w + y ≈ x + z :=
⟨calc w + y ≤ w + z : add_le_add_left h₂.1
... ≤ x + z : add_le_add_right h₁.1,
calc x + z ≤ x + y : add_le_add_left h₂.2
... ≤ w + y : add_le_add_right h₁.2⟩
theorem add_left_neg_le_zero : Π {x : pgame}, (-x) + x ≤ 0
| ⟨xl, xr, xL, xR⟩ :=
begin
rw [le_def],
split,
{ intro i,
change xr ⊕ xl at i,
cases i,
{ -- If Left played in -x, Right responds with the same move in x.
right,
refine ⟨(right_moves_add _ _).inv_fun (sum.inr i), _⟩,
convert @add_left_neg_le_zero (xR i),
exact add_move_right_inr },
{ -- If Left in x, Right responds with the same move in -x.
right,
dsimp,
refine ⟨(right_moves_add _ _).inv_fun (sum.inl i), _⟩,
convert @add_left_neg_le_zero (xL i),
exact add_move_right_inl }, },
{ rintro ⟨⟩, }
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem zero_le_add_left_neg : Π {x : pgame}, 0 ≤ (-x) + x :=
begin
intro x,
rw [le_iff_neg_ge, neg_zero],
exact le_trans neg_add_le add_left_neg_le_zero
end
theorem add_left_neg_equiv {x : pgame} : (-x) + x ≈ 0 :=
⟨add_left_neg_le_zero, zero_le_add_left_neg⟩
theorem add_right_neg_le_zero {x : pgame} : x + (-x) ≤ 0 :=
calc x + (-x) ≤ (-x) + x : add_comm_le
... ≤ 0 : add_left_neg_le_zero
theorem zero_le_add_right_neg {x : pgame} : 0 ≤ x + (-x) :=
calc 0 ≤ (-x) + x : zero_le_add_left_neg
... ≤ x + (-x) : add_comm_le
theorem add_lt_add_right {x y z : pgame} (h : x < y) : x + z < y + z :=
suffices y + z ≤ x + z → y ≤ x, by { rw ←not_le at ⊢ h, exact mt this h },
assume w,
calc y ≤ y + 0 : (add_zero_relabelling _).symm.le
... ≤ y + (z + -z) : add_le_add_left zero_le_add_right_neg
... ≤ (y + z) + (-z) : (add_assoc_relabelling _ _ _).symm.le
... ≤ (x + z) + (-z) : add_le_add_right w
... ≤ x + (z + -z) : (add_assoc_relabelling _ _ _).le
... ≤ x + 0 : add_le_add_left add_right_neg_le_zero
... ≤ x : (add_zero_relabelling _).le
theorem add_lt_add_left {x y z : pgame} (h : y < z) : x + y < x + z :=
calc x + y ≤ y + x : add_comm_le
... < z + x : add_lt_add_right h
... ≤ x + z : add_comm_le
theorem le_iff_sub_nonneg {x y : pgame} : x ≤ y ↔ 0 ≤ y - x :=
⟨λ h, le_trans zero_le_add_right_neg (add_le_add_right h),
λ h,
calc x ≤ 0 + x : (zero_add_relabelling x).symm.le
... ≤ (y - x) + x : add_le_add_right h
... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le
... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero)
... ≤ y : (add_zero_relabelling y).le⟩
theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x :=
⟨λ h, lt_of_le_of_lt zero_le_add_right_neg (add_lt_add_right h),
λ h,
calc x ≤ 0 + x : (zero_add_relabelling x).symm.le
... < (y - x) + x : add_lt_add_right h
... ≤ y + (-x + x) : (add_assoc_relabelling _ _ _).le
... ≤ y + 0 : add_le_add_left (add_left_neg_le_zero)
... ≤ y : (add_zero_relabelling y).le⟩
/-- The pre-game `star`, which is fuzzy/confused with zero. -/
def star : pgame := pgame.of_lists [0] [0]
theorem star_lt_zero : star < 0 :=
by rw lt_def; exact
or.inr ⟨⟨0, zero_lt_one⟩, (by split; rintros ⟨⟩)⟩
theorem zero_lt_star : 0 < star :=
by rw lt_def; exact
or.inl ⟨⟨0, zero_lt_one⟩, (by split; rintros ⟨⟩)⟩
/-- The pre-game `ω`. (In fact all ordinals have game and surreal representatives.) -/
def omega : pgame := ⟨ulift ℕ, pempty, λ n, ↑n.1, pempty.elim⟩
end pgame
|
68a4449106d7846a69cea1a0a82be61cf3ccf594
|
35677d2df3f081738fa6b08138e03ee36bc33cad
|
/src/topology/uniform_space/uniform_convergence.lean
|
e392848b8f21db40cec8d334369414e6167b59a4
|
[
"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
| 16,752
|
lean
|
/-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.uniform_space.basic
/-!
# Uniform convergence
A sequence of functions `Fₙ` (with values in a metric space) converges uniformly on a set `s` to a
function `f` if, for all `ε > 0`, for all large enough `n`, one has for all `y ∈ s` the inequality
`dist (f y, Fₙ y) < ε`. Under uniform convergence, many properties of the `Fₙ` pass to the limit,
most notably continuity. We prove this in the file, defining the notion of uniform convergence
in the more general setting of uniform spaces, and with respect to an arbitrary indexing set
endowed with a filter (instead of just `ℕ` with `at_top`).
## Main results
Let `α` be a topological space, `β` a uniform space, `Fₙ` and `f` be functions from `α`to `β`
(where the index `n` belongs to an indexing type `ι` endowed with a filter `p`).
* `tendsto_uniformly_on F f p s`: the fact that `Fₙ` converges uniformly to `f` on `s`. This means
that, for any entourage `u` of the diagonal, for large enough `n` (with respect to `p`), one has
`(f y, Fₙ y) ∈ u` for all `y ∈ s`.
* `tendsto_uniformly F f p`: same notion with `s = univ`.
* `tendsto_uniformly_on.continuous_on`: a uniform limit on a set of functions which are continuous
on this set is itself continuous on this set.
* `tendsto_uniformly.continuous`: a uniform limit of continuous functions is continuous.
* `tendsto_uniformly_on.tendsto_comp`: If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends
to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s`.
* `tendsto_uniformly.tendsto_comp`: If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then
`Fₙ gₙ` tends to `f x`.
We also define notions where the convergence is locally uniform, called
`tendsto_locally_uniformly_on F f p s` and `tendsto_locally_uniformly F f p`. The previous theorems
all have corresponding versions under locally uniform convergence.
## Implementation notes
Most results hold under weaker assumptions of locally uniform approximation. In a first section,
we prove the results under these weaker assumptions. Then, we derive the results on uniform
convergence from them.
## Tags
Uniform limit, uniform convergence, tends uniformly to
-/
noncomputable theory
open_locale topological_space classical uniformity
open set filter
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-!
### Different notions of uniform convergence
We define uniform convergence and locally uniform convergence, on a set or in the whole space.
-/
variables {ι : Type*} [uniform_space β]
{F : ι → α → β} {f : α → β} {s s' : set α} {x : α} {p : filter ι} {g : ι → α}
/-- A sequence of functions `Fₙ` converges uniformly on a set `s` to a limiting function `f` with
respect to the filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually
`(f x, Fₙ x) ∈ u` for all `x ∈ s`. -/
def tendsto_uniformly_on (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) :=
∀ u ∈ 𝓤 β, ∀ᶠ n in p, ∀ x ∈ s, (f x, F n x) ∈ u
/-- A sequence of functions `Fₙ` converges uniformly to a limiting function `f` with respect to a
filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually
`(f x, Fₙ x) ∈ u` for all `x`. -/
def tendsto_uniformly (F : ι → α → β) (f : α → β) (p : filter ι) :=
∀ u ∈ 𝓤 β, ∀ᶠ n in p, ∀ x, (f x, F n x) ∈ u
lemma tendsto_uniformly_on_univ :
tendsto_uniformly_on F f p univ ↔ tendsto_uniformly F f p :=
by simp [tendsto_uniformly_on, tendsto_uniformly]
lemma tendsto_uniformly_on.mono {s' : set α}
(h : tendsto_uniformly_on F f p s) (h' : s' ⊆ s) : tendsto_uniformly_on F f p s' :=
λ u hu, (h u hu).mono (λ n hn x hx, hn x (h' hx))
lemma tendsto_uniformly.tendsto_uniformly_on
(h : tendsto_uniformly F f p) : tendsto_uniformly_on F f p s :=
(tendsto_uniformly_on_univ.2 h).mono (subset_univ s)
/-- Composing on the right by a function preserves uniform convergence on a set -/
lemma tendsto_uniformly_on.comp (h : tendsto_uniformly_on F f p s) (g : γ → α) :
tendsto_uniformly_on (λ n, F n ∘ g) (f ∘ g) p (g ⁻¹' s) :=
begin
assume u hu,
apply (h u hu).mono (λ n hn, _),
exact λ x hx, hn _ hx
end
/-- Composing on the right by a function preserves uniform convergence -/
lemma tendsto_uniformly.comp (h : tendsto_uniformly F f p) (g : γ → α) :
tendsto_uniformly (λ n, F n ∘ g) (f ∘ g) p :=
begin
assume u hu,
apply (h u hu).mono (λ n hn, _),
exact λ x, hn _
end
variable [topological_space α]
/-- A sequence of functions `Fₙ` converges locally uniformly on a set `s` to a limiting function
`f` with respect to a filter `p` if, for any entourage of the diagonal `u`, for any `x ∈ s`, one
has `p`-eventually `(f x, Fₙ x) ∈ u` for all `y` in a neighborhood of `x` in `s`. -/
def tendsto_locally_uniformly_on (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) :=
∀ u ∈ 𝓤 β, ∀ x ∈ s, ∃ t ∈ nhds_within x s, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u
/-- A sequence of functions `Fₙ` converges locally uniformly to a limiting function `f` with respect
to a filter `p` if, for any entourage of the diagonal `u`, for any `x`, one has `p`-eventually
`(f x, Fₙ x) ∈ u` for all `y` in a neighborhood of `x`. -/
def tendsto_locally_uniformly (F : ι → α → β) (f : α → β) (p : filter ι) :=
∀ u ∈ 𝓤 β, ∀ (x : α), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u
lemma tendsto_uniformly_on.tendsto_locally_uniformly_on
(h : tendsto_uniformly_on F f p s) : tendsto_locally_uniformly_on F f p s :=
λ u hu x hx, ⟨s, self_mem_nhds_within, h u hu⟩
lemma tendsto_uniformly.tendsto_locally_uniformly
(h : tendsto_uniformly F f p) : tendsto_locally_uniformly F f p :=
λ u hu x, ⟨univ, univ_mem_sets, by simpa using h u hu⟩
lemma tendsto_locally_uniformly_on.mono (h : tendsto_locally_uniformly_on F f p s) (h' : s' ⊆ s) :
tendsto_locally_uniformly_on F f p s' :=
begin
assume u hu x hx,
rcases h u hu x (h' hx) with ⟨t, ht, H⟩,
exact ⟨t, nhds_within_mono x h' ht, H.mono (λ n, id)⟩
end
lemma tendsto_locally_uniformly_on_univ :
tendsto_locally_uniformly_on F f p univ ↔ tendsto_locally_uniformly F f p :=
by simp [tendsto_locally_uniformly_on, tendsto_locally_uniformly, nhds_within_univ]
lemma tendsto_locally_uniformly_on.comp [topological_space γ] {t : set γ}
(h : tendsto_locally_uniformly_on F f p s)
(g : γ → α) (hg : maps_to g t s) (cg : continuous_on g t) :
tendsto_locally_uniformly_on (λ n, (F n) ∘ g) (f ∘ g) p t :=
begin
assume u hu x hx,
rcases h u hu (g x) (hg hx) with ⟨a, ha, H⟩,
have : g⁻¹' a ∈ nhds_within x t :=
((cg x hx).preimage_mem_nhds_within' (nhds_within_mono (g x) hg.image_subset ha)),
exact ⟨g ⁻¹' a, this, H.mono (λ n hn y hy, hn _ hy)⟩
end
lemma tendsto_locally_uniformly.comp [topological_space γ]
(h : tendsto_locally_uniformly F f p) (g : γ → α) (cg : continuous g) :
tendsto_locally_uniformly (λ n, (F n) ∘ g) (f ∘ g) p :=
begin
rw ← tendsto_locally_uniformly_on_univ at h ⊢,
rw continuous_iff_continuous_on_univ at cg,
exact h.comp _ (maps_to_univ _ _) cg
end
/-!
### Uniform approximation
In this section, we give lemmas ensuring that a function is continuous if it can be approximated
uniformly by continuous functions. We give various versions, within a set or the whole space, at
a single point or at all points, with locally uniform approximation or uniform approximation. All
the statements are derived from a statement about locally uniform approximation within a set at
a point, called `continuous_within_at_of_locally_uniform_approx_of_continuous_within_at`. -/
/-- A function which can be locally uniformly approximated by functions which are continuous
within a set at a point is continuous within this set at this point. -/
lemma continuous_within_at_of_locally_uniform_approx_of_continuous_within_at
(hx : x ∈ s) (L : ∀ u ∈ 𝓤 β, ∃ t ∈ nhds_within x s, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u)
(C : ∀ n, continuous_within_at (F n) s x) : continuous_within_at f s x :=
begin
apply uniform.continuous_within_at_iff'_left.2 (λ u₀ hu₀, _),
obtain ⟨u₁, h₁, u₁₀⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), comp_rel u u ⊆ u₀ :=
comp_mem_uniformity_sets hu₀,
obtain ⟨u₂, h₂, hsymm, u₂₁⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β),
(∀{a b}, (a, b) ∈ u → (b, a) ∈ u) ∧ comp_rel u u ⊆ u₁ := comp_symm_of_uniformity h₁,
rcases L u₂ h₂ with ⟨t, tx, n, ht⟩,
have A : ∀ᶠ y in nhds_within x s, (f y, F n y) ∈ u₂ := eventually.mono tx ht,
have B : ∀ᶠ y in nhds_within x s, (F n y, F n x) ∈ u₂ :=
uniform.continuous_within_at_iff'_left.1 (C n) h₂,
have C : ∀ᶠ y in nhds_within x s, (f y, F n x) ∈ u₁ :=
(A.and B).mono (λ y hy, u₂₁ (prod_mk_mem_comp_rel hy.1 hy.2)),
have : (F n x, f x) ∈ u₁ :=
u₂₁ (prod_mk_mem_comp_rel (refl_mem_uniformity h₂) (hsymm (A.self_of_nhds_within hx))),
exact C.mono (λ y hy, u₁₀ (prod_mk_mem_comp_rel hy this))
end
/-- A function which can be locally uniformly approximated by functions which are continuous at
a point is continuous at this point. -/
lemma continuous_at_of_locally_uniform_approx_of_continuous_at
(L : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous_at (F n) x) :
continuous_at f x :=
begin
simp only [← continuous_within_at_univ] at C ⊢,
apply continuous_within_at_of_locally_uniform_approx_of_continuous_within_at (mem_univ _) _ C,
simpa [nhds_within_univ] using L
end
/-- A function which can be locally uniformly approximated by functions which are continuous
on a set is continuous on this set. -/
lemma continuous_on_of_locally_uniform_approx_of_continuous_on
(L : ∀ (x ∈ s) (u ∈ 𝓤 β), ∃t ∈ nhds_within x s, ∃n, ∀ y ∈ t, (f y, F n y) ∈ u)
(C : ∀ n, continuous_on (F n) s) : continuous_on f s :=
λ x hx, continuous_within_at_of_locally_uniform_approx_of_continuous_within_at hx
(L x hx) (λ n, C n x hx)
/-- A function which can be uniformly approximated by functions which are continuous on a set
is continuous on this set. -/
lemma continuous_on_of_uniform_approx_of_continuous_on
(L : ∀ u ∈ 𝓤 β, ∃ n, ∀ y ∈ s, (f y, F n y) ∈ u) :
(∀ n, continuous_on (F n) s) → continuous_on f s :=
continuous_on_of_locally_uniform_approx_of_continuous_on
(λ x hx u hu, ⟨s, self_mem_nhds_within, L u hu⟩)
/-- A function which can be locally uniformly approximated by continuous functions is continuous. -/
lemma continuous_of_locally_uniform_approx_of_continuous
(L : ∀ (x : α), ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u)
(C : ∀ n, continuous (F n)) : continuous f :=
begin
simp only [continuous_iff_continuous_on_univ] at ⊢ C,
apply continuous_on_of_locally_uniform_approx_of_continuous_on _ C,
simpa [nhds_within_univ] using L
end
/-- A function which can be uniformly approximated by continuous functions is continuous. -/
lemma continuous_of_uniform_approx_of_continuous (L : ∀ u ∈ 𝓤 β, ∃ N, ∀ y, (f y, F N y) ∈ u) :
(∀ n, continuous (F n)) → continuous f :=
continuous_of_locally_uniform_approx_of_continuous $ λx u hu,
⟨univ, by simpa [filter.univ_mem_sets] using L u hu⟩
/-!
### Uniform limits
From the previous statements on uniform approximation, we deduce continuity results for uniform
limits.
-/
/-- A locally uniform limit on a set of functions which are continuous on this set is itself
continuous on this set. -/
lemma tendsto_locally_uniformly_on.continuous_on (h : tendsto_locally_uniformly_on F f p s)
(hc : ∀ n, continuous_on (F n) s) (hp : p ≠ ⊥) : continuous_on f s :=
begin
apply continuous_on_of_locally_uniform_approx_of_continuous_on (λ x hx u hu, _) hc,
rcases h u hu x hx with ⟨t, ht, H⟩,
exact ⟨t, ht, H.exists hp⟩
end
/-- A uniform limit on a set of functions which are continuous on this set is itself continuous
on this set. -/
lemma tendsto_uniformly_on.continuous_on (h : tendsto_uniformly_on F f p s)
(hc : ∀ n, continuous_on (F n) s) (hp : p ≠ ⊥) : continuous_on f s :=
h.tendsto_locally_uniformly_on.continuous_on hc hp
/-- A locally uniform limit of continuous functions is continuous. -/
lemma tendsto_locally_uniformly.continuous (h : tendsto_locally_uniformly F f p)
(hc : ∀ n, continuous (F n)) (hp : p ≠ ⊥) : continuous f :=
begin
apply continuous_of_locally_uniform_approx_of_continuous (λ x u hu, _) hc,
rcases h u hu x with ⟨t, ht, H⟩,
exact ⟨t, ht, H.exists hp⟩
end
/-- A uniform limit of continuous functions is continuous. -/
lemma tendsto_uniformly.continuous (h : tendsto_uniformly F f p)
(hc : ∀ n, continuous (F n)) (hp : p ≠ ⊥) : continuous f :=
h.tendsto_locally_uniformly.continuous hc hp
/-!
### Composing limits under uniform convergence
In general, if `Fₙ` converges pointwise to a function `f`, and `gₙ` tends to `x`, it is not true
that `Fₙ gₙ` tends to `f x`. It is true however if the convergence of `Fₙ` to `f` is uniform. In
this paragraph, we prove variations around this statement.
-/
/-- If `Fₙ` converges locally uniformly on a neighborhood of `x` within a set `s` to a function `f`
which is continuous at `x` within `s `, and `gₙ` tends to `x` within `s`, then `Fₙ (gₙ)` tends
to `f x`. -/
lemma tendsto_comp_of_locally_uniform_limit_within
(h : continuous_within_at f s x) (hg : tendsto g p (nhds_within x s))
(hunif : ∀ u ∈ 𝓤 β, ∃ t ∈ nhds_within x s, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u) :
tendsto (λ n, F n (g n)) p (𝓝 (f x)) :=
begin
apply uniform.tendsto_nhds_right.2 (λ u₀ hu₀, _),
obtain ⟨u₁, h₁, u₁₀⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), comp_rel u u ⊆ u₀ :=
comp_mem_uniformity_sets hu₀,
rcases hunif u₁ h₁ with ⟨s, sx, hs⟩,
have A : ∀ᶠ n in p, g n ∈ s := hg sx,
have B : ∀ᶠ n in p, (f x, f (g n)) ∈ u₁ := hg (uniform.continuous_within_at_iff'_right.1 h h₁),
refine ((hs.and A).and B).mono (λ y hy, _),
rcases hy with ⟨⟨H1, H2⟩, H3⟩,
exact u₁₀ (prod_mk_mem_comp_rel H3 (H1 _ H2))
end
/-- If `Fₙ` converges locally uniformly on a neighborhood of `x` to a function `f` which is
continuous at `x`, and `gₙ` tends to `x`, then `Fₙ (gₙ)` tends to `f x`. -/
lemma tendsto_comp_of_locally_uniform_limit (h : continuous_at f x) (hg : tendsto g p (𝓝 x))
(hunif : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u) :
tendsto (λ n, F n (g n)) p (𝓝 (f x)) :=
begin
rw ← continuous_within_at_univ at h,
rw ← nhds_within_univ at hunif hg,
exact tendsto_comp_of_locally_uniform_limit_within h hg hunif
end
/-- If `Fₙ` tends locally uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then
`Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s` and `x ∈ s`. -/
lemma tendsto_locally_uniformly_on.tendsto_comp (h : tendsto_locally_uniformly_on F f p s)
(hf : continuous_within_at f s x) (hx : x ∈ s) (hg : tendsto g p (nhds_within x s)) :
tendsto (λ n, F n (g n)) p (𝓝 (f x)) :=
tendsto_comp_of_locally_uniform_limit_within hf hg (λ u hu, h u hu x hx)
/-- If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends
to `f x` if `f` is continuous at `x` within `s`. -/
lemma tendsto_uniformly_on.tendsto_comp (h : tendsto_uniformly_on F f p s)
(hf : continuous_within_at f s x) (hg : tendsto g p (nhds_within x s)) :
tendsto (λ n, F n (g n)) p (𝓝 (f x)) :=
tendsto_comp_of_locally_uniform_limit_within hf hg (λ u hu, ⟨s, self_mem_nhds_within, h u hu⟩)
/-- If `Fₙ` tends locally uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/
lemma tendsto_locally_uniformly.tendsto_comp (h : tendsto_locally_uniformly F f p)
(hf : continuous_at f x) (hg : tendsto g p (𝓝 x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) :=
tendsto_comp_of_locally_uniform_limit hf hg (λ u hu, h u hu x)
/-- If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/
lemma tendsto_uniformly.tendsto_comp (h : tendsto_uniformly F f p)
(hf : continuous_at f x) (hg : tendsto g p (𝓝 x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) :=
h.tendsto_locally_uniformly.tendsto_comp hf hg
|
9b134df18e855c4436cdcc35092978ae6f51a670
|
4a1811b87c1a16ede17c8d4db9267aa4c6a01a83
|
/README.lean
|
3dc6843c76795cd874845051cd920bd6fb96b97e
|
[] |
no_license
|
xu-hao/tranql-haskell
|
fb34ec63f92c1627d39111deca45566d6c128714
|
41903cd0cd94a3650fd828ab62395df75309f55b
|
refs/heads/master
| 1,587,955,791,233
| 1,553,191,562,000
| 1,553,191,562,000
| 174,006,347
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 3,521
|
lean
|
namespace rational
inductive rational : Type
| frac : int -> int -> rational
def rational_div : rational → rational → rational
| (rational.frac a b) (rational.frac c d) := rational.frac (a * d) (b * c)
def rational_one : rational := rational.frac 1 1
def rational_add : rational → rational → rational
| (rational.frac a b) (rational.frac c d) := rational.frac (a * d + b * c) (b * d)
instance rational_has_div : has_div rational := {has_div.
div := rational_div
}
instance rational_has_add : has_add rational := {has_add.
add := rational_add
}
instance rational_has_one : has_one rational := {has_one.
one := rational_one
}
end rational
namespace io
constant io : Type → Type
instance io_monad : monad io := sorry
end io
namespace TranQL
open rational
open io
-- all query subsystems implements this class
structure query :=
(selector : Type)
(prop : Type)
(set : selector → Type)
(exec : Π (s : selector), prop → io (set s))
-- all query subsystems implements this class
structure lquery extends query :=
(record : selector → Type)
(toList : Π (s : selector), set s → list (record s))
-- FROM q SELECT s WHERE p
def select (q : query) (s : query.selector q) (p : query.prop q) : io (query.set q s) :=
query.exec q s p
notation `SELECT` a `FROM` b `WHERE` c := select b a c
notation `BIND` := bind
end TranQL
namespace ICEES
open TranQL
open int
-- example ICEES query subsystem
inductive ISelector : Type
| patient : ISelector
inductive IFeature : Type
| AgeStudyStart : IFeature
| AvgDailyPM25Exposure : IFeature
| Theophylline : IFeature
inductive IOp : IFeature → Type
| le : Π {f : IFeature}, IOp f
| ge : Π {f : IFeature}, IOp f
| lt : Π {f : IFeature}, IOp f
| gt : Π {f : IFeature}, IOp f
| eq : Π {f : IFeature}, IOp f
| ne : Π {f : IFeature}, IOp f
inductive ageBins : Type
| a0_2
| a3_17
| a18_34
| a35_50
| a51_69
| a70_89
inductive quintile : Type
| q1
| q2
| q3
| q4
| q5
def IValue : IFeature → Type
| IFeature.AgeStudyStart := ageBins
| IFeature.AvgDailyPM25Exposure := quintile
| IFeature.Theophylline := bool
inductive IProp : Type
| ITrue : IProp
| IAnd : IProp → IProp → IProp
| ICond : Π (f : IFeature), IOp f → IValue f → IProp
notation a `<=` b := IProp.ICond a IOp.le b
notation a `>=` b := IProp.ICond a IOp.ge b
notation a `<` b := IProp.ICond a IOp.lt b
notation a `>` b := IProp.ICond a IOp.gt b
notation a `=` b := IProp.ICond a IOp.eq b
notation a `<>` b := IProp.ICond a IOp.ne b
notation a `AND` b := IProp.IAnd a b
notation `TRUE` := IProp.ITrue
notation `.<=` := IOp.le
notation `.>=` := IOp.ge
notation `.<` := IOp.lt
notation `.>` := IOp.gt
notation `.=` := IOp.eq
notation `.<>` := IOp.ne
inductive ISet : Type
| ICohort : string → ISet
def ICEES := {query.
selector := ISelector,
prop := IProp,
set := λ _, ISet,
exec := sorry
}
open rational
open io
constant associationsToAllFeatures : Π (f : IFeature), IOp f → IValue f → rational → ISet → io (list IFeature)
-- example query
open ISelector
open IFeature
open ageBins
open quintile
def qu1 := SELECT patient FROM ICEES WHERE (AgeStudyStart > a0_2 AND Theophylline = true)
def qu2 :=
let x := true in SELECT patient FROM ICEES WHERE (AgeStudyStart > a0_2 AND Theophylline = x)
def qu3 :=
(SELECT patient FROM ICEES WHERE (AgeStudyStart > a0_2 AND Theophylline = true))
>>=
λ cohort, associationsToAllFeatures AvgDailyPM25Exposure .>= q1 (1 / 10) cohort
end ICEES
|
2cc71a1454f6f6f254fb0c49fe55de17d9ba965e
|
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
|
/src_icannos_totilas/aops/2004-IMO-Problem_2.lean
|
9f6cf687719349edf5c6c323243254d13007e260
|
[] |
no_license
|
ahayat16/lean_exos
|
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
|
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
|
refs/heads/main
| 1,693,101,073,585
| 1,636,479,336,000
| 1,636,479,336,000
| 415,000,441
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 348
|
lean
|
import data.real.basic
import data.polynomial.basic
import data.polynomial.eval
theorem exo (f: polynomial real):
let f_fun (x: real) := polynomial.eval x f in
(forall (a b c: real), a*b + b*c + c*a = 0 -> f_fun(a - b) + f_fun(b - c) + f_fun(c - a) = 2*f_fun(a + b + c))
<-> (exists c1 c2, forall x, f_fun x = c1 * x^4 + c2 * x^2)
:=
sorry
|
86ba4ccb1844e3ca3468e66df0253dc42e7867db
|
a45212b1526d532e6e83c44ddca6a05795113ddc
|
/src/tactic/omega/nat/neg_elim.lean
|
206b33915667de13196b316904d39649e0b0d43d
|
[
"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
| 4,007
|
lean
|
/-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
Negation elimination.
-/
import tactic.omega.nat.form
namespace omega
namespace nat
local notation x ` =* ` y := form.eq x y
local notation x ` ≤* ` y := form.le x y
local notation `¬* ` p := form.not p
local notation p ` ∨* ` q := form.or p q
local notation p ` ∧* ` q := form.and p q
@[simp] def push_neg : form → form
| (p ∨* q) := (push_neg p) ∧* (push_neg q)
| (p ∧* q) := (push_neg p) ∨* (push_neg q)
| (¬*p) := p
| p := ¬* p
lemma push_neg_equiv :
∀ {p : form}, form.equiv (push_neg p) (¬* p) :=
begin
form.induce `[intros v; try {refl}],
{ simp only [classical.not_not, form.holds, push_neg] },
{ simp only [form.holds, push_neg, not_or_distrib, ihp v, ihq v] },
{ simp only [form.holds, push_neg, classical.not_and_distrib, ihp v, ihq v] }
end
def nnf : form → form
| (¬* p) := push_neg (nnf p)
| (p ∨* q) := (nnf p) ∨* (nnf q)
| (p ∧* q) := (nnf p) ∧* (nnf q)
| a := a
def is_nnf : form → Prop
| (t =* s) := true
| (t ≤* s) := true
| ¬*(t =* s) := true
| ¬*(t ≤* s) := true
| (p ∨* q) := is_nnf p ∧ is_nnf q
| (p ∧* q) := is_nnf p ∧ is_nnf q
| _ := false
lemma is_nnf_push_neg : ∀ p : form, is_nnf p → is_nnf (push_neg p) :=
begin
form.induce `[intro h1; try {trivial}],
{ cases p; try {cases h1}; trivial },
{ cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption },
{ cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption }
end
lemma is_nnf_nnf : ∀ p : form, is_nnf (nnf p) :=
begin
form.induce `[try {trivial}],
{ apply is_nnf_push_neg _ ih },
{ constructor; assumption },
{ constructor; assumption }
end
lemma nnf_equiv : ∀ {p : form}, form.equiv (nnf p) p :=
begin
form.induce `[intros v; try {refl}; simp only [nnf]],
{ rw push_neg_equiv,
apply not_iff_not_of_iff, apply ih },
{ apply pred_mono_2' (ihp v) (ihq v) },
{ apply pred_mono_2' (ihp v) (ihq v) }
end
@[simp] def neg_elim_core : form → form
| (¬* (t =* s)) := (t.add_one ≤* s) ∨* (s.add_one ≤* t)
| (¬* (t ≤* s)) := s.add_one ≤* t
| (p ∨* q) := (neg_elim_core p) ∨* (neg_elim_core q)
| (p ∧* q) := (neg_elim_core p) ∧* (neg_elim_core q)
| p := p
lemma neg_free_neg_elim_core : ∀ p, is_nnf p → (neg_elim_core p).neg_free :=
begin
form.induce `[intro h1, try {simp only [neg_free, neg_elim_core]}, try {trivial}],
{ cases p; try {cases h1}; try {trivial},
constructor; trivial },
{ cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption },
{ cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption }
end
lemma le_and_le_iff_eq {α : Type} [partial_order α] {a b : α} :
(a ≤ b ∧ b ≤ a) ↔ a = b :=
begin
constructor; intro h1,
{ cases h1, apply le_antisymm; assumption },
{ constructor; apply le_of_eq; rw h1 }
end
lemma implies_neg_elim_core : ∀ {p : form},
form.implies p (neg_elim_core p) :=
begin
form.induce `[intros v h, try {apply h}],
{ cases p with t s t s; try {apply h},
{ have : preterm.val v (preterm.add_one t) ≤ preterm.val v s ∨
preterm.val v (preterm.add_one s) ≤ preterm.val v t,
{ rw or.comm,
simpa only [form.holds, le_and_le_iff_eq.symm,
classical.not_and_distrib, not_le] using h },
simpa only [form.holds, neg_elim_core, int.add_one_le_iff] },
simpa only [form.holds, not_le, int.add_one_le_iff] using h },
{ simp only [neg_elim_core], cases h;
[{left, apply ihp}, {right, apply ihq}];
assumption },
apply and.imp (ihp _) (ihq _) h
end
def neg_elim : form → form := neg_elim_core ∘ nnf
lemma neg_free_neg_elim {p : form} : (neg_elim p).neg_free :=
neg_free_neg_elim_core _ (is_nnf_nnf _)
lemma implies_neg_elim {p : form} : form.implies p (neg_elim p) :=
begin
intros v h1, apply implies_neg_elim_core,
apply (nnf_equiv v).elim_right h1
end
end nat
end omega
|
14d6d965a3f28061c92e1df6df1cc6d5aebc868a
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/category_theory/monoidal/Mon_.lean
|
c25d0535bdc4f0afd57c751569b84c7e4d93a2e8
|
[
"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
| 18,564
|
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.monoidal.braided
import category_theory.monoidal.discrete
import category_theory.monoidal.coherence_lemmas
import category_theory.limits.shapes.terminal
import algebra.punit_instances
/-!
# The category of monoids in a monoidal category.
We define monoids in a monoidal category `C` and show that the category of monoids is equivalent to
the category of lax monoidal functors from the unit monoidal category to `C`. We also show that if
`C` is braided, then the category of monoids is naturally monoidal.
-/
universes v₁ v₂ u₁ u₂ u
open category_theory
open category_theory.monoidal_category
variables (C : Type u₁) [category.{v₁} C] [monoidal_category.{v₁} C]
/--
A monoid object internal to a monoidal category.
When the monoidal category is preadditive, this is also sometimes called an "algebra object".
-/
structure Mon_ :=
(X : C)
(one : 𝟙_ C ⟶ X)
(mul : X ⊗ X ⟶ X)
(one_mul' : (one ⊗ 𝟙 X) ≫ mul = (λ_ X).hom . obviously)
(mul_one' : (𝟙 X ⊗ one) ≫ mul = (ρ_ X).hom . obviously)
-- Obviously there is some flexibility stating this axiom.
-- This one has left- and right-hand sides matching the statement of `monoid.mul_assoc`,
-- and chooses to place the associator on the right-hand side.
-- The heuristic is that unitors and associators "don't have much weight".
(mul_assoc' : (mul ⊗ 𝟙 X) ≫ mul = (α_ X X X).hom ≫ (𝟙 X ⊗ mul) ≫ mul . obviously)
restate_axiom Mon_.one_mul'
restate_axiom Mon_.mul_one'
restate_axiom Mon_.mul_assoc'
attribute [reassoc] Mon_.one_mul Mon_.mul_one -- We prove a more general `@[simp]` lemma below.
attribute [simp, reassoc] Mon_.mul_assoc
namespace Mon_
/--
The trivial monoid object. We later show this is initial in `Mon_ C`.
-/
@[simps]
def trivial : Mon_ C :=
{ X := 𝟙_ C,
one := 𝟙 _,
mul := (λ_ _).hom,
mul_assoc' := by coherence,
mul_one' := by coherence }
instance : inhabited (Mon_ C) := ⟨trivial C⟩
variables {C} {M : Mon_ C}
@[simp] lemma one_mul_hom {Z : C} (f : Z ⟶ M.X) : (M.one ⊗ f) ≫ M.mul = (λ_ Z).hom ≫ f :=
by rw [←id_tensor_comp_tensor_id, category.assoc, M.one_mul, left_unitor_naturality]
@[simp] lemma mul_one_hom {Z : C} (f : Z ⟶ M.X) : (f ⊗ M.one) ≫ M.mul = (ρ_ Z).hom ≫ f :=
by rw [←tensor_id_comp_id_tensor, category.assoc, M.mul_one, right_unitor_naturality]
lemma assoc_flip : (𝟙 M.X ⊗ M.mul) ≫ M.mul = (α_ M.X M.X M.X).inv ≫ (M.mul ⊗ 𝟙 M.X) ≫ M.mul :=
by simp
/-- A morphism of monoid objects. -/
@[ext]
structure hom (M N : Mon_ C) :=
(hom : M.X ⟶ N.X)
(one_hom' : M.one ≫ hom = N.one . obviously)
(mul_hom' : M.mul ≫ hom = (hom ⊗ hom) ≫ N.mul . obviously)
restate_axiom hom.one_hom'
restate_axiom hom.mul_hom'
attribute [simp, reassoc] hom.one_hom hom.mul_hom
/-- The identity morphism on a monoid object. -/
@[simps]
def id (M : Mon_ C) : hom M M :=
{ hom := 𝟙 M.X, }
instance hom_inhabited (M : Mon_ C) : inhabited (hom M M) := ⟨id M⟩
/-- Composition of morphisms of monoid objects. -/
@[simps]
def comp {M N O : Mon_ C} (f : hom M N) (g : hom N O) : hom M O :=
{ hom := f.hom ≫ g.hom, }
instance : category (Mon_ C) :=
{ hom := λ M N, hom M N,
id := id,
comp := λ M N O f g, comp f g, }
@[simp] lemma id_hom' (M : Mon_ C) : (𝟙 M : hom M M).hom = 𝟙 M.X := rfl
@[simp] lemma comp_hom' {M N K : Mon_ C} (f : M ⟶ N) (g : N ⟶ K) :
(f ≫ g : hom M K).hom = f.hom ≫ g.hom := rfl
section
variables (C)
/-- The forgetful functor from monoid objects to the ambient category. -/
@[simps]
def forget : Mon_ C ⥤ C :=
{ obj := λ A, A.X,
map := λ A B f, f.hom, }
end
instance forget_faithful : faithful (@forget C _ _) := { }
instance {A B : Mon_ C} (f : A ⟶ B) [e : is_iso ((forget C).map f)] : is_iso f.hom := e
/-- The forgetful functor from monoid objects to the ambient category reflects isomorphisms. -/
instance : reflects_isomorphisms (forget C) :=
{ reflects := λ X Y f e, by exactI ⟨⟨
{ hom := inv f.hom,
mul_hom' :=
begin
simp only [is_iso.comp_inv_eq, hom.mul_hom, category.assoc, ←tensor_comp_assoc,
is_iso.inv_hom_id, tensor_id, category.id_comp],
end }, by tidy⟩⟩ }
/--
Construct an isomorphism of monoids by giving an isomorphism between the underlying objects
and checking compatibility with unit and multiplication only in the forward direction.
-/
def iso_of_iso {M N : Mon_ C}
(f : M.X ≅ N.X)
(one_f : M.one ≫ f.hom = N.one)
(mul_f : M.mul ≫ f.hom = (f.hom ⊗ f.hom) ≫ N.mul) :
M ≅ N :=
{ hom := { hom := f.hom, one_hom' := one_f, mul_hom' := mul_f },
inv :=
{ hom := f.inv,
one_hom' := by { rw ←one_f, simp },
mul_hom' :=
begin
rw ←(cancel_mono f.hom),
slice_rhs 2 3 { rw mul_f },
simp,
end } }
instance unique_hom_from_trivial (A : Mon_ C) : unique (trivial C ⟶ A) :=
{ default :=
{ hom := A.one,
one_hom' := by { dsimp, simp, },
mul_hom' := by { dsimp, simp [A.one_mul, unitors_equal], } },
uniq := λ f,
begin
ext, simp,
rw [←category.id_comp f.hom],
erw f.one_hom,
end }
open category_theory.limits
instance : has_initial (Mon_ C) :=
has_initial_of_unique (trivial C)
end Mon_
namespace category_theory.lax_monoidal_functor
variables {C} {D : Type u₂} [category.{v₂} D] [monoidal_category.{v₂} D]
/--
A lax monoidal functor takes monoid objects to monoid objects.
That is, a lax monoidal functor `F : C ⥤ D` induces a functor `Mon_ C ⥤ Mon_ D`.
-/
-- TODO: map_Mod F A : Mod A ⥤ Mod (F.map_Mon A)
@[simps]
def map_Mon (F : lax_monoidal_functor C D) : Mon_ C ⥤ Mon_ D :=
{ obj := λ A,
{ X := F.obj A.X,
one := F.ε ≫ F.map A.one,
mul := F.μ _ _ ≫ F.map A.mul,
one_mul' :=
begin
conv_lhs { rw [comp_tensor_id, ←F.to_functor.map_id], },
slice_lhs 2 3 { rw [F.μ_natural], },
slice_lhs 3 4 { rw [←F.to_functor.map_comp, A.one_mul], },
rw [F.to_functor.map_id],
rw [F.left_unitality],
end,
mul_one' :=
begin
conv_lhs { rw [id_tensor_comp, ←F.to_functor.map_id], },
slice_lhs 2 3 { rw [F.μ_natural], },
slice_lhs 3 4 { rw [←F.to_functor.map_comp, A.mul_one], },
rw [F.to_functor.map_id],
rw [F.right_unitality],
end,
mul_assoc' :=
begin
conv_lhs { rw [comp_tensor_id, ←F.to_functor.map_id], },
slice_lhs 2 3 { rw [F.μ_natural], },
slice_lhs 3 4 { rw [←F.to_functor.map_comp, A.mul_assoc], },
conv_lhs { rw [F.to_functor.map_id] },
conv_lhs { rw [F.to_functor.map_comp, F.to_functor.map_comp] },
conv_rhs { rw [id_tensor_comp, ←F.to_functor.map_id], },
slice_rhs 3 4 { rw [F.μ_natural], },
conv_rhs { rw [F.to_functor.map_id] },
slice_rhs 1 3 { rw [←F.associativity], },
simp only [category.assoc],
end, },
map := λ A B f,
{ hom := F.map f.hom,
one_hom' := by { dsimp, rw [category.assoc, ←F.to_functor.map_comp, f.one_hom], },
mul_hom' :=
begin
dsimp,
rw [category.assoc, F.μ_natural_assoc, ←F.to_functor.map_comp, ←F.to_functor.map_comp,
f.mul_hom],
end },
map_id' := λ A, by { ext, simp, },
map_comp' := λ A B C f g, by { ext, simp, }, }
variables (C D)
/-- `map_Mon` is functorial in the lax monoidal functor. -/
def map_Mon_functor : (lax_monoidal_functor C D) ⥤ (Mon_ C ⥤ Mon_ D) :=
{ obj := map_Mon,
map := λ F G α,
{ app := λ A,
{ hom := α.app A.X, } } }
end category_theory.lax_monoidal_functor
namespace Mon_
open category_theory.lax_monoidal_functor
namespace equiv_lax_monoidal_functor_punit
/-- Implementation of `Mon_.equiv_lax_monoidal_functor_punit`. -/
@[simps]
def lax_monoidal_to_Mon : lax_monoidal_functor (discrete punit.{u+1}) C ⥤ Mon_ C :=
{ obj := λ F, (F.map_Mon : Mon_ _ ⥤ Mon_ C).obj (trivial (discrete punit)),
map := λ F G α, ((map_Mon_functor (discrete punit) C).map α).app _ }
/-- Implementation of `Mon_.equiv_lax_monoidal_functor_punit`. -/
@[simps]
def Mon_to_lax_monoidal : Mon_ C ⥤ lax_monoidal_functor (discrete punit.{u+1}) C :=
{ obj := λ A,
{ obj := λ _, A.X,
map := λ _ _ _, 𝟙 _,
ε := A.one,
μ := λ _ _, A.mul,
map_id' := λ _, rfl,
map_comp' := λ _ _ _ _ _, (category.id_comp (𝟙 A.X)).symm, },
map := λ A B f,
{ app := λ _, f.hom,
naturality' := λ _ _ _, by { dsimp, rw [category.id_comp, category.comp_id], },
unit' := f.one_hom,
tensor' := λ _ _, f.mul_hom, }, }
/-- Implementation of `Mon_.equiv_lax_monoidal_functor_punit`. -/
@[simps]
def unit_iso :
𝟭 (lax_monoidal_functor (discrete punit.{u+1}) C) ≅
lax_monoidal_to_Mon C ⋙ Mon_to_lax_monoidal C :=
nat_iso.of_components (λ F,
monoidal_nat_iso.of_components
(λ _, F.to_functor.map_iso (eq_to_iso (by ext)))
(by tidy) (by tidy) (by tidy))
(by tidy)
/-- Implementation of `Mon_.equiv_lax_monoidal_functor_punit`. -/
@[simps]
def counit_iso : Mon_to_lax_monoidal C ⋙ lax_monoidal_to_Mon C ≅ 𝟭 (Mon_ C) :=
nat_iso.of_components (λ F, { hom := { hom := 𝟙 _, }, inv := { hom := 𝟙 _, } })
(by tidy)
end equiv_lax_monoidal_functor_punit
open equiv_lax_monoidal_functor_punit
/--
Monoid objects in `C` are "just" lax monoidal functors from the trivial monoidal category to `C`.
-/
@[simps]
def equiv_lax_monoidal_functor_punit : lax_monoidal_functor (discrete punit.{u+1}) C ≌ Mon_ C :=
{ functor := lax_monoidal_to_Mon C,
inverse := Mon_to_lax_monoidal C,
unit_iso := unit_iso C,
counit_iso := counit_iso C, }
end Mon_
namespace Mon_
/-!
In this section, we prove that the category of monoids in a braided monoidal category is monoidal.
Given two monoids `M` and `N` in a braided monoidal category `C`, the multiplication on the tensor
product `M.X ⊗ N.X` is defined in the obvious way: it is the tensor product of the multiplications
on `M` and `N`, except that the tensor factors in the source come in the wrong order, which we fix
by pre-composing with a permutation isomorphism constructed from the braiding.
A more conceptual way of understanding this definition is the following: The braiding on `C` gives
rise to a monoidal structure on the tensor product functor from `C × C` to `C`. A pair of monoids
in `C` gives rise to a monoid in `C × C`, which the tensor product functor by being monoidal takes
to a monoid in `C`. The permutation isomorphism appearing in the definition of the multiplication
on the tensor product of two monoids is an instance of a more general family of isomorphisms which
together form a strength that equips the tensor product functor with a monoidal structure, and the
monoid axioms for the tensor product follow from the monoid axioms for the tensor factors plus the
properties of the strength (i.e., monoidal functor axioms). The strength `tensor_μ` of the tensor
product functor has been defined in `category_theory.monoidal.braided`. Its properties, stated as
independent lemmas in that module, are used extensively in the proofs below. Notice that we could
have followed the above plan not only conceptually but also as a possible implementation and could
have constructed the tensor product of monoids via `map_Mon`, but we chose to give a more explicit
definition directly in terms of `tensor_μ`.
To complete the definition of the monoidal category structure on the category of monoids, we need
to provide definitions of associator and unitors. The obvious candidates are the associator and
unitors from `C`, but we need to prove that they are monoid morphisms, i.e., compatible with unit
and multiplication. These properties translate to the monoidality of the associator and unitors
(with respect to the monoidal structures on the functors they relate), which have also been proved
in `category_theory.monoidal.braided`.
-/
variable {C}
-- The proofs that associators and unitors preserve monoid units don't require braiding.
lemma one_associator {M N P : Mon_ C} :
((λ_ (𝟙_ C)).inv ≫ ((λ_ (𝟙_ C)).inv ≫ (M.one ⊗ N.one) ⊗ P.one)) ≫ (α_ M.X N.X P.X).hom
= (λ_ (𝟙_ C)).inv ≫ (M.one ⊗ (λ_ (𝟙_ C)).inv ≫ (N.one ⊗ P.one)) :=
begin
simp,
slice_lhs 1 3 { rw [←category.id_comp P.one, tensor_comp] },
slice_lhs 2 3 { rw associator_naturality },
slice_rhs 1 2 { rw [←category.id_comp M.one, tensor_comp] },
slice_lhs 1 2 { rw [←left_unitor_tensor_inv] },
rw ←(cancel_epi (λ_ (𝟙_ C)).inv),
slice_lhs 1 2 { rw [left_unitor_inv_naturality] },
simp only [category.assoc],
end
lemma one_left_unitor {M : Mon_ C} :
((λ_ (𝟙_ C)).inv ≫ (𝟙 (𝟙_ C) ⊗ M.one)) ≫ (λ_ M.X).hom = M.one :=
by { slice_lhs 2 3 { rw left_unitor_naturality }, simp }
lemma one_right_unitor {M : Mon_ C} :
((λ_ (𝟙_ C)).inv ≫ (M.one ⊗ 𝟙 (𝟙_ C))) ≫ (ρ_ M.X).hom = M.one :=
by { slice_lhs 2 3 { rw [right_unitor_naturality, ←unitors_equal] }, simp }
variable [braided_category C]
lemma Mon_tensor_one_mul (M N : Mon_ C) :
((λ_ (𝟙_ C)).inv ≫ (M.one ⊗ N.one) ⊗ 𝟙 (M.X ⊗ N.X)) ≫
tensor_μ C (M.X, N.X) (M.X, N.X) ≫ (M.mul ⊗ N.mul)
= (λ_ (M.X ⊗ N.X)).hom :=
begin
rw [←category.id_comp (𝟙 (M.X ⊗ N.X)), tensor_comp],
slice_lhs 2 3 { rw [←tensor_id, tensor_μ_natural] },
slice_lhs 3 4 { rw [←tensor_comp, one_mul M, one_mul N] },
symmetry,
exact tensor_left_unitality C M.X N.X,
end
lemma Mon_tensor_mul_one (M N : Mon_ C) :
(𝟙 (M.X ⊗ N.X) ⊗ (λ_ (𝟙_ C)).inv ≫ (M.one ⊗ N.one)) ≫
tensor_μ C (M.X, N.X) (M.X, N.X) ≫ (M.mul ⊗ N.mul)
= (ρ_ (M.X ⊗ N.X)).hom :=
begin
rw [←category.id_comp (𝟙 (M.X ⊗ N.X)), tensor_comp],
slice_lhs 2 3 { rw [←tensor_id, tensor_μ_natural] },
slice_lhs 3 4 { rw [←tensor_comp, mul_one M, mul_one N] },
symmetry,
exact tensor_right_unitality C M.X N.X,
end
lemma Mon_tensor_mul_assoc (M N : Mon_ C) :
(tensor_μ C (M.X, N.X) (M.X, N.X) ≫ (M.mul ⊗ N.mul) ⊗ 𝟙 (M.X ⊗ N.X)) ≫
tensor_μ C (M.X, N.X) (M.X, N.X) ≫
(M.mul ⊗ N.mul)
= (α_ (M.X ⊗ N.X) (M.X ⊗ N.X) (M.X ⊗ N.X)).hom ≫
(𝟙 (M.X ⊗ N.X) ⊗ tensor_μ C (M.X, N.X) (M.X, N.X) ≫ (M.mul ⊗ N.mul)) ≫
tensor_μ C (M.X, N.X) (M.X, N.X) ≫
(M.mul ⊗ N.mul) :=
begin
rw [←category.id_comp (𝟙 (M.X ⊗ N.X)), tensor_comp],
slice_lhs 2 3 { rw [←tensor_id, tensor_μ_natural] },
slice_lhs 3 4 { rw [←tensor_comp, mul_assoc M, mul_assoc N, tensor_comp, tensor_comp] },
slice_lhs 1 3 { rw [tensor_associativity] },
slice_lhs 3 4 { rw [←tensor_μ_natural] },
slice_lhs 2 3 { rw [←tensor_comp, tensor_id] },
simp only [category.assoc],
end
lemma mul_associator {M N P : Mon_ C} :
(tensor_μ C (M.X ⊗ N.X, P.X) (M.X ⊗ N.X, P.X) ≫
(tensor_μ C (M.X, N.X) (M.X, N.X) ≫ (M.mul ⊗ N.mul) ⊗ P.mul)) ≫
(α_ M.X N.X P.X).hom
= ((α_ M.X N.X P.X).hom ⊗ (α_ M.X N.X P.X).hom) ≫
tensor_μ C (M.X, N.X ⊗ P.X) (M.X, N.X ⊗ P.X) ≫
(M.mul ⊗ tensor_μ C (N.X, P.X) (N.X, P.X) ≫ (N.mul ⊗ P.mul)) :=
begin
simp,
slice_lhs 2 3 { rw [←category.id_comp P.mul, tensor_comp] },
slice_lhs 3 4 { rw [associator_naturality] },
slice_rhs 3 4 { rw [←category.id_comp M.mul, tensor_comp] },
slice_lhs 1 3 { rw associator_monoidal },
simp only [category.assoc],
end
lemma mul_left_unitor {M : Mon_ C}:
(tensor_μ C (𝟙_ C, M.X) (𝟙_ C, M.X) ≫ ((λ_ (𝟙_ C)).hom ⊗ M.mul)) ≫ (λ_ M.X).hom
= ((λ_ M.X).hom ⊗ (λ_ M.X).hom) ≫ M.mul :=
begin
rw [←(category.comp_id (λ_ (𝟙_ C)).hom), ←(category.id_comp M.mul), tensor_comp],
slice_lhs 3 4 { rw left_unitor_naturality },
slice_lhs 1 3 { rw ←left_unitor_monoidal },
simp only [category.assoc, category.id_comp],
end
lemma mul_right_unitor {M : Mon_ C} :
(tensor_μ C (M.X, 𝟙_ C) (M.X, 𝟙_ C) ≫ (M.mul ⊗ (λ_ (𝟙_ C)).hom)) ≫ (ρ_ M.X).hom
= ((ρ_ M.X).hom ⊗ (ρ_ M.X).hom) ≫ M.mul :=
begin
rw [←(category.id_comp M.mul), ←(category.comp_id (λ_ (𝟙_ C)).hom), tensor_comp],
slice_lhs 3 4 { rw right_unitor_naturality },
slice_lhs 1 3 { rw ←right_unitor_monoidal },
simp only [category.assoc, category.id_comp],
end
instance Mon_monoidal : monoidal_category (Mon_ C) :=
{ tensor_obj := λ M N,
{ X := M.X ⊗ N.X,
one := (λ_ (𝟙_ C)).inv ≫ (M.one ⊗ N.one),
mul := tensor_μ C (M.X, N.X) (M.X, N.X) ≫ (M.mul ⊗ N.mul),
one_mul' := Mon_tensor_one_mul M N,
mul_one' := Mon_tensor_mul_one M N,
mul_assoc' := Mon_tensor_mul_assoc M N },
tensor_hom := λ M N P Q f g,
{ hom := f.hom ⊗ g.hom,
one_hom' :=
begin
dsimp,
slice_lhs 2 3 { rw [←tensor_comp, hom.one_hom f, hom.one_hom g] },
end,
mul_hom' :=
begin
dsimp,
slice_rhs 1 2 { rw [tensor_μ_natural] },
slice_lhs 2 3 { rw [←tensor_comp, hom.mul_hom f, hom.mul_hom g, tensor_comp] },
simp only [category.assoc],
end },
tensor_id' := by { intros, ext, apply tensor_id },
tensor_comp' := by { intros, ext, apply tensor_comp },
tensor_unit := trivial C,
associator := λ M N P, iso_of_iso (α_ M.X N.X P.X) one_associator mul_associator,
associator_naturality' := by { intros, ext, dsimp, apply associator_naturality },
left_unitor := λ M, iso_of_iso (λ_ M.X) one_left_unitor mul_left_unitor,
left_unitor_naturality' := by { intros, ext, dsimp, apply left_unitor_naturality },
right_unitor := λ M, iso_of_iso (ρ_ M.X) one_right_unitor mul_right_unitor,
right_unitor_naturality' := by { intros, ext, dsimp, apply right_unitor_naturality },
pentagon' := by { intros, ext, dsimp, apply pentagon },
triangle' := by { intros, ext, dsimp, apply triangle } }
end Mon_
/-!
Projects:
* Check that `Mon_ Mon ≌ CommMon`, via the Eckmann-Hilton argument.
(You'll have to hook up the cartesian monoidal structure on `Mon` first, available in #3463)
* Check that `Mon_ Top ≌ [bundled topological monoids]`.
* Check that `Mon_ AddCommGroup ≌ Ring`.
(We've already got `Mon_ (Module R) ≌ Algebra R`, in `category_theory.monoidal.internal.Module`.)
* Can you transport this monoidal structure to `Ring` or `Algebra R`?
How does it compare to the "native" one?
* Show that when `C` is braided, the forgetful functor `Mon_ C ⥤ C` is monoidal.
* Show that when `F` is a lax braided functor `C ⥤ D`, the functor `map_Mon F : Mon_ C ⥤ Mon_ D`
is lax monoidal.
-/
|
37e448bd32a117ac66f3f21cb7c555268871c67f
|
c31182a012eec69da0a1f6c05f42b0f0717d212d
|
/src/for_mathlib/kronecker.lean
|
2780c65ab1c0d633238d004ab25327a6aa0d0754
|
[] |
no_license
|
Ja1941/lean-liquid
|
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
|
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
|
refs/heads/master
| 1,689,437,983,362
| 1,628,362,719,000
| 1,628,362,719,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 3,417
|
lean
|
import linear_algebra.matrix
/-!
# Kronecker product of matrices
TODO: this should probably become a bilinear map
we might want to vary coefficient rings
-/
open_locale big_operators
namespace matrix
variables {l m n o l' m' n' o' R: Type*}
variables [fintype l] [fintype m] [fintype n] [fintype o]
variables [fintype l'] [fintype m'] [fintype n'] [fintype o']
def kronecker [has_mul R] (f : matrix m n R) (f' : matrix m' n' R) :
matrix (m × m') (n × n') R :=
λ i j, f i.1 j.1 * f' i.2 j.2
@[simps]
def kroneckerₗ [comm_semiring R] :
matrix m n R →ₗ[R] matrix m' n' R →ₗ[R] matrix (m × m') (n × n') R :=
{ to_fun := λ M,
{ to_fun := λ M', M.kronecker M',
map_add' := λ M'₁ M'₂, by { ext, apply mul_add },
map_smul' := λ c M', by { ext, dsimp [kronecker], rw mul_left_comm } },
map_add' := λ M₁ M₂, by { ext, apply add_mul },
map_smul' := λ c M, by { ext, dsimp [kronecker], rw mul_assoc } }
lemma kronecker_mul [decidable_eq n'] [comm_semiring R]
(f : matrix m n R) (g : matrix n o R) (f' : matrix m' n' R) (g' : matrix n' o' R) :
(f.mul g).kronecker (f'.mul g') =
(f.kronecker f').mul (g.kronecker g') :=
begin
ext ⟨i, i'⟩ ⟨j, j'⟩,
dsimp [mul_apply, kronecker],
simp only [finset.sum_mul, finset.mul_sum],
rw [← finset.univ_product_univ, finset.sum_product, finset.sum_comm],
simp only [mul_assoc, mul_left_comm (g _ j)],
end
@[simp] lemma kronecker_one_one [decidable_eq m] [decidable_eq n] [semiring R] :
kronecker (1 : matrix m m R) (1 : matrix n n R) = 1 :=
begin
ext ⟨i, i'⟩ ⟨j, j'⟩,
simp only [kronecker, one_apply, boole_mul, prod.mk.inj_iff],
convert (@ite_and _ (i = j) (i' = j') _ _ (1 : R) (0 : R)).symm
end
.
lemma kronecker_reindex [semiring R] (el : l ≃ l') (em : m ≃ m') (en : n ≃ n') (eo : o ≃ o')
(M : matrix l m R) (N : matrix n o R) :
kronecker (reindex_linear_equiv ℕ _ el em M) (reindex_linear_equiv ℕ _ en eo N) =
reindex_linear_equiv ℕ _
(el.prod_congr en) (em.prod_congr eo) (kronecker M N) :=
by { ext ⟨i, i'⟩ ⟨j, j'⟩, refl }
lemma kronecker_reindex_left [semiring R] (el : l ≃ l') (em : m ≃ m') (M : matrix l m R) (N : matrix n o R) :
kronecker (reindex_linear_equiv ℕ _ el em M) N =
reindex_linear_equiv ℕ _
(el.prod_congr (equiv.refl _)) (em.prod_congr (equiv.refl _)) (kronecker M N) :=
by { ext ⟨i, i'⟩ ⟨j, j'⟩, refl }
lemma kronecker_reindex_right [semiring R] (en : n ≃ n') (eo : o ≃ o') (M : matrix l m R) (N : matrix n o R) :
kronecker M (reindex_linear_equiv ℕ _ en eo N) =
reindex_linear_equiv ℕ _
((equiv.refl _).prod_congr en) ((equiv.refl _).prod_congr eo) (kronecker M N) :=
by { ext ⟨i, i'⟩ ⟨j, j'⟩, refl }
lemma kronecker_assoc [semiring R] (A : matrix m m' R) (B : matrix n n' R) (C : matrix o o' R) :
(A.kronecker B).kronecker C =
reindex_linear_equiv ℕ _
(equiv.prod_assoc _ _ _).symm
(equiv.prod_assoc _ _ _).symm
(A.kronecker (kronecker B C)) :=
by { ext ⟨⟨i, j⟩, k⟩ ⟨⟨i', j'⟩, k'⟩, apply mul_assoc }
lemma kronecker_assoc' [semiring R] (A : matrix m m' R) (B : matrix n n' R) (C : matrix o o' R) :
A.kronecker (kronecker B C) =
reindex_linear_equiv ℕ _
(equiv.prod_assoc _ _ _)
(equiv.prod_assoc _ _ _)
((A.kronecker B).kronecker C) :=
by { ext ⟨i, ⟨j, k⟩⟩ ⟨i', ⟨j', k'⟩⟩, symmetry, apply mul_assoc }
end matrix
|
4ee3848eb162f1a5498c9283e14d2788e982c06b
|
35677d2df3f081738fa6b08138e03ee36bc33cad
|
/src/category_theory/yoneda.lean
|
e1e87474c25d5b321d3ddd2d3c4e00aae36210b6
|
[
"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
| 6,699
|
lean
|
/-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.opposites
import category_theory.hom_functor
/-!
# The Yoneda embedding
The Yoneda embedding as a functor `yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁)`,
along with an instance that it is `fully_faithful`.
Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`.
-/
namespace category_theory
open opposite
universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {C : Type u₁} [𝒞 : category.{v₁} C]
include 𝒞
@[simps] def yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁) :=
{ obj := λ X,
{ obj := λ Y, unop Y ⟶ X,
map := λ Y Y' f g, f.unop ≫ g,
map_comp' := λ _ _ _ f g, begin ext, dsimp, erw [category.assoc] end,
map_id' := λ Y, begin ext, dsimp, erw [category.id_comp] end },
map := λ X X' f, { app := λ Y g, g ≫ f } }
@[simps] def coyoneda : Cᵒᵖ ⥤ (C ⥤ Type v₁) :=
{ obj := λ X,
{ obj := λ Y, unop X ⟶ Y,
map := λ Y Y' f g, g ≫ f,
map_comp' := λ _ _ _ f g, begin ext1, dsimp, erw [category.assoc] end,
map_id' := λ Y, begin ext1, dsimp, erw [category.comp_id] end },
map := λ X X' f, { app := λ Y g, f.unop ≫ g },
map_comp' := λ _ _ _ f g, begin ext, dsimp, erw [category.assoc] end,
map_id' := λ X, begin ext, dsimp, erw [category.id_comp] end }
namespace yoneda
lemma obj_map_id {X Y : C} (f : op X ⟶ op Y) :
((@yoneda C _).obj X).map f (𝟙 X) = ((@yoneda C _).map f.unop).app (op Y) (𝟙 Y) :=
by obviously
@[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y)
{Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app (op Z') h = α.app (op Z) (f ≫ h) :=
begin erw [functor_to_types.naturality], refl end
instance yoneda_full : full (@yoneda C _) :=
{ preimage := λ X Y f, (f.app (op X)) (𝟙 X) }
instance yoneda_faithful : faithful (@yoneda C _) :=
{ injectivity' := λ X Y f g p,
begin
injection p with h,
convert (congr_fun (congr_fun h (op X)) (𝟙 X)); dsimp; simp,
end }
/-- Extensionality via Yoneda. The typical usage would be
```
-- Goal is `X ≅ Y`
apply yoneda.ext,
-- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these
functions are inverses and natural in `Z`.
```
-/
def ext (X Y : C)
(p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X))
(h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f)
(n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y :=
@preimage_iso _ _ _ _ yoneda _ _ _ _
(nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy))
def is_iso {X Y : C} (f : X ⟶ Y) [is_iso (yoneda.map f)] : is_iso f :=
is_iso_of_fully_faithful yoneda f
end yoneda
namespace coyoneda
@[simp] lemma naturality {X Y : Cᵒᵖ} (α : coyoneda.obj X ⟶ coyoneda.obj Y)
{Z Z' : C} (f : Z' ⟶ Z) (h : unop X ⟶ Z') : (α.app Z' h) ≫ f = α.app Z (h ≫ f) :=
begin erw [functor_to_types.naturality], refl end
instance coyoneda_full : full (@coyoneda C _) :=
{ preimage := λ X Y f, ((f.app (unop X)) (𝟙 _)).op }
instance coyoneda_faithful : faithful (@coyoneda C _) :=
{ injectivity' := λ X Y f g p,
begin
injection p with h,
have t := (congr_fun (congr_fun h (unop X)) (𝟙 _)),
simpa using congr_arg has_hom.hom.op t,
end }
def is_iso {X Y : Cᵒᵖ} (f : X ⟶ Y) [is_iso (coyoneda.map f)] : is_iso f :=
is_iso_of_fully_faithful coyoneda f
end coyoneda
class representable (F : Cᵒᵖ ⥤ Type v₁) :=
(X : C)
(w : yoneda.obj X ≅ F)
end category_theory
namespace category_theory
-- For the rest of the file, we are using product categories,
-- so need to restrict to the case morphisms are in 'Type', not 'Sort'.
universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
open opposite
variables (C : Type u₁) [𝒞 : category.{v₁} C]
include 𝒞
-- We need to help typeclass inference with some awkward universe levels here.
instance prod_category_instance_1 : category ((Cᵒᵖ ⥤ Type v₁) × Cᵒᵖ) :=
category_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) Cᵒᵖ
instance prod_category_instance_2 : category (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) :=
category_theory.prod.{v₁ (max u₁ v₁)} Cᵒᵖ (Cᵒᵖ ⥤ Type v₁)
open yoneda
def yoneda_evaluation : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) :=
evaluation_uncurried Cᵒᵖ (Type v₁) ⋙ ulift_functor.{u₁}
@[simp] lemma yoneda_evaluation_map_down
(P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) :
((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl
def yoneda_pairing : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) :=
functor.prod yoneda.op (𝟭 (Cᵒᵖ ⥤ Type v₁)) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁)
@[simp] lemma yoneda_pairing_map
(P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) :
(yoneda_pairing C).map α β = yoneda.map α.1.unop ≫ β ≫ α.2 := rfl
def yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C :=
{ hom :=
{ app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))),
naturality' :=
begin
intros X Y f, ext, dsimp,
erw [category.id_comp,
←functor_to_types.naturality,
obj_map_id,
functor_to_types.naturality,
functor_to_types.map_id_apply]
end },
inv :=
{ app := λ F x,
{ app := λ X a, (F.2.map a.op) x.down,
naturality' :=
begin
intros X Y f, ext, dsimp,
rw [functor_to_types.map_comp_apply]
end },
naturality' :=
begin
intros X Y f, ext, dsimp,
rw [←functor_to_types.naturality, functor_to_types.map_comp_apply]
end },
hom_inv_id' :=
begin
ext, dsimp,
erw [←functor_to_types.naturality,
obj_map_id,
functor_to_types.naturality,
functor_to_types.map_id_apply],
refl,
end,
inv_hom_id' :=
begin
ext, dsimp,
rw [functor_to_types.map_id_apply]
end }.
variables {C}
@[simp] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) :
(yoneda.obj X ⟶ F) ≅ ulift.{u₁} (F.obj (op X)) :=
(yoneda_lemma C).app (op X, F)
omit 𝒞
@[simp] def yoneda_sections_small {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) :
(yoneda.obj X ⟶ F) ≅ F.obj (op X) :=
yoneda_sections X F ≪≫ ulift_trivial _
end category_theory
|
616e4536e3af526aa434fa521ddada63a2e049c6
|
a4673261e60b025e2c8c825dfa4ab9108246c32e
|
/tests/lean/PPRoundtrip.lean
|
384f9a55db43b2ca984ec0dd0598e25b5d6c992a
|
[
"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
| 2,766
|
lean
|
import Lean
open Lean
open Lean.Elab
open Lean.Elab.Term
open Lean.Elab.Command
open Lean.Format
open Lean.Meta
def checkM (stx : TermElabM Syntax) (optionsPerPos : OptionsPerPos := {}) : TermElabM Unit := do
let opts ← getOptions
let stx ← stx
let e ← elabTermAndSynthesize stx none <* throwErrorIfErrors
let stx' ← delab Name.anonymous [] e optionsPerPos
let f' ← PrettyPrinter.ppTerm stx'
let s := f'.pretty opts
IO.println s
let env ← getEnv
match Parser.runParserCategory env `term s "<input>" with
| Except.error e => throwErrorAt stx e
| Except.ok stx'' => do
let e' ← elabTermAndSynthesize stx'' none <* throwErrorIfErrors
unless (← isDefEq e e') do
throwErrorAt stx (fmt "failed to round-trip" ++ line ++ fmt e ++ line ++ fmt e')
-- set_option trace.PrettyPrinter.parenthesize true
set_option format.width 20
-- #eval checkM `(?m) -- fails round-trip
#eval checkM `(Sort)
#eval checkM `(Type)
#eval checkM `(Type 0)
#eval checkM `(Type 1)
-- can't add a new universe variable inside a term...
#eval checkM `(Type _)
#eval checkM `(Type (_ + 2))
#eval checkM `(Nat)
#eval checkM `(List Nat)
#eval checkM `(id Nat)
#eval checkM `(id (id (id Nat)))
section
set_option pp.explicit true
#eval checkM `(List Nat)
#eval checkM `(id Nat)
end
section
set_option pp.universes true
#eval checkM `(List Nat)
#eval checkM `(id Nat)
#eval checkM `(Sum Nat Nat)
end
#eval checkM `(id (id Nat)) (Std.RBMap.empty.insert 4 $ KVMap.empty.insert `pp.explicit true)
-- specify the expected type of `a` in a way that is not erased by the delaborator
def typeAs.{u} (α : Type u) (a : α) := ()
#eval checkM `(fun (a : Nat) => a)
#eval checkM `(fun (a b : Nat) => a)
#eval checkM `(fun (a : Nat) (b : Bool) => a)
#eval checkM `(fun {a b : Nat} => a)
-- implicit lambdas work as long as the expected type is preserved
#eval checkM `(typeAs ({α : Type} → (a : α) → α) fun a => a)
section
set_option pp.explicit true
#eval checkM `(fun {α : Type} [ToString α] (a : α) => toString a)
end
#eval checkM `((α : Type) → α)
#eval checkM `((α β : Type) → α) -- group
#eval checkM `((α β : Type) → Type) -- don't group
#eval checkM `((α : Type) → (a : α) → α)
#eval checkM `((α : Type) → (a : α) → a = a)
#eval checkM `({α : Type} → α)
#eval checkM `({α : Type} → [ToString α] → α)
-- TODO: hide `ofNat`
#eval checkM `(0)
#eval checkM `(1)
#eval checkM `(42)
#eval checkM `("hi")
set_option pp.structure_instance_type true in
#eval checkM `({ type := Nat, val := 0 : PointedType })
#eval checkM `((1,2,3))
#eval checkM `((1,2).fst)
#eval checkM `(1 < 2 || true)
#eval checkM `(id (fun a => a) 0)
#eval checkM `(typeAs Nat (do
let x ← pure 1
pure 2
let y := 3
return x + y))
|
9695e29568b7ad1e6a2fa9e2d4678e3ceff0938c
|
0845ae2ca02071debcfd4ac24be871236c01784f
|
/library/init/data/hashable.lean
|
85f69aa511d95c398643a98987e7fb0fe08266e1
|
[
"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
| 648
|
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.data.uint init.data.string
universes u
class Hashable (α : Type u) :=
(hash : α → USize)
export Hashable (hash)
@[extern cpp "lean::usize_mix_hash"]
constant mixHash (u₁ u₂ : USize) : USize := default _
@[extern cpp "lean::string_hash"]
protected constant String.hash (s : String) : USize := default _
instance : Hashable String := ⟨String.hash⟩
protected def Nat.hash (n : Nat) : USize :=
USize.ofNat n
instance : Hashable Nat := ⟨Nat.hash⟩
|
6d0fed00801b359cafec13b05bd0206d56deb72d
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/geometry/manifold/sheaf/basic.lean
|
5c4722153c10212b2ee4c07a48ac2e6a6d193cff
|
[
"Apache-2.0"
] |
permissive
|
leanprover-community/mathlib
|
56a2cadd17ac88caf4ece0a775932fa26327ba0e
|
442a83d738cb208d3600056c489be16900ba701d
|
refs/heads/master
| 1,693,584,102,358
| 1,693,471,902,000
| 1,693,471,902,000
| 97,922,418
| 1,595
| 352
|
Apache-2.0
| 1,694,693,445,000
| 1,500,624,130,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 4,285
|
lean
|
/-
Copyright © 2023 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth
-/
import geometry.manifold.local_invariant_properties
import topology.sheaves.local_predicate
/-! # Generic construction of a sheaf from a `local_invariant_prop` on a manifold
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file constructs the sheaf-of-types of functions `f : M → M'` (for charted spaces `M`, `M'`)
which satisfy the lifted property `lift_prop P` associated to some locally invariant (in the sense
of `structure_groupoid.local_invariant_prop`) property `P` on the model spaces of `M` and `M'`. For
example, differentiability and smoothness are locally invariant properties in this sense, so this
construction can be used to construct the sheaf of differentiable functions on a manifold and the
sheaf of smooth functions on a manifold.
The mathematical work is in associating a `Top.local_predicate` to a
`structure_groupoid.local_invariant_prop`: that is, showing that a differential-geometric "locally
invariant" property is preserved under restriction and gluing.
## Main definitions
* `structure_groupoid.local_invariant_prop.local_predicate`: the `Top.local_predicate` (in the
sheaf-theoretic sense) on functions from open subsets of `M` into `M'`, which states whether
such functions satisfy `lift_prop P`.
* `structure_groupoid.local_invariant_prop.sheaf`: the sheaf-of-types of functions `f : M → M'`
which satisfy the lifted property `lift_prop P`.
-/
open_locale manifold topology
open set topological_space structure_groupoid structure_groupoid.local_invariant_prop opposite
universe u
variables {H : Type*} [topological_space H] {H' : Type*} [topological_space H']
{G : structure_groupoid H} {G' : structure_groupoid H'}
{P : (H → H') → (set H) → H → Prop}
(M : Type u) [topological_space M] [charted_space H M]
(M' : Type u) [topological_space M'] [charted_space H' M']
instance Top.of.charted_space : charted_space H (Top.of M) := (infer_instance : charted_space H M)
instance Top.of.has_groupoid [has_groupoid M G] : has_groupoid (Top.of M) G :=
(infer_instance : has_groupoid M G)
/-- Let `P` be a `local_invariant_prop` for functions between spaces with the groupoids `G`, `G'`
and let `M`, `M'` be charted spaces modelled on the model spaces of those groupoids. Then there is
an induced `local_predicate` on the functions from `M` to `M'`, given by `lift_prop P`. -/
def structure_groupoid.local_invariant_prop.local_predicate (hG : local_invariant_prop G G' P) :
Top.local_predicate (λ (x : Top.of M), M') :=
{ pred := λ {U : opens (Top.of M)}, λ (f : U → M'), lift_prop P f,
res := begin
intros U V i f h x,
have hUV : U ≤ V := category_theory.le_of_hom i,
show lift_prop_at P (f ∘ set.inclusion hUV) x,
rw ← hG.lift_prop_at_iff_comp_inclusion hUV,
apply h,
end,
locality := begin
intros V f h x,
obtain ⟨U, hxU, i, hU : lift_prop P (f ∘ i)⟩ := h x,
let x' : U := ⟨x, hxU⟩,
have hUV : U ≤ V := category_theory.le_of_hom i,
have : lift_prop_at P f (inclusion hUV x'),
{ rw hG.lift_prop_at_iff_comp_inclusion hUV,
exact hU x' },
convert this,
ext1,
refl
end }
/-- Let `P` be a `local_invariant_prop` for functions between spaces with the groupoids `G`, `G'`
and let `M`, `M'` be charted spaces modelled on the model spaces of those groupoids. Then there is
a sheaf of types on `M` which, to each open set `U` in `M`, associates the type of bundled
functions from `U` to `M'` satisfying the lift of `P`. -/
def structure_groupoid.local_invariant_prop.sheaf (hG : local_invariant_prop G G' P) :
Top.sheaf (Type u) (Top.of M) :=
Top.subsheaf_to_Types (hG.local_predicate M M')
instance structure_groupoid.local_invariant_prop.sheaf_has_coe_to_fun
(hG : local_invariant_prop G G' P) (U : (opens (Top.of M))ᵒᵖ) :
has_coe_to_fun ((hG.sheaf M M').val.obj U) (λ _, (unop U) → M') :=
{ coe := λ a, a.1 }
lemma structure_groupoid.local_invariant_prop.section_spec (hG : local_invariant_prop G G' P)
(U : (opens (Top.of M))ᵒᵖ) (f : (hG.sheaf M M').val.obj U) :
lift_prop P f :=
f.2
|
eecb9a5abbe494ccf4398b53fcb848b96b9e71fb
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/measure_theory/function/l1_space.lean
|
80b6a243cb362bf0ca4954f6b4927726c2bab48d
|
[
"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
| 51,902
|
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.function.lp_order
/-!
# 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.
Such a predicate is already available under the name `mem_ℒp 1`. We give a direct definition which
is easier to use, and show that it is equivalent to `mem_ℒp 1`
In the second part, we establish an API between `integrable` and the space `L¹` of equivalence
classes of integrable functions, already defined as a special case of `L^p` spaces for `p = 1`.
## Notation
* `α →₁[μ] β` is the type of `L¹` space, where `α` is a `measure_space` and `β` is a
`normed_add_comm_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_add_comm_group`.
Then `has_finite_integral f` means `(∫⁻ a, ‖f a‖₊) < ∞`.
* If `β` is moreover a `measurable_space` then `f` is called `integrable` if
`f` is `measurable` and `has_finite_integral f` holds.
## Implementation notes
To prove something for an arbitrary integrable function, a useful theorem is
`integrable.induction` in the file `set_integral`.
## Tags
integrable, function space, l1
-/
noncomputable theory
open_locale classical topological_space big_operators ennreal measure_theory nnreal
open set filter topological_space ennreal emetric measure_theory
variables {α β γ δ : Type*} {m : measurable_space α} {μ ν : measure α} [measurable_space δ]
variables [normed_add_comm_group β]
variables [normed_add_comm_group γ]
namespace measure_theory
/-! ### Some results about the Lebesgue integral involving a normed group -/
lemma lintegral_nnnorm_eq_lintegral_edist (f : α → β) :
∫⁻ a, ‖f a‖₊ ∂μ = ∫⁻ a, edist (f a) 0 ∂μ :=
by simp only [edist_eq_coe_nnnorm]
lemma lintegral_norm_eq_lintegral_edist (f : α → β) :
∫⁻ a, (ennreal.of_real ‖f a‖) ∂μ = ∫⁻ a, edist (f a) 0 ∂μ :=
by simp only [of_real_norm_eq_coe_nnnorm, edist_eq_coe_nnnorm]
lemma lintegral_edist_triangle {f g h : α → β}
(hf : ae_strongly_measurable f μ) (hh : ae_strongly_measurable h μ) :
∫⁻ a, edist (f a) (g a) ∂μ ≤ ∫⁻ a, edist (f a) (h a) ∂μ + ∫⁻ a, edist (g a) (h a) ∂μ :=
begin
rw ← lintegral_add_left' (hf.edist hh),
refine lintegral_mono (λ a, _),
apply edist_triangle_right
end
lemma lintegral_nnnorm_zero : ∫⁻ a : α, ‖(0 : β)‖₊ ∂μ = 0 := by simp
lemma lintegral_nnnorm_add_left
{f : α → β} (hf : ae_strongly_measurable f μ) (g : α → γ) :
∫⁻ a, ‖f a‖₊ + ‖g a‖₊ ∂μ = ∫⁻ a, ‖f a‖₊ ∂μ + ∫⁻ a, ‖g a‖₊ ∂μ :=
lintegral_add_left' hf.ennnorm _
lemma lintegral_nnnorm_add_right
(f : α → β) {g : α → γ} (hg : ae_strongly_measurable g μ) :
∫⁻ a, ‖f a‖₊ + ‖g a‖₊ ∂μ = ∫⁻ a, ‖f a‖₊ ∂μ + ∫⁻ a, ‖g a‖₊ ∂μ :=
lintegral_add_right' _ hg.ennnorm
lemma lintegral_nnnorm_neg {f : α → β} :
∫⁻ a, ‖(-f) a‖₊ ∂μ = ∫⁻ a, ‖f a‖₊ ∂μ :=
by simp only [pi.neg_apply, nnnorm_neg]
/-! ### The predicate `has_finite_integral` -/
/-- `has_finite_integral f μ` means that the integral `∫⁻ a, ‖f a‖ ∂μ` is finite.
`has_finite_integral f` means `has_finite_integral f volume`. -/
def has_finite_integral {m : measurable_space α} (f : α → β) (μ : measure α . volume_tac) : Prop :=
∫⁻ a, ‖f a‖₊ ∂μ < ∞
lemma has_finite_integral_iff_norm (f : α → β) :
has_finite_integral f μ ↔ ∫⁻ a, (ennreal.of_real ‖f a‖) ∂μ < ∞ :=
by simp only [has_finite_integral, of_real_norm_eq_coe_nnnorm]
lemma has_finite_integral_iff_edist (f : α → β) :
has_finite_integral f μ ↔ ∫⁻ a, edist (f a) 0 ∂μ < ∞ :=
by simp only [has_finite_integral_iff_norm, edist_dist, dist_zero_right]
lemma has_finite_integral_iff_of_real {f : α → ℝ} (h : 0 ≤ᵐ[μ] f) :
has_finite_integral f μ ↔ ∫⁻ a, ennreal.of_real (f a) ∂μ < ∞ :=
by rw [has_finite_integral, lintegral_nnnorm_eq_of_ae_nonneg h]
lemma has_finite_integral_iff_of_nnreal {f : α → ℝ≥0} :
has_finite_integral (λ x, (f x : ℝ)) μ ↔ ∫⁻ a, f a ∂μ < ∞ :=
by simp [has_finite_integral_iff_norm]
lemma has_finite_integral.mono {f : α → β} {g : α → γ} (hg : has_finite_integral g μ)
(h : ∀ᵐ a ∂μ, ‖f a‖ ≤ ‖g a‖) : has_finite_integral f μ :=
begin
simp only [has_finite_integral_iff_norm] at *,
calc ∫⁻ a, (ennreal.of_real ‖f a‖) ∂μ ≤ ∫⁻ (a : α), (ennreal.of_real ‖g a‖) ∂μ :
lintegral_mono_ae (h.mono $ assume a h, of_real_le_of_real h)
... < ∞ : hg
end
lemma has_finite_integral.mono' {f : α → β} {g : α → ℝ} (hg : has_finite_integral g μ)
(h : ∀ᵐ a ∂μ, ‖f a‖ ≤ g a) : has_finite_integral f μ :=
hg.mono $ h.mono $ λ x hx, le_trans hx (le_abs_self _)
lemma has_finite_integral.congr' {f : α → β} {g : α → γ} (hf : has_finite_integral f μ)
(h : ∀ᵐ a ∂μ, ‖f a‖ = ‖g a‖) :
has_finite_integral g μ :=
hf.mono $ eventually_eq.le $ eventually_eq.symm h
lemma has_finite_integral_congr' {f : α → β} {g : α → γ} (h : ∀ᵐ a ∂μ, ‖f a‖ = ‖g a‖) :
has_finite_integral f μ ↔ has_finite_integral g μ :=
⟨λ hf, hf.congr' h, λ hg, hg.congr' $ eventually_eq.symm h⟩
lemma has_finite_integral.congr {f g : α → β} (hf : has_finite_integral f μ) (h : f =ᵐ[μ] g) :
has_finite_integral g μ :=
hf.congr' $ h.fun_comp norm
lemma has_finite_integral_congr {f g : α → β} (h : f =ᵐ[μ] g) :
has_finite_integral f μ ↔ has_finite_integral g μ :=
has_finite_integral_congr' $ h.fun_comp norm
lemma has_finite_integral_const_iff {c : β} :
has_finite_integral (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ∞ :=
by simp [has_finite_integral, lintegral_const, lt_top_iff_ne_top, or_iff_not_imp_left]
lemma has_finite_integral_const [is_finite_measure μ] (c : β) :
has_finite_integral (λ x : α, c) μ :=
has_finite_integral_const_iff.2 (or.inr $ measure_lt_top _ _)
lemma has_finite_integral_of_bounded [is_finite_measure μ] {f : α → β} {C : ℝ}
(hC : ∀ᵐ a ∂μ, ‖f a‖ ≤ C) : has_finite_integral f μ :=
(has_finite_integral_const C).mono' hC
lemma has_finite_integral.mono_measure {f : α → β} (h : has_finite_integral f ν) (hμ : μ ≤ ν) :
has_finite_integral f μ :=
lt_of_le_of_lt (lintegral_mono' hμ le_rfl) h
lemma has_finite_integral.add_measure {f : α → β} (hμ : has_finite_integral f μ)
(hν : has_finite_integral f ν) : has_finite_integral f (μ + ν) :=
begin
simp only [has_finite_integral, lintegral_add_measure] at *,
exact add_lt_top.2 ⟨hμ, hν⟩
end
lemma has_finite_integral.left_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) :
has_finite_integral f μ :=
h.mono_measure $ measure.le_add_right $ le_rfl
lemma has_finite_integral.right_of_add_measure {f : α → β} (h : has_finite_integral f (μ + ν)) :
has_finite_integral f ν :=
h.mono_measure $ measure.le_add_left $ le_rfl
@[simp] lemma has_finite_integral_add_measure {f : α → β} :
has_finite_integral f (μ + ν) ↔ has_finite_integral f μ ∧ has_finite_integral f ν :=
⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩
lemma has_finite_integral.smul_measure {f : α → β} (h : has_finite_integral f μ) {c : ℝ≥0∞}
(hc : c ≠ ∞) : has_finite_integral f (c • μ) :=
begin
simp only [has_finite_integral, lintegral_smul_measure] at *,
exact mul_lt_top hc h.ne
end
@[simp] lemma has_finite_integral_zero_measure {m : measurable_space α} (f : α → β) :
has_finite_integral f (0 : measure α) :=
by simp only [has_finite_integral, lintegral_zero_measure, with_top.zero_lt_top]
variables (α β μ)
@[simp] lemma has_finite_integral_zero : has_finite_integral (λa:α, (0:β)) μ :=
by simp [has_finite_integral]
variables {α β μ}
lemma has_finite_integral.neg {f : α → β} (hfi : has_finite_integral f μ) :
has_finite_integral (-f) μ :=
by simpa [has_finite_integral] using hfi
@[simp] lemma has_finite_integral_neg_iff {f : α → β} :
has_finite_integral (-f) μ ↔ has_finite_integral f μ :=
⟨λ h, neg_neg f ▸ h.neg, has_finite_integral.neg⟩
lemma has_finite_integral.norm {f : α → β} (hfi : has_finite_integral f μ) :
has_finite_integral (λa, ‖f a‖) μ :=
have eq : (λa, (nnnorm ‖f a‖ : ℝ≥0∞)) = λa, (‖f a‖₊ : ℝ≥0∞),
by { funext, rw nnnorm_norm },
by { rwa [has_finite_integral, eq] }
lemma has_finite_integral_norm_iff (f : α → β) :
has_finite_integral (λa, ‖f a‖) μ ↔ has_finite_integral f μ :=
has_finite_integral_congr' $ eventually_of_forall $ λ x, norm_norm (f x)
lemma has_finite_integral_to_real_of_lintegral_ne_top
{f : α → ℝ≥0∞} (hf : ∫⁻ x, f x ∂μ ≠ ∞) :
has_finite_integral (λ x, (f x).to_real) μ :=
begin
have : ∀ x, (‖(f x).to_real‖₊ : ℝ≥0∞) =
@coe ℝ≥0 ℝ≥0∞ _ (⟨(f x).to_real, ennreal.to_real_nonneg⟩ : ℝ≥0),
{ intro x, rw real.nnnorm_of_nonneg },
simp_rw [has_finite_integral, this],
refine lt_of_le_of_lt (lintegral_mono (λ x, _)) (lt_top_iff_ne_top.2 hf),
by_cases hfx : f x = ∞,
{ simp [hfx] },
{ lift f x to ℝ≥0 using hfx with fx,
simp [← h] }
end
lemma is_finite_measure_with_density_of_real {f : α → ℝ} (hfi : has_finite_integral f μ) :
is_finite_measure (μ.with_density (λ x, ennreal.of_real $ f x)) :=
begin
refine is_finite_measure_with_density ((lintegral_mono $ λ x, _).trans_lt hfi).ne,
exact real.of_real_le_ennnorm (f x)
end
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, (h n).mono $ λ 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‖ :=
h.mono $
λ 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 ← ae_all_iff at F_le_bound,
apply F_le_bound.mp ((all_ae_tendsto_of_real_norm h_lim).mono _),
assume a tendsto_norm F_le_bound,
exact le_of_tendsto' tendsto_norm (F_le_bound)
end
lemma has_finite_integral_of_dominated_convergence {F : ℕ → α → β} {f : α → β} {bound : α → ℝ}
(bound_has_finite_integral : has_finite_integral bound μ)
(h_bound : ∀ n, ∀ᵐ a ∂μ, ‖F n a‖ ≤ bound a)
(h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) :
has_finite_integral f μ :=
/- `‖F n a‖ ≤ bound a` and `‖F n a‖ --> ‖f a‖` implies `‖f a‖ ≤ bound a`,
and so `∫ ‖f‖ ≤ ∫ bound < ∞` since `bound` is has_finite_integral -/
begin
rw has_finite_integral_iff_norm,
calc ∫⁻ a, (ennreal.of_real ‖f a‖) ∂μ ≤ ∫⁻ a, ennreal.of_real (bound a) ∂μ :
lintegral_mono_ae $ all_ae_of_real_f_le_bound h_bound h_lim
... < ∞ :
begin
rw ← has_finite_integral_iff_of_real,
{ exact bound_has_finite_integral },
exact (h_bound 0).mono (λ a h, le_trans (norm_nonneg _) h)
end
end
lemma tendsto_lintegral_norm_of_dominated_convergence
{F : ℕ → α → β} {f : α → β} {bound : α → ℝ}
(F_measurable : ∀ n, ae_strongly_measurable (F n) μ)
(bound_has_finite_integral : has_finite_integral 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) :=
have f_measurable : ae_strongly_measurable f μ :=
ae_strongly_measurable_of_tendsto_ae _ F_measurable h_lim,
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]
with 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
rw ← ennreal.of_real_zero,
refine h_lim.mono (λ a h, (continuous_of_real.tendsto _).comp _),
rwa ← tendsto_iff_norm_tendsto_zero
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 almost everywhere measurable for all `n`
{ exact λ n, measurable_of_real.comp_ae_measurable
((F_measurable n).sub f_measurable).norm.ae_measurable },
-- Show `2 * bound` is has_finite_integral
{ rw has_finite_integral_iff_of_real at bound_has_finite_integral,
{ calc ∫⁻ a, b a ∂μ = 2 * ∫⁻ a, ennreal.of_real (bound a) ∂μ :
by { rw lintegral_const_mul', exact coe_ne_top }
... ≠ ∞ : mul_ne_top coe_ne_top bound_has_finite_integral.ne },
filter_upwards [h_bound 0] with _ h using 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 has_finite_integral.max_zero {f : α → ℝ} (hf : has_finite_integral f μ) :
has_finite_integral (λa, max (f a) 0) μ :=
hf.mono $ eventually_of_forall $ λ x, by simp [abs_le, le_abs_self]
lemma has_finite_integral.min_zero {f : α → ℝ} (hf : has_finite_integral f μ) :
has_finite_integral (λa, min (f a) 0) μ :=
hf.mono $ eventually_of_forall $ λ x,
by simp [abs_le, neg_le, neg_le_abs_self, abs_eq_max_neg, le_total]
end pos_part
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β]
lemma has_finite_integral.smul (c : 𝕜) {f : α → β} : has_finite_integral f μ →
has_finite_integral (c • f) μ :=
begin
simp only [has_finite_integral], assume hfi,
calc
∫⁻ (a : α), ‖c • f a‖₊ ∂μ = ∫⁻ (a : α), (‖c‖₊) * ‖f a‖₊ ∂μ :
by simp only [nnnorm_smul, ennreal.coe_mul]
... < ∞ :
begin
rw lintegral_const_mul',
exacts [mul_lt_top coe_ne_top hfi.ne, coe_ne_top]
end
end
lemma has_finite_integral_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) :
has_finite_integral (c • f) μ ↔ has_finite_integral f μ :=
begin
split,
{ assume h,
simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.smul c⁻¹ },
exact has_finite_integral.smul _
end
lemma has_finite_integral.const_mul {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) :
has_finite_integral (λ x, c * f x) μ :=
(has_finite_integral.smul c h : _)
lemma has_finite_integral.mul_const {f : α → ℝ} (h : has_finite_integral f μ) (c : ℝ) :
has_finite_integral (λ x, f x * c) μ :=
by simp_rw [mul_comm, h.const_mul _]
end normed_space
/-! ### The predicate `integrable` -/
-- variables [measurable_space β] [measurable_space γ] [measurable_space δ]
/-- `integrable f μ` means that `f` is measurable and that the integral `∫⁻ a, ‖f a‖ ∂μ` is finite.
`integrable f` means `integrable f volume`. -/
def integrable {α} {m : measurable_space α} (f : α → β) (μ : measure α . volume_tac) : Prop :=
ae_strongly_measurable f μ ∧ has_finite_integral f μ
lemma mem_ℒp_one_iff_integrable {f : α → β} : mem_ℒp f 1 μ ↔ integrable f μ :=
by simp_rw [integrable, has_finite_integral, mem_ℒp, snorm_one_eq_lintegral_nnnorm]
lemma integrable.ae_strongly_measurable {f : α → β} (hf : integrable f μ) :
ae_strongly_measurable f μ :=
hf.1
lemma integrable.ae_measurable [measurable_space β] [borel_space β]
{f : α → β} (hf : integrable f μ) :
ae_measurable f μ :=
hf.ae_strongly_measurable.ae_measurable
lemma integrable.has_finite_integral {f : α → β} (hf : integrable f μ) : has_finite_integral f μ :=
hf.2
lemma integrable.mono {f : α → β} {g : α → γ}
(hg : integrable g μ) (hf : ae_strongly_measurable f μ) (h : ∀ᵐ a ∂μ, ‖f a‖ ≤ ‖g a‖) :
integrable f μ :=
⟨hf, hg.has_finite_integral.mono h⟩
lemma integrable.mono' {f : α → β} {g : α → ℝ}
(hg : integrable g μ) (hf : ae_strongly_measurable f μ) (h : ∀ᵐ a ∂μ, ‖f a‖ ≤ g a) :
integrable f μ :=
⟨hf, hg.has_finite_integral.mono' h⟩
lemma integrable.congr' {f : α → β} {g : α → γ}
(hf : integrable f μ) (hg : ae_strongly_measurable g μ) (h : ∀ᵐ a ∂μ, ‖f a‖ = ‖g a‖) :
integrable g μ :=
⟨hg, hf.has_finite_integral.congr' h⟩
lemma integrable_congr' {f : α → β} {g : α → γ}
(hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) (h : ∀ᵐ a ∂μ, ‖f a‖ = ‖g a‖) :
integrable f μ ↔ integrable g μ :=
⟨λ h2f, h2f.congr' hg h, λ h2g, h2g.congr' hf $ eventually_eq.symm h⟩
lemma integrable.congr {f g : α → β} (hf : integrable f μ) (h : f =ᵐ[μ] g) :
integrable g μ :=
⟨hf.1.congr h, hf.2.congr h⟩
lemma integrable_congr {f g : α → β} (h : f =ᵐ[μ] g) :
integrable f μ ↔ integrable g μ :=
⟨λ hf, hf.congr h, λ hg, hg.congr h.symm⟩
lemma integrable_const_iff {c : β} : integrable (λ x : α, c) μ ↔ c = 0 ∨ μ univ < ∞ :=
begin
have : ae_strongly_measurable (λ (x : α), c) μ := ae_strongly_measurable_const,
rw [integrable, and_iff_right this, has_finite_integral_const_iff]
end
lemma integrable_const [is_finite_measure μ] (c : β) : integrable (λ x : α, c) μ :=
integrable_const_iff.2 $ or.inr $ measure_lt_top _ _
lemma mem_ℒp.integrable_norm_rpow {f : α → β} {p : ℝ≥0∞}
(hf : mem_ℒp f p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) :
integrable (λ (x : α), ‖f x‖ ^ p.to_real) μ :=
begin
rw ← mem_ℒp_one_iff_integrable,
exact hf.norm_rpow hp_ne_zero hp_ne_top,
end
lemma mem_ℒp.integrable_norm_rpow' [is_finite_measure μ] {f : α → β} {p : ℝ≥0∞}
(hf : mem_ℒp f p μ) :
integrable (λ (x : α), ‖f x‖ ^ p.to_real) μ :=
begin
by_cases h_zero : p = 0,
{ simp [h_zero, integrable_const] },
by_cases h_top : p = ∞,
{ simp [h_top, integrable_const] },
exact hf.integrable_norm_rpow h_zero h_top
end
lemma integrable.mono_measure {f : α → β} (h : integrable f ν) (hμ : μ ≤ ν) : integrable f μ :=
⟨h.ae_strongly_measurable.mono_measure hμ, h.has_finite_integral.mono_measure hμ⟩
lemma integrable.of_measure_le_smul {μ' : measure α} (c : ℝ≥0∞) (hc : c ≠ ∞)
(hμ'_le : μ' ≤ c • μ) {f : α → β} (hf : integrable f μ) :
integrable f μ' :=
by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.of_measure_le_smul c hc hμ'_le, }
lemma integrable.add_measure {f : α → β} (hμ : integrable f μ) (hν : integrable f ν) :
integrable f (μ + ν) :=
begin
simp_rw ← mem_ℒp_one_iff_integrable at hμ hν ⊢,
refine ⟨hμ.ae_strongly_measurable.add_measure hν.ae_strongly_measurable, _⟩,
rw [snorm_one_add_measure, ennreal.add_lt_top],
exact ⟨hμ.snorm_lt_top, hν.snorm_lt_top⟩,
end
lemma integrable.left_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f μ :=
by { rw ← mem_ℒp_one_iff_integrable at h ⊢, exact h.left_of_add_measure, }
lemma integrable.right_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f ν :=
by { rw ← mem_ℒp_one_iff_integrable at h ⊢, exact h.right_of_add_measure, }
@[simp] lemma integrable_add_measure {f : α → β} :
integrable f (μ + ν) ↔ integrable f μ ∧ integrable f ν :=
⟨λ h, ⟨h.left_of_add_measure, h.right_of_add_measure⟩, λ h, h.1.add_measure h.2⟩
@[simp] lemma integrable_zero_measure {m : measurable_space α} {f : α → β} :
integrable f (0 : measure α) :=
⟨ae_strongly_measurable_zero_measure f, has_finite_integral_zero_measure f⟩
theorem integrable_finset_sum_measure {ι} {m : measurable_space α} {f : α → β}
{μ : ι → measure α} {s : finset ι} :
integrable f (∑ i in s, μ i) ↔ ∀ i ∈ s, integrable f (μ i) :=
by induction s using finset.induction_on; simp [*]
lemma integrable.smul_measure {f : α → β} (h : integrable f μ) {c : ℝ≥0∞} (hc : c ≠ ∞) :
integrable f (c • μ) :=
by { rw ← mem_ℒp_one_iff_integrable at h ⊢, exact h.smul_measure hc, }
lemma integrable_smul_measure {f : α → β} {c : ℝ≥0∞} (h₁ : c ≠ 0) (h₂ : c ≠ ∞) :
integrable f (c • μ) ↔ integrable f μ :=
⟨λ h, by simpa only [smul_smul, ennreal.inv_mul_cancel h₁ h₂, one_smul]
using h.smul_measure (ennreal.inv_ne_top.2 h₁), λ h, h.smul_measure h₂⟩
lemma integrable_inv_smul_measure {f : α → β} {c : ℝ≥0∞} (h₁ : c ≠ 0) (h₂ : c ≠ ∞) :
integrable f (c⁻¹ • μ) ↔ integrable f μ :=
integrable_smul_measure (by simpa using h₂) (by simpa using h₁)
lemma integrable.to_average {f : α → β} (h : integrable f μ) :
integrable f ((μ univ)⁻¹ • μ) :=
begin
rcases eq_or_ne μ 0 with rfl|hne,
{ rwa smul_zero },
{ apply h.smul_measure, simpa }
end
lemma integrable_average [is_finite_measure μ] {f : α → β} :
integrable f ((μ univ)⁻¹ • μ) ↔ integrable f μ :=
(eq_or_ne μ 0).by_cases (λ h, by simp [h]) $ λ h,
integrable_smul_measure (ennreal.inv_ne_zero.2 $ measure_ne_top _ _)
(ennreal.inv_ne_top.2 $ mt measure.measure_univ_eq_zero.1 h)
lemma integrable_map_measure {f : α → δ} {g : δ → β}
(hg : ae_strongly_measurable g (measure.map f μ)) (hf : ae_measurable f μ) :
integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ :=
by { simp_rw ← mem_ℒp_one_iff_integrable, exact mem_ℒp_map_measure_iff hg hf, }
lemma integrable.comp_ae_measurable {f : α → δ} {g : δ → β}
(hg : integrable g (measure.map f μ)) (hf : ae_measurable f μ) : integrable (g ∘ f) μ :=
(integrable_map_measure hg.ae_strongly_measurable hf).mp hg
lemma integrable.comp_measurable {f : α → δ} {g : δ → β}
(hg : integrable g (measure.map f μ)) (hf : measurable f) : integrable (g ∘ f) μ :=
hg.comp_ae_measurable hf.ae_measurable
lemma _root_.measurable_embedding.integrable_map_iff
{f : α → δ} (hf : measurable_embedding f) {g : δ → β} :
integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ :=
by { simp_rw ← mem_ℒp_one_iff_integrable, exact hf.mem_ℒp_map_measure_iff, }
lemma integrable_map_equiv (f : α ≃ᵐ δ) (g : δ → β) :
integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ :=
by { simp_rw ← mem_ℒp_one_iff_integrable, exact f.mem_ℒp_map_measure_iff, }
lemma measure_preserving.integrable_comp {ν : measure δ} {g : δ → β}
{f : α → δ} (hf : measure_preserving f μ ν) (hg : ae_strongly_measurable g ν) :
integrable (g ∘ f) μ ↔ integrable g ν :=
by { rw ← hf.map_eq at hg ⊢, exact (integrable_map_measure hg hf.measurable.ae_measurable).symm }
lemma measure_preserving.integrable_comp_emb {f : α → δ} {ν} (h₁ : measure_preserving f μ ν)
(h₂ : measurable_embedding f) {g : δ → β} :
integrable (g ∘ f) μ ↔ integrable g ν :=
h₁.map_eq ▸ iff.symm h₂.integrable_map_iff
lemma lintegral_edist_lt_top {f g : α → β}
(hf : integrable f μ) (hg : integrable g μ) :
∫⁻ a, edist (f a) (g a) ∂μ < ∞ :=
lt_of_le_of_lt
(lintegral_edist_triangle hf.ae_strongly_measurable ae_strongly_measurable_zero)
(ennreal.add_lt_top.2 $ by { simp_rw [pi.zero_apply, ← has_finite_integral_iff_edist],
exact ⟨hf.has_finite_integral, hg.has_finite_integral⟩ })
variables (α β μ)
@[simp] lemma integrable_zero : integrable (λ _, (0 : β)) μ :=
by simp [integrable, ae_strongly_measurable_const]
variables {α β μ}
lemma integrable.add' {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) :
has_finite_integral (f + g) μ :=
calc ∫⁻ a, ‖f a + g a‖₊ ∂μ ≤ ∫⁻ a, ‖f a‖₊ + ‖g a‖₊ ∂μ :
lintegral_mono (λ a, by exact_mod_cast nnnorm_add_le _ _)
... = _ : lintegral_nnnorm_add_left hf.ae_strongly_measurable _
... < ∞ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩
lemma integrable.add
{f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f + g) μ :=
⟨hf.ae_strongly_measurable.add hg.ae_strongly_measurable, hf.add' hg⟩
lemma integrable_finset_sum' {ι} (s : finset ι)
{f : ι → α → β} (hf : ∀ i ∈ s, integrable (f i) μ) : integrable (∑ i in s, f i) μ :=
finset.sum_induction f (λ g, integrable g μ) (λ _ _, integrable.add)
(integrable_zero _ _ _) hf
lemma integrable_finset_sum {ι} (s : finset ι)
{f : ι → α → β} (hf : ∀ i ∈ s, integrable (f i) μ) : integrable (λ a, ∑ i in s, f i a) μ :=
by simpa only [← finset.sum_apply] using integrable_finset_sum' s hf
lemma integrable.neg {f : α → β} (hf : integrable f μ) : integrable (-f) μ :=
⟨hf.ae_strongly_measurable.neg, hf.has_finite_integral.neg⟩
@[simp] lemma integrable_neg_iff {f : α → β} :
integrable (-f) μ ↔ integrable f μ :=
⟨λ h, neg_neg f ▸ h.neg, integrable.neg⟩
lemma integrable.sub {f g : α → β}
(hf : integrable f μ) (hg : integrable g μ) : integrable (f - g) μ :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma integrable.norm {f : α → β} (hf : integrable f μ) :
integrable (λ a, ‖f a‖) μ :=
⟨hf.ae_strongly_measurable.norm, hf.has_finite_integral.norm⟩
lemma integrable.inf {β} [normed_lattice_add_comm_group β] {f g : α → β}
(hf : integrable f μ) (hg : integrable g μ) :
integrable (f ⊓ g) μ :=
by { rw ← mem_ℒp_one_iff_integrable at hf hg ⊢, exact hf.inf hg, }
lemma integrable.sup {β} [normed_lattice_add_comm_group β] {f g : α → β}
(hf : integrable f μ) (hg : integrable g μ) :
integrable (f ⊔ g) μ :=
by { rw ← mem_ℒp_one_iff_integrable at hf hg ⊢, exact hf.sup hg, }
lemma integrable.abs {β} [normed_lattice_add_comm_group β] {f : α → β} (hf : integrable f μ) :
integrable (λ a, |f a|) μ :=
by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.abs, }
lemma integrable.bdd_mul {F : Type*} [normed_division_ring F]
{f g : α → F} (hint : integrable g μ) (hm : ae_strongly_measurable f μ)
(hfbdd : ∃ C, ∀ x, ‖f x‖ ≤ C) :
integrable (λ x, f x * g x) μ :=
begin
casesI is_empty_or_nonempty α with hα hα,
{ rw μ.eq_zero_of_is_empty,
exact integrable_zero_measure },
{ refine ⟨hm.mul hint.1, _⟩,
obtain ⟨C, hC⟩ := hfbdd,
have hCnonneg : 0 ≤ C := le_trans (norm_nonneg _) (hC hα.some),
have : (λ x, ‖f x * g x‖₊) ≤ λ x, ⟨C, hCnonneg⟩ * ‖g x‖₊,
{ intro x,
simp only [nnnorm_mul],
exact mul_le_mul_of_nonneg_right (hC x) (zero_le _) },
refine lt_of_le_of_lt (lintegral_mono_nnreal this) _,
simp only [ennreal.coe_mul],
rw lintegral_const_mul' _ _ ennreal.coe_ne_top,
exact ennreal.mul_lt_top ennreal.coe_ne_top (ne_of_lt hint.2) },
end
lemma integrable_norm_iff {f : α → β} (hf : ae_strongly_measurable f μ) :
integrable (λa, ‖f a‖) μ ↔ integrable f μ :=
by simp_rw [integrable, and_iff_right hf, and_iff_right hf.norm, has_finite_integral_norm_iff]
lemma integrable_of_norm_sub_le {f₀ f₁ : α → β} {g : α → ℝ}
(hf₁_m : ae_strongly_measurable f₁ μ)
(hf₀_i : integrable f₀ μ)
(hg_i : integrable g μ)
(h : ∀ᵐ a ∂μ, ‖f₀ a - f₁ a‖ ≤ g a) :
integrable f₁ μ :=
begin
have : ∀ᵐ a ∂μ, ‖f₁ a‖ ≤ ‖f₀ a‖ + g a,
{ apply h.mono,
intros a ha,
calc ‖f₁ a‖ ≤ ‖f₀ a‖ + ‖f₀ a - f₁ a‖ : norm_le_insert _ _
... ≤ ‖f₀ a‖ + g a : add_le_add_left ha _ },
exact integrable.mono' (hf₀_i.norm.add hg_i) hf₁_m this
end
lemma integrable.prod_mk {f : α → β} {g : α → γ} (hf : integrable f μ) (hg : integrable g μ) :
integrable (λ x, (f x, g x)) μ :=
⟨hf.ae_strongly_measurable.prod_mk hg.ae_strongly_measurable,
(hf.norm.add' hg.norm).mono $ eventually_of_forall $ λ x,
calc max ‖f x‖ ‖g x‖ ≤ ‖f x‖ + ‖g x‖ : max_le_add_of_nonneg (norm_nonneg _) (norm_nonneg _)
... ≤ ‖(‖f x‖ + ‖g x‖)‖ : le_abs_self _⟩
lemma mem_ℒp.integrable {q : ℝ≥0∞} (hq1 : 1 ≤ q) {f : α → β} [is_finite_measure μ]
(hfq : mem_ℒp f q μ) : integrable f μ :=
mem_ℒp_one_iff_integrable.mp (hfq.mem_ℒp_of_exponent_le hq1)
lemma lipschitz_with.integrable_comp_iff_of_antilipschitz {K K'} {f : α → β} {g : β → γ}
(hg : lipschitz_with K g) (hg' : antilipschitz_with K' g) (g0 : g 0 = 0) :
integrable (g ∘ f) μ ↔ integrable f μ :=
by simp [← mem_ℒp_one_iff_integrable, hg.mem_ℒp_comp_iff_of_antilipschitz hg' g0]
lemma integrable.real_to_nnreal {f : α → ℝ} (hf : integrable f μ) :
integrable (λ x, ((f x).to_nnreal : ℝ)) μ :=
begin
refine ⟨hf.ae_strongly_measurable.ae_measurable
.real_to_nnreal.coe_nnreal_real.ae_strongly_measurable, _⟩,
rw has_finite_integral_iff_norm,
refine lt_of_le_of_lt _ ((has_finite_integral_iff_norm _).1 hf.has_finite_integral),
apply lintegral_mono,
assume x,
simp [ennreal.of_real_le_of_real, abs_le, le_abs_self],
end
lemma of_real_to_real_ae_eq {f : α → ℝ≥0∞} (hf : ∀ᵐ x ∂μ, f x < ∞) :
(λ x, ennreal.of_real (f x).to_real) =ᵐ[μ] f :=
begin
filter_upwards [hf],
assume x hx,
simp only [hx.ne, of_real_to_real, ne.def, not_false_iff],
end
lemma coe_to_nnreal_ae_eq {f : α → ℝ≥0∞} (hf : ∀ᵐ x ∂μ, f x < ∞) :
(λ x, ((f x).to_nnreal : ℝ≥0∞)) =ᵐ[μ] f :=
begin
filter_upwards [hf],
assume x hx,
simp only [hx.ne, ne.def, not_false_iff, coe_to_nnreal],
end
section
variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E]
lemma integrable_with_density_iff_integrable_coe_smul
{f : α → ℝ≥0} (hf : measurable f) {g : α → E} :
integrable g (μ.with_density (λ x, f x)) ↔ integrable (λ x, (f x : ℝ) • g x) μ :=
begin
by_cases H : ae_strongly_measurable (λ (x : α), (f x : ℝ) • g x) μ,
{ simp only [integrable, ae_strongly_measurable_with_density_iff hf, has_finite_integral, H,
true_and],
rw lintegral_with_density_eq_lintegral_mul₀' hf.coe_nnreal_ennreal.ae_measurable,
{ congr',
ext1 x,
simp only [nnnorm_smul, nnreal.nnnorm_eq, coe_mul, pi.mul_apply] },
{ rw ae_measurable_with_density_ennreal_iff hf,
convert H.ennnorm,
ext1 x,
simp only [nnnorm_smul, nnreal.nnnorm_eq, coe_mul] } },
{ simp only [integrable, ae_strongly_measurable_with_density_iff hf, H, false_and] }
end
lemma integrable_with_density_iff_integrable_smul {f : α → ℝ≥0} (hf : measurable f) {g : α → E} :
integrable g (μ.with_density (λ x, f x)) ↔ integrable (λ x, f x • g x) μ :=
integrable_with_density_iff_integrable_coe_smul hf
lemma integrable_with_density_iff_integrable_smul'
{f : α → ℝ≥0∞} (hf : measurable f) (hflt : ∀ᵐ x ∂μ, f x < ∞) {g : α → E} :
integrable g (μ.with_density f) ↔ integrable (λ x, (f x).to_real • g x) μ :=
begin
rw [← with_density_congr_ae (coe_to_nnreal_ae_eq hflt),
integrable_with_density_iff_integrable_smul],
{ refl },
{ exact hf.ennreal_to_nnreal },
end
lemma integrable_with_density_iff_integrable_coe_smul₀
{f : α → ℝ≥0} (hf : ae_measurable f μ) {g : α → E} :
integrable g (μ.with_density (λ x, f x)) ↔ integrable (λ x, (f x : ℝ) • g x) μ :=
calc
integrable g (μ.with_density (λ x, f x))
↔ integrable g (μ.with_density (λ x, hf.mk f x)) :
begin
suffices : (λ x, (f x : ℝ≥0∞)) =ᵐ[μ] (λ x, hf.mk f x), by rw with_density_congr_ae this,
filter_upwards [hf.ae_eq_mk] with x hx,
simp [hx],
end
... ↔ integrable (λ x, (hf.mk f x : ℝ) • g x) μ :
integrable_with_density_iff_integrable_coe_smul hf.measurable_mk
... ↔ integrable (λ x, (f x : ℝ) • g x) μ :
begin
apply integrable_congr,
filter_upwards [hf.ae_eq_mk] with x hx,
simp [hx],
end
lemma integrable_with_density_iff_integrable_smul₀
{f : α → ℝ≥0} (hf : ae_measurable f μ) {g : α → E} :
integrable g (μ.with_density (λ x, f x)) ↔ integrable (λ x, f x • g x) μ :=
integrable_with_density_iff_integrable_coe_smul₀ hf
end
lemma integrable_with_density_iff {f : α → ℝ≥0∞} (hf : measurable f)
(hflt : ∀ᵐ x ∂μ, f x < ∞) {g : α → ℝ} :
integrable g (μ.with_density f) ↔ integrable (λ x, g x * (f x).to_real) μ :=
begin
have : (λ x, g x * (f x).to_real) = (λ x, (f x).to_real • g x), by simp [mul_comm],
rw this,
exact integrable_with_density_iff_integrable_smul' hf hflt,
end
section
variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E]
lemma mem_ℒ1_smul_of_L1_with_density {f : α → ℝ≥0} (f_meas : measurable f)
(u : Lp E 1 (μ.with_density (λ x, f x))) :
mem_ℒp (λ x, f x • u x) 1 μ :=
mem_ℒp_one_iff_integrable.2 $ (integrable_with_density_iff_integrable_smul f_meas).1 $
mem_ℒp_one_iff_integrable.1 (Lp.mem_ℒp u)
variable (μ)
/-- The map `u ↦ f • u` is an isometry between the `L^1` spaces for `μ.with_density f` and `μ`. -/
noncomputable def with_density_smul_li {f : α → ℝ≥0} (f_meas : measurable f) :
Lp E 1 (μ.with_density (λ x, f x)) →ₗᵢ[ℝ] Lp E 1 μ :=
{ to_fun := λ u, (mem_ℒ1_smul_of_L1_with_density f_meas u).to_Lp _,
map_add' :=
begin
assume u v,
ext1,
filter_upwards [(mem_ℒ1_smul_of_L1_with_density f_meas u).coe_fn_to_Lp,
(mem_ℒ1_smul_of_L1_with_density f_meas v).coe_fn_to_Lp,
(mem_ℒ1_smul_of_L1_with_density f_meas (u + v)).coe_fn_to_Lp,
Lp.coe_fn_add ((mem_ℒ1_smul_of_L1_with_density f_meas u).to_Lp _)
((mem_ℒ1_smul_of_L1_with_density f_meas v).to_Lp _),
(ae_with_density_iff f_meas.coe_nnreal_ennreal).1 (Lp.coe_fn_add u v)],
assume x hu hv huv h' h'',
rw [huv, h', pi.add_apply, hu, hv],
rcases eq_or_ne (f x) 0 with hx|hx,
{ simp only [hx, zero_smul, add_zero] },
{ rw [h'' _, pi.add_apply, smul_add],
simpa only [ne.def, ennreal.coe_eq_zero] using hx }
end,
map_smul' :=
begin
assume r u,
ext1,
filter_upwards [(ae_with_density_iff f_meas.coe_nnreal_ennreal).1 (Lp.coe_fn_smul r u),
(mem_ℒ1_smul_of_L1_with_density f_meas (r • u)).coe_fn_to_Lp,
Lp.coe_fn_smul r ((mem_ℒ1_smul_of_L1_with_density f_meas u).to_Lp _),
(mem_ℒ1_smul_of_L1_with_density f_meas u).coe_fn_to_Lp],
assume x h h' h'' h''',
rw [ring_hom.id_apply, h', h'', pi.smul_apply, h'''],
rcases eq_or_ne (f x) 0 with hx|hx,
{ simp only [hx, zero_smul, smul_zero] },
{ rw [h _, smul_comm, pi.smul_apply],
simpa only [ne.def, ennreal.coe_eq_zero] using hx }
end,
norm_map' :=
begin
assume u,
simp only [snorm, linear_map.coe_mk, Lp.norm_to_Lp, one_ne_zero, ennreal.one_ne_top,
ennreal.one_to_real, if_false, snorm', ennreal.rpow_one, _root_.div_one, Lp.norm_def],
rw lintegral_with_density_eq_lintegral_mul_non_measurable _ f_meas.coe_nnreal_ennreal
(filter.eventually_of_forall (λ x, ennreal.coe_lt_top)),
congr' 1,
apply lintegral_congr_ae,
filter_upwards [(mem_ℒ1_smul_of_L1_with_density f_meas u).coe_fn_to_Lp] with x hx,
rw [hx, pi.mul_apply],
change ↑‖(f x : ℝ) • u x‖₊ = ↑(f x) * ↑‖u x‖₊,
simp only [nnnorm_smul, nnreal.nnnorm_eq, ennreal.coe_mul],
end }
@[simp] lemma with_density_smul_li_apply {f : α → ℝ≥0} (f_meas : measurable f)
(u : Lp E 1 (μ.with_density (λ x, f x))) :
with_density_smul_li μ f_meas u =
(mem_ℒ1_smul_of_L1_with_density f_meas u).to_Lp (λ x, f x • u x) :=
rfl
end
lemma mem_ℒ1_to_real_of_lintegral_ne_top
{f : α → ℝ≥0∞} (hfm : ae_measurable f μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) :
mem_ℒp (λ x, (f x).to_real) 1 μ :=
begin
rw [mem_ℒp, snorm_one_eq_lintegral_nnnorm],
exact ⟨(ae_measurable.ennreal_to_real hfm).ae_strongly_measurable,
has_finite_integral_to_real_of_lintegral_ne_top hfi⟩
end
lemma integrable_to_real_of_lintegral_ne_top
{f : α → ℝ≥0∞} (hfm : ae_measurable f μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) :
integrable (λ x, (f x).to_real) μ :=
mem_ℒp_one_iff_integrable.1 $ mem_ℒ1_to_real_of_lintegral_ne_top hfm hfi
section pos_part
/-! ### Lemmas used for defining the positive part of a `L¹` function -/
lemma integrable.pos_part {f : α → ℝ} (hf : integrable f μ) : integrable (λ a, max (f a) 0) μ :=
⟨(hf.ae_strongly_measurable.ae_measurable.max ae_measurable_const).ae_strongly_measurable,
hf.has_finite_integral.max_zero⟩
lemma integrable.neg_part {f : α → ℝ} (hf : integrable f μ) : integrable (λ a, max (-f a) 0) μ :=
hf.neg.pos_part
end pos_part
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β]
lemma integrable.smul (c : 𝕜) {f : α → β}
(hf : integrable f μ) : integrable (c • f) μ :=
⟨hf.ae_strongly_measurable.const_smul c, hf.has_finite_integral.smul c⟩
lemma integrable_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) :
integrable (c • f) μ ↔ integrable f μ :=
and_congr (ae_strongly_measurable_const_smul_iff₀ hc) (has_finite_integral_smul_iff hc f)
lemma integrable.const_mul {f : α → ℝ} (h : integrable f μ) (c : ℝ) :
integrable (λ x, c * f x) μ :=
integrable.smul c h
lemma integrable.const_mul' {f : α → ℝ} (h : integrable f μ) (c : ℝ) :
integrable ((λ (x : α), c) * f) μ :=
integrable.smul c h
lemma integrable.mul_const {f : α → ℝ} (h : integrable f μ) (c : ℝ) :
integrable (λ x, f x * c) μ :=
by simp_rw [mul_comm, h.const_mul _]
lemma integrable.mul_const' {f : α → ℝ} (h : integrable f μ) (c : ℝ) :
integrable (f * (λ (x : α), c)) μ :=
integrable.mul_const h c
lemma integrable.div_const {f : α → ℝ} (h : integrable f μ) (c : ℝ) :
integrable (λ x, f x / c) μ :=
by simp_rw [div_eq_mul_inv, h.mul_const]
lemma integrable.bdd_mul' {f g : α → ℝ} {c : ℝ} (hg : integrable g μ)
(hf : ae_strongly_measurable f μ) (hf_bound : ∀ᵐ x ∂μ, ‖f x‖ ≤ c) :
integrable (λ x, f x * g x) μ :=
begin
refine integrable.mono' (hg.norm.smul c) (hf.mul hg.1) _,
filter_upwards [hf_bound] with x hx,
rw [pi.smul_apply, smul_eq_mul],
exact (norm_mul_le _ _).trans (mul_le_mul_of_nonneg_right hx (norm_nonneg _)),
end
end normed_space
section normed_space_over_complete_field
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] [complete_space 𝕜]
variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
lemma integrable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) :
integrable (λ x, f x • c) μ ↔ integrable f μ :=
begin
simp_rw [integrable, ae_strongly_measurable_smul_const_iff hc, and.congr_right_iff,
has_finite_integral, nnnorm_smul, ennreal.coe_mul],
intro hf, rw [lintegral_mul_const' _ _ ennreal.coe_ne_top, ennreal.mul_lt_top_iff],
have : ∀ x : ℝ≥0∞, x = 0 → x < ∞ := by simp,
simp [hc, or_iff_left_of_imp (this _)]
end
end normed_space_over_complete_field
section is_R_or_C
variables {𝕜 : Type*} [is_R_or_C 𝕜] {f : α → 𝕜}
lemma integrable.of_real {f : α → ℝ} (hf : integrable f μ) :
integrable (λ x, (f x : 𝕜)) μ :=
by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.of_real }
lemma integrable.re_im_iff :
integrable (λ x, is_R_or_C.re (f x)) μ ∧ integrable (λ x, is_R_or_C.im (f x)) μ ↔
integrable f μ :=
by { simp_rw ← mem_ℒp_one_iff_integrable, exact mem_ℒp_re_im_iff }
lemma integrable.re (hf : integrable f μ) : integrable (λ x, is_R_or_C.re (f x)) μ :=
by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.re, }
lemma integrable.im (hf : integrable f μ) : integrable (λ x, is_R_or_C.im (f x)) μ :=
by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.im, }
end is_R_or_C
section inner_product
variables {𝕜 E : Type*} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] {f : α → E}
local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y
lemma integrable.const_inner (c : E) (hf : integrable f μ) : integrable (λ x, ⟪c, f x⟫) μ :=
by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.const_inner c, }
lemma integrable.inner_const (hf : integrable f μ) (c : E) : integrable (λ x, ⟪f x, c⟫) μ :=
by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.inner_const c, }
end inner_product
section trim
variables {H : Type*} [normed_add_comm_group H] {m0 : measurable_space α} {μ' : measure α}
{f : α → H}
lemma integrable.trim (hm : m ≤ m0) (hf_int : integrable f μ') (hf : strongly_measurable[m] f) :
integrable f (μ'.trim hm) :=
begin
refine ⟨hf.ae_strongly_measurable, _⟩,
rw [has_finite_integral, lintegral_trim hm _],
{ exact hf_int.2, },
{ exact @strongly_measurable.ennnorm _ m _ _ f hf },
end
lemma integrable_of_integrable_trim (hm : m ≤ m0) (hf_int : integrable f (μ'.trim hm)) :
integrable f μ' :=
begin
obtain ⟨hf_meas_ae, hf⟩ := hf_int,
refine ⟨ae_strongly_measurable_of_ae_strongly_measurable_trim hm hf_meas_ae, _⟩,
rw has_finite_integral at hf ⊢,
rwa lintegral_trim_ae hm _ at hf,
exact ae_strongly_measurable.ennnorm hf_meas_ae
end
end trim
section sigma_finite
variables {E : Type*} {m0 : measurable_space α} [normed_add_comm_group E]
lemma integrable_of_forall_fin_meas_le' {μ : measure α} (hm : m ≤ m0) [sigma_finite (μ.trim hm)]
(C : ℝ≥0∞) (hC : C < ∞) {f : α → E} (hf_meas : ae_strongly_measurable f μ)
(hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, ‖f x‖₊ ∂μ ≤ C) :
integrable f μ :=
⟨hf_meas, (lintegral_le_of_forall_fin_meas_le' hm C hf_meas.ennnorm hf).trans_lt hC⟩
lemma integrable_of_forall_fin_meas_le [sigma_finite μ]
(C : ℝ≥0∞) (hC : C < ∞) {f : α → E} (hf_meas : ae_strongly_measurable f μ)
(hf : ∀ s : set α, measurable_set s → μ s ≠ ∞ → ∫⁻ x in s, ‖f x‖₊ ∂μ ≤ C) :
integrable f μ :=
@integrable_of_forall_fin_meas_le' _ _ _ _ _ _ _ (by rwa trim_eq_self) C hC _ hf_meas hf
end sigma_finite
/-! ### The predicate `integrable` on measurable functions modulo a.e.-equality -/
namespace ae_eq_fun
section
/-- A class of almost everywhere equal functions is `integrable` if its function representative
is integrable. -/
def integrable (f : α →ₘ[μ] β) : Prop := integrable f μ
lemma integrable_mk {f : α → β} (hf : ae_strongly_measurable f μ ) :
(integrable (mk f hf : α →ₘ[μ] β)) ↔ measure_theory.integrable f μ :=
begin
simp [integrable],
apply integrable_congr,
exact coe_fn_mk f hf
end
lemma integrable_coe_fn {f : α →ₘ[μ] β} : (measure_theory.integrable f μ) ↔ integrable f :=
by rw [← integrable_mk, mk_coe_fn]
lemma integrable_zero : integrable (0 : α →ₘ[μ] β) :=
(integrable_zero α β μ).congr (coe_fn_mk _ _).symm
end
section
lemma integrable.neg {f : α →ₘ[μ] β} : integrable f → integrable (-f) :=
induction_on f $ λ f hfm hfi, (integrable_mk _).2 ((integrable_mk hfm).1 hfi).neg
section
lemma integrable_iff_mem_L1 {f : α →ₘ[μ] β} : integrable f ↔ f ∈ (α →₁[μ] β) :=
by rw [← integrable_coe_fn, ← mem_ℒp_one_iff_integrable, Lp.mem_Lp_iff_mem_ℒp]
lemma integrable.add {f g : α →ₘ[μ] β} : integrable f → integrable g → integrable (f + g) :=
begin
refine induction_on₂ f g (λ f hf g hg hfi hgi, _),
simp only [integrable_mk, mk_add_mk] at hfi hgi ⊢,
exact hfi.add hgi
end
lemma integrable.sub {f g : α →ₘ[μ] β} (hf : integrable f) (hg : integrable g) :
integrable (f - g) :=
(sub_eq_add_neg f g).symm ▸ hf.add hg.neg
end
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β]
lemma integrable.smul {c : 𝕜} {f : α →ₘ[μ] β} : integrable f → integrable (c • f) :=
induction_on f $ λ f hfm hfi, (integrable_mk _).2 $ ((integrable_mk hfm).1 hfi).smul _
end normed_space
end
end ae_eq_fun
namespace L1
lemma integrable_coe_fn (f : α →₁[μ] β) :
integrable f μ :=
by { rw ← mem_ℒp_one_iff_integrable, exact Lp.mem_ℒp f }
lemma has_finite_integral_coe_fn (f : α →₁[μ] β) :
has_finite_integral f μ :=
(integrable_coe_fn f).has_finite_integral
lemma strongly_measurable_coe_fn (f : α →₁[μ] β) : strongly_measurable f :=
Lp.strongly_measurable f
lemma measurable_coe_fn [measurable_space β] [borel_space β] (f : α →₁[μ] β) :
measurable f :=
(Lp.strongly_measurable f).measurable
lemma ae_strongly_measurable_coe_fn (f : α →₁[μ] β) : ae_strongly_measurable f μ :=
Lp.ae_strongly_measurable f
lemma ae_measurable_coe_fn [measurable_space β] [borel_space β] (f : α →₁[μ] β) :
ae_measurable f μ :=
(Lp.strongly_measurable f).measurable.ae_measurable
lemma edist_def (f g : α →₁[μ] β) :
edist f g = ∫⁻ a, edist (f a) (g a) ∂μ :=
by { simp [Lp.edist_def, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] }
lemma dist_def (f g : α →₁[μ] β) :
dist f g = (∫⁻ a, edist (f a) (g a) ∂μ).to_real :=
by { simp [Lp.dist_def, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] }
lemma norm_def (f : α →₁[μ] β) :
‖f‖ = (∫⁻ a, ‖f a‖₊ ∂μ).to_real :=
by { simp [Lp.norm_def, snorm, snorm'] }
/-- Computing the norm of a difference between two L¹-functions. Note that this is not a
special case of `norm_def` since `(f - g) x` and `f x - g x` are not equal
(but only a.e.-equal). -/
lemma norm_sub_eq_lintegral (f g : α →₁[μ] β) :
‖f - g‖ = (∫⁻ x, (‖f x - g x‖₊ : ℝ≥0∞) ∂μ).to_real :=
begin
rw [norm_def],
congr' 1,
rw lintegral_congr_ae,
filter_upwards [Lp.coe_fn_sub f g] with _ ha,
simp only [ha, pi.sub_apply],
end
lemma of_real_norm_eq_lintegral (f : α →₁[μ] β) :
ennreal.of_real ‖f‖ = ∫⁻ x, (‖f x‖₊ : ℝ≥0∞) ∂μ :=
by { rw [norm_def, ennreal.of_real_to_real], exact ne_of_lt (has_finite_integral_coe_fn f) }
/-- Computing the norm of a difference between two L¹-functions. Note that this is not a
special case of `of_real_norm_eq_lintegral` since `(f - g) x` and `f x - g x` are not equal
(but only a.e.-equal). -/
lemma of_real_norm_sub_eq_lintegral (f g : α →₁[μ] β) :
ennreal.of_real ‖f - g‖ = ∫⁻ x, (‖f x - g x‖₊ : ℝ≥0∞) ∂μ :=
begin
simp_rw [of_real_norm_eq_lintegral, ← edist_eq_coe_nnnorm],
apply lintegral_congr_ae,
filter_upwards [Lp.coe_fn_sub f g] with _ ha,
simp only [ha, pi.sub_apply],
end
end L1
namespace integrable
/-- Construct the equivalence class `[f]` of an integrable function `f`, as a member of the
space `L1 β 1 μ`. -/
def to_L1 (f : α → β) (hf : integrable f μ) : α →₁[μ] β :=
(mem_ℒp_one_iff_integrable.2 hf).to_Lp f
@[simp] lemma to_L1_coe_fn (f : α →₁[μ] β) (hf : integrable f μ) : hf.to_L1 f = f :=
by simp [integrable.to_L1]
lemma coe_fn_to_L1 {f : α → β} (hf : integrable f μ) : hf.to_L1 f =ᵐ[μ] f :=
ae_eq_fun.coe_fn_mk _ _
@[simp] lemma to_L1_zero (h : integrable (0 : α → β) μ) : h.to_L1 0 = 0 := rfl
@[simp] lemma to_L1_eq_mk (f : α → β) (hf : integrable f μ) :
(hf.to_L1 f : α →ₘ[μ] β) = ae_eq_fun.mk f hf.ae_strongly_measurable :=
rfl
@[simp] lemma to_L1_eq_to_L1_iff (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) :
to_L1 f hf = to_L1 g hg ↔ f =ᵐ[μ] g :=
mem_ℒp.to_Lp_eq_to_Lp_iff _ _
lemma to_L1_add (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) :
to_L1 (f + g) (hf.add hg) = to_L1 f hf + to_L1 g hg := rfl
lemma to_L1_neg (f : α → β) (hf : integrable f μ) :
to_L1 (- f) (integrable.neg hf) = - to_L1 f hf := rfl
lemma to_L1_sub (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) :
to_L1 (f - g) (hf.sub hg) = to_L1 f hf - to_L1 g hg := rfl
lemma norm_to_L1 (f : α → β) (hf : integrable f μ) :
‖hf.to_L1 f‖ = ennreal.to_real (∫⁻ a, edist (f a) 0 ∂μ) :=
by { simp [to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm] }
lemma norm_to_L1_eq_lintegral_norm (f : α → β) (hf : integrable f μ) :
‖hf.to_L1 f‖ = ennreal.to_real (∫⁻ a, (ennreal.of_real ‖f a‖) ∂μ) :=
by { rw [norm_to_L1, lintegral_norm_eq_lintegral_edist] }
@[simp] lemma edist_to_L1_to_L1 (f g : α → β) (hf : integrable f μ) (hg : integrable g μ) :
edist (hf.to_L1 f) (hg.to_L1 g) = ∫⁻ a, edist (f a) (g a) ∂μ :=
by { simp [integrable.to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm_sub] }
@[simp] lemma edist_to_L1_zero (f : α → β) (hf : integrable f μ) :
edist (hf.to_L1 f) 0 = ∫⁻ a, edist (f a) 0 ∂μ :=
by { simp [integrable.to_L1, snorm, snorm'], simp [edist_eq_coe_nnnorm] }
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β]
lemma to_L1_smul (f : α → β) (hf : integrable f μ) (k : 𝕜) :
to_L1 (λ a, k • f a) (hf.smul k) = k • to_L1 f hf := rfl
lemma to_L1_smul' (f : α → β) (hf : integrable f μ) (k : 𝕜) :
to_L1 (k • f) (hf.smul k) = k • to_L1 f hf := rfl
end integrable
end measure_theory
open measure_theory
variables {E : Type*} [normed_add_comm_group E]
{𝕜 : Type*} [nontrivially_normed_field 𝕜] [normed_space 𝕜 E]
{H : Type*} [normed_add_comm_group H] [normed_space 𝕜 H]
lemma measure_theory.integrable.apply_continuous_linear_map {φ : α → H →L[𝕜] E}
(φ_int : integrable φ μ) (v : H) : integrable (λ a, φ a v) μ :=
(φ_int.norm.mul_const ‖v‖).mono' (φ_int.ae_strongly_measurable.apply_continuous_linear_map v)
(eventually_of_forall $ λ a, (φ a).le_op_norm v)
lemma continuous_linear_map.integrable_comp {φ : α → H} (L : H →L[𝕜] E)
(φ_int : integrable φ μ) : integrable (λ (a : α), L (φ a)) μ :=
((integrable.norm φ_int).const_mul ‖L‖).mono'
(L.continuous.comp_ae_strongly_measurable φ_int.ae_strongly_measurable)
(eventually_of_forall $ λ a, L.le_op_norm (φ a))
|
40ef6a39f1327aaedada310122e3d1f807622fb8
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/category_theory/linear/basic.lean
|
cd01f81bef101a48e1f631d7648f24a7cb8a3358
|
[
"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,684
|
lean
|
/-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.preadditive.basic
import algebra.module.linear_map
import algebra.invertible
import algebra.algebra.basic
/-!
# Linear categories
An `R`-linear category is a category in which `X ⟶ Y` is an `R`-module in such a way that
composition of morphisms is `R`-linear in both variables.
Note that sometimes in the literature a "linear category" is further required to be abelian.
## Implementation
Corresponding to the fact that we need to have an `add_comm_group X` structure in place
to talk about a `module R X` structure,
we need `preadditive C` as a prerequisite typeclass for `linear R C`.
This makes for longer signatures than would be ideal.
## Future work
It would be nice to have a usable framework of enriched categories in which this just became
a category enriched in `Module R`.
-/
universes w v u
open category_theory.limits
open linear_map
namespace category_theory
/-- A category is called `R`-linear if `P ⟶ Q` is an `R`-module such that composition is
`R`-linear in both variables. -/
class linear (R : Type w) [semiring R] (C : Type u) [category.{v} C] [preadditive C] :=
(hom_module : Π X Y : C, module R (X ⟶ Y) . tactic.apply_instance)
(smul_comp' : ∀ (X Y Z : C) (r : R) (f : X ⟶ Y) (g : Y ⟶ Z),
(r • f) ≫ g = r • (f ≫ g) . obviously)
(comp_smul' : ∀ (X Y Z : C) (f : X ⟶ Y) (r : R) (g : Y ⟶ Z),
f ≫ (r • g) = r • (f ≫ g) . obviously)
attribute [instance] linear.hom_module
restate_axiom linear.smul_comp'
restate_axiom linear.comp_smul'
attribute [simp,reassoc] linear.smul_comp
attribute [reassoc, simp] linear.comp_smul -- (the linter doesn't like `simp` on the `_assoc` lemma)
end category_theory
open category_theory
namespace category_theory.linear
variables {C : Type u} [category.{v} C] [preadditive C]
instance preadditive_nat_linear : linear ℕ C :=
{ smul_comp' := λ X Y Z r f g, (preadditive.right_comp X g).map_nsmul f r,
comp_smul' := λ X Y Z f r g, (preadditive.left_comp Z f).map_nsmul g r, }
instance preadditive_int_linear : linear ℤ C :=
{ smul_comp' := λ X Y Z r f g, (preadditive.right_comp X g).map_zsmul f r,
comp_smul' := λ X Y Z f r g, (preadditive.left_comp Z f).map_zsmul g r, }
section End
variables {R : Type w}
instance [semiring R] [linear R C] (X : C) : module R (End X) :=
by { dsimp [End], apply_instance, }
instance [comm_semiring R] [linear R C] (X : C) : algebra R (End X) :=
algebra.of_module (λ r f g, comp_smul _ _ _ _ _ _) (λ r f g, smul_comp _ _ _ _ _ _)
end End
section
variables {R : Type w} [semiring R] [linear R C]
section induced_category
universes u'
variables {C} {D : Type u'} (F : D → C)
instance induced_category : linear.{w v} R (induced_category C F) :=
{ hom_module := λ X Y, @linear.hom_module R _ C _ _ _ (F X) (F Y),
smul_comp' := λ P Q R f f' g, smul_comp' _ _ _ _ _ _,
comp_smul' := λ P Q R f g g', comp_smul' _ _ _ _ _ _, }
end induced_category
instance full_subcategory (Z : C → Prop) : linear.{w v} R (full_subcategory Z) :=
{ hom_module := λ X Y, @linear.hom_module R _ C _ _ _ X.obj Y.obj,
smul_comp' := λ P Q R f f' g, smul_comp' _ _ _ _ _ _,
comp_smul' := λ P Q R f g g', comp_smul' _ _ _ _ _ _, }
variables (R)
/-- Composition by a fixed left argument as an `R`-linear map. -/
@[simps]
def left_comp {X Y : C} (Z : C) (f : X ⟶ Y) : (Y ⟶ Z) →ₗ[R] (X ⟶ Z) :=
{ to_fun := λ g, f ≫ g,
map_add' := by simp,
map_smul' := by simp, }
/-- Composition by a fixed right argument as an `R`-linear map. -/
@[simps]
def right_comp (X : C) {Y Z : C} (g : Y ⟶ Z) : (X ⟶ Y) →ₗ[R] (X ⟶ Z) :=
{ to_fun := λ f, f ≫ g,
map_add' := by simp,
map_smul' := by simp, }
instance {X Y : C} (f : X ⟶ Y) [epi f] (r : R) [invertible r] : epi (r • f) :=
⟨λ R g g' H, begin
rw [smul_comp, smul_comp, ←comp_smul, ←comp_smul, cancel_epi] at H,
simpa [smul_smul] using congr_arg (λ f, ⅟r • f) H,
end⟩
instance {X Y : C} (f : X ⟶ Y) [mono f] (r : R) [invertible r] : mono (r • f) :=
⟨λ R g g' H, begin
rw [comp_smul, comp_smul, ←smul_comp, ←smul_comp, cancel_mono] at H,
simpa [smul_smul] using congr_arg (λ f, ⅟r • f) H,
end⟩
end
section
variables {S : Type w} [comm_semiring S] [linear S C]
/-- Composition as a bilinear map. -/
@[simps]
def comp (X Y Z : C) : (X ⟶ Y) →ₗ[S] ((Y ⟶ Z) →ₗ[S] (X ⟶ Z)) :=
{ to_fun := λ f, left_comp S Z f,
map_add' := by { intros, ext, simp, },
map_smul' := by { intros, ext, simp, }, }
end
end category_theory.linear
|
38a83938c8da23751ef8f90fa8050774aafb03f2
|
2f291cee459e0e7f5af2abd1034c11b969936560
|
/src/power_series_mk_is_lin_map.lean
|
67a74662f4618518ccbff2269b6d376f0f32e19b
|
[] |
no_license
|
mo271/faulhaber
|
be5a22e717f59b5a0a5b1f1e1acf61ff768c5400
|
2e39d9cb7bc6fc400a818b2581ee921d41a7871a
|
refs/heads/master
| 1,678,216,700,259
| 1,613,991,672,000
| 1,613,991,672,000
| 338,251,172
| 1
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 485
|
lean
|
import algebra.module.linear_map
import ring_theory.power_series.basic
variables {σ R : Type*}
variables (R) [semiring R]
/-
theorem linear_map_test :
is_linear_map R (λ (z:R), z) :=
begin
refine {map_add := _, map_smul := _},
intros,
simp,
intros,
simp,
end
-/
theorem pow_series_mk_is_lin_map (R :Type) [semiring R]:
is_linear_map R (λ (z:power_series R), z) :=
begin
refine {map_add := _, map_smul := _},
repeat {simp only [forall_const, eq_self_iff_true]},
end
|
a98442b0afe89b578baa869a46dc00fad2df8924
|
53618200bef52920c1e974173f78cd378d268f3e
|
/hott/types/pointed.hlean
|
918ec139b42505ab0b8a1b68da466afaedfdf9dd
|
[
"Apache-2.0"
] |
permissive
|
sayantangkhan/lean2
|
cc41e61102e0fcc8b65e8501186dcca40b19b22e
|
0fc0378969678eec25ea425a426bb48a184a6db0
|
refs/heads/master
| 1,590,323,112,724
| 1,489,425,932,000
| 1,489,425,932,000
| 84,854,525
| 0
| 0
| null | 1,489,425,509,000
| 1,489,425,509,000
| null |
UTF-8
|
Lean
| false
| false
| 40,487
|
hlean
|
/-
Copyright (c) 2014-2016 Jakob von Raumer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jakob von Raumer, Floris van Doorn
Ported from Coq HoTT
The basic definitions are in init.pointed
-/
import .nat.basic ..arity ..prop_trunc
open is_trunc eq prod sigma nat equiv option is_equiv bool unit algebra sigma.ops sum
namespace pointed
variables {A B : Type}
definition pointed_loop [instance] [constructor] (a : A) : pointed (a = a) :=
pointed.mk idp
definition pointed_fun_closed [constructor] (f : A → B) [H : pointed A] : pointed B :=
pointed.mk (f pt)
definition loop [reducible] [constructor] (A : Type*) : Type* :=
pointed.mk' (point A = point A)
definition loopn [reducible] : ℕ → Type* → Type*
| loopn 0 X := X
| loopn (n+1) X := loop (loopn n X)
notation `Ω` := loop
notation `Ω[`:95 n:0 `]`:0 := loopn n
namespace ops
-- this is in a separate namespace because it caused type class inference to loop in some places
definition is_trunc_pointed_MK [instance] [priority 1100] (n : ℕ₋₂) {A : Type} (a : A)
[H : is_trunc n A] : is_trunc n (pointed.MK A a) :=
H
end ops
definition is_trunc_loop [instance] [priority 1100] (A : Type*)
(n : ℕ₋₂) [H : is_trunc (n.+1) A] : is_trunc n (Ω A) :=
!is_trunc_eq
definition loopn_zero_eq [unfold_full] (A : Type*)
: Ω[0] A = A := rfl
definition loopn_succ_eq [unfold_full] (k : ℕ) (A : Type*)
: Ω[succ k] A = Ω (Ω[k] A) := rfl
definition rfln [constructor] [reducible] {n : ℕ} {A : Type*} : Ω[n] A := pt
definition refln [constructor] [reducible] (n : ℕ) (A : Type*) : Ω[n] A := pt
definition refln_eq_refl [unfold_full] (A : Type*) (n : ℕ) : rfln = rfl :> Ω[succ n] A := rfl
definition loopn_space [unfold 3] (A : Type) [H : pointed A] (n : ℕ) : Type :=
Ω[n] (pointed.mk' A)
definition loop_mul {k : ℕ} {A : Type*} (mul : A → A → A) : Ω[k] A → Ω[k] A → Ω[k] A :=
begin cases k with k, exact mul, exact concat end
definition pType_eq {A B : Type*} (f : A ≃ B) (p : f pt = pt) : A = B :=
begin
cases A with A a, cases B with B b, esimp at *,
fapply apdt011 @pType.mk,
{ apply ua f},
{ rewrite [cast_ua, p]},
end
definition pType_eq_elim {A B : Type*} (p : A = B :> Type*)
: Σ(p : carrier A = carrier B :> Type), Point A =[p] Point B :=
by induction p; exact ⟨idp, idpo⟩
protected definition pType.sigma_char.{u} : pType.{u} ≃ Σ(X : Type.{u}), X :=
begin
fapply equiv.MK,
{ intro x, induction x with X x, exact ⟨X, x⟩},
{ intro x, induction x with X x, exact pointed.MK X x},
{ intro x, induction x with X x, reflexivity},
{ intro x, induction x with X x, reflexivity},
end
definition pType.eta_expand [constructor] (A : Type*) : Type* :=
pointed.MK A pt
definition add_point [constructor] (A : Type) : Type* :=
pointed.Mk (none : option A)
postfix `₊`:(max+1) := add_point
-- the inclusion A → A₊ is called "some", the extra point "pt" or "none" ("@none A")
end pointed
namespace pointed
/- truncated pointed types -/
definition ptrunctype_eq {n : ℕ₋₂} {A B : n-Type*}
(p : A = B :> Type) (q : Point A =[p] Point B) : A = B :=
begin
induction A with A HA a, induction B with B HB b, esimp at *,
induction q, esimp,
refine ap010 (ptrunctype.mk A) _ a,
exact !is_prop.elim
end
definition ptrunctype_eq_of_pType_eq {n : ℕ₋₂} {A B : n-Type*} (p : A = B :> Type*)
: A = B :=
begin
cases pType_eq_elim p with q r,
exact ptrunctype_eq q r
end
definition is_trunc_ptrunctype [instance] {n : ℕ₋₂} (A : n-Type*) : is_trunc n A :=
trunctype.struct A
end pointed open pointed
namespace pointed
variables {A B C D : Type*} {f g h : A →* B}
/- categorical properties of pointed maps -/
definition pmap_of_map [constructor] {A B : Type} (f : A → B) (a : A) :
pointed.MK A a →* pointed.MK B (f a) :=
pmap.mk f idp
definition pid [constructor] [refl] (A : Type*) : A →* A :=
pmap.mk id idp
definition pcompose [constructor] [trans] (g : B →* C) (f : A →* B) : A →* C :=
pmap.mk (λa, g (f a)) (ap g (respect_pt f) ⬝ respect_pt g)
infixr ` ∘* `:60 := pcompose
definition passoc [constructor] (h : C →* D) (g : B →* C) (f : A →* B) : (h ∘* g) ∘* f ~* h ∘* (g ∘* f) :=
phomotopy.mk (λa, idp)
abstract !idp_con ⬝ whisker_right _ (!ap_con ⬝ whisker_right _ !ap_compose'⁻¹) ⬝ !con.assoc end
definition pid_pcompose [constructor] (f : A →* B) : pid B ∘* f ~* f :=
begin
fconstructor,
{ intro a, reflexivity},
{ reflexivity}
end
definition pcompose_pid [constructor] (f : A →* B) : f ∘* pid A ~* f :=
begin
fconstructor,
{ intro a, reflexivity},
{ reflexivity}
end
/- equivalences and equalities -/
definition pmap.sigma_char [constructor] {A B : Type*} : (A →* B) ≃ Σ(f : A → B), f pt = pt :=
begin
fapply equiv.MK : intros f,
{ exact ⟨f , respect_pt f⟩ },
all_goals cases f with f p,
{ exact pmap.mk f p },
all_goals reflexivity
end
definition pmap.eta_expand [constructor] {A B : Type*} (f : A →* B) : A →* B :=
pmap.mk f (pmap.resp_pt f)
definition pmap_equiv_right (A : Type*) (B : Type)
: (Σ(b : B), A →* (pointed.Mk b)) ≃ (A → B) :=
begin
fapply equiv.MK,
{ intro u a, exact pmap.to_fun u.2 a},
{ intro f, refine ⟨f pt, _⟩, fapply pmap.mk,
intro a, esimp, exact f a,
reflexivity},
{ intro f, reflexivity},
{ intro u, cases u with b f, cases f with f p, esimp at *, induction p,
reflexivity}
end
/- some specific pointed maps -/
-- The constant pointed map between any two types
definition pconst [constructor] (A B : Type*) : A →* B :=
pmap.mk (λ a, Point B) idp
-- the pointed type of pointed maps
definition ppmap [constructor] (A B : Type*) : Type* :=
pType.mk (A →* B) (pconst A B)
definition pcast [constructor] {A B : Type*} (p : A = B) : A →* B :=
pmap.mk (cast (ap pType.carrier p)) (by induction p; reflexivity)
definition pinverse [constructor] {X : Type*} : Ω X →* Ω X :=
pmap.mk eq.inverse idp
definition ap1 [constructor] (f : A →* B) : Ω A →* Ω B :=
begin
fconstructor,
{ intro p, exact !respect_pt⁻¹ ⬝ ap f p ⬝ !respect_pt},
{ esimp, apply con.left_inv}
end
definition apn (n : ℕ) (f : A →* B) : Ω[n] A →* Ω[n] B :=
begin
induction n with n IH,
{ exact f},
{ esimp [loopn], exact ap1 IH}
end
notation `Ω→`:(max+5) := ap1
notation `Ω→[`:95 n:0 `]`:0 := apn n
definition ptransport [constructor] {A : Type} (B : A → Type*) {a a' : A} (p : a = a')
: B a →* B a' :=
pmap.mk (transport B p) (apdt (λa, Point (B a)) p)
definition pmap_of_eq_pt [constructor] {A : Type} {a a' : A} (p : a = a') :
pointed.MK A a →* pointed.MK A a' :=
pmap.mk id p
definition pbool_pmap [constructor] {A : Type*} (a : A) : pbool →* A :=
pmap.mk (bool.rec pt a) idp
-- properties of pointed maps
definition apn_zero [unfold_full] (f : A →* B) : Ω→[0] f = f := idp
definition apn_succ [unfold_full] (n : ℕ) (f : A →* B) : Ω→[n + 1] f = Ω→ (Ω→[n] f) := idp
theorem ap1_con (f : A →* B) (p q : Ω A) : ap1 f (p ⬝ q) = ap1 f p ⬝ ap1 f q :=
begin
rewrite [▸*,ap_con, +con.assoc, con_inv_cancel_left], repeat apply whisker_left
end
theorem ap1_inv (f : A →* B) (p : Ω A) : ap1 f p⁻¹ = (ap1 f p)⁻¹ :=
begin
rewrite [▸*,ap_inv, +con_inv, inv_inv, +con.assoc], repeat apply whisker_left
end
definition pinverse_con [constructor] {X : Type*} (p q : Ω X)
: pinverse (p ⬝ q) = pinverse q ⬝ pinverse p :=
!con_inv
definition pinverse_inv [constructor] {X : Type*} (p : Ω X)
: pinverse p⁻¹ = (pinverse p)⁻¹ :=
idp
theorem apn_con (n : ℕ) (f : A →* B) (p q : Ω[n+1] A)
: apn (n+1) f (p ⬝ q) = apn (n+1) f p ⬝ apn (n+1) f q :=
by rewrite [+apn_succ, ap1_con]
theorem apn_inv (n : ℕ) (f : A →* B) (p : Ω[n+1] A) : apn (n+1) f p⁻¹ = (apn (n+1) f p)⁻¹ :=
by rewrite [+apn_succ, ap1_inv]
definition is_equiv_ap1 (f : A →* B) [is_equiv f] : is_equiv (ap1 f) :=
begin
induction B with B b, induction f with f pf, esimp at *, cases pf, esimp,
apply is_equiv.homotopy_closed (ap f),
intro p, exact !idp_con⁻¹
end
definition is_equiv_apn (n : ℕ) (f : A →* B) [H : is_equiv f]
: is_equiv (apn n f) :=
begin
induction n with n IH,
{ exact H},
{ exact is_equiv_ap1 (apn n f)}
end
definition is_equiv_pcast [instance] {A B : Type*} (p : A = B) : is_equiv (pcast p) :=
!is_equiv_cast
/- categorical properties of pointed homotopies -/
protected definition phomotopy.refl [constructor] [refl] (f : A →* B) : f ~* f :=
begin
fconstructor,
{ intro a, exact idp},
{ apply idp_con}
end
protected definition phomotopy.rfl [constructor] {f : A →* B} : f ~* f :=
phomotopy.refl f
protected definition phomotopy.trans [constructor] [trans] (p : f ~* g) (q : g ~* h)
: f ~* h :=
phomotopy.mk (λa, p a ⬝ q a) (!con.assoc ⬝ whisker_left (p pt) (to_homotopy_pt q) ⬝ to_homotopy_pt p)
protected definition phomotopy.symm [constructor] [symm] (p : f ~* g) : g ~* f :=
phomotopy.mk (λa, (p a)⁻¹) (inv_con_eq_of_eq_con (to_homotopy_pt p)⁻¹)
infix ` ⬝* `:75 := phomotopy.trans
postfix `⁻¹*`:(max+1) := phomotopy.symm
/- equalities and equivalences relating pointed homotopies -/
definition phomotopy.sigma_char [constructor] {A B : Type*} (f g : A →* B)
: (f ~* g) ≃ Σ(p : f ~ g), p pt ⬝ respect_pt g = respect_pt f :=
begin
fapply equiv.MK : intros h,
{ exact ⟨h , to_homotopy_pt h⟩ },
all_goals cases h with h p,
{ exact phomotopy.mk h p },
all_goals reflexivity
end
definition phomotopy.eta_expand [constructor] {A B : Type*} {f g : A →* B} (p : f ~* g) : f ~* g :=
phomotopy.mk p (phomotopy.homotopy_pt p)
definition is_trunc_pmap [instance] (n : ℕ₋₂) (A B : Type*) [is_trunc n B] :
is_trunc n (A →* B) :=
is_trunc_equiv_closed_rev _ !pmap.sigma_char
definition is_trunc_ppmap [instance] (n : ℕ₋₂) {A B : Type*} [is_trunc n B] :
is_trunc n (ppmap A B) :=
!is_trunc_pmap
definition phomotopy_of_eq [constructor] {A B : Type*} {f g : A →* B} (p : f = g) : f ~* g :=
phomotopy.mk (ap010 pmap.to_fun p) begin induction p, apply idp_con end
definition pconcat_eq [constructor] {A B : Type*} {f g h : A →* B} (p : f ~* g) (q : g = h)
: f ~* h :=
p ⬝* phomotopy_of_eq q
definition eq_pconcat [constructor] {A B : Type*} {f g h : A →* B} (p : f = g) (q : g ~* h)
: f ~* h :=
phomotopy_of_eq p ⬝* q
infix ` ⬝*p `:75 := pconcat_eq
infix ` ⬝p* `:75 := eq_pconcat
definition pmap_eq_equiv_internal {A B : Type*} (f g : A →* B) : (f = g) ≃ (f ~* g) :=
calc (f = g) ≃ pmap.sigma_char f = pmap.sigma_char g
: eq_equiv_fn_eq pmap.sigma_char f g
... ≃ Σ(p : pmap.to_fun f = pmap.to_fun g),
pathover (λh, h pt = pt) (respect_pt f) p (respect_pt g)
: sigma_eq_equiv _ _
... ≃ Σ(p : pmap.to_fun f = pmap.to_fun g), respect_pt f = ap (λh, h pt) p ⬝ respect_pt g
: sigma_equiv_sigma_right (λp, eq_pathover_equiv_Fl p (respect_pt f)
(respect_pt g))
... ≃ Σ(p : pmap.to_fun f = pmap.to_fun g), respect_pt f = ap10 p pt ⬝ respect_pt g
: sigma_equiv_sigma_right
(λp, equiv_eq_closed_right _ (whisker_right _ (ap_eq_apd10 p _)))
... ≃ Σ(p : pmap.to_fun f ~ pmap.to_fun g), respect_pt f = p pt ⬝ respect_pt g
: sigma_equiv_sigma_left' eq_equiv_homotopy
... ≃ Σ(p : pmap.to_fun f ~ pmap.to_fun g), p pt ⬝ respect_pt g = respect_pt f
: sigma_equiv_sigma_right (λp, eq_equiv_eq_symm _ _)
... ≃ (f ~* g) : phomotopy.sigma_char f g
definition pmap_eq_equiv_internal_idp {A B : Type*} (f : A →* B) :
pmap_eq_equiv_internal f f idp = phomotopy.refl f :=
begin
apply ap (phomotopy.mk (homotopy.refl _)), induction B with B b₀, induction f with f f₀,
esimp at *, induction f₀, reflexivity
end
definition eq_of_phomotopy' (p : f ~* g) : f = g :=
to_inv (pmap_eq_equiv_internal f g) p
definition pmap_eq_equiv {A B : Type*} (f g : A →* B) : (f = g) ≃ (f ~* g) :=
begin
refine equiv_change_fun (pmap_eq_equiv_internal f g) _,
{ apply phomotopy_of_eq },
{ intro p, induction p, exact pmap_eq_equiv_internal_idp f }
end
definition eq_of_phomotopy (p : f ~* g) : f = g :=
to_inv (pmap_eq_equiv f g) p
-- TODO: flip arguments in s
definition pmap_eq (r : Πa, f a = g a) (s : respect_pt f = (r pt) ⬝ respect_pt g) : f = g :=
eq_of_phomotopy (phomotopy.mk r s⁻¹)
definition pmap_eq_of_homotopy {A B : Type*} {f g : A →* B} [is_set B] (p : f ~ g) : f = g :=
pmap_eq p !is_set.elim
definition pmap_equiv_left (A : Type) (B : Type*) : A₊ →* B ≃ (A → B) :=
begin
fapply equiv.MK,
{ intro f a, cases f with f p, exact f (some a)},
{ intro f, fconstructor,
intro a, cases a, exact pt, exact f a,
reflexivity},
{ intro f, reflexivity},
{ intro f, cases f with f p, esimp, fapply pmap_eq,
{ intro a, cases a; all_goals (esimp at *), exact p⁻¹},
{ esimp, exact !con.left_inv⁻¹}},
end
-- pmap_pbool_pequiv is the pointed equivalence
definition pmap_pbool_equiv [constructor] (B : Type*) : (pbool →* B) ≃ B :=
begin
fapply equiv.MK,
{ intro f, cases f with f p, exact f tt},
{ intro b, fconstructor,
intro u, cases u, exact pt, exact b,
reflexivity},
{ intro b, reflexivity},
{ intro f, cases f with f p, esimp, fapply pmap_eq,
{ intro a, cases a; all_goals (esimp at *), exact p⁻¹},
{ esimp, exact !con.left_inv⁻¹}},
end
/-
Pointed maps respecting pointed homotopies.
In general we need function extensionality for pap,
but for particular F we can do it without function extensionality.
This is preferred, because such pointed homotopies compute
-/
definition pap (F : (A →* B) → (C →* D)) {f g : A →* B} (p : f ~* g) : F f ~* F g :=
phomotopy.mk (ap010 (λf, pmap.to_fun (F f)) (eq_of_phomotopy p))
begin cases eq_of_phomotopy p, apply idp_con end
definition ap1_phomotopy {f g : A →* B} (p : f ~* g)
: ap1 f ~* ap1 g :=
begin
induction p with p q, induction f with f pf, induction g with g pg, induction B with B b,
esimp at *, induction q, induction pg,
fapply phomotopy.mk,
{ intro l, esimp, refine _ ⬝ !idp_con⁻¹, refine !con.assoc ⬝ _, apply inv_con_eq_of_eq_con,
apply ap_con_eq_con_ap},
{ induction A with A a, unfold [ap_con_eq_con_ap], generalize p a, generalize g a, intro b q,
induction q, reflexivity}
end
definition apn_phomotopy {f g : A →* B} (n : ℕ) (p : f ~* g) : apn n f ~* apn n g :=
begin
induction n with n IH,
{ exact p},
{ exact ap1_phomotopy IH}
end
/- pointed homotopies between the given pointed maps -/
definition ap1_pid [constructor] {A : Type*} : ap1 (pid A) ~* pid (Ω A) :=
begin
fapply phomotopy.mk,
{ intro p, esimp, refine !idp_con ⬝ !ap_id},
{ reflexivity}
end
definition ap1_pinverse {A : Type*} : ap1 (@pinverse A) ~* @pinverse (Ω A) :=
begin
fapply phomotopy.mk,
{ intro p, esimp, refine !idp_con ⬝ _, exact !inv_eq_inv2⁻¹ },
{ reflexivity}
end
definition ap1_pcompose (g : B →* C) (f : A →* B) : ap1 (g ∘* f) ~* ap1 g ∘* ap1 f :=
begin
induction B, induction C, induction g with g pg, induction f with f pf, esimp at *,
induction pg, induction pf,
fconstructor,
{ intro p, esimp, apply whisker_left, exact ap_compose g f p ⬝ ap (ap g) !idp_con⁻¹},
{ reflexivity}
end
definition ap1_pcompose_pinverse (f : A →* B) : ap1 f ∘* pinverse ~* pinverse ∘* ap1 f :=
begin
fconstructor,
{ intro p, esimp, refine !con.assoc ⬝ _ ⬝ !con_inv⁻¹, apply whisker_left,
refine whisker_right _ !ap_inv ⬝ _ ⬝ !con_inv⁻¹, apply whisker_left,
exact !inv_inv⁻¹},
{ induction B with B b, induction f with f pf, esimp at *, induction pf, reflexivity},
end
definition ap1_pconst (A B : Type*) : Ω→(pconst A B) ~* pconst (Ω A) (Ω B) :=
phomotopy.mk (λp, idp_con _ ⬝ ap_constant p pt) rfl
definition ptransport_change_eq [constructor] {A : Type} (B : A → Type*) {a a' : A} {p q : a = a'}
(r : p = q) : ptransport B p ~* ptransport B q :=
phomotopy.mk (λb, ap (λp, transport B p b) r) begin induction r, apply idp_con end
definition pnatural_square {A B : Type} (X : B → Type*) {f g : A → B}
(h : Πa, X (f a) →* X (g a)) {a a' : A} (p : a = a') :
h a' ∘* ptransport X (ap f p) ~* ptransport X (ap g p) ∘* h a :=
by induction p; exact !pcompose_pid ⬝* !pid_pcompose⁻¹*
definition apn_pid [constructor] {A : Type*} (n : ℕ) : apn n (pid A) ~* pid (Ω[n] A) :=
begin
induction n with n IH,
{ reflexivity},
{ exact ap1_phomotopy IH ⬝* ap1_pid}
end
definition apn_pconst (A B : Type*) (n : ℕ) :
apn n (pconst A B) ~* pconst (Ω[n] A) (Ω[n] B) :=
begin
induction n with n IH,
{ reflexivity },
{ exact ap1_phomotopy IH ⬝* !ap1_pconst }
end
definition apn_pcompose (n : ℕ) (g : B →* C) (f : A →* B) :
apn n (g ∘* f) ~* apn n g ∘* apn n f :=
begin
induction n with n IH,
{ reflexivity},
{ refine ap1_phomotopy IH ⬝* _, apply ap1_pcompose}
end
definition pcast_idp [constructor] {A : Type*} : pcast (idpath A) ~* pid A :=
by reflexivity
definition pinverse_pinverse (A : Type*) : pinverse ∘* pinverse ~* pid (Ω A) :=
begin
fapply phomotopy.mk,
{ apply inv_inv},
{ reflexivity}
end
definition pcast_ap_loop [constructor] {A B : Type*} (p : A = B) :
pcast (ap Ω p) ~* ap1 (pcast p) :=
begin
fapply phomotopy.mk,
{ intro a, induction p, esimp, exact (!idp_con ⬝ !ap_id)⁻¹},
{ induction p, reflexivity}
end
definition ap1_pmap_of_map [constructor] {A B : Type} (f : A → B) (a : A) :
ap1 (pmap_of_map f a) ~* pmap_of_map (ap f) (idpath a) :=
begin
fapply phomotopy.mk,
{ intro a, esimp, apply idp_con},
{ reflexivity}
end
definition pcast_commute [constructor] {A : Type} {B C : A → Type*} (f : Πa, B a →* C a)
{a₁ a₂ : A} (p : a₁ = a₂) : pcast (ap C p) ∘* f a₁ ~* f a₂ ∘* pcast (ap B p) :=
phomotopy.mk
begin induction p, reflexivity end
begin induction p, esimp, refine !idp_con ⬝ !idp_con ⬝ !ap_id⁻¹ end
/- pointed equivalences -/
/- constructors / projections + variants -/
definition pequiv_of_pmap [constructor] (f : A →* B) (H : is_equiv f) : A ≃* B :=
pequiv.mk f _ (respect_pt f)
definition pequiv_of_equiv [constructor] (f : A ≃ B) (H : f pt = pt) : A ≃* B :=
pequiv.mk f _ H
protected definition pequiv.MK [constructor] (f : A →* B) (g : B → A)
(gf : Πa, g (f a) = a) (fg : Πb, f (g b) = b) : A ≃* B :=
pequiv.mk f (adjointify f g fg gf) (respect_pt f)
definition equiv_of_pequiv [constructor] (f : A ≃* B) : A ≃ B :=
equiv.mk f _
definition to_pinv [constructor] (f : A ≃* B) : B →* A :=
pmap.mk f⁻¹ ((ap f⁻¹ (respect_pt f))⁻¹ ⬝ left_inv f pt)
definition to_pmap_pequiv_of_pmap {A B : Type*} (f : A →* B) (H : is_equiv f)
: pequiv.to_pmap (pequiv_of_pmap f H) = f :=
by cases f; reflexivity
/-
A version of pequiv.MK with stronger conditions.
The advantage of defining a pointed equivalence with this definition is that there is a
pointed homotopy between the inverse of the resulting equivalence and the given pointed map g.
This is not the case when using `pequiv.MK` (if g is a pointed map),
that will only give an ordinary homotopy.
-/
protected definition pequiv.MK2 [constructor] (f : A →* B) (g : B →* A)
(gf : g ∘* f ~* !pid) (fg : f ∘* g ~* !pid) : A ≃* B :=
pequiv.MK f g gf fg
definition to_pmap_pequiv_MK2 [constructor] (f : A →* B) (g : B →* A)
(gf : g ∘* f ~* !pid) (fg : f ∘* g ~* !pid) : pequiv.MK2 f g gf fg ~* f :=
phomotopy.mk (λb, idp) !idp_con
definition to_pinv_pequiv_MK2 [constructor] (f : A →* B) (g : B →* A)
(gf : g ∘* f ~* !pid) (fg : f ∘* g ~* !pid) : to_pinv (pequiv.MK2 f g gf fg) ~* g :=
phomotopy.mk (λb, idp)
abstract [irreducible] begin
esimp,
note H := to_homotopy_pt gf, note H2 := to_homotopy_pt fg,
note H3 := eq_top_of_square (natural_square (to_homotopy fg) (respect_pt f)),
rewrite [▸* at *, H, H3, H2, ap_id, - +con.assoc, ap_compose' f g, con_inv,
- ap_inv, - +ap_con g],
apply whisker_right, apply ap02 g,
rewrite [ap_con, - + con.assoc, +ap_inv, +inv_con_cancel_right, con.left_inv],
end end
/- categorical properties of pointed equivalences -/
protected definition pequiv.refl [refl] [constructor] (A : Type*) : A ≃* A :=
pequiv_of_pmap !pid !is_equiv_id
protected definition pequiv.rfl [constructor] : A ≃* A :=
pequiv.refl A
protected definition pequiv.symm [symm] [constructor] (f : A ≃* B) : B ≃* A :=
pequiv_of_pmap (to_pinv f) !is_equiv_inv
protected definition pequiv.trans [trans] [constructor] (f : A ≃* B) (g : B ≃* C) : A ≃* C :=
pequiv_of_pmap (g ∘* f) !is_equiv_compose
definition pequiv_compose {A B C : Type*} (g : B ≃* C) (f : A ≃* B) : A ≃* C :=
pequiv_of_pmap (g ∘* f) (is_equiv_compose g f)
infixr ` ∘*ᵉ `:60 := pequiv_compose
postfix `⁻¹ᵉ*`:(max + 1) := pequiv.symm
infix ` ⬝e* `:75 := pequiv.trans
/- more on pointed equivalences -/
definition pequiv_ap [constructor] {A : Type} (B : A → Type*) {a a' : A} (p : a = a')
: B a ≃* B a' :=
pequiv_of_pmap (ptransport B p) !is_equiv_tr
definition to_pmap_pequiv_trans {A B C : Type*} (f : A ≃* B) (g : B ≃* C)
: pequiv.to_pmap (f ⬝e* g) = g ∘* f :=
!to_pmap_pequiv_of_pmap
definition pequiv_change_fun [constructor] (f : A ≃* B) (f' : A →* B) (Heq : f ~ f') : A ≃* B :=
pequiv_of_pmap f' (is_equiv.homotopy_closed f Heq)
definition pequiv_change_inv [constructor] (f : A ≃* B) (f' : B →* A) (Heq : to_pinv f ~ f')
: A ≃* B :=
pequiv.MK f f' (to_left_inv (equiv_change_inv f Heq)) (to_right_inv (equiv_change_inv f Heq))
definition pequiv_rect' (f : A ≃* B) (P : A → B → Type)
(g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) :=
left_inv f a ▸ g (f a)
definition pua {A B : Type*} (f : A ≃* B) : A = B :=
pType_eq (equiv_of_pequiv f) !respect_pt
definition pequiv_of_eq [constructor] {A B : Type*} (p : A = B) : A ≃* B :=
pequiv_of_pmap (pcast p) !is_equiv_tr
definition peconcat_eq {A B C : Type*} (p : A ≃* B) (q : B = C) : A ≃* C :=
p ⬝e* pequiv_of_eq q
definition eq_peconcat {A B C : Type*} (p : A = B) (q : B ≃* C) : A ≃* C :=
pequiv_of_eq p ⬝e* q
definition eq_of_pequiv {A B : Type*} (p : A ≃* B) : A = B :=
pType_eq (equiv_of_pequiv p) !respect_pt
definition peap {A B : Type*} (F : Type* → Type*) (p : A ≃* B) : F A ≃* F B :=
pequiv_of_pmap (pcast (ap F (eq_of_pequiv p))) begin cases eq_of_pequiv p, apply is_equiv_id end
infix ` ⬝e*p `:75 := peconcat_eq
infix ` ⬝pe* `:75 := eq_peconcat
definition pequiv_of_eq_commute [constructor] {A : Type} {B C : A → Type*} (f : Πa, B a →* C a)
{a₁ a₂ : A} (p : a₁ = a₂) : pequiv_of_eq (ap C p) ∘* f a₁ ~* f a₂ ∘* pequiv_of_eq (ap B p) :=
pcast_commute f p
definition pequiv.eta_expand [constructor] {A B : Type*} (f : A ≃* B) : A ≃* B :=
pequiv.mk f _ (pequiv.resp_pt f)
/-
the theorem pequiv_eq, which gives a condition for two pointed equivalences are equal
is in types.equiv to avoid circular imports
-/
/- computation rules of pointed homotopies, possibly combined with pointed equivalences -/
definition pwhisker_left [constructor] (h : B →* C) (p : f ~* g) : h ∘* f ~* h ∘* g :=
phomotopy.mk (λa, ap h (p a))
abstract !con.assoc⁻¹ ⬝ whisker_right _ (!ap_con⁻¹ ⬝ ap02 _ (to_homotopy_pt p)) end
definition pwhisker_right [constructor] (h : C →* A) (p : f ~* g) : f ∘* h ~* g ∘* h :=
phomotopy.mk (λa, p (h a))
abstract !con.assoc⁻¹ ⬝ whisker_right _ (!ap_con_eq_con_ap)⁻¹ ⬝ !con.assoc ⬝
whisker_left _ (to_homotopy_pt p) end
definition pconcat2 [constructor] {A B C : Type*} {h i : B →* C} {f g : A →* B}
(q : h ~* i) (p : f ~* g) : h ∘* f ~* i ∘* g :=
pwhisker_left _ p ⬝* pwhisker_right _ q
definition pleft_inv (f : A ≃* B) : f⁻¹ᵉ* ∘* f ~* pid A :=
phomotopy.mk (left_inv f)
abstract begin
esimp, symmetry, apply con_inv_cancel_left
end end
definition pright_inv (f : A ≃* B) : f ∘* f⁻¹ᵉ* ~* pid B :=
phomotopy.mk (right_inv f)
abstract begin
induction f with f H p, esimp,
rewrite [ap_con, +ap_inv, -adj f, -ap_compose],
note q := natural_square (right_inv f) p,
rewrite [ap_id at q],
apply eq_bot_of_square,
exact q
end end
definition pcancel_left (f : B ≃* C) {g h : A →* B} (p : f ∘* g ~* f ∘* h) : g ~* h :=
begin
refine _⁻¹* ⬝* pwhisker_left f⁻¹ᵉ* p ⬝* _:
refine !passoc⁻¹* ⬝* _:
refine pwhisker_right _ (pleft_inv f) ⬝* _:
apply pid_pcompose
end
definition pcancel_right (f : A ≃* B) {g h : B →* C} (p : g ∘* f ~* h ∘* f) : g ~* h :=
begin
refine _⁻¹* ⬝* pwhisker_right f⁻¹ᵉ* p ⬝* _:
refine !passoc ⬝* _:
refine pwhisker_left _ (pright_inv f) ⬝* _:
apply pcompose_pid
end
definition phomotopy_pinv_right_of_phomotopy {f : A ≃* B} {g : B →* C} {h : A →* C}
(p : g ∘* f ~* h) : g ~* h ∘* f⁻¹ᵉ* :=
begin
refine _ ⬝* pwhisker_right _ p, symmetry,
refine !passoc ⬝* _,
refine pwhisker_left _ (pright_inv f) ⬝* _,
apply pcompose_pid
end
definition phomotopy_of_pinv_right_phomotopy {f : B ≃* A} {g : B →* C} {h : A →* C}
(p : g ∘* f⁻¹ᵉ* ~* h) : g ~* h ∘* f :=
begin
refine _ ⬝* pwhisker_right _ p, symmetry,
refine !passoc ⬝* _,
refine pwhisker_left _ (pleft_inv f) ⬝* _,
apply pcompose_pid
end
definition pinv_right_phomotopy_of_phomotopy {f : A ≃* B} {g : B →* C} {h : A →* C}
(p : h ~* g ∘* f) : h ∘* f⁻¹ᵉ* ~* g :=
(phomotopy_pinv_right_of_phomotopy p⁻¹*)⁻¹*
definition phomotopy_of_phomotopy_pinv_right {f : B ≃* A} {g : B →* C} {h : A →* C}
(p : h ~* g ∘* f⁻¹ᵉ*) : h ∘* f ~* g :=
(phomotopy_of_pinv_right_phomotopy p⁻¹*)⁻¹*
definition phomotopy_pinv_left_of_phomotopy {f : B ≃* C} {g : A →* B} {h : A →* C}
(p : f ∘* g ~* h) : g ~* f⁻¹ᵉ* ∘* h :=
begin
refine _ ⬝* pwhisker_left _ p, symmetry,
refine !passoc⁻¹* ⬝* _,
refine pwhisker_right _ (pleft_inv f) ⬝* _,
apply pid_pcompose
end
definition phomotopy_of_pinv_left_phomotopy {f : C ≃* B} {g : A →* B} {h : A →* C}
(p : f⁻¹ᵉ* ∘* g ~* h) : g ~* f ∘* h :=
begin
refine _ ⬝* pwhisker_left _ p, symmetry,
refine !passoc⁻¹* ⬝* _,
refine pwhisker_right _ (pright_inv f) ⬝* _,
apply pid_pcompose
end
definition pinv_left_phomotopy_of_phomotopy {f : B ≃* C} {g : A →* B} {h : A →* C}
(p : h ~* f ∘* g) : f⁻¹ᵉ* ∘* h ~* g :=
(phomotopy_pinv_left_of_phomotopy p⁻¹*)⁻¹*
definition phomotopy_of_phomotopy_pinv_left {f : C ≃* B} {g : A →* B} {h : A →* C}
(p : h ~* f⁻¹ᵉ* ∘* g) : f ∘* h ~* g :=
(phomotopy_of_pinv_left_phomotopy p⁻¹*)⁻¹*
definition pcompose2 {A B C : Type*} {g g' : B →* C} {f f' : A →* B} (p : f ~* f') (q : g ~* g') :
g ∘* f ~* g' ∘* f' :=
pwhisker_right f q ⬝* pwhisker_left g' p
infixr ` ◾* `:80 := pcompose2
definition phomotopy_pinv_of_phomotopy_pid {A B : Type*} {f : A →* B} {g : B ≃* A}
(p : g ∘* f ~* pid A) : f ~* g⁻¹ᵉ* :=
phomotopy_pinv_left_of_phomotopy p ⬝* !pcompose_pid
definition phomotopy_pinv_of_phomotopy_pid' {A B : Type*} {f : A →* B} {g : B ≃* A}
(p : f ∘* g ~* pid B) : f ~* g⁻¹ᵉ* :=
phomotopy_pinv_right_of_phomotopy p ⬝* !pid_pcompose
definition pinv_phomotopy_of_pid_phomotopy {A B : Type*} {f : A →* B} {g : B ≃* A}
(p : pid A ~* g ∘* f) : g⁻¹ᵉ* ~* f :=
(phomotopy_pinv_of_phomotopy_pid p⁻¹*)⁻¹*
definition pinv_phomotopy_of_pid_phomotopy' {A B : Type*} {f : A →* B} {g : B ≃* A}
(p : pid B ~* f ∘* g) : g⁻¹ᵉ* ~* f :=
(phomotopy_pinv_of_phomotopy_pid' p⁻¹*)⁻¹*
definition pinv_pinv {A B : Type*} (f : A ≃* B) : (f⁻¹ᵉ*)⁻¹ᵉ* ~* f :=
(phomotopy_pinv_of_phomotopy_pid (pleft_inv f))⁻¹*
definition pinv2 {A B : Type*} {f f' : A ≃* B} (p : f ~* f') : f⁻¹ᵉ* ~* f'⁻¹ᵉ* :=
phomotopy_pinv_of_phomotopy_pid (pinv_right_phomotopy_of_phomotopy (!pid_pcompose ⬝* p)⁻¹*)
postfix [parsing_only] `⁻²*`:(max+10) := pinv2
definition trans_pinv {A B C : Type*} (f : A ≃* B) (g : B ≃* C) :
(f ⬝e* g)⁻¹ᵉ* ~* f⁻¹ᵉ* ∘* g⁻¹ᵉ* :=
begin
refine (phomotopy_pinv_of_phomotopy_pid _)⁻¹*,
refine !passoc ⬝* _,
refine pwhisker_left _ (!passoc⁻¹* ⬝* pwhisker_right _ !pright_inv ⬝* !pid_pcompose) ⬝* _,
apply pright_inv
end
definition pinv_trans_pinv_left {A B C : Type*} (f : B ≃* A) (g : B ≃* C) :
(f⁻¹ᵉ* ⬝e* g)⁻¹ᵉ* ~* f ∘* g⁻¹ᵉ* :=
!trans_pinv ⬝* pwhisker_right _ !pinv_pinv
definition pinv_trans_pinv_right {A B C : Type*} (f : A ≃* B) (g : C ≃* B) :
(f ⬝e* g⁻¹ᵉ*)⁻¹ᵉ* ~* f⁻¹ᵉ* ∘* g :=
!trans_pinv ⬝* pwhisker_left _ !pinv_pinv
definition pinv_trans_pinv_pinv {A B C : Type*} (f : B ≃* A) (g : C ≃* B) :
(f⁻¹ᵉ* ⬝e* g⁻¹ᵉ*)⁻¹ᵉ* ~* f ∘* g :=
!trans_pinv ⬝* !pinv_pinv ◾* !pinv_pinv
definition pinv_pcompose_cancel_left {A B C : Type*} (g : B ≃* C) (f : A →* B) :
g⁻¹ᵉ* ∘* (g ∘* f) ~* f :=
!passoc⁻¹* ⬝* pwhisker_right f !pleft_inv ⬝* !pid_pcompose
definition pcompose_pinv_cancel_left {A B C : Type*} (g : C ≃* B) (f : A →* B) :
g ∘* (g⁻¹ᵉ* ∘* f) ~* f :=
!passoc⁻¹* ⬝* pwhisker_right f !pright_inv ⬝* !pid_pcompose
definition pinv_pcompose_cancel_right {A B C : Type*} (g : B →* C) (f : B ≃* A) :
(g ∘* f⁻¹ᵉ*) ∘* f ~* g :=
!passoc ⬝* pwhisker_left g !pleft_inv ⬝* !pcompose_pid
definition pcompose_pinv_cancel_right {A B C : Type*} (g : B →* C) (f : A ≃* B) :
(g ∘* f) ∘* f⁻¹ᵉ* ~* g :=
!passoc ⬝* pwhisker_left g !pright_inv ⬝* !pcompose_pid
/- pointed equivalences between particular pointed types -/
-- TODO: remove is_equiv_apn, which is proven again here
definition loopn_pequiv_loopn [constructor] (n : ℕ) (f : A ≃* B) : Ω[n] A ≃* Ω[n] B :=
pequiv.MK2 (apn n f) (apn n f⁻¹ᵉ*)
abstract begin
induction n with n IH,
{ apply pleft_inv},
{ replace nat.succ n with n + 1,
rewrite [+apn_succ],
refine !ap1_pcompose⁻¹* ⬝* _,
refine ap1_phomotopy IH ⬝* _,
apply ap1_pid}
end end
abstract begin
induction n with n IH,
{ apply pright_inv},
{ replace nat.succ n with n + 1,
rewrite [+apn_succ],
refine !ap1_pcompose⁻¹* ⬝* _,
refine ap1_phomotopy IH ⬝* _,
apply ap1_pid}
end end
definition loop_pequiv_loop [constructor] (f : A ≃* B) : Ω A ≃* Ω B :=
loopn_pequiv_loopn 1 f
definition to_pmap_loopn_pequiv_loopn [constructor] (n : ℕ) (f : A ≃* B)
: loopn_pequiv_loopn n f ~* apn n f :=
!to_pmap_pequiv_MK2
definition to_pinv_loopn_pequiv_loopn [constructor] (n : ℕ) (f : A ≃* B)
: (loopn_pequiv_loopn n f)⁻¹ᵉ* ~* apn n f⁻¹ᵉ* :=
!to_pinv_pequiv_MK2
definition loopn_pequiv_loopn_con (n : ℕ) (f : A ≃* B) (p q : Ω[n+1] A)
: loopn_pequiv_loopn (n+1) f (p ⬝ q) =
loopn_pequiv_loopn (n+1) f p ⬝ loopn_pequiv_loopn (n+1) f q :=
ap1_con (loopn_pequiv_loopn n f) p q
definition loop_pequiv_loop_con {A B : Type*} (f : A ≃* B) (p q : Ω A)
: loop_pequiv_loop f (p ⬝ q) = loop_pequiv_loop f p ⬝ loop_pequiv_loop f q :=
loopn_pequiv_loopn_con 0 f p q
definition loopn_pequiv_loopn_rfl (n : ℕ) (A : Type*) :
loopn_pequiv_loopn n (pequiv.refl A) ~* pequiv.refl (Ω[n] A) :=
begin
exact !to_pmap_loopn_pequiv_loopn ⬝* apn_pid n,
end
definition loop_pequiv_loop_rfl (A : Type*) :
loop_pequiv_loop (pequiv.refl A) ~* pequiv.refl (Ω A) :=
loopn_pequiv_loopn_rfl 1 A
definition pmap_functor [constructor] {A A' B B' : Type*} (f : A' →* A) (g : B →* B') :
ppmap A B →* ppmap A' B' :=
pmap.mk (λh, g ∘* h ∘* f)
abstract begin
fapply pmap_eq,
{ esimp, intro a, exact respect_pt g},
{ rewrite [▸*, ap_constant], apply idp_con}
end end
definition pequiv_pinverse (A : Type*) : Ω A ≃* Ω A :=
pequiv_of_pmap pinverse !is_equiv_eq_inverse
definition pequiv_of_eq_pt [constructor] {A : Type} {a a' : A} (p : a = a') :
pointed.MK A a ≃* pointed.MK A a' :=
pequiv_of_pmap (pmap_of_eq_pt p) !is_equiv_id
definition pointed_eta_pequiv [constructor] (A : Type*) : A ≃* pointed.MK A pt :=
pequiv.mk id !is_equiv_id idp
/- every pointed map is homotopic to one of the form `pmap_of_map _ _`, up to some
pointed equivalences -/
definition phomotopy_pmap_of_map {A B : Type*} (f : A →* B) :
(pointed_eta_pequiv B ⬝e* (pequiv_of_eq_pt (respect_pt f))⁻¹ᵉ*) ∘* f ∘*
(pointed_eta_pequiv A)⁻¹ᵉ* ~* pmap_of_map f pt :=
begin
fapply phomotopy.mk,
{ reflexivity},
{ esimp [pequiv.trans, pequiv.symm],
exact !con.right_inv⁻¹ ⬝ ((!idp_con⁻¹ ⬝ !ap_id⁻¹) ◾ (!ap_id⁻¹⁻² ⬝ !idp_con⁻¹)), }
end
/- -- TODO
definition pmap_pequiv_pmap {A A' B B' : Type*} (f : A ≃* A') (g : B ≃* B') :
ppmap A B ≃* ppmap A' B' :=
pequiv.MK (pmap_functor f⁻¹ᵉ* g) (pmap_functor f g⁻¹ᵉ*)
abstract begin
intro a, esimp, apply pmap_eq,
{ esimp, },
{ }
end end
abstract begin
end end
-/
/- properties of iterated loop space -/
variable (A)
definition loopn_succ_in (n : ℕ) : Ω[succ n] A ≃* Ω[n] (Ω A) :=
begin
induction n with n IH,
{ reflexivity},
{ exact loop_pequiv_loop IH}
end
definition loopn_add (n m : ℕ) : Ω[n] (Ω[m] A) ≃* Ω[m+n] (A) :=
begin
induction n with n IH,
{ reflexivity},
{ exact loop_pequiv_loop IH}
end
definition loopn_succ_out (n : ℕ) : Ω[succ n] A ≃* Ω(Ω[n] A) :=
by reflexivity
variable {A}
definition loopn_succ_in_con {n : ℕ} (p q : Ω[succ (succ n)] A) :
loopn_succ_in A (succ n) (p ⬝ q) =
loopn_succ_in A (succ n) p ⬝ loopn_succ_in A (succ n) q :=
!loop_pequiv_loop_con
definition loopn_loop_irrel (p : point A = point A) : Ω(pointed.Mk p) = Ω[2] A :=
begin
intros, fapply pType_eq,
{ esimp, transitivity _,
apply eq_equiv_fn_eq_of_equiv (equiv_eq_closed_right _ p⁻¹),
esimp, apply eq_equiv_eq_closed, apply con.right_inv, apply con.right_inv},
{ esimp, apply con.left_inv}
end
definition loopn_space_loop_irrel (n : ℕ) (p : point A = point A)
: Ω[succ n](pointed.Mk p) = Ω[succ (succ n)] A :> pType :=
calc
Ω[succ n](pointed.Mk p) = Ω[n](Ω (pointed.Mk p)) : eq_of_pequiv !loopn_succ_in
... = Ω[n] (Ω[2] A) : loopn_loop_irrel
... = Ω[2+n] A : eq_of_pequiv !loopn_add
... = Ω[n+2] A : by rewrite [algebra.add.comm]
definition apn_succ_phomotopy_in (n : ℕ) (f : A →* B) :
loopn_succ_in B n ∘* Ω→[n + 1] f ~* Ω→[n] (Ω→ f) ∘* loopn_succ_in A n :=
begin
induction n with n IH,
{ reflexivity},
{ exact !ap1_pcompose⁻¹* ⬝* ap1_phomotopy IH ⬝* !ap1_pcompose}
end
definition loopn_succ_in_natural {A B : Type*} (n : ℕ) (f : A →* B) :
loopn_succ_in B n ∘* Ω→[n+1] f ~* Ω→[n] (Ω→ f) ∘* loopn_succ_in A n :=
!apn_succ_phomotopy_in
definition loopn_succ_in_inv_natural {A B : Type*} (n : ℕ) (f : A →* B) :
Ω→[n + 1] f ∘* (loopn_succ_in A n)⁻¹ᵉ* ~* (loopn_succ_in B n)⁻¹ᵉ* ∘* Ω→[n] (Ω→ f):=
begin
apply pinv_right_phomotopy_of_phomotopy,
refine _ ⬝* !passoc⁻¹*,
apply phomotopy_pinv_left_of_phomotopy,
apply apn_succ_phomotopy_in
end
/- properties of ppmap, the pointed type of pointed maps -/
definition pcompose_pconst [constructor] (f : B →* C) : f ∘* pconst A B ~* pconst A C :=
phomotopy.mk (λa, respect_pt f) (idp_con _)⁻¹
definition pconst_pcompose [constructor] (f : A →* B) : pconst B C ∘* f ~* pconst A C :=
phomotopy.mk (λa, rfl) (ap_constant _ _)⁻¹
definition ppcompose_left [constructor] (g : B →* C) : ppmap A B →* ppmap A C :=
pmap.mk (pcompose g) (eq_of_phomotopy (pcompose_pconst g))
definition is_pequiv_ppcompose_left [instance] [constructor] (g : B →* C) [H : is_equiv g] :
is_equiv (@ppcompose_left A B C g) :=
begin
fapply is_equiv.adjointify,
{ exact (ppcompose_left (pequiv_of_pmap g H)⁻¹ᵉ*) },
all_goals (intros f; esimp; apply eq_of_phomotopy),
{ exact calc g ∘* ((pequiv_of_pmap g H)⁻¹ᵉ* ∘* f)
~* (g ∘* (pequiv_of_pmap g H)⁻¹ᵉ*) ∘* f : passoc
... ~* pid _ ∘* f : pwhisker_right f (pright_inv (pequiv_of_pmap g H))
... ~* f : pid_pcompose f },
{ exact calc (pequiv_of_pmap g H)⁻¹ᵉ* ∘* (g ∘* f)
~* ((pequiv_of_pmap g H)⁻¹ᵉ* ∘* g) ∘* f : passoc
... ~* pid _ ∘* f : pwhisker_right f (pleft_inv (pequiv_of_pmap g H))
... ~* f : pid_pcompose f }
end
definition pequiv_ppcompose_left [constructor] (g : B ≃* C) : ppmap A B ≃* ppmap A C :=
pequiv_of_pmap (ppcompose_left g) _
definition ppcompose_right [constructor] (f : A →* B) : ppmap B C →* ppmap A C :=
pmap.mk (λg, g ∘* f) (eq_of_phomotopy (pconst_pcompose f))
definition pequiv_ppcompose_right [constructor] (f : A ≃* B) : ppmap B C ≃* ppmap A C :=
begin
fapply pequiv.MK,
{ exact ppcompose_right f },
{ exact ppcompose_right f⁻¹ᵉ* },
{ intro g, apply eq_of_phomotopy, refine !passoc ⬝* _,
refine pwhisker_left g !pright_inv ⬝* !pcompose_pid, },
{ intro g, apply eq_of_phomotopy, refine !passoc ⬝* _,
refine pwhisker_left g !pleft_inv ⬝* !pcompose_pid, },
end
definition loop_pmap_commute (A B : Type*) : Ω(ppmap A B) ≃* (ppmap A (Ω B)) :=
pequiv_of_equiv
(calc Ω(ppmap A B) ≃ (pconst A B ~* pconst A B) : pmap_eq_equiv _ _
... ≃ Σ(p : pconst A B ~ pconst A B), p pt ⬝ rfl = rfl : phomotopy.sigma_char
... ≃ (A →* Ω B) : pmap.sigma_char)
(by reflexivity)
definition papply [constructor] {A : Type*} (B : Type*) (a : A) : ppmap A B →* B :=
pmap.mk (λ(f : A →* B), f a) idp
definition papply_pcompose [constructor] {A : Type*} (B : Type*) (a : A) : ppmap A B →* B :=
pmap.mk (λ(f : A →* B), f a) idp
definition pmap_pbool_pequiv [constructor] (B : Type*) : ppmap pbool B ≃* B :=
begin
fapply pequiv.MK,
{ exact papply B tt },
{ exact pbool_pmap },
{ intro f, fapply pmap_eq,
{ intro b, cases b, exact !respect_pt⁻¹, reflexivity },
{ exact !con.left_inv⁻¹ }},
{ intro b, reflexivity },
end
definition papn_pt [constructor] (n : ℕ) (A B : Type*) : ppmap A B →* ppmap (Ω[n] A) (Ω[n] B) :=
pmap.mk (λf, apn n f) (eq_of_phomotopy !apn_pconst)
definition papn_fun [constructor] {n : ℕ} {A : Type*} (B : Type*) (p : Ω[n] A) :
ppmap A B →* Ω[n] B :=
papply _ p ∘* papn_pt n A B
end pointed
|
11c044fded1e464af0459cc6bb59887f205a85af
|
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
|
/stage0/src/Lean/Elab/App.lean
|
4c7342378ad5f2d5cb19587ad77a6d4717f43602
|
[
"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
| 42,717
|
lean
|
/-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.FindMVar
import Lean.Parser.Term
import Lean.Elab.Term
import Lean.Elab.Binders
import Lean.Elab.SyntheticMVars
import Lean.Elab.Arg
namespace Lean.Elab.Term
open Meta
builtin_initialize elabWithoutExpectedTypeAttr : TagAttribute ←
registerTagAttribute `elabWithoutExpectedType "mark that applications of the given declaration should be elaborated without the expected type"
def hasElabWithoutExpectedType (env : Environment) (declName : Name) : Bool :=
elabWithoutExpectedTypeAttr.hasTag env declName
instance : ToString Arg := ⟨fun
| Arg.stx val => toString val
| Arg.expr val => toString val⟩
instance : ToString NamedArg where
toString s := "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")"
def throwInvalidNamedArg {α} (namedArg : NamedArg) (fn? : Option Name) : TermElabM α :=
withRef namedArg.ref <| match fn? with
| some fn => throwError "invalid argument name '{namedArg.name}' for function '{fn}'"
| none => throwError "invalid argument name '{namedArg.name}' for function"
private def ensureArgType (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do
let argType ← inferType arg
ensureHasTypeAux expectedType argType arg f
/-
Relevant definitions:
```
class CoeFun (α : Sort u) (γ : α → outParam (Sort v))
abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a
```
-/
private def tryCoeFun? (α : Expr) (a : Expr) : TermElabM (Option Expr) := do
let v ← mkFreshLevelMVar
let type ← mkArrow α (mkSort v)
let γ ← mkFreshExprMVar type
let u ← getLevel α
let coeFunInstType := mkAppN (Lean.mkConst ``CoeFun [u, v]) #[α, γ]
let mvar ← mkFreshExprMVar coeFunInstType MetavarKind.synthetic
let mvarId := mvar.mvarId!
try
if (← synthesizeCoeInstMVarCore mvarId) then
expandCoe <| mkAppN (Lean.mkConst ``coeFun [u, v]) #[α, γ, a, mvar]
else
return none
catch _ =>
return none
def synthesizeAppInstMVars (instMVars : Array MVarId) : TermElabM Unit :=
for mvarId in instMVars do
unless (← synthesizeInstMVarCore mvarId) do
registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass
namespace ElabAppArgs
/- Auxiliary structure for elaborating the application `f args namedArgs`. -/
structure State where
explicit : Bool -- true if `@` modifier was used
f : Expr
fType : Expr
args : List Arg -- remaining regular arguments
namedArgs : List NamedArg -- remaining named arguments to be processed
ellipsis : Bool := false
expectedType? : Option Expr
etaArgs : Array Expr := #[]
toSetErrorCtx : Array MVarId := #[] -- metavariables that we need the set the error context using the application being built
instMVars : Array MVarId := #[] -- metavariables for the instance implicit arguments that have already been processed
-- The following field is used to implement the `propagateExpectedType` heuristic.
propagateExpected : Bool -- true when expectedType has not been propagated yet
abbrev M := StateRefT State TermElabM
/- Add the given metavariable to the collection of metavariables associated with instance-implicit arguments. -/
private def addInstMVar (mvarId : MVarId) : M Unit :=
modify fun s => { s with instMVars := s.instMVars.push mvarId }
/-
Try to synthesize metavariables are `instMVars` using type class resolution.
The ones that cannot be synthesized yet are registered.
Remark: we use this method before trying to apply coercions to function. -/
def synthesizeAppInstMVars : M Unit := do
let s ← get
let instMVars := s.instMVars
modify fun s => { s with instMVars := #[] }
Lean.Elab.Term.synthesizeAppInstMVars instMVars
/- fType may become a forallE after we synthesize pending metavariables. -/
private def synthesizePendingAndNormalizeFunType : M Unit := do
synthesizeAppInstMVars
synthesizeSyntheticMVars
let s ← get
let fType ← whnfForall s.fType
if fType.isForall then
modify fun s => { s with fType := fType }
else
match (← tryCoeFun? fType s.f) with
| some f =>
let fType ← inferType f
modify fun s => { s with f := f, fType := fType }
| none =>
for namedArg in s.namedArgs do
let f := s.f.getAppFn
if f.isConst then
throwInvalidNamedArg namedArg f.constName!
else
throwInvalidNamedArg namedArg none
throwError "function expected at{indentExpr s.f}\nterm has type{indentExpr fType}"
/- Normalize and return the function type. -/
private def normalizeFunType : M Expr := do
let s ← get
let fType ← whnfForall s.fType
modify fun s => { s with fType := fType }
pure fType
/- Return the binder name at `fType`. This method assumes `fType` is a function type. -/
private def getBindingName : M Name := return (← get).fType.bindingName!
/- Return the next argument expected type. This method assumes `fType` is a function type. -/
private def getArgExpectedType : M Expr := return (← get).fType.bindingDomain!
def eraseNamedArgCore (namedArgs : List NamedArg) (binderName : Name) : List NamedArg :=
namedArgs.filter (·.name != binderName)
/- Remove named argument with name `binderName` from `namedArgs`. -/
def eraseNamedArg (binderName : Name) : M Unit :=
modify fun s => { s with namedArgs := eraseNamedArgCore s.namedArgs binderName }
/-
Add a new argument to the result. That is, `f := f arg`, update `fType`.
This method assumes `fType` is a function type. -/
private def addNewArg (arg : Expr) : M Unit :=
modify fun s => { s with f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg }
/-
Elaborate the given `Arg` and add it to the result. See `addNewArg`.
Recall that, `Arg` may be wrapping an already elaborated `Expr`. -/
private def elabAndAddNewArg (arg : Arg) : M Unit := do
let s ← get
let expectedType ← getArgExpectedType
match arg with
| Arg.expr val =>
let arg ← ensureArgType s.f val expectedType
addNewArg arg
| Arg.stx val =>
let val ← elabTerm val expectedType
let arg ← ensureArgType s.f val expectedType
addNewArg arg
/- Return true if the given type contains `OptParam` or `AutoParams` -/
private def hasOptAutoParams (type : Expr) : M Bool := do
forallTelescopeReducing type fun xs type =>
xs.anyM fun x => do
let xType ← inferType x
return xType.getOptParamDefault?.isSome || xType.getAutoParamTactic?.isSome
/- Return true if `fType` contains `OptParam` or `AutoParams` -/
private def fTypeHasOptAutoParams : M Bool := do
hasOptAutoParams (← get).fType
/- Auxiliary function for retrieving the resulting type of a function application.
See `propagateExpectedType`.
Remark: `(explicit : Bool) == true` when `@` modifier is used. -/
private partial def getForallBody (explicit : Bool) : Nat → List NamedArg → Expr → Option Expr
| i, namedArgs, type@(Expr.forallE n d b c) =>
match namedArgs.find? fun (namedArg : NamedArg) => namedArg.name == n with
| some _ => getForallBody explicit i (eraseNamedArgCore namedArgs n) b
| none =>
if !explicit && !c.binderInfo.isExplicit then
getForallBody explicit i namedArgs b
else if i > 0 then
getForallBody explicit (i-1) namedArgs b
else if d.isAutoParam || d.isOptParam then
getForallBody explicit i namedArgs b
else
some type
| 0, [], type => some type
| _, _, _ => none
private def shouldPropagateExpectedTypeFor (nextArg : Arg) : Bool :=
match nextArg with
| Arg.expr _ => false -- it has already been elaborated
| Arg.stx stx =>
-- TODO: make this configurable?
stx.getKind != ``Lean.Parser.Term.hole &&
stx.getKind != ``Lean.Parser.Term.syntheticHole &&
stx.getKind != ``Lean.Parser.Term.byTactic
/-
Auxiliary method for propagating the expected type. We call it as soon as we find the first explict
argument. The goal is to propagate the expected type in applications of functions such as
```lean
Add.add {α : Type u} : α → α → α
List.cons {α : Type u} : α → List α → List α
```
This is particularly useful when there applicable coercions. For example,
assume we have a coercion from `Nat` to `Int`, and we have
`(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function,
the elaborator will fail to elaborate
```
List.cons x []
```
First, the elaborator creates a new metavariable `?α` for the implicit argument `{α : Type u}`.
Then, when it processes `x`, it assigns `?α := Nat`, and then obtain the
resultant type `List Nat` which is **not** definitionally equal to `List Int`.
We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example).
This method infers that the resultant type is `List ?α` and unifies it with `List Int`.
Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the
term
```
@List.cons Int (coe x) (@List.nil Int)
```
is produced.
The method will do nothing if
1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`).
2- The resultant type contains optional/auto params.
We have considered adding the following extra conditions
a) The resultant type does not contain any type metavariable.
b) The resultant type contains a nontype metavariable.
These two conditions would restrict the method to simple functions that are "morally" in
the Hindley&Milner fragment.
If users need to disable expected type propagation, we can add an attribute `[elabWithoutExpectedType]`.
-/
private def propagateExpectedType (arg : Arg) : M Unit := do
if shouldPropagateExpectedTypeFor arg then
let s ← get
-- TODO: handle s.etaArgs.size > 0
unless !s.etaArgs.isEmpty || !s.propagateExpected do
match s.expectedType? with
| none => pure ()
| some expectedType =>
/- We don't propagate `Prop` because we often use `Prop` as a more general "Bool" (e.g., `if-then-else`).
If we propagate `expectedType == Prop` in the following examples, the elaborator would fail
```
def f1 (s : Nat × Bool) : Bool := if s.2 then false else true
def f2 (s : List Bool) : Bool := if s.head! then false else true
def f3 (s : List Bool) : Bool := if List.head! (s.map not) then false else true
```
They would all fail for the same reason. So, let's focus on the first one.
We would elaborate `s.2` with `expectedType == Prop`.
Before we elaborate `s`, this method would be invoked, and `s.fType` is `?α × ?β → ?β` and after
propagation we would have `?α × Prop → Prop`. Then, when we would try to elaborate `s`, and
get a type error because `?α × Prop` cannot be unified with `Nat × Bool`
Most users would have a hard time trying to understand why these examples failed.
Here is a possible alternative workarounds. We give up the idea of using `Prop` at `if-then-else`.
Drawback: users use `if-then-else` with conditions that are not Decidable.
So, users would have to embrace `propDecidable` and `choice`.
This may not be that bad since the developers and users don't seem to care about constructivism.
We currently use a different workaround, we just don't propagate the expected type when it is `Prop`. -/
if expectedType.isProp then
modify fun s => { s with propagateExpected := false }
else
let numRemainingArgs := s.args.length
trace[Elab.app.propagateExpectedType] "etaArgs.size: {s.etaArgs.size}, numRemainingArgs: {numRemainingArgs}, fType: {s.fType}"
match getForallBody s.explicit numRemainingArgs s.namedArgs s.fType with
| none => pure ()
| some fTypeBody =>
unless fTypeBody.hasLooseBVars do
unless (← hasOptAutoParams fTypeBody) do
trace[Elab.app.propagateExpectedType] "{expectedType} =?= {fTypeBody}"
if (← isDefEq expectedType fTypeBody) then
/- Note that we only set `propagateExpected := false` when propagation has succeeded. -/
modify fun s => { s with propagateExpected := false }
/-
Create a fresh local variable with the current binder name and argument type, add it to `etaArgs` and `f`,
and then execute the continuation `k`.-/
private def addEtaArg (k : M Expr) : M Expr := do
let n ← getBindingName
let type ← getArgExpectedType
withLocalDeclD n type fun x => do
modify fun s => { s with etaArgs := s.etaArgs.push x }
addNewArg x
k
/- This method execute after all application arguments have been processed. -/
private def finalize : M Expr := do
let s ← get
let mut e := s.f
-- all user explicit arguments have been consumed
trace[Elab.app.finalize] e
let ref ← getRef
-- Register the error context of implicits
for mvarId in s.toSetErrorCtx do
registerMVarErrorImplicitArgInfo mvarId ref e
if !s.etaArgs.isEmpty then
e ← mkLambdaFVars s.etaArgs e
/-
Remark: we should not use `s.fType` as `eType` even when
`s.etaArgs.isEmpty`. Reason: it may have been unfolded.
-/
let eType ← inferType e
trace[Elab.app.finalize] "after etaArgs, {e} : {eType}"
match s.expectedType? with
| none => pure ()
| some expectedType =>
trace[Elab.app.finalize] "expected type: {expectedType}"
-- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it.
discard <| isDefEq expectedType eType
synthesizeAppInstMVars
pure e
private def addImplicitArg (k : M Expr) : M Expr := do
let argType ← getArgExpectedType
let arg ← mkFreshExprMVar argType
modify fun s => { s with toSetErrorCtx := s.toSetErrorCtx.push arg.mvarId! }
addNewArg arg
k
/- Return true if there is a named argument that depends on the next argument. -/
private def anyNamedArgDependsOnCurrent : M Bool := do
let s ← get
if s.namedArgs.isEmpty then
return false
else
forallTelescopeReducing s.fType fun xs _ => do
let curr := xs[0]
for i in [1:xs.size] do
let xDecl ← getLocalDecl xs[i].fvarId!
if s.namedArgs.any fun arg => arg.name == xDecl.userName then
if (← getMCtx).localDeclDependsOn xDecl curr.fvarId! then
return true
return false
/-
Process a `fType` of the form `(x : A) → B x`.
This method assume `fType` is a function type -/
private def processExplictArg (k : M Expr) : M Expr := do
let s ← get
match s.args with
| arg::args =>
propagateExpectedType arg
modify fun s => { s with args := args }
elabAndAddNewArg arg
k
| _ =>
let argType ← getArgExpectedType
match s.explicit, argType.getOptParamDefault?, argType.getAutoParamTactic? with
| false, some defVal, _ => addNewArg defVal; k
| false, _, some (Expr.const tacticDecl _ _) =>
let env ← getEnv
let opts ← getOptions
match evalSyntaxConstant env opts tacticDecl with
| Except.error err => throwError err
| Except.ok tacticSyntax =>
-- TODO(Leo): does this work correctly for tactic sequences?
let tacticBlock ← `(by $tacticSyntax)
let argType := argType.getArg! 0 -- `autoParam type := by tactic` ==> `type`
let argNew := Arg.stx tacticBlock
propagateExpectedType argNew
elabAndAddNewArg argNew
k
| false, _, some _ =>
throwError "invalid autoParam, argument must be a constant"
| _, _, _ =>
if !s.namedArgs.isEmpty then
if (← anyNamedArgDependsOnCurrent) then
addImplicitArg k
else
addEtaArg k
else if !s.explicit then
if (← fTypeHasOptAutoParams) then
addEtaArg k
else if (← get).ellipsis then
addImplicitArg k
else
finalize
else
finalize
/-
Process a `fType` of the form `{x : A} → B x`.
This method assume `fType` is a function type -/
private def processImplicitArg (k : M Expr) : M Expr := do
if (← get).explicit then
processExplictArg k
else
addImplicitArg k
/- Return true if the next argument at `args` is of the form `_` -/
private def isNextArgHole : M Bool := do
match (← get).args with
| Arg.stx (Syntax.node ``Lean.Parser.Term.hole _) :: _ => pure true
| _ => pure false
/-
Process a `fType` of the form `[x : A] → B x`.
This method assume `fType` is a function type -/
private def processInstImplicitArg (k : M Expr) : M Expr := do
if (← get).explicit then
if (← isNextArgHole) then
/- Recall that if '@' has been used, and the argument is '_', then we still use type class resolution -/
let arg ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.synthetic
modify fun s => { s with args := s.args.tail! }
addInstMVar arg.mvarId!
addNewArg arg
k
else
processExplictArg k
else
let arg ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.synthetic
addInstMVar arg.mvarId!
addNewArg arg
k
/- Return true if there are regular or named arguments to be processed. -/
private def hasArgsToProcess : M Bool := do
let s ← get
pure $ !s.args.isEmpty || !s.namedArgs.isEmpty
/- Elaborate function application arguments. -/
partial def main : M Expr := do
let s ← get
let fType ← normalizeFunType
if fType.isForall then
let binderName := fType.bindingName!
let binfo := fType.bindingInfo!
let s ← get
match s.namedArgs.find? fun (namedArg : NamedArg) => namedArg.name == binderName with
| some namedArg =>
propagateExpectedType namedArg.val
eraseNamedArg binderName
elabAndAddNewArg namedArg.val
main
| none =>
match binfo with
| BinderInfo.implicit => processImplicitArg main
| BinderInfo.instImplicit => processInstImplicitArg main
| _ => processExplictArg main
else if (← hasArgsToProcess) then
synthesizePendingAndNormalizeFunType
main
else
finalize
end ElabAppArgs
private def propagateExpectedTypeFor (f : Expr) : TermElabM Bool :=
match f.getAppFn.constName? with
| some declName => return !hasElabWithoutExpectedType (← getEnv) declName
| _ => return true
def elabAppArgs (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg)
(expectedType? : Option Expr) (explicit ellipsis : Bool) : TermElabM Expr := do
let fType ← inferType f
let fType ← instantiateMVars fType
trace[Elab.app.args] "explicit: {explicit}, {f} : {fType}"
unless namedArgs.isEmpty && args.isEmpty do
tryPostponeIfMVar fType
ElabAppArgs.main.run' {
args := args.toList,
expectedType? := expectedType?,
explicit := explicit,
ellipsis := ellipsis,
namedArgs := namedArgs.toList,
f := f,
fType := fType
propagateExpected := (← propagateExpectedTypeFor f)
}
/-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/
inductive LValResolution where
| projFn (baseStructName : Name) (structName : Name) (fieldName : Name)
| projIdx (structName : Name) (idx : Nat)
| const (baseStructName : Name) (structName : Name) (constName : Name)
| localRec (baseName : Name) (fullName : Name) (fvar : Expr)
| getOp (fullName : Name) (idx : Syntax)
private def throwLValError {α} (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM α :=
throwError "{msg}{indentExpr e}\nhas type{indentExpr eType}"
/-- `findMethod? env S fName`.
1- If `env` contains `S ++ fName`, return `(S, S++fName)`
2- Otherwise if `env` contains private name `prv` for `S ++ fName`, return `(S, prv)`, o
3- Otherwise for each parent structure `S'` of `S`, we try `findMethod? env S' fname` -/
private partial def findMethod? (env : Environment) (structName fieldName : Name) : Option (Name × Name) :=
let fullName := structName ++ fieldName
match env.find? fullName with
| some _ => some (structName, fullName)
| none =>
let fullNamePrv := mkPrivateName env fullName
match env.find? fullNamePrv with
| some _ => some (structName, fullNamePrv)
| none =>
if isStructureLike env structName then
(getParentStructures env structName).findSome? fun parentStructName => findMethod? env parentStructName fieldName
else
none
private def resolveLValAux (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := do
match eType.getAppFn.constName?, lval with
| some structName, LVal.fieldIdx _ idx =>
if idx == 0 then
throwError "invalid projection, index must be greater than 0"
let env ← getEnv
unless isStructureLike env structName do
throwLValError e eType "invalid projection, structure expected"
let fieldNames := getStructureFields env structName
if h : idx - 1 < fieldNames.size then
if isStructure env structName then
return LValResolution.projFn structName structName (fieldNames.get ⟨idx - 1, h⟩)
else
/- `structName` was declared using `inductive` command.
So, we don't projection functions for it. Thus, we use `Expr.proj` -/
return LValResolution.projIdx structName (idx - 1)
else
throwLValError e eType m!"invalid projection, structure has only {fieldNames.size} field(s)"
| some structName, LVal.fieldName _ fieldName _ _ =>
let env ← getEnv
let searchEnv : Unit → TermElabM LValResolution := fun _ => do
match findMethod? env structName (Name.mkSimple fieldName) with
| some (baseStructName, fullName) => pure $ LValResolution.const baseStructName structName fullName
| none =>
throwLValError e eType
m!"invalid field '{fieldName}', the environment does not contain '{Name.mkStr structName fieldName}'"
-- search local context first, then environment
let searchCtx : Unit → TermElabM LValResolution := fun _ => do
let fullName := Name.mkStr structName fieldName
let currNamespace ← getCurrNamespace
let localName := fullName.replacePrefix currNamespace Name.anonymous
let lctx ← getLCtx
match lctx.findFromUserName? localName with
| some localDecl =>
if localDecl.binderInfo == BinderInfo.auxDecl then
/- LVal notation is being used to make a "local" recursive call. -/
pure $ LValResolution.localRec structName fullName localDecl.toExpr
else
searchEnv ()
| none => searchEnv ()
if isStructure env structName then
match findField? env structName (Name.mkSimple fieldName) with
| some baseStructName => pure $ LValResolution.projFn baseStructName structName (Name.mkSimple fieldName)
| none => searchCtx ()
else
searchCtx ()
| some structName, LVal.getOp _ idx =>
let env ← getEnv
let fullName := Name.mkStr structName "getOp"
match env.find? fullName with
| some _ => pure $ LValResolution.getOp fullName idx
| none => throwLValError e eType m!"invalid [..] notation because environment does not contain '{fullName}'"
| none, LVal.fieldName _ _ (some suffix) _ =>
if e.isConst then
throwUnknownConstant (e.constName! ++ suffix)
else
throwLValError e eType "invalid field notation, type is not of the form (C ...) where C is a constant"
| _, LVal.getOp _ idx =>
throwLValError e eType "invalid [..] notation, type is not of the form (C ...) where C is a constant"
| _, _ =>
throwLValError e eType "invalid field notation, type is not of the form (C ...) where C is a constant"
/- whnfCore + implicit consumption.
Example: given `e` with `eType := {α : Type} → (fun β => List β) α `, it produces `(e ?m, List ?m)` where `?m` is fresh metavariable. -/
private partial def consumeImplicits (stx : Syntax) (e eType : Expr) : TermElabM (Expr × Expr) := do
let eType ← whnfCore eType
match eType with
| Expr.forallE n d b c =>
if c.binderInfo.isImplicit then
let mvar ← mkFreshExprMVar d
registerMVarErrorHoleInfo mvar.mvarId! stx
consumeImplicits stx (mkApp e mvar) (b.instantiate1 mvar)
else if c.binderInfo.isInstImplicit then
let mvar ← mkInstMVar d
consumeImplicits stx (mkApp e mvar) (b.instantiate1 mvar)
else match d.getOptParamDefault? with
| some defVal => consumeImplicits stx (mkApp e defVal) (b.instantiate1 defVal)
-- TODO: we do not handle autoParams here.
| _ => pure (e, eType)
| _ => pure (e, eType)
private partial def resolveLValLoop (lval : LVal) (e eType : Expr) (previousExceptions : Array Exception) : TermElabM (Expr × LValResolution) := do
let (e, eType) ← consumeImplicits lval.getRef e eType
tryPostponeIfMVar eType
try
let lvalRes ← resolveLValAux e eType lval
pure (e, lvalRes)
catch
| ex@(Exception.error _ _) =>
let eType? ← unfoldDefinition? eType
match eType? with
| some eType => resolveLValLoop lval e eType (previousExceptions.push ex)
| none =>
previousExceptions.forM fun ex => logException ex
throw ex
| ex@(Exception.internal _ _) => throw ex
private def resolveLVal (e : Expr) (lval : LVal) : TermElabM (Expr × LValResolution) := do
let eType ← inferType e
resolveLValLoop lval e eType #[]
private partial def mkBaseProjections (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do
let env ← getEnv
match getPathToBaseStructure? env baseStructName structName with
| none => throwError "failed to access field in parent structure"
| some path =>
let mut e := e
for projFunName in path do
let projFn ← mkConst projFunName
e ← elabAppArgs projFn #[{ name := `self, val := Arg.expr e }] (args := #[]) (expectedType? := none) (explicit := false) (ellipsis := false)
return e
/- Auxiliary method for field notation. It tries to add `e` as a new argument to `args` or `namedArgs`.
This method first finds the parameter with a type of the form `(baseName ...)`.
When the parameter is found, if it an explicit one and `args` is big enough, we add `e` to `args`.
Otherwise, if there isn't another parameter with the same name, we add `e` to `namedArgs`.
Remark: `fullName` is the name of the resolved "field" access function. It is used for reporting errors -/
private def addLValArg (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) (namedArgs : Array NamedArg) (fType : Expr)
: TermElabM (Array Arg × Array NamedArg) :=
forallTelescopeReducing fType fun xs _ => do
let mut argIdx := 0 -- position of the next explicit argument
let mut remainingNamedArgs := namedArgs
for i in [:xs.size] do
let x := xs[i]
let xDecl ← getLocalDecl x.fvarId!
/- If there is named argument with name `xDecl.userName`, then we skip it. -/
match remainingNamedArgs.findIdx? (fun namedArg => namedArg.name == xDecl.userName) with
| some idx =>
remainingNamedArgs := remainingNamedArgs.eraseIdx idx
| none =>
let mut foundIt := false
let type := xDecl.type
if type.consumeMData.isAppOf baseName then
foundIt := true
if !foundIt then
/- Normalize type and try again -/
let type ← withReducible $ whnf type
if type.consumeMData.isAppOf baseName then
foundIt := true
if foundIt then
/- We found a type of the form (baseName ...).
First, we check if the current argument is an explicit one,
and the current explicit position "fits" at `args` (i.e., it must be ≤ arg.size) -/
if argIdx ≤ args.size && xDecl.binderInfo.isExplicit then
/- We insert `e` as an explicit argument -/
return (args.insertAt argIdx (Arg.expr e), namedArgs)
/- If we can't add `e` to `args`, we try to add it using a named argument, but this is only possible
if there isn't an argument with the same name occurring before it. -/
for j in [:i] do
let prev := xs[j]
let prevDecl ← getLocalDecl prev.fvarId!
if prevDecl.userName == xDecl.userName then
throwError "invalid field notation, function '{fullName}' has argument with the expected type{indentExpr type}\nbut it cannot be used"
return (args, namedArgs.push { name := xDecl.userName, val := Arg.expr e })
if xDecl.binderInfo.isExplicit then
-- advance explicit argument position
argIdx := argIdx + 1
throwError "invalid field notation, function '{fullName}' does not have argument with type ({baseName} ...) that can be used, it must be explicit or implicit with an unique name"
private def elabAppLValsAux (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool)
(f : Expr) (lvals : List LVal) : TermElabM Expr :=
let rec loop : Expr → List LVal → TermElabM Expr
| f, [] => elabAppArgs f namedArgs args expectedType? explicit ellipsis
| f, lval::lvals => do
if let LVal.fieldName (ref := fieldStx) (targetStx := targetStx) .. := lval then
addDotCompletionInfo targetStx f expectedType? fieldStx
let (f, lvalRes) ← resolveLVal f lval
match lvalRes with
| LValResolution.projIdx structName idx =>
let f := mkProj structName idx f
addTermInfo lval.getRef f
loop f lvals
| LValResolution.projFn baseStructName structName fieldName =>
let f ← mkBaseProjections baseStructName structName f
let projFn ← mkConst (baseStructName ++ fieldName)
addTermInfo lval.getRef projFn
if lvals.isEmpty then
let namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f }
elabAppArgs projFn namedArgs args expectedType? explicit ellipsis
else
let f ← elabAppArgs projFn #[{ name := `self, val := Arg.expr f }] #[] (expectedType? := none) (explicit := false) (ellipsis := false)
loop f lvals
| LValResolution.const baseStructName structName constName =>
let f ← if baseStructName != structName then mkBaseProjections baseStructName structName f else pure f
let projFn ← mkConst constName
addTermInfo lval.getRef projFn
if lvals.isEmpty then
let projFnType ← inferType projFn
let (args, namedArgs) ← addLValArg baseStructName constName f args namedArgs projFnType
elabAppArgs projFn namedArgs args expectedType? explicit ellipsis
else
let f ← elabAppArgs projFn #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false)
loop f lvals
| LValResolution.localRec baseName fullName fvar =>
addTermInfo lval.getRef fvar
if lvals.isEmpty then
let fvarType ← inferType fvar
let (args, namedArgs) ← addLValArg baseName fullName f args namedArgs fvarType
elabAppArgs fvar namedArgs args expectedType? explicit ellipsis
else
let f ← elabAppArgs fvar #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false)
loop f lvals
| LValResolution.getOp fullName idx =>
let getOpFn ← mkConst fullName
addTermInfo lval.getRef getOpFn
if lvals.isEmpty then
let namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f }
let namedArgs ← addNamedArg namedArgs { name := `idx, val := Arg.stx idx }
elabAppArgs getOpFn namedArgs args expectedType? explicit ellipsis
else
let f ← elabAppArgs getOpFn #[{ name := `self, val := Arg.expr f }, { name := `idx, val := Arg.stx idx }]
#[] (expectedType? := none) (explicit := false) (ellipsis := false)
loop f lvals
loop f lvals
private def elabAppLVals (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg)
(expectedType? : Option Expr) (explicit ellipsis : Bool) : TermElabM Expr := do
if !lvals.isEmpty && explicit then
throwError "invalid use of field notation with `@` modifier"
elabAppLValsAux namedArgs args expectedType? explicit ellipsis f lvals
def elabExplicitUnivs (lvls : Array Syntax) : TermElabM (List Level) := do
lvls.foldrM (fun stx lvls => do pure ((← elabLevel stx)::lvls)) []
/-
Interaction between `errToSorry` and `observing`.
- The method `elabTerm` catches exceptions, log them, and returns a synthetic sorry (IF `ctx.errToSorry` == true).
- When we elaborate choice nodes (and overloaded identifiers), we track multiple results using the `observing x` combinator.
The `observing x` executes `x` and returns a `TermElabResult`.
`observing `x does not check for synthetic sorry's, just an exception. Thus, it may think `x` worked when it didn't
if a synthetic sorry was introduced. We decided that checking for synthetic sorrys at `observing` is not a good solution
because it would not be clear to decide what the "main" error message for the alternative is. When the result contains
a synthetic `sorry`, it is not clear which error message corresponds to the `sorry`. Moreover, while executing `x`, many
error messages may have been logged. Recall that we need an error per alternative at `mergeFailures`.
Thus, we decided to set `errToSorry` to `false` whenever processing choice nodes and overloaded symbols.
Important: we rely on the property that after `errToSorry` is set to
false, no elaboration function executed by `x` will reset it to
`true`.
-/
private partial def elabAppFnId (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal)
(namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr))
: TermElabM (Array (TermElabResult Expr)) := do
let funLVals ← withRef fIdent <| resolveName' fIdent fExplicitUnivs expectedType?
let overloaded := overloaded || funLVals.length > 1
-- Set `errToSorry` to `false` if `funLVals` > 1. See comment above about the interaction between `errToSorry` and `observing`.
withReader (fun ctx => { ctx with errToSorry := funLVals.length == 1 && ctx.errToSorry }) do
funLVals.foldlM (init := acc) fun acc (f, fIdent, fields) => do
let lvals' := toLVals fields (first := true)
let s ← observing do
addTermInfo fIdent f expectedType?
let e ← elabAppLVals f (lvals' ++ lvals) namedArgs args expectedType? explicit ellipsis
if overloaded then ensureHasType expectedType? e else pure e
return acc.push s
where
toName : List Syntax → Name
| [] => Name.anonymous
| field :: fields => Name.mkStr (toName fields) field.getId.toString
toLVals : List Syntax → (first : Bool) → List LVal
| [], _ => []
| field::fields, true => LVal.fieldName field field.getId.toString (toName (field::fields)) fIdent :: toLVals fields false
| field::fields, false => LVal.fieldName field field.getId.toString none fIdent :: toLVals fields false
private partial def elabAppFn (f : Syntax) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg)
(expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) :=
if f.getKind == choiceKind then
-- Set `errToSorry` to `false` when processing choice nodes. See comment above about the interaction between `errToSorry` and `observing`.
withReader (fun ctx => { ctx with errToSorry := false }) do
f.getArgs.foldlM (fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit ellipsis true acc) acc
else
let elabFieldName (e field : Syntax) := do
let newLVals := field.getId.eraseMacroScopes.components.map fun n =>
-- We use `none` here since `field` can't be part of a composite name
LVal.fieldName field (toString n) none e
elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit ellipsis overloaded acc
let elabFieldIdx (e idxStx : Syntax) := do
let idx := idxStx.isFieldIdx?.get!
elabAppFn e (LVal.fieldIdx idxStx idx :: lvals) namedArgs args expectedType? explicit ellipsis overloaded acc
match f with
| `($(e).$idx:fieldIdx) => elabFieldIdx e idx
| `($e |>.$idx:fieldIdx) => elabFieldIdx e idx
| `($(e).$field:ident) => elabFieldName e field
| `($e |>.$field:ident) => elabFieldName e field
| `($e[%$bracket $idx]) => elabAppFn e (LVal.getOp bracket idx :: lvals) namedArgs args expectedType? explicit ellipsis overloaded acc
| `($id:ident@$t:term) =>
throwError "unexpected occurrence of named pattern"
| `($id:ident) => do
elabAppFnId id [] lvals namedArgs args expectedType? explicit ellipsis overloaded acc
| `($id:ident.{$us,*}) => do
let us ← elabExplicitUnivs us
elabAppFnId id us lvals namedArgs args expectedType? explicit ellipsis overloaded acc
| `(@$id:ident) =>
elabAppFn id lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc
| `(@$id:ident.{$us,*}) =>
elabAppFn (f.getArg 1) lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc
| `(@$t) => throwUnsupportedSyntax -- invalid occurrence of `@`
| `(_) => throwError "placeholders '_' cannot be used where a function is expected"
| _ => do
let catchPostpone := !overloaded
/- If we are processing a choice node, then we should use `catchPostpone == false` when elaborating terms.
Recall that `observing` does not catch `postponeExceptionId`. -/
if lvals.isEmpty && namedArgs.isEmpty && args.isEmpty then
/- Recall that elabAppFn is used for elaborating atomics terms **and** choice nodes that may contain
arbitrary terms. If they are not being used as a function, we should elaborate using the expectedType. -/
let s ←
if overloaded then
observing <| elabTermEnsuringType f expectedType? catchPostpone
else
observing <| elabTerm f expectedType?
return acc.push s
else
let s ← observing do
let f ← elabTerm f none catchPostpone
let e ← elabAppLVals f lvals namedArgs args expectedType? explicit ellipsis
if overloaded then ensureHasType expectedType? e else pure e
return acc.push s
private def isSuccess (candidate : TermElabResult Expr) : Bool :=
match candidate with
| EStateM.Result.ok _ _ => true
| _ => false
private def getSuccess (candidates : Array (TermElabResult Expr)) : Array (TermElabResult Expr) :=
candidates.filter isSuccess
private def toMessageData (ex : Exception) : TermElabM MessageData := do
let pos ← getRefPos
match ex.getRef.getPos? with
| none => return ex.toMessageData
| some exPos =>
if pos == exPos then
return ex.toMessageData
else
let exPosition := (← getFileMap).toPosition exPos
return m!"{exPosition.line}:{exPosition.column} {ex.toMessageData}"
private def toMessageList (msgs : Array MessageData) : MessageData :=
indentD (MessageData.joinSep msgs.toList m!"\n\n")
private def mergeFailures {α} (failures : Array (TermElabResult Expr)) : TermElabM α := do
let msgs ← failures.mapM fun failure =>
match failure with
| EStateM.Result.ok _ _ => unreachable!
| EStateM.Result.error ex _ => toMessageData ex
throwError "overloaded, errors {toMessageList msgs}"
private def elabAppAux (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) (expectedType? : Option Expr) : TermElabM Expr := do
let candidates ← elabAppFn f [] namedArgs args expectedType? (explicit := false) (ellipsis := ellipsis) (overloaded := false) #[]
if candidates.size == 1 then
applyResult candidates[0]
else
let successes := getSuccess candidates
if successes.size == 1 then
applyResult successes[0]
else if successes.size > 1 then
let lctx ← getLCtx
let opts ← getOptions
let msgs : Array MessageData := successes.map fun success => match success with
| EStateM.Result.ok e s => MessageData.withContext { env := s.meta.core.env, mctx := s.meta.meta.mctx, lctx := lctx, opts := opts } e
| _ => unreachable!
throwErrorAt f "ambiguous, possible interpretations {toMessageList msgs}"
else
withRef f <| mergeFailures candidates
@[builtinTermElab app] def elabApp : TermElab := fun stx expectedType? =>
withoutPostponingUniverseConstraints do
let (f, namedArgs, args, ellipsis) ← expandApp stx
elabAppAux f namedArgs args (ellipsis := ellipsis) expectedType?
private def elabAtom : TermElab := fun stx expectedType? =>
elabAppAux stx #[] #[] (ellipsis := false) expectedType?
@[builtinTermElab ident] def elabIdent : TermElab := elabAtom
@[builtinTermElab namedPattern] def elabNamedPattern : TermElab := elabAtom
@[builtinTermElab explicitUniv] def elabExplicitUniv : TermElab := elabAtom
@[builtinTermElab pipeProj] def elabPipeProj : TermElab
| `($e |>.$f $args*), expectedType? =>
withoutPostponingUniverseConstraints do
let (namedArgs, args, ellipsis) ← expandArgs args
elabAppAux (← `($e |>.$f)) namedArgs args (ellipsis := ellipsis) expectedType?
| _, _ => throwUnsupportedSyntax
@[builtinTermElab explicit] def elabExplicit : TermElab := fun stx expectedType? =>
match stx with
| `(@$id:ident) => elabAtom stx expectedType? -- Recall that `elabApp` also has support for `@`
| `(@$id:ident.{$us,*}) => elabAtom stx expectedType?
| `(@($t)) => elabTerm t expectedType? (implicitLambda := false) -- `@` is being used just to disable implicit lambdas
| `(@$t) => elabTerm t expectedType? (implicitLambda := false) -- `@` is being used just to disable implicit lambdas
| _ => throwUnsupportedSyntax
@[builtinTermElab choice] def elabChoice : TermElab := elabAtom
@[builtinTermElab proj] def elabProj : TermElab := elabAtom
@[builtinTermElab arrayRef] def elabArrayRef : TermElab := elabAtom
builtin_initialize
registerTraceClass `Elab.app
end Lean.Elab.Term
|
e5eb39d2d6119c2ab9be596d82061d4e3ac201f3
|
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
|
/src/algebra/big_operators/pi.lean
|
645da4b9bbe4e7c154edbb76e33a7c18f97345a5
|
[
"Apache-2.0"
] |
permissive
|
dupuisf/mathlib
|
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
|
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
|
refs/heads/master
| 1,669,494,854,016
| 1,595,692,409,000
| 1,595,692,409,000
| 272,046,630
| 0
| 0
|
Apache-2.0
| 1,592,066,143,000
| 1,592,066,142,000
| null |
UTF-8
|
Lean
| false
| false
| 3,334
|
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 algebra.ring.pi
import algebra.big_operators
import data.fintype.basic
import algebra.group.prod
/-!
# Big operators for Pi Types
This file contains theorems relevant to big operators in binary and arbitrary product
of monoids and groups
-/
open_locale big_operators
namespace pi
@[to_additive]
lemma list_prod_apply {α : Type*} {β : α → Type*} [∀a, monoid (β a)] (a : α) :
∀ (l : list (Πa, β a)), l.prod a = (l.map (λf:Πa, β a, f a)).prod
| [] := rfl
| (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l]
@[to_additive]
lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α)
(s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod :=
quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end
end pi
@[simp, to_additive]
lemma finset.prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α)
(s : finset γ) (g : γ → Πa, β a) : (∏ c in s, g c) a = ∏ c in s, g c a :=
show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod,
by rw [pi.multiset_prod_apply, multiset.map_map]
@[to_additive prod_mk_sum]
lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ)
(f : γ → α) (g : γ → β) : (∏ x in s, f x, ∏ x in s, g x) = ∏ x in s, (f x, g x) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt})
section single
variables {I : Type*} [decidable_eq I] {Z : I → Type*}
variables [Π i, add_comm_monoid (Z i)]
-- As we only defined `single` into `add_monoid`, we only prove the `finset.sum` version here.
lemma finset.univ_sum_single [fintype I] (f : Π i, Z i) :
∑ i, pi.single i (f i) = f :=
begin
ext a,
rw [finset.sum_apply, finset.sum_eq_single a],
{ simp, },
{ intros b _ h, simp [h.symm], },
{ intro h, exfalso, simpa using h, },
end
@[ext]
lemma add_monoid_hom.functions_ext [fintype I] (G : Type*)
[add_comm_monoid G] (g h : (Π i, Z i) →+ G)
(w : ∀ (i : I) (x : Z i), g (pi.single i x) = h (pi.single i x)) : g = h :=
begin
ext k,
rw [←finset.univ_sum_single k, add_monoid_hom.map_sum, add_monoid_hom.map_sum],
apply finset.sum_congr rfl,
intros,
apply w,
end
end single
section ring_hom
open pi
variables {I : Type*} [decidable_eq I] {f : I → Type*}
variables [Π i, semiring (f i)]
-- we need `apply`+`convert` because Lean fails to unify different `add_monoid` instances
-- on `Π i, f i`
@[ext]
lemma ring_hom.functions_ext [fintype I] (G : Type*) [semiring G] (g h : (Π i, f i) →+* G)
(w : ∀ (i : I) (x : f i), g (single i x) = h (single i x)) : g = h :=
begin
apply ring_hom.coe_add_monoid_hom_injective,
convert add_monoid_hom.functions_ext _ _ _ _; assumption
end
end ring_hom
namespace prod
variables {α β γ : Type*} [comm_monoid α] [comm_monoid β] {s : finset γ} {f : γ → α × β}
@[to_additive]
lemma fst_prod : (∏ c in s, f c).1 = ∏ c in s, (f c).1 :=
(monoid_hom.fst α β).map_prod f s
@[to_additive]
lemma snd_prod : (∏ c in s, f c).2 = ∏ c in s, (f c).2 :=
(monoid_hom.snd α β).map_prod f s
end prod
|
3fb2cf655d8e25af51104b9b04e999a87217a53d
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/ring_theory/norm.lean
|
a9ee578b28db79664f530da6572c9089de428c50
|
[
"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
| 13,148
|
lean
|
/-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import field_theory.primitive_element
import linear_algebra.determinant
import linear_algebra.finite_dimensional
import linear_algebra.matrix.charpoly.minpoly
import linear_algebra.matrix.to_linear_equiv
import field_theory.is_alg_closed.algebraic_closure
import field_theory.galois
/-!
# Norm for (finite) ring extensions
Suppose we have an `R`-algebra `S` with a finite basis. For each `s : S`,
the determinant of the linear map given by multiplying by `s` gives information
about the roots of the minimal polynomial of `s` over `R`.
## Implementation notes
Typically, the norm is defined specifically for finite field extensions.
The current definition is as general as possible and the assumption that we have
fields or that the extension is finite is added to the lemmas as needed.
We only define the norm for left multiplication (`algebra.left_mul_matrix`,
i.e. `linear_map.mul_left`).
For now, the definitions assume `S` is commutative, so the choice doesn't
matter anyway.
See also `algebra.trace`, which is defined similarly as the trace of
`algebra.left_mul_matrix`.
## References
* https://en.wikipedia.org/wiki/Field_norm
-/
universes u v w
variables {R S T : Type*} [comm_ring R] [comm_ring S]
variables [algebra R S]
variables {K L F : Type*} [field K] [field L] [field F]
variables [algebra K L] [algebra K F]
variables {ι : Type w}
open finite_dimensional
open linear_map
open matrix polynomial
open_locale big_operators
open_locale matrix
namespace algebra
variables (R)
/-- The norm of an element `s` of an `R`-algebra is the determinant of `(*) s`. -/
noncomputable def norm : S →* R :=
linear_map.det.comp (lmul R S).to_ring_hom.to_monoid_hom
lemma norm_apply (x : S) : norm R x = linear_map.det (lmul R S x) := rfl
lemma norm_eq_one_of_not_exists_basis
(h : ¬ ∃ (s : finset S), nonempty (basis s R S)) (x : S) : norm R x = 1 :=
by { rw [norm_apply, linear_map.det], split_ifs with h, refl }
variables {R}
-- Can't be a `simp` lemma because it depends on a choice of basis
lemma norm_eq_matrix_det [fintype ι] [decidable_eq ι] (b : basis ι R S) (s : S) :
norm R s = matrix.det (algebra.left_mul_matrix b s) :=
by { rwa [norm_apply, ← linear_map.det_to_matrix b, ← to_matrix_lmul_eq], refl }
/-- If `x` is in the base field `K`, then the norm is `x ^ [L : K]`. -/
lemma norm_algebra_map_of_basis [fintype ι] (b : basis ι R S) (x : R) :
norm R (algebra_map R S x) = x ^ fintype.card ι :=
begin
haveI := classical.dec_eq ι,
rw [norm_apply, ← det_to_matrix b, lmul_algebra_map],
convert @det_diagonal _ _ _ _ _ (λ (i : ι), x),
{ ext i j, rw [to_matrix_lsmul, matrix.diagonal] },
{ rw [finset.prod_const, finset.card_univ] }
end
/-- If `x` is in the base field `K`, then the norm is `x ^ [L : K]`.
(If `L` is not finite-dimensional over `K`, then `norm = 1 = x ^ 0 = x ^ (finrank L K)`.)
-/
@[simp]
protected lemma norm_algebra_map {K L : Type*} [field K] [comm_ring L] [algebra K L] (x : K) :
norm K (algebra_map K L x) = x ^ finrank K L :=
begin
by_cases H : ∃ (s : finset L), nonempty (basis s K L),
{ rw [norm_algebra_map_of_basis H.some_spec.some, finrank_eq_card_basis H.some_spec.some] },
{ rw [norm_eq_one_of_not_exists_basis K H, finrank_eq_zero_of_not_exists_basis, pow_zero],
rintros ⟨s, ⟨b⟩⟩,
exact H ⟨s, ⟨b⟩⟩ },
end
section eq_prod_roots
/-- Given `pb : power_basis K S`, then the norm of `pb.gen` is
`(-1) ^ pb.dim * coeff (minpoly K pb.gen) 0`. -/
lemma power_basis.norm_gen_eq_coeff_zero_minpoly [algebra K S] (pb : power_basis K S) :
norm K pb.gen = (-1) ^ pb.dim * coeff (minpoly K pb.gen) 0 :=
begin
rw [norm_eq_matrix_det pb.basis, det_eq_sign_charpoly_coeff, charpoly_left_mul_matrix,
fintype.card_fin]
end
/-- Given `pb : power_basis K S`, then the norm of `pb.gen` is
`((minpoly K pb.gen).map (algebra_map K F)).roots.prod`. -/
lemma power_basis.norm_gen_eq_prod_roots [algebra K S] (pb : power_basis K S)
(hf : (minpoly K pb.gen).splits (algebra_map K F)) :
algebra_map K F (norm K pb.gen) =
((minpoly K pb.gen).map (algebra_map K F)).roots.prod :=
begin
rw [power_basis.norm_gen_eq_coeff_zero_minpoly, ← pb.nat_degree_minpoly, ring_hom.map_mul,
← coeff_map, prod_roots_eq_coeff_zero_of_monic_of_split
((minpoly.monic (power_basis.is_integral_gen _)).map _)
((splits_id_iff_splits _).2 hf), nat_degree_map, map_pow, ← mul_assoc, ← mul_pow],
simp
end
end eq_prod_roots
section eq_zero_iff
variables [finite ι]
lemma norm_eq_zero_iff_of_basis [is_domain R] [is_domain S] (b : basis ι R S) {x : S} :
algebra.norm R x = 0 ↔ x = 0 :=
begin
casesI nonempty_fintype ι,
have hι : nonempty ι := b.index_nonempty,
letI := classical.dec_eq ι,
rw algebra.norm_eq_matrix_det b,
split,
{ rw ← matrix.exists_mul_vec_eq_zero_iff,
rintros ⟨v, v_ne, hv⟩,
rw [← b.equiv_fun.apply_symm_apply v, b.equiv_fun_symm_apply, b.equiv_fun_apply,
algebra.left_mul_matrix_mul_vec_repr] at hv,
refine (mul_eq_zero.mp (b.ext_elem $ λ i, _)).resolve_right (show ∑ i, v i • b i ≠ 0, from _),
{ simpa only [linear_equiv.map_zero, pi.zero_apply] using congr_fun hv i },
{ contrapose! v_ne with sum_eq,
apply b.equiv_fun.symm.injective,
rw [b.equiv_fun_symm_apply, sum_eq, linear_equiv.map_zero] } },
{ rintro rfl,
rw [alg_hom.map_zero, matrix.det_zero hι] },
end
lemma norm_ne_zero_iff_of_basis [is_domain R] [is_domain S] (b : basis ι R S) {x : S} :
algebra.norm R x ≠ 0 ↔ x ≠ 0 :=
not_iff_not.mpr (algebra.norm_eq_zero_iff_of_basis b)
/-- See also `algebra.norm_eq_zero_iff'` if you already have rewritten with `algebra.norm_apply`. -/
@[simp]
lemma norm_eq_zero_iff {K L : Type*} [field K] [comm_ring L] [algebra K L] [is_domain L]
[finite_dimensional K L] {x : L} : algebra.norm K x = 0 ↔ x = 0 :=
algebra.norm_eq_zero_iff_of_basis (basis.of_vector_space K L)
/-- This is `algebra.norm_eq_zero_iff` composed with `algebra.norm_apply`. -/
@[simp]
lemma norm_eq_zero_iff' {K L : Type*} [field K] [comm_ring L] [algebra K L] [is_domain L]
[finite_dimensional K L] {x : L} : linear_map.det (linear_map.mul K L x) = 0 ↔ x = 0 :=
algebra.norm_eq_zero_iff_of_basis (basis.of_vector_space K L)
end eq_zero_iff
open intermediate_field
variable (K)
lemma norm_eq_norm_adjoin [finite_dimensional K L] [is_separable K L] (x : L) :
norm K x = norm K (adjoin_simple.gen K x) ^ finrank K⟮x⟯ L :=
begin
letI := is_separable_tower_top_of_is_separable K K⟮x⟯ L,
let pbL := field.power_basis_of_finite_of_separable K⟮x⟯ L,
let pbx := intermediate_field.adjoin.power_basis (is_separable.is_integral K x),
rw [← adjoin_simple.algebra_map_gen K x, norm_eq_matrix_det (pbx.basis.smul pbL.basis) _,
smul_left_mul_matrix_algebra_map, det_block_diagonal, norm_eq_matrix_det pbx.basis],
simp only [finset.card_fin, finset.prod_const],
congr,
rw [← power_basis.finrank, adjoin_simple.algebra_map_gen K x]
end
variable {K}
section intermediate_field
lemma _root_.intermediate_field.adjoin_simple.norm_gen_eq_one {x : L}
(hx : ¬_root_.is_integral K x) : norm K (adjoin_simple.gen K x) = 1 :=
begin
rw [norm_eq_one_of_not_exists_basis],
contrapose! hx,
obtain ⟨s, ⟨b⟩⟩ := hx,
refine is_integral_of_mem_of_fg (K⟮x⟯).to_subalgebra _ x _,
{ exact (submodule.fg_iff_finite_dimensional _).mpr (of_fintype_basis b) },
{ exact intermediate_field.subset_adjoin K _ (set.mem_singleton x) }
end
lemma _root_.intermediate_field.adjoin_simple.norm_gen_eq_prod_roots (x : L)
(hf : (minpoly K x).splits (algebra_map K F)) :
(algebra_map K F) (norm K (adjoin_simple.gen K x)) =
((minpoly K x).map (algebra_map K F)).roots.prod :=
begin
have injKxL := (algebra_map K⟮x⟯ L).injective,
by_cases hx : _root_.is_integral K x, swap,
{ simp [minpoly.eq_zero hx, intermediate_field.adjoin_simple.norm_gen_eq_one hx] },
have hx' : _root_.is_integral K (adjoin_simple.gen K x),
{ rwa [← is_integral_algebra_map_iff injKxL, adjoin_simple.algebra_map_gen],
apply_instance },
rw [← adjoin.power_basis_gen hx, power_basis.norm_gen_eq_prod_roots];
rw [adjoin.power_basis_gen hx, minpoly.eq_of_algebra_map_eq injKxL hx'];
try { simp only [adjoin_simple.algebra_map_gen _ _] },
exact hf
end
end intermediate_field
section eq_prod_embeddings
open intermediate_field intermediate_field.adjoin_simple polynomial
lemma norm_eq_prod_embeddings_gen {K L : Type*} [field K] [comm_ring L] [algebra K L]
(E : Type*) [field E] [algebra K E]
(pb : power_basis K L)
(hE : (minpoly K pb.gen).splits (algebra_map K E)) (hfx : (minpoly K pb.gen).separable) :
algebra_map K E (norm K pb.gen) =
(@@finset.univ (power_basis.alg_hom.fintype pb)).prod (λ σ, σ pb.gen) :=
begin
letI := classical.dec_eq E,
rw [power_basis.norm_gen_eq_prod_roots pb hE, fintype.prod_equiv pb.lift_equiv',
finset.prod_mem_multiset, finset.prod_eq_multiset_prod, multiset.to_finset_val,
multiset.dedup_eq_self.mpr, multiset.map_id],
{ exact nodup_roots ((separable_map _).mpr hfx) },
{ intro x, refl },
{ intro σ, rw [power_basis.lift_equiv'_apply_coe, id.def] }
end
lemma norm_eq_prod_roots [is_separable K L] [finite_dimensional K L]
{x : L} (hF : (minpoly K x).splits (algebra_map K F)) :
algebra_map K F (norm K x) = ((minpoly K x).map (algebra_map K F)).roots.prod ^ finrank K⟮x⟯ L :=
by rw [norm_eq_norm_adjoin K x, map_pow,
intermediate_field.adjoin_simple.norm_gen_eq_prod_roots _ hF]
variables (F) (E : Type*) [field E] [algebra K E]
lemma prod_embeddings_eq_finrank_pow [algebra L F] [is_scalar_tower K L F] [is_alg_closed E]
[is_separable K F] [finite_dimensional K F] (pb : power_basis K L) :
∏ σ : F →ₐ[K] E, σ (algebra_map L F pb.gen) =
((@@finset.univ (power_basis.alg_hom.fintype pb)).prod
(λ σ : L →ₐ[K] E, σ pb.gen)) ^ finrank L F :=
begin
haveI : finite_dimensional L F := finite_dimensional.right K L F,
haveI : is_separable L F := is_separable_tower_top_of_is_separable K L F,
letI : fintype (L →ₐ[K] E) := power_basis.alg_hom.fintype pb,
letI : ∀ (f : L →ₐ[K] E), fintype (@@alg_hom L F E _ _ _ _ f.to_ring_hom.to_algebra) := _,
rw [fintype.prod_equiv alg_hom_equiv_sigma (λ (σ : F →ₐ[K] E), _) (λ σ, σ.1 pb.gen),
← finset.univ_sigma_univ, finset.prod_sigma, ← finset.prod_pow],
refine finset.prod_congr rfl (λ σ _, _),
{ letI : algebra L E := σ.to_ring_hom.to_algebra,
simp only [finset.prod_const, finset.card_univ],
congr,
rw alg_hom.card L F E },
{ intros σ,
simp only [alg_hom_equiv_sigma, equiv.coe_fn_mk, alg_hom.restrict_domain, alg_hom.comp_apply,
is_scalar_tower.coe_to_alg_hom'] }
end
variable (K)
/-- For `L/K` a finite separable extension of fields and `E` an algebraically closed extension
of `K`, the norm (down to `K`) of an element `x` of `L` is equal to the product of the images
of `x` over all the `K`-embeddings `σ` of `L` into `E`. -/
lemma norm_eq_prod_embeddings [finite_dimensional K L] [is_separable K L] [is_alg_closed E]
{x : L} : algebra_map K E (norm K x) = ∏ σ : L →ₐ[K] E, σ x :=
begin
have hx := is_separable.is_integral K x,
rw [norm_eq_norm_adjoin K x, ring_hom.map_pow, ← adjoin.power_basis_gen hx,
norm_eq_prod_embeddings_gen E (adjoin.power_basis hx) (is_alg_closed.splits_codomain _)],
{ exact (prod_embeddings_eq_finrank_pow L E (adjoin.power_basis hx)).symm },
{ haveI := is_separable_tower_bot_of_is_separable K K⟮x⟯ L,
exact is_separable.separable K _ }
end
lemma norm_eq_prod_automorphisms [finite_dimensional K L] [is_galois K L] {x : L}:
algebra_map K L (norm K x) = ∏ (σ : L ≃ₐ[K] L), σ x :=
begin
apply no_zero_smul_divisors.algebra_map_injective L (algebraic_closure L),
rw map_prod (algebra_map L (algebraic_closure L)),
rw ← fintype.prod_equiv (normal.alg_hom_equiv_aut K (algebraic_closure L) L),
{ rw ← norm_eq_prod_embeddings,
simp only [algebra_map_eq_smul_one, smul_one_smul] },
{ intro σ,
simp only [normal.alg_hom_equiv_aut, alg_hom.restrict_normal', equiv.coe_fn_mk,
alg_equiv.coe_of_bijective, alg_hom.restrict_normal_commutes, id.map_eq_id,
ring_hom.id_apply] },
end
lemma is_integral_norm [algebra S L] [algebra S K] [is_scalar_tower S K L]
[is_separable K L] [finite_dimensional K L] {x : L} (hx : _root_.is_integral S x) :
_root_.is_integral S (norm K x) :=
begin
have hx' : _root_.is_integral K x := is_integral_of_is_scalar_tower hx,
rw [← is_integral_algebra_map_iff (algebra_map K (algebraic_closure L)).injective,
norm_eq_prod_roots],
{ refine (is_integral.multiset_prod (λ y hy, _)).pow _,
rw mem_roots_map (minpoly.ne_zero hx') at hy,
use [minpoly S x, minpoly.monic hx],
rw ← aeval_def at ⊢ hy,
exact minpoly.aeval_of_is_scalar_tower S x y hy },
{ apply is_alg_closed.splits_codomain },
{ apply_instance }
end
end eq_prod_embeddings
end algebra
|
3b47529fe0ca211d851ceb9172e978222f1ffd42
|
29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f
|
/24_lecture.lean
|
95ffb3fe5ff8d7cdf8edb1593f6aab50f28333cb
|
[] |
no_license
|
KjellZijlemaker/Logical_Verification_VU
|
ced0ba95316a30e3c94ba8eebd58ea004fa6f53b
|
4578b93bf1615466996157bb333c84122b201d99
|
refs/heads/master
| 1,585,966,086,108
| 1,549,187,704,000
| 1,549,187,704,000
| 155,690,284
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 4,393
|
lean
|
/- Lecture 2.4: Functional Programming — Metaprogramming -/
/- Tactics -/
example : true :=
by tactic.triv
example : true := by do
tactic.trace "Hello, Metacosmos!",
tactic.triv
meta def hello_world : tactic unit := do
tactic.trace "Hello, Metacosmos!",
tactic.triv
example : true := by hello_world
run_cmd hello_world
open tactic
example (α : Type) (a : α) : true := by do
trace "local context:",
local_context >>= trace,
trace "goals:",
get_goals >>= trace,
trace "target:",
target >>= trace,
triv
meta def exact_list : list expr → tactic unit
| [] := fail "no matching expression found"
| (e :: es) :=
(do
trace "trying ",
trace e,
exact e)
<|> exact_list es
meta def find_assumption : tactic unit := do
es ← local_context,
exact_list es
example {p : Prop} {α : Type} (a : α) (h : p) : p := by do
find_assumption
example {p : Prop} (h : p) : p := by do
p_proof ← get_local `h,
trace "p_proof:",
trace p_proof,
trace p_proof.to_raw_fmt,
trace "type of p_proof:",
infer_type p_proof >>= trace,
trace "type of type of p_proof:",
infer_type p_proof >>= infer_type >>= trace,
apply p_proof
/- Names and expressions -/
#print expr
#check expr tt -- elaborated expressions
#check expr ff -- unelaborated expressions (pre-expressions)
#print name
#check (expr.const `ℕ [] : expr)
#check expr.sort level.zero -- Sort 0, i.e. Prop
#check expr.sort (level.succ level.zero) -- Sort 1, i.e. Type 0 (Type)
#check expr.app
#check expr.var 0 -- bound variable of De Bruijn index 0
#check (expr.local_const `uniq_name `pp_name binder_info.default `(ℕ) : expr)
#check (expr.mvar `uniq_name `pp_name `(ℕ) : expr)
#check (expr.pi `pp_name binder_info.default `(ℕ) (expr.sort level.zero) : expr)
#check (expr.lam `pp_name binder_info.default `(ℕ) (expr.var 0) : expr)
#check expr.elet
#check expr.macro
/- Name literals -/
run_cmd trace `name.a
run_cmd trace ``true
run_cmd trace ``name.a -- not found
/- Expression literals -/
-- one backtick: fully elaborated expressions (using reflection)
run_cmd do
let e : expr := `(list.map (λn : ℕ, n + 1) [1, 2, 3]),
trace e
run_cmd do
let e : expr := `(list.map _ [1, 2, 3]), -- error: holes not allowed
skip
-- two backticks: checked pre-expressions
run_cmd do
let e₀ : pexpr := ``(list.map (λn, n + 1) [1, 2, 3]),
let e₁ : pexpr := ``(list.map _ [1, 2, 3]),
trace e₀,
trace e₁
-- three backticks: pre-expressions without name checking
run_cmd do
let e := ```(a),
trace e
/- Antiquotations -/
run_cmd do
let x : expr := `(2 : ℕ),
let e : expr := `(%%x + 1),
trace e
run_cmd do
let x : expr := `(@id ℕ),
let e := ``(list.map %%x),
trace e
run_cmd do
let x : expr := `(@id ℕ),
let e := ```(a _ %%x),
trace e
/- Pattern matching -/
example : 1 + 2 = 3 := by do
`(%%a + %%b = %%r) ← target,
trace a, trace b, trace r,
`(@eq %%α %%l' %%r') ← target,
trace α, trace l', trace r',
exact `(refl _ : 3 = 3)
/- A simple tactic: `destruct_and` -/
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) : a := and.left h
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) : b := and.left (and.left (and.right h))
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) : b ∧ c := and.left (and.right h)
-- `destruct_and_core t h` uses the conjunction `h : t` to prove the current goal
meta def destruct_and_core : expr → expr → tactic unit
| `(%%a ∧ %%b) h :=
exact h
<|> (to_expr ``(and.left %%h) >>= destruct_and_core a)
<|> (to_expr ``(and.right %%h) >>= destruct_and_core b)
| _ h := exact h
meta def destruct_and (h : name) : tactic unit := do
h ← get_local h,
t ← infer_type h,
destruct_and_core t h
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) : a := by destruct_and `h
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) : b := by destruct_and `h
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) : b ∧ c := by destruct_and `h
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) : b ∧ d := by destruct_and `h -- fails
#check exact
#check interactive.exact
#check lean.parser
open interactive.types
meta def tactic.interactive.destruct_and (h : interactive.parse ident_) : tactic unit :=
destruct_and h
example {a b c d : Prop} (h : a ∧ (b ∧ c) ∧ d) : a :=
by destruct_and h
|
471ece3e616102cbe4bf0382d4338df9674c9b41
|
130c49f47783503e462c16b2eff31933442be6ff
|
/src/Lean/PrettyPrinter/Formatter.lean
|
6204668262caecbf1c6447b5b4bd8e7eb8eefd04
|
[
"Apache-2.0"
] |
permissive
|
Hazel-Brown/lean4
|
8aa5860e282435ffc30dcdfccd34006c59d1d39c
|
79e6732fc6bbf5af831b76f310f9c488d44e7a16
|
refs/heads/master
| 1,689,218,208,951
| 1,629,736,869,000
| 1,629,736,896,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 21,388
|
lean
|
/-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Lean.CoreM
import Lean.Parser.Extension
import Lean.KeyedDeclsAttribute
import Lean.ParserCompiler.Attribute
import Lean.PrettyPrinter.Basic
/-!
The formatter turns a `Syntax` tree into a `Format` object, inserting both mandatory whitespace (to separate adjacent
tokens) as well as "pretty" optional whitespace.
The basic approach works much like the parenthesizer: A right-to-left traversal over the syntax tree, driven by
parser-specific handlers registered via attributes. The traversal is right-to-left so that when emitting a token, we
already know the text following it and can decide whether or not whitespace between the two is necessary.
-/
namespace Lean
namespace PrettyPrinter
namespace Formatter
structure Context where
options : Options
table : Parser.TokenTable
structure State where
stxTrav : Syntax.Traverser
-- Textual content of `stack` up to the first whitespace (not enclosed in an escaped ident). We assume that the textual
-- content of `stack` is modified only by `pushText` and `pushLine`, so `leadWord` is adjusted there accordingly.
leadWord : String := ""
-- Stack of generated Format objects, analogous to the Syntax stack in the parser.
-- Note, however, that the stack is reversed because of the right-to-left traversal.
stack : Array Format := #[]
end Formatter
abbrev FormatterM := ReaderT Formatter.Context $ StateRefT Formatter.State CoreM
@[inline] def FormatterM.orelse {α} (p₁ p₂ : FormatterM α) : FormatterM α := do
let s ← get
catchInternalId backtrackExceptionId
p₁
(fun _ => do set s; p₂)
instance {α} : OrElse (FormatterM α) := ⟨FormatterM.orelse⟩
abbrev Formatter := FormatterM Unit
unsafe def mkFormatterAttribute : IO (KeyedDeclsAttribute Formatter) :=
KeyedDeclsAttribute.init {
builtinName := `builtinFormatter,
name := `formatter,
descr := "Register a formatter for a parser.
[formatter k] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `SyntaxNodeKind` `k`.",
valueTypeName := `Lean.PrettyPrinter.Formatter,
evalKey := fun builtin stx => do
let env ← getEnv
let id ← Attribute.Builtin.getId stx
-- `isValidSyntaxNodeKind` is updated only in the next stage for new `[builtin*Parser]`s, but we try to
-- synthesize a formatter for it immediately, so we just check for a declaration in this case
if (builtin && (env.find? id).isSome) || Parser.isValidSyntaxNodeKind env id then pure id
else throwError "invalid [formatter] argument, unknown syntax kind '{id}'"
} `Lean.PrettyPrinter.formatterAttribute
@[builtinInit mkFormatterAttribute] constant formatterAttribute : KeyedDeclsAttribute Formatter
unsafe def mkCombinatorFormatterAttribute : IO ParserCompiler.CombinatorAttribute :=
ParserCompiler.registerCombinatorAttribute
`combinatorFormatter
"Register a formatter for a parser combinator.
[combinatorFormatter c] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `Parser` declaration `c`.
Note that, unlike with [formatter], this is not a node kind since combinators usually do not introduce their own node kinds.
The tagged declaration may optionally accept parameters corresponding to (a prefix of) those of `c`, where `Parser` is replaced
with `Formatter` in the parameter types."
@[builtinInit mkCombinatorFormatterAttribute] constant combinatorFormatterAttribute : ParserCompiler.CombinatorAttribute
namespace Formatter
open Lean.Core
open Lean.Parser
def throwBacktrack {α} : FormatterM α :=
throw $ Exception.internal backtrackExceptionId
instance : Syntax.MonadTraverser FormatterM := ⟨{
get := State.stxTrav <$> get,
set := fun t => modify (fun st => { st with stxTrav := t }),
modifyGet := fun f => modifyGet (fun st => let (a, t) := f st.stxTrav; (a, { st with stxTrav := t }))
}⟩
open Syntax.MonadTraverser
def getStack : FormatterM (Array Format) := do
let st ← get
pure st.stack
def getStackSize : FormatterM Nat := do
let stack ← getStack;
pure stack.size
def setStack (stack : Array Format) : FormatterM Unit :=
modify fun st => { st with stack := stack }
def push (f : Format) : FormatterM Unit :=
modify fun st => { st with stack := st.stack.push f }
def pushLine : FormatterM Unit := do
push Format.line;
modify fun st => { st with leadWord := "" }
/-- Execute `x` at the right-most child of the current node, if any, then advance to the left. -/
def visitArgs (x : FormatterM Unit) : FormatterM Unit := do
let stx ← getCur
if stx.getArgs.size > 0 then
goDown (stx.getArgs.size - 1) *> x <* goUp
goLeft
/-- Execute `x`, pass array of generated Format objects to `fn`, and push result. -/
def fold (fn : Array Format → Format) (x : FormatterM Unit) : FormatterM Unit := do
let sp ← getStackSize
x
let stack ← getStack
let f := fn $ stack.extract sp stack.size
setStack $ (stack.shrink sp).push f
/-- Execute `x` and concatenate generated Format objects. -/
def concat (x : FormatterM Unit) : FormatterM Unit := do
fold (Array.foldl (fun acc f => if acc.isNil then f else f ++ acc) Format.nil) x
def indent (x : Formatter) (indent : Option Int := none) : Formatter := do
concat x
let ctx ← read
let indent := indent.getD $ Std.Format.getIndent ctx.options
modify fun st => { st with stack := st.stack.pop.push (Format.nest indent st.stack.back) }
def group (x : Formatter) : Formatter := do
concat x
modify fun st => { st with stack := st.stack.pop.push (Format.fill st.stack.back) }
/-- Tags the top of the stack with `stx`'s position, if it has one. -/
def tagTop (stx : Syntax) : Formatter := do
if let some p := stx.getPos? then
modify fun st => { st with stack := st.stack.pop.push (Format.tag p st.stack.back) }
@[combinatorFormatter Lean.Parser.orelse] def orelse.formatter (p1 p2 : Formatter) : Formatter :=
-- HACK: We have no (immediate) information on which side of the orelse could have produced the current node, so try
-- them in turn. Uses the syntax traverser non-linearly!
p1 <|> p2
-- `mkAntiquot` is quite complex, so we'd rather have its formatter synthesized below the actual parser definition.
-- Note that there is a mutual recursion
-- `categoryParser -> mkAntiquot -> termParser -> categoryParser`, so we need to introduce an indirection somewhere
-- anyway.
@[extern "lean_mk_antiquot_formatter"]
constant mkAntiquot.formatter' (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Formatter
-- break up big mutual recursion
@[extern "lean_pretty_printer_formatter_interpret_parser_descr"]
constant interpretParserDescr' : ParserDescr → CoreM Formatter
unsafe def formatterForKindUnsafe (k : SyntaxNodeKind) : Formatter := do
if k == `missing then
push "<missing>"
goLeft
else
let f ← runForNodeKind formatterAttribute k interpretParserDescr'
let stx ← getCur
concat f
tagTop stx
@[implementedBy formatterForKindUnsafe]
constant formatterForKind (k : SyntaxNodeKind) : Formatter
@[combinatorFormatter Lean.Parser.withAntiquot]
def withAntiquot.formatter (antiP p : Formatter) : Formatter :=
-- TODO: could be optimized using `isAntiquot` (which would have to be moved), but I'd rather
-- fix the backtracking hack outright.
orelse.formatter antiP p
@[combinatorFormatter Lean.Parser.withAntiquotSuffixSplice]
def withAntiquotSuffixSplice.formatter (k : SyntaxNodeKind) (p suffix : Formatter) : Formatter := do
if (← getCur).isAntiquotSuffixSplice then
visitArgs <| suffix *> p
else
p
@[combinatorFormatter Lean.Parser.tokenWithAntiquot]
def tokenWithAntiquot.formatter (p : Formatter) : Formatter := do
if (← getCur).isTokenAntiquot then
visitArgs p
else
p
@[combinatorFormatter Lean.Parser.categoryParser]
def categoryParser.formatter (cat : Name) : Formatter := group $ indent do
let stx ← getCur
trace[PrettyPrinter.format] "formatting {indentD (format stx)}"
if stx.getKind == `choice then
visitArgs do
-- format only last choice
-- TODO: We could use elaborator data here to format the chosen child when available
formatterForKind (← getCur).getKind
else
withAntiquot.formatter (mkAntiquot.formatter' cat.toString none) (formatterForKind stx.getKind)
@[combinatorFormatter Lean.Parser.categoryParserOfStack]
def categoryParserOfStack.formatter (offset : Nat) : Formatter := do
let st ← get
let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset)
categoryParser.formatter stx.getId
@[combinatorFormatter Lean.Parser.parserOfStack]
def parserOfStack.formatter (offset : Nat) (prec : Nat := 0) : Formatter := do
let st ← get
let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset)
formatterForKind stx.getKind
@[combinatorFormatter Lean.Parser.error]
def error.formatter (msg : String) : Formatter := pure ()
@[combinatorFormatter Lean.Parser.errorAtSavedPos]
def errorAtSavedPos.formatter (msg : String) (delta : Bool) : Formatter := pure ()
@[combinatorFormatter Lean.Parser.atomic]
def atomic.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.lookahead]
def lookahead.formatter (p : Formatter) : Formatter := pure ()
@[combinatorFormatter Lean.Parser.notFollowedBy]
def notFollowedBy.formatter (p : Formatter) : Formatter := pure ()
@[combinatorFormatter Lean.Parser.andthen]
def andthen.formatter (p1 p2 : Formatter) : Formatter := p2 *> p1
def checkKind (k : SyntaxNodeKind) : FormatterM Unit := do
let stx ← getCur
if k != stx.getKind then
trace[PrettyPrinter.format.backtrack] "unexpected node kind '{stx.getKind}', expected '{k}'"
throwBacktrack
@[combinatorFormatter Lean.Parser.node]
def node.formatter (k : SyntaxNodeKind) (p : Formatter) : Formatter := do
checkKind k;
visitArgs p
@[combinatorFormatter Lean.Parser.trailingNode]
def trailingNode.formatter (k : SyntaxNodeKind) (_ _ : Nat) (p : Formatter) : Formatter := do
checkKind k
visitArgs do
p;
-- leading term, not actually produced by `p`
categoryParser.formatter `foo
def parseToken (s : String) : FormatterM ParserState := do
-- include comment tokens, e.g. when formatting `- -0`
(Parser.andthenFn Parser.whitespace (Parser.tokenFn [])) {
input := s,
fileName := "",
fileMap := FileMap.ofString "",
prec := 0,
env := ← getEnv,
options := ← getOptions,
tokens := (← read).table } (Parser.mkParserState s)
def pushTokenCore (tk : String) : FormatterM Unit := do
if tk.toSubstring.dropRightWhile (fun s => s == ' ') == tk.toSubstring then
push tk
else
pushLine
push tk.trimRight
def pushToken (info : SourceInfo) (tk : String) : FormatterM Unit := do
match info with
| SourceInfo.original _ _ ss _ =>
-- preserve non-whitespace content (i.e. comments)
let ss' := ss.trim
if !ss'.isEmpty then
let ws := { ss with startPos := ss'.stopPos }
if ws.contains '\n' then
push s!"\n{ss'}"
else
push s!" {ss'}"
modify fun st => { st with leadWord := "" }
| _ => pure ()
let st ← get
-- If there is no space between `tk` and the next word, see if we would parse more than `tk` as a single token
if st.leadWord != "" && tk.trimRight == tk then
let tk' := tk.trimLeft
let t ← parseToken $ tk' ++ st.leadWord
if t.pos <= tk'.bsize then
-- stopped within `tk` => use it as is, extend `leadWord` if not prefixed by whitespace
pushTokenCore tk
modify fun st => { st with leadWord := if tk.trimLeft == tk then tk ++ st.leadWord else "" }
else
-- stopped after `tk` => add space
pushTokenCore $ tk ++ " "
modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" }
else
-- already separated => use `tk` as is
pushTokenCore tk
modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" }
match info with
| SourceInfo.original ss _ _ _ =>
-- preserve non-whitespace content (i.e. comments)
let ss' := ss.trim
if !ss'.isEmpty then
let ws := { ss with startPos := ss'.stopPos }
if ws.contains '\n' then do
-- Indentation is automatically increased when entering a category, but comments should be aligned
-- with the actual token, so dedent
indent (push s!"{ss'}\n") (some ((0:Int) - Std.Format.getIndent (← getOptions)))
else
push s!"{ss'} "
modify fun st => { st with leadWord := "" }
| _ => pure ()
@[combinatorFormatter Lean.Parser.symbolNoAntiquot]
def symbolNoAntiquot.formatter (sym : String) : Formatter := do
let stx ← getCur
if stx.isToken sym then do
let (Syntax.atom info _) ← pure stx | unreachable!
pushToken info sym
goLeft
else do
trace[PrettyPrinter.format.backtrack] "unexpected syntax '{format stx}', expected symbol '{sym}'"
throwBacktrack
@[combinatorFormatter Lean.Parser.nonReservedSymbolNoAntiquot] def nonReservedSymbolNoAntiquot.formatter := symbolNoAntiquot.formatter
@[combinatorFormatter Lean.Parser.rawCh] def rawCh.formatter (ch : Char) := symbolNoAntiquot.formatter ch.toString
@[combinatorFormatter Lean.Parser.unicodeSymbolNoAntiquot]
def unicodeSymbolNoAntiquot.formatter (sym asciiSym : String) : Formatter := do
let Syntax.atom info val ← getCur
| throwError m!"not an atom: {← getCur}"
if val == sym.trim then
pushToken info sym
else
pushToken info asciiSym;
goLeft
@[combinatorFormatter Lean.Parser.identNoAntiquot]
def identNoAntiquot.formatter : Formatter := do
checkKind identKind
let Syntax.ident info _ id _ ← getCur
| throwError m!"not an ident: {← getCur}"
let id := id.simpMacroScopes
pushToken info id.toString
goLeft
@[combinatorFormatter Lean.Parser.rawIdentNoAntiquot] def rawIdentNoAntiquot.formatter : Formatter := do
checkKind identKind
let Syntax.ident info _ id _ ← getCur
| throwError m!"not an ident: {← getCur}"
pushToken info id.toString
goLeft
@[combinatorFormatter Lean.Parser.identEq] def identEq.formatter (id : Name) := rawIdentNoAntiquot.formatter
def visitAtom (k : SyntaxNodeKind) : Formatter := do
let stx ← getCur
if k != Name.anonymous then
checkKind k
let Syntax.atom info val ← pure $ stx.ifNode (fun n => n.getArg 0) (fun _ => stx)
| throwError m!"not an atom: {stx}"
pushToken info val
goLeft
@[combinatorFormatter Lean.Parser.charLitNoAntiquot] def charLitNoAntiquot.formatter := visitAtom charLitKind
@[combinatorFormatter Lean.Parser.strLitNoAntiquot] def strLitNoAntiquot.formatter := visitAtom strLitKind
@[combinatorFormatter Lean.Parser.nameLitNoAntiquot] def nameLitNoAntiquot.formatter := visitAtom nameLitKind
@[combinatorFormatter Lean.Parser.numLitNoAntiquot] def numLitNoAntiquot.formatter := visitAtom numLitKind
@[combinatorFormatter Lean.Parser.scientificLitNoAntiquot] def scientificLitNoAntiquot.formatter := visitAtom scientificLitKind
@[combinatorFormatter Lean.Parser.fieldIdx] def fieldIdx.formatter := visitAtom fieldIdxKind
@[combinatorFormatter Lean.Parser.manyNoAntiquot]
def manyNoAntiquot.formatter (p : Formatter) : Formatter := do
let stx ← getCur
visitArgs $ stx.getArgs.size.forM fun _ => p
@[combinatorFormatter Lean.Parser.many1NoAntiquot] def many1NoAntiquot.formatter (p : Formatter) : Formatter := manyNoAntiquot.formatter p
@[combinatorFormatter Lean.Parser.optionalNoAntiquot]
def optionalNoAntiquot.formatter (p : Formatter) : Formatter := visitArgs p
@[combinatorFormatter Lean.Parser.many1Unbox]
def many1Unbox.formatter (p : Formatter) : Formatter := do
let stx ← getCur
if stx.getKind == nullKind then do
manyNoAntiquot.formatter p
else
p
@[combinatorFormatter Lean.Parser.sepByNoAntiquot]
def sepByNoAntiquot.formatter (p pSep : Formatter) : Formatter := do
let stx ← getCur
visitArgs $ (List.range stx.getArgs.size).reverse.forM $ fun i => if i % 2 == 0 then p else pSep
@[combinatorFormatter Lean.Parser.sepBy1NoAntiquot] def sepBy1NoAntiquot.formatter := sepByNoAntiquot.formatter
@[combinatorFormatter Lean.Parser.withPosition] def withPosition.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.withoutPosition] def withoutPosition.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.withForbidden] def withForbidden.formatter (tk : Token) (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.withoutForbidden] def withoutForbidden.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.withoutInfo] def withoutInfo.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.setExpected]
def setExpected.formatter (expected : List String) (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.incQuotDepth] def incQuotDepth.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.decQuotDepth] def decQuotDepth.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.suppressInsideQuot] def suppressInsideQuot.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.evalInsideQuot] def evalInsideQuot.formatter (declName : Name) (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.checkWsBefore] def checkWsBefore.formatter : Formatter := do
let st ← get
if st.leadWord != "" then
pushLine
@[combinatorFormatter Lean.Parser.checkPrec] def checkPrec.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkLhsPrec] def checkLhsPrec.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.setLhsPrec] def setLhsPrec.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkStackTop] def checkStackTop.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkNoWsBefore] def checkNoWsBefore.formatter : Formatter :=
-- prevent automatic whitespace insertion
modify fun st => { st with leadWord := "" }
@[combinatorFormatter Lean.Parser.checkLinebreakBefore] def checkLinebreakBefore.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkTailWs] def checkTailWs.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkColGe] def checkColGe.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkColGt] def checkColGt.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkLineEq] def checkLineEq.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.eoi] def eoi.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.notFollowedByCategoryToken] def notFollowedByCategoryToken.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkNoImmediateColon] def checkNoImmediateColon.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkInsideQuot] def checkInsideQuot.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.checkOutsideQuot] def checkOutsideQuot.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.skip] def skip.formatter : Formatter := pure ()
@[combinatorFormatter Lean.Parser.pushNone] def pushNone.formatter : Formatter := goLeft
@[combinatorFormatter Lean.Parser.withOpenDecl] def withOpenDecl.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.withOpen] def withOpen.formatter (p : Formatter) : Formatter := p
@[combinatorFormatter Lean.Parser.interpolatedStr]
def interpolatedStr.formatter (p : Formatter) : Formatter := do
visitArgs $ (← getCur).getArgs.reverse.forM fun chunk =>
match chunk.isLit? interpolatedStrLitKind with
| some str => push str *> goLeft
| none => p
@[combinatorFormatter Lean.Parser.dbgTraceState] def dbgTraceState.formatter (label : String) (p : Formatter) : Formatter := p
@[combinatorFormatter ite, macroInline] def ite {α : Type} (c : Prop) [h : Decidable c] (t e : Formatter) : Formatter :=
if c then t else e
abbrev FormatterAliasValue := AliasValue Formatter
builtin_initialize formatterAliasesRef : IO.Ref (NameMap FormatterAliasValue) ← IO.mkRef {}
def registerAlias (aliasName : Name) (v : FormatterAliasValue) : IO Unit := do
Parser.registerAliasCore formatterAliasesRef aliasName v
instance : Coe Formatter FormatterAliasValue := { coe := AliasValue.const }
instance : Coe (Formatter → Formatter) FormatterAliasValue := { coe := AliasValue.unary }
instance : Coe (Formatter → Formatter → Formatter) FormatterAliasValue := { coe := AliasValue.binary }
end Formatter
open Formatter
def format (formatter : Formatter) (stx : Syntax) : CoreM Format := do
trace[PrettyPrinter.format.input] "{Std.format stx}"
let options ← getOptions
let table ← Parser.builtinTokenTable.get
catchInternalId backtrackExceptionId
(do
let (_, st) ← (concat formatter { table := table, options := options }).run { stxTrav := Syntax.Traverser.fromSyntax stx };
pure $ Format.fill $ st.stack.get! 0)
(fun _ => throwError "format: uncaught backtrack exception")
def formatTerm := format $ categoryParser.formatter `term
def formatCommand := format $ categoryParser.formatter `command
builtin_initialize registerTraceClass `PrettyPrinter.format;
end PrettyPrinter
end Lean
|
5fda41b7aaf5f6e0ed703d78c50428ec17cac5d5
|
7cef822f3b952965621309e88eadf618da0c8ae9
|
/src/topology/metric_space/hausdorff_distance.lean
|
23d51502044bb8980fd979ad57096ac1bc428536
|
[
"Apache-2.0"
] |
permissive
|
rmitta/mathlib
|
8d90aee30b4db2b013e01f62c33f297d7e64a43d
|
883d974b608845bad30ae19e27e33c285200bf84
|
refs/heads/master
| 1,585,776,832,544
| 1,576,874,096,000
| 1,576,874,096,000
| 153,663,165
| 0
| 2
|
Apache-2.0
| 1,544,806,490,000
| 1,539,884,365,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 32,532
|
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.isometry topology.instances.ennreal
topology.metric_space.lipschitz
/-!
# Hausdorff distance
The Hausdorff distance on subsets of a metric (or emetric) space.
Given two subsets `s` and `t` of a metric space, their Hausdorff distance is the smallest `d`
such that any point `s` is within `d` of a point in `t`, and conversely. This quantity
is often infinite (think of `s` bounded and `t` unbounded), and therefore better
expressed in the setting of emetric spaces.
## Main definitions
This files introduces:
* `inf_edist x s`, the infimum edistance of a point `x` to a set `s` in an emetric space
* `Hausdorff_edist s t`, the Hausdorff edistance of two sets in an emetric space
* Versions of these notions on metric spaces, called respectively `inf_dist` and
`Hausdorff_dist`.
-/
noncomputable theory
open_locale classical
universes u v w
open classical lattice set function topological_space filter
namespace emetric
section inf_edist
open_locale ennreal
variables {α : Type u} {β : Type v} [emetric_space α] [emetric_space β] {x y : α} {s t : set α} {Φ : α → β}
/-- The minimal edistance of a point to a set -/
def inf_edist (x : α) (s : set α) : ennreal := Inf ((edist x) '' s)
@[simp] lemma inf_edist_empty : inf_edist x ∅ = ∞ :=
by unfold inf_edist; simp
/-- The edist to a union is the minimum of the edists -/
@[simp] lemma inf_edist_union : inf_edist x (s ∪ t) = inf_edist x s ⊓ inf_edist x t :=
by simp [inf_edist, image_union, Inf_union]
/-- The edist to a singleton is the edistance to the single point of this singleton -/
@[simp] lemma inf_edist_singleton : inf_edist x {y} = edist x y :=
by simp [inf_edist]
/-- The edist to a set is bounded above by the edist to any of its points -/
lemma inf_edist_le_edist_of_mem (h : y ∈ s) : inf_edist x s ≤ edist x y :=
Inf_le ((mem_image _ _ _).2 ⟨y, h, by refl⟩)
/-- If a point `x` belongs to `s`, then its edist to `s` vanishes -/
lemma inf_edist_zero_of_mem (h : x ∈ s) : inf_edist x s = 0 :=
le_zero_iff_eq.1 $ @edist_self _ _ x ▸ inf_edist_le_edist_of_mem h
/-- The edist is monotonous with respect to inclusion -/
lemma inf_edist_le_inf_edist_of_subset (h : s ⊆ t) : inf_edist x t ≤ inf_edist x s :=
Inf_le_Inf (image_subset _ h)
/-- If the edist to a set is `< r`, there exists a point in the set at edistance `< r` -/
lemma exists_edist_lt_of_inf_edist_lt {r : ennreal} (h : inf_edist x s < r) :
∃y∈s, edist x y < r :=
let ⟨t, ⟨ht, tr⟩⟩ := Inf_lt_iff.1 h in
let ⟨y, ⟨ys, hy⟩⟩ := (mem_image _ _ _).1 ht in
⟨y, ys, by rwa ← hy at tr⟩
/-- The edist of `x` to `s` is bounded by the sum of the edist of `y` to `s` and
the edist from `x` to `y` -/
lemma inf_edist_le_inf_edist_add_edist : inf_edist x s ≤ inf_edist y s + edist x y :=
begin
have : ∀z ∈ s, Inf (edist x '' s) ≤ edist y z + edist x y := λz hz, calc
Inf (edist x '' s) ≤ edist x z :
Inf_le ((mem_image _ _ _).2 ⟨z, hz, by refl⟩)
... ≤ edist x y + edist y z : edist_triangle _ _ _
... = edist y z + edist x y : add_comm _ _,
have : (λz, z + edist x y) (Inf (edist y '' s)) = Inf ((λz, z + edist x y) '' (edist y '' s)),
{ refine Inf_of_continuous _ _ (by simp),
{ exact continuous_id.add continuous_const },
{ assume a b h, simp, apply add_le_add_right' h }},
simp only [inf_edist] at this,
rw [inf_edist, inf_edist, this, ← image_comp],
simpa only [and_imp, function.comp_app, lattice.le_Inf_iff, exists_imp_distrib, ball_image_iff]
end
/-- The edist to a set depends continuously on the point -/
lemma continuous_inf_edist : continuous (λx, inf_edist x s) :=
continuous_of_le_add_edist 1 (by simp) $
by simp only [one_mul, inf_edist_le_inf_edist_add_edist, forall_2_true_iff]
/-- The edist to a set and to its closure coincide -/
lemma inf_edist_closure : inf_edist x (closure s) = inf_edist x s :=
begin
refine le_antisymm (inf_edist_le_inf_edist_of_subset subset_closure) _,
refine ennreal.le_of_forall_epsilon_le (λε εpos h, _),
have εpos' : (0 : ennreal) < ε := by simpa,
have : inf_edist x (closure s) < inf_edist x (closure s) + ε/2 :=
ennreal.lt_add_right h (ennreal.half_pos εpos'),
rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ycs, hy⟩,
-- y : α, ycs : y ∈ closure s, hy : edist x y < inf_edist x (closure s) + ↑ε / 2
rcases emetric.mem_closure_iff'.1 ycs (ε/2) (ennreal.half_pos εpos') with ⟨z, zs, dyz⟩,
-- z : α, zs : z ∈ s, dyz : edist y z < ↑ε / 2
calc inf_edist x s ≤ edist x z : inf_edist_le_edist_of_mem zs
... ≤ edist x y + edist y z : edist_triangle _ _ _
... ≤ (inf_edist x (closure s) + ε / 2) + (ε/2) : add_le_add' (le_of_lt hy) (le_of_lt dyz)
... = inf_edist x (closure s) + ↑ε : by simp [ennreal.add_halves]
end
/-- A point belongs to the closure of `s` iff its infimum edistance to this set vanishes -/
lemma mem_closure_iff_inf_edist_zero : x ∈ closure s ↔ inf_edist x s = 0 :=
⟨λh, by rw ← inf_edist_closure; exact inf_edist_zero_of_mem h,
λh, emetric.mem_closure_iff'.2 $ λε εpos, exists_edist_lt_of_inf_edist_lt (by rwa h)⟩
/-- Given a closed set `s`, a point belongs to `s` iff its infimum edistance to this set vanishes -/
lemma mem_iff_ind_edist_zero_of_closed (h : is_closed s) : x ∈ s ↔ inf_edist x s = 0 :=
begin
convert ← mem_closure_iff_inf_edist_zero,
exact closure_eq_iff_is_closed.2 h
end
/-- The infimum edistance is invariant under isometries -/
lemma inf_edist_image (hΦ : isometry Φ) :
inf_edist (Φ x) (Φ '' t) = inf_edist x t :=
begin
simp only [inf_edist],
apply congr_arg,
ext b, split,
{ assume hb,
rcases (mem_image _ _ _).1 hb with ⟨y, ⟨hy, hy'⟩⟩,
rcases (mem_image _ _ _).1 hy with ⟨z, ⟨hz, hz'⟩⟩,
rw [← hy', ← hz', hΦ x z],
exact mem_image_of_mem _ hz },
{ assume hb,
rcases (mem_image _ _ _).1 hb with ⟨y, ⟨hy, hy'⟩⟩,
rw [← hy', ← hΦ x y],
exact mem_image_of_mem _ (mem_image_of_mem _ hy) }
end
end inf_edist --section
/-- The Hausdorff edistance between two sets is the smallest `r` such that each set
is contained in the `r`-neighborhood of the other one -/
def Hausdorff_edist {α : Type u} [emetric_space α] (s t : set α) : ennreal :=
Sup ((λx, inf_edist x t) '' s) ⊔ Sup ((λx, inf_edist x s) '' t)
lemma Hausdorff_edist_def {α : Type u} [emetric_space α] (s t : set α) :
Hausdorff_edist s t = Sup ((λx, inf_edist x t) '' s) ⊔ Sup ((λx, inf_edist x s) '' t) := rfl
attribute [irreducible] Hausdorff_edist
section Hausdorff_edist
open_locale ennreal
variables {α : Type u} {β : Type v} [emetric_space α] [emetric_space β]
{x y : α} {s t u : set α} {Φ : α → β}
/-- The Hausdorff edistance of a set to itself vanishes -/
@[simp] lemma Hausdorff_edist_self : Hausdorff_edist s s = 0 :=
begin
erw [Hausdorff_edist_def, lattice.sup_idem, ← le_bot_iff],
apply Sup_le _,
simp [le_bot_iff, inf_edist_zero_of_mem] {contextual := tt},
end
/-- The Haudorff edistances of `s` to `t` and of `t` to `s` coincide -/
lemma Hausdorff_edist_comm : Hausdorff_edist s t = Hausdorff_edist t s :=
by unfold Hausdorff_edist; apply sup_comm
/-- Bounding the Hausdorff edistance by bounding the edistance of any point
in each set to the other set -/
lemma Hausdorff_edist_le_of_inf_edist {r : ennreal}
(H1 : ∀x ∈ s, inf_edist x t ≤ r) (H2 : ∀x ∈ t, inf_edist x s ≤ r) :
Hausdorff_edist s t ≤ r :=
begin
simp only [Hausdorff_edist, -mem_image, set.ball_image_iff, lattice.Sup_le_iff, lattice.sup_le_iff],
exact ⟨H1, H2⟩
end
/-- Bounding the Hausdorff edistance by exhibiting, for any point in each set,
another point in the other set at controlled distance -/
lemma Hausdorff_edist_le_of_mem_edist {r : ennreal}
(H1 : ∀x ∈ s, ∃y ∈ t, edist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, edist x y ≤ r) :
Hausdorff_edist s t ≤ r :=
begin
refine Hausdorff_edist_le_of_inf_edist _ _,
{ assume x xs,
rcases H1 x xs with ⟨y, yt, hy⟩,
exact le_trans (inf_edist_le_edist_of_mem yt) hy },
{ assume x xt,
rcases H2 x xt with ⟨y, ys, hy⟩,
exact le_trans (inf_edist_le_edist_of_mem ys) hy }
end
/-- The distance to a set is controlled by the Hausdorff distance -/
lemma inf_edist_le_Hausdorff_edist_of_mem (h : x ∈ s) : inf_edist x t ≤ Hausdorff_edist s t :=
begin
rw Hausdorff_edist_def,
refine le_trans (le_Sup _) le_sup_left,
exact mem_image_of_mem _ h
end
/-- If the Hausdorff distance is `<r`, then any point in one of the sets has
a corresponding point at distance `<r` in the other set -/
lemma exists_edist_lt_of_Hausdorff_edist_lt {r : ennreal} (h : x ∈ s) (H : Hausdorff_edist s t < r) :
∃y∈t, edist x y < r :=
exists_edist_lt_of_inf_edist_lt $ calc
inf_edist x t ≤ Sup ((λx, inf_edist x t) '' s) : le_Sup (mem_image_of_mem _ h)
... ≤ Sup ((λx, inf_edist x t) '' s) ⊔ Sup ((λx, inf_edist x s) '' t) : le_sup_left
... < r : by rwa Hausdorff_edist_def at H
/-- The distance from `x` to `s`or `t` is controlled in terms of the Hausdorff distance
between `s` and `t` -/
lemma inf_edist_le_inf_edist_add_Hausdorff_edist :
inf_edist x t ≤ inf_edist x s + Hausdorff_edist s t :=
ennreal.le_of_forall_epsilon_le $ λε εpos h, begin
have εpos' : (0 : ennreal) < ε := by simpa,
have : inf_edist x s < inf_edist x s + ε/2 :=
ennreal.lt_add_right (ennreal.add_lt_top.1 h).1 (ennreal.half_pos εpos'),
rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, dxy⟩,
-- y : α, ys : y ∈ s, dxy : edist x y < inf_edist x s + ↑ε / 2
have : Hausdorff_edist s t < Hausdorff_edist s t + ε/2 :=
ennreal.lt_add_right (ennreal.add_lt_top.1 h).2 (ennreal.half_pos εpos'),
rcases exists_edist_lt_of_Hausdorff_edist_lt ys this with ⟨z, zt, dyz⟩,
-- z : α, zt : z ∈ t, dyz : edist y z < Hausdorff_edist s t + ↑ε / 2
calc inf_edist x t ≤ edist x z : inf_edist_le_edist_of_mem zt
... ≤ edist x y + edist y z : edist_triangle _ _ _
... ≤ (inf_edist x s + ε/2) + (Hausdorff_edist s t + ε/2) : add_le_add' (le_of_lt dxy) (le_of_lt dyz)
... = inf_edist x s + Hausdorff_edist s t + ε : by simp [ennreal.add_halves, add_comm]
end
/-- The Hausdorff edistance is invariant under eisometries -/
lemma Hausdorff_edist_image (h : isometry Φ) :
Hausdorff_edist (Φ '' s) (Φ '' t) = Hausdorff_edist s t :=
begin
unfold Hausdorff_edist,
congr,
{ ext b,
split,
{ assume hb,
rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩,
rcases (mem_image _ _ _ ).1 hy with ⟨z, ⟨hz, hz'⟩⟩,
rw [← hy', ← hz', inf_edist_image h],
exact mem_image_of_mem _ hz },
{ assume hb,
rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩,
rw [← hy', ← inf_edist_image h],
exact mem_image_of_mem _ (mem_image_of_mem _ hy) }},
{ ext b,
split,
{ assume hb,
rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩,
rcases (mem_image _ _ _ ).1 hy with ⟨z, ⟨hz, hz'⟩⟩,
rw [← hy', ← hz', inf_edist_image h],
exact mem_image_of_mem _ hz },
{ assume hb,
rcases (mem_image _ _ _ ).1 hb with ⟨y, ⟨hy, hy'⟩⟩,
rw [← hy', ← inf_edist_image h],
exact mem_image_of_mem _ (mem_image_of_mem _ hy) }}
end
/-- The Hausdorff distance is controlled by the diameter of the union -/
lemma Hausdorff_edist_le_ediam (hs : s ≠ ∅) (ht : t ≠ ∅) : Hausdorff_edist s t ≤ diam (s ∪ t) :=
begin
rcases ne_empty_iff_exists_mem.1 hs with ⟨x, xs⟩,
rcases ne_empty_iff_exists_mem.1 ht with ⟨y, yt⟩,
refine Hausdorff_edist_le_of_mem_edist _ _,
{ exact λz hz, ⟨y, yt, edist_le_diam_of_mem (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ },
{ exact λz hz, ⟨x, xs, edist_le_diam_of_mem (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ }
end
/-- The Hausdorff distance satisfies the triangular inequality -/
lemma Hausdorff_edist_triangle : Hausdorff_edist s u ≤ Hausdorff_edist s t + Hausdorff_edist t u :=
begin
rw Hausdorff_edist_def,
simp only [and_imp, set.mem_image, lattice.Sup_le_iff, exists_imp_distrib,
lattice.sup_le_iff, -mem_image, set.ball_image_iff],
split,
show ∀x ∈ s, inf_edist x u ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xs, calc
inf_edist x u ≤ inf_edist x t + Hausdorff_edist t u : inf_edist_le_inf_edist_add_Hausdorff_edist
... ≤ Hausdorff_edist s t + Hausdorff_edist t u :
add_le_add_right' (inf_edist_le_Hausdorff_edist_of_mem xs),
show ∀x ∈ u, inf_edist x s ≤ Hausdorff_edist s t + Hausdorff_edist t u, from λx xu, calc
inf_edist x s ≤ inf_edist x t + Hausdorff_edist t s : inf_edist_le_inf_edist_add_Hausdorff_edist
... ≤ Hausdorff_edist u t + Hausdorff_edist t s :
add_le_add_right' (inf_edist_le_Hausdorff_edist_of_mem xu)
... = Hausdorff_edist s t + Hausdorff_edist t u : by simp [Hausdorff_edist_comm, add_comm]
end
/-- The Hausdorff edistance between a set and its closure vanishes -/
@[simp] lemma Hausdorff_edist_self_closure : Hausdorff_edist s (closure s) = 0 :=
begin
erw ← le_bot_iff,
simp only [Hausdorff_edist, inf_edist_closure, -le_zero_iff_eq, and_imp,
set.mem_image, lattice.Sup_le_iff, exists_imp_distrib, lattice.sup_le_iff,
set.ball_image_iff, ennreal.bot_eq_zero, -mem_image],
simp only [inf_edist_zero_of_mem, mem_closure_iff_inf_edist_zero, le_refl, and_self,
forall_true_iff] {contextual := tt}
end
/-- Replacing a set by its closure does not change the Hausdorff edistance. -/
@[simp] lemma Hausdorff_edist_closure₁ : Hausdorff_edist (closure s) t = Hausdorff_edist s t :=
begin
refine le_antisymm _ _,
{ calc _ ≤ Hausdorff_edist (closure s) s + Hausdorff_edist s t : Hausdorff_edist_triangle
... = Hausdorff_edist s t : by simp [Hausdorff_edist_comm] },
{ calc _ ≤ Hausdorff_edist s (closure s) + Hausdorff_edist (closure s) t : Hausdorff_edist_triangle
... = Hausdorff_edist (closure s) t : by simp }
end
/-- Replacing a set by its closure does not change the Hausdorff edistance. -/
@[simp] lemma Hausdorff_edist_closure₂ : Hausdorff_edist s (closure t) = Hausdorff_edist s t :=
by simp [@Hausdorff_edist_comm _ _ s _]
/-- The Hausdorff edistance between sets or their closures is the same -/
@[simp] lemma Hausdorff_edist_closure : Hausdorff_edist (closure s) (closure t) = Hausdorff_edist s t :=
by simp
/-- Two sets are at zero Hausdorff edistance if and only if they have the same closure -/
lemma Hausdorff_edist_zero_iff_closure_eq_closure : Hausdorff_edist s t = 0 ↔ closure s = closure t :=
⟨begin
assume h,
refine subset.antisymm _ _,
{ have : s ⊆ closure t := λx xs, mem_closure_iff_inf_edist_zero.2 $ begin
erw ← le_bot_iff,
have := @inf_edist_le_Hausdorff_edist_of_mem _ _ _ _ t xs,
rwa h at this,
end,
by rw ← @closure_closure _ _ t; exact closure_mono this },
{ have : t ⊆ closure s := λx xt, mem_closure_iff_inf_edist_zero.2 $ begin
erw ← le_bot_iff,
have := @inf_edist_le_Hausdorff_edist_of_mem _ _ _ _ s xt,
rw Hausdorff_edist_comm at h,
rwa h at this,
end,
by rw ← @closure_closure _ _ s; exact closure_mono this }
end,
λh, by rw [← Hausdorff_edist_closure, h, Hausdorff_edist_self]⟩
/-- Two closed sets are at zero Hausdorff edistance if and only if they coincide -/
lemma Hausdorff_edist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t) :
Hausdorff_edist s t = 0 ↔ s = t :=
by rw [Hausdorff_edist_zero_iff_closure_eq_closure, closure_eq_iff_is_closed.2 hs,
closure_eq_iff_is_closed.2 ht]
/-- The Haudorff edistance to the empty set is infinite -/
lemma Hausdorff_edist_empty (ne : s ≠ ∅) : Hausdorff_edist s ∅ = ∞ :=
begin
rcases exists_mem_of_ne_empty ne with ⟨x, xs⟩,
have : inf_edist x ∅ ≤ Hausdorff_edist s ∅ := inf_edist_le_Hausdorff_edist_of_mem xs,
simpa using this,
end
/-- If a set is at finite Hausdorff edistance of a nonempty set, it is nonempty -/
lemma ne_empty_of_Hausdorff_edist_ne_top (hs : s ≠ ∅) (fin : Hausdorff_edist s t ≠ ⊤) : t ≠ ∅ :=
begin
by_contradiction h,
simp only [not_not, ne.def] at h,
rw [h, Hausdorff_edist_empty hs] at fin,
simpa using fin
end
end Hausdorff_edist -- section
end emetric --namespace
/-Now, we turn to the same notions in metric spaces. To avoid the difficulties related to
Inf and Sup on ℝ (which is only conditionnally complete), we use the notions in ennreal formulated
in terms of the edistance, and coerce them to ℝ. Then their properties follow readily from the
corresponding properties in ennreal, modulo some tedious rewriting of inequalities from one to the
other -/
namespace metric
section
variables {α : Type u} {β : Type v} [metric_space α] [metric_space β] {s t u : set α} {x y : α} {Φ : α → β}
open emetric
/-- The minimal distance of a point to a set -/
def inf_dist (x : α) (s : set α) : ℝ := ennreal.to_real (inf_edist x s)
/-- the minimal distance is always nonnegative -/
lemma inf_dist_nonneg : 0 ≤ inf_dist x s := by simp [inf_dist]
/-- the minimal distance to the empty set is 0 (if you want to have the more reasonable
value ∞ instead, use `inf_edist`, which takes values in ennreal) -/
@[simp] lemma inf_dist_empty : inf_dist x ∅ = 0 :=
by simp [inf_dist]
/-- In a metric space, the minimal edistance to a nonempty set is finite -/
lemma inf_edist_ne_top (h : s ≠ ∅) : inf_edist x s ≠ ⊤ :=
begin
rcases exists_mem_of_ne_empty h with ⟨y, hy⟩,
apply lt_top_iff_ne_top.1,
calc inf_edist x s ≤ edist x y : inf_edist_le_edist_of_mem hy
... < ⊤ : lt_top_iff_ne_top.2 (edist_ne_top _ _)
end
/-- The minimal distance of a point to a set containing it vanishes -/
lemma inf_dist_zero_of_mem (h : x ∈ s) : inf_dist x s = 0 :=
by simp [inf_edist_zero_of_mem h, inf_dist]
/-- The minimal distance to a singleton is the distance to the unique point in this singleton -/
@[simp] lemma inf_dist_singleton : inf_dist x {y} = dist x y :=
by simp [inf_dist, inf_edist, dist_edist]
/-- The minimal distance to a set is bounded by the distance to any point in this set -/
lemma inf_dist_le_dist_of_mem (h : y ∈ s) : inf_dist x s ≤ dist x y :=
begin
rw [dist_edist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top (ne_empty_of_mem h)) (edist_ne_top _ _)],
exact inf_edist_le_edist_of_mem h
end
/-- The minimal distance is monotonous with respect to inclusion -/
lemma inf_dist_le_inf_dist_of_subset (h : s ⊆ t) (hs : s ≠ ∅) :
inf_dist x t ≤ inf_dist x s :=
begin
rcases ne_empty_iff_exists_mem.1 hs with ⟨y, hy⟩,
have ht : t ≠ ∅ := ne_empty_of_mem (h hy),
rw [inf_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) (inf_edist_ne_top hs)],
exact inf_edist_le_inf_edist_of_subset h
end
/-- If the minimal distance to a set is `<r`, there exists a point in this set at distance `<r` -/
lemma exists_dist_lt_of_inf_dist_lt {r : real} (h : inf_dist x s < r) (hs : s ≠ ∅) :
∃y∈s, dist x y < r :=
begin
have rpos : 0 < r := lt_of_le_of_lt inf_dist_nonneg h,
have : inf_edist x s < ennreal.of_real r,
{ rwa [inf_dist, ← ennreal.to_real_of_real (le_of_lt rpos), ennreal.to_real_lt_to_real (inf_edist_ne_top hs)] at h,
simp },
rcases exists_edist_lt_of_inf_edist_lt this with ⟨y, ys, hy⟩,
rw [edist_dist, ennreal.of_real_lt_of_real_iff rpos] at hy,
exact ⟨y, ys, hy⟩,
end
/-- The minimal distance from `x` to `s` is bounded by the distance from `y` to `s`, modulo
the distance between `x` and `y` -/
lemma inf_dist_le_inf_dist_add_dist : inf_dist x s ≤ inf_dist y s + dist x y :=
begin
by_cases hs : s = ∅,
{ by simp [hs, dist_nonneg] },
{ rw [inf_dist, inf_dist, dist_edist, ← ennreal.to_real_add (inf_edist_ne_top hs) (edist_ne_top _ _),
ennreal.to_real_le_to_real (inf_edist_ne_top hs)],
{ apply inf_edist_le_inf_edist_add_edist },
{ simp [ennreal.add_eq_top, inf_edist_ne_top hs, edist_ne_top] }}
end
variable (s)
/-- The minimal distance to a set is Lipschitz in point with constant 1 -/
lemma lipschitz_inf_dist_pt : lipschitz_with 1 (λx, inf_dist x s) :=
lipschitz_with.one_of_le_add $ λ x y, inf_dist_le_inf_dist_add_dist
/-- The minimal distance to a set is uniformly continuous in point -/
lemma uniform_continuous_inf_dist_pt :
uniform_continuous (λx, inf_dist x s) :=
(lipschitz_inf_dist_pt s).to_uniform_continuous
/-- The minimal distance to a set is continuous in point -/
lemma continuous_inf_dist_pt : continuous (λx, inf_dist x s) :=
(uniform_continuous_inf_dist_pt s).continuous
variable {s}
/-- The minimal distance to a set and its closure coincide -/
lemma inf_dist_eq_closure : inf_dist x (closure s) = inf_dist x s :=
by simp [inf_dist, inf_edist_closure]
/-- A point belongs to the closure of `s` iff its infimum distance to this set vanishes -/
lemma mem_closure_iff_inf_dist_zero (h : s ≠ ∅) : x ∈ closure s ↔ inf_dist x s = 0 :=
by simp [mem_closure_iff_inf_edist_zero, inf_dist, ennreal.to_real_eq_zero_iff, inf_edist_ne_top h]
/-- Given a closed set `s`, a point belongs to `s` iff its infimum distance to this set vanishes -/
lemma mem_iff_inf_dist_zero_of_closed (h : is_closed s) (hs : s ≠ ∅) :
x ∈ s ↔ inf_dist x s = 0 :=
begin
have := @mem_closure_iff_inf_dist_zero _ _ s x hs,
rwa closure_eq_iff_is_closed.2 h at this
end
/-- The infimum distance is invariant under isometries -/
lemma inf_dist_image (hΦ : isometry Φ) :
inf_dist (Φ x) (Φ '' t) = inf_dist x t :=
by simp [inf_dist, inf_edist_image hΦ]
/-- The Hausdorff distance between two sets is the smallest nonnegative `r` such that each set is
included in the `r`-neighborhood of the other. If there is no such `r`, it is defined to
be `0`, arbitrarily -/
def Hausdorff_dist (s t : set α) : ℝ := ennreal.to_real (Hausdorff_edist s t)
/-- The Hausdorff distance is nonnegative -/
lemma Hausdorff_dist_nonneg : 0 ≤ Hausdorff_dist s t :=
by simp [Hausdorff_dist]
/-- If two sets are nonempty and bounded in a metric space, they are at finite Hausdorff edistance -/
lemma Hausdorff_edist_ne_top_of_ne_empty_of_bounded (hs : s ≠ ∅) (ht : t ≠ ∅)
(bs : bounded s) (bt : bounded t) : Hausdorff_edist s t ≠ ⊤ :=
begin
rcases ne_empty_iff_exists_mem.1 hs with ⟨cs, hcs⟩,
rcases ne_empty_iff_exists_mem.1 ht with ⟨ct, hct⟩,
rcases (bounded_iff_subset_ball ct).1 bs with ⟨rs, hrs⟩,
rcases (bounded_iff_subset_ball cs).1 bt with ⟨rt, hrt⟩,
have : Hausdorff_edist s t ≤ ennreal.of_real (max rs rt),
{ apply Hausdorff_edist_le_of_mem_edist,
{ assume x xs,
existsi [ct, hct],
have : dist x ct ≤ max rs rt := le_trans (hrs xs) (le_max_left _ _),
rwa [edist_dist, ennreal.of_real_le_of_real_iff],
exact le_trans dist_nonneg this },
{ assume x xt,
existsi [cs, hcs],
have : dist x cs ≤ max rs rt := le_trans (hrt xt) (le_max_right _ _),
rwa [edist_dist, ennreal.of_real_le_of_real_iff],
exact le_trans dist_nonneg this }},
exact ennreal.lt_top_iff_ne_top.1 (lt_of_le_of_lt this (by simp [lt_top_iff_ne_top]))
end
/-- The Hausdorff distance between a set and itself is zero -/
@[simp] lemma Hausdorff_dist_self_zero : Hausdorff_dist s s = 0 :=
by simp [Hausdorff_dist]
/-- The Hausdorff distance from `s` to `t` and from `t` to `s` coincide -/
lemma Hausdorff_dist_comm : Hausdorff_dist s t = Hausdorff_dist t s :=
by simp [Hausdorff_dist, Hausdorff_edist_comm]
/-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable
value ∞ instead, use `Hausdorff_edist`, which takes values in ennreal) -/
@[simp] lemma Hausdorff_dist_empty : Hausdorff_dist s ∅ = 0 :=
begin
by_cases h : s = ∅,
{ simp [h] },
{ simp [Hausdorff_dist, Hausdorff_edist_empty h] }
end
/-- The Hausdorff distance to the empty set vanishes (if you want to have the more reasonable
value ∞ instead, use `Hausdorff_edist`, which takes values in ennreal) -/
@[simp] lemma Hausdorff_dist_empty' : Hausdorff_dist ∅ s = 0 :=
by simp [Hausdorff_dist_comm]
/-- Bounding the Hausdorff distance by bounding the distance of any point
in each set to the other set -/
lemma Hausdorff_dist_le_of_inf_dist {r : ℝ} (hr : r ≥ 0)
(H1 : ∀x ∈ s, inf_dist x t ≤ r) (H2 : ∀x ∈ t, inf_dist x s ≤ r) :
Hausdorff_dist s t ≤ r :=
begin
by_cases h : (Hausdorff_edist s t = ⊤) ∨ (s = ∅) ∨ (t = ∅),
{ rcases h with h1 | h2 | h3,
{ simpa [Hausdorff_dist, h1] },
{ simpa [h2] },
{ simpa [h3] }},
{ simp only [not_or_distrib] at h,
have : Hausdorff_edist s t ≤ ennreal.of_real r,
{ apply Hausdorff_edist_le_of_inf_edist _ _,
{ assume x hx,
have I := H1 x hx,
rwa [inf_dist, ← ennreal.to_real_of_real hr,
ennreal.to_real_le_to_real (inf_edist_ne_top h.2.2) ennreal.of_real_ne_top] at I },
{ assume x hx,
have I := H2 x hx,
rwa [inf_dist, ← ennreal.to_real_of_real hr,
ennreal.to_real_le_to_real (inf_edist_ne_top h.2.1) ennreal.of_real_ne_top] at I }},
rwa [Hausdorff_dist, ← ennreal.to_real_of_real hr,
ennreal.to_real_le_to_real h.1 ennreal.of_real_ne_top] }
end
/-- Bounding the Hausdorff distance by exhibiting, for any point in each set,
another point in the other set at controlled distance -/
lemma Hausdorff_dist_le_of_mem_dist {r : ℝ} (hr : 0 ≤ r)
(H1 : ∀x ∈ s, ∃y ∈ t, dist x y ≤ r) (H2 : ∀x ∈ t, ∃y ∈ s, dist x y ≤ r) :
Hausdorff_dist s t ≤ r :=
begin
apply Hausdorff_dist_le_of_inf_dist hr,
{ assume x xs,
rcases H1 x xs with ⟨y, yt, hy⟩,
exact le_trans (inf_dist_le_dist_of_mem yt) hy },
{ assume x xt,
rcases H2 x xt with ⟨y, ys, hy⟩,
exact le_trans (inf_dist_le_dist_of_mem ys) hy }
end
/-- The Hausdorff distance is controlled by the diameter of the union -/
lemma Hausdorff_dist_le_diam (hs : s ≠ ∅) (bs : bounded s) (ht : t ≠ ∅) (bt : bounded t) :
Hausdorff_dist s t ≤ diam (s ∪ t) :=
begin
rcases ne_empty_iff_exists_mem.1 hs with ⟨x, xs⟩,
rcases ne_empty_iff_exists_mem.1 ht with ⟨y, yt⟩,
refine Hausdorff_dist_le_of_mem_dist diam_nonneg _ _,
{ exact λz hz, ⟨y, yt, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_left _ _ hz) (subset_union_right _ _ yt)⟩ },
{ exact λz hz, ⟨x, xs, dist_le_diam_of_mem (bounded_union.2 ⟨bs, bt⟩) (subset_union_right _ _ hz) (subset_union_left _ _ xs)⟩ }
end
/-- The distance to a set is controlled by the Hausdorff distance -/
lemma inf_dist_le_Hausdorff_dist_of_mem (hx : x ∈ s) (fin : Hausdorff_edist s t ≠ ⊤) :
inf_dist x t ≤ Hausdorff_dist s t :=
begin
have ht : t ≠ ∅ := ne_empty_of_Hausdorff_edist_ne_top (ne_empty_of_mem hx) fin,
rw [Hausdorff_dist, inf_dist, ennreal.to_real_le_to_real (inf_edist_ne_top ht) fin],
exact inf_edist_le_Hausdorff_edist_of_mem hx
end
/-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance
`<r` of a point in the other set -/
lemma exists_dist_lt_of_Hausdorff_dist_lt {r : ℝ} (h : x ∈ s) (H : Hausdorff_dist s t < r)
(fin : Hausdorff_edist s t ≠ ⊤) : ∃y∈t, dist x y < r :=
begin
have r0 : 0 < r := lt_of_le_of_lt (Hausdorff_dist_nonneg) H,
have : Hausdorff_edist s t < ennreal.of_real r,
by rwa [Hausdorff_dist, ← ennreal.to_real_of_real (le_of_lt r0),
ennreal.to_real_lt_to_real fin (ennreal.of_real_ne_top)] at H,
rcases exists_edist_lt_of_Hausdorff_edist_lt h this with ⟨y, hy, yr⟩,
rw [edist_dist, ennreal.of_real_lt_of_real_iff r0] at yr,
exact ⟨y, hy, yr⟩
end
/-- If the Hausdorff distance is `<r`, then any point in one of the sets is at distance
`<r` of a point in the other set -/
lemma exists_dist_lt_of_Hausdorff_dist_lt' {r : ℝ} (h : y ∈ t) (H : Hausdorff_dist s t < r)
(fin : Hausdorff_edist s t ≠ ⊤) : ∃x∈s, dist x y < r :=
begin
rw Hausdorff_dist_comm at H,
rw Hausdorff_edist_comm at fin,
simpa [dist_comm] using exists_dist_lt_of_Hausdorff_dist_lt h H fin
end
/-- The infimum distance to `s` and `t` are the same, up to the Hausdorff distance
between `s` and `t` -/
lemma inf_dist_le_inf_dist_add_Hausdorff_dist (fin : Hausdorff_edist s t ≠ ⊤) :
inf_dist x t ≤ inf_dist x s + Hausdorff_dist s t :=
begin
by_cases (s = ∅) ∨ (t = ∅),
{ rcases h with h1 |h2,
{ have : t = ∅,
{ by_contradiction ht,
rw Hausdorff_edist_comm at fin,
exact ne_empty_of_Hausdorff_edist_ne_top ht fin h1 },
simp [‹s = ∅›, ‹t = ∅›] },
{ have : s = ∅,
{ by_contradiction hs,
exact ne_empty_of_Hausdorff_edist_ne_top hs fin h2 },
simp [‹s = ∅›, ‹t = ∅›] }},
{ rw not_or_distrib at h,
rw [inf_dist, inf_dist, Hausdorff_dist, ← ennreal.to_real_add (inf_edist_ne_top h.1) fin,
ennreal.to_real_le_to_real (inf_edist_ne_top h.2)],
{ exact inf_edist_le_inf_edist_add_Hausdorff_edist },
{ simp [ennreal.add_eq_top, not_or_distrib, fin, inf_edist_ne_top h.1] }}
end
/-- The Hausdorff distance is invariant under isometries -/
lemma Hausdorff_dist_image (h : isometry Φ) :
Hausdorff_dist (Φ '' s) (Φ '' t) = Hausdorff_dist s t :=
by simp [Hausdorff_dist, Hausdorff_edist_image h]
/-- The Hausdorff distance satisfies the triangular inequality -/
lemma Hausdorff_dist_triangle (fin : Hausdorff_edist s t ≠ ⊤) :
Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u :=
begin
by_cases Hausdorff_edist s u = ⊤,
{ calc Hausdorff_dist s u = 0 + 0 : by simp [Hausdorff_dist, h]
... ≤ Hausdorff_dist s t + Hausdorff_dist t u :
add_le_add (Hausdorff_dist_nonneg) (Hausdorff_dist_nonneg) },
{ have Dtu : Hausdorff_edist t u < ⊤ := calc
Hausdorff_edist t u ≤ Hausdorff_edist t s + Hausdorff_edist s u : Hausdorff_edist_triangle
... = Hausdorff_edist s t + Hausdorff_edist s u : by simp [Hausdorff_edist_comm]
... < ⊤ : by simp [ennreal.add_lt_top]; simp [ennreal.lt_top_iff_ne_top, h, fin],
rw [Hausdorff_dist, Hausdorff_dist, Hausdorff_dist,
← ennreal.to_real_add fin (lt_top_iff_ne_top.1 Dtu), ennreal.to_real_le_to_real h],
{ exact Hausdorff_edist_triangle },
{ simp [ennreal.add_eq_top, lt_top_iff_ne_top.1 Dtu, fin] }}
end
/-- The Hausdorff distance satisfies the triangular inequality -/
lemma Hausdorff_dist_triangle' (fin : Hausdorff_edist t u ≠ ⊤) :
Hausdorff_dist s u ≤ Hausdorff_dist s t + Hausdorff_dist t u :=
begin
rw Hausdorff_edist_comm at fin,
have I : Hausdorff_dist u s ≤ Hausdorff_dist u t + Hausdorff_dist t s := Hausdorff_dist_triangle fin,
simpa [add_comm, Hausdorff_dist_comm] using I
end
/-- The Hausdorff distance between a set and its closure vanish -/
@[simp] lemma Hausdorff_dist_self_closure : Hausdorff_dist s (closure s) = 0 :=
by simp [Hausdorff_dist]
/-- Replacing a set by its closure does not change the Hausdorff distance. -/
@[simp] lemma Hausdorff_dist_closure₁ : Hausdorff_dist (closure s) t = Hausdorff_dist s t :=
by simp [Hausdorff_dist]
/-- Replacing a set by its closure does not change the Hausdorff distance. -/
@[simp] lemma Hausdorff_dist_closure₂ : Hausdorff_dist s (closure t) = Hausdorff_dist s t :=
by simp [Hausdorff_dist]
/-- The Hausdorff distance between two sets and their closures coincide -/
@[simp] lemma Hausdorff_dist_closure : Hausdorff_dist (closure s) (closure t) = Hausdorff_dist s t :=
by simp [Hausdorff_dist]
/-- Two sets are at zero Hausdorff distance if and only if they have the same closures -/
lemma Hausdorff_dist_zero_iff_closure_eq_closure (fin : Hausdorff_edist s t ≠ ⊤) :
Hausdorff_dist s t = 0 ↔ closure s = closure t :=
by simp [Hausdorff_edist_zero_iff_closure_eq_closure.symm, Hausdorff_dist,
ennreal.to_real_eq_zero_iff, fin]
/-- Two closed sets are at zero Hausdorff distance if and only if they coincide -/
lemma Hausdorff_dist_zero_iff_eq_of_closed (hs : is_closed s) (ht : is_closed t)
(fin : Hausdorff_edist s t ≠ ⊤) : Hausdorff_dist s t = 0 ↔ s = t :=
by simp [(Hausdorff_edist_zero_iff_eq_of_closed hs ht).symm, Hausdorff_dist,
ennreal.to_real_eq_zero_iff, fin]
end --section
end metric --namespace
|
66bfff5be64c5d72b81a25354b2cb80aef950bef
|
08a8ee10652ba4f8592710ceb654b37e951d9082
|
/src/hott/types/pi.lean
|
b33e82d9d4c5ceee333a4a2ae3cc57a7822c87a4
|
[
"Apache-2.0"
] |
permissive
|
felixwellen/hott3
|
e9f299c84d30a782a741c40d38741ec024d391fb
|
8ac87a2699ab94c23ea7984b4a5fbd5a7052575c
|
refs/heads/master
| 1,619,972,899,098
| 1,509,047,351,000
| 1,518,040,986,000
| 120,676,559
| 0
| 0
| null | 1,518,040,503,000
| 1,518,040,503,000
| null |
UTF-8
|
Lean
| false
| false
| 14,945
|
lean
|
/-
Copyright (c) 2014-15 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Partially ported from Coq HoTT
Theorems about pi-types (dependent function spaces)
-/
import .sigma hott.arity hott.cubical.square
universe u
hott_theory
namespace hott
open hott.eq hott.equiv hott.is_equiv hott.funext hott.sigma hott.is_trunc unit
namespace pi
variables {A : Type _} {A' : Type _} {B : A → Type _} {B' : A' → Type _} {C : Πa, B a → Type _}
{D : Πa b, C a b → Type _}
{a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {f g : Πa, B a}
/- Paths -/
/-
Paths [p : f ≈ g] in a function type [Πx:X, P x] are equivalent to functions taking values
in path types, [H : Πx:X, f x ≈ g x], or concisely, [H : f ~ g].
This equivalence, however, is just the combination of [apd10] and function extensionality
[funext], and as such, [eq_of_homotopy]
Now we show how these things compute.
-/
@[hott] def apd10_eq_of_homotopy (h : f ~ g) : apd10 (eq_of_homotopy h) ~ h :=
apd10 (right_inv apd10 h)
@[hott] def eq_of_homotopy_eta (p : f = g) : eq_of_homotopy (apd10 p) = p :=
left_inv apd10 p
@[hott] def eq_of_homotopy_idp (f : Πa, B a) : eq_of_homotopy (λx : A, refl (f x)) = refl f :=
eq_of_homotopy_eta (refl f)
/- homotopy.symm is an equivalence -/
@[hott] def is_equiv_homotopy_symm : is_equiv (homotopy.symm : f ~ g → g ~ f) :=
begin
apply adjointify homotopy.symm homotopy.symm,
{ intro p, apply eq_of_homotopy, intro a, apply eq.inv_inv },
{ intro p, apply eq_of_homotopy, intro a, apply eq.inv_inv }
end
/-
The identification of the path space of a dependent function space,
up to equivalence, is of course just funext.
-/
@[hott] def eq_equiv_homotopy (f g : Πx, B x) : (f = g) ≃ (f ~ g) :=
equiv.mk apd10 (by apply_instance)
@[hott] def pi_eq_equiv (f g : Πx, B x) : (f = g) ≃ (f ~ g) := eq_equiv_homotopy f g
@[hott,instance] def is_equiv_eq_of_homotopy (f g : Πx, B x)
: is_equiv (eq_of_homotopy : f ~ g → f = g) :=
is_equiv_inv _
@[hott] def homotopy_equiv_eq (f g : Πx, B x) : (f ~ g) ≃ (f = g) :=
equiv.mk eq_of_homotopy (by apply_instance)
/- Transport -/
@[hott] def pi_transport (p : a = a') (f : Π(b : B a), C a b)
: (transport (λa, Π(b : B a), C a b) p f) ~ (λb, tr_inv_tr p b ▸ (p ▸D f (p⁻¹ ▸ b))) :=
by induction p; reflexivity
/- A special case of [transport_pi] where the type [B] does not depend on [A],
and so it is just a fixed type [B]. -/
@[hott] def pi_transport_constant {C : A → A' → Type _} (p : a = a') (f : Π(b : A'), C a b) (b : A')
: (transport _ p f) b = @transport A (λa, C a b) _ _ p (f b) := --fix
by induction p; reflexivity
/- Pathovers -/
@[hott] def pi_pathover' {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'}
(r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[apd011 C p q; λX, X] g b') : f =[p; λa, Πb, C a b] g :=
begin
induction p, apply pathover_idp_of_eq,
apply eq_of_homotopy, intro b,
let z := eq_of_pathover_idp (r b b idpo), exact z --fix
end
@[hott] def pi_pathover_left' {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'}
(r : Π(b : B a), f b =[apd011 C p (pathover_tr _ _); λX, X] g (p ▸ b)) : f =[p; λa, Πb, C a b] g :=
begin
induction p, apply pathover_idp_of_eq,
apply eq_of_homotopy, hintro b,
let z := eq_of_pathover_idp (r b), exact z --fix
end
@[hott] def pi_pathover_right' {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'}
(r : Π(b' : B a'), f (p⁻¹ ▸ b') =[apd011 C p (tr_pathover _ _); λX, X] g b') : f =[p; λa, Πb, C a b] g :=
begin
induction p, apply pathover_idp_of_eq,
apply eq_of_homotopy, hintro b,
dsimp [apd011, tr_pathover] at r,
let z := eq_of_pathover_idp (r b), exact z --fix
end
@[hott] def pi_pathover_constant {C : A → A' → Type _} {f : Π(b : A'), C a b}
{g : Π(b : A'), C a' b} {p : a = a'}
(r : Π(b : A'), f b =[p; λa, C a b] g b) : f =[p; λa, Πb, C a b] g :=
begin
induction p, apply pathover_idp_of_eq,
apply eq_of_homotopy, hintro b,
let z := eq_of_pathover_idp (r b), exact z --fix
end
-- a version where C is uncurried, but where the conclusion of r is still a proper pathover
-- instead of a heterogenous equality
@[hott] def pi_pathover {C : (Σa, B a) → Type _} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩}
{p : a = a'} (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[dpair_eq_dpair p q] g b')
: f =[p; λa, Πb, C ⟨a, b⟩] g :=
begin
induction p, apply pathover_idp_of_eq,
apply eq_of_homotopy, hintro b,
apply (@eq_of_pathover_idp _ C), exact (r b b (pathover.idpatho b)),
end
@[hott] def pi_pathover_left {C : (Σa, B a) → Type _} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩}
{p : a = a'} (r : Π(b : B a), f b =[dpair_eq_dpair p (pathover_tr _ _)] g (p ▸ b))
: f =[p; λa, Πb, C ⟨a, b⟩] g :=
begin
induction p, apply pathover_idp_of_eq,
apply eq_of_homotopy, hintro b,
apply eq_of_pathover_idp, exact pathover_ap _ _ (r b)
end
@[hott] def pi_pathover_right {C : (Σa, B a) → Type _} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩}
{p : a = a'} (r : Π(b' : B a'), f (p⁻¹ ▸ b') =[dpair_eq_dpair p (tr_pathover _ _)] g b')
: f =[p; λa, Πb, C ⟨a, b⟩] g :=
begin
induction p, apply pathover_idp_of_eq,
apply eq_of_homotopy, hintro b,
apply eq_of_pathover_idp, exact pathover_ap _ _ (r b)
end
/- Maps on paths -/
/- The action of maps given by lambda. -/
@[hott] def ap_lambdaD {C : A' → Type _} (p : a = a') (f : Πa b, C b) :
ap (λa b, f a b) p = eq_of_homotopy (λb, ap (λa, f a b) p) :=
begin
apply (eq.rec_on p),
apply inverse,
apply eq_of_homotopy_idp
end
/- Dependent paths -/
/- with more implicit arguments the conclusion of the following theorem is
(Π(b : B a), transportD B C p b (f b) = g (transport B p b)) ≃
(transport (λa, Π(b : B a), C a b) p f = g) -/
@[hott] def heq_piD (p : a = a') (f : Π(b : B a), C a b)
(g : Π(b' : B a'), C a' b') : (Π(b : B a), p ▸D (f b) = g (p ▸ b)) ≃ (p ▸ f = g) :=
eq.rec_on p (λg, homotopy_equiv_eq _ _) g
@[hott] def heq_pi {C : A → Type _} (p : a = a') (f : Π(b : B a), C a)
(g : Π(b' : B a'), C a') : (Π(b : B a), p ▸ (f b) = g (p ▸ b)) ≃ (p ▸ f = g) :=
eq.rec_on p (λg, homotopy_equiv_eq _ _) g
section
/- more implicit arguments:
(Π(b : B a), transport C (sigma_eq p idp) (f b) = g (p ▸ b)) ≃
(Π(b : B a), transportD B (λ(a : A) (b : B a), C ⟨a, b⟩) p b (f b) = g (transport B p b)) -/
@[hott] def heq_pi_sigma {C : (Σa, B a) → Type _} (p : a = a')
(f : Π(b : B a), C ⟨a, b⟩) (g : Π(b' : B a'), C ⟨a', b'⟩) :
(Π(b : B a), (dpair_eq_dpair p (pathover_tr p b)) ▸ (f b) = g (p ▸ b)) ≃
(Π(b : B a), transportD (λa b, C ⟨a, b⟩) p _ (f b) = g (p ▸ b)) :=
by induction p; refl
end
/- Functorial action -/
variables (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a')
/- The functoriality of [forall] is slightly subtle: it is contravariant in the domain type and covariant in the codomain, but the codomain is dependent on the domain. -/
@[hott] def pi_functor : (Π(a:A), B a) → (Π(a':A'), B' a') :=
λg a', f1 a' (g (f0 a'))
@[hott] def pi_functor_left (B : A → Type _) : (Π(a:A), B a) → (Π(a':A'), B (f0 a')) :=
pi_functor f0 (λa, id)
@[hott] def pi_functor_right {B' : A → Type _} (f1 : Π(a:A), B a → B' a)
: (Π(a:A), B a) → (Π(a:A), B' a) :=
pi_functor id f1
@[hott,hsimp] def pi_functor_eq (g : Πa, B a) (a' : A') : pi_functor f0 f1 g a' = f1 a' (g (f0 a')) :=
by refl
@[hott] def ap_pi_functor {g g' : Π(a:A), B a} (h : g ~ g')
: ap (pi_functor f0 f1) (eq_of_homotopy h)
= eq_of_homotopy (λ(a' : A'), (ap (f1 a') (h (f0 a')))) :=
begin
apply is_equiv_rect
(@apd10 A B g g') (λh, ap (pi_functor f0 f1) (eq_of_homotopy h) =
eq_of_homotopy (λa':A', (ap (f1 a') (h (f0 a'))))), intro p, clear h,
induction p,
refine (ap (ap (pi_functor f0 f1)) (eq_of_homotopy_idp g)) ⬝ _,
symmetry, apply eq_of_homotopy_idp
end
/- Equivalences -/
/-@[hott] def pi_equiv_pi (f0 : A' ≃ A) (f1 : Πa', (B (to_fun f0 a') ≃ B' a'))
: (Πa, B a) ≃ (Πa', B' a') :=
begin
fapply equiv.MK,
exact pi_functor f0 f1,
(pi_functor f0⁻¹ᶠ
(λ(a : A) (b' : B' (f0⁻¹ᶠ a)), transport B (right_inv f0 a) ((f1 (f0⁻¹ᶠ a))⁻¹ᶠ b')))
end-/
@[hott, instance] def is_equiv_pi_functor [H0 : is_equiv f0]
[H1 : Πa', is_equiv (f1 a')] : is_equiv (pi_functor f0 f1) :=
adjointify (pi_functor f0 f1) (pi_functor f0⁻¹ᶠ
(λ(a : A) (b' : B' (f0⁻¹ᶠ a)), transport B (right_inv f0 a) ((f1 (f0⁻¹ᶠ a))⁻¹ᶠ b')))
begin
intro h, apply eq_of_homotopy, intro a', dsimp,
rwr [adj f0 a', hott.eq.inverse (tr_compose B f0 (left_inv f0 a') _), fn_tr_eq_tr_fn _ f1 _, right_inv (f1 _)], --fix
apply apdt
end
begin
intro h, apply eq_of_homotopy, intro a, dsimp,
rwr [left_inv (f1 _)],
apply apdt
end
@[hott] def pi_equiv_pi_of_is_equiv [H : is_equiv f0]
[H1 : Πa', is_equiv (f1 a')] : (Πa, B a) ≃ (Πa', B' a') :=
equiv.mk (pi_functor f0 f1) (by apply_instance)
@[hott] def pi_equiv_pi (f0 : A' ≃ A) (f1 : Πa', (B (f0 a') ≃ B' a'))
: (Πa, B a) ≃ (Πa', B' a') :=
pi_equiv_pi_of_is_equiv f0 (λa', f1 a')
@[hott] def pi_equiv_pi_right {P Q : A → Type _} (g : Πa, P a ≃ Q a)
: (Πa, P a) ≃ (Πa, Q a) :=
pi_equiv_pi equiv.rfl g
/- Equivalence if one of the types is contractible -/
variable (B)
@[hott] def pi_equiv_of_is_contr_left [H : is_contr A]
: (Πa, B a) ≃ B (center A) :=
begin
fapply equiv.MK,
{ intro f, exact f (center A)},
{ intros b a, exact center_eq a ▸ b},
{ intro b, dsimp, rwr [prop_eq_of_is_contr (center_eq (center A)) idp]},
{ intro f, apply eq_of_homotopy, intro a, dsimp, induction (center_eq a),
refl }
end
@[hott] def pi_equiv_of_is_contr_right [H : Πa, is_contr (B a)]
: (Πa, B a) ≃ unit :=
begin
fapply equiv.MK,
{ intro f, exact star },
{ intros u a, exact center _ },
{ intro u, induction u, reflexivity },
{ intro f, apply eq_of_homotopy, intro a, apply is_prop.elim }
end
variable {B}
/- Interaction with other type constructors -/
-- most of these are in the file of the other type constructor
@[hott] def pi_empty_left (B : empty → Type _) : (Πx, B x) ≃ unit :=
begin
fapply equiv.MK,
{ intro f, exact star },
{ intros x y, exact empty.elim y },
{ intro x, induction x, reflexivity },
{ intro f, apply eq_of_homotopy, intro y, exact empty.elim y }
end
@[hott] def pi_unit_left (B : unit → Type _) : (Πx, B x) ≃ B star :=
pi_equiv_of_is_contr_left _
@[hott] def pi_bool_left (B : bool → Type _) : (Πx, B x) ≃ B ff × B tt :=
begin
fapply equiv.MK,
{ intro f, exact (f ff, f tt) },
{ intros x b, induction x, induction b, all_goals {assumption}},
{ intro x, induction x, reflexivity },
{ intro f, apply eq_of_homotopy, intro b, induction b, all_goals {reflexivity}},
end
/- Truncatedness: any dependent product of n-types is an n-type -/
@[hott, instance, priority 1520] theorem is_trunc_pi (B : A → Type _) (n : trunc_index)
[H : ∀a, is_trunc n (B a)] : is_trunc n (Πa, B a) :=
begin
induction n with n IH generalizing B H,
{ fapply is_contr.mk,
intro a, apply center,
intro f, apply eq_of_homotopy,
intro x, apply (center_eq (f x)) },
{ apply is_trunc_succ_intro, intros f g,
exact is_trunc_equiv_closed_rev n (eq_equiv_homotopy f g) (by apply_instance) }
end
@[hott] theorem is_trunc_pi_eq (n : trunc_index) (f g : Πa, B a)
[H : ∀a, is_trunc n (f a = g a)] : is_trunc n (f = g) :=
is_trunc_equiv_closed_rev n (eq_equiv_homotopy f g) (by apply_instance)
@[hott, instance] theorem is_trunc_not (n : trunc_index) (A : Type _) : is_trunc (n.+1) ¬A :=
by dsimp [not]; apply_instance
@[hott] theorem is_prop_pi_eq (a : A) : is_prop (Π(a' : A), a = a') :=
is_prop_of_imp_is_contr
( assume (f : Πa', a = a'),
have is_contr A, from is_contr.mk a f,
by apply_instance)
@[hott] theorem is_prop_neg (A : Type _) : is_prop (¬A) := by apply_instance
@[hott] theorem is_prop_ne {A : Type _} (a b : A) : is_prop (a ≠ b) := by apply_instance
@[hott] def is_contr_pi_of_neg {A : Type _} (B : A → Type _) (H : ¬ A) : is_contr (Πa, B a) :=
begin
apply is_contr.mk (λa, empty.elim (H a)), intro f, apply eq_of_homotopy, intro x, exact empty.elim (H x)
end
/- Symmetry of Π -/
@[hott] def pi_flip {P : A → A' → Type _} (f : Πa b, P a b) (b : A') (a : A) : P a b := f a b
@[hott, instance] def is_equiv_flip {P : A → A' → Type _}
: is_equiv (@pi_flip A A' P) :=
begin
fapply is_equiv.mk,
exact (@pi_flip _ _ (pi_flip P)),
all_goals {intro f; refl}
end
@[hott] def pi_comm_equiv {P : A → A' → Type _} : (Πa b, P a b) ≃ (Πb a, P a b) :=
equiv.mk (@pi_flip _ _ P) (by apply_instance)
/- Dependent functions are equivalent to nondependent functions into the total space together
with a homotopy -/
@[hott] def pi_equiv_arrow_sigma_right {A : Type _} {B : A → Type _} (f : Πa, B a) :
Σ(f : A → Σa, B a), sigma.fst ∘ f ~ id :=
⟨λa, ⟨a, f a⟩, λa, idp⟩
@[hott] def pi_equiv_arrow_sigma_left
(v : Σ(f : A → Σa, B a), sigma.fst ∘ f ~ id) (a : A) : B a :=
transport B (v.2 a) (v.1 a).2
open funext
@[hott] def pi_equiv_arrow_sigma : (Πa, B a) ≃ Σ(f : A → Σa, B a), sigma.fst ∘ f ~ id :=
begin
fapply equiv.MK,
{ exact pi_equiv_arrow_sigma_right },
{ exact pi_equiv_arrow_sigma_left },
{ intro v, induction v with f p, fapply sigma_eq,
{ apply eq_of_homotopy, intro a, fapply sigma_eq,
{ exact (p a)⁻¹ },
{ apply inverseo, apply pathover_tr }},
{ apply pi_pathover_constant, intro a, apply eq_pathover_constant_right,
refine ap_compose (λf : A → A, f a) _ _ ⬝ph _,
refine ap02 _ (compose_eq_of_homotopy (@sigma.fst A B) _) ⬝ph _,
refine ap_eq_apd10 _ _ ⬝ph _,
refine apd10 (right_inv apd10 _) a ⬝ph _,
refine sigma_eq_fst _ _ ⬝ph _, apply square_of_eq, exact (con.left_inv _)⁻¹ }},
{ intro a, reflexivity }
end
end pi
namespace pi
/- pointed pi types -/
open pointed
@[hott, instance] def pointed_pi {A : Type _} (P : A → Type _) [H : Πx, pointed (P x)]
: pointed (Πx, P x) :=
pointed.mk (λx, pt)
end pi
end hott
|
02292d4a8f4cac8a62651f6cef4f529cc5f7c2f6
|
31e8ce8c3f972f4102a087008fd33dee6f2d7dfe
|
/test.lean
|
b8ecc5eb23a7d6c453a931a9664bbf6607fa8f69
|
[
"MIT"
] |
permissive
|
sakas--/lean-tauto
|
6ca908abde99b252c9a3fdce5c0e98871ebbcc26
|
3cc5c1349f9204f3b798ea8cdb6e4f36ed2d1b25
|
refs/heads/master
| 1,610,549,743,092
| 1,488,258,185,000
| 1,488,258,185,000
| 76,671,935
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 2,771
|
lean
|
/- TODO : add some test from ILTP library
-/
import .tauto
open tauto
section test
variables {A B C D E F : Prop}
example : true :=
by tauto >> tactic.trace "test1 succeeded"
example : A → A :=
by tauto >> tactic.trace "test2 succeeded"
example : A ∧ B → B ∧ A :=
by tauto >> tactic.trace "test3 succeeded"
example : A ∧ B ↔ B ∧ A :=
by tauto >> tactic.trace "test4 succeeded"
example : A ∨ B → B ∨ A :=
by tauto >> tactic.trace "test5 succeeded"
example : A ∨ B ↔ B ∨ A :=
by tauto >> tactic.trace "test6 succeeded"
example : (A → B) → A → B :=
by tauto >> tactic.trace "test7 succeeded"
example : (A ↔ B) → A → B :=
by tauto >> tactic.trace "test8 succeeded"
example : (true → A) ↔ A :=
by tauto >> tactic.trace "test9 succeeded"
example : (((A → B) → A) → A) → (B → A) → (((A → B) → B) → A) :=
by tauto >> tactic.trace "test10 succeeded"
example : (A → B) ∨ (A → C) → A → B ∨ C :=
by tauto >> tactic.trace "test11 succeeded"
example : A ∧ B ∨ C ∧ D → (A ∨ C) ∧ (B ∨ C) :=
by tauto >> tactic.trace "test12 succeeded"
example : A → A → A → A → A → A → A → A → A → A :=
by tauto >> tactic.trace "test13 succeeded"
example : ¬ A → ¬ A :=
by tauto >> tactic.trace "test14 succeeded"
example : (¬ A ∧ ¬ B) ↔ ¬ (A ∨ B) :=
by tauto >> tactic.trace "test15 succeeded"
example : ¬ A ∨ ¬ B → ¬ (A ∧ B) :=
by tauto >> tactic.trace "test16 succeeded"
example : ¬ ¬ (¬ (A ∧ B) → ¬ A ∨ ¬ B) :=
by tauto >> tactic.trace "test17 succeeded"
example : ¬ ¬ (A ∨ ¬ A) :=
by tauto >> tactic.trace "test18 succeeded"
example : (A → ¬ ¬ B) → ¬ ¬ (A → B) :=
by tauto >> tactic.trace "test19 succeeded"
example : ¬ ¬ A ↔ ¬ ¬ ¬ ¬ A :=
by tauto >> tactic.trace "test20 succeeded"
example : (¬ ¬ A → A) → (¬ B → A) → (B → A) → A :=
by tauto >> tactic.trace "test21 succeeded"
example : ¬ ¬ ((A ∧ B → C) ↔ ((A → C) ∨ (B → C))) :=
by tauto >> tactic.trace "test22 succeeded"
example : (A ↔ B) ∧ (B ↔ C) ∧ (C ↔ D) ∧ (D ↔ E) → (E ↔ A) :=
by tauto >> tactic.trace "test23 succeeded"
example : A → ¬ ¬ ¬ ¬ ¬ ¬ ¬ ¬ ¬ ¬ A :=
by tauto >> tactic.trace "test24 succeeded"
example : (A → ¬ ¬ B) ∧ ¬ (A → B) ∧ (B → ¬ ¬ C) ∧ ¬ (B → C) → A :=
by tauto >> tactic.trace "test25 succeeded"
example : A ∨ B ∨ C → (A ∨ B ∨ C → D) → D :=
by tauto >> tactic.trace "test26 succeeded"
example : ¬ ¬ (((A → B) → A) → A) :=
by tauto >> tactic.trace "test27 succeeded"
example : (¬ A ↔ B) → (¬ (C ∨ E) ↔ D ∧ F) → (¬ (C ∨ A ∨ E) ↔ D ∧ B ∧ F) :=
by tauto >> tactic.trace "test28 succeeded"
end test
|
3c164379309363d3243fcc86891203ab9a9c69c4
|
b7f22e51856f4989b970961f794f1c435f9b8f78
|
/tests/lean/run/algebra1.lean
|
c26351671d604001f47c2607c3c3708d0ffc45af
|
[
"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
| 3,225
|
lean
|
import logic
namespace experiment
definition Type1 := Type.{1}
section
variable {A : Type}
variable f : A → A → A
variable one : A
variable inv : A → A
local infixl `*` := f
local postfix `^-1`:100 := inv
definition is_assoc := ∀ a b c, (a*b)*c = a*b*c
definition is_id := ∀ a, a*one = a
definition is_inv := ∀ a, a*a^-1 = one
end
namespace algebra
inductive mul_struct [class] (A : Type) : Type :=
mk : (A → A → A) → mul_struct A
inductive add_struct [class] (A : Type) : Type :=
mk : (A → A → A) → add_struct A
definition mul {A : Type} [s : mul_struct A] (a b : A)
:= mul_struct.rec (fun f, f) s a b
infixl `*` := mul
definition add {A : Type} [s : add_struct A] (a b : A)
:= add_struct.rec (fun f, f) s a b
infixl `+` := add
end algebra
open algebra
inductive nat : Type :=
| zero : nat
| succ : nat → nat
namespace nat
constant add : nat → nat → nat
constant mul : nat → nat → nat
definition is_mul_struct [instance] : algebra.mul_struct nat
:= algebra.mul_struct.mk mul
definition is_add_struct [instance] : algebra.add_struct nat
:= algebra.add_struct.mk add
definition to_nat (n : num) : nat
:= #experiment.algebra
num.rec nat.zero (λ n, pos_num.rec (succ zero) (λ n r, r + r) (λ n r, r + r + succ zero) n) n
end nat
namespace algebra
namespace semigroup
inductive semigroup_struct [class] (A : Type) : Type :=
mk : Π (mul : A → A → A), is_assoc mul → semigroup_struct A
definition mul {A : Type} (s : semigroup_struct A) (a b : A)
:= semigroup_struct.rec (fun f h, f) s a b
definition assoc {A : Type} (s : semigroup_struct A) : is_assoc (mul s)
:= semigroup_struct.rec (fun f h, h) s
definition is_mul_struct [instance] (A : Type) [s : semigroup_struct A] : mul_struct A
:= mul_struct.mk (mul s)
inductive semigroup : Type :=
mk : Π (A : Type), semigroup_struct A → semigroup
definition carrier [coercion] (g : semigroup)
:= semigroup.rec (fun c s, c) g
definition is_semigroup [instance] [g : semigroup] : semigroup_struct (carrier g)
:= semigroup.rec (fun c s, s) g
end semigroup
namespace monoid
check semigroup.mul
inductive monoid_struct [class] (A : Type) : Type :=
mk_monoid_struct : Π (mul : A → A → A) (id : A), is_assoc mul → is_id mul id → monoid_struct A
definition mul {A : Type} (s : monoid_struct A) (a b : A)
:= monoid_struct.rec (fun mul id a i, mul) s a b
definition assoc {A : Type} (s : monoid_struct A) : is_assoc (mul s)
:= monoid_struct.rec (fun mul id a i, a) s
open semigroup
definition is_semigroup_struct [instance] (A : Type) [s : monoid_struct A] : semigroup_struct A
:= semigroup_struct.mk (mul s) (assoc s)
inductive monoid : Type :=
mk_monoid : Π (A : Type), monoid_struct A → monoid
definition carrier [coercion] (m : monoid)
:= monoid.rec (fun c s, c) m
definition is_monoid [instance] (m : monoid) : monoid_struct (carrier m)
:= monoid.rec (fun c s, s) m
end monoid
end algebra
section
open algebra algebra.semigroup algebra.monoid
variable M : monoid
variables a b c : M
check a*b*c*a*b*c*a*b*a*b*c*a
check a*b
end
end experiment
|
ba84b1b81775c5ec3d4f60f495acb261ff434dbd
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/algebraic_geometry/Spec.lean
|
eff89cbd23173716bc3c10c51fe48ff61b2ed737
|
[
"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
| 15,761
|
lean
|
/-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Justus Springer
-/
import algebraic_geometry.locally_ringed_space
import algebraic_geometry.structure_sheaf
import ring_theory.localization.localization_localization
import topology.sheaves.sheaf_condition.sites
import topology.sheaves.functors
import algebra.module.localized_module
/-!
# $Spec$ as a functor to locally ringed spaces.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define the functor $Spec$ from commutative rings to locally ringed spaces.
## Implementation notes
We define $Spec$ in three consecutive steps, each with more structure than the last:
1. `Spec.to_Top`, valued in the category of topological spaces,
2. `Spec.to_SheafedSpace`, valued in the category of sheafed spaces and
3. `Spec.to_LocallyRingedSpace`, valued in the category of locally ringed spaces.
Additionally, we provide `Spec.to_PresheafedSpace` as a composition of `Spec.to_SheafedSpace` with
a forgetful functor.
## Related results
The adjunction `Γ ⊣ Spec` is constructed in `algebraic_geometry/Gamma_Spec_adjunction.lean`.
-/
noncomputable theory
universes u v
namespace algebraic_geometry
open opposite
open category_theory
open structure_sheaf Spec (structure_sheaf)
/--
The spectrum of a commutative ring, as a topological space.
-/
def Spec.Top_obj (R : CommRing) : Top := Top.of (prime_spectrum R)
/--
The induced map of a ring homomorphism on the ring spectra, as a morphism of topological spaces.
-/
def Spec.Top_map {R S : CommRing} (f : R ⟶ S) :
Spec.Top_obj S ⟶ Spec.Top_obj R :=
prime_spectrum.comap f
@[simp] lemma Spec.Top_map_id (R : CommRing) :
Spec.Top_map (𝟙 R) = 𝟙 (Spec.Top_obj R) :=
prime_spectrum.comap_id
lemma Spec.Top_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) :
Spec.Top_map (f ≫ g) = Spec.Top_map g ≫ Spec.Top_map f :=
prime_spectrum.comap_comp _ _
/--
The spectrum, as a contravariant functor from commutative rings to topological spaces.
-/
@[simps] def Spec.to_Top : CommRingᵒᵖ ⥤ Top :=
{ obj := λ R, Spec.Top_obj (unop R),
map := λ R S f, Spec.Top_map f.unop,
map_id' := λ R, by rw [unop_id, Spec.Top_map_id],
map_comp' := λ R S T f g, by rw [unop_comp, Spec.Top_map_comp] }
/--
The spectrum of a commutative ring, as a `SheafedSpace`.
-/
@[simps] def Spec.SheafedSpace_obj (R : CommRing) : SheafedSpace CommRing :=
{ carrier := Spec.Top_obj R,
presheaf := (structure_sheaf R).1,
is_sheaf := (structure_sheaf R).2 }
/--
The induced map of a ring homomorphism on the ring spectra, as a morphism of sheafed spaces.
-/
@[simps] def Spec.SheafedSpace_map {R S : CommRing.{u}} (f : R ⟶ S) :
Spec.SheafedSpace_obj S ⟶ Spec.SheafedSpace_obj R :=
{ base := Spec.Top_map f,
c :=
{ app := λ U, comap f (unop U) ((topological_space.opens.map (Spec.Top_map f)).obj (unop U))
(λ p, id),
naturality' := λ U V i, ring_hom.ext $ λ s, subtype.eq $ funext $ λ p, rfl } }
@[simp] lemma Spec.SheafedSpace_map_id {R : CommRing} :
Spec.SheafedSpace_map (𝟙 R) = 𝟙 (Spec.SheafedSpace_obj R) :=
PresheafedSpace.ext _ _ (Spec.Top_map_id R) $ nat_trans.ext _ _ $ funext $ λ U,
begin
dsimp,
erw [PresheafedSpace.id_c_app, comap_id], swap,
{ rw [Spec.Top_map_id, topological_space.opens.map_id_obj_unop] },
simpa [eq_to_hom_map],
end
lemma Spec.SheafedSpace_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) :
Spec.SheafedSpace_map (f ≫ g) = Spec.SheafedSpace_map g ≫ Spec.SheafedSpace_map f :=
PresheafedSpace.ext _ _ (Spec.Top_map_comp f g) $ nat_trans.ext _ _ $ funext $ λ U,
by { dsimp, rw category_theory.functor.map_id, rw category.comp_id, erw comap_comp f g, refl }
/--
Spec, as a contravariant functor from commutative rings to sheafed spaces.
-/
@[simps] def Spec.to_SheafedSpace : CommRingᵒᵖ ⥤ SheafedSpace CommRing :=
{ obj := λ R, Spec.SheafedSpace_obj (unop R),
map := λ R S f, Spec.SheafedSpace_map f.unop,
map_id' := λ R, by rw [unop_id, Spec.SheafedSpace_map_id],
map_comp' := λ R S T f g, by rw [unop_comp, Spec.SheafedSpace_map_comp] }
/--
Spec, as a contravariant functor from commutative rings to presheafed spaces.
-/
def Spec.to_PresheafedSpace : CommRingᵒᵖ ⥤ PresheafedSpace.{u} CommRing.{u} :=
Spec.to_SheafedSpace ⋙ SheafedSpace.forget_to_PresheafedSpace
@[simp] lemma Spec.to_PresheafedSpace_obj (R : CommRingᵒᵖ) :
Spec.to_PresheafedSpace.obj R = (Spec.SheafedSpace_obj (unop R)).to_PresheafedSpace := rfl
lemma Spec.to_PresheafedSpace_obj_op (R : CommRing) :
Spec.to_PresheafedSpace.obj (op R) = (Spec.SheafedSpace_obj R).to_PresheafedSpace := rfl
@[simp] lemma Spec.to_PresheafedSpace_map (R S : CommRingᵒᵖ) (f : R ⟶ S) :
Spec.to_PresheafedSpace.map f = Spec.SheafedSpace_map f.unop := rfl
lemma Spec.to_PresheafedSpace_map_op (R S : CommRing) (f : R ⟶ S) :
Spec.to_PresheafedSpace.map f.op = Spec.SheafedSpace_map f := rfl
lemma Spec.basic_open_hom_ext {X : RingedSpace} {R : CommRing} {α β : X ⟶ Spec.SheafedSpace_obj R}
(w : α.base = β.base) (h : ∀ r : R, let U := prime_spectrum.basic_open r in
(to_open R U ≫ α.c.app (op U)) ≫ X.presheaf.map (eq_to_hom (by rw w)) =
to_open R U ≫ β.c.app (op U)) : α = β :=
begin
ext1,
{ apply ((Top.sheaf.pushforward β.base).obj X.sheaf).hom_ext _
prime_spectrum.is_basis_basic_opens,
intro r,
apply (structure_sheaf.to_basic_open_epi R r).1,
simpa using h r },
exact w,
end
/--
The spectrum of a commutative ring, as a `LocallyRingedSpace`.
-/
@[simps] def Spec.LocallyRingedSpace_obj (R : CommRing) : LocallyRingedSpace :=
{ local_ring := λ x, @@ring_equiv.local_ring _
(show local_ring (localization.at_prime _), by apply_instance) _
(iso.CommRing_iso_to_ring_equiv $ stalk_iso R x).symm,
.. Spec.SheafedSpace_obj R }
@[elementwise]
lemma stalk_map_to_stalk {R S : CommRing} (f : R ⟶ S) (p : prime_spectrum S) :
to_stalk R (prime_spectrum.comap f p) ≫
PresheafedSpace.stalk_map (Spec.SheafedSpace_map f) p =
f ≫ to_stalk S p :=
begin
erw [← to_open_germ S ⊤ ⟨p, trivial⟩, ← to_open_germ R ⊤ ⟨prime_spectrum.comap f p, trivial⟩,
category.assoc, PresheafedSpace.stalk_map_germ (Spec.SheafedSpace_map f) ⊤ ⟨p, trivial⟩,
Spec.SheafedSpace_map_c_app, to_open_comp_comap_assoc],
refl
end
/--
Under the isomorphisms `stalk_iso`, the map `stalk_map (Spec.SheafedSpace_map f) p` corresponds
to the induced local ring homomorphism `localization.local_ring_hom`.
-/
@[elementwise]
lemma local_ring_hom_comp_stalk_iso {R S : CommRing} (f : R ⟶ S) (p : prime_spectrum S) :
(stalk_iso R (prime_spectrum.comap f p)).hom ≫
@category_struct.comp _ _
(CommRing.of (localization.at_prime (prime_spectrum.comap f p).as_ideal))
(CommRing.of (localization.at_prime p.as_ideal)) _
(localization.local_ring_hom (prime_spectrum.comap f p).as_ideal p.as_ideal f rfl)
(stalk_iso S p).inv =
PresheafedSpace.stalk_map (Spec.SheafedSpace_map f) p :=
(stalk_iso R (prime_spectrum.comap f p)).eq_inv_comp.mp $ (stalk_iso S p).comp_inv_eq.mpr $
localization.local_ring_hom_unique _ _ _ _ $ λ x, by
rw [stalk_iso_hom, stalk_iso_inv, comp_apply, comp_apply, localization_to_stalk_of,
stalk_map_to_stalk_apply, stalk_to_fiber_ring_hom_to_stalk]
/--
The induced map of a ring homomorphism on the prime spectra, as a morphism of locally ringed spaces.
-/
@[simps] def Spec.LocallyRingedSpace_map {R S : CommRing} (f : R ⟶ S) :
Spec.LocallyRingedSpace_obj S ⟶ Spec.LocallyRingedSpace_obj R :=
LocallyRingedSpace.hom.mk (Spec.SheafedSpace_map f) $ λ p, is_local_ring_hom.mk $ λ a ha,
begin
-- Here, we are showing that the map on prime spectra induced by `f` is really a morphism of
-- *locally* ringed spaces, i.e. that the induced map on the stalks is a local ring homomorphism.
rw ← local_ring_hom_comp_stalk_iso_apply at ha,
replace ha := (stalk_iso S p).hom.is_unit_map ha,
rw iso.inv_hom_id_apply at ha,
replace ha := is_local_ring_hom.map_nonunit _ ha,
convert ring_hom.is_unit_map (stalk_iso R (prime_spectrum.comap f p)).inv ha,
rw iso.hom_inv_id_apply
end
@[simp] lemma Spec.LocallyRingedSpace_map_id (R : CommRing) :
Spec.LocallyRingedSpace_map (𝟙 R) = 𝟙 (Spec.LocallyRingedSpace_obj R) :=
LocallyRingedSpace.hom.ext _ _ $
by { rw [Spec.LocallyRingedSpace_map_val, Spec.SheafedSpace_map_id], refl }
lemma Spec.LocallyRingedSpace_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) :
Spec.LocallyRingedSpace_map (f ≫ g) =
Spec.LocallyRingedSpace_map g ≫ Spec.LocallyRingedSpace_map f :=
LocallyRingedSpace.hom.ext _ _ $
by { rw [Spec.LocallyRingedSpace_map_val, Spec.SheafedSpace_map_comp], refl }
/--
Spec, as a contravariant functor from commutative rings to locally ringed spaces.
-/
@[simps] def Spec.to_LocallyRingedSpace : CommRingᵒᵖ ⥤ LocallyRingedSpace :=
{ obj := λ R, Spec.LocallyRingedSpace_obj (unop R),
map := λ R S f, Spec.LocallyRingedSpace_map f.unop,
map_id' := λ R, by rw [unop_id, Spec.LocallyRingedSpace_map_id],
map_comp' := λ R S T f g, by rw [unop_comp, Spec.LocallyRingedSpace_map_comp] }
section Spec_Γ
open algebraic_geometry.LocallyRingedSpace
/-- The counit morphism `R ⟶ Γ(Spec R)` given by `algebraic_geometry.structure_sheaf.to_open`. -/
@[simps {rhs_md := tactic.transparency.semireducible}]
def to_Spec_Γ (R : CommRing) : R ⟶ Γ.obj (op (Spec.to_LocallyRingedSpace.obj (op R))) :=
structure_sheaf.to_open R ⊤
instance is_iso_to_Spec_Γ (R : CommRing) : is_iso (to_Spec_Γ R) :=
by { cases R, apply structure_sheaf.is_iso_to_global }
@[reassoc]
lemma Spec_Γ_naturality {R S : CommRing} (f : R ⟶ S) :
f ≫ to_Spec_Γ S = to_Spec_Γ R ≫ Γ.map (Spec.to_LocallyRingedSpace.map f.op).op :=
by { ext, symmetry, apply localization.local_ring_hom_to_map }
/-- The counit (`Spec_Γ_identity.inv.op`) of the adjunction `Γ ⊣ Spec` is an isomorphism. -/
@[simps hom_app inv_app] def Spec_Γ_identity : Spec.to_LocallyRingedSpace.right_op ⋙ Γ ≅ 𝟭 _ :=
iso.symm $ nat_iso.of_components (λ R, as_iso (to_Spec_Γ R) : _) (λ _ _, Spec_Γ_naturality)
end Spec_Γ
/-- The stalk map of `Spec M⁻¹R ⟶ Spec R` is an iso for each `p : Spec M⁻¹R`. -/
lemma Spec_map_localization_is_iso (R : CommRing) (M : submonoid R)
(x : prime_spectrum (localization M)) :
is_iso (PresheafedSpace.stalk_map (Spec.to_PresheafedSpace.map
(CommRing.of_hom (algebra_map R (localization M))).op) x) :=
begin
erw ← local_ring_hom_comp_stalk_iso,
apply_with is_iso.comp_is_iso { instances := ff },
apply_instance,
apply_with is_iso.comp_is_iso { instances := ff },
/- I do not know why this is defeq to the goal, but I'm happy to accept that it is. -/
exact (show is_iso (is_localization.localization_localization_at_prime_iso_localization
M x.as_ideal).to_ring_equiv.to_CommRing_iso.hom, by apply_instance),
apply_instance
end
namespace structure_sheaf
variables {R S : CommRing.{u}} (f : R ⟶ S) (p : prime_spectrum R)
/--
For an algebra `f : R →+* S`, this is the ring homomorphism `S →+* (f∗ 𝒪ₛ)ₚ` for a `p : Spec R`.
This is shown to be the localization at `p` in `is_localized_module_to_pushforward_stalk_alg_hom`.
-/
def to_pushforward_stalk :
S ⟶ (Spec.Top_map f _* (structure_sheaf S).1).stalk p :=
structure_sheaf.to_open S ⊤ ≫
@Top.presheaf.germ _ _ _ _ (Spec.Top_map f _* (structure_sheaf S).1) ⊤ ⟨p, trivial⟩
@[reassoc]
lemma to_pushforward_stalk_comp :
f ≫ structure_sheaf.to_pushforward_stalk f p =
structure_sheaf.to_stalk R p ≫
(Top.presheaf.stalk_functor _ _).map (Spec.SheafedSpace_map f).c :=
begin
rw structure_sheaf.to_stalk,
erw category.assoc,
rw Top.presheaf.stalk_functor_map_germ,
exact Spec_Γ_naturality_assoc f _,
end
instance : algebra R ((Spec.Top_map f _* (structure_sheaf S).1).stalk p) :=
(f ≫ structure_sheaf.to_pushforward_stalk f p).to_algebra
lemma algebra_map_pushforward_stalk :
algebra_map R ((Spec.Top_map f _* (structure_sheaf S).1).stalk p) =
f ≫ structure_sheaf.to_pushforward_stalk f p := rfl
variables (R S) [algebra R S]
/--
This is the `alg_hom` version of `to_pushforward_stalk`, which is the map `S ⟶ (f∗ 𝒪ₛ)ₚ` for some
algebra `R ⟶ S` and some `p : Spec R`.
-/
@[simps]
def to_pushforward_stalk_alg_hom :
S →ₐ[R] (Spec.Top_map (algebra_map R S) _* (structure_sheaf S).1).stalk p :=
{ commutes' := λ _, rfl, ..(structure_sheaf.to_pushforward_stalk (algebra_map R S) p) }
lemma is_localized_module_to_pushforward_stalk_alg_hom_aux (y) :
∃ (x : S × p.as_ideal.prime_compl), x.2 • y = to_pushforward_stalk_alg_hom R S p x.1 :=
begin
obtain ⟨U, hp, s, e⟩ := Top.presheaf.germ_exist _ _ y,
obtain ⟨_, ⟨r, rfl⟩, hpr : p ∈ prime_spectrum.basic_open r,
hrU : prime_spectrum.basic_open r ≤ U⟩ := prime_spectrum.is_topological_basis_basic_opens
.exists_subset_of_mem_open (show p ∈ ↑U, from hp) U.2,
change prime_spectrum.basic_open r ≤ U at hrU,
replace e := ((Spec.Top_map (algebra_map R S) _* (structure_sheaf S).1)
.germ_res_apply (hom_of_le hrU) ⟨p, hpr⟩ _).trans e,
set s' := (Spec.Top_map (algebra_map R S) _* (structure_sheaf S).1).map (hom_of_le hrU).op s
with h,
rw ← h at e,
clear_value s', clear_dependent U,
obtain ⟨⟨s, ⟨_, n, rfl⟩⟩, hsn⟩ := @is_localization.surj _ _ _
_ _ _ (structure_sheaf.is_localization.to_basic_open S $ algebra_map R S r) s',
refine ⟨⟨s, ⟨r, hpr⟩ ^ n⟩, _⟩,
rw [submonoid.smul_def, algebra.smul_def, algebra_map_pushforward_stalk, to_pushforward_stalk,
comp_apply, comp_apply],
iterate 2 { erw ← (Spec.Top_map (algebra_map R S) _* (structure_sheaf S).1).germ_res_apply
(hom_of_le le_top) ⟨p, hpr⟩ },
rw [← e, ← map_mul, mul_comm],
dsimp only [subtype.coe_mk] at hsn,
rw ← map_pow (algebra_map R S) at hsn,
congr' 1
end
instance is_localized_module_to_pushforward_stalk_alg_hom :
is_localized_module p.as_ideal.prime_compl (to_pushforward_stalk_alg_hom R S p).to_linear_map :=
begin
apply is_localized_module.mk_of_algebra,
{ intros x hx, rw [algebra_map_pushforward_stalk, to_pushforward_stalk_comp, comp_apply],
exact (is_localization.map_units ((structure_sheaf R).presheaf.stalk p) ⟨x, hx⟩).map _ },
{ apply is_localized_module_to_pushforward_stalk_alg_hom_aux },
{ intros x hx,
rw [to_pushforward_stalk_alg_hom_apply, ring_hom.to_fun_eq_coe,
← (to_pushforward_stalk (algebra_map R S) p).map_zero, to_pushforward_stalk, comp_apply,
comp_apply, map_zero] at hx,
obtain ⟨U, hpU, i₁, i₂, e⟩ := Top.presheaf.germ_eq _ _ _ _ _ _ hx,
obtain ⟨_, ⟨r, rfl⟩, hpr, hrU⟩ := prime_spectrum.is_topological_basis_basic_opens
.exists_subset_of_mem_open (show p ∈ U.1, from hpU) U.2,
change prime_spectrum.basic_open r ≤ U at hrU,
apply_fun (Spec.Top_map (algebra_map R S) _* (structure_sheaf S).1).map (hom_of_le hrU).op at e,
simp only [Top.presheaf.pushforward_obj_map, functor.op_map, map_zero, ← comp_apply,
to_open_res] at e,
have : to_open S (prime_spectrum.basic_open $ algebra_map R S r) x = 0,
{ refine eq.trans _ e, refl },
have := (@is_localization.mk'_one _ _ _
_ _ _ (structure_sheaf.is_localization.to_basic_open S $ algebra_map R S r) x).trans this,
obtain ⟨⟨_, n, rfl⟩, e⟩ := (is_localization.mk'_eq_zero_iff _ _).mp this,
refine ⟨⟨r, hpr⟩ ^ n, _⟩,
rw [submonoid.smul_def, algebra.smul_def, submonoid.coe_pow, subtype.coe_mk, map_pow],
exact e },
end
end structure_sheaf
end algebraic_geometry
|
6f77c5e97fd1371345e549309a2824819ead4c0a
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/category_theory/category/PartialFun.lean
|
46ffcb1b33c11180b1db35e0cb026c84450856bc
|
[
"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,487
|
lean
|
/-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import category_theory.category.Pointed
import data.pfun
/-!
# The category of types with partial functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This defines `PartialFun`, the category of types equipped with partial functions.
This category is classically equivalent to the category of pointed types. The reason it doesn't hold
constructively stems from the difference between `part` and `option`. Both can model partial
functions, but the latter forces a decidable domain.
Precisely, `PartialFun_to_Pointed` turns a partial function `α →. β` into a function
`option α → option β` by sending to `none` the undefined values (and `none` to `none`). But being
defined is (generally) undecidable while being sent to `none` is decidable. So it can't be
constructive.
## References
* [nLab, *The category of sets and partial functions*]
(https://ncatlab.org/nlab/show/partial+function)
-/
open category_theory option
universes u
variables {α β : Type*}
/-- The category of types equipped with partial functions. -/
def PartialFun : Type* := Type*
namespace PartialFun
instance : has_coe_to_sort PartialFun Type* := ⟨id⟩
/-- Turns a type into a `PartialFun`. -/
@[nolint has_nonempty_instance] def of : Type* → PartialFun := id
@[simp] lemma coe_of (X : Type*) : ↥(of X) = X := rfl
instance : inhabited PartialFun := ⟨Type*⟩
instance large_category : large_category.{u} PartialFun :=
{ hom := pfun,
id := pfun.id,
comp := λ X Y Z f g, g.comp f,
id_comp' := @pfun.comp_id,
comp_id' := @pfun.id_comp,
assoc' := λ W X Y Z _ _ _, (pfun.comp_assoc _ _ _).symm }
/-- Constructs a partial function isomorphism between types from an equivalence between them. -/
@[simps] def iso.mk {α β : PartialFun.{u}} (e : α ≃ β) : α ≅ β :=
{ hom := e,
inv := e.symm,
hom_inv_id' := (pfun.coe_comp _ _).symm.trans $ congr_arg coe e.symm_comp_self,
inv_hom_id' := (pfun.coe_comp _ _).symm.trans $ congr_arg coe e.self_comp_symm }
end PartialFun
/-- The forgetful functor from `Type` to `PartialFun` which forgets that the maps are total. -/
def Type_to_PartialFun : Type.{u} ⥤ PartialFun :=
{ obj := id,
map := @pfun.lift,
map_comp' := λ _ _ _ _ _, pfun.coe_comp _ _ }
instance : faithful Type_to_PartialFun := ⟨λ X Y, pfun.coe_injective⟩
/-- The functor which deletes the point of a pointed type. In return, this makes the maps partial.
This the computable part of the equivalence `PartialFun_equiv_Pointed`. -/
@[simps map] def Pointed_to_PartialFun : Pointed.{u} ⥤ PartialFun :=
{ obj := λ X, {x : X // x ≠ X.point},
map := λ X Y f, pfun.to_subtype _ f.to_fun ∘ subtype.val,
map_id' := λ X, pfun.ext $ λ a b,
pfun.mem_to_subtype_iff.trans (subtype.coe_inj.trans part.mem_some_iff.symm),
map_comp' := λ X Y Z f g, pfun.ext $ λ a c, begin
refine (pfun.mem_to_subtype_iff.trans _).trans part.mem_bind_iff.symm,
simp_rw [pfun.mem_to_subtype_iff, subtype.exists],
refine ⟨λ h, ⟨f.to_fun a, λ ha, c.2 $ h.trans
((congr_arg g.to_fun ha : g.to_fun _ = _).trans g.map_point), rfl, h⟩, _⟩,
rintro ⟨b, _, (rfl : b = _), h⟩,
exact h,
end }
/-- The functor which maps undefined values to a new point. This makes the maps total and creates
pointed types. This the noncomputable part of the equivalence `PartialFun_equiv_Pointed`. It can't
be computable because `= option.none` is decidable while the domain of a general `part` isn't. -/
@[simps map] noncomputable def PartialFun_to_Pointed : PartialFun ⥤ Pointed :=
by classical; exact
{ obj := λ X, ⟨option X, none⟩,
map := λ X Y f, ⟨option.elim none (λ a, (f a).to_option), rfl⟩,
map_id' := λ X, Pointed.hom.ext _ _ $ funext $ λ o,
option.rec_on o rfl $ λ a, part.some_to_option _,
map_comp' := λ X Y Z f g, Pointed.hom.ext _ _ $ funext $ λ o, option.rec_on o rfl $ λ a,
part.bind_to_option _ _ }
/-- The equivalence induced by `PartialFun_to_Pointed` and `Pointed_to_PartialFun`.
`part.equiv_option` made functorial. -/
@[simps] noncomputable def PartialFun_equiv_Pointed : PartialFun.{u} ≌ Pointed :=
by classical; exact
equivalence.mk PartialFun_to_Pointed Pointed_to_PartialFun
(nat_iso.of_components (λ X, PartialFun.iso.mk
{ to_fun := λ a, ⟨some a, some_ne_none a⟩,
inv_fun := λ a, get $ ne_none_iff_is_some.1 a.2,
left_inv := λ a, get_some _ _,
right_inv := λ a, by simp only [subtype.val_eq_coe, some_get, subtype.coe_eta] }) $ λ X Y f,
pfun.ext $ λ a b, begin
unfold_projs,
dsimp,
rw part.bind_some,
refine (part.mem_bind_iff.trans _).trans pfun.mem_to_subtype_iff.symm,
obtain ⟨b | b, hb⟩ := b,
{ exact (hb rfl).elim },
dsimp,
simp_rw [part.mem_some_iff, subtype.mk_eq_mk, exists_prop, some_inj, exists_eq_right'],
refine part.mem_to_option.symm.trans _,
exact eq_comm,
end)
(nat_iso.of_components (λ X, Pointed.iso.mk
{ to_fun := option.elim X.point subtype.val,
inv_fun := λ a, if h : a = X.point then none else some ⟨_, h⟩,
left_inv := λ a, option.rec_on a (dif_pos rfl) $ λ a, (dif_neg a.2).trans $
by simp only [option.elim, subtype.val_eq_coe, subtype.coe_eta],
right_inv := λ a, begin
change option.elim _ _ (dite _ _ _) = _,
split_ifs,
{ rw h, refl },
{ refl }
end } rfl) $ λ X Y f, Pointed.hom.ext _ _ $ funext $ λ a, option.rec_on a f.map_point.symm $
λ a, begin
unfold_projs,
dsimp,
change option.elim _ _ _ = _,
rw part.elim_to_option,
split_ifs,
{ refl },
{ exact eq.symm (of_not_not h) }
end)
/-- Forgetting that maps are total and making them total again by adding a point is the same as just
adding a point. -/
@[simps] noncomputable def Type_to_PartialFun_iso_PartialFun_to_Pointed :
Type_to_PartialFun ⋙ PartialFun_to_Pointed ≅ Type_to_Pointed :=
nat_iso.of_components (λ X, { hom := ⟨id, rfl⟩,
inv := ⟨id, rfl⟩,
hom_inv_id' := rfl,
inv_hom_id' := rfl }) $ λ X Y f,
Pointed.hom.ext _ _ $ funext $ λ a, option.rec_on a rfl $ λ a, by convert part.some_to_option _
|
f58d729c2a9055db3057d001e552c6da8ad459f5
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/data/fin/interval.lean
|
af0d1b267af69db33d5ebc728e099f6a0e9b81ba
|
[
"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
| 5,031
|
lean
|
/-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.nat.interval
import data.finset.locally_finite
/-!
# Finite intervals in `fin n`
This file proves that `fin n` is a `locally_finite_order` and calculates the cardinality of its
intervals as finsets and fintypes.
-/
open finset fin function
open_locale big_operators
variables (n : ℕ)
instance : locally_finite_order (fin n) :=
order_iso.locally_finite_order fin.order_iso_subtype
instance : locally_finite_order_bot (fin n) :=
order_iso.locally_finite_order_bot fin.order_iso_subtype
instance : Π n, locally_finite_order_top (fin n)
| 0 := is_empty.to_locally_finite_order_top
| (n + 1) := infer_instance
namespace fin
variables {n} (a b : fin n)
lemma Icc_eq_finset_subtype : Icc a b = (Icc (a : ℕ) b).fin n := rfl
lemma Ico_eq_finset_subtype : Ico a b = (Ico (a : ℕ) b).fin n := rfl
lemma Ioc_eq_finset_subtype : Ioc a b = (Ioc (a : ℕ) b).fin n := rfl
lemma Ioo_eq_finset_subtype : Ioo a b = (Ioo (a : ℕ) b).fin n := rfl
@[simp] lemma map_subtype_embedding_Icc : (Icc a b).map fin.coe_embedding = Icc a b :=
by simp [Icc_eq_finset_subtype, finset.fin, finset.map_map, Icc_filter_lt_of_lt_right]
@[simp] lemma map_subtype_embedding_Ico : (Ico a b).map fin.coe_embedding = Ico a b :=
by simp [Ico_eq_finset_subtype, finset.fin, finset.map_map]
@[simp] lemma map_subtype_embedding_Ioc : (Ioc a b).map fin.coe_embedding = Ioc a b :=
by simp [Ioc_eq_finset_subtype, finset.fin, finset.map_map, Ioc_filter_lt_of_lt_right]
@[simp] lemma map_subtype_embedding_Ioo : (Ioo a b).map fin.coe_embedding = Ioo a b :=
by simp [Ioo_eq_finset_subtype, finset.fin, finset.map_map]
@[simp] lemma card_Icc : (Icc a b).card = b + 1 - a :=
by rw [←nat.card_Icc, ←map_subtype_embedding_Icc, card_map]
@[simp] lemma card_Ico : (Ico a b).card = b - a :=
by rw [←nat.card_Ico, ←map_subtype_embedding_Ico, card_map]
@[simp] lemma card_Ioc : (Ioc a b).card = b - a :=
by rw [←nat.card_Ioc, ←map_subtype_embedding_Ioc, card_map]
@[simp] lemma card_Ioo : (Ioo a b).card = b - a - 1 :=
by rw [←nat.card_Ioo, ←map_subtype_embedding_Ioo, card_map]
@[simp] lemma card_fintype_Icc : fintype.card (set.Icc a b) = b + 1 - a :=
by rw [←card_Icc, fintype.card_of_finset]
@[simp] lemma card_fintype_Ico : fintype.card (set.Ico a b) = b - a :=
by rw [←card_Ico, fintype.card_of_finset]
@[simp] lemma card_fintype_Ioc : fintype.card (set.Ioc a b) = b - a :=
by rw [←card_Ioc, fintype.card_of_finset]
@[simp] lemma card_fintype_Ioo : fintype.card (set.Ioo a b) = b - a - 1 :=
by rw [←card_Ioo, fintype.card_of_finset]
lemma Ici_eq_finset_subtype : Ici a = (Icc (a : ℕ) n).fin n := by { ext, simp }
lemma Ioi_eq_finset_subtype : Ioi a = (Ioc (a : ℕ) n).fin n := by { ext, simp }
lemma Iic_eq_finset_subtype : Iic b = (Iic (b : ℕ)).fin n := rfl
lemma Iio_eq_finset_subtype : Iio b = (Iio (b : ℕ)).fin n := rfl
@[simp] lemma map_subtype_embedding_Ici : (Ici a).map fin.coe_embedding = Icc a (n - 1) :=
begin
ext x,
simp only [exists_prop, embedding.coe_subtype, mem_Ici, mem_map, mem_Icc],
split,
{ rintro ⟨x, hx, rfl⟩,
exact ⟨hx, le_tsub_of_add_le_right $ x.2⟩ },
cases n,
{ exact fin.elim0 a },
{ exact λ hx, ⟨⟨x, nat.lt_succ_iff.2 hx.2⟩, hx.1, rfl⟩ }
end
@[simp] lemma map_subtype_embedding_Ioi : (Ioi a).map fin.coe_embedding = Ioc a (n - 1) :=
begin
ext x,
simp only [exists_prop, embedding.coe_subtype, mem_Ioi, mem_map, mem_Ioc],
split,
{ rintro ⟨x, hx, rfl⟩,
exact ⟨hx, le_tsub_of_add_le_right $ x.2⟩ },
cases n,
{ exact fin.elim0 a },
{ exact λ hx, ⟨⟨x, nat.lt_succ_iff.2 hx.2⟩, hx.1, rfl⟩ }
end
@[simp] lemma map_subtype_embedding_Iic : (Iic b).map fin.coe_embedding = Iic b :=
by simp [Iic_eq_finset_subtype, finset.fin, finset.map_map, Iic_filter_lt_of_lt_right]
@[simp] lemma map_subtype_embedding_Iio : (Iio b).map fin.coe_embedding = Iio b :=
by simp [Iio_eq_finset_subtype, finset.fin, finset.map_map]
@[simp] lemma card_Ici : (Ici a).card = n - a :=
by { cases n, { exact fin.elim0 a }, rw [←card_map, map_subtype_embedding_Ici, nat.card_Icc], refl }
@[simp] lemma card_Ioi : (Ioi a).card = n - 1 - a :=
by { rw [←card_map, map_subtype_embedding_Ioi, nat.card_Ioc] }
@[simp] lemma card_Iic : (Iic b).card = b + 1 :=
by rw [←nat.card_Iic b, ←map_subtype_embedding_Iic, card_map]
@[simp] lemma card_Iio : (Iio b).card = b :=
by rw [←nat.card_Iio b, ←map_subtype_embedding_Iio, card_map]
@[simp] lemma card_fintype_Ici : fintype.card (set.Ici a) = n - a :=
by rw [fintype.card_of_finset, card_Ici]
@[simp] lemma card_fintype_Ioi : fintype.card (set.Ioi a) = n - 1 - a :=
by rw [fintype.card_of_finset, card_Ioi]
@[simp] lemma card_fintype_Iic : fintype.card (set.Iic b) = b + 1 :=
by rw [fintype.card_of_finset, card_Iic]
@[simp] lemma card_fintype_Iio : fintype.card (set.Iio b) = b :=
by rw [fintype.card_of_finset, card_Iio]
end fin
|
2a644ddf247415684c5255028bf6ad8da95f14c3
|
5ca7b1b12d14c4742e29366312ba2c2ef8201b21
|
/world_experiments/used_to_be_level2_stupid_exact_tactic.lean
|
734633b51b99890a04a02a4cff4bafc913df7bea
|
[
"Apache-2.0"
] |
permissive
|
MatthiasHu/natural_number_game
|
2e464482ef3001863430b0336133b6697b275ba3
|
2d764f72669ae30861f6a1057fce0257f3e466c4
|
refs/heads/master
| 1,609,719,110,419
| 1,576,345,737,000
| 1,576,345,737,000
| 240,296,314
| 0
| 0
|
Apache-2.0
| 1,581,608,357,000
| 1,581,608,356,000
| null |
UTF-8
|
Lean
| false
| false
| 2,673
|
lean
|
import mynat.definition -- Imports the natural numbers. -- hide
import mynat.mul -- hide
namespace mynat -- hide
/-
# World 1: Tutorial world
## level 2: the `exact` tactic.
Delete the `sorry` below and let's look at the box
on the top right. It should look like this:
```
a b : mynat,
h : 2 * a = b + 7
⊢ 2 * a = b + 7
```
So here `a` and `b` are natural numbers,
we have a hypothesis `h` that `2 * a = b + 7` (think of
`h` as a *proof* that `2 * a = b + 7`), and our
goal is to prove that `2 * a = b + 7`.
Unfortunately `refl` won't work here. `refl` proves things like `3 = 3` or `x + y = x + y`.
`refl` works when both sides of an equality are *exactly the same strings of characters
in the same order*. The reason why `2 * a = b + 7` is true is *not* because `2 * a` and `b + 7`
are exactly the same strings of characters in the same order. The reason it's true is
because it's a hypothesis. The numbers `2 * a` and `b + 7` are equal because of a theorem,
and the proof of the theorem is `h`. That's what a hypothesis
is -- it's a way of saying "imagine we have a proof of this".
We're hence in a situation where we have a hypothesis `h`,
which is *exactly* equal to the goal we're trying to prove. In
this situation, the tactic
`exact h,`
will close the goal. Try typing `exact h,` where the `sorry` was, and
hit enter after the comma to go onto a new line.
**Don't forget the `h`** and
**don't forget the comma.**
You should see the "Proof complete!" message, and the error
in the bottom right goal will disappear. The reason
this works is that `h` is *exactly* a proof of the goal.
-/
/- Lemma : no-side-bar
For all natural numbers $a$ and $b$,
if $2a=b + 7$, then $2a=b+7$.
-/
lemma example2 (a b : mynat) (h : 2 * a = b + 7): 2 * a = b + 7 :=
begin [nat_num_game]
exact h
end
/- Tactic : exact
If your goal is a proposition and you have access to a proof
of that proposition, either because it is a hypothesis `h`
or because it is a theorem which is already proved, then
`exact h,`
or
`exact <name_of_theorem>,`
will close the goal.
### Examples
1) If the top right box (the "local context") looks like
this:
```
x y : mynat
h : y = x + 3
⊢ y = x + 3
```
then
`exact h,`
will close the goal.
2) (from world 2 onwards) If the top right box looks like this:
```
a b : mynat
⊢ a + succ(b) = succ(a + b)
```
then
`exact add_succ a b,`
will close the goal.
-/
/-
These two tactics, `refl` and `exact`, clearly only
have limited capabilities by themselves. The next
tactic we will learn, the rewrite tactic `rw`, is far more powerful.
Click on "next level" to move onto the next level in tutorial world.
-/
end mynat -- hide
|
1d3929613fc0a310c3711532ab6fcaf66ca37d8e
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/tactic/swap_var.lean
|
85d285695841a6a909b5800303a4243140faf42d
|
[
"Apache-2.0"
] |
permissive
|
leanprover-community/mathlib
|
56a2cadd17ac88caf4ece0a775932fa26327ba0e
|
442a83d738cb208d3600056c489be16900ba701d
|
refs/heads/master
| 1,693,584,102,358
| 1,693,471,902,000
| 1,693,471,902,000
| 97,922,418
| 1,595
| 352
|
Apache-2.0
| 1,694,693,445,000
| 1,500,624,130,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 1,950
|
lean
|
/-
Copyright (c) 2022 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import tactic.interactive
/-!
# Swap bound variable tactic
This files defines a tactic `swap_var` whose main purpose is to be a weaker
version of `wlog` that juggles bound names.
It is a helper around the core tactic `rename`.
* `swap_var old new` renames all names named `old` to `new` and vice versa in the goal
and all hypotheses.
```lean
example (P Q : Prop) (hp : P) (hq : Q) : P ∧ Q :=
begin
split,
work_on_goal 1 { swap_var [P Q] },
all_goals { exact ‹P› }
end
```
# See also
* `tactic.interactive.rename`
* `tactic.interactive.rename_var`
-/
namespace tactic.interactive
setup_tactic_parser
private meta def swap_arg_parser : lean.parser (name × name) :=
prod.mk <$> ident <*> (optional (tk "<->" <|> tk "↔") *> ident)
private meta def swap_args_parser : lean.parser (list (name × name)) :=
(functor.map (λ x, [x]) swap_arg_parser)
<|>
(tk "[" *> sep_by (tk ",") swap_arg_parser <* tk "]")
/--
`swap_var [x y, P ↔ Q]` swaps the names `x` and `y`, `P` and `Q`.
Such a swapping can be used as a weak `wlog` if the tactic proofs use the same names.
```lean
example (P Q : Prop) (hp : P) (hq : Q) : P ∧ Q :=
begin
split,
work_on_goal 1 { swap_var [P Q] },
all_goals { exact ‹P› }
end
```
-/
meta def swap_var (renames : parse swap_args_parser) : tactic unit := do
renames.mmap' (λ e, do
n ← tactic.get_unused_name,
-- how to call `interactive.tactic.rename` here?
propagate_tags $ tactic.rename_many $ native.rb_map.of_list [(e.1, n), (e.2, e.1)],
propagate_tags $ tactic.rename_many $ native.rb_map.of_list [(n, e.2)]),
pure ()
end tactic.interactive
add_tactic_doc
{ name := "swap_var",
category := doc_category.tactic,
decl_names := [`tactic.interactive.swap_var],
tags := ["renaming"] }
|
6b58efb295d7f4c56129592c6799b057048b106d
|
2eab05920d6eeb06665e1a6df77b3157354316ad
|
/src/algebra/continued_fractions/computation/terminates_iff_rat.lean
|
87c1281554f0f446c78aa9478a8fa9b166b5d6ba
|
[
"Apache-2.0"
] |
permissive
|
ayush1801/mathlib
|
78949b9f789f488148142221606bf15c02b960d2
|
ce164e28f262acbb3de6281b3b03660a9f744e3c
|
refs/heads/master
| 1,692,886,907,941
| 1,635,270,866,000
| 1,635,270,866,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 14,318
|
lean
|
/-
Copyright (c) 2020 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import algebra.continued_fractions.computation.approximations
import algebra.continued_fractions.computation.correctness_terminating
import data.rat
/-!
# Termination of Continued Fraction Computations (`gcf.of`)
## Summary
We show that the continued fraction for a value `v`, as defined in
`algebra.continued_fractions.computation.basic`, terminates if and only if `v` corresponds to a
rational number, that is `↑v = q` for some `q : ℚ`.
## Main Theorems
- `generalized_continued_fraction.coe_of_rat` shows that
`generalized_continued_fraction.of v = generalized_continued_fraction.of q` for `v : α` given that
`↑v = q` and `q : ℚ`.
- `generalized_continued_fraction.terminates_iff_rat` shows that
`generalized_continued_fraction.of v` terminates if and only if `↑v = q` for some `q : ℚ`.
## Tags
rational, continued fraction, termination
-/
namespace generalized_continued_fraction
open generalized_continued_fraction (of)
variables {K : Type*} [linear_ordered_field K] [floor_ring K]
/-
We will have to constantly coerce along our structures in the following proofs using their provided
map functions.
-/
local attribute [simp] pair.map int_fract_pair.mapFr
section rat_of_terminates
/-!
### Terminating Continued Fractions Are Rational
We want to show that the computation of a continued fraction `generalized_continued_fraction.of v`
terminates if and only if `v ∈ ℚ`. In this section, we show the implication from left to right.
We first show that every finite convergent corresponds to a rational number `q` and then use the
finite correctness proof (`of_correctness_of_terminates`) of `generalized_continued_fraction.of` to
show that `v = ↑q`.
-/
variables (v : K) (n : ℕ)
lemma exists_gcf_pair_rat_eq_of_nth_conts_aux :
∃ (conts : pair ℚ),
(of v).continuants_aux n = (conts.map coe : pair K) :=
nat.strong_induction_on n
begin
clear n,
let g := of v,
assume n IH,
rcases n with _|_|n,
-- n = 0
{ suffices : ∃ (gp : pair ℚ), pair.mk (1 : K) 0 = gp.map coe, by simpa [continuants_aux],
use (pair.mk 1 0),
simp },
-- n = 1
{ suffices : ∃ (conts : pair ℚ), pair.mk g.h 1 = conts.map coe, by
simpa [continuants_aux],
use (pair.mk ⌊v⌋ 1),
simp },
-- 2 ≤ n
{ cases (IH (n + 1) $ lt_add_one (n + 1)) with pred_conts pred_conts_eq, -- invoke the IH
cases s_ppred_nth_eq : (g.s.nth n) with gp_n,
-- option.none
{ use pred_conts,
have : g.continuants_aux (n + 2) = g.continuants_aux (n + 1), from
continuants_aux_stable_of_terminated (n + 1).le_succ s_ppred_nth_eq,
simp only [this, pred_conts_eq] },
-- option.some
{ -- invoke the IH a second time
cases (IH n $ lt_of_le_of_lt (n.le_succ) $ lt_add_one $ n + 1)
with ppred_conts ppred_conts_eq,
obtain ⟨a_eq_one, z, b_eq_z⟩ : gp_n.a = 1 ∧ ∃ (z : ℤ), gp_n.b = (z : K), from
of_part_num_eq_one_and_exists_int_part_denom_eq s_ppred_nth_eq,
-- finally, unfold the recurrence to obtain the required rational value.
simp only [a_eq_one, b_eq_z,
(continuants_aux_recurrence s_ppred_nth_eq ppred_conts_eq pred_conts_eq)],
use (next_continuants 1 (z : ℚ) ppred_conts pred_conts),
cases ppred_conts, cases pred_conts,
simp [next_continuants, next_numerator, next_denominator] } }
end
lemma exists_gcf_pair_rat_eq_nth_conts :
∃ (conts : pair ℚ), (of v).continuants n = (conts.map coe : pair K) :=
by { rw [nth_cont_eq_succ_nth_cont_aux], exact (exists_gcf_pair_rat_eq_of_nth_conts_aux v $ n + 1) }
lemma exists_rat_eq_nth_numerator : ∃ (q : ℚ), (of v).numerators n = (q : K) :=
begin
rcases (exists_gcf_pair_rat_eq_nth_conts v n) with ⟨⟨a, _⟩, nth_cont_eq⟩,
use a,
simp [num_eq_conts_a, nth_cont_eq],
end
lemma exists_rat_eq_nth_denominator : ∃ (q : ℚ), (of v).denominators n = (q : K) :=
begin
rcases (exists_gcf_pair_rat_eq_nth_conts v n) with ⟨⟨_, b⟩, nth_cont_eq⟩,
use b,
simp [denom_eq_conts_b, nth_cont_eq]
end
/-- Every finite convergent corresponds to a rational number. -/
lemma exists_rat_eq_nth_convergent : ∃ (q : ℚ), (of v).convergents n = (q : K) :=
begin
rcases (exists_rat_eq_nth_numerator v n) with ⟨Aₙ, nth_num_eq⟩,
rcases (exists_rat_eq_nth_denominator v n) with ⟨Bₙ, nth_denom_eq⟩,
use (Aₙ / Bₙ),
simp [nth_num_eq, nth_denom_eq, convergent_eq_num_div_denom]
end
variable {v}
/-- Every terminating continued fraction corresponds to a rational number. -/
theorem exists_rat_eq_of_terminates
(terminates : (of v).terminates) :
∃ (q : ℚ), v = ↑q :=
begin
obtain ⟨n, v_eq_conv⟩ : ∃ n, v = (of v).convergents n, from
of_correctness_of_terminates terminates,
obtain ⟨q, conv_eq_q⟩ :
∃ (q : ℚ), (of v).convergents n = (↑q : K), from exists_rat_eq_nth_convergent v n,
have : v = (↑q : K), from eq.trans v_eq_conv conv_eq_q,
use [q, this]
end
end rat_of_terminates
section rat_translation
/-!
### Technical Translation Lemmas
Before we can show that the continued fraction of a rational number terminates, we have to prove
some technical translation lemmas. More precisely, in this section, we show that, given a rational
number `q : ℚ` and value `v : K` with `v = ↑q`, the continued fraction of `q` and `v` coincide.
In particular, we show that
```lean
(↑(generalized_continued_fraction.of q : generalized_continued_fraction ℚ)
: generalized_continued_fraction K)
= generalized_continued_fraction.of v`
```
in `generalized_continued_fraction.coe_of_rat`.
To do this, we proceed bottom-up, showing the correspondence between the basic functions involved in
the computation first and then lift the results step-by-step.
-/
/- The lifting works for arbitrary linear ordered fields with a floor function. -/
variables {v : K} {q : ℚ} (v_eq_q : v = (↑q : K)) (n : ℕ)
include v_eq_q
/-! First, we show the correspondence for the very basic functions in
`generalized_continued_fraction.int_fract_pair`. -/
namespace int_fract_pair
lemma coe_of_rat_eq :
((int_fract_pair.of q).mapFr coe : int_fract_pair K) = int_fract_pair.of v :=
by simp [int_fract_pair.of, v_eq_q, int.fract]
lemma coe_stream_nth_rat_eq :
((int_fract_pair.stream q n).map (mapFr coe) : option $ int_fract_pair K)
= int_fract_pair.stream v n :=
begin
induction n with n IH,
case nat.zero : { simp [int_fract_pair.stream, (coe_of_rat_eq v_eq_q)] },
case nat.succ :
{ rw v_eq_q at IH,
cases stream_q_nth_eq : (int_fract_pair.stream q n) with ifp_n,
case option.none : { simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq] },
case option.some :
{ cases ifp_n with b fr,
cases decidable.em (fr = 0) with fr_zero fr_ne_zero,
{ simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_zero] },
{ replace IH : some (int_fract_pair.mk b ↑fr) = int_fract_pair.stream ↑q n, by
rwa [stream_q_nth_eq] at IH,
have : (fr : K)⁻¹ = ((fr⁻¹ : ℚ) : K), by norm_cast,
have coe_of_fr := (coe_of_rat_eq this),
simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_ne_zero],
unfold_coes,
simpa [coe_of_fr] } } }
end
lemma coe_stream_rat_eq :
((int_fract_pair.stream q).map (option.map (mapFr coe)) : stream $ option $ int_fract_pair K) =
int_fract_pair.stream v :=
by { funext n, exact (int_fract_pair.coe_stream_nth_rat_eq v_eq_q n) }
end int_fract_pair
/-! Now we lift the coercion results to the continued fraction computation. -/
lemma coe_of_h_rat_eq : (↑((of q).h : ℚ) : K) = (of v).h :=
begin
unfold of int_fract_pair.seq1,
rw ←(int_fract_pair.coe_of_rat_eq v_eq_q),
simp
end
lemma coe_of_s_nth_rat_eq :
(((of q).s.nth n).map (pair.map coe) : option $ pair K) = (of v).s.nth n :=
begin
simp only [of, int_fract_pair.seq1, seq.map_nth, seq.nth_tail],
simp only [seq.nth],
rw [←(int_fract_pair.coe_stream_rat_eq v_eq_q)],
rcases succ_nth_stream_eq : (int_fract_pair.stream q (n + 1)) with _ | ⟨_, _⟩;
simp [stream.map, stream.nth, succ_nth_stream_eq]
end
lemma coe_of_s_rat_eq : (((of q).s).map (pair.map coe) : seq $ pair K) = (of v).s :=
by { ext n, rw ←(coe_of_s_nth_rat_eq v_eq_q), refl }
/-- Given `(v : K), (q : ℚ), and v = q`, we have that `gcf.of q = gcf.of v` -/
lemma coe_of_rat_eq :
(⟨(of q).h, (of q).s.map (pair.map coe)⟩ : generalized_continued_fraction K) = of v :=
begin
cases gcf_v_eq : (of v) with h s,
have : ↑⌊↑q⌋ = h, by { rw v_eq_q at gcf_v_eq, injection gcf_v_eq },
simp [(coe_of_h_rat_eq v_eq_q), (coe_of_s_rat_eq v_eq_q), gcf_v_eq],
rwa [←(@rat.cast_floor K _ _ q), floor_ring_unique]
end
lemma of_terminates_iff_of_rat_terminates {v : K} {q : ℚ} (v_eq_q : v = (q : K)) :
(of v).terminates ↔ (of q).terminates :=
begin
split;
intro h;
cases h with n h;
use n;
simp only [seq.terminated_at, (coe_of_s_nth_rat_eq v_eq_q n).symm] at h ⊢;
cases ((of q).s.nth n);
trivial
end
end rat_translation
section terminates_of_rat
/-!
### Continued Fractions of Rationals Terminate
Finally, we show that the continued fraction of a rational number terminates.
The crucial insight is that, given any `q : ℚ` with `0 < q < 1`, the numerator of `int.fract q` is
smaller than the numerator of `q`. As the continued fraction computation recursively operates on
the fractional part of a value `v` and `0 ≤ int.fract v < 1`, we infer that the numerator of the
fractional part in the computation decreases by at least one in each step. As `0 ≤ int.fract v`,
this process must stop after finite number of steps, and the computation hence terminates.
-/
namespace int_fract_pair
variables {q : ℚ} {n : ℕ}
/--
Shows that for any `q : ℚ` with `0 < q < 1`, the numerator of the fractional part of
`int_fract_pair.of q⁻¹` is smaller than the numerator of `q`.
-/
lemma of_inv_fr_num_lt_num_of_pos (q_pos : 0 < q) :
(int_fract_pair.of q⁻¹).fr.num < q.num :=
rat.fract_inv_num_lt_num_of_pos q_pos
/-- Shows that the sequence of numerators of the fractional parts of the stream is strictly
antitone. -/
lemma stream_succ_nth_fr_num_lt_nth_fr_num_rat {ifp_n ifp_succ_n : int_fract_pair ℚ}
(stream_nth_eq : int_fract_pair.stream q n = some ifp_n)
(stream_succ_nth_eq : int_fract_pair.stream q (n + 1) = some ifp_succ_n) :
ifp_succ_n.fr.num < ifp_n.fr.num :=
begin
obtain ⟨ifp_n', stream_nth_eq', ifp_n_fract_ne_zero, int_fract_pair.of_eq_ifp_succ_n⟩ :
∃ ifp_n', int_fract_pair.stream q n = some ifp_n' ∧ ifp_n'.fr ≠ 0
∧ int_fract_pair.of ifp_n'.fr⁻¹ = ifp_succ_n, from
succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq,
have : ifp_n = ifp_n', by injection (eq.trans stream_nth_eq.symm stream_nth_eq'),
cases this,
rw [←int_fract_pair.of_eq_ifp_succ_n],
cases (nth_stream_fr_nonneg_lt_one stream_nth_eq) with zero_le_ifp_n_fract ifp_n_fract_lt_one,
have : 0 < ifp_n.fr, from (lt_of_le_of_ne zero_le_ifp_n_fract $ ifp_n_fract_ne_zero.symm),
exact (of_inv_fr_num_lt_num_of_pos this)
end
lemma stream_nth_fr_num_le_fr_num_sub_n_rat : ∀ {ifp_n : int_fract_pair ℚ},
int_fract_pair.stream q n = some ifp_n → ifp_n.fr.num ≤ (int_fract_pair.of q).fr.num - n :=
begin
induction n with n IH,
case nat.zero
{ assume ifp_zero stream_zero_eq,
have : int_fract_pair.of q = ifp_zero, by injection stream_zero_eq,
simp [le_refl, this.symm] },
case nat.succ
{ assume ifp_succ_n stream_succ_nth_eq,
suffices : ifp_succ_n.fr.num + 1 ≤ (int_fract_pair.of q).fr.num - n, by
{ rw [int.coe_nat_succ, sub_add_eq_sub_sub],
solve_by_elim [le_sub_right_of_add_le] },
rcases (succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq) with
⟨ifp_n, stream_nth_eq, -⟩,
have : ifp_succ_n.fr.num < ifp_n.fr.num, from
stream_succ_nth_fr_num_lt_nth_fr_num_rat stream_nth_eq stream_succ_nth_eq,
have : ifp_succ_n.fr.num + 1 ≤ ifp_n.fr.num, from int.add_one_le_of_lt this,
exact (le_trans this (IH stream_nth_eq)) }
end
lemma exists_nth_stream_eq_none_of_rat (q : ℚ) : ∃ (n : ℕ), int_fract_pair.stream q n = none :=
begin
let fract_q_num := (int.fract q).num, let n := fract_q_num.nat_abs + 1,
cases stream_nth_eq : (int_fract_pair.stream q n) with ifp,
{ use n, exact stream_nth_eq },
{ -- arrive at a contradiction since the numerator decreased num + 1 times but every fractional
-- value is nonnegative.
have ifp_fr_num_le_q_fr_num_sub_n : ifp.fr.num ≤ fract_q_num - n, from
stream_nth_fr_num_le_fr_num_sub_n_rat stream_nth_eq,
have : fract_q_num - n = -1, by
{ have : 0 ≤ fract_q_num, from rat.num_nonneg_iff_zero_le.elim_right (int.fract_nonneg q),
simp [(int.nat_abs_of_nonneg this), sub_add_eq_sub_sub_swap, sub_right_comm] },
have : ifp.fr.num ≤ -1, by rwa this at ifp_fr_num_le_q_fr_num_sub_n,
have : 0 ≤ ifp.fr, from (nth_stream_fr_nonneg_lt_one stream_nth_eq).left,
have : 0 ≤ ifp.fr.num, from rat.num_nonneg_iff_zero_le.elim_right this,
linarith }
end
end int_fract_pair
/-- The continued fraction of a rational number terminates. -/
theorem terminates_of_rat (q : ℚ) : (of q).terminates :=
exists.elim (int_fract_pair.exists_nth_stream_eq_none_of_rat q)
( assume n stream_nth_eq_none,
exists.intro n
( have int_fract_pair.stream q (n + 1) = none, from
int_fract_pair.stream_is_seq q stream_nth_eq_none,
(of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none.elim_right this) ) )
end terminates_of_rat
/--
The continued fraction `generalized_continued_fraction.of v` terminates if and only if `v ∈ ℚ`.
-/
theorem terminates_iff_rat (v : K) : (of v).terminates ↔ ∃ (q : ℚ), v = (q : K) :=
iff.intro
( assume terminates_v : (of v).terminates,
show ∃ (q : ℚ), v = (q : K), from exists_rat_eq_of_terminates terminates_v )
( assume exists_q_eq_v : ∃ (q : ℚ), v = (↑q : K),
exists.elim exists_q_eq_v
( assume q,
assume v_eq_q : v = ↑q,
have (of q).terminates, from terminates_of_rat q,
(of_terminates_iff_of_rat_terminates v_eq_q).elim_right this ) )
end generalized_continued_fraction
|
9247301bb425fcf1ff3aaa5f91ff45171e58e04e
|
ce6917c5bacabee346655160b74a307b4a5ab620
|
/src/ch4/ex0407.lean
|
a7594c5d8527429f5371b98f6c3b2eaa01f8e769
|
[] |
no_license
|
Ailrun/Theorem_Proving_in_Lean
|
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
|
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
|
refs/heads/master
| 1,609,838,270,467
| 1,586,846,743,000
| 1,586,846,743,000
| 240,967,761
| 1
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 150
|
lean
|
variables (α : Type) (p q : α → Prop)
example (h : ∃ x, p x ∧ q x) : ∃ x, q x ∧ p x :=
let ⟨w, hpw, hqw⟩ := h in ⟨w, hqw, hpw⟩
|
93b7f5cfd40030cceb7baaba0b4a590071018b15
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/analysis/normed/field/infinite_sum.lean
|
67888a205379ce48eb3d326193ea94de053b2279
|
[
"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,116
|
lean
|
/-
Copyright (c) 2021 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker
-/
import analysis.normed.field.basic
import analysis.normed.group.infinite_sum
/-! # Multiplying two infinite sums in a normed ring
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file, we prove various results about `(∑' x : ι, f x) * (∑' y : ι', g y)` in a normed
ring. There are similar results proven in `topology/algebra/infinite_sum` (e.g `tsum_mul_tsum`),
but in a normed ring we get summability results which aren't true in general.
We first establish results about arbitrary index types, `β` and `γ`, and then we specialize to
`β = γ = ℕ` to prove the Cauchy product formula
(see `tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm`).
!-/
variables {α : Type*} {ι : Type*} {ι' : Type*} [normed_ring α]
open_locale big_operators classical
open finset
/-! ### Arbitrary index types -/
lemma summable.mul_of_nonneg {f : ι → ℝ} {g : ι' → ℝ}
(hf : summable f) (hg : summable g) (hf' : 0 ≤ f) (hg' : 0 ≤ g) :
summable (λ (x : ι × ι'), f x.1 * g x.2) :=
let ⟨s, hf⟩ := hf in
let ⟨t, hg⟩ := hg in
suffices this : ∀ u : finset (ι × ι'), ∑ x in u, f x.1 * g x.2 ≤ s*t,
from summable_of_sum_le (λ x, mul_nonneg (hf' _) (hg' _)) this,
assume u,
calc ∑ x in u, f x.1 * g x.2
≤ ∑ x in u.image prod.fst ×ˢ u.image prod.snd, f x.1 * g x.2 :
sum_mono_set_of_nonneg (λ x, mul_nonneg (hf' _) (hg' _)) subset_product
... = ∑ x in u.image prod.fst, ∑ y in u.image prod.snd, f x * g y : sum_product
... = ∑ x in u.image prod.fst, f x * ∑ y in u.image prod.snd, g y :
sum_congr rfl (λ x _, mul_sum.symm)
... ≤ ∑ x in u.image prod.fst, f x * t :
sum_le_sum
(λ x _, mul_le_mul_of_nonneg_left (sum_le_has_sum _ (λ _ _, hg' _) hg) (hf' _))
... = (∑ x in u.image prod.fst, f x) * t : sum_mul.symm
... ≤ s * t :
mul_le_mul_of_nonneg_right (sum_le_has_sum _ (λ _ _, hf' _) hf) (hg.nonneg $ λ _, hg' _)
lemma summable.mul_norm {f : ι → α} {g : ι' → α}
(hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) :
summable (λ (x : ι × ι'), ‖f x.1 * g x.2‖) :=
summable_of_nonneg_of_le (λ x, norm_nonneg (f x.1 * g x.2)) (λ x, norm_mul_le (f x.1) (g x.2))
(hf.mul_of_nonneg hg (λ x, norm_nonneg $ f x) (λ x, norm_nonneg $ g x) : _)
lemma summable_mul_of_summable_norm [complete_space α] {f : ι → α} {g : ι' → α}
(hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) :
summable (λ (x : ι × ι'), f x.1 * g x.2) :=
summable_of_summable_norm (hf.mul_norm hg)
/-- Product of two infinites sums indexed by arbitrary types.
See also `tsum_mul_tsum` if `f` and `g` are *not* absolutely summable. -/
lemma tsum_mul_tsum_of_summable_norm [complete_space α] {f : ι → α} {g : ι' → α}
(hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) :
(∑' x, f x) * (∑' y, g y) = (∑' z : ι × ι', f z.1 * g z.2) :=
tsum_mul_tsum (summable_of_summable_norm hf) (summable_of_summable_norm hg)
(summable_mul_of_summable_norm hf hg)
/-! ### `ℕ`-indexed families (Cauchy product)
We prove two versions of the Cauchy product formula. The first one is
`tsum_mul_tsum_eq_tsum_sum_range_of_summable_norm`, where the `n`-th term is a sum over
`finset.range (n+1)` involving `nat` subtraction.
In order to avoid `nat` subtraction, we also provide
`tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm`,
where the `n`-th term is a sum over all pairs `(k, l)` such that `k+l=n`, which corresponds to the
`finset` `finset.nat.antidiagonal n`. -/
section nat
open finset.nat
lemma summable_norm_sum_mul_antidiagonal_of_summable_norm {f g : ℕ → α}
(hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) :
summable (λ n, ‖∑ kl in antidiagonal n, f kl.1 * g kl.2‖) :=
begin
have := summable_sum_mul_antidiagonal_of_summable_mul
(summable.mul_of_nonneg hf hg (λ _, norm_nonneg _) (λ _, norm_nonneg _)),
refine summable_of_nonneg_of_le (λ _, norm_nonneg _) _ this,
intros n,
calc ‖∑ kl in antidiagonal n, f kl.1 * g kl.2‖
≤ ∑ kl in antidiagonal n, ‖f kl.1 * g kl.2‖ : norm_sum_le _ _
... ≤ ∑ kl in antidiagonal n, ‖f kl.1‖ * ‖g kl.2‖ : sum_le_sum (λ i _, norm_mul_le _ _)
end
/-- The Cauchy product formula for the product of two infinite sums indexed by `ℕ`,
expressed by summing on `finset.nat.antidiagonal`.
See also `tsum_mul_tsum_eq_tsum_sum_antidiagonal` if `f` and `g` are
*not* absolutely summable. -/
lemma tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm [complete_space α] {f g : ℕ → α}
(hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) :
(∑' n, f n) * (∑' n, g n) = ∑' n, ∑ kl in antidiagonal n, f kl.1 * g kl.2 :=
tsum_mul_tsum_eq_tsum_sum_antidiagonal (summable_of_summable_norm hf) (summable_of_summable_norm hg)
(summable_mul_of_summable_norm hf hg)
lemma summable_norm_sum_mul_range_of_summable_norm {f g : ℕ → α}
(hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) :
summable (λ n, ‖∑ k in range (n+1), f k * g (n - k)‖) :=
begin
simp_rw ← sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l),
exact summable_norm_sum_mul_antidiagonal_of_summable_norm hf hg
end
/-- The Cauchy product formula for the product of two infinite sums indexed by `ℕ`,
expressed by summing on `finset.range`.
See also `tsum_mul_tsum_eq_tsum_sum_range` if `f` and `g` are
*not* absolutely summable. -/
lemma tsum_mul_tsum_eq_tsum_sum_range_of_summable_norm [complete_space α] {f g : ℕ → α}
(hf : summable (λ x, ‖f x‖)) (hg : summable (λ x, ‖g x‖)) :
(∑' n, f n) * (∑' n, g n) = ∑' n, ∑ k in range (n+1), f k * g (n - k) :=
begin
simp_rw ← sum_antidiagonal_eq_sum_range_succ (λ k l, f k * g l),
exact tsum_mul_tsum_eq_tsum_sum_antidiagonal_of_summable_norm hf hg
end
end nat
|
b503bcbeb074c6a8a6efa2cd4112c13c454ccbaf
|
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
|
/library/init/nat.lean
|
a6cb271a47f5b2da111f3c15377d96c554d1fa50
|
[
"Apache-2.0"
] |
permissive
|
respu/lean
|
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
|
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
|
refs/heads/master
| 1,610,882,451,231
| 1,427,747,084,000
| 1,427,747,429,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 10,699
|
lean
|
/-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: init.nat
Authors: Floris van Doorn, Leonardo de Moura
-/
prelude
import init.wf init.tactic init.num
open eq.ops decidable
namespace nat
notation `ℕ` := nat
inductive lt (a : nat) : nat → Prop :=
| base : lt a (succ a)
| step : Π {b}, lt a b → lt a (succ b)
notation a < b := lt a b
definition le [reducible] (a b : nat) : Prop := a < succ b
notation a ≤ b := le a b
definition pred (a : nat) : nat :=
nat.cases_on a zero (λ a₁, a₁)
protected definition is_inhabited [instance] : inhabited nat :=
inhabited.mk zero
protected definition has_decidable_eq [instance] : ∀ x y : nat, decidable (x = y)
| has_decidable_eq zero zero := inl rfl
| has_decidable_eq (succ x) zero := inr (λ h, nat.no_confusion h)
| has_decidable_eq zero (succ y) := inr (λ h, nat.no_confusion h)
| has_decidable_eq (succ x) (succ y) :=
if H : x = y
then inl (eq.rec_on H rfl)
else inr (λ h : succ x = succ y, nat.no_confusion h (λ heq : x = y, absurd heq H))
-- less-than is well-founded
definition lt.wf [instance] : well_founded lt :=
well_founded.intro (λn, nat.rec_on n
(acc.intro zero (λ (y : nat) (hlt : y < zero),
have aux : ∀ {n₁}, y < n₁ → zero = n₁ → acc lt y, from
λ n₁ hlt, nat.lt.cases_on hlt
(λ heq, nat.no_confusion heq)
(λ b hlt heq, nat.no_confusion heq),
aux hlt rfl))
(λ (n : nat) (ih : acc lt n),
acc.intro (succ n) (λ (m : nat) (hlt : m < succ n),
have aux : ∀ {n₁} (hlt : m < n₁), succ n = n₁ → acc lt m, from
λ n₁ hlt, nat.lt.cases_on hlt
(λ (heq : succ n = succ m),
nat.no_confusion heq (λ (e : n = m),
eq.rec_on e ih))
(λ b (hlt : m < b) (heq : succ n = succ b),
nat.no_confusion heq (λ (e : n = b),
acc.inv (eq.rec_on e ih) hlt)),
aux hlt rfl)))
definition measure {A : Type} (f : A → nat) : A → A → Prop :=
inv_image lt f
definition measure.wf {A : Type} (f : A → nat) : well_founded (measure f) :=
inv_image.wf f lt.wf
definition not_lt_zero (a : nat) : ¬ a < zero :=
have aux : ∀ {b}, a < b → b = zero → false, from
λ b H, lt.cases_on H
(λ heq, nat.no_confusion heq)
(λ b h₁ heq, nat.no_confusion heq),
λ H, aux H rfl
definition zero_lt_succ (a : nat) : zero < succ a :=
nat.rec_on a
(lt.base zero)
(λ a (hlt : zero < succ a), lt.step hlt)
definition lt.trans {a b c : nat} (H₁ : a < b) (H₂ : b < c) : a < c :=
have aux : ∀ {d}, d < c → b = d → a < b → a < c, from
(λ d H, lt.rec_on H
(λ h₁ h₂, lt.step (eq.rec_on h₁ h₂))
(λ b hl ih h₁ h₂, lt.step (ih h₁ h₂))),
aux H₂ rfl H₁
definition succ_lt_succ {a b : nat} (H : a < b) : succ a < succ b :=
lt.rec_on H
(lt.base (succ a))
(λ b hlt ih, lt.trans ih (lt.base (succ b)))
definition lt_of_succ_lt {a b : nat} (H : succ a < b) : a < b :=
have aux : ∀ {a₁}, a₁ < b → succ a = a₁ → a < b, from
λ a₁ H, lt.rec_on H
(λ e₁, eq.rec_on e₁ (lt.step (lt.base a)))
(λ d hlt ih e₁, lt.step (ih e₁)),
aux H rfl
definition lt_of_succ_lt_succ {a b : nat} (H : succ a < succ b) : a < b :=
have aux : pred (succ a) < pred (succ b), from
lt.rec_on H
(lt.base a)
(λ (b : nat) (hlt : succ a < b) ih,
show pred (succ a) < pred (succ b), from
lt_of_succ_lt hlt),
aux
definition decidable_lt [instance] : decidable_rel lt :=
λ a b, nat.rec_on b
(λ (a : nat), inr (not_lt_zero a))
(λ (b₁ : nat) (ih : ∀ a, decidable (a < b₁)) (a : nat), nat.cases_on a
(inl !zero_lt_succ)
(λ a, decidable.rec_on (ih a)
(λ h_pos : a < b₁, inl (succ_lt_succ h_pos))
(λ h_neg : ¬ a < b₁,
have aux : ¬ succ a < succ b₁, from
λ h : succ a < succ b₁, h_neg (lt_of_succ_lt_succ h),
inr aux)))
a
definition le.refl (a : nat) : a ≤ a :=
lt.base a
definition le_of_lt {a b : nat} (H : a < b) : a ≤ b :=
lt.step H
definition eq_or_lt_of_le {a b : nat} (H : a ≤ b) : a = b ∨ a < b :=
begin
cases H with [b, hlt],
apply (or.inl rfl),
apply (or.inr hlt)
end
definition le_of_eq_or_lt {a b : nat} (H : a = b ∨ a < b) : a ≤ b :=
or.rec_on H
(λ hl, eq.rec_on hl !le.refl)
(λ hr, le_of_lt hr)
definition decidable_le [instance] : decidable_rel le :=
λ a b, decidable_of_decidable_of_iff _ (iff.intro le_of_eq_or_lt eq_or_lt_of_le)
definition le.rec_on {a : nat} {P : nat → Prop} {b : nat} (H : a ≤ b) (H₁ : P a) (H₂ : ∀ b, a < b → P b) : P b :=
begin
cases H with [b', hlt],
apply H₁,
apply (H₂ b' hlt)
end
definition lt.irrefl (a : nat) : ¬ a < a :=
nat.rec_on a
!not_lt_zero
(λ (a : nat) (ih : ¬ a < a) (h : succ a < succ a),
ih (lt_of_succ_lt_succ h))
definition lt.asymm {a b : nat} (H : a < b) : ¬ b < a :=
lt.rec_on H
(λ h : succ a < a, !lt.irrefl (lt_of_succ_lt h))
(λ b hlt (ih : ¬ b < a) (h : succ b < a), ih (lt_of_succ_lt h))
definition lt.trichotomy (a b : nat) : a < b ∨ a = b ∨ b < a :=
nat.rec_on b
(λa, nat.cases_on a
(or.inr (or.inl rfl))
(λ a₁, or.inr (or.inr !zero_lt_succ)))
(λ b₁ (ih : ∀a, a < b₁ ∨ a = b₁ ∨ b₁ < a) (a : nat), nat.cases_on a
(or.inl !zero_lt_succ)
(λ a, or.rec_on (ih a)
(λ h : a < b₁, or.inl (succ_lt_succ h))
(λ h, or.rec_on h
(λ h : a = b₁, or.inr (or.inl (eq.rec_on h rfl)))
(λ h : b₁ < a, or.inr (or.inr (succ_lt_succ h))))))
a
definition eq_or_lt_of_not_lt {a b : nat} (hnlt : ¬ a < b) : a = b ∨ b < a :=
or.rec_on (lt.trichotomy a b)
(λ hlt, absurd hlt hnlt)
(λ h, h)
definition lt_succ_of_le {a b : nat} (h : a ≤ b) : a < succ b :=
h
definition lt_of_succ_le {a b : nat} (h : succ a ≤ b) : a < b :=
lt_of_succ_lt_succ h
definition le_succ_of_le {a b : nat} (h : a ≤ b) : a ≤ succ b :=
lt.step h
definition succ_le_of_lt {a b : nat} (h : a < b) : succ a ≤ b :=
succ_lt_succ h
definition le.trans {a b c : nat} (h₁ : a ≤ b) (h₂ : b ≤ c) : a ≤ c :=
begin
cases h₁ with [b', hlt],
apply h₂,
apply (lt.trans hlt h₂)
end
definition lt_of_le_of_lt {a b c : nat} (h₁ : a ≤ b) (h₂ : b < c) : a < c :=
begin
cases h₁ with [b', hlt],
apply h₂,
apply (lt.trans hlt h₂)
end
definition lt_of_lt_of_le {a b c : nat} (h₁ : a < b) (h₂ : b ≤ c) : a < c :=
begin
cases h₁ with [b', hlt],
apply (lt_of_succ_lt_succ h₂),
apply (lt.trans hlt (lt_of_succ_lt_succ h₂))
end
definition lt_of_lt_of_eq {a b c : nat} (h₁ : a < b) (h₂ : b = c) : a < c :=
eq.rec_on h₂ h₁
definition le_of_le_of_eq {a b c : nat} (h₁ : a ≤ b) (h₂ : b = c) : a ≤ c :=
eq.rec_on h₂ h₁
definition lt_of_eq_of_lt {a b c : nat} (h₁ : a = b) (h₂ : b < c) : a < c :=
eq.rec_on (eq.rec_on h₁ rfl) h₂
definition le_of_eq_of_le {a b c : nat} (h₁ : a = b) (h₂ : b ≤ c) : a ≤ c :=
eq.rec_on (eq.rec_on h₁ rfl) h₂
calc_trans lt.trans
calc_trans lt_of_le_of_lt
calc_trans lt_of_lt_of_le
calc_trans lt_of_lt_of_eq
calc_trans lt_of_eq_of_lt
calc_trans le.trans
calc_trans le_of_le_of_eq
calc_trans le_of_eq_of_le
definition max (a b : nat) : nat :=
if a < b then b else a
definition min (a b : nat) : nat :=
if a < b then a else b
definition max_a_a (a : nat) : a = max a a :=
eq.rec_on !if_t_t rfl
definition max.eq_right {a b : nat} (H : a < b) : max a b = b :=
if_pos H
definition max.eq_left {a b : nat} (H : ¬ a < b) : max a b = a :=
if_neg H
definition max.right_eq {a b : nat} (H : a < b) : b = max a b :=
eq.rec_on (max.eq_right H) rfl
definition max.left_eq {a b : nat} (H : ¬ a < b) : a = max a b :=
eq.rec_on (max.eq_left H) rfl
definition max.left (a b : nat) : a ≤ max a b :=
by_cases
(λ h : a < b, le_of_lt (eq.rec_on (max.right_eq h) h))
(λ h : ¬ a < b, eq.rec_on (max.eq_left h) !le.refl)
definition max.right (a b : nat) : b ≤ max a b :=
by_cases
(λ h : a < b, eq.rec_on (max.eq_right h) !le.refl)
(λ h : ¬ a < b, or.rec_on (eq_or_lt_of_not_lt h)
(λ heq, eq.rec_on heq (eq.rec_on (max_a_a a) !le.refl))
(λ h : b < a,
have aux : a = max a b, from max.left_eq (lt.asymm h),
eq.rec_on aux (le_of_lt h)))
definition gt [reducible] a b := lt b a
notation a > b := gt a b
definition ge [reducible] a b := le b a
notation a ≥ b := ge a b
-- add is defined in init.num
definition sub (a b : nat) : nat :=
nat.rec_on b a (λ b₁ r, pred r)
notation a - b := sub a b
definition mul (a b : nat) : nat :=
nat.rec_on b zero (λ b₁ r, r + a)
notation a * b := mul a b
context
attribute sub [reducible]
definition succ_sub_succ_eq_sub (a b : nat) : succ a - succ b = a - b :=
nat.induction_on b
rfl
(λ b₁ (ih : succ a - succ b₁ = a - b₁),
eq.rec_on ih (eq.refl (pred (succ a - succ b₁))))
end
definition sub_eq_succ_sub_succ (a b : nat) : a - b = succ a - succ b :=
eq.rec_on (succ_sub_succ_eq_sub a b) rfl
definition zero_sub_eq_zero (a : nat) : zero - a = zero :=
nat.induction_on a
rfl
(λ a₁ (ih : zero - a₁ = zero),
eq.rec_on ih (eq.refl (pred (zero - a₁))))
definition zero_eq_zero_sub (a : nat) : zero = zero - a :=
eq.rec_on (zero_sub_eq_zero a) rfl
definition sub_lt {a b : nat} : zero < a → zero < b → a - b < a :=
have aux : Π {a}, zero < a → Π {b}, zero < b → a - b < a, from
λa h₁, lt.rec_on h₁
(λb h₂, lt.cases_on h₂
(lt.base zero)
(λ b₁ bpos,
eq.rec_on (sub_eq_succ_sub_succ zero b₁)
(eq.rec_on (zero_eq_zero_sub b₁) (lt.base zero))))
(λa₁ apos ih b h₂, lt.cases_on h₂
(lt.base a₁)
(λ b₁ bpos,
eq.rec_on (sub_eq_succ_sub_succ a₁ b₁)
(lt.trans (@ih b₁ bpos) (lt.base a₁)))),
λ h₁ h₂, aux h₁ h₂
definition pred_le (a : nat) : pred a ≤ a :=
nat.cases_on a
(le.refl zero)
(λ a₁, le_of_lt (lt.base a₁))
definition sub_le (a b : nat) : a - b ≤ a :=
nat.induction_on b
(le.refl a)
(λ b₁ ih, le.trans !pred_le ih)
end nat
|
3171d7be86e6ddb8e93c825c0a3b188b2e4aa02e
|
8034095e1be60c0b8f6559c39220bd537d1f9933
|
/lambda/parsing.lean
|
cbb9f2a61918f5ec5ad008a8fa4e7bd0c3e86af0
|
[] |
no_license
|
teodorov/lambda
|
40c573e2dd268824641702d9f94cf61e019ae6c5
|
4dc4d595dd0ee20c59913ef0171fd33eb0d637a1
|
refs/heads/master
| 1,585,318,070,303
| 1,530,364,515,000
| 1,530,364,515,000
| 146,645,753
| 1
| 0
| null | 1,535,569,435,000
| 1,535,569,434,000
| null |
UTF-8
|
Lean
| false
| false
| 2,342
|
lean
|
import data.buffer.parser
import lambda.types
open parser types
namespace parsing
def whitespaces := " \t\n\x0d".to_list
def reserved_chars :=
[' ', ',', 'λ', '(', ')', ':', '-']
def WordChar : parser char :=
sat (λ c, list.all (reserved_chars ++ whitespaces) (≠ c))
def LF := ch $ char.of_nat 10
def CR := ch $ char.of_nat 13
def Nl := CR >> LF <|> LF <|> CR
def Ws : parser unit :=
decorate_error "<whitespace>" $
many' $ one_of' whitespaces
def Word : parser string := many_char1 WordChar
def tok (s : string) := str s >> Ws
def Var : parser term := do
name ← Word,
pure $ term.var name
def Lam (Term_recur : parser term) : parser term := do
ch 'λ', many Ws,
names ← sep_by1 Ws (many_char1 WordChar),
ch ',', many Ws,
body ← Term_recur,
pure $ multi_lam names body
def App (Term : parser term) : parser term := do
head ← Term, many1 Ws,
body ← sep_by Ws Term,
pure $ multi_app head body
def parens (term : parser term) :=
term <|> (ch '(' >> term <* ch ')')
def Term_core : parser term → parser term
| Term_recur :=
let term := Lam (parens Term_recur) <|>
App (parens Term_recur) <|> Var in
parens term
def Term := fix Term_core
def Let : parser (string × term) := do
tok "let",
name ← Word, many1 Ws,
tok ":=", body ← Term,
pure (name, body)
def Numeral : parser char :=
sat $ λ c, list.any "0123456789".to_list (= c)
def Number := many_char1 Numeral
def Command_line : parser repl_command :=
str ":quit" >> pure repl_command.quit <|>
str ":help" >> pure repl_command.help <|>
str ":env" >> pure repl_command.env <|>
str ":depth" >> Ws >> Number >>=
(pure ∘ repl_command.depth ∘ string.to_nat) <|>
str ":import_depth" >> Ws >> Number >>=
(pure ∘ repl_command.import_depth ∘ string.to_nat) <|>
str ":show_depth" >> pure repl_command.show_depth <|>
str ":show_import_depth" >> pure repl_command.show_import_depth <|>
str ":clear_env" >> pure repl_command.clear_env <|>
str ":load" >> Ws >> Word >>= (pure ∘ repl_command.load) <|>
Let >>= (pure ∘ function.uncurry repl_command.bind) <|>
Term >>= (pure ∘ repl_command.term) <|>
many Ws >> pure repl_command.nothing
def Command : parser repl_command := do
cmd ← Command_line,
optional (str "--" >> optional Ws >> many (sat (λ _, tt))),
optional $ many Ws,
pure cmd
end parsing
|
abe83213324fcb23f6cc2e8e5f3a1c39d1c563d6
|
cf39355caa609c0f33405126beee2739aa3cb77e
|
/tests/lean/run/smt_tests3.lean
|
780ff728ce18b82f23528a97d91f19fa485af4a7
|
[
"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
| 675
|
lean
|
def f : nat → nat
| 0 := 1
| (n+1) := f n + 1
lemma ex(a : nat) : f a ≠ 0 :=
begin
induction a,
dsimp [f], intro x, contradiction,
dsimp [f],
change nat.succ (f a_n) ≠ 0,
apply nat.succ_ne_zero
end
lemma ex2 (a : nat) : f a ≠ 0 :=
begin [smt]
induction a,
{ intros, ematch_using [f] },
{ iterate { ematch_using [f, nat.add_one, nat.succ_ne_zero] }}
end
lemma ex3 (a : nat) : f (a+1) = f a + 1 :=
begin [smt]
dsimp [f]
end
lemma ex4 (a : nat) : f (a+1) = f a + 1 :=
begin [smt]
simp [f]
end
lemma ex5 (a : nat) : f (a+1) = f a + 1 :=
begin [smt]
ematch_using [f]
end
lemma ex6 (a : nat) : f 0 = 1 :=
begin [smt]
ematch_using [f]
end
|
857eca2a5233b789a823d14ff85a0c55661424b5
|
fa02ed5a3c9c0adee3c26887a16855e7841c668b
|
/src/algebra/punit_instances.lean
|
b89b2b62e897c55ecc41978cde12e9548f4f1c92
|
[
"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
| 2,819
|
lean
|
/-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.module.basic
/-!
# Instances on punit
This file collects facts about algebraic structures on the one-element type, e.g. that it is a
commutative ring.
-/
universes u
namespace punit
variables (x y : punit.{u+1}) (s : set punit.{u+1})
@[to_additive]
instance : comm_group punit :=
by refine_struct
{ mul := λ _ _, star,
one := star,
inv := λ _, star,
div := λ _ _, star,
npow := λ _ _, star,
gpow := λ _ _, star,
.. };
intros; exact subsingleton.elim _ _
instance : comm_ring punit :=
by refine
{ .. punit.comm_group,
.. punit.add_comm_group,
.. };
intros; exact subsingleton.elim _ _
instance : complete_boolean_algebra punit :=
by refine
{ le := λ _ _, true,
le_antisymm := λ _ _ _ _, subsingleton.elim _ _,
lt := λ _ _, false,
lt_iff_le_not_le := λ _ _, iff_of_false not_false (λ H, H.2 trivial),
top := star,
bot := star,
sup := λ _ _, star,
inf := λ _ _, star,
Sup := λ _, star,
Inf := λ _, star,
compl := λ _, star,
sdiff := λ _ _, star,
.. };
intros; trivial <|> simp only [eq_iff_true_of_subsingleton]
instance : canonically_ordered_add_monoid punit :=
by refine
{ lt_of_add_lt_add_left := λ _ _ _, id,
le_iff_exists_add := λ _ _, iff_of_true _ ⟨star, subsingleton.elim _ _⟩,
.. punit.comm_ring, .. punit.complete_boolean_algebra, .. };
intros; trivial
instance : linear_ordered_cancel_add_comm_monoid punit :=
{ add_left_cancel := λ _ _ _ _, subsingleton.elim _ _,
le_of_add_le_add_left := λ _ _ _ _, trivial,
le_total := λ _ _, or.inl trivial,
decidable_le := λ _ _, decidable.true,
decidable_eq := punit.decidable_eq,
decidable_lt := λ _ _, decidable.false,
.. punit.canonically_ordered_add_monoid }
instance (R : Type u) [semiring R] : module R punit := module.of_core $
by refine
{ smul := λ _ _, star,
.. punit.comm_ring, .. };
intros; exact subsingleton.elim _ _
@[simp] lemma zero_eq : (0 : punit) = star := rfl
@[simp, to_additive] lemma one_eq : (1 : punit) = star := rfl
@[simp] lemma add_eq : x + y = star := rfl
@[simp, to_additive] lemma mul_eq : x * y = star := rfl
@[simp, to_additive] lemma div_eq : x / y = star := rfl
@[simp] lemma neg_eq : -x = star := rfl
@[simp, to_additive] lemma inv_eq : x⁻¹ = star := rfl
lemma smul_eq : x • y = star := rfl
@[simp] lemma top_eq : (⊤ : punit) = star := rfl
@[simp] lemma bot_eq : (⊥ : punit) = star := rfl
@[simp] lemma sup_eq : x ⊔ y = star := rfl
@[simp] lemma inf_eq : x ⊓ y = star := rfl
@[simp] lemma Sup_eq : Sup s = star := rfl
@[simp] lemma Inf_eq : Inf s = star := rfl
@[simp] protected lemma le : x ≤ y := trivial
@[simp] lemma not_lt : ¬(x < y) := not_false
end punit
|
d83e2c1cef915554ede387b503d382dc941c842f
|
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
|
/13_More_Tactics.org.7.lean
|
568227ea2a38ccc2dc2cdb20bc12ecf120d56796
|
[] |
no_license
|
cjmazey/lean-tutorial
|
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
|
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
|
refs/heads/master
| 1,610,286,098,832
| 1,447,124,923,000
| 1,447,124,923,000
| 43,082,433
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 209
|
lean
|
import standard
import data.nat
open nat
example (x y : ℕ) (H : succ x = succ y) : x = y :=
by injection H with H'; exact H'
example (x y : ℕ) (H : succ x = succ y) : x = y :=
by injection H; assumption
|
c1da96fb776bb00bac1cb38bc7d193bad77bf5ee
|
07c76fbd96ea1786cc6392fa834be62643cea420
|
/hott/types/lift.hlean
|
9db711a4598a422f70e8959df55c4fd329f0d7cb
|
[
"Apache-2.0"
] |
permissive
|
fpvandoorn/lean2
|
5a430a153b570bf70dc8526d06f18fc000a60ad9
|
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
|
refs/heads/master
| 1,592,036,508,364
| 1,545,093,958,000
| 1,545,093,958,000
| 75,436,854
| 0
| 0
| null | 1,480,718,780,000
| 1,480,718,780,000
| null |
UTF-8
|
Lean
| false
| false
| 6,360
|
hlean
|
/-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Theorems about lift
-/
import ..function
open eq equiv is_equiv is_trunc pointed
namespace lift
universe variables u v
variables {A : Type.{u}} (z z' : lift.{u v} A)
protected definition eta : up (down z) = z :=
by induction z; reflexivity
protected definition code [unfold 2 3] : lift A → lift A → Type
| code (up a) (up a') := a = a'
protected definition decode [unfold 2 3] : Π(z z' : lift A), lift.code z z' → z = z'
| decode (up a) (up a') := λc, ap up c
variables {z z'}
protected definition encode [unfold 3 4 5] (p : z = z') : lift.code z z' :=
by induction p; induction z; esimp
variables (z z')
definition lift_eq_equiv : (z = z') ≃ lift.code z z' :=
equiv.MK lift.encode
!lift.decode
abstract begin
intro c, induction z with a, induction z' with a', esimp at *, induction c,
reflexivity
end end
abstract begin
intro p, induction p, induction z, reflexivity
end end
section
variables {a a' : A}
definition eq_of_up_eq_up [unfold 4] (p : up a = up a') : a = a' :=
lift.encode p
definition lift_transport {P : A → Type} (p : a = a') (z : lift (P a))
: p ▸ z = up (p ▸ down z) :=
by induction p; induction z; reflexivity
end
variables {A' : Type} (f : A → A') (g : lift A → lift A')
definition lift_functor [unfold 4] : lift A → lift A'
| lift_functor (up a) := up (f a)
definition is_equiv_lift_functor [constructor] [Hf : is_equiv f] : is_equiv (lift_functor f) :=
adjointify (lift_functor f)
(lift_functor f⁻¹)
abstract begin
intro z', induction z' with a',
esimp, exact ap up !right_inv
end end
abstract begin
intro z, induction z with a,
esimp, exact ap up !left_inv
end end
definition lift_equiv_lift_of_is_equiv [constructor] [Hf : is_equiv f] : lift A ≃ lift A' :=
equiv.mk _ (is_equiv_lift_functor f)
definition lift_equiv_lift [constructor] (f : A ≃ A') : lift A ≃ lift A' :=
equiv.mk _ (is_equiv_lift_functor f)
definition lift_equiv_lift_refl (A : Type) : lift_equiv_lift (erfl : A ≃ A) = erfl :=
by apply equiv_eq; intro z; induction z with a; reflexivity
definition lift_inv_functor [unfold_full] (a : A) : A' :=
down (g (up a))
definition is_equiv_lift_inv_functor [constructor] [Hf : is_equiv g]
: is_equiv (lift_inv_functor g) :=
adjointify (lift_inv_functor g)
(lift_inv_functor g⁻¹)
abstract begin
intro z', rewrite [▸*,lift.eta,right_inv g],
end end
abstract begin
intro z', rewrite [▸*,lift.eta,left_inv g],
end end
definition equiv_of_lift_equiv_lift [constructor] (g : lift A ≃ lift A') : A ≃ A' :=
equiv.mk _ (is_equiv_lift_inv_functor g)
definition lift_functor_left_inv : lift_inv_functor (lift_functor f) = f :=
eq_of_homotopy (λa, idp)
definition lift_functor_right_inv : lift_functor (lift_inv_functor g) = g :=
begin
apply eq_of_homotopy, intro z, induction z with a, esimp, apply lift.eta
end
variables (A A')
definition is_equiv_lift_functor_fn [constructor]
: is_equiv (lift_functor : (A → A') → (lift A → lift A')) :=
adjointify lift_functor
lift_inv_functor
lift_functor_right_inv
lift_functor_left_inv
definition lift_imp_lift_equiv [constructor] : (lift A → lift A') ≃ (A → A') :=
(equiv.mk _ (is_equiv_lift_functor_fn A A'))⁻¹ᵉ
-- can we deduce this from lift_imp_lift_equiv?
definition lift_equiv_lift_equiv [constructor] : (lift A ≃ lift A') ≃ (A ≃ A') :=
equiv.MK equiv_of_lift_equiv_lift
lift_equiv_lift
abstract begin
intro f, apply equiv_eq, reflexivity
end end
abstract begin
intro g, apply equiv_eq', esimp, apply eq_of_homotopy, intro z,
induction z with a, esimp, apply lift.eta
end end
definition lift_eq_lift_equiv.{u1 u2} (A A' : Type.{u1})
: (lift.{u1 u2} A = lift.{u1 u2} A') ≃ (A = A') :=
!eq_equiv_equiv ⬝e !lift_equiv_lift_equiv ⬝e !eq_equiv_equiv⁻¹ᵉ
definition is_embedding_lift [instance] : is_embedding lift :=
begin
intro A A', refine is_equiv_of_equiv_of_homotopy !lift_eq_lift_equiv⁻¹ᵉ _,
{ intro p, induction p,
esimp [lift_eq_lift_equiv,equiv.trans,equiv.symm,eq_equiv_equiv],
rewrite [equiv_of_eq_refl, lift_equiv_lift_refl],
apply ua_refl}
end
definition fiber_lift_functor {A B : Type} (f : A → B) (b : B) :
fiber (lift_functor f) (up b) ≃ fiber f b :=
begin
fapply equiv.MK: intro v; cases v with a p,
{ cases a with a, exact fiber.mk a (inj' up p) },
{ exact fiber.mk (up a) (ap up p) },
{ apply ap (fiber.mk a), apply inj'_ap },
{ cases a with a, esimp, apply ap (fiber.mk (up a)), apply ap_inj' }
end
definition lift_functor2 {A B C : Type} (f : A → B → C) (x : lift A) (y : lift B) : lift C :=
up (f (down x) (down y))
-- is_trunc_lift is defined in init.trunc
definition plift [constructor] (A : pType.{u}) : pType.{max u v} :=
pointed.MK (lift A) (up pt)
definition plift_functor [constructor] {A B : Type*} (f : A →* B) : plift A →* plift B :=
pmap.mk (lift_functor f) (ap up (respect_pt f))
definition pup [constructor] {A : Type*} : A →* plift A :=
pmap.mk up idp
definition pdown [constructor] {A : Type*} : plift A →* A :=
pmap.mk down idp
definition plift_functor_phomotopy [constructor] {A B : Type*} (f : A →* B)
: pdown ∘* plift_functor f ∘* pup ~* f :=
begin
fapply phomotopy.mk,
{ reflexivity},
{ esimp, refine !idp_con ⬝ _, refine _ ⬝ ap02 down !idp_con⁻¹,
refine _ ⬝ !ap_compose, exact !ap_id⁻¹}
end
definition pequiv_plift [constructor] (A : Type*) : A ≃* plift A :=
pequiv_of_equiv (equiv_lift A) idp
definition is_trunc_plift [instance] [priority 1450] (A : Type*) (n : ℕ₋₂)
[H : is_trunc n A] : is_trunc n (plift A) :=
is_trunc_lift A n
end lift
|
5740b6dd2cf173a704fbbb7051dca8d082739168
|
fecda8e6b848337561d6467a1e30cf23176d6ad0
|
/src/category_theory/over.lean
|
a575f4f650eca6ba16a3d7ef3590fcf139754fbe
|
[
"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
| 9,773
|
lean
|
/-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Bhavik Mehta
-/
import category_theory.comma
import category_theory.punit
import category_theory.reflects_isomorphisms
/-!
# Over and under categories
Over (and under) categories are special cases of comma categories.
* If `L` is the identity functor and `R` is a constant functor, then `comma L R` is the "slice" or
"over" category over the object `R` maps to.
* Conversely, if `L` is a constant functor and `R` is the identity functor, then `comma L R` is the
"coslice" or "under" category under the object `L` maps to.
## Tags
comma, slice, coslice, over, under
-/
namespace category_theory
universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {T : Type u₁} [category.{v₁} T]
/--
The over category has as objects arrows in `T` with codomain `X` and as morphisms commutative
triangles.
See https://stacks.math.columbia.edu/tag/001G.
-/
@[derive category]
def over (X : T) := comma.{v₁ 0 v₁} (𝟭 T) (functor.from_punit X)
-- Satisfying the inhabited linter
instance over.inhabited [inhabited T] : inhabited (over (default T)) :=
{ default :=
{ left := default T,
hom := 𝟙 _ } }
namespace over
variables {X : T}
@[ext] lemma over_morphism.ext {X : T} {U V : over X} {f g : U ⟶ V}
(h : f.left = g.left) : f = g :=
by tidy
@[simp] lemma over_right (U : over X) : U.right = punit.star := by tidy
@[simp] lemma id_left (U : over X) : comma_morphism.left (𝟙 U) = 𝟙 U.left := rfl
@[simp] lemma comp_left (a b c : over X) (f : a ⟶ b) (g : b ⟶ c) :
(f ≫ g).left = f.left ≫ g.left := rfl
@[simp, reassoc] lemma w {A B : over X} (f : A ⟶ B) : f.left ≫ B.hom = A.hom :=
by have := f.w; tidy
/-- To give an object in the over category, it suffices to give a morphism with codomain `X`. -/
@[simps]
def mk {X Y : T} (f : Y ⟶ X) : over X :=
{ left := Y, hom := f }
/-- We can set up a coercion from arrows with codomain `X` to `over X`. This most likely should not
be a global instance, but it is sometimes useful. -/
def coe_from_hom {X Y : T} : has_coe (Y ⟶ X) (over X) :=
{ coe := mk }
section
local attribute [instance] coe_from_hom
@[simp] lemma coe_hom {X Y : T} (f : Y ⟶ X) : (f : over X).hom = f := rfl
end
/-- To give a morphism in the over category, it suffices to give an arrow fitting in a commutative
triangle. -/
@[simps]
def hom_mk {U V : over X} (f : U.left ⟶ V.left) (w : f ≫ V.hom = U.hom . obviously) :
U ⟶ V :=
{ left := f }
/--
Construct an isomorphism in the over category given isomorphisms of the objects whose forward
direction gives a commutative triangle.
-/
@[simps {rhs_md:=semireducible}]
def iso_mk {f g : over X} (hl : f.left ≅ g.left) (hw : hl.hom ≫ g.hom = f.hom . obviously) : f ≅ g :=
comma.iso_mk hl (eq_to_iso (subsingleton.elim _ _)) (by simp [hw])
section
variable (X)
/--
The forgetful functor mapping an arrow to its domain.
See https://stacks.math.columbia.edu/tag/001G.
-/
def forget : over X ⥤ T := comma.fst _ _
end
@[simp] lemma forget_obj {U : over X} : (forget X).obj U = U.left := rfl
@[simp] lemma forget_map {U V : over X} {f : U ⟶ V} : (forget X).map f = f.left := rfl
/--
A morphism `f : X ⟶ Y` induces a functor `over X ⥤ over Y` in the obvious way.
See https://stacks.math.columbia.edu/tag/001G.
-/
def map {Y : T} (f : X ⟶ Y) : over X ⥤ over Y := comma.map_right _ $ discrete.nat_trans (λ _, f)
section
variables {Y : T} {f : X ⟶ Y} {U V : over X} {g : U ⟶ V}
@[simp] lemma map_obj_left : ((map f).obj U).left = U.left := rfl
@[simp] lemma map_obj_hom : ((map f).obj U).hom = U.hom ≫ f := rfl
@[simp] lemma map_map_left : ((map f).map g).left = g.left := rfl
/-- Mapping by the identity morphism is just the identity functor. -/
def map_id : map (𝟙 Y) ≅ 𝟭 _ :=
nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy)
/-- Mapping by the composite morphism `f ≫ g` is the same as mapping by `f` then by `g`. -/
def map_comp {Y Z : T} (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map f ⋙ map g :=
nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy)
end
instance forget_reflects_iso : reflects_isomorphisms (forget X) :=
{ reflects := λ Y Z f t, by exactI
{ inv := over.hom_mk t.inv ((as_iso ((forget X).map f)).inv_comp_eq.2 (over.w f).symm) } }
section iterated_slice
variables (f : over X)
/-- Given f : Y ⟶ X, this is the obvious functor from (T/X)/f to T/Y -/
@[simps]
def iterated_slice_forward : over f ⥤ over f.left :=
{ obj := λ α, over.mk α.hom.left,
map := λ α β κ, over.hom_mk κ.left.left (by { rw auto_param_eq, rw ← over.w κ, refl }) }
/-- Given f : Y ⟶ X, this is the obvious functor from T/Y to (T/X)/f -/
@[simps]
def iterated_slice_backward : over f.left ⥤ over f :=
{ obj := λ g, mk (hom_mk g.hom : mk (g.hom ≫ f.hom) ⟶ f),
map := λ g h α, hom_mk (hom_mk α.left (w_assoc α f.hom)) (over_morphism.ext (w α)) }
/-- Given f : Y ⟶ X, we have an equivalence between (T/X)/f and T/Y -/
@[simps]
def iterated_slice_equiv : over f ≌ over f.left :=
{ functor := iterated_slice_forward f,
inverse := iterated_slice_backward f,
unit_iso :=
nat_iso.of_components
(λ g, over.iso_mk (over.iso_mk (iso.refl _) (by tidy)) (by tidy))
(λ X Y g, by { ext, dsimp, simp }),
counit_iso :=
nat_iso.of_components
(λ g, over.iso_mk (iso.refl _) (by tidy))
(λ X Y g, by { ext, dsimp, simp }) }
lemma iterated_slice_forward_forget :
iterated_slice_forward f ⋙ forget f.left = forget f ⋙ forget X :=
rfl
lemma iterated_slice_backward_forget_forget :
iterated_slice_backward f ⋙ forget f ⋙ forget X = forget f.left :=
rfl
end iterated_slice
section
variables {D : Type u₂} [category.{v₂} D]
/-- A functor `F : T ⥤ D` induces a functor `over X ⥤ over (F.obj X)` in the obvious way. -/
@[simps]
def post (F : T ⥤ D) : over X ⥤ over (F.obj X) :=
{ obj := λ Y, mk $ F.map Y.hom,
map := λ Y₁ Y₂ f,
{ left := F.map f.left,
w' := by tidy; erw [← F.map_comp, w] } }
end
end over
/-- The under category has as objects arrows with domain `X` and as morphisms commutative
triangles. -/
@[derive category]
def under (X : T) := comma.{0 v₁ v₁} (functor.from_punit X) (𝟭 T)
-- Satisfying the inhabited linter
instance under.inhabited [inhabited T] : inhabited (under (default T)) :=
{ default :=
{ right := default T,
hom := 𝟙 _ } }
namespace under
variables {X : T}
@[ext] lemma under_morphism.ext {X : T} {U V : under X} {f g : U ⟶ V}
(h : f.right = g.right) : f = g :=
by tidy
@[simp] lemma under_left (U : under X) : U.left = punit.star := by tidy
@[simp] lemma id_right (U : under X) : comma_morphism.right (𝟙 U) = 𝟙 U.right := rfl
@[simp] lemma comp_right (a b c : under X) (f : a ⟶ b) (g : b ⟶ c) :
(f ≫ g).right = f.right ≫ g.right := rfl
@[simp] lemma w {A B : under X} (f : A ⟶ B) : A.hom ≫ f.right = B.hom :=
by have := f.w; tidy
/-- To give an object in the under category, it suffices to give an arrow with domain `X`. -/
@[simps]
def mk {X Y : T} (f : X ⟶ Y) : under X :=
{ right := Y, hom := f }
/-- To give a morphism in the under category, it suffices to give a morphism fitting in a
commutative triangle. -/
@[simps]
def hom_mk {U V : under X} (f : U.right ⟶ V.right) (w : U.hom ≫ f = V.hom . obviously) :
U ⟶ V :=
{ right := f }
/--
Construct an isomorphism in the over category given isomorphisms of the objects whose forward
direction gives a commutative triangle.
-/
def iso_mk {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) : f ≅ g :=
comma.iso_mk (eq_to_iso (subsingleton.elim _ _)) hr (by simp [hw])
@[simp]
lemma iso_mk_hom_right {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) :
(iso_mk hr hw).hom.right = hr.hom := rfl
@[simp]
lemma iso_mk_inv_right {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) :
(iso_mk hr hw).inv.right = hr.inv := rfl
section
variables (X)
/-- The forgetful functor mapping an arrow to its domain. -/
def forget : under X ⥤ T := comma.snd _ _
end
@[simp] lemma forget_obj {U : under X} : (forget X).obj U = U.right := rfl
@[simp] lemma forget_map {U V : under X} {f : U ⟶ V} : (forget X).map f = f.right := rfl
/-- A morphism `X ⟶ Y` induces a functor `under Y ⥤ under X` in the obvious way. -/
def map {Y : T} (f : X ⟶ Y) : under Y ⥤ under X := comma.map_left _ $ discrete.nat_trans (λ _, f)
section
variables {Y : T} {f : X ⟶ Y} {U V : under Y} {g : U ⟶ V}
@[simp] lemma map_obj_right : ((map f).obj U).right = U.right := rfl
@[simp] lemma map_obj_hom : ((map f).obj U).hom = f ≫ U.hom := rfl
@[simp] lemma map_map_right : ((map f).map g).right = g.right := rfl
/-- Mapping by the identity morphism is just the identity functor. -/
def map_id : map (𝟙 Y) ≅ 𝟭 _ :=
nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy)
/-- Mapping by the composite morphism `f ≫ g` is the same as mapping by `f` then by `g`. -/
def map_comp {Y Z : T} (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map g ⋙ map f :=
nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy)
end
section
variables {D : Type u₂} [category.{v₂} D]
/-- A functor `F : T ⥤ D` induces a functor `under X ⥤ under (F.obj X)` in the obvious way. -/
@[simps]
def post {X : T} (F : T ⥤ D) : under X ⥤ under (F.obj X) :=
{ obj := λ Y, mk $ F.map Y.hom,
map := λ Y₁ Y₂ f,
{ right := F.map f.right,
w' := by tidy; erw [← F.map_comp, w] } }
end
end under
end category_theory
|
b368afeb84ac777d889597b39758ac35362cee6d
|
cc5bb0a18c45fa529fc8bf0365b1fbf48464c5a8
|
/library/init/data/int/order.lean
|
4fcad5b7cb2131c632dbe1317b52d1afe2796ff6
|
[
"Apache-2.0"
] |
permissive
|
mk12/lean
|
6bb58b9f3cfe312236b41779478d345399f00918
|
092fc89333160661c4c5a6295f3054cafff4341e
|
refs/heads/master
| 1,609,531,450,083
| 1,501,275,267,000
| 1,501,278,025,000
| 98,760,144
| 0
| 0
| null | 1,501,364,485,000
| 1,501,364,485,000
| null |
UTF-8
|
Lean
| false
| false
| 13,012
|
lean
|
/-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
The order relation on the integers.
-/
prelude
import init.data.int.basic
namespace int
private def nonneg (a : ℤ) : Prop := int.cases_on a (assume n, true) (assume n, false)
protected def le (a b : ℤ) : Prop := nonneg (b - a)
instance : has_le int := ⟨int.le⟩
protected def lt (a b : ℤ) : Prop := (a + 1) ≤ b
instance : has_lt int := ⟨int.lt⟩
private def decidable_nonneg (a : ℤ) : decidable (nonneg a) :=
int.cases_on a (assume a, decidable.true) (assume a, decidable.false)
instance decidable_le (a b : ℤ) : decidable (a ≤ b) := decidable_nonneg _
instance decidable_lt (a b : ℤ) : decidable (a < b) := decidable_nonneg _
lemma lt_iff_add_one_le (a b : ℤ) : a < b ↔ a + 1 ≤ b := iff.refl _
private lemma nonneg.elim {a : ℤ} : nonneg a → ∃ n : ℕ, a = n :=
int.cases_on a (assume n H, exists.intro n rfl) (assume n', false.elim)
private lemma nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) :=
int.cases_on a (assume n, or.inl trivial) (assume n, or.inr trivial)
lemma le.intro_sub {a b : ℤ} {n : ℕ} (h : b - a = n) : a ≤ b :=
show nonneg (b - a), by rw h; trivial
lemma le.intro {a b : ℤ} {n : ℕ} (h : a + n = b) : a ≤ b :=
le.intro_sub (by rw [← h]; simp)
lemma le.dest_sub {a b : ℤ} (h : a ≤ b) : ∃ n : ℕ, b - a = n := nonneg.elim h
lemma le.dest {a b : ℤ} (h : a ≤ b) : ∃ n : ℕ, a + n = b :=
match (le.dest_sub h) with
| ⟨n, h₁⟩ := exists.intro n begin rw [← h₁, add_comm], simp end
end
lemma le.elim {a b : ℤ} (h : a ≤ b) {P : Prop} (h' : ∀ n : ℕ, a + ↑n = b → P) : P :=
exists.elim (le.dest h) h'
protected lemma le_total (a b : ℤ) : a ≤ b ∨ b ≤ a :=
or.imp_right
(assume H : nonneg (-(b - a)),
have -(b - a) = a - b, by simp,
show nonneg (a - b), from this ▸ H)
(nonneg_or_nonneg_neg (b - a))
lemma coe_nat_le_coe_nat_of_le {m n : ℕ} (h : m ≤ n) : (↑m : ℤ) ≤ ↑n :=
match nat.le.dest h with
| ⟨k, (hk : m + k = n)⟩ := le.intro (begin rw [← hk], reflexivity end)
end
lemma le_of_coe_nat_le_coe_nat {m n : ℕ} (h : (↑m : ℤ) ≤ ↑n) : m ≤ n :=
le.elim h (assume k, assume hk : ↑m + ↑k = ↑n,
have m + k = n, from int.coe_nat_inj ((int.coe_nat_add m k).trans hk),
nat.le.intro this)
lemma coe_nat_le_coe_nat_iff (m n : ℕ) : (↑m : ℤ) ≤ ↑n ↔ m ≤ n :=
iff.intro le_of_coe_nat_le_coe_nat coe_nat_le_coe_nat_of_le
lemma coe_zero_le (n : ℕ) : 0 ≤ (↑n : ℤ) :=
coe_nat_le_coe_nat_of_le n.zero_le
lemma eq_coe_of_zero_le {a : ℤ} (h : 0 ≤ a) : ∃ n : ℕ, a = n :=
by have t := le.dest_sub h; simp at t; exact t
lemma eq_succ_of_zero_lt {a : ℤ} (h : 0 < a) : ∃ n : ℕ, a = n.succ :=
let ⟨n, (h : ↑(1+n) = a)⟩ := le.dest h in
⟨n, by rw add_comm at h; exact h.symm⟩
lemma lt_add_succ (a : ℤ) (n : ℕ) : a < a + ↑(nat.succ n) :=
le.intro (show a + 1 + n = a + nat.succ n, begin simp [int.coe_nat_eq], reflexivity end)
lemma lt.intro {a b : ℤ} {n : ℕ} (h : a + nat.succ n = b) : a < b :=
h ▸ lt_add_succ a n
lemma lt.dest {a b : ℤ} (h : a < b) : ∃ n : ℕ, a + ↑(nat.succ n) = b :=
le.elim h (assume n, assume hn : a + 1 + n = b,
exists.intro n begin rw [← hn, add_assoc, add_comm (1 : int)], reflexivity end)
lemma lt.elim {a b : ℤ} (h : a < b) {P : Prop} (h' : ∀ n : ℕ, a + ↑(nat.succ n) = b → P) : P :=
exists.elim (lt.dest h) h'
lemma coe_nat_lt_coe_nat_iff (n m : ℕ) : (↑n : ℤ) < ↑m ↔ n < m :=
begin rw [lt_iff_add_one_le, ← int.coe_nat_succ, coe_nat_le_coe_nat_iff], reflexivity end
lemma lt_of_coe_nat_lt_coe_nat {m n : ℕ} (h : (↑m : ℤ) < ↑n) : m < n :=
(coe_nat_lt_coe_nat_iff _ _).mp h
lemma coe_nat_lt_coe_nat_of_lt {m n : ℕ} (h : m < n) : (↑m : ℤ) < ↑n :=
(coe_nat_lt_coe_nat_iff _ _).mpr h
/- show that the integers form an ordered additive group -/
protected lemma le_refl (a : ℤ) : a ≤ a :=
le.intro (add_zero a)
protected lemma le_trans {a b c : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ c) : a ≤ c :=
le.elim h₁ (assume n, assume hn : a + n = b,
le.elim h₂ (assume m, assume hm : b + m = c,
begin apply le.intro, rw [← hm, ← hn, add_assoc], reflexivity end))
protected lemma le_antisymm {a b : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ a) : a = b :=
le.elim h₁ (assume n, assume hn : a + n = b,
le.elim h₂ (assume m, assume hm : b + m = a,
have a + ↑(n + m) = a + 0, by rw [int.coe_nat_add, ← add_assoc, hn, hm, add_zero a],
have (↑(n + m) : ℤ) = 0, from add_left_cancel this,
have n + m = 0, from int.coe_nat_inj this,
have n = 0, from nat.eq_zero_of_add_eq_zero_right this,
show a = b, begin rw [← hn, this, int.coe_nat_zero, add_zero a] end))
protected lemma lt_irrefl (a : ℤ) : ¬ a < a :=
assume : a < a,
lt.elim this (assume n, assume hn : a + nat.succ n = a,
have a + nat.succ n = a + 0, by rw [hn, add_zero],
have nat.succ n = 0, from int.coe_nat_inj (add_left_cancel this),
show false, from nat.succ_ne_zero _ this)
protected lemma ne_of_lt {a b : ℤ} (h : a < b) : a ≠ b :=
(assume : a = b, absurd (begin rewrite this at h, exact h end) (int.lt_irrefl b))
lemma le_of_lt {a b : ℤ} (h : a < b) : a ≤ b :=
lt.elim h (assume n, assume hn : a + nat.succ n = b, le.intro hn)
protected lemma lt_iff_le_and_ne (a b : ℤ) : a < b ↔ (a ≤ b ∧ a ≠ b) :=
iff.intro
(assume h, ⟨le_of_lt h, int.ne_of_lt h⟩)
(assume ⟨aleb, aneb⟩,
le.elim aleb (assume n, assume hn : a + n = b,
have n ≠ 0,
from (assume : n = 0, aneb begin rw [← hn, this, int.coe_nat_zero, add_zero] end),
have n = nat.succ (nat.pred n),
from eq.symm (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero this)),
lt.intro (begin rewrite this at hn, exact hn end)))
protected lemma le_iff_lt_or_eq (a b : ℤ) : a ≤ b ↔ (a < b ∨ a = b) :=
iff.intro
(assume h,
decidable.by_cases
(assume : a = b, or.inr this)
(assume : a ≠ b,
le.elim h (assume n, assume hn : a + n = b,
have n ≠ 0, from
(assume : n = 0, ‹a ≠ b› begin rw [← hn, this, int.coe_nat_zero, add_zero] end),
have n = nat.succ (nat.pred n),
from eq.symm (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero this)),
or.inl (lt.intro (begin rewrite this at hn, exact hn end)))))
(assume h,
or.elim h
(assume h', le_of_lt h')
(assume h', h' ▸ int.le_refl a))
lemma lt_succ (a : ℤ) : a < a + 1 :=
int.le_refl (a + 1)
protected lemma add_le_add_left {a b : ℤ} (h : a ≤ b) (c : ℤ) : c + a ≤ c + b :=
le.elim h (assume n, assume hn : a + n = b,
le.intro (show c + a + n = c + b, begin rw [add_assoc, hn] end))
protected lemma add_lt_add_left {a b : ℤ} (h : a < b) (c : ℤ) : c + a < c + b :=
iff.mpr (int.lt_iff_le_and_ne _ _)
(and.intro
(int.add_le_add_left (le_of_lt h) _)
(assume heq, int.lt_irrefl b begin rw add_left_cancel heq at h, exact h end))
protected lemma mul_nonneg {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b :=
le.elim ha (assume n, assume hn,
le.elim hb (assume m, assume hm,
le.intro (show 0 + ↑n * ↑m = a * b, begin rw [← hn, ← hm], repeat {rw zero_add} end)))
protected lemma mul_pos {a b : ℤ} (ha : 0 < a) (hb : 0 < b) : 0 < a * b :=
lt.elim ha (assume n, assume hn,
lt.elim hb (assume m, assume hm,
lt.intro (show 0 + ↑(nat.succ (nat.succ n * m + n)) = a * b,
begin rw [← hn, ← hm], repeat {rw int.coe_nat_zero}, simp,
rw [← int.coe_nat_mul], simp [nat.mul_succ, nat.succ_add] end)))
protected lemma zero_lt_one : (0 : ℤ) < 1 := trivial
protected lemma not_le_of_gt {a b : ℤ} (h : a < b) : ¬ b ≤ a :=
assume hba : b ≤ a,
have a = b, from int.le_antisymm (le_of_lt h) hba,
show false, from int.lt_irrefl b (begin rw this at h, exact h end)
protected lemma lt_of_lt_of_le {a b c : ℤ} (hab : a < b) (hbc : b ≤ c) : a < c :=
have hac : a ≤ c, from int.le_trans (le_of_lt hab) hbc,
iff.mpr
(int.lt_iff_le_and_ne _ _)
(and.intro hac (assume heq, int.not_le_of_gt (by rwa [← heq]) hbc))
protected lemma lt_of_le_of_lt {a b c : ℤ} (hab : a ≤ b) (hbc : b < c) : a < c :=
have hac : a ≤ c, from int.le_trans hab (le_of_lt hbc),
iff.mpr
(int.lt_iff_le_and_ne _ _)
(and.intro hac (assume heq, int.not_le_of_gt begin rw heq, exact hbc end hab))
instance : decidable_linear_ordered_comm_ring int :=
{ int.comm_ring with
le := int.le,
le_refl := int.le_refl,
le_trans := @int.le_trans,
le_antisymm := @int.le_antisymm,
lt := int.lt,
le_of_lt := @int.le_of_lt,
lt_of_lt_of_le := @int.lt_of_lt_of_le,
lt_of_le_of_lt := @int.lt_of_le_of_lt,
lt_irrefl := int.lt_irrefl,
add_le_add_left := @int.add_le_add_left,
add_lt_add_left := @int.add_lt_add_left,
zero_ne_one := zero_ne_one,
mul_nonneg := @int.mul_nonneg,
mul_pos := @int.mul_pos,
le_iff_lt_or_eq := int.le_iff_lt_or_eq,
le_total := int.le_total,
zero_lt_one := int.zero_lt_one,
decidable_eq := int.decidable_eq,
decidable_le := int.decidable_le,
decidable_lt := int.decidable_lt }
instance : decidable_linear_ordered_comm_group int :=
by apply_instance
lemma eq_nat_abs_of_zero_le {a : ℤ} (h : 0 ≤ a) : a = nat_abs a :=
let ⟨n, e⟩ := eq_coe_of_zero_le h in by rw e; refl
lemma le_nat_abs {a : ℤ} : a ≤ nat_abs a :=
or.elim (le_total 0 a)
(λh, by rw eq_nat_abs_of_zero_le h; refl)
(λh, le_trans h (coe_zero_le _))
lemma neg_succ_lt_zero (n : ℕ) : -[1+ n] < 0 :=
lt_of_not_ge $ λ h, let ⟨m, h⟩ := eq_coe_of_zero_le h in by contradiction
lemma eq_neg_succ_of_lt_zero : ∀ {a : ℤ}, a < 0 → ∃ n : ℕ, a = -[1+ n]
| (n : ℕ) h := absurd h (not_lt_of_ge (coe_zero_le _))
| -[1+ n] h := ⟨n, rfl⟩
/- more facts specific to int -/
theorem of_nat_nonneg (n : ℕ) : 0 ≤ of_nat n := trivial
theorem coe_succ_pos (n : nat) : (nat.succ n : ℤ) > 0 :=
coe_nat_lt_coe_nat_of_lt (nat.succ_pos _)
theorem exists_eq_neg_of_nat {a : ℤ} (H : a ≤ 0) : ∃n : ℕ, a = -n :=
let ⟨n, h⟩ := eq_coe_of_zero_le (neg_nonneg_of_nonpos H) in
⟨n, eq_neg_of_eq_neg h.symm⟩
theorem nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : (nat_abs a : ℤ) = a :=
match a, eq_coe_of_zero_le H with ._, ⟨n, rfl⟩ := rfl end
theorem of_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : (nat_abs a : ℤ) = -a :=
by rw [← nat_abs_neg, nat_abs_of_nonneg (neg_nonneg_of_nonpos H)]
theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a
| (n : ℕ) := abs_of_nonneg $ coe_zero_le _
| -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _
theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a :=
by rw [abs_eq_nat_abs]; refl
theorem lt_of_add_one_le {a b : ℤ} (H : a + 1 ≤ b) : a < b := H
theorem add_one_le_of_lt {a b : ℤ} (H : a < b) : a + 1 ≤ b := H
theorem lt_add_one_of_le {a b : ℤ} (H : a ≤ b) : a < b + 1 :=
add_le_add_right H 1
theorem le_of_lt_add_one {a b : ℤ} (H : a < b + 1) : a ≤ b :=
le_of_add_le_add_right H
theorem sub_one_le_of_lt {a b : ℤ} (H : a ≤ b) : a - 1 < b :=
sub_right_lt_of_lt_add $ lt_add_one_of_le H
theorem lt_of_sub_one_le {a b : ℤ} (H : a - 1 < b) : a ≤ b :=
le_of_lt_add_one $ lt_add_of_sub_right_lt H
theorem le_sub_one_of_lt {a b : ℤ} (H : a < b) : a ≤ b - 1 :=
le_sub_right_of_add_le H
theorem lt_of_le_sub_one {a b : ℤ} (H : a ≤ b - 1) : a < b :=
add_le_of_le_sub_right H
theorem sign_of_succ (n : nat) : sign (nat.succ n) = 1 := rfl
theorem sign_eq_one_of_pos {a : ℤ} (h : 0 < a) : sign a = 1 :=
match a, eq_succ_of_zero_lt h with ._, ⟨n, rfl⟩ := rfl end
theorem sign_eq_neg_one_of_neg {a : ℤ} (h : a < 0) : sign a = -1 :=
match a, eq_neg_succ_of_lt_zero h with ._, ⟨n, rfl⟩ := rfl end
lemma eq_zero_of_sign_eq_zero : Π {a : ℤ}, sign a = 0 → a = 0
| 0 _ := rfl
theorem pos_of_sign_eq_one : ∀ {a : ℤ}, sign a = 1 → 0 < a
| (n+1:ℕ) _ := coe_nat_lt_coe_nat_of_lt (nat.succ_pos _)
theorem neg_of_sign_eq_neg_one : ∀ {a : ℤ}, sign a = -1 → a < 0
| (n+1:ℕ) h := match h with end
| 0 h := match h with end
| -[1+ n] _ := neg_succ_lt_zero _
theorem sign_eq_one_iff_pos (a : ℤ) : sign a = 1 ↔ 0 < a :=
⟨pos_of_sign_eq_one, sign_eq_one_of_pos⟩
theorem sign_eq_neg_one_iff_neg (a : ℤ) : sign a = -1 ↔ a < 0 :=
⟨neg_of_sign_eq_neg_one, sign_eq_neg_one_of_neg⟩
theorem sign_eq_zero_iff_zero (a : ℤ) : sign a = 0 ↔ a = 0 :=
⟨eq_zero_of_sign_eq_zero, λ h, by rw [h, sign_zero]⟩
theorem sign_mul_abs (a : ℤ) : sign a * abs a = a :=
by rw [abs_eq_nat_abs, sign_mul_nat_abs]
theorem eq_one_of_mul_eq_self_left {a b : ℤ} (Hpos : a ≠ 0) (H : b * a = a) : b = 1 :=
eq_of_mul_eq_mul_right Hpos (by rw [one_mul, H])
theorem eq_one_of_mul_eq_self_right {a b : ℤ} (Hpos : b ≠ 0) (H : b * a = b) : a = 1 :=
eq_of_mul_eq_mul_left Hpos (by rw [mul_one, H])
end int
|
4ef45ed77a3cdfb1a2628f7282273d165f4e9a66
|
423cba856b0cf4755b74f3fea3f0a0c5656379fd
|
/src/pipes/tactic.lean
|
856d7200f9c588d973b9f5d31c62c02ee75b1086
|
[] |
no_license
|
cipher1024/lean-pipes
|
e221aafa8f127ab8f2dabe12897427eefd762b36
|
3db1d792b987113b07578f21de26c23826809e0c
|
refs/heads/master
| 1,609,627,565,606
| 1,526,931,011,000
| 1,526,931,011,000
| 99,382,224
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 662
|
lean
|
namespace tactic
open lean.parser interactive interactive.types
open tactic.interactive (generalize cases_arg_p)
local postfix `?`:9000 := optional
local postfix `*`:9000 := many
lemma cast_eq_of_heq {α β} {x : α} {y : β}
(h : α = β)
(h' : cast h x = y)
: x == y :=
by { subst β, subst y, symmetry, simp [cast_heq] }
meta def elim_cast (e : parse texpr) (n : parse (tk "with" *> ident)) : tactic unit :=
do let h : name := ("H" ++ n.to_string : string),
interactive.generalize h () (``(cast _ %%e), n),
asm ← get_local h,
to_expr ``(cast_eq_of_heq _ %%asm) >>= note h none,
clear asm
run_cmd add_interactive [`elim_cast]
end tactic
|
89fb1f5931e9397195fd645dcabe027170014db7
|
74addaa0e41490cbaf2abd313a764c96df57b05d
|
/Mathlib/number_theory/primorial.lean
|
c12caa9bf03502a468b4f056f6e1f95ffbc43116
|
[] |
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,435
|
lean
|
/-
Copyright (c) 2020 Patrick Stevens. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Stevens
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.ring_exp
import Mathlib.data.nat.parity
import Mathlib.data.nat.choose.sum
import Mathlib.PostPort
namespace Mathlib
/-!
# Primorial
This file defines the primorial function (the product of primes less than or equal to some bound),
and proves that `primorial n ≤ 4 ^ n`.
## Notations
We use the local notation `n#` for the primorial of `n`: that is, the product of the primes less
than or equal to `n`.
-/
/-- The primorial `n#` of `n` is the product of the primes less than or equal to `n`.
-/
def primorial (n : ℕ) : ℕ :=
finset.prod (finset.filter nat.prime (finset.range (n + 1))) fun (p : ℕ) => p
theorem primorial_succ {n : ℕ} (n_big : 1 < n) (r : n % bit0 1 = 1) : primorial (n + 1) = primorial n := sorry
theorem dvd_choose_of_middling_prime (p : ℕ) (is_prime : nat.prime p) (m : ℕ) (p_big : m + 1 < p) (p_small : p ≤ bit0 1 * m + 1) : p ∣ nat.choose (bit0 1 * m + 1) (m + 1) := sorry
theorem prod_primes_dvd {s : finset ℕ} (n : ℕ) (h : ∀ (a : ℕ), a ∈ s → nat.prime a) (div : ∀ (a : ℕ), a ∈ s → a ∣ n) : (finset.prod s fun (p : ℕ) => p) ∣ n := sorry
theorem primorial_le_4_pow (n : ℕ) : primorial n ≤ bit0 (bit0 1) ^ n := sorry
|
71135d17fc27614fe867317ee4645eb2af1a5b65
|
2d34dfb0a1cc250584282618dc10ea03d3fa858e
|
/src/for_mathlib/free_abelian_group.lean
|
d175eac349143e3110a1af43906e860d1cbfea98
|
[] |
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
| 12,305
|
lean
|
import group_theory.free_abelian_group
import data.finsupp.basic
noncomputable theory
open_locale big_operators
namespace int
variables {A : Type*} [add_comm_group A]
def cast_add_hom' (a : A) : ℤ →+ A :=
add_monoid_hom.mk' (λ n, n • a) $ λ m n, add_smul _ _ _
@[simp] lemma cast_add_hom'_apply (a : A) (n : ℤ) : cast_add_hom' a n = n • a := rfl
end int
namespace free_abelian_group
variables (X : Type*)
def to_finsupp : free_abelian_group X →+ (X →₀ ℤ) :=
free_abelian_group.lift $ λ x, finsupp.single x 1
def from_finsupp : (X →₀ ℤ) →+ free_abelian_group X :=
finsupp.lift_add_hom $ λ x, @int.cast_add_hom' (free_abelian_group X) _ (of x)
@[simp] lemma from_finsupp_comp_single_add_hom (x : X) :
(from_finsupp X).comp (finsupp.single_add_hom x) =
@int.cast_add_hom' (free_abelian_group X) _ (of x) :=
begin
ext,
simp only [add_monoid_hom.coe_comp, finsupp.single_add_hom_apply, function.comp_app,
one_smul, int.cast_add_hom'_apply, from_finsupp, finsupp.lift_add_hom_apply_single]
end
@[simp] lemma to_finsupp_comp_from_finsupp :
(to_finsupp X).comp (from_finsupp X) = add_monoid_hom.id _ :=
begin
ext x y, simp only [add_monoid_hom.id_comp],
rw [add_monoid_hom.comp_assoc, from_finsupp_comp_single_add_hom],
simp only [to_finsupp, add_monoid_hom.coe_comp, finsupp.single_add_hom_apply,
function.comp_app, one_smul, lift.of, int.cast_add_hom'_apply],
end
@[simp] lemma from_finsupp_comp_to_finsupp :
(from_finsupp X).comp (to_finsupp X) = add_monoid_hom.id _ :=
begin
ext,
simp only [from_finsupp, to_finsupp, finsupp.lift_add_hom_apply_single, add_monoid_hom.coe_comp,
function.comp_app, one_smul, add_monoid_hom.id_apply, lift.of, int.cast_add_hom'_apply]
end
variable {X}
@[simp] lemma to_finsupp_of (x : X) :
to_finsupp X (of x) = finsupp.single x 1 :=
by simp only [to_finsupp, lift.of]
@[simp] lemma to_finsupp_from_finsupp (f) :
(to_finsupp X) (from_finsupp X f) = f :=
by rw [← add_monoid_hom.comp_apply, to_finsupp_comp_from_finsupp, add_monoid_hom.id_apply]
@[simp] lemma from_finsupp_to_finsupp (x) :
(from_finsupp X) (to_finsupp X x) = x :=
by rw [← add_monoid_hom.comp_apply, from_finsupp_comp_to_finsupp, add_monoid_hom.id_apply]
variable (X)
@[simps]
def equiv_finsupp : free_abelian_group X ≃+ (X →₀ ℤ) :=
{ to_fun := to_finsupp X,
inv_fun := from_finsupp X,
left_inv := from_finsupp_to_finsupp,
right_inv := to_finsupp_from_finsupp,
map_add' := (to_finsupp X).map_add }
variable {X}
def coeff (x : X) : free_abelian_group X →+ ℤ :=
(finsupp.apply_add_hom x).comp (to_finsupp X)
def support (a : free_abelian_group X) : finset X :=
(to_finsupp X a).support
lemma mem_support_iff (x : X) (a : free_abelian_group X) :
x ∈ a.support ↔ coeff x a ≠ 0 :=
by { rw [support, finsupp.mem_support_iff], exact iff.rfl }
lemma not_mem_support_iff (x : X) (a : free_abelian_group X) :
x ∉ a.support ↔ coeff x a = 0 :=
by { rw [support, finsupp.not_mem_support_iff], exact iff.rfl }
@[simp] lemma support_zero : support (0 : free_abelian_group X) = ∅ :=
by simp only [support, finsupp.support_zero, add_monoid_hom.map_zero]
@[simp] lemma support_of (x : X) : support (of x) = {x} :=
by simp only [support, to_finsupp_of, finsupp.support_single_ne_zero (one_ne_zero)]
@[simp] lemma support_neg (a : free_abelian_group X) : support (-a) = support a :=
by simp only [support, add_monoid_hom.map_neg, finsupp.support_neg]
@[simp] lemma support_gsmul (k : ℤ) (h : k ≠ 0) (a : free_abelian_group X) :
support (k •ℤ a) = support a :=
begin
ext x,
simp only [mem_support_iff, add_monoid_hom.map_gsmul],
simp only [h, gsmul_int_int, false_or, ne.def, mul_eq_zero]
end
@[simp] lemma support_smul (k : ℤ) (h : k ≠ 0) (a : free_abelian_group X) :
support (k • a) = support a :=
by rw [← gsmul_eq_smul, support_gsmul k h]
@[simp] lemma support_smul_nat (k : ℕ) (h : k ≠ 0) (a : free_abelian_group X) :
support (k • a) = support a :=
by { apply support_smul k _ a, exact_mod_cast h }
open_locale classical
lemma support_add (a b : free_abelian_group X) : (support (a + b)) ⊆ a.support ∪ b.support :=
begin
simp only [support, add_monoid_hom.map_add],
apply finsupp.support_add
end
lemma support_add_smul_of (a : free_abelian_group X) (n : ℤ) (hn : n ≠ 0)
(x : X) (hxa : x ∉ a.support) :
support (a + n • of x) = insert x a.support :=
begin
apply finset.subset.antisymm,
{ apply finset.subset.trans (support_add _ _),
intros y,
simp only [finset.mem_union, finset.mem_insert, support_smul n hn, support_of, or_comm (y = x),
finset.mem_singleton, imp_self] },
{ intros y,
simp only [finset.mem_insert],
rintro (rfl|hya),
{ rw not_mem_support_iff at hxa,
simp only [coeff, add_monoid_hom.coe_comp, finsupp.apply_add_hom_apply,
function.comp_app] at hxa,
simp only [support, add_monoid_hom.map_add, pi.add_apply, finsupp.mem_support_iff,
ne.def, finsupp.coe_add, hxa, zero_add, ← gsmul_eq_smul, add_monoid_hom.map_gsmul,
to_finsupp_of],
rw [← finsupp.single_add_hom_apply, ← add_monoid_hom.map_gsmul, gsmul_one],
simpa only [int.cast_id, finsupp.single_eq_same, finsupp.single_add_hom_apply] },
{ rw not_mem_support_iff at hxa,
rw mem_support_iff at hya,
simp only [coeff, add_monoid_hom.coe_comp, finsupp.apply_add_hom_apply,
function.comp_app, ne.def] at hxa hya,
simp only [support, add_monoid_hom.map_add, pi.add_apply, finsupp.mem_support_iff,
ne.def, finsupp.coe_add, ← gsmul_eq_smul, add_monoid_hom.map_gsmul, to_finsupp_of],
rwa [← finsupp.single_add_hom_apply, ← add_monoid_hom.map_gsmul, gsmul_one,
finsupp.single_add_hom_apply, finsupp.single_apply, if_neg, add_zero],
rintro rfl, contradiction } }
end
lemma support_sum (s : finset X) (n : X → ℤ) :
(support (∑ x in s, n x • of x)) ⊆ s :=
begin
apply finset.induction_on s,
{ simp only [finset.empty_subset, finset.sum_empty, support_zero] },
intros x s hxs IH,
rw finset.sum_insert hxs,
apply finset.subset.trans (support_add _ _),
by_cases hn : n x = 0,
{ simp only [hn, finset.empty_union, zero_smul, support_zero],
apply finset.subset.trans IH (finset.subset_insert x s) },
rw [support_smul _ hn, support_of],
intros y hy,
simp only [finset.mem_union, finset.mem_singleton] at hy,
simp only [finset.mem_insert],
apply or.imp id _ hy,
intro h, exact IH h
end
@[simp] lemma coeff_of_self (x : X) : coeff x (of x) = 1 :=
by simp only [coeff, add_monoid_hom.coe_comp, finsupp.apply_add_hom_apply,
finsupp.single_eq_same, function.comp_app, to_finsupp_of]
lemma sum_support_coeff (a : free_abelian_group X) :
∑ x in a.support, coeff x a • (of x) = a :=
begin
apply (equiv_finsupp X).injective,
simp only [equiv_finsupp_apply],
rw [← finsupp.sum_single (to_finsupp X a), finsupp.sum],
simp only [(to_finsupp X).map_sum, ← gsmul_eq_smul, add_monoid_hom.map_gsmul, to_finsupp_of],
apply finset.sum_congr rfl,
intros x hx,
simp only [← finsupp.single_add_hom_apply, ← add_monoid_hom.map_gsmul, gsmul_one, coeff,
int.cast_id, add_monoid_hom.comp_apply, finsupp.apply_add_hom_apply]
end
-- probably needs a better name
@[elab_as_eliminator] protected lemma induction_on''
{P : free_abelian_group X → Prop}
(a : free_abelian_group X)
(h0 : P 0)
(h1 : ∀ (n:ℤ) (h : n ≠ 0) x, P (n • of x))
(h2 : ∀ (a : free_abelian_group X) (n : ℤ) (hn : n ≠ 0) (x : X) (h : x ∉ a.support),
P a → (∀ (n:ℤ), P (n • of x)) → P (a + n • of x)) :
P a :=
begin
rw ← sum_support_coeff a,
generalize hs : a.support = s,
classical,
apply finset.induction_on s; clear_dependent s,
{ simpa only [finset.sum_empty] },
intros x s hxs IH,
rw [finset.sum_insert hxs, add_comm],
by_cases hxa : coeff x a = 0,
{ rw [hxa, zero_smul, add_zero], exact IH },
apply h2 _ _ hxa _ _ IH,
{ intro n, by_cases hn : n = 0, { rwa [hn, zero_smul] }, exact h1 n hn x },
contrapose! hxs,
apply support_sum _ _ hxs
end
/-- A `free_predicate` on a free abelian group is a predicate that cuts out a subgroup
generated by a subset of the generators of the free abelian group. -/
def free_predicate (Q : free_abelian_group X → Prop) :=
∀ a : free_abelian_group X, Q a ↔ ∀ x ∈ a.support, Q (of x)
namespace free_predicate
variables {Q : free_abelian_group X → Prop} {a b : free_abelian_group X}
lemma zero (h : free_predicate Q) : Q 0 :=
begin
rw h,
simp only [finset.not_mem_empty, forall_prop_of_false,
not_false_iff, support_zero, forall_true_iff]
end
lemma add (h : free_predicate Q) (ha : Q a) (hb : Q b) : Q (a + b) :=
begin
rw h at ha hb ⊢,
intros x hx,
replace hx := support_add _ _ hx,
simp only [finset.mem_union] at hx,
cases hx; solve_by_elim
end
lemma neg (h : free_predicate Q) (ha : Q a) : Q (-a) :=
begin
rw h at ha ⊢,
intros x hx,
rw support_neg at hx,
solve_by_elim
end
lemma neg_iff (h : free_predicate Q) : Q (-a) ↔ Q a :=
⟨λ ha, by simpa only [neg_neg] using h.neg ha, h.neg⟩
def add_subgroup (h : free_predicate Q) : add_subgroup (free_abelian_group X) :=
{ carrier := {a | Q a},
zero_mem' := h.zero,
add_mem' := λ a b ha hb, h.add ha hb,
neg_mem' := λ a ha, h.neg ha }
lemma gsmul (h : free_predicate Q) (n : ℤ) (ha : Q a) : Q (n •ℤ a) :=
add_subgroup.gsmul_mem h.add_subgroup ha n
lemma of_gsmul (h : free_predicate Q) (n : ℤ) (hn : n ≠ 0) (ha : Q (n •ℤ a)) : Q a :=
by { rw h at ha ⊢, simpa only [support_gsmul n hn] using ha }
lemma gsmul_iff (h : free_predicate Q) (n : ℤ) (hn : n ≠ 0) : Q (n •ℤ a) ↔ Q a :=
⟨h.of_gsmul n hn, h.gsmul n⟩
lemma smul (h : free_predicate Q) (n : ℤ) (ha : Q a) : Q (n • a) :=
by { rw ← gsmul_eq_smul, apply h.gsmul _ ha }
lemma of_smul (h : free_predicate Q) (n : ℤ) (hn : n ≠ 0) (ha : Q (n • a)) : Q a :=
by rwa [← gsmul_eq_smul, h.gsmul_iff n hn] at ha
lemma smul_iff (h : free_predicate Q) (n : ℤ) (hn : n ≠ 0) : Q (n • a) ↔ Q a :=
⟨h.of_smul n hn, h.smul n⟩
lemma smul_nat (h : free_predicate Q) (n : ℕ) (ha : Q a) : Q (n • a) :=
h.smul n ha
lemma of_smul_nat (h : free_predicate Q) (n : ℕ) (hn : n ≠ 0) (ha : Q (n • a)) : Q a :=
h.of_smul n (by exact_mod_cast hn) ha
lemma smul_nat_iff (h : free_predicate Q) (n : ℕ) (hn : n ≠ 0) : Q (n • a) ↔ Q a :=
⟨h.of_smul_nat n hn, h.smul_nat n⟩
end free_predicate
-- probably needs a better name
@[elab_as_eliminator] protected lemma induction_on_free_predicate
{P : free_abelian_group X → Prop}
(Q : free_abelian_group X → Prop)
(hQ : free_predicate Q)
(a : free_abelian_group X)
(hQa : Q a)
(hP0 : P 0)
(hof : ∀ x, Q (of x) → P (of x))
(hneg : ∀ a, Q a → P a → P (-a))
(hadd : ∀ a b, Q a → Q b → P a → P b → P (a + b)) :
P a :=
begin
revert hQa,
have N : ∀ (n:ℕ) x, Q (n • of x) → P (n • of x),
{ intros n x,
induction n with n ih,
{ intro, exact hP0 },
{ intro hQx,
have hQ1x : Q (of x) := hQ.of_smul_nat n.succ n.succ_ne_zero hQx,
have hQnx : Q (n • of x) := hQ.smul_nat n hQ1x,
rw [nat.succ_eq_add_one, add_smul, one_smul],
apply hadd _ _ hQnx hQ1x (ih hQnx) (hof _ hQ1x) } },
apply free_abelian_group.induction_on'' a,
{ intro, exact hP0 },
{ intros n hn x,
cases le_or_lt 0 n with h0n hn0,
{ lift n to ℕ using h0n, apply N },
{ have h0n : 0 ≤ -n, { rw [neg_nonneg], exact hn0.le },
lift -n to ℕ using h0n with k hk,
intro hQx,
have hQ1x : Q (of x) := hQ.of_smul n hn hQx,
rw [← neg_neg n, neg_smul],
apply hneg _ (hQ.smul _ hQ1x),
rw ← hk,
exact N _ _ (hQ.smul_nat k hQ1x) } },
{ intros a n hn x hxa IH1 IH2 hq,
have hQa : Q a,
{ rw hQ at hq ⊢, intros x hxa', apply hq, rw support_add_smul_of _ _ hn _ hxa,
apply finset.mem_insert_of_mem hxa' },
have hQx : Q (of x),
{ rw hQ at hq ⊢, intros x' hxa', apply hq, rw support_add_smul_of _ _ hn _ hxa,
rw [support_of, finset.mem_singleton] at hxa', subst hxa',
apply finset.mem_insert_self },
exact hadd _ _ hQa (hQ.smul n hQx) (IH1 hQa) (IH2 n (hQ.smul n hQx)) }
end
end free_abelian_group
|
475960cbc2772c4bdfd3d3ee6d513747173272cc
|
c46a31beec236d29b6c02e7d7683691bcfbb3014
|
/src/utils/cmp.lean
|
3001e1915acfdc54b4ba7cd0d4914cea0220fe6d
|
[] |
no_license
|
UVM-M52/quiz-5-maddiestrauss
|
a88b9bfbdd486a521ee280f9b7b551bcb48f23c6
|
214529615e08bbcdd3d6600c89432ec985e6ba3a
|
refs/heads/master
| 1,617,897,187,103
| 1,584,922,038,000
| 1,584,922,038,000
| 248,787,429
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 5,905
|
lean
|
section
variables {α : Type*} [semiring α]
theorem mul_two_eq_add_self (x : α) : x * 2 = x + x :=
show x * (1 + 1) = x + x, by rw [mul_add, mul_one]
theorem two_mul_eq_add_self (x : α) : 2 * x = x + x :=
show (1 + 1) * x = x + x, by rw [add_mul, one_mul]
end
namespace linear_ordered_ring
variables (α : Type*) [i : linear_ordered_ring α]
include i
lemma one_pos : (0:α) < 1 := zero_lt_one α
lemma two_pos : (0:α) < 2 := _root_.add_pos (one_pos α) (one_pos α)
variable {α}
lemma add_pos (x y : α) : 0 < x → 0 < y → 0 < x + y := _root_.add_pos
lemma succ_pos (x : α) : 0 < x → 0 < x + 1 := λ h, add_pos x 1 h (one_pos α)
-- linear_ordered_ring.mul_pos (x y : α) : 0 < x → 0 < y → 0 < x * y
lemma bit0_pos (x : α) : 0 < x → 0 < bit0 x := λ h, add_pos x x h h
lemma bit1_pos (x : α) : 0 < x → 0 < bit1 x := λ h, succ_pos (bit0 x) (bit0_pos x h)
class num_pos (x : α) := (elim : (0:α) < x)
namespace num_pos
variable {i}
@[priority 30] instance one : @num_pos α i (1:α) := ⟨one_pos α⟩
@[priority 30] instance two : @num_pos α i (2:α) := ⟨two_pos α⟩
@[priority 30] instance bit0 (x : α) [@num_pos α i x] : @num_pos α i (bit0 x) := ⟨bit0_pos x (elim x)⟩
@[priority 30] instance bit1 (x : α) [@num_pos α i x] : @num_pos α i (bit1 x) := ⟨bit1_pos x (elim x)⟩
@[priority 10] instance succ (x : α) [@num_pos α i x] : @num_pos α i (x+1) := ⟨succ_pos x (elim x)⟩
@[priority 20] instance add (x y : α) [@num_pos α i x] [@num_pos α i y] : @num_pos α i (x + y) := ⟨add_pos x y (elim x) (elim y)⟩
@[priority 30] instance mul (x y : α) [@num_pos α i x] [@num_pos α i y] : @num_pos α i (x * y) := ⟨mul_pos x y (elim x) (elim y)⟩
end num_pos
end linear_ordered_ring
theorem pos_trivial {α : Type*} [linear_ordered_ring α] (x : α) [linear_ordered_ring.num_pos x] : (0:α) < x := linear_ordered_ring.num_pos.elim x
section
variables {α : Type*} [linear_ordered_ring α]
theorem le_of_mul_ge_mul_left {a b c : α} : c * b ≤ c * a → c < 0 → a ≤ b :=
begin
intros h hc,
have hc : -c > 0 := neg_pos_of_neg hc,
apply le_of_mul_le_mul_left _ hc,
apply le_of_neg_le_neg,
rw [neg_mul_eq_neg_mul, neg_mul_eq_neg_mul, neg_neg],
assumption,
end
theorem le_of_mul_ge_mul_right {a b c : α} : b * c ≤ a * c → c < 0 → a ≤ b :=
begin
intros h hc,
have hc : -c > 0 := neg_pos_of_neg hc,
apply le_of_mul_le_mul_right _ hc,
apply le_of_neg_le_neg,
rw [neg_mul_eq_mul_neg, neg_mul_eq_mul_neg, neg_neg],
assumption,
end
end
section
variables {α : Type*} [linear_ordered_field α]
theorem div_le_of_le_mul_of_pos {x y : α} (z : α) : x ≤ y*z → 0 < z → x/z ≤ y :=
begin
intros hm hz,
apply le_of_mul_le_mul_right _ hz,
transitivity x,
{ apply le_of_eq,
apply div_mul_cancel,
apply ne_of_gt,
assumption },
{ assumption },
end
theorem le_div_of_mul_le_of_pos {x y : α} (z : α) : x*z ≤ y → 0 < z → x ≤ y/z :=
begin
intros hm hz,
apply le_of_mul_le_mul_right _ hz,
transitivity y,
{ assumption },
{ apply le_of_eq,
symmetry,
apply div_mul_cancel,
apply ne_of_gt,
assumption },
end
theorem le_div_of_mul_ge_of_neg {x y : α} (z : α) : y ≤ x*z → z < 0 → x ≤ y/z :=
begin
intros hm hz,
apply le_of_mul_ge_mul_right _ hz,
transitivity y,
{ apply le_of_eq,
apply div_mul_cancel,
apply ne_of_lt,
assumption },
{ assumption },
end
theorem div_le_of_ge_mul_of_neg {x y : α} (z : α) : y*z ≤ x → z < 0 → x/z ≤ y :=
begin
intros hm hz,
apply le_of_mul_ge_mul_right _ hz,
transitivity x,
{ assumption },
{ apply le_of_eq,
symmetry,
apply div_mul_cancel,
apply ne_of_lt,
assumption },
end
end
namespace order
inductive {u} lt_cmp {α : Type u} [has_lt α] (x y : α) : Type u
| eq : x = y → lt_cmp
| lt : x < y → lt_cmp
| gt : y < x → lt_cmp
inductive {u} le_cmp {α : Type u} [has_le α] (x y : α) : Type u
| le : x ≤ y → le_cmp
| ge : y ≤ x → le_cmp
variables {α : Type*} [decidable_linear_order α]
def lt_compare (x y : α) : lt_cmp x y :=
if hlt : x < y then
lt_cmp.lt hlt
else if hgt : y < x then
lt_cmp.gt hgt
else
lt_cmp.eq $ le_antisymm (le_of_not_gt hgt) (le_of_not_gt hlt)
def le_compare (x y : α) : le_cmp x y :=
if h : x < y then
le_cmp.le (le_of_lt h)
else
le_cmp.ge (le_of_not_gt h)
@[elab_as_eliminator]
def trichotomy_on (x y : α) {C : Sort*} : (x = y → C) → (x < y → C) → (y < x → C) → C :=
λ heq hlt hgt, lt_cmp.cases_on (lt_compare x y) heq hlt hgt
@[elab_as_eliminator]
def dichotomy_on (x y : α) {C : Sort*} : (x ≤ y → C) → (y ≤ x → C) → C :=
λ hle hge, le_cmp.cases_on (le_compare x y) hle hge
end order
namespace tactic
open interactive
/--
`by_trichotomy (x, y)` splits the goal into three branches, the first assuming `x = y`,
the second assuming `x < y` and the third assuming `y < x`.
This tactic requires that terms `x` and `y` have the same type and that this type has
`decidable_linear_order` instance.
-/
meta def interactive.by_trichotomy : parse types.texpr → tactic unit :=
λ e, do {
`(@prod.mk %%t %%.(t) %%x %%y) ← to_expr e,
d ← to_expr ``(decidable_linear_order %%t) >>= mk_instance
<|> fail ("cannot find decidable_linear_order instance for type " ++ to_string t),
to_expr ``(@order.trichotomy_on %%t %%d %%x %%y) >>= apply >> skip
}
/--
`by_trichotomy (x, y)` splits the goal into two branches, the first assuming `x ≤ y`
and the second assuming `y ≤ x`.
This tactic requires that terms `x` and `y` have the same type and that this type has
`decidable_linear_order` instance.
-/
meta def interactive.by_dichotomy : parse types.texpr → tactic unit :=
λ e, do {
`(@prod.mk %%t %%.(t) %%x %%y) ← to_expr e,
d ← to_expr ``(decidable_linear_order %%t) >>= mk_instance
<|> fail ("cannot find decidable_linear_order instance for " ++ to_string t),
to_expr ``(@order.dichotomy_on %%t %%d %%x %%y) >>= apply >> skip
}
end tactic
|
f57cf1ec28cb7dab958bd480612701237fdb69e6
|
297c4ceafbbaed2a59b6215504d09e6bf201a2ee
|
/finset/to_set.lean
|
e5b18fffda5e39f702c14c8d08171515bef8de6e
|
[] |
no_license
|
minchaowu/Kruskal.lean3
|
559c91b82033ce44ea61593adcec9cfff725c88d
|
a14516f47b21e636e9df914fc6ebe64cbe5cd38d
|
refs/heads/master
| 1,611,010,001,429
| 1,497,935,421,000
| 1,497,935,421,000
| 82,000,982
| 1
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 4,476
|
lean
|
import .logic .comb
open set classical
namespace finset
variable {A : Type}
variable [deceq : decidable_eq A]
definition to_set (s : finset A) : set A := λx, x ∈ s
-- def ts := @to_set A
instance finset_to_set_coe : has_coe (finset A) (set A) := ⟨to_set⟩
variables (s t : finset A) (x y : A)
theorem mem_eq_mem_to_set : x ∈ s = (x ∈ to_set s) := rfl
definition to_set.inj {s₁ s₂ : finset A} : to_set s₁ = to_set s₂ → s₁ = s₂ :=
λ h, ext (λ a, iff.of_eq (calc
(a ∈ s₁) = (a ∈ to_set s₁) : mem_eq_mem_to_set _ _
... = (a ∈ to_set s₂) : by rw -h
... = (a ∈ s₂) : mem_eq_mem_to_set _ _))
-- A example
theorem mem_to_set_empty : (set.mem x (to_set empty)) = (mem x empty) := rfl
theorem to_set_empty : to_set empty = (∅:set A) := rfl
-- theorem mem_to_set_univ [h : fintype A] : (x ∈ to_set univ) = (x ∈ set.univ) :=
-- propext (iff.intro (assume H, trivial) (assume H, !mem_univ))
-- theorem to_set_univ [h : fintype A] : to_set univ = (set.univ : set A) := funext (λ x, !mem_to_set_univ)
-- instance : has_subset (finset A) := ⟨finset.subset⟩
theorem mem_to_set_upto (x n : ℕ) : x ∈ to_set (upto n) = (x ∈ {a | a < n}) := mem_upto_eq _ _
theorem to_set_upto (n : ℕ) : to_set (upto n) = {a | a < n} := funext (λ x, mem_to_set_upto _ _)
include deceq
theorem mem_to_set_insert : x ∈ insert y s = (x ∈ set.insert y s) := mem_insert_eq _ _ _
theorem to_set_insert : (set.insert y (to_set s)) = to_set (insert y s) := funext (λ x, eq.symm (mem_to_set_insert _ _ _))
theorem mem_to_set_union : x ∈ s ∪ t = (x ∈ to_set s ∪ to_set t) := mem_union_eq _ _ _
theorem to_set_union : to_set (s ∪ t) = to_set s ∪ to_set t := funext (λ x, mem_to_set_union _ _ _)
theorem mem_to_set_inter : x ∈ s ∩ t = (x ∈ to_set s ∩ to_set t) := mem_inter_eq _ _ _
theorem to_set_inter : to_set (s ∩ t) = to_set s ∩ to_set t := funext (λ x, mem_to_set_inter _ _ _)
theorem mem_to_set_diff : x ∈ s \ t = (x ∈ to_set s \ to_set t) := mem_diff_eq _ _ _
theorem to_set_diff : to_set (s \ t) = to_set s \ to_set t := funext (λ x, mem_to_set_diff _ _ _)
theorem mem_to_set_sep (p : A → Prop) [h : decidable_pred p] : x ∈ sep p s = (x ∈ set.sep p s) :=
finset.mem_sep_eq _ _
theorem to_set_sep (p : A → Prop) [h : decidable_pred p] : to_set (sep p s) = set.sep p (to_set s) :=
funext (λ x, mem_to_set_sep _ _ _)
theorem mem_to_set_image {B : Type} [h : decidable_eq B] (f : A → B) {s : finset A} {y : B} :
y ∈ image f s = (y ∈ set.image f s) := mem_image_eq _
theorem to_set_image {B : Type} [h : decidable_eq B] (f : A → B) (s : finset A) :
to_set (image f s) = set.image f (to_set s) := funext (λ x, mem_to_set_image _)
/- relations -/
attribute [instance]
definition decidable_mem_to_set (x : A) (s : finset A) : decidable (x ∈ to_set s) :=
decidable_of_decidable_of_eq (decidable_mem _ _) (mem_eq_mem_to_set _ _)
theorem eq_of_to_set_eq_to_set {s t : finset A} (H : to_set s = to_set t) : s = t :=
to_set.inj H
theorem eq_eq_to_set_eq : (s = t) = (to_set s = to_set t) :=
propext (iff.intro (assume H, H ▸ rfl) eq_of_to_set_eq_to_set)
-- #check quot.has_decidable_eq
attribute [instance]
definition decidable_to_set_eq (s t : finset A) : decidable (to_set s = to_set t) :=
decidable_of_decidable_of_eq (has_decidable_eq _ _) (eq_eq_to_set_eq _ _)
theorem subset_eq_to_set_subset (s t : finset A) : (s ⊆ t) = (to_set s ⊆ to_set t) :=
propext (iff.intro
(assume H, take x xs, mem_of_subset_of_mem H xs)
(assume H, subset_of_forall H))
-- attribute [instance]
-- definition decidable_subset [h : decidable_eq A] : ∀ (s t: finset A), decidable (s ⊆ t) :=
-- sorry
-- definition decidable_to_set_subset (s t : finset A) : decidable (to_set s ⊆ to_set t) :=
-- decidable_of_decidable_of_eq (decidable_subset _ _) (subset_eq_to_set_subset _ _)
/- bounded quantifiers -/
-- definition decidable_bounded_forall (s : finset A) (p : A → Prop) [h : decidable_pred p] :
-- decidable (∀ x ∈ to_set s, p x) :=
-- decidable_of_decidable_of_iff _ !all_iff_forall
-- definition decidable_bounded_existo_set (s : finset A) (p : A → Prop) [h : decidable_pred p] :
-- decidable (∃₀ x ∈ to_set s, p x) :=
-- decidable_of_decidable_of_iff _ !any_iff_exists
/- properties -/
-- theorem inj_on_to_set {B : Type} [h : decidable_eq B] (f : A → B) (s : finset A) :
-- inj_on f s = inj_on f (to_set s) :=
-- rfl
end finset
|
8d7b9b046dc074cf5e730a8277a2f028f9179cf3
|
fa02ed5a3c9c0adee3c26887a16855e7841c668b
|
/src/data/pequiv.lean
|
e83da726cc7faf5c73c2d0adf05125f95af6ff82
|
[
"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
| 12,894
|
lean
|
/-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import data.set.lattice
/-!
# Partial Equivalences
In this file, we define partial equivalences `pequiv`, which are a bijection between a subset of `α`
and a subset of `β`. Notationally, a `pequiv` is denoted by "`≃.`" (note that the full stop is part
of the notation). The way we store these internally is with two functions `f : α → option β` and
the reverse function `g : β → option α`, with the condition that if `f a` is `option.some b`,
then `g b` is `option.some a`.
## Main results
- `pequiv.of_set`: creates a `pequiv` from a set `s`,
which sends an element to itself if it is in `s`.
- `pequiv.single`: given two elements `a : α` and `b : β`, create a `pequiv` that sends them to
each other, and ignores all other elements.
- `pequiv.injective_of_forall_ne_is_some`/`injective_of_forall_is_some`: If the domain of a `pequiv`
is all of `α` (except possibly one point), its `to_fun` is injective.
## Canonical order
`pequiv` is canonically ordered by inclusion; that is, if a function `f` defined on a subset `s`
is equal to `g` on that subset, but `g` is also defined on a larger set, then `f ≤ g`. We also have
a definition of `⊥`, which is the empty `pequiv` (sends all to `none`), which in the end gives us a
`semilattice_inf_bot` instance.
## Tags
pequiv, partial equivalence
-/
universes u v w x
/-- A `pequiv` is a partial equivalence, a representation of a bijection between a subset
of `α` and a subset of `β` -/
structure pequiv (α : Type u) (β : Type v) :=
(to_fun : α → option β)
(inv_fun : β → option α)
(inv : ∀ (a : α) (b : β), a ∈ inv_fun b ↔ b ∈ to_fun a)
infixr ` ≃. `:25 := pequiv
namespace pequiv
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
open function option
instance : has_coe_to_fun (α ≃. β) := ⟨_, to_fun⟩
@[simp] lemma coe_mk_apply (f₁ : α → option β) (f₂ : β → option α) (h) (x : α) :
(pequiv.mk f₁ f₂ h : α → option β) x = f₁ x := rfl
@[ext] lemma ext : ∀ {f g : α ≃. β} (h : ∀ x, f x = g x), f = g
| ⟨f₁, f₂, hf⟩ ⟨g₁, g₂, hg⟩ h :=
have h : f₁ = g₁, from funext h,
have ∀ b, f₂ b = g₂ b,
begin
subst h,
assume b,
have hf := λ a, hf a b,
have hg := λ a, hg a b,
cases h : g₂ b with a,
{ simp only [h, option.not_mem_none, false_iff] at hg,
simp only [hg, iff_false] at hf,
rwa [option.eq_none_iff_forall_not_mem] },
{ rw [← option.mem_def, hf, ← hg, h, option.mem_def] }
end,
by simp [*, funext_iff]
lemma ext_iff {f g : α ≃. β} : f = g ↔ ∀ x, f x = g x :=
⟨congr_fun ∘ congr_arg _, ext⟩
@[refl] protected def refl (α : Type*) : α ≃. α :=
{ to_fun := some,
inv_fun := some,
inv := λ _ _, eq_comm }
@[symm] protected def symm (f : α ≃. β) : β ≃. α :=
{ to_fun := f.2,
inv_fun := f.1,
inv := λ _ _, (f.inv _ _).symm }
lemma mem_iff_mem (f : α ≃. β) : ∀ {a : α} {b : β}, a ∈ f.symm b ↔ b ∈ f a := f.3
lemma eq_some_iff (f : α ≃. β) : ∀ {a : α} {b : β}, f.symm b = some a ↔ f a = some b := f.3
@[trans] protected def trans (f : α ≃. β) (g : β ≃. γ) : pequiv α γ :=
{ to_fun := λ a, (f a).bind g,
inv_fun := λ a, (g.symm a).bind f.symm,
inv := λ a b, by simp [*, and.comm, eq_some_iff f, eq_some_iff g] at * }
@[simp] lemma refl_apply (a : α) : pequiv.refl α a = some a := rfl
@[simp] lemma symm_refl : (pequiv.refl α).symm = pequiv.refl α := rfl
@[simp] lemma symm_symm (f : α ≃. β) : f.symm.symm = f := by cases f; refl
lemma symm_injective : function.injective (@pequiv.symm α β) :=
left_inverse.injective symm_symm
lemma trans_assoc (f : α ≃. β) (g : β ≃. γ) (h : γ ≃. δ) :
(f.trans g).trans h = f.trans (g.trans h) :=
ext (λ _, option.bind_assoc _ _ _)
lemma mem_trans (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) :
c ∈ f.trans g a ↔ ∃ b, b ∈ f a ∧ c ∈ g b := option.bind_eq_some'
lemma trans_eq_some (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) :
f.trans g a = some c ↔ ∃ b, f a = some b ∧ g b = some c := option.bind_eq_some'
lemma trans_eq_none (f : α ≃. β) (g : β ≃. γ) (a : α) :
f.trans g a = none ↔ (∀ b c, b ∉ f a ∨ c ∉ g b) :=
begin
simp only [eq_none_iff_forall_not_mem, mem_trans, imp_iff_not_or.symm],
push_neg, tauto
end
@[simp] lemma refl_trans (f : α ≃. β) : (pequiv.refl α).trans f = f :=
by ext; dsimp [pequiv.trans]; refl
@[simp] lemma trans_refl (f : α ≃. β) : f.trans (pequiv.refl β) = f :=
by ext; dsimp [pequiv.trans]; simp
protected lemma inj (f : α ≃. β) {a₁ a₂ : α} {b : β} (h₁ : b ∈ f a₁) (h₂ : b ∈ f a₂) : a₁ = a₂ :=
by rw ← mem_iff_mem at *; cases h : f.symm b; simp * at *
/-- If the domain of a `pequiv` is `α` except a point, its forward direction is injective. -/
lemma injective_of_forall_ne_is_some (f : α ≃. β) (a₂ : α)
(h : ∀ (a₁ : α), a₁ ≠ a₂ → is_some (f a₁)) : injective f :=
has_left_inverse.injective
⟨λ b, option.rec_on b a₂ (λ b', option.rec_on (f.symm b') a₂ id),
λ x, begin
classical,
cases hfx : f x,
{ have : x = a₂, from not_imp_comm.1 (h x) (hfx.symm ▸ by simp), simp [this] },
{ simp only [hfx], rw [(eq_some_iff f).2 hfx], refl }
end⟩
/-- If the domain of a `pequiv` is all of `α`, its forward direction is injective. -/
lemma injective_of_forall_is_some {f : α ≃. β}
(h : ∀ (a : α), is_some (f a)) : injective f :=
(classical.em (nonempty α)).elim
(λ hn, injective_of_forall_ne_is_some f (classical.choice hn)
(λ a _, h a))
(λ hn x, (hn ⟨x⟩).elim)
section of_set
variables (s : set α) [decidable_pred s]
/-- Creates a `pequiv` that is the identity on `s`, and `none` outside of it. -/
def of_set (s : set α) [decidable_pred s] : α ≃. α :=
{ to_fun := λ a, if a ∈ s then some a else none,
inv_fun := λ a, if a ∈ s then some a else none,
inv := λ a b, by split_ifs; finish [eq_comm] }
lemma mem_of_set_self_iff {s : set α} [decidable_pred s] {a : α} : a ∈ of_set s a ↔ a ∈ s :=
by dsimp [of_set]; split_ifs; simp *
lemma mem_of_set_iff {s : set α} [decidable_pred s] {a b : α} : a ∈ of_set s b ↔ a = b ∧ a ∈ s :=
by dsimp [of_set]; split_ifs; split; finish
@[simp] lemma of_set_eq_some_iff {s : set α} {h : decidable_pred s} {a b : α} :
of_set s b = some a ↔ a = b ∧ a ∈ s := mem_of_set_iff
@[simp] lemma of_set_eq_some_self_iff {s : set α} {h : decidable_pred s} {a : α} :
of_set s a = some a ↔ a ∈ s := mem_of_set_self_iff
@[simp] lemma of_set_symm : (of_set s).symm = of_set s := rfl
@[simp] lemma of_set_univ : of_set set.univ = pequiv.refl α := rfl
@[simp] lemma of_set_eq_refl {s : set α} [decidable_pred s] :
of_set s = pequiv.refl α ↔ s = set.univ :=
⟨λ h, begin
rw [set.eq_univ_iff_forall],
intro,
rw [← mem_of_set_self_iff, h],
exact rfl
end, λ h, by simp only [of_set_univ.symm, h]; congr⟩
end of_set
lemma symm_trans_rev (f : α ≃. β) (g : β ≃. γ) : (f.trans g).symm = g.symm.trans f.symm := rfl
lemma trans_symm (f : α ≃. β) : f.trans f.symm = of_set {a | (f a).is_some} :=
begin
ext,
dsimp [pequiv.trans],
simp only [eq_some_iff f, option.is_some_iff_exists, option.mem_def, bind_eq_some',
of_set_eq_some_iff],
split,
{ rintros ⟨b, hb₁, hb₂⟩,
exact ⟨pequiv.inj _ hb₂ hb₁, b, hb₂⟩ },
{ simp {contextual := tt} }
end
lemma symm_trans (f : α ≃. β) : f.symm.trans f = of_set {b | (f.symm b).is_some} :=
symm_injective $ by simp [symm_trans_rev, trans_symm, -symm_symm]
lemma trans_symm_eq_iff_forall_is_some {f : α ≃. β} :
f.trans f.symm = pequiv.refl α ↔ ∀ a, is_some (f a) :=
by rw [trans_symm, of_set_eq_refl, set.eq_univ_iff_forall]; refl
instance : has_bot (α ≃. β) :=
⟨{ to_fun := λ _, none,
inv_fun := λ _, none,
inv := by simp }⟩
@[simp] lemma bot_apply (a : α) : (⊥ : α ≃. β) a = none := rfl
@[simp] lemma symm_bot : (⊥ : α ≃. β).symm = ⊥ := rfl
@[simp] lemma trans_bot (f : α ≃. β) : f.trans (⊥ : β ≃. γ) = ⊥ :=
by ext; dsimp [pequiv.trans]; simp
@[simp] lemma bot_trans (f : β ≃. γ) : (⊥ : α ≃. β).trans f = ⊥ :=
by ext; dsimp [pequiv.trans]; simp
lemma is_some_symm_get (f : α ≃. β) {a : α} (h : is_some (f a)) :
is_some (f.symm (option.get h)) :=
is_some_iff_exists.2 ⟨a, by rw [f.eq_some_iff, some_get]⟩
section single
variables [decidable_eq α] [decidable_eq β] [decidable_eq γ]
/-- Create a `pequiv` which sends `a` to `b` and `b` to `a`, but is otherwise `none`. -/
def single (a : α) (b : β) : α ≃. β :=
{ to_fun := λ x, if x = a then some b else none,
inv_fun := λ x, if x = b then some a else none,
inv := λ _ _, by simp; split_ifs; cc }
lemma mem_single (a : α) (b : β) : b ∈ single a b a := if_pos rfl
lemma mem_single_iff (a₁ a₂ : α) (b₁ b₂ : β) : b₁ ∈ single a₂ b₂ a₁ ↔ a₁ = a₂ ∧ b₁ = b₂ :=
by dsimp [single]; split_ifs; simp [*, eq_comm]
@[simp] lemma symm_single (a : α) (b : β) : (single a b).symm = single b a := rfl
@[simp] lemma single_apply (a : α) (b : β) : single a b a = some b := if_pos rfl
lemma single_apply_of_ne {a₁ a₂ : α} (h : a₁ ≠ a₂) (b : β) : single a₁ b a₂ = none := if_neg h.symm
lemma single_trans_of_mem (a : α) {b : β} {c : γ} {f : β ≃. γ} (h : c ∈ f b) :
(single a b).trans f = single a c :=
begin
ext,
dsimp [single, pequiv.trans],
split_ifs; simp * at *
end
lemma trans_single_of_mem {a : α} {b : β} (c : γ) {f : α ≃. β} (h : b ∈ f a) :
f.trans (single b c) = single a c :=
symm_injective $ single_trans_of_mem _ ((mem_iff_mem f).2 h)
@[simp]
lemma single_trans_single (a : α) (b : β) (c : γ) : (single a b).trans (single b c) = single a c :=
single_trans_of_mem _ (mem_single _ _)
@[simp] lemma single_subsingleton_eq_refl [subsingleton α] (a b : α) : single a b = pequiv.refl α :=
begin
ext i j,
dsimp [single],
rw [if_pos (subsingleton.elim i a), subsingleton.elim i j, subsingleton.elim b j]
end
lemma trans_single_of_eq_none {b : β} (c : γ) {f : δ ≃. β} (h : f.symm b = none) :
f.trans (single b c) = ⊥ :=
begin
ext,
simp only [eq_none_iff_forall_not_mem, option.mem_def, f.eq_some_iff] at h,
dsimp [pequiv.trans, single],
simp,
intros,
split_ifs;
simp * at *
end
lemma single_trans_of_eq_none (a : α) {b : β} {f : β ≃. δ} (h : f b = none) :
(single a b).trans f = ⊥ :=
symm_injective $ trans_single_of_eq_none _ h
lemma single_trans_single_of_ne {b₁ b₂ : β} (h : b₁ ≠ b₂) (a : α) (c : γ) :
(single a b₁).trans (single b₂ c) = ⊥ :=
single_trans_of_eq_none _ (single_apply_of_ne h.symm _)
end single
section order
instance : partial_order (α ≃. β) :=
{ le := λ f g, ∀ (a : α) (b : β), b ∈ f a → b ∈ g a,
le_refl := λ _ _ _, id,
le_trans := λ f g h fg gh a b, (gh a b) ∘ (fg a b),
le_antisymm := λ f g fg gf, ext begin
assume a,
cases h : g a with b,
{ exact eq_none_iff_forall_not_mem.2
(λ b hb, option.not_mem_none b $ h ▸ fg a b hb) },
{ exact gf _ _ h }
end }
lemma le_def {f g : α ≃. β} : f ≤ g ↔ (∀ (a : α) (b : β), b ∈ f a → b ∈ g a) := iff.rfl
instance : order_bot (α ≃. β) :=
{ bot_le := λ _ _ _ h, (not_mem_none _ h).elim,
..pequiv.partial_order,
..pequiv.has_bot }
instance [decidable_eq α] [decidable_eq β] : semilattice_inf_bot (α ≃. β) :=
{ inf := λ f g,
{ to_fun := λ a, if f a = g a then f a else none,
inv_fun := λ b, if f.symm b = g.symm b then f.symm b else none,
inv := λ a b, begin
have := @mem_iff_mem _ _ f a b,
have := @mem_iff_mem _ _ g a b,
split_ifs; finish
end },
inf_le_left := λ _ _ _ _, by simp; split_ifs; cc,
inf_le_right := λ _ _ _ _, by simp; split_ifs; cc,
le_inf := λ f g h fg gh a b, begin
have := fg a b,
have := gh a b,
simp [le_def],
split_ifs; finish
end,
..pequiv.order_bot }
end order
end pequiv
namespace equiv
variables {α : Type*} {β : Type*} {γ : Type*}
/-- Turns an `equiv` into a `pequiv` of the whole type. -/
def to_pequiv (f : α ≃ β) : α ≃. β :=
{ to_fun := some ∘ f,
inv_fun := some ∘ f.symm,
inv := by simp [equiv.eq_symm_apply, eq_comm] }
@[simp] lemma to_pequiv_refl : (equiv.refl α).to_pequiv = pequiv.refl α := rfl
lemma to_pequiv_trans (f : α ≃ β) (g : β ≃ γ) : (f.trans g).to_pequiv =
f.to_pequiv.trans g.to_pequiv := rfl
lemma to_pequiv_symm (f : α ≃ β) : f.symm.to_pequiv = f.to_pequiv.symm := rfl
lemma to_pequiv_apply (f : α ≃ β) (x : α) : f.to_pequiv x = some (f x) := rfl
end equiv
|
77d4bfd3d944cc7979166314a8d1eee333376089
|
12dabd587ce2621d9a4eff9f16e354d02e206c8e
|
/world06/level02.lean
|
d913a782cd2039254116011c506f7824bf51bda6
|
[] |
no_license
|
abdelq/natural-number-game
|
a1b5b8f1d52625a7addcefc97c966d3f06a48263
|
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
|
refs/heads/master
| 1,668,606,478,691
| 1,594,175,058,000
| 1,594,175,058,000
| 278,673,209
| 0
| 1
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 67
|
lean
|
lemma imp_self (P : Prop) : P → P :=
begin
intro p,
exact p,
end
|
8fef5465e0694ad94f0006cd1db82a3c04a5c96a
|
28d9ae48dddad2ebe8cb28027b15e9c9d996e0ed
|
/src/pos_num.lean
|
04f3b64b6ed44dbbbddef347c0e3779d27971177
|
[] |
no_license
|
ImperialCollegeLondon/british-natural-number-game
|
0f76ac920488db62b3d391bd60d650e725f90938
|
593dede2c911e0651b8d177365180b659d7b2acf
|
refs/heads/master
| 1,669,990,486,571
| 1,596,886,731,000
| 1,596,886,731,000
| 285,931,256
| 4
| 1
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 31,720
|
lean
|
-- `pos_num` -- the British Natural Numbers.
-- The same as pnat
/- todo --
make nicer recursor to get less `one` and more `1`.
le world
add docstrings
add questions (these are solutions)
-/
import tactic
namespace xena
-- should be elsewhere
-- pnat inductive principle
@[elab_as_eliminator] def pnat'.induction {C : ℕ → Prop} {n : ℕ} (hn : n ≠ 0) (h1 : C 1)
(IH : ∀ d, C d → C (d + 1)) : C n :=
begin
cases n, cases hn rfl, clear hn,
induction n with d hd, assumption,
apply IH,
assumption,
end
/-- The type of positive binary numbers.
13 = 1101(base 2) = bit1 (bit0 (bit1 one)) -/
@[derive has_reflect, derive decidable_eq]
inductive pos_num : Type
| one : pos_num
| bit1 : pos_num → pos_num
| bit0 : pos_num → pos_num
notation `ℙ` := pos_num
namespace pos_num
-- there is no interface relating one, bit0 and bit1.
-- notation for 1
instance : has_one ℙ := ⟨pos_num.one⟩
-- the default natural
def thirty_seven := bit1 (bit0 (bit1 (bit0 (bit0 (one)))))
-- the naturals are nonempty
instance : inhabited ℙ := ⟨thirty_seven⟩
-- this interface for rec is just to make stuff work under the hood.
/-
using 'exit' to interrupt Lean
-/
--#check @pos_num.rec
-- if you are interested.
@[simp] lemma rec_one (C : ℙ → Type) (x : C 1) (h1 : Π (a : ℙ), C a → C (bit1 a))
(h0 : Π (a : ℙ), C a → C (bit0 a)) : (pos_num.rec x h1 h0 1 : C 1) = x := rfl
@[simp] lemma rec_one' (C : ℙ → Type) (x : C 1) (h1 : Π (a : ℙ), C a → C (bit1 a))
(h0 : Π (a : ℙ), C a → C (bit0 a)) : (pos_num.rec x h1 h0 one : C one) = x := rfl
@[simp] lemma rec_bit0 (C : ℙ → Type) (x : C 1) (h1 : Π (a : ℙ), C a → C (bit1 a))
(h0 : Π (a : ℙ), C a → C (bit0 a)) (p : ℙ) :
(pos_num.rec x h1 h0 (bit0 p) : C (bit0 p)) = h0 p (pos_num.rec x h1 h0 p) := rfl
@[simp] lemma rec_bit1 (C : ℙ → Type) (x : C 1) (h1 : Π (a : ℙ), C a → C (bit1 a))
(h0 : Π (a : ℙ), C a → C (bit0 a)) (p : ℙ) :
(pos_num.rec x h1 h0 (bit1 p) : C (bit1 p)) = h1 p (pos_num.rec x h1 h0 p) := rfl
/-! # Succ -/
-- we define `succ` and its interface with the three constructors.
def succ : ℙ → ℙ
| 1 := bit0 one
| (bit1 n) := bit0 (succ n)
| (bit0 n) := bit1 n
@[simp] lemma succ_one : succ 1 = bit0 1 := rfl
@[simp] lemma succ_bit1 (n : ℙ) : succ (bit1 n) = bit0 (succ n) := rfl
@[simp] lemma succ_bit0 (n : ℙ) : succ (bit0 n) = bit1 n := rfl
/-! # Addition -/
-- computer scientists want this definition
/-- addition on ℙ -/
protected def add : ℙ → ℙ → ℙ
| 1 b := succ b
| a 1 := succ a
| (bit0 a) (bit0 b) := bit0 (add a b)
| (bit1 a) (bit1 b) := bit0 (succ (add a b))
| (bit0 a) (bit1 b) := bit1 (add a b)
| (bit1 a) (bit0 b) := bit1 (add a b)
-- I don't need succ, I want + to be the primitive object
-- because it has more symmetries
-- My proposed definition of addition is below
/--
latexdef $ (+) : \P^2 \to \P $
| 1 1 := bit0 1
| 1 (bit0 b) := bit1 b
| 1 (bit1 b) := bit0 (1 + b)
| (bit0 a) 1 := bit1 a
| (bit0 a) (bit0 b) := bit0 (a + b)
| (bit0 a) (bit1 b) := bit1 (a + b)
| (bit1 a) 1 := bit1 (a + 1)
| (bit1 a) (bit0 b) := bit1 (a + b)
-- Now for the last one.
-- when I do the carry one, in exactly
-- what order do I add the carry 1 to the
-- two digits in the next column?
-- This way is is "add like normal, but then don't forget to add on
-- the carry one after"
| (bit1 a) (bit1 b) := bit0 ((a + b) + 1)
-/
instance : has_add ℙ := ⟨pos_num.add⟩
-- I will make the mathematician's recursor in a minute.
-- First let's do some easier stuff relating succ and addition.
-- addition and succ
@[simp] lemma add_one_eq_succ (a : ℙ) : a + 1 = succ a :=
begin
cases a; refl
end
@[simp] lemma add_one_eq_succ' (a : ℙ) : a + one = succ a :=
add_one_eq_succ a
@[simp] lemma one_add_eq_succ (a : ℙ) : 1 + a = succ a :=
begin
cases a; refl
end
@[simp] lemma one_add_eq_succ' (a : ℙ) : one + a = succ a :=
one_add_eq_succ a
/-! # Mathematician's interface to addition -/
@[simp] lemma one_add_one : 1 + 1 = bit0 1 := rfl
@[simp] lemma one_add_bit0 (p : ℙ) :
1 + bit0 p = bit1 p := rfl
@[simp] lemma one_add_bit0' (p : ℙ) :
one + bit0 p = bit1 p := rfl
@[simp] lemma one_add_bit1 (p : ℙ) :
(1 : ℙ) + (bit1 p) = bit0 (1 + p) :=
begin
change succ (bit1 p) = _,
unfold succ,
congr,
simp,
end
@[simp] lemma one_add_bit1' (p : ℙ) :
one + bit1 p = bit0 (1 + p) := one_add_bit1 p
@[simp] lemma bit0_add_one (a : ℙ) : (bit0 a) + 1 = bit1 a := rfl
@[simp] lemma bit0_add_one' (a : ℙ) : (bit0 a) + one = bit1 a := rfl
@[simp] lemma bit1_add_one (a : ℙ) : (bit1 a) + 1 = bit0 (a + 1) :=
begin
show succ (bit1 a) = _,
unfold succ,
simp,
end
@[simp] lemma bit1_add_one' (a : ℙ) : (bit1 a) + one = bit0 (a + one) :=
bit1_add_one a
@[simp] lemma bit0_add_bit0 (a b : ℙ) :
(bit0 a) + (bit0 b) = bit0 (a + b) := rfl
@[simp] lemma bit1_add_bit1 (a b : ℙ) :
(bit1 a) + (bit1 b) = bit0 ((a + b) + 1) :=
begin
-- show (bit1 a) + (bit1 b) = bit0 ((a + b) + 1) :=
show bit0 (succ (a + b)) = _,
simp
end
@[simp] lemma bit0_add_bit1 (a b : ℙ) :
(bit0 a) + (bit1 b) = bit1 (a + b) := rfl
@[simp] lemma bit1_add_bit0 (a b : ℙ) :
(bit1 a) + (bit0 b) = bit1 (a + b) := rfl
/-! # some more bit0 and bit1 things -/
lemma bit0_eq_add_self (p : ℙ) : bit0 p = p + p :=
begin
induction p with p hp p hp,
{ refl },
{ rw bit1_add_bit1,
congr',
rw ←hp,
rw bit0_add_one
},
{ rw bit0_add_bit0,
congr' }
end
lemma bit1_eq_add_self_add_one (p : ℙ) : bit1 p = p + p + 1 :=
begin
rw ←succ_bit0,
rw bit0_eq_add_self,
simp,
end
lemma bit1_eq_succ_add_self (p : ℙ) : bit1 p = succ (p + p) :=
begin
simp [bit1_eq_add_self_add_one]
end
/-! # Even and odd -/
-- This just works but it's kind of useless.
/-! # Even and odd -- it all works -/
inductive even : ℙ → Prop
| even_bit0 (n : ℙ) : even (bit0 n)
inductive odd : ℙ → Prop
| odd_one : odd 1
| odd_bit1 (n : ℙ) : odd (bit1 n)
def odd_one := odd.odd_one -- put it in the root namespace
def even_bit0 := even.even_bit0
def odd_bit1 := odd.odd_bit1
lemma even_or_odd (a : ℙ) : even a ∨ odd a :=
begin
cases a,
right, apply odd_one,
right, apply odd_bit1,
left, apply even_bit0
end
lemma not_even_and_odd (a : ℙ) : ¬ (even a ∧ odd a) :=
begin
induction a,
{ rintro ⟨⟨⟩,_⟩},
{ rintro ⟨⟨⟩,_⟩},
/-
protected eliminator xena.pos_num.rec : Π {C : ℙ → Sort l},
C one → (Π (a : ℙ), C a → C (bit1 a)) → (Π (a : ℙ), C a → C (bit0 a)) → Π (n : ℙ), C n
-/
{ rintro ⟨_,⟨⟩⟩ },
end
lemma odd_add_odd (a b : ℙ) (ha : odd a) (hb : odd b) : even (a + b) :=
begin
cases ha; cases hb; apply even_bit0,
end
lemma odd_add_even (a b : ℙ) (ha : odd a) (hb : even b) : odd (a + b) :=
begin
cases ha; cases hb; apply odd_bit1,
end
lemma even_add_odd (a b : ℙ) (ha : even a) (hb : odd b) : odd (a + b) :=
begin
cases ha; cases hb; apply odd_bit1,
end
lemma even_add_even (a b : ℙ) (ha : even a) (hb : even b) : even (a + b) :=
begin
cases ha; cases hb; apply even_bit0,
end
-- end of odd/even nonsense; now back to associativity and commutativity
lemma add_one_add_one (a : ℙ) : a + (1 + 1) = a + 1 + 1 :=
begin
induction a; simp; refl,
end
-- finally add_succ
@[simp] lemma add_succ (a b : ℙ) : a + succ b = succ (a + b) :=
begin
induction b with b hb b hb generalizing a,
{ show a + (1 + 1) = succ (a + 1),
simp,
convert add_one_add_one a,
simp,
},
{ induction a with a ha a ha,
{ simp },
{ simp, --rw succ_eq_add_one,
rw hb a },
{ simp [hb a] } },
{ induction a with a ha a ha; simp },
end
lemma add_comm (a b : ℙ) : a + b = b + a :=
begin
induction b with b hb b hb generalizing a,
{ simp },
{ cases a with a a,
{ rw one_add_bit1',
rw bit1_add_one',
rw hb 1,
refl },
{ rw [bit1_add_bit1, bit1_add_bit1, hb] },
{ rw [bit0_add_bit1, bit1_add_bit0, hb] } },
{ cases a with a a,
{ rw [one_add_bit0', bit0_add_one'] },
{ rw [bit1_add_bit0, bit0_add_bit1, hb] },
{ rw [bit0_add_bit0, bit0_add_bit0, hb] }
}
end
@[simp] lemma succ_add (a b : ℙ) : (succ a) + b = succ (a + b) :=
begin
rw add_comm,
rw add_succ,
rw add_comm,
end
lemma add_assoc (a b c : ℙ) : a + (b + c) = a + b + c :=
begin
induction c with c hc c hc generalizing a b,
{ simp [add_succ] },
{ cases b with b b,
{ rw [add_one_eq_succ', one_add_eq_succ', add_succ, succ_add] },
{ cases a with a a,
{ simp },
{ simp, rw ←hc },
{ simp [hc] } },
{ cases a with a a; simp [hc] } },
{ cases b with b b,
{ simp, rw [←succ_bit0, add_succ] },
{ cases a with a a; simp [hc] },
{ cases a; simp [hc] } }
end
lemma add_assoc' (a b c : ℙ) : a + b + c = a + (b + c) :=
by rw add_assoc a b c
/-! # Equiv.to_fun and inv_fun -/
-- data
/-- the "identity" inclusion sending n to n -/
def equiv.to_fun_aux : ℙ → ℕ :=
pos_num.rec 1 (λ b (n : ℕ), _root_.bit1 n) (λ b n, _root_.bit0 n)
-- recursor for the funtion
@[simp] lemma equiv.to_fun_one : equiv.to_fun_aux 1 = 1 := rfl
@[simp] lemma equiv.to_fun_one' : equiv.to_fun_aux one = 1 := rfl
@[simp] lemma equiv.to_fun_two : equiv.to_fun_aux (bit0 1) = 2 := rfl
@[simp] lemma equiv.to_fun_bit0 (a : ℙ) : equiv.to_fun_aux (bit0 a) =
_root_.bit0 (equiv.to_fun_aux a) :=
begin
refl
end
@[simp] lemma equiv.to_fun_bit1 (a : ℙ) : equiv.to_fun_aux (bit1 a) =
_root_.bit1 (equiv.to_fun_aux a) :=
begin
refl
end
lemma equiv.to_fun_ne_zero (p : ℙ) : equiv.to_fun_aux p ≠ 0 :=
begin
induction p;
simp [*, _root_.bit0],
rintro ⟨⟩,
end
lemma equiv.to_fun_succ (p : ℙ) :
equiv.to_fun_aux (succ p) = nat.succ (equiv.to_fun_aux p) :=
begin
induction p with p hp p hp,
{ refl },
{simp [hp], generalize h : equiv.to_fun_aux p = n, show (n + 1) + (n + 1) = (n + n + 1) + 1, ring },
{ refl }
end
-- note: returns a junk value at 0
def equiv.inv_fun_aux : ℕ → ℙ
| 0 := thirty_seven -- unreachable code has been reached
| 1 := 1
| (n + 2) := succ (equiv.inv_fun_aux (n + 1))
--#print prefix equiv.inv_fun
@[simp] lemma equiv.inv_fun_one : equiv.inv_fun_aux 1 = 1 := rfl
@[simp] lemma equiv.inv_fun_succ_succ (n : ℕ) :
equiv.inv_fun_aux (n + 2) =
succ (equiv.inv_fun_aux (n + 1)) :=
begin
refl
end
@[simp] lemma equiv.inv_fun_succ {n : ℕ} (hn : n ≠ 0) :
equiv.inv_fun_aux (nat.succ n) =
succ (equiv.inv_fun_aux n) :=
begin
cases n, cases hn rfl, clear hn,
refl
end
-- pnat inductive principle
@[elab_as_eliminator] def pnat'.induction {C : ℕ → Prop} {n : ℕ} (hn : n ≠ 0) (h1 : C 1)
(IH : ∀ d, C d → C (d + 1)) : C n :=
begin
cases n, cases hn rfl, clear hn,
induction n with d hd, assumption,
apply IH,
assumption,
end
/-! ## relation between equiv and addition -/
@[simp] lemma equiv.inv_fun_add {a b : ℕ} (ha : a ≠ 0) (hb : b ≠ 0) :
equiv.inv_fun_aux (a + b) = equiv.inv_fun_aux a + equiv.inv_fun_aux b :=
begin
cases a, cases ha rfl, cases b, cases hb rfl, clear ha, clear hb,
induction b with d hd generalizing a,
{ rw equiv.inv_fun_succ_succ,
rw ←add_one_eq_succ,
congr' },
{ rw (show (nat.succ a + nat.succ (nat.succ d) =
(nat.succ (a + d) + 2)), by omega),
rw equiv.inv_fun_succ_succ,
rw (show nat.succ (a + d) + 1 = nat.succ a + nat.succ d, by omega),
rw hd,
simp }
end
@[simp] lemma equiv.inv_fun_bit0 {a : ℕ} (ha : a ≠ 0) :
equiv.inv_fun_aux (_root_.bit0 a) = bit0 (equiv.inv_fun_aux a) :=
begin
simp [bit0_eq_add_self, (show _root_.bit0 a = a + a, from rfl),
equiv.inv_fun_add ha ha]
end
@[simp] lemma equiv.inv_fun_bit1 {a : ℕ} (ha : a ≠ 0) :
equiv.inv_fun_aux (_root_.bit1 a) = bit1 (equiv.inv_fun_aux a) :=
begin
rw [←succ_bit0, nat.bit1_eq_succ_bit0, equiv.inv_fun_succ],
congr',
rw equiv.inv_fun_bit0 ha, intro h, apply ha, exact nat.bit0_inj h,
end
-- equiv.inv_fun_aux : ℕ → pos_num is the identity on positive n.
-- it's defined by recursion
section equiv
/-! # Equiv -/
def same : ℙ ≃ {n : ℕ // n ≠ 0} :=
{ to_fun := λ p, ⟨equiv.to_fun_aux p, equiv.to_fun_ne_zero p⟩,
inv_fun := λ n, equiv.inv_fun_aux n.1,
left_inv := begin
intro p,
induction p with p h p h,
{ refl },
{ simp at *, rw [equiv.inv_fun_bit1, h], apply equiv.to_fun_ne_zero },
{ simp * at *, rw [equiv.inv_fun_bit0, h], apply equiv.to_fun_ne_zero },
end,
right_inv := begin
intro n,
cases n with n hn,
simp,
apply pnat'.induction hn, refl,
intros d hd,
rw [←nat.succ_eq_add_one],
cases d, refl,
rw equiv.inv_fun_succ_succ,
rw equiv.to_fun_succ,
rw hd
end }
lemma bij1 (p : ℙ) : equiv.inv_fun_aux (equiv.to_fun_aux p) = p :=
same.left_inv p
lemma bij2 (n : ℕ) (hn : n ≠ 0) : equiv.to_fun_aux (equiv.inv_fun_aux n) = n :=
begin
have : same (same.symm ⟨n, hn⟩) = ⟨n, hn⟩,
convert same.right_inv _,
apply_fun subtype.val at this,
rw ← this,
congr'
end
--same.right_inv ⟨n, hn⟩
--lemma equiv.same_symm_add : same.symm (a + b) = same.symm a + same.symm b
lemma nat.add_ne_zero_left (a b : ℕ) (h : b ≠ 0) : a + b ≠ 0 :=
begin
omega,
end
lemma equiv.to_fun_add (p q : ℙ) :
equiv.to_fun_aux (p + q) = equiv.to_fun_aux p + equiv.to_fun_aux q :=
begin
-- rw ← (show same.symm (same p) = p, from same.left_inv p),
--rw ← (show same.symm (same q) = q, from same.left_inv q),
rw ← (show equiv.inv_fun_aux (equiv.to_fun_aux p) = p, from same.left_inv p),
rw ← (show equiv.inv_fun_aux (equiv.to_fun_aux q) = q, from same.left_inv q),
rw ← equiv.inv_fun_add,
rw bij1,
rw bij2,
rw bij2,
{ apply equiv.to_fun_ne_zero },
{ apply nat.add_ne_zero_left,
apply equiv.to_fun_ne_zero },
{ apply equiv.to_fun_ne_zero },
{ apply equiv.to_fun_ne_zero },
end
end equiv
/-- computer-science-endorsed definition of mul-/
protected def mul (a : ℙ) : ℙ → ℙ
| 1 := a
| (bit0 b) := bit0 (mul b)
| (bit1 b) := bit0 (mul b) + a
instance : has_mul ℙ := ⟨pos_num.mul⟩
@[simp] lemma mul_one (a : ℙ) : a * 1 = a := rfl
@[simp] lemma mul_bit0 (a b : ℙ) : a * (bit0 b) = bit0 (a * b) := rfl
@[simp] lemma mul_bit1 (a b : ℙ) : a * (bit1 b) = bit0 (a * b) + a := rfl
@[simp] lemma one_mul (p : ℙ) : 1 * p = p :=
begin
induction p;
all_goals { try {rw (show (one : ℙ) = 1, from rfl)}};
simp [*]
end
/-! # Current state : working on to_fun_mul -/
-- (sorry-free up to here)
@[simp] lemma equiv.to_fun_mul (a b : ℙ) :
same (a * b) = ⟨(same a).1 * (same b).1, begin
apply nat.mul_ne_zero;
apply equiv.to_fun_ne_zero,
end⟩ :=
begin
apply subtype.eq,
induction b with b hb b hb generalizing a,
{ rw (show (one : ℙ) = 1, from rfl),
rw mul_one,
symmetry',
apply _root_.mul_one },
{ unfold_coes, simp [same] at hb ⊢,
rw equiv.to_fun_add,
rw equiv.to_fun_bit0,
sorry },
{ sorry }
end
section pred
/-! # Pred == a possibly mad project. -/
-- I get stuck proving the equiv. There is a sorry in the
-- equiv in this section.
/-! to_fun is the bijection ℙ → ℕ, considered as a function. -/
def pred.to_fun : ℙ → ℕ :=
pos_num.rec 0 (λ b (n : ℕ), (n + n + 1 + 1)) (λ b n, n + n + 1)
-- interface for pred.to_fun
lemma pred.to_fun_one : pred.to_fun 1 = 0 := rfl
lemma pred.to_fun_two : pred.to_fun (bit0 1) = 1 := rfl
lemma pred.to_fun_bit0 (a : ℙ) : pred.to_fun (bit0 a) =
(pred.to_fun a) + (pred.to_fun a) + 1 :=
begin
refl
end
lemma pred.to_fun_bit1 (a : ℙ) : pred.to_fun (bit1 a) =
(pred.to_fun a + pred.to_fun a + 1 + 1) :=
begin
refl
end
/-- `inv_fun : the bijection ℕ → ℙ, considered as a function -/
def pred.inv_fun := nat.rec 1 (λ n p, succ p)
-- the interface for inv_fun
lemma pred.inv_fun_zero : pred.inv_fun 0 = 1 :=rfl
lemma pred.inv_fun_succ (n : ℕ) :
pred.inv_fun (nat.succ n) = succ (pred.inv_fun n) :=rfl
lemma pred.inv_fun_succ' (n : ℕ) :
pred.inv_fun (n + 1) = succ (pred.inv_fun n) :=rfl
open nat
def temp : {n : ℕ // n ≠ 0} ≃ ℕ :=
{ to_fun := λ n, pred n.1,
inv_fun := λ n, ⟨nat.succ n, succ_ne_zero n⟩,
left_inv := λ n, begin
cases n with n hn,
cases n with n, cases hn rfl,
refl,
end,
right_inv := λ n, begin
refl,
end
}
/-! # equiv -/
def pred : ℙ ≃ ℕ := same.trans temp
end pred
/-! # The usual induction principle -/
-- I deduce this from an equiv to a nat-like object.
def pos_num.induction (C : ℙ → Prop) (x : C 1) (h : ∀ d, C d → C (succ d))
(p : ℙ) : C p :=
begin
suffices : ∀ n : ℕ, C (pred.symm n),
{ convert this (pred p), simp },
intro n,
induction n with d hd,
{ convert x },
{ convert h _ hd },
end
def pow : ℙ → ℙ → ℙ
| x 1 := 1
| x (bit0 y) := pow x y * pow x y
| x (bit1 y) := pow x y * pow x y * x
-- cf bit1 y = y + y + 1
-- all the usual pred stuff
def pred' : ℙ → ℙ
| 1 := 37
| (bit1 a) := bit0 a
| (bit0 a) := bit1 (pred' a)
def size : ℙ → ℙ
| 1 := 1
| (bit0 n) := succ (size n)
| (bit1 n) := succ (size n)
def of_nat_succ : ℕ → ℙ
| 0 := 1
| (nat.succ n) := succ (of_nat_succ n)
def of_nat (n : ℕ) : ℙ := of_nat_succ (nat.pred n)
/-! # semigroup-/
instance : add_semigroup ℙ :=
{ add := (+),
add_assoc := add_assoc' }
/-! # mul -/
#print pos_num.mul
-- not even a monoid because no 0
open ordering
-- inductive prop
-- not sure if this is right
inductive le : ∀ (a b : ℙ), Prop
| one_le : ∀ (a : ℙ), le 1 a
| bit0_mono : ∀ (a b : ℙ), le a b → le (bit0 a) (bit0 b)
| bit1_mono : ∀ (a b : ℙ), le a b → le (bit1 a) (bit1 b)
| comm_diag : ∀ (a b : ℙ), le a b → le (bit0 a) (bit1 b)
| funny_one : ∀ (a b : ℙ), le a b → a ≠ b → le (bit1 a) (bit0 b)
namespace le
instance : has_le ℙ := ⟨le⟩
--has_lt will be autogenerated by preorder
instance : partial_order ℙ :=
{ le := (≤),
le_refl := begin
intro a,
induction a,
apply one_le,
apply bit1_mono,
assumption,
apply bit0_mono,
assumption,
end,
le_trans := begin
rintros a b c hab hbc,
induction hab with B B C hBC bCBc b6 b7 b8 b9 b10;
clear a b,
-- with b | ⟨a, b, hab⟩ | ⟨a, b, hab⟩ | ⟨a,
--b, hab⟩ | ⟨a, b, hab, haneb⟩,
{ apply one_le },
{ rcases hbc with hab,
apply bit0_mono,
cases hbc with hbc,
-- cases hbc,
-- apply bit0_mono,
-- assumption,
-- cases c,
-- { cases hbc },
{ sorry },
{ sorry }},
-- rintros ⟨_,a0,a1⟩ ⟨_,b0,b1⟩ ⟨_,c0,c1⟩,
-- --try {cc}, -- solves five of them
-- { cc },
-- { cc },
-- { cc },
-- { intros, apply one_le one,
-- },
sorry, sorry, sorry
end,
le_antisymm := begin
sorry
end }
end le
end pos_num
end xena
#exit
--instance : has_lt ℙ := ⟨λa b, cmp a b = ordering.lt⟩
theorem le_refl (a : ℙ) : a ≤ a := sorry
#exit
instance : has_lt ℙ := ⟨λa b, cmp a b = ordering.lt⟩
instance : has_le ℙ := ⟨λa b, ¬ b < a⟩
instance decidable_lt : @decidable_rel ℙ (<)
| a b := by dsimp [(<)]; apply_instance
instance decidable_le : @decidable_rel ℙ (≤)
| a b := by dsimp [(≤)]; apply_instance
end ℙ
section
variables {α : Type*} [has_zero α] [has_one α] [has_add α]
def cast_pos_num : ℙ → α
| 1 := 1
| (ℙ.bit0 a) := bit0 (cast_pos_num a)
| (ℙ.bit1 a) := bit1 (cast_pos_num a)
def cast_num : num → α
| 0 := 0
| (num.pos p) := cast_pos_num p
@[priority 10] instance pos_num_coe : has_coe ℙ α := ⟨cast_pos_num⟩
@[priority 10] instance num_nat_coe : has_coe num α := ⟨cast_num⟩
instance : has_repr ℙ := ⟨λ n, repr (n : ℕ)⟩
instance : has_repr num := ⟨λ n, repr (n : ℕ)⟩
end
namespace num
open ℙ
def succ' : num → ℙ
| 0 := 1
| (pos p) := succ p
def succ (n : num) : num := pos (succ' n)
protected def add : num → num → num
| 0 a := a
| b 0 := b
| (pos a) (pos b) := pos (a + b)
instance : has_add num := ⟨num.add⟩
protected def bit0 : num → num
| 0 := 0
| (pos n) := pos (ℙ.bit0 n)
protected def bit1 : num → num
| 0 := 1
| (pos n) := pos (ℙ.bit1 n)
def bit (b : bool) : num → num := cond b num.bit1 num.bit0
def size : num → num
| 0 := 0
| (pos n) := pos (ℙ.size n)
def nat_size : num → nat
| 0 := 0
| (pos n) := ℙ.nat_size n
protected def mul : num → num → num
| 0 _ := 0
| _ 0 := 0
| (pos a) (pos b) := pos (a * b)
instance : has_mul num := ⟨num.mul⟩
open ordering
def cmp : num → num → ordering
| 0 0 := eq
| _ 0 := gt
| 0 _ := lt
| (pos a) (pos b) := ℙ.cmp a b
instance : has_lt num := ⟨λa b, cmp a b = ordering.lt⟩
instance : has_le num := ⟨λa b, ¬ b < a⟩
instance decidable_lt : @decidable_rel num (<)
| a b := by dsimp [(<)]; apply_instance
instance decidable_le : @decidable_rel num (≤)
| a b := by dsimp [(≤)]; apply_instance
def to_znum : num → znum
| 0 := 0
| (pos a) := znum.pos a
def to_znum_neg : num → znum
| 0 := 0
| (pos a) := znum.neg a
def of_nat' : ℕ → num :=
nat.binary_rec 0 (λ b n, cond b num.bit1 num.bit0)
end num
namespace znum
open ℙ
def zneg : znum → znum
| 0 := 0
| (pos a) := neg a
| (neg a) := pos a
instance : has_neg znum := ⟨zneg⟩
def abs : znum → num
| 0 := 0
| (pos a) := num.pos a
| (neg a) := num.pos a
def succ : znum → znum
| 0 := 1
| (pos a) := pos (ℙ.succ a)
| (neg a) := (ℙ.pred' a).to_znum_neg
def pred : znum → znum
| 0 := neg 1
| (pos a) := (ℙ.pred' a).to_znum
| (neg a) := neg (ℙ.succ a)
protected def bit0 : znum → znum
| 0 := 0
| (pos n) := pos (ℙ.bit0 n)
| (neg n) := neg (ℙ.bit0 n)
protected def bit1 : znum → znum
| 0 := 1
| (pos n) := pos (ℙ.bit1 n)
| (neg n) := neg (num.cases_on (pred' n) 1 ℙ.bit1)
protected def bitm1 : znum → znum
| 0 := neg 1
| (pos n) := pos (num.cases_on (pred' n) 1 ℙ.bit1)
| (neg n) := neg (ℙ.bit1 n)
def of_int' : ℤ → znum
| (n : ℕ) := num.to_znum (num.of_nat' n)
| -[1+ n] := num.to_znum_neg (num.of_nat' (n+1))
end znum
namespace ℙ
open znum
def sub' : ℙ → ℙ → znum
| a 1 := (pred' a).to_znum
| 1 b := (pred' b).to_znum_neg
| (bit0 a) (bit0 b) := (sub' a b).bit0
| (bit0 a) (bit1 b) := (sub' a b).bitm1
| (bit1 a) (bit0 b) := (sub' a b).bit1
| (bit1 a) (bit1 b) := (sub' a b).bit0
def of_znum' : znum → option ℙ
| (znum.pos p) := some p
| _ := none
def of_znum : znum → ℙ
| (znum.pos p) := p
| _ := 1
protected def sub (a b : ℙ) : ℙ :=
match sub' a b with
| (znum.pos p) := p
| _ := 1
end
instance : has_sub ℙ := ⟨pos_num.sub⟩
end ℙ
namespace num
def ppred : num → option num
| 0 := none
| (pos p) := some p.pred'
def pred : num → num
| 0 := 0
| (pos p) := p.pred'
def div2 : num → num
| 0 := 0
| 1 := 0
| (pos (ℙ.bit0 p)) := pos p
| (pos (ℙ.bit1 p)) := pos p
def of_znum' : znum → option num
| 0 := some 0
| (znum.pos p) := some (pos p)
| (znum.neg p) := none
def of_znum : znum → num
| (znum.pos p) := pos p
| _ := 0
def sub' : num → num → znum
| 0 0 := 0
| (pos a) 0 := znum.pos a
| 0 (pos b) := znum.neg b
| (pos a) (pos b) := a.sub' b
def psub (a b : num) : option num :=
of_znum' (sub' a b)
protected def sub (a b : num) : num :=
of_znum (sub' a b)
instance : has_sub num := ⟨num.sub⟩
end num
namespace znum
open ℙ
protected def add : znum → znum → znum
| 0 a := a
| b 0 := b
| (pos a) (pos b) := pos (a + b)
| (pos a) (neg b) := sub' a b
| (neg a) (pos b) := sub' b a
| (neg a) (neg b) := neg (a + b)
instance : has_add znum := ⟨znum.add⟩
protected def mul : znum → znum → znum
| 0 a := 0
| b 0 := 0
| (pos a) (pos b) := pos (a * b)
| (pos a) (neg b) := neg (a * b)
| (neg a) (pos b) := neg (a * b)
| (neg a) (neg b) := pos (a * b)
instance : has_mul znum := ⟨znum.mul⟩
open ordering
def cmp : znum → znum → ordering
| 0 0 := eq
| (pos a) (pos b) := ℙ.cmp a b
| (neg a) (neg b) := ℙ.cmp b a
| (pos _) _ := gt
| (neg _) _ := lt
| _ (pos _) := lt
| _ (neg _) := gt
instance : has_lt znum := ⟨λa b, cmp a b = ordering.lt⟩
instance : has_le znum := ⟨λa b, ¬ b < a⟩
instance decidable_lt : @decidable_rel znum (<)
| a b := by dsimp [(<)]; apply_instance
instance decidable_le : @decidable_rel znum (≤)
| a b := by dsimp [(≤)]; apply_instance
end znum
namespace ℙ
def divmod_aux (d : ℙ) (q r : num) : num × num :=
match num.of_znum' (num.sub' r (num.pos d)) with
| some r' := (num.bit1 q, r')
| none := (num.bit0 q, r)
end
def divmod (d : ℙ) : ℙ → num × num
| (bit0 n) := let (q, r₁) := divmod n in
divmod_aux d q (num.bit0 r₁)
| (bit1 n) := let (q, r₁) := divmod n in
divmod_aux d q (num.bit1 r₁)
| 1 := divmod_aux d 0 1
def div' (n d : ℙ) : num := (divmod d n).1
def mod' (n d : ℙ) : num := (divmod d n).2
def sqrt_aux1 (b : ℙ) (r n : num) : num × num :=
match num.of_znum' (n.sub' (r + num.pos b)) with
| some n' := (r.div2 + num.pos b, n')
| none := (r.div2, n)
end
def sqrt_aux : ℙ → num → num → num
| b@(bit0 b') r n := let (r', n') := sqrt_aux1 b r n in sqrt_aux b' r' n'
| b@(bit1 b') r n := let (r', n') := sqrt_aux1 b r n in sqrt_aux b' r' n'
| 1 r n := (sqrt_aux1 1 r n).1
/-
def sqrt_aux : ℕ → ℕ → ℕ → ℕ
| b r n := if b0 : b = 0 then r else
let b' := shiftr b 2 in
have b' < b, from sqrt_aux_dec b0,
match (n - (r + b : ℕ) : ℤ) with
| (n' : ℕ) := sqrt_aux b' (div2 r + b) n'
| _ := sqrt_aux b' (div2 r) n
end
/-- `sqrt n` is the square root of a natural number `n`. If `n` is not a
perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/
def sqrt (n : ℕ) : ℕ :=
match size n with
| 0 := 0
| succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n
end
-/
end ℙ
namespace num
def div : num → num → num
| 0 _ := 0
| _ 0 := 0
| (pos n) (pos d) := ℙ.div' n d
def mod : num → num → num
| 0 _ := 0
| n 0 := n
| (pos n) (pos d) := ℙ.mod' n d
instance : has_div num := ⟨num.div⟩
instance : has_mod num := ⟨num.mod⟩
def gcd_aux : nat → num → num → num
| 0 a b := b
| (nat.succ n) 0 b := b
| (nat.succ n) a b := gcd_aux n (b % a) a
def gcd (a b : num) : num :=
if a ≤ b then
gcd_aux (a.nat_size + b.nat_size) a b
else
gcd_aux (b.nat_size + a.nat_size) b a
end num
namespace znum
def div : znum → znum → znum
| 0 _ := 0
| _ 0 := 0
| (pos n) (pos d) := num.to_znum (ℙ.div' n d)
| (pos n) (neg d) := num.to_znum_neg (ℙ.div' n d)
| (neg n) (pos d) := neg (ℙ.pred' n / num.pos d).succ'
| (neg n) (neg d) := pos (ℙ.pred' n / num.pos d).succ'
def mod : znum → znum → znum
| 0 d := 0
| (pos n) d := num.to_znum (num.pos n % d.abs)
| (neg n) d := d.abs.sub' (ℙ.pred' n % d.abs).succ
instance : has_div znum := ⟨znum.div⟩
instance : has_mod znum := ⟨znum.mod⟩
def gcd (a b : znum) : num := a.abs.gcd b.abs
end znum
section
variables {α : Type*} [has_zero α] [has_one α] [has_add α] [has_neg α]
def cast_znum : znum → α
| 0 := 0
| (znum.pos p) := p
| (znum.neg p) := -p
@[priority 10] instance znum_coe : has_coe znum α := ⟨cast_znum⟩
instance : has_repr znum := ⟨λ n, repr (n : ℤ)⟩
end
/- The snum representation uses a bit string, essentially a list of 0 (ff) and 1 (tt) bits,
and the negation of the MSB is sign-extended to all higher bits. -/
namespace nzsnum
notation a :: b := bit a b
def sign : nzsnum → bool
| (msb b) := bnot b
| (b :: p) := sign p
@[pattern] def not : nzsnum → nzsnum
| (msb b) := msb (bnot b)
| (b :: p) := bnot b :: not p
prefix ~ := not
def bit0 : nzsnum → nzsnum := bit ff
def bit1 : nzsnum → nzsnum := bit tt
def head : nzsnum → bool
| (msb b) := b
| (b :: p) := b
def tail : nzsnum → snum
| (msb b) := snum.zero (bnot b)
| (b :: p) := p
end nzsnum
namespace snum
open nzsnum
def sign : snum → bool
| (zero z) := z
| (nz p) := p.sign
@[pattern] def not : snum → snum
| (zero z) := zero (bnot z)
| (nz p) := ~p
prefix ~ := not
@[pattern] def bit : bool → snum → snum
| b (zero z) := if b = z then zero b else msb b
| b (nz p) := p.bit b
notation a :: b := bit a b
def bit0 : snum → snum := bit ff
def bit1 : snum → snum := bit tt
theorem bit_zero (b) : b :: zero b = zero b := by cases b; refl
theorem bit_one (b) : b :: zero (bnot b) = msb b := by cases b; refl
end snum
namespace nzsnum
open snum
def drec' {C : snum → Sort*} (z : Π b, C (snum.zero b))
(s : Π b p, C p → C (b :: p)) : Π p : nzsnum, C p
| (msb b) := by rw ←bit_one; exact s b (snum.zero (bnot b)) (z (bnot b))
| (bit b p) := s b p (drec' p)
end nzsnum
namespace snum
open nzsnum
def head : snum → bool
| (zero z) := z
| (nz p) := p.head
def tail : snum → snum
| (zero z) := zero z
| (nz p) := p.tail
def drec' {C : snum → Sort*} (z : Π b, C (snum.zero b))
(s : Π b p, C p → C (b :: p)) : Π p, C p
| (zero b) := z b
| (nz p) := p.drec' z s
def rec' {α} (z : bool → α) (s : bool → snum → α → α) : snum → α :=
drec' z s
def bits : snum → Π n, vector bool n
| p 0 := vector.nil
| p (n+1) := head p :: bits (tail p) n
def test_bit : nat → snum → bool
| 0 p := head p
| (n+1) p := test_bit n (tail p)
def succ : snum → snum :=
rec' (λ b, cond b 0 1) (λb p succp, cond b (ff :: succp) (tt :: p))
def pred : snum → snum :=
rec' (λ b, cond b (~1) ~0) (λb p predp, cond b (ff :: p) (tt :: predp))
protected def neg (n : snum) : snum := succ ~n
instance : has_neg snum := ⟨snum.neg⟩
-- First bit is 0 or 1 (tt), second bit is 0 or -1 (tt)
def czadd : bool → bool → snum → snum
| ff ff p := p
| ff tt p := pred p
| tt ff p := succ p
| tt tt p := p
def cadd : snum → snum → bool → snum :=
rec' (λ a p c, czadd c a p) $ λa p IH,
rec' (λb c, czadd c b (a :: p)) $ λb q _ c,
bitvec.xor3 a b c :: IH q (bitvec.carry a b c)
protected def add (a b : snum) : snum := cadd a b ff
instance : has_add snum := ⟨snum.add⟩
protected def sub (a b : snum) : snum := a + -b
instance : has_sub snum := ⟨snum.sub⟩
protected def mul (a : snum) : snum → snum :=
rec' (λ b, cond b (-a) 0) $ λb q IH,
cond b (bit0 IH + a) (bit0 IH)
instance : has_mul snum := ⟨snum.mul⟩
end snum
namespace int
def of_snum : snum → ℤ :=
snum.rec' (λ a, cond a (-1) 0) (λa p IH, cond a (bit1 IH) (bit0 IH))
instance snum_coe : has_coe snum ℤ := ⟨of_snum⟩
end int
instance : has_lt snum := ⟨λa b, (a : ℤ) < b⟩
instance : has_le snum := ⟨λa b, (a : ℤ) ≤ b⟩
|
c239e7b09c54a5cf22c1bb1cd584581d9a570edf
|
a4673261e60b025e2c8c825dfa4ab9108246c32e
|
/src/Init/WF.lean
|
fd815d8aaf3b304a05de960cf7fd571a74ed0c7c
|
[
"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
| 11,258
|
lean
|
/-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.SizeOf
import Init.Data.Nat.Basic
universes u v
set_option codegen false
inductive Acc {α : Sort u} (r : α → α → Prop) : α → Prop :=
| intro (x : α) (h : (y : α) → r y x → Acc r y) : Acc r x
abbrev Acc.ndrec.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1}
(m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x)
{a : α} (n : Acc r a) : C a :=
Acc.rec (motive := fun α _ => C α) m n
abbrev Acc.ndrecOn.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1}
{a : α} (n : Acc r a)
(m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x)
: C a :=
Acc.rec (motive := fun α _ => C α) m n
namespace Acc
variables {α : Sort u} {r : α → α → Prop}
def inv {x y : α} (h₁ : Acc r x) (h₂ : r y x) : Acc r y :=
Acc.recOn (motive := fun (x : α) _ => r y x → Acc r y)
h₁ (fun x₁ ac₁ ih h₂ => ac₁ y h₂) h₂
end Acc
inductive WellFounded {α : Sort u} (r : α → α → Prop) : Prop :=
| intro (h : ∀ a, Acc r a) : WellFounded r
class WellFoundedRelation (α : Sort u) : Type u :=
(r : α → α → Prop)
(wf : WellFounded r)
namespace WellFounded
def apply {α : Sort u} {r : α → α → Prop} (wf : WellFounded r) (a : α) : Acc r a :=
WellFounded.recOn (motive := fun x => (y : α) → Acc r y)
wf (fun p => p) a
section
variables {α : Sort u} {r : α → α → Prop} (hwf : WellFounded r)
theorem recursion {C : α → Sort v} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := by
induction (apply hwf a) with
| intro x₁ ac₁ ih => exact h x₁ ih
theorem induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a :=
recursion hwf a h
variable {C : α → Sort v}
variable (F : ∀ x, (∀ y, r y x → C y) → C x)
def fixF (x : α) (a : Acc r x) : C x := by
induction a with
| intro x₁ ac₁ ih => exact F x₁ ih
def fixFEq (x : α) (acx : Acc r x) : fixF F x acx = F x (fun (y : α) (p : r y x) => fixF F y (Acc.inv acx p)) := by
induction acx with
| intro x r ih => exact rfl
end
variables {α : Sort u} {C : α → Sort v} {r : α → α → Prop}
-- Well-founded fixpoint
def fix (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x :=
fixF F x (apply hwf x)
-- Well-founded fixpoint satisfies fixpoint equation
theorem fixEq (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) :
fix hwf F x = F x (fun y h => fix hwf F y) :=
fixFEq F x (apply hwf x)
end WellFounded
open WellFounded
-- Empty relation is well-founded
def emptyWf {α : Sort u} : WellFounded (@emptyRelation α) := by
apply WellFounded.intro
intro a
apply Acc.intro a
intro b h
cases h
-- Subrelation of a well-founded relation is well-founded
namespace Subrelation
variables {α : Sort u} {r q : α → α → Prop}
def accessible {a : α} (h₁ : Subrelation q r) (ac : Acc r a) : Acc q a := by
induction ac with
| intro x ax ih =>
apply Acc.intro
intro y h
exact ih y (h₁ h)
def wf (h₁ : Subrelation q r) (h₂ : WellFounded r) : WellFounded q :=
⟨fun a => accessible @h₁ (apply h₂ a)⟩
end Subrelation
-- The inverse image of a well-founded relation is well-founded
namespace InvImage
variables {α : Sort u} {β : Sort v} {r : β → β → Prop}
private def accAux (f : α → β) {b : β} (ac : Acc r b) : (x : α) → f x = b → Acc (InvImage r f) x := by
induction ac with
| intro x acx ih =>
intro z e
apply Acc.intro
intro y lt
subst x
apply ih (f y) lt y rfl
def accessible {a : α} (f : α → β) (ac : Acc r (f a)) : Acc (InvImage r f) a :=
accAux f ac a rfl
def wf (f : α → β) (h : WellFounded r) : WellFounded (InvImage r f) :=
⟨fun a => accessible f (apply h (f a))⟩
end InvImage
-- The transitive closure of a well-founded relation is well-founded
namespace TC
variables {α : Sort u} {r : α → α → Prop}
def accessible {z : α} (ac : Acc r z) : Acc (TC r) z := by
induction ac with
| intro x acx ih =>
apply Acc.intro x
intro y rel
induction rel generalizing acx ih with
| base a b rab => exact ih a rab
| trans a b c rab rbc ih₁ ih₂ => apply Acc.inv (ih₂ acx ih) rab
def wf (h : WellFounded r) : WellFounded (TC r) :=
⟨fun a => accessible (apply h a)⟩
end TC
-- less-than is well-founded
def Nat.ltWf : WellFounded Nat.lt := by
apply WellFounded.intro
intro n
induction n with
| zero =>
apply Acc.intro 0
intro _ h
apply absurd h (Nat.notLtZero _)
| succ n ih =>
apply Acc.intro (Nat.succ n)
intro m h
have m = n ∨ m < n from Nat.eqOrLtOfLe (Nat.leOfSuccLeSucc h)
match this with
| Or.inl e => subst e; assumption
| Or.inr e => exact Acc.inv ih e
def measure {α : Sort u} : (α → Nat) → α → α → Prop :=
InvImage (fun a b => a < b)
def measureWf {α : Sort u} (f : α → Nat) : WellFounded (measure f) :=
InvImage.wf f Nat.ltWf
def sizeofMeasure (α : Sort u) [SizeOf α] : α → α → Prop :=
measure sizeOf
def sizeofMeasureWf (α : Sort u) [SizeOf α] : WellFounded (sizeofMeasure α) :=
measureWf sizeOf
instance hasWellFoundedOfSizeOf (α : Sort u) [SizeOf α] : WellFoundedRelation α := {
r := sizeofMeasure α,
wf := sizeofMeasureWf α
}
namespace Prod
open WellFounded
section
variables {α : Type u} {β : Type v}
variable (ra : α → α → Prop)
variable (rb : β → β → Prop)
-- Lexicographical order based on ra and rb
inductive Lex : α × β → α × β → Prop :=
| left {a₁} (b₁) {a₂} (b₂) (h : ra a₁ a₂) : Lex (a₁, b₁) (a₂, b₂)
| right (a) {b₁ b₂} (h : rb b₁ b₂) : Lex (a, b₁) (a, b₂)
-- relational product based on ra and rb
inductive Rprod : α × β → α × β → Prop :=
| intro {a₁ b₁ a₂ b₂} (h₁ : ra a₁ a₂) (h₂ : rb b₁ b₂) : Rprod (a₁, b₁) (a₂, b₂)
end
section
variables {α : Type u} {β : Type v}
variables {ra : α → α → Prop} {rb : β → β → Prop}
def lexAccessible (aca : (a : α) → Acc ra a) (acb : (b : β) → Acc rb b) (a : α) (b : β) : Acc (Lex ra rb) (a, b) := by
induction (aca a) generalizing b with
| intro xa aca iha =>
induction (acb b) with
| intro xb acb ihb =>
apply Acc.intro (xa, xb)
intro p lt
cases lt with
| left a₁ b₁ a₂ b₂ h => apply iha a₁ h
| right a b₁ b₂ h => apply ihb b₁ h
-- The lexicographical order of well founded relations is well-founded
def lexWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Lex ra rb) :=
⟨fun (a, b) => lexAccessible (WellFounded.apply ha) (WellFounded.apply hb) a b⟩
-- relational product is a Subrelation of the Lex
def rprodSubLex (a : α × β) (b : α × β) (h : Rprod ra rb a b) : Lex ra rb a b := by
cases h with
| intro a₁ b₁ a₂ b₂ h₁ h₂ => exact Lex.left b₁ b₂ h₁
-- The relational product of well founded relations is well-founded
def rprodWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Rprod ra rb) := by
apply Subrelation.wf (r := Lex ra rb) (h₂ := lexWf ha hb)
intro a b h
exact rprodSubLex a b h
end
instance {α : Type u} {β : Type v} [s₁ : WellFoundedRelation α] [s₂ : WellFoundedRelation β] : WellFoundedRelation (α × β) := {
r := Lex s₁.r s₂.r,
wf := lexWf s₁.wf s₂.wf
}
end Prod
namespace PSigma
section
variables {α : Sort u} {β : α → Sort v}
variable (r : α → α → Prop)
variable (s : ∀ a, β a → β a → Prop)
-- Lexicographical order based on r and s
inductive Lex : PSigma β → PSigma β → Prop :=
| left : ∀ {a₁ : α} (b₁ : β a₁) {a₂ : α} (b₂ : β a₂), r a₁ a₂ → Lex ⟨a₁, b₁⟩ ⟨a₂, b₂⟩
| right : ∀ (a : α) {b₁ b₂ : β a}, s a b₁ b₂ → Lex ⟨a, b₁⟩ ⟨a, b₂⟩
end
section
variables {α : Sort u} {β : α → Sort v}
variables {r : α → α → Prop} {s : ∀ (a : α), β a → β a → Prop}
def lexAccessible {a} (aca : Acc r a) (acb : (a : α) → WellFounded (s a)) (b : β a) : Acc (Lex r s) ⟨a, b⟩ := by
induction aca generalizing b with
| intro xa aca iha =>
induction (WellFounded.apply (acb xa) b) with
| intro xb acb ihb =>
apply Acc.intro
intro p lt
cases lt with
| left => apply iha; assumption
| right => apply ihb; assumption
-- The lexicographical order of well founded relations is well-founded
def lexWf (ha : WellFounded r) (hb : (x : α) → WellFounded (s x)) : WellFounded (Lex r s) :=
WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) hb b
end
section
variables {α : Sort u} {β : Sort v}
def lexNdep (r : α → α → Prop) (s : β → β → Prop) :=
Lex r (fun a => s)
def lexNdepWf {r : α → α → Prop} {s : β → β → Prop} (ha : WellFounded r) (hb : WellFounded s) : WellFounded (lexNdep r s) :=
WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) (fun x => hb) b
end
section
variables {α : Sort u} {β : Sort v}
-- Reverse lexicographical order based on r and s
inductive RevLex (r : α → α → Prop) (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop :=
| left : {a₁ a₂ : α} → (b : β) → r a₁ a₂ → RevLex r s ⟨a₁, b⟩ ⟨a₂, b⟩
| right : (a₁ : α) → {b₁ : β} → (a₂ : α) → {b₂ : β} → s b₁ b₂ → RevLex r s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩
end
section
open WellFounded
variables {α : Sort u} {β : Sort v}
variables {r : α → α → Prop} {s : β → β → Prop}
def revLexAccessible {b} (acb : Acc s b) (aca : (a : α) → Acc r a): (a : α) → Acc (RevLex r s) ⟨a, b⟩ := by
induction acb with
| intro xb acb ihb =>
intro a
induction (aca a) with
| intro xa aca iha =>
apply Acc.intro
intro p lt
cases lt with
| left => apply iha; assumption
| right => apply ihb; assumption
def revLexWf (ha : WellFounded r) (hb : WellFounded s) : WellFounded (RevLex r s) :=
WellFounded.intro fun ⟨a, b⟩ => revLexAccessible (apply hb b) (WellFounded.apply ha) a
end
section
def skipLeft (α : Type u) {β : Type v} (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop :=
RevLex emptyRelation s
def skipLeftWf (α : Type u) {β : Type v} {s : β → β → Prop} (hb : WellFounded s) : WellFounded (skipLeft α s) :=
revLexWf emptyWf hb
def mkSkipLeft {α : Type u} {β : Type v} {b₁ b₂ : β} {s : β → β → Prop} (a₁ a₂ : α) (h : s b₁ b₂) : skipLeft α s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ :=
RevLex.right _ _ h
end
instance WellFoundedRelation {α : Type u} {β : α → Type v} [s₁ : WellFoundedRelation α] [s₂ : ∀ a, WellFoundedRelation (β a)] : WellFoundedRelation (PSigma β) := {
r := Lex s₁.r (fun a => (s₂ a).r),
wf := lexWf s₁.wf (fun a => (s₂ a).wf)
}
end PSigma
|
b90cf681e23c7b1226a4813718d3d6c4831c5844
|
206422fb9edabf63def0ed2aa3f489150fb09ccb
|
/src/data/multiset/basic.lean
|
f774e2106a3176623759e8dbb2c36f3f3e969e5f
|
[
"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
| 88,068
|
lean
|
/-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.list.perm
import algebra.group_power
/-!
# Multisets
These are implemented as the quotient of a list by permutations.
## Notation
We define the global infix notation `::ₘ` for `multiset.cons`.
-/
open list subtype nat
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `multiset α` is the quotient of `list α` by list permutation. The result
is a type of finite sets with duplicates allowed. -/
def {u} multiset (α : Type u) : Type u :=
quotient (list.is_setoid α)
namespace multiset
instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩
@[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl
@[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl
@[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl
@[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq
instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α)
| s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂,
decidable_of_iff' _ quotient.eq
/-- defines a size for a multiset by referring to the size of the underlying list -/
protected def sizeof [has_sizeof α] (s : multiset α) : ℕ :=
quot.lift_on s sizeof $ λ l₁ l₂, perm.sizeof_eq_sizeof
instance has_sizeof [has_sizeof α] : has_sizeof (multiset α) := ⟨multiset.sizeof⟩
/-! ### Empty multiset -/
/-- `0 : multiset α` is the empty set -/
protected def zero : multiset α := @nil α
instance : has_zero (multiset α) := ⟨multiset.zero⟩
instance : has_emptyc (multiset α) := ⟨0⟩
instance : inhabited (multiset α) := ⟨0⟩
@[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl
@[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl
theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] :=
iff.trans coe_eq_coe perm_nil
/-! ### `multiset.cons` -/
/-- `cons a s` is the multiset which contains `s` plus one more
instance of `a`. -/
def cons (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (a :: l : multiset α))
(λ l₁ l₂ p, quot.sound (p.cons a))
infixr ` ::ₘ `:67 := multiset.cons
instance : has_insert α (multiset α) := ⟨cons⟩
@[simp] theorem insert_eq_cons (a : α) (s : multiset α) :
insert a s = a ::ₘ s := rfl
@[simp] theorem cons_coe (a : α) (l : list α) :
(a ::ₘ l : multiset α) = (a::l : list α) := rfl
theorem singleton_coe (a : α) : (a ::ₘ 0 : multiset α) = ([a] : list α) := rfl
@[simp] theorem cons_inj_left {a b : α} (s : multiset α) :
a ::ₘ s = b ::ₘ s ↔ a = b :=
⟨quot.induction_on s $ λ l e,
have [a] ++ l ~ [b] ++ l, from quotient.exact e,
singleton_perm_singleton.1 $ (perm_append_right_iff _).1 this, congr_arg _⟩
@[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a ::ₘ s = a ::ₘ t ↔ s = t :=
by rintros ⟨l₁⟩ ⟨l₂⟩; simp
@[recursor 5] protected theorem induction {p : multiset α → Prop}
(h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : ∀s, p s :=
by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih]
@[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop}
(s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : p s :=
multiset.induction h₁ h₂ s
theorem cons_swap (a b : α) (s : multiset α) : a ::ₘ b ::ₘ s = b ::ₘ a ::ₘ s :=
quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _
section rec
variables {C : multiset α → Sort*}
/-- Dependent recursor on multisets.
TODO: should be @[recursor 6], but then the definition of `multiset.pi` fails with a stack
overflow in `whnf`.
-/
protected def rec
(C_0 : C 0)
(C_cons : Πa m, C m → C (a ::ₘ m))
(C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b))
(m : multiset α) : C m :=
quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $
assume l l' h,
h.rec_heq
(assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc)
(assume a a' l, C_cons_heq a a' ⟦l⟧)
@[elab_as_eliminator]
protected def rec_on (m : multiset α)
(C_0 : C 0)
(C_cons : Πa m, C m → C (a ::ₘ m))
(C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) :
C m :=
multiset.rec C_0 C_cons C_cons_heq m
variables {C_0 : C 0} {C_cons : Πa m, C m → C (a ::ₘ m)}
{C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)}
@[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 :=
rfl
@[simp] lemma rec_on_cons (a : α) (m : multiset α) :
(a ::ₘ m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) :=
quotient.induction_on m $ assume l, rfl
end rec
section mem
/-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/
def mem (a : α) (s : multiset α) : Prop :=
quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ e.mem_iff)
instance : has_mem α (multiset α) := ⟨mem⟩
@[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl
instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) :=
quot.rec_on_subsingleton s $ list.decidable_mem a
@[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b ::ₘ s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, iff.rfl
lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b ::ₘ s :=
mem_cons.2 $ or.inr h
@[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a ::ₘ s :=
mem_cons.2 (or.inl rfl)
theorem forall_mem_cons {p : α → Prop} {a : α} {s : multiset α} :
(∀ x ∈ (a ::ₘ s), p x) ↔ p a ∧ ∀ x ∈ s, p x :=
quotient.induction_on' s $ λ L, list.forall_mem_cons
theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a ::ₘ t :=
quot.induction_on s $ λ l (h : a ∈ l),
let ⟨l₁, l₂, e⟩ := mem_split h in
e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩
@[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id
theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 :=
quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl
theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s :=
⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩
theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s :=
quot.induction_on s $ assume l hl,
match l, hl with
| [] := assume h, false.elim $ h rfl
| (a :: l) := assume _, ⟨a, by simp⟩
end
@[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a ::ₘ m :=
assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this
@[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a ::ₘ m ≠ 0 := zero_ne_cons.symm
lemma cons_eq_cons {a b : α} {as bs : multiset α} :
a ::ₘ as = b ::ₘ bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b ::ₘ cs ∧ bs = a ::ₘ cs)) :=
begin
haveI : decidable_eq α := classical.dec_eq α,
split,
{ assume eq,
by_cases a = b,
{ subst h, simp * at * },
{ have : a ∈ b ::ₘ bs, from eq ▸ mem_cons_self _ _,
have : a ∈ bs, by simpa [h],
rcases exists_cons_of_mem this with ⟨cs, hcs⟩,
simp [h, hcs],
have : a ::ₘ as = b ::ₘ a ::ₘ cs, by simp [eq, hcs],
have : a ::ₘ as = a ::ₘ b ::ₘ cs, by rwa [cons_swap],
simpa using this } },
{ assume h,
rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ simp * },
{ simp [*, cons_swap a b] } }
end
end mem
/-! ### `multiset.subset` -/
section subset
/-- `s ⊆ t` is the lift of the list subset relation. It means that any
element with nonzero multiplicity in `s` has nonzero multiplicity in `t`,
but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`;
see `s ≤ t` for this relation. -/
protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t
instance : has_subset (multiset α) := ⟨multiset.subset⟩
@[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl
@[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h
theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u :=
λ h₁ h₂ a m, h₂ (h₁ m)
theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl
theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _
@[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s :=
λ a, (not_mem_nil a).elim
@[simp] theorem cons_subset {a : α} {s t : multiset α} : (a ::ₘ s) ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp [subset_iff, or_imp_distrib, forall_and_distrib]
theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 :=
eq_zero_of_forall_not_mem h
theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 :=
⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩
end subset
section to_list
/-- Produces a list of the elements in the multiset using choice. -/
@[reducible] noncomputable def to_list {α : Type*} (s : multiset α) :=
classical.some (quotient.exists_rep s)
@[simp] lemma to_list_zero {α : Type*} : (multiset.to_list 0 : list α) = [] :=
(multiset.coe_eq_zero _).1 (classical.some_spec (quotient.exists_rep multiset.zero))
lemma coe_to_list {α : Type*} (s : multiset α) : (s.to_list : multiset α) = s :=
classical.some_spec (quotient.exists_rep _)
lemma mem_to_list {α : Type*} (a : α) (s : multiset α) : a ∈ s.to_list ↔ a ∈ s :=
by rw [←multiset.mem_coe, multiset.coe_to_list]
end to_list
/-! ### Partial order on `multiset`s -/
/-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation).
Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/
protected def le (s t : multiset α) : Prop :=
quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
propext (p₂.subperm_left.trans p₁.subperm_right)
instance : partial_order (multiset α) :=
{ le := multiset.le,
le_refl := by rintros ⟨l⟩; exact subperm.refl _,
le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _,
le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) }
theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm.subset
theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t :=
mem_of_subset (subset_of_le h)
@[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl
@[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop}
{s t : multiset α} (h : s ≤ t)
(H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t :=
quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩,
(show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h
theorem zero_le (s : multiset α) : 0 ≤ s :=
quot.induction_on s $ λ l, (nil_sublist l).subperm
theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 :=
⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩
theorem lt_cons_self (s : multiset α) (a : α) : s < a ::ₘ s :=
quot.induction_on s $ λ l,
suffices l <+~ a :: l ∧ (¬l ~ a :: l),
by simpa [lt_iff_le_and_ne],
⟨(sublist_cons _ _).subperm,
λ p, ne_of_lt (lt_succ_self (length l)) p.length_eq⟩
theorem le_cons_self (s : multiset α) (a : α) : s ≤ a ::ₘ s :=
le_of_lt $ lt_cons_self _ _
theorem cons_le_cons_iff (a : α) {s t : multiset α} : a ::ₘ s ≤ a ::ₘ t ↔ s ≤ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a
theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a ::ₘ s ≤ a ::ₘ t :=
(cons_le_cons_iff a).2
theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a ::ₘ t ↔ s ≤ t :=
begin
refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩,
suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a ::ₘ s ≤ t',
{ exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) },
introv h, revert m, refine le_induction_on h _,
introv s m₁ m₂,
rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩,
exact perm_middle.subperm_left.2 ((subperm_cons _).2 $
((sublist_or_mem_of_sublist s).resolve_right m₁).subperm)
end
/-! ### Additive monoid -/
/-- The sum of two multisets is the lift of the list append operation.
This adds the multiplicities of each element,
i.e. `count a (s + t) = count a s + count a t`. -/
protected def add (s₁ s₂ : multiset α) : multiset α :=
quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $
λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.append p₂
instance : has_add (multiset α) := ⟨multiset.add⟩
@[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl
protected theorem add_comm (s t : multiset α) : s + t = t + s :=
quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_append_comm
protected theorem zero_add (s : multiset α) : 0 + s = s :=
quot.induction_on s $ λ l, rfl
theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a ::ₘ s := rfl
protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u :=
quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_append_left _
protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u :=
le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h))
((multiset.add_le_add_left _).1 (le_of_eq h.symm))
instance : ordered_cancel_add_comm_monoid (multiset α) :=
{ zero := 0,
add := (+),
add_comm := multiset.add_comm,
add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃,
congr_arg coe $ append_assoc l₁ l₂ l₃,
zero_add := multiset.zero_add,
add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add],
add_left_cancel := multiset.add_left_cancel,
add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $
by simpa [multiset.add_comm] using h,
add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h,
le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1,
..@multiset.partial_order α }
theorem le_add_right (s t : multiset α) : s ≤ s + t :=
by simpa using add_le_add_left (zero_le t) s
theorem le_add_left (s t : multiset α) : s ≤ t + s :=
by simpa using add_le_add_right (zero_le t) s
theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u :=
⟨λ h, le_induction_on h $ λ l₁ l₂ s,
let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩,
λ ⟨u, e⟩, e.symm ▸ le_add_right _ _⟩
instance : canonically_ordered_add_monoid (multiset α) :=
{ lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _,
le_iff_exists_add := @le_iff_exists_add _,
bot := 0,
bot_le := multiset.zero_le,
..multiset.ordered_cancel_add_comm_monoid }
@[simp] theorem cons_add (a : α) (s t : multiset α) : a ::ₘ s + t = a ::ₘ (s + t) :=
by rw [← singleton_add, ← singleton_add, add_assoc]
@[simp] theorem add_cons (a : α) (s t : multiset α) : s + a ::ₘ t = a ::ₘ (s + t) :=
by rw [add_comm, cons_add, add_comm]
@[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, mem_append
/-! ### Cardinality -/
/-- The cardinality of a multiset is the sum of the multiplicities
of all its elements, or simply the length of the underlying list. -/
def card : multiset α →+ ℕ :=
{ to_fun := λ s, quot.lift_on s length $ λ l₁ l₂, perm.length_eq,
map_zero' := rfl,
map_add' := λ s t, quotient.induction_on₂ s t length_append }
@[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl
@[simp] theorem card_zero : @card α 0 = 0 := rfl
theorem card_add (s t : multiset α) : card (s + t) = card s + card t :=
card.map_add s t
lemma card_smul (s : multiset α) (n : ℕ) :
(n •ℕ s).card = n * s.card :=
by rw [card.map_nsmul s n, nat.nsmul_eq_mul]
@[simp] theorem card_cons (a : α) (s : multiset α) : card (a ::ₘ s) = card s + 1 :=
quot.induction_on s $ λ l, rfl
@[simp] theorem card_singleton (a : α) : card (a ::ₘ 0) = 1 := by simp
theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t :=
le_induction_on h $ λ l₁ l₂, length_le_of_sublist
theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t :=
le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂
theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t :=
lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂
theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a ::ₘ s ≤ t :=
⟨quotient.induction_on₂ s t $ λ l₁ l₂ h,
subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h),
λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩
@[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 :=
⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩
theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 :=
pos_iff_ne_zero.trans $ not_congr card_eq_zero
theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s :=
quot.induction_on s $ λ l, length_pos_iff_exists_mem
@[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} :
∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s
| s := λ ih, ih s $ λ t h,
have card t < card s, from card_lt_of_lt h,
strong_induction_on t ih
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]}
theorem strong_induction_eq {p : multiset α → Sort*}
(s : multiset α) (H) : @strong_induction_on _ p s H =
H s (λ t h, @strong_induction_on _ p t H) :=
by rw [strong_induction_on]
@[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop}
(s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a ::ₘ s)) : p s :=
multiset.strong_induction_on s $ assume s,
multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $
λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _
/-! ### Singleton -/
instance : has_singleton α (multiset α) := ⟨λ a, a ::ₘ 0⟩
instance : is_lawful_singleton α (multiset α) := ⟨λ a, rfl⟩
@[simp] theorem singleton_eq_singleton (a : α) : singleton a = a ::ₘ 0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ a ::ₘ 0 ↔ b = a := by simp
theorem mem_singleton_self (a : α) : a ∈ (a ::ₘ 0 : multiset α) := mem_cons_self _ _
theorem singleton_inj {a b : α} : a ::ₘ 0 = b ::ₘ 0 ↔ a = b := cons_inj_left _
@[simp] theorem singleton_ne_zero (a : α) : a ::ₘ 0 ≠ 0 :=
ne_of_gt (lt_cons_self _ _)
@[simp] theorem singleton_le {a : α} {s : multiset α} : a ::ₘ 0 ≤ s ↔ a ∈ s :=
⟨λ h, mem_of_le h (mem_singleton_self _),
λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩
theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a ::ₘ 0 :=
⟨quot.induction_on s $ λ l h,
(list.length_eq_one.1 h).imp $ λ a, congr_arg coe,
λ ⟨a, e⟩, e.symm ▸ rfl⟩
/-! ### `multiset.repeat` -/
/-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/
def repeat (a : α) (n : ℕ) : multiset α := repeat a n
@[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl
@[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a ::ₘ repeat a n := by simp [repeat]
@[simp] lemma repeat_one (a : α) : repeat a 1 = a ::ₘ 0 := by simp
@[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat
theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat
theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
(perm_repeat.1 $ (quotient.exact h)), congr_arg coe⟩ eq_repeat'
theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card :=
eq_repeat'.2
theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a :=
⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a ::ₘ 0 := repeat_subset_singleton
theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l :=
⟨λ ⟨l', p, s⟩, (perm_repeat.1 p) ▸ s, sublist.subperm⟩
/-! ### Erasing one copy of an element -/
section erase
variables [decidable_eq α] {s t : multiset α} {a b : α}
/-- `erase s a` is the multiset that subtracts 1 from the
multiplicity of `a`. -/
def erase (s : multiset α) (a : α) : multiset α :=
quot.lift_on s (λ l, (l.erase a : multiset α))
(λ l₁ l₂ p, quot.sound (p.erase a))
@[simp] theorem coe_erase (l : list α) (a : α) :
erase (l : multiset α) a = l.erase a := rfl
@[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl
@[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a ::ₘ s).erase a = s :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l
@[simp, priority 990]
theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b ::ₘ s).erase a = b ::ₘ s.erase a :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h
@[simp, priority 980]
theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s :=
quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h
@[simp, priority 980]
theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a ::ₘ s.erase a = s :=
quot.induction_on s $ λ l h, quot.sound (perm_cons_erase h).symm
theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a ::ₘ s.erase a :=
if h : a ∈ s then le_of_eq (cons_erase h).symm
else by rw erase_of_not_mem h; apply le_cons_self
theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h
theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) :
(s + t).erase a = s + t.erase a :=
by rw [add_comm, erase_add_left_pos s h, add_comm]
theorem erase_add_right_neg {a : α} {s : multiset α} (t) :
a ∉ s → (s + t).erase a = s + t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h
theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) :
(s + t).erase a = s.erase a + t :=
by rw [add_comm, erase_add_right_neg s h, add_comm]
theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s :=
quot.induction_on s $ λ l, (erase_sublist a l).subperm
@[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s :=
⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h),
λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩
theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s :=
subset_of_le (erase_le a s)
theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s :=
quot.induction_on s $ λ l, list.mem_erase_of_ne ab
theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s :=
mem_of_subset (erase_subset _ _)
theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a :=
quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b
theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a :=
le_induction_on h $ λ l₁ l₂ h, (h.erase _).subperm
theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a ::ₘ t :=
⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h),
λ h, if m : a ∈ s
then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h
else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩
@[simp] theorem card_erase_of_mem {a : α} {s : multiset α} :
a ∈ s → card (s.erase a) = pred (card s) :=
quot.induction_on s $ λ l, length_erase_of_mem
theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s :=
λ h, card_lt_of_lt (erase_lt.mpr h)
theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s :=
card_le_of_le (erase_le a s)
end erase
@[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l :=
quot.sound $ reverse_perm _
/-! ### `multiset.map` -/
/-- `map f s` is the lift of the list `map` operation. The multiplicity
of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity)
such that `f a = b`. -/
def map (f : α → β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l : list α, (l.map f : multiset β))
(λ l₁ l₂ p, quot.sound (p.map f))
theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : multiset α} :
(∀ y ∈ s.map f, p y) ↔ (∀ x ∈ s, p (f x)) :=
quotient.induction_on' s $ λ L, list.forall_mem_map_iff
@[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl
@[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl
@[simp] theorem map_cons (f : α → β) (a s) : map f (a ::ₘ s) = f a ::ₘ map f s :=
quot.induction_on s $ λ l, rfl
lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl
theorem map_repeat (f : α → β) (a : α) (k : ℕ) : (repeat a k).map f = repeat (f a) k := by
{ induction k, simp, simpa }
@[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _
instance (f : α → β) : is_add_monoid_hom (map f) :=
{ map_add := map_add _, map_zero := map_zero _ }
theorem map_nsmul (f : α → β) (n s) : map f (n •ℕ s) = n •ℕ map f s :=
(add_monoid_hom.of (map f)).map_nsmul _ _
@[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} :
b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b :=
quot.induction_on s $ λ l, mem_map
@[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s :=
quot.induction_on s $ λ l, length_map _ _
@[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 :=
by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero]
theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s :=
mem_map.2 ⟨_, h, rfl⟩
theorem mem_map_of_injective {f : α → β} (H : function.injective f) {a : α} {s : multiset α} :
f a ∈ map f s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_map_of_injective H
@[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _
theorem map_id (s : multiset α) : map id s = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_id _
@[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s
@[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card :=
quot.induction_on s $ λ l, congr_arg coe $ map_const _ _
@[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s :=
quot.induction_on s $ λ l H, congr_arg coe $ map_congr H
lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m :=
begin subst h, simp at hf, simp [map_congr hf] end
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
eq_of_mem_repeat $ by rwa map_const at h
@[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t :=
le_induction_on h $ λ l₁ l₂ h, (h.map f).subperm
@[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t :=
λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩
/-! ### `multiset.fold` -/
/-- `foldl f H b s` is the lift of the list operation `foldl f b l`,
which folds `f` over the multiset. It is well defined when `f` is right-commutative,
that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/
def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldl f b l)
(λ l₁ l₂ p, p.foldl_eq H b)
@[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl
@[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a ::ₘ s) = foldl f H (f b a) s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _
/-- `foldr f H b s` is the lift of the list operation `foldr f b l`,
which folds `f` over the multiset. It is well defined when `f` is left-commutative,
that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/
def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldr f b l)
(λ l₁ l₂ p, p.foldr_eq H b)
@[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a ::ₘ s) = f a (foldr f H b s) :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _
@[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldr f b := rfl
@[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) :
foldl f H b l = l.foldl f b := rfl
theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldl (λ x y, f y x) b :=
(congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _
theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) :
foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _
theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) :
foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
(foldr_swap _ _ _ _).symm
/-- Product of a multiset given a commutative monoid structure on `α`.
`prod {a, b, c} = a * b * c` -/
@[to_additive]
def prod [comm_monoid α] : multiset α → α :=
foldr (*) (λ x y z, by simp [mul_left_comm]) 1
@[to_additive]
theorem prod_eq_foldr [comm_monoid α] (s : multiset α) :
prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl
@[to_additive]
theorem prod_eq_foldl [comm_monoid α] (s : multiset α) :
prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s :=
(foldr_swap _ _ _ _).trans (by simp [mul_comm])
@[simp, to_additive]
theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod :=
prod_eq_foldl _
attribute [norm_cast] coe_prod coe_sum
@[simp, to_additive]
theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl
@[simp, to_additive]
theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a ::ₘ s) = a * prod s :=
foldr_cons _ _ _ _ _
@[to_additive]
theorem prod_singleton [comm_monoid α] (a : α) : prod (a ::ₘ 0) = a := by simp
@[simp, to_additive]
theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t :=
quotient.induction_on₂ s t $ λ l₁ l₂, by simp
instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) :=
{ map_add := sum_add, map_zero := sum_zero }
lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) :
∀n, (n •ℕ m).prod = m.prod ^ n
| 0 := rfl
| (n + 1) :=
by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_smul n]
@[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n :=
by simp [repeat, list.prod_repeat]
@[simp] theorem sum_repeat [add_comm_monoid α] :
∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n •ℕ a :=
@prod_repeat (multiplicative α) _
attribute [to_additive] prod_repeat
lemma prod_map_one [comm_monoid γ] {m : multiset α} :
prod (m.map (λa, (1 : γ))) = (1 : γ) :=
by simp
lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} :
sum (m.map (λa, (0 : γ))) = (0 : γ) :=
by simp
attribute [to_additive] prod_map_one
@[simp, to_additive]
lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} :
prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc)
lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} :
prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih])
lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ},
sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) :=
@prod_map_prod_map _ _ (multiplicative γ) _
attribute [to_additive] prod_map_prod_map
lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, b * f a)) = b * sum (s.map f) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add])
lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, f a * b)) = sum (s.map f) * b :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul])
theorem prod_ne_zero {R : Type*} [comm_semiring R] [no_zero_divisors R] [nontrivial R]
{m : multiset R} :
(∀ x ∈ m, (x : _) ≠ 0) → m.prod ≠ 0 :=
multiset.induction_on m (λ _, one_ne_zero) $ λ hd tl ih H,
by { rw forall_mem_cons at H, rw prod_cons, exact mul_ne_zero H.1 (ih H.2) }
lemma prod_eq_zero {α : Type*} [comm_semiring α] {s : multiset α} (h : (0 : α) ∈ s) :
multiset.prod s = 0 :=
begin
rcases multiset.exists_cons_of_mem h with ⟨s', hs'⟩,
simp [hs', multiset.prod_cons]
end
@[to_additive]
lemma prod_hom [comm_monoid α] [comm_monoid β] (s : multiset α) (f : α →* β) :
(s.map f).prod = f s.prod :=
quotient.induction_on s $ λ l, by simp only [l.prod_hom f, quot_mk_to_coe, coe_map, coe_prod]
@[to_additive]
theorem prod_hom_rel [comm_monoid β] [comm_monoid γ] (s : multiset α) {r : β → γ → Prop}
{f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) :
r (s.map f).prod (s.map g).prod :=
quotient.induction_on s $ λ l,
by simp only [l.prod_hom_rel h₁ h₂, quot_mk_to_coe, coe_map, coe_prod]
lemma dvd_prod [comm_monoid α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod :=
quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a
lemma prod_dvd_prod [comm_monoid α] {s t : multiset α} (h : s ≤ t) :
s.prod ∣ t.prod :=
begin
rcases multiset.le_iff_exists_add.1 h with ⟨z, rfl⟩,
simp,
end
theorem prod_eq_zero_iff [comm_cancel_monoid_with_zero α] [nontrivial α]
{s : multiset α} :
s.prod = 0 ↔ (0 : α) ∈ s :=
multiset.induction_on s (by simp) $
assume a s, by simp [mul_eq_zero, @eq_comm _ 0 a] {contextual := tt}
@[to_additive sum_nonneg]
lemma one_le_prod_of_one_le [ordered_comm_monoid α] {m : multiset α} :
(∀ x ∈ m, (1 : α) ≤ x) → 1 ≤ m.prod :=
quotient.induction_on m $ λ l hl, by simpa using list.one_le_prod_of_one_le hl
@[to_additive]
lemma single_le_prod [ordered_comm_monoid α] {m : multiset α} :
(∀ x ∈ m, (1 : α) ≤ x) → ∀ x ∈ m, x ≤ m.prod :=
quotient.induction_on m $ λ l hl x hx, by simpa using list.single_le_prod hl x hx
@[to_additive all_zero_of_le_zero_le_of_sum_eq_zero]
lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α] {m : multiset α} :
(∀ x ∈ m, (1 : α) ≤ x) → m.prod = 1 → (∀ x ∈ m, x = (1 : α)) :=
begin
apply quotient.induction_on m,
simp only [quot_mk_to_coe, coe_prod, mem_coe],
intros l hl₁ hl₂ x hx,
apply all_one_of_le_one_le_of_prod_eq_one hl₁ hl₂ _ hx,
end
lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] {m : multiset α} :
m.sum = 0 ↔ ∀ x ∈ m, x = (0 : α) :=
quotient.induction_on m $ λ l, by simpa using list.sum_eq_zero_iff l
lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_add_comm_monoid β]
(f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : multiset α) :
f s.sum ≤ (s.map f).sum :=
multiset.induction_on s (le_of_eq h_zero) $
assume a s ih, by rw [sum_cons, map_cons, sum_cons];
from le_trans (h_add a s.sum) (add_le_add_left ih _)
lemma abs_sum_le_sum_abs [linear_ordered_field α] {s : multiset α} :
abs s.sum ≤ (s.map abs).sum :=
le_sum_of_subadditive _ abs_zero abs_add s
theorem dvd_sum [comm_semiring α] {a : α} {s : multiset α} : (∀ x ∈ s, a ∣ x) → a ∣ s.sum :=
multiset.induction_on s (λ _, dvd_zero _)
(λ x s ih h, by rw sum_cons; exact dvd_add
(h _ (mem_cons_self _ _)) (ih (λ y hy, h _ (mem_cons.2 (or.inr hy)))))
@[simp] theorem sum_map_singleton (s : multiset α) : (s.map (λ a, a ::ₘ 0)).sum = s :=
multiset.induction_on s (by simp) (by simp)
/-! ### Join -/
/-- `join S`, where `S` is a multiset of multisets, is the lift of the list join
operation, that is, the union of all the sets.
join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/
def join : multiset (multiset α) → multiset α := sum
theorem coe_join : ∀ L : list (list α),
join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join
| [] := rfl
| (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L)
@[simp] theorem join_zero : @join α 0 = 0 := rfl
@[simp] theorem join_cons (s S) : @join α (s ::ₘ S) = s + join S :=
sum_cons _ _
@[simp] theorem join_add (S T) : @join α (S + T) = join S + join T :=
sum_add _ _
@[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s :=
multiset.induction_on S (by simp) $
by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt}
@[simp] theorem card_join (S) : card (@join α S) = sum (map card S) :=
multiset.induction_on S (by simp) (by simp)
/-! ### `multiset.bind` -/
/-- `bind s f` is the monad bind operation, defined as `join (map f s)`.
It is the union of `f a` as `a` ranges over `s`. -/
def bind (s : multiset α) (f : α → multiset β) : multiset β :=
join (map f s)
@[simp] theorem coe_bind (l : list α) (f : α → list β) :
@bind α β l (λ a, f a) = l.bind f :=
by rw [list.bind, ← coe_join, list.map_map]; refl
@[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl
@[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a ::ₘ s) f = f a + bind s f :=
by simp [bind]
@[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f :=
by simp [bind]
@[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 :=
by simp [bind, join]
@[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) :
bind s (λa, f a + g a) = bind s f + bind s g :=
by simp [bind, join]
@[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) :
bind s (λa, f a ::ₘ g a) = map f s + bind s g :=
multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt})
@[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a :=
by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm];
rw exists_swap; simp [and_assoc]
@[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) :=
by simp [bind]
lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g :=
by simp [bind] {contextual := tt}
lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' :=
begin subst h, simp at hf, simp [bind_congr hf] end
lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) :
map f (bind m n) = bind m (λa, map f (n a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) :
bind (map f m) n = bind m (λa, n (f a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} :
(s.bind f).bind g = s.bind (λa, (f a).bind g) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} :
(bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} :
(bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
@[simp, to_additive]
lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) :
prod (bind s t) = prod (s.map $ λa, prod (t a)) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind])
/-! ### Product of two `multiset`s -/
/-- The multiplicity of `(a, b)` in `product s t` is
the product of the multiplicity of `a` in `s` and `b` in `t`. -/
def product (s : multiset α) (t : multiset β) : multiset (α × β) :=
s.bind $ λ a, t.map $ prod.mk a
@[simp] theorem coe_product (l₁ : list α) (l₂ : list β) :
@product α β l₁ l₂ = l₁.product l₂ :=
by rw [product, list.product, ← coe_bind]; simp
@[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl
@[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) :
product (a ::ₘ s) t = map (prod.mk a) t + product s t :=
by simp [product]
@[simp] theorem product_singleton (a : α) (b : β) : product (a ::ₘ 0) (b ::ₘ 0) = (a,b) ::ₘ 0 := rfl
@[simp] theorem add_product (s t : multiset α) (u : multiset β) :
product (s + t) u = product s u + product t u :=
by simp [product]
@[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β,
product s (t + u) = product s t + product s u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_product, IH]; simp; cc
@[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t
| (a, b) := by simp [product, and.left_comm]
@[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t :=
by simp [product, repeat, (∘), mul_comm]
/-! ### Sigma multiset -/
section
variable {σ : α → Type*}
/-- `sigma s t` is the dependent version of `product`. It is the sum of
`(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/
protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) :=
s.bind $ λ a, (t a).map $ sigma.mk a
@[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
@multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ :=
by rw [multiset.sigma, list.sigma, ← coe_bind]; simp
@[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl
@[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) :
(a ::ₘ s).sigma t = map (sigma.mk a) (t a) + s.sigma t :=
by simp [multiset.sigma]
@[simp] theorem sigma_singleton (a : α) (b : α → β) :
(a ::ₘ 0).sigma (λ a, b a ::ₘ 0) = ⟨a, b a⟩ ::ₘ 0 := rfl
@[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) :
(s + t).sigma u = s.sigma u + t.sigma u :=
by simp [multiset.sigma]
@[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a),
s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_sigma, IH]; simp; cc
@[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a},
p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1
| ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm]
@[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) :
card (s.sigma t) = sum (map (λ a, card (t a)) s) :=
by simp [multiset.sigma, (∘)]
end
/-! ### Map for partial functions -/
/-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset
`s` whose elements are all in the domain of `f`. -/
def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β :=
quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂),
funext $ λ (H₂ : ∀ a ∈ l₂, p a),
have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a (pp.subset h),
have ∀ {s₂ e H}, @eq.rec (multiset α) l₁
(λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁))
s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e,
this.trans $ quot.sound $ pp.pmap f
@[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β)
(l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl
@[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) :
pmap f 0 h = 0 := rfl
@[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) :
∀(h : ∀b∈a ::ₘ m, p b), pmap f (a ::ₘ m) h =
f a (h a (mem_cons_self a m)) ::ₘ pmap f m (λa ha, h a $ mem_cons_of_mem ha) :=
quotient.induction_on m $ assume l h, rfl
/-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce
a multiset on `{x // x ∈ s}`. -/
def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id)
@[simp] theorem coe_attach (l : list α) :
@eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl
theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : multiset α} (hx : x ∈ s) :
sizeof x < sizeof s := by
{ induction s with l a b, exact list.sizeof_lt_sizeof_of_mem hx, refl }
theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) :
∀ H, @pmap _ _ p (λ a _, f a) s H = map f s :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f s H₁ = pmap g s H₂ :=
quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H :=
quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H
theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s :=
quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l
@[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach :=
quot.induction_on s $ λ l, mem_attach _
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b :=
quot.induction_on s (λ l H, mem_pmap) H
@[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β)
(s H) : card (pmap f s H) = card s :=
quot.induction_on s (λ l H, length_pmap) H
@[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _
@[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl
lemma attach_cons (a : α) (m : multiset α) :
(a ::ₘ m).attach = ⟨a, mem_cons_self a m⟩ ::ₘ (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) :=
quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $
by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl)
section decidable_pi_exists
variables {m : multiset α}
protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] :
decidable (∀a∈m, p a) :=
quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp)
instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∀a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _))
/-- decidable equality for functions whose domain is bounded by multisets -/
instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈m, β a) :=
assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff])
def decidable_exists_multiset {p : α → Prop} [decidable_pred p] :
decidable (∃ x ∈ m, p x) :=
quotient.rec_on_subsingleton m list.decidable_exists_mem
instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∃a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩)
(λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩))
end decidable_pi_exists
/-! ### Subtraction -/
section
variables [decidable_eq α] {s t u : multiset α} {a b : α}
/-- `s - t` is the multiset such that
`count a (s - t) = count a s - count a t` for all `a`. -/
protected def sub (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ p₁.diff p₂
instance : has_sub (multiset α) := ⟨multiset.sub⟩
@[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl
theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂,
by { rw diff_eq_foldl l₁ l₂, symmetry, exact foldl_hom _ _ _ _ _ (λ x y, rfl) }
@[simp] theorem sub_zero (s : multiset α) : s - 0 = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a ::ₘ t = s.erase a - t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _
theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t :=
begin
revert t,
refine multiset.induction_on s (by simp) (λ a s IH t h, _),
have := cons_erase (mem_of_le h (mem_cons_self _ _)),
rw [cons_add, sub_cons, IH, this],
exact (cons_le_cons_iff a).1 (this.symm ▸ h)
end
theorem sub_add' : s - (t + u) = s - t - u :=
quotient.induction_on₃ s t u $
λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _
theorem sub_add_cancel (h : t ≤ s) : s - t + t = s :=
by rw [add_comm, add_sub_of_le h]
@[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t :=
multiset.induction_on s (by simp)
(λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH])
@[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s :=
by rw [add_comm, add_sub_cancel_left]
theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u :=
by revert s t h; exact
multiset.induction_on u (by simp {contextual := tt})
(λ a u IH s t h, by simp [IH, erase_le_erase a h])
theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s :=
le_induction_on h $ λ l₁ l₂ h, begin
induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u,
{ refl },
{ rw [← cons_coe, sub_cons],
exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) },
{ rw [← cons_coe, sub_cons, ← cons_coe, sub_cons],
exact IH _ }
end
theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t :=
by revert s; exact
multiset.induction_on t (by simp)
(λ a t IH s, by simp [IH, erase_le_iff_le_cons])
theorem le_sub_add (s t : multiset α) : s ≤ s - t + t :=
sub_le_iff_le_add.1 (le_refl _)
theorem sub_le_self (s t : multiset α) : s - t ≤ s :=
sub_le_iff_le_add.2 (le_add_right _ _)
@[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t :=
(nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm
/-! ### Union -/
/-- `s ∪ t` is the lattice join operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum
of the multiplicities in `s` and `t`. -/
def union (s t : multiset α) : multiset α := s - t + t
instance : has_union (multiset α) := ⟨union⟩
theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl
theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _
theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _
theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel
theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u :=
add_le_add_right (sub_le_sub_right h _) u
theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u :=
by rw ← eq_union_left h₂; exact union_le_union_right h₁ t
@[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t :=
⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _),
or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩
@[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} :
map f (s ∪ t) = map f s ∪ map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
congr_arg coe (by rw [list.map_append f, list.map_diff finj])
/-! ### Intersection -/
/-- `s ∩ t` is the lattice meet operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum
of the multiplicities in `s` and `t`. -/
def inter (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ p₁.bag_inter p₂
instance : has_inter (multiset α) := ⟨inter⟩
@[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil
@[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter
@[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} :
a ∈ t → (a ::ₘ s) ∩ t = a ::ₘ s ∩ t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_pos _ h
@[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} :
a ∉ t → (a ::ₘ s) ∩ t = s ∩ t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_neg _ h
theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s :=
quotient.induction_on₂ s t $ λ l₁ l₂,
(bag_inter_sublist_left _ _).subperm
theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t :=
multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $
λ a s IH t, if h : a ∈ t
then by simpa [h] using cons_le_cons a (IH (t.erase a))
else by simp [h, IH]
theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u :=
begin
revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros,
{ simp [h₁] },
by_cases a ∈ u,
{ rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons],
exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) },
{ rw cons_inter_of_neg _ h,
exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ }
end
@[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t :=
⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩,
λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩
instance : lattice (multiset α) :=
{ sup := (∪),
sup_le := @union_le _ _,
le_sup_left := le_union_left,
le_sup_right := le_union_right,
inf := (∩),
le_inf := @le_inter _ _,
inf_le_left := inter_le_left,
inf_le_right := inter_le_right,
..@multiset.partial_order α }
@[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl
@[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl
@[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff
@[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff
instance : semilattice_inf_bot (multiset α) :=
{ bot := 0, bot_le := zero_le, ..multiset.lattice }
theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm
theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm
theorem eq_union_right (h : s ≤ t) : s ∪ t = t :=
by rw [union_comm, eq_union_left h]
theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t :=
sup_le_sup_left h _
theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t :=
union_le (le_add_right _ _) (le_add_left _ _)
theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) :=
by simpa [(∪), union, eq_comm, add_assoc] using show s + u - (t + u) = s - t,
by rw [add_comm t, sub_add', add_sub_cancel]
theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) :=
by rw [add_comm, union_add_distrib, add_comm s, add_comm s]
theorem cons_union_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∪ t) = (a ::ₘ s) ∪ (a ::ₘ t) :=
by simpa using add_union_distrib (a ::ₘ 0) s t
theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) :=
begin
by_contra h,
cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter
(add_le_add_right (inter_le_left s t) u)
(add_le_add_right (inter_le_right s t) u)) h) with a hl,
rw ← cons_add at hl,
exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter
(le_of_add_le_add_right (le_trans hl (inter_le_left _ _)))
(le_of_add_le_add_right (le_trans hl (inter_le_right _ _))))
end
theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) :=
by rw [add_comm, inter_add_distrib, add_comm s, add_comm s]
theorem cons_inter_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∩ t) = (a ::ₘ s) ∩ (a ::ₘ t) :=
by simp
theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t :=
begin
apply le_antisymm,
{ rw union_add_distrib,
refine union_le (add_le_add_left (inter_le_right _ _) _) _,
rw add_comm, exact add_le_add_right (inter_le_left _ _) _ },
{ rw [add_comm, add_inter_distrib],
refine le_inter (add_le_add_right (le_union_right _ _) _) _,
rw add_comm, exact add_le_add_right (le_union_left _ _) _ }
end
theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s :=
begin
rw [inter_comm],
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
by_cases a ∈ s,
{ rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] },
{ rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] }
end
theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t :=
add_right_cancel $
by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)]
end
/-! ### `multiset.filter` -/
section
variables (p : α → Prop) [decidable_pred p]
/-- `filter p s` returns the elements in `s` (with the same multiplicities)
which satisfy `p`, and removes the rest. -/
def filter (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (filter p l : multiset α))
(λ l₁ l₂ h, quot.sound $ h.filter p)
@[simp] theorem coe_filter (l : list α) : filter p (↑l) = l.filter p := rfl
@[simp] theorem filter_zero : filter p 0 = 0 := rfl
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
{s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h
@[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _
@[simp] theorem filter_le (s : multiset α) : filter p s ≤ s :=
quot.induction_on s $ λ l, (filter_sublist _).subperm
@[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s :=
subset_of_le $ filter_le _ _
theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t :=
le_induction_on h $ λ l₁ l₂ h, (filter_sublist_filter p h).subperm
variable {p}
@[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a ::ₘ s) = a ::ₘ filter p s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h
@[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a ::ₘ s) = filter p s :=
quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h
@[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a :=
quot.induction_on s $ λ l, mem_filter
theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a :=
(mem_filter.1 h).2
theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s :=
(mem_filter.1 h).1
theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l :=
mem_filter.2 ⟨m, h⟩
theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_self
theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_nil
theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a :=
⟨λ h, ⟨le_trans h (filter_le _ _), λ a m, of_mem_filter (mem_of_le h m)⟩,
λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter p h⟩
variable (p)
@[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) :
filter p (s - t) = filter p s - filter p t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
rw [sub_cons, IH],
by_cases p a,
{ rw [filter_cons_of_pos _ h, sub_cons], congr,
by_cases m : a ∈ s,
{ rw [← cons_inj_right a, ← filter_cons_of_pos _ h,
cons_erase (mem_filter_of_mem m h), cons_erase m] },
{ rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } },
{ rw [filter_cons_of_neg _ h],
by_cases m : a ∈ s,
{ rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a ::ₘ erase s a)),
cons_erase m] },
{ rw [erase_of_not_mem m] } }
end
@[simp] theorem filter_union [decidable_eq α] (s t : multiset α) :
filter p (s ∪ t) = filter p s ∪ filter p t :=
by simp [(∪), union]
@[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) :
filter p (s ∩ t) = filter p s ∩ filter p t :=
le_antisymm (le_inter
(filter_le_filter _ $ inter_le_left _ _)
(filter_le_filter _ $ inter_le_right _ _)) $ le_filter.2
⟨inf_le_inf (filter_le _ _) (filter_le _ _),
λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩
@[simp] theorem filter_filter (q) [decidable_pred q] (s : multiset α) :
filter p (filter q s) = filter (λ a, p a ∧ q a) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter p q l
theorem filter_add_filter (q) [decidable_pred q] (s : multiset α) :
filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s :=
multiset.induction_on s rfl $ λ a s IH,
by by_cases p a; by_cases q a; simp *
theorem filter_add_not (s : multiset α) :
filter p s + filter (λ a, ¬ p a) s = s :=
by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em]
/-! ### Simultaneously filter and map elements of a multiset -/
/-- `filter_map f s` is a combination filter/map operation on `s`.
The function `f : α → option β` is applied to each element of `s`;
if `f a` is `some b` then `b` is added to the result, otherwise
`a` is removed from the resulting multiset. -/
def filter_map (f : α → option β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l, (filter_map f l : multiset β))
(λ l₁ l₂ h, quot.sound $ h.filter_map f)
@[simp] theorem coe_filter_map (f : α → option β) (l : list α) :
filter_map f l = l.filter_map f := rfl
@[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) :
filter_map f (a ::ₘ s) = filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (s : multiset α) {b : β} (h : f a = some b) :
filter_map f (a ::ₘ s) = b ::ₘ filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l
theorem filter_map_eq_filter : filter_map (option.guard p) = filter p :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) :
filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l
theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) :
map g (filter_map f s) = filter_map (λ x, (f x).map g) s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l
theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) :
filter_map g (map f s) = filter_map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) :
filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l
theorem filter_map_filter (f : α → option β) (s : multiset α) :
filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l
@[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l
@[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} :
b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b :=
quot.induction_on s $ λ l, mem_filter_map f l
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (s : multiset α) :
map g (filter_map f s) = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l
theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α}
(h : s ≤ t) : filter_map f s ≤ filter_map f t :=
le_induction_on h $ λ l₁ l₂ h, (h.filter_map _).subperm
/-! ### countp -/
/-- `countp p s` counts the number of elements of `s` (with multiplicity) that
satisfy `p`. -/
def countp (s : multiset α) : ℕ :=
quot.lift_on s (countp p) (λ l₁ l₂, perm.countp_eq p)
@[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl
@[simp] theorem countp_zero : countp p 0 = 0 := rfl
variable {p}
@[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a ::ₘ s) = countp p s + 1 :=
quot.induction_on s $ countp_cons_of_pos p
@[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a ::ₘ s) = countp p s :=
quot.induction_on s $ countp_cons_of_neg p
variable (p)
theorem countp_eq_card_filter (s) : countp p s = card (filter p s) :=
quot.induction_on s $ λ l, countp_eq_length_filter _ _
@[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t :=
by simp [countp_eq_card_filter]
instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) :=
{ map_add := countp_add _, map_zero := countp_zero _ }
@[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) :
countp p (s - t) = countp p s - countp p t :=
by simp [countp_eq_card_filter, h, filter_le_filter]
theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t :=
by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter p h)
@[simp] theorem countp_filter (q) [decidable_pred q] (s : multiset α) :
countp p (filter q s) = countp (λ a, p a ∧ q a) s :=
by simp [countp_eq_card_filter]
variable {p}
theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a :=
by simp [countp_eq_card_filter, card_pos_iff_exists_mem]
theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s :=
countp_pos.2 ⟨_, h, pa⟩
end
/-! ### Multiplicity of an element -/
section
variable [decidable_eq α]
/-- `count a s` is the multiplicity of `a` in `s`. -/
def count (a : α) : multiset α → ℕ := countp (eq a)
@[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ _
@[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl
@[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a ::ₘ s) = succ (count a s) :=
countp_cons_of_pos _ rfl
@[simp, priority 990]
theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b ::ₘ s) = count a s :=
countp_cons_of_neg _ h
theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t :=
countp_le_of_le _
theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b ::ₘ s) :=
count_le_of_le _ (le_cons_self _ _)
theorem count_cons (a b : α) (s : multiset α) :
count a (b ::ₘ s) = count a s + (if a = b then 1 else 0) :=
by by_cases h : a = b; simp [h]
theorem count_singleton (a : α) : count a (a ::ₘ 0) = 1 :=
by simp
@[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t :=
countp_add _
instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) :=
countp.is_add_monoid_hom _
@[simp] theorem count_smul (a : α) (n s) : count a (n •ℕ s) = n * count a s :=
by induction n; simp [*, succ_nsmul', succ_mul]
theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s :=
by simp [count, countp_pos]
@[simp, priority 980]
theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
@[simp] theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s :=
iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero
theorem count_ne_zero {a : α} {s : multiset α} : count a s ≠ 0 ↔ a ∈ s :=
by simp [ne.def, count_eq_zero]
@[simp] theorem count_repeat_self (a : α) (n : ℕ) : count a (repeat a n) = n :=
by simp [repeat]
theorem count_repeat (a b : α) (n : ℕ) :
count a (repeat b n) = if (a = b) then n else 0 :=
begin
split_ifs with h₁,
{ rw [h₁, count_repeat_self] },
{ rw [count_eq_zero],
apply mt eq_of_mem_repeat h₁ },
end
@[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) :=
begin
by_cases a ∈ s,
{ rw [(by rw cons_erase h : count a s = count a (a ::ₘ erase s a)),
count_cons_self]; refl },
{ rw [erase_of_not_mem h, count_eq_zero.2 h]; refl }
end
@[simp, priority 980]
theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s :=
begin
by_cases b ∈ s,
{ rw [← count_cons_of_ne ab, cons_erase h] },
{ rw [erase_of_not_mem h] }
end
@[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _),
rw [sub_cons, IH],
by_cases ab : a = b,
{ subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] },
{ rw [count_erase_of_ne ab, count_cons_of_ne ab] }
end
@[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) :=
by simp [(∪), union, sub_add_eq_max, -add_comm]
@[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) :=
begin
apply @nat.add_left_cancel (count a (s - t)),
rw [← count_add, sub_add_inter, count_sub, sub_add_min],
end
lemma count_sum {m : multiset β} {f : β → multiset α} {a : α} :
count a (map f m).sum = sum (m.map $ λb, count a $ f b) :=
multiset.induction_on m (by simp) ( by simp)
lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} :
count a (bind m f) = sum (m.map $ λb, count a $ f b) := count_sum
theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s :=
quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm
@[simp] theorem count_filter_of_pos {p} [decidable_pred p]
{a} {s : multiset α} (h : p a) : count a (filter p s) = count a s :=
quot.induction_on s $ λ l, count_filter h
@[simp] theorem count_filter_of_neg {p} [decidable_pred p]
{a} {s : multiset α} (h : ¬ p a) : count a (filter p s) = 0 :=
multiset.count_eq_zero_of_not_mem (λ t, h (of_mem_filter t))
theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t :=
quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count
@[ext]
theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t :=
ext.2
@[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) :=
by ext; simp
theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t :=
⟨λ h a, count_le_of_le a h, λ al,
by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t);
apply le_union_left⟩
instance : distrib_lattice (multiset α) :=
{ le_sup_inf := λ s t u, le_of_eq $ eq.symm $
ext.2 $ λ a, by simp only [max_min_distrib_left,
multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter],
..multiset.lattice }
instance : semilattice_sup_bot (multiset α) :=
{ bot := 0,
bot_le := zero_le,
..multiset.lattice }
end
@[simp]
lemma mem_nsmul {a : α} {s : multiset α} {n : ℕ} (h0 : n ≠ 0) :
a ∈ n •ℕ s ↔ a ∈ s :=
begin
classical,
cases n,
{ exfalso, apply h0 rfl },
rw [← not_iff_not, ← count_eq_zero, ← count_eq_zero],
simp [h0],
end
/-! ### Lift a relation to `multiset`s -/
section rel
/-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`,
s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/
@[mk_iff] inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop
| zero : rel 0 0
| cons {a b as bs} : r a b → rel as bs → rel (a ::ₘ as) (b ::ₘ bs)
variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s :=
rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih)
lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s :=
⟨rel_flip_aux, rel_flip_aux⟩
lemma rel_eq_refl {s : multiset α} : rel (=) s s :=
multiset.induction_on s rel.zero (assume a s, rel.cons rfl)
lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t :=
begin
split,
{ assume h, induction h; simp * },
{ assume h, subst h, exact rel_eq_refl }
end
lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t :=
begin
induction hst,
case rel.zero { exact rel.zero },
case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) }
end
lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) :=
begin
induction hst,
case rel.zero { simpa using huv },
case rel.cons : a b s t hab hst ih { simpa using ih.cons hab }
end
lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t :=
show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm]
@[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 :=
by rw [rel_iff]; simp
@[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 :=
by rw [rel_iff]; simp
lemma rel_cons_left {a as bs} :
rel r (a ::ₘ as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b ::ₘ bs') :=
begin
split,
{ generalize hm : a ::ₘ as = m,
assume h,
induction h generalizing as,
case rel.zero { simp at hm, contradiction },
case rel.cons : a' b as' bs ha'b h ih {
rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ },
{ rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩,
exact ⟨b', b ::ₘ bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ }
} },
{ exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h }
end
lemma rel_cons_right {as b bs} :
rel r as (b ::ₘ bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a ::ₘ as') :=
begin
rw [← rel_flip, rel_cons_left],
apply exists_congr, assume a,
apply exists_congr, assume as',
rw [rel_flip, flip]
end
lemma rel_add_left {as₀ as₁} :
∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) :=
multiset.induction_on as₀ (by simp)
begin
assume a s ih bs,
simp only [ih, cons_add, rel_cons_left],
split,
{ assume h,
rcases h with ⟨b, bs', hab, h, rfl⟩,
rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩,
exact ⟨b ::ₘ bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ },
{ assume h,
rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩,
rcases h with ⟨b, bs, hab, h₀, rfl⟩,
exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ }
end
lemma rel_add_right {as bs₀ bs₁} :
rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) :=
by rw [← rel_flip, rel_add_left]; simp [rel_flip]
lemma rel_map_left {s : multiset γ} {f : γ → α} :
∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t :=
multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt})
lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} :
rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t :=
by rw [← rel_flip, rel_map_left, ← rel_flip]; refl
lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join :=
begin
induction h,
case rel.zero { simp },
case rel.cons : a b s t hab hst ih { simpa using hab.add ih }
end
lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) :
rel p (s.map f) (t.map g) :=
by rw [rel_map_left, rel_map_right]; exact hst.mono h
lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ}
(h : (r ⇒ rel p) f g) (hst : rel r s t) :
rel p (s.bind f) (t.bind g) :=
by apply rel_join; apply rel_map; assumption
lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
card s = card t :=
by induction h; simp [*]
lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b :=
begin
induction h with x y s t hxy hst ih,
{ simp },
{ assume a ha,
cases mem_cons.1 ha with ha ha,
{ exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ },
{ rcases ih ha with ⟨b, hbt, hab⟩,
exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } }
end
end rel
section map
theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} :
s.map f = t.map f ↔ s = t :=
by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff]
theorem map_injective {f : α → β} (hf : function.injective f) :
function.injective (multiset.map f) :=
assume x y, (map_eq_map hf).1
end map
section quot
theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) :
s.map (quot.mk r) = t.map (quot.mk r) :=
rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab]
theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) :
∃t:multiset α, s = t.map (quot.mk r) :=
multiset.induction_on s ⟨0, rfl⟩ $
assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a ::ₘ t, (map_cons _ _ _).symm⟩
theorem induction_on_multiset_quot
{r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) :
(∀s:multiset α, p (s.map (quot.mk r))) → p s :=
match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end
end quot
/-! ### Disjoint multisets -/
/-- `disjoint s t` means that `s` and `t` have no elements in common. -/
def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false
@[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl
theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s
| a i₂ i₁ := d i₁ i₂
theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl
theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
disjoint_comm
theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp [disjoint_left, imp_not_comm]
theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t
| x m₁ := d (h m₁)
theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t
| x m m₁ := d m (h m₁)
theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t :=
disjoint_of_subset_left (subset_of_le h)
theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t :=
disjoint_of_subset_right (subset_of_le h)
@[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l
| a := (not_mem_nil a).elim
@[simp, priority 1100]
theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a ::ₘ 0) l ↔ a ∉ l :=
by simp [disjoint]; refl
@[simp, priority 1100]
theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a ::ₘ 0) ↔ a ∉ l :=
by rw disjoint_comm; simp
@[simp] theorem disjoint_add_left {s t u : multiset α} :
disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_add_right {s t u : multiset α} :
disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u :=
by rw [disjoint_comm, disjoint_add_left]; tauto
@[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} :
disjoint (a ::ₘ s) t ↔ a ∉ t ∧ disjoint s t :=
(@disjoint_add_left _ (a ::ₘ 0) s t).trans $ by simp
@[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} :
disjoint s (a ::ₘ t) ↔ a ∉ s ∧ disjoint s t :=
by rw [disjoint_comm, disjoint_cons_left]; tauto
theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
@[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} :
disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) :=
by { simp [disjoint, @eq_comm _ (f _) (g _)], refl }
/-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/
def pairwise (r : α → α → Prop) (m : multiset α) : Prop :=
∃l:list α, m = l ∧ l.pairwise r
lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} :
multiset.pairwise r l ↔ l.pairwise r :=
iff.intro
(assume ⟨l', eq, h⟩, ((quotient.exact eq).pairwise_iff hr).2 h)
(assume h, ⟨l, rfl, h⟩)
end multiset
namespace multiset
section choose
variables (p : α → Prop) [decidable_pred p] (l : multiset α)
/-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose_x p l hp` returns
that `a` together with proofs of `a ∈ l` and `p a`. -/
def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } :=
quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin
intros,
funext hp,
suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y,
{ apply all_equal },
{ rintros ⟨x, px⟩ ⟨y, py⟩,
rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩,
congr,
calc x = z : z_unique x px
... = y : (z_unique y py).symm }
end
/-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns
that `a`. -/
def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp
lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
variable (α)
/-- The equivalence between lists and multisets of a subsingleton type. -/
def subsingleton_equiv [subsingleton α] : list α ≃ multiset α :=
{ to_fun := coe,
inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b),
list.ext_le h.length_eq $ λ n h₁ h₂, subsingleton.elim _ _,
left_inv := λ l, rfl,
right_inv := λ m, quot.induction_on m $ λ l, rfl }
end multiset
@[to_additive]
theorem monoid_hom.map_multiset_prod [comm_monoid α] [comm_monoid β] (f : α →* β) (s : multiset α) :
f s.prod = (s.map f).prod :=
(s.prod_hom f).symm
|
cf1874c583fbf037d3670d72214041d7931d3085
|
74addaa0e41490cbaf2abd313a764c96df57b05d
|
/Mathlib/data/nat/choose/default.lean
|
807baa6363db8518feb48544dcd1012613e2e69c
|
[] |
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
| 174
|
lean
|
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.nat.choose.dvd
import Mathlib.data.nat.choose.sum
import Mathlib.PostPort
namespace Mathlib
|
016e56884bbd5b53e755cd7990021e99b38da057
|
8461211c55a0962f1c8b2e7537d535b4c68194a2
|
/tao_analysis/02_natural_numbers.lean
|
d3c5718ddcd7c9159f29b00321bf8a70010a5bf8
|
[] |
no_license
|
alanhdu/lean-proofs
|
ba687a3d289c58cce9cf80a66f55bed2cdf4bdfb
|
a02cb9d0d2b6a6457f35247b89253d727f641531
|
refs/heads/master
| 1,598,769,649,392
| 1,575,379,585,000
| 1,575,379,585,000
| 218,293,755
| 1
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 9,333
|
lean
|
inductive xnat : Type
| zero : xnat
| succ : xnat → xnat
namespace xnat
axiom succ_ne_zero : ∀ n : xnat, xnat.succ n ≠ xnat.zero
axiom succ_inj : ∀ {n m: xnat}, xnat.succ n = xnat.succ m → n = m
def add : xnat → xnat → xnat
| zero m := m
| (succ n) m := succ (add n m)
-- Lemma 2.2.2
theorem add_zero : ∀ {n: xnat}, add n zero = n
| zero := by refl
| (succ n) := begin
have : add (succ n) zero = succ (add n zero), by refl,
show add (succ n) zero = succ n, by rw [this, add_zero],
end
-- Lemma 2.2.3
theorem add_succ : ∀ {n m : xnat}, add n (succ m) = succ (add n m) := begin
intros n m,
induction n, {
refl,
}, {
calc
add (succ n_a) (succ m) = succ (add n_a (succ m)) : by refl
... = succ (succ (add n_a m)) : by rw n_ih
... = succ (add (succ n_a) m): by refl
}
end
theorem add_succ' : ∀ n m : xnat, add n (succ m) = succ (add n m)
| zero m := by refl
| (succ n) m := begin
have h1 : add (succ n) (succ m) = succ (add n (succ m)), by refl,
have h2 : succ (succ (add n m)) = succ (add (succ n) m), by refl,
rw [h1, add_succ', h2]
end
-- Lemma 2.2.4
theorem add_comm : ∀ n m : xnat, add n m = add m n
| zero m := by {rw add_zero, refl}
| (succ n) m := begin
have : add (succ n) m = succ (add n m), by refl,
show add (succ n) m = add m (succ n), by rw [
this, add_comm, add_succ
],
end
-- Proposition 2.2.5
theorem add_assoc : ∀ a b c : xnat, add a (add b c) = add (add a b) c :=
begin
intros a b c,
induction a, {
refl
}, {
calc
add (succ a_a) (add b c) = succ (add a_a (add b c)) : by refl
... = succ (add (add a_a b) c) : by rw a_ih
... = add (add (succ a_a) b) c : by refl
}
end
-- Proposition 2.2.6
theorem add_left_cancel : ∀ {a b c: xnat}, add a b = add a c → b = c :=
begin
intros a b c,
intro h,
induction a, {
calc
b = add zero b : by refl
... = add zero c : h
... = c : by refl
}, {
have : add (succ a_a) b = succ (add a_a b), by refl,
rw this at h,
have : add (succ a_a) c = succ (add a_a c), by refl,
rw this at h,
have : add a_a b = add a_a c, from succ_inj h,
from a_ih this
}
end
def pos (n: xnat) : Prop := n ≠ zero
-- Proposition 2.2.8
theorem add_pos: ∀ a b : xnat, pos a → pos (add a b) := begin
intros a b,
intros pa,
induction a, {
have : zero = zero, by refl,
contradiction
}, {
have : add (succ a_a) b = succ (add a_a b), by refl,
rw this,
from succ_ne_zero (add a_a b)
}
end
-- colloary 2.2.9
theorem eq_zero_of_add_eq_zero:
∀ {a b : xnat}, (add a b) = zero → (a = zero ∧ b = zero) :=
begin
intros a b h,
induction a, {
split,
show zero = zero, by refl,
show b = zero, {
have : add zero b = b, by refl,
rw this at h,
assumption
}
}, {
have : succ (add a_a b) = zero, from (
calc
succ (add a_a b) = add (succ a_a) b : by refl
... = zero : h
),
have : succ (add a_a b) ≠ zero, from succ_ne_zero _,
contradiction
}
end
-- Lemma 2.2.10
theorem exists_eq_succ_of_ne_zero:
∀ a: xnat, a ≠ zero → ∃ b: xnat, a = succ b
| zero := by {intro, contradiction}
| (succ a) := begin
intro,
existsi a, refl
end
theorem exists_unique_pred:
∀ a b c: xnat, (succ a = c) → (succ b = c) → (a = b) :=
begin
intros a b c sac sbc,
have : succ a = succ b, {
transitivity,
assumption,
symmetry, assumption,
},
show a = b, from succ_inj this
end
def le (n m: xnat) := ∃ a : xnat, add n a = m
def lt (n m: xnat) := (le n m) ∧ n ≠ m
-- Proposition 2.2.12
theorem le_refl: ∀ n : xnat, le n n := begin
intro n,
existsi zero, from add_zero
end
theorem le_trans: ∀ {a b c : xnat}, le a b → le b c → le a c := begin
intros a b c gab gbc,
cases gab with n pan,
cases gbc with m pbm,
existsi (add n m),
show (add a (add n m )) = c, by rw [add_assoc, pan, pbm]
end
lemma add_eq_zero: ∀ {n m: xnat}, add n m = n → m = zero := begin
intros n m h,
have : add n zero = n, from add_zero,
have : add n m = add n zero, by {
transitivity n, assumption,
symmetry, assumption,
},
show m = zero, from add_left_cancel this
end
theorem le_anti_symm: ∀ {a b : xnat}, le a b → le b a → a = b := begin
intros a b gab gba,
cases gab with n pan, cases gba with m pbm,
have : add n m = zero, by {
have : a = add zero a, by refl,
rw [←pan, ←add_assoc] at pbm,
from add_eq_zero pbm,
},
have : n = zero ∧ m = zero, from eq_zero_of_add_eq_zero this,
cases this with nz _,
have pan: add a zero = b, by {rw ←nz, assumption},
show a = b, {
have : add a zero = a, from add_zero,
rw this at pan, assumption
}
end
lemma add_succ_eq_succ_add :
∀ {a b : xnat}, add (succ a) b = add a (succ b) := λ a b, calc
add (succ a) b = succ (add a b) : by refl
... = add a (succ b) : by {symmetry, from add_succ}
theorem lt_succ_le: ∀ {a b : xnat}, lt a b ↔ le (succ a) b := begin
intros a b,
split; intro h,
show le (succ a) b, by {
cases h with a_le_b a_ne_b,
cases a_le_b with n a_plus_n_eq_b,
cases n, {
have : a = b, from (calc
a = add a zero : by { symmetry, from add_zero}
... = b : a_plus_n_eq_b
),
contradiction -- a ≠ b ∧ a = b
}, {
existsi n, from (calc
add (succ a) n = succ (add a n) : by refl
... = add a (succ n) : by rw ←add_succ
... = b : a_plus_n_eq_b
)
}
},
show lt a b, by {
cases h with n ap1_plus_n_eq_b,
split,
show le a b, by {
existsi (succ n),
show add a (succ n) = b, {from calc
add a (succ n) = succ (add a n) : add_succ
... = add (succ a) n : by {symmetry, refl}
... = b : ap1_plus_n_eq_b
}
},
show a ≠ b, by {
intro a_eq_b,
have : add b (succ n) = b, {from calc
add b (succ n) = add (succ b) n : by rw add_succ_eq_succ_add
... = add (succ a) n : by rw a_eq_b
... = b : ap1_plus_n_eq_b
},
have : succ n = zero, from add_eq_zero this,
have : succ n ≠ zero, from succ_ne_zero _,
contradiction
},
}
end
theorem lt_eq_add :
∀ {a b: xnat}, lt a b ↔ ∃ d: xnat, pos d ∧ b = add a d :=
begin
intros a b,
split, {
intro lt_a_b,
have : le (succ a) b, from iff.mp lt_succ_le lt_a_b,
cases this with n add_succ_a_n_eq_b,
existsi (succ n),
split,
show pos (succ n), from succ_ne_zero n,
show b = add a (succ n), {from calc
b = add (succ a) n : eq.symm add_succ_a_n_eq_b
... = add a (succ n) : add_succ_eq_succ_add
}
}, {
intro h,
cases h with n h1,
cases h1 with pos_n b_eq_add_a_n,
split,
show le a b, by { existsi n, from eq.symm b_eq_add_a_n },
show a ≠ b, by {
intro a_eq_b,
have : add b n = b, by { symmetry, rwa a_eq_b at b_eq_add_a_n},
have : n = zero, from add_eq_zero this,
contradiction -- n = zero, but n is positive
}
}
end
lemma lt_succ: ∀ {a b: xnat}, lt a b → lt (succ a) (succ b) := begin
intros a b lt_a_b,
split,
show (le (succ a) (succ b)), by {
cases lt_a_b.left with n _,
existsi n, {from calc
add (succ a) n = succ (add a n) : by refl
... = succ b : by rw h
}
},
show (succ a ≠ succ b), by {
intro h,
have: a = b, from xnat.succ_inj h,
have: a ≠ b, from lt_a_b.right,
contradiction
}
end
theorem trichotomy: ∀ {a b: xnat}, lt a b ∨ a = b ∨ lt b a
| zero zero := or.inr (or.inl (eq.refl zero))
| (succ a) zero := begin
right, right, show lt zero (succ a), by {
split,
show le zero (succ a), by { existsi (succ a), refl },
show zero ≠ succ a, by trivial
},
end
| zero (succ b) := begin
left,
show lt zero (succ b), by {
split,
show le zero (succ b), by { existsi (succ b), refl },
show zero ≠ succ b, by trivial
}
end
| (succ a) (succ b) := begin
have : lt a b ∨ a = b ∨ lt b a, from trichotomy,
cases this with lt_a_b h,
any_goals { cases h with a_eq_b lt_b_a }, {
-- a < b
left, from lt_succ lt_a_b,
}, {
-- a = b
right, left,
show succ a = succ b, by rw a_eq_b,
}, {
-- a > b
right, right, from lt_succ lt_b_a,
}
end
end xnat
example : 4 ≠ 0 := nat.succ_ne_zero 3
example : 6 ≠ 2 := begin
intro h,
have : 5 = 1, from nat.succ_inj h,
have : 4 = 0, from nat.succ_inj this,
have : 4 ≠ 0, from nat.succ_ne_zero 3,
contradiction
end
|
394ab0986351f32cf6894a619df80560b3c9a9c2
|
d406927ab5617694ec9ea7001f101b7c9e3d9702
|
/src/linear_algebra/quadratic_form/real.lean
|
8e172a1e9c1c58fbe933e5c4bcd8ac4d1456fb38
|
[
"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,362
|
lean
|
/-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen, Kexing Ying, Eric Wieser
-/
import linear_algebra.quadratic_form.isometry
import analysis.special_functions.pow
import data.real.sign
/-!
# Real quadratic forms
Sylvester's law of inertia `equivalent_one_neg_one_weighted_sum_squared`:
A real quadratic form is equivalent to a weighted
sum of squares with the weights being ±1 or 0.
When the real quadratic form is nondegerate we can take the weights to be ±1,
as in `equivalent_one_zero_neg_one_weighted_sum_squared`.
-/
namespace quadratic_form
open_locale big_operators
open real finset
variables {ι : Type*} [fintype ι]
/-- The isometry between a weighted sum of squares with weights `u` on the
(non-zero) real numbers and the weighted sum of squares with weights `sign ∘ u`. -/
noncomputable def isometry_sign_weighted_sum_squares
[decidable_eq ι] (w : ι → ℝ) :
isometry (weighted_sum_squares ℝ w) (weighted_sum_squares ℝ (sign ∘ w)) :=
begin
let u := λ i, if h : w i = 0 then (1 : ℝˣ) else units.mk0 (w i) h,
have hu' : ∀ i : ι, (sign (u i) * u i) ^ - (1 / 2 : ℝ) ≠ 0,
{ intro i, refine (ne_of_lt (real.rpow_pos_of_pos
(sign_mul_pos_of_ne_zero _ $ units.ne_zero _) _)).symm},
convert ((weighted_sum_squares ℝ w).isometry_basis_repr
((pi.basis_fun ℝ ι).units_smul (λ i, (is_unit_iff_ne_zero.2 $ hu' i).unit))),
ext1 v,
rw [basis_repr_apply, weighted_sum_squares_apply, weighted_sum_squares_apply],
refine sum_congr rfl (λ j hj, _),
have hsum : (∑ (i : ι), v i • ((is_unit_iff_ne_zero.2 $ hu' i).unit : ℝ) •
(pi.basis_fun ℝ ι) i) j = v j • (sign (u j) * u j) ^ - (1 / 2 : ℝ),
{ rw [finset.sum_apply, sum_eq_single j, pi.basis_fun_apply, is_unit.unit_spec,
linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply, function.update_same,
smul_eq_mul, smul_eq_mul, smul_eq_mul, mul_one],
intros i _ hij,
rw [pi.basis_fun_apply, linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply,
function.update_noteq hij.symm, pi.zero_apply, smul_eq_mul, smul_eq_mul,
mul_zero, mul_zero],
intro hj', exact false.elim (hj' hj) },
simp_rw basis.units_smul_apply,
erw [hsum],
simp only [u, function.comp, smul_eq_mul],
split_ifs,
{ simp only [h, zero_smul, zero_mul, real.sign_zero] },
have hwu : w j = u j,
{ simp only [u, dif_neg h, units.coe_mk0] },
simp only [hwu, units.coe_mk0],
suffices : (u j : ℝ).sign * v j * v j = (sign (u j) * u j) ^ - (1 / 2 : ℝ) *
(sign (u j) * u j) ^ - (1 / 2 : ℝ) * u j * v j * v j,
{ erw [← mul_assoc, this], ring },
rw [← real.rpow_add (sign_mul_pos_of_ne_zero _ $ units.ne_zero _),
show - (1 / 2 : ℝ) + - (1 / 2) = -1, by ring, real.rpow_neg_one, mul_inv,
inv_sign, mul_assoc (sign (u j)) (u j)⁻¹,
inv_mul_cancel (units.ne_zero _), mul_one],
apply_instance
end
/-- **Sylvester's law of inertia**: A nondegenerate real quadratic form is equivalent to a weighted
sum of squares with the weights being ±1. -/
theorem equivalent_one_neg_one_weighted_sum_squared
{M : Type*} [add_comm_group M] [module ℝ M] [finite_dimensional ℝ M]
(Q : quadratic_form ℝ M) (hQ : (associated Q).nondegenerate) :
∃ w : fin (finite_dimensional.finrank ℝ M) → ℝ,
(∀ i, w i = -1 ∨ w i = 1) ∧ equivalent Q (weighted_sum_squares ℝ w) :=
let ⟨w, ⟨hw₁⟩⟩ := Q.equivalent_weighted_sum_squares_units_of_nondegenerate' hQ in
⟨sign ∘ coe ∘ w,
λ i, sign_apply_eq_of_ne_zero (w i) (w i).ne_zero,
⟨hw₁.trans (isometry_sign_weighted_sum_squares (coe ∘ w))⟩⟩
/-- **Sylvester's law of inertia**: A real quadratic form is equivalent to a weighted
sum of squares with the weights being ±1 or 0. -/
theorem equivalent_one_zero_neg_one_weighted_sum_squared
{M : Type*} [add_comm_group M] [module ℝ M] [finite_dimensional ℝ M]
(Q : quadratic_form ℝ M) :
∃ w : fin (finite_dimensional.finrank ℝ M) → ℝ,
(∀ i, w i = -1 ∨ w i = 0 ∨ w i = 1) ∧ equivalent Q (weighted_sum_squares ℝ w) :=
let ⟨w, ⟨hw₁⟩⟩ := Q.equivalent_weighted_sum_squares in
⟨sign ∘ coe ∘ w,
λ i, sign_apply_eq (w i),
⟨hw₁.trans (isometry_sign_weighted_sum_squares w)⟩⟩
end quadratic_form
|
13d971b1c15c0249af1705350bc09c1a7cfc1305
|
ea5678cc400c34ff95b661fa26d15024e27ea8cd
|
/fermat's little theorem.lean
|
c0ce4a4b3d3091e0efcf4ce8a980adc6b47c256c
|
[] |
no_license
|
ChrisHughes24/leanstuff
|
dca0b5349c3ed893e8792ffbd98cbcadaff20411
|
9efa85f72efaccd1d540385952a6acc18fce8687
|
refs/heads/master
| 1,654,883,241,759
| 1,652,873,885,000
| 1,652,873,885,000
| 134,599,537
| 1
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 6,916
|
lean
|
import data.nat.modeq data.nat.basic data.nat.prime data.int.basic tactic.norm_num
def prime : ℤ → Prop := λ x,nat.prime (int.nat_abs x)
theorem prime_dvd_mul {p m n : ℤ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n :=begin
have H:int.nat_abs p ∣int.nat_abs m * int.nat_abs n ↔ int.nat_abs p ∣ int.nat_abs m ∨ int.nat_abs p ∣int.nat_abs n:=begin
unfold prime at pp,revert pp, exact nat.prime.dvd_mul,end,
rw [←int.coe_nat_dvd,←int.coe_nat_dvd,←int.coe_nat_dvd,int.coe_nat_mul,int.nat_abs_dvd,int.nat_abs_dvd,int.nat_abs_dvd,
←int.abs_eq_nat_abs,←int.abs_eq_nat_abs] at H,cases lt_trichotomy m 0 with Hm Hm,
cases lt_trichotomy n 0 with Hn Hn,rwa[abs_of_neg Hm,abs_of_neg Hn,dvd_neg,dvd_neg,neg_mul_neg] at H,
cases Hn with Hn Hn,rw Hn,norm_num,rwa[abs_of_neg Hm,abs_of_pos Hn,dvd_neg,←neg_mul_eq_neg_mul,dvd_neg] at H,
cases Hm with Hm Hm,rw Hm,simp,cases lt_trichotomy n 0 with Hn Hn,rwa[abs_of_neg Hn,abs_of_pos Hm,dvd_neg,mul_neg_eq_neg_mul_symm,dvd_neg] at H,
cases Hn with Hn Hn,rw Hn,simp,rwa[abs_of_pos Hn,abs_of_pos Hm] at H,
end
theorem dioph_identity:∀ a b p q:ℤ, (a*a+b*b)*(p*p+q*q)=(a*p+b*q)*(a*p+b*q)+(a*q-b*p)*(a*q-b*p):=begin
intros,rw[mul_add,mul_add,add_mul,add_mul,add_mul,add_mul,mul_sub,sub_mul,sub_mul],norm_num,
end
theorem lemma_1 : ∀ a b p q : ℤ,∃ x y:ℤ, x*x+y*y=(a*a+b*b)*(p*p+q*q):=begin
intros,existsi [(a*p+b*q),(a*q-b*p)],
rw [mul_add,mul_add,add_mul,add_mul,add_mul,add_mul,mul_sub,sub_mul,sub_mul],norm_num,
end
theorem lemma_2 : ∀ (a b p q :ℤ), prime (p*p+q*q)→ (p*p+q*q) ∣ (a*a + b*b) → ∃ x y:ℤ,(x*x+y*y)*(p*p+q*q)=(a*a+b*b):=begin
intros a b p q H1 H2,
have H3:(p*p+q*q) ∣ (b*p-a*q)*(b*p+a*q):=begin
rw[mul_add,sub_mul,sub_mul,add_sub],
have H3:a * q * (b * p) =b * p * (a * q):=by norm_num,
rw H3,rw sub_add_cancel,clear H3,
have H3:b * p * (b * p) - a * q * (a * q)=(p*p)*(a*a+b*b)-(a*a)*(p*p+q*q):=by rw[mul_add,mul_add];norm_num,
rw H3,exact dvd_sub (dvd_mul_of_dvd_right H2 _) (dvd_mul_left _ _),
end,
rw prime_dvd_mul H1 at H3,revert a b p q H1 H2 H3,
have H:∀ a b p q:ℤ,prime (p * p + q * q)→p * p + q * q ∣ a * a + b * b→ p * p + q * q ∣ b * p - a * q→∃ (x y : ℤ), (x * x + y * y) * (p * p + q * q) = a * a + b * b:=begin
assume a b p q H1 H2 H3,
have H4:=dioph_identity b a q p,
have H5:=dvd_mul_left (p * p + q * q) (b * b + a * a),rw [add_comm (p*p),H4,add_comm (q*q)] at H5,
have H6:=iff.elim_right (dvd_add_iff_left (dvd_mul_of_dvd_right H3 (b * p - a * q))) H5,clear H5,
have H7:=mul_dvd_mul H3 H3, have H8:=exists_eq_mul_left_of_dvd H3,cases H8 with c Hc,
cases exists_eq_mul_left_of_dvd H2 with d Hd,
have H10:(b * b + a * a) * (q * q + p * p) = d* (q * q + p * p) * (q * q + p * p):=begin rw[add_comm(b*b),Hd],simp,end,rw H10 at H4,clear H10,
have H10:=dvd_mul_left ((q * q + p * p) * (q * q + p * p) ) d,
rw[←mul_assoc,H4,add_comm (q*q),←dvd_add_iff_left H7] at H10,have H11:= dvd_of_mul_left_dvd H10,rw prime_dvd_mul at H11,simp at H11,
cases exists_eq_mul_left_of_dvd H11 with e He,rw [add_comm(q*q),←Hd] at H4,
existsi [c,e],clear H10 H2 H6 H3 H7 Hd d,
suffices :(c * c + e * e) * (p * p + q * q) * (p * p + q * q) = (a * a + b * b) * (p * p + q * q),
have H3:(p*p + q*q)≠0:=begin intro,unfold prime at H1,rw a_1 at H1,revert H1,simp [int.nat_abs_zero,nat.prime,(dec_trivial:¬0≥2)],end,
have H2:(c * c + e * e) * (p * p + q * q) * (p * p + q * q) / (p * p + q * q)= (a * a + b * b) * (p * p + q * q) / (p * p + q * q):=by rw this,
rwa[int.mul_div_cancel ((c * c + e * e) * (p * p + q * q)) H3,int.mul_div_cancel (a * a + b * b) H3] at H2,rw H4,
have H12:(c * c + e * e) * (p * p + q * q) * (p * p + q * q) = (c * (p * p + q * q))*(c * (p * p + q * q))+ (e * (p * p + q * q))*(e * (p * p + q * q)):=begin
rw [add_mul _ _ (p * p + q * q),add_mul _ _ (p * p + q * q)],norm_num,end,
rw [H12,←Hc,←He],norm_num,assumption,
end,intros a b p q H1 H2 H3,cases H3 with H3 H3,exact H a b p q H1 H2 H3,
have H4:p * p + q * q ∣ -a * -a + b * b:=by rwa neg_mul_neg,
have H5:p * p + q * q ∣ b * p - -a * q:=by revert H3;simp;assumption,
have H6:=H (-a) b p q H1 H4 H5,rwa neg_mul_neg at H6,
end
open list
open nat
theorem squares_nat_int{a:ℕ}:(∃ x y:ℤ, x*x+y*y = ↑a)→∃x y:ℕ, x*x+y*y = a:=begin
simp,assume x y hxy,existsi [(int.nat_abs x),int.nat_abs y],rw [←int.coe_nat_eq_coe_nat_iff,int.coe_nat_add,int.coe_nat_mul,int.coe_nat_mul],
rwa[←int.abs_eq_nat_abs,←int.abs_eq_nat_abs, abs_mul_abs_self,abs_mul_abs_self],
end
theorem lemma_3:∀ n x:ℕ,x∣n→(¬∃x₁ x₂, x=x₁ *x₁+x₂ * x₂)→∃ p:ℕ,(p*x)∣n∧(¬∃p₁ p₂:ℕ,(p₁*p₁+p₂*p₂)=p):=begin
have: ∀ (L:list ℕ) (x a b:ℕ),x * prod L = a*a+b*b →(∀ p:ℕ,p∈L→nat.prime p)→x∣prod L→(∀ x₁ x₂:ℕ, x≠x₁ *x₁+x₂ * x₂)→∃ p:ℕ,(p*x)∣prod L∧(∀ p₁ p₂:ℕ,p≠p₁*p₁+p₂*p₂):=begin
assume L,induction L with p1 L hi,simp,intros,have:=a_3 a b a_1,contradiction,simp,
assume x a b hab hp hL hx hxs,cases classical.em (∃ p1₁ p1₂:ℕ,p1₁ *p1₁ +p1₂ *p1₂ =p1),
cases h with p1₁,cases h_h with p1₂,rw ←h_h_h at hp,rw [mul_comm,mul_assoc,←h_h_h]at hab,
have pdvd:=dvd_mul_right (p1₁ * p1₁ + p1₂ * p1₂) (prod L * x),rw [hab,←int.coe_nat_dvd,int.coe_nat_add,int.coe_nat_add,int.coe_nat_mul,int.coe_nat_mul,int.coe_nat_mul,int.coe_nat_mul] at pdvd,have:=lemma_2 a b p1₁ p1₂ hp pdvd,
cases this with x₁ hx1,cases hx1 with y₁ hxy,have:∃ x₂ y₂:nat,x*prod L = x₂*x₂+y₂*y₂,
existsi [int.nat_abs x₁,int.nat_abs y₁],rw[←int.coe_nat_mul,←int.coe_nat_mul,←int.coe_nat_mul,←int.coe_nat_mul,←int.coe_nat_add,←int.coe_nat_add,←hab,int.coe_nat_mul,mul_comm] at hxy,
have: (↑(p1₁ * p1₁ + p1₂ * p1₂) * (x₁ * x₁ + y₁ * y₁)) / ↑(p1₁ * p1₁ + p1₂ * p1₂)=(↑(p1₁ * p1₁ + p1₂ * p1₂) * ↑(prod L * x)) / ↑(p1₁ * p1₁ + p1₂ * p1₂),rw hxy,rw [int.mul_div_cancel_left,int.mul_div_cancel_left] at this,
rw[mul_comm x,←int.coe_nat_eq_coe_nat_iff,← this,int.coe_nat_add,int.coe_nat_mul,int.coe_nat_mul,←int.abs_eq_nat_abs,← int.abs_eq_nat_abs,abs_mul_abs_self,abs_mul_abs_self],rw [h_h_h,←int.coe_nat_zero,ne.def,int.coe_nat_eq_coe_nat_iff],have:=prime.pos hp,intro,rw[h_h_h, a_1] at this,revert this,exact dec_trivial,
rw [h_h_h,←int.coe_nat_zero,ne.def,int.coe_nat_eq_coe_nat_iff],have:=prime.pos hp,intro,rw[h_h_h, a_1] at this,revert this,exact dec_trivial,
clear hxy x₁ y₁,cases this with x₁ hxy,cases hxy with y₁ hxy,have:= hi x x₁ y₁ hxy hL,
end
|
e9ef80a6195b66072a1146fffb208d1e9bff244f
|
9d2e3d5a2e2342a283affd97eead310c3b528a24
|
/src/for_mathlib/category_theory/isomorphism.lean
|
69c00f649699a350e74aef756df0a4426d70f532
|
[] |
permissive
|
Vtec234/lftcm2020
|
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
|
bbbd4c8162f8c2ef602300ab8fdeca231886375d
|
refs/heads/master
| 1,668,808,098,623
| 1,594,989,081,000
| 1,594,990,079,000
| 280,423,039
| 0
| 0
|
MIT
| 1,594,990,209,000
| 1,594,990,209,000
| null |
UTF-8
|
Lean
| false
| false
| 2,149
|
lean
|
import category_theory.isomorphism
open category_theory
universes v u
variables {C : Type u} [category.{v} C]
namespace category_theory.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 category_theory.iso
|
dbc130dbabfcd1caa31fa7d5f746688dc9eb83e6
|
acc85b4be2c618b11fc7cb3005521ae6858a8d07
|
/data/prod.lean
|
163a50e836138074c244e06ebd69977656e2e2fc
|
[
"Apache-2.0"
] |
permissive
|
linpingchuan/mathlib
|
d49990b236574df2a45d9919ba43c923f693d341
|
5ad8020f67eb13896a41cc7691d072c9331b1f76
|
refs/heads/master
| 1,626,019,377,808
| 1,508,048,784,000
| 1,508,048,784,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 1,044
|
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
Extends theory on products
-/
universes u v
variables {α : Type u} {β : Type v}
-- copied from parser
@[simp] lemma prod.mk.eta : ∀{p : α × β}, (p.1, p.2) = p
| (a, b) := rfl
def prod.swap : (α×β) → (β×α) := λp, (p.2, p.1)
@[simp] lemma prod.swap_swap : ∀x:α×β, prod.swap (prod.swap x) = x
| ⟨a, b⟩ := rfl
@[simp] lemma prod.fst_swap {p : α×β} : (prod.swap p).1 = p.2 := rfl
@[simp] lemma prod.snd_swap {p : α×β} : (prod.swap p).2 = p.1 := rfl
@[simp] lemma prod.swap_prod_mk {a : α} {b : β} : prod.swap (a, b) = (b, a) := rfl
@[simp] lemma prod.swap_swap_eq : prod.swap ∘ prod.swap = @id (α × β) :=
funext $ prod.swap_swap
@[simp] lemma prod.swap_left_inverse : function.left_inverse (@prod.swap α β) prod.swap :=
prod.swap_swap
@[simp] lemma prod.swap_right_inverse : function.right_inverse (@prod.swap α β) prod.swap :=
prod.swap_swap
|
b0c624c6846c35311c6de45c72d39c11612b4d2c
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/algebra/indicator_function.lean
|
d412f3c3e71eff53547ca64a439c3bb16c772193
|
[
"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
| 26,507
|
lean
|
/-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import algebra.support
/-!
# Indicator function
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
- `indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `0` otherwise.
- `mul_indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `1` otherwise.
## Implementation note
In mathematics, an indicator function or a characteristic function is a function
used to indicate membership of an element in a set `s`,
having the value `1` for all elements of `s` and the value `0` otherwise.
But since it is usually used to restrict a function to a certain set `s`,
we let the indicator function take the value `f x` for some function `f`, instead of `1`.
If the usual indicator function is needed, just set `f` to be the constant function `λx, 1`.
The indicator function is implemented non-computably, to avoid having to pass around `decidable`
arguments. This is in contrast with the design of `pi.single` or `set.piecewise`.
## Tags
indicator, characteristic
-/
open_locale big_operators
open function
variables {α β ι M N : Type*}
namespace set
section has_one
variables [has_one M] [has_one N] {s t : set α} {f g : α → M} {a : α}
/-- `indicator s f a` is `f a` if `a ∈ s`, `0` otherwise. -/
noncomputable def indicator {M} [has_zero M] (s : set α) (f : α → M) : α → M
| x := by haveI := classical.dec_pred (∈ s); exact if x ∈ s then f x else 0
/-- `mul_indicator s f a` is `f a` if `a ∈ s`, `1` otherwise. -/
@[to_additive]
noncomputable def mul_indicator (s : set α) (f : α → M) : α → M
| x := by haveI := classical.dec_pred (∈ s); exact if x ∈ s then f x else 1
@[simp, to_additive] lemma piecewise_eq_mul_indicator [decidable_pred (∈ s)] :
s.piecewise f 1 = s.mul_indicator f :=
funext $ λ x, @if_congr _ _ _ _ (id _) _ _ _ _ iff.rfl rfl rfl
@[to_additive] lemma mul_indicator_apply (s : set α) (f : α → M) (a : α) [decidable (a ∈ s)] :
mul_indicator s f a = if a ∈ s then f a else 1 := by convert rfl
@[simp, to_additive] lemma mul_indicator_of_mem (h : a ∈ s) (f : α → M) :
mul_indicator s f a = f a :=
by { letI := classical.dec (a ∈ s), exact if_pos h }
@[simp, to_additive] lemma mul_indicator_of_not_mem (h : a ∉ s) (f : α → M) :
mul_indicator s f a = 1 :=
by { letI := classical.dec (a ∈ s), exact if_neg h }
@[to_additive] lemma mul_indicator_eq_one_or_self (s : set α) (f : α → M) (a : α) :
mul_indicator s f a = 1 ∨ mul_indicator s f a = f a :=
begin
by_cases h : a ∈ s,
{ exact or.inr (mul_indicator_of_mem h f) },
{ exact or.inl (mul_indicator_of_not_mem h f) }
end
@[simp, to_additive] lemma mul_indicator_apply_eq_self :
s.mul_indicator f a = f a ↔ (a ∉ s → f a = 1) :=
by letI := classical.dec (a ∈ s); exact ite_eq_left_iff.trans (by rw [@eq_comm _ (f a)])
@[simp, to_additive] lemma mul_indicator_eq_self : s.mul_indicator f = f ↔ mul_support f ⊆ s :=
by simp only [funext_iff, subset_def, mem_mul_support, mul_indicator_apply_eq_self, not_imp_comm]
@[to_additive] lemma mul_indicator_eq_self_of_superset (h1 : s.mul_indicator f = f) (h2 : s ⊆ t) :
t.mul_indicator f = f :=
by { rw mul_indicator_eq_self at h1 ⊢, exact subset.trans h1 h2 }
@[simp, to_additive] lemma mul_indicator_apply_eq_one :
mul_indicator s f a = 1 ↔ (a ∈ s → f a = 1) :=
by letI := classical.dec (a ∈ s); exact ite_eq_right_iff
@[simp, to_additive] lemma mul_indicator_eq_one :
mul_indicator s f = (λ x, 1) ↔ disjoint (mul_support f) s :=
by simp only [funext_iff, mul_indicator_apply_eq_one, set.disjoint_left, mem_mul_support,
not_imp_not]
@[simp, to_additive] lemma mul_indicator_eq_one' :
mul_indicator s f = 1 ↔ disjoint (mul_support f) s :=
mul_indicator_eq_one
@[to_additive] lemma mul_indicator_apply_ne_one {a : α} :
s.mul_indicator f a ≠ 1 ↔ a ∈ s ∩ mul_support f :=
by simp only [ne.def, mul_indicator_apply_eq_one, not_imp, mem_inter_iff, mem_mul_support]
@[simp, to_additive] lemma mul_support_mul_indicator :
function.mul_support (s.mul_indicator f) = s ∩ function.mul_support f :=
ext $ λ x, by simp [function.mem_mul_support, mul_indicator_apply_eq_one]
/-- If a multiplicative indicator function is not equal to `1` at a point, then that point is in the
set. -/
@[to_additive "If an additive indicator function is not equal to `0` at a point, then that point is
in the set."]
lemma mem_of_mul_indicator_ne_one (h : mul_indicator s f a ≠ 1) : a ∈ s :=
not_imp_comm.1 (λ hn, mul_indicator_of_not_mem hn f) h
@[to_additive] lemma eq_on_mul_indicator : eq_on (mul_indicator s f) f s :=
λ x hx, mul_indicator_of_mem hx f
@[to_additive] lemma mul_support_mul_indicator_subset : mul_support (s.mul_indicator f) ⊆ s :=
λ x hx, hx.imp_symm (λ h, mul_indicator_of_not_mem h f)
@[simp, to_additive] lemma mul_indicator_mul_support : mul_indicator (mul_support f) f = f :=
mul_indicator_eq_self.2 subset.rfl
@[simp, to_additive] lemma mul_indicator_range_comp {ι : Sort*} (f : ι → α) (g : α → M) :
mul_indicator (range f) g ∘ f = g ∘ f :=
by letI := classical.dec_pred (∈ range f); exact piecewise_range_comp _ _ _
@[to_additive] lemma mul_indicator_congr (h : eq_on f g s) :
mul_indicator s f = mul_indicator s g :=
funext $ λx, by { simp only [mul_indicator], split_ifs, { exact h h_1 }, refl }
@[simp, to_additive] lemma mul_indicator_univ (f : α → M) : mul_indicator (univ : set α) f = f :=
mul_indicator_eq_self.2 $ subset_univ _
@[simp, to_additive] lemma mul_indicator_empty (f : α → M) : mul_indicator (∅ : set α) f = λa, 1 :=
mul_indicator_eq_one.2 $ disjoint_empty _
@[to_additive] lemma mul_indicator_empty' (f : α → M) : mul_indicator (∅ : set α) f = 1 :=
mul_indicator_empty f
variable (M)
@[simp, to_additive] lemma mul_indicator_one (s : set α) :
mul_indicator s (λx, (1:M)) = λx, (1:M) :=
mul_indicator_eq_one.2 $ by simp only [mul_support_one, empty_disjoint]
@[simp, to_additive] lemma mul_indicator_one' {s : set α} : s.mul_indicator (1 : α → M) = 1 :=
mul_indicator_one M s
variable {M}
@[to_additive] lemma mul_indicator_mul_indicator (s t : set α) (f : α → M) :
mul_indicator s (mul_indicator t f) = mul_indicator (s ∩ t) f :=
funext $ λx, by { simp only [mul_indicator], split_ifs, repeat {simp * at * {contextual := tt}} }
@[simp, to_additive] lemma mul_indicator_inter_mul_support (s : set α) (f : α → M) :
mul_indicator (s ∩ mul_support f) f = mul_indicator s f :=
by rw [← mul_indicator_mul_indicator, mul_indicator_mul_support]
@[to_additive] lemma comp_mul_indicator (h : M → β) (f : α → M) {s : set α} {x : α}
[decidable_pred (∈ s)] :
h (s.mul_indicator f x) = s.piecewise (h ∘ f) (const α (h 1)) x :=
by letI := classical.dec_pred (∈ s); convert s.apply_piecewise f (const α 1) (λ _, h)
@[to_additive] lemma mul_indicator_comp_right {s : set α} (f : β → α) {g : α → M} {x : β} :
mul_indicator (f ⁻¹' s) (g ∘ f) x = mul_indicator s g (f x) :=
by { simp only [mul_indicator], split_ifs; refl }
@[to_additive] lemma mul_indicator_image {s : set α} {f : β → M} {g : α → β} (hg : injective g)
{x : α} : mul_indicator (g '' s) f (g x) = mul_indicator s (f ∘ g) x :=
by rw [← mul_indicator_comp_right, preimage_image_eq _ hg]
@[to_additive] lemma mul_indicator_comp_of_one {g : M → N} (hg : g 1 = 1) :
mul_indicator s (g ∘ f) = g ∘ (mul_indicator s f) :=
begin
funext,
simp only [mul_indicator],
split_ifs; simp [*]
end
@[to_additive] lemma comp_mul_indicator_const (c : M) (f : M → N) (hf : f 1 = 1) :
(λ x, f (s.mul_indicator (λ x, c) x)) = s.mul_indicator (λ x, f c) :=
(mul_indicator_comp_of_one hf).symm
@[to_additive] lemma mul_indicator_preimage (s : set α) (f : α → M) (B : set M) :
(mul_indicator s f)⁻¹' B = s.ite (f ⁻¹' B) (1 ⁻¹' B) :=
by letI := classical.dec_pred (∈ s); exact piecewise_preimage s f 1 B
@[to_additive] lemma mul_indicator_one_preimage (s : set M) :
t.mul_indicator 1 ⁻¹' s ∈ ({set.univ, ∅} : set (set α)) :=
begin
classical,
rw [mul_indicator_one', preimage_one],
split_ifs; simp
end
@[to_additive] lemma mul_indicator_const_preimage_eq_union (U : set α) (s : set M) (a : M)
[decidable (a ∈ s)] [decidable ((1 : M) ∈ s)] :
U.mul_indicator (λ x, a) ⁻¹' s = (if a ∈ s then U else ∅) ∪ (if (1 : M) ∈ s then Uᶜ else ∅) :=
begin
rw [mul_indicator_preimage, preimage_one, preimage_const],
split_ifs; simp [← compl_eq_univ_diff]
end
@[to_additive] lemma mul_indicator_const_preimage (U : set α) (s : set M) (a : M) :
U.mul_indicator (λ x, a) ⁻¹' s ∈ ({set.univ, U, Uᶜ, ∅} : set (set α)) :=
begin
classical,
rw [mul_indicator_const_preimage_eq_union],
split_ifs; simp
end
lemma indicator_one_preimage [has_zero M] (U : set α) (s : set M) :
U.indicator 1 ⁻¹' s ∈ ({set.univ, U, Uᶜ, ∅} : set (set α)) :=
indicator_const_preimage _ _ 1
@[to_additive] lemma mul_indicator_preimage_of_not_mem (s : set α) (f : α → M)
{t : set M} (ht : (1:M) ∉ t) :
(mul_indicator s f)⁻¹' t = f ⁻¹' t ∩ s :=
by simp [mul_indicator_preimage, pi.one_def, set.preimage_const_of_not_mem ht]
@[to_additive] lemma mem_range_mul_indicator {r : M} {s : set α} {f : α → M} :
r ∈ range (mul_indicator s f) ↔ (r = 1 ∧ s ≠ univ) ∨ (r ∈ f '' s) :=
by simp [mul_indicator, ite_eq_iff, exists_or_distrib, eq_univ_iff_forall, and_comm, or_comm,
@eq_comm _ r 1]
@[to_additive] lemma mul_indicator_rel_mul_indicator {r : M → M → Prop} (h1 : r 1 1)
(ha : a ∈ s → r (f a) (g a)) :
r (mul_indicator s f a) (mul_indicator s g a) :=
by { simp only [mul_indicator], split_ifs with has has, exacts [ha has, h1] }
end has_one
section monoid
variables [mul_one_class M] {s t : set α} {f g : α → M} {a : α}
@[to_additive] lemma mul_indicator_union_mul_inter_apply (f : α → M) (s t : set α) (a : α) :
mul_indicator (s ∪ t) f a * mul_indicator (s ∩ t) f a =
mul_indicator s f a * mul_indicator t f a :=
by by_cases hs : a ∈ s; by_cases ht : a ∈ t; simp *
@[to_additive] lemma mul_indicator_union_mul_inter (f : α → M) (s t : set α) :
mul_indicator (s ∪ t) f * mul_indicator (s ∩ t) f = mul_indicator s f * mul_indicator t f :=
funext $ mul_indicator_union_mul_inter_apply f s t
@[to_additive] lemma mul_indicator_union_of_not_mem_inter (h : a ∉ s ∩ t) (f : α → M) :
mul_indicator (s ∪ t) f a = mul_indicator s f a * mul_indicator t f a :=
by rw [← mul_indicator_union_mul_inter_apply f s t, mul_indicator_of_not_mem h, mul_one]
@[to_additive] lemma mul_indicator_union_of_disjoint (h : disjoint s t) (f : α → M) :
mul_indicator (s ∪ t) f = λa, mul_indicator s f a * mul_indicator t f a :=
funext $ λa, mul_indicator_union_of_not_mem_inter (λ ha, h.le_bot ha) _
@[to_additive] lemma mul_indicator_mul (s : set α) (f g : α → M) :
mul_indicator s (λa, f a * g a) = λa, mul_indicator s f a * mul_indicator s g a :=
by { funext, simp only [mul_indicator], split_ifs, { refl }, rw mul_one }
@[to_additive] lemma mul_indicator_mul' (s : set α) (f g : α → M) :
mul_indicator s (f * g) = mul_indicator s f * mul_indicator s g :=
mul_indicator_mul s f g
@[simp, to_additive] lemma mul_indicator_compl_mul_self_apply (s : set α) (f : α → M) (a : α) :
mul_indicator sᶜ f a * mul_indicator s f a = f a :=
classical.by_cases (λ ha : a ∈ s, by simp [ha]) (λ ha, by simp [ha])
@[simp, to_additive] lemma mul_indicator_compl_mul_self (s : set α) (f : α → M) :
mul_indicator sᶜ f * mul_indicator s f = f :=
funext $ mul_indicator_compl_mul_self_apply s f
@[simp, to_additive] lemma mul_indicator_self_mul_compl_apply (s : set α) (f : α → M) (a : α) :
mul_indicator s f a * mul_indicator sᶜ f a = f a :=
classical.by_cases (λ ha : a ∈ s, by simp [ha]) (λ ha, by simp [ha])
@[simp, to_additive] lemma mul_indicator_self_mul_compl (s : set α) (f : α → M) :
mul_indicator s f * mul_indicator sᶜ f = f :=
funext $ mul_indicator_self_mul_compl_apply s f
@[to_additive] lemma mul_indicator_mul_eq_left {f g : α → M}
(h : disjoint (mul_support f) (mul_support g)) :
(mul_support f).mul_indicator (f * g) = f :=
begin
refine (mul_indicator_congr $ λ x hx, _).trans mul_indicator_mul_support,
have : g x = 1, from nmem_mul_support.1 (disjoint_left.1 h hx),
rw [pi.mul_apply, this, mul_one]
end
@[to_additive] lemma mul_indicator_mul_eq_right {f g : α → M}
(h : disjoint (mul_support f) (mul_support g)) :
(mul_support g).mul_indicator (f * g) = g :=
begin
refine (mul_indicator_congr $ λ x hx, _).trans mul_indicator_mul_support,
have : f x = 1, from nmem_mul_support.1 (disjoint_right.1 h hx),
rw [pi.mul_apply, this, one_mul]
end
@[to_additive] lemma mul_indicator_mul_compl_eq_piecewise
[decidable_pred (∈ s)] (f g : α → M) :
s.mul_indicator f * sᶜ.mul_indicator g = s.piecewise f g :=
begin
ext x,
by_cases h : x ∈ s,
{ rw [piecewise_eq_of_mem _ _ _ h, pi.mul_apply, set.mul_indicator_of_mem h,
set.mul_indicator_of_not_mem (set.not_mem_compl_iff.2 h), mul_one] },
{ rw [piecewise_eq_of_not_mem _ _ _ h, pi.mul_apply, set.mul_indicator_of_not_mem h,
set.mul_indicator_of_mem (set.mem_compl h), one_mul] },
end
/-- `set.mul_indicator` as a `monoid_hom`. -/
@[to_additive "`set.indicator` as an `add_monoid_hom`."]
noncomputable def mul_indicator_hom {α} (M) [mul_one_class M] (s : set α) : (α → M) →* (α → M) :=
{ to_fun := mul_indicator s,
map_one' := mul_indicator_one M s,
map_mul' := mul_indicator_mul s }
end monoid
section distrib_mul_action
variables {A : Type*} [add_monoid A] [monoid M] [distrib_mul_action M A]
lemma indicator_smul_apply (s : set α) (r : α → M) (f : α → A) (x : α) :
indicator s (λ x, r x • f x) x = r x • indicator s f x :=
by { dunfold indicator, split_ifs, exacts [rfl, (smul_zero (r x)).symm] }
lemma indicator_smul (s : set α) (r : α → M) (f : α → A) :
indicator s (λ (x : α), r x • f x) = λ (x : α), r x • indicator s f x :=
funext $ indicator_smul_apply s r f
lemma indicator_const_smul_apply (s : set α) (r : M) (f : α → A) (x : α) :
indicator s (λ x, r • f x) x = r • indicator s f x :=
indicator_smul_apply s (λ x, r) f x
lemma indicator_const_smul (s : set α) (r : M) (f : α → A) :
indicator s (λ (x : α), r • f x) = λ (x : α), r • indicator s f x :=
funext $ indicator_const_smul_apply s r f
end distrib_mul_action
section group
variables {G : Type*} [group G] {s t : set α} {f g : α → G} {a : α}
@[to_additive] lemma mul_indicator_inv' (s : set α) (f : α → G) :
mul_indicator s (f⁻¹) = (mul_indicator s f)⁻¹ :=
(mul_indicator_hom G s).map_inv f
@[to_additive] lemma mul_indicator_inv (s : set α) (f : α → G) :
mul_indicator s (λa, (f a)⁻¹) = λa, (mul_indicator s f a)⁻¹ :=
mul_indicator_inv' s f
@[to_additive] lemma mul_indicator_div (s : set α) (f g : α → G) :
mul_indicator s (λ a, f a / g a) =
λ a, mul_indicator s f a / mul_indicator s g a :=
(mul_indicator_hom G s).map_div f g
@[to_additive] lemma mul_indicator_div' (s : set α) (f g : α → G) :
mul_indicator s (f / g) = mul_indicator s f / mul_indicator s g :=
mul_indicator_div s f g
@[to_additive indicator_compl'] lemma mul_indicator_compl (s : set α) (f : α → G) :
mul_indicator sᶜ f = f * (mul_indicator s f)⁻¹ :=
eq_mul_inv_of_mul_eq $ s.mul_indicator_compl_mul_self f
lemma indicator_compl {G} [add_group G] (s : set α) (f : α → G) :
indicator sᶜ f = f - indicator s f :=
by rw [sub_eq_add_neg, indicator_compl']
@[to_additive indicator_diff'] lemma mul_indicator_diff (h : s ⊆ t) (f : α → G) :
mul_indicator (t \ s) f = mul_indicator t f * (mul_indicator s f)⁻¹ :=
eq_mul_inv_of_mul_eq $ by { rw [pi.mul_def, ←mul_indicator_union_of_disjoint, diff_union_self,
union_eq_self_of_subset_right h], exact disjoint_sdiff_self_left }
lemma indicator_diff {G : Type*} [add_group G] {s t : set α} (h : s ⊆ t) (f : α → G) :
indicator (t \ s) f = indicator t f - indicator s f :=
by rw [indicator_diff' h, sub_eq_add_neg]
end group
section comm_monoid
variables [comm_monoid M]
/-- Consider a product of `g i (f i)` over a `finset`. Suppose `g` is a
function such as `pow`, which maps a second argument of `1` to
`1`. Then if `f` is replaced by the corresponding multiplicative indicator
function, the `finset` may be replaced by a possibly larger `finset`
without changing the value of the sum. -/
@[to_additive] lemma prod_mul_indicator_subset_of_eq_one [has_one N] (f : α → N)
(g : α → N → M) {s t : finset α} (h : s ⊆ t) (hg : ∀ a, g a 1 = 1) :
∏ i in s, g i (f i) = ∏ i in t, g i (mul_indicator ↑s f i) :=
begin
rw ← finset.prod_subset h _,
{ apply finset.prod_congr rfl,
intros i hi,
congr,
symmetry,
exact mul_indicator_of_mem hi _ },
{ refine λ i hi hn, _,
convert hg i,
exact mul_indicator_of_not_mem hn _ }
end
/-- Consider a sum of `g i (f i)` over a `finset`. Suppose `g` is a
function such as multiplication, which maps a second argument of 0 to
0. (A typical use case would be a weighted sum of `f i * h i` or `f i
• h i`, where `f` gives the weights that are multiplied by some other
function `h`.) Then if `f` is replaced by the corresponding indicator
function, the `finset` may be replaced by a possibly larger `finset`
without changing the value of the sum. -/
add_decl_doc set.sum_indicator_subset_of_eq_zero
/-- Taking the product of an indicator function over a possibly larger `finset` is the same as
taking the original function over the original `finset`. -/
@[to_additive "Summing an indicator function over a possibly larger `finset` is the same as summing
the original function over the original `finset`."]
lemma prod_mul_indicator_subset (f : α → M) {s t : finset α} (h : s ⊆ t) :
∏ i in s, f i = ∏ i in t, mul_indicator ↑s f i :=
prod_mul_indicator_subset_of_eq_one _ (λ a b, b) h (λ _, rfl)
@[to_additive] lemma _root_.finset.prod_mul_indicator_eq_prod_filter
(s : finset ι) (f : ι → α → M) (t : ι → set α) (g : ι → α) [decidable_pred (λ i, g i ∈ t i)]:
∏ i in s, mul_indicator (t i) (f i) (g i) = ∏ i in s.filter (λ i, g i ∈ t i), f i (g i) :=
begin
refine (finset.prod_filter_mul_prod_filter_not s (λ i, g i ∈ t i) _).symm.trans _,
refine eq.trans _ (mul_one _),
exact congr_arg2 (*)
(finset.prod_congr rfl $ λ x hx, mul_indicator_of_mem (finset.mem_filter.1 hx).2 _)
(finset.prod_eq_one $ λ x hx, mul_indicator_of_not_mem (finset.mem_filter.1 hx).2 _)
end
@[to_additive] lemma mul_indicator_finset_prod (I : finset ι) (s : set α) (f : ι → α → M) :
mul_indicator s (∏ i in I, f i) = ∏ i in I, mul_indicator s (f i) :=
(mul_indicator_hom M s).map_prod _ _
@[to_additive] lemma mul_indicator_finset_bUnion {ι} (I : finset ι)
(s : ι → set α) {f : α → M} : (∀ (i ∈ I) (j ∈ I), i ≠ j → disjoint (s i) (s j)) →
mul_indicator (⋃ i ∈ I, s i) f = λ a, ∏ i in I, mul_indicator (s i) f a :=
begin
classical,
refine finset.induction_on I _ _,
{ intro h, funext, simp },
assume a I haI ih hI,
funext,
rw [finset.prod_insert haI, finset.set_bUnion_insert, mul_indicator_union_of_not_mem_inter, ih _],
{ assume i hi j hj hij,
exact hI i (finset.mem_insert_of_mem hi) j (finset.mem_insert_of_mem hj) hij },
simp only [not_exists, exists_prop, mem_Union, mem_inter_iff, not_and],
assume hx a' ha',
refine disjoint_left.1 (hI a (finset.mem_insert_self _ _) a' (finset.mem_insert_of_mem ha') _) hx,
exact (ne_of_mem_of_not_mem ha' haI).symm
end
@[to_additive] lemma mul_indicator_finset_bUnion_apply {ι} (I : finset ι)
(s : ι → set α) {f : α → M} (h : ∀ (i ∈ I) (j ∈ I), i ≠ j → disjoint (s i) (s j)) (x : α) :
mul_indicator (⋃ i ∈ I, s i) f x = ∏ i in I, mul_indicator (s i) f x :=
by rw set.mul_indicator_finset_bUnion I s h
end comm_monoid
section mul_zero_class
variables [mul_zero_class M] {s t : set α} {f g : α → M} {a : α}
lemma indicator_mul (s : set α) (f g : α → M) :
indicator s (λa, f a * g a) = λa, indicator s f a * indicator s g a :=
by { funext, simp only [indicator], split_ifs, { refl }, rw mul_zero }
lemma indicator_mul_left (s : set α) (f g : α → M) :
indicator s (λa, f a * g a) a = indicator s f a * g a :=
by { simp only [indicator], split_ifs, { refl }, rw [zero_mul] }
lemma indicator_mul_right (s : set α) (f g : α → M) :
indicator s (λa, f a * g a) a = f a * indicator s g a :=
by { simp only [indicator], split_ifs, { refl }, rw [mul_zero] }
lemma inter_indicator_mul {t1 t2 : set α} (f g : α → M) (x : α) :
(t1 ∩ t2).indicator (λ x, f x * g x) x = t1.indicator f x * t2.indicator g x :=
by { rw [← set.indicator_indicator], simp [indicator] }
end mul_zero_class
section mul_zero_one_class
variables [mul_zero_one_class M]
lemma inter_indicator_one {s t : set α} :
(s ∩ t).indicator (1 : _ → M) = s.indicator 1 * t.indicator 1 :=
funext (λ _, by simpa only [← inter_indicator_mul, pi.mul_apply, pi.one_apply, one_mul])
lemma indicator_prod_one {s : set α} {t : set β} {x : α} {y : β} :
(s ×ˢ t).indicator (1 : _ → M) (x, y) = s.indicator 1 x * t.indicator 1 y :=
by { classical, simp [indicator_apply, ←ite_and] }
variables (M) [nontrivial M]
lemma indicator_eq_zero_iff_not_mem {U : set α} {x : α} :
indicator U 1 x = (0 : M) ↔ x ∉ U :=
by { classical, simp [indicator_apply, imp_false] }
lemma indicator_eq_one_iff_mem {U : set α} {x : α} :
indicator U 1 x = (1 : M) ↔ x ∈ U :=
by { classical, simp [indicator_apply, imp_false] }
lemma indicator_one_inj {U V : set α} (h : indicator U (1 : α → M) = indicator V 1) : U = V :=
by { ext, simp_rw [← indicator_eq_one_iff_mem M, h] }
end mul_zero_one_class
section order
variables [has_one M] {s t : set α} {f g : α → M} {a : α} {y : M}
section
variables [has_le M]
@[to_additive] lemma mul_indicator_apply_le' (hfg : a ∈ s → f a ≤ y) (hg : a ∉ s → 1 ≤ y) :
mul_indicator s f a ≤ y :=
begin
by_cases ha : a ∈ s,
{ simpa [ha] using hfg ha },
{ simpa [ha] using hg ha },
end
@[to_additive] lemma mul_indicator_le' (hfg : ∀ a ∈ s, f a ≤ g a) (hg : ∀ a ∉ s, 1 ≤ g a) :
mul_indicator s f ≤ g :=
λ a, mul_indicator_apply_le' (hfg _) (hg _)
@[to_additive] lemma le_mul_indicator_apply {y} (hfg : a ∈ s → y ≤ g a) (hf : a ∉ s → y ≤ 1) :
y ≤ mul_indicator s g a :=
@mul_indicator_apply_le' α Mᵒᵈ ‹_› _ _ _ _ _ hfg hf
@[to_additive] lemma le_mul_indicator (hfg : ∀ a ∈ s, f a ≤ g a) (hf : ∀ a ∉ s, f a ≤ 1) :
f ≤ mul_indicator s g :=
λ a, le_mul_indicator_apply (hfg _) (hf _)
end
variables [preorder M]
@[to_additive indicator_apply_nonneg]
lemma one_le_mul_indicator_apply (h : a ∈ s → 1 ≤ f a) : 1 ≤ mul_indicator s f a :=
le_mul_indicator_apply h (λ _, le_rfl)
@[to_additive indicator_nonneg]
lemma one_le_mul_indicator (h : ∀ a ∈ s, 1 ≤ f a) (a : α) : 1 ≤ mul_indicator s f a :=
one_le_mul_indicator_apply (h a)
@[to_additive] lemma mul_indicator_apply_le_one (h : a ∈ s → f a ≤ 1) : mul_indicator s f a ≤ 1 :=
mul_indicator_apply_le' h (λ _, le_rfl)
@[to_additive] lemma mul_indicator_le_one (h : ∀ a ∈ s, f a ≤ 1) (a : α) :
mul_indicator s f a ≤ 1 :=
mul_indicator_apply_le_one (h a)
@[to_additive] lemma mul_indicator_le_mul_indicator (h : f a ≤ g a) :
mul_indicator s f a ≤ mul_indicator s g a :=
mul_indicator_rel_mul_indicator le_rfl (λ _, h)
attribute [mono] mul_indicator_le_mul_indicator indicator_le_indicator
@[to_additive] lemma mul_indicator_le_mul_indicator_of_subset (h : s ⊆ t) (hf : ∀ a, 1 ≤ f a)
(a : α) :
mul_indicator s f a ≤ mul_indicator t f a :=
mul_indicator_apply_le' (λ ha, le_mul_indicator_apply (λ _, le_rfl) (λ hat, (hat $ h ha).elim))
(λ ha, one_le_mul_indicator_apply (λ _, hf _))
@[to_additive] lemma mul_indicator_le_self' (hf : ∀ x ∉ s, 1 ≤ f x) : mul_indicator s f ≤ f :=
mul_indicator_le' (λ _ _, le_rfl) hf
@[to_additive] lemma mul_indicator_Union_apply {ι M} [complete_lattice M] [has_one M]
(h1 : (⊥:M) = 1) (s : ι → set α) (f : α → M) (x : α) :
mul_indicator (⋃ i, s i) f x = ⨆ i, mul_indicator (s i) f x :=
begin
by_cases hx : x ∈ ⋃ i, s i,
{ rw [mul_indicator_of_mem hx],
rw [mem_Union] at hx,
refine le_antisymm _ (supr_le $ λ i, mul_indicator_le_self' (λ x hx, h1 ▸ bot_le) x),
rcases hx with ⟨i, hi⟩,
exact le_supr_of_le i (ge_of_eq $ mul_indicator_of_mem hi _) },
{ rw [mul_indicator_of_not_mem hx],
simp only [mem_Union, not_exists] at hx,
simp [hx, ← h1] }
end
end order
section canonically_ordered_monoid
variables [canonically_ordered_monoid M]
@[to_additive] lemma mul_indicator_le_self (s : set α) (f : α → M) :
mul_indicator s f ≤ f :=
mul_indicator_le_self' $ λ _ _, one_le _
@[to_additive] lemma mul_indicator_apply_le {a : α} {s : set α} {f g : α → M}
(hfg : a ∈ s → f a ≤ g a) :
mul_indicator s f a ≤ g a :=
mul_indicator_apply_le' hfg $ λ _, one_le _
@[to_additive] lemma mul_indicator_le {s : set α} {f g : α → M} (hfg : ∀ a ∈ s, f a ≤ g a) :
mul_indicator s f ≤ g :=
mul_indicator_le' hfg $ λ _ _, one_le _
end canonically_ordered_monoid
lemma indicator_le_indicator_nonneg {β} [linear_order β] [has_zero β] (s : set α) (f : α → β) :
s.indicator f ≤ {x | 0 ≤ f x}.indicator f :=
begin
intro x,
classical,
simp_rw indicator_apply,
split_ifs,
{ exact le_rfl, },
{ exact (not_le.mp h_1).le, },
{ exact h_1, },
{ exact le_rfl, },
end
lemma indicator_nonpos_le_indicator {β} [linear_order β] [has_zero β] (s : set α) (f : α → β) :
{x | f x ≤ 0}.indicator f ≤ s.indicator f :=
@indicator_le_indicator_nonneg α βᵒᵈ _ _ s f
end set
@[to_additive] lemma monoid_hom.map_mul_indicator
{M N : Type*} [mul_one_class M] [mul_one_class N] (f : M →* N)
(s : set α) (g : α → M) (x : α) :
f (s.mul_indicator g x) = s.mul_indicator (f ∘ g) x :=
congr_fun (set.mul_indicator_comp_of_one f.map_one).symm x
|
a9bc6dcb09900af8b189f9f7f856874ef60bc8e6
|
72d99e722771bfc4f845b49212c0f743cf3f08df
|
/tests/lean/run/check_constants.lean
|
9d29b68f7919553b4ccaef89104555611a9b9c6f
|
[
"Apache-2.0"
] |
permissive
|
AtnNn/lean
|
c79fa061e300e0ebea0186d9f7db971e839e8955
|
d97d77fd30601f06c751ca376c0cdddd59cf52f9
|
refs/heads/master
| 1,583,885,051,450
| 1,523,730,668,000
| 1,523,730,668,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 14,389
|
lean
|
-- DO NOT EDIT, automatically generated file, generator scripts/gen_constants_cpp.py
import smt system.io
open tactic
meta def script_check_id (n : name) : tactic unit :=
do env ← get_env, (env^.get n >> return ()) <|> (guard $ env^.is_namespace n) <|> (attribute.get_instances n >> return ()) <|> fail ("identifier '" ++ to_string n ++ "' is not a constant, namespace nor attribute")
run_cmd script_check_id `absurd
run_cmd script_check_id `acc.cases_on
run_cmd script_check_id `acc.rec
run_cmd script_check_id `add_comm_group
run_cmd script_check_id `add_comm_semigroup
run_cmd script_check_id `add_group
run_cmd script_check_id `add_monoid
run_cmd script_check_id `and
run_cmd script_check_id `and.elim_left
run_cmd script_check_id `and.elim_right
run_cmd script_check_id `and.intro
run_cmd script_check_id `and.rec
run_cmd script_check_id `and.cases_on
run_cmd script_check_id `auto_param
run_cmd script_check_id `bit0
run_cmd script_check_id `bit1
run_cmd script_check_id `bin_tree.empty
run_cmd script_check_id `bin_tree.leaf
run_cmd script_check_id `bin_tree.node
run_cmd script_check_id `bool
run_cmd script_check_id `bool.ff
run_cmd script_check_id `bool.tt
run_cmd script_check_id `combinator.K
run_cmd script_check_id `cast
run_cmd script_check_id `cast_heq
run_cmd script_check_id `char
run_cmd script_check_id `char.mk
run_cmd script_check_id `char.ne_of_vne
run_cmd script_check_id `char.of_nat
run_cmd script_check_id `char.of_nat_ne_of_ne
run_cmd script_check_id `is_valid_char_range_1
run_cmd script_check_id `is_valid_char_range_2
run_cmd script_check_id `coe
run_cmd script_check_id `coe_fn
run_cmd script_check_id `coe_sort
run_cmd script_check_id `coe_to_lift
run_cmd script_check_id `congr
run_cmd script_check_id `congr_arg
run_cmd script_check_id `congr_fun
run_cmd script_check_id `decidable
run_cmd script_check_id `decidable.to_bool
run_cmd script_check_id `distrib
run_cmd script_check_id `dite
run_cmd script_check_id `empty
run_cmd script_check_id `Exists
run_cmd script_check_id `eq
run_cmd script_check_id `eq.cases_on
run_cmd script_check_id `eq.drec
run_cmd script_check_id `eq.mp
run_cmd script_check_id `eq.mpr
run_cmd script_check_id `eq.rec
run_cmd script_check_id `eq.refl
run_cmd script_check_id `eq.subst
run_cmd script_check_id `eq.symm
run_cmd script_check_id `eq.trans
run_cmd script_check_id `eq_of_heq
run_cmd script_check_id `eq_rec_heq
run_cmd script_check_id `eq_true_intro
run_cmd script_check_id `eq_false_intro
run_cmd script_check_id `eq_self_iff_true
run_cmd script_check_id `expr
run_cmd script_check_id `expr.subst
run_cmd script_check_id `format
run_cmd script_check_id `false
run_cmd script_check_id `false_of_true_iff_false
run_cmd script_check_id `false_of_true_eq_false
run_cmd script_check_id `true_eq_false_of_false
run_cmd script_check_id `false.rec
run_cmd script_check_id `field
run_cmd script_check_id `fin.mk
run_cmd script_check_id `fin.ne_of_vne
run_cmd script_check_id `forall_congr
run_cmd script_check_id `forall_congr_eq
run_cmd script_check_id `forall_not_of_not_exists
run_cmd script_check_id `funext
run_cmd script_check_id `has_add
run_cmd script_check_id `has_add.add
run_cmd script_check_id `has_andthen.andthen
run_cmd script_check_id `has_bind.and_then
run_cmd script_check_id `has_bind.seq
run_cmd script_check_id `has_div
run_cmd script_check_id `has_div.div
run_cmd script_check_id `has_emptyc.emptyc
run_cmd script_check_id `has_mul
run_cmd script_check_id `has_mul.mul
run_cmd script_check_id `has_insert.insert
run_cmd script_check_id `has_inv
run_cmd script_check_id `has_inv.inv
run_cmd script_check_id `has_le
run_cmd script_check_id `has_le.le
run_cmd script_check_id `has_lt
run_cmd script_check_id `has_lt.lt
run_cmd script_check_id `has_neg
run_cmd script_check_id `has_neg.neg
run_cmd script_check_id `has_one
run_cmd script_check_id `has_one.one
run_cmd script_check_id `has_orelse.orelse
run_cmd script_check_id `has_sep.sep
run_cmd script_check_id `has_sizeof
run_cmd script_check_id `has_sizeof.mk
run_cmd script_check_id `has_sub
run_cmd script_check_id `has_sub.sub
run_cmd script_check_id `has_to_format
run_cmd script_check_id `has_repr
run_cmd script_check_id `has_well_founded
run_cmd script_check_id `has_well_founded.r
run_cmd script_check_id `has_well_founded.wf
run_cmd script_check_id `has_zero
run_cmd script_check_id `has_zero.zero
run_cmd script_check_id `has_coe_t
run_cmd script_check_id `heq
run_cmd script_check_id `heq.refl
run_cmd script_check_id `heq.symm
run_cmd script_check_id `heq.trans
run_cmd script_check_id `heq_of_eq
run_cmd script_check_id `hole_command
run_cmd script_check_id `id
run_cmd script_check_id `id_rhs
run_cmd script_check_id `id_delta
run_cmd script_check_id `if_neg
run_cmd script_check_id `if_pos
run_cmd script_check_id `iff
run_cmd script_check_id `iff_false_intro
run_cmd script_check_id `iff.intro
run_cmd script_check_id `iff.mp
run_cmd script_check_id `iff.mpr
run_cmd script_check_id `iff.refl
run_cmd script_check_id `iff.symm
run_cmd script_check_id `iff.trans
run_cmd script_check_id `iff_true_intro
run_cmd script_check_id `imp_congr
run_cmd script_check_id `imp_congr_eq
run_cmd script_check_id `imp_congr_ctx
run_cmd script_check_id `imp_congr_ctx_eq
run_cmd script_check_id `implies
run_cmd script_check_id `implies_of_if_neg
run_cmd script_check_id `implies_of_if_pos
run_cmd script_check_id `int
run_cmd script_check_id `int.bit0_nonneg
run_cmd script_check_id `int.bit1_nonneg
run_cmd script_check_id `int.one_nonneg
run_cmd script_check_id `int.zero_nonneg
run_cmd script_check_id `int.bit0_pos
run_cmd script_check_id `int.bit1_pos
run_cmd script_check_id `int.one_pos
run_cmd script_check_id `int.nat_abs_zero
run_cmd script_check_id `int.nat_abs_one
run_cmd script_check_id `int.nat_abs_bit0_step
run_cmd script_check_id `int.nat_abs_bit1_nonneg_step
run_cmd script_check_id `int.ne_of_nat_ne_nonneg_case
run_cmd script_check_id `int.ne_neg_of_ne
run_cmd script_check_id `int.neg_ne_of_pos
run_cmd script_check_id `int.ne_neg_of_pos
run_cmd script_check_id `int.neg_ne_zero_of_ne
run_cmd script_check_id `int.zero_ne_neg_of_ne
run_cmd script_check_id `interactive.param_desc
run_cmd script_check_id `interactive.parse
run_cmd script_check_id `io_core
run_cmd script_check_id `monad_io_impl
run_cmd script_check_id `monad_io_terminal_impl
run_cmd script_check_id `monad_io_file_system_impl
run_cmd script_check_id `monad_io_environment_impl
run_cmd script_check_id `monad_io_process_impl
run_cmd script_check_id `monad_io_random_impl
run_cmd script_check_id `io_rand_nat
run_cmd script_check_id `io
run_cmd script_check_id `is_associative
run_cmd script_check_id `is_associative.assoc
run_cmd script_check_id `is_commutative
run_cmd script_check_id `is_commutative.comm
run_cmd script_check_id `ite
run_cmd script_check_id `lean.parser
run_cmd script_check_id `lean.parser.pexpr
run_cmd script_check_id `lean.parser.tk
run_cmd script_check_id `left_distrib
run_cmd script_check_id `left_comm
run_cmd script_check_id `le_refl
run_cmd script_check_id `linear_ordered_ring
run_cmd script_check_id `linear_ordered_semiring
run_cmd script_check_id `list
run_cmd script_check_id `list.nil
run_cmd script_check_id `list.cons
run_cmd script_check_id `match_failed
run_cmd script_check_id `monad
run_cmd script_check_id `monad_fail
run_cmd script_check_id `monoid
run_cmd script_check_id `mul_one
run_cmd script_check_id `mul_zero
run_cmd script_check_id `mul_zero_class
run_cmd script_check_id `name.anonymous
run_cmd script_check_id `name.mk_numeral
run_cmd script_check_id `name.mk_string
run_cmd script_check_id `nat
run_cmd script_check_id `nat.succ
run_cmd script_check_id `nat.zero
run_cmd script_check_id `nat.has_zero
run_cmd script_check_id `nat.has_one
run_cmd script_check_id `nat.has_add
run_cmd script_check_id `nat.add
run_cmd script_check_id `nat.cases_on
run_cmd script_check_id `nat.bit0_ne
run_cmd script_check_id `nat.bit0_ne_bit1
run_cmd script_check_id `nat.bit0_ne_zero
run_cmd script_check_id `nat.bit0_ne_one
run_cmd script_check_id `nat.bit1_ne
run_cmd script_check_id `nat.bit1_ne_bit0
run_cmd script_check_id `nat.bit1_ne_zero
run_cmd script_check_id `nat.bit1_ne_one
run_cmd script_check_id `nat.zero_ne_one
run_cmd script_check_id `nat.zero_ne_bit0
run_cmd script_check_id `nat.zero_ne_bit1
run_cmd script_check_id `nat.one_ne_zero
run_cmd script_check_id `nat.one_ne_bit0
run_cmd script_check_id `nat.one_ne_bit1
run_cmd script_check_id `nat.bit0_lt
run_cmd script_check_id `nat.bit1_lt
run_cmd script_check_id `nat.bit0_lt_bit1
run_cmd script_check_id `nat.bit1_lt_bit0
run_cmd script_check_id `nat.zero_lt_one
run_cmd script_check_id `nat.zero_lt_bit1
run_cmd script_check_id `nat.zero_lt_bit0
run_cmd script_check_id `nat.one_lt_bit0
run_cmd script_check_id `nat.one_lt_bit1
run_cmd script_check_id `nat.le_of_lt
run_cmd script_check_id `nat.le_refl
run_cmd script_check_id `ne
run_cmd script_check_id `neq_of_not_iff
run_cmd script_check_id `norm_num.add1
run_cmd script_check_id `norm_num.add1_bit0
run_cmd script_check_id `norm_num.add1_bit1_helper
run_cmd script_check_id `norm_num.add1_one
run_cmd script_check_id `norm_num.add1_zero
run_cmd script_check_id `norm_num.add_div_helper
run_cmd script_check_id `norm_num.bin_add_zero
run_cmd script_check_id `norm_num.bin_zero_add
run_cmd script_check_id `norm_num.bit0_add_bit0_helper
run_cmd script_check_id `norm_num.bit0_add_bit1_helper
run_cmd script_check_id `norm_num.bit0_add_one
run_cmd script_check_id `norm_num.bit1_add_bit0_helper
run_cmd script_check_id `norm_num.bit1_add_bit1_helper
run_cmd script_check_id `norm_num.bit1_add_one_helper
run_cmd script_check_id `norm_num.div_add_helper
run_cmd script_check_id `norm_num.div_eq_div_helper
run_cmd script_check_id `norm_num.div_helper
run_cmd script_check_id `norm_num.div_mul_helper
run_cmd script_check_id `norm_num.mk_cong
run_cmd script_check_id `norm_num.mul_bit0_helper
run_cmd script_check_id `norm_num.mul_bit1_helper
run_cmd script_check_id `norm_num.mul_div_helper
run_cmd script_check_id `norm_num.neg_add_neg_helper
run_cmd script_check_id `norm_num.neg_add_pos_helper1
run_cmd script_check_id `norm_num.neg_add_pos_helper2
run_cmd script_check_id `norm_num.neg_mul_neg_helper
run_cmd script_check_id `norm_num.neg_mul_pos_helper
run_cmd script_check_id `norm_num.neg_neg_helper
run_cmd script_check_id `norm_num.neg_zero_helper
run_cmd script_check_id `norm_num.nonneg_bit0_helper
run_cmd script_check_id `norm_num.nonneg_bit1_helper
run_cmd script_check_id `norm_num.nonzero_of_div_helper
run_cmd script_check_id `norm_num.nonzero_of_neg_helper
run_cmd script_check_id `norm_num.nonzero_of_pos_helper
run_cmd script_check_id `norm_num.one_add_bit0
run_cmd script_check_id `norm_num.one_add_bit1_helper
run_cmd script_check_id `norm_num.one_add_one
run_cmd script_check_id `norm_num.pos_add_neg_helper
run_cmd script_check_id `norm_num.pos_bit0_helper
run_cmd script_check_id `norm_num.pos_bit1_helper
run_cmd script_check_id `norm_num.pos_mul_neg_helper
run_cmd script_check_id `norm_num.sub_nat_zero_helper
run_cmd script_check_id `norm_num.sub_nat_pos_helper
run_cmd script_check_id `norm_num.subst_into_div
run_cmd script_check_id `norm_num.subst_into_prod
run_cmd script_check_id `norm_num.subst_into_subtr
run_cmd script_check_id `norm_num.subst_into_sum
run_cmd script_check_id `not
run_cmd script_check_id `not_of_iff_false
run_cmd script_check_id `not_of_eq_false
run_cmd script_check_id `of_eq_true
run_cmd script_check_id `of_iff_true
run_cmd script_check_id `opt_param
run_cmd script_check_id `or
run_cmd script_check_id `out_param
run_cmd script_check_id `punit
run_cmd script_check_id `punit.cases_on
run_cmd script_check_id `punit.star
run_cmd script_check_id `prod.mk
run_cmd script_check_id `pprod
run_cmd script_check_id `pprod.mk
run_cmd script_check_id `pprod.fst
run_cmd script_check_id `pprod.snd
run_cmd script_check_id `propext
run_cmd script_check_id `to_pexpr
run_cmd script_check_id `quot.mk
run_cmd script_check_id `quot.lift
run_cmd script_check_id `reflected
run_cmd script_check_id `reflected.subst
run_cmd script_check_id `repr
run_cmd script_check_id `rfl
run_cmd script_check_id `right_distrib
run_cmd script_check_id `ring
run_cmd script_check_id `scope_trace
run_cmd script_check_id `set_of
run_cmd script_check_id `semiring
run_cmd script_check_id `psigma
run_cmd script_check_id `psigma.cases_on
run_cmd script_check_id `psigma.mk
run_cmd script_check_id `psigma.fst
run_cmd script_check_id `psigma.snd
run_cmd script_check_id `singleton
run_cmd script_check_id `sizeof
run_cmd script_check_id `string
run_cmd script_check_id `string.empty
run_cmd script_check_id `string.str
run_cmd script_check_id `string.empty_ne_str
run_cmd script_check_id `string.str_ne_empty
run_cmd script_check_id `string.str_ne_str_left
run_cmd script_check_id `string.str_ne_str_right
run_cmd script_check_id `subsingleton
run_cmd script_check_id `subsingleton.elim
run_cmd script_check_id `subsingleton.helim
run_cmd script_check_id `subtype
run_cmd script_check_id `subtype.mk
run_cmd script_check_id `subtype.val
run_cmd script_check_id `subtype.rec
run_cmd script_check_id `psum
run_cmd script_check_id `psum.cases_on
run_cmd script_check_id `psum.inl
run_cmd script_check_id `psum.inr
run_cmd script_check_id `tactic
run_cmd script_check_id `tactic.try
run_cmd script_check_id `tactic.triv
run_cmd script_check_id `tactic.mk_inj_eq
run_cmd script_check_id `thunk
run_cmd script_check_id `to_fmt
run_cmd script_check_id `trans_rel_left
run_cmd script_check_id `trans_rel_right
run_cmd script_check_id `true
run_cmd script_check_id `true.intro
run_cmd script_check_id `typed_expr
run_cmd script_check_id `unification_hint
run_cmd script_check_id `unification_hint.mk
run_cmd script_check_id `unit
run_cmd script_check_id `unit.star
run_cmd script_check_id `monad_from_pure_bind
run_cmd script_check_id `user_attribute
run_cmd script_check_id `user_attribute.parse_reflect
run_cmd script_check_id `vm_monitor
run_cmd script_check_id `partial_order
run_cmd script_check_id `well_founded.fix
run_cmd script_check_id `well_founded.fix_eq
run_cmd script_check_id `well_founded_tactics
run_cmd script_check_id `well_founded_tactics.default
run_cmd script_check_id `well_founded_tactics.rel_tac
run_cmd script_check_id `well_founded_tactics.dec_tac
run_cmd script_check_id `zero_le_one
run_cmd script_check_id `zero_lt_one
run_cmd script_check_id `zero_mul
|
4a6cab2e9569cee7623364cdae891a2d21b9b58d
|
cf39355caa609c0f33405126beee2739aa3cb77e
|
/tests/lean/run/unfold_lemmas.lean
|
fbe281cd4587b99b2081d9cd3ba0c05b8b81a94e
|
[
"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
| 275
|
lean
|
open nat well_founded
def gcd' : ℕ → ℕ → ℕ | y := λ x,
if h : y = 0 then
x
else
have x % y < y, by { apply mod_lt, cases y, contradiction, apply succ_pos },
gcd' (x % y) y
@[simp] lemma gcd_zero_right (x : nat) : gcd' 0 x = x :=
by { rw gcd', simp }
|
019bea9ba1a5ae2a0dbde881905b02af7626ee32
|
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
|
/tests/lean/run/new_compiler.lean
|
9e2c2668a2ae18178fa2cfeeadebee0dd98704e1
|
[
"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
| 1,745
|
lean
|
universe u v w r s
set_option trace.compiler.stage1 true
-- set_option pp.explicit true
set_option pp.binder_types false
-- set_option pp.proofs true
def foo (n : Nat) : Nat :=
let x := Nat.zero;
let x1 := Nat.succ x;
let x2 := Nat.succ x1;
let x3 := Nat.succ x2;
let x4 := Nat.succ x3;
let x5 := Nat.succ x4;
let x6 := Nat.succ x5;
let x7 := Nat.succ x ;
let x8 := Nat.succ x7;
let y1 := x;
let y2 := y1;
y2 + n
def cseTst (n : Nat) : Nat :=
let y := Nat.succ ((fun x => x) n);
let z := Nat.succ n;
y + z
def tst1 (n : Nat) : Nat :=
let p := (Nat.succ n, n);
let q := (p, p);
match q with
| ((z, w), y) => z
def tst2 (n : Nat) : Nat :=
let p := (fun x => Nat.succ x, Nat.zero) ;
let f := fun (p : (Nat → Nat) × Nat) => p.1;
f p n
partial def add' : Nat → Nat → Nat
| 0, b => Nat.succ b
| a+1, b => Nat.succ (Nat.succ (add' a b))
def aux (i : Nat) (h : i > 0) :=
i
axiom bad (α : Sort u) : α
unsafe def foo2 : Nat :=
@False.rec (fun _ => Nat) (bad _)
set_option pp.notation false
def foo3 (n : Nat) : Nat :=
(fun (a : Nat) => a + a + a) (n*n)
def boo (a : Nat) (l : List Nat) : List Nat :=
let f := @List.cons Nat;
f a (f a l)
def bla (i : Nat) (h : i > 0 ∧ i ≠ 10) : Nat :=
@And.rec _ _ (fun _ => Nat) (fun h₁ h₂ => aux i h₁ + aux i h₁) h
def bla' (i : Nat) (h : i > 0 ∧ i ≠ 10) : Nat :=
@And.casesOn _ _ (fun _ => Nat) h (fun h₁ h₂ => aux i h₁ + aux i h₁)
inductive vec (α : Type u) : Nat → Type u
| nil : vec α 0
| cons : ∀ {n}, α → vec α n → vec α (Nat.succ n)
/-
def vec.map {α β σ : Type u} (f : α → β → σ) : ∀ {n : Nat}, vec α n → vec β n → vec σ n
| _, nil, nil => nil
| _, cons a as, cons b bs => cons (f a b) (map f as bs)
-/
|
dac220e74c5de18553ca2c3af459b88d029edd4a
|
432d948a4d3d242fdfb44b81c9e1b1baacd58617
|
/src/analysis/normed_space/inner_product.lean
|
545161c86d7b30068a5db446985673c45c8ba3dc
|
[
"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
| 127,431
|
lean
|
/-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis, Heather Macbeth
-/
import linear_algebra.bilinear_form
import linear_algebra.sesquilinear_form
import topology.metric_space.pi_Lp
import data.complex.is_R_or_C
import analysis.special_functions.sqrt
/-!
# Inner Product Space
This file defines inner product spaces and proves its basic properties.
An inner product space is a vector space endowed with an inner product. It generalizes the notion of
dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between
two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero.
We define both the real and complex cases at the same time using the `is_R_or_C` typeclass.
## Main results
- We define the class `inner_product_space 𝕜 E` extending `normed_space 𝕜 E` with a number of basic
properties, most notably the Cauchy-Schwarz inequality. Here `𝕜` is understood to be either `ℝ`
or `ℂ`, through the `is_R_or_C` typeclass.
- We show that if `f i` is an inner product space for each `i`, then so is `Π i, f i`
- We define `euclidean_space 𝕜 n` to be `n → 𝕜` for any `fintype n`, and show that
this an inner product space.
- Existence of orthogonal projection onto nonempty complete subspace:
Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace.
Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`.
The point `v` is usually called the orthogonal projection of `u` onto `K`.
- We define `orthonormal`, a predicate on a function `v : ι → E`. We prove the existence of a
maximal orthonormal set, `exists_maximal_orthonormal`, and also prove that a maximal orthonormal
set is a basis (`maximal_orthonormal_iff_is_basis_of_finite_dimensional`), if `E` is finite-
dimensional, or in general (`maximal_orthonormal_iff_dense_span`) a set whose span is dense
(i.e., a Hilbert basis, although we do not make that definition).
## Notation
We globally denote the real and complex inner products by `⟪·, ·⟫_ℝ` and `⟪·, ·⟫_ℂ` respectively.
We also provide two notation namespaces: `real_inner_product_space`, `complex_inner_product_space`,
which respectively introduce the plain notation `⟪·, ·⟫` for the the real and complex inner product.
The orthogonal complement of a submodule `K` is denoted by `Kᗮ`.
## Implementation notes
We choose the convention that inner products are conjugate linear in the first argument and linear
in the second.
## TODO
- Fix the section on the existence of minimizers and orthogonal projections to make sure that it
also applies in the complex case.
## Tags
inner product space, norm
## References
* [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*]
* [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*]
The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html>
-/
noncomputable theory
open is_R_or_C real filter
open_locale big_operators classical topological_space
variables {𝕜 E F : Type*} [is_R_or_C 𝕜]
/-- Syntactic typeclass for types endowed with an inner product -/
class has_inner (𝕜 E : Type*) := (inner : E → E → 𝕜)
export has_inner (inner)
notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y
notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y
section notations
localized "notation `⟪`x`, `y`⟫` := @inner ℝ _ _ x y" in real_inner_product_space
localized "notation `⟪`x`, `y`⟫` := @inner ℂ _ _ x y" in complex_inner_product_space
end notations
/--
An inner product space is a vector space with an additional operation called inner product.
The norm could be derived from the inner product, instead we require the existence of a norm and
the fact that `∥x∥^2 = re ⟪x, x⟫` to be able to put instances on `𝕂` or product
spaces.
To construct a norm from an inner product, see `inner_product_space.of_core`.
-/
class inner_product_space (𝕜 : Type*) (E : Type*) [is_R_or_C 𝕜]
extends normed_group E, normed_space 𝕜 E, has_inner 𝕜 E :=
(norm_sq_eq_inner : ∀ (x : E), ∥x∥^2 = re (inner x x))
(conj_sym : ∀ x y, conj (inner y x) = inner x y)
(add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z)
(smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y)
attribute [nolint dangerous_instance] inner_product_space.to_normed_group
-- note [is_R_or_C instance]
/-!
### Constructing a normed space structure from an inner product
In the definition of an inner product space, we require the existence of a norm, which is equal
(but maybe not defeq) to the square root of the scalar product. This makes it possible to put
an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good
properties. However, sometimes, one would like to define the norm starting only from a well-behaved
scalar product. This is what we implement in this paragraph, starting from a structure
`inner_product_space.core` stating that we have a nice scalar product.
Our goal here is not to develop a whole theory with all the supporting API, as this will be done
below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as
possible to the construction of the norm and the proof of the triangular inequality.
Warning: Do not use this `core` structure if the space you are interested in already has a norm
instance defined on it, otherwise this will create a second non-defeq norm instance!
-/
/-- A structure requiring that a scalar product is positive definite and symmetric, from which one
can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/
@[nolint has_inhabited_instance]
structure inner_product_space.core
(𝕜 : Type*) (F : Type*)
[is_R_or_C 𝕜] [add_comm_group F] [module 𝕜 F] :=
(inner : F → F → 𝕜)
(conj_sym : ∀ x y, conj (inner y x) = inner x y)
(nonneg_re : ∀ x, 0 ≤ re (inner x x))
(definite : ∀ x, inner x x = 0 → x = 0)
(add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z)
(smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y)
/- We set `inner_product_space.core` to be a class as we will use it as such in the construction
of the normed space structure that it produces. However, all the instances we will use will be
local to this proof. -/
attribute [class] inner_product_space.core
namespace inner_product_space.of_core
variables [add_comm_group F] [module 𝕜 F] [c : inner_product_space.core 𝕜 F]
include c
local notation `⟪`x`, `y`⟫` := @inner 𝕜 F _ x y
local notation `norm_sqK` := @is_R_or_C.norm_sq 𝕜 _
local notation `reK` := @is_R_or_C.re 𝕜 _
local notation `absK` := @is_R_or_C.abs 𝕜 _
local notation `ext_iff` := @is_R_or_C.ext_iff 𝕜 _
local postfix `†`:90 := @is_R_or_C.conj 𝕜 _
/-- Inner product defined by the `inner_product_space.core` structure. -/
def to_has_inner : has_inner 𝕜 F := { inner := c.inner }
local attribute [instance] to_has_inner
/-- The norm squared function for `inner_product_space.core` structure. -/
def norm_sq (x : F) := reK ⟪x, x⟫
local notation `norm_sqF` := @norm_sq 𝕜 F _ _ _ _
lemma inner_conj_sym (x y : F) : ⟪y, x⟫† = ⟪x, y⟫ := c.conj_sym x y
lemma inner_self_nonneg {x : F} : 0 ≤ re ⟪x, x⟫ := c.nonneg_re _
lemma inner_self_nonneg_im {x : F} : im ⟪x, x⟫ = 0 :=
by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp [inner_conj_sym]
lemma inner_self_im_zero {x : F} : im ⟪x, x⟫ = 0 :=
inner_self_nonneg_im
lemma inner_add_left {x y z : F} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ :=
c.add_left _ _ _
lemma inner_add_right {x y z : F} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ :=
by rw [←inner_conj_sym, inner_add_left, ring_hom.map_add]; simp only [inner_conj_sym]
lemma inner_norm_sq_eq_inner_self (x : F) : (norm_sqF x : 𝕜) = ⟪x, x⟫ :=
begin
rw ext_iff,
exact ⟨by simp only [of_real_re]; refl, by simp only [inner_self_nonneg_im, of_real_im]⟩
end
lemma inner_re_symm {x y : F} : re ⟪x, y⟫ = re ⟪y, x⟫ :=
by rw [←inner_conj_sym, conj_re]
lemma inner_im_symm {x y : F} : im ⟪x, y⟫ = -im ⟪y, x⟫ :=
by rw [←inner_conj_sym, conj_im]
lemma inner_smul_left {x y : F} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ :=
c.smul_left _ _ _
lemma inner_smul_right {x y : F} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ :=
by rw [←inner_conj_sym, inner_smul_left]; simp only [conj_conj, inner_conj_sym, ring_hom.map_mul]
lemma inner_zero_left {x : F} : ⟪0, x⟫ = 0 :=
by rw [←zero_smul 𝕜 (0 : F), inner_smul_left]; simp only [zero_mul, ring_hom.map_zero]
lemma inner_zero_right {x : F} : ⟪x, 0⟫ = 0 :=
by rw [←inner_conj_sym, inner_zero_left]; simp only [ring_hom.map_zero]
lemma inner_self_eq_zero {x : F} : ⟪x, x⟫ = 0 ↔ x = 0 :=
iff.intro (c.definite _) (by { rintro rfl, exact inner_zero_left })
lemma inner_self_re_to_K {x : F} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ :=
by norm_num [ext_iff, inner_self_nonneg_im]
lemma inner_abs_conj_sym {x y : F} : abs ⟪x, y⟫ = abs ⟪y, x⟫ :=
by rw [←inner_conj_sym, abs_conj]
lemma inner_neg_left {x y : F} : ⟪-x, y⟫ = -⟪x, y⟫ :=
by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp }
lemma inner_neg_right {x y : F} : ⟪x, -y⟫ = -⟪x, y⟫ :=
by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym]
lemma inner_sub_left {x y z : F} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ :=
by { simp [sub_eq_add_neg, inner_add_left, inner_neg_left] }
lemma inner_sub_right {x y z : F} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ :=
by { simp [sub_eq_add_neg, inner_add_right, inner_neg_right] }
lemma inner_mul_conj_re_abs {x y : F} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) :=
by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), }
/-- Expand `inner (x + y) (x + y)` -/
lemma inner_add_add_self {x y : F} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ :=
by simp only [inner_add_left, inner_add_right]; ring
/- Expand `inner (x - y) (x - y)` -/
lemma inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ :=
by simp only [inner_sub_left, inner_sub_right]; ring
/--
Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia.
We need this for the `core` structure to prove the triangle inequality below when
showing the core is a normed group.
-/
lemma inner_mul_inner_self_le (x y : F) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ :=
begin
by_cases hy : y = 0,
{ rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] },
{ change y ≠ 0 at hy,
have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h,
set T := ⟪y, x⟫ / ⟪y, y⟫ with hT,
have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm,
have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm,
have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫,
{ rw [mul_div_assoc],
have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ :=
by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul],
rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] },
have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp only [inner_self_re_to_K],
have h₅ : re ⟪y, y⟫ > 0,
{ refine lt_of_le_of_ne inner_self_nonneg _,
intro H,
apply hy',
rw ext_iff,
exact ⟨by simp [H],by simp [inner_self_nonneg_im]⟩ },
have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅,
have hmain := calc
0 ≤ re ⟪x - T • y, x - T • y⟫
: inner_self_nonneg
... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫
: by simp [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂]
... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫)
: by simp [inner_smul_left, inner_smul_right, mul_assoc]
... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫)
: by field_simp [-mul_re, inner_conj_sym, hT, conj_div, h₁, h₃]
... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫)
: by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc]
... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫)
: by conv_lhs { rw [h₄] }
... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫
: by rw [div_re_of_real]
... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫
: by rw [inner_mul_conj_re_abs]
... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫
: by rw is_R_or_C.abs_mul,
have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith,
have := (mul_le_mul_right h₅).mpr hmain',
rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this }
end
/-- Norm constructed from a `inner_product_space.core` structure, defined to be the square root
of the scalar product. -/
def to_has_norm : has_norm F :=
{ norm := λ x, sqrt (re ⟪x, x⟫) }
local attribute [instance] to_has_norm
lemma norm_eq_sqrt_inner (x : F) : ∥x∥ = sqrt (re ⟪x, x⟫) := rfl
lemma inner_self_eq_norm_sq (x : F) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ :=
by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫),
sqrt_mul_self inner_self_nonneg]
lemma sqrt_norm_sq_eq_norm {x : F} : sqrt (norm_sqF x) = ∥x∥ := rfl
/-- Cauchy–Schwarz inequality with norm -/
lemma abs_inner_le_norm (x y : F) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ :=
nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _))
begin
have H : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = re ⟪y, y⟫ * re ⟪x, x⟫,
{ simp only [inner_self_eq_norm_sq], ring, },
rw H,
conv
begin
to_lhs, congr, rw[inner_abs_conj_sym],
end,
exact inner_mul_inner_self_le y x,
end
/-- Normed group structure constructed from an `inner_product_space.core` structure -/
def to_normed_group : normed_group F :=
normed_group.of_core F
{ norm_eq_zero_iff := assume x,
begin
split,
{ intro H,
change sqrt (re ⟪x, x⟫) = 0 at H,
rw [sqrt_eq_zero inner_self_nonneg] at H,
apply (inner_self_eq_zero : ⟪x, x⟫ = 0 ↔ x = 0).mp,
rw ext_iff,
exact ⟨by simp [H], by simp [inner_self_im_zero]⟩ },
{ rintro rfl,
change sqrt (re ⟪0, 0⟫) = 0,
simp only [sqrt_zero, inner_zero_right, add_monoid_hom.map_zero] }
end,
triangle := assume x y,
begin
have h₁ : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := abs_inner_le_norm _ _,
have h₂ : re ⟪x, y⟫ ≤ abs ⟪x, y⟫ := re_le_abs _,
have h₃ : re ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := by linarith,
have h₄ : re ⟪y, x⟫ ≤ ∥x∥ * ∥y∥ := by rwa [←inner_conj_sym, conj_re],
have : ∥x + y∥ * ∥x + y∥ ≤ (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥),
{ simp [←inner_self_eq_norm_sq, inner_add_add_self, add_mul, mul_add, mul_comm],
linarith },
exact nonneg_le_nonneg_of_sq_le_sq (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this
end,
norm_neg := λ x, by simp only [norm, inner_neg_left, neg_neg, inner_neg_right] }
local attribute [instance] to_normed_group
/-- Normed space structure constructed from a `inner_product_space.core` structure -/
def to_normed_space : normed_space 𝕜 F :=
{ norm_smul_le := assume r x,
begin
rw [norm_eq_sqrt_inner, inner_smul_left, inner_smul_right, ←mul_assoc],
rw [conj_mul_eq_norm_sq_left, of_real_mul_re, sqrt_mul, ←inner_norm_sq_eq_inner_self,
of_real_re],
{ simp [sqrt_norm_sq_eq_norm, is_R_or_C.sqrt_norm_sq_eq_norm] },
{ exact norm_sq_nonneg r }
end }
end inner_product_space.of_core
/-- Given a `inner_product_space.core` structure on a space, one can use it to turn
the space into an inner product space, constructing the norm out of the inner product -/
def inner_product_space.of_core [add_comm_group F] [module 𝕜 F]
(c : inner_product_space.core 𝕜 F) : inner_product_space 𝕜 F :=
begin
letI : normed_group F := @inner_product_space.of_core.to_normed_group 𝕜 F _ _ _ c,
letI : normed_space 𝕜 F := @inner_product_space.of_core.to_normed_space 𝕜 F _ _ _ c,
exact { norm_sq_eq_inner := λ x,
begin
have h₁ : ∥x∥^2 = (sqrt (re (c.inner x x))) ^ 2 := rfl,
have h₂ : 0 ≤ re (c.inner x x) := inner_product_space.of_core.inner_self_nonneg,
simp [h₁, sq_sqrt, h₂],
end,
..c }
end
/-! ### Properties of inner product spaces -/
variables [inner_product_space 𝕜 E] [inner_product_space ℝ F]
local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y
local notation `IK` := @is_R_or_C.I 𝕜 _
local notation `absR` := _root_.abs
local notation `absK` := @is_R_or_C.abs 𝕜 _
local postfix `†`:90 := @is_R_or_C.conj 𝕜 _
local postfix `⋆`:90 := complex.conj
export inner_product_space (norm_sq_eq_inner)
section basic_properties
@[simp] lemma inner_conj_sym (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ := inner_product_space.conj_sym _ _
lemma real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := inner_conj_sym x y
lemma inner_eq_zero_sym {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 :=
⟨λ h, by simp [←inner_conj_sym, h], λ h, by simp [←inner_conj_sym, h]⟩
@[simp] lemma inner_self_nonneg_im {x : E} : im ⟪x, x⟫ = 0 :=
by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp
lemma inner_self_im_zero {x : E} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im
lemma inner_add_left {x y z : E} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ :=
inner_product_space.add_left _ _ _
lemma inner_add_right {x y z : E} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ :=
by { rw [←inner_conj_sym, inner_add_left, ring_hom.map_add], simp only [inner_conj_sym] }
lemma inner_re_symm {x y : E} : re ⟪x, y⟫ = re ⟪y, x⟫ :=
by rw [←inner_conj_sym, conj_re]
lemma inner_im_symm {x y : E} : im ⟪x, y⟫ = -im ⟪y, x⟫ :=
by rw [←inner_conj_sym, conj_im]
lemma inner_smul_left {x y : E} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ :=
inner_product_space.smul_left _ _ _
lemma real_inner_smul_left {x y : F} {r : ℝ} : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_left
lemma inner_smul_real_left {x y : E} {r : ℝ} : ⟪(r : 𝕜) • x, y⟫ = r • ⟪x, y⟫ :=
by { rw [inner_smul_left, conj_of_real, algebra.smul_def], refl }
lemma inner_smul_right {x y : E} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ :=
by rw [←inner_conj_sym, inner_smul_left, ring_hom.map_mul, conj_conj, inner_conj_sym]
lemma real_inner_smul_right {x y : F} {r : ℝ} : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_right
lemma inner_smul_real_right {x y : E} {r : ℝ} : ⟪x, (r : 𝕜) • y⟫ = r • ⟪x, y⟫ :=
by { rw [inner_smul_right, algebra.smul_def], refl }
/-- The inner product as a sesquilinear form. -/
@[simps]
def sesq_form_of_inner : sesq_form 𝕜 E (conj_to_ring_equiv 𝕜) :=
{ sesq := λ x y, ⟪y, x⟫, -- Note that sesquilinear forms are linear in the first argument
sesq_add_left := λ x y z, inner_add_right,
sesq_add_right := λ x y z, inner_add_left,
sesq_smul_left := λ r x y, inner_smul_right,
sesq_smul_right := λ r x y, inner_smul_left }
/-- The real inner product as a bilinear form. -/
@[simps]
def bilin_form_of_real_inner : bilin_form ℝ F :=
{ bilin := inner,
bilin_add_left := λ x y z, inner_add_left,
bilin_smul_left := λ a x y, inner_smul_left,
bilin_add_right := λ x y z, inner_add_right,
bilin_smul_right := λ a x y, inner_smul_right }
/-- An inner product with a sum on the left. -/
lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → E) (x : E) :
⟪∑ i in s, f i, x⟫ = ∑ i in s, ⟪f i, x⟫ :=
sesq_form.sum_right (sesq_form_of_inner) _ _ _
/-- An inner product with a sum on the right. -/
lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → E) (x : E) :
⟪x, ∑ i in s, f i⟫ = ∑ i in s, ⟪x, f i⟫ :=
sesq_form.sum_left (sesq_form_of_inner) _ _ _
/-- An inner product with a sum on the left, `finsupp` version. -/
lemma finsupp.sum_inner {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) :
⟪l.sum (λ (i : ι) (a : 𝕜), a • v i), x⟫
= l.sum (λ (i : ι) (a : 𝕜), (is_R_or_C.conj a) • ⟪v i, x⟫) :=
by { convert sum_inner l.support (λ a, l a • v a) x, simp [inner_smul_left, finsupp.sum] }
/-- An inner product with a sum on the right, `finsupp` version. -/
lemma finsupp.inner_sum {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) :
⟪x, l.sum (λ (i : ι) (a : 𝕜), a • v i)⟫ = l.sum (λ (i : ι) (a : 𝕜), a • ⟪x, v i⟫) :=
by { convert inner_sum l.support (λ a, l a • v a) x, simp [inner_smul_right, finsupp.sum] }
@[simp] lemma inner_zero_left {x : E} : ⟪0, x⟫ = 0 :=
by rw [← zero_smul 𝕜 (0:E), inner_smul_left, ring_hom.map_zero, zero_mul]
lemma inner_re_zero_left {x : E} : re ⟪0, x⟫ = 0 :=
by simp only [inner_zero_left, add_monoid_hom.map_zero]
@[simp] lemma inner_zero_right {x : E} : ⟪x, 0⟫ = 0 :=
by rw [←inner_conj_sym, inner_zero_left, ring_hom.map_zero]
lemma inner_re_zero_right {x : E} : re ⟪x, 0⟫ = 0 :=
by simp only [inner_zero_right, add_monoid_hom.map_zero]
lemma inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ :=
by rw [←norm_sq_eq_inner]; exact pow_nonneg (norm_nonneg x) 2
lemma real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ := @inner_self_nonneg ℝ F _ _ x
@[simp] lemma inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 :=
begin
split,
{ intro h,
have h₁ : re ⟪x, x⟫ = 0 := by rw is_R_or_C.ext_iff at h; simp [h.1],
rw [←norm_sq_eq_inner x] at h₁,
rw [←norm_eq_zero],
exact pow_eq_zero h₁ },
{ rintro rfl,
exact inner_zero_left }
end
@[simp] lemma inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 :=
begin
split,
{ intro h,
rw ←inner_self_eq_zero,
have H₁ : re ⟪x, x⟫ ≥ 0, exact inner_self_nonneg,
have H₂ : re ⟪x, x⟫ = 0, exact le_antisymm h H₁,
rw is_R_or_C.ext_iff,
exact ⟨by simp [H₂], by simp [inner_self_nonneg_im]⟩ },
{ rintro rfl,
simp only [inner_zero_left, add_monoid_hom.map_zero] }
end
lemma real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 :=
by { have h := @inner_self_nonpos ℝ F _ _ x, simpa using h }
@[simp] lemma inner_self_re_to_K {x : E} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ :=
by rw is_R_or_C.ext_iff; exact ⟨by simp, by simp [inner_self_nonneg_im]⟩
lemma inner_self_eq_norm_sq_to_K (x : E) : ⟪x, x⟫ = (∥x∥ ^ 2 : 𝕜) :=
begin
suffices : (is_R_or_C.re ⟪x, x⟫ : 𝕜) = ∥x∥ ^ 2,
{ simpa [inner_self_re_to_K] using this },
exact_mod_cast (norm_sq_eq_inner x).symm
end
lemma inner_self_re_abs {x : E} : re ⟪x, x⟫ = abs ⟪x, x⟫ :=
begin
conv_rhs { rw [←inner_self_re_to_K] },
symmetry,
exact is_R_or_C.abs_of_nonneg inner_self_nonneg,
end
lemma inner_self_abs_to_K {x : E} : (absK ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ :=
by { rw[←inner_self_re_abs], exact inner_self_re_to_K }
lemma real_inner_self_abs {x : F} : absR ⟪x, x⟫_ℝ = ⟪x, x⟫_ℝ :=
by { have h := @inner_self_abs_to_K ℝ F _ _ x, simpa using h }
lemma inner_abs_conj_sym {x y : E} : abs ⟪x, y⟫ = abs ⟪y, x⟫ :=
by rw [←inner_conj_sym, abs_conj]
@[simp] lemma inner_neg_left {x y : E} : ⟪-x, y⟫ = -⟪x, y⟫ :=
by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp }
@[simp] lemma inner_neg_right {x y : E} : ⟪x, -y⟫ = -⟪x, y⟫ :=
by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym]
lemma inner_neg_neg {x y : E} : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp
@[simp] lemma inner_self_conj {x : E} : ⟪x, x⟫† = ⟪x, x⟫ :=
by rw [is_R_or_C.ext_iff]; exact ⟨by rw [conj_re], by rw [conj_im, inner_self_im_zero, neg_zero]⟩
lemma inner_sub_left {x y z : E} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ :=
by { simp [sub_eq_add_neg, inner_add_left] }
lemma inner_sub_right {x y z : E} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ :=
by { simp [sub_eq_add_neg, inner_add_right] }
lemma inner_mul_conj_re_abs {x y : E} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) :=
by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), }
/-- Expand `⟪x + y, x + y⟫` -/
lemma inner_add_add_self {x y : E} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ :=
by simp only [inner_add_left, inner_add_right]; ring
/-- Expand `⟪x + y, x + y⟫_ℝ` -/
lemma real_inner_add_add_self {x y : F} : ⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ :=
begin
have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl,
simp [inner_add_add_self, this],
ring,
end
/- Expand `⟪x - y, x - y⟫` -/
lemma inner_sub_sub_self {x y : E} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ :=
by simp only [inner_sub_left, inner_sub_right]; ring
/-- Expand `⟪x - y, x - y⟫_ℝ` -/
lemma real_inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ :=
begin
have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl,
simp [inner_sub_sub_self, this],
ring,
end
/-- Parallelogram law -/
lemma parallelogram_law {x y : E} :
⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) :=
by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm]
/-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. -/
lemma inner_mul_inner_self_le (x y : E) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ :=
begin
by_cases hy : y = 0,
{ rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] },
{ change y ≠ 0 at hy,
have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h,
set T := ⟪y, x⟫ / ⟪y, y⟫ with hT,
have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm,
have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm,
have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫,
{ rw [mul_div_assoc],
have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ :=
by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul],
rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] },
have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp,
have h₅ : re ⟪y, y⟫ > 0,
{ refine lt_of_le_of_ne inner_self_nonneg _,
intro H,
apply hy',
rw is_R_or_C.ext_iff,
exact ⟨by simp [H],by simp [inner_self_nonneg_im]⟩ },
have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅,
have hmain := calc
0 ≤ re ⟪x - T • y, x - T • y⟫
: inner_self_nonneg
... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫
: by simp [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂]
... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫)
: by simp [inner_smul_left, inner_smul_right, mul_assoc]
... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫)
: by field_simp [-mul_re, hT, conj_div, h₁, h₃, inner_conj_sym]
... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫)
: by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc]
... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫)
: by conv_lhs { rw [h₄] }
... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫
: by rw [div_re_of_real]
... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫
: by rw [inner_mul_conj_re_abs]
... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫
: by rw is_R_or_C.abs_mul,
have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith,
have := (mul_le_mul_right h₅).mpr hmain',
rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this }
end
/-- Cauchy–Schwarz inequality for real inner products. -/
lemma real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ :=
begin
have h₁ : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl,
have h₂ := @inner_mul_inner_self_le ℝ F _ _ x y,
dsimp at h₂,
have h₃ := abs_mul_abs_self ⟪x, y⟫_ℝ,
rw [h₁] at h₂,
simpa [h₃] using h₂,
end
/-- A family of vectors is linearly independent if they are nonzero
and orthogonal. -/
lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E}
(hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → ⟪v i, v j⟫ = 0) : linear_independent 𝕜 v :=
begin
rw linear_independent_iff',
intros s g hg i hi,
have h' : g i * inner (v i) (v i) = inner (v i) (∑ j in s, g j • v j),
{ rw inner_sum,
symmetry,
convert finset.sum_eq_single i _ _,
{ rw inner_smul_right },
{ intros j hj hji,
rw [inner_smul_right, ho i j hji.symm, mul_zero] },
{ exact λ h, false.elim (h hi) } },
simpa [hg, hz] using h'
end
end basic_properties
section orthonormal_sets
variables {ι : Type*} (𝕜)
include 𝕜
/-- An orthonormal set of vectors in an `inner_product_space` -/
def orthonormal (v : ι → E) : Prop :=
(∀ i, ∥v i∥ = 1) ∧ (∀ {i j}, i ≠ j → ⟪v i, v j⟫ = 0)
omit 𝕜
variables {𝕜}
/-- `if ... then ... else` characterization of an indexed set of vectors being orthonormal. (Inner
product equals Kronecker delta.) -/
lemma orthonormal_iff_ite {v : ι → E} :
orthonormal 𝕜 v ↔ ∀ i j, ⟪v i, v j⟫ = if i = j then (1:𝕜) else (0:𝕜) :=
begin
split,
{ intros hv i j,
split_ifs,
{ simp [h, inner_self_eq_norm_sq_to_K, hv.1] },
{ exact hv.2 h } },
{ intros h,
split,
{ intros i,
have h' : ∥v i∥ ^ 2 = 1 ^ 2 := by simp [norm_sq_eq_inner, h i i],
have h₁ : 0 ≤ ∥v i∥ := norm_nonneg _,
have h₂ : (0:ℝ) ≤ 1 := by norm_num,
rwa eq_of_sq_eq_sq h₁ h₂ at h' },
{ intros i j hij,
simpa [hij] using h i j } }
end
/-- `if ... then ... else` characterization of a set of vectors being orthonormal. (Inner product
equals Kronecker delta.) -/
theorem orthonormal_subtype_iff_ite {s : set E} :
orthonormal 𝕜 (coe : s → E) ↔
(∀ v ∈ s, ∀ w ∈ s, ⟪v, w⟫ = if v = w then 1 else 0) :=
begin
rw orthonormal_iff_ite,
split,
{ intros h v hv w hw,
convert h ⟨v, hv⟩ ⟨w, hw⟩ using 1,
simp },
{ rintros h ⟨v, hv⟩ ⟨w, hw⟩,
convert h v hv w hw using 1,
simp }
end
/-- The inner product of a linear combination of a set of orthonormal vectors with one of those
vectors picks out the coefficient of that vector. -/
lemma orthonormal.inner_right_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) :
⟪v i, finsupp.total ι E 𝕜 v l⟫ = l i :=
by simp [finsupp.total_apply, finsupp.inner_sum, orthonormal_iff_ite.mp hv]
/-- The inner product of a linear combination of a set of orthonormal vectors with one of those
vectors picks out the coefficient of that vector. -/
lemma orthonormal.inner_right_fintype [fintype ι]
{v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) :
⟪v i, ∑ i : ι, (l i) • (v i)⟫ = l i :=
by simp [inner_sum, inner_smul_right, orthonormal_iff_ite.mp hv]
/-- The inner product of a linear combination of a set of orthonormal vectors with one of those
vectors picks out the coefficient of that vector. -/
lemma orthonormal.inner_left_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) :
⟪finsupp.total ι E 𝕜 v l, v i⟫ = conj (l i) :=
by rw [← inner_conj_sym, hv.inner_right_finsupp]
/-- The inner product of a linear combination of a set of orthonormal vectors with one of those
vectors picks out the coefficient of that vector. -/
lemma orthonormal.inner_left_fintype [fintype ι]
{v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) :
⟪∑ i : ι, (l i) • (v i), v i⟫ = conj (l i) :=
by simp [sum_inner, inner_smul_left, orthonormal_iff_ite.mp hv]
/-- An orthonormal set is linearly independent. -/
lemma orthonormal.linear_independent {v : ι → E} (hv : orthonormal 𝕜 v) :
linear_independent 𝕜 v :=
begin
rw linear_independent_iff,
intros l hl,
ext i,
have key : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = ⟪v i, 0⟫ := by rw hl,
simpa [hv.inner_right_finsupp] using key
end
/-- A subfamily of an orthonormal family (i.e., a composition with an injective map) is an
orthonormal family. -/
lemma orthonormal.comp
{ι' : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) (f : ι' → ι) (hf : function.injective f) :
orthonormal 𝕜 (v ∘ f) :=
begin
rw orthonormal_iff_ite at ⊢ hv,
intros i j,
convert hv (f i) (f j) using 1,
simp [hf.eq_iff]
end
/-- A linear combination of some subset of an orthonormal set is orthogonal to other members of the
set. -/
lemma orthonormal.inner_finsupp_eq_zero
{v : ι → E} (hv : orthonormal 𝕜 v) {s : set ι} {i : ι} (hi : i ∉ s) {l : ι →₀ 𝕜}
(hl : l ∈ finsupp.supported 𝕜 𝕜 s) :
⟪finsupp.total ι E 𝕜 v l, v i⟫ = 0 :=
begin
rw finsupp.mem_supported' at hl,
simp [hv.inner_left_finsupp, hl i hi],
end
/- The material that follows, culminating in the existence of a maximal orthonormal subset, is
adapted from the corresponding development of the theory of linearly independents sets. See
`exists_linear_independent` in particular. -/
variables (𝕜 E)
lemma orthonormal_empty : orthonormal 𝕜 (λ x, x : (∅ : set E) → E) :=
by simp [orthonormal_subtype_iff_ite]
variables {𝕜 E}
lemma orthonormal_Union_of_directed
{η : Type*} {s : η → set E} (hs : directed (⊆) s) (h : ∀ i, orthonormal 𝕜 (λ x, x : s i → E)) :
orthonormal 𝕜 (λ x, x : (⋃ i, s i) → E) :=
begin
rw orthonormal_subtype_iff_ite,
rintros x ⟨_, ⟨i, rfl⟩, hxi⟩ y ⟨_, ⟨j, rfl⟩, hyj⟩,
obtain ⟨k, hik, hjk⟩ := hs i j,
have h_orth : orthonormal 𝕜 (λ x, x : (s k) → E) := h k,
rw orthonormal_subtype_iff_ite at h_orth,
exact h_orth x (hik hxi) y (hjk hyj)
end
lemma orthonormal_sUnion_of_directed
{s : set (set E)} (hs : directed_on (⊆) s)
(h : ∀ a ∈ s, orthonormal 𝕜 (λ x, x : (a : set E) → E)) :
orthonormal 𝕜 (λ x, x : (⋃₀ s) → E) :=
by rw set.sUnion_eq_Union; exact orthonormal_Union_of_directed hs.directed_coe (by simpa using h)
/-- Given an orthonormal set `v` of vectors in `E`, there exists a maximal orthonormal set
containing it. -/
lemma exists_maximal_orthonormal {s : set E} (hs : orthonormal 𝕜 (coe : s → E)) :
∃ w ⊇ s, orthonormal 𝕜 (coe : w → E) ∧ ∀ u ⊇ w, orthonormal 𝕜 (coe : u → E) → u = w :=
begin
rcases zorn.zorn_subset_nonempty {b | orthonormal 𝕜 (coe : b → E)} _ _ hs with ⟨b, bi, sb, h⟩,
{ refine ⟨b, sb, bi, _⟩,
exact λ u hus hu, h u hu hus },
{ refine λ c hc cc c0, ⟨⋃₀ c, _, _⟩,
{ exact orthonormal_sUnion_of_directed cc.directed_on (λ x xc, hc xc) },
{ exact λ _, set.subset_sUnion_of_mem } }
end
lemma orthonormal.ne_zero {v : ι → E} (hv : orthonormal 𝕜 v) (i : ι) : v i ≠ 0 :=
begin
have : ∥v i∥ ≠ 0,
{ rw hv.1 i,
norm_num },
simpa using this
end
open finite_dimensional
lemma is_basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E}
(hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) :
is_basis 𝕜 v :=
is_basis_of_linear_independent_of_card_eq_finrank hv.linear_independent card_eq
end orthonormal_sets
section norm
lemma norm_eq_sqrt_inner (x : E) : ∥x∥ = sqrt (re ⟪x, x⟫) :=
begin
have h₁ : ∥x∥^2 = re ⟪x, x⟫ := norm_sq_eq_inner x,
have h₂ := congr_arg sqrt h₁,
simpa using h₂,
end
lemma norm_eq_sqrt_real_inner (x : F) : ∥x∥ = sqrt ⟪x, x⟫_ℝ :=
by { have h := @norm_eq_sqrt_inner ℝ F _ _ x, simpa using h }
lemma inner_self_eq_norm_sq (x : E) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ :=
by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫),
sqrt_mul_self inner_self_nonneg]
lemma real_inner_self_eq_norm_sq (x : F) : ⟪x, x⟫_ℝ = ∥x∥ * ∥x∥ :=
by { have h := @inner_self_eq_norm_sq ℝ F _ _ x, simpa using h }
/-- Expand the square -/
lemma norm_add_sq {x y : E} : ∥x + y∥^2 = ∥x∥^2 + 2 * (re ⟪x, y⟫) + ∥y∥^2 :=
begin
repeat {rw [sq, ←inner_self_eq_norm_sq]},
rw[inner_add_add_self, two_mul],
simp only [add_assoc, add_left_inj, add_right_inj, add_monoid_hom.map_add],
rw [←inner_conj_sym, conj_re],
end
alias norm_add_sq ← norm_add_pow_two
/-- Expand the square -/
lemma norm_add_sq_real {x y : F} : ∥x + y∥^2 = ∥x∥^2 + 2 * ⟪x, y⟫_ℝ + ∥y∥^2 :=
by { have h := @norm_add_sq ℝ F _ _, simpa using h }
alias norm_add_sq_real ← norm_add_pow_two_real
/-- Expand the square -/
lemma norm_add_mul_self {x y : E} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * (re ⟪x, y⟫) + ∥y∥ * ∥y∥ :=
by { repeat {rw [← sq]}, exact norm_add_sq }
/-- Expand the square -/
lemma norm_add_mul_self_real {x y : F} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ :=
by { have h := @norm_add_mul_self ℝ F _ _, simpa using h }
/-- Expand the square -/
lemma norm_sub_sq {x y : E} : ∥x - y∥^2 = ∥x∥^2 - 2 * (re ⟪x, y⟫) + ∥y∥^2 :=
begin
repeat {rw [sq, ←inner_self_eq_norm_sq]},
rw[inner_sub_sub_self],
calc
re (⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫)
= re ⟪x, x⟫ - re ⟪x, y⟫ - re ⟪y, x⟫ + re ⟪y, y⟫ : by simp
... = -re ⟪y, x⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by ring
... = -re (⟪x, y⟫†) - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[inner_conj_sym]
... = -re ⟪x, y⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[conj_re]
... = re ⟪x, x⟫ - 2*re ⟪x, y⟫ + re ⟪y, y⟫ : by ring
end
alias norm_sub_sq ← norm_sub_pow_two
/-- Expand the square -/
lemma norm_sub_sq_real {x y : F} : ∥x - y∥^2 = ∥x∥^2 - 2 * ⟪x, y⟫_ℝ + ∥y∥^2 :=
norm_sub_sq
alias norm_sub_sq_real ← norm_sub_pow_two_real
/-- Expand the square -/
lemma norm_sub_mul_self {x y : E} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * re ⟪x, y⟫ + ∥y∥ * ∥y∥ :=
by { repeat {rw [← sq]}, exact norm_sub_sq }
/-- Expand the square -/
lemma norm_sub_mul_self_real {x y : F} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ :=
by { have h := @norm_sub_mul_self ℝ F _ _, simpa using h }
/-- Cauchy–Schwarz inequality with norm -/
lemma abs_inner_le_norm (x y : E) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ :=
nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (norm_nonneg _) (norm_nonneg _))
begin
have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = (re ⟪x, x⟫) * (re ⟪y, y⟫),
simp only [inner_self_eq_norm_sq], ring,
rw this,
conv_lhs { congr, skip, rw [inner_abs_conj_sym] },
exact inner_mul_inner_self_le _ _
end
/-- Cauchy–Schwarz inequality with norm -/
lemma abs_real_inner_le_norm (x y : F) : absR ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ :=
by { have h := @abs_inner_le_norm ℝ F _ _ x y, simpa using h }
/-- Cauchy–Schwarz inequality with norm -/
lemma real_inner_le_norm (x y : F) : ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ :=
le_trans (le_abs_self _) (abs_real_inner_le_norm _ _)
include 𝕜
lemma parallelogram_law_with_norm {x y : E} :
∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) :=
begin
simp only [← inner_self_eq_norm_sq],
rw[← re.map_add, parallelogram_law, two_mul, two_mul],
simp only [re.map_add],
end
omit 𝕜
lemma parallelogram_law_with_norm_real {x y : F} :
∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) :=
by { have h := @parallelogram_law_with_norm ℝ F _ _ x y, simpa using h }
/-- Polarization identity: The real part of the inner product, in terms of the norm. -/
lemma re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : E) :
re ⟪x, y⟫ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 :=
by { rw norm_add_mul_self, ring }
/-- Polarization identity: The real part of the inner product, in terms of the norm. -/
lemma re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : E) :
re ⟪x, y⟫ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 :=
by { rw [norm_sub_mul_self], ring }
/-- Polarization identity: The real part of the inner product, in terms of the norm. -/
lemma re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four (x y : E) :
re ⟪x, y⟫ = (∥x + y∥ * ∥x + y∥ - ∥x - y∥ * ∥x - y∥) / 4 :=
by { rw [norm_add_mul_self, norm_sub_mul_self], ring }
/-- Polarization identity: The imaginary part of the inner product, in terms of the norm. -/
lemma im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four (x y : E) :
im ⟪x, y⟫ = (∥x - IK • y∥ * ∥x - IK • y∥ - ∥x + IK • y∥ * ∥x + IK • y∥) / 4 :=
by { simp only [norm_add_mul_self, norm_sub_mul_self, inner_smul_right, I_mul_re], ring }
/-- Polarization identity: The inner product, in terms of the norm. -/
lemma inner_eq_sum_norm_sq_div_four (x y : E) :
⟪x, y⟫ = (∥x + y∥ ^ 2 - ∥x - y∥ ^ 2 + (∥x - IK • y∥ ^ 2 - ∥x + IK • y∥ ^ 2) * IK) / 4 :=
begin
rw [← re_add_im ⟪x, y⟫, re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four,
im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four],
push_cast,
simp only [sq, ← mul_div_right_comm, ← add_div]
end
section
variables {E' : Type*} [inner_product_space 𝕜 E']
/-- A linear isometry preserves the inner product. -/
@[simp] lemma linear_isometry.inner_map_map (f : E →ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ :=
by simp [inner_eq_sum_norm_sq_div_four, ← f.norm_map]
/-- A linear isometric equivalence preserves the inner product. -/
@[simp] lemma linear_isometry_equiv.inner_map_map (f : E ≃ₗᵢ[𝕜] E') (x y : E) :
⟪f x, f y⟫ = ⟪x, y⟫ :=
f.to_linear_isometry.inner_map_map x y
/-- A linear map that preserves the inner product is a linear isometry. -/
def linear_map.isometry_of_inner (f : E →ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E →ₗᵢ[𝕜] E' :=
⟨f, λ x, by simp only [norm_eq_sqrt_inner, h]⟩
@[simp] lemma linear_map.coe_isometry_of_inner (f : E →ₗ[𝕜] E') (h) :
⇑(f.isometry_of_inner h) = f := rfl
@[simp] lemma linear_map.isometry_of_inner_to_linear_map (f : E →ₗ[𝕜] E') (h) :
(f.isometry_of_inner h).to_linear_map = f := rfl
/-- A linear equivalence that preserves the inner product is a linear isometric equivalence. -/
def linear_equiv.isometry_of_inner (f : E ≃ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) :
E ≃ₗᵢ[𝕜] E' :=
⟨f, ((f : E →ₗ[𝕜] E').isometry_of_inner h).norm_map⟩
@[simp] lemma linear_equiv.coe_isometry_of_inner (f : E ≃ₗ[𝕜] E') (h) :
⇑(f.isometry_of_inner h) = f := rfl
@[simp] lemma linear_equiv.isometry_of_inner_to_linear_equiv (f : E ≃ₗ[𝕜] E') (h) :
(f.isometry_of_inner h).to_linear_equiv = f := rfl
end
/-- Polarization identity: The real inner product, in terms of the norm. -/
lemma real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) :
⟪x, y⟫_ℝ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 :=
re_to_real.symm.trans $
re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two x y
/-- Polarization identity: The real inner product, in terms of the norm. -/
lemma real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) :
⟪x, y⟫_ℝ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 :=
re_to_real.symm.trans $
re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two x y
/-- Pythagorean theorem, if-and-only-if vector inner product form. -/
lemma norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) :
∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 :=
begin
rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero],
norm_num
end
/-- Pythagorean theorem, vector inner product form. -/
lemma norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (x y : E) (h : ⟪x, y⟫ = 0) :
∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ :=
begin
rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero],
apply or.inr,
simp only [h, zero_re'],
end
/-- Pythagorean theorem, vector inner product form. -/
lemma norm_add_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) :
∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ :=
(norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h
/-- Pythagorean theorem, subtracting vectors, if-and-only-if vector
inner product form. -/
lemma norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) :
∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 :=
begin
rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero,
mul_eq_zero],
norm_num
end
/-- Pythagorean theorem, subtracting vectors, vector inner product
form. -/
lemma norm_sub_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) :
∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ :=
(norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h
/-- The sum and difference of two vectors are orthogonal if and only
if they have the same norm. -/
lemma real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ∥x∥ = ∥y∥ :=
begin
conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) },
simp only [←inner_self_eq_norm_sq, inner_add_left, inner_sub_right,
real_inner_comm y x, sub_eq_zero, re_to_real],
split,
{ intro h,
rw [add_comm] at h,
linarith },
{ intro h,
linarith }
end
/-- The real inner product of two vectors, divided by the product of their
norms, has absolute value at most 1. -/
lemma abs_real_inner_div_norm_mul_norm_le_one (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) ≤ 1 :=
begin
rw _root_.abs_div,
by_cases h : 0 = absR (∥x∥ * ∥y∥),
{ rw [←h, div_zero],
norm_num },
{ change 0 ≠ absR (∥x∥ * ∥y∥) at h,
rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (_root_.abs_nonneg (∥x∥ * ∥y∥))) h),
convert abs_real_inner_le_norm x y using 1,
rw [_root_.abs_mul, _root_.abs_of_nonneg (norm_nonneg x), _root_.abs_of_nonneg (norm_nonneg y),
mul_one] }
end
/-- The inner product of a vector with a multiple of itself. -/
lemma real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (∥x∥ * ∥x∥) :=
by rw [real_inner_smul_left, ←real_inner_self_eq_norm_sq]
/-- The inner product of a vector with a multiple of itself. -/
lemma real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (∥x∥ * ∥x∥) :=
by rw [inner_smul_right, ←real_inner_self_eq_norm_sq]
/-- The inner product of a nonzero vector with a nonzero multiple of
itself, divided by the product of their norms, has absolute value
1. -/
lemma abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul
{x : E} {r : 𝕜} (hx : x ≠ 0) (hr : r ≠ 0) : abs ⟪x, r • x⟫ / (∥x∥ * ∥r • x∥) = 1 :=
begin
have hx' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx],
have hr' : abs r ≠ 0 := by simp [is_R_or_C.abs_eq_zero, hr],
rw [inner_smul_right, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_sq,
norm_smul],
rw [is_R_or_C.norm_eq_abs, ←mul_assoc, ←div_div_eq_div_mul, mul_div_cancel _ hx',
←div_div_eq_div_mul, mul_comm, mul_div_cancel _ hr', div_self hx'],
end
/-- The inner product of a nonzero vector with a nonzero multiple of
itself, divided by the product of their norms, has absolute value
1. -/
lemma abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul
{x : F} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : absR ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 :=
begin
rw ← abs_to_real,
exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr
end
/-- The inner product of a nonzero vector with a positive multiple of
itself, divided by the product of their norms, has value 1. -/
lemma real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul
{x : F} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 :=
begin
rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r),
mul_assoc, _root_.abs_of_nonneg (le_of_lt hr), div_self],
exact mul_ne_zero (ne_of_gt hr)
(λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h)))
end
/-- The inner product of a nonzero vector with a negative multiple of
itself, divided by the product of their norms, has value -1. -/
lemma real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul
{x : F} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = -1 :=
begin
rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r),
mul_assoc, abs_of_neg hr, ←neg_mul_eq_neg_mul, div_neg_eq_neg_div, div_self],
exact mul_ne_zero (ne_of_lt hr)
(λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h)))
end
/-- The inner product of two vectors, divided by the product of their
norms, has absolute value 1 if and only if they are nonzero and one is
a multiple of the other. One form of equality case for Cauchy-Schwarz. -/
lemma abs_inner_div_norm_mul_norm_eq_one_iff (x y : E) :
abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x) :=
begin
split,
{ intro h,
have hx0 : x ≠ 0,
{ intro hx0,
rw [hx0, inner_zero_left, zero_div] at h,
norm_num at h, },
refine and.intro hx0 _,
set r := ⟪x, y⟫ / (∥x∥ * ∥x∥) with hr,
use r,
set t := y - r • x with ht,
have ht0 : ⟪x, t⟫ = 0,
{ rw [ht, inner_sub_right, inner_smul_right, hr],
norm_cast,
rw [←inner_self_eq_norm_sq, inner_self_re_to_K,
div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] },
replace h : ∥r • x∥ / ∥t + r • x∥ = 1,
{ rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right,
is_R_or_C.abs_div, is_R_or_C.abs_mul, ←inner_self_re_abs,
inner_self_eq_norm_sq] at h,
norm_cast at h,
rwa [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, ←mul_assoc, mul_comm,
mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), ←is_R_or_C.norm_eq_abs,
←norm_smul] at h },
have hr0 : r ≠ 0,
{ intro hr0,
rw [hr0, zero_smul, norm_zero, zero_div] at h,
norm_num at h },
refine and.intro hr0 _,
have h2 : ∥r • x∥ ^ 2 = ∥t + r • x∥ ^ 2,
{ rw [eq_of_div_eq_one h] },
replace h2 : ⟪r • x, r • x⟫ = ⟪t, t⟫ + ⟪t, r • x⟫ + ⟪r • x, t⟫ + ⟪r • x, r • x⟫,
{ rw [sq, sq, ←inner_self_eq_norm_sq, ←inner_self_eq_norm_sq ] at h2,
have h2' := congr_arg (λ z : ℝ, (z : 𝕜)) h2,
simp_rw [inner_self_re_to_K, inner_add_add_self] at h2',
exact h2' },
conv at h2 in ⟪r • x, t⟫ { rw [inner_smul_left, ht0, mul_zero] },
symmetry' at h2,
have h₁ : ⟪t, r • x⟫ = 0 := by { rw [inner_smul_right, ←inner_conj_sym, ht0], simp },
rw [add_zero, h₁, add_left_eq_self, add_zero, inner_self_eq_zero] at h2,
rw h2 at ht,
exact eq_of_sub_eq_zero ht.symm },
{ intro h,
rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩,
rw [hy, is_R_or_C.abs_div],
norm_cast,
rw [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm],
exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr }
end
/-- The inner product of two vectors, divided by the product of their
norms, has absolute value 1 if and only if they are nonzero and one is
a multiple of the other. One form of equality case for Cauchy-Schwarz. -/
lemma abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) :
absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) :=
begin
have := @abs_inner_div_norm_mul_norm_eq_one_iff ℝ F _ _ x y,
simpa [coe_real_eq_id] using this,
end
/--
If the inner product of two vectors is equal to the product of their norms, then the two vectors
are multiples of each other. One form of the equality case for Cauchy-Schwarz.
Compare `inner_eq_norm_mul_iff`, which takes the stronger hypothesis `⟪x, y⟫ = ∥x∥ * ∥y∥`. -/
lemma abs_inner_eq_norm_iff (x y : E) (hx0 : x ≠ 0) (hy0 : y ≠ 0):
abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x :=
begin
have hx0' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx0],
have hy0' : ∥y∥ ≠ 0 := by simp [norm_eq_zero, hy0],
have hxy0 : ∥x∥ * ∥y∥ ≠ 0 := by simp [hx0', hy0'],
have h₁ : abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1,
{ refine ⟨_ ,_⟩,
{ intro h,
norm_cast,
rw [is_R_or_C.abs_div, h, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm],
exact div_self hxy0 },
{ intro h,
norm_cast at h,
rwa [is_R_or_C.abs_div, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm,
div_eq_one_iff_eq hxy0] at h } },
rw [h₁, abs_inner_div_norm_mul_norm_eq_one_iff x y],
have : x ≠ 0 := λ h, (hx0' $ norm_eq_zero.mpr h),
simp [this]
end
/-- The inner product of two vectors, divided by the product of their
norms, has value 1 if and only if they are nonzero and one is
a positive multiple of the other. -/
lemma real_inner_div_norm_mul_norm_eq_one_iff (x y : F) :
⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) :=
begin
split,
{ intro h,
have ha := h,
apply_fun absR at ha,
norm_num at ha,
rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩,
use [hx, r],
refine and.intro _ hy,
by_contradiction hrneg,
rw hy at h,
rw real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx
(lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h,
norm_num at h },
{ intro h,
rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩,
rw hy,
exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr }
end
/-- The inner product of two vectors, divided by the product of their
norms, has value -1 if and only if they are nonzero and one is
a negative multiple of the other. -/
lemma real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) :
⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) :=
begin
split,
{ intro h,
have ha := h,
apply_fun absR at ha,
norm_num at ha,
rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩,
use [hx, r],
refine and.intro _ hy,
by_contradiction hrpos,
rw hy at h,
rw real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx
(lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h,
norm_num at h },
{ intro h,
rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩,
rw hy,
exact real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr }
end
/-- If the inner product of two vectors is equal to the product of their norms (i.e.,
`⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form
of the equality case for Cauchy-Schwarz.
Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/
lemma inner_eq_norm_mul_iff {x y : E} :
⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y :=
begin
by_cases h : (x = 0 ∨ y = 0), -- WLOG `x` and `y` are nonzero
{ cases h; simp [h] },
calc ⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ ∥x∥ * ∥y∥ = re ⟪x, y⟫ :
begin
norm_cast,
split,
{ intros h',
simp [h'] },
{ have cauchy_schwarz := abs_inner_le_norm x y,
intros h',
rw h' at ⊢ cauchy_schwarz,
rwa re_eq_self_of_le }
end
... ↔ 2 * ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥ - re ⟪x, y⟫) = 0 :
by simp [h, show (2:ℝ) ≠ 0, by norm_num, sub_eq_zero]
... ↔ ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ * ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ = 0 :
begin
simp only [norm_sub_mul_self, inner_smul_left, inner_smul_right, norm_smul, conj_of_real,
is_R_or_C.norm_eq_abs, abs_of_real, of_real_im, of_real_re, mul_re, abs_norm_eq_norm],
refine eq.congr _ rfl,
ring
end
... ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y : by simp [norm_sub_eq_zero_iff]
end
/-- If the inner product of two vectors is equal to the product of their norms (i.e.,
`⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form
of the equality case for Cauchy-Schwarz.
Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/
lemma inner_eq_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ = ∥x∥ * ∥y∥ ↔ ∥y∥ • x = ∥x∥ • y :=
inner_eq_norm_mul_iff
/-- If the inner product of two unit vectors is `1`, then the two vectors are equal. One form of
the equality case for Cauchy-Schwarz. -/
lemma inner_eq_norm_mul_iff_of_norm_one {x y : E} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) :
⟪x, y⟫ = 1 ↔ x = y :=
by { convert inner_eq_norm_mul_iff using 2; simp [hx, hy] }
lemma inner_lt_norm_mul_iff_real {x y : F} :
⟪x, y⟫_ℝ < ∥x∥ * ∥y∥ ↔ ∥y∥ • x ≠ ∥x∥ • y :=
calc ⟪x, y⟫_ℝ < ∥x∥ * ∥y∥
↔ ⟪x, y⟫_ℝ ≠ ∥x∥ * ∥y∥ : ⟨ne_of_lt, lt_of_le_of_ne (real_inner_le_norm _ _)⟩
... ↔ ∥y∥ • x ≠ ∥x∥ • y : not_congr inner_eq_norm_mul_iff_real
/-- If the inner product of two unit vectors is strictly less than `1`, then the two vectors are
distinct. One form of the equality case for Cauchy-Schwarz. -/
lemma inner_lt_one_iff_real_of_norm_one {x y : F} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) :
⟪x, y⟫_ℝ < 1 ↔ x ≠ y :=
by { convert inner_lt_norm_mul_iff_real; simp [hx, hy] }
/-- The inner product of two weighted sums, where the weights in each
sum add to 0, in terms of the norms of pairwise differences. -/
lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ}
(v₁ : ι₁ → F) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ}
(v₂ : ι₂ → F) (h₂ : ∑ i in s₂, w₂ i = 0) :
⟪(∑ i₁ in s₁, w₁ i₁ • v₁ i₁), (∑ i₂ in s₂, w₂ i₂ • v₂ i₂)⟫_ℝ =
(-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (∥v₁ i₁ - v₂ i₂∥ * ∥v₁ i₁ - v₂ i₂∥)) / 2 :=
by simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right,
real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two,
←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib,
finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul,
h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum,
neg_div, finset.sum_div, mul_div_assoc, mul_assoc]
/-- The inner product with a fixed left element, as a continuous linear map. This can be upgraded
to a continuous map which is jointly conjugate-linear in the left argument and linear in the right
argument, once (TODO) conjugate-linear maps have been defined. -/
def inner_right (v : E) : E →L[𝕜] 𝕜 :=
linear_map.mk_continuous
{ to_fun := λ w, ⟪v, w⟫,
map_add' := λ x y, inner_add_right,
map_smul' := λ c x, inner_smul_right }
∥v∥
(by simpa [is_R_or_C.norm_eq_abs] using abs_inner_le_norm v)
@[simp] lemma inner_right_coe (v : E) : (inner_right v : E → 𝕜) = λ w, ⟪v, w⟫ := rfl
@[simp] lemma inner_right_apply (v w : E) : inner_right v w = ⟪v, w⟫ := rfl
end norm
/-! ### Inner product space structure on product spaces -/
/-
If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space,
then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm,
we use instead `pi_Lp 2 one_le_two f` for the product space, which is endowed with the `L^2` norm.
-/
instance pi_Lp.inner_product_space {ι : Type*} [fintype ι] (f : ι → Type*)
[Π i, inner_product_space 𝕜 (f i)] : inner_product_space 𝕜 (pi_Lp 2 one_le_two f) :=
{ inner := λ x y, ∑ i, inner (x i) (y i),
norm_sq_eq_inner :=
begin
intro x,
have h₁ : ∑ (i : ι), ∥x i∥ ^ (2 : ℕ) = ∑ (i : ι), ∥x i∥ ^ (2 : ℝ),
{ apply finset.sum_congr rfl,
intros j hj,
simp [←rpow_nat_cast] },
have h₂ : 0 ≤ ∑ (i : ι), ∥x i∥ ^ (2 : ℝ),
{ rw [←h₁],
exact finset.sum_nonneg (λ j (hj : j ∈ finset.univ), pow_nonneg (norm_nonneg (x j)) 2) },
simp [norm, add_monoid_hom.map_sum, ←norm_sq_eq_inner],
rw [←rpow_nat_cast ((∑ (i : ι), ∥x i∥ ^ (2 : ℝ)) ^ (2 : ℝ)⁻¹) 2],
rw [←rpow_mul h₂],
norm_num [h₁],
end,
conj_sym :=
begin
intros x y,
unfold inner,
rw [←finset.sum_hom finset.univ conj],
apply finset.sum_congr rfl,
rintros z -,
apply inner_conj_sym,
apply_instance
end,
add_left := λ x y z,
show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i),
by simp only [inner_add_left, finset.sum_add_distrib],
smul_left := λ x y r,
show ∑ (i : ι), inner (r • x i) (y i) = (conj r) * ∑ i, inner (x i) (y i),
by simp only [finset.mul_sum, inner_smul_left]
}
@[simp] lemma pi_Lp.inner_apply {ι : Type*} [fintype ι] {f : ι → Type*}
[Π i, inner_product_space 𝕜 (f i)] (x y : pi_Lp 2 one_le_two f) :
⟪x, y⟫ = ∑ i, ⟪x i, y i⟫ :=
rfl
lemma pi_Lp.norm_eq_of_L2 {ι : Type*} [fintype ι] {f : ι → Type*}
[Π i, inner_product_space 𝕜 (f i)] (x : pi_Lp 2 one_le_two f) :
∥x∥ = sqrt (∑ (i : ι), ∥x i∥ ^ 2) :=
by { rw [pi_Lp.norm_eq_of_nat 2]; simp [sqrt_eq_rpow] }
/-- A field `𝕜` satisfying `is_R_or_C` is itself a `𝕜`-inner product space. -/
instance is_R_or_C.inner_product_space : inner_product_space 𝕜 𝕜 :=
{ inner := (λ x y, (conj x) * y),
norm_sq_eq_inner := λ x,
by { unfold inner, rw [mul_comm, mul_conj, of_real_re, norm_sq_eq_def'] },
conj_sym := λ x y, by simp [mul_comm],
add_left := λ x y z, by simp [inner, add_mul],
smul_left := λ x y z, by simp [inner, mul_assoc] }
@[simp] lemma is_R_or_C.inner_apply (x y : 𝕜) : ⟪x, y⟫ = (conj x) * y := rfl
/-- The standard real/complex Euclidean space, functions on a finite type. For an `n`-dimensional
space use `euclidean_space 𝕜 (fin n)`. -/
@[reducible, nolint unused_arguments]
def euclidean_space (𝕜 : Type*) [is_R_or_C 𝕜]
(n : Type*) [fintype n] : Type* := pi_Lp 2 one_le_two (λ (i : n), 𝕜)
lemma euclidean_space.norm_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n]
(x : euclidean_space 𝕜 n) : ∥x∥ = real.sqrt (∑ (i : n), ∥x i∥ ^ 2) :=
pi_Lp.norm_eq_of_L2 x
/-! ### Inner product space structure on subspaces -/
/-- Induced inner product on a submodule. -/
instance submodule.inner_product_space (W : submodule 𝕜 E) : inner_product_space 𝕜 W :=
{ inner := λ x y, ⟪(x:E), (y:E)⟫,
conj_sym := λ _ _, inner_conj_sym _ _ ,
norm_sq_eq_inner := λ _, norm_sq_eq_inner _,
add_left := λ _ _ _ , inner_add_left,
smul_left := λ _ _ _, inner_smul_left,
..submodule.normed_space W }
/-- The inner product on submodules is the same as on the ambient space. -/
@[simp] lemma submodule.coe_inner (W : submodule 𝕜 E) (x y : W) : ⟪x, y⟫ = ⟪(x:E), ↑y⟫ := rfl
section is_R_or_C_to_real
variables {G : Type*}
variables (𝕜 E)
include 𝕜
/-- A general inner product implies a real inner product. This is not registered as an instance
since it creates problems with the case `𝕜 = ℝ`. -/
def has_inner.is_R_or_C_to_real : has_inner ℝ E :=
{ inner := λ x y, re ⟪x, y⟫ }
/-- A general inner product space structure implies a real inner product structure. This is not
registered as an instance since it creates problems with the case `𝕜 = ℝ`, but in can be used in a
proof to obtain a real inner product space structure from a given `𝕜`-inner product space
structure. -/
def inner_product_space.is_R_or_C_to_real : inner_product_space ℝ E :=
{ norm_sq_eq_inner := norm_sq_eq_inner,
conj_sym := λ x y, inner_re_symm,
add_left := λ x y z, by {
change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫,
simp [inner_add_left] },
smul_left := λ x y r, by {
change re ⟪(r : 𝕜) • x, y⟫ = r * re ⟪x, y⟫,
simp [inner_smul_left] },
..has_inner.is_R_or_C_to_real 𝕜 E,
..normed_space.restrict_scalars ℝ 𝕜 E }
variable {E}
lemma real_inner_eq_re_inner (x y : E) :
@has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x y = re ⟪x, y⟫ := rfl
omit 𝕜
/-- A complex inner product implies a real inner product -/
instance inner_product_space.complex_to_real [inner_product_space ℂ G] : inner_product_space ℝ G :=
inner_product_space.is_R_or_C_to_real ℂ G
end is_R_or_C_to_real
section deriv
/-!
### Derivative of the inner product
In this section we prove that the inner product and square of the norm in an inner space are
infinitely `ℝ`-smooth. In order to state these results, we need a `normed_space ℝ E`
instance. Though we can deduce this structure from `inner_product_space 𝕜 E`, this instance may be
not definitionally equal to some other “natural” instance. So, we assume `[normed_space ℝ E]` and
`[is_scalar_tower ℝ 𝕜 E]`. In both interesting cases `𝕜 = ℝ` and `𝕜 = ℂ` we have these instances.
-/
variables [normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E]
lemma is_bounded_bilinear_map_inner : is_bounded_bilinear_map ℝ (λ p : E × E, ⟪p.1, p.2⟫) :=
{ add_left := λ _ _ _, inner_add_left,
smul_left := λ r x y,
by simp only [← algebra_map_smul 𝕜 r x, algebra_map_eq_of_real, inner_smul_real_left],
add_right := λ _ _ _, inner_add_right,
smul_right := λ r x y,
by simp only [← algebra_map_smul 𝕜 r y, algebra_map_eq_of_real, inner_smul_real_right],
bound := ⟨1, zero_lt_one, λ x y,
by { rw [one_mul, is_R_or_C.norm_eq_abs], exact abs_inner_le_norm x y, }⟩ }
/-- Derivative of the inner product. -/
def fderiv_inner_clm (p : E × E) : E × E →L[ℝ] 𝕜 := is_bounded_bilinear_map_inner.deriv p
@[simp] lemma fderiv_inner_clm_apply (p x : E × E) :
fderiv_inner_clm p x = ⟪p.1, x.2⟫ + ⟪x.1, p.2⟫ := rfl
lemma times_cont_diff_inner {n} : times_cont_diff ℝ n (λ p : E × E, ⟪p.1, p.2⟫) :=
is_bounded_bilinear_map_inner.times_cont_diff
lemma times_cont_diff_at_inner {p : E × E} {n} :
times_cont_diff_at ℝ n (λ p : E × E, ⟪p.1, p.2⟫) p :=
times_cont_diff_inner.times_cont_diff_at
lemma differentiable_inner : differentiable ℝ (λ p : E × E, ⟪p.1, p.2⟫) :=
is_bounded_bilinear_map_inner.differentiable_at
variables {G : Type*} [normed_group G] [normed_space ℝ G]
{f g : G → E} {f' g' : G →L[ℝ] E} {s : set G} {x : G} {n : with_top ℕ}
include 𝕜
lemma times_cont_diff_within_at.inner (hf : times_cont_diff_within_at ℝ n f s x)
(hg : times_cont_diff_within_at ℝ n g s x) :
times_cont_diff_within_at ℝ n (λ x, ⟪f x, g x⟫) s x :=
times_cont_diff_at_inner.comp_times_cont_diff_within_at x (hf.prod hg)
lemma times_cont_diff_at.inner (hf : times_cont_diff_at ℝ n f x)
(hg : times_cont_diff_at ℝ n g x) :
times_cont_diff_at ℝ n (λ x, ⟪f x, g x⟫) x :=
hf.inner hg
lemma times_cont_diff_on.inner (hf : times_cont_diff_on ℝ n f s) (hg : times_cont_diff_on ℝ n g s) :
times_cont_diff_on ℝ n (λ x, ⟪f x, g x⟫) s :=
λ x hx, (hf x hx).inner (hg x hx)
lemma times_cont_diff.inner (hf : times_cont_diff ℝ n f) (hg : times_cont_diff ℝ n g) :
times_cont_diff ℝ n (λ x, ⟪f x, g x⟫) :=
times_cont_diff_inner.comp (hf.prod hg)
lemma has_fderiv_within_at.inner (hf : has_fderiv_within_at f f' s x)
(hg : has_fderiv_within_at g g' s x) :
has_fderiv_within_at (λ t, ⟪f t, g t⟫) ((fderiv_inner_clm (f x, g x)).comp $ f'.prod g') s x :=
(is_bounded_bilinear_map_inner.has_fderiv_at (f x, g x)).comp_has_fderiv_within_at x (hf.prod hg)
lemma has_fderiv_at.inner (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) :
has_fderiv_at (λ t, ⟪f t, g t⟫) ((fderiv_inner_clm (f x, g x)).comp $ f'.prod g') x :=
(is_bounded_bilinear_map_inner.has_fderiv_at (f x, g x)).comp x (hf.prod hg)
lemma has_deriv_within_at.inner {f g : ℝ → E} {f' g' : E} {s : set ℝ} {x : ℝ}
(hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) :
has_deriv_within_at (λ t, ⟪f t, g t⟫) (⟪f x, g'⟫ + ⟪f', g x⟫) s x :=
by simpa using (hf.has_fderiv_within_at.inner hg.has_fderiv_within_at).has_deriv_within_at
lemma has_deriv_at.inner {f g : ℝ → E} {f' g' : E} {x : ℝ} :
has_deriv_at f f' x → has_deriv_at g g' x →
has_deriv_at (λ t, ⟪f t, g t⟫) (⟪f x, g'⟫ + ⟪f', g x⟫) x :=
by simpa only [← has_deriv_within_at_univ] using has_deriv_within_at.inner
lemma differentiable_within_at.inner (hf : differentiable_within_at ℝ f s x)
(hg : differentiable_within_at ℝ g s x) :
differentiable_within_at ℝ (λ x, ⟪f x, g x⟫) s x :=
((differentiable_inner _).has_fderiv_at.comp_has_fderiv_within_at x
(hf.prod hg).has_fderiv_within_at).differentiable_within_at
lemma differentiable_at.inner (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) :
differentiable_at ℝ (λ x, ⟪f x, g x⟫) x :=
(differentiable_inner _).comp x (hf.prod hg)
lemma differentiable_on.inner (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) :
differentiable_on ℝ (λ x, ⟪f x, g x⟫) s :=
λ x hx, (hf x hx).inner (hg x hx)
lemma differentiable.inner (hf : differentiable ℝ f) (hg : differentiable ℝ g) :
differentiable ℝ (λ x, ⟪f x, g x⟫) :=
λ x, (hf x).inner (hg x)
lemma fderiv_inner_apply (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) (y : G) :
fderiv ℝ (λ t, ⟪f t, g t⟫) x y = ⟪f x, fderiv ℝ g x y⟫ + ⟪fderiv ℝ f x y, g x⟫ :=
by { rw [(hf.has_fderiv_at.inner hg.has_fderiv_at).fderiv], refl }
lemma deriv_inner_apply {f g : ℝ → E} {x : ℝ} (hf : differentiable_at ℝ f x)
(hg : differentiable_at ℝ g x) :
deriv (λ t, ⟪f t, g t⟫) x = ⟪f x, deriv g x⟫ + ⟪deriv f x, g x⟫ :=
(hf.has_deriv_at.inner hg.has_deriv_at).deriv
lemma times_cont_diff_norm_sq : times_cont_diff ℝ n (λ x : E, ∥x∥ ^ 2) :=
begin
simp only [sq, ← inner_self_eq_norm_sq],
exact (re_clm : 𝕜 →L[ℝ] ℝ).times_cont_diff.comp (times_cont_diff_id.inner times_cont_diff_id)
end
lemma times_cont_diff.norm_sq (hf : times_cont_diff ℝ n f) :
times_cont_diff ℝ n (λ x, ∥f x∥ ^ 2) :=
times_cont_diff_norm_sq.comp hf
lemma times_cont_diff_within_at.norm_sq (hf : times_cont_diff_within_at ℝ n f s x) :
times_cont_diff_within_at ℝ n (λ y, ∥f y∥ ^ 2) s x :=
times_cont_diff_norm_sq.times_cont_diff_at.comp_times_cont_diff_within_at x hf
lemma times_cont_diff_at.norm_sq (hf : times_cont_diff_at ℝ n f x) :
times_cont_diff_at ℝ n (λ y, ∥f y∥ ^ 2) x :=
hf.norm_sq
lemma times_cont_diff_at_norm {x : E} (hx : x ≠ 0) : times_cont_diff_at ℝ n norm x :=
have ∥id x∥ ^ 2 ≠ 0, from pow_ne_zero _ (norm_pos_iff.2 hx).ne',
by simpa only [id, sqrt_sq, norm_nonneg] using times_cont_diff_at_id.norm_sq.sqrt this
lemma times_cont_diff_at.norm (hf : times_cont_diff_at ℝ n f x) (h0 : f x ≠ 0) :
times_cont_diff_at ℝ n (λ y, ∥f y∥) x :=
(times_cont_diff_at_norm h0).comp x hf
lemma times_cont_diff_at.dist (hf : times_cont_diff_at ℝ n f x) (hg : times_cont_diff_at ℝ n g x)
(hne : f x ≠ g x) :
times_cont_diff_at ℝ n (λ y, dist (f y) (g y)) x :=
by { simp only [dist_eq_norm], exact (hf.sub hg).norm (sub_ne_zero.2 hne) }
lemma times_cont_diff_within_at.norm (hf : times_cont_diff_within_at ℝ n f s x) (h0 : f x ≠ 0) :
times_cont_diff_within_at ℝ n (λ y, ∥f y∥) s x :=
(times_cont_diff_at_norm h0).comp_times_cont_diff_within_at x hf
lemma times_cont_diff_within_at.dist (hf : times_cont_diff_within_at ℝ n f s x)
(hg : times_cont_diff_within_at ℝ n g s x) (hne : f x ≠ g x) :
times_cont_diff_within_at ℝ n (λ y, dist (f y) (g y)) s x :=
by { simp only [dist_eq_norm], exact (hf.sub hg).norm (sub_ne_zero.2 hne) }
lemma times_cont_diff_on.norm_sq (hf : times_cont_diff_on ℝ n f s) :
times_cont_diff_on ℝ n (λ y, ∥f y∥ ^ 2) s :=
(λ x hx, (hf x hx).norm_sq)
lemma times_cont_diff_on.norm (hf : times_cont_diff_on ℝ n f s) (h0 : ∀ x ∈ s, f x ≠ 0) :
times_cont_diff_on ℝ n (λ y, ∥f y∥) s :=
λ x hx, (hf x hx).norm (h0 x hx)
lemma times_cont_diff_on.dist (hf : times_cont_diff_on ℝ n f s)
(hg : times_cont_diff_on ℝ n g s) (hne : ∀ x ∈ s, f x ≠ g x) :
times_cont_diff_on ℝ n (λ y, dist (f y) (g y)) s :=
λ x hx, (hf x hx).dist (hg x hx) (hne x hx)
lemma times_cont_diff.norm (hf : times_cont_diff ℝ n f) (h0 : ∀ x, f x ≠ 0) :
times_cont_diff ℝ n (λ y, ∥f y∥) :=
times_cont_diff_iff_times_cont_diff_at.2 $ λ x, hf.times_cont_diff_at.norm (h0 x)
lemma times_cont_diff.dist (hf : times_cont_diff ℝ n f) (hg : times_cont_diff ℝ n g)
(hne : ∀ x, f x ≠ g x) :
times_cont_diff ℝ n (λ y, dist (f y) (g y)) :=
times_cont_diff_iff_times_cont_diff_at.2 $
λ x, hf.times_cont_diff_at.dist hg.times_cont_diff_at (hne x)
lemma differentiable_at.norm_sq (hf : differentiable_at ℝ f x) :
differentiable_at ℝ (λ y, ∥f y∥ ^ 2) x :=
(times_cont_diff_at_id.norm_sq.differentiable_at le_rfl).comp x hf
lemma differentiable_at.norm (hf : differentiable_at ℝ f x) (h0 : f x ≠ 0) :
differentiable_at ℝ (λ y, ∥f y∥) x :=
((times_cont_diff_at_norm h0).differentiable_at le_rfl).comp x hf
lemma differentiable_at.dist (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x)
(hne : f x ≠ g x) :
differentiable_at ℝ (λ y, dist (f y) (g y)) x :=
by { simp only [dist_eq_norm], exact (hf.sub hg).norm (sub_ne_zero.2 hne) }
lemma differentiable.norm_sq (hf : differentiable ℝ f) : differentiable ℝ (λ y, ∥f y∥ ^ 2) :=
λ x, (hf x).norm_sq
lemma differentiable.norm (hf : differentiable ℝ f) (h0 : ∀ x, f x ≠ 0) :
differentiable ℝ (λ y, ∥f y∥) :=
λ x, (hf x).norm (h0 x)
lemma differentiable.dist (hf : differentiable ℝ f) (hg : differentiable ℝ g)
(hne : ∀ x, f x ≠ g x) :
differentiable ℝ (λ y, dist (f y) (g y)) :=
λ x, (hf x).dist (hg x) (hne x)
lemma differentiable_within_at.norm_sq (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ y, ∥f y∥ ^ 2) s x :=
(times_cont_diff_at_id.norm_sq.differentiable_at le_rfl).comp_differentiable_within_at x hf
lemma differentiable_within_at.norm (hf : differentiable_within_at ℝ f s x) (h0 : f x ≠ 0) :
differentiable_within_at ℝ (λ y, ∥f y∥) s x :=
((times_cont_diff_at_id.norm h0).differentiable_at le_rfl).comp_differentiable_within_at x hf
lemma differentiable_within_at.dist (hf : differentiable_within_at ℝ f s x)
(hg : differentiable_within_at ℝ g s x) (hne : f x ≠ g x) :
differentiable_within_at ℝ (λ y, dist (f y) (g y)) s x :=
by { simp only [dist_eq_norm], exact (hf.sub hg).norm (sub_ne_zero.2 hne) }
lemma differentiable_on.norm_sq (hf : differentiable_on ℝ f s) :
differentiable_on ℝ (λ y, ∥f y∥ ^ 2) s :=
λ x hx, (hf x hx).norm_sq
lemma differentiable_on.norm (hf : differentiable_on ℝ f s) (h0 : ∀ x ∈ s, f x ≠ 0) :
differentiable_on ℝ (λ y, ∥f y∥) s :=
λ x hx, (hf x hx).norm (h0 x hx)
lemma differentiable_on.dist (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s)
(hne : ∀ x ∈ s, f x ≠ g x) :
differentiable_on ℝ (λ y, dist (f y) (g y)) s :=
λ x hx, (hf x hx).dist (hg x hx) (hne x hx)
end deriv
section continuous
/-!
### Continuity and measurability of the inner product
Since the inner product is `ℝ`-smooth, it is continuous. We do not need a `[normed_space ℝ E]`
structure to *state* this fact and its corollaries, so we introduce them in the proof instead.
-/
lemma continuous_inner : continuous (λ p : E × E, ⟪p.1, p.2⟫) :=
begin
letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E,
letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _,
exact differentiable_inner.continuous
end
variables {α : Type*}
lemma filter.tendsto.inner {f g : α → E} {l : filter α} {x y : E} (hf : tendsto f l (𝓝 x))
(hg : tendsto g l (𝓝 y)) :
tendsto (λ t, ⟪f t, g t⟫) l (𝓝 ⟪x, y⟫) :=
(continuous_inner.tendsto _).comp (hf.prod_mk_nhds hg)
lemma measurable.inner [measurable_space α] [measurable_space E] [opens_measurable_space E]
[topological_space.second_countable_topology E] [measurable_space 𝕜] [borel_space 𝕜]
{f g : α → E} (hf : measurable f) (hg : measurable g) :
measurable (λ t, ⟪f t, g t⟫) :=
continuous.measurable2 continuous_inner hf hg
lemma ae_measurable.inner [measurable_space α] [measurable_space E] [opens_measurable_space E]
[topological_space.second_countable_topology E] [measurable_space 𝕜] [borel_space 𝕜]
{μ : measure_theory.measure α} {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) :
ae_measurable (λ x, ⟪f x, g x⟫) μ :=
begin
refine ⟨λ x, ⟪hf.mk f x, hg.mk g x⟫, hf.measurable_mk.inner hg.measurable_mk, _⟩,
refine hf.ae_eq_mk.mp (hg.ae_eq_mk.mono (λ x hxg hxf, _)),
dsimp only,
congr,
{ exact hxf, },
{ exact hxg, },
end
variables [topological_space α] {f g : α → E} {x : α} {s : set α}
include 𝕜
lemma continuous_within_at.inner (hf : continuous_within_at f s x)
(hg : continuous_within_at g s x) :
continuous_within_at (λ t, ⟪f t, g t⟫) s x :=
hf.inner hg
lemma continuous_at.inner (hf : continuous_at f x) (hg : continuous_at g x) :
continuous_at (λ t, ⟪f t, g t⟫) x :=
hf.inner hg
lemma continuous_on.inner (hf : continuous_on f s) (hg : continuous_on g s) :
continuous_on (λ t, ⟪f t, g t⟫) s :=
λ x hx, (hf x hx).inner (hg x hx)
lemma continuous.inner (hf : continuous f) (hg : continuous g) : continuous (λ t, ⟪f t, g t⟫) :=
continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.inner hg.continuous_at
end continuous
section pi_Lp
local attribute [reducible] pi_Lp
variables {ι : Type*} [fintype ι]
instance : finite_dimensional 𝕜 (euclidean_space 𝕜 ι) := by apply_instance
instance : inner_product_space 𝕜 (euclidean_space 𝕜 ι) := by apply_instance
@[simp] lemma finrank_euclidean_space :
finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 ι) = fintype.card ι := by simp
lemma finrank_euclidean_space_fin {n : ℕ} :
finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 (fin n)) = n := by simp
/-- An orthonormal basis on a fintype `ι` for an inner product space induces an isometry with
`euclidean_space 𝕜 ι`. -/
def is_basis.isometry_euclidean_of_orthonormal
{v : ι → E} (h : is_basis 𝕜 v) (hv : orthonormal 𝕜 v) :
E ≃ₗᵢ[𝕜] (euclidean_space 𝕜 ι) :=
h.equiv_fun.isometry_of_inner
begin
intros x y,
let p : euclidean_space 𝕜 ι := h.equiv_fun x,
let q : euclidean_space 𝕜 ι := h.equiv_fun y,
have key : ⟪p, q⟫ = ⟪∑ i, p i • v i, ∑ i, q i • v i⟫,
{ simp [sum_inner, inner_smul_left, hv.inner_right_fintype] },
convert key,
{ rw [← h.equiv_fun.symm_apply_apply x, h.equiv_fun_symm_apply] },
{ rw [← h.equiv_fun.symm_apply_apply y, h.equiv_fun_symm_apply] }
end
/-- `ℂ` is isometric to ℝ² with the Euclidean inner product. -/
def complex.isometry_euclidean : ℂ ≃ₗᵢ[ℝ] (euclidean_space ℝ (fin 2)) :=
complex.is_basis_one_I.isometry_euclidean_of_orthonormal
begin
rw orthonormal_iff_ite,
intros i, fin_cases i;
intros j; fin_cases j;
simp [real_inner_eq_re_inner]
end
@[simp] lemma complex.isometry_euclidean_symm_apply (x : euclidean_space ℝ (fin 2)) :
complex.isometry_euclidean.symm x = (x 0) + (x 1) * I :=
begin
convert complex.is_basis_one_I.equiv_fun_symm_apply x,
{ simpa },
{ simp },
end
lemma complex.isometry_euclidean_proj_eq_self (z : ℂ) :
↑(complex.isometry_euclidean z 0) + ↑(complex.isometry_euclidean z 1) * (I : ℂ) = z :=
by rw [← complex.isometry_euclidean_symm_apply (complex.isometry_euclidean z),
complex.isometry_euclidean.symm_apply_apply z]
@[simp] lemma complex.isometry_euclidean_apply_zero (z : ℂ) :
complex.isometry_euclidean z 0 = z.re :=
by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp }
@[simp] lemma complex.isometry_euclidean_apply_one (z : ℂ) :
complex.isometry_euclidean z 1 = z.im :=
by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp }
end pi_Lp
/-! ### Orthogonal projection in inner product spaces -/
section orthogonal
open filter
/--
Existence of minimizers
Let `u` be a point in a real inner product space, and let `K` be a nonempty complete convex subset.
Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`.
-/
-- FIXME this monolithic proof causes a deterministic timeout with `-T50000`
-- It should be broken in a sequence of more manageable pieces,
-- perhaps with individual statements for the three steps below.
theorem exists_norm_eq_infi_of_complete_convex {K : set F} (ne : K.nonempty) (h₁ : is_complete K)
(h₂ : convex K) : ∀ u : F, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u,
begin
let δ := ⨅ w : K, ∥u - w∥,
letI : nonempty K := ne.to_subtype,
have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _),
have δ_le : ∀ w : K, δ ≤ ∥u - w∥,
from cinfi_le ⟨0, set.forall_range_iff.2 $ λ _, norm_nonneg _⟩,
have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩,
-- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K`
-- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`);
-- maybe this should be a separate lemma
have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1),
{ have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from
λ n, lt_add_of_le_of_pos (le_refl _) nat.one_div_pos_of_nat,
have h := λ n, exists_lt_of_cinfi_lt (hδ n),
let w : ℕ → K := λ n, classical.some (h n),
exact ⟨w, λ n, classical.some_spec (h n)⟩ },
rcases exists_seq with ⟨w, hw⟩,
have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (nhds δ),
{ have h : tendsto (λ n:ℕ, δ) at_top (nhds δ) := tendsto_const_nhds,
have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (nhds δ),
{ convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] },
exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h'
(λ x, δ_le _) (λ x, le_of_lt (hw _)) },
-- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence
have seq_is_cauchy : cauchy_seq (λ n, ((w n):F)),
{ rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals
let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))),
use (λn, sqrt (b n)),
split,
-- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)`
assume n, exact sqrt_nonneg _,
split,
-- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)`
assume p q N hp hq,
let wp := ((w p):F), let wq := ((w q):F),
let a := u - wq, let b := u - wp,
let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1),
have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ =
2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) :=
calc
4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥
= (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring
... = (absR ((2:ℝ)) * ∥u - half•(wq + wp)∥) * (absR ((2:ℝ)) * ∥u - half•(wq+wp)∥) +
∥wp-wq∥*∥wp-wq∥ :
by { rw _root_.abs_of_nonneg, exact zero_le_two }
... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ +
∥wp-wq∥ * ∥wp-wq∥ :
by simp [norm_smul]
... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ :
begin
rw [smul_sub, smul_smul, mul_one_div_cancel (_root_.two_ne_zero : (2 : ℝ) ≠ 0),
← one_add_one_eq_two, add_smul],
simp only [one_smul],
have eq₁ : wp - wq = a - b, from (sub_sub_sub_cancel_left _ _ _).symm,
have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel,
rw [eq₁, eq₂],
end
... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm,
have eq : δ ≤ ∥u - half • (wq + wp)∥,
{ rw smul_add,
apply δ_le', apply h₂,
repeat {exact subtype.mem _},
repeat {exact le_of_lt one_half_pos},
exact add_halves 1 },
have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥,
{ mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _ },
have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) :=
mul_self_le_mul_self (norm_nonneg _)
(le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)),
have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) :=
mul_self_le_mul_self (norm_nonneg _)
(le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)),
rw dist_eq_norm,
apply nonneg_le_nonneg_of_sq_le_sq, { exact sqrt_nonneg _ },
rw mul_self_sqrt,
exact calc
∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) -
4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ : by { rw ← this, simp }
... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _
... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ :
sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _
... = 8 * δ * div + 4 * div * div : by ring,
exact add_nonneg
(mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat))
(mul_nonneg (mul_nonneg (by norm_num) nat.one_div_pos_of_nat.le) nat.one_div_pos_of_nat.le),
-- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)`
apply tendsto.comp,
{ convert continuous_sqrt.continuous_at, exact sqrt_zero.symm },
have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (nhds (0:ℝ)),
{ convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat,
simp only [mul_zero] },
have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (nhds (0:ℝ)),
{ convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat,
simp only [mul_zero] },
have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (nhds (0:ℝ)),
{ convert this.mul tendsto_one_div_add_at_top_nhds_0_nat,
simp only [mul_zero] },
convert eq₁.add eq₂, simp only [add_zero] },
-- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`.
-- Prove that it satisfies all requirements.
rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩,
use v, use hv,
have h_cont : continuous (λ v, ∥u - v∥) :=
continuous.comp continuous_norm (continuous.sub continuous_const continuous_id),
have : tendsto (λ n, ∥u - w n∥) at_top (nhds ∥u - v∥),
convert (tendsto.comp h_cont.continuous_at w_tendsto),
exact tendsto_nhds_unique this norm_tendsto,
exact subtype.mem _
end
/-- Characterization of minimizers for the projection on a convex set in a real inner product
space. -/
theorem norm_eq_infi_iff_real_inner_le_zero {K : set F} (h : convex K) {u : F} {v : F}
(hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0 :=
iff.intro
begin
assume eq w hw,
let δ := ⨅ w : K, ∥u - w∥, let p := ⟪u - v, w - v⟫_ℝ, let q := ∥w - v∥^2,
letI : nonempty K := ⟨⟨v, hv⟩⟩,
have zero_le_δ : 0 ≤ δ,
apply le_cinfi, intro, exact norm_nonneg _,
have δ_le : ∀ w : K, δ ≤ ∥u - w∥,
assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _,
have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩,
have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q,
assume θ hθ₁ hθ₂,
have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * ⟪u - v, w - v⟫_ℝ + θ*θ*∥w - v∥^2 :=
calc
∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 :
begin
simp only [sq], apply mul_self_le_mul_self (norm_nonneg _),
rw [eq], apply δ_le',
apply h hw hv,
exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _],
end
... = ∥(u - v) - θ • (w - v)∥^2 :
begin
have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v),
{ rw [smul_sub, sub_smul, one_smul],
simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] },
rw this
end
... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 :
begin
rw [norm_sub_sq, inner_smul_right, norm_smul],
simp only [sq],
show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+absR (θ)*∥w-v∥*(absR (θ)*∥w-v∥)=
∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥),
rw abs_of_pos hθ₁, ring
end,
have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)),
by abel,
rw [eq₁, le_add_iff_nonneg_right] at this,
have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring,
rw eq₂ at this,
have := le_of_sub_nonneg (nonneg_of_mul_nonneg_left this hθ₁),
exact this,
by_cases hq : q = 0,
{ rw hq at this,
have : p ≤ 0,
have := this (1:ℝ) (by norm_num) (by norm_num),
linarith,
exact this },
{ have q_pos : 0 < q,
apply lt_of_le_of_ne, exact sq_nonneg _, intro h, exact hq h.symm,
by_contradiction hp, rw not_le at hp,
let θ := min (1:ℝ) (p / q),
have eq₁ : θ*q ≤ p := calc
θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (sq_nonneg _)
... = p : div_mul_cancel _ hq,
have : 2 * p ≤ p := calc
2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) }
... ≤ p : eq₁,
linarith }
end
begin
assume h,
letI : nonempty K := ⟨⟨v, hv⟩⟩,
apply le_antisymm,
{ apply le_cinfi, assume w,
apply nonneg_le_nonneg_of_sq_le_sq (norm_nonneg _),
have := h w w.2,
exact calc
∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:F) - v) : by linarith
... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:F) - v) + ∥(w:F) - v∥^2 :
by { rw sq, refine le_add_of_nonneg_right _, exact sq_nonneg _ }
... = ∥(u - v) - (w - v)∥^2 : norm_sub_sq.symm
... = ∥u - w∥ * ∥u - w∥ :
by { have : (u - v) - (w - v) = u - w, abel, rw [this, sq] } },
{ show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩,
apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ }
end
variables (K : submodule 𝕜 E)
/--
Existence of projections on complete subspaces.
Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace.
Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`.
This point `v` is usually called the orthogonal projection of `u` onto `K`.
-/
theorem exists_norm_eq_infi_of_complete_subspace
(h : is_complete (↑K : set E)) : ∀ u : E, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (K : set E), ∥u - w∥ :=
begin
letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E,
letI : module ℝ E := restrict_scalars.module ℝ 𝕜 E,
letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _,
let K' : submodule ℝ E := submodule.restrict_scalars ℝ K,
exact exists_norm_eq_infi_of_complete_convex ⟨0, K'.zero_mem⟩ h K'.convex
end
/--
Characterization of minimizers in the projection on a subspace, in the real case.
Let `u` be a point in a real inner product space, and let `K` be a nonempty subspace.
Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if
for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`).
This is superceded by `norm_eq_infi_iff_inner_eq_zero` that gives the same conclusion over
any `is_R_or_C` field.
-/
theorem norm_eq_infi_iff_real_inner_eq_zero (K : submodule ℝ F) {u : F} {v : F}
(hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set F), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫_ℝ = 0 :=
iff.intro
begin
assume h,
have h : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0,
{ rwa [norm_eq_infi_iff_real_inner_le_zero] at h, exacts [K.convex, hv] },
assume w hw,
have le : ⟪u - v, w⟫_ℝ ≤ 0,
let w' := w + v,
have : w' ∈ K := submodule.add_mem _ hw hv,
have h₁ := h w' this,
have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg],
rw h₂ at h₁, exact h₁,
have ge : ⟪u - v, w⟫_ℝ ≥ 0,
let w'' := -w + v,
have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv,
have h₁ := h w'' this,
have h₂ : w'' - v = -w, simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg],
rw [h₂, inner_neg_right] at h₁,
linarith,
exact le_antisymm le ge
end
begin
assume h,
have : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0,
assume w hw,
let w' := w - v,
have : w' ∈ K := submodule.sub_mem _ hw hv,
have h₁ := h w' this,
exact le_of_eq h₁,
rwa norm_eq_infi_iff_real_inner_le_zero,
exacts [submodule.convex _, hv]
end
/--
Characterization of minimizers in the projection on a subspace.
Let `u` be a point in an inner product space, and let `K` be a nonempty subspace.
Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if
for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`)
-/
theorem norm_eq_infi_iff_inner_eq_zero {u : E} {v : E}
(hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set E), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫ = 0 :=
begin
letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E,
letI : module ℝ E := restrict_scalars.module ℝ 𝕜 E,
letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _,
let K' : submodule ℝ E := K.restrict_scalars ℝ,
split,
{ assume H,
have A : ∀ w ∈ K, re ⟪u - v, w⟫ = 0 := (norm_eq_infi_iff_real_inner_eq_zero K' hv).1 H,
assume w hw,
apply ext,
{ simp [A w hw] },
{ symmetry, calc
im (0 : 𝕜) = 0 : im.map_zero
... = re ⟪u - v, (-I) • w⟫ : (A _ (K.smul_mem (-I) hw)).symm
... = re ((-I) * ⟪u - v, w⟫) : by rw inner_smul_right
... = im ⟪u - v, w⟫ : by simp } },
{ assume H,
have : ∀ w ∈ K', ⟪u - v, w⟫_ℝ = 0,
{ assume w hw,
rw [real_inner_eq_re_inner, H w hw],
exact zero_re' },
exact (norm_eq_infi_iff_real_inner_eq_zero K' hv).2 this }
end
section orthogonal_projection
variables [complete_space K]
/-- The orthogonal projection onto a complete subspace, as an
unbundled function. This definition is only intended for use in
setting up the bundled version `orthogonal_projection` and should not
be used once that is defined. -/
def orthogonal_projection_fn (v : E) :=
(exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some
variables {K}
/-- The unbundled orthogonal projection is in the given subspace.
This lemma is only intended for use in setting up the bundled version
and should not be used once that is defined. -/
lemma orthogonal_projection_fn_mem (v : E) : orthogonal_projection_fn K v ∈ K :=
(exists_norm_eq_infi_of_complete_subspace K
(complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some
/-- The characterization of the unbundled orthogonal projection. This
lemma is only intended for use in setting up the bundled version
and should not be used once that is defined. -/
lemma orthogonal_projection_fn_inner_eq_zero (v : E) :
∀ w ∈ K, ⟪v - orthogonal_projection_fn K v, w⟫ = 0 :=
begin
rw ←norm_eq_infi_iff_inner_eq_zero K (orthogonal_projection_fn_mem v),
exact (exists_norm_eq_infi_of_complete_subspace K
(complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some_spec
end
/-- The unbundled orthogonal projection is the unique point in `K`
with the orthogonality property. This lemma is only intended for use
in setting up the bundled version and should not be used once that is
defined. -/
lemma eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero
{u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) :
orthogonal_projection_fn K u = v :=
begin
rw [←sub_eq_zero, ←inner_self_eq_zero],
have hvs : orthogonal_projection_fn K u - v ∈ K :=
submodule.sub_mem K (orthogonal_projection_fn_mem u) hvm,
have huo : ⟪u - orthogonal_projection_fn K u, orthogonal_projection_fn K u - v⟫ = 0 :=
orthogonal_projection_fn_inner_eq_zero u _ hvs,
have huv : ⟪u - v, orthogonal_projection_fn K u - v⟫ = 0 := hvo _ hvs,
have houv : ⟪(u - v) - (u - orthogonal_projection_fn K u), orthogonal_projection_fn K u - v⟫ = 0,
{ rw [inner_sub_left, huo, huv, sub_zero] },
rwa sub_sub_sub_cancel_left at houv
end
variables (K)
lemma orthogonal_projection_fn_norm_sq (v : E) :
∥v∥ * ∥v∥ = ∥v - (orthogonal_projection_fn K v)∥ * ∥v - (orthogonal_projection_fn K v)∥
+ ∥orthogonal_projection_fn K v∥ * ∥orthogonal_projection_fn K v∥ :=
begin
set p := orthogonal_projection_fn K v,
have h' : ⟪v - p, p⟫ = 0,
{ exact orthogonal_projection_fn_inner_eq_zero _ _ (orthogonal_projection_fn_mem v) },
convert norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (v - p) p h' using 2;
simp,
end
/-- The orthogonal projection onto a complete subspace. -/
def orthogonal_projection : E →L[𝕜] K :=
linear_map.mk_continuous
{ to_fun := λ v, ⟨orthogonal_projection_fn K v, orthogonal_projection_fn_mem v⟩,
map_add' := λ x y, begin
have hm : orthogonal_projection_fn K x + orthogonal_projection_fn K y ∈ K :=
submodule.add_mem K (orthogonal_projection_fn_mem x) (orthogonal_projection_fn_mem y),
have ho :
∀ w ∈ K, ⟪x + y - (orthogonal_projection_fn K x + orthogonal_projection_fn K y), w⟫ = 0,
{ intros w hw,
rw [add_sub_comm, inner_add_left, orthogonal_projection_fn_inner_eq_zero _ w hw,
orthogonal_projection_fn_inner_eq_zero _ w hw, add_zero] },
ext,
simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho]
end,
map_smul' := λ c x, begin
have hm : c • orthogonal_projection_fn K x ∈ K :=
submodule.smul_mem K _ (orthogonal_projection_fn_mem x),
have ho : ∀ w ∈ K, ⟪c • x - c • orthogonal_projection_fn K x, w⟫ = 0,
{ intros w hw,
rw [←smul_sub, inner_smul_left, orthogonal_projection_fn_inner_eq_zero _ w hw, mul_zero] },
ext,
simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho]
end }
1
(λ x, begin
simp only [one_mul, linear_map.coe_mk],
refine le_of_pow_le_pow 2 (norm_nonneg _) (by norm_num) _,
change ∥orthogonal_projection_fn K x∥ ^ 2 ≤ ∥x∥ ^ 2,
nlinarith [orthogonal_projection_fn_norm_sq K x]
end)
variables {K}
@[simp]
lemma orthogonal_projection_fn_eq (v : E) :
orthogonal_projection_fn K v = (orthogonal_projection K v : E) :=
rfl
/-- The characterization of the orthogonal projection. -/
@[simp]
lemma orthogonal_projection_inner_eq_zero (v : E) :
∀ w ∈ K, ⟪v - orthogonal_projection K v, w⟫ = 0 :=
orthogonal_projection_fn_inner_eq_zero v
/-- The orthogonal projection is the unique point in `K` with the
orthogonality property. -/
lemma eq_orthogonal_projection_of_mem_of_inner_eq_zero
{u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) :
(orthogonal_projection K u : E) = v :=
eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hvm hvo
/-- The orthogonal projections onto equal subspaces are coerced back to the same point in `E`. -/
lemma eq_orthogonal_projection_of_eq_submodule
{K' : submodule 𝕜 E} [complete_space K'] (h : K = K') (u : E) :
(orthogonal_projection K u : E) = (orthogonal_projection K' u : E) :=
begin
change orthogonal_projection_fn K u = orthogonal_projection_fn K' u,
congr,
exact h
end
/-- The orthogonal projection sends elements of `K` to themselves. -/
@[simp] lemma orthogonal_projection_mem_subspace_eq_self (v : K) : orthogonal_projection K v = v :=
by { ext, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero; simp }
local attribute [instance] finite_dimensional_bot
/-- The orthogonal projection onto the trivial submodule is the zero map. -/
@[simp] lemma orthogonal_projection_bot : orthogonal_projection (⊥ : submodule 𝕜 E) = 0 :=
begin
ext u,
apply eq_orthogonal_projection_of_mem_of_inner_eq_zero,
{ simp },
{ intros w hw,
simp [(submodule.mem_bot 𝕜).mp hw] }
end
variables (K)
/-- The orthogonal projection has norm `≤ 1`. -/
lemma orthogonal_projection_norm_le : ∥orthogonal_projection K∥ ≤ 1 :=
linear_map.mk_continuous_norm_le _ (by norm_num) _
variables (𝕜)
lemma smul_orthogonal_projection_singleton {v : E} (w : E) :
(∥v∥ ^ 2 : 𝕜) • (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v :=
begin
suffices : ↑(orthogonal_projection (𝕜 ∙ v) ((∥v∥ ^ 2 : 𝕜) • w)) = ⟪v, w⟫ • v,
{ simpa using this },
apply eq_orthogonal_projection_of_mem_of_inner_eq_zero,
{ rw submodule.mem_span_singleton,
use ⟪v, w⟫ },
{ intros x hx,
obtain ⟨c, rfl⟩ := submodule.mem_span_singleton.mp hx,
have hv : ↑∥v∥ ^ 2 = ⟪v, v⟫ := by { norm_cast, simp [norm_sq_eq_inner] },
simp [inner_sub_left, inner_smul_left, inner_smul_right, is_R_or_C.conj_div, mul_comm, hv,
inner_product_space.conj_sym, hv] }
end
/-- Formula for orthogonal projection onto a single vector. -/
lemma orthogonal_projection_singleton {v : E} (w : E) :
(orthogonal_projection (𝕜 ∙ v) w : E) = (⟪v, w⟫ / ∥v∥ ^ 2) • v :=
begin
by_cases hv : v = 0,
{ rw [hv, eq_orthogonal_projection_of_eq_submodule submodule.span_zero_singleton],
{ simp },
{ apply_instance } },
have hv' : ∥v∥ ≠ 0 := ne_of_gt (norm_pos_iff.mpr hv),
have key : ((∥v∥ ^ 2 : 𝕜)⁻¹ * ∥v∥ ^ 2) • ↑(orthogonal_projection (𝕜 ∙ v) w)
= ((∥v∥ ^ 2 : 𝕜)⁻¹ * ⟪v, w⟫) • v,
{ simp [mul_smul, smul_orthogonal_projection_singleton 𝕜 w] },
convert key;
field_simp [hv']
end
/-- Formula for orthogonal projection onto a single unit vector. -/
lemma orthogonal_projection_unit_singleton {v : E} (hv : ∥v∥ = 1) (w : E) :
(orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v :=
by { rw ← smul_orthogonal_projection_singleton 𝕜 w, simp [hv] }
end orthogonal_projection
/-- The subspace of vectors orthogonal to a given subspace. -/
def submodule.orthogonal : submodule 𝕜 E :=
{ carrier := {v | ∀ u ∈ K, ⟪u, v⟫ = 0},
zero_mem' := λ _ _, inner_zero_right,
add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero],
smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] }
notation K`ᗮ`:1200 := submodule.orthogonal K
/-- When a vector is in `Kᗮ`. -/
lemma submodule.mem_orthogonal (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪u, v⟫ = 0 := iff.rfl
/-- When a vector is in `Kᗮ`, with the inner product the
other way round. -/
lemma submodule.mem_orthogonal' (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪v, u⟫ = 0 :=
by simp_rw [submodule.mem_orthogonal, inner_eq_zero_sym]
variables {K}
/-- A vector in `K` is orthogonal to one in `Kᗮ`. -/
lemma submodule.inner_right_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪u, v⟫ = 0 :=
(K.mem_orthogonal v).1 hv u hu
/-- A vector in `Kᗮ` is orthogonal to one in `K`. -/
lemma submodule.inner_left_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪v, u⟫ = 0 :=
by rw [inner_eq_zero_sym]; exact submodule.inner_right_of_mem_orthogonal hu hv
/-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/
lemma inner_right_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪u, v⟫ = 0 :=
submodule.inner_right_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv
/-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/
lemma inner_left_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪v, u⟫ = 0 :=
submodule.inner_left_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv
variables (K)
/-- `K` and `Kᗮ` have trivial intersection. -/
lemma submodule.inf_orthogonal_eq_bot : K ⊓ Kᗮ = ⊥ :=
begin
rw submodule.eq_bot_iff,
intros x,
rw submodule.mem_inf,
exact λ ⟨hx, ho⟩, inner_self_eq_zero.1 (ho x hx)
end
/-- `K` and `Kᗮ` have trivial intersection. -/
lemma submodule.orthogonal_disjoint : disjoint K Kᗮ :=
by simp [disjoint_iff, K.inf_orthogonal_eq_bot]
/-- `Kᗮ` can be characterized as the intersection of the kernels of the operations of
inner product with each of the elements of `K`. -/
lemma orthogonal_eq_inter : Kᗮ = ⨅ v : K, (inner_right (v:E)).ker :=
begin
apply le_antisymm,
{ rw le_infi_iff,
rintros ⟨v, hv⟩ w hw,
simpa using hw _ hv },
{ intros v hv w hw,
simp only [submodule.mem_infi] at hv,
exact hv ⟨w, hw⟩ }
end
/-- The orthogonal complement of any submodule `K` is closed. -/
lemma submodule.is_closed_orthogonal : is_closed (Kᗮ : set E) :=
begin
rw orthogonal_eq_inter K,
convert is_closed_Inter (λ v : K, (inner_right (v:E)).is_closed_ker),
simp
end
/-- In a complete space, the orthogonal complement of any submodule `K` is complete. -/
instance [complete_space E] : complete_space Kᗮ := K.is_closed_orthogonal.complete_space_coe
variables (𝕜 E)
/-- `submodule.orthogonal` gives a `galois_connection` between
`submodule 𝕜 E` and its `order_dual`. -/
lemma submodule.orthogonal_gc :
@galois_connection (submodule 𝕜 E) (order_dual $ submodule 𝕜 E) _ _
submodule.orthogonal submodule.orthogonal :=
λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu),
λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩
variables {𝕜 E}
/-- `submodule.orthogonal` reverses the `≤` ordering of two
subspaces. -/
lemma submodule.orthogonal_le {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₂ᗮ ≤ K₁ᗮ :=
(submodule.orthogonal_gc 𝕜 E).monotone_l h
/-- `submodule.orthogonal.orthogonal` preserves the `≤` ordering of two
subspaces. -/
lemma submodule.orthogonal_orthogonal_monotone {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) :
K₁ᗮᗮ ≤ K₂ᗮᗮ :=
submodule.orthogonal_le (submodule.orthogonal_le h)
/-- `K` is contained in `Kᗮᗮ`. -/
lemma submodule.le_orthogonal_orthogonal : K ≤ Kᗮᗮ := (submodule.orthogonal_gc 𝕜 E).le_u_l _
/-- The inf of two orthogonal subspaces equals the subspace orthogonal
to the sup. -/
lemma submodule.inf_orthogonal (K₁ K₂ : submodule 𝕜 E) : K₁ᗮ ⊓ K₂ᗮ = (K₁ ⊔ K₂)ᗮ :=
(submodule.orthogonal_gc 𝕜 E).l_sup.symm
/-- The inf of an indexed family of orthogonal subspaces equals the
subspace orthogonal to the sup. -/
lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule 𝕜 E) : (⨅ i, (K i)ᗮ) = (supr K)ᗮ :=
(submodule.orthogonal_gc 𝕜 E).l_supr.symm
/-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/
lemma submodule.Inf_orthogonal (s : set $ submodule 𝕜 E) : (⨅ K ∈ s, Kᗮ) = (Sup s)ᗮ :=
(submodule.orthogonal_gc 𝕜 E).l_Sup.symm
/-- If `K₁` is complete and contained in `K₂`, `K₁` and `K₁ᗮ ⊓ K₂` span `K₂`. -/
lemma submodule.sup_orthogonal_inf_of_is_complete {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂)
(hc : is_complete (K₁ : set E)) : K₁ ⊔ (K₁ᗮ ⊓ K₂) = K₂ :=
begin
ext x,
rw submodule.mem_sup,
rcases exists_norm_eq_infi_of_complete_subspace K₁ hc x with ⟨v, hv, hvm⟩,
rw norm_eq_infi_iff_inner_eq_zero K₁ hv at hvm,
split,
{ rintro ⟨y, hy, z, hz, rfl⟩,
exact K₂.add_mem (h hy) hz.2 },
{ exact λ hx, ⟨v, hv, x - v, ⟨(K₁.mem_orthogonal' _).2 hvm, K₂.sub_mem hx (h hv)⟩,
add_sub_cancel'_right _ _⟩ }
end
variables {K}
/-- If `K` is complete, `K` and `Kᗮ` span the whole space. -/
lemma submodule.sup_orthogonal_of_is_complete (h : is_complete (K : set E)) : K ⊔ Kᗮ = ⊤ :=
begin
convert submodule.sup_orthogonal_inf_of_is_complete (le_top : K ≤ ⊤) h,
simp
end
/-- If `K` is complete, `K` and `Kᗮ` span the whole space. Version using `complete_space`. -/
lemma submodule.sup_orthogonal_of_complete_space [complete_space K] : K ⊔ Kᗮ = ⊤ :=
submodule.sup_orthogonal_of_is_complete (complete_space_coe_iff_is_complete.mp ‹_›)
variables (K)
/-- If `K` is complete, any `v` in `E` can be expressed as a sum of elements of `K` and `Kᗮ`. -/
lemma submodule.exists_sum_mem_mem_orthogonal [complete_space K] (v : E) :
∃ (y ∈ K) (z ∈ Kᗮ), v = y + z :=
begin
have h_mem : v ∈ K ⊔ Kᗮ := by simp [submodule.sup_orthogonal_of_complete_space],
obtain ⟨y, hy, z, hz, hyz⟩ := submodule.mem_sup.mp h_mem,
exact ⟨y, hy, z, hz, hyz.symm⟩
end
/-- If `K` is complete, then the orthogonal complement of its orthogonal complement is itself. -/
@[simp] lemma submodule.orthogonal_orthogonal [complete_space K] : Kᗮᗮ = K :=
begin
ext v,
split,
{ obtain ⟨y, hy, z, hz, rfl⟩ := K.exists_sum_mem_mem_orthogonal v,
intros hv,
have hz' : z = 0,
{ have hyz : ⟪z, y⟫ = 0 := by simp [hz y hy, inner_eq_zero_sym],
simpa [inner_add_right, hyz] using hv z hz },
simp [hy, hz'] },
{ intros hv w hw,
rw inner_eq_zero_sym,
exact hw v hv }
end
lemma submodule.orthogonal_orthogonal_eq_closure [complete_space E] :
Kᗮᗮ = K.topological_closure :=
begin
refine le_antisymm _ _,
{ convert submodule.orthogonal_orthogonal_monotone K.submodule_topological_closure,
haveI : complete_space K.topological_closure :=
K.is_closed_topological_closure.complete_space_coe,
rw K.topological_closure.orthogonal_orthogonal },
{ exact K.topological_closure_minimal K.le_orthogonal_orthogonal Kᗮ.is_closed_orthogonal }
end
variables {K}
/-- If `K` is complete, `K` and `Kᗮ` are complements of each other. -/
lemma submodule.is_compl_orthogonal_of_is_complete (h : is_complete (K : set E)) : is_compl K Kᗮ :=
⟨K.orthogonal_disjoint, le_of_eq (submodule.sup_orthogonal_of_is_complete h).symm⟩
@[simp] lemma submodule.top_orthogonal_eq_bot : (⊤ : submodule 𝕜 E)ᗮ = ⊥ :=
begin
ext,
rw [submodule.mem_bot, submodule.mem_orthogonal],
exact ⟨λ h, inner_self_eq_zero.mp (h x submodule.mem_top), by { rintro rfl, simp }⟩
end
@[simp] lemma submodule.bot_orthogonal_eq_top : (⊥ : submodule 𝕜 E)ᗮ = ⊤ :=
begin
rw [← submodule.top_orthogonal_eq_bot, eq_top_iff],
exact submodule.le_orthogonal_orthogonal ⊤
end
@[simp] lemma submodule.orthogonal_eq_bot_iff (hK : is_complete (K : set E)) :
Kᗮ = ⊥ ↔ K = ⊤ :=
begin
refine ⟨_, by { rintro rfl, exact submodule.top_orthogonal_eq_bot }⟩,
intro h,
have : K ⊔ Kᗮ = ⊤ := submodule.sup_orthogonal_of_is_complete hK,
rwa [h, sup_comm, bot_sup_eq] at this,
end
@[simp] lemma submodule.orthogonal_eq_top_iff : Kᗮ = ⊤ ↔ K = ⊥ :=
begin
refine ⟨_, by { rintro rfl, exact submodule.bot_orthogonal_eq_top }⟩,
intro h,
have : K ⊓ Kᗮ = ⊥ := K.orthogonal_disjoint.eq_bot,
rwa [h, inf_comm, top_inf_eq] at this
end
/-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the
orthogonal projection. -/
lemma eq_orthogonal_projection_of_mem_orthogonal
[complete_space K] {u v : E} (hv : v ∈ K) (hvo : u - v ∈ Kᗮ) :
(orthogonal_projection K u : E) = v :=
eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hv (λ w, inner_eq_zero_sym.mp ∘ (hvo w))
/-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the
orthogonal projection. -/
lemma eq_orthogonal_projection_of_mem_orthogonal'
[complete_space K] {u v z : E} (hv : v ∈ K) (hz : z ∈ Kᗮ) (hu : u = v + z) :
(orthogonal_projection K u : E) = v :=
eq_orthogonal_projection_of_mem_orthogonal hv (by simpa [hu])
/-- The orthogonal projection onto `K` of an element of `Kᗮ` is zero. -/
lemma orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero
[complete_space K] {v : E} (hv : v ∈ Kᗮ) :
orthogonal_projection K v = 0 :=
by { ext, convert eq_orthogonal_projection_of_mem_orthogonal _ _; simp [hv] }
/-- The orthogonal projection onto `Kᗮ` of an element of `K` is zero. -/
lemma orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero
[complete_space E] {v : E} (hv : v ∈ K) :
orthogonal_projection Kᗮ v = 0 :=
orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero (K.le_orthogonal_orthogonal hv)
/-- The orthogonal projection onto `(𝕜 ∙ v)ᗮ` of `v` is zero. -/
lemma orthogonal_projection_orthogonal_complement_singleton_eq_zero [complete_space E] (v : E) :
orthogonal_projection (𝕜 ∙ v)ᗮ v = 0 :=
orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero
(submodule.mem_span_singleton_self v)
variables (K)
/-- In a complete space `E`, a vector splits as the sum of its orthogonal projections onto a
complete submodule `K` and onto the orthogonal complement of `K`.-/
lemma eq_sum_orthogonal_projection_self_orthogonal_complement
[complete_space E] [complete_space K] (w : E) :
w = (orthogonal_projection K w : E) + (orthogonal_projection Kᗮ w : E) :=
begin
obtain ⟨y, hy, z, hz, hwyz⟩ := K.exists_sum_mem_mem_orthogonal w,
convert hwyz,
{ exact eq_orthogonal_projection_of_mem_orthogonal' hy hz hwyz },
{ rw add_comm at hwyz,
refine eq_orthogonal_projection_of_mem_orthogonal' hz _ hwyz,
simp [hy] }
end
/-- In a complete space `E`, the projection maps onto a complete subspace `K` and its orthogonal
complement sum to the identity. -/
lemma id_eq_sum_orthogonal_projection_self_orthogonal_complement
[complete_space E] [complete_space K] :
continuous_linear_map.id 𝕜 E
= K.subtypeL.comp (orthogonal_projection K)
+ Kᗮ.subtypeL.comp (orthogonal_projection Kᗮ) :=
by { ext w, exact eq_sum_orthogonal_projection_self_orthogonal_complement K w }
open finite_dimensional
/-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁`
containined in it, the dimensions of `K₁` and the intersection of its
orthogonal subspace with `K₂` add to that of `K₂`. -/
lemma submodule.finrank_add_inf_finrank_orthogonal {K₁ K₂ : submodule 𝕜 E}
[finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) :
finrank 𝕜 K₁ + finrank 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = finrank 𝕜 K₂ :=
begin
haveI := submodule.finite_dimensional_of_le h,
have hd := submodule.dim_sup_add_dim_inf_eq K₁ (K₁ᗮ ⊓ K₂),
rw [←inf_assoc, (submodule.orthogonal_disjoint K₁).eq_bot, bot_inf_eq, finrank_bot,
submodule.sup_orthogonal_inf_of_is_complete h
(submodule.complete_of_finite_dimensional _)] at hd,
rw add_zero at hd,
exact hd.symm
end
/-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁`
containined in it, the dimensions of `K₁` and the intersection of its
orthogonal subspace with `K₂` add to that of `K₂`. -/
lemma submodule.finrank_add_inf_finrank_orthogonal' {K₁ K₂ : submodule 𝕜 E}
[finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) {n : ℕ} (h_dim : finrank 𝕜 K₁ + n = finrank 𝕜 K₂) :
finrank 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = n :=
by { rw ← add_right_inj (finrank 𝕜 K₁),
simp [submodule.finrank_add_inf_finrank_orthogonal h, h_dim] }
/-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to
that of `E`. -/
lemma submodule.finrank_add_finrank_orthogonal [finite_dimensional 𝕜 E] {K : submodule 𝕜 E} :
finrank 𝕜 K + finrank 𝕜 Kᗮ = finrank 𝕜 E :=
begin
convert submodule.finrank_add_inf_finrank_orthogonal (le_top : K ≤ ⊤) using 1,
{ rw inf_top_eq },
{ simp }
end
/-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to
that of `E`. -/
lemma submodule.finrank_add_finrank_orthogonal' [finite_dimensional 𝕜 E] {K : submodule 𝕜 E} {n : ℕ}
(h_dim : finrank 𝕜 K + n = finrank 𝕜 E) :
finrank 𝕜 Kᗮ = n :=
by { rw ← add_right_inj (finrank 𝕜 K), simp [submodule.finrank_add_finrank_orthogonal, h_dim] }
local attribute [instance] finite_dimensional_of_finrank_eq_succ
/-- In a finite-dimensional inner product space, the dimension of the orthogonal complement of the
span of a nonzero vector is one less than the dimension of the space. -/
lemma finrank_orthogonal_span_singleton {n : ℕ} [_i : fact (finrank 𝕜 E = n + 1)]
{v : E} (hv : v ≠ 0) :
finrank 𝕜 (𝕜 ∙ v)ᗮ = n :=
submodule.finrank_add_finrank_orthogonal' $ by simp [finrank_span_singleton hv, _i.elim, add_comm]
end orthogonal
section orthonormal_basis
/-! ### Existence of Hilbert basis, orthonormal basis, etc. -/
variables {𝕜 E} {v : set E}
open finite_dimensional submodule set
/-- An orthonormal set in an `inner_product_space` is maximal, if and only if the orthogonal
complement of its span is empty. -/
lemma maximal_orthonormal_iff_orthogonal_complement_eq_bot (hv : orthonormal 𝕜 (coe : v → E)) :
(∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ (span 𝕜 v)ᗮ = ⊥ :=
begin
rw submodule.eq_bot_iff,
split,
{ contrapose!,
-- ** direction 1: nonempty orthogonal complement implies nonmaximal
rintros ⟨x, hx', hx⟩,
-- take a nonzero vector and normalize it
let e := (∥x∥⁻¹ : 𝕜) • x,
have he : ∥e∥ = 1 := by simp [e, norm_smul_inv_norm hx],
have he' : e ∈ (span 𝕜 v)ᗮ := smul_mem' _ _ hx',
have he'' : e ∉ v,
{ intros hev,
have : e = 0,
{ have : e ∈ (span 𝕜 v) ⊓ (span 𝕜 v)ᗮ := ⟨subset_span hev, he'⟩,
simpa [(span 𝕜 v).inf_orthogonal_eq_bot] using this },
have : e ≠ 0 := hv.ne_zero ⟨e, hev⟩,
contradiction },
-- put this together with `v` to provide a candidate orthonormal basis for the whole space
refine ⟨v.insert e, v.subset_insert e, ⟨_, _⟩, (v.ne_insert_of_not_mem he'').symm⟩,
{ -- show that the elements of `v.insert e` have unit length
rintros ⟨a, ha'⟩,
cases eq_or_mem_of_mem_insert ha' with ha ha,
{ simp [ha, he] },
{ exact hv.1 ⟨a, ha⟩ } },
{ -- show that the elements of `v.insert e` are orthogonal
have h_end : ∀ a ∈ v, ⟪a, e⟫ = 0,
{ intros a ha,
exact he' a (submodule.subset_span ha) },
rintros ⟨a, ha'⟩,
cases eq_or_mem_of_mem_insert ha' with ha ha,
{ rintros ⟨b, hb'⟩ hab',
have hb : b ∈ v,
{ refine mem_of_mem_insert_of_ne hb' _,
intros hbe',
apply hab',
simp [ha, hbe'] },
rw inner_eq_zero_sym,
simpa [ha] using h_end b hb },
rintros ⟨b, hb'⟩ hab',
cases eq_or_mem_of_mem_insert hb' with hb hb,
{ simpa [hb] using h_end a ha },
have : (⟨a, ha⟩ : v) ≠ ⟨b, hb⟩,
{ intros hab'',
apply hab',
simpa using hab'' },
exact hv.2 this } },
{ -- ** direction 2: empty orthogonal complement implies maximal
simp only [subset.antisymm_iff],
rintros h u (huv : v ⊆ u) hu,
refine ⟨_, huv⟩,
intros x hxu,
refine ((mt (h x)) (hu.ne_zero ⟨x, hxu⟩)).imp_symm _,
intros hxv y hy,
have hxv' : (⟨x, hxu⟩ : u) ∉ (coe ⁻¹' v : set u) := by simp [huv, hxv],
obtain ⟨l, hl, rfl⟩ :
∃ l ∈ finsupp.supported 𝕜 𝕜 (coe ⁻¹' v : set u), (finsupp.total ↥u E 𝕜 coe) l = y,
{ rw ← finsupp.mem_span_iff_total,
simp [huv, inter_eq_self_of_subset_left, hy] },
exact hu.inner_finsupp_eq_zero hxv' hl }
end
/-- An orthonormal set in an `inner_product_space` is maximal, if and only if the closure of its
span is the whole space. -/
lemma maximal_orthonormal_iff_dense_span [complete_space E] (hv : orthonormal 𝕜 (coe : v → E)) :
(∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ (span 𝕜 v).topological_closure = ⊤ :=
by rw [maximal_orthonormal_iff_orthogonal_complement_eq_bot hv, ← submodule.orthogonal_eq_top_iff,
(span 𝕜 v).orthogonal_orthogonal_eq_closure]
/-- Any orthonormal subset can be extended to an orthonormal set whose span is dense. -/
lemma exists_subset_is_orthonormal_dense_span
[complete_space E] (hv : orthonormal 𝕜 (coe : v → E)) :
∃ u ⊇ v, orthonormal 𝕜 (coe : u → E) ∧ (span 𝕜 u).topological_closure = ⊤ :=
begin
obtain ⟨u, hus, hu, hu_max⟩ := exists_maximal_orthonormal hv,
rw maximal_orthonormal_iff_dense_span hu at hu_max,
exact ⟨u, hus, hu, hu_max⟩
end
variables (𝕜 E)
/-- An inner product space admits an orthonormal set whose span is dense. -/
lemma exists_is_orthonormal_dense_span [complete_space E] :
∃ u : set E, orthonormal 𝕜 (coe : u → E) ∧ (span 𝕜 u).topological_closure = ⊤ :=
let ⟨u, hus, hu, hu_max⟩ := exists_subset_is_orthonormal_dense_span (orthonormal_empty 𝕜 E) in
⟨u, hu, hu_max⟩
variables {𝕜 E}
/-- An orthonormal set in a finite-dimensional `inner_product_space` is maximal, if and only if it
is a basis. -/
lemma maximal_orthonormal_iff_is_basis_of_finite_dimensional
[finite_dimensional 𝕜 E] (hv : orthonormal 𝕜 (coe : v → E)) :
(∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ is_basis 𝕜 (coe : v → E) :=
begin
rw maximal_orthonormal_iff_orthogonal_complement_eq_bot hv,
have hv_compl : is_complete (span 𝕜 v : set E) := (span 𝕜 v).complete_of_finite_dimensional,
rw submodule.orthogonal_eq_bot_iff hv_compl,
have hv_coe : range (coe : v → E) = v := by simp,
split,
{ refine λ h, ⟨hv.linear_independent, _⟩,
convert h },
{ intros h,
convert ← h.2 }
end
/-- In a finite-dimensional `inner_product_space`, any orthonormal subset can be extended to an
orthonormal basis. -/
lemma exists_subset_is_orthonormal_basis
[finite_dimensional 𝕜 E] (hv : orthonormal 𝕜 (coe : v → E)) :
∃ u ⊇ v, orthonormal 𝕜 (coe : u → E) ∧ is_basis 𝕜 (coe : u → E) :=
begin
obtain ⟨u, hus, hu, hu_max⟩ := exists_maximal_orthonormal hv,
rw maximal_orthonormal_iff_is_basis_of_finite_dimensional hu at hu_max,
exact ⟨u, hus, hu, hu_max⟩
end
variables (𝕜 E)
/-- A finite-dimensional `inner_product_space` has an orthonormal basis. -/
lemma exists_is_orthonormal_basis [finite_dimensional 𝕜 E] :
∃ u : set E, orthonormal 𝕜 (coe : u → E) ∧ is_basis 𝕜 (coe : u → E) :=
let ⟨u, hus, hu, hu_max⟩ := exists_subset_is_orthonormal_basis (orthonormal_empty 𝕜 E) in
⟨u, hu, hu_max⟩
variables {𝕜 E}
/-- Given a natural number `n` equal to the `finrank` of a finite-dimensional inner product space,
there exists an orthonormal basis for the space indexed by `fin n`. -/
lemma exists_is_orthonormal_basis' [finite_dimensional 𝕜 E] {n : ℕ} (hn : finrank 𝕜 E = n) :
∃ v : fin n → E, orthonormal 𝕜 v ∧ is_basis 𝕜 v :=
begin
obtain ⟨u, hu, hu_basis⟩ := exists_is_orthonormal_basis 𝕜 E,
obtain ⟨g, hg⟩ := finite_dimensional.equiv_fin_of_dim_eq hn hu_basis,
exact ⟨coe ∘ g, hu.comp _ g.injective, hg⟩
end
/-- Given a natural number `n` equal to the `finrank` of a finite-dimensional inner product space,
there exists an isometry from the space to `euclidean_space 𝕜 (fin n)`. -/
def linear_isometry_equiv.of_inner_product_space
[finite_dimensional 𝕜 E] {n : ℕ} (hn : finrank 𝕜 E = n) :
E ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) :=
let hv := classical.some_spec (exists_is_orthonormal_basis' hn) in
hv.2.isometry_euclidean_of_orthonormal hv.1
local attribute [instance] finite_dimensional_of_finrank_eq_succ
/-- Given a natural number `n` one less than the `finrank` of a finite-dimensional inner product
space, there exists an isometry from the orthogonal complement of a nonzero singleton to
`euclidean_space 𝕜 (fin n)`. -/
def linear_isometry_equiv.from_orthogonal_span_singleton
(n : ℕ) [fact (finrank 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) :
(𝕜 ∙ v)ᗮ ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) :=
linear_isometry_equiv.of_inner_product_space (finrank_orthogonal_span_singleton hv)
end orthonormal_basis
|
83be5aae1a88b203af1c0aa5f8f74e7d68f66725
|
4efff1f47634ff19e2f786deadd394270a59ecd2
|
/src/category_theory/fully_faithful.lean
|
59f29d818f4076d0e8f56b812e0b1855b66c4a72
|
[
"Apache-2.0"
] |
permissive
|
agjftucker/mathlib
|
d634cd0d5256b6325e3c55bb7fb2403548371707
|
87fe50de17b00af533f72a102d0adefe4a2285e8
|
refs/heads/master
| 1,625,378,131,941
| 1,599,166,526,000
| 1,599,166,526,000
| 160,748,509
| 0
| 0
|
Apache-2.0
| 1,544,141,789,000
| 1,544,141,789,000
| null |
UTF-8
|
Lean
| false
| false
| 8,059
|
lean
|
/-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.natural_isomorphism
import data.equiv.basic
universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation
namespace category_theory
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
/--
A functor `F : C ⥤ D` is full if for each `X Y : C`, `F.map` is surjective.
In fact, we use a constructive definition, so the `full F` typeclass contains data,
specifying a particular preimage of each `f : F.obj X ⟶ F.obj Y`.
-/
class full (F : C ⥤ D) :=
(preimage : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), X ⟶ Y)
(witness' : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), F.map (preimage f) = f . obviously)
restate_axiom full.witness'
attribute [simp] full.witness
/-- A functor `F : C ⥤ D` is faithful if for each `X Y : C`, `F.map` is injective.-/
class faithful (F : C ⥤ D) : Prop :=
(map_injective' [] : ∀ {X Y : C}, function.injective (@functor.map _ _ _ _ F X Y) . obviously)
restate_axiom faithful.map_injective'
namespace functor
lemma map_injective (F : C ⥤ D) [faithful F] {X Y : C} :
function.injective $ @functor.map _ _ _ _ F X Y :=
faithful.map_injective F
/-- The specified preimage of a morphism under a full functor. -/
def preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) : X ⟶ Y :=
full.preimage.{v₁ v₂} f
@[simp] lemma image_preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) :
F.map (preimage F f) = f :=
by unfold preimage; obviously
end functor
variables {F : C ⥤ D} [full F] [faithful F] {X Y Z : C}
@[simp] lemma preimage_id : F.preimage (𝟙 (F.obj X)) = 𝟙 X :=
F.map_injective (by simp)
@[simp] lemma preimage_comp (f : F.obj X ⟶ F.obj Y) (g : F.obj Y ⟶ F.obj Z) :
F.preimage (f ≫ g) = F.preimage f ≫ F.preimage g :=
F.map_injective (by simp)
@[simp] lemma preimage_map (f : X ⟶ Y) :
F.preimage (F.map f) = f :=
F.map_injective (by simp)
/-- If `F : C ⥤ D` is fully faithful, every isomorphism `F.obj X ≅ F.obj Y` has a preimage. -/
def preimage_iso (f : (F.obj X) ≅ (F.obj Y)) : X ≅ Y :=
{ hom := F.preimage f.hom,
inv := F.preimage f.inv,
hom_inv_id' := F.map_injective (by simp),
inv_hom_id' := F.map_injective (by simp), }
@[simp] lemma preimage_iso_hom (f : (F.obj X) ≅ (F.obj Y)) :
(preimage_iso f).hom = F.preimage f.hom := rfl
@[simp] lemma preimage_iso_inv (f : (F.obj X) ≅ (F.obj Y)) :
(preimage_iso f).inv = F.preimage (f.inv) := rfl
@[simp] lemma preimage_iso_map_iso (f : X ≅ Y) : preimage_iso (F.map_iso f) = f :=
by tidy
variables (F)
/--
If the image of a morphism under a fully faithful functor in an isomorphism,
then the original morphisms is also an isomorphism.
-/
def is_iso_of_fully_faithful (f : X ⟶ Y) [is_iso (F.map f)] : is_iso f :=
{ inv := F.preimage (inv (F.map f)),
hom_inv_id' := F.map_injective (by simp),
inv_hom_id' := F.map_injective (by simp) }
/-- If `F` is fully faithful, we have an equivalence of hom-sets `X ⟶ Y` and `F X ⟶ F Y`. -/
def equiv_of_fully_faithful {X Y} : (X ⟶ Y) ≃ (F.obj X ⟶ F.obj Y) :=
{ to_fun := λ f, F.map f,
inv_fun := λ f, F.preimage f,
left_inv := λ f, by simp,
right_inv := λ f, by simp }
@[simp]
lemma equiv_of_fully_faithful_apply {X Y : C} (f : X ⟶ Y) :
equiv_of_fully_faithful F f = F.map f := rfl
@[simp]
lemma equiv_of_fully_faithful_symm_apply {X Y} (f : F.obj X ⟶ F.obj Y) :
(equiv_of_fully_faithful F).symm f = F.preimage f := rfl
end category_theory
namespace category_theory
variables {C : Type u₁} [category.{v₁} C]
instance full.id : full (𝟭 C) :=
{ preimage := λ _ _ f, f }
instance faithful.id : faithful (𝟭 C) := by obviously
variables {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E]
variables (F F' : C ⥤ D) (G : D ⥤ E)
instance faithful.comp [faithful F] [faithful G] : faithful (F ⋙ G) :=
{ map_injective' := λ _ _ _ _ p, F.map_injective (G.map_injective p) }
lemma faithful.of_comp [faithful $ F ⋙ G] : faithful F :=
{ map_injective' := λ X Y, (F ⋙ G).map_injective.of_comp }
section
variables {F F'}
lemma faithful.of_iso [faithful F] (α : F ≅ F') : faithful F' :=
{ map_injective' := λ X Y f f' h, F.map_injective
(by rw [←nat_iso.naturality_1 α.symm, h, nat_iso.naturality_1 α.symm]) }
end
variables {F G}
lemma faithful.of_comp_iso {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G ≅ H) : faithful F :=
@faithful.of_comp _ _ _ _ _ _ F G (faithful.of_iso h.symm)
alias faithful.of_comp_iso ← category_theory.iso.faithful_of_comp
-- We could prove this from `faithful.of_comp_iso` using `eq_to_iso`,
-- but that would introduce a cyclic import.
lemma faithful.of_comp_eq {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G = H) : faithful F :=
@faithful.of_comp _ _ _ _ _ _ F G (h.symm ▸ ℋ)
alias faithful.of_comp_eq ← eq.faithful_of_comp
variables (F G)
/-- “Divide” a functor by a faithful functor. -/
protected def faithful.div (F : C ⥤ E) (G : D ⥤ E) [faithful G]
(obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X)
(map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y))
(h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) :
C ⥤ D :=
{ obj := obj,
map := @map,
map_id' :=
begin
assume X,
apply G.map_injective,
apply eq_of_heq,
transitivity F.map (𝟙 X), from h_map,
rw [F.map_id, G.map_id, h_obj X]
end,
map_comp' :=
begin
assume X Y Z f g,
apply G.map_injective,
apply eq_of_heq,
transitivity F.map (f ≫ g), from h_map,
rw [F.map_comp, G.map_comp],
congr' 1;
try { exact (h_obj _).symm };
exact h_map.symm
end }
-- This follows immediately from `functor.hext` (`functor.hext h_obj @h_map`),
-- but importing `category_theory.eq_to_hom` causes an import loop:
-- category_theory.eq_to_hom → category_theory.opposites →
-- category_theory.equivalence → category_theory.fully_faithful
lemma faithful.div_comp (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G]
(obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X)
(map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y))
(h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) :
(faithful.div F G obj @h_obj @map @h_map) ⋙ G = F :=
begin
casesI F with F_obj _ _ _, casesI G with G_obj _ _ _,
unfold faithful.div functor.comp,
unfold_projs at h_obj,
have: F_obj = G_obj ∘ obj := (funext h_obj).symm,
substI this,
congr,
funext,
exact eq_of_heq h_map
end
lemma faithful.div_faithful (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G]
(obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X)
(map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y))
(h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) :
faithful (faithful.div F G obj @h_obj @map @h_map) :=
(faithful.div_comp F G _ h_obj _ @h_map).faithful_of_comp
instance full.comp [full F] [full G] : full (F ⋙ G) :=
{ preimage := λ _ _ f, F.preimage (G.preimage f) }
/--
Given a natural isomorphism between `F ⋙ H` and `G ⋙ H` for a fully faithful functor `H`, we
can 'cancel' it to give a natural iso between `F` and `G`.
-/
def fully_faithful_cancel_right {F G : C ⥤ D} (H : D ⥤ E)
[full H] [faithful H] (comp_iso: F ⋙ H ≅ G ⋙ H) : F ≅ G :=
nat_iso.of_components
(λ X, preimage_iso (comp_iso.app X))
(λ X Y f, H.map_injective (by simpa using comp_iso.hom.naturality f))
@[simp]
lemma fully_faithful_cancel_right_hom_app {F G : C ⥤ D} {H : D ⥤ E}
[full H] [faithful H] (comp_iso: F ⋙ H ≅ G ⋙ H) (X : C) :
(fully_faithful_cancel_right H comp_iso).hom.app X = H.preimage (comp_iso.hom.app X) :=
rfl
@[simp]
lemma fully_faithful_cancel_right_inv_app {F G : C ⥤ D} {H : D ⥤ E}
[full H] [faithful H] (comp_iso: F ⋙ H ≅ G ⋙ H) (X : C) :
(fully_faithful_cancel_right H comp_iso).inv.app X = H.preimage (comp_iso.inv.app X) :=
rfl
end category_theory
|
ab40fac4c556f89369efa81206a22a6e8d8e62f6
|
1abd1ed12aa68b375cdef28959f39531c6e95b84
|
/src/measure_theory/decomposition/jordan.lean
|
a40b9c84209f1ae3ceffc8a7fe7a4662437319d8
|
[
"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
| 25,249
|
lean
|
/-
Copyright (c) 2021 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying
-/
import measure_theory.decomposition.signed_hahn
/-!
# Jordan decomposition
This file proves the existence and uniqueness of the Jordan decomposition for signed measures.
The Jordan decomposition theorem states that, given a signed measure `s`, there exists a
unique pair of mutually singular measures `μ` and `ν`, such that `s = μ - ν`.
The Jordan decomposition theorem for measures is a corollary of the Hahn decomposition theorem and
is useful for the Lebesgue decomposition theorem.
## Main definitions
* `measure_theory.jordan_decomposition`: a Jordan decomposition of a measurable space is a
pair of mutually singular finite measures. We say `j` is a Jordan decomposition of a signed
meausre `s` if `s = j.pos_part - j.neg_part`.
* `measure_theory.signed_measure.to_jordan_decomposition`: the Jordan decomposition of a
signed measure.
* `measure_theory.signed_measure.to_jordan_decomposition_equiv`: is the `equiv` between
`measure_theory.signed_measure` and `measure_theory.jordan_decomposition` formed by
`measure_theory.signed_measure.to_jordan_decomposition`.
## Main results
* `measure_theory.signed_measure.to_signed_measure_to_jordan_decomposition` : the Jordan
decomposition theorem.
* `measure_theory.jordan_decomposition.to_signed_measure_injective` : the Jordan decomposition of a
signed measure is unique.
## Tags
Jordan decomposition theorem
-/
noncomputable theory
open_locale classical measure_theory ennreal nnreal
variables {α β : Type*} [measurable_space α]
namespace measure_theory
/-- A Jordan decomposition of a measurable space is a pair of mutually singular,
finite measures. -/
@[ext] structure jordan_decomposition (α : Type*) [measurable_space α] :=
(pos_part neg_part : measure α)
[pos_part_finite : is_finite_measure pos_part]
[neg_part_finite : is_finite_measure neg_part]
(mutually_singular : pos_part ⊥ₘ neg_part)
attribute [instance] jordan_decomposition.pos_part_finite
attribute [instance] jordan_decomposition.neg_part_finite
namespace jordan_decomposition
open measure vector_measure
variable (j : jordan_decomposition α)
instance : has_zero (jordan_decomposition α) :=
{ zero := ⟨0, 0, mutually_singular.zero_right⟩ }
instance : inhabited (jordan_decomposition α) :=
{ default := 0 }
instance : has_neg (jordan_decomposition α) :=
{ neg := λ j, ⟨j.neg_part, j.pos_part, j.mutually_singular.symm⟩ }
instance : has_scalar ℝ≥0 (jordan_decomposition α) :=
{ smul := λ r j, ⟨r • j.pos_part, r • j.neg_part,
mutually_singular.smul _ (mutually_singular.smul _ j.mutually_singular.symm).symm⟩ }
instance has_scalar_real : has_scalar ℝ (jordan_decomposition α) :=
{ smul := λ r j, if hr : 0 ≤ r then r.to_nnreal • j else - ((-r).to_nnreal • j) }
@[simp] lemma zero_pos_part : (0 : jordan_decomposition α).pos_part = 0 := rfl
@[simp] lemma zero_neg_part : (0 : jordan_decomposition α).neg_part = 0 := rfl
@[simp] lemma neg_pos_part : (-j).pos_part = j.neg_part := rfl
@[simp] lemma neg_neg_part : (-j).neg_part = j.pos_part := rfl
@[simp] lemma smul_pos_part (r : ℝ≥0) : (r • j).pos_part = r • j.pos_part := rfl
@[simp] lemma smul_neg_part (r : ℝ≥0) : (r • j).neg_part = r • j.neg_part := rfl
lemma real_smul_def (r : ℝ) (j : jordan_decomposition α) :
r • j = if hr : 0 ≤ r then r.to_nnreal • j else - ((-r).to_nnreal • j) :=
rfl
@[simp] lemma coe_smul (r : ℝ≥0) : (r : ℝ) • j = r • j :=
show dite _ _ _ = _, by rw [dif_pos (nnreal.coe_nonneg r), real.to_nnreal_coe]
lemma real_smul_nonneg (r : ℝ) (hr : 0 ≤ r) : r • j = r.to_nnreal • j :=
dif_pos hr
lemma real_smul_neg (r : ℝ) (hr : r < 0) : r • j = - ((-r).to_nnreal • j) :=
dif_neg (not_le.2 hr)
lemma real_smul_pos_part_nonneg (r : ℝ) (hr : 0 ≤ r) :
(r • j).pos_part = r.to_nnreal • j.pos_part :=
by { rw [real_smul_def, ← smul_pos_part, dif_pos hr] }
lemma real_smul_neg_part_nonneg (r : ℝ) (hr : 0 ≤ r) :
(r • j).neg_part = r.to_nnreal • j.neg_part :=
by { rw [real_smul_def, ← smul_neg_part, dif_pos hr] }
lemma real_smul_pos_part_neg (r : ℝ) (hr : r < 0) :
(r • j).pos_part = (-r).to_nnreal • j.neg_part :=
by { rw [real_smul_def, ← smul_neg_part, dif_neg (not_le.2 hr), neg_pos_part] }
lemma real_smul_neg_part_neg (r : ℝ) (hr : r < 0) :
(r • j).neg_part = (-r).to_nnreal • j.pos_part :=
by { rw [real_smul_def, ← smul_pos_part, dif_neg (not_le.2 hr), neg_neg_part] }
/-- The signed measure associated with a Jordan decomposition. -/
def to_signed_measure : signed_measure α :=
j.pos_part.to_signed_measure - j.neg_part.to_signed_measure
lemma to_signed_measure_zero : (0 : jordan_decomposition α).to_signed_measure = 0 :=
begin
ext1 i hi,
erw [to_signed_measure, to_signed_measure_sub_apply hi, sub_self, zero_apply],
end
lemma to_signed_measure_neg : (-j).to_signed_measure = -j.to_signed_measure :=
begin
ext1 i hi,
rw [neg_apply, to_signed_measure, to_signed_measure,
to_signed_measure_sub_apply hi, to_signed_measure_sub_apply hi, neg_sub],
refl,
end
lemma to_signed_measure_smul (r : ℝ≥0) : (r • j).to_signed_measure = r • j.to_signed_measure :=
begin
ext1 i hi,
rw [vector_measure.smul_apply, to_signed_measure, to_signed_measure,
to_signed_measure_sub_apply hi, to_signed_measure_sub_apply hi, smul_sub,
smul_pos_part, smul_neg_part, ← ennreal.to_real_smul, ← ennreal.to_real_smul],
refl
end
/-- A Jordan decomposition provides a Hahn decomposition. -/
lemma exists_compl_positive_negative :
∃ S : set α, measurable_set S ∧
j.to_signed_measure ≤[S] 0 ∧ 0 ≤[Sᶜ] j.to_signed_measure ∧
j.pos_part S = 0 ∧ j.neg_part Sᶜ = 0 :=
begin
obtain ⟨S, hS₁, hS₂, hS₃⟩ := j.mutually_singular,
refine ⟨S, hS₁, _, _, hS₂, hS₃⟩,
{ refine restrict_le_restrict_of_subset_le _ _ (λ A hA hA₁, _),
rw [to_signed_measure, to_signed_measure_sub_apply hA,
show j.pos_part A = 0, by exact nonpos_iff_eq_zero.1 (hS₂ ▸ measure_mono hA₁),
ennreal.zero_to_real, zero_sub, neg_le, zero_apply, neg_zero],
exact ennreal.to_real_nonneg },
{ refine restrict_le_restrict_of_subset_le _ _ (λ A hA hA₁, _),
rw [to_signed_measure, to_signed_measure_sub_apply hA,
show j.neg_part A = 0, by exact nonpos_iff_eq_zero.1 (hS₃ ▸ measure_mono hA₁),
ennreal.zero_to_real, sub_zero],
exact ennreal.to_real_nonneg },
end
end jordan_decomposition
namespace signed_measure
open measure vector_measure jordan_decomposition classical
variables {s : signed_measure α} {μ ν : measure α} [is_finite_measure μ] [is_finite_measure ν]
/-- Given a signed measure `s`, `s.to_jordan_decomposition` is the Jordan decomposition `j`,
such that `s = j.to_signed_measure`. This property is known as the Jordan decomposition
theorem, and is shown by
`measure_theory.signed_measure.to_signed_measure_to_jordan_decomposition`. -/
def to_jordan_decomposition (s : signed_measure α) : jordan_decomposition α :=
let i := some s.exists_compl_positive_negative in
let hi := some_spec s.exists_compl_positive_negative in
{ pos_part := s.to_measure_of_zero_le i hi.1 hi.2.1,
neg_part := s.to_measure_of_le_zero iᶜ hi.1.compl hi.2.2,
pos_part_finite := infer_instance,
neg_part_finite := infer_instance,
mutually_singular :=
begin
refine ⟨iᶜ, hi.1.compl, _, _⟩,
{ rw [to_measure_of_zero_le_apply _ _ hi.1 hi.1.compl], simp },
{ rw [to_measure_of_le_zero_apply _ _ hi.1.compl hi.1.compl.compl], simp }
end }
lemma to_jordan_decomposition_spec (s : signed_measure α) :
∃ (i : set α) (hi₁ : measurable_set i) (hi₂ : 0 ≤[i] s) (hi₃ : s ≤[iᶜ] 0),
s.to_jordan_decomposition.pos_part = s.to_measure_of_zero_le i hi₁ hi₂ ∧
s.to_jordan_decomposition.neg_part = s.to_measure_of_le_zero iᶜ hi₁.compl hi₃ :=
begin
set i := some s.exists_compl_positive_negative,
obtain ⟨hi₁, hi₂, hi₃⟩ := some_spec s.exists_compl_positive_negative,
exact ⟨i, hi₁, hi₂, hi₃, rfl, rfl⟩,
end
/-- **The Jordan decomposition theorem**: Given a signed measure `s`, there exists a pair of
mutually singular measures `μ` and `ν` such that `s = μ - ν`. In this case, the measures `μ`
and `ν` are given by `s.to_jordan_decomposition.pos_part` and
`s.to_jordan_decomposition.neg_part` respectively.
Note that we use `measure_theory.jordan_decomposition.to_signed_measure` to represent the
signed measure corresponding to
`s.to_jordan_decomposition.pos_part - s.to_jordan_decomposition.neg_part`. -/
@[simp] lemma to_signed_measure_to_jordan_decomposition (s : signed_measure α) :
s.to_jordan_decomposition.to_signed_measure = s :=
begin
obtain ⟨i, hi₁, hi₂, hi₃, hμ, hν⟩ := s.to_jordan_decomposition_spec,
simp only [jordan_decomposition.to_signed_measure, hμ, hν],
ext k hk,
rw [to_signed_measure_sub_apply hk, to_measure_of_zero_le_apply _ hi₂ hi₁ hk,
to_measure_of_le_zero_apply _ hi₃ hi₁.compl hk],
simp only [ennreal.coe_to_real, subtype.coe_mk, ennreal.some_eq_coe, sub_neg_eq_add],
rw [← of_union _ (measurable_set.inter hi₁ hk) (measurable_set.inter hi₁.compl hk),
set.inter_comm i, set.inter_comm iᶜ, set.inter_union_compl _ _],
{ apply_instance },
{ rintro x ⟨⟨hx₁, _⟩, hx₂, _⟩,
exact false.elim (hx₂ hx₁) }
end
section
variables {u v w : set α}
/-- A subset `v` of a null-set `w` has zero measure if `w` is a subset of a positive set `u`. -/
lemma subset_positive_null_set
(hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w)
(hsu : 0 ≤[u] s) (hw₁ : s w = 0) (hw₂ : w ⊆ u) (hwt : v ⊆ w) : s v = 0 :=
begin
have : s v + s (w \ v) = 0,
{ rw [← hw₁, ← of_union set.disjoint_diff hv (hw.diff hv),
set.union_diff_self, set.union_eq_self_of_subset_left hwt],
apply_instance },
have h₁ := nonneg_of_zero_le_restrict _ (restrict_le_restrict_subset _ _ hu hsu (hwt.trans hw₂)),
have h₂ := nonneg_of_zero_le_restrict _
(restrict_le_restrict_subset _ _ hu hsu ((w.diff_subset v).trans hw₂)),
linarith,
end
/-- A subset `v` of a null-set `w` has zero measure if `w` is a subset of a negative set `u`. -/
lemma subset_negative_null_set
(hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w)
(hsu : s ≤[u] 0) (hw₁ : s w = 0) (hw₂ : w ⊆ u) (hwt : v ⊆ w) : s v = 0 :=
begin
rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu,
have := subset_positive_null_set hu hv hw hsu,
simp only [pi.neg_apply, neg_eq_zero, coe_neg] at this,
exact this hw₁ hw₂ hwt,
end
/-- If the symmetric difference of two positive sets is a null-set, then so are the differences
between the two sets. -/
lemma of_diff_eq_zero_of_symm_diff_eq_zero_positive
(hu : measurable_set u) (hv : measurable_set v)
(hsu : 0 ≤[u] s) (hsv : 0 ≤[v] s) (hs : s (u Δ v) = 0) :
s (u \ v) = 0 ∧ s (v \ u) = 0 :=
begin
rw restrict_le_restrict_iff at hsu hsv,
have a := hsu (hu.diff hv) (u.diff_subset v),
have b := hsv (hv.diff hu) (v.diff_subset u),
erw [of_union (set.disjoint_of_subset_left (u.diff_subset v) set.disjoint_diff)
(hu.diff hv) (hv.diff hu)] at hs,
rw zero_apply at a b,
split,
all_goals { linarith <|> apply_instance <|> assumption },
end
/-- If the symmetric difference of two negative sets is a null-set, then so are the differences
between the two sets. -/
lemma of_diff_eq_zero_of_symm_diff_eq_zero_negative
(hu : measurable_set u) (hv : measurable_set v)
(hsu : s ≤[u] 0) (hsv : s ≤[v] 0) (hs : s (u Δ v) = 0) :
s (u \ v) = 0 ∧ s (v \ u) = 0 :=
begin
rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu,
rw [← s.neg_le_neg_iff _ hv, neg_zero] at hsv,
have := of_diff_eq_zero_of_symm_diff_eq_zero_positive hu hv hsu hsv,
simp only [pi.neg_apply, neg_eq_zero, coe_neg] at this,
exact this hs,
end
lemma of_inter_eq_of_symm_diff_eq_zero_positive
(hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w)
(hsu : 0 ≤[u] s) (hsv : 0 ≤[v] s) (hs : s (u Δ v) = 0) :
s (w ∩ u) = s (w ∩ v) :=
begin
have hwuv : s ((w ∩ u) Δ (w ∩ v)) = 0,
{ refine subset_positive_null_set (hu.union hv) ((hw.inter hu).symm_diff (hw.inter hv))
(hu.symm_diff hv) (restrict_le_restrict_union _ _ hu hsu hv hsv) hs _ _,
{ exact symm_diff_le_sup u v },
{ rintro x (⟨⟨hxw, hxu⟩, hx⟩ | ⟨⟨hxw, hxv⟩, hx⟩);
rw [set.mem_inter_eq, not_and] at hx,
{ exact or.inl ⟨hxu, hx hxw⟩ },
{ exact or.inr ⟨hxv, hx hxw⟩ } } },
obtain ⟨huv, hvu⟩ := of_diff_eq_zero_of_symm_diff_eq_zero_positive
(hw.inter hu) (hw.inter hv)
(restrict_le_restrict_subset _ _ hu hsu (w.inter_subset_right u))
(restrict_le_restrict_subset _ _ hv hsv (w.inter_subset_right v)) hwuv,
rw [← of_diff_of_diff_eq_zero (hw.inter hu) (hw.inter hv) hvu, huv, zero_add]
end
lemma of_inter_eq_of_symm_diff_eq_zero_negative
(hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w)
(hsu : s ≤[u] 0) (hsv : s ≤[v] 0) (hs : s (u Δ v) = 0) :
s (w ∩ u) = s (w ∩ v) :=
begin
rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu,
rw [← s.neg_le_neg_iff _ hv, neg_zero] at hsv,
have := of_inter_eq_of_symm_diff_eq_zero_positive hu hv hw hsu hsv,
simp only [pi.neg_apply, neg_inj, neg_eq_zero, coe_neg] at this,
exact this hs,
end
end
end signed_measure
namespace jordan_decomposition
open measure vector_measure signed_measure function
private lemma eq_of_pos_part_eq_pos_part {j₁ j₂ : jordan_decomposition α}
(hj : j₁.pos_part = j₂.pos_part) (hj' : j₁.to_signed_measure = j₂.to_signed_measure) :
j₁ = j₂ :=
begin
ext1,
{ exact hj },
{ rw ← to_signed_measure_eq_to_signed_measure_iff,
suffices : j₁.pos_part.to_signed_measure - j₁.neg_part.to_signed_measure =
j₁.pos_part.to_signed_measure - j₂.neg_part.to_signed_measure,
{ exact sub_right_inj.mp this },
convert hj' }
end
/-- The Jordan decomposition of a signed measure is unique. -/
theorem to_signed_measure_injective :
injective $ @jordan_decomposition.to_signed_measure α _ :=
begin
/- The main idea is that two Jordan decompositions of a signed measure provide two
Hahn decompositions for that measure. Then, from `of_symm_diff_compl_positive_negative`,
the symmetric difference of the two Hahn decompositions has measure zero, thus, allowing us to
show the equality of the underlying measures of the Jordan decompositions. -/
intros j₁ j₂ hj,
-- obtain the two Hahn decompositions from the Jordan decompositions
obtain ⟨S, hS₁, hS₂, hS₃, hS₄, hS₅⟩ := j₁.exists_compl_positive_negative,
obtain ⟨T, hT₁, hT₂, hT₃, hT₄, hT₅⟩ := j₂.exists_compl_positive_negative,
rw ← hj at hT₂ hT₃,
-- the symmetric differences of the two Hahn decompositions have measure zero
obtain ⟨hST₁, -⟩ := of_symm_diff_compl_positive_negative hS₁.compl hT₁.compl
⟨hS₃, (compl_compl S).symm ▸ hS₂⟩ ⟨hT₃, (compl_compl T).symm ▸ hT₂⟩,
-- it suffices to show the Jordan decompositions have the same positive parts
refine eq_of_pos_part_eq_pos_part _ hj,
ext1 i hi,
-- we see that the positive parts of the two Jordan decompositions are equal to their
-- associated signed measures restricted on their associated Hahn decompositions
have hμ₁ : (j₁.pos_part i).to_real = j₁.to_signed_measure (i ∩ Sᶜ),
{ rw [to_signed_measure, to_signed_measure_sub_apply (hi.inter hS₁.compl),
show j₁.neg_part (i ∩ Sᶜ) = 0, by exact nonpos_iff_eq_zero.1
(hS₅ ▸ measure_mono (set.inter_subset_right _ _)),
ennreal.zero_to_real, sub_zero],
conv_lhs { rw ← set.inter_union_compl i S },
rw [measure_union, show j₁.pos_part (i ∩ S) = 0, by exact nonpos_iff_eq_zero.1
(hS₄ ▸ measure_mono (set.inter_subset_right _ _)), zero_add],
{ refine set.disjoint_of_subset_left (set.inter_subset_right _ _)
(set.disjoint_of_subset_right (set.inter_subset_right _ _) disjoint_compl_right) },
{ exact hi.inter hS₁ },
{ exact hi.inter hS₁.compl } },
have hμ₂ : (j₂.pos_part i).to_real = j₂.to_signed_measure (i ∩ Tᶜ),
{ rw [to_signed_measure, to_signed_measure_sub_apply (hi.inter hT₁.compl),
show j₂.neg_part (i ∩ Tᶜ) = 0, by exact nonpos_iff_eq_zero.1
(hT₅ ▸ measure_mono (set.inter_subset_right _ _)),
ennreal.zero_to_real, sub_zero],
conv_lhs { rw ← set.inter_union_compl i T },
rw [measure_union, show j₂.pos_part (i ∩ T) = 0, by exact nonpos_iff_eq_zero.1
(hT₄ ▸ measure_mono (set.inter_subset_right _ _)), zero_add],
{ exact set.disjoint_of_subset_left (set.inter_subset_right _ _)
(set.disjoint_of_subset_right (set.inter_subset_right _ _) disjoint_compl_right) },
{ exact hi.inter hT₁ },
{ exact hi.inter hT₁.compl } },
-- since the two signed measures associated with the Jordan decompositions are the same,
-- and the symmetric difference of the Hahn decompositions have measure zero, the result follows
rw [← ennreal.to_real_eq_to_real (measure_ne_top _ _) (measure_ne_top _ _), hμ₁, hμ₂, ← hj],
exact of_inter_eq_of_symm_diff_eq_zero_positive hS₁.compl hT₁.compl hi hS₃ hT₃ hST₁,
all_goals { apply_instance },
end
@[simp]
lemma to_jordan_decomposition_to_signed_measure (j : jordan_decomposition α) :
(j.to_signed_measure).to_jordan_decomposition = j :=
(@to_signed_measure_injective _ _ j (j.to_signed_measure).to_jordan_decomposition (by simp)).symm
end jordan_decomposition
namespace signed_measure
open jordan_decomposition
/-- `measure_theory.signed_measure.to_jordan_decomposition` and
`measure_theory.jordan_decomposition.to_signed_measure` form a `equiv`. -/
@[simps apply symm_apply]
def to_jordan_decomposition_equiv (α : Type*) [measurable_space α] :
signed_measure α ≃ jordan_decomposition α :=
{ to_fun := to_jordan_decomposition,
inv_fun := to_signed_measure,
left_inv := to_signed_measure_to_jordan_decomposition,
right_inv := to_jordan_decomposition_to_signed_measure }
lemma to_jordan_decomposition_zero : (0 : signed_measure α).to_jordan_decomposition = 0 :=
begin
apply to_signed_measure_injective,
simp [to_signed_measure_zero],
end
lemma to_jordan_decomposition_neg (s : signed_measure α) :
(-s).to_jordan_decomposition = -s.to_jordan_decomposition :=
begin
apply to_signed_measure_injective,
simp [to_signed_measure_neg],
end
lemma to_jordan_decomposition_smul (s : signed_measure α) (r : ℝ≥0) :
(r • s).to_jordan_decomposition = r • s.to_jordan_decomposition :=
begin
apply to_signed_measure_injective,
simp [to_signed_measure_smul],
end
private
lemma to_jordan_decomposition_smul_real_nonneg (s : signed_measure α) (r : ℝ) (hr : 0 ≤ r):
(r • s).to_jordan_decomposition = r • s.to_jordan_decomposition :=
begin
lift r to ℝ≥0 using hr,
rw [jordan_decomposition.coe_smul, ← to_jordan_decomposition_smul],
refl
end
lemma to_jordan_decomposition_smul_real (s : signed_measure α) (r : ℝ) :
(r • s).to_jordan_decomposition = r • s.to_jordan_decomposition :=
begin
by_cases hr : 0 ≤ r,
{ exact to_jordan_decomposition_smul_real_nonneg s r hr },
{ ext1,
{ rw [real_smul_pos_part_neg _ _ (not_le.1 hr),
show r • s = -(-r • s), by rw [neg_smul, neg_neg], to_jordan_decomposition_neg,
neg_pos_part, to_jordan_decomposition_smul_real_nonneg, ← smul_neg_part,
real_smul_nonneg],
all_goals { exact left.nonneg_neg_iff.2 (le_of_lt (not_le.1 hr)) } },
{ rw [real_smul_neg_part_neg _ _ (not_le.1 hr),
show r • s = -(-r • s), by rw [neg_smul, neg_neg], to_jordan_decomposition_neg,
neg_neg_part, to_jordan_decomposition_smul_real_nonneg, ← smul_pos_part,
real_smul_nonneg],
all_goals { exact left.nonneg_neg_iff.2 (le_of_lt (not_le.1 hr)) } } }
end
lemma to_jordan_decomposition_eq {s : signed_measure α} {j : jordan_decomposition α}
(h : s = j.to_signed_measure) : s.to_jordan_decomposition = j :=
by rw [h, to_jordan_decomposition_to_signed_measure]
/-- The total variation of a signed measure. -/
def total_variation (s : signed_measure α) : measure α :=
s.to_jordan_decomposition.pos_part + s.to_jordan_decomposition.neg_part
lemma total_variation_zero : (0 : signed_measure α).total_variation = 0 :=
by simp [total_variation, to_jordan_decomposition_zero]
lemma total_variation_neg (s : signed_measure α) : (-s).total_variation = s.total_variation :=
by simp [total_variation, to_jordan_decomposition_neg, add_comm]
lemma null_of_total_variation_zero (s : signed_measure α) {i : set α}
(hs : s.total_variation i = 0) : s i = 0 :=
begin
rw [total_variation, measure.coe_add, pi.add_apply, add_eq_zero_iff] at hs,
rw [← to_signed_measure_to_jordan_decomposition s, to_signed_measure, vector_measure.coe_sub,
pi.sub_apply, measure.to_signed_measure_apply, measure.to_signed_measure_apply],
by_cases hi : measurable_set i,
{ rw [if_pos hi, if_pos hi], simp [hs.1, hs.2] },
{ simp [if_neg hi] }
end
lemma absolutely_continuous_ennreal_iff (s : signed_measure α) (μ : vector_measure α ℝ≥0∞) :
s ≪ᵥ μ ↔ s.total_variation ≪ μ.ennreal_to_measure :=
begin
split; intro h,
{ refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _),
obtain ⟨i, hi₁, hi₂, hi₃, hpos, hneg⟩ := s.to_jordan_decomposition_spec,
rw [total_variation, measure.add_apply, hpos, hneg,
to_measure_of_zero_le_apply _ _ _ hS₁, to_measure_of_le_zero_apply _ _ _ hS₁],
rw ← vector_measure.absolutely_continuous.ennreal_to_measure at h,
simp [h (measure_mono_null (i.inter_subset_right S) hS₂),
h (measure_mono_null (iᶜ.inter_subset_right S) hS₂)] },
{ refine vector_measure.absolutely_continuous.mk (λ S hS₁ hS₂, _),
rw ← vector_measure.ennreal_to_measure_apply hS₁ at hS₂,
exact null_of_total_variation_zero s (h hS₂) }
end
lemma total_variation_absolutely_continuous_iff (s : signed_measure α) (μ : measure α) :
s.total_variation ≪ μ ↔
s.to_jordan_decomposition.pos_part ≪ μ ∧ s.to_jordan_decomposition.neg_part ≪ μ :=
begin
split; intro h,
{ split, all_goals
{ refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _),
have := h hS₂,
rw [total_variation, measure.add_apply, add_eq_zero_iff] at this },
exacts [this.1, this.2] },
{ refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _),
rw [total_variation, measure.add_apply, h.1 hS₂, h.2 hS₂, add_zero] }
end
-- TODO: Generalize to vector measures once total variation on vector measures is defined
lemma mutually_singular_iff (s t : signed_measure α) :
s ⊥ᵥ t ↔ s.total_variation ⊥ₘ t.total_variation :=
begin
split,
{ rintro ⟨u, hmeas, hu₁, hu₂⟩,
obtain ⟨i, hi₁, hi₂, hi₃, hipos, hineg⟩ := s.to_jordan_decomposition_spec,
obtain ⟨j, hj₁, hj₂, hj₃, hjpos, hjneg⟩ := t.to_jordan_decomposition_spec,
refine ⟨u, hmeas, _, _⟩,
{ rw [total_variation, measure.add_apply, hipos, hineg,
to_measure_of_zero_le_apply _ _ _ hmeas, to_measure_of_le_zero_apply _ _ _ hmeas],
simp [hu₁ _ (set.inter_subset_right _ _)] },
{ rw [total_variation, measure.add_apply, hjpos, hjneg,
to_measure_of_zero_le_apply _ _ _ hmeas.compl,
to_measure_of_le_zero_apply _ _ _ hmeas.compl],
simp [hu₂ _ (set.inter_subset_right _ _)] } },
{ rintro ⟨u, hmeas, hu₁, hu₂⟩,
exact ⟨u, hmeas,
(λ t htu, null_of_total_variation_zero _ (measure_mono_null htu hu₁)),
(λ t htv, null_of_total_variation_zero _ (measure_mono_null htv hu₂))⟩ }
end
lemma mutually_singular_ennreal_iff (s : signed_measure α) (μ : vector_measure α ℝ≥0∞) :
s ⊥ᵥ μ ↔ s.total_variation ⊥ₘ μ.ennreal_to_measure :=
begin
split,
{ rintro ⟨u, hmeas, hu₁, hu₂⟩,
obtain ⟨i, hi₁, hi₂, hi₃, hpos, hneg⟩ := s.to_jordan_decomposition_spec,
refine ⟨u, hmeas, _, _⟩,
{ rw [total_variation, measure.add_apply, hpos, hneg,
to_measure_of_zero_le_apply _ _ _ hmeas, to_measure_of_le_zero_apply _ _ _ hmeas],
simp [hu₁ _ (set.inter_subset_right _ _)] },
{ rw vector_measure.ennreal_to_measure_apply hmeas.compl,
exact hu₂ _ (set.subset.refl _) } },
{ rintro ⟨u, hmeas, hu₁, hu₂⟩,
refine vector_measure.mutually_singular.mk u hmeas
(λ t htu _, null_of_total_variation_zero _ (measure_mono_null htu hu₁)) (λ t htv hmt, _),
rw ← vector_measure.ennreal_to_measure_apply hmt,
exact measure_mono_null htv hu₂ }
end
lemma total_variation_mutually_singular_iff (s : signed_measure α) (μ : measure α) :
s.total_variation ⊥ₘ μ ↔
s.to_jordan_decomposition.pos_part ⊥ₘ μ ∧ s.to_jordan_decomposition.neg_part ⊥ₘ μ :=
measure.mutually_singular.add_iff
end signed_measure
end measure_theory
|
db9b79ea01a32e27a69be4e564845e4247a39beb
|
74addaa0e41490cbaf2abd313a764c96df57b05d
|
/Mathlib/ring_theory/free_ring.lean
|
92008aab7ba9de5b6476ef7a345d4198c123dcce
|
[] |
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,714
|
lean
|
/-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Johan Commelin
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.group_theory.free_abelian_group
import Mathlib.ring_theory.subring
import Mathlib.PostPort
universes u v
namespace Mathlib
/-!
# Free rings
The theory of the free ring over a type.
## Main definitions
* `free_ring α` : the free (not commutative in general) ring over a type.
* `lift (f : α → R)` : the ring hom `free_ring α →+* R` induced by `f`.
* `map (f : α → β)` : the ring hom `free_ring α →+* free_ring β` induced by `f`.
## Implementation details
`free_ring α` is implemented as the free abelian group over the free monoid on `α`.
## Tags
free ring
-/
/-- The free ring over a type `α`. -/
def free_ring (α : Type u) :=
free_abelian_group (free_monoid α)
namespace free_ring
protected instance ring (α : Type u) : ring (free_ring α) :=
free_abelian_group.ring (free_monoid α)
protected instance inhabited (α : Type u) : Inhabited (free_ring α) :=
{ default := 0 }
/-- The canonical map from α to `free_ring α`. -/
def of {α : Type u} (x : α) : free_ring α :=
free_abelian_group.of [x]
theorem of_injective {α : Type u} : function.injective of :=
function.injective.comp free_abelian_group.of_injective free_monoid.of_injective
protected theorem induction_on {α : Type u} {C : free_ring α → Prop} (z : free_ring α) (hn1 : C (-1)) (hb : ∀ (b : α), C (of b)) (ha : ∀ (x y : free_ring α), C x → C y → C (x + y)) (hm : ∀ (x y : free_ring α), C x → C y → C (x * y)) : C z := sorry
/-- The ring homomorphism `free_ring α →+* R` induced from a map `α → R`. -/
def lift {α : Type u} {R : Type v} [ring R] (f : α → R) : free_ring α →+* R :=
ring_hom.mk (add_monoid_hom.to_fun (free_abelian_group.lift fun (L : List α) => list.prod (list.map f L))) sorry sorry
sorry sorry
@[simp] theorem lift_of {α : Type u} {R : Type v} [ring R] (f : α → R) (x : α) : coe_fn (lift f) (of x) = f x :=
Eq.trans (free_abelian_group.lift.of (fun (L : List α) => list.prod (list.map f L)) [x]) (one_mul (f x))
@[simp] theorem lift_comp_of {α : Type u} {R : Type v} [ring R] (f : free_ring α →+* R) : lift (⇑f ∘ of) = f := sorry
/-- The canonical ring homomorphism `free_ring α →+* free_ring β` generated by a map `α → β`. -/
def map {α : Type u} {β : Type v} (f : α → β) : free_ring α →+* free_ring β :=
lift (of ∘ f)
@[simp] theorem map_of {α : Type u} {β : Type v} (f : α → β) (x : α) : coe_fn (map f) (of x) = of (f x) :=
lift_of (of ∘ f) x
|
ffc2712283d8469a64492bb92266b603fb6f6d0c
|
4727251e0cd73359b15b664c3170e5d754078599
|
/src/combinatorics/double_counting.lean
|
99e30deda21c4d5b9424a52c8be42fd12c5993f7
|
[
"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
| 3,532
|
lean
|
/-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import algebra.big_operators.order
/-!
# Double countings
This file gathers a few double counting arguments.
## Bipartite graphs
In a bipartite graph (considered as a relation `r : α → β → Prop`), we can bound the number of edges
between `s : finset α` and `t : finset β` by the minimum/maximum of edges over all `a ∈ s` times the
the size of `s`. Similarly for `t`. Combining those two yields inequalities between the sizes of `s`
and `t`.
* `bipartite_below`: `s.bipartite_below r b` are the elements of `s` below `b` wrt to `r`. Its size
is the number of edges of `b` in `s`.
* `bipartite_above`: `t.bipartite_above r a` are the elements of `t` above `a` wrt to `r`. Its size
is the number of edges of `a` in `t`.
* `card_mul_le_card_mul`, `card_mul_le_card_mul'`: Double counting the edges of a bipartite graph
from below and from above.
* `card_mul_eq_card_mul`: Equality combination of the previous.
-/
open finset function
open_locale big_operators
/-! ### Bipartite graph -/
namespace finset
section bipartite
variables {α β : Type*} (r : α → β → Prop) (s : finset α) (t : finset β) (a a' : α) (b b' : β)
[decidable_pred (r a)] [Π a, decidable (r a b)] {m n : ℕ}
/-- Elements of `s` which are "below" `b` according to relation `r`. -/
def bipartite_below : finset α := s.filter (λ a, r a b)
/-- Elements of `t` which are "above" `a` according to relation `r`. -/
def bipartite_above : finset β := t.filter (r a)
lemma bipartite_below_swap : t.bipartite_below (swap r) a = t.bipartite_above r a := rfl
lemma bipartite_above_swap : s.bipartite_above (swap r) b = s.bipartite_below r b := rfl
variables {s t a a' b b'}
@[simp] lemma mem_bipartite_below {a : α} : a ∈ s.bipartite_below r b ↔ a ∈ s ∧ r a b := mem_filter
@[simp] lemma mem_bipartite_above {b : β} : b ∈ t.bipartite_above r a ↔ b ∈ t ∧ r a b := mem_filter
lemma sum_card_bipartite_above_eq_sum_card_bipartite_below [Π a b, decidable (r a b)] :
∑ a in s, (t.bipartite_above r a).card = ∑ b in t, (s.bipartite_below r b).card :=
by { simp_rw [card_eq_sum_ones, bipartite_above, bipartite_below, sum_filter], exact sum_comm }
/-- Double counting argument. Considering `r` as a bipartite graph, the LHS is a lower bound on the
number of edges while the RHS is an upper bound. -/
lemma card_mul_le_card_mul [Π a b, decidable (r a b)]
(hm : ∀ a ∈ s, m ≤ (t.bipartite_above r a).card)
(hn : ∀ b ∈ t, (s.bipartite_below r b).card ≤ n) :
s.card * m ≤ t.card * n :=
calc
_ ≤ ∑ a in s, (t.bipartite_above r a).card : s.card_nsmul_le_sum _ _ hm
... = ∑ b in t, (s.bipartite_below r b).card
: sum_card_bipartite_above_eq_sum_card_bipartite_below _
... ≤ _ : t.sum_le_card_nsmul _ _ hn
lemma card_mul_le_card_mul' [Π a b, decidable (r a b)]
(hn : ∀ b ∈ t, n ≤ (s.bipartite_below r b).card)
(hm : ∀ a ∈ s, (t.bipartite_above r a).card ≤ m) :
t.card * n ≤ s.card * m :=
card_mul_le_card_mul (swap r) hn hm
lemma card_mul_eq_card_mul [Π a b, decidable (r a b)]
(hm : ∀ a ∈ s, (t.bipartite_above r a).card = m)
(hn : ∀ b ∈ t, (s.bipartite_below r b).card = n) :
s.card * m = t.card * n :=
(card_mul_le_card_mul _ (λ a ha, (hm a ha).ge) $ λ b hb, (hn b hb).le).antisymm $
card_mul_le_card_mul' _ (λ a ha, (hn a ha).ge) $ λ b hb, (hm b hb).le
end bipartite
end finset
|
17abb32280983c2018c77de2a2cc2ef8059eedd2
|
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
|
/src/data/pfunctor/univariate/M.lean
|
74d227d020b07ad8ba5e76768939ae2bfb469542
|
[
"Apache-2.0"
] |
permissive
|
troyjlee/mathlib
|
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
|
45e7eb8447555247246e3fe91c87066506c14875
|
refs/heads/master
| 1,689,248,035,046
| 1,629,470,528,000
| 1,629,470,528,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 22,062
|
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 data.pfunctor.univariate.basic
/-!
# M-types
M types are potentially infinite tree-like structures. They are defined
as the greatest fixpoint of a polynomial functor.
-/
universes u v w
open nat function list (hiding head')
variables (F : pfunctor.{u})
local prefix `♯`:0 := cast (by simp [*] <|> cc <|> solve_by_elim)
namespace pfunctor
namespace approx
/-- `cofix_a F n` is an `n` level approximation of a M-type -/
inductive cofix_a : ℕ → Type u
| continue : cofix_a 0
| intro {n} : ∀ a, (F.B a → cofix_a n) → cofix_a (succ n)
/-- default inhabitant of `cofix_a` -/
protected def cofix_a.default [inhabited F.A] : Π n, cofix_a F n
| 0 := cofix_a.continue
| (succ n) := cofix_a.intro (default _) $ λ _, cofix_a.default n
instance [inhabited F.A] {n} : inhabited (cofix_a F n) := ⟨ cofix_a.default F n ⟩
lemma cofix_a_eq_zero : ∀ x y : cofix_a F 0, x = y
| cofix_a.continue cofix_a.continue := rfl
variables {F}
/--
The label of the root of the tree for a non-trivial
approximation of the cofix of a pfunctor.
-/
def head' : Π {n}, cofix_a F (succ n) → F.A
| n (cofix_a.intro i _) := i
/-- for a non-trivial approximation, return all the subtrees of the root -/
def children' : Π {n} (x : cofix_a F (succ n)), F.B (head' x) → cofix_a F n
| n (cofix_a.intro a f) := f
lemma approx_eta {n : ℕ} (x : cofix_a F (n+1)) :
x = cofix_a.intro (head' x) (children' x) :=
by cases x; refl
/-- 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 : ∀ {n : ℕ}, cofix_a F n → cofix_a F (n+1) → Prop
| continue (x : cofix_a F 0) (y : cofix_a F 1) : agree x y
| intro {n} {a} (x : F.B a → cofix_a F n) (x' : F.B a → cofix_a F (n+1)) :
(∀ i : F.B 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 (x : Π n, cofix_a F n) :=
∀ n, agree (x n) (x (succ n))
@[simp]
lemma agree_trival {x : cofix_a F 0} {y : cofix_a F 1} :
agree x y :=
by { constructor }
lemma agree_children {n : ℕ} (x : cofix_a F (succ n)) (y : cofix_a F (succ n+1))
{i j} (h₀ : i == j) (h₁ : agree x y) :
agree (children' x i) (children' y j) :=
begin
cases h₁ with _ _ _ _ _ _ hagree, cases h₀,
apply hagree,
end
/-- `truncate a` turns `a` into a more limited approximation -/
def truncate : ∀ {n : ℕ}, cofix_a F (n+1) → cofix_a F n
| 0 (cofix_a.intro _ _) := cofix_a.continue
| (succ n) (cofix_a.intro i f) := cofix_a.intro i $ truncate ∘ f
lemma truncate_eq_of_agree {n : ℕ} (x : cofix_a F n) (y : cofix_a F (succ n)) (h : agree x y) :
truncate y = x :=
begin
induction n generalizing x y; cases x; cases y,
{ refl },
{ cases h with _ _ _ _ _ h₀ h₁,
cases h,
simp only [truncate, function.comp, true_and, eq_self_iff_true, heq_iff_eq],
ext y, apply n_ih,
apply h₁ }
end
variables {X : Type w}
variables (f : X → F.obj X)
/-- `s_corec f i n` creates an approximation of height `n`
of the final coalgebra of `f` -/
def s_corec : Π (i : X) n, cofix_a F n
| _ 0 := cofix_a.continue
| j (succ n) := cofix_a.intro (f j).1 (λ i, s_corec ((f j).2 i) _)
lemma P_corec (i : X) (n : ℕ) : agree (s_corec f i n) (s_corec f i (succ n)) :=
begin
induction n with n generalizing i,
constructor,
cases h : f i with y g,
constructor,
introv,
apply n_ih,
end
/-- `path F` provides indices to access internal nodes in `corec F` -/
def path (F : pfunctor.{u}) := list F.Idx
instance path.inhabited : inhabited (path F) := ⟨ [] ⟩
open list nat
instance : subsingleton (cofix_a F 0) :=
⟨ by { intros, casesm* cofix_a F 0, refl } ⟩
lemma head_succ' (n m : ℕ) (x : Π n, cofix_a F n) (Hconsistent : all_agree x) :
head' (x (succ n)) = head' (x (succ m)) :=
begin
suffices : ∀ n, head' (x (succ n)) = head' (x 1),
{ simp [this] },
clear m n, intro,
cases h₀ : x (succ n) with _ i₀ f₀,
cases h₁ : x 1 with _ i₁ f₁,
dsimp only [head'],
induction n with n,
{ rw h₁ at h₀, cases h₀, trivial },
{ have H := Hconsistent (succ n),
cases h₂ : x (succ n) with _ i₂ f₂,
rw [h₀,h₂] at H,
apply n_ih (truncate ∘ f₀),
rw h₂,
cases H with _ _ _ _ _ _ hagree,
congr, funext j, dsimp only [comp_app],
rw truncate_eq_of_agree,
apply hagree }
end
end approx
open 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 :=
(approx : ∀ n, cofix_a F n)
(consistent : all_agree approx)
/-- For polynomial functor `F`, `M F` is its final coalgebra -/
def M := M_intl F
lemma M.default_consistent [inhabited F.A] :
Π n, agree (default (cofix_a F n)) (default (cofix_a F (succ n)))
| 0 := agree.continue _ _
| (succ n) := agree.intro _ _ $ λ _, M.default_consistent n
instance M.inhabited [inhabited F.A] : inhabited (M F) :=
⟨ { approx := λ n, default _,
consistent := M.default_consistent _ } ⟩
instance M_intl.inhabited [inhabited F.A] : inhabited (M_intl F) :=
show inhabited (M F), by apply_instance
namespace M
lemma ext' (x y : M F) (H : ∀ i : ℕ, x.approx i = y.approx i) : x = y :=
by { cases x, cases y, congr' with n, apply H }
variables {X : Type*}
variables (f : X → F.obj X)
variables {F}
/-- Corecursor for the M-type defined by `F`. -/
protected def corec (i : X) : M F :=
{ approx := s_corec f i,
consistent := P_corec _ _ }
variables {F}
/-- given a tree generated by `F`, `head` gives us the first piece of data
it contains -/
def head (x : M F) :=
head' (x.1 1)
/-- return all the subtrees of the root of a tree `x : M F` -/
def children (x : M F) (i : F.B (head x)) : M F :=
let H := λ n : ℕ, @head_succ' _ n 0 x.1 x.2 in
{ approx := λ n, children' (x.1 _) (cast (congr_arg _ $ by simp only [head,H]; refl) i),
consistent :=
begin
intro,
have P' := x.2 (succ n),
apply agree_children _ _ _ P',
transitivity i,
apply cast_heq,
symmetry,
apply cast_heq,
end }
/-- select a subtree using a `i : F.Idx` or return an arbitrary tree if
`i` designates no subtree of `x` -/
def ichildren [inhabited (M F)] [decidable_eq F.A] (i : F.Idx) (x : M F) : M F :=
if H' : i.1 = head x
then children x (cast (congr_arg _ $ by simp only [head,H']; refl) i.2)
else default _
lemma head_succ (n m : ℕ) (x : M F) :
head' (x.approx (succ n)) = head' (x.approx (succ m)) :=
head_succ' n m _ x.consistent
lemma head_eq_head' : Π (x : M F) (n : ℕ),
head x = head' (x.approx $ n+1)
| ⟨x,h⟩ n := head_succ' _ _ _ h
lemma head'_eq_head : Π (x : M F) (n : ℕ),
head' (x.approx $ n+1) = head x
| ⟨x,h⟩ n := head_succ' _ _ _ h
lemma truncate_approx (x : M F) (n : ℕ) :
truncate (x.approx $ n+1) = x.approx n :=
truncate_eq_of_agree _ _ (x.consistent _)
/-- unfold an M-type -/
def dest : M F → F.obj (M F)
| x := ⟨head x,λ i, children x i ⟩
namespace approx
/-- generates the approximations needed for `M.mk` -/
protected def s_mk (x : F.obj $ M F) : Π n, cofix_a F n
| 0 := cofix_a.continue
| (succ n) := cofix_a.intro x.1 (λ i, (x.2 i).approx n)
protected lemma P_mk (x : F.obj $ M F)
: all_agree (approx.s_mk x)
| 0 := by { constructor }
| (succ n) := by { constructor, introv,
apply (x.2 i).consistent }
end approx
/-- constructor for M-types -/
protected def mk (x : F.obj $ M F) : M F :=
{ approx := approx.s_mk x,
consistent := approx.P_mk x }
/-- `agree' n` relates two trees of type `M F` that
are the same up to dept `n` -/
inductive agree' : ℕ → M F → M F → Prop
| trivial (x y : M F) : agree' 0 x y
| step {n : ℕ} {a} (x y : F.B a → M F) {x' y'} :
x' = M.mk ⟨a,x⟩ →
y' = M.mk ⟨a,y⟩ →
(∀ i, agree' n (x i) (y i)) →
agree' (succ n) x' y'
@[simp]
lemma dest_mk (x : F.obj $ M F) :
dest (M.mk x) = x :=
begin
funext i,
dsimp only [M.mk,dest],
cases x with x ch, congr' with i,
cases h : ch i,
simp only [children,M.approx.s_mk,children',cast_eq],
dsimp only [M.approx.s_mk,children'],
congr, rw h,
end
@[simp] lemma mk_dest (x : M F) :
M.mk (dest x) = x :=
begin
apply ext', intro n,
dsimp only [M.mk],
induction n with n,
{ apply subsingleton.elim },
dsimp only [approx.s_mk,dest,head],
cases h : x.approx (succ n) with _ hd ch,
have h' : hd = head' (x.approx 1),
{ rw [← head_succ' n,h,head'], apply x.consistent },
revert ch, rw h', intros, congr,
{ ext a, dsimp only [children],
h_generalize! hh : a == a'',
rw h, intros, cases hh, refl },
end
lemma mk_inj {x y : F.obj $ M F}
(h : M.mk x = M.mk y) : x = y :=
by rw [← dest_mk x,h,dest_mk]
/-- destructor for M-types -/
protected def cases {r : M F → Sort w}
(f : ∀ (x : F.obj $ M F), r (M.mk x)) (x : M F) : r x :=
suffices r (M.mk (dest x)),
by { haveI := classical.prop_decidable,
haveI := inhabited.mk x,
rw [← mk_dest x], exact this },
f _
/-- destructor for M-types -/
protected def cases_on {r : M F → Sort w}
(x : M F) (f : ∀ (x : F.obj $ 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' {r : M F → Sort w}
(x : M F) (f : ∀ a f, r (M.mk ⟨a,f⟩)) : r x :=
M.cases_on x (λ ⟨a,g⟩, f a _)
lemma approx_mk (a : F.A) (f : F.B a → M F) (i : ℕ) :
(M.mk ⟨a, f⟩).approx (succ i) = cofix_a.intro a (λ j, (f j).approx i) :=
rfl
@[simp] lemma agree'_refl {n : ℕ} (x : M F) :
agree' n x x :=
by { induction n generalizing x; induction x using pfunctor.M.cases_on';
constructor; try { refl }, intros, apply n_ih }
lemma agree_iff_agree' {n : ℕ} (x y : M F) :
agree (x.approx n) (y.approx $ n+1) ↔ agree' n x y :=
begin
split; intros h,
{ induction n generalizing x y, constructor,
{ induction x using pfunctor.M.cases_on',
induction y using pfunctor.M.cases_on',
simp only [approx_mk] at h, cases h with _ _ _ _ _ _ hagree,
constructor; try { refl },
intro i, apply n_ih, apply hagree } },
{ induction n generalizing x y, constructor,
{ cases h,
induction x using pfunctor.M.cases_on',
induction y using pfunctor.M.cases_on',
simp only [approx_mk],
have h_a_1 := mk_inj ‹M.mk ⟨x_a, x_f⟩ = M.mk ⟨h_a, h_x⟩›, cases h_a_1,
replace h_a_2 := mk_inj ‹M.mk ⟨y_a, y_f⟩ = M.mk ⟨h_a, h_y⟩›, cases h_a_2,
constructor, intro i, apply n_ih, simp * } },
end
@[simp]
lemma cases_mk {r : M F → Sort*} (x : F.obj $ M F) (f : Π (x : F.obj $ M F), r (M.mk x)) :
pfunctor.M.cases f (M.mk x) = f x :=
begin
dsimp only [M.mk,pfunctor.M.cases,dest,head,approx.s_mk,head'],
cases x, dsimp only [approx.s_mk],
apply eq_of_heq,
apply rec_heq_of_heq, congr' with x,
dsimp only [children,approx.s_mk,children'],
cases h : x_snd x, dsimp only [head],
congr' with n, change (x_snd (x)).approx n = _, rw h
end
@[simp]
lemma cases_on_mk {r : M F → Sort*} (x : F.obj $ M F) (f : Π x : F.obj $ M F, r (M.mk x)) :
pfunctor.M.cases_on (M.mk x) f = f x :=
cases_mk x f
@[simp]
lemma cases_on_mk'
{r : M F → Sort*} {a} (x : F.B a → M F) (f : Π a (f : F.B a → M F), r (M.mk ⟨a,f⟩)) :
pfunctor.M.cases_on' (M.mk ⟨a,x⟩) f = f a x :=
cases_mk ⟨_,x⟩ _
/-- `is_path p x` tells us if `p` is a valid path through `x` -/
inductive is_path : path F → M F → Prop
| nil (x : M F) : is_path [] x
| cons (xs : path F) {a} (x : M F) (f : F.B a → M F) (i : F.B a) :
x = M.mk ⟨a,f⟩ →
is_path xs (f i) →
is_path (⟨a,i⟩ :: xs) x
lemma is_path_cons {xs : path F} {a a'} {f : F.B a → M F} {i : F.B a'}
(h : is_path (⟨a',i⟩ :: xs) (M.mk ⟨a,f⟩)) :
a = a' :=
begin
revert h, generalize h : (M.mk ⟨a,f⟩) = x,
intros h', cases h', subst x,
cases mk_inj ‹_›, refl,
end
lemma is_path_cons' {xs : path F} {a} {f : F.B a → M F} {i : F.B a}
(h : is_path (⟨a,i⟩ :: xs) (M.mk ⟨a,f⟩)) :
is_path xs (f i) :=
begin
revert h, generalize h : (M.mk ⟨a,f⟩) = x,
intros h', cases h', subst x,
have := mk_inj ‹_›, cases this, cases this,
assumption,
end
/-- 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 [decidable_eq F.A] [inhabited (M F)] : path F → M F → M F
| [] x := x
| (⟨a, i⟩ :: ps) x :=
pfunctor.M.cases_on' x (λ a' f,
(if h : a = a' then isubtree ps (f $ cast (by rw h) i)
else default (M F) : (λ x, M F) (M.mk ⟨a',f⟩)))
/-- similar to `isubtree` but returns the data at the end of the path instead
of the whole subtree -/
def iselect [decidable_eq F.A] [inhabited (M F)] (ps : path F) : M F → F.A :=
λ (x : M F), head $ isubtree ps x
lemma iselect_eq_default [decidable_eq F.A] [inhabited (M F)] (ps : path F) (x : M F)
(h : ¬ is_path ps x) :
iselect ps x = head (default $ M F) :=
begin
induction ps generalizing x,
{ exfalso, apply h, constructor },
{ cases ps_hd with a i,
induction x using pfunctor.M.cases_on',
simp only [iselect,isubtree] at ps_ih ⊢,
by_cases h'' : a = x_a, subst x_a,
{ simp only [dif_pos, eq_self_iff_true, cases_on_mk'],
rw ps_ih, intro h', apply h,
constructor; try { refl }, apply h' },
{ simp * } }
end
@[simp] lemma head_mk (x : F.obj (M F)) :
head (M.mk x) = x.1 :=
eq.symm $
calc x.1
= (dest (M.mk x)).1 : by rw dest_mk
... = head (M.mk x) : by refl
lemma children_mk {a} (x : F.B a → (M F)) (i : F.B (head (M.mk ⟨a,x⟩))) :
children (M.mk ⟨a,x⟩) i = x (cast (by rw head_mk) i) :=
by apply ext'; intro n; refl
@[simp]
lemma ichildren_mk [decidable_eq F.A] [inhabited (M F)] (x : F.obj (M F)) (i : F.Idx) :
ichildren i (M.mk x) = x.iget i :=
by { dsimp only [ichildren,pfunctor.obj.iget],
congr' with h, apply ext',
dsimp only [children',M.mk,approx.s_mk],
intros, refl }
@[simp]
lemma isubtree_cons
[decidable_eq F.A] [inhabited (M F)] (ps : path F) {a} (f : F.B a → M F) {i : F.B a} :
isubtree (⟨_,i⟩ :: ps) (M.mk ⟨a,f⟩) = isubtree ps (f i) :=
by simp only [isubtree,ichildren_mk,pfunctor.obj.iget,dif_pos,isubtree,M.cases_on_mk']; refl
@[simp]
lemma iselect_nil [decidable_eq F.A] [inhabited (M F)] {a} (f : F.B a → M F) :
iselect nil (M.mk ⟨a,f⟩) = a :=
by refl
@[simp]
lemma iselect_cons [decidable_eq F.A] [inhabited (M F)] (ps : path F) {a} (f : F.B a → M F) {i} :
iselect (⟨a,i⟩ :: ps) (M.mk ⟨a,f⟩) = iselect ps (f i) :=
by simp only [iselect,isubtree_cons]
lemma corec_def {X} (f : X → F.obj X) (x₀ : X) :
M.corec f x₀ = M.mk (M.corec f <$> f x₀) :=
begin
dsimp only [M.corec,M.mk],
congr' with n,
cases n with n,
{ dsimp only [s_corec,approx.s_mk], refl, },
{ dsimp only [s_corec,approx.s_mk], cases h : (f x₀),
dsimp only [(<$>),pfunctor.map],
congr, }
end
lemma ext_aux [inhabited (M F)] [decidable_eq F.A] {n : ℕ} (x y z : M F)
(hx : agree' n z x)
(hy : agree' n z y)
(hrec : ∀ (ps : path F),
n = ps.length →
iselect ps x = iselect ps y) :
x.approx (n+1) = y.approx (n+1) :=
begin
induction n with n generalizing x y z,
{ specialize hrec [] rfl,
induction x using pfunctor.M.cases_on', induction y using pfunctor.M.cases_on',
simp only [iselect_nil] at hrec, subst hrec,
simp only [approx_mk, true_and, eq_self_iff_true, heq_iff_eq],
apply subsingleton.elim },
{ cases hx, cases hy,
induction x using pfunctor.M.cases_on', induction y using pfunctor.M.cases_on',
subst z,
iterate 3 { have := mk_inj ‹_›, repeat { cases this } },
simp only [approx_mk, true_and, eq_self_iff_true, heq_iff_eq],
ext i, apply n_ih,
{ solve_by_elim },
{ solve_by_elim },
introv h, specialize hrec (⟨_,i⟩ :: ps) (congr_arg _ h),
simp only [iselect_cons] at hrec, exact hrec }
end
open pfunctor.approx
variables {F}
local attribute [instance, priority 0] classical.prop_decidable
lemma ext [inhabited (M F)]
(x y : M F)
(H : ∀ (ps : path F), iselect ps x = iselect ps y) :
x = y :=
begin
apply ext', intro i,
induction i with i,
{ cases x.approx 0, cases y.approx 0, constructor },
{ apply ext_aux x y x,
{ rw ← agree_iff_agree', apply x.consistent },
{ rw [← agree_iff_agree',i_ih], apply y.consistent },
introv H',
dsimp only [iselect] at H,
cases H',
apply H ps }
end
section bisim
variable (R : M F → M F → Prop)
local infix ` ~ `:50 := R
/-- Bisimulation is the standard proof technique for equality between
infinite tree-like structures -/
structure is_bisimulation : Prop :=
(head : ∀ {a a'} {f f'}, M.mk ⟨a,f⟩ ~ M.mk ⟨a',f'⟩ → a = a')
(tail : ∀ {a} {f f' : F.B a → M F},
M.mk ⟨a,f⟩ ~ M.mk ⟨a,f'⟩ →
(∀ (i : F.B a), f i ~ f' i) )
theorem nth_of_bisim [inhabited (M F)] (bisim : is_bisimulation R) (s₁ s₂) (ps : path F) :
s₁ ~ s₂ →
is_path ps s₁ ∨ is_path ps s₂ →
iselect ps s₁ = iselect ps s₂ ∧
∃ a (f f' : F.B a → M F),
isubtree ps s₁ = M.mk ⟨a,f⟩ ∧
isubtree ps s₂ = M.mk ⟨a,f'⟩ ∧
∀ (i : F.B a), f i ~ f' i :=
begin
intros h₀ hh,
induction s₁ using pfunctor.M.cases_on' with a f,
induction s₂ using pfunctor.M.cases_on' with a' f',
have : a = a' := bisim.head h₀, subst a',
induction ps with i ps generalizing a f f',
{ existsi [rfl,a,f,f',rfl,rfl],
apply bisim.tail h₀ },
cases i with a' i,
have : a = a',
{ cases hh; cases is_path_cons hh; refl },
subst a', dsimp only [iselect] at ps_ih ⊢,
have h₁ := bisim.tail h₀ i,
induction h : (f i) using pfunctor.M.cases_on' with a₀ f₀,
induction h' : (f' i) using pfunctor.M.cases_on' with a₁ f₁,
simp only [h,h',isubtree_cons] at ps_ih ⊢,
rw [h,h'] at h₁,
have : a₀ = a₁ := bisim.head h₁, subst a₁,
apply (ps_ih _ _ _ h₁),
rw [← h,← h'], apply or_of_or_of_imp_of_imp hh is_path_cons' is_path_cons'
end
theorem eq_of_bisim [nonempty (M F)] (bisim : is_bisimulation R) : ∀ s₁ s₂, s₁ ~ s₂ → s₁ = s₂ :=
begin
inhabit (M F),
introv Hr, apply ext,
introv,
by_cases h : is_path ps s₁ ∨ is_path ps s₂,
{ have H := nth_of_bisim R bisim _ _ ps Hr h,
exact H.left },
{ rw not_or_distrib at h, cases h with h₀ h₁,
simp only [iselect_eq_default,*,not_false_iff] }
end
end bisim
universes u' v'
/-- corecursor for `M F` with swapped arguments -/
def corec_on {X : Type*} (x₀ : X) (f : X → F.obj X) : M F :=
M.corec f x₀
variables {P : pfunctor.{u}} {α : Type u}
lemma dest_corec (g : α → P.obj α) (x : α) :
M.dest (M.corec g x) = M.corec g <$> g x :=
by rw [corec_def,dest_mk]
lemma bisim (R : M P → M P → Prop)
(h : ∀ x y, R x y → ∃ a f f',
M.dest x = ⟨a, f⟩ ∧
M.dest y = ⟨a, f'⟩ ∧
∀ i, R (f i) (f' i)) :
∀ x y, R x y → x = y :=
begin
introv h',
haveI := inhabited.mk x.head,
apply eq_of_bisim R _ _ _ h', clear h' x y,
split; introv ih;
rcases h _ _ ih with ⟨ a'', g, g', h₀, h₁, h₂ ⟩; clear h,
{ replace h₀ := congr_arg sigma.fst h₀,
replace h₁ := congr_arg sigma.fst h₁,
simp only [dest_mk] at h₀ h₁,
rw [h₀,h₁], },
{ simp only [dest_mk] at h₀ h₁,
cases h₀, cases h₁,
apply h₂, },
end
theorem bisim' {α : Type*} (Q : α → Prop) (u v : α → M P)
(h : ∀ x, Q x → ∃ a f f',
M.dest (u x) = ⟨a, f⟩ ∧
M.dest (v x) = ⟨a, f'⟩ ∧
∀ i, ∃ x', Q x' ∧ f i = u x' ∧ f' i = v x') :
∀ x, Q x → u x = v x :=
λ x Qx,
let R := λ w z : M P, ∃ x', Q x' ∧ w = u x' ∧ z = v x' in
@M.bisim P R
(λ x y ⟨x', Qx', xeq, yeq⟩,
let ⟨a, f, f', ux'eq, vx'eq, h'⟩ := h x' Qx' in
⟨a, f, f', xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, h'⟩)
_ _ ⟨x, Qx, rfl, rfl⟩
-- for the record, show M_bisim follows from _bisim'
theorem bisim_equiv (R : M P → M P → Prop)
(h : ∀ x y, R x y → ∃ a f f',
M.dest x = ⟨a, f⟩ ∧
M.dest y = ⟨a, f'⟩ ∧
∀ i, R (f i) (f' i)) :
∀ x y, R x y → x = y :=
λ x y Rxy,
let Q : M P × M P → Prop := λ p, R p.fst p.snd in
bisim' Q prod.fst prod.snd
(λ p Qp,
let ⟨a, f, f', hx, hy, h'⟩ := h p.fst p.snd Qp in
⟨a, f, f', hx, hy, λ i, ⟨⟨f i, f' i⟩, h' i, rfl, rfl⟩⟩)
⟨x, y⟩ Rxy
theorem corec_unique (g : α → P.obj α) (f : α → M P)
(hyp : ∀ x, M.dest (f x) = f <$> (g x)) :
f = M.corec g :=
begin
ext x,
apply bisim' (λ x, true) _ _ _ _ trivial,
clear x,
intros x _,
cases gxeq : g x with a f',
have h₀ : M.dest (f x) = ⟨a, f ∘ f'⟩,
{ rw [hyp, gxeq, pfunctor.map_eq] },
have h₁ : M.dest (M.corec g x) = ⟨a, M.corec g ∘ f'⟩,
{ rw [dest_corec, gxeq, pfunctor.map_eq], },
refine ⟨_, _, _, h₀, h₁, _⟩,
intro i,
exact ⟨f' i, trivial, rfl, rfl⟩
end
/-- corecursor where the state of the computation can be sent downstream
in the form of a recursive call -/
def corec₁ {α : Type u} (F : Π X, (α → X) → α → P.obj 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' {α : Type u} (F : Π {X : Type u}, (α → X) → α → M P ⊕ P.obj X) (x : α) : M P :=
corec₁
(λ X rec (a : M P ⊕ α),
let y := a >>= F (rec ∘ sum.inr) in
match y with
| sum.inr y := y
| sum.inl y := (rec ∘ sum.inl) <$> M.dest y
end )
(@sum.inr (M P) _ x)
end M
end pfunctor
|
11d443763ec1853db5df4738958c0cdcbba46bb1
|
2eab05920d6eeb06665e1a6df77b3157354316ad
|
/src/computability/tm_to_partrec.lean
|
4c67003579f9d37fb55c3ce8bfb5e0325f9286b2
|
[
"Apache-2.0"
] |
permissive
|
ayush1801/mathlib
|
78949b9f789f488148142221606bf15c02b960d2
|
ce164e28f262acbb3de6281b3b03660a9f744e3c
|
refs/heads/master
| 1,692,886,907,941
| 1,635,270,866,000
| 1,635,270,866,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 64,484
|
lean
|
/-
Copyright (c) 2020 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import computability.halting
import computability.turing_machine
import data.num.lemmas
/-!
# Modelling partial recursive functions using Turing machines
This file defines a simplified basis for partial recursive functions, and a `turing.TM2` model
Turing machine for evaluating these functions. This amounts to a constructive proof that every
`partrec` function can be evaluated by a Turing machine.
## Main definitions
* `to_partrec.code`: a simplified basis for partial recursive functions, valued in
`list ℕ →. list ℕ`.
* `to_partrec.code.eval`: semantics for a `to_partrec.code` program
* `partrec_to_TM2.tr`: A TM2 turing machine which can evaluate `code` programs
-/
open function (update)
open relation
namespace turing
/-!
## A simplified basis for partrec
This section constructs the type `code`, which is a data type of programs with `list ℕ` input and
output, with enough expressivity to write any partial recursive function. The primitives are:
* `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`.
* `succ` returns the successor of the head of the input, defaulting to zero if there is no head:
* `succ [] = [1]`
* `succ (n :: v) = [n + 1]`
* `tail` returns the tail of the input
* `tail [] = []`
* `tail (n :: v) = v`
* `cons f fs` calls `f` and `fs` on the input and conses the results:
* `cons f fs v = (f v).head :: fs v`
* `comp f g` calls `f` on the output of `g`:
* `comp f g v = f (g v)`
* `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or
a successor (similar to `nat.cases_on`).
* `case f g [] = f []`
* `case f g (0 :: v) = f v`
* `case f g (n+1 :: v) = g (n :: v)`
* `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f`
again or finish:
* `fix f v = []` if `f v = []`
* `fix f v = w` if `f v = 0 :: w`
* `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded)
This basis is convenient because it is closer to the Turing machine model - the key operations are
splitting and merging of lists of unknown length, while the messy `n`-ary composition operation
from the traditional basis for partial recursive functions is absent - but it retains a
compositional semantics. The first step in transitioning to Turing machines is to make a sequential
evaluator for this basis, which we take up in the next section.
-/
namespace to_partrec
/-- The type of codes for primitive recursive functions. Unlike `nat.partrec.code`, this uses a set
of operations on `list ℕ`. See `code.eval` for a description of the behavior of the primitives. -/
@[derive inhabited]
inductive code
| zero'
| succ
| tail
| cons : code → code → code
| comp : code → code → code
| case : code → code → code
| fix : code → code
/-- The semantics of the `code` primitives, as partial functions `list ℕ →. list ℕ`. By convention
we functions that return a single result return a singleton `[n]`, or in some cases `n :: v` where
`v` will be ignored by a subsequent function.
* `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`.
* `succ` returns the successor of the head of the input, defaulting to zero if there is no head:
* `succ [] = [1]`
* `succ (n :: v) = [n + 1]`
* `tail` returns the tail of the input
* `tail [] = []`
* `tail (n :: v) = v`
* `cons f fs` calls `f` and `fs` on the input and conses the results:
* `cons f fs v = (f v).head :: fs v`
* `comp f g` calls `f` on the output of `g`:
* `comp f g v = f (g v)`
* `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or
a successor (similar to `nat.cases_on`).
* `case f g [] = f []`
* `case f g (0 :: v) = f v`
* `case f g (n+1 :: v) = g (n :: v)`
* `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f`
again or finish:
* `fix f v = []` if `f v = []`
* `fix f v = w` if `f v = 0 :: w`
* `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded)
-/
@[simp] def code.eval : code → list ℕ →. list ℕ
| code.zero' := λ v, pure (0 :: v)
| code.succ := λ v, pure [v.head.succ]
| code.tail := λ v, pure v.tail
| (code.cons f fs) := λ v, do n ← code.eval f v, ns ← code.eval fs v, pure (n.head :: ns)
| (code.comp f g) := λ v, g.eval v >>= f.eval
| (code.case f g) := λ v, v.head.elim (f.eval v.tail) (λ y _, g.eval (y :: v.tail))
| (code.fix f) := pfun.fix $ λ v, (f.eval v).map $ λ v,
if v.head = 0 then sum.inl v.tail else sum.inr v.tail
namespace code
/-- `nil` is the constant nil function: `nil v = []`. -/
def nil : code := tail.comp succ
@[simp] theorem nil_eval (v) : nil.eval v = pure [] := by simp [nil]
/-- `id` is the identity function: `id v = v`. -/
def id : code := tail.comp zero'
@[simp] theorem id_eval (v) : id.eval v = pure v := by simp [id]
/-- `head` gets the head of the input list: `head [] = [0]`, `head (n :: v) = [n]`. -/
def head : code := cons id nil
@[simp] theorem head_eval (v) : head.eval v = pure [v.head] := by simp [head]
/-- `zero` is the constant zero function: `zero v = [0]`. -/
def zero : code := cons zero' nil
@[simp] theorem zero_eval (v) : zero.eval v = pure [0] := by simp [zero]
/-- `pred` returns the predecessor of the head of the input:
`pred [] = [0]`, `pred (0 :: v) = [0]`, `pred (n+1 :: v) = [n]`. -/
def pred : code := case zero head
@[simp] theorem pred_eval (v) : pred.eval v = pure [v.head.pred] :=
by simp [pred]; cases v.head; simp
/-- `rfind f` performs the function of the `rfind` primitive of partial recursive functions.
`rfind f v` returns the smallest `n` such that `(f (n :: v)).head = 0`.
It is implemented as:
rfind f v = pred (fix (λ (n::v), f (n::v) :: n+1 :: v) (0 :: v))
The idea is that the initial state is `0 :: v`, and the `fix` keeps `n :: v` as its internal state;
it calls `f (n :: v)` as the exit test and `n+1 :: v` as the next state. At the end we get
`n+1 :: v` where `n` is the desired output, and `pred (n+1 :: v) = [n]` returns the result.
-/
def rfind (f : code) : code := comp pred $ comp (fix $ cons f $ cons succ tail) zero'
/-- `prec f g` implements the `prec` (primitive recursion) operation of partial recursive
functions. `prec f g` evaluates as:
* `prec f g [] = [f []]`
* `prec f g (0 :: v) = [f v]`
* `prec f g (n+1 :: v) = [g (n :: prec f g (n :: v) :: v)]`
It is implemented as:
G (a :: b :: IH :: v) = (b :: a+1 :: b-1 :: g (a :: IH :: v) :: v)
F (0 :: f_v :: v) = (f_v :: v)
F (n+1 :: f_v :: v) = (fix G (0 :: n :: f_v :: v)).tail.tail
prec f g (a :: v) = [(F (a :: f v :: v)).head]
Because `fix` always evaluates its body at least once, we must special case the `0` case to avoid
calling `g` more times than necessary (which could be bad if `g` diverges). If the input is
`0 :: v`, then `F (0 :: f v :: v) = (f v :: v)` so we return `[f v]`. If the input is `n+1 :: v`,
we evaluate the function from the bottom up, with initial state `0 :: n :: f v :: v`. The first
number counts up, providing arguments for the applications to `g`, while the second number counts
down, providing the exit condition (this is the initial `b` in the return value of `G`, which is
stripped by `fix`). After the `fix` is complete, the final state is `n :: 0 :: res :: v` where
`res` is the desired result, and the rest reduces this to `[res]`. -/
def prec (f g : code) : code :=
let G := cons tail $ cons succ $ cons (comp pred tail) $
cons (comp g $ cons id $ comp tail tail) $ comp tail $ comp tail tail in
let F := case id $ comp (comp (comp tail tail) (fix G)) zero' in
cons (comp F (cons head $ cons (comp f tail) tail)) nil
local attribute [-simp] part.bind_eq_bind part.map_eq_map part.pure_eq_some
theorem exists_code.comp {m n} {f : vector ℕ n →. ℕ} {g : fin n → vector ℕ m →. ℕ}
(hf : ∃ c : code, ∀ v : vector ℕ n, c.eval v.1 = pure <$> f v)
(hg : ∀ i, ∃ c : code, ∀ v : vector ℕ m, c.eval v.1 = pure <$> g i v) :
∃ c : code, ∀ v : vector ℕ m, c.eval v.1 = pure <$> (vector.m_of_fn (λ i, g i v) >>= f) :=
begin
suffices : ∃ c : code, ∀ v : vector ℕ m,
c.eval v.1 = subtype.val <$> vector.m_of_fn (λ i, g i v),
{ obtain ⟨cf, hf⟩ := hf, obtain ⟨cg, hg⟩ := this,
exact ⟨cf.comp cg, λ v,
by { simp [hg, hf, map_bind, seq_bind_eq, (∘), -subtype.val_eq_coe], refl }⟩ },
clear hf f, induction n with n IH,
{ exact ⟨nil, λ v, by simp [vector.m_of_fn]; refl⟩ },
{ obtain ⟨cg, hg₁⟩ := hg 0, obtain ⟨cl, hl⟩ := IH (λ i, hg i.succ),
exact ⟨cons cg cl, λ v, by { simp [vector.m_of_fn, hg₁, map_bind,
seq_bind_eq, bind_assoc, (∘), hl, -subtype.val_eq_coe], refl }⟩ },
end
theorem exists_code {n} {f : vector ℕ n →. ℕ} (hf : nat.partrec' f) :
∃ c : code, ∀ v : vector ℕ n, c.eval v.1 = pure <$> f v :=
begin
induction hf with n f hf,
induction hf,
case prim zero { exact ⟨zero', λ ⟨[], _⟩, rfl⟩ },
case prim succ { exact ⟨succ, λ ⟨[v], _⟩, rfl⟩ },
case prim nth : n i {
refine fin.succ_rec (λ n, _) (λ n i IH, _) i,
{ exact ⟨head, λ ⟨list.cons a as, _⟩, by simp; refl⟩ },
{ obtain ⟨c, h⟩ := IH,
exact ⟨c.comp tail, λ v, by simpa [← vector.nth_tail] using h v.tail⟩ } },
case prim comp : m n f g hf hg IHf IHg {
simpa [part.bind_eq_bind] using exists_code.comp IHf IHg },
case prim prec : n f g hf hg IHf IHg {
obtain ⟨cf, hf⟩ := IHf, obtain ⟨cg, hg⟩ := IHg,
simp only [part.map_eq_map, part.map_some, pfun.coe_val] at hf hg,
refine ⟨prec cf cg, λ v, _⟩, rw ← v.cons_head_tail,
specialize hf v.tail, replace hg := λ a b, hg (a ::ᵥ b ::ᵥ v.tail),
simp only [vector.cons_val, vector.tail_val] at hf hg,
simp only [part.map_eq_map, part.map_some, vector.cons_val,
vector.cons_tail, vector.cons_head, pfun.coe_val, vector.tail_val],
simp only [← part.pure_eq_some] at hf hg ⊢,
induction v.head with n IH; simp [prec, hf, bind_assoc, ← part.map_eq_map,
← bind_pure_comp_eq_map, show ∀ x, pure x = [x], from λ _, rfl, -subtype.val_eq_coe],
suffices : ∀ a b, a + b = n →
(n.succ :: 0 :: g
(n ::ᵥ (nat.elim (f v.tail) (λ y IH, g (y ::ᵥ IH ::ᵥ v.tail)) n) ::ᵥ v.tail)
:: v.val.tail : list ℕ) ∈
pfun.fix (λ v : list ℕ, do
x ← cg.eval (v.head :: v.tail.tail),
pure $ if v.tail.head = 0
then sum.inl (v.head.succ :: v.tail.head.pred :: x.head :: v.tail.tail.tail : list ℕ)
else sum.inr (v.head.succ :: v.tail.head.pred :: x.head :: v.tail.tail.tail))
(a :: b :: nat.elim (f v.tail)
(λ y IH, g (y ::ᵥ IH ::ᵥ v.tail)) a :: v.val.tail),
{ rw (_ : pfun.fix _ _ = pure _), swap, exact part.eq_some_iff.2 (this 0 n (zero_add n)),
simp only [list.head, pure_bind, list.tail_cons] },
intros a b e, induction b with b IH generalizing a e,
{ refine pfun.mem_fix_iff.2 (or.inl $ part.eq_some_iff.1 _),
simp only [hg, ← e, pure_bind, list.tail_cons], refl },
{ refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH (a+1) (by rwa add_right_comm)⟩),
simp only [hg, eval, pure_bind, nat.elim_succ, list.tail],
exact part.mem_some_iff.2 rfl } },
case comp : m n f g hf hg IHf IHg { exact exists_code.comp IHf IHg },
case rfind : n f hf IHf {
obtain ⟨cf, hf⟩ := IHf, refine ⟨rfind cf, λ v, _⟩,
replace hf := λ a, hf (a ::ᵥ v),
simp only [part.map_eq_map, part.map_some, vector.cons_val, pfun.coe_val,
show ∀ x, pure x = [x], from λ _, rfl] at hf ⊢,
refine part.ext (λ x, _),
simp only [rfind, part.bind_eq_bind, part.pure_eq_some, part.map_eq_map,
part.bind_some, exists_prop, eval, list.head, pred_eval, part.map_some,
bool.ff_eq_to_bool_iff, part.mem_bind_iff, list.length,
part.mem_map_iff, nat.mem_rfind, list.tail, bool.tt_eq_to_bool_iff,
part.mem_some_iff, part.map_bind],
split,
{ rintro ⟨v', h1, rfl⟩,
suffices : ∀ (v₁ : list ℕ), v' ∈ pfun.fix
(λ v, (cf.eval v).bind $ λ y, part.some $ if y.head = 0 then
sum.inl (v.head.succ :: v.tail) else sum.inr (v.head.succ :: v.tail)) v₁ →
∀ n, v₁ = n :: v.val → (∀ m < n, ¬f (m ::ᵥ v) = 0) →
(∃ (a : ℕ), (f (a ::ᵥ v) = 0 ∧ ∀ {m : ℕ}, m < a → ¬f (m ::ᵥ v) = 0) ∧
[a] = [v'.head.pred]),
{ exact this _ h1 0 rfl (by rintro _ ⟨⟩) },
clear h1, intros v₀ h1,
refine pfun.fix_induction h1 (λ v₁ h2 IH, _), clear h1,
rintro n rfl hm,
have := pfun.mem_fix_iff.1 h2,
simp only [hf, part.bind_some] at this,
split_ifs at this,
{ simp only [list.head, exists_false, or_false, part.mem_some_iff,
list.tail_cons, false_and] at this,
subst this, exact ⟨_, ⟨h, hm⟩, rfl⟩ },
{ simp only [list.head, exists_eq_left, part.mem_some_iff,
list.tail_cons, false_or] at this,
refine IH _ this (by simp [hf, h, -subtype.val_eq_coe]) _ rfl (λ m h', _),
obtain h|rfl := nat.lt_succ_iff_lt_or_eq.1 h', exacts [hm _ h, h] } },
{ rintro ⟨n, ⟨hn, hm⟩, rfl⟩, refine ⟨n.succ :: v.1, _, rfl⟩,
have : (n.succ :: v.1 : list ℕ) ∈ pfun.fix
(λ v, (cf.eval v).bind $ λ y, part.some $ if y.head = 0 then
sum.inl (v.head.succ :: v.tail) else sum.inr (v.head.succ :: v.tail)) (n :: v.val) :=
pfun.mem_fix_iff.2 (or.inl (by simp [hf, hn, -subtype.val_eq_coe])),
generalize_hyp : (n.succ :: v.1 : list ℕ) = w at this ⊢, clear hn,
induction n with n IH, {exact this},
refine IH (λ m h', hm (nat.lt_succ_of_lt h')) (pfun.mem_fix_iff.2 (or.inr ⟨_, _, this⟩)),
simp only [hf, hm n.lt_succ_self, part.bind_some, list.head, eq_self_iff_true,
if_false, part.mem_some_iff, and_self, list.tail_cons] } }
end
end code
/-!
## From compositional semantics to sequential semantics
Our initial sequential model is designed to be as similar as possible to the compositional
semantics in terms of its primitives, but it is a sequential semantics, meaning that rather than
defining an `eval c : list ℕ →. list ℕ` function for each program, defined by recursion on
programs, we have a type `cfg` with a step function `step : cfg → option cfg` that provides a
deterministic evaluation order. In order to do this, we introduce the notion of a *continuation*,
which can be viewed as a `code` with a hole in it where evaluation is currently taking place.
Continuations can be assigned a `list ℕ →. list ℕ` semantics as well, with the interpretation
being that given a `list ℕ` result returned from the code in the hole, the remainder of the
program will evaluate to a `list ℕ` final value.
The continuations are:
* `halt`: the empty continuation: the hole is the whole program, whatever is returned is the
final result. In our notation this is just `_`.
* `cons₁ fs v k`: evaluating the first part of a `cons`, that is `k (_ :: fs v)`, where `k` is the
outer continuation.
* `cons₂ ns k`: evaluating the second part of a `cons`: `k (ns.head :: _)`. (Technically we don't
need to hold on to all of `ns` here since we are already committed to taking the head, but this
is more regular.)
* `comp f k`: evaluating the first part of a composition: `k (f _)`.
* `fix f k`: waiting for the result of `f` in a `fix f` expression:
`k (if _.head = 0 then _.tail else fix f (_.tail))`
The type `cfg` of evaluation states is:
* `ret k v`: we have received a result, and are now evaluating the continuation `k` with result
`v`; that is, `k v` where `k` is ready to evaluate.
* `halt v`: we are done and the result is `v`.
The main theorem of this section is that for each code `c`, the state `step_normal c halt v` steps
to `v'` in finitely many steps if and only if `code.eval c v = some v'`.
-/
/-- The type of continuations, built up during evaluation of a `code` expression. -/
@[derive inhabited]
inductive cont
| halt
| cons₁ : code → list ℕ → cont → cont
| cons₂ : list ℕ → cont → cont
| comp : code → cont → cont
| fix : code → cont → cont
/-- The semantics of a continuation. -/
def cont.eval : cont → list ℕ →. list ℕ
| cont.halt := pure
| (cont.cons₁ fs as k) := λ v, do ns ← code.eval fs as, cont.eval k (v.head :: ns)
| (cont.cons₂ ns k) := λ v, cont.eval k (ns.head :: v)
| (cont.comp f k) := λ v, code.eval f v >>= cont.eval k
| (cont.fix f k) := λ v, if v.head = 0 then k.eval v.tail else f.fix.eval v.tail >>= k.eval
/-- The semantics of a continuation. -/
@[derive inhabited]
inductive cfg
| halt : list ℕ → cfg
| ret : cont → list ℕ → cfg
/-- Evaluating `c : code` in a continuation `k : cont` and input `v : list ℕ`. This goes by
recursion on `c`, building an augmented continuation and a value to pass to it.
* `zero' v = 0 :: v` evaluates immediately, so we return it to the parent continuation
* `succ v = [v.head.succ]` evaluates immediately, so we return it to the parent continuation
* `tail v = v.tail` evaluates immediately, so we return it to the parent continuation
* `cons f fs v = (f v).head :: fs v` requires two sub-evaluations, so we evaluate
`f v` in the continuation `k (_.head :: fs v)` (called `cont.cons₁ fs v k`)
* `comp f g v = f (g v)` requires two sub-evaluations, so we evaluate
`g v` in the continuation `k (f _)` (called `cont.comp f k`)
* `case f g v = v.head.cases_on (f v.tail) (λ n, g (n :: v.tail))` has the information needed to
evaluate the case statement, so we do that and transition to either `f v` or `g (n :: v.tail)`.
* `fix f v = let v' := f v in if v'.head = 0 then k v'.tail else fix f v'.tail`
needs to first evaluate `f v`, so we do that and leave the rest for the continuation (called
`cont.fix f k`)
-/
def step_normal : code → cont → list ℕ → cfg
| code.zero' k v := cfg.ret k (0 :: v)
| code.succ k v := cfg.ret k [v.head.succ]
| code.tail k v := cfg.ret k v.tail
| (code.cons f fs) k v := step_normal f (cont.cons₁ fs v k) v
| (code.comp f g) k v := step_normal g (cont.comp f k) v
| (code.case f g) k v :=
v.head.elim (step_normal f k v.tail) (λ y _, step_normal g k (y :: v.tail))
| (code.fix f) k v := step_normal f (cont.fix f k) v
/-- Evaluating a continuation `k : cont` on input `v : list ℕ`. This is the second part of
evaluation, when we receive results from continuations built by `step_normal`.
* `cont.halt v = v`, so we are done and transition to the `cfg.halt v` state
* `cont.cons₁ fs as k v = k (v.head :: fs as)`, so we evaluate `fs as` now with the continuation
`k (v.head :: _)` (called `cons₂ v k`).
* `cont.cons₂ ns k v = k (ns.head :: v)`, where we now have everything we need to evaluate
`ns.head :: v`, so we return it to `k`.
* `cont.comp f k v = k (f v)`, so we call `f v` with `k` as the continuation.
* `cont.fix f k v = k (if v.head = 0 then k v.tail else fix f v.tail)`, where `v` is a value,
so we evaluate the if statement and either call `k` with `v.tail`, or call `fix f v` with `k` as
the continuation (which immediately calls `f` with `cont.fix f k` as the continuation).
-/
def step_ret : cont → list ℕ → cfg
| cont.halt v := cfg.halt v
| (cont.cons₁ fs as k) v := step_normal fs (cont.cons₂ v k) as
| (cont.cons₂ ns k) v := step_ret k (ns.head :: v)
| (cont.comp f k) v := step_normal f k v
| (cont.fix f k) v := if v.head = 0 then step_ret k v.tail else
step_normal f (cont.fix f k) v.tail
/-- If we are not done (in `cfg.halt` state), then we must be still stuck on a continuation, so
this main loop calls `step_ret` with the new continuation. The overall `step` function transitions
from one `cfg` to another, only halting at the `cfg.halt` state. -/
def step : cfg → option cfg
| (cfg.halt _) := none
| (cfg.ret k v) := some (step_ret k v)
/-- In order to extract a compositional semantics from the sequential execution behavior of
configurations, we observe that continuations have a monoid structure, with `cont.halt` as the unit
and `cont.then` as the multiplication. `cont.then k₁ k₂` runs `k₁` until it halts, and then takes
the result of `k₁` and passes it to `k₂`.
We will not prove it is associative (although it is), but we are instead interested in the
associativity law `k₂ (eval c k₁) = eval c (k₁.then k₂)`. This holds at both the sequential and
compositional levels, and allows us to express running a machine without the ambient continuation
and relate it to the original machine's evaluation steps. In the literature this is usually
where one uses Turing machines embedded inside other Turing machines, but this approach allows us
to avoid changing the ambient type `cfg` in the middle of the recursion.
-/
def cont.then : cont → cont → cont
| cont.halt k' := k'
| (cont.cons₁ fs as k) k' := cont.cons₁ fs as (k.then k')
| (cont.cons₂ ns k) k' := cont.cons₂ ns (k.then k')
| (cont.comp f k) k' := cont.comp f (k.then k')
| (cont.fix f k) k' := cont.fix f (k.then k')
theorem cont.then_eval {k k' : cont} {v} : (k.then k').eval v = k.eval v >>= k'.eval :=
begin
induction k generalizing v; simp only [cont.eval, cont.then, bind_assoc, pure_bind, *],
{ simp only [← k_ih] },
{ split_ifs; [refl, simp only [← k_ih, bind_assoc]] }
end
/-- The `then k` function is a "configuration homomorphism". Its operation on states is to append
`k` to the continuation of a `cfg.ret` state, and to run `k` on `v` if we are in the `cfg.halt v`
state. -/
def cfg.then : cfg → cont → cfg
| (cfg.halt v) k' := step_ret k' v
| (cfg.ret k v) k' := cfg.ret (k.then k') v
/-- The `step_normal` function respects the `then k'` homomorphism. Note that this is an exact
equality, not a simulation; the original and embedded machines move in lock-step until the
embedded machine reaches the halt state. -/
theorem step_normal_then (c) (k k' : cont) (v) :
step_normal c (k.then k') v = (step_normal c k v).then k' :=
begin
induction c with generalizing k v;
simp only [cont.then, step_normal, cfg.then, *] {constructor_eq := ff},
case turing.to_partrec.code.cons : c c' ih ih'
{ rw [← ih, cont.then] },
case turing.to_partrec.code.comp : c c' ih ih'
{ rw [← ih', cont.then] },
{ cases v.head; simp only [nat.elim] },
case turing.to_partrec.code.fix : c ih
{ rw [← ih, cont.then] },
end
/-- The `step_ret` function respects the `then k'` homomorphism. Note that this is an exact
equality, not a simulation; the original and embedded machines move in lock-step until the
embedded machine reaches the halt state. -/
theorem step_ret_then {k k' : cont} {v} :
step_ret (k.then k') v = (step_ret k v).then k' :=
begin
induction k generalizing v;
simp only [cont.then, step_ret, cfg.then, *],
{ rw ← step_normal_then, refl },
{ rw ← step_normal_then },
{ split_ifs, {rw ← k_ih}, {rw ← step_normal_then, refl} },
end
/-- This is a temporary definition, because we will prove in `code_is_ok` that it always holds.
It asserts that `c` is semantically correct; that is, for any `k` and `v`,
`eval (step_normal c k v) = eval (cfg.ret k (code.eval c v))`, as an equality of partial values
(so one diverges iff the other does).
In particular, we can let `k = cont.halt`, and then this asserts that `step_normal c cont.halt v`
evaluates to `cfg.halt (code.eval c v)`. -/
def code.ok (c : code) :=
∀ k v, eval step (step_normal c k v) = code.eval c v >>= λ v, eval step (cfg.ret k v)
theorem code.ok.zero {c} (h : code.ok c) {v} :
eval step (step_normal c cont.halt v) = cfg.halt <$> code.eval c v :=
begin
rw [h, ← bind_pure_comp_eq_map], congr, funext v,
exact part.eq_some_iff.2 (mem_eval.2 ⟨refl_trans_gen.single rfl, rfl⟩),
end
theorem step_normal.is_ret (c k v) : ∃ k' v', step_normal c k v = cfg.ret k' v' :=
begin
induction c generalizing k v,
iterate 3 { exact ⟨_, _, rfl⟩ },
case cons : f fs IHf IHfs { apply IHf },
case comp : f g IHf IHg { apply IHg },
case case : f g IHf IHg {
rw step_normal, cases v.head; simp only [nat.elim]; [apply IHf, apply IHg] },
case fix : f IHf { apply IHf },
end
theorem cont_eval_fix {f k v} (fok : code.ok f) :
eval step (step_normal f (cont.fix f k) v) = f.fix.eval v >>= λ v, eval step (cfg.ret k v) :=
begin
refine part.ext (λ x, _),
simp only [part.bind_eq_bind, part.mem_bind_iff],
split,
{ suffices :
∀ c, x ∈ eval step c →
∀ v c', c = cfg.then c' (cont.fix f k) → reaches step (step_normal f cont.halt v) c' →
∃ v₁ ∈ f.eval v,
∃ v₂ ∈ (if list.head v₁ = 0 then pure v₁.tail else f.fix.eval v₁.tail),
x ∈ eval step (cfg.ret k v₂),
{ intro h,
obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ :=
this _ h _ _ (step_normal_then _ cont.halt _ _) refl_trans_gen.refl,
refine ⟨v₂, pfun.mem_fix_iff.2 _, h₃⟩,
simp only [part.eq_some_iff.2 hv₁, part.map_some],
split_ifs at hv₂ ⊢,
{ rw part.mem_some_iff.1 hv₂, exact or.inl (part.mem_some _) },
{ exact or.inr ⟨_, part.mem_some _, hv₂⟩ } },
refine λ c he, eval_induction he (λ y h IH, _),
rintro v (⟨v'⟩ | ⟨k',v'⟩) rfl hr; rw cfg.then at h IH,
{ have := mem_eval.2 ⟨hr, rfl⟩,
rw [fok, part.bind_eq_bind, part.mem_bind_iff] at this,
obtain ⟨v'', h₁, h₂⟩ := this,
rw reaches_eval at h₂, swap, exact refl_trans_gen.single rfl,
cases part.mem_unique h₂ (mem_eval.2 ⟨refl_trans_gen.refl, rfl⟩),
refine ⟨v', h₁, _⟩, rw [step_ret] at h,
revert h, by_cases he : v'.head = 0; simp only [exists_prop, if_pos, if_false, he]; intro h,
{ refine ⟨_, part.mem_some _, _⟩,
rw reaches_eval, exact h, exact refl_trans_gen.single rfl },
{ obtain ⟨k₀, v₀, e₀⟩ := step_normal.is_ret f cont.halt v'.tail,
have e₁ := step_normal_then f cont.halt (cont.fix f k) v'.tail,
rw [e₀, cont.then, cfg.then] at e₁,
obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ :=
IH (step_ret (k₀.then (cont.fix f k)) v₀) _ _ v'.tail _ step_ret_then _,
{ refine ⟨_, pfun.mem_fix_iff.2 _, h₃⟩,
simp only [part.eq_some_iff.2 hv₁, part.map_some, part.mem_some_iff],
split_ifs at hv₂ ⊢; [exact or.inl (part.mem_some_iff.1 hv₂),
exact or.inr ⟨_, rfl, hv₂⟩] },
{ rwa [← @reaches_eval _ _ (cfg.ret (k₀.then (cont.fix f k)) v₀), ← e₁],
exact refl_trans_gen.single rfl },
{ rw [step_ret, if_neg he, e₁], refl },
{ apply refl_trans_gen.single, rw e₀, exact rfl } } },
{ rw reaches_eval at h, swap, exact refl_trans_gen.single rfl,
exact IH _ h rfl _ _ step_ret_then (refl_trans_gen.tail hr rfl) } },
{ rintro ⟨v', he, hr⟩,
rw reaches_eval at hr, swap, exact refl_trans_gen.single rfl,
refine pfun.fix_induction he (λ v (he : v' ∈ f.fix.eval v) IH, _),
rw [fok, part.bind_eq_bind, part.mem_bind_iff],
obtain he | ⟨v'', he₁', he₂'⟩ := pfun.mem_fix_iff.1 he,
{ obtain ⟨v', he₁, he₂⟩ := (part.mem_map_iff _).1 he, split_ifs at he₂; cases he₂,
refine ⟨_, he₁, _⟩,
rw reaches_eval, swap, exact refl_trans_gen.single rfl,
rwa [step_ret, if_pos h] },
{ obtain ⟨v₁, he₁, he₂⟩ := (part.mem_map_iff _).1 he₁', split_ifs at he₂; cases he₂,
clear he₂ he₁', change _ ∈ f.fix.eval _ at he₂',
refine ⟨_, he₁, _⟩,
rw reaches_eval, swap, exact refl_trans_gen.single rfl,
rwa [step_ret, if_neg h],
exact IH v₁.tail he₂' ((part.mem_map_iff _).2 ⟨_, he₁, if_neg h⟩) } }
end
theorem code_is_ok (c) : code.ok c :=
begin
induction c; intros k v; rw step_normal,
iterate 3 { simp only [code.eval, pure_bind] },
case cons : f fs IHf IHfs {
rw [code.eval, IHf],
simp only [bind_assoc, cont.eval, pure_bind], congr, funext v,
rw [reaches_eval], swap, exact refl_trans_gen.single rfl,
rw [step_ret, IHfs], congr, funext v',
refine eq.trans _ (eq.symm _);
try {exact reaches_eval (refl_trans_gen.single rfl)} },
case comp : f g IHf IHg {
rw [code.eval, IHg],
simp only [bind_assoc, cont.eval, pure_bind], congr, funext v,
rw [reaches_eval], swap, exact refl_trans_gen.single rfl,
rw [step_ret, IHf] },
case case : f g IHf IHg {
simp only [code.eval], cases v.head; simp only [nat.elim, code.eval];
[apply IHf, apply IHg] },
case fix : f IHf { rw cont_eval_fix IHf },
end
theorem step_normal_eval (c v) : eval step (step_normal c cont.halt v) = cfg.halt <$> c.eval v :=
(code_is_ok c).zero
theorem step_ret_eval {k v} : eval step (step_ret k v) = cfg.halt <$> k.eval v :=
begin
induction k generalizing v,
case halt : {
simp only [mem_eval, cont.eval, map_pure],
exact part.eq_some_iff.2 (mem_eval.2 ⟨refl_trans_gen.refl, rfl⟩) },
case cons₁ : fs as k IH {
rw [cont.eval, step_ret, code_is_ok],
simp only [← bind_pure_comp_eq_map, bind_assoc], congr, funext v',
rw [reaches_eval], swap, exact refl_trans_gen.single rfl,
rw [step_ret, IH, bind_pure_comp_eq_map] },
case cons₂ : ns k IH { rw [cont.eval, step_ret], exact IH },
case comp : f k IH {
rw [cont.eval, step_ret, code_is_ok],
simp only [← bind_pure_comp_eq_map, bind_assoc], congr, funext v',
rw [reaches_eval], swap, exact refl_trans_gen.single rfl,
rw [IH, bind_pure_comp_eq_map] },
case fix : f k IH {
rw [cont.eval, step_ret], simp only [bind_pure_comp_eq_map],
split_ifs, { exact IH },
simp only [← bind_pure_comp_eq_map, bind_assoc, cont_eval_fix (code_is_ok _)],
congr, funext, rw [bind_pure_comp_eq_map, ← IH],
exact reaches_eval (refl_trans_gen.single rfl) },
end
end to_partrec
/-!
## Simulating sequentialized partial recursive functions in TM2
At this point we have a sequential model of partial recursive functions: the `cfg` type and
`step : cfg → option cfg` function from the previous section. The key feature of this model is that
it does a finite amount of computation (in fact, an amount which is statically bounded by the size
of the program) between each step, and no individual step can diverge (unlike the compositional
semantics, where every sub-part of the computation is potentially divergent). So we can utilize the
same techniques as in the other TM simulations in `computability.turing_machine` to prove that
each step corresponds to a finite number of steps in a lower level model. (We don't prove it here,
but in anticipation of the complexity class P, the simulation is actually polynomial-time as well.)
The target model is `turing.TM2`, which has a fixed finite set of stacks, a bit of local storage,
with programs selected from a potentially infinite (but finitely accessible) set of program
positions, or labels `Λ`, each of which executes a finite sequence of basic stack commands.
For this program we will need four stacks, each on an alphabet `Γ'` like so:
inductive Γ' | Cons | cons | bit0 | bit1
We represent a number as a bit sequence, lists of numbers by putting `cons` after each element, and
lists of lists of natural numbers by putting `Cons` after each list. For example:
0 ~> []
1 ~> [bit1]
6 ~> [bit0, bit1, bit1]
[1, 2] ~> [bit1, cons, bit0, bit1, cons]
[[], [1, 2]] ~> [Cons, bit1, cons, bit0, bit1, cons, Cons]
The four stacks are `main`, `rev`, `aux`, `stack`. In normal mode, `main` contains the input to the
current program (a `list ℕ`) and `stack` contains data (a `list (list ℕ)`) associated to the
current continuation, and in `ret` mode `main` contains the value that is being passed to the
continuation and `stack` contains the data for the continuation. The `rev` and `aux` stacks are
usually empty; `rev` is used to store reversed data when e.g. moving a value from one stack to
another, while `aux` is used as a temporary for a `main`/`stack` swap that happens during `cons₁`
evaluation.
The only local store we need is `option Γ'`, which stores the result of the last pop
operation. (Most of our working data are natural numbers, which are too large to fit in the local
store.)
The continuations from the previous section are data-carrying, containing all the values that have
been computed and are awaiting other arguments. In order to have only a finite number of
continuations appear in the program so that they can be used in machine states, we separate the
data part (anything with type `list ℕ`) from the `cont` type, producing a `cont'` type that lacks
this information. The data is kept on the `stack` stack.
Because we want to have subroutines for e.g. moving an entire stack to another place, we use an
infinite inductive type `Λ'` so that we can execute a program and then return to do something else
without having to define too many different kinds of intermediate states. (We must nevertheless
prove that only finitely many labels are accessible.) The labels are:
* `move p k₁ k₂ q`: move elements from stack `k₁` to `k₂` while `p` holds of the value being moved.
The last element, that fails `p`, is placed in neither stack but left in the local store.
At the end of the operation, `k₂` will have the elements of `k₁` in reverse order. Then do `q`.
* `clear p k q`: delete elements from stack `k` until `p` is true. Like `move`, the last element is
left in the local storage. Then do `q`.
* `copy q`: Move all elements from `rev` to both `main` and `stack` (in reverse order),
then do `q`. That is, it takes `(a, b, c, d)` to `(b.reverse ++ a, [], c, b.reverse ++ d)`.
* `push k f q`: push `f s`, where `s` is the local store, to stack `k`, then do `q`. This is a
duplicate of the `push` instruction that is part of the TM2 model, but by having a subroutine
just for this purpose we can build up programs to execute inside a `goto` statement, where we
have the flexibility to be general recursive.
* `read (f : option Γ' → Λ')`: go to state `f s` where `s` is the local store. Again this is only
here for convenience.
* `succ q`: perform a successor operation. Assuming `[n]` is encoded on `main` before,
`[n+1]` will be on main after. This implements successor for binary natural numbers.
* `pred q₁ q₂`: perform a predecessor operation or `case` statement. If `[]` is encoded on
`main` before, then we transition to `q₁` with `[]` on main; if `(0 :: v)` is on `main` before
then `v` will be on `main` after and we transition to `q₁`; and if `(n+1 :: v)` is on `main`
before then `n :: v` will be on `main` after and we transition to `q₂`.
* `ret k`: call continuation `k`. Each continuation has its own interpretation of the data in
`stack` and sets up the data for the next continuation.
* `ret (cons₁ fs k)`: `v :: k_data` on `stack` and `ns` on `main`, and the next step expects
`v` on `main` and `ns :: k_data` on `stack`. So we have to do a little dance here with six
reverse-moves using the `aux` stack to perform a three-point swap, each of which involves two
reversals.
* `ret (cons₂ k)`: `ns :: k_data` is on `stack` and `v` is on `main`, and we have to put
`ns.head :: v` on `main` and `k_data` on `stack`. This is done using the `head` subroutine.
* `ret (fix f k)`: This stores no data, so we just check if `main` starts with `0` and
if so, remove it and call `k`, otherwise `clear` the first value and call `f`.
* `ret halt`: the stack is empty, and `main` has the output. Do nothing and halt.
In addition to these basic states, we define some additional subroutines that are used in the
above:
* `push'`, `peek'`, `pop'` are special versions of the builtins that use the local store to supply
inputs and outputs.
* `unrev`: special case `move ff rev main` to move everything from `rev` back to `main`. Used as a
cleanup operation in several functions.
* `move_excl p k₁ k₂ q`: same as `move` but pushes the last value read back onto the source stack.
* `move₂ p k₁ k₂ q`: double `move`, so that the result comes out in the right order at the target
stack. Implemented as `move_excl p k rev; move ff rev k₂`. Assumes that neither `k₁` nor `k₂` is
`rev` and `rev` is initially empty.
* `head k q`: get the first natural number from stack `k` and reverse-move it to `rev`, then clear
the rest of the list at `k` and then `unrev` to reverse-move the head value to `main`. This is
used with `k = main` to implement regular `head`, i.e. if `v` is on `main` before then `[v.head]`
will be on `main` after; and also with `k = stack` for the `cons` operation, which has `v` on
`main` and `ns :: k_data` on `stack`, and results in `k_data` on `stack` and `ns.head :: v` on
`main`.
* `tr_normal` is the main entry point, defining states that perform a given `code` computation.
It mostly just dispatches to functions written above.
The main theorem of this section is `tr_eval`, which asserts that for each that for each code `c`,
the state `init c v` steps to `halt v'` in finitely many steps if and only if
`code.eval c v = some v'`.
-/
namespace partrec_to_TM2
section
open to_partrec
/-- The alphabet for the stacks in the program. `bit0` and `bit1` are used to represent `ℕ` values
as lists of binary digits, `cons` is used to separate `list ℕ` values, and `Cons` is used to
separate `list (list ℕ)` values. See the section documentation. -/
@[derive [decidable_eq, inhabited]]
inductive Γ' | Cons | cons | bit0 | bit1
/-- The four stacks used by the program. `main` is used to store the input value in `tr_normal`
mode and the output value in `Λ'.ret` mode, while `stack` is used to keep all the data for the
continuations. `rev` is used to store reversed lists when transferring values between stacks, and
`aux` is only used once in `cons₁`. See the section documentation. -/
@[derive [decidable_eq, inhabited]]
inductive K' | main | rev | aux | stack
open K'
/-- Continuations as in `to_partrec.cont` but with the data removed. This is done because we want
the set of all continuations in the program to be finite (so that it can ultimately be encoded into
the finite state machine of a Turing machine), but a continuation can handle a potentially infinite
number of data values during execution. -/
@[derive inhabited]
inductive cont'
| halt
| cons₁ : code → cont' → cont'
| cons₂ : cont' → cont'
| comp : code → cont' → cont'
| fix : code → cont' → cont'
/-- The set of program positions. We make extensive use of inductive types here to let us describe
"subroutines"; for example `clear p k q` is a program that clears stack `k`, then does `q` where
`q` is another label. In order to prevent this from resulting in an infinite number of distinct
accessible states, we are careful to be non-recursive (although loops are okay). See the section
documentation for a description of all the programs. -/
inductive Λ'
| move (p : Γ' → bool) (k₁ k₂ : K') (q : Λ')
| clear (p : Γ' → bool) (k : K') (q : Λ')
| copy (q : Λ')
| push (k : K') (s : option Γ' → option Γ') (q : Λ')
| read (f : option Γ' → Λ')
| succ (q : Λ')
| pred (q₁ q₂ : Λ')
| ret (k : cont')
instance : inhabited Λ' := ⟨Λ'.ret cont'.halt⟩
/-- The type of TM2 statements used by this machine. -/
@[derive inhabited]
def stmt' := TM2.stmt (λ _:K', Γ') Λ' (option Γ')
/-- The type of TM2 configurations used by this machine. -/
@[derive inhabited]
def cfg' := TM2.cfg (λ _:K', Γ') Λ' (option Γ')
open TM2.stmt
/-- A predicate that detects the end of a natural number, either `Γ'.cons` or `Γ'.Cons` (or
implicitly the end of the list), for use in predicate-taking functions like `move` and `clear`. -/
def nat_end : Γ' → bool
| Γ'.Cons := tt
| Γ'.cons := tt
| _ := ff
/-- Pop a value from the stack and place the result in local store. -/
@[simp] def pop' (k : K') : stmt' → stmt' := pop k (λ x v, v)
/-- Peek a value from the stack and place the result in local store. -/
@[simp] def peek' (k : K') : stmt' → stmt' := peek k (λ x v, v)
/-- Push the value in the local store to the given stack. -/
@[simp] def push' (k : K') : stmt' → stmt' := push k (λ x, x.iget)
/-- Move everything from the `rev` stack to the `main` stack (reversed). -/
def unrev := Λ'.move (λ _, ff) rev main
/-- Move elements from `k₁` to `k₂` while `p` holds, with the last element being left on `k₁`. -/
def move_excl (p k₁ k₂ q) :=
Λ'.move p k₁ k₂ $ Λ'.push k₁ id q
/-- Move elements from `k₁` to `k₂` without reversion, by performing a double move via the `rev`
stack. -/
def move₂ (p k₁ k₂ q) := move_excl p k₁ rev $ Λ'.move (λ _, ff) rev k₂ q
/-- Assuming `tr_list v` is on the front of stack `k`, remove it, and push `v.head` onto `main`.
See the section documentation. -/
def head (k : K') (q : Λ') : Λ' :=
Λ'.move nat_end k rev $
Λ'.push rev (λ _, some Γ'.cons) $
Λ'.read $ λ s,
(if s = some Γ'.Cons then id else Λ'.clear (λ x, x = Γ'.Cons) k) $
unrev q
/-- The program that evaluates code `c` with continuation `k`. This expects an initial state where
`tr_list v` is on `main`, `tr_cont_stack k` is on `stack`, and `aux` and `rev` are empty.
See the section documentation for details. -/
@[simp] def tr_normal : code → cont' → Λ'
| code.zero' k := Λ'.push main (λ _, some Γ'.cons) $ Λ'.ret k
| code.succ k := head main $ Λ'.succ $ Λ'.ret k
| code.tail k := Λ'.clear nat_end main $ Λ'.ret k
| (code.cons f fs) k :=
Λ'.push stack (λ _, some Γ'.Cons) $
Λ'.move (λ _, ff) main rev $ Λ'.copy $
tr_normal f (cont'.cons₁ fs k)
| (code.comp f g) k := tr_normal g (cont'.comp f k)
| (code.case f g) k := Λ'.pred (tr_normal f k) (tr_normal g k)
| (code.fix f) k := tr_normal f (cont'.fix f k)
/-- The main program. See the section documentation for details. -/
@[simp] def tr : Λ' → stmt'
| (Λ'.move p k₁ k₂ q) :=
pop' k₁ $ branch (λ s, s.elim tt p)
( goto $ λ _, q )
( push' k₂ $ goto $ λ _, Λ'.move p k₁ k₂ q )
| (Λ'.push k f q) :=
branch (λ s, (f s).is_some)
( push k (λ s, (f s).iget) $ goto $ λ _, q )
( goto $ λ _, q )
| (Λ'.read q) := goto q
| (Λ'.clear p k q) :=
pop' k $ branch (λ s, s.elim tt p)
( goto $ λ _, q )
( goto $ λ _, Λ'.clear p k q )
| (Λ'.copy q) :=
pop' rev $ branch option.is_some
( push' main $ push' stack $ goto $ λ _, Λ'.copy q )
( goto $ λ _, q )
| (Λ'.succ q) :=
pop' main $ branch (λ s, s = some Γ'.bit1)
( push rev (λ _, Γ'.bit0) $
goto $ λ _, Λ'.succ q ) $
branch (λ s, s = some Γ'.cons)
( push main (λ _, Γ'.cons) $
push main (λ _, Γ'.bit1) $
goto $ λ _, unrev q )
( push main (λ _, Γ'.bit1) $
goto $ λ _, unrev q )
| (Λ'.pred q₁ q₂) :=
pop' main $ branch (λ s, s = some Γ'.bit0)
( push rev (λ _, Γ'.bit1) $
goto $ λ _, Λ'.pred q₁ q₂ ) $
branch (λ s, nat_end s.iget)
( goto $ λ _, q₁ )
( peek' main $ branch (λ s, nat_end s.iget)
( goto $ λ _, unrev q₂ )
( push rev (λ _, Γ'.bit0) $
goto $ λ _, unrev q₂ ) )
| (Λ'.ret (cont'.cons₁ fs k)) := goto $ λ _,
move₂ (λ _, ff) main aux $
move₂ (λ s, s = Γ'.Cons) stack main $
move₂ (λ _, ff) aux stack $
tr_normal fs (cont'.cons₂ k)
| (Λ'.ret (cont'.cons₂ k)) := goto $ λ _, head stack $ Λ'.ret k
| (Λ'.ret (cont'.comp f k)) := goto $ λ _, tr_normal f k
| (Λ'.ret (cont'.fix f k)) :=
pop' main $ goto $ λ s,
cond (nat_end s.iget) (Λ'.ret k) $
Λ'.clear nat_end main $ tr_normal f (cont'.fix f k)
| (Λ'.ret cont'.halt) := load (λ _, none) $ halt
/-- Translating a `cont` continuation to a `cont'` continuation simply entails dropping all the
data. This data is instead encoded in `tr_cont_stack` in the configuration. -/
def tr_cont : cont → cont'
| cont.halt := cont'.halt
| (cont.cons₁ c _ k) := cont'.cons₁ c (tr_cont k)
| (cont.cons₂ _ k) := cont'.cons₂ (tr_cont k)
| (cont.comp c k) := cont'.comp c (tr_cont k)
| (cont.fix c k) := cont'.fix c (tr_cont k)
/-- We use `pos_num` to define the translation of binary natural numbers. A natural number is
represented as a little-endian list of `bit0` and `bit1` elements:
1 = [bit1]
2 = [bit0, bit1]
3 = [bit1, bit1]
4 = [bit0, bit0, bit1]
In particular, this representation guarantees no trailing `bit0`'s at the end of the list. -/
def tr_pos_num : pos_num → list Γ'
| pos_num.one := [Γ'.bit1]
| (pos_num.bit0 n) := Γ'.bit0 :: tr_pos_num n
| (pos_num.bit1 n) := Γ'.bit1 :: tr_pos_num n
/-- We use `num` to define the translation of binary natural numbers. Positive numbers are
translated using `tr_pos_num`, and `tr_num 0 = []`. So there are never any trailing `bit0`'s in
a translated `num`.
0 = []
1 = [bit1]
2 = [bit0, bit1]
3 = [bit1, bit1]
4 = [bit0, bit0, bit1]
-/
def tr_num : num → list Γ'
| num.zero := []
| (num.pos n) := tr_pos_num n
/-- Because we use binary encoding, we define `tr_nat` in terms of `tr_num`, using `num`, which are
binary natural numbers. (We could also use `nat.binary_rec_on`, but `num` and `pos_num` make for
easy inductions.) -/
def tr_nat (n : ℕ) : list Γ' := tr_num n
@[simp] theorem tr_nat_zero : tr_nat 0 = [] := rfl
/-- Lists are translated with a `cons` after each encoded number.
For example:
[] = []
[0] = [cons]
[1] = [bit1, cons]
[6, 0] = [bit0, bit1, bit1, cons, cons]
-/
@[simp] def tr_list : list ℕ → list Γ'
| [] := []
| (n :: ns) := tr_nat n ++ Γ'.cons :: tr_list ns
/-- Lists of lists are translated with a `Cons` after each encoded list.
For example:
[] = []
[[]] = [Cons]
[[], []] = [Cons, Cons]
[[0]] = [cons, Cons]
[[1, 2], [0]] = [bit1, cons, bit0, bit1, cons, Cons, cons, Cons]
-/
@[simp] def tr_llist : list (list ℕ) → list Γ'
| [] := []
| (l :: ls) := tr_list l ++ Γ'.Cons :: tr_llist ls
/-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack
using `tr_llist`. -/
@[simp] def cont_stack : cont → list (list ℕ)
| cont.halt := []
| (cont.cons₁ _ ns k) := ns :: cont_stack k
| (cont.cons₂ ns k) := ns :: cont_stack k
| (cont.comp _ k) := cont_stack k
| (cont.fix _ k) := cont_stack k
/-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack
using `tr_llist`. -/
def tr_cont_stack (k : cont) := tr_llist (cont_stack k)
/-- This is the nondependent eliminator for `K'`, but we use it specifically here in order to
represent the stack data as four lists rather than as a function `K' → list Γ'`, because this makes
rewrites easier. The theorems `K'.elim_update_main` et. al. show how such a function is updated
after an `update` to one of the components. -/
@[simp] def K'.elim (a b c d : list Γ') : K' → list Γ'
| K'.main := a
| K'.rev := b
| K'.aux := c
| K'.stack := d
@[simp] theorem K'.elim_update_main {a b c d a'} :
update (K'.elim a b c d) main a' = K'.elim a' b c d := by funext x; cases x; refl
@[simp] theorem K'.elim_update_rev {a b c d b'} :
update (K'.elim a b c d) rev b' = K'.elim a b' c d := by funext x; cases x; refl
@[simp] theorem K'.elim_update_aux {a b c d c'} :
update (K'.elim a b c d) aux c' = K'.elim a b c' d := by funext x; cases x; refl
@[simp] theorem K'.elim_update_stack {a b c d d'} :
update (K'.elim a b c d) stack d' = K'.elim a b c d' := by funext x; cases x; refl
/-- The halting state corresponding to a `list ℕ` output value. -/
def halt (v : list ℕ) : cfg' := ⟨none, none, K'.elim (tr_list v) [] [] []⟩
/-- The `cfg` states map to `cfg'` states almost one to one, except that in normal operation the
local store contains an arbitrary garbage value. To make the final theorem cleaner we explicitly
clear it in the halt state so that there is exactly one configuration corresponding to output `v`.
-/
def tr_cfg : cfg → cfg' → Prop
| (cfg.ret k v) c' := ∃ s, c' =
⟨some (Λ'.ret (tr_cont k)), s, K'.elim (tr_list v) [] [] (tr_cont_stack k)⟩
| (cfg.halt v) c' := c' = halt v
/-- This could be a general list definition, but it is also somewhat specialized to this
application. `split_at_pred p L` will search `L` for the first element satisfying `p`.
If it is found, say `L = l₁ ++ a :: l₂` where `a` satisfies `p` but `l₁` does not, then it returns
`(l₁, some a, l₂)`. Otherwise, if there is no such element, it returns `(L, none, [])`. -/
def split_at_pred {α} (p : α → bool) : list α → list α × option α × list α
| [] := ([], none, [])
| (a :: as) := cond (p a) ([], some a, as) $
let ⟨l₁, o, l₂⟩ := split_at_pred as in ⟨a :: l₁, o, l₂⟩
theorem split_at_pred_eq {α} (p : α → bool) : ∀ L l₁ o l₂,
(∀ x ∈ l₁, p x = ff) →
option.elim o (L = l₁ ∧ l₂ = []) (λ a, p a = tt ∧ L = l₁ ++ a :: l₂) →
split_at_pred p L = (l₁, o, l₂)
| [] _ none _ _ ⟨rfl, rfl⟩ := rfl
| [] l₁ (some o) l₂ h₁ ⟨h₂, h₃⟩ := by simp at h₃; contradiction
| (a :: L) l₁ o l₂ h₁ h₂ := begin
rw [split_at_pred],
have IH := split_at_pred_eq L,
cases o,
{ cases l₁ with a' l₁; rcases h₂ with ⟨⟨⟩, rfl⟩,
rw [h₁ a (or.inl rfl), cond, IH L none [] _ ⟨rfl, rfl⟩], refl,
exact λ x h, h₁ x (or.inr h) },
{ cases l₁ with a' l₁; rcases h₂ with ⟨h₂, ⟨⟩⟩, {rw [h₂, cond]},
rw [h₁ a (or.inl rfl), cond, IH l₁ (some o) l₂ _ ⟨h₂, _⟩]; try {refl},
exact λ x h, h₁ x (or.inr h) },
end
theorem split_at_pred_ff {α} (L : list α) : split_at_pred (λ _, ff) L = (L, none, []) :=
split_at_pred_eq _ _ _ _ _ (λ _ _, rfl) ⟨rfl, rfl⟩
theorem move_ok {p k₁ k₂ q s L₁ o L₂} {S : K' → list Γ'}
(h₁ : k₁ ≠ k₂) (e : split_at_pred p (S k₁) = (L₁, o, L₂)) :
reaches₁ (TM2.step tr)
⟨some (Λ'.move p k₁ k₂ q), s, S⟩
⟨some q, o, update (update S k₁ L₂) k₂ (L₁.reverse_core (S k₂))⟩ :=
begin
induction L₁ with a L₁ IH generalizing S s,
{ rw [(_ : [].reverse_core _ = _), function.update_eq_self],
swap, { rw function.update_noteq h₁.symm, refl },
refine trans_gen.head' rfl _,
simp, cases S k₁ with a Sk, {cases e, refl},
simp [split_at_pred] at e ⊢,
cases p a; simp at e ⊢,
{ revert e, rcases split_at_pred p Sk with ⟨_, _, _⟩, rintro ⟨⟩ },
{ simp only [e] } },
{ refine trans_gen.head rfl _, simp,
cases e₁ : S k₁ with a' Sk; rw [e₁, split_at_pred] at e, {cases e},
cases e₂ : p a'; simp only [e₂, cond] at e, swap, {cases e},
rcases e₃ : split_at_pred p Sk with ⟨_, _, _⟩, rw [e₃, split_at_pred] at e, cases e,
simp [e₂],
convert @IH (update (update S k₁ Sk) k₂ (a :: S k₂)) _ _ using 2;
simp [function.update_noteq, h₁, h₁.symm, e₃, list.reverse_core],
simp [function.update_comm h₁.symm] }
end
theorem unrev_ok {q s} {S : K' → list Γ'} :
reaches₁ (TM2.step tr) ⟨some (unrev q), s, S⟩
⟨some q, none, update (update S rev []) main (list.reverse_core (S rev) (S main))⟩ :=
move_ok dec_trivial $ split_at_pred_ff _
theorem move₂_ok {p k₁ k₂ q s L₁ o L₂} {S : K' → list Γ'}
(h₁ : k₁ ≠ rev ∧ k₂ ≠ rev ∧ k₁ ≠ k₂) (h₂ : S rev = [])
(e : split_at_pred p (S k₁) = (L₁, o, L₂)) :
reaches₁ (TM2.step tr)
⟨some (move₂ p k₁ k₂ q), s, S⟩
⟨some q, none, update (update S k₁ (o.elim id list.cons L₂)) k₂ (L₁ ++ S k₂)⟩ :=
begin
refine (move_ok h₁.1 e).trans (trans_gen.head rfl _),
cases o; simp only [option.elim, tr, id.def],
{ convert move_ok h₁.2.1.symm (split_at_pred_ff _) using 2,
simp only [function.update_comm h₁.1, function.update_idem],
rw show update S rev [] = S, by rw [← h₂, function.update_eq_self],
simp only [function.update_noteq h₁.2.2.symm, function.update_noteq h₁.2.1,
function.update_noteq h₁.1.symm, list.reverse_core_eq, h₂,
function.update_same, list.append_nil, list.reverse_reverse] },
{ convert move_ok h₁.2.1.symm (split_at_pred_ff _) using 2,
simp only [h₂, function.update_comm h₁.1,
list.reverse_core_eq, function.update_same, list.append_nil, function.update_idem],
rw show update S rev [] = S, by rw [← h₂, function.update_eq_self],
simp only [function.update_noteq h₁.1.symm,
function.update_noteq h₁.2.2.symm, function.update_noteq h₁.2.1,
function.update_same, list.reverse_reverse] },
end
theorem clear_ok {p k q s L₁ o L₂} {S : K' → list Γ'}
(e : split_at_pred p (S k) = (L₁, o, L₂)) :
reaches₁ (TM2.step tr) ⟨some (Λ'.clear p k q), s, S⟩ ⟨some q, o, update S k L₂⟩ :=
begin
induction L₁ with a L₁ IH generalizing S s,
{ refine trans_gen.head' rfl _,
simp, cases S k with a Sk, {cases e, refl},
simp [split_at_pred] at e ⊢,
cases p a; simp at e ⊢,
{ revert e, rcases split_at_pred p Sk with ⟨_, _, _⟩, rintro ⟨⟩ },
{ simp only [e] } },
{ refine trans_gen.head rfl _, simp,
cases e₁ : S k with a' Sk; rw [e₁, split_at_pred] at e, {cases e},
cases e₂ : p a'; simp only [e₂, cond] at e, swap, {cases e},
rcases e₃ : split_at_pred p Sk with ⟨_, _, _⟩, rw [e₃, split_at_pred] at e, cases e,
simp [e₂],
convert @IH (update S k Sk) _ _ using 2; simp [e₃] }
end
theorem copy_ok (q s a b c d) :
reaches₁ (TM2.step tr)
⟨some (Λ'.copy q), s, K'.elim a b c d⟩
⟨some q, none, K'.elim (list.reverse_core b a) [] c (list.reverse_core b d)⟩ :=
begin
induction b with x b IH generalizing a d s,
{ refine trans_gen.single _, simp, refl },
refine trans_gen.head rfl _, simp, exact IH _ _ _,
end
theorem tr_pos_num_nat_end : ∀ n (x ∈ tr_pos_num n), nat_end x = ff
| pos_num.one _ (or.inl rfl) := rfl
| (pos_num.bit0 n) _ (or.inl rfl) := rfl
| (pos_num.bit0 n) _ (or.inr h) := tr_pos_num_nat_end n _ h
| (pos_num.bit1 n) _ (or.inl rfl) := rfl
| (pos_num.bit1 n) _ (or.inr h) := tr_pos_num_nat_end n _ h
theorem tr_num_nat_end : ∀ n (x ∈ tr_num n), nat_end x = ff
| (num.pos n) x h := tr_pos_num_nat_end n x h
theorem tr_nat_nat_end (n) : ∀ x ∈ tr_nat n, nat_end x = ff := tr_num_nat_end _
theorem tr_list_ne_Cons : ∀ l (x ∈ tr_list l), x ≠ Γ'.Cons
| (a :: l) x h := begin
simp [tr_list] at h,
obtain h | rfl | h := h,
{ rintro rfl, cases tr_nat_nat_end _ _ h },
{ rintro ⟨⟩ },
{ exact tr_list_ne_Cons l _ h }
end
theorem head_main_ok {q s L} {c d : list Γ'} :
reaches₁ (TM2.step tr)
⟨some (head main q), s, K'.elim (tr_list L) [] c d⟩
⟨some q, none, K'.elim (tr_list [L.head]) [] c d⟩ :=
begin
let o : option Γ' := list.cases_on L none (λ _ _, some Γ'.cons),
refine (move_ok dec_trivial
(split_at_pred_eq _ _ (tr_nat L.head) o (tr_list L.tail) (tr_nat_nat_end _) _)).trans
(trans_gen.head rfl (trans_gen.head rfl _)),
{ cases L; exact ⟨rfl, rfl⟩ },
simp [show o ≠ some Γ'.Cons, by cases L; rintro ⟨⟩],
refine (clear_ok (split_at_pred_eq _ _ _ none [] _ ⟨rfl, rfl⟩)).trans _,
{ exact λ x h, (to_bool_ff (tr_list_ne_Cons _ _ h)) },
convert unrev_ok, simp [list.reverse_core_eq],
end
theorem head_stack_ok {q s L₁ L₂ L₃} :
reaches₁ (TM2.step tr)
⟨some (head stack q), s, K'.elim (tr_list L₁) [] [] (tr_list L₂ ++ Γ'.Cons :: L₃)⟩
⟨some q, none, K'.elim (tr_list (L₂.head :: L₁)) [] [] L₃⟩ :=
begin
cases L₂ with a L₂,
{ refine trans_gen.trans (move_ok dec_trivial
(split_at_pred_eq _ _ [] (some Γ'.Cons) L₃ (by rintro _ ⟨⟩) ⟨rfl, rfl⟩))
(trans_gen.head rfl (trans_gen.head rfl _)),
convert unrev_ok, simp, refl },
{ refine trans_gen.trans (move_ok dec_trivial
(split_at_pred_eq _ _ (tr_nat a) (some Γ'.cons)
(tr_list L₂ ++ Γ'.Cons :: L₃) (tr_nat_nat_end _) ⟨rfl, by simp⟩))
(trans_gen.head rfl (trans_gen.head rfl _)),
simp,
refine trans_gen.trans (clear_ok
(split_at_pred_eq _ _ (tr_list L₂) (some Γ'.Cons) L₃
(λ x h, (to_bool_ff (tr_list_ne_Cons _ _ h))) ⟨rfl, by simp⟩)) _,
convert unrev_ok, simp [list.reverse_core_eq] },
end
theorem succ_ok {q s n} {c d : list Γ'} :
reaches₁ (TM2.step tr)
⟨some (Λ'.succ q), s, K'.elim (tr_list [n]) [] c d⟩
⟨some q, none, K'.elim (tr_list [n.succ]) [] c d⟩ :=
begin
simp [tr_nat, num.add_one],
cases (n:num) with a,
{ refine trans_gen.head rfl _, simp,
rw if_neg, swap, rintro ⟨⟩, rw if_pos, swap, refl,
convert unrev_ok, simp, refl },
simp [num.succ, tr_num, num.succ'],
suffices : ∀ l₁,
∃ l₁' l₂' s', list.reverse_core l₁ (tr_pos_num a.succ) = list.reverse_core l₁' l₂' ∧
reaches₁ (TM2.step tr)
⟨some q.succ, s, K'.elim (tr_pos_num a ++ [Γ'.cons]) l₁ c d⟩
⟨some (unrev q), s', K'.elim (l₂' ++ [Γ'.cons]) l₁' c d⟩,
{ obtain ⟨l₁', l₂', s', e, h⟩ := this [], simp [list.reverse_core] at e,
refine h.trans _, convert unrev_ok using 2, simp [e, list.reverse_core_eq] },
induction a with m IH m IH generalizing s; intro l₁,
{ refine ⟨Γ'.bit0 :: l₁, [Γ'.bit1], some Γ'.cons, rfl, trans_gen.head rfl (trans_gen.single _)⟩,
simp [tr_pos_num] },
{ obtain ⟨l₁', l₂', s', e, h⟩ := IH (Γ'.bit0 :: l₁),
refine ⟨l₁', l₂', s', e, trans_gen.head _ h⟩, swap,
simp [pos_num.succ, tr_pos_num] },
{ refine ⟨l₁, _, some Γ'.bit0, rfl, trans_gen.single _⟩, simp, refl },
end
theorem pred_ok (q₁ q₂ s v) (c d : list Γ') :
∃ s', reaches₁ (TM2.step tr)
⟨some (Λ'.pred q₁ q₂), s, K'.elim (tr_list v) [] c d⟩
(v.head.elim
⟨some q₁, s', K'.elim (tr_list v.tail) [] c d⟩
(λ n _, ⟨some q₂, s', K'.elim (tr_list (n :: v.tail)) [] c d⟩)) :=
begin
rcases v with _|⟨_|n, v⟩,
{ refine ⟨none, trans_gen.single _⟩, simp, refl },
{ refine ⟨some Γ'.cons, trans_gen.single _⟩, simp, refl },
refine ⟨none, _⟩, simp [tr_nat, num.add_one, num.succ, tr_num],
cases (n:num) with a,
{ simp [tr_pos_num, tr_num, show num.zero.succ' = pos_num.one, from rfl],
refine trans_gen.head rfl _, convert unrev_ok, simp, refl },
simp [tr_num, num.succ'],
suffices : ∀ l₁,
∃ l₁' l₂' s', list.reverse_core l₁ (tr_pos_num a) = list.reverse_core l₁' l₂' ∧
reaches₁ (TM2.step tr)
⟨some (q₁.pred q₂), s, K'.elim (tr_pos_num a.succ ++ Γ'.cons :: tr_list v) l₁ c d⟩
⟨some (unrev q₂), s', K'.elim (l₂' ++ Γ'.cons :: tr_list v) l₁' c d⟩,
{ obtain ⟨l₁', l₂', s', e, h⟩ := this [], simp [list.reverse_core] at e,
refine h.trans _, convert unrev_ok using 2, simp [e, list.reverse_core_eq] },
induction a with m IH m IH generalizing s; intro l₁,
{ refine ⟨Γ'.bit1 :: l₁, [], some Γ'.cons, rfl, trans_gen.head rfl (trans_gen.single _)⟩,
simp [tr_pos_num, show pos_num.one.succ = pos_num.one.bit0, from rfl], refl },
{ obtain ⟨l₁', l₂', s', e, h⟩ := IH (some Γ'.bit0) (Γ'.bit1 :: l₁),
refine ⟨l₁', l₂', s', e, trans_gen.head _ h⟩, simp, refl },
{ obtain ⟨a, l, e, h⟩ : ∃ a l, tr_pos_num m = a :: l ∧ nat_end a = ff,
{ cases m; refine ⟨_, _, rfl, rfl⟩ },
refine ⟨Γ'.bit0 :: l₁, _, some a, rfl, trans_gen.single _⟩,
simp [tr_pos_num, pos_num.succ, e, h, nat_end,
show some Γ'.bit1 ≠ some Γ'.bit0, from dec_trivial] },
end
theorem tr_normal_respects (c k v s) : ∃ b₂, tr_cfg (step_normal c k v) b₂ ∧
reaches₁ (TM2.step tr)
⟨some (tr_normal c (tr_cont k)), s, K'.elim (tr_list v) [] [] (tr_cont_stack k)⟩ b₂ :=
begin
induction c generalizing k v s,
case zero' : { refine ⟨_, ⟨s, rfl⟩, trans_gen.single _⟩, simp },
case succ : { refine ⟨_, ⟨none, rfl⟩, head_main_ok.trans succ_ok⟩ },
case tail : {
let o : option Γ' := list.cases_on v none (λ _ _, some Γ'.cons),
refine ⟨_, ⟨o, rfl⟩, _⟩, convert clear_ok _, simp, swap,
refine split_at_pred_eq _ _ (tr_nat v.head) _ _ (tr_nat_nat_end _) _,
cases v; exact ⟨rfl, rfl⟩ },
case cons : f fs IHf IHfs {
obtain ⟨c, h₁, h₂⟩ := IHf (cont.cons₁ fs v k) v none,
refine ⟨c, h₁, trans_gen.head rfl $ (move_ok dec_trivial (split_at_pred_ff _)).trans _⟩,
simp [step_normal],
refine (copy_ok _ none [] (tr_list v).reverse _ _).trans _,
convert h₂ using 2,
simp [list.reverse_core_eq, tr_cont_stack] },
case comp : f g IHf IHg { exact IHg (cont.comp f k) v s },
case case : f g IHf IHg {
rw step_normal,
obtain ⟨s', h⟩ := pred_ok _ _ s v _ _,
cases v.head with n,
{ obtain ⟨c, h₁, h₂⟩ := IHf k _ s', exact ⟨_, h₁, h.trans h₂⟩ },
{ obtain ⟨c, h₁, h₂⟩ := IHg k _ s', exact ⟨_, h₁, h.trans h₂⟩ } },
case fix : f IH { apply IH }
end
theorem tr_ret_respects (k v s) : ∃ b₂, tr_cfg (step_ret k v) b₂ ∧
reaches₁ (TM2.step tr)
⟨some (Λ'.ret (tr_cont k)), s, K'.elim (tr_list v) [] [] (tr_cont_stack k)⟩ b₂ :=
begin
induction k generalizing v s,
case halt : { exact ⟨_, rfl, trans_gen.single rfl⟩ },
case cons₁ : fs as k IH {
obtain ⟨s', h₁, h₂⟩ := tr_normal_respects fs (cont.cons₂ v k) as none,
refine ⟨s', h₁, trans_gen.head rfl _⟩, simp,
refine (move₂_ok dec_trivial _ (split_at_pred_ff _)).trans _, {refl}, simp,
refine (move₂_ok dec_trivial _ _).trans _, swap 4, {refl},
swap 4, {exact (split_at_pred_eq _ _ _ (some Γ'.Cons) _
(λ x h, to_bool_ff (tr_list_ne_Cons _ _ h)) ⟨rfl, rfl⟩)},
refine (move₂_ok dec_trivial _ (split_at_pred_ff _)).trans _, {refl}, simp,
exact h₂ },
case cons₂ : ns k IH {
obtain ⟨c, h₁, h₂⟩ := IH (ns.head :: v) none,
exact ⟨c, h₁, trans_gen.head rfl $ head_stack_ok.trans h₂⟩ },
case comp : f k IH {
obtain ⟨s', h₁, h₂⟩ := tr_normal_respects f k v s,
exact ⟨_, h₁, trans_gen.head rfl h₂⟩ },
case fix : f k IH {
rw [step_ret],
have : if v.head = 0
then nat_end (tr_list v).head'.iget = tt ∧ (tr_list v).tail = tr_list v.tail
else nat_end (tr_list v).head'.iget = ff ∧
(tr_list v).tail = (tr_nat v.head).tail ++ Γ'.cons :: tr_list v.tail,
{ cases v with n, {exact ⟨rfl, rfl⟩}, cases n, {exact ⟨rfl, rfl⟩},
rw [tr_list, list.head, tr_nat, nat.cast_succ, num.add_one, num.succ, list.tail],
cases (n:num).succ'; exact ⟨rfl, rfl⟩ },
by_cases v.head = 0; simp [h] at this ⊢,
{ obtain ⟨c, h₁, h₂⟩ := IH v.tail (tr_list v).head',
refine ⟨c, h₁, trans_gen.head rfl _⟩,
simp [tr_cont, tr_cont_stack, this], exact h₂ },
{ obtain ⟨s', h₁, h₂⟩ := tr_normal_respects f (cont.fix f k) v.tail (some Γ'.cons),
refine ⟨_, h₁, trans_gen.head rfl $ trans_gen.trans _ h₂⟩,
swap 3, simp [tr_cont, this.1],
convert clear_ok (split_at_pred_eq _ _ (tr_nat v.head).tail (some Γ'.cons) _ _ _) using 2,
{ simp },
{ exact λ x h, tr_nat_nat_end _ _ (list.tail_subset _ h) },
{ exact ⟨rfl, this.2⟩ } } },
end
theorem tr_respects : respects step (TM2.step tr) tr_cfg
| (cfg.ret k v) _ ⟨s, rfl⟩ := tr_ret_respects _ _ _
| (cfg.halt v) _ rfl := rfl
/-- The initial state, evaluating function `c` on input `v`. -/
def init (c : code) (v : list ℕ) : cfg' :=
⟨some (tr_normal c cont'.halt), none, K'.elim (tr_list v) [] [] []⟩
theorem tr_init (c v) : ∃ b, tr_cfg (step_normal c cont.halt v) b ∧
reaches₁ (TM2.step tr) (init c v) b := tr_normal_respects _ _ _ _
theorem tr_eval (c v) : eval (TM2.step tr) (init c v) = halt <$> code.eval c v :=
begin
obtain ⟨i, h₁, h₂⟩ := tr_init c v,
refine part.ext (λ x, _),
rw [reaches_eval h₂.to_refl], simp,
refine ⟨λ h, _, _⟩,
{ obtain ⟨c, hc₁, hc₂⟩ := tr_eval_rev tr_respects h₁ h,
simp [step_normal_eval] at hc₂,
obtain ⟨v', hv, rfl⟩ := hc₂,
exact ⟨_, hv, hc₁.symm⟩ },
{ rintro ⟨v', hv, rfl⟩,
have := tr_eval tr_respects h₁,
simp [step_normal_eval] at this,
obtain ⟨_, ⟨⟩, h⟩ := this _ hv rfl,
exact h }
end
end
end partrec_to_TM2
end turing
|
54be8ac68ab5ca0db4ef9d1f84ffade14e652197
|
2eab05920d6eeb06665e1a6df77b3157354316ad
|
/src/tactic/group.lean
|
bc74780c84d5a97c60488910b75efdf038599869
|
[
"Apache-2.0"
] |
permissive
|
ayush1801/mathlib
|
78949b9f789f488148142221606bf15c02b960d2
|
ce164e28f262acbb3de6281b3b03660a9f744e3c
|
refs/heads/master
| 1,692,886,907,941
| 1,635,270,866,000
| 1,635,270,866,000
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 3,690
|
lean
|
/-
Copyright (c) 2020. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import tactic.ring
import tactic.doc_commands
/-!
# `group`
Normalizes expressions in the language of groups. The basic idea is to use the simplifier
to put everything into a product of group powers (`gpow` which takes a group element and an
integer), then simplify the exponents using the `ring` tactic. The process needs to be repeated
since `ring` can normalize an exponent to zero, leading to a factor that can be removed
before collecting exponents again. The simplifier step also uses some extra lemmas to avoid
some `ring` invocations.
## Tags
group_theory
-/
-- The next four lemmas are not general purpose lemmas, they are intended for use only by
-- the `group` tactic.
lemma tactic.group.gpow_trick {G : Type*} [group G] (a b : G) (n m : ℤ) : a*b^n*b^m = a*b^(n+m) :=
by rw [mul_assoc, ← gpow_add]
lemma tactic.group.gpow_trick_one {G : Type*} [group G] (a b : G) (m : ℤ) : a*b*b^m = a*b^(m+1) :=
by rw [mul_assoc, mul_self_gpow]
lemma tactic.group.gpow_trick_one' {G : Type*} [group G] (a b : G) (n : ℤ) : a*b^n*b = a*b^(n+1) :=
by rw [mul_assoc, mul_gpow_self]
lemma tactic.group.gpow_trick_sub {G : Type*} [group G] (a b : G) (n m : ℤ) :
a*b^n*b^(-m) = a*b^(n-m) :=
by rw [mul_assoc, ← gpow_add] ; refl
namespace tactic
setup_tactic_parser
open tactic.simp_arg_type interactive tactic.group
/-- Auxiliary tactic for the `group` tactic. Calls the simplifier only. -/
meta def aux_group₁ (locat : loc) : tactic unit :=
simp_core {} skip tt [
expr ``(mul_one),
expr ``(one_mul),
expr ``(one_pow),
expr ``(one_gpow),
expr ``(sub_self),
expr ``(add_neg_self),
expr ``(neg_add_self),
expr ``(neg_neg),
expr ``(tsub_self),
expr ``(int.coe_nat_add),
expr ``(int.coe_nat_mul),
expr ``(int.coe_nat_zero),
expr ``(int.coe_nat_one),
expr ``(int.coe_nat_bit0),
expr ``(int.coe_nat_bit1),
expr ``(int.mul_neg_eq_neg_mul_symm),
expr ``(int.neg_mul_eq_neg_mul_symm),
symm_expr ``(gpow_coe_nat),
symm_expr ``(gpow_neg_one),
symm_expr ``(gpow_mul),
symm_expr ``(gpow_add_one),
symm_expr ``(gpow_one_add),
symm_expr ``(gpow_add),
expr ``(mul_gpow_neg_one),
expr ``(gpow_zero),
expr ``(mul_gpow),
symm_expr ``(mul_assoc),
expr ``(gpow_trick),
expr ``(gpow_trick_one),
expr ``(gpow_trick_one'),
expr ``(gpow_trick_sub),
expr ``(tactic.ring.horner)]
[] locat >> skip
/-- Auxiliary tactic for the `group` tactic. Calls `ring_nf` to normalize exponents. -/
meta def aux_group₂ (locat : loc) : tactic unit :=
ring_nf none tactic.ring.normalize_mode.raw locat
end tactic
namespace tactic.interactive
setup_tactic_parser
open tactic
/--
Tactic for normalizing expressions in multiplicative groups, without assuming
commutativity, using only the group axioms without any information about which group
is manipulated.
(For additive commutative groups, use the `abel` tactic instead.)
Example:
```lean
example {G : Type} [group G] (a b c d : G) (h : c = (a*b^2)*((b*b)⁻¹*a⁻¹)*d) : a*c*d⁻¹ = a :=
begin
group at h, -- normalizes `h` which becomes `h : c = d`
rw h, -- the goal is now `a*d*d⁻¹ = a`
group, -- which then normalized and closed
end
```
-/
meta def group (locat : parse location) : tactic unit :=
do when locat.include_goal `[rw ← mul_inv_eq_one],
try (aux_group₁ locat),
repeat (aux_group₂ locat ; aux_group₁ locat)
end tactic.interactive
add_tactic_doc
{ name := "group",
category := doc_category.tactic,
decl_names := [`tactic.interactive.group],
tags := ["decision procedure", "simplification"] }
|
4fd2fa88d5f3988f2d2919f86802bd9c3859335c
|
1437b3495ef9020d5413178aa33c0a625f15f15f
|
/data/finset.lean
|
3afcdaaf2c3b495abc2167380960ceac420f52a5
|
[
"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
| 72,938
|
lean
|
/-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro
Finite sets.
-/
import logic.embedding order.boolean_algebra algebra.order_functions
data.multiset data.sigma.basic data.set.lattice
open multiset subtype nat lattice
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `finset α` is the type of finite sets of elements of `α`. It is implemented
as a multiset (a list up to permutation) which has no duplicate elements. -/
structure finset (α : Type*) :=
(val : multiset α)
(nodup : nodup val)
namespace finset
theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t
| ⟨s, _⟩ ⟨t, _⟩ rfl := rfl
@[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t :=
⟨eq_of_veq, congr_arg _⟩
@[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 :=
erase_dup_eq_self.2 s.2
instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α)
| s₁ s₂ := decidable_of_iff _ val_inj
/- membership -/
instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩
theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl
@[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl
instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) :=
multiset.decidable_mem _ _
/- set coercion -/
/-- Convert a finset to a set in the natural way. -/
def to_set (s : finset α) : set α := {x | x ∈ s}
instance : has_lift (finset α) (set α) := ⟨to_set⟩
@[simp] lemma mem_coe {a : α} {s : finset α} : a ∈ (↑s : set α) ↔ a ∈ s := iff.rfl
@[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = ↑s := rfl
/- extensionality -/
theorem ext {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ :=
val_inj.symm.trans $ nodup_ext s₁.2 s₂.2
@[extensionality]
theorem ext' {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ :=
ext.2
@[simp] theorem coe_inj {s₁ s₂ : finset α} : (↑s₁ : set α) = ↑s₂ ↔ s₁ = s₂ :=
(set.ext_iff _ _).trans ext.symm
/- subset -/
instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩
theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl
@[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _
theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans
theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset
theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ :=
ext.2 $ λ a, ⟨@H₁ a, @H₂ a⟩
theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl
@[simp] theorem coe_subset {s₁ s₂ : finset α} :
(↑s₁ : set α) ⊆ ↑s₂ ↔ s₁ ⊆ s₂ := iff.rfl
@[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2
instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩
instance : partial_order (finset α) :=
{ le := (⊆),
lt := (⊂),
le_refl := subset.refl,
le_trans := @subset.trans _,
le_antisymm := @subset.antisymm _ }
theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ :=
le_antisymm_iff
@[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl
@[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl
@[simp] lemma coe_ssubset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊂ s₂ :=
show (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁,
by simp only [set.ssubset_iff_subset_not_subset, finset.coe_subset]
@[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ :=
and_congr val_le_iff $ not_congr val_le_iff
/- empty -/
protected def empty : finset α := ⟨0, nodup_zero⟩
instance : has_emptyc (finset α) := ⟨finset.empty⟩
instance : inhabited (finset α) := ⟨∅⟩
@[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl
@[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id
@[simp] theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅
| e := not_mem_empty a $ e ▸ h
@[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _
theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ :=
eq_of_veq (eq_zero_of_forall_not_mem H)
lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s :=
⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩
@[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅
theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero
theorem exists_mem_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a : α, a ∈ s :=
exists_mem_of_ne_zero (mt val_eq_zero.1 h)
@[simp] lemma coe_empty : ↑(∅ : finset α) = (∅ : set α) := rfl
/-- `singleton a` is the set `{a}` containing `a` and nothing else. -/
def singleton (a : α) : finset α := ⟨_, nodup_singleton a⟩
local prefix `ι`:90 := singleton
@[simp] theorem singleton_val (a : α) : (ι a).1 = a :: 0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ ι a ↔ b = a := mem_singleton
theorem not_mem_singleton {a b : α} : a ∉ ι b ↔ a ≠ b := not_iff_not_of_iff mem_singleton
theorem mem_singleton_self (a : α) : a ∈ ι a := or.inl rfl
theorem singleton_inj {a b : α} : ι a = ι b ↔ a = b :=
⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩
@[simp] theorem singleton_ne_empty (a : α) : ι a ≠ ∅ := ne_empty_of_mem (mem_singleton_self _)
@[simp] lemma coe_singleton (a : α) : ↑(ι a) = ({a} : set α) := rfl
/- insert -/
section decidable_eq
variables [decidable_eq α]
/-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/
instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩
@[simp] theorem has_insert_eq_insert (a : α) (s : finset α) : has_insert.insert a s = insert a s := rfl
theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl
@[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl
theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a :: s.1) :=
by rw [erase_dup_cons, erase_dup_eq_self]; refl
theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a :: s.1 :=
by rw [insert_val, ndinsert_of_not_mem h]
@[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert
theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1
theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h
theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s :=
(mem_insert.1 h).resolve_left
@[simp] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a ↑s : set α) :=
set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff]
@[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s :=
eq_of_veq $ ndinsert_of_mem h
theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) :=
ext.2 $ λ x, by simp only [finset.mem_insert, or.left_comm]
@[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s :=
ext.2 $ λ x, by simp only [finset.mem_insert, or.assoc.symm, or_self]
@[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ :=
ne_empty_of_mem (mem_insert_self a s)
theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib]
theorem subset_insert [h : decidable_eq α] (a : α) (s : finset α) : s ⊆ insert a s :=
λ b, mem_insert_of_mem
theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t :=
insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩
lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a, a ∉ s ∧ insert a s ⊆ t) :=
iff.intro
(assume ⟨h₁, h₂⟩,
have ∃a ∈ t, a ∉ s, by simpa only [finset.subset_iff, classical.not_forall] using h₂,
let ⟨a, hat, has⟩ := this in ⟨a, has, insert_subset.mpr ⟨hat, h₁⟩⟩)
(assume ⟨a, hat, has⟩,
let ⟨h₁, h₂⟩ := insert_subset.mp has in
⟨h₂, assume h, hat $ h h₁⟩)
lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s :=
ssubset_iff.mpr ⟨a, h, subset.refl _⟩
@[recursor 6] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α]
(h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s
| ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin
cases nodup_cons.1 nd with m nd',
rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a::s, nd⟩)],
{ exact h₂ (by exact m) (IH nd') },
{ rw [insert_val, ndinsert_of_not_mem m] }
end) nd
@[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α]
(s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s :=
finset.induction h₁ h₂ s
@[simp] theorem singleton_eq_singleton (a : α) : _root_.singleton a = ι a := rfl
@[simp] theorem insert_empty_eq_singleton (a : α) : {a} = ι a := rfl
@[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = ι a :=
insert_eq_of_mem $ mem_singleton_self _
/- union -/
/-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/
instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩
theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl
@[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 :=
ndunion_eq_union s₁.2
@[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion
theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h
theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h
theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ :=
by rw [mem_union, not_or_distrib]
@[simp] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (↑s₁ ∪ ↑s₂ : set α) := set.ext $ λ x, mem_union
theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ :=
val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩)
theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _
theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _
@[simp] theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ :=
ext.2 $ λ x, by simp only [mem_union, or_comm]
instance : is_commutative (finset α) (∪) := ⟨union_comm⟩
@[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) :=
ext.2 $ λ x, by simp only [mem_union, or_assoc]
instance : is_associative (finset α) (∪) := ⟨union_assoc⟩
@[simp] theorem union_idempotent (s : finset α) : s ∪ s = s :=
ext.2 $ λ _, mem_union.trans $ or_self _
instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩
theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) :=
ext.2 $ λ _, by simp only [mem_union, or.left_comm]
theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ :=
ext.2 $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)]
@[simp] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s
@[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s :=
ext.2 $ λ x, mem_union.trans $ or_false _
@[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s :=
ext.2 $ λ x, mem_union.trans $ false_or _
theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl
@[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) :=
by simp only [insert_eq, union_assoc]
@[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) :=
by simp only [insert_eq, union_left_comm]
theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t :=
by simp only [insert_union, union_insert, insert_idem]
/- inter -/
/-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/
instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩
theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl
@[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 :=
ndinter_eq_inter s₁.2
@[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter
theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1
theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2
theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ :=
and_imp.1 mem_inter.2
theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left
theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right
theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ :=
by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial
@[simp] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (↑s₁ ∩ ↑s₂ : set α) := set.ext $ λ _, mem_inter
@[simp] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ :=
ext.2 $ λ _, by simp only [mem_inter, and_comm]
@[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) :=
ext.2 $ λ _, by simp only [mem_inter, and_assoc]
@[simp] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
ext.2 $ λ _, by simp only [mem_inter, and.left_comm]
@[simp] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ :=
ext.2 $ λ _, by simp only [mem_inter, and.right_comm]
@[simp] theorem inter_self (s : finset α) : s ∩ s = s :=
ext.2 $ λ _, mem_inter.trans $ and_self _
@[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ :=
ext.2 $ λ _, mem_inter.trans $ and_false _
@[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ :=
ext.2 $ λ _, mem_inter.trans $ false_and _
@[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) :
insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) :=
ext.2 $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h,
by simp only [mem_inter, mem_insert, or_and_distrib_left, this]
@[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) :
s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) :=
by rw [inter_comm, insert_inter_of_mem h, inter_comm]
@[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) :
insert a s₁ ∩ s₂ = s₁ ∩ s₂ :=
ext.2 $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H,
by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or]
@[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) :
s₁ ∩ insert a s₂ = s₁ ∩ s₂ :=
by rw [inter_comm, insert_inter_of_not_mem h, inter_comm]
@[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : ι a ∩ s = ι a :=
show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter]
@[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : ι a ∩ s = ∅ :=
eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h
@[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ ι a = ι a :=
by rw [inter_comm, singleton_inter_of_mem h]
@[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ ι a = ∅ :=
by rw [inter_comm, singleton_inter_of_not_mem h]
/- lattice laws -/
instance : lattice (finset α) :=
{ sup := (∪),
sup_le := assume a b c, union_subset,
le_sup_left := subset_union_left,
le_sup_right := subset_union_right,
inf := (∩),
le_inf := assume a b c, subset_inter,
inf_le_left := inter_subset_left,
inf_le_right := inter_subset_right,
..finset.partial_order }
@[simp] theorem sup_eq_union (s t : finset α) : s ⊔ t = s ∪ t := rfl
@[simp] theorem inf_eq_inter (s t : finset α) : s ⊓ t = s ∩ t := rfl
instance : semilattice_inf_bot (finset α) :=
{ bot := ∅, bot_le := empty_subset, ..finset.lattice.lattice }
instance : distrib_lattice (finset α) :=
{ le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c,
by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt};
simp only [true_or, imp_true_iff, true_and, or_true],
..finset.lattice.lattice }
theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left
theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right
theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left
theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right
/- erase -/
/-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are
not equal to `a`. -/
def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩
@[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl
@[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s :=
mem_erase_iff_of_nodup s.2
theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2
@[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl
theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a :=
by simp only [mem_erase]; exact and.left
theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase
theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b :=
by simp only [mem_erase]; exact and.intro
theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s :=
ext.2 $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or];
apply and_iff_right_of_imp; rintro H rfl; exact h H
theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s :=
ext.2 $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and];
apply or_iff_right_of_imp; rintro rfl; exact h
theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a :=
val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h
theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _
@[simp] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (↑s \ {a} : set α) :=
set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl
lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s :=
calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _
... = _ : insert_erase h
theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s :=
eq_of_veq $ erase_of_not_mem h
theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t :=
by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp];
exact forall_congr (λ x, forall_swap)
theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s :=
subset_insert_iff.1 $ subset.refl _
theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) :=
subset_insert_iff.2 $ subset.refl _
/- sdiff -/
/-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/
instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩
@[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} :
a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2
@[simp] theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ :=
ext.2 $ λ a, by simpa only [mem_sdiff, mem_union, or_comm,
or_and_distrib_left, dec_em, and_true] using or_iff_right_of_imp (@h a)
@[simp] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ :=
(union_comm _ _).trans (sdiff_union_of_subset h)
@[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ :=
eq_empty_of_forall_not_mem $
by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h
@[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ :=
(inter_comm _ _).trans (inter_sdiff_self _ _)
theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ :=
by simpa only [subset_iff, mem_sdiff, and_imp] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂)
@[simp] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (↑s₁ \ ↑s₂ : set α) :=
set.ext $ λ _, mem_sdiff
end decidable_eq
/- attach -/
/-- `attach s` takes the elements of `s` and forms a new set of elements of the
subtype `{x // x ∈ s}`. -/
def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩
@[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl
@[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _
@[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl
section decidable_pi_exists
variables {s : finset α}
instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] :
decidable (∀a (h : a ∈ s), p a h) :=
multiset.decidable_dforall_multiset
/-- decidable equality for functions whose domain is bounded by finsets -/
instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈s, β a) :=
multiset.decidable_eq_pi_multiset
instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] :
decidable (∃a (h : a ∈ s), p a h) :=
multiset.decidable_dexists_multiset
end decidable_pi_exists
/- filter -/
section filter
variables {p q : α → Prop} [decidable_pred p] [decidable_pred q]
/-- `filter p s` is the set of elements of `s` that satisfy `p`. -/
def filter (p : α → Prop) [decidable_pred p] (s : finset α) : finset α :=
⟨_, nodup_filter p s.2⟩
@[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl
@[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter
@[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _
theorem filter_filter (s : finset α) :
(s.filter p).filter q = s.filter (λa, p a ∧ q a) :=
ext.2 $ assume a, by simp only [mem_filter, and_comm, and.left_comm]
@[simp] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] :
@finset.filter α (λ _, true) h s = s :=
by ext; simp
@[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ :=
ext.2 $ assume a, by simp only [mem_filter, and_false]; refl
lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s :=
eq_of_veq $ filter_congr H
variable [decidable_eq α]
theorem filter_union (s₁ s₂ : finset α) :
(s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p :=
ext.2 $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right]
theorem filter_or (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q :=
ext.2 $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left]
theorem filter_and (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q :=
ext.2 $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self]
theorem filter_not (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p :=
ext.2 $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $
λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm
theorem sdiff_eq_filter (s₁ s₂ : finset α) :
s₁ \ s₂ = filter (∉ s₂) s₁ := ext.2 $ λ _, by simp only [mem_sdiff, mem_filter]
theorem filter_union_filter_neg_eq (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s :=
by simp only [filter_not, union_sdiff_of_subset (filter_subset s)]
theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ :=
by simp only [filter_not, inter_sdiff_self]
@[simp] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) :=
set.ext $ λ _, mem_filter
end filter
/- range -/
section range
variables {n m l : ℕ}
/-- `range n` is the set of natural numbers less than `n`. -/
def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩
@[simp] theorem range_val (n : ℕ) : (range n).1 = multiset.range n := rfl
@[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range
@[simp] theorem range_zero : range 0 = ∅ := rfl
@[simp] theorem range_one : range 1 = {0} := rfl
theorem range_succ : range (succ n) = insert n (range n) :=
eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm
@[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self
@[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset
theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n :=
finset.induction_on s ⟨0, empty_subset _⟩ $ λ a s ha ⟨n, hn⟩,
⟨max (a + 1) n, insert_subset.2
⟨by simpa only [mem_range] using le_max_left (a+1) n,
subset.trans hn (by simpa only [range_subset] using le_max_right (a+1) n)⟩⟩
end range
/- useful rules for calculations with quantifiers -/
theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false :=
by simp only [not_mem_empty, false_and, exists_false]
theorem exists_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) :=
by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left]
theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true :=
iff_true_intro $ λ _, false.elim
theorem forall_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) :=
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
end finset
namespace option
/-- Construct an empty or singleton finset from an `option` -/
def to_finset (o : option α) : finset α :=
match o with
| none := ∅
| some a := finset.singleton a
end
@[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl
@[simp] theorem to_finset_some {a : α} : (some a).to_finset = finset.singleton a := rfl
@[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o :=
by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl
end option
/- erase_dup on list and multiset -/
namespace multiset
variable [decidable_eq α]
/-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/
def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩
@[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl
theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset :=
finset.val_inj.1 (erase_dup_eq_self.2 n).symm
@[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s :=
mem_erase_dup
@[simp] lemma to_finset_zero :
to_finset (0 : multiset α) = ∅ :=
rfl
@[simp] lemma to_finset_cons (a : α) (s : multiset α) :
to_finset (a :: s) = insert a (to_finset s) :=
finset.eq_of_veq erase_dup_cons
@[simp] lemma to_finset_add (s t : multiset α) :
to_finset (s + t) = to_finset s ∪ to_finset t :=
finset.ext' $ by simp
end multiset
namespace list
variable [decidable_eq α]
/-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/
def to_finset (l : list α) : finset α := multiset.to_finset l
@[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl
theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset :=
multiset.to_finset_eq n
@[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l :=
mem_erase_dup
@[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ :=
rfl
@[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) :=
finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h]
end list
namespace finset
section map
open function
def map (f : α ↪ β) (s : finset α) : finset β :=
⟨s.1.map f, nodup_map f.2 s.2⟩
@[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl
@[simp] theorem map_empty (f : α ↪ β) (s : finset α) : (∅ : finset α).map f = ∅ := rfl
variables {f : α ↪ β} {s : finset α}
@[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b :=
mem_map.trans $ by simp only [exists_prop]; refl
theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s :=
mem_map_of_inj f.2
@[simp] theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f :=
(mem_map' _).2
theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} :
s.to_finset.map f = (s.map f).to_finset :=
ext.2 $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset]
theorem map_refl : s.map (embedding.refl _) = s :=
ext.2 $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right
theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) :=
eq_of_veq $ by simp only [map_val, multiset.map_map]; refl
theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ :=
⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs,
λ h, by simp [subset_def, map_subset_map h]⟩
theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ :=
by simp only [subset.antisymm_iff, map_subset_map]
def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩
@[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl
theorem map_filter {p : β → Prop} [decidable_pred p] :
(s.map f).filter p = (s.filter (p ∘ f)).map f :=
ext.2 $ λ b, by simp only [mem_filter, mem_map, exists_prop, and_assoc]; exact
⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, h1, h2, rfl⟩,
by rintro ⟨x, h1, h2, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩
theorem map_union [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f :=
ext.2 $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib]
theorem map_inter [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f :=
ext.2 $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact
⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩,
by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩
@[simp] theorem map_singleton (f : α ↪ β) (a : α) : (singleton a).map f = singleton (f a) :=
ext.2 $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm
@[simp] theorem map_insert [decidable_eq α] [decidable_eq β]
(f : α ↪ β) (a : α) (s : finset α) :
(insert a s).map f = insert (f a) (s.map f) :=
by simp only [insert_eq, insert_empty_eq_singleton, map_union, map_singleton]
@[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s :=
eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _
end map
section image
variables [decidable_eq β]
/-- `image f s` is the forward image of `s` under `f`. -/
def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset
@[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl
@[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl
variables {f : α → β} {s : finset α}
@[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b :=
by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop]
@[simp] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f :=
mem_image.2 ⟨_, h, rfl⟩
@[simp] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s :=
set.ext $ λ _, mem_image.trans $ by simp only [exists_prop]; refl
theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset :=
ext.2 $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map]
@[simp] theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f :=
multiset.erase_dup_eq_self.2 (nodup_map_on H s.2)
theorem image_id [decidable_eq α] : s.image id = s :=
ext.2 $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right]
theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) :=
eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map]
theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f :=
by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h]
theorem image_filter {p : β → Prop} [decidable_pred p] :
(s.image f).filter p = (s.filter (p ∘ f)).image f :=
ext.2 $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact
⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩,
by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩
theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f :=
ext.2 $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib]
theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f :=
ext.2 $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b,
⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩,
λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩.
@[simp] theorem image_singleton [decidable_eq α] (f : α → β) (a : α) : (singleton a).image f = singleton (f a) :=
ext.2 $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm
@[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) :
(insert a s).image f = insert (f a) (s.image f) :=
by simp only [insert_eq, insert_empty_eq_singleton, image_singleton, image_union]
@[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s :=
eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self]
@[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} :
attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s})
((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) :=
ext.2 $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx)
(assume h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h)
(assume h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩),
λ _, finset.mem_attach _ _⟩
theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f :=
eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm
lemma image_const [decidable_eq β] {s : finset α} (h : s ≠ ∅) (b : β) : s.image (λa, b) = singleton b :=
ext.2 $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right,
exists_mem_of_ne_empty h, true_and, mem_singleton, eq_comm]
protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) :=
(s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩,
λ x y H, subtype.eq $ subtype.mk.inj H⟩
@[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} :
∀{a : subtype p}, a ∈ s.subtype p ↔ a.val ∈ s
| ⟨a, ha⟩ := by simp [finset.subtype, ha]
end image
/- card -/
section card
/-- `card s` is the cardinality (number of elements) of `s`. -/
def card (s : finset α) : nat := s.1.card
theorem card_def (s : finset α) : s.card = s.1.card := rfl
@[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl
@[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ :=
card_eq_zero.trans val_eq_zero
theorem card_pos {s : finset α} : 0 < card s ↔ s ≠ ∅ :=
pos_iff_ne_zero.trans $ not_congr card_eq_zero
theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = finset.singleton a :=
by cases s; simp [multiset.card_eq_one, finset.singleton, finset.card]
@[simp] theorem card_insert_of_not_mem [decidable_eq α]
{a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 :=
by simpa only [card_cons, card, insert_val] using
congr_arg multiset.card (ndinsert_of_not_mem h)
theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 :=
by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right},
rw [card_insert_of_not_mem h]]
@[simp] theorem card_singleton (a : α) : card (singleton a) = 1 := card_singleton _
theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem
@[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n
@[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach
theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α}
(H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s :=
by simp only [card, image_val_of_inj_on H, card_map]
theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α)
(H : function.injective f) : card (image f s) = card s :=
card_image_of_inj_on $ λ x _ y _ h, H h
lemma card_eq_of_bijective [decidable_eq α] {s : finset α} {n : ℕ}
(f : ∀i, i < n → α)
(hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s)
(f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) :
card s = n :=
have ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a,
from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩,
assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩,
have s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)),
by simpa only [ext, mem_image, exists_prop, subtype.exists, mem_attach, true_and],
calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) :
by rw [this]
... = card ((range n).attach) :
card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq,
subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq
... = card (range n) : card_attach
... = n : card_range n
lemma card_eq_succ [decidable_eq α] {s : finset α} {a : α} {n : ℕ} :
s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) :=
iff.intro
(assume eq,
have card s > 0, from eq.symm ▸ nat.zero_lt_succ _,
let ⟨a, has⟩ := finset.exists_mem_of_ne_empty $ card_pos.mp this in
⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩)
(assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat)
theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t :=
multiset.card_le_of_le ∘ val_le_iff.mpr
theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t :=
eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂
lemma card_lt_card [decidable_eq α] {s t : finset α} (h : s ⊂ t) : s.card < t.card :=
card_lt_of_lt (val_lt_iff.2 h)
lemma card_le_card_of_inj_on [decidable_eq α] [decidable_eq β] {s : finset α} {t : finset β}
(f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) :
card s ≤ card t :=
calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj]
... ≤ card t : card_le_of_subset $
assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end
lemma card_le_of_inj_on [decidable_eq α] {n} {s : finset α}
(f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s :=
calc n = card (range n) : (card_range n).symm
... ≤ card s : card_le_card_of_inj_on f
(by simpa only [mem_range])
(by simp only [mem_range]; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂)
@[elab_as_eliminator] lemma strong_induction_on {p : finset α → Sort*} :
∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s
| ⟨s, nd⟩ ih := multiset.strong_induction_on s
(λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd
@[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop}
(s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s :=
finset.strong_induction_on s $ λ s,
finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $
λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _)
lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β)
(h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b)
(h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card :=
by haveI := classical.prop_decidable; exact
calc s.card = s.attach.card : card_attach.symm
... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card :
eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h)))
... = t.card : congr_arg card (finset.ext.2 $ λ b,
⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _,
λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩)
lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) :
(s ∪ t).card + (s ∩ t).card = s.card + t.card :=
finset.induction_on t (by simp) (λ a, by by_cases a ∈ s; simp * {contextual := tt})
lemma card_union_le [decidable_eq α] (s t : finset α) :
(s ∪ t).card ≤ s.card + t.card :=
card_union_add_card_inter s t ▸ le_add_right _ _
lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β}
(f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t)
(hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂)
(hst : card t ≤ card s) :
(∀ b ∈ t, ∃ a ha, b = f a ha) :=
by haveI := classical.dec_eq β; exact
λ b hb,
have h : card (image (λ (a : {a // a ∈ s}), f (a.val) a.2) (attach s)) = card s,
from @card_attach _ s ▸ card_image_of_injective _
(λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h),
have h₁ : image (λ a : {a // a ∈ s}, f a.1 a.2) s.attach = t :=
eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in
ha₂ ▸ hf _ _) (by simp [hst, h]),
begin
rw ← h₁ at hb,
rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩,
exact ⟨a, a.2, ha₂.symm⟩,
end
end card
section bind
variables [decidable_eq β] {s : finset α} {t : α → finset β}
/-- `bind s t` is the union of `t x` over `x ∈ s` -/
protected def bind (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset
@[simp] theorem bind_val (s : finset α) (t : α → finset β) :
(s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl
@[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl
@[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a :=
by simp only [mem_def, bind_val, mem_erase_dup, mem_bind, exists_prop]
@[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t :=
ext.2 $ λ x, by simp only [mem_bind, exists_prop, mem_union, mem_insert,
or_and_distrib_right, exists_or_distrib, exists_eq_left]
-- ext.2 $ λ x, by simp [or_and_distrib_right, exists_or_distrib]
@[simp] lemma singleton_bind [decidable_eq α] {a : α} : (singleton a).bind t = t a :=
show (insert a ∅ : finset α).bind t = t a, from bind_insert.trans $ union_empty _
theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} :
(s.image f).bind t = s.bind (λa, t (f a)) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [image_insert, bind_insert, ih])
theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} :
(s.bind t).image f = s.bind (λa, (t a).image f) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [bind_insert, image_union, ih])
theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) :
(s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) :=
ext.2 $ λ x, by simp only [multiset.mem_to_finset, mem_bind, multiset.mem_bind, exists_prop]
lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ :=
have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a),
from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩,
by simpa only [subset_iff, mem_bind, exists_imp_distrib, and_imp, exists_prop]
lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f :=
ext.2 $ λ x, by simp only [mem_bind, mem_image, insert_empty_eq_singleton, mem_singleton, eq_comm]
lemma image_bind_filter_eq [decidable_eq α] (s : finset β) (g : β → α) :
(s.image g).bind (λa, s.filter $ (λc, g c = a)) = s :=
begin
ext b,
simp,
split,
{ rintros ⟨a, ⟨b', _, _⟩, hb, _⟩, exact hb },
{ rintros hb, exact ⟨g b, ⟨b, hb, rfl⟩, hb, rfl⟩ }
end
end bind
section prod
variables {s : finset α} {t : finset β}
/-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/
protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩
@[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl
@[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product
theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) :
s.product t = s.bind (λa, t.image $ λb, (a, b)) :=
ext.2 $ λ ⟨x, y⟩, by simp only [mem_product, mem_bind, mem_image, exists_prop, prod.mk.inj_iff,
and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left]
@[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t :=
multiset.card_product _ _
end prod
section sigma
variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)}
/-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/
protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) :=
⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩
@[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma
theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)}
(H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ :=
λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩
theorem sigma_eq_bind [decidable_eq α] [∀a, decidable_eq (σ a)] (s : finset α) (t : Πa, finset (σ a)) :
s.sigma t = s.bind (λa, (t a).image $ λb, ⟨a, b⟩) :=
ext.2 $ λ ⟨x, y⟩, by simp only [mem_sigma, mem_bind, mem_image, exists_prop,
and.left_comm, exists_and_distrib_left, exists_eq_left, heq_iff_eq, exists_eq_right]
end sigma
section pi
variables {δ : α → Type*} [decidable_eq α]
def pi (s : finset α) (t : Πa, finset (δ a)) : finset (Πa∈s, δ a) :=
⟨s.1.pi (λ a, (t a).1), nodup_pi s.2 (λ a _, (t a).2)⟩
@[simp] lemma pi_val (s : finset α) (t : Πa, finset (δ a)) :
(s.pi t).1 = s.1.pi (λ a, (t a).1) := rfl
@[simp] lemma mem_pi {s : finset α} {t : Πa, finset (δ a)} {f : Πa∈s, δ a} :
f ∈ s.pi t ↔ (∀a (h : a ∈ s), f a h ∈ t a) :=
mem_pi _ _ _
def pi.empty (β : α → Sort*) [decidable_eq α] (a : α) (h : a ∈ (∅ : finset α)) : β a :=
multiset.pi.empty β a h
def pi.cons (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' :=
multiset.pi.cons s.1 a b f _ (multiset.mem_cons.2 $ mem_insert.symm.2 h)
@[simp] lemma pi.cons_same (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (h : a ∈ insert a s) :
pi.cons s a b f a h = b :=
multiset.pi.cons_same _
lemma pi.cons_ne {s : finset α} {a a' : α} {b : δ a} {f : Πa, a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') :
pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) :=
multiset.pi.cons_ne _ _
lemma injective_pi_cons {a : α} {b : δ a} {s : finset α} (hs : a ∉ s) :
function.injective (pi.cons s a b) :=
assume e₁ e₂ eq,
@multiset.injective_pi_cons α _ δ a b s.1 hs _ _ $
funext $ assume e, funext $ assume h,
have pi.cons s a b e₁ e (by simpa only [mem_cons, mem_insert] using h) = pi.cons s a b e₂ e (by simpa only [mem_cons, mem_insert] using h),
by rw [eq],
this
@[simp] lemma pi_empty {t : Πa:α, finset (δ a)} :
pi (∅ : finset α) t = singleton (pi.empty δ) := rfl
@[simp] lemma pi_insert [∀a, decidable_eq (δ a)]
{s : finset α} {t : Πa:α, finset (δ a)} {a : α} (ha : a ∉ s) :
pi (insert a s) t = (t a).bind (λb, (pi s t).image (pi.cons s a b)) :=
begin
apply eq_of_veq,
rw ← multiset.erase_dup_eq_self.2 (pi (insert a s) t).2,
refine (λ s' (h : s' = a :: s.1), (_ : erase_dup (multiset.pi s' (λ a, (t a).1)) =
erase_dup ((t a).1.bind $ λ b,
erase_dup $ (multiset.pi s.1 (λ (a : α), (t a).val)).map $
λ f a' h', multiset.pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha),
subst s', rw pi_cons,
congr, funext b,
rw multiset.erase_dup_eq_self.2,
exact multiset.nodup_map (multiset.injective_pi_cons ha) (pi s t).2,
end
end pi
section powerset
def powerset (s : finset α) : finset (finset α) :=
⟨s.1.powerset.pmap finset.mk
(λ t h, nodup_of_le (mem_powerset.1 h) s.2),
nodup_pmap (λ a ha b hb, congr_arg finset.val)
(nodup_powerset.2 s.2)⟩
@[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t :=
by cases s; simp only [powerset, mem_mk, mem_pmap, mem_powerset, exists_prop, exists_eq_right]; rw ← val_le_iff
@[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s :=
mem_powerset.2 (empty_subset _)
@[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s :=
mem_powerset.2 (subset.refl _)
@[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t :=
⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _),
λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩
@[simp] theorem card_powerset (s : finset α) :
card (powerset s) = 2 ^ card s :=
(card_pmap _ _ _).trans (card_powerset s.1)
end powerset
section fold
variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op]
local notation a * b := op a b
include hc ha
/-- `fold op b f s` folds the commutative associative operation `op` over the
`f`-image of `s`, i.e. `fold (+) b f {1,2,3} = `f 1 + f 2 + f 3 + b`. -/
def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b
variables {op} {f : α → β} {b : β} {s : finset α} {a : α}
@[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl
@[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f :=
by unfold fold; rw [insert_val, ndinsert_of_not_mem h, map_cons, fold_cons_left]
@[simp] theorem fold_singleton : (singleton a).fold op b f = f a * b := rfl
@[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ}
(H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) :=
by simp only [fold, image_val_of_inj_on H, multiset.map_map]
@[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g :=
by rw [fold, fold, map_congr H]
theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} :
s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g :=
by simp only [fold, fold_distrib]
theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op']
{m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) :
s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) :=
by rw [fold, fold, ← fold_hom op hm, multiset.map_map]
theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} :
(s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f :=
by unfold fold; rw [← fold_add op, ← map_add, union_val,
inter_val, union_add_inter, map_add, hc.comm, fold_add]
@[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] :
(insert a s).fold op b f = f a * s.fold op b f :=
by haveI := classical.prop_decidable;
rw [fold, insert_val', ← fold_erase_dup_idem op, erase_dup_map_erase_dup_eq,
fold_erase_dup_idem op]; simp only [map_cons, fold_cons_left, fold]
end fold
section sup
variables [semilattice_sup_bot α]
/-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/
def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f
variables {s s₁ s₂ : finset β} {f : β → α}
lemma sup_val : s.sup f = (s.1.map f).sup := rfl
@[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ :=
fold_empty
@[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f :=
fold_insert_idem
@[simp] lemma sup_singleton [decidable_eq β] {b : β} : ({b} : finset β).sup f = f b :=
calc _ = f b ⊔ (∅:finset β).sup f : sup_insert
... = f b : sup_bot_eq
lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f :=
finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih,
by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc]
lemma sup_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.sup f ≤ s.sup g :=
by letI := classical.dec_eq β; from
finset.induction_on s (λ _, le_refl _) (λ a s has ih H,
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H;
simp only [sup_insert]; exact sup_le_sup H.1 (ih H.2))
lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f :=
by letI := classical.dec_eq β; from
calc f b ≤ f b ⊔ s.sup f : le_sup_left
... = (insert b s).sup f : sup_insert.symm
... = s.sup f : by rw [insert_eq_of_mem hb]
lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a :=
by letI := classical.dec_eq β; from
finset.induction_on s (λ _, bot_le) (λ n s hns ih H,
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H;
simp only [sup_insert]; exact sup_le H.1 (ih H.2))
lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) :=
iff.intro (assume h b hb, le_trans (le_sup hb) h) sup_le
lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f :=
sup_le $ assume b hb, le_sup (h hb)
lemma sup_lt [is_total α (≤)] {a : α} : (⊥ < a) → (∀b ∈ s, f b < a) → s.sup f < a :=
by letI := classical.dec_eq β; from
finset.induction_on s (by simp) (by simp {contextual := tt})
lemma comp_sup_eq_sup_comp [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ]
(g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) :=
have A : ∀x y, g (x ⊔ y) = g x ⊔ g y :=
begin
assume x y,
cases (is_total.total (≤) x y) with h,
{ simp [sup_of_le_right h, sup_of_le_right (mono_g h)] },
{ simp [sup_of_le_left h, sup_of_le_left (mono_g h)] }
end,
by letI := classical.dec_eq β; from
finset.induction_on s (by simp [bot]) (by simp [A] {contextual := tt})
end sup
lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) :=
le_antisymm
(finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha)
(supr_le $ assume a, supr_le $ assume ha, le_sup ha)
section inf
variables [semilattice_inf_top α]
/-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/
def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f
variables {s s₁ s₂ : finset β} {f : β → α}
lemma inf_val : s.inf f = (s.1.map f).inf := rfl
@[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ :=
fold_empty
@[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f :=
fold_insert_idem
@[simp] lemma inf_singleton [decidable_eq β] {b : β} : ({b} : finset β).inf f = f b :=
calc _ = f b ⊓ (∅:finset β).inf f : inf_insert
... = f b : inf_top_eq
lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f :=
finset.induction_on s₁ (by rw [empty_union, inf_empty, top_inf_eq]) $ λ a s has ih,
by rw [insert_union, inf_insert, inf_insert, ih, inf_assoc]
lemma inf_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.inf f ≤ s.inf g :=
by letI := classical.dec_eq β; from
finset.induction_on s (λ _, le_refl _) (λ a s has ih H,
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H;
simp only [inf_insert]; exact inf_le_inf H.1 (ih H.2))
lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b :=
by letI := classical.dec_eq β; from
calc f b ≥ f b ⊓ s.inf f : inf_le_left
... = (insert b s).inf f : inf_insert.symm
... = s.inf f : by rw [insert_eq_of_mem hb]
lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f :=
by letI := classical.dec_eq β; from
finset.induction_on s (λ _, le_top) (λ n s hns ih H,
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H;
simp only [inf_insert]; exact le_inf H.1 (ih H.2))
lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ (∀b ∈ s, a ≤ f b) :=
iff.intro (assume h b hb, le_trans h (inf_le hb)) le_inf
lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f :=
le_inf $ assume b hb, inf_le (h hb)
lemma lt_inf [is_total α (≤)] {a : α} : (a < ⊤) → (∀b ∈ s, a < f b) → a < s.inf f :=
by letI := classical.dec_eq β; from
finset.induction_on s (by simp) (by simp {contextual := tt})
lemma comp_inf_eq_inf_comp [is_total α (≤)] {γ : Type} [semilattice_inf_top γ]
(g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) :=
have A : ∀x y, g (x ⊓ y) = g x ⊓ g y :=
begin
assume x y,
cases (is_total.total (≤) x y) with h,
{ simp [inf_of_le_left h, inf_of_le_left (mono_g h)] },
{ simp [inf_of_le_right h, inf_of_le_right (mono_g h)] }
end,
by letI := classical.dec_eq β; from
finset.induction_on s (by simp [top]) (by simp [A] {contextual := tt})
end inf
lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) :=
le_antisymm
(le_infi $ assume a, le_infi $ assume ha, inf_le ha)
(finset.le_inf $ assume a ha, infi_le_of_le a $ infi_le _ ha)
/- max and min of finite sets -/
section max_min
variables [decidable_linear_order α]
protected def max : finset α → option α :=
fold (option.lift_or_get max) none some
theorem max_eq_sup_with_bot (s : finset α) :
s.max = @sup (with_bot α) α _ s some := rfl
@[simp] theorem max_empty : (∅ : finset α).max = none := rfl
@[simp] theorem max_insert {a : α} {s : finset α} :
(insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem
@[simp] theorem max_singleton {a : α} : finset.max {a} = some a := max_insert
@[simp] theorem max_singleton' {a : α} : finset.max (singleton a) = some a := max_singleton
theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max :=
(@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst
theorem max_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.max :=
let ⟨a, ha⟩ := exists_mem_of_ne_empty h in max_of_mem ha
theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ :=
⟨λ h, by_contradiction $
λ hs, let ⟨a, ha⟩ := max_of_ne_empty hs in by rw [h] at ha; cases ha,
λ h, h.symm ▸ max_empty⟩
theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s :=
finset.induction_on s (λ _ H, by cases H)
(λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max),
begin
by_cases p : b = a,
{ induction p, exact mem_insert_self b s },
{ cases option.lift_or_get_choice max_choice (some b) s.max with q q;
rw [max_insert, q] at h,
{ cases h, cases p rfl },
{ exact mem_insert_of_mem (ih h) } }
end)
theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b :=
by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩;
cases h₂.symm.trans hb; assumption
protected def min : finset α → option α :=
fold (option.lift_or_get min) none some
theorem min_eq_inf_with_top (s : finset α) :
s.min = @inf (with_top α) α _ s some := rfl
@[simp] theorem min_empty : (∅ : finset α).min = none := rfl
@[simp] theorem min_insert {a : α} {s : finset α} :
(insert a s).min = option.lift_or_get min (some a) s.min :=
fold_insert_idem
@[simp] theorem min_singleton {a : α} : finset.min {a} = some a := min_insert
theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min :=
(@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst
theorem min_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.min :=
let ⟨a, ha⟩ := exists_mem_of_ne_empty h in min_of_mem ha
theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ :=
⟨λ h, by_contradiction $
λ hs, let ⟨a, ha⟩ := min_of_ne_empty hs in by rw [h] at ha; cases ha,
λ h, h.symm ▸ min_empty⟩
theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s :=
finset.induction_on s (λ _ H, by cases H) $
λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min),
begin
by_cases p : b = a,
{ induction p, exact mem_insert_self b s },
{ cases option.lift_or_get_choice min_choice (some b) s.min with q q;
rw [min_insert, q] at h,
{ cases h, cases p rfl },
{ exact mem_insert_of_mem (ih h) } }
end
theorem le_min_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b :=
by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩;
cases h₂.symm.trans hb; assumption
end max_min
section sort
variables (r : α → α → Prop) [decidable_rel r]
[is_trans α r] [is_antisymm α r] [is_total α r]
/-- `sort s` constructs a sorted list from the unordered set `s`.
(Uses merge sort algorithm.) -/
def sort (s : finset α) : list α := sort r s.1
@[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) :=
sort_sorted _ _
@[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 :=
sort_eq _ _
@[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup :=
(by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s))
@[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s :=
list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s)
@[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
multiset.mem_sort _
end sort
section disjoint
variable [decidable_eq α]
theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t :=
by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl
theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 :=
disjoint_left
theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ :=
disjoint_iff
theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
by rw [disjoint.comm, disjoint_left]
theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t :=
disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁))
theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t :=
disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁))
@[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left
@[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right
@[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s :=
by simp only [disjoint_left, mem_singleton, forall_eq]
@[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s :=
disjoint.comm.trans singleton_disjoint
@[simp] theorem disjoint_insert_left {a : α} {s t : finset α} :
disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t :=
by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
@[simp] theorem disjoint_insert_right {a : α} {s t : finset α} :
disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t :=
disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm]
@[simp] theorem disjoint_union_left {s t u : finset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right {s t u : finset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib]
@[simp] theorem card_disjoint_union {s t : finset α} :
disjoint s t → card (s ∪ t) = card s + card t :=
finset.induction_on s (λ _, by simp only [empty_union, card_empty, zero_add]) $ λ a s ha ih H,
have h1 : a ∉ s ∪ t, from λ h, or.elim (mem_union.1 h) ha (disjoint_insert_left.1 H).1,
by rw [insert_union, card_insert_of_not_mem h1, card_insert_of_not_mem ha, ih (disjoint_insert_left.1 H).2, add_right_comm]
end disjoint
theorem sort_sorted_lt [decidable_linear_order α] (s : finset α) :
list.sorted (<) (sort (≤) s) :=
(sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _)
instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩
def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) :=
⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.mk.inj) s.2⟩
@[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} :
a ∈ s.attach_fin h ↔ a.1 ∈ s :=
⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁,
λ h, multiset.mem_pmap.2 ⟨a.1, h, fin.eta _ _⟩⟩
@[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) :
(s.attach_fin h).card = s.card := multiset.card_pmap _ _ _
section choose
variables (p : α → Prop) [decidable_pred p] (l : finset α)
def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } :=
multiset.choose_x p l.val hp
def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp
lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
theorem lt_wf {α} [decidable_eq α] : well_founded (@has_lt.lt (finset α) _) :=
have H : subrelation (@has_lt.lt (finset α) _)
(inv_image (<) card),
from λ x y hxy, card_lt_card hxy,
subrelation.wf H $ inv_image.wf _ $ nat.lt_wf
section decidable_linear_order
variables {α} [decidable_linear_order α]
def min' (S : finset α) (H : S ≠ ∅) : α :=
@option.get _ S.min $
let ⟨k, hk⟩ := exists_mem_of_ne_empty H in
let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb]
def max' (S : finset α) (H : S ≠ ∅) : α :=
@option.get _ S.max $
let ⟨k, hk⟩ := exists_mem_of_ne_empty H in
let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb]
variables (S : finset α) (H : S ≠ ∅)
theorem min'_mem : S.min' H ∈ S := mem_of_min $ by simp [min']
theorem min'_le (x) (H2 : x ∈ S) : S.min' H ≤ x := le_min_of_mem H2 $ option.get_mem _
theorem le_min' (x) (H2 : ∀ y ∈ S, x ≤ y) : x ≤ S.min' H := H2 _ $ min'_mem _ _
theorem max'_mem : S.max' H ∈ S := mem_of_max $ by simp [max']
theorem le_max' (x) (H2 : x ∈ S) : x ≤ S.max' H := le_max_of_mem H2 $ option.get_mem _
theorem max'_le (x) (H2 : ∀ y ∈ S, y ≤ x) : S.max' H ≤ x := H2 _ $ max'_mem _ _
theorem min'_lt_max' {i j} (H1 : i ∈ S) (H2 : j ∈ S) (H3 : i ≠ j) : S.min' H < S.max' H :=
begin
rcases lt_trichotomy i j with H4 | H4 | H4,
{ have H5 := min'_le S H i H1,
have H6 := le_max' S H j H2,
apply lt_of_le_of_lt H5,
apply lt_of_lt_of_le H4 H6 },
{ cc },
{ have H5 := min'_le S H j H2,
have H6 := le_max' S H i H1,
apply lt_of_le_of_lt H5,
apply lt_of_lt_of_le H4 H6 }
end
end decidable_linear_order
end finset
namespace list
variable [decidable_eq α]
theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length :=
congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h
end list
|
c14e5a2665245a0b6c0524ea62c9ed76c5dc5b3e
|
cf39355caa609c0f33405126beee2739aa3cb77e
|
/tests/lean/run/record9.lean
|
5c126635ec3737f9ec419856d8d72ec2a1f2204f
|
[
"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
| 127
|
lean
|
constant {u} fibrant : Type u → Prop
structure {u} Fib : Type (u+1) :=
{type : Type u} (pred : fibrant type)
#check Fib.mk
|
d1355b66364515010ec0df75ffdc482f2a59dd8d
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/linear_algebra/projection.lean
|
d8f56f520278e01d478deb84e6eaff47a10b1aeb
|
[
"Apache-2.0"
] |
permissive
|
leanprover-community/mathlib
|
56a2cadd17ac88caf4ece0a775932fa26327ba0e
|
442a83d738cb208d3600056c489be16900ba701d
|
refs/heads/master
| 1,693,584,102,358
| 1,693,471,902,000
| 1,693,471,902,000
| 97,922,418
| 1,595
| 352
|
Apache-2.0
| 1,694,693,445,000
| 1,500,624,130,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 16,863
|
lean
|
/-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import linear_algebra.quotient
import linear_algebra.prod
/-!
# Projection to a subspace
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we define
* `linear_proj_of_is_compl (p q : submodule R E) (h : is_compl p q)`: the projection of a module `E`
to a submodule `p` along its complement `q`; it is the unique linear map `f : E → p` such that
`f x = x` for `x ∈ p` and `f x = 0` for `x ∈ q`.
* `is_compl_equiv_proj p`: equivalence between submodules `q` such that `is_compl p q` and
projections `f : E → p`, `∀ x ∈ p, f x = x`.
We also provide some lemmas justifying correctness of our definitions.
## Tags
projection, complement subspace
-/
section ring
variables {R : Type*} [ring R] {E : Type*} [add_comm_group E] [module R E]
{F : Type*} [add_comm_group F] [module R F]
{G : Type*} [add_comm_group G] [module R G] (p q : submodule R E)
variables {S : Type*} [semiring S] {M : Type*} [add_comm_monoid M] [module S M] (m : submodule S M)
noncomputable theory
namespace linear_map
variable {p}
open submodule
lemma ker_id_sub_eq_of_proj {f : E →ₗ[R] p} (hf : ∀ x : p, f x = x) :
ker (id - p.subtype.comp f) = p :=
begin
ext x,
simp only [comp_apply, mem_ker, subtype_apply, sub_apply, id_apply, sub_eq_zero],
exact ⟨λ h, h.symm ▸ submodule.coe_mem _, λ hx, by erw [hf ⟨x, hx⟩, subtype.coe_mk]⟩
end
lemma range_eq_of_proj {f : E →ₗ[R] p} (hf : ∀ x : p, f x = x) :
range f = ⊤ :=
range_eq_top.2 $ λ x, ⟨x, hf x⟩
lemma is_compl_of_proj {f : E →ₗ[R] p} (hf : ∀ x : p, f x = x) :
is_compl p f.ker :=
begin
split,
{ rw disjoint_iff_inf_le,
rintros x ⟨hpx, hfx⟩,
erw [set_like.mem_coe, mem_ker, hf ⟨x, hpx⟩, mk_eq_zero] at hfx,
simp only [hfx, set_like.mem_coe, zero_mem] },
{ rw codisjoint_iff_le_sup,
intros x hx,
rw [mem_sup'],
refine ⟨f x, ⟨x - f x, _⟩, add_sub_cancel'_right _ _⟩,
rw [mem_ker, linear_map.map_sub, hf, sub_self] }
end
end linear_map
namespace submodule
open linear_map
/-- If `q` is a complement of `p`, then `M/p ≃ q`. -/
def quotient_equiv_of_is_compl (h : is_compl p q) : (E ⧸ p) ≃ₗ[R] q :=
linear_equiv.symm $ linear_equiv.of_bijective (p.mkq.comp q.subtype)
⟨by rw [← ker_eq_bot, ker_comp, ker_mkq, disjoint_iff_comap_eq_bot.1 h.symm.disjoint],
by rw [← range_eq_top, range_comp, range_subtype, map_mkq_eq_top, h.sup_eq_top]⟩
@[simp] lemma quotient_equiv_of_is_compl_symm_apply (h : is_compl p q) (x : q) :
(quotient_equiv_of_is_compl p q h).symm x = quotient.mk x := rfl
@[simp] lemma quotient_equiv_of_is_compl_apply_mk_coe (h : is_compl p q) (x : q) :
quotient_equiv_of_is_compl p q h (quotient.mk x) = x :=
(quotient_equiv_of_is_compl p q h).apply_symm_apply x
@[simp] lemma mk_quotient_equiv_of_is_compl_apply (h : is_compl p q) (x : E ⧸ p) :
(quotient.mk (quotient_equiv_of_is_compl p q h x) : E ⧸ p) = x :=
(quotient_equiv_of_is_compl p q h).symm_apply_apply x
/-- If `q` is a complement of `p`, then `p × q` is isomorphic to `E`. It is the unique
linear map `f : E → p` such that `f x = x` for `x ∈ p` and `f x = 0` for `x ∈ q`. -/
def prod_equiv_of_is_compl (h : is_compl p q) : (p × q) ≃ₗ[R] E :=
begin
apply linear_equiv.of_bijective (p.subtype.coprod q.subtype),
split,
{ rw [← ker_eq_bot, ker_coprod_of_disjoint_range, ker_subtype, ker_subtype, prod_bot],
rw [range_subtype, range_subtype],
exact h.1 },
{ rw [← range_eq_top, ← sup_eq_range, h.sup_eq_top] }
end
@[simp] lemma coe_prod_equiv_of_is_compl (h : is_compl p q) :
(prod_equiv_of_is_compl p q h : (p × q) →ₗ[R] E) = p.subtype.coprod q.subtype := rfl
@[simp] lemma coe_prod_equiv_of_is_compl' (h : is_compl p q) (x : p × q) :
prod_equiv_of_is_compl p q h x = x.1 + x.2 := rfl
@[simp] lemma prod_equiv_of_is_compl_symm_apply_left (h : is_compl p q) (x : p) :
(prod_equiv_of_is_compl p q h).symm x = (x, 0) :=
(prod_equiv_of_is_compl p q h).symm_apply_eq.2 $ by simp
@[simp] lemma prod_equiv_of_is_compl_symm_apply_right (h : is_compl p q) (x : q) :
(prod_equiv_of_is_compl p q h).symm x = (0, x) :=
(prod_equiv_of_is_compl p q h).symm_apply_eq.2 $ by simp
@[simp] lemma prod_equiv_of_is_compl_symm_apply_fst_eq_zero (h : is_compl p q) {x : E} :
((prod_equiv_of_is_compl p q h).symm x).1 = 0 ↔ x ∈ q :=
begin
conv_rhs { rw [← (prod_equiv_of_is_compl p q h).apply_symm_apply x] },
rw [coe_prod_equiv_of_is_compl', submodule.add_mem_iff_left _ (submodule.coe_mem _),
mem_right_iff_eq_zero_of_disjoint h.disjoint]
end
@[simp] lemma prod_equiv_of_is_compl_symm_apply_snd_eq_zero (h : is_compl p q) {x : E} :
((prod_equiv_of_is_compl p q h).symm x).2 = 0 ↔ x ∈ p :=
begin
conv_rhs { rw [← (prod_equiv_of_is_compl p q h).apply_symm_apply x] },
rw [coe_prod_equiv_of_is_compl', submodule.add_mem_iff_right _ (submodule.coe_mem _),
mem_left_iff_eq_zero_of_disjoint h.disjoint]
end
@[simp]
lemma prod_comm_trans_prod_equiv_of_is_compl (h : is_compl p q) :
linear_equiv.prod_comm R q p ≪≫ₗ prod_equiv_of_is_compl p q h =
prod_equiv_of_is_compl q p h.symm :=
linear_equiv.ext $ λ _, add_comm _ _
/-- Projection to a submodule along its complement. -/
def linear_proj_of_is_compl (h : is_compl p q) :
E →ₗ[R] p :=
(linear_map.fst R p q) ∘ₗ ↑(prod_equiv_of_is_compl p q h).symm
variables {p q}
@[simp] lemma linear_proj_of_is_compl_apply_left (h : is_compl p q) (x : p) :
linear_proj_of_is_compl p q h x = x :=
by simp [linear_proj_of_is_compl]
@[simp] lemma linear_proj_of_is_compl_range (h : is_compl p q) :
(linear_proj_of_is_compl p q h).range = ⊤ :=
range_eq_of_proj (linear_proj_of_is_compl_apply_left h)
@[simp] lemma linear_proj_of_is_compl_apply_eq_zero_iff (h : is_compl p q) {x : E} :
linear_proj_of_is_compl p q h x = 0 ↔ x ∈ q:=
by simp [linear_proj_of_is_compl]
lemma linear_proj_of_is_compl_apply_right' (h : is_compl p q) (x : E) (hx : x ∈ q) :
linear_proj_of_is_compl p q h x = 0 :=
(linear_proj_of_is_compl_apply_eq_zero_iff h).2 hx
@[simp] lemma linear_proj_of_is_compl_apply_right (h : is_compl p q) (x : q) :
linear_proj_of_is_compl p q h x = 0 :=
linear_proj_of_is_compl_apply_right' h x x.2
@[simp] lemma linear_proj_of_is_compl_ker (h : is_compl p q) :
(linear_proj_of_is_compl p q h).ker = q :=
ext $ λ x, mem_ker.trans (linear_proj_of_is_compl_apply_eq_zero_iff h)
lemma linear_proj_of_is_compl_comp_subtype (h : is_compl p q) :
(linear_proj_of_is_compl p q h).comp p.subtype = id :=
linear_map.ext $ linear_proj_of_is_compl_apply_left h
lemma linear_proj_of_is_compl_idempotent (h : is_compl p q) (x : E) :
linear_proj_of_is_compl p q h (linear_proj_of_is_compl p q h x) =
linear_proj_of_is_compl p q h x :=
linear_proj_of_is_compl_apply_left h _
lemma exists_unique_add_of_is_compl_prod (hc : is_compl p q) (x : E) :
∃! (u : p × q), (u.fst : E) + u.snd = x :=
(prod_equiv_of_is_compl _ _ hc).to_equiv.bijective.exists_unique _
lemma exists_unique_add_of_is_compl (hc : is_compl p q) (x : E) :
∃ (u : p) (v : q), ((u : E) + v = x ∧ ∀ (r : p) (s : q),
(r : E) + s = x → r = u ∧ s = v) :=
let ⟨u, hu₁, hu₂⟩ := exists_unique_add_of_is_compl_prod hc x in
⟨u.1, u.2, hu₁, λ r s hrs, prod.eq_iff_fst_eq_snd_eq.1 (hu₂ ⟨r, s⟩ hrs)⟩
lemma linear_proj_add_linear_proj_of_is_compl_eq_self (hpq : is_compl p q) (x : E) :
(p.linear_proj_of_is_compl q hpq x + q.linear_proj_of_is_compl p hpq.symm x : E) = x :=
begin
dunfold linear_proj_of_is_compl,
rw ←prod_comm_trans_prod_equiv_of_is_compl _ _ hpq,
exact (prod_equiv_of_is_compl _ _ hpq).apply_symm_apply x,
end
end submodule
namespace linear_map
open submodule
/-- Given linear maps `φ` and `ψ` from complement submodules, `of_is_compl` is
the induced linear map over the entire module. -/
def of_is_compl {p q : submodule R E} (h : is_compl p q)
(φ : p →ₗ[R] F) (ψ : q →ₗ[R] F) : E →ₗ[R] F :=
(linear_map.coprod φ ψ) ∘ₗ ↑(submodule.prod_equiv_of_is_compl _ _ h).symm
variables {p q}
@[simp] lemma of_is_compl_left_apply
(h : is_compl p q) {φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} (u : p) :
of_is_compl h φ ψ (u : E) = φ u := by simp [of_is_compl]
@[simp] lemma of_is_compl_right_apply
(h : is_compl p q) {φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} (v : q) :
of_is_compl h φ ψ (v : E) = ψ v := by simp [of_is_compl]
lemma of_is_compl_eq (h : is_compl p q)
{φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} {χ : E →ₗ[R] F}
(hφ : ∀ u, φ u = χ u) (hψ : ∀ u, ψ u = χ u) :
of_is_compl h φ ψ = χ :=
begin
ext x,
obtain ⟨_, _, rfl, _⟩ := exists_unique_add_of_is_compl h x,
simp [of_is_compl, hφ, hψ]
end
lemma of_is_compl_eq' (h : is_compl p q)
{φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} {χ : E →ₗ[R] F}
(hφ : φ = χ.comp p.subtype) (hψ : ψ = χ.comp q.subtype) :
of_is_compl h φ ψ = χ :=
of_is_compl_eq h (λ _, hφ.symm ▸ rfl) (λ _, hψ.symm ▸ rfl)
@[simp] lemma of_is_compl_zero (h : is_compl p q) :
(of_is_compl h 0 0 : E →ₗ[R] F) = 0 :=
of_is_compl_eq _ (λ _, rfl) (λ _, rfl)
@[simp] lemma of_is_compl_add (h : is_compl p q)
{φ₁ φ₂ : p →ₗ[R] F} {ψ₁ ψ₂ : q →ₗ[R] F} :
of_is_compl h (φ₁ + φ₂) (ψ₁ + ψ₂) = of_is_compl h φ₁ ψ₁ + of_is_compl h φ₂ ψ₂ :=
of_is_compl_eq _ (by simp) (by simp)
@[simp] lemma of_is_compl_smul
{R : Type*} [comm_ring R] {E : Type*} [add_comm_group E] [module R E]
{F : Type*} [add_comm_group F] [module R F] {p q : submodule R E}
(h : is_compl p q) {φ : p →ₗ[R] F} {ψ : q →ₗ[R] F} (c : R) :
of_is_compl h (c • φ) (c • ψ) = c • of_is_compl h φ ψ :=
of_is_compl_eq _ (by simp) (by simp)
section
variables {R₁ : Type*} [comm_ring R₁] [module R₁ E] [module R₁ F]
/-- The linear map from `(p →ₗ[R₁] F) × (q →ₗ[R₁] F)` to `E →ₗ[R₁] F`. -/
def of_is_compl_prod {p q : submodule R₁ E} (h : is_compl p q) :
((p →ₗ[R₁] F) × (q →ₗ[R₁] F)) →ₗ[R₁] (E →ₗ[R₁] F) :=
{ to_fun := λ φ, of_is_compl h φ.1 φ.2,
map_add' := by { intros φ ψ, rw [prod.snd_add, prod.fst_add, of_is_compl_add] },
map_smul' := by { intros c φ, simp [prod.smul_snd, prod.smul_fst, of_is_compl_smul] } }
@[simp] lemma of_is_compl_prod_apply {p q : submodule R₁ E} (h : is_compl p q)
(φ : (p →ₗ[R₁] F) × (q →ₗ[R₁] F)) : of_is_compl_prod h φ = of_is_compl h φ.1 φ.2 := rfl
/-- The natural linear equivalence between `(p →ₗ[R₁] F) × (q →ₗ[R₁] F)` and `E →ₗ[R₁] F`. -/
def of_is_compl_prod_equiv {p q : submodule R₁ E} (h : is_compl p q) :
((p →ₗ[R₁] F) × (q →ₗ[R₁] F)) ≃ₗ[R₁] (E →ₗ[R₁] F) :=
{ inv_fun := λ φ, ⟨φ.dom_restrict p, φ.dom_restrict q⟩,
left_inv :=
begin
intros φ, ext,
{ exact of_is_compl_left_apply h x },
{ exact of_is_compl_right_apply h x }
end,
right_inv :=
begin
intro φ, ext,
obtain ⟨a, b, hab, _⟩ := exists_unique_add_of_is_compl h x,
rw [← hab], simp,
end, .. of_is_compl_prod h }
end
@[simp] lemma linear_proj_of_is_compl_of_proj (f : E →ₗ[R] p) (hf : ∀ x : p, f x = x) :
p.linear_proj_of_is_compl f.ker (is_compl_of_proj hf) = f :=
begin
ext x,
have : x ∈ p ⊔ f.ker,
{ simp only [(is_compl_of_proj hf).sup_eq_top, mem_top] },
rcases mem_sup'.1 this with ⟨x, y, rfl⟩,
simp [hf]
end
/-- If `f : E →ₗ[R] F` and `g : E →ₗ[R] G` are two surjective linear maps and
their kernels are complement of each other, then `x ↦ (f x, g x)` defines
a linear equivalence `E ≃ₗ[R] F × G`. -/
def equiv_prod_of_surjective_of_is_compl (f : E →ₗ[R] F) (g : E →ₗ[R] G) (hf : f.range = ⊤)
(hg : g.range = ⊤) (hfg : is_compl f.ker g.ker) :
E ≃ₗ[R] F × G :=
linear_equiv.of_bijective (f.prod g) ⟨by simp [← ker_eq_bot, hfg.inf_eq_bot],
by { rw [←range_eq_top], simp [range_prod_eq hfg.sup_eq_top, *] }⟩
@[simp] lemma coe_equiv_prod_of_surjective_of_is_compl {f : E →ₗ[R] F} {g : E →ₗ[R] G}
(hf : f.range = ⊤) (hg : g.range = ⊤) (hfg : is_compl f.ker g.ker) :
(equiv_prod_of_surjective_of_is_compl f g hf hg hfg : E →ₗ[R] F × G) = f.prod g :=
rfl
@[simp] lemma equiv_prod_of_surjective_of_is_compl_apply {f : E →ₗ[R] F} {g : E →ₗ[R] G}
(hf : f.range = ⊤) (hg : g.range = ⊤) (hfg : is_compl f.ker g.ker) (x : E):
equiv_prod_of_surjective_of_is_compl f g hf hg hfg x = (f x, g x) :=
rfl
end linear_map
namespace submodule
open linear_map
/-- Equivalence between submodules `q` such that `is_compl p q` and linear maps `f : E →ₗ[R] p`
such that `∀ x : p, f x = x`. -/
def is_compl_equiv_proj :
{q // is_compl p q} ≃ {f : E →ₗ[R] p // ∀ x : p, f x = x} :=
{ to_fun := λ q, ⟨linear_proj_of_is_compl p q q.2, linear_proj_of_is_compl_apply_left q.2⟩,
inv_fun := λ f, ⟨(f : E →ₗ[R] p).ker, is_compl_of_proj f.2⟩,
left_inv := λ ⟨q, hq⟩, by simp only [linear_proj_of_is_compl_ker, subtype.coe_mk],
right_inv := λ ⟨f, hf⟩, subtype.eq $ f.linear_proj_of_is_compl_of_proj hf }
@[simp] lemma coe_is_compl_equiv_proj_apply (q : {q // is_compl p q}) :
(p.is_compl_equiv_proj q : E →ₗ[R] p) = linear_proj_of_is_compl p q q.2 := rfl
@[simp] lemma coe_is_compl_equiv_proj_symm_apply (f : {f : E →ₗ[R] p // ∀ x : p, f x = x}) :
(p.is_compl_equiv_proj.symm f : submodule R E) = (f : E →ₗ[R] p).ker := rfl
end submodule
namespace linear_map
open submodule
/--
A linear endomorphism of a module `E` is a projection onto a submodule `p` if it sends every element
of `E` to `p` and fixes every element of `p`.
The definition allow more generally any `fun_like` type and not just linear maps, so that it can be
used for example with `continuous_linear_map` or `matrix`.
-/
structure is_proj {F : Type*} [fun_like F M (λ _, M)] (f : F) : Prop :=
(map_mem : ∀ x, f x ∈ m)
(map_id : ∀ x ∈ m, f x = x)
lemma is_proj_iff_idempotent (f : M →ₗ[S] M) : (∃ p : submodule S M, is_proj p f) ↔ f ∘ₗ f = f :=
begin
split,
{ intro h, obtain ⟨p, hp⟩ := h, ext, rw comp_apply, exact hp.map_id (f x) (hp.map_mem x), },
{ intro h, use f.range, split,
{ intro x, exact mem_range_self f x, },
{ intros x hx, obtain ⟨y, hy⟩ := mem_range.1 hx, rw [←hy, ←comp_apply, h], }, },
end
namespace is_proj
variables {p m}
/--
Restriction of the codomain of a projection of onto a subspace `p` to `p` instead of the whole
space.
-/
def cod_restrict {f : M →ₗ[S] M} (h : is_proj m f) : M →ₗ[S] m :=
f.cod_restrict m h.map_mem
@[simp]
lemma cod_restrict_apply {f : M →ₗ[S] M} (h : is_proj m f) (x : M) :
↑(h.cod_restrict x) = f x := f.cod_restrict_apply m x
@[simp]
lemma cod_restrict_apply_cod {f : M →ₗ[S] M} (h : is_proj m f) (x : m) :
h.cod_restrict x = x :=
by {ext, rw [cod_restrict_apply], exact h.map_id x x.2}
lemma cod_restrict_ker {f : M →ₗ[S] M} (h : is_proj m f) :
h.cod_restrict.ker = f.ker := f.ker_cod_restrict m _
lemma is_compl {f : E →ₗ[R] E} (h : is_proj p f) : is_compl p f.ker :=
by { rw ←cod_restrict_ker, exact is_compl_of_proj h.cod_restrict_apply_cod, }
lemma eq_conj_prod_map' {f : E →ₗ[R] E} (h : is_proj p f) :
f = (p.prod_equiv_of_is_compl f.ker h.is_compl).to_linear_map ∘ₗ prod_map id 0 ∘ₗ
(p.prod_equiv_of_is_compl f.ker h.is_compl).symm.to_linear_map :=
begin
refine (linear_map.cancel_right
(p.prod_equiv_of_is_compl f.ker h.is_compl).surjective).1 _,
ext,
{ simp only [coe_comp, linear_equiv.coe_to_linear_map, coe_inl, function.comp_app,
linear_equiv.of_top_apply, linear_equiv.of_injective_apply, coprod_apply, submodule.coe_subtype,
coe_zero, add_zero, prod_equiv_of_is_compl_symm_apply_left, prod_map_apply, id_coe, id.def,
zero_apply, coe_prod_equiv_of_is_compl', h.map_id x x.2], },
{simp only [coe_comp, linear_equiv.coe_to_linear_map, coe_inr, function.comp_app,
linear_equiv.of_top_apply, linear_equiv.of_injective_apply, coprod_apply, submodule.coe_subtype,
coe_zero, zero_add, map_coe_ker, prod_equiv_of_is_compl_symm_apply_right, prod_map_apply, id_coe,
id.def, zero_apply, coe_prod_equiv_of_is_compl'], }
end
end is_proj
end linear_map
end ring
section comm_ring
namespace linear_map
variables {R : Type*} [comm_ring R] {E : Type*} [add_comm_group E] [module R E] {p : submodule R E}
lemma is_proj.eq_conj_prod_map {f : E →ₗ[R] E} (h : is_proj p f) :
f = (p.prod_equiv_of_is_compl f.ker h.is_compl).conj (prod_map id 0) :=
by {rw linear_equiv.conj_apply, exact h.eq_conj_prod_map'}
end linear_map
end comm_ring
|
eee53b7f4d1b6729eb0cccb5000c900494f56ece
|
b3fced0f3ff82d577384fe81653e47df68bb2fa1
|
/src/measure_theory/measure_space.lean
|
7f218566327cc510c416d7f2e22353064ad77bfc
|
[
"Apache-2.0"
] |
permissive
|
ratmice/mathlib
|
93b251ef5df08b6fd55074650ff47fdcc41a4c75
|
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
|
refs/heads/master
| 1,599,240,104,318
| 1,572,981,183,000
| 1,572,981,183,000
| 219,830,178
| 0
| 0
|
Apache-2.0
| 1,572,980,897,000
| 1,572,980,896,000
| null |
UTF-8
|
Lean
| false
| false
| 35,080
|
lean
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
Measure spaces -- measures
Measures are restricted to a measurable space (associated by the type class `measurable_space`).
This allows us to prove equalities between measures by restricting to a generating set of the
measurable space.
On the other hand, the `μ.measure s` projection (i.e. the measure of `s` on the measure space `μ`)
is the _outer_ measure generated by `μ`. This gives us a unrestricted monotonicity rule and it is
somehow well-behaved on non-measurable sets.
This allows us for the `lebesgue` measure space to have the `borel` measurable space, but still be
a complete measure.
-/
import data.set.lattice data.set.finite
import topology.instances.ennreal
measure_theory.outer_measure
noncomputable theory
open classical set lattice filter finset function
open_locale classical
universes u v w x
namespace measure_theory
section of_measurable
parameters {α : Type*} [measurable_space α]
parameters (m : Π (s : set α), is_measurable s → ennreal)
parameters (m0 : m ∅ is_measurable.empty = 0)
include m0
/-- Measure projection which is ∞ for non-measurable sets.
`measure'` is mainly used to derive the outer measure, for the main `measure` projection. -/
def measure' (s : set α) : ennreal := ⨅ h : is_measurable s, m s h
lemma measure'_eq {s} (h : is_measurable s) : measure' s = m s h :=
by simp [measure', h]
lemma measure'_empty : measure' ∅ = 0 :=
(measure'_eq is_measurable.empty).trans m0
lemma measure'_Union_nat
{f : ℕ → set α}
(hm : ∀i, is_measurable (f i))
(mU : m (⋃i, f i) (is_measurable.Union hm) = (∑i, m (f i) (hm i))) :
measure' (⋃i, f i) = (∑i, measure' (f i)) :=
(measure'_eq _).trans $ mU.trans $
by congr; funext i; rw measure'_eq
/-- outer measure of a measure -/
def outer_measure' : outer_measure α :=
outer_measure.of_function measure' measure'_empty
lemma measure'_Union_le_tsum_nat'
(mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)),
m (⋃i, f i) (is_measurable.Union hm) ≤ (∑i, m (f i) (hm i)))
(s : ℕ → set α) :
measure' (⋃i, s i) ≤ (∑i, measure' (s i)) :=
begin
by_cases h : ∀i, is_measurable (s i),
{ rw [measure'_eq _ _ (is_measurable.Union h),
congr_arg tsum _], {apply mU h},
funext i, apply measure'_eq _ _ (h i) },
{ cases not_forall.1 h with i hi,
exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) }
end
parameter (mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union hm) = (∑i, m (f i) (hm i)))
include mU
lemma measure'_Union
{β} [encodable β] {f : β → set α}
(hd : pairwise (disjoint on f)) (hm : ∀i, is_measurable (f i)) :
measure' (⋃i, f i) = (∑i, measure' (f i)) :=
begin
rw [encodable.Union_decode2, outer_measure.Union_aux],
{ exact measure'_Union_nat _ _
(λ n, encodable.Union_decode2_cases is_measurable.empty hm)
(mU _ (measurable_space.Union_decode2_disjoint_on hd)) },
{ apply measure'_empty },
end
lemma measure'_union {s₁ s₂ : set α}
(hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
measure' (s₁ ∪ s₂) = measure' s₁ + measure' s₂ :=
begin
rw [union_eq_Union, measure'_Union _ _ @mU
(pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩),
tsum_fintype],
change _+_ = _, simp
end
lemma measure'_mono {s₁ s₂ : set α} (h₁ : is_measurable s₁) (hs : s₁ ⊆ s₂) :
measure' s₁ ≤ measure' s₂ :=
le_infi $ λ h₂, begin
have := measure'_union _ _ @mU disjoint_diff h₁ (h₂.diff h₁),
rw union_diff_cancel hs at this,
rw ← measure'_eq m m0 _,
exact le_iff_exists_add.2 ⟨_, this⟩
end
lemma measure'_Union_le_tsum_nat : ∀ (s : ℕ → set α),
measure' (⋃i, s i) ≤ (∑i, measure' (s i)) :=
measure'_Union_le_tsum_nat' $ λ f h, begin
simp [Union_disjointed.symm] {single_pass := tt},
rw [mU (is_measurable.disjointed h) disjoint_disjointed],
refine ennreal.tsum_le_tsum (λ i, _),
rw [← measure'_eq m m0, ← measure'_eq m m0],
exact measure'_mono _ _ @mU (is_measurable.disjointed h _) (inter_subset_left _ _)
end
lemma outer_measure'_eq {s : set α} (hs : is_measurable s) :
outer_measure' s = m s hs :=
by rw ← measure'_eq m m0 hs; exact
(le_antisymm (outer_measure.of_function_le _ _ _) $
le_infi $ λ f, le_infi $ λ hf,
le_trans (measure'_mono _ _ @mU hs hf) $
measure'_Union_le_tsum_nat _ _ @mU _)
lemma outer_measure'_eq_measure' {s : set α} (hs : is_measurable s) :
outer_measure' s = measure' s :=
by rw [measure'_eq m m0 hs, outer_measure'_eq m m0 @mU hs]
end of_measurable
namespace outer_measure
variables {α : Type*} [measurable_space α] (m : outer_measure α)
def trim : outer_measure α :=
outer_measure' (λ s _, m s) m.empty
theorem trim_ge : m ≤ m.trim :=
λ s, le_infi $ λ f, le_infi $ λ hs,
le_trans (m.mono hs) $ le_trans (m.Union_nat f) $
ennreal.tsum_le_tsum $ λ i, le_infi $ λ hf, le_refl _
theorem trim_eq {s : set α} (hs : is_measurable s) : m.trim s = m s :=
le_antisymm (le_trans (of_function_le _ _ _) (infi_le _ hs)) (trim_ge _ _)
theorem trim_congr {m₁ m₂ : outer_measure α}
(H : ∀ {s : set α}, is_measurable s → m₁ s = m₂ s) :
m₁.trim = m₂.trim :=
by unfold trim; congr; funext s hs; exact H hs
theorem trim_le_trim {m₁ m₂ : outer_measure α} (H : m₁ ≤ m₂) : m₁.trim ≤ m₂.trim :=
λ s, infi_le_infi $ λ f, infi_le_infi $ λ hs,
ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _
theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔
∀ s, is_measurable s → m₁ s ≤ m₂ s :=
le_of_function.trans $ forall_congr $ λ s, le_infi_iff
theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), m t :=
begin
refine le_antisymm
(le_infi $ λ t, le_infi $ λ st, le_infi $ λ ht, _)
(le_infi $ λ f, le_infi $ λ hf, _),
{ rw ← trim_eq m ht, exact (trim m).mono st },
{ by_cases h : ∀i, is_measurable (f i),
{ refine infi_le_of_le _ (infi_le_of_le hf $
infi_le_of_le (is_measurable.Union h) _),
rw congr_arg tsum _, {exact m.Union_nat _},
funext i, exact measure'_eq _ _ (h i) },
{ cases not_forall.1 h with i hi,
exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } }
end
theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ is_measurable t}, m t.1 :=
by simp [infi_subtype, infi_and, trim_eq_infi]
theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim :=
le_antisymm (le_trim_iff.2 $ λ s hs, by simp [trim_eq _ hs, le_refl]) (trim_ge _)
theorem trim_zero : (0 : outer_measure α).trim = 0 :=
ext $ λ s, le_antisymm
(le_trans ((trim 0).mono (subset_univ s)) $
le_of_eq $ trim_eq _ is_measurable.univ)
(zero_le _)
theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim :=
ext $ λ s, begin
simp [trim_eq_infi'],
rw ennreal.infi_add_infi,
rintro ⟨t₁, st₁, ht₁⟩ ⟨t₂, st₂, ht₂⟩,
exact ⟨⟨_, subset_inter_iff.2 ⟨st₁, st₂⟩, ht₁.inter ht₂⟩,
add_le_add'
(m₁.mono' (inter_subset_left _ _))
(m₂.mono' (inter_subset_right _ _))⟩,
end
theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim :=
λ s, by simp [trim_eq_infi]; exact
λ t st ht, ennreal.tsum_le_tsum (λ i,
infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht)
end outer_measure
structure measure (α : Type*) [measurable_space α] extends outer_measure α :=
(m_Union {f : ℕ → set α} :
(∀i, is_measurable (f i)) → pairwise (disjoint on f) →
measure_of (⋃i, f i) = (∑i, measure_of (f i)))
(trimmed : to_outer_measure.trim = to_outer_measure)
/-- Measure projections for a measure space.
For measurable sets this returns the measure assigned by the `measure_of` field in `measure`.
But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and
subadditivity for all sets.
-/
instance measure.has_coe_to_fun {α} [measurable_space α] : has_coe_to_fun (measure α) :=
⟨λ _, set α → ennreal, λ m, m.to_outer_measure⟩
namespace measure
def of_measurable {α} [measurable_space α]
(m : Π (s : set α), is_measurable s → ennreal)
(m0 : m ∅ is_measurable.empty = 0)
(mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑i, m (f i) (h i))) :
measure α :=
{ m_Union := λ f hf hd,
show outer_measure' m m0 (Union f) =
∑ i, outer_measure' m m0 (f i), begin
rw [outer_measure'_eq m m0 @mU, mU hf hd],
congr, funext n, rw outer_measure'_eq m m0 @mU
end,
trimmed :=
show (outer_measure' m m0).trim = outer_measure' m m0, begin
unfold outer_measure.trim,
congr, funext s hs,
exact outer_measure'_eq m m0 @mU hs
end,
..outer_measure' m m0 }
lemma of_measurable_apply {α} [measurable_space α]
{m : Π (s : set α), is_measurable s → ennreal}
{m0 : m ∅ is_measurable.empty = 0}
{mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑i, m (f i) (h i))}
(s : set α) (hs : is_measurable s) :
of_measurable m m0 @mU s = m s hs :=
outer_measure'_eq m m0 @mU hs
@[extensionality] lemma ext {α} [measurable_space α] :
∀ {μ₁ μ₂ : measure α}, (∀s, is_measurable s → μ₁ s = μ₂ s) → μ₁ = μ₂
| ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h := by congr; rw [← h₁, ← h₂];
exact outer_measure.trim_congr h
end measure
section
variables {α : Type*} {β : Type*} [measurable_space α] {μ μ₁ μ₂ : measure α} {s s₁ s₂ : set α}
@[simp] lemma to_outer_measure_apply (s) : μ.to_outer_measure s = μ s := rfl
lemma measure_eq_trim (s) : μ s = μ.to_outer_measure.trim s :=
by rw μ.trimmed; refl
lemma measure_eq_infi (s) : μ s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), μ t :=
by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl
lemma measure_eq_outer_measure' :
μ s = outer_measure' (λ s _, μ s) μ.empty s :=
measure_eq_trim _
lemma to_outer_measure_eq_outer_measure' :
μ.to_outer_measure = outer_measure' (λ s _, μ s) μ.empty :=
μ.trimmed.symm
lemma measure_eq_measure' (hs : is_measurable s) :
μ s = measure' (λ s _, μ s) μ.empty s :=
by rw [measure_eq_outer_measure',
outer_measure'_eq_measure' (λ s _, μ s) _ μ.m_Union hs]
@[simp] lemma measure_empty : μ ∅ = 0 := μ.empty
lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h
lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 :=
by rw [← le_zero_iff_eq, ← h₂]; exact measure_mono h
lemma exists_is_measurable_superset_of_measure_eq_zero {s : set α} (h : μ s = 0) :
∃t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 :=
begin
rw [measure_eq_infi] at h,
have h := (infi_eq_bot _).1 h,
choose t ht using show ∀n:ℕ, ∃t, s ⊆ t ∧ is_measurable t ∧ μ t < n⁻¹,
{ assume n,
have : (0 : ennreal) < n⁻¹ :=
(zero_lt_iff_ne_zero.2 $ ennreal.inv_ne_zero.2 $ ennreal.nat_ne_top _),
rcases h _ this with ⟨t, ht⟩,
use [t],
simpa [(>), infi_lt_iff, -add_comm] using ht },
refine ⟨⋂n, t n, subset_Inter (λn, (ht n).1), is_measurable.Inter (λn, (ht n).2.1), _⟩,
refine eq_of_le_of_forall_le_of_dense bot_le (assume r hr, _),
rcases ennreal.exists_inv_nat_lt (ne_of_gt hr) with ⟨n, hn⟩,
calc μ (⋂n, t n) ≤ μ (t n) : measure_mono (Inter_subset _ _)
... ≤ n⁻¹ : le_of_lt (ht n).2.2
... ≤ r : le_of_lt hn
end
theorem measure_Union_le {β} [encodable β] (s : β → set α) : μ (⋃i, s i) ≤ (∑i, μ (s i)) :=
μ.to_outer_measure.Union _
lemma measure_Union_null {β} [encodable β] {s : β → set α} :
(∀ i, μ (s i) = 0) → μ (⋃i, s i) = 0 :=
μ.to_outer_measure.Union_null
theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ :=
μ.to_outer_measure.union _ _
lemma measure_union_null {s₁ s₂ : set α} : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 :=
μ.to_outer_measure.union_null
lemma measure_Union {β} [encodable β] {f : β → set α}
(hn : pairwise (disjoint on f)) (h : ∀i, is_measurable (f i)) :
μ (⋃i, f i) = (∑i, μ (f i)) :=
by rw [measure_eq_measure' (is_measurable.Union h),
measure'_Union (λ s _, μ s) _ μ.m_Union hn h];
simp [measure_eq_measure', h]
lemma measure_union (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
μ (s₁ ∪ s₂) = μ s₁ + μ s₂ :=
by rw [measure_eq_measure' (h₁.union h₂),
measure'_union (λ s _, μ s) _ μ.m_Union hd h₁ h₂];
simp [measure_eq_measure', h₁, h₂]
lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s)
(hd : pairwise_on s (disjoint on f)) (h : ∀b∈s, is_measurable (f b)) :
μ (⋃b∈s, f b) = ∑p:s, μ (f p.1) :=
begin
haveI := hs.to_encodable,
rw [← measure_Union, bUnion_eq_Union],
{ rintro ⟨i, hi⟩ ⟨j, hj⟩ ij x ⟨h₁, h₂⟩,
exact hd i hi j hj (mt subtype.eq' ij:_) ⟨h₁, h₂⟩ },
{ simpa }
end
lemma measure_sUnion {S : set (set α)} (hs : countable S)
(hd : pairwise_on S disjoint) (h : ∀s∈S, is_measurable s) :
μ (⋃₀ S) = ∑s:S, μ s.1 :=
by rw [sUnion_eq_bUnion, measure_bUnion hs hd h]
lemma measure_diff {s₁ s₂ : set α} (h : s₂ ⊆ s₁)
(h₁ : is_measurable s₁) (h₂ : is_measurable s₂)
(h_fin : μ s₂ < ⊤) : μ (s₁ \ s₂) = μ s₁ - μ s₂ :=
begin
refine (ennreal.add_sub_self' h_fin).symm.trans _,
rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h]
end
lemma measure_Union_eq_supr_nat {s : ℕ → set α} (h : ∀i, is_measurable (s i)) (hs : monotone s) :
μ (⋃i, s i) = (⨆i, μ (s i)) :=
begin
refine le_antisymm _ (supr_le $ λ i, measure_mono $ subset_Union _ _),
rw [← Union_disjointed,
measure_Union disjoint_disjointed (is_measurable.disjointed h),
ennreal.tsum_eq_supr_nat],
refine supr_le (λ n, _),
cases n, {apply zero_le _},
suffices : sum (finset.range n.succ) (λ i, μ (disjointed s i)) = μ (s n),
{ rw this, exact le_supr _ n },
rw [← Union_disjointed_of_mono hs, measure_Union, tsum_eq_sum],
{ apply sum_congr rfl, intros i hi,
simp [finset.mem_range.1 hi] },
{ intros i hi, simp [mt finset.mem_range.2 hi] },
{ rintro i j ij x ⟨⟨_, ⟨_, rfl⟩, h₁⟩, ⟨_, ⟨_, rfl⟩, h₂⟩⟩,
exact disjoint_disjointed i j ij ⟨h₁, h₂⟩ },
{ intro i,
by_cases h' : i < n.succ; simp [h', is_measurable.empty],
apply is_measurable.disjointed h }
end
lemma measure_Inter_eq_infi_nat {s : ℕ → set α}
(h : ∀i, is_measurable (s i)) (hs : ∀i j, i ≤ j → s j ⊆ s i)
(hfin : ∃i, μ (s i) < ⊤) :
μ (⋂i, s i) = (⨅i, μ (s i)) :=
begin
rcases hfin with ⟨k, hk⟩,
rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k),
ennreal.sub_infi,
← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)),
← measure_diff (Inter_subset _ k) (h k) (is_measurable.Inter h)
(lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk),
diff_Inter, measure_Union_eq_supr_nat],
{ congr, funext i,
cases le_total k i with ik ik,
{ exact measure_diff (hs _ _ ik) (h k) (h i)
(lt_of_le_of_lt (measure_mono (hs _ _ ik)) hk) },
{ rw [diff_eq_empty.2 (hs _ _ ik), measure_empty,
ennreal.sub_eq_zero_of_le (measure_mono (hs _ _ ik))] } },
{ exact λ i, (h k).diff (h i) },
{ exact λ i j ij, diff_subset_diff_right (hs _ _ ij) }
end
lemma measure_eq_inter_diff {μ : measure α} {s t : set α}
(hs : is_measurable s) (ht : is_measurable t) :
μ s = μ (s ∩ t) + μ (s \ t) :=
have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs ,
by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t]
lemma tendsto_measure_Union {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : monotone s) :
tendsto (μ ∘ s) at_top (nhds (μ (⋃n, s n))) :=
begin
rw measure_Union_eq_supr_nat hs hm,
exact tendsto_at_top_supr_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm $ hnm)
end
lemma tendsto_measure_Inter {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : ∀n m, n ≤ m → s m ⊆ s n) (hf : ∃i, μ (s i) < ⊤) :
tendsto (μ ∘ s) at_top (nhds (μ (⋂n, s n))) :=
begin
rw measure_Inter_eq_infi_nat hs hm hf,
exact tendsto_at_top_infi_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm _ _ $ hnm),
end
end
def outer_measure.to_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
measure α :=
measure.of_measurable (λ s _, m s) m.empty
(λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd)
lemma le_to_outer_measure_caratheodory {α} [ms : measurable_space α]
(μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory :=
begin
assume s hs,
rw to_outer_measure_eq_outer_measure',
refine outer_measure.caratheodory_is_measurable (λ t, le_infi $ λ ht, _),
rw [← measure_eq_measure' (ht.inter hs),
← measure_eq_measure' (ht.diff hs),
← measure_union _ (ht.inter hs) (ht.diff hs),
inter_union_diff],
exact le_refl _,
exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁
end
lemma to_measure_to_outer_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
(m.to_measure h).to_outer_measure = m.trim := rfl
@[simp] lemma to_measure_apply {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory)
{s : set α} (hs : is_measurable s) :
m.to_measure h s = m s := m.trim_eq hs
lemma to_outer_measure_to_measure {α : Type*} [ms : measurable_space α] {μ : measure α} :
μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ :=
measure.ext $ λ s, μ.to_outer_measure.trim_eq
namespace measure
variables {α : Type*} {β : Type*} {γ : Type*}
[measurable_space α] [measurable_space β] [measurable_space γ]
instance : has_zero (measure α) :=
⟨{ to_outer_measure := 0,
m_Union := λ f hf hd, tsum_zero.symm,
trimmed := outer_measure.trim_zero }⟩
@[simp] theorem zero_to_outer_measure :
(0 : measure α).to_outer_measure = 0 := rfl
@[simp] theorem zero_apply (s : set α) : (0 : measure α) s = 0 := rfl
instance : inhabited (measure α) := ⟨0⟩
instance : has_add (measure α) :=
⟨λμ₁ μ₂, {
to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure,
m_Union := λs hs hd,
show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑ i, μ₁ (s i) + μ₂ (s i),
by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs],
trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩
@[simp] theorem add_to_outer_measure (μ₁ μ₂ : measure α) :
(μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl
@[simp] theorem add_apply (μ₁ μ₂ : measure α) (s : set α) :
(μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl
instance : add_comm_monoid (measure α) :=
{ zero := 0,
add := (+),
add_assoc := assume a b c, ext $ assume s hs, add_assoc _ _ _,
add_comm := assume a b, ext $ assume s hs, add_comm _ _,
zero_add := assume a, ext $ assume s hs, zero_add _,
add_zero := assume a, ext $ assume s hs, add_zero _ }
instance : partial_order (measure α) :=
{ le := λm₁ m₂, ∀ s, is_measurable s → m₁ s ≤ m₂ s,
le_refl := assume m s hs, le_refl _,
le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs),
le_antisymm := assume m₁ m₂ h₁ h₂, ext $
assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) }
theorem le_iff {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, is_measurable s → μ₁ s ≤ μ₂ s := iff.rfl
theorem to_outer_measure_le {μ₁ μ₂ : measure α} :
μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ :=
by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl
theorem le_iff' {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s :=
to_outer_measure_le.symm
section
variables {m : set (measure α)} {μ : measure α}
lemma Inf_caratheodory (s : set α) (hs : is_measurable s) :
(Inf (measure.to_outer_measure '' m)).caratheodory.is_measurable s :=
begin
rw [outer_measure.Inf_eq_of_function_Inf_gen],
refine outer_measure.caratheodory_is_measurable (assume t, _),
by_cases ht : t = ∅, { simp [ht] },
simp only [outer_measure.Inf_gen_nonempty1 _ _ ht, le_infi_iff, ball_image_iff,
to_outer_measure_apply, measure_eq_infi t],
assume μ hμ u htu hu,
have hm : ∀{s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t,
{ assume s t hst,
rw [outer_measure.Inf_gen_nonempty2 _ _ (mem_image_of_mem _ hμ)],
refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _),
rw [to_outer_measure_apply],
refine measure_mono hst },
rw [measure_eq_inter_diff hu hs],
refine add_le_add' (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu)
end
instance : has_Inf (measure α) :=
⟨λm, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩
lemma Inf_apply {m : set (measure α)} {s : set α} (hs : is_measurable s) :
Inf m s = Inf (to_outer_measure '' m) s :=
to_measure_apply _ _ hs
private lemma Inf_le (h : μ ∈ m) : Inf m ≤ μ :=
have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h),
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
private lemma le_Inf (h : ∀μ' ∈ m, μ ≤ μ') : μ ≤ Inf m :=
have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) :=
le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ,
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
instance : has_Sup (measure α) := ⟨λs, Inf {μ' | ∀μ∈s, μ ≤ μ' }⟩
private lemma le_Sup (h : μ ∈ m) : μ ≤ Sup m := le_Inf $ assume μ' h', h' _ h
private lemma Sup_le (h : ∀μ' ∈ m, μ' ≤ μ) : Sup m ≤ μ := Inf_le h
instance : order_bot (measure α) :=
{ bot := 0, bot_le := assume a s hs, bot_le, .. measure.partial_order }
instance : order_top (measure α) :=
{ top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top),
le_top := assume a s hs,
by by_cases s = ∅; simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply],
.. measure.partial_order }
instance : complete_lattice (measure α) :=
{ Inf := Inf,
Sup := Sup,
inf := λa b, Inf {a, b},
sup := λa b, Sup {a, b},
le_Sup := assume s μ h, le_Sup h,
Sup_le := assume s μ h, Sup_le h,
Inf_le := assume s μ h, Inf_le h,
le_Inf := assume s μ h, le_Inf h,
le_sup_left := assume a b, le_Sup $ by simp,
le_sup_right := assume a b, le_Sup $ by simp,
sup_le := assume a b c hac hbc, Sup_le $ by simp [*, or_imp_distrib] {contextual := tt},
inf_le_left := assume a b, Inf_le $ by simp,
inf_le_right := assume a b, Inf_le $ by simp,
le_inf := assume a b c hac hbc, le_Inf $ by simp [*, or_imp_distrib] {contextual := tt},
.. measure.partial_order, .. measure.lattice.order_top, .. measure.lattice.order_bot }
end
def map (f : α → β) (μ : measure α) : measure β :=
if hf : measurable f then
(μ.to_outer_measure.map f).to_measure $ λ s hs t,
le_to_outer_measure_caratheodory μ _ (hf _ hs) (f ⁻¹' t)
else 0
variables {μ ν : measure α}
@[simp] theorem map_apply {f : α → β} (hf : measurable f)
{s : set β} (hs : is_measurable s) :
(map f μ : measure β) s = μ (f ⁻¹' s) :=
by rw [map, dif_pos hf, to_measure_apply _ _ hs]; refl
@[simp] lemma map_id : map id μ = μ :=
ext $ λ s, map_apply measurable_id
lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) :
map g (map f μ) = map (g ∘ f) μ :=
ext $ λ s hs,
by simp [hf, hg, hs, hg.preimage hs, hg.comp hf];
rw ← preimage_comp
/-- The dirac measure. -/
def dirac (a : α) : measure α :=
(outer_measure.dirac a).to_measure (by simp)
@[simp] lemma dirac_apply (a : α) {s : set α} (hs : is_measurable s) :
(dirac a : measure α) s = ⨆ h : a ∈ s, 1 :=
to_measure_apply _ _ hs
/-- Sum of an indexed family of measures. -/
def sum {ι : Type*} (f : ι → measure α) : measure α :=
(outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $
le_trans
(by exact le_infi (λ i, le_to_outer_measure_caratheodory _))
(outer_measure.le_sum_caratheodory _)
/-- Counting measure on any measurable space. -/
def count : measure α := sum dirac
@[class] def is_complete {α} {_:measurable_space α} (μ : measure α) : Prop :=
∀ s, μ s = 0 → is_measurable s
/-- The "almost everywhere" filter of co-null sets. -/
def a_e (μ : measure α) : filter α :=
{ sets := {s | μ (-s) = 0},
univ_sets := by simp [measure_empty],
inter_sets := λ s t hs ht, by simp [compl_inter]; exact measure_union_null hs ht,
sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs }
lemma mem_a_e_iff (s : set α) : s ∈ μ.a_e.sets ↔ μ (- s) = 0 := iff.refl _
end measure
end measure_theory
section is_complete
open measure_theory
variables {α : Type*} [measurable_space α] (μ : measure α)
def is_null_measurable (s : set α) : Prop :=
∃ t z, s = t ∪ z ∧ is_measurable t ∧ μ z = 0
theorem is_null_measurable_iff {μ : measure α} {s : set α} :
is_null_measurable μ s ↔
∃ t, t ⊆ s ∧ is_measurable t ∧ μ (s \ t) = 0 :=
begin
split,
{ rintro ⟨t, z, rfl, ht, hz⟩,
refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩,
simp [union_diff_left, diff_subset] },
{ rintro ⟨t, st, ht, hz⟩,
exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ }
end
theorem is_null_measurable_measure_eq {μ : measure α} {s t : set α}
(st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t :=
begin
refine le_antisymm _ (measure_mono st),
have := measure_union_le t (s \ t),
rw [union_diff_cancel st, hz] at this, simpa
end
theorem is_measurable.is_null_measurable
{s : set α} (hs : is_measurable s) : is_null_measurable μ s :=
⟨s, ∅, by simp, hs, μ.empty⟩
theorem is_null_measurable_of_complete [c : μ.is_complete]
{s : set α} : is_null_measurable μ s ↔ is_measurable s :=
⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact
is_measurable.union ht (c _ hz),
λ h, h.is_null_measurable _⟩
variables {μ}
theorem is_null_measurable.union_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s ∪ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, le_zero_iff_eq.1
(le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩
end
theorem null_is_null_measurable {z : set α}
(hz : μ z = 0) : is_null_measurable μ z :=
by simpa using (is_measurable.empty.is_null_measurable _).union_null hz
theorem is_null_measurable.Union_nat {s : ℕ → set α}
(hs : ∀ i, is_null_measurable μ (s i)) :
is_null_measurable μ (Union s) :=
begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht,
rcases ht with ⟨st, ht, hz⟩,
refine is_null_measurable_iff.2
⟨Union t, Union_subset_Union st, is_measurable.Union ht,
measure_mono_null _ (measure_Union_null hz)⟩,
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff)
end
theorem is_measurable.diff_null {s z : set α}
(hs : is_measurable s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rw measure_eq_infi at hz,
choose f hf using show ∀ q : {q:ℚ//q>0}, ∃ t:set α,
z ⊆ t ∧ is_measurable t ∧ μ t < (nnreal.of_real q.1 : ennreal),
{ rintro ⟨ε, ε0⟩,
have : 0 < (nnreal.of_real ε : ennreal), { simpa using ε0 },
rw ← hz at this, simpa [infi_lt_iff] },
refine is_null_measurable_iff.2 ⟨s \ Inter f,
diff_subset_diff_right (subset_Inter (λ i, (hf i).1)),
hs.diff (is_measurable.Inter (λ i, (hf i).2.1)),
measure_mono_null _ (le_zero_iff_eq.1 $ le_of_not_lt $ λ h, _)⟩,
{ exact Inter f },
{ rw [diff_subset_iff, diff_union_self],
exact subset.trans (diff_subset _ _) (subset_union_left _ _) },
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩,
simp at ε0,
apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h),
exact measure_mono (Inter_subset _ _)
end
theorem is_null_measurable.diff_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
rw [set.union_diff_distrib],
exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz')
end
theorem is_null_measurable.compl {s : set α}
(hs : is_null_measurable μ s) :
is_null_measurable μ (-s) :=
begin
rcases hs with ⟨t, z, rfl, ht, hz⟩,
rw compl_union,
exact ht.compl.diff_null hz
end
def null_measurable {α : Type u} [measurable_space α]
(μ : measure α) : measurable_space α :=
{ is_measurable := is_null_measurable μ,
is_measurable_empty := is_measurable.empty.is_null_measurable _,
is_measurable_compl := λ s hs, hs.compl,
is_measurable_Union := λ f, is_null_measurable.Union_nat }
def completion {α : Type u} [measurable_space α] (μ : measure α) :
@measure_theory.measure α (null_measurable μ) :=
{ to_outer_measure := μ.to_outer_measure,
m_Union := λ s hs hd, show μ (Union s) = ∑ i, μ (s i), begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩,
rw is_null_measurable_measure_eq (Union_subset_Union st),
{ rw measure_Union _ ht,
{ congr, funext i,
exact (is_null_measurable_measure_eq (st i) (hz i)).symm },
{ rintro i j ij x ⟨h₁, h₂⟩,
exact hd i j ij ⟨st i h₁, st j h₂⟩ } },
{ refine measure_mono_null _ (measure_Union_null hz),
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff) }
end,
trimmed := begin
letI := null_measurable μ,
refine le_antisymm (λ s, _) (outer_measure.trim_ge _),
rw outer_measure.trim_eq_infi,
dsimp, clear _inst,
rw measure_eq_infi s,
exact infi_le_infi (λ t, infi_le_infi $ λ st,
infi_le_infi2 $ λ ht, ⟨ht.is_null_measurable _, le_refl _⟩)
end }
instance completion.is_complete {α : Type u} [measurable_space α] (μ : measure α) :
(completion μ).is_complete :=
λ z hz, null_is_null_measurable hz
end is_complete
namespace measure_theory
/-- A measure space is a measurable space equipped with a
measure, referred to as `volume`. -/
class measure_space (α : Type*) extends measurable_space α :=
(μ {} : measure α)
section measure_space
variables {α : Type*} [measure_space α] {s₁ s₂ : set α}
open measure_space
def volume : set α → ennreal := @μ α _
@[simp] lemma volume_empty : volume (∅ : set α) = 0 := μ.empty
lemma volume_mono : s₁ ⊆ s₂ → volume s₁ ≤ volume s₂ := measure_mono
lemma volume_mono_null : s₁ ⊆ s₂ → volume s₂ = 0 → volume s₁ = 0 :=
measure_mono_null
theorem volume_Union_le {β} [encodable β] :
∀ (s : β → set α), volume (⋃i, s i) ≤ (∑i, volume (s i)) :=
measure_Union_le
lemma volume_Union_null {β} [encodable β] {s : β → set α} :
(∀ i, volume (s i) = 0) → volume (⋃i, s i) = 0 :=
measure_Union_null
theorem volume_union_le : ∀ (s₁ s₂ : set α), volume (s₁ ∪ s₂) ≤ volume s₁ + volume s₂ :=
measure_union_le
lemma volume_union_null : volume s₁ = 0 → volume s₂ = 0 → volume (s₁ ∪ s₂) = 0 :=
measure_union_null
lemma volume_Union {β} [encodable β] {f : β → set α} :
pairwise (disjoint on f) → (∀i, is_measurable (f i)) →
volume (⋃i, f i) = (∑i, volume (f i)) :=
measure_Union
lemma volume_union : disjoint s₁ s₂ → is_measurable s₁ → is_measurable s₂ →
volume (s₁ ∪ s₂) = volume s₁ + volume s₂ :=
measure_union
lemma volume_bUnion {β} {s : set β} {f : β → set α} : countable s →
pairwise_on s (disjoint on f) → (∀b∈s, is_measurable (f b)) →
volume (⋃b∈s, f b) = ∑p:s, volume (f p.1) :=
measure_bUnion
lemma volume_sUnion {S : set (set α)} : countable S →
pairwise_on S disjoint → (∀s∈S, is_measurable s) →
volume (⋃₀ S) = ∑s:S, volume s.1 :=
measure_sUnion
lemma volume_bUnion_finset {β} {s : finset β} {f : β → set α}
(hd : pairwise_on ↑s (disjoint on f)) (hm : ∀b∈s, is_measurable (f b)) :
volume (⋃b∈s, f b) = s.sum (λp, volume (f p)) :=
show volume (⋃b∈(↑s : set β), f b) = s.sum (λp, volume (f p)),
begin
rw [volume_bUnion (countable_finite (finset.finite_to_set s)) hd hm, tsum_eq_sum],
{ show s.attach.sum (λb:(↑s : set β), volume (f b)) = s.sum (λb, volume (f b)),
exact @finset.sum_attach _ _ s _ (λb, volume (f b)) },
simp
end
lemma volume_diff : s₂ ⊆ s₁ → is_measurable s₁ → is_measurable s₂ →
volume s₂ < ⊤ → volume (s₁ \ s₂) = volume s₁ - volume s₂ :=
measure_diff
/-- `∀ₘ a:α, p a` states that the property `p` is almost everywhere true in the measure space
associated with `α`. This means that the measure of the complementary of `p` is `0`.
In a probability measure, the measure of `p` is `1`, when `p` is measurable.
-/
def all_ae (p : α → Prop) : Prop := { a | p a } ∈ (@measure_space.μ α _).a_e
notation `∀ₘ` binders `, ` r:(scoped P, all_ae P) := r
lemma all_ae_congr {p q : α → Prop} (h : ∀ₘ a, p a ↔ q a) : (∀ₘ a, p a) ↔ (∀ₘ a, q a) :=
iff.intro
(assume h', by filter_upwards [h, h'] assume a hpq hp, hpq.1 hp)
(assume h', by filter_upwards [h, h'] assume a hpq hq, hpq.2 hq)
lemma all_ae_iff {p : α → Prop} : (∀ₘ a, p a) ↔ volume { a | ¬ p a } = 0 := iff.refl _
lemma all_ae_of_all {p : α → Prop} : (∀a, p a) → ∀ₘ a, p a := assume h,
by {rw all_ae_iff, convert volume_empty, simp only [h, not_true], reflexivity}
lemma all_ae_all_iff {ι : Type*} [encodable ι] {p : α → ι → Prop} :
(∀ₘ a, ∀i, p a i) ↔ (∀i, ∀ₘ a, p a i) :=
begin
refine iff.intro (assume h i, _) (assume h, _),
{ filter_upwards [h] assume a ha, ha i },
{ have h := measure_Union_null h,
rw [← compl_Inter] at h,
filter_upwards [h] assume a, mem_Inter.1 }
end
end measure_space
end measure_theory
|
cbff6294c706baffbd1e6854b454e8763f71d183
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/data/sym/card.lean
|
f45e2c505f828ef8907e3cfd98e9823c8bb1d99b
|
[
"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
| 8,914
|
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, Huỳnh Trần Khanh, Stuart Presnell
-/
import algebra.big_operators.basic
import data.finset.sym
import data.fintype.sum
/-!
# Stars and bars
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file, we prove (in `sym.card_sym_eq_multichoose`) that the function `multichoose n k`
defined in `data/nat/choose/basic` counts the number of multisets of cardinality `k` over an
alphabet of cardinality `n`. In conjunction with `nat.multichoose_eq` proved in
`data/nat/choose/basic`, which shows that `multichoose n k = choose (n + k - 1) k`,
this is central to the "stars and bars" technique in combinatorics, where we switch between
counting multisets of size `k` over an alphabet of size `n` to counting strings of `k` elements
("stars") separated by `n-1` dividers ("bars").
## Informal statement
Many problems in mathematics are of the form of (or can be reduced to) putting `k` indistinguishable
objects into `n` distinguishable boxes; for example, the problem of finding natural numbers
`x1, ..., xn` whose sum is `k`. This is equivalent to forming a multiset of cardinality `k` from
an alphabet of cardinality `n` -- for each box `i ∈ [1, n]` the multiset contains as many copies
of `i` as there are items in the `i`th box.
The "stars and bars" technique arises from another way of presenting the same problem. Instead of
putting `k` items into `n` boxes, we take a row of `k` items (the "stars") and separate them by
inserting `n-1` dividers (the "bars"). For example, the pattern `*|||**|*|` exhibits 4 items
distributed into 6 boxes -- note that any box, including the first and last, may be empty.
Such arrangements of `k` stars and `n-1` bars are in 1-1 correspondence with multisets of size `k`
over an alphabet of size `n`, and are counted by `choose (n + k - 1) k`.
Note that this problem is one component of Gian-Carlo Rota's "Twelvefold Way"
https://en.wikipedia.org/wiki/Twelvefold_way
## Formal statement
Here we generalise the alphabet to an arbitrary fintype `α`, and we use `sym α k` as the type of
multisets of size `k` over `α`. Thus the statement that these are counted by `multichoose` is:
`sym.card_sym_eq_multichoose : card (sym α k) = multichoose (card α) k`
while the "stars and bars" technique gives
`sym.card_sym_eq_choose : card (sym α k) = choose (card α + k - 1) k`
## Tags
stars and bars, multichoose
-/
open finset fintype function sum nat
variables {α β : Type*}
namespace sym
section sym
variables (α) (n : ℕ)
/--
Over `fin n+1`, the multisets of size `k+1` containing `0` are equivalent to those of size `k`,
as demonstrated by respectively erasing or appending `0`.
-/
protected def E1 {n k : ℕ} :
{s : sym (fin n.succ) k.succ // ↑0 ∈ s} ≃ sym (fin n.succ) k :=
{ to_fun := λ s, s.1.erase 0 s.2,
inv_fun := λ s, ⟨cons 0 s, mem_cons_self 0 s⟩,
left_inv := λ s, by simp,
right_inv := λ s, by simp }
/--
The multisets of size `k` over `fin n+2` not containing `0`
are equivalent to those of size `k` over `fin n+1`,
as demonstrated by respectively decrementing or incrementing every element of the multiset.
-/
protected def E2 {n k : ℕ} :
{s : sym (fin n.succ.succ) k // ↑0 ∉ s} ≃ sym (fin n.succ) k :=
{ to_fun := λ s, map (fin.pred_above 0) s.1,
inv_fun := λ s, ⟨map (fin.succ_above 0) s,
(mt mem_map.1) (not_exists.2 (λ t, (not_and.2 (λ _, (fin.succ_above_ne _ t)))))⟩,
left_inv := λ s, by
{ obtain ⟨s, hs⟩ := s,
simp only [map_map, comp_app],
nth_rewrite_rhs 0 ←(map_id' s),
refine sym.map_congr (λ v hv, _),
simp [fin.pred_above_zero (ne_of_mem_of_not_mem hv hs)] },
right_inv := λ s, by
{ simp only [fin.zero_succ_above, map_map, comp_app],
nth_rewrite_rhs 0 ←(map_id' s),
refine sym.map_congr (λ v hv, _),
rw [←fin.zero_succ_above v, ←@fin.cast_succ_zero n.succ, fin.pred_above_succ_above 0 v] } }
lemma card_sym_fin_eq_multichoose (n k : ℕ) : card (sym (fin n) k) = multichoose n k :=
begin
apply @pincer_recursion (λ n k, card (sym (fin n) k) = multichoose n k),
{ simp },
{ intros b,
induction b with b IHb, { simp },
rw [multichoose_zero_succ, card_eq_zero_iff],
apply_instance },
{ intros x y h1 h2,
rw [multichoose_succ_succ, ←h1, ←h2, add_comm],
cases x,
{ simp only [card_eq_zero_iff, card_unique, self_eq_add_right],
apply_instance },
rw ←card_sum,
refine fintype.card_congr (equiv.symm _),
apply (equiv.sum_congr sym.E1.symm sym.E2.symm).trans,
apply equiv.sum_compl },
end
/-- For any fintype `α` of cardinality `n`, `card (sym α k) = multichoose (card α) k` -/
lemma card_sym_eq_multichoose (α : Type*) (k : ℕ) [fintype α] [fintype (sym α k)] :
card (sym α k) = multichoose (card α) k :=
by { rw ←card_sym_fin_eq_multichoose, exact card_congr (equiv_congr (equiv_fin α)) }
/-- The *stars and bars* lemma: the cardinality of `sym α k` is equal to
`nat.choose (card α + k - 1) k`. -/
lemma card_sym_eq_choose {α : Type*} [fintype α] (k : ℕ) [fintype (sym α k)] :
card (sym α k) = (card α + k - 1).choose k :=
by rw [card_sym_eq_multichoose, nat.multichoose_eq]
end sym
end sym
namespace sym2
variables [decidable_eq α]
/-- The `diag` of `s : finset α` is sent on a finset of `sym2 α` of card `s.card`. -/
lemma card_image_diag (s : finset α) : (s.diag.image quotient.mk).card = s.card :=
begin
rw [card_image_of_inj_on, diag_card],
rintro ⟨x₀, x₁⟩ hx _ _ h,
cases quotient.eq.1 h,
{ refl },
{ simp only [mem_coe, mem_diag] at hx,
rw hx.2 }
end
lemma two_mul_card_image_off_diag (s : finset α) :
2 * (s.off_diag.image quotient.mk).card = s.off_diag.card :=
begin
rw [card_eq_sum_card_fiberwise
(λ x, mem_image_of_mem _ : ∀ x ∈ s.off_diag, quotient.mk x ∈ s.off_diag.image quotient.mk),
sum_const_nat (quotient.ind _), mul_comm],
rintro ⟨x, y⟩ hxy,
simp_rw [mem_image, exists_prop, mem_off_diag, quotient.eq] at hxy,
obtain ⟨a, ⟨ha₁, ha₂, ha⟩, h⟩ := hxy,
obtain ⟨hx, hy, hxy⟩ : x ∈ s ∧ y ∈ s ∧ x ≠ y,
{ cases h; have := ha.symm; exact ⟨‹_›, ‹_›, ‹_›⟩ },
have hxy' : y ≠ x := hxy.symm,
have : s.off_diag.filter (λ z, ⟦z⟧ = ⟦(x, y)⟧) = ({(x, y), (y, x)} : finset _),
{ ext ⟨x₁, y₁⟩,
rw [mem_filter, mem_insert, mem_singleton, sym2.eq_iff, prod.mk.inj_iff, prod.mk.inj_iff,
and_iff_right_iff_imp],
rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩); rw mem_off_diag; exact ⟨‹_›, ‹_›, ‹_›⟩ }, -- hxy' is used here
rw [this, card_insert_of_not_mem, card_singleton],
simp only [not_and, prod.mk.inj_iff, mem_singleton],
exact λ _, hxy',
end
/-- The `off_diag` of `s : finset α` is sent on a finset of `sym2 α` of card `s.off_diag.card / 2`.
This is because every element `⟦(x, y)⟧` of `sym2 α` not on the diagonal comes from exactly two
pairs: `(x, y)` and `(y, x)`. -/
lemma card_image_off_diag (s : finset α) :
(s.off_diag.image quotient.mk).card = s.card.choose 2 :=
by rw [nat.choose_two_right, mul_tsub, mul_one, ←off_diag_card,
nat.div_eq_of_eq_mul_right zero_lt_two (two_mul_card_image_off_diag s).symm]
lemma card_subtype_diag [fintype α] :
card {a : sym2 α // a.is_diag} = card α :=
begin
convert card_image_diag (univ : finset α),
rw [fintype.card_of_subtype, ←filter_image_quotient_mk_is_diag],
rintro x,
rw [mem_filter, univ_product_univ, mem_image],
obtain ⟨a, ha⟩ := quotient.exists_rep x,
exact and_iff_right ⟨a, mem_univ _, ha⟩,
end
lemma card_subtype_not_diag [fintype α] :
card {a : sym2 α // ¬a.is_diag} = (card α).choose 2 :=
begin
convert card_image_off_diag (univ : finset α),
rw [fintype.card_of_subtype, ←filter_image_quotient_mk_not_is_diag],
rintro x,
rw [mem_filter, univ_product_univ, mem_image],
obtain ⟨a, ha⟩ := quotient.exists_rep x,
exact and_iff_right ⟨a, mem_univ _, ha⟩,
end
/-- Finset **stars and bars** for the case `n = 2`. -/
lemma _root_.finset.card_sym2 (s : finset α) : s.sym2.card = s.card * (s.card + 1) / 2 :=
begin
rw [←image_diag_union_image_off_diag, card_union_eq, sym2.card_image_diag,
sym2.card_image_off_diag, nat.choose_two_right, add_comm, ←nat.triangle_succ, nat.succ_sub_one,
mul_comm],
rw disjoint_left,
rintro m ha hb,
rw [mem_image] at ha hb,
obtain ⟨⟨a, ha, rfl⟩, ⟨b, hb, hab⟩⟩ := ⟨ha, hb⟩,
refine not_is_diag_mk_of_mem_off_diag hb _,
rw hab,
exact is_diag_mk_of_mem_diag ha,
end
/-- Type **stars and bars** for the case `n = 2`. -/
protected lemma card [fintype α] : card (sym2 α) = card α * (card α + 1) / 2 := finset.card_sym2 _
end sym2
|
4228a9f12de7b1b81e1fecbd1f9f51c307ce5766
|
957a80ea22c5abb4f4670b250d55534d9db99108
|
/tests/lean/run/unification_hints.lean
|
43e596e3b20a8794476a05b2fb725278a59e7a1b
|
[
"Apache-2.0"
] |
permissive
|
GaloisInc/lean
|
aa1e64d604051e602fcf4610061314b9a37ab8cd
|
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
|
refs/heads/master
| 1,592,202,909,807
| 1,504,624,387,000
| 1,504,624,387,000
| 75,319,626
| 2
| 1
|
Apache-2.0
| 1,539,290,164,000
| 1,480,616,104,000
|
C++
|
UTF-8
|
Lean
| false
| false
| 800
|
lean
|
open list nat
namespace toy
constants (A : Type.{1}) (f h : A → A) (x y z : A)
attribute [irreducible]
noncomputable definition g (x y : A) : A := f z
@[unify]
noncomputable definition toy_hint (x y : A) : unification_hint :=
{ pattern := g x y ≟ f z,
constraints := [] }
open tactic
set_option trace.type_context.unification_hint true
definition ex1 (a : A) (H : g x y = a) : f z = a :=
by do {trace_state, assumption}
#print ex1
end toy
namespace add
constants (n : ℕ)
@[unify] definition add_zero_hint (m n : ℕ) [has_add ℕ] [has_one ℕ] [has_zero ℕ] : unification_hint :=
{ pattern := m + 1 ≟ succ n,
constraints := [m ≟ n] }
attribute [irreducible] has_add.add
open tactic
definition ex2 (H : n + 1 = 0) : succ n = 0 :=
by assumption
#print ex2
end add
|
170f78b97f82c8515a0a27293d1474be0ec00864
|
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
|
/11_Tactic-Style_Proofs.org.39.lean
|
75961cda53ad6e744550c5c78bb0fcf4b9b71c70
|
[] |
no_license
|
cjmazey/lean-tutorial
|
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
|
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
|
refs/heads/master
| 1,610,286,098,832
| 1,447,124,923,000
| 1,447,124,923,000
| 43,082,433
| 0
| 0
| null | null | null | null |
UTF-8
|
Lean
| false
| false
| 165
|
lean
|
import standard
import data.nat
open nat
-- BEGIN
example (a b c : nat) : a + b + c = a + c + b :=
begin
rewrite [add.assoc, {b + _}add.comm, -add.assoc]
end
-- END
|
6bc63951f3651df7d9dcd47b81c3afb522acc7d9
|
9dc8cecdf3c4634764a18254e94d43da07142918
|
/src/algebra/big_operators/ring.lean
|
312adc17b6e5f3342c88cf77daabb57dceded4c5
|
[
"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
| 11,181
|
lean
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import algebra.big_operators.basic
import algebra.field.basic
import data.finset.pi
import data.finset.powerset
/-!
# Results about big operators with values in a (semi)ring
We prove results about big operators that involve some interaction between
multiplicative and additive structures on the values being combined.
-/
universes u v w
open_locale big_operators
variables {α : Type u} {β : Type v} {γ : Type w}
namespace finset
variables {s s₁ s₂ : finset α} {a : α} {b : β} {f g : α → β}
section comm_monoid
variables [comm_monoid β]
open_locale classical
lemma prod_pow_eq_pow_sum {x : β} {f : α → ℕ} :
∀ {s : finset α}, (∏ i in s, x ^ (f i)) = x ^ (∑ x in s, f x) :=
begin
apply finset.induction,
{ simp },
{ assume a s has H,
rw [finset.prod_insert has, finset.sum_insert has, pow_add, H] }
end
end comm_monoid
section semiring
variables [non_unital_non_assoc_semiring β]
lemma sum_mul : (∑ x in s, f x) * b = ∑ x in s, f x * b :=
add_monoid_hom.map_sum (add_monoid_hom.mul_right b) _ s
lemma mul_sum : b * (∑ x in s, f x) = ∑ x in s, b * f x :=
add_monoid_hom.map_sum (add_monoid_hom.mul_left b) _ s
lemma sum_mul_sum {ι₁ : Type*} {ι₂ : Type*} (s₁ : finset ι₁) (s₂ : finset ι₂)
(f₁ : ι₁ → β) (f₂ : ι₂ → β) :
(∑ x₁ in s₁, f₁ x₁) * (∑ x₂ in s₂, f₂ x₂) = ∑ p in s₁ ×ˢ s₂, f₁ p.1 * f₂ p.2 :=
by { rw [sum_product, sum_mul, sum_congr rfl], intros, rw mul_sum }
end semiring
section semiring
variables [non_assoc_semiring β]
lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) :
(∑ x in s, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 :=
by simp
lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) :
(∑ x in s, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 :=
by simp
end semiring
lemma sum_div [division_semiring β] {s : finset α} {f : α → β} {b : β} :
(∑ x in s, f x) / b = ∑ x in s, f x / b :=
by simp only [div_eq_mul_inv, sum_mul]
section comm_semiring
variables [comm_semiring β]
/-- The product over a sum can be written as a sum over the product of sets, `finset.pi`.
`finset.prod_univ_sum` is an alternative statement when the product is over `univ`. -/
lemma prod_sum {δ : α → Type*} [decidable_eq α] [∀a, decidable_eq (δ a)]
{s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} :
(∏ a in s, ∑ b in (t a), f a b) =
∑ p in (s.pi t), ∏ x in s.attach, f x.1 (p x.1 x.2) :=
begin
induction s using finset.induction with a s ha ih,
{ rw [pi_empty, sum_singleton], refl },
{ have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y,
disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)),
{ assume x hx y hy h,
simp only [disjoint_iff_ne, mem_image],
rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq,
have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _),
{ rw [eq₂, eq₃, eq] },
rw [pi.cons_same, pi.cons_same] at this,
exact h this },
rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bUnion h₁],
refine sum_congr rfl (λ b _, _),
have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from
assume p₁ h₁ p₂ h₂ eq, pi_cons_injective ha eq,
rw [sum_image h₂, mul_sum],
refine sum_congr rfl (λ g _, _),
rw [attach_insert, prod_insert, prod_image],
{ simp only [pi.cons_same],
congr' with ⟨v, hv⟩, congr',
exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm },
{ exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj },
{ simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } }
end
open_locale classical
/-- The product of `f a + g a` over all of `s` is the sum
over the powerset of `s` of the product of `f` over a subset `t` times
the product of `g` over the complement of `t` -/
lemma prod_add (f g : α → β) (s : finset α) :
∏ a in s, (f a + g a) = ∑ t in s.powerset, ((∏ a in t, f a) * (∏ a in (s \ t), g a)) :=
calc ∏ a in s, (f a + g a)
= ∏ a in s, ∑ p in ({true, false} : finset Prop), if p then f a else g a : by simp
... = ∑ p in (s.pi (λ _, {true, false}) : finset (Π a ∈ s, Prop)),
∏ a in s.attach, if p a.1 a.2 then f a.1 else g a.1 : prod_sum
... = ∑ t in s.powerset, (∏ a in t, f a) * (∏ a in (s \ t), g a) : begin
refine eq.symm (sum_bij (λ t _ a _, a ∈ t) _ _ _ _),
{ simp [subset_iff]; tauto },
{ intros t ht,
erw [prod_ite (λ a : {a // a ∈ s}, f a.1) (λ a : {a // a ∈ s}, g a.1)],
refine congr_arg2 _
(prod_bij (λ (a : α) (ha : a ∈ t), ⟨a, mem_powerset.1 ht ha⟩)
_ _ _
(λ b hb, ⟨b, by cases b;
simpa only [true_and, exists_prop, mem_filter, and_true, mem_attach, eq_self_iff_true,
subtype.coe_mk] using hb⟩))
(prod_bij (λ (a : α) (ha : a ∈ s \ t), ⟨a, by simp * at *⟩)
_ _ _
(λ b hb, ⟨b, by cases b; begin
simp only [true_and, mem_filter, mem_attach, subtype.coe_mk] at hb,
simpa only [true_and, exists_prop, and_true, mem_sdiff, eq_self_iff_true, subtype.coe_mk,
b_property],
end⟩));
intros; simp * at *; simp * at * },
{ assume a₁ a₂ h₁ h₂ H,
ext x,
simp only [function.funext_iff, subset_iff, mem_powerset, eq_iff_iff] at h₁ h₂ H,
exact ⟨λ hx, (H x (h₁ hx)).1 hx, λ hx, (H x (h₂ hx)).2 hx⟩ },
{ assume f hf,
exact ⟨s.filter (λ a : α, ∃ h : a ∈ s, f a h),
by simp, by funext; intros; simp *⟩ }
end
/-- `∏ i, (f i + g i) = (∏ i, f i) + ∑ i, g i * (∏ j < i, f j + g j) * (∏ j > i, f j)`. -/
lemma prod_add_ordered {ι R : Type*} [comm_semiring R] [linear_order ι] (s : finset ι)
(f g : ι → R) :
(∏ i in s, (f i + g i)) = (∏ i in s, f i) +
∑ i in s, g i * (∏ j in s.filter (< i), (f j + g j)) * ∏ j in s.filter (λ j, i < j), f j :=
begin
refine finset.induction_on_max s (by simp) _,
clear s, intros a s ha ihs,
have ha' : a ∉ s, from λ ha', (ha a ha').false,
rw [prod_insert ha', prod_insert ha', sum_insert ha', filter_insert, if_neg (lt_irrefl a),
filter_true_of_mem ha, ihs, add_mul, mul_add, mul_add, add_assoc],
congr' 1, rw add_comm, congr' 1,
{ rw [filter_false_of_mem, prod_empty, mul_one],
exact (forall_mem_insert _ _ _).2 ⟨lt_irrefl a, λ i hi, (ha i hi).not_lt⟩ },
{ rw mul_sum,
refine sum_congr rfl (λ i hi, _),
rw [filter_insert, if_neg (ha i hi).not_lt, filter_insert, if_pos (ha i hi), prod_insert,
mul_left_comm],
exact mt (λ ha, (mem_filter.1 ha).1) ha' }
end
/-- `∏ i, (f i - g i) = (∏ i, f i) - ∑ i, g i * (∏ j < i, f j - g j) * (∏ j > i, f j)`. -/
lemma prod_sub_ordered {ι R : Type*} [comm_ring R] [linear_order ι] (s : finset ι) (f g : ι → R) :
(∏ i in s, (f i - g i)) = (∏ i in s, f i) -
∑ i in s, g i * (∏ j in s.filter (< i), (f j - g j)) * ∏ j in s.filter (λ j, i < j), f j :=
begin
simp only [sub_eq_add_neg],
convert prod_add_ordered s f (λ i, -g i),
simp,
end
/-- `∏ i, (1 - f i) = 1 - ∑ i, f i * (∏ j < i, 1 - f j)`. This formula is useful in construction of
a partition of unity from a collection of “bump” functions. -/
lemma prod_one_sub_ordered {ι R : Type*} [comm_ring R] [linear_order ι] (s : finset ι) (f : ι → R) :
(∏ i in s, (1 - f i)) = 1 - ∑ i in s, f i * ∏ j in s.filter (< i), (1 - f j) :=
by { rw prod_sub_ordered, simp }
/-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a `finset`
gives `(a + b)^s.card`.-/
lemma sum_pow_mul_eq_add_pow
{α R : Type*} [comm_semiring R] (a b : R) (s : finset α) :
(∑ t in s.powerset, a ^ t.card * b ^ (s.card - t.card)) = (a + b) ^ s.card :=
begin
rw [← prod_const, prod_add],
refine finset.sum_congr rfl (λ t ht, _),
rw [prod_const, prod_const, ← card_sdiff (mem_powerset.1 ht)]
end
theorem dvd_sum {b : β} {s : finset α} {f : α → β}
(h : ∀ x ∈ s, b ∣ f x) : b ∣ ∑ x in s, f x :=
multiset.dvd_sum (λ y hy, by rcases multiset.mem_map.1 hy with ⟨x, hx, rfl⟩; exact h x hx)
@[norm_cast]
lemma prod_nat_cast (s : finset α) (f : α → ℕ) :
↑(∏ x in s, f x : ℕ) = (∏ x in s, (f x : β)) :=
(nat.cast_ring_hom β).map_prod f s
end comm_semiring
section comm_ring
variables {R : Type*} [comm_ring R]
lemma prod_range_cast_nat_sub (n k : ℕ) :
∏ i in range k, (n - i : R) = (∏ i in range k, (n - i) : ℕ) :=
begin
rw prod_nat_cast,
cases le_or_lt k n with hkn hnk,
{ exact prod_congr rfl (λ i hi, (nat.cast_sub $ (mem_range.1 hi).le.trans hkn).symm) },
{ rw ← mem_range at hnk,
rw [prod_eq_zero hnk, prod_eq_zero hnk]; simp }
end
end comm_ring
/-- A product over all subsets of `s ∪ {x}` is obtained by multiplying the product over all subsets
of `s`, and over all subsets of `s` to which one adds `x`. -/
@[to_additive "A sum over all subsets of `s ∪ {x}` is obtained by summing the sum over all subsets
of `s`, and over all subsets of `s` to which one adds `x`."]
lemma prod_powerset_insert [decidable_eq α] [comm_monoid β] {s : finset α} {x : α} (h : x ∉ s)
(f : finset α → β) :
(∏ a in (insert x s).powerset, f a) =
(∏ a in s.powerset, f a) * (∏ t in s.powerset, f (insert x t)) :=
begin
rw [powerset_insert, finset.prod_union, finset.prod_image],
{ assume t₁ h₁ t₂ h₂ heq,
rw [← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₁ h),
← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₂ h), heq] },
{ rw finset.disjoint_iff_ne,
assume t₁ h₁ t₂ h₂,
rcases finset.mem_image.1 h₂ with ⟨t₃, h₃, H₃₂⟩,
rw ← H₃₂,
exact ne_insert_of_not_mem _ _ (not_mem_of_mem_powerset_of_not_mem h₁ h) }
end
/-- A product over `powerset s` is equal to the double product over sets of subsets of `s` with
`card s = k`, for `k = 1, ..., card s`. -/
@[to_additive "A sum over `powerset s` is equal to the double sum over sets of subsets of `s` with
`card s = k`, for `k = 1, ..., card s`"]
lemma prod_powerset [comm_monoid β] (s : finset α) (f : finset α → β) :
∏ t in powerset s, f t = ∏ j in range (card s + 1), ∏ t in powerset_len j s, f t :=
begin
classical,
rw [powerset_card_bUnion, prod_bUnion],
intros i hi j hj hij,
rw [function.on_fun, powerset_len_eq_filter, powerset_len_eq_filter, disjoint_filter],
intros x hx hc hnc,
apply hij,
rwa ← hc,
end
lemma sum_range_succ_mul_sum_range_succ [non_unital_non_assoc_semiring β] (n k : ℕ) (f g : ℕ → β) :
(∑ i in range (n+1), f i) * (∑ i in range (k+1), g i) =
(∑ i in range n, f i) * (∑ i in range k, g i) +
f n * (∑ i in range k, g i) +
(∑ i in range n, f i) * g k +
f n * g k :=
by simp only [add_mul, mul_add, add_assoc, sum_range_succ]
end finset
|
f0e3a069a908e7027dc4ad1683a6cb453272943e
|
205f0fc16279a69ea36e9fd158e3a97b06834ce2
|
/src/04_Implication/00_intro.lean
|
36eb698a6f0ff33ac6a7280cc56c557edfb1c8db
|
[] |
no_license
|
kevinsullivan/cs-dm-lean
|
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
|
a06a94e98be77170ca1df486c8189338b16cf6c6
|
refs/heads/master
| 1,585,948,743,595
| 1,544,339,346,000
| 1,544,339,346,000
| 155,570,767
| 1
| 3
| null | 1,541,540,372,000
| 1,540,995,993,000
|
Lean
|
UTF-8
|
Lean
| false
| false
| 11,564
|
lean
|
/-
Given any two propositions, P and Q, we can form
the proposition, P → Q. That is the syntax of an
implications.
If P and Q are propositions, we read P → Q as
P implies Q. A proof of a proposition, P → Q,
is a program that that converts any proof of P
into a proof of Q. The type of such a program
is P → Q.
-/
/- Elimination Rule for Implication -/
/-
From two premises, (1) that "if it's raining then
the streets are wet," and (2) "it's raining,"" we
can surely derive as a conclusion that the streets
are wet. Combining "raining → streets wet" with
"raining" reduces to "streets wet." This is modus
ponens.
Let's abbreviate the proposition "it's raining",
as R, and let's also abbreviate the proposition,
"the streets are wet as W". We will then abbreviate
the proposition "if it's raining then the streets
are wet" as R → W.
Such a proposition is in the form of what we call
an implication. It can be pronounced as "R implies
W", or simply "if R is true then W must be true."
Note that by this latter reading, in a case where
R is not true, the implication says nothing about
whether W must be true or not. We will thus judge
an implication to be true if either R is false (in
which case the implications does not constrain W
to be any value), or if whenever R is true, W is,
too. The one situation under which we will not be
able to judge R → W to be true is if it can be
the case that R is true and yet W is not, as that
would contradict the meaning of an implication.
With these abbreviations in hand, we can write
an informal inference rule to capture the idea
we started with. If we know that a proposition,
R → W, is true, and we know that the proposition,
R, is true, then we can deduce that W therefore
must also be true. We can write this inference
rule informally like this:
R → W, R
-------- (→ elim)
W
This is the arrow (→) elimination rule?
In the rest of this chapter, we will formalize
this notion of inference by first presenting the
elimination rule for implication. We will see
that this rule not only formalizes Aristotle's
modus ponens rule of reasoning (it is one of
his fundamental "syllogisms"), but it also
corresponds to function application!
EXERCISE: When you apply a function that takes
an argument of type R and returns a value of
type W to a value of type R, what do you get?
-/
/-
Now let's specify that R and W are arbitrary
propositions in the type theory of Lean. And
recall that to judge R → W to be true or to
judge either R or W to be true means that we
have proofs of these propositions. We can now
give a precise rule in type theory capturing
Aristotle's modus ponens: what it means to be
a function, and how function application works.
{ R W : Prop }, pfRtoW : R → W, pfR : R
--------------------------------------- (→-elim)
pfW: W
Here it is formalized as a function.
-/
def
arrow_elim
{ R W: Prop } (pfRtopfW : R → W) (pfR : R) : W :=
pfRtopfW pfR
/-
This program expresses the inference rule. The
name of the rule (a program) is arrow_elim. The
function takes (1) two propositions, R and W;
(2) a proof of R → W (itself a program that
converts and proof of R into a proof of W;
(3) a proof of R. If promises that if it is
given any values of these types, it will
return a proof of(a value of type) W. Given
values for its arguments it derives a proof
of W by applying that given function to that
given value. The result will be a proof of (a
value of type) W.
We thus now have another way to pronounce this
inference rule: "if you have a function that can
turn any proof of R into a proof of W, and if you
have a proof of R, then you obtain a proof of W,
and you do it in particular by applying the
function to that value."
-/
/- In yet other words, if you've got a function
and you've got an argument value, then you can
eliminate the function (the "arrow") by applying
the function to that value, yielding a value of
the return type.
-/
/-
A concrete example of a program that serves as
a proof of W → R is found in our program, from
the 03_Conjunction chapter that turns any proof
of P ∧ Q (W) into a proof Q ∧ P (R).
We wrote that code so that for any propositions,
P and Q, for any proof of P ∧ Q, it returns a
proof of Q ∧ P. It can always do this because
from any proof of P ∧ Q, it can obtain separate
proofs of P and Q that it can then re-assembled
into a proof of Q ∧ P. That function is a proof
of this type: ∀ P Q: Prop, P ∧ Q → Q ∧ P. That
says, for any propositions, P and Q, a function
of this type turns a proof of P ∧ Q into a proof
of Q ∧ P. It thus proves P ∧ Q → Q ∧ P.
-/
/-
We want to give an example of the use of the
arrow-elim rule. In this example we use a new
(for us) capability of Lean: you can define
variables to be give given types without proofs,
i.e., as axioms.
Here (read the code) we assume that P and Q
are arbitrary propositions. We do not say
what specific propositions they are. Next
we assume that we have a proof that P → Q,
which will be represented as a program
that takes proofs of Ps and returns proofs
of Qs. Third we assume that we have some
proof of P. And finally we check to see
that the result of applying impl to pfP is
of type Q.
-/
variables P Q : Prop
variable impl : P → Q
variable pfP : P
#check (impl pfP)
#check (arrow_elim impl pfP)
/-
In Lean, a proof of R → W is given as a
program: a "recipe" for making a proof of W
out of a proof of R. With such a program in
hand, if we apply it to a proof of R it will
derive a proof of W.
-/
/-
EXAMPLE: implications involving true and false
-/
/-
Another way to read P → Q is "if P (is true)
then Q (is true)."
We now ask which of the following implications
can be proved?
true → true -- if true (is true) then true (is true)
true → false -- if true (is true) then false (is true)
false → true -- if false (is true) then true (is true)
false → false -- if false (is true) then false (is true)
EXERCISE: What is your intuition?
Hint: Remember the unit on true and false. Think about
the false elimination rule. Recall how many proofs there
are of the proposition, false.
-/
/- true → true -/
/-
Let's see one of the simplest of all possible
examples to make these abstract ideas concrete.
Consider the proposition, true → true. We can
read this as "true implies true". But for our
purposes, a better way to say it is, "if you
assume you are given a proof of true, then you
can construct and return a proof of true."
We can also see this proposition as the type of
any program that turns a proof of true into a
proof of true. That's going to be easy! Here it
is: a simple function definition in Lean. We call
the program timpt (for "true implies true"). It
takes an argument, pf_true, of type true, i.e.,
a proof of true, as an argument, and it builds
and returns a proof of true by just returning
the proof it was given! This function is thus
just the identity function of type true → true.
-/
def timpt ( pf_true: true ) : true := pf_true
theorem timpt_theorem : true → true := timpt
#check timpt
/-
If this program is given a proof, pf, of true,
it can and does return a proof of true. Let's
quickly verify that by looking at the value we
get when we apply the function (implication) to
true.intro, which is the always-available proof
of true.
-/
#reduce (timpt true.intro)
/-
Indeed, this program is in effect a proof
of true → true because if it's given any
proof of true (there's only one), it then
returns a proof of true.
Now we can see explicitly that this program
is a proof of the proposition, true → true,
by formalizing the proposition, true → true,
and giving the program as a proof!
-/
theorem true_imp_true : true → true := timpt
/-
And the type of the program, which we are
now interpreting as a proof of true → true,
is thus true → true. The program is a value
of the proposition, and type, true → true.
-/
#check timpt
/- true → false -/
/-
EXERCISE: Can you prove true → false? If
so, state and prove the theorem. If not,
explain exactly why you think you can't
do it.
-/
-- def timpf (pf_true : true) : false := _
-- theorem timpf_theorem: true → false := _
/- false → true -/
/-
EXERCISE: Prove false → true. The key to
doing this is to remember that applying
false.elim (think of it as a function) to
a proof of false proves anything at all.
-/
def fimpt (f: false) : true := true.intro
theorem fimpt_theorem : false → true := fimpt
/- false → false -/
/-
EXERCISE: Is it true that false → false?
Prove it. Hint: We wrote a program that
turned out to be a proof of true → true.
If you can write such a program, call it
fimpf, then use it to prove the theorem,
false_imp_false: false → false.
-/
def fimpf (f: false) : false := f
theorem fimpf_theorem : false → false := fimpf
def fimpzeqo (f: false) : 0 = 1 := false.elim f
theorem fizeo : false → 0 = 1 := fimpzeqo
/-
We summarize our findings in the following
table for implication.
true → true : proof, true
true → false : <no proof>
false → true : proof, true
false → false : proof, true
What's deeply interesting here is that
we're not just given these judgments as
unexplained pronouncements. We've *proved*
three of these judgments. The fourth we
could not prove, and we made an argument
that it can't be proved, but we haven't
yet formally proved, nor do even have a
way to say yet, that the proposition is
false. The best we can say at this time
is that we don't have a proof.
-/
#check true_imp_true -- (proof of) implication
#check true.intro -- (proof of) premise
#check (true_imp_true true.intro) -- conclusion!
/- *** → INTRODUCTION RULE -/
/-
The → introduction rules say that if
assuming that there is proof of P allows
you to derive a proof of Q, then one can
derive a proof of P → Q, discharging the
assumption.
To represent this rule as an inference
rule, we need a notation to represent
the idea that from an assumption that
there is a proof of P one can derive a
proof of Q. The notation used in most
logic books represents this notion as a
vertical dotted line from a P above to
a Q below. If one has such a derivation
then one can conclude P → Q. The idea
is that the derivation is in essence a
program; the program is the proof; and
it is a proof of the proposition, which
is to say, of the type, P → Q.
P
|
|
Q
-----
P → Q
The proof of a proposition, P → Q, in
Lean, is thus a program that takes an
argument of type P and returns a result
of type Q.
-/
/- ** Direct Proofs: Proof Strategy -/
/-
Many of the propositions you need to
prove in practice are implications, of
the form P → Q. It's a way of saying,
"under conditions defined by P it must
be the case that Q is also true. A
direct proof is just what we have
seen: a way to derive a proof of Q
from an assumed proof of P.
To prove P → Q, you thus start with an
assumption that there's a proof of P,
and from that you deduce a proof of Q.
-/
/-
EXAMPLE: Give a direct proof of eqsym:
a = b → b = a. Give it as both a lambda
expression and as an assume-show-from
tactic script.
-/
lemma eqsym :
∀ a b : nat, a = b → b = a
:= sorry
lemma eqsym' :
∀ a b : nat, a = b → b = a
:= begin
sorry
end
/-
http://zimmer.csufresno.edu/~larryc/proofs/proofs.direct.html
-/
|
043481018f5d438ff693c816ae2d6a467f8a772e
|
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
|
/src/ring_theory/polynomial/chebyshev/dickson.lean
|
54c1b4bff9eda9d99f6d4ecf02cc518c9e5a4508
|
[
"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
| 3,094
|
lean
|
/-
Copyright (c) 2021 Julian Kuelshammer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Julian Kuelshammer
-/
import data.polynomial.eval
import ring_theory.polynomial.chebyshev.defs
/-!
# Dickson polynomials
The (generalised) Dickson polynomials are a family of polynomials indexed by `ℕ × ℕ`,
with coefficients in a commutative ring `R` depending on an element `a∈R`. More precisely, the
they satisfy the recursion `dickson k a (n + 2) = X * (dickson k a n + 1) - a * (dickson k a n)`
with starting values `dickson k a 0 = 3 - k` and `dickson k a 1 = X`. In the literature,
`dickson k a n` is called the `n`-th Dickson polynomial of the `k`-th kind associated to the
parameter `a : R`. They are closely related to the Chebyshev polynomials in the case that `a=1`.
When `a=0` they are just the family of monomials `X ^ n`.
## Main definition
* `polynomial.dickson`: the generalised Dickson polynomials.
## References
* [R. Lidl, G. L. Mullen and G. Turnwald, _Dickson polynomials_][MR1237403]
## TODO
* Redefine `dickson` in terms of `linear_recurrence`.
* Show that `dickson 2 1` is equal to the characteristic polynomial of the adjacency matrix of a
type A Dynkin diagram.
* Prove that the adjacency matrices of simply laced Dynkin diagrams are precisely the adjacency
matrices of simple connected graphs which annihilate `dickson 2 1`.
-/
noncomputable theory
namespace polynomial
variables {R S : Type*} [comm_ring R] [comm_ring S] (k : ℕ) (a : R)
/-- `dickson` is the `n`the (generalised) Dickson polynomial of the `k`-th kind associated to the
element `a ∈ R`. -/
noncomputable def dickson : ℕ → polynomial R
| 0 := 3 - k
| 1 := X
| (n + 2) := X * dickson (n + 1) - (C a) * dickson n
@[simp] lemma dickson_zero : dickson k a 0 = 3 - k := rfl
@[simp] lemma dickson_one : dickson k a 1 = X := rfl
lemma dickson_two : dickson k a 2 = X ^ 2 - C a * (3 - k) :=
by simp only [dickson, pow_two]
@[simp] lemma dickson_add_two (n : ℕ) :
dickson k a (n + 2) = X * dickson k a (n + 1) - C a * dickson k a n :=
by rw dickson
lemma dickson_of_two_le {n : ℕ} (h : 2 ≤ n) :
dickson k a n = X * dickson k a (n - 1) - C a * dickson k a (n - 2) :=
begin
obtain ⟨n, rfl⟩ := nat.exists_eq_add_of_le h,
rw add_comm,
exact dickson_add_two k a n
end
variables {R S k a}
lemma map_dickson (f : R →+* S) :
∀ (n : ℕ), map f (dickson k a n) = dickson k (f a) n
| 0 := by simp only [dickson_zero, map_sub, map_nat_cast, bit1, bit0, map_add, map_one]
| 1 := by simp only [dickson_one, map_X]
| (n + 2) :=
begin
simp only [dickson_add_two, map_sub, map_mul, map_X, map_C],
rw [map_dickson, map_dickson]
end
variable {R}
@[simp] lemma dickson_two_zero :
∀ (n : ℕ), dickson 2 (0 : R) n = X ^ n
| 0 := by { simp only [dickson_zero, pow_zero], norm_num }
| 1 := by simp only [dickson_one, pow_one]
| (n + 2) :=
begin
simp only [dickson_add_two, C_0, zero_mul, sub_zero],
rw [dickson_two_zero, pow_add X (n + 1) 1, mul_comm, pow_one]
end
end polynomial
|
c2b591e338745efa8d79f3426c47c4db2324e667
|
74addaa0e41490cbaf2abd313a764c96df57b05d
|
/Mathlib/algebra/monoid_algebra.lean
|
f05ac5e98e3a28eb5b1b729b10ae80b785305775
|
[] |
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
| 40,442
|
lean
|
/-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Yury G. Kudryashov, Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.algebra.basic
import Mathlib.linear_algebra.finsupp
import Mathlib.PostPort
universes u₁ u₂ u_1 u_2 u_3 u₃ ui
namespace Mathlib
/-!
# Monoid algebras
When the domain of a `finsupp` has a multiplicative or additive structure, we can define
a convolution product. To mathematicians this structure is known as the "monoid algebra",
i.e. the finite formal linear combinations over a given semiring of elements of the monoid.
The "group ring" ℤ[G] or the "group algebra" k[G] are typical uses.
In this file we define `monoid_algebra k G := G →₀ k`, and `add_monoid_algebra k G`
in the same way, and then define the convolution product on these.
When the domain is additive, this is used to define polynomials:
```
polynomial α := add_monoid_algebra ℕ α
mv_polynomial σ α := add_monoid_algebra (σ →₀ ℕ) α
```
When the domain is multiplicative, e.g. a group, this will be used to define the group ring.
## Implementation note
Unfortunately because additive and multiplicative structures both appear in both cases,
it doesn't appear to be possible to make much use of `to_additive`, and we just settle for
saying everything twice.
Similarly, I attempted to just define
`add_monoid_algebra k G := monoid_algebra k (multiplicative G)`, but the definitional equality
`multiplicative G = G` leaks through everywhere, and seems impossible to use.
-/
/-! ### Multiplicative monoids -/
/--
The monoid algebra over a semiring `k` generated by the monoid `G`.
It is the type of finite formal `k`-linear combinations of terms of `G`,
endowed with the convolution product.
-/
def monoid_algebra (k : Type u₁) (G : Type u₂) [semiring k] :=
G →₀ k
namespace monoid_algebra
/-! #### Semiring structure -/
/-- The product of `f g : monoid_algebra k G` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x * y = a`. (Think of the group ring of a group.) -/
protected instance has_mul {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] : Mul (monoid_algebra k G) :=
{ mul :=
fun (f g : monoid_algebra k G) =>
finsupp.sum f fun (a₁ : G) (b₁ : k) => finsupp.sum g fun (a₂ : G) (b₂ : k) => finsupp.single (a₁ * a₂) (b₁ * b₂) }
theorem mul_def {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] {f : monoid_algebra k G} {g : monoid_algebra k G} : f * g = finsupp.sum f fun (a₁ : G) (b₁ : k) => finsupp.sum g fun (a₂ : G) (b₂ : k) => finsupp.single (a₁ * a₂) (b₁ * b₂) :=
rfl
/-- The unit of the multiplication is `single 1 1`, i.e. the function
that is `1` at `1` and zero elsewhere. -/
protected instance has_one {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] : HasOne (monoid_algebra k G) :=
{ one := finsupp.single 1 1 }
theorem one_def {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] : 1 = finsupp.single 1 1 :=
rfl
protected instance semiring {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] : semiring (monoid_algebra k G) :=
semiring.mk Add.add sorry 0 sorry sorry sorry Mul.mul sorry 1 sorry sorry sorry sorry sorry sorry
/-- A non-commutative version of `monoid_algebra.lift`: given a additive homomorphism `f : k →+ R`
and a multiplicative monoid homomorphism `g : G →* R`, returns the additive homomorphism from
`monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f` is a ring homomorphism
and the range of either `f` or `g` is in center of `R`, then the result is a ring homomorphism. If
`R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra homomorphism called
`monoid_algebra.lift`. -/
def lift_nc {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] {R : Type u_1} [semiring R] (f : k →+ R) (g : G →* R) : monoid_algebra k G →+ R :=
coe_fn finsupp.lift_add_hom fun (x : G) => add_monoid_hom.comp (add_monoid_hom.mul_right (coe_fn g x)) f
@[simp] theorem lift_nc_single {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] {R : Type u_1} [semiring R] (f : k →+ R) (g : G →* R) (a : G) (b : k) : coe_fn (lift_nc f g) (finsupp.single a b) = coe_fn f b * coe_fn g a :=
finsupp.lift_add_hom_apply_single (fun (x : G) => add_monoid_hom.comp (add_monoid_hom.mul_right (coe_fn g x)) f) a b
@[simp] theorem lift_nc_one {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] {R : Type u_1} [semiring R] (f : k →+* R) (g : G →* R) : coe_fn (lift_nc (↑f) g) 1 = 1 := sorry
theorem lift_nc_mul {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] {R : Type u_1} [semiring R] (f : k →+* R) (g : G →* R) (a : monoid_algebra k G) (b : monoid_algebra k G) (h_comm : ∀ {x y : G}, y ∈ finsupp.support a → commute (coe_fn f (coe_fn b x)) (coe_fn g y)) : coe_fn (lift_nc (↑f) g) (a * b) = coe_fn (lift_nc (↑f) g) a * coe_fn (lift_nc (↑f) g) b := sorry
/-- `lift_nc` as a `ring_hom`, for when `f x` and `g y` commute -/
def lift_nc_ring_hom {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] {R : Type u_1} [semiring R] (f : k →+* R) (g : G →* R) (h_comm : ∀ (x : k) (y : G), commute (coe_fn f x) (coe_fn g y)) : monoid_algebra k G →+* R :=
ring_hom.mk (⇑(lift_nc (↑f) g)) (lift_nc_one f g) sorry sorry sorry
protected instance comm_semiring {k : Type u₁} {G : Type u₂} [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_algebra k G) :=
comm_semiring.mk semiring.add sorry semiring.zero sorry sorry sorry semiring.mul sorry semiring.one sorry sorry sorry
sorry sorry sorry sorry
protected instance nontrivial {k : Type u₁} {G : Type u₂} [semiring k] [nontrivial k] [monoid G] : nontrivial (monoid_algebra k G) :=
finsupp.nontrivial
/-! #### Derived instances -/
protected instance unique {k : Type u₁} {G : Type u₂} [semiring k] [subsingleton k] : unique (monoid_algebra k G) :=
finsupp.unique_of_right
protected instance add_group {k : Type u₁} {G : Type u₂} [ring k] : add_group (monoid_algebra k G) :=
finsupp.add_group
protected instance ring {k : Type u₁} {G : Type u₂} [ring k] [monoid G] : ring (monoid_algebra k G) :=
ring.mk semiring.add sorry semiring.zero sorry sorry Neg.neg
(add_comm_group.sub._default semiring.add sorry semiring.zero sorry sorry Neg.neg) sorry sorry semiring.mul sorry
semiring.one sorry sorry sorry sorry
protected instance comm_ring {k : Type u₁} {G : Type u₂} [comm_ring k] [comm_monoid G] : comm_ring (monoid_algebra k G) :=
comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry ring.one sorry sorry
sorry sorry sorry
protected instance has_scalar {k : Type u₁} {G : Type u₂} {R : Type u_1} [semiring R] [semiring k] [semimodule R k] : has_scalar R (monoid_algebra k G) :=
finsupp.has_scalar
protected instance semimodule {k : Type u₁} {G : Type u₂} {R : Type u_1} [semiring R] [semiring k] [semimodule R k] : semimodule R (monoid_algebra k G) :=
finsupp.semimodule G k
protected instance distrib_mul_action {k : Type u₁} {G : Type u₂} [group G] [semiring k] : distrib_mul_action G (monoid_algebra k G) :=
finsupp.comap_distrib_mul_action_self
theorem mul_apply {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] (f : monoid_algebra k G) (g : monoid_algebra k G) (x : G) : coe_fn (f * g) x =
finsupp.sum f fun (a₁ : G) (b₁ : k) => finsupp.sum g fun (a₂ : G) (b₂ : k) => ite (a₁ * a₂ = x) (b₁ * b₂) 0 := sorry
theorem mul_apply_antidiagonal {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] (f : monoid_algebra k G) (g : monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ prod.fst p * prod.snd p = x) : coe_fn (f * g) x = finset.sum s fun (p : G × G) => coe_fn f (prod.fst p) * coe_fn g (prod.snd p) := sorry
theorem support_mul {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] (a : monoid_algebra k G) (b : monoid_algebra k G) : finsupp.support (a * b) ⊆
finset.bUnion (finsupp.support a)
fun (a₁ : G) => finset.bUnion (finsupp.support b) fun (a₂ : G) => singleton (a₁ * a₂) := sorry
@[simp] theorem single_mul_single {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] {a₁ : G} {a₂ : G} {b₁ : k} {b₂ : k} : finsupp.single a₁ b₁ * finsupp.single a₂ b₂ = finsupp.single (a₁ * a₂) (b₁ * b₂) := sorry
@[simp] theorem single_pow {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] {a : G} {b : k} (n : ℕ) : finsupp.single a b ^ n = finsupp.single (a ^ n) (b ^ n) := sorry
/-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/
theorem map_domain_mul {α : Type u_1} {β : Type u_2} {α₂ : Type u_3} [semiring β] [monoid α] [monoid α₂] {x : monoid_algebra β α} {y : monoid_algebra β α} (f : mul_hom α α₂) : finsupp.map_domain (⇑f) (x * y) = finsupp.map_domain (⇑f) x * finsupp.map_domain (⇑f) y := sorry
/-- Embedding of a monoid into its monoid algebra. -/
def of (k : Type u₁) (G : Type u₂) [semiring k] [monoid G] : G →* monoid_algebra k G :=
monoid_hom.mk (fun (a : G) => finsupp.single a 1) sorry sorry
@[simp] theorem of_apply {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] (a : G) : coe_fn (of k G) a = finsupp.single a 1 :=
rfl
theorem of_injective {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] [nontrivial k] : function.injective ⇑(of k G) := sorry
theorem mul_single_apply_aux {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] (f : monoid_algebra k G) {r : k} {x : G} {y : G} {z : G} (H : ∀ (a : G), a * x = z ↔ a = y) : coe_fn (f * finsupp.single x r) z = coe_fn f y * r := sorry
theorem mul_single_one_apply {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] (f : monoid_algebra k G) (r : k) (x : G) : coe_fn (f * finsupp.single 1 r) x = coe_fn f x * r :=
mul_single_apply_aux f
fun (a : G) => eq.mpr (id (Eq._oldrec (Eq.refl (a * 1 = x ↔ a = x)) (mul_one a))) (iff.refl (a = x))
theorem single_mul_apply_aux {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] (f : monoid_algebra k G) {r : k} {x : G} {y : G} {z : G} (H : ∀ (a : G), x * a = y ↔ a = z) : coe_fn (finsupp.single x r * f) y = r * coe_fn f z := sorry
theorem single_one_mul_apply {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] (f : monoid_algebra k G) (r : k) (x : G) : coe_fn (finsupp.single 1 r * f) x = r * coe_fn f x :=
single_mul_apply_aux f
fun (a : G) => eq.mpr (id (Eq._oldrec (Eq.refl (1 * a = x ↔ a = x)) (one_mul a))) (iff.refl (a = x))
theorem lift_nc_smul {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] {R : Type u_1} [semiring R] (f : k →+* R) (g : G →* R) (c : k) (φ : monoid_algebra k G) : coe_fn (lift_nc (↑f) g) (c • φ) = coe_fn f c * coe_fn (lift_nc (↑f) g) φ := sorry
/-! #### Algebra structure -/
theorem single_one_comm {k : Type u₁} {G : Type u₂} [comm_semiring k] [monoid G] (r : k) (f : monoid_algebra k G) : finsupp.single 1 r * f = f * finsupp.single 1 r := sorry
/-- `finsupp.single 1` as a `ring_hom` -/
def single_one_ring_hom {k : Type u₁} {G : Type u₂} [semiring k] [monoid G] : k →+* monoid_algebra k G :=
ring_hom.mk (add_monoid_hom.to_fun (finsupp.single_add_hom 1)) sorry sorry sorry sorry
/-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1`
and `single 1 b`, then they are equal. -/
theorem ring_hom_ext {k : Type u₁} {G : Type u₂} {R : Type u_1} [semiring k] [monoid G] [semiring R] {f : monoid_algebra k G →+* R} {g : monoid_algebra k G →+* R} (h₁ : ∀ (b : k), coe_fn f (finsupp.single 1 b) = coe_fn g (finsupp.single 1 b)) (h_of : ∀ (a : G), coe_fn f (finsupp.single a 1) = coe_fn g (finsupp.single a 1)) : f = g := sorry
/-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1`
and `single 1 b`, then they are equal.
See note [partially-applied ext lemmas]. -/
theorem ring_hom_ext' {k : Type u₁} {G : Type u₂} {R : Type u_1} [semiring k] [monoid G] [semiring R] {f : monoid_algebra k G →+* R} {g : monoid_algebra k G →+* R} (h₁ : ring_hom.comp f single_one_ring_hom = ring_hom.comp g single_one_ring_hom) (h_of : monoid_hom.comp (↑f) (of k G) = monoid_hom.comp (↑g) (of k G)) : f = g :=
ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of)
/--
The instance `algebra k (monoid_algebra A G)` whenever we have `algebra k A`.
In particular this provides the instance `algebra k (monoid_algebra k G)`.
-/
protected instance algebra {k : Type u₁} {G : Type u₂} {A : Type u_1} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : algebra k (monoid_algebra A G) :=
algebra.mk (ring_hom.mk (ring_hom.to_fun (ring_hom.comp single_one_ring_hom (algebra_map k A))) sorry sorry sorry sorry)
sorry sorry
/-- `finsupp.single 1` as a `alg_hom` -/
def single_one_alg_hom {k : Type u₁} {G : Type u₂} {A : Type u_1} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : alg_hom k A (monoid_algebra A G) :=
alg_hom.mk (ring_hom.to_fun single_one_ring_hom) sorry sorry sorry sorry sorry
@[simp] theorem coe_algebra_map {k : Type u₁} {G : Type u₂} {A : Type u_1} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : ⇑(algebra_map k (monoid_algebra A G)) = finsupp.single 1 ∘ ⇑(algebra_map k A) :=
rfl
theorem single_eq_algebra_map_mul_of {k : Type u₁} {G : Type u₂} [comm_semiring k] [monoid G] (a : G) (b : k) : finsupp.single a b = coe_fn (algebra_map k (monoid_algebra k G)) b * coe_fn (of k G) a := sorry
theorem single_algebra_map_eq_algebra_map_mul_of {k : Type u₁} {G : Type u₂} {A : Type u_1} [comm_semiring k] [semiring A] [algebra k A] [monoid G] (a : G) (b : k) : finsupp.single a (coe_fn (algebra_map k A) b) = coe_fn (algebra_map k (monoid_algebra A G)) b * coe_fn (of A G) a := sorry
/-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/
def lift_nc_alg_hom {k : Type u₁} {G : Type u₂} [comm_semiring k] [monoid G] {A : Type u₃} [semiring A] [algebra k A] {B : Type u_1} [semiring B] [algebra k B] (f : alg_hom k A B) (g : G →* B) (h_comm : ∀ (x : A) (y : G), commute (coe_fn f x) (coe_fn g y)) : alg_hom k (monoid_algebra A G) B :=
alg_hom.mk ⇑(lift_nc_ring_hom (↑f) g h_comm) sorry sorry sorry sorry sorry
/-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its
values on the functions `single a 1`. -/
theorem alg_hom_ext {k : Type u₁} {G : Type u₂} [comm_semiring k] [monoid G] {A : Type u₃} [semiring A] [algebra k A] {φ₁ : alg_hom k (monoid_algebra k G) A} {φ₂ : alg_hom k (monoid_algebra k G) A} (h : ∀ (x : G), coe_fn φ₁ (finsupp.single x 1) = coe_fn φ₂ (finsupp.single x 1)) : φ₁ = φ₂ :=
alg_hom.to_linear_map_inj (finsupp.lhom_ext' fun (a : G) => linear_map.ext_ring (h a))
/-- See note [partially-applied ext lemmas]. -/
theorem alg_hom_ext' {k : Type u₁} {G : Type u₂} [comm_semiring k] [monoid G] {A : Type u₃} [semiring A] [algebra k A] {φ₁ : alg_hom k (monoid_algebra k G) A} {φ₂ : alg_hom k (monoid_algebra k G) A} (h : monoid_hom.comp (↑φ₁) (of k G) = monoid_hom.comp (↑φ₂) (of k G)) : φ₁ = φ₂ :=
alg_hom_ext (monoid_hom.congr_fun h)
/-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism
`monoid_algebra k G →ₐ[k] A`. -/
def lift (k : Type u₁) (G : Type u₂) [comm_semiring k] [monoid G] (A : Type u₃) [semiring A] [algebra k A] : (G →* A) ≃ alg_hom k (monoid_algebra k G) A :=
equiv.mk (fun (F : G →* A) => lift_nc_alg_hom (algebra.of_id k A) F sorry)
(fun (f : alg_hom k (monoid_algebra k G) A) => monoid_hom.comp (↑f) (of k G)) sorry sorry
theorem lift_apply' {k : Type u₁} {G : Type u₂} [comm_semiring k] [monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : G →* A) (f : monoid_algebra k G) : coe_fn (coe_fn (lift k G A) F) f = finsupp.sum f fun (a : G) (b : k) => coe_fn (algebra_map k A) b * coe_fn F a :=
rfl
theorem lift_apply {k : Type u₁} {G : Type u₂} [comm_semiring k] [monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : G →* A) (f : monoid_algebra k G) : coe_fn (coe_fn (lift k G A) F) f = finsupp.sum f fun (a : G) (b : k) => b • coe_fn F a := sorry
theorem lift_def {k : Type u₁} {G : Type u₂} [comm_semiring k] [monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : G →* A) : ⇑(coe_fn (lift k G A) F) = ⇑(lift_nc (↑(algebra_map k A)) F) :=
rfl
@[simp] theorem lift_symm_apply {k : Type u₁} {G : Type u₂} [comm_semiring k] [monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : alg_hom k (monoid_algebra k G) A) (x : G) : coe_fn (coe_fn (equiv.symm (lift k G A)) F) x = coe_fn F (finsupp.single x 1) :=
rfl
theorem lift_of {k : Type u₁} {G : Type u₂} [comm_semiring k] [monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : G →* A) (x : G) : coe_fn (coe_fn (lift k G A) F) (coe_fn (of k G) x) = coe_fn F x := sorry
@[simp] theorem lift_single {k : Type u₁} {G : Type u₂} [comm_semiring k] [monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : G →* A) (a : G) (b : k) : coe_fn (coe_fn (lift k G A) F) (finsupp.single a b) = b • coe_fn F a := sorry
theorem lift_unique' {k : Type u₁} {G : Type u₂} [comm_semiring k] [monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : alg_hom k (monoid_algebra k G) A) : F = coe_fn (lift k G A) (monoid_hom.comp (↑F) (of k G)) :=
Eq.symm (equiv.apply_symm_apply (lift k G A) F)
/-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by
its values on `F (single a 1)`. -/
theorem lift_unique {k : Type u₁} {G : Type u₂} [comm_semiring k] [monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : alg_hom k (monoid_algebra k G) A) (f : monoid_algebra k G) : coe_fn F f = finsupp.sum f fun (a : G) (b : k) => b • coe_fn F (finsupp.single a 1) := sorry
/-- When `V` is a `k[G]`-module, multiplication by a group element `g` is a `k`-linear map. -/
def group_smul.linear_map (k : Type u₁) {G : Type u₂} [monoid G] [comm_semiring k] (V : Type u₃) [add_comm_monoid V] [semimodule k V] [semimodule (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] (g : G) : linear_map k V V :=
linear_map.mk (fun (v : V) => finsupp.single g 1 • v) sorry sorry
@[simp] theorem group_smul.linear_map_apply (k : Type u₁) {G : Type u₂} [monoid G] [comm_semiring k] (V : Type u₃) [add_comm_monoid V] [semimodule k V] [semimodule (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] (g : G) (v : V) : coe_fn (group_smul.linear_map k V g) v = finsupp.single g 1 • v :=
rfl
/-- Build a `k[G]`-linear map from a `k`-linear map and evidence that it is `G`-equivariant. -/
def equivariant_of_linear_of_comm {k : Type u₁} {G : Type u₂} [monoid G] [comm_semiring k] {V : Type u₃} {W : Type u₃} [add_comm_monoid V] [semimodule k V] [semimodule (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] [add_comm_monoid W] [semimodule k W] [semimodule (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (f : linear_map k V W) (h : ∀ (g : G) (v : V), coe_fn f (finsupp.single g 1 • v) = finsupp.single g 1 • coe_fn f v) : linear_map (monoid_algebra k G) V W :=
linear_map.mk ⇑f sorry sorry
@[simp] theorem equivariant_of_linear_of_comm_apply {k : Type u₁} {G : Type u₂} [monoid G] [comm_semiring k] {V : Type u₃} {W : Type u₃} [add_comm_monoid V] [semimodule k V] [semimodule (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] [add_comm_monoid W] [semimodule k W] [semimodule (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (f : linear_map k V W) (h : ∀ (g : G) (v : V), coe_fn f (finsupp.single g 1 • v) = finsupp.single g 1 • coe_fn f v) (v : V) : coe_fn (equivariant_of_linear_of_comm f h) v = coe_fn f v :=
rfl
theorem prod_single {k : Type u₁} {G : Type u₂} {ι : Type ui} [comm_semiring k] [comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (finset.prod s fun (i : ι) => finsupp.single (a i) (b i)) =
finsupp.single (finset.prod s fun (i : ι) => a i) (finset.prod s fun (i : ι) => b i) := sorry
@[simp] theorem mul_single_apply {k : Type u₁} {G : Type u₂} [semiring k] [group G] (f : monoid_algebra k G) (r : k) (x : G) (y : G) : coe_fn (f * finsupp.single x r) y = coe_fn f (y * (x⁻¹)) * r :=
mul_single_apply_aux f fun (a : G) => iff.symm eq_mul_inv_iff_mul_eq
@[simp] theorem single_mul_apply {k : Type u₁} {G : Type u₂} [semiring k] [group G] (r : k) (x : G) (f : monoid_algebra k G) (y : G) : coe_fn (finsupp.single x r * f) y = r * coe_fn f (x⁻¹ * y) :=
single_mul_apply_aux f fun (z : G) => iff.symm eq_inv_mul_iff_mul_eq
theorem mul_apply_left {k : Type u₁} {G : Type u₂} [semiring k] [group G] (f : monoid_algebra k G) (g : monoid_algebra k G) (x : G) : coe_fn (f * g) x = finsupp.sum f fun (a : G) (b : k) => b * coe_fn g (a⁻¹ * x) := sorry
-- If we'd assumed `comm_semiring`, we could deduce this from `mul_apply_left`.
theorem mul_apply_right {k : Type u₁} {G : Type u₂} [semiring k] [group G] (f : monoid_algebra k G) (g : monoid_algebra k G) (x : G) : coe_fn (f * g) x = finsupp.sum g fun (a : G) (b : k) => coe_fn f (x * (a⁻¹)) * b := sorry
end monoid_algebra
/-! ### Additive monoids -/
/--
The monoid algebra over a semiring `k` generated by the additive monoid `G`.
It is the type of finite formal `k`-linear combinations of terms of `G`,
endowed with the convolution product.
-/
def add_monoid_algebra (k : Type u₁) (G : Type u₂) [semiring k] :=
G →₀ k
namespace add_monoid_algebra
/-! #### Semiring structure -/
/-- The product of `f g : add_monoid_algebra k G` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x + y = a`. (Think of the product of multivariate
polynomials where `α` is the additive monoid of monomial exponents.) -/
protected instance has_mul {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] : Mul (add_monoid_algebra k G) :=
{ mul :=
fun (f g : add_monoid_algebra k G) =>
finsupp.sum f fun (a₁ : G) (b₁ : k) => finsupp.sum g fun (a₂ : G) (b₂ : k) => finsupp.single (a₁ + a₂) (b₁ * b₂) }
theorem mul_def {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] {f : add_monoid_algebra k G} {g : add_monoid_algebra k G} : f * g = finsupp.sum f fun (a₁ : G) (b₁ : k) => finsupp.sum g fun (a₂ : G) (b₂ : k) => finsupp.single (a₁ + a₂) (b₁ * b₂) :=
rfl
/-- The unit of the multiplication is `single 1 1`, i.e. the function
that is `1` at `0` and zero elsewhere. -/
protected instance has_one {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] : HasOne (add_monoid_algebra k G) :=
{ one := finsupp.single 0 1 }
theorem one_def {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] : 1 = finsupp.single 0 1 :=
rfl
protected instance semiring {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] : semiring (add_monoid_algebra k G) :=
semiring.mk Add.add sorry 0 sorry sorry sorry Mul.mul sorry 1 sorry sorry sorry sorry sorry sorry
/-- A non-commutative version of `add_monoid_algebra.lift`: given a additive homomorphism `f : k →+
R` and a multiplicative monoid homomorphism `g : multiplicative G →* R`, returns the additive
homomorphism from `add_monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f`
is a ring homomorphism and the range of either `f` or `g` is in center of `R`, then the result is a
ring homomorphism. If `R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra
homomorphism called `add_monoid_algebra.lift`. -/
def lift_nc {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] {R : Type u_1} [semiring R] (f : k →+ R) (g : multiplicative G →* R) : add_monoid_algebra k G →+ R :=
coe_fn finsupp.lift_add_hom
fun (x : G) => add_monoid_hom.comp (add_monoid_hom.mul_right (coe_fn g (coe_fn multiplicative.of_add x))) f
@[simp] theorem lift_nc_single {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] {R : Type u_1} [semiring R] (f : k →+ R) (g : multiplicative G →* R) (a : G) (b : k) : coe_fn (lift_nc f g) (finsupp.single a b) = coe_fn f b * coe_fn g (coe_fn multiplicative.of_add a) :=
finsupp.lift_add_hom_apply_single
(fun (x : G) => add_monoid_hom.comp (add_monoid_hom.mul_right (coe_fn g (coe_fn multiplicative.of_add x))) f) a b
@[simp] theorem lift_nc_one {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] {R : Type u_1} [semiring R] (f : k →+* R) (g : multiplicative G →* R) : coe_fn (lift_nc (↑f) g) 1 = 1 :=
monoid_algebra.lift_nc_one f g
theorem lift_nc_mul {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] {R : Type u_1} [semiring R] (f : k →+* R) (g : multiplicative G →* R) (a : add_monoid_algebra k G) (b : add_monoid_algebra k G) (h_comm : ∀ {x y : G}, y ∈ finsupp.support a → commute (coe_fn f (coe_fn b x)) (coe_fn g (coe_fn multiplicative.of_add y))) : coe_fn (lift_nc (↑f) g) (a * b) = coe_fn (lift_nc (↑f) g) a * coe_fn (lift_nc (↑f) g) b :=
monoid_algebra.lift_nc_mul f g a b h_comm
/-- `lift_nc` as a `ring_hom`, for when `f` and `g` commute -/
def lift_nc_ring_hom {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] {R : Type u_1} [semiring R] (f : k →+* R) (g : multiplicative G →* R) (h_comm : ∀ (x : k) (y : multiplicative G), commute (coe_fn f x) (coe_fn g y)) : add_monoid_algebra k G →+* R :=
ring_hom.mk (⇑(lift_nc (↑f) g)) (lift_nc_one f g) sorry sorry sorry
protected instance comm_semiring {k : Type u₁} {G : Type u₂} [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_algebra k G) :=
comm_semiring.mk semiring.add sorry semiring.zero sorry sorry sorry semiring.mul sorry semiring.one sorry sorry sorry
sorry sorry sorry sorry
protected instance nontrivial {k : Type u₁} {G : Type u₂} [semiring k] [nontrivial k] [add_monoid G] : nontrivial (add_monoid_algebra k G) :=
finsupp.nontrivial
/-! #### Derived instances -/
protected instance unique {k : Type u₁} {G : Type u₂} [semiring k] [subsingleton k] : unique (add_monoid_algebra k G) :=
finsupp.unique_of_right
protected instance add_group {k : Type u₁} {G : Type u₂} [ring k] : add_group (add_monoid_algebra k G) :=
finsupp.add_group
protected instance ring {k : Type u₁} {G : Type u₂} [ring k] [add_monoid G] : ring (add_monoid_algebra k G) :=
ring.mk semiring.add sorry semiring.zero sorry sorry Neg.neg Sub.sub sorry sorry semiring.mul sorry semiring.one sorry
sorry sorry sorry
protected instance comm_ring {k : Type u₁} {G : Type u₂} [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_algebra k G) :=
comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry ring.one sorry sorry
sorry sorry sorry
protected instance has_scalar {k : Type u₁} {G : Type u₂} {R : Type u_1} [semiring R] [semiring k] [semimodule R k] : has_scalar R (add_monoid_algebra k G) :=
finsupp.has_scalar
protected instance semimodule {k : Type u₁} {G : Type u₂} {R : Type u_1} [semiring R] [semiring k] [semimodule R k] : semimodule R (add_monoid_algebra k G) :=
finsupp.semimodule G k
/-! It is hard to state the equivalent of `distrib_mul_action G (add_monoid_algebra k G)`
because we've never discussed actions of additive groups. -/
theorem mul_apply {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] (f : add_monoid_algebra k G) (g : add_monoid_algebra k G) (x : G) : coe_fn (f * g) x =
finsupp.sum f fun (a₁ : G) (b₁ : k) => finsupp.sum g fun (a₂ : G) (b₂ : k) => ite (a₁ + a₂ = x) (b₁ * b₂) 0 :=
monoid_algebra.mul_apply f g x
theorem mul_apply_antidiagonal {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] (f : add_monoid_algebra k G) (g : add_monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ prod.fst p + prod.snd p = x) : coe_fn (f * g) x = finset.sum s fun (p : G × G) => coe_fn f (prod.fst p) * coe_fn g (prod.snd p) :=
monoid_algebra.mul_apply_antidiagonal f g x s hs
theorem support_mul {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] (a : add_monoid_algebra k G) (b : add_monoid_algebra k G) : finsupp.support (a * b) ⊆
finset.bUnion (finsupp.support a)
fun (a₁ : G) => finset.bUnion (finsupp.support b) fun (a₂ : G) => singleton (a₁ + a₂) :=
monoid_algebra.support_mul a b
theorem single_mul_single {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] {a₁ : G} {a₂ : G} {b₁ : k} {b₂ : k} : finsupp.single a₁ b₁ * finsupp.single a₂ b₂ = finsupp.single (a₁ + a₂) (b₁ * b₂) :=
monoid_algebra.single_mul_single
/-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/
theorem map_domain_mul {α : Type u_1} {β : Type u_2} {α₂ : Type u_3} [semiring β] [add_monoid α] [add_monoid α₂] {x : add_monoid_algebra β α} {y : add_monoid_algebra β α} (f : add_hom α α₂) : finsupp.map_domain (⇑f) (x * y) = finsupp.map_domain (⇑f) x * finsupp.map_domain (⇑f) y := sorry
/-- Embedding of a monoid into its monoid algebra. -/
def of (k : Type u₁) (G : Type u₂) [semiring k] [add_monoid G] : multiplicative G →* add_monoid_algebra k G :=
monoid_hom.mk (fun (a : multiplicative G) => finsupp.single a 1) sorry sorry
@[simp] theorem of_apply {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] (a : multiplicative G) : coe_fn (of k G) a = finsupp.single (coe_fn multiplicative.to_add a) 1 :=
rfl
theorem of_injective {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] [nontrivial k] : function.injective ⇑(of k G) := sorry
theorem mul_single_apply_aux {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] (f : add_monoid_algebra k G) (r : k) (x : G) (y : G) (z : G) (H : ∀ (a : G), a + x = z ↔ a = y) : coe_fn (f * finsupp.single x r) z = coe_fn f y * r :=
monoid_algebra.mul_single_apply_aux f H
theorem mul_single_zero_apply {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] (f : add_monoid_algebra k G) (r : k) (x : G) : coe_fn (f * finsupp.single 0 r) x = coe_fn f x * r :=
mul_single_apply_aux f r 0 x x
fun (a : G) => eq.mpr (id (Eq._oldrec (Eq.refl (a + 0 = x ↔ a = x)) (add_zero a))) (iff.refl (a = x))
theorem single_mul_apply_aux {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] (f : add_monoid_algebra k G) (r : k) (x : G) (y : G) (z : G) (H : ∀ (a : G), x + a = y ↔ a = z) : coe_fn (finsupp.single x r * f) y = r * coe_fn f z :=
monoid_algebra.single_mul_apply_aux f H
theorem single_zero_mul_apply {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] (f : add_monoid_algebra k G) (r : k) (x : G) : coe_fn (finsupp.single 0 r * f) x = r * coe_fn f x :=
single_mul_apply_aux f r 0 x x
fun (a : G) => eq.mpr (id (Eq._oldrec (Eq.refl (0 + a = x ↔ a = x)) (zero_add a))) (iff.refl (a = x))
theorem lift_nc_smul {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] {R : Type u_1} [semiring R] (f : k →+* R) (g : multiplicative G →* R) (c : k) (φ : monoid_algebra k G) : coe_fn (lift_nc (↑f) g) (c • φ) = coe_fn f c * coe_fn (lift_nc (↑f) g) φ :=
monoid_algebra.lift_nc_smul f g c φ
end add_monoid_algebra
/-!
#### Conversions between `add_monoid_algebra` and `monoid_algebra`
While we were not able to define `add_monoid_algebra k G = monoid_algebra k (multiplicative G)` due
to definitional inconveniences, we can still show the types are isomorphic.
-/
/-- The equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of
`multiplicative` -/
protected def add_monoid_algebra.to_multiplicative (k : Type u₁) (G : Type u₂) [semiring k] [add_monoid G] : add_monoid_algebra k G ≃+* monoid_algebra k (multiplicative G) :=
ring_equiv.mk (add_equiv.to_fun (finsupp.dom_congr multiplicative.of_add))
(add_equiv.inv_fun (finsupp.dom_congr multiplicative.of_add)) sorry sorry sorry sorry
/-- The equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of `additive` -/
protected def monoid_algebra.to_additive (k : Type u₁) (G : Type u₂) [semiring k] [monoid G] : monoid_algebra k G ≃+* add_monoid_algebra k (additive G) :=
ring_equiv.mk (add_equiv.to_fun (finsupp.dom_congr additive.of_mul))
(add_equiv.inv_fun (finsupp.dom_congr additive.of_mul)) sorry sorry sorry sorry
namespace add_monoid_algebra
/-! #### Algebra structure -/
/-- `finsupp.single 0` as a `ring_hom` -/
@[simp] theorem single_zero_ring_hom_apply {k : Type u₁} {G : Type u₂} [semiring k] [add_monoid G] : ∀ (ᾰ : k), coe_fn single_zero_ring_hom ᾰ = add_monoid_hom.to_fun (finsupp.single_add_hom 0) ᾰ :=
fun (ᾰ : k) => Eq.refl (coe_fn single_zero_ring_hom ᾰ)
/-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1`
and `single 0 b`, then they are equal. -/
theorem ring_hom_ext {k : Type u₁} {G : Type u₂} {R : Type u_1} [semiring k] [add_monoid G] [semiring R] {f : add_monoid_algebra k G →+* R} {g : add_monoid_algebra k G →+* R} (h₀ : ∀ (b : k), coe_fn f (finsupp.single 0 b) = coe_fn g (finsupp.single 0 b)) (h_of : ∀ (a : G), coe_fn f (finsupp.single a 1) = coe_fn g (finsupp.single a 1)) : f = g :=
monoid_algebra.ring_hom_ext h₀ h_of
/-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1`
and `single 0 b`, then they are equal.
See note [partially-applied ext lemmas]. -/
theorem ring_hom_ext' {k : Type u₁} {G : Type u₂} {R : Type u_1} [semiring k] [add_monoid G] [semiring R] {f : add_monoid_algebra k G →+* R} {g : add_monoid_algebra k G →+* R} (h₁ : ring_hom.comp f single_zero_ring_hom = ring_hom.comp g single_zero_ring_hom) (h_of : monoid_hom.comp (↑f) (of k G) = monoid_hom.comp (↑g) (of k G)) : f = g :=
ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of)
/--
The instance `algebra R (add_monoid_algebra k G)` whenever we have `algebra R k`.
In particular this provides the instance `algebra k (add_monoid_algebra k G)`.
-/
protected instance algebra {k : Type u₁} {G : Type u₂} {R : Type u_1} [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : algebra R (add_monoid_algebra k G) :=
algebra.mk
(ring_hom.mk (ring_hom.to_fun (ring_hom.comp single_zero_ring_hom (algebra_map R k))) sorry sorry sorry sorry) sorry
sorry
/-- `finsupp.single 0` as a `alg_hom` -/
def single_zero_alg_hom {k : Type u₁} {G : Type u₂} {R : Type u_1} [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : alg_hom R k (add_monoid_algebra k G) :=
alg_hom.mk (ring_hom.to_fun single_zero_ring_hom) sorry sorry sorry sorry sorry
@[simp] theorem coe_algebra_map {k : Type u₁} {G : Type u₂} {R : Type u_1} [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : ⇑(algebra_map R (add_monoid_algebra k G)) = finsupp.single 0 ∘ ⇑(algebra_map R k) :=
rfl
/-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/
def lift_nc_alg_hom {k : Type u₁} {G : Type u₂} [comm_semiring k] [add_monoid G] {A : Type u₃} [semiring A] [algebra k A] {B : Type u_1} [semiring B] [algebra k B] (f : alg_hom k A B) (g : multiplicative G →* B) (h_comm : ∀ (x : A) (y : multiplicative G), commute (coe_fn f x) (coe_fn g y)) : alg_hom k (add_monoid_algebra A G) B :=
alg_hom.mk ⇑(lift_nc_ring_hom (↑f) g h_comm) sorry sorry sorry sorry sorry
/-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its
values on the functions `single a 1`. -/
theorem alg_hom_ext {k : Type u₁} {G : Type u₂} [comm_semiring k] [add_monoid G] {A : Type u₃} [semiring A] [algebra k A] {φ₁ : alg_hom k (add_monoid_algebra k G) A} {φ₂ : alg_hom k (add_monoid_algebra k G) A} (h : ∀ (x : G), coe_fn φ₁ (finsupp.single x 1) = coe_fn φ₂ (finsupp.single x 1)) : φ₁ = φ₂ :=
monoid_algebra.alg_hom_ext h
/-- See note [partially-applied ext lemmas]. -/
theorem alg_hom_ext' {k : Type u₁} {G : Type u₂} [comm_semiring k] [add_monoid G] {A : Type u₃} [semiring A] [algebra k A] {φ₁ : alg_hom k (add_monoid_algebra k G) A} {φ₂ : alg_hom k (add_monoid_algebra k G) A} (h : monoid_hom.comp (↑φ₁) (of k G) = monoid_hom.comp (↑φ₂) (of k G)) : φ₁ = φ₂ :=
alg_hom_ext (monoid_hom.congr_fun h)
/-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism
`monoid_algebra k G →ₐ[k] A`. -/
def lift (k : Type u₁) (G : Type u₂) [comm_semiring k] [add_monoid G] (A : Type u₃) [semiring A] [algebra k A] : (multiplicative G →* A) ≃ alg_hom k (add_monoid_algebra k G) A :=
equiv.mk
(fun (F : multiplicative G →* A) =>
alg_hom.mk ⇑(lift_nc_alg_hom (algebra.of_id k A) F sorry) sorry sorry sorry sorry sorry)
(fun (f : alg_hom k (add_monoid_algebra k G) A) => monoid_hom.comp (↑f) (of k G)) sorry sorry
theorem lift_apply' {k : Type u₁} {G : Type u₂} [comm_semiring k] [add_monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : multiplicative G →* A) (f : monoid_algebra k G) : coe_fn (coe_fn (lift k G A) F) f =
finsupp.sum f fun (a : G) (b : k) => coe_fn (algebra_map k A) b * coe_fn F (coe_fn multiplicative.of_add a) :=
rfl
theorem lift_apply {k : Type u₁} {G : Type u₂} [comm_semiring k] [add_monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : multiplicative G →* A) (f : monoid_algebra k G) : coe_fn (coe_fn (lift k G A) F) f = finsupp.sum f fun (a : G) (b : k) => b • coe_fn F (coe_fn multiplicative.of_add a) := sorry
theorem lift_def {k : Type u₁} {G : Type u₂} [comm_semiring k] [add_monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : multiplicative G →* A) : ⇑(coe_fn (lift k G A) F) = ⇑(lift_nc (↑(algebra_map k A)) F) :=
rfl
@[simp] theorem lift_symm_apply {k : Type u₁} {G : Type u₂} [comm_semiring k] [add_monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : alg_hom k (add_monoid_algebra k G) A) (x : multiplicative G) : coe_fn (coe_fn (equiv.symm (lift k G A)) F) x = coe_fn F (finsupp.single (coe_fn multiplicative.to_add x) 1) :=
rfl
theorem lift_of {k : Type u₁} {G : Type u₂} [comm_semiring k] [add_monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : multiplicative G →* A) (x : multiplicative G) : coe_fn (coe_fn (lift k G A) F) (coe_fn (of k G) x) = coe_fn F x := sorry
@[simp] theorem lift_single {k : Type u₁} {G : Type u₂} [comm_semiring k] [add_monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : multiplicative G →* A) (a : G) (b : k) : coe_fn (coe_fn (lift k G A) F) (finsupp.single a b) = b • coe_fn F (coe_fn multiplicative.of_add a) := sorry
theorem lift_unique' {k : Type u₁} {G : Type u₂} [comm_semiring k] [add_monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : alg_hom k (add_monoid_algebra k G) A) : F = coe_fn (lift k G A) (monoid_hom.comp (↑F) (of k G)) :=
Eq.symm (equiv.apply_symm_apply (lift k G A) F)
/-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by
its values on `F (single a 1)`. -/
theorem lift_unique {k : Type u₁} {G : Type u₂} [comm_semiring k] [add_monoid G] {A : Type u₃} [semiring A] [algebra k A] (F : alg_hom k (add_monoid_algebra k G) A) (f : monoid_algebra k G) : coe_fn F f = finsupp.sum f fun (a : G) (b : k) => b • coe_fn F (finsupp.single a 1) := sorry
theorem alg_hom_ext_iff {k : Type u₁} {G : Type u₂} [comm_semiring k] [add_monoid G] {A : Type u₃} [semiring A] [algebra k A] {φ₁ : alg_hom k (add_monoid_algebra k G) A} {φ₂ : alg_hom k (add_monoid_algebra k G) A} : (∀ (x : G), coe_fn φ₁ (finsupp.single x 1) = coe_fn φ₂ (finsupp.single x 1)) ↔ φ₁ = φ₂ :=
{ mp := fun (h : ∀ (x : G), coe_fn φ₁ (finsupp.single x 1) = coe_fn φ₂ (finsupp.single x 1)) => alg_hom_ext h,
mpr := fun (ᾰ : φ₁ = φ₂) (x : G) => Eq._oldrec (Eq.refl (coe_fn φ₁ (finsupp.single x 1))) ᾰ }
theorem prod_single {k : Type u₁} {G : Type u₂} {ι : Type ui} [comm_semiring k] [add_comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (finset.prod s fun (i : ι) => finsupp.single (a i) (b i)) =
finsupp.single (finset.sum s fun (i : ι) => a i) (finset.prod s fun (i : ι) => b i) := sorry
|
0e3ceba81b10ca3c5df4967c74949c8f409a2e47
|
2a70b774d16dbdf5a533432ee0ebab6838df0948
|
/_target/deps/mathlib/src/analysis/special_functions/trigonometric.lean
|
dc1d16dcd4e8b53def750c0c7951cbe99d9224f3
|
[
"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
| 123,837
|
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.exp_log
import data.set.intervals.infinite
import algebra.quadratic_discriminant
import ring_theory.polynomial.chebyshev.defs
/-!
# Trigonometric functions
## Main definitions
This file contains the following definitions:
* π, arcsin, arccos, arctan
* argument of a complex number
* logarithm on complex numbers
## Main statements
Many basic inequalities on trigonometric functions are established.
The continuity and differentiability of the usual trigonometric functions are proved, and their
derivatives are computed.
* `polynomial.chebyshev₁_complex_cos`: the `n`-th Chebyshev polynomial evaluates on `complex.cos θ`
to the value `n * complex.cos θ`.
## Tags
log, sin, cos, tan, arcsin, arccos, arctan, angle, argument
-/
noncomputable theory
open_locale classical topological_space filter
open set filter
namespace complex
/-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/
lemma has_deriv_at_sin (x : ℂ) : has_deriv_at sin (cos x) x :=
begin
simp only [cos, div_eq_mul_inv],
convert ((((has_deriv_at_id x).neg.mul_const I).cexp.sub
((has_deriv_at_id x).mul_const I).cexp).mul_const I).mul_const (2:ℂ)⁻¹,
simp only [function.comp, id],
rw [sub_mul, mul_assoc, mul_assoc, I_mul_I, neg_one_mul, neg_neg, mul_one, one_mul, mul_assoc,
I_mul_I, mul_neg_one, sub_neg_eq_add, add_comm]
end
lemma times_cont_diff_sin {n} : times_cont_diff ℂ n sin :=
(((times_cont_diff_neg.mul times_cont_diff_const).cexp.sub
(times_cont_diff_id.mul times_cont_diff_const).cexp).mul times_cont_diff_const).div_const
lemma differentiable_sin : differentiable ℂ sin :=
λx, (has_deriv_at_sin x).differentiable_at
lemma differentiable_at_sin {x : ℂ} : differentiable_at ℂ sin x :=
differentiable_sin x
@[simp] lemma deriv_sin : deriv sin = cos :=
funext $ λ x, (has_deriv_at_sin x).deriv
lemma continuous_sin : continuous sin :=
differentiable_sin.continuous
lemma continuous_on_sin {s : set ℂ} : continuous_on sin s := continuous_sin.continuous_on
lemma measurable_sin : measurable sin := continuous_sin.measurable
/-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/
lemma has_deriv_at_cos (x : ℂ) : has_deriv_at cos (-sin x) x :=
begin
simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul],
convert (((has_deriv_at_id x).mul_const I).cexp.add
((has_deriv_at_id x).neg.mul_const I).cexp).mul_const (2:ℂ)⁻¹,
simp only [function.comp, id],
ring
end
lemma times_cont_diff_cos {n} : times_cont_diff ℂ n cos :=
((times_cont_diff_id.mul times_cont_diff_const).cexp.add
(times_cont_diff_neg.mul times_cont_diff_const).cexp).div_const
lemma differentiable_cos : differentiable ℂ cos :=
λx, (has_deriv_at_cos x).differentiable_at
lemma differentiable_at_cos {x : ℂ} : differentiable_at ℂ cos x :=
differentiable_cos x
lemma deriv_cos {x : ℂ} : deriv cos x = -sin x :=
(has_deriv_at_cos x).deriv
@[simp] lemma deriv_cos' : deriv cos = (λ x, -sin x) :=
funext $ λ x, deriv_cos
lemma continuous_cos : continuous cos :=
differentiable_cos.continuous
lemma continuous_on_cos {s : set ℂ} : continuous_on cos s := continuous_cos.continuous_on
lemma measurable_cos : measurable cos := continuous_cos.measurable
/-- The complex hyperbolic sine function is everywhere differentiable, with the derivative
`cosh x`. -/
lemma has_deriv_at_sinh (x : ℂ) : has_deriv_at sinh (cosh x) x :=
begin
simp only [cosh, div_eq_mul_inv],
convert ((has_deriv_at_exp x).sub (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹,
rw [id, mul_neg_one, sub_eq_add_neg, neg_neg]
end
lemma times_cont_diff_sinh {n} : times_cont_diff ℂ n sinh :=
(times_cont_diff_exp.sub times_cont_diff_neg.cexp).div_const
lemma differentiable_sinh : differentiable ℂ sinh :=
λx, (has_deriv_at_sinh x).differentiable_at
lemma differentiable_at_sinh {x : ℂ} : differentiable_at ℂ sinh x :=
differentiable_sinh x
@[simp] lemma deriv_sinh : deriv sinh = cosh :=
funext $ λ x, (has_deriv_at_sinh x).deriv
lemma continuous_sinh : continuous sinh :=
differentiable_sinh.continuous
lemma measurable_sinh : measurable sinh := continuous_sinh.measurable
/-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `sinh x`. -/
lemma has_deriv_at_cosh (x : ℂ) : has_deriv_at cosh (sinh x) x :=
begin
simp only [sinh, div_eq_mul_inv],
convert ((has_deriv_at_exp x).add (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹,
rw [id, mul_neg_one, sub_eq_add_neg]
end
lemma times_cont_diff_cosh {n} : times_cont_diff ℂ n cosh :=
(times_cont_diff_exp.add times_cont_diff_neg.cexp).div_const
lemma differentiable_cosh : differentiable ℂ cosh :=
λx, (has_deriv_at_cosh x).differentiable_at
lemma differentiable_at_cosh {x : ℂ} : differentiable_at ℂ cos x :=
differentiable_cos x
@[simp] lemma deriv_cosh : deriv cosh = sinh :=
funext $ λ x, (has_deriv_at_cosh x).deriv
lemma continuous_cosh : continuous cosh :=
differentiable_cosh.continuous
lemma measurable_cosh : measurable cosh := continuous_cosh.measurable
end complex
section
/-! ### Simp lemmas for derivatives of `λ x, complex.cos (f x)` etc., `f : ℂ → ℂ` -/
variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ}
/-! #### `complex.cos` -/
lemma measurable.ccos {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) :
measurable (λ x, complex.cos (f x)) :=
complex.measurable_cos.comp hf
lemma has_deriv_at.ccos (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') x :=
(complex.has_deriv_at_cos (f x)).comp x hf
lemma has_deriv_within_at.ccos (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') s x :=
(complex.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_ccos (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
deriv_within (λx, complex.cos (f x)) s x = - complex.sin (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.ccos.deriv_within hxs
@[simp] lemma deriv_ccos (hc : differentiable_at ℂ f x) :
deriv (λx, complex.cos (f x)) x = - complex.sin (f x) * (deriv f x) :=
hc.has_deriv_at.ccos.deriv
/-! #### `complex.sin` -/
lemma measurable.csin {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) :
measurable (λ x, complex.sin (f x)) :=
complex.measurable_sin.comp hf
lemma has_deriv_at.csin (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') x :=
(complex.has_deriv_at_sin (f x)).comp x hf
lemma has_deriv_within_at.csin (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') s x :=
(complex.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_csin (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
deriv_within (λx, complex.sin (f x)) s x = complex.cos (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.csin.deriv_within hxs
@[simp] lemma deriv_csin (hc : differentiable_at ℂ f x) :
deriv (λx, complex.sin (f x)) x = complex.cos (f x) * (deriv f x) :=
hc.has_deriv_at.csin.deriv
/-! #### `complex.cosh` -/
lemma measurable.ccosh {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) :
measurable (λ x, complex.cosh (f x)) :=
complex.measurable_cosh.comp hf
lemma has_deriv_at.ccosh (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') x :=
(complex.has_deriv_at_cosh (f x)).comp x hf
lemma has_deriv_within_at.ccosh (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') s x :=
(complex.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_ccosh (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
deriv_within (λx, complex.cosh (f x)) s x = complex.sinh (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.ccosh.deriv_within hxs
@[simp] lemma deriv_ccosh (hc : differentiable_at ℂ f x) :
deriv (λx, complex.cosh (f x)) x = complex.sinh (f x) * (deriv f x) :=
hc.has_deriv_at.ccosh.deriv
/-! #### `complex.sinh` -/
lemma measurable.csinh {α : Type*} [measurable_space α] {f : α → ℂ} (hf : measurable f) :
measurable (λ x, complex.sinh (f x)) :=
complex.measurable_sinh.comp hf
lemma has_deriv_at.csinh (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') x :=
(complex.has_deriv_at_sinh (f x)).comp x hf
lemma has_deriv_within_at.csinh (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') s x :=
(complex.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_csinh (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
deriv_within (λx, complex.sinh (f x)) s x = complex.cosh (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.csinh.deriv_within hxs
@[simp] lemma deriv_csinh (hc : differentiable_at ℂ f x) :
deriv (λx, complex.sinh (f x)) x = complex.cosh (f x) * (deriv f x) :=
hc.has_deriv_at.csinh.deriv
end
section
/-! ### Simp lemmas for derivatives of `λ x, complex.cos (f x)` etc., `f : E → ℂ` -/
variables {E : Type*} [normed_group E] [normed_space ℂ E] {f : E → ℂ} {f' : E →L[ℂ] ℂ}
{x : E} {s : set E}
/-! #### `complex.cos` -/
lemma has_fderiv_at.ccos (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, complex.cos (f x)) (- complex.sin (f x) • f') x :=
(complex.has_deriv_at_cos (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.ccos (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, complex.cos (f x)) (- complex.sin (f x) • f') s x :=
(complex.has_deriv_at_cos (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.ccos (hf : differentiable_within_at ℂ f s x) :
differentiable_within_at ℂ (λ x, complex.cos (f x)) s x :=
hf.has_fderiv_within_at.ccos.differentiable_within_at
@[simp] lemma differentiable_at.ccos (hc : differentiable_at ℂ f x) :
differentiable_at ℂ (λx, complex.cos (f x)) x :=
hc.has_fderiv_at.ccos.differentiable_at
lemma differentiable_on.ccos (hc : differentiable_on ℂ f s) :
differentiable_on ℂ (λx, complex.cos (f x)) s :=
λx h, (hc x h).ccos
@[simp] lemma differentiable.ccos (hc : differentiable ℂ f) :
differentiable ℂ (λx, complex.cos (f x)) :=
λx, (hc x).ccos
lemma fderiv_within_ccos (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
fderiv_within ℂ (λx, complex.cos (f x)) s x = - complex.sin (f x) • (fderiv_within ℂ f s x) :=
hf.has_fderiv_within_at.ccos.fderiv_within hxs
@[simp] lemma fderiv_ccos (hc : differentiable_at ℂ f x) :
fderiv ℂ (λx, complex.cos (f x)) x = - complex.sin (f x) • (fderiv ℂ f x) :=
hc.has_fderiv_at.ccos.fderiv
lemma times_cont_diff.ccos {n} (h : times_cont_diff ℂ n f) :
times_cont_diff ℂ n (λ x, complex.cos (f x)) :=
complex.times_cont_diff_cos.comp h
lemma times_cont_diff_at.ccos {n} (hf : times_cont_diff_at ℂ n f x) :
times_cont_diff_at ℂ n (λ x, complex.cos (f x)) x :=
complex.times_cont_diff_cos.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.ccos {n} (hf : times_cont_diff_on ℂ n f s) :
times_cont_diff_on ℂ n (λ x, complex.cos (f x)) s :=
complex.times_cont_diff_cos.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.ccos {n} (hf : times_cont_diff_within_at ℂ n f s x) :
times_cont_diff_within_at ℂ n (λ x, complex.cos (f x)) s x :=
complex.times_cont_diff_cos.times_cont_diff_at.comp_times_cont_diff_within_at x hf
/-! #### `complex.sin` -/
lemma has_fderiv_at.csin (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, complex.sin (f x)) (complex.cos (f x) • f') x :=
(complex.has_deriv_at_sin (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.csin (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, complex.sin (f x)) (complex.cos (f x) • f') s x :=
(complex.has_deriv_at_sin (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.csin (hf : differentiable_within_at ℂ f s x) :
differentiable_within_at ℂ (λ x, complex.sin (f x)) s x :=
hf.has_fderiv_within_at.csin.differentiable_within_at
@[simp] lemma differentiable_at.csin (hc : differentiable_at ℂ f x) :
differentiable_at ℂ (λx, complex.sin (f x)) x :=
hc.has_fderiv_at.csin.differentiable_at
lemma differentiable_on.csin (hc : differentiable_on ℂ f s) :
differentiable_on ℂ (λx, complex.sin (f x)) s :=
λx h, (hc x h).csin
@[simp] lemma differentiable.csin (hc : differentiable ℂ f) :
differentiable ℂ (λx, complex.sin (f x)) :=
λx, (hc x).csin
lemma fderiv_within_csin (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
fderiv_within ℂ (λx, complex.sin (f x)) s x = complex.cos (f x) • (fderiv_within ℂ f s x) :=
hf.has_fderiv_within_at.csin.fderiv_within hxs
@[simp] lemma fderiv_csin (hc : differentiable_at ℂ f x) :
fderiv ℂ (λx, complex.sin (f x)) x = complex.cos (f x) • (fderiv ℂ f x) :=
hc.has_fderiv_at.csin.fderiv
lemma times_cont_diff.csin {n} (h : times_cont_diff ℂ n f) :
times_cont_diff ℂ n (λ x, complex.sin (f x)) :=
complex.times_cont_diff_sin.comp h
lemma times_cont_diff_at.csin {n} (hf : times_cont_diff_at ℂ n f x) :
times_cont_diff_at ℂ n (λ x, complex.sin (f x)) x :=
complex.times_cont_diff_sin.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.csin {n} (hf : times_cont_diff_on ℂ n f s) :
times_cont_diff_on ℂ n (λ x, complex.sin (f x)) s :=
complex.times_cont_diff_sin.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.csin {n} (hf : times_cont_diff_within_at ℂ n f s x) :
times_cont_diff_within_at ℂ n (λ x, complex.sin (f x)) s x :=
complex.times_cont_diff_sin.times_cont_diff_at.comp_times_cont_diff_within_at x hf
/-! #### `complex.cosh` -/
lemma has_fderiv_at.ccosh (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) • f') x :=
(complex.has_deriv_at_cosh (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.ccosh (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, complex.cosh (f x)) (complex.sinh (f x) • f') s x :=
(complex.has_deriv_at_cosh (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.ccosh (hf : differentiable_within_at ℂ f s x) :
differentiable_within_at ℂ (λ x, complex.cosh (f x)) s x :=
hf.has_fderiv_within_at.ccosh.differentiable_within_at
@[simp] lemma differentiable_at.ccosh (hc : differentiable_at ℂ f x) :
differentiable_at ℂ (λx, complex.cosh (f x)) x :=
hc.has_fderiv_at.ccosh.differentiable_at
lemma differentiable_on.ccosh (hc : differentiable_on ℂ f s) :
differentiable_on ℂ (λx, complex.cosh (f x)) s :=
λx h, (hc x h).ccosh
@[simp] lemma differentiable.ccosh (hc : differentiable ℂ f) :
differentiable ℂ (λx, complex.cosh (f x)) :=
λx, (hc x).ccosh
lemma fderiv_within_ccosh (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
fderiv_within ℂ (λx, complex.cosh (f x)) s x = complex.sinh (f x) • (fderiv_within ℂ f s x) :=
hf.has_fderiv_within_at.ccosh.fderiv_within hxs
@[simp] lemma fderiv_ccosh (hc : differentiable_at ℂ f x) :
fderiv ℂ (λx, complex.cosh (f x)) x = complex.sinh (f x) • (fderiv ℂ f x) :=
hc.has_fderiv_at.ccosh.fderiv
lemma times_cont_diff.ccosh {n} (h : times_cont_diff ℂ n f) :
times_cont_diff ℂ n (λ x, complex.cosh (f x)) :=
complex.times_cont_diff_cosh.comp h
lemma times_cont_diff_at.ccosh {n} (hf : times_cont_diff_at ℂ n f x) :
times_cont_diff_at ℂ n (λ x, complex.cosh (f x)) x :=
complex.times_cont_diff_cosh.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.ccosh {n} (hf : times_cont_diff_on ℂ n f s) :
times_cont_diff_on ℂ n (λ x, complex.cosh (f x)) s :=
complex.times_cont_diff_cosh.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.ccosh {n} (hf : times_cont_diff_within_at ℂ n f s x) :
times_cont_diff_within_at ℂ n (λ x, complex.cosh (f x)) s x :=
complex.times_cont_diff_cosh.times_cont_diff_at.comp_times_cont_diff_within_at x hf
/-! #### `complex.sinh` -/
lemma has_fderiv_at.csinh (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) • f') x :=
(complex.has_deriv_at_sinh (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.csinh (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, complex.sinh (f x)) (complex.cosh (f x) • f') s x :=
(complex.has_deriv_at_sinh (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.csinh (hf : differentiable_within_at ℂ f s x) :
differentiable_within_at ℂ (λ x, complex.sinh (f x)) s x :=
hf.has_fderiv_within_at.csinh.differentiable_within_at
@[simp] lemma differentiable_at.csinh (hc : differentiable_at ℂ f x) :
differentiable_at ℂ (λx, complex.sinh (f x)) x :=
hc.has_fderiv_at.csinh.differentiable_at
lemma differentiable_on.csinh (hc : differentiable_on ℂ f s) :
differentiable_on ℂ (λx, complex.sinh (f x)) s :=
λx h, (hc x h).csinh
@[simp] lemma differentiable.csinh (hc : differentiable ℂ f) :
differentiable ℂ (λx, complex.sinh (f x)) :=
λx, (hc x).csinh
lemma fderiv_within_csinh (hf : differentiable_within_at ℂ f s x)
(hxs : unique_diff_within_at ℂ s x) :
fderiv_within ℂ (λx, complex.sinh (f x)) s x = complex.cosh (f x) • (fderiv_within ℂ f s x) :=
hf.has_fderiv_within_at.csinh.fderiv_within hxs
@[simp] lemma fderiv_csinh (hc : differentiable_at ℂ f x) :
fderiv ℂ (λx, complex.sinh (f x)) x = complex.cosh (f x) • (fderiv ℂ f x) :=
hc.has_fderiv_at.csinh.fderiv
lemma times_cont_diff.csinh {n} (h : times_cont_diff ℂ n f) :
times_cont_diff ℂ n (λ x, complex.sinh (f x)) :=
complex.times_cont_diff_sinh.comp h
lemma times_cont_diff_at.csinh {n} (hf : times_cont_diff_at ℂ n f x) :
times_cont_diff_at ℂ n (λ x, complex.sinh (f x)) x :=
complex.times_cont_diff_sinh.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.csinh {n} (hf : times_cont_diff_on ℂ n f s) :
times_cont_diff_on ℂ n (λ x, complex.sinh (f x)) s :=
complex.times_cont_diff_sinh.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.csinh {n} (hf : times_cont_diff_within_at ℂ n f s x) :
times_cont_diff_within_at ℂ n (λ x, complex.sinh (f x)) s x :=
complex.times_cont_diff_sinh.times_cont_diff_at.comp_times_cont_diff_within_at x hf
end
namespace real
variables {x y z : ℝ}
lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x :=
(complex.has_deriv_at_sin x).real_of_complex
lemma times_cont_diff_sin {n} : times_cont_diff ℝ n sin :=
complex.times_cont_diff_sin.real_of_complex
lemma differentiable_sin : differentiable ℝ sin :=
λx, (has_deriv_at_sin x).differentiable_at
lemma differentiable_at_sin : differentiable_at ℝ sin x :=
differentiable_sin x
@[simp] lemma deriv_sin : deriv sin = cos :=
funext $ λ x, (has_deriv_at_sin x).deriv
lemma continuous_sin : continuous sin :=
differentiable_sin.continuous
lemma measurable_sin : measurable sin := continuous_sin.measurable
lemma has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x :=
(complex.has_deriv_at_cos x).real_of_complex
lemma times_cont_diff_cos {n} : times_cont_diff ℝ n cos :=
complex.times_cont_diff_cos.real_of_complex
lemma differentiable_cos : differentiable ℝ cos :=
λx, (has_deriv_at_cos x).differentiable_at
lemma differentiable_at_cos : differentiable_at ℝ cos x :=
differentiable_cos x
lemma deriv_cos : deriv cos x = - sin x :=
(has_deriv_at_cos x).deriv
@[simp] lemma deriv_cos' : deriv cos = (λ x, - sin x) :=
funext $ λ _, deriv_cos
lemma continuous_cos : continuous cos :=
differentiable_cos.continuous
lemma continuous_on_cos {s} : continuous_on cos s := continuous_cos.continuous_on
lemma measurable_cos : measurable cos := continuous_cos.measurable
lemma has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x :=
(complex.has_deriv_at_sinh x).real_of_complex
lemma times_cont_diff_sinh {n} : times_cont_diff ℝ n sinh :=
complex.times_cont_diff_sinh.real_of_complex
lemma differentiable_sinh : differentiable ℝ sinh :=
λx, (has_deriv_at_sinh x).differentiable_at
lemma differentiable_at_sinh : differentiable_at ℝ sinh x :=
differentiable_sinh x
@[simp] lemma deriv_sinh : deriv sinh = cosh :=
funext $ λ x, (has_deriv_at_sinh x).deriv
lemma continuous_sinh : continuous sinh :=
differentiable_sinh.continuous
lemma measurable_sinh : measurable sinh := continuous_sinh.measurable
lemma has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x :=
(complex.has_deriv_at_cosh x).real_of_complex
lemma times_cont_diff_cosh {n} : times_cont_diff ℝ n cosh :=
complex.times_cont_diff_cosh.real_of_complex
lemma differentiable_cosh : differentiable ℝ cosh :=
λx, (has_deriv_at_cosh x).differentiable_at
lemma differentiable_at_cosh : differentiable_at ℝ cosh x :=
differentiable_cosh x
@[simp] lemma deriv_cosh : deriv cosh = sinh :=
funext $ λ x, (has_deriv_at_cosh x).deriv
lemma continuous_cosh : continuous cosh :=
differentiable_cosh.continuous
lemma measurable_cosh : measurable cosh := continuous_cosh.measurable
/-- `sinh` is strictly monotone. -/
lemma sinh_strict_mono : strict_mono sinh :=
strict_mono_of_deriv_pos differentiable_sinh (by { rw [real.deriv_sinh], exact cosh_pos })
end real
section
/-! ### Simp lemmas for derivatives of `λ x, real.cos (f x)` etc., `f : ℝ → ℝ` -/
variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ}
/-! #### `real.cos` -/
lemma measurable.cos {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) :
measurable (λ x, real.cos (f x)) :=
real.measurable_cos.comp hf
lemma has_deriv_at.cos (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, real.cos (f x)) (- real.sin (f x) * f') x :=
(real.has_deriv_at_cos (f x)).comp x hf
lemma has_deriv_within_at.cos (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, real.cos (f x)) (- real.sin (f x) * f') s x :=
(real.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_cos (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, real.cos (f x)) s x = - real.sin (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.cos.deriv_within hxs
@[simp] lemma deriv_cos (hc : differentiable_at ℝ f x) :
deriv (λx, real.cos (f x)) x = - real.sin (f x) * (deriv f x) :=
hc.has_deriv_at.cos.deriv
/-! #### `real.sin` -/
lemma measurable.sin {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) :
measurable (λ x, real.sin (f x)) :=
real.measurable_sin.comp hf
lemma has_deriv_at.sin (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, real.sin (f x)) (real.cos (f x) * f') x :=
(real.has_deriv_at_sin (f x)).comp x hf
lemma has_deriv_within_at.sin (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, real.sin (f x)) (real.cos (f x) * f') s x :=
(real.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_sin (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, real.sin (f x)) s x = real.cos (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.sin.deriv_within hxs
@[simp] lemma deriv_sin (hc : differentiable_at ℝ f x) :
deriv (λx, real.sin (f x)) x = real.cos (f x) * (deriv f x) :=
hc.has_deriv_at.sin.deriv
/-! #### `real.cosh` -/
lemma measurable.cosh {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) :
measurable (λ x, real.cosh (f x)) :=
real.measurable_cosh.comp hf
lemma has_deriv_at.cosh (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') x :=
(real.has_deriv_at_cosh (f x)).comp x hf
lemma has_deriv_within_at.cosh (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') s x :=
(real.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_cosh (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, real.cosh (f x)) s x = real.sinh (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.cosh.deriv_within hxs
@[simp] lemma deriv_cosh (hc : differentiable_at ℝ f x) :
deriv (λx, real.cosh (f x)) x = real.sinh (f x) * (deriv f x) :=
hc.has_deriv_at.cosh.deriv
/-! #### `real.sinh` -/
lemma measurable.sinh {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) :
measurable (λ x, real.sinh (f x)) :=
real.measurable_sinh.comp hf
lemma has_deriv_at.sinh (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') x :=
(real.has_deriv_at_sinh (f x)).comp x hf
lemma has_deriv_within_at.sinh (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') s x :=
(real.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_sinh (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
deriv_within (λx, real.sinh (f x)) s x = real.cosh (f x) * (deriv_within f s x) :=
hf.has_deriv_within_at.sinh.deriv_within hxs
@[simp] lemma deriv_sinh (hc : differentiable_at ℝ f x) :
deriv (λx, real.sinh (f x)) x = real.cosh (f x) * (deriv f x) :=
hc.has_deriv_at.sinh.deriv
end
section
/-! ### Simp lemmas for derivatives of `λ x, real.cos (f x)` etc., `f : E → ℝ` -/
variables {E : Type*} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : E →L[ℝ] ℝ}
{x : E} {s : set E}
/-! #### `real.cos` -/
lemma has_fderiv_at.cos (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, real.cos (f x)) (- real.sin (f x) • f') x :=
(real.has_deriv_at_cos (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.cos (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, real.cos (f x)) (- real.sin (f x) • f') s x :=
(real.has_deriv_at_cos (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.cos (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ x, real.cos (f x)) s x :=
hf.has_fderiv_within_at.cos.differentiable_within_at
@[simp] lemma differentiable_at.cos (hc : differentiable_at ℝ f x) :
differentiable_at ℝ (λx, real.cos (f x)) x :=
hc.has_fderiv_at.cos.differentiable_at
lemma differentiable_on.cos (hc : differentiable_on ℝ f s) :
differentiable_on ℝ (λx, real.cos (f x)) s :=
λx h, (hc x h).cos
@[simp] lemma differentiable.cos (hc : differentiable ℝ f) :
differentiable ℝ (λx, real.cos (f x)) :=
λx, (hc x).cos
lemma fderiv_within_cos (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
fderiv_within ℝ (λx, real.cos (f x)) s x = - real.sin (f x) • (fderiv_within ℝ f s x) :=
hf.has_fderiv_within_at.cos.fderiv_within hxs
@[simp] lemma fderiv_cos (hc : differentiable_at ℝ f x) :
fderiv ℝ (λx, real.cos (f x)) x = - real.sin (f x) • (fderiv ℝ f x) :=
hc.has_fderiv_at.cos.fderiv
lemma times_cont_diff.cos {n} (h : times_cont_diff ℝ n f) :
times_cont_diff ℝ n (λ x, real.cos (f x)) :=
real.times_cont_diff_cos.comp h
lemma times_cont_diff_at.cos {n} (hf : times_cont_diff_at ℝ n f x) :
times_cont_diff_at ℝ n (λ x, real.cos (f x)) x :=
real.times_cont_diff_cos.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.cos {n} (hf : times_cont_diff_on ℝ n f s) :
times_cont_diff_on ℝ n (λ x, real.cos (f x)) s :=
real.times_cont_diff_cos.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.cos {n} (hf : times_cont_diff_within_at ℝ n f s x) :
times_cont_diff_within_at ℝ n (λ x, real.cos (f x)) s x :=
real.times_cont_diff_cos.times_cont_diff_at.comp_times_cont_diff_within_at x hf
/-! #### `real.sin` -/
lemma has_fderiv_at.sin (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, real.sin (f x)) (real.cos (f x) • f') x :=
(real.has_deriv_at_sin (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.sin (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, real.sin (f x)) (real.cos (f x) • f') s x :=
(real.has_deriv_at_sin (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.sin (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ x, real.sin (f x)) s x :=
hf.has_fderiv_within_at.sin.differentiable_within_at
@[simp] lemma differentiable_at.sin (hc : differentiable_at ℝ f x) :
differentiable_at ℝ (λx, real.sin (f x)) x :=
hc.has_fderiv_at.sin.differentiable_at
lemma differentiable_on.sin (hc : differentiable_on ℝ f s) :
differentiable_on ℝ (λx, real.sin (f x)) s :=
λx h, (hc x h).sin
@[simp] lemma differentiable.sin (hc : differentiable ℝ f) :
differentiable ℝ (λx, real.sin (f x)) :=
λx, (hc x).sin
lemma fderiv_within_sin (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
fderiv_within ℝ (λx, real.sin (f x)) s x = real.cos (f x) • (fderiv_within ℝ f s x) :=
hf.has_fderiv_within_at.sin.fderiv_within hxs
@[simp] lemma fderiv_sin (hc : differentiable_at ℝ f x) :
fderiv ℝ (λx, real.sin (f x)) x = real.cos (f x) • (fderiv ℝ f x) :=
hc.has_fderiv_at.sin.fderiv
lemma times_cont_diff.sin {n} (h : times_cont_diff ℝ n f) :
times_cont_diff ℝ n (λ x, real.sin (f x)) :=
real.times_cont_diff_sin.comp h
lemma times_cont_diff_at.sin {n} (hf : times_cont_diff_at ℝ n f x) :
times_cont_diff_at ℝ n (λ x, real.sin (f x)) x :=
real.times_cont_diff_sin.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.sin {n} (hf : times_cont_diff_on ℝ n f s) :
times_cont_diff_on ℝ n (λ x, real.sin (f x)) s :=
real.times_cont_diff_sin.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.sin {n} (hf : times_cont_diff_within_at ℝ n f s x) :
times_cont_diff_within_at ℝ n (λ x, real.sin (f x)) s x :=
real.times_cont_diff_sin.times_cont_diff_at.comp_times_cont_diff_within_at x hf
/-! #### `real.cosh` -/
lemma has_fderiv_at.cosh (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, real.cosh (f x)) (real.sinh (f x) • f') x :=
(real.has_deriv_at_cosh (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.cosh (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, real.cosh (f x)) (real.sinh (f x) • f') s x :=
(real.has_deriv_at_cosh (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.cosh (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ x, real.cosh (f x)) s x :=
hf.has_fderiv_within_at.cosh.differentiable_within_at
@[simp] lemma differentiable_at.cosh (hc : differentiable_at ℝ f x) :
differentiable_at ℝ (λx, real.cosh (f x)) x :=
hc.has_fderiv_at.cosh.differentiable_at
lemma differentiable_on.cosh (hc : differentiable_on ℝ f s) :
differentiable_on ℝ (λx, real.cosh (f x)) s :=
λx h, (hc x h).cosh
@[simp] lemma differentiable.cosh (hc : differentiable ℝ f) :
differentiable ℝ (λx, real.cosh (f x)) :=
λx, (hc x).cosh
lemma fderiv_within_cosh (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
fderiv_within ℝ (λx, real.cosh (f x)) s x = real.sinh (f x) • (fderiv_within ℝ f s x) :=
hf.has_fderiv_within_at.cosh.fderiv_within hxs
@[simp] lemma fderiv_cosh (hc : differentiable_at ℝ f x) :
fderiv ℝ (λx, real.cosh (f x)) x = real.sinh (f x) • (fderiv ℝ f x) :=
hc.has_fderiv_at.cosh.fderiv
lemma times_cont_diff.cosh {n} (h : times_cont_diff ℝ n f) :
times_cont_diff ℝ n (λ x, real.cosh (f x)) :=
real.times_cont_diff_cosh.comp h
lemma times_cont_diff_at.cosh {n} (hf : times_cont_diff_at ℝ n f x) :
times_cont_diff_at ℝ n (λ x, real.cosh (f x)) x :=
real.times_cont_diff_cosh.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.cosh {n} (hf : times_cont_diff_on ℝ n f s) :
times_cont_diff_on ℝ n (λ x, real.cosh (f x)) s :=
real.times_cont_diff_cosh.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.cosh {n} (hf : times_cont_diff_within_at ℝ n f s x) :
times_cont_diff_within_at ℝ n (λ x, real.cosh (f x)) s x :=
real.times_cont_diff_cosh.times_cont_diff_at.comp_times_cont_diff_within_at x hf
/-! #### `real.sinh` -/
lemma has_fderiv_at.sinh (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, real.sinh (f x)) (real.cosh (f x) • f') x :=
(real.has_deriv_at_sinh (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.sinh (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, real.sinh (f x)) (real.cosh (f x) • f') s x :=
(real.has_deriv_at_sinh (f x)).comp_has_fderiv_within_at x hf
lemma differentiable_within_at.sinh (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ x, real.sinh (f x)) s x :=
hf.has_fderiv_within_at.sinh.differentiable_within_at
@[simp] lemma differentiable_at.sinh (hc : differentiable_at ℝ f x) :
differentiable_at ℝ (λx, real.sinh (f x)) x :=
hc.has_fderiv_at.sinh.differentiable_at
lemma differentiable_on.sinh (hc : differentiable_on ℝ f s) :
differentiable_on ℝ (λx, real.sinh (f x)) s :=
λx h, (hc x h).sinh
@[simp] lemma differentiable.sinh (hc : differentiable ℝ f) :
differentiable ℝ (λx, real.sinh (f x)) :=
λx, (hc x).sinh
lemma fderiv_within_sinh (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
fderiv_within ℝ (λx, real.sinh (f x)) s x = real.cosh (f x) • (fderiv_within ℝ f s x) :=
hf.has_fderiv_within_at.sinh.fderiv_within hxs
@[simp] lemma fderiv_sinh (hc : differentiable_at ℝ f x) :
fderiv ℝ (λx, real.sinh (f x)) x = real.cosh (f x) • (fderiv ℝ f x) :=
hc.has_fderiv_at.sinh.fderiv
lemma times_cont_diff.sinh {n} (h : times_cont_diff ℝ n f) :
times_cont_diff ℝ n (λ x, real.sinh (f x)) :=
real.times_cont_diff_sinh.comp h
lemma times_cont_diff_at.sinh {n} (hf : times_cont_diff_at ℝ n f x) :
times_cont_diff_at ℝ n (λ x, real.sinh (f x)) x :=
real.times_cont_diff_sinh.times_cont_diff_at.comp x hf
lemma times_cont_diff_on.sinh {n} (hf : times_cont_diff_on ℝ n f s) :
times_cont_diff_on ℝ n (λ x, real.sinh (f x)) s :=
real.times_cont_diff_sinh.comp_times_cont_diff_on hf
lemma times_cont_diff_within_at.sinh {n} (hf : times_cont_diff_within_at ℝ n f s x) :
times_cont_diff_within_at ℝ n (λ x, real.sinh (f x)) s x :=
real.times_cont_diff_sinh.times_cont_diff_at.comp_times_cont_diff_within_at x hf
end
namespace real
lemma exists_cos_eq_zero : 0 ∈ cos '' Icc (1:ℝ) 2 :=
intermediate_value_Icc' (by norm_num) continuous_on_cos
⟨le_of_lt cos_two_neg, le_of_lt cos_one_pos⟩
/-- The number π = 3.14159265... Defined here using choice as twice a zero of cos in [1,2], from
which one can derive all its properties. For explicit bounds on π, see `data.real.pi`. -/
noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero
localized "notation `π` := real.pi" in real
@[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
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.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).1.2
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_ne_zero : π ≠ 0 :=
ne_of_gt pi_pos
lemma pi_div_two_pos : 0 < π / 2 :=
half_pos pi_pos
lemma two_pi_pos : 0 < 2 * π :=
by linarith [pi_pos]
@[simp] lemma sin_pi : sin π = 0 :=
by rw [← mul_div_cancel_left π (@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 π (@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 [sub_eq_add_neg, 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 [sub_eq_add_neg, 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_pos_of_mem_Ioo {x : ℝ} (hx : x ∈ Ioo 0 π) : 0 < sin x :=
sin_pos_of_pos_of_lt_pi hx.1 hx.2
lemma sin_nonneg_of_mem_Icc {x : ℝ} (hx : x ∈ Icc 0 π) : 0 ≤ sin x :=
begin
rw ← closure_Ioo pi_pos at hx,
exact closure_lt_subset_le continuous_const continuous_sin
(closure_mono (λ y, sin_pos_of_mem_Ioo) hx)
end
lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x :=
sin_nonneg_of_mem_Icc ⟨h0x, hxp⟩
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_sq_add_cos_sq (π / 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 [sub_eq_add_neg, sin_add]
lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x :=
by simp [sub_eq_add_neg, 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 [sub_eq_add_neg, 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_mem_Ioo {x : ℝ} (hx : x ∈ Ioo (-(π / 2)) (π / 2)) : 0 < cos x :=
sin_add_pi_div_two x ▸ sin_pos_of_mem_Ioo ⟨by linarith [hx.1], by linarith [hx.2]⟩
lemma cos_nonneg_of_mem_Icc {x : ℝ} (hx : x ∈ Icc (-(π / 2)) (π / 2)) : 0 ≤ cos x :=
sin_add_pi_div_two x ▸ sin_nonneg_of_mem_Icc ⟨by linarith [hx.1], by linarith [hx.2]⟩
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_mem_Ioo ⟨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_mem_Icc ⟨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 [sub_eq_add_neg, sin_add, h, sin_int_mul_pi]))⟩,
λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩
lemma sin_ne_zero_iff {x : ℝ} : sin x ≠ 0 ↔ ∀ n : ℤ, (n : ℝ) * π ≠ x :=
by rw [← not_exists, not_iff_not, sin_eq_zero_iff]
lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 :=
by rw [← mul_self_eq_one_iff, ← sin_sq_add_cos_sq 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,
begin
rcases (cos_eq_one_iff _).1 h with ⟨n, rfl⟩,
rw [mul_lt_iff_lt_one_left two_pi_pos] at hx₂,
rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos] at hx₁,
norm_cast at hx₁ hx₂,
obtain rfl : n = 0, by omega,
simp
end,
λ h, by simp [h]⟩
lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ π / 2) (hxy : x < y) :
cos y < cos x :=
begin
rw [← sub_lt_zero, cos_sub_cos],
have : 0 < sin ((y + x) / 2),
{ refine sin_pos_of_pos_of_lt_pi _ _; linarith },
have : 0 < sin ((y - x) / 2),
{ refine sin_pos_of_pos_of_lt_pi _ _; linarith },
nlinarith,
end
lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (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₁ 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 [pi_pos])
... < cos x : cos_pos_of_mem_Ioo ⟨by linarith, hx⟩)
(λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith [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 strict_mono_decr_on_cos : strict_mono_decr_on cos (Icc 0 π) :=
λ x hx y hy hxy, cos_lt_cos_of_nonneg_of_le_pi hx.1 hy.2 hxy
lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ π) (hxy : x ≤ y) :
cos y ≤ cos x :=
(strict_mono_decr_on_cos.le_iff_le ⟨hx₁.trans hxy, hy₂⟩ ⟨hx₁, hxy.trans hy₂⟩).2 hxy
lemma sin_lt_sin_of_lt_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x)
(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 strict_mono_incr_on_sin : strict_mono_incr_on sin (Icc (-(π / 2)) (π / 2)) :=
λ x hx y hy hxy, sin_lt_sin_of_lt_of_le_pi_div_two hx.1 hy.2 hxy
lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x)
(hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y :=
(strict_mono_incr_on_sin.le_iff_le ⟨hx₁, hxy.trans hy₂⟩ ⟨hx₁.trans hxy, hy₂⟩).2 hxy
lemma inj_on_sin : inj_on sin (Icc (-(π / 2)) (π / 2)) :=
strict_mono_incr_on_sin.inj_on
lemma inj_on_cos : inj_on cos (Icc 0 π) := strict_mono_decr_on_cos.inj_on
lemma surj_on_sin : surj_on sin (Icc (-(π / 2)) (π / 2)) (Icc (-1) 1) :=
by simpa only [sin_neg, sin_pi_div_two]
using intermediate_value_Icc (neg_le_self pi_div_two_pos.le) continuous_sin.continuous_on
lemma surj_on_cos : surj_on cos (Icc 0 π) (Icc (-1) 1) :=
by simpa only [cos_zero, cos_pi]
using intermediate_value_Icc' pi_pos.le continuous_cos.continuous_on
lemma sin_mem_Icc (x : ℝ) : sin x ∈ Icc (-1 : ℝ) 1 := ⟨neg_one_le_sin x, sin_le_one x⟩
lemma cos_mem_Icc (x : ℝ) : cos x ∈ Icc (-1 : ℝ) 1 := ⟨neg_one_le_cos x, cos_le_one x⟩
lemma maps_to_sin (s : set ℝ) : maps_to sin s (Icc (-1 : ℝ) 1) := λ x _, sin_mem_Icc x
lemma maps_to_cos (s : set ℝ) : maps_to cos s (Icc (-1 : ℝ) 1) := λ x _, cos_mem_Icc x
lemma bij_on_sin : bij_on sin (Icc (-(π / 2)) (π / 2)) (Icc (-1) 1) :=
⟨maps_to_sin _, inj_on_sin, surj_on_sin⟩
lemma bij_on_cos : bij_on cos (Icc 0 π) (Icc (-1) 1) :=
⟨maps_to_cos _, inj_on_cos, surj_on_cos⟩
@[simp] lemma range_cos : range cos = (Icc (-1) 1 : set ℝ) :=
subset.antisymm (range_subset_iff.2 cos_mem_Icc) surj_on_cos.subset_range
@[simp] lemma range_sin : range sin = (Icc (-1) 1 : set ℝ) :=
subset.antisymm (range_subset_iff.2 sin_mem_Icc) surj_on_sin.subset_range
lemma range_cos_infinite : (range real.cos).infinite :=
by { rw real.range_cos, exact Icc.infinite (by norm_num) }
lemma range_sin_infinite : (range real.sin).infinite :=
by { rw real.range_sin, exact Icc.infinite (by norm_num) }
lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x :=
begin
cases le_or_gt x 1 with h' h',
{ have hx : abs x = x := abs_of_nonneg (le_of_lt h),
have : abs x ≤ 1, rwa [hx],
have := sin_bound this, rw [abs_le] at this,
have := this.2, rw [sub_le_iff_le_add', hx] at this,
apply lt_of_le_of_lt this, rw [sub_add], apply lt_of_lt_of_le _ (le_of_eq (sub_zero x)),
apply sub_lt_sub_left, rw [sub_pos, div_eq_mul_inv (x ^ 3)], apply mul_lt_mul',
{ rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)),
rw mul_le_mul_right, exact h', apply pow_pos h },
norm_num, norm_num, apply pow_pos h },
exact lt_of_le_of_lt (sin_le_one x) h'
end
/- note 1: this inequality is not tight, the tighter inequality is sin x > x - x ^ 3 / 6.
note 2: this is also true for x > 1, but it's nontrivial for x just above 1. -/
lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : x - x ^ 3 / 4 < sin x :=
begin
have hx : abs x = x := abs_of_nonneg (le_of_lt h),
have : abs x ≤ 1, rwa [hx],
have := sin_bound this, rw [abs_le] at this,
have := this.1, rw [le_sub_iff_add_le, hx] at this,
refine lt_of_lt_of_le _ this,
rw [add_comm, sub_add, sub_neg_eq_add], apply sub_lt_sub_left,
apply add_lt_of_lt_sub_left,
rw (show x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 * 12⁻¹,
by simp [div_eq_mul_inv, ← mul_sub]; norm_num),
apply mul_lt_mul',
{ rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)),
rw mul_le_mul_right, exact h', apply pow_pos h },
norm_num, norm_num, apply pow_pos h
end
section cos_div_pow_two
variable (x : ℝ)
/-- the series `sqrt_two_add_series x n` is `sqrt(2 + sqrt(2 + ... ))` with `n` square roots,
starting with `x`. We define it here because `cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2`
-/
@[simp, pp_nodot] noncomputable def sqrt_two_add_series (x : ℝ) : ℕ → ℝ
| 0 := x
| (n+1) := sqrt (2 + sqrt_two_add_series n)
lemma sqrt_two_add_series_zero : sqrt_two_add_series x 0 = x := by simp
lemma sqrt_two_add_series_one : sqrt_two_add_series 0 1 = sqrt 2 := by simp
lemma sqrt_two_add_series_two : sqrt_two_add_series 0 2 = sqrt (2 + sqrt 2) := by simp
lemma sqrt_two_add_series_zero_nonneg : ∀(n : ℕ), 0 ≤ sqrt_two_add_series 0 n
| 0 := le_refl 0
| (n+1) := sqrt_nonneg _
lemma sqrt_two_add_series_nonneg {x : ℝ} (h : 0 ≤ x) : ∀(n : ℕ), 0 ≤ sqrt_two_add_series x n
| 0 := h
| (n+1) := sqrt_nonneg _
lemma sqrt_two_add_series_lt_two : ∀(n : ℕ), sqrt_two_add_series 0 n < 2
| 0 := by norm_num
| (n+1) :=
begin
refine lt_of_lt_of_le _ (le_of_eq $ sqrt_sqr $ le_of_lt zero_lt_two),
rw [sqrt_two_add_series, sqrt_lt, ← lt_sub_iff_add_lt'],
{ refine (sqrt_two_add_series_lt_two n).trans_le _, norm_num },
{ exact add_nonneg zero_le_two (sqrt_two_add_series_zero_nonneg n) }
end
lemma sqrt_two_add_series_succ (x : ℝ) :
∀(n : ℕ), sqrt_two_add_series x (n+1) = sqrt_two_add_series (sqrt (2 + x)) n
| 0 := rfl
| (n+1) := by rw [sqrt_two_add_series, sqrt_two_add_series_succ, sqrt_two_add_series]
lemma sqrt_two_add_series_monotone_left {x y : ℝ} (h : x ≤ y) :
∀(n : ℕ), sqrt_two_add_series x n ≤ sqrt_two_add_series y n
| 0 := h
| (n+1) :=
begin
rw [sqrt_two_add_series, sqrt_two_add_series],
exact sqrt_le_sqrt (add_le_add_left (sqrt_two_add_series_monotone_left _) _)
end
@[simp] lemma cos_pi_over_two_pow : ∀(n : ℕ), cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2
| 0 := by simp
| (n+1) :=
begin
have : (2 : ℝ) ≠ 0 := two_ne_zero,
symmetry, rw [div_eq_iff_mul_eq this], symmetry,
rw [sqrt_two_add_series, sqrt_eq_iff_sqr_eq, mul_pow, cos_square, ←mul_div_assoc,
nat.add_succ, pow_succ, mul_div_mul_left _ _ this, cos_pi_over_two_pow, add_mul],
congr, { norm_num },
rw [mul_comm, pow_two, mul_assoc, ←mul_div_assoc, mul_div_cancel_left, ←mul_div_assoc,
mul_div_cancel_left]; try { exact this },
apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, norm_num,
apply le_of_lt, apply cos_pos_of_mem_Ioo ⟨_, _⟩,
{ transitivity (0 : ℝ), rw neg_lt_zero, apply pi_div_two_pos,
apply div_pos pi_pos, apply pow_pos, norm_num },
apply div_lt_div' (le_refl pi) _ pi_pos _,
refine lt_of_le_of_lt (le_of_eq (pow_one _).symm) _,
apply pow_lt_pow, norm_num, apply nat.succ_lt_succ, apply nat.succ_pos, all_goals {norm_num}
end
lemma sin_square_pi_over_two_pow (n : ℕ) :
sin (pi / 2 ^ (n+1)) ^ 2 = 1 - (sqrt_two_add_series 0 n / 2) ^ 2 :=
by rw [sin_square, cos_pi_over_two_pow]
lemma sin_square_pi_over_two_pow_succ (n : ℕ) :
sin (pi / 2 ^ (n+2)) ^ 2 = 1 / 2 - sqrt_two_add_series 0 n / 4 :=
begin
rw [sin_square_pi_over_two_pow, sqrt_two_add_series, div_pow, sqr_sqrt, add_div, ←sub_sub],
congr, norm_num, norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg,
end
@[simp] lemma sin_pi_over_two_pow_succ (n : ℕ) :
sin (pi / 2 ^ (n+2)) = sqrt (2 - sqrt_two_add_series 0 n) / 2 :=
begin
symmetry, rw [div_eq_iff_mul_eq], symmetry,
rw [sqrt_eq_iff_sqr_eq, mul_pow, sin_square_pi_over_two_pow_succ, sub_mul],
{ congr, norm_num, rw [mul_comm], convert mul_div_cancel' _ _, norm_num, norm_num },
{ rw [sub_nonneg], apply le_of_lt, apply sqrt_two_add_series_lt_two },
apply le_of_lt, apply mul_pos, apply sin_pos_of_pos_of_lt_pi,
{ apply div_pos pi_pos, apply pow_pos, norm_num },
refine lt_of_lt_of_le _ (le_of_eq (div_one _)), rw [div_lt_div_left],
refine lt_of_le_of_lt (le_of_eq (pow_zero 2).symm) _,
apply pow_lt_pow, norm_num, apply nat.succ_pos, apply pi_pos,
apply pow_pos, all_goals {norm_num}
end
@[simp] lemma cos_pi_div_four : cos (pi / 4) = sqrt 2 / 2 :=
by { transitivity cos (pi / 2 ^ 2), congr, norm_num, simp }
@[simp] lemma sin_pi_div_four : sin (pi / 4) = sqrt 2 / 2 :=
by { transitivity sin (pi / 2 ^ 2), congr, norm_num, simp }
@[simp] lemma cos_pi_div_eight : cos (pi / 8) = sqrt (2 + sqrt 2) / 2 :=
by { transitivity cos (pi / 2 ^ 3), congr, norm_num, simp }
@[simp] lemma sin_pi_div_eight : sin (pi / 8) = sqrt (2 - sqrt 2) / 2 :=
by { transitivity sin (pi / 2 ^ 3), congr, norm_num, simp }
@[simp] lemma cos_pi_div_sixteen : cos (pi / 16) = sqrt (2 + sqrt (2 + sqrt 2)) / 2 :=
by { transitivity cos (pi / 2 ^ 4), congr, norm_num, simp }
@[simp] lemma sin_pi_div_sixteen : sin (pi / 16) = sqrt (2 - sqrt (2 + sqrt 2)) / 2 :=
by { transitivity sin (pi / 2 ^ 4), congr, norm_num, simp }
@[simp] lemma cos_pi_div_thirty_two : cos (pi / 32) = sqrt (2 + sqrt (2 + sqrt (2 + sqrt 2))) / 2 :=
by { transitivity cos (pi / 2 ^ 5), congr, norm_num, simp }
@[simp] lemma sin_pi_div_thirty_two : sin (pi / 32) = sqrt (2 - sqrt (2 + sqrt (2 + sqrt 2))) / 2 :=
by { transitivity sin (pi / 2 ^ 5), congr, norm_num, simp }
-- This section is also a convenient location for other explicit values of `sin` and `cos`.
/-- The cosine of `π / 3` is `1 / 2`. -/
@[simp] lemma cos_pi_div_three : cos (π / 3) = 1 / 2 :=
begin
have h₁ : (2 * cos (π / 3) - 1) ^ 2 * (2 * cos (π / 3) + 2) = 0,
{ have : cos (3 * (π / 3)) = cos π := by { congr' 1, ring },
linarith [cos_pi, cos_three_mul (π / 3)] },
cases mul_eq_zero.mp h₁ with h h,
{ linarith [pow_eq_zero h] },
{ have : cos π < cos (π / 3),
{ refine cos_lt_cos_of_nonneg_of_le_pi _ rfl.ge _;
linarith [pi_pos] },
linarith [cos_pi] }
end
/-- The square of the cosine of `π / 6` is `3 / 4` (this is sometimes more convenient than the
result for cosine itself). -/
lemma square_cos_pi_div_six : cos (π / 6) ^ 2 = 3 / 4 :=
begin
have h1 : cos (π / 6) ^ 2 = 1 / 2 + 1 / 2 / 2,
{ convert cos_square (π / 6),
have h2 : 2 * (π / 6) = π / 3 := by cancel_denoms,
rw [h2, cos_pi_div_three] },
rw ← sub_eq_zero at h1 ⊢,
convert h1 using 1,
ring
end
/-- The cosine of `π / 6` is `√3 / 2`. -/
@[simp] lemma cos_pi_div_six : cos (π / 6) = (sqrt 3) / 2 :=
begin
suffices : sqrt 3 = cos (π / 6) * 2,
{ field_simp [(by norm_num : 0 ≠ 2)], exact this.symm },
rw sqrt_eq_iff_sqr_eq,
{ have h1 := (mul_right_inj' (by norm_num : (4:ℝ) ≠ 0)).mpr square_cos_pi_div_six,
rw ← sub_eq_zero at h1 ⊢,
convert h1 using 1,
ring },
{ norm_num },
{ have : 0 < cos (π / 6) := by { apply cos_pos_of_mem_Ioo; split; linarith [pi_pos] },
linarith },
end
/-- The sine of `π / 6` is `1 / 2`. -/
@[simp] lemma sin_pi_div_six : sin (π / 6) = 1 / 2 :=
begin
rw [← cos_pi_div_two_sub, ← cos_pi_div_three],
congr,
ring
end
/-- The square of the sine of `π / 3` is `3 / 4` (this is sometimes more convenient than the
result for cosine itself). -/
lemma square_sin_pi_div_three : sin (π / 3) ^ 2 = 3 / 4 :=
begin
rw [← cos_pi_div_two_sub, ← square_cos_pi_div_six],
congr,
ring
end
/-- The sine of `π / 3` is `√3 / 2`. -/
@[simp] lemma sin_pi_div_three : sin (π / 3) = (sqrt 3) / 2 :=
begin
rw [← cos_pi_div_two_sub, ← cos_pi_div_six],
congr,
ring
end
end cos_div_pow_two
/-- The type of angles -/
def angle : Type :=
quotient_add_group.quotient (add_subgroup.gmultiples (2 * π))
namespace angle
instance angle.add_comm_group : add_comm_group angle :=
quotient_add_group.add_comm_group _
instance : inhabited angle := ⟨0⟩
instance angle.has_coe : has_coe ℝ angle :=
⟨quotient.mk'⟩
@[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl
@[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl
@[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl
@[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) :=
by rw [sub_eq_add_neg, sub_eq_add_neg, coe_add, coe_neg]
@[simp, norm_cast] lemma coe_nat_mul_eq_nsmul (x : ℝ) (n : ℕ) :
↑((n : ℝ) * x) = n •ℕ (↑x : angle) :=
by simpa using add_monoid_hom.map_nsmul ⟨coe, coe_zero, coe_add⟩ _ _
@[simp, norm_cast] lemma coe_int_mul_eq_gsmul (x : ℝ) (n : ℤ) :
↑((n : ℝ) * x : ℝ) = n •ℤ (↑x : angle) :=
by simpa using add_monoid_hom.map_gsmul ⟨coe, coe_zero, coe_add⟩ _ _
@[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) :=
quotient.sound' ⟨-1, show (-1 : ℤ) •ℤ (2 * π) = _, by rw [neg_one_gsmul, add_zero]⟩
lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k :=
by simp only [quotient_add_group.eq, add_subgroup.gmultiples_eq_closure,
add_subgroup.mem_closure_singleton, gsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm]
theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ :=
begin
split,
{ intro Hcos,
rw [←sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero,
false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos,
rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩,
{ right,
rw [eq_div_iff_mul_eq (@two_ne_zero ℝ _ _), ← sub_eq_iff_eq_add] at hn,
rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc,
coe_int_mul_eq_gsmul, mul_comm, coe_two_pi, gsmul_zero] },
{ left,
rw [eq_div_iff_mul_eq (@two_ne_zero ℝ _ _), eq_sub_iff_add_eq] at hn,
rw [← hn, coe_add, mul_assoc,
coe_int_mul_eq_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] },
apply_instance, },
{ rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub],
rintro (⟨k, H⟩ | ⟨k, H⟩),
rw [← sub_eq_zero_iff_eq, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _ _),
mul_comm π _, sin_int_mul_pi, mul_zero],
rw [←sub_eq_zero_iff_eq, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k,
mul_div_cancel_left _ (@two_ne_zero ℝ _ _), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] }
end
theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π :=
begin
split,
{ intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin,
cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h,
{ left, rw [coe_sub, coe_sub] at h, exact sub_right_inj.1 h },
right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub,
sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h,
exact h.symm },
{ rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub],
rintro (⟨k, H⟩ | ⟨k, H⟩),
rw [← sub_eq_zero_iff_eq, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _ _),
mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul],
have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add,
mul_assoc, mul_comm π _, ←mul_assoc] at H,
rw [← sub_eq_zero_iff_eq, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ (@two_ne_zero ℝ _ _),
cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] }
end
theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ :=
begin
cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc },
cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs },
rw [eq_neg_iff_add_eq_zero, hs] at hc,
cases quotient.exact' hc with n hn, change n •ℤ _ = _ at hn,
rw [← neg_one_mul, add_zero, ← sub_eq_zero_iff_eq, gsmul_eq_mul, ← mul_assoc, ← sub_mul,
mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add,
← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn,
have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn,
rw [add_comm, int.add_mul_mod_self] at this,
exact absurd this one_ne_zero
end
end angle
/-- `real.sin` as an `order_iso` between `[-(π / 2), π / 2]` and `[-1, 1]`. -/
def sin_order_iso : Icc (-(π / 2)) (π / 2) ≃o Icc (-1:ℝ) 1 :=
(strict_mono_incr_on_sin.order_iso _ _).trans $ order_iso.set_congr _ _ bij_on_sin.image_eq
@[simp] lemma coe_sin_order_iso_apply (x : Icc (-(π / 2)) (π / 2)) :
(sin_order_iso x : ℝ) = sin x := rfl
lemma sin_order_iso_apply (x : Icc (-(π / 2)) (π / 2)) :
sin_order_iso x = ⟨sin x, sin_mem_Icc x⟩ := rfl
/-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x ≤ π / 2`.
It defaults to `-π / 2` on `(-∞, -1)` and to `π / 2` to `(1, ∞)`. -/
@[pp_nodot] noncomputable def arcsin : ℝ → ℝ :=
coe ∘ Icc_extend (neg_le_self zero_le_one) sin_order_iso.symm
lemma arcsin_mem_Icc (x : ℝ) : arcsin x ∈ Icc (-(π / 2)) (π / 2) := subtype.coe_prop _
@[simp] lemma range_arcsin : range arcsin = Icc (-(π / 2)) (π / 2) :=
by { rw [arcsin, range_comp coe], simp [Icc] }
lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 := (arcsin_mem_Icc x).2
lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x := (arcsin_mem_Icc x).1
lemma arcsin_proj_Icc (x : ℝ) :
arcsin (proj_Icc (-1) 1 (neg_le_self $ @zero_le_one ℝ _) x) = arcsin x :=
by rw [arcsin, function.comp_app, Icc_extend_coe, function.comp_app, Icc_extend]
lemma sin_arcsin' {x : ℝ} (hx : x ∈ Icc (-1 : ℝ) 1) : sin (arcsin x) = x :=
by simpa [arcsin, Icc_extend_of_mem _ _ hx, -order_iso.apply_symm_apply]
using subtype.ext_iff.1 (sin_order_iso.apply_symm_apply ⟨x, hx⟩)
lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x :=
sin_arcsin' ⟨hx₁, hx₂⟩
lemma arcsin_sin' {x : ℝ} (hx : x ∈ Icc (-(π / 2)) (π / 2)) : arcsin (sin x) = x :=
inj_on_sin (arcsin_mem_Icc _) hx $ by rw [sin_arcsin (neg_one_le_sin _) (sin_le_one _)]
lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x :=
arcsin_sin' ⟨hx₁, hx₂⟩
lemma strict_mono_incr_on_arcsin : strict_mono_incr_on arcsin (Icc (-1) 1) :=
(subtype.strict_mono_coe _).comp_strict_mono_incr_on $
sin_order_iso.symm.strict_mono.strict_mono_incr_on_Icc_extend _
lemma monotone_arcsin : monotone arcsin :=
(subtype.mono_coe _).comp $ sin_order_iso.symm.monotone.Icc_extend _
lemma inj_on_arcsin : inj_on arcsin (Icc (-1) 1) := strict_mono_incr_on_arcsin.inj_on
lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) :
arcsin x = arcsin y ↔ x = y :=
inj_on_arcsin.eq_iff ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩
lemma continuous_arcsin : continuous arcsin :=
continuous_subtype_coe.comp sin_order_iso.symm.continuous.Icc_extend
lemma continuous_at_arcsin {x : ℝ} : continuous_at arcsin x :=
continuous_arcsin.continuous_at
lemma arcsin_eq_of_sin_eq {x y : ℝ} (h₁ : sin x = y) (h₂ : x ∈ Icc (-(π / 2)) (π / 2)) :
arcsin y = x :=
begin
subst y,
exact inj_on_sin (arcsin_mem_Icc _) h₂ (sin_arcsin' (sin_mem_Icc x))
end
@[simp] lemma arcsin_zero : arcsin 0 = 0 :=
arcsin_eq_of_sin_eq sin_zero ⟨neg_nonpos.2 pi_div_two_pos.le, pi_div_two_pos.le⟩
@[simp] lemma arcsin_one : arcsin 1 = π / 2 :=
arcsin_eq_of_sin_eq sin_pi_div_two $ right_mem_Icc.2 (neg_le_self pi_div_two_pos.le)
lemma arcsin_of_one_le {x : ℝ} (hx : 1 ≤ x) : arcsin x = π / 2 :=
by rw [← arcsin_proj_Icc, proj_Icc_of_right_le _ hx, subtype.coe_mk, arcsin_one]
lemma arcsin_neg_one : arcsin (-1) = -(π / 2) :=
arcsin_eq_of_sin_eq (by rw [sin_neg, sin_pi_div_two]) $
left_mem_Icc.2 (neg_le_self pi_div_two_pos.le)
lemma arcsin_of_le_neg_one {x : ℝ} (hx : x ≤ -1) : arcsin x = -(π / 2) :=
by rw [← arcsin_proj_Icc, proj_Icc_of_le_left _ hx, subtype.coe_mk, arcsin_neg_one]
@[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x :=
begin
cases le_total x (-1) with hx₁ hx₁,
{ rw [arcsin_of_le_neg_one hx₁, neg_neg, arcsin_of_one_le (le_neg.2 hx₁)] },
cases le_total 1 x with hx₂ hx₂,
{ rw [arcsin_of_one_le hx₂, arcsin_of_le_neg_one (neg_le_neg hx₂)] },
refine arcsin_eq_of_sin_eq _ _,
{ rw [sin_neg, sin_arcsin hx₁ hx₂] },
{ exact ⟨neg_le_neg (arcsin_le_pi_div_two _), neg_le.2 (neg_pi_div_two_le_arcsin _)⟩ }
end
lemma arcsin_le_iff_le_sin {x y : ℝ} (hx : x ∈ Icc (-1 : ℝ) 1) (hy : y ∈ Icc (-(π / 2)) (π / 2)) :
arcsin x ≤ y ↔ x ≤ sin y :=
by rw [← arcsin_sin' hy, strict_mono_incr_on_arcsin.le_iff_le hx (sin_mem_Icc _), arcsin_sin' hy]
lemma arcsin_le_iff_le_sin' {x y : ℝ} (hy : y ∈ Ico (-(π / 2)) (π / 2)) :
arcsin x ≤ y ↔ x ≤ sin y :=
begin
cases le_total x (-1) with hx₁ hx₁,
{ simp [arcsin_of_le_neg_one hx₁, hy.1, hx₁.trans (neg_one_le_sin _)] },
cases lt_or_le 1 x with hx₂ hx₂,
{ simp [arcsin_of_one_le hx₂.le, hy.2.not_le, (sin_le_one y).trans_lt hx₂] },
exact arcsin_le_iff_le_sin ⟨hx₁, hx₂⟩ (mem_Icc_of_Ico hy)
end
lemma le_arcsin_iff_sin_le {x y : ℝ} (hx : x ∈ Icc (-(π / 2)) (π / 2)) (hy : y ∈ Icc (-1 : ℝ) 1) :
x ≤ arcsin y ↔ sin x ≤ y :=
by rw [← neg_le_neg_iff, ← arcsin_neg,
arcsin_le_iff_le_sin ⟨neg_le_neg hy.2, neg_le.2 hy.1⟩ ⟨neg_le_neg hx.2, neg_le.2 hx.1⟩,
sin_neg, neg_le_neg_iff]
lemma le_arcsin_iff_sin_le' {x y : ℝ} (hx : x ∈ Ioc (-(π / 2)) (π / 2)) :
x ≤ arcsin y ↔ sin x ≤ y :=
by rw [← neg_le_neg_iff, ← arcsin_neg, arcsin_le_iff_le_sin' ⟨neg_le_neg hx.2, neg_lt.2 hx.1⟩,
sin_neg, neg_le_neg_iff]
lemma arcsin_lt_iff_lt_sin {x y : ℝ} (hx : x ∈ Icc (-1 : ℝ) 1) (hy : y ∈ Icc (-(π / 2)) (π / 2)) :
arcsin x < y ↔ x < sin y :=
not_le.symm.trans $ (not_congr $ le_arcsin_iff_sin_le hy hx).trans not_le
lemma arcsin_lt_iff_lt_sin' {x y : ℝ} (hy : y ∈ Ioc (-(π / 2)) (π / 2)) :
arcsin x < y ↔ x < sin y :=
not_le.symm.trans $ (not_congr $ le_arcsin_iff_sin_le' hy).trans not_le
lemma lt_arcsin_iff_sin_lt {x y : ℝ} (hx : x ∈ Icc (-(π / 2)) (π / 2)) (hy : y ∈ Icc (-1 : ℝ) 1) :
x < arcsin y ↔ sin x < y :=
not_le.symm.trans $ (not_congr $ arcsin_le_iff_le_sin hy hx).trans not_le
lemma lt_arcsin_iff_sin_lt' {x y : ℝ} (hx : x ∈ Ico (-(π / 2)) (π / 2)) :
x < arcsin y ↔ sin x < y :=
not_le.symm.trans $ (not_congr $ arcsin_le_iff_le_sin' hx).trans not_le
lemma arcsin_eq_iff_eq_sin {x y : ℝ} (hy : y ∈ Ioo (-(π / 2)) (π / 2)) :
arcsin x = y ↔ x = sin y :=
by simp only [le_antisymm_iff, arcsin_le_iff_le_sin' (mem_Ico_of_Ioo hy),
le_arcsin_iff_sin_le' (mem_Ioc_of_Ioo hy)]
@[simp] lemma arcsin_nonneg {x : ℝ} : 0 ≤ arcsin x ↔ 0 ≤ x :=
(le_arcsin_iff_sin_le' ⟨neg_lt_zero.2 pi_div_two_pos, pi_div_two_pos.le⟩).trans $ by rw [sin_zero]
@[simp] lemma arcsin_nonpos {x : ℝ} : arcsin x ≤ 0 ↔ x ≤ 0 :=
neg_nonneg.symm.trans $ arcsin_neg x ▸ arcsin_nonneg.trans neg_nonneg
@[simp] lemma arcsin_eq_zero_iff {x : ℝ} : arcsin x = 0 ↔ x = 0 :=
by simp [le_antisymm_iff]
@[simp] lemma zero_eq_arcsin_iff {x} : 0 = arcsin x ↔ x = 0 :=
eq_comm.trans arcsin_eq_zero_iff
@[simp] lemma arcsin_pos {x : ℝ} : 0 < arcsin x ↔ 0 < x :=
lt_iff_lt_of_le_iff_le arcsin_nonpos
@[simp] lemma arcsin_lt_zero {x : ℝ} : arcsin x < 0 ↔ x < 0 :=
lt_iff_lt_of_le_iff_le arcsin_nonneg
@[simp] lemma arcsin_lt_pi_div_two {x : ℝ} : arcsin x < π / 2 ↔ x < 1 :=
(arcsin_lt_iff_lt_sin' (right_mem_Ioc.2 $ neg_lt_self pi_div_two_pos)).trans $
by rw sin_pi_div_two
@[simp] lemma neg_pi_div_two_lt_arcsin {x : ℝ} : -(π / 2) < arcsin x ↔ -1 < x :=
(lt_arcsin_iff_sin_lt' $ left_mem_Ico.2 $ neg_lt_self pi_div_two_pos).trans $
by rw [sin_neg, sin_pi_div_two]
@[simp] lemma arcsin_eq_pi_div_two {x : ℝ} : arcsin x = π / 2 ↔ 1 ≤ x :=
⟨λ h, not_lt.1 $ λ h', (arcsin_lt_pi_div_two.2 h').ne h, arcsin_of_one_le⟩
@[simp] lemma pi_div_two_eq_arcsin {x} : π / 2 = arcsin x ↔ 1 ≤ x :=
eq_comm.trans arcsin_eq_pi_div_two
@[simp] lemma pi_div_two_le_arcsin {x} : π / 2 ≤ arcsin x ↔ 1 ≤ x :=
(arcsin_le_pi_div_two x).le_iff_eq.trans pi_div_two_eq_arcsin
@[simp] lemma arcsin_eq_neg_pi_div_two {x : ℝ} : arcsin x = -(π / 2) ↔ x ≤ -1 :=
⟨λ h, not_lt.1 $ λ h', (neg_pi_div_two_lt_arcsin.2 h').ne' h, arcsin_of_le_neg_one⟩
@[simp] lemma neg_pi_div_two_eq_arcsin {x} : -(π / 2) = arcsin x ↔ x ≤ -1 :=
eq_comm.trans arcsin_eq_neg_pi_div_two
@[simp] lemma arcsin_le_neg_pi_div_two {x} : arcsin x ≤ -(π / 2) ↔ x ≤ -1 :=
(neg_pi_div_two_le_arcsin x).le_iff_eq.trans arcsin_eq_neg_pi_div_two
lemma maps_to_sin_Ioo : maps_to sin (Ioo (-(π / 2)) (π / 2)) (Ioo (-1) 1) :=
λ x h, by rwa [mem_Ioo, ← arcsin_lt_pi_div_two, ← neg_pi_div_two_lt_arcsin,
arcsin_sin h.1.le h.2.le]
/-- `real.sin` as a `local_homeomorph` between `(-π / 2, π / 2)` and `(-1, 1)`. -/
@[simp] def sin_local_homeomorph : local_homeomorph ℝ ℝ :=
{ to_fun := sin,
inv_fun := arcsin,
source := Ioo (-(π / 2)) (π / 2),
target := Ioo (-1) 1,
map_source' := maps_to_sin_Ioo,
map_target' := λ y hy, ⟨neg_pi_div_two_lt_arcsin.2 hy.1, arcsin_lt_pi_div_two.2 hy.2⟩,
left_inv' := λ x hx, arcsin_sin hx.1.le hx.2.le,
right_inv' := λ y hy, sin_arcsin hy.1.le hy.2.le,
open_source := is_open_Ioo,
open_target := is_open_Ioo,
continuous_to_fun := continuous_sin.continuous_on,
continuous_inv_fun := continuous_arcsin.continuous_on }
lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) :=
cos_nonneg_of_mem_Icc ⟨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_sq_add_cos_sq (arcsin x),
begin
rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_sq_le_one (arcsin x))),
pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this,
rw [this, sin_arcsin hx₁ hx₂],
end
lemma deriv_arcsin_aux {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) :
has_deriv_at arcsin (1 / sqrt (1 - x ^ 2)) x ∧ times_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_deriv_at_const _ _).congr_of_eventually_eq this,
times_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 h₁.le h₂.le, one_div] at this ⊢,
exact ⟨sin_local_homeomorph.has_deriv_at_symm ⟨h₁, h₂⟩ this.ne' (has_deriv_at_sin _),
sin_local_homeomorph.times_cont_diff_at_symm_deriv this.ne' ⟨h₁, h₂⟩
(has_deriv_at_sin _) times_cont_diff_sin.times_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_deriv_at_const _ _).congr_of_eventually_eq this,
times_cont_diff_at_const.congr_of_eventually_eq this⟩ }
end
lemma has_deriv_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) :
has_deriv_at arcsin (1 / sqrt (1 - x ^ 2)) x :=
(deriv_arcsin_aux h₁ h₂).1
lemma times_cont_diff_at_arcsin {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) {n : with_top ℕ} :
times_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 =ᶠ[𝓝[Ici (-1:ℝ)] (-1)] id,
{ filter_upwards [Icc_mem_nhds_within_Ici ⟨le_rfl, neg_lt_self (@zero_lt_one ℝ _ _)⟩],
exact λ x, 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 times_cont_diff_on_arcsin {n : with_top ℕ} :
times_cont_diff_on ℝ n arcsin {-1, 1}ᶜ :=
λ x hx, (times_cont_diff_at_arcsin (mt or.inl hx) (mt or.inr hx)).times_cont_diff_within_at
lemma times_cont_diff_at_arcsin_iff {x : ℝ} {n : with_top ℕ} :
times_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 $
with_top.one_le_iff_pos.2 (pos_iff_ne_zero.2 hn),
λ h, h.elim (λ hn, hn.symm ▸ (times_cont_diff_zero.2 continuous_arcsin).times_cont_diff_at) $
λ hx, times_cont_diff_at_arcsin hx.1 hx.2⟩
lemma measurable_arcsin : measurable arcsin := continuous_arcsin.measurable
/-- 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` -/
@[pp_nodot] 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 [neg_pi_div_two_le_arcsin x]
lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x :=
by unfold arccos; linarith [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 [sub_eq_add_neg]; linarith
lemma strict_mono_decr_on_arccos : strict_mono_decr_on arccos (Icc (-1) 1) :=
λ x hx y hy h, sub_lt_sub_left (strict_mono_incr_on_arcsin hx hy h) _
lemma arccos_inj_on : inj_on arccos (Icc (-1) 1) := strict_mono_decr_on_arccos.inj_on
lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) :
arccos x = arccos y ↔ x = y :=
arccos_inj_on.eq_iff ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩
@[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]
@[simp] lemma arccos_eq_zero {x} : arccos x = 0 ↔ 1 ≤ x :=
by simp [arccos, sub_eq_zero]
@[simp] lemma arccos_eq_pi_div_two {x} : arccos x = π / 2 ↔ x = 0 :=
by simp [arccos, sub_eq_iff_eq_add]
@[simp] lemma arccos_eq_pi {x} : arccos x = π ↔ x ≤ -1 :=
by rw [arccos, sub_eq_iff_eq_add, ← sub_eq_iff_eq_add', div_two_sub_self, neg_pi_div_two_eq_arcsin]
lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x :=
by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self, sub_neg_eq_add]
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 continuous_arccos : continuous arccos := continuous_const.sub continuous_arcsin
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 times_cont_diff_at_arccos {x : ℝ} (h₁ : x ≠ -1) (h₂ : x ≠ 1) {n : with_top ℕ} :
times_cont_diff_at ℝ n arccos x :=
times_cont_diff_at_const.sub (times_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 times_cont_diff_on_arccos {n : with_top ℕ} :
times_cont_diff_on ℝ n arccos {-1, 1}ᶜ :=
times_cont_diff_on_const.sub times_cont_diff_on_arcsin
lemma times_cont_diff_at_arccos_iff {x : ℝ} {n : with_top ℕ} :
times_cont_diff_at ℝ n arccos x ↔ n = 0 ∨ (x ≠ -1 ∧ x ≠ 1) :=
by refine iff.trans ⟨λ h, _, λ h, _⟩ times_cont_diff_at_arcsin_iff;
simpa [arccos] using (@times_cont_diff_at_const _ _ _ _ _ _ _ _ _ _ (π / 2)).sub h
lemma measurable_arccos : measurable arccos := continuous_arccos.measurable
@[simp] lemma tan_pi_div_four : tan (π / 4) = 1 :=
begin
rw [tan_eq_sin_div_cos, cos_pi_div_four, sin_pi_div_four],
have h : (sqrt 2) / 2 > 0 := by cancel_denoms,
exact div_self (ne_of_gt h),
end
@[simp] lemma tan_pi_div_two : tan (π / 2) = 0 := by simp [tan_eq_sin_div_cos]
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_mem_Ioo ⟨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 [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))
lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ}
(hx₁ : 0 ≤ x) (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_lt_of_le_pi_div_two (by linarith) (le_of_lt hy₂) hxy)
(cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) (le_of_lt hxy))
(sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith))
(cos_pos_of_mem_Ioo ⟨by linarith, hy₂⟩)
end
lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x)
(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 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 hy₂ hxy
end
lemma strict_mono_incr_on_tan : strict_mono_incr_on tan (Ioo (-(π / 2)) (π / 2)) :=
λ x hx y hy, tan_lt_tan_of_lt_of_lt_pi_div_two hx.1 hy.2
lemma inj_on_tan : inj_on tan (Ioo (-(π / 2)) (π / 2)) :=
strict_mono_incr_on_tan.inj_on
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 :=
inj_on_tan ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩ hxy
end real
namespace complex
open_locale real
/-- `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
if hx₂ : 0 ≤ x.im
then by rw [arg, if_neg hx₁, if_pos hx₂, ← le_sub_iff_add_le, sub_self, real.arcsin_nonpos,
neg_im, neg_div, neg_nonpos];
exact div_nonneg hx₂ (abs_nonneg _)
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 [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₂, ← sub_lt_iff_lt_add];
exact (lt_of_lt_of_le (by linarith [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _))
else by rw [arg, if_neg hx₁, if_neg hx₂, lt_sub_iff_add_lt, neg_add_self, real.arcsin_pos,
neg_im];
exact div_pos (neg_pos.2 (lt_of_not_ge hx₂)) (abs_pos.2 hx)
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 [sub_eq_add_neg, 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, ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)),
one_mul, pow_two, mul_self_abs, norm_sq_apply, 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 [sub_eq_add_neg, 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 :=
begin
by_cases h : x = 0,
{ simp only [h, zero_div, complex.zero_im, complex.arg_zero, real.tan_zero, complex.zero_re] },
rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg h,
div_div_div_cancel_right _ (mt abs_eq_zero.1 h)]
end
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_mem_Icc hx₃,
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 [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re],
by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; try {simp [add_left_comm]}; 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 [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re],
by rw [← real.sin_pi_sub, real.arcsin_sin]; simp [sub_eq_add_neg]; 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`-/
@[pp_nodot] 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 range_exp : range exp = {x | x ≠ 0} :=
set.ext $ λ x, ⟨by { rintro ⟨x, rfl⟩, exact exp_ne_zero x }, λ hx, ⟨log x, exp_log hx⟩⟩
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])
lemma log_of_real_re (x : ℝ) : (log (x : ℂ)).re = real.log x := by simp [log_re]
@[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 exists_pow_nat_eq (x : ℂ) {n : ℕ} (hn : 0 < n) : ∃ z, z ^ n = x :=
begin
by_cases hx : x = 0,
{ use 0, simp only [hx, zero_pow_eq_zero, hn] },
{ use exp (log x / n),
rw [← exp_nat_mul, mul_div_cancel', exp_log hx],
exact_mod_cast (pos_iff_ne_zero.mp hn) }
end
lemma exists_eq_mul_self (x : ℂ) : ∃ z, x = z * z :=
begin
obtain ⟨z, rfl⟩ := exists_pow_nat_eq x zero_lt_two,
exact ⟨z, pow_two z⟩
end
lemma two_pi_I_ne_zero : (2 * π * I : ℂ) ≠ 0 :=
by norm_num [real.pi_ne_zero, I_ne_zero]
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 [sub_eq_add_neg, 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 [sub_eq_add_neg, 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 [sub_eq_add_neg, sin_add]
lemma sin_pi_div_two_sub (x : ℂ) : sin (π / 2 - x) = cos x :=
by simp [sub_eq_add_neg, 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 [sub_eq_add_neg, 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]
lemma exp_pi_mul_I : exp (π * I) = -1 :=
by rw exp_mul_I; simp
theorem cos_eq_zero_iff {θ : ℂ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * π / 2 :=
begin
have h : (exp (θ * I) + exp (-θ * I)) / 2 = 0 ↔ exp (2 * θ * I) = -1,
{ rw [@div_eq_iff _ _ (exp (θ * I) + exp (-θ * I)) 2 0 (by norm_num), zero_mul, add_eq_zero_iff_eq_neg,
neg_eq_neg_one_mul (exp (-θ * I)), ← div_eq_iff (exp_ne_zero (-θ * I)), ← exp_sub],
field_simp, ring },
rw [cos, h, ← exp_pi_mul_I, exp_eq_exp_iff_exists_int],
split; simp; intros x h2; use x,
{ field_simp, ring at h2,
rwa [mul_right_comm 2 I θ, mul_right_comm (2*(x:ℂ)+1) I (π:ℂ), mul_left_inj' I_ne_zero,
mul_comm 2 θ] at h2},
{ field_simp at h2, ring,
rw [mul_right_comm 2 I θ, mul_right_comm (2*(x:ℂ)+1) I (π:ℂ), mul_left_inj' I_ne_zero,
mul_comm 2 θ, h2] },
end
theorem cos_ne_zero_iff {θ : ℂ} : cos θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ (2 * k + 1) * π / 2 :=
by rw [← not_exists, not_iff_not, cos_eq_zero_iff]
theorem sin_eq_zero_iff {θ : ℂ} : sin θ = 0 ↔ ∃ k : ℤ, θ = k * π :=
begin
rw [← complex.cos_sub_pi_div_two, cos_eq_zero_iff],
split,
{ rintros ⟨k, hk⟩,
use k + 1,
field_simp [eq_add_of_sub_eq hk],
ring },
{ rintros ⟨k, rfl⟩,
use k - 1,
field_simp,
ring }
end
theorem sin_ne_zero_iff {θ : ℂ} : sin θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ k * π :=
by rw [← not_exists, not_iff_not, sin_eq_zero_iff]
lemma sin_eq_zero_iff_cos_eq {z : ℂ} : sin z = 0 ↔ cos z = 1 ∨ cos z = -1 :=
by rw [← mul_self_eq_one_iff, ← sin_sq_add_cos_sq, 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 tan_eq_zero_iff {θ : ℂ} : tan θ = 0 ↔ ∃ k : ℤ, θ = k * π / 2 :=
begin
have h := (sin_two_mul θ).symm,
rw mul_assoc at h,
rw [tan, div_eq_zero_iff, ← mul_eq_zero, ← zero_mul ((1/2):ℂ), mul_one_div,
cancel_factors.cancel_factors_eq_div h two_ne_zero', mul_comm],
simpa only [zero_div, zero_mul, ne.def, not_false_iff] with field_simps using sin_eq_zero_iff,
end
lemma tan_ne_zero_iff {θ : ℂ} : tan θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ k * π / 2 :=
by rw [← not_exists, not_iff_not, tan_eq_zero_iff]
lemma tan_int_mul_pi_div_two (n : ℤ) : tan (n * π/2) = 0 :=
tan_eq_zero_iff.mpr (by use n)
lemma tan_int_mul_pi (n : ℤ) : tan (n * π) = 0 :=
by rw tan_eq_zero_iff; use (2*n); field_simp [mul_comm ((n:ℂ)*(π:ℂ)) 2, ← mul_assoc]
lemma cos_eq_cos_iff {x y : ℂ} :
cos x = cos y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = 2 * k * π - x :=
calc cos x = cos y ↔ cos x - cos y = 0 : sub_eq_zero.symm
... ↔ -2 * sin((x + y)/2) * sin((x - y)/2) = 0 : by rw cos_sub_cos
... ↔ sin((x + y)/2) = 0 ∨ sin((x - y)/2) = 0 : by simp [(by norm_num : (2:ℂ) ≠ 0)]
... ↔ sin((x - y)/2) = 0 ∨ sin((x + y)/2) = 0 : or.comm
... ↔ (∃ k : ℤ, y = 2 * k * π + x) ∨ (∃ k :ℤ, y = 2 * k * π - x) :
begin
apply or_congr;
field_simp [sin_eq_zero_iff, (by norm_num : -(2:ℂ) ≠ 0), eq_sub_iff_add_eq',
sub_eq_iff_eq_add, mul_comm (2:ℂ), mul_right_comm _ (2:ℂ)],
split; { rintros ⟨k, rfl⟩, use -k, simp, },
end
... ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = 2 * k * π - x : exists_or_distrib.symm
lemma sin_eq_sin_iff {x y : ℂ} :
sin x = sin y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = (2 * k + 1) * π - x :=
begin
simp only [← complex.cos_sub_pi_div_two, cos_eq_cos_iff, sub_eq_iff_eq_add],
refine exists_congr (λ k, or_congr _ _); refine eq.congr rfl _; field_simp; ring
end
lemma tan_add {x y : ℂ}
(h : ((∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, y ≠ (2 * l + 1) * π / 2)
∨ ((∃ k : ℤ, x = (2 * k + 1) * π / 2) ∧ ∃ l : ℤ, y = (2 * l + 1) * π / 2)) :
tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) :=
begin
rcases h with ⟨h1, h2⟩ | ⟨⟨k, rfl⟩, ⟨l, rfl⟩⟩,
{ rw [tan, sin_add, cos_add,
← div_div_div_cancel_right (sin x * cos y + cos x * sin y)
(mul_ne_zero (cos_ne_zero_iff.mpr h1) (cos_ne_zero_iff.mpr h2)),
add_div, sub_div],
simp only [←div_mul_div, ←tan, mul_one, one_mul,
div_self (cos_ne_zero_iff.mpr h1), div_self (cos_ne_zero_iff.mpr h2)] },
{ obtain ⟨t, hx, hy, hxy⟩ := ⟨tan_int_mul_pi_div_two, t (2*k+1), t (2*l+1), t (2*k+1+(2*l+1))⟩,
simp only [int.cast_add, int.cast_bit0, int.cast_mul, int.cast_one, hx, hy] at hx hy hxy,
rw [hx, hy, add_zero, zero_div,
mul_div_assoc, mul_div_assoc, ← add_mul (2*(k:ℂ)+1) (2*l+1) (π/2), ← mul_div_assoc, hxy] },
end
lemma tan_add' {x y : ℂ}
(h : ((∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, y ≠ (2 * l + 1) * π / 2)) :
tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) :=
tan_add (or.inl h)
lemma tan_two_mul {z : ℂ} : tan (2 * z) = 2 * tan z / (1 - tan z ^ 2) :=
begin
by_cases h : ∀ k : ℤ, z ≠ (2 * k + 1) * π / 2,
{ rw [two_mul, two_mul, pow_two, tan_add (or.inl ⟨h, h⟩)] },
{ rw not_forall_not at h,
rw [two_mul, two_mul, pow_two, tan_add (or.inr ⟨h, h⟩)] },
end
lemma tan_add_mul_I {x y : ℂ}
(h : ((∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, y * I ≠ (2 * l + 1) * π / 2)
∨ ((∃ k : ℤ, x = (2 * k + 1) * π / 2) ∧ ∃ l : ℤ, y * I = (2 * l + 1) * π / 2)) :
tan (x + y*I) = (tan x + tanh y * I) / (1 - tan x * tanh y * I) :=
by rw [tan_add h, tan_mul_I, mul_assoc]
lemma tan_eq {z : ℂ}
(h : ((∀ k : ℤ, (z.re:ℂ) ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, (z.im:ℂ) * I ≠ (2 * l + 1) * π / 2)
∨ ((∃ k : ℤ, (z.re:ℂ) = (2 * k + 1) * π / 2) ∧ ∃ l : ℤ, (z.im:ℂ) * I = (2 * l + 1) * π / 2)) :
tan z = (tan z.re + tanh z.im * I) / (1 - tan z.re * tanh z.im * I) :=
by convert tan_add_mul_I h; exact (re_add_im z).symm
lemma has_deriv_at_tan {x : ℂ} (h : cos x ≠ 0) :
has_deriv_at tan (1 / (cos x)^2) x :=
begin
convert has_deriv_at.div (has_deriv_at_sin x) (has_deriv_at_cos x) h,
rw ← sin_sq_add_cos_sq x,
ring,
end
lemma tendsto_abs_tan_of_cos_eq_zero {x : ℂ} (hx : cos x = 0) :
tendsto (λ x, abs (tan x)) (𝓝[{x}ᶜ] x) at_top :=
begin
simp only [tan_eq_sin_div_cos, ← norm_eq_abs, normed_field.norm_div],
have A : sin x ≠ 0 := λ h, by simpa [*, pow_two] using sin_sq_add_cos_sq x,
have B : tendsto cos (𝓝[{x}ᶜ] (x)) (𝓝[{0}ᶜ] 0),
{ refine tendsto_inf.2 ⟨tendsto.mono_left _ inf_le_left, tendsto_principal.2 _⟩,
exacts [continuous_cos.tendsto' x 0 hx,
hx ▸ (has_deriv_at_cos _).eventually_ne (neg_ne_zero.2 A)] },
exact tendsto.mul_at_top (norm_pos_iff.2 A) continuous_sin.continuous_within_at.norm
(tendsto.inv_tendsto_zero $ tendsto_norm_nhds_within_zero.comp B),
end
lemma tendsto_abs_tan_at_top (k : ℤ) :
tendsto (λ x, abs (tan x)) (𝓝[{(2 * k + 1) * π / 2}ᶜ] ((2 * k + 1) * π / 2)) at_top :=
tendsto_abs_tan_of_cos_eq_zero $ cos_eq_zero_iff.2 ⟨k, rfl⟩
@[simp] lemma continuous_at_tan {x : ℂ} : continuous_at tan x ↔ cos x ≠ 0 :=
begin
refine ⟨λ hc h₀, _, λ h, (has_deriv_at_tan h).continuous_at⟩,
exact not_tendsto_nhds_of_tendsto_at_top (tendsto_abs_tan_of_cos_eq_zero h₀) _
(hc.norm.tendsto.mono_left inf_le_left)
end
@[simp] lemma differentiable_at_tan {x : ℂ} : differentiable_at ℂ tan x ↔ cos x ≠ 0:=
⟨λ h, continuous_at_tan.1 h.continuous_at, λ h, (has_deriv_at_tan h).differentiable_at⟩
@[simp] lemma deriv_tan (x : ℂ) : deriv tan x = 1 / (cos x)^2 :=
if h : cos x = 0 then
have ¬differentiable_at ℂ tan x := mt differentiable_at_tan.1 (not_not.2 h),
by simp [deriv_zero_of_not_differentiable_at this, h, pow_two]
else (has_deriv_at_tan h).deriv
lemma continuous_on_tan : continuous_on tan {x | cos x ≠ 0} :=
continuous_on_sin.div continuous_on_cos $ λ x, id
lemma continuous_tan : continuous (λ x : {x | cos x ≠ 0}, tan x) :=
continuous_on_iff_continuous_restrict.1 continuous_on_tan
@[simp] lemma times_cont_diff_at_tan {x : ℂ} {n : with_top ℕ} :
times_cont_diff_at ℂ n tan x ↔ cos x ≠ 0 :=
⟨λ h, continuous_at_tan.1 h.continuous_at,
times_cont_diff_sin.times_cont_diff_at.div times_cont_diff_cos.times_cont_diff_at⟩
lemma cos_eq_iff_quadratic {z w : ℂ} :
cos z = w ↔ (exp (z * I)) ^ 2 - 2 * w * exp (z * I) + 1 = 0 :=
begin
rw ← sub_eq_zero,
field_simp [cos, exp_neg, exp_ne_zero],
refine eq.congr _ rfl,
ring
end
lemma cos_surjective : function.surjective cos :=
begin
intro x,
obtain ⟨w, w₀, hw⟩ : ∃ w ≠ 0, 1 * w * w + (-2 * x) * w + 1 = 0,
{ rcases exists_quadratic_eq_zero one_ne_zero (exists_eq_mul_self _) with ⟨w, hw⟩,
refine ⟨w, _, hw⟩,
rintro rfl,
simpa only [zero_add, one_ne_zero, mul_zero] using hw },
refine ⟨log w / I, cos_eq_iff_quadratic.2 _⟩,
rw [div_mul_cancel _ I_ne_zero, exp_log w₀],
convert hw,
ring
end
@[simp] lemma range_cos : range cos = set.univ :=
cos_surjective.range_eq
lemma sin_surjective : function.surjective sin :=
begin
intro x,
rcases cos_surjective x with ⟨z, rfl⟩,
exact ⟨z + π / 2, sin_add_pi_div_two z⟩
end
@[simp] lemma range_sin : range sin = set.univ :=
sin_surjective.range_eq
end complex
section chebyshev₁
open polynomial complex
/-- the `n`-th Chebyshev polynomial evaluates on `cos θ` to the value `cos (n * θ)`. -/
lemma chebyshev₁_complex_cos (θ : ℂ) :
∀ n, (chebyshev₁ ℂ n).eval (cos θ) = cos (n * θ)
| 0 := by simp only [chebyshev₁_zero, eval_one, nat.cast_zero, zero_mul, cos_zero]
| 1 := by simp only [eval_X, one_mul, chebyshev₁_one, nat.cast_one]
| (n + 2) :=
begin
simp only [eval_X, eval_one, chebyshev₁_add_two, eval_sub, eval_bit0, nat.cast_succ, eval_mul],
rw [chebyshev₁_complex_cos (n + 1), chebyshev₁_complex_cos n],
have aux : sin θ * sin θ = 1 - cos θ * cos θ,
{ rw ← sin_sq_add_cos_sq θ, ring, },
simp only [nat.cast_add, nat.cast_one, add_mul, cos_add, one_mul, sin_add, mul_assoc, aux],
ring,
end
/-- `cos (n * θ)` is equal to the `n`-th Chebyshev polynomial evaluated on `cos θ`. -/
lemma cos_nat_mul (n : ℕ) (θ : ℂ) :
cos (n * θ) = (chebyshev₁ ℂ n).eval (cos θ) :=
(chebyshev₁_complex_cos θ n).symm
end chebyshev₁
namespace real
open_locale real
lemma tan_add {x y : ℝ}
(h : ((∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, y ≠ (2 * l + 1) * π / 2)
∨ ((∃ k : ℤ, x = (2 * k + 1) * π / 2) ∧ ∃ l : ℤ, y = (2 * l + 1) * π / 2)) :
tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) :=
by simpa only [← complex.of_real_inj, complex.of_real_sub, complex.of_real_add, complex.of_real_div,
complex.of_real_mul, complex.of_real_tan]
using @complex.tan_add (x:ℂ) (y:ℂ) (by convert h; norm_cast)
lemma tan_add' {x y : ℝ}
(h : ((∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, y ≠ (2 * l + 1) * π / 2)) :
tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) :=
tan_add (or.inl h)
lemma tan_two_mul {x:ℝ} : tan (2 * x) = 2 * tan x / (1 - tan x ^ 2) :=
by simpa only [← complex.of_real_inj, complex.of_real_sub, complex.of_real_div, complex.of_real_pow,
complex.of_real_mul, complex.of_real_tan, complex.of_real_bit0, complex.of_real_one]
using complex.tan_two_mul
theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * π / 2 :=
by exact_mod_cast @complex.cos_eq_zero_iff θ
theorem cos_ne_zero_iff {θ : ℝ} : cos θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ (2 * k + 1) * π / 2 :=
by rw [← not_exists, not_iff_not, cos_eq_zero_iff]
lemma tan_ne_zero_iff {θ : ℝ} : tan θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ k * π / 2 :=
by rw [← complex.of_real_ne_zero, complex.of_real_tan, complex.tan_ne_zero_iff]; norm_cast
lemma tan_eq_zero_iff {θ : ℝ} : tan θ = 0 ↔ ∃ k : ℤ, θ = k * π / 2 :=
by rw [← not_iff_not, not_exists, ← ne, tan_ne_zero_iff]
lemma tan_int_mul_pi_div_two (n : ℤ) : tan (n * π/2) = 0 :=
tan_eq_zero_iff.mpr (by use n)
lemma tan_int_mul_pi (n : ℤ) : tan (n * π) = 0 :=
by rw tan_eq_zero_iff; use (2*n); field_simp [mul_comm ((n:ℝ)*(π:ℝ)) 2, ← mul_assoc]
lemma cos_eq_cos_iff {x y : ℝ} :
cos x = cos y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = 2 * k * π - x :=
by exact_mod_cast @complex.cos_eq_cos_iff x y
lemma sin_eq_sin_iff {x y : ℝ} :
sin x = sin y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = (2 * k + 1) * π - x :=
by exact_mod_cast @complex.sin_eq_sin_iff x y
lemma has_deriv_at_tan {x : ℝ} (h : cos x ≠ 0) :
has_deriv_at tan (1 / (cos x)^2) x :=
by exact_mod_cast (complex.has_deriv_at_tan (by exact_mod_cast h)).real_of_complex
lemma tendsto_abs_tan_of_cos_eq_zero {x : ℝ} (hx : cos x = 0) :
tendsto (λ x, abs (tan x)) (𝓝[{x}ᶜ] x) at_top :=
begin
have hx : complex.cos x = 0, by exact_mod_cast hx,
simp only [← complex.abs_of_real, complex.of_real_tan],
refine (complex.tendsto_abs_tan_of_cos_eq_zero hx).comp _,
refine tendsto.inf complex.continuous_of_real.continuous_at _,
exact tendsto_principal_principal.2 (λ y, mt complex.of_real_inj.1)
end
lemma tendsto_abs_tan_at_top (k : ℤ) :
tendsto (λ x, abs (tan x)) (𝓝[{(2 * k + 1) * π / 2}ᶜ] ((2 * k + 1) * π / 2)) at_top :=
tendsto_abs_tan_of_cos_eq_zero $ cos_eq_zero_iff.2 ⟨k, rfl⟩
lemma continuous_at_tan {x : ℝ} : continuous_at tan x ↔ cos x ≠ 0 :=
begin
refine ⟨λ hc h₀, _, λ h, (has_deriv_at_tan h).continuous_at⟩,
exact not_tendsto_nhds_of_tendsto_at_top (tendsto_abs_tan_of_cos_eq_zero h₀) _
(hc.norm.tendsto.mono_left inf_le_left)
end
lemma differentiable_at_tan {x : ℝ} : differentiable_at ℝ tan x ↔ cos x ≠ 0 :=
⟨λ h, continuous_at_tan.1 h.continuous_at, λ h, (has_deriv_at_tan h).differentiable_at⟩
@[simp] lemma deriv_tan (x : ℝ) : deriv tan x = 1 / (cos x)^2 :=
if h : cos x = 0 then
have ¬differentiable_at ℝ tan x := mt differentiable_at_tan.1 (not_not.2 h),
by simp [deriv_zero_of_not_differentiable_at this, h, pow_two]
else (has_deriv_at_tan h).deriv
@[simp] lemma times_cont_diff_at_tan {n x} : times_cont_diff_at ℝ n tan x ↔ cos x ≠ 0 :=
⟨λ h, continuous_at_tan.1 h.continuous_at,
λ h, (complex.times_cont_diff_at_tan.2 $ by exact_mod_cast h).real_of_complex⟩
lemma continuous_on_tan : continuous_on tan {x | cos x ≠ 0} :=
λ x hx, (continuous_at_tan.2 hx).continuous_within_at
lemma has_deriv_at_tan_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-(π/2):ℝ) (π/2)) :
has_deriv_at tan (1 / (cos x)^2) x :=
has_deriv_at_tan (cos_pos_of_mem_Ioo h).ne'
lemma differentiable_at_tan_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-(π/2):ℝ) (π/2)) :
differentiable_at ℝ tan x :=
(has_deriv_at_tan_of_mem_Ioo h).differentiable_at
lemma continuous_on_tan_Ioo : continuous_on tan (Ioo (-(π/2)) (π/2)) :=
λ x hx, (differentiable_at_tan_of_mem_Ioo hx).continuous_at.continuous_within_at
lemma tendsto_sin_pi_div_two : tendsto sin (𝓝[Iio (π/2)] (π/2)) (𝓝 1) :=
by { convert continuous_sin.continuous_within_at, simp }
lemma tendsto_cos_pi_div_two : tendsto cos (𝓝[Iio (π/2)] (π/2)) (𝓝[Ioi 0] 0) :=
begin
apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within,
{ convert continuous_cos.continuous_within_at, simp },
{ filter_upwards [Ioo_mem_nhds_within_Iio (right_mem_Ioc.mpr (norm_num.lt_neg_pos
_ _ pi_div_two_pos pi_div_two_pos))] λ x hx, cos_pos_of_mem_Ioo hx },
end
lemma tendsto_tan_pi_div_two : tendsto tan (𝓝[Iio (π/2)] (π/2)) at_top :=
begin
convert (tendsto.inv_tendsto_zero tendsto_cos_pi_div_two).at_top_mul (by norm_num)
tendsto_sin_pi_div_two,
simp only [pi.inv_apply, ← div_eq_inv_mul, ← tan_eq_sin_div_cos]
end
lemma tendsto_sin_neg_pi_div_two : tendsto sin (𝓝[Ioi (-(π/2))] (-(π/2))) (𝓝 (-1)) :=
by { convert continuous_sin.continuous_within_at, simp }
lemma tendsto_cos_neg_pi_div_two : tendsto cos (𝓝[Ioi (-(π/2))] (-(π/2))) (𝓝[Ioi 0] 0) :=
begin
apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within,
{ convert continuous_cos.continuous_within_at, simp },
{ filter_upwards [Ioo_mem_nhds_within_Ioi (left_mem_Ico.mpr (norm_num.lt_neg_pos
_ _ pi_div_two_pos pi_div_two_pos))] λ x hx, cos_pos_of_mem_Ioo hx },
end
lemma tendsto_tan_neg_pi_div_two : tendsto tan (𝓝[Ioi (-(π/2))] (-(π/2))) at_bot :=
begin
convert (tendsto.inv_tendsto_zero tendsto_cos_neg_pi_div_two).at_top_mul_neg (by norm_num)
tendsto_sin_neg_pi_div_two,
simp only [pi.inv_apply, ← div_eq_inv_mul, ← tan_eq_sin_div_cos]
end
lemma surj_on_tan : surj_on tan (Ioo (-(π / 2)) (π / 2)) univ :=
have _ := neg_lt_self pi_div_two_pos,
continuous_on_tan_Ioo.surj_on_of_tendsto (nonempty_Ioo.2 this)
(by simp [tendsto_tan_neg_pi_div_two, this]) (by simp [tendsto_tan_pi_div_two, this])
lemma tan_surjective : function.surjective tan :=
λ x, surj_on_tan.subset_range trivial
lemma image_tan_Ioo : tan '' (Ioo (-(π / 2)) (π / 2)) = univ :=
univ_subset_iff.1 surj_on_tan
/-- `real.tan` as an `order_iso` between `(-(π / 2), π / 2)` and `ℝ`. -/
def tan_order_iso : Ioo (-(π / 2)) (π / 2) ≃o ℝ :=
(strict_mono_incr_on_tan.order_iso _ _).trans $ (order_iso.set_congr _ _ image_tan_Ioo).trans
order_iso.set.univ
/-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and
`arctan x < π / 2` -/
@[pp_nodot] noncomputable def arctan (x : ℝ) : ℝ :=
tan_order_iso.symm x
@[simp] lemma tan_arctan (x : ℝ) : tan (arctan x) = x :=
tan_order_iso.apply_symm_apply x
lemma arctan_mem_Ioo (x : ℝ) : arctan x ∈ Ioo (-(π / 2)) (π / 2) :=
subtype.coe_prop _
lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x :=
subtype.ext_iff.1 $ tan_order_iso.symm_apply_apply ⟨x, hx₁, hx₂⟩
lemma cos_arctan_pos (x : ℝ) : 0 < cos (arctan x) :=
cos_pos_of_mem_Ioo $ arctan_mem_Ioo x
lemma cos_sq_arctan (x : ℝ) : cos (arctan x) ^ 2 = 1 / (1 + x ^ 2) :=
by rw [one_div, ← inv_one_add_tan_sq (cos_arctan_pos x).ne', tan_arctan]
lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) :=
by rw [← tan_div_sqrt_one_add_tan_sq (cos_arctan_pos x), tan_arctan]
lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) :=
by rw [one_div, ← inv_sqrt_one_add_tan_sq (cos_arctan_pos x), tan_arctan]
lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 :=
(arctan_mem_Ioo x).2
lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x :=
(arctan_mem_Ioo x).1
lemma arctan_eq_arcsin (x : ℝ) : arctan x = arcsin (x / sqrt (1 + x ^ 2)) :=
eq.symm $ arcsin_eq_of_sin_eq (sin_arctan x) (mem_Icc_of_Ioo $ arctan_mem_Ioo x)
@[simp] lemma arctan_zero : arctan 0 = 0 :=
by simp [arctan_eq_arcsin]
lemma arctan_eq_of_tan_eq {x y : ℝ} (h : tan x = y) (hx : x ∈ Ioo (-(π / 2)) (π / 2)) :
arctan y = x :=
inj_on_tan (arctan_mem_Ioo _) hx (by rw [tan_arctan, h])
@[simp] lemma arctan_one : arctan 1 = π / 4 :=
arctan_eq_of_tan_eq tan_pi_div_four $ by split; linarith [pi_pos]
@[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x :=
by simp [arctan_eq_arcsin, neg_div]
lemma continuous_arctan : continuous arctan :=
continuous_subtype_coe.comp tan_order_iso.to_homeomorph.continuous_inv_fun
lemma continuous_at_arctan {x : ℝ} : continuous_at arctan x := continuous_arctan.continuous_at
/-- `real.tan` as a `local_homeomorph` between `(-(π / 2), π / 2)` and the whole line. -/
def tan_local_homeomorph : local_homeomorph ℝ ℝ :=
{ to_fun := tan,
inv_fun := arctan,
source := Ioo (-(π / 2)) (π / 2),
target := univ,
map_source' := maps_to_univ _ _,
map_target' := λ y hy, arctan_mem_Ioo y,
left_inv' := λ x hx, arctan_tan hx.1 hx.2,
right_inv' := λ y hy, tan_arctan y,
open_source := is_open_Ioo,
open_target := is_open_univ,
continuous_to_fun := continuous_on_tan_Ioo,
continuous_inv_fun := continuous_arctan.continuous_on }
@[simp] lemma coe_tan_local_homeomorph : ⇑tan_local_homeomorph = tan := rfl
@[simp] lemma coe_tan_local_homeomorph_symm : ⇑tan_local_homeomorph.symm = arctan := rfl
lemma has_deriv_at_arctan (x : ℝ) : has_deriv_at arctan (1 / (1 + x^2)) x :=
have A : cos (arctan x) ≠ 0 := (cos_arctan_pos x).ne',
by simpa [cos_sq_arctan]
using tan_local_homeomorph.has_deriv_at_symm trivial (by simpa) (has_deriv_at_tan A)
lemma differentiable_at_arctan (x : ℝ) : differentiable_at ℝ arctan x :=
(has_deriv_at_arctan x).differentiable_at
lemma differentiable_arctan : differentiable ℝ arctan := differentiable_at_arctan
@[simp] lemma deriv_arctan : deriv arctan = (λ x, 1 / (1 + x^2)) :=
funext $ λ x, (has_deriv_at_arctan x).deriv
lemma times_cont_diff_arctan {n : with_top ℕ} : times_cont_diff ℝ n arctan :=
times_cont_diff_iff_times_cont_diff_at.2 $ λ x,
have cos (arctan x) ≠ 0 := (cos_arctan_pos x).ne',
tan_local_homeomorph.times_cont_diff_at_symm_deriv (by simpa) trivial (has_deriv_at_tan this)
(times_cont_diff_at_tan.2 this)
lemma measurable_arctan : measurable arctan := continuous_arctan.measurable
end real
section
/-!
### Lemmas for derivatives of the composition of `real.arctan` with a differentiable function
In this section we register lemmas for the derivatives of the composition of `real.arctan` with a
differentiable function, for standalone use and use with `simp`. -/
open real
lemma measurable.arctan {α : Type*} [measurable_space α] {f : α → ℝ} (hf : measurable f) :
measurable (λ x, arctan (f x)) :=
measurable_arctan.comp hf
section deriv
variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ}
lemma has_deriv_at.arctan (hf : has_deriv_at f f' x) :
has_deriv_at (λ x, arctan (f x)) ((1 / (1 + (f x)^2)) * f') x :=
(real.has_deriv_at_arctan (f x)).comp x hf
lemma has_deriv_within_at.arctan (hf : has_deriv_within_at f f' s x) :
has_deriv_within_at (λ x, arctan (f x)) ((1 / (1 + (f x)^2)) * f') s x :=
(real.has_deriv_at_arctan (f x)).comp_has_deriv_within_at x hf
lemma deriv_within_arctan (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) :
deriv_within (λ x, arctan (f x)) s x = (1 / (1 + (f x)^2)) * (deriv_within f s x) :=
hf.has_deriv_within_at.arctan.deriv_within hxs
@[simp] lemma deriv_arctan (hc : differentiable_at ℝ f x) :
deriv (λ x, arctan (f x)) x = (1 / (1 + (f x)^2)) * (deriv f x) :=
hc.has_deriv_at.arctan.deriv
end deriv
section fderiv
variables {E : Type*} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {f' : E →L[ℝ] ℝ} {x : E}
{s : set E} {n : with_top ℕ}
lemma has_fderiv_at.arctan (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ x, arctan (f x)) ((1 / (1 + (f x)^2)) • f') x :=
(has_deriv_at_arctan (f x)).comp_has_fderiv_at x hf
lemma has_fderiv_within_at.arctan (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, arctan (f x)) ((1 / (1 + (f x)^2)) • f') s x :=
(has_deriv_at_arctan (f x)).comp_has_fderiv_within_at x hf
lemma fderiv_within_arctan (hf : differentiable_within_at ℝ f s x)
(hxs : unique_diff_within_at ℝ s x) :
fderiv_within ℝ (λ x, arctan (f x)) s x = (1 / (1 + (f x)^2)) • (fderiv_within ℝ f s x) :=
hf.has_fderiv_within_at.arctan.fderiv_within hxs
@[simp] lemma fderiv_arctan (hc : differentiable_at ℝ f x) :
fderiv ℝ (λ x, arctan (f x)) x = (1 / (1 + (f x)^2)) • (fderiv ℝ f x) :=
hc.has_fderiv_at.arctan.fderiv
lemma differentiable_within_at.arctan (hf : differentiable_within_at ℝ f s x) :
differentiable_within_at ℝ (λ x, real.arctan (f x)) s x :=
hf.has_fderiv_within_at.arctan.differentiable_within_at
@[simp] lemma differentiable_at.arctan (hc : differentiable_at ℝ f x) :
differentiable_at ℝ (λ x, arctan (f x)) x :=
hc.has_fderiv_at.arctan.differentiable_at
lemma differentiable_on.arctan (hc : differentiable_on ℝ f s) :
differentiable_on ℝ (λ x, arctan (f x)) s :=
λ x h, (hc x h).arctan
@[simp] lemma differentiable.arctan (hc : differentiable ℝ f) :
differentiable ℝ (λ x, arctan (f x)) :=
λ x, (hc x).arctan
lemma times_cont_diff_at.arctan (h : times_cont_diff_at ℝ n f x) :
times_cont_diff_at ℝ n (λ x, arctan (f x)) x :=
times_cont_diff_arctan.times_cont_diff_at.comp x h
lemma times_cont_diff.arctan (h : times_cont_diff ℝ n f) :
times_cont_diff ℝ n (λ x, arctan (f x)) :=
times_cont_diff_arctan.comp h
lemma times_cont_diff_within_at.arctan (h : times_cont_diff_within_at ℝ n f s x) :
times_cont_diff_within_at ℝ n (λ x, arctan (f x)) s x :=
times_cont_diff_arctan.comp_times_cont_diff_within_at h
lemma times_cont_diff_on.arctan (h : times_cont_diff_on ℝ n f s) :
times_cont_diff_on ℝ n (λ x, arctan (f x)) s :=
times_cont_diff_arctan.comp_times_cont_diff_on h
end fderiv
end
|
290c34e60e56e8692e6969c144e3aadcdb0c1322
|
8cae430f0a71442d02dbb1cbb14073b31048e4b0
|
/src/measure_theory/function/ae_measurable_sequence.lean
|
90a71460a9acdc735e2269a02ecba7710283c46a
|
[
"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,354
|
lean
|
/-
Copyright (c) 2021 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne
-/
import measure_theory.measurable_space
/-!
# Sequence of measurable functions associated to a sequence of a.e.-measurable functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define here tools to prove statements about limits (infi, supr...) of sequences of
`ae_measurable` functions.
Given a sequence of a.e.-measurable functions `f : ι → α → β` with hypothesis
`hf : ∀ i, ae_measurable (f i) μ`, and a pointwise property `p : α → (ι → β) → Prop` such that we
have `hp : ∀ᵐ x ∂μ, p x (λ n, f n x)`, we define a sequence of measurable functions `ae_seq hf p`
and a measurable set `ae_seq_set hf p`, such that
* `μ (ae_seq_set hf p)ᶜ = 0`
* `x ∈ ae_seq_set hf p → ∀ i : ι, ae_seq hf hp i x = f i x`
* `x ∈ ae_seq_set hf p → p x (λ n, f n x)`
-/
open measure_theory
open_locale classical
variables {ι : Sort*} {α β γ : Type*} [measurable_space α] [measurable_space β]
{f : ι → α → β} {μ : measure α} {p : α → (ι → β) → Prop}
/-- If we have the additional hypothesis `∀ᵐ x ∂μ, p x (λ n, f n x)`, this is a measurable set
whose complement has measure 0 such that for all `x ∈ ae_seq_set`, `f i x` is equal to
`(hf i).mk (f i) x` for all `i` and we have the pointwise property `p x (λ n, f n x)`. -/
def ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) (p : α → (ι → β) → Prop) : set α :=
(to_measurable μ {x | (∀ i, f i x = (hf i).mk (f i) x) ∧ p x (λ n, f n x)}ᶜ)ᶜ
/-- A sequence of measurable functions that are equal to `f` and verify property `p` on the
measurable set `ae_seq_set hf p`. -/
noncomputable
def ae_seq (hf : ∀ i, ae_measurable (f i) μ) (p : α → (ι → β) → Prop) : ι → α → β :=
λ i x, ite (x ∈ ae_seq_set hf p) ((hf i).mk (f i) x) (⟨f i x⟩ : nonempty β).some
namespace ae_seq
section mem_ae_seq_set
lemma mk_eq_fun_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α}
(hx : x ∈ ae_seq_set hf p) (i : ι) :
(hf i).mk (f i) x = f i x :=
begin
have h_ss : ae_seq_set hf p ⊆ {x | ∀ i, f i x = (hf i).mk (f i) x},
{ rw [ae_seq_set, ←compl_compl {x | ∀ i, f i x = (hf i).mk (f i) x}, set.compl_subset_compl],
refine set.subset.trans (set.compl_subset_compl.mpr (λ x h, _)) (subset_to_measurable _ _),
exact h.1, },
exact (h_ss hx i).symm,
end
lemma ae_seq_eq_mk_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α}
(hx : x ∈ ae_seq_set hf p) (i : ι) :
ae_seq hf p i x = (hf i).mk (f i) x :=
by simp only [ae_seq, hx, if_true]
lemma ae_seq_eq_fun_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ) {x : α}
(hx : x ∈ ae_seq_set hf p) (i : ι) :
ae_seq hf p i x = f i x :=
by simp only [ae_seq_eq_mk_of_mem_ae_seq_set hf hx i, mk_eq_fun_of_mem_ae_seq_set hf hx i]
lemma prop_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ)
{x : α} (hx : x ∈ ae_seq_set hf p) :
p x (λ n, ae_seq hf p n x) :=
begin
simp only [ae_seq, hx, if_true],
rw funext (λ n, mk_eq_fun_of_mem_ae_seq_set hf hx n),
have h_ss : ae_seq_set hf p ⊆ {x | p x (λ n, f n x)},
{ rw [←compl_compl {x | p x (λ n, f n x)}, ae_seq_set, set.compl_subset_compl],
refine set.subset.trans (set.compl_subset_compl.mpr _) (subset_to_measurable _ _),
exact λ x hx, hx.2, },
have hx' := set.mem_of_subset_of_mem h_ss hx,
exact hx',
end
lemma fun_prop_of_mem_ae_seq_set (hf : ∀ i, ae_measurable (f i) μ)
{x : α} (hx : x ∈ ae_seq_set hf p) :
p x (λ n, f n x) :=
begin
have h_eq : (λ n, f n x) = λ n, ae_seq hf p n x,
from funext (λ n, (ae_seq_eq_fun_of_mem_ae_seq_set hf hx n).symm),
rw h_eq,
exact prop_of_mem_ae_seq_set hf hx,
end
end mem_ae_seq_set
lemma ae_seq_set_measurable_set {hf : ∀ i, ae_measurable (f i) μ} :
measurable_set (ae_seq_set hf p) :=
(measurable_set_to_measurable _ _).compl
lemma measurable (hf : ∀ i, ae_measurable (f i) μ) (p : α → (ι → β) → Prop)
(i : ι) :
measurable (ae_seq hf p i) :=
measurable.ite ae_seq_set_measurable_set (hf i).measurable_mk $ measurable_const' $
λ x y, rfl
lemma measure_compl_ae_seq_set_eq_zero [countable ι] (hf : ∀ i, ae_measurable (f i) μ)
(hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) :
μ (ae_seq_set hf p)ᶜ = 0 :=
begin
rw [ae_seq_set, compl_compl, measure_to_measurable],
have hf_eq := λ i, (hf i).ae_eq_mk,
simp_rw [filter.eventually_eq, ←ae_all_iff] at hf_eq,
exact filter.eventually.and hf_eq hp,
end
lemma ae_seq_eq_mk_ae [countable ι] (hf : ∀ i, ae_measurable (f i) μ)
(hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) :
∀ᵐ (a : α) ∂μ, ∀ (i : ι), ae_seq hf p i a = (hf i).mk (f i) a :=
begin
have h_ss : ae_seq_set hf p ⊆ {a : α | ∀ i, ae_seq hf p i a = (hf i).mk (f i) a},
from λ x hx i, by simp only [ae_seq, hx, if_true],
exact le_antisymm (le_trans (measure_mono (set.compl_subset_compl.mpr h_ss))
(le_of_eq (measure_compl_ae_seq_set_eq_zero hf hp))) (zero_le _),
end
lemma ae_seq_eq_fun_ae [countable ι] (hf : ∀ i, ae_measurable (f i) μ)
(hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) :
∀ᵐ (a : α) ∂μ, ∀ (i : ι), ae_seq hf p i a = f i a :=
begin
have h_ss : {a : α | ¬∀ (i : ι), ae_seq hf p i a = f i a} ⊆ (ae_seq_set hf p)ᶜ,
from λ x, mt (λ hx i, (ae_seq_eq_fun_of_mem_ae_seq_set hf hx i)),
exact measure_mono_null h_ss (measure_compl_ae_seq_set_eq_zero hf hp),
end
lemma ae_seq_n_eq_fun_n_ae [countable ι] (hf : ∀ i, ae_measurable (f i) μ)
(hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) (n : ι) :
ae_seq hf p n =ᵐ[μ] f n:=
ae_all_iff.mp (ae_seq_eq_fun_ae hf hp) n
lemma supr [complete_lattice β] [countable ι]
(hf : ∀ i, ae_measurable (f i) μ) (hp : ∀ᵐ x ∂μ, p x (λ n, f n x)) :
(⨆ n, ae_seq hf p n) =ᵐ[μ] ⨆ n, f n :=
begin
simp_rw [filter.eventually_eq, ae_iff, supr_apply],
have h_ss : ae_seq_set hf p ⊆ {a : α | (⨆ (i : ι), ae_seq hf p i a) = ⨆ (i : ι), f i a},
{ intros x hx,
congr,
exact funext (λ i, ae_seq_eq_fun_of_mem_ae_seq_set hf hx i), },
exact measure_mono_null (set.compl_subset_compl.mpr h_ss)
(measure_compl_ae_seq_set_eq_zero hf hp),
end
end ae_seq
|
c15f13cac4fccbb9fa90cd4b5e6fbdbe4a3d2dca
|
df561f413cfe0a88b1056655515399c546ff32a5
|
/8-inequality-world/l3.lean
|
a67eef6965de26cd7faa1f9999df5fd989bf3012
|
[] |
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
| 156
|
lean
|
theorem le_succ (a b : mynat) : a ≤ b → a ≤ (succ b) :=
begin
intro h,
cases h with c hc,
use c + 1,
rw add_one_eq_succ,
rw add_succ,
rw hc,
refl,
end
|
6fdda07d5238c63aef27ecf6342c54a7743b11eb
|
1b8f093752ba748c5ca0083afef2959aaa7dace5
|
/src/category_theory/follow_your_nose.lean
|
44169f1044a9ddadfd706337bd29c29680919a18
|
[] |
no_license
|
khoek/lean-category-theory
|
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
|
63dcb598e9270a3e8b56d1769eb4f825a177cd95
|
refs/heads/master
| 1,585,251,725,759
| 1,539,344,445,000
| 1,539,344,445,000
| 145,281,070
| 0
| 0
| null | 1,534,662,376,000
| 1,534,662,376,000
| null |
UTF-8
|
Lean
| false
| false
| 1,179
|
lean
|
import category_theory.natural_transformation
import category_theory.opposites
import category_theory.types
import category_theory.tactics.obviously
universes u₁ v₁
open tactic
def fyn_names :=
[ `category_theory.category.id,
`category_theory.functor.map,
`category_theory.nat_trans.app,
`category_theory.category.comp,
`prod.mk ]
meta def construct_morphism : tactic unit :=
do ctx ← local_context,
extra ← fyn_names.mmap (λ n, mk_const n),
solve_by_elim { restr_hyp_set := some (ctx ++ extra) }
meta def fyn := tidy { tactics := tactic.tidy.default_tactics ++ [construct_morphism >> pure "construct_morphism"] }
local attribute [tidy] construct_morphism
notation `ƛ` binders `, ` r:(scoped f, { category_theory.functor . obj := f }) := r
open category_theory
-- These examples require adding `. obviously` to functor.hom and nat_trans.app
-- variables (C : Type u₁) [𝒞 : category.{u₁ v₁} C]
-- include 𝒞
-- def yoneda : C ⥤ ((Cᵒᵖ) ⥤ (Type v₁)) := ƛ X, ƛ Y : C, Y ⟶ X.
-- variables (D : Type u₁) [𝒟 : category.{u₁ v₁} D]
-- include 𝒟
-- def curry_id : C ⥤ (D ⥤ (C × D)) := ƛ X, ƛ Y, (X, Y)
|
4295cda02a7aa09ba33ec5ea1655f043c7e833e0
|
367134ba5a65885e863bdc4507601606690974c1
|
/src/data/equiv/encodable/basic.lean
|
874cee4c4b32c51feb1c336ee5646ce46546b35b
|
[
"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
| 14,920
|
lean
|
/-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Mario Carneiro
Type class for encodable Types.
Note that every encodable Type is countable.
-/
import data.equiv.nat
import order.rel_iso
import order.directed
open option list nat function
/-- An encodable type is a "constructively countable" type. This is where
we have an explicit injection `encode : α → nat` and a partial inverse
`decode : nat → option α`. This makes the range of `encode` decidable,
although it is not decidable if `α` is finite or not. -/
class encodable (α : Type*) :=
(encode : α → nat)
(decode [] : nat → option α)
(encodek : ∀ a, decode (encode a) = some a)
attribute [simp] encodable.encodek
namespace encodable
variables {α : Type*} {β : Type*}
universe u
open encodable
theorem encode_injective [encodable α] : function.injective (@encode α _)
| x y e := option.some.inj $ by rw [← encodek, e, encodek]
lemma surjective_decode_iget (α : Type*) [encodable α] [inhabited α] :
surjective (λ n, (encodable.decode α n).iget) :=
λ x, ⟨encodable.encode x, by simp_rw [encodable.encodek]⟩
/- This is not set as an instance because this is usually not the best way
to infer decidability. -/
def decidable_eq_of_encodable (α) [encodable α] : decidable_eq α
| a b := decidable_of_iff _ encode_injective.eq_iff
def of_left_injection [encodable α]
(f : β → α) (finv : α → option β) (linv : ∀ b, finv (f b) = some b) : encodable β :=
⟨λ b, encode (f b),
λ n, (decode α n).bind finv,
λ b, by simp [encodable.encodek, linv]⟩
def of_left_inverse [encodable α]
(f : β → α) (finv : α → β) (linv : ∀ b, finv (f b) = b) : encodable β :=
of_left_injection f (some ∘ finv) (λ b, congr_arg some (linv b))
/-- If `α` is encodable and `β ≃ α`, then so is `β` -/
def of_equiv (α) [encodable α] (e : β ≃ α) : encodable β :=
of_left_inverse e e.symm e.left_inv
@[simp] theorem encode_of_equiv {α β} [encodable α] (e : β ≃ α) (b : β) :
@encode _ (of_equiv _ e) b = encode (e b) := rfl
@[simp] theorem decode_of_equiv {α β} [encodable α] (e : β ≃ α) (n : ℕ) :
@decode _ (of_equiv _ e) n = (decode α n).map e.symm := rfl
instance nat : encodable nat :=
⟨id, some, λ a, rfl⟩
@[simp] theorem encode_nat (n : ℕ) : encode n = n := rfl
@[simp] theorem decode_nat (n : ℕ) : decode ℕ n = some n := rfl
instance empty : encodable empty :=
⟨λ a, a.rec _, λ n, none, λ a, a.rec _⟩
instance unit : encodable punit :=
⟨λ_, zero, λn, nat.cases_on n (some punit.star) (λ _, none), λ⟨⟩, by simp⟩
@[simp] theorem encode_star : encode punit.star = 0 := rfl
@[simp] theorem decode_unit_zero : decode punit 0 = some punit.star := rfl
@[simp] theorem decode_unit_succ (n) : decode punit (succ n) = none := rfl
instance option {α : Type*} [h : encodable α] : encodable (option α) :=
⟨λ o, option.cases_on o nat.zero (λ a, succ (encode a)),
λ n, nat.cases_on n (some none) (λ m, (decode α m).map some),
λ o, by cases o; dsimp; simp [encodek, nat.succ_ne_zero]⟩
@[simp] theorem encode_none [encodable α] : encode (@none α) = 0 := rfl
@[simp] theorem encode_some [encodable α] (a : α) :
encode (some a) = succ (encode a) := rfl
@[simp] theorem decode_option_zero [encodable α] : decode (option α) 0 = some none := rfl
@[simp] theorem decode_option_succ [encodable α] (n) :
decode (option α) (succ n) = (decode α n).map some := rfl
def decode2 (α) [encodable α] (n : ℕ) : option α :=
(decode α n).bind (option.guard (λ a, encode a = n))
theorem mem_decode2' [encodable α] {n : ℕ} {a : α} :
a ∈ decode2 α n ↔ a ∈ decode α n ∧ encode a = n :=
by simp [decode2]; exact
⟨λ ⟨_, h₁, rfl, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨_, h₁, rfl, h₂⟩⟩
theorem mem_decode2 [encodable α] {n : ℕ} {a : α} :
a ∈ decode2 α n ↔ encode a = n :=
mem_decode2'.trans (and_iff_right_of_imp $ λ e, e ▸ encodek _)
theorem decode2_is_partial_inv [encodable α] : is_partial_inv encode (decode2 α) :=
λ a n, mem_decode2
theorem decode2_inj [encodable α] {n : ℕ} {a₁ a₂ : α}
(h₁ : a₁ ∈ decode2 α n) (h₂ : a₂ ∈ decode2 α n) : a₁ = a₂ :=
encode_injective $ (mem_decode2.1 h₁).trans (mem_decode2.1 h₂).symm
theorem encodek2 [encodable α] (a : α) : decode2 α (encode a) = some a :=
mem_decode2.2 rfl
def decidable_range_encode (α : Type*) [encodable α] : decidable_pred (set.range (@encode α _)) :=
λ x, decidable_of_iff (option.is_some (decode2 α x))
⟨λ h, ⟨option.get h, by rw [← decode2_is_partial_inv (option.get h), option.some_get]⟩,
λ ⟨n, hn⟩, by rw [← hn, encodek2]; exact rfl⟩
def equiv_range_encode (α : Type*) [encodable α] : α ≃ set.range (@encode α _) :=
{ to_fun := λ a : α, ⟨encode a, set.mem_range_self _⟩,
inv_fun := λ n, option.get (show is_some (decode2 α n.1),
by cases n.2 with x hx; rw [← hx, encodek2]; exact rfl),
left_inv := λ a, by dsimp;
rw [← option.some_inj, option.some_get, encodek2],
right_inv := λ ⟨n, x, hx⟩, begin
apply subtype.eq,
dsimp,
conv {to_rhs, rw ← hx},
rw [encode_injective.eq_iff, ← option.some_inj, option.some_get, ← hx, encodek2],
end }
section sum
variables [encodable α] [encodable β]
def encode_sum : α ⊕ β → nat
| (sum.inl a) := bit0 $ encode a
| (sum.inr b) := bit1 $ encode b
def decode_sum (n : nat) : option (α ⊕ β) :=
match bodd_div2 n with
| (ff, m) := (decode α m).map sum.inl
| (tt, m) := (decode β m).map sum.inr
end
instance sum : encodable (α ⊕ β) :=
⟨encode_sum, decode_sum, λ s,
by cases s; simp [encode_sum, decode_sum, encodek]; refl⟩
@[simp] theorem encode_inl (a : α) :
@encode (α ⊕ β) _ (sum.inl a) = bit0 (encode a) := rfl
@[simp] theorem encode_inr (b : β) :
@encode (α ⊕ β) _ (sum.inr b) = bit1 (encode b) := rfl
@[simp] theorem decode_sum_val (n : ℕ) :
decode (α ⊕ β) n = decode_sum n := rfl
end sum
instance bool : encodable bool :=
of_equiv (unit ⊕ unit) equiv.bool_equiv_punit_sum_punit
@[simp] theorem encode_tt : encode tt = 1 := rfl
@[simp] theorem encode_ff : encode ff = 0 := rfl
@[simp] theorem decode_zero : decode bool 0 = some ff := rfl
@[simp] theorem decode_one : decode bool 1 = some tt := rfl
theorem decode_ge_two (n) (h : 2 ≤ n) : decode bool n = none :=
begin
suffices : decode_sum n = none,
{ change (decode_sum n).map _ = none, rw this, refl },
have : 1 ≤ div2 n,
{ rw [div2_val, nat.le_div_iff_mul_le],
exacts [h, dec_trivial] },
cases exists_eq_succ_of_ne_zero (ne_of_gt this) with m e,
simp [decode_sum]; cases bodd n; simp [decode_sum]; rw e; refl
end
section sigma
variables {γ : α → Type*} [encodable α] [∀ a, encodable (γ a)]
def encode_sigma : sigma γ → ℕ
| ⟨a, b⟩ := mkpair (encode a) (encode b)
def decode_sigma (n : ℕ) : option (sigma γ) :=
let (n₁, n₂) := unpair n in
(decode α n₁).bind $ λ a, (decode (γ a) n₂).map $ sigma.mk a
instance sigma : encodable (sigma γ) :=
⟨encode_sigma, decode_sigma, λ ⟨a, b⟩,
by simp [encode_sigma, decode_sigma, unpair_mkpair, encodek]⟩
@[simp] theorem decode_sigma_val (n : ℕ) : decode (sigma γ) n =
(decode α n.unpair.1).bind (λ a, (decode (γ a) n.unpair.2).map $ sigma.mk a) :=
show decode_sigma._match_1 _ = _, by cases n.unpair; refl
@[simp] theorem encode_sigma_val (a b) : @encode (sigma γ) _ ⟨a, b⟩ =
mkpair (encode a) (encode b) := rfl
end sigma
section prod
variables [encodable α] [encodable β]
instance prod : encodable (α × β) :=
of_equiv _ (equiv.sigma_equiv_prod α β).symm
@[simp] theorem decode_prod_val (n : ℕ) : decode (α × β) n =
(decode α n.unpair.1).bind (λ a, (decode β n.unpair.2).map $ prod.mk a) :=
show (decode (sigma (λ _, β)) n).map (equiv.sigma_equiv_prod α β) = _,
by simp; cases decode α n.unpair.1; simp;
cases decode β n.unpair.2; refl
@[simp] theorem encode_prod_val (a b) : @encode (α × β) _ (a, b) =
mkpair (encode a) (encode b) := rfl
end prod
section subtype
open subtype decidable
variable {P : α → Prop}
variable [encA : encodable α]
variable [decP : decidable_pred P]
include encA
def encode_subtype : {a : α // P a} → nat
| ⟨v, h⟩ := encode v
include decP
def decode_subtype (v : nat) : option {a : α // P a} :=
(decode α v).bind $ λ a,
if h : P a then some ⟨a, h⟩ else none
instance subtype : encodable {a : α // P a} :=
⟨encode_subtype, decode_subtype,
λ ⟨v, h⟩, by simp [encode_subtype, decode_subtype, encodek, h]⟩
lemma subtype.encode_eq (a : subtype P) : encode a = encode a.val :=
by cases a; refl
end subtype
instance fin (n) : encodable (fin n) :=
of_equiv _ (equiv.fin_equiv_subtype _)
instance int : encodable ℤ :=
of_equiv _ equiv.int_equiv_nat
instance ulift [encodable α] : encodable (ulift α) :=
of_equiv _ equiv.ulift
instance plift [encodable α] : encodable (plift α) :=
of_equiv _ equiv.plift
noncomputable def of_inj [encodable β] (f : α → β) (hf : injective f) : encodable α :=
of_left_injection f (partial_inv f) (λ x, (partial_inv_of_injective hf _ _).2 rfl)
end encodable
section ulower
local attribute [instance, priority 100] encodable.decidable_range_encode
/--
`ulower α : Type 0` is an equivalent type in the lowest universe, given `encodable α`.
-/
@[derive decidable_eq, derive encodable]
def ulower (α : Type*) [encodable α] : Type :=
set.range (encodable.encode : α → ℕ)
end ulower
namespace ulower
variables (α : Type*) [encodable α]
/--
The equivalence between the encodable type `α` and `ulower α : Type 0`.
-/
def equiv : α ≃ ulower α :=
encodable.equiv_range_encode α
variables {α}
/--
Lowers an `a : α` into `ulower α`.
-/
def down (a : α) : ulower α := equiv α a
instance [inhabited α] : inhabited (ulower α) := ⟨down (default _)⟩
/--
Lifts an `a : ulower α` into `α`.
-/
def up (a : ulower α) : α := (equiv α).symm a
@[simp] lemma down_up {a : ulower α} : down a.up = a := equiv.right_inv _ _
@[simp] lemma up_down {a : α} : (down a).up = a := equiv.left_inv _ _
@[simp] lemma up_eq_up {a b : ulower α} : a.up = b.up ↔ a = b :=
equiv.apply_eq_iff_eq _
@[simp] lemma down_eq_down {a b : α} : down a = down b ↔ a = b :=
equiv.apply_eq_iff_eq _
@[ext] protected lemma ext {a b : ulower α} : a.up = b.up → a = b :=
up_eq_up.1
end ulower
/-
Choice function for encodable types and decidable predicates.
We provide the following API
choose {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] : (∃ x, p x) → α :=
choose_spec {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] (ex : ∃ x, p x) :
p (choose ex) :=
-/
namespace encodable
section find_a
variables {α : Type*} (p : α → Prop) [encodable α] [decidable_pred p]
private def good : option α → Prop
| (some a) := p a
| none := false
private def decidable_good : decidable_pred (good p)
| n := by cases n; unfold good; apply_instance
local attribute [instance] decidable_good
open encodable
variable {p}
def choose_x (h : ∃ x, p x) : {a:α // p a} :=
have ∃ n, good p (decode α n), from
let ⟨w, pw⟩ := h in ⟨encode w, by simp [good, encodek, pw]⟩,
match _, nat.find_spec this : ∀ o, good p o → {a // p a} with
| some a, h := ⟨a, h⟩
end
def choose (h : ∃ x, p x) : α := (choose_x h).1
lemma choose_spec (h : ∃ x, p x) : p (choose h) := (choose_x h).2
end find_a
theorem axiom_of_choice {α : Type*} {β : α → Type*} {R : Π x, β x → Prop}
[Π a, encodable (β a)] [∀ x y, decidable (R x y)]
(H : ∀x, ∃y, R x y) : ∃f:Πa, β a, ∀x, R x (f x) :=
⟨λ x, choose (H x), λ x, choose_spec (H x)⟩
theorem skolem {α : Type*} {β : α → Type*} {P : Π x, β x → Prop}
[c : Π a, encodable (β a)] [d : ∀ x y, decidable (P x y)] :
(∀x, ∃y, P x y) ↔ ∃f : Π a, β a, (∀x, P x (f x)) :=
⟨axiom_of_choice, λ ⟨f, H⟩ x, ⟨_, H x⟩⟩
/-
There is a total ordering on the elements of an encodable type, induced by the map to ℕ.
-/
/-- The `encode` function, viewed as an embedding. -/
def encode' (α) [encodable α] : α ↪ nat :=
⟨encodable.encode, encodable.encode_injective⟩
instance {α} [encodable α] : is_trans _ (encode' α ⁻¹'o (≤)) :=
(rel_embedding.preimage _ _).is_trans
instance {α} [encodable α] : is_antisymm _ (encodable.encode' α ⁻¹'o (≤)) :=
(rel_embedding.preimage _ _).is_antisymm
instance {α} [encodable α] : is_total _ (encodable.encode' α ⁻¹'o (≤)) :=
(rel_embedding.preimage _ _).is_total
end encodable
namespace directed
open encodable
variables {α : Type*} {β : Type*} [encodable α] [inhabited α]
/-- Given a `directed r` function `f : α → β` defined on an encodable inhabited type,
construct a noncomputable sequence such that `r (f (x n)) (f (x (n + 1)))`
and `r (f a) (f (x (encode a + 1))`. -/
protected noncomputable def sequence {r : β → β → Prop} (f : α → β) (hf : directed r f) : ℕ → α
| 0 := default α
| (n + 1) :=
let p := sequence n in
match decode α n with
| none := classical.some (hf p p)
| (some a) := classical.some (hf p a)
end
lemma sequence_mono_nat {r : β → β → Prop} {f : α → β} (hf : directed r f) (n : ℕ) :
r (f (hf.sequence f n)) (f (hf.sequence f (n+1))) :=
begin
dsimp [directed.sequence],
generalize eq : hf.sequence f n = p,
cases h : decode α n with a,
{ exact (classical.some_spec (hf p p)).1 },
{ exact (classical.some_spec (hf p a)).1 }
end
lemma rel_sequence {r : β → β → Prop} {f : α → β} (hf : directed r f) (a : α) :
r (f a) (f (hf.sequence f (encode a + 1))) :=
begin
simp only [directed.sequence, encodek],
exact (classical.some_spec (hf _ a)).2
end
variables [preorder β] {f : α → β} (hf : directed (≤) f)
lemma sequence_mono : monotone (f ∘ (hf.sequence f)) :=
monotone_of_monotone_nat $ hf.sequence_mono_nat
lemma le_sequence (a : α) : f a ≤ f (hf.sequence f (encode a + 1)) :=
hf.rel_sequence a
end directed
section quotient
open encodable quotient
variables {α : Type*} {s : setoid α} [@decidable_rel α (≈)] [encodable α]
/-- Representative of an equivalence class. This is a computable version of `quot.out` for a setoid
on an encodable type. -/
def quotient.rep (q : quotient s) : α :=
choose (exists_rep q)
theorem quotient.rep_spec (q : quotient s) : ⟦q.rep⟧ = q :=
choose_spec (exists_rep q)
/-- The quotient of an encodable space by a decidable equivalence relation is encodable. -/
def encodable_quotient : encodable (quotient s) :=
⟨λ q, encode q.rep,
λ n, quotient.mk <$> decode α n,
by rintros ⟨l⟩; rw encodek; exact congr_arg some ⟦l⟧.rep_spec⟩
end quotient
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.